content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def pending_mediated_transfer(app_chain, token_network_identifier, amount, identifier):
""" Nice to read shortcut to make a LockedTransfer where the secret is _not_ revealed.
While the secret is not revealed all apps will be synchronized, meaning
they are all going to receive the LockedTransfer message.
... | 82ae40ffa45a759f1aac132c3edc221ebd11ae9e | 20,600 |
def get_comments(post, sort_mode='hot', max_depth=5, max_breadth=5):
"""
Retrieves comments for a post.
:param post: The unique id of a Post from which Comments will be returned.
:type post: `str` or :ref:`Post`
:param str sort_mode: The order that the Posts will be sorted by. Options are: "top... | 333009358f622560135e7e239741613356387d55 | 20,601 |
def neighbor_json(json):
"""Read neighbor game from json"""
utils.check(
json['type'].split('.', 1)[0] == 'neighbor', 'incorrect type')
return _NeighborDeviationGame(
gamereader.loadj(json['model']),
num_neighbors=json.get('neighbors', json.get('devs', None))) | 19891d59970610ad412fd4eb204477c96d1d82fd | 20,602 |
def get_b16_config():
"""Returns the ViT-B/16 configuration."""
config = ml_collections.ConfigDict()
config.name = 'ViT-B_16'
config.half_precision = True
config.encoder = ml_collections.ConfigDict()
config.encoder.patches = ml_collections.ConfigDict({'size': (16, 16)})
config.encoder.hidden_size = 768
... | 6afdb862bd07c21d569db65fbb1780492ff153f2 | 20,603 |
from typing import Container
def build_container_hierarchy(dct):
"""Create a hierarchy of Containers based on the contents of a nested dict.
There will always be a single top level scoping Container regardless of the
contents of dct.
"""
top = Container()
for key,val in dct.items():
if... | 7fb629d7f570e5f77b381766b5c2d909d7c0d6c1 | 20,604 |
def occ_frac(stop_rec_range, bin_size_minutes, edge_bins=1):
"""
Computes fractional occupancy in inbin and outbin.
Parameters
----------
stop_rec_range: list consisting of [intime, outtime]
bin_size_minutes: bin size in minutes
edge_bins: 1=fractional, 2=whole bin
Returns
-------
... | d3d93cd92386a98c865c61ad2b595786aa5d4837 | 20,605 |
def geomprogr_mesh(N=None, a=0, L=None, Delta0=None, ratio=None):
"""Compute a sequence of values according to a geometric progression.
Different options are possible with the input number of intervals in the
sequence N, the length of the first interval Delta0, the total length L
and the ratio of the so... | 3de67b8ee2d75b69638648316fcfad07dbabde3a | 20,606 |
def list_subclasses(package, base_class):
"""
Dynamically import all modules in a package and scan for all subclasses of a base class.
`package`: the package to import
`base_class`: the base class to scan for subclasses
return: a dictionary of possible subclasses with class name as key and class typ... | e5570c30c89869b702c1c1015914540403be356f | 20,607 |
def maxima_in_range(r, g_r, r_min, r_max):
"""Find the maxima in a range of r, g_r values"""
idx = np.where(np.logical_and(np.greater_equal(r, r_min), np.greater_equal(r_max, r)))
g_r_slice = g_r[idx]
g_r_max = g_r_slice[g_r_slice.argmax()]
idx_max, _ = find_nearest(g_r, g_r_max)
return r[idx_ma... | 14a4e3dc65465dd2e515ac09fb74704a366368b4 | 20,608 |
def shared_fit_preprocessing(fit_class):
"""
Shared preprocessing to get X, y, class_order, and row_weights.
Used by _materialize method for both python and R fitting.
:param fit_class: PythonFit or RFit class
:return:
X: pd.DataFrame of features to use in fit
y: pd.Series of target... | b87831540ba6fc4bc65fe0532e2af0574515c3a3 | 20,609 |
import json
def webhook():
"""
Triggers on each GET and POST request. Handles GET and POST requests using this function.
:return: Return status code acknowledge for the GET and POST request
"""
if request.method == 'POST':
data = request.get_json(force=True)
log(json.dumps(data)) ... | 0c9f39c1159990e6a84dc9ce0091078397a3b65e | 20,610 |
def extract_winner(state: 'TicTacToeState') -> str:
"""
Return the winner of the game, or announce if the game resulted in a
tie.
"""
winner = 'No one'
tictactoe = TicTacToeGame(True)
tictactoe.current_state = state
if tictactoe.is_winner('O'):
winner = 'O'
elif tictactoe.is_... | c92cef3bc3214923107871d5f044df16baf63401 | 20,611 |
def _prensor_value_fetch(prensor_tree: prensor.Prensor):
"""Fetch function for PrensorValue. See the document in session_lib."""
# pylint: disable=protected-access
type_spec = prensor_tree._type_spec
components = type_spec._to_components(prensor_tree)
def _construct_prensor_value(component_values):
return... | ccea4a94fff5f17c6e650e1ac820ec6da1be023d | 20,612 |
import subprocess
def start_workers_with_fabric():
""" testing spinning up workers using fabric """
tmp_file = open(settings.AUTOSCALE_TMP_FILE, 'w')
tmp_file.write('running')
tmp_file.close()
subprocess.call("/usr/local/bin/fab \
-f /opt/codebase/auto-scale/fabfile.py \
... | 8d6044c07ff0b92f0bd56d1793f0d7bae16d86dd | 20,613 |
def request_validation_error(error):
"""Handles Value Errors from bad data"""
message = str(error)
app.logger.error(message)
return {
'status_code': status.HTTP_400_BAD_REQUEST,
'error': 'Bad Request',
'message': message
}, status.HTTP_400_BAD_REQUEST | 1d5c779286d83d756e1d73201f1274dbec7cf84b | 20,614 |
def all(request):
"""Handle places list page."""
places = Place.objects.all()
context = {'places': places}
return render(request, 'rental/list_place.html', context) | d978a4ec22004a1a863e57113639722eaf1f02cf | 20,615 |
def get_key_by_value(dictionary, search_value):
"""
searchs a value in a dicionary and returns the key of the first occurrence
:param dictionary: dictionary to search in
:param search_value: value to search for
"""
for key, value in dictionary.iteritems():
if value == search_value:
... | febad38e70c973de23ce4e1a5702df92860a6c2e | 20,616 |
def _subtract_ten(x):
"""Subtracts 10 from x using control flow ops.
This function is equivalent to "x - 10" but uses a tf.while_loop, in order
to test the use of functions that involve control flow ops.
Args:
x: A tensor of integral type.
Returns:
A tensor representing x - 10.
"""
def stop_con... | f2db402e5c98251dc93036be60f02eb88a4d13d9 | 20,617 |
def load_fortune_file(f: str) -> list:
"""
load fortunes from a file and return it as list
"""
saved = []
try:
with open(f, 'r') as datfile:
text = datfile.read()
for line in text.split('%'):
if len(line.strip()) > 0:
saved.append(l... | 824ddb0bcb34abf597fb317d10fa3eeab99a292e | 20,618 |
def maskStats(wins, last_win, mask, maxLen):
"""
return a three-element list with the first element being the total proportion of the window that is masked,
the second element being a list of masked positions that are relative to the windown start=0 and the window end = window length,
and the third bein... | b5d75d2e86f1b21bf35cbc69d360cd1639c5527b | 20,619 |
def dsoftmax(Z):
"""Given a (m,n) matrix, returns a (m,n,n) jacobian matrix"""
m,n=np.shape(Z)
softZ=(softmax(Z))
prodtensor=np.einsum("ij,ik->ijk",softZ,softZ)
diagtensor=np.einsum('ij,jk->ijk', softZ, np.eye(n, n))
return diagtensor-prodtensor | 15296d493608dac1fc9843dd8a7d6eaaf29c4839 | 20,620 |
async def vbd_unplug(cluster_id: str, vbd_uuid: str):
"""Unplug from VBD"""
try:
session = create_session(
_id=cluster_id, get_xen_clusters=Settings.get_xen_clusters()
)
vbd: VBD = VBD.get_by_uuid(session=session, uuid=vbd_uuid)
if vbd is not None:
ret = ... | 8b36c55354b35470bceb47ef212aa183be09fad4 | 20,621 |
def calculate_age(created, now):
"""
Pprepare a Docker CLI-like output of image age.
After researching `datetime`, `dateutil` and other libraries
I decided to do this manually to get as close as possible to
Docker CLI output.
`created` and `now` are both datetime.datetime objects.
"""
a... | f2b1a6fc643a78c9a2d3cdd0f497e05c3294eb03 | 20,622 |
def Maxout(x, num_unit):
"""
Maxout as in the paper `Maxout Networks <http://arxiv.org/abs/1302.4389>`_.
Args:
x (tf.Tensor): a NHWC or NC tensor. Channel has to be known.
num_unit (int): a int. Must be divisible by C.
Returns:
tf.Tensor: of shape NHW(C/num_unit) named ``output... | d10294d7ad180b47c4276e3bb0f43e7ac4a9fa3b | 20,623 |
import re
def is_youtube_url(url: str) -> bool:
"""Checks if a string is a youtube url
Args:
url (str): youtube url
Returns:
bool: true of false
"""
match = re.match(r"^(https?\:\/\/)?(www\.youtube\.com|youtu\.be)\/.+$", url)
return bool(match) | 97536b8e7267fb5a72c68f242b3f5d6cbd1b9492 | 20,624 |
def time_nanosleep():
""" Delay for a number of seconds and nanoseconds"""
return NotImplementedError() | 9ec91f2ef2656b5a481425dc65dc9f81a07386c2 | 20,625 |
import os
def get_regions(positions, genome_file, base=0, count=7):
"""Return a list of regions surrounding a position.
Will loop through each chromosome and search all positions in that
chromosome in one batch. Lookup is serial per chromosome.
Args:
positions (dict): Dictionary of {chrom->... | 4371e5a8eb51fd8303636147364e0ebc09865312 | 20,626 |
import jinja2
def render_series_fragment(site_config):
"""
Adds "other posts in this series" fragment to series posts.
"""
series_fragment = open("_includes/posts_in_series.html", "r").read()
for post_object in site_config["series_posts"]:
print("Generating 'Other posts in this series' fr... | 6cf947148af2978e926d51e9007684b9580d2cb0 | 20,627 |
import os
def create_barplot_orthologues_by_species(df, path, title, colormap, genes, species):
"""
The function creates a bar plot using seaborn.
:param df: pandas.DataFrame object
:param path: The CSV file path.
:param title: Title for the plot.
:param colormap: Colormap
:param genes: Or... | 0d1f23dba45095a85f87db0c5112c110e2ebcf0c | 20,628 |
def get_class_by_name(name):
"""Gets a class object by its name, e.g. sklearn.linear_model.LogisticRegression"""
if name.startswith('cid.analytics'):
# We changed package names in March 2017. This preserves compatibility with old models.
name = name.replace('cid.analytics', 'analytics.core')
... | bf52eb8472e63cbb453183b57c5275d592665fc9 | 20,629 |
import functools
def _single_optimize(
direction,
criterion,
criterion_kwargs,
params,
algorithm,
constraints,
algo_options,
derivative,
derivative_kwargs,
criterion_and_derivative,
criterion_and_derivative_kwargs,
numdiff_options,
logging,
log_options,
erro... | 9f349f8e1124da3a2747b3880969a90e76aad52a | 20,630 |
def item_len(item):
"""return length of the string format of item"""
return len(str(item)) | 7d68629a5c2ae664d267844fc90006a7f23df1ba | 20,631 |
def get_progress_logger():
"""Returns the swift progress logger"""
return progress_logger | b1c0e8e206e2f051dcb97337dc51d4971fe0aa8b | 20,632 |
import sys
import time
def retry(ExceptionToCheck, tries=4, delay=3, backoff=2, logger=None):
"""Retry calling the decorated function using an exponential backoff.
http://www.saltycrane.com/blog/2009/11/trying-out-retry-decorator-python/
original from: http://wiki.python.org/moin/PythonDecoratorLibrary#R... | 1ff65dbc0999f6ea129a8cf354edad54052b0156 | 20,633 |
def instantiate_me(spec2d_files, spectrograph, **kwargs):
"""
Instantiate the CoAdd2d subclass appropriate for the provided
spectrograph.
The class must be subclassed from Reduce. See :class:`Reduce` for
the description of the valid keyword arguments.
Args:
spectrograph
(:... | f9961231ead7c3ece5757e5b18dc5620a3492a40 | 20,634 |
def quoteattr(s, table=ESCAPE_ATTR_TABLE):
"""Escape and quote an attribute value.
"""
for c, r in table:
if c in s:
s = s.replace(c, r)
return '"%s"' % s | 7af3e8ed6bfc0c23a957881ca41065d24cb288d5 | 20,635 |
def is_numeric(array):
"""Return False if any value in the array or list is not numeric
Note boolean values are taken as numeric"""
for i in array:
try:
float(i)
except ValueError:
return False
else:
return True | 2ab0bb3e6c35e859e54e435671b5525c6392f66c | 20,636 |
def reductions_right(collection, callback=None, accumulator=None):
"""This method is like :func:`reductions` except that it iterates over
elements of a `collection` from right to left.
Args:
collection (list|dict): Collection to iterate over.
callback (mixed): Callback applied per iteration... | eba2de662a6386d609da8cf3011010ae822c0440 | 20,637 |
import math
def pelt_settling_time(margin=1, init=0, final=PELT_SCALE, window=PELT_WINDOW, half_life=PELT_HALF_LIFE, scale=PELT_SCALE):
"""
Compute an approximation of the PELT settling time.
:param margin: How close to the final value we want to get, in PELT units.
:type margin_pct: float
:para... | c8d53d1132bc45278f2c127ed95ce10cfea0498b | 20,638 |
import urllib
import sys
def get_file_content(url, comes_from=None):
"""Gets the content of a file; it may be a filename, file: URL, or
http: URL. Returns (location, content). Content is unicode."""
match = _scheme_re.search(url)
if match:
scheme = match.group(1).lower()
if (scheme =... | 7f87b75459219da800f5a665c69b4842735e42d9 | 20,639 |
def InstancesOverlap(instanceList,instance):
"""Returns True if instance contains a vertex that is contained in an instance of the given instanceList."""
for instance2 in instanceList:
if InstanceOverlap(instance,instance2):
return True
return False | 634312b7e8d2ce4e36826410fcd1f6c3c06a40ce | 20,640 |
def calc_qm_lea(p_zone_ref, temp_zone, temp_ext, u_wind_site, dict_props_nat_vent):
"""
Calculation of leakage infiltration and exfiltration air mass flow as a function of zone indoor reference pressure
:param p_zone_ref: zone reference pressure (Pa)
:param temp_zone: air temperature in ventilation zon... | 4d3f4789b3faedf68b9de3b3e6c8f17bcb478a51 | 20,641 |
async def ban(bon):
""" For .ban command, bans the replied/tagged person """
# Here laying the sanity check
chat = await bon.get_chat()
admin = chat.admin_rights
creator = chat.creator
# Well
if not (admin or creator):
return await bon.edit(NO_ADMIN)
user, reason = await get_us... | f79f16c5e2722f576511a528f546a7f87f7e5236 | 20,642 |
def read_offset(rt_info):
"""
获取所有分区的offset
:param rt_info: rt的详细信息
:return: offset_msgs 和 offset_info
"""
rt_id = rt_info[RESULT_TABLE_ID]
task_config = get_task_base_conf_by_name(f"{HDFS}-table_{rt_id}")
if not task_config:
return {}
try:
partition_num = task_confi... | cc890301d4403a7815480ad0b414e16e26283fa7 | 20,643 |
def _CalculateElementMaxNCharge(mol,AtomicNum=6):
"""
#################################################################
**Internal used only**
Most negative charge on atom with atomic number equal to n
#################################################################
"""
Hmol=Chem.AddHs... | f7bd9957c6e958f31cccc2bc20d6651baaf2f5fa | 20,644 |
import os
def get_task_metrics_dir(
model="spatiotemporal_mean", submodel=None, gt_id="contest_tmp2m", horizon="34w",
target_dates=None
):
"""Returns the directory in which evaluation metrics for a given submodel
or model are stored
Args:
model: string model name
submodel: string su... | a8398d68864e560dfd472b6051e15b70d4c0daca | 20,645 |
def check_stability(lambda0, W, mu, tau, dt_max):
"""Check if the model is stable for given parameter estimates."""
N, _ = W.shape
model = NetworkPoisson(N=N, dt_max=dt_max)
model.lamb = lambda0
model.W = W
model.mu = mu
model.tau = tau
return model.check_stability(return_value=True) | d417bdba0f236edf5f5c9e17c09e2d2a93bf2b4a | 20,646 |
import re
def pid2id(pid):
"""convert pid to slurm jobid"""
with open('/proc/%s/cgroup' % pid) as f:
for line in f:
m = re.search('.*slurm\/uid_.*\/job_(\d+)\/.*', line)
if m:
return m.group(1)
return None | e7d0ee60d5a8930b8a6f761d5c27451a28b6ec2a | 20,647 |
import platform
import os
def get_develop_directory():
"""
Return the develop directory
"""
if platform.system() == "Windows":
return os.path.dirname(os.path.realpath(__file__)) + "\\qibullet"
else:
return os.path.dirname(os.path.realpath(__file__)) + "/qibullet" | 5654b3c5b2417e8429a3ec2ca310567a185d78a1 | 20,648 |
import copy
def multiaxis_scatterplot(xdata,
ydata,
*,
axes_loc,
xlabel='',
ylabel='',
title='',
num_cols=1,
n... | 22d9aa3b0de496c498535b2b4bf663be429b8f48 | 20,649 |
import torch
def log1p_mse_loss(estimate: torch.Tensor, target: torch.Tensor,
reduce: str = 'sum'):
"""
Computes the log1p-mse loss between `x` and `y` as defined in [1], eq. 4.
The `reduction` only affects the speaker dimension; the time dimension is
always reduced by a mean operat... | 7c67a67dcf6f6d14bb712d5a92b54ea979f7a73c | 20,650 |
def quaternion_inverse(quaternion: np.ndarray) -> np.ndarray:
"""Return inverse of quaternion."""
return quaternion_conjugate(quaternion) / np.dot(quaternion, quaternion) | b71c5b544199b02a76362bc42db900b157ea80ec | 20,651 |
def _make_indexable(iterable):
"""Ensure iterable supports indexing or convert to an indexable variant.
Convert sparse matrices to csr and other non-indexable iterable to arrays.
Let `None` and indexable objects (e.g. pandas dataframes) pass unchanged.
Parameters
----------
iterable : {list, d... | 29d067826e0a863b06b1fb0295b12d57ecaea00d | 20,652 |
def batchnorm_forward(x, gamma, beta, bn_param):
"""
Forward pass for batch normalization.
During training the sample mean and (uncorrected) sample variance are
computed from minibatch statistics and used to normalize the incoming data.
During training we also keep an exponentially decaying running ... | b36ea808c5865eb92a81464c3efe14ab9325d01e | 20,653 |
def chunking():
"""
transforms dataframe of full texts into a list of chunked texts of 2000 tokens each
"""
word_list = []
chunk_list = []
text_chunks = []
# comma separating every word in a book
for entry in range(len(df)):
word_list.append(df.text[entry].split())
# create a chunk of ... | 66e1976b3bd9e88420fab370f1eee9053986bd56 | 20,654 |
def generate_random_string():
"""Create a random string with 8 letters for users."""
letters = ascii_lowercase + digits
return ''.join(choice(letters) for i in range(8)) | 027a9d50e2ff5b80b7344d35e492ace7c65366e8 | 20,655 |
def contains_message(response, message):
"""
Inspired by django's self.assertRaisesMessage
Useful for confirming the response contains the provided message,
"""
if len(response.context['messages']) != 1:
return False
full_message = str(list(response.context['messages'])[0])
return... | 4afcdba84603b8b53095a52e769d0a8e3f7bbb17 | 20,656 |
def definition():
"""To be used by UI."""
sql = f"""
SELECT c.course_id,
c.curriculum_id,
cs.course_session_id,
description + ' year ' +CAST(session as varchar(2)) as description,
CASE WHEN conf.course_id IS NULL THEN 0 ELSE 1 END as linked,
0 as changed
FROM (... | ac67783943604e0e83bd4ccfc2b704737e427edd | 20,657 |
def exec_psql_cmd(command, host, port, db="template1", tuples_only=True):
"""
Sets up execution environment and runs the HAWQ queries
"""
src_cmd = "export PGPORT={0} && source {1}".format(port, hawq_constants.hawq_greenplum_path_file)
if tuples_only:
cmd = src_cmd + " && psql -d {0} -c \\\\\\\"{1};\\\\\\... | 453f0c2ef0dfdf2a5d03b22d4a6fbd03282dd72a | 20,658 |
def carla_cityscapes_image_to_ndarray(image: carla.Image) -> np.ndarray: # pylint: disable=no-member
"""Returns a `NumPy` array from a `CARLA` semantic segmentation image.
Args:
image: The `CARLA` semantic segmented image.
Returns:
A `NumPy` array representation of the image.
"""
image.convert(carl... | f191d3f9700b281178f395726d649e90dfc57bb7 | 20,659 |
import re
def since(version):
"""A decorator that annotates a function to append the version
of skutil the function was added. This decorator is an adaptation of PySpark's.
Parameters
----------
version : str, float or int
The version the specified method was added to skutil.
Exam... | e6b29b5e4c67ba4a213b183a0b79a1f16a85d81c | 20,660 |
def get_dMdU():
"""Compute dMdU"""
dMdC = form_nd_array("dMdC", [3,3,3,3,3])
dMdPsi = form_nd_array("dMdPsi", [3,3,3,3,3])
dMdGamma = form_nd_array("dMdGamma",[3,3,3,3,3,3])
dCdU = form_symb_dCdU()
dPsidU = form_symb_dPhidU()
dGammadU = form_symb_dGammadU()
... | 55d6dedc5311c8a2a30c44569508bd7687400cb5 | 20,661 |
def get_group_value_ctx_nb(sc_oc):
"""Get group value from context.
Accepts `vectorbt.portfolio.enums.SegmentContext` and `vectorbt.portfolio.enums.OrderContext`.
Best called once from `segment_prep_func_nb`.
To set the valuation price, change `last_val_price` of the context in-place.
!!! note
... | 0646e7a26b36af42ee38196e0ee60e3684da2d16 | 20,662 |
import math
import torch
import scipy
def motion_blur_generate_kernel(radius, angle, sigma):
"""
Args:
radius
angle (float): Radians clockwise from the (x=1, y=0) vector. This
is how ImageMagick's -motion-blur filter accepts angles, as far
as I can tell.
>>> mb_1_0... | ff4e939d2ffbc91b6ef6af2ca11aceb1d32df594 | 20,663 |
def substitute_crypto_to_req(req):
"""Replace crypto requirements if customized."""
crypto_backend = get_crypto_req()
if crypto_backend is None:
return req
def is_not_crypto(r):
CRYPTO_LIBS = PYCRYPTO_DIST, "cryptography"
return not any(r.lower().startswith(c) for c in CRYPTO_L... | 0e1836120f52981c3ff126038c0c74b9da94aa7f | 20,664 |
def remove_att(doc_id, doc_rev, att_id, **kwargs):
"""Delete an attachment.
http://docs.couchdb.org/en/stable/api/document/attachments.html#delete--db-docid-attname
:param str doc_id: The attachment document.
:param str doc_rev: The document revision.
:param str att_id: The attachment to remove.
... | 2b9361468baf4dc2e358b2fa2f4c43403556cd40 | 20,665 |
import urllib
def read_file(file_path):
"""Read file according to its file schema"""
s3_schema = 's3'
path_comps = urllib.parse.urlparse(file_path)
scheme = path_comps.scheme
return_result = None
if not scheme or scheme != s3_schema:
file_stream = open(file_path)
return_result... | 438c6286f5f29792fd7c99412bead96a11adc757 | 20,666 |
from typing import List
def build_command(codemodders_list: List) -> BaseCodemodCommand:
"""Build a custom command with the list of visitors."""
class CustomCommand(BaseCodemodCommand):
transformers = codemodders_list
return CustomCommand(CodemodContext()) | 5aed3c94c954a8e62c7cfb23f2b338e3a017d988 | 20,667 |
def default_gen_mat(dt: float, size: int) -> np.ndarray:
"""Default process matrix generator.
Parameters
----------
dt : float
Dimension variable difference.
size : int
Size of the process matrix, equals to number of rows and columns.
Returns
-------
np.ndarray
... | fc4c19b33dae27ec412a00d20b89c25c5bc8668c | 20,668 |
def _PrepareListOfSources(spec, generator_flags, gyp_file):
"""Prepare list of sources and excluded sources.
Besides the sources specified directly in the spec, adds the gyp file so
that a change to it will cause a re-compile. Also adds appropriate sources
for actions and copies. Assumes later stage will un-ex... | a6a0d0d6d7531b8e858c8ec0d0aedee320c20d8d | 20,669 |
def striptag(tag):
"""
Get the short representation of a fully qualified tag
:param str tag: a (fully qualified or not) XML tag
"""
if tag.startswith('{'):
return tag.rsplit('}')[1]
return tag | f0193e3f792122ba8278e599247439a91139e72b | 20,670 |
def dump_key(key):
""" Convert key into printable form using openssl utility
Used to compare keys which can be stored in different
format by different OpenSSL versions
"""
return Popen(["openssl","pkey","-text","-noout"],stdin=PIPE,stdout=PIPE).communicate(key)[0] | 71dd28876c2fd3e28a4434b926b483cef3b104c2 | 20,671 |
def download_complete(root_data_path, domain_name, start_date, end_date):
"""
Check that all files have been downloaded and that they contain the data in
the expected date range
"""
missing_files = _find_missing_files(
root_data_path=root_data_path,
domain_name=domain_name,
s... | 3540632c5ec48fb0741b8173f926fd1cb5970333 | 20,672 |
from typing import Any
def get_test_string(actual: Any, rtol: float, atol: float) -> str:
"""
Args:
actual: The actual value that was produced, and that should be the desired value.
rtol: The relative tolerance of the comparisons in the assertion.
atol: The absolute tolerance of the co... | f017806bef4336bf187071436bd454d0ca980636 | 20,673 |
def is_type_resolved(_type):
"""Helper function that checks if type is already resolved."""
return _type in BASIC_TYPES or isinstance(_type, TypeDef) | 9451a5dbf17aef1685122b881ede994d1a02b7a0 | 20,674 |
import types
def get_extension(media):
"""Gets the corresponding extension for any Telegram media."""
# Photos are always compressed as .jpg by Telegram
try:
get_input_photo(media)
return '.jpg'
except TypeError:
# These cases are not handled by input photo because it can't
... | cb05f122fdf03df38c6d7b7904c7ec611f09c7a0 | 20,675 |
def process_input(df, col_group, col_t, col_death_rate, return_df=True):
"""
Trim filter and adding extra information to the data frame.
Args:
df (pd.DataFrame): Provided data frame.
col_group (str): Column name of group definition.
col_t (str): Column name of the independent variab... | 24b1e7274959c5b4befbd826c1a60ca700316b2f | 20,676 |
def cross_entropy_loss():
"""
Returns an instance to compute Cross Entropy loss
"""
return tf.keras.losses.BinaryCrossentropy(from_logits=True) | 5fcc673d9339bd4acb84d55fe0c316bc4cf802c4 | 20,677 |
def f(x):
"""
Surrogate function over the error metric to be optimized
"""
evaluation = run_quip(cutoff = float(x[:,0]), delta = float(x[:,1]), n_sparse = float(x[:,2]), nlmax = float(x[:,3]))
print("\nParam: {}, {}, {}, {} | MAE : {}, R2: {}".format(float(x[:,0]),float(x[:,1]),float(x[:,2]),f... | 0663b9eb2b717f547f57a8485739165414fbbdba | 20,678 |
def equal(* vals):
"""Returns True if all arguments are equal"""
if len(vals) < 2:
return True
a = vals[0]
for b in vals[1:]:
if a != b:
return False
return True | dbd947016d2b84faaaa7fefa6f35975da0a1b5ec | 20,679 |
import os
def chrome_options() -> Options:
"""Pass standard Chrome options to a test."""
options = Options()
executable_path = os.getenv("EXECUTABLE_PATH")
assert (
executable_path is not None
), "EXECUTABLE_PATH environment variable must be set"
logger.info(f"EXECUTABLE_PATH is {execu... | 1c1c32aec18cfea1c040045da401052953626b29 | 20,680 |
def exp(x: pd.Series) -> pd.Series:
"""
Exponential of series
:param x: timeseries
:return: exponential of each element
**Usage**
For each element in the series, :math:`X_t`, raise :math:`e` (Euler's number) to the power of :math:`X_t`.
Euler's number is the base of the natural logarithm,... | c4cb057be2dd988a152cc8f224d4bd4300f88263 | 20,681 |
import os
def level_location(level, cache_dir):
"""
Return the path where all tiles for `level` will be stored.
>>> level_location(2, '/tmp/cache')
'/tmp/cache/02'
"""
if isinstance(level, string_type):
return os.path.join(cache_dir, level)
else:
return os.path.join(cache_... | 368fb5696001133ebdbaeb885b0408c7bb3715b0 | 20,682 |
def pil_paste_image(im, mask, start_point=(0, 0)):
"""
:param im:
:param mask:
:param start_point:
:return:
"""
out = Image.fromarray(im)
mask = Image.fromarray(mask)
out.paste(mask, start_point, mask)
return np.asarray(out) | b6393426aa5b7434e64cddc11ed598fca78a2b47 | 20,683 |
import requests
def service_northwind_v2(schema_northwind_v2):
"""https://services.odata.org/V2/Northwind/Northwind.svc/"""
return pyodata.v2.service.Service('http://not.resolvable.services.odata.org/V2/Northwind/Northwind.svc',
schema_northwind_v2, requests) | a7934ff032725589bb11aab9cd84c26d9f2845c3 | 20,684 |
from typing import Mapping
from typing import Any
import logging
import os
from sys import flags
def train_and_eval(
params: base_configs.ExperimentConfig,
strategy_override: tf.distribute.Strategy) -> Mapping[str, Any]:
"""Runs the train and eval path using compile/fit."""
logging.info('Running train and... | 6e1e8a4bf8b6821277e541e1433ba27973aa59c4 | 20,685 |
def make_params(params, extra_params):
"""
Creates URL query params by combining arbitrary params
with params designated by keyword arguments and escapes
them to be compatible with HTTP request URI.
Raises an exception if there is a conflict between the
two ways to specify a query param.
""... | f2df0c52675476c0420d40f5ef9053cd2a719194 | 20,686 |
def raw_tag(name, value):
"""Create a DMAP tag with raw data."""
return name.encode('utf-8') + \
len(value).to_bytes(4, byteorder='big') + \
value | 9f86a5a9ebc38fcfd31eb7d76ac8bb01618f6ca7 | 20,687 |
def get_command(tool_xml):
"""Get command XML element from supplied XML root."""
root = tool_xml.getroot()
commands = root.findall("command")
command = None
if len(commands) == 1:
command = commands[0]
return command | 8d50b2675b3a6089b15b5380025ca7def9e4339e | 20,688 |
from whoosh.reading import SegmentReader
def OPTIMIZE(writer, segments):
"""This policy merges all existing segments.
"""
for seg in segments:
reader = SegmentReader(writer.storage, writer.schema, seg)
writer.add_reader(reader)
reader.close()
return [] | e5985641cbe724072f37158196cdaed0600b403e | 20,689 |
def build_features_revenue_model_q2(
df_listings: pd.DataFrame, df_daily_revenue: pd.DataFrame
):
"""Builds the features to be used on the revenue modelling for
answer question 2.
Parameters
----------
df_listings : pd.DataFrame
Pandas dataframe with information about listings.
df_d... | 16658cbc76edf66cf718b008d5fba58414df1f8c | 20,690 |
import gzip
def load_data():
"""Return the MNIST data as a tuple containing the training data,
the validation data, and the test data.
The ``training_data`` is returned as a tuple with two entries.
The first entry contains the actual training images. This is a
numpy ndarray with 50,000 entries. ... | f021f1db4b0b22c6d89620f44db7e2578c516489 | 20,691 |
def find_by_id(cls, groupkey, objectid, raises=False):
"""A helper function to look up an object by id"""
ob = None
try:
ob = keyedcache.cache_get(groupkey, objectid)
except keyedcache.NotCachedError as e:
try:
ob = cls.objects.get(pk=objectid)
keyedcache.cache_s... | c2ce6b2081411dd51ba4af231d9618f321c8f6fc | 20,692 |
def get_elements(xmldoc, tag_name, attribute):
"""Returns a list of elements"""
l = []
for item in xmldoc.getElementsByTagName(tag_name) :
value = item.getAttribute(attribute)
l.append( repr( value ) )
return l | 2cda65802d0dc1ebbb7796f6a43fa9bacfbe852e | 20,693 |
def test_algorithm(circuit, iterations=(1000000)):
"""
Tests a circuit by submitting it to both aer_simulator and PyLinalg.
"""
linalg = PyLinalg()
qlm_circ, _ = qiskit_to_qlm(circuit, sep_measures=True)
test_job = qlm_circ.to_job(nbshots=0, aggregate_data=False)
expected = linalg.submit(tes... | ac11f10f9b467ab08275d55515a15d6906076191 | 20,694 |
def return_list_of_sn_host():
""" Return potential SN host names
This includes:
- List of object names in SIMBAD that would correspond to extra-galactic object
- Unknown objects
- objects with failed crossmatch
In practice, this exclude galactic objects from SIMBAD.
"""
list_simbad_ga... | c2a536fc4b742dc0e4a4c57a582174017d6e2877 | 20,695 |
import glob
import re
def folder2catalog(path, granule_trunk='', granule_extension='*', add_sf=False, client=None):
""" Reads a folder of granules into a STAREDataFrame catalog
:param path: Path of the folder containing granules
:type path: str
:param granule_trunk: Granule identifier (e.g. MOD09)
... | 3d1d34a3b2e85ddbfb624289126f077d1668bab4 | 20,696 |
def _check_satellite_low(xbee, is_on_hold):
"""
Check if satellites are low and set the is_on_hold flag.
Args:
xbee(xbee.Zigbee): the XBee communication interface.
is_on_hold(bool): a flag telling if the thread is already on hold.
Returns:
bool: True if low sats, False ... | 5ecfdc304a9f6aa5aa41335637f6e783a3643df1 | 20,697 |
import requests
def indexof(path):
"""Returns list of filenames parsed off "Index of" page"""
resp = requests.get(path)
return [a for a, b in file_index_re.findall(resp.text) if a == b] | 38b165bfd4f3dbefedff21c7ac62fb57cd8f2d97 | 20,698 |
from typing import Optional
def get_oversight(xml: str) -> Optional[OversightInfo]:
""" Get oversight """
if val := xml.get('oversight_info'):
return OversightInfo(
has_dmc=val.get('has_dmc', ''),
is_fda_regulated_drug=val.get('is_fda_regulated_drug', ''),
is_fda_r... | fc14da139eb350306175016a2b8d2d036d02b042 | 20,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.