content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import six
import asyncio
def maybe_coroutine(obj):
"""
If 'obj' is a coroutine and we're using Python3, wrap it in
ensureDeferred. Otherwise return the original object.
(This is to insert in all callback chains from user code, in case
that user code is Python3 and used 'async def')
"""
i... | d02703f283b32349c756f8d5539f3cf395ccea5c | 37,708 |
def inchi(xgr):
""" InChI string of this connectivity graph
"""
ich, _ = _inchi_with_atom_inchi_numbers(xgr)
return ich | 385c2d89d8b3fc450f1fb7d34dca18c09c3db5c8 | 37,709 |
def _compute_dloss_by_dmin_using_dmax(dloss_by_dmax):
"""
compute derivative of loss w.r.t min, it is sign flipped version of derivative w.r.t max
:param dq_by_dmax derivative w.r.t max
:return: derivative w.r.t min
"""
return tf.negative(dloss_by_dmax) | 986dd73f9d50b1a1a2ddc5569f45a7b8b153b7a8 | 37,710 |
import requests
def get_gitlab_groups(default_val=False):
"""
Get a list of groups for display in a drop-down menu box.
:return: List of groups name tuples.
"""
groups = {}
try:
groups = requests.get(
gitlab_import_config.gitlab_url + 'groups?search=' + gitlab_import_conf... | b73caa42659ce11290ddd89b36be4424d2989b13 | 37,711 |
def unsalt():
"""
Remove salt/solvates.
Examples and documentation: [https://wwwdev.ebi.ac.uk/chembl/extra/francis/standardiser/04\_unsalt.html](https://wwwdev.ebi.ac.uk/chembl/extra/francis/standardiser/04_unsalt.html)
CTAB is either single molfile or SDF file.
cURL examples:
curl -X POST --data-binary @unsal... | d9664d3c7c044f4e83ef282e9bcd5d6b616e2a05 | 37,712 |
def Select3D_SensitiveTriangle_Status(*args):
"""
:param X:
:type X: float
:param Y:
:type Y: float
:param aTol:
:type aTol: float
:param Dmin:
:type Dmin: float &
:rtype: int
* Dmin gives the distance between the cdg and aPoint return
:param p0:
:type p0: gp_XY
:... | e547e8a589cd218c1c182089f362fc39d94356cd | 37,713 |
def confirm_action(config, msg=None, allow_auto=True):
# type: (dict, str, bool) -> bool
"""Confirm action with user before proceeding
:param dict config: configuration dict
:param msg str: confirmation message
:param bool allow_auto: allow auto confirmation
:rtype: bool
:return: if user con... | 16911ed6095e25e7e7d738ba5112e207717c5332 | 37,714 |
import numpy
def read_nam_maps(netcdf_file_name, PREDICTOR_NAMES):
"""Reads fog-centered maps from NetCDF file.
E = number of examples (fog objects) in file
M = number of rows in each fog-centered grid
N = number of columns in each fog-centered grid
C = number of channels (predictor variables)
... | b3c253014dbec3ee3dc9866d977915d7a563a54a | 37,715 |
import socket
def pick_free_port():
""" Pick free port using socket """
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('localhost', 0))
addr, port = s.getsockname()
s.close()
return port | 9199b167ae8400e4796cb42c6c89fed47f2b3214 | 37,717 |
def borders(district, unit):
"""Check if a unit borders a district."""
if district == []:
return True
neighbour_coords = [(unit.x+i, unit.y+j) for i in [1, 0, -1]
for j in [1, 0, -1] if bool(i) ^ bool(j)]
district_coords = [(d_unit.x, d_unit.y) for d_unit in district]
... | d95bf55b54f0df63980236def80610dcdc6cbfeb | 37,718 |
def get_step_g(step_f, norm_L2, N=1, M=1):
"""Get step_g compatible with step_f (and L) for ADMM, SDMM, GLMM.
"""
# Nominally: minimum step size is step_f * norm_L2
# see Parikh 2013, sect. 4.4.2
#
# BUT: For multiple constraints, need to multiply by M.
# AND: For multiple variables, need to... | 4adec493ff82450ff0546088af86bac2372b862f | 37,719 |
def isDefinition():
"""Matches if the cursor is a definition
>>> from glud import *
>>> config = '''
... class X {};
... class Y;
... '''
>>> m = cxxRecordDecl(isDefinition())
>>> for c in walk(m, parse_string(config).cursor):
... print(c.spelling)
X
"""
return PredM... | cd3dfe601ccdd6caae7c66e5d26a7e437eab475b | 37,720 |
def read_string(buff, byteorder="big"):
"""Read a string from a file-like object."""
length = read_numeric(USHORT, buff, byteorder)
return buff.read(length).decode("utf-8") | 46f1deb426b38a54b5b47ae49bcaadb694d07b95 | 37,721 |
def SGD_ninits(setup):
"""Perform stochastic gradiend descent for a number of initial models.
Arguments:
setup -- SGDsetup object which contains SGD parameters.
"""
print_SGDsetup(setup)
dRMSEs = []
models_costmin = []
zs_hist = []
mRMSEs = []
for j in range(setup.ninits):
... | cb9c199eff1186958748225d996c22b253106684 | 37,723 |
def _cv_checkerboard(image_size, square_size):
"""Generates a checkerboard level set function.
According to Pascal Getreuer, such a level set function has fast convergence.
"""
yv = np.arange(image_size[0]).reshape(image_size[0], 1)
xv = np.arange(image_size[1])
return (np.sin(np.pi/square_size... | 9a8fa8c72605591dac7e65c7bdaf587e48c2d3e8 | 37,724 |
from typing import Tuple
def calc_sigma_units(time_vector: np.ndarray, range_los: np.ndarray) -> Tuple[float, float]:
"""Calculates Gaussian peak std parameters.
The amount of smoothing is hard coded. This function calculates
how many steps in time and height corresponds to this smoothing.
Args:
... | cee943aa800bfbd7b5ef6389561db8d2c201047f | 37,725 |
def format_request(routes, route, method, base_url="{{base_Url}}"):
"""Populates atomic_request dictionary with route metatdata.
Returns a postman formatted dictionary request item."""
request = atomic_request()
doc = get_route_doc_string(routes, route, method)
name = get_route_name(route)
url ... | 96c1b7b6430b260ae897ee0668db6ae21b0508ff | 37,726 |
def reachable(fanin, n):
"""
Figure out what circuits are reachable from gates with limited fanin.
"""
seen = set()
answer = []
atoms = Toffoli.generate(fanin, n)
pending = list(atoms)
while pending:
circuit = pending.pop()
sig = signature(circuit, n)
if sig in se... | ef7512574eae0fc3db37a6f5c04d323c04391857 | 37,727 |
from typing import Dict
from typing import List
from typing import Any
import re
def process_action(action_info: Dict, sentences_info: List[Dict[str, Any]],
words: List[str], sentence_number: int) -> Action:
"""
Create action and his object
Parameters
----------
action_info
... | 4390ba373e356a8f766b4c417c1295ac0d673f58 | 37,729 |
def unique_slugify(data, models, duplicate_key=''):
"""Returns a unique slug string. If duplicate_key is provided, this is
appended for non-unique slugs before adding a count."""
slug_base = slugify(data)
counter = 0
slug = slug_base
while any(model.objects.filter(slug=slug).exists() for mod... | 0fea02eb2efd1a0b06fc7a06d8fd78d270076445 | 37,730 |
import torch
def affine_del_homogeneous(affine):
"""Ensure that the last row of the matrix is _not_ (*zeros, 1).
This function is more generic than `make_rect` because it
works with images where the dimension of the output space differs
from the dimension of the input space.
Parameters
-----... | 65e0b0d8b99828445452c1129806aa25be5b92d3 | 37,731 |
def Kurt(poly, dist=None, fisher=True, **kws):
"""
Kurtosis operator.
Element by element 4rd order statistics of a distribution or polynomial.
Args:
poly (numpoly.ndpoly, Distribution):
Input to take kurtosis on.
dist (Distribution):
Defines the space the skewne... | 74ba9fdd76b4e7a4d02ba83459a2446dcecf8643 | 37,732 |
import copy
def relabel_graph_nodes(graph, label_dict=None, with_data=True):
"""
Relabel graph nodes.The graph
is relabelled (and returned) according to the label
dictionary and an inverted dictionary is returned.
Only integers are allowed as labels. If some other
objects will be passed inn th... | 65aa8707691e3c6b9b13a6ae18efa9be30989832 | 37,733 |
def add_form_shared(request, client_api, form_acess="", external=False):
"""
Method to render form request vip
"""
try:
lists = dict()
lists["action"] = reverse('vip-request.form')
lists['ports'] = ''
lists['ports_error'] = ''
lists['reals_error'] = ''
l... | 18e1e64c822be571f0441b4e577d060846ee10d9 | 37,734 |
import time
from datetime import datetime
def adv_results(request):
"""
Process the form from an advanced search.
We expect to always get here from the advanced search page and
always on a get, either from the submit button on the form or the
paging navigation buttons.
* On first search sub... | 0a2fd13061500b72345bf4270d1630483dfa706b | 37,735 |
def code_duplication_figure(metrics):
"""Create the code duplication donut."""
duplicated_loc = metrics["duplicated_loc"]
total_loc = metrics["total_loc"]
labels = ["Duplicated code", "Non duplicated code"]
values = [duplicated_loc, (total_loc - duplicated_loc)]
percentage = (duplicated_loc /... | fc37e896e45aa120e9b5f5f2302d3fd8d41e3be9 | 37,736 |
def adduser(username, uid=None, system=False, no_login=True, no_password=False, gecos=None,
arg_mapping=CmdArgMappings.DEBIAN, **kwargs):
"""
Formats an ``adduser`` command.
:param username: User name.
:type username: unicode | str
:param uid: Optional user id to use.
:type uid: lon... | d1ddd2e07bfb94e9081f1fa445a504f4ac28f722 | 37,737 |
def lin(p,x):
""" Linear function for fitting """
return p[0]+np.dot(p[1],x) | 9b711c9a3aed6dd4786283cb291bd3697f100219 | 37,738 |
def _chartToDF(c):
"""internal"""
df = pd.DataFrame(c)
_toDatetime(df)
_reindex(df, "date")
return df | ebe443ac083a64f498a14d90963d2a739e06801b | 37,740 |
def file_diff_format(filename1, filename2):
"""
Inputs:
filename1 - name of first file
filename2 - name of second file
Output:
Returns a four line string showing the location of the first
difference between the two files named by the inputs.
If the files are identical, the fun... | d2e190754982ba429af369f5b404108a5e507214 | 37,741 |
def qlength(rcd):
"""
Returns "quality length"
"""
qscore = rcd.letter_annotations["phred_quality"]
nq = np.array(qscore)
q_mean = []
for i in range(1,len(nq)):
q_mean.append(abs(nq[:i].mean() - nq[i:].mean()))
q_mean[0] = q_mean[1]
return q_mean.index(max(q_mean)) | d0854483e9a93c39e7c278ac1235e65a5f4503f7 | 37,743 |
def social():
"""Redirects to the Accent Twitter profile."""
return redirect(SOCIAL_URL) | ca2ca341155dbed9b57f704c90486dc1b479d6bc | 37,744 |
def MakeCircleRange(circle_size, slice_side):
"""factory function that pre computes all circular slices
slices are assumed to be 2*slice_side+1 in length
"""
assert (circle_size - 1) % 2 == 0
slice_collection = {}
full_indices = list(range(0, circle_size))
for centre_index in range(circle_s... | f952b7b110233780164916afcef102364c3b7399 | 37,745 |
def TDataXtd_Constraint_GetID(*args):
"""
* Returns the GUID for constraints.
:rtype: Standard_GUID
"""
return _TDataXtd.TDataXtd_Constraint_GetID(*args) | 761883f727e6c4a7ecc280b7fc6f7246e31293cf | 37,747 |
def dependency_on_infectiousness_width_homogeneous_model_example():
"""
Example of several computations of the limit Eff_∞ in homogeneous scenarios (i.e. with no app usage)
in which the default distribution ρ^0 of the generation time is rescaled by different factors.
"""
infectiousness_rescale_fact... | 31b505d9c42d0c805deabf116f730a1297fe3d4e | 37,749 |
def octree_et(sc, margin, idx=None, eidx=None, bounds=None, cloth=None):
"""Adaptive octree. Good for finding doubles or broad
phase collision culling. et does edges and tris.
Also groups edges in boxes.""" # first box is based on bounds so first box could be any shape rectangle
#sh = cloth.pierce_co.s... | 523c3eeffac13d8aefd640e3a844e4ae46fed9e9 | 37,750 |
from .base import IODescriptorBase
def descriptor_dict_to_uri(ddict):
"""
Translates a descriptor dictionary into a uri.
:param ddict: descriptor dictionary
:returns: descriptor uri
"""
return IODescriptorBase.uri_from_dict(ddict) | 81eac77d3ef12103af457665ea28e6a6a32ef09a | 37,751 |
def process_df(df,
sentence_column='SentenceID',
word_column='Word',
tag_column='Tag',
verbose=1):
"""
Extract words, tags, and sentences from dataframe
"""
# get words and tags
words = list(set(df[word_column].values))
n_words = l... | 64ec6fabb657712524e333bb805a9352a93d6017 | 37,752 |
def ramp_geometric(phi, A):
""" Weighted geometric mean according to phi. """
return A[0]**(0.5*(1.+phi))*A[1]**(0.5*(1.-phi)) | 0f79e345336f4038e03947b10446031bd9f3e404 | 37,753 |
def dipole(sign, simplified=False):
"""Segmented BC dipole model."""
segtypes = {
'b': ('B', _pyaccel.elements.rbend),
'b_edge': ('edgeB', _pyaccel.elements.marker),
'b_pb': ('physB', _pyaccel.elements.marker),
}
# FIELDMAP
# trajectory centered in good-field region. init_... | f2a228ee722e4424c875af982350daba344aa588 | 37,756 |
def edge_to_string(token, is_head=False):
"""
Converts the token to an edge string representation
:param token: the token
:return: the edge string
"""
t = token
if not isinstance(token, spacy.tokens.token.Token):
t = token.root
return '/'.join([token_to_lemma(token), t.pos_, t.d... | 9473e543b635ee34e0723b15ad22bc8c2b20b21c | 37,757 |
def sknet152(**kwargs):
"""
SKNet-152 model from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.tensorflow/models'
Location for... | 2cd81b34d8d2d5d9316d956dbc997ff61ea8a993 | 37,758 |
import pathlib
def get_model_and_assets():
"""Returns a tuple containing the model XML string and a dict of assets."""
current_dir = pathlib.Path(__file__).parent.absolute()
return (resources.GetResource(f'{current_dir}/ball_in_cup_explore.xml'),
common.ASSETS) | c344513a4416273de90fccb95ed9e74d4d4ddd34 | 37,760 |
def render_file(path: str, **kwargs):
"""
Renders a file at the specified absolute path. The file can reside
anywhere on the local disk as Cauldron's template environment path
searching is ignored.
:param path:
Absolute path to a template file to render
:param kwargs:
Named argu... | 207e70699efb936f2f84fd8f01b6293626c8f6e1 | 37,762 |
import io
import csv
from datetime import datetime
async def export_books_csv():
"""export `Book`s to csv file"""
session = Session()
books = session.query(
BookTable.title,
BookTable.author,
BookTable.publisher,
BookTable.shorthand,
BookTable.number,
BookTa... | 0a641f42c9ffd2a416bae03f7cadd5692ef00c46 | 37,764 |
def export_videos(videos, email):
"""
Exporting videos is done in a seperate Celery process from the Flask handler.
Args:
videos (array): Array of video objects (See README.md for general idea of formats).
email (string): Email address (string) where a download link of the export results wi... | 2f2ad9e6aadf6d391f910157882fa861768fd880 | 37,765 |
def text_words(tree, show_traces=False):
"""Print just the words in the tree."""
text = []
for node in tree:
if node.is_terminal():
if node.is_trace() and not show_traces:
continue
text.append(node.word)
return ' '.join(text) | 58ae53ec1f10b8eb189d6714cbbdf391391c3728 | 37,766 |
from typing import Protocol
def edit_protocol(protocol_id):
"""Edit details of a protocol."""
current_protocol = Protocol.query.filter_by(id=protocol_id).first()
if current_protocol.user != current_user:
flash('Not your protocol!', 'danger')
return redirect('.')
form = ProtocolForm(r... | 407d0282e99449c3684bb4659b2ea6e89f895bf6 | 37,767 |
def get_win_drives():
""" Return list of detected drives """
assert NT
drives = []
bitmask = windll.kernel32.GetLogicalDrives()
for letter in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ':
if (bitmask & 1) and win32file.GetDriveType('%s:\\' % letter) in DRIVES:
drives.append(letter)
bitma... | 982f984ff1ee9fafcb26f065e594b6b4324b9d3b | 37,768 |
def query_grakn(session, query_object) -> dict:
"""
Purpose:
Gateway to the grakn queries
Args:
session: The Grakn session
query_object: the query_object
Returns:
answers_df_map: Answers to the queries by entity
"""
answers = {}
if query_object.action == "Find... | de2b6255a66302511c581b307d765686d6101fcd | 37,769 |
def skewa(s):
"""
SKEWA creates augmented skew-symmetric matrix
:param s: 3 or 6 vector
:return: augmented skew-symmetric matrix
SKEWA(V) is an augmented skew-symmetric matrix formed from V.
If V (1x3) then S =
| 0 -v3 v1 |
| v3 0 v2 |
| 0 0 0 |
... | 8dbdd9a4b885f9e96b1007fca42def50ef107374 | 37,770 |
import hashlib
def generate_server_uuid(input_string):
""" Create your own server_uuid
@param input_string (str): information to be encoded as server_uuid
@returns server_uuid (str): your unique server_uuid
"""
s = hashlib.sha256()
data = (input_string+SALT).encode("utf-8")
s.update(data)
... | 0857beb322ab2bbe280e8714ef7b8daa926e018f | 37,771 |
def get_subject_data(layout: BIDSLayout, subject: str):
"""
Gathers subject specific experimental data
"""
# Get the high resolution T1-weighted anatomical MRI scan
"""
In addition to the functional scan, a high resolution T1-weighted anatomical MRI scan was
made (3D gradient echo sequence,... | 1eb9fe9199b3314a29851d4de45b4ab63d897989 | 37,772 |
def multi_point(point_gdf):
"""Create a multi-point GeoDataFrame."""
multi_point = point_gdf.unary_union
out_df = GeoDataFrame(
geometry=GeoSeries(
[multi_point, Point(2, 5), Point(-11, -14), Point(-10, -12)]
),
crs="EPSG:4326",
)
out_df["attr"] = ["tree", "anothe... | 2f6e281f068273f7e100465c8c33da3dbc0cc378 | 37,773 |
def download_topo_land(load=True): # pragma: no cover
"""Download topo land dataset.
Parameters
----------
load : bool, optional
Load the dataset after downloading it when ``True``. Set this
to ``False`` and only the filename will be returned.
Returns
-------
pyvista.Poly... | 65137c5f8dfe6e6a0d7b2bc564f934ced6402b11 | 37,775 |
def transform_skycoordinates_to_radec(df, names, move_to_rad=True):
"""
Transform ``SkyCoordinate`` column to ``sindec``, ``sinra``, ``cosra``.
:param df:
Data frame with ``SkyCoordinate`` column.
:param names:
Iterable with names of columns with ``SkyCoordinate``s.
:param move... | 354d84b989d1468003c76c58412058e102b15821 | 37,777 |
def rot13(encoded: str) -> str:
"""
>>> rot13("har crefbaar abeznyr crafr dh’ha xvyb-bpgrg rfg étny à 1000 bpgrgf, ha vasbezngvpvra rfg pbainvaph dh’haxvybzèger rfg étny à 1024 zègerf.")
'une personne normale pense qu’un kilo-octet est égal à 1000 octets, un informaticien est convaincu qu’unkilomètre est ég... | 790d260a1cc517c49d3ea6e4c481fba32dca0831 | 37,778 |
def create_scene(gym, sim, props, assets_biotac, assets_indenters, biotac_offset=0.05, indenter_offset=0.01785938):
"""Create a scene (i.e., ground plane, environments, BioTac actors, and indenter actors)."""
plane_params = gymapi.PlaneParams()
gym.add_ground(sim, plane_params)
env_handles = []
ac... | 4b8df3a7f27b43e211235c6863f482e0754cef9b | 37,779 |
def ni_parse(*, df_list, year, **_):
"""
Combine, parse, and format the provided dataframes
:param df_list: list of dataframes to concat and format
:param args: dictionary, used to run flowbyactivity.py
('year' and 'source')
:return: df, parsed and partially formatted to flowbyactivity
... | 4a7bb161154d24f96cd94bf846423458b7f1885b | 37,780 |
from re import X
from re import T
def run(dx, Tf, generator="cython", sorder=None, withPlot=True):
"""
Parameters
----------
dx: double
spatial step
Tf: double
final time
generator: pylbm generator
sorder: list
storage order
withPlot: boolean
if Tru... | 9e9dee091ae3bff151e310391fd3fc5416dbee2f | 37,781 |
def get_policy(arn: str, configuration: Configuration = None,
secrets: Secrets = None) -> bool:
"""
Get a policy by its ARN
"""
client = aws_client("iam", configuration, secrets)
return client.get_policy(PolicyArn=arn) | e37c20893d44bc1d59fbb04247a35ae0f96e624a | 37,782 |
def soft_crossentropy(predicted_logprobs, target_probs):
"""
Cross-entropy loss capable of handling soft target probabilities.
"""
return -(target_probs * predicted_logprobs).sum(1).mean(0) | 8f6f0168c67cd0b3f432a5c91c7f4069c54de7c8 | 37,783 |
def is_slashable_attestation_data(data_1: AttestationData, data_2: AttestationData) -> bool:
"""
Check if ``data_1`` and ``data_2`` are slashable according to Casper FFG rules.
"""
return (
# Double vote
(data_1 != data_2 and data_1.target.epoch == data_2.target.epoch) or
# Surro... | 9c6f7c933c45b0643ea476feac56a57b0f3091b6 | 37,784 |
def trunc(x):
"""
Truncate the values to the integer value without rounding
"""
if isinstance(x, UncertainFunction):
mcpts = np.trunc(x._mcpts)
return UncertainFunction(mcpts)
else:
return np.trunc(x) | e1a48ca75903ee869d571677034afce7305f6d0b | 37,785 |
def _mine_store(mine_data, clear=False):
"""
Helper function to store the provided mine data.
This will store either locally in the cache (for masterless setups), or in
the master's cache.
:param dict mine_data: Dictionary with function_name: function_data to store.
:param bool clear: Whether o... | 2c568a8652876e24a22cc381bb58f855294411fc | 37,786 |
def semivariogram(F, sites, xbin=None, robust=True, trimmed=True, cloud=False, counts=False, se=False):
"""
Classical semivariogram estimator with option for Cressie's robust
estimator. Can also return a semivariogram "cloud".
Parameters
----------
F : ndarray, (N, ...)
One or more sam... | 42c9c0dec1167bca86e06a8adff4ebc9a4c598b7 | 37,787 |
def linelength(x0, y0, x1, y1):
"""Returns the length of the line."""
a = pow(abs(x0 - x1), 2)
b = pow(abs(y0 - y1), 2)
return sqrt(a+b) | 9df83b77666b88b07230ae09bafde701312bbd1c | 37,788 |
def get_table_max_columns_width(table, column_mapping):
""" Returns a list with columns width
Args:
table (list): of dictionaries must correspond to column_mapping
column_mapping (list): of tuples: mapping of final table column names to actual `table keys`
.. code-block:: python
... | f80e7ab053dee415570c64f2a96565f9c59aedcc | 37,789 |
def create_switch_with_ecobee_clear_hold_button(accessory):
"""Define setup button characteristics."""
service = accessory.add_service(ServicesTypes.OUTLET)
setup = service.add_char(CharacteristicsTypes.Vendor.ECOBEE_CLEAR_HOLD)
setup.value = ""
setup.format = "string"
cur_state = service.add... | a541f36dd7c5c90490e5dc876140c3c21e9aa548 | 37,790 |
def infer_mime(
mime,
args,
vocab,
data,
fuzz_ops,
emotion=None,
format_data_output_path=None,
):
"""
Infer
"""
fuzzed_data = fuzz(data, {"ops": fuzz_ops})
formatter = MIMEPipeline(vocab)
formatter.format([[obj["fuzzed"]] for obj in fuzzed_data], emotion=emotion)
... | 044d2714d0b00b47d9f123fd3862fa39eb315c7b | 37,791 |
def request_priority_access(requester: str, trusted_by: str = None,
url: str = None):
"""(draft) Request priority to access data (eg Overloaded server allow you)
Example:
please = hxlm.routing.request_priority_access(
url='https://example.org/dataset/data... | a9f03d6b8f67f7551562fa6a078a7d0aca686e15 | 37,792 |
def trycmd(*args, **kwargs):
"""Convenience wrapper around oslo's trycmd() function."""
if 'run_as_root' in kwargs and 'root_helper' not in kwargs:
kwargs['root_helper'] = _get_root_helper()
return processutils.trycmd(*args, **kwargs) | e69f389b4fb8adeea0a2fae8ad47a7b7dceda236 | 37,793 |
import nomenclator.utilities
def mocked_fetch_next_version(mocker):
"""Return mocked 'nomenclator.utilities.fetch_next_version' function."""
return mocker.patch.object(nomenclator.utilities, "fetch_next_version", ) | e9506caf038ef7a6a2b39000d856c2d807b2849c | 37,794 |
from re import T
def is_from_keyword(token):
"""
「FROM」判定
"""
return token.match(T.Keyword, "FROM") | 006dede893eb4e9978dda7e669cc27145a1cd3b3 | 37,795 |
import copy
def get_saved_state(model, optimizer, lr_scheduler, epoch, hyp):
"""Get the information to save with checkpoints"""
if hasattr(model, 'module'):
model_state_dict = model.module.state_dict()
else:
model_state_dict = model.state_dict()
utils_state_dict = {
'epoch': ep... | ab4d9642c1a55e4a006844d21522c4d081d9595a | 37,796 |
def compact(number):
"""Convert the number to the minimal representation. This strips the
number of any valid separators and removes surrounding whitespace."""
return clean(number, ' -.').strip() | 55208b33fddcc8d53f2dec737010c4871d0f96f8 | 37,797 |
def pretty_status_str(status,color,bold):
"""return pretty status string from status code"""
if bold:
bold_str='1'
else:
bold_str='0'
color_map = {
0: 32, # green
10: 32, # green
15: 37, # white
20: 31, # red
30: 31, # red
}
color_code=color_map.get(st... | 7612c87289270d09cf6685b044cea2f6d91e925d | 37,798 |
def dynamic_import(import_string):
"""
Dynamically import a module or object.
"""
# Use rfind rather than rsplit for Python 2.3 compatibility.
lastdot = import_string.rfind('.')
if lastdot == -1:
return __import__(import_string, {}, {}, [])
module_name, attr = import_string[:las... | 5dabdf31632502a5352ee4e1cc707846eb3a3843 | 37,799 |
import re
def get_list():
"""Supports starling/peafowl-style queue_<name>_items introspection via stats."""
conn = Client(CONN.split(';'))
queue_list = []
queue_re = re.compile(r'queue\_(.*?)\_total_items')
try:
for server in conn.get_stats():
for key in server[1].keys():
... | cfd19a24f9e49836eda87fa25c6e52ccaf6a7155 | 37,800 |
def net(n_ID):
"""
simple sample net to be used to train larger representations of given representations
while retaining the identity information
return: keras model
"""
model = Sequential()
model.add(Dense(256, input_shape=(128,), activation="relu", kernel_ini... | ec2be4984347532206804be2bf8fdbd40f8689d1 | 37,802 |
from re import L
def fullrank(X, r=None):
"""
Return a matrix whose column span is the same as X.
If the rank of X is known it can be specified as r -- no check
is made to ensure that this really is the rank of X.
"""
if r is None:
r = rank(X)
V, D, U = L.svd(X, full_matrices=0... | 6375359a8fd6a4d7671b3bfc6aa972079ec8ed62 | 37,803 |
import random
def update_solution_set(thresholds, threshold_h, asked_no_solutions, campus_id, current_sol):
"""Updates the set of solutions stored when one of the thresholds changes."""
print("Running 'update_solution_set'.")
# Check that all thresholds are integers, otherwise do nothing.
if not all(m... | 62db52e7408ddde1c999a66780297a8be081c33c | 37,804 |
def gwloss(constC, hC1, hC2, T):
""" Return the Loss for Gromov-Wasserstein
The loss is computed as described in Proposition 1 Eq. (6) in [12].
Parameters
----------
constC : ndarray, shape (ns, nt)
Constant C matrix in Eq. (6)
hC1 : ndarray, shape (ns, ns)
h1(C1) matrix ... | 465b389a17489ee6ed707748f751a7d057518496 | 37,805 |
def get_tag_by_storage_id(storage_id):
"""
根据storage_id查询地域tag
:param storage_id:
:return: None if not found
"""
return get_tag_by_target_id(STORAGE_CLUSTER, storage_id) | b36a91bd7ebbd951a347a346ba84b954d13869e6 | 37,806 |
def load_merged_with_style(dataset, style):
"""Load the merged dataframe for all the splits and then filter them
based on style."""
assert dataset in ['duke_ct','openi_cxr']
if dataset == 'duke_ct':
train_merged, test_merged, predict_merged = load_data_duke_ct()
elif dataset == 'openi_cxr':
... | caf9f3328f4ddf52901a464a15da2d25b78754cd | 37,807 |
import html
def update_stats(preds, names, *args):
"""
Get the prediction of the best model and calculate
price per square meter and difference in price from
the previous parameters.
Notes
-----
Difference shows up after the user
changes the settings.
"""
area = args[2]
... | 059e6213a8c8056d977fc0041b6bcaecad0c34f1 | 37,809 |
def tflops_per_second(flops, dt):
""" Computes an effective processing rate in TFLOPS per second.
TFLOP/S = flops * / (dt * 1E12)
Args:
flops: Estimated FLOPS in the computation.
dt: Elapsed time in seconds.
Returns:
The estimate.
"""
return flops / (1E12 * dt) | f244632e1378a69ea55d4a994a9711bd3a2dca2a | 37,810 |
def format_img(img, C):
""" formats an image for model prediction based on config """
img, ratio = format_img_size(img, C)
img = format_img_channels(img, C)
return img, ratio | 84426f043c4ea8de5acb7b195aaabc1ecf082582 | 37,811 |
import json
def register():
#构造要返回的字符串# 初始化返回的数据 [arg1, arg2, arg3, arg4] arg1=状态码(num)arg2=msg(str) arg3= count(num) arg4=tuple
"""
:return:
{
"code": 0,
"msg": "",
"count": 29,
"data": []
}
"""
code = 500
print('??????????????code type=', type(code))
msg = '注册失败,请重新尝... | ace5184b847d9ce4fa7f5600ef0b8fa2646c9e1d | 37,812 |
from typing import Mapping
from typing import Dict
def get_instance_groups(context: models.Context) -> Mapping[str, InstanceGroup]:
"""Get a list of InstanceGroups matching the given context, indexed by name."""
groups: Dict[str, InstanceGroup] = {}
if not apis.is_enabled(context.project_id, 'compute'):
ret... | 08e1a09230856920aa4a25b6770b9ec8429b91dd | 37,813 |
def get_criteria_description(criterias, milestone_name):
"""Get implementation of the criteria, based on config.
This function checks for config criteria_name in config['criterias'],
gets class - realization of this criteria - and returns an instance
of this class.
"""
description = ""
for... | 0ba8b02206588c5fa978ed4c76d69a9be05b6e94 | 37,816 |
import pyslalib
def geo_to_bary(ra,dec,jd,epoch):
"""
For a given ra/dec, return the conversion from geocentric velocity to heliocentric
:ra: Decimal right ascension (degrees)
:dec: Decimal declination (degrees)
:jd: Modified (2000 = 51544) julian date
:epoch: Epoch of observations (e.g., 200... | b42c8d494c08c3c6f4da5c8d64712c3909225922 | 37,817 |
def plot_precinct_scatterplot(ei_runs, run_names, candidate, demographic_group="all", ax=None):
"""
Given two RxC EI runs, plot precinct-by-precinct comparison of preferences
for a given candidate from a given demographic group.
Parameters
----------
ei_runs: array
Length = 2
El... | 12432f06d643beb642883cf8924b87c18401d2a4 | 37,818 |
def linear_cubic_interpolation(driver_array=(), divisions=20, interpolation='quadratic'):
"""
interpolate the cubic line between points.
:return: <tuple> the array of point dictionary.
"""
point_final = ()
if interpolation == 'quadratic':
for t in xrange(divisions):
v1 = Vect... | d7820ba2a3bfc4f0dcb202b85bfdafb14b231a08 | 37,819 |
def gf_edf_shoup(f, n, p, K):
"""
Gathen-Shoup: Probabilistic Equal Degree Factorization
Given a monic square-free polynomial ``f`` in ``GF(p)[x]`` and integer
``n`` such that ``n`` divides ``deg(f)``, returns all irreducible factors
``f_1,...,f_d`` of ``f``, each of degree ``n``. This is a complet... | 46b2a478d6d3486d459337866c8f7fe427a7f5ef | 37,820 |
import inspect
def create_wrappers_for_class_methods(klass):
"""Wraps all the functions and class methods of a class."""
for name, func in inspect.getmembers(klass, predicate=inspect.isfunction):
setattr(klass, name, strong(func))
return klass | 559f10f9bc8449920fdbe093d942537fe9b21a8e | 37,821 |
def eci2geodetic(eci, t):
"""
convert ECI to geodetic coordinates
inputs:
eci/ecef: Nx3 vector of x,y,z triplets in the eci or ecef system [meters]
t : length N vector of datetime OR greenwich sidereal time angle [radians].
output
------
lat,lon (degrees/radians)
alt (meters)
... | ae3b974ba9ec1a8a143e33a912515e3f6832b4c7 | 37,822 |
def convert_to_circuit(image):
"""Encode truncated classical image into quantum datapoint."""
values = np.ndarray.flatten(image)
qubits = cirq.GridQubit.rect(4, 4)
circuit = cirq.Circuit()
for i, value in enumerate(values):
if value:
circuit.append(cirq.X(qubits[i]))
return c... | 0514aa99b30fe7b76e45b66bdd1d2c64560680c7 | 37,823 |
def verify_email_change(userid, token):
"""
Verify a user's email change request, updating the `login` record if it validates.
Compare a supplied token against the record within the `emailverify` table, and provided
a match exists, copy the email within into the user's account record.
Parameters:
... | e18e0481cd574027fd28cde7086b2198b1d8b940 | 37,824 |
import torch
def huber_fn_gradient(x, mu):
""" Huber function gradient """
y = torch.zeros_like(x)
with torch.no_grad():
mask = torch.abs(x) <= mu
y[mask] = x[mask]/mu
y[~mask] = x[~mask] / torch.abs(x[~mask])
return y | 1bcbe697a76c06afd49e7bbf106a3c1be0a47481 | 37,825 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.