content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def parse_ff_port_status(data):
"""
Parse binary data (pb.FFPortStatus)
"""
msg = pb.FFPortStatus()
msg.ParseFromString(data)
return msg | 3174abd3db86100877fc948c87585d53faa3494f | 65,100 |
def normalize(point):
"""
Returns a new vector that has the same direction as vec,
but has a length of one.
"""
if(point[0] == 0. and point[1] == 0.):
return (0., 0.)
return (point[0] / length(point), point[1] / length(point)) | 882bcc73b87098e5e420b4ced9009709cccf0971 | 65,101 |
import functools
import logging
def RPCWrapper(f):
"""A decorator for converting exceptions to rpc status messages.
This decorator should be inserted below the rpcserver.Handler call to prevent
normal exceptions from reaching the RCP layer. These expected exceptions are
then encoded into the status message o... | 1ec82c93054272540f48e26d9c956be10644f0d5 | 65,102 |
from itertools import combinations
def Resilient(n):
"""
12 -> 1 5 7 11
-> 2 3 4 6 8 9 10
-> {2 4 6 8 10 12} + {3 6 9 12} - {6 12}
1 - {[1/2 + 1/3] - 1/6}
4/11 = 0.36..
>>> Resilient(12)
0.36363636363636365
"""
seq = mymath.factorLst(n)
seq = [k for k, v in seq]
r... | e10ca8ef9e8f12b7cfce5ae46a829c230d787b00 | 65,103 |
def get_http_exception_handler(app):
"""
# refer: https://stackoverflow.com/questions/29332056/global-error-handler-for-any-exception#44083675
Overrides the default http exception handler to return JSON.
"""
handle_http_exception = app.handle_http_exception
@wraps(handle_http_exception)
def ... | d981eec6cfc37e9f77778deb512a40c6bcc4bf3b | 65,104 |
import base64
import pyDes
def cdes(obj, deskey='12345678', desiv='abcdefgh', mode: int = 1,
to_file: t.Union[str, Path] = None,
desmode='CBC', despadmode='PAD_PKCS5'):
"""
des加密与解密(des mode: ECB or CBC)
使用示例:
# 1)针对字符
obj = b'这是一个示例'
deskey = b'asdfhjkl' # 8 by... | 9308b01baeae37401765116993938cdf3d42574e | 65,105 |
from SimPEG.PF import BaseMag
def readUBCmagneticsObservations(obs_file):
"""
Read and write UBC mag file format
INPUT:
:param fileName, path to the UBC obs mag file
OUTPUT:
:param survey
:param M, magnetization orentiaton (MI, MD)
"""
fid = open(obs_file,... | 72970991000b9974fcd2701f019fd86564ba597c | 65,106 |
def _decrypt(
keys: list[int], salt: int, encoded_secret: int, key_size: int = 128
) -> int:
"""Decryption with keys and salt"""
key = salt
for index, subkey in enumerate(keys):
key ^= subkey << index + 1
key %= 2**key_size
return _enc(key, key_size) ^ key ^ encoded_secret | e2afc8dfb87fdb529eebfad7c744e27ea50f5011 | 65,107 |
from datetime import datetime
import os
import logging
def timeStamp(arg):
""" Create a unique time stamp for each run and log configuration"""
ts = '{:%Y-%m-%d-%H-%M-%S}'.format(datetime.datetime.now())
logfolder = os.path.join(arg.outFolder, 'log')
if not os.path.exists(logfolder):
os.mkdir(... | b0d75028fed750e818fb5a97a5e81d9b839ed767 | 65,108 |
import time
def spectra2moments(Z_spec, paraminfo, **kwargs):
"""
This routine calculates the radar moments: reflectivity, mean Doppler velocity, spectrum width, skewness and
kurtosis from the level 0 spectrum files of the 94 GHz RPG cloud radar.
Args:
Z_spec (list of dicts): list containing ... | 0089aec30738daf13df6e7fc79e19c9500e8be42 | 65,109 |
def plot_mag_map(fignum, element, lons, lats, element_type, cmap='coolwarm', lon_0=0, date="", contours=False, proj='PlateCarree', min=False,max=False):
"""
makes a color contour map of geomagnetic field element
Parameters
____________
fignum : matplotlib figure number
element : field element a... | 0627b785e4ca629f87f35b61623bdede8d09a54e | 65,110 |
def scrub_response(response):
"""
Drop irrelevant headers.
"""
headers = response["headers"]
for header in [
"CF-Cache-Status",
"CF-RAY",
"Cache-Control",
"Connection",
"Date",
"Expect-CT",
"NEL",
"Report-To",
"Server",
... | 8f1a9f9499df1fbaf7147ccdda8c7854c4c638ec | 65,111 |
def _fix_recession_reserve_data(df: pd.DataFrame) -> pd.DataFrame:
"""
Fix Recession Reserve data in the Finance Department.
Note: Any class 900 spending in Finance should be labeled as
"Recession Reserve".
"""
finance = df.query("dept_code == '35'").copy()
finance_900 = finance["class_900"... | 0d66de23d70e2e560fe73db57830a2010359d8b1 | 65,112 |
def check_necessary_conds(val_inf, muls):
"""
The necessary conditions for a rational solution
to exist are as follows -
i) Every pole of a(x) must be either a simple pole
or a multiple pole of even order.
ii) The valuation of a(x) at infinity must be even
or be greater than or equal to 2.... | 58463ac2855d07eb36e1850cec3208d69d5a545c | 65,113 |
def crossval_predict(estimator, cv, X, y, groups=None, X_new=None, new_index=None,
test_avg=True, avg_type='auto', method='predict', scoring=None,
n_jobs=None, verbose=0, n_digits=4, compact=False,
train_score=False, target_func=None):
"""Get Out-of-Fol... | 0d2b6d93e1316166480a662e84a45f1df2204506 | 65,114 |
def polygon(points, **kwargs):
"""Creates a polygon with given list points.
Example:
p1 = point(x=0, y=0)
p2 = point(x=100, y=0)
p3 = point(x=0, y=100)
triangle = polygon([p1, p2, p3])
show(triangle)
"""
points_str = " ".join(f"{p.x},{p.y}" for p in points)
... | 8e4c2d7502993cd5decbb2c10bd2d34524eb924c | 65,115 |
def arrange_dlc_data(df):
"""
Restructure DLC dataframe
"""
scorer = df.keys()[0][0]
bodyparts = df[scorer].columns.levels[0]
data = {}
for bp in bodyparts:
data[bp] = df[scorer][bp]
return data | 26cfbe04ef2dc84d522e1e8c7f9db2a1ee3fe175 | 65,116 |
def get_rect_footprint(l_m=4.8, w_m=1.83):
"""
Get rectangular footprint of length (x, longitudinal direction) and width (y, lateral direction)
l_m : length (default 4.8)
w_m : width (default 1.83)
Return Values
=============
footprint_x : tuple of x coordinates of the footprint
footpr... | dd40304c404226543023c1f81bca5aac81e70eec | 65,117 |
import bz2
import struct
def ReadPrefix(input_filename):
"""
Read the prefix of a graph data structure from disk
@param input_filename: the filename where the graph data is stored
"""
assert (input_filename.endswith('.graph.bz2'))
data = bz2.decompress(open(input_filename, 'rb').read())
... | 1c585963bb2387ad9de2b4bf7e53f7b642bafcb8 | 65,118 |
import codecs
def detect_encoding(data):
"""Detect which UTF codec was used to encode the given bytes.
The latest JSON standard (:rfc:`8259`) suggests that only UTF-8 is
accepted. Older documents allowed 8, 16, or 32. 16 and 32 can be big
or little endian. Some editors or libraries may prepend a BOM.... | 69b7990fa4e7f9db5d84843162abb210b8792fd9 | 65,119 |
def _parse_source_file_list_blob_key(blob_key):
"""Parse the BLOB key for source file list.
Args:
blob_key: The BLOB key to parse. By contract, it should have the format:
`${SOURCE_FILE_LIST_BLOB_TAG}.${run_id}`
Returns:
- run ID
"""
return blob_key[blob_key.index(".") + 1 :] | a7f5c7ccee1404e17b90cb6cd58922ec162d33e3 | 65,120 |
def get_ast(token):
"""
Recursively unrolls token attributes into dictionaries (token.children
into lists).
Returns:
a dictionary of token's attributes.
"""
node = {}
# Python 3.6 uses [ordered dicts] [1].
# Put in 'type' entry first to make the final tree format somewhat
# ... | a5f4d32678f95e4af680239d5cf67ae947199d62 | 65,121 |
def rotaxis_nonfootflat(frame,ankle_JC):
"""Calculate the anatomically correct foot joint center and axis function for a non-flat foot.
Takes in a dictionary of xyz positions & marker names
and the ankle axis then calculates the anatomically
correct foot axis for a non-flat foot.
Markers used: RTO... | 7e804948c273be87808f462ec23e643ac32e3d3c | 65,122 |
def get_edges(da, dim, mode="edge", **kwargs):
"""Interpolate and extrapolate a data array at grid edges along the `dim` dimension(s)
.. note:: Coordinates are linearly extrapolated
Parameters
----------
da: xarray.DataArray
dim: str, tuple
Single or tuple of data-array or generic dime... | 054773391d2b6a02ca3db350c2958edf561869f4 | 65,123 |
from typing import List
def get_colnames(table: pd.DataFrame) -> List[str]:
"""
Get column names from a DataFrame.
"""
return list(table.columns) | 7f5f6428c854332c0ad151faa615f85cc57b3f21 | 65,124 |
def get_primary(
hostname,
refresh_key,
authorization_host,
org_id,
sddc_id,
verify_ssl=True,
cert=None,
):
"""
Retrieves the primary cluster in provided customer sddc UUID
Please refer the `VMC Get primary cluster documentation <https://developer.vmware.com/docs/vmc/latest/vmc/... | 9376db85d31aaa34e982c86b810035099fbe686e | 65,125 |
def guess_digikey_package(jo):
"""
Attempts to extract the mount type package ID from DigiKey data.
@param jo: JSON output from part search.
"""
package = None
package_id = None
mount_type = None
mount_type_id = None
for p in jo["Parameters"]:
if "ParameterId" in p.keys():
if p["ParameterId"] == 16: # ... | 9703ea9bcb3f361c9bce9ba733bdeb0be68f359e | 65,126 |
def progteam_desc(request):
"""backend.about.urls: /about/progteam-desc
Progteam team description. We assume there is only one description object
lives in the table, and returns the first and only one.
"""
obj = ProgteamDesc.objects.first()
return JsonResponse({
'desc': obj.desc,
}) | d263223246aec29861df18f4731c021b2be707db | 65,127 |
def invert(boolexpr):
"""invert
>>> print invert('0=0')
not (0=0)
>>> print invert(invert('0=0'))
0=0
"""
if isinstance(boolexpr, Not):
return boolexpr.element
else:
return Not(boolexpr) | 2d7cef12fc360f80485a3b032e190a98df4e4050 | 65,128 |
def prop_FC(csp, newVar=None):
"""
Do forward checking. That is check constraints with
only one uninstantiated variable. Remember to keep
track of all pruned variable,value pairs and return
"""
constraints = csp.get_cons_with_var(newVar) if newVar else csp.get_all_cons()
pruned = []
for... | 3956cf0ae03a03c0dbc3504ab2ed2a20b8343d90 | 65,129 |
def t_rel_len2048_dropout15_tiny():
"""Hparams for LM with relative attention, tiny transformer."""
# hparams = transformer.transformer_base()
hparams = transformer.transformer_tiny()
update_transformer_hparams_for_music(hparams)
update_truncate_length(hparams, 2048)
update_dropout(hparams, 0.15... | abaa85a14578f638f5e9be1faf5db952981fe404 | 65,130 |
def quick_sort(alist):
"""
快速排序,不稳定,空间O(logn)
时间:最好O(nlogn),平均O(nlogn),最坏O(n^2)
"""
length = len(alist)
if length <= 1:
# print(alist)
return alist
low = 0
high = length - 1
mid_value = alist[0]
while low < high:
while low < high and alist[high] >= mid_val... | b284759dc021bc252fc2e3c77345eaf2b8415317 | 65,131 |
def python_identifier(string):
""" pythonify a string for use as an identifier """
ident = (string.strip()
.replace('<', '')
.replace('>', '')
.replace('(', '')
.replace(')', '')
.replace(' ', '_')
.replace('+', '')
.repl... | 41a9deb89c42c8773acbcb2b657df68b5ff37f53 | 65,132 |
import os
def _fo_apextr(fpath, _):
"""Opens a regular file in append mode and truncates it,
raises an error if it doesn't exists"""
return os.open(fpath, os.O_WRONLY | os.O_APPEND | os.O_TRUNC) | 550b12996b5fdbaba6995b37d47daaceb27cb652 | 65,133 |
import requests
import logging
def group_nodes(group):
"""
:param group: group name
:return: list of nodes
"""
try:
api_url = get_apiurl()
nodes_group = requests.get(f'{api_url}/groups/{group}').json()
return nodes_group
except Exception as e:
logging.error('so... | 698036ce4d55f2590d63a7ba73a5e3b396c3bc9a | 65,134 |
def go_suffix_for_arch(arch: str, is_private: bool = False) -> str:
"""
Imagestreams and namespaces for the release controller indicate
a CPU architecture and whether the release is part of the private release controller.
using [-<arch>][-priv] as a suffix. This method calculates that suffix
based o... | e3da6de620d571e89c00c05883080805eea76f33 | 65,135 |
def get_gpu_config():
"""Share GPU memory between image preprocessing and inference."""
gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=_GPU_MEM_FRACTION)
return tf.ConfigProto(gpu_options=gpu_options) | 9310bd55863e3ecfb352af910c1e6fce1f9f81b4 | 65,136 |
def _construct_unicode(self, node):
"""Override the default string handling function to always return unicode
objects. Required for Python 2.7.
Thanks to:
http://stackoverflow.com/questions/2890146/how-to-force-pyyaml-to-load-strings-as-unicode-objects
"""
return self.construct_scalar(node) | eed380a154fe5cfd313c6f61a0648862f7d07a0f | 65,137 |
def chamnetv2_100(pretrained=False, num_classes=1000, in_chans=3, **kwargs):
""" ChamNet """
default_cfg = default_cfgs['chamnetv2_100']
model = _gen_chamnet_v2(1.0, num_classes=num_classes, in_chans=in_chans, **kwargs)
model.default_cfg = default_cfg
return model | aa0c32fb82e387d18da15b6fa5e331f298d24411 | 65,138 |
def update_real_pred_150d(real_pred_150d, buffer):
"""@params:
real_pred_150d: List[dict]
buffer: dict: {"date": , "value0": , "value1": }
Note: buffer has to be complete
"""
return real_pred_150d[1:] + [buffer] | 1ef0c648c5f921a9b66e23f41cfd7cf53cf16c0b | 65,139 |
def resnet50(num_classes=100):
""" return a ResNet 50 object
"""
return ResNet(BottleNeck, [3, 4, 6, 3],num_classes=num_classes) | b2a1defb4eb3f1054f3d069250fa481df99d6d65 | 65,140 |
import urllib
import os
def download(url, folder=".", overwrite=False, verbose=True):
"""
Function to download all files stored in a cloud directory
:param str url: url or list of urls for the file(s) to be downloaded ("https://...")
:param str folder: folder to where the directory is created and fil... | a686c686481b29595303380c9f48ce6d2cdf426e | 65,141 |
def get_recommendation_models(client: Client, id: int) -> dict:
"""Query for model info/data by recommendation ID."""
params = collect_parameters(request, optional=['type_id', 'include_data'], defaults={'include_data': False})
type_id = params.pop('type_id', None)
include_data = params.pop('include_data... | 71c6a22604279a56f2e9b81231ca47e7ce94e9e3 | 65,142 |
def get_lookup_coords(nrms=10, ninc=10, naz=36, ntheta=45):
"""
Return coordinate arrays corresponding to number of elements in each axis.
Return lookup axes in the following order with ranges:
rms: [0, 50] degrees
inc: [0, 90] degrees
az: [0, 360] degrees
theta: [0, 90] deg... | c37a0285424769476fa4acb7eb18e073e1e34a47 | 65,143 |
def get_datapath(app, dpid):
"""
Get datapath object by dpid.
Returns None on error.
"""
assert isinstance(dpid, (int, long))
return app.send_request(event.GetDatapathRequest(dpid=dpid))() | b096c02bbb2f212b5e7992478244eeb7a3f1da10 | 65,144 |
from datetime import datetime
def now():
"""Return a string representation of the current date/time.
Returns:
(str): current UTC time as a string
"""
return str(datetime.utcnow())[:19] + "Z" | 93906571ce2b74846e73f1ec5f773589ce70e4bb | 65,145 |
import pytz
from datetime import datetime
def current_year(time_zone: pytz.timezone = pytz.timezone("UTC")):
"""Return the current year"""
now = datetime.now(time_zone)
return now.strftime("%Y") | de116f0a95d8bb16de91e4b3c6582c9e583271d0 | 65,146 |
def execute(
metric_id: str = None,
) -> list:
"""Returns node peers information.
:param metric_id: Identifier of node metric.
:returns: Node metrics information.
"""
endpoint = f"{pycspr.CONNECTION.address_rest}/{_API_ENDPOINT}"
response = rest_client.get(endpoint).content.decode("ut... | 675986fdc2781f4de508cd7c527b8bc3a319e319 | 65,147 |
def _check_pair(minterm1, minterm2):
"""
Checks if a pair of minterms differs by only one bit. If yes, returns
index, else returns -1.
"""
index = -1
for x, (i, j) in enumerate(zip(minterm1, minterm2)):
if i != j:
if index == -1:
index = x
else:
... | 8016c3aba245973729b0807dd08e27fc39f512a8 | 65,148 |
from datetime import datetime
def get_date(date_long):
"""Convert longs to datetime."""
dt = None
try:
dt = datetime.datetime.fromtimestamp(date_long / 1e3)
except (KeyError, TypeError, ValueError):
try:
dt = datetime.datetime(1970, 1, 1) + datetime.timedelta(seconds=(date_... | c831bd79b9a94b66b516c2805f4ce07ad215033a | 65,149 |
import torch
def lossmin(z):
"""
nh: number of nodes in each hidden layer
nlh: number of hidden layers
mom: momentum
bs: mini-batch size
lr: learning rate
wd: weight-decay factor
"""
nh,nlh,mom,bs,lr,wd=z
print('nh,nlh,mom,bs,lr,wd: '+str(z))
bs=int(bs)
ltmin=[]
for... | e35747ae0eee84a5dd696db983434a2b4d18c680 | 65,150 |
def convert_pandas_to_dask(df, npartitions=4, partition_size="100MB",
*args, **kwargs):
"""
Convert a pandas dataframe to a distributed dask dataframe, enabling
lazy evaluation that can be prompted using .compute() or .persist()
"""
dask_df = dd.from_pandas(df, npartitio... | 13d980797930c301e4f366332a6b088e06154767 | 65,151 |
def calc_lnoverlaps(group_pars, star_pars, nstars):
"""Find the lnoverlaps given the parameters of a group
Parameters
----------
group_pars : [npars] array
Group parameters (internal encoding, 1/dX... no nstars)
star_pars : dict
stars: (nstars) high astropy table including columns a... | 6aaeecfb1712134a4f5761c9a047763d572517b7 | 65,152 |
def shift_vort_to_T(array):
"""! Shift the array from vorticity points to the corresponding tracer point."""
shifted = (array[...,0:-1] + array[...,1:])/2
shifted = (shifted[...,0:-1,:] + shifted[...,1:,:])/2
return shifted | 9408eb38cf667f2e48e31e7174e9e681bb27ed91 | 65,153 |
import io
def usgs_gold_call(*, resp, year, **_):
"""
Convert response for calling url to pandas dataframe, begin parsing
df into FBA format
:param url: string, url
:param resp: df, response from url call
:param args: dictionary, arguments specified when running
flowbyactivity.py ('yea... | a4d185c0f3e1fa3c0fbd6e3933c3b3997b369312 | 65,154 |
def total_sizeof(o, handlers={}, verbose=False):
"""
Returns the approximate memory footprint an object and its contents.
Automatically finds the contents of the following builtin containers and
their subclasses: tuple, list, deque, dict, set and frozenset.
To search other containers, add handlers... | cabf0e1f37da0725b0b4f7551f4443e873a18345 | 65,155 |
def pad(val: str) -> str:
"""Pad base64 values if need be: JWT calls to omit trailing padding."""
padlen = 4 - len(val) % 4
return val if padlen > 2 else (val + "=" * padlen) | 3ab1c91fde1522f15a766730f73e44c97dbeda1a | 65,156 |
def display_users():
"""
Function for displaying users
"""
return User.display_users() | 485a921e3d37b31b425deb242575b2b158bd59b2 | 65,157 |
def non_zero_row(arr):
"""
0. Empty row returns False.
>>> arr = array([])
>>> non_zero_row(arr)
False
1. Row with a zero returns False.
>>> arr = array([1, 4, 3, 0, 5, -1, -2])
>>> non_zero_row(arr)
False
2. Row... | 7052dac96bbf359800c43e0b750e999fba5ef2e0 | 65,158 |
def softnms2(dets, Nt=0.3, sigma=0.5, thresh=0.001, method=2):
"""
py_cpu_softnms
:param dets: boexs 坐标矩阵 format [y1, x1, y2, x2]
:param Nt: iou 交叠门限
:param sigma: 使用 gaussian 函数的方差
:param thresh: 最后的分数门限
:param method: 使用的方法
:return: 留下的 boxes 的 index
"""
# indexes... | e647a06c62b5935087096492fc87e70426f92596 | 65,159 |
def get_prop_layers(unsig_data: dict) -> list:
"""Group properties by layer and return list of layers"""
props = unsig_data.get("properties")
multipliers = props.get("multipliers")
colors = props.get("colors")
rotations = props.get("rotations")
distributions = props.get("distributions")
re... | d5d95eade48df026d0c7be0dd3d500a0b7b3bb07 | 65,160 |
def get_meshes_from_nodes(nodes, search_child_node=False, full_path=False, mesh=True, nurbs=False):
"""
Function that returns polygon meshes from given nodes
:param nodes: list(str)
:param search_child_node: bool
:param full_path: bool
:param mesh: bool
:param nurbs: bool
:return: list(s... | d15e43348c8cd3ead002469e3b94a5721a23235e | 65,161 |
def calc_elbo(sum_r2, n_jumps, r, n, A, B, n0, A0, B0,
exp_log_occs, exp_inv_phi, exp_log_phi,
identifiability_corr=True):
"""
Calculate the variational evidence lower bound for
a particular mixture model.
args
----
Most of the arguments are those produced internally
by the ... | 8e77c5d825a28d1721dbf3e47288e4209d8a1788 | 65,162 |
import argparse
def parse_args():
"""Parse input arguments."""
parser = argparse.ArgumentParser(description='Face Detection using Faster R-CNN')
parser.add_argument('--gpu', dest='gpu_id', help='GPU device id to use [0]',
default=0, type=int)
parser.add_argument('--cpu', dest='cpu_mode',
... | 0bf2bfcf18297f46922078574b1c723620c33091 | 65,163 |
import re
def ignore_stacktrace(crash_stacktrace):
"""Return whether the stacktrace needs to be ignored."""
# Filter crash based on search exclude pattern specified in job definition.
search_excludes = environment.get_value('SEARCH_EXCLUDES')
if search_excludes and re.search(search_excludes, crash_stacktrace)... | 9eeb59ecb0df01e6a628743df4e68d6675c252be | 65,164 |
def est_riskshrink_thresh(Wx, nv):
"""Estimate the RiskShrink hard thresholding level.
# Arguments:
Wx: np.ndarray. Wavelet transform of a signal.
opt: dict. Options structure used for forward wavelet transform.
# Returns:
gamma: float. The RiskShrink hard thresholding est... | 6769004c30a5e6c197814683d1910872d18b4675 | 65,165 |
def word_remove(text, wordlist):
"""
This function takes a list of text strings and a list of words. It returns the list of text strings
with the words appearing in the wordlist removed.
"""
# Create new emoty list for the cleaned text
clean_text = []
# Seperate ALL words from each other an... | 8dac46d54345efedf7bb117af3e4eb67704c0f85 | 65,166 |
def links_detail(request):
"""
Links list
"""
links = Link.objects.all()
links_json = serializers.serialize('json', links)
return render(
request,
'link_detail.html',
context={
'links': links_json
}) | 2bb3726f5b7cee784c1e5543d62dbb3a40820789 | 65,167 |
def secretary(request):
""" Renders the secretary page giving access to excuses and ChapterEvents """
print utils.verify_secretary(request.user)
if not utils.verify_secretary(request.user):
messages.error(request, "Secretary Access Denied!")
return HttpResponseRedirect(reverse('dashboard:hom... | bde9f4720de97c68cacf013526718693c2511961 | 65,168 |
def process_noise(pulses, noise_list, dims, t1=None, t2=None,
device_noise=False):
"""
Apply noise to the input list of pulses. It does not modify the input
pulse, but return a new one containing the noise.
Parameters
----------
pulses: list of :class:`qutip.qip.Pulse`
... | c5ffafd096fcbaeed59addf6e2388e5ce5cb48eb | 65,169 |
def ensure_user_access(model: models.Model, pk: int, user):
"""ensure user has access to specified model"""
if model is None:
return None
return get_object_or_404(model, pk=pk, user=user) | 49346035358ceb0a24b46eacc2a3ceb0b47421e1 | 65,170 |
def init_region(conf, region=None):
"""
Initialize the caching module.
"""
cache_region = make_region(function_key_generator=keygen_function)
kwargs = dict(
(k, conf[k]) for k in
("arguments", "expiration_time") if k in conf)
cache_region.configure(conf["backend"], **kwargs)
... | 51a9df1669c29dbff4d511faca22248167c72012 | 65,171 |
import calendar
from datetime import datetime
def get_month_start_end(dt):
"""
Returns the first and last day of the month for the specified date.
:param dt:
:return:
"""
month_range = calendar.monthrange(dt.year, dt.month)
month_start = pd.to_datetime(datetime(
dt.year, dt.month,... | 096211697617da95a025ef6fd1047872249717d5 | 65,172 |
import re
def get_found_exceptions(text, to_lower=False):
"""Extract exception and errors from logs"""
unique_exceptions = set()
found_exceptions = []
for word in split_words(text, to_lower=to_lower):
for key_word in ["error", "exception", "failure"]:
if re.search(r"[^\s]{3,}%s(\s|... | bdf6b460eec646f0d6ae320332338a5ae25ef32f | 65,173 |
def peak_intensity(P,radius):
"""For Gaussian beams, the peak intensity is 2x that of a flat top. I.e.:
P/((pi*radius**2)/2).
Power is in W, radius in m. Returns W/cm**2
"""
w = radius*100 #convert from m to cm
return P/((np.pi*w**2)/2) | d1bb8362c31115f52ac3e1f163308be3aa0905be | 65,174 |
def factRecursive(k):
"""factorial value from recursive algorithm"""
if k == 0:
return 1
else:
return k*factorial(k-1) | aa45a772a01e269fa042eee5c624486f71ed2bcd | 65,175 |
def expand_node(tree, path, plane):
"""Splits a `tree` at the node given by `path` using `plane`. Returns a copy of the original tree but with the
split node
:param tree: tree to split
:type tree: `bsp_tree.BSPTree`
:param path: path pointing to the node to split
:type path: tuple
:param pl... | 4cf03ba1aa6fccac5cdb794df4aa800f8a937adf | 65,176 |
def fs_write(obj, file_path):
"""
Convenience function to write an Object to a FilePath
Args:
obj (varies): The Object to write out
file_path (str): The Full path including filename to write to
Returns: The object that was written
"""
try:
with open(str(file_path), 'w')... | c94db2399283a26529bf4416f5b05a93fafb4e07 | 65,177 |
def find_max_locs(df):
"""Find iloc location of maximum values in pd.DataFrame"""
num_df = df.apply(pd.to_numeric, errors='coerce').values
row_max = num_df.max(axis=1)
ij_max = []
for i, i_max in enumerate(row_max):
if np.isnan(i_max): # ignore nan values
continue
for j... | 7fdca73a2a75566771ccc068000199a2896fe662 | 65,178 |
import re
def handle_line(fname, state, lines, linenum, line, app_state):
"""Parse, process and replace a single line in a list of lines."""
# skip comments
if re.match(r"^ *#", line):
return "n"
# skip function decorators that are inline, these are too hard
elif re.match(r"^ *@", line):... | 37f32398412196ad57719689ccdd4f697c824afd | 65,179 |
from datetime import datetime
def utcnow():
"""Quick UTC Now for default purposes"""
return datetime.utcnow().replace(tzinfo=bson.utc) | e950f5416de2f0d4688eeb00ffaf809fa4ce5f64 | 65,180 |
def mock_results(methods, swallow_not_found=False):
"""Mock API methods more easily.
:type methods: dict
:param methods: A dictionary containing one callable for each API method.
:type swallow_not_found: bool
:param swallow_not_found: Whether to return {'result': {}} on unmocked API
method... | 63653995518f725359c1805b8ba78d3830dcdf7a | 65,181 |
def check_string(arg, allow_none=False, message='Argument "%(string)s" of type %(actual)s is not a string', level=1):
"""
>>> check_string([1, 2, 3])
Traceback (most recent call last):
...
AssertionError: Argument "[1, 2, 3]" of type <class 'list'> is not a string
>>> check_string(3)
Tra... | bc3a2e2ed6d756c18867a92ca475c6f3dcf488a6 | 65,182 |
def complex_dot_pattern(kind_num=3, whole_repeat=2,
fg_color=np.array([1.0, 1.0, 1.0]),
bg_color=np.array([0.15, 0.15, 0.15])):
"""
dot pattern 作る。
Parameters
----------
kind_num : integer
作成するドットサイズの種類。
例えば、kind_num=3 ならば、1dot, 2dot, ... | 1b36b21dc7f63da3ec4e696feb1091fcdcac10a8 | 65,183 |
def get_task_category(request):
"""
@summary 获取所有模板分类列表
:param request:
:return:
"""
groups = []
for category in TASK_CATEGORY:
groups.append({
'value': category[0],
'name': category[1],
})
return JsonResponse({'result': True, 'data': groups}) | b37980a67d05a6f34df1d99ed2ca5658dd58454e | 65,184 |
def preprocess_once(set_x, set_y, gray_scale=True, dist_ratio=3.8/4.0):
"""
This method detects the face in the gray-scale (if user wants)
and detects a bounding box around the face using the keypoints.
It is done once for all the dataset, at the beginning of training.
Parameters:
-----------
... | 644a19efb1bff13d634e8f8283658bb0585aa3fe | 65,185 |
def get_raster_data(fp):
"""Get the digital number of the raster file.
Parameters
----------
fp: str
File path of the raster file.
Returns
-------
data : ndarray
Digital number of the raster file whose shape will be (rows, cols, bnads).
Examples
--------
>>> im... | 040d01453cbff02d1285b8b72f1e10bcc94976c9 | 65,186 |
def login(request):
"""
测试账户
mark
mark1234
:param request:
:return:
"""
if request.method == 'POST':
response = {'user': None, 'msg': None}
input_user = request.POST.get('user')
pwd = request.POST.get('pwd')
valid_code = request.POST.get('valid_code')
... | 889c7b691c712c77c7d655dae3ed05f1695e01cd | 65,187 |
def snake_dict_to_camel_dict(snake_dict, capitalize_first=False):
"""
Perhaps unexpectedly, snake_dict_to_camel_dict returns dromedaryCase
rather than true CamelCase. Passing capitalize_first=True returns
CamelCase. The default remains False as that was the original implementation
"""
def camel... | d20ce57f25a417286427ea08d58fd23e473b035e | 65,188 |
import typing
import pathlib
def from_python(
filepath: typing.Union[str, pathlib.Path, typing.IO[bytes]]
) -> typing.Union[Categorization, HierarchicalCategorization]:
"""Read Categorization or HierarchicalCategorization from a python cache file.
Note that this executes the python cache file. Only load ... | d746c19eddbba1062b996621f2b5693f8bfa3d9f | 65,189 |
def createTriangle(vertices, resolution = 1):
"""
Creates a staircase triangle with an array of small pillars.
coordinates given should form a right angled triangle with two sides parallel to grid axes.
Arguments:-
vertices (list): List of cartesian coordinates of vertices of triangle
resolution (int): Smalle... | 3ec56369d0d5c015862c36b21a5a0da7e7195b1e | 65,190 |
import json
def get_json(inp_dict):
"""Converts a given dictionary to prettified JSON string.
Parameters
----------
inp_dict: map
Input dictionary to be converted to JSON.
Returns
-------
Prettified JSON string
"""
return json.dumps(inp_dict, indent=4) | 9404064536a12595fe9b601363eee07b09a97bc8 | 65,191 |
def feature_vecs_DOC(train_pos, train_neg, test_pos, test_neg):
"""
Returns the feature vectors for all text in the train and test datasets.
"""
# Doc2Vec requires LabeledSentence objects as input.
# Turn the datasets from lists of words to lists of LabeledSentence objects.
labeled_train_pos=[]
... | 3f5161b157d2f8248f9b3ceea708cf5b13da0d1c | 65,192 |
def trimf(x, abc):
"""
Triangular membership function generator.
Parameters
----------
x : 1d array
Independent variable.
abc : 1d array, length 3
Three-element vector controlling shape of triangular function.
Requires a <= b <= c.
Returns
-------
y : 1d arr... | 33b0d215274885c51fd61d342953a9be39545da8 | 65,193 |
import torch
def mul_edge_softmax(graph, edge_val):
"""
Returns:
Softmax values of multi-dimension edge values. shape: [E, H]
"""
csr_edge_softmax = CONFIGS["csr_edge_softmax"]
if csr_edge_softmax is not None and edge_val.device.type != "cpu":
val = csr_edge_softmax(graph.row_indpt... | dfedc4895defd4d5525882d7b4502e1521c4437d | 65,194 |
from typing import Union
from typing import List
def get_online_retail_dataset(
number_of_documents: Union[None, int] = 1000, select_fields: list = []
) -> List:
"""
Download an example online retail dataset from UCI machine learning \n
Total Len: 541909 \n
Sample document:
>>> {'Country': '... | d330b434b2997f53f7ccf8effe90a2304586d00d | 65,195 |
def build_compound_annotation_df(
pset_dict: dict,
column_dict: dict={'compound_id': str, 'smiles': str, 'inchikey': str,
'pubchem': str, 'FDA': bool},
rename_dict: dict={'rownames': 'compound_id', 'cid': 'pubchem',
'FDA': 'fda_status'}
) -> pd.DataFrame:
"""
Build a table mapp... | 8779241f605a36bcd37b31022166c56c9d373f15 | 65,196 |
from datetime import datetime
def parse_matches(patient_id, match_objs):
"""Parse a list of matchmaker matches objects and returns
a readable list of matches to display in matchmaker matches view.
Args:
patient_id(str): id of a mme patient
match_objs(list): list of match objs returned ... | 2404de0e238269f1f4a1b6fe32143093494c1cb2 | 65,197 |
def message_url_path(course_key, access_point):
"""Determine the URL path for the message explaining why the user was blocked.
This is configured per-course. See `RestrictedCourse` in the `embargo.models`
module for more details.
Arguments:
course_key (CourseKey): The location of the course.
... | 7da091b791f55186f6cbffdd5bdc88b0bb852c44 | 65,198 |
def is_discard_class(outter_key, inner_key) -> None:
"""Prints discard class"""
values = {}
if outter_key == "discard-class":
values['discard_class'] = ', '.join(is_instance(inner_key.get('discard-class', {})))
return values | 9446ff5d448fd45d009365d90eaec2cabf382b4e | 65,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.