content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def doNestedGroup(indata, group_key_func, group_element_func=None): """Group the indata based on the keys that satisfy group_key_func (applied to the value) Return a dict of dictionaries created by group_element_func Each each value of the dictionaries returned by group_element_func must be a dictionary...
e7aa3b29a7bb743e7bc57d0e22e8f6887f92d152
642,317
import typing import math def generate_servers(size: int) -> typing.List[str]: """Generates a list of servers randomly generated.""" fill = math.ceil(math.log(size, 10)) return ['workstation' + str(i).zfill(fill) for i in range(size)]
7d5f652b01c72d5c77a875d8769f4cf399342eee
642,318
import os def check_present_and_executable(subdir, filenames): """ Checks that all the files in the list are present in the subdirectory and are executable. Returns a list of any files in the list that are not present or not executable. """ invalid = [] for filename in filenames: p...
d2137dc042d28d81fe2897c572526ccbd933221e
642,319
def get_vector_length_squared(carla_vector): """ Calculate the squared length of a carla_vector :param carla_vector: the carla vector :type carla_vector: carla.Vector3D :return: squared vector length :rtype: float64 """ return carla_vector.x * carla_vector.x + \ carla_vector.y ...
ee612d94c20441c88beea13b8091e62cc94cfce1
642,320
import argparse def parse_args(): """ Auto Dialogue Evaluation Config """ parser = argparse.ArgumentParser('Automatic Dialogue Evaluation.') parser.add_argument( '--do_train', type=bool, default=False, help='Whether to perform training.') parser.add_argument( '--do_val', type=b...
7c2a72f3030995b65b5d22b87931dc9da0f6660a
642,321
def dmp_to_trajectory(dmp, x0, g, gd, execution_time): """Computes trajectory generated by open-loop controlled DMP.""" dmp.set_meta_parameters(["x0", "g", "gd", "execution_time"], [x0, g, gd, execution_time]) return dmp.trajectory()
68348fb041abc02b516393d09735cb845ca32e67
642,322
def version_str(version_info): """Format the python version information""" return "{}.{}".format(version_info[0], version_info[1])
3f7ba3c140e25eec4e128ec689cf2050ef4fb952
642,323
def fibonacci(number): """ Returns True if number is fibonacci """ if number == 1: return True f1 = 1 f2 = 2 while f2 < number: f3 = f1 + f2 f1 = f2 f2 = f3 return f2 == number
8e3da3452726716ebc461d7dc461acf0b6d513e5
642,324
def row(): """Build a row of pdf statement data parsed in stream mode.""" return {"extraction_method": "stream", "top": 0.0, "left": 0.0, "width": 0.0, "height": 4.1, "data": []}
60506c1cdfa79c3f46274198d9b5b6f1c80d524d
642,326
from typing import Set from typing import Dict def _sorted_value_indices(values: Set) -> Dict[str, int]: """Converts values to a Dict mapping to unique indexes. Values will be sorted. Example: >>> _sorted_value_indices({"b", "a", "c", "a"}) {"a": 0, "b": 1, "c": 2} """ return {va...
d6141d77e006b4bdca09f541f014624bc1e0b0fa
642,328
def writeTerm(index): """ Writes the basis function term with the given index """ global coeffs coeffs = [] eqtn = "" term_index = 0 for i in range(1, 9): for j in range(1, 13): # 12 term_index += 1 coeffs.append([i, j / 8.0, 0]) if index == t...
af74f220a61a380373be63ca3b184d9bcce0340a
642,329
import requests import json def isdisambiguation(pagename): """Given a wikipedia page name, returns True if that page is a disambiguation page and False otherwise :param pagename: The name of a wikipedia page :type pagename: String :return: True if pagename is the name of a wikipedia page in...
466d481523b4e86a4562644798047a9a4544cab9
642,330
def fmt(s): """Formats rules with common patterns""" s = s.replace('{org}', r'(?P<organization_slug>[^\/]+)') return s
10106a49c53929b93dbe88c70507c61330cc6709
642,331
def get_column(A, j): """获取列""" return [A_i[j] for A_i in A]
26e030a26a7bc6487a7d103644a6be2f0403317f
642,332
def _strip_lines(latex_string): """Strip Lines in Latex Source Arguments: latex_string {string} -- LateX Source Returns: string -- Latex with lines striped """ lines = latex_string.splitlines() result = [] for line in lines: result.append(line.strip()) return "\...
cc812db77ace6ca62a1ed88c5c59a4c02ead6fa8
642,333
def lire_noms_equipes(noms_equipes, ne): """Lire le contenu du fichier ayant les noms d'equipes et renvoyer la liste des noms lus par ordre. Si le nombre d'equipes lu est inferieur que ne, ajouter automatiquement les noms manquants""" if not noms_equipes: return [f"Equipe {e}" for e in range(ne)] noms = [] comp...
31f25a6870e0f52f7494b4c536fddc40d37f97e4
642,334
def f(x): """ int -> int """ print(x) return x
dc946d668ae4f6bb88966bbbd349293fc95376eb
642,335
def map_traps(prev_pat, row_limit): """Work out the number of safe tiles in a trapped room.""" safe = prev_pat.count('.') row = 1 while row < row_limit: next_row = '' trap_patterns = ('^^.', '.^^', '^..', '..^') pattern = '.{}{}'.format(prev_pat[0], prev_pat[1]) if patte...
f93033e510976f86cca5693a81efe17c68d823a1
642,336
def ms_to_seconds(time: float) -> float: """ Convert milliseconds to seconds. Parameters ---------- time : float A ``float`` of time in milliseconds. Returns ------- float Returns a ``float`` of the converted time in seconds. """ return round(time / 1000, 3)
4dbaf2e3d3680f41c71ddab1c1e7917154f40be1
642,337
def extract_eq(data, col, value): """ extract all rows from the data table where the values of the column = value data must be a 2d matrix: shape: (rows, columns) col1 col2 col3 ... row1 row2 row3 ... """ mask = ((data[:,col] == value) *...
5a64b85758fdf84f74cb79613e9030f34ac65582
642,338
def _calc_predictability(allowable_designs, threshold): """calculate how many designes are classified as predictable for a given threshold on 'p_chose_B' """ highly_predictable = (allowable_designs["p_chose_B"] < threshold) | ( allowable_designs["p_chose_B"] > 1 - threshold ) n_predictable =...
83cb9148cad368de1b40d5c04644c82fb5c8a835
642,339
def list_spatial_correlators(): """ list the abbreviations of the different implemented correlators, being: norm_corr - normalized cross correlation cumu_corr - cumulative cross correlation sq_diff - sum of squared differences sad_diff - sum of absolute differences max_like -...
438ef9215aa9fb8da8e1e3777a43bf4224f7cb13
642,340
def GetMissingGuests(sMissingGuestsFileName): """Load missing guest data. [sMissingGuestsFileName]: string, missing guest file name. <retval>: """ with open(sMissingGuestsFileName,"r") as fResults: lsResults= [sLine.strip().split("\t") for sLine in fResults.readlines()] dtResults={} for lsResult in lsResults:...
5f9f2fefea2e17d2346e61f3d0109b2bbf6c95f3
642,341
def check_for_wrong_schema(error): """ Checks if column does not exist """ return "UndefinedColumn" in str(error)
0ff17e4f19b5ad2827c2fd7b3c7ebf1a717f900f
642,342
import configparser import os def read_config_file(project_name: str) -> configparser.ConfigParser: """Find and load the ini file It maybe in the current directory or it's parents depending on project structure. If a .local. version is found, use that fires """ base_dir = os.path.dirname(__file_...
ab64f303ee8613ea76773c3b7db40a2a4b104d67
642,343
import time def convert_epoch_to_date(epoch, short=True): """Evernote timestamps are *miliseconds* since epoch, so we strip off the last 3 zeros""" #time.strftime("%a, %d %b %Y %H:%M:%S %Z", time.localtime(epoch)) epoch_seconds = epoch / 1000 if short: time_str = time.strftime("%b %d", time.localtime...
61a743066ec88faa4daf195a1324f8bab66bc78b
642,344
def get_stat_output(args, first_year, stats_dict, top_words, data_list): """ Function to format output statistics for one subset of corpus between first_year and first_year + args.year_split. input: args (argparse object): input arguments first_year (int): start year...
179718c83cfd165be58da5c2ae90394f9f92e48c
642,345
def parse_response_number(response): """Handles the parsing of a string response representing a number (no decimal) All responses are sent as strings. In order to convert these strings to their python equivalent value, you must call a parse_response_* function. Args: response (str): respon...
f62b2221c41335ad8d988449634a429ff1433a67
642,346
import os import subprocess def call_lsof(): """ Call lsof and return the result as one big string """ env = os.environ.copy() if "LANG" in env: del env["LANG"] # See OUTPUT FOR OTHER PROGRAMS: http://linux.die.net/man/8/lsof # Output lines can be in one of two formats: # 1. "...
d1065a97a72e0e985a625cb67690ef6d5ffb6aeb
642,347
import base64 def base64_from_hex(hexstr): """ Returns the base64 string for the hex string specified :param hexstr: The hex string to convert to base64 :return: The base64 value for the specified hes string """ return base64.b64encode(bytes(bytearray.fromhex(hexstr))).decode("utf8")
5d457d08ed47356073bd2238699b65a3c3037df3
642,348
def calcite_production(vs, plankton, DIC, calcite): """Calcite is produced at a rate similar to detritus Intended for use with a smoothing rule If explicit tracking of calcite is desired use rules for the explicit relationship """ # changes to production of calcite dprca = (vs.mortality[pl...
d105a99684fe53a5fc5a61eeb6423abbcc546b7f
642,349
import math def power_digit_sum_simple(base=2, power=1000): """Simply finds the power using Python's math.pow. Note that a lot of languages do not support such large numbers.""" result = int(math.pow(base, power)) summation = 0 while result > 0: summation += result%10 result /= 10 return summation
70bf1af34da0abd6f7b2303a44b5437cb31b0846
642,350
import csv def get_entries(): """Return all entries from csv file""" with open("entries.csv", newline="") as csvfile: csvreader = csv.DictReader(csvfile, delimiter=",") entries = list(csvreader) return entries
eb40b3aed65d31c1baf051de7ea2321863cbe0fc
642,351
def __dict_replace(s, d): """Replace substrings of a string using a dictionary.""" for key, value in d.items(): s = s.replace(key, value) return s
0377e3deced100e64ae73e5dcb1c7fd583a19f54
642,352
from typing import Union from typing import Sequence import torch from typing import Mapping def to_device(inp: Union[Sequence[torch.Tensor], torch.Tensor, Mapping[str, torch.Tensor]], device: Union[torch.device, str], detach: bool = False, **kwargs) -> \ Union[Sequence[torch.Tenso...
0cfda6e2e9cdd3b275145f49efd18afd34ad60b6
642,354
def getNeighbors(node, graph, start, end): """ Find all the vertex reachable from the current node and the respective cost of the paths updated Parameters: node (int): the current node graph: the graph we are working on start (string)...
7ad05e47f7184feb821969d92caf8159184c46c7
642,355
def base10toN(num,n): """Change a to a base-n number. Up to base-36 is supported without special notation.""" num_rep={10:'a', 11:'b', 12:'c', 13:'d', 14:'e', 15:'f', 16:'g', 17:'h', 18:'i', 19:'j', 20:'k', 2...
e1c8d89a9b9867316b966a0308566056a0f67137
642,356
import os import platform def get_salt_file() -> str: """Returns the location of the salt file used for cryptography. On Unix systems the salt file is at `/var/secure/robocrypt.salt`, and on Windows the salt is at `C:/secure/robocrypt.salt`. If a custom salt is specified in the environment variable `ROBO_SAL...
76e1827f7a3b869d8530d0b1d416206c1a3d49ce
642,358
def getArrayIndicesForParityEncoding(key): """return a tuple with 2 items, corresponding to the indices to encode parity in/ the indices parity is encoded in""" firstBit = 0 secondBit = 0 #cases for the possible values of key if key == "0": firstBit = 0 secondBit = 1 elif key == ...
51e54d226723b154a9ae117a9292e04aa71a406a
642,359
def _library_paths(): """Returns hard-coded set of relative paths to look for library files.""" return [ "", "lib64", "lib", "lib/*-linux-gnu", "lib/x64", "extras/CUPTI/*", ]
6c00697c8cd58378ce470760753164985488dea4
642,360
def K(A,L=None): """ Function we are trying to maximize: sum_{i<j} A[L[i]][L[j]] A is m x m matrix, L is a subset of range(m) (or defaults to range(m) if no L given) """ if L==None: L = range(len(A)) return sum([A[L[i]][L[j]] for j in range(len(L)) for i in range(j)])
de8c83c695a8262131b4bef707d48255a3be89de
642,361
import argparse def parseLossArguments(choices, help): """ Creates a custom type for loss parsing, it overrides the type, choice and help of add_argument, in order to properly extract the loss type, and still be able to print the choices available. Example: in: 'autoencoder:1:10' (loss:weight:stat...
6028d9d79afe195756eb51bb070f71d263c60be4
642,362
import os import time import logging def log_configuration(verbose): """Logger configuration: time/date formatting. """ os.environ["TZ"] = "UTC" # Windows doesn't support tzset. Ignore for now. try: time.tzset() except AttributeError: pass if verbose: logging.ba...
39a00448d92d2040bada62c4526e56cf2c669f98
642,364
def big_vote_power(karma): """See https://github.com/LessWrong2/Lesswrong2/blob/devel/packages/lesswrong/lib/voting/new_vote_types.ts for the vote power implementation. See also the blog post at https://lw2.issarice.com/posts/7Sx3CJXA7JHxY2yDG/strong-votes-update-deployed#Vote_Power_by_Karma""" if k...
783b23bb5f0ab96492a3cf56bd2359c6e5fe54b2
642,365
def degree_to_DMS(degree): """Convert from plain degrees format to DMS format of geolocalization. DMS: "Degrees, Minutes, Seconds" is a format for coordinates at the surface of earth. Decimal Degrees = degrees + (minutes/60) + (seconds/3600) This measure permit to gain in precision when a degree...
e1acc43c4bf667df904b4d4d16e948b0dce40ec9
642,366
import math def test1(x): """ >>> %timeit test1(123456) 1000000 loops, best of 3: 381 ns per loop """ return math.sin(x)
9fea76170c2e12b287089b09d9268df212c0c75d
642,367
def safe_str_cmp(a, b): """Compare two strings in constant time.""" if len(a) != len(b): return False r = 0 for c, d in zip(a, b): r |= ord(c) ^ ord(d) return r == 0
aa3ab9ca592cba926d3cdb94e1273825401119ac
642,368
import os def find_iso_path_in_cwd(log, host, iso_path_pattern): """ Find iso path in current work directory """ command = ("ls %s" % (iso_path_pattern)) retval = host.sh_run(log, command) if retval.cr_exit_status: log.cl_error("failed to run command [%s] on host [%s], " ...
da84b68bef43f4d44468cb62e4d3fe68819a4676
642,369
def try_multi(method, repeats=5, default_value=None, **kwargs): """ Will attempt to call method a number of times, returning the results if successful. """ for i in range(repeats): try: return method(**kwargs) except Exception as e: pass return default_val...
4d57dda210bd63d3031b016b21dc8e54814fbb35
642,370
import torch def prod_matrix(pts_src: torch.Tensor, pts_dst: torch.Tensor): """ Returns the matrix of "x_i * y_j". :param pts_src: [R, D] matrix :param pts_dst: [C, D] matrix :return: [R, C, D] sum matrix """ x_col = pts_src.unsqueeze(1) y_row = pts_dst.unsqueeze(0) return x_col * ...
e4dbceedfb489f101ea9e65c1d6e2a3aaf8fbb89
642,371
def source_page(is_awesome) -> str: """ Returns an awesome string Args: is_awesome (bool): is SourcePage awesome? """ if is_awesome: return f"{is_awesome}! SourcePage is awesome!" return f"{is_awesome}! Nah, SourcePage is still awesome!"
49f3931e38179ce1b52d200a52b221bf4fc8caba
642,373
import math def _pad(text, block_size): """ Performs padding on the given plaintext to ensure that it is a multiple of the given block_size value in the parameter. Uses the PKCS7 standard for performing paddding. """ no_of_blocks = math.ceil(len(text)/float(block_size)) pad_value = int(no_...
d5334e05924c2221c539d92e819e2188074faac8
642,374
import math def distance(pt_a, pt_b): """ Calculate distance between 2 points. @params: pt_a: (x, y) pt_b: (x, y) """ return math.sqrt((pt_a[0] - pt_b[0])**2 + (pt_a[1] - pt_b[1])**2)
f8f655d683011eb3161daf871f6158d8a91563ce
642,375
def parse(words): """ Stores the words frequency """ counts = dict() for word in words: if word in counts: counts[word] += 1 else: counts[word] = 1 return counts
0d31557d512e02d14ae1813b5659b846eb5dea06
642,376
import os def get_event_dir(base_dir: str, event: int): """ Given event and base directory return event directory :param base_dir: base directory :param event: event number :return: directory with files associated with given event """ return os.path.join(base_dir, 'event_{}').format(event)
5374a761b91f7356deb1c01a0889d8f0cadc9590
642,377
import torch def compute_returns(rewards, masks, discount, returns4traj=True): """ Using rewards to compute returns. :param rewards: rewards agent obtains per step. Size: batch_size x 1 :param masks: indicate the final step of each trajectory. 0 for last step and 1 for others. Size: batch_size x 1 ...
6817d26464b7b04d123a1b6e5d17179d0ba3a37d
642,378
def min_coins(coins, total): """ Computes the minimum number of coins which sum up to total. Params: coins: list of non-negative integers representing the values of the coins. total: int, in fact it has to be a non-negative integer. Returns tuple: (min_num_coins, picked_coins) ...
9630e851e5a2b8af24c5e557645913a340e0c5e0
642,380
def offset(coordinates, offset_scales): """Apply offsets to box coordinates # Arguments coordinates: List of floats containing coordinates in point form. offset_scales: List of floats having x and y scales respectively. # Returns coordinates: List of floats containing coordinates i...
7b70fead737c771f224dcff073fb76676134d76e
642,381
def getNumberOfMatches(segment): """ Get numnber of matches from alignment Do not consider insertion/deletion as mismatches """ parsed_MD = segment.get_aligned_pairs(with_seq=True) return len([ base for (read_pos, ref_pos, base) in parsed_MD if ((base is not None and base.isuppe...
61bb0170e1f10f2f9721b5441516e7accb29345d
642,382
def _cli_options(parameters): """Return command line options for parameters passed as AiiDA ArrayData """ arrayname = parameters.get_arraynames()[0] dVarray = parameters.get_array(arrayname) # array of volume change in %: -6, -2, ... ndV = 0 # number of non-zero volume changes options = '' ...
51274ccd0cb1980b08286980073efff3f0632461
642,383
def _set_form_values(xmpp, room, form=None): """Creates/Updates an XMPP room config form""" if form is None: form = xmpp.plugin['xep_0004'].make_form(ftype='submit') form.add_field('FORM_TYPE', value='http://jabber.org/protocol/muc#roomconfig') form.add_field('muc#roomconfig_publicroom',...
658548b1556a2c1776a9b289c725f073c080c1f4
642,384
def get_order_by_querytring(ordering, current_order=None, remove=False): """ Using the ordering parameter (a list), returns a query string with the orders of the columns The parameter current_order can be passed along to handle the specific order of a single column. So for example if you are orderi...
bea3175099737fc57cb80567ba192e4be42af1b0
642,385
import re def replace_pattern(pattern_string, replacement, in_value): """Returns the regex replaced value.""" return re.compile(pattern_string).sub(replacement, in_value)
23c49ce7cfb236751dc8c1a4207f938cd36f532a
642,386
import numpy def padded_extension(values_in, n, fill_value): """ Forces values_in to be at least length n by appending copies of fill_value as needed :param values_in: scalar or 1D iterable :param n: int :param fill_value: scalar :return: 1D array with length >= n """ x = numpy.atle...
35b73de8d757b67722e5dec49e737ddd4ad43b21
642,387
def get_action_by_name(client, cluster, name): """ Get action by name from some object Args: client: ADCM client API objects cluster: cluster object name: action name Returns: (action object): Action object by name Raises: :py:class:`ValueError` ...
9089b2e5d5b5b131eea0ddd9a16dace9decc5905
642,388
import aiohttp async def search_wikipedia(term): """Search Wikipedia for a given term""" url = 'http://en.wikipedia.org/w/api.php' params = {"action": 'opensearch', "search": term, "format": 'json'} print("TRYING:", term) async with aiohttp.ClientSession() as session:...
16b5324131824a9015d30828d6c87f4b957823a3
642,389
def remove_title(text): """ Removes the title of a document :param text: text containing an article output from cleanhtml() :return: text of the article without title """ index = text.find("\n\n") if index != -1: return text[index+2:] else: return text
ff1364dce525eb8007381c9b4b51b26fcb24a07f
642,390
def _s(strs): """ Convert a byte array to string using UTF8 encoding. """ if strs is None: return None assert isinstance(strs, bytes) return strs.decode('utf8')
f437ff006c50184d3853f5a4d317c4ef3a761d2c
642,391
def _time2dict(time): """Convert PaStreamCallbackTimeInfo struct to dict.""" return {'input_adc_time': time.inputBufferAdcTime, 'current_time': time.currentTime, 'output_dac_time': time.outputBufferDacTime}
8ac1feab267d8d3a852fbb29f4692d39f8fe73ac
642,392
def format_traits(code, value): """Format traits as list of names. """ result = [] for trait in code: if value & code[trait]: result.append(trait) result.sort() return ','.join(result)
0e8db29db14f6f6918e983c8a461b193b92776a1
642,393
def solution_one(numbers: list[int]) -> list[int]: """ timeComplexity: BigO(n^2) spaceComplexity: BigO(n) """ result = [] for idx, i in enumerate(numbers): tmp = 1 for idj, j in enumerate(numbers): if idx == idj: continue tmp *= j ...
0f7ae0b8e396d5505b0eeaab9cd4e6ea54a76409
642,394
def _get(node, nodeId, nodeAttrs=('id','class','model','pattern')): """ (internal) Get a node with the specified C{nodeId} as any of the C{class}, C{id} or C{pattern} attributes. """ if hasattr(node, 'hasAttributes') and node.hasAttributes(): for nodeAttr in nodeAttrs: if (str (...
a86b983289126f75aee71f6cd5c261a700716bc8
642,395
from typing import Any def int_from_str(arg: Any) -> int: """Take in an argument and try to return its int equivalent. Args: arg (Any): This can be any type. However, in general use it should be either an int or str. Returns: int: The int equivalent of the passed in argument. I...
b64a5744847c566edddc98d1aad1e793f641eca3
642,396
def view_query (db, userid, itemid) : """ Users are allowed to view their own and public queries for classes where they have search permission """ q = db.query.getnode (itemid) if not q.private_for : if not q.klass : return False prop = db.getclass (q.klass).labelprop...
6c18129e2e5eff45eac1bb26454ff65348dc5dd5
642,398
def parse_to( buffer, keyword ): """Continues through the buffer until a line with a first token that matches the specified keyword. """ while True: line = buffer.next() if line == '': return None values = line.split( None ) if values[ 0 ] == keyword: ...
749e3436a84eff879e602c886ad11fd5a6c1e94e
642,400
def getWordFrequency(words: list) -> dict: """ :Return: dictionary with word and count """ dici = {} for word in words: if word in dici: dici[word] += 1 else: dici[word] = 1 return dici
b0871de6ae76d7540dc14f9a8092ee9ff3abc8a9
642,401
def StripBuiltinMessages(messages): """Strips the builtin messages.""" assert len(messages) >= 2 return messages[2:]
aac22cdb5911821e852ff45abdb3623f84a5c855
642,402
from functools import reduce def partition(predicate, iterable): """ splits the items in iter into two partitions based on predicate() outcome True --> into first list of returned tuple False --> into second list """ def split(parts, item): parts[int(not predicate(item))].append(i...
2445cfc2fc125f5a5ccfcb4dbfbaaef050598ecb
642,403
import requests def check_ifup(url): """ Desc : Function checks if the URL is UP? by checking the return status for the request head call. param : URL return : true if site is down false if site is up """ return requests.head(url).status...
0e94ea6654fc762a7cbb31625c8eba9dfa662af8
642,404
def __is_forbidden(scope, endpoint): """是否禁止的""" return endpoint in scope.forbidden
8d454f623ecb08bde7fd547f20f32bda4d1e0e3c
642,405
def returnPreds(preds, threshold): """ Return predicted binary values from prediction probabilities based on a given threshold Inputs: - preds: prediction probabilities - threshold: threshold for positive prediction value Output: - predicted_labels list of binary predicted labe...
7b8d606dc4ff0be8966dea1d26621d6ef3c07230
642,406
import numpy def generate_tiles(samples, lines, xtile=None, ytile=None): """ Generates a list of tile indices for a 2D array. :param samples: An integer expressing the total number of samples in an array. :param lines: An integer expressing the total number of lines in an array. ...
886ca0fea1cb74b6b04c26f1462101cc77d9fb7f
642,407
import re def validate_url(url: str) -> bool: """ Convenience function to check whether the given URL is valid or not. (regex validation) :param url: URL to check validation :return: bool """ print(re.search(r"[^a-zA-Z]|\d|[^\-._~:/?#[]@!\$&'\(\)\*+,;=]", url)) return url.startswith( ...
e8c3b6d1ea6f131db99f9459601c97317dde4d54
642,408
def solve2(lines): """Solve the problem.""" nlines = len(lines) nch = len(lines[0]) result = [] for ich in range(nch): ids = [line[:ich]+line[ich+1:] for line in lines] if len(set(ids)) < nlines: ids.sort() for v1, v2 in zip(ids[:-1], ids[1:]): ...
5995084e7f96683cfedeefadeb98e11bb05761ad
642,409
def validate_security_group_rule_operation(session, row): """Validate security_group_rule operation based on dependencies. Validate security_group_rule operation depending on whether it's dependencies are still in 'pending' or 'processing' state. e.g. """ return True
a1459592b3325c6dba68fea254a9543e2d7c4046
642,410
import uuid def __search_uuid_sql(p_uuid_list: list): """ Формирует запрос поиска по метаданным с помощью uuid :param p_uuid_list: список uuid объекта/объектов метаданных """ l_sql=" AND id IN (" for i_uuid in p_uuid_list: uuid.UUID(i_uuid) # проверка на корректный uuid l_sql=...
247bff296faa4811c6818d15fdbbdb7af3c09579
642,411
def publish_devices(path_list, *_, **__): """ Returns paths as "--device" or "--mount" arguments. Fall back to "--privileged" if no devices found. Args: path_list (str): List of devices paths, one path per line. Returns: str: arguments """ return ' '.join( f'--devi...
30b6576b6f3407bb84530977199c5be6f46c47ad
642,412
import hashlib def hashtext(stringText): """Return a string with first 16 numeric chars from hashing a given string """ #hashlib md5 returns same hash for given string each time return hashlib.md5(str(stringText).encode('utf-8')).hexdigest()[:16]
01b8a553ed6a8db309594138cb4393f7601999c8
642,413
def flatten(x): """flatten x.""" # [batch, heads, h,w, ch/h] # [batch, heads, length, channels], length = d*h*w l = x.shape[2] * x.shape[3]*x.shape[4] # [batch, heads, length, channels], length = d*h*w x = x.view(x.shape[0], x.shape[1], l,-1) # print('flatten shape', x.shape) retu...
d6423a3050b27888d171738881b61e36e5bc4752
642,414
def format_address(*, ip_address, port, protocol): """ Format address """ port = f':{port}' if port else '' return f'{protocol}://{ip_address}{port}'
1ede426ec7d88a3207cb41dba4b1c2376cf4e1c5
642,415
def get_equipment_slot_string(equipment_item) -> str: """ This function is called specifically for the print_character_equipment function in information_printer.py Returns the string representation of an Equipment object or returns empty if there is no such item. """ if equipment_item: retur...
48fefe9f83056dff37f32c0841b1c55d4fe8b705
642,416
import warnings def _warn_for_empty_labels(): """Helper for missing ground truth sets""" warnings.warn("Empty ground truth set! Check input data") return 0.
1a179f456d630e2b3578e1f54df66fe995b09833
642,417
from time import strftime,localtime def datestring(seconds): """Format time in seconds since 1 Jan 1970 00:00 UST as local time string in the format '1-Jan-70 00:00:00'""" return strftime("%d-%b-%y %H:%M:%S",localtime(seconds))
e656b4c27236a4813c02c9e8d29d94b45b39644b
642,418
import torch def get_maximum_similarity_word(phrase_embedding_t, maximum_similarity_box_t): """ Return the embedding of the word with maximum similarity wrt given box similarity. The box similarity is a tensor where each entry represents the maximum similarity of a word wrt bounding box's class for e...
69b75d08da959dfd3b4f2cc0fe9eec1013e37503
642,419
def left_canonical_form_mps(orig_mps, chi=0, threshold=1e-14, normalise=False): """ Computes left canonical form of an MPS See also -------- Tensor.left_canonise() """ mps = orig_mps.copy() mps.left_canonise(chi=chi, threshold=threshold, normalise=normalise) ...
22c3f997ba3b83a3d592b816f02cb4464ec72ef1
642,421
def as_dict(language_object): """ Get a dict representing a language """ # Previously we had a list of ISO_639_2b (bibliographic) languages in datasets.py represented e.g. # [u"wel", u"cym", u"cy", u"Welsh", u"gallois"] - now we have pycountry, so we favour the bibliographic name when # available. Frenc...
d3b3bd81ceb771abdfb9970bd87f916c4c1cdf02
642,422
def has(name, o): """Returns whether or not an object has an own property with the specified name""" if hasattr(o, str(name)): return True try: o[name] return True except (TypeError, KeyError): return False
066854da62cacb8aa739c8efcf6fcb69382c028c
642,424
def all_equal(elements): """ :param elements: A collection of things :return: True if all things are equal, otherwise False. (Note that an empty list of elements returns true, just as all([]) is True """ element_iterator = iter(elements) try: first = next(element_iterator) # Will throw ...
d4756b30603300e2021073fbe75740b82f66f644
642,425
def poseidon_mix(state, M, p): """ The mixing layer is a matrix vector product of the state with the mixing matrix - https://mathinsight.org/matrix_vector_multiplication """ return [ sum([M[i][j] * _ for j, _ in enumerate(state)]) % p for i in range(len(M)) ]
642e14e005c66d60214b87fa6c723f0cb3cb39d6
642,426
def _get_physical_table(api, *, table_id: str) -> str: """ Returns the physical table name for a given GUID. """ r = api._metadata.detail(guid=table_id, type='LOGICAL_TABLE').json() return r['logicalTableContent']['physicalTableName']
964cf16af34bcc134b9ee188427c7f34dc1e138e
642,427