content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def EvalCode(code_str, parse_ctx, comp_lookup=None, mem=None, aliases=None):
"""
Unit tests can evaluate code strings and then use the resulting
CommandEvaluator.
"""
arena = parse_ctx.arena
comp_lookup = comp_lookup or completion.Lookup()
mem = mem or state.Mem('', [], arena, [])
parse_opts, exec_opts... | 181ea721a788da2a56a2cf1c1df6bfc35cdfbefc | 3,629,400 |
import csv
def read_forces(fname):
"""Read .forces file format from Cortex MAC.
The .forces file in ASCII contains force plate data. The data is saved
based on the forcepla.cal file of the trial and converts the raw force
plate data into calibrated forces. The units used are Newtons and
Newton-me... | 62b7c8050be5fd9cb79d2edfb2b459e4d705f704 | 3,629,401 |
def mpw_plot_points(slope, years, values):
"""
Calculate start and end points for line describing MPW best fit
:param float slope: line slope
:param float array years: x-coordinates
:param float array values: y-coordinates
:returns: [[x1,x2], [y1,y1]]
"""
mu_x = np.ma.mean(years)
... | 4265b26485e22ba8306edd0b647292eba2803b6b | 3,629,402 |
def get_target(module, array):
"""Return Pod or None"""
try:
return array.get_pod(module.params['target'])
except Exception:
return None | ee95f125073c852bdef11b42e9e9dda394fec9e1 | 3,629,403 |
def int_kinenergy(basis):
"""Calculates the kinenergy matrix for a given basis.
Parameters
----------
basis : BasisSet
Returns
-------
kinenergy : np.ndarray
Kinetic energy matrix with shape M x M, where `M = len(basis)`.
"""
M = len(basis)
kinenergy = np.zeros((M, M))
... | 0dfd6777bea20620d20f08578d61e6961777a10c | 3,629,404 |
from datetime import datetime
import requests
def test_commit_in_last_year_yes(monkeypatch):
"""
11. Has there been a commit in the last year?
"""
headers = {}
def mock_get(*args, **kwargs):
return MockResponseCommitsYes()
today = datetime.now()
test_date = datetime.strptime(GOOD... | 2473c6a86322749f26e3c9086d822799fa6d48fd | 3,629,405 |
def all_columns_functional(use_cache = True, update_cache = True):
""" Returns all functional categories identified in the data set. """
return get_columns('pathabundance_columns.pickle', 'pathabundance_relab', use_cache, update_cache) | b30bb59556f2597eda0821490515cd855c31c293 | 3,629,406 |
def json_replace(json_obj, **values):
"""
Search for elements of `{"{{REPLACE_PARAM}}": "some_key"}` and replace
with the result of `values["some_key"]`.
"""
if type(json_obj) is list:
return [json_replace(x, **values) for x in json_obj]
elif type(json_obj) is dict:
new = {}
... | f6a8b44b5dd10d37140445b9dc8ebd71107df0a2 | 3,629,407 |
def slit_scan_area_comp(slits, yag, x_width=1.0,y_width=1.0,samples=1):
"""Find the ratio of real space/pixel in the PIM
1. Send slits to specified position
2. Measure pixel dimensions of passed light.
The idea is that the width, height values will be pulled from the
PIMPulnixDetector inst... | de7081c1fedae29563ab8473af7d25bee9239674 | 3,629,408 |
def diff(f, *x, allowed_nonsmoothness="discontinuous"):
"""
A differentiator which computes :math:`\\partial f / \\partial x` and understands
:class:`Field`\\ s. If ``x`` is one of ``t``, ``x``, ``y``, or ``z`` and ``f``
is a :class:`DynamicField`, the corresponding derivative :class:`Field` is
retu... | 2031ae7cea5b36b4c660116ff82ee3570eb647d9 | 3,629,409 |
def append_store_prices(ticker_list, loc, start = '01/01/1990'):
"""
Given an existing store located at ``loc``, check to make sure
the tickers in ``ticker_list`` are not already in the data
set, and then insert the tickers into the store.
:ARGS:
ticker_list: :class:`list` of tickers to ad... | b7aa347eaa84b79342d44db2c5b757f56d831cf9 | 3,629,410 |
from typing import List
def trace_for_kbps(kbps: int) -> List[int]:
""" Returns Mahimahi trace lines whose average kbps approximates the passed in value """
# - convert kbps to a Fraction representing # packets per line of a Mahimahi trace file
# - Fraction will also simplify the ratio, giving us exactly ... | 80c16739ae85a5c236aa03cf23ce63fcf51a226f | 3,629,411 |
def barotropic_input_qref_to_compute_lwa(ylat,qref,vort,area,dmu,planet_radius = 6.378e+6): # used to be Eqlat_LWA
"""
This function computes LWA based on a *prescribed* Qref instead of Qref obtained from the vorticity field on a barotropic sphere.
Parameters
----------
ylat : sequence or array_lik... | aae459dd30fa4fbf8f1ab2a5ff29ed2e36f34878 | 3,629,412 |
def merge_models(old, new):
"""docstring for merge_model"""
if old.rowCount() == 0:
return new
if new.rowCount() == 0:
return old
old_crcs = [(old.item(row, COLUMN_CRC).text(), row) for row in
xrange(old.rowCount())]
new_crcs = [(new.item(row, COLUMN_CRC).text(), row) f... | 985f8ac5aa43409dab2d31859125b1d3d64a79fb | 3,629,413 |
import torch
def get_operator_norm(*ops):
""" Computes the l2-operator norm of a product of linear operators. """
if all([hasattr(op, "get_matrix") for op in ops]):
mat = ops[-1].get_matrix()
for op in ops[:-1][::-1]:
mat = torch.matmul(op.get_matrix(), mat)
return np.linal... | 4a1030d64fbdd0431a6351aa408b927dae98480b | 3,629,414 |
def fileexistspolicy(
overwrite_if_exists: bool, skip_if_file_exists: bool
) -> FileExistsPolicy:
"""Return the policy for overwriting existing files."""
return (
FileExistsPolicy.RAISE
if not overwrite_if_exists
else FileExistsPolicy.SKIP
if skip_if_file_exists
else ... | d8bd5e07c7f46aa9036460884ae5e1c588765cc2 | 3,629,415 |
import requests
def createDummy(name, type):
"""
Create a dummy entry to the SSRQ Person db.
:param name:
:param type:
:return link_id (string):
"""
try:
print("Requesting dummy id for " + name)
if type == "person":
r = requests.get("https://www.ssrq-sds-fds.ch/... | e7a6a124dbf49a51fa3971206fb9d630c9e2221c | 3,629,416 |
def generate(fin, fout):
"""
Search first author last name, year, and first meaningful word in title.
Assemble Google-Scholar-style keys (lastname+year+titlefirstword).
Replace original keys ``RN+number" with new keys.
Also adds letter suffixes to repeated keys
(e.g. peter1998researcha, peter1... | 30d7f2ae0a344dc663198aabecec4c8b9b05a8ff | 3,629,417 |
import torch
from typing import Optional
from typing import Union
def fbeta_score(
outputs: torch.Tensor,
targets: torch.Tensor,
beta: float = 1.0,
eps: float = 1e-7,
argmax_dim: int = -1,
num_classes: Optional[int] = None,
) -> Union[float, torch.Tensor]:
"""
Counts fbeta score for gi... | 081a90826acd0174a46af3cf8969a7935c7cde19 | 3,629,418 |
def gc_blocks(seq,block_size):
""" Divide sequence into non-overlapping blocks and compute GC content
of each block."""
blocks = []
for i in range(0, len(seq) - (len(seq) % block_size), block_size):
blocks.append(gc_content(seq[i:i+block_size]))
return tuple(blocks) | 3bf33ab361f520ffc53781ae48d51037bdd343e6 | 3,629,419 |
def is_android(filename):
"""
check if the files is an apk file or not
"""
with open(filename, "rb") as f:
# AndroidManifest.xml
if b"AndroidManifest.xml" in f.read(4096):
return True
return False | 95405710bbf361eef9ddc4dff877745c4c42be02 | 3,629,420 |
def enrich(alert, rules):
"""Determine if an alert meets an enrichment rule
:param alert: The alert to test
:param rules: An array of enrichment rules to test against
:returns: Alert - The enriched Alert object
"""
for enrichment in rules:
updates = enrichment(alert)
if not upda... | 97bf2d387e4c6e1ab38628860415bdf83c4634b9 | 3,629,421 |
def max_ea():
"""
Return the highest mapped address of the IDB.
Wrapper on :meth:`BipIdb.max_ea`.
"""
return BipIdb.max_ea() | 9f79ad7e6b71e81b3ecf9440a313243b6946d116 | 3,629,422 |
from ..architectures import create_unet_model_3d
from ..utilities import get_pretrained_network
from ..utilities import get_antsxnet_data
from ..utilities import preprocess_brain_image
def desikan_killiany_tourville_labeling(t1,
do_preprocessing=True,
... | e7b37f918f07823e9b4e297f065e72fa5a8aad16 | 3,629,423 |
def empty(document, selection, selectmode=''):
"""Reduce the selection to a single uppermost empty interval."""
beg = selection[0][0]
return Selection(Interval(beg, beg)) | dc349c95bd9cf492695e906630762d6e67bf33bf | 3,629,424 |
def re(rm,rf,beta):
"""Returns cost of equity using CAPM formula."""
return rf + beta*(rm-rf) | 5f91fd21ba1833dcb816ac767c8e1a15e2a30a5a | 3,629,425 |
def find_path(matrix, start_x, start_y, end_x, end_y, tile_size, map_height):
"""
Creates a path from a matrix of barriers, a start position,
a desired end position, the size of tiles used in a map,
and the map's height (in tiles).
"""
# TODO: Get map height from matrix instead of it being a pa... | a18222ab80f58d7db4e3adfc795046bf1566228d | 3,629,426 |
from typing import Dict
def _kwargs_to_bond_parameters(bond_type: Array,
kwargs: Dict[str, Array]) -> Dict[str, Array]:
"""Extract parameters from keyword arguments."""
# NOTE(schsam): We could pull out the species case from the generic case.
for k, v in kwargs.items():
if bon... | 6ff9cf3d3662d84ca5a8c0fbb0298a33f59ac253 | 3,629,427 |
import time
def wait_for_result(func, *args, matcher=simple_matcher(True), attempts=20,
interval=5, decode=decode_wrapper):
"""Runs `func` with `args` until `matcher(out)` returns true or timesout
Returns the matching result, or raises an exception.
"""
for i in range(attempts):
... | fcaf21eeceac3c2f5096763f41250de1d9508fec | 3,629,428 |
def host_is_trusted(hostname: str, trusted_list: t.Iterable[str]) -> bool:
"""Check if a host matches a list of trusted names.
:param hostname: The name to check.
:param trusted_list: A list of valid names to match. If a name
starts with a dot it will match all subdomains.
.. versionadded:: 0.... | e33fb74f12e61016f0e042d6765c93547b26fd15 | 3,629,429 |
from typing import Sequence
import copy
def average_data(flow_fields: Sequence[GmxFlow]) -> GmxFlow:
"""Average a given list of flow fields.
The flow fields must be of identical shape and be regular. It is further
assumed that they have the same origin and bin spacing, and that the bins
have the same... | 57454ec23498e54bc6792c37b94ed5c2bb9cec50 | 3,629,430 |
import typing
import os
import glob
import warnings
def identify_background_video_folder(parent_folder: typing.Union[str, bytes, os.PathLike], fname: str, fname_format: str, optional_settings: dict = {}) -> typing.Tuple[bool,str]:
"""
Identifies a background folder that matches a given experimental fname.
... | e20d015ff47d0f1d54f50a7a09d9b30750e254e9 | 3,629,431 |
def user_dashboard_request_view(request, **kwargs):
"""User dashboard request details view."""
avatar = current_user_resources.users_service.links_item_tpl.expand(
current_user
)["avatar"]
request_type = request["type"]
is_draft_submission = request_type == CommunitySubmission.type_id
... | afd57187d5a0c74229e3190c5e30079a7d8019a9 | 3,629,432 |
def _load_discrim_net(path: str, venv: VecEnv) -> common.RewardFn:
"""Load test reward output from discriminator."""
del venv # Unused.
discriminator = th.load(path)
# TODO(gleave): expose train reward as well? (hard due to action probs?)
return discriminator.predict_reward_test | 1b9e11f8182183b80540b544180385ae52798119 | 3,629,433 |
from typing import Sequence
def _is_generator_like(data):
"""Checks if data is a generator, Sequence, or Iterator."""
return (hasattr(data, 'next') or hasattr(data, '__next__') or isinstance(
data, (Sequence, iterator_ops.Iterator, iterator_ops.IteratorV2))) | 444516eed895f1877cd63d1970254ad3890c9cd9 | 3,629,434 |
import socket
def check_tcp_port(host, port, timeout=3):
"""
Try connecting to a given TCP port.
:param host: Host to connect to
:param port: TCP port to connect to
:param timeout: Connection timeout, in seconds
:return: True if the port is open, False otherwise.
"""
s = socket.socke... | 5e49ebab2c219e9772174d830dffcb958033befd | 3,629,435 |
import logging
def create_logger(logger=None, loglevel=DEFAULT_LOGLEVEL):
"""
Attaches or creates a new logger and creates console handlers if not present
"""
logger = logger or logging.getLogger('{0}.SSHTunnelForwarder'. \
format(__name__))
if not logger.... | 7f6f9721964c0644d882e0206c2eb75f07fe0258 | 3,629,436 |
def psi_from(grid, axis_ratio, core_radius):
"""
Returns the $\Psi$ term in expressions for the calculation of the deflection of an elliptical isothermal mass
distribution. This is used in the `Isothermal` and `Chameleon` `MassProfile`'s.
The expression for Psi is:
$\Psi = \sqrt(q^2(s^2 + x^2) + y... | 257bbbd0f5826e5d78c1d24a9a565fd4473d6887 | 3,629,437 |
from io import StringIO
def create_station_dataframe():
"""Creates a pandas dataframe from the csv list of all stations
downloaded from the uhrqds.
"""
files = get_station_files()
combinedlst = ""
for item in files:
for line in item.read().decode().splitlines():
try:
... | 924de681b7cc6803e83705d35fe8ad81d7a87c07 | 3,629,438 |
def _get_value_from_value_pb(value_pb):
"""Given a protobuf for a Value, get the correct value.
The Cloud Datastore Protobuf API returns a Property Protobuf which
has one value set and the rest blank. This function retrieves the
the one value provided.
Some work is done to coerce the return value... | cc3d2585d1afbb92fcf8dd363c28c1d362ee97a7 | 3,629,439 |
def load_audio(path):
"""Load audio data, mp3 or wav format
Parameters
----------
path : str
audio file path.
Returns:
-------
data : array-like
Audio data.
fs : int
Sampling frequency in Hz.
"""
if path[-4:] == ".wav":
fs... | d4c4ba20cde2332fa9e6379ddcfdd6a2a40a5e51 | 3,629,440 |
from . import operators
import inspect
def export_rule_data(variables, actions):
""" export_rule_data is used to export all information about the
variables, actions, and operators to the client. This will return a
dictionary with three keys:
- variables: a list of all available variables along with th... | d348ca2e6b79276a41da9b63764f9a56c534727d | 3,629,441 |
def produce_nm_phase_locked_sig(sig, phase_lag, n, m, wn_base, sfreq, nonsin_mode=2, kappa=None):
"""
:param sig:
:param phase_lag:
:param n:
:param m:
:param wn_base:
:param sfreq:
:param kappa:
if None, the signals are completely locked to each other
:return:
"... | 0888c40dafd96faec38cf9053c97eba8bb49b8f4 | 3,629,442 |
import functools
def patch_schedule_and_run():
"""
Patches ``luigi.interface._schedule_and_run`` to invoke all callbacks registered via
:py:func:`before_run` right before luigi starts running scheduled tasks. This is achieved by
patching ``luigi.worker.Worker.run`` within the scope of ``luigi.interfac... | aed2991df52ed54cb7861e0e4cbf4d7b7c00232a | 3,629,443 |
def randonness_test(ts, lag=None):
"""
样本的随机性检验;
:param ts:
:return:
"""
# The Run Test
"""
H0: the sequence was produced in a random manner
"""
ts = ts.dropna()
statistic, pval = runstest_1samp(ts, correction=False)
print(" The Run Test Result \n"
"=======... | 9e4325c29c07a219741664317838fcea90c56998 | 3,629,444 |
import torch
def batch_norm1d ( input # in_minibatch x 1 x in_size
, running_mean # 1 x in_size (not no minibatch)
, running_var # 1 x in_size (not no minibatch)
, weight=None # 1 x in_size
, bias=None # 1 x in_size
, eps=1E-5
... | 4ac97e421e835e4488711e0e490401be24daf558 | 3,629,445 |
def isolated_margin_account(self, **kwargs):
"""Query Isolated Margin Account Info (USER_DATA)
GET /sapi/v1/margin/isolated/account
https://binance-docs.github.io/apidocs/spot/en/#query-isolated-margin-account-info-user_data
Keyword Args:
symbols (str, optional): Max 5 symbols can be sent; se... | 6109b995f9f64f850816963fa098117f4a4230fd | 3,629,446 |
import random
def multiplex_erdos_renyi(mg, seed=None, include_all=True):
"""Return a Multinet such that each layer is an Erdos-Renyi network with
same p as the original Multinet given.
Parameters
----------
mg : Multinet
Multiplex network to be configured.
seed : object
Seed for... | 78a8e7989b0fbe53e680f35734f73ef8b5078ef2 | 3,629,447 |
import os
def load_model(model_dir,
model_file=None,
model_name=None,
serialize_model=True):
"""Loads the model from the catalog or a definition file.
Args:
model_dir: The model directory.
model_file: An optional model configuration.
Mutually exclusive w... | deacb60d7459d3ef11b82079086444cc1e6309f9 | 3,629,448 |
def homography(points1, points1_indices, points2, points2_indices, num_points=4, min_num_points=4):
"""
Computes homography matrix for given two sets of points
:param points1: First point set
:param points1_indices: First point set indices
:param points2: Second point set
:param points2_indices... | f873c5adb4f78f9e3d9e903ff4b0e4055c486a4a | 3,629,449 |
def get_sid_trid_combination_score(site_id, tr_ids_list, idfilt2best_trids_dic):
"""
Get site ID - transcript ID combination score, based on selected
transcripts for each of the 10 different filter settings.
10 transcript quality filter settings:
EIR
EXB
TSC
ISRN
ISR
ISRFC
S... | 9cc2d9a0f2fab4e4bf3030ef360b582caeaab45f | 3,629,450 |
def extract_address_from_dnb_company(dnb_company, prefix, ignore_when_missing=()):
"""
Extract address from dnb company data. This takes a `prefix` string to
extract address fields that start with a certain prefix.
"""
country = Country.objects.filter(
iso_alpha2_code=dnb_company[f'{prefix}... | 9d004152bf2091538c00b9d871ebfaba9ad09739 | 3,629,451 |
def prepare_inverse_operator(orig, nave, lambda2, dSPM):
"""Prepare an inverse operator for actually computing the inverse
Parameters
----------
orig: dict
The inverse operator structure read from a file
nave: int
Number of averages (scales the noise covariance)
lambda2: float
... | 5d48cada9c80fd77e155b737676dca2be19822d6 | 3,629,452 |
def filter_non_primary_chromosomes(df):
"""Filter out all variants that do not reside on the primary chromosomes
(i.e. 1-22, X, Y, MT)."""
# Print excluded variants for debugging/logging purpose.
exclude_indices = df.index[~df['Chromosome'].isin(["%s" % chrom for chrom in range(1, 23)] + ['X', 'Y', 'MT... | e5b646e399ffdb46952874a8fa85c8ed8a873671 | 3,629,453 |
def float_convert(d, include_keys=None, exclude_keys=None):
"""Convert elements in a document to floats.
By default, traverse all keys
If include_keys is specified, only convert the list from include_keys a.b, a.b.c
If exclude_keys is specified, only exclude the list from exclude_keys
:param d: a ... | 5bb592e20e37696c36738a41c20c1c516bb24d7c | 3,629,454 |
def bin_downsample(Ain, dsfac):
"""
Downsample an array by binning.
Parameters
----------
Ain : 2-D array
The matrix to be downsampled
dsfac : int
Downsampling factor for the matrix
Returns
-------
Aout : 2-D array
Downsampled array
"""
# Err... | 80bf451b719f6e62275c3ded950cdc34cfecaa4d | 3,629,455 |
def testComPolValidity(compol):
"""
The P3P header syntax must be one of the followings:
* P3P: CP="...", policyref="..."
* P3P: policyref="...", CP="..."
* P3P: CP="..."
* P3P: policyref="..."
---
'policyref="..."' contains ONE Link to a Policy Reference file
'CP="..."' contains spe... | c7e364d63e1afba0309b986e4344e1f792eb834a | 3,629,456 |
from typing import List
from typing import Optional
from typing import Dict
from typing import Any
import re
def sentry_event_filter( # noqa: WPS231
event, hint, ignored_types: List[str] = None, ignored_messages: List[str] = None
) -> Optional[Dict[str, Any]]:
"""Avoid sending events to Sentry that match the... | 54f4aa87a256418e9fad3a82ec57636af2420b61 | 3,629,457 |
def map_dymola_and_json(results, case, res_fin, case_dict):
"""
This function couples the .mat file variable with the final .json variable
:param results: Result obtained from the _extract_data function
:param case: Dictionary that specifies the BESTEST case
:param res_fin: Dictionary with the same... | 138224f9fd3e2060b43ca08cbc4b0af459b60b6f | 3,629,458 |
import os
def upload_word_book(request):
"""
处理上传单词本
"""
username = request.POST.get("username")
# 获取上传的文件,如果没有文件,则默认为None
word_book = request.FILES.get("word_book", None)
# 没有上传文件,没有上传txt文件
book_name = str(word_book.name)
# 错误需要重新渲染html
user = request.session['user']
# 获取... | 33bc92e91cdabcbca287efdcf321e77c58491637 | 3,629,459 |
def statusName(dictname):
"""Return the underlying key used for access to the status of the
dictlist named dictname.
"""
return (dictname, "S") | 77700d17830c1521d543551a380ad611b050bda5 | 3,629,460 |
def stydiffstat(dataNameList, SELECT_RANGE, dateStart, dateEnd):
"""
Return the place name of input places
Parameters
----------
dataNameList : list - list of strings of all participant id with shared data
SELECT_RANGE: var - flag to define if select certain period
dateStart: str - the s... | aef52a67e06013aa51ab43f1b2cc0220f7a94b72 | 3,629,461 |
def ergsperSecondtoLsun(ergss):
"""
Converts ergs per second to solar luminosity in L_sun.
:param ergss: ergs per second
:type ergss: float or ndarray
:return: luminosity in L_sun
:rtype: float or ndarray
"""
return ergss / 3.839e33 | 806b590c713bc9177db66993aff2f6feaa32d736 | 3,629,462 |
def svd(A, maxiter=30):
"""
Given a matrix A, this routine computes its SVD A = U.W.VT
- The matrix U is output mxm matrix. This mean
matrix U will have same size of matrix A.
- The matrix W is ouput as the diagonal mxn matrix that contains
the singular values
- The matrix V ... | 121efa0b27fb135af9a226a74f58feb3ac9ae9e3 | 3,629,463 |
import os
def sys_unlink(kernel: Kernel, pathname_addr: Uint):
"""
int sys_unlink(const char * pathname)
"""
pathname = kernel.kernel_read_string(pathname_addr).decode()
logger.info('sys_unlink(const char * pathname = %r)', pathname)
try:
os.unlink(pathname)
except OSError:
... | c26aae34113670137e6d2fbb836c0dee260d74fe | 3,629,464 |
import os
def make(merger, toc, default_folder, parent, bookmarks, evenpages):
"""Join several pdf files to target."""
for title, pdf, childs in toc:
if pdf.startswith(FOLDER):
pdf = os.path.join(
default_folder,
pdf.replace(FOLDER, '')
)
new... | 85638f43315b96136f0fe4d9d359cb409b1d5ed3 | 3,629,465 |
import os
from datetime import datetime
def directory_for_model(args):
"""
:param args:
:return:
"""
model_dir = os.path.join(args.models_folder, args.model)
model_img_dir = os.path.join(model_dir, 'images')
check_dir(model_img_dir)
model_video_dir = os.path.join(model_dir, 'videos'... | 5d2f6156aebad7824332ace07a8ca306b300c054 | 3,629,466 |
from typing import Any
def produces_record(obj: Any) -> bool:
"""Check if `obj` is annotated to generate records."""
if hasattr(obj, 'get_data_specs'):
return True
else:
return False | b65ffe3d599963f8f5ee4d1581179ab7567aa074 | 3,629,467 |
import json
def readJson(fname):
""" Read json file and load it line-by-line into data
"""
data = []
line_num = 0
with open(fname, encoding="utf-8") as f:
for line in f:
line_num += 1
try:
data.append(json.loads(line))
except:
... | 0a4a78ce7e36fbc444b27ca6eec3ad5ba582b7cd | 3,629,468 |
def parse_address(address):
"""Parse an address and return it as an Integer."""
if is_hex(address):
return int(address, 16)
return to_unsigned_long(gdb.parse_and_eval(address)) | a6fbde1fc69f1ea815c983e0b43455dc0030e617 | 3,629,469 |
def index(request):
"""Index page for upload images"""
form = ImageForm(request.POST or None, files=request.FILES or None)
context = {
"form": form
}
if not form.is_valid():
return render(request, "index.html", context)
image = form.save()
pixel_count_add(image.id)
return... | 7e2b31845ce492aee84de0cb275c3f0c8328a380 | 3,629,470 |
def binary_search(arr, val):
"""
Summary of binary_search function: searches an input array for a value and
returns the index to matching element in array or -1 if not found.
Parameters:
array (array): An array of values
val (integer): An integer value
Returns:
index (integer): Re... | 3d5a44b5edce3820d1e669e549f9395d9052d433 | 3,629,471 |
import os
def get_authorized_http():
"""Create an httplib2.Http wrapped with OAuth credentials.
This checks the user's configuration directory for stored
credentials. If found, it uses them. If not found, this opens a
browser window to prompt the user to sign in and authorize access
to the user... | ceb58a9148bca367bca681fe02f51f57e76561b8 | 3,629,472 |
def update_resource(resource, incoming_request):
"""Replace the contents of a resource with *data* and return an appropriate
*Response*.
:param resource: :class:`sandman.model.Model` to be updated
:param data: New values for the fields in *resource*
"""
resource.from_dict(get_resource_data(inc... | f21b679b16926fea8b1d47897bbd3f5e86d2b58c | 3,629,473 |
import types
def new_object_graph(
modules=finding.ALL_IMPORTED_MODULES, classes=None, binding_specs=None,
only_use_explicit_bindings=False, allow_injecting_none=False,
configure_method_name='configure',
dependencies_method_name='dependencies',
get_arg_names_from_class_name=(
... | d44d83a9d47260fd545ad9cb4193f927ceadff7e | 3,629,474 |
def telegram_settings():
"""set telegram client configuration.
"""
return {
'result': []
} | 01aff4c347759ca34c609b69b53b4ce4880dc803 | 3,629,475 |
def find_pointing_documents(path, index):
"""
Returns the Metadata of the documents that use a given block as a pointer.
Args:
path(str): Path to the file
index(int): Index of the block in the file
Returns:
list(Metadata): List of documents that used the block as a pointer
""... | 4e6b447cdb2c4b0a841313956d67cce59c099bf2 | 3,629,476 |
def make_shell_context():
"""注册了程序,数据库实例,以及模型,使得这些对象可直接导入shell"""
return dict(app=app, db=db, User=User, Post=Post, Category=Category,
Tag=Tag, Role=Role, Permission=Permission) | 470667f7b551817999a0c2f51660487cdd42ab51 | 3,629,477 |
import torch
def compute_jacobian(x, y, structured_tensor=False,
retain_graph=False):
"""Compute the Jacobian matrix of output with respect to input.
If input and/or output have more than one dimension, the Jacobian of the
flattened output with respect to the flattened input is retur... | bd5fd8e3e2b8171680bf059d10fadfe1c39d8899 | 3,629,478 |
def unwarp_chunk_slices_backward(mat3D, xcenter, ycenter, list_fact,
start_index, stop_index):
"""
Generate a chunk of unwarped slices [:,start_index: stop_index, :] used
for tomographic data.
Parameters
----------
mat3D : array_like
3D array. Corre... | 0f6115c63ce752d82087c93582952dae08e1d475 | 3,629,479 |
def load_data(database_filepath):
"""
Function to load data from a database
Inputs:
database_filepath (path): location of the database
Returns:
X (pandas dataframe): messages (features)
Y (pandas dataframe): categories (targets)
category_name... | 7115c50901b5edca01f92387c2971817cff6c6b7 | 3,629,480 |
def ndarray_duplicate_element_by_array(arr1,arr2):
"""
Duplicate each element in arr1[i] by the corresponding value of
arr2[i], if arr2[i]==0, then arr1[i] will be dropped in final
output, if all elements of arr2 is zero, then a None value
will be returned.
Parameters:
---------... | b2d2b3979681d818f20f47ada905756101a36488 | 3,629,481 |
import collections
def namedtuple(typename, field_names, default_value=None, default_values=()):
"""namedtuple with default value.
Args:
typename (str): type name of this namedtuple
field_names (list[str]): name of each field
default_value (Any): the default value for all fields
... | 1b387e870e3e5acfd11e5c709d21e77ebd67723d | 3,629,482 |
def log_quaternion_loss_batch(predictions, labels, params):
"""A helper function to compute the error between quaternions.
Args:
predictions: A Tensor of size [batch_size, 4].
labels: A Tensor of size [batch_size, 4].
params: A dictionary of parameters. Expecting 'use_logging', 'batch_size'.
Returns... | 39738a93a62d4330703aa58fb08fc11ac40e88ac | 3,629,483 |
from typing import List
import requests
import time
def scrape_users(basic_users: List[BasicUser]) -> List[User]:
"""Scrape user pages for list of User objects.
"""
def major_delay(base: int, offset: int) -> None:
delay = getdelay(base, offset)
print(f"\nDelaying server request for {delay}... | 5996033a94b121e545ca896c1a12b2ba887b0c0b | 3,629,484 |
def angle_section(
d: float,
b: float,
t: float,
r_r: float,
r_t: float,
n_r: int,
material: pre.Material = pre.DEFAULT_MATERIAL,
) -> geometry.Geometry:
"""Constructs an angle section with the bottom left corner at the origin *(0, 0)*, with depth
*d*, width *b*, thickness *t*, root ... | e66a2a2a717c1b1fbe02a3ba5a456bee7b3fc27e | 3,629,485 |
def normalize_adj(adj, type='sym'):
"""Symmetrically normalize adjacency matrix."""
if type == 'sym':
adj = sp.coo_matrix(adj)
rowsum = np.array(adj.sum(1))
# d_inv_sqrt = np.power(rowsum, -0.5)
# d_inv_sqrt[np.isinf(d_inv_sqrt)] = 0.
# return adj*d_inv_sqrt*d_inv_sqrt.fl... | 0e1e2c428fbfd1961c13e86279a5072b76db5951 | 3,629,486 |
def get_mb(
num):
"""get_mb
convert a the number of bytes (as an ``integer``)
to megabytes with 2 decimal points of precision
:param num: integer - number of bytes
"""
return to_f(num / NUM_BYTES_IN_AN_MB) | 984ee371db8d9f82f9bf8bcd288a1677acf483ff | 3,629,487 |
def GetComments(node, layers='core') :
"""Get the rdfs:comment(s) we find on this node within any of the specified layers."""
return GetTargets(Unit.GetUnit("rdfs:comment", True), node, layers=layers ) | 61959b90ff8f522bcfdda637e3cb01284f899548 | 3,629,488 |
def _ValidateObbFileList(arg_internal_name, arg_value):
"""Validates that 'obb-files' contains at most 2 entries."""
arg_value = ValidateStringList(arg_internal_name, arg_value)
if len(arg_value) > 2:
raise test_exceptions.InvalidArgException(
arg_internal_name, 'At most two OBB files may be specified... | b99604b220e475ae858908f2decba0af4fd0bf07 | 3,629,489 |
def _depol_error_value_one_qubit(gate_error, gate_time=0, t1=inf, t2=inf):
"""Return 2-qubit depolarizing channel probability for device model"""
# Check trivial case where there is no gate error
if gate_error is None:
return None
if gate_error == 0:
return 0
# Check t1 and t2 are v... | 135304ea8853f81aba5ad00bf7a556072fcb8370 | 3,629,490 |
def meh(text):
"""
>>> meh(EXAMPLE_INPUT)
[3, 8, 9, 1, 2, 5, 4, 6, 7]
"""
return [int(c) for c in text] | a295b94395f132cf4f8906fb293e9c989da1d7d1 | 3,629,491 |
def get_latest_dataset():
""" Return latest dataset that was created """
return getattr(qcodes.DataSet._latest, None) | 7179904df6a7d2269ad845c5401f934ec4527bed | 3,629,492 |
def insert_newlines(text, line_length):
"""
Given text and a desired line length, wrap the text as a typewriter would.
Insert a newline character ("\n") after each word that reaches or exceeds
the desired line length.
text: a string containing the text to wrap.
line_length: the number of charac... | 3f6ef4dc02cac415c586be04c86b032b415ef0ea | 3,629,493 |
def gen_annular_fpm(inputs):
"""
Generate an annular FPM using PROPER.
Outside the outer ring is opaque.If rhoOuter = infinity, then the outer
ring is omitted and the mask is cropped down to the size of the inner spot.
The inner spot has a specifyable amplitude value. The output array is the
sm... | 74591fb8a5eeccc332d804b0c8c757ecc4bd52c1 | 3,629,494 |
import time
import re
def _get_time_ts(string: str) -> float:
"""
通过传入的字符串获取时间戳
"""
year = time.localtime().tm_year
month = re.search(r"(\d+)月", string).group(1)
day = re.search(r"(\d+)日", string).group(1)
return time.mktime(time.strptime(f"{year}-{month:>02}-{day:>02}", "%Y-%m-%d")) | bce5550c23bb3f60ada2e0a8fdc1054a347fdecc | 3,629,495 |
def octresnet10_ad2(**kwargs):
"""
Oct-ResNet-10 (alpha=1/2) model from 'Drop an Octave: Reducing Spatial Redundancy in Convolutional Neural Networks
with Octave Convolution,' https://arxiv.org/abs/1904.05049.
Parameters:
----------
pretrained : bool, default False
Whether to load the p... | 1eab26df3ac3c8b4f7a905e9dc90d602d7ef2672 | 3,629,496 |
import base64
import sys
import pickle
import subprocess
def create_standalone_plot(fig, fname, backend=None):
"""
Create a script which can be executed to plot the given figure.
Pickles the figure and stores it as string in the script.
Parameter
---------
fig : matplotlib.figure.Figure
... | 2fd128d46f1abd89364046444d0ccd99527afb70 | 3,629,497 |
import os
def getdict_userid_username():
"""
Make a dictionary to map from Moodle user IDs to user names
"""
dict_userid_username = {}
userxml = os.path.join("backup","users.xml")
docs = parse(userxml)
users = docs.getElementsByTagName("user")
for user in users:
userid = int(us... | e4fcea087e8f2bac0277a56fe641e3dbe5af65c4 | 3,629,498 |
def generate_template(global_entity, sentence, sent_ent, kb_arr, domain):
"""
code from GLMP: https://github.com/jasonwu0731/GLMP/blob/master/utils/utils_Ent_kvr.py
Based on the system response and the provided entity table, the output is the sketch response.
"""
sketch_response = []
if sent_ent... | d409a21965ce84e09fc785172aae9fdd41726d69 | 3,629,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.