content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def add_variable_declarations(message: str, code_snippets: list) -> list:
""" Add variable declarations to the beginning of code snippets. """
spec_fields = set()
for fields in mds.get_msg_fields(message):
name, size = fields[0], int(fields[1])
if not 0 < size <= 64:
spec_fields.... | a54b94236f01b7c7e3347b83307de6d94dfbdb8e | 3,594,882 |
def get_training_status(trials, task_protocol, ephys_sess_dates, n_delay):
"""
Compute training status of a subject from three consecutive training datasets
:param trials: dict containing trials objects from three consective training sessions
:type trials: Bunch
:param task_protocol: task protocol ... | 69a4f43899ec6cc1ad2063fe445ae376c8a5333f | 3,594,883 |
from datetime import datetime
def cast_date(value, connection):
"""Cast a date value."""
# The output format depends on the server setting DateStyle. The default
# setting ISO and the setting for German are actually unambiguous. The
# order of days and months in the other two settings is however amb... | 2e0558a45459099337584ea0156d37a996f2b546 | 3,594,884 |
def setup_axes():
"""
Sets up the 3x3 axis grid with the proper axis labels and ranges
Returns
=======
axes :: list
The axes, indexable via axes[row number][column number]
"""
axes = visuals.subplots(3, 3, figsize = (21, 21))
for i in range(3):
axes[i][0].xaxis.set_ticks([0, 2, 4, 6, 8, 10])
axe... | 4e80a1eb70fbccee196efdb422ef562f05c658d2 | 3,594,885 |
def laser_levels(video):
"""
Computes the levels for a single laser video.
:param video: Video to compute the levels
:return: A unique set of levels with limits.
"""
return np.unique(np.asarray([[0, 1023], [0, video.max()], [video.min(), video.max()]]), axis=0) | 5d6af0b2c1e98ab7bf13b7b5957d7a5839551ef0 | 3,594,886 |
def any(condition) -> BooleanExpression:
"""Returns ``True`` if `condition` is ``True`` for any record.
Examples
--------
>>> (table1.group_by(table1.SEX)
... .aggregate(any_over_70 = hl.agg.any(table1.HT > 70))
... .show())
+-----+-------------+
| SEX | any_over_70 |
+-----+------... | 61533a4e79dfff0e4472e345db7b7adb2dd4cd11 | 3,594,887 |
def promote_testimonial():
"""Send a 'promoted' testimonial notification (to KA's main slack channel).
This webhook is hit by the main KA webapp when it notices that a
testimonial has received a certain number of upvotes in the #testimonials
channel.
"""
testimonial = testimonials.Testimonial.p... | 6835b0ef1368b64e6bde1912af41b20820bd6c45 | 3,594,888 |
def best_scoring_const_region_hits(frame):
""" Returns dataframe subset to the max scoring row
for each SEQUENCE_ID
"""
return frame.loc[frame.groupby('SEQUENCE_ID').C_SCORE.idxmax()] | 1ec94e9befd83ff9dbf48caff7ae65b217887484 | 3,594,889 |
def get_stack_output_value(stack, key: str) -> str:
"""
Get a stack output value
:param stack: the boto3 stack resource
:param key: the output key
:return: str
"""
results = [i for i in stack.outputs if i["OutputKey"] == key]
if not results:
raise ValueError(f"could not find outp... | 0742a2b8558b7aa4ea1656a6645a9b3e5fbdb17a | 3,594,890 |
def get_tpr_fpr(truth, pred):
"""
Returns the Sensitivity (True Positive Rate) and the Specificity (False Positive Rate) for two
numpy arrays: a `pred` and a `truth`.
"""
if not pred.shape == truth.shape :
raise IndexError("The prediction and the truth arrays must have the same dimensions")
n_true = np.wher... | 8c9c71155f3ea237e778e122907f11c0afb43a27 | 3,594,891 |
from abstract_open_traffic_generator.config import Config
from abstract_open_traffic_generator.flow import Flow, TxRx, DeviceTxRx, \
def b2b_ipv4_flow_config(options, tx_port, rx_port, b2b_ipv4_devices):
"""Returns a configuration with an ipv4 flow.
The flow uses a DeviceTxRx endpoint.
"""
Size, R... | c98b7f8062952fe3901ab92c42801dec8395712d | 3,594,892 |
def LeastSquare_general(Xs, Y, weights=None):
"""Computes a linear fit using the least square method. The 'Xs' is a list of numpy arrays of same size as 'Y' which give each of the X-parameters of the fit. Each such parameter will have a regresion coefficient 'a' and its error that will be computed by this function.... | 577a36eca0095a546ecd85baf9a1de4dcd02e6a5 | 3,594,893 |
def add_markings(obj, marking):
"""
Append an object level marking to the object_marking_refs collection.
Args:
obj: A SDO or SRO object.
marking: identifier or list of identifiers to apply SDO or SRO object.
Returns:
A new version of the given SDO or SRO with specified marking... | 1a8abbb105c6b2d1d0d64daec51fca70e150e14d | 3,594,894 |
from typing import Callable
async def http_error_handler(req: Request, handler: Callable) -> Response:
"""Middleware for handling exceptions received from the API methods.
:param req: A request instance
:param handler: A request handler
:raises: Reformatted HTTP Exceptions
:returns: Successful re... | 51a23728b6c7289be830fc1aa6c1587634ca0094 | 3,594,895 |
from typing import Optional
def get_order_cart_product_options_plan(cart_id: Optional[str] = None,
catalog_name: Optional[str] = None,
options_plan_code: Optional[str] = None,
plan_code: Optional[st... | af95a79c671003e9c402459e6553c75319b8eb46 | 3,594,896 |
def get_feature_map_spatial_dims(feature_maps):
"""Return list of spatial dimensions for each feature map in a list.
Args:
feature_maps: a list of tensors where the ith tensor has shape
[batch, height_i, width_i, depth_i].
Returns:
a list of pairs (height, width) for each feature map... | e95a55268b891734476b33c14b884291cb760323 | 3,594,898 |
def convert_graph(G, Gprime=nx.DiGraph()):
"""
convert a multigraph to another graph type
args:
:G (nx.Graph child) - graph to collapse edges
:Gprime (nx.Graph child) - graph to populate; defaults to digraph
returns:
:the newly converted graph
"""
Gprime.add_edges_fro... | 571ae33ef2c4b4ce29d05dff7db018bb1c6b4c5e | 3,594,899 |
def merge_multilevel(data, mode = "full"):
"""Merges multilevel data (data as returned by the :func:`multilevel` function)
Parameters
----------
data : ndarray
data as returned by :func:`multilevel`
mode : str, optional
Either 'full' or 'half'. Defines how data from the zero-th... | 48628b25d7d3c3994927adffa577d1dd383e7bc5 | 3,594,900 |
import types
import hashlib
import base64
def _generate_public_key(*, sub: types.TSub) -> types.TPublicKey:
"""Generate the public key."""
sha256 = hashlib.sha256()
sha256.update(sub.encode())
random_token = _generate_salt()
sha256.update(random_token)
raw_public_key = sha256.digest()
b6... | 4c48b5a100b6418cbd713952758dc0db7773b562 | 3,594,901 |
def get_container(context, pool, log=None):
"""Retrun a DAOS a container that has been created an opened.
Args:
context (DaosContext): the context to use to create the container
pool (DaosPool): pool in which to create the container
log (DaosLog|None): object for logging messages
R... | e8ad47b3d63c85eb679bbc734f8b07a5983ed0f3 | 3,594,902 |
from typing import Union
from datetime import datetime
def search_manifactured_date(header: list) -> Union[datetime.datetime, None]:
"""Grep manifactured date from illumina header
Args:
header (list): affymetrix header section
Returns:
datetime.datetime: a datetime object
"""
rec... | c495b7dbcbc9c37bc93fb8a0d6793bee2dfd66a4 | 3,594,903 |
def check_TCP_Nmap_match(pkt, nfq_packet, INPUT_TCP_OPTIONS, EXPECTED_TCP_flags, IP_flags="no", urgt_ptr=0):
"""
Check if the packet is a Nmap probe
IPflags and urgt_ptr are optional
return 1 if packet is a Nmap probe
"""
# print pkt[TCP]
if pkt[TCP].window == EXPECTED_TCP_flags['WSZ'] and p... | dadc588ad0d43e72e8e6e0fa9085598550fc0a68 | 3,594,904 |
import hashlib
def make_key(key):
"""
Returns SHA256 key
:param key:
:return:
"""
h = hashlib.sha256()
h.update(key)
return h.digest() | c3833de2e4e8c289004a7a72039a7c7a3161659d | 3,594,905 |
def _skip_class_name(name):
"""Determine if the class name should be skipped."""
return name == "Bundled" or name.startswith("_") | 7cc942d327784da2ae1aefc99859e52b3696475b | 3,594,906 |
import json
def ajax_get_link_audit_code(request):
"""
Generate a token, and record that token with email in cache, expires in
one hour, send token to that email address.
User provide token and email at share link page, if the token and email
are valid, record that email in session.
"""
c... | 2a95ff9d97ad33c681ed2697c212baffed4d5a82 | 3,594,907 |
def test_abstract_base_class_complete():
"""
Test the abstract base class.
"""
class TestProvider(BaseProvider):
def __init__(self, application=None):
super().__init__(application)
def mark_essential(self):
return
def mark_enrolled(self):
re... | 12374d7ef8c2683520fd919693191d787e02fb1b | 3,594,908 |
def valid_ipv4(address: str):
"""
:param address: ip address string
:return: if the address is a valid dotted ipv4 address
"""
try:
inet_pton(AF_INET, address)
except AttributeError:
try:
inet_aton(address)
except error:
return False
return... | e812c109813a36fea97231f0a9d5ceb806bd2310 | 3,594,909 |
def merge(env, current_env):
"""Merge the tools environment with the 'current_env'.
This finalizes the join with a current environment by formatting the
remainder of dynamic variables with that from the current environment.
Remaining missing variables result in an empty value.
Args:
env (... | 85646372a3ea8bf56632607b3639e51839b69943 | 3,594,910 |
def get_sql_sms_pillow(pillow_id='SqlSMSPillow', num_processes=1, process_num=0,
processor_chunk_size=DEFAULT_PROCESSOR_CHUNK_SIZE, **kwargs):
"""SMS Pillow
Processors:
- :py:class:`pillowtop.processors.elastic.BulkElasticProcessor`
"""
assert pillow_id == 'SqlSMSPillow', '... | 0ddb6e53097efd6b86015359d591cb7490ba59f1 | 3,594,911 |
def AO_to_Cfour_SO(C_AO_pi, wfn, map_p2c, scale):
"""
transforms n_irrep blocks of Psi4-MOs from the Psi4-AO to the
Cfour-SO representation
Parameters
----------
C_AO_pi : psi4.core.Matrix C[AO:MO[irrep]]
wfn : psi4.core.wavefunction (tested for RHF)
map_p2c: np.array[AO]
scale:np.... | ce1d4951f1a04b993f9599f671f4b6e3a6282585 | 3,594,912 |
from typing import List
from typing import Dict
import torch
def lookup_alignments(
cut_ids: List[str],
alignments: Dict[str, torch.Tensor],
num_classes: int,
log_score: float = -10,
) -> torch.Tensor:
"""Return a mask constructed from alignments by a list of cut IDs.
The returned mask is a 3... | 3822bd9d9af55225af0e10d5f4c3c18e6bce6235 | 3,594,914 |
from functools import cmp_to_key
def zorder_fragments(fragments):
"""Order the fragments in appropriate z curve order
Args:
fragments: Fragments
Returns:
fragments: Z-curve sorted fragments
"""
fragments, _ = zip(
*sorted(zip(fragments, [fragment.position for fragment in... | 21c177022c5a7a83060dca9a5f79eecf9eaf98df | 3,594,915 |
def pack(data):
"""pack bytes for sending to client"""
frame_head = bytearray(2)
# set final fragment
frame_head[0] = set_bit(frame_head[0], 7)
# set opcode 1 = text
frame_head[0] = set_bit(frame_head[0], 0)
# payload length
assert len(data) < 126, "haven't implemented that yet"
fram... | d0ea8c0dc5523a0b940c6548fdb07005d23bc68c | 3,594,916 |
import urllib
def getContent(url):
""" Takes the url and returns the response from urlopen
Having a separate function avoids checking for exceptions all
throughout the code.
Parameters
----------
url : string
Returns
-------
resp : HTTPResponse object
"""
req = urllib.re... | d6ffb105b1b7009a090cb204f1cdf1534de87514 | 3,594,917 |
def execute():
"""
RMAP Protocol Benchmarking
"""
# Target and method
host = raw_input('Hostname or IP address: ')
method = -1
while method not in (1, 2):
method = input('Access method (1: SpW 2: RMAP): ')
# Initialize SpaceWire I/F and RMAP Engine
spwif = SpaceWire.Interface(host)
rmap = RMAP.Engine(s... | 8e97b447b1734383569021950da09fb2abffaf2a | 3,594,918 |
def list_inputs(locales):
"""Returns the names of files that will be processed for the given locales.
This is to provide gyp the list of input files, so build targets can properly
track their prerequisites.
"""
inputs = []
for locale in locales:
inputs += calc_inputs(locale)
# Quote each element so f... | 4c166caf03933f00c53d02a07b57532665c47aaa | 3,594,919 |
def read_image(path: str) -> np.ndarray:
"""Load an image from file using cv2.
Args:
path: path to an image. JPEG format works, other formats probably work too.
Returns:
Shape is (H, W, 3). Each element is a uint8 in [0, 255].
Raises:
ValueError:
* If path does not re... | 1686493ece8e74e2d52aa40a8cdd6650c755d235 | 3,594,920 |
def insert_row(df, data):
"""Insert data as new row at top of df.
Keyword arguments:
df -- a Pandas dataframe.
data -- a list of data to insert.
"""
# If data length is less then number columns, insert blanks.
num_blanks = len(df.columns.values)-len(data)
for i in range(num_blanks):
data.extend([''])
df.loc... | 7f32eeb5e5a07790adc48bc7dcdabbb9ba409972 | 3,594,921 |
def get_dependents_of_id(idx, df=False, repeat=False, attr=False, coref=False):
"""
Get dependents of a token
"""
sent_id, tok_id = getattr(idx, 'name', idx)
deps = df.ix[sent_id, tok_id]['d'].split(',')
out = []
for govid in deps:
if attr:
# might not exist...
... | 0f87bb385e594a96ebc35e5bd1d1113dd84f94a1 | 3,594,922 |
def _ignore_value_tensor(dtype, ignore_value=None):
"""Create `Tensor` from provided `ignore_value` and `dtype`."""
if ignore_value is None:
if dtype == dtypes.string:
# Exception due to TF strings are converted to numpy objects by default.
ignore_value = ""
else:
# NOTE: `as_numpy_dtype`... | 59e285b04d581e1c468d70763e715e0a8f9c8b3b | 3,594,923 |
from typing import List
from typing import Optional
def _read_files_then_shard(matched_files: List[str],
dataset_fn,
input_context: Optional[
tf.distribute.InputContext] = None,
sharding: bool = False,
... | 7b05f4e1e46a69a68ca4ffb3a12a9065e5722fb7 | 3,594,924 |
def thresh_salient(img, thresh_limit=60):
""" Threshold using blue channel """
b, g, r = cv2.split(img)
mask = get_salient(b)
mask = cv2.threshold(mask, thresh_limit, 255, cv2.THRESH_BINARY)[1]
return mask | aca034dd860d556665f90e87191739427f0b5c37 | 3,594,925 |
def change_backend_to_sqla(profile=None):
"""
Gets the main AiiDA configuration and searches if there is a backend
defined. If there isn't any then Django is added.
"""
# Get the available configuration
conf = setup.get_config() # Profile key
_profiles_key = "profiles"
# Identifying a... | 2669e6b167f6112b1c2f7b93ed1078f4a88e66d6 | 3,594,926 |
def defineEdgeTable(D_nodes: pd.DataFrame, D_IO: pd.DataFrame) -> pd.DataFrame:
"""
Define a dataframe containing the arcs of the warehouse graph
Args:
D_nodes (pd.DataFrame): Input DataFrame with nodes.
D_IO (pd.DataFrame): Input DataFrame with i/o points.
Returns:
edgeTable (... | e98359e20f4aea59d70e420fef2eb3a2259f4e61 | 3,594,927 |
def bootstrap(new, demeaned_resid, y_pred, n, category_col, demean_df, consist_col, formula, index_name, i):
"""
:param new: dataframe with continuous variables and dependent variable
:param demeaned_resid: dataframe of residuals obtained from model on demeaned dataframe
:param y_pred: dataframe of the... | b6a4adb57c0d482fc53b9114da64c26027aaa9ec | 3,594,928 |
def query_latest_machine_report(cid):
"""
Get machine report (from factor etc.) by CID
:param cid: CID, string
:return:
"""
c3username = configuration.config['C3']['UserName']
c3apikey = configuration.config['C3']['APIKey']
c3url = configuration.config['C3']['URI']
report_api = conf... | f88721cf59e1c07df9c83b5d3986280fcaeedcdb | 3,594,929 |
def send_like(self, user_ids, thread_id=None):
"""
:param self: bot
:param user_ids: list of user_ids for creating group or
one user_id for send to one person
:param thread_id: thread_id
"""
user_ids = _get_user_ids(self, user_ids)
if not isinstance(user_ids, (list, str)):
self.l... | 7259aaf2fb68db8f8233b0af64cf95a33f23967a | 3,594,930 |
import platform
import json
def get_disk_usage(
directory, summarize=False, search=None, to_human_readable_units=None
):
"""Retrieve directory disk usage information.
:param directory: Disk usage directory.
:param summarize: Displays a total size of a directory.
:param search: Filter parameters t... | cc28fb7db76025158f6ad11af04478d7234f5665 | 3,594,931 |
from compass.db.api import host as host_api
from compass.tasks import client as celery_client
def deploy_cluster(
cluster_id, deploy={}, user=None, session=None, **kwargs
):
"""deploy cluster.
Args:
cluster_id: cluster id.
deploy: dict contains key either hosts or clusterhosts.
... | 4b09e1c8d799b0b7c569cba95ccb9fdfb6bb9539 | 3,594,932 |
import math
def st_asin(x):
"""Inverse sine function.
Parameters
----------
x : float, int, MissingValue instance, or None
Returns
-------
Inverse sine (measured in radians) when -1 <= x <= 1,
MISSING (".") otherwise
"""
if isinstance(x, StataVarVals):
re... | 085918d1386b014c9c503628163f1f44ea4acd28 | 3,594,933 |
def get_longest_parent(task):
"""
Returns the parent of the given task which has the longest execution time
Args:
task (Node)
Returns:
Node
"""
longest_parent = task.get_parents()[0]
for parent in task.get_parents():
if longest_parent.get_exec_time() < parent.get_e... | 8e41984c1e287f8a2d457150d332f868660c4eef | 3,594,934 |
from typing import Optional
from typing import Sequence
from typing import Mapping
def get_managed_prefix_list(filters: Optional[Sequence[pulumi.InputType['GetManagedPrefixListFilterArgs']]] = None,
id: Optional[str] = None,
name: Optional[str] = None,
... | af16be9da268c16e558dcbe07f77c164c29fc4c0 | 3,594,935 |
from typing import Dict
from typing import Any
def heater_shaker_module_use_stdin(
heater_shaker_module_default: Dict[str, Any]
) -> Dict[str, Any]:
"""Heater-shaker dictionary with mode set to stdin."""
heater_shaker_module_default["hardware_specific_attributes"] = {
"mode": HeaterShakerModes.STD... | 9b3931f71281537c584dd7fc0af71d8e5339ff68 | 3,594,936 |
def meta_model(row):
"""
Inputs the metamodel AND operator as condition
Retrieves the tamper value of the UL model only when both models agree in classifying
as non tampered. Otherwise retrieves the SL classification
UL classifier has a higher TPR but lower TNR, meaning it is less restrictive toward... | 9c8804840fdf39075716d01808275fafafa7941d | 3,594,937 |
def hooddisplay(request):
"""
View function that displays all listed neighbourhoods
"""
hoods = Hood.objects.all()
return render(request, 'all/displayhood.html', {"hoods": hoods}) | e4b50040ac7ea7fa9daca740133c52f1f208dfa4 | 3,594,938 |
def rmsPoint(rays,point,weights=None):
"""
Compute the RMS of rays about a point
"""
if np.size(point) == 10:
rho = (rays[1]-point[1])**2 + \
(rays[2]-point[2])**2 + \
(rays[3]-point[3])**2
else:
rho = (rays[1]-point[0])**2 + \
(rays[2]-point... | 0225efed09c84640b944c63f648d8e667f5cec22 | 3,594,940 |
def get_callnumber(record):
"""Follows CC's practice, you may have different priority order
for your call number."""
callnumber = ''
# First check to see if there is a sudoc number
if record['086']:
callnumber = record['086'].value()
# Next check to see if there is a local call number
... | bf5226c2d39c7913f1701f245f48e4ab5f2b1d15 | 3,594,941 |
def LinearTimeScaling(Tf, t):
"""
Computes s(t) for a quintic time scaling
"""
return t/Tf | 305e09f20f391f1643e6cecaeb84ad7c7e66fea9 | 3,594,942 |
def gen_mapping(args, service, weight=None, labels={}):
"""
Generate a Mapping for a service/prefix and (optional) weight
"""
prefix = args.prefix
mapping = {
"apiVersion": "getambassador.io/v1",
"kind": "Mapping",
"metadata": {
"name": f"mapping-for-{service}"
... | 167d044cffed74d5d04498e4941a147395977602 | 3,594,943 |
def GFBasicData(path):
"""
Reads Rachel's SAMs output data.
If AB = True then the function converts
Johnson U, B, V, and K bands to Vega system.
:note: This is really ineffective way of reading in
data and should be used only when a rather
small simulation is being processed.
... | 32b9243d9c8cb8f6a56155b502271357162c40f3 | 3,594,944 |
def use_loss_func(loss_func=bce_loss):
"""
Decorator function that makes a native Keras / Tensorflow function
compatible with the pca_tests function
"""
def calcloss(original, latent, decoder):
return loss_func(original, decoder.predict(latent)).numpy()
return calcloss | 1043ae0b7183603ba4339b7abbcd1b696ce007c8 | 3,594,945 |
from bs4 import BeautifulSoup
import re
def parse_feed_item(feed_item):
"""
Takes a dict representing a feed item for today and generates
a strucutred dict from it:
{
"text": The plain text of this entry,
"links": List of all links in this entry, which do not
... | 8e702b587f94874d0df9cc9320168fd78c345820 | 3,594,946 |
def findfwhm(model, sig_x):
""" Calculate the spatial FWHM from an object profile. Utitlit routine for fit_profile
Parameters
----------
model : numpy float 2-d array [nspec, nspat]
x :
Returns
-------
peak : Peak value of the profile model
peak_x: sig_x location where the peak... | 771929150fcdfcde0eb874804acf82eefaee36ea | 3,594,947 |
import tensorflow as tf
import torch
from autograd import numpy as np
import numpy as np
def _get_dot_func(interface, x=None):
"""Helper function for :func:`~.dot` to determine
the correct dot product function depending on the QNodeCollection
interface.
Args:
interface (str): the interface to... | 5be13fe85f8f756c8abb4bb69dcd7c7b5b44b231 | 3,594,948 |
from typing import Union
from typing import Type
from typing import Any
import builtins
def issubdtype(
arg1: Union[str, Type[datatype], Any], arg2: Union[str, Type[datatype], Any]
) -> builtins.bool:
"""
Returns True if first argument is a typecode lower/equal in type hierarchy.
Parameters
-----... | 8a49053fc8ae2bf9fd25d8c06a1b8455f373f3f4 | 3,594,949 |
def null_to_p(test_value, null_array, tail="two", symmetric=False):
"""Return p-value for test value(s) against null array.
.. versionchanged:: 0.0.7
* [FIX] Add parameter *symmetric*.
Parameters
----------
test_value : 1D array_like
Values for which to determine p-value.
null... | 881a84858e37c18559b682c759ddcdc770966cd1 | 3,594,950 |
def null():
"""Get Null"""
return write_tv(ASN1_NULL, b'') | 5f7aefa17b09a9342e15f86348eb3d9bfc2033cf | 3,594,951 |
from typing import Any
def fill_not_finite(array: np.ndarray, value: Any = 0) -> np.ndarray:
"""
Return a copy of array with nans and infs replaced with a given value.
Parameters
----------
array : np.ndarray
Input array.
value : Any, optional
Value to replace nans and infs wi... | 134b1dd6d3bdd4fdac5792bb47b4203918218731 | 3,594,952 |
def _make_empty_seq_output(
shape: Shape,
dtype: tf.dtypes.DType,
) -> tf.Tensor:
"""Return an empty (0, *shape) `tf.Tensor` with `0` instead of `None`."""
if not isinstance(shape, (tuple, list)) or None not in shape:
raise ValueError(f'Could not construct empty output for shape: {shape}')
return tf.c... | 988e072dc979ccee925e37046569085da4725c4b | 3,594,954 |
def compute_answer_part_two(cups: deque[int]) -> int:
"""Compute the answer of the part two
:param cups: list of digits
:return: part one answer
"""
while cups[0] != 1:
cups.rotate(-1)
following_cups = list(cups)[1:3]
answer = int(following_cups[0]) * int(following_cups[1])
retu... | 676cd03b278832ce0c2a008ecf6198396fecd05e | 3,594,955 |
def polyhedron_extrude_from_concave_vertices(cap_vertices, extrude_direction):
# type: (list[Point], Vector) -> Mesh
""" Creates an polygon-extrude-like-box.
The algorithm will call conforming_delaunay_triangulation to patch polygons with concave polygons.
Note that the ordering of the given vertices ar... | d55cbc49ded20949814e4238c4d9a8f85a975a00 | 3,594,956 |
def index():
"""
Route for mainpage. Create pagination for rounds played by user
"""
page = request.args.get('page', 1, type=int)
rounds = current_user.get_rounds().paginate(page,5,False)
next_url = url_for('index', page=rounds.next_num) \
if rounds.has_next else None
prev_url = url... | 5f85eea859a5678520d489a2df325403d314cd73 | 3,594,958 |
def update_project():
"""
update project
"""
data = loads(request.data)
file_path = manage(YML_PATH + '/' + data["name"], data["yml"], True)
if 'env' in data and data["env"]:
env_file = open(YML_PATH + '/' + data["name"] + "/.env", "w")
env_file.write(data["env"])
env_f... | 205203e74b3c706c13cf61e77895ce655fa1ab50 | 3,594,959 |
def generate_table(low_mass_model = 'heger_woosley_2010',
pisne_model = 'heger_woosley_2002'):
"""
Combine yield tables together
"""
if low_mass_model == 'heger_woosley_2010':
low_mass_yields, low_mass_masses = generate_heger_woosley_2010()
elif low_mass_model == 'nomo... | 438c8b181981384469e8ec6031a0ab31c17cc6c2 | 3,594,960 |
def spatial_binning(info_dict):
""" Compute the spatial binning representing the number of pixels affected by the light in the spatial direction
Parameters
----------
info_dict: dictionnary
wavelength: float
wavelength in angstrom
Returns
----------
spabin: float
... | a6af35e8e7afabc6dea2aa89937aecd096f265c2 | 3,594,961 |
def as_usize(num):
"""Cast number to usize."""
return ffi.cast("unsigned long", num) | 068420a74675658d9511acb4f22074bc8ee43d86 | 3,594,962 |
import _uuid
def create_uuid(create: bool = True) -> str:
"""
:param create: is a bool to make creation of the uuid optional
and use 577000099446A instead
:return: a uuid
Description
----
This method creates a pseudo uuid. this helps to identify objects
Params
----
"""
... | 11d3e5beb55db7f0cb29ce1f6881d7e1c4848482 | 3,594,963 |
def onboarding_pipeline_patterns_post(pipeline_pattern): # noqa: E501
"""Create a new pipeline pattern
# noqa: E501
:param pipeline_pattern: Pipeline detail description
:type pipeline_pattern: dict | bytes
:rtype: PipelinePattern
"""
if connexion.request.is_json:
pipeline_patter... | 39f83502d11f3fef9964b17fc1362fc970142a90 | 3,594,964 |
def keep_alpha_numeric(input_text: str) -> str:
""" Remove any character except alphanumeric characters """
return ''.join(c for c in input_text if c.isalnum()) | 6775d7ba72ae06c294acde9bc2964ae51a954ce3 | 3,594,965 |
import sklearn.linear_model as lm
def linear_classifier_discrimination(model, data, C_range=[1], verbose=True, samples=None):
"""
Compute the logistic regression classification accuracy.
"""
n_examples = data.shape[0]
if samples is None:
gnp.seed_rand(8)
samples = model.generate_sa... | 5e0b69875c3bacc0c0bdab42ea42d32b45061494 | 3,594,966 |
def rejection_sample_2d(kernel, k_max, samples=1, oversample=2):
"""A simple two-dimensional rejection sampler. The kernel is assumed to be
defined on [0,1] times [0,1].
:param kernel: A callable object giving the kernel. Should be able to
accept an array of shape (2, #points) and return an array o... | 8753393acf96646d5e0d05ee22e5b355fbd0f183 | 3,594,968 |
async def randomise(items):
""" For .random command, get a random item from the list of items. """
itemo = (items.text[8:]).split()
if len(itemo) < 2:
return await items.edit(
"`2 item atau lebih diperlukan! Periksa .help random untuk info lebih lanjut.`"
)
index = randint(1,... | 399da2b76cc667e4d59c6d8dac50c37afed38d07 | 3,594,970 |
def reunion(set1, set2):
"""Given the two sets, returns their reunion."""
return set1 | set2 | 3e7af2a784d570d2a28c6665905242f5b6e812de | 3,594,971 |
def box_iou(bboxes1, bboxes2, box_format='xywh', do_ioa=False, do_giou=False):
""" Calculates the IOU (intersection over union) between two arrays of boxes.
Allows variable box formats ('xywh' and 'x0y0x1y1').
If do_ioa (intersection over area), then calculates the intersection over the area of boxes1 - thi... | 02c97adfb1f59bc4fb00ee95cea49211936041ae | 3,594,974 |
import json
import logging
def update_interface_ipv4(interface_name, ipv4, interface_admin_state, vrf, **kwargs):
"""
Perform GET and PUT calls to update an L3 interface's ipv4 address
:param interface_name: Alphanumeric name of the Port
:param ipv4: IPv4 address to associate with the VLAN Port
:... | 298fad468c9fcd6f4ec8a99b762a5167fba47561 | 3,594,975 |
def numberList(listItems):
"""Convert a string list into number
@param listItems (list) list of numbers
@return list of number list
"""
return [float(node) for node in listItems] | df50b5ce22f63c22cfa67051422cc4b13718cb57 | 3,594,976 |
def u3_replacement(theta: float, phi: float, lam: float):
""" implemented with a custom gate """
# implemented with two X90 pulse: https://arxiv.org/pdf/1707.03429.pdf
# p = Program()
# p += RZ(phi + 3*np.pi, 0)
# p += RX(np.pi/2, 0)
# p += RZ(np.pi + theta, 0)
# p += RX(np.pi/2, 0)
# p... | b73c7872659882a9dfb3c14eac837b6aa2681b56 | 3,594,977 |
def decodeRGB(input_queue, seq_length, size=96):
""" Args:
filename_and_label_tensor: A scalar string tensor.
Returns:
Three tensors: one with the decoded images, one with the corresponding labels and another with the image file locations
"""
images = []
labels = input_queue[1]
... | c7f24ef6accc40a76a4350ab25aca224f1b07785 | 3,594,978 |
import six
def _safe_write(function):
"""Avoid issues related to unicode strings handling."""
def _wrapper(message):
# Unicode strings are not properly handled by the serial module
if isinstance(message, six.text_type):
function(message.encode("utf-8"))
else:
fu... | b467c959e0833f8cb016b48fc031e0223fc2809e | 3,594,980 |
def evalResultGraph(graph, evalresult):
"""
This function combines the results from the evaluate function (above) to return
a single RDF result graph that is the result of the checklist evaluation service,
and also is returned when RDF output is requested by 'ro evaluate checklist'.
graph ... | 8aa8afe544c55928561462dffad63400d7e2d111 | 3,594,981 |
def ihu_optimize_rivlen(
idxs_short,
valid,
streams,
idxs_ds,
subidxs_out,
subidxs_ds,
subuparea,
subshape,
shape,
cellsize,
minlen=0,
minupa=0,
mv=_mv,
):
"""Reduces the number of cells with smaller than <minlen> downstream
subgrid length by finding an altern... | bf33422b31a001a9cd89d77fb1b315a4af4f1009 | 3,594,982 |
def results_ok(api, cfg, utils, size, packets):
"""
Returns true if stats are as expected, false otherwise.
"""
port_results, flow_results = utils.get_all_stats(api)
return packets == sum(
[p.frames_tx for p in port_results if p.name == "raw_tx"]
) | 618106436b0de5403f9f325c61fb2066a9493b31 | 3,594,983 |
def get_percent_values_by_range(bg_values, lower_threshold: int, upper_threshold: int, round_val=2):
"""
Calculate the percent of values that match has a bg within the lower and upper threshold.
The lower and upper values will be included in the range to calculate on.
Arguments:
bg_... | dc1626bc9d5448a9397a8e14fea9b3abb6dc47c5 | 3,594,985 |
def are_brackets_balanced(expr):
"""
Checks to see if there are parens or brackets that are unbalanced
"""
stack = []
# Traversing the Expression
for char in expr:
if char in ["(", "{", "["]:
# Push the element in the stack
stack.append(char)
e... | 3e548cb2999c404d6ed0587ef1a959767c11d479 | 3,594,986 |
def clean_rows(all_rows, original_rows):
"""
Remove duplicated values and remove original rows
"""
all_set = set(all_rows)
original_set = set(original_rows)
return all_set - original_set | 76de02aa72e8753481b58b4eddcabc4330a92e0b | 3,594,987 |
import re
def parse_phmmer_output(result_path):
"""
Read the fasta header of the sequence with highest homology
from a phmmer result file
returns: string
"""
with open(result_path, "r") as infile:
results_str = infile.read()
# Hacky regex solution to parsing results...
... | 4e7f40ff0f16316ee88096d8f3f4084706cef42b | 3,594,988 |
def transform(sequence):
"""
>>> sequence = [int(c) for c in "12345678"]
>>> transform(sequence)
[4, 8, 2, 2, 6, 1, 5, 8]
"""
return [abs(n)%10 for n in get_sum(sequence, 1)] | 80d53d028dc64b69da742424cca1761cce709621 | 3,594,989 |
import math
def prime_factors (number, use_cache = True):
"""Returns a list of all primes that are divisors of a given integer
number.
The list contains only prime numbers, whose product is equal to the original
number"""
if is_prime (number):
return [number]
if number in prime_factor... | 72af6a420911e0e2959b47ec2be4f65d5074c2e7 | 3,594,990 |
def merge_matching_indices(args):
"""
Takes a list of mapping indices, fills the graph matrix counting the number
of times a match happens in the mappings. Then start taking matching from
the most matched and iteratively adding new matching. If two conflicting
matching have the same number of counts... | 692f289cb23434beadeec0e12f6c319eae588ad5 | 3,594,991 |
def find_and_store_key(n, body):
"""
Looks through chord for node where key should be stored and stores it there
:param n: the node on which to call find_and_store_key
:param body: the request body
:return: string of response
"""
resp_header = {"status": STATUS_OK if n.find_and_store_key(bod... | 92f2887a23ae85e1f61b051b559ec3c76e11f2fb | 3,594,992 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.