Operation type [start] failed with message “The zone ‘projects/???/zones/us-west2-b’ does not have enough resources available to fulfill the request. Try a different zone, or try again later.”

I waited for two weeks and tried to start it from time to time, while I always saw that cold message. oooookay, I gave up and switched to a different zone.

Luckily, I am not the only one who facing this issue. I followed the suggestions in this stackoverflow post and it was easy to migrate.

]]>The challenging is “Assume that the BST is balanced, could you solve it in less than O(n) runtime (where n = total nodes)?” Reasonably, the answer is yes. We can do it better than O(n), as O(logN + k). However, it took me quite a few days to find out the right solution.

When I got stuck with this problem, I tried to Google the other blogs. Unfortunately, among the pages I visited, some so-called O(logN + K) solutions are essentially O(N + k). For example, some solution prepare all the predecessors and successors in functions like getPredecessor(TreeNode root, double target, Stack precedessor), where the function fills the stack with all qualified nodes. Since nearly all nodes will be either predecessor or successor, these functions are O(N).

In fact, the key is how to get the predecessor and successor without visiting the whole tree. And the answer is a variable of iteration-based in-order traversal.

from math import isclose """ Definition of TreeNode: class TreeNode: def __init__(self, val): self.val = val self.left, self.right = None, None """ def Previous(input_stack): # Reverse in-order travesal the binary tree and yield the previous node # (with smaller value) stack = input_stack * 1 # Deep copy current = None while stack or current: while current: stack.append(current) current = current.right current = stack.pop() yield current.val current = current.left def Next(input_stack): # In-order traversal the binary tree and yield the next node (with larger # value). stack = input_stack * 1 # Deep copy current = None while stack or current: while current: stack.append(current) current = current.left current = stack.pop() yield current.val current = current.right class Solution: """ @param root: the given BST @param target: the given target @param k: the given k @return: k values in the BST that are closest to the target """ def closestKValues(self, root, target, k): TreeNode.__repr__ = lambda x: str(x.val) # For debug purpose # Find the node with the closest value # If BST is balanced, the time is O(logN) stack = [] current = root min_diff = float("inf") min_diff_node = None while current: stack.append(current) if abs(current.val - target) < min_diff: min_diff = abs(current.val - target) min_diff_node = current if isclose(current.val, target): # Find the target break elif current.val > target: current = current.left else: current = current.right # Move back the node with the closest value. while stack[-1] != min_diff_node: stack.pop() # For the stack of in-order traversal, it should be decreasing. next_stack = [] for node in stack: if next_stack and node.val >= next_stack[-1].val: next_stack.pop() next_stack.append(node) # For the stack of reverse in-order traversal, it should be increasing. prev_stack = [] for node in stack: if prev_stack and node.val < prev_stack[-1].val: prev_stack.pop() prev_stack.append(node) next_generator = Next(next_stack) # The closest item should exist in just one side, not both next(next_generator) pre_generator = Previous(prev_stack) next_item = next(next_generator, None) pre_item = next(pre_generator, None) result = [] # Since it's guaranteed to have one result, it's not a must to have # (next_item != None or pre_item != None) # The time is O(k). The key point is the generator. We do NOT need to # traversal the whole trees. while len(result) < k and (next_item != None or pre_item != None): # Must use `next_item == None` instead of `next_item`, because it # might be 0. if next_item == None: result.append(pre_item) pre_item = next(pre_generator, None) elif pre_item == None: result.append(next_item) next_item = next(next_generator, None) elif abs(next_item - target) < abs(pre_item - target): result.append(next_item) next_item = next(next_generator, None) else: result.append(pre_item) pre_item = next(pre_generator, None) return result]]>

I extracted a list of my target products from the homepage, and on each product page tried to add it to my cart. Basically I need to:

- Check each product page if it’s marked as available on home page;
- The interval between two attempt for the same product page is at least 1 hour. That is, in the hour following the first check, we do nothing. After one hour, if it’s still marked as available, try it again. Otherwise, do nothing.
- The number of unique product pages is small, like less than 100.

To achieve that, I made a simple expiring set in Python. It does not consider garbage collection, because

- The same items are added from time to time;
- The number of unique items is small.

