content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from functools import reduce
def convert_array_to_df(emission_map):
"""
This function converts the emission map dict to a DataFrame where
- 'emission_map' is a dictionary containing at least 'z_var_ave', 'count_var','std_var','q25_var' and'q75_var
"""
def reform_df(df, nr):
"""This subfun... | 171e387ca51f543b522946a213e51040463aec74 | 6,500 |
def add_missing_flows(data):
"""There are some flows not given in ReCiPe that seem like they should be there, given the relatively coarse precision of these CFs."""
new_cfs = {
"managed forest": {
"amount": 0.3,
"flows": [
"occupation, forest, unspecified",
... | e23184bb7363db4777d9f693a3fdc4ace9f8ff14 | 6,501 |
from typing import List
def cglb_conjugate_gradient(
K: TensorType,
b: TensorType,
initial: TensorType,
preconditioner: NystromPreconditioner,
cg_tolerance: float,
max_steps: int,
restart_cg_step: int,
) -> tf.Tensor:
"""
Conjugate gradient algorithm used in CGLB model. The method ... | bc00f2423c4ffdaf0494ab6e6114222cbc694915 | 6,502 |
import os
def build_docker_build(latest=True):
"""Create command used to (re)build the container.
We store the Dockerfile (as that name)
in dir .next or .latest so that we can
have various templates and assets and so on
in the 'context' directory.
"""
tmpl = "{} build -t {{tagname}}:{{t... | 317b5d63cc941d6db57d704e1be76c7aa8b32799 | 6,503 |
def scrape_new_thread(thread_name, url):
"""Scrape data for a thread that isn't already in our database."""
logger.debug(f"Start of scrape_new_thread for {thread_name}, {url}")
# URL Validation
# TODO: write this function, then hand it off to scrape_existing_thread()
logger.debug("Now that the thr... | cbb583e262c938378562951af495d122b2db13bd | 6,504 |
def num_fixed_points(permutation):
"""
Compute the number of fixed points (elements mapping to themselves) of a permutation.
:param permutation: Permutation in one-line notation (length n tuple of the numbers 0, 1, ..., n-1).
:return: Number of fixed points in the permutation.
.. rubric:: Examples... | 124713cd4c90988c43630a74881e7107ff748682 | 6,505 |
import os
def load_messages(path, unique, verbose):
""" Loads messages from the corpus and returns them as Message objects """
messages = []
signatures = set()
for root, _, files in os.walk(path):
if verbose:
print("Processing {}".format(root))
for message_file in files:
... | 61e3abafb0bd6c20adf9dfbc45c03e510704880c | 6,506 |
import numpy
def mutate(grid):
"""
Alters the cycle by breaking it into two separate circuits, and then fusing
them back together to recreate a (slightly different) cycle.
This operation is called "sliding" in 'An Algorithm for Finding Hamiltonian
Cycles in Grid Graphs Without Holes', and it's sp... | 35cc32385d090fa8091f872858fbeb0c32ecf43d | 6,507 |
def reverse_permute(output_shape: np.array, order: np.array):
"""
Calculates Transpose op input shape based on output shape and permute order.
:param output_shape: Transpose output shape
:param order: permute order
:return: Transpose input shape corresponding to the specified output shape
"""
... | ada631cc086a1dc0d2dce05f6d97a74a1f3861f4 | 6,508 |
def recursive_bisection(block, block_queue, epsilon_cut, depth_max, theta, lamb, delta, verbose=False):
"""Random cut and random converge
Args:
block_queue (multiprocessing.Queue): Shared queue to store blocks to be executed
Returns:
[{"range": {int: (int,int)}, "mondrian_budget": float, "... | d65070c2cf64356277c4af044b97c5eaa8efdd3d | 6,509 |
def _get_global_step_read(graph=None):
"""Gets global step read tensor in graph.
Args:
graph: The graph in which to create the global step read tensor. If missing,
use default graph.
Returns:
Global step read tensor.
Raises:
RuntimeError: if multiple items found in collection GLOBAL_STEP_RE... | 46bf3b55b36216e4247d6d73226d22b20383321f | 6,510 |
from unittest.mock import Mock
def light_control() -> LightControl:
"""Returns the light_control mock object."""
mock_request = Mock()
mock_request.return_value = ""
return LightControl(mock_request) | cb135ed24d2e992eab64b298e5c9238576a37c5d | 6,511 |
def map_threshold(stat_img=None, mask_img=None, alpha=.001, threshold=3.,
height_control='fpr', cluster_threshold=0):
""" Compute the required threshold level and return the thresholded map
Parameters
----------
stat_img : Niimg-like object or None, optional
statistical image (... | ea7c1ca48641ed76eef2f2b0396b93fd522fdbaf | 6,512 |
import time
import random
def grab_features(dataframe: pd.DataFrame) -> pd.DataFrame:
"""
Attempts to assign song features using the get_features function to all songs in given dataframe.
This function creates a column that encompasses all features retuerned from Spotify in a json format for each track I... | 7a2810b68815241a62f2ce753169bd982a17a211 | 6,513 |
def _build_geo_shape_query(field, geom, relation):
"""Crea una condición de búsqueda por relación con una geometría en formato
GeoJSON.
Args:
field (str): Campo de la condición.
geom (dict): Geometría GeoJSON.
relation (str): Tipo de búsqueda por geometrías a realizar. Ver la
... | f42fe6e21da30e3d6c8466be92143b215925686c | 6,514 |
import os
from sys import version
def ProcessConfigurationFile(options):
"""Process configuration file, merge configuration with OptionParser.
Args:
options: optparse.OptionParser() object
Returns:
options: optparse.OptionParser() object
global_ns: A list of global nameserver tuples.
regional_... | e1d78fa2b904b2c46e27d67f3679d7192456db29 | 6,515 |
from typing import Optional
def map_symptom(symptom_name: str) -> Optional[str]:
"""
Maps a *symptom_name* to current symptom values in ID3C warehouse.
There is no official standard for symptoms, we are using the values
created by Audere from year 1 (2018-2019).
"""
symptom_map = {
'f... | c86f0694715b434b1e3b2dc3f66ddfc3afadeaf0 | 6,516 |
def check_sbatch(cmd, call=True, num_cpus=1, mem="2G", time=None,
partitions=None, dependencies=None, no_output=False, no_error=False,
use_slurm=False, mail_type=['FAIL', 'TIME_LIMIT'], mail_user=None,
stdout_file=None, stderr_file=None,
args=None):
""" This function wraps calls t... | 292757f8a9901a722d10d3d9f76f7e584d802b3b | 6,517 |
def get_project_details(p):
"""Extract from the pickle object detailed information about
a given project and parse it in a comprehensive dict structure."""
res = {}
project = p['projects'][0]
fields = {'Owner(s)': 'project_owners',
'Member(s)': 'project_members',
'Colla... | f8ba3debdd8be7cc7a906851a6a6fb1e3c5f039a | 6,518 |
def get_category(name: str) -> Category:
"""Returns a category with a given name"""
return Category.objects.get(name=name) | 4dc99ed672bbb3d7843692da797d0cd901c2c44c | 6,519 |
def log_report():
""" The log report shows the log file. The user can filter and search the log. """
log_main = open(main_log, 'r').readlines()
data_main = []
for line in log_main:
split_line = line.split(' ')
data_main.append([' '.join(split_line[:2]), ' '.join(split_line[2:])])
ret... | 53905c90bed2666c7e668bf76ff03a6ba93eca5b | 6,520 |
def int_or_none(x) -> int:
"""Either convert x to an int or return None."""
try:
return int(x)
except TypeError:
return None
except ValueError:
return None | e7fbd422a6c61293c9f4f71df211a85570d4400e | 6,521 |
import argparse
import logging
def create_parser_for_docs() -> argparse.ArgumentParser:
"""Create a parser showing all options for the default CLI
documentation.
Returns:
The primary parser, specifically for generating documentation.
"""
daiquiri.setup(level=logging.FATAL)
# load defa... | 97fca333d2e5893f21070efc0016bcf3634d7977 | 6,522 |
def needed_to_build_multi(deriv_outputs, existing=None, on_server=None):
"""
:param deriv_outputs: A mapping from derivations to sets of outputs.
:type deriv_outputs: ``dict`` of ``Derivation`` to ``set`` of ``str``
"""
if existing is None:
existing = {}
if on_server is None:
on... | d05083ea9c71c982d312e8b420b21bba92b80ee4 | 6,523 |
def iscode(c):
"""
Tests if argument type could be lines of code,
i.e. list of strings
"""
if type(c) == type([]):
if c:
return type(c[0]) == type('')
else:
return True
else: return False | e60da6c05922ff1e67db15fa4caa1500a8f470c7 | 6,524 |
def get_comment_list(request, thread_id, endorsed, page, page_size, requested_fields=None):
"""
Return the list of comments in the given thread.
Arguments:
request: The django request object used for build_absolute_uri and
determining the requesting user.
thread_id: The id of th... | 980e52645e96853339df0525359ddba4698bf7e7 | 6,525 |
from typing import List
def files(name: str, dependencies=False, excludes=None) -> List[PackagePath]:
"""
List all files belonging to a distribution.
Arguments:
name:
The name of the distribution.
dependencies:
Recursively collect files of dependencies too.
... | cfda01bb7e6858e378aadeea47e6e4a0d76dda2f | 6,526 |
def ready_to_delete_data_node(name, has_executed, graph):
"""
Determines if a DataPlaceholderNode is ready to be deleted from the
cache.
Args:
name:
The name of the data node to check
has_executed: set
A set containing all operations that have been executed so fa... | 7da3c6053146a1772223e29e1eca15107e0347b6 | 6,527 |
import hashlib
def extract_hash_parts(repo):
"""Extract hash parts from repo"""
full_hash = hashlib.sha1(repo.encode("utf-8")).hexdigest()
return full_hash[:2], full_hash[2:] | aa1aebaf9b8330539eb0266c4ff97fd3459753c8 | 6,528 |
def create_cloud_mask(im_QA, satname, cloud_mask_issue):
"""
Creates a cloud mask using the information contained in the QA band.
KV WRL 2018
Arguments:
-----------
im_QA: np.array
Image containing the QA band
satname: string
short name for the satellite: ```'L5', 'L7', 'L8... | 5143c1c61425a131bdb3b0f91018643c9a9d4123 | 6,529 |
import re
def split_bucket(s3_key):
"""
Returns the bucket name and the key from an s3 location string.
"""
match = re.match(r'(?:s3://)?([^/]+)/(.*)', s3_key, re.IGNORECASE)
if not match:
return None, s3_key
return match.group(1), match.group(2) | 6b854bdc9d105643a9fa528e6fefd19672451e63 | 6,530 |
def contains_chinese(ustr):
"""
将字符串中的中文去除
Args:
ustr: 字符串
Returns: 去除中文的字符串
"""
return any('\u4e00' <= char <= '\u9fff' for char in ustr) | 8d53a214e1754e1c129f1583a298f5a19e1f76d3 | 6,531 |
def payment_activity():
"""Request for extra-curricular activity"""
try:
req_json = request.get_json(force=True)
except TypeError:
return jsonify(message='Invalid json input'), 400
activity_info = req_json['activity']
student = req_json['student']
envelope_args = {
'sign... | a313b6e5ed00ffc9b3685ce28a9c640e96276347 | 6,532 |
def gdc_to_dos_list_response(gdcr):
"""
Takes a GDC list response and converts it to GA4GH.
:param gdc:
:return:
"""
mres = {}
mres['data_objects'] = []
for id_ in gdcr.get('ids', []):
mres['data_objects'].append({'id': id_})
if len(gdcr.get('ids', [])) > 0:
mres['nex... | a237a64f55c15fb10070d76b6f3cc4f283460a96 | 6,533 |
def get_labels_by_db_and_omic_from_graph(graph):
"""Return labels by db and omic given a graph."""
db_subsets = defaultdict(set)
db_entites = defaultdict(dict)
entites_db = defaultdict(dict)
# entity_type_map = {'Gene':'genes', 'mirna_nodes':'mirna', 'Abundance':'metabolites', 'BiologicalProcess':'... | 14374977afb09fded25f78e14fced607bb8f9ea1 | 6,534 |
import os
def python_modules():
"""Determine if there are python modules in the cwd.
Returns:
list of python modules as strings
"""
ignored = ["setup.py", "conftest.py"]
py_modules = []
for file_ in os.listdir(os.path.abspath(os.curdir)):
if file_ in ignored or not os.path.i... | eba262b38bddb0f76f614c74a9a0b1c090e48e6b | 6,535 |
import logging
def covid_API_england ():
"""Function retrieves date, hospital admissions, total deaths
and daily cases using government API"""
england_only = [
'areaType=nation',
'areaName=England'
]
dates_and_cases = {
"date": "date",
"newCasesByPublishDate": ... | a13090a052a35dd675c1fb31b861cbcc4b9e7c4a | 6,536 |
from meerschaum.actions.shell import default_action_completer
from typing import Optional
from typing import List
from typing import Any
def _complete_uninstall(
action : Optional[List[str]] = None,
**kw : Any
) -> List[str]:
"""
Override the default Meerschaum `complete_` function.
""... | 1cfdc5694a069c924316f57e4804ae04d63bb4af | 6,537 |
def test_bucket():
"""Universal bucket name for use throughout testing"""
return 'test_bucket' | 2f78b1b1bf7ccfff07ca29213d975f3b20f0e9a5 | 6,538 |
import os
import sys
def validate_args(args):
""" Validate all of the arguments parsed.
Args:
args (argparser.ArgumentParser) : Args parsed by the argument parser.
Returns:
args (CoreclrArguments) : Args parsed
Notes:
If the arguments are valid then return them all in a... | 35f9446ba1d52c0ec824e0184b5e17ddd16bbb76 | 6,539 |
import os
def _path_restrict(path, repo):
"""Generate custom package restriction from a given path.
This drops the repo restriction (initial entry in path restrictions)
since runs can only be made against single repo targets so the extra
restriction is redundant and breaks several custom sources invo... | dbcff06e3cc32b0ff606459ce13cfc275bfae173 | 6,540 |
def us_send_code():
"""
Send code view.
This takes an identity (as configured in USER_IDENTITY_ATTRIBUTES)
and a method request to send a code.
"""
form_class = _security.us_signin_form
if request.is_json:
if request.content_length:
form = form_class(MultiDict(request.ge... | 7ca09dc6d6fdc7840d893e01b4166d65a1b9cc02 | 6,541 |
def merge_texts(files, file_index, data_type):
""" merge the dataframes in your list """
dfs, filenames = get_dataframe_list(files, file_index, data_type)
# enumerate over the list, merge, and rename columns
try:
df = dfs[0]
# print(*[df_.columns for df_ in dfs],sep='\n')
for i, ... | 4e336a240afd100797b707efc9ccc96feb8d2919 | 6,542 |
def create_dictionary(names, months, years, max_sustained_winds, areas_affected, updated_damages, deaths):
"""Create dictionary of hurricanes with hurricane name as the key and a dictionary of hurricane data as the value."""
hurricanes = dict()
num_hurricanes = len(names)
for i in range(num_hurricanes):
hur... | 5a27d5349113f29d2af55df27a2ee2c2cc524549 | 6,543 |
def create_variable_type(parent, nodeid, bname, datatype):
"""
Create a new variable type
args are nodeid, browsename and datatype
or idx, name and data type
"""
nodeid, qname = _parse_nodeid_qname(nodeid, bname)
if datatype and isinstance(datatype, int):
datatype = ua.NodeId(datatyp... | b2202b929bc51e2a2badfef6ec31df45e9736268 | 6,544 |
def load_NWP(input_nc_path_decomp, input_path_velocities, start_time, n_timesteps):
"""Loads the decomposed NWP and velocity data from the netCDF files
Parameters
----------
input_nc_path_decomp: str
Path to the saved netCDF file containing the decomposed NWP data.
input_path_velocities: str
... | d96dacc14404f59b15a428e62608765486623460 | 6,545 |
def get_ts(fn, tc, scale=0):
"""Returns timestamps from a frame number and timecodes file or cfr fps
fn = frame number
tc = (timecodes list or Fraction(fps),tc_type)
scale default: 0 (ns)
examples: 3 (µs); 6 (ms); 9 (s)
"""
scale = 9 - scale
tc, tc_type = tc
if tc_type... | 845b2600268a2942ca0fe2b09336ab724b00e299 | 6,546 |
import numpy
def adapt_array(array):
"""
Using the numpy.save function to save a binary version of the array,
and BytesIO to catch the stream of data and convert it into a BLOB.
:param numpy.array array: NumPy array to turn into a BLOB
:return: NumPy array as BLOB
:rtype: BLOB
"""
out... | 36a62c745de0e933b520821ea7cce70f5013c5d2 | 6,547 |
def make_queue(paths_to_image, labels, num_epochs=None, shuffle=True):
"""returns an Ops Tensor with queued image and label pair"""
images = tf.convert_to_tensor(paths_to_image, dtype=tf.string)
labels = tf.convert_to_tensor(labels, dtype=tf.uint8)
input_queue = tf.train.slice_input_producer(
... | 7a2ad9338642a5d6c7af59fe972ee9fd07f128b8 | 6,548 |
def display_import(request, import_id):
"""Display the details of an import."""
import_object = get_object_or_404(RegisteredImport, pk=import_id)
context_data = {'import': import_object}
return render(request, 'eats/edit/display_import.html', context_data) | b5676dd5da1791fb6eda3d6989b9c7c0c8b02b8c | 6,549 |
def TransformContainerAnalysisData(image_name, occurrence_filter=None,
deployments=False):
"""Transforms the occurrence data from Container Analysis API."""
analysis_obj = container_analysis_data_util.ContainerAndAnalysisData(
image_name)
occs = FetchOccurrencesForResource... | d7021dde08a77ac6922274f3e69d841983728f4e | 6,550 |
def setup_milp(model, target, remove_blocked=False, exclude_reaction_ids=set()):
"""
This function constructs the MILP.
exclude_reaction_ids takes a list of reaction ids that shouldn't be considered for heterologous addition
(i.e. spontaneous reactions and exchange reactions). These reactions are thus a... | ddefa4b44ac0dce087367762ead2cb0ce9bbb14b | 6,551 |
def bilinear_initializer(shape, dtype, partition_info):
"""
Bilinear initializer for deconvolution filters
"""
kernel = get_bilinear_kernel(shape[0], shape[1], shape[2])
broadcasted_kernel = np.repeat(kernel.reshape(shape[0], shape[1], shape[2], -1), repeats=shape[3], axis=3)
return broadcaste... | 48a7cc2808e72df816c9b6ff7a8975eb52e4185e | 6,552 |
def pdf():
"""
Демо-версия PDF отчеа, открывается прямо в браузере,
это удобнее, чем каждый раз скачивать
"""
render_pdf(sample_payload_obj, './output.pdf')
upload_file('./output.pdf')
return send_file('./output.pdf', attachment_filename='output.pdf') | a2a60c26df9844e605606538d40d1402cd5a4985 | 6,553 |
def run_clear_db_es(app, arg_env, arg_skip_es=False):
"""
This function actually clears DB/ES. Takes a Pyramid app as well as two flags. _Use with care!_
For safety, this function will return without side-effect on any production system.
Also does additional checks based on arguments supplied:
If... | e7d865dec8691c4d0db7bef71b68bab9bc5174a2 | 6,554 |
def init_total_population():
"""
Real Name: b'init total population'
Original Eqn: b'init Infected asymptomatic+init Susceptible'
Units: b'person'
Limits: (None, None)
Type: component
b''
"""
return init_infected_asymptomatic() + init_susceptible() | cf742a00d0140c48dbdb4692dabbb8bbd6c5c6b2 | 6,555 |
def one_hot(dim: int, idx: int):
""" Get one-hot vector """
v = np.zeros(dim)
v[idx] = 1
return v | 84b87b357dc7b7bf54af4718885aa1d6fbcb35e4 | 6,556 |
import re
def process_priors(prior_flat, initial_fit):
"""Process prior input array into fit object."""
if any(
[float(val) <= 0 for key, val in prior_flat.items() if key.endswith("sdev")]
):
raise ValueError("Standard deviations must be larger than zero.")
prior = {}
for key, val... | 32358fb494a221e5e7d5d4d73776993f1c363f0f | 6,557 |
def _sample_data(ice_lines, frac_to_plot):
"""
Get sample ice lines to plot
:param ice_lines: all ice lines
:param frac_to_plot: fraction to plot
:return: the sampled ice lines
"""
if frac_to_plot < 1.:
ice_plot_data = ice_lines.sample(int(ice_lines.shape[0] * frac_to_plot))
e... | e5da9b1ecaf615863504e81cdd246336de97b319 | 6,558 |
def fast_dot(M1, M2):
"""
Specialized interface to the numpy.dot function
This assumes that A and B are both 2D arrays (in practice)
When A or B are represented by 1D arrays, they are assumed to reprsent
diagonal arrays
This function then exploits that to provide faster multiplication
""... | b34e44787f48dfb25af4975e74262f3d8eaa5096 | 6,559 |
async def autoredeem(
bot: commands.Bot,
guild_id: int
) -> bool:
"""Iterates over the list of users who have
enabled autoredeem for this server, and if
one of them does redeem some of their credits
and alert the user."""
await bot.wait_until_ready()
conn = bot.db.conn
guild = bot.g... | ee0a34e4aa9d85e9402dcbec8a1ecce5a2ca58e1 | 6,560 |
def get_ISO_369_3_from_string(term: str,
default: str = None,
strict: bool = False,
hdp_lkg: dict = None) -> str:
"""Convert an individual item to a ISO 369-3 language code, UPPERCASE
Args:
term (str): The input t... | 434c39cad948bf7e4e33e9f5a6bd8da7c8a708ab | 6,561 |
from typing import Optional
from typing import Sequence
def plot_heatmap(
data: DataFrame,
columns: Optional[Sequence[str]] = None,
droppable: bool = True,
sort: bool = True,
cmap: Optional[Sequence[str]] = None,
names: Optional[Sequence[str]] = None,
yaxis: boo... | 84233ee9293131ce98072f880a3c1a57fc71b321 | 6,562 |
def iadd_tftensor(left, right, scale=1):
"""This function performs an in-place addition. However, TensorFlow returns
a new object after a mathematical operation. This means that in-place here
only serves to avoid the creation of a TfTensor instance. We do not have
any control over the memory where the T... | 3f14de3df3544b74f0a900fca33eb6cdf6e11c00 | 6,563 |
import sys
def bookmark_desc_cmd(query):
"""describe: desc [num.. OR url/tag substr..]."""
split_query = query[4:].strip().split()
if not split_query:
sys.stderr.write(BOOKMARK_HELP)
return False
bk_indices = find_bookmark_indices(split_query)
if bk_indices:
return describ... | 2572ffbb801f01bdff4706a2823d2ca385943290 | 6,564 |
def encode(string_):
"""Change String to Integers"""
return (lambda f, s: f(list( ord(c) for c in str(string_) ) , \
s))(lambda f, s: sum(f[i] * 256 ** i for i in \
range(len(f))), str(string_)) | da3a729c2024d80792e08424745dc267ca67dff7 | 6,565 |
def generate_file_prefix(bin_params):
""" Use the bin params to generate a file prefix."""
prefix = "bin_"
for j in range(0, len(bin_params)):
if (j + 1) % 2 != 0:
prefix += str(bin_params[j]) + "-"
else:
prefix += str(bin_params[j]) + "_"
return prefix | cc058a64fcab77f6a4794a8bf7edb1e0e86c040c | 6,566 |
def extract_features_from_html(html, depth, height):
"""Given an html text, extract the node based features
including the descendant and ancestor ones if depth and
height are respectively nonzero."""
root = etree.HTML(html.encode('utf-8')) # get the nodes, serve bytes, unicode fails if html has meta
... | ee7b627bf7c859fc886eab10f6a8b6b793653262 | 6,567 |
def __clean_field(amazon_dataset, option):
"""Cleanes the Text field from the datset """
clean = []
if option == 1:
for i in amazon_dataset['Text']:
clean.append(__one(i))
elif option == 2:
for i in amazon_dataset['Summary']:
clean.append(__one(i))
else:
... | 1e8ef28c810413b87804a42514059c347d715972 | 6,568 |
import os
def write_bruker_search_path(ftype, destfile, sourcefile=None, sourcetext=None):
"""Will copy a file from sourcefile (out of the add_files directory) or
text to destfile in first directory of Bruker search path for
ftype = cpd, f1, gp, ... with checks for overwrite, identity, etc.
"""
if... | eaeaac026502308cbeb50932decfcc79d83d127c | 6,569 |
import warnings
def _read_atom_line(line):
"""
COLUMNS DATATYPE FIELD DEFINITION
-------------------------------------------------------------------------------------
1 - 6 RecordName "ATOM "
7 - 11 Integer serial Atom serial number.
13... | e511352dcc0bfcdec98035673adf759256c13e4c | 6,570 |
from typing import List
def semantic_parse_entity_sentence(sent: str) -> List[str]:
"""
@param sent: sentence to grab entities from
@return: noun chunks that we consider "entities" to work with
"""
doc = tnlp(sent)
ents_ke = textacy.ke.textrank(doc, normalize="lemma")
entities = [ent for ... | c65fa1d8da74b86b3e970cbf7f351e03d5a3fcec | 6,571 |
import json
import os
def extract_to_files(pkr_path, verbose=False):
"""
Extract data and image to .json and .png (if any) next to the .pkr
"""
title, buttons, png_data = parse_animschool_picker(pkr_path, verbose)
# Save to json
with open(pkr_path + '.json', 'w') as f:
json.dump([title... | 097a4ceb87f456b4a333ed18f7fa961aba2a2cad | 6,572 |
def readLog(jobpath):
"""
Reads log to determine disk/mem usage, runtime
For processing time, it will only grab the last execution/evict/terminated times.
And runTime supercedes evictTime (eg. an exec->evict combination will not be written if
a later exec-termination combination exists in the log)
... | 4bc3f6b79d3eb18544ea54dd5b6ac173da43f83b | 6,573 |
from numpy import array
def match_cam_time(events, frame_times):
"""
Helper function for mapping ephys events to camera times. For each event in events, we return the nearest
camera frame before the event.
Parameters
----------
events : 1D numpy array
Events of interest. Sampled at... | 3f086a0f65a34183a429cf3c50e90fdc742672d3 | 6,574 |
import ctypes
def _glibc_version_string_ctypes() -> Optional[str]:
"""
Fallback implementation of glibc_version_string using ctypes.
"""
try:
except ImportError:
return None
# ctypes.CDLL(None) internally calls dlopen(NULL), and as the dlopen
# manpage says, "If filename is NULL, ... | 86ae885182585eeb1c5e53ee8109036dd93d06d3 | 6,575 |
from typing import Sequence
from typing import List
from typing import Tuple
def encode_instructions(
stream: Sequence[Instruction],
func_pool: List[bytes],
string_pool: List[bytes],
) -> Tuple[bytearray, List[bytes], List[bytes]]:
"""
Encode the bytecode stream as a single `bytes` object that can... | 0a371731f627b96ca3a07c5ac992fd46724a7817 | 6,576 |
def get_random(selector):
"""Return one random game"""
controller = GameController
return controller.get_random(MySQLFactory.get(), selector) | 89f458a434cd20e10810d03e7addb1c5d6f1475a | 6,577 |
def get_ssh_dispatcher(connection, context):
"""
:param Message context: The eliot message context to log.
:param connection: The SSH connection run commands on.
"""
@deferred_performer
def perform_run(dispatcher, intent):
context.bind(
message_type="flocker.provision.ssh:ru... | 1cb965c4e175276672173d5696e3196da5725fce | 6,578 |
def read_ac(path, cut_off, rnalen):
"""Read the RNA accessibility file and output its positions and values
The file should be a simple table with two columns:
The first column is the position and the second one is the value
'#' will be skipped
"""
access = []
with open(path) as f:
... | 0a8b6c2ff6528cf3f21d3b5efce14d59ff8ad2b6 | 6,579 |
def subtableD0(cxt: DecoderContext, fmt: Format):
""" ORI """
fmt = FormatVI(fmt)
return MNEM.ORI, [Imm(fmt.imm16, width=16, signed=False), Reg(fmt.reg1), Reg(fmt.reg2)], 2 | 2bb307bd74568745b7f453365f7667c383cae9ff | 6,580 |
from datetime import datetime
def format_date(unix_timestamp):
""" Return a standardized date format for use in the two1 library.
This function produces a localized datetime string that includes the UTC timezone offset. This offset is
computed as the difference between the local version of the timestamp ... | cc1a6ee0c604e14f787741ff2cb0e118134c9b92 | 6,581 |
import copy
from operator import and_
def or_(kb, goals, substitutions=dict(), depth=0, mask=None,
k_max=None, max_depth=1):
"""Base function of prover, called recursively.
Calls and_, which in turn calls or_, in order to recursively calculate scores for every possible proof in proof
tree.
A... | d19382167143ffc3b5267fda126cc4f8d45fc86c | 6,582 |
import copy
def print_term(thy, t):
"""More sophisticated printing function for terms. Handles printing
of operators.
Note we do not yet handle name collisions in lambda terms.
"""
def get_info_for_operator(t):
return thy.get_data("operator").get_info_for_fun(t.head)
def get_pri... | 745b378dac77411ba678911c478b6f5c8915c762 | 6,583 |
def build_model():
"""Builds the model."""
return get_model()() | f843bce4edf099efd138a198f12c392aa2e723cd | 6,584 |
def truncate_field_data(model, data):
"""Truncate all data fields for model by its ``max_length`` field
attributes.
:param model: Kind of data (A Django Model instance).
:param data: The data to truncate.
"""
fields = dict((field.name, field) for field in model._meta.fields)
return dict((n... | 3f0c77d279e712258d3a064ca9fed06cd64d9eaf | 6,585 |
import io
def get_all_students(zip):
"""Returns student tuple for all zipped submissions found in the zip file."""
students = []
# creating all the student objects that we can zip files of
for filename in zip.namelist():
if not filename.endswith(".zip"):
continue
firstname,... | d5088ecf43275664e8420f30f508e70fad7cef77 | 6,586 |
def is_shipping_method_applicable_for_postal_code(
customer_shipping_address, method
) -> bool:
"""Return if shipping method is applicable with the postal code rules."""
results = check_shipping_method_for_postal_code(customer_shipping_address, method)
if not results:
return True
if all(
... | cca519a35ab01dddac71ac18bdf8a40e1b032b83 | 6,587 |
def populate_api_servers():
""" Find running API servers. """
def api_server_info(entry):
prefix, port = entry.rsplit('-', 1)
project_id = prefix[len(API_SERVER_PREFIX):]
return project_id, int(port)
global api_servers
monit_entries = yield monit_operator.get_entries()
server_entries = [api_serve... | 0543e350917c3fe419022aebdd9002098021923a | 6,588 |
import torch
def gen_classification_func(model, *, state_file=None, transform=None, pred_func=None,
device=None):
""" 工厂函数,生成一个分类器函数
用这个函数做过渡的一个重要目的,也是避免重复加载模型
:param model: 模型结构
:param state_file: 存储参数的文件
:param transform: 每一个输入样本的预处理函数
:param pred_func: model 结果... | 4d905dfc9bd330cd68a2cc78b121debe04669720 | 6,589 |
def create_recipe_json(image_paths: list) -> dict:
"""
Orchestrate the various services to respond to a create recipe request.
"""
logger.info('Creating recipe json from image paths: {}'.format(image_paths))
full_text = load_images_return_text(image_paths)
recipe_json = assign_text_to_recip... | 25ef26d15bf20384df81f46da519c07ea883d5a7 | 6,590 |
def rstrip_extra(fname):
"""Strip extraneous, non-discriminative filename info from the end of a file.
"""
to_strip = ("_R", "_", "fastq", ".", "-")
while fname.endswith(to_strip):
for x in to_strip:
if fname.endswith(x):
fname = fname[:len(fname) - len(x)]
... | 281ff6dcfae1894dd4685acf433bde89538fe87e | 6,591 |
def run(preprocessors, data, preprocessing=defaultdict(lambda: None), fit=True):
"""Applies preprocessing to data. It currently suppoerts StandardScaler and
OneHotEncoding
Parameters
----------
preprocessors : list
preprocessors to be applied
data : pd.DataFrame
data to be prepr... | 94b10007896062760a278cdeaf60388152c96f73 | 6,592 |
def vouchers_tab(request, voucher_group, deleted=False, template_name="manage/voucher/vouchers.html"):
"""Displays the vouchers tab
"""
vouchers = voucher_group.vouchers.all()
paginator = Paginator(vouchers, 20)
page = paginator.page((request.POST if request.method == 'POST' else request.GET).get("p... | f488c21a83b6b22e3c0e4d5fa2e35156435bada7 | 6,593 |
import torch
def normalise_intensity(x,
mode="minmax",
min_in=0.0,
max_in=255.0,
min_out=0.0,
max_out=1.0,
clip=False,
clip_range_percentile=(0.05, 99... | 4dace59c8c12dda2c01c6c8a4bcd631b1e562c48 | 6,594 |
def spots_rmsd(spots):
""" Calculate the rmsd for a series of small_cell_spot objects
@param list of small_cell_spot objects
@param RMSD (pixels) of each spot
"""
rmsd = 0
count = 0
print 'Spots with no preds', [spot.pred is None for spot in spots].count(True), 'of', len(spots)
for spot in spots:
if... | 13809a7a0353dc18b037cd2d78944ed5f9cdc596 | 6,595 |
def sanitize_df(data_df, schema, setup_index=True, missing_column_procedure='fill_zero'):
""" Sanitize dataframe according to provided schema
Returns
-------
data_df : pandas DataFrame
Will have fields provided by schema
Will have field types (categorical, datetime, etc) provided by sch... | 8664f9dd8feea60044397072d85d21c8b5dfd6d4 | 6,596 |
def get_id_argument(id_card):
"""
获取身份证号码信息
:param id_card:
:return:
"""
id_card = id_card.upper()
id_length = len(id_card)
if id_length == 18:
code = {
'body': id_card[0:17],
'address_code': id_card[0:6],
'birthday_code': id_card[6:14],
... | ae4cad97e787fe1b0697b6a0f842f0da09795d6a | 6,597 |
def rhypergeometric(n, m, N, size=None):
"""
Returns hypergeometric random variates.
"""
if n == 0:
return np.zeros(size, dtype=int)
elif n == N:
out = np.empty(size, dtype=int)
out.fill(m)
return out
return np.random.hypergeometric(n, N - n, m, size) | e8ea95bb742891037de264462be168fab9d68923 | 6,598 |
from typing import Tuple
def _validate_query(
hgnc_manager: HgncManager,
query_result,
original_identifier: str,
original_namespace: str,
) -> Tuple[str, str, str]:
"""Process and validate HGNC query.
:param hgnc_manager: hgnc manager
:param query_result:
:param original_identifier:
... | 0dd516d3f1a1a178015835ee1dc72b657757d789 | 6,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.