content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def validate(number):
"""Check if the number provided is a valid NCF."""
number = compact(number)
if len(number) != 19:
raise InvalidLength()
if number[0] not in 'AP' or not number[1:].isdigit():
raise InvalidFormat()
if number[9:11] not in (
'01', '02', '03', '04', '11',... | 5,303,700 |
def pressure_broad_coefs(Te):
"""
Defines the values of the constants :math:`a` and :math:`\\gamma` that go into the collisional broadening formula
of Salgado et al. (2017).
:param Te: Electron temperature.
:type Te: float
:returns: The values of :math:`a` and :math:`\\gamma`.
:rtype: l... | 5,303,701 |
def parse_sources(sources: dict) -> Union[SourcesV1, SourcesV2, SourcesV3]:
"""Parse sources.json
Args:
sources: A dict of sources.json
Returns:
Union[SourcesV1, SourcesV2, SourcesV3]
"""
dbt_schema_version = get_dbt_schema_version(artifact_json=sources)
if dbt_schema_version =... | 5,303,702 |
def _get_indices_from_highest(highest_indices):
"""Return a list of coordinates from a set of highest indices.
Parameters
----------
highest_indices : list, tuple, or numpy.ndarray
Highest indices to consider.
Returns
-------
indices : numpy.ndarray
An array of indices sort... | 5,303,703 |
def reports_ovc_rawdata(request):
"""Method to do adhoc pivot reports."""
try:
ext = 'Pivot'
# time_now = int(datetime.now().strftime('%H'))
user_id = request.user.id
report_variables = get_variables(request)
if request.method == 'POST':
ext = request.... | 5,303,704 |
def get_buggy_path(error_path):
"""
return list buggy path.
"""
error_path_list = []
f = open(error_path, 'r')
lines = f.readlines()
for line in lines:
if '---' in line:
path = line.split('::')
buggy_path = path[0].split('---')[-1].strip().replace('.', '/')
... | 5,303,705 |
def get_config(arguments=None, events=None):
"""
Retruns a pre-formatted configuration block for supervisor
"""
if arguments is None:
arguments = ''
if events is None:
events = 'PROCESS_STATE'
configuration_string = '''
[eventlistener:logstash-notifier]
command = ./logstash_not... | 5,303,706 |
def sieve_of_eratosphenes(n: int) -> list[int]:
"""
Finds prime numbers <= n using the sieve of Eratosphenes algorithm.
:param n: the upper limit of sorted list of primes starting with 2
:return: sorted list of primes
Integers greater than 2 are considered good input that gives
meaningful ... | 5,303,707 |
def owf_exit(owf_instance, *args):
"""
Quit Octowire framework.
:param owf_instance: Octowire framework instance (self).
:param args: Varargs command options.
:return: Nothing
"""
# TODO: close everything before exit
exit(0) | 5,303,708 |
def load_test_set(
filename=DATA_FILE,
add_target=True,
target_species=DEFAULT_TARGET):
"""Load the test set"""
df = load_data(filename, add_target, target_species)
train, test = get_train_test_split(df)
return test | 5,303,709 |
def create_observation(host_since, property_type, room_type, accommodates,
bathrooms, bed_type, cancellation_policy, cleaning_fee,
city, host_identity_verified, instant_bookable,
review_scores_rating, zipcode, bedrooms, beds,
n_... | 5,303,710 |
def gibbs_sampling_inference(factor_graph: FactorGraph,
sample_pool: List[Tuple[int]],
num_samples: int, init_temp: float,
anneal_rate: float, min_temp: float,
metric: Callable[[List[int]],
... | 5,303,711 |
def __get_arguments():
"""Parse command line arguments"""
argument_parser = argparse.ArgumentParser(
description='Handle YAML and JSON config files')
argument_parser.add_argument(
'-v', '--verbose',
action='store_true',
help='Verbose output')
subparsers = argument_parser.... | 5,303,712 |
def update_ansible_vars(version: Tuple[str, str, str], dry_run: bool = False) -> Optional[str]:
"""
Updates the ansible project variables file with the new release number
:param version: Release number tuple (major, minor, release)
:param dry_run: If `True`, no operation performed
:return: changed ... | 5,303,713 |
def net():
"""Run all network tests"""
suite = ServiceTestSuite()
suite.addTest(unittest.makeSuite(AttributeTestCase, 'test_net'))
return suite | 5,303,714 |
def xor_decipher(text, key):
"""
Decipher a message using XOR.
text -- a list of integers corresponding to the ASCII value of characters.
key -- a list of characters used as keys.
"""
deciphered = []
key_length = len(key)
key_ascii = [ord(_k) for _k in key]
for i, _ascii in enumerate... | 5,303,715 |
def itkElastix_MDR_coregistration(target, source, elastix_model_parameters, image_parameters):
"""
This function takes unregistered source image and target image as input
and returns ffd based co-registered image and corresponding deformation field.
"""
shape_source = np.shape(source)
... | 5,303,716 |
def _create_signed_certificate(ca_cert, ca_key, name, valid_days=365, type='client', **kwargs):
"""
Creates signed cert of type provided and signs it with ca_key provided. To create subject for the new certificate
common name is set new value, rest of the attributes are copied from subject of provided ca ce... | 5,303,717 |
def _get_expanded_variable_list(var_list):
"""Given an iterable of variables, expands them if they are partitioned.
Args:
var_list: An iterable of variables.
Returns:
A list of variables where each partitioned variable is expanded to its
components.
"""
returned_list = []
for variable in var_l... | 5,303,718 |
def get_terminal_size() -> (int, int):
"""
Get size of the terminal in symbols and lines.
:return: height (lines), width (symbols)
"""
def ioctl_GWINSZ(fd):
try:
import fcntl, termios, struct, os
cr = struct.unpack(
"hh", fcntl.ioctl(fd, termios.TIOCG... | 5,303,719 |
def update_created(timestamp):
"""
Updates the creation timestamp for the SADFace document to the supplied timestamp.
This can be useful when moving analysed argument data between formats whilst
maintaining original metadata.
"""
sd["timestamp"] = timestamp | 5,303,720 |
def name_generator(size=9, chars=string.ascii_uppercase + string.digits):
"""
this method is for generating a randndom name for the downloaded files
@param size: number of random characters
@param chars: type of the random characters
"""
return ''.join(random.choice(chars) for x in range(size)) | 5,303,721 |
def recovery_secret_to_ksk(recovery_secret):
"""Turn secret and salt to the URI.
>>> recovery_secret_to_ksk("0123.4567!ABCD")
'KSK@babcom-recovery-0123.4567!ABCD'
"""
if isinstance(recovery_secret, bytes):
recovery_secret = recovery_secret.decode("utf-8")
# fix possible misspellings... | 5,303,722 |
def test_codepoint_text():
""" Test case of extracting the correct sentence text using codepoints """
text = 'Unban mox opal 🐱. This is a second sentence.'
with corenlp.CoreNLPClient(annotators=["tokenize","ssplit"],
properties={'tokenize.codepoint': 'true'}) as client:
... | 5,303,723 |
def plot_beta_by_type(beta_df, probe_type='all', return_fig=False, silent=False, on_lambda=False):
"""compare betas for type I and II probes -- (inspired by the plotBetasByType() function)
Plot the overall density distribution of beta values and the density distributions of the Infinium I or II probe types
1 distr... | 5,303,724 |
def validate_end_date(ctx, param, value):
"""
Validator for the 'click' command line interface, checking whether the entered date as argument 'start_date' is
later than argument 'end_date' and 'end_date' argument is later than current date.
"""
# option when the user enters the '--end_date' paramete... | 5,303,725 |
def transform_uppercase(val, mode=None):
"""
Convert to uppercase
<dotted>|uppercase string to uppercase
<dotted>|uppercase:force string to uppercase or raises
"""
try:
return val.upper()
except TypeError:
if mode == 'force':
raise
return v... | 5,303,726 |
def get_installer_packages(installer_dirs):
"""
Returns a list of nipkg files in the provided directories.
:param installer_dirs: List of directories containing nipkgs.
:return The list of nipkg files.
"""
installers = []
for dir in installer_dirs:
packages = glob.glob(join(dir... | 5,303,727 |
def test_unify_preconds_effects_options():
"""Tests for unify_preconds_effects_options()."""
# The following test checks edge cases of unification with respect to
# the split between effects and option variables.
# The case is basically this:
# Add set 1: P(a, b)
# Option 1: A(b, c)
# Add se... | 5,303,728 |
def receive():
"""Receive file over TCP socket."""
port, size = get_config()
host_ip = sock.gethostbyname(sock.gethostname())
debug('Binding receiver to %s:%d', host_ip, port)
with sock_manager(sock.socket(sock.AF_INET, sock.SOCK_STREAM)) as receiver:
receiver.bind((host_ip, port))
r... | 5,303,729 |
def get_H2_surface_density_error(co_error: np.array, inclination: int) -> np.array:
"""Calculate the error on the H2 surface density from the CO emission maps from Heracles, this follows Leroy, et al. 2008/2009
Args:
co_error (np.array): error on the CO emission in [K km/s]
inclination (int): i... | 5,303,730 |
def setup_lattice(prm, fol):
"""Store the lattice BDDs in `prm`."""
log.info('partial order')
u_leq_p, p_leq_u = partial_order(prm._px, fol)
log.info('subseteq')
p_leq_q = subseteq(prm._varmap, fol)
log.info('eq')
p_eq_q = eq(prm._varmap, fol)
pq_vars = prm.p_vars.union(prm.q_vars)
a... | 5,303,731 |
def _copy_object(obj: Mapping):
"""
Performs a deep copy of a Mapping.
Converts to a basic dict to avoid problems with kopf Body mapping type.
Pykube expects json-serializable types, i.e. basic types.
"""
new_obj = deepcopy(dict(obj))
for key in [
"resourceVersion",
"selfLink... | 5,303,732 |
def quick_run(time_to_pause: Number):
"""
Only run the application for the specified time in seconds.
Useful for unit testing or continuous integration (CI) testing
where there is no user interaction.
:param Number time_to_pause: Number of seconds to pause before automatically
closing.
... | 5,303,733 |
def dmoist_bdz(th, th_ref, p, q_v, q_cl, z, zn, thresh = 1.0e-5):
"""
Vertical Gradient of (buoyancy including cloud condensation).
Derived variable name: dmoist_bdz
MONC approximation.
This is db/dz with b = beta_t theta_l + beta_q q_t.
Note - not to be used for vertical buoyancy flux.
P... | 5,303,734 |
def tag_list(page=None):
"""
标签列表
"""
if page is None:
page = 1
page_data = Tag.query.order_by(
Tag.addtime.desc()
).paginate(page=page, per_page=3)
return render_template('admin/tag_list.html', page_data=page_data) | 5,303,735 |
def test092():
"""
Check that a bad apiVersion/kind raises a RuntimeError
"""
try:
docs = load_full_yaml(path="bad.yaml")
assert False, f"num docs: {len(docs)}"
except RuntimeError:
pass | 5,303,736 |
def audit_permission(ctx, server, username, password):
"""Audit user permission"""
# TODO | 5,303,737 |
def login(username, password):
"""登录网易云音乐账号,支持邮箱和手机登录
Args:
username (str): 手机号或邮箱地址
password (str): 密码
"""
if not api.profile:
api.login(username, password)
rich.print(f'登录成功! [bold magenta]{api.profile.nickname}[/bold magenta]') | 5,303,738 |
def _parse_handler(handler: Union[callable, object, Subscriber]):
"""Parse handler name and body.
Function accept functions, callable object and instance of Subscriber.
If Subscriber has been given, parser will extract its name and handler.
:param handler: Function or callable object.
:type handle... | 5,303,739 |
def test_get_all_of_time():
"""Test for bwaw.insights.data.get_all_of_time"""
all_dates = np.array(['2021-02-01 12:30:00',
'2021-02-01 13:30:00',
'2021-02-01 14:30:00']).astype('datetime64[ns]')
proper_input = pd.DataFrame(all_dates, columns=['Time'])
... | 5,303,740 |
def string_pair_list_to_dictionary_no_json(spl):
"""
Covert a mongodb_store_msgs/StringPairList into a dictionary, ignoring content
:Args:
| spl (StringPairList): The list of (key, value) to pairs convert
:Returns:
| dict: resulting dictionary
"""
return dict((pair.first, pair.s... | 5,303,741 |
def sanitize(inStr):
"""Hide any sensitive info from the alert"""
# Key-value pairs of patterns with what to replace them with
patterns = {
"https\:\/\/oauth2\:[\d\w]{64}@gitlab\.pavlovia\.org\/.*\.git": "[[OAUTH key hidden]]" # Remove any oauth keys
}
# Replace each pattern
for pattern,... | 5,303,742 |
def str2dict(s):
"""Convert a "foo=bar, blah=baz" type string into a dictionary"""
if type(s) not in (str, unicode):
s = str(s)
d = {}
for kv in [[x.strip() for x in i.split('=', 1)] for i in s.split(',')]:
if (len(kv[0]) > 0) and (len(kv[1]) > 0):
d[kv[0]] = kv[1]
retur... | 5,303,743 |
def get_techniques_of_tactic(tactic, techniques):
"""Given a tactic and a full list of techniques, return techniques that
appear inside of tactic
"""
techniques_list = []
for technique in techniques:
for phase in technique['kill_chain_phases']:
if phase['phase_name'] == tact... | 5,303,744 |
def unabc(msg):
"""
Add dummy methods to a class to satisfy abstract base class constraints.
Usage::
@unabc
class NotAbstract(SomeAbstractClass):
pass
@unabc('Fake {}')
class NotAbstract(SomeAbstractClass):
pass
"""
# Handle the possibility... | 5,303,745 |
def extract_logic_free_variables(expression):
"""Extract variables from expression assuming it's in logic format.
Parameters
----------
expression : Expression
Returns
-------
OrderedSet
set of all free variables in the expression.
"""
efvw = ExtractFreeVariablesWa... | 5,303,746 |
def inNativeByteOrder(im):
""" Put image in native byte order."""
if ((im.dtype.byteorder=='<') & (sys.byteorder=='big')) | ((im.dtype.byteorder=='>') & (sys.byteorder=='little')):
return im.byteswap(inplace=True).newbyteorder()
else:
return im | 5,303,747 |
def train_val_test_split_adjacency(A, p_val=0.10, p_test=0.05, seed=0, neg_mul=1,
every_node=True, connected=False, undirected=False,
use_edge_cover=True, set_ops=False, asserts=False):
"""
Split the edges of the adjacency matrix into train, ... | 5,303,748 |
def get_status(invocation_id):
"""check status
:param invocation_id: Id of image-building Invocation
:type invocation_id: str
:rtype: Invocation
"""
logger.debug(f"Checking status for invocation with ID {invocation_id}")
inv = invocation_service.load_invocation(invocation_id)
if not in... | 5,303,749 |
def test_dishmaster_conforms_to_dishmaster_spec():
"""Check that dishmaster device conforms to dishmaster specification"""
request_headers = get_job_token_header()
if request_headers:
logging.info("Using job token")
with NamedTemporaryFile(mode="wb") as tmp_file:
spec_response = request... | 5,303,750 |
def odia_to_other_lang(text: str, dest_language_code: str = "en") -> str:
"""Translate from Odia to other language"""
return _hit_google_api(text, "or", dest_language_code) | 5,303,751 |
def _invoke_with_properties(callable_obj, all_props, environ, prop_defs,
arg_names, **additional_args):
"""Internal version of invoke_with_properties.
The main difference is it gets passed the argument names as `arg_names`.
This allows us to reuse this logic elsewhere, without definin... | 5,303,752 |
def initial_time():
"""
Real Name: b'INITIAL TIME'
Original Eqn: b'1960'
Units: b'Year'
Limits: (None, None)
Type: constant
b'The initial time for the simulation.'
"""
return 1960 | 5,303,753 |
def test_get_user_id_by_name_user_not_found(get_config_mock, slack_api):
"""
Check that UserNotFoundException will be raised under expected conditions.
"""
get_config_mock.return_value = {'smtp': {'mail_address': 'redhat.com'}}
slack_api.mock_slack_client.return_value\
.users_lookupByEmail.s... | 5,303,754 |
def trac_delete_trac_for_object(sender, instance, **kwargs):
"""
Delete a matching trac when an instance object is deleted.
"""
tracs = util.trac_get_tracs_for_object(obj=instance)
for trac in tracs:
trac.delete() | 5,303,755 |
def _run():
"""Plots performance diagram on testing data.
This is effectively the main method.
"""
_, axes_object = pyplot.subplots(
1, 1, figsize=(FIGURE_WIDTH_INCHES, FIGURE_HEIGHT_INCHES)
)
model_eval_plotting.plot_performance_diagram(
axes_object=axes_object, pod_by_thresh... | 5,303,756 |
def get_y_eval(dataset_id):
"""
retrieves the y value of the eval set
:param dataset_id: id of the dataset
:return: y values
"""
#
return pickle.load(open(get_dataset_folder(dataset_id) + '/y_eval.pkl', 'rb')) | 5,303,757 |
def test_dict_merge_take_right_deep():
"""Check if editing a nested dict has effects on the merged one."""
a = {"1": {"2": [0, 1, 2]}}
b = {"2": "3"}
merged = dict_merge(a, b, merge_method="take_right_deep")
a["1"]["2"].append(42)
assert 42 not in merged["1"]["2"] | 5,303,758 |
def main():
"""Scripty bits"""
t0 = time.time()
kwargs = parse_args()
if "histo_data_dir" in kwargs:
histo_data_dir = expand(kwargs["histo_data_dir"])
if basename(histo_data_dir) != "histo_data":
histo_data_dir = join(histo_data_dir, "histo_data")
kwargs["histo_data... | 5,303,759 |
def bh(app):
"""Bashhub Search"""
app.post_run = post_run_exception_handling
limit = app.params.number
query = app.params.query
system_name = BH_SYSTEM_NAME if app.params.system else None
path = os.getcwd() if app.params.directory else None
session_id = app.params.session
# By default s... | 5,303,760 |
def _gre_setitem_ ( graph , ipoint , point ) :
""" Set the point in Graph
>>> graph = ...
>>> graph[4] = x,y
"""
#
if not ipoint in graph : raise IndexError
if not 2 == len ( point ) :
raise AttributeError("Invalid dimension of 'point'")
x = VE ( point[0] )
v = ... | 5,303,761 |
def CalculateDescendingEnumerationIndex(graph, method):
"""
Calculate the enumeration index in an ascending fashion
@param graph: an input graph to determine the enumeration indices
@param method: the method for determining enumeration order
"""
# create a mapping from vertex indices to the nei... | 5,303,762 |
def spk14b(
handle: int,
segid: str,
body: int,
center: int,
framename: str,
first: float,
last: float,
chbdeg: int,
) -> None:
"""
Begin a type 14 SPK segment in the SPK file associated with
handle. See also :func:`spk14a` and :func:`spk14e`.
https://naif.jpl.nasa.gov/p... | 5,303,763 |
def sourcecontrol_repos_repo_id_refs_get(repo_id): # noqa: E501
"""sourcecontrol_repos_repo_id_refs_get
# noqa: E501
:param repo_id: Source control repository identifier
:type repo_id: str
:rtype: None
"""
return 'do some magic!' | 5,303,764 |
def duration_offpeak(
ts_left: Union[pd.Timestamp, pd.DatetimeIndex], freq: str = None
) -> Union[Q_, pd.Series]:
"""
Total duration of offpeak periods in a timestamp.
See also
--------
.tools.stamps.duration
"""
return duration_base(ts_left, freq) - duration_peak(ts_left, freq) | 5,303,765 |
def truncate_labels(labels):
"""
(1) replacing row[0] by 10, and move it to the last of row
(2) replace the second 10 by -1 row wise
"""
def do_one_row(row):
erase = False
for i, _ in enumerate(row):
if erase:
row[i] = -1
else:
... | 5,303,766 |
def test_referrer():
""" Test referrer. """
l = Link("https://made.ua")
referrer = "https://example.com"
l.add_referrer(referrer)
l.add_referrer(referrer)
assert referrer in l.get_referrers() | 5,303,767 |
def sample(problem, N, calc_second_order=True, seed=None, skip_values=1024):
"""Generates model inputs using Saltelli's extension of the Sobol' sequence.
Returns a NumPy matrix containing the model inputs using Saltelli's sampling
scheme. Saltelli's scheme extends the Sobol' sequence in a way to reduce... | 5,303,768 |
def create_wall(obj_name, document):
"""Create a wall."""
obj = document.addObject('Part::FeaturePython', obj_name)
origin = document.addObject('App::Origin', 'WallOrigin')
Wall(obj, origin)
WallViewProvider(obj.ViewObject)
return obj | 5,303,769 |
def prepare_roi(image5d, roi_size, roi_offset):
"""Extracts a region of interest (ROI).
Calls :meth:`prepare_subimage` but expects size and offset variables to
be in x,y,z order following this software's legacy convention.
Args:
image5d: Image array as a 5D array (t, z, y, x, c), or 4D if
... | 5,303,770 |
def get_model_summary(model, *input_tensors, item_length=26, verbose=False):
"""
:param model:
:param input_tensors:
:param item_length:
:return:
"""
summary = []
ModuleDetails = namedtuple(
"Layer", ["name", "input_size", "output_size", "num_parameters", "multiply_adds"])
hooks = []
layer_instances = {}
... | 5,303,771 |
def test_no_dependencies():
"""
run dependency-less tasks (with threads)
"""
from arbiter.async import run_tasks
executed_tasks = set()
def make_task(name, dependencies=(), should_succeed=True):
"""
Make a task
"""
from arbiter.task import create_task
f... | 5,303,772 |
def create_pandaset_infos(dataset_cfg, class_names, data_path, save_path):
"""
Create dataset_infos files in order not to have it in a preprocessed pickle
file with the info for each sample
See PandasetDataset.get_infos for further details.
"""
dataset = PandasetDataset(dataset_cfg=dataset... | 5,303,773 |
def decode(s):
"""
Deserialize a DMRS object from a DMRS-JSON string.
"""
return from_dict(json.loads(s)) | 5,303,774 |
def cross_multiply_array(array_1, array_2=None, axis=0):
"""Cross multiply the arrays along the given axis.
Cross multiplies along axis and computes array_1.conj() * array_2
if axis has length M then a new axis of size M will be inserted directly succeeding the original.
Parameters
----------
... | 5,303,775 |
def Create(
allow_multiple=True,
) -> Union[ZeroOrMorePhraseItem, OptionalPhraseItem]:
"""\
('@' <name> <<Arguments>>? <newline>?)*
- or -
('@' <name> <<Arguments>>? <newline>?)? # If 'allow_multiple' is False
"""
phrase_item = PhraseItem.Create(
name="At... | 5,303,776 |
def return_largest_region(image_bin):
"""Returns the largest region in the input image.
Parameters
----------
image_bin : (M, N) ndarray
A binary image.
Returns
-------
image_bin : (M, N) ndarray
The input binary image containing only the largest region.
"""
props =... | 5,303,777 |
def config_import(path_list, file_regex, namespace = "__main__",
raise_on_fail = True):
"""Import Python [configuration] files that match file_regex in any of
the list of given paths into the given namespace.
Any symbol available to the current namespace is available to the
configurat... | 5,303,778 |
def com_google_fonts_check_cmap_alien_codepoints(ttFont, config):
"""Check no PUA or Surrogate Pair codepoints encoded"""
pua = []
surrogate = []
for cp in ttFont.getBestCmap().keys():
if ((0xE000 <= cp <= 0xF8FF) or
(0xF0000 <= cp <= 0xFFFFD) or
(0x100000 <= cp <= 0x10FF... | 5,303,779 |
def stretchedAmplitude(TA_file, pol_time, peak_min, peak_max, time_zero=None):
"""Takes in TA data and picks out the peak for the polaron state and returns
the average value so it can be used for fitting function. Must make sure to
pick the right energy range, peak_min and max are in eV."""
TA = n... | 5,303,780 |
def _write_rollup_config(
ctx,
root_dir,
filename = "_%s.rollup.conf.js",
downlevel_to_es2015 = False):
"""Generate a rollup config file.
Args:
ctx: Bazel rule execution context
root_dir: root directory for module resolution (defaults to None)
filename: output ... | 5,303,781 |
def raw_images_to_array(images):
"""
Decode and normalize multiple images from tfrecord data
:param images: list of images encoded as a png in a string
:return: a numpy array of size (N, 56, 56, channels), normalized for training
"""
image_list = []
for image_str in images:
image = d... | 5,303,782 |
def set_translations_files_path(full_path, flat_build=False, build_architecture=""):
"""
This function is used to define the access path to the translation files.
Args:
- full_path (required): The full path to the folder containing the uncompiled translation files
- flat_build (optional): Pu... | 5,303,783 |
def create_model(model: str, config: Dict) -> object:
"""
Creates a model with a given configuration
Args:
model (str): name of the model
config (dict): dictionary of parameters
Returns:
(object): created model (HHVAEM, HMCVAEM, ...)
"""
if model=='VAE':
model =... | 5,303,784 |
def make_positions(tensor, padding_idx, onnx_trace=False):
"""Replace non-padding symbols with their position numbers.
Position numbers begin at padding_idx+1. Padding symbols are ignored.
"""
mask = tensor.ne(padding_idx).long()
return torch.cumsum(mask, dim=1) * mask + padding_idx | 5,303,785 |
def get_song_list(playlist_url):
"""
This function get the song list in the form of "name creator" from the spotify page
"""
# validating the data
if not playlist_url.startswith("https://open.spotify.com"):
print("this is not a spotify url")
return []
elif playlist_url == "https... | 5,303,786 |
def makeTestSuiteV201101():
"""Set up test suite using v201101.
Returns:
TestSuite test suite using v201101.
"""
suite = unittest.TestSuite()
suite.addTests(unittest.makeSuite(CustomTargetingServiceTestV201101))
return suite | 5,303,787 |
def sbol2genbank():
"""Convert an SBOL3 file to a GenBank file"""
parser = argparse.ArgumentParser()
parser.add_argument('input_file', help='Genetic design file used as input')
parser.add_argument('-o', '--output', dest='output_file', default='out',
help='Name of output file to b... | 5,303,788 |
def add_bond_features(X_df):
"""
Using the information about standard C-H,N-H and O-H bond distances, we compute features
which aims to find a notion of deviation from the expected bond distances.
"""
assert len(set(['atom_1', 'atom_0', 'x_0', 'x_1', 'y_0', 'y_1', 'z_0', 'z_1']) - set(X_df.columns))... | 5,303,789 |
def port_to_ip_mapping(index):
"""
A user defined mapping port_id (kni) to ipv4.
"""
return {"vEth0_{}".format(index): "192.167.10.{}".format(index + 1)} | 5,303,790 |
def quote():
"""Get stock quote."""
current_userid = session["user_id"]
userbalance = get_userbal(db, current_userid)
userstocks = get_userstock(db, current_userid)
stocklist = get_stocklist(db, stocksid=True, prices=True)
if request.method == "POST":
response = lookup(request.form.get("... | 5,303,791 |
def cleanup_dataframe(df, logger=None):
"""Cleans the dataframe
- strips new lines, double, single quotes; None -> nan, etc
- formats the column names for Bigquery input
"""
if logger:
logger.log_text("Cleaning up the dataframe", severity='INFO')
if df.empty:
logger.log... | 5,303,792 |
def read_text_file_lines(filepath):
"""Reads a single text file into lines, ensuring each line is unicode.
Args:
filepath: The path to a single text file.
Yields:
Each line as unicode text, with left and right whitespace stripped.
"""
# We open in binary mode here to avoid unicode decoding errors. T... | 5,303,793 |
def organize_key(filename):
"""用于sorted的key参数"""
if filename[0:2].upper() == 'AD':
return 0
name = re.findall(r"-([0-9]+[A-Z]*).pdf", filename)[0]
num = get_group_index(filename)
alpha = name.replace(num, '')
if len(alpha) == 1:
return int(num)*100+ord(alpha)-64 # 使用ASCII码,A对应1,... | 5,303,794 |
def launch_svr(X, y, sample_weight=None, kernel='linear', C=1):
"""Fit the classification SVMs according to the given training data.
Parameters
----------
X : array-like, shape (n_samples, n_features)
Training vectors.
y : array-like, shape (n_samples,)
Target values.
sample_weig... | 5,303,795 |
def cancel_candidacy(request, candidacy):
"""Cancel your own, yet-unapproved candidacy."""
user = request.user
cd = get_candidacy(candidacy)
if user != cd.user:
return HttpResponseForbidden(u"Vous ne pouvez annuler que vos propres candidatures.")
m.JournalEntry.log(user, "Cancelled own appli... | 5,303,796 |
def generate_rsa_keys(prime_lenth=4):
"""Return tuple of (open, close, mod)"""
start = 10 ** (prime_lenth-1)
end = (10 ** (prime_lenth)) - 1
p, q = get_generate_prime_pair(start=start, end=end)
n = p * q
print("p: {} q: {}".format(p, q))
print("n: {}".format(n))
euler = (p - 1)*(q ... | 5,303,797 |
def cache_by_hashed_args(obj):
""" Decorator for caching a function values
.. deprecated:: v0.9.8.3
:func:`cache_by_hashed_args` will be removed in pyGSTi
v0.9.9. Use :func:`functools.lru_cache` instead.
"""
return lru_cache(maxsize=128)(obj) | 5,303,798 |
def setBadRegions(exposure, badStatistic="MEDIAN"):
"""Set all BAD areas of the chip to the average of the rest of the exposure
Parameters
----------
exposure : `lsst.afw.image.Exposure`
Exposure to mask. The exposure mask is modified.
badStatistic : `str`, optional
Statistic to us... | 5,303,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.