```
from time import time
class ExpiringSet():
def __init__(self, max_age_seconds):
assert max_age_seconds > 0
self.age = max_age_seconds
self.container = {}
def contains(self, value):
if value not in self.container:
return False
if time() - self.container[value] > self.age:
del self.container[value]
return False
return True
def add(self, value):
self.container[value] = time()
```

Aside from using vulnerabilities in WordPress, a less-skilled but much more common attack is brute force attack. The invader (I don’t want to call them hackers. They don’t deserve the name.) would try to login your WordPress with the guessing usernames and passwords, over and over again. These usernames and passwords may be common ones, such as “admin” with “123456789”. Or they may be aggregated from the leaked data breach.

In the marketplace, we have many different types of solutions to secure your WordPress login. This article discuses some easy and free ways to add more protections against brute force attacks. You could pick one or more of them depending on your situation.

I know, it’s not going to make your login system safer. But first of all, we all have to admit that, there is **NO** complete security. Regular backup is important in recovery. Save it for a rainy day.

Captcha is a system to determine whether or not the user is human. Without the Captcha protection, the invader would use the computer program to automatically try to login your WordPress tirelessly. With Captcha enabled on the login pages, it increases the bar to launch an automatic attack.

The most popular and free solution is reCAPTCHA from Google. And we have quite a few excellent WordPress plugins to integrate it. Personally I used Advanced noCaptcha & invisible Captcha and Invisible reCaptcha for WordPress.

Unfortunately, Google services including reCaptcha is unavailable or unstable in some countries and areas. If your site has a huge traffic from there, you need to consider some alternatives.

We might mis-type our password once or twice. How about three times or four or even more? Do you think it’s normal? Probably no. A sequence of failed login attempts seems very suspicious.

Limit Login Attempts Reloaded is a wonderful and essential WordPress plugin. It blocks the requests, if the Internet address sent too many failed login attempts. Before I installed this plugin, I did not even notice that the brute force attacks are so frequent.

Limit Login Attempts Reloaded would notify you if someone tried but failed to login your WordPress site. But what if they stole or got the username and password from somewhere else, and successfully logged into your site? I would like a notification at least!

Per a quick search in WordPress site, we do not have many (popular) plugins to choose. Additionally, my use case is very simple: singe site and singe user. So I made this functionality manually:

```
function notice_login($user_login, $user) {
$to = 'my email at codesays.com';
$subject = 'Login Alert';
$message = 'Someone logged in as ' . $user_login;
wp_mail( $to, $subject, $message );
}
add_action( 'wp_login', 'notice_login', 10, 2);
```

Two Factor Authentication (aka 2FA) would drastically increase the overall login security. Nowadays it’s widely used in our online services, such as Google account and bank account.

Personally I do not use it on this site. But per the search on WordPress, there are some highly-rated and popular plugins for this purpose. And *Google Authenticator – WordPress Two Factor Authentication (2FA)* declares that “for 1 User forever FREE”.

Lastly and the most importantly, use a **STRONG** password: be long and complex!

Question Name: Rectangle-Builder-Greater-Area or RectangleBuilderGreaterArea

This key is the binary search.

def solution(A, X): fence_count = {} for fence in A: fence_count[fence] = fence_count.get(fence, 0) + 1 num_of_pens = 0 usable_fences = [] for fence in fence_count: if fence_count[fence] < 2: # Less than one pair. We cannot use it. continue elif fence_count[fence] < 4: usable_fences.append(fence) else: usable_fences.append(fence) # We consider the square pen here. if fence * fence >= X: num_of_pens += 1 # We consider the non-square pen here. usable_fences.sort() candidate_size = len(usable_fences) for i in xrange(candidate_size): # Use binary search to find the first fence pair, that # could be used with current pair to form a pen. begin = i + 1 end = candidate_size - 1 while begin <= end: mid = (begin + end) // 2 if usable_fences[mid] * usable_fences[i] >= X: end = mid - 1 else: begin = mid + 1 # Now the usable_fences[end + 1] is the first qualified # fence. combination_num = candidate_size - (end + 1) num_of_pens += combination_num if num_of_pens > 1000000000: return -1 return num_of_pens]]>

Question Name: Dwarfs-Rafting or DwarfsRafting

Need some simple mathematical knowledge. The code is unnecessarily long. A 2-d array is better to write much shorter code. However, I keep the long version for better readability.

