content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def test_FeatureSetSelector_3():
"""Assert that the StackingEstimator returns transformed X based on 2 subsets' names"""
ds = FeatureSetSelector(subset_list="tests/subset_test.csv", sel_subset=["test_subset_1", "test_subset_2"])
ds.fit(test_X, y=None)
transformed_X = ds.transform(test_X)
assert tra... | 29,200 |
def initialize_builtin_extensions():
"""Initialize third-party extensions."""
app = current_app._get_current_object()
db.init_app(app)
migrate.init_app(app, db=db)
babel.init_app(app)
initialize_security(app) | 29,201 |
def collaspe_fclusters(data=None, t=None, row_labels=None, col_labels=None,
linkage='average', pdist='euclidean', standardize=3, log=False):
"""a function to collaspe flat clusters by averaging the vectors within
each flat clusters achieved from hierarchical clustering"""
## preprocess data
if log:
data = np.l... | 29,202 |
def iapproximate_add_fourier_state(self,
lhs: Union[int, QuantumRegister],
rhs: QRegisterPhaseLE,
qcirc: QuantumCircuit,
approximation: int = None) -> ApproximateAddFourierStateGat... | 29,203 |
def _get_indices(A):
"""Gets the index for each element in the array."""
dim_ranges = [range(size) for size in A.shape]
if len(dim_ranges) == 1:
return dim_ranges[0]
return itertools.product(*dim_ranges) | 29,204 |
def test_prediction(prediction_gen, mail_info, api_url="http://127.0.0.1:5000/test-api?prediction_id=", result_wait_time=7):
"""tests prediction by generating posting prediction, waiting and geting prediction result
if result is an error send mail
"""
try:
# make prediction
predictio... | 29,205 |
def calculateOriginalVega(f, k, r, t, v, cp):
"""计算原始vega值"""
price1 = calculatePrice(f, k, r, t, v*STEP_UP, cp)
price2 = calculatePrice(f, k, r, t, v*STEP_DOWN, cp)
vega = (price1 - price2) / (v * STEP_DIFF)
return vega | 29,206 |
def test_string_representation() -> None:
"""Tests printable representation of Jobs."""
def dummy(msg):
pass
assert "Job(function=dummy, args=('a',), kwargs={'msg': 'a'})" == Job(dummy, ('a',), {'msg': 'a'}).__repr__()
assert "Job(function=dummy, args=('a',), kwargs={'msg': 'a'})" == Job(dummy... | 29,207 |
def run_ansible_lint(
*argv: str,
cwd: Optional[str] = None,
executable: Optional[str] = None,
env: Optional[Dict[str, str]] = None
) -> CompletedProcess:
"""Run ansible-lint on a given path and returns its output."""
if not executable:
executable = sys.executable
args = [sys.exe... | 29,208 |
def to_numpy(tensor):
""" Converts a PyTorch Tensor to a Numpy array"""
if isinstance(tensor, np.ndarray):
return tensor
if hasattr(tensor, 'is_cuda'):
if tensor.is_cuda:
return tensor.cpu().detach().numpy()
if hasattr(tensor, 'detach'):
return tensor.detach().numpy()... | 29,209 |
async def save_image_urls(channel, filename=_CARD_IMG_URLS_PATH):
"""Like upload_images but saves the resulting dict into a file."""
result = await upload_images(channel)
with open(filename, 'w') as f:
json.dump(result, f, indent=4, separators=(',', ': ')) | 29,210 |
def gradual_light_on(seconds):
"""
Gradually increases the light brightness from minimum to maximum in inputted
amount of time.
:param seconds: Time in seconds for the entire procedure to take.
"""
sleep_time = seconds / 255.0
light_bulb = Light(__connected_bridge(), ROOM_LIGHT_BULB_ID)
... | 29,211 |
def test_delete_request_db_contents(test_client):
""" A fixture to simply delete the db contents
(starting at Request() as the root - does not delete User() contents)
after each test runs
"""
print('----------Setup test_delete_request_db_contents fixture ----------')
yield # this is where the test is run
prin... | 29,212 |
def show_tables():
"""
Load all available data files that have the right format.
All files will be assumed to have the same 8 fields in the header.
This demonstrates pulling a specific file name as well as
wildcard file search in the uploads/ directory.
And as an example, filtering the data to o... | 29,213 |
def _redirect_io(inp, out, f):
"""Calls the function `f` with ``sys.stdin`` changed to `inp`
and ``sys.stdout`` changed to `out`. They are restored when `f`
returns. This function returns whatever `f` returns.
"""
import os
import sys
oldin, sys.stdin = sys.stdin, inp
oldout, sys.std... | 29,214 |
def _maybe_to_dense(obj):
"""
try to convert to dense
"""
if hasattr(obj, 'to_dense'):
return obj.to_dense()
return obj | 29,215 |
def update_visit_counter(visit_counter_matrix, observation, action):
"""Update the visit counter
Counting how many times a state-action pair has been
visited. This information can be used during the update.
@param visit_counter_matrix a matrix initialised with zeros
@param observation the state... | 29,216 |
def writeFileHashIndex(Data, Path, Filename=Cfg.HASH_INDEX_FILENAME):
"""
Write the file hash index to the specified path.
"""
writeYaml(Path, Filename, Data) | 29,217 |
def pandas_time_safe(series):
"""Pandas check time safe"""
return (series.map(dt_seconds)
if isinstance(series.iloc[0], datetime.time)
else series) | 29,218 |
def binary_cross_entropy_loss(predicted_y, true_y):
"""Compute the binary cross entropy loss between a vector of labels of size N and a vector of probabilities of same
size
Parameters
----------
predicted_y : numpy array of shape (N, 1)
The predicted probabilities
true_y : numpy array o... | 29,219 |
def money_flow_index(high, low, close, volume, n=14, fillna=False):
"""Money Flow Index (MFI)
Uses both price and volume to measure buying and selling pressure. It is
positive when the typical price rises (buying pressure) and negative when
the typical price declines (selling pressure). A ratio of posi... | 29,220 |
def insert_extracted_sources(image_id, results, extract_type='blind',
ff_runcat_ids=None, ff_monitor_ids=None):
"""
Insert all detections from sourcefinder into the extractedsource table.
Besides the source properties from sourcefinder, we calculate additional
attributes th... | 29,221 |
def main(**kwargs):
"""Entry point for GravityBee CLI."""
print("GravityBee CLI,", gravitybee.__version__)
# Create an instance
args = gravitybee.Arguments(**kwargs)
package_generator = gravitybee.PackageGenerator(args)
sys.exit(package_generator.generate()) | 29,222 |
def finalize():
"""Cleans up fault injection visualization
"""
print "Finalizing fault injection visualization..."
#conn.commit()
#conn.close() | 29,223 |
def parse_args(args=[], doc=False):
"""
Handle parsing of arguments and flags. Generates docs using help from `ArgParser`
Args:
args (list): argv passed to the binary
doc (bool): If the function should generate and return manpage
Returns:
Processed args and a copy of the `ArgPa... | 29,224 |
def gaussian_kernel_dx_i_dx_j(x, y, sigma=1.):
""" Matrix of \frac{\partial k}{\partial x_i \partial x_j}"""
assert(len(x.shape) == 1)
assert(len(y.shape) == 1)
d = x.size
pairwise_dist = np.outer(y-x, y-x)
x_2d = x[np.newaxis,:]
y_2d = y[np.newaxis,:]
k = gaussian_kernel(x_2d, y_2d, ... | 29,225 |
def clone_compressed_repository(base_path, name):
"""Decompress and clone a repository."""
compressed_repo_path = Path(__file__).parent / "tests" / "fixtures" / f"{name}.tar.gz"
working_dir = base_path / name
bare_base_path = working_dir / "bare"
with tarfile.open(compressed_repo_path, "r") as fix... | 29,226 |
def slices(series, length):
"""
Given a string of digits, output all the contiguous substrings
of length n in that string in the order that they appear.
:param series string - string of digits.
:param length int - the length of the series to find.
:return list - List of substrings of specif... | 29,227 |
def get_flight_time(dset):
"""Get flight time of GNSS signal between satellite and receiver
Args:
dset(Dataset): Model data
Return:
numpy.ndarray: Flight time of GNSS signal between satellite and receiver in [s]
"""
from where.models.delay import gnss_range # Local import to... | 29,228 |
def get_salary(request, responder):
"""
If a user asks for the salary of a specific person, this function returns their
hourly salary by querying into the knowledge base according to the employee name.
"""
responder = _get_person_info(request, responder, 'money')
try:
responder.reply("{... | 29,229 |
def textToTuple(text, defaultTuple):
"""This will convert the text representation of a tuple into a real
tuple. No checking for type or number of elements is done. See
textToTypeTuple for that.
"""
# first make sure that the text starts and ends with brackets
text = text.strip()
if t... | 29,230 |
def main():
"""Main module execution code path"""
AzureRMManagedDiskInfo() | 29,231 |
def draw_bboxes_with_labels(img, bboxes, label_indices, probs, labels):
"""Drawing bounding boxes with labels on given image.
inputs:
img = (height, width, channels)
bboxes = (total_bboxes, [y1, x1, y2, x2])
in denormalized form
label_indices = (total_bboxes)
probs = ... | 29,232 |
def m2m_bi2uni(m2m_list):
""" Splits a bigram word model into a unique unigram word model
i=11, j=3 i=10, j=3 i=9,10,11,12, j=3,4,5,6
###leilatem### ###leilatem### ###leilatem###
###temum### ###temum### ###temum###
^ ... | 29,233 |
async def run_server() -> None:
"""Begin listening for and handling connections on all endpoints."""
# we'll be working on top of transport layer posix sockets.
# these implement tcp/ip over ethernet for us, and osu!stable
# uses http/1.0 ontop of this. we'll need to parse the http data,
# find the... | 29,234 |
def time_func(func):
"""Times how long a function takes to run.
It doesn't do anything clever to avoid the various pitfalls of timing a function's runtime.
(Interestingly, the timeit module doesn't supply a straightforward interface to run a particular
function.)
"""
def timed(*args, **kwargs)... | 29,235 |
def GetPhiPsiChainsAndResiduesInfo(MoleculeName, Categorize = True):
"""Get phi and psi torsion angle information for residues across chains in
a molecule containing amino acids.
The phi and psi angles are optionally categorized into the following groups
corresponding to four types of Ramachandran plo... | 29,236 |
def generate_data(n_samples=30):
"""Generate synthetic dataset. Returns `data_train`, `data_test`,
`target_train`."""
x_min, x_max = -3, 3
x = rng.uniform(x_min, x_max, size=n_samples)
noise = 4.0 * rng.randn(n_samples)
y = x ** 3 - 0.5 * (x + 1) ** 2 + noise
y /= y.std()
data_train = p... | 29,237 |
def get_element_event(element_key):
"""
Get object's event.
"""
model = apps.get_model(settings.WORLD_DATA_APP, "event_data")
return model.objects.filter(trigger_obj=element_key) | 29,238 |
def test_md020_good_with_html_blocks():
"""
Test to make sure we get the expected behavior after scanning a good file from the
test/resources/rules/md020 directory that has a closed atx heading with bad spacing
inside of the start hashes, except that is is part of a html block.
"""
# Arrange
... | 29,239 |
def mock_os_path_join():
"""Fixture to mock join."""
with patch("os.path.join") as mock_path_join:
yield mock_path_join | 29,240 |
def func_3(csidata):
"""CSI: time-phase"""
s_index = 15 # subcarrier index
csi = csidata.get_scaled_csi_sm()
t = csidata.timestamp_low/1000000 - csidata.timestamp_low[0]/1000000
phase = np.unwrap(np.angle(csi), axis=1)
phase = calib(phase)
plt.figure()
plt.plot(t, phase[:, s_index, 0... | 29,241 |
def get_seller_price(sellers,seller_id,core_request):
"""
sellers is a list of list where each list contains follwing item in order
1. Seller Name
2. Number of available cores
3. Price of each core
4. List of lists where length of main list is equal to number of cores. Length of minor list will be zero.
seller_i... | 29,242 |
def create_affiliation_ttl(noun_uri: str, noun_text: str, affiliated_text: str, affiliated_type: str) -> list:
"""
Creates the Turtle for an Affiliation.
@param noun_uri: String holding the entity/URI to be affiliated
@param noun_text: String holding the sentence text for the entity
@param affiliat... | 29,243 |
def get_subpixel_indices(col_num: int) -> Tuple[int, int, int]:
"""Return a 3-tuple of 1-indexed column indices representing subpixels of a single pixel."""
offset = (col_num - 1) * 2
red_index = col_num + offset
green_index = col_num + offset + 1
blue_index = col_num + offset + 2
return red_ind... | 29,244 |
def sigmoid(x):
""" This function computes the sigmoid of x for NeuralNetwork"""
return NN.sigmoid(x) | 29,245 |
def extractTranslatingSloth(item):
"""
'Translating Sloth'
"""
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol or frag) or 'preview' in item['title'].lower():
return None
tagmap = [
('娘子我才是娃的爹', 'Wife, I Am the Baby\'s Father', 'translated'),
... | 29,246 |
def set_planet_count(request):
"""
"""
# Get the ip
ip = get_ip(request)
# Try to fetch count from cache.
planets = cache.get(ip)
if planets is None:
# Get latest blog posts
date = now() - timedelta(weeks=1)
planets = BlogPost.objects.filter(rank__gte=date)[:100].co... | 29,247 |
def human(number: int, suffix='B') -> str:
"""Return a human readable memory size in a string.
Initially written by Fred Cirera, modified and shared by Sridhar Ratnakumar
(https://stackoverflow.com/a/1094933/6167478), edited by Victor Domingos.
"""
for unit in ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z'... | 29,248 |
def _get_field_names(field: str, aliases: dict):
"""
Override this method to customize how
:param field:
:param aliases:
:return:
"""
trimmed = field.lstrip("-")
alias = aliases.get(trimmed, trimmed)
return alias.split(",") | 29,249 |
def get_answer(question_with_context):
"""
Get answer for question and context.
"""
# Create pipeline
question_answering_pipeline = pipeline('question-answering')
# Get answer
answer = question_answering_pipeline(question_with_context)
# Return answer
return answer | 29,250 |
def model_init():
"""
Initialize models.
"""
LOGGER.info("model-init") | 29,251 |
def undiskify(z):
"""Maps SL(2)/U(1) poincare disk coord to Lie algebra generator-factor."""
# Conventions match (2.13) in https://arxiv.org/abs/1909.10969
return 2* numpy.arctanh(abs(z)) * numpy.exp(1j * numpy.angle(z)) | 29,252 |
def mean_vertex_normals(vertex_count,
faces,
face_normals,
**kwargs):
"""
Find vertex normals from the mean of the faces that contain
that vertex.
Parameters
-----------
vertex_count : int
The number of vertices faces... | 29,253 |
def fast_scan(root, path=None, search_filter=fast_scan_regex_filter()):
"""
>>> import tempfile
>>> import pathlib
>>> tempdir = tempfile.TemporaryDirectory()
>>> for p in (map(partial(pathlib.Path, tempdir.name), (
... 'test/folder/1/file1.txt',
... 'test/folder/1/file2.txt',
..... | 29,254 |
def _silence_resource_warning(popen):
"""Silence Popen's ResourceWarning.
Note this should only be used if the process was created as a daemon.
"""
# Set the returncode to avoid this warning when popen is garbage collected:
# "ResourceWarning: subprocess XXX is still running".
# See https://bug... | 29,255 |
def migrate():
"""Run all migrations."""
migrations.upgrade() | 29,256 |
def get_beam_jobs():
"""Returns the list of all registered Apache Beam jobs.
Returns:
list(BeamJob). The list of registered Apache Beam jobs.
"""
return [beam_job_domain.BeamJob(j) for j in jobs_registry.get_all_jobs()] | 29,257 |
def p_exprlist(p):
"""exprlist : empty
| expr
| expr ',' exprlist
"""
if len(p) > 2:
p[0] = p[3]
p[0].append(p[1])
else:
p[0] = [p[1]] if p[1] else [] | 29,258 |
def z_norm(dataset, max_seq_len=50):
"""Normalize data in the dataset."""
processed = {}
text = dataset['text'][:, :max_seq_len, :]
vision = dataset['vision'][:, :max_seq_len, :]
audio = dataset['audio'][:, :max_seq_len, :]
for ind in range(dataset["text"].shape[0]):
vision[ind] = np.nan... | 29,259 |
def days_upto(year):
"""
Return the number of days from the beginning of the test period to the
beginning of the year specified
"""
return sum([days_in_year(y) for y in range(2000,year)]) | 29,260 |
def read_DEM(fn=None, fjord=None):
"""
Reads in the DEM (only accepts GeoTiffs right now) into an XArray Dataarray with the desired format.
"""
# intake.open_rasterio accepts a list of input files and may effectively do what this function does!
# try using cropped versions of the input files. Doesn'... | 29,261 |
def choose_field_size():
"""a function that crafts a field"""
while True:
print('Пожалуйста, задайте размер поля (число от 3 до 5):')
try:
field_size = int(input())
except ValueError:
continue
if field_size == 3:
print('\nПоле для игры:\n')
... | 29,262 |
def mbt_merge(source, *more_sources:str, dest:str, name='', description='', log=print):
""" Does a "real" merge, relying on [Upsert](https://www.sqlite.org/lang_UPSERT.html),
which was added to SQLite with version 3.24.0 (2018-06-04).
It relies on an index for the conflict detection,
but a... | 29,263 |
def delete_submission_change(id):
"""Delete a post.
Ensures that the post exists and that the logged in user is the
author of the post.
"""
db = get_db()
db.execute('DELETE FROM submission_change WHERE id = ?', (id,))
db.commit()
return jsonify(status='ok') | 29,264 |
async def test_cache_garbage_collection():
"""Test caching a template."""
template_string = (
"{% set dict = {'foo': 'x&y', 'bar': 42} %} {{ dict | urlencode }}"
)
tpl = template.Template(
(template_string),
)
tpl.ensure_valid()
assert template._NO_HASS_ENV.template_cache.get... | 29,265 |
def get_search_response(db, search_term):
"""Method to get search result from db or google api.
Args:
db: The database object.
search_term: The search term.
Returns:
String: List of relevant links separated by line break.
"""
# Find if the search results for the term is st... | 29,266 |
async def test_form_user_discover_fails_aborts_already_configured(hass):
"""Test if we manually configure an existing host we abort after failed discovery."""
await setup.async_setup_component(hass, "persistent_notification", {})
entry = MockConfigEntry(domain=DOMAIN, data=VALID_CONFIG, unique_id="BLID")
... | 29,267 |
def lattice_2d_rescale_wave_profile(kfit, X, dT, Z_C, Y_C, v, dx=1.):
"""
Fit the wave profile (X, dT) to the ODE solution (X_C, dT_C)
"""
# recenter the profile around 0
k0 = np.argmax(dT)
x0 = X[k0]
Z = kfit*(X.copy()-x0)
# retain a window corresponding to the input ODE solution
z... | 29,268 |
def extract_upload_zip4_text_files(zip_file_path, extract_file_path, s3_connection=None):
"""
Extracts text files from the specified zip4 zip file, uploads the files to s3 if bucket provided
Args:
zip_file_path: file path of the extracted zip4 zip
extract_file_path: file path... | 29,269 |
def extent_switch_ijk_kji(
extent_in: npt.NDArray[np.int_]) -> npt.NDArray[np.int_]: # reverse order of elements in extent
"""Returns equivalent grid extent switched either way between simulator and python protocols."""
dims = extent_in.size
result = np.zeros(dims, dtype = 'int')
for d in range... | 29,270 |
def create_data(f, x_vals):
"""Assumes f is a function of one argument
x_vals is an array of suitable arguments for f
Returns array containing results of applying f to the
elements of x_vals"""
y_vals = []
for i in x_vals:
y_vals.append(f(x_vals[i]))
return ... | 29,271 |
def merge(
left: pandas.core.frame.DataFrame,
right: pandas.core.frame.DataFrame,
how: Literal["left"],
):
"""
usage.dask: 4
"""
... | 29,272 |
def register():
"""注册"""
req_dict = request.get_json()
phone = req_dict.get("phone")
password = req_dict.get("password")
password2 = req_dict.get("password2")
sms_code = req_dict.get("sms_code")
phone = str(phone)
sms_code = str(sms_code)
# 校验参数
if not all([phone, password, pass... | 29,273 |
def print_exception(t, v, tb, limit=None, file=None, as_html=False,
with_filenames=True):
"""Print exception up to 'limit' stack trace entries from 'tb' to 'file'.
Similar to 'traceback.print_exception', but adds supplemental
information to the traceback and accepts two options, 'as_htm... | 29,274 |
def cpp_flag(compiler):
"""Return the -std=c++[11/14/17] compiler flag.
The newer version is prefered over c++11 (when it is available).
"""
flags = ["-std=c++17", "-std=c++14", "-std=c++11"]
for flag in flags:
if has_flag(compiler, flag):
return flag
raise RuntimeError(
... | 29,275 |
def make_model_vs_obs_plots(
cfg,
metadata,
model_filename,
obs_filename):
"""
Make a figure showing four maps and the other shows a scatter plot.
The four pane image is a latitude vs longitude figures showing:
* Top left: model
* Top right: observations
* Botto... | 29,276 |
def _validate_package_name(package_name: str):
"""Check that the package name matches the pattern r"[a-zA-Z_][a-zA-Z0-9_]*".
>>> _validate_package_name("this_is_a_good_package_name")
>>> _validate_package_name("this-is-not")
Traceback (most recent call last):
...
click.exceptions.BadParameter: ... | 29,277 |
def to_null(string):
"""
Usage::
{{ string|to_null}}
"""
return 'null' if string is None else string | 29,278 |
def get_mtime(path, mustExist=True):
"""
Get mtime of a path, even if it is inside a zipfile
"""
warnings.warn("Don't use this function", DeprecationWarning)
try:
return zipio.getmtime(path)
except IOError:
if not mustExist:
return -1
raise | 29,279 |
def get_table_8():
"""表 8 主たる居室の照明区画݅に設置された照明設備の調光による補正係数
Args:
Returns:
list: 表 8 主たる居室の照明区画݅に設置された照明設備の調光による補正係数
"""
table_8 = [
(0.9, 1.0),
(0.9, 1.0),
(1.0, 1.0)
]
return table_8 | 29,280 |
def csv_file_iterator(root_directory):
"""Returns a generator (iterator) of absolute file paths for CSV files in a given directory"""
for root_path, _, files in os.walk(root_directory, followlinks=True):
for f in files:
if f.endswith("csv"):
yield os.path.join(root_path, f) | 29,281 |
def query_epmc(query):
"""
Parameters
----------
query :
Returns
-------
"""
url = "https://www.ebi.ac.uk/europepmc/webservices/rest/search?query="
page_term = "&pageSize=999" ## Usual limit is 25
request_url = url + query + page_term
r = requests.get(request_url)
if... | 29,282 |
def register_unwinder(locus, unwinder, replace=False):
"""Register unwinder in given locus.
The unwinder is prepended to the locus's unwinders list. Unwinder
name should be unique.
Arguments:
locus: Either an objfile, progspace, or None (in which case
the unwinder is registered ... | 29,283 |
def is_default_array_type(f, type_map=TYPE_MAP):
"""
Check whether the field is an array and is made up of default types, e.g. u8 or s16.
"""
return f.type_id == 'array' and type_map.get(f.options['fill'].value, None) | 29,284 |
def delete_police_station_collection():
"""
Helper function to delete station collection in db.
"""
result = PoliceStation.objects().delete()
return result | 29,285 |
def compute_asvspoof_tDCF(
asv_target_scores,
asv_nontarget_scores,
asv_spoof_scores,
cm_bonafide_scores,
cm_spoof_scores,
cost_model,
):
"""
Compute t-DCF curve as in ASVSpoof2019 competition:
Fix ASV threshold to EER point and compute t-DCF curve over thresholds in CM.
... | 29,286 |
def generate_ul_fragment_patch(e, depth):
"""Similar to generate_fragment_patch, but for <ul>
"""
first_line_prefix = '{}* '.format(' ' * depth)
other_line_prefix = '{} '.format(' ' * depth)
for item in e:
if item.tag != '{http://www.w3.org/1999/xhtml}li':
raise ValueError("u... | 29,287 |
def print_stderr(exc_info: Any, stream: Optional[TextIO] = None) -> None:
"""
if the exc_info has stderr attribute (like the subprocess.CalledProcessError)
that will be printed to stderr
>>> class ExcInfo(object):
... pass
>>> exc_info = ExcInfo()
>>> # test no stdout attribute
>>>... | 29,288 |
def all_divisor(n, includeN=True):
"""
>>> all_divisor(28)
[1, 2, 4, 7, 14, 28]
>>> all_divisor(28, includeN=False)
[1, 2, 4, 7, 14]
Derived from https://qiita.com/LorseKudos/items/9eb560494862c8b4eb56
"""
lower_divisors, upper_divisors = [], []
i = 1
while i * i <= n:
i... | 29,289 |
def isTrue(value, noneIsFalse=True):
"""
Returns True if <value> is one of the valid string representations for True.
By default, None is considered False.
"""
if not value:
if noneIsFalse:
return False
else:
return None
else:
return value.lower() in TRUE_STRINGS | 29,290 |
def test_MMParser_Attributes_NoChannel():
"""Will MMParser extract the acquisition info w/o a channel identifier?
"""
inputFilename = 'Cos7_Microtubules_12_MMStack_Pos1_locResults.dat'
datasetType = 'TestType'
mmParser = leb.MMParser()
mmParser.parseFilename(inputFilename, datase... | 29,291 |
def account_factory(app, company_factory):
""" Creates factory for creating fake companies
"""
pass | 29,292 |
def test_inspec_package_installed(host):
"""
Tests if inspec packages is installed.
"""
assert host.package(PACKAGE).is_installed | 29,293 |
def read_doc_labels(input_dir):
"""
:param input_dir:
:return: doc labels
"""
with open(input_dir + "doc_labels.pkl", 'rb') as fin:
labels = pickle.load(fin)
return labels | 29,294 |
def which(bin_dir, program):
"""
rough equivalent of the 'which' command to find external programs
(current script path is tested first, then PATH envvar)
"""
def is_executable(fpath):
return os.path.exists(fpath) and os.access(fpath, os.X_OK)
fpath, fname = os.path.split(program)
if... | 29,295 |
def search(catalog_number):
"""
A top level `catalog_number` search that returns a list of result dicts.
Usually catalog numbers are unique but not always hence the returned list.
"""
results = query(catalog_number)
result_list = []
for result in results:
dict_result = vars(result)["... | 29,296 |
def login_user(force_login=False, no_browser=False, no_local_server=False):
"""
Arguments:
force_login -- Force a login flow with Globus Auth, even if tokens are valid
no_browser -- Disable automaically opening a browser for login
no_local_server -- Disable local server for automatically... | 29,297 |
def fetch_csv_for_date(dt, session=None):
"""
Fetches the whole month of the give datetime
returns the data as a DataFrame
throws an exception data is not available
"""
if not session:
session = requests.session()
# build the parameters and fill in the requested date
# T... | 29,298 |
def get_stats_binary(stats, img, var_img, roi, suffix="", ignore_nan=True, ignore_inf=True, ignore_zerovar=True, min_nvoxels=10, mask=None):
"""
Get a set of statistics for a 3D image within an roi
:param img: 3D Numpy array
:param roi: 3D Numpy array with same dimensions as img and boolean data type
... | 29,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.