content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def schurs_complement(H, g, m, r, precond=False):
""" Shurs-complement """
assert H.shape[0] == (m + r)
# H = [Hmm, Hmr
# Hrm, Hrr];
Hmm = H[0:m, 0:m]
Hmr = H[0:m, m:]
Hrm = Hmr.T
Hrr = H[m:, m:]
# g = [gmm, grr]
gmm = g[1:]
grr = g[m:]
# Precondition Hmm
if precond:
Hmm = 0.5 * (H... | 08d14e0ab5a275230ca926ce20a5ba7bb7cc8c71 | 59,400 |
def markdown(text):
"""
Return match object if text is Markdown-formatted, otherwise None.
@param text: The message to check for Markdown formatting.
@type text: L{str}
"""
return mdre_code.match(text) or mdre_reply.match(text) or \
mdre_mono.search(text) or mdre_link.search(text) or \
... | a658a2932e952deebe140b9369e50a77fe056813 | 59,401 |
def neighborSelect(a, x, y):
"""
finds (local) minima in a 2d grid
:param a: 1d array of displacements from the source positions
:type a: numpy array with length numPix**2 in float
:returns: array of indices of local minima, values of those minima
:raises: AttributeError, KeyError
"""
... | 283066456ab5e9d93402ba24e1623e9d99ef17d2 | 59,402 |
import os
import re
def find_path_type(path):
"""Return a string indicating the type of thing, object or root, at path.
Looks only at "0=*" Namaste files to determing the path type. Will return
an error description if not an `object` or storage `root`.
"""
if not os.path.isdir(path):
retu... | f00b672658e2a3cc9bd8a489b6f94f803f2f9cb0 | 59,403 |
from typing import Optional
from typing import Set
def extract_active_themes(raw_themes: str, graph: dict) -> Optional[Set[str]]:
"""Safely parse and extract theme uuids."""
if raw_themes != constants.ALL_THEMES:
active_themes = set()
candidates = [
x.strip()
for x in c... | 5144361ebee59038c97afe5d44b76f7e73ed7a93 | 59,404 |
def hash_password(plain_text_password, salt=None):
"""Convert a plain text password to salted/hashed form."""
plain_text_password = plain_text_password.encode('utf-8')
if salt is None:
salt = bcrypt.gensalt()
hashed_password = bcrypt.hashpw(plain_text_password, salt)
return hashed_password | 1fdb95265f535eac868c8486052b0803e9c71146 | 59,405 |
import os
from pathlib import Path
def getFeatures():
"""
Getting features required for training and testing ML models
"""
# Getting Training Economic Indicators from World Bank (From EconIndicators.ipynb)
raw_data = getAllIndicatorsTraining(20, full_country_basket)
norm_data = relativeStrengt... | a667e9d3ef637366a68a2aadf30073a2b0ec4b9f | 59,406 |
def pairwise_cos_similarity_np(features):
"""Compute the pairwise cosine similarity.
Args:
features: The input embeddings.
:return: The pairwise cosine similarity matrix.
"""
feature_norm = np.sqrt(np.sum(features ** 2, axis=1, keepdims=True))
features = features / feature_norm
retu... | f894666722ea05bd22007f641d1d1f4916d879fb | 59,407 |
def disqus_show_comments(context, shortname=''):
"""
Return the HTML code to display DISQUS comments.
"""
shortname = getattr(settings, 'DISQUS_WEBSITE_SHORTNAME', shortname)
return {
'shortname': shortname,
'config': get_config(context),
} | 6ba672b887c5dfb395558943d2110a8ee195b1ac | 59,408 |
def sentence_length_feature(sentences):
""" List of values from 0 to 1 rating the length of the sentence in comparation with the longest one """
sentence_length_feature_values = []
max_length_sentence = len(sentences[0].original.split(' '))
# Find the longest sentence
for sentence in sentences[1:... | 89e705a6b12b30f29352d70977bd80db45a14b6a | 59,409 |
from pathlib import Path
import os
def _s3_upload(video: Path) -> str:
"""Upload `video` to S3 and return a public URL."""
# It's assumed that credentials are set via environment variables.
s3 = boto3.client("s3")
bucket = os.environ["S3_BUCKET"]
key = video.name
with video.open("rb") as f:
... | a53f59e05ae8d990b2e821923e4bd00bc01ffa09 | 59,410 |
def radar_coords_to_cart_track_relative(rng, rot, roll, drift, tilt, pitch):
"""
Calculate track-relative Cartesian coordinates from radar coordinates.
Parameters
----------
rng : array
Distances to the center of the radar gates (bins) in kilometers.
rot : array
Rotation angle o... | d44912656223c54e6f2e1c94e598b479ee6acfe8 | 59,411 |
def _get_agreement_violations(agreement_id, term=None):
"""
:rtype : list[wsag_model.Violation]
"""
violations_client = _get_violations_client()
violations, response = violations_client.getbyagreement(agreement_id, term)
return violations | f0b9e24731acda7233d6dd1dd80f5890641af897 | 59,412 |
import os
def system_terminal_emulator() -> str:
"""
Goal: find the default terminal emulator
"""
try:
return os.environ["TERM"]
except KeyError:
raise EnvironmentError("Cannot find default terminal") | 21f6914a656fb018289b9193b9ab378de2bcf7ff | 59,413 |
def processHis(pdb,his_tautomers,default_his=2,
valid_his={"CD1":0,"ND1":1,"NE2":2}):
"""
Take the calc_param.his_tautomers and generate proper input for the
generation of an input file. Either:
1) An input file is specified; read the file but return an error if it
is mang... | 55f2d030168b97b749e613ef11de1912dfaa3d8a | 59,414 |
def serialize(selector: Selector) -> str:
"""
# Equality:
>>> serialize({"a": "b", "c__neq": "d"})
'a=b,c!=d'
# Inclusion:
>>> serialize({"a__in": {"x", "y"}, "b__notin": ("z",)})
'a in (x,y),b notin (z)'
# Existence:
>>> serialize({"a": Is.PRESENT, "b": Is.ABSENT})
'a,!b'
... | 4fb83bf019ab3dff7761d86d1878542f9f463782 | 59,415 |
def __retrieve_linear_data(location=None):
""" Testdata from intervention cases. Univariable (here: at one location)"""
subsample = list(map(int, np.loadtxt('{}/intervention/subsample.csv'.format(testdata_path), delimiter=",")))
predictor = pd.read_csv('{}/intervention/reference.csv'.format(testdata_pa... | 93727086814c0882bccec5e54a50fc72ea018eeb | 59,416 |
import inspect
def get_argument_help_string(param: inspect.Parameter) -> str:
"""Get a default help string for a parameter
:param param: Parameter object
:type param: inspect.Parameter
:return: String describing the parameter based on the annotation and default value
:rtype: str
"""
help_... | 7381591ce45591bf1aef62280fc4b98e57969576 | 59,417 |
def _inTkStep(window):
"""Return true if the TkStep patches have been applied to Tk."""
global _in_tkstep
try:
return _in_tkstep
except NameError:
try:
f = Frame(window, text='is TkStep installed?')
except TclError:
_in_tkstep = 0
else:
... | 62c6fd896677ac447f4e31d006fb9ffdcf536744 | 59,418 |
def fill_marker_gap_rbt(itf, tgt_mkr_name, cl_mkr_names, log=False):
"""
Fill the gaps in the trajectory of a marker by rbt(rigid body transformation) using a group (cluster) markers.
Parameters
----------
itf : win32com.client.CDispatch
COM object of the C3Dserver.
tgt_mkr_name : str
... | dfd8ab7d8de20222d997b49c3295bf1081559733 | 59,419 |
def _dask_array_fft_has_norm_kwarg():
"""returns True if dask.array's fft supports the norm keyword argument
"""
return False | 93e111839aa5a175ebcdb995193c7774c45e25ec | 59,420 |
import six
def generic_signature(name_tensor_map):
"""Creates a generic signature of name to Tensor name.
Args:
name_tensor_map: Map from logical name to Tensor.
Returns:
A Signature message.
"""
signature = manifest_pb2.Signature()
for name, tensor in six.iteritems(name_tensor_map):
signatu... | bf652746645348efa0ebabec2bb59c3190edef9a | 59,421 |
def preprocess(input_sentence, en_vocab, en_word2index, output_sentence = None, de_vocab= None):
"""
:param input_sentence: test sample of input language
:param en_vocab: English language vocabulary
:param en_word2index: word-to-index dictionary
:param output_sentence: target language sentence for c... | f1798a38bebb80b4ecad3a237648b3f1f6f2e33b | 59,422 |
def dm_only() -> AC:
"""A :func:`.check` that indicates this command must only be used in a
DM context. Only private messages are allowed when
using the command.
This check raises a special exception, :exc:`.ApplicationPrivateMessageOnly`
that is inherited from :exc:`.ApplicationCheckFailure`.
... | 6d86ff53b4c73d5a753aef41f8bd9c14cc02abc6 | 59,423 |
from typing import Sequence
from typing import Union
from typing import AbstractSet
from typing import Optional
import warnings
def get_time_series(cube: xr.Dataset,
geometry: GeometryLike = None,
var_names: Sequence[str] = None,
start_date: Date = None,
... | b5418da1ae8198d200e1181042557e3abb9a8904 | 59,424 |
def communitiesandcrime(display=False):
""" Predict total number of non-violent crimes per 100K popuation.
This dataset is from the classic UCI Machine Learning repository:
https://archive.ics.uci.edu/ml/datasets/Communities+and+Crime+Unnormalized
"""
raw_data = pd.read_csv(
cache(github_d... | 144831dd5112417c18ce6f0cf587441680e340f5 | 59,425 |
def insert_discrete_time_mutations(ts, num_times=4, num_sites=10):
"""
Inserts mutations in the tree sequence at regularly-spaced num_sites
positions, at only a discrete set of times (the same for all trees): at
num_times times evenly spaced between 0 and the maximum time.
"""
tables = ts.tables... | c011525a7f810aec3eaacda3c016d82df5c3afbb | 59,426 |
def combine_shape(shape, comm=None):
"""
Return the shape of the global array resulting from stacking local arrays
along the first dimension.
"""
shape = tointtuple(shape)
comm = comm or MPI.COMM_WORLD
with timer_mpi:
shapes = comm.allgather(shape)
if any(len(s) != len(shapes[0]... | 2e45b29de7a48e0682a818b6cd2c3d8241993245 | 59,427 |
def make_zoomlock_radio():
"""Generates radio buttons for selecting whether or not
to save map zoom/position settings between filtering steps.
@return dash.dcc RadioItems object
"""
radio = dcc.RadioItems(
id='lock-zoom',
options=[{'label': i, 'value': i}
for i in ['... | 0dcf871e00a37f48c27cc8ce55af25f9b4e3192b | 59,428 |
def nested_select(d, v, default_selected=True):
"""
Nestedly select part of the object d with indicator v. If d is a dictionary, it will continue to select the child
values. The function will return the selected parts as well as the dropped parts.
:param d: The dictionary to be selected
:param v: Th... | 84aa16adfb324fef8452966087cbf446d57893d2 | 59,429 |
import time
def timestamp_2_datetime_str(timestamp):
"""将时间戳转为日期时间字符串"""
datetime_tuple = time.localtime(timestamp)
return time.strftime("%Y-%m-%d %H:%:%S", datetime_tuple) | 1b8b5e4338d1fa49729fa253b029c0521a7f5f55 | 59,430 |
def gen_point_cloud(n, scale=1.0):
"""
sample points on the unit square
"""
return np.random.uniform(low=-scale, high=scale, size=(n,2)) | 75248dc91efe73922c92d1b79077afa691a3e867 | 59,431 |
def refine_group_exit_event_msg(ctx: EventMsg) -> _GroupExitEventMsg:
"""群成员退出群聊事件"""
if not isinstance(ctx, EventMsg):
raise InvalidContextError("Expected `EventMsg`, but got `%s`" % ctx.__class__)
if ctx.EventName == EventNames.ON_EVENT_GROUP_EXIT:
return _GroupExitEventMsg(ctx)
return... | 466c0f504940ae90fd19b5ab1fb5174610cf918b | 59,432 |
import os
import pickle
def load_parameters():
"""Read the "bridge file to get back the arguments."""
parameter_file_name = os.path.abspath("gdb_driver.params")
parameter_file = open(parameter_file_name, "rb")
return pickle.loads(parameter_file.read()) | 521f2e71eee324ec048e79a300abdcfd26b73066 | 59,433 |
def xlconvertJSON(workBook, jsonObject={}, sheetName="all", testing=False):
""" sheetName used to specify a single sheet to convert
otherwise default is all sheets
workBook is excel workbook object returned by xlrd.open"""
# Function Variables
# none
if sheetName == "all":
sheetL... | 4e6b2a4c91654b1492c0a97eddf8f9077be3e66f | 59,434 |
def muller(
f: FuncionReal,
a: float,
b: float,
c: float,
max_iter: int = 100
) -> float:
"""Método de muller para encontrar la raíz de una función.
:parma f: función a la cual se le aplica el método.
:f type: Callable
:parma a: Valor inicial 1.
:a type: float
:parma b: Valo... | cb031b44a8144075d5229b3eb0d6248353bb50c9 | 59,435 |
from typing import List
def video_segment_is_repeat(
video_segment: VideoSegment, video_segments_used: List[VideoSegment]
) -> bool:
"""
Returns
-------
True if a video segment is a repeat of a video segment already used, False otherwise
"""
for used_segment in video_segments_used:
... | 71a603fe07a20a1842cadad3be30cac7c9ced9a5 | 59,436 |
def mle(x):
"""
Fit distribution parameters to sample by maximum likelihood estimation
Parameters
----------
x : array_like
sample
Notes
-----
MLE equation set is given in 'Statistical Distributions' by Forbes et.al. (2010) and referred
at [4]
"""
def mle_eq(p, z):... | 2e6ad0dc5751a4cd3e32a7ff7fc1570e5cdc7f94 | 59,437 |
def is_trans(reaction):
"""Check if a reaction is a transporter."""
return len(reaction.metabolites) == 1 | a0b9be30b4a88156e7a89cf48b8ecb76345e4cab | 59,438 |
def VSH_far(n, m, mode=vsh_mode.outgoing):
"""electric and magnetic vector spherical harmonic function in the far field
n: int order
m: int degree
mode: vsh_mode type of VSH (outgoing, incident)
returns (N(r,θ,ϕ,k) -> [2,...], M(r,θ,ϕ,k) -> [2,...])... | c99c679c7c011550034a123c15560847e42ae7d3 | 59,439 |
def compile_ir(llvm_ir):
"""
Compile the LLVM IR string with the given engine.
The compiled module object is returned.
"""
# Create a LLVM module object from the IR
mod = llvm.parse_assembly(llvm_ir)
mod.verify()
# Now add the module and make sure it is ready for execution
engine.add... | 5140091da854accb330a3c009ce4fc8220670485 | 59,440 |
from datetime import datetime
def average_plot_ondatetime(FEDs, groups, dependent, average_bins, average_error,
shade_dark, lights_on, lights_off,**kwargs):
"""
FED3 Viz: Create an average line plot for Grouped FED3 Files; averaging
is only done for periods where all devices we... | eace2f7181268e9d1a32dc4573ac0f8079f73bd2 | 59,441 |
import json
def verify_mail(data):
"""
data:{
'email': 'test@gmail.com',
'key':'KB7Y2OBU0iuhgulTbNCf8xmqxsGOAUC5'
}
enables user through key
"""
try:
response = frappe._dict({})
args = json.loads(data)
if frappe.db.exists("User", args.get("email")) and args.get("key"):
user = frappe.db.get_val... | 40a454f7d0b591cc180efa047ca7192edcb0cecc | 59,442 |
def Code(*content, **attrs):
"""
Wrapper for code tag
>>> Code().render()
'<code></code>'
"""
return KWElement('code', *content, **attrs) | e190070fe9c080b59b68bd9278e4bf07e35164b9 | 59,443 |
def format_tile(tile, tile_format, format_str='{x} {y} {z}'):
"""Convert tile to necessary format.
Parameters
----------
tile: pygeotile.tile.Tile
Tile object to be formatted.
tile_format: str
Desired tile format. `google`, `tms`, or `quad_tree`
format_str: str
String to... | e7ce2653f49f0c535bb3ea0a0c4bec3b48a74331 | 59,444 |
def percent(a, b):
"""
Given a and b, this function returns a% of b
"""
return (a/100)*b | d8adae353bb1b7aba6eb0149af065182bf752449 | 59,445 |
def create_plan(
plan: plan_schemas.PlanDTO,
db: orm.Session = Depends(get_db),
user: users_schemas.User = Depends(is_authenticated)):
"""Creates a new plan
Args:
plan (plan_schemas.PlanDTO): body of the request
db (orm.Session, optional): [description]. Defaults to Depends(get_db... | 59d650e5b131c3a00f98fb13b09ccacb8b9b91eb | 59,446 |
import math
def filter_none(mongo_dict):
"""Function to filter out Nones and NaN from a dict."""
for key in list(mongo_dict.keys()):
val = mongo_dict[key]
try:
if val is None or math.isnan(val):
mongo_dict.pop(key)
except Exception:
continue
... | 6853a7153f98466dc00d262bfaf4a63db1b0cd5c | 59,447 |
def get_audio_features(signal, sr, frame_length, frame_skip, feature_set='eGeMAPSv02', feature_level='LLDs'):
"""Extract ComParE16 features using the OpenSMILE toolkit
Parameters
----------
signal : ndarray
Array of signal data from audio file
sr : int
Sampling rate of audio
frame_length : float
... | 3a49107538166cd50a23689d42c45728c45e46a8 | 59,448 |
def axiom_generator_percept_sentence(t, tvec):
"""
Asserts that each percept proposition is True or False at time t.
t := time
tvec := a boolean (True/False) vector with entries corresponding to
percept propositions, in this order:
(<stench>,<breeze>,<glitter>,<bump>,<scream... | a1be06bb64043bd1a8b1250b7c8d3884ae5a0a2a | 59,449 |
def get_arguments_sqlite(sid, did, scid, func_id):
"""
get_arguments_sqlite(sid, did, scid, func_id)
This method is responsible to get the function arguments saved to sqlite
database during first debugging.
Parameters:
sid
- Server Id
did
- Database Id
scid
... | 9d432ffbea79235f3c32314e8a14194412caebd5 | 59,450 |
import configparser
def read_configfile():
"""Read the config file
:returns: The ConfigParser object
"""
c = configparser.ConfigParser()
c.read("config.conf")
return c | cdc8b63cca40af1cc516161746ffd016aeb4d65d | 59,451 |
from typing import List
from typing import Tuple
def parse_intensity_bounds(
image: Image, out_channels: List[int], out_zslices: List[int], out_timepoints: List[int],
min_intensities: Intensities, max_intensities: Intensities, allow_none: bool = False
) -> Tuple[List[int], List[int]]:
"""
Parse intens... | 80dfa51a9dee9b366e9edb0f778bcfec2a156212 | 59,452 |
def subresultants(f, g, *gens, **args):
"""Computes subresultant PRS sequence of `f` and `g`. """
gens = _analyze_gens(gens)
try:
F, G = _polify_basic(f, g, *gens, **args)
except CoercionFailed, (f, g):
raise GeneratorsNeeded("can't compute subresultants of %s and %s without generators"... | 1fdfdb59b15be6d8b2ae5a1af8f46a75e0ac2ae5 | 59,453 |
from ray.experimental.serve.handle import RayServeHandle
def get_handle(endpoint_name):
"""Retrieve RayServeHandle for service endpoint to invoke it from Python.
Args:
endpoint_name (str): A registered service endpoint.
Returns:
RayServeHandle
"""
assert endpoint_name in global_s... | 00542dac4e7900de42fd2e07bc9a9083b81ac9a5 | 59,454 |
from typing import Dict
def kg_path_discovering(
options: BuildDGOption,
qnodes: Dict[str, QNode],
kg_object_index: KGObjectIndex,
dg: nx.MultiDiGraph,
u: DGNode,
v: DGNode,
max_n_hop: int = 2,
bidirection: bool = True,
):
"""Find all paths between two nodes in the graph.
Para... | e0eb147dcb1f11837204d86317d71bb3ea6e62c0 | 59,455 |
def _normal_surface_single(obj, uv, normalize):
""" Evaluates the surface normal vector at the given (u, v) parameter pair.
The output returns a list containing the starting point (i.e. origin) of the vector and the vector itself.
:param obj: input surface
:type obj: Abstract.Surface
:param uv: (u... | 3402616985b04fc2161a21009901c56bc8de6d8d | 59,456 |
import csv
def read_us_counties_csv(file_name):
"""
"""
# read the data
with open(file_name) as csv_file:
# convert each row to a list of strings
csv_reader = csv.reader(csv_file, delimiter=',')
line_count = 0
counties_with_deaths = []
for row in csv_reader... | 2b203f200d7efbe26cbcaff17c150afde388f7e3 | 59,457 |
def measure(word1, word2, ALPHA=0.7):
"""
combine phonetic association value and semantic association value
@word1 -- the first word
@word2 -- the second word
@ALPHA -- contribution parameter of phonetic association value
@return -- a combined metric value to determine how associated these two ... | c97a452c6fdf343b1eedc53bffe5b367818e7bcc | 59,458 |
def ARGmetric_params_from_row(row):
"""
Create some ARGmetric params (see ARGmetrics.py) from a row
We hack the same polytomy seed as inference seed
This stupidly has to be defined at the top level, since it is
part of the function passed in to a multiprocessing Pool, and
hence needs to be 'pic... | eeb43b5fdf0b1fd8705d95ab7dd6a2d7f6422801 | 59,459 |
def encrypt_password(password, salt):
"""
Encrypts the password with the given salt using SHA-256. The salt must
be cryptographically random bytes.
:param password: the password that was provided by the user to try and
authenticate. This is the clear text version that we
... | 89c6f7e24c6f76e599095937f7f347f28e434fb7 | 59,460 |
def calc_ratio_significance(odd, even):
"""Calculate ratio significance between odd and even.
Parameters
----------
odd, even : float
Returns
-------
ratio : float
Ratio of odd to even.
sigma : float
Significance that the ratio is not 1.
"""
error_ratio = ((od... | bf34ed6b4e9c8c202ec152e4df802b92c498a2ae | 59,461 |
def rgba_to_rgb(image: np.ndarray) -> np.ndarray:
"""Convert an image from RGBA to RGB.
Args:
image (np.ndarray[B, 4, H, W]):
RGBA Image to be converted to RGB.
Returns:
rgb (np.ndarray[B, 3, H, W]):
RGB version of the image.
"""
return cv2.cvtColor(image, c... | ac5f62b61bc5316de98ed5bb9dc2b155abca0af4 | 59,462 |
def upload():
"""Process a file upload"""
if request.files["image"].filename != '':
image = request.files["image"]
# Write image to GCS
bucket = storage_client.bucket(BUCKET_NAME)
blob = bucket.blob(image.filename)
blob.upload_from_file(image)
# Create entry in Fi... | 3e20e0fc9f97061f7bd0f1f0b98002015881891d | 59,463 |
def UserDecode(user_str):
"""Returns User with string encoding of: <user_id>|<email>.
Note that the encoding must match that of UserEncode()
"""
try:
user_id, email = user_str.split('|', 1)
except ValueError: # only 1 part given
return users.User(email=user_str)
return users.User(email=email, _use... | e8f4e049a3cd87423f630f408ecba83428300db5 | 59,464 |
def interval_evalf(interval):
"""Proper implementation of evalf() on Interval.
Examples
========
>>> from sympy.core import Interval, Symbol
>>> from sympy.solvers.inequalities import interval_evalf
>>> interval_evalf(Interval(1, 3))
[1.0, 3.0]
>>> x = Symbol('x', real=True)
>>> ... | bcbdc5b044b6d1286cccde76eba3eba6fbef3e3b | 59,465 |
def _migrate_database(main_app):
"""
:param main_app:
:return:
"""
migrate = Migrate(main_app, db)
manager = Manager(main_app)
manager.add_command('db', MigrateCommand)
migrate.init_app(main_app, db)
return main_app | d9fb79d070d92e1b989c77b233b43b99fa94e575 | 59,466 |
import immcli
def usage(msg, parser, version):
"""
Emit usage from docstring at top of file.
msg - message string
parser - command line parser object returned by argparse.ArgumentParser()
"""
lines = list()
lines.append(msg)
lines.append('')
lines.append("Version: %s" % ve... | 72e2a08e6587dfe8ea280edba5fadd33e9257766 | 59,467 |
def parse3ds(file):
"""
returns a geometry
"""
logger.info('parsing %s' % file)
infile = File3Ds.open(file)
# only one object
OBJ = infile.main.children.editor.children.object
if type(OBJ) is list:
# there are several models, return a list
models = []
for obj in... | c8c412f85b51ba75cc9446f5786d22f7f527c091 | 59,468 |
def create_sparse_W_prior(shape, cutoff, slope):
"""Constructs sparsity parameters for W (alphaW) to learn pattern length
Follows equation (6) in the ISMIR paper referenced in this
module's docstring.
"""
# W.shape is (ndim, nseg, nwin)
prior = np.zeros(shape[-1])
prior[cutoff:] = prior[0] + slope * np.arange(... | 13648670905826fbda5364599eb8f4b034dfadb5 | 59,469 |
def argument(*name_or_flags, **kwargs):
"""Helper function to satisfy argparse.ArgumentParser.add_argument()'s
input argument syntax"""
return (list(name_or_flags), kwargs) | 24748b59202964d1bca05c5c24dac144e67d964e | 59,470 |
import scipy
def generate_signals(n_features=17, n_confounds=5, length=41,
same_variance=True, order="C"):
"""Generate test signals.
All returned signals have no trends at all (to machine precision).
Parameters
----------
n_features, n_confounds : int, optional
respe... | 658e406539682dc35aeb524113f45b2c6c794478 | 59,471 |
def kde_gauss(events_x, events_y, xout=None, yout=None):
""" Gaussian Kernel Density Estimation
Parameters
----------
events_x, events_y: 1D ndarray
The input points for kernel density estimation. Input
is flattened automatically.
xout, yout: ndarray
The coordinates at which ... | 147b8b4f857342d1db4f5ecb2f292255141b62c9 | 59,472 |
import io
def is_service_running(service_name):
"""
Checks if the named Service is running.
:param service_name:
:return:
"""
resultbuf = io.StringIO()
with settings(warn_only=True, stdout=resultbuf):
result = sudo('jps')
resultstring = resultbuf.getvalue()
resultbu... | 4de95200a6e8f3b1b6382156d5cfb50b23692d88 | 59,473 |
def _get_3rd_point(a, b):
"""To calculate the affine matrix, three pairs of points are required. This
function is used to get the 3rd point, given 2D points a & b.
The 3rd point is defined by rotating vector `a - b` by 90 degrees
anticlockwise, using b as the rotation center.
Args:
a (np.n... | 1619429fe77a490013d6a7a3d7a49f722f03831b | 59,474 |
import torch
def compute_rpn_class_loss(rpn_match, rpn_class_logits):
"""RPN anchor classifier loss.
rpn_match: [batch, anchors, 1]. Anchor match type. 1=positive,
-1=negative, 0=neutral anchor.
rpn_class_logits: [batch, anchors, 2]. RPN classifier logits for FG/BG.
"""
# Squeeze la... | 87246f4201fd253d22fee54ae20860d238f6f83f | 59,475 |
import argparse
def parse_args(args):
""" Parse the arguments.
"""
parser = argparse.ArgumentParser(description='Simple training script for training a RetinaNet network.')
subparsers = parser.add_subparsers(help='Arguments for specific dataset types.', dest='dataset_type')
subparsers.required ... | d5832e868dae688aa338fbbcf14fa442118b7fa3 | 59,476 |
import os
def find_best(exp_dir):
"""find best experiment."""
exp_dir = os.path.join(spiker.SPIKER_EXPS, exp_dir)
file_list = os.listdir(exp_dir)
file_clean_list = []
for item in file_list:
if ".hdf5" in item:
file_clean_list.append(item)
file_list = sorted(file_clean_list)... | 85c299a23701f9b759fb6ea3c85dd40b67638d34 | 59,477 |
def xception_internal(inputs, hparams):
"""Xception body."""
with tf.variable_scope("xception"):
cur = inputs
if cur.get_shape().as_list()[1] > 200:
# Large image, Xception entry flow
cur = xception_entry(cur, hparams.hidden_size)
else:
# Small image, conv
cur = common_layers.co... | 519bf118f76acfbab60222e64cee9236457e79d1 | 59,478 |
import re
def fetch_geneid(fn):
"""
fetch gene id from GTF records
gene_id "FBgn0267431"; gene_name "Myo81F"; gene_source "FlyBase"; gene_biotype "protein_coding";
"""
assert isinstance(fn, str)
ps = fn.split(';')
dn = {}
for i in fn.split(';'):
if len(i) < 8: # shortest field
... | c3ddb9c5c820799800131c6e11dc2ef91d4556c1 | 59,479 |
def model_users(user1, user2, text):
"""Input the two users and the tweet you are predicting.
Outputs good the goods.\n
```json
{
"winner": <prediction results>,
"user1": {
"name": <user 1 display name>,
"tweetAmount": <user 1 tweet amount>
},
"use... | 06d1175c8277f53c9f7a6326a12845bf932cbf67 | 59,480 |
def merge(G, nodes_to_merge):
"""
This method merges the list of nodes_to_merge in a 'Caterpillar' fashion, having the node of largest size closest
to the root. The method sorts the nodes in decreasing order of their sizes and constructs the tree recursively
:param G: A networkx graph
:param nodes_... | 0ed6dda1ec6618b5269c32bf1313131540b5edf6 | 59,481 |
def get_account_list_from_organization(config):
""" use config file parameters to query the account list from organization
"""
# Getting root session
if config.get('ProfileName'):
root_session = boto3.Session(profile_name=config.get('ProfileName'))
else:
root_session = boto3.Session(... | 72bb9d05c438360954cf8d79a8e25e85a7587c24 | 59,482 |
def password_set(username=None, password=None):
"""
Stores a password in a keychain for a particular environment and
configuration parameter pair.
"""
try:
keyring.set_password('superironic', username, password)
return True
except:
return False | 956d70bb133b99171a483e1e7e33140773f28b23 | 59,483 |
def fieldsMatch(f0, f1):
"""
Checks whether any entry in one list appears in a second list.
"""
for f in f0:
if f in f1: return True
return False | 172772fca613fe97e32bb6860c3bd217b643fe2d | 59,484 |
def _are_git_files_changed() -> bool:
"""
Check changes in the local repo.
If any file in the local repo changed, returns False.
"""
result = True
changed_files = hgit.get_modified_files()
if changed_files:
_LOG.warning("Modified files: %s.", changed_files)
result = False
... | d500c540b4bed08569e430a415fe8b1bdddc4dea | 59,485 |
def list_to_str(lst):
"""convert list/tuple to string split by space"""
result = " ".join(str(i) for i in lst)
return result | 1e6c59f834b98b1d49ca1c0919d2d976fd1de1de | 59,486 |
def _real_entropy(indi, gs):
"""
Calculates actual entropy for series of symbols
:param indi: unique identifier
:param gs: series of symbols
:return: an unique identifier and entropy value
"""
return indi, np.power(np.mean(matchfinder(gs)), -1) * np.log2(len(gs)) | 02884de548da4a2253a6042ac999ceba1e27b8d0 | 59,487 |
def match(pattern, term):
"""Try to match a pattern.
Args:
pattern : a term with optional free nominal variables
term : a term
Returns:
None if no match was found; otherwise a dict from NVARs to values.
"""
assert isinstance(pattern, Term), pattern
assert isinstance(term, Te... | aa2e954c23eff7e56a3f366b243054af74a270c7 | 59,488 |
def hillshade(az, ze, slope, aspect):
"""Computes hillshade"""
azimuth = radians(ee.Image.constant(az))
zenith = radians(ee.Image.constant(90).subtract(ee.Image.constant(ze)))
return azimuth \
.subtract(aspect).cos().multiply(slope.sin()).multiply(zenith.sin()) \
.add(zenith.cos().multi... | 800b22b357d09a738e7e6b44ff2f900d63b3cbb1 | 59,489 |
def element_damage(raw_element, sharpness, monster_ehitbox):
"""
Calculate elemental damage to a monster part with the given elemental
attack, the given sharpness, and the given monster elemental weakness.
Note that this is independent of the motion value of the attack.
"""
return floor(element_... | 22699ed3eb73a02277babb06a9b36be4cad26196 | 59,490 |
def extract_bias_diagonal(module, S, sum_batch=True):
"""Extract diagonal of ``(Jᵀ S) (Jᵀ S)ᵀ`` where ``J`` is the bias Jacobian.
Args:
module (torch.nn.Conv1d or torch.nn.Conv2d or torch.nn.Conv3d): Convolution
layer for which the diagonal is extracted w.r.t. the bias.
S (torch.Ten... | b2f8aaefa22d1ae915c59f80f98341059a4d1ad3 | 59,491 |
import os
def ensure_local(file_path: Text) -> Text:
"""Ensures that the given file path is made available locally."""
if not any([file_path.startswith(prefix) for prefix in _REMOTE_FS_PREFIX]):
return file_path
local_path = os.path.basename(file_path)
copy_file(file_path, local_path, True)
return loca... | 12868960386945a1d02f7969a0e61627d5f59ffb | 59,492 |
def _memmaps_to_file_paths(obj):
"""Convert memmap objects to corresponding file paths.
Acts recursively on arbitrary 'pytrees' of nested dict/tuple/lists with
memmap leaves.
Arg:
obj: NumPy memmap object or pytree of memmap objects to convert.
Returns:
File path string or pytree ... | 1b79a95075a6f0df2f35519c6a2f3839c03c265f | 59,493 |
from sklearn.tree import DecisionTreeClassifier
import time
def run_decision_tree(X_train, X_test, y_train, y_test, complexities):
"""
Run a decision tree classification over the dataset
The complexity here is ruled by the number of samples considered for every split
"""
dtc_list, dtc_pred, dtc_a... | bae1f64bbf531ab55bd02041e718cf40a1ba37e9 | 59,494 |
def squarespace(start, end, N, center=0):
""" Generate a grid from start to end with N points that is uniform after
taken square root.
:param float start: the start of the mesh, must be non-negative
:param float end: the end of the mesh, must be non-negative
:param int N: the total number of mesh p... | 2f2144e39b3fe8e14673f24744a63e8c0a1fb6fd | 59,495 |
import logging
def configureStreamLogger(loggername, level):
"""
Configure a stdout/stderr logger (logging.StreamHandler) with the given
``loggername`` and ``level``. If you are configuring logging for a
task, use :func:`configureStreamLoggerForTask`.
This is suitable for log-configuration for a ... | 86f2a8b1018191b4adada997c3d89b1eba9b85bb | 59,496 |
def load(source_file):
"""
Load a GeoJSON `dict` object from a ``source_file`` containing
GeoPackage (as a byte string).
:param source_file:
Open and readable file-like object.
:return:
A GeoJSON `dict` representing the geometry read from the file.
"""
return loads(source_f... | 87f8967028dc6290c9101e9f60bb5cb10663834e | 59,497 |
def is_template_update_possible(client):
"""Check if the project can be updated to a newer version of the project template."""
return _update_template(client, check_only=True) | 6f8ecb0bf6ca8a3d03a71a48435efba1f72ce4c6 | 59,498 |
from operator import sub
def ejectDrive(drivePath):
"""Eject drive"""
args = ['eject', drivePath]
try:
p = sub.Popen(args, stdout=sub.PIPE, stderr=sub.PIPE, shell=False)
output, errors = p.communicate()
exitStatus = p.returncode
except Exception:
# I don't even want... | 60f607428202f0ad1e489c8b629acbe3559df619 | 59,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.