content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def index_by(d, index_by, value_from_key): """ Extract a key from a dictionary and assign the value to the one from another key """ return {d[index_by]: d[value_from_key]}
d6ebd19f610d050525e27e6c936ce05284dba7ab
672,502
import json import re def parseResult(directions_result): """ Parse result form google maps API's directions-function. """ turn_coord = None turn_type = None distance_to_turn = 0; data = json.loads(json.dumps(directions_result)) steps = data[0]['legs'][0]['steps'] for step in steps: ...
8fe17059b4fbdf6c37af2c78c7a8d7cac78db24f
672,503
def _ngm_2(in_fa): """Infer ngm file paths from in_fa""" return '%s%s' % (in_fa, '-ht-13-2.2.ngm')
f26ff837a7d4834b1af998c7b97fef1f3a97d36a
672,504
def get_mentions(content) -> str: """ Get user mentions from json """ mentions = list() for name in content['entities']['user_mentions']: mentions.append(name['screen_name']) return '|'.join(mentions)
c989e70314297ef16f4f7d3a87cbfe3304c6c9ad
672,505
def Welcome(): """List all available api routes.""" return ( f"*List of Available Routes:<br/><br/>" f"*Date and Precipitation.<br/>" f" /api/v1.0/precipitation<br/><br/>" f"*stations.<br/>" f" /api/v1.0/stations<br/><br/>" f"*temperature observations...
00bf0839f1a8410123c48131248a2f11060acdbb
672,506
import uuid def trace_key(): """ Return a "trace key" suitable to track program execution. It's most likely unique between invocations. """ # We will never make a 32-bit operating system. return uuid.uuid4().hex[:16].upper()
7761be64bd20b427c56157df34c5edf4575f129e
672,507
def cast_run_to_run_ts(run, array_list=None, station_id=None): """ add to mth5 helpers? basically embed data into a run_ts object. array_list = get_example_array_list(components_list=HEXY, load_actual=True, station_id="PKD")...
7c5f73c159a809de7463b3e6ec1c21906549572d
672,508
import datetime from time import sleep import urllib.request import json import pandas as pd def getData(date): """recebe um objeto date ou uma string com a data no formato YYYY-MM-DD e retorna uma 'Série' (do pacote pandas) com os níveis dos reservatórios da sabesp""" fixPercent = lambda s: float(s....
056d16fb1fe8df0dbaef223145aadcd563ba166b
672,509
import pydoc def _find_return_type(func): """Return the K8s response type as a string, eg `V1Namespace`. Return None if the return type was not in the doc string of `func`. Raise `AssertionError` if the doc string was ambiguous. NOTE: this function _assumes_ the doc strings have a certain type. ...
52fc239ae49d7213a2cc39aaa523fdfd9319075a
672,510
def spread(spread_factor: int, N: int, n: int) -> float: """Spread the numbers For example, when we have N = 8, n = 0, 1, ..., 7, N, we can have fractions of form n / N with equal distances between them: 0/8, 1/8, 2/8, ..., 7/8, 8/8 Sometimes it's desirable to transform such sequence with finer st...
4252d123a223a30acbcf41f9c8eb00e6a3f08a4f
672,511
import re def intersection(file1, file2): """ Args: Returns: """ set1 = set() with open(file1) as fh: for line in fh: if re.search(r"^#|^\s*$", line): continue if re.search('Plasmid', line): array = line.strip().split("\t") ...
95a832f75c1cd7bf16fc2066f24a7aa5d248c002
672,512
def get_n_p(A_A): """付録 C 仮想居住人数 Args: A_A(float): 床面積 Returns: float: 仮想居住人数 """ if A_A < 30: return 1.0 elif A_A < 120: return A_A / 30 else: return 4.0
1acd1b943a86977635011bc6b0b7064bf6683abd
672,513
import os import logging def active_and_install_packages_pip() -> bool: """ Activate virtualenv and install package pip in virtualenv Parameter Return """ try: os.system(f'. .venv/bin/activate &&' f'pip install -r requirements.txt' ) loggi...
d501cc44b0b05ba4eb6341e768e458277a4f4fde
672,514
def csv_is_empty(filename): """Check if a given csv file is empty by making sure each of the rows in the file does not have a string on it. """ with open(filename, 'r') as f: for row in f: if len(row) != 0: return False return True
99aa7325f96f3b5f72c7e31b562a9d0c4392dde3
672,515
def value_info_parse(t): """parsing tensor value information""" # make_tensor_value_info(name,elem_type,shape,doc_string="",shape_denotation=None) --> ValueInfoProto dynamic = False name = t.name etype = t.type.tensor_type.elem_type shape = t.type.tensor_type.shape dims = [] for e in sh...
ee09b6fc1c9f613c46ba814be3ca902af4512c90
672,517
def count_inversion(sequence): """ Count inversions in a sequence of numbers """ s = list(sequence) a = 0 b = True while b: b = False for i in range(1, len(s)): if s[i-1] > s[i]: s[i], s[i-1] = s[i-1], s[i] a += 1 ...
5637b8ed51b38b30d5975c8fb11cf177d5c0c47d
672,518
def get_image_bytes(image_file_name): """get the bytes of an image file in base64""" image_file = open(image_file_name,'rb') image_bytes = image_file.read() return image_bytes
daeb58f6789fe44afe1c4ffcee21898a05f5721c
672,519
def _ParsePlusMinusList(value): """Parse a string containing a series of plus/minuse values. Strings are seprated by whitespace, comma and/or semi-colon. Example: value = "one +two -three" plus = ['one', 'two'] minus = ['three'] Args: value: string containing unparsed plus minus values. Re...
43847aeedc61fd49a76475ee97ff534f55d80044
672,520
def filter_secrets(txt: str) -> str: """Replaces secrets with *'s""" # Example: # output = txt.replace(password, '*' * len(password)) # output = output.replace(username, '*' * len(username)) # return output return txt
691ac872ab696a8a4c74a5825ea02286f8b38681
672,521
def load_id01_monitor(logfile, scan_number): """ Load the default monitor for a dataset measured at ID01. :param logfile: Silx SpecFile object containing the information about the scan and image numbers :param scan_number: the scan number to load :return: the default monitor values """ ...
be5d9ea24b328c07a471fe3d8327298d900111a2
672,522
from datetime import datetime def time_delta(t1, t2): """ Takes two datetime strings in the following format : Sun 10 May 2015 13:54:36 -0700 and returns the time difference in seconds between them. Parameters ---------- t1, t2 : string Input two timestamps to compute ...
b53bd6bb372b74aa025429c2721f75ff006eabb0
672,523
import json import base64 def get_key(path): """ This is to retrieve a stored key and username combination to access the EPC API. These values are stored in a JSON file in a local directory and hidden by the .gitignore to avoid making these public. The key is then encoded as per the EPC documentation....
1ae39887c1e12bbc2919600b1f1b531b3ec6ad03
672,524
def _get_edge_length_in_direction(curr_i: int, curr_j: int, dir_i: int, dir_j: int, i_rows: int, i_cols: int, edge_pixels: set) -> int: """ find the maximum length of a move in the given direction along the perimeter of the image :param curr_i: current row index :param ...
7dcf08f91c80b351d27fe2b497b24f6368ee32d8
672,526
def generate_news_url(query, first, recent, country_code): """(str, str) -> str A url in the required format is generated. """ query = '+'.join(query.split()) url = 'http://www.bing.com/news/search?q=' + query + '&first' + first if recent in ['h', 'd', 'w', 'm', 'y']: # A True/False would be eno...
f95905c6e221ed2d31365e1d1229521cd9bfa1f3
672,527
def __model_forward_pass__(args, model, obs_traj_seq, pred_traj_len, seq_start_end, metadata, curr_sample, model_fun): """ Wrapper call to the model forward pass, which depending on the exact model, may require different kinds of input :param args: command line arguments that contain several parameters to c...
69c7f761631248931d70e8f46da8a0068695c21b
672,528
def check_database(con, dbname): """Check a database exists in a given connection""" cur = con.cursor() sql = """SELECT 0 FROM pg_database WHERE datname = '%s'""" cur.execute(sql % dbname) result = cur.fetchall() if result: return(True) else: return(False)
1349e46fdf99e5180e4c889c4e510ba4c71d1f2f
672,529
def are_sorted_heaps_equal(first_heap, second_heap): """ Determine if the heaps produce identical sequences when heap-sorted. Applying sorting to two heaps and comparing output is the way to determine if two heaps are equivalent. As function continiously extracts elements from the heaps, the heaps...
603bf139f0e68eb2d9672797b74f76f0105f01e7
672,530
import math def _circle_loss(labels, scores, rank_discount_form=None, gamma=64., margin=0.25): """Returns the circle loss given the loss form. Args: labels: A list of graded relevance. scores: A list of item ranking scores. rank_disc...
0ad130145d2c7c206c075f5614676048245a2555
672,531
def validation_backends(): """Return a list of validation backends supported by the environment.""" ret = [] try: ret.append('flex') # pragma: nocover except (ImportError, SyntaxError): # pragma: nocover pass try: ret.append('openapi-spec-validator') # pragma: nocover except (ImportError, S...
27b3b26cec577605bc1f1f79a4cb912d6822ff23
672,532
def isIsomorphic(self, s, t): """ :type s: str :type t: str :rtype: bool """ return len(set(zip(s, t))) == len(set(s)) == len(set(t))
1e74ac17cc3c054d714333ba2d2c7c69a40c32b5
672,533
def search_for_elmt(L, e): """ >>> search_for_elmt([1,2,3,4], 2) True >>> search_for_elmt([2,4,6,8], 3) False >>> search_for_elmt(list(range(1**2, 10)), 4) True """ for i in L: if i == e: return True return False
99b7c10f5b2b868c1517f1d2b7d93d7c740f0aec
672,534
def uncompressEcdsaPublicKey(pubkey): """ Uncompressed public key is: 0x04 + x-coordinate + y-coordinate Compressed public key is: 0x02 + x-coordinate if y is even 0x03 + x-coordinate if y is odd y^2 mod p = (x^3 + 7) mod p read more : https://bitcointalk.org/index.php?topic=644919.msg7205689#msg7205689 """...
850831ec5832ab1a65f91815fd24fd80609c183f
672,535
def get_filename_with_dead_code_stats(hist_repo, repo_to_measure): """Get the filename that contains dead code statistic.""" return "repositories/{repo}/dashboard/{repo_to_measure}.dead_code.txt".format( repo=hist_repo, repo_to_measure=repo_to_measure)
de4048e756d3300a3ec3c2e69b8d0e0660bb8c31
672,536
def perc_data_bars(column): """ Display bar plots inside a dash DataTable cell. Assumes a value between 0 - 100. Adapted from: https://dash.plotly.com/datatable/conditional-formatting """ n_bins = 100 bounds = [i * (1.0 / n_bins) for i in range(n_bins + 1)] ranges = [float(x) for x in ...
a59b742b71a845f01e71580aaaf67e9a2d78950c
672,537
import torch def random_ccm(): """Generates random RGB -> Camera color correction matrices.""" # Takes a random convex combination of XYZ -> Camera CCMs. xyz2cams = [[[1.0234, -0.2969, -0.2266], [-0.5625, 1.6328, -0.0469], [-0.0703, 0.2188, 0.6406]], [[0.4913, -0.0541...
aef8fee15d961619a7ae8b4d88d2fc478715e091
672,538
import os def infiniband_devices(interface): """Return a list of device paths associated with a kernel network interface, or an empty list if not an Infiniband device. This is based on https://github.com/amaumene/mlnx-en-dkms/blob/master/ofed_scripts/ibdev2netdev plus inspection of /sys. """ ...
008e483a388e71cf50bbe3ef6710e3cea59b6d98
672,539
def sort_work(params, priority): """ Returns a dictionary as params but ordered by score Input: params = dictionary of the form {input_name : value} priority = the list of input_name ordered by score calculated by score_function Output: sorted_dict = the same dictionary as params b...
6ecfca8245cccd539893c23366490a9b9e00e92d
672,540
from typing import Set def get_unique_id(id_: str, reserved_ids: Set[str]) -> str: """ Returns a unique ID for a field. """ if id_ not in reserved_ids: reserved_ids.add(id_) return id_ i = 1 while True: new_id = f"{id_}_{i}" if new_id not in reserved_ids: ...
0c98e91149f97f68cc08927af75d9c4993e03cd5
672,541
import logging import json def get_urls(u_type) -> str: """this function returns the required base URL given by u_type """ logging.info("URLs extracted by get_urls()") with open('config.json', 'r') as file: json_file = json.load(file) urls = json_file["base-URLs"] if u_type == "weather": ...
3de2f6b8be98f5cae4843dfa96e65c9204810ad6
672,543
def reallocate(array, old_size, new_size): # """ """ if new_size == 0: return None elif old_size > new_size: return array[:new_size] # Create empty list if array is None array = array or [] return array + (new_size - old_size) * [None]
0ee207c1087d3b020743449673fc8a30e9c198ec
672,544
import re def camelize(string, uppercase_first_letter=True): """ Convert strings to CamelCase. From inflection package: https://github.com/jpvanhal/inflection Examples:: >>> camelize("device_type") 'DeviceType' >>> camelize("device_type", False) 'deviceType' """ if not strin...
8f355a1ce2648250a6bf5b7b37614fd53e7706b6
672,545
import dateparser from datetime import datetime def _parse_date(string): """ A simple dateparser that detects common date formats Parameters ---------- string : str a date string in format as denoted below. Returns ------- datetime.datetime datetime object of a time....
707fe62df1cc348ac71accd70f08da6aace813ed
672,546
import time def time_to_call_it_a_day(settings, start_time): """Have we exceeded our timeout?""" if settings.timeout <= 0: return False return time.time() >= start_time + settings.timeout
a0c5c3e28da369522093760a3977af89dba5a5a8
672,547
from typing import List from typing import Tuple def fold_the_stuff( coords: List[Tuple[int, ...]], actions: List[Tuple[str, int]], iteration_loops: int = 0, ) -> List[Tuple[int, ...]]: """ Folding across X means... For all values with X > fold point: Dist = N => subtract 2 * N from th...
8f076e11ef53738e5de1fe7858d998f99f6b95e4
672,548
def _convert_change_list_to_new_query_json(inp_json, change_list): """ As the json for the new query would be very similar to the json of the requested query, the oversights only return a list of changes to be made in the current json. This function takes as input the current json, applies the list ...
efc61c291b01d2743b38e0a3327f06fa1d046bbd
672,549
def input_file(tmpdir_factory): """Generate a temporary file used for testing the parse_file method.""" rows = [('81 : (1,53.38,€45) (2,88.62,€98) (3,78.48,€3) (4,72.30,€76) ' '(5,30.18,€9) (6,46.34,€48)'), '8 : (1,15.3,€34)', ('75 : (1,85.31,€29) (2,14.55,€74) (3,3.98,€16) (4,26.24,€55...
7e4e10c8096a44da6b9e8caac7f84a1e9ea224e7
672,550
from datetime import datetime def datetime_from_qdatedit(qdatedit): """ Return the Python datetime object corresponding to the value of the provided Qt date edit widget. """ return datetime( qdatedit.date().year(), qdatedit.date().month(), qdatedit.date().day())
725f6a65ba8cb4012eb2955a7a672989a5d2c722
672,551
def normalize_method_target(name): """ メソッド名からロードする実際の関数名に戻す """ return name.replace("-","_")
4394fea85c1777f63a5af7caf382cc427492bd39
672,552
def clean_url(url): """ Strips the ending / from a URL if it exists. Parameters ---------- url : string HTTP URL Returns ------- url : string URL that is stripped of an ending / if it existed """ if url[-1] == '/': return url[:-1] return url
e5d5015adf4e06064a0d4d5638284bf1341f1a28
672,553
def make_test(path, status, method='GET', data=None): """ Generate a test method """ def run(self): response = getattr(self.client, method.lower())(path, data or {}) self.assertEqual(response.status_code, status) return run
c04c15cfad3721eb3b8a73e315f45ac7a3e42a50
672,554
import os def full_file_list(scan_path): """ Returns a list of all files in a folder and its subfolders (only files). """ file_list = [] path = os.path.abspath(scan_path) for root, dirs, files in os.walk(path): if len(files) != 0 and not '.svn' in root and not '.git' in root: ...
34c48986f0a4c4e539b3a5e3ac684e33c65b174b
672,555
def insertion_sort_inc(A): """ insertion sort always maintains a sorted sublist it has O(n2) time complexity sorted sublist is in the lower positions of the list """ for i in range(1, len(A)): key = A[i] j = i-1 while (j >= 0 and A[j] > key): A[j+1] = A[j] j -= 1 A[j+1] = key return A
59175b34980005bfb2323db0e5926d56b4c1d0e6
672,556
import os def readBbox(path): """ Function: Read bbox of face, [x, y, w, h] Input: path, Date: 2017.12.01 """ if not os.path.isfile(path): raise ValueError('error: not exist file: ' + path) with open(path) as fid: imgNameList = [] bboxList = [] cnt = 0 for line in fid: cnt += 1 if cnt <= 2: ...
2c146a1e4bf0ee0dba459a763308c50077577b84
672,557
import requests import json def call_rest_api(endpoint, query): """ Call REST API endpoint :param endpoint:e.g. 'http://127.0.0.1:9500/wind_deg_to_wind_rose' :param query: e.g. query = {'wind_deg': wind_deg} :return: """ response = requests.get(endpoint, params=query) if response.sta...
9a0e061dca1d3fa76803dcc70c883d5f80e460a0
672,558
def combine_docstrings(cls): """ Combine the docstrings of a method and earlier implementations of the same method in parent classes """ for name, func in cls.__dict__.items(): # Allow users to see the Poppy calc_psf docstring along with the JWInstrument version if name == 'calc_psf': ...
321a01473ee8683c785c5f308bb403bcc02c4c30
672,559
def _fix_ergowear_raw_data_axis(acc_data, gyr_data, mag_data): """ Correct sensor axis for NWU. """ acc_data *= [-1., 1., 1.] gyr_data *= [ 1., -1., -1.] mag_data *= [ 1., -1., -1.] return acc_data, gyr_data, mag_data
da8384afd5beb993ea5eebb60cc628cb8dbfe524
672,560
import os def GcsBasename(path): """Get the base path of a Cloud Storage path. Example: GcsBasename('gcs://bucket/dir/file.ext') => 'file.ext' Args: path: A Cloud Storage path. Returns: Path without the directory part. """ return os.path.basename(path)
3ad903ba63651556dddb5541e5982cdaf5dcde0b
672,561
from typing import Any def cursorless_decorated_symbol(m) -> dict[str, dict[str, Any]]: """A decorated symbol""" hat_color = getattr(m, "cursorless_hat_color", "default") try: hat_style_name = f"{hat_color}-{m.cursorless_hat_shape}" except AttributeError: hat_style_name = hat_color ...
27e72991ff4e2fc46f43456df8258f29d46c234b
672,562
import torch def linreg(X, w, b): """Linear regression.""" return torch.mm(X, w) + b
bcdf82e2f39a3035b57e8ac4e5eff8bc1a33517e
672,563
def split_even_odd(x): """ split a list into two different lists by the even and odd entries :param x: the list :return: two lists with even and odd entries of x respectively """ n, c, h, w = x.size() x = x.view(n * c, -1) return [x[0:((n * c) - ((n * c) % 2)), :].t().view(h * w, -1, 2)[...
690aca808d54c5602453ef151a8f17f687fd330a
672,564
def display_rows(content, message, is_ratio=True): """Return content formatted for display to terminal. keyword args: content list -- A list of tuples obtained from a SQL query message string -- A string used as the title of the formatted output is_ratio boolean -- A boolean used to determine if '%...
2eda7c52e34d14503dad36f4281b93879b7051e4
672,565
def _read_file(fname): """ Args: fname (str): Name of the grammar file to be parsed Return: list: The grammar rules """ with open(fname) as input_file: re_grammar = [x.strip('\n') for x in input_file.readlines()] return re_grammar
9e6fba0bf76f3170a3d26a73ba6bac3c9c8c34be
672,566
import itertools def f(d, n): """ my itertools solution. too slow for final solution """ dice = '123456' comb = itertools.product(dice, repeat=d) perm_list = [] def sum_check(x, n): return sum(x) == n for c in comb: intd = list(map(int, c)) if sum_check(intd, ...
4d517953b21f66aaa011d483546bf46f88d3f297
672,567
def H2Oraman(rWS, slope): """Calculate water contents using the equation (3) from Le Losq et al. (2012) equation: H2O/(100-H2O)= intercept + slope * rWS rWS= (Area water peaks / Area silica peaks) of sample raman spectra intercept & slope are determined empirically through calibration with standa...
f36f74d6026ee3759e8b66c67d063447e7407684
672,568
def _clean_col_name(column): """Removes special characters from column names """ column = str(column).replace(" ", "_").replace("(","").replace(")","").replace("[","").replace("]","") column = f"[{column}]" return column
4f8bd6ae210629394e3b50702fc7134e4c4cc5bf
672,569
def italics(text: str) -> str: """Make text to italics.""" return f'_{text}_'
ea5a4474e3d7490c746fffd8edd74a7b8349a010
672,570
def data_range(x): """返回数据 x 的极差,即最大元素与最小元素的差""" return max(x) - min(x)
39169b924a127a4f808016be3534843e838b5bd3
672,571
def skyblock_auctions(): """ Returns SkyBlock auctions that are currently active in the in-game Auction House. This method uses pagination due to the amount of results returned. Each page will return up to 1,000 results. Parameters: `page` Example Response: ```json { "succes...
757f898a11b70aafef97e6e5dc1637933a764e87
672,572
import torch def prepare_batch(batch): """This is the collate function The mass spectra must be padded so that they fit nicely as a tensor. However, the padded elements are ignored during the subsequent steps. Parameters ---------- batch : tuple of tuple of torch.Tensor A batch of da...
8d762d7d5cf812ab8612854eb692b1ffd827713d
672,573
def return_all_from_table(table_name,conn,c): """ Return everything in this table """ cmd = "SELECT * FROM %s"%(table_name) c.execute(cmd) result = c.fetchall() return result
26a2f12f572fd7dd8707e412b562519c04564166
672,574
def getConstituents(jet, node_id, outers_list): """ Recursive function to get a list of the tree leaves """ if jet["tree"][node_id, 0] == -1: outers_list.append(jet["content"][node_id]) else: getConstituents( jet, jet["tree"][node_id, 0], outers_list,) ...
0524af18b2e0514392500d9425c5daef523106a0
672,575
import os def junit_fpath(output_path): """Returns the path to the jUNIT XML-file""" return os.path.join(output_path, "trun.xml")
b65c7750bc5bb01568d45c8ab204142283b04bbc
672,576
def reversed_list (seq) : """Returns a reversed copy of `seq`. >>> reversed_list ([1, 2, 3, 4, 5]) [5, 4, 3, 2, 1] >>> reversed_list ([1]) [1] >>> reversed_list ([]) [] """ result = list (seq) result.reverse () return result
effb925f734def5720364f14b97814279d79d161
672,577
def drop_samples_based_on_string(df,list_of_strings_for_QC_Blank_filter,column): """ drop samples based on string Args: pd dataframe list of string Returns: pd dataframe """ print(df.shape) for string in list_of_strings_for_QC_Blank_filter: df = df[~df[column]....
27cf17edeac8ae06801577727dd069b7d01440b9
672,578
import re def phone_format(n): """Return a pretty phone format The data warehouse send back 1234567890 we want 123-456-7890 :param n: a ten digit number to parse """ if n is None: return "" return re.sub(r"(\d{3})(\d{3})(\d{4})", r"\1-\2-\3", n)
9604fdd333757d46357a1aac83c568f0d406e44d
672,579
def grouper(some_list, count=2): """ splits a list into sublists given: [1, 2, 3, 4] returns: [[1, 2], [3, 4]] """ return [some_list[i:i+count] for i in range(0, len(some_list), count)]
9cd9f79a077b0cd64fd51dc0c6b4ea7ede2188fa
672,580
def parse_youtube_tag(text): """Replaces [youtube: id] tags""" video_id = text.group("video") return f'<div class="video-container"><iframe src="https://www.youtube-nocookie.com/embed/{video_id}" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe></div>'
94ecf50beaafa6badf17e9337c0b9b115afb4eef
672,581
def amdahls_law(p, s): """Speedup relative to proportion parallel Amdahl's Law gives an idealized speedup we can expect for an algorithm given the proportion that algorithm can be parallelized and the speed we gain from that parallelization. The best case scenario is that the speedup, `s`, is ...
355ad85403778c117a60fe30f523aaef5bb9f64e
672,582
import subprocess import time def get_slurm_deadline(): """ Returns the linux epoch at which this job will be terminated if run in a slurm environment. None otherwise. """ def slurm_seconds(duration): if '-' in duration: days, rest = duration.split('-') else: days = 0 rest = duration try: hours, m...
4d51e1545d3726e54e9365719cebbfaf89e5bb48
672,583
def choose_word(file_path, index): """ the function gets a string that represent a file path and a number represent index of a word in the file. the function return the secret word for the game :param file_path: the function gets wth words from this file :type file_path: string :param index: a number which is t...
12a1deb257dd31e400edca9382a8aed85c33991a
672,584
def _recur_flatten(key, x, out, sep='.'): """Helper function to flatten_dict Recursively flatten all nested values within a dict Args: key (str): parent key x (object): object to flatten or add to out dict out (dict): 1D output dict sep (str): flattened key separato...
344e1f5c89997fe188ca5857a72a4ad071eda941
672,586
def get_tti_v1(speed, def_speed): """ :param speed: 路段实际速度 :param def_speed: 路段期望速度 :return: tti """ if speed < 1e-5: speed = 0.1 radio = def_speed / speed max_radio = 5.0 min_radio = 1.0 if radio >= max_radio: tti = 9.9 elif radio <= min_radio: tti = ...
6daacb5cfaa11476f219fa002924713efd820a9d
672,588
import hashlib def calculate_digest(body): """Calculate the sha256 sum for some body (bytes)""" hasher = hashlib.sha256() hasher.update(body) return hasher.hexdigest()
11d6c4e9d331bc7ffb97118e707143bdee59bb04
672,589
import signal import errno def _settable_signal(sig) -> bool: """Check whether provided signal may be set. """ try: old = signal.signal(sig, lambda _num, _frame: ...) except OSError as e: # POSIX response assert e.errno == errno.EINVAL return False except ValueError...
a5efd821befd8dbde2a65757f713542f1be1f225
672,590
def u2t(x): """ Convert uint-8 encoding to 'tanh' encoding (aka range [-1, 1]) """ return x.astype('float32') / 255 * 2 - 1
f278fc1b8c6b408744766af28d78b2625dae890d
672,591
def compute_covariance(WW_n, wavelet, dj, dt): """Implemetation based on xarray input instead of numpy array Input: WW_n: real values of product of wavelet coefficients. """ scaling_factor = dj * dt / wavelet.C_delta return (WW_n / WW_n.scale).sum(dim='scale') * scaling_factor
6eb2059f49be798ae674925f6f8a6bbf4d05e5fb
672,592
def first_non_empty(data_or_instance, field_or_fields, default=None): """ Return the first non-empty attribute of `instance` or `default` :type data_or_instance: object or dict :param data_or_instance: the instance or the resource :type field_or_fields: str or tuple or list :param field_or_fiel...
9be9d7fddcfc3b71b92ca12fb8949d85ad4cb342
672,593
def get_tile_size(model_height, model_width, padding, batch_height, batch_width): """ Calculate the super tile dimension given model height, padding, the number of tiles vertically and horizontally :param model_height: the model's height :param model_width: the model's width :param padding: padding ...
6ad9781ebd4a6ca1326de9b7123b3d717e4bf615
672,595
def results_ok(api, flow_names, expected): """ Returns True if there is no traffic loss else False """ request = api.metrics_request() request.flow.flow_names = flow_names flow_results = api.get_metrics(request).flow_metrics flow_rx = sum([f.frames_rx for f in flow_results]) return flow_...
3cea3d4b1ee6b799a1e4941e2ae015b38119c03c
672,596
def sample() -> bool: """ sample process. """ return True
d65fa285d60cde818d9e11ffdba8a2f4cc38b510
672,597
import os import subprocess def try_call(command, quiet=False): """Try to call the given command.""" try: print('Calling {0}'.format(command)) f_null = open(os.devnull, 'w') if quiet else None return subprocess.check_call(command, stdout=f_null, ...
5d22a02bb3ae842f2abccd7bedf96c64fbe6eef6
672,598
import torch def ndc_to_screen_points_naive(points, imsize): """ Transforms points from PyTorch3D's NDC space to screen space Args: points: (N, V, 3) representing padded points imsize: (N, 2) image size = (height, width) Returns: (N, V, 3) tensor of transformed points """ ...
d8b361b8dca2c89aef6988efcae67e9554f1dae8
672,599
def k8s_api_response(): """ Return an object that looks like an API response from Kubernetes. """ class FauxK8sResponse(object): def to_dict(self, *args, **kwargs): return {} def _make_response(): return FauxK8sResponse() yield _make_response
36f8ab3cbb3f16cc3c7e2284fd937ab150f40d98
672,600
def dec(text): """ Create a declarative sentence """ formatted = '%s%s.' % (text[0].capitalize(), text[1:len(text)]) return formatted
a6003e54e2edc9443cbc7c28afd9795582719b7a
672,601
def normalize(qualName): """ Turn a fully-qualified Python name into a string usable as part of a table name. """ return qualName.lower().replace('.', '_')
3f87366a595451dc43e8c0392cac4eae03b10e64
672,602
def load_language_modeling(from_path: str) -> list: """Load language modeling dataset. """ dataset = [] with open(from_path, 'r', encoding='utf-8') as reader: for line in reader.readlines(): dataset.append(line.strip()) return dataset
528466c259757bea4e1893e3b0fc3a684b75a3eb
672,604
def merge_sort(alist): """list -> list sorted from least to greatest """ print("Splitting ", alist) if len(alist)>1: mid = len(alist)//2 lefthalf = alist[:mid] righthalf = alist[mid:] merge_sort(lefthalf) merge_sort(righthalf) i=0 j=0 ...
8fc0b398ce2853d7a45117fddd91d17d08bccef7
672,605
def num_to_str(num): # type: (None) -> str """Number to string without trailing zeros""" s = str(num) return '0' if s == '0' else s.rstrip('0').rstrip('.')
1d326ad885797bb69ca961994d93d1ec7f730208
672,606
import base64 def base64_encode(inputStr): """ Encode strings in Base64. Internally, it is encoded by converting it to a byte sequence once, and then decoded into str. Parameters ---------- inputStr : str String to be encoded Returns ------- _ : str encoded string...
76075cd54b22c5abe070dae8e8d149688684e0d9
672,607
import os def get_git_tag(): """ Return current git tag. """ return os.popen("git describe --tags --abbrev=0").read()
3eb0f12090a39ef2946092b96d087e3f7f3d0445
672,608