content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def compare_model(models_list=None, x_train=None, y_train=None, calculate_accuracy=False, scoring_metrics=None, scoring_cv=3, silenced=False):
"""
Trains multiple user-defined model and pass out report
Parameters
----------------
models_list: list
a list of models to be tra... | 49,000 |
def link_assets():
"""Load premade assets into blender. Then available via bpy.data."""
# starting from empty scene
# linking scenecity assets
bpy.ops.scene.sc_op_link_assets()
#bpy.ops.scene.sc_ot_append_template_cities()
# hide and disable render for assets
bpy.data.collections["Collection... | 49,001 |
def start(start_time: int = None):
"""Starts shepherd.
Writes 'start' to the 'state' sysfs attribute in order to transition from
'idle' to 'running' state. Optionally allows to start at a later point in
time, transitioning shepherd to 'armed' state.
Args:
start_time (int): Desired start ti... | 49,002 |
def Material (colorVector):
"""
Material color.
"""
if colorVector == None:
return None
else:
assert isinstance (colorVector, (list, tuple))
assert len (colorVector), 3
for cid in range (0, 3):
assert colorVector[cid] >= 0
assert colorVector[ci... | 49,003 |
def linear_objective(
weights: np.ndarray, samples: np.ndarray, labels: np.ndarray, loss_fn: Callable
) -> float:
"""Calculates the final loss objective for a linear model"""
# Compute scores for loss
z = (samples @ weights) * labels
# Mean loss over batch
loss = np.mean(loss_fn(z)).item()
r... | 49,004 |
def generate_html_jump(htmlfilename, projectname, css_filename, jumpinfos):
"""Generates an html file at filename that contains links
to all items in paths.
:param htmlfilename: Filename of the resultant file.
:param projectname: The name of the project metrics were generated for.
:param css_... | 49,005 |
def main(path_dataset, path_landmarks_out, path_landmarks_in, path_csv):
""" main entry point
:param str path_dataset: path to image dataset
:param str path_landmarks_out: path to landmarks dataset [output]
:param str path_landmarks_in: path to landmarks dataset [intput]
:param str path_csv: path t... | 49,006 |
def jpg_walk(path: str, filter_types: list) -> list:
"""
获取指导目录全部的图片路径
"""
with checkTimes("image walker"):
pools = list(
itertools.chain(
*[
list(pathlib.Path(path).glob(f"**/*.{types}"))
for types in filter_types
... | 49,007 |
def auto_border_start(min_corner_point, border_size):
"""Determine upper-right corner coords for auto border crop
:param min_corner_point: extreme corner component either 'min_x' or 'min_y'
:param border_size: min border_size determined by extreme_frame_corners in vidstab process
:return: adjusted extr... | 49,008 |
def val(model):
""" 计算模型在验证集上的分数 """
top_k = 3
# 状态置为验证
model.eval()
# 数据准备
dataset = ZhiHuData(conf.dev_data)
data_loader = DataLoader(dataset, batch_size=conf.batch_size)
# 预测
predict_label_and_marked_label_list = []
for i, batch in enumerate(data_loader):
title, conte... | 49,009 |
def regress_origin(x, y):
"""Returns coefficients to regression "y=ax+b" passing through origin.
Requires vectors x and y of same length.
See p. 351 of Zar (1999) Biostatistical Analysis.
returns slope, intercept as a tuple.
"""
x, y = array(x, "float64"), array(y, "float64")
return npsum(... | 49,010 |
def bootPropsConfig(artifact, resources, targetDir, scalaVersion = "2.13.1"):
"""Create the configuration to install an artifact and its dependencies"""
scala = {}
scala["version"] = scalaVersion
app = {}
app["org"] = artifact.org
app["name"] = artifact.name
app["version"] = artifact.versi... | 49,011 |
def broadcast_transaction(hex_tx, blockchain_client=BlockchainInfoClient()):
""" Dispatch a raw transaction to the network.
"""
url = BLOCKCHAIN_API_BASE_URL + '/pushtx'
payload = {'tx': hex_tx}
r = requests.post(url, data=payload, auth=blockchain_client.auth)
if 'submitted' in r.text.lower... | 49,012 |
def save_restart_data(sim, filename=None):
"""Given a simulation object, this function saves the current
magnetisation, and some integrator metadata into a file. """
# create metadata
integrator_stats = sim.integrator.stats()
datetimetuple = datetime.now()
drivertype = 'cvode' # we should dedu... | 49,013 |
def download_network_folder(network_path, local_path, user, password):
"""
Downloads the directory at network_path into local_path
The folder in local_path must not exist
"""
authenticate_network_resource(network_path, user, password)
shutil.copytree(network_path, local_path) | 49,014 |
def check_energies(input_file):
"""
check energies
"""
print("Checking for intermidiate energies in input file %s" % input_file)
f = None
try:
f = open(input_file, 'r')
except IOError:
print("Couldn't read from energy file %s" % input_file, file=sys.stderr)
input_lines ... | 49,015 |
def convert_BigWig2Wig(fname, path_to_binary=None):
""" uses the UCSC bigwigToWig to do the conversion, ready for reading """
tmp_path = tempfile.mkdtemp()
success=subprocess.check_call(["BigWig2Wig", fname,
"%s/out.wig" % tmp_path])
if success==0:
... | 49,016 |
def concat(inputs_list, axis=-1):
"""
Concatenate input tensors list
Parameters
----------
inputs_list: Input tensors list
axis: Axis along which to concatenate the tensors
"""
return tf.concat(inputs_list, axis=axis) | 49,017 |
def redirected_stdout(file: AnyTextIOType) -> Generator[TextIO, None, None]:
"""
ContextManager that redirects stdout to a given file-like object
and restores the original state when leaving the context
:param file: string or file-like object to redirect stdout to.
If passed a string, ... | 49,018 |
def string_to_tensor(string, char_list):
"""A helper function to create a target-tensor from a target-string
params:
string - the target-string
char_list - the ordered list of characters
output: a torch.tensor of shape (len(string)). The entries are the 1-shifted
indices of... | 49,019 |
def do_lock(
project: Project,
strategy: str = "all",
tracked_names: Iterable[str] | None = None,
requirements: list[Requirement] | None = None,
dry_run: bool = False,
) -> dict[str, Candidate]:
"""Performs the locking process and update lockfile."""
check_project_file(project)
# TODO: m... | 49,020 |
def unique_nrpzs_active_subquery():
"""Returns unique NRPZS within active centers."""
return db.session.query(OckovaciMisto.nrpzs_kod) \
.filter(OckovaciMisto.status == True) \
.group_by(OckovaciMisto.nrpzs_kod) \
.having(func.count(OckovaciMisto.nrpzs_kod) == 1) \
.subquery() | 49,021 |
def test_fail_handler_stoppipeline():
"""Failure handler with StopPipeline exits pypyr with no exception."""
pipename = 'errors/fail-handler-stoppipeline'
test_pipe_runner.assert_pipeline_notify_output_is(pipename, ['A']) | 49,022 |
def new_block(n):
"""Create a new block"""
sleep(0.25)
i = number_empty_block(n)
print (i)
if i > 1:
two_new_blocks(n)
elif i == 1:
one_new_block(n)
control_end(n)
set_pixels(n) | 49,023 |
def retrieve_context_service_interface_point_total_potential_capacity_total_size_total_size(uuid): # noqa: E501
"""Retrieve total-size
Retrieve operation of resource: total-size # noqa: E501
:param uuid: ID of uuid
:type uuid: str
:rtype: CapacityValue
"""
return 'do some magic!' | 49,024 |
def index():
""" Index page. """
return render_template('dashboard/index.html') | 49,025 |
def delete_data_by_key(data, database, table, key_column):
"""
通过#{key_column}删除数据
:param data: data_dict对象
:param database: 数据库
:param table: 表名
:param key_column: 逐渐列
:return: None
"""
sql = "delete from %s where %s = '%s'" % (table, key_column, data[key_column])
database_pool... | 49,026 |
def encrypt_and_add_metadata(input_pdf,
output_folder,
usr_pass,
owner_pass,
remove_original=False):
"""Encrypts PDF, changes permissions and adds metadata to PDF.
Default permissions let the use... | 49,027 |
def is_tax_id_obligatory(country):
"""
Returns True if country is in EU or is Poland. Returns False for others.
"""
if country.name in all_eu_countries:
return True
return False | 49,028 |
def isMaskedArray(x: List[int]):
"""
usage.scipy: 5
"""
... | 49,029 |
def indexTupleToStr(idx):
"""
Generate a string contains all the lowercase letters corresponding to given index list.
Parameters
----------
idx : list of int
A list of indices, each should be in [0, 26).
Returns
-------
str
A string that corresponding to the indices... | 49,030 |
def _LookupPermset(role, status, access):
"""Lookup the appropriate PermissionSet in _PERMISSIONS_TABLE.
Args:
role: a string indicating the user's role in the project.
status: a Project PB status value, or UNDEFINED_STATUS.
access: a Project PB access value, or UNDEFINED_ACCESS.
Returns:
A Perm... | 49,031 |
def _add_sld_boilerplate(symbolizer):
"""
Wrap an XML snippet representing a single symbolizer in the appropriate
elements to make it a valid SLD which applies that symbolizer to all features,
including format strings to allow interpolating a "name" variable in.
"""
return """
<StyledLayerDescri... | 49,032 |
def calculate_distance(location1, location2):
"""Calculate geodesic distance between two coordinates with ellipsoidal earth model.
Args:
location1: tuple of (latitude, longitude) as floats in Decimal Degrees
location2: tuple of (latitude, longitude) as floats in Decimal Degrees
Returns:
A float in me... | 49,033 |
def user():
"""
form传值变量名:
email,call,signature,mail,pre_school,address,detail_address,nickname
返回值:
user_info: 用户个人信息的字典
"""
if 'USR_ID' in session:
if request.method == 'GET':
user_info = query_db("SELECT * FROM student WHERE user_id = %s",
... | 49,034 |
def sequence_names_match(r1, r2):
"""
Check whether the sequences r1 and r2 have identical names, ignoring a
suffix of '1' or '2'. Some old paired-end reads have names that end in '/1'
and '/2'. Also, the fastq-dump tool (used for converting SRA files to FASTQ)
appends a .1 and .2 to paired-end reads if option -I ... | 49,035 |
def generate_mobile_module_lints(script_module: torch.jit.ScriptModule):
"""
Args:
script_module: An instance of torch script module with type of ScriptModule
Returns:
lint_map: A list of dictionary that contains modules lints
"""
if not isinstance(script_module, torch.jit.ScriptMod... | 49,036 |
def manipulation(macid: MACID, decision: str, effective_set: Set[str]) -> bool:
"""Check whether a decision is motivated by an incentive for manipulation.
Graphical Criterion:
1) There is a directed decision-free path from D_A to an effective decision node D_B.
2) There is a directed, effective path fr... | 49,037 |
def _get_client_ids_meeting_condition(train_tff_data, bad_accuracy_cutoff,
good_accuracy_cutoff,
invert_imagery_likelihood,
classifier_model):
"""Get clients that classify <bad_accuracy_cutoff or >good_ac... | 49,038 |
def get_wccp_service_group_settings(
self,
ne_id: str,
cached: bool,
) -> dict:
"""Get per-group WCCP configuration settings from appliance
.. list-table::
:header-rows: 1
* - Swagger Section
- Method
- Endpoint
* - wccp
- GET
- /wccp... | 49,039 |
def container_storage_opt() -> int:
"""Return the size for the 'storage_opt' options of the container.
Return -1 if no option (or the default 'host') was given."""
if "storage_opt" in settings.DOCKER_PARAMETERS:
storage = settings.DOCKER_PARAMETERS["storage_opt"].get("size", -1)
if stor... | 49,040 |
def loadStylesheet(filename:str):
"""
Loads an qss stylesheet to current QApplication instance
:param filename: Filename of qss stylesheet
:type filename: str
"""
print('STYLE loading:', filename)
file = QFile(filename)
file.open(QFile.ReadOnly | QFile.Text)
stylesheet = file.readAl... | 49,041 |
def checkfixablectx(ui, repo, ctx):
"""Aborts if the revision shouldn't be replaced with a fixed one."""
if ctx.obsolete():
# It would be better to actually check if the revision has a successor.
allowdivergence = ui.configbool(
b'experimental', b'evolution.allowdivergence'
)... | 49,042 |
def sscreen_chrome(url: str, path: str, website_name: str, index: int, width=1920, height=1080):
"""Настройка браузера и создание скриншота в формате png/base64
Args:
url (str): URL сайта для перехода методом get
path (str): Путь сохранения скриншота в формате png
website_name (str): На... | 49,043 |
def construct_insert_conversatie_query(graph_uri, conversatie, bericht, delivery_timestamp):
"""
Construct a SPARQL query for inserting a new conversatie with a first bericht attached.
:param graph_uri: string
:param conversatie: dict containing escaped properties for conversatie
:param bericht: di... | 49,044 |
def _minimum_chunk_size_accuracy(
data: pd.DataFrame,
partition_column_name: str = NML_METADATA_PARTITION_COLUMN_NAME,
prediction_column_name: str = NML_METADATA_PREDICTION_COLUMN_NAME,
target_column_name: str = NML_METADATA_TARGET_COLUMN_NAME,
required_std: float = 0.02,
):
"""Estimation of min... | 49,045 |
def estimate_directions(correlations, pairs):
"""Estimate directions from a correlation matrix for specific pairs.
Parameters
----------
correlations : numpy.ndarray, shape=(n_samples, n_samples)
A correlation matrix. Can contain nan values.
pairs : numpy.ndarray, shape=(< n_samples, 2)
... | 49,046 |
def render_template2(template, template_vars):
"""convenience function to render template in a non-Flask context"""
loader_dir = os.path.join(os.path.dirname(__file__), 'templates')
loader = FileSystemLoader(loader_dir)
env = Environment(loader=loader, extensions=['jinja2.ext.i18n'])
translations_... | 49,047 |
def build_parser():
"""Build the argument parser."""
parser = argparse.ArgumentParser(description=DESCRIPTION, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument('-v', '--verbose', action="count", default=0, help="Increase logging level (goes error, warn, info, debug)")
subparser ... | 49,048 |
def get_est_input_size(out, height, p2pkh_pksize, p2sh_scriptsize, nonstd_scriptsize, p2wsh_scriptsize):
"""
Computes the estimated size an input created by a given output type (parsed from the chainstate) will have.
The size is computed in two parts, a fixed size that is non type dependant, and a variable ... | 49,049 |
def test_rate_limit_interface():
"""
Just test that very basic usage doesn't error
"""
per_user_rate_def = RateDefinition(per_week=50000, per_day=13000, per_second=.001)
min_rate_def = RateDefinition(per_second=10)
per_user_rate_def = PerUserRateDefinition(per_user_rate_def, min_rate_def)
my... | 49,050 |
def VisumInit(path=None,COMAddress='Visum.Visum.125'):
"""
###
Automatic Plate Number Recognition Support
(c) 2012 Rafal Kucharski info@intelligent-infrastructure.eu
####
VISUM INIT
"""
import win32com.client
Visum = win32com.client.Dispatch(COMAddress)
if pat... | 49,051 |
def get(section, option, default=None):
"""
Simple accessor to hide/protect the multiple depth dict access: conf["SECTION"]["OPTION"]
"""
if section in conf.keys():
if option in conf[section].keys():
return conf[section][option]
return default | 49,052 |
def inceptionresnetv1(**kwargs):
"""
InceptionResNetV1 model from 'Inception-v4, Inception-ResNet and the Impact of Residual Connections on Learning,'
https://arxiv.org/abs/1602.07261.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for mod... | 49,053 |
def commonpath(paths):
"""py2 compatible version of py3's os.path.commonpath
>>> commonpath([""])
''
>>> commonpath(["/"])
'/'
>>> commonpath(["/a"])
'/a'
>>> commonpath(["/a//"])
'/a'
>>> commonpath(["/a", "/a"])
'/a'
>>> commonpath(["/a/b", "/a"])
'/a'
>>> comm... | 49,054 |
def test_get_expired_disabled(app, db):
"""Test get first active with future date."""
Banner.create(**banners["expired"])
Banner.create(**banners["disabled"])
db.session.commit()
assert Banner.get_active("/") is None
assert Banner.get_active("/other") is None
assert Banner.get_active("/reco... | 49,055 |
def series_length(x: np.array, freq: int = 1) -> Dict[str, float]:
"""Series length.
Parameters
----------
x: numpy array
The time series.
freq: int
Frequency of the time series
Returns
-------
dict
'series_length': Wrapper of len(x).
"""
return {'serie... | 49,056 |
def request_put_multipart(uri, headers, multipart_title, multipart_file):
"""
Requests PUT uri as multipart.
"""
try:
if multipart_file != '':
f = open(multipart_file, "rb")
else:
f = None
multipart_body = { multipart_title : (multipart_file, f, "applicati... | 49,057 |
def _load_uvtp(date, time, latitude=-30, longitude=289.5):
"""Load U, V, T componenents of wind for GFS file given date and time."""
# do not want pygrib to be a dependency for the whole psfws package.
import pygrib
# load in dataset (specific date/time given by args)
try:
grbs = pygrib.ope... | 49,058 |
def prend(obj=None): #py:take
"""Prend un objet. Si plus d'un type d'objet se trouve à l'endroit où
Reeborg est, on doit spécifier lequel sinon ceci causera une exception.
"""
if obj is None:
RUR._take_()
else:
RUR._take_(obj) | 49,059 |
def ds2_variables(input, output_vars=False, names=None):
"""Generate a collection of `DS2Variable` instances corresponding to the input
Parameters
----------
input : function or OrderedDict<string, tuple> or Pandas DataFrame or Numpy or OrderedDict<string, type>
a function or mapping parameter ... | 49,060 |
def get_default_dal(_db_type, _db_name=""):
"""Returns a default database connection for the given db typ.
Read from environment variable first, then assume files are in /config/subdirectory.
# TODO: Fix so it uses \ on the windows platform. """
cfg_path = os.path.expanduser(
os.getenv('OPTIMAL_... | 49,061 |
def p_expComp_ternario_1(t):
"""
expComp : datatype R_BETWEEN datatype R_AND datatype
"""
t[0] = code.TernaryExpression(
newTemp(), t[1], t[3], t[5], t[2], isBlock, t[1].row, t[1].column
)
incTemp(2)
repGrammar.append(t.slice) | 49,062 |
def register():
"""Register User"""
# forget any user_id
session.clear()
# If the user has been redirected through an event url
event = request.args.get('event')
# if user reached route via POST (as by submitting a form via POST)
if request.method == 'POST':
# check if form field... | 49,063 |
def test_no_errors_if_excluded_player_is_not_in_data(test_excluded_players_list, num_excluded_in_data):
"""
Given a list of players that have been drafted,
when a drafted player does not exist in the data
it should remove the drafted players that exist from
analysis and not error on players that do ... | 49,064 |
def topological_sort(edges: Sequence[Sequence]) -> list:
"""Produce a topological sorting (if one exists) using a BFS approach.
Args:
edges (Sequence[Sequence]): A list of edges pairs, ex: [('A', 'B'), ('A', 'C')].
Returns:
list: An array with a non-unique topological order of nodes.
"... | 49,065 |
def notify_retweet(t):
"""
Notify a retweet
"""
source = t['user']
created_at = t['created_at']
# Format
source_user = cycle_color(source['name']) + \
color_func(c['NOTIFICATION']['source_nick'])(
' @' + source['screen_name'])
notify = color_func(c['NOTIFICATION']['notify... | 49,066 |
def test_get_document_returns_response():
"""Test if the API responds.
When we try to create a content library document.
"""
assert _heartbeat(client.get_document(fixtures['document'])) | 49,067 |
def rename_bad_cache_file():
"""
An attempt to open a bad cache file will cause it to be dropped and recreated.
>>> with open('cache', 'w') as f:
... _ = f.write('x'*100)
>>> import logging, sys
>>> handler = logging.StreamHandler(sys.stdout)
>>> logging.getLogger().addHandler(handler)
... | 49,068 |
def map_currency(currency, currency_map):
"""
Returns the currency symbol as specified by the exchange API docs.
NOTE: Some exchanges (kraken) use different naming conventions. (e.g. BTC->XBT)
"""
if currency not in currency_map.keys():
return currency
return currency_map[currency] | 49,069 |
def FastResultRow(cols):
"""Create a ResultRow-like class that has all fields already preparsed.
Non-UTF-8-String columns must be suffixed with !."""
getters = {}
_keys = []
for i, col in enumerate(cols.split()):
if col[-1] == '!':
col = col[:-1]
getter = itemgetter(i... | 49,070 |
def new_answer(notification):
"""
Obtains a new answer body for notifs where **source is
the post**
"""
answer = Answer.query.filter_by(id=notification.target_id).first()
post = Post.query.filter_by(id=notification.source_id).first()
if not isinstance(answer, Answer):
return "A new ... | 49,071 |
def test_no_duplicate_corrections():
"""
Compatibility should never apply the same correction twice
"""
entry = ComputedEntry("Fe2O3", -2)
compat = DummyCompatibility()
assert entry.correction == 0
compat.process_entries(entry)
assert entry.correction == -10
compat.process_entries(e... | 49,072 |
def gather_indexes(sequence_tensor, positions):
"""Gathers the vectors at the specific positions.
Args:
sequence_tensor: Sequence output of `BertModel` layer of shape
(`batch_size`, `seq_length`, num_hidden) where num_hidden is number of
hidden units of `BertModel` layer.
positions: Pos... | 49,073 |
def test_complex009_complex009_v2_xml(mode, save_output, output_format):
"""
xsi:type use="required Specifying use="required" for xsi:type is
allowed and effective
"""
assert_bindings(
schema="saxonData/Complex/complex009.xsd",
instance="saxonData/Complex/complex009.v2.xml",
... | 49,074 |
def _check_type(value, expected_type):
"""Perform type checking on the provided value
This is a helper that will raise ``TypeError`` if the provided value is
not an instance of the provided type. This method should be used sparingly
but can be good for preventing problems earlier when you want to rest... | 49,075 |
def find_rbm_procrustes(frompts, topts):
"""
Finds a rigid body transformation M that moves points in frompts to the points in topts
that is, it finds a rigid body motion [ R | t ] with R \in SO(3)
This algorithm first approximates the rotation by solving
the orthogonal procrustes problem.
"""
... | 49,076 |
def adapt_type_to_browse_processor() -> Callable[[MediaProcessorType], BrowseGeneratorType]:
"""
Create generator for media objects from provided ID's
:return: Decorator
"""
def _decorate(func: MediaProcessorType):
"""
Decorate
:param func:
:return:
"""
... | 49,077 |
async def file(
location,
status=200,
mime_type=None,
headers=None,
filename=None,
_range=None,
):
"""Return a response object with file data.
:param location: Location of file on system.
:param mime_type: Specific mime_type.
:param headers: Custom Headers.
:param filename: ... | 49,078 |
def get_skyarea(output_mock, Nside):
"""
"""
import healpy as hp
# compute sky area from ra and dec ranges of galaxies
nominal_skyarea = np.rad2deg(np.rad2deg(4.0*np.pi/hp.nside2npix(Nside)))
if Nside > 8:
skyarea = nominal_skyarea
else:
pixels = set()
for k in outpu... | 49,079 |
def _fetch_checksum(checksum, image_info):
"""Fetch checksum from remote location, if needed."""
if not (checksum.startswith('http://') or checksum.startswith('https://')):
# Not a remote checksum, return as it is.
return checksum
LOG.debug('Downloading checksums file from %s', checksum)
... | 49,080 |
def paginator(request, **params):
"""Split requests in multiple batches and return records as generator"""
rows = request.get(**params)
yield from rows
while request.records_remaining:
rows = request.get_next()
yield from rows | 49,081 |
def get_patch_info(shape, p_size):
"""
shape: origin image size, (x, y)
p_size: patch size (square)
return: n_x, n_y, step_x, step_y
"""
x = shape[0]
y = shape[1]
n = m = 1
while x > n * p_size:
n += 1
while p_size - 1.0 * (x - p_size) / (n - 1) < 50:
n += 1
w... | 49,082 |
def validate_token(token=None):
"""Helps in confirming the Email Address with the help of the token, sent on the registered email address.\n
Keyword Arguments:
token -- Token passed in the user's email
"""
try:
res = URLSafeTimedSerializer(SECRET).loads( # noqa
token, salt=VERIF... | 49,083 |
def generate_csv(folder_id):
"""Given folder, folder/prediction.nrrd is given and folder/prediction.csv written."""
pred_fn = os.path.join(folder_id, 'prediction.nrrd')
csv_fn = os.path.join(folder_id, 'prediction.csv')
if os.path.exists(csv_fn):
os.remove(csv_fn)
prediction_to_csv(pred_fn... | 49,084 |
def rate2amount(
rate: xr.DataArray, dim: str = "time", out_units: str = None
) -> xr.DataArray:
"""Convert a rate variable to an amount by multiplying by the sampling period length.
If the sampling period length cannot be inferred, the rate values
are multiplied by the duration between their time coor... | 49,085 |
def makechis(d, N, maxchi):
"""Create the vector of chis for the chain.
This is a length-N+1 list of exponents of d. The exponents are of
the form
[0, 1, 2, 1, 0] (if N+1 is odd)
[0, 1, 2, 2, 1, 0] (if N+1 is even)
Any numbers in the above exceeding ln(maxchi) / ln(d) are replace... | 49,086 |
def generate_input_f(reagent, MW, density):
""" A helper function to properly formate input for concentration-to-amount calculations.
Returns a dictionary where each key is a reagent component and each value is a sub-dictionary
containing concentration, phase, molecular weight, and density.
For reagents... | 49,087 |
def addCol(adjMatrix):
"""Adds a column to the end of adjMatrix and returns the index of the comlumn that was added"""
for j in range(len(adjMatrix)):
adjMatrix[j].append(0)
return len(adjMatrix[0])-1 | 49,088 |
def setup(bot):
"""Add cog."""
check_folder()
check_file()
bot.add_cog(UserData(bot)) | 49,089 |
def get_table_m_1_a_5():
"""表M.1(a)-5 居住人数4人における基準給湯量および入浴人数(生活スケジュール:平日(小))
Args:
Returns:
list: 表M.1(a)-5 居住人数4人における基準給湯量および入浴人数(生活スケジュール:平日(小))
"""
# 表M.1(a)-5 居住人数4人における基準給湯量および入浴人数(生活スケジュール:平日(小))
table_m_1_a_5 = np.array([
(0, 0, 0, 0, 0, 0, 0, 0),
(0, 0, 0, 0, 0, ... | 49,090 |
def get_shell_python_version(command='python -V'):
""" Get version of Python running in shell | None --> tuple
Use command keyword to test python3 instead of python
if python version is Python 2.
Minor version is not used at present but is included in case it is needed
in future versions.
"""
... | 49,091 |
def get_all_pattern_files():
"""Return all data files in the data folder"""
d = raw_data_dir()
return sorted([x for x in os.listdir(d) if is_pattern_file(os.path.join(d, x))]) | 49,092 |
def _get_first_sentence(s):
"""
Get the first sentence from a string and remove any carriage
returns.
"""
x = re.match(r".*?\S\.\s", s)
if x is not None:
s = x.group(0)
return s.replace('\n', ' ') | 49,093 |
def open_tsg_from_legos(filename):
"""
Open thermosalinograph (TSG) transect from the LEGOS dataset,
and homogenize the coordinates
Parameters
----------
filename : str
Name of the file to open
Returns
-------
ds : xarray.Dataset
The TSG transect under the ... | 49,094 |
def main():
""" メイン関数 """
# 接続ピン
PIN_AIN1 = 6
PIN_AIN2 = 5
PIN_BIN1 = 26
PIN_BIN2 = 27
# 左右モーター設定(PWM)
motors = Robot(left=(PIN_AIN1,PIN_AIN2),right=(PIN_BIN1,PIN_BIN2),pwm=True)
# 1秒毎の正負パルス値の信号源
dirleft = post_delayed(scaled(alternating_values(True) ,-1,1),1)
dirright = post_delayed(scaled(alternating_val... | 49,095 |
def get_current_time():
"""Return timestamp for current system time in UTC time zone.
Returns
-------
datetime
Current system time
"""
return datetime.datetime.utcnow() | 49,096 |
def p_simple_operation(p):
"""simple_operation : assignment
| matrix_assignment
| basic_function
| if_else
| for
| while""" | 49,097 |
def preprocess_wiki(source_dir, output_dir, processes, use_existing,
edit_freq_file='edit_freq.json'):
"""Generate synthetic error corpus from Wikipedia dump."""
if not os.path.isdir(source_dir):
raise ValueError(f'WikiExtractor text folder not found at {source_dir}')
n_sents = 0... | 49,098 |
def calculate_average(result):
"""Calculates the average package size"""
vals = result.values()
if len(vals) == 0:
raise ValueError("Cannot calculate average on empty dictionary.")
return sum(vals)/float(len(vals)) | 49,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.