content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def search_array_dict(array, id_name, id):
"""指定キーで配列から検索する - Search from the array with the specified key
Args:
array (arr): array
id_name (str): key
id (str): id
Returns:
dict: array item
"""
for item in array:
if item[id_name] == id:
return it... | 8b716e0522ed4a4a0637a4f1d7e3832fea8543ef | 635,451 |
def _arg_olen1(dvi, delta):
"""Optionally signed, length *delta*+1
Read *delta*+1 bytes, returning the bytes interpreted as
unsigned integer for 0<=*delta*<3 and signed if *delta*==3."""
return dvi._arg(delta + 1, delta == 3) | d5073c0feb12289c07b8c19b556dbc29c0aff10f | 635,453 |
def BandwidthToString(bandwidth):
"""Converts a bandwidth to string.
Args:
bandwidth: The bandwidth to convert in byte/s. Must be a multiple of 1024/8.
Returns:
A string compatible with wpr --{up,down} command line flags.
"""
assert bandwidth % (1024/8) == 0
bandwidth_kbps = (int(bandwidth) * 8) /... | 55caf2dc557e9a4b499020b5c57d663e91bf8845 | 635,454 |
import logging
def _read_gold_and_pred(gold_fpath, pred_fpath):
"""
Read gold and predicted data.
:param gold_fpath: the original annotated gold file, where the last 4th column contains the labels.
:param pred_fpath: a file with line_number and score at each line.
:return: {line_number:label} dict... | d1bb7f79115b2914193881ad8b966448e080dad8 | 635,455 |
def normalize_tag_name(name_tag):
"""
docker-py provides "RepoTags", which are strings of format "<image name>:<image tag>"
We want to strip off the tag part and normalize the name:
some.domain.com/organization/image:tag -> organization/image
organization/image:tag -> organiz... | bd8f049e4a815835e702cbe28c414bebec1fcbc8 | 635,457 |
def find_last_word(s):
"""Find the last word in a string."""
# Note: will break on \n, \r, etc.
alpha_only_sentence = "".join([c for c in s if (c.isalpha() or (c == " "))]).strip()
return alpha_only_sentence.split()[-1] | aaa163496a6c6ba4a5b8113b98e28390398fcbf9 | 635,460 |
def get_codon(seq, codon_no, start_offset):
"""
This function takes a sequece and a codon number and returns the codon
found in the sequence at that position
"""
seq = seq.replace("-","")
codon_start_pos = int(codon_no - 1)*3 - start_offset
codon = seq[codon_start_pos:codon_start_pos + 3]
... | dedbd8aa482a16d4d6cd61e46fe68347ee3697e6 | 635,463 |
def jump_to_match(input_file, regex):
"""Jump to regex match in file.
@param input_file: File object
@param regex: Compiled regex object
@return: True if successful, False otherwise
"""
for line in input_file:
if regex.match(line):
return True
return False | 9ecae9a2218d3f334e2183cc1979d839113c995b | 635,465 |
def conjoin_args(args):
""" Conjoin from left to right.
Args:
args (list): [<something> CONJUNCTION] <something>
Returns:
dict: MongoDB filter
"""
if len(args) == 1:
return args[0]
conj = f"${args[1].value.lower()}"
return {conj: [args[0], args[2]]} | feafb1dc37fc5df1d37bf1c22456a46d3968d043 | 635,466 |
def multAll(lst):
"""Multiplies a list of variables together"""
if len(lst) == 0:
return 0
out = lst[0]
for i in range(1,len(lst)):
out *= lst[i]
return out | 6d985d8c69b25f35b14b2bc94cc4e45be8f826e0 | 635,467 |
from typing import Union
import ast
from typing import List
def get_assign_targets(node: Union[ast.Assign, ast.AnnAssign]) -> List[ast.expr]:
"""
An AnnAssign `target` is a single node.
An Assign `targets` is a list of nodes.
Example:
`a = b = 1` return [ast.Name('a'), ast.Name('b')]
... | 9c12b6ba8ab7401c29e62b9fa1c73c1d5f995c1f | 635,469 |
def extract_between(source: str, start: str, end: str) -> str:
"""Extract all of the characters between start and end.
:param source: The input string from which to extract a substring.
:param start: The substring that marks the extraction starting place.
:param end: The substring that marks the place ... | 7f3c5f428cbfa80adc1781ae01ea15788ed9a3e8 | 635,470 |
import torch
from typing import Optional
def one_hot(labels: torch.Tensor,
num_classes: int,
device: Optional[torch.device] = None,
dtype: Optional[torch.dtype] = None,
eps: Optional[float] = 1e-6) -> torch.Tensor:
"""Converts an integer label x-D tensor to a one-ho... | 7ecc2eaf0b32ccb4b7abea8a870aaa302e4cffc6 | 635,472 |
from typing import Iterable
from typing import Any
from typing import Iterator
from typing import Tuple
import itertools
def pairwise(iterable: Iterable[Any]) -> Iterator[Tuple[Any, Any]]:
"""Return iterator of overlapping pairs of items from an iterable.
Will return an empty iterable if the passed iterable ... | 9d61ed5c0dd2b165ac93d6c59b0a62700a0ddbe8 | 635,474 |
def normalize_ctu_name(name):
"""Ensure name is in the normal CTU form."""
return name.title().replace('Ctu', 'CTU').replace('Iot', 'IoT') | b530f8d6316a559c3e3935c7a46d0753477b87f6 | 635,475 |
def count_string_dictionary(list_of_strings):
"""
Count the number of instances in a list and return them in a dictionary where the keys are the strings and
the value the number of times it appeared in the list
"""
to_return = {}
for e in list_of_strings:
try:
to_ret... | 56b4613eb2f5eb63db4575462c9891471509e7ba | 635,476 |
def addright(page, right_page, tx=0):
"""Adds page (PageObject) on the right side, tx is an addtional offset"""
page.mergeTranslatedPage(right_page, page.mediaBox[2] + tx, 0, expand=True)
return page | ca05db31c7d1b3a4177bb6317b7ddd3fe391e671 | 635,484 |
def get_data_from_pipeline(pipeline, image, coordinates, labels):
"""
Function defined to apply the data augmentation pipeline and retrive image,
bounding boxes coordinates and corresponding class labels.
Args:
-----
- pipeline: albumentations.Compose Object
- image: ndarray, image to be au... | 941a3c1da203c31a09421dad80881d89eca7c661 | 635,487 |
def Get_Parses(data):
"""
Reads parses from data, counting number of parses by newlines
- sentences: list with tokenized sentences in data
- parses: a list of lists containing the split links of each parse
[
[[link1-parse1][link2-parse1] ... ]
[[link1-parse2][link... | d6a552821722452bcd42f8125a18e071339d29df | 635,491 |
def get_args_of_function_node(function_node, args_to_ignore):
"""Extracts the arguments from a function definition.
Args:
function_node: ast.FunctionDef. Represents a function.
args_to_ignore: list(str). Ignore these arguments in a function
definition.
Returns:
list(str... | 7a5dd3e26a2b95714c569e751b9fb056f80eae32 | 635,498 |
import yaml
def _import_current_tasks(course, template):
"""
Render tasks from the course.
:param course: Path to the course file
:type course: ``str``
:param template: Template environment
:type template: :class:`narrenschiff.templating.Template`
:return: Tasks as a list of dictionaries
... | b83747fcc2a7ac0567c9d8ad2d986453a52b0ce4 | 635,499 |
def _extract_gpcrdb_residue_info(residue_html):
"""
Extracts the relevant info from GPCRdb html entries of residues.
Parameters
----------
residue_html : list
A list in which each item contains the html lines for one residue.
Returns
-------
residue_info : list
... | b4d8aa658adfc6c8669b9d45ff59462b1755cbac | 635,504 |
from pathlib import Path
from typing import Union
import json
def load_json_data(fpath: Path) -> Union[list, dict]:
"""
Loads a JSON file and returns data.
Args:
fpath (Path): The path to the file
Returns:
Union[list, dict]: The data loaded from JSON.
"""
with open(fpath) as ... | 9745dd74016d036f13e11d91b2a8cee4d5d9766f | 635,506 |
def instant_name_to_class_name(name):
"""
This will convert from 'parent_name.child_name' to
'ParentName_ChildName'
:param name: str of the name to convert
:return: str of the converted name
"""
name2 = ''.join([e.title() for e in name.split('_')])
return '_'.join([e[0].upper() +... | 380acd68925ce24846bc30737d7d066609ae3525 | 635,507 |
from typing import Dict
def _is_subscriber(patient_record: Dict):
"""Returns true if the patient is a subscriber record"""
return patient_record.get("hl_segment", {}).get("hierarchical_level_code") == "22" | b8350dc4e69c740e777e9a225618c07d254e5d0a | 635,508 |
import re
def alphanum_split(key):
"""Split the key into a list of [text, int, text, int, ..., text].
Args:
key (str): String to split.
Returns:
list: List of tokens
Examples:
::
>>> alphanum_split("hello1world27")
['hello', 1, 'world', 27, '']
>>> alphanum_... | 473d1f930e42eda9c870b2fd2f605e69b8e6171b | 635,509 |
def find_lowest_common_in_paths(path_a, path_b):
"""Find the element with the smallest height that appears in both given lists.
The height of an element here is defined as the maximum over the indices where
it occurs in the two lists. For example if path_a = [2, 3, 5] and
path_b = [5, 6, 2] then the height of ... | 652d62e8787a3581ec82de48a56e38d39c2471c2 | 635,510 |
def marginal_contribution_set(game, player, lower_set):
"""
Takes a subset of players and a player, transforms them into a higher set c2 and lower set c1 and calculates
their marginal contribution based on the implemented payoff function.
:param player: An element of self.players
:type player: str... | 8f958aa499e47300e7706e38720bd7a3eea6aa1a | 635,515 |
import torch
def get_last_token(t, lengths):
"""
Grab last hidden activation of each batch element according to `lengths`
# ^ (1) ^ (2) ^ (3)
>>> t = torch.tensor([[[1],[2],[3]], [[2],[3],[4]], [[3],[4],[5]]])
>>> lengths = torch.tensor([3, 2, 1])
>>> g... | 64e10c0d66615da68a0cf2743cd502d5a8581aab | 635,517 |
def decode_to_str(batch_text, max_len=512) :
"""
Converts bytes string data to text. And truncates to max_len.
"""
return [ ' '.join(text.decode('utf-8').split()[:max_len]) if isinstance(text, bytes) else text[:max_len]
for text in batch_text ] | 25da1b9a0f3a0cbf9bf870732422aed7c9900ac4 | 635,518 |
def compute_similarity_within_df(df, similarity_metric):
""" Compute all pairwise similarities between the columns of df.
Args:
df (pandas df): size = m x n
similarity_metric (string): "pearson" or "spearman"
Returns:
out_df (pandas df): size = n x n
"""
# Compute similarity
... | aa8af36db6e7584d2c20b05a7546e3779b1c11ca | 635,520 |
def get_yt_ids(label_ids, csv):
"""
Function for getting the youtube IDs for all clips where the specified classes are present
:param label_ids: list of label IDs (will most often only contain 1 label)
:param csv: path to csv file containing dataset info (i.e. youtube ids and labels)
:return: dicti... | 32684d2de8eb5450b1a9cb656ff82f1a5bb36387 | 635,524 |
def classic_example_3(sequence_of_sequences,
what_to_count, what_to_mutate_into):
"""
Shows counting and mutating in a sequence of LISTS.
-- Counts and returns the number of 'what_to_count' occurrences.
-- Mutates those occurrences into the 'what_to_mutate_into'.
"""
pr... | 9e285b30645c643dcd7acf0007aa7c63b5a606fb | 635,526 |
def login(client, user, password):
"""Return the User instance after logging the user in."""
assert client.login(username=user.username, password=password)
return user | 32c1d621b515086cf1811b146ca10a26ebc1d6fa | 635,533 |
def common_prefix(s1, s2):
"""Return the common prefix of strings s1 and s2."""
prefix = []
for c1, c2 in zip(s1, s2):
if c1 != c2:
break
prefix.append(c1)
return ''.join(prefix) | 3f5f43e984a1a42b2057bdbffe09a4f6a7b48e69 | 635,534 |
def getUsername(dn):
"""Get the uid/cn of the given DN."""
return dn.split(',')[0].split('=')[1] | 7d741e03cf7380b0da07558beea69d870b0dcc2e | 635,536 |
import pathlib
def has_parent_path(sub_path: pathlib.Path, parent_path: pathlib.Path) -> bool:
"""Check if sub_path has the specified parent_dir path."""
# sub_path should be longer than parent path
if len(sub_path.parts) < len(parent_path.parts):
return False
for i, part in enumerate(parent_... | 7d7d8f390a45157db2bb364f984329df774d5621 | 635,544 |
import re
def _parse_key(key):
"""Parse the input key into an int, antpol tuple, or string.
Parameters
----------
key : str
Input string to parse.
Returns
-------
out_key : int or tuple or str
Parsed key as an int, antpol tuple, or string.
"""
try:
# is k... | 8f38d513ae9d1c583842a6ee63fd7bc935046da6 | 635,549 |
import pytz
def local_tzinfo_factory(offset):
"""
Create a tzinfo object using the offset of the db connection. This ensures
that the datetimes returned are timezone aware and will be printed in the
reports with timezone information.
"""
return pytz.FixedOffset(offset) | 8d64e715aa9193d10234ac400fcc879361460c4f | 635,552 |
def rescale_points(points, scale):
""" Take as input a list of points `points` in (x,y) coordinates and scale them according to the rescaling factor
`scale`.
:param points: list of points in (x,y) coordinates
:type points: list of Tuple(int, int)
:param scale: scaling factor
:type scale: float... | 9afbb972d747e5f03e7066756faaeb7c4b0e402c | 635,556 |
from typing import List
from typing import Counter
def get_characters(lang_data: List[str]) -> Counter:
"""
Return a sorted list of characters in the language corpus.
Parameters
----------
lang_data : List[str]
A list of all paragraphs
Returns
-------
characters : Counter
... | 77aad0cb4146cb9bf64eae217c2dc65364f6e081 | 635,558 |
def convert_dotted_str_to_int(dotted_str: str) -> int:
"""
Convert dotted str into int:
- This function takes a dotted str and converts into an int.
- Useful in converting version into a number.
- Eg: "1.2.3" -> 123
"""
return int("".join(dotted_str.split("."))) | 7065b9ce08f467722f70f8f8289a252f03a305f3 | 635,559 |
def run_maze(maze: list[list[int]], i: int, j: int, solutions: list[list[int]]) -> bool:
"""
This method is recursive starting from (i, j) and going in one of four directions:
up, down, left, right.
If a path is found to destination it returns True otherwise it returns False.
Parameters:
maz... | b2c56fdd2d3c289b1ca62705de00d03f6fd92e63 | 635,561 |
def listify(x):
"""convert object to a list; if not an iterable, wrap as a list of length 1"""
return list(x) if hasattr(x, '__iter__') else [x] | aa7a90a438b851350f2f3dab1e5934213f409ac5 | 635,562 |
def _get_rating(mr_val, snt):
"""
Handle the rating part.
:param mr_val: value of the 'customerRating' field.
:param snt: sentence string built so far.
:return: refined sentence string.
"""
# if the previous sentence ends with a dot
if snt[-1] != ".":
beginning = " with"
else... | b5abb8754f05adc1562db6bf501317bd7f357d5b | 635,563 |
import json
def normalize_nested_dicts(row):
"""Transform nested dicts into json strings with sorted keys.
Args:
row (dict): A dictionary to normalize.
Returns:
dict: A row with nested dicts transformed to json string.
"""
new_row = {}
for key, value in list(row.items()):
... | 708987df988cc396786523e3563ff6b9bf06af07 | 635,566 |
def _improve_latex(s):
"""Improve an OSIRIS-generated latex string using common rules."""
# Descriptive subindexes in roman
s2 = s.replace(r"\omega_p", r"\omega_{\mathrm{p}}")
s2 = s2.replace("m_e", r"m_{\mathrm{e}}")
# "Arbitrary units" in roman
s2 = s2.replace("a.u.", r"\mathrm{a.u.}")
ret... | 1aa3ae218da5d140ae3bf64a8f78643a7f906a8e | 635,569 |
def nextID_in_poly(poly, id):
"""
Determines the id of the next point on a standard polygon.
Parameters
----------
poly :: List of (x,y) tuples
Representation of a polygon, with identical first and last vertices.
id : Integer
Returns
-------
Integer
"""
if id==len(... | 1e941fd17aaf6214666fc020c04c49916694bef8 | 635,576 |
def display_ar(section):
"""
Show access rights of a section
"""
res = ""
if section.IMAGE_SCN_MEM_READ:
res += "R"
else:
res += "-"
if section.IMAGE_SCN_MEM_WRITE:
res += "W"
else:
res += "-"
if section.IMAGE_SCN_MEM_EXECUTE:
res += "X"
el... | eb5393f274b9ad6d1d8663f605d59b6f5f85058e | 635,582 |
from typing import Tuple
def addpair(pair: Tuple[float, float]) -> float:
"""(a, b) -> a + b """
(v1, v2) = pair
return v1 + v2 | 937a0881c2af22c514922300749d88a5cea8d967 | 635,583 |
def valid_path(path):
""" Determine if a path is deemed "valid". This means we are looking for real partitions (not kernel devices)
and mounted partitions.
:param path: Usually named tuple returned from psutil.disk_partitions()
:type path: namedtuple
:return: Valid path state
:rtype: bool
"... | 3aca63892294396f298ce6b0820ee68f2b6b0b18 | 635,584 |
def read(file_path):
""" Read a file and return it's contents. """
with open(file_path) as f:
return f.read() | d5a5df9f5ba54cb51409733146cc8ccd8c0886f7 | 635,588 |
import json
def read_in_config_file(conf_file):
"""
Read in the JSON configuration file used to make the groupme bot aware of the groups it is in.
:param conf_file: The path to the JSON file of configuration information for the groupme bot.
:return: The bot_name from the config, the dictionary mapping... | 011ceaa2c4be576589ba25436662742f27ff5ccf | 635,589 |
def get_slug(clip: str) -> str:
"""
Splits up the URL given and returns the slug
of the clip.
"""
slug = clip.split("/")
return slug[len(slug) - 1] | 9f2aa0a85f6d212b8cff13b6337f12e6a05a2741 | 635,590 |
from typing import Dict
def calculate_possibilities(max: int) -> Dict[int, int]:
"""Calculate the numbers of lucky numbers from 0 to 10**(max - 1)"""
possibilities: Dict[int, int] = { 0: 0, 1: 2 }
index: int = 2
while index < max:
possibilities[index] = 2 * (9 ** (index - 1)) + 8 * possibiliti... | a43a52ec44066ebf6e6a14c022edcc4bfbd45e30 | 635,591 |
from typing import Optional
def search_divs(term: str, divs: list) -> Optional[list]:
"""
Searches the provided div tags for the term that we are interested in
:param term: String, the search term
:param divs: List, div tags that were scraped
:return: List of divs or None
"""
for div in di... | 6bf85f5e30d779f725dde1ae8685f1f51ddaaf36 | 635,592 |
def change_to_tuples(dict):
"""
Turns an unitary dictionary into a tuple
"""
return (list(dict.keys())[0], list(dict.values())[0]) | fd713d185e204649b0c532ec51836d33508c2d2c | 635,593 |
def cloneRange(rng):
"""
Make a copy of the given js range; the JS range is decoupled from any
changes.
@param range a js range to copy
@return a full copy of the range
"""
return rng.cloneRange() | 267bba0f6ce012ed47360228c20154510b5312b0 | 635,594 |
def get_lower_long_from_trace_id(trace_id):
"""Returns the lower 8 bytes of the trace ID as a long value, assuming
little endian order.
:rtype: long
:returns: Lower 8 bytes of trace ID
"""
lower_bytes = trace_id[16:]
lower_long = int(lower_bytes, 16)
return lower_long | 34ce01fd951282b57774a17bd5caa6fc7b44458a | 635,596 |
def default_image_loader(filename, flags, **kwargs):
"""This default image loader just returns filename, rect, and any flags."""
def load(rect=None, flags=None):
return filename, rect, flags
return load | 58c0516156c790f60846be1fa08f41c3e62de2de | 635,597 |
def formatsWritersField(writers_list):
""" Formats Writers field for Web app template. """
film_writers=""
if writers_list != None:
for writer in writers_list:
if len(writers_list) == 1 or writer == writers_list[-2]:
film_writers = writer
elif writer != w... | 6088f8bed1b754d1769c694f4671252bf9ffadf8 | 635,602 |
def compute_exact_score(predictions, target_lists):
"""Computes the Exact score (accuracy) of the predictions.
Exact score is defined as the percentage of predictions that match at least
one of the targets.
Args:
predictions: List of predictions.
target_lists: List of targets (1 or mor... | 8b4c80670413cee6cc232eca4740692981755f99 | 635,603 |
def bits2val(bits):
"""For a given enumeratable bits, compute the corresponding decimal integer."""
# We assume bits are given in high to low order. For example,
# the bits [1, 1, 0] will produce the value 6.
return sum(v * (1 << (len(bits)-i-1)) for i, v in enumerate(bits)) | 52471c014418e8cfcee09ecb9c37cd13f883857c | 635,604 |
def clamp_value(n, minimum, maximum):
"""
Clamp a value between a min and max
:param n:
:param minimum:
:param maximum:
:return:
"""
return max(minimum, min(n, maximum)) | 7edcf25454f0cd5989ed1a77ae877d2d9c783020 | 635,605 |
def boundary_conditions(cells, cell_data, phy_lin, nodes_array, bc_x, bc_y):
"""Impose nodal point boundary conditions as required by SolidsPy
Parameters
----------
cell : dictionary
Dictionary created by meshio with cells information.
cell_data: dictionary
Dictionar... | 573e892ff48e30cb3a18469a153f445be1aceedc | 635,606 |
def string2index(sentences, vocab):
"""Convert string to its corresponding index
i.e. A -> 0, B -> 1 ... for vocab [A,B,...]
Args:
sentences (np.array of String): list of String to convert.
shape = [num_samples, length]
vocab (list of String): list of vocabulary
Returns:
index (np.array of In... | c0c02dacd312f541e97bcdb330b11562227835c2 | 635,612 |
def _remove_type_bracket_block_from_args_str(args_str: str) -> str:
"""
Remove type annotation block bracket from arguments string.
Parameters
----------
args_str : str
The target arguments string.
e.g., 'dict_val: Dict[str, int] == {}'
Returns
-------
result_str : str
... | d4dcc2f2968c543161ef08cb76cf2baa56058648 | 635,615 |
def parse_country_code(country_code):
"""
Parse country code from URL to determine origin.
:param country_code: country code from URL
:return: parsed country code
"""
cc = str(country_code).lower()
if cc.lower() == 'edu' or cc.lower() == 'com' or cc.lower() == 'org' or cc.lower() == 'gov':
... | 01b9a1e319dc9d08455e69a638154b0c2e8493ee | 635,616 |
def _wrap(text, width):
"""Break text into lines of specific width."""
lines = []
pos = 0
while pos < len(text):
lines.append(text[pos:pos + width])
pos += width
return lines | 3288dfb868996906357b235b9add27b34678bcc4 | 635,618 |
def rename_nfa_states(nfa: dict, suffix: str):
""" Side effect on input! Renames all the states of the NFA
adding a **suffix**.
It is an utility function to be used to avoid automata to have
states with names in common.
Avoid suffix that can lead to special name like "as", "and",...
:param di... | 4f4ceeeb3298cb2e04c3c832cd9328502371ccfd | 635,625 |
def join_matrixes(matrix_1, matrix_2, matrix_2_offset):
""" Copy matrix 2 onto matrix 1 based on the passed in x, y offset coordinate """
offset_x, offset_y = matrix_2_offset
for cy, row in enumerate(matrix_2):
for cx, val in enumerate(row):
matrix_1[cy + offset_y - 1][cx + offset_x] += ... | 5186863471187d3b595786d995552fdb66c62b02 | 635,627 |
def merge_envelopes(envelopes, extent_type='intersection'):
"""Return the extent of a list of envelopes.
Return the extent of the union or intersection of a list of envelopes
:param envelopes: list of envelopes or raster filenames (also mixed)
:type envelopes: list, tuple, iterator
:param extent_t... | 90304f0ea88e735a9a995cb7125928545312cac0 | 635,628 |
import random
def generate_ascending_array(power):
"""Generate an array of integers sorted in ascending order."""
A = []
for k in range((2**power)+1):
A.append(random.randint(-1000000, 1000000))
return sorted(A) | b989e2b9f50a93347ba0c0147c2bb36d6bafa049 | 635,629 |
import string
def format_output(rc, time):
"""
Formats the output that is used in sending the message to the client,
depending on the return code of the command.
"""
template = string.Template("""
${greeting}!\n
I have finished executing your job. Its return code is `$rc`, which
$comment.\n
Your command to... | 091613f5c3b07b822d61b184def02d42abc01a11 | 635,630 |
def elem_to_dict(elem, ns, key_map, value_map={}):
"""Convert an XML etree.Element to a desired dictionary
as specified by the key map and value map.
Args:
elem (etree.Element): An ancestor element
of the tags specified in the key map.
ns (string): The namespace to use
... | fc5c894bba1d374679db23e6cfa176a598c18fdc | 635,631 |
def list_to_string(in_list, conjunction):
"""Simple helper for formatting lists contaings strings as strings.
This is intended for simple lists that contain strings. Input will
not be checked.
:param in_list: List to be converted to a string.
:param conjunction: String - conjunction to be used (e.... | 192b9a01fc7f861ec21e54647097f1a53ce6bc7c | 635,632 |
def to_bio2(tags):
"""
Convert the original tag sequence to BIO2 format. If the input is already in BIO2 format,
the original input is returned.
Args:
tags: a list of tags in either BIO or BIO2 format
Returns:
new_tags: a list of tags in BIO2 format
"""
new_tags = []
... | c0430d7f04c9a7b3e7399c35c26c4cee2a430c76 | 635,633 |
def execute_request(service, property_uri, request):
"""Executes a searchAnalytics.query request.
Args:
service: The webmasters service to use when executing the query.
property_uri: The site or app URI to request data for.
request: The request to be executed.
Returns:
An array of response rows.... | a40ca88b1a60e2da01ff237c95db0cb08cb57bab | 635,637 |
def custom_admin_notification(session, notification_type, message, task_id=None):
"""
Function for implementing custom admin notifications.
notifications are stored in session and show to user when user refreshes page.
A valid session object must be passed to this function with notification type and me... | 6ab3b478c5109a821fc64201c9468e3d8d132cff | 635,646 |
def calculate_product(alist):
""" Returns the product of a list of numbers. """
product = 1
for fact in alist:
product *= fact
return product | 7abcc1287703bed8cd499738d6afaba9c35199f4 | 635,647 |
def _get_pgh_obj_pk_col(history_model):
"""
Returns the column name of the PK field tracked by the history model
"""
return history_model._meta.get_field(
'pgh_obj'
).related_model._meta.pk.column | 8ff914a7c0142973b58b48b22d9c7429682d69de | 635,662 |
def _parse_query(query):
"""extract key-value pairs from a url query string
for example
"collection=23&someoption&format=json"
-> {"collection": "23", "someoption": None, "format": "json"}
"""
parts = [p.split("=") for p in query.split("&")]
result = {}
for p in parts:
if len... | 7d390f86bc7e74f4016396f066b5aab8afa72f72 | 635,668 |
async def get_modification_stats(db, index_id):
"""
Get the number of modified otus and the number of changes made for a specific index.
:param db: the application database client
:type db: :class:`~motor.motor_asyncio.AsyncIOMotorClient`
:param index_id: the id of the index to return counts for
... | cbeadb2e7d194b57a9b47e664f3d1cbdbe412bf7 | 635,669 |
def should_show(name, pruning_params):
"""Whether to show the layer's distribution or not."""
in_whitelist = not pruning_params.white_list or any(
e in name for e in pruning_params.white_list)
in_blacklist = any(e in name for e in pruning_params.black_list)
if pruning_params.white_list and not i... | ced5ed604e75ed7f32267a3f703ddcf2828e546d | 635,674 |
def test_case_is_success(test):
"""Determine if the the test expects a successful parse"""
if "results" not in test:
return True
for result in test["results"]:
if "error" in result:
return False
return True | fee43364a8a11ed42564b07533a2500b69c60894 | 635,677 |
def part_2_fuel(pos, list_):
"""gives the fuel amount for a specific position according to rules of part 2"""
fuel = [(abs(pos - i)*(abs(pos-i)+1))/2 for i in list_]
return sum(fuel) | 95c24df030e8a2eb93bb281a8aef424c1cf6197d | 635,680 |
def segments_intersect_or_coincide(a, b, c, d):
"""Return True if segments intersect or coincide"""
def overlapping():
if ((c.x < a.x < d.x) or (c.x < b.x < d.x) or
(c.y < a.y < d.y) or (c.y < b.y < d.y) or
(c in (a, b)) or (d in (a, b))):
return True
... | c2e5e9cef5fa2da10f7c3c61fa43c3664ac7c5e0 | 635,684 |
def is_variable(x):
"""
Checks if the provided expression x is a variable, i.e., a string that
starts with ?.
>>> is_variable('?x')
True
>>> is_variable('x')
False
"""
return isinstance(x, str) and len(x) > 0 and x[0] == "?" | 6eca19d849bfc318f96b54980e1c63d2f8845850 | 635,687 |
def ozip(*optionals):
"""Zip optional values. Return None if one value or the other is None."""
return None if any(x is None for x in optionals) else tuple(optionals) | 1b71b721244d2e922c86848564461600671645b1 | 635,688 |
def check_fizz(number: int) -> str:
"""If a integer is divisible by three function outputs fizz
Args:
number (int): integer to check if divisible by three
Returns:
str: returns fizz if divisible by three, else continues
Examples:
>>> check_fizz(3)
'fizz'
>>> ch... | 35026ef713b0fa3849f0954b7e5df75a8fa72222 | 635,689 |
def add_lower(line):
"""Returns if the upper case string is different from the lower case line
Param:
line (unicode)
Returns:
False if they are the same
Lowered string if they are not
"""
line_lower = line.lower()
if line != line_lower:
return line_lower
else... | 440bcb97cf3af831856b9eab2580e7c7cc407294 | 635,692 |
def encode_labels(label: str, label2id: dict, other_class: int) -> int:
""" Encodes labels with corresponding labels id. If relation is unknown, returns special id for unknown relations"""
return label2id.get(label, other_class) | 137c38d41333f6d6cdf403890a63ad90d85ee63f | 635,693 |
import torch
def check_device(device):
"""Check torch device validity."""
if isinstance(device, str):
device = torch.device(device)
if not isinstance(device, torch.device):
raise TypeError("Specify device as torch.device or as string : 'cpu','cuda',...")
if device.type != 'cpu':
... | aef225b71748fe4823b59d85feec84975baae097 | 635,696 |
import getpass
def secure_input(prompt: str) -> str:
"""Get secure input without showing it in the command line.
Args:
prompt (str): The prompt asking the user to input.
Returns:
str: The secure input.
"""
return getpass.getpass(prompt + ' ') | b02befc04196873e793d17820a4d5a010c400d86 | 635,697 |
def SplitLines( contents ):
"""Return a list of each of the lines in the byte string |contents|.
Behavior is equivalent to str.splitlines with the following exceptions:
- empty strings are returned as [ '' ];
- a trailing newline is not ignored (i.e. SplitLines( '\n' )
returns [ '', '' ], not [ '' ] ).""... | 550fa8e48f8672378fa863c69d1f1696135bdfc5 | 635,699 |
def scan_for_benchmark_versions(bmkdir):
"""Scan subdirectories of a benchmark Directory 'bmkdir' to find
benchmark versions. Return a sequence containing all benchmark
version names."""
srcdir = bmkdir.getChildByName('src')
srcdir.scan()
return srcdir.getScannedChildren() | f6e262e6032e9b413ca47faf02f61a3f16fb1a80 | 635,701 |
def get_lattice(lattice, alat, rescale = False):
"""
Compute the lattice vectors. If rescale = True the vectors are expressed in units
of the lattice constant.
Args:
lattice (:py:class:`array`) : array with the lattice vectors. The i-th
row represents the i-th lattice vectors in car... | 791dd282b5d7f829c21d11999aa86ecf182f528a | 635,702 |
from typing import BinaryIO
def is_real_file(the_input: BinaryIO) -> bool:
"""
Determine if the file-like object is associated with an actual file.
This is mainly to consider suitability for establishment of a numpy.memmap.
Parameters
----------
the_input : BinaryIO
Returns
-------
... | 04427b6f801bbfad083adecd9117df67c20535ac | 635,705 |
def jumlah_deret_geometri(utama: int, rasio_umum: int, jumlah: int) -> int:
"""
Menghitung jumlah deret geometri
>>> jumlah_deret_geometri(1, 2, 10)
1023.0
>>> jumlah_deret_geometri(1, 10, 5)
11111.0
>>> jumlah_deret_geometri(0, 2, 10)
0.0
"""
if rasio_umum == 1:
# Rumus ... | 314228d51f4f08bcb6e77a93de55f4b714615e40 | 635,708 |
def convert_string(*, start='|', newlines=True):
"""Return a function that can be used as a converter.
The default converter ``str`` handles multiline values like
:class:`~configparser.ConfigParser`, i.e. preserving newlines but
ignoring indentations (because nothing gets realy converted).
A conve... | c1c29aca537f5669deafa15eae3608a21d0f3859 | 635,712 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.