text:
from pprint import pprint as print
#46 Simple Python Exercises
#Define a function max() that takes two numbers as arguments and returns the largest of them. Use the if-then-else construct available in Python. (It is true that Python has the max() function built in, but writing it yourself is nevertheless a good exercise.)
def max(a, b):
  if a > b:
    return a
  else:
    return b
print(max(1,2),max(2,1), max(3,8))
#Define a function max_of_three() that takes three numbers as arguments and returns the largest of them.
def max_of_three(a,b,c):
  return max(a,(max(b,c)))
print(max_of_three(1,2,3),max_of_three(8,7,6),max_of_three(8,10,3))
#
#Define a function that computes the length of a given list or string. (It is true that Python has the len() function built in, but writing it yourself is nevertheless a good exercise.)
def leng(x):
  l = 0
  for i in x:
    l += 1
  return l
print(leng("abladfalsfd;"),leng([2,3,"",7]))
#Write a function that takes a character (i.e. a string of length 1) and returns True if it is a vowel, False otherwise.
def vow(c):
  vowels = "aeiouy"
  return c in vowels
print(vow('a'),vow('b'))
#Write a function translate() that will translate a text into "rövarspråket" (Swedish for "robber's language"). That is, double every consonant and place an occurrence of "o" in between. For example, translate("this is fun") should return the string "tothohisos isos fofunon".
def translate(s):
  r = ""
  for x in s:
    if not vow(x) and not x == ' ':
      r += x + "o" + x
    else:
      r += x
  return r
print(translate("this is fun"))
#Define a function sum() and a function multiply() that sums and multiplies (respectively) all the numbers in a list of numbers. For example, sum([1, 2, 3, 4]) should return 10, and multiply([1, 2, 3, 4]) should return 24.
def sum(a):
  s = 0
  for x in a:
    s += x
  return s
def mul(a):
  m = 1
  for x in a:
    m *= x
  return m
print(sum([1,2,3,4]), mul([1,2,3,4]))
#Define a function reverse() that computes the reversal of a string. For example, reverse("I am testing") should return the string "gnitset ma I".
def reverse(s):
  r=""
  for x in range(leng(s)-1, -1, -1):
    r += s[x]
  return r
