content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def html_it():
"""Run coverage and make an HTML report for everything."""
import coverage
cov = coverage.coverage()
cov.start()
import here # pragma: nested
cov.stop() # pragma: nested
cov.html_report(directory="../html_other") | 5,342,700 |
def mkdirs(path, raise_path_exits=False):
"""Create a dir leaf"""
if not os.path.exists(path):
os.makedirs(path)
else:
if raise_path_exits:
raise ValueError('Path %s has exitsted.' % path)
return path | 5,342,701 |
def is_triplet(tiles):
"""
Checks if the tiles form a triplet.
"""
return len(tiles) == 3 and are_all_equal(tiles) | 5,342,702 |
def cli(ctx, comment, metadata=""):
"""Add a canned comment
Output:
A dictionnary containing canned comment description
"""
return ctx.gi.cannedcomments.add_comment(comment, metadata=metadata) | 5,342,703 |
def get_latest_slot_for_resources(latest, task, schedule_set):
"""
Finds the latest opportunity that a task may be executed
:param latest: type int
A maximum bound on the latest point where a task may be executed
:param task: type DAGSubTask
The task to obtain the latest starting slot fo... | 5,342,704 |
def _get_text(url: str):
"""
Get the text from a message url
Args:
url: rest call URL
Returns:
response: Request response
"""
response = requests.get(url["messageUrl"].split("?")[0])
return response | 5,342,705 |
def test_mat_discover():
"""Perform a simple run of mat_discover to ensure it runs without errors.
This does not involve checking to verify that the output is correct, and
additionally it uses a `dummy_run` and `dummy` such that MDS is used on a small
dataset rather than UMAP on a large dataset (for fa... | 5,342,706 |
def animate_a_b(
symbols=["AAPL", "GOOG", "MSFT", "BRK-A", "AMZN",
"FB", "XOM", "JNJ", "JPM", "WFC"],
start_date="2006-12-01", end_date="2016-12-01",
period=252 * 2):
""" --- Preprocess: You have to take Udacity! --- """
# Read data
dates = pd.date_range(start_date,... | 5,342,707 |
def divideFacet(aFacet):
"""Will always return four facets, given one, rectangle or triangle."""
# Important: For all facets, first vertex built is always the most south-then-west, going counter-clockwise thereafter.
if len(aFacet) == 5:
# This is a triangle facet.
orient = aFacet[4] #... | 5,342,708 |
def compute_g(n):
"""g_k from DLMF 5.11.3/5.11.5"""
a = compute_a(2*n)
g = []
for k in range(n):
g.append(mp.sqrt(2)*mp.rf(0.5, k)*a[2*k])
return g | 5,342,709 |
def initialize_hs(IMAG_counter):
"""Initialize the HiSeq and return the handle."""
global n_errors
experiment = config['experiment']
method = experiment['method']
method = config[method]
if n_errors is 0:
if not userYN('Initialize HiSeq'):
sys.exit()
hs.initializ... | 5,342,710 |
def print_toc() -> int:
"""
Entry point for `libro print-toc`
The meat of this function is broken out into the generate_toc.py module for readability
and maintainability.
"""
parser = argparse.ArgumentParser(description="Build a table of contents for an SE source directory and print to stdout.")
parser.add_arg... | 5,342,711 |
def new_game():
"""Starts new game."""
global paddle1_pos, paddle2_pos, paddle1_vel, paddle2_vel # these are numbers
global score1, score2 # these are ints
paddle1_pos = [[0, HEIGHT/2 - PAD_HEIGHT/2],
[PAD_WIDTH, HEIGHT/2 - PAD_HEIGHT/2],
... | 5,342,712 |
def get_colden(theta_xy, theta_xz, theta_yz, n_sample_factor=1.0,
directory=None, file_name='save.npy', quick=False,
gridrate=0.5, shift=[0, 0, 0], draw=False, save=False, verbose=False):
"""
Rotate gas into arbitrary direction
"""
if gridrate < 2**(-7):
boxsize... | 5,342,713 |
def main(file, size):
"""Program that solve N-puzzel game"""
if file:
puzzel_size, puzzel = parser(file)
game = Game(puzzel_size, puzzel)
elif size:
game = Game(size)
else:
raise SystemExit("Need puzzel size or puzzel file")
a_star(game) | 5,342,714 |
def PyException_GetCause(space, w_exc):
"""Return the cause (another exception instance set by raise ... from ...)
associated with the exception as a new reference, as accessible from Python
through __cause__. If there is no cause associated, this returns
NULL."""
w_cause = space.getattr(w_exc, spa... | 5,342,715 |
def _get_style_data(stylesheet_file_path=None):
"""Read the global stylesheet file and provide the style data as a str.
Args:
stylesheet_file_path (str) : The path to the global stylesheet.
Returns:
str : The style data read from the stylesheet file
"""
global __style_data
if ... | 5,342,716 |
def row_interval(rows: int) -> Expression:
"""
Creates an interval of rows.
Example:
::
>>> tab.window(Over
>>> .partition_by(col('a'))
>>> .order_by(col('proctime'))
>>> .preceding(row_interval(4))
>>> .following(CURRENT_ROW)
... | 5,342,717 |
def build_post_async_retry_failed_request(*, json: Any = None, content: Any = None, **kwargs: Any) -> HttpRequest:
"""Long running post request, service returns a 202 to the initial request, with an entity that
contains ProvisioningState=’Creating’. Poll the endpoint indicated in the Azure-AsyncOperation
he... | 5,342,718 |
def check_thresholds_memory_usage(X, X2, y2, sample_weight2, n_trees: int = 10, n_thresholds: int = 10, depth: int = 3):
"""
Check if tree really only gets the memory view (reference for object inside memory)
And that tree does not copy all thresholds array
"""
X = GeneticTree._check_X(GeneticTree()... | 5,342,719 |
def splitclass(classofdevice):
"""
Splits the given class of device to return a 3-item tuple with the
major service class, major device class and minor device class values.
These values indicate the device's major services and the type of the
device (e.g. mobile phone, laptop, etc.). If you google ... | 5,342,720 |
def change_to_local_price(us_fee):
"""Get us dollar change price from redis and apply it on us_fee.
"""
dollar_change = RedisClient.get('dollar_change')
if not dollar_change:
raise ValueError(ERRORS['CHANGE_PRICE'])
Rial_fee = float(us_fee) * int(dollar_change)
return int(Rial_fee) | 5,342,721 |
def get_positive(data_frame, column_name):
"""
Query given data frame for positive values, including zero
:param data_frame: Pandas data frame to query
:param column_name: column name to filter values by
:return: DataFrame view
"""
return data_frame.query(f'{column_name} >= 0') | 5,342,722 |
def axes(*args, **kwargs):
"""
Add an axes to the figure.
The axes is added at position *rect* specified by:
- ``axes()`` by itself creates a default full ``subplot(111)`` window axis.
- ``axes(rect, axisbg='w')`` where *rect* = [left, bottom, width,
height] in normalized (0, 1) units. *ax... | 5,342,723 |
def scrape_options_into_new_groups(source_groups, assignments):
"""Puts options from the :py:class:`OptionParser` and
:py:class:`OptionGroup` objects in `source_groups` into the keys of
`assignments` according to the values of `assignments`. An example:
:type source_groups: list of :py:class:`OptionPar... | 5,342,724 |
def write_dau_pack16(fid, kind, data):
"""Write a dau_pack16 tag to a fif file."""
data_size = 2
data = np.array(data, dtype='>i2').T
_write(fid, data, kind, data_size, FIFF.FIFFT_DAU_PACK16, '>i2') | 5,342,725 |
def resnext56_32x2d_cifar10(classes=10, **kwargs):
"""
ResNeXt-56 (32x2d) model for CIFAR-10 from 'Aggregated Residual Transformations for Deep Neural Networks,'
http://arxiv.org/abs/1611.05431.
Parameters:
----------
classes : int, default 10
Number of classification classes.
pretr... | 5,342,726 |
def _get_server_argparser():
"""
Create a :class:`argparse.ArgumentParser` with standard configuration
options that cli subcommands which communicate with a server require, e.g.,
hostname and credential information.
:return: the argparser
:rtype: argparse.ArgumentParser
"""
parser = arg... | 5,342,727 |
def is_internet_file(url):
"""Return if url starts with http://, https://, or ftp://.
Args:
url (str): URL of the link
"""
return (
url.startswith("http://")
or url.startswith("https://")
or url.startswith("ftp://")
) | 5,342,728 |
def zip(*args: Observable[Any]) -> Observable[Tuple[Any, ...]]:
"""Merges the specified observable sequences into one observable
sequence by creating a :class:`tuple` whenever all of the
observable sequences have produced an element at a corresponding
index.
.. marble::
:alt: zip
-... | 5,342,729 |
def GetFilter(image_ref, holder):
"""Get the filter of occurrences request for container analysis API."""
filters = [
# Display only packages
'kind = "PACKAGE_MANAGER"',
# Display only compute metadata
'has_prefix(resource_url,"https://www.googleapis.com/compute/")',
]
client = holder.cl... | 5,342,730 |
def predict_image_paths(image_paths, model_path, target_size=(128, 128)):
"""Use a trained classifier to predict the class probabilities of a list of images
Returns most likely class and its probability
:param image_paths: list of path(s) to the image(s)
:param model_path: path to the pre-trained model... | 5,342,731 |
def in_bounding_box(point):
"""Determine whether a point is in our downtown bounding box"""
lng, lat = point
in_lng_bounds = DOWNTOWN_BOUNDING_BOX[0] <= lng <= DOWNTOWN_BOUNDING_BOX[2]
in_lat_bounds = DOWNTOWN_BOUNDING_BOX[1] <= lat <= DOWNTOWN_BOUNDING_BOX[3]
return in_lng_bounds and in_lat_bounds | 5,342,732 |
def __DataContainerERT_addFourPointData(self, *args, **kwargs):
"""Add a new data point to the end of the dataContainer.
Add a new 4 point measurement to the end of the dataContainer and increase
the data size by one. The index of the new data point is returned.
Parameters
----------
... | 5,342,733 |
def spin_up(work_func, cfgs, max_workers = 8, log=None, single_thread=False, pass_n=True):
"""
Run a threadable function (typically a subprocess) in parallel.
Parameters
----------
work_func : callable
This does the work. It gets called with one or two arguments. The first
argument in always a config item f... | 5,342,734 |
def list_run_directories(solid_run_dir):
"""Return list of matching run directories
Given the name of a SOLiD run directory, find all the 'matching'
run directories based on the instrument name and date stamp.
For example, 'solid0127_20120123_FRAG_BC' and
'solid0127_20120123_FRAG_BC_2' would form ... | 5,342,735 |
def dummy_register():
"""Dummy register."""
with tempfile.TemporaryDirectory() as tmp_path:
tmp_path = pathlib.Path(tmp_path)
# Prepare the datasets
# Namespace 0
Ds0(data_dir=tmp_path / 'kaggle').download_and_prepare()
Ds1(data_dir=tmp_path / 'kaggle').download_and_prepare()
# Namespace 1
... | 5,342,736 |
def refresh_remote_vpsa(session, rvpsa_id, return_type=None, **kwargs):
"""
Refreshes information about a remote VPSA - such as discovering new pools
and updating how much free space remote pools have.
:type session: zadarapy.session.Session
:param session: A valid zadarapy.session.Session object. ... | 5,342,737 |
def zeros(shape, int32=False):
"""Return a blob of all zeros of the given shape with the correct float or
int data type.
"""
return np.zeros(shape, dtype=np.int32 if int32 else np.float32) | 5,342,738 |
def _connect():
"""Connect to a XMPP server and return the connection.
Returns
-------
xmpp.Client
A xmpp client authenticated to a XMPP server.
"""
jid = xmpp.protocol.JID(settings.XMPP_PRIVATE_ADMIN_JID)
client = xmpp.Client(server=jid.getDomain(), port=settings.XMPP_PRIVATE_SERV... | 5,342,739 |
def index():
"""Return the main page."""
return send_from_directory("static", "index.html") | 5,342,740 |
def get_groups(records_data: dict, default_group: str) -> List:
"""
Returns the specified groups in the
SQS Message
"""
groups = records_data["Groups"]
try:
if len(groups) > 0:
return groups
else:
return [default_group]
except IndexError as err:
... | 5,342,741 |
def sanitized_log(func: Callable[..., None], msg: AnyStr, *args, **kwargs) -> None:
"""
Sanitize args before passing to a logging function.
"""
sanitized_args = [
sanitize(a) if isinstance(a, bytes) else a
for a in args
]
func(msg, *sanitized_args, **kwargs) | 5,342,742 |
def build_stats(history, eval_output, time_callback):
"""Normalizes and returns dictionary of stats.
Args:
history: Results of the training step. Supports both categorical_accuracy
and sparse_categorical_accuracy.
eval_output: Output of the eval step. Assumes first value is eval_loss and
second... | 5,342,743 |
def test_tags_limited_to_user(authenticated_user: User, api_client: APIClient):
"""Test that tags returned are for the authenticated user"""
user2 = create_user(email="other@testing.com", password="testpass")
Tag.objects.create(user=user2, name="Fruity")
tag = Tag.objects.create(user=authenticated_user,... | 5,342,744 |
def truncate_single_leafs(nd):
"""
>>> truncate_single_leafs(node(name='a', subs=[node(name='a', subs=None, layer='a')], layer=None))
node(name='a', subs=None, layer='a')
"""
if nd.layer:
return nd
if nd.subs and len(nd.subs) == 1:
if nd.subs[0].layer:
return node(nd.... | 5,342,745 |
def postprocess_output(output, example, postprocessor):
"""Applies postprocessing function on a translation output."""
# Send all parts to the postprocessing.
if postprocessor is None:
text = output.output[0]
score = None
align = None
else:
tgt_tokens = output.output
... | 5,342,746 |
def get_aqua_timestamp(iyear,ichunk,branch_flag):
"""
outputs a timestamp string for model runs with a
predifined year-month-day timestamp split into
5 x 73 day chunks for a given year
"""
import numpy as np
if branch_flag == 0:
if ichunk == 0:
timestamp = format(iyear,... | 5,342,747 |
def aggregate_native(gradients, f, m=None, **kwargs):
""" Multi-Krum rule.
Args:
gradients Non-empty list of gradients to aggregate
f Number of Byzantine gradients to tolerate
m Optional number of averaged gradients for Multi-Krum
... Ignored keyword-arguments
Returns:
Ag... | 5,342,748 |
def isNormalTmpVar(vName: types.VarNameT) -> bool:
"""Is it a normal tmp var"""
if NORMAL_TMPVAR_REGEX.fullmatch(vName):
return True
return False | 5,342,749 |
def dump_obj(obj, path):
"""Dump object to file."""
file_name = hex(id(obj))
file_path = path + file_name
with open(file_path, 'wb') as f:
os.chmod(file_path, stat.S_IWUSR | stat.S_IRUSR)
pickle.dump(obj, f)
return file_name | 5,342,750 |
def count_time(start):
"""
:param start:
:return: return the time in seconds
"""
import time
end = time.time()
return end-start | 5,342,751 |
def split_by_state(xs, ys, states):
"""
Splits the results get_frame_per_second into a list of continuos line segments,
divided by state. This is to plot multiple line segments with different color for
each segment.
"""
res = []
last_state = None
for x, y, s in zip(xs, ys, states):
... | 5,342,752 |
def _free_x(N: int, Y: int, queen_y2x: List[int]):
"""Getting free cells in the Yth board row
>>> [x for x in _free_x(1, 0,[-1])]
[0]
>>> [x for x in _free_x(2, 1,[ 0,-1])]
[]
>>> [x for x in _free_x(2, 0,[-1,-1])]
[0, 1]
>>> [x for x in _free_x(3, 0,[ -1 ,-1, -1]... | 5,342,753 |
def sgd_update(trainables, learning_rate=1e-2):
"""
Updates the value of each trainable with SGD.
"""
for trainable in trainables:
trainable.value -= learning_rate*trainable.gradients[trainable] | 5,342,754 |
def final_spectrum(t, age, LT, B, EMAX, R, V, dens, dist, Tfir, Ufir, Tnir, Unir, binss, tmin, ebreak, alpha1, alpha2):
"""
GAMERA computation of the particle spectrum (for the extraction of the
photon sed at the end of the evolution of the PWN)
http://libgamera.github.io/GAMERA/docs/time_de... | 5,342,755 |
def exportWorkflowTool(context):
"""Export workflow tool and contained workflow definitions as XML files.
"""
sm = getSiteManager(context.getSite())
tool = sm.queryUtility(IWorkflowTool)
if tool is None:
logger = context.getLogger('workflow')
logger.debug('Nothing to export.')
... | 5,342,756 |
def stop_workers(ctx):
"""Stop the workers"""
if settings['env'] == 'local':
raise Exit(
'In the local environment use kill to quit the workers '
)
else:
for conn in settings['hosts']:
conn.run(f'/etc/cron.scripts/h51_stop_workers {settings["env"]}') | 5,342,757 |
def modal():
"""Contributions input controller for modal view.
request.vars.book_id: id of book, optional
request.vars.creator_id: id of creator, optional
if request.vars.book_id is provided, a contribution to a book is presumed.
if request.vars.creator_id is provided, a contribution to a creator ... | 5,342,758 |
def test_launch_with_none_or_empty_lti_message_type():
"""
Does the launch request work with an empty or None lti_message_type value?
"""
oauth_consumer_key = 'my_consumer_key'
oauth_consumer_secret = 'my_shared_secret'
launch_url = 'http://jupyterhub/hub/lti/launch'
headers = {'Content-Type... | 5,342,759 |
def returns(data):
"""Returns for any number of days"""
try:
trading_days = len(data)
logger.info(
"Calculating Returns for {} trading days".format(trading_days))
df = pd.DataFrame()
df['daily_returns'] = data.pct_change(1)
mean_daily_returns = df['daily_retur... | 5,342,760 |
def initialize_gear(context):
"""
Used to initialize the gear context 'gear_dict' dictionary with objects that
are used by all gears in the HCP-Suite.
Environment Variables
Manifest
Logging
dry-run
"""
# This gear will use a "gear_dict" dictionary as a custom-user field
# on th... | 5,342,761 |
def test_reraise_indirect():
"""
>>> test_reraise_indirect()
Traceback (most recent call last):
ValueError: TEST INDIRECT
"""
try:
raise ValueError("TEST INDIRECT")
except ValueError:
reraise() | 5,342,762 |
def do_rot13_on_input(input_string, ordered_radix=ordered_rot13_radix):
""" Perform a rot13 encryption on the provided message.
"""
encrypted_message = str()
for char in input_string:
# Two possibilities: in radix, or NOT in radix.
if char in ordered_radix:
# must find inde... | 5,342,763 |
def pwr_y(x, a, b, e):
"""
Calculate the Power Law relation with a deviation term.
Parameters
----------
x : numeric
Input to Power Law relation.
a : numeric
Constant.
b : numeric
Exponent.
e : numeric
Deviation term.
Returns
-------
nume... | 5,342,764 |
def test_get_serializer_class():
"""
Test the serializer class used by the view.
"""
view = views.EmailVerificationView()
expected = serializers.EmailVerificationSerializer
assert view.get_serializer_class() == expected | 5,342,765 |
def file_update_projects(file_id):
""" Page that allows users to interact with a single TMC file """
this_file = TMCFile.query.filter_by(uid=file_id).first()
project_form = AssignProjectsToFile()
if project_form.validate_on_submit():
data = dict((key, request.form.getlist(key) if len(... | 5,342,766 |
def find_optimal_cut(edge, edge1, left, right):
"""Computes the index corresponding to the optimal cut such that applying
the function compute_blocks() to the sub-blocks defined by the cut reduces
the cost function comparing to the case when the function compute_blocks() is
applied to the whole matrix. ... | 5,342,767 |
def test_get_wikidata_csl_item_author_ordering():
"""
Test extraction of author ordering from https://www.wikidata.org/wiki/Q50051684.
Wikidata uses a "series ordinal" qualifier that must be considered or else author
ordering may be wrong.
Author ordering was previously not properly set by the Wiki... | 5,342,768 |
def seq_to_networkx(header, seq, constr=None):
"""Convert sequence tuples to networkx graphs."""
graph = nx.Graph()
graph.graph['id'] = header.split()[0]
graph.graph['header'] = header
for id, character in enumerate(seq):
graph.add_node(id, label=character, position=id)
if id > 0:
... | 5,342,769 |
def add_vertex_edge_for_load_support(network, sup_dic, load_dic, bars_len, key_removed_dic):
"""
Post-Processing Function:
Adds vertices and edges in accordance with supports and loads
returns the cured network
"""
if not key_removed_dic:
load_sup_dic=merge_two_dicts(sup_dic, load_dic)
... | 5,342,770 |
def mimicry(span):
"""Enrich the match."""
data = {'mimicry': span.lower_}
sexes = set()
for token in span:
if token.ent_type_ in {'female', 'male'}:
if token.lower_ in sexes:
return {}
sexes.add(token.lower_)
return data | 5,342,771 |
def send_sms_code(mobile, sms_num, expires, temp_id):
"""
发送短信验证码
:param mobile: 手机号
:param sms_num: 验证码
:param expires: 有效期
:return: None
"""
try:
result = CCP().send_Template_sms(mobile, [sms_num, expires], temp_id)
except Exception as e:
logger.error("发送验证码短信[异常][... | 5,342,772 |
def LeftBinarySearch(nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
low = 0
high = len(nums)
while low < high:
mid = (low + high) // 2
if nums[mid] < target:
low = mid + 1
else:
high = mid
assert l... | 5,342,773 |
def backup_file_content(jwd, filepath, content):
"""backs up a string in the .jak folder.
TODO Needs test
"""
backup_filepath = create_backup_filepath(jwd=jwd, filepath=filepath)
return create_or_overwrite_file(filepath=backup_filepath, content=content) | 5,342,774 |
async def security_rule_get(
hub, ctx, security_rule, security_group, resource_group, **kwargs
):
"""
.. versionadded:: 1.0.0
Get a security rule within a specified network security group.
:param name: The name of the security rule to query.
:param security_group: The network security group c... | 5,342,775 |
def create_centroid_pos(Direction, Spacing, Size, position):
# dim0, dim1,dim2, label):
"""
:param Direction,Spacing, Size: from sitk raw.GetDirection(),GetSpacing(),GetSize()
:param position:[24,3]
:return:
"""
direction = np.round(list(Direction))
direc0 = direction[0:7:3]
direc1... | 5,342,776 |
def group_split_data_cv(df, cv=5, split=0):
"""
Args:
cv: number of cv folds
split: index of the cv fold to return
Note that GroupKFold is not random
"""
from sklearn.model_selection import GroupKFold
splitter = GroupKFold(n_splits=cv)
split_generator = splitter.split(df, gro... | 5,342,777 |
def encode(valeur,base):
""" int*int -->String
hyp valeur >=0
hypothèse : base maxi = 16
"""
chaine=""
if valeur>255 or valeur<0 :
return ""
for n in range (1,9) :
calcul = valeur % base
if (calcul)>9:
if calcul==10:
bit='A'
if... | 5,342,778 |
def main(request):
"""
Main admin page.
Displayes a paginated list of files configured source directory (sorted by
most recently modified) to be previewed, published, or prepared for
preview/publish.
"""
# get sorted archive list for this user
try:
archives = request.user.archiv... | 5,342,779 |
def parse_char(char, invert=False):
"""Return symbols depending on the binary input
Keyword arguments:
char -- binary integer streamed into the function
invert -- boolean to invert returned symbols
"""
if invert == False:
if char == 0:
return '.'
elif char == 1... | 5,342,780 |
def test_entities(
reference_data: np.ndarray,
upper_bound: np.ndarray,
lower_bound: np.ndarray,
ishan: Entity,
) -> None:
"""Test that the n_entities works for SEPTs"""
tensor = SEPT(
child=reference_data, max_vals=upper_bound, min_vals=lower_bound, entity=ishan
)
assert isinsta... | 5,342,781 |
def remote_connect(rname, rhost):
"""供master调用的接口:进行远程的rpc连接
"""
GlobalObject().remote_connect(rname, rhost) | 5,342,782 |
def run_blast(database, program, filestore, file_uuid, sequence, options):
"""
Perform a BLAST search on the given database using the given query
Args:
database: The database to search (full path).
program: The program to use (e.g. BLASTN, TBLASTN, BLASTX).
filestore: The director... | 5,342,783 |
def get_transformer_dim(transformer_name='affine'):
""" Returns the size of parametrization for a given transformer """
lookup = {'affine': 6,
'affinediffeo': 6,
'homografy': 9,
'CPAB': load_basis()['d'],
'TPS': 32
}
assert (transformer_na... | 5,342,784 |
def ListVfses(client_urns):
"""Lists all known paths for a list of clients.
Args:
client_urns: A list of `ClientURN` instances.
Returns:
A list of `RDFURN` instances corresponding to VFS paths of given clients.
"""
vfs = set()
cur = set()
for client_urn in client_urns:
cur.update([
... | 5,342,785 |
def test_create_one_dimensional():
"""Tessellate a (finite) line."""
tes_one = pqca.tessellation.one_dimensional(10, 2)
assert str(
tes_one) == "Tessellation(10 qubits as 5 cells, first cell: [0, 1])" | 5,342,786 |
def delete_product(productId):
"""Deletes product"""
response = product2.delete_product(productId)
return response | 5,342,787 |
def compute_face_normals(points, trilist):
"""
Compute per-face normals of the vertices given a list of
faces.
Parameters
----------
points : (N, 3) float32/float64 ndarray
The list of points to compute normals for.
trilist : (M, 3) int16/int32/int64 ndarray
The list of face... | 5,342,788 |
def get_deletion_confirmation(poll):
"""Get the confirmation keyboard for poll deletion."""
delete_payload = f"{CallbackType.delete.value}:{poll.id}:0"
delete_all_payload = f"{CallbackType.delete_poll_with_messages.value}:{poll.id}:0"
locale = poll.user.locale
buttons = [
[
Inlin... | 5,342,789 |
def ngram_tokenizer(lines, ngram_len=DEFAULT_NGRAM_LEN, template=False):
"""
Return an iterable of ngram Tokens of ngram length `ngram_len` computed from
the `lines` iterable of UNICODE strings. Treat the `lines` strings as
templated if `template` is True.
"""
if not lines:
return
n... | 5,342,790 |
def list_datasets(service, project_id):
"""Lists BigQuery datasets.
Args:
service: BigQuery service object that is authenticated. Example: service = build('bigquery','v2', http=http)
project_id: string, Name of Google project
Returns:
List containing dataset names
"""
data... | 5,342,791 |
def tors(universe, seg, i):
"""Calculation of nucleic backbone dihedral angles.
The dihedral angles are alpha, beta, gamma, delta, epsilon, zeta, chi.
The dihedral is computed based on position of atoms for resid `i`.
Parameters
----------
universe : Universe
:class:`~MDAnalysis.core... | 5,342,792 |
def get_metric(metric,midi_notes,Fe,nfft,nz=1e4,eps=10,**kwargs):
"""
returns the optimal transport loss matrix from a list of midi notes (interger indexes)
"""
nbnotes=len(midi_notes)
res=np.zeros((nfft/2,nbnotes))
f=np.fft.fftfreq(nfft,1.0/Fe)[:nfft/2]
f_note=[2.0**((n-60)*1./12)*440 for n... | 5,342,793 |
def octave(track, note, dur):
"""Generate the couple of blanche"""
track.append(Message('note_on', note=note, velocity=100, time=0))
track.append(Message('note_on', note=note + 12, velocity=100, time=0))
track.append(Message('note_off', note=note, velocity=64, time=dur))
track.append(Message('note_o... | 5,342,794 |
def test_hist_2d_against_matlab():
"""
Testing for 2d sample_vec as that's the one only needed in kde2d
reference solution: kde2d.m function binned_sample=hist_2d(sample_vec,M)
"""
x = [0.11, 0.21, 0.31, 0.31, 0.21]
y = [0.61, 0.31, 0.91, 0.91, 0.31]
sample = np.vstack((x, y)).T
m = 5
... | 5,342,795 |
def solveTrajectoryPickle(dir_path, file_name, only_plot=False, solver='original', **kwargs):
""" Rerun the trajectory solver on the given trajectory pickle file. """
# Load the pickles trajectory
traj_p = loadPickle(dir_path, file_name)
# Run the PyLIG trajectory solver
if solver == 'original':
... | 5,342,796 |
def check_arguments(funcdef, args, kw):
"""Check if some arguments are missing"""
assert len(args) == 0
for arg in funcdef.arguments:
if arg.mandatory and arg.name not in kw:
raise MissingArgument(arg.name) | 5,342,797 |
def test_date(date_string):
"""Test date string
:param str date_string: Date string
"""
try:
datetime.strptime(date_string, '%Y-%m-%d')
except ValueError:
raise ValueError("Incorrect date format, should be YYYY-MM-DD")
exit(1) | 5,342,798 |
def load_data(path):
"""
读取.mat的原始eeg数据
:param path:
:return:
"""
data=scio.loadmat(path)
labels = data['categoryLabels'].transpose(1, 0)
X = data['X_3D'].transpose(2, 1, 0)
return X,labels | 5,342,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.