content
stringlengths
39
9.28k
sha1
stringlengths
40
40
id
int64
8
710k
import math def gcd(*args): """ Generalize math.gcd to take more than two inputs. """ items = list(args) while len(items) > 1: items.append(math.gcd(items.pop(), items.pop())) return items[0]
c9d139b9a05d68e09ff7b0756167d92a0b1c2211
596,641
def signature(params, separator='/'): """Create a params str signature.""" def _signature(params, sig): for key in params.keys(): sig.append(key) if isinstance(params[key], dict): _signature(params[key], sig) my_list = list() _signature(params, my_list) return separator.join(my_list)
44470d1e4fed1a357cec888f6ec112e67f60a3a1
316,603
import json def get_user_data(user_id, orgs=None, groups=None): """Get an example redis user object""" if groups is None: groups = [ { "name": "organization_admin", "permissions": [ {"name": "all", "code": "all"}, {"name": "foo", "code": "foo"}, {"name": "bar", "code": "bar"}, {"name": "baz", "code": "baz"}, ], } ] if orgs is None: orgs = [{"name": "organization.admin", "id": 1, "groups": groups}] return json.dumps({"id": user_id, "username": "test.user", "organizations": orgs})
2af1b7daaa2acfd355e3d0535d62fa03ca07a783
352,792
def filter_number(data, target, number): """Filters the given data for the wanted number.""" return [x for x, y in zip(data, target) if y == number]
b2ef61e32e33084e45a3be19e6d39e2207885e78
419,997
def intersect_line_ray(lineSeg, raySeg): """ Constructs a line from the start and end points of a given line segment, and finds the intersection between that line and a ray constructed from the start and end points of a given ray segment. If there is no intersection (i.e. the ray goes in the opposite direction or the ray is parallel to the line), returns None. """ lineStart, lineEnd = lineSeg rayStart, rayEnd = raySeg lineVector = (lineEnd[0] - lineStart[0], lineEnd[1] - lineStart[1]) rayVector = (rayEnd[0] - rayStart[0], rayEnd[1] - rayStart[1]) p1x, p1y = lineStart p2x, p2y = rayStart d1x, d1y = lineVector d2x, d2y = rayVector # Check if the ray is parallel to the line. parallel = ( (d1x == 0 and d2x == 0) or ((d1x != 0 and d2x != 0) and (float(d1y) / d1x == float(d2y) / d2x)) ) intersection = None # Only non-parallel lines can ever intersect. if not parallel: # Parametrize the line and ray to find the intersection. parameter = ( float(p2y * d1x - p1y * d1x - p2x * d1y + p1x * d1y) / (d2x * d1y - d1x * d2y) ) # Only consider intersections that occur in front of the ray. if parameter >= 0: intersection = ( p2x + parameter * d2x, p2y + parameter * d2y, ) return intersection
365836039161666eb30d0051916dceb7260f3c19
90,062
def get_denominator(denominator: float | int) -> int: """ If denominator is a float or int, then return the integer value. If denominator is a float, then round it to the nearest integer. If the rounded value is 0, then return 1. Parameters ---------- denominator : Union[float, int] The denominator. Returns ------- int The denominator as integer. """ return int(max(round(denominator, 0), 1))
95ba08743fd9b1a30ed246e39095666dcfc2494c
326,939
def build_edge_topic_prefix(device_id: str, module_id: str) -> str: """ Helper function to build the prefix that is common to all topics. :param str device_id: The device_id for the device or module. :param str module_id: (optional) The module_id for the module. Set to `None` if build a prefix for a device. :return: The topic prefix, including the trailing slash (`/`) """ if module_id: return "$iothub/{}/{}/".format(device_id, module_id) else: return "$iothub/{}/".format(device_id)
05fe493967b1064dc21c0f4280297a35102f55a1
107,534
import torch def compute_angle(xyz, angle_list): """ Compute angles between atoms. Args: xyz (torch.Tensor): coordinates of the atoms. angle_list (torch.LongTensor): directed indices of sets of three atoms that are all in each other's neighborhood. Returns: angle (torch.Tensor): tensor of angles for each element in the angle list. """ # points from j -> i r_ji = xyz[angle_list[:, 0]] - xyz[angle_list[:, 1]] # points from j -> k r_jk = xyz[angle_list[:, 2]] - xyz[angle_list[:, 1]] x = torch.sum(r_ji * r_jk, dim=-1) y = torch.cross(r_ji, r_jk) y = torch.norm(y, dim=-1) angle = torch.atan2(y, x) return angle
da689c38f891d582130a880ced7b6f5c9da3d62b
295,262
def create_location_code(channel_obj): """ Get the location code given the components and channel number :param channel_obj: Channel object :type channel_obj: :class:`~mth5.metadata.Channel` :return: 2 character location code :rtype: string """ location_code = "{0}{1}".format( channel_obj.component[0].upper(), channel_obj.channel_number % 10 ) return location_code
bfee90668369d075690e72efc2eadec95c4ed2cf
320,788
def alias(aliases): """Decorator for slashcommand aliases that will add the same command but with different names. Parameters ---------- aliases: List[:class:`str`] | :class:`str` The alias(es) for the command with wich the command can be invoked with Usage: .. code-block:: @ui.slash.command(name="cats", ...) @ui.slash.alias(["catz", "cute_things"]) """ def wraper(command): if not hasattr(command, "__aliases__"): command.__aliases__ = [] # Allow multiple alias decorators command.__aliases__.extend(aliases if not isinstance(aliases, str) else [aliases]) return command return wraper
95c20f61348dc043ced53f4e95fac0fb24ee117f
641,732
from typing import Dict from typing import Tuple def extract_base_url_from_spec(spec: Dict) -> Tuple[str, Dict]: """Extract the server urls from the spec to be used when generating functions. Args: spec: The OpenAPI Spec dictionary to extract the urls from. Returns: A tuple of the first BASE_URL (as default) and a variables dictionary that sets the BASE_URL. Exceptions: ValueError: If the spec has no URLs in its "servers" section. """ if len(spec["servers"]) == 0: raise ValueError("No server URLs found in spec") base_urls = [s["url"] for s in spec["servers"]] variables = {"BASE_URL": base_urls[0]} return base_urls[0], variables
ab434db79c5e3e76667668bedcde6af5054c6709
148,228
def seconds_to_time(seconds): """Return a nicely formatted time given the number of seconds.""" m, s = divmod(seconds, 60) h, m = divmod(m, 60) d, h = divmod(h, 24) return "%d days, %02d hours, %02d minutes, %02d seconds" % (d, h, m, s)
bf87da51527af08f60b3425169af1f696ecc9020
14,605
def elementwise_within_bands(true_val, lower_val, upper_val): """Whether ``true_val`` is strictly between ``lower_val`` and ``upper_val``. Parameters ---------- true_val : float True value. lower_val : float Lower bound. upper_val : float Upper bound. Returns ------- is_within_band : float 1.0 if error is strictly within the limits, else 0.0 """ return 1.0 if lower_val < true_val < upper_val else 0.0
90f822eed76339446ec56836d0d80ee58a08219c
394,180
def split(el, n): """ Split list of elements in n approx. equal parts for multiprocessing Parameters ---------- el : list List of elements to split n : int Number of lists to split input up into Returns ------- parts : Iterable List of n lists of parts of the input """ k, m = divmod(len(list(el)), n) parts = [el[i * k + min(i, m):(i + 1) * k + min(i + 1, m)] for i in range(n)] return parts
1f4045ade61a3b80fbe0092b1e335bfc870a8d32
253,208
def name_to_number(name): """ Converts a string called name to an integer. Otherwise, it sends an error message letting you know that an invalid choice was made. """ if name == "rock": return 0 elif name == "Spock": return 1 elif name == "paper": return 2 elif name == "lizard": return 3 elif name == "scissors": return 4 else: return "Not a valid choice"
a38fd44573cb6a5be9fe58a6b1859ae7a3a47849
430,845
def get_status(dev): """Get FPGA status""" dev.write_raw('PL:ACTIVE?') r = dev.read_raw() assert len(r) == 1 return ord(r[0]) - ord('0')
b5ecbc32ff1da632742d6d32694eb63a9ab23bea
534,109
def set_default_attr(obj, name, value): """Set the `name` attribute of `obj` to `value` if the attribute does not already exist Parameters ---------- obj: Object Object whose `name` attribute will be returned (after setting it to `value`, if necessary) name: String Name of the attribute to set to `value`, or to return value: Object Default value to give to `obj.name` if the attribute does not already exist Returns ------- Object `obj.name` if it exists. Else, `value` Examples -------- >>> foo = type("Foo", tuple(), {"my_attr": 32}) >>> set_default_attr(foo, "my_attr", 99) 32 >>> set_default_attr(foo, "other_attr", 9000) 9000 >>> assert foo.my_attr == 32 >>> assert foo.other_attr == 9000 """ try: return getattr(obj, name) except AttributeError: setattr(obj, name, value) return value
651538a814dee5c3af69a99f1a97be0e49734d88
657,571
def delta(m, n): """Kronecker delta""" if m == n: val = 1 else: val = 0 return val
d2586ff41a7f8cd743f061a4235fd31675636f93
300,537
def find_combos(length: int) -> int: """ In the data, there are no gaps of two, only gaps of one or three, between numbers in the sorted list. The rules are such that the number of combos are the same regardless of the specific numbers involved--there are the same number of combos for [0, 1, 2, 3] and for [23, 24, 25, 26]. So we only need the length of a run to figure out the number of combos in it. The rule is that any number can be skipped as long as there's not a gap of more than three. Since we're dealing with runs that are separated by gaps of three, the first and last numbers must be included in each combo. So for [0, 1, 2] the only combos are [0, 2] and [0, 1, 2]. For runs of three, the answer is two. For four, it's four. But at five, you hit a limit of having a gap of more than three between the start and finish. Because the start and finish numbers of each run are required, and gaps of more than three aren't allowed, and there are no gaps of two, it looks like a run of n has combos equal to the sum of runs of n-1, n-2, n-3. n1 = 1 n2 = 1 n3 = 2 n4 = 4 n5 = 7 n6 = 13 """ start = {0: 0, 1: 1, 2: 1} if length in start: return start[length] return sum(map(find_combos, [max([0, length - _]) for _ in (1, 2, 3)]))
8ff8d5c161508c9d55d24ddbcfa2f67f8e95fc5b
620,115
def prod_cart(in_list_1: list, in_list_2: list) -> list: """ Compute the cartesian product of two list :param in_list_1: the first list to be evaluated :param in_list_2: the second list to be evaluated :return: the prodotto cartesiano result as [[x,y],..] """ _list = [] for element_1 in in_list_1: for element_2 in in_list_2: _list.append([element_1,element_2]) return _list
9fdbfc558f5ec3b11c78535b9125e0a1c293035e
1,727
import torch def select_class(X: torch.Tensor, y: torch.Tensor, k: int): """ Select all vector examples from the training set matrix X that correspond to the class k :param X: a Float matrix of size (N, d), where d is the vector dimension :param y: a Long vector of class labels :param k: the class to select :return: a Float torch.Tensor matrix of size (N_k, d), where N_k is the number of examples of class k """ indices = (y == k).nonzero().squeeze(1) return torch.index_select(X, 0, indices)
04dc6729da8fb23f44eaca0ed3bfe3a0dfffef77
223,560
def calc_map_dims(x_size, y_size, mp_size, mp_dpi): """ Calculate output map size. :param x_size: <int or float> Image x dimension :param y_size: <int or float> Image y dimension :param mp_size: <int> Percent of image space of which the map will occupy :param mp_dpi: <int> Map density, as dots per inch :return: <list> [x_dimension, y_dimension] """ if x_size <= 0: raise Exception("x_size must be greater than 0; value supplied: {0}".format(x_size)) if y_size <= 0: raise Exception("y_size must be greater than 0; value supplied: {0}".format(y_size)) if mp_size <= 0: raise Exception("mp_size must be greater than 0; value supplied: {0}".format(mp_size)) if mp_dpi <= 0: raise Exception("mp_dpi must be greater than 0; value supplied: {0}".format(mp_dpi)) img_y_scaled = y_size * (mp_size * 0.01) img_x_scaled = x_size * (mp_size * 0.01) map_y_dim = img_y_scaled / mp_dpi map_x_dim = img_x_scaled / mp_dpi return map_x_dim, map_y_dim
6ba3d1299097b3247c2527a321b1924e58f9ac85
587,339
def inter_cluster_variance(clusters, graph): """ The inter cluster variance, or the within-cluster sum of squares returns for all given clusters the sum of squared distances of each sample within that cluster to the clusters centroid. The sum of those squared distances is returned. For distance calculation the distance function provided by the given graph is used. :param clusters: The clusters to determine the squared sum for :param graph: The underlying graph that offers a distance function :return: Sum of inter cluster variances for all given clusters """ if len(clusters) > 0: result = 0 for cluster in clusters: cluster_mean = graph.distance.mean(list(cluster)) for node in cluster: result += graph.distance(cluster_mean, node)**2 return result return float("inf")
42bef8a0863baaa64f9dde64bde3b4890b145000
518,558
def runge_kutta4(t0, dt, tf, x0, f): """ Implements the Runge Kutta 4 algorithm for numerically integrating the solution of a system of first order differential equations. :param t0: Initial time :param dt: Fixed time step :param tf: Final time :param x0: Initial state; NOTE: must be numpy array for non-scalar case :param f: System dynamics as f(t,x) :return: t, x; the time and state histories """ # Initialize time, state history variables ts = [t0] xs = [x0] dxs = [] # Determine number of time steps n_steps = round((tf - t0) / dt) # Initialize time, state t = t0 x = x0 for i_step in range(0, n_steps): # Perform Integration k1 = dt*f(t, x) k2 = dt*f(t + 0.5*dt, x + 0.5*k1) k3 = dt*f(t + 0.5*dt, x + 0.5*k2) k4 = dt*f(t + dt, x + k3) # Update time, state t += dt dx = (1.0/6.0)*(k1 + 2*k2 + 2*k3 + k4) x = x + dx # Record Time, State ts.append(t) xs.append(x) dxs.append(dx/dt) return ts, xs, dxs
2d6445e123e615f70f83b2a215a7706323ac6ffb
221,849
def expand_series(ser, columns): """ Helper function to quickly expand a series to a dataframe with according column axis and every single column being the equal to the given series. """ return ser.to_frame(columns[0]).reindex(columns=columns).ffill(axis=1)
e86956f5a32cb44066361846a0e602d53cfb241b
572,901
from typing import Union import torch from typing import Any def squeeze(_list:Union[list, tuple, torch.Tensor, Any], hard=False): """If list only has 1 element, returns that element, else returns original list. :param hard: If True, then if list/tuple, filters out None, and takes the first element out even if that list/tuple has more than 1 element""" if isinstance(_list, (tuple, list)): if hard: return [e for e in _list if e != None and e != ""][0] elif len(_list) == 1: return _list[0] if isinstance(_list, torch.Tensor): return _list.squeeze() return _list
7c2acb01db65106b8b3cef116b7cd799517e4498
487,290
def jaccard(set1,set2): """ Calculates Jaccard coefficient between two sets.""" if(len(set1) == 0 or len(set2) == 0): return 0 return float(len(set1 & set2)) / len(set1 | set2)
20dfb2d2c34b0915bd13979b732344176bec7e84
430,157
def fixed16(code, length): """Creates a fixed16 header.""" return "%s %11d\n" % (code, length)
a368eb1056a9d13979e6fd1023cd77740d41d702
311,999
import json def parse_json(file_path: str) -> dict: """Summary Load and parse json file Args: file_path (str): path of config file """ with open(file_path) as file_obj: return json.load(file_obj)
9177ee41f174fa9e62e4eb2ddb7726948f7dd116
279,889
def compare(riddle, attempt): """ compare function gets answer for "Bulls&Cows" game by comparison riddle to attempt :param riddle: the string consisted of 4 different numeric symbols to be recognised :param attempt: the string consisted of 4 different numeric symbols as an attempt to recognize the riddle :return result: the string of template 'B1 C2' ('B0 C0', 'B2 C2', etc.) """ bulls = 0 cows = 0 # check every 4 symbols of the attempt against the riddle for i in range(4): if attempt[i] == riddle[i]: # if symbol is in the same position it contributes to bulls bulls += 1 else: if attempt[i] in riddle: # if symbol is in the different position it contributes to cows cows += 1 # the response of template 'B1 C2' ('B0 C0', 'B2 C2', etc.) return 'B' + str(bulls) + ' C' + str(cows)
bffce2ae5d0a06a9dcc2c1b685537b48373df0d9
533,195
def nullHeuristic(state, problem=None): """ A heuristic function estimates the cost from the current state to the nearest goal in the provided SearchProblem. This heuristic is trivial. """ return 0
34502d37d218cacda6857818c8f51229f48042b5
419,360
def convert(x,y): """ converts a set and a dict into the required "X" format for algX for instance: X = {1, 2, 3, 4, 5, 6, 7} Y = { 'A': [1, 4, 7], 'B': [1, 4], 'C': [4, 5, 7], 'D': [3, 5, 6], 'E': [2, 3, 6, 7], 'F': [2, 7]} outputs: { 1: {'A', 'B'}, 2: {'E', 'F'}, 3: {'D', 'E'}, 4: {'A', 'B', 'C'}, 5: {'C', 'D'}, 6: {'D', 'E'}, 7: {'A', 'C', 'E', 'F'}} """ x = {j: set() for j in x} for i in y: for j in y[i]: x[j].add(i) return x
129c6283bd1dd0276df6a3954e032ccf5a2e3221
409,505
import math def acos_deg(value): """ returns acos as angle in degrees """ return math.degrees(math.acos(value) )
c908ad126caf0be23a2df15446392d0448bbda8a
241,847
import pickle def load_dt(filename): """ 加载保存好的决策树 :param filename: 文件名 :return: python dict """ # 'b' 表示二进制模式 fr = open(filename, 'rb') return pickle.load(fr)
c61772d6c8606e45ef323bd8dd30cb0c9e6ebf35
11,008
import math def calculate_distance_km_given_pl_abg_nlos(acceptable_PL_ABG_NLOS, radio_frequency, alpha, beta, gamma, sigma): """ Calculate distance given Free-space path loss (FSPL) Formula: PL_ABG_NLOS (in dB) = 10 * alpha * log(d) + beta + 10 * gamma * log(f) + sigma distance in meters formula d = 10 ** (1/(10 * alpha) * (PL_ABG_NLOS - beta - 10 * gamma * log(f) - sigma)) Distance from path loss in db, radio frequency, alpha, beta, gamma, sigma :param acceptable_PL_ABG_NLOS: :param radio_frequency: :param alpha: alpha :param beta: beta (in dB) :param gamma: gamma :param sigma: sigma (in dB) :return: """ return round((10 ** (1 / (10 * alpha) * (acceptable_PL_ABG_NLOS - beta - sigma - (10 * gamma * math.log10(radio_frequency / 1000000000)))))/1000, 2)
bc8424e8716490e4729417892f54c67ecb1beecc
502,177
def zero_counter(number): """Counts the number of consecutive 0's at the end of the number""" x = 0 while (number >> x) & 1 == 0: x = x + 1 return x
598fdc5bfed992f6921151e831c3d71c6ea184cf
258,911
def flatten_dict(d): """Flatten a dictionary where values may be other dictionaries The dictionary returned will have keys created by joining higher- to lower-level keys with dots. e.g. if the original dict d is {'a': {'x':3, 'y':4}, 'b':{'z':5}, 'c':{} } then the dict returned will be {'a.x':3, 'a.y': 4, 'b.z':5} Note that if a key is mapped to an empty dict or list, NO key in the returned dict is created for this key. Also note that values may be overwritten if there is conflicting dot notation in the input dictionary, e.g. {'a': {'x': 3}, 'a.x': 4}. """ # http://codereview.stackexchange.com/a/21035 def expand(key, value): if isinstance(value, list): value = {i: v for (i, v) in enumerate(value)} if isinstance(value, dict): return [ (str(key) + "." + str(k), v) for k, v in flatten_dict(value).items() ] else: return [(key, value)] items = [item for k, v in d.items() for item in expand(k, v)] return dict(items)
3efd9a4edacedd22ac42f3b8db16392acd69d70a
410,689
import gzip def open_file(file_path, mode = 'r'): """ Open a file which can be gzipped. :param file_path: :param mode: :return: """ if file_path.split(".")[-1] =="gz": #print "opening gzipped file" INFILE = gzip.open(file_path, mode+'b') else: INFILE = open(file_path, mode) return INFILE
f117344ead1f51397689e5af3c427a109290a884
429,670
def can_link_to(person, contact, model): """ Determines whether or not the specified person can form a social network link to the specified contact. :param person: The person wanting to link. :param contact: The contact to determine link eligibility. :param model: The model to use. """ if model.require_mutual and \ len(contact.contacts) >= contact.max_contacts and \ not person.unique_id in contact.contacts: return False return True
8250b3d2ff7fb5be2cb47e83caa99c827517ea79
689,344
def skeletonModuleName(mname): """Convert a scoped name string into the corresponding skeleton module name. e.g. M1.M2.I -> M1__POA.M2.I""" l = mname.split(".") l[0] = l[0] + "__POA" return ".".join(l)
e6c898d11303d7138e14e0fcd061782873c08142
356,781
def get_variables_for_task(doc, task): """ Get the variables that a task must record Args: doc (:obj:`SedDocument`): SED document task (:obj:`Task`): task Returns: :obj:`list` of :obj:`Variable`: variables that task must record """ variables = set() for data_gen in doc.data_generators: for var in data_gen.variables: if var.task == task: variables.add(var) return list(variables)
727db5187c9f9cc19ba8a258a4e01bd270ca470a
556,834
def number_of_sublists(l): """ Retorna el numero de sublistas que contiene una lista. :param l: Lista a calcular :type l: list :return: Número de sublistas :rtype: int """ count = 0 for i in l: if isinstance(i, list): count = count + 1 + number_of_sublists(i) return count
185c56b91fd2a34c71fcf0e12fb4401596883e72
501,669
import six def Enum(*sequential, **named): """ Create an enumeration. >>> Numbers = Enum('ZERO', 'ONE', 'TWO') >>> Numbers.ZERO 0 >>> Numbers.ONE 1 Credits http://stackoverflow.com/a/1695250 """ enums = dict(six.moves.zip(sequential, six.moves.range(len(sequential))), **named) return type('Enum', (), enums)
1508d2b3b5ea16d9404c23b901cc9e9a52ef2168
332,766
def list_symbols(client, drawing=None, symbol_file=None, sheet=None): """List symbols contained on a drawing. Args: client (obj): creopyson Client drawing (str, optional): Drawing name. Defaults: current active drawing. symbol_file (str, optional): Symbol file name filter. Defaults: no filter. sheet (int, optional): Sheet number (0 for all sheets). Defaults: The symbol will be added to all sheets. Returns: (list:dict): List of symbols in the drawing. id (int): Symbol ID. symbol_name (str): Symbol name. sheet (int): Sheet number. """ data = {} if drawing: data["drawing"] = drawing if symbol_file: data["symbol_file"] = symbol_file if sheet: data["sheet"] = sheet return client._creoson_post("drawing", "list_symbols", data, "symbols")
859c9c3689ef795db5b06ce3ed760ddf5c4d14f2
201,126
def unhex(x): """Ensure hexidecimal strings are converted to decimal form""" if x == '': return '0' elif x.startswith('0x'): return str(int(x, base=16)) else: return x
a13c64dc8ae4bded1a2d5f896c83b5fa5bc08bba
515,170
import yaml def parse_yaml_to_dict(contents): """ Parses YAML to a dict. Parameters ---------- contents : str The contents of a file with user-defined configuration settings. Returns ------- dict Configuration settings (one key-value pair per setting) or an empty dict. """ if contents: return yaml.safe_load(contents) else: return dict()
de97a20c5343ab909351261a3dfafad8590b2f57
61,870
def net_gains(principal,expected_returns,years,people=1): """Calculates the net gain after Irish Capital Gains Tax of a given principal for a given expected_returns over a given period of years""" cgt_tax_exemption=1270*people #tax free threashold all gains after this are taxed at the cgt_ta_rate cgt_tax_rate=0.33 #cgt_tax_rate as of 19/3/21 total_p=principal year=0 while year < years: year+=1 gross_returns=total_p*expected_returns if gross_returns >cgt_tax_exemption: taxable_returns=gross_returns-cgt_tax_exemption net_returns=cgt_tax_exemption+(taxable_returns*(1-cgt_tax_rate)) else: net_returns=gross_returns total_p= total_p + net_returns return total_p
623b6c1126ad2486ba94c3b02f1a8ed335fed74b
648,228
def selection_sort(items): """Sort given items by finding minimum item, swapping it with first unsorted item, and repeating until all items are in sorted order. Running time: O(n**2) As it loops through the whole array for each element Memory usage: O(1) Sorting is done in place on the array """ # Loop through each index for i in range(len(items)): # Find the smallest unsorted value ind = items.index(min(items[i:]), i) # Switch it with the current index items[ind], items[i] = items[i], items[ind] return items
d7396df561adc9805d5e91dcbfa3ddd3e67018a8
146,046
import functools import operator def comb(n: int, k: int) -> int: """Compute binomial coefficient n choose k""" if not 0 <= k <= n: return 0 k = min(k, n - k) numerator = functools.reduce(operator.mul, range(n, n - k, -1), 1) denominator = functools.reduce(operator.mul, range(1, k + 1), 1) return numerator // denominator
a2bd3ec8dc28b581e271b9420d4dac3cf30a4547
423,314
import torch def apply_gains(bayer_images, red_gains, blue_gains): """Applies white balance gains to a batch of Bayer images.""" red_gains = red_gains.squeeze(1) blue_gains= blue_gains.squeeze(1) bayer_images = bayer_images.permute(0, 2, 3, 1) # Permute the image tensor to BxHxWxC format from BxCxHxW format green_gains = torch.ones_like(red_gains) gains = torch.stack([red_gains, green_gains, green_gains, blue_gains], dim=-1) gains = gains[:, None, None, :] outs = bayer_images * gains outs = outs.permute(0, 3, 1, 2) # Re-Permute the tensor back to BxCxHxW format return outs
f8bb037ba247d5c5e3963d16c9a9c4dd3d002b0e
238,710
def get_sha1_or_none(repo, ref): """Return string of the ref's commit hash if valid, else None. :repo: a callable supporting git commands, e.g. repo("status") :ref: string of the reference to parse :returns: string of the ref's commit hash if valid, else None. """ commit = repo("rev-parse", "--revs-only", ref).strip() return commit if commit else None
d20473120136b5f2410b5210a013451bfa68e250
647,336
def reached_minimum_node_size(data, min_node_size): """ Purpose: Determine if the node contains at most the minimum number of data points Input : Data array and minimum node size Output : True if minimum size has been reached, else False """ if len(data) <= min_node_size: return True else: return False
6240a65f67ad8d98232395f7184c0ff44a24c996
410,015
def check_sequence_names_present(sequence): """ Checks that the names of entities are all present """ result = any(map(lambda x: 'name' in x, sequence)) if not result: return { 'result': False, 'message': "All entries in ssl_sequence must have a name." } return { 'result': True, 'message': "All entries have a defined name." }
3edcf93023f18d5db731712c9e248c1ba24c6834
318,413
def find_distance(a, b, c): """Determine if distance between three ints is equal assuming unsorted entries""" int_holder = [a, b, c] int_holder.sort() distance_1 = int_holder[1] - int_holder[0] distance_2 = int_holder[2] - int_holder[1] if distance_1 == distance_2: return 'They are equally spaced' return None
3e488b631c248de3069f4167f157022358114852
33,879
import builtins def podstrc_vstup(monkeypatch): """Podstrčí funkci input daný vstup, tak jako by ho zadal uživatel.""" # Tohle je trochu pokročilá testovací magie. # Viz pokročilý kurz: https://naucse.python.cz/course/mi-pyt/intro/testing/ vstup = [] def _podstrc(*args): vstup.extend(args) def podstrceny_input(otazka): assert vstup != [], 'Program by neměl pokládat další otázku' odpoved = vstup.pop(0) print(otazka + odpoved) return odpoved monkeypatch.setattr(builtins, 'input', podstrceny_input) yield _podstrc # Kontrola, že všechno ze vstupu bylo přečteno: assert vstup == [], 'Nepřečtené odpovědi'
29d19db389bc87cdd10c1d73361c6025a5eca9e8
399,579
def proc_to_str(val, entry): """Process a value to string""" return str(val)
04c01556c1f6673f3935b9880a7eb4e6839badb6
572,322
def find_nodes(graph, filter_fn): """ Find all nodes whose names pass the predicate :filter_fn. """ nodes = set() for node in graph.nodes.values(): if filter_fn(node.name): nodes.add(node) return nodes
d4aca7e4582161098677ed44051cf9cd65956b4b
185,725
def parse_file(filename): """ Parses file for error messages in logs Args: filename Returns: error_count: count of error messages in file error_msgs: list of error messages """ # Initialize return vals error_count = 0 error_msgs = [] with open(filename, 'r') as file: for line in file: # Try to find error message and locate index in string str_to_find = 'error -' str_idx = line.lower().find(str_to_find) # If error is found, extract and increment count if str_idx != -1: error_count += 1 str_start = str_idx + len(str_to_find) + 1 error_msg = line[str_start:].strip() error_msgs.append(error_msg) return error_count, error_msgs
855ad9411646961b3afdec14e7b3547af81fae84
35,214
import unicodedata def is_control(ch): """判断'char'是否是Control or Format""" if ch == "\t" or ch == "\n" or ch == "\r": return False cat = unicodedata.category(ch) # Cc表示Control Cf表示Format if cat in ("Cc", "Cf"): return True return False
0fb469bff38a0c677bbcf66eddb27c7a0466622e
449,927
import torch def loss_bbox_regression(offsets, gt_offsets): """ Use sum-squared error as in YOLO. @Params: ------- offsets (tensor): Predicted bbox offsets of shape [M, 4]. gt_offsets (tensor): GT bbox offsets of shape [M, 4]. @Returns: ------- loss_bbox_reg (scalar tensor): Loss of bbox regression. """ return torch.mean(torch.sum((offsets - gt_offsets)**2, dim=1))
0adc65b74a925ff38b3051c2f0cd33d93efd9fcf
384,141
import re def pascal_case_ify(name): """ Uppercase first letter of ``name``, or any letter following an ``_``. In the latter case, also strips out the ``_``. => key_for becomes KeyFor => options becomes Options """ return re.sub(r'(^|_)\w', lambda m: m.group(0)[-1].upper(), name)
5b7a47274f7e6e774089ad7618a63dfe7651a4ab
295,374
import random def _random_value(x = None, min=0, max=10): """ (not very eye pleasing ;) returns a random int between min and max """ return random.randint(min,max)
315300dd21d56885d47448e5b6660a72cffb0bc4
678,416
def IsVector(paramType): """ Check if a param type translates to a vector of values """ pType = paramType.lower() if pType == 'integer' or pType == 'float': return False elif pType == 'color' or pType.startswith('float'): return True return False
58a14693ffabc2230eea0b3f6702aa56ffc514ca
41,857
def subprocess_command(exp='xpptut15', run='0260', procname='pixel_status', qname='psnehq',\ dt_sec=60, sources='cspad,opal,epix100,pnccd,princeton,andor') : """Returns command like 'proc_control -e xpptut15 -r 0260 -p pixel_status -q psnehq -t 60 -s cspad,pnccd' """ if procname == 'pixel_status' : return 'proc_control -e %s -r %s -p %s -q %s -t %d -s %s' %\ (exp, str(run), procname, qname, dt_sec, sources) else : return None
4e9a6665c6fd75470ac118a9630d3f684e9261f6
213,655
import re def extractYearMonthDate(url): """Assumes url is a string, representing a url with a full date returns re match object, representing the full date from the url""" pattern = "\d{4}/\d{2}/\d{2}" result = re.search(pattern, url) return result
4ec18936ab43368aba09e49d1699ab26a4d57e8f
111,263
def norm_ws(s): """Normalize whitespace in the given string.""" return ' '.join(s.strip().split())
7d9b5e01bd3b310a09ef1205e0ce94da1f0d4a42
262,186
import json def _exiftool_json_sidecar( self, use_albums_as_keywords=False, use_persons_as_keywords=False, keyword_template=None, description_template=None, ignore_date_modified=False, ): """ Return dict of EXIF details for building exiftool JSON sidecar or sending commands to ExifTool. Does not include all the EXIF fields as those are likely already in the image. Args: use_albums_as_keywords: treat album names as keywords use_persons_as_keywords: treat person names as keywords keyword_template: (list of strings); list of template strings to render as keywords description_template: (list of strings); list of template strings to render for the description ignore_date_modified: if True, sets EXIF:ModifyDate to EXIF:DateTimeOriginal even if date_modified is set Returns: dict with exiftool tags / values Exports the following: EXIF:ImageDescription XMP:Description (may include template) XMP:Title XMP:TagsList IPTC:Keywords (may include album name, person name, or template) XMP:Subject XMP:PersonInImage EXIF:GPSLatitude, EXIF:GPSLongitude EXIF:GPSPosition EXIF:GPSLatitudeRef, EXIF:GPSLongitudeRef EXIF:DateTimeOriginal EXIF:OffsetTimeOriginal EXIF:ModifyDate IPTC:DigitalCreationDate IPTC:DateCreated """ exif = self._exiftool_dict( use_albums_as_keywords=use_albums_as_keywords, use_persons_as_keywords=use_persons_as_keywords, keyword_template=keyword_template, description_template=description_template, ignore_date_modified=ignore_date_modified, ) return json.dumps([exif])
13d3cfe697d34f1967a1251dce0703adc3d16c59
240,367
import re from datetime import datetime import pytz def parse_dates(date_string, hour=12): """ Extract a pair of dates from a string Args: date_string(str): A string containing start and end dates hour(int): Default hour of the day Returns: tuple of datetime: Start and end datetimes """ # Start and end dates in same month (Jun 18-19, 2020) pattern_1_month = re.compile( r"(?P<start_m>\w+)\s+(?P<start_d>\d+)\s*-\s*(?P<end_d>\d+)?,\s*(?P<year>\d{4})$" ) # Start and end dates in different months, same year (Jun 18 - Jul 18, 2020) pattern_1_year = re.compile( r"(?P<start_m>\w+)\s+(?P<start_d>\d+)\s*\-\s*(?P<end_m>\w+)\s+(?P<end_d>\d+),\s*(?P<year>\d{4})$" ) # Start and end dates in different years (Dec 21, 2020-Jan 10,2021) pattern_2_years = re.compile( r"(?P<start_m>\w+)\s+(?P<start_d>\d+),\s*(?P<start_y>\d{4})\s*-\s*(?P<end_m>\w+)\s+(?P<end_d>\d+),\s*(?P<end_y>\d{4})$" ) match = re.match(pattern_1_month, date_string) if match: start_date = datetime.strptime( f"{match.group('start_m')} {match.group('start_d')} {match.group('year')}", "%b %d %Y", ).replace(hour=hour, tzinfo=pytz.utc) end_date = datetime.strptime( f"{match.group('start_m')} {match.group('end_d')} {match.group('year')}", "%b %d %Y", ).replace(hour=hour, tzinfo=pytz.utc) return start_date, end_date match = re.match(pattern_1_year, date_string) if match: start_date = datetime.strptime( f"{match.group('start_m')} {match.group('start_d')} {match.group('year')}", "%b %d %Y", ).replace(hour=hour, tzinfo=pytz.utc) end_date = datetime.strptime( f"{match.group('end_m')} {match.group('end_d')} {match.group('year')}", "%b %d %Y", ).replace(hour=hour, tzinfo=pytz.utc) return start_date, end_date match = re.match(pattern_2_years, date_string) if match: start_date = datetime.strptime( f"{match.group('start_m')} {match.group('start_d')} {match.group('start_y')}", "%b %d %Y", ).replace(hour=hour, tzinfo=pytz.utc) end_date = datetime.strptime( f"{match.group('end_m')} {match.group('end_d')} {match.group('end_y')}", "%b %d %Y", ).replace(hour=hour, tzinfo=pytz.utc) return start_date, end_date
eb24dd98e405b87cff6224d89450ee6834bebb27
159,799
def parse_row(row, cols, sheet): """ parse a row into a dict :param int row: row index :param dict cols: dict of header, column index :param Sheet sheet: sheet to parse data from :return: dict of values key'ed by their column name :rtype: dict[str, str] """ vals = {} for header, col in cols.items(): cell = sheet.cell(row, col) vals[header] = cell.value return vals
580afc8d38f1ea2ce13fa9ccdc5c75e56860a97c
668,398
def accuracy(reference, test): """ Given a list of reference values and a corresponding list of test values, return the percentage of corresponding values that are equal. In particular, return the percentage of indices C{0<i<=len(test)} such that C{test[i] == reference[i]}. @type reference: C{list} @param reference: An ordered list of reference values. @type test: C{list} @param test: A list of values to compare against the corresponding reference values. @raise ValueError: If C{reference} and C{length} do not have the same length. """ if len(reference) != len(test): raise ValueError("Lists must have the same length.") num_correct = [1 for x,y in zip(reference, test) if x==y] return float(len(num_correct)) / len(reference)
d4729fb115efb3037f677342c9faf3f08c993466
288,151
def _calculate_payload_size(payload_length): """For a given payload, return the bytes needed for the payload. This is for the entire payload with padding, regardless of which unit it is stored in. >>> _calculate_payload_size(0) 8 >>> _calculate_payload_size(8) 8 >>> _calculate_payload_size(9) 16 >>> _calculate_payload_size(16) 16 """ if 8 < payload_length: return (payload_length + 7) & 0x07F8 else: return 8
473679c2ddf2a088b037a312777269c6b3535f20
452,372
import threading def threaded(call, *args, **kwargs): """Execute ``call(*args, **kwargs)`` in a thread""" thread = threading.Thread(target=call, args=args, kwargs=kwargs) thread.start() return thread
6c16d5bfcf9eb037169d1b4e6958d46e2fc6abe9
576,214
def parse_response_status(status: str) -> str: """Create a message from the response status data :param status: Status of the operation. :return: Resulting message to be sent to the UI. """ message = status if status == 'SUCCESS': message = "Face authentication successful" elif status == 'NEW_USER': message = "Face signup successful" elif status == 'USER_NOT_FOUND': message = "User not registered" elif status == 'FAILED': message = "Face authentication failed" return message
7eab8fa4b115d79c014070fd78d7d088011bf226
80,931
import pathlib def git_path(repo_root, tail=None): """Returns a Path to the .git directory in repo_root with tail appended (if present) or None if repo_root is not set. """ path = None if repo_root: path = pathlib.Path(repo_root) / ".git" if tail is not None: path = path / str(tail) return path
6335deadff7613657ea3dcd7e5019bf863aba67d
667,766
import re def CamelCaseToOutputFriendly(string): """Converts camel case text into output friendly text. Args: string: The string to convert. Returns: The string converted from CamelCase to output friendly text. Examples: 'camelCase' -> 'camel case' 'CamelCase' -> 'camel case' 'camelTLA' -> 'camel tla' """ return re.sub('([A-Z]+)', r' \1', string).strip().lower()
a1d726fe68649efe0c0b6cf17e95e55ad4a8183f
54,813
def help_flag_present(argv: list[str], flag_name: str = 'help') -> bool: """ Checks if a help flag is present in argv. :param argv: sys.argv :param flag_name: the name, which will be prefixed with '-', that is a help flag. The default value is 'help' :return: if the help flag is present """ return any([arg == f'-{flag_name}' for arg in argv])
a804ec64702e6173d94c50f024373f67d9893344
669,769
def slicebyn(obj, n, end=None): """ Iterator over n-length slices of obj from the range 0 to end. end defaults to len(obj). """ if end is None: end = len(obj) return (obj[i:i+n] for i in range(0, end, n))
4a87829826a8d440a99a1815252b25526623ef00
95,281
def regrid_get_operator_method(operator, method): """Return the regridding method of a regridding operator. :Parameters: operator: `RegridOperator` The regridding operator. method: `str` or `None` A regridding method. If `None` then ignored. If a `str` then an exception is raised if it not equivalent to the regridding operator's method. :Returns: `string` The operator's regridding method. """ if method is None: method = operator.method elif not operator.check_method(method): raise ValueError( f"Method {method!r} does not match the method of the " f"regridding operator: {operator.method!r}" ) return method
59b728fc74d89cf3daee34dff668d62a6d1fe5b0
638,039
def getName(fp, fp_names): """Determines the new name of a fingerprint in case multiple fingerprints with the same name""" # check if fp already exists. if yes, add a number if fp in fp_names: suffix = 2 tmp_name = fp + "_" + str(suffix) while tmp_name in fp_names: suffix += 1 tmp_name = fp + "_" + str(suffix) return tmp_name else: return fp
446701f56c142bd07e7ae12b796439481feda337
151,055
def get_least_key(kv): """ Given a dictionary, returns the key with minimum value. :param kv: Dictionary considered. :return: Key with the minimum value. """ min_k = None min_v = None for k, v in kv.items(): if min_v is None or v.item() < min_v: min_k = k min_v = v.item() return min_k
4357754a492ab3f463025d85576f3fe1a03c32e4
322,958
def char_encode(num: int, is_lower=True) -> str: """ Converts an integer to a character string \ with elements from a-z or A-Z. :num: The integer base 10 to be converted. :return: The character base 26. """ buffer = 97 if is_lower else 65 result = "" if num != 0 else chr(buffer + num % 26) while num > 0: result = chr(buffer + num % 26) + result num //= 26 return result
ccf90376d3dd260d8287cbf80df65fb799cc1ce6
333,620
def clean(s, chars): """Clean string s of characters in chars.""" translation_table = dict.fromkeys(map(ord, chars), '_') return s.translate(translation_table)
da18deb6ba272016a90ff5894f7bb63d2d4e57ee
283,626
def bytestring(s, encoding='utf-8', fallback='iso-8859-1'): """Convert a given string into a bytestring.""" if isinstance(s, bytes): return s try: return s.encode(encoding) except UnicodeError: return s.encode(fallback)
d73ae1377c770d218585c51db216b21918d5d562
122,423
def getValue(dataMatrix,x,y): """Return the sum of all the numbers in neighborhood.""" return dataMatrix[x-1][y-1]+dataMatrix[x-1][y]+dataMatrix[x-1][y+1]+dataMatrix[x][y-1]+dataMatrix[x][y]+dataMatrix[x][y+1]+dataMatrix[x+1][y-1]+dataMatrix[x+1][y]+dataMatrix[x+1][y+1]
7b80889bb91e0c9c68aee38f4ea0dddb773c0088
270,275
from datetime import datetime def validate_date(date_text): """Validates that the date is in ISO 8601 format: YYYY-MM-DD""" try: if date_text != datetime.strptime(date_text, "%Y-%m-%d").strftime('%Y-%m-%d'): return False return True except ValueError: return False
2d7592edc150b9270403d01c849fd57097111107
636,734
def filter_low_swh(ds): """Remove all records with low significant wave heights.""" return ds['sea_state_30m_significant_wave_height_spectral'] > 1.0
93c872885f446c0db87c6b3616b549a677ef5af8
676,386
from functools import reduce def compute_product_string(product_string): """Takes `product_string` and returns the product of the factors as string. Arguments: - `product_string`: string containing product ('<factor>*<factor>*...') """ factors = [float(f) for f in product_string.split("*")] return str(reduce(lambda x,y: x*y, factors))
ebd2a7e57529dc24960a29b5406634830f30bf83
628,380
def calc_rso(ra, frac=0.75): """ Clear-sky solar radiation. Parameters ---------- ra : numpy ndarray Extraterrestrial solar radiation. frac : float <= 1 Fraction of extraterrestrial solar radiation that reaches earth on clear-sky days. """ s = 'Please enter a fractional value less than or equal to 1.0 and ' \ 'greater than or equal to 0.0.' assert 0 <= frac <= 1, s return ra * frac
f6cd63ed42a30cb545b43df9991013bf2f0513d2
489,602
import re def lit_sub(*args, **kw): """Literal-safe version of re.sub. If the string to be operated on is a literal, return a literal result. All arguments are passed directly to ``re.sub``. """ lit = hasattr(args[2], '__html__') cls = args[2].__class__ result = re.sub(*args, **kw) if lit: return cls(result) else: return result
403c93ee341e4b0b2c6b7a7ef91bf55a0726ace0
537,149
import torch def init_mask(aux): """ Initializes masks of weight to freeze Parameters ---------- aux: dict A map from weight name to tuple (W, Z, U, project_fun) Returns ------- mask: dict A map from weight name to tuple (W, mask) """ with torch.no_grad(): mask = {} for weight_name, (W, _, _, project_fun) in aux.items(): _, m = project_fun(W) W[m] = 0 mask[weight_name] = (W, m) return mask
d9131d150a65ed00d4b4ee587fdad210b540652c
428,466
import re def interpret_cv(cv_index, settings): """ Read the cv_index'th CV from settings.cvs, identify its type (distance, angle, dihedral, or differance-of-distances) and the atom indices the define it (one-indexed) and return these. This function is designed for use in the umbrella_sampling jobtype only. For this reason, it only supports the aforementioned CV types. If none of these types appears to fit, this function raises a RuntimeError. Parameters ---------- cv_index : int The index for the CV to use; e.g., 6 corresponds to CV6. Must be in the range [1, len(settings.cvs)]. settings : argparse.Namespace Settings namespace object Returns ------- atoms : list A list of 1-indexed atom indices as strings that define the given CV optype : str A string (either 'distance', 'angle', 'dihedral', or 'diffdistance') corresponding to the type for this CV. nat : int The number of atoms constituting the given CV """ if not 1 <= cv_index <= len(settings.cvs): raise RuntimeError('called interpret_cv with an index outside the range [1, len(settings.cvs)].\n' 'len(settings.cvs) = ' + str(len(settings.cvs)) + ' and cv_index = ' + str(cv_index)) this_cv = settings.cvs[cv_index - 1] # -1 because CVs are 1-indexed if 'pytraj.dihedral' in this_cv or 'mdtraj.compute_dihedrals' in this_cv: optype = 'dihedral' nat = 4 elif 'pytraj.angle' in this_cv or 'mdtraj.compute_angles' in this_cv: optype = 'angle' nat = 3 elif 'pytraj.distance' in this_cv or 'mdtraj.compute_distances' in this_cv: if '-' in this_cv and (this_cv.count('pytraj.distance') == 2 or this_cv.count('mdtraj.compute_distances') == 2 or ('mdtraj.distance' in this_cv and 'pytraj.distance' in this_cv)): optype = 'diffdistance' nat = 4 else: optype = 'distance' nat = 2 else: raise RuntimeError('unable to discern CV type for CV' + str(int(cv_index)) + '\nOnly ' 'distances, angles, dihedrals, and differences of distances (all defined ' 'using either pytraj or mdtraj distance, angle, and/or dihedral functions) ' 'are supported in umbrella sampling. The offending CV is defined as: ' + this_cv) # Get atom indices as a string, then convert to list atoms = '' if not optype == 'diffdistance': count = 0 for match in re.finditer('[\[\\\']([@0-9]+[,\ ]){' + str(nat - 1) + '}[@0-9]+[\]\\\']', this_cv.replace(', ', ',')): atoms += this_cv.replace(', ', ',')[match.start():match.end()] # should be only one match count += 1 if not count == 1: raise RuntimeError('failed to identify atoms constituting CV definition: ' + this_cv + '\nInterpreted as a ' + optype + ' but found ' + str(count) + ' blocks of atom indices with length ' + str(nat) + '(should be one). Is' ' this CV formatted in an unusual way?') if not atoms: raise RuntimeError('unable to identify atoms constituting CV definition: ' + this_cv + '\nIs it formatted in an unusual way?') atoms = atoms.replace('[', '').replace(']', ',').replace('\'', '') # included delimeters for safety, but don't want them if '@' in atoms: atoms = [item.replace('@', '') for item in atoms.split(' @')] # pytraj style atom indices else: atoms = atoms.split(',') # mdtraj style atom indices atoms = [str(int(item) + 1) for item in atoms if not item == ''] # fix zero-indexing in mdtraj else: count = 0 for match in re.finditer('[\[\\\']([@0-9]+[,\ ]){1}[@0-9]+[\]\\\']', this_cv.replace(', ', ',')): atoms += this_cv.replace(', ', ',')[match.start():match.end()] # should be two matches count += 1 if not count == 2: raise RuntimeError('failed to identify atoms constituting CV definition: ' + this_cv + '\nInterpreted as a difference of distances but found ' + str(count) + ' blocks of atom indices with length 2 (should be two). Is this CV ' 'formatted in an unusual way?') if not atoms: raise RuntimeError('unable to identify atoms constituting CV definition: ' + this_cv + '\nIs it formatted in an unusual way?') atoms = atoms.replace('[', '').replace(']', ',').replace('\'', '') # included delimeters for safety, but don't want them if '@' in atoms: atoms = [item.replace('@', '') for item in atoms.replace('\'', ' ').replace('@', ' @').split()] else: atoms = atoms.split(',') atoms = [str(int(item) + 1) for item in atoms if not item == ''] # fix zero-indexing in mdtraj while '' in atoms: atoms.remove('') # remove empty list elements if present return atoms, optype, nat
01ef867caf1aa8756182dcab3a0e3bc2261cacc2
661,824
def add_to_dict_if_not_present(target_dict, target_key, value): """Adds the given value to the give dict as the given key only if the given key is not in the given dict yet. """ if target_key in target_dict: return False target_dict[target_key] = value return True
343b3324a17adb8055680e0226404c8c127e3267
375,550
def cytoscape_edge(edge): """convert edge data into cytoscape format""" return dict( id=edge["_id"], edgeType=edge["edge_type"], score=edge["score"], source=edge["_from"], target=edge["_to"], )
e435f4aac213795f8fb755b84d765ceda6751493
549,272
def the_H_function(sorted_citations_list, n=1): """from a list of integers [n1, n2 ..] representing publications citations, return the max list-position which is >= integer eg >>> the_H_function([10, 8, 5, 4, 3]) => 4 >>> the_H_function([25, 8, 5, 3, 3]) => 3 >>> the_H_function([1000, 20]) => 2 """ if sorted_citations_list and sorted_citations_list[0] >= n: return the_H_function(sorted_citations_list[1:], n + 1) else: return n - 1
24ad3d85963ef0a9d4531ba552371d7e829f1c2a
709,949
import re def create_index_search_tag_for_variable(variable_expression): """ Creates tag from variable expressions such as 'A%b(i)%c' that can be used to search the index via the scoper module. The example 'A%b(i)%c' is translated to a tag 'a%b%c' (lower case). All array indexing expressions are stripped away. A single identifer 'a' would be translated to the tag 'a'. :param str variable_expression: a simple identifier such as 'a' or 'A_d' or a more complicated derived-type member variable expression such as 'a%b%c' or 'A%b(i)%c'. :see: indexer.scoper.search_index_for_variable """ result = variable_expression.lstrip("-+") # remove trailing minus sign if not "(" in result: return result.lower() else: parts = re.split("([()%,])",result.lower()) open_brackets = 0 result = [] curr = "" for part in parts: if part == "(": open_brackets += 1 elif part == ")": open_brackets -= 1 elif part == "%" and open_brackets == 0: result.append(curr) curr = "" elif open_brackets == 0: curr += part result.append(curr) return "%".join(result)
7d2e3b5a17e29a29d8fd397316fb2abbb5aa58b1
564,053
import six def parse_int(num): """ Parse integer from a string. """ is_empty = isinstance(num, six.string_types) and len(num) == 0 if is_empty: return None try: return num and int(num) except ValueError: pass
d2c61b20d0612602457a375c84a1a26d4cd59ed1
472,853
import math def wrap_always(text, width): """A simple word-wrap function that wraps text on exactly width characters. It doesn't split the text in words.""" return '\n'.join([text[width * i:width * (i + 1)] \ for i in range(int(math.ceil(1. * len(text) / width)))])
f6e5b85007fffc78576c8d5bbe89077400ca96b0
654,814
import errno def _maybe_read_file(filename): """Read the given file, if it exists. Args: filename: A path to a file. Returns: A string containing the file contents, or `None` if the file does not exist. """ try: with open(filename) as infile: print(infile.read()) return infile.read() except IOError as e: if e.errno == errno.ENOENT: return None
c8cb46edaa0af2a0cffda530b3a6d98e8f9ee166
256,804
def rreplace(s, old, new, occurrence, only_if_not_followed_by=None): """replaces occurences of character, counted from last to first, with new character. Arguments: s - string old - character/string to be replaced new - character/string to replace old with occurence - nth occurence up to which instances should be replaced, counting from end to beginning. e.g. if set to 2, the two last instances of "old" will be replaced only_if_not_followed_by - if this is set to a string, [old] is only replaced by [new] if [old] is not followed by [only_if_not_followed_by] in [s]. Useful for gene names like abc-1.d, in that case we do not want to replace the dash. Returns: string with replaced character """ if old not in s: return s elif only_if_not_followed_by != None: # test if latest instance of old is followed by [only_if_not_followed_by] last_inst_old = s.rfind(old) last_inst_oinfb = s.rfind(only_if_not_followed_by) if last_inst_oinfb > last_inst_old: return s li = s.rsplit(old, occurrence) return new.join(li)
8db045d1399697d5bc3bfa7fb3d345019c04cfd8
166,087
def dict_depth(dic, level=0): """ Check the depth of a dictionary. **Parameters** dic: dict Instance of dictionary object or its subclass. level: int | 0 Starting level of the depth counting. """ if not isinstance(dic, dict) or not dic: return level return max(dict_depth(dic[key], level+1) for key in dic)
b036dbdd796c866e4ea5293d2dee6139e15d881c
264,972