content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def two_opt_with_cycle(orderedPoseListe):
"""
returns an optimised list from an orderedpose using the 2-opt algo with creating a Hamilton cycle
"""
improve = True #we iterate in the list as long as we find improvements
while improve == True:
improve = False
for i in range(len(ordered... | 3d303220fbcb6e9f9832a68ae0580f27247acc5c | 3,616,932 |
def html_to_spreadsheet_cell(html_element):
""" Parse HTML elmement, like <a href=www.google.com>Google</a> to =HYPERLINK(www.google.com, Google) """
link = html_element.find("a")
if link:
return '=HYPERLINK("{}", "{}")'.format(link['href'], link.contents[0])
else:
return html_element.te... | f0c797f59ed55d1ce6aab32ff8c40cf83577ee27 | 3,616,933 |
def get_bucket(bucket_name):
"""
Established a connection and gets s3 bucket
"""
if '.' in bucket_name:
s3 = boto.connect_s3(calling_format=OrdinaryCallingFormat())
else:
s3 = boto.connect_s3()
return s3.get_bucket(bucket_name) | 02cc01b9bf70864fdd3a0e80525e6d7a34536ab6 | 3,616,934 |
def _get_class(canonical_name: str):
"""
Gets a class by it's canonical name. Mind that this can only work with classes that does not require
any argument during instantiation.
:param canonical_name: the canonical name of the class to load dynamically, e.g. x.y.Module.Class
:returns: the instance ... | 289630cf65fcb915da4f4b49baa650d2e27e7a7c | 3,616,935 |
def build_tcp_flags() -> int:
"""
Assembles TCP flags.
"""
flags = 0
for flag in (
TCP_CWR, TCP_ECE, TCP_URG, TCP_ACK,
TCP_PSH, TCP_RST, TCP_SYN, TCP_FIN
):
flags <<= 1
flags |= flag
return flags | c4e04fc9c6201782c242636fc7aca284447ccb84 | 3,616,936 |
from typing import Tuple
def parseOptionWithArgs(plugin: str) -> Tuple[str, str]:
"""Parse the plugin name into name and parameter
@type plugin: str
@param plugin: The plugin argument
@returns tuple[str, str]: The plugin name and parameter
"""
if '=' in plugin:
plugin, param = plugin.... | 0e1f85f2e31349bf7ddcdc2d35b9ba815a61ec06 | 3,616,938 |
def spm_warp_to_mni(wf_name="spm_warp_to_mni"):
""" Run Gunzip and SPM Normalize12 to the list of files input and outputs the list of warped files.
It does:
- Warp each individual input image to the standard SPM template
Parameters
----------
wf_name: str
Name of the workflow.
Nip... | 5e497c7f34f6349b21807c30e169d7c26e1bc359 | 3,616,939 |
def build_insert_ddl(table_name: TableName, column_list, query_stmt) -> str:
"""Assemble the statement to insert data based on a query."""
columns = join_with_double_quotes(column_list, sep=",\n ")
insert_stmt = """
-- arthur.insert: {table.identifier}
INSERT INTO {table} (
... | 8feab467cb650052f772e5e54680432c06468d0a | 3,616,940 |
import functools
import warnings
def silent_nan_np(f):
"""Decorator that silences np errors and returns nan if undefined.
The np.nanmax and other numpy functions will log RuntimeErrors when the
input is only nan (e.g. All-NaN axis encountered). This decorator silences
these messages.
Args:
... | 25a861f4304dab03913995a992c0cd710d0e5c7c | 3,616,942 |
from typing import List
def evaluate_non_measured_estimation_tasks(
estimation_tasks: List[EstimationTask],
) -> List[ExpectationValues]:
"""This function evaluates a list of EstimationTask that are not
measured, and either contain only a constant term or require 0 shot.
Non-constant EstimationTask wi... | bd07ffd48362fc0ed9c5dc66699bea7b6ee0affb | 3,616,943 |
def knapsack(p, v, cmax):
"""Knapsack problem: select maximum value set of items if total size not
more than capacity
:param p: table with size of items
:param v: table with value of items
:param cmax: capacity of bag
:requires: number of items non-zero
:returns: value optimal solution, lis... | 484ae09e663c834e42a9e05d684138d4fb6ddf08 | 3,616,944 |
def identity(n, dtype='d', format=None):
"""Identity matrix in sparse format
Returns an identity matrix with shape (n,n) using a given
sparse format and dtype.
Parameters
----------
n : integer
Shape of the identity matrix.
dtype :
Data type of the matrix
format : strin... | ff459b04e3876f03cd1bd1d8a060c0a70d8190ea | 3,616,945 |
from datetime import datetime
def d2s(d):
"""
Date to string in friendly format, without time.
"""
return datetime.datetime.strftime(d, '%B %d, %Y') | a4fa2791d602c7bce4642d492818f9b8c1c9182e | 3,616,946 |
def refresh_content(username, password):
"""
Refresh the annoucements and resources for a user
Args:
username (String) : a UQ username to sign into blackboard and scrape
password (String) : the password for the UQ username's blackboard
Returns:
courses
"""
scraper = UQ... | 68f5b5c837625803b9f4ba28870741bd97e9c35e | 3,616,947 |
def adresa_inceput(netmask, ip):
"""
Ia un netmask si un IP si determina adresa de inceput
a retelei
:param (str) netmask:
:param (str) ip:
:return adresa_inceput (str):
"""
netmask_nums = netmask.split(".")
ip_nums = ip.split(".")
adresa_inceput = ""
for i in range(0, 4):
... | dcbe18f68b216d6772fcad01e43829bc33de43c9 | 3,616,948 |
import json
def get_all_features(after_time_added=None):
"""
Args:
after_time_added: get all features that were added to the db after this date.
Returns:
"""
features = []
if after_time_added:
for feature in Feature.objects.exclude(feature_added_time__lt=after_time_added):
... | 19d1bc06ee252ed9c0b5718f548ab8f79ad8f650 | 3,616,949 |
def ASBII(ATcur_P, ATxyz_P, ATxyz_K):
"""
| X | Astr. Azimuth , Zenith , Slope
| Y | ---------------+-------> from P to K distance distance
| Z |AT_P | (Apk) (Bpk) (Spk)
... | 01ac0a6dc8509ee6a0aaf4787268356fb8af2e5e | 3,616,950 |
import socket
def auto_build_socket(address):
"""Auto build a socket.socket instance from address"""
address_type = get_address_type(address)
if address_type == 'tcp':
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)
elif address_type == 'uds':
sock = socket.socket(socket.... | 676246e4468ea914fa0d72041e0fbd880ce30168 | 3,616,951 |
def get_usage_data_labels(usage_data):
"""Return dict with human readable labels for each of the groups in each of the given usage data timeframes."""
labels = {}
timeframe_formats = {"day": "%H", "week": "%b %d", "month": "%b %d", "year": "%b %Y"}
for timeframe, timeframe_data in usage_data.items():
... | 7c8610a7feb8a3a4a6454f508bfb9c95ccba55ff | 3,616,952 |
def has_same_disk_several_positions(board):
"""
Check if the same disk appears multiple times on the same board
Returns True is there is one or are multiple appearances, False if not
"""
used_disks = list(board.values())
for pos in range(len(used_disks) - 1, -1, -1):
if used_dis... | b184e5c8bfb34c9819e4ffb146c4159c4d247a4c | 3,616,953 |
def _get_temporal_props(ds: xr.Dataset) -> dict:
"""
Get temporal boundaries, resolution and duration of the given dataset. If
the 'bounds' are explicitly defined, these will be used for calculation,
otherwise it will rest on information gathered from the 'time' dimension
itself.
:param ds: Dat... | 662c6f777f86395c6cd6e53888b7bc2e9913fcf2 | 3,616,954 |
def draft_file_resource():
"""Draft file resource."""
return DraftFileResource(
config=DraftFileResourceConfig,
service=Service(config=ServiceConfig)
) | 964c884beb60ac097d93ea4cb9822aba24be2ee7 | 3,616,955 |
import logging
def make_models():
"""build all the models based on the arguments provided via absl
Returns: encoder_model, decoder_model, discriminator_model
"""
if FLAGS.model == "default" and FLAGS.training_method == "adaptive_st" or FLAGS.model == "adaptive_st":
logging.info("define adapt... | 165a840b8802c102d25660da3804c58b4063c558 | 3,616,956 |
def get_expression_parser(_: Environment) -> ExpressionParser:
"""Return an expression parser for the given environment."""
# Future proofing.
return STANDARD_EXPRESSION_PARSER | d7edf3cb6b58da851985f40da8d6bad33c68a2b6 | 3,616,957 |
async def _setup(hass, hass_ws_client, properties_data):
"""Set up tests."""
ws_client = await hass_ws_client(hass)
devices = MockDevices()
await devices.async_load()
devices.fill_properties("33.33.33", properties_data)
async_load_api(hass)
return ws_client, devices | 846716470b62c823e60256e6fff55e06344c2c33 | 3,616,958 |
def filter(function, iterable) -> object:
"""filter."""
if function is None:
return (item for item in iterable if item)
return (item for item in iterable if function(item)) | 36bfce957476f934a18c2bb3a24e994ec2799973 | 3,616,959 |
def red_car(red,lat):
"""
Convert reduced coordinates to cartesian
"""
return np.array(map( lambda coord: coord[0]*lat[0]+coord[1]*lat[1]+coord[2]*lat[2], red)) | 182cf99a6bb3d519d2a2674d12d4ac5ae738fe47 | 3,616,960 |
def byte_at_a_time_ecb_decryption_harder(encryption_oracle):
"""Performs the byte-at-a-time ECB decryption attack to discover the secret padding used by the oracle."""
# Find the block length
block_length = find_block_length(encryption_oracle)
# To detect if the oracle encrypts with ECB mode, we can e... | 6b45a4674fa796cfcba3f0d6b7c45c8f5aa78284 | 3,616,962 |
from typing import Optional
from typing import List
from typing import Union
def data_cleaning(
data: pd.DataFrame,
drop_threshold_cols: float = 0.9,
drop_threshold_rows: float = 0.9,
drop_duplicates: bool = True,
convert_dtypes: bool = True,
col_exclude: Optional[List[str]] = None,
catego... | 868c47ec1c1ed9827bfe7c009656eb8e14d04e2e | 3,616,964 |
def _pmf_doc_name(doc):
"""Helper to generate document name for a ProceedingsMaterialFactory LazyAttribute"""
return 'proceedings-{number}-{slug}'.format(
number=doc.factory_parent.meeting.number,
slug=xslugify(doc.factory_parent.type.slug).replace("_", "-")[:128]
) | e3a327ac418a6207e7148621593898ab2190ccbc | 3,616,965 |
def isWanted(client, date):
"""Check if the page of a date contains free time slots."""
loadDate(client, date)
times = getAvailableTimes(client.html)
ret = len(times) > 0
print('\tinspecting date', date, ', result =', 'available!!' if ret else 'full')
return ret | 8a115513a23b5cde7a85737864f16036d8c32190 | 3,616,966 |
import typing
def _get_counter_one(store: typing.Callable, item_key: ItemKey) -> int:
"""Returns count under exactly matched key.
"""
count = store.get(item_key.key)
return 0 if count is None else int(count) | 92b26c65f2abeb0aa7fedd5dfd9e4e626f150892 | 3,616,967 |
def wait_loading():
"""
Wait for selenium page to be ready
"""
return driver.execute_script('return document.readyState;') != 'complete' | 186233548abc55747fa8a46e8eeb19b05f35c608 | 3,616,968 |
def tril(m, k=0):
"""
Returns a lower triangle of an array.
Returns a copy of an array with elements above the k-th diagonal zeroed.
Args:
m(array_like): The shape and data-type of a define these same
attributes of the returned array.
k(int, optional): Diagonal above which ... | 13f1ca4437d8b9084251fcea2910f45fec9808ff | 3,616,969 |
def distance(request):
"""
Compute the Euclidean distance using our package. Check that multithreading has no
effect on the result.
"""
kwargs = request.param
kwargs.update(DATASET_1)
return g.distance_pairwise(**kwargs) | bf60a32584ee2627d6cacd6647468055af2ad6dd | 3,616,970 |
def modify_primer_file( infile, outfile ):
"""! @brief add subfix number to all primers """
counter = 0
mapping_table = {}
with open( outfile, "w" ) as out:
with open( infile, "r" ) as f:
line = f.readline()
while line:
if line[0] == ">":
if counter % 2 == 0:
name = line.strip()
out.w... | 20802c5578adceddafa6c7584a2da5c17b80ede6 | 3,616,971 |
def show_interface(dut, interface_name = None, cli_type="klish"):
"""
API to show sflow interface configuration
Author: Chaitanya Vella (chaitanya-vella.kumar@broadcom.com)
:param dut:
:return:
"""
output = list()
if cli_type == "klish":
command = "show sflow interface"
i... | 8b726e237d1531971b29604a93f0891cfc83349b | 3,616,972 |
def format_currency(amount):
"""Convert float to string currency with 2 decimal places."""
str_format = str(amount)
cents = str_format.split('.')[1]
if len(cents) == 1:
str_format += '0'
return '{0} USD'.format(str_format) | b90d064fe6b095227e5c590ad8d175f072e07957 | 3,616,973 |
async def async_setup(hass, config) -> bool:
"""Initialize the Sure Petcare component."""
if DOMAIN not in config:
return True
hass.async_create_task(
hass.config_entries.flow.async_init(
DOMAIN,
context={"source": config_entries.SOURCE_IMPORT},
data=conf... | 85a5bf34af18410cebee5f5fed5d178f2ebbd265 | 3,616,974 |
def _build_module_validity_mat(module_names):
"""
Build a module validity matrix, ensuring that only valid modules will have
non-zero probabilities. A module is only valid to run if there are enough
attentions to be popped from the stack, and have space to push into
(e.g. _Find), so that stack will not underf... | bf064711d6483237e8ca846dc4954d4454abbb37 | 3,616,975 |
def make_predictions(df):
"""
Uses the pycaret best model to make predictions on data in the df dataframe.
"""
model = load_model('churn_ada')
predictions = predict_model(model, data=df)
predictions.rename({'Label': 'Churn_prediction'}, axis=1, inplace=True)
predictions['Churn_prediction'].r... | 9a1a3914020cfa685f92612b834117a47f722842 | 3,616,977 |
def _audio_to_embeddings_fn(kv, teacher_fn, output_dimension):
"""Map audio to teacher labels."""
samples = kv[SAMPLES_]
teacher_embeddings = teacher_fn(samples)
teacher_embeddings.shape.assert_has_rank(2)
teacher_embeddings.set_shape([None, output_dimension])
return {SAMPLES_: samples, TARGETS_: teacher_em... | 4965bad9bd367bffa82b2ec40a61514870a42907 | 3,616,978 |
def _get_delay_time(session):
"""
Helper function to extract the delay time from the session.
:param session: Pytest session object.
:return: Returns the delay time for each test loop.
"""
return session.config.option.delay | 466ce191962df90ee8cdc1a5f8a004094eb9e79f | 3,616,979 |
def req_send_restore():
"""Отправка сообщения для активации"""
temp = User.find_link(request.get_json())
data = {
'title': 'Восстановление пароля',
'button': 'Изменить',
'login': temp[0],
'link': "http://127.0.0.1:5000/restore/" + get_link(temp[1]),
'color': col[temp[... | 92ef287b01eecbb1f93f01226a5362dc56fe9dbe | 3,616,980 |
def discretize(df, nbins=10, cut=pd.qcut,
verbose=2, drop_useless=True):
"""Discretize columns in {df} to have at most {nbins} categories.
* Categorical columns: take the Top n-1 plus "Other"
* Continuous columns: cut into {nbins} using {cut}.
Returns a new discretized dataframe with... | 70af1343fdd3464f799e08db02672329bd7771f8 | 3,616,981 |
def get_flavor_kind(penalty):
"""
Gets the flavor kind of a penalty.
Parameters
----------
penalty: PenaltyConfig, PenaltyTuner
The penalty whose flavor we want to know.
Output
------
flavor_kind: None, str
The flavor; one of [None, 'adaptive', 'non_convex']
"""
... | 8da150f1958df61ca494193a673189a929d3aa97 | 3,616,982 |
from typing import Sequence
def is_overlapping_lane_seq(lane_seq1: Sequence[int], lane_seq2: Sequence[int]) -> bool:
"""
Check if the 2 lane sequences are overlapping.
Overlapping is defined as::
s1------s2-----------------e1--------e2
Here lane2 starts somewhere on lane 1 and ends after it,... | 155e3a962f3f457a868585798e1ab8d92c9f115f | 3,616,983 |
def make_uniform_edge_dataset(args):
""" Uniform edge-sampled dataset. """
def dataset_fn(graph_data, seed):
neighbours, lengths, offsets = tensorboard_hack(graph_data)
def _fn(s):
return dataset_ops.UniformEdgeDataset(
args.num_edges, neighbours=neighbours, lengths=... | d3075d81fca902b5684d4750ff0756a58ac43f73 | 3,616,985 |
def output_handler(data, context):
"""Post-process TensorFlow Serving output before it is returned to the client.
Args:
data (obj): the TensorFlow serving response
context (Context): an object containing request and configuration details
Returns:
(bytes, string): data to return to cl... | 7d1bbcb2310c4527c5ae9cfcd51be660532555df | 3,616,986 |
def largest_rectangle(h):
"""Hackerrank Problem: https://www.hackerrank.com/challenges/largest-rectangle/problem
Skyline Real Estate Developers is planning to demolish a number of old, unoccupied buildings and construct a
shopping mall in their place. Your task is to find the largest solid area in which th... | 7d7b66929e8416fdf8fe64e080ec5ed288c72d88 | 3,616,987 |
def fahr2cel(t):
"""Converts an input temperature in fahrenheit to degrees celsius
Inputs:
t: temperature, in degrees Fahrenheit
Returns:
Temperature, in C
"""
return (t - 32) * 5 / 9 | b55f2405e06b124adf23b7833dedbe42ff9f75ba | 3,616,990 |
def str2tod(timeval=''):
"""Return tod for given string without fail."""
ret = None
if timeval is not None and timeval != '':
try:
ret = tod(timeval)
except:
pass
return ret | 91a787f61051d297e71c45687ae177e6c2855aad | 3,616,991 |
def readFDOUB1(stream):
"""
Read FDOUB1 from given stream
:type stream: FileIO or ByteIO
:param stream: stream to be read
:return: Result.
:rtype: FDOUB1
"""
return FDOUB1(stream) | 1124b0ab96519500cf9e3fffd992fe3e59d4c542 | 3,616,992 |
def _sub_sample(matrix_X, matrix_Y, test_statistic, num_samples, sub_samples, which_test):
"""
Sub samples the data and calculates the sub sampled test statistic
:param matrix_X: is interpreted as a ``[n*p]`` data matrix, a matrix with ``n`` samples in ``p`` dimensions
:type matrix_X: 2D numpy.array
... | eb40ef16a1e53ad7c50553ba9bffc9ad3aa8a66f | 3,616,993 |
def read_csv(param_name, filepath):
"""read dataframe using pandas.read_csv, but with appropriate types
"""
specs = filemanager.get_specs(param_name)
columndata = specs['columns']
converters = {c: eval(data['type']) for c, data in columndata.items()}
try:
cols = find_cols(filepath, colum... | 141a2edb13bf8056a5c3f459bd837e8b66710793 | 3,616,996 |
def test_custom_action(FormAction):
""" """
def name(self) -> Text:
return "action_recipe_search"
@staticmethod
def required_slots(tracker:Tracker) -> List[Text]:
# returns names of all slots that must be provides
return ["purpose", "diet_type"]
# can define slot_mappi... | 9e2a3c317a61ac947eb90104f22e0eb0050644b0 | 3,616,997 |
def reshape_data(state_trajectory, control_inputs, numstates):
"""
Reshapes the data of get_sampled_traj_and_ctrls
"""
traj = np.array(state_trajectory)
len_traj = len(state_trajectory)
traj = traj.reshape(len_traj, numstates)
ctrl = np.array(control_inputs)
return [traj, ctrl] | d9057e71c8e27644c85ec81664b4432c5c21bcd6 | 3,616,999 |
def getPrivateKeyObject(filename = None, data = '', passphrase = ''):
"""
Return a C{Crypto.PublicKey.pubkey.pubkey} object corresponding to the
private key file/data. If the private key is encrypted, passphrase B{must}
be specified, other wise a L{BadKeyError} will be raised.
@type filename: ... | 07a5c5b302726b2db4eab3e451765ebbe592e374 | 3,617,003 |
import statistics
def get_two_movies_average_rating(movie1_id, movie2_id, threshold=50):
"""return the average rating for two movies, based on the users who have watched both of the movies"""
users = get_user_watched_two_movies(movie1_id, movie2_id)
if users and len(users) > threshold:
ratings1 = ... | 8a2080624357cd112d8789317984d0e01d1cf2da | 3,617,004 |
import torch
def test_extraction():
"""End-to-end test of a model extraction attack"""
# Create a query function for a target PyTorch Lightning model
model = train_four_layer_mnist_victim(gpus=torch.cuda.device_count())
def query_mnist(input_data):
# PrivacyRaven provides built-in query func... | 72ce6c053a9bca2cfaf965193b9cf5aa9f889df6 | 3,617,005 |
def read_parquet(filename, column, **kwargs):
"""read_parquet"""
memory = kwargs.get("memory", "")
start = kwargs.get("start", 0)
stop = kwargs.get("stop", None)
if stop is None and column.shape[0] is not None:
stop = column.shape[0] - start
if stop is None:
stop = -1
return parquet_ops.io_read_pa... | 785f0a6f16679b0f60ee37bcdadc9fba409b8099 | 3,617,006 |
def to_int(value):
"""Converts the given string value into an integer. Returns 0 if the
conversion fails."""
try:
return int(value)
except (TypeError, ValueError):
return 0 | f219844de96d1d2236e94c4427c0ad27cc4b587b | 3,617,008 |
def create_two_transforms_curve(transform1, transform2, name = ''):
"""
Create a curve between two transforms.
"""
if not name:
name = '%s_to_%s_curve' % (transform1, transform2)
pos1 = cmds.xform(transform1, q = True, ws = True, t = True)
pos2 = cmds.xform(transform2, q = True, ws ... | e894c77d647afdbe7676360ed73640193f03fe2e | 3,617,009 |
def vms_ajax_assign_disk(request, vm_id, template_name='vms/ajax/assign_disk.html', form_class=AssignDiskForm):
"""
Ajax view for assigning Disk to a virtual machine.
"""
rest_data = prep_data({'disks': 'user/storage_image/get_list/',
'disk_controllers': 'user/storage_image/ge... | c0fd472d9a9fbbd8a1e27a1b5bb86c313776cbdf | 3,617,010 |
def _default_function(l, default, i):
"""
EXAMPLES::
sage: from sage.combinat.integer_vector import _default_function
sage: import functools
sage: f = functools.partial(_default_function, [1,2,3], 99)
sage: f(-1)
99
sage: f(0)
1
sage: f(1)
... | 05da74d0c4ecee914928e8760d75730efc3434e5 | 3,617,011 |
import base64
import json
def parse_id_token(token: str) -> GoogleUserInfo:
"""Parse the base64 encoded id token."""
parts = token.split(".")
if len(parts) != 3:
raise RuntimeError("Received Invalid ID Token")
payload = parts[1]
padded = payload + ("=" * (4 - len(payload) % 4))
decode... | 8a7ea6c8d959c35df8f623f892b4df7e4b8af3b0 | 3,617,012 |
def _parse_apple(data):
"""Parse an AppleSingle or AppleDouble file."""
header = _APPLE_HEADER.from_bytes(data)
if header.magic == _APPLESINGLE_MAGIC:
container = 'AppleSingle'
elif header.magic == _APPLEDOUBLE_MAGIC:
container = 'AppleDouble'
else:
raise ValueError('Not an A... | 8cade17b36fcafdfde6ebd81a9918d77e114586c | 3,617,013 |
def convert_headers_str(_str):
"""
convert headers str to dict
"""
_list = [i.strip() for i in _str.split('\n')]
headers_dict = dict()
for i in _list:
k, v = i.split(':', 1)
headers_dict[k.strip()] = v.strip()
return headers_dict | cc80c1c2f5fc128243e59529808685335f7cead4 | 3,617,014 |
def make_expand_dims_tests(options):
"""Make a set of tests to do expand_dims."""
test_parameters = [{
"input_type": [tf.float32, tf.int32],
"input_shape": [[5, 4], [1, 5, 4]],
"axis_value": [0, 1, 2, -1, -2, -3],
"constant_axis": [True, False],
"fully_quantize": [False],
}, {
... | 238d4a6ba427357c4e02223c01d5245610016492 | 3,617,015 |
def eliminate_from_neighbors(csp, var) :
"""Eliminates incompatible values from var's neighbors' domains, modifying
the original csp. Returns an alphabetically sorted list of the neighboring
variables whose domains were reduced, with each variable appearing at most
once. If no domains were reduced, re... | 66062fce99f7f596239c27b27265bdec20cd55ae | 3,617,016 |
def cross(a, b):
"""Cross Product function
Given vectors a and b, calculate the cross product.
Parameters
----------
a : list
First 3D vector.
b : list
Second 3D vector.
Returns
-------
c : list
The cross product of vector a and vector b.
... | d71244391e28af7b42eff45af62cc936b8651cd2 | 3,617,017 |
from operator import add
def add_multiply(x, y, z):
"""Add two numbers and multiply it with a third."""
addition = add(x, y)
product = multiply(addition, z)
return product | 430e5c17106faab4a123123c42c10064727e654c | 3,617,018 |
async def async_setup(hass: HomeAssistant, config: dict):
"""Set up the media_source component."""
hass.data[DOMAIN] = {}
hass.components.websocket_api.async_register_command(websocket_browse_media)
hass.components.websocket_api.async_register_command(websocket_resolve_media)
hass.components.fronten... | 4de2588406b96b0a9eb8f9ad6ac959c79ad601ee | 3,617,019 |
import random
def rand_sampling(ratio, stop, start=1) :
"""
random sampling from close interval [start, stop]
Args :
ratio (float): percentage of sampling
stop (int): upper bound of sampling interval
start (int): lower bound of sampling interval
Returns :
A random... | 9b54c6b364e71a97d7cd9fa392790c4afde2bae0 | 3,617,020 |
import urllib
def open_webpage(url):
"""some webpages block the user agent 'python'"""
hdr = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11'}
req = urllib.request.Request(url, headers=hdr)
return urllib.request.urlopen(req) | 1b7fd7d6edd652818f6c454e9e27a4c5bd11c298 | 3,617,021 |
def compare_from_file(filename, disable_tokenizers=None, verbose=True,
additional_tokenizers=None):
"""
Method to compare the tokenizers from an input text.
This function outputs information about the execution environment
and data and comparison results.
Parameters
-----... | 77863249c1ee2940bb5c3fa770ae3bd2ec934858 | 3,617,022 |
def humanbool(name, value):
"""
Determine human boolean value
:Parameters:
`name` : ``str``
The config key (used for error message)
`value` : ``str``
The config value
:Return: The boolean value
:Rtype: ``bool``
:Exceptions:
- `ValueError` : The value could n... | 422d45167c26f422e1f0a2fc5aa1c5e2eb752276 | 3,617,023 |
async def filter_record(record_a, record_b, filter_fields=None):
"""
Filters a record for unique information.
Args:
record_a (``dictionary``): New airtable record.
record_b (``dictionary``): Old airtable record (This will be dictate the ``id``)
Kwargs:
filter_fields (``list``, o... | 79e42ff50bf8e43fb7c4df218b0de58f61ea778d | 3,617,025 |
def mask_tokens_evenly(tokens, gap, min_token_lengths, mask_token, gap_mask=1):
"""Produce several maskings for the given tokens where each masking is created by masking every
"gap" tokens, as long as the token is large enough according to min_token_lengths.
Args:
tokens (List[str]): a sequence of ... | 76cb6d402b73a5d5af0e1e87835485962e9b2353 | 3,617,026 |
from .hosts import Host
def valid_host(host: Host) -> Host:
""" Validation test for valid Host class
Parameters:
host (Host): Host class object
Returns:
Host: Valid Host object
"""
if not isinstance(host, Host):
raise ex.InvalidHostError(
f'Must be Host class ... | bc8b25f3be0df5ed82b15d9e59f0453f70848be5 | 3,617,028 |
def build_graph(input_file):
"""Build the graph data structure from the input csv file."""
# Open the csv as dict iterator
input_file = open(input_file, 'rU')
reader = csv.DictReader(input_file)
# Create all nodes
nodes = {}
for row in reader:
name = row['NODE']
nodes[name] ... | aea8f7ccbadad85495c9d621de78ce31e03df4cb | 3,617,029 |
def build_rnn_dataset(sst_home, reader, class_func=ternary_class_func):
"""Given an SST reader, return the `class_func` version of the
dataset as (X, y) training pair.
Parameters
----------
sst_home : str
Full path to the 'trees' directory for SST.
reader : train_reader or dev_reader
... | 52526a5d778c17d229ac48beb7b70dcfd1ad83a0 | 3,617,030 |
from datetime import datetime
def iso_dt_to_datetime(t: str) -> str:
""" """
return default_datetime_repr(datetime.datetime.fromisoformat(t[:-1])) | 7b6fbb00188572aeac5629423ef739a5adc01861 | 3,617,031 |
def index():
"""
后台管理首页
"""
user = g.user
return render_template("admin/index.html", user=user.to_dict()) | 4d1b2fc5af8e5f0774e482a5201b4fc1ac73a839 | 3,617,032 |
def test_distance(markers, verbose=True,threshold=200,size=None):
"""detect if to center is too near than seuil delet the smaller
markers : image input
verbose : if you want display process
threshold : the sqaure distance into center
size : the minimum size of area of the retai... | d1c4cefcfb19a75493a5ca1b14a543711ef3eeab | 3,617,033 |
def cs(dataset, pts=0.0, neg=False, **kwargs):
"""
Circular shift.
For multidimensional NDDataset,
the shift is by default performed on the last dimension.
Parameters
----------
dataset : nddataset
nddataset to be shifted
pts : int
Number of points toshift.
neg : bo... | 051b56afa521f8c545cba27bef6648c1e21f9edc | 3,617,034 |
def _result_value_flat_to_batchable(result_value_flat, result_flat_signature):
"""Converts result_value_flat -> result_value_batchable."""
result_value_batchable = []
for (r_value, r_spec) in zip(result_value_flat, result_flat_signature):
if isinstance(r_spec, tensor_spec.TensorSpec):
result_value_batch... | bc63f3fa692912622bfa1ce84373c94f3f9ec5e3 | 3,617,035 |
def sample_action(Q, state, num_actions, epsilon):
"""
Epsilon greedy action selection.
Parameters
----------
Q : numpy array of shape (N, 1)
Q function for the environment where N is the total number of states.
state : int
The current state.
num_actions : int
The ... | 8034037fbdb4bb0538f786b262930c64c4615412 | 3,617,036 |
def get_socket_from_cluster_id(cluster_id):
"""
Returns the socket and token/queue dict for the specified cluster id
:param cluster_id: The if of the cluster to check
:return: The websocket and dict if found or None
"""
# Iterate over the connections
for sock in CONNECTION_MAP:
# Ch... | 07ffe7a17e093d7bd8f1087501019f7527681535 | 3,617,037 |
from typing import Tuple
from typing import Dict
def save_user_giphy(user: "Users", giphy: "str") -> "Tuple[Response, int]":
""" Saves giphy to user account
Params:
user (Users): User model provided by token_required
giphy (str): Giphy ID provided by GIPHY
Returns Tuple[Response, int]
... | 2d0ffaa40841cef373cea600c968bea6a9dd9682 | 3,617,038 |
def contain_same_digit(a, b):
"""
This function tests whether or not numbers a and b contains the same digits.
"""
list_a = list(str(a))
list_b = list(str(b))
if len(list_a) == len(list_b):
for elt in list_a:
if elt not in list_b:
return False
return T... | a09feb891e5413593531e56871a92c335e585d7b | 3,617,039 |
from typing import Union
def has_nonnegative_entries(input_matrix: Union[sparse.csr_matrix, np.ndarray]) -> bool:
"""True if the array has non negative entries."""
if type(input_matrix) == sparse.csr_matrix:
return np.all(input_matrix.data >= 0)
else:
return np.all(input_matrix >= 0) | 882bb05a6ef60835145dafdbe1f7a1a5b855fe84 | 3,617,041 |
def get_worker():
"""
Creates a redis queue worker with a retry exception handler.
To run the worker:
>> worker = get_worker()
>> worker.work(with_scheduler=True)
"""
settings = get_config()
queue = redis_queue(settings)
return Worker(
queues=[queue], connection=queue.connec... | 2397098513afb9fad917b2d1e1ea2cf5cb800077 | 3,617,042 |
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Setup the Command Sensor."""
if config.get('command') is None:
_LOGGER.error('Missing required variable: "command"')
return False
data = CommandSensorData(config.get('command'))
add_devices([CommandBinarySensor(
... | 784a790b375ab25d4c6bbb4c42f131c08f270c1a | 3,617,043 |
def error_data(code):
"""Constructs a dictionary with status and message for returning in an
error response"""
error = {
'status': code,
'message': http_status_message(code),
}
return error | 6e4a01e5b32a74701605dba62b88738f9e852073 | 3,617,044 |
def test_Mesh_NO6_transfinite():
"""Unittests for the mesh."""
if rAnk == mAster_rank:
print(">>> {test_Mesh_NO6_transfinite} ...... ", flush=True)
def u(t, x, y, z): return np.cos(np.pi*x) + np.sin(np.pi*y) * np.sin(np.pi*z-0.125)**2 + t/2
def v(t, x, y, z): return np.sin(np.pi*x) + np.sin(np.... | aada50c384ffff0477962158f2e3902e8c9f471f | 3,617,046 |
def isPILAllowed():
"""Return true iff PIL should be used by the caller."""
global _pil_allowed
if _pil_allowed is None:
app = grailutil.get_grailapp()
_pil_allowed = (app.prefs.GetBoolean("browser", "enable-pil")
and pil_installed())
return _pil_allowed | 34a33d0789cca703c8dc36103b652c307bb51820 | 3,617,048 |
import yaml
def read_yaml(config_path):
"""Load config files."""
with open(config_path) as file:
data = yaml.load(file, Loader=yaml.FullLoader)
return data | b46882ad841228edb3398a5742fa4dea6c4e9495 | 3,617,049 |
def read_jsonlines(filepath: str) -> pd.DataFrame:
"""Function that reads a jsonlines file as a pandas dataframe"""
with open(filepath) as f:
lines = f.read().splitlines()
dicts = [eval(line) for line in lines]
return pd.DataFrame(dicts) | 01c77934df604de88d747d032045f886ffe33bdf | 3,617,050 |
from typing import Tuple
def read_data_attention(strategy: tf.distribute.TPUStrategy,
max_len: int,
) -> Tuple[np.array, np.array, np.array, np.array, tf.data.Dataset, tf.data.Dataset, tf.data.Dataset, int]:
"""
read data from attention models
"""
logger... | fa3943c787f203a6e57a59da7c93baa090223360 | 3,617,051 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.