def solution(N, S, T): quadrant_left_front = (N // 2) * (N // 2) quadrant_left_back = (N // 2) * (N // 2) quadrant_right_front = (N // 2) * (N // 2) quadrant_right_back = (N // 2) * (N // 2) boundary = N // 2 # Compute how many slots are available in each quadrant. for barrel in S.split(): # Adjust to 0-based index. row = int(barrel[:-1]) - 1 column = ord(barrel[-1]) - ord("A") if row < boundary: # The barrel is in the front. if column < boundary: # The barrel is in the left. quadrant_left_front -= 1 else: # The barrel is in the right. quadrant_right_front -= 1 else: # The barrel is in the back. if column < boundary: # The barrel is in the left. quadrant_left_back -= 1 else: # The barrel is in the right. quadrant_right_back -= 1 # lf is short for left front, etc. # To keep balance, we need: # 1. weight_lf + weight_lb = weight_rf + weight_rb # 2. weight_lf + weight_rf = weight_rf + weight_rb # Solve the equations and we can get the answer: # 1. weight_lf = weight_rb # 2. And weight_rf = weight_lb allowance_lf = min(quadrant_left_front, quadrant_right_back) allowance_rb = min(quadrant_left_front, quadrant_right_back) allowance_lb = min(quadrant_left_back, quadrant_right_front) allowance_rf = min(quadrant_left_back, quadrant_right_front) # Minus the seats, which are already occupied by dwarfs. for dwarf in T.split(): # Adjust to 0-based index. row = int(dwarf[:-1]) - 1 column = ord(dwarf[-1]) - ord("A") if row < boundary: # The dwarf is in the front. if column < boundary: # The dwarf is in the left. allowance_lf -= 1 if allowance_lf < 0: return -1 else: # The dwarf is in the right. allowance_rf -= 1 if allowance_rf < 0: return -1 else: # The dwarf is in the back. if column < boundary: # The dwarf is in the left. allowance_lb -= 1 if allowance_lb < 0: return -1 else: # The dwarf is in the right. allowance_rb -= 1 if allowance_rb < 0: return -1 return allowance_lf + allowance_rb + allowance_lb + allowance_rf]]>

Question Name: Slalom-Skiing or SlalomSkiing

This is a wonderful variant of longest increasing subsequence. Because the longest increasing subsequence is a very classic question withe O(NlogN) solution, the key point to solve this question is to covert its original form to the classic question. We would like to extend it with two mirror universe.

+--------+--------+--------+ | | | | | | | | |Original| mirror | mirror | | | #1 | #2 | | Points | | | | | | | | | | | | | | | +--------+--------+--------+

The original question is convert into: find the longest increasing subsequence in the new extended multiverse. Here is an example of extended multiverse:

Original universe: +------+ |X | | X | | X | | X | | X | +------+ Extended multiverse: +------+------+------+ |X | X|X | | X | X | X | | X | X | X | | X | X | X | | X | X | X | +------+------+------+

For each point P, it has three instances: the instance in the original world as P0, one in the mirror world as P1, and the last in the double-mirror world as P2. We process P2 firstly, then P1, and finally P0, so that to avoid the self-link sequence. In other words, we do not want that P2 is connected from P0 or P1, because they are essentially the same point.

The relationship between the original qualified subsequence (change direction at most two times) and the new longest increasing subsequence is 1:N mapping. Actually every subsequence in the original question has multiple equivalent subsequence in the new multiverse. Oppositely, every subsequence in the new multiverse has one equivalent in the original world.

def LongestIncreasingSubsequence(seq): ''' The classic dynamic programming solution for longest increasing subsequence. More details could be found: https://en.wikipedia.org/wiki/Longest_increasing_subsequence http://www.geeksforgeeks.org/dynamic-programming-set-3-longest-increasing-subsequence/ http://stackoverflow.com/questions/3992697/longest-increasing-subsequence ''' # smallest_end_value[i] = j means, for all i-length increasing # subsequence, the minmum value of their last elements is j. smallest_end_value = [None] * (len(seq) + 1) # The first element (with index 0) is a filler and never used. smallest_end_value[0] = -1 # The length of the longest increasing subsequence. lic_length = 0 for i in range(len(seq)): # Binary search: we want the index j such that: # smallest_end_value[j-1] < seq[i] # AND # ( smallest_end_value[j] > seq[i] # OR # smallest_end_value[j] == None # ) # Here, the result "lower" is the index j. lower = 0 upper = lic_length while lower <= upper: mid = (upper + lower) // 2 if seq[i] < smallest_end_value[mid]: upper = mid - 1 elif seq[i] > smallest_end_value[mid]: lower = mid + 1 else: raise "Should never happen: " + \ "the elements of A are all distinct" if smallest_end_value[lower] == None: smallest_end_value[lower] = seq[i] lic_length += 1 else: smallest_end_value[lower] = \ min(smallest_end_value[lower], seq[i]) return lic_length def solution(A): # We are solving this question by creating two mirrors. bound = max(A) + 1 multiverse = [] for point in A: # The point in the double-mirror universe. multiverse.append(bound * 2 + point) # The point in the mirror universe. multiverse.append(bound * 2 - point) # The point in the original universe. multiverse.append(point) return LongestIncreasingSubsequence(multiverse)]]>

Question Name: Flood-Depth or FloodDepth

This is a variant of Trapping Rain Water by LeetCode. The undergoing concept is the same. However, the implementation is a bit different.

from collections import namedtuple def solution(A): if len(A) < 3: return 0 # The blocks in the stack is in strictly height descending order. # For the first block in the stack, its max_depth is maximum water # depth of its (exclusive) left area. # The other blocks' max_depth is the maximum water depth between its # previous block in the stack and itself, both exclusive. Block = namedtuple("Block", ["height", "max_depth"]) stack = [Block(A[0],0)] for height in A[1:]: if height == stack[-1].height: # These two adjacent blocks have the same height. They act # totally the same in building any water container. continue elif height < stack[-1].height: stack.append(Block(height, 0)) else: max_depth = 0 # Let the current iterating block be C, the previous two # blocks in the stack be A and B. And their positions are # demoed as: # C # A C # A ... B ... C # while the blocks between A and B are omitted. So do the # blocks between B and C. # # The additional_depth consider the blocks A, B, and C only, # and igonres all the omitted blocks, such as: # C # A C # A B C (no block is between A and B, or B and C) # # HOWEVER, the additional_depth is not always the maximum # water depth between A and C, because there may be some # water between A and B, or B and C, as exists in the omitted # blocks. We need to adjust the additional_depth to get the # maximum water depth between A and C, both exclusive. while len(stack) > 1 and height > stack[-1].height: additional_depth = min(stack[-2].height, height) - \ stack[-1].height max_depth = max(max_depth, stack[-1].max_depth) + \ additional_depth stack.pop() # Combine leftward same-or-less-height blocks. These dropped # blocks are never going to be part of the remaining water # container. while len(stack) > 0 and height >= stack[-1].height: max_depth = max(max_depth, stack[-1].max_depth) stack.pop() stack.append(Block(height, max_depth)) overall_max_depth = 0 for block in stack: if block.max_depth > overall_max_depth: overall_max_depth = block.max_depth return overall_max_depth]]>

Question Name: Longest-Password or LongestPassword

The solution could be more Pythonic with some additional space.

def solution(S): longest = -1 num_of_letters = 0 num_of_digits = 0 num_of_others = 0 for letter in S: if letter.isalpha(): num_of_letters += 1 elif letter.isdigit(): num_of_digits += 1 elif letter == " ": # Check whether it's a valid password. if num_of_others == 0 and \ num_of_letters % 2 == 0 and \ num_of_digits % 2 == 1: if longest < num_of_letters + num_of_digits: longest = num_of_letters + num_of_digits # Reset the counters for the next word. num_of_letters = 0 num_of_digits = 0 num_of_others = 0 else: num_of_others += 1 # Check whether the last word is a valid password. if num_of_others == 0 and \ num_of_letters % 2 == 0 and \ num_of_digits % 2 == 1: if longest < num_of_letters + num_of_digits: longest = num_of_letters + num_of_digits return longest]]>

Question Name: Sql-Sum or SqlSum

This question is too easy to be a serious training lesson. Most likely, it’s a live test for SQL challenges on Codility.com. The following solution works in both PostgreSQL and SQLite.

SELECT SUM(v) FROM elements]]>