content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def get_absolute_url(body_string: str):
"""Get absolute manga mangadex url"""
parser = BeautifulSoup(body_string, 'html.parser')
for link_elements in parser.find_all('link'):
# aiming for canonical link
try:
rel = link_elements.attrs['rel']
href = link_elements... | 5,319,700 |
def panel_grid(hspace, wspace, ncols, num_panels):
"""Init plot."""
n_panels_x = min(ncols, num_panels)
n_panels_y = np.ceil(num_panels / n_panels_x).astype(int)
if wspace is None:
# try to set a wspace that is not too large or too small given the
# current figure size
wspace =... | 5,319,701 |
def ma_rhythm(ppath, recordings, ma_thr=20.0, min_dur = 160, band=[10,15],
state=3, win=64, pplot=True, pflipx=True, pnorm=False):
"""
calculate powerspectrum of EEG spectrogram to identify oscillations in sleep activity within different frequency bands;
only contineous NREM periods are consid... | 5,319,702 |
async def find_file_ids(paths: Dict[str, int]) -> Dict[str, str]:
"""Parameter 1: dict of "file path" -> file size."""
fpaths = [p for p in paths.keys() if p]
if not fpaths:
return {}
query = "select path, size, file_id from file_ids where path in ({})".format(
','.join('?' * len(fpaths)... | 5,319,703 |
def test__collect_mors_and_attributes(vsphere, instance):
"""
Test that we check for errors when collecting properties with property collector
"""
server_instance = vsphere._get_server_instance(instance)
with mock.patch("datadog_checks.vsphere.vsphere.vmodl"):
obj = MagicMock(missingSet=None... | 5,319,704 |
def select_curve(message='Select one curve.'):
"""Select one curve in the Rhino view.
Parameters
----------
message : str, optional
Instruction for the user.
Returns
-------
System.Guid
The identifer of the selected curve.
"""
return rs.GetObject(message, preselect... | 5,319,705 |
def fetch_cert(url: str) -> Certificate:
"""
Fetch a certificate from a URL.
:param url: the URL to the certificate file
:return: a certificate object
"""
with fetch_file(url) as cert_file:
return ssl_serializer.deserialize_cert(cert_file.read()) | 5,319,706 |
def import_execute(request, extra_context={}):
"""
This is the view that actually processed the import based on the options
set by the user in import_options (above).
In addition to calling the appropriate import function (see below) this
view also prepares the status information dictionary that will be us... | 5,319,707 |
def get_default_view(source_type, source_name, menu_name=None,
source_transform=None, viewer_transform=None, **kwargs):
""" Create default view metadata for a single source.
Arguments:
source_type [str] - type of the source, either "image" or "segmentation"
source_name [str... | 5,319,708 |
def PullToBrepFace(curve, face, tolerance, multiple=False):
"""
Pull a curve to a BrepFace using closest point projection.
Args:
curve (Curve): Curve to pull.
face (BrepFace): Brep face that pulls.
tolerance (double): Tolerance to use for pulling.
Returns:
Curve[]: An a... | 5,319,709 |
def event_return(events):
"""
Write event data (return data and non-return data) to file on the master.
"""
if len(events) == 0:
# events is an empty list.
# Don't open the logfile in vain.
return
opts = _get_options({}) # Pass in empty ret, since this is a list of events
... | 5,319,710 |
def floatX(X):
""" Change data to theano type """
return np.asarray(X, dtype=theano.config.floatX) | 5,319,711 |
def primes_sieve3(n):
""" Sieve method 3: Returns a list of primes < n
>>> primes_sieve3(100)
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
"""
# begin half-sieve, n>>1 == n//2
sieve = [True] * (n>>1)
upper = int(n**0.5)+1
fo... | 5,319,712 |
def __detect_app_dir(name):
"""
如果app目录不存在,报错
:param name:
:return:
"""
app_dir = services.detect_app_dir(name)
if not os.path.exists(app_dir):
raise ServiceException("无法找到应用根目录")
return app_dir | 5,319,713 |
def main():
"""Program's Main running function."""
while True:
res = set_view(View.main_view, True)
if res == 1:
while True:
cat_id = set_view(View.cats_view)
if cat_id:
while True:
prod_id = set_view(lambda... | 5,319,714 |
def kl_mvg_diag(
pm: jnp.ndarray, pv: jnp.ndarray, qm: jnp.ndarray, qv: jnp.ndarray
) -> jnp.ndarray:
"""
Kullback-Leibler divergence from Gaussian pm,pv to Gaussian qm,qv.
Also computes KL divergence from a single Gaussian pm,pv to a set
of Gaussians qm,qv.
Diagonal covariances are assumed. Di... | 5,319,715 |
def isstring(var:Any, raise_error:bool=False) -> bool:
"""Check if var is a string
Args:
var (str): variable to check
raise_error (bool, optional): TypeError raised if set to `True`. Defaults to `False`.
Raises:
TypeError: raised if var is not string
Returns:
bool: `Tr... | 5,319,716 |
def run_simulation(solution, times, conditions=None,
condition_type = 'adiabatic-constant-volume',
output_species = True,
output_reactions = True,
output_directional_reactions = False,
output_rop_roc = False,
... | 5,319,717 |
def first_second_person_density(doc):
"""Compute density of first|second person.
:param doc: Processed text
:type doc: Spacy Doc
:return: Density 1,2 person
:rtype: float
"""
return first_second_person_count(doc) / word_count(doc) | 5,319,718 |
def create_map(*columns):
"""
Creates a new map column. The input columns must be grouped as key-value pairs, e.g.
(key1, value1, key2, value2, ...). The key columns must all have the same data type, and can't
be null. The value columns must all have the same data type.
"""
return _with_expr(exp... | 5,319,719 |
def for_review_request_field(context, nodelist, review_request_details,
fieldset):
"""Loops through all fields in a fieldset.
This can take a fieldset instance or a fieldset ID.
"""
s = []
request = context.get('request')
if isinstance(fieldset, six.text_type):
... | 5,319,720 |
def bayesian_optimization(f, gpr, acq_func, bounds, max_iter = None,
prop_kwargs = None, minimize = None,
verbose = False, noise=0.0):
"""
Implement Bayesian optimization to maximize or minimize a scalar function.
Arguments
---------
f : calla... | 5,319,721 |
def test_weather_type_programmatic(
weather_type: str,
max_err: float,
weather_env: HolodeckEnvironment,
request: FixtureRequest,
) -> None:
"""Validate that weather type can be set programmatically by comparing
RGB sensor data with saved baseline data
Args:
weather_type: Type of we... | 5,319,722 |
def to_nearest(num, tick_size):
"""
Given a number, round it to the nearest tick. Very useful for sussing float error
out of numbers: e.g. toNearest(401.46, 0.01) -> 401.46, whereas processing is
normally with floats would give you 401.46000000000004.
Use this after adding/subtracting/multiplying nu... | 5,319,723 |
def u3_propagator ( t ):
"""U3 and U3' combined: thermostat propagator.
t is the time over which to propagate (typically dt/2).
v, eta, p_eta, and q are accessed from the calling program.
"""
global v, eta, eta_baro, p_eps
import numpy as np
# U3 part
v = v * np.exp ( -t * p_eta[... | 5,319,724 |
def create_epub(raw_articles: List[Article], title: str) -> str:
"""
Create an EPUB book from multiple articles.
:returns temp path to created ebook
"""
epub_path = mkdtemp()
logger.debug(f"Creating epub folder in {epub_path}")
articles = [EPUBArticle(raw_article, epub_path) for raw_articl... | 5,319,725 |
def placeholder(value, token):
""" Add placeholder attribute, esp. for form inputs and textareas """
value.field.widget.attrs["placeholder"] = token
return value | 5,319,726 |
def create_xml_element(connection, token, name):
"""A helper function creating an etree.Element with the necessary
attributes
:param name: The name of the element
:returns: etree.Element
"""
return etree.Element(
name,
nsmap={None: XHTML_NAMESPACE},
shop_id=connection.s... | 5,319,727 |
def generate_categorical_dataframe(
sm: nx.DiGraph,
n_samples: int,
distribution: str = "logit",
n_categories: int = 3,
noise_scale: float = 1.0,
intercept: bool = False,
seed: int = None,
kernel: Optional[Kernel] = None,
) -> pd.DataFrame:
"""
Generates a dataframe with samples ... | 5,319,728 |
def bias_cross_func(data, *args, **kwargs):
"""
生成一条年利率 4% 的模拟货币基金基准线
支持QA add_func,第二个参数 默认为 indices= 为已经计算指标
理论上这个函数只计算单一标的,不要尝试传递复杂标的,indices会尝试拆分。
"""
if (ST.VERBOSE in data.columns):
print('Phase bias_cross_func', QA_util_timestamp_to_str())
# 针对多标的,拆分 indices 数据再自动合并
code ... | 5,319,729 |
def login(uid: str, pwd: str) -> Optional[Admin]:
"""
登录
:return:
"""
sql = '''SELECT admins.id, admins.uid, admins.is_super FROM admins WHERE uid=%s AND pwd=%s LIMIT 1'''
connect = get_connect()
with connect.cursor() as cursor:
cursor.execute(sql, (uid, pwd))
row = cursor.f... | 5,319,730 |
async def catch_uniqueness_error(
request: aiohttp.web.Request, handler: swift_browser_ui.common.types.AiohttpHandler
) -> aiohttp.web.Response:
"""Catch excepetion arising from a non-unique primary key."""
try:
return await handler(request)
except asyncpg.exceptions.UniqueViolationError:
... | 5,319,731 |
def customization_data(client=None):
"""Produce any customization definitions (types, fields, message destinations, etc)
that should be installed by `resilient-circuits customize`
"""
# This import data contains:
# Function inputs:
# cisco_alerttime
# cisco_deviceid
# c... | 5,319,732 |
def df_canonicalize_from_smiles(df, smiles_col: str, include_stereocenters=True)->pd.Series:
"""
Canonicalize the SMILES strings with RDKit.
Args:
df: dataframe
smiles_col: column name in df
include_stereocenters: whether to keep the stereochemical information in the canonical SMILES... | 5,319,733 |
def mse_loss(y, pred, w):
""" Regression loss function, mean squared error. """
return T.mean(w * (y - pred) ** 2) | 5,319,734 |
def compute_gradients(
state,
supermatrices,
supergradients,
super_oplabels,
observables,
observables_labels,
num_discretes,
):
"""
Compute the gradients of a symplectic acyclic_graph for the cost function
<psi|sum_n H_n |psi>, with H_n the element at `observables[n]`, acting on
... | 5,319,735 |
def running_from_pacman():
""" Return True if the parent process is pacman """
debug = InformantConfig().get_argv_debug()
ppid = os.getppid()
p_name = subprocess.check_output(['ps', '-p', str(ppid), '-o', 'comm='])
p_name = p_name.decode().rstrip()
if debug:
debug_print('informant: runni... | 5,319,736 |
def test_find_resource(root, path, keys):
"""Resolving paths yields the expected resource."""
resource = functools.reduce(operator.getitem, keys, root)
assert traversal.find_resource(root, path) == resource | 5,319,737 |
def _cs_count_top_bottom(fragments):
"""Counting: top and bottom of the entire core sample"""
cs_top, cs_bottom = 1e10, 0
for fragment in fragments:
cs_top = min(cs_top, float(fragment['top']))
cs_bottom = max(cs_bottom, float(fragment['bottom']))
return cs_top, cs_bottom | 5,319,738 |
def awaken(app, databaseurl):
"""Restore the database from a given url."""
id = app
config = get_config()
config.load()
bucket = data.user_s3_bucket()
key = bucket.lookup('{}.dump'.format(id))
url = key.generate_url(expires_in=300)
heroku_app = HerokuApp(id, output=None, team=None)
... | 5,319,739 |
def get_index_from_filename(
file_name: str
) -> str:
"""
Returns the index of chart from a reproducible JSON filename.
:param file_name: `str`
The name of the file without parent path.
:returns: `str`
The index of the chart (e.g., 1) or an empty string.
"""
assembled_ind... | 5,319,740 |
def get_box_transformation_matrix(box):
"""
Create a transformation matrix for a given box pose.
"""
# tx,ty,tz = box.center_x,box.center_y,box.center_z
tx,ty,tz = box[0], box[1], box[2]
c = np.cos(box[6])
s = np.sin(box[6])
sl, sw, sh = box[3], box[4], box[5] # 这里如果读取的是 det3d 的 det... | 5,319,741 |
def get_redirect_target():
"""
获取跳转目标
:return:
"""
for target in request.args.get('next'), request.referrer:
if not target:
continue
if is_safe_url(target):
return target | 5,319,742 |
def printMissingValues(df, logger):
"""
Print missing values in Dataframe
Parameters
----------
df: Dataframe
Spark Dataframe
logs_dir: string
Directory for log file
Return
----------
"""
# Check data
df_missingVals_cols = df.select([count(when(c... | 5,319,743 |
def mixer_carrier_cancellation(SH, source, MC,
chI_par, chQ_par,
frequency: float=None,
SH_ref_level: float=-40,
init_stepsize: float=0.1,
x0=(0.0, 0.0),
... | 5,319,744 |
def resetdb(app, db):
"""
Delete all tables; Create all tables; Populate roles and users.
"""
# Drop all tables
print('Dropping all tables')
db.drop_all()
# Create all tables
print('Creating all tables')
db.create_all()
# Adding roles
print('Adding roles')
admin_role =... | 5,319,745 |
def create_single_wall_box(box_dimensions):
"""
width, depth, height, thickness,
fold_margin, wing_width
returns ShapeArray
"""
width = box_dimensions['width']
height = box_dimensions['height']
depth = box_dimensions['depth']
thickness = box_dimensions['thickness']
fold_margin ... | 5,319,746 |
def correct_start_cell_number(
start_cell_number: Optional[int], mcnp: Optional[str]
) -> int:
"""Define cell number to start with on output to accompanying excel.
Args:
start_cell_number: number from command line or configuration, optional.
mcnp: MCNP file name, optional
Returns:
... | 5,319,747 |
def add_run_stats_context(run, context):
"""Add all the detailed summary stats about a run and its networks and games.
For use on homepage or run detail view."""
context["run"] = run
context["top_recent_user_list"] = (
RecentGameCountByUser.objects.filter(run=run)
.values("username")
... | 5,319,748 |
def convert_labels_to_one_hot(
label_list: List[List[str]], label_dict: Dictionary
) -> List[List[int]]:
"""
Convert list of labels (strings) to a one hot list.
:param label_list: list of labels
:param label_dict: label dictionary
:return: converted label list
"""
return [
[1... | 5,319,749 |
def create(container_dir, distro_config):
"""Create a container using chocolatey."""
return _fetch_choco(container_dir, distro_config) | 5,319,750 |
def record_writer(iterator, create_example, path, num_threads=8):
"""Create a RecordIO file from data for efficient reading."""
if num_threads == 1:
writer = tf.python_io.TFRecordWriter(path)
for item in iterator:
example = create_example(item)
writer.write(example.SerializeToString())
write... | 5,319,751 |
def ESMP_VMPrint(vm):
"""
Preconditions: An ESMP_VM object has been retrieved.\n
Postconditions: The contents of 'vm' have been printed to standard
output.\n
Arguments:\n
ESMP_VM :: vm\n
"""
rc = _ESMF.ESMC_VMPrint(vm)
if rc != constants._ESMP_SUCCESS:
rai... | 5,319,752 |
def notas(*num, sit=False):
"""
Essa função cria um dicionário que guarda várias informações sobre o boletim de um aluno
:param num: lista de notas do aluno
:param sit: situação do aluno (aprovado, reprovado, recuperação)
:return: retorna o dicionário completo
"""
boletim = {}
boletim['Q... | 5,319,753 |
def columnize(student: 'StudentResult',
longest_user: str,
max_hwk_num: int,
max_lab_num: int,
max_wst_num: int,
highlight_partials: bool = True):
"""Build the data for each row of the information table"""
name = '{0:<{1}}'.format(student.nam... | 5,319,754 |
def get_db_statistics(fname=None, db=None, tables=None):
"""Get statistics on the contents of the database"""
if db is None:
db = get_primary_db()
task_dict = {
'text_ref': get_text_ref_stats,
'text_content': get_text_content_stats,
'readings': get_readings_stats,
's... | 5,319,755 |
def relate_one_to_many(
lhs: Iterable[Left],
rhs: Iterable[Right],
lhs_key: Callable[[Left], Key]=DEFAULT_KEY,
rhs_key: Callable[[Right], Key]=DEFAULT_KEY,
) -> Iterator[Tuple[Left, Iterator[Right]]]:
"""
Relates `rhs` items to each `lhs` items.
Note that:
- `Key` must be 'comparable' (... | 5,319,756 |
def cut(vid, bx, by):
"""Scales image without changing aspect ratio but instead growing to at least the size of box bx/by."""
ix = vid.get(cv.CAP_PROP_FRAME_WIDTH)
iy = vid.get(cv.CAP_PROP_FRAME_HEIGHT)
if bx / float(ix) > by / float(iy): # fit to width
scale_factor = bx / float(ix)
... | 5,319,757 |
def _conserve_heat(m, t):
"""
TODO
"""
sources = m.NuCap
sinks = -(m.Turbine[t] / ECONV_RATE) + m.NPP_unused[t]
battery = 0
for tes in HEAT_TECHS:
charge = getattr(m, f'{tes}_charge')[t]
discharge = getattr(m, f'{tes}_discharge')[t]
battery += (charge + discharge)
... | 5,319,758 |
def write_pickle(input_data, output_file, path=None):
"""
Write an object to pickle
Args:
input_data(dict): A dict to be written to json.
output_file(str): A filename or path to which the json will be saved.
path(str): A string which will be prepended onto `output_file` with
... | 5,319,759 |
def test_parse_env():
"""Test that options can be parsed from environment variables."""
cfg = config.Configuration(
test_env_parse=namespace.Namespace(env_loaded=boolopt.BoolOption())
)
os.environ["CONFPY_TEST_ENV_PARSE_ENV_LOADED"] = "TRUE"
cfg = parser.set_environment_var_options(config=c... | 5,319,760 |
def files_to_daisy_chain(ifg_names, figures = True):
"""
Given a list of interfergram names (masterDate_slaveDate), it:
- finds all the acquisition dates
- forms a list of names of the simplest daisy chain of interfegrams we can make
- lists which number acquistion each interferogra... | 5,319,761 |
def test_geturl():
"""Verify the short-cut to the URL."""
uri = (
builder.URIBuilder()
.add_scheme("https")
.add_credentials("sigmavirus24", "not-my-re@l-password")
.add_host("github.com")
.add_path("sigmavirus24/rfc3986")
.geturl()
)
expected = (
... | 5,319,762 |
def test_ap_wps_reg_config(dev, apdev):
"""WPS registrar configuring and AP using AP PIN"""
ssid = "test-wps-init-ap-pin"
appin = "12345670"
hostapd.add_ap(apdev[0]['ifname'],
{ "ssid": ssid, "eap_server": "1", "wps_state": "2",
"ap_pin": appin})
logger.info("... | 5,319,763 |
def set_group_attribute(data: AnnData, attribute_string: str) -> None:
"""Set group attributes used in batch correction.
Batch correction assumes the differences in gene expression between channels are due to batch effects. However, in many cases, we know that channels can be partitioned into several groups an... | 5,319,764 |
def find_region_candidates_volume(volume, peak_threshold, shifts = (0, 0)):
"""
:param volume:
:param peak_threshold:
:param shifts: (x, y)
:return:
"""
results = list()
for i in range(volume.shape[-1]):
slice = volume[..., i].copy()
cv2.GaussianBlur(slice, (3, 3), 0.4, ... | 5,319,765 |
def summarize(text):
""" Summarizes some text
"""
if len(text) > 20:
summary = text[0:10] + " ... " + text[-10:]
else:
summary = text
summary = summary.replace("\n", "\\n")
return summary | 5,319,766 |
def create_nic(fco_api, cluster_uuid, net_type, net_uuid, vdc_uuid, name=None):
"""
Create NIC.
:param fco_api: FCO API object
:param cluster_uuid: Cluster UUID
:param net_type: Network type; currently recommended 'IP'
:param net_uuid: Network UUID
:param vdc_uuid: VDC UUID
:param name:... | 5,319,767 |
def clean_logger(name = settings["app_name"]):
"""
Removes all handlers associated with a given logger
Parameters
----------
name : string
name of the logger
Returns
-------
logger.logger
"""
logger = lg.getLogger(name)
handlers = logger.handlers
for handler i... | 5,319,768 |
def model_from_json(json_string, custom_objects=None):
"""Parses a JSON model configuration string and returns a model instance.
Usage:
>>> model = tf.keras.Sequential([
... tf.keras.layers.Dense(5, input_shape=(3,)),
... tf.keras.layers.Softmax()])
>>> config = model.to_json()
>>> loaded_model ... | 5,319,769 |
def get_stock_stream(symbol, params={}):
""" gets stream of messages for given symbol
copied from api.py (found on GitHub)
"""
all_params = ST_BASE_PARAMS.copy()
return R.get_json(ST_BASE_URL + 'streams/symbol/{}.json'.format(symbol), params=all_params) | 5,319,770 |
async def test_zwave_js_event_invalid_config_entry_id(
hass, client, integration, caplog
):
"""Test zwave_js.event automation trigger fails when config entry ID is invalid."""
trigger_type = f"{DOMAIN}.event"
assert await async_setup_component(
hass,
automation.DOMAIN,
{
... | 5,319,771 |
def html_module_detail(filename, module_name, nav=None):
"""
Creates a module detail report based on coverage testing at the specified
filename. If ``nav`` is specified, the nav template will be used as well.
It uses `templates.default_module_detail` to create the page. The template
contains the fo... | 5,319,772 |
def get_free_swap_memory() -> int:
"""Get the free swap memory size in bytes."""
return swap_memory().free | 5,319,773 |
def get_application(application_id: str = None):
"""
Returns an application.
:param application_id: The numeric ID of the application you're interested in.
:returns: String containing xml or an lxml element.
"""
return get_anonymous('getApplication', application_id=application_id) | 5,319,774 |
def sexastr2deci(sexa_str):
"""Converts as sexagesimal string to decimal
Converts a given sexagesimal string to its decimal value
Args:
A string encoding of a sexagesimal value, with the various
components separated by colons
Returns:
A decimal value corresponding to the sexagesimal... | 5,319,775 |
def test_get_directory_files_no_files(working_dir):
"""Get directory file: no files.
"""
received = []
for filename in filester.get_directory_files(working_dir):
received.append(filename)
msg = 'Empty directory listing error'
assert not received, msg
received = filester.get_director... | 5,319,776 |
def run_extractor_on_dataset(dataset_path):
"""Run the feature extractor pipeline on the target dataset then consolidate results.
Note: This function runs on all images within SUB DIRECTORIES of the dataset path.
Output will be a single features JSON for each frame ID. All emitted individual image
fea... | 5,319,777 |
def run_pipeline_func_on_cluster(
pipeline_func: Callable,
arguments: Mapping[str, str],
run_name: str = None,
experiment_name: str = None,
kfp_client: Client = None,
pipeline_conf: dsl.PipelineConf = None,
):
"""Runs pipeline on KFP-enabled Kubernetes cluster.
This command compiles the... | 5,319,778 |
def find_duplicates(dirname, extension):
"""Write a program that searches a directory and all of its subdirectories, recursively, and returns
a list of complete paths for all files with a given suffix (like .mp3)."""
possible_duplicates = dict()
for file in filter_files_with_extension(dirname, extension):
... | 5,319,779 |
def generate_LoD_to_FNR_table(min_LoD, max_LoD):
"""
Generate a lookup table for (detection threshold, FNR)
"""
LoDs = np.arange(min_LoD, max_LoD + 1)
num_processes = cpu_count()
print(LoDs, num_processes)
with Pool(num_processes) as p:
FNRs = p.map(calculate_FNR, LoDs)
resu... | 5,319,780 |
def reverb2mix_transcript_parse(path):
"""
Parse the file format of the MLF files that
contains the transcripts in the REVERB challenge
dataset
"""
utterances = {}
with open(path, "r") as f:
everything = f.read()
all_utt = everything.split("\n.\n")
for i, utt in enumerate... | 5,319,781 |
def extract_qa_bits(qa_band, start_bit, end_bit):
"""Extracts the QA bitmask values for a specified bitmask (starting
and ending bit).
Parameters
----------
qa_band : numpy array
Array containing the raw QA values (base-2) for all bitmasks.
start_bit : int
First bit in the bit... | 5,319,782 |
def is_scalar(v,value=None):
"""Returns True if v evaluates to a scalar. If value is provided, then
returns True only if v evaluates to be equal to value"""
if isinstance(v,Variable):
if not v.type.is_scalar(): return False
return value is None or v.value == value
elif isinstance(v,Cons... | 5,319,783 |
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the Awesome Light platform."""
# Assign configuration variables.
# The configuration check takes care they are present.
ipAddress = config[CONF_IP_ADDRESS]
email = config[CONF_EMAIL]
password = config.get(CONF_PASSWOR... | 5,319,784 |
def plot(x, y, xlabel="", ylabel="", title=""):
"""
plot(x, y, xlabel="", ylabel="") function description:
plots a function given a domain and range
Args:
x - the domain of values
y - the range of values
xlabel - the label of the x-axis (defaults to "")
ylabel - the lab... | 5,319,785 |
def cluster_homogeneity(df:pd.DataFrame, edge_type="Edge", iteration_type="Iteration"):
"""
# Create Graph
from soothsayer_utils import get_iris_data
df_adj = get_iris_data(["X"]).iloc[:5].T.corr() + np.random.RandomState(0).normal(size=(5,5))
graph = nx.from_pandas_adjacency(df_adj)
graph.nodes... | 5,319,786 |
def to_json_for_storage(desc: SomeRunDescriber) -> str:
"""
Serialize the given RunDescriber to JSON as a RunDescriber of the
version for storage
"""
return json.dumps(to_dict_for_storage(desc)) | 5,319,787 |
def astar(graph, start, end, heuristic={}):
"""
Performs A-star search to find the shortest path from start to end
Args:
graph (gennav.utils.graph): Dictionary representing the graph where keys are the nodes
and the value is a list of all neighbouring nodes
start (gennav.utils.R... | 5,319,788 |
def extractFileName(form, id, cleanup=True, allowEmptyPostfix=False):
"""Extract the filename of the widget with the given id.
Uploads from win/IE need some cleanup because the filename includes also
the path. The option ``cleanup=True`` will do this for you. The option
``allowEmptyPostfix`` allows to ... | 5,319,789 |
def disable_debug():
"""Turn off debug logging."""
global DEBUG_LOGGING
DEBUG_LOGGING = False | 5,319,790 |
def find_pointing_start(asn_table_name):
"""
Parameters:
asn_table_name : string
For example, 'gs2-01-189-g102'. Targname-visit-PA-filter
Returns:
0 : if visit starts with direct image
1 : if visit starts with grism
Outputs:
"""
# Parse out the asn tab... | 5,319,791 |
def data_logs(recipe_id=None):
""" Flask controller: show logs for a recipe
"""
level = flask.request.args.get('level', 'WARNING').upper()
recipe = recipes.Recipe(recipe_id)
return flask.render_template("data-logs.html", recipe=recipe, level=level, in_logger=True) | 5,319,792 |
def slice_metadata_using_already_sliced_data_df(data_df, row_meta_df, col_meta_df):
"""Slice row_meta_df and col_meta_df to only contain the row_ids and col_ids
in data_df.
Args:
data_df (pandas df)
row_meta_df (pandas df)
col_meta_df (pandas df)
Returns:
out_gct (GCToo... | 5,319,793 |
def create_user(request, template_name='create_user.html',
redirect_field_name=REDIRECT_FIELD_NAME,
user_creation_form=UserCreationForm,
current_app=None, extra_context=None):
"""
Displays the login form and handles the login action.
"""
# noinspection PyU... | 5,319,794 |
def process_need_nodes(app, doctree, fromdocname):
"""
Event handler to add title meta data (status, tags, links, ...) information to the Need node.
:param app:
:param doctree:
:param fromdocname:
:return:
"""
if not app.config.needs_include_needs:
for node in doctree.traverse(N... | 5,319,795 |
def found_table(schema:str, table_name:str) -> bool:
"""Returns whether the given table is found in the list of cached tables"""
return len(
[
table for table in tables
if table.table_name == table_name and table.schema == schema
]
) == 1 | 5,319,796 |
def setup_ctx(
ctx,
private_key,
rpc_provider,
wait,
gas_price,
gas_limit,
):
"""Set up deployment context according to common options (shared among all
subcommands).
"""
if private_key is None:
return
logging.basicConfig(level=logging.DEBUG)
logging.getLogger('w... | 5,319,797 |
def download_url(url, pth_download=None, speak=False):
"""Download data from URL."""
if wget is None:
raise ImportError('wget not available')
bar = None
if speak:
def bar(current, total, width=80):
print("Downloading %s to %s | Progress: %d%% (%d/%d bytes)"
... | 5,319,798 |
def openurl(url):
"""Retries urlopen.
:param url: url to open
"""
return urlopen(url) | 5,319,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.