print(reverse("I am testing"))
#Define a function is_palindrome() that recognizes palindromes (i.e. words that look the same written backwards). For example, is_palindrome("radar") should return True.
def is_palindrome(s):
  for x in range(len(s) // 2):
    #print(x, s[x], s[len(s) -x - 1], len(s) - x - 1)
    if s[x] != s[len(s) - x - 1]:
      return False
  return True
print(is_palindrome("radar"), is_palindrome("zoxaxoz"))
#Write a function is_member() that takes a value (i.e. a number, string, etc) x and a list of values a, and returns True if x is a member of a, False otherwise. (Note that this is exactly what the in operator does, but for the sake of the exercise you should pretend Python did not have this operator.)
def is_member(l, v):
  for x in l:
    if x == v:
      return True
  return False
print(is_member(list("123456678"),"6"),is_member(list("123456678"),"1"),is_member(list("123456678"),'8'), is_member("lj;lj","a"),is_member([1,5,6],6))
#Define a function overlapping() that takes two lists and returns True if they have at least one member in common, False otherwise. You may use your is_member() function, or the in operator, but for the sake of the exercise, you should (also) write it using two nested for-loops.
def overlapping(x, y):
  for a in x:
    for b in y:
      if a == b:
        return True
  return False
print(overlapping("23456789","rtyuio"), overlapping("56789","2345"))
#Define a function generate_n_chars() that takes an integer n and a character c and returns a string, n characters long, consisting only of c:s. For example, generate_n_chars(5,"x") should return the string "xxxxx". (Python is unusual in that you can actually write an expression 5 * "x" that will evaluate to "xxxxx". For the sake of the exercise you should ignore that the problem can be solved in this manner.)
def generate_n_chars(n, c):
  s = ''
  x = 0
  while x < n:
    s += c
    x += 1
  return s
print(generate_n_chars(10,"a"),generate_n_chars(5,"5"))
#Define a procedure histogram() that takes a list of integers and prints a histogram to the screen. For example, histogram([4, 9, 7]) should print the following:
#****
#*********
#*******
def histogram(l):
  for x in l:
    print(generate_n_chars(x,"*"))
histogram([4,9,7,1,2,3,8,8,1,0,1,5,1,1])
#The function max() from exercise 1) and the function max_of_three() from exercise 2) will only work for two and three numbers, respectively. But suppose we have a much larger number of numbers, or suppose we cannot tell in advance how many they are? Write a function max_in_list() that takes a list of numbers and returns the largest one.
def max_in_list(l):
  m = l[0]
  for x in l:
    if x > m:
      m = x
  return m
print(max_in_list([-20,2,-30,8,10,8,1]))
#Write a program that maps a list of words into a list of integers representing the lengths of the correponding words.
def wordsLens1(l):
  r = []
  for x in l:
    r += [len(x)]
  return r
def wordsLens2(l):
  return [len(x) for x in l]
def wordsLens3(l):
  return list(map(len, l))
print(wordsLens1(["x","run","asdf",'']))
print(wordsLens2(["x","run","asdf",'']))
print(wordsLens3(["x","run","asdf",'']))
#Write a function find_longest_word() that takes a list of words and returns the length of the longest one.
def find_longest_word(l):
  return max_in_list(wordsLens3(l))
print(find_longest_word(["x","run","asdf",'']))
#Write a function filter_long_words() that takes a list of words and an integer n and returns the list of words that are longer than n.
def filter_long_words(l,n):
  r = []
  for x in l:
    if len(x) > n:
      r += [x]
  return r
print(filter_long_words(["x","run","asdf",'kkkkkk'],3))
#Write a version of a palindrome recognizer that also accepts phrase palindromes such as "Go hang a salami I'm a lasagna hog.", "Was it a rat I saw?", "Step on no pets", "Sit on a potato pan, Otis", "Lisa Bonet ate no basil", "Satan, oscillate my metallic sonatas", "I roamed under it as a tired nude Maori", "Rise to vote sir", or the exclamation "Dammit, I'm mad!". Note that punctuation, capitalization, and spacing are usually ignored.
def is_palindrome2(s):
  z = ''
  for x in s.lower():
    if x.isalpha():
      z += x
  #print(z)
  return is_palindrome(z)
print(is_palindrome2("Was it a rat I saw?"), is_palindrome2("Was it a rat I saz?"))
#A pangram is a sentence that contains all the letters of the English alphabet at least once, for example: The quick brown fox jumps over the lazy dog. Your task here is to write a function to check a sentence to see if it is a pangram or not.
def is_pangram(s):
  alphabet = set(map(chr, range(ord('a'), ord('z') + 1)))
  x = set(s)
  return (alphabet - x) == set()
print(is_pangram("The quick brown fox jumps over the lazy dogggg"))
print(is_pangram("The quick brown fox jumps over the lazy do"))
#"99 Bottles of Beer" is a traditional song in the United States and Canada:
#99 bottles of beer on the wall, 99 bottles of beer.
#Take one down, pass it around, 98 bottles of beer on the wall.
#The same verse is repeated, each time with one fewer bottle. The song is completed when the singer or singers reach zero.
#
#Your task here is write a Python program capable of generating all the verses of the song.
def a99bofb():
  for x in range(99,0,-1):
    print(str(x) + ' bottles of beer on the wall, ' + str(x) + ' bottles of beer.')
    print('Take one down, pass it around, ' + str(x-1) + ' bottles of beer on the wall.')
a99bofb()
#Represent a small bilingual lexicon as a Python dictionary in the following fashion {"merry":"god", "christmas":"jul", "and":"och", "happy":gott", "new":"nytt", "year":"år"} and use it to translate your Christmas cards from English into Swedish. That is, write a function translate() that takes a list of English words and returns a list of Swedish words.
def strToWordList(s):
  return s.split(' ')
def translate(l):
  a = {"merry":"god", "christmas":"jul", "and":"och", "happy":"gott", "new":"nytt", "year":"år"}
  return list(map(lambda x: a.get(x,x), strToWordList(l)))
print(translate("We wish you a merry christmas and xmas. happy new year!"))
#Write a function char_freq() that takes a string and builds a frequency listing of the characters contained in it. Represent the frequency listing as a Python dictionary. Try it with something like char_freq("abbabcbdbabdbdbabababcbcbab").
def char_freq(s):
  r = {}
  for x in s:
    if not x in r:
      r[x] = 1
    else:
      r[x] += 1
  return r
print(char_freq("abbabcbdbabdbdbabababcbcbab"))
#In cryptography, a Caesar cipher is a very simple encryption techniques in which each letter in the plain text is replaced by a letter some fixed number of positions down the alphabet. For example, with a shift of 3, A would be replaced by D, B would become E, and so on. The method is named after Julius Caesar, who used it to communicate with his generals. ROT-13 ("rotate by 13 places") is a widely used example of a Caesar cipher where the shift is 13. In Python, the key for ROT-13 may be represented by means of the following dictionary:
#
#key = {'a':'n', 'b':'o', 'c':'p', 'd':'q', 'e':'r', 'f':'s', 'g':'t', 'h':'u',
#       'i':'v', 'j':'w', 'k':'x', 'l':'y', 'm':'z', 'n':'a', 'o':'b', 'p':'c',
#       'q':'d', 'r':'e', 's':'f', 't':'g', 'u':'h', 'v':'i', 'w':'j', 'x':'k',
#       'y':'l', 'z':'m', 'A':'N', 'B':'O', 'C':'P', 'D':'Q', 'E':'R', 'F':'S',
#       'G':'T', 'H':'U', 'I':'V', 'J':'W', 'K':'X', 'L':'Y', 'M':'Z', 'N':'A',
#       'O':'B', 'P':'C', 'Q':'D', 'R':'E', 'S':'F', 'T':'G', 'U':'H', 'V':'I',
#       'W':'J', 'X':'K', 'Y':'L', 'Z':'M'}
#Your task in this exercise is to implement an encoder/decoder of ROT-13. Once you're done, you will be able to read the following secret message:
#   Pnrfne pvcure? V zhpu cersre Pnrfne fnynq!
#Note that since English has 26 characters, your ROT-13 program will be able to both encode and decode texts written in English.
key = {'a':'n', 'b':'o', 'c':'p', 'd':'q', 'e':'r', 'f':'s', 'g':'t', 'h':'u',
       'i':'v', 'j':'w', 'k':'x', 'l':'y', 'm':'z', 'n':'a', 'o':'b', 'p':'c',
       'q':'d', 'r':'e', 's':'f', 't':'g', 'u':'h', 'v':'i', 'w':'j', 'x':'k',
       'y':'l', 'z':'m', 'A':'N', 'B':'O', 'C':'P', 'D':'Q', 'E':'R', 'F':'S',
       'G':'T', 'H':'U', 'I':'V', 'J':'W', 'K':'X', 'L':'Y', 'M':'Z', 'N':'A',
       'O':'B', 'P':'C', 'Q':'D', 'R':'E', 'S':'F', 'T':'G', 'U':'H', 'V':'I',
       'W':'J', 'X':'K', 'Y':'L', 'Z':'M'}
def rot13decode(msg):
  m = ''
  for x in msg:
    if x in key:
      m += key[x]
    else:
      m += x
  return m
def rot13encode2(msg):
  return ''.join((list(map(lambda x: key[x], msg))))
print(rot13decode("Pnrfne pvcure? V zhpu cersre Pnrfne fnynq!"))
#Define a simple "spelling correction" function correct() that takes a string and sees to it that 1) two or more occurrences of the space character is compressed into one, and 2) inserts an extra space after a period if the period is directly followed by a letter. E.g. correct("This   is  very funny  and    cool.Indeed!") should return "This is very funny and cool. Indeed!" Tip: Use regular expressions!
def correct(s): #N:23
  import re
  nomorespace = re.sub('\s\s+',' ',s)
  return re.sub('\.(\w)','. \g<1>',nomorespace)
print(correct("This   is  very funny  and    cool.Indeed!"))
#The third person singular verb form in English is distinguished by the suffix -s, which is added to the stem of the infinitive form: run -> runs. A simple set of rules can be given as follows:
#If the verb ends in y, remove it and add ies
#If the verb ends in o, ch, s, sh, x or z, add es
#By default just add s
#Your task in this exercise is to define a function make_3sg_form() which given a verb in infinitive form returns its third person singular form. Test your function with words like try, brush, run and fix. Note however that the rules must be regarded as heuristic, in the sense that you must not expect them to work for all cases. Tip: Check out the string method endswith().
def make_3sg_form(s):
  import re
  if s.endswith('y'):
    return s[:-1] + 'ies'
  else:
    return re.sub('(o$|ch$|s$|sh$|x$|z$)','\g<1>e',s) + 's'
print(make_3sg_form('try'), make_3sg_form('brush'), make_3sg_form('run'), make_3sg_form('fix'))
#In English, the present participle is formed by adding the suffix -ing to the infinite form: go -> going. A simple set of heuristic rules can be given as follows:
#If the verb ends in e, drop the e and add ing (if not exception: be, see, flee, knee, etc.)
#If the verb ends in ie, change ie to y and add ing
#For words consisting of consonant-vowel-consonant, double the final letter before adding ing
#By default just add ing
#Your task in this exercise is to define a function make_ing_form() which given a verb in infinitive form returns its present participle form. Test your function with words such as lie, see, move and hug. However, you must not expect such simple rules to work for all cases.

#Higher order functions and list comprehensions

#Using the higher order function reduce(), write a function max_in_list() that takes a list of numbers and returns the largest one. Then ask yourself: why define and call a new function, when I can just as well call the reduce() function directly?
def max_in_list2(l):
  import functools
  return functools.reduce(max, l)
print(max_in_list2([1,2,3,4,66,5,43,4,4]))
#Write a program that maps a list of words into a list of integers representing the lengths of the correponding words. Write it in three different ways: 1) using a for-loop, 2) using the higher order function map(), and 3) using list comprehensions.

#Write a function find_longest_word() that takes a list of words and returns the length of the longest one. Use only higher order functions.
def find_longest_word2(l):
  import functools
  return functools.reduce(lambda x, y: max(x, len(y)),l,0)
print(find_longest_word2(["x","run","asdf",'']))
#Using the higher order function filter(), define a function filter_long_words() that takes a list of words and an integer n and returns the list of words that are longer than n.
def filter_long_words2(l, n):
  return list(filter(lambda x: x if len(x) > n else False, l))
print(filter_long_words2(["x","run","asdf",'kkkkkk'],3))
#Represent a small bilingual lexicon as a Python dictionary in the following fashion {"merry":"god", "christmas":"jul", "and":"och", "happy":gott", "new":"nytt", "year":"år"} and use it to translate your Christmas cards from English into Swedish. Use the higher order function map() to write a function translate() that takes a list of English words and returns a list of Swedish words.
def translate2(s):
  d = {"merry":"god", "christmas":"jul", "and":"och", "happy":"gott", "new":"nytt", "year":"år"}
  return list(map(lambda x: d.get(x, x), s))
print(translate2("We wish you a merry christmas and xmas. happy new year!".split()))
#Implement the higher order functions map(), filter() and reduce(). (They are built-in but writing them yourself may be a good exercise.)
def map2(f,l):
  r = []
  for x in l:
    r += [f(x)]
  return r
print(map2(lambda x: x*x, list(range(10))))
def odd(x):
  return x % 2 == 1
def filter2(f, l):
  r = []
  for x in l:
    if f(x):
      r += [x]
  return r
print(filter2(odd, list(range(10))))
def reduce2(f,l,i = False):
  if not i:
    i = l[0]
  r = i
  for x in l:
    r = f(r, x)
  return r
print(reduce2(lambda x, y: x * y,list(range(1,10))))
#Simple exercises including I/O

#Write a version of a palindrome recogniser that accepts a file name from the user, reads each line, and prints the line to the screen if it is a palindrome.
def palindromF(fn):
  fileobj = open(fn, 'r')
  while True:
    line = fileobj.readline()
    #print(is_palindrome2(line))
    if not line:
      break
    if is_palindrome2(line):
      print(line)
  fileobj.close()
palindromF('pali.txt')
#According to Wikipedia, a semordnilap is a word or phrase that spells a different word or phrase backwards. ("Semordnilap" is itself "palindromes" spelled backwards.) Write a semordnilap recogniser that accepts a file name (pointing to a list of words) from the user and finds and prints all pairs of words that are semordnilaps to the screen. For example, if "stressed" and "desserts" is part of the word list, the the output should include the pair "stressed desserts". Note, by the way, that each pair by itself forms a palindrome!
def semordnilap(fn):
  with open(fn, 'rt') as f:
  #  for line in f:
    a = f.read().split()
    printed = []
    for x in a:
      if x[::-1] in a and not x in printed:
        print(x, x[::-1])
        printed += [x[::-1]]
semordnilap('semo.txt')
#Write a procedure char_freq_table() that, when run in a terminal, accepts a file name from the user, builds a frequency listing of the characters contained in the file, and prints a sorted and nicely formatted character frequency table to the screen.
def char_freq_table(fn):
  with open(fn, 'rt') as f:
    cf = char_freq(f.read())
    import math
    col = int(math.ceil(math.sqrt(len(cf))))
    i = 0
    for x,y in sorted(cf.items(), key=lambda x: x[1]):
      print( (str(ord(x)) + ' : ' + str(y)).center(10) , end='|\n' if col == i else '    ')
      i+=1
      if i > col:
        i = 0
char_freq_table('semo.txt')
#The International Civil Aviation Organization (ICAO) alphabet assigns code words to the letters of the English alphabet acrophonically (Alfa for A, Bravo for B, etc.) so that critical combinations of letters (and numbers) can be pronounced and understood by those who transmit and receive voice messages by radio or telephone regardless of their native language, especially when the safety of navigation or persons is essential. Here is a Python dictionary covering one version of the ICAO alphabet:
#
#d = {'a':'alfa', 'b':'bravo', 'c':'charlie', 'd':'delta', 'e':'echo', 'f':'foxtrot',
#     'g':'golf', 'h':'hotel', 'i':'india', 'j':'juliett', 'k':'kilo', 'l':'lima',
#     'm':'mike', 'n':'november', 'o':'oscar', 'p':'papa', 'q':'quebec', 'r':'romeo',
#     's':'sierra', 't':'tango', 'u':'uniform', 'v':'victor', 'w':'whiskey',
#     'x':'x-ray', 'y':'yankee', 'z':'zulu'}
#Your task in this exercise is to write a procedure speak_ICAO() able to translate any text (i.e. any string) into spoken ICAO words. You need to import at least two libraries: os and time. On a mac, you have access to the system TTS (Text-To-Speech) as follows: os.system('say ' + msg), where msg is the string to be spoken. (Under UNIX/Linux and Windows, something similar might exist.) Apart from the text to be spoken, your procedure also needs to accept two additional parameters: a float indicating the length of the pause between each spoken ICAO word, and a float indicating the length of the pause between each word spoken.
def speak_ICAO(s, charPause, wordPause):
  d = {'a':'alfa', 'b':'bravo', 'c':'charlie', 'd':'delta', 'e':'echo', 'f':'foxtrot',
     'g':'golf', 'h':'hotel', 'i':'india', 'j':'juliett', 'k':'kilo', 'l':'lima',
     'm':'mike', 'n':'november', 'o':'oscar', 'p':'papa', 'q':'quebec', 'r':'romeo',
     's':'sierra', 't':'tango', 'u':'uniform', 'v':'victor', 'w':'whiskey',
     'x':'x-ray', 'y':'yankee', 'z':'zulu'}
  import os
  import time
  for x in s:
    print(d.get(x,''))
    if ' ' == x:
      time.sleep(wordPause)
    else:
      time.sleep(charPause)

def icaotest():
  speak_ICAO("some birds can fly", 0.1, 0.5)
#python -i 46Sim...
#A hapax legomenon (often abbreviated to hapax) is a word which occurs only once in either the written record of a language, the works of an author, or in a single text. Define a function that given the file name of a text will return all its hapaxes. Make sure your program ignores capitalization.
def hapax(fn): # Гапакс
  with open(fn, 'rt') as f:
    contents = f.read().lower()
    wordFreq = dict()
    for x in contents.split():
      if x in wordFreq:
        wordFreq[x] += 1
      else:
        wordFreq[x] = 1
    #hapaxes = list(filter(lambda x: x == 1, wordFreq.values()))
    hapaxes = []
    for s,n in wordFreq.items():
      if n == n:
        hapaxes += [s]
    return hapaxes
print(hapax('semo.txt'))
#Write a program that given a text file will create a new text file in which all the lines from the original file are numbered from 1 to n (where n is the number of lines in the file).
def numFileLines(fn):
  with open(fn, 'rt') as fin:
    with open(fn+'.out', 'wt') as fout:
      n = 1
      for x in fin:
        fout.write(str(n) + ' ' + x)
        n += 1
#numFileLines('46SimplePythonExercises.py')
 #Write a program that will calculate the average word length of a text stored in a file (i.e the sum of all the lengths of the word tokens in the text, divided by the number of word tokens).
def avgWordLen(fn):
  with open(fn, 'rt') as f:
    words = f.read().split()
    return sum(wordsLens3(words)) / len(words)
print(avgWordLen('semo.txt'))
#39. Write a program able to play the "Guess the number"-game, where the number to be guessed is randomly chosen between 1 and 20. (Source: http://inventwithpython.com) This is how it should work when run in a terminal:
#>>> import guess_number
#Hello! What is your name?
#Torbjörn
#Well, Torbjörn, I am thinking of a number between 1 and 20.
#Take a guess.
#10
#Your guess is too low.
#Take a guess.
#15
#Your guess is too low.
#Take a guess.
#18
#Good job, Torbjörn! You guessed my number in 3 guesses!
def guess_number():
  import random
  print('Hello! What is your name?')
  name = input()
  print('Well, ' + name + ', I am thinking of a number between 1 and 20.')
  number = random.randint(1,20)
  turns = 0
  while True:
    print('Take a guess.')
    g = int(input())
    turns += 1
    if g > number:
      print('Your guess is too high.')
    elif g < number:
      print('Your guess is too low.')
    else:
      print('Good job, ' + name + '! You guessed my number in ' + str(turns) + ' guesses!')
      break
#guess_number()

#40. An anagram is a type of word play, the result of rearranging the letters of a word or phrase to produce a new word or phrase, using all the original letters exactly once; e.g., orchestra = carthorse, A decimal point = I'm a dot in place. Write a Python program that, when started 1) randomly picks a word w from given list of words, 2) randomly permutes w (thus creating an anagram of w), 3) presents the anagram to the user, and 4) enters an interactive loop in which the user is invited to guess the original word. It may be a good idea to work with (say) colour words only. The interaction with the program may look like so:
#>>> import anagram
#Colour word anagram: onwbr
#Guess the colour word!
#black
#Guess the colour word!
#brown
#Correct!
def anagram(l):
  import random as r
  r.seed()
  word = l[r.randint(0, len(l)-1)]
  lword = list(word)
  #print(l, lword, word)
  for x in range(r.randint(5,20)):
    a = r.randint(0, len(word)-1)
    b = r.randint(0, len(word)-1)
    lword[a], lword[b] = lword[b], lword[a]
  print('Colour word anagram:', ''.join(lword))
  while True:
    print('Guess the colour word!')
    g = input()
    if g == word:
      print('Correct!')
      break
def anagramRun():
  anagram('there hidden word five characters long'.split())

#41. In a game of Lingo, there is a hidden word, five characters long. The object of the game is to find this word by guessing, and in return receive two kinds of clues: 1) the characters that are fully correct, with respect to identity as well as to position, and 2) the characters that are indeed present in the word, but which are placed in the wrong position. Write a program with which one can play Lingo. Use square brackets to mark characters correct in the sense of 1), and ordinary parentheses to mark characters correct in the sense of 2). Assuming, for example, that the program conceals the word "tiger", you should be able to interact with it in the following way:
#>>> import lingo
#snake
#Clue: snak(e)
#fiest
#Clue: f[i](e)s(t)
#times
#Clue: [t][i]m[e]s
#tiger
#Clue: [t][i][g][e][r]
def lingo():
  def printLingo(s, w):
    i = 0
    r = ''
    while i < len(s):
      if s[i] == w[i]:
        r += '[' + s[i] + ']'
      elif s[i] in w:
        r += '(' + s[i] + ')'
      else:
        r += s[i]
      i += 1
    print(r)

  import random as r
  r.seed()
  words='tiger snake holod burge cotto'.split()
  word = words[r.randint(0, len(words)-1)]
  while True:
    g = input('Clue: ')
    printLingo(g[:5], word)
    if g == word:
      break

#Somewhat harder exercises
#42. A sentence splitter is a program capable of splitting a text into sentences. The standard set of heuristics for sentence splitting includes (but isn't limited to) the following rules:
#Sentence boundaries occur at one of "." (periods), "?" or "!", except that

#Periods followed by whitespace followed by a lower case letter are not sentence boundaries.
#Periods followed by a digit with no intervening whitespace are not sentence boundaries.
#Periods followed by whitespace and then an upper case letter, but preceded by any of a short list of titles are not sentence boundaries. Sample titles include Mr., Mrs., Dr., and so on.
#Periods internal to a sequence of letters with no adjacent whitespace are not sentence boundaries (for example, www.aptex.com, or e.g).
#Periods followed by certain kinds of punctuation (notably comma and more periods) are probably not sentence boundaries.
# (\.\s[a-z]) (\.\d) ((Mr|Mrs|Dr|Jr)\.\s[A-Z]) (\w\.\w) (\.(\,|\.))
# (\.\s[a-z])|(\.\d)|((Mr|Mrs|Dr|Jr)\.\s[A-Z])|(\w\.\w)|(\.(\,|\.))
# ((Mr|Mrs|Dr|Jr)\.\s[A-Z]) (\w\.\w)   (\.\s[a-z]) (\.\d) (\.(\,|\.))
#Your task here is to write a program that given the name of a text file is able to write its content with each sentence on a separate line. Test your program with the following short text: Mr. Smith bought cheapsite.com for 1.5 million dollars, i.e. he paid a lot for it. Did he mind? Adam Jones Jr. thinks he didn't. In any case, this isn't true... Well, with a probability of .9 it isn't. The result should be:
#Mr. Smith bought cheapsite.com for 1.5 million dollars, i.e. he paid a lot for it.
#Did he mind?
#Adam Jones Jr. thinks he didn't.
#In any case, this isn't true...
#Well, with a probability of .9 it isn't.
def sentenceSplitter(fn):
  content = ''
  with open(fn, 'rt') as fin:
    content = fin.read();
  with open(fn, 'wt') as fout:
    import re
    s = re.sub('\.','.\n', content)
    s = re.sub('((Mr|Mrs|Dr|Jr)\.\n(\s[A-Z]))','\g<2>.\g<3>', s)
    s = re.sub('(\w)\.\n(\w)','\g<1>.\g<2>', s)
    s = re.sub('\.\n(\s[a-z])','.\g<1>', s)
    s = re.sub('\.\n(\d)','.\g<1>', s)
    s = re.sub('\.\n(\.+)','.\g<1>', s)
    s = re.sub('\.\n(\,|\.)','.\g<1>', s)
    s = re.sub('(\?|\!)\s', '\g<1>\n', s)
    print(s)
    fout.write(content)
#sentenceSplitter('test.txt')
#43. An anagram is a type of word play, the result of rearranging the letters of a word or phrase to produce a new word or phrase, using all the original letters exactly once; e.g., orchestra = carthorse. Using the word list at http://www.puzzlers.org/pub/wordlists/unixdict.txt, write a program that finds the sets of words that share the same characters that contain the most words in them.
def is_anagram(a,b):
  a = list(a)
  b = list(b)
  for x in a:
    if x in b:
      del b[b.index(x)]

  return [] == b
def anagrams(l):
  x = y = 0
  r = []
  while x < len(l)-1:
    y = x + 1
    z = []
    while y < len(l)-1:
      if is_anagram(l[x], l[y]):
        if len(z) == 0:
          z += [l[x]]
        z += [l[y]]
      y += 1
    if z:
      r += [z]
    x +=1
  return r
#print(is_anagram('bda', 'dab'))
#print(anagrams('bda dab bad ddd ada daa dda cad aaa dac'.split()))
def anagramFile():

  fn = 'unixdict.txt'
  content = ''
  with open(fn, 'rt') as f:
    content = f.read().split()
  # сначала создадим словарь вида {длинна : список слов данной длинны}
  words = dict()
  for x in content:
    if words.get(len(x),False):
      words[len(x)] += [x]
    else:
      words[len(x)] = [x]

  anag = []
  for l,v in words.items():
    words[l] = anagrams(v)

  with open(fn+'.out', 'wt') as f:
    for l,v in words.items():
      for x in v:
        f.write(x)
      f.write('\n')
#anagramFile()
#44. Your task in this exercise is as follows:
#
#Generate a string with N opening brackets ("[") and N closing brackets ("]"), in some arbitrary order.
#Determine whether the generated string is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest.
#Examples:
#
#   []        OK   ][        NOT OK
#   [][]      OK   ][][      NOT OK
#   [[][]]    OK   []][[]    NOT OK
def bracketsBalance(s):
  balance = 0
  if ']' == s[0] or '[' == s[-1]:
    return False
  for x in s:
    if balance < 0:
      return False
    if '[' == x:
      balance += 1
    else:
      balance -= 1
  return 0 == balance
def bracketsTest():
  import random as r
  r.seed()
  n = r.randint(2,3) * 2
  while True:
    s = ''
    for x in range(n):
      s += r.choice(['[',']'])
    print(s, bracketsBalance(s))
    if bracketsBalance(s):
      return
  #генерировать пока не будет True
bracketsTest()
for x in ' [] ][ [[ ]] [[[ ]]] [[] []] [][] [[][]] ][ ][][ []][[]'.split():
  print(x, bracketsBalance(x))
bracketsTest()
#45. A certain childrens game involves starting with a word in a particular category. Each participant in turn says a word, but that word must begin with the final letter of the previous word. Once a word has been given, it cannot be repeated. If an opponent cannot give a word in the category, they fall out of the game. For example, with "animals" as the category,
#Child 1: dog
#Child 2: goldfish
#Child 1: hippopotamus
#Child 2: snake
#Your task in this exercise is as follows: Take the following selection of 70 English Pokemon names (extracted from Wikipedia's list of Pokemon) and generate the/a sequence with the highest possible number of Pokemon names where the subsequent name starts with the final letter of the preceding name. No Pokemon name is to be repeated.
pokes = 'audino bagon baltoy banette bidoof braviary bronzor carracosta charmeleon cresselia croagunk darmanitan deino emboar emolga exeggcute gabite girafarig gulpin haxorus heatmor heatran ivysaur jellicent jumpluff kangaskhan kricketune landorus ledyba loudred lumineon lunatone machamp magnezone mamoswine nosepass petilil pidgeotto pikachu pinsir poliwrath poochyena porygon2 porygonz registeel relicanth remoraid rufflet sableye scolipede scrafty seaking sealeo silcoon simisear snivy snorlax spoink starly tirtouga trapinch treecko tyrogue vigoroth vulpix wailord wartortle whismur wingull yamask'
def seqpo(lst, n, al):
  item = lst[n]
  del lst[n]
  nxt = list(filter(lambda x: x.startswith(item[-1]), lst))
  print(item, lst, nxt)
  r = [item]
  if nxt:
    for x in nxt:
      r += seqpo(lst.copy(), lst.index(x), al + [item])
  return r
def highestSeq(l):
  return
print(seqpo('abc can nok nak ona'.split(),4, []))
# 45 Пред СЛОЖН

#46. An alternade is a word in which its letters, taken alternatively in a strict sequence, and used in the same order as the original word, make up at least two other words. All letters must be used, but the smaller words are not necessarily of the same length. For example, a word with seven letters where every second letter is used will produce a four-letter word and a three-letter word. Here are two examples:
#
#  "board": makes "bad" and "or".
#  "waists": makes "wit" and "ass".
#Using the word list at http://www.puzzlers.org/pub/wordlists/unixdict.txt, write a program that goes through each word in the list and tries to make two smaller words using every second letter. The smaller words must also be members of the list. Print the words to the screen in the above fashion.


text:
title: BeagleBone Air User Guide
tags: "open-hardware"
published: true
img: ic-bbair.png
image: "http://support.thingplus.net/assets/ogp/ogp_bbair.png"
permalink: /en/open-hardware/bba-user-guide.html
---

Thing+ Integration Guide for BeagleBone Air

1. [Environment Setting](#id-setting)
2. [Install Thing+ Embedded Package](#id-package)
3. [Gatway Registration](#id-register)

---

#### 1. Environment Setting

1) Telnet/SSH Client is required for controlling the BeagleBone Green from your PC.

- If you are a Mac or Linux user, please use the default terminal utility.
- If you are a Windows user, we recommend that you use the "Putty" client to access your Raspberry Pi.
- [Putty Download link](http://the.earth.li/~sgtatham/putty/latest/x86/putty.exe)
- [Putty Manual](http://the.earth.li/~sgtatham/putty/0.58/htmldoc/)

2) The example configuration of this guide is as follows.

  - BBA, OLED display, Temperature&Humidity sensor

![BBG + Ehternet + USB Cable](/assets/bba_board_sensors.png)

3) After the BeagleBone is booted up completely, connect to it over SSH. The booting process takes 2~3 minutes

- If you can't found IP address, please refer the [`Troubleshooting`](/en/help/troubleshooting.html) section.

   ```bash
   $ ssh root@<IP Address>
   ```

   - Example for Mac & Linux

     ```bash
     $ ssh root@192.168.1.XXX
     ```

- Example for Windows
  - Run the putty, and Insert your IP Address, and then, Click the button `Open` and Enter a password.
    ![BBG putty login](/assets/putty_login_bbg.png)

> Notice : BeagleBone Green is possible to connect with PC and USB cable. Please refer the [`How to connect with USB on Beaglebone Green`](#id-bbg-usbconnect) section.

> Notice: In case of Windows, you have to re-launch putty, when BeagleBone Green is rebooted.

4) Change the hostname of your BBG for identifying it.

> Remark: You can't move the cursor on the Terminal and/or Putty with your mouse. please use your keyboard to move it.

- Modify `/etc/hostname`.

  ```bash
  @BBA:$ nano /etc/hostname
  ```

- Change the `BeagleBone` in the file to your own name(letter, number and hyphen(-) allowed only) like the below image.
  ![BBG Modify hostname](/assets/modify_hostname.png)

  - When you complete the edit task, press `CTRL-O` and `Enter` for saving the updates. Press `CTRL-X` to close the nano editor

- To apply your modification, please reboot your BeagleBone Air.

  ```bash
  @BBA:$ reboot
  ```

---

#### 2. Install Thing+ Embedded Package

1) Connect Grove Starter kit sensor to BeagleBone Air without Ethernet(LAN cable) and Power Cable.

- I2C HUB: How to Connection BeagleBone Air with I2C hub
![BBG + Grove](/assets/bba_i2chub.png)

- J4: Means a line connecting Beagle Bon Air and I2C HUB.
![BBG + Grove](/assets/bba_sensor_connect.png)

2) Connect Ethernet(LAN cable), and Power Cable to BeagleBone Air.

3) Connect to your BeagleBone Air

