content
stringlengths
39
9.28k
sha1
stringlengths
40
40
id
int64
8
710k
def is_complete(self): """ Returns if the task is complete """ return self.status == "DONE"
239d0e7dae32f1171a38ecd40fb648b724280fd7
503,853
def mode(lst): """Calculates the mode of a list""" return max(set(lst), key=lst.count)
6bf4393a3e8b3904d0c06fee483e7ca1338af12a
80,701
import requests def read_url(url: str) -> str: """ Return url contents. :param url: URL for request :return: return response content string """ cal_data = requests.get(url).text return cal_data
efe617722ddde37b2ba5e39eca3d3bdfa311f015
572,525
from typing import Dict from typing import Any def response_state_from_mediation_record(record: Dict[str, Any]): """Maps from acapy mediation role and state to AATH state""" state = record["state"] mediator_states = { "request": "request-received", "granted": "grant-sent", "denied": "deny-sent", } recipient_states = { "request": "request-sent", "granted": "grant-received", "denied": "deny-received", } # recipient if record["role"] == "client": return recipient_states[state] # mediator else: return mediator_states[state]
15062fc26f13d907299793df692bf1e39932691c
641,733
def in_to_cm(inches): """ Convert inches to centimeters """ return inches * 2.54
dd774bcd1de1aa8c6d5e7f8123bbe2b0e6a0892c
223,589
def index_union(df_src, df_target, use_target_names=True): """ Create the union of the indices for the two Pandas DataFrames. This combines the "rows" of the two indices, so the index-types must be identical. :param df_src: Pandas Series or DataFrame. :param df_target: Pandas Series or DataFrame. :param use_target_names: Boolean whether to use the index-names from `df_target` (True) or `df_src` (False). :return: Pandas Index. """ # This is not a "deep" type comparison. Two MultiIndex could be different. assert (type(df_src.index) == type(df_target.index)) # Create the union of the indices. # This does not copy the index-names. idx = df_src.index.union(df_target.index) if use_target_names: # Use the index-names from the target. # This is similar to Pandas' reindex. idx.names = df_target.index.names else: # Use the index-names from the source. idx.names = df_src.index.names return idx
d69e8714405a6ee55f5e5b14c5e4f069e67b7b87
605,358
def coalesce_dates(dates): """ Coalesces all date pairs into combined date pairs that makes it easy to find free time gaps. >>> from date_collapse import coalesce_dates >>> dates = [(1,4),(2,8),(12,16),(16,21)] >>> cdates = coalesce_dates(dates) >>> print(cdates) [(1, 8), (12, 21)] >>> dates = [(1,4),(2,8),(8,10),(12,16),(16,21),(21,31)] >>> cdates = coalesce_dates(dates) >>> print(cdates) [(1, 10), (12, 31)] """ parsed_dates = [] for date in dates: parsed_dates.extend([(date[0], 1),(date[1], -1)]) parsed_dates.sort(key = lambda d: d[0]) count = 0 coalesced = [] current_block = [None, None] for date in parsed_dates: if count == 0: if not coalesced or (coalesced[-1][1] != date[0]): current_block = [date[0], None] else: coalesced.pop() count += date[1] if count == 0: current_block[1] = date[0] coalesced.append((current_block[0], current_block[1])) return coalesced
161ef92c6c8946a277e11504cb3dee1082582123
40,337
def _gr_text_to_no(l, offset=(0, 0)): """ Transform a single point from a Cornell file line to a pair of ints. :param l: Line from Cornell grasp file (str) :param offset: Offset to apply to point positions :return: Point [y, x] """ x, y = l.split() return [int(round(float(y))) - offset[0], int(round(float(x))) - offset[1]]
b07a7587cc82ecc9b6a8796e0d09119086092ad7
668,559
def source_to_locale_path(path): """ Return locale resource path for the given source resource path. Locale files for .pot files are actually .po. """ if path.endswith("pot"): path = path[:-1] return path
6a2ca315e7bb2dfe03dede7c2be06602ff47cb40
685,385
def check_field(vglist,key,value): """ Accepts a list of dicts; for each dict, check the the specified key contains the specified value. """ for row in vglist: assert row[key] == value, \ '** Error: Field: %s contains value: %s, expected: %s' % (str(key),str(row[key]),str(value)) return True
92ba6c26b47e2f96176b4593d89c2b509a004e2f
269,721
def det(x): """ Return the determinant of ``x``. EXAMPLES:: sage: M = MatrixSpace(QQ,3,3) sage: A = M([1,2,3,4,5,6,7,8,9]) sage: det(A) 0 """ return x.det()
8e74bb3c1f8c99ea25b4868690813b11ac47087f
660,614
def calculate_overlap(a: str, b: str) -> int: """ Calculates an overlap between two strings using Knuth–Morris–Pratt algorithm """ pi = [0] * (len(a) + len(b) + 1) string = b + '#' + a for i in range(len(string)): if i == 0: continue j = pi[i - 1] while j > 0 and string[i] != string[j]: j = pi[j - 1] if string[i] == string[j]: j += 1 pi[i] = j return pi[-1]
3f2f902d8a9b8d23d69cfbd502cc4d75723e55c5
95,165
def is_file(obj): """ Check if the given object is file-like. """ return hasattr(obj, 'flush') and hasattr(obj, 'readline')
df70bf8651ecfa7e9a2530178c9dda8cef87c787
490,614
def get_request_id_or_none(filename): """Get a unique id out of a filename.""" if filename.endswith(".json"): return int(filename.replace(".", "").replace("json", ""))
c5889e3647025794822dc88cb22f8f05083b34f0
208,038
def is_markdown_cpp_src(ipynb_cell): """ True if a cell is markdown && multiline source code && C++ ```'s wrap multiline code blocks C++ source code blocks have C++ right after starting ``` """ result = False # Markdown if 'markdown' == ipynb_cell['cell_type']: src = ipynb_cell['source'].strip() # Multiline code block within ```'s if (src.startswith('```') and src.endswith('```')): # check C++ right after ``` if "c++" in src.splitlines()[0].lower(): result = True return result
2bfcc92b54b9e4645f32422c6909ca33f3bd4add
525,624
def _assign_axis(attributes, axis): """Assign the given axis to the _metpy_axis attribute.""" existing_axes = attributes.get('_metpy_axis', '').split(',') if ((axis == 'y' and 'latitude' in existing_axes) or (axis == 'latitude' and 'y' in existing_axes)): # Special case for combined y/latitude handling attributes['_metpy_axis'] = 'y,latitude' elif ((axis == 'x' and 'longitude' in existing_axes) or (axis == 'longitude' and 'x' in existing_axes)): # Special case for combined x/longitude handling attributes['_metpy_axis'] = 'x,longitude' else: # Simply add it/overwrite past value attributes['_metpy_axis'] = axis return attributes
a1586cbdc618a7c958a2b7ee3d9296a63bb99647
498,767
import re def get_valid_filename(s): """ Return the given string converted to a string that can be used for a clean filename. Remove leading and trailing spaces; convert other spaces to underscores; and remove anything that is not an alphanumeric, dash, underscore, or dot. >>> get_valid_filename("john's portrait in 2004.jpg") 'johns_portrait_in_2004.jpg' Function sourced from Django 2.1 https://github.com/django/django/blob/master/django/utils/text.py """ s = str(s).strip().replace(' ', '_') return re.sub(r'(?u)[^-\w.]', '', s)
6561030d1e444e8fd5121636ec08d561433ce73c
623,635
def str_to_hex(string): """Convert given string to hex string.""" return ":".join("{:02x}".format(ord(c)) for c in string)
f84337f96970faafee0283748581f5e5654c71a7
502,565
import math def root_mean_square(x): """ Root mean square (RMS) is the square root of the sum of the squares of values in a list divided by the length of the list. It is a mean function that measures the magnitude of values in the list regardless of their sign. Args: x: A list or tuple of numerical objects. Returns: A float of the root mean square of the list. Examples: >>> root_mean_square([-1, 1, -1, 1]) 1.0 >>> root_mean_square((9, 4)) 6.96419413859206 >>> root_mean_square(9) Traceback (most recent call last): ... TypeError: root_mean_square() expects a list or a tuple. """ if type(x) not in [list, tuple]: raise TypeError('root_mean_square() expects a list or a tuple.') squares = [] squares = [pow(num, 2) for num in x] sum_of_squares = sum(squares) ms = sum_of_squares / len(x) rms = math.sqrt(ms) return(rms)
9a594179fd873e8bd5dd439a427ed917cebcd05c
96,463
def convert_roman(ch): """ converts a roman numeral character into the respective integer """ ret = -1 if ch == 'I': ret = 1 elif ch == 'V': ret = 5 elif ch == 'X': ret = 10 elif ch == 'L': ret = 50 elif ch == 'C': ret = 100 elif ch == 'D': ret = 500 elif ch == 'M': ret = 1000 return ret
912e82046733ca39ba7be112a13d82fba60f9980
245,387
import hashlib import json def treehash(var): """ Returns the hash of any dict or list, by using a string conversion via the json library. """ return hashlib.sha256(json.dumps(var, sort_keys=True).encode("utf-8")).hexdigest()
e196a8d601b59a893bf05bc903aa7e3af4927cef
696,038
def IsArray(obj): """Determine if an object is an array""" return isinstance(obj, (list, tuple))
815e212c276b6c6dbbf15029b5fa2cdf1754c8a4
363,806
def get(api_key, types, p1, p2, n_threads=20, radius=180, all_places=False): """ :param api_key: str; api key from google places web service :param types: [str]; placetypes :param p1: (float, float); lat/lng of a delimiting point :param p2: (float, float); lat/lng of a delimiting point :param n_threads: int; number of threads to use :param radius: int; meters; :param all_places: bool; include/exclude places without populartimes :return: see readme """ params = { "API_key": api_key, "radius": radius, "type": types, "n_threads": n_threads, "all_places": all_places, "bounds": { "lower": { "lat": min(p1[0], p2[0]), "lng": min(p1[1], p2[1]) }, "upper": { "lat": max(p1[0], p2[0]), "lng": max(p1[1], p2[1]) } } } return params
173e9a2367250d3744db4dfe77b486965ea0a62a
357,720
def atf_fc_uri(article_uri): """URI of feature collection""" return article_uri+"/featurecollection"
c725642309955795b5558b638146b782c7f51d0b
63,018
import ast def get_ast_node_name(x): """Return human-readable name of ast.Attribute or ast.Name. Pass through anything else.""" if isinstance(x, ast.Attribute): # x.value might also be an ast.Attribute (think "x.y.z") return "%s.%s" % (get_ast_node_name(x.value), x.attr) elif isinstance(x, ast.Name): return x.id else: return x
c00c31638f4789ed45741b4744f290c1822e0a7f
162,221
def element_located_to_be_selected(locator): """An expectation for the element to be located is selected. locator is a tuple of (by, path)""" def _predicate(driver): return driver.find_element(*locator).is_selected() return _predicate
41eca03c731f50aa71692beb407d7c8001945a67
320,439
def greet(name): """Greets you by name!""" return 'Hello {name}!'.format(name=name)
1822209df3852c11f3a6731c9ddbb1ee4c2c5286
373,232
def prompt_for_password(prompt=None): """Fake prompt function that just returns a constant string""" return 'promptpass'
49499970c7698b08f38078c557637907edef3223
2,777
def get_representative(location: str) -> tuple[str, str]: """ Split the location into numeric (row) and alphabet (column). Parameters ---------- location: str A string use to locate the position on the board. Returns ------- row: str The row representative. column: str The column representative. """ column = '' row = '' for c in location: if c.isalpha(): column += c elif c.isnumeric(): row += c return column, row
b2c973d6e9e5180761fc393a388fa424d7e016dc
142,315
from typing import List def create_id_access_token_header(id_access_token: str) -> List[str]: """Create an Authorization header for passing to SimpleHttpClient as the header value of an HTTP request. Args: id_access_token: An identity server access token. Returns: The ascii-encoded bearer token encased in a list. """ # Prefix with Bearer bearer_token = "Bearer %s" % id_access_token # Encode headers to standard ascii bearer_token.encode("ascii") # Return as a list as that's how SimpleHttpClient takes header values return [bearer_token]
db2450d58c9a8292b80f2d5bbf79cf88c87c2637
314,639
def char_to_word_index(ci, sequence): """ Given a character-level index (offset), return the index of the **word this char is in** """ i = None for i, co in enumerate(sequence.char_offsets): if ci == co: return i elif ci < co: return i - 1 return i
ecdfafd0c301d98d3f600b34022eb2e605a6e1da
637,956
def is_letter_guessed_correctly(player_input, secret_word): """ check whether the (guessed_letter/ player_input) is in the secret_word Arguments: player_input (string): the player_input secret_word (string): the secret, random word that the player should guess Returns: boolean: True if the player_input is in the secret_word; False otherwise """ for i in secret_word: if player_input == i: return True return False
2fd0840300ae16aba4ba1d997c4cd98343778f74
619,247
def my_data_pypath(tmpdir_factory): """temporary directory for storing test data""" pypath = tmpdir_factory.mktemp('singlecell_data', numbered=False) return pypath
c4057f32008c064a5b703e80469d68d0afaf0b2b
371,588
def isMissionary(info, iReligion): """ Returns True if <info> is the Missionary for <iReligion>. """ return info.getReligionSpreads(iReligion)
5331f459cb57f116443c1837d62df8143bb9a133
92,794
def default_flist_reader(flist): """ This reader reads a filelist and return a list of paths. :param flist: path of the flislist to read. The flist format should be: impath label, impath label, ...(same to caffe's filelist) :returns: Returns a list of paths (the examples to be loaded). """ imlist = [] with open(flist, "r") as rf: for line in rf.readlines(): impath, imlabel = line.strip().split() imlist.append((impath, int(imlabel))) return imlist
216af3ae7e7fbdf7215e4b554a070cabc99ced48
452,007
import uuid def generate_id(length: int = 18): """ Generate a pseudo-random ID. :param length: Length of the requested ID. :return: Generated id. """ return str(uuid.uuid4().hex)[:length]
3b685fd72c38248e1420806f2968fba4ec0db3d0
222,610
import json def process_config(json_file): """Load configuration as a python dictionary. Args: json_file (str): Path to the JSON file. Returns: dict: """ # parse the configurations from the config json file provided with open(json_file, 'r') as config_file: config_dict = json.load(config_file) return config_dict
2190525330bb319547fa143ea9e78bbddf052ffa
646,660
def is_in_combat(character): """ Returns true if the given character is in combat. Args: character (obj): Character to determine if is in combat or not Returns: (bool): True if in combat or False if not in combat """ return bool(character.db.combat_turnhandler)
0aaa73d15df3019df8d9bf0dfcc1329e386d27b5
589,933
def _solve_method_3(arr): """ https://github.com/JaredLGillespie/HackerRank/blob/master/Python/minimum-swaps-2.py Couldn't really figure it out via my method, but I found this solution that was very small and I understand. One thing I did was factor out a portion of it into a function call, for easier understanding. A lot of times, of course, in programming, one can pack a lot of information in one line of code, but it's good to factor that out sometimes. """ def _swap_2_elements(arr, first_index, second_index): """ Swaps 2 positions of the array. This function is different from my `update_entries` function above, only in that my function operates on an augmented array, rather than a bare array. """ temp = arr[first_index] arr[first_index] = arr[second_index] arr[second_index] = temp return arr N = len(arr) swaps = 0 for i in range(0, N - 1): while arr[i] != i + 1: first_index = arr[i] - 1 second_index = i arr = _swap_2_elements(arr, first_index, second_index) swaps += 1 return swaps
fca3a8ace9f026eed0d56a1b80c56073842f3249
687,463
def extract_rules(lines): """ Extracts rules from file. Rules are structured in nested dictionaries. The outer dictionary has the color as key with a dictionary as value that contains the bag colors and amounts. The inner dictionary has the bag color as key and the amount as value. :param lines: Lines from input file :return: dictionary """ rules = {} # iterate over every line for line in lines: rule = {} # get key and value key, value = line.split('contain ') key = key.split(' bags')[0] # if bag doesn't contain other bags make value None if value == 'no other bags.': rules[key] = None else: # add bags to value values = value.split(', ') for v in values: v = v.split(' ') rule['{} {}'.format(v[1], v[2])] = int(v[0]) rules[key] = rule return rules
5e57f8df21eae3c3778bd2be3dba6d4aedb8dc7b
513,043
from typing import List def missing_number(nums: List[int]) -> int: """Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array. From `leetcode <https://leetcode.com/problems/missing-number/>` :param nums: {List[int]} 0, 1, 2, ..., n :return: {int} missing number in array """ nums.sort() num = nums[0] length = len(nums) if length == 1: return num - 1 if num > 0 else num + 1 if 0 not in nums: return 0 for i in range(1, length): num = nums[i - 1] + 1 if nums[i] != num: break num += 1 return num
6dd75d9e596258fab489691e4720e391024139a6
124,521
def _get_part(pointlist, strokes): """Get some strokes of pointlist Parameters ---------- pointlist : list of lists of dicts strokes : list of integers Returns ------- list of lists of dicts """ result = [] strokes = sorted(strokes) for stroke_index in strokes: result.append(pointlist[stroke_index]) return result
7f2c96945d39b7704ddefed746c358ee6b41a667
454,883
def parse_list_file(file): """ parses a text file with a list, one string per row :param file: list file to be parsed (strings, one per row) :return: a list of strings """ # get rows of file rows = [row.strip() for row in file.splitlines()] # remove any empty rows rows = [_f for _f in rows if _f] # return only unique rows rows = list(set(rows)) return rows
144303456b58f215208171b2ed88bb958d760464
215,901
def make_obj_list(obj_or_objs): """This method will take an object or list of objects and ensure a list is returned. Example: >>> make_obj_list('hello') ['hello'] >>> make_obj_list(['hello', 'world']) ['hello', 'world'] >>> make_obj_list(None) [] """ if not obj_or_objs: return [] if not isinstance(obj_or_objs, (list, tuple)): return [obj_or_objs] return obj_or_objs
d65407167714d02c63ee8a784e688668711f3b75
169,888
def merge(items1, items2): """Merge given lists of items, each assumed to already be in sorted order, and return a new list containing all items in sorted order. Running time: O(n) Passes over each element once Memory usage: O(n) Makes a new list for all the elements """ ind_1, ind_2 = 0, 0 new_list = [] # Repeat until one list is empty while ind_1 <= len(items1) - 1 and ind_2 <= len(items2) - 1: # Find minimum item in both lists and append it to new list if items1[ind_1] <= items2[ind_2]: new_list.append(items1[ind_1]) ind_1 += 1 else: new_list.append(items2[ind_2]) ind_2 += 1 # Append remaining items in non-empty list to new list if ind_1 <= len(items1) - 1: new_list.extend(items1[ind_1:]) elif ind_2 <= len(items2) - 1: new_list.extend(items2[ind_2:]) return new_list
3fa477a93d3aed5337a2b62a516b653b88929d30
623,441
def select_group_nodes(graph, group): """Select nodes from a networkx graph based on a group. Args: graph (networkx.Graph): Networkx graph object. group (str): Group name. Returns: list: List of networkx nodes that are of the specified group. """ nodes = [node for node in graph.nodes(data=True) if group < 0 or node[1]["group"] == group] return nodes
b9d451ebaa81835275ae243684e2cbb86c66f34c
186,898
def index_to_angle(i): """ Takes an index into a LIDAR scan array and returns the associated angle, in degrees. """ return -135.0 + (i / 1081.0) * 0.25
63f99389ef532a662d5ea3a3a173a1ba8dd9df09
43,626
def compose1(f, g): """Return a function that composes f and g. f, g -- functions of a single argument """ def h(x): return f(g(x)) return h
8d4829a787b78826f1c03d5e9621fb7d6a6ea56c
647,491
def getinstancepublicip(instance): """Given a JSON instance, get its public IP address""" if "PublicIpAddress" in instance: return instance["PublicIpAddress"] else: return ""
f265f567ad6fbea5889e1ad9b710fa89834a8ff0
417,966
def create_flickr_url(photo, size): """Create a Flickr image url based on the given photo object and size (in Flickr terms).""" # pylint: disable=C0301 return "https://farm{farm}.staticflickr.com/{server}/{id}_{secret}_{size}.jpg".format( size=size, **photo )
1ec25f0d7300ea85ed6bafd52d66a8cc1fbfc874
414,935
import torch def product_of_gaussians(mus, sigmas_squared): """Compute mu, sigma of product of gaussians. Args: mus (torch.Tensor): Means, with shape :math:`(N, M)`. M is the number of mean values. sigmas_squared (torch.Tensor): Variances, with shape :math:`(N, V)`. V is the number of variance values. Returns: torch.Tensor: Mu of product of gaussians, with shape :math:`(N, 1)`. torch.Tensor: Sigma of product of gaussians, with shape :math:`(N, 1)`. """ sigmas_squared = torch.clamp(sigmas_squared, min=1e-7) sigma_squared = 1. / torch.sum(torch.reciprocal(sigmas_squared), dim=0) mu = sigma_squared * torch.sum(mus / sigmas_squared, dim=0) return mu, sigma_squared
27a59cf57e70c1056ebe5703be1d36aa7e69af67
254,018
import re def get_links(text): """ It will return website links from the text :param text: string :return: list example >>> message = 'http://twitter.com Project URL: https://app.grepsr.com/app/project/message/70454' >>> get_links(message) ['http://twitter.com', 'https://app.grepsr.com/app/project/message/70454'] """ result = re.findall(r"(?P<url>https?://[^\s]+)", text) return result
c0cb6c5b499db48c553ba76af5044b032547ba34
375,223
import re def baseOfBaseCode(baseCode): """ Return the base (jrnlCode) of the baseCode >>> print baseOfBaseCode("IJP.001") IJP >>> print baseOfBaseCode("IJP001") IJP >>> print baseOfBaseCode("JOAP221") JOAP >>> print baseOfBaseCode("ANIJP-IT.2006") ANIJP-IT >>> print baseOfBaseCode("anijp-it.2006") ANIJP-IT """ retVal = re.split("\.|[0-9]", baseCode.upper()) return retVal[0]
9597272d4ffa6f1b6a74a7beff50e1197cda0c54
77,856
def non_content_line(line): """ Returns True iff <line> represents a non-content line of an Extended CSV file, i.e. a blank line or a comment. :param line: List of comma-separated components in an input line. :returns: `bool` of whether the line contains no data. """ if len(line) == 0: return True elif len(line) == 1: first = line[0].strip() return len(first) == 0 or first.startswith('*') else: return line[0].strip().startswith('*')
8f094f678fedb8307f3ab78a8e3b15b7d35f7497
419,763
import re def _extract_from_arn(arn, position): """ Helper Function to extract part of an ARN :param arn: Arn to extract from :param position: Position in Arn of interest :return: String containing value at requested position """ return re.findall("(.*?):", arn)[position]
b2b19bd1b29a99578115df95172211579d112c90
347,456
def get_dgs(align_dg_dict): """ Function that creates inverse dictionary of align_dg_dict align_dg_dict: dict. Dictionary of alignments and clustering DG assignments Returns dg_align_dict: dict, k=dg_id, v=[alignids] align_dg_dict comes from get_spectral(graph) or get_cliques(graph) """ dgs_list = set(align_dg_dict.values()) #list of all duplex groups dg_align_dict = {} for dg in dgs_list: dg_align_list =[x for (x,y) in align_dg_dict.items() if y == dg] dg_align_dict[dg] = dg_align_list return dg_align_dict #test case:
85bca47657c83d2b308d38f05d1c88d9a78fa448
705,451
import random def choix(liste): """ Renvoie un élément de la liste ``liste`` choisi (pseudo)aléatoirement et de manière équipropable Arguments: liste (int): La liste dans laquelle on choisit un élément. """ return random.choice(liste)
01254d22ee62528e41fcaa75ef28d4c2c3683d73
493,030
import hmac def PRF512(K: bytes, A: bytes, B: bytes) -> bytes: """ Implementation of PRF-512, as defined in IEEE Std 802.11-2007 Part 11, section 8.5.1.1. Returns a 512-bit value. :param K: key :param A: a unique label for each different purpose of the PRF :param B: binary input to the PRF """ num_bytes = 64 R = b'' Y = b'\x00' for i in range((num_bytes * 8 + 159) // 160 + 1): R += hmac.new(K, A + Y + B + bytes([i]), 'sha1').digest() return R[:num_bytes]
770f6b90ccc8e0ee037232872191d1e94d4389b2
169,272
def seconds_to_human(seconds): """Convert seconds to a human readable format. Args: seconds (int): Seconds. Returns: str: Return seconds into human readable format. """ units = ( ('week', 60 * 60 * 24 * 7), ('day', 60 * 60 * 24), ('hour', 60 * 60), ('min', 60), ('sec', 1) ) if seconds == 0: return '0 secs' parts = [] for unit, div in units: amount, seconds = divmod(int(seconds), div) if amount > 0: parts.append('{} {}{}'.format( amount, unit, '' if amount == 1 else 's')) return ' '.join(parts)
7aea36c236aad9bec1927b4704f322b19a9de308
577,125
def get_user_id(user): """ JavaScript-friendly user-id. """ if user.id: return user.id return 'null'
e9b33099c1b313c81b5a9dcfb35ddcfd5127d6a8
385,846
import itertools def all_combinations(items): """Generate combinations of variable size. :param items: Sequence of items. :return: List of all combinations. :rtype: :py:class:`list` """ combinations = [] for rsize in range(1, len(items) + 1): combinations.extend(list(itertools.combinations(items, rsize))) return combinations
fbb697d75edb4452addb78803e5d48969ba6b250
404,479
def shrink_path(full_path: str, max_len: int = 70) -> str: """ Shrinks the path name to fit into a fixed number of characters. Parameters ----------- full_path: String containing the full path that is to be printed. \n max_len: Integer containing the maximum length for the final path. Should be more than 10 characters. Default: 15 \n Returns -------- String containing path after shrinking it. Will be at most `max_len` characters in length. """ if len(full_path) <= max_len: # Directly return the path if it fits within the maximum length allowed. return full_path allowed_len = max_len - 6 return f'{full_path[:int(allowed_len / 2)]}......{full_path[-int(allowed_len / 2):]}'
36bfcc9b3216ef84cc41ea550f8c0176518e0fb6
442,532
def char(int): """ CHAR int outputs the character represented in the ASCII code by the input, which must be an integer between 0 and 255. """ return chr(int)
7fa90e06d9b4498a1603fa2439776789c98bd2be
675,039
def static_isinstance(obj, obj_type): """ A static implementation of isinstance() - instead of comparing an object and a class, the object is compared to a string, like 'pyiron.base.job.generic.GenericJob' or a list of strings. Args: obj: the object to check obj_type (str/list): object type as string or a list of object types as string. Returns: bool: [True/False] """ if not hasattr(obj, '__mro__'): obj = obj.__class__ obj_class_lst = ['.'.join([subcls.__module__, subcls.__name__]) for subcls in obj.__mro__] if isinstance(obj_type, list): return any([obj_type_element in obj_class_lst for obj_type_element in obj_type]) elif isinstance(obj_type, str): return obj_type in obj_class_lst else: raise TypeError()
c18184293cbad98f3eda6c1450674f6a9d1079c1
532,406
def calculate_error(t_k, y_k): """ Beda antara data target dengan prediksi model args: - t_k: target pada hidden layer k - y_k: hasil prediksi pada hidden layer k """ return t_k - y_k
a8fe6b575b47323b7cf7db44ab10918175fd1e1b
457,079
def NumWord(number): """ Just a bunch of numbers in word-form. Returns the 'number'th element which happens to be that number as a word. works for 0-99 should be good enough for a clock. """ Words=["zero", "one","two","three","four","five","six","seven","eight","nine","ten", "eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","nineteen","twenty" "twenty-one","twenty-two","twenty-three","twenty-four","twenty-five","twenty-six","twenty-seven","twenty-eight","twenty-nine","thirty", "thirty-one","thirty-two","thirty-three","thirty-four","thirty-five","thirty-six","thirty-seven","thirty-eight","thirty-nine","forty", "forty-one","forty-two","forty-three","forty-four","forty-five","forty-six","forty-seven","forty-eight","forty-nine","fifty", "fifty-one","fifty-two","fifty-three","fifty-four","fifty-five","fifty-six","fifty-seven","fifty-eight","fifty-nine","sixty", "sixty-one","sixty-two","sixty-three","sixty-four","sixty-five","sixty-six","sixty-seven","sixty-eight","sixty-nine","seventy", "seventy-one","seventy-two","seventy-three","seventy-four","seventy-five","seventy-six","seventy-seven","seventy-eight","seventy-nine","eighty", "eighty-one","eighty-two","eighty-three","eighty-four","eighty-five","eighty-six","eighty-seven","eighty-eight","eighty-nine","ninety"] return Words[number]
3f141832a8a6ec16d056e055704c4420f5dfb8cf
377,616
def getIntervalStr( rg, label ): """ Converts and stores range along string as string Parameters: * rg (list, array, tuple): array object with three elements [start, stop, step] * label (str): label to be concatenated with range info Returns: * str: concatenated label and range info """ if len(rg) < 3: return str = label + " range: "+ repr(rg[0]) + "-" + repr(rg[1]) str = str + " (step " + repr(rg[2]) + ")" return str
4f7585767151cbac636b26c9d01212ddbdd167b8
499,329
import json def get_value(json_file, key): """ return the value associated with the key in the specified json file :param json_file: the json file where the key and value present :param key: the key where the value is associated with :returns: 0 if there is not key found in the json_file. else return the value associated with the key """ count = 0 with open(json_file, 'r') as f: data = json.load(f) if key not in data: return count count = data[key] return count
a97f8e5cb714061cdc1551cf5f9fb49280354471
164,597
def unquote(value): """Removes left most and right most quote for str parsing.""" return value.lstrip('"').rstrip('"')
fe38a7e2786783a11e0f39886517c8b567084e49
549,358
def one_of_k_encoding_unk(x, allowable_set): """ taken from https://github.com/thinng/GraphDTA function which one hot encodes x w.r.t. allowable_set with one bit reserved for elements not in allowable_set x: element from allowable_set allowable_set: list list of all known elements """ if x not in allowable_set: x = allowable_set[-1] return list(map(lambda s: x == s, allowable_set))
1ccd42a1d4f27e09baedac0e5cdf43ca8871a58a
618,016
def get_iwp_label_name( iwp_label, shortened_flag=False ): """ Retrieves a name for the supplied IWP label. May be a shortened nickname for readability or the full label identifier depending on the caller's needs. Takes 1 argument: iwp_label - IWP label to extract a name from. shortened_flag - Optional flag specifying whether a shortened name is requested. If specified as True, the first six characters of the name are returned, otherwise the entire identifier. If omitted, defaults to False. NOTE: Shortened names may not necessarily be unique! Returns 1 value: label_name - Name string associated with iwp_label. """ # the first six characters of an identifier seems fairly unique, since it # covers a space of 6^62 combinations, and is short enough to overlay on # XY slices without cluttering things. # # NOTE: no analysis has been done on Scalabel identifiers to understand # their generation. use the full label when uniqueness must be # guaranteed. # if shortened_flag == True: return iwp_label["id"][:6] return iwp_label["id"]
f7f2388e19fcd2fb07008d3615792e7271c4980e
522,046
def time_interval_since(date_1, date_2): """ Calculate seconds between two times Arguments: date_1 -- datetime object #1 date_2 -- datetime object #2 Output: Num of seconds between the two times (with a sign) """ return (date_1 - date_2).total_seconds()
6a5f11b0e2705a4e577e037ba43dfed6bda06be4
687,624
def adapt_format(item): """Javascript expects timestamps to be in milliseconds and counter values as floats Args item (list): List of 2 elements, timestamp and counter Return: Normalized tuple (timestamp in js expected time, counter as float) """ timestamp = int(item[0]) counter_value = item[1] return [timestamp*1000, float(counter_value)]
bc39c3b644bbf833a3288c520707d67c07e9cfb1
291,538
import pickle def load_model(filename): """ Function to load an HMM model from a pickle file. :param filename: full path or just file name where to save the variable :type filename: str :return: the trained HMM that was in the file :rtype: object """ with open(filename, 'rb') as f: model = pickle.load(f) return model
6a8c3dc590da4f299a17f1e3ffc7378e97be95ba
114,276
def get_rpath_deps(pkg): """Return immediate or transitive RPATHs depending on the package.""" if pkg.transitive_rpaths: return [d for d in pkg.spec.traverse(root=False, deptype=('link'))] else: return pkg.spec.dependencies(deptype='link')
1664fd2e54b2b29cf615a365131c057d7eb261b7
669,704
def ProfondeurMoyenne(tree): """Retourne la hauteur moyenne de l'arbre tree.""" return tree.av_leaf_height()
a59c9ed83bdd7f5a337a0ba82441cf2154df82a7
94,481
def find_all_tiltgroups(fileList): """ Find all unique ID codes for each tilt group in the dataset and return them as a list for use: [ "tilt_id_1", "tilt_id_2", ... "tilt_id_n"] """ tilt_ids = [] for file in fileList: filename_to_list = file.split("_") tilt_id = filename_to_list[3] if not tilt_id in tilt_ids: tilt_ids.append(tilt_id) print(" %s tilt groups found in dataset" % len(tilt_ids)) return tilt_ids
1a26132a2ec7b8b9b7e0a4892266b31bcd0e3484
520,123
import psutil def get_num_procs(njobs:int)->int: """ Small wrapper function used to get an integer number of cores, based on the user selection via njobs: - njobs = 0, set it to 1 core (serial) - njobs > 0, set it to njobs cores (parallel) - njobs < 0, set it to njobs * the number of physical cores as obtained by psutil.cpu_count (This is useful for multi-socket setups, where psutil will only give the number of cores on a single socket) """ if (njobs==0): njobs=1 if (njobs<0): procs=psutil.cpu_count(logical=False)*abs(njobs) else: procs=njobs return procs
f026e4a748e25175f335eceebb2e709cb310bf5e
317,876
import re def hashtag(phrase, plain=False): """ Generate hashtags from phrases. Camelcase the resulting hashtag, strip punct. Allow suppression of style changes, e.g. for two-letter state codes. """ words = phrase.split(' ') if not plain: for i in range(len(words)): try: if not words[i]: del words[i] words[i] = words[i][0].upper() + words[i][1:] words[i] = re.sub(r"['./-]", "", words[i]) except IndexError: break return '#' + ''.join(words)
b6e7ab647330a42cf9b7417469565ce5198edd4f
703,665
def get_device_name(doc): """ Finds device name in the document title :param doc: docx Document instance :return: device name as string """ found = False for paragraph in doc.paragraphs: if found: title = paragraph.text for word in str(title).split(): if any(char.isdigit() for char in word): return word[0:20].replace(',', '').replace('*', '').replace('#', '') if 'ЦЕЛЬ ИСПЫТАНИЙ' in paragraph.text or \ 'Цель ИСПЫТАНИЙ' in paragraph.text or \ 'ЦЕЛЬ РАБОТЫ' in paragraph.text: found = True
e2b1201a6425b345f1e0c20d7d1afe5a8774aaa8
358,152
def is_number_offset(c_offset): """ Is the offset a number """ return 0x66 <= c_offset <= 0x6f
6606048314047de7f59e77e01f48e438d4113159
34,107
def validate_higlass_file_sources(files_info, expected_genome_assembly): """ Args: files_info(list) : A list of dicts. Each dict contains the file's uuid and data. expected_genome_assembly(str, optional, default=None): If provided, each file should have this genome assembly. If it's not provided, all of the files will be checked to ensure they have a matching genome assembly. Returns: A dictionary with the following keys: success(bool) : True if there were no errors. current_genome_assembly(str): A string indicating the genome assembly of the files. errors(str) : A string (or None if there are no errors) """ files_by_genome_assembly = {} for file in files_info: # Get the uuid. uuid = file["uuid"] # Get the file data. data = file["data"] if not data: return { "success" : False, "errors" : "File {uuid} does not exist".format(uuid=uuid), } # Get the higlass_uid. if "higlass_uid" not in data: return { "success" : False, "errors" : "File {uuid} does not have higlass_uid".format(uuid=uuid) } # Get the genome_assembly. if "genome_assembly" not in data: return { "success" : False, "errors" : "File {uuid} does not have genome assembly".format(uuid=uuid) } if data["genome_assembly"] not in files_by_genome_assembly: files_by_genome_assembly[data["genome_assembly"]] = [] files_by_genome_assembly[data["genome_assembly"]].append(uuid) # Make sure all of the files have the same genome assembly. human_readable_ga_listings = [] for ga in [g for g in files_by_genome_assembly if g != expected_genome_assembly]: human_readable_ga_listings.append( "{ga}: {uuids}".format( ga=ga, uuids=", ".join(files_by_genome_assembly[ga]) ) ) if len(files_info) > 0: if expected_genome_assembly: if expected_genome_assembly not in files_by_genome_assembly or \ len(files_by_genome_assembly.keys()) > 1: return { "success" : False, "errors" : "All files are not {expected} genome assembly: {files_by_ga}".format( expected = expected_genome_assembly, files_by_ga = "; ".join(human_readable_ga_listings), ) } else: if len(files_by_genome_assembly.keys()) > 1: return { "success" : False, "errors" : "Files have multiple genome assemblies: {files_by_ga}".format( expected = expected_genome_assembly, files_by_ga = "; ".join(human_readable_ga_listings), ) } # Make sure we found a genome assembly. if not (expected_genome_assembly or files_by_genome_assembly): return { "success" : False, "errors": "No Genome Assembly provided or found in files." } # Everything is verified. return { "success" : True, "errors": "", "genome_assembly": expected_genome_assembly or list(files_by_genome_assembly.keys())[0] }
42124e5a3132861dc3a81b8751859630761b80d2
653,908
def is_file_wanted(f, extensions): """ extensions is an array of wanted file extensions """ is_any = any([f.lower().endswith(e) for e in extensions]) return is_any
c84250126c9700966248b969ded3121ae2c96764
26,558
import io def s_map(p_string, domain, mapping): """ Replaces all characters of the `domain` in `p_string` with their respective mapping in `mapping`. The length of the domain string must be the same as the mapping string unless the mapping string is empty or a single character, in which case all domain characters will be either replaced or substituted with that mapping character in the `p_string`. :param p_string The string whose characters in domain to substitute with their respective mappings in `mapping`. :param domain The string of characters to replace in the `p_string`. If some characters reappear, this will not affect the substitution process, the extra characters are simply ignored. :param mapping The corresponding mapping of the `domain`. This must match the length of the `domain` string, empty, or be a single character to which all domain characters will be mapped to. If any of `p_string`, `domain`, or `mapping` are None, this function does nothing and simply returns `p_string`. If len(mapping) != len(domain) and len(mapping) > 1, this function raises a ValueError. """ if p_string is None or domain is None or mapping is None: return p_string res = io.StringIO() # void mapping if len(mapping) == 0: for c in p_string: if c not in domain: res.write(c) # surjective mapping elif len(mapping) == 1: for c in p_string: if c in domain: res.write(mapping) else: res.write(c) # injective mapping elif len(mapping) == len(domain): for c in p_string: pos = domain.find(c) if pos != -1: res.write(mapping[pos]) else: res.write(c) else: raise ValueError("len(mapping) > 1 and len(mapping) != len(domain)") return res.getvalue()
032f46aab9be5443ea118184068406b97391d785
544,112
def train_supervised( model, input_tensor, y_true, loss_fn, optimizer, multiclass =False, n_out = 1, ): """ Helper function to make forward and backward pass with minibatch. Params ------ n_out (int, default = 1) Dimensionality of output dimension. Leave as 1 for multiclass, i.e. the output is a probability distribution over classes (e.g. MNIST). """ # Zero out grads model.zero_grad() y_pred = model(input_tensor) #Note that if it's a multiclass classification (i.e. the output is a # probability distribution over classes) the loss_fn # nn.NLLLoss(y_pred, y_true) uses as input y_pred.size = (n_batch, n_classes) # and y_true.size = (n_batch), that's why it doesn't get reshaped. if multiclass: loss = loss_fn(y_pred, y_true) else: # Backprop error loss = loss_fn(y_pred, y_true.view(-1, n_out).float()) loss.backward() # Update weights optimizer.step() return loss
a17d0e883c281b7f5275dcc242e45c1537e8df57
418,692
def is_profile_flag(flag): """ return true if provided profile flag is valid """ return flag in ('cpu', 'mem', 'block', 'trace')
27931fe812840ffa935595d145b80c8073de0c70
611,537
def get_micro_secs(real_str: str) -> int: """ If there is a decimal point returns fractional part as an integer in units based on 10 to minus 6 ie if dealing with time; real_str is in seconds and any factional part is returned as an integer representing microseconds. Zero returned if no factional part :param real_str: A string with optional fraction :return: decimal part as integer based on micro units eg microseconds """ try: p1, p2 = real_str.split(".") except ValueError: return 0 if p2: p2 = f"{p2:0<6}" return int(p2) return 0
33f602bbfff3f18510609beaa7a2153b6ab35c9e
619,303
from typing import List def _get_difference_by(fields1: List[str], fields2: List[str]) -> List[str]: """Get list with common fields used to decimate and difference given Datasets Args: fields1: Fields of 1st Dataset fields2: Fields of 2nd Dataset Returns: List with common fields to decimate and difference given Datasets """ difference_by = [] common_fields = set(fields1) & set(fields2) for field in ["time", "satellite"]: if field in common_fields: difference_by.append(field) return difference_by
f80b36788c895269e41f6b2a67fe8961c58fb73c
38,453
def list_to_lowercase(l): """given a list of strings, make them all lowercase.""" return [x.lower() for x in l if type(x) is str]
c7dfee82d633e43d776dfb29924aa2c0f3b8a089
130,094
def playback_settings(framecount, days, sleep_sec): """Determine how many frames to skip based on days for total movie playtime and sleep time between screen refreshes. Returns tuple of (sec-to-sleep, frames-to-skip). """ sec_to_play = days * 24 * 60 * 60 frames_to_display = sec_to_play / sleep_sec frames_to_skip = framecount / frames_to_display adjusted_sleep_sec = sleep_sec # If there aren't enough frames to last 'days', # determine how long we should sleep in order to # stretch it out. if frames_to_skip < 1: adjusted_sleep_sec = (sec_to_play / framecount) frames_to_skip = 0 return (adjusted_sleep_sec, frames_to_skip)
6faea961d4e1edc5d4470256ccf1c025205ba111
285,482
import torch def mpjpe(predicted, target): """ Mean per-joint position error (i.e. mean Euclidean distance), often referred to as "Protocol #1" in many papers. """ assert predicted.shape == target.shape #l2_error = torch.mean(torch.norm((predicted - target), dim=len(target.shape) - 1), -1).squeeze() #print('each joint error:', torch.norm((predicted - target), dim=len(target.shape) - 1)) #index = np.where(l2_error.cpu().detach().numpy() > 0.3) # mean body l2 distance larger than 300mm #value = l2_error[l2_error > 0.3] #print('Index of mean body l2 distance larger than 300mm', index, value) return torch.mean(torch.norm((predicted - target), dim=len(target.shape) - 1))
d4f0d8ec6f611e064a97b55fe990a21a519efde8
299,423
def check_number_threads(numThreads): """Checks whether or not the requested number of threads has a valid value. Parameters ---------- numThreads : int or str The requested number of threads, should either be a strictly positive integer or "max" or None Returns ------- numThreads : int Corrected number of threads """ if (numThreads is None) or (isinstance(numThreads, str) and numThreads.lower() == 'max'): return -1 if (not isinstance(numThreads, int)) or numThreads < 1: raise ValueError('numThreads should either be "max" or a strictly positive integer') return numThreads
a8d683d5c265f43567031e8c10314efad2411ec9
42,809
def get_nx_pos(g): """Get x,y positions from a NetworkX CONSTELLATION graph. The returned dictionary is suitable to pass to networkx.draw(g, pos).""" pos = {} for n in g.nodes: x = g.nodes[n]['x'] y = g.nodes[n]['y'] pos[n] = x, y return pos
5004ae7e3314cc95a691e14b4e3acb3487b50982
416,906
def sanitize(guid: str) -> str: """ Removes dashes and replaces ambiguous characters :param guid: guid with either dashes or lowercase letters or ambiguous letters :return: sanitized guid """ if not guid: return '' guid = guid.replace('-', '').upper().replace('I', '1').replace('L', '1').replace('O', '0') return guid
fbb8c5e241e71f0919a55d89d805be6dfb5ac631
421,846
import json def get_dict(raw_json: bytes) -> dict: """ In the database our dictionaries are stored as raw bytes, this function returns them decoded and transformed back as dictionaries. :param raw_json: A JSON represented as raw bytes string :return: A dictionary from the decoded bytes """ return json.loads(raw_json.decode('utf-8'))
f911bcc5bcf4842a8c1692708b259fd9b546dca7
266,401
import math def gauss_objective(x, amplitude, sigma, mu): """Gaussian distribution objective function. This differs from many normal distribution equations online but the amplitude is required to stretch the Gaussian upward to match your specific data size. This equation was adapted from: https://stackoverflow.com/questions/19206332/gaussian-fit-for-python, but also matches the first equation on the Gaussian function Wikipedia page: https://en.wikipedia.org/wiki/Gaussian_function, and can be found elsewhere in this form as well.""" # return amplitude * (1 / (math.sqrt(2*math.pi*sigma**2))) * math.e**(-1 * (x-mu)**2 / 2*sigma**2) # return amplitude * np.exp(-(x - mu)**2 / (2 * sigma**2)) return amplitude * math.e**(-(x - mu)**2 / (2 * sigma**2))
5d98c35a900361c44bd2110d3325f5b58b1a3ca2
420,965
def customiseFor34120(process): """Ensure TrackerAdditionalParametersPerDetRcd ESProducer is run""" process.load("Geometry.TrackerGeometryBuilder.TrackerAdditionalParametersPerDet_cfi") return process
812279d18922ad1b3130447697f1010ac85b035e
632,523
def generate_progress_bar(percentage): """Generates the progress bar that can be used in a tweet Args: percentage (integer): Percentage progress to Christmas day Returns: string: Progress base using present emojis to visually show the progress of reaching Christmas day """ presents = (percentage//10)*"\U0001F381" empty_blocks = (10-percentage//10)*"🔲" tweet = f"{presents}{empty_blocks} {percentage}%" return tweet
91fb40078eca888fe6fe18292269009ad08c8844
522,212
def search_key(usb_dict, ids): """ Compare provided IDs to the built USB dictionary. If found, it will return the common name, otherwise returns the string "unknown". """ vendor_key = ids[0] product_key = ids[1] vendor, vendor_data = usb_dict.get(vendor_key, ['unknown', {}]) product = 'unknown' if vendor != 'unknown': product = vendor_data.get(product_key, 'unknown') return vendor, product
f2ef7128ca7fd18f45cc0ce2251aca3985f71c38
358,573
def metadata_from_box(box): """Return a metadata from box.""" return {"box_id": box.box_id, "name": box.name, "owner": box.owner, "created_at": box.created_at}
498a14d32f5b8ad3b50165477fa8aa6de44c6805
414,123