content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def call_status():
"""
入浴状態を取得
入浴前:0
入浴中:1
入浴後:2
:return:
"""
user_id = "testuser"
result_dict = check_status(user_id)
return jsonify(result_dict) | 9ef37eeb309c64cb7b4759323b4cb9569b910c65 | 31,674 |
def dice_loss(pred, target, smooth=1.):
"""Dice loss
"""
pred = pred.contiguous()
target = target.contiguous()
intersection = (pred * target).sum(dim=2).sum(dim=2)
loss = (1 - ((2. * intersection + smooth) / (pred.sum(dim=2).sum(dim=2) + target.sum(dim=2).sum(dim=2) + smooth)))
return los... | 5879769ac379395e35f9accda9d917094aa07301 | 31,675 |
def _get_scope_contacts_by_object_id(connection, object_id,
object_type, scope_contact_type):
"""Gets scope contacts by object id.
Args:
connection: Database connection.
object_id: An integer value of scope object id.
object_type: A string value of scope object type... | c7c1fe05cb48fb5e28499f995a8c606c9e421d6e | 31,676 |
import re
def remove_mentions(text):
"""Remove @-mentions from the text"""
return re.sub('@\w+', '', text) | 5cbdd40a602f24f8274369e92f9159cbb2f6a230 | 31,677 |
def put_thread(req_thread: ReqThreadPut):
"""Put thread for video to DynamoDB"""
input = create_update_item_input(req_thread)
try:
res = client.update_item(**input)
return res
except ClientError as err:
err_message = err.response["Error"]["Message"]
raise HTTPException(... | 733370296c022a985b49193a1b528e0df8271624 | 31,678 |
from admin.admin_blueprint import admin_blueprint
from questionnaire.questionnaire_blueprint import questionnaire_blueprint
from user.user_blueprint import user_blueprint
def create_app(config_name: str):
"""Application factory
Args:
config_name (str): the application config name to determine which e... | 13e171d780f87ffad0802703ab72483669bc3453 | 31,679 |
import numpy
def get_clean_num(num):
"""
Get the closest clean number match to num with bases 1, 2, 5.
Args:
num: the number
Returns:
the closest number
"""
if num == 0: return 0
sign = num > 0 and 1 or -1
exp = get_exp(num)
nums = numpy.array((1, 2, 5, 10))*(10**... | 09b4f5893e8d33a16217a2292ca75d7730e5d90e | 31,680 |
def with_config_error(func):
"""Add config error context."""
@wraps(func)
def wrapper(*args, **kwargs):
with config_key_error():
return func(*args, **kwargs)
return wrapper | 667ab25648c17d087fbc54fd9d284c98c40b4b0b | 31,681 |
def _flat(l):
"""Flattens a list.
"""
f = []
for x in l:
f += x
return f | 9b2e432d79f08840d417601ff950ff9fa28073ef | 31,682 |
def axesDict(T_axes):
"""Check connectivity based on Interval Vectors."""
intervalList = [
T_axes[0],
T_axes[1],
T_axes[2],
(12 - T_axes[0]),
(12 - T_axes[1]),
(12 - T_axes[2])]
return intervalList | 6b1e8c59d12a3c2c548b95f3bcd8d7a3de4ef931 | 31,683 |
def _settings_to_component(
name: str,
settings: configuration.ProjectSettings,
options: amos.Catalog) -> bases.Projectbases.Component:
"""[summary]
Args:
name (str): [description]
settings (configuration.ProjectSettings): [description]
options (amos.Catalog): [description]... | 7e709a27b275587ce742c08d10efbd7b0aa171ce | 31,684 |
import ipdb
import tqdm
def iss(data, gamma21, gamma32, KDTree_radius, NMS_radius, max_num=100):
"""
Description: intrinsic shape signatures algorithm based on cuda FRNN and cuda maximum suppression
Args:
data: numpy array of point cloud, shape(num_points, 3)
gamma21:
gamma32:
... | bf2b84ed179314334a6e7a88f84f6f86468006dd | 31,685 |
import requests
def login_wechat():
"""
This api logins a user through wechat app.
"""
code = request.json.get('code', None)
wechat_code2session_url = 'https://api.weixin.qq.com/sns/jscode2session'
payload = {
'appid': current_app.config['WECHAT_APPID'],
'secret': current_app.... | 985eddbcb39ade8aebad3d9d179a0b174df50280 | 31,688 |
def is_no_entitled(request):
"""Check condition for needing to entitled user."""
no_entitled_list = ["source-status"]
no_auth = any(no_auth_path in request.path for no_auth_path in no_entitled_list)
return no_auth | feee0962568b20c685fd85096ce00dbb91b91fe5 | 31,689 |
def _make_selector_from_key_distribution_options(
options) -> reverb_types.SelectorType:
"""Returns a Selector from its KeyDistributionOptions description."""
one_of = options.WhichOneof('distribution')
if one_of == 'fifo':
return item_selectors.Fifo()
if one_of == 'uniform':
return item_selectors.U... | 3b932328f7b3e226e3dada54c8f1ca08e32167af | 31,690 |
import base64
def json_numpy_obj_hook(dct):
"""
Decodes a previously encoded numpy ndarray
with proper shape and dtype
from: http://stackoverflow.com/a/27948073/5768001
:param dct: (dict) json encoded ndarray
:return: (ndarray) if input was an encoded ndarray
"""
if isinstance(dct, dic... | 50aab4855d63206534981bce95ec0219dec9724e | 31,691 |
from typing import Optional
import copy
def redirect_edge(state: SDFGState,
edge: graph.MultiConnectorEdge[Memlet],
new_src: Optional[nodes.Node] = None,
new_dst: Optional[nodes.Node] = None,
new_src_conn: Optional[str] = None,
... | 368ff8dace5b781d05f7e75fe9d57cae648aee9d | 31,692 |
def svn_fs_lock(*args):
"""
svn_fs_lock(svn_fs_t fs, char path, char token, char comment, svn_boolean_t is_dav_comment,
apr_time_t expiration_date,
svn_revnum_t current_rev, svn_boolean_t steal_lock,
apr_pool_t pool) -> svn_error_t
"""
return _fs.svn_fs_lock(*args) | f711b280a24f5d3c595a81013d1dc5275a997a60 | 31,693 |
def maybe_double_last(hand):
"""
:param hand: list - cards in hand.
:return: list - hand with Jacks (if present) value doubled.
"""
if hand[-1] == 11:
hand[-1] = 22
return hand | 378546e8dd650a67a5d9d9eed490969fd085bfb1 | 31,694 |
def length(draw, min_value=0, max_value=None):
"""Generates the length for Blast+6 file format.
Arguments:
- `min_value`: Minimum value of length to generate.
- `max_value`: Maximum value of length to generate.
"""
return draw(integers(min_value=min_value, max_value=max_value)) | e3ac6b5d9bcc6380e475785047438b3be8a81288 | 31,695 |
def ppw(text):
"""PPW -- Percentage of Polysyllabic Words."""
ppw = None
polysyllabic_words_num = 0
words_num, words = word_counter(text, 'en')
for word in words:
if syllable_counter(word) >= 3:
polysyllabic_words_num += 1
if words_num != 0:
ppw = polysyllabic_words... | b8c8c92a4947404a7166e63458e7d4eb2f9a00fc | 31,696 |
def is_running_in_azure_ml(aml_run: Run = RUN_CONTEXT) -> bool:
"""
Returns True if the given run is inside of an AzureML machine, or False if it is on a machine outside AzureML.
When called without arguments, this functions returns True if the present code is running in AzureML.
Note that in runs with ... | 3d2d6bcf95c34def5fff9c8bf1053c785b075895 | 31,697 |
def format_test_case(test_case):
"""Format test case from `-[TestClass TestMethod]` to `TestClass_TestMethod`.
Args:
test_case: (basestring) Test case id in format `-[TestClass TestMethod]` or
`[TestClass/TestMethod]`
Returns:
(str) Test case id in format TestClass/TestMethod.
"""
tes... | f2d4530fbcc9d07409bfc7a88225653a7f550185 | 31,698 |
def _truncate_seed(seed):
"""
Truncate the seed with MAXINT32.
Args:
seed (int): The seed to be truncated.
Returns:
Integer. The seed with MAXINT32.
"""
return seed % _MAXINT32 | 2caf14236ec1697d6ab7144604e0f2be05d525d2 | 31,699 |
import torch
def get_default_device():
""" Using GPU if available or CPU """
if torch.cuda.is_available():
return torch.device('cuda')
else:
return torch.device('cpu') | ff65f896938b9e53b78d3a6578883129bc886204 | 31,700 |
def build_stateless_broadcaster():
"""Just tff.federated_broadcast with empty state, to use as a default."""
return tff.utils.StatefulBroadcastFn(
initialize_fn=lambda: (),
next_fn=lambda state, value: ( # pylint: disable=g-long-lambda
state, tff.federated_broadcast(value))) | 6d78f3f452551cb2eb7640bb09ee7541c5a752bd | 31,701 |
def getTestSuite(select="unit"):
"""
Get test suite
select is one of the following:
"unit" return suite of unit tests only
"component" return suite of unit and component tests
"all" return suite of unit, component and integration tests
"pending" ... | 1816286c04b8b7a2e994522622a5f567869cad48 | 31,702 |
from typing import Union
from pathlib import Path
def find_mo(search_paths=None) -> Union[Path, None]:
"""
Args:
search_paths: paths where ModelOptimizer may be found. If None only default paths is used.
Returns:
path to the ModelOptimizer or None if it wasn't found.
"""
default_m... | 4657e15649692415dd10f2daa6527cade351d8fc | 31,703 |
def autoaugment(dataset_path, repeat_num=1, batch_size=32, target="Ascend"):
"""
define dataset with autoaugment
"""
if target == "Ascend":
device_num, rank_id = _get_rank_info()
else:
init("nccl")
rank_id = get_rank()
device_num = get_group_size()
if device_num ... | 596eb26fe376298327900a240d07c89f6914f76d | 31,704 |
def dropout_mask(x, sz, dropout):
""" Applies a dropout mask whose size is determined by passed argument 'sz'.
Args:
x (torch.Tensor): A torch Variable object
sz (tuple(int, int, int)): The expected size of the new tensor
dropout (float): The dropout fraction to apply
This method us... | ae6aebad62fa97014227f4ac68bca68f2eafe95f | 31,705 |
def two_body_mc_force_en_jit(bond_array_1, c1, etypes1,
bond_array_2, c2, etypes2,
d1, sig, ls, r_cut, cutoff_func,
nspec, spec_mask, bond_mask):
"""Multicomponent two-body force/energy kernel accelerated with
Numba's njit de... | c027a874b1662d0b9c954302cc3d0b26f77f9a21 | 31,706 |
def customize_hrm_programme(**attr):
"""
Customize hrm_programme controller
"""
# Organisation needs to be an NS/Branch
ns_only(current.s3db.hrm_programme.organisation_id,
required=False,
branches=False,
)
return attr | 3ef74f74e09b9c4498700b9f0d20245829d48c42 | 31,707 |
def freq_count(line, wrddict, win, ctxcounter, wrdcounter):
"""
Counts words and context words of a string.
line: The sentence as a string.
wrddict: Word index mapping.
win: Word context window size.
ctxcounter: Context Counter.
wrdcounter: Word Counter.
"""
if not (isinstance(line, ... | 87ebe01058f8958f5ffe06e0944068c10b26ae44 | 31,708 |
def _onehot_encoding_unk(x, allowable_set):
"""Maps inputs not in the allowable set to the last element."""
if x not in allowable_set:
x = allowable_set[-1]
return list(map(lambda s: x == s, allowable_set)) | 3b386c6640bd5e37a6ab2276e090c8ea56eed5ce | 31,709 |
import re
def getChironSpec(obnm, normalized=True, slit='slit', normmech='flat', returnFlat=False):
"""PURPOSE: To retrieve a CHIRON spectrum given the observation
name (obnm)."""
#extract the date (yymmdd) from the obnm:
date = re.search(r'chi(\d{6})', obnm).group(1)
#extract the core of the ob... | a29090e0838f93feeb8ad758beb1bd563b78178e | 31,710 |
import posixpath
def api_routes(api_classes, base_path='/_ah/api', regex='[^/]+'):
"""Creates webapp2 routes for the given Endpoints v1 services.
Args:
api_classes: A list of protorpc.remote.Service classes to create routes for.
base_path: The base path under which all service paths should exist. If
... | 47cd1da8300f010e1c3ef7ee8bca21d7139a40ad | 31,711 |
def WrapReportText(text):
"""Helper to allow report string wrapping (e.g. wrap and indent).
Actually invokes textwrap.fill() which returns a string instead of a list.
We always double-indent our wrapped blocks.
Args:
text: String text to be wrapped.
Returns:
String of wrapped and indented text.
"... | 4818f0d777c8165fd7a762033379741781bf48af | 31,712 |
import math
def point_in_wave(point_x, frequency, amplitude, offset_x, offset_y):
"""Returns the specified point x in the wave of specified parameters."""
return (math.sin((math.pi * point_x)/frequency + offset_x) * amplitude) + offset_y | 5a91c9204819492bb3bd42f0d4c9231d39e404d8 | 31,713 |
def tile(A, reps):
"""
Construct an array by repeating A the number of times given by reps.
If `reps` has length ``d``, the result will have dimension of
``max(d, A.ndim)``.
If ``A.ndim < d``, `A` is promoted to be d-dimensional by prepending new
axes. So a shape (3,) array is promoted to (1, ... | 446247517aaaaecff377571a14384a2bbd0c949f | 31,714 |
import requests
def get_super_user_token(endpoint):
"""
Gets the initialized super user token.
This is one time, cant get the token again once initialized.
Args:
endpoint (str): Quay Endpoint url
Returns:
str: Super user token
"""
data = (
f'{{"username": "{consta... | bf5782fe3cc563b70d7fbd925b4f06e9d29fba1a | 31,715 |
import torch
def to_input_variable(sequences, vocab, cuda=False, training=True):
"""
given a list of sequences,
return a tensor of shape (max_sent_len, batch_size)
"""
word_ids = word2id(sequences, vocab)
sents_t, masks = input_transpose(word_ids, vocab['<pad>'])
if type(sents_t[0][0]) !=... | 3dea99cdf94a06ce3f1b1be02a49f0d8396cb140 | 31,716 |
def map_to_docs(solr_response):
"""
Response mapper that only returns the list of result documents.
"""
return solr_response['response']['docs'] | 2661b9075c05a91c241342151d713702973b9c12 | 31,718 |
def get_config_type(service_name):
"""
get the config type based on service_name
"""
if service_name == "HDFS":
type = "hdfs-site"
elif service_name == "HDFS":
type = "core-site"
elif service_name == "MAPREDUCE":
type = "mapred-site"
elif service_name == "HBASE":
type = "hbase-site... | 96793f932334eb8e4a5460767a80ee6a989cee22 | 31,719 |
def regression_model(X, y, alpha=.5):
"""
trains a simple ridge regession model
Args:
X:
y:
alpha:
Returns: model
"""
reg = linear_model.Ridge(alpha=alpha, fit_intercept=True)
# reg = linear_model.Lasso(alpha = alpha,fit_intercept = True)
reg.fit(X, y)
r... | f15741ac95a8738e031d6eb77f9d5bed76f4958d | 31,720 |
def array2d_export(f, u2d, fmt=None, **kwargs):
"""
export helper for Util2d instances
Parameters
----------
f : str
filename or existing export instance type (NetCdf only for now)
u2d : Util2d instance
fmt : str
output format flag. 'vtk' will export to vtk
**kwargs : ke... | 59c7962d24a688eabebe069500f49d01aef80c28 | 31,721 |
def not_daily(request):
"""
Several timedelta-like and DateOffset instances that are _not_
compatible with Daily frequencies.
"""
return request.param | e30563d0b6ee62cd995908045ddc356ca58b5796 | 31,722 |
from pandas.core.reshape.concat import concat
import itertools
from typing import List
def get_dummies(
data,
prefix=None,
prefix_sep="_",
dummy_na=False,
columns=None,
sparse=False,
drop_first=False,
dtype=None,
) -> "DataFrame":
"""
Convert categorical variable into dummy/ind... | a3be8d5a3f56d438d1182254749b2967d7bf48fd | 31,723 |
import io
def get_call_xlsx(call, submitted=False, proposals=None):
"""Return the content of an XLSX file for all proposals in a call.
Optionally only the submitted ones.
Optionally for the given list proposals.
"""
if proposals is None:
title = f"Proposals in {call['identifier']}"
... | 2077b0b38262d4dff83ebaccc808da3a4e728992 | 31,724 |
def to_array(t):
"""
Converts a taco tensor to a NumPy array.
This always copies the tensor. To avoid the copy for dense tensors, see the notes section.
Parameters
-----------
t: tensor
A taco tensor to convert to a NumPy array.
Notes
-------
Dense tensors export python's ... | 29df47e3535c610954e8f1bae828af80ad6ae9f7 | 31,726 |
def perform_operation(operator_sign: str, num1: float, num2: float) -> float:
"""
Perform the operation on the two numbers.
Parameters
----------
operator_sign : str
Plus, minus, multiplication or division.
num1 : float
Number 1.
num2 : float
Number 2.
Returns
... | e515a103a47b32e2a7197e10a1ad7a395433e7d9 | 31,727 |
def whitespace_tokenize(subtokens):
"""An implementation of BERT's whitespace tokenizer that preserves space."""
return split_subtokens_on(
subtokens, lambda char: char.isspace(), are_good=True) | 09e451a80b8df66ce0a4401bf3ff681dc9c1b1da | 31,728 |
def moon_phase(
ephemerides: skyfield.jpllib.SpiceKernel, time: skyfield.timelib.Timescale
) -> float:
"""Calculate the phase angle of the Moon.
This will be 0 degrees at new moon, 90 degrees at first quarter, 180
degrees at full moon, etc.
"""
sun = ephemerides[Planets.SUN.value]
earth = ... | 8a24d3166816ba42f150866f89fbbfa98f418ed1 | 31,729 |
def fib_functools(n):
"""Return nth fibonacci number starting at fib(1) == 0 using functools
decorator."""
# incorrect fib, but the tests expect it
if n == 0: return 1
if n in [1, 2]:
return n-1
return fib(n - 1) + fib(n - 2) | 335908076cff922e9a27dbb2a50e88901fd7e637 | 31,730 |
def sync_filter(func, *iterables):
"""
Filter multiple iterable at once, selecting values at index i
such that func(iterables[0][i], iterables[1][i], ...) is True
"""
return tuple(zip(*tuple(i for i in zip(*iterables) if func(*i)))) or ((),) * len(
iterables
) | 7a2ab5e6356dadff0fe78d3f2bb0da584e0ff41b | 31,731 |
def visit_hostname(hostname):
"""
Have a chance to visit a hostname before actually using it.
:param hostname: The original hostname.
:returns: The hostname with the necessary changes.
"""
for processor in [hostname_ssl_migration, hostname_tld_migration, ]:
hostname = processor(hostname... | dd8d57a88bd5951d9748c362112954e4549cdd6c | 31,732 |
async def wait_for_other(client):
"""Await other tasks except the current one."""
base_tasks = aio.all_tasks()
async def wait_for_other():
ignore = list(base_tasks) + [aio.current_task()]
while len(tasks := [t for t in aio.all_tasks() if t not in ignore]):
await aio.gather(*task... | ab276973862fd89ba935d70fb2fb72dbd6fe7cfa | 31,733 |
def register_series(series, ref, pipeline):
"""Register a series to a reference image.
Parameters
----------
series : Nifti1Image object
The data is 4D with the last dimension separating different 3D volumes
ref : Nifti1Image or integer or iterable
Returns
-------
transformed_li... | 3afefd4cf1f33cba1d04bd49437e33cfcfbdb578 | 31,735 |
import random
def normal27(startt,endt,money2,first,second,third,forth,fifth,sixth,seventh,zz1,zz2,bb1,bb2,bb3,aa1,aa2):
"""
for source and destination id generation
"""
"""
for type of banking work,label of fraud and type of fraud
"""
idvariz=random.choice(zz2)
... | 469c0a88a77b083d666e938d4d13199987918e1d | 31,736 |
def linear_diophantine(a, b, c):
"""Solve ax + by = c, where x, y are integers
1. solution exists iff c % gcd(a,b) = 0
2. all solutions have form (x0 + b'k, y0 - a'k)
Returns
-------
None if no solutions exists
(x0, y0, a', b') otherwise
"""
# d = pa + qb
p, q, d = extended_euc... | 6b5fdebe7508249978ea97f0a40330d2ed2243b8 | 31,737 |
from operator import and_
def count_per_packet_loss(organization_id, asset_type=None, asset_status=None,
data_collector_ids=None,
gateway_ids=None, device_ids=None,
min_signal_strength=None, max_signal_strength=None,
min_packet_loss=None... | bc202c8e0e77921f74281ff58857659279dba8f7 | 31,738 |
import re
def _slug_strip(value, separator=None):
"""
Cleans up a slug by removing slug separator characters that occur at the
beginning or end of a slug.
If an alternate separator is used, it will also replace any instances of
the default '-' separator with the new separator.
"""
if sepa... | ade4274643191ee702fe39ccefccc5d68ed3a8cb | 31,741 |
def get_segments_loudness_max(h5, songidx=0):
"""
Get segments loudness max array. Takes care of the proper indexing if we are in aggregate
file. By default, return the array for the first song in the h5 file.
To get a regular numpy ndarray, cast the result to: numpy.array( )
"""
if h5.root.anal... | a65111b565686a57add325cc4c29d16b37aa89e8 | 31,742 |
def take_along_axis(arr, indices, axis):
"""
Takes values from the input array by matching 1d index and data slices.
This iterates over matching 1d slices oriented along the specified axis in the
index and data arrays, and uses the former to look up values in the latter.
These slices can be differe... | 84492b7ac09b26510dfe3851122587a702753b04 | 31,743 |
def _is_possible_grab(grid_world, agent_id, object_id, grab_range, max_objects):
""" Private MATRX method.
Checks if an :class:`matrx.objects.env_object.EnvObject` can be
grabbed by an agent.
Parameters
----------
grid_world : GridWorld
The :class:`matrx.grid_world.GridWorld` instance ... | a57d120747199b84b3047d822547b5367d2b9905 | 31,744 |
def euclidean_distance_matrix(embeddings):
"""Get euclidean distance matrix based on embeddings
Args:
embeddings (:obj:`numpy.ndarray`): A `ndarray` of shape
`[num_sensors, dim]` that translates each sensor into a vector
embedding.
Returns:
A `ndarray` of shape `[nu... | 5b50248a94eb926078a20fd5efbac83f115c26b0 | 31,745 |
def get_actor_id(name):
"""
Get TMDB id for an actor based on their name.
If more than one result (likely), fetches the
first match. TMDB results are sorted by popularity,
so first match is likely to be the one wanted.
"""
search = tmdb.Search()
search.person(query=name)
# get id o... | ac75cbaac7dec85fd965d8cc421c6bbba8fc5f67 | 31,746 |
import json
def generate_prompt(
test_case_path, prompt_path, solutions_path, tokenizer, starter_path=None
):
"""
Generate a prompt for a given test case.
Original version from https://github.com/hendrycks/apps/blob/main/eval/generate_gpt_codes.py#L51.
"""
_input = "\nQUESTION:\n"
with ope... | ecd3218839b346741e5beea8ec7113ea2892571e | 31,747 |
def projects_upload_to(instance, filename):
"""construct path to uploaded project archives"""
today = timezone.now().strftime("%Y/%m")
return "projects/{date}/{slug}/{filename}".format(
date=today, slug=instance.project.slug, filename=filename) | 01f97cf5994cca7265ede0a4b5c73672f61e2f90 | 31,748 |
def assign_employee(id):
"""
Assign a department and a role to an employee
"""
check_admin()
employee = Employee.query.get_or_404(id)
form = EmployeeAssignForm(obj=employee)
employee.department = form.department.data
employee.role = form.role.data
db.session.add(employee)
... | f88a1b49cadf73d8a62c0be23742fd03cace36cd | 31,749 |
import copy
def autofocus(field, nm, res, ival, roi=None,
metric="average gradient", minimizer="lmfit",
minimizer_kwargs=None, padding=True, num_cpus=1):
"""Numerical autofocusing of a field using the Helmholtz equation.
Parameters
----------
field: 1d or 2d ndarray
... | a954f96cf8c3c16dbdfb9ea31c22e61cac2a9245 | 31,750 |
def ZeroPaddedRoundsError(handler=None):
"""error raised if hash was recognized but contained zero-padded rounds field"""
return MalformedHashError(handler, "zero-padded rounds") | b0ff8bb894505041382aaf2d79f027708c7a2134 | 31,751 |
def get_adj_mat(G):
"""Represent ppi network as adjacency matrix
Parameters
----------
G : networkx graph
ppi network, see get_ppi()
Returns
-------
adj : square sparse scipy matrix
(i,j) has a 1 if there is an interaction reported by irefindex
ids : list
same length as adj, ith index con... | 95ee8df6be45f12df8da93c7fed10a3c8a32a058 | 31,752 |
def load_ndarray_list(fname):
"""Load a list of arrays saved by `save_ndarray_list`.
Parameters
----------
fname : string
filename to load.
Returns
-------
la : list of np.ndarrays
The list of loaded numpy arrays. This should be identical tp
what was saved by `save_nd... | fc76373d45c8934bd81d6ac7e144dff97ae6d1c9 | 31,753 |
def save_result(data, format, options=UNSET) -> ProcessBuilder:
"""
Save processed data to storage
:param data: The data to save.
:param format: The file format to save to. It must be one of the values that the server reports as
supported output file formats, which usually correspond to the sho... | be9e8f36869cbe2fdf7b938dfd59cf7b8743ff2a | 31,754 |
def load_suites_from_classes(classes):
# type: (Sequence[Any]) -> List[Suite]
"""
Load a list of suites from a list of classes.
"""
return list(
filter(
lambda suite: not suite.hidden, map(load_suite_from_class, classes)
)
) | 6c4b45c7ab99a3e3f7742f247ea65552c7c70927 | 31,755 |
import torch
def update(quantized_model, distilD):
"""
Update activation range according to distilled data
quantized_model: a quantized model whose activation range to be updated
distilD: distilled data
"""
print('******updateing BN stats...', end='')
with torch.no_grad():
for bat... | 70e4cd9032e12f1f461c1cd13ac81ead06091728 | 31,756 |
def _get_color(value):
"""To make positive DFCs plot green, negative DFCs plot red."""
green, red = sns.color_palette()[2:4]
if value >= 0:
return green
return red | 888edb2307bd6f4da65c6c1d5c0a40cb146dfa8c | 31,758 |
def parse_feed(feed: str) -> list:
"""
Parses a TV Show *feed*, returning the episode files included in that feed.
:param feed: the feed to parse
:return: list of episode files included in *feed*
"""
try:
root = ElementTree.fromstring(feed)
except ElementTree.ParseError as error:
... | 6fec9c1d71d3ae31480103dd2e6a2f5d81e12287 | 31,759 |
def copy_emb_weights(embedding, idx2word, embedding_weights, emb_index_dict, vocab_size):
"""Copy from embs weights of words that appear in our short vocabulary (idx2word)."""
c = 0
for i in range(vocab_size):
w = idx2word[i]
g = emb_index_dict.get(w, emb_index_dict.get(w.lower()))
i... | e5d361efd342cc7e194ee325fdf4a98831121576 | 31,762 |
def cost_aggregation(c_v, max_d):
"""
the formula
Lr(p,d) = C(p,d)
+ min[Lr(p-r, d),Lr(p-r, d-1)+p1,Lr(p-r,d+1)+p1,miniLr(p-r, i)+p2]
- minkLr(p-r,k)
:param c_v:
:param max_d:
:return: sum of all the Lr
"""
(H, W, D) = c_v.shape
p1 = 10
p2 = 120
Lr1 = ... | 71ff7bbbea8c3faebc8269d707198240c258c9c3 | 31,763 |
def send_approved_resource_email(user, request, reason):
"""
Notify the user the that their request has been approved.
"""
email_template = get_email_template()
template = "core/email/resource_request_approved.html"
subject = "Your Resource Request has been approved"
context = {
"sup... | 52571470104e802ef9bcc491fa614a9420710df5 | 31,764 |
from sphinx.util.nodes import traverse_parent
import warnings
def is_in_section_title(node: Element) -> bool:
"""Determine whether the node is in a section title"""
warnings.warn('is_in_section_title() is deprecated.',
RemovedInSphinx30Warning, stacklevel=2)
for ancestor in traverse_pa... | fb1e981e9ec8ad26cb49a144eb696d035dcbc2e8 | 31,765 |
def common_mgr():
"""
Create a base topology.
This uses the ExtendedNMLManager for it's helpers.
"""
# Create base topology
mgr = ExtendedNMLManager(name='Graphviz Namespace')
sw1 = mgr.create_node(identifier='sw1', name='My Switch 1')
sw2 = mgr.create_node(identifier='sw2', name='My S... | e181b231bc859a6595417bbc63b695a00d7c3ae7 | 31,766 |
def reshape_array_h5pyfile(array,number_of_gatesequences,datapoints_per_seq):
"""reshaping function"""
new_array = np.reshape(array,(number_of_gatesequences,datapoints_per_seq),order='F') #order is important, for data as column,
#use order F, this will give an number_of_gatesequences x datapoints_per_seq ma... | c05edd9963396362f3f36f4293e28eb05fe22359 | 31,767 |
def build_value_counts_query(table: str,
categorical_column: str,
limit: int):
"""
Examples:
SELECT
{column_name},
COUNT (*) as frequency
FROM
`{table}`
WHERE
{not_null_str... | 605e25310e3c91c693d72e7e4eae3c513cea2a8b | 31,768 |
from pathlib import Path
def get_model_benchmarks_data(benchmark_runlogs_filepath: Path):
"""
Return Python dict with summary of model performance for one choice of
training set size.
"""
benchmark_genlog = read_json(benchmark_runlogs_filepath)
benchmark_runlog = read_json(benchmark_runlogs_fi... | 494e94a371a682e84f211204b189f3d17727f1c0 | 31,769 |
import collections
def make_labels(module_path, *names, **names_labels):
"""Make a namespace of labels."""
return collections.Namespace(
*((name, Label(module_path, name)) for name in names),
*((n, l if isinstance(l, Label) else Label(module_path, l))
for n, l in names_labels.items()... | aaf0d204442bb9b712c2cf17babe45fd46905c8d | 31,770 |
import socket
def check_port_occupied(port, address="127.0.0.1"):
"""Check if a port is occupied by attempting to bind the socket and returning any resulting error.
:return: socket.error if the port is in use, otherwise False
"""
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
... | 4bf302f89793df47a28cb2bd608abd4344f40ff2 | 31,771 |
def test_heterogeneous_multiagent_env(
common_config,
pf_config,
multicomponent_building_config,
pv_array_config,
ev_charging_config
):
"""Test multiagent env with three heterogeneous agents."""
building_agent ={
"name": "building",
"bus": "675c",
"cls": MultiCompone... | 75939f0e548001ab34f411d15ae822cc7b1c1790 | 31,772 |
import requests
from bs4 import BeautifulSoup
def find_sublinks(artist_link):
"""Some artists have that many songs so we have multiple pages for them. This functions finds all subpages for given artist
e.g if we have page freemidi/queen_1 script go on that page and seek for all specific hyperlinks.
... | 3b24623d1cdbf4bf83f92a6e741576ff74e3facb | 31,773 |
from unittest.mock import patch
def class_mock(request, q_class_name, autospec=True, **kwargs):
"""Return mock patching class with qualified name *q_class_name*.
The mock is autospec'ed based on the patched class unless the optional
argument *autospec* is set to False. Any other keyword arguments are
... | 08bd1aacf75784668845ace13af6514461850d1a | 31,774 |
import inspect
def kwargs_only(fn):
"""Wraps function so that callers must call it using keyword-arguments only.
Args:
fn: fn to wrap.
Returns:
Wrapped function that may only be called using keyword-arguments.
"""
if hasattr(inspect, 'getfullargspec'):
# For Python 3
args = inspect.getful... | cc5bb7d4d31d1bb392c306410c3c22267e93e891 | 31,775 |
def _labeling_complete(labeling, G):
"""Determines whether or not LPA is done.
Label propagation is complete when all nodes have a label that is
in the set of highest frequency labels amongst its neighbors.
Nodes with no neighbors are considered complete.
"""
return all(labeling[v] in... | 130454cbb4a3bc77dfb94f97f20ad11e3239fb82 | 31,776 |
import _random
def get_random_id_str(alphabet=None):
""" Get random integer and encode it to URL-safe string. """
if not alphabet:
alphabet = BASE62
n = _random(RANDOM_ID_SOURCE_BYTES)
return int2str(n, len(alphabet), alphabet) | 51d27c2838ccdd506e23aa2e707ac304e80c249c | 31,777 |
def multivariate_normal_pdf(x, mean, cov):
"""Unnormalized multivariate normal probability density function."""
# Convert to ndarray
x = np.asanyarray(x)
mean = np.asanyarray(mean)
cov = np.asarray(cov)
# Deviation from mean
dev = x - mean
if isinstance(dev, np.ma.MaskedArray):
... | ce3c9171ee7cf78660118ecdab1949efce402827 | 31,778 |
def remove_below(G, attribute, value):
""" Remove attribute below certain value
Parameters
----------
G : nx.graph
Graph
attribute : str
Attribute
value : float
Value
Returns
-------
G : nx.graph
Graph
"""
# Assertions
... | 8d60ce75d8334d5de52b877a9fcd6a9c826c7418 | 31,779 |
def format_header(header_values):
"""
Formats a row of data with bolded values.
:param header_values: a list of values to be used as headers
:return: a string corresponding to a row in enjin table format
"""
header = '[tr][td][b]{0}[/b][/td][/tr]'
header_sep = '[/b][/td][td][b]'
return ... | 5b7cd734a486959660551a6d915fbbf52ae7ef1e | 31,780 |
import random
def getRandomWalk(initial_position: int, current_path: np.ndarray, adjacency_matrix: np.ndarray,
heuristic: np.ndarray, pheromone: np.ndarray, alpha: float, max_lim: int,
Q: float or None, R: float or None) -> np.ndarray:
"""
Function that given an array indic... | a19a33cea8aadd58d99f87bb3ef111ce33df1ce7 | 31,782 |
def sample_circle(plane="xy", N=100):
"""Define all angles in a certain plane."""
phi = np.linspace(0, 2 * np.pi, N)
if plane == "xy":
return np.array([np.cos(phi), np.sin(phi), np.ones_like(phi)])
elif plane == "xz":
return np.array([np.cos(phi), np.ones_like(phi), np.sin(phi)])
eli... | 1546c3e74b5ef1f7d43fa3352a708b5f7acf03ae | 31,783 |
from pathlib import Path
from datetime import datetime
def generate_today_word_cloud(path='images/'):
"""
generate today word cloud
Args:
path (str, optional): [description]. Defaults to 'images/'.
"""
terms_counts = get_term_count()
if terms_counts:
word_cloud = generate_word... | f606135b181235eba5df4367d8721ff73e98af48 | 31,784 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.