4) Make folder to be install Thing+ Embedded Package and move that folder.

```bash
@BBA:$ mkdir /opt/thingplus
@BBA:$ cd /opt/thingplus
```

5) Download a install script file.

```bash
@BBA:$ wget http://support.thingplus.net/download/install/thingplus_embedded_sdk_bba_install.sh
```

6) Grant a run permission to the script you downloaded and Install the Thing+ Embedded Package.

- It can take few minutes to install the Thing+ Embedded Package.

  ```bash
  @BBA:$ chmod 755 thingplus_embedded_sdk_bba_install.sh
  @BBA:$ ./thingplus_embedded_sdk_bba_install.sh
  ```

7) Reboot BeagleBone Air.

```bash
@BBA:$ reboot
```

---

#### 3. Gatway Registration
Plesase refer [Gateway Registration](/en/user-guide/registration.html#id-gateway)

redpajama_set_name: RedPajamaGithub


text:
// task/control.rs
// AltOS Rust
//
// Created by Daniel Seitz on 1/11/17

use super::stack::Stack;
use super::args::Args;
use alloc::boxed::Box;
use sync::CriticalSection;

pub const NUM_PRIORITIES: usize = 4;

pub const VALID_TASK: usize = 0xBADB0100;
pub const INVALID_TASK: usize = 0x0;

type HandleResult<T> = Result<T, ()>;

mod tid {
  use atomic::{ATOMIC_USIZE_INIT, AtomicUsize, Ordering};

  static CURRENT_TID: AtomicUsize = ATOMIC_USIZE_INIT;

  /// Atomically increment the task id and return the old value
  pub fn fetch_next_tid() -> usize {
    CURRENT_TID.fetch_add(1, Ordering::Relaxed)
  }
}

#[derive(Debug, Copy, Clone, PartialEq)]
pub enum Delay {
  Timeout,
  Sleep,
  Overflowed,
  Invalid,
}

/// Priorities that a task can have.
///
/// Priorities declare which tasks should be run before others. A higher priority task will always
/// be run before a lower priority task if it is ready to be run.
#[derive(Debug, Copy, Clone, PartialEq)]
pub enum Priority {
  /// The highest priority.
  ///
  /// Tasks with this priority will always be run before any other task. This priority should be
  /// reserved for short lived, time critical tasks that do work important to the functioning of
  /// the system.
  Critical = 0,

  /// The standard task priority.
  ///
  /// Most tasks should be given this priority. The task can be preempted at any time so should not
  /// rely on any operation to be atomic unless specifically marked in a critical section.
  Normal = 1,

  /// The minimal task priority.
  ///
  /// These tasks should be purely optional for the system to run. They will only be run if there
  /// are no other tasks to run, so on some systems they may never run at all.
  Low = 2,

  #[doc(hidden)]
  __Idle = 3,
}

impl Priority {
  /// Returns a range of values corresponding to each priority, starting from the highest.
  pub fn all() -> ::core::ops::Range<usize> {
    (0..NUM_PRIORITIES)
  }

  /// Returns a range of values corresponding to priorities equal to or higher than `self`.
  ///
  /// Use this to iterate over priority queues starting from the highest priority queue down to the
  /// current priority.
  pub fn higher(&self) -> ::core::ops::Range<usize> {
    0..(*self as usize + 1)
  }
}

/// States a task can be in
///
/// States describe the current condition of a task. The scheduler uses this to determine which
/// tasks are available to run.
#[derive(Debug, Copy, Clone, PartialEq)]
pub enum State {
  /// The task is in the process of being created, it has not been initialized yet and is not yet
  /// usable.
  Embryo,

  /// The task is ready to be run if the scheduler decides to pick it.
  Ready,

  /// The task is currently running.
  Running,

  /// The task is blocked on some I/O or event. This could mean it's waiting for a device or some
  /// shared resource to become available.
  Blocked,

  /// The task is suspended, it will not run until it is resumed.
  Suspended,
}

/// A `TaskControl` tracks the running state of a task.
///
/// This struct keeps track of information about a specific task. When a `TaskControl` goes out of
/// scope the memory associated with it is freed.
#[repr(C)]
#[doc(hidden)]
#[derive(Debug)]
pub struct TaskControl {
  stack: Stack, /*** stack MUST be the first field of the struct ***/
  args: Box<Args>,
  tid: usize,
  name: &'static str,
  valid: usize,
  pub wchan: usize,
  pub delay: usize,
  pub delay_type: Delay,
  pub destroy: bool,
  pub priority: Priority,
  pub state: State,
}

unsafe impl Send for TaskControl {}
unsafe impl Sync for TaskControl {}

impl TaskControl {
  /// Creates a new `TaskControl` initialized and ready to be scheduled.
  ///
  /// All of the arguments to this function are the same as the `new_task` kernel function.
  pub fn new(code: fn(&mut Args), args: Args, depth: usize, priority: Priority, name: &'static str) -> Self {
    let stack = Stack::new(depth);

    // Arguments struct stored right above the stack
    let args_mem: Box<Args> = Box::new(args);

    let tid = tid::fetch_next_tid();

    let mut task = TaskControl {
      stack: stack,
      args: args_mem,
      tid: tid,
      name: name,
      valid: VALID_TASK + (tid & 0xFF),
      wchan: 0,
      delay: 0,
      delay_type: Delay::Invalid,
      destroy: false,
      priority: priority,
      state: State::Embryo,
    };
    task.initialize(code);
    task
  }

  /// This initializes the task's stack. This method MUST only be called once, calling it more than
  /// once could at best waste some stack space and at worst corrupt an active stack.
  fn initialize(&mut self, code: fn(&mut Args)) {
    self.stack.initialize(code, &self.args);
    self.state = State::Ready;
  }

  pub fn destroy(&mut self) {
    // TODO: Check if task is INIT task? So at least we always have a safe task to run...
    let _g = CriticalSection::begin();
    self.destroy = true;
    self.valid = INVALID_TASK;
  }

  /// Checks if the stack has gone past its bounds, returns true if it has.
  ///
  /// Used to check if the stack has exceeded the memory allocated for it. If it has this means
  /// that we may have corrupted some memory.
  pub fn is_stack_overflowed(&self) -> bool {
    // TODO: Add some stack guard bytes to check if we've overflowed during execution?
    //  This would add some extra overhead, maybe have some #[cfg] that determines if we should add
    //  this extra security?
    self.stack.check_overflow()
  }

  pub fn tid(&self) -> usize { self.tid }
}

/// A `TaskHandle` references a `TaskControl` and provides access to some state about it.
///
/// A `TaskHandle` is created whenever a new task is requested from the operating system. It
/// provides a way to examine the state of the task at run time as well as perform some operations
/// on it like marking it for destruction.
///
/// This struct is thread safe, as all accesses to the internal `TaskControl` are checked for
/// validity. If a task has been destroyed by one thread, then any other thread trying to access it
/// will be returned an `Err`.
#[derive(Copy, Clone, Debug)]
pub struct TaskHandle(*const TaskControl);

unsafe impl Send for TaskHandle {}
unsafe impl Sync for TaskHandle {}

impl TaskHandle {
  /// Creates a new `TaskHandle` referencing a `TaskControl`.
  pub fn new(task: &TaskControl) -> Self {
    TaskHandle(task)
  }

  /// Marks a task for destruction by the OS, returns true if it was in a valid state before the
  /// call, false otherwise.
  ///
  /// This does not immediately clean up the task, it only marks the task for destruction. The
  /// memory associated with that task will be reclaimed at the operating system's convenience.
  /// There is no guarantee about when this will happen, and in some circumstances it may in fact
  /// never happen, but once a task has been marked for destruction all attempts to access its data
  /// through a `TaskHandle` will return `Err(())`.
  ///
  /// # Examples
  ///
  /// ```rust,no_run
  /// # use altos_core::{TaskHandle, Priority};
  /// # use altos_core::syscall::new_task;
  /// # use altos_core::args::Args;
  ///
  /// let handle = new_task(test_task, Args::empty(), 512, Priority::Normal, "new_task_name");
  ///
  /// if handle.destroy() {
  ///   // Task was valid, now invalid
  /// }
  /// else {
  ///   // Task had already been destroyed
  /// }
  ///
  /// # fn test_task(_args: &mut Args) {
  /// #   loop {}
  /// # }
  /// ```
  pub fn destroy(&mut self) -> bool {
    // FIXME: If the task has allocated any dynamic memory on it own, this will be leaked when the
    //  task is destroyed.
    //    A possible solution... allocate a heap space for each task. Pass a heap allocation
    //    interface to the task implicitly and do all dynamic memory allocation through this
    //    interface. When the task is destroyed we can just free the whole task-specific heap so we
    //    wont have to worry about leaking memory. This means we would likely have to disallow core
    //    library `Box` allocations within the task. Or... we just don't allow dynamic allocation
    //    within tasks. - Daniel Seitz
    let _g = CriticalSection::begin();
    if self.is_valid() {
      let task = self.task_ref_mut();
      task.destroy();
      true
    }
    else {
      false
    }
  }

  /// Returns a task's priority.
  ///
  /// The `Priority` of a task determines in what order it should be run compared to other tasks.
  ///
  /// # Examples
  ///
  /// ```rust,no_run
  /// # use altos_core::{TaskHandle, Priority};
  /// # use altos_core::syscall::new_task;
  /// # use altos_core::args::Args;
  ///
  /// let handle = new_task(test_task, Args::empty(), 512, Priority::Normal, "new_task_name");
  ///
  /// match handle.priority() {
  ///   Ok(priority) => { /* Task was valid */ },
  ///   Err(()) => { /* Task was destroyed */ },
  /// }
  ///
  /// # fn test_task(_args: &mut Args) {
  /// #   loop {}
  /// # }
  /// ```
  ///
  /// # Errors
  ///
  /// If the task has been destroyed then this method will return an `Err(())`.
  pub fn priority(&self) -> HandleResult<Priority> {
    let _g = CriticalSection::begin();
    if self.is_valid() {
      let task = self.task_ref();
      Ok(task.priority)
    }
    else {
      Err(())
    }
  }

  /// Returns a task's current state.
  ///
  /// The `State` of a task determines if it is able to run or not.
  ///
  /// # Examples
  ///
  /// ```rust,no_run
  /// # use altos_core::{TaskHandle, Priority};
  /// # use altos_core::syscall::new_task;
  /// # use altos_core::args::Args;
  ///
  /// let handle = new_task(test_task, Args::empty(), 512, Priority::Normal, "new_task_name");
  ///
  /// match handle.state() {
  ///   Ok(state) => { /* Task was valid */ },
  ///   Err(()) => { /* Task was destroyed */ },
  /// }
  ///
  /// # fn test_task(_args: &mut Args) {
  /// #   loop {}
  /// # }
  /// ```
  ///
  /// # Errors
  ///
  /// If the task has been destroyed then this method will return an `Err(())`.
  pub fn state(&self) -> HandleResult<State> {
    let _g = CriticalSection::begin();
    if self.is_valid() {
      let task = self.task_ref();
      Ok(task.state)
    }
    else {
      Err(())
    }
  }

  /// Returns a task's tid (task identifier).
  ///
  /// The tid is a unique identifier that differentiates different tasks even if they have the same
  /// name.
  ///
  /// # Examples
  ///
  /// ```rust,no_run
  /// # use altos_core::{TaskHandle, Priority};
  /// # use altos_core::syscall::new_task;
  /// # use altos_core::args::Args;
  ///
  /// let handle = new_task(test_task, Args::empty(), 512, Priority::Normal, "new_task_name");
  ///
  /// match handle.tid() {
  ///   Ok(tid) => { /* Task was valid */ },
  ///   Err(()) => { /* Task was destroyed */ },
  /// }
  ///
  /// # fn test_task(_args: &mut Args) {
  /// #   loop {}
  /// # }
  /// ```
  ///
  /// # Errors
  ///
  /// If the task has been destroyed then this method will return an `Err(())`.
  pub fn tid(&self) -> HandleResult<usize> {
    let _g = CriticalSection::begin();
    if self.is_valid() {
      let task = self.task_ref();
      Ok(task.tid)
    }
    else {
      Err(())
    }
  }

  /// Returns the task's name.
  ///
  /// ```rust,no_run
  /// # use altos_core::{TaskHandle, Priority};
  /// # use altos_core::syscall::new_task;
  /// # use altos_core::args::Args;
  ///
  /// let handle = new_task(test_task, Args::empty(), 512, Priority::Normal, "new_task_name");
  ///
  /// match handle.name() {
  ///   Ok(name) => { /* Task was valid */ },
  ///   Err(()) => { /* Task was destroyed */ },
  /// }
  ///
  /// # fn test_task(_args: &mut Args) {
  /// #   loop {}
  /// # }
  /// ```
  ///
  /// # Errors
  ///
  /// If the task has been destroyed then this method will return an `Err(())`.
  pub fn name(&self) -> HandleResult<&'static str> {
    let _g = CriticalSection::begin();
    if self.is_valid() {
      let task = self.task_ref();
      Ok(task.name)
    }
    else {
      Err(())
    }
  }

  /// Returns the task's stack size.
  ///
  /// # Examples
  ///
  /// ```rust,no_run
  /// # use altos_core::{TaskHandle, Priority};
  /// # use altos_core::syscall::new_task;
  /// # use altos_core::args::Args;
  ///
  /// let handle = new_task(test_task, Args::empty(), 512, Priority::Normal, "new_task_name");
  ///
  /// match handle.stack_size() {
  ///   Ok(size) => { /* Task was valid */ },
  ///   Err(()) => { /* Task was destroyed */ },
  /// }
  ///
  /// # fn test_task(_args: &mut Args) {
  /// #   loop {}
  /// # }
  /// ```
  ///
  /// # Errors
  ///
  /// If the task has been destroyed then this method will return an `Err(())`.
  pub fn stack_size(&self) -> HandleResult<usize> {
    let _g = CriticalSection::begin();
    if self.is_valid() {
      let task = self.task_ref();
      Ok(task.stack.depth())
    }
    else {
      Err(())
    }
  }

  /// Check if the task pointed to by this handle is valid
  ///
  /// # Examples
  ///
  /// ```rust,no_run
  /// use altos_core::syscall::new_task;
  ///
  /// let handle = new_task(test_task, Args::empty(), 512, Priority::Normal, "new_task_name");
  ///
  /// if handle.is_valid() {
  ///   // The task is still valid
  /// }
  /// else {
  ///   // The task has been destroyed
  /// }
  ///
  /// ```
  pub fn is_valid(&self) -> bool {
    // UNSAFE: Yes, potentially we're reading from a dangling pointer (if the task has been freed,
    // for instance), but there should be specific values at these locations, and if they aren't
    // there then at least we'll know not to do anymore reads.
    let (tid, valid) = unsafe { ((*self.0).tid, (*self.0).valid) };
    let tid_mask = tid & 0xFF;
    valid == VALID_TASK + tid_mask
  }

  fn task_ref(&self) -> &TaskControl {
    // UNSAFE: This is used internally to the TaskHandle, and is only ever called after checking if
    // the handle is still valid. All operations are within critical sections and so can be
    // considered atomic
    unsafe { &*self.0 }
  }

  fn task_ref_mut(&mut self) -> &mut TaskControl {
    // UNSAFE: This is used internally to the TaskHandle, and is only ever called after checking if
    // the handle is still valid. All operations are within critical sections and so can be
    // considered atomic
    unsafe { &mut *(self.0 as *mut TaskControl) }
  }
}

