content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
from pathlib import Path
def get_format(f):
"""tells if file is from calpost or hysplit"""
if isinstance(f, (str, Path)):
with open(f) as ff:
return get_format(ff)
line = next(f)
f.seek(0)
if line.startswith(' TIME-SERIES Output -------- '):
fmt = 'calpost'
elif... | 70e70b9a2ea1f209958a46b363a7033271262050 | 635,482 |
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_integer_input(message="Enter: "):
"""Method Defined to take integer inputs from user with
some default value and avoid exceptions
PARAMETERS\n
message: string to show as prompt for input (default: 'Enter: ')
RETURNS\n
input_value: user input as integer (default: 10)
"""
input_... | 08ea697c20d26cb372c45c5c241abf0dd8dd09b8 | 635,485 |
def is_numeric(s):
"""test if a string is numeric"""
for c in s:
if c in "1234567890-.":
return True
else:
return False | 0af9d2f7399c335d6c5f9afb08ecc8c2dd8fc956 | 635,486 |
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 inverse_gamma_sRGB(ic):
"""Inverse of sRGB gamma function. (approx 2.2)"""
c = ic/255.0
if ( c <= 0.04045 ):
return c/12.92
else:
return pow(((c+0.055)/(1.055)),2.4) | c22f2669049353cefcd1390606d86be706ba75b8 | 635,488 |
async def volume(ctx, volume: int):
"""Changes the player's volume"""
if ctx.voice_client is None:
return await ctx.send("Not connected to a voice channel.")
ctx.voice_client.source.volume = volume / 100
await ctx.send(f"Changed volume to {volume}%") | 918338371cd0e262fee829dceb1cd2f3ef7ae83b | 635,489 |
import pickle
def _load_model_from_local_file(path):
"""Load a scikit-learn model saved as an aiflow artifact on the local file system."""
with open(path, "rb") as f:
return pickle.load(f) | 72a40b2e384ff6b909b829838277d0914535783e | 635,490 |
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 |
import sys
import getopt
def get_args(argv):
"""Get arguments from the command line
:param argv: sys.argv
:return: configfile
"""
syntax = 'Usage: python callattendant.py -c [FILE]'
configfile = None
try:
opts, args = getopt.getopt(argv[1:], "hc:", ["help", "config="])
... | dd0e729ca0034e17ecea1516cb8a297810411236 | 635,492 |
def rax_find_loadbalancer(module, rax_module, loadbalancer):
"""Find a Cloud Load Balancer by ID or name"""
clb = rax_module.cloud_loadbalancers
try:
found = clb.get(loadbalancer)
except:
found = []
for lb in clb.list():
if loadbalancer == lb.name:
fou... | 8c48a49f554a1b101c0067478f964844a153ee10 | 635,493 |
def adjust_schedule_date(instance):
"""If assignment object did not provide any reminder time,
tag's reminder time will be used.
Args:
instance (Assignment): Assignment object.
schedule_date (list): List of reminder times.
"""
# Default value in schedule date is 0 because we have to... | 449b451b0a2a606732227871d8775df9c95b181d | 635,494 |
import os
def ComputeOutputDir(params):
"""Returns the path from the toplevel_dir to the build output directory."""
# generator_dir: relative path from pwd to where make puts build files.
# Makes migrating from make to ninja easier, ninja doesn't put anything here.
generator_dir = os.path.relpath(para... | 9ea8a6e6702ad0a69da64757a2885df4af7efbba | 635,497 |
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 |
import numpy
def count_doubex(occ_orbs, orb_symm, lookup_tabl):
"""Count the number of spin- and symmetry-allowed double excitations from a
given determinant.
Parameters
----------
occ_orbs : (numpy.ndarray, unsigned int)
list of occupied orbitals in the origin determi... | 9d0d6463b53130d84debcab9d8361ed359dec0e7 | 635,501 |
from typing import Any
import numpy
def running_avg(lst: list) -> Any:
"""
Calculate a running average of a list
Parameters
----------
lst: lst
The list to find the average of.
Returns
-------
int
"""
return numpy.unique(numpy.mean(lst, dtype=object)) | 367583dca6fdbec10f3c18c36702384b17f6a260 | 635,503 |
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 |
def load_np_dtype(arr):
""" Load a numpy array """
# Just return first value
return arr.value | 44e309c6dfba3491b37eb2957303504b5431ad41 | 635,505 |
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 macro(func):
"""
Marks the func as a macro.
In S-expressions, macros are given any S-expressions
unevaluated, then the result is evaluated.
"""
func._macro_ = None
return func | f4fcbd01f564168da0e8fb6a617fdbf04def6912 | 635,512 |
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 |
from typing import List
from typing import Any
import re
def _keywords_default_dependencies(
keyword: str, default: str, parent_sections: List[str]
) -> List[Any]:
"""Collects a list of of tuples (keyword, default dependency) within one section.
Both the keyword and the default dependency are lists.
... | 01301f95145db2226cb92b92b40c1008e88b719b | 635,516 |
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 contains_cumulative_interval(scale, interval_size):
"""
Returns true if a scale contains a particular interval.
:param interval_size:
:param scale:
:return:
"""
# This basically amounts to playing blackjack:
# we add up intervals starting from the first, and if we hit the interval size before we exceed it,... | 058ab039bb6352f230ebacb9a3c9e46e968c3e34 | 635,521 |
def mock_avatar_url(self):
"""Avoid libravatar DNS lookups during tests"""
if self.user.email is None:
return None
return "avatar-%s" % self.user.email | 4e084110ad963e099d0c55766afb83443f37a2e3 | 635,522 |
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 |
import sys
def _get_args_for_reloading():
"""Returns the executable."""
main_module = sys.modules["__main__"]
mod_spec = getattr(main_module, "__spec__", None)
if sys.argv[0] in ("", "-c"):
raise RuntimeError(
f"Autoreloader cannot work with argv[0]={sys.argv[0]!r}"
)
i... | 16fbd1efe5539773c4dbd2b8f6f78da968e0c142 | 635,527 |
def magic(current):
"""Fuzz magic header field.
The function just returns the current magic value and provides uniformity
of calls for all fuzzing functions.
"""
return current | 81c0396173d8c0f9f2a25527663e231b9d07a307 | 635,528 |
def flatten_list(items):
""" List flattener helper function """
for i, x in enumerate(items):
while isinstance(items[i], list):
items[i:i+1] = items[i]
return items | 15fe7983186e0893bb4752b77e9e11e1066f6d12 | 635,529 |
import os
def get_bz2_arxivs(dirpath):
"""Return a list of absolute .bz2 filepaths from a given dirpath."""
return [os.path.join(dirpath, filename) for filename in
os.listdir(dirpath) if '.bz2' in filename] | c233f7e4145ba7fef68b53b1e032c2f520905e11 | 635,530 |
def flat_weights_to_model_format(weights_slices, weights_shapes, weights_flat):
"""
Convert flat weights into shape matching model.set_weights
"""
weights = []
for weights_slice, weights_shape in zip(weights_slices, weights_shapes):
layer_weights_flat = weights_flat[weights_slice]
la... | 85214c93891eafe48f727f3aa139308bab8b1276 | 635,531 |
def get_pos_couleur(cercle,nb_couleur,nb_point):
"""renvoi un tableau de la possition des point ranger par couleur
ex : [[5,7,9,22,30,...],[1,2,3,...]] index de la list = numero couleur
valeur = position dans le cercle"""
tab_res = [-1]*nb_couleur
tab_res_int = []
for i in range(0,nb_couleur):
... | ec6fc056f2310ecfe3568d07a97f1480480cd6c3 | 635,532 |
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 tailFile(filename, offset, length):
"""
Read length bytes from the file named by filename starting at
offset, automatically increasing offset and setting overflow
flag if log size has grown beyond (offset + length). If length
bytes are not available, as many bytes as are available are returned.... | 2b9495b041f7f427a5569e1e3005165c1a56c4c3 | 635,535 |
def getUsername(dn):
"""Get the uid/cn of the given DN."""
return dn.split(',')[0].split('=')[1] | 7d741e03cf7380b0da07558beea69d870b0dcc2e | 635,536 |
def set_default_indices():
"""
Sets default dict for columns (placeholders for indices)
"""
fields = ('unique id',
'hospital name',
'city',
'state',
'region')
columns = {}
for field in fields:
columns.setdefault(field, None)
re... | 045b781d18ba0b801d5e0c90f02ca763b2ae0ac4 | 635,537 |
from typing import Tuple
def get_special_pythagorean_triplet(triplet_sum: int) -> Tuple[int, int, int]:
"""Get special Pythagorean triplet, for which `a + b + c = triplet_sum`."""
square_map = {i: i**2 for i in range(1, triplet_sum - 2)}
for a in range(1, triplet_sum // 3):
for b in range(a + 1, (... | 99967024213500121e9f4eab7f552e0cd479d51a | 635,538 |
import argparse
def defineConsole():
"""
defines the program console line commands
"""
parser = argparse.ArgumentParser(description='SBML to BNGL translator')
parser.add_argument('-i', '--input', type=str, help='sbml file', required=True)
parser.add_argument('-r', '--raw', type=str, help='raw ... | d6ae37424c0da46872eaacd2cc263fc97cc63aa9 | 635,540 |
def getErrorTime(segs, mapSpkrs):
"""
This function calculates the speaker error time generated by the speaker diarization system. This involves
iterating over all ground truth speakers identified for the relevant segment and then, if none of those speakers
are mapped to the speaker diarization system ... | 3e10d1d7409f2cefb2d08924d81f344d28d7487a | 635,541 |
import os
def parse_args(parser, parser_server, parser_client):
"""Add arguments for this driver to the parser.
:param parser: Parser
:type parser: Object
:param parser_server: SubParser object
:type parser_server: Object
:param parser_client: SubParser object
:type parser_client: Object
... | 663f873cd2ae5028177a77f59b69054b59b27091 | 635,542 |
import copy
import random
def staticSizeLimit(max_size):
"""Implement a static limit on the size of a GP tree. It may be used to
decorate both crossover and mutation operators. When an invalid (too big)
child is generated, it is simply replaced by one of its parents.
:param max_size: The maximum ... | 21fbc136b22ee032fb3883ab59dc99bd8fa0fa94 | 635,543 |
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 torch
def get_path(batch_size, input_stream, input_channels, device, path_grad):
"""Gets a path."""
return torch.rand(batch_size, input_stream, input_channels, device=device, requires_grad=path_grad,
dtype=torch.double) | bd14330cff834a4a918a6fc985358074630074a2 | 635,545 |
def merge_args(args_opt, cloud_args):
"""dictionary"""
args_dict = vars(args_opt)
if isinstance(cloud_args, dict):
for key_arg in cloud_args.keys():
val = cloud_args[key_arg]
if key_arg in args_dict and val:
arg_type = type(args_dict[key_arg])
... | 4dc6aa132b368cddd7eadd0ab55435c116c2b940 | 635,546 |
def max_value(array_of_data):
"""
Function who work with an array of numbers greater than 0
Parameters:
N: the number of iterations (équivalant to the size of the array)
Returns:
highest_number: the max value of the array is returned as float
"""
N=0
highe... | 89b0c1a844113190b44b0199ce47bf8cb1647442 | 635,548 |
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 os
import subprocess
def _SubprocessCall(cmd, cwd=None):
"""Runs a command in a subprocess.
Args:
cmd: The command to run.
cwd: Working directory to run from.
Returns:
The return code of the call.
"""
if os.name == 'nt':
# "HOME" isn't normally defined on windows, but is needed
... | 960c5543ccd5615c2ce2096e32666ffda27504b1 | 635,550 |
def doFilter(pTable):
"""
for each row, see, which candidate in the subject cell matched best to the rest of the row
remove candidates in other fields accordingly
"""
# get subject cells
subjColIds = pTable.getSubjectCols()
subjCells = pTable.getCells(col_id=subjColIds, unsolved=True)
... | 7df2ae61a646673fa9ff6353d0d82ecadd0653ce | 635,551 |
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 |
import torch
def collate_fn_text_pair(samples):
""" Creates a batch out of samples """
new_samples = []
for a, b in samples:
length = min(len(a), len(b))
new_samples.append([a[:length], b[:length]])
x = torch.LongTensor(new_samples)
return x | ab706d056be187de4da753b2dfa56a303dec8bd5 | 635,553 |
import os
def path_to_git_root(full_path_to_git_repo):
"""
Strips the path of '.git' at the end.
:param full_path_to_git_repo: Full path to git repo.
:return: Full path to git root.
"""
if not full_path_to_git_repo.endswith('.git'):
raise EnvironmentError('No git repo found')
ret... | 34fd88401aaf8615a73b94508a714ed7412a8b39 | 635,555 |
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 |
import subprocess
import sys
def _ExecuteCommand(command):
"""Execute a command in the shell.
Args:
command: list, a list of strings the build a command to execute.
Returns:
A running process.
"""
process = subprocess.Popen(command)
result = process.wait()
if result:
sys.exit(result)
ret... | b893c5a58b5f1b3a08816907ac8a061e4ef7f89e | 635,557 |
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 |
def _sorted_log_paths(log_paths, log_path_re, step_num_to_id=None):
"""Order log paths so that the ones most useful for diagnosing
failure (usually, the latest ones) come first."""
step_id_to_num = dict((v, k) for k, v in (step_num_to_id or {}).items())
def sort_key_for_m_group(m_groups, group_name):
... | 2a43461f40d6f362396842a3c47ea5802ac0c89a | 635,564 |
import fnmatch
import re
def safe_fnmatch(f, pattern):
""" fnmatch will fail if the pattern contains any of it's
key characters, like [, ] or !.
"""
try:
return fnmatch.fnmatch(f, pattern)
except re.error:
return False | 3fe95573b29b0b3dce3453bd11c00bfb2103988d | 635,565 |
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 single_model_specify(single_model):
"""Returns an instance of MultiTaskLSTMCRF initialized with the default configuration file and
a single specified model."""
single_model.specify()
return single_model | f4557c096ee995c880ec52ad03aab1b258fc8b91 | 635,567 |
def linkParentNodesOfSingleLinkedChildren(matchList, srcPL, tgtPL):
"""
If a linked node is the only linked child of its parent, at both source and target,
link the parents too
"""
ml=[]
srcLinkedPos = [s.treeposition() for (s,_t) in matchList ]
tgtLinkedPos = [t.treeposition() for (s,t) in ... | d3bf575d33fd7830fe1a36379e1210dc481a384e | 635,568 |
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 return_contents(entry):
"""ブログのタイトルと本文をつなげて返す"""
title = entry.find("{http://www.w3.org/2005/Atom}title").text
content = entry.find("{http://www.w3.org/2005/Atom}content").text
return f"{title}。\n\n{content}" | 6b2ed231de3de8ff2a9801b9f8a2f727e9680920 | 635,570 |
def _GetClearedFieldsForUrlRedirect(url_redirect, field_prefix):
"""Gets a list of fields cleared by the user for UrlRedirect."""
cleared_fields = []
if not url_redirect.hostRedirect:
cleared_fields.append(field_prefix + 'hostRedirect')
if not url_redirect.pathRedirect:
cleared_fields.append(field_prefi... | e18731087d6324571ba3b9ad4f3da27efb17e69c | 635,571 |
def invert(grid):
"""
Inverts the grid for up/down movement
"""
grid = grid[::-1]
for y in range(len(grid)):
grid[y] = grid[y][::-1]
return grid | cc88ffcb5ec076171338370c0c9ea79544ea6035 | 635,572 |
def check_install(action):
"""Skip install check action
Parameters
----------
action : list
Returns
-------
bool
"""
return action not in ['install', 'upgrade', 'uninstall', 'verify'] | 4e1fc092d33eade36e2abc2c65d1d2e7389e866a | 635,573 |
import argparse
def get_args():
"""Get command-line arguments"""
parser = argparse.ArgumentParser(
description='Warn the captain of imminent danger',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('danger', metavar='danger', help='The imminent danger')
pa... | 54c819b99cbeffb120d5d5230033da68edcef22d | 635,574 |
def zoomToFitSelected():
"""
zoomToFitSelected() -> None
Does a zoom to fit on the selected nodes in the DAG
@return: None.
"""
return None | adc24d351eddbe899e5fcdfeb4c5063ec77ad3d3 | 635,575 |
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 |
import subprocess
def create_blast_database(fasta_str, save_path):
"""
:param fasta_str:
:param save_path:
:return:
"""
with open(save_path + 'fasta.txt', 'w') as f:
f.write(fasta_str)
f.close()
database_filename = save_path + '_database'
# creation of the makeblastdb... | f5deeedc8c92538db846af8d4b9ef6ba7e9cfcd0 | 635,577 |
from typing import List
def _split_docstring(docstring: str) -> List[str]:
"""Divides docstring by splitting on ---, also unindents
first in case of indented docstrings (similar to this one)
"""
lines = docstring.strip().split("\n")
try:
indent_spaces = min(
[len(line) - len(l... | bf01530316cf780b3a5cf8a2d44f6c82e48926bc | 635,579 |
def calc_observables(evt_index, d, l1_p4, l2_p4, k_p4, sets, MAXT3):
"""NON-JAGGED (NORMAL) observables.
Args:
l1_p4:
l2_p4:
k_p4:
Returns:
x: Observables
"""
x = {
}
return x | 9ab3cd16587f4ce517ab6d1e7f0e377294f130d1 | 635,581 |
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 |
import os
def is_non_zero_file(filepath):
"""Module to validate filepath and content presence
"""
return os.path.isfile(filepath) and os.path.getsize(filepath) > 0 | f8c4d9f5ac95733042b95d988dff402f4a7e1c7c | 635,586 |
def get_id(function):
"""Given a function, calculate its identifier.
A identifier is a string in the format ``<module name>:<function name>``,
similarly to the convention used for setuptools entry points.
Note:
This function does not return a Python 3 ``__qualname__`` equivalent.
If th... | 07fdc32804dacbfcdd2f42a732fc1fc1a1f23fa8 | 635,587 |
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 healthcheck():
"""
Return 200 as default
"""
return '', 200 | c94a2c8133ad462a6cf1f5020faac1c9ec716f8e | 635,595 |
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 canonmtu(text):
"""canonicalize a MTU value"""
try:
mtu = int(text)
if (mtu < 1280) or (mtu > 65535):
return None
return str(mtu)
except ValueError:
#print 'canonmtu failed on', text
return None | cfeafa85dfc776aa192e140cfe93f85c8154b429 | 635,598 |
def get_prefered_gpu(gpu_indices, prefered):
"""Move prefered GPU on a first position if it is available."""
if prefered in gpu_indices:
gpu_indices.remove(prefered)
return [prefered, ] + gpu_indices
return gpu_indices | 0f8797db6d2bdcbc3b85925aeb3e7f9f56ffd534 | 635,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.