content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def determine_clim_by_standard_deviation(color_data, n_std_dev=2.5):
"""Automatically determine color limits based on number of standard
deviations from the mean of the color data (color_data). Useful if there
are outliers in the data causing difficulties in distinguishing most of
the data. Outputs vmin... | 5,335,100 |
def test_TDMA_solver():
"""
Test the matrix solver function solve()
"""
# define test matrix
test_a = [[0, -2.6, 1], [1, -2.6, 1], [1, -2.6, 1], [1, -2.6, 0]]
test_b = [-240.0, 0.0, 0.0, -150.0]
# define the solution to the test matrix
correct_x = [118.1122, 67.0916, 56.3261, 79.3562]
... | 5,335,101 |
def dt(c):
"""
Remove all models on models folder and retrain
"""
c.run("rm -f models/*", pty=True)
print("All model files removed.")
t(c) | 5,335,102 |
def ec_double(point: ECPoint, alpha: int, p: int) -> ECPoint:
"""
Doubles a point on an elliptic curve with the equation y^2 = x^3 + alpha*x + beta mod p.
Assumes the point is given in affine form (x, y) and has y != 0.
"""
assert point[1] % p != 0
m = div_mod(3 * point[0] * point[0] + alpha, 2 ... | 5,335,103 |
def scaled_dot_product_attention(q, k, v, mask):
"""
Calculate the attention weights.
q, k, v must have matching leading dimensions.
k, v must have matching penultimate dimension, i.e.: seq_len_k = seq_len_v.
The mask has different shapes depending on its type(padding or look ahead)
but it must ... | 5,335,104 |
def _parse_message(message):
"""Parses the message.
Splits the message into separators and tags. Tags are named tuples
representing the string ^^type:name:format^^ and they are separated by
separators. For example, in
"123^^node:Foo:${file}^^456^^node:Bar:${line}^^789", there are two tags and
three separat... | 5,335,105 |
def plot_simp_pat2D():
"""Test 2D plot of the tangential vector function given by the
spherical harmonic function Psi in vsh package."""
THETA, PHI, E_th, E_ph = gen_simp_pat()
tvecfun.plotvfonsph(THETA, PHI, E_th, E_ph) | 5,335,106 |
def model_fn(features, labels, mode, params):
"""Model function."""
del labels, params
encoder_module = hub.Module(FLAGS.retriever_module_path)
block_emb = encoder_module(
inputs=dict(
input_ids=features["block_ids"],
input_mask=features["block_mask"],
segment_ids=features["b... | 5,335,107 |
def get_rotated_coords(vec, coords):
"""
Given the unit vector (in cartesian), 'vec', generates
the rotation matrix and rotates the given 'coords' to
align the z-axis along the unit vector, 'vec'
Args:
vec, coords - unit vector to rotate to, coordinates
Returns:
rot_coords: ro... | 5,335,108 |
def SetDrainFlag(drain_flag):
"""Sets the drain flag for the queue.
@type drain_flag: boolean
@param drain_flag: Whether to set or unset the drain flag
@attention: This function should only called the current holder of the queue
lock
"""
getents = runtime.GetEnts()
if drain_flag:
utils.WriteFil... | 5,335,109 |
def journalMethodCall(objectPath: str, methodName: str, args: tuple, kargs: str):
"""This function may be used by a user-defined command to record itself in the Abaqus
journal file.
For example
def setValues( self, **kargs ):
for arg,value in kargs.items():
setattr(arg, value... | 5,335,110 |
def merge_on_pids(all_pids, pdict, ddict):
"""
Helper function to merge dictionaries
all_pids: list of all patient ids
pdict, ddict: data dictionaries indexed by feature name
1) pdict[fname]: patient ids
2) ddict[fname]: data tensor corresponding to each patient
"""
set_ids = s... | 5,335,111 |
def dump(columns, fp, name=None, labels=None, formats=None):
"""
Serialize a SAS compressed transport file format document.
data = {
'a': [1, 2],
'b': [3, 4],
}
with open('example.cpt', 'wb') as f:
dump(data, f)
"""
raise NotImplementedError() | 5,335,112 |
def parse_args():
"""Parse command line arguments"""
parser = argparse.ArgumentParser(description='Characterize the synapse pulse extender')
parser.add_argument("--syn_pd", dest="syn_pd", type=int, default=SYN_PD, help="Set DAC_SYN_PD bias. Default {}".format(SYN_PD))
args = parser.parse_args()
retu... | 5,335,113 |
def add_target_resources(document):
"""Add fragmentless target URL values to make search easier."""
if oajson.is_collection(document):
for item in document.get(oajson.ITEMS, []):
add_target_resources(item)
else:
target = document.get('target')
if target is None:
... | 5,335,114 |
def do_inference(hostport, work_dir, concurrency, num_tests):
"""Tests PredictionService over Tensor-Bridge.
Args:
hostport: Host:port address of the PredictionService.
work_dir: The full path of working directory for test data set.
concurrency: Maximum number of concurrent requests.
num_tests: Num... | 5,335,115 |
def checkbox_2D(image, checkbox, debug=False):
"""
Find the course location of an input psf by finding the
brightest checkbox.
This function uses a 2 dimensional image as input, and
finds the the brightest checkbox of given size in the
image.
Keyword arguments:
image -- 2 d... | 5,335,116 |
def test_true() -> None:
"""This is a test that should always pass. This is just a default test
to make sure tests runs.
Parameters
----------
None
Returns
-------
None
"""
# Always true test.
assert_message = "This test should always pass."
assert True, assert_message
... | 5,335,117 |
def parseStylesheetFile(filename):
"""Load and parse an XSLT stylesheet"""
ret = libxsltmod.xsltParseStylesheetFile(filename)
if ret == None: return None
return stylesheet(_obj=ret) | 5,335,118 |
def tensor_to_index(tensor: torch.tensor, dim=1) -> np.ndarray:
"""Converts a tensor to an array of category index"""
return tensor_to_longs(torch.argmax(tensor, dim=dim)) | 5,335,119 |
def write_ef_first_stage_solution(ef,
solution_file_name,
first_stage_solution_writer=first_stage_nonant_writer):
"""
Write a solution file, if a solution is available, to the solution_file_name provided
Args:
ef : A Concrete Model... | 5,335,120 |
def create_superuser(site):
"""Create an initial superuser for the site.
This will ask for a username, password, and e-mail address for the
initial superuser account.
If a superuser already exists (due to re-running this script on an
existing database), it will be displayed for reference, and the ... | 5,335,121 |
def _process_json(outdata, **kwargs):
"""Function: _process_json
Description: Private function for chk_slv_time(). Process JSON data.
Arguments:
(input) outdata -> JSON document of Check Slave Time output.
(input) **kwargs:
ofile -> file name - Name of output file.
... | 5,335,122 |
def matchAPKs(sourceAPK, targetAPKs, matchingDepth=1, matchingThreshold=0.67, matchWith=10, useSimiDroid=False, fastSearch=True, matchingTimeout=500, labeling="vt1-vt1", useLookup=False):
"""
Compares and attempts to match two APK's and returns a similarity measure
:param sourceAPK: The path to the source A... | 5,335,123 |
def _le_(x: symbol, y: symbol) -> symbol:
"""
>>> isinstance(le_(symbol(3), symbol(2)), symbol)
True
>>> le_.instance(3, 2)
False
"""
return x <= y | 5,335,124 |
def convert_country_codes(source_codes: List[str], source_format: str, target_format: str,
throw_error: bool = False) -> List[str]:
"""
Convert country codes, e.g., from ISO_2 to full name.
Parameters
----------
source_codes: List[str]
List of codes to convert.
... | 5,335,125 |
def test_cartpole_dynamics_deviation():
"""Difference between analytical dynamics model and ground truth model.
"""
import matplotlib.pyplot as plt
from munch import munchify
from safe_il.envs.cartpole import CartPole
config = {
"seed": 1234,
"env_config": {
"normali... | 5,335,126 |
def _test_request(op):
"""Make a request to a wsgiref.simple_server and attempt to call
op(req) in the application. Succeed if the operation does not
time out."""
app = _make_test_app(op)
server = _make_test_server(app)
worker = threading.Thread(target=server.handle_request)
worker.setDaemon... | 5,335,127 |
def get_simple_lca_length(std_tree, test_gold_dict, node1, node2):
"""
get the corresponding node of node1 and node2 on std tree.
calculate the lca distance between them
Exception:
Exception("[Error: ] std has not been lca initialized yet")
std tree need to be initialized before running ... | 5,335,128 |
def test_popleft_child_existing_deque():
"""Testing popleft_child method on a existing deque."""
test_deque = Deque([1, 2, 3, 5])
popleft_child_value = test_deque.popleft_child()
assert popleft_child_value == 5 | 5,335,129 |
def test_check_retry_valid():
"""
Test that a retry is valid if the maximum number of retries has not been reached
"""
retry_handler = RetryHandler()
settings = retry_handler.get_retry_options({})
assert retry_handler.check_retry_valid(settings, 0) | 5,335,130 |
def edit_catagory(catagory_id):
"""edit catagory"""
name = request.form.get('name')
guest_id = session['guest_id']
exists = db.session.query(Catalogs).filter_by(name=name,
guest_id=guest_id).scalar()
if exists:
return abort(404)
if name... | 5,335,131 |
def match_patterns(name, name_w_pattern, patterns):
"""March patterns to filename.
Given a SPICE kernel name, a SPICE Kernel name with patterns, and the
possible patterns, provide a dictionary with the patterns as keys and
the patterns values as value after matching it between the SPICE Kernel
name... | 5,335,132 |
def _generate_good_delivery_token_email(request, good_delivery, msg=''):
"""
Send an email to user with good_delivery activation URL
and return the token
:type request: HttpRequest
:type good_delivery: GoodDelivery
:type msg: String
:param structure_slug: current HttpRequest
:param str... | 5,335,133 |
def test_fileinrewriterstep_in_and_out_with_formatting():
"""File rewriter step instantiates with in and out applies formatting."""
context = Context({'k1': 'v1',
'root': {'in': 'inpath{k1}here',
'out': 'outpath{k1}here'}})
obj = FileInRewriterStep('bl... | 5,335,134 |
def get_flavor(disk=None, min_disk=None, min_ram=None, name=None, ram=None, region=None, rx_tx_factor=None, swap=None, vcpus=None):
"""
Use this data source to get the ID of an available OpenStack flavor.
"""
__args__ = dict()
__args__['disk'] = disk
__args__['minDisk'] = min_disk
__args__[... | 5,335,135 |
def deal_hands(deck: Deck) -> Tuple[Deck, Deck, Deck, Deck]:
"""Deal the cards in the deck into four hands"""
return (deck[0::4], deck[1::4], deck[2::4], deck[3::4]) | 5,335,136 |
def add_new_publication_group(project):
"""
Create a new publication_group
POST data MUST be in JSON format
POST data SHOULD contain the following:
name: name for the group
published: publication status for the group, 0 meaning unpublished
"""
request_data = request.get_json()
if n... | 5,335,137 |
def basic_demo():
"""
Enable this to be run as a CLI script, as well as used as a library.
Mostly intended for testing or a basic demo.
"""
# Get the command-line arguments
parser = argparse.ArgumentParser(description='Perform SNMP discovery on a host, \
returning its data in a single struct... | 5,335,138 |
def test_gmres_against_graph_scipy(n, tensor_type, dtype, error, preconditioner, solve_method):
"""
Feature: ALL TO ALL
Description: test cases for [N x N] X [N X 1]
Expectation: the result match scipy in graph
"""
if not _is_valid_platform(tensor_type):
return
# Input CSRTensor of... | 5,335,139 |
def wtime() -> float:
"""
:return: the current time as a floating point number.
"""
return MPI.Wtime() | 5,335,140 |
def test_filter_syncing_pools():
"""test filter_syncing_pools
"""
myzfssnapshot=flexmock(zfssnapshot)
myzfssnapshot.should_receive('is_syncing').and_return(
False, True, False).one_by_one()
r = myzfssnapshot.filter_syncing_pools(['tank/foo',
'tank... | 5,335,141 |
def get_paginated_results(func, key, **kwargs):
"""
Many boto3 methods return only a limited number of results at once,
with pagination information. This function handles the pagination to
retrieve the entire result set.
@param func
The function to call to get the data.
@param key
... | 5,335,142 |
def survival_df(data, t_col="t", e_col="e", label_col="Y", exclude_col=[]):
"""
Transform original DataFrame to survival dataframe that would be used in model
training or predicting.
Parameters
----------
data: DataFrame
Survival data to be transformed.
t_col: str
Column na... | 5,335,143 |
def get_date_today():
"""Get date today in str format such as 20201119. """
return datetime.today().strftime('%Y%m%d') | 5,335,144 |
def check_model_in_dict(name, model_dict):
"""
Check whether the new model, name, exists in all previously considered models,
held in model_lists.
[previously in construct_models]
If name has not been previously considered, False is returned.
"""
# Return true indicates it has not been c... | 5,335,145 |
def generate_api_key(request):
"""Handles AJAX requests for a new API key."""
new_key = ApiUser.objects.get_unique_key()
return HttpResponse(json.dumps({'token' : new_key}), content_type="application/javascript") | 5,335,146 |
def input_output_details(interpreter):
"""
input_output_details:
Used to get the details from the interperter
"""
input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()
return input_details, output_details | 5,335,147 |
def charge_drone_battery(drone):
"""Handle the drone battery charging operation."""
battery_level = drone["State"]["Battery"]
if float(battery_level) < 95:
# Increase battery level
drone["State"]["Battery"] = float(battery_level) + 5
else:
# If battery >= 95 set battery le... | 5,335,148 |
def expirations(self, symbol, useDatetime=True, block: bool = True):
"""Gets list of available expiration dates for a symbol.
Calls the 'market/options/expirations.json' endpoint to get list of all
exp_dates available for some given equity.
Args:
symbol: Specify the stock symbol against wh... | 5,335,149 |
def track(name, x, direction=None):
"""
An identity function that registers hooks to
track the value and gradient of the specified tensor.
Here is an example of how to track an intermediate output ::
input = ...
conv1 = nnt.track('op', nnt.Conv2d(shape, 4, 3), 'all')
conv2 = nn... | 5,335,150 |
def print_summary_title():
"""
Prints the Summary title
"""
print (f"\n") # New line
print ("-" * 40) # Print horizontal line
print (f"SUMMARY")
print ("-" * 40) # Print horizontal line
return | 5,335,151 |
def expected_l1_ls8_folder(
l1_ls8_folder: Path,
offset: Callable[[Path, str], str] = relative_offset,
organisation="usgs.gov",
collection="1",
l1_collection="1",
lineage=None,
):
"""
:param collection: The collection of the current scene
:param l1_collection: The collection of the o... | 5,335,152 |
def fetchPackageNames(graphJson):
"""Parses serialized graph and returns all package names it uses
:param graphJson: Serialized graph
:type graphJson: dict
:rtyoe: list(str)
"""
packages = set()
def worker(graphData):
for node in graphData["nodes"]:
packages.add(node["p... | 5,335,153 |
def get_nc_BGrid_POP(grdfile, name='POP_NEP', \
xrange=(170,270), yrange=(240, 350)):
"""
grd = get_nc_BGrid_POP(grdfile)
Load Bgrid object for POP from netCDF file
"""
nc = pycnal.io.Dataset(grdfile)
lon_t = nc.variables['TLONG'][:]
lat_t = nc.variables['TLAT'][:... | 5,335,154 |
def types_and_shorthands():
"""a mapping from type names in the json doc to their
one letter short hands in the output of 'attr'
"""
return {
'int': 'i',
'uint': 'u',
'bool': 'b',
'decimal': 'd',
'color': 'c',
'string': 's',
'regex': 'r',
'... | 5,335,155 |
def _make_event_from_message(message):
"""Turn a raw message from the wire into an event.Event object
"""
if 'oslo.message' in message:
# Unpack the RPC call body and discard the envelope
message = rpc_common.deserialize_msg(message)
tenant_id = _get_tenant_id_for_message(message)
cr... | 5,335,156 |
def to_region(obj):
"""Convert `obj` to instance of Region."""
if obj is not None and not isinstance(obj, Region):
return Region(*obj)
else:
return obj | 5,335,157 |
def create_textures():
""" Create a list of images for sprites based on the global colors.
!!! SHOULD be able to add custom images in here instead of the general colors."""
texture_list = []
for color in colors:
image = PIL.Image.new('RGB', (WIDTH, HEIGHT), color)
texture_list.append(ar... | 5,335,158 |
def check_if_process_is_running(process_name):
""""
Check if there is any running process that contains the given name process_name.
"""
# Iterate over the all the running process
for process in psutil.process_iter():
try:
# Check if process name contains the given name string.
... | 5,335,159 |
def uncover_homework(filepath, cipher, fs=None):
"""Convert a text file into a homework.
A homework is defined as two files, one with some lines changed according
to the language defined by the library (see the docs) and another one with
the solution. The solution file is encrypted so that the student'... | 5,335,160 |
def fair_d6(seed=None):
"""Uses a biased d6 to generate fair values between 1 and 6."""
# pick random weights for the faces, then normalize
if seed:
random.seed(seed)
faces = [random.random() for x in range(6)]
total = sum(faces)
faces = map(lambda x: x / total, faces)
faces = [sum(fac... | 5,335,161 |
def tweet_sunset():
""" Sends a tweet about sunset """
try:
now = datetime.now()
time_ran = now.strftime("%-I:%M %p")
day_length_text = ""
# Compute Length of Day
_, sunset_time, day_length_today = _get_sunrise_sunset_times(now)
_, _, day_length_tomorrow = _get_... | 5,335,162 |
def exec_main_with_profiler(options: "optparse.Values") -> int:
"""Enable profiler."""
import cProfile
import pstats
import io
from pstats import SortKey # type: ignore
profile = cProfile.Profile()
profile.enable()
ret = exec_main(options)
profile.disable()
string_io = io.Strin... | 5,335,163 |
def put_text(image, text, point, scale, color, thickness):
"""Draws text in image.
# Arguments
image: Numpy array.
text: String. Text to be drawn.
point: Tuple of coordinates indicating the top corner of the text.
scale: Float. Scale of text.
color: Tuple of integers. RG... | 5,335,164 |
def test_url_join():
"""
Some basic URL joining tests.
"""
url = URL("https://example.org:123/path/to/somewhere")
assert url.join('/somewhere-else') == "https://example.org:123/somewhere-else"
assert url.join('somewhere-else') == "https://example.org:123/path/to/somewhere-else"
assert url.jo... | 5,335,165 |
def squash_dimensions(
dimensions: List[Dimension], check_path_changes=True
) -> Dimension:
"""Squash a list of nested Dimensions into a single one.
Args:
dimensions: The Dimensions to squash, from slowest to fastest moving
check_path_changes: If True then check that nesting the output
... | 5,335,166 |
def do_delete(cs, args):
"""Delete specified instance(s)."""
utils.do_action_on_many(
lambda s: cs.instances.delete(_find_instance(cs, s)),
args.instance,
_("Request to delete instance %s has been accepted."),
_("Unable to delete the specified instance(s).")) | 5,335,167 |
def CreateRootRelativePath(self, path):
"""
Generate a path relative from the root
"""
result_path = self.engine_node.make_node(path)
return result_path.abspath() | 5,335,168 |
def test_packages(host, name, codenames):
"""
Test installed packages
"""
if host.system_info.distribution not in ['debian', 'ubuntu']:
pytest.skip('{} ({}) distribution not managed'.format(
host.system_info.distribution, host.system_info.release))
if codenames and host.system_... | 5,335,169 |
def commit():
""" copy built docs to gh-pages and commit"""
dest = join(PATH['gh-pages'], GIT_NAME)
src = join(PATH['root'], 'build/html')
os.chdir(dest)
os.system('rm -rf *')
print('Copying docs to:',dest)
copytree(src,dest)
os.system("git add *")
os.system("git commit... | 5,335,170 |
async def test_user_flow_cannot_connect(hass):
"""Test that config flow handles connection errors."""
with patch(
"homeassistant.components.hvv_departures.hub.GTI.init",
side_effect=CannotConnect(),
):
# step: user
result_user = await hass.config_entries.flow.async_init(
... | 5,335,171 |
def test_node():
"""Test creation of node."""
node = Node(1, 9000)
assert node.name == "nodo1"
assert str(node) == str({"name": "nodo1", "port": 9000}) | 5,335,172 |
def resolve_font(name):
"""Sloppy way to turn font names into absolute filenames
This isn't intended to be a proper font lookup tool but rather a
dirty tool to not have to specify the absolute filename every
time.
For example::
>>> path = resolve_font('IndUni-H-Bold')
>>> fontdir... | 5,335,173 |
def to_shape(shape_ser):
""" Deserializes a shape into a Shapely object - can handle WKT, GeoJSON,
Python dictionaries and Shapely types.
"""
if isinstance(shape_ser, str):
try:
# Redirecting stdout because there's a low level exception that
# prints.
with... | 5,335,174 |
def _from_module(module, object):
"""
Return true if the given object is defined in the given module.
"""
if module is None:
return True
elif inspect.getmodule(object) is not None:
return module is inspect.getmodule(object)
elif inspect.isfunction(object):
return module._... | 5,335,175 |
def _escape_pgpass(txt):
"""
Escape a fragment of a PostgreSQL .pgpass file.
"""
return txt.replace('\\', '\\\\').replace(':', '\\:') | 5,335,176 |
def harvest_dirs(path):
"""Return a list of versioned directories under working copy
directory PATH, inclusive."""
# 'svn status' output line matcher, taken from the Subversion test suite
rm = re.compile('^([!MACDRUG_ ][MACDRUG_ ])([L ])([+ ])([S ])([KOBT ]) ' \
'([* ]) [^0-9-]*(\... | 5,335,177 |
def gen_index(doc_term_map: Dict[PT.Word, Set[PT.IndexNum]],
dependency_map: Dict[PT.IndexNum, Count],
i: PT.IndexNum,
words: List[PT.Word]
) -> PT.PkgIndex:
"""Generate package index by scoring each word / term."""
word_freq: Dict[PT.Word, Count] = utils... | 5,335,178 |
def arr_to_dict(arr, ref_dict):
"""
Transform an array of data into a dictionary keyed by the same keys in
ref_dict, with data divided into chunks of the same length as in ref_dict.
Requires that the length of the array is the sum of the lengths of the
arrays in each entry of ref_dict. The other di... | 5,335,179 |
def test_makecpt_truncated_zlow_zhigh(position):
"""
Use static color palette table that is truncated to z-low and z-high.
"""
fig = Figure()
makecpt(cmap="rainbow", truncate=[0.15, 0.85], series=[0, 1000])
fig.colorbar(cmap=True, frame=True, position=position)
return fig | 5,335,180 |
def extract_boar_teloFISH_as_list(path):
"""
FUNCTION FOR PULLING KELLY'S TELOFISH DATA FOR 40 BOARS into a LIST.. TO BE MADE INTO A DATAFRAME & JOINED W/
MAIN DATAFRAME if possible
These excel files take forever to load.. the objective here is to synthesize all the excel files for
telomere FISH ... | 5,335,181 |
def captured_stdout():
"""Capture the output of sys.stdout:
with captured_stdout() as stdout:
print("hello")
self.assertEqual(stdout.getvalue(), "hello\n")
"""
return captured_output("stdout") | 5,335,182 |
def login():
"""
Handles user authentication.
The hash of the password the user entered is compared to the hash in the database.
Also saves the user_id in the user's session.
"""
form = SignInForm()
banned = None
reason = None
if form.validate_on_submit():
user_id = form.user... | 5,335,183 |
def create_ipu_strategy(num_ipus,
fp_exceptions=False,
enable_recomputation=True,
min_remote_tensor_size=50000,
max_cross_replica_sum_buffer_size=10*1024*1024):
"""
Creates an IPU config and returns an IPU strategy r... | 5,335,184 |
def run_pipeline(context, func, ast, func_signature,
pipeline=None, **kwargs):
"""
Run a bunch of AST transformers and visitors on the AST.
"""
# print __import__('ast').dump(ast)
pipeline = pipeline or context.numba_pipeline(context, func, ast,
... | 5,335,185 |
def convert_acc_data_to_g(
data: Union[AccDataFrame, ImuDataFrame], inplace: Optional[bool] = False
) -> Optional[Union[AccDataFrame, ImuDataFrame]]:
"""Convert acceleration data from :math:`m/s^2` to g.
Parameters
----------
data : :class:`~biopsykit.utils.datatype_helper.AccDataFrame` or \
... | 5,335,186 |
def replace_by_one_rule(specific_rule: dict, sentence: str):
"""
This function replace a sentence with the given specific replacement dict.
:param specific_rule: A dict containing the replacement rule, where the keys are the words to use, the values will
be replaced by the keys.
:param sentence: A s... | 5,335,187 |
def get_os(platform):
"""
Return the icon-name of the OS.
@type platform: C{string}
@param platform: A string that represents the platform of the
relay.
@rtype: C{string}
@return: The icon-name version of the OS of the relay.
"""
if platform:
for os in __OS_LIST:
... | 5,335,188 |
def get_loglikelihood_fn(dd_s, f_l=f_l, f_h=f_h, n_f=n_f):
"""
x: parameter point
dd_s: signal system
"""
fs = jnp.linspace(f_l, f_h, n_f)
pad_low, pad_high = get_match_pads(fs)
def _ll(x):
# Unpack parameters into dark dress ones
gamma_s, rho_6T, M_chirp_MSUN, log10_q = x
... | 5,335,189 |
def to_module_name(field):
"""_to_module_name(self, field: str) -> str
Convert module name to match syntax used in https://github.com/brendangregg/FlameGraph
Examples:
[unknown] -> [unknown]'
/usr/bin/firefox -> [firefox]
"""
if field != '[unknown]':
field = '[{}]'.format(fi... | 5,335,190 |
def ApplyMomentum(variable, accumulation, learning_rate, gradient, momentum, use_nesterov=False, gradient_scale=1.0):
"""apply momentum"""
return apply_momentum.apply_momentum(variable, gradient, accumulation, learning_rate,
momentum, use_nesterov=use_nesterov, grad_scal... | 5,335,191 |
def init():
"""Return True if the plugin has loaded successfully."""
ok = True
if ok:
#g.registerHandler('start2',onStart2)
g.plugin_signon(__name__)
#serve_thread()
#g.app.remoteserver = ss = LeoSocketServer()
return ok | 5,335,192 |
def _fftconvolve_14(in1, in2, int2_fft, mode="same"):
"""
scipy routine scipy.signal.fftconvolve with kernel already fourier transformed
"""
in1 = signaltools.asarray(in1)
in2 = signaltools.asarray(in2)
if in1.ndim == in2.ndim == 0: # scalar inputs
return in1 * in2
elif not in1.ndi... | 5,335,193 |
def solve_step(previous_solution_space, phase_space_position, step_num):
"""
Solves the differential equation across the full spectrum of trajectory angles and neutrino energies
:param previous_solution_space: solution to previous step of the differential equation
across all angles and energies, include... | 5,335,194 |
def gradientDescentMulti(X, y, theta, alpha, num_iters):
"""
Performs gradient descent to learn theta
theta = gradientDescent(x, y, theta, alpha, num_iters) updates theta by
taking num_iters gradient steps with learning rate alpha
"""
# Initialize some useful values
J_history = []
... | 5,335,195 |
def execute(*args, **kw):
"""Wrapper for ``Cursor#execute()``."""
return _m.connection["default"].cursor().execute(*args, **kw) | 5,335,196 |
def redeem_with_retry(client, data, headers):
"""
Attempt a redemption. Retry if it fails.
:return: A ``Deferred`` that fires with (duration of successful request,
number of failed requests).
"""
errors = 0
while True:
before = time()
response = yield client.post(
... | 5,335,197 |
def get_login_client():
"""
Returns a LinodeLoginClient configured as per the config module in this
example project.
"""
return LinodeLoginClient(config.client_id, config.client_secret) | 5,335,198 |
def ensure_path_is_valid(pth):
""" Raise an exception if we can’t write to the specified path """
if isnotpath(pth):
raise FilesystemError(f"Operand must be a path type: {pth}")
if os.path.exists(pth):
if os.path.isdir(pth):
raise FilesystemError(f"Can’t save over directory: {pth... | 5,335,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.