content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def dummy_img(w, h, intensity=200):
"""Creates a demodata test image"""
img = np.zeros((int(h), int(w)), dtype=np.uint8) + intensity
return img | a416753d8aa8682aef2b344f7de416139c9ed33a | 3,641,091 |
def getHandler(database):
"""
a function instantiating and returning this plugin
"""
return Events(database, 'events', public_endpoint_extensions=['insert']) | e42e69b379e2053437ac75fe3fe8fc81229579c1 | 3,641,092 |
import logging
def RegQueryValueEx(key, valueName=None):
""" Retrieves the type and data for the specified registry value.
Parameters
key A handle to an open registry key.
The key must have been opened with the KEY_QUERY_VALUE access right
valueName The name of the registry ... | 5cceedabfaef44040067424696d13eb8d0f15550 | 3,641,093 |
def read_molecules(filename):
"""Read a file into an OpenEye molecule (or list of molecules).
Parameters
----------
filename : str
The name of the file to read (e.g. mol2, sdf)
Returns
-------
molecule : openeye.oechem.OEMol
The OEMol molecule read, or a list of molecules i... | 420ba85dc768435927441500fe8005e3f009b9af | 3,641,094 |
def euler(derivative):
"""
Euler method
"""
return lambda t, x, dt: (t + dt, x + derivative(t, x) * dt) | 08d636ec711f4307ab32f9a8bc3672197a3699d9 | 3,641,095 |
def detect_encoding_type(input_geom):
"""
Detect geometry encoding type:
- ENC_WKB: b'\x01\x01\x00\x00\x00\x00\x00\x00\x00\x00H\x93@\x00\x00\x00\x00\x00\x9d\xb6@'
- ENC_EWKB: b'\x01\x01\x00\x00 \xe6\x10\x00\x00\x00\x00\x00\x00\x00H\x93@\x00\x00\x00\x00\x00\x9d\xb6@'
- ENC_WKB_HEX: '01010000000000000... | 4361abf695edad5912559175bd48cfa0bad92769 | 3,641,096 |
def unet_weights(input_size = (256,256,1), learning_rate = 1e-4, weight_decay = 5e-7):
"""
Weighted U-net architecture.
The tuple 'input_size' corresponds to the size of the input images and labels.
Default value set to (256, 256, 1) (input images size is 256x256).
The float 'learning_rate... | f091627475f13985e33f2960afd4b0136e9d10f4 | 3,641,098 |
from re import T
def std(x, axis=None, keepdims=False):
"""Standard deviation of a tensor, alongside the specified axis. """
return T.std(x, axis=axis, keepdims=keepdims) | ad3c547d19507243ec143d38dd22f9fc92becffb | 3,641,099 |
def validate_email_address(
value=_undefined,
allow_unnormalized=False,
allow_smtputf8=True,
required=True,
):
"""
Checks that a string represents a valid email address.
By default, only email addresses in fully normalized unicode form are
accepted.
Validation logic is based on the... | 85b590186f2e147c6c19e91bace33f0301115d0e | 3,641,100 |
import numpy
import math
def rotation_matrix_from_quaternion(quaternion):
"""Return homogeneous rotation matrix from quaternion."""
q = numpy.array(quaternion, dtype=numpy.float64)[0:4]
nq = numpy.dot(q, q)
if nq == 0.0:
return numpy.identity(4, dtype=numpy.float64)
q *= math.sqrt(2.0 / nq... | 51b169ffa702e3798f7a6138271b415b369566ba | 3,641,101 |
def get_metadata(doi):
"""Extract additional metadata of paper based on doi."""
headers = {"accept": "application/x-bibtex"}
title, year, journal = '', '', ''
sessions = requests.Session()
retry = Retry(connect=3, backoff_factor=0.5)
adapter = HTTPAdapter(max_retries=retry)
sessions.mount('h... | 8b7fee95ca247b0ffebfa704628be8a4659dd008 | 3,641,103 |
def format_channel(channel):
""" Returns string representation of <channel>. """
if channel is None or channel == '':
return None
elif type(channel) == int:
return 'ch{:d}'.format(channel)
elif type(channel) != str:
raise ValueError('Channel must be specified in string format.... | 4eeb42899762d334599df831b7520a956998155a | 3,641,104 |
def download_emoji_texture(load=True): # pragma: no cover
"""Download emoji texture.
Parameters
----------
load : bool, optional
Load the dataset after downloading it when ``True``. Set this
to ``False`` and only the filename will be returned.
Returns
-------
pyvista.Text... | 3ff7805e6ab4f18d0064938f8863cbbe395a7c78 | 3,641,105 |
import random
def shuffle_sequence(sequence: str) -> str:
"""Shuffle the given sequence.
Randomly shuffle a sequence, maintaining the same composition.
Args:
sequence: input sequence to shuffle
Returns:
tmp_seq: shuffled sequence
"""
tmp_seq: str = ""
while len(sequence... | 9e833aed9e5a17aeb419a77176713e76566d2d06 | 3,641,106 |
def bayesian_twosample(countsX, countsY, prior=None):
"""
Calculates a Bayesian-like two-sample test between `countsX` and `countsY`.
The idea is taken from [1]_. We assume the counts are generated IID. Then
we use Dirichlet prior to infer the underlying discrete distribution.
In the null hypothes... | fc64ba0d6e64ffcd7d57d51b3ea0f4967d4e5096 | 3,641,107 |
import torch
def load_image(image_path):
"""
loads an image from the specified image path
:param image_path:
:return: the loaded image
"""
image = Image.open(image_path)
image = loader(image)
image = image.unsqueeze(0)
image = image.to(device, torch.float)
return image | 064f9a4a71fdf9347a455269bf673bd2952dd9b2 | 3,641,108 |
import json
def feed_reader(url):
"""Returns json from feed url"""
content = retrieve_feed(url)
d = feed_parser(content)
json_string = json.dumps(d, ensure_ascii=False)
return json_string | 47726236afe429ab29720e917238960b17891938 | 3,641,109 |
def create_app(env_name):
"""
Create app
"""
# app initiliazation
app = Flask(__name__)
app.config.from_object(app_config[env_name])
cors = CORS(app)
# initializing bcrypt and db
bcrypt.init_app(app)
db.init_app(app)
app.register_blueprint(book_blueprint, url_prefix='/api/v1/books')
@app... | b694e8867b0bd3efefff0f7cae753b0ede91a36c | 3,641,110 |
def get_shed_tool_conf_dict( app, shed_tool_conf ):
"""Return the in-memory version of the shed_tool_conf file, which is stored in the config_elems entry in the shed_tool_conf_dict associated with the file."""
for index, shed_tool_conf_dict in enumerate( app.toolbox.shed_tool_confs ):
if shed_tool_conf ... | 21eae3a037498758425b29f10110f8e4e8ad24ff | 3,641,111 |
def oio_make_subrequest(env, method=None, path=None, body=None, headers=None,
agent='Swift', swift_source=None,
make_env=oio_make_env):
"""
Same as swift's make_subrequest, but let some more headers pass through.
"""
return orig_make_subrequest(env, method... | f454b027243f2e72b9e59c50dfc3819a22b887d6 | 3,641,114 |
from typing import Optional
def get_channel(id: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetChannelResult:
"""
Resource schema for AWS::MediaPackage::Channel
:param str id: The ID of the Channel.
"""
__args__ = dict()
__args__['id'] = id
... | 28ca816326203ca37cf514dade19ce9b6205144d | 3,641,116 |
import torch
def _get_activation_fn(activation):
"""Return an activation function given a string"""
if activation == "relu":
return torch.nn.functional.relu
if activation == "gelu":
return torch.nn.functional.gelu
if activation == "glu":
return torch.nn.functional.glu
raise... | ecc690e9b9ec6148b6ea8df4bd08ff2d0c1c322e | 3,641,117 |
def make_05dd():
"""移動ロック終了(イベント終了)"""
return "" | bb85e01a4a4515ac88688690cacd67e7c9351034 | 3,641,118 |
import json
def lambda_handler(request, context):
"""Main Lambda handler.
Since you can expect both v2 and v3 directives for a period of time during the migration
and transition of your existing users, this main Lambda handler must be modified to support
both v2 and v3 requests.
"""
try:
... | 8eddd8ac2a47ecbc9c15f2644da6a2c7c6575371 | 3,641,119 |
from re import T
def batch_flatten(x):
"""Turn a n-D tensor into a 2D tensor where
the first dimension is conserved.
"""
y = T.reshape(x, (x.shape[0], T.prod(x.shape[1:])))
if hasattr(x, '_keras_shape'):
if None in x._keras_shape[1:]:
y._keras_shape = (x._keras_shape[0], None)
... | 6543f3056d9e08b382cbd9e0ac1df6df84c59716 | 3,641,120 |
import typing
def msg_constant_to_behaviour_type(value: int) -> typing.Any:
"""
Convert one of the behaviour type constants in a
:class:`py_trees_ros_interfaces.msg.Behaviour` message to
a type.
Args:
value: see the message definition for details
Returns:
a behaviour class ty... | bdb2342ad9abbbc6db51beebcb82313799bc110e | 3,641,121 |
def calc_skewness(sig):
"""Compute skewness along the specified axes.
Parameters
----------
input: ndarray
input from which skewness is computed.
Returns
-------
s: int
skewness result.
"""
return skew(sig) | cad86d0a358a9bfe1891411522a6281e1eb291ed | 3,641,122 |
import pandas as pd
import pkgutil
def check_is_pandas_dataframe(log):
"""
Checks if a log object is a dataframe
Parameters
-------------
log
Log object
Returns
-------------
boolean
Is dataframe?
"""
if pkgutil.find_loader("pandas"):
return type(log) ... | 93fa02445302cf695fd86beb3e4836d58660e376 | 3,641,124 |
def mk_creoson_post_sessionId(monkeypatch):
"""Mock _creoson_post return dict."""
def fake_func(client, command, function, data=None, key_data=None):
return "123456"
monkeypatch.setattr(
creopyson.connection.Client, '_creoson_post', fake_func) | c8f5fcec40d55e14a7c955a90f32eccf597179f3 | 3,641,125 |
def isUsernameFree(name):
"""Checks to see if the username name is free for use."""
global username_array
global username
for conn in username_array:
if name == username_array[conn] or name == username:
return False
return True | 6a30766e35228e1ebea47c7f6d4f7f4f2832572d | 3,641,126 |
def get_quadrangle_dimensions(vertices):
"""
:param vertices:
A 3D numpy array which contains a coordinates of a quadrangle, it should look like this:
D---C
| |
A---B
[ [[Dx, Dy]], [[Cx, Cy]], [[Bx, By]], [[Ax, Ay]] ].
:return:
width, height (which are integers)
"""
temp = np.zeros((4, 2), dtype=int)... | 25e74cf63237d616c1fd0b1b3428dd0763a27fba | 3,641,127 |
def optimal_r(points, range_min, range_max):
"""
Computes the optimal Vietoris-Rips parameter r for the given list of points.
Parameter needs to be as small as possible and VR complex needs to have 1 component
:param points: list of tuples
:return: the optimal r parameter and list of (r, n_componen... | 950c8cc40de9ff9fbb0bd142461fc2710b54ead9 | 3,641,128 |
from pathlib import Path
def get_root_path():
"""
this is to get the root path of the code
:return: path
"""
path = str(Path(__file__).parent.parent)
return path | bc01b4fb15569098286fc24379a258300ff2dfa0 | 3,641,129 |
def _handle_requirements(hass: core.HomeAssistant, component,
name: str) -> bool:
"""Install the requirements for a component."""
if hass.config.skip_pip or not hasattr(component, 'REQUIREMENTS'):
return True
for req in component.REQUIREMENTS:
if not pkg_util.instal... | 6608228271fe37d607e7980d6c4cfe876b45b853 | 3,641,130 |
def check_image(filename):
""" Check if filename is an image """
try:
im = Image.open(filename)
im.verify() # is it an image?
return True
except OSError:
return False | b2854195c83cc6ab20e967e25f3892a46d3c146f | 3,641,131 |
import torch
def encode_save(sig=np.random.random([1, nfeat, nsensors]), name='simpleModel_ini', dir_path="../src/vne/models"):
"""
This function will create a model, test it, then save a persistent version (a file)
Parameters
__________
sig:
a numpy array with shape (nsamples, nfeatures,... | 96fbeb853c66afd7f4a6c3a1a087faee64ec76d0 | 3,641,132 |
from typing import Set
from typing import Tuple
from typing import Counter
def _imports_to_canonical_import(
split_imports: Set[Tuple[str, ...]],
parent_prefix=(),
) -> Tuple[str, ...]:
"""Extract the canonical import name from a list of imports
We have two rules.
1. If you have at least 4 impor... | e9cfd11b5837576ccc6f380463fe4b8ce9f4a63d | 3,641,133 |
def score_hmm_logprob(bst, hmm, normalize=False):
"""Score events in a BinnedSpikeTrainArray by computing the log
probability under the model.
Parameters
----------
bst : BinnedSpikeTrainArray
hmm : PoissonHMM
normalize : bool, optional. Default is False.
If True, log probabilities ... | d20e5e75c875602c7ac2e3b0dadc5adcae45406d | 3,641,135 |
def rotate_2d_list(squares_list):
"""
http://stackoverflow.com/questions/8421337/rotating-a-two-dimensional-array-in-python
"""
return [x for x in zip(*squares_list[::-1])] | a6345ce6954643b8968ffb4c978395baf777fca4 | 3,641,136 |
def next_ticket(ticket):
"""Return the next ticket for the given ticket.
Args:
ticket (Ticket): an arbitrary ticket
Returns:
the next ticket in the chain of tickets, having the next
pseudorandom ticket number, the same ticket id, and a
generation number that is one larger.
... | 7f5cfbd9992322e394a9e3f4316d654ef9ad6749 | 3,641,137 |
def icecreamParlor4(m, arr):
"""I forgot about Python's nested for loops - on the SAME array - and how
that's actually -possible-, and it makes things so much simplier.
It turns out, that this works, but only for small inputs."""
# Augment the array of data, so that it not only includes the item, but
... | 6af2da037aa3e40c650ac48ebeb931399f1a6eaa | 3,641,138 |
import datasets
def get_data(filepath, transform=None, rgb=False):
"""
Read in data from the given folder.
Parameters
----------
filepath: str
Path for the file e.g.: F'string/containing/filepath'
transform: callable
A function which tranforms the data to the required format
... | 99eb506c9033e259ad5769d8eff10b7fd985a1d6 | 3,641,139 |
def read_input_files(input_file: str) -> frozenset[IntTuple]:
"""
Extracts an initial pocket dimension
which is a set of active cube 3D coordinates.
"""
with open(input_file) as input_fobj:
pocket = frozenset(
(x, y)
for y, line in enumerate(input_fobj)
fo... | c44e85e0c4f998e04b3d5e8b1e4dc30260102fce | 3,641,141 |
def resnet101(pretrained=False, root='./pretrain_models', **kwargs):
"""Constructs a ResNet-101 model.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
"""
model = ResNet(Bottleneck, [3, 4, 23, 3], **kwargs)
if pretrained:
model.load_state_dict(model_zoo.load... | ba77d75d52aa5ce92cc5a8bec09347c799ebc02a | 3,641,142 |
def insert_left_side(left_side, board_string):
"""
Replace the left side of the Sudoku board 'board_string' with 'left_side'.
"""
# inputs should match in upper left corner
assert(left_side[0] == board_string[0])
# inputs should match in lower left corner
assert(left_side[8] == low_left_digi... | da607155e5c82a597f1ec62e6def3fbe31119c36 | 3,641,143 |
import tqdm
import uuid
def collect_story_predictions(story_file, policy_model_path, nlu_model_path,
max_stories=None, shuffle_stories=True):
"""Test the stories from a file, running them through the stored model."""
def actions_since_last_utterance(tracker):
actions = [... | d47d83c62d119f99c5c3c74b490866ffc64dc3ed | 3,641,144 |
import select
def sniff(store=False, prn=None, lfilter=None,
count=0,
stop_event=None, refresh=.1, *args, **kwargs):
"""Sniff packets
sniff([count=0,] [prn=None,] [store=1,] [offline=None,] [lfilter=None,] + L2ListenSocket args)
store: wether to store sniffed packets or discard them
prn... | 06309d056c0a68046025b806d91b7c7f0c5fdeb6 | 3,641,146 |
def _brighten_images(images: np.ndarray, brightness: int = BRIGHTNESS) -> np.ndarray:
"""
Adjust the brightness of all input images
:params images: The original images of shape [H, W, D].
:params brightness: The amount the brighness should be raised or lowered
:return: Images with adjusted brightne... | b2bc8c801e459b5f913a2bf725709cbc80df128a | 3,641,148 |
def CreateMovie(job_name, input_parameter, view_plane, plot_type):
"""encoder = os.system("which ffmpeg")
print encoder
if(len(encoder) == 0):
feedback['error'] = 'true'
feedback['message'] = ('ERROR: Movie create encoder not found')
print feedback
return
"""
movie_name = job_name + '_' + input_parameter+ ... | ff518f485db1de7a2d00af2984f5829cfe4279dc | 3,641,150 |
def describe_recurrence(recur, recurrence_dict, connective="and"):
"""Create a textual description of the recur set.
Arguments:
recur (Set): recurrence pattern as set of day indices eg Set(["1","3"])
recurrence_dict (Dict): map of strings to recurrence patterns
connective (Str): word to... | 0189fa88f64a284367829c3f95ecd056aec7bfa8 | 3,641,151 |
def route_image_zoom_in():
"""
Zooms in.
"""
result = image_viewer.zoom_in()
return jsonify({'zoom-in' : result}) | 758acf681718cc1c2be2c3bac112f4fc83243cf9 | 3,641,152 |
def evaluate_flow_file(gt_file, pred_file):
"""
evaluate the estimated optical flow end point error according to ground truth provided
:param gt_file: ground truth file path
:param pred_file: estimated optical flow file path
:return: end point error, float32
"""
# Read flow files and calcula... | ecbe960cd011f4282758a3f6bf4f345853f9a49d | 3,641,153 |
def get_heavy_load_rses(threshold, session=None):
"""
Retrieve heavy load rses.
:param threshold: Threshold as an int.
:param session: Database session to use.
:returns: .
"""
try:
results = session.query(models.Source.rse_id, func.count(models.Source.rse_id).label('load'))\
... | 52b44132c1680e0ca9ba64a0afb2938abcab1228 | 3,641,154 |
import operator
def facetcolumns(table, key, missing=None):
"""
Like :func:`petl.util.materialise.columns` but stratified by values of the
given key field. E.g.::
>>> import petl as etl
>>> table = [['foo', 'bar', 'baz'],
... ['a', 1, True],
... ['b', 2, ... | bec3419a22128c2863032022c5e9e507c9791f1b | 3,641,155 |
def divide_set(vectors, labels, column, value):
"""
Divide the sets into two different sets along a specific dimension and value.
"""
set_1 = [(vector, label) for vector, label in zip(vectors, labels) if split_function(vector, column, value)]
set_2 = [(vector, label) for vector, label in zip(vectors... | dd99c4d700ad8294ce2b2a33b18feb79165487fb | 3,641,156 |
def execute_freezerc(dict, must_fail=False, merge_stderr=False):
"""
:param dict:
:type dict: dict[str, str]
:param must_fail:
:param merge_stderr:
:return:
"""
return execute([FREEZERC] + dict_to_args(dict), must_fail=must_fail,
merge_stderr=merge_stderr) | 596490d1fe0ae90a807c6553674273e470165e57 | 3,641,157 |
def corField2D_vector(field):
"""
2D correlation field of a vector field. Correlations are calculated with
use of Fast Fourier Transform.
Parameters
----------
field : (n, n, 2) shaped array like
Vector field to extract correlations from.
Points are supposed to be uniformly dist... | 35b4c1dc646c30b9fdae7c1ad1095ae67ea1356d | 3,641,158 |
import json
def load_json_fixture(filename: str):
"""Load stored JSON data."""
return json.loads((TEST_EXAMPLES_PATH / filename).read_text()) | 1021975d2111a9391a93ff9bd757479a8c9663f6 | 3,641,159 |
from typing import List
from typing import Optional
def stat_list_card(
box: str,
title: str,
items: List[StatListItem],
name: Optional[str] = None,
subtitle: Optional[str] = None,
commands: Optional[List[Command]] = None,
) -> StatListCard:
"""Render a card display... | fa9036442fdad3028d40918741e91ca5077925fb | 3,641,160 |
def test_DataGeneratorAllSpectrums_fixed_set():
"""
Test whether use_fixed_set=True toggles generating the same dataset on each epoch.
"""
# Get test data
binned_spectrums, tanimoto_scores_df = create_test_data()
# Define other parameters
batch_size = 4
dimension = 88
# Create norm... | 95d8a13f1eaa5d7ef93936a8f9e224a56119e6af | 3,641,161 |
import math
def inverse_gamma(data, alpha=0.1, beta=0.1):
"""
Inverse gamma distributions
:param data: Data value
:param alpha: alpha value
:param beta: beta value
:return: Inverse gamma distributiion
"""
return (pow(beta, alpha) / math.gamma(alpha)) *\
pow(alpha, data-1) * ... | c13f5e4a05e111ae0082b7e69ef5b31498d2c221 | 3,641,162 |
def query(queryid):
"""
Dynamic Query View.
Must be logged in to access this view, otherwise redirected to login page.
A unique view is generated based off a query ID.
A page is only returned if the query ID is associated with a logged in user.
Otherwise a logged in user will be redirected to a... | 22c77dc122b15d8bb6589a823a8f3904f189371a | 3,641,163 |
def get_ssid() -> str:
"""Gets SSID of the network connected.
Returns:
str:
Wi-Fi or Ethernet SSID.
"""
process = Popen(
['/System/Library/PrivateFrameworks/Apple80211.framework/Versions/Current/Resources/airport', '-I'],
stdout=PIPE)
out, err = process.communicate()... | def6c485099219cd0894cde636ac93dc1b130a98 | 3,641,164 |
def train_predict(clf, X_train, X_test, y_train, y_test):
"""Train clf on <X_train, y_train>, predict <X_test, y_test>; return y_pred."""
print("Training a {}...".format(clf.__class__.__name__))
get_ipython().run_line_magic('time', 'clf.fit(X_train, y_train)')
print(clf)
print("Predicting test ... | eda266df2cea704d557e4de4f7600b62c533f362 | 3,641,165 |
def get_executable_choices(versions):
"""
Return available Maya releases.
"""
return [k for k in versions if not k.startswith(Config.DEFAULTS)] | df0c253b8ca29b42f7863a8944d21678847b7c9a | 3,641,167 |
def list_songs():
"""
Lists all the songs in your media server
Can do this without a login
"""
# # Check if the user is logged in, if not: back to login.
# if('logged_in' not in session or not session['logged_in']):
# return redirect(url_for('login'))
page['title'] = 'List Songs'
... | bbeb4e11404dcce582ed86cc711508645399a7cd | 3,641,168 |
import statistics
def linear_regression(xs, ys):
"""
Computes linear regression coefficients
https://en.wikipedia.org/wiki/Simple_linear_regression
Returns a and b coefficients of the function f(y) = a * x + b
"""
x_mean = statistics.mean(xs)
y_mean = statistics.mean(ys)
num, den = 0... | 6b6ecbd31262e5fe61f9cf7793d741a874327598 | 3,641,169 |
def calcR1(n_hat):
"""
Calculate the rotation matrix that would rotate the
position vector x_ae to the x-y plane.
Parameters
----------
n_hat : `~numpy.ndarray` (3)
Unit vector normal to plane of orbit.
Returns
-------
R1 : `~numpy.matrix` (3, 3)
Rotation matrix.
... | c3202c477eefe43648e693316079f9e2c6ac0aa0 | 3,641,170 |
def get_arb_info(info, n=1000):
"""
Example: info := {'start':1556668800, 'period':300, 'trading_pair':'eth_btc', 'exchange_id':'binance'}
"""
assert {'exchange_id', 'trading_pair', 'period', 'start'}.issubset(info.keys())
info['n'] = n
q = """with sub as (
select * from candlestick... | 20177d71b0a816031aded0151e91711f729fe0bf | 3,641,171 |
from typing import List
def parse_nested_root(stream: TokenStream) -> AstRoot:
"""Parse nested root."""
with stream.syntax(colon=r":"):
colon = stream.expect("colon")
if not consume_line_continuation(stream):
exc = InvalidSyntax("Expected non-empty block.")
raise set_location(exc,... | ea559c4c2592b4ecabfb10df39059391799f4462 | 3,641,172 |
def wg_config_write():
""" Write configuration file. """
global wg_config_file
return weechat.config_write(wg_config_file) | add032c3447d2c68005bbc1cc33006ba452afaa3 | 3,641,173 |
def is_palindrome_permutation(phrase):
"""checks if a string is a permutation of a palindrome"""
table = [0 for _ in range(ord("z") - ord("a") + 1)]
countodd = 0
for c in phrase:
x = char_number(c)
if x != -1:
table[x] += 1
if table[x] % 2:
countod... | dac9d0fc67f628cb22213d5fcad947baa3d2d8f1 | 3,641,174 |
import json
def get_stored_username():
"""Get Stored Username"""
filename = 'numbers.json'
try:
with open(filename) as file_object:
username = json.load(file_object)
except FileNotFoundError:
return None
else:
return username | 3471369cfc147dd9751cedb7cde92ceb5d69e908 | 3,641,175 |
import posixpath
def post_process_symbolizer_image_file(file_href, dirs):
""" Given an image file href and a set of directories, modify the image file
name so it's correct with respect to the output and cache directories.
"""
# support latest mapnik features of auto-detection
# of image sizes ... | 42026823be510b5ffbb7404bd24809a1232e8206 | 3,641,176 |
import torch
def collate_fn_feat_padded(batch):
"""
Sort a data list by frame length (descending order)
batch : list of tuple (feature, label). len(batch) = batch_size
- feature : torch tensor of shape [1, 40, 80] ; variable size of frames
- labels : torch tensor of shape (1)
ex) sampl... | b901b6c3eacfd4d0bac93e1569d59ad944365fd2 | 3,641,177 |
import unicodedata
import re
def slugify(value, allow_unicode=False):
"""
Taken from https://github.com/django/django/blob/master/django/utils/text.py
Convert to ASCII if 'allow_unicode' is False. Convert spaces or repeated
dashes to single dashes. Remove characters that aren't alphanumerics,
unde... | 39f7ed291e6a2cec5111ba979c35a6aaa8e521c0 | 3,641,178 |
def average_gradient_norm(model, data):
""" Computes the average gradient norm for a keras model """
# just checking if the model was already compiled
if not hasattr(model, "train_function"):
raise RuntimeError("You must compile your model before using it.")
weights = model.trainable_weights #... | 84f5feb894f72856ef43eea8befc048f216020bd | 3,641,179 |
import logging
def string_regex_matcher(input_str: str, regex: str, replacement_str=""):
"""Python version of StringRegexMatcher in mlgtools.
Replaces all substring matched with regular expression (regex) with replacement string (replacement_str).
Args:
input_str (str): input string to match
... | c813447a1453347a1b263f603970d8ff4f709696 | 3,641,180 |
def cont_scatterplot(data: pd.DataFrame,
x: str,
y: str,
z: str or None,
label: str,
cmap: str,
size: int or str or None,
fig: plt.Figure,
cbar_kwargs: ... | e6c85d1fafa93c9000c807c7ec82ac7851082aec | 3,641,181 |
def performance(problem, W, H, C, R_full):
"""Compute the performance of the IMC estimates."""
assert isinstance(problem, IMCProblem), \
"""`problem` must be an IMC problem."""
assert W.ndim == H.ndim, """Mismatching dimensionality."""
if W.ndim < 3:
W, H = np.atleast_3d(W, H)
n_i... | 79635826cc72633a0024df29980ecc678f20e32d | 3,641,182 |
import pytz
from datetime import datetime
def courseschedules_to_private_ical_feed(user):
"""
Generate an ICAL feed for all course schedules associated with the given user.
The IDs given for each event are sequential, unique only amongst the results of this particular query, and not
guaranteed to be ... | 1d1ae7f650416eb240d0ce5240523d8c66067389 | 3,641,183 |
def AuxStream_Cast(*args):
"""
Cast(BaseObject o) -> AuxStream
AuxStream_Cast(Seiscomp::Core::BaseObjectPtr o) -> AuxStream
"""
return _DataModel.AuxStream_Cast(*args) | a38248e5476273aa6b18da5017a7ca0a033fd0a8 | 3,641,184 |
def BPNet(tasks, bpnet_params):
"""
BPNet architecture definition
Args:
tasks (dict): dictionary of tasks info specifying
'signal', 'loci', and 'bias' for each task
bpnet_params (dict): parameters to the BPNet architecture
The keys includ... | cfffac8da543241160b6fc1963b8b19df7fa2b02 | 3,641,185 |
def getCubePixels(cubeImages):
"""
Returns a list containing the raw pixels from the `bpy.types.Image` images
in the list `cubeImages`. Factoring this functionality out into its own
function is useful for performance profiling.
"""
return [face.pixels[:] for face in cubeImages] | cdb2ba02ce9466e1b92a683dbea409e66b60c8da | 3,641,186 |
import select
async def get_round_details(round_id):
"""
Get details for a given round (include snapshot)
"""
query = (
select(detail_columns)
.select_from(select_from_default)
.where(rounds_table.c.id == round_id)
) # noqa: E127
result = await conn.fetch_one(query=que... | b7d64f52a8dff1a68a327651653f1f217f688146 | 3,641,187 |
import random
def dens_hist_plot(**kwargs):
"""
plot prediction probability density histogram
Arguments:
df: classification prediction probability in pandas datafrane
"""
data = {'top1prob' : random.sample(range(1, 100), 5),
'top2prob' : random.sample(range(... | 9b9e65f4aef04c2676b48737f4b9bf525172b6ea | 3,641,188 |
import time
def run_query(run_id, athena_client, query, athena_database_name, wait_to_finish):
""" Run the given Athena query
Arguments:
run_id {string} -- run_id for the current Step Function execution
athena_client {boto3.client} -- Boto3 Athena client
query {string} -- Athena query... | 0ee4618de6df9e32bbe3255f7a423dd838a564f1 | 3,641,189 |
def next_version(v: str) -> str:
"""
If ``v`` is a prerelease version, returns the base version. Otherwise,
returns the next minor version after the base version.
"""
vobj = Version(v)
if vobj.is_prerelease:
return str(vobj.base_version)
vs = list(vobj.release)
vs[1] += 1
vs... | aea76df6874e368494ca630d594bee978ffc7e08 | 3,641,190 |
def temp_obs():
"""Return a list of tobs from the 2016-08-24 to 2017-08-23"""
# Query temperature data with date
temp_query = session.query(Measurement.date, Measurement.tobs).filter(Measurement.date > year_start_date).all()
# Create a dictionary from the row data and append to a list of all temp... | 6a74ad37cb95d1103943f15dfcac82e39c38620d | 3,641,192 |
def pcmh_5_5c__3():
"""ER/IP discharge log"""
er_ip_log_url = URL('init', 'word', 'er_ip_log.doc',
vars=dict(**request.get_vars),
hmac_key=MY_KEY, salt=session.MY_SALT, hash_vars=["app_id", "type"])
# er_ip_log tracking chart
er_ip_log = MultiQNA(
... | 968bcc181cf3ec4513cfeb73004cdd3336f62003 | 3,641,193 |
import json
def is_jsonable(data):
"""
Check is the data can be serialized
Source: https://stackoverflow.com/a/53112659/8957978
"""
try:
json.dumps(data)
return True
except (TypeError, OverflowError):
return False | acfc697025a8597fdd8043fe3245a339b27051c4 | 3,641,196 |
def check_ref_type(ref, allowed_types, ws_url):
"""
Validates the object type of ref against the list of allowed types. If it passes, this
returns True, otherwise False.
Really, all this does is verify that at least one of the strings in allowed_types is
a substring of the ref object type name.
... | 263cf56124fb466544dfba8879a55d1f09160d35 | 3,641,197 |
from typing import Dict
from typing import List
def check_infractions(
infractions: Dict[str, List[str]],
) -> int:
"""
Check infractions.
:param infractions: the infractions dict {commit sha, infraction explanation}
:return: 0 if no infractions, non-zero otherwise
"""
if len(infractions)... | 954f5f80dbfdd2a834f56662f4d04c1f788bb9ef | 3,641,198 |
def default_role(name, arguments, options, content, lineno,
content_offset, block_text, state, state_machine):
"""Set the default interpreted text role."""
if not arguments:
if roles._roles.has_key(''):
# restore the "default" default role
del roles._roles['']
... | f1f6ed82da74cd898d4df0753cd1044a6666d216 | 3,641,200 |
def input_fn(evaluate=False) -> tf.data.Dataset:
"""
Returns the text as char array
Args:
n_repetitions: Number of times to repeat the inputs
"""
# The dataset
g = ( evaluate_generator if evaluate else train_generator )
ds = tf.data.Dataset.from_generator( generator=g,
out... | 2954eb4b4f657fff3e029096a562516842c615e8 | 3,641,202 |
async def validate_input(data):
"""Validate the user input allows us to connect.
Data has the keys from DATA_SCHEMA with values provided by the user.
"""
harmony = await get_harmony_client_if_available(data[CONF_HOST])
if not harmony:
raise CannotConnect
return {
CONF_NAME: fin... | fc174ed28bd80fd8e118094ea21358b9c8f41fa3 | 3,641,204 |
import numpy
def window_tukey(M, alpha=0.5):
"""Return a Tukey window, also known as a tapered cosine window.
The function returns a Hann window for `alpha=0` and a boxcar window for `alpha=1`
"""
if alpha == 0:
return numpy.hann(M)
elif alpha == 1:
return window_boxcar(M)
n =... | f62d216de29e2271270a4fc3c03b0f93930f1275 | 3,641,205 |
def workshopsDF(symbol="", **kwargs):
"""This is a meeting or series of meetings at which a group of people engage in discussion and activity on a particular subject, product or service to gain hands-on experience.
https://iexcloud.io/docs/api/#workshops
Args:
symbol (str): symbol to use
"""
... | 7f6417acecdd7a2bd7279e5d0367894458589241 | 3,641,206 |
def free_path(temp, diff, m_mol):
"""
Calculates the free path for a molecule
Based on free_path.m by Joni Kalliokoski 2014-08-13
:param temp: temperature (K)
:param diff: diffusion coefficient (m^2/s)
:param m_mol: molar mass (kg/mol)
:return: free path (m)
"""
return 3*diff*np.sqrt... | 053a2af667e1e9ecc85f1ea6ca898c80e14ec81f | 3,641,207 |
def comp_periodicity_spatial(self):
"""Compute the (anti)-periodicities of the machine in space domain
Parameters
----------
self : Machine
A Machine object
Returns
-------
pera : int
Number of spatial periodicities of the machine over 2*pi
is_apera : bool
True ... | b34a50f0df0bc1bfd3ffaddb5e8a57780e50a6b8 | 3,641,208 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.