content
stringlengths
42
6.51k
def forward(facing, x_axis, y_axis): """Returns the X and Y axis after stepping forward""" if facing == "N": x_axis += 1 if facing == "S": x_axis -= 1 if facing == "E": y_axis += 1 if facing == "W": y_axis -= 1 return x_axis, y_axis
def _update_set(index, n_qubits): """The bits that need to be updated upon flipping the occupancy of a mode.""" indices = set() # For bit manipulation we need to count from 1 rather than 0 index += 1 # Ensure index is not a member of the set index += index & -index while index <= n_qubits: indices.add(index - 1) # Add least significant one to index # E.g. 00010100 -> 00011000 index += index & -index return indices
def first_of(iterable, function): """ Return the first matching element of an iterable This function is useful if you already know there is at most one matching element. """ for item in iterable: if function(item): return item return None
def mean(values): """ Returns the mean of values """ return sum(values) / len(values)
def get_cities(src): """Return list of cities.""" cities = [] for city in src.get("city", []): cities.append("%s, %s" % (city.get("name", ""), city.get("admin1_name", ""))) return cities
def square_of_sum(n): """ Calculate the square of the sum of the first n natural numbers """ return sum(i for i in range(1, n + 1)) ** 2
def dict_merge(d1, d2): """ Merge two dictionaries recursively. Merge the lists embedded within dictionary at the same positions too (with caveats). """ result = dict(d2) for k1, v1 in d1.items(): if k1 not in result: result[k1] = v1 elif isinstance(v1, list): result[k1] = list(set(d2[k1] + v1)) elif isinstance(v1, dict): result[k1] = dict_merge(v1, d2[k1]) return result
def wherechanged(arr): """ Returns the indices where a list changes values Parameters ---------- arr : array or list the array or list that may contain changes Returns ------ where : a list of indices that changes occur """ where = [] for i in range(len(arr) - 1): diff = arr[i + 1] ^ arr[i] if diff != 0: where.append(i + 1) return where
def plusOneSum(arr): """returns the sum of the integers after adding 1 to each element""" return sum(arr)+len(arr)
def _next_power_two(x): """ given a number, returns the next power of two """ x = int(x) n = 1 while n < x: n = n << 1 return n
def test_exif_jfif(h, f): """JPEG data in JFIF or Exif format""" if h[6:10] in (b'JFIF', b'Exif') or b'JFIF' in h[:23] or h[:2] == b'\xff\xd8': return 'jpeg'
def matches_rule(column, rule): """ Check if a list of numbers all match a particular rule. :param column: list of numbers to check, this can be a column or a row of numbers :param rule: a list with two tuples, each containing a low and high range number :return: True if the list of numbers all match the rule. """ for n in column: if all(not(low <= n <= hi) for low, hi in rule): return False return True
def avg_calc(times): """Calculate average of 5 for a given list of times Args: times (list): List of times, in seconds Returns: float or str: AO5 score or DNF """ dnf_counter = 0 conv_times = [] for i in times: if i.upper() == "DNF": dnf_counter += 1 continue elif i == "": dnf_counter += 1 continue conv_times.append(float(i)) # If there are 2 or more DNFs, return DNF # Regulation 9f9 if dnf_counter >= 2: return("DNF") # Sum all the times temp = sum(conv_times) # If all times present, subtract best and worst if len(conv_times)==5 : tt = temp - max(conv_times) - min(conv_times) return round(tt/3.0,2) # If one attempt is DNF, subtract only the best (as DNF is the worst) elif len(conv_times)==4 : tt = temp - min(conv_times) return round(tt/3.0,2)
def _create_fake_operation(resource_link, verb, name): """Creates a fake operation resource dictionary for dry run. Args: resource_link (str): The full URL to the resource the operation would have modified. verb (str): The API method the operation would have been for. name (str): The operation name, can be any string. Returns: dict: A fake Operation resource. """ return { 'targetLink': resource_link, 'operationType': verb, 'name': name, 'status': 'DONE', 'progress': 100, }
def to_float(s_val): """ Converts s to a float if possible. @ In, s_val, any, value to convert @ Out, s_val, float or any """ try: return float(s_val) except ValueError: return s_val
def get_item(dictionary, key_id): """Returns value in dictionary from the key_id. Used when you want to get a value from a dictionary key using a variable :param dictionary: dict :param key_id: string :return: value in the dictionary[key_id] How to use: {{ mydict|get_item:item.NAME }} """ return dictionary.get(key_id)
def urljoin(*parts: str) -> str: """Take as input an unpacked list of strings and joins them to form an URL""" return "/".join(part.strip("/") for part in parts)
def _call_string(*args, **kwargs): """Return format of args and kwargs as viewed when typed out""" arg_strings = [] for arg in args: arg_strings.append(repr(arg)) for key, arg in kwargs.items(): arg_strings.append(key+'='+repr(arg)) return "(%s)" % ', '.join(arg_strings)
def collect(spotify, results, page_operation=None): """ :param spotify: Spotify :param results: API response as Dictionary :param page_operation: Function that has items from API response as parameter :return: """ collection = [] if page_operation: page_operation(results['items']) collection.extend(results['items']) while results['next']: results = spotify.next(results) if page_operation: page_operation(results['items']) collection.extend(results['items']) return collection
def before_send(event, hint): """Don't log django.DisallowedHost errors in Sentry.""" if "log_record" in hint: if hint["log_record"].name == "django.security.DisallowedHost": return None return event
def kalkulasi_kecepatan_akhir( kecepatan_awal: float, percepatan: float, waktu: float ) -> float: """ Menghitung kecepatan akhir dari suatu pergerakan dengan percepatan yang berbeda >>> kalkulasi_kecepatan_akhir(10, 2.4, 5) 22.0 >>> kalkulasi_kecepatan_akhir(10, 7.2, 1) 17.2 """ # jika waktu 0 diisi dengan 1 detik return kecepatan_awal + percepatan * waktu
def pam4_decision(x,l,m,h): """produces pam4 symbol from analog voltage Parameters ---------- x : float the analog voltage l: float voltage threshold between 0 and 1 symbol m: float voltage threshold between 1 and 2 symbol h: float voltage threshold between 2 and 3 symbol Returns ------- int the pam4 symbol that represents x """ if x<l: return 0 elif x<m: return 1 elif x<h: return 2 else: return 3
def expand_float(data): """helper method for ``expand_thru_case_control``""" out = [] for datai in data: out.append(float(datai)) out.sort() return out
def _line_reformat(line, width=70, firstlinewidth=0): """Takes line string and inserts newlines and spaces on following continuation lines so it all fits in width characters @param width: how many characters to fit it in @param firstlinewidth: if >0 then first line is this width. if equal to zero then first line is same width as rest. if <0 then first line will go immediately to continuation. """ if firstlinewidth == 0: firstlinewidth = width if len(line) < firstlinewidth: return line res = "" if firstlinewidth > 0: res += line[:firstlinewidth] line = line[firstlinewidth:] while len(line): res += "\n "+line[:width] if len(line)<width: break line = line[width:] return res
def format_data(mapping): """Format given mapping as HTML "data" attributes "-data" prefix is not required for given mapping keys """ return ' '.join(('data-{}="{}"'.format(k, v) for k, v in mapping.items()))
def _check_extension(filename): """ check file type Arguments: ---------- filename {str} -- file name Returns: -------- {str} -- file extension Examples: --------- >>> _check_extension("hoge") None >>> _check_extension("hoge.png") 'png' """ split_filename = filename.split(".") if len(split_filename) == 1: return None return split_filename[-1].lower()
def _compute_annot_reliability_score(tf_row, entities, freq_matrix): """ Compute likelihood of neg samples belonging to pos space based on onto annotation freqs :return: """ # Score is the sum of (freq in pos)-(freqs in neg) of the entities occurring in that text n_ent_found = sum(tf_row) if n_ent_found > 0: score = sum(tf_row * freq_matrix[entities])/n_ent_found else: score = 0 return score
def extract_pipeline_config(pipeline): """Extracts the configuration entities of a pipeline :param pipeline: Pipeline configuration entity :type pipeline: dict :returns: The configuration entities of pipeline :rtype: dict """ return list(pipeline.values())[0]
def check(program_out,expected_out): """ User can edit this function for check if the output is correct. By default this function will return "PASSED" if program output exactly matches to expected output. User needs to edit this function for problems where Multiple Correct Outputs are accepted. """ if(program_out==expected_out): return "PASSED" return "FAILED"
def times(number): """provides a range() like template filter to iterate over integer values. from :https://stackoverflow.com/questions/1107737 """ return range(1, number + 1)
def solution(A): """Count the number of pairs of cars that pass each other. Each element in A[k] represents a car at position k moving in direction: (1) right-bound if A[k] = 0 (2) left-bound if A[k] = 1 Args: A (list): A list of cars at positions k moving in directions A[k]. Returns: int: The total pairs of passing cars. If the number exceeds 1e9, returns -1. Complexity: Time: O(N) Space: O(1) """ n_pairs = 0 right_bound = 0 for direction in A: if n_pairs > 1e9: return -1 if direction == 0: right_bound += 1 else: n_pairs += right_bound return n_pairs
def toSignature(s): """ transform wsdl address to valid package signature """ # cannot have ':' in package name return 'SUDS#' + s.replace(':', '$')
def extract_evidence_id(condition): """Extracts the id of the evidence resource linked to the Condition. In this demo, the evidence is always a QuestionnaireResponse, which is the only evidence and set on the detail field. Example resource: { ... "evidence":[ { "detail":[ {"reference":"QuestionnaireResponse/ab376d48-5fdc-4876-9441-c68cf59a8431"} ] } ], "resourceType":"Condition", ... } """ return condition['evidence'][0]['detail'][0]['reference']
def check_palindrome(string): """ Question 7.5: Check palindromicity of string """ begin = 0 end = len(string) - 1 while begin < end: while not string[begin].isalnum() and begin < end: begin += 1 while not string[end].isalnum() and begin < end: end -= 1 if string[begin].lower() != string[end].lower(): return False begin += 1 end -= 1 return True
def reduceCategories(events): """:Description: Legacy Facebook events have old categories that are consolidated, OTHER will be discarded from the training data""" categoryMapping = { u'BOOK': u'LITERATURE', u'COMEDY': u'COMEDY_PERFORMANCE', u'CLASS': u'OTHER', u'DINING': u'FOOD', u'FAMILY': u'OTHER', u'FESTIVAL': u'PARTY', u'FOOD_TASTING': u'FOOD', u'FUNDRAISER': u'CAUSE', u'LECTURE': u'OTHER', u'MOVIE': u'FILM', u'NEIGHBORHOOD': u'OTHER', u'NIGHTLIFE': u'OTHER', u'RELIGIOUS': u'RELIGION', u'VOLUNTEERING': u'CAUSE', u'WORKSHOP': u'OTHER' } for e in events: category = e['category'] if category in categoryMapping: e['category'] = categoryMapping[category] reducedEvents = [e for e in events if e['category'] != u'OTHER'] return reducedEvents
def create_html_email_template(data): """ Creates the HTML Email Template""" return f""" <p><strong>Company</strong>: {data.get('company')}</p> <p><strong>Contact Name</strong>: {data.get('contact_name')}</p> <p><strong>Email</strong>: {data.get('email')}</p> <p><strong>Phone</strong>: {data.get('phone')}</p> <p><strong>Hackathon Idea</strong>:<br> {data.get('description')}</p> """
def trial_success(boutlist): """Takes list of times of bouts in seconds, returns bool of whether the mouse managed to get the tape off in time. """ if boutlist[-1] == 300: success = False else: success = True return success
def toggles_block_quote(line): """Returns true if line toggles block quotes on or off (i.e. finds odd number of ```)""" n_block_quote = line.count("```") return n_block_quote > 0 and line.count("```") % 2 != 0
def root_of_closest_perfect_square(n): """ http://stackoverflow.com/questions/15390807/integer-square-root-in-python """ x = n y = (x + 1) // 2 while y < x: x = y y = (x + n // x) // 2 return x
def cfact(n: int) -> int: """ >>> cfact(5) 120 """ if n == 0: return 1 return n*cfact(n-1)
def combine_lines(lines): """ Combines the stings contained in a list into a single string. """ new = '' for each in lines: new = new + each return new
def get_cred_fh(library: str) -> str: """ Determines correct SimplyE credential file """ if library == "BPL": return ".simplyE/bpl_simply_e.yaml" elif library == "NYPL": return ".simplyE/nyp_simply_e.yaml" else: raise ValueError("Invalid library code passsed")
def is_proper(str): """Tests if a set of parentheses are properly closed. >>> is_proper('()(())') # regular doctests True >>> is_proper('(()()') # too many open parens False >>> is_proper('())') # too many close parens False >>> is_proper('())(') # parens don't match False """ try: parens = [] for c in str: if c == '(': parens.append(c) # > [1, 2, 3].pop() => 3 else: parens.pop() # > [1, 2, 3].pop(0) => 3 return len(parens) == 0 except IndexError: return False
def get_mse_sorted_norm(series1, series2): """ sorted and normalized series length has to be equal """ assert len(series1) == len(series2) mse = 0.0 max_v = max(series1) if max_v == 0.0: # difference is equa series2 return sum((value * value for value in series2))/len(series1) s1 = tuple((value/max_v for value in sorted(series1))) s2 = tuple((value/max_v for value in sorted(series2))) for index, data1 in enumerate(s1): diff = (data1 - s2[index]) mse += diff * diff mse /= len(series1) return mse
def clean_pci_read_output(output: str): """ Cleans the output from the "pci_read" function. This essentially only means, that all the newlines and the leading whitespaces are being removed. :param output: The output message of the "pci_read" function :type output: str :return: """ # Removing the newlines cleaned = output.replace('\n', '') # Removing the whitespaces in the front cleaned = cleaned.lstrip(' ') return cleaned
def tokenize(lines, token='word'): #@save """Split sentences into word or char tokens.""" if token == 'word': return [line.split(' ') for line in lines] elif token == 'char': return [list(line) for line in lines] else: print('ERROR: unknown token type '+token)
def quote_identifier(identifier, sql_mode=""): """Quote the given identifier with backticks, converting backticks (`) in the identifier name with the correct escape sequence (``). Args: identifier (string): Identifier to quote. sql_mode (Optional[string]): SQL mode. Returns: A string with the identifier quoted with backticks. """ if len(identifier) == 0: return "``" if "ANSI_QUOTES" in sql_mode: return '"{0}"'.format(identifier.replace('"', '""')) return "`{0}`".format(identifier.replace("`", "``"))
def updatedf(x,setval): """ update the negative values to requested value :param name: each row of the column setval: value to be set :return: updated value of the row for the column """ if x < 0 : x=setval return x
def tostr(st): """Return normal quoted string.""" if not st: return None try: st = str(st) except UnicodeEncodeError: st = st.encode("utf-8") return st
def expand_position(position, length=4): """Take a tuple with length <= 4 and pad it with ``None``'s up to length. Example, if ``length=4`` and ``position=(1, 0)``, then the output is ``(1, 0, None, None)``. """ new_position = tuple(position) + (None,) * (length-len(position)) return new_position
def get_straights(edge): """ Get vectors representing straight edges """ return [v for v in edge if v[0] == 0 or v[1] == 0]
def fstatus(plus, minus, lines): """ returns git file change status in three digit string """ status = [] if plus == 0: status.append('0') else: status.append('1') if minus == 0: status.append('0') else: status.append('1') if lines == 0: status.append('0') else: status.append('1') if len(status) == 3: return str().join(status)
def _messageForError(status: int): """ Return a description string for an HTTP error code """ errors = { 500: 'Internal server error', 503: 'Service temporarily unavailable', 598: 'Network read timeout error' } return errors[status]
def construct_conn_msg(stream, lines=None, protocol_opts=None): """Return a connnection message :param stream: stream name :param lines: number of messages to consume :param protocol_opts: optional arguments """ connection_msg = stream if lines: connection_msg += ' {0}'.format(lines) if protocol_opts: connection_msg += ''.join([' {0}={1}'.format(k, v) for k, v in protocol_opts.items()]) return connection_msg + '\n'
def readme_name(repo): """Given a repo, return the name of the readme file.""" if repo == "libcxx": return "LICENSE.TXT" return "README.txt"
def initial_velocity(final_velocity, acceleration, time): """ Calculates the initial_velocity when given final_velocity, acceleration and time Parameters ---------- final_velocity : float acceleration : float time : float Returns ------- float """ return final_velocity - acceleration * time
def last_base_slope(c0, c1, a0, a1): """Calculate slope of line""" dy = c1 - c0 dx = a1 - a0 return dy / dx
def get_counties_with_deaths_today(counties_list, date): """ :param counties_list: :return: """ # counties with deaths today today_list = [] for county in counties_list: if county[0] == date: today_list.append(county) return today_list
def int2padstr(int_val): """ :param int_val: :return: """ if int_val < 10: return str(int_val).zfill(2) else: return str(int_val)
def positive_response_id(service_id: int) -> int: """Given a service ID of a request, return the corresponding SID for a positive response""" assert service_id != 0x7f - 0x40 return service_id + 0x40
def _drop_keys_with_none_values(main_dict: dict): """ Drop keys with None values to parse safe dictionary config """ return {k: v for k, v in main_dict.items() if v is not None}
def format_response(code = 0, data = {}, info = 'ok'): """ format response :param code: return status code :param data: return data :param info: return hint message :return :class:`dict` :rtype: dict """ return { "code": code, "data": data, "info": info }
def reverseString(s): """reverse string >>> reverseString('abc') 'cba' """ return s[::-1]
def convert_kv_to_dict(data): """ convert text values in format: key1=value1 key2=value2 to dict {'key1':'value1', 'key2':'value2'} :param data: string containing lines with these values :return: dict """ output = {} for line in data.split("\n"): stripped = line.strip() if stripped: key, value = stripped.split("=", 1) output[key] = value return output
def robot_tidy_one(angents, self_state, self_name, cube): """ @param angents: @param self_state: @param self_name: @param cube: @return: @ontology_type cube: Cube """ return [("robot_tell_human_to_tidy", "human", cube), ("robot_wait_for_human_to_tidy", "human", cube)]
def calculate(not_to_exceed): """Returns the sum of the even-valued terms in the Fibonacci sequence whose values do not exceed the specified number""" answer = 0 term_one = 1 term_two = 2 while term_two < not_to_exceed: if not term_two % 2: answer += term_two next_term = term_one + term_two term_one = term_two term_two = next_term return answer
def _format(payload): """Format the payload (variables) as a string. When logging to the terminal or a file, only the string message is logged. This converts the payload into a string, which can then be appended to the log message itself. :param dict payload: The variable payload. :returns string: The formatted payload message. """ message = '' for key in payload.keys(): message += '\n`{}`: {}'.format(key, payload[key]) return message
def kwargsGet(kwargs, key, replacement): """As kwargs.get but uses replacement if the value is None.""" if key not in kwargs: return replacement elif key in kwargs and kwargs[key] is None: return replacement else: return kwargs[key]
def _middle(values): """Lower bound of median, without using numpy (heavy reqs)""" n = len(values) is_odd = n % 2 middle_idx = int((n + is_odd) / 2) - 1 return sorted(values)[middle_idx]
def add_friend(person, person2) -> None: """ Adds a person to this functional persons friends list """ person['friends'].append(person2) return person
def trim_url(url): """Removes extra punctuation from URLs found in text. :param str url: the raw URL match :return str: the cleaned URL This function removes trailing punctuation that looks like it was not intended to be part of the URL: * trailing sentence- or clause-ending marks like ``.``, ``;``, etc. * unmatched trailing brackets/braces like ``}``, ``)``, etc. It is intended for use with the output of :py:func:`~.search_urls`, which may include trailing punctuation when used on input from chat. """ # clean trailing sentence- or clause-ending punctuation while url[-1] in '.,?!\'":;': url = url[:-1] # clean unmatched parentheses/braces/brackets for (opener, closer) in [('(', ')'), ('[', ']'), ('{', '}'), ('<', '>')]: if url[-1] == closer and url.count(opener) < url.count(closer): url = url[:-1] return url
def format_imm(raw): """Format one of the singleton immediate values.""" tag = (raw >> 3) & 0x3 if tag == 0: return "True" if raw & 0x20 else "False" return ("NotImplemented", "Unbound", "None")[tag - 1]
def getSlice(m,wdcad): """ Get slice Parameters ---------- m : middle index (center of the slice). wdcad : width of slice list (units of cadence). """ return slice( m-wdcad/2 , m+wdcad/2 )
def fromHex(data,offset=0,step=2): """ Utility function to convert a hexadecimal string to buffer """ return bytearray([ int(data[x:x+2],16) for x in range(offset,len(data),step) ])
def _matches_version(actual_version, required_version): """Checks whether some version meets the requirements. All elements of the required_version need to be present in the actual_version. required_version actual_version result ----------------------------------------- 1 1.1 True 1.2 1 False 1.2 1.3 False 1 True Args: required_version: The version specified by the user. actual_version: The version detected from the CUDA installation. Returns: Whether the actual version matches the required one. """ if actual_version is None: return False # Strip spaces from the versions. actual_version = actual_version.strip() required_version = required_version.strip() return actual_version.startswith(required_version)
def win_safe_name(cityname): """Edit the string so that it can be used as a valid file name in Windows. """ cityname = cityname.strip() if cityname.endswith("."): cityname = cityname[:-1] + "_" for chr in cityname: if chr in ("<", ">", ":", "/", "\\", "|", "?", "*", "\""): cityname = cityname.replace(chr, "_") return cityname
def pad_or_trim_sentence(sentence, max_sentence_length, padding_word="<PAD/>"): """ Pads all sentences to the same length. The length is defined by the longest sentence. Returns padded sentences. Credits: Ana Marasovic (marasovic@cl.uni-heidelberg.de) """ if len(sentence)>max_sentence_length: new_sentence = sentence[:max_sentence_length] elif len(sentence) < max_sentence_length: num_padding = max_sentence_length - len(sentence) new_sentence = sentence + [padding_word] * num_padding else: new_sentence = sentence[:] return new_sentence
def compute_loss_packet_count(overall_packets, lost_packets): """ Compute loss percentage based on the number of lost packets and the number of overal packets. """ if overall_packets != 0: loss = (lost_packets / overall_packets)*100 else: return 100 return loss if loss >=0 else 0
def no_parens(s): """Delete parenteses from a string Args: s (str): String to delete parentheses from Returns: str: Input without any opening or closing parentheses. """ return s.replace('(','').replace(')','')
def digits_are_unique(n): """Returns whether digits in n are unique (and no 0)""" digits = set([int(d) for d in str(n)]) if 0 in digits: return False return len(str(n)) == len(digits)
def password(password_str): """Checks if password length is greater than 4, else raises error""" if len(password_str) > 4: return password_str else: raise ValueError('Invalid password')
def getUrlWithoutScheme(url: str): """Get the target url without scheme @type url: str @param url: The target URL @returns str: The url without scheme """ return url[(url.index('://')+3):]
def lr_schedule(epoch): """Learning Rate Schedule Learning rate is scheduled to be reduced after 80, 120, 160, 180 epochs. Called automatically every epoch as part of callbacks during training. :param epoch (int): The number of epochs :return lr (float32): learning rate """ lr = 1e-3 if epoch > 180: lr *= 0.5e-3 elif epoch > 160: lr *= 1e-3 elif epoch > 120: lr *= 1e-2 elif epoch > 80: lr *= 1e-1 print('Learning rate: ', lr) return lr
def reverse(s): """ :param s: :return: """ return s[::-1]
def threept_center(x1, x2, x3, y1, y2, y3): """ Calculates center coordinate of a circle circumscribing three points Parameters -------------- x1: `double` First x-coordinate x2: `double` Second x-coordinate x3: `double` Third y-coordinate y1: `double` First y-coordinate y2: `double` Second y-coordinate y3: `double` Third y-coordinate Returns ---------- double, double: Returns center coordinates of the circle. Return None, None if the determinant is zero """ determinant = 2*( (x3-x2)*(y2 - y1) - (x2 - x1)*(y3-y2) ) if determinant < 0.1: return None, None x_numerator = (y3 - y2)*(x1**2 + y1**2) + (y1 - y3)*(x2**2 + y2**2) + (y2 - y1)*(x3**2 + y3**2) y_numerator = (x3 - x2)*(x1**2 + y1**2) + (x1 - x3)*(x2**2 + y2**2) + (x2 - x1)*(x3**2 + y3**2) xc = x_numerator/(2*determinant) yc = -y_numerator/(2*determinant) return xc, yc
def zip_tuple(a_tuple): """Zip a tuple of tuple pairs into a tuple (cached) >>> zip_tuple((('hi', 123), ('hello', 321))) (('hi', 'hello'), (123, 321)) """ tuple1, tuple2 = zip(*a_tuple) return tuple1, tuple2
def _cons_trits(left: int, right: int) -> int: """ Compares two trits. If they have the same value, returns that value. Otherwise, returns 0. """ return left if left == right else 0
def bin2int(arr): """Convert binary array to integer. For example ``arr`` = `[1, 0, 1]` is converted to `5`. Input ----- arr: int or float An iterable that yields 0's and 1's. Output ----- : int Integer representation of ``arr``. """ if len(arr) == 0: return None return int(''.join([str(x) for x in arr]), 2)
def create_logdir(model_name, dataset, K, v, KNN, l1, l2, l3): """ Directory to save training logs, weights, biases, etc.""" return "train_logs/{}/{}_KNN{}_K{}_v{}_l1{}_l2{}_l3{}".format(model_name, dataset, KNN, K, v, l1, l2, l3)
def member_name(n): """ Formats a version of the name for use as a C# member variable. @param n: The attribute name to format in variable style. @type n: string @return The resulting valid C# variable name @rtype: string """ if n == None: return None if n == 'ARG': return 'ARG' n2 = '' lower = True for i, c in enumerate(n): if c == ' ': lower = False elif (('A' <= c) and (c <= 'Z')) or (('a' <= c) and (c <= 'z')) or (('0' <= c) and (c <= '9')): if lower: n2 += c.lower() else: n2 += c.upper() lower = True elif c == '\\': # arg member access operator n2 += '.' else: n2 += '_' lower = True return n2
def ansible_stdout_to_str(ansible_stdout): """ The stdout of Ansible host is essentially a list of unicode characters. This function converts it to a string. Args: ansible_stdout: stdout of Ansible Returns: Return a string """ result = "" for x in ansible_stdout: result += x.encode('UTF8') return result
def normalize(block): """ Normalize a block of text to perform comparison. Strip newlines from the very beginning and very end Then split into separate lines and strip trailing whitespace from each line. """ assert isinstance(block, str) block = block.strip('\n') return [line.rstrip() for line in block.splitlines()]
def clean_field(value): """ Strip whitespace, cast empty -> None. Args: value (str): The field value. Returns: list: The cleaned tokens. """ return (value.strip() or None) if value else None
def repeated(f, n, x): """Returns the result of composing f n times on x. >>> def square(x): ... return x * x ... >>> repeated(square, 2, 3) # square(square(3)), or 3 ** 4 81 >>> repeated(square, 1, 4) # square(4) 16 >>> repeated(square, 6, 2) # big number 18446744073709551616 >>> def opposite(b): ... return not b ... >>> repeated(opposite, 4, True) True >>> repeated(opposite, 5, True) False >>> repeated(opposite, 631, 1) False >>> repeated(opposite, 3, 0) True """ counter = 1 value = f(x) while (counter < n): value = f(value) counter += 1 return value
def to_camel_case(source: str) -> str: """Converts kebab-case or snake_case to camelCase.""" parts = source.replace("-", "_").split("_") return "".join([parts[0], *[p.capitalize() for p in parts[1:]]])
def paths(m, n): """Return the number of paths from one corner of an M by N grid to the opposite corner. >>> paths(2, 2) 2 >>> paths(5, 7) 210 >>> paths(117, 1) 1 >>> paths(1, 157) 1 """ "*** YOUR CODE HERE ***" if m is 1: # if m is 1 then we have a grid the size of 1 x n. any grid with a size 1 for any axis means we have only one path left so return 1 return 1 elif n is 1: return 1 x = m - 1 # get the next size down on the m axis y = n - 1 # get the next size down on the n axis return paths(x, n) + paths(m, y)
def _path_to_name(path): """ Internal function to turn a path into an endpoint name """ return " > ".join(elem.title().replace("-", " ").replace("_", " ") for elem in str(path).split("/"))
def toHours(spec): """spec is of the form '08:00-10:00' """ return (int(spec[0:2])+int(spec[3:5])/60.0, int(spec[6:8])+int(spec[9:11])/60.0)
def create_help(header, options): """Create formated help Args: header (str): The header for the help options (list[str]): The options that are available for argument Returns: str: Formated argument help """ return "\n" + header + "\n" + \ "\n".join(map(lambda x: " " + x, options)) + "\n"
def parse_num(n): """ :param n: str Number to parse :return: float Parses numbers written like 123,949.99 """ m = str(n).strip().replace(".", "").replace(",", ".") return float(m)