content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def show(
document: vp.Document,
classic: bool,
force: bool,
show_pen_up: bool,
show_points: bool,
outline: bool,
colorful: bool,
show_axes: bool,
show_grid: bool,
hide_legend: bool,
unit: str,
):
"""Display the geometry in an graphical user interface.
By default, th... | 54,700 |
def _float(value):
"""Return env var cast as float."""
return float(value) | 54,701 |
def press(key: str) -> None:
"""
Press a key.
"""
print(key) | 54,702 |
def correctMSdataset(data, window=11, method='LOWESS', align='median', parallelise=True, excludeFailures=True):
"""
Conduct run-order correction and batch alignment on the :py:class:`~nPYc.objects.MSDataset` instance *data*, returning a new instance with corrected intensity values.
Sample are seperated into batches... | 54,703 |
def create_assignment_registry():
"""Create the registry for course properties."""
reg = FieldRegistry(
base.OfflineAssignmentBase.NAME,
description=base.OfflineAssignmentBase.DESCRIPTION)
# Course level settings.
reg.add_property(SchemaField(
'key', 'ID', 'string', editable=Fa... | 54,704 |
def do_s3_media_url(parser, token, static=False):
"""
This is for use with ``CloudFrontURLs`` and will return the appropriate url
if a match is found.
Usage::
{% s3_media_url path %}
For ``HTTPS``, the ``cuddlybuddly.storage.s3.middleware.ThreadLocals``
middleware must also be used.
... | 54,705 |
def wavlm(refresh=False, *args, **kwargs):
"""
The default model - Base-Plus
refresh (bool): whether to download ckpt/config again if existed
"""
return wavlm_base_plus(refresh=refresh, *args, **kwargs) | 54,706 |
def add_area_from_serialized_data(
annotation_model, area_id, serialized_area_data, lv0_height
):
"""Add point annotation data to annotation model from serialized_data"""
serialized_area_data = AreaAnnotationSerializedData(
*serialized_area_data
)
flag, area_record = create_area_annotati... | 54,707 |
def select_largest_3prime_footprint(transcripts):
"""Select transcript(s) with largest 3' footprint"""
ret = [transcripts[0]]
furthest = transcripts[0].utr3_end
for i in range(1, len(transcripts)):
t = transcripts[i]
utr3footprint = t.utr3_end
if utr3footprint == furthest:
... | 54,708 |
def read_mutation_matrix(file_in):
"""Create a table from a mutation matrix provided by SNPad
Returns
-------
tbl : Pandas.table
A table containing the mutation probability for base at each position of a read.
sn : list of dict
The list contains the highest probability for which we ... | 54,709 |
def ctc_cost(acts, labels, input_lengths = None):
"""
Given sequences of output layer activations and labels, compute the softmax output at each timestep,
and then compute the CTC cost of each sequence with respect to its corresponding label sequence.
:param acts: Tensor of pre-softmax activations, with shape=... | 54,710 |
def center_size(boxes):
""" Convert prior_boxes to (cx, cy, w, h)
representation for comparison to center-size form ground truth data.
Args:
boxes: (tensor) point_form boxes
Return:
boxes: (tensor) Converted xmin, ymin, xmax, ymax form of boxes.
"""
wh = boxes[:, 2:] - boxes[:, :... | 54,711 |
def train_network(data, supervisor):
"""
This function abstracts out the learning process for the Fuzzy ARTMAP algorithm.
:param data: The data of the training set
:param supervisor: The supervisor data, to train against
:return: new_network, the trained ARTMAP network utilised in classification and... | 54,712 |
def add(user_obj):
"""Add a User"""
user_obj.set_password()
return crud.add(user_obj) | 54,713 |
def perspective_transform(img):
"""
This class takes in the Gradient and Color Space thresholded binary image,
and perspective transforms the Binary image to halp make view the lanes to be
viewed from the top (as like in Bird's eye view). We take 4 source points that
are assumed to form a Quadrilat... | 54,714 |
def numericise(value, empty_value=''):
"""Returns a value that depends on the input string:
- Float if input can be converted to Float
- Integer if input can be converted to integer
- Zero if the input string is empty and empty2zero flag is set
- The same input string, empty or not, ... | 54,715 |
def test_likelihood_value():
"""Just a sanity check to show we get the right likelihood values"""
config = test_conf_reparam(events_per_day=1)
conv_config = deepcopy(BASE_CONV_CONFIG)
# initialize the old likelihood first
# this is an input for the reparameterized likelihood
lf_old = UnbinnedLog... | 54,716 |
def auto_delete_files(sender, instance, **kwargs):
"""
Delete task's file from system after delete.
"""
try:
task_file = instance.file
except Task.DoesNotExist:
return False
if task_file:
if os.path.isfile(task_file.path):
os.remove(task_file.path) | 54,717 |
def show_booking_page():
"""Show booking page."""
return render_template('booking.html')
# will need another route to process the booking form
| 54,718 |
def axis(*v, **kwargs):
"""
Convenience method to get or set axis properties.
Calling with no arguments::
>>> axis()
returns the current axes limits ``[xmin, xmax, ymin, ymax]``.::
>>> axis(v)
sets the min and max of the x and y axes, with
``v = [xmin, xmax, ymin, ymax]``.::
... | 54,719 |
def main():
"""CLI entry point"""
ensure_not_root()
try:
cli()
except FailedAPICallException as e:
sys.exit('Error: %s\n' % e.message)
except Exception as e:
sys.exit(e) | 54,720 |
def split_data(data, num_folds, fold):
"""
Partitions and returns selected partition
:param data: data
:param num_folds: num folds to make
:param fold: selected fold
:return: data_fold, data_rest
"""
X = data['X']
t = data['t']
xJoinT = np.c_[X, t]
rows = np.size... | 54,721 |
def fourthTab(modelProvided=None):
"""Get the values of controls and process"""
#Read global controls registered
global ctrls, commonData, normData, liveTrainingLoss
history = None
#Clear de previous output for dataframe or series - plot
plotHistoryOutput.clear_output()
plotModelResults... | 54,722 |
def buy(
symbol: str,
quantity: int,
duration: str = "gtc",
order_type: str = "market",
price: typing.Any = None,
stop: typing.Any = None,
brokerage: typing.Any = USER_BROKERAGE,
access_token: str = USER_ACCESS_TOKEN,
account_number: str = USER_ACC... | 54,723 |
def test_PATCH_patrao():
"""Tem de retornar o codigo 202, pois informará que a atualização do patrão foi aceita (PATCH)"""
response = patch(patroes + '2/' + '?public_key=2×tamp=' + TIMESTAMP_AGORA, {"usuario":"/api/v1/usuario/3/"})
assert_code(response, 202) | 54,724 |
def main():
"""
Main entry point for module execution
:returns: the result form module invocation
"""
module = AnsibleModule(
argument_spec=Prefix_listsArgs.argument_spec,
mutually_exclusive=[["config", "running_config"]],
required_if=[
["state", "merged", ["conf... | 54,725 |
def get_provider_info(provider_name):
"""Get provider info matching given provider name"""
return PROVIDERS_INFO.get(provider_name) | 54,726 |
def setRateLaw(neti:int, reai:int, rateLaw:str):
"""
setRateLaw edit rate law of reaction
errCode: -6: reaction index out of range
-5: net index out of range
"""
global stackFlag, errCode, networkSet, netSetStack, redoStack
errCode = 0
if neti < 0 or neti >= len(networkSet):
errC... | 54,727 |
def manage_sell(request):
"""
manage page
"""
#TODO judge whether the user is the super user
return RTR('manage_sell.html', {}) | 54,728 |
def close_ticket(session, ticket_id, return_type=None, **kwargs):
"""
Closes a support ticket for the VPSA.
:type session: zadarapy.session.Session
:param session: A valid zadarapy.session.Session object. Required.
:type ticket_id: int
:param ticket_id: The support ticket 'id' value as return... | 54,729 |
def download_img(img_url, save_filename):
"""
download image from a given url
:param img_url:
:param save_filename:
:return:
"""
response = requests.get(img_url, timeout=TIMEOUT)
if response.status_code not in [404, 403, 500]:
with open(save_filename, mode='wb') as f:
... | 54,730 |
def verify_mpls_ping(
device, address=None, mask=None, expected_max_success_rate=100,
expected_min_success_rate=0,count=None, source=None, vc_id=None,
tunnel_id=None, vrf=None, max_time=60, check_interval=10,):
"""Verify ping
Args:
device ('obj'): Device object
address ('s... | 54,731 |
def python(args):
"""
Generate an python shell with the client.
"""
import code
client = create_client(args)
code.interact(local={"client": client}) | 54,732 |
def get_module_mappings(label, attrs, srcs = [], workspace_name = None, mappings_attr = "es6_module_mappings"):
"""Returns the module_mappings from the given attrs.
Collects a {module_name - module_root} hash from all transitive dependencies,
checking for collisions. If a module has a non-empty `module_roo... | 54,733 |
def prepare_avd(device: str, avd_name: str):
"""
Create and run android virtual device.
:param device: Device name
:param avd_name: Name of android virtual device / emulator
"""
device_name_bash = device.replace(' ', '\ ')
skin_name = device.replace(' ', '_').lower()
# For custom hard... | 54,734 |
def cryoscope_v2_processing(
time_ns: np.array,
osc_data: np.array,
pnts_per_fit_first_pass: int = 4,
pnts_per_fit_second_pass: int = 3,
init_guess_first_pass: dict = {},
fixed_params_first_pass: dict = {},
init_guess_second_pass: dict = {},
max_params: dict = {},
min_params: dict = ... | 54,735 |
def test_calling_ruler_without_overwrite_will_keep_exisiting_ents(
nlp: Language, patterns: List[Dict[str, Any]], doc: Doc
) -> None:
"""It keeps existing ents without overwrite_ents."""
sr = SpaczzRuler(nlp, spaczz_patterns=patterns)
doc.ents += (
Span(doc, 2, 4, label="WRONG"),
Span(do... | 54,736 |
def map_reads(reads, genome_index, out_dir, annotation='', multimax=10, mismatches=2, threads=1):
"""
Map FASTQ file reads to reference genome.
TODO
Parameters
----------
reads : str
Sequencing reads to map to genome.
genome_index : str
Folder with genome index.
out_dir... | 54,737 |
def getCurrentSettingsAsDict():
"""
Returns the current babylon parameters saved in the root node as a dict
\nout:
dictionary key: pymxs user property string
value: var
"""
sceneRoot = sceneUtils.getSceneRootNode()
newDict = dict()
for val in BabylonPYMXS.bab... | 54,738 |
def isjsonclass(class_: type) -> bool:
"""Check if a class is jsonclass.
Args:
class_ (type): The class to check.
Returns:
bool: True if it's a jsonclass, otherwise False.
"""
return hasattr(class_, '__is_jsonclass__') | 54,739 |
def mu_from_pdiv(pdiv, nobj=3):
"""
Get population count based on divisions per objective for NSGA-III
"""
h = int(math.factorial(nobj + pdiv - 1) / (math.factorial(pdiv) * math.factorial(nobj - 1)))
mu = int(h + (4 - h % 4))
return mu | 54,740 |
def on_reload_plugins(branch='master'):
"""
`[branch]` - reload plugins in debot
"""
resp = []
try:
git_plugins_manager = current_app.extensions['git_plugins_manager']
except KeyError:
pass
else:
resp.append(git_plugins_manager.reload(branch))
dispatcher = current... | 54,741 |
def _get_model_cfg(fname):
"""Grab configs necessary to create a model.
These are deep copied to allow for safe modification of parameters without
influencing other tests.
"""
config = _get_config_module(fname)
model = copy.deepcopy(config.model)
return model | 54,742 |
def make_inference_request(serving_name, data, verb=":predict"):
"""
Submit an inference request
Example use-case:
>>> from hops import serving
>>> serving.make_inference_request("irisFlowerClassifier", [[1,2,3,4]], ":predict")
Args:
:serving_name: name of the model being served
... | 54,743 |
def online_variance(paths):
"""
Calculate mean and variance in an online way (Welford's algorithm)
:param paths:
:return:
"""
mean = np.zeros((conf.img_h, conf.img_w, conf.dest_channels))
M2 = np.zeros((conf.img_h, conf.img_w, conf.dest_channels))
i = 0
for i, path in tqdm(enumerate... | 54,744 |
def check_requires(request):
"""
This call checks whether a certain value requires another input to be filled.
"""
values = map(int, request.POST.getlist('value[]'))
model = apps.get_model(request.POST.get('app'), request.POST.get('model'))
required_values = model.objects.filter(**{
requ... | 54,745 |
def room2blocks(data, label, num_point,
block_size=100.0,
stride=50.0,
random_sample=False,
sample_num=None,
use_all_points=False):
""" Prepare block training data.
Args:
data (array-like): N x F numpy array, where N is t... | 54,746 |
def triggerBackup(locationKey, config, tokenData, args):
"""
Make a API request to start a backup.
Returns True on success and False on failure
"""
if config["locations"][locationKey]["enabled"] is False:
if args.verbose:
print "INFO: Skipping disabled location %s" % locatio... | 54,747 |
async def test_play_neil_with_pipes(audio_dest, audio_uri): # noqa: F811
"""Try pipe operators on the *Come on Baby Let's Go Downtown* intro.
This method is gapless. The `Transport` can keep the speaker
open while switching files.
"""
logging.debug('+++++++++++++++++++++>> BEGIN TEST_PLAY_NEIL_W... | 54,748 |
def start(name):
"""
Start running a recipe.
:param name:
The recipe name. Must be one of the items returned by /list
:return:
object
response
One of:
ok
error
message
Only present if response is "error" and there is a ... | 54,749 |
def get_conversion_factor(old_units, new_units):
"""
Use the conversion factors table to figure out the factor between these two
units.
Parameters
----------
old_units: Unit object
The current units.
new_units : Unit object
The units we want.
Returns
-------
con... | 54,750 |
def ate_exploitability(dist, payoff_tensor, p=1, aggregate=np.mean):
"""Compute Tsallis regularized exploitability of dist for non-symmetric game.
Args:
dist: list of 1-d np.arrays, current estimate of nash distribution
payoff_tensor: (n x A1 x ... x An) np.array, payoffs for each joint action
assume... | 54,751 |
def angular_cl_cov_SSC(cosmo, cltracer1, cltracer2, ell, tkka,
sigma2_B=None, fsky=1.,
cltracer3=None, cltracer4=None, ell2=None,
integration_method='qag_quad'):
"""Calculate the super-sample contribution to the connected
non-Gaussian covarian... | 54,752 |
def locals_in_putty():
"""Hard-coded information regarding local variables
"""
locals_d = {
# k: index
# v: dict of local properties
0x14007DA84: {
6: {'name': 'v6', 'size': 8, 'type_name': '__int64'},
7: {'name': 'v7', 'size': 8, 'type_name': '__int64'},
... | 54,753 |
def _post_apply_columns(
pydf: "PyDataFrame",
columns: ColumnsType,
) -> "PyDataFrame":
"""
Apply 'columns' param _after_ PyDataFrame creation (if no alternative).
"""
pydf_columns, pydf_dtypes = pydf.columns(), pydf.dtypes()
columns, dtypes = _unpack_columns(columns or pydf_columns)
if ... | 54,754 |
def join_blocks(splitted, final_shape):
"""Join blocks to reobtain a splitted image
Attribute:
splitted (tensor) = image splitted in blocks, size = (N_blocks, Channels, Height, Width)
final_shape (tuple) = size of the final image reconstructed (Height, Width)
Return:
tensor: image r... | 54,755 |
def Function2():
""" Function 2: get news from specific 30 major new press twitter accounts and analyze key word
analyze and visualize result from function3
"""
grt.RawTweet(recent_days=7).get_from_accounts('macro',savename='corona-2020-07-21') # get recent 3 days news from all 30 major press
key_wo... | 54,756 |
def log_agg_function_alpha(alpha, cent1, cent2):
""" Allows additional scaling of log_agg_function with a parameter alpha
to roughly get retain factors for BA use
retain factor 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9
alpha 1.7, 1.0, 0.7, 0.5, 0.4, 0.26, 0.2, 0.1, 0.015 """
return np.cli... | 54,757 |
def _init_():
"""初始化"""
global _env
_env = Properties(CONF_FILE_URL).properties | 54,758 |
def from_yaml(c: Type[T], s: str, de=YamlDeserializer, **opts) -> T:
"""
Take yaml string and return deserialized object..
>>> from dataclasses import dataclass
>>> from serde import deserialize
>>>
>>> @deserialize
... @dataclass
... class Settings:
... host: str
... po... | 54,759 |
def init_n4_only_wf(
atropos_model=None,
atropos_refine=True,
atropos_use_random_seed=True,
bids_suffix="T1w",
mem_gb=3.0,
name="n4_only_wf",
omp_nthreads=None,
):
"""
Build a workflow to sidetrack brain extraction on skull-stripped datasets.
An alternative workflow to "init_bra... | 54,760 |
def dvi( redchan, nirchan ):
"""
DVI: Difference Vegetation Index
dvi( redchan, nirchan )
"""
redchan = 1.0*redchan
nirchan = 1.0*nirchan
result = ( nirchan - redchan )
return result | 54,761 |
def needs_min_max_values(mode, buckets):
"""
Returns True, if an encoding mode needs minimum and maximum column values, otherwise False
"""
return not buckets and mode in ['one-hot',
'one-hot-gaussian',
'one-hot-gaussian-fluent',
... | 54,762 |
def test_prep_git_pr(py_package, runner):
"""With RH_BRANCH"""
env = dict(RH_BRANCH="foo", GITHUB_ACTIONS="")
result = runner(["prep-git", "--git-url", py_package], env=env)
os.chdir(util.CHECKOUT_NAME)
assert util.get_branch() == "foo", util.get_branch() | 54,763 |
def _rolling_player_f(player, gfcf, **kwargs):
"""
Creates a graph with CF% or GF% (on plus off). Use gfcf to indicate which one.
:param player: str or int, player to generate for
:param gfcf: str. Use 'G' for GF% and GF% Off and 'C' for CF% and CF% Off
:param kwargs: other filters. See scrapenhl2.... | 54,764 |
def param(myval=None):
"""Parameterised decorator example"""
if myval:
print(f"Param: {myval}")
def decorator(func): # real decorator
decorated["param"].append(func)
name = func.__name__
@wraps(func)
def wrapparam(*argv): # inner to return
arg_str = ",... | 54,765 |
def DownloadAllfiles(out):
""" Download any detailed feedback PDFs """
fileIds = []
# Grab the files for manufacturable submissions
if "bestScore" in out[0]:
for entry in out[0]["bestScore"]["manufacturingDetails"]:
if "detailedFeedback" in entry:
fileIds.app... | 54,766 |
def send_data_to_front(root_name, config_file):
"""
Sends data to front.
"""
saved_csv_file = os.path.join(config_file["extracted_data_path"], f"{root_name}.csv")
front_dst_file = os.path.join(config_file["front_data_path"], "data.csv")
shutil.copyfile(saved_csv_file, front_dst_file) | 54,767 |
def asset_spec_from_abspath(abspath, package):
""" Try to convert an absolute path to a resource in a package to
a resource specification if possible; otherwise return the
absolute path. """
if getattr(package, '__name__', None) == '__main__':
return abspath
pp = package_path(package) + os.... | 54,768 |
def to_prog():
"""Next dot_out() will be to the prog column"""
global field_idx
field_idx = F_PROG | 54,769 |
def listed_list(list_list):
"""Return presentable string from given list
"""
return '{} and {}'.format(', '.join(list_list[:-1]), list_list[-1]) if (
len(list_list) > 1) else list_list[0] | 54,770 |
def remove_plus_signs(_s: str) -> str:
"""Removes plus signs from string"""
return re.sub(pattern=r'\+', repl=r'', string=_s) | 54,771 |
def has_more_than_two_occurence(x):
"""creating a function for finding words with more than 2 occurences"""
if(x[1]>1):
return(x) | 54,772 |
def compute_gas_flux(gas_coords, star_data, times, params, bins, fig_name,
plot_flag=True):
"""Calculate the flux contribution from each point particle.
Assumptions: light travel time from stars to gas plus the
recombination time is shorter than the time it takes the
stars to move ... | 54,773 |
def evaluate(predictions, answerss):
"""
Returns a tuple of (F1 score, EM score, sentence score)
The sentence score is our evaluation method for determining the
effectiveness of finding the correct sentence within the context
paragraph that may contain the answer. This metric is much softer
than the F1 or... | 54,774 |
def test_rfftnd_autocorrelate2d():
"""Test rfft2d autocorrelate function."""
shape = 256, 128
test = numpy.random.rand(*shape)
result = numpy.empty_like(test)
# default scaling and shift
mode = 0
a = test.copy()
with rfftnd(shape, mode=mode) as fft:
fft.autocorrelate(a, result)
... | 54,775 |
def test_fee_schedule_find_by_none_corp_type_and_filing_type(session):
"""Assert a valid fee schedule is stored correctly.
Start with a blank database.
"""
now = date.today()
fee_code = factory_feecode('EN000X', 100)
corp_type = factory_corp_type('XX', 'Cooperative')
filing_type = factory_f... | 54,776 |
def style(
text: Any,
*,
fg: Union[str, fg] = '',
bg: Union[str, bg] = '',
bold: bool = False,
dim: bool = False,
underline: bool = False
) -> str:
"""
Apply ANSI colors and/or styles to a string and return it.
The styling is self contained which means that at the end of the stri... | 54,777 |
def get_shape_tags(tags, font_info=(cv2.FONT_HERSHEY_COMPLEX_SMALL, 0.75, (255,255,255), 1)):
"""Get information about how much the list of tags will occupy (width and height)
with the current configuration.
Arguments:
tags -- list of strings/tags you want to check shape.
Keyword arguments:
fo... | 54,778 |
def Intersection(S1x, S1y, D1x, D1y, S2x, S2y, D2x, D2y):
"""
Find intersection of 2 line segments
:param S1x: x coordinate of segment 1's start point
:param S1y: y coordinate of segment 1's start point
:param D1x: x coordinate of segment 1's end point
:param D1y: y coordinate of segment 1's end... | 54,779 |
def change_log_types(apps, schema_editor):
"""Change the log type for some of the logs"""
Old_Log = apps.get_model('ontask', 'Log')
for log_item in Old_Log.objects.all():
if log_item.name == 'action_run_list':
log_item.name = models.Log.ACTION_RUN_JSON_LIST
log_item.save()
... | 54,780 |
def optimization_writer():
""" Writes an input file for a geometry optimization.
"""
return opt_string | 54,781 |
def _offset(ax, x, y):
"""Provide offset in pixels
Parameters
----------
x : int
Offset in pixels for x
y : int
Offset in pixels for y
Idea borrowed from
http://www.scipy.org/Cookbook/Matplotlib/Transformations
but then heavily extended to be compatible with many
reinc... | 54,782 |
def augment(input_img, input_angle):
"""
Increase the training data set.
"""
output_images, output_angles = [],[]
"""
Fun fact: I had this condition around the data flipping code
but these function calls somehow SIGNIFICANTLY slowed down
the training process!!!
if ((abs(in... | 54,783 |
def insert_cdp_datapoints(client, name, datapoints, limit=10000):
"""Store datapoints in CDP, 'limit' amount in each call."""
if len(datapoints) > limit:
insert_cdp_datapoints(client, name, datapoints[limit:])
objs = [Datapoint(timestamp=ts, value=value) for ts, value in datapoints[:limit]]
logg... | 54,784 |
def check_host(hwaddr, ipaddr, config, args, timestr):
"""
check host infos against the config
returns changes, updated_config
"""
changes = []
# get hostname
hostname = get_hostname(ipaddr)
if hwaddr in config:
# shortcut
c = config[hwaddr]
# check statu... | 54,785 |
def Update(dEntities):
"""This will initiate all of the different updates that need done for
the Chunk Manager Entity."""
Update_Load_List({"LoadList":dEntities["ChunkMan"].get_component("LIST:LoadList"), \
"ChunkDataDir":dEntities["ChunkMan"].get_component("MISC:C... | 54,786 |
def getIdForTable(table):
"""resolve a table name to an ID"""
with sqlite3.connect(DB_PATH) as conn:
db = conn.cursor()
db.execute('SELECT table_id FROM tables WHERE table_name=?', [table])
return db.fetchone()[0] | 54,787 |
def blasi(wood, gas, tar, char, T, dt, s=1):
"""
Primary and secondary kinetic reactions from Table 1 in Blasi 1993 paper.
Note that primary reaction parameters in table are not cited correctly from
the Thurner and Mann 1981 paper, this function uses the correct parameters.
Parameters
---------... | 54,788 |
def run(num, roi_class_name, trials_name):
""" For subject <num>, run all models for all ROIs.
Note: Must be run from the parent folder of all the fMRI datasets."""
sdir = subdir(num)
roi_class_path = roi_class_name.split('.')
txt_classes = ['CatMean', 'Nobox', 'CatMeanFir', 'Subtime']
if roi_... | 54,789 |
def davis_southern_women_graph() -> nx.Graph:
"""Returns Davis Southern women social network.
This is a bipartite graph.
References
----------
.. [1] A. Davis, Gardner, B. B., Gardner, M. R., 1941. Deep South.
University of Chicago Press, Chicago, IL.
"""
G = nx.Graph()
# Top n... | 54,790 |
def is_extension_enabled(extension_name, service):
"""A function that will check the list of enabled extensions from config
"""
config_dict = {
'compute': CONF.compute_feature_enabled.api_extensions,
'volume': CONF.volume_feature_enabled.api_extensions,
'network': CONF.network_featu... | 54,791 |
def existing_droplets(token):
"""infos about existing Marian droplets."""
params = {
'tag_name': 'marian'
}
url = 'https://api.digitalocean.com/v2/droplets'
request = requests.get(url, headers=headers(token), params=params)
return request.json()['droplets'] | 54,792 |
def cross_lists(*sets):
"""Return the cross product of the arguments"""
wheels = [iter(_) for _ in sets]
digits = [next(it) for it in wheels]
while True:
yield digits[:]
for i in range(len(digits)-1, -1, -1):
try:
digits[i] = next(wheels[i])
br... | 54,793 |
def overlayLabel(dataSource, labelSource, sink = None, alpha = False, labelColorMap = 'jet', x = all, y = all, z = all):
"""Overlay a gray scale image with colored labeled image
Arguments:
dataSouce (str or array): volumetric image data
labelSource (str or array): labeled image to be overl... | 54,794 |
def constrain_sum(a, b, result):
"""Constrain a + b == result. Note that overflows are forbidden,
even if the result is never used."""
# This is a ripple-carry adder.
c = False # carry bit
# Optimization: stop at the the necessary number of bits.
max_bit = max([i+1 for i in BITS if a.bits[i].i... | 54,795 |
def min_pos_root(a, b, c):
"""Returns the minimum positive root for the function ax²+bx+c = 0. If no positive roots exist, returns None"""
roots = all_pos_roots(a, b, c)
if not roots or len(roots) == 0:
return None
return roots[0] | 54,796 |
def status(repo, samplesize=3):
"""Prints out some basic status information about this repository."""
print = builtins.print
if not hasattr(repo, 'get_status'):
return
print("Status for document repository '%s' (%s)" %
(repo.alias, getattr(repo.config, 'class')))
s = repo.get_statu... | 54,797 |
def patch_module(module):
"""
Extends all iterables in the module
with ``asq.queryables.Queryable`` methods.
Applies the same as ``patch_type`` to every appropriate member of
the module.
Args:
module: Module object or its __dict__.
Returns:
A list of patched classes.
"... | 54,798 |
def export_csv(districts, scores):
"""Exports result to a csv file.
"""
headers = ['district_id', 'district_name', 'score'] # Column names.
# Un-does our "hack": removes the "None" key from scores.
scores.pop(None, None)
# scores is a dict of score objects, identified by district name.
... | 54,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.