content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def get_all_recommendations(csv_file): """ This function reads all recommendations for users using the result of the recommendation system stored in a csv file :param csv_file: the csv file where the recommendations are stored :return: the dataframe of recommendations predicted for users """ df_recommendations = csv_file df_recommendations.columns = ['user_id', 'recommendations'] return df_recommendations
fe0578bb77c60deaf833a22fd9a1b9e946183f91
698,327
from bs4 import BeautifulSoup def filter_bank_account_info(html: str) -> dict: """Filter the bank account info in the data of the HTML structure. Keyword arguments: `html: str` - Content in html structure. """ soup = BeautifulSoup(html, 'html.parser') # Get all the labels to use as a key in the dictionary return. labels = [div.text for div in soup.find_all('div', 'output-subtitle')] # Get all the data to use as a value in the dictionary return. data_of_bank_account = [div.text for div in soup.find_all('div', 'output-txt')] # Join labels with bank account data # and convert to a dictionary in the key-value format respectively. data_dict = dict( zip(labels, data_of_bank_account) ) return data_dict
e4558d52895dbb01f57a26d3722597577367ba26
698,328
def is_prime(nb: int) -> bool: """Check if a number is a prime number or not :param nb: the number to check :return: True if prime, False otherwise """ # even numbers are not prime if nb % 2 == 0 and nb > 2: return False # checking all numbers up to the square root of the number # full explanation: # https://stackoverflow.com/questions/18833759/python-prime-number-checker/18833870#18833870 return all(nb % i for i in range(3, int(nb ** .5) + 1, 2))
4368fd20eadd4d773d5f5af06f8717ef633d48b8
698,329
async def present(hub, ctx, name: str, image: str, **kwargs): """ Ensure a container is present .. code-block:: yaml new container: lxd.containers.present: - name: webserver01 - image: ubuntu1804 """ ret = { "result": False, "name": name, "comment": "", "changes": {}, } container = await hub.exec.lxd.containers.get(ctx, name) if name in container: ret["result"] = True ret["comment"] = 'Container "{}" already exists'.format(name) return ret if ctx["test"]: ret["result"] = None ret["comment"] = 'Container "{}" does not exist and will be created'.format( name ) return ret changes = await hub.exec.lxd.containers.create(ctx, name, image, wait=True) container = await hub.exec.lxd.containers.get(ctx, name) ret["result"] = True ret["comment"] = 'Container "{}" was created'.format(name) ret["changes"] = {"new": changes["status"]} return ret
911b27a3318bc273f790041f2c003f6e8f56645d
698,330
from typing import Sequence from typing import Any from functools import reduce from operator import getitem def get_in_dict(d: dict, keys: Sequence[str]) -> Any: """ Retrieve nested key from dictionary >>> d = {'a': {'b': {'c': 3}}} >>> get_in_dict(d, ('a', 'b', 'c')) 3 """ return reduce(getitem, keys, d)
d851c1d9360e90cbecbff401b98b76afb9b7e52f
698,331
import logging def level_from_verbosity(verbosity=3, maxlevel=logging.CRITICAL): """Return the logging level corresponding to the given verbosity.""" return max(1, # 0 disables it, so we use the next lowest. min(maxlevel, maxlevel - verbosity * 10))
45064e04e27fa170257f37faa56de02ea544f811
698,332
def add_tag(row, tag_key, capitalize=False): """ Looks up the correct tag based on the row, and appends it to the list of tags :param row: :param tag_key: the tag key (string of tag) to add :param capitalize: True to initial cap the tag key :return: the updated row """ if not tag_key: return if 'tag' not in row: row['tag'] = [] if capitalize: tag_key = tag_key.capitalize() if tag_key not in row['tag']: row['tag'].append(tag_key) return row
f8a84d4eeb82f516a301553528c3f66741879a7a
698,333
def nested_dict_traverse(path, d): """Uses path to traverse a nested dictionary and returns the value at the end of the path. Assumes path is valid, will return KeyError if it is not. Warning: if key is in multiple nest levels, this will only return one of those values.""" val = d for p in path: val = val[p] return val
1f7e4744585ae134ab1f2eface9284756526ed65
698,335
def is_file_download_finish(file_name): """ 判断文件是否下载完 判断文件后缀为xltd即未下载完 :param file_name: :return: """ return not file_name.endswith('.xltd')
b782d358359c03f50efb6d791bd4403a4190aac0
698,336
import itertools def list_flatten(_l): """Flatten a complex nested list of nested lists into a flat list """ return itertools.chain(*[list_flatten(j) if isinstance(j, list) else [j] for j in _l])
05d1e4018accfe850c07504f123d85949a2ced60
698,340
def handle_2_columns(datalist, return_list = False): """This function has the intent of changing: ('A8', '2') => ('A8', '', '2') ('A8', '', '2') => ('A8', '', '2') [('E2', '5')] => [('E2', '', '5')] [('G1', '', '5')] => [('G1', '', '5')] with the purpose of handling 2 column csv part file inputs, as at times when 2 column csv files are input it creates tuples of length 2 instead of 3 """ if isinstance(datalist,list): # if data list is a list, extract tuple datalist = datalist[0] return_list = True if len(datalist) == 2: # if tuple is of length 2, insert empty value at position 1 datalist = (datalist[0], "", datalist[1]) if return_list: # if list passed to function, return output as list datalist = [datalist] return datalist
57a9c1dbad9484a3513cebab68069983d3ae9f35
698,343
def format_button(recipient_id, button_text, buttons): """ Ref: https://developers.facebook.com/docs/messenger-platform/send-api-reference/button-template """ return { "recipient": {"id": recipient_id}, "message": { "attachment": { "type": "template", "payload": { "template_type": "button", "text": button_text, "buttons": buttons, } } } }
a05f6d08b87d0897a65b291c539b3cbd883c0799
698,344
def get_position_key(atom): """ Get atom position as tuple of integers to be used as lookup key. Rounds the coordinates to 4 decimal places before multiplying by 50 to get unique integer-space coordinates, and avoid floating point errors. :param atom: Atom to get key for :type atom: :class:`nanome.structure.Atom` :return: Position key tuple :rtype: (int, int, int) """ return tuple(map(lambda x: int(50 * round(x, 4)), atom.position))
b367fd851a0afa903c2d73548849cc8864233f56
698,348
def _str_eval_break(eval, act, ctxt) : """Passes through [break] so that the writer can handle the formatting code.""" return ["[break]"]
2da4059adb4305a3d7e2183c29d89c9539f3c63b
698,349
import math def tuning_score_size(performance_space, peak): """ Computes TS_s, the tuning score based on the size of the performance space compared to the achievable performance. """ return math.sqrt(performance_space.top() / peak)
9e5386932fa164f0d33e65dd41d57d7a22ebe4d6
698,350
def available(func): """A decorator to indicate that a method on the adapter will be exposed to the database wrapper, and will be available at parse and run time. """ func._is_available_ = True return func
a0c886bccb9bbbdacfe23c5659929b8be68c004e
698,352
def spaces_and_caps_to_snake(spaced_str: str) -> str: """Convert caps and spaces to snake.""" underscored = spaced_str.strip().replace(' ', '_') return underscored.lower()
31796e696c2d4efa7821a0cdff09e04b3e7e8232
698,353
from typing import OrderedDict from typing import Type import collections def kwtypes(**kwargs) -> OrderedDict[str, Type]: """ This is a small helper function to convert the keyword arguments to an OrderedDict of types. .. code-block:: python kwtypes(a=int, b=str) """ d = collections.OrderedDict() for k, v in kwargs.items(): d[k] = v return d
8024e6940f84f2eab8d4c44924889624d75ca3bd
698,354
def sort_libraries(libraries): """Sort libraries according to their necessary include order""" for i in range(len(libraries)): for j in range(i, len(libraries)): if libraries[i].depends_on(libraries[j]) or libraries[i].has_addon_for(libraries[j]): tmp = libraries[i] libraries[i] = libraries[j] libraries[j] = tmp return libraries
81187aaeb1879d8de4b23d0adae6547739f6a327
698,356
def hamming(g1,g2,cutoff=1): """ Compare two genotypes and determine if they are within cutoff sequence differences of one another. Parameters ---------- g1, g2 : strs two genotypes to compare (must be same length) cutoff : int max allowable sequence differences between them Returns ------- neighbor : bool whether or not the genotypes are neighbors """ try: if len(g1) != len(g2): raise TypeError except TypeError: err = "g1 and g2 must have the same length\n" raise ValueError(err) return sum([g1[i] != g2[i] for i in range(len(g1))]) <= cutoff
24a180c68545fc1cbd0887bf2bee38cbfe6034e0
698,359
def __dtw_backtracking(steps, step_sizes_sigma, subseq, start=None): # pragma: no cover """Backtrack optimal warping path. Uses the saved step sizes from the cost accumulation step to backtrack the index pairs for an optimal warping path. Parameters ---------- steps : np.ndarray [shape=(N, M)] Step matrix, containing the indices of the used steps from the cost accumulation step. step_sizes_sigma : np.ndarray [shape=[n, 2]] Specifies allowed step sizes as used by the dtw. subseq : bool Enable subsequence DTW, e.g., for retrieval tasks. start : int Start column index for backtraing (only allowed for ``subseq=True``) Returns ------- wp : list [shape=(N,)] Warping path with index pairs. Each list entry contains an index pair (n, m) as a tuple See Also -------- dtw """ if start is None: cur_idx = (steps.shape[0] - 1, steps.shape[1] - 1) else: cur_idx = (steps.shape[0] - 1, start) wp = [] # Set starting point D(N, M) and append it to the path wp.append((cur_idx[0], cur_idx[1])) # Loop backwards. # Stop criteria: # Setting it to (0, 0) does not work for the subsequence dtw, # so we only ask to reach the first row of the matrix. while (subseq and cur_idx[0] > 0) or (not subseq and cur_idx != (0, 0)): cur_step_idx = steps[(cur_idx[0], cur_idx[1])] # save tuple with minimal acc. cost in path cur_idx = ( cur_idx[0] - step_sizes_sigma[cur_step_idx][0], cur_idx[1] - step_sizes_sigma[cur_step_idx][1], ) # If we run off the side of the cost matrix, break here if min(cur_idx) < 0: break # append to warping path wp.append((cur_idx[0], cur_idx[1])) return wp
e22a25f7d9e02aeb9413a7f9b39401f7628848e8
698,361
import torch def extract_bboxes(mask): """Compute bounding boxes from masks. mask: [height, width]. Mask pixels are either 1 or 0. Returns: bbox array (y1, x1, y2, x2). """ # Bounding box. horizontal_indicies = torch.where(torch.any(mask, dim=0))[0] vertical_indicies = torch.where(torch.any(mask, dim=1))[0] if horizontal_indicies.shape[0]: x1, x2 = horizontal_indicies[[0, -1]] y1, y2 = vertical_indicies[[0, -1]] # x2 and y2 should not be part of the box. Increment by 1. x2 += 1 y2 += 1 else: # No mask for this instance. Might happen due to # resizing or cropping. Set bbox to zeros x1, x2, y1, y2 = 0, 0, 0, 0 boxes = torch.Tensor([x1, y1, x2, y2]).to(mask.device) return boxes
f634b6cfca16cf06da07f194c701920187f4d3e7
698,364
def strip_domain_address(ip_address): """Return the address or address/netmask from a route domain address. When an address is retrieved from the BIG-IP that has a route domain it contains a %<number> in it. We need to strip that out so we are just dealing with an IP address or IP address/mask. Examples: 192.168.1.1%20 ==> 192.168.1.1 192.168.1.1%20/24 ==> 192.168.1.1/24 """ mask_index = ip_address.find('/') if mask_index > 0: return ip_address[:mask_index].split('%')[0] + ip_address[mask_index:] else: return ip_address.split('%')[0]
adf566580249d00b660e108cabcf99892a44d32b
698,365
from typing import List def athlete_sort(k: int, arr: List[List[int]]) -> List[List[int]]: """ >>> athlete_sort(1, [[10, 2, 5], [7, 1, 0], [9, 9, 9], ... [1, 23, 12], [6, 5, 9]]) [[7, 1, 0], [10, 2, 5], [6, 5, 9], [9, 9, 9], [1, 23, 12]] """ arr.sort(key=lambda x: x[k]) return arr
1655882b7760a705afcbbeba55f5051eaf7d448f
698,368
def list_to_group_count(input_list): """ List to item occurrences count dictionary """ group_count = {} for input_item in input_list: if input_item in group_count: group_count[input_item] = group_count[input_item] + 1 else: group_count[input_item] = 1 return group_count
bc6714d2d0b8872e29089eb0d142517c4ef63154
698,373
from typing import Any def affix(orig: Any, ch: str) -> str: """Ensure a given character is prepended to some original value.""" if isinstance(orig, (list, tuple,)): orig = '.'.join(map(str, orig)) return '%s%s' % (ch, str(orig).lstrip(ch))
f5f01b7fa0e82944646dc755cfa0770cec8c72c9
698,376
import yaml def get_project_id(dataset: str) -> str: """Returns the GCP project ID associated with the given dataset.""" with open(f'../stack/Pulumi.{dataset}.yaml', encoding='utf-8') as f: return yaml.safe_load(f)['config']['gcp:project']
d951e8d2a6c96df9aa2dc15499c36f93123f8038
698,377
def score_state(num_answer, ans_one): """Takes in the player's answer, and ans_one (explained in question); checks if the player's choice is correct """ #assert num_answer in [1, 2] if num_answer == 1: if ans_one == True: correct = True else: correct = False else: if ans_one == True: correct = False else: correct = True if correct == True: print('Correct! choice ' + str(num_answer) + ' is real!') else: print('Incorrect!: choice ' + str(num_answer) + ' is fake!') return correct
123a0c5f40930fe5a6dc65220c39097a55120c19
698,379
def arg_name2cli_name(arg_name: str) -> str: """ Convert a snake_case argument into a --kabob-case argument. """ return "--" + arg_name.lower().replace("_", "-")
541601ae07b09acdd2d33487517159cd3cbd6125
698,382
def get_users(client): """Return the db containing users metadata. Parameters ---------- client --> pymongo.mongo_client.MongoClient class, MongoDB client Returns ------- metadatafs['fs'] --> pymongo.collection.Collection, reference to collection users """ #get the MongoDb collection called "users" metadatafs = client['metadatafs'] return metadatafs['users']
bd2f0b60781e27a23f015f7a7573821a0e2b8ef0
698,387
def read_raw_values(datasize, datastore, test): """read the raw data for a given test""" in_file_name = str(datasize) + '/' + datastore + '_' + test + '.csv' return [int(line.strip()) for line in open(in_file_name)]
1d724b873ee0ccf50d2027df79a2d32472e7942a
698,388
def TrimMu(Stot, oldmu, thresh, norm=True): """ Remove mu measurements below the threshold and adjust mu measurements above the threshold to unity if we seek P(mu > thresh). """ trim = oldmu > thresh if norm: oldmu[:] = 0 oldmu[trim] = 1 else: oldmu = oldmu[trim] Stot = Stot[trim] return Stot, oldmu
2a986599a6116b104b839d8b664f0caff57b1aee
698,389
import collections def mkparts(sequence, indices=None): """ Make some parts from sequence by indices :param sequence: indexable object :param indices: index list :return: [seq_part1, seq_part2, ...] """ indices = indices or [1] result_list = collections.deque() start = 0 seq_len = len(sequence) for end in indices: if end < 0: end = seq_len + end if end < start: raise ValueError("end index is less than start index") result_list.append(sequence[start:end]) start = end result_list.append(sequence[start:]) return tuple(result_list)
710841ca3861a33382b6243579eec07f866eb965
698,391
def log_minor_tick_formatter(y: int, pos: float) -> str: """ Provide reasonable minor tick formatting for a log y axis. Provides ticks on the 2, 3, and 5 for every decade. Args: y: Tick value. pos: Tick position. Returns: Formatted label. """ ret_val = "" # The positions of major ticks appear to be skipped, so the numbering starts at 2 # Thus, to label the 2, 3, and 5 ticks, we need to return the label for the 0th, 1st, and # 3rd labels. values_to_plot = [0, 1, 3] # The values 2 - 9 are available for the minor ticks, so we take the position mod 8 to # ensure that we are repeating the same labels over multiple decades. if (pos % 8) in values_to_plot: # "g" auto formats to a reasonable presentation for most numbers. ret_val = f"{y:g}" return ret_val
a378bd94ceab8698a45403544a728c6c29b402c9
698,392
from typing import Union from pathlib import Path from typing import Any from typing import TextIO def fopen(filepath: Union[str, Path], *args: Any, **kwargs: Any) -> TextIO: """Open file. Args: filepath (Union[str, Path]): filepath Returns: TextIOWrapper: buffer text stream. """ if isinstance(filepath, str): return open(filepath, *args, **kwargs) elif isinstance(filepath, Path): return filepath.open(*args, **kwargs)
fcf4ccf53c99a390ceaa9b27f86a7e3f4cff3af1
698,394
import signal def signal_number_to_name(signum): """ Given an OS signal number, returns a signal name. If the signal number is unknown, returns ``'UNKNOWN'``. """ # Since these numbers and names are platform specific, we use the # builtin signal module and build a reverse mapping. signal_to_name_map = dict((k, v) for v, k in signal.__dict__.items() if v.startswith('SIG')) return signal_to_name_map.get(signum, 'UNKNOWN')
cc17db79f6e47b25e9ec5b9c33fb8d7bf7c0ad26
698,397
def labeledFcn(fcn, paramNames): """Wraps a function with its parameter names (in-place). :type fcn: callable Python object :param fcn: function to wrap :type paramNames: list of strings :param paramNames: parameters to attach to the function :rtype: callable Python object :return: the original function, modified in-place by adding ``paramNames`` as an attribute """ fcn.paramNames = paramNames return fcn
e8885cf0cf4db4e84069ec4f0164748b0ab52ae3
698,402
import torch def value_td_residuals( rewards: torch.Tensor, values: torch.Tensor, next_values: torch.Tensor, discount: float, ) -> torch.Tensor: """Compute TD residual of state value function. All tensors must be one dimensional. This is valid only for one trajectory. Parameters ---------- rewards: The one step reward. values: The estimated values at the current step. Note that the last test is terminal, the associated value should be zero. next_values: The estimated values at the next step. discount: The discount rate. """ return rewards + (discount * next_values) - values
723ed0f0ce651cc7da5ad9c7950972d104198888
698,405
async def agather(aiter): """Gather an async iterator into a list""" lst = [] async for elem in aiter: lst.append(elem) return lst
0a7f278d38237a722724572b6705deab429c8e70
698,407
import socket def tcp_socket_open(host, port): """ Returns True if there is an open TCP socket at the given host/port """ sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.settimeout(1) try: return sock.connect_ex((host, port)) == 0 except socket.timeout: return False
11519e5d9f2d1de39d8091af011f0458e556021c
698,413
from typing import Optional from typing import List import math import random def sample_from_range(range_max: int, sample_ratio: float, max_samples: int, preselected: Optional[List[int]]) -> List[int]: """ Given a range of numbers in 0..range_max, return random samples. Count of samples is set by sample_ratio, up to max_samples. If preselected is passed, include these indexes first. """ available_indexes = list(range(range_max)) sample_count = min(math.floor(range_max * sample_ratio), max_samples) if preselected: chosen = list(preselected) for i in preselected: available_indexes.remove(i) sample_count = max(sample_count - len(preselected), 0) else: chosen = [] if sample_count > 0: chosen += random.choices(available_indexes, k=sample_count) return chosen
8be7b5ded3b6f3b54da57027a5d7629a9bf5dc9f
698,415
def occ(s1,s2): """occ (s1, s2) - returns the number of times that s2 occurs in s1""" count = 0 start = 0 while True: search = s1.find(s2,start) if search == -1: break else: count +=1 start = search+1 return count
4f107e5552d794e9e82a8a6b19ec63992034e9f7
698,416
import functools import operator def prod(x): """Equivalent of sum but with multiplication.""" # http://stackoverflow.com/a/595396/1088938 return functools.reduce(operator.mul, x, 1)
31f4defa3401d6dcf05f8ec70c32650f000a1852
698,417
def indent(text, prefix=" "): """ Add a prefix to every line in a string. """ return "\n".join(prefix+line for line in text.splitlines())
e83cc0b14c5b8c304f6e41bf145b06b1de451e8c
698,418
def get_resblock(model, layer_name): """ model is a class resnet e.g. layer_name is "layer1.0.relu2" """ obj_name, b_idx, act_name = layer_name.split(".") b_idx = int(b_idx) block = getattr(model, obj_name)[b_idx] return block
a4ae6c65df336b3dd36b53e9dd348a76b4a47b89
698,419
def FindClientNode(mothership): """Search the mothership for the client node.""" nodes = mothership.Nodes() assert len(nodes) == 2 if nodes[0].IsAppNode(): return nodes[0] else: assert nodes[1].IsAppNode() return nodes[1]
06ac3bcde5571ca425d47885ad5839f2aa32ca0d
698,421
import textwrap def to_flatimage(pathfile, to="(-3,0,0)", width=8, height=8, name="temp"): """ Adds a flat image to the canvas. """ text = rf""" \node[canvas is xy plane at z=0] ({name}) at {to}{{ \includegraphics[width={width}cm,height={height}cm]{{{pathfile}}} }}; """ return textwrap.dedent(text=text)
61906516d85ba3311506067ad4ec81b32786f1b9
698,422
def _get_primary_status(row): """Get package primary status.""" try: return row.find('div', {'class': 'pack_h3'}).string except AttributeError: return None
1df5b66e9e16e17b8c5f3fc019a587a4320cf6d0
698,424
def calc_n_g(df_schedule, week): """Calculate list of games i.e. Ng Each row has home_id, away_id, home_total_points, away_total_points :param df_schedule: data frame with each matchup :param week: current matchup period id :return: list of games with team ids and scores for home/away """ df_scores = ( df_schedule .query(f'matchupPeriodId <= {week} & winner!="UNDECIDED"') [['home_id', 'away_id', 'home_total_points', 'away_total_points']] ) return df_scores
1029840d28617d5de60fa499e8e6a9ae40b4ddea
698,425
def is_string(s): """ Portable function to answer whether a variable is a string. Parameters ---------- s : object An object that is potentially a string Returns ------- isstring : bool A boolean decision on whether ``s`` is a string or not """ return isinstance(s, str)
ed59a1b3a80f6695c971c49ff3b7936aa048523f
698,426
from typing import Any from typing import Optional def _strat_has_unitary_from_has_unitary(val: Any) -> Optional[bool]: """Attempts to infer a value's unitary-ness via its _has_unitary_ method.""" if hasattr(val, '_has_unitary_'): result = val._has_unitary_() if result is NotImplemented: return None return result return None
96965cfec5f5c3c29ea641c95f20a2d4b1f3b859
698,431
def BFS(map_dict, start, end, verbose): """ BFS algorithm to find the shortest path between the start and end points on the map, following the map given by map_dict If an invalid end location is given then it will return the longest possible path and its length. Returns the length of the shortest route, and the overall path. """ initPath = [start] pathQueue = [initPath] longest = 0 longest_path = [] moves = {1:(0,1), 2:(0,-1), 3:(-1, 0), 4:(1,0)} while len(pathQueue) != 0: # Get and remove oldest element of path queue: tmpPath = pathQueue.pop(0) if verbose: print('Current BFS path: ', tmpPath) lastNode = tmpPath[-1] if len(tmpPath) > longest: longest = len(tmpPath) longest_path = tmpPath # If the last node in the path is the end, shortest route found if lastNode == end: return tmpPath, len(tmpPath) # Otherwise add all new possible paths to path queue: for i in range(1,5,1): dx, dy = moves[i] pos_x, pos_y = lastNode testpos = (pos_x + dx, pos_y + dy) # Check if legit path and not backtracking if map_dict[testpos] > 0 and testpos not in tmpPath: newPath = tmpPath + [testpos] pathQueue.append(newPath) # If no path found return longest path: return longest_path, longest
f6770fe8cd5f6c4ebffce2a78992c76cfbb5bd31
698,434
def update_letter_view(puzzle: str, view: str, position: int, guess: str) -> str: """Return the updated view based on whether the guess matches position in puzzle >>> update_letter_view('apple', 'a^^le', 2, 'p') p >>> update_letter_view('banana', 'ba^a^a', 0, 'b') b >>> update_letter_view('bitter', '^itter', 0, 'c') ^ """ if guess == puzzle[position]: return puzzle[position] return view[position]
b7c534acdbc57c04e1f7ee6a83fc94ff2734948a
698,438
def _remove_duplicates(items): """Return `items`, filtering any duplicate items. Disussion: https://stackoverflow.com/a/7961390/4472195 NOTE: this requires Python 3.7+ in order to preserve order Parameters ---------- items : list [description] Returns ------- list Updated `items` """ return list(dict.fromkeys(items))
b44a16ed815e8cc09598fe2dc8e9871d45d0ae7e
698,441
import re def seqs_dic_count_lc_nts(seqs_dic): """ Count number of lowercase nucleotides in sequences stored in sequence dictionary. >>> seqs_dic = {'seq1': "gtACGTac", 'seq2': 'cgtACacg'} >>> seqs_dic_count_lc_nts(seqs_dic) 10 >>> seqs_dic = {'seq1': "ACGT", 'seq2': 'ACGTAC'} >>> seqs_dic_count_lc_nts(seqs_dic) 0 """ assert seqs_dic, "Given sequence dictionary empty" c_uc = 0 for seq_id in seqs_dic: c_uc += len(re.findall(r'[a-z]', seqs_dic[seq_id])) return c_uc
4542885f22e255fa0f3d14a9d4ef523fdf19f2e8
698,442
def gaussian_kernel(D, sigma): """ Applies Gaussian kernel element-wise. Computes exp(-d / (2 * (sigma ^ 2))) for each element d in D. Parameters ---------- D: torch tensor sigma: scalar Gaussian kernel width. Returns ------- torch tensor Result of applying Gaussian kernel to D element-wise. """ return (-D / (2 * (sigma ** 2))).exp()
22885ccb785893522e57861b82612989945cd5cf
698,444
def trigger_event(connection, id, fields=None, error_msg=None): """Trigger an event. Args: connection(object): MicroStrategy connection object returned by `connection.Connection()`. id(str): ID of the event error_msg (string, optional): Custom Error Message for Error Handling Returns: HTTP response object returned by the MicroStrategy REST server. """ url = f'{connection.base_url}/api/events/{id}/trigger' return connection.post( url=url, params={'fields': fields} )
418994565cd20cac681575286553d4fa92cf89c9
698,445
def eratosthenes(n): """ This function is titled eratosthenes(n) because it uses the Eratosthenes Sieve to produce a list of prime numbers. It takes in one positive integer arguement, the returns a list of all the primes less than the given number. Args: n (int): User input Returns: primes (list): List of prime numbers less than the user input """ primes = [] #checks for positive number if n<=0: print("Please enter a positive number") return #creates list of numbers up to n count = 2 while count<=n-1: primes.append(count) count +=1 p = 2 #starts with 2, then removes all multiples of 2. Moves to 3, removes #all multiples of 3, and so on until we have a list of prime numbers #less than n. while p<=n: for i in range(2, n+1): if i*p <= n: #checks to see if the number was already removed from the list if i*p not in primes: continue else: primes.remove(i*p) p +=1 return primes
7c0e0e89c1571dfc7a87883423a217ef36a984af
698,449
def y_aver_bot(yw_mol, ypf_mol): """ Calculates the average mol concentration at bottom of column. Parameters ---------- yw_mol : float The mol concentration of waste, [kmol/kmol] ypf_mol : float The mol concentration of point of feed, [kmol/kmol] Returns ------- y_aver_top : float The average mol concentration at top of column, [kmol/kmol] References ---------- Дытнерский, стр.230, формула 6.8 """ return (yw_mol + ypf_mol) / 2
21a438551cc7f6c3774999bafa30495dffd99201
698,450
def _convert_to_numpy_obj(numpy_dtype, obj): """Explicitly convert obj based on numpy type except for string type.""" return numpy_dtype(obj) if numpy_dtype is not object else str(obj)
54a7bd1576ec95456d47e2e3957370c0970cb376
698,451
from datetime import datetime def start_of_month(dt, d_years=0, d_months=0): """ Given a date, return a date first day of the month. @param dt: The date to base the return value upon. @param d_years: Specify a delta in years to apply to date. @param d_months: Specify a delta in months to apply to date. @see http://code.activestate.com/recipes/476197-first-last-day-of-the-month/ """ y, m = dt.year + d_years, dt.month + d_months a, m = divmod(m-1, 12) return datetime(y+a, m+1, 1)
90976e7df97b8581622df77528540487181cbb8f
698,452
def frames(string): """Takes a comma separate list of frames/frame ranges, and returns a set containing those frames Example: "2,3,4-7,10" => set([2,3,4,5,6,7,10]) """ def decode_frames(string): print('s', string) if '-' in string: a = string.split('-') start, end = int(a[0]), int(a[1]) for i in range(start, end + 1): yield i else: yield int(string) framesList = string.split(',') frames = set() for strFrames in framesList: for frameNumber in decode_frames(strFrames): frames.add(frameNumber) return frames
a00a80bba4ab369a9682db6b62dad88911ecc711
698,454
import importlib def class_from_module_path(module_path): """Given the module name and path of a class, tries to retrieve the class. The loaded class can be used to instantiate new objects. """ # load the module, will raise ImportError if module cannot be loaded if "." in module_path: module_name, _, class_name = module_path.rpartition('.') m = importlib.import_module(module_name) # get the class, will raise AttributeError if class cannot be found return getattr(m, class_name) else: return globals()[module_path]
e1b4935efd165c38c6394274c030c52eca5e241d
698,456
def get_ocr_json_url_for_an_image(first_three_digits, second_three_digits, third_three_digits, fourth_three_digits, image_name): """ Get the URL of a JSON file given a barcode in 4 chunks of 3 digits and an image name (1, 2, 3, front_fr...). """ url = "https://world.openfoodfacts.org/images/products/" url += "%s/%s/%s/%s/%s.json" % ( first_three_digits, second_three_digits, third_three_digits, fourth_three_digits, image_name ) return url
44c4d70971f24beee622ff2e11bef0474001aaa3
698,459
def tupleRemoveByIndex(initTuple, indexList): """ Remove the elements of given indices from a tuple. Parameters ---------- initTuple : tuple of any The given tuple from which we will remove elements. indexList : list of ints The indices of elements that we want to remove. Returns ------- tuple of any The tuple after removing elements from initTuple """ initList = list(initTuple) indexSet = set(indexList) resList = [] for i in range(len(initList)): if not (i in indexSet): resList.append(initList[i]) return tuple(resList)
17009fc3616afa586467f43b1e7910a17c89ed0d
698,461
def format_one_query(q, read_seq, read_coords, barcode_dict=None): """Formats output. Parameters ---------- q : dict A dictionary of fuzzy searching result. Key is levenshtein distance. Value is list of matched barcodes. read_seq : str A DNA string (full length read). read_coords : tuple or list The positions of read used for comparison. barcode_dict : dict, optional Names for the matched barcodes. Keys are barcode sequences. Values are alternative names. Returns ------- str Sequencing read (full length). str Matched barcode or barcode name. str Levenshtein distance. """ x, y = read_coords read_seq = (read_seq[:x].lower() + read_seq[x:y] + read_seq[y:].lower()) if barcode_dict: barcode = barcode_dict[q[0]] else: barcode = q[0] return read_seq, barcode, str(q[1])
2523ca6e15547a89e466fc4b4c9dad322fe91dbf
698,463
from typing import Tuple def create_categorical_encoder_and_decoder(categorical_variables: list[str]) -> Tuple[dict, dict]: """ Given a list of categorical variables, returns an encoder and decoder. Encoder Key = category. Value = integer encoding. Decoder Key = integer encoding. Value = category. """ decoder = {} encoder = {} for idx, variable in enumerate(categorical_variables): decoder[idx] = variable encoder[variable] = idx return decoder, encoder
70de5c8a3e1667da2776a3750c1fae1edf9fd8ae
698,466
def _convert_to_int_list(check_codes): """Takes a comma-separated string or list of strings and converts to list of ints. Args: check_codes: comma-separated string or list of strings Returns: list: the check codes as a list of integers Raises: ValueError: if conversion fails RuntimeError: if cannot determine how to convert input """ if isinstance(check_codes, list): if all(isinstance(x, int) for x in check_codes): return check_codes # good input else: return [int(x) for x in check_codes] # list of str elif isinstance(check_codes, str): return [int(x) for x in check_codes.split(",")] # str, comma-separated expected raise RuntimeError("Could not convert values: {} of type {}".format(check_codes, type(check_codes)))
965a68466d0aab358043cedb4838ac9d99ce3249
698,469
def get_note_freq(p): """ Return the frequency corresponding to a particular note number Parameters ---------- p: int Note number, in halfsteps. 0 is a concert a """ return 440*2**(p/12)
cec12355f481494fa53fb0ed535ecd82fd038016
698,470
def stringify_parameters(items): """ Convert all items in list to string. """ return [str(item) for item in items]
41a47f611d1514043eeac27de6c8be6c01607649
698,471
def get_current_spec_list(ctx): """ Get the current spec list, either from -p/--project-specs or --specs-to-include-in-project-generation or specs_to_include_in_project_generation in user_settings.options :param ctx: Current context :return: The current spec list """ try: return ctx.current_spec_list except AttributeError: pass # Get either the current spec being built (build) or all the specs for the solution generation (configure/msvs) current_spec = getattr(ctx.options, 'project_spec') if not current_spec: # Specs are from 'specs_to_include_in_project_generation' spec_string_list = getattr(ctx.options, 'specs_to_include_in_project_generation', '').strip() if len(spec_string_list) == 0: ctx.fatal( "[ERROR] Missing/Invalid specs ('specs_to_include_in_project_generation') in user_settings.options") spec_list = [spec.strip() for spec in spec_string_list.split(',')] if len(spec_list) == 0: ctx.fatal("[ERROR] Empty spec list ('specs_to_include_in_project_generation') in user_settings.options") else: spec_list = [current_spec] # Vet the list and make sure all of the specs are valid specs for spec in spec_list: if not ctx.is_valid_spec_name(spec): ctx.fatal( "[ERROR] Invalid spec '{}'. Make sure it exists in the specs folder and is a valid spec file.".format( spec)) ctx.current_spec_list = spec_list return ctx.current_spec_list
e0e2788b86bf005b6986ab84f507d784ef837cca
698,472
def title_from_name(name): """ Create a title from an attribute name. """ def _(): """ Generator to convert parts of title """ try: int(name) yield 'Item #%s'% name return except ValueError: pass it = iter(name) last = None while 1: ch = it.next() if ch == '_': if last != '_': yield ' ' elif last in (None,'_'): yield ch.upper() elif ch.isupper() and not last.isupper(): yield ' ' yield ch.upper() else: yield ch last = ch return ''.join(_())
44182a7aefc552701517292563717884835230aa
698,474
def fill_empties(abstract): """Fill empty cells in the abstraction The way the row patterns are constructed assumes that empty cells are marked by the letter `C` as well. This function fill those in. The function also removes duplicate occurrances of ``CC`` and replaces these with ``C``. Parameters ---------- abstract : str The abstract representation of the file. Returns ------- abstraction : str The abstract representation with empties filled. """ while "DD" in abstract: abstract = abstract.replace("DD", "DCD") while "DR" in abstract: abstract = abstract.replace("DR", "DCR") while "RD" in abstract: abstract = abstract.replace("RD", "RCD") while "CC" in abstract: abstract = abstract.replace("CC", "C") if abstract.startswith("D"): abstract = "C" + abstract if abstract.endswith("D"): abstract += "C" return abstract
cc27354fd50ac8588c8374e06025a2ceeff691c6
698,475
def pretty_print(state): """ Returns a 3x3 string matrix representing the given state. """ assert len(state) == 9 str_state = [str(i) for i in state] lines = [' '.join(map(str, l)) for l in [state[:3], state[3:6], state[6:]]] return '\n'.join(lines)
67fb7b091e7256d1fa71f2936d3c8989d5a90f0e
698,477
import re def find_images(document): """Returns the list of image filepaths used by the `document`.""" images = [] for line in document: match = re.match(r"\.\. image::\s+(img\/.+)", line) if match: images.append(match[1]) return list(set(images))
2c58b04974f5ec0d1752cb405cfd314de81a841c
698,481
def determine_time_system(header: dict) -> str: """Determine which time system is used in an observation file.""" # Current implementation is quite inconsistent in terms what is put into # header. try: file_type = header['RINEX VERSION / TYPE'][40] except KeyError: file_type = header['systems'] if file_type == 'G': ts = 'GPS' elif file_type == 'R': ts = 'GLO' elif file_type == 'E': ts = 'GAL' elif file_type == 'J': ts = 'QZS' elif file_type == 'C': ts = 'BDT' elif file_type == 'I': ts = 'IRN' elif file_type == 'M': # Else the type is mixed and the time system must be specified in # TIME OF FIRST OBS row. ts = header['TIME OF FIRST OBS'][48:51] else: raise ValueError(f'unknown file type {file_type}') return ts
00a7908aa5eaf21eaaa39d97b23304644ebe27b4
698,486
def expand_header(row): """Parse the header information. Args: List[str]: sambamba BED header row Returns: dict: name/index combos for fields """ # figure out where the sambamba output begins sambamba_start = row.index('readCount') sambamba_end = row.index('sampleName') coverage_columns = row[sambamba_start + 2:sambamba_end] thresholds = {int(column.replace('percentage', '')): row.index(column) for column in coverage_columns} keys = { 'readCount': sambamba_start, 'meanCoverage': sambamba_start + 1, 'thresholds': thresholds, 'sampleName': sambamba_end, 'extraFields': slice(3, sambamba_start) } return keys
740790e5aa0f5415d3cb0fc22902403b16bef455
698,488
def cap_text(text): """ Capitalize first letter of a string :param text: input string :return: capitalized string """ return text.title()
8403db85d37399db3b4b0693bc9e578ddcf01c3b
698,489
def size_as_recurrence_map(size, sentinel=''): """ :return: dict, size as "recurrence" map. For example: - size = no value, will return: {<sentinel>: None} - size = simple int value of 5, will return: {<sentinel>: 5} - size = timed interval(s), like "2@0 22 * * *:24@0 10 * * *", will return: {'0 10 * * *': 24, '0 22 * * *': 2} """ if not size and size != 0: return {sentinel: None} return {sentinel: int(size)} if str(size).isdigit() else { part.split('@')[1]: int(part.split('@')[0]) for part in str(size).split(':')}
203bc0697cca9b3710f4079de03e759659116883
698,490
import requests import json def get_mactable(auth): """ Function to get list of mac-addresses from Aruba OS switch :param auth: AOSSAuth class object returned by pyarubaoss.auth :return list of mac-addresses :rtype list """ headers = {'cookie': auth.cookie} url_mactable = "http://" + auth.ipaddr + "/rest/"+auth.version+"/mac-table" try: r = requests.get(url_mactable, headers=headers) mactable = json.loads(r.text)['mac_table_entry_element'] return mactable except requests.exceptions.RequestException as error: return "Error:\n" + str(error) + " get_mactable: An Error has occured"
96c064696bf47872e5a1bec5e8770d6470b76bfc
698,493
def es_primo(n: int) -> bool: """Determina si un número es primo. :param n: número a evaluar. :n type: int :return: True si es primo, False en caso contrario. :rtype: bool """ if n == 2 or n == 3: return True if n % 2 == 0 or n < 2: return False for i in range(3, int(n**0.5)+1, 2): if n % i == 0: return False return True
fff4802d6e47c379b6510f13e2ffe9a9d56429d2
698,494
def replace_string(string_value, replace_string, start, end): """ Replaces one string by another :param string_value: str, string to replace :param replace_string: str, string to replace with :param start: int, string index to start replacing from :param end: int, string index to end replacing :return: str, new string after replacing """ first_part = string_value[:start] second_part = string_value[end:] return first_part + replace_string + second_part
b79d685a13c427334149789195e5fbbb4a6ad28d
698,495
import hashlib def hash_str(data, hasher=None): """Checksum hash a string.""" hasher = hasher or hashlib.sha1() hasher.update(data) return hasher
5dd433a3cc04037bb439b64b71d3495d03f51ef1
698,496
import functools def synchronize(lock): """ Decorator that invokes the lock acquire call before a function call and releases after """ def sync_func(func): @functools.wraps(func) def wrapper(*args, **kwargs): lock.acquire() res = func(*args, **kwargs) lock.release() return res return wrapper return sync_func
e9ac48d67cf45e1b0cf9b6e776a93f569726b5d4
698,501
def help_invocation_for_command(prefix, command, locale): """ Get the help command invocation for a command. Parameters ---------- prefix: str The command prefix to show. command: senko.Command The command to get the help invocation for. locale: senko.Locale The locale to get the help invocation for. Returns ------- str The help invocation for the given command in the given locale. """ command_name = command.get_qualified_name(locale) help_name = locale("#command_help_name") return f"{prefix}{help_name} {command_name}"
abf80554c479e3f766e6a7dc1e7bbcafdbaa6098
698,502
import torch def derivative_sigmoid(x): """Compute the derivative of the sigmoid for a given input. Args: x (torch.Tensor): The input. Returns: (torch.Tensor): The derivative at the input. """ return torch.mul(torch.sigmoid(x), 1. - torch.sigmoid(x))
00da3734436294bc8bb40189bc1298972fbe7f93
698,503
from pathlib import Path async def check_node_modules(): """Check if node_modules exists and has contents. Returns: {bool} -- True if exists and has contents. """ ui_path = Path(__file__).parent / "ui" node_modules = ui_path / "node_modules" exists = node_modules.exists() valid = exists if exists and not tuple(node_modules.iterdir()): valid = False return valid
e76703372c46982cf728b26125808e50e2b92907
698,508
def double(number): """ This function returns twice the value of a given number """ return number * 2
65a4bb13ecb45b37f0349f4be2f834f2fd23f813
698,514
def unique_dict_in_list(array): """Returns the unique dictionaries in the input list, preserving the original order. Replaces ``unique_elements_in_list`` because `dict` is not hashable. Parameters ---------- array: `List` [`dict`] List of dictionaries. Returns ------- unique_array : `List` [`dict`] Unique dictionaries in `array`, preserving the order of first appearance. """ if not array: return array result = [] # Brute force. # Avoids comparing json dumped ordered dictionary. # The reason is that when dictionary contains list/dict unhashable items, set does not work. for item in array: if not any([item == element for element in result]): result.append(item) return result
ef18d64c4a896321d57f984c0ede3e0e897c59f5
698,517
def _clean_str(value, strip_whitespace=True): """ Remove null values and whitespace, return a str This fn is used in two places: in SACTrace.read, to sanitize strings for SACTrace, and in sac_to_obspy_header, to sanitize strings for making a Trace that the user may have manually added. """ null_term = value.find('\x00') if null_term >= 0: value = value[:null_term] + " " * len(value[null_term:]) if strip_whitespace: value = value.strip() return value
41b9f0a1388045b86d019464512a0253eb5d6523
698,523
def has_access(user, users): """A list of users should look as follows: ['!deny', 'user1', 'user2'] This means that user1 and user2 have deny access. If we have something longer such as ['!deny', 'user1', '!allow', 'user2'] then user2 has access but user1 does not have access. If no keywords are found then it returns None if the user is in the list. """ if user not in users: return None rusers = users[::-1] try: action = next(x[1] for x in enumerate(rusers) if x[1][0] == '!') except StopIteration: return None if action == '!allow': return True if action == '!deny': return False return False
07d3f47cf3725002023d8c9e487e14280dabc2bf
698,528
def isVowel(letter): """ isVowel checks whether a given letter is a vowel. For purposes of this function, treat y as always a vowel, w never as a vowel. letter should be a string containing a single letter return "error" if the value of the parameter is not a single letter string, return True, if the letter is a vowel, otherwise False """ if (type(letter) != str): # letter must be a string return "error" if (len(letter) != 1): # letter must only be a single character return "error" # return True if letter is a vowel (capital or lowercase) if (letter in ["a","e","i","o","u","y","A","E","I","O","U","Y"]): return True return False
5ba6917c80c4679a59580b8f3a05513d0904cd63
698,531
def isCCW(ring): """ Determines if a LinearRing is oriented counter-clockwise or not """ area = 0.0 for i in range(0,len(ring)-1): p1 = ring[i] p2 = ring[i+1] area += (p1[1] * p2[0]) - (p1[0] * p2[1]) if area > 0: return False else: return True
ef7b3ad88a3a5926896ab1c627b65f2e4e4dc47f
698,533
def get_grant_key(grant_statement): """ Create the key from the grant statement. The key will be used as the dictionnary key. :param grant_statement: The grant statement :return: The key """ splitted_statement = grant_statement.split() grant_privilege = splitted_statement[1] if "." in splitted_statement[3]: grant_table = splitted_statement[3].split('.')[1] else: grant_table = splitted_statement[3] return grant_privilege + "_" + grant_table
200b77d0988090628e013463bba5fe395dd76c00
698,534
def invert(d): """Dict of lists -> list of dicts.""" if d: return [dict(zip(d, i)) for i in zip(*d.values())]
1ac60d7c294e159836be3f6c83817ad7de4f7125
698,536
from datetime import datetime def datetime_str_to_datetime(datetime_str): """ This converts the strings generated when matlab datetimes are written to a table to python datetime objects """ if len(datetime_str) == 24: # Check for milliseconds return datetime.strptime(datetime_str, '%d-%b-%Y %H:%M:%S.%f') else: return datetime.strptime(datetime_str, '%d-%b-%Y %H:%M:%S')
84960880bccfb21bdb2dc1a15b0bd09ef358187c
698,540
def mangle(prefix, name): """Make a unique identifier from the prefix and the name. The name is allowed to start with $.""" if name.startswith('$'): return '%sinternal_%s' % (prefix, name[1:]) else: return '%s_%s' % (prefix, name)
6d949e61a87c6667fdfb262376e476aea64bde4b
698,541
def get_string_value(value_format, vo): """Return a string from a value or object dictionary based on the value format.""" if "value" in vo: return vo["value"] elif value_format == "label": # Label or CURIE (when no label) return vo.get("label") or vo["id"] elif value_format == "curie": # Always the CURIE return vo["id"] # IRI or CURIE (when no IRI, which shouldn't happen) return vo.get("iri") or vo["id"]
0efaa0850a63076dd0334bc54f2c96e4f352d6ae
698,546
def create_msearch_payload(host, st, mx=1): """ Create an M-SEARCH packet using the given parameters. Returns a bytes object containing a valid M-SEARCH request. :param host: The address (IP + port) that the M-SEARCH will be sent to. This is usually a multicast address. :type host: str :param st: Search target. The type of services that should respond to the search. :type st: str :param mx: Maximum wait time, in seconds, for responses. :type mx: int :return: A bytes object containing the generated M-SEARCH payload. """ data = ( "M-SEARCH * HTTP/1.1\r\n" "HOST:{}\r\n" 'MAN: "ssdp:discover"\r\n' "ST:{}\r\n" "MX:{}\r\n" "\r\n" ).format(host, st, mx) return data.encode("utf-8")
cb0da629716e992dd35a5b211f26cae3ad949dcb
698,547
def get_values_from_line(line): """Get values of an observation as a list from string, splitted by semicolons. Note 1: Ignore ';' inside \"...\". E.g. consider \"xxx;yyy\" as one value. Note 2: Null string '' for NA values. """ raw_list = line.strip().split(';') i = 0 values = [] while i < len(raw_list): if raw_list[i] == "" or raw_list[i][0] != '\"': values.append(raw_list[i]) i = i + 1 else: if raw_list[i][-1] == '\"': values.append(raw_list[i][1:-1]) i = i + 1 else: j = i + 1 entry = raw_list[i][1:] while j < len(raw_list) and raw_list[j][-1] != '\"': entry = entry + raw_list[j] j = j + 1 if j == len(raw_list): i = j else: entry = entry + raw_list[j][:-1] values.append(entry) i = j + 1 return values
585c6c9484f6ad145f7265613dc189351cc2d556
698,551