content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def sort_data(data, cols):
"""Sort `data` rows and order columns"""
return data.sort_values(cols)[cols + ['value']].reset_index(drop=True) | 66,100 |
def calc_2d_ellipse_properties(cov,nstd=2):
"""Calculate the properties for 2d ellipse given the covariance matrix."""
def eigsorted(cov):
vals, vecs = np.linalg.eigh(cov)
order = vals.argsort()[::-1]
return vals[order], vecs[:,order]
vals, vecs = eigsorted(cov)
width, height = ... | 66,101 |
def test_edit_units(data, runner):
"""Edit units"""
inputfile = str(data.join('RGB.byte.tif'))
result = runner.invoke(main_group, [
'edit-info', inputfile, '--bidx', '1', '--units', 'DN'],
catch_exceptions=False)
assert result.exit_code == 0
with rasterio.open(inputfile) as src:
... | 66,102 |
def crawl(username, media):
"""
Start crawling celery task,
"""
assert media in ('twitter', 'facebook'), \
'media :`{}` not supported yet!'.format(media)
spider = TwitterSpider(username) if media=='twitter' else FacebookSpider(username)
settings = get_project_settings()
crawler = Cra... | 66,103 |
def show_read_only_doc_view(view, content, name, syntaxes, point=0):
"""Helper for creating read-only scratch view.
"""
view.run_command('requester_replace_view_text', {'text': content, 'point': point})
view.set_read_only(True)
view.set_scratch(True)
view.set_name(name)
# attempts to set fi... | 66,104 |
def maybe_distribute(distribution_strategy):
"""Distributes if distribution_strategy is set."""
if distribution_strategy is None:
yield
else:
with distribution_strategy.scope():
yield | 66,105 |
def _augment_grid(
policy: np.ndarray,
value: np.ndarray,
expected_value: np.ndarray,
min_wealth_grid: float,
params: pd.DataFrame,
options: Dict[str, int],
compute_utility: Callable,
) -> Tuple[np.ndarray, np.ndarray]:
"""Extends the endogenous wealth grid, value, and policy function to... | 66,106 |
def parse_args():
"""
Parse optional benchmarking arguments.
"""
parser = argparse.ArgumentParser(description='Inscriptis benchmarking '
'suite')
parser.add_argument('converter', type=str, nargs='*',
help='The list of converters to benchma... | 66,107 |
def argval_subsample_idx(values, n, polarity="MAX"):
"""values is a list, n an int, polarity is MAX or MIN"""
assert n > 0
descending = {"MAX": True, "MIN": False}[polarity]
_, idxs = torch.sort(torch.Tensor(values), descending=descending)
return idxs.tolist()[:n] | 66,108 |
def add_proxy_user_group(cursor, groups, user):
"""
Add the proxy user to all the Amazon Redshift groups that the corp user belongs to.
"""
if len(groups) > 0:
for group in groups:
add_group_sql = "ALTER GROUP " + group + " ADD USER " + user.lstrip().rstrip() + "; "
try:
... | 66,109 |
def shortest_path_matrix(G):
"""
Return a matrix of pairwise shortest path lengths between nodes.
Parameters
----------
G (nx.Graph): the graph in question
Returns
-------
pmat (np.ndarray): a matrix of shortest paths between nodes in G
"""
N = G.number_of_nodes()
pmat = ... | 66,110 |
def encrypt(file_path, password, write_path, mode=None):
"""Encrypts file with password protected AES-256."""
if(not write_path):
write_path = new_file_ext(file_path, ".enc")
encrypted_bytes = encrypt_file(file_path, password)
# write encrypted bytes to write file
with open(write_... | 66,111 |
def _cnv_del_pads_ ( self ) :
""" deleter for the created pad structure
"""
while self.pads :
key , pad = self.pads.popitem ()
if pad :
logger.verbose ( 'delete pad %s' % pad .GetName() )
del pad | 66,112 |
def build_put201_creating_failed200_request(*, json: Any = None, content: Any = None, **kwargs: Any) -> HttpRequest:
"""Long running put request, service returns a 201 to the initial request, with an entity that
contains ProvisioningState=’Created’. Polls return this value until the last poll returns a
‘20... | 66,113 |
def safe_convert_list_to_sql_tuple(filter_list):
""" Safe version of convert_list_to_sql_tuple(), by first flattening the input list
and then casting all its elements to strings, before proceeding with the conversion.
"""
return convert_list_to_sql_tuple(cast_elements_to_string(flatten_list(filter_lis... | 66,114 |
def depthAvgFlow(U, V, dz, depthRange=500):
"""
Depth averaged flow for flow from bottom up to depthrange.
"""
steps = int(np.ceil(depthRange/dz))
Umeans = np.empty(0)
Vmeans = np.empty(0)
for Ui, Vi in zip(U.T, V.T):
mask = np.where(np.isfinite(Ui))[0]
mask = mask[-1:np.max... | 66,115 |
def fibonacci():
"""
Generates the terms of the Fibonacci sequence defined by
f(1) = 1, f(2) = 1, f(n) = f(n - 1) + f(n - 2) for n > 2
The first 10 terms are
1, 1, 2, 3, 5, 8, 13, 21, 34, 55
"""
yield 1
yield 1
a = b = 1
k = 2
while True:
a,... | 66,116 |
def get_array4d(json_data, microplate_names):
"""Return well values as numpy' 4d array.
(iteration x spreadsheet x microplate x well)
"""
if len(json_data[u'iterations']) > 0:
pad_missing_spreadsheets(json_data)
iterations = []
for iteration in json_data[u'iterations']:
... | 66,117 |
def sanitise_graphite_url(current_skyline_app, graphite_url):
"""
Transform any targets in the URL that need modifications like double encoded
forward slash and return whether the URL was sanitised and the url.
:param current_skyline_app: the Skyline app calling the function
:param graphite_url: th... | 66,118 |
async def async_setup_entry(hass, entry, async_add_entities):
"""Add sensors if new."""
def add_entities(discovery_info=None):
async_add_ecowitt_entities(hass, entry, EcowittSensor,
SENSOR_DOMAIN, async_add_entities,
discovery_info)
... | 66,119 |
def convention(predictions, length):
"""
Function for implementimg the convention of Indian plates
"""
cls = np.argmax(predictions, axis = 1)
for i in [0,1]: # first 2 district code must represent letters
if cls[i]==0:
cls[i]= 24
# else:
# print(np.argmax(pred... | 66,120 |
def match_axes_height(ax_src, ax_dst):
""" Match the axes height of two axes objects.
The height of `ax_dst` is synced to that of `ax_src`.
"""
# HACK: plot geometry isn't set until the plot is drawn
plt.draw()
dst = ax_dst.get_position()
src = ax_src.get_position()
ax_dst.set_position(... | 66,121 |
def main():
"""Main function for the sample."""
demo = DataFeedDemo()
demo.PrintFeedDetails()
demo.PrintDataSources()
demo.PrintFeedAggregates()
demo.PrintSegmentInfo()
demo.PrintOneEntry()
demo.PrintFeedTable() | 66,122 |
def is_connected_dominating_set(G, nodes):
"""Return whether or not *nodes* is a connected dominating set of *G*.
A set *D* is a *connected dominating set* of *G* is *D* is a
dominating set in *G* and the subgraph of *G* induced by *D* is a
connected graph.
Parameters
----------
G : Networ... | 66,123 |
def test_cluster_points():
""" Tests that _cluster_points returns the correct value """
inputs = {
'a': (4, 0, 0, 0),
'b': (0, 4, 0, 0),
'c': (0, 0, 4, 0),
'd': (0, 0, 0, 4),
}
# Centers are chosen so the result is unique
centers = [(4, 4, 0, 0), (0, 0, 4, 4)]
re... | 66,124 |
def aws_resource_names():
""" Get names for various aws resources the manager relies on. For example:
vpcname, securitygroupname, keyname, etc.
Regular users are instructed to hardcode many of these to firesim.
Other users may have special settings pre-determined for them (e.g.
tutorial users. Thi... | 66,125 |
def _retry_on_deadlock(f):
"""Decorator to retry a DB API call if Deadlock was received."""
@functools.wraps(f)
def wrapped(*args, **kwargs):
while True:
try:
return f(*args, **kwargs)
except db_exc.DBDeadlock:
LOG.warning(_LW("Deadlock detecte... | 66,126 |
def command(server, cmd):
"""
Simple ssh remote command.
Args:
server (collection): Collection with server data
cmd (string): Command to run on remote server
Returns:
string: STDOUT for the remote command
"""
with setup_server_connection(server) as connection:
result = connection.run(cmd, ... | 66,127 |
async def reader_wrapper(connect, readers, reader_id):
"""Add some stats and logging for the worker."""
global workers_running, workers_running_max, pool_tickets
workers_running += 1
workers_running_max = max(workers_running_max, workers_running)
logging.info("starting new worker %s / %s (%s runnin... | 66,128 |
def _union_all(iterables):
"""Return a set representing the union of all the contents of an
iterable of iterables.
"""
out = set()
for iterable in iterables:
out.update(iterable)
return out | 66,129 |
def _valid_dimension_name(name):
"""Check if given dimension name is valid for PRMS.
:param str name: dimension name
:returns: True if dimension name is valid otherwise False
:rtype: bool
"""
return name in DIMENSION_NAMES | 66,130 |
def construct_relative_positions(pos: int, max_length: int) -> List[int]:
"""Construct relative positions to a specified pos
Args:
pos: the pos that will be `0`
max_length: max sequence length
Returns:
a list of relative positions
Raises:
ValueError: if pos is less tha... | 66,131 |
def get_jira_task(req_sheet, row_num):
""" Accessor for JIRA Key
Args:
req_sheet: A variable holding an Excel Workbook sheet in memory.
row_num: A variable holding the row # of the data being accessed.
Returns:
A string value of the Notes
"""
return (req_sheet['F' + str(r... | 66,132 |
def make_Palomar_pupil(N, apRad, sp_thickness=0.0127, write=False, plot=False, spiders=True, obscuration=True):
"""
Make Palomar pupil
:param N:
:param apRad:
:return:
"""
outer_diameter = 5.09
inner_diameter = 1.83
#sp_thickness = 0.0127
Rin = apRad*inner_diameter/outer_diamete... | 66,133 |
def plot_grid(lon,lat,
title_string = 'N/A',
meridians_delta = 15,
parallels_delta = 15,
same_figure = False,
figsize = None,
file_name = None,
dpi = 80,
skip = 5,
return_map = False,
marker = '+'
):
"""Function to plot grids similar to those generated by WPS
Modified 27/01/08: Minor ... | 66,134 |
def score(molfile1, molfile2, path_to_lsalign='/data/rsg/chemistry/yangk/LSalign/src'):
"""
LSalign similarity score for two molecules, each in a separate molfile whose path is given as input.
"""
with open('tmp.txt', 'w') as f:
subprocess.call([os.path.join(path_to_lsalign, 'LSalign'), molfile1... | 66,135 |
def _logme(output, logfile=sys.stderr, print_level=0):
"""Print a string to logfile
From: https://raw2.github.com/MikeDacre/handy-functions/master/mike.py"""
import datetime
timestamp = datetime.datetime.now().strftime("%Y%m%d %H:%M:%S")
output = str(output)
timeput = ' | '.join([... | 66,136 |
def _match_path(p1, p2):
"""Compare two paths from right to left and return True if they could refer
to the same file.
As a special case, if the second argument is None, or empty, it is always
considered a match. This simplifies query logic when the target does not
have a path component.
If p2... | 66,137 |
def get_consensus_data(issue, project_path, consensus=False):
"""Get full data for one issue and project path.
Checks out the commit locally, reads the hunks from the db and pre-labels everything.
"""
commits = []
folder = tempfile.mkdtemp()
git.repo.base.Repo.clone_from(project_path + "/", fo... | 66,138 |
def submit(host, entity_class, body):
"""
Negotiate submitting the data for an entity to the target service.
:param host: host url
:type host: str
:param entity_class: which entity class is being sent
:type entity_class: class
:param body: map between entity keys and values
:type body: ... | 66,139 |
def note_name_to_number(note_name):
"""Converts a note name in the format
``'(note)(accidental)(octave number)'`` (e.g. ``'C#4'``) to MIDI note
number.
``'(note)'`` is required, and is case-insensitive.
``'(accidental)'`` should be ``''`` for natural, ``'#'`` for sharp and
``'!'`` or ``'b'`` for... | 66,140 |
def determine_temps_for_date_range(start, end):
"""Return a JSON list of the minimum temperature, the average temperature, and the max temperature for a given start or start-end range."""
"""When given the start only, calculate TMIN, TAVG, and TMAX for all dates greater than and equal to the start date."""
... | 66,141 |
def is_acceptable_mutant(client_bugzoo: bugzoo.Client,
client_boggart: boggart.Client,
snapshot: bugzoo.Bug,
mutation: boggart.Mutation
) -> bool:
"""
Determines whether a given mutant is suitable for use in a gr... | 66,142 |
def scan_coordinate(rxn, zma):
""" Obtain the scan coordinates
:param rxn: a hydrogen migration Reaction object
"""
return SCAN_COORD_DCT[rxn.class_](rxn, zma) | 66,143 |
def create_parent_parser(prog_name):
"""
Create parent parser
Args:
prog_name (str): program name
Returns:
parser: parent argument parser
Raises:
DistributionNotFound: version of family not found
"""
parent_parser = argparse.ArgumentParser(prog=prog_name, add_help... | 66,144 |
def copy_chunks(old_id, new_id, hosts):
"""Function for copying the content of the chunks of a file (operation required for cp).
Parameters
----------
old_id --> str, source file prefix
new_id --> str, destination file prefix
hosts --> list, the datanodes which maintain some replicas of the... | 66,145 |
def rescaleImage(image, output_size=128, scale=1 / 255.0):
"""Rescale the image in a sample to a given size.
Args:
output_size (tuple or int): Desired output size. If tuple, output is
matched to output_size. If int, smaller of image edges is matched
to output_size keeping as... | 66,146 |
def generate_and_write_mol_dataset(task_type: tasks.Task):
"""Generate all variables and optionally files needed for a molecular task."""
task = tasks.get_task(task_type)
use_h = task_type == tasks.Task.crippen
use_data_aug = isinstance(
task.task_type,
tasks.BinaryClassificationTaskType... | 66,147 |
def mkdir_p(path):
"""mkdir_p(path) - Make the "path" directory, if it does not exist; this
will also make directories for any missing parent directories."""
import errno
if not path or os.path.exists(path):
return
parent = os.path.dirname(path)
if parent != path:
mkdir_p(paren... | 66,148 |
def test_run(ray_start_2_cpus):
"""Tests that Train can be run without any specific backends."""
num_workers = 2
key = "value"
value = 1
config = TestConfig()
def train_func():
checkpoint = train.load_checkpoint()
train.report(**checkpoint)
train.save_checkpoint(**checkp... | 66,149 |
def import_files(configuration):
"""
Import trades from configured files.
"""
return CsvOrderImporter(configuration).import_orders() | 66,150 |
def image_targets_bottom(x, model_hparams, vocab_size):
"""Bottom transformation for target images."""
pixel_embedding_size = 64
inputs = x
with tf.variable_scope("image_modality"):
if not tf.executing_eagerly():
tf.summary.image(
"targets_bottom",
common_layers.tpu_safe_image_summ... | 66,151 |
def _GetEventTriggerEventParams(trigger_event, trigger_resource):
"""Get the args for creating an event trigger.
Args:
trigger_event: The trigger event
trigger_resource: The trigger resource
Returns:
A dictionary containing trigger_provider, trigger_event, and
trigger_resource.
"""
trigger_pr... | 66,152 |
def pie_chart(start_date, end_date):
# select date range
"""
Presents the day of the week proportion summary of the energy consumed by the appliances in the house.
Parameters
----------
df : pd.DataFrame(selected_data)
Groups the initial dataframe by day_of_week.
start_date : start... | 66,153 |
def _propose_rois_tpu(scores,
boxes,
anchor_boxes,
height,
width,
scale,
rpn_pre_nms_topn,
rpn_post_nms_topn,
rpn_nms_threshold,
... | 66,154 |
def has_text_an_image(text):
"""
:param text: String with base64 data
:return: true if text has base64 data otherwise false
"""
regex_to_extract = r'data:image.+\"'
return re.search(regex_to_extract, text) | 66,155 |
def grab_dir(inpath, outdir=None, r=False):
"""
Grabs all image files in a directory
:param inpath: path to directory of desired files
:param outdir: path to output csv directory, to check for existing images
:param r: Recursively grab images from all subdirectories as well
:return: list of imag... | 66,156 |
def post(url, data={}, headers={}, files=None, cookies=None, auth=None, **kwargs):
"""Sends a POST request. Returns :class:`Response` object.
:param url: URL for the new :class:`Request` object.
:param data: (optional) Dictionary of POST data to send with the :class:`Request`.
:param headers: (optional... | 66,157 |
def _get_max(lhs, rhs):
"""Get max value"""
if lhs < 0:
return lhs
if rhs < 0:
return rhs
return max(lhs, rhs) | 66,158 |
def csr_matmat(data, indices, indptr, B, *, shape, transpose=False):
"""Product of CSR sparse matrix and a dense matrix.
Args:
data : array of shape ``(nse,)``.
indices : array of shape ``(nse,)``
indptr : array of shape ``(shape[0] + 1,)`` and dtype ``indices.dtype``
B : array of shape ``(shape[0]... | 66,159 |
def create_output_dir_for_chromosome(output_dir, chr_name):
"""
Create an internal directory inside the output directory to dump chromosomal summary files
:param output_dir: Path to output directory
:param chr_name: chromosome name
:return: New directory path
"""
path_to_dir = output_dir + c... | 66,160 |
def simplify_elaspic_data(data) -> DataFrame:
"""
Given ELASPIC results data, simplify it into three columns: "UniProt_ID", "Mutation", "Interactor_UniProt_ID".
"""
data = data[["UniProt_ID", "Mutation", "Interactor_UniProt_ID"]].copy(deep=True)
return data | 66,161 |
def pickle_load(content, safe_to_import=None):
"""
**pickle_load**
Load the pickled content. content should be a bytes object.
**Parameters**
content : Bytes of pickled object. It needs to have Delta header in it that is
separated by a newline character from the rest of the pickled object.... | 66,162 |
def import_string(dotted_path: str):
"""
Import a dotted module path and return the attribute/class designated by the
last name in the path. Raise ImportError if the import failed.
"""
try:
module_path, class_name = dotted_path.rsplit(".", 1)
except ValueError as err:
raise Impor... | 66,163 |
def get_new_ids(index, playlist_name, client):
"""
Gets a list of youtube videoIDs that are in the Elasticsearch index but not
in the Youtube playlist
"""
playlist_id = get_playlist_id(playlist_name, client)
# Force evaluation of scan here since it can throw an exception if done
# lazily (El... | 66,164 |
def process_articles(articles_list):
"""Function that processes the article results and transforms them to a list of Article Objects"""
articles_results = []
for article in articles_list:
author = article.get("author")
article_title = article.get("title")
article_description = articl... | 66,165 |
def _check_for_transfer(G, custom_msg=None):
"""
A helper function to assert whether the given object is a State or
Transfer.
"""
if not isinstance(G, Transfer):
if custom_msg is None:
custom_msg = 'The argument should be a Transfer'\
'. Instead found a {... | 66,166 |
def create_pool_if_not_exist(batch_client, pool):
"""Creates the specified pool if it doesn't already exist
:param batch_client: The batch client to use.
:type batch_client: `batchserviceclient.BatchServiceClient`
:param pool: The pool to create.
:type pool: `batchserviceclient.models.PoolAddParame... | 66,167 |
def wait_for_processes(processes):
"""
Wait for the given processes to end.
Prints an overview of running processes to the terminal once a second so
the user knows what they are waiting for.
This function is not specific to :mod:`proc.cron` at all (it doesn't
even need to know what cron jobs a... | 66,168 |
def delete_vocabulary(word_id: int) -> str:
"""削除する"""
slack_msg = "該当する番号は見つからなかったっぽ!"
with VocabularyDatabase() as v_d:
result = v_d.get_word_list()
cnt = 1
for row in result:
row_id, _ = row
if cnt == word_id:
delete_id = row_id
... | 66,169 |
async def async_setup_entry(
hass: HomeAssistant,
config_entry: ConfigEntry,
async_add_entities: AddEntitiesCallback,
) -> None:
"""Add a weather entity from a config_entry."""
coordinator = hass.data[DOMAIN][config_entry.entry_id]
async_add_entities(
[
MetWeather(
... | 66,170 |
def write_quake_brush_cube(fw, ob, faces):
"""
Takes 6 faces and writes a brush,
these faces can be from 1 mesh, 1 cube within a mesh of larger cubes
Faces could even come from different meshes or be contrived.
"""
format_vec = '( %d %d %d ) ' if PREF_GRID_SNAP else '( %.9g %.9g %.9g ) '
fw... | 66,171 |
def process_all():
"""Process all unprocessed sequences."""
couch = couchdb.Server()
db = couch["fecs"]
for row in db.view("sequences/need-tdc-processing"):
response = db.get_attachment(row.id, "tdc.npy")
if response is not None:
# convert to byte file which np.load can pro... | 66,172 |
def regnety160(**kwargs):
"""
RegNetY-16GF model from 'Designing Network Design Spaces,' https://arxiv.org/abs/2003.13678.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for... | 66,173 |
def write_val_file(image_path, mask_path, val_names, out_path, num_sample):
"""
Write validation point clouds in to a numpy file
All validation data as an area
"""
for val_name in tqdm(val_names):
points, labels = get_points_label(image_path, mask_path, val_name)
out_file = np.conca... | 66,174 |
def test_name():
"""pytest: test set/get name"""
for group_info in all_group_info:
group = ReportGroup()
group.set_name(group_info["name"])
assert group.get_name() == group_info["name"] | 66,175 |
def unicode_open(filename, *args, **kwargs):
"""
Opens a file with UTF-8 encoding, in a Python 2- and 3-compatible way.
:param filename: Name of file to open.
:param *args: Optional args to be passed on to `open()`.
:param **kwargs: Optional kwargs to be passed on to `open()`.
"""
kwargs['... | 66,176 |
def tupled_argmax(a):
"""
Argmax that returns an index tuple. Note that `numpy.argmax` will return a
scalar index as if you had flattened the array.
Parameters
----------
a : array_like
Input array.
Returns
-------
index : tuple
Tuple of index, even if `a` is one-di... | 66,177 |
def flood_fill(board, start_pos, allow_start_in_occupied_cell=False):
""" Flood fill is an algorithm that expands from a starting position into adjacent
vacant cells. Returns the set of all vacant cells found.
If allow_start_in_occupied_cell is True, the flood fill start position may be occupied
and th... | 66,178 |
async def register(app: web.Application):
"""Register routes."""
app.add_routes(
[web.post("/connections/{conn_id}/start-introduction", introduction_start)]
) | 66,179 |
def record_permission_factory(record=None, action=None):
"""Record permission factory."""
return RecordPermission.create(record, action) | 66,180 |
def create_parameter(name, **kwargs):
"""Create ArcPy parameter object using an attribute mapping.
Note that this doesn't check if the attribute exists in the default
parameter instance. This means that you can attempt to set a new
attribute, but the result will depend on how the class implements ... | 66,181 |
def init_notification_views(app):
"""Add url rules for all notification views.
Args:
app: current flask app.
"""
app.add_url_rule(
"/_notifications/send_todays_digest", "send_todays_digest_notifications",
view_func=common.send_todays_digest_notifications)
app.add_url_rule(
"/_notificat... | 66,182 |
def title_match_ratio(title1, title2):
"""
Returns a number between 0 and 100, representing the percent
match (Levenshtein Distance) between book title1 and book title2,
after each has been normalized.
"""
title1 = normalize_title_for_matching(title1)
title2 = normalize_title_for_matching(ti... | 66,183 |
def get_theme(txt, min_topic_freq=0.05):
"""return the most likely topic based on text"""
new_doc = get_tokens(txt)
new_doc_bow = dictionary.doc2bow(new_doc)
main_theme = sorted(lda.get_document_topics(new_doc_bow), key=itemgetter(1), reverse=True)[0]
return main_theme | 66,184 |
def merge(lhs: _cpp.Dataset, rhs: _cpp.Dataset) -> _cpp.Dataset:
"""Merge two datasets into one.
:param lhs: First dataset.
:param rhs: Second dataset.
:raises: If there are conflicting items with different content.
:return: A new dataset that contains the union of all data items,
coor... | 66,185 |
def calc_uff_atom_types(bonds, elements, override_rules=None):
"""
"""
g = nx.Graph()
g.add_edges_from(bonds)
if override_rules is None:
override_rules = default_uff_rules()
uff_keys = UFF4MOF.keys()
atom_types = []
add_aromatic_flag(g)
for n in sorted(g.nodes):
#... | 66,186 |
def _extract_asm_mnemonic(asm):
"""
:param asm:
:type asm:
"""
return asm.split()[0].strip().upper() | 66,187 |
def calc_model_age(t2_parent, t1_parent, t2_daughter, t1_daughter,
decay_constant):
"""Calculate the model age of a sample. NOTE: THIS FUNCTION IS UNDER
TESTING AND MAY NOT GIVE THE CORRECT ANSWER!
Parameters
----------
t2_parent : float
The measured parent composit... | 66,188 |
def PutWord(dst, val):
""" Put big-endian val byte by byte into dst. """
dst.append((val >> 8) & 0xFF)
dst.append(val & 0xFF) | 66,189 |
def AddAuthorizedNetworksFlag(parser):
"""Adds a `--authorized-networks` flag."""
cidr_validator = arg_parsers.RegexpValidator(
_CIDR_REGEX, ('Must be specified in CIDR notation, also known as '
'\'slash\' notation (e.g. 192.168.100.0/24).'))
help_text = """\
List of external network... | 66,190 |
def Tri(a, b, c, tag=None):
"""
A triangular random variate
Parameters
----------
a : scalar
Lower bound of the distribution support (default=0)
b : scalar
Upper bound of the distribution support (default=1)
c : scalar
The location of the triangle's peak (a <= c ... | 66,191 |
def test_escape_path(esc_path, esc_arg, esc_res):
"""Test escaping of special characters in path argument """
esc_arg = bren.validate_esc(esc_arg)
esc = helper.escape_path(esc_path, esc_arg)
assert esc == esc_res | 66,192 |
def reverse_match(text, dict_word, longest_term):
"""
反向最長匹配
參數 text : 要分詞的文字
參數 dict_word : 繁體中文詞語字典
參數 longest_term : 字典中最長詞語的長度
回傳值 : 一個串列 內部元素為 詞語的(起始索引,結束索引)
"""
result_list = []
stack = [] #因為反向最長匹配是由後往前進行分詞 所以使用堆疊的資料結構
end = len(text) - 1
while end... | 66,193 |
def available_packages():
"""Returns a list of package names available for the current version of Holodeck
Returns (:obj:`list` of :obj:`str`):
List of package names
"""
# Get the index json file from the backend
url = "packages/{ver}/available".format(ver=util.get_holodeck_version())
t... | 66,194 |
def mean(sample1, sample2, axis=0, sample_size=130, borders=0, max_sample=1460, ratio=True,
median=False, **kwargs):
""" Adjustment method using mean differences or ratios
ratio=False
dataset[sampleout] + (MEAN(dataset[sample1]) - MEAN(dataset[sample2]))
ratio=True
dataset[sampleout] * ... | 66,195 |
def get_mean_ztf_alert_braai(_db, ra, dec):
"""
Cross-match by position and get mean alert braai score
"""
try:
ra_geojson = float(ra)
# geojson-friendly ra:
ra_geojson -= 180.0
dec_geojson = float(dec)
''' catalogs '''
catalog = 'ZTF_alerts'
... | 66,196 |
def rasa_x(args: argparse.Namespace) -> None:
"""Run Rasa with the `x` subcommand."""
from rasa.cli.utils import signal_handler
signal.signal(signal.SIGINT, signal_handler)
if args.production:
run_in_enterprise_connection_mode(args)
else:
rasa.shared.utils.io.raise_warning(
... | 66,197 |
def _write_tfrecord(path, iterator):
"""Write single (non sharded) TFrecord file from iterator."""
with tf.io.TFRecordWriter(path) as writer:
for serialized_example in iterator:
writer.write(serialized_example)
writer.flush() | 66,198 |
def get_spaces(depth):
"""returns the required number of spaces
for indentation purpose"""
return ' ' * (depth * 4 - 2) | 66,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.