How to Test Whether CORS Is Properly Enabled on a Website

With Cross-Origin Resource Sharing (hereafter CORS) settings, JavaScript can get past the browser’s same-origin policy and access resources (APIs) on other domains. But every time I set up CORS, I have a headache working out whether the server was really configured successfully. Sometimes the browser caches CORS results, so even when the server is configured correctly, the request keeps failing no matter how many times you refresh the page. Here I will show you how to use cURL to inspect the headers directly and check whether CORS is enabled! ...

January 4, 2017 · 1 min

JavaScript Page Load, Focus, UnFocus, and Exit Events

Most people know how to use JavaScript to record when a user enters a web page, but have you ever thought about how to tell when a user has “closed” it? Browsers today show multiple web pages as tabs, so it’s possible the user is actually looking at someone else’s page while yours just sits there. For example, YouTube often runs into this: a user leaves the page open to listen to music, but in fact they’re looking at Facebook… Today I’ll briefly note the JS page load and close events, as well as the focus (entering the page) and unfocus (leaving the page) events. With these events, you can record user behavior for analysis, and even do things like stop playing music when the user leaves the page. ...

January 3, 2017 · 3 min

Python Global Exception Handler

Normally, exception handling should not be global, because when you apply exception handling globally, it becomes hard to pinpoint where the problem occurred and handle it. But in rare cases, you do need to write code like this. For example, this time I wrote a Python program to process webhooks. The information the server sends is very varied, so whenever an exception occurs, I needed to print out the environment data so I could debug it afterward. This is exactly when you should use the Global Exception Hook technique. ...

January 2, 2017 · 1 min

String Split in Elasticsearch Script Field (Painless)

If you found this article, you have probably been searching for how to use Split in an Elasticsearch (or Kibana) Script Field for a long time! I deliberately included every keyword I could think of, so that engineers who suffer like I did do not waste too much of their lives on this… To cut to the chase: although Painless claims to support the Java Native API, a few things are not supported, and one of them is split. The story goes that the Elasticsearch developers felt the time complexity of split was too poor, so they cut it out. I did not know this at first, and I tried all kinds of approaches, from doubting whether my syntax was correct to wondering whether some special syntax was needed to import the Java API. Finally, on an Elasticsearch Issue, I found this post: [Painless - Request for native String split function], and my feelings at that moment were…… ...

December 14, 2016 · 2 min

Python Join with Lambda - A More Customizable Join

If you write code, you’re surely familiar with split() and join(). In Python, you can use String.join(list) to merge a List into a string. For example, “,".join([“A”, “B”, “C”]) returns the string “A,B,C”. Going the other way, “A,B,C”.split(”,") splits it into a List. But have you ever run into needs like these that you couldn’t solve? Joining strings while capitalizing the first letter of each one The List holds numbers, but join needs strings to work with them These problems can be solved with List Comprehension. For example, the type conversion part can be written like this: nums = [1,2,3,4,5] nums_str = [str(num) for num in nums] print(",".join(nums_str)) But are there other solutions besides List Comprehension? I bet you've also thought about passing a lambda function to join, the way you can with sort!...

December 13, 2016 · 2 min

Laravel Artisan Migrate "Table Already Exists" or "Foreign Key" Error

While deploying a project I had developed half a year earlier with Laravel 5.2, I ran into quite a few problems. One of them: after running php artisan migrate, I got a “Table Already Exists” error. But I had never created that table before. Digging deeper, I found that the table did exist, but there was no record for it in the project_migrations table. So I deleted the table manually and ran php artisan migrate once more. Sure enough, this time the real error message appeared: “General error: 1005 Can’t create table ‘dbname.#sql-fbc1_15e6’ (errno: 121) (SQL: alter table karl_project add constraint project_user_id_foreign foreign key (user_id) references karl_user (id))” ...

December 12, 2016 · 2 min

Copying Text to the Clipboard with JavaScript

In the past, using JavaScript to copy and paste text through the clipboard was very cumbersome. While developing NTUST.ME, a short URL service for National Taiwan University of Science and Technology, I wanted to make it easy for people to copy the shortened URLs, so I looked into the clipboard API in JavaScript. I found that newer browsers have an execCommand function that supports many handy text operations, such as copy and select all. Let me introduce it to you! ...

December 10, 2016 · 2 min

Chinese Pinyin Conversion in Python (Translating Names and Addresses)

Today I helped a coworker with a large batch of name and address translation requests from Chinese to English, so I looked into how Python handles Hanyu Pinyin. After all, you can’t copy everything one by one into a post office form or a website, right? (lol). The result was surprisingly simple. Address translation can be handled through the Geocoder APIs of various providers, and for pinyin there are third-party libraries you can use. The translation quality is pretty good. It’s not perfect, but combined with some “manual intelligence” (工人智慧, a pun on 人工智慧, “artificial intelligence”), the small flaws are good enough. To fix the last small flaws, you would probably need to invest a lot of resources and technology and introduce machine learning methods. (I’m actually interested in trying that out someday, since there are really too few useful tools in the Chinese-speaking world.) ...

December 9, 2016 · 4 min

How to Make elasticsearch.py Fast (Bulk Operations)

When you work with Elasticsearch in Python, you will inevitably install the official elasticsearch.py library. Recently, while using Python to receive email logs and write them into Elasticsearch, I picked up quite a few lessons worth sharing. As everyone knows, AWS Lambda charges by execution time, so when writing Lambda functions every second counts. Anything that ran over 0.5 seconds had me in agony. So I went from inserting records one at a time with .index, to using streaming_bulk, and finally, unable to stand it anymore, mixing parallel_bulk with streaming_bulk. Here I will talk about the differences between these approaches and the pitfalls I ran into! ...

December 8, 2016 · 4 min

Converting a String to a Boolean in Python

Today, while writing an AWS Lambda function, I needed to read a setting from an environment variable and convert it from a string to a boolean so I could use it in a condition. The obvious guesses are that Python will convert it automatically, or that bool("True") will do the job. But first of all, Python does not do automatic type conversion. This is important! It simply raises an error without any fuss. But surely you’d expect bool() to solve it, right?! In fact, this landmine cost me half an hour today… ...

December 8, 2016 · 1 min