content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def fix_lng_degrees(lng: float) -> float:
"""
For a lng degree outside [-180;180] return the appropriate
degree assuming -180 = 180°W and 180 = 180°E.
"""
sign = 1 if lng > 0 else -1
lng_adj = (abs(lng) % 360) * sign
if lng_adj > 180:
return (lng_adj % 180) - 180
elif lng_adj < -... | bde58152883874095b15ec38cfb24ea68d73c188 | 16,700 |
def create_code(traits):
"""Assign bits to list of traits.
"""
code = 1
result = {INVALID: code}
if not traits:
return result
for trait in traits:
code = code << 1
result[trait] = code
return result | cfc7b1662edaf7f3e3763009a460157f7ec677bb | 16,701 |
from typing import List
from typing import Dict
from typing import Any
from typing import Optional
def get_current_table(grid_id: str) -> List[Dict[Any, Any]]:
""" Get current Data from the grid
Args:
grid_id: Grid ID to retrieve data from.
Returns:
list: Exsiting grid data.
"""
... | d1a8c21398aa2aca54ca587aa577c8ff50d8d46f | 16,702 |
def read_graph(filepath):
"""Creates a graph based on the content of the file at given filepath.
Parameters
----------
filename : filepath
Path to a file containing an adjacency matrix.
"""
g_data = np.loadtxt(open(filepath, "rb"), delimiter=",")
return nx.from_numpy_matrix(g_data) | 74e0b687c6cf9e404d9446505799a84b5680c5b3 | 16,703 |
def get_seed(seed=None):
"""Get valid Numpy random seed value"""
# https://groups.google.com/forum/#!topic/briansupport/9ErDidIBBFM
random = np.random.RandomState(seed)
return random.randint(0, 2147483647) | 5ac1280a30265518edcf8bb07a03cfe5fb0ae21d | 16,704 |
import traceback
import sys
def explain_predictions_best_worst(pipeline, input_features, y_true, num_to_explain=5, top_k_features=3,
include_shap_values=False, metric=None, output_format="text"):
"""Creates a report summarizing the top contributing features for the best and wors... | 9138b92d13e3aa44a31b91d512cbbbd08e35ecd6 | 16,705 |
import typing
import inspect
def resolve_lookup(
context: dict, lookup: str, call_functions: bool = True
) -> typing.Any:
"""
Helper function to extract a value out of a context-dict.
A lookup string can access attributes, dict-keys, methods without parameters and indexes by using the dot-accessor (e.... | a2090f2488ee10f7c11684952fd7a2498f6d4979 | 16,706 |
def check_actions_tool(tool):
"""2.2.x to 2.3.0 upgrade step checker
"""
atool = getToolByName(tool, 'portal_actions')
try:
atool['user']['change_password']
except KeyError:
return True
try:
atool['global']['members_register']
except KeyError:
return True
... | 2ecc6064cd26aa670743c25018dd27e2ce0f41ca | 16,707 |
def integer_byte_length(number):
"""
Number of bytes needed to represent a integer excluding any prefix 0 bytes.
:param number:
Integer value. If num is 0, returns 0.
:returns:
The number of bytes in the integer.
"""
quanta, remainder = divmod(integer_bit_length(number), 8)
if remainder:
... | 0de5828117107461e23e36cf3c38bab0850b7203 | 16,708 |
def ones(input_dim, output_dim, name=None):
"""All zeros."""
initial = tf.ones((input_dim, output_dim), dtype=tf.float32)
return tf.Variable(initial, name=name) | 02867b278e224e436e470a9eaeac32b44e99a99a | 16,709 |
def enrichment_score2(mat, idx, line_width, norm_factors, distance_range=(20, 40), window_size=10,
stats_test_log=({}, {})):
"""
Calculate the enrichment score of a stripe given its location, width and the contact matrix
Parameters:
----------
mat: np.array (2D)
Contac... | bfb987bd2e2d0770d81f811ba2486893b62d269d | 16,710 |
def paginate(data, page=1, per_page=None):
"""Create a paginated response of the given query set.
Arguments:
data -- A flask_mongoengine.BaseQuerySet instance
"""
per_page = app.config['DEFAULT_PER_PAGE'] if not per_page else per_page
pagination_obj = data.paginate(page=page, per_page=per_p... | c5a692067e5f58a971762316c83bcfe6f75051bf | 16,711 |
def compute_mean_wind_dirs(res_path, dset, gids, fracs):
"""
Compute mean wind directions for given dset and gids
"""
with Resource(res_path) as f:
wind_dirs = np.radians(f[dset, :, gids])
sin = np.mean(np.sin(wind_dirs) * fracs, axis=1)
cos = np.mean(np.cos(wind_dirs) * fracs, axis=1)
... | bd3f91cc0f4b05f630d252f6026e3f27c56cd134 | 16,712 |
import numpy
def plot_area_and_score(samples: SampleList, compound_name: str, include_none: bool = False):
"""
Plot the peak area and score for the compound with the given name
:param samples: A list of samples to plot on the chart
:param compound_name:
:param include_none: Whether samples where the compound wa... | cce2dd3c3fca742627dca5c893f498d83e0d7840 | 16,713 |
def get_strides(fm: NpuFeatureMap) -> NpuShape3D:
"""Calculates STRIDE_C/Y/X"""
if fm.strides is not None:
return fm.strides
elem_size = fm.data_type.size_in_bytes()
if fm.layout == NpuLayout.NHWC:
stride_c = elem_size
stride_x = fm.shape.depth * stride_c
stride_y = fm.sh... | e933fd3b06fb53e44b81bcb28341137a14990dec | 16,714 |
def gram_linear(x):
"""Compute Gram (kernel) matrix for a linear kernel.
Args:
x: A num_examples x num_features matrix of features.
Returns:
A num_examples x num_examples Gram matrix of examples.
"""
return x.dot(x.T) | f0a625d3ca6b846396c3c7c723b1bc8130a6c140 | 16,715 |
def to_feature(shape, properties={}):
"""
Create a GeoJSON Feature object for the given shapely.geometry :shape:.
Optionally give the Feature a :properties: dict.
"""
collection = to_feature_collection(shape)
feature = collection["features"][0]
feature["properties"] = properties
# remov... | 39d8e7658ae2043c081d137f0a69ddd4344876fc | 16,716 |
def read_responses(file):
"""
Read dialogs from file
:param file: str, file path to the dataset
:return: list, a list of dialogue (context) contained in file
"""
with open(file, 'r') as f:
samples = f.read().split('<|endoftext|>')
samples = samples[1:] # responses = [i.strip() f... | e654a075622f04c3eca6c18e3d092593387ef237 | 16,717 |
def build_parametric_ev(data, onset, name, value, duration=None,
center=None, scale=None):
"""Make design info for a multi-column constant-value ev.
Parameters
----------
data : DataFrame
Input data; must have "run" column and any others specified.
onset : string
... | 47400052e2b2f4bf8217d9eaf71a83257180f5c4 | 16,718 |
import operator
import bisect
def time_aware_indexes(t, train_size, test_size, granularity, start_date=None):
"""Return a list of indexes that partition the list t by time.
Sorts the list of dates t before dividing into training and testing
partitions, ensuring a 'history-aware' split in the ensuing clas... | 96e27c7a3f7284476d615a8d03f7c365f0406187 | 16,719 |
def send_invite_mail(invite, request):
"""
Send an email invitation to user not yet registered in the system.
:param invite: ProjectInvite object
:param request: HTTP request
:return: Amount of sent email (int)
"""
invite_url = build_invite_url(invite, request)
message = get_invite_body... | 4554bb6bea20e03749739026583d6215714febbf | 16,720 |
import os
import json
import google
def get_credentials(quota_project_id=None):
"""Obtain credentials object from json file and environment configuration."""
credentials_path = os.environ.get("GOOGLE_APPLICATION_CREDENTIALS")
with open(credentials_path, "r", encoding="utf8") as file_handle:
creden... | b88c2de4adb034d7373fc8191ecc590c2201d344 | 16,721 |
def binary_n(total_N, min_n=50):
"""
Creates a list of values by successively halving the total length total_N
until the resulting value is less than min_n.
Non-integer results are rounded down.
Args:
total_N (int):
total length
Kwargs:
min_n (int):
minimal length after division
Ret... | 240296c6024243da5750cb5aa7e64bea45ae91ca | 16,722 |
def thresholding(pred,label,thres):
""" Given the threshold return boolean matrix with 1 if > thres 0 if <= 1 """
conf =[]
for i in thres:
pr_th,lab_th = (pred>i),(label>i)
conf += confusion(pr_th,lab_th)
return np.array(conf).reshape(-1,4) | 97727a75b4f7648c82a095c7804709e9a52f13ed | 16,723 |
def unicode_test(request, oid):
"""Simple view to test funky characters from the database."""
funky = News.objects.using('livewhale').get(pk=oid)
return render(request, 'bridge/unicode.html', {'funky': funky}) | 8357d76bfc22fdc3f12176332a4b19fd3bfb79c9 | 16,724 |
from typing import Optional
from typing import Dict
from typing import Any
def _field_to_schema_object(field: BaseType, apistrap: Optional[Apistrap]) -> Optional[Dict[str, Any]]:
"""
Convert a field definition to OpenAPI 3 schema.
:param field: the field to be converted
:param apistrap: the extension... | 1451f8795dc39d3168c141fd0ad8dd2615903163 | 16,725 |
import os
import subprocess
def linux_gcc_name():
"""Returns the name of the `gcc` compiler. Might happen that we are cross-compiling and the
compiler has a longer name.
Args:
None
Returns:
str: Name of the `gcc` compiler or None
"""
cc_env = os.getenv('CC')
if cc_env... | 47cf0ee9af4b1b7c9169632b86bc9b5e1db96ad3 | 16,726 |
from typing import Dict
from typing import Any
def drop_test(robot, *, z_rot: float, min_torque: bool, initial_height: float = 1.) -> Dict[str, Any]:
"""Params which have been tested for this task:
nfe = 20, total_time = 1.0, vary_timestep_with=(0.8,1.2), 5 mins for solving
if min_torque is True, quite a... | e6a070fd52356a314e5d2992d03fa61ead40f950 | 16,727 |
from typing import List
from typing import Union
from datetime import datetime
from typing import Dict
from typing import Any
import httpx
from typing import cast
def get_user_list(
*, client: Client, an_enum_value: List[AnEnum], some_date: Union[date, datetime],
) -> Union[
List[AModel], HTTPValidationError,... | 77ca30fafb6c29f4cb04d25b52b7cca37e3ede04 | 16,728 |
def old_func5(self, x):
"""Summary.
Bizarre indentation.
"""
return x | 5bc9cdbc406fa49960613578296e81bdd4eeb771 | 16,729 |
def set_(
computer_policy=None,
user_policy=None,
cumulative_rights_assignments=True,
adml_language="en-US",
):
"""
Set a local server policy.
Args:
computer_policy (dict):
A dictionary of "policyname: value" pairs of computer policies to
set. 'value' should... | ee000c61cf4eb0653367340d87160b2e8e0f09d2 | 16,730 |
def get_dotenv_variable(var_name: str) -> str:
""" """
try:
return config.get(var_name)
except KeyError:
error_msg = f"{var_name} not found!\nSet the '{var_name}' environment variable"
raise ImproperlyConfigured(error_msg) | e3a06f3a439f5eb238688805985fb54eea7221e4 | 16,731 |
def load_dataset():
"""
Create a PyTorch Dataset for the images.
Notes
-----
- See https://discuss.pytorch.org/t/computing-the-mean-and-std-of-dataset/34949
"""
transform = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.9720, 0.9720, 0.9720),
... | 204e33cb7cb79ef81349b083e21ed6779c04dad0 | 16,732 |
import sys
def load():
"""Load list of available storage managers."""
storage_type = config.get("rights", "type")
if storage_type == "custom":
rights_module = config.get("rights", "custom_handler")
__import__(rights_module)
module = sys.modules[rights_module]
else:
root... | f65c76af008c4cf2d41347d84815921d6897edc7 | 16,733 |
def vote(pred1, pred2, pred3=None):
"""Hard voting for the ensembles"""
vote_ = []
index = []
if pred3 is None:
mean = np.mean([pred1, pred2], axis=0)
for s, x in enumerate(mean):
if x == 1 or x == 0:
vote_.append(int(x))
else:
vote... | a24858c0f14fe51a70ff2c0146a4e1aa3a2afdeb | 16,734 |
from pathlib import Path
def generate_master_flat(
science_frame : CCDData,
bias_path : Path,
dark_path : Path,
flat_path : Path,
use_cache : bool=True
) -> CCDData:
"""
"""
cache_path = generate_cache_path(science_frame, flat_path) / 'flat'
if use_cach... | 5448e6f95e1d2c9249ac9419c767e675dc424c5b | 16,735 |
def natrix_mqttclient(client_id):
"""Generate a natrix mqtt client.
This function encapsulates all configurations about natrix mqtt client.
Include:
- client_id
The unique id about mqtt connection.
- username & password
Username is device serial number which used to identify who am I;
... | 20960873f265068aff035ec554b880fa93c49e32 | 16,736 |
def insert_singletons(words, singletons, p=0.5):
"""
Replace singletons by the unknown word with a probability p.
"""
new_words = []
for word in words:
if word in singletons and np.random.uniform() < p:
new_words.append(0)
else:
new_words.append(word)
retu... | c99e9ed38287c175cd97f9cec0c0f8fb8f3629a7 | 16,737 |
def talk(text, is_yelling=False, trim=False, verbose=True):
"""
Prints text
is_yelling capitalizes text
trim - trims whitespace from both ends
verbose - if you want to print something on screen
returns transformed text
"""
if trim:
text = text.strip()
if is_yelling:
t... | 22728a877460b4504653e2a0ea9ecdf81fa422f9 | 16,738 |
def getNorthPoleAngle(target, position, C, B, camera):
"""
Get angle north pole of target makes with image y-axis, in radians.
"""
# get target spin axis
# the last row of the matrix is the north pole vector, *per spice docs*
# seems correct, as it's nearly 0,0,1
Bz = B[2]
print 'Bz=nor... | cf6d79ef3af005a170694d5fe00b93e9dd2665dd | 16,739 |
def ray_casting(polygon, ray_line):
""" checks number of intersection a ray makes with polygon
parameters: Polygon, ray (line)
output: number of intersection
"""
vertex_num = polygon.get_count()
ray_casting_result = [False] * vertex_num
''' count for vertices that is colinear and in... | 004c73fbef35bec5af35b6b93cc5b2bdb2e40f33 | 16,740 |
import os
import subprocess
import re
import glob
import shutil
from pathlib import Path
def main_install(args, config=None):
"""
Main function for the 'install' command.
"""
if not config:
# Load configuration file
config = autokernel.config.load_config(args.autokernel_config)
# ... | 647e2558532274d061c823682e831f928aafaadc | 16,741 |
import logging
import os
import tqdm
def kmeans_clustering_missing(reduced_components, output_path,
n_clusters=2, max_iter=10):
"""
Performs a K-means clustering with missing data.
:param reduced_components: reduced components matrix
:type reduced_components: np.ndarray
... | f6e5310982526b581a99ef2961ea8c5b30008f04 | 16,742 |
def ErrorWrapper(err, resource_name):
"""Wraps http errors to handle resources names with more than 4 '/'s.
Args:
err: An apitools.base.py.exceptions.HttpError.
resource_name: The requested resource name.
Returns:
A googlecloudsdk.api_lib.util.exceptions.HttpException.
"""
exc = exceptions.HttpE... | ebcce6241f88d0fa4f093f6823d0ccb9ae1bd431 | 16,743 |
def get_str_cmd(cmd_lst):
"""Returns a string with the command to execute"""
params = []
for param in cmd_lst:
if len(param) > 12:
params.append('"{p}"'.format(p=param))
else:
params.append(param)
return ' '.join(params) | a7cc28293eb381604112265a99b9c03e762c2f2c | 16,744 |
def calculate_score(arr):
"""Inside calculate_score() check for a blackjack (a hand with only 2 cards: ace + 10) and return 0 instead of the actual score. 0 will represent a blackjack in our game.
It check for an 11 (ace). If the score is already over 21, remove the 11 and replace it with a 1"""
... | 0890c55068b8a92d9f1f577ccf2c5a770f7887d4 | 16,745 |
def tt_true(alpha):
"""Is the propositional sentence alpha a tautology? (alpha will be
coerced to an expr.)
>>> tt_true(expr("(P >> Q) <=> (~P | Q)"))
True
"""
return tt_entails(TRUE, expr(alpha)) | 91ca0d445407f50d4b985e16428dfeb7f1e1b5a2 | 16,746 |
from e2e_simulators import webbpsf_imaging as webbim
import time
import os
def contrast_jwst_ana_num(matdir, matrix_mode="analytical", rms=1. * u.nm, im_pastis=False, plotting=False):
"""
Calculate the contrast for an RMS WFE with image PASTIS, matrix PASTIS
:param matdir: data directory to use for matrix... | 93336020d4d1c276fd7918d12b648476d63505f1 | 16,747 |
import configparser
def show_config_data_by_section(data:configparser.ConfigParser, section:str):
"""Print a section's data by section name
Args:
data (configparser.ConfigParser): Data
section (str): Section name
"""
if not _check_data_section_ok(data, section):
return None
... | 620abac7791a9e34707236ea6186b4e77591a393 | 16,748 |
def train_save_tfidf(filein, target):
"""input is a bow corpus saved as a tfidf file. The output is
a saved tfidf corpus"""
try:
corpus = corpora.MmCorpus(filein)
except:
raise NameError('HRMMPH. The file does not seem to exist. Create a file'+
'first by runni... | e4d41443d27f8b55f9fd6ba4b8c13a42d381a980 | 16,749 |
def ScrewTrajectoryList(Xstart, Xend, Tf, N, method, gripper_state, traj_list):
""" Modified from the modern_robotics library ScrewTrajectory
Computes a trajectory as a list of SE(3) matrices with a gripper value and
converts into a list of lists
Args:
Xstart : The initial end-effector con... | 146f4f7b96207c74bbe0ed08e162c3ba656d7a43 | 16,750 |
def calculate_phase(time, period):
"""Calculates phase based on period.
Parameters
----------
time : type
Description of parameter `time`.
period : type
Description of parameter `period`.
Returns
-------
list
Orbital phase of the object orbiting the star.
"... | a537810a7705b5d8b0144318469b249f64a01456 | 16,751 |
import os
import re
def get_sbappname(filepath):
""" Given a file path, find an acceptable name on the BL filesystem """
filename = os.path.split(filepath)[1]
filename = filename.split('.')[0]
return re.sub(r'[:*?"<>|]', "", filename)[:24] | c81154ee8ec97cd51f3fae55ba8b1778170de1b6 | 16,752 |
def perspective_transform(img):
"""
Do a perspective transform over an image.
Points are hardcoded and depend on the camera and it's positioning
:param img:
:return:
"""
pts1 = np.float32([[250, 686], [1040, 680], [740, 490], [523, 492]])
pts2 = np.float32([[295, 724], [980, 724], [988, ... | 51411c1fc73e897a657e2e89c44275796b16a1b6 | 16,753 |
def login():
"""Log user in"""
# Forget any user_id
session.clear()
# User reached route via POST (as by submitting a form via POST)
if request.method == "POST":
# Ensure username was submitted
if not request.form.get("username"):
return apology("must provide username"... | ffa2152cffdbfd161f3e8aa23aefa3c49993e630 | 16,754 |
def value_iteration(P, nS, nA, gamma=0.9, tol=1e-3):
"""
Learn value function and policy by using value iteration method for a given
gamma and environment.
Parameters:
----------
P, nS, nA, gamma:
defined at beginning of file
tol: float
Terminate value iteration when
max |value(s) - prev_value(s)| < tol
... | 7362b95cd453f0983e6b82acf73d0350eae2734c | 16,755 |
def get_clients():
"""
Determine if the current user has a connected client.
"""
return jsonify(g.user.user_id in clients) | 602d77b25b6608db24fca66d5bc55bc83a0530e8 | 16,756 |
def get_split_indices(word, curr_tokens, include_joiner_token, joiner):
"""Gets indices for valid substrings of word, for iterations > 0.
For iterations > 0, rather than considering every possible substring, we only
want to consider starting points corresponding to the start of wordpieces in
the curren... | 495d924716cfd0e14430d225e50b313fea305dbb | 16,757 |
def perspective(
vlist: list[list[Number,
Number,
Number]],
rotvec: list[list[float, float],
list[float, float],
list[float, float]],
dispvec: list[Number,
Number,
... | daece49851ecca55ba30d4f6f82fe59d5deb5497 | 16,758 |
import os
def _check_shebang(filename, disallow_executable):
"""Return 0 if the filename's executable bit is consistent with the
presence of a shebang line and the shebang line is in the whitelist of
acceptable shebang lines, and 1 otherwise.
If the string "# noqa: shebang" is present in the file, th... | 205fa2bc88b4c80899223e691b6f9cd00492c011 | 16,759 |
def actor_is_contact(api_user, nick, potential_contact):
"""Determine if one is a contact.
PARAMETERS:
potential_contact - stalkee.
RETURNS: boolean
"""
nick = clean.user(nick)
potential_contact = clean.user(potential_contact)
key_name = Relation.key_from(relation='contact',
... | 93a3bfd0a52b2acb043c162428f0fa45754702bf | 16,760 |
def compute_mem(w, n_ring=1, spectrum='nonzero', tol=1e-10):
"""Compute Moran eigenvectors map.
Parameters
----------
w : BSPolyData, ndarray or sparse matrix, shape = (n_vertices, n_vertices)
Spatial weight matrix or surface. If surface, the weight matrix is
built based on the inverse ... | fe622d75816629aaf5fce34405eb7a3021393d7d | 16,761 |
def eval_BenchmarkModel(x, a, y, model, loss):
"""
Given a dataset (x, a, y) along with predictions,
loss function name
evaluate the following:
- average loss on the dataset
- DP disp
"""
pred = model(x) # apply model to get predictions
n = len(y)
if loss == "square":
er... | cdb4e82004d94c7b25a705d33f716ac3d81e38de | 16,762 |
def parse_sgf_game(s):
"""Read a single SGF game from a string, returning the parse tree.
s -- 8-bit string
Returns a Coarse_game_tree.
Applies the rules for FF[4].
Raises ValueError if can't parse the string.
If a property appears more than once in a node (which is not permitted by
the... | 4315277a91f732f92c3001cf570221ab6aa657a7 | 16,763 |
import re
def retrieve(
framework,
region,
version=None,
py_version=None,
instance_type=None,
accelerator_type=None,
image_scope=None,
container_version=None,
distribution=None,
base_framework_version=None,
):
"""Retrieves the ECR URI for the Docker image matching the given... | eeee1aec620de5b29650b9605c7fb2b13aed76e5 | 16,764 |
def deconstruct_DMC(G, alpha, beta):
"""Deconstruct a DMC graph over a single step."""
# reverse complementation
if G.has_edge(alpha, beta):
G.remove_edge(alpha, beta)
w = 1
else:
w = 0
# reverse mutation
alpha_neighbors = set(G.neighbors(alpha))
beta_neighbors = set... | fa32a325fd49435e3191a20b908ac0e9c3b992f8 | 16,765 |
def new_followers_view(request):
"""
View to show new followers.
:param request:
:return:
"""
current_author = request.user.user
followers_new = FollowRequest.objects.all().filter(friend=current_author).filter(acknowledged=False)
for follow in followers_new:
follow.acknowledged... | 88277967b8185c47b9bb955dabf6fcd79ea3a530 | 16,766 |
def inv(a, p):
"""Inverse of a in :math:`{mathbb Z}_p`
:param a,p: non-negative integers
:complexity: O(log a + log p)
"""
return bezout(a, p)[0] % p | d2caab3a564d5f58d1be345900382e762350a2ea | 16,767 |
import os
import zipfile
def get_iSUN(location=None):
"""
Loads or downloads and caches the iSUN dataset.
@type location: string, defaults to `None`
@param location: If and where to cache the dataset. The dataset
will be stored in the subdirectory `iSUN` of
l... | 76f429a8caf4090b1df09550e3455888928f71d6 | 16,768 |
def metadata_columns(request, metadata_column_headers):
"""Make a metadata column header and column value dictionary."""
template = 'val{}'
columns = {}
for header in metadata_column_headers:
columns[header] = []
for i in range(0, request.param):
columns[header].append(templa... | ca1f89935260e9d55d57df5fe5fbb0946b5948ac | 16,769 |
def all_done_tasks_for_person(person, client=default):
"""
Returns:
list: Tasks that are done for given person (only for open projects).
"""
person = normalize_model_parameter(person)
return raw.fetch_all("persons/%s/done-tasks" % person["id"], client=client) | 68883d7ac9c1e0cd009ff02ae4944782ae6fc637 | 16,770 |
def transform_cfg_to_wcnf(cfg: CFG) -> CFG:
"""
Transform given cfg into Weakened Normal Chomsky Form (WNCF)
Parameters
----------
cfg: CFG
CFG object to transform to WNCF
Returns
-------
wncf: CFG
CFG in Weakened Normal Chomsky Form (WNCF)
"""
wncf = (
c... | 55d72634b02feab7150d290619b40fc2976ffae3 | 16,771 |
def add_def() -> bool:
""" Retrieves the definition from the user and
enters it into the database.
"""
logger.info("Start <add_def>")
fields = ["what", "def_body", "subject"]
fields_dict = {"what": '', "def_body": '', "subject": ''}
for fi in fields:
phrase = PHRASES[fi]
fi... | 20888544e2e7293c5226b62532ffa32a4aa2b874 | 16,772 |
def insert_scope_name(urls):
"""
given a tuple of URLs for webpy with '%s' as a placeholder for
SCOPE_NAME_REGEXP, return a finalised tuple of URLs that will work for all
SCOPE_NAME_REGEXPs in all schemas
"""
regexps = get_scope_name_regexps()
result = []
for i in range(0, len(urls), 2)... | 28cda0956f232adf176666c776b39463caca9847 | 16,773 |
def fit_cochrane_orcutt(ts, regressors, maxIter=10, sc=None):
"""
Fit linear regression model with AR(1) errors , for references on Cochrane Orcutt model:
See [[https://onlinecourses.science.psu.edu/stat501/node/357]]
See : Applied Linear Statistical Models - Fifth Edition - Michael H. Kutner , page 492... | 958ca88e6ac37ebd58c7f1ff88c191d801e4cb87 | 16,774 |
def get_nodeweight(obj):
"""
utility function that returns a
node class and it's weight
can be used for statistics
to get some stats when NO Advanced Nodes are available
"""
k = obj.__class__.__name__
if k in ('Text',):
return k, len(obj.caption)
elif k == 'ImageLink' and obj... | 1ab88f73621c8396fca08551dd14c9a757d019ad | 16,775 |
def CMYtoRGB(C, M, Y):
""" convert CMY to RGB color
:param C: C value (0;1)
:param M: M value (0;1)
:param Y: Y value (0;1)
:return: RGB tuple (0;255) """
RGB = [(1.0 - i) * 255.0 for i in (C, M, Y)]
return tuple(RGB) | cfc2c7b91dd7f1faf93351e28ffdd9906613471a | 16,776 |
def update_local_artella_root():
"""
Updates the environment variable that stores the Artella Local Path
NOTE: This is done by Artella plugin when is loaded, so we should not do it manually again
"""
metadata = get_metadata()
if metadata:
metadata.update_local_root()
return True... | 23fb9f0eb47aec566dc6b9862474535545b963dc | 16,777 |
def app_tests(enable_migrations, tags, verbosity):
"""Gets the TestRunner and runs the tests"""
# prepare the actual test environment
setup(enable_migrations, verbosity)
# reuse Django's DiscoverRunner
if not hasattr(settings, 'TEST_RUNNER'):
settings.TEST_RUNNER = 'django.test.runner.Disc... | c56ca20ea98dadf97f39a30e2f07c0eb3952b418 | 16,778 |
def quicksort(numbers, low, high):
"""Python implementation of quicksort."""
if low < high:
pivot = _partition(numbers, low, high)
quicksort(numbers, low, pivot)
quicksort(numbers, pivot + 1, high)
return numbers | 064aa30f032036aa73f08b2b94ce4556ffc565fd | 16,779 |
import scipy
def bsput_delta(k, t, *, x0=1., r=0., q=0., sigma=1.):
"""
bsput_delta(k, t, *, x0=1., r=0., q=0., sigma=1.)
Black-Scholes put option delta.
See Also
--------
bscall
"""
r, q = np.asarray(r), np.asarray(q)
d1, d2 = bsd1d2(k, t, x0=x0, r=r, q=q, sigma=sigma)
retur... | d6e1e3e6c2f97fa856b156170ac49ea3d5530423 | 16,780 |
from typing import Sequence
import re
def regex_filter(patterns: Sequence[Regex], negate: bool = False, **kwargs) -> SigMapper:
"""Filter out the signals that do not match regex patterns (or do match if negate=True)."""
patterns = list(map(re.compile, patterns))
def filt(sigs):
def map_sig(sig):
... | 4c76d4bd5f76d5d35373ec14c910291b155cd4db | 16,781 |
def cpncc(img, vertices_lst, tri):
"""cython version for PNCC render: original paper"""
h, w = img.shape[:2]
c = 3
pnccs_img = np.zeros((h, w, c))
for i in range(len(vertices_lst)):
vertices = vertices_lst[i]
pncc_img = crender_colors(vertices, tri, pncc_code, h, w, c)
pnccs... | 8c7e380b56e26197cfb6b9b65c8d373ada0be4b1 | 16,782 |
import time
def run_net(X, y, batch_size, dnn, data_layer_name, label_layer_name,
loss_layer, accuracy_layer, accuracy_sink, is_train):
"""Runs dnn on given data"""
start = time.time()
total_loss = 0.
run_iter = dnn.learn if is_train else dnn.run
math_engine = dnn.math_engine
accur... | 43121dff269df6a03763f130e8f75f0ce6984a57 | 16,783 |
from typing import Any
import json
def json_safe(arg: Any):
"""
Checks whether arg can be json serialized and if so just returns arg as is
otherwise returns none
"""
try:
json.dumps(arg)
return arg
except:
return None | 97ac87464fb4b31b4fcfc7896252d23a10e57b72 | 16,784 |
def _key_iv_check(key_iv):
"""
密钥或初始化向量检测
"""
# 密钥
if key_iv is None or not isinstance(key_iv, string_types):
raise TypeError('Parameter key or iv:{} not a basestring'.format(key_iv))
if isinstance(key_iv, text_type):
key_iv = key_iv.encode(encoding=E_FMT)
if len(key_iv) > ... | 809ff811a433f9843b330a56be926411871d8b7a | 16,785 |
def decomposeArbitraryLength(number):
"""
Returns decomposition for the numbers
Examples
--------
number 42 : 32 + 8 + 2
powers : 5, 3, 1
"""
if number < 1:
raise WaveletException("Number should be greater than 1")
tempArray = list()
current = number
position = 0
... | 5645c9024dd93aa3bfaf904d7a69f4d46977fb5a | 16,786 |
def ax_draw_macd2(axes, ref, kdata, n1=12, n2=26, n3=9):
"""绘制MACD
:param axes: 指定的坐标轴
:param KData kdata: KData
:param int n1: 指标 MACD 的参数1
:param int n2: 指标 MACD 的参数2
:param int n3: 指标 MACD 的参数3
"""
macd = MACD(CLOSE(kdata), n1, n2, n3)
bmacd, fmacd, smacd = macd.getResult(0),... | 3bcb73756211a8906f3bf601207092177aa45ade | 16,787 |
import scipy
def scipy_bfgs(
criterion_and_derivative,
x,
*,
convergence_absolute_gradient_tolerance=CONVERGENCE_ABSOLUTE_GRADIENT_TOLERANCE,
stopping_max_iterations=STOPPING_MAX_ITERATIONS,
norm=np.inf,
):
"""Minimize a scalar function of one or more variables using the BFGS algorithm.
... | e1d61454e7ea782d37b4ab222599c69b2c89df1b | 16,788 |
from random import shuffle
import six
def assign_to_coders_backend(sample,
limit_to_unassigned,
shuffle_pieces_before_assigning,
assign_each_piece_n_times,
max_assignments_per_piece,
coders, max_pieces_per_coder,
creation_time, creator):
"""Assignment to coders curr... | ffe59dce1b85f7b77e652a1823f298b643d104c7 | 16,789 |
def mask_rcnn_heads_add_mask_rcnn_losses(model, blob_mask):
"""Add Mask R-CNN specific losses."""
loss_mask = model.net.SigmoidCrossEntropyLoss(
[blob_mask, 'masks_int32'],
'loss_mask',
scale=model.GetLossScale() * cfg.MRCNN.WEIGHT_LOSS_MASK
)
loss_gradients = blob_utils_get_loss... | 1f94662948d2576874ca4bb13a602e0a0482d787 | 16,790 |
def parse_ns_headers(ns_headers):
"""Ad-hoc parser for Netscape protocol cookie-attributes.
The old Netscape cookie format for Set-Cookie can for instance contain
an unquoted "," in the expires field, so we have to use this ad-hoc
parser instead of split_header_words.
XXX This may not make the bes... | 91d1006d6495b1ad86ff65abbc1575d9c759f183 | 16,791 |
def same_kind_right_null(a: DataType, _: Null) -> bool:
"""Return whether `a` is nullable."""
return a.nullable | 005e9d62702d8f9c6d1e1a4911c7dedf7d81bb73 | 16,792 |
def unary_col(op, v):
"""
interpretor for executing unary operator expressions on columnars
"""
if op == "+":
return v
if op == "-":
return compute.subtract(0.0, v)
if op.lower() == "not":
return compute.invert(v)
raise Exception("unary op not implemented") | ff4eec1f333cd0425cb1b7c533ec4dc94179512e | 16,793 |
def test_start_sep_graph() -> nx.Graph:
"""test graph with known clique partition that needs start_separate"""
G = nx.Graph()
G.add_nodes_from(range(6))
G.add_edges_from([(0, 1, {'weight': 1.0}), (0, 2, {'weight': -10}), (0, 3, {'weight': 1}), (0, 4, {'weight': -10}), (0, 5, {'weight': -10}),
... | 84bd5a140ff7c8882513395a305f69d64d1830a7 | 16,794 |
def structure(table_toplevels):
"""
Accepts an ordered sequence of TopLevel instances and returns a navigable object structure representation of the
TOML file.
"""
table_toplevels = tuple(table_toplevels)
obj = NamedDict()
last_array_of_tables = None # The Name of the last array-of... | c34590f604d52ff4bfcf3cf1bae1fc41a7a1f3ec | 16,795 |
import math
def h(q):
"""Binary entropy func"""
if q in {0, 1}:
return 0
return (q * math.log(1 / q, 2)) + ((1 - q) * math.log(1 / (1 - q), 2)) | ad3d02d6e7ddf622c16ec8df54752ac5c77f8972 | 16,796 |
def has_next_page(page_info: dict) -> bool:
"""
Extracts value from a dict with hasNextPage key, raises an error if the key is not available
:param page_info: pagination info
:return: a bool indicating if response hase a next page
"""
has_next_page = page_info.get('hasNextPage')
if has_next... | 13c7bf0096127e054adaa8a331d2168bfb76c1d3 | 16,797 |
def _stuw_code(current_name=None):
""""
Zoekt door TYPESTUW naar de naam van het stuwtype, geeft attribuut waarde uit DAMO
"""
if current_name not in TYPESTUW.values():
return 99
for i, name in TYPESTUW.items():
if name == current_name:
return i | f0444885fd9956bdb150442dc1de7de09a0ac693 | 16,798 |
def _build_init_nodes(context, device):
"""
Build initial inputs for beam search algo
"""
decoder_input = _prepare_init_inputs(context, device)
root_node = BeamSearchNode(None, None, decoder_input, 0, len(context))
return [root_node] | 009cf7b09f39eb5c9722015d310ecab0b32f7c59 | 16,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.