content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def test_caret_cmd(vim_bot, text, cmd_list, cursor_pos):
"""Test ^ command."""
_, _, editor, vim, qtbot = vim_bot
editor.set_text(text)
cmd_line = vim.get_focus_widget()
for cmd in cmd_list:
qtbot.keyClicks(cmd_line, cmd)
assert cmd_line.text() == ""
assert editor.textCursor().posi... | 78,500 |
def clean_dfg_based_on_noise_thresh(dfg, activities, noise_threshold, parameters=None):
"""
Clean Directly-Follows graph based on noise threshold
Parameters
----------
dfg
Directly-Follows graph
activities
Activities in the DFG graph
noise_threshold
Noise threshold
... | 78,501 |
def configure_app(config):
"""
Fetch configuration.
:param config: Config object.
"""
app.config.from_object(config)
CORS(app, resources={r"/*": {"origins": "*"}}, support_credentials=True) | 78,502 |
def post_form(lti):
# pylint: disable=unused-argument,
"""
Access route with 'initial' request.
:param lti: `lti` object
:return: string "hi"
"""
return "hi" | 78,503 |
def cached_accessor(func_or_att):
"""Decorated function checks in-memory cache and disc cache for att first"""
if callable(func_or_att): #allows decorator to be called without arguments
att = func_or_att.__name__
return cached_accessor(func_or_att.__name__)(func_or_att)
att = func_or_att
... | 78,504 |
def test_models_file(tmp_path):
"""
GIVEN specification stored in a YAML file
WHEN init_yaml is called with the file and a models file path
THEN the models are written to the models file.
"""
# pylint: disable=import-error,import-outside-toplevel
# Generate spec file
directory = tmp_path... | 78,505 |
def function_parts(subdir='./'):
"""
Parse the gsw m-files in a given subdirectory.
Returns a list of parts: function base name, arguments,
inputs, and the help lines with a section index dictionary.
"""
d = os.path.join(mfiledir, subdir)
mfilelist = glob.glob(os.path.join(d, '*.m'))
p... | 78,506 |
def make_graph():
"""Convert the data to a BEL graph."""
if not os.path.exists(DATA_PATH):
download_data()
df = extract_data()
return _make_graph(df) | 78,507 |
def write_tf_records(args):
"""Run TFRecord writer with given arguments."""
image_size = None
if args.image_size is not None:
image_size = parse_image_size(args.image_size)
writer = a2d2.data_loader.A2D2TFRecordWriter(args.output, os.path.join(args.datadir, "class_list.json"), image_size)
wr... | 78,508 |
def find_valid_background_scan_segments(
N2_CVs, maximum_scanrate=0.011, scan_length=1950, segment_key="Segment #"
) -> List[int]:
"""checks if the data possibly contains a N2 background scan"""
# finder_warning = None
if not isinstance(N2_CVs, pd.DataFrame):
# optional warning for TypeError
... | 78,509 |
def __typePrinterLoc(arg):
""" Shorthand for printing all elements of locals() or globals() """
for elem in arg: __typePrinter(arg[elem], name=elem) | 78,510 |
def api_root(request, format=None):
"""
GET:
Display all available urls.
Since some urls have specific permissions, you might not be able to access
them all.
"""
apis = PUBLIC_APIS(request, format)
if request.user.is_staff:
apis += PROTECTED_APIS(request, format)
return Res... | 78,511 |
def get_gas_from_etherscan(key: str,
verbose: bool = False) -> Tuple[int, int, int]:
"""
Fetch gas from Etherscan API
"""
r = requests.get('https://api.etherscan.io/api',
params={'module': 'gastracker',
'action': 'gasoracle',
... | 78,512 |
def bit(value, position, length=1):
"""
Return bit of number value at position
Position starts from 0 (LSB)
:param value:
:param position:
:param length:
:return:
"""
binary = bin(value)[2:]
size = len(binary) - 1
if position > size:
return 0
else:
return ... | 78,513 |
def sidereal_lunar_longitude(tee):
"""Return sidereal lunar longitude at moment, tee."""
return mod(lunar_longitude(tee) - precession(tee) + SIDEREAL_START, 360) | 78,514 |
def create_view_event_from_tensor_basic_info(tensors_info):
"""
Create view event reply according to tensor names.
Args:
tensors_info (list[TensorBasicInfo]): The list of TensorBasicInfo. Each element has keys:
`full_name`, `node_type`, `iter`.
Returns:
EventReply, the even... | 78,515 |
def diff_template(page, label=None):
"""
Return a Template:Diff2 string for the given Page.
"""
if label is None:
label = page.title()
return f"{{{{Diff2|{page.latest_revision_id}|{label}}}}}" | 78,516 |
def is_builtin(func):
"""Return true if the function is a DGL builtin function."""
return isinstance(func, fn.BuiltinFunction) | 78,517 |
def compute_sun_angle(
position,
pose,
utc_datetime,
sensor_orientation,
):
""" compute the sun angle using pysolar functions"""
altitude = 0
azimuth = 0
import warnings
with warnings.catch_warnings(): # Ignore pysolar leap seconds offset warning
warnings.simplefilter("ignore... | 78,518 |
def find_tuple_with_max_ncp(base, T, key, T_max_vals, T_min_vals):
"""
Scan through the whole table T, and find the i-th tuple that maximizes NCP(base, i).
Parameters
----------
:param base: list of int
Tuple to compare T's tuples against
:param key: T
the table
:param... | 78,519 |
def make_dataset_name(name):
"""Dataset name contains "letters, numbers, -, _" only, any other content will be replaced with "-"
"""
def may_replace(c):
if re.match("\w", c) is None:
if c == '-':
return c
else:
return "_"
else:
... | 78,520 |
def averageOfNumbers():
""" averageOfNumbers
Outputs the average of a series of numbers entered by the user.
returns:
The average of the numbers input by the user.
"""
numbers = []
amount_of_numbers = input("How many numbers do you wish to input? ")
for x in range(1, int(amount... | 78,521 |
def process_covid_ctset_data(covid_ctset_meta_csv, covid_ctset_dir, output_dir):
"""Processes slices for all patients in the given COVID-CTSet CSV file"""
filenames = []
classes = []
with open(covid_ctset_meta_csv, 'r') as f:
reader = list(csv.DictReader(f, delimiter=',', quotechar='|'))
... | 78,522 |
def list_command_invocations(CommandId=None, InstanceId=None, MaxResults=None, NextToken=None, Filters=None, Details=None):
"""
An invocation is copy of a command sent to a specific instance. A command can apply to one or more instances. A command invocation applies to one instance. For example, if a user execu... | 78,523 |
def validate(xmlfile=None, type='request'):
"""
:type xmlfile: str
"""
if type not in ['request', 'response', 'cixml']:
print('Invalid xml document type')
sys.exit()
else:
schema = xmlschema.XMLSchema('{}{}.xsd'.format(SCHEMAS_FOLDER, type))
return schema.is_valid(xm... | 78,524 |
def pinsage_sample(graph,
nodes,
samples,
top_k=10,
proba=0.5,
norm_bais=1.0,
ignore_edges=set()):
"""Implement of graphsage sample.
Reference paper: .
Args:
graph: A pgl graph instanc... | 78,525 |
def nbytes(obj, pprint=False):
""" return the number of bytes of the object, which includes size of nested
structures
Parameters
----------
obj: object
object to find the size of
pprint: bool, optional (default=False)
if set, returns the result after calling pretty_size_print
... | 78,526 |
def s2m_comrelid(request, s, sattr, m, mattr):
""" """
if mattr != 'relation' or sattr != 'commentRelationId':
raise RuntimeError, "s2m_comrelid is confused by %s and %s" % (sattr, mattr)
if sattr in s:
if isinstance(s[sattr], int):
m.relation = Relation.objects.get(id=s[sattr])
elif re.match(r'^\d+... | 78,527 |
def calc_entropy(data, base=2):
"""
Calculate the entropy of data. Using documentation from
scipy.stats.entropy as the basis for this code
(https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.entropy.html).
:param data: Measure the entropy of this object
:return: Calculated entropy ... | 78,528 |
def calbar(axl, calbar=None, axesoff=True, orient='left', unitNames=None, fontsize=11, weight='normal', font='Arial'):
"""
draw a calibration bar and label it. The calibration bar is defined as:
[x0, y0, xlen, ylen]
"""
axl = _ax_tolist(axl)
# if type(axl) is not list:
# axl = [a... | 78,529 |
def singledispatch_method(func):
"""Singledispatch on second argument, i.e. the one that isn't `self`."""
dispatcher = functools.singledispatch(func)
def wrapper(*args, **kw):
return dispatcher.dispatch(args[1].__class__)(*args, **kw)
wrapper.register = dispatcher.register
functools.update... | 78,530 |
def set_slops_from_read_orientation(slop, tpl_reads_orientation, cipos, ciend, buffer=0): # TODO: from Hardcoded to Dynamic Variable for buffer if requested
"""
set the slop boundaries according to the svtype and the reads orientation fro that svtype
:param slop: minimum slop value
:param tpl_reads_ori... | 78,531 |
def authenticate_user_registration(some_function):
""" Decorator for functions (pages) that require a user to provide identification. Returns
403 (forbidden) or 401 (depending on beiwe-api-version) if the identifying info (username,
password, device ID) are invalid.
In any function wrapped with thi... | 78,532 |
def delete_group_keywords(session, group_name, group_keywords, priority=None):
"""
Function to delete a list of keyword of a group.
Parameters
----------
session : sqlalchemy.orm.session.Session
SQL Alchemy session
group_name : str
group name in the database
group_keywords :... | 78,533 |
def getValidPaths(author_collabs, year):
"""
selects the neighbours with valid paths
returns a list where each result is a tuple of author name, collaborations < year
"""
valid_neighbours = list()
for n in author_collabs:
valid_collabs = list()
for c in author_collabs[n]:
... | 78,534 |
def _Tokenize(template_str, meta_left, meta_right, whitespace):
"""Yields tokens, which are 2-tuples (TOKEN_TYPE, token_string)."""
trimlen = len(meta_left)
token_re = MakeTokenRegex(meta_left, meta_right)
do_strip = (whitespace == 'strip-line') # Do this outside loop
do_strip_part = False
for line in te... | 78,535 |
def add_path(G, data, one_way):
"""
https://github.com/gboeing/osmnx/blob/master/osmnx/core.py
Add a path to the graph.
Parameters
----------
G : networkx multidigraph
data : dict
the attributes of the path
one_way : bool
if this path is one-way or if it is bi-directional... | 78,536 |
def plot_image(
image: ArrayLike,
imshow_kwargs: Optional[Dict] = None,
text_kwargs: Optional[Dict] = None,
**kwargs: Any,
) -> Tuple[plt.Figure, plt.Axes]:
"""
Plots given image.
Parameters
----------
image
Image to plot.
imshow_kwargs
Keyword arguments for the ... | 78,537 |
def check_pv_deleted(pv_name, created_objects):
""" checks pv is deleted or not , if not deleted ,asserts"""
if keep_objects:
return
count = 12
api_instance = client.CoreV1Api()
while (count > 0):
try:
api_response = api_instance.read_persistent_volume(
... | 78,538 |
def get_same_pinyin(char):
"""
取同音字
:param char:
:return:
"""
return same_pinyin.get(char, set()) | 78,539 |
def get_chart_params(title, output, show_legend=False):
"""Parse output type and output options and return related chart
parameters. For example: returns filename if output_type is file
or server it output_type is server
Args:
title (str): the title of your plot.
output (str): selected ... | 78,540 |
def preprocess(img, net_input_height_size=368, stride=8,
pad_value=(0, 0, 0), img_mean=(128, 128, 128), img_scale=1/256):
"""
Args:
img:
Returns:
"""
height, width, _ = img.shape
scale = net_input_height_size / height
scaled_img = cv2.resize(img, (0, 0), fx=scale,... | 78,541 |
def compute_DVARS(func_img, mean_img=None, mask=None, apply_mask=False):
"""Computes the DVARS for a given fMRI image."""
if mean_img is None:
mean_img = np.mean(func_img, axis=3)
if apply_mask:
if mask is None:
mask = mask_image(mean_img)
mean_img[np.logical_not(mask)]... | 78,542 |
def count_unplayed_cards(r, progress):
"""Returns the number of cards which are not yet played, including cards
which are unplayable because all those cards (or cards of a value below it)
are already discarded"""
n = 0
for suit in r.suits:
n += 5 - progress[suit]
return n | 78,543 |
def dump_raw_data(filename, data):
""" Write the data into a raw format file. Big endian is always used. """
rawfile = open(filename,'wb')
a = array.array('f')
for o in data:
a.fromlist(list(o))
if is_little_endian():
a.byteswap()
a.tofile(rawfile)
rawfile.close() | 78,544 |
async def test_lid_status(thermocycler: Thermocycler):
"""It should run open and close lid."""
await thermocycler.wait_next_poll()
assert thermocycler.lid_status == "open"
await thermocycler.close()
assert thermocycler.lid_status == "closed"
await thermocycler.open()
assert thermocycler.li... | 78,545 |
def new_drop(pixels, values):
"""Generate a new particle at the top of the board"""
# First, get a list of columns that haven't generated
# a particle recently
cols = []
for x in range(0, width):
good_col = True
for y in range(0, int(height * values['safe'])):
if pixels[... | 78,546 |
def index(request):
"""View function for home page of site."""
# Render the HTML template index.html with the data in the context variable.
return render(
request,
'index.html',
context = {},
) | 78,547 |
def find_start_time(arr, reps=1):
"""! A function to find when simulations reaches a steady state with
respect to array, arr.
@param arr: Array to find steady state in
@param reps: repetitions of recursion
@return: st Start time, the index of time array when the simulation
first reaches a the s... | 78,548 |
def execute_sql(sql, model=Award, fetcher=fetchall_fetcher, read_only=True):
"""
Executes a sql query against a database.
sql - Can be either a sql string statement or a psycopg2 Composable
object (Identifier, Literal, SQL, etc).
model - A Django model that represents a ... | 78,549 |
def calc_region(bbox, ratio, featmap_size=None):
"""Calculate a proportional bbox region.
The bbox center are fixed and the new h' and w' is h * ratio and w * ratio.
Args:
bbox (Tensor): Bboxes to calculate regions, shape (n, 4)
ratio (float): Ratio of the output region.
featmap_si... | 78,550 |
def toFENhash(fen):
""" Removes the two last parts of the FEN notation
"""
return ' '.join(fen.split(" ")[:-2]) | 78,551 |
def certify(collaborator_name, silent, request_pkg=False, import_=False):
"""Sign/certify collaborator certificate key pair."""
from click import confirm
from shutil import unpack_archive
from shutil import make_archive, copy
from glob import glob
from os.path import basename, join, splitext
... | 78,552 |
def fill_properties(p):
"""Sets up some properties with various types"""
p['prop_1'] = 1
p['prop_2'] = '1'
p['prop_3'] = False
p['prop_4'] = 3.14 | 78,553 |
def test_implements() -> None:
"""Test the implements decorator."""
class BaseClass:
def func(self) -> None:
"""Do nothing."""
def no_docstring(self) -> None:
pass
class CorrectImplementation(BaseClass):
@implements(BaseClass)
def func(self) -> None... | 78,554 |
def test_correlogram():
"""
Test for correlogram function in the functions module.
"""
with pytest.raises(ValueError):
fn.correlogram(signal=1)
with pytest.raises(TypeError):
fn.correlogram(signal='sa')
with pytest.raises(TypeError):
fn.correlogram(signal=1+3j)
with ... | 78,555 |
def test_string_composed_filter_with_count():
"""
Test count composed string filter.
"""
filter_string = '[sort[-title]] [count[2]]'
filters = filter.compose_from_string(filter_string)
found_tiddlers = filter.by_composition(filters, tiddlers)
assert [tiddler.title for tiddler in found_tidd... | 78,556 |
def remap_lads(lad_name):
"""Some LADs of MSOA census data do not match
the LAD geographies of the LAD population data
"""
if lad_name == 'E06000048':
lad_mapped = 'E06000057' #Northumberland
elif lad_name == 'E08000020':
lad_mapped = 'E08000037'
elif lad_name == 'E07000097':
... | 78,557 |
def generate_dummy_ip():
"""
makes a random ip address as a string
"""
return str(randint(0,255)) + "." + str(randint(0,255)) + "." + str(randint(0,255)) + "." + str(randint(0,255)) | 78,558 |
def _upload_and_get_command(boto3_factory, args, job_s3_folder, job_name, config, log):
"""
Get command by parsing args and config.
The function will also perform an s3 upload, if needed.
:param boto3_factory: initialized Boto3ClientFactory object
:param args: input arguments
:param job_s3_fold... | 78,559 |
def _root_broyden1_doc():
"""
Options
-------
nit : int, optional
Number of iterations to make. If omitted (default), make as many
as required to meet tolerances.
disp : bool, optional
Print status to stdout on every iteration.
maxiter : int, optional
Maximum numb... | 78,560 |
def get_cached(path: str, category: str=None) -> Union[str, dict, list]:
"""Get contents of a file.
The file contents are cached in memory, and all subsequent calls
to `get_cached()` with identical `path` & `category` arguments
return cached contents rather than reading the file on disk.
Sho... | 78,561 |
def asbytes(s: Literal["testdouble"]):
"""
usage.scipy: 1
"""
... | 78,562 |
def get_paying_proxy_contract(w3: Web3, address=None):
"""
Get Paying Proxy Contract. This should be used just for contract creation/changing master_copy
If you want to call Safe methods you should use `get_safe_contract` with the Proxy address,
so you can access every method of the Safe
:param w3: ... | 78,563 |
def search_motif_positions_debug(sequence, motif):
"""
Search a sequence for a given motif (as regex),
and return position as list. Return False if the motif
is absent from the sequence.
"""
print("Found motifs: %s" % regex.findall(r"%s" % motif, sequence))
positions = [m.start() + 1 for m in ... | 78,564 |
def validate(detector, val_data, metric):
"""Test on validation dataset."""
metric.reset()
for img, label in val_data:
# scores, bboxes = detector.detect(img)
scores, bboxes = detector.ms_detect(img)
metric.update(bboxes, scores, label)
return metric.get() | 78,565 |
def save_yaml(outdir, fname, data):
"""
Save data as '.yaml' file.
Parameters:
-----------
outdir : str
Directory to save data.
fname : str
Filename for output yaml.
data : dict
Data to save to yaml.
"""
filepath = os.path.join(outdir, fname)
if not os.p... | 78,566 |
def calculate_EcefPoints(lats, longs):
"""
Construct a numpy array of EcefPoints from 2 arrays containing
Latitudes and Longitudes.
Note: lats and longs must be of equal lengths.
Parameters
----------
lats: float array
An array of Latitudes in [degrees].
longs: float array
... | 78,567 |
def compute_flow_map(u, v, gran=8):
"""
Plot optical flow map
"""
flow_map = np.zeros(u.shape)
for y in range(flow_map.shape[0]):
for x in range(flow_map.shape[1]):
if y % gran == 0 and x % gran == 0:
dx = 2 * int(u[y, x])
dy = 2 * int(v[y, x])
... | 78,568 |
def brand_usage(number_of_brand_purchasers, total_purchasers):
"""Returns the percentage of brand usage for a period.
Args:
number_of_brand_purchasers (int): Total number of unique purchasers of a brand in a period.
total_purchasers (int): Total unique purchasers in a period.
Returns:
... | 78,569 |
def sim_walks(num_steps, num_trials, d_class):
"""Assumes num_steps an int >= 0, num_trials an int > 0,
d_class a subclass of Drunk
Simulates num_trials walks of num_steps steps each.
Returns a list of the final distances for each trial"""
Homer = d_class()
origin = Location(0, 0)
... | 78,570 |
def launch():
"""
Loads all of the cogs and starts the bot with the discord application.
"""
print()
print("-------------------------------")
print("Starting Analitica Discord Bot.")
print("-------------------------------")
# Load all the cogs from the files in the cogs folder on startu... | 78,571 |
def colormaps_path():
"""Returns the path to user-defined colormaps"""
return os.path.join(user_path(), "colormaps") | 78,572 |
def init_processes(fn):
""" Initialize the distributed environment. """
print(f"Running rank {RANK} of {SIZE} on {HOSTNAME}")
fn() | 78,573 |
def _construct_request_parameters(args: dict, keys: list, params={}):
"""A helper function to add the keys arguments to the dict parameters"""
parameters = {}
if params is not None:
for p in params:
parameters[p] = params[p]
for (arg_field, filter_field) in keys:
value = ar... | 78,574 |
def __run_query_table(context, client, sql: String) -> Optional[DataFrame]:
"""
Execute an SQL
:param context: execution context
:param sql: the SQL select query to execute
:return: panda DataFrame or None
:rtype: panda.DataFrame
"""
df = None
close_down = client is None
if clos... | 78,575 |
def install_enterprise_cli_package():
"""Install `dcos-enterprise-cli` package. It is required by the `dcos security`
command to create secrets, manage service accounts etc.
"""
print('Installing dcos-enterprise-cli package')
stdout, stderr, return_code = shakedown.run_dcos_command('package insta... | 78,576 |
def add_parts_json(ibs, annot_uuid_list, part_bbox_list, part_theta_list, **kwargs):
"""
REST:
Method: POST
URL: /api/part/json/
Ignore:
sudo pip install boto
Args:
annot_uuid_list (list of str) : list of annot UUIDs to be used in IBEIS IA
part_uuid_list (list o... | 78,577 |
def haskell_nixpkgs_packageset(name, base_attribute_path, repositories = {}, **kwargs):
"""Import all the available haskell packages.
The arguments are the same as the arguments of ``nixpkgs_package``, except
for the ``base_attribute_path`` which should point to an `haskellPackages`
set in the nix expre... | 78,578 |
def single_re_sub_empty_test():
"""A function without arguments, needed for timeit.
NB: uses global variable text to solve the argument problem"""
return single_re_sub_empty(text, repl_chars) | 78,579 |
def A_STAR(global_map, start, end, Type = '8c',e = 1, heuristic = 'eu' ):
"""
Implements A* Algorithm for the Given Grid Map
Arguments:
global_map - np.array()
start - start location [x,y]
end - end location [x,y]
Type - Type of Neibhours ('8c' or '4c')
e - Heurestic Factor
heuristic... | 78,580 |
def test_missing_image():
"""
Confirm that we get a -1 result for a missing image.
"""
image_data = CACHE.get('missing')
assert image_data == -1 | 78,581 |
def main(argv):
"""Builds, trains, and evaluates the model."""
args = parser.parse_args(argv[1:])
(train_x,train_y), (test_x, test_y) = automobile_data.load_data()
train_y /= args.price_norm_factor
test_y /= args.price_norm_factor
# Provide the training input dataset.
train_input_fn = automobile_data.m... | 78,582 |
def resetOptions():
""" Reset options to their default values. """
global options
defaultOptions = {
'inputEncoding' : 'utf-8', # default input encoding for strings
'outputEncoding' : 'utf-8', # default output encoding
'substituteChar' : '?', # use to substitute unrecognised charact... | 78,583 |
def test_callback_inheritance():
"""Check inheritance of dispatcher callbacks.
* Inheriting from a dispatcher gives access to its callbacks.
* Inherited callbacks can be overloaded.
* Overloading a callback doesn't affect the base dispatcher.
"""
base = Base()
spec = Specialized()
keys... | 78,584 |
def create_templates(filename):
"""Create templates with the service."""
data_to_use = _load_json(filename)
service = current_records_marc21.templates_service
templates = []
for data in data_to_use:
template = service.create(data=data["values"], name=data["name"])
templates.append(t... | 78,585 |
def test_approvals_fp():
"""Verify that FP tags get transformed, but only if they match a
certain string"""
with XMLBuilder("PART") as ctx:
ctx.APPRO(_control_number('1111-2222'))
ctx.FP("Something else")
ctx.FP(_control_number('2222-4444'))
ctx.P(_control_number('3333-6666')... | 78,586 |
def coherence_limit(nQ=2, T1_list=None, T2_list=None,
gatelen=0.1):
"""
The error per gate (1-average_gate_fidelity) given by the T1,T2 limit.
Args:
nQ: number of qubits (1 and 2 supported).
T1_list: list of T1's (Q1,...,Qn).
T2_list: list of T2's (as measured, ... | 78,587 |
def connection_from_list_slice(
list_slice: Sequence,
args: ConnectionArguments = None,
connection_type: ConnectionConstructor = Connection,
edge_type: EdgeConstructor = Edge,
pageinfo_type: PageInfoConstructor = PageInfo,
slice_start=0,
list_length=0,
list_slice_length=None,
) -> Connec... | 78,588 |
def logp_model(residuals, params_nodes, Pk, Variance, distribution_parameters):
"""returns -2log p of residuals"""
Pk_double = np.concatenate((Pk, Pk))
return 2*np.sum(np.square(params_nodes) / Pk_double) + negative_2loglikelihood(residuals, Variance, distribution_parameters) | 78,589 |
def _loadParamFromFile(config, section, paramName):
"""
read param from file
validate it
and load to to global conf dict
"""
# Get paramName from answer file
value = config.get(section, paramName)
# Validate param value using its validation func
param = controller.getParamByName(pa... | 78,590 |
def plotcross(a,val=[0,0,0],hard=None,sum=True) :
""" plot cross sections of input 3D grid of synthetic spectra
Args:
a : input HDU with synthetic spectral grid
val : 3 ([M/H], logg, Teff) grid indices to use when varying other dimensions (default=[0,0,0])
"""
dim=a.data.shap... | 78,591 |
def nonConv(wSpace, pts, val= -100, vis= False, img_name= 'img'):
"""This function takes in list of convex shapes with there points list for each shape
and the union of these shapes will give us the desired nonConvex shape"""
convPts = []
ctr=0
for conv in pts:
ctr+=1
wSpace1 = convPolygon(wSpace, conv, vis=... | 78,592 |
def restart_run(db) -> list:
"""When restarting a hash run, identify which files need to be skipped from the
database
Args:
db (TinyDB database): A TinyDB database objects containing filepaths and hashes
of the search so far
"""
logger.info("Restarting hashing process")
retu... | 78,593 |
def votes_per_month(values: Dict[str, List[str] | Tuple[str]]) -> Dict[str, Dict[str, int]]:
"""
:param values: a dictionary formatted like: {month: list of votes}
:returns: dictionary every person for every month
"""
all_persons = set([person.lower().replace(" ", "") for element in values.values() ... | 78,594 |
def CalculationElement(curr_doc, elementlist):
"""
:param elementlist: list of all elements
:return:
all_functions: [[functions of elements 1][functions of element 2]...[functions of element n]]
--> order of functions: N, u, Q, M, w, phi
x: Symbol to plot over
l_list: lis... | 78,595 |
def adjacency2digraph(
adj_matrix: np.ndarray,
similar_this_dgraph: nx.DiGraph = None) -> nx.DiGraph:
"""Converts the adjacency matrix to directed graph.
If similar_this_graph is given, then the final directed graph has the same
node labeling as the given graph has.
Using dgraph2adjacen... | 78,596 |
def make_list_equal(lhs: list, rhs: list, pad_element: str = '') -> None:
""" Make two vector of string equation in length by padding with `pad_element`
Parameters
----------
lhs : list
2 vectors of string to be made equal in length
rhs : list
2 vectors of string to be made equal in... | 78,597 |
def test_initialization(pro):
"""
Ertu hress?
"""
assert pro.comm.project.inversion_root == pro.root_folder
assert os.path.exists(
os.path.join(pro.comm.project.inversion_root, "DOCUMENTATION")
)
assert os.path.exists(
os.path.join(pro.comm.project.inversion_root, "DOCUMENTAT... | 78,598 |
def move_cursor(move):
"""Return move value for cursor."""
return {
'left': -1,
'right': 1,
}[move] | 78,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.