content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
import itertools def non_empty_stream(stream): """yields a single None if the previous stream is exhausted""" return itertools.chain(stream, (None,))
d2e605dc688520d409e00e88b5121b6fac19cac1
628,753
def _copy_ancestor_docstring(mro, fn): """Decorator to set docstring for *fn* from *mro*""" if fn.__doc__ is not None: raise RuntimeError("Function already has docstring") # Search for docstring in superclass for cls in mro: super_fn = getattr(cls, fn.__name__, None) if super_f...
2d915a38141e6b4e8a9869702b9dab07325a2b68
628,754
def getNames(struct): """ 返回某一hpo结构中的name+synonym,并简单处理 """ # 训练集中同义词部分 names = struct.name synonyms = struct.synonym # all name + synonym names.extend(synonyms) # 去重 names = list(set(names)) return names
a38ddabe2b0670f13eeea84dc2e524c06d0e157b
628,756
def parse_exts(extstr): """ Parse a comma or space-separated list of file extensions. """ if not extstr: return None exts = [] for word in extstr.split(): exts.extend((s for s in word.split(',') if s)) return set(( s if s.startswith('.') else '.{}'.format(s) for s in ...
530e49ecfc3f7ee5600d3b11c08f4f9957d09087
628,757
import re def get_prefixes_from_labels(labels): """Extracts a unique list of trigger prefixes from a dict of labels. """ regex = r'^SCALING_TRIGGER_[0-9]+_' trigger_prefixes = set() for k in labels: match = re.match(regex, k) if match is not None: trigger_prefixes.add(m...
661441d729d7acf87dfb925f31bf749f096bd70d
628,758
def get_form_details(form): """ This function extracts all possible useful information about an HTML `form` """ details = {} # get the form action (target url) action = form.attrs.get("action").lower() # get the form method (POST, GET, etc.) method = form.attrs.get("method", "get").lower...
3868f9edf07ea731cb2ce8e68be603dd7a9a936c
628,759
import numpy def find_first_index_reaching_cumulative_sum(a_list, threshold): """ Returns the index at which the cumulative sum of a list has reached a given value :param a_list: list object containing floats or integers :param threshold: a float or integer :return: an index (integer) """ ...
28a57e65badcb9d9d80f2fa5df3d800d972b4d63
628,760
def _prepend_row_index(rows, index): """Add a left-most index column.""" if index is None or index is False: return rows if len(index) != len(rows): print("index=", index) print("rows=", rows) raise ValueError("index must be as long as the number of data rows") rows = [[v...
f0679d3aa24243b78cb7eaba0ef7cf39bb4a6ed1
628,761
from typing import Counter def longestSubstring(s: str, k: int) -> int: """Return the length of the longest substring in 's' such that the frequency of each character in this substring is at least 'k'.""" if len(s) < k: # String shorter than k characters cannot possibly have a # substrin...
f6df7132e14d30a78cf7155f3cdf029e1dec6a64
628,763
def num_of_books_complete_message(tracker): """Return the number of books complete in a message string format.""" num_of_books_complete = tracker.shelf.num_complete_books message = f"You have completed {num_of_books_complete} book" message += "s" if num_of_books_complete != 1 else "" # Add plural m...
2ec18a8a161e73283034cb5dcf14dba0a705dd9f
628,764
import os def sort_by_modified(files_or_folders: list) -> list: """ Sort files or folders by modified time Args: files_or_folders: list of files or folders Returns: list """ return sorted(files_or_folders, key=os.path.getmtime, reverse=True)
16c4b01fca272c95945bd1cd84ba5f36ab37e1fa
628,765
def extract_all_wiki_links(entry): """ Extract all wikipedia links associated to an entry :param entry: entry data :return: """ if "sitelinks" in entry: return entry['sitelinks']
58760d1971c68d18880345f7c4999fd844c61fe7
628,766
def escape_attribute(value, encoding): """Escape an attribute value using the given encoding.""" if "&" in value: value = value.replace("&", "&amp;") if "<" in value: value = value.replace("<", "&lt;") if '"' in value: value = value.replace('"', "&quot;") return value.encode(...
2a3ff495a5082e130b8a59af1bff82a4a4ca6430
628,768
def build_json(**data): """ build_json(**data) -> dict Build a dictionary out of arguments. """ return data
949f84e07a7c16b73c8d9c9b1514f9d63d0b69c0
628,769
def is_uc_alpha(astring): """ (str) -> Boolean return True if any char in astring is an uppercase letter. else return False >>> is_uc_alpha('CIS122') True >>> is_uc_alpha('Ducks') True >>> is_uc_alpha('testing') False """ for c in astring: if c.isupper(): ...
8a409d37cba7110e82b2fef08b8ffa735c868e66
628,770
def getUniversitiesData(): """ This function gets the data from the file and formats it in this format: { format }: 'Name of University + delimeter: (-)' """ print('(Info): Select the name of the file you will work with.') print('(Notice): Example the file name `test.txt`.') fileName = input('> ') if fileN...
ea701b38242ab2d3b993c04aed32ebb689303be1
628,771
def update_last_charged(charging_times, assign_power_cps, time_step): """ Updates the dict containing parking events with their start time and the last time they were charged based on the currently assigned power. Args: charging_times: (dict): Containing each car as keys and their connection ti...
b1e10c7250a317cd91223b2f355f26c15c156bed
628,772
def get_window_in_sec(s): """Returns number of seconds in a given duration or zero if it fails. Supported durations are seconds (s), minutes (m), hours (h), and days(d).""" seconds_per_unit = {"s": 1, "m": 60, "h": 3600, "d": 86400} try: return int(float(s[:-1])) * seconds_per_unit[s[-1]] ex...
099bdb21dc5745064e5942aae559ea1e2e03d62e
628,773
def echo(event): """Echoes back the message it recieves.""" return ' '.join(event.args)
55621b3f3d7fd362ef7ec11e6101e7abcb417b56
628,774
def refetch(model_instance): """ Gets a fresh model instance from the database """ return model_instance.__class__.objects.get(pk=model_instance.pk)
04057c4407749c64cfea3df6fecccb5896596206
628,775
def ddm_irref(a, _partial_pivot=False): """a <-- rref(a)""" # a is (m x n) m = len(a) if not m: return [] n = len(a[0]) i = 0 pivots = [] for j in range(n): # Proper pivoting should be used for all domains for performance # reasons but it is only strictly need...
e6aaf470e954530a7c18f42c0b9f710954426b24
628,776
import os def _get_dest_path(file_name, db_name): """ Append S3 MIDAS_DB path to file(s) """ if db_name.startswith("https://"): compress_cmd = "tar.gz" else: compress_cmd = "lz4" if isinstance(file_name, list): return [os.path.join(db_name, f"{fn}.{compress_cmd}") for fn in fil...
b2387d599e96615e625fc03c9e4b990afef30a0f
628,777
def sumofdigits(G,k=1)->int: """find + of digits """ su = 0 while G > 0: if k == 1: su += (G%10) else: su += (G%10)**k G //=10 return su
40313598fd30a2a377585ff505b87339f65f132e
628,778
import os import json def load_zeshel_data(data_dir, cands_dir, macro_eval=True): """ :param data_dir: train_data_dir if args.train else eval_data_dir :return: mentions, entities,doc """ print('begin loading data') men_path = os.path.join(data_dir, 'mentions') def load_documents(): ...
9df1662ed3a88179995c71daa0f266697af6c983
628,779
import os def read_package_variable(key): """Read the value of a variable from the package without importing.""" module_path = os.path.join('d3m', '__init__.py') with open(module_path) as module: for line in module: parts = line.strip().split(' ') if parts and parts[0] == k...
d03446264be00609c9193778f1d1aa83a68cece4
628,781
import inspect import sys def get_losses(): """ Get all available losses. Returns ------- losses: dict a dictionnary containing all declared losses. """ losses = {} for name, obj in inspect.getmembers(sys.modules[__name__]): if inspect.isclass(obj): losses[name...
1a8f70d5c35211bc1d9012e52d72069bc81e91cd
628,782
import random def random_int(*, k_min: int = 1, k_max: int = 100000) -> int: """Generate a random integer.""" return random.randint(k_min, k_max)
c2542ed55a4a50eee238b09e589d4d9b77df57f2
628,783
def decode_flag(value): """Default a flag. It's exising is just flagged by returning True""" return True
4b72d8ab2761657cbc207263a3cd15d5511dded6
628,784
def permutations(lst): """Lists all permutations of the given list. >>> permutations(['angie', 'cat']) [['angie', 'cat'], ['cat', 'angie']] >>> permutations([1, 2, 3]) [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]] """ if len(lst) <= 1: return [lst] total = [...
eb976e799ed1d0dce93572eab6466880d8a92543
628,785
import subprocess def any_uncommitted_changes(): """Check if there are any uncommitted changes.""" result = subprocess.run( ['git', 'status', '--porcelain'], check=True, capture_output=True, ) return bool(result.stdout)
8f75d213a9a260f696e08719f0369bc2737a7da8
628,786
import platform def get_toolchain_name(): """Return toolchain name.""" if platform.system() == 'Windows': return 'RTools' return ''
8a2918de5e53a0636a1da535afabc1cb34287f89
628,787
def set_walls(rooms, walls): """ Sets the number of walls between every room :param rooms: Dictionary of room objects :param walls: nested list containing number of walls between each room :return: the updated rooms dictionary """ # loop through all walls except the first row, since does not...
7a09b919c65b5ad061b281cafb26c6289fbdba0b
628,788
def coverage(g, c): """Evaluates the coverage of the clustering solution c on a given graph g.""" n = len(g.vs) A_delta = 0 A = 0 for i in range(n): for j in g.neighbors(i): A += 1 if c[i] == c[j]: A_delta += 1 return A_delta/A
64a1dc3d4678bdf72c4c360f10316f4de117480f
628,789
def bytesToMac(addr_bytes): """Convert byte sequence into MAC address Byte sequence can comprise of both single character string elements, as well as byte-encoded string elements, which is extracted as an int. So we need to convert the character to its ordinal Unicode datapoint. b'\\xac\\x84\\xc6\...
14597fdbdd9d0e722907f8437b23826b15534066
628,790
def user_res(users): """User agosti (restricted/restricted).""" return users["res"]
c9370746a558f6f0f3c32be87894322effd8cdc1
628,791
import numpy def accuracy(probas): """ Returns the proportion of predictions that assign the highest probability to the correct answer :param probas: a list of numpy arrays, each containing a distribution of probabilities over candidates answers for one example :return: accuracy """ ncorrect =...
198281b08c81966b9d4ff65150a860c01728efea
628,792
import math def get_phase(jd, jd_phase_zero, period_days): """ For any Julian Date, Julian Date corresponding to phase zero, and period in days, return the phase [float]. TESTS OK 2020-10-24.""" phase = math.modf((jd - jd_phase_zero) / period_days)[0] if phase < 0: phase += 1 return p...
9b48f4c8415c7ff1477084e02af4d8a0bcdb0eb7
628,793
def mni2tal(xin): """ mni2tal for converting from ch2/mni space to tal - very approximate. This is a standard approach but it's not very accurate. ANTsR function: `mni2tal` Arguments --------- xin : tuple point in mni152 space. Returns ------- tuple Example -...
585db96b55c511e58056ba727c07957ff4ce2e52
628,794
from typing import Set def is_sum_of_numbers(number: int, numbers: Set[int]) -> bool: """Check if a given number `number` is the sum of any two numbers from `numbers`.""" for i in range(1, number): if i in numbers and (number - i) in numbers: return True return False
16cf2a7b2e6a5310a43d6e39fb5ecf1e93419f71
628,795
def safe_int(to_int: str) -> int: """Return int from str safely.""" try: return int(to_int) except ValueError: return -1
b5cf6a4af460b102a0c510542348f856c1329899
628,796
def parse_events(props): """ Pull out the dashEvents from the Component props Parameters ---------- props: dict Dictionary with {propName: propMetadata} structure Returns ------- list List of Dash event strings """ if 'dashEvents' in props and props['dashEvents'...
f5cfb1b7feaa8833fecff47be2a3e9ba8128df54
628,797
def make_successive(xs): """ Return a list of successive combinations Parameters ---------- xs : list List of elements, e.g. [X, Y, Z] Returns ------- list List of combinations where each combination include all the preceding elements Examples -------- >>> ...
2a56ad0b5510a514c777b73ddd2507694e1469da
628,798
def y2label(y_pred, int2tag, mask=0): """ Transforms numbers to the corresponding label :param y_pred: list of lists of tag predictions as integers for each word in a sentence :param int2tag: (dict) dictionary of integers to their corresponding tag :param mask: (int) integer corresponding to '-PAD-'...
4ec74c164c05a0198cd2c9bf15134c8c123dbe38
628,800
def log_parameter_task(experiment, parameter_name, parameter_value, **kwargs): """Log a parameter within a `prefect` flow. This `prefect` task can be used within a flow to log a parameter to an existing experiment. Parameters ---------- experiment : rubicon.client.Experiment The experi...
91ad98d1037e32481d4f691b4af28bbba1289531
628,801
def set_custom_certs_enabled( self, enabled: bool, ) -> dict: """Enable or disable custom CA certificate trust store .. list-table:: :header-rows: 1 * - Swagger Section - Method - Endpoint * - customCerts - POST - /customCert/enable ...
942e01fb4dead8166ec328b6e16451ba86e5beed
628,802
def location_modifier(fields): """ Modify the parsed location variable. Subtract 1 from all the start positions in order to be able to use pd.read_fwf() Parameters: field (list): The list of tuples created by location_parser() Returns: fields: A list of tuples """ for i, i...
a121a8d81c96e783c0868df54355d912f1e0ed35
628,803
def format_output(dets, w, h): """ :param dets: detection result input: x1, y1, x2, y2, score, cls_id :param w: image's original width :param h: image's original height :return: list of items: cls_id, conf_score, center_x, center_y, bbox_w, bbox_h, [0, 1] """ if dets is None: return...
7880cb8e94b79056a3303106d45f094134d9b61e
628,804
def snake_to_camel(name): """Converts Python Snake Case to Zscaler's lower camelCase.""" # Edge-cases where camelCase is breaking edge_cases = { "routable_ip": "routableIP", "is_name_l10n_tag": "isNameL10nTag", "name_l10n_tag": "nameL10nTag", "surrogate_ip": "surrogateIP", ...
99f89107e64135353c339f702b16b1113e7e0a1a
628,805
import pickle def predict_model(): """ This function unpickles the saved model and returns it as an object. """ filename = 'trained_model.sav' new_model = pickle.load(open(filename, 'rb')) return new_model
d330d1adbf14f345f5cebd0775eb8fbfea39f221
628,806
import torch def load_embeddings(path): """ """ word2embed = {} with open(path) as f: for line in f: row = line.split(" ") word = row[0] embedding = torch.FloatTensor(list(map(float, row[1:]))) word2embed[word] = embedding return word2embed
fbb4197c39d1d92034d35cf46195580de0344f8f
628,807
def has_keys(data, keys): """ Checks whether a dictionary has all the given keys. @type data: dict @param data: Parameter name @type keys: list @param keys: list containing the expected keys to be found in the dict. @rtype: bool @return: True if all the keys are found in the dict, ...
eeac1caddc30e703cde22ce849707a05d12ef44c
628,808
def _memoryview_safe(x): """Make array safe to run in a Cython memoryview-based kernel. These kernels typically break down with the error ``ValueError: buffer source array is read-only`` when running in dask distributed. SEE: https://github.com/dask/distributed/issues/1978 """ if not x.flags.wri...
e5941e7ba2779d62179a4c303d0b0664cef1fda6
628,809
import random def simulate(cc, tc): """Takes the total count of cards in a card pack and the count of specific cards to be obtained and returns the count of rolls and duplicates aggregated in obtained the target cards.""" tc = tc if cc >= tc else cc missing = set(range(1, cc + 1)) targets = ...
ba2d014b887f0bdbc92373af3151ed4eb0f8c405
628,810
def cleanup_string(dset) -> str: """ Returns bytes as string """ if len(dset) == 1: return dset[0].decode('ascii').rstrip('\0') return dset[:].tobytes().decode('ascii').rstrip('\0')
e16c9171ea2852662baede2e7223820d60f23c9c
628,811
import string def simple(s): """Break str `s` into a list of str. 1. `s` has all of its peripheral whitespace removed. 1. `s` is downcased with `lower`. 2. `s` is split on whitespace. 3. For each token, any peripheral punctuation on it is stripped off. Punctuation is here defined by `strin...
9065163ec57a3d733e900b7608341e98fc318f40
628,812
from pathlib import Path import os def project_root() -> Path: """Root directory of the project.""" return Path(os.path.dirname(__file__)).parent
772a125697ebde05048158ba90926a1add75a504
628,814
def get_player_names(): """ Get a list of names from the players. """ print("Enter player names. Enter as many players as you like.") done = False players = [] while not done: player = input("Enter player (hit enter to quit): ") if len(player) > 0: players.append(player) ...
3ee0a832dcadc7d29b1e28aab3297f76c1761328
628,815
def _normalize_depth_vars(depth_k, depth_v, filters): """ Accepts depth_k and depth_v as either floats or integers and normalizes them to integers. Args: depth_k: float or int. depth_v: float or int. filters: number of output filters. Returns: depth_k, depth_v as inte...
27cc0635b3e5f3f8529ed20883a97efb03ee0c89
628,816
def str2int(s1): """ Convert an ASCII string to it's corresponding integer format """ return int(s1.encode("hex"), 16)
9c7484c6e3b2e92dd37f1cf95be4053a7d90077d
628,817
def add_comma_rs(_index, _value, _row_separator): """Adds a comma and row separator if index > 0, used in loops when making lists of references.""" if _index > 0: return ',' + _row_separator + _value else: return _value # Some database functions
6a9b684ee95429e1034184654ef6bdcd9269113d
628,818
def store_metadata(file): """ Store file's metadata as a dictionary of strings. :param file: unprocessed input file. :return: dictionary of metadata. """ metadata = {} filetype = False # Check if the file has an embedded json. for i in range(2): devnull = file.readline() # I...
334478be2c6616450ccebfb8f4cb7d5dcd94fb3d
628,819
def group_values_nearest(values, closest=2): """Group given values together under multiple buckets. :param values: values to group :type values: list :param closest: closest is the maximun value difference between two values in order to be considering in the same bucket, defaults to 2 :type clo...
c604ac0e9295da033c10afbc231e06b77a140a61
628,820
def combinations(seqs): """ Recipe 496807 from ActiveState Python CookBook Non recursive technique for getting all possible combinations of a sequence of sequences. """ r=[[]] for x in seqs: r = [ i + [y] for y in x for i in r ] return r
0c084b40105c284a29ad9ef189cfda60ce4088a1
628,821
def collect_content(parent_tag): """Collects all text from children p tags of parent_tag""" content = '' for tag in parent_tag: p_tags = tag.find_all('p') for tag in p_tags: content += tag.text + '\n' return content
8ad73c3c6fc0e4e0fea0fac14485ba881508a881
628,822
import pandas as pd def read_in_LSHTM(): """ Read in new LSHTM Reff csv from David Price et al """ path = "../data/LSHTM_Reff_estimates/Reff_LSHTM.csv" return pd.read_csv(path,parse_dates=['date','date_of_analysis'])
3ff9db4f110f31e384404d77fb6ce11d093c7568
628,824
def build_gameboard(term): """Build the gameboard layout.""" column, row = 0, 0 board = dict() spacing = 2 for keycode in sorted(term._keycodes.values()): if (keycode.startswith('KEY_F') and keycode[-1].isdigit() and int(keycode[len('KEY_F'):]) > 24): ...
d844ae414e11bbf895b42f62c4965b05009d108e
628,825
def create_error_text(error_response: dict) -> str: """ Creates error text for Telegram Bot error response. See https://core.telegram.org/bots/api/#making-requests """ description = error_response.get("description", "?") error_code = error_response.get("error_code", "?") return f"{error_cod...
d9e8b8002e5ce422c29bda85ed9a935ddf1ecf68
628,826
def extract_file_names(videos_path: str) -> list: """ Extract filenames from .lst file. Args: videos_path (str): Path to .lst file. Returns: list: List of filenames. """ with open(videos_path, "r") as f: file_names = [line.strip() for line in f.readlines()] return file...
e27245dd80ffb668a4e47054805dbc56fee1c498
628,827
from typing import Counter def get_stocks_with_count(series): """ Count all mentioned stocks params: Series p.Series return: dict with stock symbol and total count """ j = 0 counter_list = [] dict_counter = [] for i in series: counter_list.append(Counter(se...
f30df15ae9e04bafd0d6236c9c74bbee4e31c959
628,828
def byte_length(n): """Finds the byte length of an `int` object.""" return (n.bit_length() + 7) // 8
5d4b258d8c9bcccbdd4f0739458ce91cbd8825fa
628,829
def changePlayer(player): """Returns the opposite player given any player""" if player == "X": return "O" else: return "X"
118d4c7ad04c16edebb1c8b829462327cccc4235
628,830
import re def get_opts(): """Get optimization options Returns: list of optimization flags. eg: ['-fdefer-pop', '-fdse'] """ f = open("target/opt.txt") lines = f.read() f.close() # return [line.replace(" \n", "") for line in lines if line != ""] return re.findall(...
48837258fbc88d005122212413dd122cb49962ba
628,831
def pad_cust_seq(cust_list: list, max_seq: int, max_items: int) -> list: """ Function to pad customer sequences to equal lengths as required by downstream models Parameters ---------- cust_list: list List of customers and items purchased in each transaction max_seq: int Length of th...
c2d52610178678c3823e68fa062838de781f3efb
628,832
def noop_handler(request): """Catch all handler, checks if the request has a context, if it does, return a 204 else 404. """ response = request.response if request.context: response.status_int = 204 response.body = '' del response.content_type else: response.st...
d28ed0fdc3286fd72ea04fa9fe39ca84a0485406
628,833
def generate_election_administration(election_authorities): """ PURPOSE: generates election_administration dataframe for .txt file INPUT: election_authorities RETURN: election_administration dataframe SPEC: https://vip-specification.readthedocs.io/en/latest/csv/element_files/election_administration....
120be1cb1fc48761ca73f021a004f9cd5fdb8222
628,835
import configparser def read_configuration(file_path): """ reads configuration from given file path For two displays: return (p_brightness, p_red, p_green, p_blue, temperature s_brightness, s_red, s_green, s_blue) for one display: return (p_brightness, p_red, p_green, p_blue, tempe...
6b428d19698f43d35d80345e927a4d8213155837
628,836
import os import glob def find_thermo_libs(path: str): """ This function search for the thermo library based on ``RMG libraries/thermo/*.py`` Args: path (str): The path to project directories Returns: thermo_lib_list (list): Entries of the path to thermo libraries """ # I...
077e2c7d127a719573fa6a5d1d148d224e49b6ec
628,837
def exp_to_int(s): """ Converts numbers like 1.01e+2 or 1.007783151912803607421e+21 to integers. By default, these are parsed by the float function and lose precision """ if 'e' in s: #if it is exponential exp = int(s.split('+')[1]) (whole, tmp) = s.split('.') frac = tmp.split('e')[0] assert(len(frac) <= e...
a7afed4d2a69d5380fee301d52887d4f0785477f
628,838
def reduce_diff(diff): """remove the lines added for context and just keep the lines that show the actual differences """ new_diff = "" for line in diff.splitlines(): if line[:2] in [" ", "? "]: continue new_diff += line + "\n" return new_diff
e297728e9e6948a51c31ecf68f7031b8e2848012
628,839
def create_time_periods(connector, future_years): """ This function writes the time_periods table to an sqlite database. Only "future" time periods will be written. Parameters ---------- connector : sqlite3 connection object An object for connecting to a specific SQLite database...
a4175f8029427c772c0dc340f85fd52f504d3ee9
628,841
def get_operand_expression(nvols): """ Generates operand string Parameters ---------- nvols : int Returns ------- expr : string """ expr = None vol = int(nvols) expr = ('a*sqrt(%d-3)' % vol) return expr
48eb937ab241e74b061c6f0abe84d00e6e9ee0d6
628,842
from typing import List from typing import Tuple import re def parseList(page: str) -> List[Tuple[str, str]]: """Parse given wikicode of a List page.""" result: List[Tuple[str, str]] = [] currentSection = '' for part in page.split('==='): # Sometimes should be == part = part.strip() i...
183c3c95b5233a0dbc0932ff14e782aeebd6f93c
628,843
from json import dumps def format_json(source): """Structure json.""" return dumps(source, indent=4, sort_keys=True)
0d49557c1ec54715a530e8c67d95ec0289174a3d
628,845
def merge_list(list1, list2, remove_duplicate=False): """ merge two lists when remove_duplicate is false, duplicate item will be kept. when remove_dupliate is true, no duplicate item is allowed """ merged_list = [] if not list1 and list2: merged_list.extend(list2) elif list1 and ...
a24183694c44e75be4d3f3946dab691c9c6ff734
628,847
import argparse def parse_args(): """ Parse input arguments """ parser = argparse.ArgumentParser(description='Single image depth estimation') parser.add_argument('--cuda', dest='cuda', help='whether use CUDA', action='store_true') parser.add_argu...
51838ab799333da5e66f27ef100bac91b4205109
628,848
def get_date_filter(report_config): """ Returns the first date filter, or None. Assumes the first date filter is the one to use. .. NOTE: The user might not want to filter by date for DHIS2 integration. They can use a "period" column to return rows for multiple periods, or se...
c5c105334e96d90b3e6ecd322f69af240c5b7268
628,849
def Brflen(value,arg): """ :param value: flow :param arg: user :return: """ try: allflow = arg.flow_set.all() if value in allflow: return True else: return False except: return False
6279b858595f89ec75cd5cc94ecb8f9980bc9f9b
628,850
def freeze_layers(model, stop_layer, offset, printParams=True): """Utility to stop tracking gradients in earlier layers of NN for transfer learning""" cntr = offset for name, param in model.named_parameters(): if cntr < stop_layer or name.find('batch_norm') >= 0: param.requires_grad ...
8aa944cc907609bf81fb6962dee5bd24a331ec57
628,851
import pathlib def join(*pthslist): """ Returns the join of all paths""" return str(pathlib.PurePath(*pthslist))
a783d49670ba908d5331dfbabef008e957905ff2
628,853
import pytz from datetime import datetime def get_current_date(): """ returns the current date in UTC as a datetime object """ utc = pytz.utc date = datetime.now(tz=utc) return date
d0e2a4b76dd8be7008ef6513c3012f1042e82616
628,854
import json def question_pack(info="", userid="A0001", key="A0001"): """Package the question as the JSON format specified by the server. 将问题打包为服务器指定的json格式。 Args: info: User question. 用户的聊天或提问。 Defaults to "". userid: User id. 用户唯一标识。 Defaults to "userid". Ret...
2bec6ad486da250e91036130b8341397a1eb207c
628,855
def total_after(number: int) -> int: """Return the total number of grains up to a given square.""" return (1 << number) - 1
522e62af2bcc7e571dde80ea8bd413e17a1e8e35
628,856
import os def get_last_dir_and_file_names(file_path): """ Return a string with the name of the last directory and the name of the file in file_path. :param file_path: Example: /dir1/dir2/filename.txt :return: a string. Example: dir2/filename.txt """ path = os.path.dirname(file_path) dir = ...
1954acfde0d7cd7020e14d79114017c01b07d267
628,857
def _parsems(value): """Parse a I[.F] seconds value into (seconds, microseconds).""" if "." not in value: return int(value), 0 else: i, f = value.split(".") return int(i), int(f.ljust(6, "0")[:6])
d444b18bb255a997b7c8a3e84e66a5842a1658b5
628,858
import ast def parse_cwes(str1): """ Converts string to list. """ lst = ast.literal_eval(str1) lst = [x.strip() for x in lst] return lst
01511481c4c86823143e4d24dea068cbe747d4cc
628,859
def clean_rent(df): """ Clean the data frame from the sales query. :param df: the data frame with data from sales :return: the cleaned data frame """ # Reassign column names col = ['Unnamed', 'Keskivuokra ARA-vuokra', 'Keskivuokra Vapaarah. vanhat', 'Keskivuokra Vapaarah. uudet', ...
090f39c484909c67fdce51f7801fd7d62a80eff3
628,860
def get_error_codes(err_code_file): """Function to retrieve all block numbers from the `run-tests-codes.sh` file to maintain backwards compatibility with the `run-tests-jenkins` script""" with open(err_code_file, 'r') as f: err_codes = [e.split()[1].strip().split('=') for e...
c95d4f6212af08a75696ca2fc45ef898f9ccbd69
628,861
import os import sys import json def load_credentials(filepath = "~/.ega.json"): """Load credentials for EMBL/EBI EGA from ~/.ega.json""" filepath = os.path.expanduser(filepath) if not os.path.exists(filepath): print("{} does not exist".format(filepath)) sys.exit(1) with open(filepath)...
dae39b747862424d6da271a374036ce8c0a7733d
628,863
def reader(fileaddress): """Reads the contents of a given file into an array""" tied = [] with open(fileaddress, 'r') as ft: for line in ft: if(line[0]!="#"): tied.append(line) ft.close() return tied
30e36e49d7af69bff246af1c9cce5d7d7c4e6e95
628,864
def _expand_path(graph, source, step, visited, degrees): """Walk a path on a graph until reaching a tip or junction. A path is a sequence of degree-2 nodes. Parameters ---------- graph : NBGraph A graph encoded identically to a SciPy sparse compressed sparse row matrix. See the doc...
a79b838319b6314210a86f417554f6d354f22647
628,866