content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def darpaNodeNet(node_id): """Return IP subnet of radio node on DARPA's network.""" return '192.168.{:d}.0'.format(node_id+100)
b0d0b5c2271f48b908a62850fbfbfcb514d1ccd1
659,593
from sympy.stats.stochastic_process_types import StochasticProcess def sample_stochastic_process(process): """ This function is used to sample from stochastic process. Parameters ========== process: StochasticProcess Process used to extract the samples. It must be an instance of ...
600f3f7a4eba48075966cbf28b83bf1bfc564339
659,597
def make_title(passage_name, process=True, line_end=''): """Make a valid page header from a name""" passage_name = passage_name.lower() if process else passage_name return f':: {passage_name}{line_end}'
c148285fc49a32bf612f32eeb98671aaf4c1ab8a
659,601
def challenge(authentication, realm): """Constructs the string to be sent in the WWW-Authenticate header""" return u"{0} realm=\"{1}\"".format(authentication, realm)
18b5e4f5f142fa3d6311b9a9af59bc910e38c999
659,603
def timesteps(paths): """Return the total number of timesteps in a list of trajectories""" return sum(len(path.rewards) for path in paths)
dcbe20ccb04efdaba786e171d02fc91ebe87867d
659,604
def flag_to_list(flagval, flagtype): """Convert a string of comma-separated tf flags to a list of values.""" if flagtype == 'int': return [int(_) for _ in flagval.split(',') if _] elif flagtype == 'float': return [float(_) for _ in flagval.split(',') if _] elif flagtype == 'str': ...
7c9376d17d47d6220c32690240652a3c4b52d6a5
659,606
def get_open_pull_requests(repo=None, base=None): """ retrieve open pull requests from specified repository :param repo: :param base: :return github.PaginatedList.PaginatedList """ if not repo: raise ValueError("you must provide repo") if not base: raise ValueError("yo...
da25581c6e1abf00c67c9461232b63bf83b305e5
659,607
def is_prolog_functor(json_term): """ True if json_term is Prolog JSON representing a Prolog functor (i.e. a term with zero or more arguments). See `swiplserver.prologserver` for documentation on the Prolog JSON format. """ return ( isinstance(json_term, dict) and "functor" in json_term and "ar...
b3435672520b2be45e2194a016f73b987d3e1dc6
659,609
def get_cmd_param(command, input): """return word after command if input starts with command, otherwise return None""" cl = command.lower() il = input.lower() n1 = len(command) n2 = len(input) if n1 > n2 or not il.startswith(cl): return None # it is not command return input[n1:].lstrip()
06f79d115cec1be0421e4ca63cdc74fb147c82f5
659,610
from pathlib import Path def make_file(dir: Path, f: Path): """outputs a file in a dir using the current file features""" output = dir / (f"{f.stem}_cookies{f.suffix}") if not output.exists(): output.touch() return output
39ede7a7622451709a8b7bb53e7b18e10e227306
659,619
import linecache def checkline(filename, lineno, ui): """Return line number of first line at or after input argument such that if the input points to a 'def', the returned line number is the first non-blank/non-comment line to follow. If the input points to a blank or comment line, return 0. At ...
acdcc76a91e7882a0a836e2783847e23deb1f84b
659,623
def _is_none(arg): """Check if argument is None.""" return arg is None
bc8a02871d2d52db1f031d4ea354edfd1728c5b7
659,625
import re def _match_trainid(value): """Return the trainID in value, None if no trainID.""" mat = re.search(r"TR(\d{4})", value) if mat is not None and len(mat.groups()) > 0: return mat.groups()[0] return None
be5676b31ead30e6220bbde0058ef63110f0a53c
659,627
def argument_parser(input_args): """ Returns a list of tokens for a given argument :param input_args: input string :return: argument list """ arguments = input_args.split(' ') if len(arguments) > 1: return arguments[1:] else: return arguments
8c3256ac7760b67ef00928beb54026788d3159bd
659,631
from typing import List from typing import Dict from typing import Any def _add_conditions(hyperparameters: List[Dict[str, Any]]) -> List[Dict[str, Any]]: """Returns a list of conditions in a format that is compatible with the json reader of the ConfigSpace API. The conditions are used to activate and de...
6ea21a08c9bfcc0643759a0bf6ada9ba2920b66d
659,635
def capitalize_first(x): """ This function upper-cases only the first letter, unlike .capitalize() that leaves the other letters uppercase. It leaves other letters as they were. """ return x[0].capitalize() + x[1:] if len(x) > 0 else x
17e827c6298aa4e9576a75c2591693b2b14e4c12
659,636
def getFilePath(id): """Retrieves file path and name, given file entry ID Args: id (str): File entry ID to get details of Returns: dict: Object contains file ID, path and name """ return {'id': id, 'path': 'test/test.txt', 'name': 'test.txt'}
125a678eed3e1e2024c678e4712665ccc04d4903
659,639
def width(canv): """ gets the height of the canvas :param canv: :return: integer height of the canvas """ return (canv and len(canv[0])) or 0
e9c5c229d57b73839e8b985a15aad96342c0fd29
659,645
def kl_div(mean, logvar): """Computes KL Divergence between a given normal distribution and a standard normal distribution Parameters ---------- mean : torch.tensor mean of the normal distribution of shape (batch_size x latent_dim) logvar : torch.tensor diagonal log variance of...
39fc74df4190a023e5b03132cd3102dc562a0401
659,646
def string_ancilla_mask(location, length): """Returns a bit string with a 1 in a certain bit and the 0 elsewhere. Parameters ---------- location : int location of the bit which should be set to '1' in the mask length : int length of string in the mask Returns ------...
0c4365f4bcdfd453062dcc723b17df2e43781a15
659,648
import _struct def parse_notify_req(pkt): """Parse a notification request. pkt -- raw packet data (str). Returns: (service, userid, messid, data) """ NOTIFY_REQ_LEN = 12 # Minimum packet size for notifications if len(pkt) < NOTIFY_REQ_LEN: raise ValueError("Invalid packe...
97806e0d8514b19177e91fcf2ba00e60c0cc0539
659,649
def overlap(x1, x2, y1, y2): """ Return True iff [x1:x2] overlaps with [y1:y2] """ if not all([isinstance(i, int) for i in [x1, x2, y1, y2]]): return False return ((y1 <= x1 <= y2) or (y1 <= x2 <= y2) or (x1 <= y1 <= x2) or (x1 <= y2 <= x2))
6bafaf7cbd012fe3ed9e32c6bf510a6298c8d5dc
659,650
def float2transparency(value: float) -> int: """ Returns DXF transparency value as integer in the range from ``0`` to ``255``, where ``0`` is 100% transparent and ``255`` is opaque. Args: value: transparency value as float in the range from ``0`` to ``1``, where ``0`` is opaque a...
803c6f6f65b43653248a0297532d7f6a5b49f5bf
659,651
def is_in_groups(user, group_names): """ Returns True if the user is a member of any groups given their names in group_names """ return any(user.groups.filter(name=group_name).exists() for group_name in group_names)
9d591331819003aa2542cb8b32dc98a13dbcba00
659,652
def illinois_algorithm(f, a, b, y, margin=1e-5): """ Bracketed approach of Root-finding with illinois method. Parameters ---------- f : callable Continuous function. a : float Lower bound to be searched. b : float Upper bound to be searched. y : float ...
742ce8d508d5e6895938c1765463be7f84070b9a
659,653
def get_choice_menu() -> str: """ Display the menu and ask for the choice from the user. Returns ------- choice: str The valid choice enter by the user. """ valid_choice_list = ['0', '1', '2', '3'] choice = '' menu = ( '1. Start new game\n' ...
be8d921d6ec2e555325aae0c4aa48e2e1b95a2ac
659,658
import math def compute_entropy(_list): """ 计算熵 https://zh.wikipedia.org/zh-hans/%E7%86%B5_(%E4%BF%A1%E6%81%AF%E8%AE%BA) https://baike.baidu.com/item/熵/19190273 Calculating entropy :param _list: :return: """ length = float(len(_list)) frequence = {} if length == 0: ...
df1f8602d8297c22ae01baa9edf32afb89eff52f
659,659
def MEAN(src_column): """ Builtin average aggregator for groupby. Synonym for tc.aggregate.AVG. If src_column is of array type, and if array's do not match in length a NoneType is returned in the destination column. Example: Get the average rating of each user. >>> sf.groupby("user", ... {'r...
8230c17d0dec7f277638274041e50290883c9eb9
659,665
import pickle def load_model_pkl(path): """ loads a model stored as pickle file (e.g. from sklearn) """ with open(path, 'rb') as f: return pickle.load(f)
f4618e0041d15b35b6653244ff19c732d2ce21aa
659,668
import requests import zipfile import io def downloadZipFile(url, directory): """ Multimedia Content are stored in cloud in ecar or zip format. This function downloads a zip file pointed by url location. The user is expected to have access to the file pointed by url. The extracted file is availab...
0422ddf5da24017772c56fe0058ab17b4edf9bef
659,672
def get_discussion_id_map_entry(xblock): """ Returns a tuple of (discussion_id, metadata) suitable for inclusion in the results of get_discussion_id_map(). """ return ( xblock.discussion_id, { "location": xblock.location, "title": xblock.discussion_category.split(...
b5cc1e0bf90719169c56f8c9da6d2021d2e7db63
659,674
def parse_directions_response(directions_response): """Extract basic information relevant to route from the response. Args: directions_response: list of directions in the deserialized Maps API response format Returns: if a valid route is found a tuple containing: a list of the (lat,lon) points ...
ca32f3582cf65c2eb4cfa981664c5bb117c6c85d
659,676
def to_percentage(number): """ Formats a number as a percentage, including the % symbol at the end of the string """ return "{:.2%}".format(number)
0f2b5af0e301503cb0cffc1c5c31f46b1d7803e8
659,683
from typing import Tuple def diagonal_distance(pa : Tuple[int, int], pb : Tuple[int, int]) -> int: """ Gets manhattan distance with diagonals between points pa and pb. I don't know what this is called, but the fastest route is to take the diagonal and then do any excess. """ (ax, ay) = pa ...
5f4fb653ab8d8bb77172b1637af3edb7c2f0b704
659,684
import re def is_invocation_allowed(command_requested, exact_allowed=[], regex_allowed=[]): """ Check if command_requested is an element of exact_allowed or if it matches a pattern in regex_allowed. If so, then return True. """ allowed = False if command_requested in exact_allowed: ...
e7b3ac061ce714bfe7afe9e709c19786735592ff
659,686
import click def conditional_argument(condition, *param_decls, **attrs): """ Attaches an argument to the command only when condition is True """ def decorator(f): if condition: f = click.argument(*param_decls, **attrs)(f) return f return decorator
39599ad3aa6ab29e56c3e419304818385f8c26f8
659,687
def windows_matcher(repository_ctx): """Matches Windows.""" if repository_ctx.os.name.lower().find("windows") != -1: return True return False
5d220b29db6495b53f3924edf45c37fac3008069
659,690
from typing import Tuple from typing import List def pad_line_to_ontonotes(line: Tuple[str, ...], domain: str) -> List[str]: """ Pad line to conform to OntoNotes representation. """ word_ind, word = line[:2] pos = "XX" oie_tags = line[2:] line_num = "0" parse = "-" lemma = "-" ...
db9831b4e466e4fe48b2023dfda65e24f1b498e8
659,691
def buy_signal(df): """Function calculates signal to open long position Args: df (pandas.DataFrame): pandas.DataFrame Returns: string: return "Buy" if condition is met else False """ tsi = df["TSI"] tsi_ma = df["TSI_MA"] signal = "" if ((tsi[-2] < 0 and tsi_ma[-1] < 0)...
a9f950b8059fdbdc89b92e87499b5482ee03f4ed
659,693
def strahler_stream_order(start_arc_id, start_up_node, nodes_per_arc, arcs_per_node, stream_orders): """Calculate the Strahler stream order This function recursively computes the Strahler stream order using the algorithm described by Gleyzer et al. (2004). The sequence of stre...
32b7c5c5c0e3aee169d97ade6403248494ca591e
659,694
import math def _distance(loc1, loc2): """ Returns the Euclidean distance between two co-ordinates in km """ R_EARTH = 6378.1 lat1_rad = math.radians(loc1[0]) lat2_rad = math.radians(loc2[0]) lon1_rad = math.radians(loc1[1]) lon2_rad = math.radians(loc2[1]) delta_lat = lat1_ra...
732208e1ab1e8a8a1737275f678c4d47778eeda0
659,697
def has_c19_tag (tags): """ Check if the COVID-19 tag is present """ for tag in tags: if tag.vocabulary == "99" and tag.code.upper() == "COVID-19": return True return False
6ffddcb3557c923fd9310d5cd550f3d006bb438e
659,702
import json def load_namelist(namelist_path:str): """Given path to `namelist.in` file, load and return as a nested dictionary.""" with open(namelist_path, 'r') as f: namelist = json.load(f) return namelist
00feb59d051891ed78dc39465738718174894d31
659,709
def exclude_targets(*args): """Exclude a test from running on a particular target. Use this decorator when you want your test to be run over a variety of targets and devices (including cpu and gpu devices), but want to exclude some particular target or targets. For example, a test may wish to be r...
679ec59718e0ff9228c0373bd530860823931fa9
659,710
import click def demander_mouvement(mvmts_possibles: str): """ Fonction qui demande au joueur le mouvement qu'il souhaite effectuer Args: mvmts_possibles (str): Mouvements que le joueur peut faire Retourne: str: Mouvement choisi par le joueur H : Aller vers le Haut B : Aller vers le Bas ...
40f06c023e6792bf1b752c2181fcd87a3a0b722f
659,711
def shape_attr_name(name, length=6, keep_layer=False): """ Function for to format an array name to a maximum of 10 characters to conform with ESRI shapefile maximum attribute name length Parameters ---------- name : string data array name length : int maximum length of strin...
a681b460cac8960dd103bfd9c0dc0a8a69721ac0
659,713
def attention_padding_mask(q, k, padding_index=0): """Generate mask tensor for padding value Args: q (Tensor): (B, T_q) k (Tensor): (B, T_k) padding_index (int): padding index. Default: 0 Returns: (torch.BoolTensor): Mask with shape (B, T_q, T_k). True element stands for re...
16fb98c267b7b42f7b02ffaf8c423438b1a86a3b
659,714
def lowercase_dict(original): """Copies the given dictionary ensuring all keys are lowercase strings. """ copy = {} for key in original: copy[key.lower()] = original[key] return copy
fd28bd266b1a46aaf522432db38f9b0f1f148746
659,715
from typing import Sequence import re def convert_sequence_to_text( schema_name: str, schema_desc: str, sequence: Sequence[str], ) -> str: """Converts sequence to text to use as GPT-2 input. Args: schema_name: Name of schema to run on. schema_desc: Description / definition of the ...
83af1ab73cb508171c2487503f1158fc83dfd1c3
659,716
import re def get_error_from_html(html_error, v1=False): """This function parses an error message from Khoros displayed in HTML format. .. versionchanged:: 2.0.0 Added the ``v1`` Boolean argument :param html_error: The raw HTML returned via the :py:mod:`requests` module :type html_error: str ...
d6587b9253c3902a02e5b9a3adcf50e1c75182f6
659,719
def _break_crt_chain(buffer): """Breaks the certificate chain string into a list. Splits the cert chain with "-----END CERTIFICATE-----". There are two cases to consider: 1) Certificates ending on "-----END CERTIFICATE-----" 2) Certificates ending on "-----END CERTIFICATE-----\n" In case (1),...
04f25569cf7cdd6049904a569ac6233a8b400b80
659,722
def mkfile(name, meta={}): """Return file node.""" return { 'name': name, 'meta': meta, 'type': 'file' }
5dc7ce835bef23abec93d989bff1445df5988f10
659,723
import pickle def load_pickle(file_path = "data.pickle"): """ Loads a pickle file created with `create_pickle()` :param file_path: Path of pickle file :type file_path: str :return: Serialized object :rtype: object """ with open(file_path, "rb") as readFile: data = pickle.load(...
1611bef0e2af40efe6f720c247d4a36d26142454
659,726
def plotFinal(solPlot,aSolPlot,tn,test,tpars,problems, mlMesh,mlScalarTransport,testOut): """ plot out solution and mesh at last step in a couple of formats """ if tpars['DG'] == False: solPlot.hardcopy(testOut+'_sol.eps', eps=1,enhanced=1,color=1) aSolPlot.hardcopy(testOut...
413a5d110b557f60cd7155a5edf9a83bc0a1658a
659,727
import re import yaml def parse_front_matter_and_content( contents: list[str], ) -> tuple[dict[str, str], list[str]]: """ Parse a list of all lines in a file into: front matter (merged result of existing ones and title + preview image) all markdown lines in the content apart from the recipe na...
85a2a49dac688d07427394ec4d2b3a7a3e546693
659,728
def get_mean_and_med_age(d): """ Calculate mean and median age of passengers :param d: data frame :return: rounded mean amd median """ return round(d['Age'].mean(), 2), d['Age'].median()
9a8478ffb654a1981fed8ede651c988a110102bd
659,730
def hzip(x): """ Zips the first and second half of `x`. If `x` has odd length, the last element will be ignored. >>> list(hzip([1, 2, 3, 4, 5, 6])) [(1, 4), (2, 5), (3, 6)] >>> list(hzip([1, 2, 3, 4, 5, 6, 7])) [(1, 4), (2, 5), (3, 6)] """ N = int(len(x) // 2) return zip(x[:N...
c99214a2f8e3110b0d070ed5fa3fdd428cb0dd6b
659,731
def human_readable_number(number: float) -> str: """Print a large number in a readable format. Return a readable format for a number, e.g. 123 milions becomes 123M. Args: number: a float to be printed in human readable format. Returns: readable_number: a string containing the formatted number. """ ...
70febc0c4ffe38bf2592209d1b490ae335d442f4
659,732
def write_dot(g): """Replacement for pygraph.readwrite.dot.write, which is dog slow. Note: This isn't a general replacement. It will work for the graphs that Rez generates, but there are no guarantees beyond that. Args: g (`pygraph.digraph`): Input graph. Returns: str:...
01b34ff8644ece4d3204e59b934040e66eecdd08
659,734
def simplify(conc_results): """Turn concordance output into something slightly more human-readable""" out = [] for r in conc_results: if len(r) == 3: out.append( [r[1][0], r[1][1]] + [r[0][i] for i in r[0][-1]] ) else: # Have context a...
f46e6406ed50c1c47f2eb8d4c5ef90beb8c89274
659,737
import re def _results_from_main_index(fields, query_regex, time_series_stem=''): """_results_from_main_index Returns dictionary mapping elasticsearch field names from fields to pairs containing that field's values that match query_regex, and a boolean indicating if the field is a time series fie...
dccc0160cae9eaba8131f20653db3b08572d936f
659,738
def getFrameIndex(t, fs): """ calculates and returns the frame index of at a given time offset within a signal @param t the time offset [s] @param fs sampling frequency [Hz] """ return int(round(float(t) * float(fs)))
b541ef24f5825089624223ebedbb195e858167c0
659,739
import re def get_filename(cd: str) -> str: """Returns filename from content disposition header.""" return re.findall(r'filename\*?=[\'"]?(?:UTF-\d[\'"]*)?([^;\r\n"\']*)[\'"]?;?', cd)[0]
3646bca9173aa3e5c37b82e6b1cbedc1bb14b9dd
659,741
import re def natsort(s): """ Natural sorting, e.g. test3 comes before test100. Taken from https://stackoverflow.com/a/16090640/3110740 """ # if not isinstance(s, (str, bytes)): return s x = [int(t) if t.isdigit() else t.lower() for t in re.split('([0-9]+)', s)] return x
3bc4b9aaec3e4eba149f728fd826a68a7574b42f
659,743
def size_from_shape(shape): """Returns size from the shape sequence """ size=1 for d in shape: size*=d return size
86b45daa7b93baec8d361066f900780b7cfbae61
659,745
def remove_suffix(x, suffix=" "): """ Remove a specific suffix from the end of a string. """ if x.endswith(suffix): x = x[: -len(suffix)] return x
3953e90dec3042fa6167b29bcbf4da3b9a53ff84
659,746
def collatzSeq(n, outputSeq = None): """ collatzSeq(int, list) -> list accepts two inputs: - n (required): the integer against which the conjecture is about to be tested - outputSeq (optional): only used during ricursion to store the state of the current test """ if outputSeq is None: ...
44e18ef019b76b1aac1ce145551bc5cc78ac8baa
659,747
def is_boolean(op): """ Tests whether an operation requires conversion to boolean. """ return op in ['or', 'and', '!']
5989c5db1befe76e61baa22a313b2d2e8f201553
659,748
def notas(*notasalunos, sit=False): """ Função para analisar notas de alunos e situações da turma. :param notasalunos: uma ou mais notas de alunos. :param sit: (valor opcional). Se True, mostra a situação da turma. :return: dicionário com várias informações sobre a situação da turma. """ con...
fdb8efe9ad27403f0c6f670bcbf8610095c6d1a9
659,749
def dumps(name, namelist): """ Writes a namelist to a string. Parameters ---------- name : str The name of the namelist namelist : dict Members of the namelist Returns ------- str String representation of the namelist """ # start with the opening mar...
6347d26bb07be8172ea04c193e2f077a77218d75
659,750
def trimquotes(s): """ Remove the single quotes around an expression:: trimquotes("'test'") == "test" :param s: expression to transform :type s: string :rtype: string """ if not s: return '' s = s.rstrip() if s[0] == "'" and s[-1] == "'": return s[1:-1] return s
d65786fa51b65db09906c644c206ff6f89398f0d
659,752
def sumall(*args): """ Take any number of arguments and return their sum """ sumall = 0 sumall = sum(args[0], *args[1:]) return sumall
e78f683cde5e01be88fa6c5e35cdf1b4f7a20586
659,757
from typing import Any from typing import MutableSequence def ensure_list(value: Any, convert_csv: bool = False, delimiter: str = ',') -> MutableSequence[Any]: """Convert an object, response, or (optionally) comma-separated string into a list""" if not value: return [] elif isinstance(value, dict)...
76262a0620e4988071eac3a28bd504801b938915
659,758
def _player_n_frame(base_df, n): """Create a dataframe of player level results for the nth player in a game frame This just gets called in player_level_df, doesn't need to be called directly Properties ---------- base_df: pd.DataFrame game level dataframe n: int the player ...
4aa3666cae22eb9be8ded796f6ee7e1d6f916610
659,763
import torch def warp_homography(sources, homography): """Warp features given a homography Parameters ---------- sources: torch.tensor (1,H,W,2) Keypoint vector. homography: torch.Tensor (3,3) Homography. Returns ------- warped_sources: torch.tensor (1,H,W,2) ...
c99e4e00606604dea152b5de7c513f69eb646d2e
659,764
def edges_to_line(edges, N): """ Returns a list of integers corresponding to a relabellign of the edge tuples by mapping (i,j) --> to N*i + j as per my convention for labelling of lineP, lineT. """ def relabel(edge): return N*edge[0] +edge[1] newlist = list(map(relabel, edges)) retu...
e5c0fe985e5b82e324467e74fd4b46314893cc50
659,765
import re def search_re(out, l): """ Search the regular expression 'l' in the output 'out' and return the start index when successful. """ m = re.search(l, out) if m: return m.start() return None
c20c5df306c9f0914825fb1e2c10d0ef5590dda6
659,770
from typing import Union import multiprocessing import re def parse_num_processors(value: Union[str, int, float]): """Convert input value (parse if string) to number of processors. Args: value: an int, float or string; string value can be "X" or "MAX-X" Returns: An int of the number of pro...
174f825c00946e80a64ce998508d34149e01bf14
659,772
def TagValues(d, lstTagValues): """ Return TRUE if you have a match within the list of tags (strings) """ bool = False if d['TAG'] in lstTagValues: bool = True return bool
978e1d7b0060339c3b9e4c92998096788cd7c8ab
659,775
def shift_TTD_dailyconservation_idx_rule(M): """ Index is (window, day, week, tour type). The index set gets used in the TTD_TTDS_con and TTD_TT_UB constraints. :param M: :return: Constraint index rule """ return [(i, j, w, t) for i in M.WINDOWS for j in M.DAYS for ...
07a65fe45bab32eaf53bd8f1182df32fb2930038
659,777
def containsExploit(text: str) -> bool: """ Returns whether or not the given str contains evidence that it is a sqli exploit """ return ('or' in text.lower() or 'and' in text.lower() or 'select' in text.lower() or 'from' in text.lower() or 'where' in text.lower())
e8c48013eb1bda4d2037132e602183f33a4050c8
659,783
def snake_to_camelcase(name: str) -> str: """Convert snake-case string to camel-case string.""" return "".join(n.capitalize() for n in name.split("_"))
a98c751ec3ff6b31a9c7c85ad8484c13c52cb695
659,784
def create_curl_command(authorization, payload, command, url, curl_options, show_api_key, content_type='application/json'): """ cURL command generator :param authorization: Authorization part e.g Bearer API key :param payload: Payload data :param command: GET, PUT, etc :p...
422d11c3837844111a1ef10a537ef4a52d0a988d
659,785
def getFullPath(request): """Get full URL path from the request """ # When testing, there is no request.META['HTTP_HOST'] in Django test client host = request.META.get('HTTP_HOST', 'none') full_path = ('http', ('', 's')[request.is_secure()], \ '://', host, request.path) return '...
726ca7205d4ad7537655853a7062ea07cc4814ef
659,789
def is_point_inside_rect(point: tuple, rect:tuple): """Returns whether a point is inside a rectangular region Args: point (tuple): The point to be tested rect (tuple): A rectangular region coordinates (up_left_x,upleft_y,bottom_right_x,bottom_right_y) Returns: boolean: If true then ...
d63e07d31191bdd3affa3fa4443111f7431376e3
659,790
def is_list(value): """ Tests the value to determine whether it is a list. :param any value: :return: True of the value is a list (an instance of the list class) >>> is_list( 'Hello' ) False >>> is_list( ['Hello'] ) True """ return isinstance(value, list)
bffc34bdfe9421418e36f303c3cd5afc7ed3c8dd
659,797
def sents_sync(ck_sents, sj_sents): """ check if two sentences are same. if there're differences, return the list to banish. :param ck_sents: :param sj_sents: :return: """ # ck_sents = mk_sents_with_lemma(ck_file, 3) # sj_sents = mk_sents_with_lemma(sj_file, 2) # ck_sents = mk_s...
202fd3d7dcfd84c3c5f5cdcc84b13f8cb2dc722c
659,799
import torch def compute_similarity_transform(S1: torch.Tensor, S2: torch.Tensor) -> torch.Tensor: """ Computes a similarity transform (sR, t) in a batched way that takes a set of 3D points S1 (B, N, 3) closest to a set of 3D points S2 (B, N, 3), where R is a 3x3 rotation matrix, t 3x1 translation, s ...
405c2656929551d843aefa458ae6348e297995b6
659,801
import re def _process_text(text): """Remove URLs from text.""" # Matches 'http' and any characters following until the next whitespace return re.sub(r"http\S+", "", text).strip()
6daea73170599f8600c8bfd0f1866a0f49380e20
659,802
def pchange(x1, x2) -> float: """Percent change""" x1 = float(x1) x2 = float(x2) return round(((x2 - x1) / x1) * 100., 1)
25dbc8b94a275aed8914458020f3e24649c61c9e
659,803
def _get_instance_id_from_arn(arn): """ Parses the arn to return only the instance id Args: arn (str) : EC2 arn Returns: EC2 Instance id """ return arn.split('/')[-1]
bac33ae4ce79e5a83325dcf303c6d77c05482fdd
659,807
def check_categories(categories_str, category_list): """ Check if at least one entry in category_list is in the category string :param categories_str: Comma-separated list of categories :param category_list: List of categories to match :return: """ req = False if isinstance(categories_st...
a3a0f68d1d6dbc9f1ff71ad80e26794c582c4130
659,808
def isIsomorphic(s,t): """ Given two strings s and t, determine if they are isomorphic. Two strings s and t are isomorphic if the characters in s can be replaced to get t. All occurrences of a character must be replaced with another character while preserving the order of characters. No two characte...
4a32379d16779f1b5e025df39e63155efd9805d3
659,810
def nextpow2(i: int) -> int: """returns the first P such that 2**P >= abs(N)""" return i.bit_length()
1c98858c6f7d6bb2201459f8f2ba215c8629cf8f
659,814
import re def short_urs(upi, taxid): """ Create a truncated URS. This basically strips off the leading zeros to produce a shorter identifier. It will be easier for people to copy and use. """ name = "{upi}_{taxid}".format(upi=upi, taxid=taxid) return re.sub("^URS0+", "URS", name)
4efb2556b60fe6397c76ea6a7fb403543fd3eab5
659,815
from pathlib import Path def get_suffix(path: Path) -> str: """Extracts full extension (as in everything after the first dot in the filename) from Path :param path: Original Path obj :return: String representation of full filename extension """ return f".{'.'.join(path.name.split('.')[1:])}"
80e3d90437d75f6162617973ab4cb8bf2cf76be3
659,816
import six import functools def command_aware_wraps(f): """ Decorator passing the command attribute of the wrapped function to the wrapper This needs to be used by decorators that are trying to wrap clicmd decorated command functions. """ additional = () if hasattr(f, 'command'): addi...
7161e7ee60a6f73304712f2e52b1c59e81ddf402
659,818
def set_parameter_requires_grad(model, requires_grad=False): """https://pytorch.org/tutorials/beginner/finetuning_torchvision_models_tutorial.html""" for param in model.parameters(): param.requires_grad = requires_grad return None
94d81cadd56309ee5e27263432ac2db23801db88
659,821
def encode(data): """ Encode string to byte in utf-8 :param data: Byte or str :return: Encoded byte data :raises: TypeError """ if isinstance(data, bytes): return data elif isinstance(data, str): return str.encode(data) else: return bytes(data)
77b2a070f6b436671e6d6074f37fe0e10ebff98d
659,824
import math def get_lng_lat_coord(origin_lnglat, xy_pt): """ Get the (lng, lat) from a given eucledian point (x,y). The origin point is given by origin_lnglat in (longitude, latitude) format. We assume (x,y) is "x" kilometers along longitude from the origin_lnglat, and "y" kilometers along the lat...
90cbbd1fa4c9f28415c5fcd49cfd2a2b6def540d
659,826