content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def new(request, pk=""):
""" New CodeStand Entry
When user presses 'Associate new project' there is a Project Container
associated, then you need reuse this information in the form
:param request: HttpResponse
:param pk: int - Indicates which project must be loaded
"""
if re... | 5,347,100 |
def sideral(
date, longitude=0.0, model="mean", eop_correction=True, terms=106
): # pragma: no cover
"""Sideral time as a rotation matrix
"""
theta = _sideral(date, longitude, model, eop_correction, terms)
return rot3(np.deg2rad(-theta)) | 5,347,101 |
def _make_mount_handler_command(
handler_name: str, handler: Type[ForeignDataWrapperDataSource]
) -> Command:
"""Turn the mount handler function into a Click subcommand
with help text and kwarg/connection string passing"""
help_text, handler_options_help = _generate_handler_help(handler)
params = ... | 5,347,102 |
def test_load_settings_onto_instrument(tmp_test_data_dir):
"""
Test that we can successfully load the settings of a dummy instrument
"""
# Always set datadir before instruments
set_datadir(tmp_test_data_dir)
def get_func():
return 20
tuid = "20210319-094728-327-69b211"
instr =... | 5,347,103 |
def dashboard_3_update_graphs(n_intervals):
"""Update all the graphs."""
figures = load_data_make_graphs()
main_page_layout = html.Div(children=[
html.Div(className='row', children=[
make_sub_plot(figures, LAYOUT_COLUMNS[0]),
make_sub_plot(figures, LAYOUT_COLUMNS[1]),... | 5,347,104 |
def connect_base_layer(graph, membership2node_translator):
"""
Currently builds full list of permutations, may switch to generator
Use 4 loop through combinations to do a memory friendly use of the generator w/ add edges - for larger graphs
"""
# Fully connect lowest layer
for nodes in memb... | 5,347,105 |
def fx(sl, dataset, roi_ids, results):
"""this requires the searchlight conditional attribute 'roi_feature_ids'
to be enabled"""
import numpy as np
from mvpa2.datasets import Dataset
resmap = None
probmap = None
for resblock in results:
for res in resblock:
if resmap is... | 5,347,106 |
def check_file(file_name):
"""
test if file: exists and is writable or can be created
Args:
file_name (str): the file name
Returns:
(pathlib.Path): the path or None if problems
"""
if not file_name:
return None
path = pathlib.Path(file_name)
# if... | 5,347,107 |
def insert_article(cur, article_id, article):
"""Inserts article into articles table."""
sql = 'INSERT IGNORE INTO articles VALUES(%s,%s,%s,%s,%s,%s,%s,%s)'
title = truncate_value(article['title'], CONSTANTS.max_title_length)
journal = truncate_value(article['journal'], CONSTANTS.max_journal_length)
... | 5,347,108 |
async def push(request):
"""Push handler. Authenticate, then return generator."""
if request.method != "POST":
return 405, {}, "Invalid request"
fingerprint = authenticate(request)
if not fingerprint:
return 403, {}, "Access denied"
# Get given file
payload = await request.get_... | 5,347,109 |
def getfile(url, outdir=None):
"""Function to fetch files using urllib
Works with ftp
"""
fn = os.path.split(url)[-1]
if outdir is not None:
fn = os.path.join(outdir, fn)
if not os.path.exists(fn):
#Find appropriate urlretrieve for Python 2 and 3
try:
from u... | 5,347,110 |
def duplicatesby(iteratee, seq, *seqs):
"""
Like :func:`duplicates` except that an `iteratee` is used to modify each element in the
sequences. The modified values are then used for comparison.
Examples:
>>> list(duplicatesby('a', [{'a':1}, {'a':3}, {'a':2}, {'a':3}, {'a':1}]))
[{'a': 3}... | 5,347,111 |
def isroutine(object):
"""Return true if the object is any kind of function or method."""
return (isbuiltin(object)
or isfunction(object)
or ismethod(object)
or ismethoddescriptor(object)) | 5,347,112 |
def account_upload_avatar():
"""Admin Account Upload Avatar Action.
*for Ajax only.
Methods:
POST
Args:
files: [name: 'userfile']
Returns:
status: {success: true/false}
"""
if request.method == 'POST':
re_helper = ReHelper()
data = request.files['u... | 5,347,113 |
def get_front_end_url_expression(model_name, pk_expression, url_suffix=''):
"""
Gets an SQL expression that returns a front-end URL for an object.
:param model_name: key in settings.DATAHUB_FRONTEND_URL_PREFIXES
:param pk_expression: expression that resolves to the pk for the model
:param ur... | 5,347,114 |
def mock_config_entry() -> MockConfigEntry:
"""Return the default mocked config entry."""
return MockConfigEntry(
title="KNX",
domain=KNX_DOMAIN,
data={
CONF_KNX_INDIVIDUAL_ADDRESS: XKNX.DEFAULT_ADDRESS,
ConnectionSchema.CONF_KNX_MCAST_GRP: DEFAULT_MCAST_GRP,
... | 5,347,115 |
def load_escores(name_dataset, classifier, folds):
"""Excluir xxxxxxx Return escore in fold. """
escores=[]
escores.append(load_dict_file("escores/"+name_dataset +"_"+classifier +"_escore_grid_train"+str(folds)))
return escores
for index in range(folds):
escores.append(load_dict_file("escore... | 5,347,116 |
def get_devices():
""" will also get devices ready
:return: a list of avaiable devices names, e.g., emulator-5556
"""
ret = []
p = sub.Popen(settings.ADB + ' devices', stdout=sub.PIPE, stderr=sub.PIPE, shell=True)
output, errors = p.communicate()
print output
segs = output.split("\n")
for seg in segs:
device... | 5,347,117 |
def _proc_event_full(st, **kwargs):
"""
processings including
:param st:
:param kwargs:
:return:
"""
# instrument response removal, spectral whitening, temporal normalization
# autocorrelation and filter, then output results.
def iter3c(stream):
# for an event, there is alwa... | 5,347,118 |
def optional_is_none(context, builder, sig, args):
"""Check if an Optional value is invalid
"""
[lty, rty] = sig.args
[lval, rval] = args
# Make sure None is on the right
if lty == types.none:
lty, rty = rty, lty
lval, rval = rval, lval
opt_type = lty
opt_val = lval
... | 5,347,119 |
def get_volume_disk_capacity(pod_name, namespace, volume_name):
"""
Find the container in the specified pod that has a volume named
`volume_name` and run df -h or du -sb in that container to determine
the available space in the volume.
"""
api = get_api("v1", "Pod")
res = api.get(name=pod_na... | 5,347,120 |
def is_valid_battlefy_id(battlefy_id: str) -> bool:
"""
Verify a str is a Battlefy Id (20 <= length < 30) and is alphanumeric.
:param battlefy_id:
:return: Validity true/false
"""
return 20 <= len(battlefy_id) < 30 and re.match("^[A-Fa-f0-9]*$", battlefy_id) | 5,347,121 |
def update_embedded_documents_using_multiple_field_matches():
"""当query有关多个field时, 使用$elemMatch
"""
_id = 5
col.insert({
"_id": _id,
"grades": [
{"grade": 80, "mean": 75, "std": 8},
{"grade": 85, "mean": 90, "std": 5},
{"grade": 90, "mean": 85, "std": ... | 5,347,122 |
def echo(word:str, n:int, toupper:bool=False) -> str:
"""
Repeat a given word some number of times.
:param word: word to repeat
:type word: str
:param n: number of repeats
:type n: int
:param toupper: return in all caps?
:type toupper: bool
:return: result
:return type: str
... | 5,347,123 |
def verify_package_info(package_info):
"""Check if package_info points to a valid package dir (i.e. contains
at least an osg/ dir or an upstream/ dir).
"""
url = package_info['canon_url']
rev = package_info['revision']
command = ["svn", "ls", url, "-r", rev]
out, err = utils.sbacktick(comma... | 5,347,124 |
def test_custom_taper():
"""Test setting custom taper."""
test_win = windows.blackman
dspec = DelaySpectrum(taper=test_win)
assert test_win == dspec.taper | 5,347,125 |
def add(a,b):
""" This function adds two numbers together """
return a+b | 5,347,126 |
def decode_ADCP(data):
"""
Decodes ADCP data read in over UDP. Returns two lists: header and current.
input: Raw data string from ADCP UDP stream
Output:
header: [timestamp, nCells, nBeams, pressure]
- timestamp in unix format
- nBeams x nCells gives dimensions of current data
... | 5,347,127 |
def RowToModelInput(row, kind):
"""
This converts a patient row into inputs for the SVR.
In this model we use RNAseq values as inputs.
"""
SampleID = row[TissueSampleRow(kind)]
TrueSampleIDs = [r for r in TissueSamples.columns
if r.startswith(SampleID)]
if not TrueSa... | 5,347,128 |
def foldlM(f, b, ta):
"""``foldrM :: (Foldable t, Monad m) => (a -> b -> m b) -> b -> t a -> m b``
Monadic fold over the elements of a structure, associating to the right,
i.e. from right to left.
"""
raise NotImplementedError() | 5,347,129 |
def update_video(secret, site_id, media_id, body):
"""
Function which allows you to update a video
:param secret: <string> Secret value for your JWPlatform API key
:param site_id: <string> ID of a JWPlatform site
:param media_id: <string> Video's object ID. Can be found within JWPlayer Dashboard.
... | 5,347,130 |
def test_should_setup_method_returns_true_if_container_does_not_exist(mock_docker, setup_course_environ):
"""
Does the should_setup method return True when the container not was found?
"""
course = Course(org='org1', course_id='example', domain='example.com')
def _container_not_exists(name):
... | 5,347,131 |
def str_to_timedelta(td_str):
"""Parses a human-readable time delta string to a timedelta"""
if "d" in td_str:
day_str, time_str = td_str.split("d", 1)
d = int(day_str.strip())
else:
time_str = td_str
d = 0
time_str = time_str.strip()
if not time_str:
return d... | 5,347,132 |
def check_deletion_key_pair(key_filter: List[Dict], aws_region: str) -> None:
"""Verify Deletion of a key pair by filter."""
ec2_resource = boto3.resource("ec2", region_name=aws_region)
key_pairs_list = ec2_resource.key_pairs.filter(**key_filter)
assert not list(key_pairs_list) | 5,347,133 |
def filter_safe_enter(s):
"""正文 换行替换"""
return '<p>' + cgi.escape(s).replace("\n", "</p><p>") + '</p>' | 5,347,134 |
def fig2png(filename, title, rat, begin, end):
"""
Args:
filename:
title:
rat:
begin:
end:
"""
raise NotImplemented
matfile = loadmat(filename, squeeze_me=True, struct_as_record=False)
print(matfile)
data = np.array(matfile['LMG_muscle']).T
for i, k in enumerate(data):
plt.plot(np.arange(len(k)) * ... | 5,347,135 |
def _full_rank(X, cmax=1e15):
"""
This function possibly adds a scalar matrix to X
to guarantee that the condition number is smaller than a given threshold.
Parameters
----------
X: array of shape(nrows, ncols)
cmax=1.e-15, float tolerance for condition number
Returns
-------
X... | 5,347,136 |
def create(
session: Session,
instance: Instance,
name: str,
description: Optional[str] = None,
external_id: Optional[str] = None,
unified_dataset_name: Optional[str] = None,
) -> Project:
"""Create a Mastering project in Tamr.
Args:
instance: Tamr instance
name: Project... | 5,347,137 |
def main(argv):
"""
Solr Core loader
:param list argv: the list elements should be:
[1]: source IMPC parquet file
[2]: Output Path
"""
stats_results_parquet_path = argv[1]
ontology_parquet_path = argv[2]
output_path = argv[3]
spark = SparkSession.... | 5,347,138 |
def users_with_pending_lab(connection, **kwargs):
"""Define comma seperated emails in scope
if you want to work on a subset of all the results"""
check = CheckResult(connection, 'users_with_pending_lab')
# add random wait
wait = round(random.uniform(0.1, random_wait), 1)
time.sleep(wait)
che... | 5,347,139 |
def test_check_family_naming_recommendations():
""" Font follows the family naming recommendations ? """
from fontbakery.profiles.name import com_google_fonts_check_family_naming_recommendations as check
# Our reference Mada Medium is known to be good
ttFont = TTFont(TEST_FILE("mada/Mada-Medium.ttf"))
... | 5,347,140 |
def hpat_pandas_series_lt(self, other, level=None, fill_value=None, axis=0):
"""
Pandas Series method :meth:`pandas.Series.lt` implementation.
.. only:: developer
Test: python -m sdc.runtests sdc.tests.test_series.TestSeries.test_series_op8
Parameters
----------
self: :class:`pandas.Serie... | 5,347,141 |
def convert_kv(
key: str,
val: str | numbers.Number,
attr_type: bool,
attr: dict[str, Any] = {},
cdata: bool = False,
) -> str:
"""Converts a number or string into an XML element"""
if DEBUGMODE: # pragma: no cover
LOG.info(
f'Inside convert_kv(): key="{str(key)}", val="... | 5,347,142 |
def getBanner(host, port):
"""
Connects to host:port and returns the banner.
"""
try:
s = socket.socket()
s.connect((host, port))
banner = s.recv(1024)
return str(banner).strip()
except Exception, e:
error(str(host) + ':' + str(port) + ' ' + str(e)) | 5,347,143 |
def create_cmd_table(table_data: List[List[str]], width: int = 15) -> BorderedTable:
"""Create a bordered table for cmd2 output.
Args:
table_data: list of lists with the string data to display
width: integer width of the columns. Default is 15 which generally works for ~4 columns
Returns:
... | 5,347,144 |
def main():
"""Apply different types of convolutions to an image.
"""
# construct the argument parse and parse the arguments
args = argparse.ArgumentParser()
args.add_argument("-i", "--image", required=True, help="path to the input image")
args = vars(args.parse_args())
# construct average ... | 5,347,145 |
def gen_log_files():
"""Generate log files"""
for root, _, files in os.walk(DEFAULT_LOG_DIR):
for name in files:
if is_pref_file(name):
yield os.path.join(root, name) | 5,347,146 |
def get_parser(dataset_name):
"""Returns a csv line parser function for the given dataset."""
def inat_parser(line, is_train=True):
if is_train:
user_id, image_id, class_id, _ = line
return user_id, image_id, class_id
else:
image_id, class_id, _ = line
return image_id, class_id
d... | 5,347,147 |
def read_all_bdds(project_path):
"""
Read all feature files from project
:param project_path: base path of the project
:return: Array of Feature objects
"""
features = []
for root, _, files in os.walk(project_path + '/features/'):
for file in files:
if file.endswith(".fea... | 5,347,148 |
def one_sentence_to_ids(sentence, sentence_length=SENTENCE_LENGTH):
"""Convert one sentence to a list of word IDs."
Crop or pad to 0 the sentences to ensure equal length if necessary.
Words without ID are assigned ID 1.
>>> one_sentence_to_ids(['my','first','sentence'], 2)
([11095, 121], 2)
>>> one_sentence_to_ids... | 5,347,149 |
def main() -> NoReturn:
"""
Command-line processor. See ``--help`` for details.
"""
logging.basicConfig()
log.setLevel(logging.DEBUG)
parser = argparse.ArgumentParser(
description="Send an e-mail from the command line.")
parser.add_argument("sender", action="store",
... | 5,347,150 |
def full_class_name(class_):
"""
Returns the absolute name of a class, with all nesting namespaces included
"""
return '::'.join(get_scope(class_) + [class_.name]) | 5,347,151 |
def mul_pdf(mean1, var1, mean2, var2):
"""
Multiply Gaussian (mean1, var1) with (mean2, var2) and return the
results as a tuple (mean, var, scale_factor).
Strictly speaking the product of two Gaussian PDFs is a Gaussian
function, not Gaussian PDF. It is, however, proportional to a Gaussian
PDF.... | 5,347,152 |
def mean_squared_error(y_true, y_pred):
"""
Mean squared error loss.
:param y_true: groundtruth.
:param y_pred: prediction.
:return: loss symbolic value.
"""
P = norm_saliency(y_pred) # Normalized to sum = 1
Q = norm_saliency(y_true) # Normalized to sum = 1
return K.mean(K.square(P... | 5,347,153 |
def format_epilog():
"""Program entry point.
:param argv: command-line arguments
:type argv: :class:`list`
"""
author_strings = []
for name, email in zip(metadata.authors, metadata.emails):
author_strings.append('Author: {0} <{1}>'.format(name, email))
epilog = '''
{project} {versio... | 5,347,154 |
def _get_process_environment(process, proxy):
"""Get env to be used by the script process.
This env must at the very least contain the proxy url, and a PATH
allowing bash scripts to use `ctx`, which is expected to live next to
the current executable.
"""
env = os.environ.copy()
env.setdefau... | 5,347,155 |
def text_differences(original_text: List[str], new_text_version: List[str]) -> TextDifferences:
"""
Builds text differences from input texts.
Parameters
----------
original_text: List[str]
original text (as a list of lines)
new_text_version: List[str]
new text version (as a list... | 5,347,156 |
def find_install_requires():
"""Return a list of dependencies and non-pypi dependency links.
A supported version of tensorflow and/or tensorflow-gpu is required. If not
found, then tensorflow is added to the install_requires list.
Depending on the version of tensorflow found or installed, either
k... | 5,347,157 |
def test_get_valid_coupon_versions_over_redeemed(basket_and_coupons, order_status):
"""
Verify that CouponPaymentVersions that have exceeded redemption limits are not returned
"""
with unprotect_version_tables():
civ_worst = basket_and_coupons.coupongroup_worst.coupon_version.payment_version
... | 5,347,158 |
def plot_rms(data, POL='xx'):
"""Plots rms values at input to ADC's by looking at the autos.
Args:
data (dict): Dictionary of auto's.
POL (str): String of polarization."""
fig = plt.figure(figsize=(20, 12))
CHUNK = 256
BINS = 24
rmscolors = 'bgrcmy'
ants = sorted([i for (i, ... | 5,347,159 |
def remote_fixture():
"""Patch the samsungctl Remote."""
with patch(
"homeassistant.components.samsungtv.bridge.Remote"
) as remote_class, patch(
"homeassistant.components.samsungtv.config_flow.socket"
) as socket_class:
remote = mock.Mock()
remote.__enter__ = mock.Mock()... | 5,347,160 |
async def delete_port(request : VueRequest):
"""
删除端口的接口
:param:
:return: str response: 需要返回的数据
"""
try:
response = {'code': '', 'message': '', 'data': ''}
request = rsa_crypto.decrypt(request.data)
request = json.loads(request)
target = request['target']
... | 5,347,161 |
def get_start_indices_labesl(waveform_length, start_times, end_times):
"""
Returns: a waveform_length size boolean array where the ith entry says wheter or not a frame starting from the ith
sample is covered by an event
"""
label = np.zeros(waveform_length)
for start, end in zip(start_times, end... | 5,347,162 |
def get_function_euler_and_module():
"""
Function return tuple with value function euler and module.
This tuple is namedtuple and we can use it this way:
euler = tuple.euler
module = tuple.module
Thanks to this, we will not be mistaken.
"""
first_number_prime, second_number_prime... | 5,347,163 |
def _read_host_df(host, seq=True):
"""Reads the metrics data for the host and returns a DataFrame.
Args:
host (str): Hostname, one of wally113, wally117, wally122, wally123,
wally124
seq (bool): If sequential or concurrent metrics should be read
Returns:
DataFrame: Containing all t... | 5,347,164 |
def compacify(train_seq, test_seq, dev_seq, theano=False):
"""
Create a map for indices that is be compact (do not have unused indices)
"""
# REDO DICTS
new_x_dict = LabelDictionary()
new_y_dict = LabelDictionary(['noun'])
for corpus_seq in [train_seq, test_seq, dev_seq]:
for seq in... | 5,347,165 |
def obfuscate_email(email):
"""Takes an email address and returns an obfuscated version of it.
For example: test@example.com would turn into t**t@e*********m
"""
if email is None:
return None
splitmail = email.split("@")
# If the prefix is 1 character, then we can't obfuscate it
if l... | 5,347,166 |
def list_small_kernels():
"""Return list of small kernels to generate."""
kernels1d = [
NS(length= 1, threads_per_block= 64, threads_per_transform= 1, factors=(1,)),
NS(length= 2, threads_per_block= 64, threads_per_transform= 1, factors=(2,)),
NS(length= 3, threads_per_block= 64... | 5,347,167 |
def init_weights_kaiming_uniform(m):
""" Weight initialization for linear layers """
if type(m) == nn.Linear:
nn.init.kaiming_uniform(m.weight)
m.bias.data.fill_(0.01) | 5,347,168 |
def parse_boolean(arg: str):
"""Returns boolean representation of argument."""
arg = str(arg).lower()
if 'true'.startswith(arg):
return True
return False | 5,347,169 |
def test_multiple_repos_bad_default() -> None:
"""Check error for prepare_repository_configurations with a missing default_repo."""
from valiant.config import Config
from valiant.repositories import RepositoryConfiguration
with pytest.raises(ValueError):
Config.prepare_repository_configurations... | 5,347,170 |
def test_amb_file():
"""
The amb file records the appearance of non-ATGC characters (e.g. N)
"""
amb_file = expanduser("~/.genome/F1L3/") + "F1L3.fa.gz.amb"
with open(amb_file, "r") as f:
assert '5252759 94 1 575 10 N' == ' '.join(f.read().splitlines()) | 5,347,171 |
async def log_rtsp_urls(device: VivintCamera):
"""Logs the rtsp urls of a Vivint camera."""
_LOGGER.info(
"%s rtsp urls:\n direct hd: %s\n direct sd: %s\n internal hd: %s\n internal sd: %s\n external hd: %s\n external sd: %s",
device.name,
await device.get_direct_rtsp_url(hd=True),... | 5,347,172 |
def ascending_coin(coin):
"""Returns the next ascending coin in order.
>>> ascending_coin(1)
5
>>> ascending_coin(5)
10
>>> ascending_coin(10)
25
>>> ascending_coin(2) # Other values return None
"""
if coin == 1:
return 5
elif coin == 5:
return 10
elif coi... | 5,347,173 |
def start_game() -> None:
"""Start the game by asking
the number of people and setting their attributes."""
number_of_people: int = ask_number_of_people()
ask_and_set_player_attributes(number_of_people) | 5,347,174 |
def to_numpy(qg8_tensor):
"""
Convert qg8_tensor to dense numpy array
"""
dtype = dtype_to_name(qg8_tensor.dtype_id)
ndarray = np.zeros(qg8_tensor.dims, dtype=dtype)
if np.iscomplexobj(ndarray):
ndarray[tuple(qg8_tensor.indices)] = np.asfortranarray(qg8_tensor.re)\
... | 5,347,175 |
def _get_results(report):
"""Limit the number of documents to REPORT_MAX_DOCUMENTS so as not to crash the server."""
query = _build_query(report)
try:
session.execute(f"SET statement_timeout TO {int(REPORT_COUNT_TIMEOUT * 1000)}; commit;")
if query.count() == 0:
return None
e... | 5,347,176 |
def mark(metric_name):
"""
Mark event in metrics collector.
"""
if settings.COLLECT_METRICS:
logger.info('New mark event: {}'.format(metric_name), extra={
'metric_name': metric_name
})
counter = Metrology.meter(metric_name)
counter.mark() | 5,347,177 |
def connect_input(source_node, source_attr_name, target_node, target_attr_name):
"""Basic connection from source to target ndoe
:param source_node:
:param source_attr_name:
:param target_node:
:param target_attr_name:
:return:
"""
inputs = source_node.attr(source_attr_name).inputs(p=1)
... | 5,347,178 |
def test_missing_node_name_raises(topology, validator):
"""
Verify topology schema is valid
"""
test_topology = topology["missing_node_name"]
with pytest.raises(jsonschema.exceptions.ValidationError) as e:
validator.validate(test_topology)
assert "'name' is a required property" in str(e.... | 5,347,179 |
def text_match_one_hot(df, column=None, text_phrases=None, new_col_name=None, return_df=False, case=False,
supress_warnings: bool=False):
"""Given a dataframe, text column to search and a list of text phrases, return a binary
column with 1s when text is present and 0 otherwise
"""
... | 5,347,180 |
def pack_feed_dict(name_prefixs, origin_datas, paddings, input_fields):
"""
Args:
name_prefixs: A prefix string of a list of strings.
origin_datas: Data list or a list of data lists.
paddings: A padding id or a list of padding ids.
input_fields: The input fieds dict.
Return... | 5,347,181 |
async def test_singleswitch_requests(zigpy_device_from_quirk, quirk):
"""Test tuya single switch."""
switch_dev = zigpy_device_from_quirk(quirk)
switch_cluster = switch_dev.endpoints[1].on_off
tuya_cluster = switch_dev.endpoints[1].tuya_manufacturer
with mock.patch.object(
tuya_cluster.en... | 5,347,182 |
def get_directory(**kwargs):
"""
Wrapper function for PyQt4.QtGui.QFileDialog.getExistingDirectory().
Returns the absolute directory of the chosen directory.
Parameters
----------
None
Returns
-------
filename : string of absolute directory.
"""
from PyQt4 import QtGui
... | 5,347,183 |
def single_particle_relative_pzbt_metafit(fitfn, exp_list, **kwargs):
"""Fit to single-particle energies plus zero body term, relative to the
first point
"""
return single_particle_metafit_int(
fitfn, exp_list,
dpath_sources=DPATH_FILES_INT, dpath_plots=DPATH_PLOTS,
transform=rel... | 5,347,184 |
def hetmat_from_permuted_graph(hetmat, permutation_id, permuted_graph):
"""
Assumes subdirectory structure and that permutations inherit nodes but not
edges.
"""
permuted_hetmat = initialize_permutation_directory(hetmat, permutation_id)
permuted_hetmat = hetmat_from_graph(
permuted_graph... | 5,347,185 |
def can_see_all_content(requesting_user: types.User, course_key: CourseKey) -> bool:
"""
Global staff, course staff, and instructors can see everything.
There's no need to run processors to restrict results for these users.
"""
return (
GlobalStaff().has_user(requesting_user) or
Cou... | 5,347,186 |
def part2(steps, workers=2, extra_time=0):
""" Time is in seconds """
workers = [Worker() for _ in range(workers)]
steps_to_time = {
step: alphabet.index(step) + 1 + extra_time
for step in alphabet
}
time = 0
graph = build_graph(steps)
chain = find_orphans(graph)
while... | 5,347,187 |
def test_class_weight_auto_classifies():
"""Test that class_weight="auto" improves f1-score"""
# This test is broken; its success depends on:
# * a rare fortuitous RNG seed for make_classification; and
# * the use of binary F1 over a seemingly arbitrary positive class for two
# datasets, and weig... | 5,347,188 |
def to_local_df(df: Any, schema: Any = None, metadata: Any = None) -> LocalDataFrame:
"""Convert a data structure to :class:`~fugue.dataframe.dataframe.LocalDataFrame`
:param df: :class:`~fugue.dataframe.dataframe.DataFrame`, pandas DataFramme and
list or iterable of arrays
:param schema: |SchemaLike... | 5,347,189 |
def create_local_meta(name):
"""
Create the metadata dictionary for this level of execution.
Parameters
----------
name : str
String to describe the current level of execution.
Returns
-------
dict
Dictionary containing the metadata.
"""
local_meta = {
'... | 5,347,190 |
def matches_uri_ref_syntax(s):
"""
This function returns true if the given string could be a URI reference,
as defined in RFC 3986, just based on the string's syntax.
A URI reference can be a URI or certain portions of one, including the
empty string, and it can have a fragment component.
"""
... | 5,347,191 |
def get_end_hour(dt=None):
"""根据日期、或时间取得该小时59:59的时间;参数可以是date或datetime类型"""
end = None
if not dt:
dt = datetime.date.today()
if isinstance(dt, datetime.date):
dt_str = dt.strftime("%Y-%m-%d %H") + ":59:59"
end = datetime.datetime.strptime(dt_str, "%Y-%m-%d %H:%M:%S")
return e... | 5,347,192 |
def all_ped_combos_strs(num_locs=4, val_set=("0", "1")):
"""Return a list of all pedestrian observation combinations (in string format) for a vehicle under the 4 location scheme"""
res = []
lsts = all_ped_combos_lsts(num_locs, val_set)
for lst in lsts:
res.append(" ".join(lst))
return res | 5,347,193 |
def create_image(
image_request: ImageRequest,
background_tasks: BackgroundTasks,
db: Session = Depends(get_db),
):
"""
(2) add database record
(3) give background_tasks a reference of image record
"""
image = Images()
image.url = image_request.image
# image.output = "4" # <<<... | 5,347,194 |
def test_list_policies_freebsd():
"""
Test if it return a dictionary of policies nested by vhost
and name based on the data returned from rabbitmqctl list_policies.
"""
mock_run = MagicMock(
return_value={"retcode": 0, "stdout": "saltstack", "stderr": ""}
)
mock_pkg = MagicMock(retur... | 5,347,195 |
def get_key(rule_tracker, value):
"""
Given an event index, its corresponding key from the dictionary is returned.
Parameters:
rule_tracker (dict): Key-value pairs specific to a rule where key is an activity, pair is an event index
value (int): Index of event in event log
Returns:
... | 5,347,196 |
def get_cxml(filename):
""" Create and return CXML object from File or LocalCache """
cxml = Cxml(filename)
return cxml | 5,347,197 |
def save_layer(index, settings) -> Action:
"""Action to save layer settings"""
return {"kind": SAVE_LAYER, "payload": {"index": index, "settings": settings}} | 5,347,198 |
def csvProcessing(args):
"""iterate through mudviz/plain dirs, collecting the associated usernames and cvs file paths"""
groupPath1 = args['dir']+'/mudviz'
groupPath2 = args['dir']+'/plain'
#avoid potential user-input trouble with extra forward slashes
if args['dir'][-1] == '/':
groupPath1 = args['dir'][:-1]+'... | 5,347,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.