content
stringlengths
39
9.28k
sha1
stringlengths
40
40
id
int64
8
710k
def create_non_8021Q_vea_cmd(lpar_id, slot_num, port_vlan_id): """ Generate HMC command to create a non-8021Q virtual ethernet adapter :param lpar_id: LPAR id :param slot_num: virtual adapter slot number :param port_vlan_id: untagged port vlan id :returns: A HMC command to create a non 8021Q veth adapter based on the specification from input. """ return ("chhwres -r virtualio --rsubtype eth -o a -s %(slot)s " "--id %(lparid)s -a ieee_virtual_eth=0,port_vlan_id=%(pvid)s," "is_trunk=1,trunk_priority=1" % {'slot': slot_num, 'lparid': lpar_id, 'pvid': port_vlan_id})
a3ede365325f9eec46316546c566b6fbf1882604
500,684
import string def decode_labels(encoded_labels: list) -> str: """ Decodes predictions to their string equivalent :param encoded_labels: List of encoded predictions :return: Str of decoded predictions """ labels = string.digits + string.ascii_uppercase + "." + "+" + "-" + "?" text = "" for x in encoded_labels: text += labels[x] return text
e9e3557eb49910a5f834eb2b815b01e235c9940e
283,806
def dt_calc(etime): """Returns an interval of time that increased as the ellapsed time etime increases""" if etime <= 10: return 0.25 elif etime <= 60: return 0.5 elif etime <= 120: return 1.0 elif etime <= 300: return 5.0 elif etime <= 3600: return 10.0 else: return 60.0
9f8b7d5d07e336287674e2d5cd044f9a0bf752f9
476,551
def idify(string: str): """ Converts a string to a format suitable for HTML IDs eg 'Add goods' becomes 'add_goods' """ return string.lower().replace(" ", "_")
ebe3279e0fc10cf0bfe97e0d5a8ab070291629cb
311,962
def min_with_none(x_seq): """Find the minimum in a (possibly empty) sequence, ignoring Nones""" xmin = None for x in x_seq: if xmin is None: xmin = x elif x is not None: xmin = min(x, xmin) return xmin
f85f115f29a625eea967d2fe483c27e74aadf81c
416,114
def select_daily_mean(daily_mean, gw_data): """ Select the lakes in the daily_mean file that are retained in the final growth window. Input: daily_mean: dataframe with all compiled daily mean water quality data gw_data: growth window dataframe (output from the growth_window_means function) Output: selected_daily_mean: Dataframe of daily mean data for all lakes within the growth window dataset """ final_lakes_list = gw_data.lake.unique() boolean_series = daily_mean.lake.isin(final_lakes_list) selected_daily_mean = daily_mean[boolean_series] return selected_daily_mean
331bead7dcbe17086f52b247f807be87d5fe0e43
44,607
import random def generate_random_seed(project_parameter): """ Generate random seed for project parameters Args: project_parameter (dict): Returns: dict: The project parameters dictionary including the key 'seed' """ if "seed" not in project_parameter.keys(): project_parameter["seed"] = random.randint(0, 99999) return project_parameter
a6047689de5a585f915a01b478dbd048d1ca67d4
209,206
def buscar_posicion_minimo(lista, i): """Devuelve la posición del elemento mínimo en lista[i:]""" posicion_minimo = i while i < len(lista): if lista[i] < lista[posicion_minimo]: posicion_minimo = i i += 1 return posicion_minimo
2a2feb608fb8b0e52ea6f38da690f432eed7d26f
631,585
import torch def _psnr(input, target, normalization='max'): """ This function is a torch implementation of skimage.metrics.compare_psnr Parameters ---------- input : torch.Tensor target : torch.Tensor norm : either max or mean Returns ------- torch.Tensor """ input_view = input.reshape(-1) target_view = target.reshape(-1) if normalization == 'mean': maximum_value = torch.mean(input_view) else: maximum_value = torch.max(input_view) mean_square_error = torch.mean((input_view - target_view) ** 2) psnrs = 20.0 * torch.log10(maximum_value) - 10.0 * torch.log10(mean_square_error) return psnrs
58ae2615ab77d3deff68310638e122afdab9a061
255,946
from typing import Union import requests def validate_request_success(resp: Union[requests.Response, str]): """ Validate the response from the webhook request """ return not isinstance(resp, str) and resp.status_code in [200, 201]
13fa27f2c71780f7f33a62ff767eccae45722b91
673,028
def tds_quote_id(ident): """ Quote an identifier :param ident: id to quote :returns: Quoted identifier """ return '[{0}]'.format(ident.replace(']', ']]'))
c85cba28fe3b9d7791cc8541e42356f8088e1207
466,422
def read_file_to_lines(filename): """ Reads an input filename and process it into a list of strings representing the lines of input. :param filename: File to read :return: List of string """ with open(filename) as reader: return reader.read().split('\n')
d4e35687f226582fac378e5a16c736fe4a26d34e
372,972
def _remove_duplicate_folders(folder_list): """Removes duplicate folders from a list of folders and maintains the original order of the list Args: folder_list(list of str): List of folders Returns: list of str: List of folders with duplicates removed """ new_folders_set = set() new_folders_list = [] for folder in folder_list: if folder not in new_folders_set: new_folders_set.add(folder) new_folders_list.append(folder) return new_folders_list
17243262bcbe9ff46e0b4d55b786fb22946fc892
386,870
def _http_400(start_response): """Responds with HTTP 400.""" start_response('400 Bad Request', [('Content-Length', '0')]) return []
73017c350321b5c190f27c12bbe63ec64bc1337b
299,182
import re def configMultiEntry (lineData, configSection): """ Search for section and return list of strings of the multiply entry lines after section heading """ sectionContentsStringList = [] error='NONE' sectionfound = 0 for line in lineData: #print(line) if sectionfound is 0: if re.match(configSection, line): sectionfound = 1 #print(line2 + "\n") # section found get data until empty line else: if line is '': break else: sectionContentsStringList.append(line) #print(line2) if sectionfound is 0: error = "Section " + configSection + " not found" return error, sectionContentsStringList
96530d70b27a760b87bfa27a51c16dbd0a238679
235,343
def _get_user_display_name(user): """Return a human-friendly display name for a user.""" # An anonymous user has no display name if user.is_anonymous: return '' # Form display name by concatenating first and last names and stripping whitespace display_name = user.get_full_name().strip() # If the display name is empty, use the username instead if display_name == '': return user.username return display_name
dfd8572893bb5c491d2b6c16e07975f6a141b235
669,067
def ktau_weighted_distance(r_1, r_2): """ Computes a weighted kendall tau distance. Runs in O(n^2) Args: r_1, r_2 (list): list of weighted rankings. Index corresponds to an item and the value is the weight Entries should be positive and sum to 1 Example: r_1 = [0.1, 0.2, 0.7] Returns: float >= 0 representing the distance between the rankings """ # confirm r_1 and r_2 have same lengths if len(r_1) != len(r_2): raise ValueError("rankings must contain the same number of elements") distance = 0 for i in range(len(r_1) - 1): for j in range(i, len(r_1)): r_1_order = r_1[i] - r_1[j] r_2_order = r_2[i] - r_2[j] # check if i and j appear in a different order if r_1_order * r_2_order < 0: weight = r_1[i] * r_1[j] * r_2[i] * r_2[j] distance += 1 * weight return distance
ec04adb26c084a0c49f3004742893faa86c55fab
441,273
def IoA(poly1, poly2): """ Intersection-over-area (ioa) between two boxes poly1 and poly2 is defined as their intersection area over box2's area. Note that ioa is not symmetric, that is, IOA(poly1, poly2) != IOA(poly1, poly2). :param (shapely.geometry.Polygon) poly1: Polygon1 :param (shapely.geometry.Polygon) poly2: Polygon2 :return: (float) IoA between poly1 and poly2 """ return poly1.intersection(poly2).area / poly1.area
4960e10b486f6cf80ee2ea8bc1caa99ebf30fb5b
242,567
import re def multi_replace(text, d): """ Takes a dictionary pattern -> substitution and applies all substitutions to text """ s = text for key in d: s = re.sub(key, d[key], s) return s
73367f611dccce39c82ff49c8724c7e1705bb888
458,399
def is_code_line(line): """A code line is a non empty line that don't start with #""" return line.strip()[:1] not in {'#', '%', ''}
558a37d8a30f20d75f5dcc9b72e82f5981e6f84b
291,996
def to_identifier(name): """Convert name to an identifier (upper snake case) Args: string: a string to be converted to an identifier Returns: a string in upper snake case """ return name.replace(' ', '_').upper()
39d7d3804e8a6b59dc46efb271197ee7882e805b
549,840
def get_tag(instance): """ Get the tag associated with the instance, if there is one. """ return getattr(instance, '_tag', None)
8df7540a12beb3eff634aad983374cce60fba56a
212,301
def clean_headers(headers): """ Sanitize a dictionary containing HTTP headers of sensitive values. :param headers: The headers to sanitize. :type headers: dict :returns: A list of headers without sensitive information stripped out. :rtype: dict """ cleaned_headers = headers.copy() authorization_header = headers.get("Authorization") if authorization_header: sanitized = "****" + authorization_header[-4:] cleaned_headers["Authorization"] = sanitized return cleaned_headers
4e375db09ad38cff145344a38225a38c75a98e85
354,993
def dot(xx:list,yy:list): """ Dot product of two lists. >>> dot([1,2,3],[4,5,6]) 32 """ return sum([x*y for (x,y) in zip(xx,yy)])
21bdeafc0a53af3f30b1ca354a33def5c5c16c59
220,991
def complete_cases(_data): """Return a logical vector indicating values of rows are complete. Args: _data: The dataframe Returns: A logical vector specifying which observations/rows have no missing values across the entire sequence. """ return _data.apply(lambda row: row.notna().all(), axis=1).values
3e6e294f11988d04fd1c3d7d46b409badf1f90f9
678,727
def massage_key(key): """Massage the keybase return for only what we care about""" return { 'fingerprint': key['key_fingerprint'].lower(), 'bundle': key['bundle'] }
229cf81b90e9d4602ad2e25f7cc6fcea6afd12e8
56,590
def separate_particles(samples, index=None): """Get particle coordinates from array (just reshape the array) Args: samples (array_like): [N_samples, 2xN_particles] index (int, optional): Where to split, (usually at the half of the array). Defaults to None. Returns: px (array_like): [N_samples, N_particles] first coordinate of the particles py (array_like): [N_samples, N_particles] second coordinate of the particles """ if index is None: index = int(len(samples.shape[1])/2) px = samples[:, :index] py = samples[:, index:] return px, py
1c2074c168a668157fc34349cc02c6be7f1a82f2
553,778
import math def cs_h(c, R): """Height of the circular segment, given its radius R and chord length c See: [http://en.wikipedia.org/wiki/Circular_segment] """ if c >= 2*R: print('WARNING: the chord is greater than the diameter!') print('WARNING: returning maximum height, the radius') return R else: return R - math.sqrt( R**2 - (c**2/4) )
8ac19c5703a35953135ff0730130aa76926df2e2
417,184
import redis def log_to_redis(host="localhost", port=6379, dbn=11): """Record the tuning record to a redis DB. Parameters ---------- host: str, optional Host address of redis db port: int, optional Port of redis db dbn: int, optional which redis db to use, default 11 """ # import here so only depend on redis when necessary red = redis.StrictRedis(host=host, port=port, db=dbn) def _callback(_, inputs, results): """Callback implementation""" for inp, result in zip(inputs, results): red.set(inp, result) return _callback
893849c368705f3bad05701012bfa246bc0eacdf
289,502
from typing import List from typing import Dict def get_images(ecr_client, repository_name: str) -> List[Dict]: """Get all images from a repository.""" return ecr_client.list_images(repositoryName=repository_name)["imageIds"]
26cfab58ed3d16767df43c1f7972f28d81ffc557
181,394
def parse_hal_spikes(hal_spikes): """Parses the tag information from the output of HAL Parameters ---------- hal_spikes: output of HAL.get_spikes() (list of tuples) Returns a nested dictionary: [pool][neuron] = list of (times, 1) tuples The 1 is for consistency with the return of parse_hal_tags """ parsed_spikes = {} for time, pool, neuron in hal_spikes: if pool not in parsed_spikes: parsed_spikes[pool] = {} if neuron not in parsed_spikes[pool]: parsed_spikes[pool][neuron] = [] parsed_spikes[pool][neuron].append((time, 1)) return parsed_spikes
fb1faba1c10845331bc2e526bbd5553289be2be7
36,641
import re def parse_kernel_monitor(output): """Parse the thread monitor output and return the parsed data as a dictionary with thread names as keys. """ re_thread = re.compile(r'(.*)\s+([\d\.]+)') threads = {} for line in output.splitlines(): mo = re_thread.match(line) if mo: name = mo.group(1).strip() threads[name] = float(mo.group(2)) return threads
9c5437b2d4b506fe57d48aa647940dc249ac110f
349,878
def toBytes(b): """ Converts a string to a bytes object by encoding it as utf-8. """ if type(b) == str: return b.encode("utf-8") else: return b
29912d7cbc75c7d7a6b4e73bf3b7a4935699ef68
629,226
def produce_inter_times(timestamps, max_filter=None): """ Produces a list of the ordered timespans in seconds between epoch timestamps. Args: timestamps: list of positive numbers representing epoch time stamps in seconds. Returns: inter_times: list of time invervals (in seconds) between the values in timestamps. """ inter_times = [] last_t=None for t in timestamps: if (not last_t is None) and (not t is None): if t<last_t: raise ValueError("Timestamps are not increasing!") if t!=0 and last_t!=0: if max_filter is None or t-last_t<=max_filter: inter_times.append((t-last_t)) last_t=t return inter_times
e7b91435dd4bfe24cd02f81c759872e9bd4ed359
111,507
import pickle def pickle_load(path): """Un-pickles a file provided at the input path Parameters ---------- path : str path of the pickle file to read Returns ------- dict data that was stored in the input pickle file """ with open(path, 'rb') as f: return pickle.load(f)
8d68e349118eb2fa2d5c1ce5b31b65cbc29a382f
686,268
def confirm_yorn(prompt_msg: str) -> bool: """Prompts the user for a yes or no answer.""" confirm_input: str = input(prompt_msg) return confirm_input.lower()[0] == "y"
f537126becd483a427d179b4afbe54386629b6af
208,331
def flatten(lst_of_lst): """ Flatten list of list objects. """ lst = [] for l in lst_of_lst: if isinstance(l, list): lst += flatten(l) else: lst.append(l) return lst
589d31f3999ffbfaa0b065357976462500fa9838
604,851
def index_in_str(text, substring, starting=0): """ Gets index of text in string :arg text: text to search through :arg substring: text to search for :arg starting: offset :return position """ search_in = text[starting:] if substring in search_in: return search_in.index(substring) else: return -1
397ffb9e5e6e0235e77b2deaa1ab03dbc84810ad
469,371
def combine_meta_classes(*args, **kwargs): """ Combine multiple metaclasses into one. When a class hierarchy employs metaclasses the subclasses metaclass must always be a subclass of the parents metaclass. This function combines multiple metaclasses into one. Suppose you have two metaclasses Meta_A(type) and Meta_B(type) and the following class hierarchy: .. code-block:: python class Meta_A(type): pass class Meta_B(type): pass class A(object, metaclass=Meta_A): pass class B(object, metaclass=Meta_B): pass Class B will raise an error, as Meta_B must be a subclass of the parents subclass which is Meta_A. This can be solved by defining Meta_B as: .. code-block:: python class Meta_B(Meta_A): pass Since this is not always wanted, e.g., if you want to use Meta_B in file hierarchies where Meta_A is not used, you may use this function to create a combined metaclass: .. code-block:: class B(object, metaclass=combine_meta_classes(Meta_B, Meta_A)) pass """ return type('Combined(%s)' % ', '.join(map(lambda c: c.__name__, args)), tuple(args), kwargs)
e945aa12f52861fe939c19e3bbb29bc757c8f9a3
516,479
import torch def pcorrect(out, tilt): """Compute proportion of stimuli classified correctly from network output Args: out (torch.Tensor): output of network for each stimulus, i.e. the predicted probability of each stimulus being tilted right tilt (torch.Tensor): true tilt of each stimulus (1. for tilt right, 0. for tilt left) Returns: float: proportion of stimuli classified correctly """ out_tilt = (out > 0.5).type(torch.float) # predicted tilt label: 1. for tilt right, 0. for tilt left (make sure to convert to float!) return (tilt == out_tilt).type(torch.float).mean().item()
7d051c2ebb2e4850553e6846e828d57f3c5890c9
212,147
def should_concat(prev_type, cur_type): """This function contains the logic deciding if the current node should be grouped with the previous node in the same notebook cell. Args: prev_type: (str) type of the previous node. cur_type: (str) type of the current node. Returns A Boolean """ concat_types = ['Import', 'ImportFrom', 'Assign'] import_types = ['Import', 'ImportFrom'] if prev_type == cur_type and cur_type in concat_types: return True if prev_type in import_types and cur_type in import_types: return True return False
f91e4026f376906b42e5a0182e1ca42e7e285b9e
496,267
def arg_range(arg, lo, hi): """ Given a string of the format `[int][-][int]`, return a list of integers in the inclusive range specified. Open intervals are allowed, which will be capped at the `lo` and `hi` values given. If `arg` is empty or only contains `-`, then all integers in the range `[lo, hi]` will be returned. """ arg = arg.strip() if len(arg) == 0 or arg == '-': return range(lo, hi+1) if '-' not in arg: return [int(arg)] start, end = map(str.strip, arg.split('-')) if len(start) == 0: return range(lo, int(end)+1) elif len(end) == 0: return range(int(start), hi+1) else: return range(int(start), int(end)+1)
77dda7ac1fb3ad3f05aa50ac01045565e0bb426b
56,952
def partition(iterable, pivot, key): """Returns 3 lists: the lists of smaller, equal and larger elements, compared to pivot. Elements are compared by applying the key function and comparing the results""" pkey = key(pivot) less = [] equal = [] greater = [] for x in iterable: k = key(x) if k < pkey: less.append(x) elif k == pkey: equal.append(x) else: greater.append(x) return less, equal, greater
122b88af683f80dee8d31a026b931fcebc318bf9
527,441
def insertion_sort(alist): """ Returns the history of running the insertion sorting algorithm on a list of numbers, i.e. saves the state of the list after each step of the algorithm. """ history = [alist[:]] for index in range(1,len(alist)): currentvalue = alist[index] position = index while position>0 and alist[position-1]>currentvalue: alist[position]=alist[position-1] alist[position-1]=currentvalue position = position-1 history.append(alist[:]) alist[position]=currentvalue return history
0f6e4aac97676380712823a0739bab3c0c91eacc
252,686
def getAllListings(command): """ Check if command is to get all listings (l | list). """ return (command.strip().lower() == "l" or command.strip().lower() == "list")
a821b78e13b6788cd27eac03204529e1e792106f
335,308
import re def create_regex_function(body): """ Create function from regex pattern. It is used for creating a function for classification. Args: body (string): A regex pattern Returns: function: A function which will return string for classification """ pattern = re.compile(body) def fn(data): filename = data[0] m = pattern.search(filename) if m and len(m.groups()) > 0: # use a first group if there are any groups return m.group(1) elif m: # use entire match return m.group() # no mathced text found return filename return fn
a9f3b79b2f13feddf494e51b04cf7a716de37b4e
395,412
def _get_record_depends(fn, record, instructions): """ Return the depends information for a record, including any patching. """ record_depends = record.get('depends', []) if fn in instructions['packages']: if 'depends' in instructions['packages'][fn]: # the package depends have already been patched record_depends = instructions['packages'][fn]['depends'] return record_depends
3a394278244d221de2fb85678a7a1f129a6756e9
161,734
def getAxis(node): """Parse rotation axis of a joint.""" axis = [0.0, 0.0, 0.0] axisElement = node.getElementsByTagName('axis')[0].getAttribute('xyz').split() axis[0] = float(axisElement[0]) axis[1] = float(axisElement[1]) axis[2] = float(axisElement[2]) return axis
ce9b268fcbd564845a1b05a342c96ed94998bd09
616,018
def raiser(exception): """Returns a function that raises an exception""" def do_raise(*args, **kwargs): raise exception return do_raise
c4d5d5aab728b2c3903cb1a9d0b6bca129adab58
520,790
def get_progress(context, scope): """ Returns the number of calls to callbacks registered in the specified `scope`. """ return context.get("progress", {}).get(scope)
cd0f827c3bf1f548a51dce992949b804d6b97aba
663,579
import re def ParseElastix(input,par): """Parse an elastix parameter file or elastix.log file and extract a number associated with the given string parameter. Parameters ---------- input: string Path to input file. par: string String indicating the parameter in the files to extract. Returns ------- number: string Orginal string found in the given file. This will be converted to an integer or a floating point number. num: integer or float Number corresponding to the parameter specified. """ #Read the transform parameters with open(input, 'r') as file: filedata = file.readlines() #Add each line to a list with separation result=[] for x in filedata: result.append(x.split('\n')[0]) #Find the parameter (Add a space for a match) lines = [s for s in result if str(par+' ') in s][-1] number = re.findall(r"[-+]?\d*\.\d+|\d+", lines)[0] #Try to convert to integer, otherwise convert to float if number.isdigit(): num = int(number) else: num = float(number) #Return the number return number, num
69f2e09bcb70e05490f48fff31f3c318bfff13b7
199,807
import math def polares_cartesianas_complejos(nump:list) -> list: """ Funcion que realiza la transformacion de coordenadas polares a cartesianas de un numero complejo. :param nump: lista que representa el numero complejo en cordenadas polares :return: lista que representa la forma cartesiana del numero complejo. """ res = [] res1 = nump[0]*(math.cos(math.radians(nump[1]))) res2 = nump[0]*(math.sin(math.radians(nump[1]))) res.append(round(res1,2)) res.append(round(res2,2)) return res
ddb7020946d623543e6c9c1d1e142d2847462315
413,105
def generate_grid(obj, size): """Returns an array of x,y pairs representing all the coordinates in a square (size * size) grid centered around a RoomPosition object""" pos = obj.pos or obj # set boundaries to respect room position limits left, right = max(0, pos.x - size), min(49, pos.x + size) + 1 top, bottom = max(0, pos.y - size), min(49, pos.y + size) + 1 return [[x, y] for x in range(left, right) for y in range(top, bottom)]
50024640d5b59320d594ec4bfccb241657294e01
114,336
import requests def lldp_local(url, cookie): """ Retrieve LLDP Local Information :param url: base url :param cookie: Cookie Value :return: LLDP per local port information :Example: result = lldp_local(base_url, sessionid) """ header = {'cookie': cookie} get_lldp_local = requests.get(url + "lldp/local-port", headers=header, verify=False, timeout=2) return get_lldp_local.json()
df2afe0deb7e449808889738309ee9184ce6e985
488,985
import multiprocessing def forkitindexer(filelist): """ Return a list of tuples of indecies that divide the passed list into almost equal slices """ p = int(8*multiprocessing.cpu_count()/10) lenset = len(filelist) modulus = int(lenset%p) floordiv = int(lenset/p) slicer = [[floordiv*i, floordiv*(i+1)] for i in range(p-1)] slicer.append([floordiv*(p-1), p*floordiv+int(modulus)-1]) return slicer
5175761c1014a94755a575404b006be6a0b248ff
323,556
def get_roll_selection(prompt:str = '\nRoll again? (y/n): '): """Return the users character when prompted to continue (y/n).""" return input(prompt)
f18203efa800da09c789e330625c4ba4c3d23ee6
93,837
from pathlib import Path def is_dir_gzipped(directory: str) -> bool: """ Check if the all the files in directory have a '.gz' extension """ files = Path(directory).glob("**") if not files: return False files = filter(lambda x: x.is_file(), files) for f in files: if f.suffix != ".gz": return False return True
5ae4672df96388a815c7dc6247428f6898cab587
436,406
import re def getJUnitVersion(commandsList): """ Find the junit version Parameters ---------- commandsList : list of str A list of the parts of a command for running junit Returns ------- None, int, or str Returns None if it cannot find the string junit in the classpath string Returns -1 if it cannot find a string of the format `junit-\d+\.\d+` Returns a str of the major junit verison """ if any(c.startswith("-classpath") or c.startswith("-cp") for c in commandsList): classpaths = [c for c in commandsList if c.startswith("-classpath") or c.startswith("-cp")] if len(classpaths) == 1: splits = classpaths[0].split(" ") if len(splits) == 2: cp = splits[1].split(":") if any(p.find("junit") >= 0 for p in cp): junitPaths = [p for p in cp if p.find("junit") >= 0] match = [re.search(r"junit-(\d+\.\d+)", p) for p in junitPaths] match = [m for m in match if m] match = [int(re.sub(r"(\d+).\d+", r"\1", m.group(1))) for m in match] matchset = set(match) if len(matchset) == 1: return list(match)[0] return -1
9295cbb789d761ff041585f2d40c680f61f3bf42
179,890
def peek(state, pos=0): """Peeks the character at pos from the head of data.""" if state.head + pos >= len(state.data): return None return state.data[state.head + pos]
d62925a2ee91f21b1371bf0cd42570735fb44498
538,033
import string import random def generate_uuid(length=4, characters=string.ascii_letters + string.digits): """Generate a string of random characters. Args: length (int, optional): The length of the UUID to generate. characters (string, optional): The character set used to build the UUID. Returns: string: A string representation of the generated UUID. """ # Loop through a range defined by the length size # In each loop, make a random choice from our characters and append that to the uuid list uuid = [] for _ in range(length): uuid.append(random.choice(characters)) # Use join to convert the uuid list to a string return ''.join(uuid)
396cf1d979b2bf4edbba0bd690ebc628a56abe77
595,782
import torch def add_channels(imgs: torch.Tensor, num_channels: int=3) -> torch.Tensor: """ Converts an Input image with one channel to a multi-channel input image. Parameters ---------- imgs: Input images, for which the channels should be repeated. num_channels: Target number of channels. Returns ------- imgs: Images, for which the channels are repeated. """ imgs = imgs.repeat(1, num_channels, 1, 1) return imgs
756aea35f65d5862dbd6609ad3c2716280dc1a1c
131,823
def verbose_name(obj): """Return the object's verbose name.""" try: return obj._meta.verbose_name except Exception: return ''
ae5542404b326be960331632239c11b0ad0411dc
653,815
import torch def cross_squared_distance_matrix(x, y, device): """Pairwise squared distance between two matrices' rows. Computes the pairwise distances between rows of x and rows of y Args: x: [n, d] float `Tensor` y: [m, d] float `Tensor` Returns: squared_dists: [n, m] float `Tensor`, where squared_dists[i,j] = ||x[i,:] - y[j,:]||^2 """ x_norm_squared = torch.sum(torch.mul(x, x), 1) y_norm_squared = torch.sum(torch.mul(y, y), 1) # Expand so that we can broadcast. x_norm_squared_tile = x_norm_squared.unsqueeze(1) y_norm_squared_tile = y_norm_squared.unsqueeze(0) x_y_transpose = torch.matmul(x.to(device), torch.transpose(y, 0, 1)) # squared_dists[i,j] = ||x_i - y_j||^2 = x_i'x_i- 2x_i'x_j + x_j'x_j squared_dists = x_norm_squared_tile.to(device) - 2 * x_y_transpose + y_norm_squared_tile return squared_dists
37c8176b454320e4dd5a998251a8419f82ae1380
299,890
def img_resolution(width, height): """ Returns the image's resolution in megapixels. """ res = (width * height) / (1000000) return round(res, 2)
1275a92842fd95f1cd745ac2c8366ec03a183e3e
284,417
def get_chess_square(size, x, y): """ Returns the coordinates of the square block given mouse position `x` and `y` """ return (x // (size // 8), y // (size // 8))
d51ef89ceb5f88a1b189b01e9f0b0034ebfcd8c4
121,878
def shame(df): """ Filter the dataframe of game data on shame (games where one team was shamed). Returns: tuple (string reason, pd dataframe) """ reason = 'shame' filt = df.loc[df['shame']==True] filt = filt.sort_values(['runDiff', 'winningScore', 'season', 'day'], ascending=[False, False, True, True]) return (reason, filt)
de8e49446c618c9ce562b568a656b3671b4c6b9b
295,273
def crosscorr_time(u, v, model, **kwargs): """ Cross correlation of forward and adjoint wavefield Parameters ---------- u: TimeFunction or Tuple Forward wavefield (tuple of fields for TTI or dft) v: TimeFunction or Tuple Adjoint wavefield (tuple of fields for TTI) model: Model Model structure """ w = kwargs.get('w') or u[0].indices[0].spacing * model.irho return w * sum(vv.dt2 * uu for uu, vv in zip(u, v))
ac3f84bf13e56e910fa2780ecb7aa803cdd6f325
177,272
from typing import Dict from typing import Any from typing import Tuple def global_average_precision_score( y_true: Dict[Any, Any], y_pred: Dict[Any, Tuple[Any, float]] ) -> float: """ Compute Global Average Precision score (GAP) Parameters ---------- y_true : Dict[Any, Any] Dictionary with query ids and true ids for query samples y_pred : Dict[Any, Tuple[Any, float]] Dictionary with query ids and predictions (predicted id, confidence level) Returns ------- float GAP score """ indexes = list(y_pred.keys()) indexes.sort( key=lambda x: -y_pred[x][1], ) queries_with_target = len([i for i in y_true.values() if i is not None]) correct_predictions = 0 total_score = 0.0 for i, k in enumerate(indexes, 1): relevance_of_prediction_i = 0 if y_true[k] == y_pred[k][0]: correct_predictions += 1 relevance_of_prediction_i = 1 precision_at_rank_i = correct_predictions / i total_score += precision_at_rank_i * relevance_of_prediction_i return 1 / queries_with_target * total_score
3cb7b97fa19ec63053b7b10668dd3d7a992b9fb9
629,620
from math import floor, sqrt def is_triangular(num): """ Determine if a number is of the form (1/2)n(n+1). """ assert isinstance(num, int) and num > 0 near_sqrt = floor(sqrt(2 * num)) return bool(int((1 / 2) * near_sqrt * (near_sqrt + 1)) == num)
4279545769d3e0f200381abd4bf493fe5bc2ec4e
296,933
def flatten_rf(flow): """ Flattens the Risky Flow objects into a flat dict to write to CSV. """ return { "id": flow.get("id"), "businessUnit": flow.get("businessUnit", {}).get("name"), "riskRule": flow.get("riskRule", {}).get("name"), "internalAddress": flow.get("internalAddress"), "internalPort": flow.get("internalPort"), "externalAddress": flow.get("externalAddress"), "externalPort": flow.get("externalPort"), "flowDirection": flow.get("flowDirection"), "acked": flow.get("acked"), "protocol": flow.get("protocol"), "externalCountryCode": flow.get("externalCountryCode"), "internalCountryCode": flow.get("internalCountryCode"), "observationTimestamp": flow.get("observationTimestamp"), "created": flow.get("created"), "internalExposureTypes": ",".join(flow.get("internalExposureTypes")), "internalDomains": ",".join(flow.get("internalDomains")), }
461f051ba4e92aacefc085367052a2511410e354
491,215
def dobra(x): """ Dobra o valor da entrada Parâmetros ---------- x : número O valor a ser dobrado Retorno ------- número O dobro da entrada """ return 2*x
00431c5fb8a1ab056252b5d8389868f71c872c62
665,853
def build_reaction(reac): """ This function gets the reactants and products in smiles format from reaction list and writes the reaction in a way that can be fed to rdkit. Parameters ------ reac : str A reaction string with reactants/products and their stoichiometric coeffs. Typically an entry from complete reaction list Returns -------------- reaction_list : str list of reactants and products of a specific reaction seperated by space """ reactants = [] products = [] for species in reac: if (float(species[0])) < 0: reactants.append(species[1]) else: products.append(species[1]) seperator = [''] reaction_list = reactants + seperator + products return reaction_list
3761ecd54a4d9f6976a0581ac1260096135691ed
539,460
def req_thickness(t_min, t_corr, f_tol): """Return the required wall thickness [m] based on the mechanical allowances - extrapolated from PD8010-2 Equation (4). :param float t_min: Minimum wall thickness [m] :param float t_corr: Corrosion allowance [m] :param float f_tol: Fabrication tolerance [-] """ try: return (t_min + t_corr) / (1 - f_tol) except ZeroDivisionError: raise ZeroDivisionError( "Divide by zero. Check fabrication tolerance.")
81266f3abe36dd7d1252461660ae9aa0757de877
393,832
import six def convert_perm(perm): """Convert a string to an integer, interpreting the text as octal. Or, if `perm` is an integer, reinterpret it as an octal number that has been "misinterpreted" as decimal. """ if isinstance(perm, six.integer_types): perm = six.text_type(perm) return int(perm, 8)
a20ed3337cf4ffffa73a978c0b736e5d10bbc7bd
455,026
import re def mkccj_is_compiler_command(parsedArgs, commandString): """Return True if the commandString is or appears to name a compiler""" if parsedArgs.compiler: if parsedArgs.compiler == commandString: return True else: return False if re.search(r"cc$", commandString): return True if re.search(r"[cg]\+\+$", commandString): return True return False
5b45a87fddf4b93059dad65d8b031058a0962f18
472,912
def compare_dictionaries(d1, d2): """ Compare two dictionaries :param d1: :param d2: :return: (bool) True if equal, False if different """ res = True try: for key in d1: res &= (d1[key] == d2[key]) for key in d2: res &= (d1[key] == d2[key]) except KeyError: return False return res
480ffc59e52d2831ab079d755d9125fcb6033264
466,351
def byte2hex(buf): """Convert a bytestring to a hex-represenation: b'1234' -> '\x31\x32\x33\x34'""" return "\\x" + "\\x".join(["%02X" % x for x in buf])
0bf55720cd5cb98936ae435f8f25782605eedb5c
471,046
def smaller_starting_year(year, starting_year): """ If the year is older than the defined "starting_year", i.e the year from when we start counting, set it to the "starting_year" This is just internal handling of the code and won't change the data """ if year < starting_year: year = starting_year return year
544096038a15a42630af7c1cb7e7842487bd18c0
206,294
def cbrt(x): """cubic root, this cubic root routine handles negative arguments""" if x == 0.0: return 0 elif x > 0.0: return pow(x, 1./3.) else: return -pow(-x, 1./3.)
06dbfcdcfbfe3d11d8b2d6ebc7f7043b66735511
81,327
def parse_direction(direction): """ Use this to standardize parsing the traffic direction strings. :param direction: str; The direction value to parse. :return: Optional[str]; One of 'ingress', 'egress', or 'both'. Returns None if it could not parse the value. """ direction = direction.lower() if direction in {'ingress', 'incoming', 'inbound', 'in', 'i'}: return 'ingress' if direction in {'egress', 'outgoing', 'outbound', 'out', 'o'}: return 'egress' if direction in {'both', 'b', 'all', 'a'}: return 'both' return None
513274ba3be44f266099c1561c3719b37053c74d
126,430
import torch def mat2euler(rot_mat, seq='xyz'): """ convert rotation matrix to euler angle :param rot_mat: rotation matrix rx*ry*rz [B, 3, 3] :param seq: seq is xyz(rotate along z first) or zyx :return: three angles, x, y, z """ r11 = rot_mat[:, 0, 0] r12 = rot_mat[:, 0, 1] r13 = rot_mat[:, 0, 2] r21 = rot_mat[:, 1, 0] r22 = rot_mat[:, 1, 1] r23 = rot_mat[:, 1, 2] r31 = rot_mat[:, 2, 0] r32 = rot_mat[:, 2, 1] r33 = rot_mat[:, 2, 2] if seq == 'xyz': z = torch.atan2(-r12, r11) y = torch.asin(r13) x = torch.atan2(-r23, r33) else: y = torch.asin(-r31) x = torch.atan2(r32, r33) z = torch.atan2(r21, r11) return torch.stack((x, y, z), dim=1)
d06397aaa3ecd15211a2fb20483aef0ef4223568
574,573
import json def load_table(pinyin_word_table_path): """ Load pinyin-word table from pinyin_word_table_path. Args: pinyin_word_table_path: Path to the source pinyin-word table json file. Returns: pinyin-word table, a dict, key->pinyin, value->(word, log(probability)). """ with open(pinyin_word_table_path, 'r') as f: return json.load(f)
a1d90dde5aa28aefa8038a2a30594354c0226ae8
149,860
def partition(start, stop, step): """Partition an integer interval into equally-sized subintervals. Like builtin :py:func:`range`, but yields pairs of end points. Examples -------- >>> for lo, hi in partition(0, 9, 2): print(lo, hi) 0 2 2 4 4 6 6 8 8 9 """ return ((i, min(i + step, stop)) for i in range(start, stop, step))
60949af9fdcc5b5a387de99fda3d4f4aa8f99862
309,853
def containsZero(n): """ n: an int or a str output: True if n contains '0' """ numStr = str(n) for letter in numStr: if letter is '0': return True return False
e8698f6ba935079ecdb37adbdeb88b61edf9d640
44,090
def drop_duplicate_rows(data_frame, column_name): """Drop duplicate rows in given column in pandas data_frame""" df = data_frame.drop_duplicates(subset=column_name, keep="first") return df
9dcdc06cf4f5ef466c6d808e03a92ef09b451994
42,429
def _make_row(old, parent_key=None): """Make nested dictionary into a single-level dictionary, with additional processing for lists For example: { "metadata": { "durations": { "call": 38.6015, "setup": 0.0021 }, "statuses": { "call": ["failed", False], "setup": ["passed", False] } }, "result": "failed", "test_id": "test_navigation" } becomes: { "metadata.durations.call": 38.6015, "metadata.durations.setup": 0.0021, "metadata.statuses.call": "\"failed\",False", "metadata.statuses.setup": "\"passed\",False", "result": "failed", "test_id": "test_navigation" } :param old: The old dictionary to flatten :type old: dict :param parent_key: The key of the parent object :type parent_key: str | None :rtype: dict """ new = {} for key, value in old.items(): new_key = "{}.{}".format(parent_key, str(key)) if parent_key else str(key) if isinstance(value, dict): new.update(_make_row(value, new_key)) elif isinstance(value, list): new[new_key] = ",".join([str(v) for v in value]) else: new[new_key] = value return new
894649a98d12d88f7543e5ede9383ec3703148b3
118,820
def delta(prev, cur, m): """ Compute the delta in metric 'm' between two metric snapshots. """ if m not in prev or m not in cur: return 0 return cur[m] - prev[m]
c525ff4402b244b6a599d6380fb4b2a029c940b4
249,670
def convert_kb_into_str(size): """ Converte um parâmetro de tamanho de arquivos (em kb) para a escala mais adequada Parâmetros ---------- :param size: variável numérica representando o tamanho de arquivos em kb [type: float] Retorno ------- :param size: valor convertido pra escala mais adequada com o indicativo em str [type: str] """ # Aplicando regras de conversão if size > 1000000: size = str(round(size / 1000000, 2)) + ' GB' elif size > 1000: size = str(round(size / 1000, 2)) + ' MB' else: size = str(round(size, 2)) + ' KB' return size
60fe61288540e0f710b2aa0d1376c8d1b9ef79b5
157,913
def is_valid_0_1(param): """ Checks if param is zero or one """ return param == "0" or param == "1" or param == 0 or param == 1
25541824db5d587ba142238793028a414e524075
175,075
def is_binary(file_path): """ Returns True if the file is binary """ with open(file_path, 'rb') as fp: data = fp.read(1024) if not data: return False if b'\0' in data: return True return False
2df56f93d4e31220a580bf1e659c3c51b96260d2
707,743
def process_collection(id, col): """ Helper function processing the collection. Args: id: (short) name of the collection. col: a collection (python module). """ return { "id": id, "name": col.__name__, "description": col.__description__, "version": col.__version__, "author": col.__author__, }
32a53a1fe8711b00b6faf2abe046f187a7ab40bb
415,806
def repeat(character: str) -> str: """Repeat returns character repeated 5 times.""" word = "" for _ in range(5): word = word + character return word
19bdda35ffafa97d22200f74f1e078958e193962
57,579
import logging def _decodeCStd( version, strictAnsi ): """ Decodes the C standard given the values of the macros __STDC_VERSION__ and __STRICT_ANSI__ """ retVal = None if version == '__STDC_VERSION__' and strictAnsi == '1': retVal = 'c90' elif version == '199409L' and strictAnsi == '1': retVal = 'iso9899:199409' elif version == '199901L' and strictAnsi == '1': retVal = 'c99' elif version == '201112L' and strictAnsi == '1': retVal = 'c11' elif version == '__STDC_VERSION__' and strictAnsi == '__STRICT_ANSI__': retVal = 'gnu90' elif version == '199901L' and strictAnsi == '__STRICT_ANSI__': retVal = 'gnu99' elif version == '201112L' and strictAnsi == '__STRICT_ANSI__': retVal = 'gnu11' elif version == '201710L' and strictAnsi == '__STRICT_ANSI__': retVal = 'gnu17' else: logging.warning( 'Cannot decode default language standard for C. (__STDC_VERSION__ = %s __STRICT_ANSI__ = %s)', version, strictAnsi ) return retVal
2620f3ae0e1a42c2c616c2b087163071dcdc29eb
102,946
def _is_git_url_mismatch(mismatch_item): """Returns whether the given mismatch item is for a GitHub URL.""" _, (required, _) = mismatch_item return required.startswith('git')
b1c3cec3d8cf3c7d3ffa5c405522b1a08754223b
2,096
def read(filename): """Read content of specified test file. :param str filename: Name of file in 'testdata' folder. :return: Content of file :rtype: str """ with open('testdata/' + filename) as f: return f.read()
3d5485021d3a3578485f3b5f3ea59e0badc4a3c7
653,147
def tonative(n, encoding='ISO-8859-1'): """Return the given string as a native string in the given encoding.""" # In Python 3, the native string type is unicode if isinstance(n, bytes): return n.decode(encoding) return n
bb71e3718bc3f0537159971ce123e861beb98abb
337,170
def certificate_domain_list(list_of_domains, certificate_file): """Build a list of domains where certificate_file should be used""" cert_list = [] for domain in list_of_domains: cert_list.append({"host": domain, "certificateFile": certificate_file}) return cert_list
352ab45ce7bfb855eaf0acdb6c1fea632fcdd0ed
499,007
def user_input_validator(validator, question): # pragma: no cover """Validate a user input until it passes a validator function. validator: function, test for user input. Returns a truthy value for a valid input, falsey for invalid. question: str, prompt for user to answer """ user_input = input(question).upper() while not validator(user_input) and user_input.upper() != 'Q': print('Invalid user input, input again\n') user_input = input(question).upper() return user_input
95d54e223ce1023e5a5ebc2b8c28df82b648e8ad
113,418
def get_wgs84_utm_epsg_code(*utm_zone): """ Convert utm zone information to an EPSG code to make projection definition easier. Can take parameters output from `get_utm_zone` as arguments for `utm_zone`. :param utm_zone: iterable with at least two parameters (zone number[int], hemisphere[str:'north'|'south'] :return: the appropriately zoned WGS84 UTM EPSG code """ utm_band = '%02d' % utm_zone[0] hemisphere = utm_zone[1] if hemisphere == 'north' or hemisphere is False: epsg_code = '326' + utm_band else: epsg_code = '327' + utm_band return int(epsg_code)
428bb59e50b15cc3a6035a593c82b1d8d24c0510
507,721
def clean_rating_count(rating_count): """Return just the digits for the rating count""" return rating_count.replace('Bewertungen', '')
8eb024208f5c8fafd733cbe54141b1466a544018
177,419