content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from typing import Union
def zeros_like(x: Union[ivy.Array, ivy.NativeArray], dtype: ivy.Dtype = None, dev: ivy.Device = None,
) -> Union[ivy.Array, ivy.NativeArray]:
"""
Returns an array of zeros with the same shape and type as x, unless dtype provided which overrides.
:param x: The shape... | fff4e8d408c94b4ef687bc4f34bce926a6e943d9 | 3,610,800 |
def get_data_ts(type, mask_disc=False, filter_missing_vft=False):
"""
get data as tme series i.e no input output
:param type:
:param use_deltat:
:return:
"""
pickle = True
if (type == 'train'):
data = np.load('../oct_forecasting/temp/lstmdata_train.npz', allow_pickle=pickle)
... | 3d6a5da5024cd035a0b284f78d233932c7164807 | 3,610,801 |
def get_lwt_topic(mqtt: dict) -> dict:
"""Return last will topic."""
if not mqtt["last_will_topic"]:
mqtt["last_will_topic"] = f"{mqtt['client_id']}/lwt"
return mqtt | fdc6941dff5d702adeebf81f02d10c7f6a21c180 | 3,610,802 |
import time
import math
import json
def list_count(choice, dataset_id, start_timestamp, end_timestamp, dataset_type='result_table', frequency='1d'):
"""
查询生命周期指标的数据趋势
:param choice:
:param dataset_id:
:param start_timestamp:
:param end_timestamp:
:param dataset_type:
:param frequency:
... | 85fd2d003438dffa1874d615b93cbe10190e1347 | 3,610,803 |
from typing import Callable
from typing import Any
def debounce(wait: int):
"""Debounce main method."""
def decorator(fn: Callable):
def debounced(*args: Any, **kwargs: Any):
def call_it() -> None:
fn(*args, **kwargs)
try:
debounced.timer.cance... | eff91661552238b98bd80e7c34002072ae3a0847 | 3,610,804 |
def aos_delete(session, endpoint, aos_id):
"""
DELETE request aginst aos RestApi
:param session: dict
:param endpoint: string
:param aos_id: string
:return: dict
"""
aos_url = "https://{}/api/{}/{}".format(session['server'],
endpoint,
... | 4d7c09fd111a5190b12d8daa7113783583b97575 | 3,610,805 |
def value_to_key_strokes(value):
"""Convert value to a list of key strokes
>>> value_to_key_strokes(123)
['123']
>>> value_to_key_strokes('123')
['123']
>>> value_to_key_strokes([1, 2, 3])
['123']
>>> value_to_key_strokes(['1', '2', '3'])
['123']
Args:
value(int|str|list... | d211d39a0018c6eef66ab30ba33d3996b74db930 | 3,610,806 |
def legacy_data_config_to_new_data_config(
ds_section: DictConfig, legacy_dataset_section: DictConfig, train: bool
) -> DictConfig:
"""
Transform old style dataset to new format dataset.
Args:
ds_section: a ds section (``train_ds``, or ``validation_ds``, or ``test_ds``) from old style config. Su... | 30ef2a03fdafa7072d97bf4e840e49718654a447 | 3,610,807 |
import math
def _calculate_gain(nonlinearity, param=None):
"""
Calculate gain.
Args:
nonlinearity (str): nonlinearity function.
param (str): used to calculate negative_slope.
Returns:
number.
"""
linear_fns = ['linear', 'conv1d', 'conv2d', 'conv3d', 'conv_transpose1d'... | 78d675f7654897afee074b08cb44c76e272ff3e8 | 3,610,808 |
import os
import sys
def verifyDirectory(path, create, quiet):
"""
ERROR CHECK: verify directory exists
:param path: str, path to save the file
:param create: bool, whether to create missing dir
:param quiet: bool, whether to quietly return T/F
:return: exists, bool, indicates existence of directory
"""
exi... | c7a479dc44beaac96a6c963fc2ec8735c95d1687 | 3,610,809 |
def listify(array, valuename, colnames):
"""
converts a multidimensional numpy array into a pandas dataframe with colnames[0] referring to dimension 0, etc
and valuecolumn containing the array values
"""
multiindex = pd.MultiIndex.from_product([range(i) for i in array.shape])
colmapping = {"level_" + ... | 9727e3dd8682dcf2dc7be942c8d7d8e805dd5a83 | 3,610,810 |
from re import T
def Lp(params, p=2):
"""
Given a list of parameters, compute the p-th power of its Lp norm.
:type params: list
:param params: Parameters to take the Lp norm of.
:type p: int
:param p: p of the Lp norm. Defaults to 2.
:return: (Lp norm)^p
"""
# Compute Lp^p
... | 5e5092bf71839069d719af64ab7491d59c20b15a | 3,610,811 |
import logging
def unpack_student_answer_1_5(questions_info, valid_question_ids,
assessment_weights, group_to_questions,
unit_responses, timestamp):
"""Unpack JSON from event; convert to QuestionAnswerInfo objects.
The JSON for events is unusually s... | 5cd967c38d2a57ec2b9e0c4ccbcf3e20a8dc1875 | 3,610,812 |
import json
def handle_all_coordinates():
"""
Kezeli az ossz koordinata lekereset.
:return:
"""
response = make_response(json.dumps(coordinates))
response.headers["Content-Type"] = "application/json"
return response | 88474fd266713cacf26246b6239da0407a3eb084 | 3,610,813 |
def loadXML(path):
"""
returns a 'xml.etree.ElementTree.ElementTree' object read from a xml file
or object-type.
"""
return et.parse(path) | 01e6dfc3a7c48e6bd16d0099e97d65aed9a0a3df | 3,610,814 |
def _label(img: np.ndarray) -> np.ndarray:
""" Applies labeling to given binary image returning array in which each group of pixels has the same value. """
return measure.label(img) | 1f2271155e688f17a1fbbb904b2c53a984442a12 | 3,610,815 |
def execute_remote_ssh_commands(hostname, username, password, commands, verbose=True):
""" Execute a remote command line.
hostname (str): This is the IP or domain name of ssh server.
username (str): This value is the username use to login to ssh server.
password (str): This value... | 899ef4ff8b2e5fd3ef76a924a4ed7168aee77ee3 | 3,610,816 |
def consolidate_rows(df: pd.DataFrame) -> pd.DataFrame:
"""
Group rows by all columns except "origin" to remove redundancies
created by entity recognition from multiple sources/ontologies
:param df: Input DataFrame
:type df: pd.DataFrame
:return: Consolidated DataFrame
:rtype: pd.DataFrame
... | 4d8ef18812faf983ee129302e41fc3f263b40957 | 3,610,817 |
def get_locale():
"""Return the default locale string."""
return ('es_ES' if getdefaultlocale()[0] == 'es_CU' else
getdefaultlocale()[0])
# return 'es_ES' | 3507d73e5312fda06ee302dafdf0fac8f6f273fa | 3,610,818 |
def process_fare(df):
"""
Converts the Fare column into pre-defined bins.
:param df: Dataframe
:return: Dataframe with Fare column having pre-defined bins
"""
cut_points = [-1, 12, 50, 100, 1000]
label_names = ["0-12", "12-50", "50-100", "100+"]
df["Fare_categories"] = pd.cut(df["Fare"]... | 07407bfe1804a31b7d395ce420231f8646742095 | 3,610,819 |
from datetime import datetime
def disable_account_ajax(request):
"""
Ajax call to change user standing. Endpoint of the form
in manage_user_standing.html
"""
if not request.user.is_staff:
raise Http404
username = request.POST.get('username')
context = {}
if username is None or ... | 43941cf6b7d1a14900f64643a84b17cca419adf3 | 3,610,820 |
import os
import platform
import re
def spacja(sciezka):
""" escaping space and special char in pathname """
sciezka = os.path.normpath(sciezka)
if platform.system() == "Windows":
czy_spacja = re.search(" ", sciezka)
if czy_spacja is not None:
sciezka = '"' + sciezka + '"'
... | 3ca0c3d743662d6811e5281b4b7d5c3988902a1b | 3,610,821 |
def ghg_parse(dataframe_list, args):
"""
Parse the given EPA GHGI data and return multiple dataframes, one per-year per-table.
:param dataframe_list:
:param args:
:return:
"""
cleaned_list = []
for df in dataframe_list:
special_format = False
source_name = df["SourceName"... | d176e29dc3aa31f3de9b8b447377298251266b6d | 3,610,822 |
def create_collection(href, cls):
"""
This collection type inserts a ``create`` method into the collection.
This will proxy to the sub elements create method while restricting
access to other attributes that wouldn't be initialized yet.
.. py:method:: create(...)
Create method is inser... | 78e1d221a9c79384ad84cfd51b2b4650abd7efe2 | 3,610,823 |
from datetime import datetime
def videopost(request):
"""Renders the about page."""
assert isinstance(request, HttpRequest)
return render(
request,
'app/videopost.html',
{
'title':'О Нас',
'message':'Сведения о нашей компании',
'year':datetime.no... | 55383674efa356a5f4057cd4017c555030782702 | 3,610,824 |
def generic_5v5_log_graph_title(figtype, **kwargs):
"""
Generates a figure title incorporating parameters from kwargs:
[Fig type] for [player, or multiple players, or team]
[date range]
[rolling window, if applicable]
[TOI range, if applicable]
[TOI60 range, if applicable]
Methods for ... | 52095506dedf1d431643f3efc2695f57b3a6e1c8 | 3,610,825 |
def not_in(a, b):
"""Evalutes a not in b"""
result = False if a in b else True
return result | bf5f2fd22a48f4ba517c75de2d05c11ab585756b | 3,610,826 |
def _is_list(arg):
"""Checks if arg is list-like. This excludes strings and dicts."""
if isinstance(arg, dict):
return False
if isinstance(arg, str): # Python 3-only, as str has __iter__
return False
return (not _has_method(arg, "strip")
and _has_method(arg, "__getitem__")
... | 0d6e37f0d698d44035d9dd8be2cc57d593bc3d6c | 3,610,827 |
def calculate_ssd(desc1: list, desc2: list) -> float:
"""
This function is responsible of:
- Calculating the Sum Square Distance between two feature vectors.
- Matching a feature in the first image with the closest feature in the second image.
Note:
- Multiple features from the firs... | 27da019ebdccfbe9ecb2162fd635e1911469b77d | 3,610,828 |
def encode_imsi(imsi):
"""
Convert a IMSI string to a uint + length. IMSI strings can contain two
prefix zeros for test MCC and maximum fifteen digits. Bit 1 of the
compacted uint is always 1, so that we can match on it set. Bits 2-3
the compacted uint contain how many leading 0's are in the IMSI. F... | 31d025168ba2421be2b235a049983ee331437ffd | 3,610,829 |
def find_by_type_or_id(type_or_id, prs):
"""
:param type_or_id: Type of the data to process or ID of the processor class
:param prs: A list of :class:`anyconfig.models.processor.Processor` classes
:return:
A list of processor classes to process files of given data type or
processor 'type... | d01b77eec359223c8f969c68353c3bdff14e7224 | 3,610,830 |
def parse_content(content):
"""Parse the content of a file into a dictionary mapping words to word"""
words = {}
for line in content.split('\n'):
word, frequency = line.split()
words[word] = int(frequency)
return words | 83757725e29d00732835002db4a2dec4b4d71b8c | 3,610,831 |
import sgtk
import inspect
import os
def start_engine(data):
"""
Start the tk-desktop engine given a data dictionary like the one passed
to the launch_python hook.
"""
engine = Bootstrap(data).start_engine()
# Import Toolkit locally. We need to capture this Python path so we can use it to boo... | 160fd903c616941420095d7e8548950928d0d685 | 3,610,832 |
def extract_frequency(im, pixel_value = 255):
"""
Extract frequency of non-zero entries across bands for each pixel.
NOTE: The result is indexed from one rather than zero, to distinguish
a signal from the case where all bands are zero.
A frequency of 1 indicates one count from across all bands
... | 2c95ba6cef96f76f1aea459fc643204d15687b09 | 3,610,833 |
def NaiveBayesSmsSpamCollection():
"""Apply Naive Bayes to SMS Spam Collection
"""
def convert(x):
ret = []
for i in x:
ret.append(1) if i == 'spam' else ret.append(0)
return ret
df = read_lines_and_convert_to_df('SMSSpamCollection/SMSSpamCollection')
#df = read... | b7874d4f844ebf417ae8dae3649c9ca37b78ecd9 | 3,610,834 |
def EffectiveProxyInfo():
"""Returns ProxyInfo effective in gcloud and if it is from gloud properties.
Returns:
A tuple of two elements in which the first element is an httplib2.ProxyInfo
object and the second is a bool that is True if the proxy info came from
previously set Cloud SDK proxy propert... | 29988be8f7909086c37de577307aa3df0548bb34 | 3,610,835 |
def reply(threaded=False):
"""Plugin reply decorator."""
def wrapper(func):
func._is_reply = True
func._is_threaded = threaded
return func
return wrapper | 016917e073471150696ba02dbb25d07dca95865c | 3,610,836 |
def create_mask_from_vector(vector_data_path, cols, rows, geo_transform,
projection, target_value=1):
"""Rasterize the given vector (wrapper for gdal.RasterizeLayer)."""
data_source = gdal.OpenEx(vector_data_path, gdal.OF_VECTOR)
layer = data_source.GetLayer(0)
driver = gdal.... | 050719dc44ad9988ba771120f1f93628a96fe9e3 | 3,610,837 |
from typing import Tuple
def egcd(a: int, b: int) -> Tuple[int, int, int]:
"""Euler's extended algorithm for GCD"""
if a == 0:
return b, 0, 1
else:
g, y, x = egcd(b % a, a)
return g, x - (b // a) * y, y | a329313472c55cc7cb8a9cef454859ef80ae4bd7 | 3,610,838 |
import re
from datetime import datetime
def json2py(json_obj):
"""
Converts the inputted JSON object to a python value.
:param json_obj | <variant>
"""
for key, value in json_obj.items():
if type(value) not in (str, unicode):
continue
# restore a datetime
... | b89171046573401e30256906ea911c21a56121d4 | 3,610,839 |
def load_epoch_as_lists(session_name, epoch, trialtypes=None, SNRthresh=0,
verbose=False):
"""
Load SUA spike trains of specific session and epoch from Lilou's data.
* The output is a dictionary, with SUA ids as keys.
* Each SUA id is associated to a list of spike trains, one pe... | 2c009d235100acf06ef57e03f417cbd6ffc4822f | 3,610,840 |
import typing
import itertools
def generate_fixed_permutations(
base_name: str,
locations: typing.List[str],
perm_length: int,
) -> typing.List[typing.List[str]]:
"""
Generate path permutations of a specified length which always start and
end at base_name.
:param base_name:
Name of... | 61c03cb166ca4dc7691d3c09eaedf26b5ff3c288 | 3,610,841 |
def scorer_from_spec(language, approach):
"""Create scorer from language and approach.
Args:
language (str): Name of language to use.
approach (str): Approach to use.
Returns:
An instance of :class:`subsclu.scorers.base.Scorer`.
"""
logger.info("creating scorer from spec w... | 060b60a66c50aa9c812aa20210e67f9792dbd8eb | 3,610,842 |
def parse_managed_variant_lines(csv_lines):
"""Parse managed variant csv lines into managed variant info dicts.
Shares implementation structure with panel csv parsing. Could be generalised.
Args:
csv_lines(iterable(str))
Returns:
list(managed_variant_info(dict)): A list of variant i... | 00341eddc6c28940bcb9b3dabcd9a082ea2ccf42 | 3,610,843 |
import re
def cleanEngText(eng_raw_string, customize_stop_words=[]):
"""
Args:
eng_raw_string: str -
customize_stop_words: list - all stopwords to remove
Returns:
refined_doc: str - curated string of eng text
"""
# Remove dates
# 1 or 2 digit number followed by back ... | 7a3c24991538f5fdce9aa9625725899ae52ed195 | 3,610,844 |
from pathlib import Path
def get_experiment(flags):
"""
Get experiments class from dir_data flag.
"""
if flags.dataset == 'celeba':
return CelebaExperiment(flags)
if Path(flags.dir_data).name in ['PolyMNIST', 'polymnist']:
return PolymnistExperiment(flags)
elif Path(flags.dir_d... | d57476145036fcd6c53cd3ba7295db42f776d2a4 | 3,610,845 |
def PydroVersionType():
""" Return "Developer" or "Release" to indicate if the repository is from trunk or tag
"""
install_type = "Developer" if PydroVersionIsDev() else "Release"
return install_type | a9fe54ed6d2d0298326a961e5bf077853525f6f9 | 3,610,846 |
import scipy
def dlqr(a, b, q, r, gamma=None):
"""Solve the discrete time lqr controller.
x[k+1] = a @ x[k] + b @ u[k]
with instantaneous cost
x[k].T @ q @ x[k] + u[k].T @ r @ u[k]
Parameters
----------
a: state transition matrix.
b: input matrix.
q: state cost matrix (semi-posi... | 1fe62ceff3c57ef8d466ec23ca760dda7b81db1f | 3,610,847 |
from typing import Optional
import random
import logging
def run_dmc(task: tasks.Task,
seed: int,
num_samples: int,
batch_size: Optional[int] = None,
logger: Optional[logger_lib.Logger] = None):
"""Run the Direct Monte Carlo (DMC) baseline.
Args:
task: `Task` f... | 9ebb1ddc48abdbbd041d760aba2d22b30c2f37a3 | 3,610,848 |
import typing
import pathlib
import hashlib
from pathlib import Path
def md5(p: typing.Union[pathlib.Path, str], bufsize: int = 32768) -> str:
"""
Compute md5 sum of the content of a file.
"""
hash_md5 = hashlib.md5()
with Path(p).open('rb') as fp:
for chunk in iter(lambda: fp.read(bufsize... | 2399177dca4d64de231287f7bd25346df8437dbd | 3,610,849 |
def pck_coverage(path, date_format="infomod2", system="UTC"):
"""Returns the coverage of a PCK file.
The function assumes that the appropriate kernels have already been loaded.
:param path: File path
:type path: str
:param date_format: Date format, the default is the one
pr... | a82533e1bc3f68b22f3d39455ea8abfcf2095370 | 3,610,850 |
def cv(temp,dflu,chkbnd=False):
"""Calculate fluid water isochoric heat capacity.
Calculate the isochoric (constant volume) heat capacity of fluid
water from temperature and fluid density.
:arg float temp: Temperature in K.
:arg float dflu: Fluid water density in kg/m3.
:arg bool chkbn... | 808a678ef81ff2336501a172fb2f5e22efde01ff | 3,610,851 |
import os
import pickle
def load_dict_genomic_annotations(parameters, cell_line):
"""
Function loads dict of lists indicating the number of annotations of specific genomic annotations in each genomic
bin for each chromsome.
:param parameters: dictionary with parameters set in parameters.json file
... | 20712e7580cfc4c6f3eb7dff9c7281f7e313d5a8 | 3,610,852 |
def get_authorize_url(client_id, client_secret, redirect_uri, scope):
"""
Get a spotify oauth authorization url.
Redirect user here and read response
at redirect_uri.
"""
auth = ExtendedOAuth(
client_id, client_secret, redirect_uri, scope=scope)
auth_url = auth.get_authorize_url()
... | 5a5dfedb62c777b48e2ef9f9a9ca99f2b80d566a | 3,610,853 |
def book_genres(book_info: tuple) -> set:
"""
Returns the genres of the book by its title and writer.
>>> book_genres(('Through the looking-glass. Sambahsa', 'Lewis Carroll')) \
== {"Children's fiction", 'Fantasy'}
True
>>> book_genres(('Through the looking-glass', 'Lewis Carroll')) == {'Illustratio... | fda249d95c2b3ad520179ef73bb656ec98474391 | 3,610,854 |
def food(request):
""" Food view
Displays the database of food items.
"""
foods = Food.objects.all()
context = {
'foods': foods,
'foods_total_count': len(foods),
}
return render(request, 'tracker_app/food.html', context=context) | 76ccb23b33cd7873f7c37cdba38d0b5255c4a3e5 | 3,610,855 |
def test_callback_compiling_args_or_kwargs():
"""Test compiling callbacks with routed positional (args) or keyword (kwargs) arguments.
"""
def get_clf() -> keras.Model:
model = keras.models.Sequential()
model.add(keras.layers.InputLayer((1,)))
model.add(keras.layers.Dense(1, activat... | af839936487bbb125a0c2e92a07c34c201b78632 | 3,610,856 |
import os
import time
def get_file_mod_time(pth):
"""
Safely get last modification time for a file. Prevents situation when file
is deleted between file existence check and last file modification check.
:param str pth: file path to check
:return float: number of seconds since Jan 1, 1970 00:00:00... | a3046860b0cf7a193618bc20071e8532a52f9e89 | 3,610,857 |
def auth_user(self):
"""
Authenticates visitor as logged-in user, returns data about user
:param self:
:return: {'authorized', 'user_id', 'penname'} or {'authorized: false'}
"""
try:
user_hash = self.request.cookies.get('user-id', 'None')
except AttributeError:
user_hash = ... | f1c02468031b47e4d4f94c6fe5c22157eb17ec0b | 3,610,858 |
def convert_linear_parameters(parameters: ndarray) -> ndarray:
"""
Convert all A1, A2 parameters of sum of sines function to amplitudes and phases.
For more info see approximate_sines_sum function.
Parameters
----------
parameters : ndarray
An array with all parameters of sum of sines fu... | 5645b60c3abd08897a225843c4f274c726cf85a0 | 3,610,859 |
import os
def get_int(name, default):
"""
Get an environment variable as an int.
Args:
name (str): An environment variable name
default (int): The default value to use if the environment variable doesn't exist.
Returns:
int:
The environment variable value parsed a... | a52870c1d99ee6aec9e078572b1fad962cb67131 | 3,610,860 |
def parse_sml(response):
"""Parse the json for a SML Hue motion sensor and return the data."""
if response.type == "ZLLLightLevel":
lightlevel = response.state['lightlevel']
if lightlevel is not None:
lux = round(float(10**((lightlevel-1)/10000)), 2)
dark = response.state... | 34a2395894536a25fcb9b1700e24a77e58eeb9ba | 3,610,861 |
import logging
import requests
def fetch_typeform(typeform_creds, last_successful_runtime):
"""Fetches data from Typeform."""
logging.info('Fetching data from Typeform')
header_dict = {'Authorization': 'Bearer {token}'.format(token=typeform_creds['typeform_api_key']), # noqa: E501
}
... | 0798f2845f6b585b8ae428b2d4e6e4dccb28ce80 | 3,610,862 |
def lematize(words):
"""Lematizes words (need to be preprocessed first)
Parameters
----------
words : list of str
Returns
-------
list of str
"""
lemmatizer = WordNetLemmatizer()
doc = [lemmatizer.lemmatize(x[0], wordnet_tags(x[1])) for x in pos_tag(words)]
return ' '.join(... | 007224209084b3a0b908a22e9e3347ee0df7745c | 3,610,863 |
import cv2
def resize_image_with_padding(img_bgr, desired_size=224):
"""
padding resize 方法
"""
old_size = img_bgr.shape[:2] # old_size is in (height, width) format
ratio = float(desired_size) / max(old_size)
new_size = tuple([int(x * ratio) for x in old_size])
# new_size should be in (... | 8b5387fc7c1e990f74ceada1a4ef57b8fe4b7963 | 3,610,864 |
import logging
import sys
def setup_logging():
""" setup the logging system """
base_log = logging.getLogger()
handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(logging.Formatter("%(asctime)s %(levelname)s [%(filename)s:%(lineno)d] %(message)s"))
base_log.addHandler(handler)
... | 0567115913fbc8ebe314f8ba0fc7db9bbaaf38c5 | 3,610,865 |
def load_module(name):
"""load a module
Args:
name: python dotted namespace path of the module to import
Returns:
imported module
Raises:
FailedImport if importing fails
"""
m = __import__(name)
# __import__('foo.bar') returns foo, so...
for bit in name.split('.')[1:]:
m = getattr(m, ... | 6cfcb58fccbf7d0c6de22a561312aff8931b8317 | 3,610,866 |
def make_predictions_dominant_v2(
damage_probs: np.ndarray, min_size=32, assign_dominant=True, max_building_area=4096, min_solidity=0.9
):
"""
Combines floodfill and dominant postprocessing
:param damage_probs:
:param min_size:
:param assign_dominant:
:param max_building_area:
:param min... | 64d51b083c4c4f71d84b61b4deebf5a0799c5c06 | 3,610,867 |
def draw_rectangle(image, corner_A, corner_B, color, thickness):
""" Draws a filled rectangle from ``corner_A`` to ``corner_B``.
# Arguments
image: Numpy array of shape ``[H, W, 3]``.
corner_A: List of length two indicating ``(y, x)`` openCV coordinates.
corner_B: List of length two ind... | 101bd8212e8a84a4a76b148b089d1250f9b85eef | 3,610,868 |
import re
def parse(inFile):
"""Parse the tomtom output file
Args:
tomtom.txt output file
Returns:
A dict between motif Ids and list of matched motif Ids
"""
#dict between query and target Ids
matchDict = {}
#read the tomtom.txt file and see if any known are found
with open(inFile, 'rb') as handler:
fo... | bcac3a1cac6b705f18d244b84314a2d86c9b6348 | 3,610,869 |
def _get_listeners(alb_id):
"""
"""
host, port = get_etcd_addr()
client = etcd.Client(host=host, port=int(port))
listeners = {}
try:
listeners_prefix = '/alb/{name}/listeners'.format(name=alb_id)
for i in client.read(listeners_prefix).children:
listener_id = i.key[1:... | f813566f903fa0b8f71318e4e536b5d236e58c31 | 3,610,870 |
def read_extra_stats2169(fp, fh, wl=None):
"""
These structures appear optionally, but always in this order.
"""
total_read = 0
if fh.sa_proc:
c_read = 0
for i in range(fh.sa_proc):
cpu_stats = StatsOneCpu2169()
ret = fp.readinto(cpu_stats)
check_r... | 0b46f7b39376a3ce67b61c24b3a98a4eff23d095 | 3,610,871 |
import torch
def project_simplex(v, z=1.0):
"""Project a vector v onto the simplex.
That is, return argmin_w ||w - v||^2 where w >= 0 elementwise and sum(w) = z.
Parameters:
v: Tensor of shape (batch_size, n)
z: real number
Return:
Projection of v on the simplex, along the last... | 80c3ec1b4bb94681b5515840da27a32a09512680 | 3,610,872 |
def uniquify(iterable):
"""
Make unique list while preserving order.
"""
unique = []
for entry in iterable:
if entry not in unique:
unique.append(entry)
return unique | a579c5e4cf8b38213fbc9cdcac2c122586bab97a | 3,610,873 |
def execute_paasta_cluster_boost_on_remote_master(
clusters,
system_paasta_config,
action,
pool,
duration=None,
override=None,
boost=None,
verbose=0,
):
"""Returns a string containing an error message if an error occurred.
Otherwise returns the output of run_paasta_cluster_boost(... | b6e1919e3004f47a4a5693889944c9d026793e2e | 3,610,874 |
def as_bytes(data) -> bytes:
"""Converts the input into bytes. Input data should be a Payload, string, bytes,
dict, list, or a file-like object.
Args:
data: input data
Returns:
bytes: bytes representation of the input data
"""
bytes_data = None
if isinstance(data, str):
... | 5900652fc67167dae3f53b3a753f141ae3caf1ee | 3,610,875 |
def get_selection_for_new_device(selection, insert_left=False):
"""
Returns a device, depending on the type of object that is selected at this moment.
For drum pads, it returns the last device in the pads chain.
If the selected object is no device, it returns the selected deviec.
"""
selected = ... | e3bf22b1fd2dd07e1d46dc00597a971cb74d721e | 3,610,876 |
def rook_attack(board):
"""
Question 22.7: Given 2D array of 1s and 0s, where
0s encode positions of rooks on n x m chessboard,
update array to contain 0s at all positions which
can be attacked by rooks
"""
num_rows = len(board)
num_cols = len(board[0])
first_row_attacked = False
... | a8ae4b940bccf829daceb11b59fe18e9fc591694 | 3,610,877 |
def repr2(val, **kwargs):
"""
Makes a pretty and easy-to-doctest string representation!
This is an alternative to repr, and `pprint.pformat` that attempts to be
both more configurable and generate output that is consistent between
python versions.
Args:
val (object): an arbitrary pytho... | 49cc16120f6a24f9690c48b134c50f043209d1d8 | 3,610,878 |
def exec_code(*, source=None, path=None, include=None, lang=None):
"""This uses check_syntax to see if the code is valid and, if so,
executes it into a globals dict containing only
``{"__name__": "__main__"}``.
If no ``SyntaxError`` exception is raised, this dict is returned;
otherwise, an empty dic... | 1e1988250a17d25926086fd5a622b569c57f2494 | 3,610,879 |
from pathlib import Path
import yaml
def read_config():
"""Read the config file for cenv from the users-home path if it exists.
If there is no user-config-file the default one is used.
Returns:
the content of the read config file.
"""
user_config_path = Path.home() / '.config/cenv/cenv.... | 83322b77fcdb1030179309f7139cf9e6df9a8232 | 3,610,880 |
from typing import Dict
from typing import Any
def create_default_metadata() -> Dict[str, Any]:
"""Creates a dictionary with the default metadata."""
return {
'title': 'Default title',
'base_url': 'https://example.org',
'description': 'Default description',
'language': 'en-US',... | 2ee6aeffaafd209cb93e33bd42291ac3c12b10d8 | 3,610,881 |
def _is_fingerprint_valid(fingerprint):
"""Validate that a fingerprint is in the right format"""
if len(fingerprint) != 40:
return False
elif set(fingerprint).difference(ALLOWED_FINGERPRINT_CHARACTERS):
return False
else:
return True | 8328b8ab4a9e5db12073989c635749348fc3b7b6 | 3,610,882 |
import sys
def exec_command(doit, logger, cmd, msg):
"""
Execute given command and return its output.
Exit the program on failure.
"""
cmd = Command(cmd, logger=logger, redirect_stderr=False)
if not doit:
logger.info(cmd)
return
cmd.execute()
if cmd.getstate() is not Co... | 6e30b628f4dd73c04ce8ae8c673b82da16648cac | 3,610,883 |
def ga_service_account_private_key()-> t.Optional[str]:
"""Google Service Account private_key used to download the Google Analytics Data"""
return None | e91365bb80b12f11203543d320f7682384c8ab77 | 3,610,884 |
import os
def paths_differ(path1,path2):
"""Check whether two paths differ."""
if os.path.isdir(path1):
if not os.path.isdir(path2):
return True
for nm in os.listdir(path1):
if paths_differ(os.path.join(path1,nm),os.path.join(path2,nm)):
return True
... | 89268b17eed7bb70a8f123c99a818fce85be9053 | 3,610,885 |
import signal
def get_doppler(csi, rate=1000):
"""get_doppler_spectrum
Args:
csi: csidata.csi[:, :, :, :1]
rate: sample rate
"""
# Filter Configuration
half_rate = rate / 2
upper_order, upper_stop = 6, 60
lower_order, lower_stop = 3, 2
lb, la = signal.butter(upper_orde... | 5824b8bb8f2181a963ffdb61ace1af30a071662c | 3,610,886 |
def HideArea(start, end, description, header, footer, color):
"""
Hide an area
Hidden areas - address ranges which can be replaced by their descriptions
@param start: area start
@param end: area end
@param description: description to display if the area is collapsed
@param he... | a6e18c96c2873d058af877a461e7657aec106318 | 3,610,887 |
def var_asymmetry ( a , b , name = '' , title = '' ) :
"""``Asymmetry'' f(x) = (a-b)/(a+b)
>>> a = ...
>>> b = ...
>>> e = var_asymmetry ( a , b )
"""
f1 = isinstance ( v1 , num_types )
f2 = isinstance ( v2 , num_types )
if f1 and f2 :
r = ( float ( v1 ) - float ( v2 ) )... | 508ec2273cb60ab0f357cd89b2605d8ee143d7d4 | 3,610,888 |
import doctest
def run_doctests(module, flags=FLAGS):
"""
Runs doctests with our default flags
"""
return doctest.testmod(module, optionflags=flags) | 98e312b95809bea8858a1df034b21043e388aac5 | 3,610,889 |
def posterize(image, bits):
"""
Reduce the number of bits for each color channel.
:param image: The image to posterize.
:param bits: The number of bits to keep for each channel (1-8).
:return: An image.
"""
lut = []
mask = ~(2 ** (8 - bits) - 1)
for i in range(256):
lut.appe... | 6f8eb8c6495e961dacfa8ffde954bd62fd83583b | 3,610,890 |
def early_downsample_count(nyquist, filter_cutoff, hop_length, n_octaves):
"""Compute the number of early downsampling operations"""
downsample_count1 = max(
0, int(np.ceil(np.log2(0.85 * nyquist / filter_cutoff)) - 1) - 1
)
# print("downsample_count1 = ", downsample_count1)
num_twos = next... | c3b2c3dbfb1bf355221d04fb6dba51eabda6b72e | 3,610,891 |
import os
import _random
def listusers(l, b, i):
"""
!d List all users who have files
!r user
"""
b.l_say('Users:', i, 0)
for f in os.listdir(os.path.join('..', 'files', 'users')):
b.l_say(' %s' % (_random() + f.replace('.json', '')), i, 0)
return True | dbbb41cc463facfb4bb2458276e438f590c1aee2 | 3,610,892 |
def endswith(stringarr, pat):
"""
Check whether each element ends with the substring 'pat', and returns
a boolean array of the results.
For now, 'pat' must be a string literal.
"""
define_pat = "let pat = {};".format(string_to_weld_literal(pat))
return """
{define_pat}
let lenPat ... | caa703f257a691ee72c20ef54f3e8212b4b7d262 | 3,610,893 |
import typing
from typing import Counter
def batchnorm_flop_jit(
inputs: typing.List[object], outputs: typing.List[object]
) -> typing.Counter[str]:
"""
This method counts the flops for batch norm.
Args:
inputs (list(torch._C.Value)): The input shape in the form of a list of
jit ob... | 1c88d177d286fb715ef9d95d0c192fc7672f671d | 3,610,894 |
def manifest_licenses(licensestr, dont_want_licenses, canonical_license, d):
"""Given a license string and dont_want_licenses list,
return license string filtered and a list of licenses"""
manifest = ManifestVisitor(dont_want_licenses, canonical_license, d)
try:
elements = manifest.get_eleme... | 89f04c357d7d40ef4905fd4e4ddc55cc63dc1d33 | 3,610,895 |
def app():
"""Import the test app"""
app = Flask(__name__)
app.config["OPA_SECURED"] = True
app.config["OPA_URL"] = 'http://localhost:8181/v1/data/examples/allow'
app.opa = OPA(app, input_function=parse_input).secured()
init_app(app)
return app | c9d775b9971aad0be601cecb132ea673afc8ac81 | 3,610,896 |
def regress_array(input, regression):
"""
Works out coefficients for linear regression on the previous sample, for
each axis of the array.
@param [in] input The array to be compressed; must contain floats or doubles.
@param [in] regression True if we are doing regression; if false,
... | e8dc8d9d854191356e7266002831e1f47de5f868 | 3,610,897 |
def check(file_name_a, file_name_b):
"""
check if the two input files are considered equal, for the purpose of this specific homework
:param file_name_a: output of one run
:param file_name_b: output of another run
:return: 0 if the files are equal (the content might be not identical)
"""
re... | 0cdcef0921c922ef25b897521a0d1b7e69da3d38 | 3,610,898 |
def cubic_bezier_spline(
p0: float,
p1: float,
p2: float,
p3: float
):
"""
Create a sigle cubic bezier spline
:param p0: starting point
:param p1: control point 1
:param p2: control point 2
:param p3: end point
:return: a cubic polynomial function that represe... | 4601d4dd119bd374cc075bf13504512a52bf43a1 | 3,610,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.