content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def astToMongo(ast):
"""Run the AST-to-mongo helper function after converting it to a not-free equivalent AST."""
return _astToMongo_helper(_eliminate_not(ast)) | 27,300 |
async def aliases() -> None:
"""\
Custom command aliases
======================
Aliases provide a way to abbreviate system commands and
add default arguments to commonly used commands.
Aliases are described in user-config files
(see `neuro help user-config` for details).
`~/.neuro/use... | 27,301 |
def write_seqs_fasta(out_fp_seqs_fasta: str, out_fp_seqs_qza: str,
tsv_pd: pd.DataFrame) -> str:
"""
Write the fasta sequences.
:param out_fp_seqs_fasta: output sequences fasta file name.
:param out_fp_seqs_qza: output sequences qiime2 Artefact file name.
:param tsv_pd: table w... | 27,302 |
def f(x,y):
"""
Takes in two numpy arrays that are result of meshgrid.
Returns a numpy array with points representing the iteration number for divergence
"""
max_iter = 100 #maximum number of interations
c = x + 1j*y
z = np.zeros((N,N),dtype=complex)
r = np.zeros((N,N),dtype=int) #return... | 27,303 |
def AMZN_dataprep():
"""
将csv的数据的时间戳改成序号
Returns:
"""
src_file_path = "/Users/seenli/Documents/workspace/code/pytorch_learn2/time_series_DL/Twitter_volume_AMZN.csv"
tar_file_path = "/Users/seenli/Documents/workspace/code/pytorch_learn2/time_series_DL/Twitter_volume_AMZN_num.csv"
tar_file = ... | 27,304 |
def _expand_param_name(param: BaseDescriptor) -> List[str]:
"""
Get expanded param names
:param param: The param to expand
"""
if not getattr(param, 'expand', False):
raise ValueError('Cannot expand param that does not have the expand kwarg')
new_arg_names = _get_expanded_param_names(pa... | 27,305 |
def accuracy_top_k(output, target, top_k=(1,)):
"""Computes the precision@k for the specified values of k"""
max_k = max(top_k)
batch_size = target.size(0)
_, pred = output.topk(max_k, 1, True, True)
pred = pred.t()
correct = pred.eq(target.view(1, -1).expand_as(pred))
res = []
for k i... | 27,306 |
def softmax(data: NodeInput, axis: int, name: Optional[str] = None) -> Node:
"""Apply softmax operation on each element of input tensor.
:param data: The tensor providing input data.
:param axis: An axis along which Softmax should be calculated. Can be positive or negative.
:param name: Optional name f... | 27,307 |
def get_duts_mac_address(duts):
"""
This is used to get the Duts and its mac addresses mapping
:param duts: List of DUTs
:return : Duts and its mac addresses mapping
"""
duts_mac_addresses = {}
cmd = "show platform syseeprom"
for dut in duts:
if st.is_vsonic(dut):
... | 27,308 |
def crop(sample, crop_area, in_crop_threshold):
"""Crop an image to a given area and transform target accordingly.
Args:
sample: {
"image": PIL.Image,
"bboxes": Numpy array :math:`(N, 4)` (XYXY format),
"keypoints": Numpy array :math:`(N, n, 2)`, (optional)
... | 27,309 |
def delete_if_exists(fname):
"""remove a file if it exists, with a message to stdout
ARGS:
fname (string): full path to the file to be removed
"""
if os.path.exists(fname):
sys.stdout.write('removed {}\n'.format(fname))
sys.stdout.flush()
os.remove(fname)
if os.p... | 27,310 |
def plugin_settings(settings):
"""
Update the LMS/Production (aka AWS) settings to use Figures properly.
Adds entries to the environment settings
You can disable CeleryBeat scheduler for Figures by configuration the
``lms.env.json`` file.
Create or update ``FIGURES`` as a top level key in
... | 27,311 |
def get_cpu_utilization(mqueries, region, days):
"""
Gets CPU utilization for instances
"""
client = SESSION.client('cloudwatch', region_name=region)
time_from = (datetime.now() - timedelta(days=days))
time_to = datetime.now()
response = client.get_metric_data(
MetricDataQueries=m... | 27,312 |
def std_opt_end_independent(policy_net, target_net, optimizer, memory,
batch_size=128, GAMMA=0.99, device='cuda'):
"""
Apply the standard procedure to an ensemble of deep Q network.
"""
if len(memory) < batch_size:
return 0
total_loss = 0
for ens_num in range... | 27,313 |
def scrape_forecast_products() -> Dict[str, Tuple[str, str]]:
""" Get list of forecast products by scraping state overivew pages
"""
logging.info("Scraping list of BOM forecast products")
products = dict()
for state in STATES:
url = f"http://www.bom.gov.au/{state}/forecasts/precis.shtml"
... | 27,314 |
def plate_from_list_spreadsheet(
filename, sheet_name=0, num_wells="infer", wellname_field="wellname"
):
"""Create a plate from a Pandas dataframe where each row contains the
name of a well and metadata on the well.
Parameters
----------
filename
Path to the spreadsheet file.
sheet... | 27,315 |
def frexp(x: float) -> _Tuple[float, int]:
"""Decomposes a value ``x`` into a
tuple ``(m, p)``, such that ``x == m * (2 ** p)``.
Arguments:
x: The value to be decomposed.
Returns:
Tuple of ``m`` and ``p``.
"""
pass | 27,316 |
def main():
"""PE Tree Carve script entry-point"""
# Check command line arguments
parser = ArgumentParser(description="PE-Tree (Carve)")
parser.add_argument("filename", help="Path to file to carve", type=FileType("rb"))
args = parser.parse_args()
# Create PE Tree Qt application
application ... | 27,317 |
def displaced_species_along_mode(species: Species,
mode_number: int,
disp_factor: float = 1.0,
max_atom_disp: float = 99.9) -> Optional[Species]:
"""
Displace the geometry along a normal mode with mode n... | 27,318 |
def constant(pylist, dtype=None, ragged_rank=None, inner_shape=None,
name=None, row_splits_dtype=dtypes.int64):
"""Constructs a constant RaggedTensor from a nested Python list.
Example:
```python
>>> ragged.constant([[1, 2], [3], [4, 5, 6]]).eval()
RaggedTensorValue(values=[1, 2, 3, 4, ... | 27,319 |
def parse_args():
"""Parses command line arguments."""
parser = argparse.ArgumentParser(description='Install cert on device.')
parser.add_argument(
'-n', '--cert-name', default='dummycert', help='certificate name')
parser.add_argument(
'--overwrite', default=False, action='store_true',
help='O... | 27,320 |
def partition(lst, fn):
"""Partition lst by predicate.
- lst: list of items
- fn: function that returns True or False
Returns new list: [a, b], where `a` are items that passed fn test,
and `b` are items that failed fn test.
>>> def is_even(num):
... return num % ... | 27,321 |
def get_page(token, size):
"""Return portion of s3 backet objects."""
if token:
response = client.list_objects_v2(
Bucket=s3_bucket_name,
MaxKeys=size,
Prefix=s3_pbject_prefix,
ContinuationToken=token,
)
else:
response = client.list_obj... | 27,322 |
def get_segment_base_addr_by_proc_maps(pid:int, filename:str=None) -> dict:
"""Read /proc/pid/maps file to get base address. Return a dictionary obtaining keys: 'code',
'libc', 'ld', 'stack', 'heap', 'vdso'.
Args:
pid (int): Pid of process.
filename (str, optional): Filename to get code bas... | 27,323 |
def num_physical_shards_option(f):
"""
Function to parse/validate the --num-physical-shards CLI option to dirbs-db repartition.
:param f: obj
:return: options obj
"""
def callback(ctx, param, value):
if value is not None:
if value < 1 or value > 100:
raise cl... | 27,324 |
def _ls(method_name, ls_type, path=None, log_throwing=True):
"""
Private helper method shared by various API methods
:param method_name: calling method name
:param ls_type: the WLST return type requested
:param path: the path (default is the current path)
:param log_throwing: whether or not to l... | 27,325 |
def serialize_input_str(tx, prevout_n, sequence, script_sig):
"""
Based on project: https://github.com/chaeplin/dashmnb.
"""
s = ['CTxIn(']
s.append('COutPoint(%s, %s)' % (tx, prevout_n))
s.append(', ')
if tx == '00' * 32 and prevout_n == 0xffffffff:
s.append('coinbase %s' % script_s... | 27,326 |
def evidence():
"""
Confirm prohibition number and last name matches VIPS and
applicant business rules satisfied to submit evidence.
"""
if request.method == 'POST':
# invoke middleware functions
args = helper.middle_logic(business.is_okay_to_submit_evidence(),
... | 27,327 |
def skop(p, rule="b3s23"):
"""Return a list of pairs (Pattern, minimum population) representing
the smallest known oscillators of the specified period in the given rule.
Assumes that the local installation of lifelib knows about said rule."""
rule = sanirule(rule)
rmod = import_module(f"..{aliases.g... | 27,328 |
def relabel_nodes_with_contiguous_numbers(graph_nx, start= 0):
"""
Creates a shallow copy
"""
mapping= {n : (idx + start) for idx, n in enumerate(list(graph_nx.nodes()))}
return nx.relabel.relabel_nodes(graph_nx, mapping, copy= True), mapping | 27,329 |
def get_yaml_frontmatter(file):
"""
Get the yaml front matter and the contents of the given file-like object.
"""
line = file.readline()
if line != "---\n":
return (None, line + file.read())
frontmatter = []
for line in file:
if line == "---\n":
break
else... | 27,330 |
def add_permissions():
"""Add Permissions for UAE VAT Settings and UAE VAT Account."""
for doctype in ('UAE VAT Settings', 'UAE VAT Account'):
add_permission(doctype, 'All', 0)
for role in ('Accounts Manager', 'Accounts User', 'System Manager'):
add_permission(doctype, role, 0)
update_permission_property(do... | 27,331 |
def haversine(coordinate1, coordinate2):
"""
returns the distance between two
coordinates using the haversine formula
"""
lon1 = coordinate1['Longitude']
lat1 = coordinate1['Latitude']
lon2 = coordinate2['Longitude']
lat2 = coordinate2['Latitude']
lon1, lat1, lon2, lat2 = map(radia... | 27,332 |
def sine_from_peak(
peak,
num_samples=6000,
sample_duration=0.001,
target_integral=118,
plot=False,
title="Timecourse",
xlabel="Time",
ylabel="Measure",
save_to=None,
delimiter=",",
frequency=1,
xunit="s",
yunit="m",
annotation_x=0.6,
annotation_y=0.9,
):
... | 27,333 |
def f1(R1,R2,R3):
""" f1 switching function """
R01,R02,R03 = 1.160, 1.160, 2.320
alpha1 = 1.0
rho1 = R1 - R01
rho2 = R2 - R02
rho3 = R3 - R03
return 0.5 * (1 - adf.tanh(0.5 * alpha1 * (3*rho1 - rho2 - rho3))) | 27,334 |
def getUser(client, attrs):
"""Get the user, create it as needed.
"""
try:
return client.assertedSearch("User [name='%s']" % attrs['name'])[0]
except icat.SearchResultError:
user = client.new("user")
initobj(user, attrs)
user.create()
return user | 27,335 |
def _fn_pow_ ( self , b ) :
""" Power function: f = pow( a, b ) )
>>> f =
>>> a = f.pow ( b )
>>> a = f ** b
"""
return _fn_make_fun_ ( self ,
b ,
Ostap.MoreRooFit.Power ,
... | 27,336 |
def funder_trans(params):
"""
:param params:
:return:
"""
if 6 > len(params):
LOG.error('funder_trans: Invalid params {}!'.format(params))
return None
selfpubkey = params[0]
otherpubkey = params[1]
addressFunding = params[2]
scriptFunding = params[3]
... | 27,337 |
def get_replacements_by_guid(replacements_by_name):
"""Returns a lookup table that is by-guid rather than by-name."""
brush_lookup = BrushLookup.get()
def guid_or_name_to_guid(guid_or_name):
if guid_or_name in brush_lookup.guid_to_name:
return guid_or_name
elif guid_or_name in brush_lookup.name_to_... | 27,338 |
def _make_divergence_numba_1d(bcs: Boundaries) -> Callable:
"""make a 1d divergence operator using numba compilation
Args:
dim (int): The number of support points for each axes
boundaries (:class:`~pde.grids.boundaries.axes.Boundaries`):
{ARG_BOUNDARIES_INSTANCE}
dx (float):... | 27,339 |
def draw_predicted_rectangle(image_arr, y, x, half_height, half_width):
"""Draws a rectangle onto the image at the provided coordinates.
Args:
image_arr: Numpy array of the image.
y: y-coordinate of the rectangle (normalized to 0-1).
x: x-coordinate of the rectangle (normalized to 0-1).
... | 27,340 |
def my_max(seq: Sequence[ItemType]) -> Optional[ItemType]:
"""Максимальный элемент последовательности
Использует подход динамического программирования.
:param seq: последовательность
:type seq: Sequence[ItemType]
:return: максимальный элемент последовательности
:rtype: ItemType
"""
if ... | 27,341 |
def correct_pm0(ra, dec, pmra, pmdec, dist, vlsr=vlsr0, vx=0, vy=0, vz=0):
"""Corrects the proper motion for the speed of the Sun
Arguments:
ra - RA in deg
dec -- Declination in deg
pmra -- pm in RA in mas/yr
pmdec -- pm in declination in mas/yr
dist -- distance in kpc
... | 27,342 |
def clean_output_type_names(df: pd.DataFrame) -> pd.DataFrame:
"""Convenience function for cleaning up output type names
The `outputs_clean` dict is located in the defaults submodule
:param df: Input data frame to be cleaned up
:type df: pandas DataFrame
:return: DataFrame with output type names cle... | 27,343 |
def run_mask_camera(video_path, output_video_name, conf_thresh, target_shape):
"""
Runs the model on a video stream (file or camera input)
Parameters:
video_path (str): 0 for camera input or the path to the video
output_video_name (str): Output video name
conf_thresh (float): The mi... | 27,344 |
def analyze_sentiment(input_text):
"""
Using VADER perform sentiment analysis on the given text
"""
sentiment_analyzer = SentimentIntensityAnalyzer()
sentiment_dict = sentiment_analyzer.polarity_scores(input_text)
return sentiment_dict | 27,345 |
def get_free_header(filepath, needed_keys=(), original_name=None, observatory=None):
"""Return the complete unconditioned header dictionary of a reference file.
DOES NOT hijack warnings. DOES NOT verify checksums.
Original name is used to determine file type for web upload temporary files
which have... | 27,346 |
def clean_ice(options, args):
"""
Clean all orphaned VMs
"""
if len(args) < 2:
print "The iceage command requires a run name. See --help"
return 1
dbname = args[1]
cb = CloudInitD(options.database, db_name=dbname, log_level=options.loglevel, logdir=options.logdir, terminate=Fal... | 27,347 |
def ADD_CIPD_FILE(api, pkg, platform, image, customization, success=True):
""" mock add cipd file to unpacked image step """
return ADD_FILE(
api, image, customization,
'[CACHE]\\Pkgs\\CIPDPkgs\\resolved-instance_id-of-latest----------' +
'\\{}\\{}\\*'.format(pkg, platform), success) | 27,348 |
def init(
ctx: typer.Context,
verbose: bool = typer.Option(
False,
"--verbose",
"-V",
is_flag=True,
help="Print each step as it happens.",
),
) -> None:
"""Configure PyBites credentials and repository."""
while True:
username = Prompt.ask("Enter your P... | 27,349 |
def row_to_columns(row):
"""Takes a row as a string and returns it as a list of columns."""
return [column for column in row.split() if column.strip() != ''] | 27,350 |
def circ_diagonal_mode_mat(bk):
"""Diagonal matrix of radial coefficients for all modes/wavenumbers.
Parameters
----------
bk : (M, N+1) numpy.ndarray
Vector containing values for all wavenumbers :math:`M` and modes up to
order :math:`N`
Returns
-------
Bk : (M, 2*N+1, 2*N+... | 27,351 |
def log_updater(log, repetition, average_loss, optimization_time):
"""
Function to update the log object.
"""
index = repetition + 1
log["losses"] = log["losses"] + [[index, average_loss]]
log["times"] = log["times"] + [[index, optimization_time]]
return log | 27,352 |
def execute_function_multithreaded(fn,
args_list,
block_until_all_done=True,
max_concurrent_executions=1000):
"""
Executes fn in multiple threads each with one set of the args in the
args_list.
:para... | 27,353 |
def cli(incluster, kubeconfig):
"""
CLI for testing kubernetes NetworkPolicies.
"""
if incluster:
k8s.config.load_incluster_config()
else:
try:
k8s.config.load_kube_config(config_file=kubeconfig)
except k8s.config.ConfigException as config_error:
LOGGE... | 27,354 |
def volume_encryption_metadata_get(context, volume_id, session=None):
"""Return the encryption metadata for a given volume."""
volume_ref = _volume_get(context, volume_id)
encryption_ref = volume_type_encryption_get(context,
volume_ref['volume_type_id'])
... | 27,355 |
def test_shift_to_other_frame(hlwm, direction, frameindex, clients_per_frame):
"""
in a frame grid with 3 columns, where the middle column has 3 rows, we put
the focused window in the middle, and then invoke 'shift' with the given
'direction'. Then, it is checked that the window stays focused but now
... | 27,356 |
def parse_local_cpus():
"""Return information about available CPU's and cores in local system.
The information is gathered from ``lscpu`` command which besides the available CPUs informations, also returns
information about physical cores in the system, which is usefull for hyper threading systems.
Ret... | 27,357 |
def perform_tick(gamefield):
"""
Perfom a tick.
A tick is one round where each cell has a rule check
"""
tick_changes = get_tick_changes(gamefield)
activate_rules(gamefield, tick_changes)
return gamefield | 27,358 |
def get_cairo_surface(pygame_surface):
""" Black magic. """
class Surface(ctypes.Structure):
_fields_ = [
(
'HEAD', ctypes.c_byte * object.__basicsize__),
(
'SDL_Surface', ctypes.c_void_p)]
class SDL_Surface(ctypes.Structure):
_fields_ = [
(
... | 27,359 |
def string_out_table(dat, columns, caption, preferred_sizes=None, table_size="footnotesize"):
"""
- dat: (Dict String (Array String)), dict of arrays of data for the table
- columns: (Array String), the column names in desired order
- path: string, path to where to save the table
- caption: None or ... | 27,360 |
def getCreationDate(pdf):
"""Return the creation date of a document."""
r = string_at(libc.pycpdf_getCreationDate(pdf.pdf)).decode()
checkerror()
return r | 27,361 |
async def fast_dependencies(
_: Annotated[int, Dependant(dep_without_delays)]
) -> Response:
"""An endpoint with dependencies that execute instantly"""
return Response() | 27,362 |
def _pretty_print_bnode(bnode: BNode):
"""Print a blank node."""
return f'😶 {bnode}' | 27,363 |
def resource_config():
"""
The path to the resource configuration file.
A file containing the name of the current host and all host containers in
the training.
Returns:
path (str): The absolute path to the resource config JSON
"""
return os.path.join(config(), 'resourceconfig.json'... | 27,364 |
def combine_div(range1, range2):
"""
Combiner for Divide operation.
>>> import gast as ast
>>> combine(Range(-1, 5), Range(3, 8), ast.Div())
Range(low=-1, high=1)
>>> combine(Range(-1, 5), Range(-5, -4), ast.Div())
Range(low=-2, high=0)
>>> combine(Range(-1, 5), Range(-5, 3), ast.Div())... | 27,365 |
def run_covid(country):
"""Run the COVID model for some country"""
runner = getattr(covid_19, country)
runner.run_model() | 27,366 |
def air(pos, res=None, shape=None, rowmajor=False, rad=None, ref=None):
"""Setups up an Airy system. See the build function for details."""
pos, res, shape, mid = validate(pos, res, shape, rowmajor)
if rad is None:
if pos.ndim != 2:
raise ValueError("Airy requires either rad or pos[2,2]")
w = angdist(mid[0]*d... | 27,367 |
def start():
"""
Method to initiate socket server services.
"""
server.listen()
butter = (f"[SERVER_LISTENING] Server up and running on {SERVER}:{PORT} waiting for connections.")
print(butter.lower())
while True:
conn, addr = server.accept()
thread = threading.Thread(tar... | 27,368 |
def get_pdf(list_of_figures: list, pdf_name: str) -> None:
"""Create a pdf with given plots in a list.
Keyword arguments:
list_of_figures -- list of matplotlib figures
pdf_name -- Name of the pdf file.
"""
# save pdf in a file called 'Output' which is located in the project file Lets... | 27,369 |
def get_config_type(service_name):
"""
get the config tmp_type based on service_name
"""
if service_name == "HDFS":
tmp_type = "hdfs-site"
elif service_name == "HDFS":
tmp_type = "core-site"
elif service_name == "MAPREDUCE":
tmp_type = "mapred-site"
elif service_name ... | 27,370 |
def batch_request(config, dataset_id, geographies, date_format,
record_offset=0, max_api_calls=10):
"""Fetch a NOMIS dataset from the API, in batches,
based on a configuration object.
Args:
config (dict): Configuration object, from which a get
request is for... | 27,371 |
def audit_rds(accounts, send_report):
""" Runs auditors/rds_security_group """
sm_audit_rds(accounts, send_report) | 27,372 |
def get_val(in_root: str, wnid2idx: Dict[str, int]) -> List[Tuple[str, int]]:
"""Get validation split sample pairs.
Args:
in_root (str): Input dataset root directory.
wnid2idx (dict): Mapping of WordNet ID to class ID.
Returns:
List of pairs of (image filename, class ID).
"""
... | 27,373 |
def is_music(file: File) -> bool:
"""See if the ext is a Music type."""
return file.ext in {
"aac",
"m4a",
"mp3",
"ogg",
"wma",
"mka",
"opus",
"alac",
"ape",
"flac",
"wav",
} | 27,374 |
def sqeuclidean_pdist(x, y=None):
"""Fast and efficient implementation of ||X - Y||^2 = ||X||^2 + ||Y||^2 - 2 X^T Y
Input: x is a Nxd matrix
y is an optional Mxd matirx
Output: dist is a NxM matrix where dist[i,j] is the square norm between x[i,:] and y[j,:]
if y is not given then use... | 27,375 |
def test_receive_order_internal_duplicate_from_same_neighbor(scenario, engine):
"""
This tests receiving the same internal order from the neighbor multiple times.
"""
# Arrange.
peer_list: List[Peer] = create_test_peers(scenario, engine, 2)
peer_list[0].add_neighbor(peer_list[1])
peer_list[... | 27,376 |
def parse_options() -> argparse.Namespace:
"""Parse command line arguments"""
parser: argparse.ArgumentParser = argparse.ArgumentParser(
"Arguments for pretraining")
parser.add_argument('--sample_size', type=int, default=3200,
help='sample size for training')
parser.add_a... | 27,377 |
def plot_ellipse(ax, mu, sigma, color="k"):
"""
Based on
http://stackoverflow.com/questions/17952171/not-sure-how-to-fit-data-with-a-gaussian-python.
"""
# Compute eigenX_embeddedues and associated eigenvectors
X_embeddeds, vecs = np.linalg.eigh(sigma)
# Compute "tilt" of ellipse using fir... | 27,378 |
def commit(dir_info):
"""
Moves files from the temp directory to the final directory based
on the input given. Returns list of all files
Keyword arguments:
dir_info -- dictionary of service to dir_info hash
"""
def walk_file_list(base_dir, srcdir, resultdir, done_files=set()):
"... | 27,379 |
def len(file, path):
"""获取dataset第一维长度。
Args:
file: 文件路径。
path: dataset路径。
Returns:
返回长度。
"""
with h5py.File(file, mode='r') as h5_file:
length = h5_file[path].len()
return length | 27,380 |
def format_(session):
"""Format the code."""
session.install(*REQUIREMENTS_FORMAT)
session.run(
'black', '-l', '88', '-t', 'py38', '-S', '--exclude=.*/migrations/.*', *PY_PATHS
)
session.run('isort', *PY_PATHS)
session.run(
'docformatter',
'--in-place',
'--recursi... | 27,381 |
def get_time_with_limits(
db_name: str,
user: str,
port: int,
test_mols_path: Path,
search_type: str,
path_to_save: Path,
password=None,
) -> None:
"""
Searches the database for the specified molecules and saves the search time to a excel file.
"""
... | 27,382 |
def loop(step_fn, n_steps,
sequences=None, outputs_info=None, non_sequences=None,
go_backwards=False):
"""
Helper function to unroll for loops. Can be used to unroll theano.scan.
The parameter names are identical to theano.scan, please refer to here
for more information.
Note that this func... | 27,383 |
def get_model(hidden_size=20, n_hidden=5, in_dim=2, out_dim=1, penultimate=False, use_cuda=True, bn=False):
"""
Initialize the model and send to gpu
"""
in_dim = in_dim
out_dim = out_dim #1
model = Net(in_dim, out_dim, n_hidden=n_hidden, hidden_size=hidden_size,
activation=torch... | 27,384 |
def main(args=None):
"""Project entrypoint function"""
argparser = argparse.ArgumentParser(
description="""\r
\r-----------------------------
\r Spacin, puts space between!
\r-----------------------------\n\n
\rSpacin is a word-separator that distinguishes
\reach... | 27,385 |
def convert_sweep(sweep,sweep_loc,new_sweep_loc,AR,taper):
"""This converts arbitrary sweep into a desired sweep given
wing geometry.
Assumptions:
None
Source:
N/A
Inputs:
sweep [degrees]
sweep_loc [unitless]
new_sweep_loc [unitless]
AR ... | 27,386 |
def is_circular(linked_list):
"""
Determine whether the Linked List is circular or not
Args:
linked_list(obj): Linked List to be checked
Returns:
bool: Return True if the linked list is circular, return False otherwise
The way we'll do this is by having two pointers, called "runne... | 27,387 |
def bm_cv(
X_train: pd.DataFrame,
y_train: pd.Series,
cv: int,
metrics: List[Any],
metrics_proba: List[Any],
metric_kwargs: dict,
model_dict: dict,
):
"""
Perform cross validation benchmark with all models specified under model_dictionary, using the metrics defined.
Args:
... | 27,388 |
def index_get(array, *argv):
"""
checks if a index is available in the array and returns it
:param array: the data array
:param argv: index integers
:return: None if not available or the return value
"""
try:
for index in argv:
array = array[index]
... | 27,389 |
def add_graph(writer: torch.utils.tensorboard.SummaryWriter = None,
model: torch.nn.Module = None,
data_loader: torch.utils.data.dataloader = None,
device: torch.device = torch.device('cpu')):
"""Plot the graph of the model"""
# get an example image for running through ... | 27,390 |
def _test_converter(testname, fail_expected, error_text=None, format="yaml"):
"""
Convert a v1 object to v3, then apply the result and read it back.
"""
# Let's start every test afresh
wipe_etcd(get_ip())
testdata = data[testname]
# Convert data to V3 API using the tool under test
rc = ... | 27,391 |
def test_version():
"""
Make sure the version in the TOML file and in the __init__.py file are the same.
"""
with open("pyproject.toml") as f:
tomllines = f.read().splitlines()
tomlversion = set([l for l in tomllines if "version =" in l])
initversion = set([f'version = "{mei2volp... | 27,392 |
def _env_vars_available() -> bool:
"""
Returns: `True` if all required environment variables for the Postgres connection are set, `False` otherwise
"""
return all(env_var in environ for env_var in DBConfigProviderEnvVarBasedImpl.required_env_vars) | 27,393 |
def launch(
code, structure, pseudo_family, daemon, protocol):
"""
Run the PwBandStructureWorkChain for a given input structure
to compute the band structure for the relaxed structure
"""
from aiida.orm.data.base import Str
from aiida.orm import DataFactory
from aiida.orm.utils import W... | 27,394 |
def precisionatk_implementation(y_true, y_pred, k):
"""Fujnction to calculate precision at k for a given sample
Arguments:
y_true {list} -- list of actual classes for the given sample
y_pred {list} -- list of predicted classes for the given sample
k {[int]} -- top k predictions we are i... | 27,395 |
def add_plane_data(
data_frame: pandas.DataFrame,
file_path: str,
target_col: str = const.DF_PLANE_COL_NAME
) -> pandas.DataFrame:
"""Merges DataFrame with information about the flight planes
Args:
data_frame (pandas.DataFrame): Source DataFrame
file_path (str): ... | 27,396 |
def record(location):
"""Creates an empty record."""
draft = RDMDraft.create({})
record = RDMRecord.publish(draft)
return record | 27,397 |
def generate_tests():
# type: () -> Generator[Tuple[str, Callable, List[Any], List[Any]]]
"""
Yield tuples of test data.
:return: Tuple with testdata (test_name, func_obj, inputs, outputs)
:rtype: Generator[Tuple[str, Callable, List[Any], List[Any]]]
"""
with open(TEST_DATA, "rb") as stream... | 27,398 |
def firfls(x, f_range, fs=1000, w=3, tw=.15):
"""
Filter signal with an FIR filter
*Like firls in MATLAB
x : array-like, 1d
Time series to filter
f_range : (low, high), Hz
Cutoff frequencies of bandpass filter
fs : float, Hz
Sampling rate
w : float
Length of ... | 27,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.