content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def try_to_datetime(x, frmt=''):
"""Try to convert a string to a date. In case of failure, return nan"""
try:
if frmt == '':
return pandas.to_datetime(x)
else:
return pandas.to_datetime(x, format=frmt)
except:
return numpy.nan | 5,296,100 |
def parallel(*children, **kwargs):
"""Run tasks in parallel until the success policy is fulfilled or broken.
If the success policy is met, return a success. If the policy is
broken, return a failure.
For more information, see the discussion at
U{aigamedev.com/hierarchical-logic/parallel}.
... | 5,296,101 |
def seq_to_arr(working_dir: Path, user_list: Path, ignore_uncommon:bool=True):
"""Produces prediction format compatible with the benchmarking tool.
working_dir: Path
Dir where EvoEF2 results are stored.
user_list: Path
Path to .txt file with protein chains to include in the benchmark... | 5,296,102 |
def record():
"""avvia la registrazione sulla nucleo esalva i valori sul file csv
:return:
"""
toggle_record()
threading.Thread(target=tail).start()
with open(file_name, mode='a') as file:
in_str = read()
while in_str: # in_str list vuota se non c'è nulla
# todo la n... | 5,296,103 |
def crs_from_layers(source_layers: t.List[t.SourceLayer]) -> t.List[t.Crs]:
"""Return an intersection of crs supported by each source layer."""
cs = set()
for sl in source_layers:
if not sl.supported_crs:
continue
if not cs:
cs.update(sl.supported_crs)
else:... | 5,296,104 |
def copy_folder(from_dir: str, to_dir: str, indent: int) -> None:
"""
Function copies one directory to another with all its contents.
Prints what was copied, each sub-directory gets more indented.
Args:
from_dir (str): Path to directory to copy.
to_dir (str): Path to directory where to ... | 5,296,105 |
def food_image_upload_path(filename):
"""美食图片上传路径"""
return os.path.join(
"food_image",
"%Y/%m",
filename
) | 5,296,106 |
def test_app():
"""Return a test Application."""
return Application('testing') | 5,296,107 |
def test_single_pseudo_parse_obj_aliased():
"""Check that for local/non_local data we can also use the abbrev 'coeffs' for loading"""
with (TEST_DIR / "inputs" / "GTH_POTENTIALS.Cl").open() as fhandle:
pseudo = PseudopotentialData.from_lines([line for line in fhandle])
assert pseudo.local.coefficie... | 5,296,108 |
def download(local_qanta_prefix):
"""
Download the qanta dataset
"""
for s3_file, local_file in make_file_pairs(FILES, S3_HTTP_PREFIX, local_qanta_prefix):
download_file(s3_file, local_file) | 5,296,109 |
def main_cli(opts, args, gt_instance_uuid=None):
"""! This is main CLI function with all command line parameters
@details This function also implements CLI workflow depending on CLI parameters inputed
@return This function doesn't return, it exits to environment with proper success code
"""
def fil... | 5,296,110 |
def test_identity_band_to_block_sym(block_size, h_blocks, v_blocks):
"""
Operator block_to_band is the inverse of band_to_block.
Composing the pair should result in the identity operator.
This desired outcome is tested here for symmetric matrices.
block_to_band ( band_to_block (X) ) = X
"""
... | 5,296,111 |
def determine_torsion_symmetry(label, top1, mol_list, torsion_scan):
"""
Check whether a torsion is symmetric.
If a torsion well is "well defined" and not smeared, it could be symmetric.
Check the groups attached to the rotor pivots to determine whether it is indeed symmetric
We don't care about th... | 5,296,112 |
def check_holdings(asset_id, address):
"""
Checks the asset balance for the specific address and asset id.
"""
account_info = client.account_info(address)
assets = account_info.get("assets")
if assets:
asset_holding = None
for i in account_info["assets"]:
if i['asset-... | 5,296,113 |
def isValidGUID(guid):
""" Verify the GUID generated with uuidgen """
status = False
pattern = "[A-F0-9]{8}-[A-F0-9]{4}-[A-F0-9]{4}-[A-F0-9]{4}-[A-F0-9]{12}"
m = re.search(pattern, guid.upper())
if not m:
tolog("!!WARNING!!2333!! GUID=\'%s\' does not follow pattern \'%s\'" % (guid, pattern... | 5,296,114 |
def init_extensions(app: Flask):
"""Initialize all flask extensions.
Args:
app: The Flask application object.
"""
global celery
celery = make_celery(app)
csrf.init_app(app)
db.init_app(app)
lm.init_app(app)
mail.init_app(app)
migrate.init_app(app, db) | 5,296,115 |
def dump_stanc_warnings(stanc_warnings: str, model_name: str) -> None:
"""Dump stanc warnings associated with a model."""
model_directory_ = model_directory(model_name)
model_directory_.mkdir(parents=True, exist_ok=True)
with (model_directory_ / "stanc.log").open("w") as fh:
fh.write(stanc_warni... | 5,296,116 |
def read_probabilties(proba_folder, subset='valid',
model_names=model_names):
"""Reads saved .npy validation and test predicted probabilities from PsychicLearners/data/probabilities"""
proba_folder = Path(proba_folder)
all_probabilities = []
for folder in proba_folder.iterdir():
... | 5,296,117 |
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Setup the sensors.
right now only one, but later there should probably be another sensor for deviations at the same site
"""
ri4data = SlDepartureData(
config.get(CONF_RI4_KEY),
config.get(CONF_SITEID),
... | 5,296,118 |
def parse_args():
"""Parse input arguments."""
parser = argparse.ArgumentParser(description='Faster R-CNN demo')
parser.add_argument('--gpu', dest='gpu_id', help='GPU device id to use [0]',
default=0, type=int)
parser.add_argument('--cpu', dest='cpu_mode',
... | 5,296,119 |
def filter_bad_ids(
data: DataFrame,
bad_ids: Union[Series, list[str], str],
filter_col: str,
filter_method: Union[str, Callable] = "odo",
):
"""
Filter observation IDs that are flagged as badded, either from an
online Google Sheet or from a Series or list.
:param data: Dataset
:typ... | 5,296,120 |
def normalized_abl1():
"""Return normalized Gene Descriptor for ABL1."""
params = {
"id": "normalize.gene:ABL1",
"type": "GeneDescriptor",
"gene_id": "hgnc:76",
"label": "ABL1",
"xrefs": {
"ensembl:ENSG00000097007",
"ncbigene:25"
},
... | 5,296,121 |
def download_tif(image, polygon, bandsId, filepath):
"""
Downloads a .TIF image from the ee server. The image is downloaded as a
zip file then moved to the working directory, unzipped and stacked into a
single .TIF file.
Two different codes based on which version of the earth-engine-api is being
... | 5,296,122 |
def init_logger():
""" Initializes logging. Must be called before any other function. Calling this again will re-initalize logging. """
global out_file, out_fp, out_file2, out_fp2, semaphore
semaphore.acquire()
out_file = tc_config.config_dic['out_file']
if out_fp is not None:
out_fp.close()
out_fp = open(o... | 5,296,123 |
def lookup_school_reverse(school_id):
"""
A function to lookup school name from school_id
Args:
school_id as int
Returns:
school (str): the name of the school
Examples:
lookup_school_id_reverse(167)
>>> "Cornell"
"""
school_row = _SCHOOL_ID_LU... | 5,296,124 |
def inspect_signatures(spec, imp):
"""Print mismatches of method names or argument names.
@param spec: the specification
@param imp: the implementation
"""
print('Specification class: {t}'.format(t=type(spec)))
print('Implementation class: {t}'.format(t=type(imp)))
print('Checking whether a... | 5,296,125 |
def SeparaPorTamanho(dicionário, palavra):
"""
Separa as possíveis candidatas a palavras substitutas
por tamanho
""" | 5,296,126 |
def flip(x):
"""
flip image(翻轉影像)
"""
x = tf.image.random_flip_left_right(x) # 隨機左右翻轉影像
return x | 5,296,127 |
def three_to_one(s):
"""
Three letter code to one letter code.
For example: ALA to A.
"""
i=d3_to_index[s]
return dindex_to_1[i] | 5,296,128 |
def get_queue_index(name='default'):
"""
Returns the position of Queue for the named queue in QUEUES_LIST
"""
queue_index = None
connection = get_connection(name)
connection_kwargs = connection.connection_pool.connection_kwargs
for i in range(0, 100):
q = get_queue_by_index(i)
... | 5,296,129 |
def to_hash_str(source, encoding="ascii"): # pragma: no cover -- deprecated & unused
"""deprecated, use to_native_str() instead"""
return to_native_str(source, encoding, param="hash") | 5,296,130 |
def k_pod(data, n_clusters,max_iter=300,tol=0,random_state=0):
""" Compute cluster centers and predict cluster index for sample containing missing data.
Parameters
----------
data: {array-like, sparse matrix} of shape (N, P)
Data to predict clusters for.
n_clusters: int
The number ... | 5,296,131 |
def _get_datemapping(df, events):
"""
return the mapping of human_readable dates to
integer numbers for plotting. Mapping is a dict.
Furthermore return a sorted list of the dates.
"""
dates = sorted(df.human_readable.unique(), key=_date_key_function)
date_mapping = {}
for in... | 5,296,132 |
def list_ids(args):
"""Use the provided list of ids to retrieve funds
Args:
args (str): A list of ms id's separated by commas
"""
funds = args.list.split(',')
get_funds(funds, MSUniverses[args.universe.upper()], args.output, args.savefiles) | 5,296,133 |
def load_rotated_mnist(data_dir, image_size=32, train=True, rotation=0):
"""
Load a MNIST dataset where each image has a rotation.
"""
rotate_image = rotate_transform(rotation)
image_transforms = [
transforms.Resize(image_size),
transforms.CenterCrop(image_size),
rotate_image... | 5,296,134 |
def appendProduct(prod_properties, userID):
"""Move products from aggregated tab onto pending invoices one"""
db = MySQLdb.connect(passwd=db_password, db=db_name, user='orsys')
logging.debug("This is output from appendProduct")
logging.debug(prod_properties)
(sku, price, qty, supplier_id, o_oprice) ... | 5,296,135 |
def p_relational_op_1(p):
"""
RELOP : LESS
"""
p[0] = p[1] | 5,296,136 |
def install_swaggerui():
"""
"""
stage_require()
put('../swagger-ui', '/home/%s/deploy/'
% env.user, use_sudo=True) | 5,296,137 |
def some(args):
"""
%prog some bedfile idsfile > newbedfile
Retrieve a subset of bed features given a list of ids.
"""
from jcvi.formats.base import SetFile
from jcvi.utils.cbook import gene_name
p = OptionParser(some.__doc__)
p.add_option("-v", dest="inverse", default=False, action="s... | 5,296,138 |
def slave_delete(request):
"""
接令人删除为同意的召集令请求
"""
# body = json.loads(request.body)
body = request.GET
req = body.get('request_id', '')
try:
Request.objects.filter(
uid__exact=req, request_status__exact=0).delete()
except Request.DoesNotExist:
return HttpResp... | 5,296,139 |
def meetup(date):
"""
Displays the meetup taking place on the given date.
"""
meetup = _get_meetup(date)
user_upvotes = []
user_downvotes = []
ideas = meetup.sessionideas
idea_ids = [idea.id for idea in ideas]
vote_results = collections.defaultdict(int)
for vote in db.session.que... | 5,296,140 |
def is_hilbert_squarefree_number(n):
"""
I define a "Hilbert squarefree" number as a positive integer not divisible
by the square of any Hilbert number, i.e. by a Hilbert square.
Note: the given n need not be a Hilbert number but could be any positive
integer.
"""
ubound = math.ceil(n / 2)... | 5,296,141 |
def get_plotting_specs_somato(beamf_type, plot_type):
"""Get all parameters and settings for plotting."""
if plot_type not in ('corr', 'foc', 'ori'):
raise ValueError('Do not know plotting type "%s".' % plot_type)
if beamf_type == 'lcmv':
xmax = 130
if plot_type == 'foc':
... | 5,296,142 |
def set_clipboard_string(window, string):
"""
Sets the clipboard to the specified string.
Wrapper for:
void glfwSetClipboardString(GLFWwindow* window, const char* string);
"""
_glfw.glfwSetClipboardString(window, _to_char_p(string)) | 5,296,143 |
def update_rows(table_name, join_columns, target_columns, update_row, batch_size=-1, engine=None):
"""
Updates records in the given table with custom modified values.
:param table_name: the name of the table with row values to be modified
:param join_columns: one or more column names that constitute un... | 5,296,144 |
def isplit(iterable, size):
"""
Makes an iterator that returns batches of the indicated ``size`` of
elements from the ``iterable``::
>>> list(isplit([1, 2, 3, 4, 5, 6, 7], 3))
[[1, 2, 3], [4, 5, 6], [7]]
If the length of the ``iterable`` is not evenly divisible by ``size``, the
las... | 5,296,145 |
def parse_fp(source, module_name, lexer=None, parser=None, enable_cache=True):
"""Parse a file-like object to thrift module object, e.g.::
>>> from thriftpy.parser.parser import parse_fp
>>> with open("path/to/note.thrift") as fp:
parse_fp(fp, "note_thrift")
<module 'note_th... | 5,296,146 |
def question_16_a():
"""
Question 16 a, plotting the experiment.
:param data: data of 5 batches of 1000 coin tosses.
:return: nothing.
"""
plot_q16() | 5,296,147 |
def create_streaming_params(client_params: List[ClientParam]) -> str:
"""Build the C++ parameter list for streaming functions."""
params = _to_parameter_list(client_params)
client_context_param = "::grpc::ClientContext& context"
params = [stub_param()] + [client_context_param] + params
return str.jo... | 5,296,148 |
def app(request):
"""AioHTTP application with configurable endpoints.
Endpoint names should be passed as positional arguments to `pytest.mark.endpoints` decorator.
"""
marker = request.node.get_closest_marker("endpoints")
if marker:
endpoints = marker.args
else:
endpoints = ("su... | 5,296,149 |
def test_invalid_instantiation():
"""
Serializableを直接インスタンス化することはできるが、
serialized()は呼び出せない
"""
serializable_class = Serializable()
with pytest.raises(NotImplementedError):
serializable_class.serialized()
with pytest.raises(NotImplementedError):
Serializable.deserialized({}) | 5,296,150 |
def scraperMode():
"""
The operating mode of the scraper.
It can either send notification if text is found on the page, or waiting and keep refreshing
until the text goes away from the page.
:return: the mode
"""
print("In which mode should the scraper behave?\nInsert the... | 5,296,151 |
def show_files(files):
"""
Print `files` to the standard output, one item per line, in a blue color.
"""
print_line(blue("%s: files to be checked:" % sys.argv[0]))
for f in files:
print_line(blue(" %s" % f)) | 5,296,152 |
def checkCoordinateList(coordinates, varname="coordinates"):
"""
Check that the given coordinates is a valid Nx3 sequence of numbers.
:param coordinates: The object to test. To pass the test this must be
an Nx3 array of floating point numbers.
:param varname: The name of the var... | 5,296,153 |
def validate_enum(temp_enum):
"""
Strips spaces & converts values that could be interpreted in yaml as
nonstring, to double quotation string
"""
enum = stripper(temp_enum)
# enum = enum.replace(':', '-')
if enum != 'open' and '/' not in enum:
if isinstance(enum, str) and enum.lower... | 5,296,154 |
def encode_circuits(circuits, model):
"""
Encode a list of circuits generated from a given model. Each circuit will be encoded using 4 integers:
1. The index of the gate sequence before the germ, i.e. preparation fiducials
2. The index of the gate sequence after the germ, i.e. measurement fi... | 5,296,155 |
def init_events_command():
"""Clear existing data and create new tables."""
init_events()
click.echo('Initialized the predefined events.') | 5,296,156 |
def domain_match(A, B):
"""Return True if domain A domain-matches domain B, according to RFC 2965.
A and B may be host domain names or IP addresses.
RFC 2965, section 1:
Host names can be specified either as an IP address or a HDN string.
Sometimes we compare one host name with another. ... | 5,296,157 |
def step_add_return_value(context: dict) -> None:
"""Add a Return Value to the Mocked Function.
This step will generate a new return value to the mocked function on the chain.
"""
context.expected_output = context.fake.pydict()
context.mocked_function.return_value = context.expected_output | 5,296,158 |
def test_send_ctrl_alt_del(test_microvm_with_api):
"""
Test shutting down the microVM gracefully on x86, by sending CTRL+ALT+DEL.
@type: functional
"""
# This relies on the i8042 device and AT Keyboard support being present in
# the guest kernel.
test_microvm = test_microvm_with_api
tes... | 5,296,159 |
def _build_timetables(schedules, events=None, partner=None):
"""
Dati un elenco di schedule ids/eventi e partner program ritorna una lista
di TimeTable relative ai dati passati.
_build_timetables([1,2])
Restituisce due TimeTable relative agli schedule 1 e 2 (gli eventi
vengono recupera... | 5,296,160 |
def readSeeingFromASDM_minidom(asdm):
"""
Reads information from CalSeeing.xml into a dictionary
Returns a dictionary with the following keys:
atmPhaseCorrection: AP_UNCORRECTED or AP_CORRECTED
baselineLengths: typically 3 values (in meters)
startValidTime: MJD nano seconds
endValidTime: MJD... | 5,296,161 |
def get_tags(owner: str, repo: str, n: int = 100, filter: Optional[str] = None) -> Iterator[str]:
"""Get the tags on a repository in descending commit tag date order."""
ref_query = ""
if filter is not None:
ref_query = f', query: "{filter}"'
# Use GraphQL to get tag by commit date and not by ... | 5,296,162 |
def Function(from_types, to_type):
"""A binary type constructor which builds function types"""
return TypeOperator('fun', list(from_types) + [to_type]) | 5,296,163 |
def _threshold_binary(image, thresholds):
"""
Apply binary thresholding to an image
Inputs
----------
image: numpy.ndarray
A single image, grayscale or RGB
thresholds: numpy.ndarray
A list containing a min and max value for thresholding
Outputs
-------
binary_ou... | 5,296,164 |
def is_field_remote(model, field_name):
"""Check whether a given model field is a remote field.
"""
if not hasattr(model, '_meta'):
# ephemeral model with no metaclass
return False
model_field = get_model_field(model, field_name)
return isinstance(model_field, (ManyToManyField, Rela... | 5,296,165 |
def dist_bool_output(dist, dist1, dist2=0, mode='lim'):
"""
This function takes an input distance and the upper and lower limits or the central value and the tolerance and outputs
if it satisfies or not the given criteria.
modes:
lim -> limit mode, it requires a max and a min value
tol ... | 5,296,166 |
def rollaxis(a, axis, start=0):
"""
Roll the specified axis backwards, until it lies in a given position.
Parameters
----------
a : ndarray
Input array.
axis : int
The axis to roll backwards. The positions of the other axes do not
change relative to one another.
sta... | 5,296,167 |
def consistency_check(args, alphabet, key):
"""Checks the alphabet and the key for consistency and normalizes both to lower case
:param object args: object containing the converted arguments
:param str alphabet: the untrusted alphabet to check
:param str key: the untrusted key to check
:return: a t... | 5,296,168 |
def init_commit_repo(project, struct):
"""
Initialize a git repository
:param project: path to the project as string
:param struct: directory structure as dictionary of dictionaries
"""
with utils.chdir(project):
git('init')
git_tree_add(struct[project])
git('commit', '-... | 5,296,169 |
def func(arg1, arg2):
"""magic function
"""
return arg2, arg1 | 5,296,170 |
def make_summary_table(indir,aggregation_rules,aggregation_rules_twiki, hashing_flag, standalone_flag):
"""Create a table, with as rows the directories and as columns the samples.
Each box in the table will contain a pie chart linking to the directory.
"""
#aggregation_rules={}
#aggregation_rules_twiki={}
... | 5,296,171 |
def compute_cylinder_neighborhood(environment_pc, target_pc, radius):
"""Find the indices of points within a cylindrical neighbourhood (using KD Tree) for a given point of a target
point cloud among the points from an environment point cloud.
:param environment_pc: environment point cloud
:param target... | 5,296,172 |
def network_exists(network: str):
"""True if a network exists in docker, else False"""
try:
get_client().networks.get(network)
return True
except NotFound:
return False | 5,296,173 |
def calc_theta(t,p):
"""
Calculate potential temperature.
**Inputs/Outputs**
Variable I/O Description Units
-------- --- ----------- -----
t I Air pressure Pa
p I Air temperature K
theta O Potential temp. K
"""
re... | 5,296,174 |
def louvain(adj_mat: np.ndarray,
verbose: bool = False,
shuffle_nodes: bool = False,
tol_optimization: float = 0.0001,
tol_aggregation: float = 0.001,
return_adj: bool = False,
**kwargs):
""" Performs louvain partiti... | 5,296,175 |
def _init_search_param(search_idx, x, y0):
"""Initialize search_param
"""
if len(search_idx[0]) != len(set(search_idx[0])):
raise ValueError('Duplicate param name.')
elif len(search_idx[1]) != len(set(search_idx[1])):
raise ValueError('Duplicate var name.')
else:
pass
se... | 5,296,176 |
def test_find_starting_node_from_spec(example_topology, start_nodes, expected):
"""<mol_name>#<mol_idx>-<resname>#<resid>"""
result = polyply.src.gen_coords.find_starting_node_from_spec(example_topology,
start_nodes)
assert result == expected | 5,296,177 |
def test(device, slave_address):
"""
Test if get_slave_address() returns the value previously set with
set_slave_address().
"""
result = device.set_slave_address(slave_address + 10)
assert result is None
result = device.get_slave_address()
assert type(result) is int
assert result ==... | 5,296,178 |
def test_delete_models_is_sequence():
"""Assert that for a sequence, multiple models are deleted."""
atom = ATOMClassifier(X_bin, y_bin, random_state=1)
atom.run(["LR", "Tree", "RF"])
atom.delete(["Tree", "RF"])
assert atom.models == "LR"
assert atom.winner is atom.LR
assert len(atom.results... | 5,296,179 |
def create_timelength(
seconds: spec.TimelengthSecondsRaw,
to_representation: spec.TimelengthRepresentation = None,
) -> spec.Timelength:
"""create Timelength
## Inputs
- seconds: int or float seconds
- to_reprsentation: str name of Timelength representation
## Returns
- Timelength wit... | 5,296,180 |
def _load_vocabulary(filename):
"""Loads a vocabulary file.
Args:
filename: Path to text file containing newline-separated words.
Returns:
vocab: A dictionary mapping word to word id.
"""
tf.logging.info("Reading vocabulary from %s", filename)
vocab = collections.OrderedDict()
with tf.gfile.GFil... | 5,296,181 |
def get_instance_type_by_flavor_id(flavor_id):
"""Retrieve instance type by flavor_id."""
ctxt = context.get_admin_context()
try:
return db.instance_type_get_by_flavor_id(ctxt, flavor_id)
except ValueError:
raise exception.FlavorNotFound(flavor_id=flavor_id) | 5,296,182 |
def _check_not_on_time_coaches():
"""
检查没有准时上课的教练(教练必须上课前10分钟登录系统),每日早上6点至晚上11点的1至59分每15分钟执行一次
:return:
"""
with db_session_manager.with_session() as db_session:
manager = ClassSuperviseManager(db_session)
manager.check_not_on_time_coaches() | 5,296,183 |
def save_experiment(experiment: Experiment, db_settings: DBSettings) -> None:
"""
Save experiment to db.
Args:
experiment: `Experiment` object.
db_settings: Specifies decoder and xdb tier where experiment is stored.
"""
initialize_db(db_settings)
_save_experiment(experiment, db_... | 5,296,184 |
def create_job(system, args:Args) -> str:
""" Create a job file template """
return f"""#!/usr/bin/bash
# --------------------------------------------------
# Request resources here
# --------------------------------------------------
#{system} --job-name={args.name}
#{system} --output={args.name}.out
#{system... | 5,296,185 |
def test_both_fain_and_url_supplied(database):
""" Tests File D2 (award financial assistance) having both uri and fain populated. """
tas = _TAS
afa = AwardFinancialAssistanceFactory(tas=tas, fain='abc', uri='xyz', federal_action_obligation=1,
original_loan_subsidy_... | 5,296,186 |
def standardize_features(df_train, df_test, cols=[]):
"""Scale continuous features to unit variance and zero mean.
Parameters
----------
df_train : pandas.core.frame.DataFrame
A subset of data intended for training.
df_test : pandas.core.frame.DataFrame
A subset of data inte... | 5,296,187 |
def tile_ref_enc_to_elements(ref_enc, elements_mask):
"""Utility to tile the ref_enc to the same shape as the elements."""
with tf.variable_scope('tile_ref_enc_to_elements'):
orig_shape = tf.shape(ref_enc)
orig_shape_static = ref_enc.get_shape().as_list()
ref_enc = tf.tile(
tf.reshape(ref_enc, [... | 5,296,188 |
def run_simulation( gamma_boost, show ):
"""
Run a simulation with a relativistic electron bunch crosses a laser
Parameters
----------
gamma_boost: float
The Lorentz factor of the frame in which the simulation is carried out.
show: bool
Whether to show a plot of the angular dist... | 5,296,189 |
async def get_level(request: web.Request) -> web.Response:
"""GET /api/level/{id}
Description:
Fetch a level by given ID.
Example:
link: /api/level/30029017
Returns:
200: JSON with level info;
400: Invalid type;
404: Level was not found.
Return Type:
a... | 5,296,190 |
def sanity_fit(model: nn.Module, train_loader, val_loader,
device: str, num_batches: int = None,
log_interval: int = 100, fp16: bool = False,):
"""
Performs Sanity fit over train loader and valid loader.
Use this to dummy check your fit function. It does not calculate metrics,... | 5,296,191 |
def spkezp(
targ: int, et: float, ref: str, abcorr: str, obs: int
) -> Tuple[ndarray, float]:
"""
Return the position of a target body relative to an observing
body, optionally corrected for light time (planetary aberration)
and stellar aberration.
https://naif.jpl.nasa.gov/pub/naif/toolkit_doc... | 5,296,192 |
def main(argv=None):
"""
Utilize Pandas library to read in both UNSD M49 country and area .csv file
(tab delimited) as well as the UNESCO heritage site .csv file (tab delimited).
Extract regions, sub-regions, intermediate regions, country and areas, and
other column data. Filter out duplicate values and NaN value... | 5,296,193 |
def make_birefringent(theta, eta=pi, phi=0):
"""
:param theta: Angle fast axis makes with horizontal
:param eta: retardance
:param phi: "circularity"?
:return: Jones matrix for the given parameters
"""
a = exp(1j * eta/2)*cos(theta)**2 + exp(-1j * eta/2)*sin(theta)**2
b = (exp(1j * eta... | 5,296,194 |
def news_API_request(covid_terms:str=json.loads(
open("config.json").read())["news_terms"]) -> list:
"""news_API_request function
This function takes in covid_terms and returns a list of dictionaries of news articles with those terms.
Args:
covid_terms (string): A string with terms seperat... | 5,296,195 |
def gt(value, other):
"""Greater than"""
return value > other | 5,296,196 |
def vmlmb_printer(output, iters, evals, rejects,
t, x, fx, gx, pgnorm, alpha, fg):
"""Default printer for `optm.vmlmb`."""
if iters < 1:
print("# Iter. Time (ms) Eval. Reject. Obj. Func. Grad. Step", file=output)
print("# -----------------------------... | 5,296,197 |
def read_and_process_and_write(paths_in, paths_out, process: lambda line: line):
"""
Parameters
----------
paths_in: list[str]
paths_out: list[str]
process: function: str -> str
"""
assert len(paths_in) == len(paths_out)
n_files = len(paths_in)
prog_bar = pyprind.ProgBar(n_files)... | 5,296,198 |
def echo(bot, update):
"""Echo the user message."""
update.message.reply_text('''Available commands:
/start
/packt
/help''') | 5,296,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.