#[cfg(test)]
mod tests {
  use super::*;
  use test;

  fn get_task() -> TaskControl {
    // NOTE: We can't return the TaskControl and the TaskHandle as a tuple here because the
    // TaskControl object get's moved on return so we would end up with a dangling pointer in our
    // TaskHandle
    test::create_test_task(512, Priority::Normal, "task test")
  }

  fn get_invalid_task() -> TaskControl {
    let mut task = test::create_test_task(512, Priority::Normal, "invalid test");
    task.valid = INVALID_TASK;
    task
  }

  #[test]
  fn task_handle_valid() {
    let mut task = get_task();
    let handle = TaskHandle::new(&task);

    assert!(handle.is_valid());
    task.valid = INVALID_TASK;
    assert!(!handle.is_valid());
  }

  #[test]
  fn task_handle_destroy() {
    let task = get_task();
    let mut handle = TaskHandle::new(&task);

    assert!(handle.is_valid());
    assert!(handle.destroy());

    assert!(task.destroy);
    assert!(!handle.is_valid());
  }

  #[test]
  fn invalid_task_handle_destroy() {
    let task = get_invalid_task();
    let mut handle = TaskHandle::new(&task);

    assert!(!handle.is_valid());
    assert!(!handle.destroy());
    assert!(!handle.is_valid());
  }

