content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def texture_symmetry_predict_patches(classifier, data=None, data_backup_file='FeaturesForPreds'):
"""Predict if symetric pairs of patches taken in a dermoscopic image are similar or not using features extracted
with the `texture_symmetry_features()` function and stored in the "FeatureForPreds.csv" file.
... | 15,300 |
def stack_bands(source_path, mgrs_coordinate, save_path):
"""
Stacks bands
:param source_path: Path to source images
:param mgrs_coordinates: List of MGRS coordinates, for example ['31/U/FQ', '31/U/FO']
:param save_path: Directory where a stacked raster would be saved
"""
# selecting the SW... | 15,301 |
def instantiateSong(fileName):
"""Create an AudioSegment with the data from the given file"""
ext = detectFormat(fileName)
if(ext == "mp3"):
return pd.AudioSegment.from_mp3(fileName)
elif(ext == "wav"):
return pd.AudioSegment.from_wav(fileName)
elif(ext == "ogg"):
return pd.A... | 15,302 |
def get_href(link: bs4.element.Tag) -> str:
"""If a link has an href attribute, return it
:param link: The link to be checked
:returns: An href
"""
if (link.has_attr("href")):
return (link["href"]) | 15,303 |
def get_contrib_requirements(filepath: str) -> Dict:
"""
Parse the python file from filepath to identify a "library_metadata" dictionary in any defined classes, and return a requirements_info object that includes a list of pip-installable requirements for each class that defines them.
Note, currently we ar... | 15,304 |
def main(files: List[pathlib.Path], name: str) -> None:
"""Create samplesheet for list of files"""
data = []
for file in files:
dir = file.parent
id_ = dir.stem
otu_table = dir / "otu_table.tsv"
obs_metadata = dir / "obs_metadata.tsv"
sample_metadata = dir / "sample_m... | 15,305 |
def test_database(app: Flask):
"""Initializes database for testing purposes."""
# Create the database and the database table
db_session = connect_db(app)
# db_session.create_all()
yield db_session, {"Project": Project, "Item": Item, "Option": Option}
# db_session.drop_all() | 15,306 |
def _append_to_kokoro_bazel_invocations(invocation_id: str) -> None:
"""Kokoro can display "Bazel" result link on kokoro jobs if told so."""
# to get "bazel" link for kokoro build, we need to upload
# the "bazel_invocation_ids" file with bazel invocation ID as artifact.
kokoro_artifacts_dir = os.getenv(... | 15,307 |
def watch(endpoint, key):
"""watch sends watch request to etcd.
Examples:
curl -L http://localhost:2379/v3alpha/watch \
-X POST -d ''{"create_request": {"key":"Zm9v"} }'
"""
# Python 2
# key_str = base64.b64encode(key)
# Python 3 base64 requires utf-08 encoded bytes
# Pyth... | 15,308 |
def __zedwalther(kin):
"""
Calculate the z-parameter for the Walther equation (ASTM D341).
Parameters
----------
kin: scalar
The kinematic viscosity of the lubricant.
Returns
-------
zed: scalar
The z-parameter.
"""
zed = kin + 0.7 + 10 ** (-1.47 - 1.84 * kin ... | 15,309 |
def o1_cosmologies_list():
"""
Return the list of $\\sigma_8$ values used in training Q1
:return: A numpy array of 20 $\\sigma_8$ values
"""
return np.array([0.969, 0.654, 1.06, 0.703,
1.1615, 0.759, 0.885, 0.6295,
0.605, 0.7205, 1.1685, 1.179,
... | 15,310 |
def chrelerr(fbest, stop):
"""
checks whether the required tolerance for a test function with known
global minimum has already been achieved
Input:
fbest function value to be checked
stop(0) relative error with which a global minimum with not too
small absolute value ... | 15,311 |
def prop_test(df):
"""
Inspired from R package caret confusionMatrix.R
"""
from scipy.stats import binom
x = np.diag(df).sum()
n = df.sum().sum()
p = (df.sum(axis=0) / df.sum().sum()).max()
d = {
"statistic": x, # number of successes
"parameter": n, # number of trials
... | 15,312 |
def time_and_log_query( fn ):
"""
Decorator to time operation of method
From High Performance Python, p.27
"""
@wraps( fn )
def measure_time( *args, **kwargs ):
t1 = time.time()
result = fn( *args, **kwargs )
t2 = time.time()
elapsed = t2 - t1
log_query( ... | 15,313 |
def parse_anchor_body(anchor_body):
"""
Given the body of an anchor, parse it to determine what topic ID it's
anchored to and what text the anchor uses in the source help file.
This always returns a 2-tuple, though based on the anchor body in the file
it may end up thinking that the topic ID and th... | 15,314 |
def func_parameters(func_name):
"""
Generates function parameters for a particular function.
Parameters
----------
func_name : string
Name of function.
Returns
--------
d : integer
Size of dimension.
g : gradient of objective function.
`g(x, *func_ar... | 15,315 |
def range_overlap(range1, range2):
"""
determine range1 is within range2 (or is completely the same)
:param range range1: a range
:param range range2: another range
:rtype: bool
:return: True, range1 is subset of range2, False, not the case
"""
result = all([
range1.start >= ra... | 15,316 |
def _expand_query_list(session, queries, recursive=False, verbose=False):
"""This function expands ls queries by resolving relative paths,
expanding wildcards and expanding recursive queries. If the user provides no
queries, the method defaults to a single nonrecursive query for the current working director... | 15,317 |
def qsnorm(p):
"""
rational approximation for x where q(x)=d, q being the cumulative
normal distribution function. taken from Abramowitz & Stegun p. 933
|error(x)| < 4.5*10**-4
"""
d = p
if d < 0. or d > 1.:
print('d not in (1,1) ')
sys.exit()
x = 0.
if (d - 0.5) > 0:... | 15,318 |
def check_auth(username, password):
"""This function is called to check if a username /
password combination is valid.
"""
user = User.query.filter(User.name==username and User.password_hash==encrypt_password(passsword)).first()
if user == None:
return False
else:
return True | 15,319 |
def redirect_success():
"""Save complete jsPsych dataset to disk."""
if request.is_json:
## Retrieve jsPsych data.
JSON = request.get_json()
## Save jsPsch data to disk.
write_data(session, JSON, method='pass')
## Flag experiment as complete.
session['complete'] = 'su... | 15,320 |
def fill_region(compound, n_compounds, region, overlap=0.2,
seed=12345, edge=0.2, temp_file=None):
"""Fill a region of a box with a compound using packmol.
Parameters
----------
compound : mb.Compound or list of mb.Compound
Compound or list of compounds to be put in region.
... | 15,321 |
def morris_traversal(root):
"""
Morris(InOrder) travaersal is a tree traversal algorithm that does not employ
the use of recursion or a stack. In this traversal, links are created as
successors and nodes are printed using these links.
Finally, the changes are reverted back to restore the original t... | 15,322 |
def validateILine(lineno, line, prevline, filename):
""" Checks all lines that start with 'i' and raises an exepction if
the line is malformed.
i lines are made up of five fields after the 'i':
From http://genome.ucsc.edu/FAQ/FAQformat#format5 :
src -- The name of the source sequence for the alignment.
... | 15,323 |
def normalize_matrix_rows(A):
"""
Normalize the rows of an array.
:param A: An array.
:return: Array with rows normalized.
"""
return A / np.linalg.norm(A, axis=1)[:, None] | 15,324 |
def UADDW(cpu_context: ProcessorContext, instruction: Instruction):
"""Unsigned add wide (vector form)"""
logger.debug("%s instruction not currently implemented.", instruction.mnem) | 15,325 |
def clear_cache() -> int:
"""
Очистка локального кэша форматов, меню и прочих ресурсов,
прочитанных с сервера.
:return: код возврата
"""
return IC_clearresourse() | 15,326 |
def plot_inner_iterations(err):
"""
Auxiliary function for plotting inner iterations error.
"""
plt.yscale('log') #logarithmic scale for y axis
plt.plot(np.arange(err.size),err,'.-')
plt.ylabel("Log relative error: $f_o(x^k)$ y $p^*$",size=12)
plt.xlabel("Inner iterations",size=12)
plt.g... | 15,327 |
def get_files_by_ymd(dir_path, time_start, time_end, ext=None, pattern_ymd=None):
"""
:param dir_path: 文件夹
:param time_start: 开始时间
:param time_end: 结束时间
:param ext: 后缀名, '.hdf5'
:param pattern_ymd: 匹配时间的模式, 可以是 r".*(\d{8})_(\d{4})_"
:return: list
"""
files_found = []
if pattern_y... | 15,328 |
def transform(shiftX=0.0, shiftY=0.0, rotate=0.0, skew=0.0, scale=1.0):
"""
Returns an NSAffineTransform object for transforming layers.
Apply an NSAffineTransform t object like this:
Layer.transform_checkForSelection_doComponents_(t,False,True)
Access its transformation matrix like this:
tMatrix = t.transformS... | 15,329 |
def test_create_order(function_arn, table_name, order_request):
"""
Test the CreateOrder function
"""
order_request = copy.deepcopy(order_request)
table = boto3.resource("dynamodb").Table(table_name) #pylint: disable=no-member
lambda_ = boto3.client("lambda")
# Trigger the function
re... | 15,330 |
def get_entity(text, tokens):
"""获取ner结果
"""
# 如果text长度小于规定的max_len长度,则只保留text长度的tokens
text_len = len(text)
tokens = tokens[:text_len]
entities = []
entity = ""
for idx, char, token in zip(range(text_len), text, tokens):
if token.startswith("O") or token.startswith(app.model_co... | 15,331 |
def new_func(message):
"""
new func
:param message:
:return:
"""
def get_message(message):
"""
get message
:param message:
:return:
"""
print('Got a message:{}'.format(message))
return get_message(message) | 15,332 |
def run_cmd(cmd: Union[list, str], capture_output: bool = False) -> None:
"""Run a shell command.
:param cmd: The command to run.
:param capture_output: Whether to capture stdout and stderr of the command.
"""
proc = sp.run(
cmd, shell=isinstance(cmd, str), check=True, capture_output=captur... | 15,333 |
async def test_new_users_available(hass):
"""Test setting up when new users available on Plex server."""
MONITORED_USERS = {"Owner": {"enabled": True}}
OPTIONS_WITH_USERS = copy.deepcopy(DEFAULT_OPTIONS)
OPTIONS_WITH_USERS[MP_DOMAIN][CONF_MONITORED_USERS] = MONITORED_USERS
entry = MockConfigEntry(... | 15,334 |
def process_midi(raw_mid, max_seq, random_seq, condition_token=False, interval = False, octave = False, fusion=False, absolute=False, logscale=False, label = 0):
"""
----------
Author: Damon Gwinn
----------
Takes in pre-processed raw midi and returns the input and target. Can use a random sequence ... | 15,335 |
async def test_secure_inner_join(
alice: DatabaseOwner, bob: DatabaseOwner, henri: Helper
) -> None:
"""
Tests entire protocol
:param alice: first database owner
:param bob: second database owner
:param henri: helper party
"""
await asyncio.gather(
*[alice.run_protocol(), bob.ru... | 15,336 |
def _rack_models():
"""
Models list (for racks)
"""
models = list(Rack.objects. \
values_list('rack_model', flat=True).distinct())
models.sort()
return models | 15,337 |
def confidence_ellipse(cov, means, ax, n_std=3.0, facecolor='none', **kwargs):
"""
Create a plot of the covariance confidence ellipse of *x* and *y*.
Parameters
----------
cov : array-like, shape (2, 2)
Covariance matrix
means: array-like, shape (2, )
Means array
ax : matp... | 15,338 |
def catalogResolveURI(URI):
"""Do a complete resolution lookup of an URI """
ret = libxml2mod.xmlCatalogResolveURI(URI)
return ret | 15,339 |
def high_low_difference(dataframe: pd.DataFrame, scale: float = 1.0, constant: float = 0.0) -> pd.DataFrame:
"""
Returns an allocation based on the difference in high and low values. This has been added as an
example with multiple series and parameters.
parameters:
scale: determines amplitude facto... | 15,340 |
def e_x(x, terms=10):
"""Approximates e^x using a given number of terms of
the Maclaurin series
"""
n = np.arange(terms)
return np.sum((x ** n) / fac(n)) | 15,341 |
async def parser(html: str) -> list:
"""解析页面
Args:
html (str): 返回页面的源码
Returns:
list: 最先的3个搜图结果(不满3个则返回所有,没有结果则返回str)
"""
if "No hits found" in html:
return "没有找到符合的本子!"
soup = BeautifulSoup(html, "lxml").find_all("table", class_="itg gltc")[0].contents
all_list = [... | 15,342 |
def set_namespace_root(namespace):
"""
Stores the GO ID for the root of the selected namespace.
Parameters
----------
namespace : str
A string containing the desired namespace. E.g. biological_process, cellular_component
or molecular_function.
Returns
-------
list
... | 15,343 |
def get_commit(oid):
"""
get commit by oid
"""
parents = []
commit = data.get_object(oid, 'commit').decode()
lines = iter(commit.splitlines())
for line in itertools.takewhile(operator.truth, lines):
key, value = line.split(' ', 1)
if key == 'tree':
tree = value
... | 15,344 |
def _gaussian_dilated_conv2d_oneLearned(x, kernel_size, num_o, dilation_factor, name, top_scope, biased=False):
"""
Dilated conv2d with antecedent gaussian filter and without BN or relu.
"""
num_x = x.shape[3].value
filter_size = dilation_factor - 1
sigma = _get_sigma(top_scope)
# create k... | 15,345 |
def get_cos_similarity(hy_vec, ref_vec):
"""
measure similarity from two vec
"""
return (1 - spatial.distance.cosine(hy_vec, ref_vec)) | 15,346 |
def addDepthDimension (ds):
"""
Create depth coordinate
Parameters
----------
ds : xarray DataSet
OOI Profiler mooring data for one profiler
Returns
-------
ds : xarray DataSet
dataset with iDEPTH coordinate set as a dimension
"""
if ( 'prof_depth' not in ds ):
... | 15,347 |
def divide_dataset_by_dataarray(ds, dr, varlist=None):
"""
Divides variables in an xarray Dataset object by a single DataArray
object. Will also make sure that the Dataset variable attributes
are preserved.
This method can be useful for certain types of model diagnostics
that have to be divide... | 15,348 |
async def connect(bot: DonLee_Robot_V2, update):
"""
A Funtion To Handle Incoming /add Command TO COnnect A Chat With Group
"""
chat_id = update.chat.id
user_id = update.from_user.id if update.from_user else None
target_chat = update.text.split(None, 1)
global VERIFY
if VERIFY.get(s... | 15,349 |
def count_words(my_str):
"""
count number of word in string sentence by using string spilt function.
INPUT - This is testing program
OUTPUT - 4
"""
my_str_list = my_str.split(" ")
return len(my_str_list) | 15,350 |
def suggest_create():
"""Create a suggestion for a resource."""
descriptors = Descriptor.query.all()
for descriptor in descriptors:
if descriptor.is_option_descriptor and \
descriptor.name != 'supercategories':
choices = [(str(i), v) for i, v in enumerate(descript... | 15,351 |
async def test_manual_update(hass: HomeAssistant) -> None:
"""Annual collection."""
config_entry: MockConfigEntry = MockConfigEntry(
domain=const.DOMAIN,
data={
"name": "test",
"frequency": "blank",
"manual_update": True,
},
title="blank",
... | 15,352 |
def remove_dataset_tags():
"""Command for removing tags from a dataset."""
command = Command().command(_remove_dataset_tags).lock_dataset()
return command.require_migration().with_commit(commit_only=DATASET_METADATA_PATHS) | 15,353 |
def delete_device(connection: Connection, id: str, error_msg: Optional[str] = None):
"""Delete a device.
Args:
connection: MicroStrategy REST API connection object
id: ID of the device
error_msg (string, optional): Custom Error Message for Error Handling
Returns:
Complete H... | 15,354 |
def run_job(job):
"""Handler that blocks until job is finished."""
job.poll(interval=2)
if job.status != "finished":
raise ValueError("Calculation job finished with status '{}'".format(job.status)) | 15,355 |
def build_model():
"""
Build a ML pipeline with RandomForest classifier GriSearch
:return: GridSearch Output
"""
pipeline = Pipeline([
('vect', CountVectorizer(tokenizer=tokenize)),
('tfidf', TfidfTransformer()),
('clf', MultiOutputClassifier(RandomForestClassifier()))
])... | 15,356 |
def init_bot():
"""Inits the bot."""
# We create the Reddit instance.
reddit = praw.Reddit(client_id=config.APP_ID, client_secret=config.APP_SECRET,
user_agent=config.USER_AGENT, username=config.REDDIT_USERNAME,
password=config.REDDIT_PASSWORD)
# Load ... | 15,357 |
def check_table_id_fn(
key_interaction):
"""Adds interaction, table and question id if missing."""
key, interaction = key_interaction
if not _has_valid_shape(interaction.table):
beam.metrics.Metrics.counter(_NS, "Tables empty or of ragged shape").inc()
return
if interaction.id and interaction.tabl... | 15,358 |
def test_renders_xml(app, context):
"""An xml extension results in no doctype and a application/xml mimetype"""
with app.test_request_context():
rendered = render_response("test.xml", context)
assert rendered.mimetype == "application/xml"
assert rendered.data == b"<name>Rudolf</name>"
... | 15,359 |
def basic_auth(func):
"""Decorator for basic auth"""
def wrapper(request, *args, **kwargs):
try:
if is_authenticated(request):
return func(request, *args, **kwargs)
else:
return HttpResponseForbidden()
except Exception, ex... | 15,360 |
async def test_transmute(request, user: str, env: str=None, group: [str]=None):
"""
API Description: Transmute Get. This will show in the swagger page (localhost:8000/api/v1/).
"""
return {
"user": user,
"env": env,
"group": group,
} | 15,361 |
def simdispim(incat=None, config=None, lambda_psf=None, dispim_name=None,
model_spectra=None, model_images=None, nx=None, ny=None,
exptime=None, bck_flux=0.0, extraction=True, extrfwhm=3.0,
orient=True, slitless_geom=True, adj_sens=True, silent=True):
"""
Main function ... | 15,362 |
def ref_from_rfgc(sample):
"""
rename columns from RFGC catalog
"""
ref = dict(
ra = sample['RAJ2000'],
dec = sample['DEJ2000'],
a = sample['aO'],
b = sample['bO'],
PA = sample['PA']
)
return ref | 15,363 |
def build_cmdline():
"""
creates OptionParser instance and populates command-line options
and returns OptionParser instance (cmd)
"""
cmd=optparse.OptionParser(version=__version__)
cmd.add_option('-c', '', dest='config_fname',type="string", help='WHM/WHMCS configuration file', metavar="FILE")
cmd.add_option('-s'... | 15,364 |
def get_repo_slugname(repo):
"""
>>> get_repo_slugname("https://build.frida.re")
build.frida.re
>>> get_repo_slugname("https://build.frida.re/./foo/bar")
build.frida.re
>>> get_repo_slugname("://build.frida.re")
build.frida.re
"""
parse_result = urllib.parse.urlparse(repo)
return... | 15,365 |
def check_asserttruefalse(logical_line, filename):
"""N328 - Don't use assertEqual(True/False, observed)."""
if 'ovn_octavia_provider/tests/' in filename:
if re.search(r"assertEqual\(\s*True,[^,]*(,[^,]*)?", logical_line):
msg = ("N328: Use assertTrue(observed) instead of "
... | 15,366 |
def run_file(file_path, globals_, script_dir=SCRIPT_DIR):
"""Execute the file at the specified path with the passed-in globals."""
script_name = os.path.basename(file_path)
if re.match(OAUTH_CLIENT_EXTRA_PATH_SCRIPTS, script_name):
extra_extra_paths = OAUTH_CLIENT_EXTRA_PATHS
elif re.match(GOOGLE_SQL_EXTRA... | 15,367 |
def create_znode(zookeeper_quorum, solr_znode, java64_home, retry = 5 , interval = 10):
"""
Create znode if does not exists, throws exception if zookeeper is not accessible.
"""
solr_cli_prefix = __create_solr_cloud_cli_prefix(zookeeper_quorum, solr_znode, java64_home, True)
create_znode_cmd = format('{solr_c... | 15,368 |
def lowess(x, y, f=2. / 3., itera=3):
"""lowess(x, y, f=2./3., iter=3) -> yest
Lowess smoother: Robust locally weighted regression.
The lowess function fits a nonparametric regression curve to a scatterplot.
The arrays x and y contain an equal number of elements; each pair
(x[i], y[i]) defines ... | 15,369 |
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Set up a config entry."""
tibber_connection = tibber.Tibber(
access_token=entry.data[CONF_ACCESS_TOKEN],
websession=async_get_clientsession(hass),
time_zone=dt_util.DEFAULT_TIME_ZONE,
)
hass.data[DO... | 15,370 |
def scenario_mask_vulnerable(plot=plt, show=False):
"""
creates scenario with different groups that are more or less vulnerable
Args:
plot: plot to show
show (bool): variable if graphic should be shown
Returns:
plot: plot to show
ani_humans: animation of the humans
... | 15,371 |
def _operator_parser(expr, first, current):
"""This method parses the expression string and substitutes
the temporal operators with numerical values.
Supported operators for relative and absolute time are:
- td() - the time delta of the current interval in days
and fractions of days ... | 15,372 |
def _read_data(filename):
"""
Read the script and return is as string
:param filename:
:return:
"""
javascript_path = _get_data_absolute_path(filename)
with open(javascript_path) as javascript:
return javascript.read() | 15,373 |
def xonshconfig(env):
"""Ensures and returns the $XONSHCONFIG"""
xcd = env.get("XONSH_CONFIG_DIR")
xc = os.path.join(xcd, "config.json")
return xc | 15,374 |
def file_open(filename, mode='r', encoding='utf8'):
"""Open file with implicit gzip/bz2 support
Uses text mode by default regardless of the compression.
In write mode, creates the output directory if it does not exist.
"""
if 'w' in mode and not os.path.isdir(os.path.dirname(filename)):
o... | 15,375 |
def schoollist():
"""
Return all the schools.
Return an empty schools object if no schools
:return:
"""
items = get_schools()
if items:
return response_for_schools_list(get_schools_json_list(items))
return response_for_schools_list([]) | 15,376 |
def getNumNullops(duration, max_sample=1.0):
"""Return number of do-nothing loop iterations."""
for amount in [2**x for x in range(100)]: # 1,2,4,8,...
begin = datetime.now()
for ii in xrange(amount): pass
elapsed = (datetime.now() - begin).total_seconds()
if elapsed > max_sampl... | 15,377 |
def get_dependencies_from_wheel_cache(ireq):
"""Retrieves dependencies for the given install requirement from the wheel cache.
:param ireq: A single InstallRequirement
:type ireq: :class:`~pip._internal.req.req_install.InstallRequirement`
:return: A set of dependency lines for generating new InstallReq... | 15,378 |
def hbp_fn():
"""Create a ReLU layer with HBP functionality."""
return HBPReLU() | 15,379 |
def plot_models_results(results, names, figsize=(16, 14), save=False, prefix_name_fig=None, folder='Charts'):
"""Compare the models plotting their results in a boxplot
Arguments --> the model results, their names, the figure size, a boolean to indicate if the plot has to be saved or not, the prefix nam... | 15,380 |
def xtrans(r):
"""RBDA Tab. 2.2, p. 23:
Spatial coordinate transform (translation of origin).
Calculates the coordinate transform matrix from A to B coordinates
for spatial motion vectors, in which frame B is translated by an
amount r (3D vector) relative to frame A.
"""
r1,r2,r3 = r
return matrix.sqr((
1... | 15,381 |
def get_chop_flux(obs, chunk_method="nanmedian", method="nanmean",
err_type="internal", weight=None, on_off=True):
"""
Calculate the flux in chopped data. The data will first be processed in each
chop chunk by chunk_method, unless the chunk_method is set to None or
'none' and the data ... | 15,382 |
def my_example_embeddings_method(paths, embedding_size, default_value=1):
"""
:param paths: (list) a list of BGP paths; a BGP path is a list of integers (ASNs)
:param embedding_size: (int) the size of the embedding
:param default_value: (int) the value for the embeddings
:return: (pandas dataframe o... | 15,383 |
def process_prompt_choice(value, prompt_type):
"""Convert command value to business value."""
if value is not None:
idx = prompt_type(value)
return idx
raise CommandError("The choice is not exist, please choice again.") | 15,384 |
def summarise_input(rawimg, labelimg):
"""This function takes as input: 'rawimg' (the data) and 'labelimg' (the cell boundary cartoon)
Then using the z=1, channel=1 frame, produces a summary table for inspection.
It also calculates which label is the background, assuming it is the largest cell.
It returns the fol... | 15,385 |
def create_inchi_from_ctfile_obj(ctf, **options):
"""Create ``InChI`` from ``CTfile`` instance.
:param ctf: Instance of :class:`~ctfile.ctfile.CTfile`.
:type ctf: :class:`~ctfile.ctfile.CTfile`
:return: ``InChI`` string.
:rtype: :py:class:`str`
"""
# apply fixed hydrogen layer when atom cha... | 15,386 |
def get_info(df, verbose = None,max_cols = None, memory_usage = None, null_counts = None):
""" Returns the .info() output of a dataframe
"""
assert type(df) is pd.DataFrame
buffer = io.StringIO()
df.info(verbose, buffer, max_cols, memory_usage, null_counts)
return buffer.getvalue() | 15,387 |
def get_directory_size(directory):
"""" Get directory disk usage in MB"""
directory_size = 0
for (path, dirs, files) in os.walk(directory):
for file in files:
directory_size += os.path.getsize(os.path.join(path, file))
return directory_size / (1024 * 1024.0) | 15,388 |
def iwave_modes(N2, dz, k=None):
"""
Calculates the eigenvalues and eigenfunctions to the internal wave eigenvalue problem:
$$
\left[ \frac{d^2}{dz^2} - \frac{1}{c_0} \bar{\rho}_z \right] \phi = 0
$$
with boundary conditions
"""
nz = N2.shape[0] # Remove the surface values
... | 15,389 |
def test_hollowsphere_degenerate_neighborhood():
"""Test either we sustain empty neighborhoods
"""
hs = ne.HollowSphere(1, inner_radius=0, element_sizes=(3,3,3))
assert_equal(len(hs((1,1,1))), 0) | 15,390 |
def run_sql_migration(config, migration):
"""
Returns bool
Runs all statements in a SQL migration file one-at-a-time. Uses get_statements as a generator in a loop.
"""
conn = config['conn']
write_log(config, "SQL migration from file '{}'".format(migration['filename']))
with op... | 15,391 |
def get_variable_type(n: int, data: Dict[str, Any]) -> str:
"""Given an index n, and a set of data,
return the type of a variable with the same index."""
if n in data[s.BOOL_IDX]:
return VariableTypes.BINARY
elif n in data[s.INT_IDX]:
return VariableTypes.INTEGER
return VariableTypes... | 15,392 |
def draw_boxes_on_image(image_path: str,
boxes: np.ndarray,
scores: np.ndarray,
labels: np.ndarray,
label_names: list,
score_thresh: float = 0.5,
save_path: str = 'result'):
... | 15,393 |
def pretty_print_expr(expr, indent=0):
"""Print Expr in a pretty way by recursion and indentation.
Arguments:
expr {Expr} -- the Expr to print
Keyword Arguments:
indent {int} -- spaces to indent (default: {0})
"""
if expr.op == 'id':
print(indent*'\t', expr.args[0])
els... | 15,394 |
def online_decompilation_main(result_path,path):
"""
:param online_decompiler_result_save_file: Store all the contract information in the name result.json, and then save it in this folder
:param solidity_code_result: The address of the folder where the source code of the contract obtained by parsing the fil... | 15,395 |
def filter_unit_name(merged_df:pd.DataFrame)->pd.DataFrame:
"""
Iteratively selects names that are close together based
on the Levenstein distance (number of added/inserted/
removed letters of make two strings identical).
TODO: this iterative approach is very inefficient and would
not scale. F... | 15,396 |
def calculate_snr(
Efield: np.ndarray,
freqRange: tuple,
h_obs: float = 525.0,
Nants: int = 1,
gain: float = 10.0,
) -> np.ndarray:
"""
given a peak electric field in V/m and a frequency range, calculate snr
Parameters
Efield: np.ndarray
peak electric field in V/m
freqRa... | 15,397 |
def retrieve_obj_indices(batch_cls: np.ndarray, num_classes: int):
"""Helper function to save the object indices for later.
E.g. a batch of 3 samples with varying number of objects (1, 3, 1) will
produce a mapping [[0], [1,2,3], [4]]. This will be needed later on in the
bipartite matching.
Paramete... | 15,398 |
def get_code_type(code):
"""
判断代码是属于那种类型,目前仅支持 ['fund', 'stock']
:return str 返回code类型, fund 基金 stock 股票
"""
if code.startswith(('00', '30', '60')):
return 'stock'
return 'fund' | 15,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.