content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def hyperheader2dic(head):
"""
Convert a hypercomplex block header into a python dictionary.
"""
dic = dict()
dic["s_spare1"] = head[0]
dic["status"] = head[1]
dic["s_spare2"] = head[2]
dic["s_spare3"] = head[3]
dic["l_spare1"] = head[4]
dic["lpval1"] = head[5]
dic["rpva... | 3fd2611b52491e16a8402ba7a2755b723e13601d | 38,881 |
def convert_order_to_href(keystone_id, order_id):
"""Convert the tenant/order IDs to a HATEOS-style href."""
if order_id:
resource = 'orders/' + order_id
else:
resource = 'orders/????'
return utils.hostname_for_refs(keystone_id=keystone_id, resource=resource) | fa87d2e992df5be3e94ed60bf506da4ae282daa3 | 38,882 |
def pretty_struct(ctx, title, args, kwargs, sep=' :: '):
"""Pretty print a struct."""
kwargs = {f'{k}<<{sep}>>': v
for k, v in kwargs.items()}
return pp.pretty_call_alt(ctx, str(title), args, kwargs) | bf0e12c9eca187f3959d77b244c1c6625ee382b8 | 38,883 |
def Gerrity_score(contingency):
"""
Returns Gerrity equitable score given a contingency table
Author: Dougie Squire
Date: 12/05/2018
Parameters
----------
contingency : xarray DataArray
A contingency table of the form output from doppyo.skill.co... | 288aecd1581cbd71d167dbaab9c1b281146d8aba | 38,884 |
def parse_args():
"""
Parse and establish the arguments we take in on the CLI
"""
parser = ArgumentParser(description="Mirror a Red Hat mirror.")
# Programmatic Things
parser.add_argument("-b", "--base", dest="base",
help="The remote base URL of the OS you want to "
... | f3f1f12e2496533de7cfaa87d59c9a598f8d879a | 38,885 |
from datetime import datetime
import pytz
def get_course_assignments(course_key, user, include_access=False): # lint-amnesty, pylint: disable=too-many-statements
"""
Returns a list of assignment (at the subsection/sequential level) due dates for the given course.
Each returned object is a namedtuple wit... | 2efa2fa18921d4391f8aa2529c7801dba2df745d | 38,886 |
def ltl_tp(L, out = None):
"""
L.T @ L with a lower triangular matrix.
Parameters
----------
L : (np, ...) ndarray
Lower triangular matrix in packed storage.
out : (np, ...) ndarray
Output buffer. If None, this will be created.
If out = L, then in-place multiplication i... | 9294e316f0285906bcdf24af976fdf4e5f46ba90 | 38,887 |
def return_dictionary_list(lst_of_tuples):
""" Returns a dictionary of lists if you send in a list of Tuples"""
orDict = defaultdict(list)
# iterating over list of tuples
for key, val in lst_of_tuples:
orDict[key].append(val)
return orDict | c495aa209def87f947c7347d84941abecc6c39b2 | 38,888 |
from typing import Any
def force_bytes(
s: Any,
encoding: str = 'utf-8',
strings_only: bool = False,
errors: str = 'strict',
) -> bytes:
"""
Similar to smart_bytes, except that lazy instances are resolved to
strings, rather than kept as lazy objects.
If strings_only is... | e990853108696879e360ca42bb108cc71d6f4f2d | 38,889 |
def delete_content():
"""
DESC : Fonction permettant de supprimer un contenu
"""
try:
compte_id, access = get_jwt_identity().split("+")
content_id = request.get_json().get("content_id")
if compte_id:
try:
CURSOR.execute("""
DEL... | 7c70d380f87e657c6ada02669e50b9587819717a | 38,890 |
def collect_nested(expr):
"""
Collect numeric coefficients, trascendental functions, and symbolic powers,
across all levels of the expression tree.
The collection gives precedence to (in order of importance):
1) Trascendental functions,
2) Symbolic powers,
3) Numeric coefficien... | 534cff29bbcc0dc6faa83a1fe9929ec176bebde1 | 38,891 |
def euler2(f2p, b, t, h, p):
"""
tuple b = boundary condition (x0, y0, y'0)
float h = step
int t = number of steps
lambda f2p = dy/dx
int p = significant digits after x values
"""
x = b[0]
y = b[1]
yp = b[2]
y2p = f2p(x, y, yp)
ret = [(x, y)] #list of tuples to be returned with x and ... | 67e390f0c21ba87d8aeec97920403c2d62678dc9 | 38,892 |
def Conv2D(in_channels, out_channels, kernel_size, dropout=0, weight_norm=False, **kwargs):
"""Weight-normalized Conv2d layer"""
m = nn.Conv2d(in_channels, out_channels, kernel_size, **kwargs)
nn.init.normal_(m.weight, mean=0, std=0.1)
nn.init.constant_(m.bias, 0)
if weight_norm:
return nn.u... | 43240086ef50cf3edc4bfcbf1fea422eac0f339d | 38,893 |
def get_profile():
"""Obtain the profile of the logged in user."""
user = util.user_from_jwt(request.get_json().get('token'))
if not user:
return api_error(m.USER_NOT_FOUND), 404
response = {
'username': user.username,
'name': user.name,
}
return api_success(**response... | 902f2c76fadb092d002de9cd16ec3e850be0ea9f | 38,894 |
def parse_int(text: str) -> int:
"""
Takes in a number in string form and returns that string in integer form
and handles zeroes represented as dashes
"""
text = text.strip()
if text == '-':
return 0
else:
return int(text.replace(',', '')) | 1f49a2d75c2fadc4796456640e9999796fddfa93 | 38,897 |
def english_to_french(english_text):
"""
This Function Translates input text from English-French
"""
translate = language_translator.translate(
text = english_text,
model_id = 'en-fr').get_result()
french_text = translate['translations'][0]['translation']
return french_text | 0e9a5797b3299d4cd76fe2b5acfa3ca90efda7b8 | 38,898 |
def pred_transform(image, target):
"""
:param image: ndarray[H, W, C] RGB
:param target: None
:return: ndarray[H, W, C] RGB 0-255, None"""
image = resize_pad(image, image_size, False, 32, False, 114)[0]
return image, target | e742f0549b08c8dc2cb2f505c24c80653d0d4a50 | 38,899 |
def _get_object_url_for_region(region, uri):
"""Internal function used to get the full URL to the passed PAR URI
for the specified region. This has the format;
https://objectstorage.{region}.oraclecloud.com/{uri}
Args:
region (str): Region for cloud service
uri (str): ... | 72b069e1657b94c7800ba7e5fd2269909e83c856 | 38,900 |
def _sx_source_idx_delta(azimuths, radius, dx, dy):
"""Compute indices of pixels that lie at a distance 'radius' from
the target, in the direction of 'azimuths'.
"""
azimuths_rad = np.deg2rad(azimuths)
delta_y_idx = np.rint(radius / dy * np.cos(azimuths_rad))
delta_x_idx = np.rint(radius / dx *... | fe56feecc50df58b6f6b448383c16f992dfa6671 | 38,901 |
def _create_motion_field(input_precip, motion_type):
"""
Create idealized motion fields to be applied to the reference image.
Parameters
----------
input_precip: numpy array (lat, lon)
motion_type : str
The supported motion fields are:
- linear_x: (u=2, v=0)
-... | e5a56c0f80ac894017cc5393512cb409adda16a3 | 38,902 |
from typing import Callable
from typing import Any
import threading
def build_walker(concurrency: int) -> Callable[..., Any]:
"""Return a function for waling a graph.
Passed to :class:`runway.cfngin.plan.Plan` for walking the graph.
If concurrency is 1 (no parallelism) this will return a simple topologi... | a064b48f82c8c8390a915362991473123a88662f | 38,903 |
import numpy
def calculate_severity_distribution(elt, grid_size=2**14, max_loss_factor=5):
""" This function calculates the severity distribution or the distribution
of the size of losses, given that an event has occurred
----------
elt : pandas dataframe containing ELT
Returns
-------
se... | c101622e0d3460ff4e96f2b26139389cf1172397 | 38,905 |
def full_like(other, nodata=None, lazy=False):
"""Return a full object with the same grid and geospatial attributes as ``other``.
Arguments
---------
other: DataArray
DataArray from which coordinates and attributes are taken
nodata: float, int, optional
Fill value for new DataArray,... | 54b4e88c78a122ae1a339540228272c98e7ce311 | 38,907 |
def linear_mcca_resps_only(all_data, new_chans, o_dim):
"""
LINEAR MCCA WITH ONLY THE N SUBJECTS' EEG RESPONSES.
THE COMMON STIMULUS IS NOT CONSIDERED FOR THE MCCA STEP.
ARGUMENTS:
all_data: AN (N+1) ELEMENTS LIST WITH N EEG RESPONSES AND THE ELEMENT AS THE COMMON STIMULI DATA.
... | 9f60676ebf19bfbfff4fd946ec9067937d383649 | 38,909 |
def _CanCreateRevertForCulprit(parameters, analysis_id):
"""Checks if a culprit can be reverted by a specific analysis.
The culprit can be reverted by the analysis if:
No revert of this culprit is complete or skipped, and
no other pipeline is doing the revert on the same culprit.
"""
culprit = entity_u... | 90d0204a6a326c2db61b0f59003c1a54197e21b5 | 38,910 |
def read_selection(*args):
"""read_selection(ea_t ea1, ea_t ea2) -> bool"""
return _idaapi.read_selection(*args) | 86bebb1493b5aec209f672e3f8b3d6848871a58d | 38,911 |
def losses_and_metrics(num_classes):
"""
Define loss and metrics
Loss: Categorical Crossentropy
Metrics: (Train, Validation) Accuracy, Precision, Recall, F1
Returns:
loss, train loss, train acc, valid loss, valid acc, precision, recall, auc, f1
"""
loss_fn = CategoricalCrossentropy... | e8129cb9ed48ef3024b0d9062491ecceefceedd8 | 38,912 |
def get_spans():
"""
Get and flush all spans
:return:
"""
global spans
with span_lock:
r = spans
spans = []
return r | 5fe90a4e9cc69674c4503056c042bc78cd6ff855 | 38,914 |
def sign(message, key):
"""Signs a string 'message' with the private key 'key'"""
if 'p' not in key:
raise Exception("You must use the private key with sign")
return chopstring(message, key['d'], key['p']*key['q'], encrypt_int) | c5cd017d0dd97b50077dbc078f56789c049d2f1a | 38,915 |
def GTreeGPMutatorOperation(genome, **args):
""" The mutator of GTreeGP, Operation Mutator
.. versionadded:: 0.6
The *GTreeGPMutatorOperation* function
"""
if args["pmut"] <= 0.0:
return 0
elements = len(genome)
mutations = args["pmut"] * elements
ga_engine = args["ga_engine"]
gp_... | 3edfc6e5326f709f7b7adc4731250aa67b9779ef | 38,916 |
def sequence_delta(previous_sequence, next_sequence):
""" Check the number of items between two sequence numbers. """
if previous_sequence is None:
return 0
delta = next_sequence - (previous_sequence + 1)
return delta & 0xFFFFFFFF | 8580c26d583c0a816de2d3dfc470274f010c347f | 38,917 |
import re
def is_email(email: str) -> bool:
""" Uses regex to check if a incoming string is an email address"""
regex = "^([a-zA-Z0-9]+[\\._-]?[a-zA-Z0-9]+)[@](\\w+[.])+\\w{2,3}$"
return re.search(regex, email) | a332f39a3662f764c0f4e0782196393ac606e038 | 38,918 |
def matrix_plot_input(result, kde=False, margins=None):
"""
"""
input_sample = result.input_sample
if margins:
sample = np.zeros(input_sample.shape)
for i, marginal in enumerate(margins):
for j, ui in enumerate(input_sample[:, i]):
sample[j, i] = marginal.com... | 3f0749684377c3ba73e5b58c4d7d9b36b012b8d0 | 38,919 |
def train_and_predict(k, D_tr, D_te, nontf_X, tfs, genes):
"""Train classifier and predict gene responses.
"""
logger.info('Cross validating fold {}'.format(k))
tf_X_tr, y_tr = D_tr
tf_X_te, y_te = D_te
tfs_tr, tfs_te = tfs
X_tr = np.hstack([tf_X_tr, np.vstack([nontf_X for i in range(len(... | b86ca9af29791a9f748aeaf5d2deb29e388e08a3 | 38,920 |
import pandas
import types
def hpat_pandas_series_ne(self, other, level=None, fill_value=None, axis=0):
"""
Pandas Series method :meth:`pandas.Series.ne` implementation.
.. only:: developer
Test: python -m hpat.runtests hpat.tests.test_series.TestSeries.test_series_op8
Parameters
--------... | 2173e968fba6027db950f9ede334b9c054642c37 | 38,921 |
def _unescape_serialized_class(dct):
# type: (Dict[str, Any]) -> Dict[str, Any]
"""
Unescape serialized '__class__' key.
:param dct: Serialized dictionary.
:return: Unescaped serialized dictionary.
"""
if _ESCAPED_SERIALIZED_CLASS_KEY in dct:
dct = dct.copy()
dct[_SERIALIZED... | 1f66f99b019243f24f24e85b173ad6bb83139a46 | 38,922 |
def get_transitions(data_vals, threshold, hysteresis):
"""
Find the high-to-low and low-to-high state transistions
"""
pend_len, time_vals, sens_vals = data_vals
# Get initial state
if sens_vals[0] > threshold:
state = 'high'
else:
state = 'low'
# Find state changes
... | 144a6463178820ef1cc6a6943cda5fe2e7117274 | 38,923 |
def load_from_file(filename, key):
"""
Loads an object from a .pkl file or a .py file/module.
If a .pkl file, returns the object.
If a .py file, returns the object named key within that file
"""
#Check for pickle first
if filename[-4:]=='.pkl':
with open(filename,'rb') as file:
... | fc1b7ae35c0edadbeaea52aa4f5645d6577b5ac5 | 38,925 |
def get_our_template(ours):
"""get template in the form of 23 keypoints ours
Args:
-ours: a list of length 92 [x1,y1,z1,c1,x2,y2,z2,c2,......]
Returns:
ours_form: 3 by 13 numpy array
"""
ours_0 = np.asarray(ours).reshape((-1,4)).T[0:3,:] # 3 by 23
ours_head = (ours_0[:,0].copy(... | 4bdad9bba592c172e6a86790df7df5a7d8b0c0ef | 38,926 |
def single_number_generalized(nums, k, l):
"""
Given an array of integers, every element appears k times except for one.
Find that single one which appears l times.
We need a array x[i] with size k for saving the bits appears i times.
For every input number a, generate the new counter by
x[j] =... | 90e28c2023622f23e808b89bb255d67aefe7bda8 | 38,927 |
def variant(name):
"""
:doc: screens
Returns true if a `name` is a screen variant that can be chosen
by Ren'Py. See :ref:`screen-variants` for more details. This function
can be used as the condition in a Python if statement to set up the
appropriate styles for the selected screen variant.
... | f9f4079c29f85a727ec184f74df57c28887b9ee4 | 38,929 |
def quat_to_rot(normalized_quat):
"""Convert a normalized quaternion to a rotation matrix."""
rot_tensor = jnp.sum(
np.reshape(QUAT_TO_ROT, (4, 4, 9)) *
normalized_quat[..., :, None, None] *
normalized_quat[..., None, :, None],
axis=(-3, -2))
rot = jnp.moveaxis(rot_tensor, -1, 0) # Unstac... | 22041ad7ec691009e5c61ac13b3272c1b7188035 | 38,930 |
def read_tops(path, skip=-999.25000, delimiter='\t', header=0, colnames=[]):
"""
Read well tops file into dataframe
Parameters:
path (string): path to the well tops file
skip (): NaN identifier in the selected file
delimiter (char): character or list of characters used to separate... | 0052f3e924d26500d8c02513e0b7a7d244960bfe | 38,931 |
from userbot.modules.sql_helper.globals import gvarstatus
async def translateme(trans):
"""For .trt command, translate the given text using Google Translate."""
translator = Translator()
textx = await trans.get_reply_message()
message = trans.pattern_match.group(1)
if message:
pass
eli... | 1a31f1775d2f52e99b9307c64b4d264a174d734d | 38,933 |
def guests():
"""
Overview over all non_vip guests.
:return:
"""
class ItemTable(Table):
guest_id = Col('Guest ID')
items = db_helper.get_paying_sessions()
table = ItemTable(items)
return render_template('service.html',
service_description='If you ar... | 6a97c5980520773708588879fd96b7a2c25ca448 | 38,934 |
import random
def distribution_generator(num_samples, distribution_type, mean=0, sd=1, interval=1, n=1, p=0.5):
""" Generate random data within a given distribution
:param num_samples: Int The number of samples to be returned
:param distribution_type: String The type of distribution to be used
:param... | 581d08202297f30c40be8de0527d19fe04939010 | 38,936 |
import re
def getrevision(binary):
"""returns the revision string from binary"""
revision = ""
with open(binary, "rb") as rtgt:
stream = rtgt.read()
sppattern = re.compile(r"storpool_revision=[a-z0-9\.]+")
results = set(sppattern.findall(stream))
if results:
assert len(results)... | e514ed1397002fa7c69ef963acaf1d70ff132389 | 38,937 |
def edit(request, id):
"""
Edit contact information. Address, Email and Phone records are provided as inlineformsets.
**Templates:**
* ``rolodex/edit.html``
**Template Variables:**
* person, person_form, email_formset
"""
person = get_object_or_404(Person, id=id)
EmailFormset... | 57a419c9ea093cd6cd3f1ba4eb6cda0dd5ea2a0e | 38,938 |
def gSquared(properFrame):
"""
The gradient squared at each pixel of the image, also known as the convolution
of a Laplacian kernel across the image.
Optimized via `numba`.
Edge values are padded with values of 0.
Parameters
----------
properFrame : np.ndarray[H,W]
An array r... | 99f26632804178f68d80f0780361020ee2dbe91d | 38,939 |
def wallet_opened(func):
"""
:param func:
:return:
"""
@wraps(func)
def wapper(self, *args, **kwargs):
if not self.Wallet:
console_log.error("No opened wallet, please open wallet first")
return None
else:
return func(self, *args, **kwargs)
... | 251d03a283ff916b0f7aa439f15579fd3b1dd03b | 38,940 |
import copy
def subtract_electron_shells(s1, s2, rel_tol=0.0):
"""
Returns the difference between two lists of electron shells (s1 - s2)
This will remove any shells from s1 that are also in s2, within a tolerance
"""
diff_shells = []
for sh1 in s1:
for sh2 in s2:
if compa... | a8480d3eb06fccc9de70d7276a3a83ec1b63ecc4 | 38,941 |
import re
def is_enabled_path(path):
"""
Determine whether or not the path matches one or more paths
in the ENABLED_PATHS setting.
:param path: A string describing the path to be matched.
"""
for enabled_path in ENABLED_PATHS:
match = re.search(enabled_path, path[1:])
if match... | a0d7cb077b4f22bbd72c448383c6c064142037d7 | 38,942 |
import logging
def insert_context(session, run_id: str, algorithm: str, parameters: str) -> Contexts:
"""
method to insert values to the events table
:param session: database session
:param run_id: run_id
:param algorithm: algorithm
:param parameters: parameters
:re... | 093b9cd5b565f2b2bf38c7a62dee817bb71ca12c | 38,943 |
import re
def find_matched_pos(str, pattern):
""" Find all positions (start,end) of matched characters
>>> find_matched_pos('ss12as34cdf', '\d')
[(2, 3), (3, 4), (6, 7), (7, 8)]
"""
match_objs = re.finditer(pattern ,str)
match_pos = [match_obj.span() for match_obj in match_objs]
return ma... | 17e352299d7874bdfb66a4a181d04e90fba0af7e | 38,944 |
def reccyl(rectan1):
"""reccyl(ConstSpiceDouble [3] rectan1)"""
return _cspyce0.reccyl(rectan1) | 5e4eb9fb30de014c998b07410cc7311901682da4 | 38,945 |
def get_message_from_dict(d):
"""Create a TAXIIMessage object from a dictonary.
This function automatically detects which type of Message should be created
based on the 'message_type' key in the dictionary.
Args:
d (dict): The dictionary to build the TAXII message from.
Example:
.... | 3c2a2522402cc573752c1c40bb9c952634279ef1 | 38,946 |
import codecs
def diff_files(initial_path, new_path):
"""
Given two files, open them to variables and pass them to diff_strings
for diffing.
:type initial_path: object
:param initial_path: initial file to diff against
:type new_path: object
:param new_path: new file to compare to f1
:... | 91cea1cb3cd61ee1c0f065b85913cd36734fbdd3 | 38,947 |
from typing import Optional
from typing import Iterator
from typing import List
import types
def script(
description: str = "",
category: Optional[str] = None,
gesture: Optional[str] = None,
gestures: Optional[Iterator[str]] = None,
canPropagate: bool = False,
bypassInputHelp: bool = False,
allowInSleep... | a7902fc067452c5c43ed294f52564d93d0640fbb | 38,948 |
def get_doc_vec_keyedvectors(kv_obj, doc_counter, dict_df, avg_scheme):
"""
Calculates a document embedding via weighted averaging
Parameters
----------
kv_obj: KeyedVectors-like object
doc_counter: Counter() that contains the same information as an entry in VowpalWabbit file
dict_df: panda... | 21ec82b6c1ca5dfbf683645e780a585b052a47bc | 38,949 |
def shift_right(shift_register, bit_count):
"""Shifts the least significant bits out of the shift register by the given
amount.
Parameters:
shift_register (ShiftRegister): The shift register to operate on.
bit_count (int): The number of bits to shift out.
Returns:
(ShiftRegister, int): New... | f2e2e491d1f869b50632bb8498c51ffee4a970f8 | 38,950 |
def mark_corners(image, harris_scores, settings, progress_consumer, progress):
"""
A helper method we use to make the marks of corner as rectangles or bold circles, rather than single pixels.
Use a blank image (black), then light up the pixels that have been found by Harris Detector
This way we create a... | 88b3c5ad6ad454870de5ba4f827704a58baeafb8 | 38,951 |
from typing import Dict
from typing import Optional
from typing import List
from typing import OrderedDict
def build_fairseq_vocab(
vocab_file: str,
dictionary_class: Dictionary = Dictionary,
special_token_replacements: Dict[str, str] = None,
unk_token: str = "<unk>",
max_vocab: int = -1,
min_... | d8b469a613d1cc7c07e94f813cbdc396bbdacc11 | 38,952 |
def score_density(leaderboard):
"""Create a density esitmate figure for each user
It will be useful to keep track of how much each user's score's
vary over time. This will give us a density estimate for each
user's scores.
"""
board = leaderboard.drop(['Submission Time', 'counter'], axis=1)
... | 779657cc87ea2a9321b86a5f7d4b9a66f34f018a | 38,953 |
from xml.dom import minidom
def getSplunkVersion(sessionKey):
""" function to obtain the Splunk software version. This is used to determine parsing of the sessionKey """
base_url = 'https://localhost:8089'
request = urllib2.Request(base_url + '/services/server/info',None,headers = { 'Authorization': ('... | 8d1cd683e78f9f9cce33f94ae207247eae0240f0 | 38,954 |
def preprocessing(filepath,files,product,attr):
"""
文本预处理
:return:
"""
#with open(text_path) as f:
# content = readtxtline(text_path)
# print(content)
content = readexcel(filepath)[product][attr]
return clean_using_stopword(content,files)
return content | 00af91c20ce0d37d1c9836925d32c156b3f7ce53 | 38,955 |
import requests
def fetch_fhpg(code):
"""股票分红配股数据
返回:
list
0: 分红配股
1: 配股一览
2: 增发一览
3: 历年融资计划
"""
url = f'http://quotes.money.163.com/f10/fhpg_{code}.html#01d05'
r = requests.get(url)
attrs = {'class': 'table_bg001 border_box limit_sale'}
dfs = pd.re... | 7283bd502b60635e16ed5251ecbb6ea73214756c | 38,956 |
from typing import Dict
from typing import Any
def run_launcher(config: Configuration) -> Dict[str, Any]:
"""Runs the launcher.
Returns the dict with two entries:
"artifacts" - contain a mapping `Artifact` => `bool denoting if artifact is deploted`
"instances" - contain a mapping `Instance` => `Opti... | f7e6d9d664bb0f88251b1d147548e8e3e737422e | 38,957 |
def black_payers_swaption_value_fprime_by_strike(
init_swap_rate,
option_strike,
swap_annuity,
option_maturity,
vol):
"""black_payers_swaption_value_fprime_by_strike
First derivative of value of payer's swaption with respect to strike
under black model.
See :py:fu... | 53c4519828155f264e64728b3901cd697fb154ea | 38,958 |
def utc2localdatetime(naive):
""" input: naive utc timestamp from dataframe
output: timestamp in local tz """
#print("naive=", naive)
utc = naive.tz_localize(utctz)
#print('utc=', utc)
pac = utc.astimezone(pactz)
#print('pac=', pac)
return pac | fa5b594c60b84177f260beae5a090093a0ec0e7f | 38,959 |
def box_area(box):
"""
Calculates the area of a bounding box.
Source code mainly taken from:
https://www.pyimagesearch.com/2016/11/07/intersection-over-union-iou-for-object-detection/
`box`: the bounding box to calculate the area for with the format ((x_min, x_max), (y_min, y_max))
return: the b... | 3a52a41e8dc92d3a3a2e85a33a4ebcbbb7131091 | 38,960 |
def dsigmoid(sigmoid_x):
"""
dSigmoid(x) = Sigmoid(x) * (1-Sigmoid(x)) = Sigmoid(x) - Sigmoid(x)^2
"""
return sigmoid_x - sigmoid_x**2 | 37e163e6baab1a2b584e9eef726895c919c80406 | 38,961 |
def clip(agera5_dir, day, bbox, add_gridid=False):
"""Extracts a portion of agERA5 for the given bounding box and returns a Xarray dataset.
:param agera5_dir: the path to AgERA5
:param day: the date for which to clip
:param bbox: a BoundingBox object
:param add_idgrid: Add a grid ID (True) or not (... | 1883a4bfb4a0ef16c8b6be4b46ca8e0f75b0566c | 38,962 |
def shortcut_url(url, name):
"""
:param url:
:param name:
:return:
"""
# remove slash at the end
if url.endswith('/'):
url = url[:-1]
# gitlab
gl_prefix = 'https://gitlab.com/'
if url.startswith(gl_prefix):
return [make_icon('gitlab', css='is-link'), make_text(u... | 861e50e57eb61d314711fdc3e48fb9e9485e0a5c | 38,963 |
import requests
import json
from datetime import datetime
def get_day(game):
"""Return single day"""
payload = PAYLOAD_SAMPLE
payload["gameID"] = game.game_id
payload["stateType"] = 12
request = requests.post(game.game_host, headers=HEADERS, json=payload)
text = json.loads(request.text)
... | 192736150b3cda5ee0a7b0d652497e865f960db0 | 38,965 |
def compose_text_context_menu_click (selectedtext) :
"""Translate selected text to LOLSPAEK"""
return translate_to_lolspeak(selectedtext) | 13129b339485637cc216d103b10adc960b6c0cbd | 38,966 |
import typing
def find_blobs(
key:typing.Tuple[int, int, int],
x0s:int, x1s:int, y0s:int, y1s:int, z0s:int, z1s:int) -> \
typing.Tuple[np.ndarray, np.ndarray]:
"""
Find blobs in a volume
:param volume: the volume in question
:param x0s: the starting x coordinate in global coor... | 50bb881810a7c041644578d6bb6901f3f58c5cb1 | 38,967 |
def progress_bar(iteration, total):
"""
entertain the user with a simple yet exquisitely designed progress bar and %
:param iteration:
:param total:
:return:
"""
try:
perc = round((iteration/total)*100, 2)
bar = ('░'*19).replace('░','█',int(round(perc/5,0))) + '░'
ret... | a32bd5edd108142583f0ea1573848c91c6d61c33 | 38,968 |
def make_tensor_seed(seed):
"""Converts a seed to a `Tensor` seed."""
if _is_stateful_seed(seed):
iinfo = np.iinfo(np.int32)
return tf.random.uniform([2],
minval=iinfo.min,
maxval=iinfo.max,
dtype=tf.int32,
... | 108d098fb3be3b9db28ac37ef3c2c32877478cb0 | 38,970 |
def par_auteur(name):
"""
Add 'par' to the author names
"""
author_phrase = ''
if name:
author_phrase = " par {},".format(name)
return author_phrase | a09bbc79cb152239bc178d74ebd11cc0f74c1d30 | 38,971 |
from typing import Dict
from typing import List
def remove_items(item_capacities:Dict[str,int], items_to_remove:List[str])->Dict[str,int]:
"""
Remove the given items from the given dict.
>>> stringify(remove_items({"x":3, "y":2, "z":1, "w":0}, ["x","y"]))
'{x:2, y:1, z:1}'
>>> stringify(remove_it... | c17b972050b4054121fffd478dd3252f90959b8a | 38,972 |
from typing import Dict
from typing import Any
from typing import List
def split_results(result: Result, agg_info:Dict[Any, Any]) -> List[Result]:
"""Retrieve the results of the initial quantum circuits from the aggregated result
Args:
result (Result): Result of the aggregated QuantumCircuit
... | 030c8a08a7932b591e412db9ec208c8805b42c1f | 38,973 |
def text_value(value):
"""Force a value to text, render None as an empty string."""
if value is None:
return ""
return force_text(value) | 5260ebb8b0c0932b44d1ff77f48bc9c5d905588b | 38,974 |
import torch
import time
def train(fcstnet, train_x, train_y, validation_x=None, validation_y=None, restore_session=False):
"""
Train the ForecastNet model on a provided dataset.
In the following variable descriptions, the input_seq_length is the length of the input sequence
(2*seasonal_period in th... | eadf791c6679fc6c5acf575d26be510236d58891 | 38,975 |
def get_networks_for_instance(context, instance):
"""Returns a prepared nw_info list for passing into the view builders
We end up with a data structure like::
{'public': {'ips': [{'address': '10.0.0.1',
'version': 4,
'mac_address': 'aa:aa:aa:aa... | 551e5bedd81784c7fa4a4c986a03d0a56d578437 | 38,976 |
def load_article_from_nif_file(nif_file, corpus_name, limit=1000000):
"""
Load a dataset in NIF format.
"""
print(f'NOW LOADING THE NIF FILE {nif_file}')
g = Graph()
#for nif_file in glob.glob('%s/*.ttl' % nif_dir):
g.parse(nif_file, format="n3")
print(f'THE FILE {nif_file} IS LOADED. N... | fc55d671969b958249a91d630698f8b29982fc0b | 38,977 |
from typing import List
def _draw_equal_dataset(
target: np.ndarray, num_samples: int = 1000, allowed_classes: List[int] = None
) -> np.ndarray:
"""
given the `target` and `num_samples`, return the labeled_index`
:param target: target
:param num_samples: 4000
:param allowed_classes: None or li... | e89462e403976a714d5197bd515311044735a613 | 38,978 |
def firstof(parser, token):
"""
Outputs the first variable passed that is not False.
Outputs nothing if all the passed variables are False.
Sample usage::
{% firstof var1 var2 var3 as myvar %}
This is equivalent to::
{% if var1 %}
{{ var1 }}
{% elif var2 %}
... | 6e83b26fbba4e977d83eb943e27a8f272d85b358 | 38,979 |
def canPickupPile(top_card, prepared_cards, played_cards, round_index):
"""Determines if the player can pick up the pile with their suggested play"""
top_key = None
try:
key_opts = getKeyOptions(top_card)
except:
raise Exception("Cannot pickup the pile on 3s because you cannot play 3s")
... | 7a5f27884475abcc2437412ebdaa9ada305a2237 | 38,980 |
def _valid_arg(*args, src=None):
"""Return some data, possibly extracted from an AxisManager (or
dict...), based on the arguments args. This is to help with
processing function arguments that override a default behavior
which is to look up a thing in axisman. For example::
signal = _valid_arg(s... | d410ee09451473999f2b072b92365f5631207888 | 38,981 |
def find_nearest_store(lat_lng, stores, units):
"""Finds store from list of stores that is closest to a given set of coords.
Args:
lat_lng (list(float)): Latitude and longitude being compared to.
stores (list(dict)): List of stores to search against.
units (str): Distance metric used fo... | 11460b73d2d0e4e5b1b39c2b060a836ccc97e0c9 | 38,982 |
def aumentar(p, tax):
"""
-> Aumenta o valor inicial em uma porcentagem definida pelo usuário
:param p: valor inicial
:param tax: valor da taxa
:return: valor inicial somada a taxa
"""
res = p + (p * tax/100)
return res | a72a016dd02a43871a8807522f9510ca980526e2 | 38,984 |
def greenfield_5g_sa(region, strategy, costs,
global_parameters, core_lut, country_parameters):
"""
Get the cost structure for a greenfield 5G SA asset.
Parameters
----------
region : dict
The region being assessed and all associated parameters.
strategy : dict
The strategy ... | 4b13bf8b568810f77f877d856f0eb07bcc1f6443 | 38,985 |
def predict_landmarks(param, bbox, dense=False):
""" Predicts the 68 face landmarks from a 3D face, scaling them by the face bounding box.
Parameters:
param (ndarray): Contains 3DMM params (12-pose, 40-shape, 10-expression).
bbox (array): The face bounding box.
dense (bool): Predic... | ec06f807a7462ba55738b207059eb7ab8d6110da | 38,986 |
def calculate_directions_single_track(
single_traj: pd.DataFrame, dt: int = 1, time_step: float = 10
):
"""Calculate distribution of angles for a particular dt.
dt in arbitrary units.
If an appropriate frame is missing than simply do not
calculate any angle.
inputs:
single track in a Da... | 4d02efc3b58e97a1fbd278188f2967e96a22d9fe | 38,990 |
def markdown(value):
"""
Run Markdown over a given value.
"""
return mark_safe(markdown_func(value)) | a463c05d0d08d9acc4785b0b68d9cc4ed868ea3f | 38,991 |
def get_min_freeboard(fjord):
"""
Get a required minimum median freeboard for filtering out icebergs
"""
minfree = {"JI": 15, "KB":5}
try:
return minfree.pop(fjord)
except KeyError:
print("The current fjord does not have a minimum freeboard median entry - using a default value!... | b80fec4224dcf8ce0d24a19ca28e88e66db52150 | 38,993 |
def login(request, template_name='registration/login.html', redirect_field_name=REDIRECT_FIELD_NAME,
authentication_form=AuthenticationForm, extra_context=None):
"""
Displays the login form and handles the login action.
"""
if request.method == "POST":
redirect_to = request.GET.get(red... | 3a61915c1052dcfc7eaec3fabcaf7d58c8250108 | 38,994 |
def view_assignments(id, course_id):
"""Single page view of all the assignments in a session."""
con = db.get_db()
cur = con.cursor()
cur.execute("""SELECT sessions.id, sessions.course_id, courses.course_id,
courses.teacherid, courses.name
AS class_name FROM sessions JO... | f8703878a8b01ca1331a413d81cf64a31167730b | 38,995 |
def name_indel_mutation(sbjct_seq, indel, sbjct_rf_indel, qry_rf_indel, codon_no, mut, start_offset):
"""
This function serves to name the individual mutations dependently on
the type of the mutation.
"""
# Get the subject and query sequences without gaps
sbjct_nucs = sbjct_rf_indel.replace("-"... | d1fdb61c196299f5890687b2bcc7af2fa87a44d2 | 38,998 |
import inspect
def clone_or_construct(estimator):
"""
Clone an estimator, or construct a default one from a class or function.
Parameters
----------
estimator : sklearn estimator instance, class, or a function returning same.
Returns
-------
estimator
"""
try:
return clone(estimator)
except TypeError:
... | 9c574aa149967c732f15a708d5646b6ed0902f86 | 38,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.