content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def get_dataset(dataset_id: Optional[str] = None,
location: Optional[str] = None,
project: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetDatasetResult:
"""
Gets any metadata associated with a dataset.
"""
__args__ = dict... | 10,200 |
def is_email_available() -> bool:
"""
Returns whether email services are available on this instance (i.e. settings are in place).
"""
return bool(settings.EMAIL_HOST) | 10,201 |
def open_link(url):
"""
Takes a QtCore.QUrl
"""
ok = QtGui.QDesktopServices.openUrl(url)
if (not ok):
detail = ["Could not find location:", unicode(url.toString())]
Error.show_error("Failed to open URL", "\n\n".join(detail)) | 10,202 |
def sql2label(sql, num_cols):
"""encode sql"""
# because of classification task, label is from 0
# so sel_num and cond_num should -1,and label should +1 in prediction phrase
cond_conn_op_label = sql.cond_conn_op
sel_num_label = sql.sel_num - 1
# the new dataset has cond_num = 0, do not -1
c... | 10,203 |
def retrieveToken(verbose: bool = False, save: bool = False, **kwargs)->str:
"""
LEGACY retrieve token directly following the importConfigFile or Configure method.
"""
token_with_expiry = token_provider.get_token_and_expiry_for_config(config.config_object,**kwargs)
token = token_with_expiry['token']... | 10,204 |
def format_str_for_write(input_str: str) -> bytes:
"""Format a string for writing to SteamVR's stream."""
if len(input_str) < 1:
return "".encode("utf-8")
if input_str[-1] != "\n":
return (input_str + "\n").encode("utf-8")
return input_str.encode("utf-8") | 10,205 |
def do(createMap=False):
"""
creates maps for all recorded experiments
:param createMap:
:return:
"""
experimentLog = Experiments.getExperimentLog()
for log in experimentLog:
exp = Experiments()
exp.package = log[0]
exp.time = log[1]
exp.test_case = log[2]
... | 10,206 |
def reverse_result(func):
"""The recursive function `get_path` returns results in order reversed
from desired. This decorator just reverses those results before returning
them to caller.
"""
@wraps(func)
def inner(*args, **kwargs):
result = func(*args, **kwargs)
if result is not ... | 10,207 |
def convert_from_opencorpora_tag(to_ud, tag: str, text: str):
"""
Конвертировать теги их формата OpenCorpora в Universal Dependencies
:param to_ud: конвертер.
:param tag: тег в OpenCorpora.
:param text: токен.
:return: тег в UD.
"""
ud_tag = to_ud(str(tag), text)
pos = ud_tag.sp... | 10,208 |
def reg_to_float(reg):
"""convert reg value to Python float"""
st = struct.pack(">L", reg)
return struct.unpack(">f", st)[0] | 10,209 |
def wvelocity(grid, u, v, zeta=0):
"""
Compute "true" vertical velocity
Parameters
----------
grid : seapy.model.grid,
The grid to use for the calculations
u : ndarray,
The u-field in time
v : ndarray,
The v-field in time
zeta : ndarray, optional,
The zeta-field ... | 10,210 |
def test_bltz():
"""Test the bgtz instruction."""
bltz_regex = Instructions["bltz"].regex
assert re.match(bltz_regex, "bltz $zero, $t1, label") is None
assert re.match(bltz_regex, "bltz $zero, label") is not None
assert re.match(bltz_regex, "bltz $zero") is None
assert re.match(bltz_regex, "bltz... | 10,211 |
def _as_nested_lists(vertices):
""" Convert a nested structure such as an ndarray into a list of lists. """
out = []
for part in vertices:
if hasattr(part[0], "__iter__"):
verts = _as_nested_lists(part)
out.append(verts)
else:
out.append(list(part))
re... | 10,212 |
def test_aspect_ratio(DSHAPE):
"""Tests aspect ratio computation."""
# VMEC value
file = Dataset(str(DSHAPE["vmec_nc_path"]), mode="r")
AR_vmec = float(file.variables["aspect"][-1])
file.close
# DESC value
eq = EquilibriaFamily.load(load_from=str(DSHAPE["desc_h5_path"]))[-1]
AR_desc = ... | 10,213 |
def markdown(code: str) -> str:
"""Convert markdown to HTML using markdown2."""
return markdown2.markdown(code, extras=markdown_extensions) | 10,214 |
async def post_notification(request):
"""
Create a new notification to run a specific plugin
:Example:
curl -X POST http://localhost:8081/fledge/notification -d '{"name": "Test Notification", "description":"Test Notification", "rule": "threshold", "channel": "email", "notification_type": "one ... | 10,215 |
def test_send_file_to_router(monkeypatch, capsys):
"""
.
"""
# pylint: disable=unused-argument
@counter_wrapper
def get_commands(*args, **kwargs):
"""
.
"""
return "commands"
@counter_wrapper
def add_log(log: Log, cursor=None):
"""
.
... | 10,216 |
def sem_get(epc):
"""プロパティ値要求 'Get' """
global tid_counter
frame = sem.GET_FRAME_DICT['get_' + epc]
tid_counter = tid_counter + 1 if tid_counter + 1 != 65536 else 0 # TICカウントアップ
frame = sem.change_tid_frame(tid_counter, frame)
res = y3.udp_send(1, ip6, True, y3.Y3_UDP_ECHONET_PORT, frame) | 10,217 |
def serialize_entities_graph(graph: GeNeG):
""" Serialize the complete entity graph as individual files. """
utils.get_logger().info('GeNeG: Serializing the entity graph as individual files..')
_write_lines_to_file(_get_lines_metadata(graph), 'results.geneg_entities.metadata')
_write_lines_to_file(_get... | 10,218 |
def smiles2mol(smiles):
"""Convert SMILES string into rdkit.Chem.rdchem.Mol.
Args:
smiles: str, a SMILES string.
Returns:
mol: rdkit.Chem.rdchem.Mol
"""
smiles = canonicalize(smiles)
mol = Chem.MolFromSmiles(smiles)
if mol is None:
return None
Chem.Kekulize(mol)
... | 10,219 |
def parallel_execute(objects, func, get_name, msg, get_deps=None):
"""Runs func on objects in parallel while ensuring that func is
ran on object only after it is ran on all its dependencies.
get_deps called on object must return a collection with its dependencies.
get_name called on object must return ... | 10,220 |
def process_config(config_path, script_dir):
"""Process the users config file and set defaults.
Processing of user config file, setting defaults, printing overview
and write processed config parameters to temporary config file
Args:
config_path(str): path to user config file
script_dir(str... | 10,221 |
def build_term_map(deg, blocklen):
"""
Builds term map (degree, index) -> term
:param deg:
:param blocklen:
:return:
"""
term_map = [[0] * comb(blocklen, x, True) for x in range(deg + 1)]
for dg in range(1, deg + 1):
for idx, x in enumerate(term_generator(dg, blocklen - 1)):
... | 10,222 |
def gen_sets():
"""
List of names of all available problem generators
"""
return registered_gens.keys() | 10,223 |
async def _ensure_system_is(status: TecStatus) -> None:
"""Ensure that the TEC subsystem status is `status` and raise otherwise.
:raises TecStatusError: System is not `status`.
"""
tec_status = await get_tec_status() # type: TecStatus
if tec_status != status:
raise TecStatusError(
... | 10,224 |
def is_valid_currency(currency_: str) -> bool:
"""
is_valid_currency:判断给定货币是否有效
@currency_(str):货币代码
return(bool):FROM_CNY、TO_CNY均有currency_记录
"""
return currency_ in FROM_CNY and currency_ in TO_CNY | 10,225 |
def load_gene_prefixes() -> List[Tuple[str, str, str]]:
"""Returns FamPlex gene prefixes as a list of rows
Returns
-------
list
List of lists corresponding to rows in gene_prefixes.csv. Each row has
three columns [Pattern, Category, Notes].
"""
return _load_csv(GENE_PREFIXES_PAT... | 10,226 |
def create_page_panels_base(num_panels=0,
layout_type=None,
type_choice=None,
page_name=None):
"""
This function creates the base panels for one page
it specifies how a page should be layed out and
how many panels should... | 10,227 |
def uri2dict(uri):
"""Take a license uri and convert it into a dictionary of values."""
if uri.startswith(LICENSES_BASE) and uri.endswith('/'):
base = LICENSES_BASE
license_info = {}
raw_info = uri[len(base):]
raw_info = raw_info.rstrip('/')
info_list = raw_info.split('... | 10,228 |
def Reboot() -> None:
"""Reboots the device"""
try:
_MPuLib.Reboot.restype = c_int32
CTS3Exception._check_error(_MPuLib.Reboot())
finally:
CloseCommunication() | 10,229 |
def test_clean_str(text, language='english'):
"""
Method to pre-process an text for training word embeddings.
This is post by Sebastian Ruder: https://s3.amazonaws.com/aylien-main/data/multilingual-embeddings/preprocess.py
and is used at this paper: https://arxiv.org/pdf/1609.02745.pdf
"""
... | 10,230 |
def plot_wpm(output):
"""Reads `output` and plots typing speeds uniformly apart.
Adds a trendline.
"""
df = pd.read_csv(
output,
header=None,
names=["timestamp", "wpm", "accuracy", "actual_duration", "duration", "hash"],
)
if len(df) < 2:
print(
"More... | 10,231 |
def run_venv_script(venv, script, fLOG=None,
file=False, is_cmd=False,
skip_err_if=None, platform=None,
**kwargs): # pragma: no cover
"""
Runs a script on a vritual environment (the script should be simple).
@param venv virtual enviro... | 10,232 |
def calc_iou(boxes1, boxes2, scope='iou'):
"""calculate ious
Args:
boxes1: 5-D tensor [BATCH_SIZE, CELL_SIZE, CELL_SIZE, BOXES_PER_CELL, 4] ====> (x_center, y_center, w, h)
boxes2: 5-D tensor [BATCH_SIZE, CELL_SIZE, CELL_SIZE, BOXES_PER_CELL, 4] ===> (x_center, y_center, w, h)
Return:
iou... | 10,233 |
def not_before(cert):
"""
Gets the naive datetime of the certificates 'not_before' field.
This field denotes the first date in time which the given certificate
is valid.
:param cert:
:return: Datetime
"""
return cert.not_valid_before | 10,234 |
def get_data_from_dict_for_2pttype(type1,type2,datadict):
"""
Given strings identifying the type of 2pt data in a fits file
and a dictionary of 2pt data (i.e. the blinding factors),
returns the data from the dictionary matching those types.
"""
#spectra type codes in fits file, under hdutable... | 10,235 |
def simple_unweighted_distance(g, source, return_as_dicts=True):
"""Returns the unweighted shortest path length between nodes and source."""
dist_dict = nx.shortest_path_length(g, source)
if return_as_dicts:
return dist_dict
else:
return np.fromiter((dist_dict[ni] for ni in g), dtype=in... | 10,236 |
def A070939(i: int = 0) -> int:
"""Length of binary representation of n."""
return len(f"{i:b}") | 10,237 |
def feed_pump(pin: int, water_supply_time: int=FEED_PUMP_DEFAULT_TIME) -> bool:
"""
feed water
Parameters
----------
pin : int
target gpio (BCM)
water_supply_time : int
water feeding time
Returns
-------
bool
Was water feeding successful ?
"""
is... | 10,238 |
def add_player(url):
"""Add a player to the sc2monitor by Battl.net URL."""
kwargs = {}
kwargs['db'] = '{protocol}://{user}:{passwd}@{host}/{db}'.format(
**db_credentials)
controller = Controller(**kwargs)
controller.add_player(url=url) | 10,239 |
def app_nav(context):
"""Renders the main nav, topnav on desktop, sidenav on mobile"""
url_name = get_url_name(context)
namespace = get_namespace(context)
cache_id = "{}:{}x".format(context['request'].user.username, context.request.path)
cache_key = make_template_fragment_key('app_nav', [cache_id])... | 10,240 |
def centre_to_zeroes(cartesian_point, centre_point):
"""Converts centre-based coordinates to be in relation to the (0,0) point.
PIL likes to do things based on (0,0), and in this project I'd like to keep
the origin at the centre point.
Parameters
----------
cartesian_point : (numeric)
... | 10,241 |
def check_write_defaults(querier, varenv):
"""
It is painful to deal with $user, $permission, $authority and $attribution
all the time, so this function verifies them and the sets them to member
variables.
"""
if not varenv.get_user_guid():
raise MQLAccessError(
None, 'You must specify ... | 10,242 |
def get_all_stack_names(cf_client=boto3.client("cloudformation")):
"""
Get all stack names
Args:
cf_client: boto3 CF client
Returns: list of StackName
"""
LOGGER.info("Attempting to retrieve stack information")
response = cf_client.describe_stacks()
LOGGER.info("Retrieved stack... | 10,243 |
def match_date(date, date_pattern):
"""
Match a specific date, a four-tuple with no special values, with a date
pattern, four-tuple possibly having special values.
"""
# unpack the date and pattern
year, month, day, day_of_week = date
year_p, month_p, day_p, day_of_week_p = date_pattern
... | 10,244 |
def get_heating_features(df, fine_grained_HP_types=False):
"""Get heating type category based on HEATING_TYPE category.
heating_system: heat pump, boiler, community scheme etc.
heating_source: oil, gas, LPC, electric.
Parameters
----------
df : pandas.DataFrame
Dataframe that is updated... | 10,245 |
def integrate_eom(initial_conditions, t_span, design_params, SRM1, SRM2):
"""Numerically integrates the zero gravity equations of motion.
Args:
initial_conditions (np.array()): Array of initial conditions. Typically set
to an array of zeros.
t_span (np.array()): Time vector (s) over whi... | 10,246 |
def activation_sparse(net, transformer, images_files):
"""
Activation bottom/top blob sparse analyze
Args:
net: the instance of Caffe inference
transformer:
images_files: sparse dataset
Returns:
none
"""
print("\nAnalyze the sparse info of the Activation:")... | 10,247 |
def save(obr, destination=False):
"""Save the current state of the image."""
if destination:
obr.save(destination)
else:
main = Tk()
filename = asksaveasfilename(initialfile="image", defaultextension=".jpg", filetypes=[
("JPEG", ".jpg"), ("PNG", "... | 10,248 |
def cfg_load(filename):
"""Load a config yaml file."""
return omegaconf2namespace(OmegaConf.load(filename)) | 10,249 |
def char_to_num(x: str) -> int:
"""Converts a character to a number
:param x: Character
:type x: str
:return: Corresponding number
:rtype: int
"""
total = 0
for i in range(len(x)):
total += (ord(x[::-1][i]) - 64) * (26 ** i)
return total | 10,250 |
def time_it(f: Callable):
"""
Timer decorator: shows how long execution of function took.
:param f: function to measure
:return: /
"""
def timed(*args, **kwargs):
t1 = time.time()
res = f(*args, **kwargs)
t2 = time.time()
log("\'", f.__name__, "\' took ", round(... | 10,251 |
def has_prefix(sub_s, dictionary):
"""
:param sub_s: (str) A substring that is constructed by neighboring letters on a 4x4 square grid
:return: (bool) If there is any words with prefix stored in sub_s
"""
s = ''
for letter in sub_s:
s += letter
for words in dictionary:
if words.startswith(s):
return True
... | 10,252 |
def search_paths_for_executables(*path_hints):
"""Given a list of path hints returns a list of paths where
to search for an executable.
Args:
*path_hints (list of paths): list of paths taken into
consideration for a search
Returns:
A list containing the real path of every e... | 10,253 |
def tf_center_crop(images, sides):
"""Crops central region"""
images_shape = tf.shape(images)
top = (images_shape[1] - sides[0]) // 2
left = (images_shape[2] - sides[1]) // 2
return tf.image.crop_to_bounding_box(images, top, left, sides[0], sides[1]) | 10,254 |
def get_video_features(image_volume, occlusion_volume, max_level, file):
"""
this function retrieves a spatio-temporal pyramid of features
for the purpose of video inpainting
:param image_volume:
:param occlusion_volume:
:param max_level:
:param file:
:return: feature pyramid
"""
... | 10,255 |
def convert_timezone(time_in: datetime.datetime) -> datetime.datetime:
"""
用来将系统自动生成的datetime格式的utc时区时间转化为本地时间
:param time_in: datetime.datetime格式的utc时间
:return:输出仍旧是datetime.datetime格式,但已经转换为本地时间
"""
time_utc = time_in.replace(tzinfo=pytz.timezone("UTC"))
time_local = time_utc.astimezone(py... | 10,256 |
def gpupdate_install():
""" Install the Update Tool. """
file = '\\gpupdate.zip'
url = SERVER + '/GPU/gpupdate.zip'
download(url, file)
unzip(file, 'GPUpdate')
return | 10,257 |
def add_aws_cluster(name, cluster):
"""Add an aws cluster to config."""
config = get_config()
config.set("general", "provider", "gke")
config.set("aws", "current-cluster", name)
section = "aws.{}".format(name)
if not config.has_section(section):
config.add_section(section)
config... | 10,258 |
def convert_bool(
key: str, val: bool, attr_type: bool, attr: dict[str, Any] = {}, cdata: bool = False
) -> str:
"""Converts a boolean into an XML element"""
if DEBUGMODE: # pragma: no cover
LOG.info(
f'Inside convert_bool(): key="{str(key)}", val="{str(val)}", type(val) is: "{type(val)... | 10,259 |
def plot_model(model,
to_file='model.png',
show_shapes=False,
show_dtype=False,
show_layer_names=True,
rankdir='TB',
expand_nested=False,
dpi=96,
layer_range=None,
show_layer_activation... | 10,260 |
def catalog_info(EPIC_ID=None, TIC_ID=None, KIC_ID=None):
"""Takes EPIC ID, returns limb darkening parameters u (linear) and
a,b (quadratic), and stellar parameters. Values are pulled for minimum
absolute deviation between given/catalog Teff and logg. Data are from:
- K2 Ecliptic Plane Input... | 10,261 |
def classifier_fn_from_tfhub(output_fields, inception_model, return_tensor=False):
"""Returns a function that can be as a classifier function.
Copied from tfgan but avoid loading the model each time calling _classifier_fn
Args:
output_fields: A string, list, or `None`. If present, assume the module
... | 10,262 |
def get_rate_limit(client):
"""
Get the Github API rate limit current state for the used token
"""
query = '''query {
rateLimit {
limit
remaining
resetAt
}
}'''
response = client.execute(query)
json_response = json.loads(response)
retur... | 10,263 |
def dns(args):
"""Create/Delete dns entries"""
delete = args.delete
name = args.name
net = args.net
domain = net
ip = args.ip
config = Kconfig(client=args.client, debug=args.debug, region=args.region, zone=args.zone, namespace=args.namespace)
k = config.k
if delete:
if config... | 10,264 |
def pret(f):
"""
Decorator which prints the result returned by `f`.
>>> @pret
... def f(x, y): return {'sum': x + y, 'prod': x * y}
>>> res = f(2, 3)
==> @pret(f) -- {'prod': 6, 'sum': 5}
"""
@functools.wraps(f)
def g(*args, **kwargs):
ret = f(*args, **kwargs)
... | 10,265 |
def parse_arguments() -> tuple[str, str, bool]:
"""Return the command line arguments."""
current_version = get_version()
description = f"Release Quality-time. Current version is {current_version}."
epilog = """preconditions for release:
- the current folder is the release folder
- the current branch... | 10,266 |
def test_empty_conf():
"""Test to check an unexiting path"""
with pytest.raises(Exception):
ConfUltimate.load([]) | 10,267 |
def toggle(knob):
""" "Inverts" some flags on the selected nodes.
What this really does is set all of them to the same value, by finding the
majority value and using the inverse of that."""
value = 0
n = nuke.selectedNodes()
for i in n:
try:
val = i.knob(knob).value()
if val:
value... | 10,268 |
def process_submission(problem_id: str, participant_id: str, file_type: str,
submission_file: InMemoryUploadedFile,
timestamp: str) -> STATUS_AND_OPT_ERROR_T:
"""
Function to process a new :class:`~judge.models.Submission` for a problem by a participant.
:param... | 10,269 |
def eq_text_partially_marked(
ann_objs,
restrict_types=None,
ignore_types=None,
nested_types=None):
"""Searches for spans that match in string content but are not all
marked."""
# treat None and empty list uniformly
restrict_types = [] if restrict_types is None else rest... | 10,270 |
def wait_for_status(status_key, status, get_client, object_id,
interval: tobiko.Seconds = None,
timeout: tobiko.Seconds = None,
error_ok=False, **kwargs):
"""Waits for an object to reach a specific status.
:param status_key: The key of the status fiel... | 10,271 |
def can_hold_bags(rule: str, bag_rules: dict) -> dict:
"""
Returns a dict of all bags that can be held by given bag color
:param rule: Color of a given bag
:param bag_rules: Dictionary of rules
:type rule: str
:type bag_rules: dict
:return:
"""
return bag_rules[rule] | 10,272 |
def eWriteNameArray(handle, name, numValues, aValues):
"""Performs Modbus operations that writes values to a device.
Args:
handle: A valid handle to an open device.
name: The register name to write an array to.
numValues: The size of the array to write.
aValues: List of v... | 10,273 |
def fix_levers_on_same_level(same_level, above_level):
"""
Input: 3D numpy array with malmo_object_to_index mapping
Returns:
3D numpy array where 3 channels represent
object index, color index, state index
for minigrid
"""
lever_idx = malmo_object_to_index['lever']
con... | 10,274 |
def test_words():
"""Tests basic functionality of word segmentation."""
language = common.Common
words = language.words(u"")
assert words == []
words = language.words(u"test sentence.")
assert words == [u"test", u"sentence"]
# Let's test Khmer with zero width space (\u200b)
words = lan... | 10,275 |
def persist_to_json_file(activations, filename):
"""
Persist the activations to the disk
:param activations: activations (dict mapping layers)
:param filename: output filename (JSON format)
:return: None
"""
with open(filename, 'w') as w:
json.dump(fp=w, obj=OrderedDict({k: v.tolist(... | 10,276 |
def iv_plot(df, var_name=None, suffix='_dev'):
"""Returns an IV plot for a specified variable"""
p_suffix = suffix.replace('_','').upper()
sub_df = df if var_name is None else df.loc[df.var_name==var_name, ['var_cuts_string'+suffix, 'ln_odds'+suffix, 'resp_rate'+suffix, 'iv'+suffix]]
sub_df['resp_rate_t... | 10,277 |
def is_alive(pid):
"""Return whether a process is running with the given PID."""
return LocalPath('/proc').join(str(pid)).isdir() | 10,278 |
def inheritable_thread_target(f: Callable) -> Callable:
"""
Return thread target wrapper which is recommended to be used in PySpark when the
pinned thread mode is enabled. The wrapper function, before calling original
thread target, it inherits the inheritable properties specific
to JVM thread such ... | 10,279 |
def build_grad(verts, edges, edge_tangent_vectors):
"""
Build a (V, V) complex sparse matrix grad operator. Given real inputs at vertices, produces a complex (vector value) at vertices giving the gradient. All values pointwise.
- edges: (2, E)
"""
edges_np = toNP(edges)
edge_tangent_vectors... | 10,280 |
def join_label_groups(grouped_issues, grouped_prs, issue_label_groups,
pr_label_groups):
"""Combine issue and PR groups in to one dictionary.
PR-only groups are added after all issue groups. Any groups that are
shared between issues and PRs are added according to the order in the
... | 10,281 |
def meth_browser(meth_data, window, gtf=False, bed=False, simplify=False,
split=False, outfile=None, dotsize=4, static=False, binary=False, minqual=20):
"""
meth_Data is a list of Methylation objects from the import_methylation submodule
annotation is optional and is a gtf or bed file
... | 10,282 |
def healpix_ijs_neighbours(istar, jstar, nside):
"""Gets the healpix i, jstar neighbours for a single healpix pixel.
Parameters
----------
istar : array
Healpix integer i star index.
jstar : array
Healpix integer i star index.
nside : int
Healpix nside.
Returns
... | 10,283 |
def micropub_blog_endpoint_POST(blog_name: str):
"""The POST verb for the micropub blog route
Used by clients to change content (CRUD operations on posts)
If this is a multipart/form-data request,
note that the multiple media items can be uploaded in one request,
and they should be sent with a `na... | 10,284 |
def create_parser(config: YAMLConfig) -> ArgumentParser:
"""
Automatically creates a parser from all of the values specified in a config
file. Will use the dot syntax for nested dictionaries.
Parameters
----------
config: YAMLConfig
Config object
Returns
-------
ArgumentPar... | 10,285 |
def detect_version(conn):
"""
Detect the version of the database. This is typically done by reading the
contents of the ``configuration`` table, but before that was added we can
guess a couple of versions based on what tables exist (or don't). Returns
``None`` if the database appears uninitialized, ... | 10,286 |
def nIonDotBHmodel2(z):
"""Ionization model 2 from BH2007: constant above z=6.
"""
return ((z < 6) * nIonDotLowz(z) +
(z >= 6) * nIonDotLowz(6)) | 10,287 |
def p_procedure(t):
"""
procedure : ID LPAREN procedure_expression_list RPAREN
| ID LPAREN RPAREN
"""
pass | 10,288 |
def answer(input):
"""
>>> answer("1234")
1234
"""
lines = input.split('\n')
for line in lines:
return int(line) | 10,289 |
def attach_model_to_base(
config: Configurator, ModelClass: type, Base: type, ignore_reattach: bool = True
):
"""Dynamically add a model to chosen SQLAlchemy Base class.
More flexibility is gained by not inheriting from SQLAlchemy declarative base
and instead plugging in models during the pyramid confi... | 10,290 |
def get_leading_states(contributions):
"""
Return state contributions, names as lists in descending order of contribution amount
:param contributions:
:return:
"""
contributions['state'] = contributions['clean_fips'].apply(get_state)
states = contributions.groupby('state')
state_sums = s... | 10,291 |
def convertFoot(tweakParameters, kneePosition, anklePosition, footPosition):
"""
This method takes the position of the foot guides coming out of the
embedding algorithm (knee, ankle and foot) and maps them to foot joints
that fits what HumanIK expects.
"""
pass | 10,292 |
def plot_lr(list_lr, list_steps):
"""
Utility function to track and plot learning rate
:param list_lr: list of learning rates tracked duriong training
:param list_steps: list of steps/iterations
:return:
"""
plt.figure(figsize=(8, 6))
plt.plot(list_steps, list_lr)
plt.titl... | 10,293 |
def contacts_per_person_normal_self_20():
"""
Real Name: b'contacts per person normal self 20'
Original Eqn: b'30'
Units: b'contact/Day'
Limits: (None, None)
Type: constant
b''
"""
return 30 | 10,294 |
def copy_file(src, dst):
"""
Tried to copy utf-8 text files line-by-line to avoid
getting CRLF characters added on Windows.
If the file fails to be decoded with utf-8, we revert to a regular copy.
"""
try:
with io.open(src, "r", encoding="utf-8") as fh_src:
with io.open(dst,... | 10,295 |
def __compute_partition_gradient(data, fit_intercept=True):
"""
Compute hetero regression gradient for:
gradient = ∑d*x, where d is fore_gradient which differ from different algorithm
Parameters
----------
data: DTable, include fore_gradient and features
fit_intercept: bool, if model has int... | 10,296 |
def calc_nsd(x, n=21):
"""
Estimate Noise Standard Deviation of Data.
Parameters
----------
x : 1d-ndarray
Input data.
n : int
Size of segment.
Returns
-------
result : float
Value of noise standard deviation.
"""
x_diff = np.diff(x, n=2)
x_frag ... | 10,297 |
def mixed_args(fixed1, fixed2, var1, var2, kwarg1=None, kwarg2=None):
""" Test function for mix of fixed and live args | str --> None
Copy paste following to test:
foo, bar, kwarg1 = barfoo, kwarg2 = foobar
"""
print('Builtin: ' + kwarg2 + ' ' + kwarg1 + ' ' + var2 + ' ' + var1 + ' ' +
fi... | 10,298 |
def deflection_from_kappa_grid_adaptive(kappa_high_res, grid_spacing, low_res_factor, high_res_kernel_size):
"""
deflection angles on the convergence grid with adaptive FFT
the computation is performed as a convolution of the Green's function with the convergence map using FFT
The grid is returned in th... | 10,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.