content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def collapse(intlist):
"""Collapse a list of int values of chars into the int they represent."""
f = ''
for i in intlist:
f += chr(i)
return int(f) | 42,400 |
def _create_profile_for_host_communication(profile_name):
"""
Create a profile which allows traffic to and from the host.
"""
_log.info("Autocreating profile %s", profile_name)
datastore.create_profile(profile_name)
prof = datastore.get_profile(profile_name)
host_net = str(_get_host_ip_net(... | 42,401 |
def file_is_dll_client(
path_name):
"""
.. todo::
Document.
"""
file_is_dll_client_by_platform = {
"darwin": file_is_dll_client_unix,
"linux2": file_is_dll_client_unix,
"win32": file_is_dll_client_win32
}
return file_is_dll_client_by_platform[sys.platform... | 42,402 |
def _validate_environment_variable(
ctx: click.core.Context,
param: Union[click.core.Option, click.core.Parameter],
value: Tuple[str],
) -> Dict[str, str]:
"""
Validate that environment variables are set as expected.
"""
# We "use" variables to satisfy linting tools.
for _ in (param, ctx... | 42,403 |
def get_settings() -> Tuple[int, int]:
"""Gets some settings for the board."""
return board_size, num_ships | 42,404 |
def run_sunset():
""" Sends a tweet about the sunset and captures image """
tweet_sunset()
return run_tweeter() | 42,405 |
def test_get_known_transcripts_specific_dataset():
""" Now make sure the correct transcript is returned when the dataset is
specified. """
database = "scratch/filter/test.db"
# Both datasets
known = filt.get_known_transcripts(database, "toy",
datasets =... | 42,406 |
def get_data():
"""Get the population data."""
# Construct population
pop = CosmicPopulation(n_srcs=SIZE, n_days=1, name='standard_candle')
pop.set_dist(model='sfr', z_max=2.5, H_0=67.74, W_m=0.3089, W_v=0.6911)
pop.set_dm_host(model='constant', value=100)
pop.set_dm_igm(model='ioka', slope=1000... | 42,407 |
def dummy1_3857_tif():
"""Fixture for dummy1_3857.tif"""
return os.path.join(TESTDATA_DIR, "dummy1_3857.tif") | 42,408 |
def create_token(request):
"""Debug helper view.
========== =====================================================
Argument Value
========== =====================================================
timeout Number of seconds to keep token alive (default=6).
url The url to ... | 42,409 |
def test_parse_source():
""" Ensure a tuple of two non-empty lists is returned """
with open('tests/names-generator.go', 'r') as go_source:
source = go_source.read()
parsed_source = _parse_source(source)
assert type(parsed_source) == tuple
assert type(parsed_source[0]) == list
assert t... | 42,410 |
def tag_user(request, tag, username):
""" Display all `tag` snippets of `username` user """
user = get_object_or_404(User, username=username)
snippets = Snippet.objects.filter(author=user).filter(
tags__name__in=[tag, ]).all()
return render_to_response('tags/view.html', {
'tag': tag,
... | 42,411 |
def rmsfcalc(u, rmsfout, modus="calphas"):
"""
Calculation of Protein RMSF
:param u: MDAnalysis universe
:param rmsfout: File path to output file
:param modus: Selection to align and calculation ("calphas" or "allatoms")
:return: None
"""
calphas = u.select_atoms("protein and ... | 42,412 |
def extract_keywords(keywlist_handle):
"""extract_keywords(keywlist_handle) -> list of keywords
Return the keywords from a keywlist.txt file.
"""
import warnings
warnings.warn("Bio.SwissProt.KeyWList.extract_keywords is deprecated. Please use the function Bio.SwissProt.KeyWList.parse instead to pa... | 42,413 |
def automated_threshold_setting(image, mask_local_max):
"""Automatically set the optimal threshold to detect spots.
In order to make the thresholding robust, it should be applied to a
filtered image (bigfish.stack.log_filter for example). The optimal
threshold is selected based on the spots distributio... | 42,414 |
def _get_raw_test_commands(name: str) -> List[str]:
"""テストケースのinclude解決を行っていない状態の生のコマンドを取得する
Args:
name (str): テストケース名
Raises:
Exception: 取得に失敗した場合例外を送出します
Returns:
List[str]: テストコマンド配列
"""
testcase = _get_testcase_object(name)
return _convert_test_commands(testcas... | 42,415 |
def extract_params(func, standard_args):
"""Return WhyNot parameters for user-defined function.
Performs error-checking to ensure parameters are disjoint from
standard arguments and all arguments to the function are either
standard arguments or parameters.
Parameters
----------
func: f... | 42,416 |
def lark_to_float_value_node(tree: "Tree") -> "FloatValueNode":
"""
Creates and returns a FloatValueNode instance extracted from the parsing of
the tree instance.
:param tree: the Tree to parse in order to extract the proper node
:type tree: Tree
:return: a FloatValueNode instance extracted from... | 42,417 |
def confusion_matrix(pred, gt, thres=0.5):
"""Calculate the confusion matrix given a probablility threshold in (0,1).
"""
TP = np.sum((gt == 1) & (pred > thres))
FP = np.sum((gt == 0) & (pred > thres))
TN = np.sum((gt == 0) & (pred <= thres))
FN = np.sum((gt == 1) & (pred <= thres))
return (... | 42,418 |
def save_score_results(score, cfg, logger, verbose=None, config_name='None', current_step=0, time_stamp='time_step'):
"""Save scores.
This method is used to store the normal/abnormal scores of frames which are used for the evaluation functions
Args:
score(list): The scores of all of the video... | 42,419 |
def data_path(filename: str) -> str:
"""Get full path to a file in the data folder.
Args:
filename (str): The data file's name.
Returns:
path (str): The full path to the file.
"""
return os.path.join(os.path.dirname(__file__), "data", filename) | 42,420 |
def do_heatmap(df):
"""
Make a bottom heatmap
"""
mask = np.zeros_like(df, dtype=np.bool)
mask[np.triu_indices_from(mask)] = True
cmap = sns.diverging_palette(220, 10, as_cmap=True)
sns.heatmap(df.values.tolist(), yticklabels=df.columns, xticklabels=df.columns, vmin=-1, vmax=1, center=0,
... | 42,421 |
def docs2omop(
docs: List[Doc],
extensions: Optional[List[str]] = None,
) -> Tuple[pd.DataFrame, pd.DataFrame]:
"""
Transforms a list of spaCy docs to a pair of OMOP tables.
Parameters
----------
docs : List[Doc]
List of documents to transform.
extensions : Optional[List[str]], ... | 42,422 |
def getWebVersion(d):
"""Get the version from the web of the catalog entry in d
Use the page at the url specified in d['version']['url'], and the regular
expression specified in d['version']['regex'] to find the latest version
number of the passed package. The d['version']['regexpos']'th match of the
... | 42,423 |
def stdev_outliers_proxy(self, *args, **kwargs):
"""
Calls :meth:`.stdev_outliers` on each table in the TableSet.
"""
return self._proxy('stdev_outliers', *args, **kwargs) | 42,424 |
def load_cells():
"""Load cell data.
This cell dataset contains cell boundaries of mouse osteosarcoma
(bone cancer) cells. The dlm8 cell line is derived from dunn and is more
aggressive as a cancer. The cells have been treated with one of three
treatments : control (no treatment), jasp (jasplakinol... | 42,425 |
def test_searchparam_type_date_period_ge(store: FHIRStore, index_resources):
"""Handle date search parameters on FHIR data type "period"
The date format is the standard XML format, though other formats may be supported
prefix ge: the range above the search value intersects (i.e. overlaps)
with the r... | 42,426 |
def approve_story(story: str):
"""
Moves a story from the pending file to the story file.
:param story: The story to approve.
:return:
"""
pending_data = load_pending_list()
story_to_approve = pending_data[story.lower()]
del pending_data[story.lower()]
update_pending_list(pending_da... | 42,427 |
def k_fold_cross_validation(X, k=None, randomize=False):
"""
Generates K (training, validation) pairs from the items in X.
Each pair is a partition of X, where validation is an iterable
of length len(X)/K. So each training iterable is of length
(K-1)*len(X)/K.
Parameters
----------
X :... | 42,428 |
def correlation_matrix(
spark, idf, list_of_cols="all", drop_cols=[], stats_unique={}, print_impact=False
):
"""
:param spark: Spark Session
:param idf: Input Dataframe
:param list_of_cols: List of columns to analyse e.g., ["col1","col2"].
Alternatively, columns can be speci... | 42,429 |
def _model_variable_getter(getter, name, shape=None, dtype=None,
initializer=None, regularizer=None, trainable=True,
collections=None, caching_device=None,
partitioner=None, rename=None, use_resource=None,
**_):
... | 42,430 |
def password_check(value, user):
"""
Check that the password passes the following validation:
Password is long enough (based on configuration setting)
Password contains at least one digit
Password contains at least one letter
Password contains at least one uppercase character
Password conta... | 42,431 |
def test_histogram_cli_no_datasets(output_path):
""" Tests that the command line interface works correctly on the test
dataset for histogram plots when the test dataset is passed in via
command line.
"""
subprocess.run(
[
"svl",
# NOTE Don't need the template ... | 42,432 |
def copiar_dic(origen):
"""
Devuelve una copia nueva de ``origen`` con el menor estado compartido
posible.
Utiliza `fusionar_dics` debajo del capó, con un dict ``base`` vacío;
consulte su documentación para obtener detalles sobre el comportamiento.
.. versionadded:: 1.0
"""
return fu... | 42,433 |
def get_all_users(conn):
"""Iterator that yields all IAM users, to simplify getting all
users. The amazon interface presents a "next" token that has to
be guarded. This makes that easier. However it doesn't present
the returned object, only the list of user dicts
Enables this sort of search:
In [210]: r = get... | 42,434 |
def to_weight(df: pd.DataFrame, renorm=True):
"""
Converts molar quantities to mass quantities of the same order.
E.g.:
mol% --> mass%
mol-ppm --> mass-ppm
"""
MWs = [pt.formula(c).mass for c in df.columns]
if renorm:
return renormalise(df.multiply(MWs))
else:
return ... | 42,435 |
def sind(ang: ArrayLike) -> ArrayLike:
"""Return the sine of an angle specified in degrees.
Parameters
----------
ang : float
An angle, in degrees.
"""
return numpy.sin(numpy.radians(ang)) | 42,436 |
def linscale(x, lb_in, ub_in, lb_out, ub_out):
"""linscale scales x according to the provided bounds.
Parameters
----------
x : (N, x_dim) numpy array
lb_in : scalar or 1D list of len x_dim or (1,) or (x_dim,) numpy array
Returns
-------
xs : (N, x_dim) numpy array
"""
lb_i... | 42,437 |
def sync_from(src, dest):
"""Synchronize a directory from Dropbox."""
return False | 42,438 |
def replypost(postnum):
"""
Reply to a post.
Arguments:
postnum:
Post number to reply to.
if postnum == "":
ask for post number to reply to
else:
reply to global postum
User input:
Post number and/or post text.
"""
getme()
global posttext
posttext = ''
if str(postnum) == "":
postnu... | 42,439 |
async def get_view_config(
name: str = Path(None, description="Name of the view"),
token_jenkins_auth: TokenModel = Security(
get_token_jenkins_auth
),
) -> str:
"""Retrieve view configuration"""
... | 42,440 |
def transcribe(seq: str) -> str:
"""
transcribes DNA to RNA by generating
the complement sequence with T -> U replacement
"""
#stores the complement, RNA seq
RNA_seq = ""
#generate complement sequence
#DNA->ACTG->A-><-T, C-><-G
#T->U replacement
keep_alpha_only = re.sub(r'[... | 42,441 |
def filter_timeline_actions(tim, **filters):
"""tim (dict) contains info for one TIM"""
actions = tim['timeline']
for field, required_value in filters.items():
if field == 'time':
# Times are given as closed intervals: either [0,134] or [135,150]
acceptable_times = range(requ... | 42,442 |
def _make_n_rows(x, n, y=None):
"""
Multiplies or reduces the rows of x to get
exactly *n* rows.
"""
if n < x.shape[0]:
if y is None:
return x[:n].copy()
return x[:n].copy(), y[:n].copy()
if len(x.shape) < 2:
r = np.empty((n,), dtype=x.dtype)
... | 42,443 |
def calculate_match_unnormd_fft(
params_h: Binary, params_d: Binary, fs, pad_low, pad_high, S_n=S_n_LISA
):
"""
Inner product of waveforms, maximized over Phi_c by taking absolute value
and t_c using the fast Fourier transform.
"""
df = fs[1] - fs[0]
wf_h = amp(fs, params_h) * jnp.exp(1j * P... | 42,444 |
def _force_merge(session, model, new_model):
"""Force merge an existing `model` with a `new_model` by copying the
primary key values from `model` to `new_model` before calling
``session.merge(model)``.
"""
pk_cols = mapper_primary_key(model.__class__)
for col in pk_cols:
setattr(new_mod... | 42,445 |
def get_alignment(ra_difference, dec_difference):
"""
This function ...
:param ra_difference:
:param dec_difference:
:return:
"""
ra_alignment = None
dec_alignment = None
if np.isclose(ra_difference, 1.0, atol=0.0001): # if RA increment is close to 1 with a positive x increment
... | 42,446 |
def three_to_one_with_mods(res: str) -> str:
"""
Converts three letter AA codes into 1 letter. Allows for modified residues.
:param res: Three letter residue code str:
:type res: str
:return: 1-letter residue code
:rtype: str
"""
return RESI_THREE_TO_1[res] | 42,447 |
def sent2features(sent, pos_lex=None, neg_lex=None):
"""
Converts a sentence (list of (word, pos_tag) tuples) into a list of feature
dictionaries
"""
return [word2features(sent, i, pos_lex, neg_lex) for i in range(len(sent))] | 42,448 |
def ensure_virtualenv( python, numpy=True ):
"""Check/create virtualenv using our naming scheme"""
expected_name = os.path.join( TEST_ENVS, python+['-nonum','-num'][bool(numpy)])
log.info( 'Ensuring %s', expected_name )
bin_path = os.path.join( expected_name, 'bin' )
if not os.path.exists( expected_... | 42,449 |
def effect_of_travel_range_on_afv_attractiveness():
"""
Real Name: b'Effect of travel range on AFV Attractiveness'
Original Eqn: b'AFV travel range/travel range max'
Units: b'Dmnl'
Limits: (None, None)
Type: component
b''
"""
return afv_travel_range() / travel_range_max() | 42,450 |
def serialize_read(function_code: int, transaction_id: int, unit_address: int, first_address: int, count: int) -> str:
"""
Universal function for handling serialization of all read type messages.
Args:
function_code: Unique function code.
transaction_id: Unique ID of the transaction.
... | 42,451 |
def plot_locally_connected_weights(
weights: torch.Tensor,
n_filters: int,
kernel_size: Union[int, Tuple[int, int]],
conv_size: Union[int, Tuple[int, int]],
locations: torch.Tensor,
input_sqrt: Union[int, Tuple[int, int]],
wmin: float = 0.0,
wmax: float = 1.0,
im: Optional[AxesImage]... | 42,452 |
def clean(context, derived_data, caches, build, all):
"""Clean project & punic environment."""
logging.info("<cmd>Clean</cmd>")
punic = context.obj
with timeit('clean'):
if build or all:
logging.info('Erasing Carthage/Build directory')
if punic.config.build_path.exists()... | 42,453 |
def draw_box_list(img_bgr, box_list, thickness=-1, color=None,
is_overlap=True, is_arrow=False, is_text=True, is_show=False, is_new=False, save_name=None):
"""
绘制矩形列表
"""
if is_new:
img_bgr = copy.deepcopy(img_bgr)
n_box = len(box_list)
if not color:
color_list... | 42,454 |
def adjust_protons(formula, protons):
"""
@param formula: chemical formula as string
@param protons: number of hydrogens to add/remove as intager
@return: new formula as string
"""
if not protons:
return (formula,"")
protons = int(protons)
Notes = ""
#The whole function assum... | 42,455 |
def angsep(ra1,dec1,ra2,dec2):
"""Compute the angular separations between two points on a sphere
Parameters:
- ra1 - Right ascension of first position
- dec1 - Declination of first position
- ra2 - Right ascension of second position
- dec2 - Declination of second position
Note: All inp... | 42,456 |
def construct_schema_function_without_choices() -> Callable:
"""
Modifies model example and description if needed.
Note that schema extra has to be a function, otherwise it's called to soon
before all the relations are expanded.
:return: callable that will be run by pydantic to modify the schema
... | 42,457 |
def is_cross_not_claimed(event_list, team):
"""Returns if event list has a cross-not-claimed Goalkeeper event; cross not successfully caught"""
cnc = False
for e in event_list[:1]:
if e.type_id == 53:
cnc = True
return cnc | 42,458 |
def update_items(controller, async_add_entities, switches):
"""Update POE port state from the controller."""
new_switches = []
devices = controller.api.devices
for client_id in controller.api.clients:
if client_id in switches:
LOGGER.debug("Updating UniFi switch %s (%s)",
... | 42,459 |
def _do_monte_carlo_run(pools, lulc_counts):
"""Do a single Monte Carlo run for carbon storage.
Returns a dict with the results, keyed by scenario, and
# including results for sequestration.
"""
# Sample carbon-per-grid-cell from the given normal distribution.
# We sample this independently fo... | 42,460 |
def compute_partition(df):
"""Perform compute on a partition
Partitions are perfectly aligned along 1 minute and the timestamp index is
sorted.
Below is a reasonably costly operation that aggregates data from
each timestep. That dataframe would aggregate what the timestep had (i.e.,
measureme... | 42,461 |
def main(event , context):
"""Permite detectar las emociones de una imagen"""
uri_base = event['bucket'] #Bucket donde esta la imagen
pic = event['name'] #Nombre de la imagen a analizar
result = emotion_detection.emo_detect(uri_base, pic) #Detectar emocion
print("Emocion detectada: "+resul... | 42,462 |
def first_impressions_view(request):
"""First impressions view."""
auth = False
try:
auth = request.cookies['auth_tkt']
auth_tools = request.dbsession.query(
MyModel
).filter(MyModel.category == 'admin').all()
except KeyError:
auth_tools = []
query = reque... | 42,463 |
def mysql_create_tables():
"""
when using mysql database, this is the function that is used to create the tables in the database for the first
time when you run the nettacker module.
Args:
None
Returns:
True if success otherwise False
"""
try:
... | 42,464 |
def get_camera_intrinsic_parameters(stub):
""" Get camera intrinsic params from gprc detection server. """
request = detection_server_pb2.Empty()
try:
response = stub.GetCameraIntrinsicParameters(request)
return response
except grpc.RpcError as err:
logger.error(err.details()) #p... | 42,465 |
def update_local_pool(online_pool) -> None:
"""
更新本地卡池文件, 并备份原卡池
"""
# 读取本地卡池
with open(local_pool_path, 'r', encoding='utf-8') as lf:
local_pool = json.load(lf)
# 备份本地卡池
logger.info(f'开始备份本地卡池')
with open(local_pool_backup_path, 'w', encoding='utf-8') as backup:
json.du... | 42,466 |
def remove_boot_record(boot_num):
"""Remove an EFI boot record with efibootmgr.
:param boot_num: the number of the boot record
"""
utils.execute('efibootmgr', '-b', boot_num, '-B') | 42,467 |
def version_strategy(version: str) -> AwesomeVersionStrategy:
"""Return the version stragegy."""
if is_buildver(version):
return AwesomeVersionStrategy.BUILDVER
if is_calver(version):
return AwesomeVersionStrategy.CALVER
if is_semver(version):
return AwesomeVersionStrategy.SEMVER... | 42,468 |
def get_name_from_path(path):
""" Parses a directory in 'mgmt_<name> ' format into the camel case name used by ARM. The
directory name should be in snake case. """
while path:
path, item = os.path.split(path)
if 'mgmt_' in item:
return snake_to_camel(item.replace('mgmt_', '', 1))... | 42,469 |
def get_transcript_name(ids):
"""Get transcript name."""
return _search(transcript_name_re, ids) | 42,470 |
def rank_items(ratings, similarities):
"""
(アイテムのインデックス, 予測した評価値)のタプルリストをランキング(評価値の降順ソート)で返す
"""
ranking = [ ]
for i, r in enumerate(ratings):
if r != -1:
continue
ranking.append((i, predict_rating(ratings, i, similarities)))
return sorted(ranking, key=lambda r: r[... | 42,471 |
def hex2(n, uppercase=True):
"""
Return 2 characters corresponding to the hexadecimal representation of `n`.
:param n: 0 <= int < 256
:param uppercase: bool
:return: str (length == 2)
"""
assert isinstance(n, int)
assert 0 <= n < 256
assert isinstance(uppercase, bool), type(upperca... | 42,472 |
def test(ctx):
"""
Run the playbook
:param ctx: context object
:return: None
"""
os.chdir('tests/')
test_case_list = glob.glob('*.py')
for test_case in test_case_list:
ctx.run(
"ANSIBLE_PRIVATE_KEY_FILE={0} ANSIBLE_REMOTE_USER={1} pytest {2} -s -v --gherkin-terminal-r... | 42,473 |
async def async_remove_entry(hass, config_entry):
"""Handle removal of an entry."""
try:
await hass.config_entries.async_forward_entry_unload(config_entry, PLATFORM)
_LOGGER.info("Successfully removed sensor from the Deeds integration")
except ValueError:
pass | 42,474 |
def test_register_internal(plugin_manager):
"""Tests registration of internal flaskbb plugins."""
class A(object):
pass
a1, a2 = A(), A()
plugin_manager.register(a1, "notinternal")
plugin_manager.register(a2, "internal", internal=True)
assert plugin_manager.is_registered(a2)
out = ... | 42,475 |
def get_split_statistics(filepath):
"""
Computes the label frequency, amount of utterances and tokens for a
preprocessed tsv file.
"""
label_freq = defaultdict(int)
amount_tokens = 0
with open(filepath, 'r') as file:
reader = csv.DictReader(file, delimiter='\t')
for li... | 42,476 |
def test_complex_pattern_call():
"""Ensure ComplexPattern calling (refinement) works as expected."""
Monomer('A', ['w', 'x'], {'x': ('e', 'f')})
Monomer('B', ['y', 'z'], {'z': ('g', 'h')})
cp = A(w=1, x='e') % B(y=1, z='g')
r = {'x': 'f', 'z': 'h'} # refinement for complexpattern
ok_(cp(**r))
... | 42,477 |
def cast_int(value):
"""
Cast value to 32bit integer
Usage:
cast_int(1 << 31) == -1
(where as: 1 << 31 == 2147483648)
"""
value = value & 0xffffffff
if value & 0x80000000:
value = ~value + 1 & 0xffffffff
return -value
else:
return value | 42,478 |
def dense_fast_decode(
src_vocab_size,
trg_vocab_size,
max_in_len,
n_layer,
enc_n_layer,
n_head,
d_key,
d_value,
d_model,
d_inner_hid,
prepostprocess_dropout,
attention_dropout,
relu_dropout,
preprocess_cmd,
... | 42,479 |
def fixed_rotation_objective(link,ref=None,local_axis=None,world_axis=None):
"""Convenience function for fixing the given link at its current orientation
in space.
If local_axis and world_axis are not provided, the entire link's orientation
is constrained.
If only local_axis is provided, the link... | 42,480 |
def chinese_cut(text):
"""
进行中文分词
:param text: 中文数据
:return: 分词后的数据
"""
return ' '.join(jieba.cut(text)) | 42,481 |
def bottleneck_block_(inputs,
filters,
is_training,
strides,
use_projection=False,
pruning_method='baseline',
init_method='baseline',
data_format='channels_first',
... | 42,482 |
def main():
""" Main function for the polynomial synthetic data experiment.
"""
### Experiments with polynomials:
_ = polynomial_experiment(scm_polynomial_thresholding_first, "./experiments/results/roc_polynomials_first.png")
_ = polynomial_experiment(scm_polynomial_thresholding_second, "./experimen... | 42,483 |
def WaitForOperation(client, operation_ref, message):
"""Waits until the given operation finishes.
Wait loop terminates when the operation's status becomes 'DONE'.
Args:
client: interface to the Cloud Updater API
operation_ref: operation to poll
message: message to be displayed by progress tracker
... | 42,484 |
def ifloordiv():
"""//=: Inplace floor divide operator."""
class _Operand:
def __init__(self):
self.value = ''
def __ifloordiv__(self, other):
self.value = "int(val/{})".format(other)
return self
item = _Operand()
item //= 2
return item.value | 42,485 |
def send_async_email(app, msg):
"""
Restore Flask's application context
and send email via flask_mail's Mail instance.
"""
with app.app_context():
mail.send(msg) | 42,486 |
def search_custom_results(result_id):
"""
Search a result for predictions.
request['maxPredictionSort'] - when true sort by max prediction
request['all'] - include values in download
request['page'] - which page of results to show
request['perPage'] - items per page to show
:param result_id:... | 42,487 |
def create_1_layer_ANN_classification(
input_shape,
num_hidden_nodes,
num_classes,
activation_function='relu'
):
"""
Creates a 1 layer classification ANN with the keras backend.
Arguments:
input_shape (int tuple): The shape of the input excluding batch.
num_hidden_nodes (i... | 42,488 |
def unsqueeze(x, axis, name=None):
"""
:alias_main: paddle.unsqueeze
:alias: paddle.unsqueeze, paddle.tensor.unsqueeze, paddle.tensor.manipulation.unsqueeze
Insert single-dimensional entries to the shape of input Tensor ``x``. Takes one
required argument axis, a dimension or list of dimensions that will ... | 42,489 |
def test_flow_affine():
"""Test if Flow inheritance requirements are preserved.
We'll run all Flow functions with the modules.AffineFlow flow.
If flow.Flow has changed, AffineFlow should stop working.
"""
weight = torch.ones(1, 1) * 2
flow = AffineFlow(weight=weight)
x = torch.ones(1, 1)
... | 42,490 |
def get_kills_info_player_match(player_id,match_id,prt=False):
"""
get ONE player in ONE match's kills information
:param player_id:
:param match_id:
:param prt:
:return: list of kill information
"""
info = get_player_info_match_id(player_id,match_id)
info_kills = {}
if('hero_kil... | 42,491 |
def update_args(args: Dict, inv_file: str, conf_file: str) -> Dict:
""" Add inventory file and config file in the correct spots inside the
arguments
Args:
args (Dict): controller args
inv_file (str): inventory file
conf_file (str): config file
Returns:
Dict: updated arg... | 42,492 |
def _add_vessel_class(df):
"""Creates 'Class' column based on vessel LOA ft."""
df.loc[:, "Class"] = "Panamax"
post_row = (df.loc[:, "LOA ft"] > 965)
post_loc = df.loc[post_row, :].index
post_pan = df.index.isin(post_loc)
df.loc[post_pan, "Class"] = "Post-Panamax"
return df | 42,493 |
def async_generate_ptr_query(ip):
"""Generate a ptr query with the next random id."""
return message.make_query(ip.reverse_pointer, rdatatype.PTR) | 42,494 |
def masked_within_block_local_attention_1d(q, k, v, block_length=64, name=None):
"""Attention to the source and a neighborhood to the left within a block.
The sequence is divided into blocks of length block_length. Attention for a
given query position can only see memory positions less than or equal to the
que... | 42,495 |
def catch_all(path):
"""
Repeats the request to the latest version of default service by
replacing all occurrences of the hostname to the new_host defined
above. The replacement happens for:
- URL and URL query string
- Headers, including cookie headers
- The body, if we can decode it.... | 42,496 |
def main(model_to_run, dataset_name, task, verbose=False):
"""
Takes model, dataset combination as input as well as classification or regression task and runs the respective
model training and evaluation as well as calculating/averaging the metrics at the end.
Sets the random state to 1 and n_fold for C... | 42,497 |
def bulk_process(
debug = False, number_of_cycles_before_rate_analysis = 10, cell_ids = None,
):
"""
TEMPDOC
first calls process_single_file then, calls process_cell_id
"""
if cell_ids is None:
errors = list(
map(
lambda x: process_single_file(x, debug),
... | 42,498 |
def refresh_asset_cache(id, asset, action, remote_id=None):
""" Perform asset cache add or update depending on action provided.
"""
try:
if action == 'create':
asset_cache_add(id, asset)
elif action == 'update':
update_asset_cache(id, asset, remote_id)
else:
... | 42,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.