content
stringlengths
39
9.28k
sha1
stringlengths
40
40
id
int64
8
710k
def not_at_goal_set(trees): """convenience / readability function which returns the not terminated trees from a list :param trees: list of input trees :type trees: list :return: trees from the input list which are not terminated :rtype: list """ not_at_goal = [] for tree in trees: if not tree.terminated: not_at_goal.append(tree) return not_at_goal
0f5e911573a86deb16f842c8a2d57da06dc7db3f
563,773
def permalink_to_full_link(link: str) -> str: """Turns permalinks returned by Praw 4.0+ into full links""" return "https://www.reddit.com" + link
13a2eb003d4268eaffd4e1d0a51064a7e1b5e009
567,912
def extract_helm_from_json(input_json): """Extracts the HELM strings out of a JSON array. :param input_json: JSON array of Peptide objects :return: output_helm: string (extracted HELM strings separated by a newline) """ output_helm = "" for peptide in input_json: if len(output_helm) > 0: output_helm += "\n" output_helm += peptide["HELM"] return output_helm
8bad6bbc46f0c535f76cfb144d0d929a4d4b37c5
561,806
def category_name(value): """Maps category value to names""" return { 0: "idle", 1: "unassigned", 2: "work", 3: "private", 4: "break", }.get(value, "?")
5db040c808182b71fb3328fffefd82df02c9da73
442,761
import inspect def private_method(func): """Decorator for making an instance method private.""" def func_wrapper(*args, **kwargs): """Decorator wrapper function.""" outer_frame = inspect.stack()[1][0] if 'self' not in outer_frame.f_locals or outer_frame.f_locals['self'] is not args[0]: raise RuntimeError('%s.%s is a private method' % (args[0].__class__.__name__, func.__name__)) return func(*args, **kwargs) return func_wrapper
7dcab3cc628d8fa8e9eca357f026c6a7c598ed20
147,019
def unify_pos(pos, size): """ Convert position into standard one. Example: Given size = 5, Point(-2, -7) -> Point(3, 3) """ return pos % size
b7298aaa0c0055b038dead8e2a3a8424ca145b72
464,813
def exclude(func): """Return the opposite of ``func`` (i.e. ``False`` instead of ``True``)""" return lambda x: not func(x)
8052e10311a5d0be206da9d3a82a36564e69b7f8
607,558
import random def randInt32(rng=random.random): """returns a random integer in [-2147483648..2147483647]. rng must return float in [0..1] """ i = int(rng() * 0x7FFFFFFF) if rng() < .5: i *= -1 return i
fd51eeabf32ececcf19acaca425cbcf5844cf00f
514,585
import typing def split_name(name: str) -> typing.Tuple[str, str]: """ Returns a likely `(first, last)` split given a full name. This uses very simple heuristics, and assumes Western usage. :param name: A full name (first and last name). :return: A split pair with the first names, and the last name. """ words = name.split() first_bits = words[:-1] last_bits = words[-1:] while len(first_bits) > 0 and first_bits[-1][0].islower(): last_bits = [first_bits[-1]] + last_bits first_bits = first_bits[:-1] first_joined = " ".join(first_bits) last_joined = " ".join(last_bits) return first_joined, last_joined
54fe7579d382674b35b6e177e2c6feb6beeef6f8
380,417
def create_grid_string(grid): """Return a crossword grid as a string.""" size = len(grid) separator = ' +' + ('-----+')*size column_number_line = ' ' column_number_line += ''.join(f' {j:2} ' for j in range(size)) result = f'{column_number_line}\n{separator}\n' for (i, row) in enumerate(grid): fill = ' |' centre_line = f'{i:2}|' for entry in row: if entry == '#': fill += '#####|' centre_line += '#####|' else: fill += ' |' centre_line += f' {entry} |' result += f'{fill}\n{centre_line}\n{fill}\n{separator}\n' return result
2a820971f941e30de4d47482b65bbe5c1ebd34cf
540,076
def superset_data_db_name() -> str: """The name (in Superset) of the database that Superset reads from""" return 'MyCompany DWH'
e03a9e07268402badf35d649ef2bf3689e672dc1
466,996
def get_subsequences_matching_query(hit_obj): """Takes a SearchIO hit object, and returns a list with the first element being a string representing the coordinates of the query to which the subject sequence aligns, and the second being the corresponding subject subsequence(s). """ # ***Eventually add more sophisticated approach similar to # search_scaffolds.py, so that multiple HSPs can be represented. return [str(list(hit_obj[0].query_range)).replace(' ', ''),\ str(hit_obj[0].hit.seq).replace('-', '')]
f2382cb92d7b95289b2f4fc35bb08f25a5b830e0
611,463
def buoy_distance(pixel_width, focal_length, ACTUAL_WIDTH=0.4): """ Calculates the distance of the buoy from the boat. The algorithm uses the similar triangles in the following equation: (focal_len / pixel_width) = (actual_distance / actual_width) Keyword arguments: pixel_width -- The width of the buoy in pixels focal_length -- The focal length of the camera in pixels ACTUAL_WIDTH -- The actual width of the buoy in desired units (default 0.4m) Returns: distance -- The distance of the buoy in the units of the ACTUAL_WIDTH """ return focal_length * ACTUAL_WIDTH / pixel_width
492c4bb532cfed8aec0619b003711157051331ee
491,931
def init_jsobject(cls, bridge, name, value, description=None): """Initialize a JS object that is a subclassed base type. Arguments: cls -- Class the object has to be created from bridge -- JSBridge instance to use name -- Name of the JS object value -- Value of the object wrapped as JS object Keyword arguments: description -- Additional information about the object """ obj = cls(value) obj._bridge_ = bridge obj._name_ = name obj._description_ = description return obj
18d5a49b23e996c84aee725e29ffed2bee183f96
249,401
def default_order(json_page_obj): """Return ordering based on metadata.""" return json_page_obj["meta_order"], json_page_obj["title"]
04afeeaa9fd24b25638dc64cd1d97c4b64e01096
155,314
def centered_average(nums): """ take out 1 value of the smallest and largst compute and return the mean of the rest int div --> truncate the floating part? ASSUME: +3 ints pos/neg unsorted dupes possible Intutition: - computing an average (sum / # of points) Approach: 1. Simple - compute the min - compute the max - sum the whole list - subtract (min), and subtract max - return (remaining_sum) by (len = 2) Edge Cases: - all negatives --> normal - if in prod and saw input that broke constraints --> Error """ # - compute the min # - compute the max min_val, max_val = min(nums), max(nums) # - sum the whole list total = sum(nums) # - subtract (min), and subtract max remaining_sum = total - (min_val + max_val) # - return (remaining_sum) by (len = 2) return int(remaining_sum / (len(nums) - 2))
f6a664dd501b5ac36709d1ea482a5b274174d381
562,574
def x12_271_member_not_found_message() -> str: """A X12 271 message where the member is not found in the payer system and does not have insurance coverage""" return 'ISA*00* *00* *ZZ*890069730 *ZZ*154663145 *200929*1705*|*00501*000000001*0*T*:~GS*HS*890069730*154663145*20200929*1705*0001*X*005010X279A1~ST*271*4321*005010X279A1~BHT*0022*11*10001234*20060501*1319~HL*1**20*1~NM1*PR*2*ABC COMPANY*****PI*842610001~HL*2*1*21*1~NM1*1P*2*BONE AND JOINT CLINIC*****SV*2000035~HL*3*2*22*0~TRN*2*1453915417*9877281234~NM1*IL*1*DOE*JOHN****MI*11122333301~DMG*D8*19800519*M~AAA*Y**75*C~SE*12*4321~'
c98abb2ad2214c56c8a64d0f777f2a4354c7f885
550,105
def is_file_supported(suffix: str) -> bool: """ Check a path to be supported by safitty (only YAML or JSON) Args: suffix (str): path extension Returns: bool: File is YAML or JSON """ return suffix in [".json", ".yml", ".yaml"]
d89f10f563f1a415fd108b1a05b989ab20e0b191
448,641
def spacing(area, shape): """ Returns the spacing between grid nodes Parameters: * area ``(x1, x2, y1, y2)``: Borders of the grid * shape Shape of the regular grid, ie ``(nx, ny)``. Returns: * ``[dx, dy]`` Spacing the y and x directions Examples: >>> print(spacing((0, 10, 0, 20), (11, 11))) [1.0, 2.0] >>> print(spacing((0, 10, 0, 20), (11, 21))) [1.0, 1.0] >>> print(spacing((0, 10, 0, 20), (5, 21))) [2.5, 1.0] >>> print(spacing((0, 10, 0, 20), (21, 21))) [0.5, 1.0] """ x1, x2, y1, y2 = area nx, ny = shape dx = (x2 - x1)/(nx - 1) dy = (y2 - y1)/(ny - 1) return [dx, dy]
456a895baf875fb32dc9319602620848176b3ba1
62,546
def look_through_rows(board, column, player): """ Given a matrix, a column of the matrix, and a key, This function will look through the column bottom to top, and find the first empty slot indicated by a 0 and place a piece there (1 or 2) >>> look_through_rows(numpy.matrix('0,0,0,0,0; 0,0,0,0,0; 0,0,0,0,0; 0,0,0,0,0'), 2, 1) matrix([[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 1, 0, 0]]) >>> look_through_rows(numpy.matrix('0,0,0; 0,0,0; 0,0,0; 0,0,0; 0,0,0; 0,0,0; 0,0,0'), 1, 2) matrix([[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 2, 0]]) """ if board.shape[1] > column: count = board.shape[0] - 1 count2 = 1 while count >= 0 and count2 == 1: if board[count,column] == 0: board[count,column] = player count2 = count2 - 1 else: count = count - 1 return board else: print('Improper Column Given')
9849a0543d7430ac215b1debb6af820b573bde50
342,234
def get_available_resources(threshold, usage, total): """Get a map of the available resource capacity. :param threshold: A threshold on the maximum allowed resource usage. :param usage: A map of hosts to the resource usage. :param total: A map of hosts to the total resource capacity. :return: A map of hosts to the available resource capacity. """ return dict((host, int(threshold * total[host] - resource)) for host, resource in usage.items())
e5eca0a5eb6977d580f74ae6592b13211ac04f37
75,792
from typing import List from typing import Dict def find_it(seq: List[int]) -> int: """ Given an array, find the int that appears an odd number of times. :param seq: :return: """ pares: Dict[int, int] = dict() result: int = 0 for n in seq: if n not in pares: pares[n] = 1 else: pares[n] = pares[n] + 1 for key in pares.keys(): if pares[key] % 2 > 0: result = key break return result
224b01d5c09c4c97927760624931549c94972b41
301,458
def AND(*args) -> str: """ Creates an AND Statement >>> AND(1, 2, 3) 'AND(1, 2, 3)' """ return "AND({})".format(",".join(args))
c36b5fc6cfeeedfc0cc47c389a97aa1b63e77377
488,738
def scaled_grad(g, inv_d): """Computes the scaled gradient.""" return inv_d * g
c6b812a723d7c92dd66e63925368b7a542a2a50a
541,690
def invariants(tensor): """ Calculates the first, second, and dimensionless invariants of the gradient tensor. .. note:: The coordinate system used is x->North, y->East, z->Down Parameters: * tensor : list A list of arrays with the 6 components of the gradient tensor measured on a set of points. The order of the list should be: [gxx, gxy, gxz, gyy, gyz, gzz] Returns: * invariants : list = [:math:`I_1`, :math:`I_2`, :math:`I`] The invariants calculated for each point """ gxx, gxy, gxz, gyy, gyz, gzz = tensor gyyzz = gyy * gzz gyz_sqr = gyz ** 2 inv1 = gxx * gyy + gyyzz + gxx * gzz - gxy ** 2 - gyz_sqr - gxz ** 2 inv2 = (gxx * (gyyzz - gyz_sqr) + gxy * (gyz * gxz - gxy * gzz) + gxz * (gxy * gyz - gxz * gyy)) inv = -((0.5 * inv2) ** 2) / ((inv1 / 3.) ** 3) return [inv1, inv2, inv]
31a7bbe891be97b1e945fde85c956a36f1b28be3
262,322
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
d7a083575859bcdf92df697d4cb8a0bb22dbb19f
107,868
def find_features(extent, df): """ given an extent and a dataframe, return a new dataframe containing only features that fall within the extent Parameters ---------- extent: list -- geographic extent in lon (deg E)/lat (deg N) df: the geopandas dataframe to slice """ xleft, xright, ybot, ytop = extent hit_rows = df.cx[xleft:xright, ybot:ytop] return hit_rows
90d7e0811dbb6340d89387dc5331c4039cc9f6bf
617,010
def sum_even_integers(sequence): """ What comes in: -- A sequence What goes out: Returns the sum of the items in the sequence that: -- are integers AND -- are even. Side effects: None. Examples: sum_even_integers([3, 10, 6, 5, 5, 10]) returns 10 + 6 + 10, which is 26 sum_even_integers([3, 9, 10, 99, 101, 5, 6, 5, 5, 10]) still returns 10 + 6 + 10, which is 26 sum_even_integers(['hello', 3, 10, 6, 'bye', 5, 7.33, 5, 10]) still returns 10 + 6 + 10, which is 26 Type hints: :type sequence: list or tuple """ # ------------------------------------------------------------------ # EXAMPLE 2. Iterates through a sequence, # identifying and summing the items that are EVEN INTEGERS. # # Note how: # -- The TYPE function returns the TYPE of its argument. # -- An integer X is EVEN if the remainder is 0 # when you divide X by 2 and take the remainder. # ------------------------------------------------------------------ total = 0 for k in range(len(sequence)): item = sequence[k] if type(item) is int: if item % 2 == 0: total = total + item return total # Here is an alternative (there are other alternatives as well): total = 0 for k in range(len(sequence)): if (type(sequence[k]) is int) and (sequence[k] % 2 == 0): total = total + sequence[k] return total
ef7b1b1785d4d5ec0948f1b29b6e06bcb2e1ebda
448,790
import random def balance_dataset(data, ratio): """ Subsamples dataset according to ratio. @param data: List of samples. @param ratio: Ratio of samples to be returned. @return: Subsampled dataset. """ sampled_data = random.sample(data, int(ratio * len(data))) return sampled_data
a2471e909d0b8622bfb806912d54915254c4c198
222,533
def linear(y_0, y_1, x_0, x_1, k): """Returns the particular integral and its derivative for linear load. y_0, y_1 the ordinates @ the extremes of the loading, x_0, x_1 the abscissae @ the extremes of the loading, k the stiffness of the oscillator. The returned functions are defined in terms of a new variable, csi=x-x_0, in the interval 0 <= csi <= x_0. """ y_0, y_1 = y_0/k, y_1/k return (lambda x: y_0 + (y_1-y_0)/(x_1-x_0)*x, lambda x: (y_1-y_0)/(x_1-x_0))
9c1f9b1c0e5a7af70ca3dae48a6df103846534d2
277,449
from datetime import datetime def _datetime_now() -> datetime: """Wrap ``datetime.now`` to easily mock it for testing. Returns ------- datetime Current datetime. """ return datetime.now()
3373dbbcc6181c4a25e3b79f85f432876b56294a
438,057
def _get_available_memory(mem_feat, constraints=None): """Get available memory If constraints are given, parse constraint string into array of constraints and compare them to active features. Currently only handles comma-separated strings and not the more advanced constructs described in the slurm manual. Else, the minimum memory for a given partition is returned. """ if constraints is None: return min([int(x['mem']) for x in mem_feat]) try: constraint_set = set(constraints.split(",")) for x in mem_feat: if constraint_set.intersection(x["features"]) == constraint_set: return int(x["mem"]) except Exception as e: print(e) raise
9783084657979b46bd5a2a1c81abed09f5969fcd
605,963
def split(attr): """ Split <key>=<val> into tuple (<key>,<val>), if only string is passed, return ('id', <val>)""" if '=' in attr: ret = attr.split('=') return ret[0], ret[1] else: return 'id', attr
a975e8a0b44c73e52566144a80f886e88de61b04
377,303
def zero_diag(Q): """ Copy of Q altered such that diagonal entries are all 0. """ Q_nodiag = Q.copy() for ii in range(Q.shape[0]): Q_nodiag[ii, ii] = 0 return Q_nodiag
8c40fc58ee8e7af7a905de1d17b39c7d074cda17
73,034
def get_extremas_from_positions(positions): """ returns the minimum and maximum value for each dimension in the positions given """ return zip(*[(min(values), max(values)) for values in zip(*positions)])
9b30e2fde7f1ce5cf54b849793b67a5c02897c60
456,666
def degree(G,nbunch=None,weight=None): """Return degree of single node or of nbunch of nodes. If nbunch is ommitted, then return degrees of *all* nodes. """ return G.degree(nbunch,weight)
9a1fcc95960d6f318054fbc0a5a69add8ed78a46
511,466
def calc_angle(per, line): """ Calculate angle between two vector. Take into consideration a quarter circle :param per: first vector :type per: DB.XYZ :param line: second vector :type line: DB.XYZ :return: Angle between [-pi, pi] :rtype: float """ return (1 if per.Y >= 0 else -1) * per.AngleTo(line)
81290fd40dfd4d714f56478a2c41b33156ca8157
20,665
def generate_target_states_list(sweep, initial_state_labels): """Based on a bare state label (i1, i2, ...) with i1 being the excitation level of subsystem 1, i2 the excitation level of subsystem 2 etc., generate a list of new bare state labels. These bare state labels correspond to target states reached from the given initial one by single-photon qubit transitions. These are transitions where one of the qubit excitation levels increases at a time. There are no changes in oscillator photon numbers. Parameters ---------- sweep: ParameterSweep initial_state_labels: tuple(int1, int2, ...) bare-state labels of the initial state whose energy is supposed to be subtracted from the spectral data Returns ------- list of tuple""" target_states_list = [] for subsys_index, qbt_subsys in sweep.qbt_subsys_list: # iterate through qubit subsystems initial_qbt_state = initial_state_labels[subsys_index] for state_label in range(initial_qbt_state + 1, qbt_subsys.truncated_dim): # for given qubit subsystem, generate target labels by increasing that qubit excitation level target_labels = list(initial_state_labels) target_labels[subsys_index] = state_label target_states_list.append(tuple(target_labels)) return target_states_list
cbd7dc76790b48614fe81ec08c29453947c6984e
556,989
def linked_embeddings_name(channel_id): """Returns the name of the linked embedding matrix for some channel ID.""" return 'linked_embedding_matrix_%d' % channel_id
da3a095d86add49741fcb15f28059c124e6e7916
635,838
from typing import Callable from typing import List from typing import OrderedDict def order_json(data, sort_fn: Callable[[List[str]], List[str]] = sorted): """Sort json to a consistent order. When you hash json that has the some content but is different orders you get different fingerprints. .. code:: python >>> hashlib.sha1(json.dumps({'a': 12, 'b':14}).encode('utf-8')).hexdigest() ... '647aa7508f72ece3f8b9df986a206d95fd9a2caf' >>> hashlib.sha1(json.dumps({'b': 14, 'a':12}).encode('utf-8')).hexdigest() ... 'a22215982dc0e53617be08de7ba9f1a80d232b23' Note: According to json.org `An object is an unordered set of name/value pairs`. This means that the maps (dicts in python) should not contain semantic meaning in the order of the key value pairs. This means we are allowed to sort these maps without breaking something a user is doing in their custom config Similarly `An array is an ordered collection of values` this means that we should not sort the lists because that might break the way that a user is using a custom list in the json. :param data: The json data. :param sort_fn: A function that sorts the keys of the dictionary. :returns: collections.OrderedDict: The data in a consistent order (keys sorted alphabetically). """ new = OrderedDict() for key in sort_fn(data.keys()): value = data[key] # If the value is another map recursively sort that if isinstance(value, dict): value = order_json(value) # If the value is a list, recursively sort any maps that are in it. elif isinstance(value, list): value = [order_json(v) if isinstance(v, dict) else v for v in value] new[key] = value return new
657f932d54111405ee9ac606346d2b7cc02391eb
640,090
import torch def compute_argmax(ten): """Compute argmax for 2D grid for tensors of shape (batch_size, size_y, size_x) Args: ten (torch.[cuda].FloatTensor): (batch_size, size_y, size_x) Returns: indices (torch.[cuda].LongTensor): (batch_size, 2) index order: (y, x) """ batch_size = ten.shape[0] size_y = ten.shape[1] size_x = ten.shape[2] # shape: flattened_indices (batch_size) flattened_indices = torch.argmax(ten.view(batch_size, -1), dim=1) # shape: index_y (batch_size) # shape: index_x (batch_size) index_y = (flattened_indices // size_x) index_x = (flattened_indices % size_x) # shape: index_y (batch_size, 2) indices = torch.cat([index_y.unsqueeze(1), index_x.unsqueeze(1)], dim=1) return indices
d69c6ae13dfa2aef27a7e6ed621e928c146c0554
651,526
def get_util_shape(row): """Get utility term shape based on ROI. Parameters ---------- row : pandas.core.series.Series Row of func_df DataFrame. Returns ------- str If 'chest' or 'rib in row['Roi'], then return 'linear'. Otherwise, return 'linear_quadratic'. """ if any([roi in row['Roi'].lower() for roi in ['chest', 'rib']]): return 'linear' return 'linear_quadratic'
4ebb50dd0991f3edda7f33ad17fb3a3dfaf39de3
48,897
def isprefix(path1, path2): """Return true is path1 is a prefix of path2. :param path1: An FS path :param path2: An FS path >>> isprefix("foo/bar", "foo/bar/spam.txt") True >>> isprefix("foo/bar/", "foo/bar") True >>> isprefix("foo/barry", "foo/baz/bar") False >>> isprefix("foo/bar/baz/", "foo/baz/bar") False """ bits1 = path1.split("/") bits2 = path2.split("/") while bits1 and bits1[-1] == "": bits1.pop() if len(bits1) > len(bits2): return False for (bit1,bit2) in zip(bits1,bits2): if bit1 != bit2: return False return True
fad5eed531ed7fb3ed4e982d3fd7649dbf08ecac
622,237
from typing import Tuple def sat_idx_to_in_orbit_idx(sat_idx: int, num_sat_per_orbit: int) -> Tuple[int, int]: """ Compute the satellite index in orbit and orbit index. Starting from the satellite index in the constellation. Args: sat_idx: Index of the satellite in the constellation. num_sat_per_orbit: Total number of satellites in each orbit of the constellation. Returns: (int, int): Index of the satellite inside its orbit, index of the satellite's orbit. """ if num_sat_per_orbit < 1: raise ValueError sat_idx_in_orbit = sat_idx % num_sat_per_orbit orbit_idx = sat_idx // num_sat_per_orbit return sat_idx_in_orbit, orbit_idx
2985747f75887217bc4f1761d2407fce00db37d1
275,340
def non_gaussian(onset, frame): """ Calculate the Non-Gaussian parameter : ..math: \alpha_2 (t) = \frac{3}{5}\frac{\langle r_i^4(t)\rangle}{\langle r_i^2(t)\rangle^2} - 1 """ r_2 = ((frame - onset)**2).sum(axis=-1) return 3 / 5 * (r_2**2).mean() / r_2.mean()**2 - 1
961388fa6d7d362683ee830d3834afcf2b5c0740
410,720
def get_rain_svg(risk_of_rain: float) -> str: """ Get SVG path to risk of rain icon :param risk_of_rain: Risk of rain between 0 and 1 :return: path to SVG resource """ if risk_of_rain < 0.33: return 'Icons/Shades.svg' return 'Icons/Umbrella.svg'
fb5d28d9d0105d333366d8ced97cc04693cd9a37
278,973
import importlib def get_extractor_implementation(cls, pkg=None): """ Get the implementation of an Extractor. :param cls: class name (str) :param pkg: package where implementation is found (str) :return: class implementation """ # known extractors # others must be fully specified through pkg.cls if pkg: try: module = importlib.import_module(pkg) impl = getattr(module, cls) except: raise ValueError('Could not load feature definitions from file %s', pkg) else: impl = eval(cls) return impl
33bfa823e4b5dd44a0a02483f2a51965855c1bf2
592,210
import torch def disagreement(logits_1, logits_2): """Disagreement between the predictions of two classifiers.""" preds_1 = torch.argmax(logits_1, dim=-1).type(torch.int32) preds_2 = torch.argmax(logits_2, dim=-1).type(torch.int32) return torch.mean((preds_1 != preds_2).type(torch.float32))
82d12bb657018c4b446fd05c94c8f5834ce4fd59
636,464
def getPropertyAsSingleValue( data, name, default ): """ Read a property from an LDAP data structure. Multi-valued properties are read as single-valued, with only the first value being used. """ try: return data[name][0] except (IndexError, KeyError): return default
18d806b11d155a3c7dfbdf1d0aa2606a037e1bda
398,468
from typing import Tuple from typing import List from typing import Dict def selection(triple: Tuple[str, str, str], variables: List[str]) -> Dict[str, str]: """Apply a selection on a RDF triple, producing a set of solution mappings. Args: * triple: RDF triple on which the selection is applied. * variables: Input variables of the selection. Returns: A set of solution mappings built from the selection results. Example: >>> triple = (":Ann", "foaf:knows", ":Bob") >>> variables = ["?s", None, "?knows"] >>> selection(triple, variables) { "?s": ":Ann", "?knows": ":Bob" } """ bindings = dict() if variables[0] is not None: bindings[variables[0]] = triple[0] if variables[1] is not None: bindings[variables[1]] = triple[1] if variables[2] is not None: bindings[variables[2]] = triple[2] return bindings
fee52583e62d589863214e74e99fc427a0b6577d
35,175
import json def dump_json(file, array): """Dumps a dict to a JSON file""" with open(file, 'w') as f: return json.dump(array, f)
605a7bfcaeb7502749999b7a0b8353c724b66242
102,631
def models_of_same_type(*models): """ Checks whether all the provided `models` are of the same type. """ return len(set(m._meta.concrete_model for m in models)) == 1
c66abb7f115aee7f25fad474f560f1ea5d244d6b
316,064
def get_layout_locations(version, base_path, dsid): """Return dataset-related path in a RIA store Parameters ---------- version : int Layout version of the store. base_path : Path Base path of the store. dsid : str Dataset ID Returns ------- Path, Path, Path The location of the bare dataset repository in the store, the directory with archive files for the dataset, and the annex object directory are return in that order. """ if version == 1: dsgit_dir = base_path / dsid[:3] / dsid[3:] archive_dir = dsgit_dir / 'archives' dsobj_dir = dsgit_dir / 'annex' / 'objects' return dsgit_dir, archive_dir, dsobj_dir else: raise ValueError("Unknown layout version: {}".format(version))
1e147b1b056a63747b9445468cb043358cb64b44
295,940
def calCentroid(xmn, ymn, xmx, ymx): """ Function to calculate the centroid of a given image """ xmid = (xmx + xmn) / 2 ymid = (ymx + ymn) / 2 return xmid, ymid
98212262d8eff2b55f14a1feabfa49b00c33912a
182,385
def eqrr(registers, opcodes): """eqrr (equal register/register) sets register C to 1 if register A is equal to register B. Otherwise, register C is set to 0. """ return int(registers[opcodes[1]] == registers[opcodes[2]])
08b7e01e940fb6313fdcdc80df9fde604f951c5d
245,485
def get_normalisation_coefficient(sample_size): """ Returns a multiplicator for normalising entropy estimated on the sample based on the size of the sample. The coefficients were estimated empirically based on bootstrap resampling. """ if sample_size < 55: raise ValueError('No coefficients were estimated for sample sizes < 55') elif sample_size >= 55 and sample_size < 60: # 55-59 1.04 (2 langs) return 1.04 elif sample_size >= 60 and sample_size < 70: # 60-69 1.03 (1 lang) return 1.03 elif sample_size >= 70 and sample_size < 79: # 70-78 1.02 (0 langs) return 1.02 elif sample_size >= 79 and sample_size < 93: # 79-92 1.01 (5 langs) return 1.01 elif sample_size >= 110: # 110-130 0.99 return 0.99 else: # 93-109 1.00 return 1
add5b906f1f0fe3ad65647ec448896634008e5a3
267,817
import torch def focal_loss(bce_loss, targets, gamma, alpha): """Binary focal loss, mean. Per https://discuss.pytorch.org/t/is-this-a-correct-implementation-for-focal-loss-in-pytorch/43327/5 with improvements for alpha. :param bce_loss: Binary Cross Entropy loss, a torch tensor. :param targets: a torch tensor containing the ground truth, 0s and 1s. :param gamma: focal loss power parameter, a float scalar. :param alpha: weight of the class indicated by 1, a float scalar. """ p_t = torch.exp(-bce_loss) alpha_tensor = (1 - alpha) + targets * (2 * alpha - 1) # alpha if target = 1 and 1 - alpha if target = 0 f_loss = alpha_tensor * (1 - p_t) ** gamma * bce_loss return f_loss
b0f6cf127be66f178a2b509675bfab7007288e99
509,870
def response_id(req_data): """ Get the ID for the response from a JSON-RPC request Return None if ID is missing or invalid """ _id = None if isinstance(req_data, dict): _id = req_data.get('id') if type(_id) in (str, int): return _id else: return None
7c34d733aff93e213754833a2aadb19e0edfc0b5
160,374
import requests from bs4 import BeautifulSoup def get_data(url): """ Return BeautifulSoup html object. """ r = requests.get(url) data = BeautifulSoup(r.text, 'lxml') return data
2f21b5e7be7e86f4d04c361369332109cd852632
493,177
from typing import List import re def _find_matching_tags(tag: 'str', lst: 'List[str]'): """ Extract the full list of matches to the regex stored in tag. :param tag: A regex to search for :type tag: str :param lst: A set of tags to search :type lst: List[str] :return: The matching tags from lst :rtype: list[str] """ return [match for match in lst if re.fullmatch(tag, match)]
0976aba29fcefffff57428714882e6421de83846
557,412
def serialize_tree(root): """ Given a tree root node (some object with a 'data' attribute and a 'children' attribute which is a list of child nodes), serialize it to a list, each element of which is either a pair (data, has_children_flag), or None (which signals an end of a sibling chain). """ lst = [] def serialize_aux(node): # Recursive visitor function if len(node.children) > 0: # The node has children, so: # 1. add it to the list & mark that it has children # 2. recursively serialize its children # 3. finally add a "null" entry to signal this node has no children lst.append((node.data, True)) for child in node.children: serialize_aux(child) lst.append(None) else: # The node is child-less, so simply add it to # the list & mark that it has no children: lst.append((node.data, False)) serialize_aux(root) return lst
830a0dcaad9921b7eae1714bd2c7758aa11c4ad0
679,991
from typing import List from typing import Dict def species_by_charge(state_ids: List[str], charges: List[int]) -> Dict[int, List[str]]: """Make a dict with charge as key, and lists of species as values. Parameters ---------- state_ids - identifiers for states charges - charges for states Returns ------- Dict with charge as keys, and lists that contain the names of microstates with that charge. """ charge_dict = dict(zip(state_ids, charges)) species_dict = dict() # Duplicates don't matter for value in charge_dict.values(): species_dict[value] = list() for state_id, charge in charge_dict.items(): species_dict[charge].append(state_id) return species_dict
2b6736b4773f5d11a949c422de760a989ea9f252
391,158
def admin_pc_client(admin_pc): """Returns the client from the default admin's ProjectContext """ return admin_pc.client
e870e216b7a21c9e879d1bd12a5255f224c62310
73,811
from pathlib import Path def filesize(fname): """ Simply returns the size of the file fname in bytes """ return (Path(fname).stat().st_size)
1cf2cb0fbab2533e69c5200b25a134ee6dd61424
39,588
def _format_optname(value): """Format the name of an option in the configuration file to a more readable option in the command-line.""" return value.replace('_', '-').replace(' ', '-')
e12d0d27ed744d45d789f3e9e0207f04be9f5024
638,190
import zlib import pickle def blobdumps(py_obj, cPickle_protocol=2, compression_level=7): """ Pickle any Python object, and compress the pickled object. Returns a binary string. `compression_level`: Between 1 and 9 The higher the level is, the more compressed the object will be. """ return zlib.compress(pickle.dumps(py_obj, cPickle_protocol), compression_level).decode('latin1')
d84096ec369cff633f13f13754adf75565394d3e
462,649
def format_imports(import_statements): """ ----- examples: @need from fastest.constants import TestBodies @end @let import_input = TestBodies.TEST_STACK_IMPORTS_INPUT output = TestBodies.TEST_STACK_IMPORTS_OUTPUT @end 1) format_imports(import_input) -> output ----- :param import_statements: list :return: list """ return [ '{}\n'.format(import_statement.strip()) for import_statement in import_statements if len(import_statement) > 0 ]
91514d19da4a4dab8c832e6fc2d3c6cbe7cca04a
705,430
def CleanStrForFilenames(filename): """Sanitize a string to be used as a filename""" keepcharacters = (' ', '.', '_') FILEOUT = "".join(c for c in filename if c.isalnum() or c in keepcharacters).rstrip() return FILEOUT
f121fc167fcb80b00bf1f6aa5ecbff9b36acc54a
282,200
def lerp(a, b, x): """Linear interpolation between a and b using weight x.""" return a + x * (b - a)
b6790c221e797bfa0fe063a22ebced60eab877db
681,170
def make_key(x,y): """ function to combine two coordinates into a valid dict key """ return f'{x}, {y}'
14e414dd448eba8e3a7adfb5d5bbfc7f4fd22165
426,959
import re def extract_swagger_path(path): """ Extracts a swagger type path from the given flask style path. This /path/<parameter> turns into this /path/{parameter} And this /<string(length=2):lang_code>/<string:id>/<float:probability> to this: /{lang_code}/{id}/{probability} """ return re.sub('<(?:[^:]+:)?([^>]+)>', '{\\1}', path)
8563f028d4736d4032492a6d7a166aa5c3d97e36
607,791
def find_number_3_multiples(x): """Calculate the number of times that 3 goes into x.""" mult3=x//3 return mult3
64d429b520688afabad656b9d975daf8d9846ff1
122,881
def is_triangle_possible(triangle): """Check if triangle is possible.""" return sum(sorted(triangle)[:2]) > max(triangle)
6ce637fb523547b6aa11cd30e7497706ac97b88e
186,894
def create_content_item_id_set(id_set_list: list) -> dict: """ Given an id_set.json content item list, creates a dictionary representation""" res = dict() for item in id_set_list: for key, val in item.items(): res[key] = val return res
455f131fcf781fabf2573a226023f2cd8d4be5ae
526,139
import ast def parse_imports(filepath): """Formulate a dictionary of imports within a python file for usage by ``apipkg``. Parameters ---------- filepath The python file containing the imports to be parsed. Returns ------- imports_for_apipkg A dictionary of imports in the format expected by ``apipkg``. """ with open(filepath) as f: imports_string = f.read() imports_for_apipkg = {} for node in ast.parse(imports_string).body: if not isinstance(node, ast.Import): raise ValueError("Only direct import statements are supported") aliases = list(node.names) if len(aliases) != 1: raise ValueError("Only one alias per import supported") alias = aliases[0] asname = alias.asname if asname is None: asname = alias.name imports_for_apipkg[asname] = alias.name return imports_for_apipkg
9229c83812038d6a4370857fb933e0de69d87fd7
217,835
def aic_hmm(log_likelihood, dof): """ Function to compute the Aikaike's information criterion for an HMM given the log-likelihood of observations. :param log_likelihood: logarithmised likelihood of the model dof (int) - single numeric value representing the number of trainable parameters of the model :type log_likelihood: float :param dof: single numeric value representing the number of trainable parameters of the model :type dof: int :return: the Aikaike's information criterion :rtype: float """ return -2 * log_likelihood + 2 * dof
86fdea3262697eb5dd168f4f0927befa285c0e1a
544,464
def searchList(listOfTerms, query: str, filter='in'): """Search within a list""" matches = [] for item in listOfTerms: if filter == 'in' and query in item: matches.append(item) elif filter == 'start' and item.startswith(query): matches.append(item) elif filter == 'end' and item.endswith(query): matches.append(item) elif filter == 'exact' and item == query: matches.append(item) return matches
1a8b0fa6e870b2b3f088b634e3be1cc94a44e95b
143,573
def get_extrap_col_and_ht(height, num, primary_height, sensor='Ane', var='WS'): """ Determine name of column and height to use for extrapolation purposes :param height: comparison height :param num: number/label of comparison height :param primary_height: Primary comparison height :param sensor: type of sensor (either "Ane" or "RSD") :param var: variable to be extracted (can be 'WS', 'SD', or 'TI') :return col_name: column name of data to be extracted from inputdata :return ht: height to be extracted for extrapolation """ col_name = sensor + "_" + str(var) + "_Ht" + str(num) if 'primary' in col_name: if sensor == 'Ane': col_name = "Ref_" + str(var) elif sensor == 'RSD': col_name = 'RSD_' + str(var) height = float(primary_height) else: height = float(height) return col_name, height
286fd76046ee1bb9a128d1334b3475b5f15bafa3
273,460
def add_plugin_to_endpoints(endpoints, plugin): """ Add the endpoint key to each endpoint dictionary in the list :param endpoints: List of endpoint dictionaries :param plugin: String of the plugin name """ for endpoint in endpoints: endpoint.update({ 'plugin': plugin, }) return endpoints
2784278479c74a5b265dd8dedb0e7dd72ab3cd57
441,528
def compose(*functions): """ Compose functions This is useful for combining decorators. """ def _composed(*args): for fn in functions: try: args = fn(*args) except TypeError: # args must be scalar so we don't try to expand it args = fn(args) return args return _composed
50089b9343e6c7a91e88f679d8d02d7533083596
139,650
def getArrayDimensions(shape): """ Get the dimensions of the grid where the cell will be zoomed. The zoomed cell contains a `numpy` array and will be displayed in a table with the same shape than it. :Parameter shape: the cell shape :Returns: a tuple (rows, columns) """ # Numpy scalars are special a case if shape == (): nrows = ncols = 1 # 1-D arrays are displayed as a 1-column vector with nrows elif len(shape) == 1: nrows = shape[0] ncols = 1 # N-D arrays are displayed as a matrix (nrowsXncols) which # elements are (N-2)-D arrays else: nrows = shape[0] ncols = shape[1] return (nrows, ncols)
b79ae249763328196a3ab48306738287c063f600
361,080
def get_item_properties(item, columns): """Get specified in columns properties, with preserved order. Required for correct cli table generation :param item: dict :param columns: list with arbitrary keys """ properties = [] for key in columns: properties.append(item.get(key, '')) return properties
7e2a9bd3d337b2fc5fd83e10243ff7e96783f79a
553,576
def get_original_keys(keys, keymap, strict=False): """ Get original keys from normalized keys. Args: keys: The collection of keys that identify a value in the dataset. keymap: The keymap returned from :meth:`load` or :meth:`loads`. strict: If true, a KeyError will be raised if the given keys are not found in the keymap. Otherwise, the given key will be returned rather than the original key. This is helpful when reporting errors on required keys that do not exist in the data set. Since they are not in the dataset, no original key is available. Returns: A tuple containing the original keys names. """ original_keys = [] for i in range(len(keys)): try: loc = keymap[tuple(keys[:i+1])] line = loc.key_line original_keys.append(line.key) except AttributeError: # this occurs normally for list indexes original_keys.append(keys[i]) except (KeyError, IndexError): if strict: raise original_keys.append(keys[i]) return tuple(original_keys)
876d2ba8a7be2b8652958c27b0841242c5ed279e
289,939
from pathlib import Path def enterprise_1_12_artifact() -> Path: """ Return the path to a build artifact for DC/OS Enterprise 1.12. """ return Path('/tmp/dcos_generate_config_1_12.ee.sh')
33273d2a4e220c6b28b69310c69452172e4cad29
289,310
import json def create_label(name, color, repos, session, origin): """ Creates label :param name: name of the label :param color: color of the label :param repos: repository where label is created :param session: session for communication :param origin: repository where the label came from :return: message code 200 (int) """ for repo in repos: if(repo != origin): data = {"name": name, "color": color} json_data = json.dumps(data) r = session.post("https://api.github.com/repos/"+repo+"/labels", json_data) return "200"
c5f157673967c8f1b8928c3831abf4558ef5dc92
674,625
def indent(block): """Indent each row of the given string block with ``n*2`` spaces.""" indentation = " " * 2 return "\n".join([indentation + s for s in block.split('\n')])
c694c3eca23fbc5d2d8b4df2d321f55db559799e
342,904
def version_greater_or_equal_to(version, min_version): """Compares two version strings and returns True if version > min_version >>> version_greater_or_equal_to('1.0', '0') True >>> version_greater_or_equal_to('1.0', '0.9.9.9') True >>> version_greater_or_equal_to('1.0', '2.0') False >>> version_greater_or_equal_to('0.9.9.9', '1.0') False >>> version_greater_or_equal_to('1.0', '1.0') True >>> version_greater_or_equal_to('9.8.7.6.5.4.32.1', '9.8.7.6.5.4.3.1') True """ for i in range(0, min(len(min_version), len(version))): if version[i] < min_version[i]: return False elif version[i] > min_version[i]: return True # if equal we need to check the next least-significant number # All checked numbers were equal, but version could be smaller if it is # shorter, e.g. 2.4 < 2.4.1 return len(version) <= len(min_version)
b3050bd321374abb0d2e82b3080a4174644d20e9
605,226
def to_red(string): """ Converts a string to bright red color (16bit) Returns: str: the string in bright red color """ return f"\u001b[31;1m{string}\u001b[0m"
c4c7ee43c872b1ea9ad37c1d72540a1227b58926
98,298
import re def get_function_name(line): """Get name of a function.""" func_name = re.split(r"\(", line)[0] func_name = re.split(r" ", func_name)[-1] func_name = re.sub(r"(\*|\+|\-)", r"", func_name) return func_name
f5b7048755000929822a6d97577dc872a4d4e966
656,369
def linearize_dict(indict, sep='_', lower=False): """Linearize levels of an input dict, using separator Args: indict(`dict`): input dict with nested levels sep(str): separator lower(bool): lower all itens Returns: `dict`: output dict with just one level """ def linearize_level(level, sep, lower, suffix=''): outdict = {} for i in level.keys(): new_suffix = suffix + i.lower() if lower else suffix + i if isinstance(level[i], dict): part = linearize_level(level[i], sep, lower, new_suffix + sep) outdict.update(part) else: outdict[new_suffix] = level[i] return outdict return linearize_level(indict, sep, lower)
7e236f607cb4c583c9818dd3c51b3184f9e26252
523,895
def check_resource_existence(client, resource_group): """Create if resource group exists in Azure or not :param client: Azure object using ResourceManagementClient :param resource_group: string, name of Azure resource group :return: True if exists, otherwise False :rtype: boolean """ response = client.resource_groups.check_existence(resource_group) return response
b6f66d10593ce8208167bb965bbdc7c5252296ee
145,487
import re def diff_replace_old_new(diff): """Return the (old, new) filenames from difference tuple `diff`.""" match = re.search(r"replaced '(.+)' with '(.+)'", diff[-1]) if match: return match.group(1), match.group(2) else: return None, None
ef8365320bc9a01d5de9aec8265b7f572eb15011
142,693
import hashlib def checksum_file(f, blocksize: int = 2 << 15) -> str: """ Checksum a file-like object. """ hasher = hashlib.sha256() for block in iter(lambda: f.read(blocksize), b""): hasher.update(block) f.seek(0) return hasher.hexdigest()
c40f53bf03612564f5817c1a732e246dce330ed3
605,351
def get_node_set_map(tuple_list): """ Function to get a mapping of random node names to values between 0 and number of nodes - 1, with a modified adjacency list. Args: tuple_list : adjacency list with weights and arbitrary node names Returns: tuples : canonicalized adjacency list node_map : mapping from node name to index """ node_set = set() for tpl in tuple_list: node_set.update(tpl[:2]) node_map = {node_name: idx for idx, node_name in enumerate(node_set)} tuples = [(node_map[src], node_map[dst], wgt) for src, dst, wgt in tuple_list] return tuples, node_map
e30113775a4783d38da6b994fc49b83154db10ae
317,655
import json def is_new_version_model_file(model_file_path: str) -> bool: """Check whether the model file belongs to the new version of HuggingFace Tokenizers, i.e., >= 0.8 Parameters ---------- model_file_path Path to the model file Returns ------- is_new_version Whether the model file is generated by the new version of huggingface tokenizer. """ with open(model_file_path, 'r', encoding='utf-8') as f: try: _ = json.load(f) return True except Exception: return False
5cea582ca6fd4a86bcb71832fe8866f86a319b0e
408,754
import json def configure_connection (instance, name = 'database', credentials = None): """Configures IBM Streams for a certain connection. Creates or updates an application configuration object containing the required properties with connection information. Example for creating a configuration for a Streams instance with connection details:: from icpd_core import icpd_util from streamsx.rest_primitives import Instance import streamsx.database as db cfg = icpd_util.get_service_instance_details (name='your-streams-instance') cfg[context.ConfigParams.SSL_VERIFY] = False instance = Instance.of_service (cfg) app_cfg = db.configure_connection (instance, credentials = 'my_credentials_json') In Cloud Pak for Data you can configure a connection to Db2 with `Connecting to data sources <https://www.ibm.com/support/producthub/icpdata/docs/content/SSQNUZ_current/cpd/access/connect-data-sources.html>`_ Example using this configured external connection with the name 'Db2-Cloud' to create an application configuration for IBM Streams:: db_external_connection = icpd_util.get_connection('Db2-Cloud',conn_class='external') app_cfg = db.configure_connection (instance, credentials = db_external_connection) Args: instance(streamsx.rest_primitives.Instance): IBM Streams instance object. name(str): Name of the application configuration, default name is 'database'. credentials(str|dict): The service credentials, for example Db2 Warehouse service credentials. Returns: Name of the application configuration. """ description = 'Database credentials' properties = {} if credentials is None: raise TypeError (credentials) if isinstance (credentials, dict): if 'class' in credentials: if credentials.get('class') == 'external': # CP4D external connection if 'url' in credentials: db_json = {} db_json['jdbcurl'] = credentials.get('url') db_json['username'] = credentials.get('username') db_json['password'] = credentials.get('password') properties ['credentials'] = json.dumps (db_json) else: raise TypeError(credentials) else: properties ['credentials'] = json.dumps (credentials) else: properties ['credentials'] = credentials # check if application configuration exists app_config = instance.get_application_configurations (name = name) if app_config: print ('update application configuration: ' + name) app_config[0].update (properties) else: print ('create application configuration: ' + name) instance.create_application_configuration (name, properties, description) return name
4d55b1ff45c59831b8d398a0420df9a7048bab6a
233,314
def has_tag(method, tag: str) -> bool: """ Checks if the given method has the given tag. :param method: The method to check. :param tag: The tag to check for. :return: True if the tag exists on the method, False if not. """ return hasattr(method, '__tags') and tag in method.__tags
efa797eee30cff4614db899a968b1122c5882de2
515,964
def make_plant_indices(plant_ids, storage_candidates=None): """Make the indices for existing and hypothetical generators for input to Switch. :param iterable plant_ids: plant IDs. :param set storage_candidates: buses at which to enable storage expansion. :return: (*dict*) -- keys are {'existing', 'expansion', 'storage'}, values are lists of indices (str) for each sub-type. """ indices = {"existing": [f"g{p}" for p in plant_ids]} indices["expansion"] = [f"{e}i" for e in indices["existing"]] if storage_candidates is None: indices["storage"] = [] else: indices["storage"] = [f"s{b}i" for b in sorted(storage_candidates)] return indices
526ceb12896ddc9f4e7abae977b733896f277ebc
488,244
def get_blurb(in_file): """Get the first paragraph of a Markdown file""" with open(in_file, "r") as f: f.readline() # Title f.readline() # Title underline f.readline() # Blank out = "" line = f.readline() while len(line) > 0 and line != "\n": out += line.replace("\n", " ") line = f.readline() return out.strip()
8701ad31e5e99dd42b6cfab222b1c33aab255a5a
535,189
def pointInRect(p, rect): """Return True when point (x, y) is inside rect.""" (x, y) = p xMin, yMin, xMax, yMax = rect return (xMin <= x <= xMax) and (yMin <= y <= yMax)
1754deaf63b1b78f2ed5c67cc8a7824e4c8f1a35
152,278