content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def _fix_filename(filename):
"""Return a filename which we can use to identify the file.
The file paths printed by llvm-cov take the form:
/path/to/repo/out/dir/../../src/filename.cpp
And then they're truncated to 22 characters with leading ellipses:
...../../src/filename.cpp
This makes it real... | 5,292,900 |
def topics(request):
"""Show all topics."""
topics = Topic.objects.order_by('date_added')
context = {'topics': topics}
return render(request, 'blogs/topics.html', context) | 5,292,901 |
def to_inport_xml(table, variables, project):
"""
Generate NMFS/FIS InPort XML Format document for DWSupport table
Document represents an Entity Insert if no table
inport_entity_id is available. If an inport_entity_id is available
the document will represent an Entity Update.
per: https://inpor... | 5,292,902 |
def PolsDeath(t):
"""Number of policies: Death override"""
return (PolsIF_Beg1(t) * asmp.BaseMortRate(AttAge(t))
* asmp.MortFactor(t) * MortRateFactor(t)) | 5,292,903 |
async def test_service_set_ac_start_simple(
hass: HomeAssistant, config_entry: ConfigEntry
):
"""Test that service invokes renault_api with correct data."""
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
temperature = 13.5
data = {
ATTR_V... | 5,292,904 |
def unflat_vecmap(func, unflat_items, vectorized=False, **kwargs):
"""unflat map for vectorized functions"""
import utool as ut
# First flatten the list, and remember the original dimensions
flat_items, reverse_list = ut.invertible_flatten2(unflat_items)
# Then preform the lookup / implicit mapping... | 5,292,905 |
def hrs_process(image_name, ampsec=[], oscansec=[], trimsec=[],
masterbias=None, error=False, bad_pixel_mask=None, flip=False,
rdnoise=None, oscan_median=True, oscan_model=None):
"""Processing required for HRS observations. If the images have multiple
amps, then this will pro... | 5,292,906 |
def label_allocation_method(data):
"""Add ``allocation method`` attribute to each dataset with the chosen allocation function."""
for ds in data:
ds['allocation method'] = choose_allocation_method(ds)
detailed.info({
'ds': ds,
'message': ds['allocation method'],
... | 5,292,907 |
def get_event(event_id):
"""
Get event by event_id
"""
for ec in (ActiveEvent, ArchivedEvent, FailedEvent):
e = ec.objects.filter(id=event_id).first()
if e:
return e
return None | 5,292,908 |
def test_multiple_epochs(carbon_synthetic_dataset, reader_factory):
"""Tests that multiple epochs works as expected"""
num_epochs = 5
with reader_factory(carbon_synthetic_dataset.url, num_epochs=num_epochs) as reader:
# Read all expected entries from the dataset and compare the data to reference
single_ep... | 5,292,909 |
def testFloat(val):
"""
Test value for float.
Used to detect use of variables, strings and none types, which cannot be checked.
"""
try:
return type(float(val)) == float
except Exception:
return False | 5,292,910 |
def _mpl_sp_kw_split(kwargs):
"""
Process keyword arguments supplied to a matplotlib plot function.
Returns
--------
:class:`tuple` ( :class:`dict`, :class:`dict` )
"""
sctr_kwargs = scatterkwargs(kwargs)
# c kwarg is first priority, if it isn't present, use the color arg
... | 5,292,911 |
def test_comparison_ops():
"""Test greater, lesser, equal"""
def test_ops(op_name, inputs, input_tensors, numpy_op):
outputs = [helper.make_tensor_value_info("output", TensorProto.FLOAT, shape=np.shape(inputs[0]))]
nodes = [helper.make_node(op_name, ["input"+str(i+1) for i in range(len(inputs))]... | 5,292,912 |
def disassemble_shcbin(binfile, objdumpcmd):
"""Extract a disassembly dump of a compiled shellcode binary file
Return a list of (bytes, instruction) tuples
"""
# Disassemble the .shcode code section
cmd = [objdumpcmd, '-d', '-j', '.shcode', binfile]
try:
output = subprocess.check_output(... | 5,292,913 |
def main(args: None):
"""
Process user arguments and render Control Tower manifest
Parameters:
args(dictionary): dicitonary of arguments
{"input_cf": PATH}
"""
if args:
output_manifest_file = os.path.join(args.output, "manifest.yaml")
default_region = args.default_region
... | 5,292,914 |
def test_create_fileinfos_list(test_dir, monkeypatch):
"""Create the archive from a list of FileInfo objects.
"""
monkeypatch.chdir(test_dir)
fileinfos = list(FileInfo.iterpaths([Path("base")], set()))
archive_path = Path("archive-fi-list.tar")
Archive().create(archive_path, "", fileinfos=filein... | 5,292,915 |
def send_most_optimal_runes_for(champion: str) -> None:
"""Function scrapes the best runes from u.gg for a provided champion and posts it to the LCU. In case of no
place for another rune page the first fetched rune page will be deleted and in its place the new one is added.
"""
runes = import_runes_for... | 5,292,916 |
def get_videos_page_url(url):
"""
Get a valid videos page URL from a YouTube channel/user URL. See
`Understand Your Channel URLs`_.
Args:
url (str): URL for a YouTube channel or user. The end of the URL may
contain extra parameters or a subpath to a different page on the
... | 5,292,917 |
def Xception65(params):
"""
Construct Xception network modified in DeepLabv3+
"""
return Xception(params) | 5,292,918 |
def generate_domain_csv(request):
"""
Generate a CSV file of the Domain information
:param request: The request for this CSV.
:type request: :class:`django.http.HttpRequest`
:returns: :class:`django.http.HttpResponse`
"""
response = csv_export(request,Domain)
return response | 5,292,919 |
def truthy(iterable):
"""Returns a iterable with only the truthy values.
Example::
truthy((0, 1, 2, False, None, True)) -> (1, 2, True)
:param iterable:
Iterable sequence.
:returns:
Iterable with truthy values.
"""
return select(bool, iterable) | 5,292,920 |
def get_file_list_match(file_list, match_string):
"""Get filenames containing the given match_string."""
match_list = []
for fid in file_list:
fid = str(fid) # MW: To also allow fid to be of type pathlib.Path
if fnmatch(fid, match_string):
match_list.append(fid)
return mat... | 5,292,921 |
def test_construct_from_dict() -> None:
"""Test that manifest can be constructed from dictionary."""
manifest = Manifest(DICTIONARY_MANIFEST)
assert manifest.version == 0
assert len(manifest.projects) == 1
assert manifest.projects[0].name == "my-project"
assert len(manifest._remotes) == 1
a... | 5,292,922 |
def alpha(S,T,P=0):
"""Compute thermal expansion coefficient
Usage: alpha(S, T, [P])
Input:
S = Salinity, [PSS-78]
T = Temperature, [�C]
P = Pressure, [dbar]
P is optional, with a default value = zero
Output:
Thermal expansion coefficient, [1/K]
"""
... | 5,292,923 |
def iterate_value_v_pi(
agent: MdpAgent,
environment: ModelBasedMdpEnvironment,
theta: float,
evaluation_iterations_per_improvement: int,
update_in_place: bool
) -> Dict[MdpState, float]:
"""
Run dynamic programming value iteration on an agent using state-value estimates.... | 5,292,924 |
def get_first_oembed_response(oembed_urls, max_width=None, max_height=None):
"""Fetches an OEmbed response from a list of OEmbed URLs. The URLs will be
tried in turn until one returns successfully.
:param oembed_urls: an iterable of OEmbed URLs.
:param max_width: (optional) the maximum width of the em... | 5,292,925 |
def display():
"""Build and render the status page."""
build_key = current_app.bert_e.settings.build_key
output_mode = request.args.get('output')
if output_mode is None:
output_mode = 'html'
current_job = current_app.bert_e.status.get('current job', None)
merged_prs = current_app.bert_e... | 5,292,926 |
def load_genre(metadata_path):
"""Load beatport_key genre data from a file
Args:
metadata_path (str): path to metadata annotation file
Returns:
(dict): with the list of strings with genres ['genres'] and list of strings with sub-genres ['sub_genres']
"""
if metadata_path is None:
... | 5,292,927 |
def transaction(callback, retry=None, entity_group=None, **ctx_options):
"""Run a callback in a transaction.
Args:
callback: A function or tasklet to be called.
retry: Optional retry count (keyword only; default set by
ndb.context.Context.transaction()).
entity_group: Optional root key to use as ... | 5,292,928 |
def _run_mailbox_simulator(address):
"""Runs the AWS SES mailbox-simulator see:
docs.aws.amazon.com/ses/latest/DeveloperGuide/mailbox-simulator.html
"""
options['recipients'] = [address]
return send_email(**options) | 5,292,929 |
def outliers(input):
"""
Extract index and values of outliers in input
Works with NaN values
:param input: vector data (signal)
:return: index, (whisker inf, sup)
"""
Quart = np.nanpercentile(input, [25, 75]) # 1er et 3ème quartile
IQuart = Quart[1] - Quart[0] # interquartil... | 5,292,930 |
def credits_in_subject(line, creditsInMatch):
"""
Parse string of type "x credits in/at/of subject"
Attributes
---------
line: str
pre-requisite string
creditMatch: str
used in regex expression to find if "x credits in/at/of subject" pattern is matched
Returns
-----... | 5,292,931 |
def choose_backup(backup_list, recovery_target_time):
""" pick up the latest backup file starting before time recovery_target_time"""
match_timestamp = match = None
for backup in backup_list:
last_modified = parse(backup['last_modified'])
if last_modified < recovery_target_time:
... | 5,292,932 |
def get_reverse(sequence):
"""Reverse orientation of `sequence`.
Returns a string with `sequence` in the reverse order.
If `sequence` is empty, an empty string is returned.
"""
#Convert all rna_sequence to upper case:
sequence=sequence.upper()
#reverse rna sequence:
rna_rev_list=sequen... | 5,292,933 |
def test_births():
"""Test module births.py by downloading
births.csv and testing shape of
extracted data has 7305 rows and 8 columns
"""
test_path = tempfile.mkdtemp()
x_train, metadata = births(test_path)
try:
assert x_train.shape == (7305, 8)
except:
shutil.rmtree(test_path)
raise() | 5,292,934 |
def is_gnome():
"""
Check if current DE is GNOME or not.
On Ubuntu 20.04, $XDG_CURRENT_DESKTOP = ubuntu:GNOME
On Fedora 34, $XDG_CURRENT_DESKTOP = GNOME
Hence we do the detection by looking for the word "gnome"
"""
return "gnome" in os.environ["XDG_CURRENT_DESKTOP"].lower() | 5,292,935 |
def attach_grad(tensor):
""" Attach gradients to the input tensor
"""
pass | 5,292,936 |
async def async_unload_entry(
hass: core.HomeAssistant, entry: config_entries.ConfigEntry
):
"""Unload a config entry."""
if entry.data[CONF_KEY] is not None:
platforms = GATEWAY_PLATFORMS
else:
platforms = GATEWAY_PLATFORMS_NO_KEY
unload_ok = await hass.config_entries.async_unload_... | 5,292,937 |
def guess_the_number(lowest_guess: int = 1, highest_guess: int = 10, *,
guess_limit: int = 3, is_basic: bool = False) -> None:
"""Starts the guess the number prompting
:param lowest_guess: Minimum possible number
:type lowest_guess: int
:param highest_guess: Maximum possible number... | 5,292,938 |
def get_trace_summaries(StartTime=None, EndTime=None, Sampling=None, FilterExpression=None, NextToken=None):
"""
Retrieves IDs and metadata for traces available for a specified time frame using an optional filter. To get the full traces, pass the trace IDs to BatchGetTraces .
See also: AWS API Documentation... | 5,292,939 |
def disable_cached_db_connections():
"""Disables cached database connections for this process and thread.
This function also removes any existing database connections that have been cached."""
with _global_db_cache_lock:
keys = list(_global_db_cache.keys())
for key in keys:
if... | 5,292,940 |
def raise_error(condition, msg):
"""raising error with a condition"""
if condition:
raise ValueError(msg) | 5,292,941 |
def nll_catogrical(preds, target, add_const=False):
"""compute the loglikelihood of discrete variables"""
total_loss = 0
for node_size in range(preds.size(1)):
total_loss += -(
torch.log(preds[:, node_size, target[:, node_size].long()])
* target[:, node_size]
).mean(... | 5,292,942 |
def test_sample_condition_2():
""" Test the experimental condition sampling -- onset = 0
"""
condition = ([0, 20, 36.5], [2, 2, 2], [1, 1, 1])
frame_times = np.linspace(0, 49, 50)
reg, rf = _sample_condition(condition, frame_times, oversampling=1,
min_onset=- 10)
... | 5,292,943 |
def robustfit(
X, y, weight_function="bisquare", tune=None, rcond=1, tol=0.001, maxit=50
):
"""
Multiple linear regression via iteratively reweighted least squares.
Parameters
----------
X : ndarray (n, p)
MLR model with `p` parameters (independent variables) at `n` times
y : ndarra... | 5,292,944 |
def to_xhr_response(request, non_xhr_result, form):
"""
Return an XHR response for the given ``form``, or ``non_xhr_result``.
If the given ``request`` is an XMLHttpRequest then return an XHR form
submission response for the given form (contains only the ``<form>``
element as an HTML snippet, not th... | 5,292,945 |
def set_organization_throttle():
"""Determine if organization should be throttled"""
# Currently throttling only happens if billing is enabled and user has free plan.
if settings.BILLING_ENABLED:
events_max = settings.BILLING_FREE_TIER_EVENTS
free_tier_organizations = get_free_tier_organizat... | 5,292,946 |
def tail_vertical(vehicle, wing, rudder_fraction=0.25):
""" Calculate the weight of the vertical fin of an aircraft without the weight of
the rudder and then calculate the weight of the rudder
Assumptions:
Vertical tail weight is the weight of the vertical fin without the rudder weight.
... | 5,292,947 |
def concat_recarrays(arr):
""" Concatenate two or more record arrays.
This increases the string field size to accommodate strings in all
the arrays, converting to a new dtype where necessary. The
original input arrays are not changed.
Parameters
----------
arr : sequence of Numpy record/st... | 5,292,948 |
def test_shape_grid_domain():
"""
"""
ddom = grid_domain_from_shape(shape)
assert_equal(np.sum(ddom.local_volume), np.prod(shape)) | 5,292,949 |
def get_config_files(
path: str,
) -> List[ConfigFile]:
"""
:param path: relative path to directory with files
:return:
"""
config_files: List[ConfigFile] = []
abs_path: Path = Path(path)
files: List[Path] = [abs_path.joinpath(f) for f in listdir(str(abs_path)) if isfile(str(abs_path.jo... | 5,292,950 |
def seasonStats(personId,type = 'gameLog',group = 'hitting'):
"""Returns a player's season/career stats and wether it's hitting or pitching or fielding
fix and improve this later"""
#playerInfo = get('people', {'personIds':personId})
teamStats = get('person',{ 'ver':'v1' , 'personId':personId,'h... | 5,292,951 |
def ensemble_address():
"""Zookeeper ensemble address
:return:
"""
zk_port = __pillar__['zookeeper']['port']
return '{0}:{1}'.format(':{0},'.format(zk_port).join(hosts()), zk_port) | 5,292,952 |
def STEL_methods(CASRN):
"""Return all methods available to obtain STEL for the desired chemical.
Parameters
----------
CASRN : str
CASRN, [-]
Returns
-------
methods : list[str]
Methods which can be used to obtain STEL with the given inputs.
See Also
--------
... | 5,292,953 |
def optional(converter):
"""
A converter that allows an attribute to be optional. An optional attribute
is one which can be set to ``None``.
:param callable converter: the converter that is used for non-``None``
values.
.. versionadded:: 17.1.0
"""
def optional_converter(val):
... | 5,292,954 |
def import_ids():
"""
1. Import the ids of the races on Wikidata and on the official site.
2. Import the qids of the mushers on Wikidata
"""
with open(root_dir + races_dir + 'finnmarkslopet-qid.csv', 'r') as csv_race_ids:
reader = csv.DictReader(csv_race_ids)
for row in reader:
race_qids[row['race']] = { 'r... | 5,292,955 |
def token_subject() -> str:
"""TODO."""
yield 'bar' | 5,292,956 |
def get_challenge_by_channel_id(database, challenge_channel_id):
"""
Fetch a Challenge object in the database with a given channel ID
Return the matching Challenge object if found, or None otherwise.
"""
ctfs = pickle.load(open(database, "rb"))
for ctf in ctfs:
for challenge in ctf.chall... | 5,292,957 |
def get_action(action):
"""Get action according to the action."""
return {
'create': create_issue,
'list': list_issues
}.get(action, create_issue) | 5,292,958 |
def combine_orderings(ordering_1, ordering_2):
"""
Function to combine two orderings.
Example 1:
ordering_1 = ((7,2), 'X')
ordering_2 = ((6,5),)
combined_ordering = ((7,2),(6,5))
Example 2:
ordering_1 = ((7,2), 'X', 'X')
ordering_2 = ((6,5), 'X')
combined_ordering = ((7,2),(6,5... | 5,292,959 |
def are_counts_even(env):
""" From dcicutils - to be ported over in this form at some point. """
try:
totals = get_metadata('/counts', ff_env=env)['db_es_total'].split()
except Exception:
# if we cant get counts page assume its False
return False, {}
# example value of split tot... | 5,292,960 |
def whoami_fn(request):
"""
Test-route to validate token and nickname from headers.
:return: welcome-dict
"""
nickname = request.validated["user"].nickname
return {
"status": "ok",
"nickname": nickname,
"message": "Hello " + nickname + ", nice to meet you."
} | 5,292,961 |
def sort_points_on_line(point_list):
""" Sorts points by distance on a line, taking the
two first points as the reference direction. """
point_list = [Coord(p[0], p[1]) for p in point_list]
p0 = point_list[0]
dx = point_list[1][0] - point_list[0][0]
dy = point_list[1][1] - point_list[0][1]
p... | 5,292,962 |
def save_tracks(input_tracks, out_filename):
"""Saves smoothed tracks to the specified file.
:param input_tracks: List of input tracks
:param out_filename: File to save tracks
"""
def _convert_track(input_track):
"""Converts event from internal representation to dict format
:param... | 5,292,963 |
def show_unconfirmed_users(args): # pylint: disable=unused-argument
"""Show users who haven't confirmed their email yet."""
session = session_for(**common.get_config())
LOG.debug("fetching unconfirmed accounts")
query = (
session.query(Users)
.filter(Users.confirmed_at == None) # py... | 5,292,964 |
def new(**kwargs):
"""Return a new instance of a BLAKE2s hash object.
:Keywords:
data : byte string
The very first chunk of the message to hash.
It is equivalent to an early call to `BLAKE2s_Hash.update()`.
digest_bytes : integer
The size of the digest, in bytes (1 to 32).
... | 5,292,965 |
def DTKN(token, wsL='', wsR=r'\s*'):
"""Syntactic Sugar for 'Series(Whitespace(wsL), DropText(token), Whitespace(wsR))'"""
return withWS(lambda: Drop(Text(token)), wsL, wsR) | 5,292,966 |
def remove_ngram(sentence, ngram_to_remove, n):
"""Removes all occurrences of an n-gram from a sentence.
:param sentence: The sentence.
:param ngram_to_remove: The n-gram that will be removed from the sentence.
:param n: The n in n-gram.
"""
# If the number of words in the sentence is < than th... | 5,292,967 |
def prepare_new_session():
"""
Prepares a new session for managing a user's interactions.
:return: Session ID as a string
"""
return session.create_new_session() | 5,292,968 |
def verificar(palavra, entrada):
"""
Confere se as tentativas do usuário estão corretas conforme a palavra sorteada.
Se não estiver, retorna à função principal e continua a iteração.
Entrada: palavra, entrada (string, input/string).
Saída: bool.
"""
return palavra == entrada | 5,292,969 |
def test_format_exception_should_format_method_not_allowed():
"""Should format the MethodNotAllowed Exception"""
exception = MethodNotAllowed()
statusCode, status, error_message = format_exception(exception)
assert statusCode == 405
assert status == 'Method Not Allowed'
assert error_message == ... | 5,292,970 |
def centeredMoment(moments, order):
"""
Compute a single moment of a specific order about the mean (centered)
given moments about the origin (raw).
:param moments: (list) First 'order' raw moments
:param order: (int) The order of the moment to calculate
"""
moment_c = 0 # first centered mo... | 5,292,971 |
def signal_periodic_impulse(period, phase):
"""Signal generator for periodic pulses
Parameters
----------
period : SignalUserTemplate
singal or constant describing the period in samples at which the pulses are generated
phase : SignalUserTemplate
singal or constant describing the p... | 5,292,972 |
def qstr(s, validate=True):
"""Return a quoted string after escaping '\' and '"' characters.
When validate is set to True (default), the string must consist only of
7-bit ASCII characters excluding NULL, CR, and LF.
"""
if validate:
s.encode('ascii')
if '\0' in s or '\r' in s or '\n' in s:
raise ValueError... | 5,292,973 |
def test_template_read_js(client):
""" test if JS loaded in templated with read """
resp = client.get('/read').data
assert b'Flask-gTTS failed to fetch TTS' in resp | 5,292,974 |
def record_expense(budget_id, date_incurred, description, amount, payment_id,
payee_id):
"""Inserts a new expense into the database."""
query = sqlalchemy.text("""
INSERT INTO budget_expenses
(budget_id, date_incurred, description, cost, payment_id, payee_id)
VALUES
((:b_id), (:d_inc), (:de... | 5,292,975 |
def random_permutation(iterable, r = None):
"""random_product(iterable, r = None) -> tuple
Arguments:
iterable: An iterable.
r(int): Size of the permutation. If :const:`None` select all elements in
`iterable`.
Returns:
A random element from ``itertools.permutations(iterable, r... | 5,292,976 |
def readconfig(filename='database.ini', section='py'):
"""Reads the config file for DB """
# create a parser
parser = ConfigParser()
# read config file
parser.read(filename)
# get section, default to postgresql
# Checks to see if section (postgresql) parser exists
if parser.has_section... | 5,292,977 |
def stringToAscii(sequence):
"""sequence is a sequence of characters.
Return the string with the hex representation for each character"""
return "".join("%02x" % ord(c) for c in sequence).upper() | 5,292,978 |
def get_version():
"""
Returns a PEP 386-compliant version number from VERSION.
"""
assert len(VERSION) == 5
assert VERSION[3] in ('alpha', 'beta', 'rc', 'final')
# Now build the two parts of the version number:
# main = X.Y[.Z]
# sub = .devN - for pre-alpha releases
# | {a|b|c... | 5,292,979 |
def fit_HH_x_single_layer(
damping_data_in_pct,
*,
use_scipy=True,
pop_size=800,
n_gen=100,
lower_bound_power=-4,
upper_bound_power=6,
eta=0.1,
seed=0,
show_fig=False,
verbose=False,
suppress_warnings=True,
parallel=... | 5,292,980 |
def get_int(dgram: bytes, start_index: int) -> Tuple[int, int]:
"""Get a 32-bit big-endian two's complement integer from the datagram.
Args:
dgram: A datagram packet.
start_index: An index where the integer starts in the datagram.
Returns:
A tuple containing the integer and the new end i... | 5,292,981 |
def test_arithmetic():
"""Cube class: tests arithmetic functions"""
cube1 = generate_cube(uwave=u.nm)
image1 = generate_image(wcs=cube1.wcs, unit=2 * u.ct)
spectrum1 = generate_spectrum(data=2.3, cdelt=30.0, crval=5)
cube2 = image1 + cube1
for op in (add, sub, mul, div):
cube3 = op(cube... | 5,292,982 |
def language_to_flag(code):
"""Generates css flag class for the language code"""
if code.lower() == 'en':
return 'flag-icon flag-icon-us'
return 'flag-icon flag-icon-' + code.lower() | 5,292,983 |
def get_file_id_of_media(message: 'Ubot .Message') -> Optional[str]:
""" get file_id """
file_ = message.audio or message.animation or message.photo \
or message.sticker or message.voice or message.video_note \
or message.video or message.document
if file_:
return file_.file_id
r... | 5,292,984 |
def parse(filepath:str, cpp_args:list):
"""
Parse c source file by pycparser, and return AST object.
"""
ast = parse_file(filepath, use_cpp=True,
cpp_path='gcc',
cpp_args=cpp_args)
return ast | 5,292,985 |
def grab(host):
""" """
for porta in (21, 22, 23, 25, 53, 80, 111, 10000, 445):
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((host, porta))
saida = sock.recv(1024)
# print('[i] bytes', len(saida))
if saida == 0... | 5,292,986 |
def setup_logging(logger, debug=False, color=True):
"""
Configure logging.
:param logger: Logger to configure.
:type logger: Logger
:param debug: If True - print debug messages
:param color: If True - print colored messages
"""
fmt_str = (
"%(asctime)s: %(levelname)s:"
... | 5,292,987 |
def make_polynomial_regression_data(n_data=100, degree=2, coefficients=None,
coefficient_scale=3.0, noise=0.1, x_range=(-1.0, 1.0), random_seed=None):
"""
It generates artificial data for linear regression
:param int n_data: Number of generated data
:param int degree: Degree of polynomial
:para... | 5,292,988 |
def add_percentage_value(l:int, to:List[list]) -> List[list]:
"""
counter.most_commonしたtaxonomyリストに割合を追加する
:param sids:
:param sto:
:return:
"""
for d in to:
d.append(d[2]/l)
return to | 5,292,989 |
def gru(inputs,targets,hprev):
"""
inputs and targets are both lists of integers.
hprev is Hx1 array of initial hidden state
returns the loss, gradients on model params and last hidden state
"""
x,r,i,h,h_hat,y,p = {},{},{},{},{},{},{}
#copy the hprev to last element of hs dict
h[-1] = ... | 5,292,990 |
def log(error_type, error_val, msg = True, time = True):
"""
Report the error type and optionally value and date
"""
config = configparser.ConfigParser()
config.read("config.ini")
fname = os.path.expanduser(config["Paths"]["logging_file"])
dologging = config["Options"].get... | 5,292,991 |
def run(*cohorts, **kwargs):
"""
Executes the workflow example shown in the corresponding
(notebook)[https://github.com/reactome-fi/workflows/blob/master/CytoscapeReactomeFI.ipynb].
This method generalizes the example for any two cohort
inputs and customized threshold options.
:param cohorts: t... | 5,292,992 |
def matching(acc, objectives=None, constraints=None,variables=None, covariables=None):
""" Performs the matching of optical functions using least squares.
variables : Must be a list of dictionaries with keys:
'elements': family name or list of indices of ring elements to be varied.
'separated':... | 5,292,993 |
def test_check_086():
""" METADATA.pb should contain at least "menu" and "latin" subsets. """
from fontbakery.specifications.googlefonts import (com_google_fonts_check_086 as check,
family_metadata)
# Let's start with the METADATA.pb file from our reference Fa... | 5,292,994 |
def parse_cmu(cmufh):
"""Parses an incoming file handle as a CMU pronouncing dictionary file.
(Most end-users of this module won't need to call this function explicitly,
as it's called internally by the :func:`init_cmu` function.)
:param cmufh: a filehandle with CMUdict-formatted data
:returns: a ... | 5,292,995 |
def apply_changes(lbl, chgtbl):
"""
Example of `chgtbl`:
chgtbl = [[1, 'AREALOAD', 1, 'PQ', 'REP', 1000.],
[1, 'AREALOAD', 2, 'PQ', 'REP', 600.],
[1, 'AREALOAD', 3, 'PQ', 'REP', 800.],
[2, 'GEN', 10, 'STATUS', 'REP', 0 ],
[2, ... | 5,292,996 |
def GetNextElement(op):
"""Returns the next material or shader after `op`."""
if not op:
return
if op.IsInstanceOf(c4d.Mmaterial) and op.GetFirstShader():
return op.GetFirstShader()
elif op.GetDown():
return op.GetDown()
while (not op.GetNext()) and op.GetUp():
op ... | 5,292,997 |
def test_filter_releases_by_target():
"""
Tests that all releases greater than the target gets correctly filtered out when using filter_releases_by_target.
"""
releases = [(7, 6), (7, 7), (7, 8), (7, 9), (8, 0), (8, 1), (8, 2), (8, 3), (9, 0), (9, 1)]
filtered_releases = filter_releases_by_target(re... | 5,292,998 |
def cli(
cls: str,
description: str,
default: list[str],
) -> dict[str, Any]:
"""Create CLI that loads kwargs from config files
Parameters
----------
cls: str
Class to be constructed from configuration parameters.
This is only used as a :code:`help` prompt.
description: ... | 5,292,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.