content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def is_pending(version, releases): """Check if given version is pending (is not released yet) or not. :param version: str, version :param releases: list, a list with information about fedora releases from Bodhi :return: bool, True if given version is a pending release, False otherwise """ for r...
097b9de121208ed81b9265c2f25f790b42dffd35
570,194
import re def subword(string, sub): """ Extract number of subwords from sentences and words. Parameters ---------- string: str Text selected to apply transformation. sub: str subwords from sentences Examples: --------- ```python sentence = 'Fu...
375c730daeadaad67a136fa51c3d8935b57ea563
570,196
def is_power_of_two(input_integer): """ Test if an integer is a power of two. """ if input_integer == 1: return False return input_integer != 0 and ((input_integer & (input_integer - 1)) == 0)
61f653b152162b3fca2fd44dc20ef68b7ce21455
570,201
def get_public_endpoint_url_by_name(body_response, endpoint_name, region_name): """ Get the public endpoint for service in a region by service NAME :param body_response: Keystone response (/token) :param endpoint_name: Service name :param region_name: Name of the region :return: Public URL or No...
5fb7dcb91132b8d6dfabc9b5b9ec2b0f66e18fc7
570,202
def is_partition(device): """ Check is a device is a partition """ if device[-1].isdigit(): return True return False
be8a643f337d8d28b57881918890a80120cb7ca2
570,206
import re def extract_gc_objects_set(log_file_path): """Extract a set of all objects that appeared in the garbage collector count section""" objs = set() with open(log_file_path, "r") as log: for line in log.readlines(): match = re.match(r".*\* (?P<name>.*) \(gc\): (?P<value>\d+).*", ...
462ed996c0922a70c467be3c65736400b8e10e1b
570,208
import struct def color_byte_chunk(color: dict) -> bytes: """ Build up a byte-chunk for a color in the correct format required for an Adobe ASE file. credit: https://github.com/nsfmc/swatch :returns: byte-chunk for a color """ title = color["name"] + "\0" title_length = len(title) ...
65b730192d10bfe453abfa4269f7b7ffa2fcf064
570,210
def RGB01ToHex(rgb): """ Return an RGB color value as a hex color string. """ return '#%02x%02x%02x' % tuple([int(x * 255) for x in rgb])
ebeae8bf7f7a93fa85a8e1155c8dead18611dbee
570,212
def glyph_contour_count(font, name): """Contour count for specified glyph. This implementation will also return contour count for composite glyphs. """ contour_count = 0 items = [font['glyf'][name]] while items: g = items.pop(0) if g.isComposite(): for comp in g....
65469809aa789ca48778f95fbb6e661f6c74259d
570,220
def ppm_to_pa(ppm, pres): """ Convert ppm (umol mol^-1) to a partial pressure Args: ppm (float) : ppm of gas [umol mol^-1] pres (float) : atmospheric pressure [Pa] Returns: pa (float) : partial pressure of gas [Pa] """ pa = ppm * 1e-6 * pres return pa
3dff62717f30ba5c086a6dfb2c9c7fe9c1cde429
570,221
def get_f_H_2(region, direction, y1, y2, z): """開口部の暖房期の取得日射熱補正係数(面する方位に応じた求め方) (2) Args: region(int): 省エネルギー地域区分 direction(str): 外皮の部位の方位 y1(float): 日除け下端から一般部及び大部分がガラスで構成されていないドア等の開口部の上端までの垂直方向距離 (mm) y2(float): 一般部及び大部分がガラスで構成されていないドア等の開口部の高さ寸法 (mm) z(float): 壁面からの日除けの張り出し寸法(軒等...
f334631218b9fb82e436fa7271bd10d1e52a31da
570,223
def list_to_map(j, k): """Turn a list into a map.""" return {entry[k]: entry for entry in j}
96fbed9a6ffa6683ce6c0ca1b3f211c0c927a91a
570,224
def glsl_file_type_value(op): """Gets file type value for given file type.""" if op == "vertex": return 0 elif op == "geometry": return 1 elif op == "fragment": return 2 raise RuntimeError("unknown GLSL file type: %s" % (op))
ab6051258be0453fe2ca79d9444973c99c3ba5ef
570,225
from typing import List def findMedianArrays(nums1: List[int], nums2: List[int]) -> float: """Receives two arrays of ints and returns the median of the merged arrays after sorting.""" nums1.extend(nums2) nums1.sort() if len(nums1) % 2 == 0: return (nums1[len(nums1)//2 - 1] + nums1[len(nums1)//...
760d910d86b5f6689c99e9ab07c123659a22683b
570,229
def builder_support(builder): """ Return True when builder is supported. Supported builders output in html format, but exclude `PickleHTMLBuilder` and `JSONHTMLBuilder`, which run into issues when serializing blog objects. """ if hasattr(builder, "builder"): builder = builder.build...
3e3244bfefa0cb81f52fc3aadb12b052865a5b90
570,231
import math def calc_angle(x: float, y: float) -> float: """Calculate the angle of a point from the center in degrees""" return math.degrees(math.atan2(float(y), float(x)))
999bf7448dc89cd1051ccec0c2b114b2c80d97bd
570,233
import inspect def appropriate_kwargs(kwargs, func): """ Auto get the appropriate kwargs according to those allowed by the func. Args: kwargs (dict): kwargs. func (object): function object. Returns: filtered_dict (dict): filtered kwargs. """ sig = inspect.signature(fu...
4b93b96811bf72f8f7219abf737ac2736884d71a
570,234
def getColors(surface): """Returns a list of all different colors in a surface""" surface = surface.copy() w, h = surface.get_size() colors = [] for x in range(w): for y in range(h): color = surface.get_at((x, y))[:3] if not color in colors: colors.app...
45eb3bf8360a9fadf8023f5f94ec4a52d304660d
570,236
def filter_key_blocks(blocks: dict) -> list: """Identify blocks that are keys in extracted key-value pairs.""" return [ k for k, v in blocks.items() if v["BlockType"] == "KEY_VALUE_SET" and "KEY" in v["EntityTypes"] ]
a30a362a3058cceb99336de275e6fd04a3a6fd17
570,239
def convert_rating(element): """Convert a rating from the Goodreads API.""" rating = element.text # The Goodreads API returns '0' to indicate an unrated book; # make this a proper null type. if rating == '0': return None else: return int(rating)
8ef18a6d2292f10171a41c70f3ce4756c5cfb2ef
570,244
from typing import Dict def process_results(metrics: Dict) -> str: """Filter to include only useful metrics from trainer.predict()'s output Args: metrics (Dict): Metrics from trainer.predict() Returns: str: str containing relevant eval metrics """ results = {k: v for k, v in metr...
ff7a3a31b4b82e306414fc8914aa14d44901aae1
570,249
import logging def parse_logs_head(data: bytes) -> set[str]: """Retrieve object hashes from logs/HEAD file.""" ret = set() lines = data.split(b"\n") for line in lines: fields = line.split(b" ") if len(fields) < 2: break for i in range(2): #first two fields are ...
03ffb95bef5951efb57d98d9adb68b66b044b797
570,250
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 and 1 is 100% transparent. ...
aaa8bcab30a4c0b414f2c696396d843ea03df374
570,251
def _get_indent_num_from_line(*, line: str) -> int: """ Get an indent number from a specified docstring line. Parameters ---------- line : str Target docstring line. Returns ------- indent_num : int Indent number of a specified docstring line. """ spaces: int = ...
a193b4b9fd4550be3b4daf761661142f6d9667f8
570,253
from typing import Callable from typing import Optional from typing import List from typing import Counter def get_most_frequent_tokens( corpus: str, tokenize_function: Callable, minimum_frequency: int = 1, max_number_of_tokens: Optional[int] = None, ) -> List[str]: """Helper function to get the m...
c7d0507704670820029da5a957f4d50eb01f67af
570,260
def set_shape_inputs(g, shape): """Set the shape of input graph nodes in the graph attribute. Parameters ---------- g : Graph The input graph shape : dict of str to tuple The input shape Returns ------- g : Graph The updated graph with updated shape. """ ...
1bf3cbb0f143e4f4a58b0f0b1f1637c7ba711be2
570,262
def check_balanced(input_str): """ Checks if input string is balanced paranthesis """ stack = list() balanced = True for char_ in input_str: if char_ == '(': stack.append(char_) elif char_ == ')': if len(stack) == 0: balanced = False ...
f16afe93d1c8ba4fc8ca9b55eeabc991552351fa
570,269
def construct_url(*components): """Concetenate strings to URL.""" separator = '/' url = separator.join(components) return url
804ff3e36d6b4d0cd9c99966b6058d65fcbcc1d0
570,272
def get_table_schema(conn, table): """Get column name and type of given table Args: conn: a database connection, this function will leave it open table: table name or db.table Returns: Tuple of (field_name, field_type) tuples """ if conn.driver == "maxcompute": sche...
d470b2747a16720cf4349fea5bfa1bfa466d59f7
570,273
def hass_to_wilight_saturation(value): """Convert hass saturation 0..100 to wilight 1..255 scale.""" return min(255, round((value * 255) / 100))
75994845588b960b2b6dc7b0d404e09f3248c1cc
570,276
def reversel(l,a=0,b=None): """ Reverse a list in place from index a up to b, which default to the start and the end. """ if b is None: b = len(l) assert a <= b <= len(l) num_swaps = (b-a)//2 for i in range(num_swaps): j = b-i-1 l[a+i],l[j] = l[j],l[a+i] return l
aa9f97049c6a431f52daf81c8f86d79c448c5aad
570,284
def pad_left_side(sequences, padding_value): """ Modification of torch.nn.utils.rnn.pad_sequence so that we pad left side and not right side :param sequences : list of tensors :param padding_value : tokenizer.pad_token_id :return tensor of shape (len(sequences), max_length of sequence in sequences) the tensor a...
220c43e0d35e05677838f773b8d02d6d28f062b2
570,287
def get_color_for_annotation_file(filename): """Gets color dict for annotation file. This function is specialized for some specfic files used in the FMP notebooks, i.e.: * FMP_C4_Audio_Brahms_HungarianDances-05_Ormandy * FMP_C6_Audio_Brahms_HungarianDances-05_Ormandy * FMP_C4_F13_ZagerEvans_InTheYe...
91522525805328f21be44316edc55f0cbe38c3be
570,288
def get_api_models(actor, what): """ Used to retrieve the full list of models including the ones defined by WorkflowAPIs used by the actor. :param what: A string which either is 'consumes' or 'produces' :type what: str :param actor: Actor type/instance or ActorDefinition instance to retrieve the in...
a17dd128b66481289fdf43b7f5229c744c5e81b1
570,291
def simplify_nested_dict(dictionary, name, separator='_'): """ Takes a nested dictionary and transforms it into a flat one. :param dictionary: (dict) dictionary to transform :return: (dict) result dictionary """ res = dict() for key in dictionary: if isinstance(dictionary[key], dict...
74698d6280840cd8bfccb343d2616d20b2e68b82
570,296
def printable_value_record(value_record): """Prints a GPOS ValueRecord.""" if value_record is None: return "<NULL>" if vars(value_record).keys() == ["XAdvance"]: return "%d" % value_record.XAdvance output_list = [] for key in ["XPlacement", "YPlacement", "XAdvance", "YAdvance"]: ...
1d029a5ba41037f9a896d640b56fe298664547bf
570,302
def mg_m3_to_ppm(c_mg_m3, mol_mass=None, mol_vol=None): """ converts concentration in ppm to concentration in mg/m³ :param c_mg_m3: concentration in mg/m³ :param mol_mass: molar mass of the component; default is 44.01 g/mol for CO2 :param mol_vol: molar volume of the component; default ...
823cc689709852a5e1634c9fcaebbcd3a878b16e
570,311
def dot(x: dict, y: dict): """Returns the dot product of two vectors represented as dicts. Parameters ---------- x y Examples -------- >>> from river import utils >>> x = {'x0': 1, 'x1': 2} >>> y = {'x1': 21, 'x2': 3} >>> utils.math.dot(x, y) 42 """ if len(...
5480250407b5c563e1aa058e774c2427458a47c5
570,315
def strip_swagger_markup(schema): """Turn a swagger URL parameter schema into a raw jsonschema. Involves just removing various swagger-specific markup tags. """ swagger_specific_keys = ( 'paramType', 'name', ) return dict( (k, v) for k, v in schema.items() ...
e9b361a5a9bb6d2be0c36b758e0ed636d5b16f8f
570,316
def serial_line_endings_to_sublime(text, line_endings): """ Converts the serial line endings to sublime text line endings :param text: the text to convert line endings for :param line_endings: the serial's line endings setting: "CR", "LF", or "CRLF" :return: the new text """ if line_endings...
e8304fffdc94d0e16cdfeedb26708de970fe63fd
570,320
import re def needs_character(syntax: str): """Determines whether a roll needs a character.""" return re.search(r"[A-z_]", syntax) is not None
3632176142545f12703a66dd1a7471dd57a3a7aa
570,321
def gpib_pass_control(library, session, primary_address, secondary_address): """Tell the GPIB device at the specified address to become controller in charge (CIC). Corresponds to viGpibPassControl function of the VISA library. :param library: the visa library wrapped by ctypes. :param session: Unique ...
5d6f2474ae897106bac217e93e153a8908d12383
570,328
def extend_model_config( model_config, syndrome_size, stack_depth, num_actions_per_qubit=3, device="cpu" ): """ Extend an existing model or agent configuration dictionary with information about the environment. Parameters ========== model_config: (dict) dictionary contiaining information ab...
1e5c91be3e52794a2cd9980783d2eac9d34c95b5
570,330
def depolarizing_par_to_eps(alpha, d): """ Convert depolarizing parameter to infidelity. Dugas et al. arXiv:1610.05296v2 contains a nice overview table of common RB paramater conversions. Parameters ---------- alpha (float): depolarizing parameter, also commonly referred to as lam...
89d7b9d33d53b5074f47e8d22e4a980750bc4da6
570,334
def get_marital_status(x): """ returns the int value for the nominal value marital-status """ if x == 'Never-married': return 1 elif x == 'Married-civ-spouse': return 2 elif x == 'Divorced': return 3 elif x == 'Married-spouse-absent': return 4 elif x == 'Widow...
b13c10817fd8b711626eb4b74e486709a069c0c6
570,335
import math def psnr(pred, target): """ Compute PSNR of two tensors in decibels. pred/target should be of same size or broadcastable """ mse = ((pred - target) ** 2).mean() psnr = -10 * math.log10(mse) return psnr
f7c50c801979686457e9d648f94a06c858d7c6a5
570,336
import calendar def date_format(date_ymd: str) -> str: """Convert date to IMAP SEARCH Command acceptable format. Args: date_ymd (str): The date in `YYYY-MM-DD` format. Returns: str: The date in `DD-MM-YYYY` format and the month replaced with its abbreviated form. """ ...
49e494500e75460a79b52d5d9f95424e128923ae
570,337
def prune_df(df, max_num_images_per_source, summary_file_pruned=None): """Keep first N images from each source to create a pruned summary file. The motivation is to trim down samples from sources with too many images, to create more balanced datasets. Args: df: summary dataframe created by summarize...
f19836bf1b886e3c19171083198fdde4d8fde752
570,339
def get_x_axis_values(columns, prefix, x_value_type): """ Get x-axis values for precision-recall plots (i.e. k-values) from the column names of result table. Arguments: - columns: list of column names - prefix: prefix of columns to consider - x_value_type: type for values; one ...
12073c64a7b75cfcd80c700042f254fe28603419
570,340
def count(generator): """Count the number of items in the stream.""" counter = 0 for _ in generator: counter += 1 return counter
208d2eacd956481b0b7bf7d33716c42233eb4e7b
570,344
def remove_suffix(string: str, suffix: str) -> str: """ Remove suffix from string. Parameters ---------- string Given string to remove suffix from. suffix Suffix to remove. Raises ------ AssertionError If string doesn't end with given suffix. """ if ...
c94a2a431e5aefd1585da51f6f7304e33c8de18d
570,345
def save_dct_to_txt(data_dict): """Saves the key-value pairs of a dictionary to text files on local disk, with each key as a filename and its value(s) as the contents of that file. Parameters ---------- data_dict : dict dictionary containing keys as filenames and values as the contents to be sa...
e4af330feefdded9e021b4c5953b7e550d81359b
570,347
def _sample_discrete__python(pmf, rand): """Returns a sample from a discrete distribution. Note: This version has no bells or whistles. Parameters ---------- pmf : list of floats A list of floats representing the probability mass function. The events will be the indices of the list...
3c1d9482c0d39f205477f9f3a3733599fb3cdd80
570,351
def _totuple(size, dim): """ Converts size to tuple. """ if not isinstance(size, tuple): if dim == 2: size = (size, size) elif dim == 3: size = (size, size, size) return size
2f6c514838bed8508d9cac951796c5e00bf65ef3
570,356
def bid_order_array(market,p,q,reference_price): """ make array of orders from array of percents, quantities and reference price """ i = 0 orders = list() print ("bid order array. ref: " + str(reference_price)) print (str(p)) for px in p: submit_price = reference_price * (1-px) o...
0e2810b6acc2644e797fd568a7f33ae1542bde2c
570,357
def timeseries_split(df, test_fraction=0.2, dropna=None): """Split timeseries data with test in the future""" # If there are lots of nan's we can ignore them when splitting into portions if isinstance(dropna, list): index = df.dropna(subset=dropna).index elif dropna is True: index =...
526464e71558756753711885190b415dc22a973e
570,358
def _get_header(text): """Gets first paragraph of a text Args: text (str or None): Text to be split Returns: str: First paragraph """ if isinstance(text, str): return text.split("\n")[0] elif text is None: return ""
4bf073835d853f70e1b02ffa809b6f3f9f108b82
570,360
import re def get_two_mismatches_loc(g_ob, g_ex): """ Given a observed protospacer vs expected protospacer, if 1-2 mismatches, output the position of mismatches starting from the PAM-distal end. :param g_ob: observed protospacer :param g_ex: expected protospacer :return: [position...
bc4895e488d680994a63497d185e15bf3cef1303
570,364
import torch def merge_videos(first: torch.Tensor, second: torch.Tensor) -> torch.Tensor: """Merges two videos together, first is played before second. Args: first (torch.Tensor): First video second (torch.Tensor): Second video Returns: torch.Tensor: Merged video """ retu...
5ceafd0cf0bc8e19ad75084568208ac1a82b5b52
570,365
def parse_args(parser): """ Parse commandline arguments. """ parser.add_argument('-d', '--dataset-path', type=str, default='./', help='Path to dataset') parser.add_argument('--wav-text-filelists', required=True, nargs='+', type=str, help='Files with au...
e12a237caa7da9a2a3de9cbdd5e6fe9c8d008347
570,366
def _format_type(json_value): """Helper to determine the Python type of the provided value from CLI. Args: json_value: (str) Value providing from CLI. Returns: json_value: The provided input coerced into proper Python Type. """ if (json_value.startswith('-') and json_value[1:].isdigit()) or ( ...
0f6dd0750ec8cd42c8741898687b4c1adb42a687
570,370
def read_fasta(fn): """ read fasta file :param fn: file name :return: AA sequences, AA names """ seq_names = [] seqs = [] with open(fn, 'r') as f: lines = f.readlines() for line in lines: line = line.strip() if line[0] == '>': # 去掉'...
b1cd7dd7d4cc917cdfbe2590fa2e83f975805e5d
570,373
def multiply(score, pixel): """Returns the result of score * pixel """ return score * pixel
ab68dbe873f59759b9547c36426cc3a16cf37cf4
570,380
def pwd_checker(pwd): """A utility to use for verify_client_func. Checks a client's auth password""" return (lambda id_data: pwd == id_data.get("pwd"))
aaa0702ebdc296bb0a1e2df308ed0db40b0cc367
570,391
def yolo2coco(size, yolo): """convert yolo format to coco bbox Args: size (tuple): (width, height) yolo (tuple): (ratio-bbox-centre-x, ratio-bbox-centre-y, ratio-bbox-w, ratio-bbox-h) Rets: coco: xmin, ymin, boxw, boxh """ width = size[0] height = size[1] centrex =...
404e10ea5fb2f43ca130ff43de7d8a8fc22080f4
570,392
def pick_best_loci(patterns): """ For patterns with multiple loci, pick the loci with the most conserved primer zones Input: patterns: A dictionary of patterns Output: A dictionary with a single loci from each pattern """ return {pattern: sorted(loci, key=lambda k:...
6c87bea45700f4f1b44af16aedd7c38d88316704
570,393
def _get_consecutive_sublists(list_): """ Groups list into sublists of consecutive numbers :param list_: input list to group :return cons_lists: list of lists with consecutive numbers """ # get upper bounds of consecutive sublists ubs = [x for x,y in zip(list_, list_[1:]) if y-x != 1] ...
f227e5d22c4af278eb8f1fddf2e5a51089e8f96c
570,395
import math def statistical_difference(pair_one, pair_two): """ The statistical difference between two values, considering their respective margins of error. Assumes the provided margins of error were generated at the Census Bureau's standard 90% confidence level. Args: pair_one (list): A tw...
0be99e43dad20e16bdf3abce2abb0222b54ba6a9
570,396
from typing import List from typing import Tuple import torch from typing import Dict import collections def map_key_names(scaled_yolo: List[Tuple[str, torch.Tensor]], our_model_dict: Dict[str, torch.Tensor]) -> Dict[str, torch.Tensor]: """ Translate scaled yolov4 weights' keys to our model weights' key P...
f9c14106138c8ddd08a99a1f54b5d096323f61a7
570,398
def Swap(xs, **unused_kwargs): """Swaps two elements.""" return (xs[1], xs[0])
6f8b833e32f5baf197b6dc41d848ef85babb6949
570,400
def parse_article_id_url(response, url_limit): """ Finds url on novinky.cz with article_id, that satisfies url_limit condition :param response: Scrapy response :param url_limit: :return: URL as str """ # finds first link to article, splits it into subarrays by '-' and takes last element => i...
2010d0f7395342dc090fce78a8bc99f2b1008818
570,409
def stemWord(w): """Renders a word in to its generic form. This function is used preprocess words for NLP. It removes all trailing punctuation marks "';-?.,!:". It also removes the possessive "'s" from words. And it converts it to all lower case Args: w (str): A string containi...
9d7425591724cf81a42f55cd95288be2041b95ea
570,415
def get_degrees(A): """ Pre-computation for degree of each node in the adjacency matrix :param A: adjacency matrix :return: degrees for each node, 2 * number of edges """ two_m = 0 degree_list = [0] * A.shape[0] for processed, e in enumerate(A.items()): node1, node2 = e[0] ...
ab171ef73b3561086fc482cd001d186e19e6c24f
570,418
def _translate_keys(cons): """Coerces a console instance into proper dictionary format.""" pool = cons['pool'] info = {'id': cons['id'], 'console_type': pool['console_type']} return dict(console=info)
ca1c2e1459c471a4eb73d8e6519cb299bbf709f8
570,424
import pathlib def IsFileCargo(toml_file_path: str) -> bool: """ Cargo requires the file to be named Cargo.toml Checking only file path should not be ambiguous """ return pathlib.Path(toml_file_path).name == "Cargo.toml"
b78410a903f43e3bd1c70e2b32c70f984c8e9226
570,428
def addattr(**kwargs): """ Add attributes to a function. Notes: Eliminates the need to write things such as `func.short_description = "This func does this"` """ def decorator(func): for key in kwargs: setattr(func, key, kwargs[key]) return func ret...
0c18a1132140f40a5d048dfa3f92f53f92dec88d
570,429
def emission(height: int) -> int: """ Emission rate (nanoERG/block) at given height. """ initial_rate = 75 fixed_rate_period = 525600 epoch_length = 64800 step = 3 if height <= fixed_rate_period: em = initial_rate else: em = initial_rate - (((height - fixed_rate_peri...
fb2f7c69fbf735c751e63b27d787747d28b7c6d1
570,436
def list_of_lines(text, include_lines=False): """Parse Text newlines into list. Safely parses strings into list. Filters Binary. If the text is in bytes it is decoded via UTF-8 Args: text (str/bytes): Text Returns: list of lines separated by new lines \n """ lst = []...
5e1de9b9a2aac0cba40d7fef978aab1afed1d4b2
570,441
import random def fisher_yates_shuffle(sequence): """Shuffles the sequence in-place randomly and returns it""" if len(sequence) < 1: return sequence index_last = len(sequence) - 1 for index_curr in range(index_last): index_random = random.randint(index_curr, index_last) ...
4c0b55a23ce7d8c580e477fd94274d5b8b872ad5
570,442
from typing import Dict def viaReg2cocoReg(region:Dict ): """Convert VIA x,y to COCO annotation Extract super category infomation from via json (type : radio) Args: region (Dict): VIA annotation info (region_attributes) Returns: seg (List): COCO annotation bbox (List): Bo...
de4185ae38252d6c456529baf169bb0baa25dcb1
570,443
from typing import List from typing import Tuple def generate_standard_headers() -> List[Tuple[str, str]]: """Generate a standard list of HTTP header, value pairs for openers.""" return [ ("Accept", "application/vnd.docker.distribution.manifest.v2+json"), ("Accept-Encoding", "gzip, deflate"), ...
4af1c5ec11d02d6d5fbec9d5d76ad0f579289adf
570,445
def correct_predictions(output_probabilities, targets): """ Compute the number of predictions that match some target classes in the output of a model. Args: output_probabilities: A tensor of probabilities for different output classes. targets: The indices of the actual targe...
61080fd06cb3ecdac8722ede2844da39d7cd6041
570,446
def find_max_independent_set(graph, params): """Find the maximum independent set of an input graph given some optimized QAOA parameters. The code you write for this challenge should be completely contained within this function between the # QHACK # comment markers. You should create a device, set up the QA...
89f2e0bd061625e14d90c90d4b7ef4e4d0439095
570,451
def sort_key(module_name): """ v1alpha1 -> 1.-2.1 v1alpha2 -> 1.-2.2 v1beta1 -> 1.-1.1 v1beta2 -> 1.-1.2 v1 -> 1.2.0 """ try: version = module_name.split("_v", 1)[1] except: version = "1" version = version.replace("alpha", ".-2.").replace("beta", ".-1.") versi...
127cbe0fd46dd47462742261b8bebab5b677662f
570,454
def is_command_yes(cmd: str): """Check if user agree with current command. Args: cmd (str): Command input value. Returns: bool: True if command value is match "yes" or "y" (case insensitive.). """ lower_cmd = cmd.lower() return lower_cmd == "yes" or lower_cmd == "y"
e929d10d70832dd12f6d2be57915a9e3584b453d
570,455
def task_flake8() -> dict: """Run flake8 check.""" return { 'actions': ['flake8 setup.py wdom tests'], }
bec087b8cc04b47c64d9e451e4bde5552f9036bd
570,461
import time def wait_for_channel_states(medialive, channel_id, states): """ Wait for a MediaLive channel to be in a specified state. """ current_state = '' while current_state not in states: time.sleep(5) current_state = medialive.describe_channel(ChannelId=channel_id)['State'] ...
b2ba07874cb932c7dbe3a6c09234148dbafee1cf
570,463
def logical_changes_in_branch(sbox, branch): """Return the set of logical changes that are actually in branch BRANCH (at its current working version), by examining the state of the branch files and directories rather than its mergeinfo. Each logical change is described by its branch and revision numbe...
aac33c10ca1c7f88a1c7375b4b134929b83db559
570,464
def poll_for_valid_message(consumer): """ Polls the subscribed topics by the consumer and checks the buffer is not empty or malformed. :param consumer: The consumer object. :return: The message object received from polling. """ msg = consumer.poll() assert not msg.error() return msg
50e7e48cf24427101e1db52854b540ebb2d60f9f
570,472
import time def dw_WriteHydFile(fname, d): """ Generates a Delwaq *.hyd file. d is dict holding all the required data: - d['runid'] : current run id - d['tref'] : reference time of simulation as datetime - d['tstart'] : start time of simulation as datetime - d['tstop'] ...
145f4841200e828051f4b97e76bd454b6a7dd5da
570,476
def extract(expr, name, name_index): """extract named part of expression, using name_index :param str expr: the lucene expression :param str name: name of the part to extract :param dict name_index: the dict obtained from :py:func:`name_index` """ return expr[name_index[name][0]: name_index[nam...
32ab5b4cb914aaa3f682ebe68d85fbce0e2658d5
570,480
def is_random(name): """ Determine if a user has a randomly generated display name. """ if len(name.split('_')) and name.startswith('user'): return True else: return False
9cd2d35eabfcbb1c21ffb269f1976a2c17d8905c
570,484
def normalize_repo_root_url(url): """Normalize a GitHub URL into the root repository URL. Parameters ---------- url : `str` A GitHub URL Returns ------- url : `str` Normalized URL of a GitHub repository. Examples -------- >>> normalize_repo_root_url('https://gi...
bbd01746ebdc777ba23cce3ef6a1aa9081d8d46f
570,485
def red_cube_path(blue_path): """Return the corresponding red cube path matched to a blue cube path.""" start = blue_path.rfind('blue') red_path = blue_path[:start] + 'red' + blue_path[start+4:] return red_path
ca69d4e484542efa5a20fdf1abe90534a8fde16c
570,486
def spliterator(bad_string): """Split a comma separated string into a list, removing any white space while your there.""" if bad_string: return bad_string.replace(' ', '').split(',')
248fa3e3f549c441e5bcd60b8e261ed56b86129e
570,489
def _convert_to_float_if_possible(s): """ A small helper function to convert a string to a numeric value if appropriate :param s: the string to be converted :type s: str """ try: ret = float(s) except (ValueError, TypeError): ret = s return ret
d8e736ee3072f1368a991b3b2cc974f3d04894d1
570,490
from typing import Dict from typing import Any def get_fp_length(fp_type: str, fp_params: Dict[str, Any]) -> int: """Returns the FP length given the name of the FP function and it's parameters. Parameters ---------- fp_type : str Name of the function used to generate the fingerprints. f...
74c1bc4bf8c236f7c980bbd9c4529395109b98d8
570,492
import copy from typing import Callable from typing import MutableSequence from typing import Mapping def apply_modifier(initial_dict, modifier): """ Returns a copy of an initial dictionary with modified values. :param initial_dict: any dictionary to create a copy from and modify :param modifier: eit...
ef99a846aeee2d919435076870012b0d4f03d3e9
570,494
def get_test_case_and_alg(basename): """ Extracts the changefile name and algorithm name from the basename of the file, e.g. changefile100Lazy Floyd-Warshall.out yields the output (changefile100, Lazy Floyd-Warshall) """ # Skip "changefile" in the search of an integer i = 10 while True: try: # Check if we...
43e25512d534a2672b4a426f8670e92c6b07d79b
570,495
import reprlib def clipped_repr(text, numchars=50): """`repr(text)`, but limited to `numchars`.""" r = reprlib.Repr() r.maxstring = numchars return r.repr(text)
83ff405f07cd098a707e68ecf9fd2568e4440a3d
570,496