content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from typing import Union
from typing import Literal
def primitive_vertices_sphere(
radius: Floating = 0.5,
segments: Integer = 8,
intermediate: Boolean = False,
origin: ArrayLike = np.array([0, 0, 0]),
axis: Union[Literal["+z", "+x", "+y", "yz", "xz", "xy"], str] = "+z",
) -> NDArray:
"""
... | 4519d0629273eeb4391fb0fa49ba552c139acb98 | 3,631,383 |
def VtuDiff(vtu1, vtu2, filename = None):
"""
Generate a vtu with fields generated by taking the difference between the field
values in the two supplied vtus. Fields that are not common between the two vtus
are neglected. If probe is True, the fields of vtu2 are projected onto the cell
points of vtu1. Otherwi... | 5b3ce93ae70b32e112f66332bfeb101d3804b772 | 3,631,384 |
def senv(key, default=NoDefault, required=False, settings=None, _altered_defaults=None, _defaults=None):
"""
return the value for key by checking the following sources:
- the environment
- the settings dictionary
if the key is in _defaults but not in _altered_defaults, don't consider the val... | 7d73117e6b9a47bcf0266e82d86b98a3662c37cf | 3,631,385 |
def average_balance_observer(validator_type):
""" A function factory that returns an observer function"""
def obs_func(state):
validators = state["network"].validators
validator = validators[0]
head = br.specs.get_head(validator.store)
current_state = validator.store.block_states... | f771f306d7cc3653e73fbb915ed7938ec35bcbeb | 3,631,386 |
def get_channel_members_names(channel):
"""Returns a list of all members of a channel. If the member has a nickname, the nickname is used instead of their name, otherwise their name is used"""
names = []
for member in channel.members:
if member.nick is None:
names.append(member.name)
... | 955ea4013841fe8aac52f0474a65e221795db571 | 3,631,387 |
def getRaCfg(name, default):
""" Gets a config attribute, if not set, return the default. """
if 'raCfg' in config:
if name in config['raCfg'] and isinstance(config['raCfg'][name], bool):
return config['raCfg'][name]
return default | 9ea0498568f86948ac2a111622cbae7a2535c24a | 3,631,389 |
import typing
def quat_mean(quaternions: typing.Sequence[typing.Union[typing.Sequence, np.ndarray]]) -> np.ndarray:
"""
Find the mean of a bunch of quaternions
Fails in some pathological cases where the quats are widely distributed.
:param quaternions:
:return:
"""
if len(quaternions) <= ... | cc95cdb2be8db53701e5e97c5200cdcf67ab6be9 | 3,631,390 |
def get_element_dict(propname='mass_number'):
""" Obtain dictionary of elements ordered by a property.
"""
prop_dict = {k:getattr(elements[k], propname) for k in elements.keys()}
elems = list(elements.keys())
props = list(prop_dict.values())
# Sort the element list by the masses
srtse... | 9902bb1f96618a2d8e4d328711cbacdc68c8a2e3 | 3,631,391 |
def get_match_history(start_at_match_id=None, player_name=None, hero_id=None,
skill=0, date_min=None, date_max=None, account_id=None,
league_id=None, matches_requested=None, game_mode=None,
min_players=None, tournament_games_only=None,
... | ad89ec7b54e03cddbbe966cc8b2701e6002e8a7e | 3,631,392 |
from alert.models import AddDropPeriod
def get_add_drop_period(semester):
"""
Returns the AddDropPeriod object corresponding to the given semester. Throws the same
errors and behaves the same way as AddDropPeriod.objects.get(semester=semester) but runs faster.
This function uses caching to speed up ad... | b2e18e73d2d01e064866fb95c5d425e615a5c7da | 3,631,393 |
from solarforecastarbiter.io.fetch import nwp as fetch_nwp
def run_nwp(forecast, model, run_time, issue_time):
"""
Calculate benchmark irradiance and power forecasts for a Forecast or
ProbabilisticForecast.
Forecasts may be run operationally or retrospectively. For
operational forecasts, *run_tim... | bcff6b763b5391e074f262b96848e3caa216bfa1 | 3,631,394 |
def get_path_filename(handle):
""" cleans path, combines it"""
path = config['path'].strip('/').strip()
return path + '/' + handle + config['extension'] | 01b4a60fdf28327849e2ae63633b1f42c4b09dc8 | 3,631,395 |
def get_user_subscription_steps(signature=None):
"""ユーザー申込みのステップ数
:return:
"""
url_pattern = 'format:user_subscription_step%s'
url_kwargs = {'signature': signature}
step_list = create_steps(
[
('①', '申込み基本情報'),
('②', '申込者分類選択'),
('③', '申込者情報入力'),
... | ba0a3e2b50de225d94e10abe5bdaadf51e95b636 | 3,631,396 |
def approx(g, nodes):
"""
Computes the approximation of g over the nodes for Simpson's method
"""
factor = g(nodes[2] - nodes[0]) / _real(6)
_sum = g(nodes[0]) + _real(4) * g(nodes[1]) + g(nodes[2])
return factor * _sum | b8d41129c251f436aad2d93c166fde744ba4128d | 3,631,397 |
def get_fmtfldsdict(prtfmt):
"""Return the fieldnames in the formatter text."""
# Example prtfmt: "{NS} {study_cnt:2} {fdr_bh:5.3e} L{level:02} D{depth:02} {GO} {name}\n"
return {v:v for v in get_fmtflds(prtfmt)} | 12fbdf364f907783b13babc9ba7f3d8b618b32e5 | 3,631,399 |
import hashlib
def get_checksum(file_name: str) -> str:
"""Returns checksum of the file"""
sha_hash = hashlib.sha224()
a_file = open(file_name, "rb")
content = a_file.read()
sha_hash.update(content)
digest = sha_hash.hexdigest()
a_file.close()
return digest | 6bb506accc6aa7826976a2d8033116dcff2f4a55 | 3,631,400 |
def sync_grains(name, **kwargs):
"""
Performs the same task as saltutil.sync_grains module
See :mod:`saltutil module for full list of options <salt.modules.saltutil>`
.. code-block:: yaml
sync_everything:
saltutil.sync_grains:
- refresh: True
"""
return _sync_sing... | ae8847df3ce84cf63748ded81c79fb9286e9d356 | 3,631,402 |
import torch
from typing import Union
from typing import Tuple
def masked_topk(
input_: torch.FloatTensor,
mask: torch.BoolTensor,
k: Union[int, torch.LongTensor],
dim: int = -1,
) -> Tuple[torch.LongTensor, torch.LongTensor, torch.FloatTensor]:
"""
Extracts the top-k items along a certain dim... | bdf84849f24deb23e183e825227c98e1c9db03f6 | 3,631,403 |
def bessel_kve(v, z, name=None):
"""Computes exponentially scaled modified Bessel function of the 2nd kind.
This function computes `Kve` which is an exponentially scaled version
of the modified Bessel function of the first kind.
`Kve(v, z) = Kv(v, z) * exp(abs(z))`
Warning: Gradients with respect to the fi... | 1c580585811391b007d2c37b6d08e85d9098b3f0 | 3,631,404 |
def cvReleaseConDensation(*args):
"""cvReleaseConDensation(PyObject obj)"""
return _cv.cvReleaseConDensation(*args) | ba8ebc2bc39d6d4792831c7f4025ace8a24d72d6 | 3,631,405 |
def solution(num_buns, num_required):
"""
Each choice of num_required-1 of the num_buns determines a missing key.
Therefore, we use binom[num_buns,num_required-1] different keys.
Each key is used in each num_buns-num_required+1 bunny.
Therefore, each key is repeated num_buns-num_required+1 times.
... | 4ff53d7c9e2b8bbfe348440bb702f965879bd6b6 | 3,631,406 |
import urllib
from datetime import datetime
import ssl
import socket
import json
def check_SSL_certificate(url, verbose):
""" Check SSL certificate expiration date of a server hostname """
hostname = urllib.parse.urlparse(url).hostname
port = urllib.parse.urlparse(url).port
if verbose == 1:
... | d8d1c3218a111d2f850c6bfa50b46a20dddb84b8 | 3,631,407 |
from datetime import datetime
def isToday(date_str):
"""
Check whether the last_checkt_time is today.
:param date:
:return:
"""
today = datetime.datetime.today()
date = datetime.datetime.strptime(date_str, '%Y-%m-%d %H:%M')
return today.year == date.year and today.month == date.month a... | 2e80d602a1370583b0ee2e7c404f6838ac9e2db3 | 3,631,408 |
from mpl_toolkits.mplot3d.axis3d import Axis
def mpl_3d_remove_margins():
"""
Remove thin margins in matplotlib 3d plots.
The Solution is from `Stackoverflow`_.
.. _Stackoverflow:
http://stackoverflow.com/questions/16488182/
"""
if not hasattr(Axis, "_get_coord_info_old"):
d... | 10c208ecc11859ab34c66648adcefa23e98ff9d9 | 3,631,409 |
def get_chinese_relation_name(request, user1, user2):
"""
Gets what user1 called user2 in Chinese
Response:
{'status': Http status,
'title': string
}
"""
try:
title = get_chinese_relation(user1, user2)
return Response({
'title': title
})
... | 162a243792db781b03e07b290b84fb4a8c05e907 | 3,631,411 |
def compress_vertex_list(individual_vertex: list) -> list:
"""
Given a list of vertices that should not be fillet'd,
search for a range and make them one compressed list.
If the vertex is a point and not a line segment, the returned tuple's
start and end are the same index.
Args:
indivi... | a98f8b101219215f719b598ed8c47074a42ecb13 | 3,631,413 |
def update_context_with_user_data(update: Update, context: CallbackContext) -> tuple:
"""Update context.user_data with UserProfile data."""
# Update needed only when context.user_data is empty
if context.user_data:
return update, context
if hasattr(update.callback_query, 'message'):
chat... | 64cf6f6a18ce75b332cee910ab48728f9d154a14 | 3,631,414 |
def multiply_images( images, normalize_result = False, color_mode = MODE ):
"""Multiplica N imagens
Args:
images: lista de imagens
normalize_result: indica truncamento(False) ou normalização(True), default=False
color_mode = 'color color_mode' da imagem resultante, defaul='RGB'
... | 2328b363bbac8377d029269ff48b2eb919eefbe0 | 3,631,415 |
from torch.optim import lr_scheduler
def setup_harn(**kwargs):
"""
CommandLine:
python ~/code/netharn/netharn/examples/ggr_matching.py setup_harn
Args:
dbname (str): Name of IBEIS database to use
nice (str): Custom tag for this run
workdir (PathLike): path to dump all the ... | 2c73ded2db56cdde6d91a1b3391a90890f9e7e2d | 3,631,416 |
def sanitize_comment(comment):
"""Sanitize malicious tags from posted comments.
Takes an HTML comment string, returns that comment with malicious tags removed.
Defaults to bleach's default set of allowed tags:
['a', 'abbr', 'acronym', 'b', 'blockquote', 'code', 'em', 'i', 'li', 'ol', 'strong', 'ul']
... | f92fbb9c967b3e95b41325cd00ea8f2732fe5440 | 3,631,417 |
import requests
def get_api_result(mode, extra_arguments={}):
""" Build JSON request to SABnzbd """
arguments = {'apikey': 'apikey', 'output': 'json', 'mode': mode}
arguments.update(extra_arguments)
r = requests.get('http://%s:%s/api' % (SAB_HOST, SAB_PORT), params=arguments)
return r.json() | 84b388b72611541b2eb486de5155f70ec2aa8833 | 3,631,418 |
async def get_exchange_info(exchange):
""" Fetches and returns relevant information about an exchange for historical data fetch.
Args:
exchange (str): The name of the exchange.
Returns:
str: JSON data with market exchange information.
"""
# Loads the market.
ex = getattr(ccxt_... | ef6a30a1e899e74c01a72cf8cc34ada7f2ca3173 | 3,631,419 |
def create_top_key_words_all(data_res, query, filter, filter_values):
"""Returns keywords graph as dcc.Graph component
Only displays it when all data is retrieved"""
dff_res = pd.DataFrame(data_res['data'])
dff_res['result'] = 'direct'
dff_res = data_preprocess.filter_data_by_time(dff_res, filter... | 804cadf9cf926d30203e8a733df66c5c663584d5 | 3,631,420 |
import re
def proccess_grains(grains_data, model_code, host_name, ip=None):
""" new_data 增加 model_code + "_HOSTNAME"""
all_data = grains_data.get("data")
data = all_data.get(host_name)
selinux = data.get("selinux", None)
dns = data.get("dns", None)
if dns:
dns = dns.get("nameservers")
... | 439c31846cad1d3283967a6320d647a3976bea00 | 3,631,421 |
def V2(params, fs, hs, ops, opsH, vector, shots=2**13, backend=Aer.get_backend('aer_simulator') ):
"""
Calculate the matrix A
"""
N = params.shape[0]
v = np.zeros(N)
for k in range(N):
v[k] = V_k(params, fs, hs, ops, opsH, vector, k, shots, backend )
return v | 46427c53b68c6626fcd2a0bb00031d5d62cb931d | 3,631,422 |
def cachedeterministic(parser, token):
"""
This will cache the contents of a template fragment for a given amount of
time, just like {% cache .. %} except that the key is deterministic and not
mangled or run through MD5.
Usage::
{% cachedeterministic [expire_time] [key] %}
.. s... | 1f7955a09fbc6a14ebe8e98ca4049b0febb35931 | 3,631,423 |
from typing import List
async def generate_acl6(participant: Participant) -> List[str]:
"""Generate a Participant-Specific IPv6 ACL."""
peer_acl = sorted(DEFAULT6.copy())
init_lines = (
f"no ipv6 access-list ipv6-{participant.asn}-in",
f"ipv6 access-list ipv6-{participant.asn}-in",
)
... | 32aaeb586b44b3fd4bcfd3b171e509761958ebd8 | 3,631,424 |
import random
import time
def make_veth_signed_order(
asset_infos, # pylint: disable=redefined-outer-name
pydex_client, # pylint: disable=redefined-outer-name
exchange_address, # pylint: disable=redefined-outer-name
):
"""Convenience function for creating a new instance of a signed order"""
def... | 2e064678df9b1e5756c77debd1ba249f1268c32c | 3,631,425 |
def normalize(vec):
"""Return unit vector for parameter vec.
>>> normalize(np.array([3, 4]))
array([ 0.6, 0.8])
"""
if np.any(vec):
norm = np.linalg.norm(vec)
return vec / norm
else:
return vec | 9987224b84a30aee4e64afee8170cc763cfea955 | 3,631,426 |
def get_x_coordinate(width, year_index):
"""
Given the width of the canvas and the index of the current year
in the YEARS list, returns the x coordinate of the vertical
line associated with that year.
Input:
width (int): The width of the canvas
year_index (int): The index of the cur... | e880be55ed530dd39257c0dae06d9301cadc869d | 3,631,427 |
def get_downloader(start_date,
end_date,
granularity='daily',):
"""returns a downloader closure for oanda
:param start_date: the first day on which dat are downloaded
:param end_date: the last day on which data are downloaded
:param granularity: the frequency of price data,... | 2f6b94df6253b6f9c1e7fd335bd45b1fe7238422 | 3,631,429 |
def stick_together(seg, factor, connectivity=1):
"""
For every segment which are immediate neighbors, determine the number
of neighboring pixels and the volume of the smaller of the two
segments. If n_neighbors / volume**(2/3) > factor, stick the two
segments together. This is based on the heuristic... | a2406bd26132ebe2f278cc2f3463787db1629d38 | 3,631,430 |
def spkacs(targ, et, arg3, arg4, obs):
"""spkacs(SpiceInt targ, SpiceDouble et, ConstSpiceChar * arg3, ConstSpiceChar * arg4, SpiceInt obs)"""
return _cspyce0.spkacs(targ, et, arg3, arg4, obs) | 59d9734f84f4b4a3fcfad413bfa2088a76db3ef2 | 3,631,431 |
from typing import Optional
def replicated_all_reduce_(t: Tensor,
op: CollectiveOperator = CollectiveOperator.Add,
group: Optional[CommGroup] = None) -> Tensor:
"""Reduces tensor `t` across replicas inplace on `t`.
Args:
t (Tensor): Tensor to be r... | e3f5c33ef6dd27ef147690552399e5968d3faf7d | 3,631,432 |
def main():
"""Main function."""
runner = IcePartialRunner()
return runner.start() | 5a7e65f77f5fe6f8976e5a909aa53d0b63ef1c71 | 3,631,433 |
from typing import Dict
from typing import Any
import requests
def get_kip_main_page_body(kip_main_info: Dict[str, Any]) -> str:
"""Gets the RAW HTML body of the KIP main page"""
kip_body_request: requests.Response = requests.get(
CONTENT_URL + "/" + kip_main_info["id"], params={"expand": "body.view"... | 86c402ff311b230aa385cf727aae3d30bd500eac | 3,631,434 |
def load_model_tf(checkpoint_path):
"""
Restores custom model class which imitates keras' Model behaviour
"""
model = Model()
model.load(checkpoint_path)
return model | 4a26d63f3c13439597e3f86daa2222c4de21fe19 | 3,631,435 |
def _get_project_folder(name: str) -> str:
"""
Returns the full folder path of the named project.
Args:
name (str): The name of the project.
Returns:
(str): The path of the project folder.
"""
reg_data = _get_registry_data()
return reg_data[name]["location"] | 399a45e0895f12d8b51004a83aa82b7789661968 | 3,631,436 |
def dcos_service_url(service):
"""Return the URL of a service running on DC/OS, based on the value of
shakedown.dcos.dcos_url() and the service name.
:param service: the name of a registered DC/OS service, as a string
:return: the full DC/OS service URL, as a string
"""
return _gen_url("/service... | 916d5ed5f78efc69f46e22c433dbf2376de8b68e | 3,631,437 |
def get_configuration(resource_type, resource_id, configuration_capture_time):
"""Get configurationItem using getResourceConfigHistory API
in case of OversizedConfigurationItemChangeNotification
"""
result = AWS_CONFIG_CLIENT.get_resource_config_history(
resourceType=resource_type,
resou... | 6cf92171d12b3059e1ee6630dea58e1ad477b6cd | 3,631,438 |
def scenario_development_one_hot_encoded(sources, scenarios, territory="Europe"):
"""
Creates a dataframe with the operation of a production facility encoded to its activity in the given
years
:param sources: List or string of carbon sources
:param scenarios: List of Desired scenarios
:param ter... | f6eeb093a5b67a413bdd2b762c8f283d35bfe826 | 3,631,439 |
def urlparse(d, keys=None):
"""Return a copy of the given dictionary with url values parsed."""
d = d.copy()
if keys is None:
keys = d.keys()
for key in keys:
d[key] = _urlparse(d[key])
return d | 260079c2e223de8c5211faa5cdab530c30fac07d | 3,631,440 |
def URFeaturizer(input_shape, hparams, **kwargs):
"""Auto-select an appropriate featurizer for the given input shape."""
if input_shape[1:3] == (224, 224):
return URResNet(input_shape, hparams, **kwargs)
else:
raise NotImplementedError(f"Input shape {input_shape} is not supported") | 412422db5611c5efdc142196df080baa2f65bb9a | 3,631,441 |
def week_of_year(datetime_col):
"""Returns the week from a datetime column."""
return datetime_col.dt.week | c1bf4e0cd5d4aeddf2cff9a1142fcb45b17d1425 | 3,631,442 |
def _NamespaceKeyToString(key):
"""Extract namespace name from __namespace__ key.
Raises an ApplicationError if the key is not of the form '__namespace__'/name
or '__namespace__'/_EMPTY_NAMESPACE_ID.
Args:
key: a key for a __namespace__ instance.
Returns:
namespace specified by key.
"""
key_path... | febb6e084916e645b0eb7c39b0bc01b7463ecb7d | 3,631,443 |
import crypt
def novo_usuario(usuario,senha,root):
"""Cria e insere um usuário no banco"""
if("True" in root):
estado=1
else:
estado=""
dados={"login":usuario,"senha":crypt.crypt(senha),"root":bool(estado)}
try:
colecao.insert_one(dados)
#sucesso ao criar um usuário... | a93f732b7a529cc0ddf03deb178e2fe34eaf183a | 3,631,444 |
def fill_dict(_dict, **kwargs):
"""A helper to fill the dict passed with the items passed as keyword
arguments if they are not yet in the dict. If the dict passed was
`None` a new dict is created and returned.
This can be used to prepopulate initial dicts in overriden constructors:
class MyFo... | 7e9cd1bb7b15633696d82ded89f39868bb77524c | 3,631,445 |
def list_live_assessment_results(request_ctx, course_id, assessment_id, user_id=None, **request_kwargs):
"""
Returns a list of live assessment results
:param request_ctx: The request context
:type request_ctx: :class:RequestContext
:param course_id: (required) ID
:type course_id... | 871a592f97828c68cb844ab09c844ebca351ecb3 | 3,631,446 |
def extract_format_data(matrix):
"""Extract format information from the upper-left corner.
Parameters:
matrix (ndarray): 2D array containing the QR matrix.
Returns:
Tuple (error_correction_level, mask_pattern).
Raises:
QRDecodeError: If the format information can not be decode... | 44fb1c4e1c305bee84dbec218fa675cb32b85bc9 | 3,631,447 |
def decrypt_and_print_message(args):
"""Try to decrypt and print a message."""
for key in args.keys:
for nounce in range(args.nounce_lower, args.nounce_upper):
if _decrypt_chacha20poly1305(args.message, nounce, key):
return 0
return 1 | 919a391862d727dac3596f07ad5df33e6fc08199 | 3,631,448 |
def readCylWFSRaw(fn):
"""
Load in data from WFS measurement of cylindrical mirror.
Assumes that data was processed using processHAS, and loaded into
a .fits file.
Scale to microns, remove misalignments,
strip NaNs.
If rotate is set to an array of angles, the rotation angle
which minimiz... | 3302806ba302c87c55160569d5bebcd4a0fcc6d3 | 3,631,449 |
def normalize(df, df_ref=None):
"""
Normalize all numerical values in dataframe
:param df: dataframe
:param df_ref: reference dataframe
"""
if df_ref is None:
df_ref = df
df_norm = (df - df_ref.mean()) / df_ref.std()
return df_norm | 56c96f43c98593a5cf21425f23cfd92a7f6d6fe3 | 3,631,450 |
def get_shapes(ndim):
"""
produce a bunch of tensor shapes of order `ndim`.
Args:
ndim: The tensor order.
Returns:
list[tuple[int]]: A list of shapes.
"""
if ndim == 3:
shapes = unique_permutations((8, 64, 128))
some_combs = sum((list(zip(shapes, unique_permutations(pshape)))
... | 05afb6198a9c2291c4645e4de47728800431db34 | 3,631,451 |
def gen_stimuli(M, N):
"""
This function generates the stimuli (taken from actual data)
"""
a = (np.random.randn(1, M) * 100).astype(np.float32)
B = (np.random.randn(M, N) * 100).astype(np.float32)
y = custom_vecmatmul(a, B)
return a, B, y | b9fec03e16fb45469e7e708d5a3ca8f5e8fe7ca5 | 3,631,452 |
def agentXML(request, identifier):
"""
Return a representation of a given agent
"""
if 'premis' in request.path:
identifier = identifier.replace('.premis', '')
try:
agentObject = Agent.objects.get(agent_identifier=identifier)
except Agent.DoesNotExist:
re... | 4dabb9676f0389b170461a4a617975b09decb131 | 3,631,453 |
from dmlc_tracker import opts
def dmlc_opts(opts):
"""convert from mxnet's opts to dmlc's opts
"""
args = ['--num-workers', str(opts.num_workers),
'--num-servers', str(opts.num_servers),
'--cluster', opts.launcher,
'--host-file', opts.hostfile,
'--sync-dst-d... | 2a83684512fa49d624e2e99169d1e600a45b5cdc | 3,631,454 |
from typing import Optional
from typing import Sequence
def get_virtual_border_routers(filters: Optional[Sequence[pulumi.InputType['GetVirtualBorderRoutersFilterArgs']]] = None,
ids: Optional[Sequence[str]] = None,
name_regex: Optional[str] = None,
... | af55f1ed6b5713451599c8c0da40d35fa48cc61f | 3,631,455 |
def PermutationGroup(gens=None, gap_group=None, domain=None, canonicalize=True, category=None):
"""
Return the permutation group associated to `x` (typically a
list of generators).
INPUT:
- ``gens`` - list of generators (default: ``None``)
- ``gap_group`` - a gap permutation group (default... | fcff1b525590544d108accc51780fde7b61d0428 | 3,631,457 |
def lunar_diameter(tee):
"""Return the geocentric apparent lunar diameter of the moon (in
degrees) at moment, tee. Adapted from 'Astronomical
Algorithms' by Jean Meeus, Willmann_Bell, Inc., 2nd ed."""
return deg(1792367000/9) / lunar_distance(tee) | e13e514c449f89b5fb10c1f927f3460a22a0a888 | 3,631,458 |
def findCongressPerson(name, nicknames_json):
"""
Checks the nicknames endpoint of the NYT Congress API
to determine if the inputted name is that of a member of Congress
"""
congress_json = [x['nickname'] for x in nicknames_json if x['nickname'] == name]
if len(congress_json) > 0:
return... | d03dc1f55c970379b283f78cfd23e393e494bd48 | 3,631,459 |
from typing import Tuple
def make_canonical_transform_np(
n_xyz: np.ndarray,
ca_xyz: np.ndarray,
c_xyz: np.ndarray) -> Tuple[np.ndarray, np.ndarray]:
"""Returns translation and rotation matrices to canonicalize residue atoms.
Note that this method does not take care of symmetries. If you provide ... | 59c0a5ca06f3f0d612cc25ce453e201c4daff184 | 3,631,460 |
def get_data_for_result_table(all_answers):
"""
Generate simple data for result table (question, answer status true/false).
@param all_answers: dict with pairs question_id and list of answers for question.
@return: dict with all data for result table.
"""
result_data = {}
for question_id, a... | c9bdd9920698ed758d27ceb2bcf04e143f705bd4 | 3,631,461 |
def _validate_positive_int(value):
"""Validate value is a natural number."""
try:
value = int(value)
except ValueError as err:
raise ValueError("Could not convert to int") from err
if value > 0:
return value
else:
raise ValueError("Only positive values are valid") | ddc2087d69c96fa72594da62192df58555b25029 | 3,631,462 |
def transpose(table):
"""
Returns a copy of table with rows and columns swapped
Example:
1 2 1 3 5
3 4 => 2 4 6
5 6
Parameter table: the table to transpose
Precondition: table is a rectangular 2d List of numbers
"""
result = []... | fe84714d3e09deb22058fd75ac3333c2206f77c3 | 3,631,463 |
def predict_posterior_marginals(
F, features, mean, kernel, chol_fact, pred_mat, test_features,
test_intermediates=None):
"""
Computes posterior means and variances for test_features.
If pred_mat is a matrix, so will be posterior_means, but not
posterior_variances. Reflects the fact that... | 702ec32d43566e8e17a19f597ed0dd90b28d85d8 | 3,631,464 |
def rule_ContributesLight_possessions_can_light_person(x, world) : # maybe should handle concealment at some point?
"""A person contributes light if any of their posessions contribute light."""
if any(world[ContributesLight(o)] for o in world[Contents(x)]) :
return True
else : raise NotHandled() | d67c50903e1c7b50b6e6ec2c6369b91db50a494c | 3,631,465 |
def xml():
""" Return an XML response with an HTTP 200 OK status """
data: str = """<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url>
<loc>http://www.example.com/</loc>
<lastmod>2005-01-01</lastmod>
<changefreq>monthly</changefreq>
... | 4b4391ff9b22570885e4056ba62f4dbe84724c18 | 3,631,467 |
from typing import Iterable
import pathlib
def read_device_files(directory_paths: Iterable[pathlib.Path]) -> DeviceFileInfo:
"""Read data from files contained on an mbed enabled device's USB mass storage device.
If details.txt exists and it contains a product code, then we will use that code. If not then we ... | e11c2dee5db2fa957bc9794a87414d72b708a85e | 3,631,468 |
def max_rl(din):
"""
A MAX function should "go high" only when all of
its inputs have arrived. Thus, AND gates are
used for its implementation.
Input: a list of 1-bit WireVectors
Output: a 1-bit WireVector
"""
if len(din) == 1:
dout = din[0]
else:
... | b65710967a8a785e1ca0679252ac69c140b4c560 | 3,631,469 |
def compute_success(
classifier: "CLASSIFIER_TYPE",
x_clean: np.ndarray,
labels: np.ndarray,
x_adv: np.ndarray,
targeted: bool = False,
batch_size: int = 1,
) -> float:
"""
Compute the success rate of an attack based on clean samples, adversarial samples and targets or correct labels.
... | 0e8f44038b8d661912393edb6b248ff93356f180 | 3,631,470 |
def set_up_basic_stubs(app_id):
"""Set up a basic set of stubs.
Configures datastore and memcache stubs for testing.
Args:
app_id: Application ID to configure stubs with.
Returns:
Dictionary mapping stub name to stub.
"""
apiproxy_stub_map.apiproxy = apiproxy_stub_map.APIProxyStubMap()
ds_stub ... | 197d1c94cbca97ed0b8f4663280a2feb6518b00e | 3,631,471 |
import requests
def process_request(url, auth):
"""Perform an http request.
:param url: full url to query
:type url: ``str``
:param auth: username, password credentials
:type auth: ``tuple`` || ``None``
:returns: ``dict``
"""
content = requests.get(url, auth=auth)
if content.statu... | 051c60e03458e3c38d93dfd65d15f355ec284c12 | 3,631,473 |
def close_channel(sender_addr, receiver_addr,channel_name):
"""
:param sender_addr: String, the sender address
:param receiver_addr: String, receiver's address
:param channel_name: String, channel name
:return:
"""
sender, receiver = split_channel_name(channel_name)
ch = Channel(sender, ... | ee7bd2311f7ef7c3ad4abb0c7701116208079ef2 | 3,631,474 |
from typing import Collection
from typing import Tuple
from typing import Iterator
from typing import Set
def get_proj_edges(edges: Collection[Tuple[int, int]]) -> Iterator[Tuple[int, int]]:
"""Obtain projective edges from a collection of edges of a dependency tree."""
adj_set: dict = defaultdict(set)
for... | 6c822140e2627046ee8f36769fd14cda14829a5f | 3,631,475 |
from typing import Union
from typing import Any
def convertClrs(clr: Union[dict[Any, Union[str, Color]], Color], conversion: str) -> Union[str, tuple, dict, None]:
"""
Convert color values to HEX and vice-versa
@clr: Color value to convert.
@conversion: Type of conversion to do ('RGB' or 'HEX')
"""
if isinsta... | 70329d19984f970fcaee86ca9403615a2995e9a9 | 3,631,476 |
def fuzzy_op(x, a, y, b, op):
"""Operation of two fuzzy sets.
Operate fuzzy set ``a`` with fuzzy set ``b``,
using +, * or any other binary operator.
Parameters
----------
x : 1d array, length N
Universe variable for fuzzy set ``a``.
a : 1d array, length N
Fuzzy set for ... | c4b10f024fd7c4bfb0ec4faaedef1f57c62527f7 | 3,631,477 |
def check_int(item):
"""
:param item: txtcrtl containing a value
"""
flag = True
try:
mini = int(item.GetValue())
item.SetBackgroundColour(wx.WHITE)
item.Refresh()
except:
flag = False
item.SetBackgroundColour("pink")
item.Refresh()
return flag | c5ded12ef242a4286fe1b0e9af160dfc9698b5af | 3,631,478 |
def load_h5py(path):
"""Loads datasets from a file.
params:
path: A string, which is a path to the dataset
return: A dictionary, which contains the dataset
"""
dataset = {}
with h5py.File(path, 'r') as hf:
if 'train_x' in hf:
dataset['train_x'] = hf['train_x'][:]
... | 9bc12ee86249a20931c0f5a83ad0cc7910f55ced | 3,631,479 |
def from_timedelta(val):
"""escape a python datetime.timedelta"""
sec = int(val.total_seconds())
hour = sec // 3600
sec = sec % 3600
mns = sec // 60
sec = sec % 60
msec = val.microseconds
return _time(hour, mns, sec, msec) | f618a82b9253f27bb8c0574c697ee3e35f7d9d22 | 3,631,480 |
def stringify_column(df: DataFrame, column: str) -> DataFrame:
"""Takes dataframe and column that contains array structures. Stringify that column values."""
array_to_string_udf = udf(array_to_string, StringType())
df = df.withColumn(column, array_to_string_udf(df[column]))
return df | d0496053279c39e4decd349b649ddd899277719a | 3,631,481 |
import platform
def get_os():
"""
Get operating system.
:return: operating system
:rtype: str or unicode
"""
return platform.platform() | 104c8547c751388a2ea4be675be1fa44758d61d0 | 3,631,482 |
def powerLaw(y, x):
"""
'When the frequency of an event varies as power of some attribute of that
event the frequency is said to follow a power law.' (wikipedia)
This is represented by the following equation, where c and alpha are
constants:
y = c . x ^ alpha
Args
--------
y: array w... | 39ad30d5f0c150df06faa41bbcd960352c708b6a | 3,631,483 |
def _separate_talairach_levels(atlas_img, labels, verbose=1):
"""Separate the multiple annotation levels in talairach raw atlas.
The Talairach atlas has five levels of annotation: hemisphere, lobe, gyrus,
tissue, brodmann area. They are mixed up in the original atlas: each label
in the atlas correspond... | 1d05eab354eada01322bfd2fb79bcdeaeaf4ab34 | 3,631,484 |
def merge(a, b):
"""
Hierarchical merge of dictionaries, lists, tuples and sets.
If b is None, it keeps a, otherwise it merges with a.
In case of ambiguities, b overrides a
it returns is a deepcopy, not a reference of the original objects.
"""
if isinstance(b, dict) and isinstance(a, dict):... | 5ae3533ded3018a8e7789d0b50cf150c19c4a6d5 | 3,631,485 |
def block_inception_a(blk, net):
"""Builds Inception-A block for Inception v4 network."""
# By default use stride=1 and SAME padding
s = net.add(Split('%s/Split' % blk, 4))
br0 = conv2d(net, '%s/Branch_0/Conv2d_0a_1x1' % blk, 96, 1, src=s)
conv2d(net, '%s/Branch_1/Conv2d_0a_1x1' % blk, 64, 1, src=s)... | c09d1d0c3c2465f9cd273a611ea16871635a6bea | 3,631,486 |
def mgas(sg, sp, gpotential, potential, xv, dt, kappa=1.0, alpha=1.0):
"""
Evolve satellite gas mass due to tidal stripping, by an amount of
[m - m(l_rp)] * dt / t_dyn
where m is the satellite gas mass; m(l_rp) is the satellite gas mass
within ram pressure radius l_rp; dt is the timestep size;... | 4d8b823a0814bf78f3e30c20bfbab17d0d5b87e5 | 3,631,487 |
import random
def genpass(pwds_amount=1, paswd_length=8):
""" Returns a list of 'pwds_amount' random passwords, having length of 'paswd_length' """
return [ ''.join([chr(random.randint(32, 126)) for _ in range(paswd_length)]) for _ in range(pwds_amount)] | d5d4e38cc334f44e837c72f265a391bf72f5bd5f | 3,631,488 |
def _gini(x):
"""
Memory efficient calculation of Gini coefficient in relative mean difference form
Parameters
----------
x : array-like
Attributes
----------
g : float
Gini coefficient
Notes
-----
Based on http://www.statsdirect.com/help/default.htm#nonparametri... | 581f12e46544df307b8f53f2f4261779b7069d67 | 3,631,490 |
def render_edit_view(request, form_name, nid):
"""according resource primary key,render edit view
Arguments:
request {object} -- wsgi http request object
form_name {str} -- resources type name
nid {int} -- resources id
Returns:
html -- html template
"""
... | d69d0f2f45351077253b750fe0e197951c1fe853 | 3,631,492 |
def decrypt_default_password(message):
"""
You Can Use this for internal data (Aka Non-User controlled data) that needs to be encrypted.
:param message:
:return:
"""
if type(message) == bytes:
f = Fernet(getkey(Settings.ENCRYPTION_PASSWORD))
decrypted = f.decrypt(message)
... | 2d9b087db80a0645bae88564373642a900e5ea28 | 3,631,493 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.