  #[test]
  fn task_handle_stack_size() {
    let task = get_task();
    let handle = TaskHandle::new(&task);

    assert_eq!(handle.stack_size(), Ok(512));
  }

  #[test]
  fn invalid_task_handle_stack_size() {
    let task = get_invalid_task();
    let handle = TaskHandle::new(&task);

    assert!(handle.stack_size().is_err());
  }

  #[test]
  fn task_handle_priority() {
    let task = get_task();
    let handle = TaskHandle::new(&task);

    assert_eq!(handle.priority(), Ok(Priority::Normal));
  }

  #[test]
  fn invalid_task_handle_priority() {
    let task = get_invalid_task();
    let handle = TaskHandle::new(&task);

    assert!(handle.priority().is_err());
  }

  #[test]
  fn task_handle_state() {
    let task = get_task();
    let handle = TaskHandle::new(&task);

    assert_eq!(handle.state(), Ok(State::Ready));
  }

  #[test]
  fn invalid_task_handle_state() {
    let task = get_invalid_task();
    let handle = TaskHandle::new(&task);

    assert!(handle.state().is_err());
  }

  #[test]
  fn task_handle_name() {
    let task = get_task();
    let handle = TaskHandle::new(&task);

    assert_eq!(handle.name(), Ok("task test"));
  }

  #[test]
  fn invalid_task_handle_name() {
    let task = get_invalid_task();
    let handle = TaskHandle::new(&task);

    assert!(handle.name().is_err());
  }

  #[test]
  fn task_handle_tid() {
    let task = get_task();
    let handle = TaskHandle::new(&task);

    assert_eq!(handle.tid(), Ok(task.tid));

  }

  #[test]
  fn invalid_task_handle_tid() {
    let task = get_invalid_task();
    let handle = TaskHandle::new(&task);

    assert!(handle.tid().is_err());
  }
}


text:
package org.springframework.test.context;

import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.util.LinkedHashSet;
import java.util.Set;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.springframework.beans.BeanUtils;
import org.springframework.core.log.LogMessage;
import org.springframework.lang.Nullable;
import org.springframework.test.context.TestContextAnnotationUtils.AnnotationDescriptor;
import org.springframework.util.ClassUtils;

/**
 * {@code BootstrapUtils} is a collection of utility methods to assist with
 * bootstrapping the Spring TestContext Framework.
 *
 *
Only intended for internal use.
 *
 * @author Sam Brannen
 * @author Phillip Webb
 * @since 4.1
 * @see BootstrapWith
 * @see BootstrapContext
 * @see TestContextBootstrapper
 */
public abstract class BootstrapUtils {

	private static final String DEFAULT_BOOTSTRAP_CONTEXT_CLASS_NAME =
			"org.springframework.test.context.support.DefaultBootstrapContext";

	private static final String DEFAULT_CACHE_AWARE_CONTEXT_LOADER_DELEGATE_CLASS_NAME =
			"org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate";

	private static final String DEFAULT_TEST_CONTEXT_BOOTSTRAPPER_CLASS_NAME =
			"org.springframework.test.context.support.DefaultTestContextBootstrapper";

	private static final String DEFAULT_WEB_TEST_CONTEXT_BOOTSTRAPPER_CLASS_NAME =
			"org.springframework.test.context.web.WebTestContextBootstrapper";

	private static final String WEB_APP_CONFIGURATION_ANNOTATION_CLASS_NAME =
			"org.springframework.test.context.web.WebAppConfiguration";

	private static final Class<? extends Annotation> webAppConfigurationClass = loadWebAppConfigurationClass();

	private static final Log logger = LogFactory.getLog(BootstrapUtils.class);

	/**
	 * Create the {@code BootstrapContext} for the specified {@linkplain Class test class}.
	 *
Uses reflection to create a {@link org.springframework.test.context.support.DefaultBootstrapContext}.
	 * that uses a {@link org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate}.
	 * @param testClass the test class for which the bootstrap context should be created
	 * @return a new {@code BootstrapContext}; never {@code null}
	 */
	@SuppressWarnings("unchecked")
	static BootstrapContext createBootstrapContext(Class<?> testClass) {
		CacheAwareContextLoaderDelegate cacheAwareContextLoaderDelegate = createCacheAwareContextLoaderDelegate();
		String className = DEFAULT_BOOTSTRAP_CONTEXT_CLASS_NAME;
		Class<? extends BootstrapContext> clazz = null;
		try {
			clazz = (Class<? extends BootstrapContext>)
					ClassUtils.forName(className, BootstrapUtils.class.getClassLoader());
			Constructor<? extends BootstrapContext> constructor =
					clazz.getConstructor(Class.class, CacheAwareContextLoaderDelegate.class);
			logger.trace(LogMessage.format("Instantiating BootstrapContext using constructor [%s]", constructor));
			return BeanUtils.instantiateClass(constructor, testClass, cacheAwareContextLoaderDelegate);
		}
		catch (Throwable ex) {
			throw new IllegalStateException("Could not load BootstrapContext [%s]".formatted(className), ex);
		}
	}

	@SuppressWarnings("unchecked")
	private static CacheAwareContextLoaderDelegate createCacheAwareContextLoaderDelegate() {
		String className = DEFAULT_CACHE_AWARE_CONTEXT_LOADER_DELEGATE_CLASS_NAME;
		Class<? extends CacheAwareContextLoaderDelegate> clazz = null;
		try {
			clazz = (Class<? extends CacheAwareContextLoaderDelegate>)
					ClassUtils.forName(className, BootstrapUtils.class.getClassLoader());
			logger.trace(LogMessage.format("Instantiating CacheAwareContextLoaderDelegate from class [%s]", className));
			return BeanUtils.instantiateClass(clazz, CacheAwareContextLoaderDelegate.class);
		}
		catch (Throwable ex) {
			throw new IllegalStateException("Could not load CacheAwareContextLoaderDelegate [%s]".formatted(className), ex);
		}
	}

	/**
	 * Resolve the {@link TestContextBootstrapper} type for the supplied test class
	 * using the default {@link BootstrapContext}, instantiate the bootstrapper,
	 * and provide it a reference to the {@code BootstrapContext}.
	 *
If the {@link BootstrapWith @BootstrapWith} annotation is present on
	 * the test class, either directly or as a meta-annotation, then its
	 * {@link BootstrapWith#value value} will be used as the bootstrapper type.
	 * Otherwise, either the
	 * {@link org.springframework.test.context.support.DefaultTestContextBootstrapper
	 * DefaultTestContextBootstrapper} or the
	 * {@link org.springframework.test.context.web.WebTestContextBootstrapper
	 * WebTestContextBootstrapper} will be used, depending on the presence of
	 * {@link org.springframework.test.context.web.WebAppConfiguration @WebAppConfiguration}.
	 * @param testClass the test class for which the bootstrapper should be created
	 * @return a fully configured {@code TestContextBootstrapper}
	 * @since 6.0
	 */
	public static TestContextBootstrapper resolveTestContextBootstrapper(Class<?> testClass) {
		return resolveTestContextBootstrapper(createBootstrapContext(testClass));
	}

	/**
	 * Resolve the {@link TestContextBootstrapper} type for the test class in the
	 * supplied {@link BootstrapContext}, instantiate it, and provide it a reference
	 * to the {@link BootstrapContext}.
	 *
If the {@link BootstrapWith @BootstrapWith} annotation is present on
	 * the test class, either directly or as a meta-annotation, then its
	 * {@link BootstrapWith#value value} will be used as the bootstrapper type.
	 * Otherwise, either the
	 * {@link org.springframework.test.context.support.DefaultTestContextBootstrapper
	 * DefaultTestContextBootstrapper} or the
	 * {@link org.springframework.test.context.web.WebTestContextBootstrapper
	 * WebTestContextBootstrapper} will be used, depending on the presence of
	 * {@link org.springframework.test.context.web.WebAppConfiguration @WebAppConfiguration}.
	 * @param bootstrapContext the bootstrap context to use
	 * @return a fully configured {@code TestContextBootstrapper}
	 */
	static TestContextBootstrapper resolveTestContextBootstrapper(BootstrapContext bootstrapContext) {
		Class<?> testClass = bootstrapContext.getTestClass();

		Class<?> clazz = null;
		try {
			clazz = resolveExplicitTestContextBootstrapper(testClass);
			if (clazz == null) {
				clazz = resolveDefaultTestContextBootstrapper(testClass);
			}
			logger.trace(LogMessage.format("Instantiating TestContextBootstrapper for test class [%s] from class [%s]",
					testClass.getName(), clazz.getName()));
			TestContextBootstrapper testContextBootstrapper =
					BeanUtils.instantiateClass(clazz, TestContextBootstrapper.class);
			testContextBootstrapper.setBootstrapContext(bootstrapContext);
			return testContextBootstrapper;
		}
		catch (IllegalStateException ex) {
			throw ex;
		}
		catch (Throwable ex) {
			throw new IllegalStateException("""
					Could not load TestContextBootstrapper [%s]. Specify @BootstrapWith's 'value' \
					attribute or make the default bootstrapper class available.""".formatted(clazz), ex);
		}
	}

	@Nullable
	private static Class<?> resolveExplicitTestContextBootstrapper(Class<?> testClass) {
		Set<BootstrapWith> annotations = new LinkedHashSet<>();
		AnnotationDescriptor<BootstrapWith> descriptor =
				TestContextAnnotationUtils.findAnnotationDescriptor(testClass, BootstrapWith.class);
		while (descriptor != null) {
			annotations.addAll(descriptor.findAllLocalMergedAnnotations());
			descriptor = descriptor.next();
		}

		if (annotations.isEmpty()) {
			return null;
		}
		if (annotations.size() == 1) {
			return annotations.iterator().next().value();
		}

		// Allow directly-present annotation to override annotations that are meta-present.
		BootstrapWith bootstrapWith = testClass.getDeclaredAnnotation(BootstrapWith.class);
		if (bootstrapWith != null) {
			return bootstrapWith.value();
		}

		throw new IllegalStateException(String.format(
				"Configuration error: found multiple declarations of @BootstrapWith for test class [%s]: %s",
				testClass.getName(), annotations));
	}

	private static Class<?> resolveDefaultTestContextBootstrapper(Class<?> testClass) throws Exception {
		boolean webApp = TestContextAnnotationUtils.hasAnnotation(testClass, webAppConfigurationClass);
		String bootstrapperClassName = (webApp ? DEFAULT_WEB_TEST_CONTEXT_BOOTSTRAPPER_CLASS_NAME :
				DEFAULT_TEST_CONTEXT_BOOTSTRAPPER_CLASS_NAME);
		return ClassUtils.forName(bootstrapperClassName, BootstrapUtils.class.getClassLoader());
	}

	@SuppressWarnings("unchecked")
	private static Class<? extends Annotation> loadWebAppConfigurationClass() {
		try {
			return (Class<? extends Annotation>) ClassUtils.forName(WEB_APP_CONFIGURATION_ANNOTATION_CLASS_NAME,
				BootstrapUtils.class.getClassLoader());
		}
		catch (ClassNotFoundException | LinkageError ex) {
			throw new IllegalStateException(
				"Failed to load class for @" + WEB_APP_CONFIGURATION_ANNOTATION_CLASS_NAME, ex);
		}
	}

}


