content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def plat_specific_errors(*errnames):
"""Return error numbers for all errors in errnames on this platform.
The 'errno' module contains different global constants depending on
the specific platform (OS). This function will return the list of
numeric values for a given list of potential names.
"""
... | 27,700 |
def fft(array, nfft=None, dim=None, dx=None, detrend=None, tapering=False,
shift=True, sym=False, chunks=None):
"""Compute the spectrum on several dimensions of xarray.DataArray objects
using the Fast Fourrier Transform parrallelized with dask.
Parameters
----------
array : xarray.DataArray
Array from w... | 27,701 |
def make_symmetric_matrix(d: Union[list, float]) -> list:
"""
d (list or float):
len(d) == 1: Suppose cubic system
len(d) == 3: Suppose tetragonal or orthorhombic system
len(d) == 6: Suppose the other system
"""
if isinstance(d, float):
tensor = [[d, 0, 0], [0, d, 0], [0,... | 27,702 |
def convert_lds_to_block_tridiag(As, bs, Qi_sqrts, ms, Ri_sqrts):
"""
Parameterize the LDS in terms of pairwise linear Gaussian dynamics
and per-timestep Gaussian observations.
p(x_{1:T}; theta)
= [prod_{t=1}^{T-1} N(x_{t+1} | A_t x_t + b_t, Q_t)]
* [prod_{t=1}^T N(x_t |... | 27,703 |
def tearDownModule():
# pylint: disable=invalid-name
"""TearDown for the whole unittests.
- Remove all the created persisted data.
"""
print("tearDownModule Begin.")
CF.util.clear_face_lists()
CF.util.clear_person_groups()
CF.util.clear_large_face_lists()
CF.util.clear_lar... | 27,704 |
def extract_string_from_tensor(input_ids, mode="single", config=None, tokenizer=None):
"""
Args:
input_ids (Tensor): input sentences with shape [batch_size, seq_len].
mode (str): ["pair", "single"]
"pair" for tasks with paired inputs `<bos> A <eos> B <eos>`,
... | 27,705 |
def schema_validation_matching(source_fields, target_fields):
"""Compare schemas between two dictionary objects"""
results = []
# Go through each source and check if target exists and matches
for source_field_name, source_field_type in source_fields.items():
# target field exists
if sour... | 27,706 |
def find_thirdparty_marshaller_plugins():
""" Find, but don't load, all third party marshaller plugins.
Third party marshaller plugins declare the entry point
``'hdf5storage.marshallers.plugins'`` with the name being the
Marshaller API version and the target being a function that returns
a ``tuple`... | 27,707 |
def justTransportResponse(transport):
"""
Helper function for creating a Response which uses the given transport.
All of the other parameters to L{Response.__init__} are filled with
arbitrary values. Only use this method if you don't care about any of
them.
"""
return Response((b'HTTP', 1, ... | 27,708 |
def get_tools_location() -> str:
"""Get the path to the Alteryx Python SDK Tools directory."""
admin_path = os.path.join(os.environ["APPDATA"], "Alteryx", "Tools")
user_path = os.path.join(os.environ["PROGRAMDATA"], "Alteryx", "Tools")
if contains_path(__file__, admin_path):
return admin_path
... | 27,709 |
def test_url_raise_error(tmpdir):
"""ValueError is raised if there is no valid character to be used as filename."""
with pytest.raises(ValueError):
download.sanitize_url(_URL_RAISE_ERROR)
with pytest.raises(ValueError):
download.maybe_download_and_extract(tmpdir, _URL_RAISE_ERROR) | 27,710 |
def object_comparator_lookup(src_obj, dst_obj):
"""
Compare an object with another entry by entry
"""
dont_match = []
no_upstream = []
for i in dst_obj:
count_name = 0
count_value = 0
for j in src_obj:
if list(j.keys())[0] == list(i.keys())[0]:
... | 27,711 |
def line(
data_frame=None,
x=None,
y=None,
line_group=None,
color=None,
line_dash=None,
hover_name=None,
hover_data=None,
custom_data=None,
text=None,
facet_row=None,
facet_row_weights=None,
facet_col=None,
facet_col_weights=None,
facet_col_wrap=0,
facet_r... | 27,712 |
def is_primitive(v):
"""
Checks if v is of primitive type.
"""
return isinstance(v, (int, float, bool, str)) | 27,713 |
def linkify_only_full_urls(attrs, new=False):
"""Linkify only full links, containing the scheme."""
if not new: # This is an existing <a> tag, leave it be.
return attrs
# If the original text doesn't contain the scheme, don't linkify.
if not attrs['_text'].startswith(('http:', 'https:')):
... | 27,714 |
def update_learning_rate_rel(optimizer, cur_lr, new_lr):
"""Update learning rate"""
if cur_lr != new_lr:
ratio = _get_lr_change_ratio(cur_lr, new_lr)
if ratio > cfg.TRAIN.LOG_LR_CHANGE_THRESHOLD:
print('Changing learning rate %.6f -> %.6f', cur_lr, new_lr)
# Update learning r... | 27,715 |
def _oauth_error(handler, error_msg, error):
"""Set expected status and error formatting for Oauth2 style error
Parameters
----------
error_msg : str
Human parsable error message
error : str
Oauth2 controlled vocab error
Returns
-------
Writes out Oauth2 formatted error JS... | 27,716 |
def brain_viz_nodes(nodes,title,method,node_size):
"""
"""
global coordinates
NEWcoordinates = coordinates[nodes,:]
node_size = np.array(node_size).astype('float32')
node_size-=np.mean(node_size)
if np.std(node_size)!=0:
node_size/=np.std(node_size)
if method == '2d':
... | 27,717 |
def test_captchasolution_obj_get_string(captcha_class):
"""
Checks get_type() function of CaptchaSolution class.
"""
solution_class = captcha_class.get_solution_class()
fields_count = len(solution_class.__dataclass_fields__)
field_values = [f'field{n}' for n in range(fields_count)]
solution_... | 27,718 |
def retrieve_model_list(opt):
"""
retrive the model information from form a directory.
:param opt: parser
:return: list of Checkpoint object.
"""
files = os.listdir(os.path.join(opt.dir, 'models'))
files.sort()
# file name format "address/$NAME_acc_XX.YY_ppl_XX.YY_eZZ.pt"
valid_addre... | 27,719 |
def plotTopFiveContributors():
"""
根据authorDict绘制扇形图,并保存至/staic/image,名为TopFiveContributors.png
"""
authorDict = getAuthorCommitDict()
# 按值从大到小进行排序
sortedList = Counter(authorDict).most_common()
size, labels = selectTopFive(sortedList)
# 偏移量
explode = [0.02, 0.02, 0.02, 0.02, 0.02]
... | 27,720 |
def _read_filenames_in_dir(path, extension):
"""Returns the name of the Yaml files in a certain directory
Arguments
---------
path: str
Path to directory
extension: str
Extension of files (such as: '.yml' or '.csv')
Returns
-------
list
The list of files in `pat... | 27,721 |
def setup_cccc_tool_plugin(use_plugin_context=True, binary=None, cccc_config=None):
"""Create an instance of the CCCC plugin."""
arg_parser = argparse.ArgumentParser()
arg_parser.add_argument("--cccc-bin", dest="cccc_bin")
arg_parser.add_argument("--cccc-config", dest="cccc_config")
resources = Res... | 27,722 |
def submit_script_to_scheduler(
script: str,
proc_type: int,
queue_folder: str,
sim_dir: str,
run_name: str,
target_machine: str = None,
logger: Logger = get_basic_logger(),
):
"""
Submits the slurm script and updates the management db.
Calling the scheduler submitter may result ... | 27,723 |
def _valid_dir(path, description):
""" Check if the path is a valid directory.
@param path: Path which should be checked.
@type path: str
@param description: Description which is used for the error
message if necessary.
@ty... | 27,724 |
def Precedence(op):
"""The numeric precedence of a binary operator."""
# Particularly convenient during layout of binary operators.
return float(sum(i * (op in grp[1:])
for i, grp in enumerate(precedence))) / len(precedence) | 27,725 |
def _FeastToExampleTransform(
pipeline: beam.Pipeline, exec_properties: Dict[str, Any], split_pattern: str
) -> beam.pvalue.PCollection:
"""Read from BigQuery and transform to TF examples.
Args:
pipeline: beam pipeline.
exec_properties: A dict of execution properties.
split_pattern: Split... | 27,726 |
def fluxional_mode(atom_indices, span=360.0):
""" Writes the string for each fluxional mode
"""
# Format the aotm indices string
atom_indices = util.format_flux_mode_indices(atom_indices)
# Create dictionary to fill template
flux_mode_keys = {
'atom_indices': atom_indices,
'spa... | 27,727 |
def test_create_geom_init_and_pass_vars():
"""init with an object and pass vars - should raise warning"""
g = vol.IsoSurfGeom(data='fake_data', dbname='fake_db')
with pytest.warns(None) as warn_info:
g.create_geometry(data=dataname, dbname=exp_db)
assert(len(warn_info) == 2) # initial warning, ... | 27,728 |
def reply_handler(bot, update):
"""Reply message."""
"""check with from id"""
global last_reply_time
username = update.message.from_user.username
text = update.message.text
logger.info(text)
logger.info(username)
if username == 'cming_ou':
now = datetime.datetime.now()
di... | 27,729 |
def parse_host_info(qhost_tree, queues_tree, queues_to_ignore=[]):
"""
:return: dictionary key: host, value HostInfo
"""
dctRet = {}
for host_node in qhost_tree.findall('host'):
host_name = host_node.get('name')
dct_hostvalues = dict([(hostvalue_node.get('name'), hostvalue_node.text)... | 27,730 |
def select(pTable, purged=False, proxyService=None):
"""
for all OBJECT cells select the candidate whose value is most similar to the original one
ties are broken by popularity, i.e. the entity with the most incoming links
can be executed either on the remaining candidates or the purged candidates
"... | 27,731 |
def download_artifacts(file_name, file_type, file_extension, file_url):
"""
get run artifacts
Arguments:
file_name (str): file name
file_type (str): file type
file_extension (str): file extension
file_url (str): file url
"""
work_directory = os.getcw... | 27,732 |
def marc2rf_researcherFormat(marc_path, request_path, output_folder, options, debug=False):
"""Convert MARC records to Researcher Format.
:rtype: object
:param marc_path: Path to file of MARC records.
:param request_path: Path to Outlook message containing details of the request.
:param outpu... | 27,733 |
def _get_param_type_from_str(
type_name: str = None,
param_doc: docstring_parser.DocstringParam = None,
) -> t.Tuple[_ParamArgs, t.Union[click.ParamType, None]]:
"""Guess parameter type from parameter type name."""
type_name = type_name or ""
desc = param_doc.description if param_doc else ""... | 27,734 |
def solve(task: str) -> int:
"""How many differently colored bags can contain shiny gold?"""
parents = process_data(task)
seen = set()
candidates = parents["shiny gold"]
while candidates:
candidate = candidates.pop()
if candidate not in seen:
seen.add(candidate)
... | 27,735 |
def create_users_table():
"""Creates the users table."""
con, cur = create_con()
cur.execute('CREATE TABLE IF NOT EXISTS users('
'username TEXT PRIMARY KEY,'
'password TEXT NOT NULL,'
'role TEXT NOT NULL);')
con.commit()
cur.close()
con.cl... | 27,736 |
def cityDesc(codePostal):
"""
code de retour :
100 : tout est normal
200 : la requete n'a pas abouti
300 : pas de cine dans la ville
400 : la ville n'existe pas
"""
headersUA = init_connect()
YMDstr = getDate()
searchField = codePostal
filterField = ''
countField = '500'
pageField = '1'
url =... | 27,737 |
async def test_atomic_update(client: Client) -> None:
"""Atomically updating a float value"""
model = await client.types.create({'id': 1, 'float_': 1})
assert model.float_ == 1
updated = await client.types.update(
where={
'id': 1,
},
data={
'float_': {'in... | 27,738 |
async def get_reposet(request: AthenianWebRequest, id: int) -> web.Response:
"""List a repository set.
:param id: Numeric identifier of the repository set to list.
:type id: repository set ID.
"""
rs_cols = [
RepositorySet.name,
RepositorySet.items,
RepositorySet.precomputed... | 27,739 |
def test_delete(cursor, run):
"""verify delete operation"""
test = MockTable(the_key=100, name='foo')
run(test.delete, cursor)
assert cursor.query == \
"DELETE FROM 'tester' WHERE 'the_key'=%s"
assert cursor.query_after == \
"DELETE FROM 'tester' WHERE 'the_key'=100" | 27,740 |
def _train(params: Dict,
dtrain: RayDMatrix,
model_factory: Type[LGBMModel],
boost_rounds_left: int,
*args,
evals=(),
ray_params: RayParams,
cpus_per_actor: int,
gpus_per_actor: int,
_training_state: _TrainingState,
... | 27,741 |
def web_entity_detection(inputpath, outputpath):
"""
docstring
"""
for folder in os.listdir(inputpath):
# get the absolute path of input
filepath_in = os.path.join(inputpath, folder)
# get the absolute path of output
filepath_out = os.path.join(outputpath, folder)
... | 27,742 |
def is_called_at_module_level() -> bool:
"""
Check if the current function is being called at the module level.
Raise `RuntimeError` if `is_called_at_module_level()` is not called in a function.
"""
if not (frame := getcallerframe().f_back):
raise RuntimeError(
"is_called_at_mo... | 27,743 |
def raise_for_failed_build(module_build_ids):
"""
Raises an exception if any module build from `module_build_ids` list is in failed state.
This function also calls "failed" handler before raises an exception.
:param list module_build_ids: List of module build IDs (int) to build locally.
"""
bui... | 27,744 |
def extract_dominant_keypoints2D(keypoint_2D, dominant_hand):
""" Extract keypoint 2D.
# Look Later with Octavio
# Arguments
keypoint_2D: Numpy array of shape (num_keypoints, 1).
dominant_hand: List of size (2) with booleans.
# Returns
keypoint_visibility_2D_21: Numpy array of s... | 27,745 |
def NN_regressor(X_train, Y_train, X_valid, Y_valid):
"""
Trains a neural network to perform regression on the dataset. Makes predictions
on the validation set, and prints out the validation loss from a least squares
regression versus that of the neural network regression.
Input:
X_train, Y_tra... | 27,746 |
def verify_mailgun_request(timestamp, token, signature):
"""
Ensures that a webhook request from Mailgun is valid.
Raises an exception if the request is invalid.
"""
# Check to avoid reused tokens to prevent replay attacks.
global cached_mailgun_token
if token == cached_mailgun_token:
... | 27,747 |
def translation_ev(h, t, tol=1e6):
"""Compute the eigenvalues of the translation operator of a lead.
Adapted from kwant.physics.leads.modes.
Parameters
----------
h : numpy array, real or complex, shape (N, N) The unit cell
Hamiltonian of the lead unit cell.
t : numpy array, real or co... | 27,748 |
def bsearch(n, pred):
"""
Given a boolean function pred that takes index arguments in [0, n).
Assume the boolean function pred returns all False and then all True for
values. Return the index of the first True, or n if that does not exist.
"""
# invariant: last False lies in [l, r) and pred(l) i... | 27,749 |
def test_rotating_file_handler_interval(tmpdir, logger, monkeypatch):
"""Test the rotating file handler when the rollover return a time smaller
than the current time.
"""
def rollover(obj, current_time):
return current_time - 0.1
monkeypatch.setattr(DayRotatingTimeHandler, 'computeRollover... | 27,750 |
def compute_zero_crossing_wavelength(period, water_depth, gravity=GRAVITY):
"""Computes zero-crossing wavelength from given period.
This uses the dispersion relation for linear waves.
"""
return wavenumber_to_wavelength(
frequency_to_wavenumber(1. / period, water_depth, gravity)
) | 27,751 |
def problem1b(m, f):
"""
What comes in: Positive integers m and f such that m >= 2.
What goes out:
-- Returns the number of integers from m to (f * m),
inclusive, that are prime.
Side effects: None.
Examples:
-- If m is 3 and f is 5, this function returns 5,
since ... | 27,752 |
def run(is_cpp):
"""Passes its arguments directly to pnacl-clang.
If -fsanitize-address is specified, extra information is passed to
pnacl-clang to ensure that later instrumentation in pnacl-sz can be
performed. For example, clang automatically inlines many memory allocation
functions, so this scri... | 27,753 |
def launch_transport_listener(transport, bindaddr, role, remote_addrport, pt_config, ext_or_cookie_file=None):
"""
Launch a listener for 'transport' in role 'role' (socks/client/server/ext_server).
If 'bindaddr' is set, then listen on bindaddr. Otherwise, listen
on an ephemeral port on localhost.
'... | 27,754 |
def div(style, render=False, label=''):
"""Render divider."""
if len(style) == 1:
if label == '':
res = hfill('', style)
else:
res = hfill(style * 2 + ' ' + label + ' ', style)
elif style[0] == style[-1]:
# Windows does line wrapping weird
sp_left = '... | 27,755 |
def send_array(A, flags=0, copy=True, track=False):
"""send a numpy array with metadata
Inputs
------
A: (subplots,dim) np array to transmit
subplots - the amount of subplots that are
defined in the current plot
dim - the amount of data that you want to plot.
... | 27,756 |
async def test_single_group_role():
"""Test with single group role for happy path when multiples users are granted group role."""
data = {"group": [("group", "user"), ("group", "user2"), ("group", "user3")]}
role_service = FakeRoleService(data)
users_with_roles = await get_users_with_roles(role_service,... | 27,757 |
def test__job_create_manual_rollback(client):
"""
Start a job update, and half-way to a manual rollback
"""
res = client.start_job_update(
get_job_update_request("test_dc_labrat_large_job.yaml"),
"start job update test/dc/labrat_large_job",
)
job_update_key = res.key
job_key ... | 27,758 |
def api_file_upload(request):
""" Upload a file to the storage system """
try:
fobj = request.FILES["file"]
checksum, ext = fobj._name.split(".")
try:
request.user.check_staged_space(fobj._size, checksum)
except Exception as e:
return HttpResponseForbidden... | 27,759 |
def calculateAggregateInterferenceForGwpz(gwpz_record, grants):
"""Calculates per-channel aggregate interference for GWPZ.
Args:
gwpz_record: A GWPZ record dict.
grants: An iterable of CBSD grants of type |data.CbsdGrantInfo|.
Returns:
Aggregate interference to GWPZ in the nested dictionary format.
... | 27,760 |
def from_pandas_ephemeral(
engine: Engine,
df: pandas.DataFrame,
convert_objects: bool,
name: str
) -> DataFrame:
"""
Instantiate a new DataFrame based on the content of a Pandas DataFrame. The data will be represented
using a `select * from values()` query, or something simi... | 27,761 |
def cmdline_upload():
"""upload docker image to glance via commandline"""
# only admin can upload images from commandline
os.environ.update({'OS_USERNAME': 'admin'})
cmd = "docker save {name} | " \
"glance image-create " \
"--is-public=True " \
"--container-format=docker " ... | 27,762 |
def set_vars(api, file:str, tess_profile:dict):
"""
Reads the user-specific variables from the tess_profile
:param api:
:param file:
:param tess_profile:
:return:
"""
# Set necessary information
api.SetImageFile(file)
# Set Variable
api.SetVariable("save_blob_choices", "T")
... | 27,763 |
def qtrfit(numpoints, defcoords, refcoords, nrot):
"""Find the quaternion, q, [and left rotation matrix, u] that minimizes
| qTXq - Y | ^ 2 [|uX - Y| ^ 2]
This is equivalent to maximizing Re (qTXTqY)
The left rotation matrix, u, is obtained from q by
u = qT1q
Parameters
numpoint... | 27,764 |
def _embedded_bundles_partial_impl(
ctx,
bundle_embedded_bundles,
embeddable_targets,
frameworks,
plugins,
watch_bundles):
"""Implementation for the embedded bundles processing partial."""
_ignore = [ctx]
embeddable_providers = [
x[_AppleEmbeddableInf... | 27,765 |
def load_instrument(yml):
"""
Instantiate an instrument from YAML spec.
Parameters
----------
yml : str
filename for the instrument configuration in YAML format.
Returns
-------
hexrd.instrument.HEDMInstrument
Instrument instance.
"""
with open(yml, 'r') as f:
... | 27,766 |
def serialize_model(self: models.Model, excludes: List[str] = None) -> dict:
"""
模型序列化,会根据 select_related 和 prefetch_related 关联查询的结果进行序列化,可以在查询时使用 only、defer 来筛选序列化的字段。
它不会自做主张的去查询数据库,只用你查询出来的结果,成功避免了 N+1 查询问题。
# See:
https://aber.sh/articles/A-new-idea-of-serializing-Django-model/
"""
excl... | 27,767 |
def p_object_list_path(p):
"""
object_list_path : object_path object_path_expr
"""
p[0] = p[1] + p[2] | 27,768 |
def isint(x):
"""
For an ``mpf`` *x*, or any type that can be converted
to ``mpf``, determines whether *x* is exactly
integer-valued::
>>> from sympy.mpmath import *
>>> isint(3), isint(mpf(3)), isint(3.2)
(True, True, False)
"""
if isinstance(x, int_types):
retu... | 27,769 |
def update_header(file):
"""
Create a standard WCS header from the HDF5 header. To do this we clean up the
header data (which is initially stored in individual arrays). We then create
a new header dictionary with the old cleaned header info. Finally, we use
astropy.wcs.WCS to create an updated WCS h... | 27,770 |
def test_fltruncate(doctest):
"""
! (require racket/flonum)
> (fltruncate 2.5)
2.0
> (fltruncate -2.5)
-2.0
> (fltruncate +inf.0)
+inf.0
""" | 27,771 |
def get_MD_psat():
""" MD data for saturation densities:
Thermodynamic properties of the 3D Lennard-Jones/spline model
Bjørn Hafskjold and Karl Patrick Travis and Amanda Bailey Hass and
Morten Hammer and Ailo Aasen and Øivind Wilhelmsen
doi: 10.1080/00268976.2019.1664780
"""
T = np.array([0.... | 27,772 |
def get_reddit_client():
"""Utility to get a Reddit Client"""
reddit_username = redditUsername
reddit_password = redditPassword
reddit_user_agent = redditUserAgent
reddit_client_secret = redditClientSecret
reddit_client_id = redditClientID
logging.info("Logged in as user (%s).." % reddit_us... | 27,773 |
def handle_leet(command: Command) -> None:
"""
`!leet [`easy` | `medium` | `hard`] - Retrieves a set of questions from online coding
websites, and posts in channel with a random question from this set. If a difficulty
is provided as an argument, the random question will be restricted to this level of
... | 27,774 |
def get_member_id():
"""
Retrieve member if for the current process.
:rtype: ``bytes``
"""
proc_info = system_info.get_process_info()
member_id = six.b('%s_%d' % (proc_info['hostname'], proc_info['pid']))
return member_id | 27,775 |
def get_table_arn():
"""A method to get the DynamoDB table ARN string.
Returns
-------
dict
A dictionary with AWS ARN string for the table ARN.
"""
resp = dynamodb_client.describe_table(
TableName=table_name
)
return {
"table_arn": resp['Table']['TableArn']
} | 27,776 |
def replace_characters(request):
"""Function to process execute replace_characters function."""
keys = ['text', 'characters', 'replacement']
values = get_data(request, keys)
if not values[0]:
abort(400, 'missing text parameter')
if not values[2]:
values[2] = ''
return _call('r... | 27,777 |
def serialize_to_jsonable(obj):
"""
Serialize any object to a JSONable form
"""
return repr(obj) | 27,778 |
def move():
"""Move namespaces/files from one parent folder to another
"""
pass | 27,779 |
def test_godlikea(err, xpi_package):
"""Test to make sure that the godlikea namespace is not in use."""
if 'chrome/godlikea.jar' in xpi_package:
err.error(
err_id=('testcases_packagelayout',
'test_godlikea'),
error="Banned 'godlikea' chrome namespace",
... | 27,780 |
def compare(optimizers, problems, runs=20, all_kwargs={}):
"""Compare a set of optimizers.
Args:
optimizers: list/Optimizer; Either a list of optimizers to compare,
or a single optimizer to test on each problem.
problems: list/Problem; Either a problem instance or a list of problem ... | 27,781 |
def az_el2norm(az: float, el: float):
"""Return solar angle as normalized vector."""
theta = np.pi/2-el*np.pi/180
phi = az*np.pi/180
norm = np.asarray(
[
np.sin(theta)*np.cos(phi),
np.sin(theta)*np.sin(phi),
np.cos(theta)
])
return norm | 27,782 |
async def api_get_user(user_id: int, db: Session = Depends(get_db)):
"""
Gets user entity
- **user_id**: the user id
- **db**: current database session object
"""
try:
user = await User.get_by_id(id=user_id, db=db)
return user
except UserNotFoundException as e:
... | 27,783 |
def remove_comments(json_like):
"""
Removes C-style comments from *json_like* and returns the result. Example::
>>> test_json = '''\
{
"foo": "bar", // This is a single-line comment
"baz": "blah" /* Multi-line
Comment */
}'''
>>> remove_commen... | 27,784 |
def test_extract_multiple_ranges_for_file():
"""Check multiple ranges in a single file.
Note: Final region is at end of file and does not have a trailing
context line.
"""
diffs = """diff --git a/whodunit.py b/whodunit.py
index 2af698e..79da120 100644
--- a/whodunit.py
+++ b/whodunit.py
@@ -475,8 +... | 27,785 |
def install_editable(projectroot, **kwargs):
"""Install the given project as an "editable" install."""
return run_pip('install', '-e', projectroot, **kwargs) | 27,786 |
def retry_get(tap_stream_id, url, config, params=None):
"""Wrap certain streams in a retry wrapper for frequent 500s"""
retries = 20
delay = 120
backoff = 1.5
attempt = 1
while retries >= attempt:
r = authed_get(tap_stream_id, url, config, params)
if r.status_code != 200:
... | 27,787 |
def build_trie_from_to(template_dictionary: Mapping, from_timestamp: datetime.datetime, to_timestamp: datetime.datetime) -> Tuple[ahocorasick.Automaton, Mapping]:
"""Function which builds the trie from the first timestamp tot the last one given"""
trie = ahocorasick.Automaton()
words_mapping = dict() # wor... | 27,788 |
def check_monotonicity_at_split(
tree_df, tree_no, trend, variable, node, child_nodes_left, child_nodes_right
):
"""Function to check monotonic trend is in place at a given split in a single tree."""
if not isinstance(tree_df, pd.DataFrame):
raise TypeError("tree_df should be a pd.DataFrame")
... | 27,789 |
def allocate_usda_ers_mlu_land_in_urban_areas(df, attr, fbs_list):
"""
This function is used to allocate the USDA_ERS_MLU activity 'land in
urban areas' to NAICS 2012 sectors. Allocation is dependent on
assumptions defined in 'literature_values.py' as well as results from
allocating 'EIA_CBECS_Land'... | 27,790 |
def verify_flash(octowire_ser, fw):
"""
Verify Flash contents (against a given firmware image)
:param octowire_ser: Octowire serial instance
:param fw: Buffer containing the firmware image
:return: Nothing
"""
print(f"{Colors.OKBLUE}Verifying flash...{Colors.ENDC}")
pages = math.ceil(len... | 27,791 |
def start():
"""
THIS IS WHAT calls function `job` repetitively.
note: you can set `INTERVAL_SECONDS` param in settings.py
"""
scheduler = BackgroundScheduler()
scheduler.add_job(job, 'interval', seconds=settings.INTERVAL_SECONDS)
scheduler.start() | 27,792 |
def get_distances_between_points(ray_points3d, last_bin_width=1e10):
"""Estimates the distance between points in a ray.
Args:
ray_points3d: A tensor of shape `[A1, ..., An, M, 3]`,
where M is the number of points in a ray.
last_bin_width: A scalar indicating the witdth of the last bin.
Returns:
... | 27,793 |
def test_form__DatetimeDataConverter__toWidgetValue__1(DatetimeDataConverter):
"""`toWidgetValue` renders datetime with timezone localized."""
assert u'13/02/01 21:20' == DatetimeDataConverter.toWidgetValue(
datetime(2013, 2, 1, 17, 20, tzinfo=utc)) | 27,794 |
def reclassification_heavy_duty_trucks_to_light_commercial_vehicles(register_df: pd.DataFrame) -> pd.DataFrame:
"""
Replace Category to Light Commercial Vehicles for Heavy Duty Trucks of weight below 3500kg
Es Tracta de vehicles registrats TIPUS CAMIONS i per tant classificats en la categoria Heavy Duty Tr... | 27,795 |
def test_create_update_and_delete_room_team_roles(
db: Session,
client: TestClient,
data: Data,
) -> None:
"""
This test is responsible for checking the ability
to create, update and delete team roles for a dataroom
"""
auth_header = create_access_header(data.admin_user_room_2)
new... | 27,796 |
def SpComp(rho, U, mesh, fea, penal):
"""Alias SpCompFunction class with the apply method"""
return SpCompFunction.apply(rho, U, mesh, fea, penal) | 27,797 |
def remove_event_class(request):
"""
Remove the given event class, and update the
order of the rest classes
"""
if request.user.is_authenticated:
class_id = request.POST.get("classId", None)
event_class = EventClass.get_classes_by_user(request.user.id).get(id=class_id)
event_... | 27,798 |
def get_landmark_position_from_state(x, ind):
"""
Extract landmark position from state vector
"""
lm = x[STATE_SIZE + LM_SIZE * ind: STATE_SIZE + LM_SIZE * (ind + 1), :]
return lm | 27,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.