content
stringlengths
42
6.51k
def apply_move(board_state, move, side): """Returns a copy of the given board_state with the desired move applied. Args: board_state (3x3 tuple of int): The given board_state we want to apply the move to. move (int, int): The position we want to make the move in. side (int): The side we are making this move for, 1 for the first player, -1 for the second player. Returns: (3x3 tuple of int): A copy of the board_state with the given move applied for the given side. """ move_x, move_y = move def get_tuples(): for x in range(3): if move_x == x: temp = list(board_state[x]) temp[move_y] = side yield tuple(temp) else: yield board_state[x] return tuple(get_tuples())
def num_of_ways_to_climb(n: int, steps: list): """ :param n: number of steps :param steps: number of steps that can be taken :return: number of ways to use steps """ if n < min(steps): return 0 ways = 0 for step in steps: if n == step: ways += 1 elif n > step: ways += num_of_ways_to_climb(n - step, steps) return ways
def to_bytes(obj, encoding='utf-8', errors='strict'): """Makes sure that a string is a byte string. Args: obj: An object to make sure is a byte string. encoding: The encoding to use to transform from a text string to a byte string. Defaults to using 'utf-8'. errors: The error handler to use if the text string is not encodable using the specified encoding. Any valid codecs error handler may be specified. Returns: Typically this returns a byte string. """ if isinstance(obj, bytes): return obj return bytes(obj, encoding=encoding, errors=errors)
def plusOne(digits): """ :type digits: List[int] :rtype: List[int] """ digits[-1] = digits[-1] + 1 res = [] ten = 0 i = len(digits)-1 while i >= 0 or ten == 1: sum = 0 if i >= 0: sum += digits[i] if ten: sum += 1 res.append(sum % 10) ten = sum / 10 i -= 1 return res[::-1]
def is_number(my_value): """ Check if value is a number or not by casting to a float and handling any errors. :param my_value: value to check :return: true if number, false if not. """ try: float(my_value) return True except Exception: return False
def set_file_ext(ext): """Set the filename suffix(extension)""" global _EXT _EXT = ext return _EXT
def volume_type_validator(x): """ Property: VolumeSpecification.VolumeType """ valid_values = ["standard", "io1", "gp2"] if x not in valid_values: raise ValueError("VolumeType must be one of: %s" % ", ".join(valid_values)) return x
def get_all_paste_ids(filters={}, fdefaults={}): """ This method must return a Python list containing the ASCII ID of all pastes which match the (optional) filters provided. The order does not matter so it can be the same or it can be different every time this function is called. In the case of no pastes, the method must return a Python list with a single item, whose content must be equal to 'none'. :param filters: a dictionary of filters :param fdefaults: a dictionary with the default value for each filter if it's not present :return: a list containing all paste IDs """ return ['none']
def Scale( h, scale = 1.0): """rescale bins in histogram. """ n = [] for b, v in h: n.append( (b * scale, v) ) return n
def solution(string): # O(N) """ Write a function to convert a string into an integer. Return None if string is an invalid integer. >>> solution('123') 123 >>> solution('0') 0 >>> solution('-1243') -1243 >>> solution('hello') >>> solution('31-12') """ number_value = { '0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9 } # O(1) is_negative = False # O(1) result = 0 # O(1) for count, char in enumerate(string): # O(N) value = number_value.get(char) # O(1) if count == 0 and char == '-': # O(1) is_negative = True # O(1) elif value is None: # O(1) return value # O(1) else: # O(1) result *= 10 # O(1) result += value # O(1) if is_negative: # O(1) return result * -1 # O(1) return result # O(1)
def history_dict_for_file(listdicts, fname) : """Returns dictionary-record for from history_list_of_dicts. """ if listdicts is None : return None for d in listdicts : v = d.get('file', None) if v == None : continue if v == fname : return d return None
def sizeof_fmt(num): """Takes the a filesize in bytes and returns a nicely formatted string. """ for x in ["bytes", "KB", "MB", "GB", "TB"]: if num < 1024.0: return f"{num:3.1f} {x}" num /= 1024.0
def max_value(input_list): """ Brief: return the max value in a list Arg: a list of numeric values, else it will raise an Error Return: the max value Raise: ValueError if value is found ValueError if input tab is not a list """ if not(isinstance(input_list,list)): raise ValueError("Expected a list as input") ## # basic function able to return the max value of a list # @param input_list : the input list to be scanned # @throws an exception (ValueError) on an empty list #first check if provided list is not empty if len(input_list)==0: raise ValueError('provided list is empty') #init max_value and its index max_val=input_list[0] # max_idx=0 #compute the average of positive elements of a list for item in input_list: #select only positive items if max_val<item: max_val=item return max_val
def textindent(t, indent=0): """Indent text.""" return "\n".join(" " * indent + p for p in t.split("\n"))
def exists(test_subject, keys): """Check if a list of keys exists in an object. :param test_subject: A dictionary object. :type test_subject: dic :param keys: The list of keys to be checked against the 'test_subject'. :type keys: list of str :return: True if the list of keys is available, false otherwise. :rtype: bool """ #Examples:froggy.gadgets.exists({"id": 1, "name": "Anna"}, {"createdon", "updatedon"}) for key in keys: if key in test_subject: # Check if there is a value in the key, if not, return false. if (not test_subject[key]): return(False) else: return(False) # 'They call me Mister Tibbs!' return(True)
def equals(a, b) -> bool: """ compares two values and check if their values are equal @input: two integers a, b @output: True if a, b have same values, False otherwise """ a, b = int(a), int(b) return a == b
def api_response(success, message, http_status_code, data={}): """ API Response common method. Args: success (bool): API status message (str): Message to display http_status_code (str or int): HTTP Response type. i.e. 200 or STATUS_OK data (dict): Data to be sent in api Response Returns: API response with payload and HTTP status code """ payload = {"success": success, "message": message, "data": data if isinstance(data, dict) else {}} return payload, http_status_code
def make_complete_graph(num_nodes): """ generates a complete undirected graph as a dictionary """ ugraph = {} full_set = set(range(num_nodes)) for node in full_set: ugraph[node] = full_set.difference(set([node])) return ugraph
def leap(year: int): """ - If a year is evenly divisible by 4 means having no remainder then go to next step. - If it is not divisible by 4. It is not a leap year. For example: 1997 is not a leap year. - If a year is divisible by 4, but not by 100. For example: 2012, it is a leap year. - If a year is divisible by both 4 and 100, go to next step. - If a year is divisible by 100, but not by 400. For example: 1900, then it is not a leap year. - If a year is divisible by both, then it is a leap year. So 2000 is a leap year. """ if (year % 4) == 0: if (year % 100) == 0: if (year % 400) == 0: return True else: return False else: return True else: return False
def get_terraform_path(project, cloud): """Derive appropriate terraform code path based on inputs""" if not cloud or cloud not in ['aws', 'azure', 'gcp'] or not project or project not in ['traffic', 'activity', 'jenkins']: raise Exception("Cloud provider '{}' or project '{}' is NOT valid!".format(cloud, project)) return '/terraform/{}/{}'.format(cloud, project)
def hammingWeight(n): """ :type n: int :rtype: int """ numOnes = 0 binaryString = bin(n) for elem in binaryString: if (elem == '1'): print (elem) numOnes += 1 if (n == 0): return 0 else: if (n < 0): return (32 - numOnes) else: return (numOnes)
def is_single(text): """Determine if there are many items in the text.""" indicators = [', ', ' y ', ' e '] return not any(ind in text for ind in indicators)
def is_model_class(val) -> bool: """Return whether the parameter is a SQLAlchemy model class.""" return hasattr(val, '__base__') and hasattr(val, '__table__')
def before(n): """Bits before n exclusive, indexing from 0""" return (1 << n) - 1
def convert_compartment_id(modelseed_id, format_type): """ Convert a compartment ID in ModelSEED source format to another format. No conversion is done for unknown format types. Parameters ---------- modelseed_id : str Compartment ID in ModelSEED source format format_type : {'modelseed', 'bigg'} Type of format to convert to Returns ------- str ID in specified format """ if format_type == 'modelseed' or format_type == 'bigg': return modelseed_id[0] return modelseed_id
def collect_sentences_vist_dii(data): """Collect all sentences from the VisualGenome regions and tag them""" sentences = [] for ann in data['annotations']: sentences.append(ann[0]['text']) return sentences
def sort_keys_by_cnt(misclfds): """ """ cnts = [] for misclf_key in misclfds: cnts.append([misclf_key, len(misclfds[misclf_key])]) sorted_keys = [v[0] for v in sorted(cnts, key = lambda v:v[1], reverse = True)] return sorted_keys
def get_next_coordinates(x, y, direction): """ >>> get_next_coordinates(0, 0, '>') (1, 0) >>> get_next_coordinates(0, 0, '<') (-1, 0) >>> get_next_coordinates(0, 0, '^') (0, 1) >>> get_next_coordinates(0, 0, 'v') (0, -1) """ if direction == '^': y += 1 elif direction == 'v': y -= 1 elif direction == '<': x -= 1 elif direction == '>': x += 1 else: raise SyntaxError('Expected <^v> got {0}'.format(direction)) return x, y
def update_distributions(existing, new, current_node): """ Given the existing distributions dictionary and another containing new entries to add this function will handle merging them """ # Loop through the keys in the new dictionary for new_key in new.keys(): # Check to see if the key exists in the existing dictionary if new_key not in existing.keys(): # This means this customer class hasn't been defined for # other nodes in the network so far. So to keep things # consistent we need to initialise the existing dictionary # with (current_node - 1) NoArrivals existing[new_key] = ['NoArrivals' for n in range(current_node - 1)] # Add the distribution to the existing dictionary existing[new_key].append(new[new_key]) # We also need to handle the cases where we have a node which doesn't recieve # customers which have been defined elsewhere in the network. So we now need # to go through each key in the exisiting dictionary to ensure that each list # is the required length and append 'NoArrivals' to any that don't match for existing_key in existing.keys(): # Check the length - it should match the current node if len(existing[existing_key]) != current_node: # We need to add a 'NoArrivals' existing[existing_key].append('NoArrivals') # Finally return the existing dictionary return existing
def uint8array_to_number(uint8array): """ Convert array of uint8_t into a single Python number """ return sum([x << (i*8) for i, x in enumerate(uint8array)])
def speed_to_pace(x): """ convert speed in m/s to pace in min/km """ if x == 0: return 0 else: p = 16.6666666 / x # 1 m/s --> min/km return ':'.join([str(int(p)), str(int((p * 60) % 60)).zfill(2)])
def resolve_di(resolved_keys_d, di_list_model): """ Resolve DI values in a list :param resolved_keys_d: {di key : func} The Func has empty signature :param di_list_model: DI list model (e.g., ['$tmpfile', '$tmpdir','$nproc']) :return: a list of resolved DI values """ resolved_specials = [] for s in di_list_model: if s in resolved_keys_d: func = resolved_keys_d[s] v = func() resolved_specials.append(v) else: _d = dict(s=s, t=resolved_keys_d.keys()) raise ValueError("Unable to resolve special '{s}'. Valid specials are '{t}'".format(**_d)) return resolved_specials
def func_from_fraction_continued(list_int_generator): """ a int list such as [0,1,2,3] -> the denominator 7 of 0+1/(1+1/(2+1/3)))=10/7 :param list_int_generator: a int list such as [0,1,2,3] :return: the denominator of the fraction generated by the list even though the func returns the variable int_numerator """ int_denominator = 1 int_numerator = 0 while len(list_int_generator) != 0: # We use a stack data structure to compute the denominator of continued # fraction, and the fraction is stored as two int: the denominator and the numerator int_denominator_new = list_int_generator.pop() * int_denominator + int_numerator int_numerator = int_denominator int_denominator = int_denominator_new # The above swapping step implicate computing the inverse of a fraction return int_numerator
def check_str_png(s): """ Check if string has .png extension. """ if not isinstance(s, str): raise TypeError("Input must be of type str") if not s.endswith('.png'): raise ValueError("String must end with .png") return s
def get_change(current, previous): """gets the percent change between two numbers""" negative = 0 if current < previous: negative = True try: value = (abs(current - previous) / previous) * 100.0 value = float('%.2f' % value) # pylint: disable=consider-using-f-string if value >= 0.01 and negative: value = value * -1 return value except ZeroDivisionError: return 0
def clean_hex(d): """Convert decimal to hex and remove the "L" suffix that is appended to large numbers. :param d: :return: """ return hex(d).rstrip("L")
def count_str_whitespace(mystr): """Counts no of whitespace in string and returns an int.""" count = 0 for mychar in mystr: if mychar.isspace(): count += 1 return count
def enrich_description(header, row): """ Place additional information in the description Tasks would be mark up, labels eventually real label, and the URL of the original story :param header: :param row: :return: """ description = row[header.index("Description")] # all of the tasks taskIndexes = [] for i in range(0, len(header)): if header[i] == "Task": taskIndexes.append(i) for v in taskIndexes: try: if row[v + 1] == "completed" and row[v]: #task done description += "\n# --%s--" % (row[v]) elif row[v]: description += "\n# %s" % (row[v]) except: pass description += "\n\nPT#%s" % (row[header.index("Id")]) description += "\nURL:%s" % (row[header.index("URL")]) labels = row[header.index("Labels")] if labels: description += "\nLabels:%s" % (row[header.index("Labels")]) return description
def word_to_word_ids(word_counts,unk_required): """Function to map individual words to their id's. Input: word_counts: Dictionary with words mapped to their counts Output: word_to_id: Dictionary with words mapped to their id's. """ count = 0 word_to_id = {} id_to_word = {} if unk_required: word_to_id['<UNK>'] = count id_to_word[count] = '<UNK>' count += 1 for word in word_counts.keys(): word_to_id[word] = count id_to_word[count] = word count+=1 return word_to_id,id_to_word
def elide_text(text: str, max_length: int) -> str: """Shorten a string to a max length and end it with an ellipsis.""" return text if len(text) < max_length else f"{text[:max_length]}..."
def dyn2kin(dyn, density): """ Convert from dynamic to kinematic viscosity. Parameters ---------- dyn: ndarray, scalar The dynamic viscosity of the lubricant. density: ndarray, scalar The density of the lubricant. Returns ------- kin: ndarray, scalar The kinematic viscosity of the lubricant. """ kin = dyn / density return kin
def create_rdict(d): """ Return a dictionary with each key mapping to a set of values. """ rd = {} for (key, value) in list(d.items()): v = rd.setdefault(value, set([])) v.add(key) return rd
def _sp_exit_with(e: int) -> str: """Return the subprocess cmd for exiting with `e` exit code.""" return 'python -c "import sys; sys.exit({})"'.format(e)
def present_seconds(seconds): """ strip off useless zeros or return nothing if zero - this algorithm only good to about 1 decimal place in seconds... """ if seconds == 0: # not needed at all seconds = '' elif seconds - int(seconds) == 0: #no need for trailing zeros seconds = "%d" % int(seconds) else: # present with decimals seconds = "%2.2f" % seconds seconds = seconds.strip('0') # remove unused zeros return seconds
def list_equal(*elements): """Check if all given elements are equal.""" l0 = elements[0] for element in elements[1:]: if element != l0: return False return True
def getPeriod(n): """ Returns period of 1/n Parameters ---------- n : int denotes positive integer return : int returns an integer denoting period of 1/n """ if(n!=int(n) or n<1): raise ValueError( "n must be positive integer" ) rem = 1 for i in range(1,n+2): rem = (10 * rem) % n d = rem count = 0 rem = (10 * rem) % n count += 1 while(rem != d): rem = (10 * rem) % n count += 1 return count
def _get_course_cohort_settings_representation(cohort_id, is_cohorted): """ Returns a JSON representation of a course cohort settings. """ return { 'id': cohort_id, 'is_cohorted': is_cohorted, }
def _dict_deep_merge(x, y): """Returns the union of x and y. y takes predescence. """ if x is None: return y if y is None: return x if isinstance(x, dict): if isinstance(y, dict): return {k: _dict_deep_merge(x.get(k), y.get(k)) for k in set(x).union(y)} assert y is None, repr(y) return x if isinstance(y, dict): assert x is None, repr(x) return y # y is overriding x. return y
def median(inList): """ Computes the median of a list. NOTE: The list must be sorted!!! """ if len(inList) == 1: return inList[0] if len(inList) == 0: return 0. if not len(inList) % 2: return (inList[len(inList) // 2] + inList[len(inList) // 2 - 1]) / 2.0 return inList[len(inList) // 2]
def seqs_from_empty(obj, *args, **kwargs): """Allows empty initialization of Module, useful when data must be added.""" return [], []
def hsv2rgb(hsv): """ hsv: [h, s, v] h in [0, 360] s in [0, 1] v in [0, 1] return [r, g, b] r, g, b in [0, 1] """ h = hsv[0] s = hsv[1] v = hsv[2] hd = h/60; # in [0, 6] r = v g = v b = v if s > 0: hdi = max(0, min(5, int(hd))); f = hd - hdi if hdi==0: g *= 1 - s * (1-f) b *= 1 - s elif hdi==1: r *= 1 - s * f b *= 1 - s elif hdi==2: r *= 1 - s b *= 1 - s * (1-f) elif hdi==3: r *= 1 - s g *= 1 - s * f elif hdi==4: r *= 1 - s * (1-f) g *= 1 - s elif hdi==5: g *= 1 - s b *= 1 - s * f return [r, g, b]
def make_text(text, i18n_texts=None): """ make text. reference - https://developers.worksmobile.com/jp/document/100500801?lang=en :return: text content. """ if i18n_texts is not None: return {"type": "text", "text": text, "i18nTexts": i18n_texts} return {"type": "text", "text": text}
def gen_action_validations(validation_list): """Generates a CLI formatted listing of validations Assumes validation_list is a list of dictionaries with 'validation_name', 'action_id', 'id', and 'details'. """ if validation_list: validations = [] for val in validation_list: validations.append('{} : validation/{}/{}\n'.format( val.get('validation_name'), val.get('action_id'), val.get( 'id'))) validations.append(val.get('details')) validations.append('\n\n') return 'Validations: {}'.format('\n'.join(validations)) else: return 'Validations: {}'.format('None')
def calculateHammingSyndrom(byte): """Calculates hamming syndrom""" #S0 = C1 xor C3 xor C5 xor C7 xor C9 xor C11 S0 = str( int(byte[1]) ^ int(byte[3]) ^ int(byte[5]) ^ int(byte[7]) ^ int(byte[9]) ^ int(byte[11]) ) #S1 = C2 xor C3 xor C6 xor C7 xor C10 xor C11 S1 = str( int(byte[2]) ^ int(byte[3]) ^ int(byte[6]) ^ int(byte[7]) ^ int(byte[10]) ^ int(byte[11]) ) #S2 = C4 xor C5 xor C6 xor C7 xor C12 S2 = str( int(byte[4]) ^ int(byte[5]) ^ int(byte[6]) ^ int(byte[7]) ^ int(byte[12]) ) #S3 = C8 xor C9 xor C10 xor C11 xor C12 S3 = str( int(byte[8]) ^ int(byte[9]) ^ int(byte[10]) ^ int(byte[11]) ^ int(byte[12]) ) #SX = C1 to C12 SX = str( int(byte[0]) ^ int(byte[1]) ^ int(byte[2]) ^ int(byte[3]) ^ int(byte[4]) ^ int(byte[5]) ^ int(byte[6]) ^ int(byte[7]) ^ int(byte[8]) ^ int(byte[9]) ^ int(byte[10]) ^ int(byte[11]) ^ int(byte[12]) ) S = int(S3 + S2 + S1 + S0, 2) return {"SX": int(SX), "S": S}
def get_games_count(json_data): """ get the number of games contained in the specified json data :param json_data: a string containing the json data retrieved from a previous web REST api call :return: returns the total number of games (0 if there are none) """ total_games = 0 if 'totalGames' in json_data: total_games = int(json_data['totalGames']) return total_games
def generate_multigrams(sentence): """Generate n-grams of the sentence""" tokens, multigrams = sentence.split(), [] tk_length = len(tokens) for y in range(tk_length): new_sentence = True support_text = "" for x in range(y, tk_length): if y == 0 and tk_length > 2 and x == tk_length: continue if len(tokens[x]) <= 2 and tokens[x] != tokens[-1]: support_text += f" {tokens[x]}" continue last = "" if x > y and len(multigrams) > 0 and not new_sentence: last = multigrams[-1] multigrams.append(f"{last}{support_text} {tokens[x]}".strip()) new_sentence = False support_text = "" return multigrams
def get_second_validate_param(tel_num): """ Assemble param for get_second_validate :param tel_num: Tel number :return: Param in dict """ param_dict = dict() param_dict['act'] = '1' param_dict['source'] = 'wsyytpop' param_dict['telno'] = tel_num param_dict['password'] = '' param_dict['validcode'] = '' param_dict['authLevel'] = '' param_dict['decode'] = '1' param_dict['iscb'] = '1' return param_dict
def doolittle(matrix_a): """ Doolittle's Method for LU-factorization. :param matrix_a: Input matrix (must be a square matrix) :type matrix_a: list, tuple :return: a tuple containing matrices (L,U) :rtype: tuple """ # Initialize L and U matrices matrix_u = [[0.0 for _ in range(len(matrix_a))] for _ in range(len(matrix_a))] matrix_l = [[0.0 for _ in range(len(matrix_a))] for _ in range(len(matrix_a))] # Doolittle Method for i in range(0, len(matrix_a)): for k in range(i, len(matrix_a)): # Upper triangular (U) matrix matrix_u[i][k] = float(matrix_a[i][k] - sum([matrix_l[i][j] * matrix_u[j][k] for j in range(0, i)])) # Lower triangular (L) matrix if i == k: matrix_l[i][i] = 1.0 else: matrix_l[k][i] = float(matrix_a[k][i] - sum([matrix_l[k][j] * matrix_u[j][i] for j in range(0, i)])) # Handle zero division error try: matrix_l[k][i] /= float(matrix_u[i][i]) except ZeroDivisionError: matrix_l[k][i] = 0.0 return matrix_l, matrix_u
def _dequeue_sets(q_set): """Empty the q sets to form new list (1 idx iteration).""" temp_sorted = [] for q in q_set: for _ in range(len(q)): temp_sorted.append(q.dequeue()) return temp_sorted
def convert_pairs(string_pairs): """ Convert pair names to usable format Args: string_pairs: str Comma seperated node pairs in format "node1-node2" Returns: [tuple]: List of tuples with node pair names """ tuple_pairs = string_pairs if type(string_pairs) == str: pairs = string_pairs.replace(" ", "").split(",") tuple_pairs = [tuple(pair.split("-")) for pair in pairs] return tuple_pairs
def url_to_id(url): """ Takes a tweet url and returns its id """ character_list = url.split('/') return int(character_list[5])
def rect_vertices(xywh, integers): """ p1 ----- p4 | | p2 ----- p3 """ if integers: xywh = map(lambda e: int(round(e)), xywh) x, y, w, h = xywh return (x, y), (x, y + h), (x + w, y + h), (x + w, y)
def format_url(base_string): """ Turns multiline strings in generated clients into simple one-line string Args: base_string (str): multiline URL Returns: str: single line URL """ return ''.join( [line.strip() for line in base_string.splitlines()] )
def fibonacci(k): """ Calculates the kth Fibonacci number """ if k == 0: return 0 elif k == 1 or k == 2: return 1 else: return fibonacci(k-1)+fibonacci(k-2)
def parseMoClassName(className): """ Given a class name (aaaUserEp) returns tuple aaa,UserEp""" idx = -1 upperFound = False for c in className: idx += 1 if c.isupper(): upperFound = True break if upperFound: pkg = className[:idx] klass = className[idx:] else: pkg = className klass = "" return pkg, klass
def get_shard_number(file_name: str) -> int: """Retrieves the shard number from a shard filename.""" return int(file_name[5:])
def get_address_from_hosts_file(hostname): """ Get the IP address of a host from the /etc/hosts file :param hostname: hostname to look up :return: IP address of host """ hosts = open('/etc/hosts') for line in hosts: if line.strip() and line.split()[1] == hostname: return line.split()[0] raise Exception("Hostname %s not found in /etc/hosts" % hostname)
def is_thin_archive(path): """ Returns True if path refers to a thin archive (ar file), False if not. """ with open(path, 'rb') as f: return f.read(8) == b'!<thin>\n'
def init_bugfix_changes_stats(stats, data, commit, changes): """Initialize stats related to changes in the bugfix commit Those statistics include currently: - n_changes: total number of all changed files - n_effective: all changes except deletions - n_renames: all file renames - n_deletions: all file deletions - n_additions: all file additions (new files in the commit) Parameters ---------- stats : dict Statistics for each commit / bug report, to be saved as CSV and/or to generate summary of overall statistics of bug reports and the repository. data : dict Combined data about bug reports and bugfix commits, read from the JSON file. commit : str Identifier of the bugfix commit, key to 'stats' structure to create and/or update. changes : dict Result of calling retrieve_changes_status() for a commit; key is pair of pre-commit and post-commit pathnames, while the value is one-letter status of changes. Returns ------- dict Updated statistics data Side effects ------------ Modifies contents of 'stats' parameter """ if commit not in stats: stats[commit] = {} stats[commit].update({ 'n_changes': len(changes), 'n_effective': len([pair for pair, status in changes.items() if status != 'D']), 'n_renames': len([pair for pair, status in changes.items() if status == 'R']), 'n_deletions': len([pair for pair, status in changes.items() if status == 'D']), 'n_additions': len([pair for pair, status in changes.items() if status == 'A']), }) return stats
def get_interface_props(props): """Get the interface properties.""" FLAGS = { 0x01: "UP", 0x02: "BROADCAST", 0x04: "LOOPBACK", 0x08: "POINTOPOINT", 0x10: "MULTICAST", 0x20: "RUNNING"} flag = int(props, 16) flag_name = "" for bit in FLAGS: if flag & bit != 0: flag_name += FLAGS[bit] + "|" return flag_name
def metrics_to_str(metrics, prefix=""): """ Converts metrics dictionary into a human readable string. :param metrics: dict where keys are metric names and values are scores. :param prefix: self-explanatory. :return: str representation. """ my_str = ", ".join(["%s: %.3f" % (k, v) for k, v in metrics.items()]) if prefix: my_str = prefix + " " + my_str return my_str
def tau_pf(spc_mod_dct_i): """ determine if pf is done with tau """ tors_model = spc_mod_dct_i['tors']['mod'] return bool(tors_model in ('tau', 'tau-1dhr', 'tau-1dhrf', 'tau-1dhrfa'))
def parse_permission(perm): """Convert the string permission into a dict to unpack for insert_permission.""" perm_dict = {} perm = perm.split("|") for part in perm: if "@" in part: perm_dict["value"] = part perm_dict["perm_type"] = "user" elif "." in part: perm_dict["value"] = part perm_dict["perm_type"] = "domain" elif "anyone" == part: perm_dict["perm_type"] = "anyone" elif part in ["grp", "group"]: perm_dict["perm_type"] = "group" elif part in ["owner", "writer", "reader"]: perm_dict["role"] = part elif part in ["no", "false"]: perm_dict["notify"] = False elif part == "link": perm_dict["with_link"] = True perm_dict["role"] = perm_dict.get("role", "reader") return perm_dict
def format_special_tokens(token): """Convert <> to # if there are any HTML syntax tags. Example: '<Hello>' will be converted to '#Hello' to avoid confusion with HTML tags. Args: token (str): The token to be formatted. Returns: (str): The formatted token. """ if token.startswith("<") and token.endswith(">"): return "#" + token.strip("<>") return token
def isin(elt, seq): """Like (elt in seq), but compares with is, not ==. >>> e = []; isin(e, [1, e, 3]) True >>> isin(e, [1, [], 3]) False """ for x in seq: if elt is x: return True return False
def has_duplicates(n): """ Check if the given list has unique elements Uses the property of sets: If converted into a set it is guaranteed to have unique elements. -> Compare number of elements to determine if the list contains duplicates """ if type(n) is not list: raise TypeError("Given input is not a list") if len(n) != len(set(n)): return True return False
def check_and_as_str_tuple_list(arg_name, strs): """Check whether the input parameters are reasonable multiple str inputs, which can be single str, tuple or list of str. finally, return tuple of str""" if isinstance(strs, str): strs = (strs,) if not isinstance(strs, (tuple, list)): raise RuntimeError(f"Parameter '{arg_name}' should be str or tuple/list of str, but actually {type(strs)}") str_list = [] for item in strs: if not isinstance(item, str): raise RuntimeError(f"The item of parameter '{arg_name}' should be str, but actually {type(item)}") if not item: raise RuntimeError(f"The item of parameter '{arg_name}' should not be empty str") if item in str_list: raise RuntimeError(f"The item value '{item}' in parameter '{arg_name}' should not be repeated") str_list.append(item) return tuple(str_list)
def garbage(stream): """Skip over any garbage in the stream, properly handling escaped (!) characters, and counting all characters. :stream: stream of characters :returns: number of garbage characters """ count = 0 for c in stream: if c == '!': # escape, skip the next char next(stream) elif c == '>': return count else: count += 1
def rquicksort(arr): """Recursive quicksort""" if len(arr) <= 1: return arr return rquicksort([i for i in arr[1:] if i < arr[0]]) + \ [arr[0]] + \ rquicksort([i for i in arr[1:] if i > arr[0]])
def next_power_of_2(x): """Returns the smallest greater than x, power of 2 value. https://stackoverflow.com/a/14267557/576363 """ x = int(x) return 1 if x == 0 else 2 ** (x - 1).bit_length()
def quote_unicode(s): """ Quote unicode strings for URLs for Rocket """ chars = [] for char in s: o = ord(char) if o < 128: chars.append(char) else: chars.append(hex(o).replace("0x", "%").upper()) return "".join(chars)
def cgi_escape(s, quote=False): """Replace special characters '&', '<' and '>' by SGML entities. This is a slightly more efficient version of the cgi.escape by using 'in' membership to test if the replace is needed. This function returns a plain string. Programs using the HTML builder should call ``webhelpers.html.builder.escape()`` instead of this to prevent double-escaping. Changed in WebHelpers 1.2: escape single-quote as well as double-quote. """ if '&' in s: s = s.replace("&", "&amp;") # Must be done first! if '<' in s: s = s.replace("<", "&lt;") if '>' in s: s = s.replace(">", "&gt;") if quote: s = s.replace('"', "&quot;") s = s.replace("'", "&apos;") return s
def dict_to_aws_tags(d): """ Transforms a python dict {'a': 'b', 'c': 'd'} to the aws tags format [{'Key': 'a', 'Value': 'b'}, {'Key': 'c', 'Value': 'd'}] Only needed for boto3 api calls :param d: dict: the dict to transform :return: list: the tags in aws format >>> from pprint import pprint >>> pprint(sorted(dict_to_aws_tags({'a': 'b', 'c': 'd'}), key=lambda d: d['Key'])) [{'Key': 'a', 'Value': 'b'}, {'Key': 'c', 'Value': 'd'}] """ return [{'Key': k, 'Value': v} for k, v in d.items()]
def parse_arguments(arguments): """Parse command line arguments into positional parameters, options and flags.""" positional_arguments = [] option_values = {} flag_values = [] for arg in arguments: if arg[0] != '-': positional_arguments.append(arg) else: if '=' in arg: pair = arg.split('=') if pair[0][1] == '-': option_values[pair[0][2:]] = pair[1] else: option_values[pair[0][1]] = pair[1] else: if arg[1] == '-': flag_values.append(arg[2:]) else: flag_values.append(arg[1:]) return (positional_arguments, option_values, flag_values)
def get_label_from_in_depth_analysis(fileinfo): """ Simulated in-depth analysis. Returns the real label of the file. """ return fileinfo['family']
def mkcol_mock(url, request): """Simulate collection creation.""" return {"status_code": 201}
def sigmoid_output_to_derivative(output): """ convert output of sigmoid function to its derivative """ return output*(1-output)
def longest_substring(string): """ time: O(n) """ last_seen = {} start = 0 # for single char inputs max_length = 0 for i, char in enumerate(string): if char in last_seen: start = max(start, last_seen[char] + 1) last_seen[char] = i max_length = max(max_length, i - start + 1) return max_length
def get_vendors(ven): """ Input arguments for function = tuple Coverts tuple into a list. I know, it is silly. Input example: get_vendors(("Neste", "Circle K")) Output example: ['Neste', 'Circle K'] """ vendors_list = list(ven) return vendors_list
def invert_sym(sym_op): """ Invert the sign of the given symmetry operation Usage: new_op = invert_sym(sym_op) sym_op = str symmetry operation e.g. 'x,y,z' new_op = inverted symmetry E.G. new_op = invert_sym('x,y,z') >> new_op = '-x,-y,-z' """ sym_op = sym_op.lower() new_op = sym_op.replace('x', '-x').replace('y', '-y').replace('z', '-z').replace('--', '+').replace('+-', '-') return new_op
def letter_grades(highest): """ :param highest: integer of highest exam score. :return: list of integer lower threshold scores for each D-A letter grade interval. For example, where the highest score is 100, and failing is <= 40, The result would be [41, 56, 71, 86]: 41 <= "D" <= 55 14 56 <= "C" <= 70 14 71 <= "B" <= 85 14 86 <= "A" <= 100 14 """ thresholds = [] intervals = [] failing = 41 # 100 - 41 = 59 59 / 4 = 15 # 100 41 56 71 86 # 97 41 55 69 83 97-41 56/4 14 # 85 41 52 63 74 85 85-41 44/4 11 # 92 41 54 67 80 92-41 51/4 13 # 81 41 51 61 71 81-41 40/4 10 interval = 0 interval = round((highest-failing) /4 ) intervals.append(failing) intervals.append(failing + interval*1) intervals.append(failing + interval*2) intervals.append(failing + interval*3) return intervals
def _round_up_to_multiple(value, multiple): """Rounds an integer value up to a multiple specified.""" mod = value % multiple # Value is already an exact multiple, so return the original value. if mod == 0: return value # Round up to next multiple return (value - mod) + multiple
def get_correct_final_coordinates_product(commands): """Get result of multiplying a final horizontal position by a final depth taking into account the aim value; commands(list of list[direction(str), steps(int)]): instructions""" hor = 0 dep = 0 aim = 0 for com in commands: if com[0] == "up": aim -= com[1] elif com[0] == "down": aim += com[1] else: hor += com[1] dep += com[1] * aim return hor * dep
def matrix_multiplication(X_M, *Y_M): """Return a matrix as a matrix-multiplication of X_M and arbitary number of matrices *Y_M""" def _mat_mult(X_M, Y_M): """Return a matrix as a matrix-multiplication of two matrices X_M and Y_M >>> matrix_multiplication([[1, 2, 3], [2, 3, 4]], [[3, 4], [1, 2], [1, 0]]) [[8, 8],[13, 14]] """ assert len(X_M[0]) == len(Y_M) result = [[0 for i in range(len(Y_M[0]))] for j in range(len(X_M))] for i in range(len(X_M)): for j in range(len(Y_M[0])): for k in range(len(Y_M)): result[i][j] += X_M[i][k] * Y_M[k][j] return result result = X_M for Y in Y_M: result = _mat_mult(result, Y) return result
def area_of_imgblocks(imgblocks): """ It adds the """ sum_areas = 0 for imgblock in imgblocks: block_area = imgblock['width'] * imgblock['height'] sum_areas = sum_areas + block_area return(sum_areas)
def _LinkifyString(s): """Turns instances of links into anchor tags. Args: s: The string to linkify. Returns: A copy of |s| with instances of links turned into anchor tags pointing to the link. """ for component in s.split(): if component.startswith('http'): component = component.strip(',.!') s = s.replace(component, '<a href="%s">%s</a>' % (component, component)) return s
def remote_prd_mock(url, request): """ Mock for remote PRD info. """ thebody = b'{"PRD-63999-999":{"curef":"PRD-63999-999","variant":"Snek","last_ota":"AAZ888","last_full":"AAZ999"}}' return {'status_code': 200, 'content': thebody}
def check_address(btc_addr, network='test'): """ Checks if a given string is a Bitcoin address for a given network (or at least if it is formatted as if it is). :param btc_addr: Bitcoin address to be checked. :rtype: hex str :param network: Network to be checked (either mainnet or testnet). :type network: hex str :return: True if the Bitcoin address matches the format, raise exception otherwise. """ if network in ['test', "testnet"] and btc_addr[0] not in ['m', 'n']: raise Exception("Wrong testnet address format.") elif network in ['main', 'mainnet'] and btc_addr[0] != '1': raise Exception("Wrong mainnet address format.") elif network not in ['test', 'testnet', 'main', 'mainnet']: raise Exception("Network must be test/testnet or main/mainnet") elif len(btc_addr) not in range(26, 35+1): raise Exception( "Wrong address format, Bitcoin addresses should be 27-35 hex char long.") else: return True
def morphology_used_in_fitting(optimized_params_dict, emodel): """Returns the morphology name from finals.json used in model fitting. Args: optimized_params_dict (dict): contains the optimized parameters, as well as the original morphology path emodel (str): name of the emodel Returns: str: the original morphology name used in model fitting """ emodel_params = optimized_params_dict[emodel] morph_path = emodel_params["morph_path"] morph_name = morph_path.split("/")[-1] return morph_name
def _deep_tuple(item): """ Convert a nested list with arbitrary structure to a nested _tuple_ instead. """ if isinstance(item, list): # In the recursive case (item is a list), recursively deep_tuple-ify all # list items, and store all items in a tuple intead. return tuple(_deep_tuple(i) for i in item) else: # In the base case (any items that are not lists, including some # possibly deep objects like dicts, and tuples themselves), change # nothing. return item