content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import itertools
def generate_all_specs(
population_specs, treatment_specs, outcome_specs, model_specs, estimator_specs
):
"""
Generate all combinations of population, treatment,
outcome, causal model and estimator
"""
causal_graph = CausalGraph(treatment_specs, outcome_specs, model_specs)
... | 8180bd19d87b69d346edc4fd4442430e0c951873 | 23,771 |
def wsFoc(r,psi,L1,z0,alpha):
"""Return optimum focal surface height at radius r
as given by Chase & Van Speybroeck
"""
return .0625*(psi+1)*(r**2*L1/z0**2)/tan(alpha)**2 | 90076856f2fbef0cea3d662d1789d8392e9b19e0 | 23,772 |
def hough_lines(img, rho, theta, threshold, min_line_len, max_line_gap, draw_function=draw_lines, **kwargs):
"""
`img` should be the output of a Canny transform.
draw_function: Which which accepts image & line to render lanes. Default: draw_lines()
Returns an image with hough lines drawn.
"""
... | 586de545e1ad51c5495047f5d513b17ca2f7e369 | 23,773 |
from .models import Topography
def instances_to_topographies(topographies, surfaces, tags):
"""Returns a queryset of topographies, based on given instances
Given topographies, surfaces and tags are resolved and
all topographies are returned which are either
- explicitly given
- given indirectly b... | a5d94de84046a7218f92fb3f75320b7f78bde446 | 23,774 |
from typing import Optional
from typing import Union
from typing import Tuple
import math
def plot_histogram(
s: pd.Series,
*,
number_bins: Optional[int] = None,
bin_range: Union[Tuple[int, int], Tuple[int, int]] = None,
figsize: Optional[Tuple[int, int]] = (8, 6),
bin_width: Optional[int] = N... | 3f51a9abbf8dde862e18bb21b82f89c34dd6a536 | 23,775 |
def get_tracks():
"""
Returns all tracks on the minerva DB
"""
# connect to the database
db = connect_minerva_db()
# return all the tracks as a list
tracks = list(db.tracks.find())
return tracks | 65eedeaf32f448a6c32f8c77476dbea6b55a55b0 | 23,776 |
def mult_pair(pair):
"""Return the product of two, potentially large, numbers."""
return pair[0]*pair[1] | b616a0fb706eec5ca8723aa05c273ece079a2350 | 23,777 |
def get_only_filename(file_list):
"""
Get filename from file's path and return list that has only filename.
Input:
file_list: List. file's paths list.
Attribute:
file_name: String. "01.jpg"
file_name_without_ext: String. "01"
Return:
filename_list: Only filename lis... | 3b9b202a4320825eba9d32170f527c0de6e1bdc6 | 23,778 |
import _ctypes
def simple_calculate_hmac(sym_key, message,
digest_algo=DIGEST_ALGORITHM.SHA256):
"""Calculates a HMAC of given message using symmetric key."""
message_param = _get_char_param_nullify_if_zero(message)
mac = _ctypes.POINTER(_ctypes.c_char)()
mac_length = _ctypes... | 242f703d062366828f6980d90901a1b803fc426a | 23,779 |
def convert_from_sliced_object(data):
"""Fix the memory of multi-dimensional sliced object."""
if isinstance(data, np.ndarray) and isinstance(data.base, np.ndarray):
if not data.flags.c_contiguous:
_log_warning("Usage of np.ndarray subset (sliced data) is not recommended "
... | 88361b30137ce9ca646e49b1865d79b65f2693aa | 23,780 |
def stat_helper(path):
"""os.path.exists will return None for PermissionError (or any other
exception) , leading us to believe a file is not present when it, in fact,
is. This is behavior is awful, so stat_helper preserves any exception
other than FileNotFoundError.
"""
try:
return path... | 32e0863489ca19b55203d31b141d837189655cc2 | 23,782 |
from typing import Tuple
from datetime import datetime
def create_beacon_and_now_datetime(
game_name: str = "st",
waiting_time: float = 12.0,
platform_name: str = "pc"
) -> Tuple[beacons.BeaconBase, datetime.datetime]:
"""Return a BeaconBase instance with start time to current time."""
... | cff66d951e2b488a0c8ecd61f6ce5bdbeddae4f7 | 23,783 |
def validate(number, check_country=True):
"""Checks to see if the number provided is a valid IBAN. The country-
specific check can be disabled with the check_country argument."""
number = compact(number)
# ensure that checksum is valid
mod_97_10.validate(number[4:] + number[:4])
# look up the nu... | 55ee5423ff025ab9e4332d099e5c2d7b695163dd | 23,784 |
from numpy import array
def read_group(fname):
"""Reads the symmetry group in from the 'rot_perms' styled group
output by enum.x.
:arg fname: path to the file to read the group from.
"""
i=0
groupi = []
with open(fname) as f:
for line in f:
if i > 5:
if... | 7971781ae157c94329c638d4afd51a871b39498f | 23,785 |
def find_last_layer(model):
"""
Find last layer.
Args:
model (_type_): Model.
Returns:
_type_: Last layer.
"""
for layer in reversed(model.layers):
return layer | ff82705e4a74d7ad15b3d0e3e030c340b49052ca | 23,787 |
def seconds_to_time(sec):
"""
Convert seconds into time H:M:S
"""
return "%02d:%02d" % divmod(sec, 60) | 5fe639a9a6ade59258dfb2b3df8426c7e79d19fa | 23,788 |
def _compute_nfp_real(l, u, counts, sizes):
"""Computes the expected number of false positives caused by using
u to approximate set sizes in the interval [l, u], using the real
set size distribution.
Args:
l: the lower bound on set sizes.
u: the upper bound on set sizes.
counts:... | 40abf796ce116a92cd89c813a6343c917e413707 | 23,789 |
from typing import Union
from typing import Dict
from typing import List
from typing import Set
def is_equal_subset(
subset: Union[Dict, List, Set], superset: Union[Dict, List, Set]
) -> bool:
"""determine if all shared keys have equal value"""
if isinstance(subset, dict):
return all(
... | 4c2edbc73c350783d795ee0aa6e12180642e205c | 23,790 |
import copy
import itertools
def concatenate_over(argname):
"""Decorator to "vectorize" functions and concatenate outputs
"""
def _prepare_args(arg_map, value):
params = copy(arg_map)
params[argname] = value
return params
@decorator
def _concatenate_over(func, *args, **kwa... | 8bdf286566409bc6f8f97e06f5800e495afbc042 | 23,791 |
import ctypes
def logicalToPhysicalPoint(window, x, y):
"""Converts the logical coordinates of a point in a window to physical coordinates.
This should be used when points are received directly from a window that is not DPI aware.
@param window: The window handle.
@param x: The logical x coordinate.
@type x: int... | 81aeadcef460ffe1be64a69e64b562cea5dc94d6 | 23,793 |
import numba
def _node2vec_walks(Tdata, Tindptr, Tindices,
sampling_nodes,
walklen,
return_weight,
neighbor_weight):
"""
Create biased random walks from the transition matrix of a graph
in CSR sparse format. Bias method c... | 1a6ec24c62168f905a22809fc411036ab9f83b57 | 23,794 |
def schedule_prettify(schedule):
"""
Принимает на вход расписание в формате:
[День недели, Время, Тип занятия, Наименование занятия, Имя преподавателя, Место проведения]
Например: ['Чт', '13:00 – 14:30', 'ПЗ', 'Физическая культура', '', 'Кафедра']
"""
if not schedule:
return 'Сегодня зан... | 868469b99bb68ec407f6861e12d063bcd6b56236 | 23,795 |
def autodelegate(prefix=''):
"""
Returns a method that takes one argument and calls the method named prefix+arg,
calling `notfound()` if there isn't one. Example:
urls = ('/prefs/(.*)', 'prefs')
class prefs:
GET = autodelegate('GET_')
def GET_password(self): pass
... | 8ea5f555c3b102fc1830a4c616bd71f2dbf98ce4 | 23,796 |
def _compute_new_static_size(image, min_dimension, max_dimension):
"""Compute new static shape for resize_to_range method."""
image_shape = image.get_shape().as_list()
orig_height = image_shape[0]
orig_width = image_shape[1]
num_channels = image_shape[2]
# Scale factor such that maximal dimensi... | 1cc3a3465f69a8c799ccc529ba95efba0319fdf0 | 23,797 |
def deepupdate(original, update):
"""
Recursively update a dict.
Subdict's won't be overwritten but also updated.
"""
for key, value in original.items():
if key not in update:
update[key] = value
elif isinstance(value, dict):
deepupdate(value, update[key])
... | fc06aded11a674a0c5815a6f365ff790506af362 | 23,798 |
import itertools
def _omega_spectrum_odd_c(n, field):
"""Spectra of groups \Omega_{2n+1}(q) for odd q.
[1, Corollary 6]
"""
n = (n - 1) // 2
q = field.order
p = field.char
# (1)
t = (q ** n - 1) // 2
a1 = [t, t + 1]
# (2)
a2 = SemisimpleElements(q, n, min_length=2)
#... | 02512e8368ce1ef048ce0bfa8380ff7e102cdff7 | 23,799 |
def get_service(hass, config, discovery_info=None):
"""Get the ClickSend notification service."""
if not _authenticate(config):
_LOGGER.error("You are not authorized to access ClickSend")
return None
return ClicksendNotificationService(config) | 4b3dd52d7ebcb37012bc847288d0ea38c4ca91f6 | 23,800 |
from faker import Faker
def mock_features_dtypes(num_rows=100):
"""Internal function that returns the default full dataset.
:param num_rows: The number of observations in the final dataset. Defaults to 100.
:type num_rows: int, optional
:return: The dataset with all columns included.
:rtype tuple... | c9d9bef26d908b2e47d4bc2e013f0c29e328b2b3 | 23,801 |
def random_bitstring(n, p, failcount=0):
"""
Constructs a random bitstring of length n with parity p
Parameters
----------
n : int
Number of bits.
p : int
Parity.
failcount : int, optional
Internal use only.
Returns
-------
numpy.ndarray
"""
bi... | 07637061e50bc1fe853aeb2eef19505ee1a6b612 | 23,802 |
import json
def serializer(message):
"""serializes the message as JSON"""
return json.dumps(message).encode('utf-8') | 7e8d9ae8e31653aad594a81e9f45170a915e291d | 23,803 |
def send_mail(request, format=None):
"""
Send mail to admin
"""
# serialize request data
serializer = MailSerializer(data=request.data)
if serializer.is_valid():
try:
# create data for mail
subject = settings.EMAIL_SUBJECT.format(
first_name=reque... | 02ac2d0f7bf76fcea0afcff0a2a690cf72836e08 | 23,804 |
def correct_name(name):
"""
Ensures that the name of object used to create paths in file system do not
contain characters that would be handled erroneously (e.g. \ or / that
normally separate file directories).
Parameters
----------
name : str
Name of object (course, file, folder, e... | b1df7a503324009a15f4f08e7641722d15a826b7 | 23,805 |
def runner(parallel, config):
"""Run functions, provided by string name, on multiple cores on the current machine.
"""
def run_parallel(fn_name, items):
items = [x for x in items if x is not None]
if len(items) == 0:
return []
items = diagnostics.track_parallel(items, fn_... | 66ba2c5cd57d4d2738d9dd3d57ca9d5daca2ec8d | 23,806 |
def hsv_to_hsl(hsv):
"""
HSV to HSL.
https://en.wikipedia.org/wiki/HSL_and_HSV#Interconversion
"""
h, s, v = hsv
s /= 100.0
v /= 100.0
l = v * (1.0 - s / 2.0)
return [
HSV._constrain_hue(h),
0.0 if (l == 0.0 or l == 1.0) else ((v - l) / min(l, 1.0 - l)) * 100,
... | 4fee4508f6db770265ef46e928cfed6dee094892 | 23,807 |
from .._mesh import Mesh
def reindex_faces(mesh, ordering):
"""
Reorder the faces of the given mesh, returning a new mesh.
Args:
mesh (lacecore.Mesh): The mesh on which to operate.
ordering (np.arraylike): An array specifying the order in which
the original faces should be arr... | 254cf3a036fa92253b105f3acd93dfe26d33a61c | 23,809 |
import re
def check_exact_match(line, expected_line):
"""
Uses regular expressions to find an exact (not partial) match for 'expected_line' in 'line', i.e.
in the example below it matches 'foo' and succeeds:
line value: '66118.999958 - INFO - [MainThread] - ly_test_tools.o3de.asset_processor - foo... | d01eaa13c40d66999e870d3b287ac869f64ae314 | 23,810 |
def rounding_filters(filters, w_multiplier):
""" Calculate and round number of filters based on width multiplier. """
if not w_multiplier:
return filters
divisor = 8
filters *= w_multiplier
new_filters = max(divisor, int(filters + divisor / 2) // divisor * divisor)
if new_filters < 0.9 *... | eb2938732792564fd324602fd74be41e6f88b265 | 23,811 |
def process(request, service, identifier):
"""
View that displays a detailed description for a WPS process.
"""
wps = get_wps_service_engine(service)
wps_process = wps.describeprocess(identifier)
context = {'process': wps_process,
'service': service,
'is_link': abs... | 0d9f5a0cdf7c15470547ff82ff3534cf6f624960 | 23,812 |
def update(pipeline_id, name, description):
"""Submits a request to CARROT's pipelines update mapping"""
# Create parameter list
params = [
("name", name),
("description", description),
]
return request_handler.update("pipelines", pipeline_id, params) | e808fb0fc313e8a5e51bb448d0aca68e389bfc30 | 23,813 |
from re import S
def symmetric_poly(n, *gens, **args):
"""Generates symmetric polynomial of order `n`. """
gens = _analyze_gens(gens)
if n < 0 or n > len(gens) or not gens:
raise ValueError("can't generate symmetric polynomial of order %s for %s" % (n, gens))
elif not n:
poly = S.One
... | 51177adf8873628669c1b75267c3c65821920044 | 23,814 |
from typing import Any
def load(name: str, *args, **kwargs) -> Any:
"""
Loads the unit specified by `name`, initialized with the given arguments
and keyword arguments.
"""
entry = get_entry_point(name)
return entry.assemble(*args, **kwargs) | e924dcebf082443fb9f36cd81302cb62ac53775d | 23,815 |
from typing import List
def get_gate_names_2qubit() -> List[str]:
"""Return the list of valid gate names of 2-qubit gates."""
names = []
names.append("cx")
names.append("cz")
names.append("swap")
names.append("zx90")
names.append("zz90")
return names | d3d7f20263805a186d9142ec087039eb53076346 | 23,816 |
def positive_leading_quat(quat):
"""Returns the positive leading version of the quaternion.
This function supports inputs with or without leading batch dimensions.
Args:
quat: A quaternion [w, i, j, k].
Returns:
The equivalent quaternion [w, i, j, k] with w > 0.
"""
# Ensure quat is an np.array ... | e0dce2e8fce42a15abdeeccc4bbf63c9e9241cf1 | 23,817 |
def comp_avg_silh_metric(data_input, cluster_indices, silh_max_samples, silh_distance):
"""
Given a input data matrix and an array of cluster indices, returns the
average silhouette metric for that clustering result (computed across all clusters).
Parameters
----------
data_input : ndarray
... | 0d2cb42b1f0b354f4776c9c2064d23ed4b8f0b75 | 23,818 |
def prepare_url(base_url, path, url_params=None):
"""Prepare url from path and params"""
if url_params is None:
url_params = {}
url = '{0}{1}'.format(base_url, path)
if not url.endswith('/'):
url += '/'
url_params_str = urlencode(url_params)
if url_params_str:
url += '?'... | 0a447d9f340a4ea9c99b98ca1e6f778f907d8a3d | 23,819 |
def extract_at_interval(da: xr.DataArray, interval) -> xr.DataArray:
"""Reduce size of an Error Grid by selecting data at a fixed interval along
both the number of high- and low-fidelity samples.
"""
return da.where(
da.n_high.isin(da.n_high[slice(None, None, interval)]) *
da.n_low.isin(... | cad3dce9850edbad9decadbc37e0372001b8ecc9 | 23,820 |
def compute_log_zT_var(log_rho_var, log_seebeck_sqr_var, log_kappa_var):
"""Compute the variance of the logarithmic thermoelectric figure
of merit zT.
"""
return log_rho_var + log_seebeck_sqr_var + log_kappa_var | 3528181796aeafb3df5eac09b06852afe028cb13 | 23,821 |
def main(global_config, **settings):
""" Very basic pyramid app """
config = Configurator(settings=settings)
config.include('pyramid_swagger')
config.add_route(
'sample_nonstring',
'/sample/nonstring/{int_arg}/{float_arg}/{boolean_arg}',
)
config.add_route('standard', '/sample/... | 677187e63b6b885f5dc27850039a54b7510ed9cf | 23,822 |
def get_name():
"""MUST HAVE FUNCTION! Returns plugin name."""
return "ASP.NET MVC" | 08a8b413ad1c86c270c79da245f0718aa22883a8 | 23,823 |
def load_CIFAR(model_mode):
"""
Loads CIFAR-100 or CIFAR-10 dataset and maps it to Target Model and Shadow Model.
:param model_mode: one of "TargetModel" and "ShadowModel".
:param num_classes: one of 10 and 100 and the default value is 100
:return: Tuple of numpy arrays:'(x_train, y_train), (x_test,... | d47d5546c26b1a776b84acb407782837170da43d | 23,825 |
def _jbackslashreplace_error_handler(err):
"""
Encoding error handler which replaces invalid characters with Java-compliant Unicode escape sequences.
:param err: An `:exc:UnicodeEncodeError` instance.
:return: See https://docs.python.org/2/library/codecs.html?highlight=codecs#codecs.register_error
... | 2bec9e9563a7f4a4d206f630f7d8372fa7c56d89 | 23,826 |
from pathlib import Path
def run_on_host(con_info, command):
"""
Runs a command on a target pool of host defined in a hosts.yaml file.
"""
# Paramiko client configuration
paramiko.util.log_to_file(base + "prt_paramiko.log")
UseGSSAPI = (paramiko.GSS_AUTH_AVAILABLE)
DoGSSAPIKeyExchange = (p... | e3747daa1ea6e68ae4900bd596458bf756017c69 | 23,828 |
import colorsys
import hashlib
def uniqueColor(string):
"""
Returns a color from the string.
Same strings will return same colors, different strings will return different colors ('randomly' different)
Internal: string =md5(x)=> hex =x/maxhex=> float [0-1] =hsv_to_rgb(x,1,1)=> rgb =rgb_to_int=> int
... | 0c895612c3bf2dd5f594a15daf6f2aa5d778eeb0 | 23,829 |
def _quoteattr(data, entities={}):
""" Escape and quote an attribute value.
Escape &, <, and > in a string of data, then quote it for use as
an attribute value. The \" character will be escaped as well, if
necessary.
You can escape other strings of data by passing a dictionary as
... | 1f03a09e19d349458ec48b6041159e48ef93d97e | 23,830 |
import http
import urllib
def external_login_confirm_email_get(auth, uid, token):
"""
View for email confirmation links when user first login through external identity provider.
HTTP Method: GET
When users click the confirm link, they are expected not to be logged in. If not, they will be logged out ... | 18a92d289e63224b245e4e958efd6d5924495ce1 | 23,831 |
def date_since_epoch(date, unit='day'):
""" Get the date for the specified date in unit
:param date: the date in the specified unit
:type date: int
:param unit: one of 'year', 'month' 'week', 'day', 'hour', 'minute',
or 'second'
:return: the corresponding date
:rtype: ee.Date
"""
... | f787170869ba081a2d321d0198d27948dc44ffa6 | 23,832 |
def eval_assoc(param_list, meta):
"""
Evaluate the assoication score between a given text and
a list of categories or statements.
Param 1 - string, the text in question
Param 2 - list of strings, the list of categories to associate Param 1 to
"""
data = {
'op': 'eval_assoc',
... | f49d5080d0b5f6a526be11b487bbbf17782d7197 | 23,833 |
def quiver3d(*args, **kwargs):
"""Wraps `mayavi.mlab.quiver3d`
Args:
*args: passed to `mayavi.mlab.quiver3d`
**kwargs: Other Arguments are popped, then kwargs is passed to
`mayavi.mlab.quiver3d`
Keyword Arguments:
cmap (str, None, False): see :py:func:`apply_cmap`
... | 8cfd494f0b801490372d94f7ab842c0b5cd19099 | 23,834 |
def get_instance_types(self):
"""
Documentation:
---
Description:
Generate SSH pub
"""
instance_types = sorted([instance_type["InstanceType"] for instance_type in self.ec2_client.describe_instance_types()["InstanceTypes"]])
return instance_types | 583311de8b2f23a967e40c8be5d140f6ab28244c | 23,835 |
def ret_digraph_points(sed, digraph):
"""Finds the digraph points of the subject extracted data.
Parameters
----------
`sed` (object) "_subject","_track_code", "data": [{"digraph","points"}]
Returns
---------
(list) The points of the particular digraph found
"""
ret = [d['points'] fo... | 853dac3afdb542dbc2878340c8d75b8b4544c531 | 23,836 |
def _sizeof_fmt(num):
"""Format byte size to human-readable format.
https://web.archive.org/web/20111010015624/http://blogmag.net/blog/read/38/Print_human_readable_file_size
Args:
num (float): Number of bytes
"""
for x in ["bytes", "KB", "MB", "GB", "TB", "PB"]:
if num < 1024.0:
... | 97c700954248a455592b3da9b274bfda69a7370f | 23,837 |
from .. import sim
from typing import Dict
def gatherData(gatherLFP = True):
"""
Function for/to <short description of `netpyne.sim.gather.gatherData`>
Parameters
----------
gatherLFP : bool
<Short description of gatherLFP>
**Default:** ``True``
**Options:** ``<option>`` <... | a40b61088aaedbb8f866014f933671b2264a2031 | 23,838 |
def stations_by_distance(stations, p):
"""For a list of stations (MonitoringStation object) and
coordinate p (latitude, longitude), returns list of tuples
(station, distance) sorted by the distance from the given
coordinate p"""
# Create the list of (stations, distance) tuples
station_dist = []... | 098e692c2ec18b7c15cebf84043eaca768566075 | 23,839 |
from typing import TextIO
from typing import Optional
from typing import Dict
import csv
def process(fh: TextIO, headers: Optional[Dict[str, str]],
writer: csv.DictWriter, args: Args) -> int:
"""
Process the file into Mongo (client)
First 5 columns are: STREAM, DATE, STATION, REP, #GRIDS
... | 40a68091d65e1f9a56ca150703aaaa207ef438a2 | 23,840 |
def dipole_moment_programs():
""" Constructs a list of program modules implementing
static dipole moment output readers.
"""
return pm.program_modules_with_function(pm.Job.DIP_MOM) | a225997a445451411819ebfb8c7bf14629ee3742 | 23,841 |
def kappa(a, b, c, d):
""" GO term 2
| yes | no |
-------------------------------
GO | yes | a | b |
term1 | no | c | d |
kapa(GO_1, GO_2) = 1 - (1 - po) / (1 - pe)
po = (a + d) / (a + b + c + d)
marginal_a = ( (a + b) * ( a + c )) / (a + b + ... | 5884a6745f6a93b044eabb1bfe38834cb59366d4 | 23,842 |
import functools
import torch
def test_CreativeProject_integration_ask_tell_ask_works(covars, model_type, train_X, train_Y,
covars_proposed_iter, covars_sampled_iter,
response_sampled_it... | 98d665e85b19acf956026848614d9b49e204afb8 | 23,843 |
def ferret_init(id):
"""
Initialization for the stats_chisquare Ferret PyEF
"""
axes_values = [ pyferret.AXIS_DOES_NOT_EXIST ] * pyferret.MAX_FERRET_NDIM
axes_values[0] = pyferret.AXIS_CUSTOM
false_influences = [ False ] * pyferret.MAX_FERRET_NDIM
retdict = { "numargs": 3,
"d... | 5231fec470d8c968334d6f72766cc1d0ad9ae61c | 23,844 |
def has(key):
"""Checks if the current context contains the given key."""
return not not (key in Context.currentContext.values) | 0c6c46812e97c9d38d101dcc06346b329a3cd81a | 23,845 |
def VGG_16(weights_path=None):
"""
Creates a convolutional keras neural network, training it with data from ct scans from both datasets.
Using the VGG-16 architecture.
----
Returns the model
"""
X_train, Y_train = loadfromh5(1, 2, 19)
X_train1, Y_train1 = loadfromh5(2, 2, 19)
X_tr... | 640aa7480afac0c8c4b71f3045f702888672172f | 23,846 |
from scipy import optimize
def inv_fap_davies(p, fmax, t, y, dy, normalization='standard'):
"""Inverse of the davies upper-bound"""
args = (fmax, t, y, dy, normalization)
z0 = inv_fap_naive(p, *args)
func = lambda z, *args: fap_davies(z, *args) - p
res = optimize.root(func, z0, args=args, method='... | 9b6f8a82ca25235785d5fe83a5c671130ddd509b | 23,847 |
def public(request):
"""browse public repos. Login not required"""
username = request.user.get_username()
public_repos = DataHubManager.list_public_repos()
# This should really go through the api... like everything else
# in this file.
public_repos = serializers.serialize('json', public_repos)
... | 0d44053c6db872032b65b4786c5771dbecad946a | 23,848 |
def get_boundaries_old(im,su=5,sl=5,valley=5,cutoff_max=1.,plt_val=False):
"""Bintu et al 2018 candidate boundary calling"""
im_=np.array(im)
ratio,ration,center,centern=[],[],[],[]
for i in range(len(im)):
x_im_l,y_im_l = [],[]
x_im_r,y_im_r = [],[]
xn_im_l,yn_im_l = [],[]
... | 620fa37306f85a06d88b4f08fd84e9873866e011 | 23,849 |
def zfsr32(val, n):
"""zero fill shift right for 32 bit integers"""
return (val >> n) if val >= 0 else ((val + 4294967296) >> n) | 4b890caa0b7b086e923e7b229e5551fd66d24016 | 23,850 |
def n_optimize_fn(step: int) -> int:
"""`n_optimize` scheduling function."""
if step <= FLAGS.change_n_optimize_at:
return FLAGS.n_optimize_1
else:
return FLAGS.n_optimize_2 | 2d8b05a19c05a662119e51ace97817246c38ebe3 | 23,851 |
import torch
def compute_receptive_field(model, img_size=(1, 3, 3)):
"""Computes the receptive field for a model.
The receptive field is computed using the magnitude of the gradient of the
model's output with respect to the input.
Args:
model: Model for hich to compute the receptive field. A... | bdc3065e696bf221698d1abdb0717b7da957ca84 | 23,852 |
def flippv(pv, n):
"""Flips the meaning of an index partition vector.
Parameters
----------
pv : ndarray
The index partition to flip.
n : integer
The length of the dimension to partition.
Returns
-------
notpv : ndarray
The complement of pv.
Example:
>>... | 6c063169100eba098460cd12339f7a6266ea01f0 | 23,853 |
from typing import Union
from pathlib import Path
def is_dir(path: Union[str, Path]) -> bool:
"""Check if the given path is a directory
:param path: path to be checked
"""
if isinstance(path, str):
path = Path(path)
if path.exists():
return path.is_dir()
else:
return ... | 540cce7f5c6a25186427ba71b94aa090c2ab90a7 | 23,854 |
from itertools import cycle
def _replace_dendro_colours(
colours,
above_threshold_colour="C0",
non_cluster_colour="black",
colorscale=None
):
""" Returns colorscale used for dendrogram tree clusters.
Keyword arguments:
colorscale -- Colors to use for the plot in rgb format.
Should... | ce50b8c061bb908d8670b059261cde83e7dd62b1 | 23,856 |
import re
def document_to_vector(lemmatized_document, uniques):
"""
Converts a lemmatized document to a bow vector
representation.
1/0 for word exists/doesn't exist
"""
#print(uniques)
# tokenize
words = re.findall(r'\w+', lemmatized_document.lower())
# vector = {}
vector = ... | e4b108b8e99a827788d7eff5d4eabf71021d6e21 | 23,857 |
def ubcOcTree(FileName_Mesh, FileName_Model, pdo=None):
"""
Description
-----------
Wrapper to Read UBC GIF OcTree mesh and model file pairs. UBC OcTree models are defined using a 2-file format. The "mesh" file describes how the data is descritized. The "model" file lists the physical property values fo... | f9d71c7beebc8ca5f3c45fc24a4fd6ccae607634 | 23,858 |
def load_colormaps():
"""Return the provided colormaps."""
return load_builtin_data('colormaps') | 00b0d73e127cbbf11b76d5a2281493af95337008 | 23,859 |
def discriminator(hr_images, scope, dim):
"""
Discriminator
"""
conv_lrelu = partial(conv, activation_fn=lrelu)
def _combine(x, newdim, name, z=None):
x = conv_lrelu(x, newdim, 1, 1, name)
y = x if z is None else tf.concat([x, z], axis=-1)
return minibatch_stddev_layer(y)
... | 9af149750aed5febd17ab37b1e816356d2e27a40 | 23,860 |
def addchallenges(request) :
"""
管理员添加新的题目
"""
if request.user.is_superuser :
if request.method == 'POST' :
success = 0
form = forms.AddChallengeForm(request.POST, request.FILES)
if form.is_valid() :
success = 1
print(request.FILES)
if request.FILES :
i = models.Challenges(file=request.F... | e7aaa3a8418f66322f050dee74d74fd1d71bc0c9 | 23,861 |
def _decompose_ridge(Xtrain, alphas, n_alphas_batch=None, method="svd",
negative_eigenvalues="zeros"):
"""Precompute resolution matrices for ridge predictions.
To compute the prediction::
Ytest_hat = Xtest @ (XTX + alphas * Id)^-1 @ Xtrain^T @ Ytrain
where XTX = Xtrain^T ... | ba7d466546f4d417f9f455aee5fa0cccdaba968c | 23,862 |
import requests
def get_new_listing(old_listing):
"""Get the new listing."""
try:
fetched_listing = requests.get(cfg['api_url']).json()['product']
except requests.exceptions.RequestException:
return old_listing
else:
old_item_ids = {old_item['productId'] for old_item in old_lis... | f8aa02d1a804ef5cfbb1192da15091d8e8816d16 | 23,863 |
from typing import Union
import logging
def create_user(engine: create_engine, data: dict) -> Union[User, None]:
"""
Function for creating row in database
:param engine: sqlmodel's engine
:param data: dictionary with data that represents user
:return: Created user instance or nothing
"""
l... | bb1dff7aca37a8a1eab9104d0b6cd27cb55f78da | 23,864 |
def _densify_2D(a, fact=2):
"""Densify a 2D array using np.interp.
:fact - the factor to density the line segments by
:Notes
:-----
:original construction of c rather than the zero's approach
: c0 = c0.reshape(n, -1)
: c1 = c1.reshape(n, -1)
: c = np.concatenate((c0, c1), 1)
"""
... | e9a881f014c9ebcae6f3550c3b0c4d7beb576203 | 23,865 |
from typing import Union
def get_neighbor_edge(
graph: srf.Alignment,
edge: tuple[int, int],
column: str = 'z',
direction: str = 'up',
window: Union[None, int] = None,
statistic: str = 'min'
) -> Union[None, tuple[int, int]]:
"""Return the neighboring edge having the lowest minimum value
... | df81a5480a673efbf66bda7951b634f99996ffcf | 23,867 |
def show_comparison(x_coordinates: np.ndarray, analytic_expression: callable, numeric_solution: [dict, np.ndarray],
numeric_label: str = "Numeric Solution", analytic_label: str = "Analytic Solution",
title: str = None, x_label: str = None, y_label: str = None, save_file_as: str =... | 10727c4db401469f88fa93db31a13e21037f8e63 | 23,868 |
def has_master(mc: MasterCoordinator) -> bool:
""" True if `mc` has a master. """
return bool(mc.sc and not mc.sc.master and mc.sc.master_url) | 314fc4a2aa4deed7291d4676230bc9dafbb142d8 | 23,869 |
import time
def sz_margin_details(date='', retry_count=3, pause=0.001):
"""
获取深市融资融券明细列表
Parameters
--------
date:string
明细数据日期 format:YYYY-MM-DD 默认为空''
retry_count : int, 默认 3
如遇网络等问题重复执行的次数
pause : int, 默认 0
重复请求数据过程中暂停的秒数,防止请求间隔时间太短出现的问题... | 115ef7ec68a08de065f086b53835c7bd05a34ff8 | 23,870 |
def delay_slot_insn(*args):
"""
delay_slot_insn(ea, bexec, fexec) -> bool
Helper function to get the delay slot instruction.
@param ea (C++: ea_t *)
@param bexec (C++: bool *)
@param fexec (C++: bool *)
"""
return _ida_idp.delay_slot_insn(*args) | 6b0316845c4cefa2a33a9e9f5e0c24c1f2920a52 | 23,871 |
import numpy
def pairwise_radial_basis(K: numpy.ndarray, B: numpy.ndarray) -> numpy.ndarray:
"""Compute the TPS radial basis function phi(r) between every row-pair of K
and B where r is the Euclidean distance.
Arguments
---------
K : numpy.array
n by d vector containing n d-dimens... | 5ce4ff200bf953d80b7aff30b84b4ae0a62a0445 | 23,873 |
def low_index_subgroups(G, N, Y=[]):
"""
Implements the Low Index Subgroups algorithm, i.e find all subgroups of
``G`` upto a given index ``N``. This implements the method described in
[Sim94]. This procedure involves a backtrack search over incomplete Coset
Tables, rather than over forced coinciden... | 03dc48ada37302ca6d4bc5054660aae60bca2ca5 | 23,874 |
def ifft_complex(fft_sig_complex) -> np.ndarray:
"""
Compute the one-dimensional inverse discrete Fourier Transform.
:param fft_sig_complex: input array, can be complex.
:return: the truncated or zero-padded input, transformed along the axis
"""
ifft_sig = np.fft.ifft(fft_sig_complex)
fft_p... | 101189d4116b0d968ee015534ab8b8fc0020a769 | 23,875 |
def merge_eopatches(*eopatches, features=..., time_dependent_op=None, timeless_op=None):
""" Merge features of given EOPatches into a new EOPatch
:param eopatches: Any number of EOPatches to be merged together
:type eopatches: EOPatch
:param features: A collection of features to be merged together. By ... | 6328528c6b6fc3013db6aa17f0153354230efd4b | 23,876 |
import math
def dispos(dra0, decd0, dra, decd):
"""
Source/credit: Skycat
dispos computes distance and position angle solving a spherical
triangle (no approximations)
INPUT :coords in decimal degrees
OUTPUT :dist in arcmin, returns phi in degrees (East of North)
AUTHOR ... | 5c1b7c79a82f59764fd43ba0d89a763955b09a04 | 23,878 |
import socket
def bind_port(sock, host=HOST):
"""Bind the socket to a free port and return the port number. Relies on
ephemeral ports in order to ensure we are using an unbound port. This is
important as many tests may be running simultaneously, especially in a
buildbot environment. This method rai... | a326581bea0f0873292028a5e39a710ea89fde4b | 23,879 |
from typing import Union
def node_to_html(node: Union[str, NodeElement, list]) -> str:
"""
Convert Nodes to HTML
:param node:
:return:
"""
if isinstance(node, str): # Text
return escape(node)
elif isinstance(node, list): # List of nodes
result = ''
for child_nod... | 0366dffc181f27ac10cbae8d9eae65b6822371c6 | 23,880 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.