text:
define([
  'core/agent', 'core/dom', 'core/range', 'core/async', 'editing/Style'
], function (agent, dom, range, async, Style) {
  /**
   * Editor
   */
  var Editor = function () {
    // save current range
    this.saveRange = function ($editable) {
      $editable.data('range', range.create());
    };

    // restore lately range
    this.restoreRange = function ($editable) {
      var rng = $editable.data('range');
      if (rng) { rng.select(); }
    };

    //currentStyle
    var style = new Style();
    this.currentStyle = function (elTarget) {
      var rng = range.create();
      return rng.isOnEditable() && style.current(rng, elTarget);
    };

    this.tab = function ($editable) {
      recordUndo($editable);
      var rng = range.create();
      var sNbsp = new Array($editable.data('tabsize') + 1).join(' ');
      rng.insertNode($('' + sNbsp + '')[0]);
      var $tab = $('#noteTab').removeAttr('id');
      rng = range.create($tab[0], 1);
      rng.select();
      dom.remove($tab[0]);
    };

    // undo
    this.undo = function ($editable) {
      $editable.data('NoteHistory').undo($editable);
    };

    // redo
    this.redo = function ($editable) {
      $editable.data('NoteHistory').redo($editable);
    };

    // recordUndo
    var recordUndo = this.recordUndo = function ($editable) {
      $editable.data('NoteHistory').recordUndo($editable);
    };

    /* jshint ignore:start */
    // native commands(with execCommand), generate function for execCommand
    var aCmd = ['bold', 'italic', 'underline', 'strikethrough',
                'justifyLeft', 'justifyCenter', 'justifyRight', 'justifyFull',
                'insertOrderedList', 'insertUnorderedList',
                'indent', 'outdent', 'formatBlock', 'removeFormat',
                'backColor', 'foreColor', 'insertHorizontalRule'];

    for (var idx = 0, len = aCmd.length; idx < len; idx ++) {
      this[aCmd[idx]] = (function (sCmd) {
        return function ($editable, sValue) {
          recordUndo($editable);
          document.execCommand(sCmd, false, sValue);
        };
      })(aCmd[idx]);
    }
    /* jshint ignore:end */

    this.insertImage = function ($editable, sUrl) {
      async.loadImage(sUrl).done(function (image) {
        recordUndo($editable);
        var $image = $('').attr('src', sUrl);
        $image.css('width', Math.min($editable.width(), image.width));
        range.create().insertNode($image[0]);
      }).fail(function () {
        var callbacks = $editable.data('callbacks');
        if (callbacks.onImageUploadError) {
          callbacks.onImageUploadError();
        }
      });
    };

    this.insertVideo = function ($editable, sUrl) {
      // video url patterns(youtube, instagram, vimeo, dailymotion)
      var ytRegExp = /^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|\&v=)([^#\&\?]*).*/;
      var ytMatch = sUrl.match(ytRegExp);

      var igRegExp = /\/\/instagram.com\/p\/(.[a-zA-Z0-9]*)/;
      var igMatch = sUrl.match(igRegExp);

      var vRegExp = /\/\/vine.co\/v\/(.[a-zA-Z0-9]*)/;
      var vMatch = sUrl.match(vRegExp);

      var vimRegExp = /\/\/(player.)?vimeo.com\/([a-z]*\/)*([0-9]{6,11})[?]?.*/;
      var vimMatch = sUrl.match(vimRegExp);

      var dmRegExp = /.+dailymotion.com\/(video|hub)\/([^_]+)[^#]*(#video=([^_&]+))?/;
      var dmMatch = sUrl.match(dmRegExp);

      var $video;
      if (ytMatch && ytMatch[2].length === 11) {
        var youtubeId = ytMatch[2];
        $video = $('')
          .attr('src', 'http://www.youtube.com/embed/' + youtubeId)
          .attr('width', '640').attr('height', '360');
      } else if (igMatch && igMatch[0].length > 0) {
        $video = $('')
          .attr('src', igMatch[0] + '/embed/')
          .attr('width', '612').attr('height', '710')
          .attr('scrolling', 'no')
          .attr('allowtransparency', 'true');
      } else if (vMatch && vMatch[0].length > 0) {
        $video = $('')
          .attr('src', vMatch[0] + '/embed/simple')
          .attr('width', '600').attr('height', '600')
          .attr('class', 'vine-embed');
      } else if (vimMatch && vimMatch[3].length > 0) {
        $video = $('')
          .attr('src', '//player.vimeo.com/video/' + vimMatch[3])
          .attr('width', '640').attr('height', '360');
      } else if (dmMatch && dmMatch[2].length > 0) {
        $video = $('')
          .attr('src', 'http://www.dailymotion.com/embed/video/' + dmMatch[2])
          .attr('width', '640').attr('height', '360');
      } else {
        // this is not a known video link. Now what, Cat? Now what?
      }

      if ($video) {
        $video.attr('frameborder', 0);
        range.create().insertNode($video[0]);
      }
    };

    this.formatBlock = function ($editable, sValue) {
      recordUndo($editable);
      sValue = agent.bMSIE ? '<' + sValue + '>' : sValue;
      document.execCommand('FormatBlock', false, sValue);
    };

    this.fontSize = function ($editable, sValue) {
      recordUndo($editable);
      document.execCommand('fontSize', false, 3);
      if (agent.bFF) {
        // firefox:  to , buggy
        $editable.find('font[size=3]').removeAttr('size').css('font-size', sValue + 'px');
      } else {
        // chrome:  to
        $editable.find('span').filter(function () {
          return this.style.fontSize === 'medium';
        }).css('font-size', sValue + 'px');
      }
    };

    this.lineHeight = function ($editable, sValue) {
      recordUndo($editable);
      style.stylePara(range.create(), {lineHeight: sValue});
    };

    this.unlink = function ($editable) {
      var rng = range.create();
      if (rng.isOnAnchor()) {
        recordUndo($editable);
        var elAnchor = dom.ancestor(rng.sc, dom.isAnchor);
        rng = range.create(elAnchor, 0, elAnchor, 1);
        rng.select();
        document.execCommand('unlink');
      }
    };

    this.setLinkDialog = function ($editable, fnShowDialog) {
      var rng = range.create();
      if (rng.isOnAnchor()) {
        var elAnchor = dom.ancestor(rng.sc, dom.isAnchor);
        rng = range.create(elAnchor, 0, elAnchor, 1);
      }
      fnShowDialog({
        range: rng,
        text: rng.toString(),
        url: rng.isOnAnchor() ? dom.ancestor(rng.sc, dom.isAnchor).href : ''
      }, function (sLinkUrl) {
        rng.select();
        recordUndo($editable);

        var sLinkUrlWithProtocol;
        if (sLinkUrl.indexOf('@') !== -1) { // email address
          sLinkUrlWithProtocol = sLinkUrl.indexOf(':') !== -1 ? sLinkUrl : 'mailto:' + sLinkUrl;
        } else { // normal address
          sLinkUrlWithProtocol = sLinkUrl.indexOf('://') !== -1 ? sLinkUrl : 'http://' + sLinkUrl;
        }

        //IE: createLink when range collapsed.
        if (agent.bMSIE && rng.isCollapsed()) {
          rng.insertNode($('' + sLinkUrl + '')[0]);
          var $anchor = $('#linkAnchor').removeAttr('id')
                                          .attr('href', sLinkUrlWithProtocol);
          rng = range.create($anchor[0], 0, $anchor[0], 1);
          rng.select();
        } else {
          document.execCommand('createlink', false, sLinkUrlWithProtocol);
        }
      });
    };

    this.setVideoDialog = function ($editable, fnShowDialog) {
      var rng = range.create();
      var editor = this;

      if (rng.isOnAnchor()) {
        var elAnchor = dom.ancestor(rng.sc, dom.isAnchor);
        rng = range.create(elAnchor, 0, elAnchor, 1);
      }

      fnShowDialog({
        range: rng,
        text: rng.toString()
      }, function (sLinkUrl) {
        rng.select();
        recordUndo($editable);
        editor.insertVideo($editable, sLinkUrl);
      });
    };

    this.color = function ($editable, sObjColor) {
      var oColor = JSON.parse(sObjColor);
      var foreColor = oColor.foreColor, backColor = oColor.backColor;

      recordUndo($editable);
      if (foreColor) { document.execCommand('foreColor', false, foreColor); }
      if (backColor) { document.execCommand('backColor', false, backColor); }
    };

    this.insertTable = function ($editable, sDim) {
      recordUndo($editable);
      var aDim = sDim.split('x');
      var nCol = aDim[0], nRow = aDim[1];

      var aTD = [], sTD;
      var sWhitespace = agent.bMSIE ? ' ' : '
';
      for (var idxCol = 0; idxCol < nCol; idxCol++) {
        aTD.push('' + sWhitespace + '	');
      }
      sTD = aTD.join('');

      var aTR = [], sTR;
      for (var idxRow = 0; idxRow < nRow; idxRow++) {
        aTR.push('
' + sTD + '
');
      }
      sTR = aTR.join('');
      var sTable = '
' + sTR + '
';
      range.create().insertNode($(sTable)[0]);
    };

    this.floatMe = function ($editable, sValue, elTarget) {
      recordUndo($editable);
      elTarget.style.cssFloat = sValue;
    };

    this.resize = function ($editable, sValue, elTarget) {
      recordUndo($editable);
      elTarget.style.width = $editable.width() * sValue + 'px';
      elTarget.style.height = '';
    };

    this.resizeTo = function (pos, $target) {
      var newRatio = pos.y / pos.x;
      var ratio = $target.data('ratio');

      $target.css({
        width: ratio > newRatio ? pos.x : pos.y / ratio,
        height: ratio > newRatio ? pos.x * ratio : pos.y
      });
    };
  };

  return Editor;
});


text:
"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports["default"] = mayHaveAccessibleLabel;

var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));

var _arrayIncludes = _interopRequireDefault(require("array-includes"));

var _jsxAstUtils = require("jsx-ast-utils");

/**
 * Returns true if a labelling element is found or if it cannot determine if
 * a label is present because of expression containers or spread attributes.
 * A false return value means that the node definitely does not have a label,
 * but a true return return value means that the node may or may not have a
 * label.
 *
 *
 */
function hasLabellingProp(openingElement) {
  var additionalLabellingProps = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
  var labellingProps = ['alt', // Assume alt is used correctly on an image
  'aria-label', 'aria-labelledby'].concat((0, _toConsumableArray2["default"])(additionalLabellingProps));
  return openingElement.attributes.some(function (attribute) {
    // We must assume that a spread value contains a labelling prop.
    if (attribute.type !== 'JSXAttribute') {
      return true;
    } // Attribute matches.

    if ((0, _arrayIncludes["default"])(labellingProps, (0, _jsxAstUtils.propName)(attribute)) && !!(0, _jsxAstUtils.getPropValue)(attribute)) {
      return true;
    }

    return false;
  });
}

function mayHaveAccessibleLabel(root) {
  var maxDepth = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1;
  var additionalLabellingProps = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [];

  function checkElement(node, depth) {
    // Bail when maxDepth is exceeded.
    if (depth > maxDepth) {
      return false;
    } // Check for literal text.

    if (node.type === 'Literal' && !!node.value) {
      return true;
    } // Assume an expression container renders a label. It is the best we can
    // do in this case.

    if (node.type === 'JSXExpressionContainer') {
      return true;
    } // Check for JSXText.
    // $FlowFixMe Remove after updating ast-types-flow

    if (node.type === 'JSXText' && !!node.value) {
      return true;
    } // Check for labelling props.

    if (node.openingElement
    /* $FlowFixMe */
    && hasLabellingProp(node.openingElement, additionalLabellingProps)) {
      return true;
    } // Recurse into the child element nodes.

    if (node.children) {
      /* $FlowFixMe */
      for (var i = 0; i < node.children.length; i += 1) {
        /* $FlowFixMe */
        if (checkElement(node.children[i], depth + 1)) {
          return true;
        }
      }
    }

    return false;
  }

  return checkElement(root, 0);
}

module.exports = exports.default;


text:
package sbt
package appmacro

	import scala.reflect._
	import macros._
	import scala.tools.nsc.Global
	import ContextUtil.{DynamicDependencyError, DynamicReferenceError}

object ContextUtil {
	final val DynamicDependencyError = "Illegal dynamic dependency"
	final val DynamicReferenceError = "Illegal dynamic reference"

	/** Constructs an object with utility methods for operating in the provided macro context `c`.
	* Callers should explicitly specify the type parameter as `c.type` in order to preserve the path dependent types. */
	def apply[C <: Context with Singleton](c: C): ContextUtil[C] = new ContextUtil(c)

	/** Helper for implementing a no-argument macro that is introduced via an implicit.
	* This method removes the implicit conversion and evaluates the function `f` on the target of the conversion.
	*
	* Given `myImplicitConversion(someValue).extensionMethod`, where `extensionMethod` is a macro that uses this
	* method, the result of this method is `f(<Tree of someValue>)`. */
	def selectMacroImpl[T: c.WeakTypeTag, S: c.WeakTypeTag](c: Context)(f: c.Expr[S] => c.Expr[T]): c.Expr[T] =
	{
			import c.universe._
		c.macroApplication match {
			case Select(Apply(_, t :: Nil), _) => f( c.Expr[S](t) )
			case x => unexpectedTree(x)
		}
	}

	def unexpectedTree[C <: Context](tree: C#Tree): Nothing = error("Unexpected macro application tree (" + tree.getClass + "): " + tree)
}

/** Utility methods for macros.  Several methods assume that the context's universe is a full compiler (`scala.tools.nsc.Global`).
* This is not thread safe due to the underlying Context and related data structures not being thread safe.
* Use `ContextUtil[c.type](c)` to construct. */
final class ContextUtil[C <: Context](val ctx: C)
{
		import ctx.universe.{Apply=>ApplyTree,_}

	lazy val alistType = ctx.typeOf[AList[KList]]
	lazy val alist: Symbol = alistType.typeSymbol.companionSymbol
	lazy val alistTC: Type = alistType.typeConstructor

	/** Modifiers for a local val.*/
	lazy val localModifiers = Modifiers(NoFlags)

	def getPos(sym: Symbol) = if(sym eq null) NoPosition else sym.pos

	def atypeOf[T](implicit att: WeakTypeTag[T]): Type = att.tpe

	/** Constructs a unique term name with the given prefix within this Context.
	* (The current implementation uses Context.fresh, which increments*/
	def freshTermName(prefix: String) = newTermName(ctx.fresh("$" + prefix))

	/** Constructs a new, local ValDef with the given Type, a unique name,
	* the same position as `sym`, and an empty implementation (no rhs). */
	def freshValDef(tpe: Type, sym: Symbol): ValDef =
	{
		val vd = localValDef(TypeTree(tpe), EmptyTree)
		vd setPos getPos(sym)
		vd
	}

	/* Tests whether a Tree is a Select on `methodName`. */
	def isWrapper(methodName: String): Tree => Boolean = {
		case Select(_, nme) => nme.decoded == methodName
		case _ => false
	}

	lazy val parameterModifiers = Modifiers(Flag.PARAM)

	/** Collects all definitions in the tree for use in checkReferences.
	* This excludes definitions in wrapped expressions because checkReferences won't allow nested dereferencing anyway. */
	def collectDefs(tree: Tree, isWrapper: Tree => Boolean): collection.Set[Symbol] =
	{
		val defs = new collection.mutable.HashSet[Symbol]
		// adds the symbols for all non-Ident subtrees to `defs`.
		val process = new Traverser {
			override def traverse(t: Tree) = t match {
				case _: Ident => ()
				case ApplyTree(TypeApply(fun, tpe :: Nil), qual :: Nil) if isWrapper(fun) => ()
				case tree =>
					if(tree.symbol ne null) defs += tree.symbol;
					super.traverse(tree)
			}
		}
		process.traverse(tree)
		defs
	}

	/** A reference is illegal if it is to an M instance defined within the scope of the macro call.
	* As an approximation, disallow referenced to any local definitions `defs`. */
	def illegalReference(defs: collection.Set[Symbol], sym: Symbol): Boolean =
		sym != null && sym != NoSymbol && defs.contains(sym)

	/** A function that checks the provided tree for illegal references to M instances defined in the
	*  expression passed to the macro and for illegal dereferencing of M instances. */
	def checkReferences(defs: collection.Set[Symbol], isWrapper: Tree => Boolean): Tree => Unit = {
		case s @ ApplyTree(TypeApply(fun, tpe :: Nil), qual :: Nil) => if(isWrapper(fun)) ctx.error(s.pos, DynamicDependencyError)
		case id @ Ident(name) if illegalReference(defs, id.symbol) => ctx.error(id.pos, DynamicReferenceError + ": " + name)
		case _ => ()
	}

	/** Constructs a ValDef with a parameter modifier, a unique name, with the provided Type and with an empty rhs. */
	def freshMethodParameter(tpe: Type): ValDef =
		ValDef(parameterModifiers, freshTermName("p"), TypeTree(tpe), EmptyTree)

	/** Constructs a ValDef with local modifiers and a unique name. */
	def localValDef(tpt: Tree, rhs: Tree): ValDef =
		ValDef(localModifiers, freshTermName("q"), tpt, rhs)

	/** Constructs a tuple value of the right TupleN type from the provided inputs.*/
	def mkTuple(args: List[Tree]): Tree =
	{
		val global: Global = ctx.universe.asInstanceOf[Global]
		global.gen.mkTuple(args.asInstanceOf[List[global.Tree]]).asInstanceOf[ctx.universe.Tree]
	}

	/** Creates a new, synthetic type variable with the specified `owner`. */
	def newTypeVariable(owner: Symbol, prefix: String = "T0"): TypeSymbol =
	{
		val global: Global = ctx.universe.asInstanceOf[Global]
		owner.asInstanceOf[global.Symbol].newSyntheticTypeParam(prefix, 0L).asInstanceOf[ctx.universe.TypeSymbol]
	}
	/** The type representing the type constructor `[X] X` */
	lazy val idTC: Type =
	{
		val tvar = newTypeVariable(NoSymbol)
		polyType(tvar :: Nil, refVar(tvar))
	}
	/** A Type that references the given type variable. */
	def refVar(variable: TypeSymbol): Type = variable.toTypeConstructor
	/** Constructs a new, synthetic type variable that is a type constructor. For example, in type Y[L[x]], L is such a type variable. */
	def newTCVariable(owner: Symbol): TypeSymbol =
	{
		val tc = newTypeVariable(owner)
		val arg = newTypeVariable(tc, "x")
		tc.setTypeSignature(PolyType(arg :: Nil, emptyTypeBounds))
		tc
	}
	/** >: Nothing <: Any */
	def emptyTypeBounds: TypeBounds = TypeBounds(definitions.NothingClass.toType, definitions.AnyClass.toType)

	/** Create a Tree that references the `val` represented by `vd`. */
	def refVal(vd: ValDef): Tree =
	{
		val t = Ident(vd.name)
		assert(vd.tpt.tpe != null, "val type is null: " + vd + ", tpt: " + vd.tpt.tpe)
		t.setType(vd.tpt.tpe)
		t
	}

	/** Returns the Symbol that references the statically accessible singleton `i`. */
	def singleton[T <: AnyRef with Singleton](i: T)(implicit it: ctx.TypeTag[i.type]): Symbol =
		it.tpe match {
			case SingleType(_, sym) if !sym.isFreeTerm && sym.isStatic => sym
			case x => error("Instance must be static (was " + x + ").")
		}

	/** Returns the symbol for the non-private method named `name` for the class/module `obj`. */
	def method(obj: Symbol, name: String): Symbol = {
		val global: Global = ctx.universe.asInstanceOf[Global]
		val ts: Type = obj.typeSignature
		val m: global.Symbol = ts.asInstanceOf[global.Type].nonPrivateMember(global.newTermName(name))
		m.asInstanceOf[Symbol]
	}

	/** Returns a Type representing the type constructor tcp.<name>.  For example, given
	*  `object Demo { type M[x] = List[x] }`, the call `extractTC(Demo, "M")` will return a type representing
	* the type constructor `[x] List[x]`.
	**/
	def extractTC(tcp: AnyRef with Singleton, name: String)(implicit it: ctx.TypeTag[tcp.type]): ctx.Type =
	{
		val global: Global = ctx.universe.asInstanceOf[Global]
		val itTpe = it.tpe.asInstanceOf[global.Type]
		val m = itTpe.nonPrivateMember(global.newTypeName(name))
		val tc = itTpe.memberInfo(m).asInstanceOf[ctx.universe.Type]
		assert(tc != NoType && tc.takesTypeArgs, "Invalid type constructor: " + tc)
		tc
	}

	/** Substitutes wrappers in tree `t` with the result of `subWrapper`.
	* A wrapper is a Tree of the form `f[T](v)` for which isWrapper(<Tree of f>) returns true.
	* Typically, `f` is a `Select` or `Ident`.
	* The wrapper is replaced with the result of `subWrapper(<Type of T>, <Tree of v>)` */
	def transformWrappers(t: Tree, isWrapper: Tree => Boolean, subWrapper: (Type, Tree) => Tree): Tree =
	{
		// the main tree transformer that replaces calls to InputWrapper.wrap(x) with
		//  plain Idents that reference the actual input value
		object appTransformer extends Transformer
		{
			override def transform(tree: Tree): Tree =
				tree match
				{
					case ApplyTree(TypeApply(fun, targ :: Nil), qual :: Nil) if isWrapper(fun) =>
						assert(qual.tpe != null, "Internal error: null type for wrapped tree with " + qual.getClass + "\n\t" + qual + "\n in " + t)
						subWrapper(targ.tpe, qual)
					case _ => super.transform(tree)
				}
		}

		appTransformer.transform(t)
	}
}


text:
using Flood.GUI.Controls;

namespace Flood.GUI.ControlInternal
{
    /// <summary>
    /// Header of CollapsibleCategory.
    /// </summary>
    public class CategoryHeaderButton : Button
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="CategoryHeaderButton"/> class.
        /// </summary>
        /// <param name="parent">Parent control.</param>
        public CategoryHeaderButton(Control parent)
            : base(parent)
        {
            ShouldDrawBackground = false;
            IsToggle = true;
            Alignment = Pos.Center;
            TextPadding = new Padding(3, 0, 3, 0);
        }

        /// <summary>
        /// Updates control colors.
        /// </summary>
        public override void UpdateColors()
        {
            if (IsDepressed || ToggleState)
                TextColor = Skin.Colors.Category.Header_Closed;
            else
                TextColor = Skin.Colors.Category.Header;
        }
    }
}


text:
local folderOfThisFile = (...):match("(.-)[^%/%.]+$")

path = {}
for i in string.gmatch(folderOfThisFile, '.[^.]*') do
    table.insert(path, i)
end
table.remove(path, #path)
table.remove(path, #path)
folderOfThisFile = table.concat(path, ".")

local ComponentAdded = require(folderOfThisFile .. '.namespace').class("ComponentAdded")

function ComponentAdded:initialize(entity, component)
    self.entity = entity
    self.component = component
end

return ComponentAdded


text:
.class public Lcom/baidu/themeanimation/net/sourceforge/jeval/function/math/Min;
.super Ljava/lang/Object;
.source "Min.java"

# interfaces
.implements Lcom/baidu/themeanimation/net/sourceforge/jeval/function/Function;

# direct methods
.method public constructor <init>()V
    .locals 0

    .prologue
    .line 34
    invoke-direct/range {p0 .. p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method

# virtual methods
.method public execute(Lcom/baidu/themeanimation/net/sourceforge/jeval/Evaluator;Ljava/lang/String;)Lcom/baidu/themeanimation/net/sourceforge/jeval/function/FunctionResult;
    .locals 10
    .parameter "evaluator"
    .parameter "arguments"
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Lcom/baidu/themeanimation/net/sourceforge/jeval/function/FunctionException;
        }
    .end annotation

    .prologue
    const/4 v9, 0x0

    .line 61
    const/4 v6, 0x0

    .line 63
    .local v6, result:Ljava/lang/Double;
    const/16 v7, 0x2c

    invoke-static {p2, v7}, Lcom/baidu/themeanimation/net/sourceforge/jeval/function/FunctionHelper;->getDoubles(Ljava/lang/String;C)Ljava/util/ArrayList;

    move-result-object v5

    .line 66
    .local v5, numbers:Ljava/util/ArrayList;
    invoke-virtual {v5}, Ljava/util/ArrayList;->size()I

    move-result v7

    const/4 v8, 0x2

    if-eq v7, v8, :cond_0

    .line 67
    new-instance v7, Lcom/baidu/themeanimation/net/sourceforge/jeval/function/FunctionException;

    const-string v8, "Two numeric arguments are required."

    invoke-direct {v7, v8}, Lcom/baidu/themeanimation/net/sourceforge/jeval/function/FunctionException;-><init>(Ljava/lang/String;)V

    throw v7

    .line 71
    :cond_0
    const/4 v7, 0x0

    :try_start_0
    invoke-virtual {v5, v7}, Ljava/util/ArrayList;->get(I)Ljava/lang/Object;

    move-result-object v7

    check-cast v7, Ljava/lang/Double;

    invoke-virtual {v7}, Ljava/lang/Double;->doubleValue()D

    move-result-wide v0

    .line 72
    .local v0, argumentOne:D
    const/4 v7, 0x1

    invoke-virtual {v5, v7}, Ljava/util/ArrayList;->get(I)Ljava/lang/Object;

    move-result-object v7

    check-cast v7, Ljava/lang/Double;

    invoke-virtual {v7}, Ljava/lang/Double;->doubleValue()D

    move-result-wide v2

    .line 73
    .local v2, argumentTwo:D
    new-instance v6, Ljava/lang/Double;

    .end local v6           #result:Ljava/lang/Double;
    invoke-static {v0, v1, v2, v3}, Ljava/lang/Math;->min(DD)D

    move-result-wide v7

    invoke-direct {v6, v7, v8}, Ljava/lang/Double;-><init>(D)V
    :try_end_0
    .catch Ljava/lang/Exception; {:try_start_0 .. :try_end_0} :catch_0

    .line 78
    .restart local v6       #result:Ljava/lang/Double;
    new-instance v7, Lcom/baidu/themeanimation/net/sourceforge/jeval/function/FunctionResult;

    invoke-virtual {v6}, Ljava/lang/Double;->toString()Ljava/lang/String;

    move-result-object v8

    invoke-direct {v7, v8, v9}, Lcom/baidu/themeanimation/net/sourceforge/jeval/function/FunctionResult;-><init>(Ljava/lang/String;I)V

    return-object v7

    .line 74
    .end local v0           #argumentOne:D
    .end local v2           #argumentTwo:D
    .end local v6           #result:Ljava/lang/Double;
    :catch_0
    move-exception v4

    .line 75
    .local v4, e:Ljava/lang/Exception;
    new-instance v7, Lcom/baidu/themeanimation/net/sourceforge/jeval/function/FunctionException;

    const-string v8, "Two numeric arguments are required."

    invoke-direct {v7, v8, v4}, Lcom/baidu/themeanimation/net/sourceforge/jeval/function/FunctionException;-><init>(Ljava/lang/String;Ljava/lang/Exception;)V

    throw v7
.end method

.method public getName()Ljava/lang/String;
    .locals 1

    .prologue
    .line 41
    const-string v0, "min"

    return-object v0
.end method


text:
using CellSpacePartitionLib.Tests;
using Microsoft.Xna.Framework;
using NUnit.Framework;
using Shouldly;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CellSpacePartitionLib.Tests
{
	[TestFixture]
	public class ConstructionTests
	{
		[TestCase(0, 0)]
		[TestCase(-100, -100)]
		[TestCase(100, 100)]
		public void XPosition(float x, float expectedValue)
		{
			var partition = new TestCellSpacePartition(new Vector2(x, 0), 0, 0, 0);
			partition.CellSpace.X.ShouldBe(expectedValue);
		}

		[TestCase(0, 0)]
		[TestCase(-100, -100)]
		[TestCase(100, 100)]
		public void YPosition(float y, float expectedValue)
		{
			var partition = new TestCellSpacePartition(new Vector2(0, y), 0, 0, 0);
			partition.CellSpace.Y.ShouldBe(expectedValue);
		}

		[TestCase(0, 0, 0)]
		[TestCase(10, 10, 100)]
		[TestCase(10, 20, 200)]
		public void TestWidth(int cellSize, int numColumns, float expectedValue)
		{
			var partition = new TestCellSpacePartition(new Vector2(0, 0), cellSize, numColumns, 0);
			partition.CellSpace.Width.ShouldBe(expectedValue);
		}

		[TestCase(0, 0, 0)]
		[TestCase(10, 10, 100)]
		[TestCase(10, 20, 200)]
		public void TestHeight(int cellSize, int numRows, float expectedValue)
		{
			var partition = new TestCellSpacePartition(new Vector2(0, 0), cellSize, 0, numRows);
			partition.CellSpace.Height.ShouldBe(expectedValue);
		}
	}
}


text:
<?php

/*
 * This file is part of Mongator.
 *
 * (c) Pablo Díez <pablodip@gmail.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Mongator\Tests\Type;

use Mongator\Type\BinDataType;

class BinDataTypeTest extends TestCase
{
    public function testToMongo()
    {
        $type = new BinDataType();
        $this->assertEquals(new \MongoBinData('123', \MongoBinData::BYTE_ARRAY), $type->toMongo('123'));
        $this->assertEquals(new \MongoBinData(file_get_contents(__FILE__), \MongoBinData::BYTE_ARRAY), $type->toMongo(__FILE__));
    }

    public function testToPHP()
    {
        $type = new BinDataType();
        $this->assertSame('123', $type->toPHP(new \MongoBinData('123', \MongoBinData::BYTE_ARRAY)));
    }

    public function testToMongoInString()
    {
        $type = new BinDataType();
        $function = $this->getTypeFunction($type->toMongoInString());

        $this->assertEquals(new \MongoBinData('123', \MongoBinData::BYTE_ARRAY), $function('123'));
        $this->assertEquals(new \MongoBinData(file_get_contents(__FILE__), \MongoBinData::BYTE_ARRAY), $function(__FILE__));
    }

    public function testToPHPInString()
    {
        $type = new BinDataType();
        $function = $this->getTypeFunction($type->toPHPInString());

        $this->assertSame('123', $function(new \MongoBinData('123', \MongoBinData::BYTE_ARRAY)));
    }
}


text:
def run(whatweb, pluginname):
    whatweb.recog_from_file(pluginname, "Admin_Cy/Script/xselect.js", "Dsy")


text:
import { readFileSync } from 'fs';
import { dirname } from 'path';

const getFileContent = (module, filename) => {
  module.exports = readFileSync(filename, 'utf8');
};

const getFilePath = (module, filename) => {
  module.exports = filename;
};

window.require.extensions['.html'] = getFileContent;

['.png', '.jpg', '.gif'].forEach(extension => {
  window.require.extensions[extension] = getFilePath;
});


text:
<?php

/**
 * This is the model class for table "{{status_publish}}".
 *
 * The followings are the available columns in table '{{status_publish}}':
 * @property integer $status_publish_id
 * @property string $nama_status
 *
 * The followings are the available model relations:
 * @property Berita[] $beritas
 * @property Post[] $posts
 */
class StatusPublish extends CActiveRecord
{
	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return '{{status_publish}}';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('nama_status', 'required'),
			array('nama_status', 'length', 'max'=>50),
			// The following rule is used by search().
			// @todo Please remove those attributes that should not be searched.
			array('status_publish_id, nama_status', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
			'beritas' => array(self::HAS_MANY, 'Berita', 'is_publish'),
			'posts' => array(self::HAS_MANY, 'Post', 'is_publish'),
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'status_publish_id' => 'Status Publish',
			'nama_status' => 'Nama Status',
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 *
	 * Typical usecase:
	 * - Initialize the model fields with values from filter form.
	 * - Execute this method to get CActiveDataProvider instance which will filter
	 * models according to data in model fields.
	 * - Pass data provider to CGridView, CListView or any similar widget.
	 *
	 * @return CActiveDataProvider the data provider that can return the models
	 * based on the search/filter conditions.
	 */
	public function search()
	{
		// @todo Please modify the following code to remove attributes that should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('status_publish_id',$this->status_publish_id);
		$criteria->compare('nama_status',$this->nama_status,true);

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
		));
	}

	/**
	 * Returns the static model of the specified AR class.
	 * Please note that you should have this exact method in all your CActiveRecord descendants!
	 * @param string $className active record class name.
	 * @return StatusPublish the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}
}


text:
Mexico (``mx``)
===============

Forms
-----

.. automodule:: localflavor.mx.forms
    :members:

Models
------

.. automodule:: localflavor.mx.models
    :members:

Data
----

.. autodata:: localflavor.mx.mx_states.STATE_CHOICES


text:
package com.github.agourlay.cornichon.steps.wrapped

import com.github.agourlay.cornichon.core.{ FailedStep, RunState, SimpleWrapperStep, Step }

import scala.concurrent.duration.Duration

// `Resources` that are released at the end of the `Scenario`
case class ScenarioResourceStep(title: String, acquire: Step, release: Step) extends SimpleWrapperStep {
  override def setTitle(newTitle: String): Step = copy(title = newTitle)
  override val nestedToRun = AttachAsStep(s"$title - acquire step", _ => acquire :: Nil) :: Nil
  override val indentLog = false

  def onNestedError(failedStep: FailedStep, resultRunState: RunState, runState: RunState, executionTime: Duration): (RunState, FailedStep) =
    (runState.mergeNested(resultRunState), failedStep)

  def onNestedSuccess(resultRunState: RunState, runState: RunState, executionTime: Duration): RunState =
    runState.mergeNested(resultRunState).registerCleanupStep(AttachAsStep(s"$title - release step", _ => release :: Nil))
}


text:
package qora.web;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.mapdb.DB;

import utils.ByteArrayUtils;
import database.DBListValueMap;
import database.DBMap;
import database.DBSet;

public class OrphanNameStorageHelperMap extends DBListValueMap<String, byte[], List<byte[]>> {

	private Map<Integer, Integer> observableData = new HashMap<Integer, Integer>();

	public OrphanNameStorageHelperMap(DBSet databaseSet, DB database) {
		super(databaseSet, database);
	}

	public OrphanNameStorageHelperMap(DBMap<String, List<byte[]>> parent) {
		super(parent);
	}

	@Override
	protected Map<String, List<byte[]>> getMap(DB database) {
		return database.createTreeMap("OrphanNameStorageHelperMap").makeOrGet();
	}

	@Override
	protected Map<String, List<byte[]>> getMemoryMap() {
		return new HashMap<>();
	}

	@Override
	protected Map<Integer, Integer> getObservableData() {
		return this.observableData;
	}

	@Override
	protected void createIndexes(DB database) {
	}

	@Override
	protected List<byte[]> getDefaultValue() {
		return null;
	}

	@Override
	protected List<byte[]> newListValue() {
		return new ArrayList<byte[]>();
	}

	public void add(String name, byte[] signatureOfTx) {
		// Add signature to list if list doesn't already contain it
		this.listAdd(name, signatureOfTx, (list, sig) -> !ByteArrayUtils.contains(list, sig), (list, sig) -> list.add(sig));
	}

	public void remove(String name, byte[] signatureOfTx) {
		// Always remove signature from list
		this.listRemove(name, signatureOfTx, (list, sig) -> true, (list, sig) -> ByteArrayUtils.remove(list, sig));
	}
}


text:
class AddWebsiteToSponsor < ActiveRecord::Migration
  def change
    add_column :sponsors, :website, :string
  end
end


text:
import os
from setuptools import setup, find_packages

SHORT_DESC = """A reusable Django application for viewing and debugging
all the data that has been pushed into Haystack"""

REQUIREMENTS = [
    'Django>=1.2.0',
    'django-haystack>=1.2.0',
    'django-classy-tags>=0.3.4.1',
]

TROVE_CLASSIFIERS = [
    'Development Status :: 3 - Alpha',
    'Environment :: Web Environment',
    'Framework :: Django',
    'Intended Audience :: Developers',
    'Operating System :: OS Independent',
    'Programming Language :: Python :: 2.6',
    'Programming Language :: Python :: 2.7',
    'Natural Language :: English',
    'Topic :: Internet :: WWW/HTTP :: Site Management',
    'Topic :: Database :: Front-Ends',
    'License :: OSI Approved :: BSD License',
]

PACKAGES = find_packages()

setup(
    name='django-haystackbrowser',
    version='0.6.0',
    description=SHORT_DESC,
    author='Keryn Knight',
    author_email='python-package@kerynknight.com',
    license="BSD License",
    keywords="django",
    long_description=open(os.path.join(os.path.dirname(__file__), 'README.rst')).read(),
    url='https://github.com/kezabelle/django-haystackbrowser/tree/master',
    packages=PACKAGES,
    install_requires=REQUIREMENTS,
    classifiers=TROVE_CLASSIFIERS,
    platforms=['OS Independent'],
    package_data={'': [
        'templates/admin/haystackbrowser/*.html',
    ]},
)


text:
import logging

#log = logging.getLogger('pyzookeeper')

format_string = "%(asctime)s %(name)s [%(levelname)s]:%(message)s"
level = 'INFO'
logger = logging.getLogger('pyzookeeper')
logger.setLevel(level)
lhandler = logging.StreamHandler()
lhandler.setLevel(level)
fm = logging.Formatter(format_string)
lhandler.setFormatter(fm)
logger.addHandler(lhandler)
log = logger

def election(zk_ip, qname):
    from pyzookeeper.algos.election import LeaderElection
    return LeaderElection(zk_ip,qname)