content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def contour(data2d, levels, container=None, **kwargs):
"""HIDE"""
if container is None:
_checkContainer()
container = current.container
current.object = kaplot.objects.Contour(container, data2d, levels, **kwargs)
return current.object | 11,200 |
def FilterSuboptimal(old_predictions,
new_predictions,
removed_predictions,
min_relative_coverage=0.0,
min_relative_score=0.0,
min_relative_pide=0.0):
"""remove suboptimal alignments.
"""
best_predicti... | 11,201 |
def send_message(msg_type, kwds):
"""Do some final preprocessing and send the message."""
if kwds["file"]:
get_body_from_file(kwds)
kwargs = trim_args(kwds)
send(msg_type, send_async=False, **kwargs) | 11,202 |
def process_pair(librispeech_md_file, librispeech_dir,
wham_md_file, wham_dir, n_src, pair):
"""Process a pair of sources to mix."""
utt_pair, noise = pair # Indices of the utterances and the noise
# Read the utterance files and get some metadata
source_info, source_list = read_ut... | 11,203 |
def getMultiDriverSDKs(driven, sourceDriverFilter=None):
"""get the sdk nodes that are added through a blendweighted node
Args:
driven (string): name of the driven node
sourceDriverFilter (list, pynode): Driver transforms to filter by,
if the connected SDK is not driven by this node it ... | 11,204 |
def resnet_model_fn(features, labels, mode, model_class,
resnet_size, weight_decay, learning_rate_fn, momentum,
data_format, version, loss_filter_fn=None, multi_gpu=False):
"""Shared functionality for different resnet model_fns.
Initializes the ResnetModel representing t... | 11,205 |
def dataframe_from_stomate(filepattern,largefile=True,multifile=True,
dgvmadj=False,spamask=None,
veget_npindex=np.s_[:],areaind=np.s_[:],
out_timestep='annual',version=1,
replace_nan=False):
"""
Paramete... | 11,206 |
def random_application(request, event, prev_application):
"""
Get a new random application for a particular event,
that hasn't been scored by the request user.
"""
from applications.models import Application # circular import
return Application.objects.filter(
form__event=event
).ex... | 11,207 |
def flutter_velocity(pressures, speeds_of_sound,
root_chord, tip_chord, semi_span, thickness,
shear_modulus=2.62e9):
"""Calculate flutter velocities for a given fin design.
Fin dimensions are given via the root_chord, tip_chord, semi_span and
thickness arguments. ... | 11,208 |
def replace_within(begin_re, end_re, source, data):
"""Replace text in source between two delimeters with specified data."""
pattern = r'(?s)(' + begin_re + r')(?:.*?)(' + end_re + r')'
source = re.sub(pattern, r'\1@@REPL@@\2' , source)
if '@@REPL@@' in source:
source = source.replace('@@REPL@@'... | 11,209 |
def mean(
a: Numeric, axis: Union[Int, None] = None, squeeze: bool = True
): # pragma: no cover
"""Take the mean of a tensor, possibly along an axis.
Args:
a (tensor): Tensor.
axis (int, optional): Optional axis.
squeeze (bool, optional): Squeeze the dimension after the reduction. ... | 11,210 |
def if_binary_exists(binary_name, cc):
"""
Returns the path of the requested binary if it exists and clang is being used, None if not
:param binary_name: Name of the binary
:param cc: Path to CC binary
:return: A path to binary if it exists and clang is being used, None if either condition is false
... | 11,211 |
def test_email_chart_report_schedule_with_csv(
csv_mock, email_mock, mock_open, mock_urlopen, create_report_email_chart_with_csv,
):
"""
ExecuteReport Command: Test chart email report schedule with CSV
"""
# setup csv mock
response = Mock()
mock_open.return_value = response
mock_urlopen.... | 11,212 |
def random_outputs_for_tier(rng, input_amount, scale, offset, max_count, allow_extra_change=False):
""" Make up to `max_number` random output values, chosen using exponential
distribution function. All parameters should be positive `int`s.
None can be returned for expected types of failures, which will oft... | 11,213 |
def test_slices_any(input, expected):
"""Test the "any()" function."""
assert input.any(lambda s: "abc" in s.raw) == expected | 11,214 |
def test_slow_to_event_model():
"""This doesn't use threads so it should be slower due to sleep"""
source = Stream(asynchronous=True)
t = FromEventStream("event", ("data", "det_image"), source, principle=True)
assert t.principle
a = t.map(slow_inc)
L = a.sink_to_list()
futures_L = a.sink_to... | 11,215 |
def create_connection(host, username, password):
""" create a database connection to the SQLite database
specified by db_file
:return: Connection object or None
"""
try:
conn = mysql.connect(host=host, # your host, usually db-guenette_neutrinos.rc.fas.harvard.edu
... | 11,216 |
def Dadjust(profile_ref, profile_sim, diffsys, ph, pp=True, deltaD=None, r=0.02):
"""
Adjust diffusion coefficient fitting function by comparing simulated
profile against reference profile. The purpose is to let simulated
diffusion profile be similar to reference profile.
Parameters
----------
... | 11,217 |
def setup_test():
"""setup test"""
def create_test_tables(db):
"""create test tables"""
db("""
create table if not exists person (
id integer PRIMARY KEY AUTOINCREMENT,
name varchar(100),
age integer,
kids integer,
... | 11,218 |
def validate_workload(args):
"""
Validate a workload description for JSSPP OSP.
:param args: The command line arguments passed to this command.
:return:
"""
logging.info('Processing file %s', args.file.name)
logging.info('Validating structural requirements')
schema = load_workload_schem... | 11,219 |
def compute_levenshtein_blocks(seq1, seq2, max_complexity=1e8):
"""Compute the Levenshtein blocks of insertion, deletion, replacement.
"""
# TODO: better method for dealing with long sequences?
l1, l2 = len(seq1), len(seq2)
if l1 * l2 > max_complexity:
return [("change", (0, l1), (0, l2))]
... | 11,220 |
def mapdict_values(function, dic):
"""
Apply a function to a dictionary values,
creating a new dictionary with the same keys
and new values created by applying the function
to the old ones.
:param function: A function that takes the dictionary value as argument
:param dic: A dictionary... | 11,221 |
async def callback(
request: Request,
code: str = None,
error: Optional[str] = Query(None),
db: AsyncSession = Depends(get_db),
):
"""
Complete the OAuth2 login flow
"""
client = get_discord_client()
with start_span(op="oauth"):
with start_span(op="oauth.authorization_token"... | 11,222 |
def set_serial_port(p):
"""Sets the name/path of the serial/tty port to use for a
key+sounder/loop interface
Parameters
----------
p : str
The 'COM' port for Windows, the 'tty' device path for Mac and Linux
"""
global serial_port
serial_port = noneOrValueFromStr(p)
app_conf... | 11,223 |
def align_centroids(config, ref):
"""Align centroids"""
diff_centroids = np.round(ref.mean(axis=0) - config.mean(axis=0))
# diff_centroids = np.round(diff_centroids).astype(int)
config = config + diff_centroids
return config | 11,224 |
def _make_headers_df(headers_response):
"""
Parses the headers portion of the watson response and creates the header dataframe.
:param headers_response: the ``row_header`` or ``column_header`` array as returned
from the Watson response,
:return: the completed header dataframe
"""
headers_d... | 11,225 |
def getMemInfo() -> CmdOutput:
"""Returns the RAM size in bytes.
Returns:
CmdOutput: The output of the command, as a `CmdOutput` instance containing
`stdout` and `stderr` as attributes.
"""
return runCommand(exe_args=ExeArgs("wmic", ["memorychip", "get", "capacity"])) | 11,226 |
def test_add(integration_test_config, service_instance):
"""
Test esxi add
"""
if integration_test_config["esxi_manage_test_instance"]:
ret = esxi.add(
integration_test_config["esxi_manage_test_instance"]["name"],
integration_test_config["esxi_manage_test_instance"]["user... | 11,227 |
def svn_swig_py_make_editor(*args):
"""svn_swig_py_make_editor(PyObject * py_editor, apr_pool_t pool)"""
return _delta.svn_swig_py_make_editor(*args) | 11,228 |
def register_confirm(request, activation_key):
"""finish confirmation and active the account
Args:
request: the http request
activation_key: the activation key
Returns:
Http redirect to successful page
"""
user_safety = get_object_or_404(UserSafety, activation_key=activation... | 11,229 |
def get_best_z_index(classifications):
"""Get optimal z index based on quality classifications
Ties are broken using the index nearest to the center of the sequence
of all possible z indexes
"""
nz = len(classifications)
best_score = np.min(classifications)
top_z = np.argwhere(np.array(clas... | 11,230 |
def _raise_404():
"""Raise 404 error"""
raise _exc.ObjectNotFoundError("Object not found") | 11,231 |
def mean_z_available():
"""docstring for mean_z_available"""
if glob.glob("annual_mean_z.nc"):
return True
return False | 11,232 |
def make_conversations_wb():
""" Create a report of all conversations from system messages """
print "Making Conversations XLSX Report"
wb = xl.Workbook()
ws = wb.active
header = ('id','sent','auto','short','topic','status','delivery_delta','response_delta',
'participant','nurse','... | 11,233 |
def wait_for_url(monitor_url, status_code=None, timeout=None):
"""Blocks until the URL is availale"""
if not timeout:
timeout = URL_TIMEOUT
end_time = time.time() + timeout
while (end_time - time.time()) > 0:
if is_url(monitor_url, status_code):
return True
time.sleep... | 11,234 |
def sources_from_arxiv(eprint):
"""
Download sources on arXiv for a given preprint.
:param eprint: The arXiv id (e.g. ``1401.2910`` or ``1401.2910v1``).
:returns: A ``TarFile`` object of the sources of the arXiv preprint.
"""
r = requests.get("http://arxiv.org/e-print/%s" % (eprint,))
file_... | 11,235 |
def nvidia_smi_gpu_memused(): # pragma: no cover
"""Returns the GPU memory used by the process.
(tested locally, cannot be tested on Travis CI bcs no GPU available)
Returns
-------
int
[MiB]
"""
# if theano.config.device=='cpu': return -2
try:
... | 11,236 |
def render():
"""
This method renders the HTML webside including the isOnline Status and the last 30 database entries.
:return:
"""
online = isonline()
return render_template("index.html", news=News.query.order_by(News.id.desc()).limit(30), online=online) | 11,237 |
def iterate(f: Callable[[_T], _T], x: _T = 0) -> Generator[_T, None, None]:
"""Iterate produces an infinite sequence of x, f(x), f(f(x)), ...
See Clojure's iterate.
"""
while True:
yield x
x = f(x) | 11,238 |
def test_serialization():
"""
testing that None values are removed when serializing
"""
bb_1 = t2.TBoundingBox(0.4, 0.3, 0.1, top=None) # type:ignore forcing some None/null values
bb_2 = t2.TBoundingBox(0.4, 0.3, 0.1, top=0.2)
p1 = t2.TPoint(x=0.1, y=0.1)
p2 = t2.TPoint(x=0.3, y=None) ... | 11,239 |
def write_programs_rst():
""" Genereate the RST.
"""
parts = []
# Create title
parts.append('Program classes')
parts.append('=' * len(parts[-1]))
parts.append(' ')
# Intro
parts.append('.. automodule:: ppci.programs')
parts.append('')
# Add TOC
toc_htm... | 11,240 |
def start_vaurien_httpserver(port):
"""Start a vaurien httpserver, controlling a fake proxy"""
config = get_config()
config.registry['proxy'] = FakeProxy()
server = WSGIServer(('localhost', int(port)), config.make_wsgi_app(),
log=None)
server.serve_forever() | 11,241 |
def _layout_graph_up(graph):
"""
Auto layout the nodes up stream.
"""
nodes = graph.selected_nodes() or graph.all_nodes()
graph.auto_layout_nodes(nodes=nodes, down_stream=False) | 11,242 |
async def execute_request(url):
"""Method to execute a http request asynchronously
"""
async with aiohttp.ClientSession() as session:
json = await fetch(session, url)
return json | 11,243 |
def game_over(remaining_words: List[str]) -> bool:
"""Return True iff remaining_words is empty.
>>> game_over(['dan', 'paul'])
False
>>> game_over([])
True
"""
return remaining_words == [] | 11,244 |
def read_manifest(instream):
"""Read manifest file into a dictionary
Parameters
----------
instream : readable file like object
"""
reader = csv.reader(instream, delimiter="\t")
header = None
metadata = {}
for row in reader:
if header is None:
header = row
... | 11,245 |
def get_backbone_from_model(model:Model, key_chain:list) -> nn.Cell:
"""Obtain the backbone from a wrapped mindspore Model using the
key chain provided.
Args:
model(Model): A Model instance with wrapped network and loss.
key_chain(list[str]): the keys in the right order according to
... | 11,246 |
def test_core_init():
"""Test initialization"""
LOGGER.info("Running core Init test...")
name = "Test Timeline"
tm = TimelineManager()
timeline = tm.create_timeline(name)
assert timeline.name == name | 11,247 |
def dv_upper_lower_bound(f):
"""
Donsker-Varadhan lower bound, but upper bounded by using log outside.
Similar to MINE, but did not involve the term for moving averages.
"""
first_term = f.diag().mean()
second_term = logmeanexp_nodiag(f)
return first_term - second_term | 11,248 |
def main():
"""
Populate the database
"""
# Projects
proj = get_or_create(Project, short_name='CMIP6',
full_name='Coupled Model Intercomparison Project Phase 6')
proj = get_or_create(Project, short_name='PRIMAVERA',
full_name='PRIMAVERA High Resolution Modelling Project')
# ... | 11,249 |
def create_training_files_for_document(
file_name,
key_field_names,
ground_truth_df,
ocr_data,
pass_number):
"""
Create the ocr.json file and the label file for a document
:param file_path: location of the document
:param file_name: just the document name.ext
... | 11,250 |
def incoming(ui, repo, source="default", **opts):
"""show new changesets found in source
Show new changesets found in the specified path/URL or the default
pull location. These are the changesets that would have been pulled
if a pull at the time you issued this command.
See pull for valid source f... | 11,251 |
def test_project_update_role_points():
"""Test that relation to project roles are created for stories not related to those roles.
The "relation" is just a mere `RolePoints` relation between the story and the role with
points set to the project's null-point.
"""
project = f.ProjectFactory.create()
... | 11,252 |
def timeout(limit=5):
"""
Timeout
This decorator is used to raise a timeout error when the
given function exceeds the given timeout limit.
"""
@decorator
def _timeout(func, *args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
duration = time.time() -... | 11,253 |
def main():
"""Export all the file options to pdf
"""
setup()
LINE_STYLE["ls"] = "--"
for options in FILE_OPTIONS:
export_grid_plot(**options) | 11,254 |
def puts(n, s):
"""连续打印输出n个s"""
for _ in range(n):
print(s, end='') | 11,255 |
def OIII4363_flux_limit(combine_flux_file: str, verbose: bool = False,
log: Logger = log_stdout()) -> \
Union[None, np.ndarray]:
"""
Determine 3-sigma limit on [OIII]4363 based on H-gamma measurements
:param combine_flux_file: Filename of ASCII file containing emission-line
... | 11,256 |
def convert_units_co2(ds,old_data,old_units,new_units):
"""
Purpose:
General purpose routine to convert from one set of CO2 concentration units
to another.
Conversions supported are:
umol/m2/s to gC/m2 (per time step)
gC/m2 (per time step) to umol/m2/s
mg/m3 to umol/mol
mg... | 11,257 |
def install_shutdown_handlers(function, override_sigint=True):
"""Install the given function as a signal handler for all common shutdown
signals (such as SIGINT, SIGTERM, etc). If override_sigint is ``False`` the
SIGINT handler won't be install if there is already a handler in place
(e.g. Pdb)
"""
... | 11,258 |
def query_urlhaus(session, provided_ioc, ioc_type):
""" """
uri_dir = ioc_type
if ioc_type in ["md5_hash", "sha256_hash"]:
uri_dir = "payload"
api = "https://urlhaus-api.abuse.ch/v1/{}/"
resp = session.post(api.format(uri_dir), timeout=180, data={ioc_type: provided_ioc})
ioc_dicts ... | 11,259 |
def arrow_to_json(data):
"""
Convert an arrow FileBuffer into a row-wise json format.
Go via pandas (To be revisited!!)
"""
reader = pa.ipc.open_file(data)
try:
frame = reader.read_pandas()
return frame.to_json(orient='records')
except:
raise DataStoreException("Unabl... | 11,260 |
def get_wmc_pathname(subject_id, bundle_string):
"""Generate a valid pathname of a WMC file given subject_id and
bundle_string (to resolve ACT vs noACT).
The WMC file contrains the bundle-labels for each streamline of the
corresponding tractogram.
"""
global datadir
ACT_string = 'ACT'
i... | 11,261 |
def _union_polygons(polygons, precision = 1e-4, max_points = 4000):
""" Performs the union of all polygons within a PolygonSet or list of
polygons.
Parameters
----------
polygons : PolygonSet or list of polygons
A set containing the input polygons.
precision : float
Desired prec... | 11,262 |
def check_aliens_bottom(ai_settings, screen, stats, sb, ship, aliens, bullets):
"""Verifica se algum alienígena alcançou a parte inferior da tela."""
screen_rect = screen.get_rect()
for alien in aliens.sprites():
if alien.rect.bottom >= screen_rect.bottom:
# Trata esse caso do mesmo modo... | 11,263 |
def parse_or_none(
field: str,
field_name: str,
none_value: str,
fn: Callable[[str, str], T],
) -> Optional[T]:
""" If the value is the same as the none value, will return None.
Otherwise will attempt to run the fn with field and field name as the
first and 2nd arguments.
"""
if fie... | 11,264 |
def get_lattice_parameter(elements, concentrations, default_title):
"""Finds the lattice parameters for the provided atomic species using Vagars law.
:arg elements: A dictionary of elements in the system and their concentrations.
:arg title: The default system title.
:arg concentrations: The concentrat... | 11,265 |
def tokenize(text):
"""
Tokenizes,normalizes and lemmatizes a given text.
Input:
text: text string
Output:
- array of lemmatized and normalized tokens
"""
def is_noun(tag):
return tag in ['NN', 'NNS', 'NNP', 'NNPS']
def is_verb(tag):
return tag in ['VB', 'VBD',... | 11,266 |
def bandpass_filterbank(bands, fs=1.0, order=8, output="sos"):
"""
Create a bank of Butterworth bandpass filters
Parameters
----------
bands: array_like, shape == (n, 2)
The list of bands ``[[flo1, fup1], [flo2, fup2], ...]``
fs: float, optional
Sampling frequency (default 1.)
... | 11,267 |
def get_couch_client(https: bool = False,
host: str = 'localhost',
port: int = 5984,
request_adapter: BaseHttpClient = HttpxCouchClient,
**kwargs) -> CouchClient:
"""
Initialize CouchClient
Parameters
----------
htt... | 11,268 |
def test_cases(
k=(5, 10),
batch_size=(3, 16),
num_queries=(3, 15, 16),
num_candidates=(1024, 128),
indices_dtype=(np.str, None),
use_exclusions=(True, False)) -> Iterator[Dict[str, Any]]:
"""Generates test cases.
Generates all possible combinations of input arguments as test cases.
Args... | 11,269 |
def compute_rmse(loss_mse):
"""
Computes the root mean squared error.
Args:
loss_mse: numeric value of the mean squared error loss
Returns:
loss_rmse: numeric value of the root mean squared error loss
"""
return np.sqrt(2 * loss_mse) | 11,270 |
def __detect_geometric_decomposition(pet: PETGraphX, root: CUNode) -> bool:
"""Detects geometric decomposition pattern
:param pet: PET graph
:param root: root node
:return: true if GD pattern was discovered
"""
for child in pet.subtree_of_type(root, NodeType.LOOP):
if not (child.reducti... | 11,271 |
def add_two_frags_together(fragList, atm_list, frag1_id, frag2_id):
"""Combine two fragments in fragList."""
new_id = min(frag1_id, frag2_id)
other_id = max(frag1_id, frag2_id)
new_fragList = fragList[:new_id] # copy up to the combined one
new_frag = { # combined frag
'ids': fragList[frag1... | 11,272 |
def load_dataset(
file: str,
out_dir: str = "/tmp",
download: bool = True,
url: str = None,
labels: str = "labels",
verbose: int = 2,
) -> Tuple[ndarray, ndarray, ndarray, ndarray]:
"""Load Dataset from storage or cloud h5 format
Args:
file (str): File name or file path if local... | 11,273 |
def concatenate(arrays, axis=0):
"""
Joins a sequence of tensors along an existing axis.
Args:
arrays: Union[Tensor, tuple(Tensor), list(Tensor)], a tensor or a list
of tensors to be concatenated.
axis (int, optional): The axis along which the tensors will be joined,
if... | 11,274 |
def build_hdf5(
save_file, video_file, label_file=None, pose_algo=None, batch_size=128, xpix=None,
ypix=None, label_likelihood_thresh=0.9, zscore=True):
"""Build Behavenet-style HDF5 file from video file and optional label file.
This function provides a basic example for how to convert raw vide... | 11,275 |
def six_nine():
"""
For all lockers, they should be open and shut an even number of times leaving all
lockers closed (except for a few). Since each locker will be toggled once for each
of its factors up to the square root, and again for each factor after the square
root, the number of toggles w... | 11,276 |
def get_answer():
"""
get answer
"""
# logger
M_LOG.info("get_answer")
# exist answer in dict ?
if "answer" in gdct_data:
# convert to JSON
l_json = json.dumps(gdct_data["answer"])
M_LOG.debug("Requested answer: %s", str(l_json))
# remove answer from dict
... | 11,277 |
def default_todo_data():
"""Словарь с данными пользователя поумолчанию"""
return {"title": "Молоко", "description": "Купить молоко в Ашане 200 литров", "created_datetime": "2041-08-12T00:00:00.000Z"} | 11,278 |
def generate_new_key(access_key, secret_key, user_to_rotate):
"""generates a new key pair and returns the access key and secret key"""
LOGGER.info("Begin generate new key")
iam_client = boto3.client('iam', aws_access_key_id=access_key, aws_secret_access_key=secret_key)
resp = iam_client.create_access_ke... | 11,279 |
def withCHID(fcn):
"""decorator to ensure that first argument to a function is a Channel
ID, ``chid``. The test performed is very weak, as any ctypes long or
python int will pass, but it is useful enough to catch most accidental
errors before they would cause a crash of the CA library.
"""
# It... | 11,280 |
def current_user_get():
"""ユーザー情報取得 user info get
Returns:
Response: HTTP Respose
"""
app_name = multi_lang.get_text("EP020-0001", "ユーザー情報:")
exec_stat = multi_lang.get_text("EP020-0017", "取得")
error_detail = ""
try:
globals.logger.debug('#' * 50)
globals.logger.de... | 11,281 |
def asin(a: Dual) -> Dual:
"""inverse of sine or arcsine of the dual number a, using math.asin(x)"""
if abs(a.value) >= 1:
raise ValueError('Arcsin cannot be evaluated at {}.'.format(a.value))
value = np.arcsin(a.value)
ders = dict()
for k,v in a.ders.items():
ders[k] = 1/(np.sqrt(1-a.value**2))*v
r... | 11,282 |
def hydrotopeQ(cover,hydrotopemap):
"""Get mean values of the cover map for the hydrotopes"""
grass.message(('Get mean hydrotope values for %s' %cover))
tbl = grass.read_command('r.univar', map=cover, zones=hydrotopemap,
flags='gt').split('\n')[:-1] #:-1 as last line hast line br... | 11,283 |
def write_genfile(h1, he4, n14, qb, acc_mult, numerical_params,
geemult, path, header, qnuc,
t_end, accdepth, accrate0, accmass,
lumdata=0, accrate1_str='', nuc_heat=False,
setup_test=False, substrate_off=True):
"""=============================... | 11,284 |
def convert_to_seconds(duration_str):
"""
return duration in seconds
"""
seconds = 0
if re.match(r"[0-9]+$", duration_str):
seconds = int(duration_str)
elif re.match(r"[0-9]+s$", duration_str):
seconds = int(duration_str[:-1])
elif re.match(r"[0-9]+m$", duration_str):
... | 11,285 |
def iter_extensions(extension):
""" Depth-first iterator over sub-extensions on `extension`.
"""
for _, ext in inspect.getmembers(extension, is_extension):
for item in iter_extensions(ext):
yield item
yield ext | 11,286 |
def get_chunk_n_rows(row_bytes: int,
working_memory: Num,
max_n_rows: int = None) -> int:
"""Calculates how many rows can be processed within working_memory
Parameters
----------
row_bytes : int
The expected number of bytes of memory that will be consum... | 11,287 |
def elasticsearch_ispartial_log(line):
"""
>>> line1 = ' [2018-04-03T00:22:38,048][DEBUG][o.e.c.u.c.QueueResizingEsThreadPoolExecutor] [search17/search]: there were [2000] tasks in [809ms], avg task time [28.4micros], EWMA task execution [790nanos], [35165.36 tasks/s], optimal queue is [35165], current capacit... | 11,288 |
def find_signal_analysis(prior, sparsity, sigma_data):
"""
Generates a signal using an analytic prior.
Works only with square and overcomplete full-rank priors.
"""
N, L = prior.shape
k = np.sum(np.random.random(L) > (1 - sparsity))
V = np.zeros(shape=(L, L - k))
while np.linalg.matrix_... | 11,289 |
def download_images(sorted_urls) -> List:
"""Download images and convert to list of PIL images
Once in an array of PIL.images we can easily convert this to a PDF.
:param sorted_urls: List of sorted URLs for split financial disclosure
:return: image_list
"""
async def main(urls):
image... | 11,290 |
def get_molecules(struct,
bonds_kw={"mult":1.20, "skin":0.0, "update":False},
ret="idx"):
"""
Returns the index of atoms belonging to each molecule in the Structure.
"""
bonds = struct.get_bonds(**bonds_kw)
## Build connectivity matrix
graph = np.z... | 11,291 |
def cdivs(a,b,c,d,e,f,al1,al2,al3,x11,x21,x22,x23,x31,x32,x33):
"""Finds the c divides conditions for the symmetry preserving HNFs.
Args:
a (int): a from the HNF.
b (int): b from the HNF.
c (int): c from the HNF.
d (int): d from the HNF.
e (int): e from the HNF.
... | 11,292 |
def numeric_field_list(model_class):
"""Return a list of field names for every numeric field in the class."""
def is_numeric(type):
return type in [BigIntegerField, DecimalField, FloatField, IntegerField,
PositiveIntegerField, PositiveSmallIntegerField,
S... | 11,293 |
def _get_lambda_source_code(lambda_fn, src):
"""Attempt to find the source code of the ``lambda_fn`` within the string ``src``."""
def gen_lambdas():
def gen():
yield src + "\n"
g = gen()
step = 0
tokens = []
for tok in tokenize.generate_tokens(getattr(g, "ne... | 11,294 |
def retrieve_keycloak_public_key_and_algorithm(token_kid: str, oidc_server_url: str) -> (str, str):
""" Retrieve the public key for the token from keycloak
:param token_kid: The user token
:param oidc_server_url: Url of the server to authorize with
:return: keycloak public key and algorithm
"""
... | 11,295 |
def read_conformations(filename, version="default", sep="\t", comment="#",
encoding=None, mode="rb", **kw_args):
"""
Extract conformation information.
Parameters
----------
filename: str
Relative or absolute path to file that contains the RegulonDB information.
Returns
---... | 11,296 |
def maskRipple(inRpl, outFile, mask):
"""maskRipple(inRpl, outFile, mask)
Sets the individual data items to zero based on the specified mask. If mask.getRGB(c,r)>0 /
then copy the contents at(c,r) of inRpl to outFile.rpl. Otherwise the contents of outFile /
is set to all zeros."""
outRpl = "%s.rpl... | 11,297 |
def GetCurrentScene() -> Scene:
"""
Returns current scene. Raises SpykeException
if current scene is not set.
"""
if not _currentScene:
raise SpykeException("No scene is set current.")
return _currentScene | 11,298 |
def Login():
"""Performs interactive login and caches authentication token.
Returns:
non-zero value on error.
"""
ConfirmUserAgreedToS()
parser = argparse.ArgumentParser()
parser.add_argument('--browser', action='store_true',
help=('Use browser to get goma OAuth2 token.'))
opti... | 11,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.