content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def get_exposure_id(exposure):
"""Returns exposure id.
"""
expinf = exposure.getInfo()
visinf = expinf.getVisitInfo()
expid = visinf.getExposureId()
return expid | a269a08cd62b629d65db803d92d6e6356b76feab | 41,508 |
import re
def escapeRegex(text):
"""
Escape string to use it in a regular expression:
prefix special characters « ^.+*?{}[]|()\$ » by an antislash.
"""
return re.sub(r"([][^.+*?{}|()\\$])", r"\\\1", text) | 97f13b05996daf2a7d01ade0e428244bed156af4 | 41,509 |
def results_query_part(entity):
""" Generates the results part of the query. The results contain
all the entity's fields as well as prefetched relationships.
Note that this is a recursive function. If there is a cycle in the
prefetched relationship graph, this function will recurse infinitely.
Arg... | 63f1e613c67bc1591218d965cc20486f5624c748 | 41,510 |
def dataframe_cleaner(df):
"""This function takes in a pandas dataframe
and gets rid of columns with 25% percent
of null data. It returns a dataframe"""
num_nan = {}
for col in df:
num_nan[col]=df[col].isnull().sum()
colums = []
for colum,nan in sorted(num_nan.items(), k... | 2a105f3b59c6d3b30e7fa2ec37dc5bd62bf951ad | 41,511 |
def none(active):
"""No tapering window.
Parameters
----------
active : array_like, dtype=bool
A boolean array containing ``True`` for active loudspeakers.
Returns
-------
type(active)
The input, unchanged.
Examples
--------
.. plot::
:context: close-fi... | e323f7e153049a4f663688d7bee4b73bd8dd1ca9 | 41,513 |
import re
def get_sandwich(seq, aa="FYW"):
"""
Add sandwich counts based on aromatics.
Parameters:
seq: str, peptide sequence
aa: str,
amino acids to check fo rsandwiches. Def:FYW
"""
# count sandwich patterns between all aromatic aminocds and do not
# distinguish... | d8df68a1873d3912aa64fc91563aae9827da324c | 41,514 |
import torch
def pad_to_size(tensor, sizes, axes=-1, before_and_after=False,
mode='constant', constant_values=0):
""" Pads tensor to a given size along specified axis. """
if isinstance(sizes, int):
sizes = [sizes]
if isinstance(axes, int):
axes = [axes]
for i, ax in en... | 344b08976b289aa1a5f05e30240fac0efbd9adc0 | 41,516 |
def pure_literal(ast_set):
"""
Performs pure literal rule on list format CNF
:param: Result of cnf_as_disjunction_lists
:return: CNF with clauses eliminated
>>> pure_literal([['a']])
[]
>>> pure_literal([[(Op.NOT, 'a')], ['x', (Op.NOT, 'y'), 'b'], ['z'], ['c', 'd']])
[]
>>> pure_lite... | 1f90b738d3085ea81c8e1a752e50e93d2e17c1bc | 41,517 |
import subprocess
def run_raw_cli(cmd, print_output=True):
"""Runs the command with `dcos` as the prefix to the shell command
and returns the resulting output (stdout seperated from stderr by a newline).
eg. `cmd`= "package install <package-name>" results in:
$ dcos package install <package-name>
... | 94edd528e9df5ee08dd342394f7b082557a685cd | 41,518 |
def is_param_free(expr) -> bool:
"""Returns true if expression is not parametrized."""
return not expr.parameters() | e9dadcaae0c9c0cdcffe1afe5202925d98c6b4fb | 41,519 |
import os
from pathlib import Path
def find_installed_cargo_packages(env):
"""Find out which prefix contains each of the dependencies.
:param env: Environment dict for this package
:returns: A mapping of package names to paths
:rtype dict(str, Path)
"""
prefix_for_package = {}
for prefix ... | bf96d8a8cbcb5f2a7c9367dd4a50c9e6edfa0d87 | 41,520 |
def getSecret():
"""
parses credentials.json and allows other program files to access database password for user 'rcos' to create tables/schemas
Returns:
list of size 1 containing password for user 'rcos' in database
"""
f = open("secret.txt", 'r')
return (f.read().split('\n')) | f17528dc32d69fc2b94c9644236f52749d5f249a | 41,521 |
def null_count(df):
"""
Returns the number of null values in the input DataFrame
"""
return df.isna().sum().sum() | d92582292a01412df3433cfaa69ec68a92057301 | 41,522 |
def get_armstrong_value(num):
"""Return Armstrong value of a number, this is the sum of n**k
for each digit, where k is the length of the numeral.
I.e 54 -> 5**2 + 4**2 -> 41.
Related to narcisstic numbers and pluperfect digital invariants.
"""
num = str(num)
length = len(num)
armstrong_... | fd0692566ab0beffb785c1ac4fbd4aa27893cfbf | 41,523 |
import json
def serialize(c):
"""
Takes a message and turns it into a json string.
"""
if c.Class == 'Image':
c.encodeB64()
return json.dumps(c, default=lambda o: vars(o)) | 7342b95b7e3f0e4f2391be8ccba98abe631eb228 | 41,525 |
import re
def convert_bert_word(word):
"""
Convert bert token to regular word.
"""
return re.sub("##|\[SEP\]|\[CLS\]", "", word) | f7f7d95fd7fd90b55a104ce13e10b08f6ae0c9f0 | 41,526 |
def cleanly_separate_key_values(line):
"""Find the delimiter that separates key from value.
Splitting with .split() often yields inaccurate results
as some values have the same delimiter value ':', splitting
the string too inaccurately.
"""
index = line.find(':')
key = line[:index]
value = line[index + 1:]
r... | d790f6bca2b52ee87bce01467a561901ba08655d | 41,527 |
def batch(tensor, batch_size = 50):
""" It is used to create batch samples, each batch has batch_size samples"""
tensor_list = []
length = tensor.shape[0]
i = 0
while True:
if (i+1) * batch_size >= length:
tensor_list.append(tensor[i * batch_size: length])
return tens... | 2b4b10520fd72b90ebe1239b7f52e61ba442484d | 41,528 |
def binary_search1():
"""
Input: nums = [-1, 0, 3, 5, 9, 12], target = 9
Output: 4
Explanation: 9 exists in nums and its index is 4
"""
nums = [-1, 0, 3, 5, 9, 12]
target = 9
nums = [-1, 0, 3, 5, 9, 12]
target = 2
left, right = 0, len(nums) - 1
while left <= right:
... | e50916b577a7deec4829b69c5e730c71845fee4d | 41,529 |
def pack():
"""packs content."""
return 0 | b440220cddbda9ef2358ab5e9cf34a70ebb90286 | 41,530 |
def mse(predictions, targets):
"""Compute mean squared error"""
return ((predictions - targets) ** 2).mean() | 516c8767731577db36dc4b503c179c034fca1166 | 41,531 |
def _command(register_offset, port_number, register_type):
"""Return the command register value corresponding to the register type for a given port number and register offset."""
return (register_offset * register_type) + port_number | d09815a2451e86448e0da280c8b037b59cfbd87b | 41,532 |
def fetch_synonyms(what):
"""
fetch_synonyms
Parameter(s): what - The region type. Use to determine which synonym list to return.
Return: syns - A list of strings containing synonyms of 'what'.
Description: Takes in a string and returns a list containing the string and several synonyms.
"""
... | 4e4458199aa59494ac9331884ab86789c922829d | 41,533 |
def tile_to_screen(pos, dims, off, p, screen_height=None):
"""Take tile coords and convert to screen coords
by default converts into bottom-left screen coords,
but with height attribute supplied converts to top-left
returns the bottom-left position of the tile on the screen"""
offx, offy = off
... | 86c09d8cec52c79acf5a9b503120419cf823acb6 | 41,534 |
import os
import glob
import json
def extract_files_from_dir(results_dir_path):
"""
Checks if existent an then extracts relevant files (params.pkl, variant.json) from results_dir_path
:param results_dir_path: directory which shall be evaluated
:return: variant_dict with additional entries 'params_pick... | fdcdfe3287a5dd04a407490593e732b1d98568ae | 41,536 |
import math
def myceil(x, base=10):
"""
Returns the upper-bound integer of 'x' in base 'base'.
Parameters
----------
x: float
number to be approximated to closest number to 'base'
base: float
base used to calculate the closest 'largest' number
Returns
-------
n_h... | 6e52b99755cdd25b882f707c54c3ff27f8ff279e | 41,537 |
import math
def _assign_shard_id_to_roidb(roidb, num_splits, tot_vids):
"""
Returns:
list with one element for each entry in roidb
(shard_dir_name,
(start_frame_id (0-indexed, included),
end_frame_id (0-indexed, not included)))
"""
shards = []
vids_per_job ... | 0bbe1bfeb87d2b3b6e7a6cc510299fedbc26f772 | 41,538 |
import sys
def progress_factory(message):
"""
"""
def progress(position, total):
"""
"""
done = int((position / total) * 100)
sys.stdout.write('\r{}: {:2d}%'.format(message, done))
sys.stdout.flush()
return progress | e841ceb35e67a41caeae5b6844c6458ed1be8a16 | 41,539 |
def verifyTraceConstraints(graph):
"""
"""
for neg in graph.layers["nterms"]:
if graph.traceConstraint(graph.layers["$"], neg):
return False
for pos in graph.layers["pterms"]:
if not graph.traceConstraint(graph.layers["$"], pos):
return False
return True | 09939e3c13dec1e41e4a570eaf874b9fc01ccc89 | 41,541 |
def get_branch_name(ref):
"""
Take a full git ref name and return a more simple branch name.
e.g. `refs/heads/demo/dude` -> `demo/dude`
:param ref: the git head ref sent by GitHub
:return: str the simple branch name
"""
refs_prefix = 'refs/heads/'
if ref.startswith(refs_prefix):
... | bb7e791c6dac430fef9a38f8933879782b943fd1 | 41,542 |
import torch
import sys
def load_esm_model(model, use_gpu=True):
"""
Load an ESM model
"""
esm_model, alphabet = torch.hub.load("facebookresearch/esm:main", model)
batch_converter = alphabet.get_batch_converter()
esm_model = esm_model.eval()
if torch.cuda.is_available() and use_gpu:
... | 40860bf7bff72f5a9d8c1408a18a767fd5c87daa | 41,544 |
def test_auto(auto):
"""Test automatic setting."""
assert auto.foo == 42
return True | b8b9cbcbdaf407539fdb0509645054867d248200 | 41,545 |
def stdin(sys_stdin):
"""
Imports standard input.
"""
return [int(x.strip()) for x in sys_stdin] | 54964452384ae54961472328e603066f69391957 | 41,546 |
from typing import Tuple
def parse_interval(interval: str) -> Tuple[str, str, str]:
"""
Split the interval in three elements. They are, start time of the working day,
end time of the working day, and the abbreviation of the day.
:param interval: A str that depicts the day, start time and end time
... | f2bac53a1b56e1f6371187743170646c08109a27 | 41,547 |
def surrogate_loss(policy, all_obs, all_actions, all_adv, old_dist):
"""
Compute the loss of policy evaluated at current parameter
given the observation, action, and advantage value
Parameters
----------
policy (nn.Module):
all_obs (Variable):
all_actions (Variable):
all_adv (Variab... | 26e0f53e91a9537a4b9d0bfc3a3122dbe4917fc2 | 41,550 |
def _get_zero_one_knapsack_matrix(total_weight: int, n: int) -> list:
"""Returns a matrix for a dynamic programming solution to the 0/1 knapsack
problem.
The first row of this matrix contains the numbers corresponding to the
weights of the (sub)problems. The first column contains an enumeration of
... | bc96eb43f487b6ad20b143c177474ba04afc2319 | 41,551 |
def get_bus_stop_index(bus_stop_osm_id, bus_stop_osm_ids, start):
"""
:param bus_stop_osm_id: int
:param bus_stop_osm_ids: [int]
:param start: int
:return: bus_stop_index: int
"""
bus_stop_index = -1
for i in range(start, len(bus_stop_osm_ids)):
if bus_stop_osm_ids[i] == bus_st... | b294b766bb3151436c0dd0dad1c1e706b5f33158 | 41,552 |
def read_atom_file(file):
"""Read file with atoms label
Args:
file (str): Name of file with atoms labels
Returns:
list: atoms labeled as <Residue Name> <Atom Name>
"""
atoms = [line.rstrip('\n').split() for line in open(file, "r")]
atoms = [[a[0] + " " + aa for aa in a[1::]] fo... | 3d85dff55f7165d1c9b747eb75d395ec03f5b3ce | 41,554 |
def combine_bolds(graph_text):
"""
Make ID marker bold and remove redundant bold markup between bold elements.
"""
if graph_text.startswith("("):
graph_text = (
graph_text.replace(" ", " ")
.replace("(", "**(", 1)
.replace(")", ")**", 1)
.replace(... | b87afc51de6bb1e83c0f8528773e50f5d797fe2d | 41,555 |
def format_id(kepler_id):
"""Formats the id to be a zero padded integer with a length of 9 characters.
No ID is greater than 9 digits and this function will throw a ValueError
if such an integer is given.
:kepler_id: The Kepler ID as an integer.
:returns: A 0 padded formatted string of length 9.
... | 427726b825f6ee1c4a20c07d098a3a063c18a0c1 | 41,556 |
import argparse
def parse_args():
"""argument parser"""
parser = \
argparse.ArgumentParser(description='Check tensorflow split correctness.')
parser.add_argument('--tfmodel_path', type=str, default='',
required=True,
help="Tensorflow pb model path")
parser.add_a... | 6f2b5eeb4189cc944e88de1ea235455254a7ae05 | 41,558 |
def rev_comp(s):
"""A simple reverse complement implementation working on strings
Args:
s (string): a DNA sequence (IUPAC, can be ambiguous)
Returns:
list: reverse complement of the input sequence
"""
bases = {
"a": "t", "c": "g", "g": "c", "t": "a", "y": "r", "r": "y", "w"... | 3fd61300016da5e8546f0c00303a8477af79902f | 41,559 |
def sumIO(io_list, pos, end_time):
"""
Given io_list = [(timestamp, byte_count), ...], sorted by timestamp
pos is an index in io_list
end_time is either a timestamp or None
Find end_index, where io_list[end_index] is the index of the first entry in
io_list such that timestamp > end_time.
Sum the byte_cou... | a6b36148e05ac57f599bc6c68ffac242020dc65f | 41,561 |
def gap(gap_size=5):
"""Returns a given number of whitespace characters.
Parameters
----------
gap_size : int, optional
Number of whitespace characters to be printed.
Returns
-------
str
Whitespace.
"""
gap_str = gap_size*' '
return gap_str | 048fb5da573b392b00a4def446e9fb74bfd78598 | 41,563 |
def get_main_folder_name(item_container):
""" liefert den Namen der Hauptseite """
ic = item_container.get_parent()
while ic.item.integer_2 >=2:
ic = ic.get_parent()
return ic.item.name | ce1f8e463be99024f2dccf6dfdc0051aeaa88cd3 | 41,564 |
import subprocess
def get_conda_envs():
"""Get a list of all conda environments on the system.
Returns
-------
list
Name (str) of all the conda environments returned by "conda env list"
"""
output = subprocess.run(["conda", "env", "list"], capture_output=True, check=True)
lines = ... | 6e5d931474327eaa9e351c8d1937644f0ef4dbac | 41,565 |
def is_child_class(target, base):
""" Check if the target type is a subclass of the base type and not base type itself """
return issubclass(target, base) and target is not base | 731c551149f94401a358b510aa124ee0cba6d0bd | 41,567 |
import os
def ignore_files(directory, files) -> list:
"""Callable that returns list of files to be ignored while copying tree.
Ignore files
"""
return [f for f in files if os.path.isfile(os.path.join(directory, f))] | 505601236e362035642aced6324f0b9d93f55947 | 41,568 |
def get_pyramid_single(xyz):
"""Determine to which out of six pyramids in the cube a (x, y, z)
coordinate belongs.
Parameters
----------
xyz : numpy.ndarray
1D array (x, y, z) of 64-bit floats.
Returns
-------
pyramid : int
Which pyramid `xyz` belongs to as a 64-bit int... | 8fe2fbc727f13adf242094c3b0db3805af31a1e9 | 41,569 |
import copy
def get_midpoint_radius(pos):
"""Return the midpoint and radius of the hex maze as a tuple (x,y), radius.
Params
======
pos: PositionArray
nelpy PositionArray containing the trajectory data.
Returns
=======
midpoint: (x0, y0)
radius: float
"""
# make a loc... | 76290309f12e00b6a487f71b2393fabd8f3944ac | 41,570 |
import threading
def Lockable(cls):
"""
This class decorator will add lock/unlock methods to the thusly decorated
classes, which will be enacted via an also added `threading.RLock` member
(`self._rlock`)::
@Lockable
class A (object) :
def call (self) :
pr... | 6a779306db6d4882e1e54ad117c864cb03cf058a | 41,572 |
def dictzip(keys,values):
""" zips to lists into a dictionary """
#if not keys or not values:
# raise Exception("Bad params")
#if len(keys) != len(values):
# raise
d = {}
for x in list(zip(keys,values)):
d[x[0]] = x[1]
return d | 66579650a6b126ea16ed118b8d62865feeef16d2 | 41,573 |
from pathlib import Path
from typing import Tuple
from typing import List
def listdir_grouped(root: Path, ignore_folders=[], include_hidden=False) -> Tuple[List, List]:
"""Dizindeki dosya ve dizinleri sıralı olarak listeler
Arguments:
root {Path} -- Listenelecek dizin
Keyword Arguments:
... | 13d2ea09cafd3b4062714cbf151c0a4b290616e1 | 41,574 |
from typing import Optional
from typing import List
def _with_config_file_cmd(config_file: Optional[str], cmd: List[str]):
""" Prefixes `cmd` with ["--config-file", config_file] if
config_file is not None """
return (["--config-file", config_file] if config_file else []) + cmd | a7a93f2b089e4265a22fb7fd0ccced1e78e1c55c | 41,575 |
def _clip_points(gdf, poly):
"""Clip point geometry to the polygon extent.
Clip an input point GeoDataFrame to the polygon extent of the poly
parameter. Points that intersect the poly geometry are extracted with
associated attributes and returned.
Parameters
----------
gdf : GeoDataFrame, ... | c7f21807d28f37044a4f36f4ededce26defbb837 | 41,578 |
def hamiltonian_mse_blocks(blocks1, blocks2, scale=1.0):
""" Average element-wise error between Hamiltonians in block form.
Defined so that the sum over blocks equals the overall MSE in the matrix form.
"""
mse = {}
nel = 0
for k in blocks1.keys():
mse[k] = {}
for b in blocks1[k... | ec74bdde9092cc693f39f7bcc4ac89b40c771eca | 41,582 |
import re
def get_relval_id(file):
"""Returns unique relval ID (dataset name) for a given file."""
dataset_name = re.findall('R\d{9}__([\w\d]*)__CMSSW_', file)
return dataset_name[0] | 5b3369920ae86d7c4e9ce73e1104f6b05779c6d4 | 41,584 |
import os
def librato_test_space(test_space=os.environ.get('LIBRATO_TEST_SPACE')):
"""Return librato test space from an environment variable"""
return test_space | b97d313be8e0a1192dedcc6bc0894a76c71dc27c | 41,585 |
def splitdrive(path):
"""Split a pathname into drive and path specifiers.
Returns a 2-tuple "(drive,path)"; either part may be empty.
"""
# Algorithm based on CPython's ntpath.splitdrive and ntpath.isabs.
if path[1:2] == ':' and path[0].lower() in 'abcdefghijklmnopqrstuvwxyz' \
and (pa... | ed50877516130669cfe0c31cd8a6d5085a83e7c6 | 41,586 |
def triedctk():
"""
Les méthodes ctk : Cartes Topologiques de Kohonen
findbmus : Détermine les référents les plus proches (Best Match Units)
mbmus : Trouve les multiples bmus dans l'ordre des plus proches
errtopo : Erreur topologique (cas d'une carte rectangulaire uniquement)
findhits : C... | 74444be34275e5842e8930b6431796e925df09b1 | 41,587 |
import re
def safe_filename(url):
"""
Sanitize input to be safely used as the basename of a local file.
"""
ret = re.sub(r'[^A-Za-z0-9]+', '.', url)
ret = re.sub(r'^\.*', '', ret)
ret = re.sub(r'\.\.*', '.', ret)
# print('safe filename: %s -> %s' % (url, ret))
return ret | 4f43984c35678e9b42e2a9294b5ee5dc8c766ac6 | 41,588 |
async def combine_channel_ids(ctx):
"""Combines all channel IDs.
Called by `channel_setter` and `channel_deleter`.
Args:
ctx (discord.ext.commands.Context): context of the message
Returns:
list of int: of Discord channel IDs
"""
channels = []
if not ctx.message.channel_me... | 1351faa7e49ce026d4da04c2c8886b62a5f294c3 | 41,589 |
def get_role_arn(iam, role_name):
"""Gets the ARN of role"""
response = iam.get_role(RoleName=role_name)
return response['Role']['Arn'] | ab6ed4fa7fd760cd6f5636e77e0d1a55372909a8 | 41,590 |
def wordCount(wordListRDD):
"""Creates a pair RDD with word counts from an RDD of words.
Args:
wordListRDD (RDD of str): An RDD consisting of words.
Returns:
RDD of (str, int): An RDD consisting of (word, count) tuples.
"""
return wordListRDD.map(lambda w: (w, 1)).reduceByKey(lambd... | 061581ef8e7719fe39d0209d3409500da0e33d2a | 41,592 |
def is_ascii(identifier) -> bool:
"""
print(is_ascii('\\xAA'))
print(is_ascii('\\u02C6-'))
print(is_ascii('0x10000'))
print(is_ascii('你好'))
"""
if ('0x' in identifier) or ('\\x' in identifier) or ('\\u' in identifier): # hex or unicode
return False
else:
return str.isasc... | 36b6ceae30adc0263213b3975e7d9200c07c302e | 41,593 |
import logging
def get_logger(name: str, level: int = logging.INFO) -> logging.Logger:
"""
Creates a logger with the given attributes and a standard formatter format.
:param name: Name of the logger.
:param level: Logging level used by the logger.
:return: The newly or previously created Logger ob... | 7348e1775d236e34e25d9810d71db59a7faff88e | 41,594 |
def write_raw(code, input):
""" write <args> - Send a raw command to the server. WARNING THIS IS DANGEROUS! Owner-only. """
secure = '{red}That seems like an insecure message. Nope!'
r = input.group(2).encode('ascii', 'ignore')
bad = ['ns', 'nickserv', 'chanserv', 'cs',
'q', 'authserv', 'bots... | 64a4aa52fe29f3ae9870436c0676739d15f9f755 | 41,595 |
def gera_estados(quantidade_estados: int) -> list:
"""
Recebe uma quantidade e retorna uma lista com nomes de estados
"""
estados: list = []
for i in range(quantidade_estados):
estados.append('q'+str(i))
return estados | 555ff4821626121b4e32d85acfa1f2ef2a7b08bb | 41,596 |
def valid_cards_syntax(cards_str):
""" Confirm that only numeric values separated by periods was given as input """
cards = cards_str.split('.')
for c in cards:
if not c.isnumeric():
return 'Cards must contain only digits 0-9 separated by periods'
return None | 8e3811505075269d2b1a37751c14017e107ce69b | 41,597 |
def togti(boollst, tlst):
"""得到bool值列表和与其对应的时间列表的时间段"""
boolcha = boollst[1:]^boollst[:-1] #寻找边界,TF翻转时为T
boolcha[0] = boollst[0]^boolcha[0]
boolcha[-1] = boollst[-1]^boolcha[-1]
timeint = tlst[:-1][boolcha]
time0 = timeint[::2]; time1 = timeint[1::2]
#timestart, timestop
return time0, ti... | 7b172e560927c3ae1665299bc2256c7607856634 | 41,598 |
def db_to_amplitude(amplitude_db: float, reference: float = 1e-6) -> float:
"""
Convert amplitude from decibel (dB) to volts.
Args:
amplitude_db: Amplitude in dB
reference: Reference amplitude. Defaults to 1 µV for dB(AE)
Returns:
Amplitude in volts
"""
return reference... | d1a2a4a1c82ad2d3083b86687670af37dafa8269 | 41,599 |
def hsv2rgb(hsvColor):
"""
Conversione del formato colore HSV in RGB
:param hsvColor: Stringa del colore HSV
:return: Tripla RGB
"""
# hsvColor = '#1C8A88' #LOW
# hsvColor = '#BDEFEF' #HIGH
h = hsvColor.lstrip('#')
rgb = tuple(int(h[i:i + 2], 16) for i in (0, 2, 4))
return rgb... | a836d70f791cb1cca553ea8806b694cc26c11a0a | 41,600 |
def get_title(soup):
"""
Returns the product title. If there is an unknown character in the title, it
returns it as '?'.
"""
title = soup.find('h1', attrs={'class': 'it-ttl'})
if not title:
return "N/A"
for i in title('span'):
i.extract()
title = title.get_text() # .e... | ea4a6d4e53f57c0ba0419e9268a80a7a21d7ad21 | 41,601 |
def simple_expand_spark(x):
""" Expand a semicolon separated strint to a list (ignoring empties)"""
if not x:
return []
return list(filter(None, x.split(";"))) | 1d4a9f8007f879c29770ea0ea8350a909b866788 | 41,602 |
def STRING_examples(request):
"""
:return: Tuple(ENSPs_list, TaxID(str))
"""
return request.param | 23d7f24850ff31e49d29cbdf452a9de45cda0269 | 41,603 |
def full_code(code,is_index=True,is_dot=False):
"""补全证券代码
code:6位证券代码
is_index:是否是指数代码
return:补全的代码
"""
if is_dot:
sh = 'sh.'
sz = 'sz.'
else:
sh = 'sh'
sz = 'sz'
if is_index:
if code[0] == '0':
full = sh + code
else:
... | 90aa27209865d5f2c58430ee26e27e1e76a8a2f3 | 41,605 |
def get_output_parameters_of_execute(taskFile):
"""Get the set of output parameters of an execute method within a program"""
# get the invocation of the execute method to extract the output parameters
invokeExecuteNode = taskFile.find('assign', recursive=True,
value=la... | 56ba0c1f1941a72174befc69646b4bdb6bc9e009 | 41,606 |
from typing import Union
from typing import Tuple
from typing import Dict
def generate_collector_dicts(collect_agents) -> Union[Tuple[Dict, Dict], Dict]:
"""
This returns two dictionaries consisting of as many key/value pairs as the elements
contained within the @model_reporters, @agent_reporters paramete... | 7a813319c29d1bce8bc11fd6a4e7a22e86445ef5 | 41,607 |
def drop_empty(facets):
"""Prevent any 'bucket' type facets from being displayed on the portal
if the buckets contain no data. This also preserves backwards
compatibility for v0.3.x"""
return [facet for facet in facets if facet.get('buckets') != []] | 83059a6f91eb1d7f3e13ee99d93477de1b2dc7b4 | 41,608 |
def split_addr(ip_port: tuple[str, int]) -> tuple[int, ...]:
"""Split ip address and port for sorting later.
Example
--------
>>> split_addr(('172.217.163.78', 80))
>>> (172, 217, 163, 78, 80)
"""
split = [int(i) for i in ip_port[0].split(".")]
split.append(ip_port[1])
return tupl... | d768e493d9bdfe07923927c7d157683515c52d7d | 41,610 |
def is_set(bb, bit):
""" Is bit a position `bit` set? """
return (bb & 1 << bit) != 0 | 4990ccb7eb796da8141bf2b3aec7741addfe2a0c | 41,611 |
def redirect(status, location, start_response):
"""
Return a redirect code. This function does not set any cookie.
Args:
status (str): code and verbal representation (e.g. `302 Found`)
location (str): the location the client should be redirected to (a URL)
start_response: the start_... | 7fb5569d5872be69285a29c404b04df7ff7eef74 | 41,612 |
import re
def _parse_path_string(variables, path):
"""
Parse the longest prefix of 'path'
made of any characters beyond '{' and '}'.
"""
pattern = re.compile(r"([^{}]*)(.*)")
match = pattern.match(path)
if match:
string = match.group(1)
rest = match.group(2)
ret... | 48bacdde239cf4c074cf59801363b55f0dc5c135 | 41,613 |
def all_data(self):
"""
# 猴子补丁,增加Query对象all_data 方法返回字典
"""
field = tuple([f["name"] for f in self.column_descriptions])
all_info = self.all()
result_data = []
for item in all_info:
result_data.append(dict(zip(field, item)))
return result_data | 2132f759bac5e321eb2995dffda3c8660de378dc | 41,614 |
def count_att(data, column, value):
"""
:param data: Pandas DataFrame
:param column: specific column in the dataset
:param value: which value in the column should be counted
:return: probability of (value) to show in (column), included Laplacian correction
"""
dataset_len = len(data)
try... | 4dd11d02257ab2a5ac7fcc0f366de0286cdc84f7 | 41,615 |
def _get_method_for_string(method_str, the_globals=None):
"""
This setting will provide a way to move easily from
'my_method' --> my_method the function
"""
if not the_globals:
the_globals = globals()
return the_globals[method_str] | de9fdad657cd3084b20a7ed5ea00c70b61e49803 | 41,616 |
from unittest.mock import patch
def patch_data_collector():
"""
Replaces DataCollector with a dummy mock.
"""
def decorator(old_function):
patcher = patch("insights.client.client.DataCollector")
return patcher(old_function)
return decorator | c588bae380c59fb1c3e1bebd6f56d3863fb8958e | 41,617 |
def _afunc(arg1, arg2):
"""
Used to concatenate two lists inside a reduce call
"""
return arg1 + arg2 | 5895aeabebf93e714dfefbd7ea0a187eff57a88f | 41,618 |
def process(text):
"""Метод, которым будет обрабатываться каждое текстовое сообщение.
В нашем случае обработка следующая: разбить строку по пробелам -> перевести
строки в числа -> посчитать сумму -> вернуть ответ.
Аргументы:
text (str): Строка, которую необзодимо обработать.
Возвращает:
... | 9339758f6b199307cdbf192b9d8a1b9a334576c3 | 41,619 |
def get_height(root):
"""
>>> assert(get_height(None) == -1)
>>> root = Node(1)
>>> assert(get_height(root) == 0)
>>> root = Node(1, Node(2))
>>> assert(get_height(root) == 1)
>>> root = Node(1, Node(2, Node(3)))
>>> assert(get_height(root) == 2)
"""
if root is None:
ret... | 340783583252922d796a3988da76b15678ca8fc7 | 41,621 |
def null_getter(d, fld, default="-"):
"""
Return value if not falsy else default value
"""
return d.get(fld, default) or default | 7970045e766c60e96bca005f86d214e21762f55c | 41,625 |
def convert_vars_to_readable(variables_list):
"""Substitutes out variable names for human-readable ones
:param variables_list: a list of variable names
:returns: a copy of the list with human-readable names
"""
human_readable_list = list()
for var in variables_list:
if False: # var in V... | cfc8b9309a728f228dbd09ce6fdb30d849c3ff62 | 41,627 |
import os
import requests
import json
def _get_jama_item_types():
"""GETs item types defined in a Jama instance
Args:
None
Returns:
Array: objects of users data in the Jama instance
"""
url = os.environ['JAMA_URL'] + "/rest/latest/itemtypes?maxResults=50"
resp = requests.get... | 0eb47b4fc6c6a33b913e4285f1b58bd78f28c873 | 41,629 |
from typing import Dict
import re
import pkgutil
import io
from typing import OrderedDict
import json
def _load_signatures(filepath: str) -> Dict[str, re.Pattern]:
"""Load signatures for blockpage matching.
Args:
filepath: relative path to json file containing signatures
Returns:
Dictionary mapping fi... | a4046adcb4873de4f1de2e0fdd06ab88de7b64b1 | 41,630 |
def get_list_string(data: list, delim: str = '\t', fmt: str = '{}') -> str:
"""Converts a 1D data array into a [a0, a1, a2,..., an] formatted string."""
result = "["
first = True
for i in data:
if not first:
result += delim + " "
else:
first = False
resul... | 25e9bb0e0220776ff79e121bab3bddf99168602d | 41,631 |
def mbar2kPa(mbar: float) -> float:
"""Utility function to convert from millibars to kPa."""
return mbar/10 | 9dcb74581fb099da0d136aad57de1c8ac3cf7c1d | 41,632 |
def user_requested_cassette_replacement(request):
"""Did the user ask to delete VCR cassettes?"""
return request.config.getoption("--replace-vcrs") | 92347f44e845fe67af625fc38e251990dad3aaa7 | 41,636 |
import re
def prep_for_search(string):
"""
Expects a string. Encodes strings in a search-friendy format,
lowering and replacing spaces with "+"
"""
string = re.sub('[^A-Za-z0-9 ]+', '', string).lower()
string = string.replace(" ", "+")
return string | 61a6762598fe3538b2d2e2328bc77de53fba4d74 | 41,638 |
def twoSum(nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
numsSorted = sorted(nums)
n = len(nums)
print(numsSorted)
for i in range(n - 1, 0, -1):
# for j in range(i+1, n):
# if nums[i] + nums[j] == target:
# print(... | 41af967611844b0b34d3a17dff518b293b08311f | 41,639 |
import sys
def write_arpa(prob_list, out=sys.stdout):
"""Convert an lists of n-gram probabilities to arpa format
The inverse operation of :func:`pydrobert.torch.util.parse_arpa_lm`
Parameters
----------
prob_list : list of dict
out : file or str, optional
Path or file object to outpu... | 0c65ca1a63a332cfc50fe807b44e699827a2d76c | 41,640 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.