content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def remove_rule(rule_id):
"""Remove a single rule"""
ruleset = packetfilter.get_ruleset()
ruleset.remove(rule_id)
packetfilter.load_ruleset(ruleset)
save_pfconf(packetfilter)
return redirect(url_for('rules', message=PFWEB_ALERT_SUCCESS_DEL), code=302) | fe45a3d5af532ff67e8aef21ab093438818c6dbc | 6,749 |
def HexToMPDecimal(hex_chars):
""" Convert bytes to an MPDecimal string. Example \x00 -> "aa"
This gives us the AppID for a chrome extension.
"""
result = ''
base = ord('a')
for i in xrange(len(hex_chars)):
value = ord(hex_chars[i])
dig1 = value / 16
dig2 = value % 16
result += chr(dig1 ... | 5d81c0e1ee3f4f94e615578e132377b803beb47b | 6,750 |
def fit_growth_curves(input_file, file_data_frame, file_data_units,
condition_unit, time_unit, cell_density_unit):
"""
:Authors:
Chuankai Cheng <[email protected]> and J. Cameron Thrash <[email protected]>
:License:
MIT
:Version:
1.0
:Date:
2021-03-17
:Repository: https://github.com/t... | d551a094ea398e09dcc88f8f9668922b3e665317 | 6,751 |
def stringify(li,delimiter):
""" Converts list entries to strings and joins with delimiter."""
string_list = map(str,li)
return delimiter.join(string_list) | a4c35a19d8ea654a802cd3f92ababcbdfdf0ecfb | 6,752 |
def norm_w(x, w):
"""
Compute sum_i( w[i] * |x[i]| ).
See p. 7.
"""
return (w * abs(x)).sum() | a9825750cb6ee0bbbe87b0c4d1bd132bcfca90db | 6,753 |
def _tensor_run_opt_ext(opt, momentum, learning_rate, gradient, weight, moment):
"""Apply momentum optimizer to the weight parameter using Tensor."""
success = True
success = F.depend(success, opt(weight, moment, learning_rate, gradient, momentum))
return success | 89ae490ba0f05455dff03bcd57d4b6f52f7d8327 | 6,754 |
from typing import Dict
import yaml
def get_config_settings(env: str = "dev") -> Dict:
"""
Retrieves configuration from YAML file
"""
config_fh = construct_config_path(env)
with open(config_fh, "r") as f:
data = yaml.safe_load(f)
return data | 190a7f8cb2a297ee4ae6d5734d4d9f521a18bb3f | 6,755 |
def get_all(connection: ApiConnection, config: str, section: str = None) -> dict:
"""Get all sections of a config or all values of a section.
:param connection:
:param config:UCI config name
:param section:[optional] UCI section name
:return: JSON RPC response result
"""
return request(conne... | be4a76f87398ce1d4e0765314266647867964e39 | 6,756 |
def load_module(module, app):
"""Load an object from a Python module
In:
- ``module`` -- name of the module
- ``app`` -- name of the object to load
Return:
- (the object, None)
"""
r = __import__(module, fromlist=('',))
if app is not None:
r = getattr(r, app)
re... | 858d9d0bf91ff7d83ad391218b8ff1b37007b43b | 6,757 |
def get_routes(app: web.Application) -> list:
"""
Get the full list of defined routes
"""
return get_standard_routes(app) + get_custom_routes(app) | 7f5d365c28ee45096e089ee6913d3aec4d8214d8 | 6,758 |
def cb_round(series: pd.Series, base: Number = 5, sig_dec: int = 0):
""" Returns the pandas series (or column) with values rounded per the
custom base value
Args:
series (pd.Series): data to be rounded
base (float): base value to which data should be rounded (may be
deci... | 29599898fa8686c260e89d2efcdcceec108d5b4c | 6,759 |
def makeGaussian(size, sigma=3, center=None):
""" Make a square gaussian kernel.
size is the length of a side of the square
fwhm is full-width-half-maximum, which
can be thought of as an effective radius.
"""
x = np.arange(0, size, 1, float)
y = x[:, np.newaxis]
if center is None:
x0 = y0 = size ... | 8efef3cc265375d5412107a465a97380e8c4d101 | 6,760 |
import torch
def average_relative_error(y_pred, y_true):
"""Calculate Average Relative Error
Args:
y_true (array-like): np.ndarray or torch.Tensor of dimension N x d with actual values
y_pred (array-like): np.ndarray or torch.Tensor of dimension N x d with predicted values
Returns:
... | 2243eb82c78ff03181be3c10d50c3aa000e8476c | 6,761 |
from unittest.mock import Mock
def make_subprocess_hook_mock(exit_code: int, output: str) -> Mock:
"""Mock a SubprocessHook factory object for use in testing.
This mock allows us to validate that the RenvOperator is executing
subprocess commands as expected without running them for real.
"""
resu... | a047608503be8bc7fc4b782139e7d12145efb3cd | 6,762 |
def binstr2int(bin_str: str) -> int:
"""转换二进制形式的字符串为10进制数字, 和int2binstr相反
Args:
bin_str: 二进制字符串, 比如: '0b0011'或'0011'
Returns:
转换后的10进制整数
"""
return int(bin_str, 2) | 87c6ac16c2215e533cb407407bef926ed8668e3e | 6,763 |
def _nodeset_compare(compare, a, b, relational=False):
"""
Applies a comparison function to node-sets a and b
in order to evaluate equality (=, !=) and relational (<, <=, >=, >)
expressions in which both objects to be compared are node-sets.
Returns an XPath boolean indicating the result of the com... | 5751b793662689a1e0073cfe5fc4b86505952dcd | 6,764 |
def test_cl_shift(options):
"""
Create tests for centerline shifts
8 out of 8 points are on one side of the mean
>= 10 out of 11 points are on one side of the mean
>= 12 out of 14 points are on one side of the mean
>= 14 out of 17 points are on one side of the mean
>= 16 out of 20 points ar... | 60d874c8b1484ff23c4791043eae949912a969d0 | 6,765 |
def _scale(tensor):
"""Scale a tensor based on min and max of each example and channel
Resulting tensor has range (-1, 1).
Parameters
----------
tensor : torch.Tensor or torch.autograd.Variable
Tensor to scale of shape BxCxHxW
Returns
-------
Tuple (scaled_tensor, min, max), where min and max ar... | 64eed9bd70c543def6456f3af89fa588ec35bca8 | 6,766 |
def get_moscow_oh(opening_hours):
"""
returns an OpeningHourBlock from a fake json
corresponding to a POI located in moscow city
for different opening_hours formats.
"""
return get_oh_block(opening_hours, lat=55.748, lon=37.588, country_code="RU") | 42f795e262753cc82d8689c2a98e6a82e143a2c3 | 6,767 |
def get_firebase_credential_errors(credentials: str):
""" Wrapper to get error strings for test_firebase_credential_errors because otherwise the
code is gross. Returns None if no errors occurred. """
try:
test_firebase_credential_errors(credentials)
return None
except Exception as e... | fbca79e837a3d6dc85ee90bfd426008c6ce25ac2 | 6,768 |
def url(endpoint, path):
"""append the provided path to the endpoint to build an url"""
return f"{endpoint.rstrip('/')}/{path}" | dee733845984bfc4cf5728e9614cce08d19a2936 | 6,769 |
def is_collision(line_seg1, line_seg2):
"""
Checks for a collision between line segments p1(x1, y1) -> q1(x2, y2)
and p2(x3, y3) -> q2(x4, y4)
"""
def on_segment(p1, p2, p3):
if (p2[0] <= max(p1[0], p3[0])) & (p2[0] >= min(p1[0], p3[0])) & (p2[1] <= max(p1[1], p3[1])) & (p2[1] >= min(p1[1],... | 17dba61faebe50336cbc2cd2cc56c49474db5431 | 6,770 |
import numpy
def plot_bar_graph_one_time(
example_table_xarray, time_index, predictor_indices, info_string=None,
figure_object=None, axes_object=None):
"""Plots predictors at one time as bar graph.
:param example_table_xarray: xarray table in format returned by
`example_io.read_file`.... | 5b1faab11bd6e79bd617ca23a8f49aeb83de2aae | 6,771 |
def reshape_nda_to_2d(arr) :
"""Reshape np.array to 2-d
"""
sh = arr.shape
if len(sh)<3 : return arr
arr.shape = (arr.size/sh[-1], sh[-1])
return arr | 11c721b938e45fd07d2ed1674a569e6836913ff3 | 6,772 |
async def async_setup(hass, config):
"""Initialize the DuckDNS component."""
domain = config[DOMAIN][CONF_DOMAIN]
token = config[DOMAIN][CONF_ACCESS_TOKEN]
session = async_get_clientsession(hass)
result = await _update_duckdns(session, domain, token)
if not result:
return False
as... | 7208d0a25b219b6decbae314618e219705224a5a | 6,773 |
def mock_signal(*args):
"""Mock creation of a binary signal array.
:return: binary array
:rtype: np.ndarray
"""
signal = np.array([1, 0, 1])
return signal | ebeb1f40a43c2c51d941208da78e0bfc0acb6530 | 6,774 |
def matmul(a, b):
"""np.matmul defaults to bfloat16, but this helper function doesn't."""
return np.matmul(a, b, precision=jax.lax.Precision.HIGHEST) | a4efb25933a25067b0b37ada8271f09b76929cb8 | 6,775 |
def predictions(logit_1, logit_2, logit_3, logit_4, logit_5):
"""Converts predictions into understandable format.
For example correct prediction for 2 will be > [2,10,10,10,10]
"""
first_digits = np.argmax(logit_1, axis=1)
second_digits = np.argmax(logit_2, axis=1)
third_digits = np.argmax(logit... | 99e22cc4808634e6510196f2e9e79cba9dafd61c | 6,777 |
def execute_parent(parent_path, child_path, input_tensor_npy, return_full_ctx=False):
"""Execute parent model containing a single StreamingDataflowPartition by
replacing it with the model at child_path and return result."""
parent_model = load_test_checkpoint_or_skip(parent_path)
iname = parent_model.g... | 2757d22c46ee89f34cc89c702393d4a42d275c28 | 6,778 |
def fibonacci(position):
"""
Based on a position returns the number in the Fibonacci sequence
on that position
"""
if position == 0:
return 0
elif position == 1:
return 1
return fibonacci(position-1)+fibonacci(position-2) | cc4fe0860fa97234ead2179e18d208a8567e0cb3 | 6,780 |
def visualize_gebco(source, band, min=None, max=None):
"""
Specialized function to visualize GEBCO data
:param source: String, Google Earth Engine image id
:param band: String, band of image to visualize
:return: Dictionary
"""
data_params = deepcopy(DATASETS_VIS[source]) # prevent mutation... | ccd382f1e1ede4cbe58bca6fc7eec15aa1b0a85a | 6,781 |
import asyncio
import functools
def bound_concurrency(size):
"""Decorator to limit concurrency on coroutine calls"""
sem = asyncio.Semaphore(size)
def decorator(func):
"""Actual decorator"""
@functools.wraps(func)
async def wrapper(*args, **kwargs):
"""Wrapper"""
... | 030e4dea0efccf9d5f2cbe4a40f3e6f32dfef846 | 6,783 |
import socket
def _download_file(url, required_length, STRICT_REQUIRED_LENGTH=True):
"""
<Purpose>
Given the url, hashes and length of the desired file, this function
opens a connection to 'url' and downloads the file while ensuring its
length and hashes match 'required_hashes' and 'required_length'.... | a9df32371f24a85971807354636621224fc8f7bd | 6,784 |
def tune_speed_librosa(src=None, sr=_sr, rate=1., out_type=np.ndarray):
"""
变语速
:param src:
:param rate:
:return:
"""
wav = anything2wav(src, sr=sr)
spec = librosa.stft(wav)
spec = zoom(spec.T, rate=1 / rate, is_same=0).T
out = librosa.istft(spec)
# out = librosa.griffinlim(s... | 423b83c6a266e8ee2b259bf3497e53ff2087ca44 | 6,785 |
import pathlib
def fqn_from_file(java_filepath: pathlib.Path) -> str:
"""Extract the expected fully qualified class name for the given java file.
Args:
java_filepath: Path to a .java file.
"""
if not java_filepath.suffix == ".java":
raise ValueError("{} not a path to a .java file".for... | cb1d515af968c1653d31f0529ce40fa6241cf1f4 | 6,786 |
def assert_raises(*args, **kwargs):
"""Assert an exception is raised as a context manager or by passing in a
callable and its arguments.
As a context manager:
>>> with assert_raises(Exception):
... raise Exception
Pass in a callable:
>>> def raise_exception(arg, kwarg=None):
... ... | 6ef00a131f6ce5192e88fe9bab34f5cd04dd5a8a | 6,787 |
import click
def proxy(ctx, control, host, port, socket, proxy):
"""Settings to configure the connection to a Tor node acting as proxy."""
if control == 'port':
if host is None or port is None:
raise click.BadOptionUsage(
option_name='control',
message=f"--... | 4fe25cb7dc38116e26fe61b43e3903908e098459 | 6,788 |
import gzip
def get_gzip_uncompressed_file_size(file_name):
"""
this function will return the uncompressed size of a gzip file
similar as gzip -l file_name
"""
file_obj = gzip.open(file_name, 'r')
file_obj.seek(-8, 2)
# crc32 = gzip.read32(file_obj)
isize = gzip.read32(file_obj)
re... | bf1e40a83098fa32c95959e28069e4a4d4dcc2d7 | 6,789 |
def Capitalize(v):
"""Capitalise a string.
>>> s = Schema(Capitalize)
>>> s('hello world')
'Hello world'
"""
return str(v).capitalize() | 9072ea91b946694bbb1410fb10a5b1b1f5cdd7c2 | 6,790 |
def pg_index_exists(conn, schema_name: str, table_name: str, index_name: str) -> bool:
"""
Does a postgres index exist?
Unlike pg_exists(), we don't need heightened permissions on the table.
So, for example, Explorer's limited-permission user can check agdc/ODC tables
that it doesn't own.
"""
... | 98ebdc0db7f3e42050e61205fd17309d015352a0 | 6,791 |
def create_mock_data(bundle_name: str,
user_params: dict):
"""
create some mock data and push to S3 bucket
:param bundle_name: str, bundle name
:param user_params: dict, what parameters to save
:return:
"""
api.context(context_name)
api.remote(context_name, remote_co... | 0fd377eac24555306aceff26a61d4a2b4666d33d | 6,792 |
def _vertex_arrays_to_list(x_coords_metres, y_coords_metres):
"""Converts set of vertices from two arrays to one list.
V = number of vertices
:param x_coords_metres: length-V numpy array of x-coordinates.
:param y_coords_metres: length-V numpy array of y-coordinates.
:return: vertex_list_xy_metres... | ef5bed973f684670f979f6cdb0fcfc38b45a4557 | 6,793 |
from typing import Optional
from typing import Dict
from typing import Any
def info_from_apiKeyAuth(token: str, required_scopes) -> Optional[Dict[str, Any]]:
"""
Check and retrieve authentication information from an API key.
Returned value will be passed in 'token_info' parameter of your operation functi... | 29fec65450780e14dfc94979ba2fb73c00d2a4bf | 6,794 |
from datetime import datetime
def convert_unix2dt(series):
"""
Parameters
----------
series : column from pandas dataframe in UNIX microsecond formatting
Returns
-------
timestamp_dt : series in date-time format
"""
if (len(series) == 1):
unix_s = series/1000
else: ... | 92b912ba85b123e9f368b3613bff4a374826130a | 6,795 |
import re
def sentence_segment(text, delimiters=('?', '?', '!', '!', '。', ';', '……', '…'), include_symbols=True):
"""
Sentence segmentation
:param text: query
:param delimiters: set
:param include_symbols: bool
:return: list(word, idx)
"""
result = []
delimiters = set([item for ite... | c8860a872e779873330eaded8e9951cabdbba01e | 6,797 |
def time_rep_song_to_16th_note_grid(time_rep_song):
"""
Transform the time_rep_song into an array of 16th note with pitches in the onsets
[[60,4],[62,2],[60,2]] -> [60,0,0,0,62,0,60,0]
"""
grid_16th = []
for pair_p_t in time_rep_song:
grid_16th.extend([pair_p_t[0]] + [0 for _ in range(pair_p_t[1]-1)])
retur... | 8986819bd39ae4830d04bf40ab158d310bb45485 | 6,798 |
def _double_threshold(x, high_thres, low_thres, n_connect=1, return_arr=True):
"""_double_threshold
Computes a double threshold over the input array
:param x: input array, needs to be 1d
:param high_thres: High threshold over the array
:param low_thres: Low threshold over the array
:param n_con... | 74a34ed39336c35dfc7eb954af12bb30b3089609 | 6,799 |
def upload():
"""
Implements the upload page form
"""
return render_template('upload.html') | 4dda3418621b3894234b049e22f810304050a398 | 6,800 |
def detect_changepoints(points, min_time, data_processor=acc_difference):
""" Detects changepoints on points that have at least a specific duration
Args:
points (:obj:`Point`)
min_time (float): Min time that a sub-segmented, bounded by two changepoints, must have
data_processor (functio... | 872c2e4d5d8cbb33de100495bc8d9ddb050400c8 | 6,801 |
def quad1(P):
"""[summary]
Arguments:
P (type): [description]
Returns:
[type]: [description]
"""
x1, z1, x2, z2 = P
return (Fraction(x1, z1) - Fraction(x2, z2))**2 | f3e9c34740038242c29f4abbe168df573da12390 | 6,803 |
def update_position(position, velocity):
"""
:param position: position(previus/running) of a particle
:param velocity: the newest velocity that has been calculated during the specific iteration- new velocity is calculated
before the new position
:return: list - new position
"""
pos = []
... | 7734e4021d958f42d974401b78331bcd2911ac92 | 6,804 |
def respond_batch():
"""
responses with [{"batch": [{blacklist_1_name: true}, ]}]
"""
result = get_result(request)
return jsonify([{"batch": result}]) | 97b1ceaafa88aacba09fc0ba6c564e87bfb07b66 | 6,805 |
from typing import Union
import types
from typing import Iterable
def get_iterable_itemtype(obj):
"""Attempts to get an iterable's itemtype without iterating over it,
not even partly. Note that iterating over an iterable might modify
its inner state, e.g. if it is an iterator.
Note that obj is expecte... | 103a3928e4a161f119c8664e58ba7e6270a94a14 | 6,806 |
import re
def getTimerIPs():
"""
returns list of ip addr
"""
client = docker.from_env()
container_list = client.containers.list()
timer_ip_list = []
for container in container_list:
if re.search("^timer[1-9][0-9]*", container.name):
out = container.exec_run("awk 'END... | e4bc28407fb8b292df9a813809998bf6b323c938 | 6,807 |
def BRepBlend_BlendTool_NbSamplesV(*args):
"""
:param S:
:type S: Handle_Adaptor3d_HSurface &
:param v1:
:type v1: float
:param v2:
:type v2: float
:rtype: int
"""
return _BRepBlend.BRepBlend_BlendTool_NbSamplesV(*args) | 99af0513463ce64d5369fde226e679e48a7e397a | 6,809 |
def get_response(session, viewstate, event_validation, event_target, outro=None, stream=False, hdfExport=''):
"""
Handles all the responses received from every request made to the website.
"""
url = "http://www.ssp.sp.gov.br/transparenciassp/"
data = [
('__EVENTTARGET', event_target),
... | 0bb31b29fb8fb8a0fe007f87d88b8d131fd4308c | 6,811 |
def matchVuln(vuln, element, criteria):
"""
================================================================================
Name:
matchVuln
Description:
Sets the finding details of a given VULN.
Parameter(s):
vuln: The VULN element to be searched.
element: ... | 7158b263fd70e921b0b131fd8f2537223521570f | 6,812 |
def require(*modules):
"""Check if the given modules are already available; if not add them to
the dependency list."""
deplist = []
for module in modules:
try:
__import__(module)
except ImportError:
deplist.append(module)
return deplist | 88df83cd33d8bddea63e4d2fbfb4d8351a3c23b1 | 6,813 |
def fixture_base_context(
env_name: str,
) -> dict:
"""Return a basic context"""
ctx = dict(
current_user="a_user",
current_host="a_host",
)
return ctx | fbfed439f784bdd64e93910bbb581955200af2bb | 6,814 |
from typing import Optional
from typing import List
import yaml
def definition(server: KedroLanguageServer, params: TextDocumentPositionParams) -> Optional[List[Location]]:
"""Support Goto Definition for a dataset or parameter.
Currently only support catalog defined in `conf/base`
"""
if not server.is... | 7713d92fafa2f0acf68ee34b4dc83f1d5100a9b3 | 6,816 |
def augmented_neighbors_list(q_id,
neighbors,
is_training,
processor,
train_eval=False):
"""Retrieve and convert the neighbors to a list.
Args:
q_id: a question id
neighbors: a table mapping ... | 3ae8756a60fdfa4ce3fc6de91d364c5edebcc0ff | 6,817 |
def estimate_tau_exp(chains, **kwargs):
"""
Estimate the exponential auto-correlation time for all parameters in a chain.
"""
# Calculate the normalised autocorrelation function in each parameter.
rho = np.nan * np.ones(chains.shape[1:])
for i in range(chains.shape[2]):
try:
... | 3de72cec6fa079913489c9c1b9b72ff572cedf60 | 6,818 |
def lda_model_onepass(dictionary, corpus, topics):
"""Create a single pass LDA model"""
start_time = time.time()
model = LdaMulticore(corpus, id2word = dictionary, num_topics = topics)
model.save(""./data/lda/all_topics_single.lda"")
print(model.print_topics(-1))
print("\nDone in {}".format(tim... | 3a88250af8c83fb23112b15cacaad39eeaebb27c | 6,819 |
import dataclasses
import pydantic
def paramclass(cls: type) -> type:
""" Parameter-Class Creation Decorator
Transforms a class-definition full of Params into a type-validated dataclass,
with methods for default value and description-dictionary retrieval.
Hdl21's `paramclass`es are immutable, str... | 5f5b4b6612d3afc7858a4b26419d9238aaf6ec92 | 6,820 |
import string
def text_process(mess):
"""
Takes in a string of text, then performs the following:
1. Remove all punctuation
2. Remove all stopwords
3. Returns a list of the cleaned text
"""
# Check characters to see if they are in punctuation
nopunc = [char for char in mess if char not... | 9069df05eb4d1b87c2091a64e7dd55754e362334 | 6,821 |
def IntCurveSurface_ThePolyhedronToolOfHInter_IsOnBound(*args):
"""
:param thePolyh:
:type thePolyh: IntCurveSurface_ThePolyhedronOfHInter &
:param Index1:
:type Index1: int
:param Index2:
:type Index2: int
:rtype: bool
"""
return _IntCurveSurface.IntCurveSurface_ThePolyhedronToolOf... | bd64cb058793730197a805d7660fe4c8dc4f7af5 | 6,822 |
def read_mrc_like_matlab(mrc_file):
""" Read MRC stack and make sure stack is 'Fortran indexed' before returning it. """
mrc_stack = mrcfile.open(mrc_file).data
fortran_indexed_stack = c_to_fortran(mrc_stack)
return fortran_indexed_stack | 245a7371e94ae6c05248d24e231ce56afc937dd1 | 6,823 |
from typing import List
def freeze_session(session: tf.Session,
keep_var_names: List[str] = None,
output_names: List[str] = None,
clear_devices: bool = True) -> tf.GraphDef:
"""
Freezes the state of a session into a pruned computation graph.
Creates... | 4754de754217031ac6151bc3360b6969a46a4e66 | 6,824 |
def evaluation(evaluators, dataset, runners, execution_results, result_data):
"""Evaluate the model outputs.
Args:
evaluators: List of tuples of series and evaluation functions.
dataset: Dataset against which the evaluation is done.
runners: List of runners (contains series ids and loss... | ef3470edb8b2336bdc54507a5df8023f8095b995 | 6,827 |
def bestof(reps, func, *args, **kwargs):
"""Quickest func() among reps runs.
Returns (best time, last result)
"""
best = 2 ** 32
for i in range(reps):
start = timer()
ret = func(*args, **kwargs)
elapsed = timer() - start
if elapsed < best: best = elapsed
return (b... | 975d106a79b79cab3bc287d8b658585f45dd648d | 6,828 |
import tempfile
def gdal_aspect_analysis(dem, output=None, flat_values_are_zero=False):
"""Return the aspect of the terrain from the DEM.
The aspect is the compass direction of the steepest slope (0: North, 90: East, 180: South, 270: West).
Parameters
----------
dem : str
Path to file stor... | ec8aa51f799368508f78dcff81ae991087b56132 | 6,829 |
import requests
import json
def _handle_braze_response(response: requests.Response) -> int:
"""Handles server response from Braze API.
The amount of requests made is well
below the limits for the given API endpoint therefore Too Many Requests
API errors are not expected. In case they do, however, occ... | da8aca622f7a4812235797501a1afe56cc760ea4 | 6,830 |
def unpack_file(filepath, tmpdir):
"""
Attempt to unpack file.
filepath is the path to the file that should be attempted unpacked.
tmpdir is a path to a temporary directory unique to this thread where
the thread will attempt to unpack files to.
Returns a list of unpacked files or an empty list.
... | 79fb80fe61145e865b128587525bc743d19e2ad0 | 6,831 |
def xarray_image_as_png(img_data, loop_over=None, animate=False, frame_duration=1000):
"""
Render an Xarray image as a PNG.
:param img_data: An xarray dataset, containing 3 or 4 uint8 variables: red, greed, blue, and optionally alpha.
:param loop_over: Optional name of a dimension on img_data. If set,... | 201cb29144054417d7eb743690601ae37558dfbd | 6,832 |
def x_section_from_latlon(elevation_file,
x_section_lat0,
x_section_lon0,
x_section_lat1,
x_section_lon1,
as_polygon=False,
auto_clean=False):
"""
This wor... | 0773cf535ee18ff91db805d692687c67bf6b2ed4 | 6,833 |
import re
def convert_not_inline(line):
""" Convert the rest of part which are not inline code but might impact inline code
This part will dealing with following markdown syntax
- strong
- scratch
- italics
- image
- link
- checkbox
- highlight
:param line: str, the not inlin... | 871abca2977fc494036c6d5aa19de789cfbfd5b9 | 6,834 |
def uniform_square_aperture(side, skypos, frequency, skyunits='altaz',
east2ax1=None, pointing_center=None,
power=False):
"""
-----------------------------------------------------------------------------
Compute the electric field or power pattern p... | 275249164bba5fae8f8652f8af1f2c8dc13c9525 | 6,835 |
def sources_table(citator):
"""
Return the content for an HTML table listing every template that the
citator can link to.
"""
rows = []
for template in citator.templates.values():
# skip templates that can't make URLs
if not template.__dict__.get('URL_builder'):
con... | 460a06e03e7ec6d5cee465001d9b828976a4da1b | 6,836 |
def parse_bot_commands(data, starterbot_id):
"""
Parses a list of events coming from the Slack RTM API to find bot commands.
If a bot command is found, this function returns a tuple of command and channel.
If its not found, then this function returns None, None.
"""
user_id, message ... | 5d614cfdf55133180425a87aedac34896a54b552 | 6,837 |
from typing import Callable
def construct_obj_in_dict(d: dict, cls: Callable) -> dict:
"""
Args
d (dict):
d[name][charge][annotation]
"""
if not isinstance(d, dict):
return d
else:
new_d = deepcopy(d)
for key, value in d.items():
if value.get... | c069fb474a6a675f8d917483435856df506ff331 | 6,838 |
def signup_user(request):
"""
Function to sing up user that are not admins
:param request: This param contain all the information associated to the request
:param type request: Request
:return: The URL to render
:rtype: str
"""
try:
log = LoggerManager('info', 'singup_manager-in... | 3ea45a9b84cb8281f3afc6997230fdcbab75f045 | 6,839 |
def haar_rand_state(dim: int) -> np.ndarray:
"""
Given a Hilbert space dimension dim this function returns a vector
representing a random pure state operator drawn from the Haar measure.
:param dim: Hilbert space dimension.
:return: Returns a dim by 1 vector drawn from the Haar measure.
"""
... | 3d374fe32fee91667747df86d79f9feb08836c61 | 6,840 |
from pathlib import Path
def is_src_package(path: Path) -> bool:
"""Checks whether a package is of the form:
├─ src
│ └─ packagename
│ ├─ __init__.py
│ └─ ...
├─ tests
│ └─ ...
└─ setup.py
The check for the path will be if its a directory with only one subdirectory
... | 36bfd704a0a71a41e9943dc9a9d19cf5e46746f8 | 6,841 |
from re import T
from typing import Optional
from re import I
def value_element(units=(OneOrMore(T('NN')) | OneOrMore(T('NNP')) | OneOrMore(T('NNPS')) | OneOrMore(T('NNS')))('raw_units').add_action(merge)):
"""
Returns an Element for values with given units. By default, uses tags to guess that a unit exists.
... | 1b111fb30369d0d3b6c506d5f02e80b5c88044d5 | 6,842 |
def get_pattern(model_id, release_id) -> list:
"""
content demo:
[
'...',
{
0.1: [
['if', 'checker.check'],
3903,
['if', 'checker.check', '*', Variable(name="ip", value='10.0.0.1')],
['if checker.check():', 'if check... | 2307180d26e687fd7057c326e15e21b7aaf81471 | 6,843 |
def bit_remove(bin_name, byte_offset, byte_size, policy=None):
"""Creates a bit_remove_operation to be used with operate or operate_ordered.
Remove bytes from bitmap at byte_offset for byte_size.
Args:
bin_name (str): The name of the bin containing the map.
byte_offset (int): Position of b... | 356ff2f3421b67790f7e224ecc49c844335864f8 | 6,844 |
def four2five(data, format_, dst_dtype='float16', need_custom_tiling=True):
"""
Convert 4-dims "data" to 5-dims,the format of "data" is defined in "format_"
Args:
data (tvm.tensor.Tensor): 4-dims tensor of type float16, float32
format_ (str): a str defined the format of "data"
dst_d... | 71de138f15e5b407a244c1670c48eb806b3be765 | 6,846 |
def MT33_SDR(MT33):
"""Converts 3x3 matrix to strike dip and rake values (in radians)
Converts the 3x3 Moment Tensor to the strike, dip and rake.
Args
MT33: 3x3 numpy matrix
Returns
(float, float, float): tuple of strike, dip, rake angles in radians
(Note: Function from MTFIT.MTconv... | 0b80df0e43bc546aa36a06858f144f32d75cb478 | 6,847 |
from generate_changelog.utilities import pairs
from typing import Optional
from typing import List
import re
def get_commits_by_tags(repository: Repo, tag_filter_pattern: str, starting_tag: Optional[str] = None) -> List[dict]:
"""
Group commits by the tags they belong to.
Args:
repository: The gi... | 1e870d2169496e183c1df8d90ddceb4e63cb1689 | 6,848 |
def GetObject():
"""
Required module function.
@returns class object of the implemented adapter.
"""
return SpacePacketAdapter | 38ddac47a1ac7a58f203fc5552a00340a542518d | 6,849 |
def parse(args):
"""Parse the command-line arguments of the `inpaint` command.
Parameters
----------
args : list of str
List of arguments, without the command name.
Returns
-------
InPaint
Filled structure
"""
struct = InPaint()
struct.files = []
while cl... | 6b3eb929ce13559f9bd3d50ee2b15dd25e967d33 | 6,851 |
from unittest.mock import Mock
from datetime import datetime
def log_context(servicer_context: Mock) -> LogContext:
"""Mock LogContext."""
context = LogContext(
servicer_context,
"/abc.test/GetTest",
Mock(name="Request"),
Mock(name="Response", ByteSize=Mock(return_value=10)),
... | 1ea1b8d4e6dad80ac8d95925a70a7f79ec84a686 | 6,852 |
import base64
def base64_decode(string):
"""
Decodes data encoded with MIME base64
"""
return base64.b64decode(string) | 38870882fca9e6595e3f5b5f8943d0bf781f006c | 6,854 |
import re
def convert_operand_kind(operand_tuple):
"""Returns the corresponding operand type used in spirv-tools for the given
operand kind and quantifier used in the JSON grammar.
Arguments:
- operand_tuple: a tuple of two elements:
- operand kind: used in the JSON grammar
- qu... | 3d26a0b330ae64209655b24dfe86578cb4b8724c | 6,855 |
from datetime import datetime
def screen_missing_data(database,subject,begin=None,end=None):
""" Returns a DataFrame contanining the percentage (range [0,1]) of loss data
calculated based on the transitions of screen status. In general, if
screen_status(t) == screen_status(t+1), we declared we have at lea... | 70666ed7ddfea359c4c91afd8b52f9821580bda6 | 6,856 |
def check(text):
"""Check the text."""
error_code = "example.first"
msg = "First line always has an error."
reverse(text)
return [(1, 1, error_code, msg)] | 50d8406322225153c055b925609af702bb86d7b6 | 6,857 |
def figure(**kwargs):
"""
Create a new figure with the given settings.
Settings like the current colormap, title or axis limits as stored in the
current figure. This function creates a new figure, restores the default
settings and applies any settings passed to the function as keyword
arguments... | a7de48597ecc80872d8d4b108a642956200adcc2 | 6,858 |
from typing import List
from bs4 import BeautifulSoup
def parse(content: str, target: str = "all") -> List[Inline]:
"""Parses an HTML document and extracts."""
soup = BeautifulSoup(content, "html.parser")
if target == "all":
search_queries = chain(*_VALID_TARGETS.values())
elif target in _VAL... | 56238a4def01713220c7d59b266cfcc55f1daf7f | 6,859 |
def create_output(verified_specific_headers_list:list) -> str:
""" Design Output """
if args.verbose is True:
print("[!] INFO: Outputting Specific Header Information")
return_output = ""
for specific_header in verified_specific_headers_list:
split_header = specific_header.split(":")
... | e38fdf467d1f01167ff00040e7d0f7d8816e4915 | 6,860 |
def registered_response_data():
"""Body (bytes) of the registered response."""
return b"response data" | 1ee44d70592747947d76ff757901f44fde5c9946 | 6,861 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.