content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def test_save_multiple_user(self):
"""
test_save_multiple _user to check if we can save multiple user object to our user_list
"""
self.new_user.save_user()
test_user = User("Test","12338")
test_user.save_user()
self.assertEqual(len(User.user_list),2) | 65,500 |
def get_stream(graph):
"""
Return a stream of prior samples
Args:
graph: json graph as loaded by daphne wrapper
Returns: a python iterator with an infinite stream of samples
"""
while True:
yield sample_from_joint(graph)[0] | 65,501 |
def get_headers(token_scope: str = TIMER_SERVICE_SCOPE) -> Dict[str, str]:
"""
Assemble any needed headers that should go in all requests to the timer API, such
as the access token.
"""
token = get_access_token_for_scope(token_scope)
if not token:
raise ValueError("couldn't get token")
... | 65,502 |
def unrank(n, sequence=string.ascii_lowercase):
"""Unrank n from sequence in colexicographical order.
>>> [''.join(unrank(i)) for i in range(8)]
['', 'a', 'b', 'ab', 'c', 'ac', 'bc', 'abc']
>>> unrank(299009)
['a', 'm', 'p', 's']
"""
return list(map(sequence.__getitem__, indexes(n))) | 65,503 |
def waste_schema():
"""Provides schema validation to tests"""
schema_file_contents = pkgutil.get_data("atomic6ghg.schemas", "waste.json")
schema = json.loads(schema_file_contents)
v = Draft7Validator(schema=schema)
return v | 65,504 |
def min_threshold_dist_from_shapefile(shapefile, radius=None, p=2):
"""
Kernel weights with adaptive bandwidths.
Parameters
----------
shapefile : string
shapefile name with shp suffix.
radius : float
If supplied arc_distances will be calculated
... | 65,505 |
def datetimetodatetime64(t):
"""
Convert a vector of datetime64 to datetime objects
"""
#return np.array([np.datetime64(tt) for tt in t]).astype('datetime64[us]')
return np.array([np.datetime64(tt) for tt in t]).astype('<M8[ns]') | 65,506 |
def check_session():
"""
Checks validity of session using only required() decorator
"""
return '{}' | 65,507 |
def gaussian(area, mean=0, sigma=0.8):
"""
mean 均值, sigma 標準差
輸出縮限到0~1之間
"""
noise = np.random.normal(mean, sigma, area)
return np.clip(noise, 0, 1) | 65,508 |
def blocks(
ctx, input, output, precision, indent, compact, projection, sequence,
use_rs, bidx):
"""Write dataset blocks as GeoJSON features.
This command writes features describing a raster's internal blocks, which
are used directly for raster I/O. These features can be used to visualize... | 65,509 |
async def test_product():
"""Create a test product which can be modified by the test"""
product = ApigeeApiProducts()
await product.create_new_product()
await _set_default_rate_limit(product)
yield product
await product.destroy_product() | 65,510 |
def direction_to_index(direction: str) -> int:
"""Converts string representation of direction into integer
Parameters
----------
direction: str
"UP", "DOWN", "LEFT", "RIGHT
Returns
-------
direction_onehot: torch.LongTensor
Integer representation of the direction
"""
... | 65,511 |
def test_panel_in_panel_out_supported():
"""Test that fit/transform runs and returns the correct output type.
Setting: transformer has tags
"scitype:transform-input" = "Series"
"scitype:transform-output" = "Series"
"fit-in-transform" = False
"X_inner_mtype" supports "Panel"
... | 65,512 |
def histo_analysis(hist_data):
"""
Calculates the mean and standard deviation of derivatives of (x,y) points. Requires at least 2 points to compute.
parameters:
hist_data: list of real coordinate point data (x, y)
return:
Dictionary with (mean, deviation) as keys to corresponding values
"""
if len(hist_data[0... | 65,513 |
def check_if_object_exists(
local_uri: str,
file_loc: str,
obj_type: str,
search_data: typing.Dict,
token: str = None,
) -> str:
"""Checks if a data product is already present in the registry
Parameters
----------
local_uri : str
local registry endpoint
file_loc : str
... | 65,514 |
def test_nothing_assembled_02(info):
"""It handles an empty assembly."""
asm = build_assembler()
asm.file['output'] = 'tests/data/empty_file.txt'
assert asm.nothing_assembled()
expect = 'No new assemblies in iteration {}'.format(
asm.state['iteration'])
info.assert_called_once_with(exp... | 65,515 |
def copy_docs(build):
""" copy documentation into the application directory. This allows
the docs to be packaged with the app itself.
"""
doc_dir = os.path.join(
build.root, build.config["uranium-plus"]["module"], "docs"
)
if os.path.exists(doc_dir):
shutil.rmtree(doc_dir)
sh... | 65,516 |
def platform():
"""
:return (string): returns the name of the platform
"""
return "circadia sunrise lamp" | 65,517 |
def destroy_workspace(workspace_name, workspace_path):
"""Delete tempest workspace.
:param workspace_name: name of workspace
:type workspace_name: str
:param workspace_path: directory path where workspace is stored
:type workspace_path: str
:returns: None
:rtype: None
"""
try:
... | 65,518 |
def Adam(loss, all_params, learning_rate=0.001, b1=0.9, b2=0.999, e=1e-8,
gamma=1-1e-8):
"""
ADAM update rules
Default values are taken from [Kingma2014]
References:
[Kingma2014] Kingma, Diederik, and Jimmy Ba.
"Adam: A Method for Stochastic Optimization."
arXiv preprint arXiv:1412.... | 65,519 |
def _ggm_prob_wait_whitt_z(ca2, cs2):
"""
Equation 3.8 on p139 of Whitt (1993). Used in approximation for P(Wq > 0) in GI/G/c/inf queue.
See Whitt, Ward. "Approximations for the GI/G/m queue"
Production and Operations Management 2, 2 (Spring 1993): 114-161.
Parameters
----------
ca2 : flo... | 65,520 |
def get_market_orders(region_id='10000030', type_id='34'):
"""Get the current market orders for an item in a region.
API has 6 min cache time."""
crest_order_url = 'https://crest-tq.eveonline.com/market/{}/orders/{}/?type=https://public-crest.eveonline.com/inventory/types/{}/'
dfs = []
for order_... | 65,521 |
def wait(
service,
condition,
fail_condition=lambda e: False,
timeout=180,
wait=True,
poll_interval=3,
):
"""
Wait until entity fulfill expected condition.
:param service: service of the entity
:param condition: condition to be fulfilled
:param fail_condition: if this condit... | 65,522 |
def date(m=0,d=0):
"""
returns all the fun holidays on the specified date
"""
holidays = holidays_date(m, d)
if not holidays:
return jsonify(holidays), status.HTTP_400_BAD_REQUEST
return jsonify({"day": d, "month": m, "holidays": [h.holiday for h in holidays]}) | 65,523 |
def test_pipe(tmp_path, raw, insert_blank):
"""Test pipe method on UV object"""
infile = os.path.join(DATA_PATH, "zen.2456865.60537.xy.uvcRREAA")
test_file = os.path.join(tmp_path, "miriad_test.uv")
aipy_uv = aipy_extracts.UV(infile)
aipy_uv2 = aipy_extracts.UV(test_file, status="new")
aipy_uv2... | 65,524 |
def pproc_Mindlin_2d(size, shape: nparray, points: nparray,
solution: nparray, D: nparray, S: nparray):
"""
JIT-compiled function that calculates post-processing quantities
at selected ponts for multiple left- and right-hand sides.
Parameters
----------
size : tuple... | 65,525 |
def addanovap_real1():
"""
addanovap_real1
description:
Uses the raw data from real_data_1.csv to compute ANOVA p-values for all 5 of the defined groups
Test fails if the shape of the resulting "test_anova" statistic array in the Dataset object does not have
the proper shape: (773,)
... | 65,526 |
def _verify_input_is_provided( metric, conditioning, ab_comp, infile2, centrality, correlation ):
"""
This function provides preventative error checking.
If a metric is used make sure the parameters for it have been provided.
Otherwise the process should be terminated immediately in order to prevent was... | 65,527 |
def test_error_bounded_no_exception() -> None:
"""Test error bounded decorator during happy case."""
def mock_fun() -> Tuple[Optional[AppError], bool]:
return AppError(ErrorCode.GOOGLE_API_ERROR, "google error"), False
wrapper = error_bounded((AppError(ErrorCode.MONGO_ERROR, "mongo"), True))
w... | 65,528 |
def attack_single_target(caller,target, attack):
"""
Launch an attack on a single EC2 instance.
:param caller: Calling menu to return to.
:param target: Target EC2 instance id
:param attack: The attack to launch.
:return: True
"""
global ec2instances
target_id = ''
target_platfor... | 65,529 |
def get_repost_list(html, mid):
"""
Get repost details
:param html: page source
:param mid: weibo mid
:return: list of repost infos
"""
cont = get_html_cont(html)
if not cont:
return list()
soup = BeautifulSoup(cont, 'html.parser')
repost_list = list()
... | 65,530 |
def validate():
""" Validate code of the current directory. Previous initialization might be needed. """
run(command="validate", enable_mfa=False) | 65,531 |
def login_access_token(
response: Response,
db: Session = Depends(deps.get_db),
form_data: OAuth2PasswordRequestForm = Depends()
) -> Any:
"""
OAuth2 compatible token login, get an access token for future requests
"""
user = crud.user.authenticate(
db, email=form_data.use... | 65,532 |
def parse_method(name):
"""Parse hyperparameters from string name to make legend label.
Parameters
----------
name : str
Name of method
Returns
-------
string : str
Formatted string
"""
string = r""
if name.split('es_')[1][0] == '1':
string += r'ES'
... | 65,533 |
def update_game_index(path: pathlib.Path,
source: str, league: str,
df: pd.DataFrame) -> pd.DataFrame:
"""Update the game index for league with data from source."""
league = league.replace(" ", "").replace("-", "")
(path/league).mkdir(exist_ok=True, parents=True)
... | 65,534 |
def find_td_chordal(graph, order):
"""Finding a tree decomposition for chordal graphs."""
cliques = find_all_maximal_cliques(graph, order)
H = Graph() # graf przeciec klik maksymalnych
bag_dict = dict()
# Budowanie workow.
for c in cliques:
bag = tuple(sorted(c))
bag_dict[bag] ... | 65,535 |
def get_categories() -> pd.DataFrame:
"""Returns dataframe of tesco food categories"""
return pd.read_csv(TESCO_DIR / "food_categories.csv") | 65,536 |
def Transformer(input_vocab_size,
output_vocab_size=None,
d_model=512,
d_ff=2048,
n_encoder_layers=6,
n_decoder_layers=6,
n_heads=8,
dropout=0.1,
dropout_shared_axes=None,
max_... | 65,537 |
def test_discriminating_path():
"""Test the output of a discriminating path.
We look at a graph presented in [1] Figure 2.
References
----------
[1] Colombo, Diego, et al. "Learning high-dimensional directed acyclic
graphs with latent and selection variables." The Annals of Statistics
(201... | 65,538 |
def schedule_conv2d_NHWC_quantized_native_without_transform(cfg, outs):
"""Interface for native schedule_conv2d_NHWC_quantized"""
return _schedule_conv2d_NHWC_quantized(cfg, outs, False) | 65,539 |
def describe_stack_resource(StackName=None, LogicalResourceId=None):
"""
Returns a description of the specified resource in the specified stack.
For deleted stacks, DescribeStackResource returns resource information for up to 90 days after the stack has been deleted.
See also: AWS API Documentation
... | 65,540 |
def mentions(date, aliases):
"""Pull dark web mentions data for an organization."""
# aliases = aliases.replace("'", '"')
# aliases = str(aliases)[1:-1]
mentions = ""
for mention in aliases:
mentions += '"' + mention + '"' + ","
mentions = mentions[:-1]
print(mentions)
query = "s... | 65,541 |
def queue_with(items):
"""Return a thread-safe iterator that yields the given items.
+items+ can be given as an array or an iterator. If an iterator is
given, it will be consumed to fill the queue before queue_with()
returns.
"""
q = queue.Queue()
for val in items:
q.put(val)
re... | 65,542 |
def resample_by(image_array, compression_factor_list, is_seg=False):
"""
Resamples `image` to new resolution according to a compression factor using scipy's `ndimage`
Attributes:
image_array (float, np.array) : Array of voxel values for image
compression_factor_list (list) : Compression or... | 65,543 |
def enable_vnc(module, array, app):
"""Enable VNC port"""
changed = False
vnc_fact = []
if not app['vnc_enabled']:
try:
if not module.check_mode:
array.enable_app_vnc(module.params['name'])
vnc_fact = array.get_app_node(module.params['name'])
... | 65,544 |
def unit_orthogonal_initialize_equivariant_linears(mod: torch.nn.Module):
"""Initialize ``e3nn.o3.Linear``s that have internal weights with ``unit_orthogonal_init_``"""
if isinstance(mod, e3nn.o3.Linear) and mod.internal_weights:
for w in mod.weight_views():
unit_orthogonal_init_(w) | 65,545 |
def get_highlight(request):
"""
Get Originals objects with highlight status and
render them.
"""
highlight = Original.objects.filter(status='h')
context = {
'highlight': highlight,
'highlight_page': 'active',
'title': 'Highlights'
}
return render(request, "highli... | 65,546 |
def set_stdio_utf8():
"""
Set standard I/O streams to UTF-8.
Attempt to reassign standard I/O streams to new streams using UTF-8.
Standard input should discard any leading BOM. If an error is raised,
assume the environment is inflexible but correct (IDLE).
"""
try:
sys.stdin = io.T... | 65,547 |
def create_or_update_out_of_the_bbox(
move_data: DataFrame,
bbox: Tuple[int, int, int, int],
new_label: Optional[Text] = OUT_BBOX,
inplace: Optional[bool] = True
) -> Optional[DataFrame]:
"""
Create or update a boolean feature to detect points out of the bbox.
Parameters
----------
... | 65,548 |
def plot_classes_statistics(labels, values, dataset_type, include_indels=True):
"""
WARNING: This function is for racon-hax data format.
:param labels: X-axis labels (classes).
:type labels: list of str
:param values: List of values to be plotted.
:type values: list of np.ndarray
:param dat... | 65,549 |
def pin_compatible(m, package_name, lower_bound=None, upper_bound=None, min_pin='x.x.x.x.x.x',
max_pin='x', permit_undefined_jinja=True):
"""dynamically pin based on currently installed version.
only mandatory input is package_name.
upper_bound is the authoritative upper bound, if provid... | 65,550 |
def _get_etc_dir():
"""The root directory of xedge, such as `/home/gamecenter/etc`"""
return os_path.join(os_path.dirname(os_path.abspath(__file__)),
os_path.pardir, 'etc') | 65,551 |
def _sandbox_executable() -> Path:
"""Return full path to Algorand's sandbox executable."""
return ConfigParams.sandbox_dir / "sandbox" | 65,552 |
def set_remote_async_python_execution_context(channels,
thread_pool_executor=None,
dispose_batch_size=20,
max_fanout: int = 100,
default... | 65,553 |
def _get_file_contents(path):
"""
Gets the contents of a specified file, ensuring that the file is properly
closed when the function exits
"""
with open(path, "r") as f:
return f.read() | 65,554 |
def latency_echo(url, count, size=None, poll=False, copy=True, quiet=False):
"""echo messages on a REP socket
Should be started before `latency`
"""
ctx = zmq.Context()
s = ctx.socket(zmq.REP)
if poll:
p = zmq.Poller()
p.register(s)
s.bind(url)
block = zmq.NOB... | 65,555 |
def get_user_by_phone_number(phone):
"""
Returns a user object that is dictionary
of the user with attributes:
display_name , email , password, phone_number
"""
from firebase_admin import auth
try:
user = auth.get_user_by_phone_number(phone)
doc = db.collection(u'users').document(user.uid)
doc = doc.get()... | 65,556 |
def test_main_export_config(capsys):
"""Test export_config() function directly"""
iface = MagicMock(autospec=SerialInterface)
with patch('meshtastic.serial_interface.SerialInterface', return_value=iface) as mo:
mo.getLongName.return_value = 'foo'
mo.getShortName.return_value = 'oof'
... | 65,557 |
def analyzer():
"""
For a doconce file, possibly composed of many other doconce
files, in a nested fashion, this function returns a tree
data structure with the various parts, included files,
involved source code, figures, movies, etc.
Method:
Go through all #include's in a doconce file, fi... | 65,558 |
def get_root_server(domain):
"""
Find the WHOIS server for a given domain
:param domain: The domain to find a WHOIS server for
:return: The WHOIS server, or an empty string if no server is found
"""
data = whois_request(domain, "whois.iana.org").response or ""
for line in [x.strip() for x in... | 65,559 |
def insert_into_kline_table(symbol, interval, klines, conn):
"""
:param symbol: The ticker symbol. Ex: BTCUSDT
:param interval: The interval. Ex: 1m, 4h, 1D
:param klines: List of tuples containing values : [()]
:param conn: TimescaleDB connection object
"""
start = time.time()
cursor = ... | 65,560 |
def sample_user(email='test@test.com',password='testpass'):
"""Create a sample user"""
return get_user_model().objects.create_user(email,password) | 65,561 |
def getsubheader(runid,snapnum,datadir=None,datascope=False,getfof=False,verbose=False):
"""Reads the SUBFIND header (total number of subhalos) of an Indra snapshot.
Parameters
----------
runid : int or tuple
Specifies the Indra run either as an integer from 0 to 511
or as a length ... | 65,562 |
def from_config(config, token_store: tokens.TokenStore):
""" Generate a Fediverse handler from the given config dictionary.
:param dict config: Configuration values; relevant keys:
* ``FEDIVERSE_NAME``: the name of your website (required)
* ``FEDIVERSE_HOMEPAGE``: your website's homepage (rec... | 65,563 |
def clickwrap_responses():
"""
1. Get required arguments
2. Call the worker method
3. Render the response
"""
# 1. Get required arguments
args = Eg005Controller.get_args()
try:
# 2. Call the worker method to get clickwrap responses
results = Eg005Controller.worker(args)
... | 65,564 |
def get_confirm_token(response):
"""
Filters response for confirm token.
:param Response response: Response object to filter through.
:returns: token or None
"""
for key, value in response.cookies.items():
if key.startswith('download_warning'):
return value
return None | 65,565 |
def wilcoxont(x, y):
"""
Calculates the Wilcoxon T-test for related samples and returns the
result. A non-parametric T-test.
Usage: lwilcoxont(x,y)
Returns: a t-statistic, two-tail probability estimate
"""
if len(x) != len(y):
raise ValueError('Unequal N in wilcoxont. Aborting.')
d = []
for... | 65,566 |
def msgfmt(msg, prefix=''):
"""Format a message"""
lines = []
for line in msg.splitlines():
lines += textwrap.wrap(line, 80 - len(prefix))
return '\n'.join([prefix + line for line in lines]) | 65,567 |
def _parse_text(raw_object: RawObject) -> Text:
"""Parse the raw object into Text.
Args:
raw_object: Raw object to be parsed to a Text
Returns:
Text: The Text object created from the raw object
"""
# required attributes
raw_text: RawText = raw_object["text"]
text = raw_text... | 65,568 |
def _is_onetime_boot(task):
"""Check onetime boot from server hardware.
Check if the onetime boot option of an OneView server hardware
is set to 'Once' in iLO.
:param task: a task from TaskManager.
:returns: Boolean value. True if onetime boot is 'Once'
False otherwise.
"""
s... | 65,569 |
def get_setting(name: str) -> Setting:
"""Return appropriate setting."""
if name not in SETTINGS:
raise Exception(
"Setting does not exist. Valid settings are: %s" % list(SETTINGS.keys())
)
return SETTINGS[name] | 65,570 |
def convertKeyValueToString(dict,key) -> str:
""" converts a single key value pair into a concatenated string"""
if dict and key:
# force cast key to string
val = dict[key]
valStr = str(val)
keyStr = str(key)
concantStr = keyStr + valStr
else:
concantStr = ""... | 65,571 |
def _flatten(seq):
"""Internal function."""
res = ()
for item in seq:
if isinstance(item, (tuple, list)):
res = res + _flatten(item)
elif item is not None:
res = res + (item,)
return res | 65,572 |
def get_uuid(value):
"""
gets the uuid object of given value.
it raises an error if value is not a valid uuid string.
:param str value: value to get uuid instance from it.
:raises ValueError: value error.
:rtype: uuid.UUID
"""
return uuid.UUID(value) | 65,573 |
def tag_autocomplete():
""" CKAN autocomplete discards vocabulary_id from request.
This is modification from tag_autocomplete function from CKAN.
Takes vocabulary_id as parameter.
"""
q = request.args.get('incomplete', '')
limit = request.args.get('limit', 10)
vocabulary_id = request... | 65,574 |
def get_lengths(input_list: list):
"""
Generator function that yields the length of the strings in input_list
"""
for person in input_list:
yield len(person) | 65,575 |
def hex_22(n):
"""Finds the symmetry preserving HNFs for the hexagonal lattices
with a determinant of n. Assuming A = [[0,0,-0.5],[1,0,0],[-0.5,0.8660254037844386,0]].
Args:
n (int): The determinant of the HNFs.
Returns:
spHNFs (list of lists): The symmetry preserving HNFs.
"""
... | 65,576 |
def preprocess_int(i, **options):
"""Convert a string to an integer."""
return str(i) | 65,577 |
def _convert_to_parquet(dataset,year,datafolder):
""" convert sas dataset in given year to parquet format
Args:
dataset (str): name of dataset
year (int): year
datafolder (str): path to where results are saved
"""
# a. load sas data
df = pd.read_sas(f'{datafolder}/{... | 65,578 |
def es_cadena_valida(adn):
"""
Ingresa una cadena y determina si es valida o no
:param adn: Ingresa unos caracteres en mayuscula para validar si estan o no en el rango
:return: True o False si es o no cadena respectivamente
>>> es_cadena_valida('AGATA')
True
>>> es_cadena_valida('GATA')
... | 65,579 |
def legendre_basis(x_data, n_state=2, domain=(0, 1), chunks=(1,)):
"""
legendre discretization of a microstructure.
Args:
x_data (ND array) : The microstructure as an `(n_samples, n_x, ...)`
shaped array where `n_samples` is the number of samples and
`n_x` is the spatial dis... | 65,580 |
def redemption_group_counts():
"""
Build integers which can represent the number of groups in the redemption
process.
"""
return integers(
min_value=1,
# Make this similar to the max_value of voucher_counters since those
# counters count through the groups.
max_value=... | 65,581 |
def draw_turtle_screensaver():
""" Draw random lines on the screen that bounce around
If left mouse button is clicked, bob the turtle changes
direction. If right mouse button is clicked, bob the turtle
is killed.
"""
# Define or hard working turtle
turtle_screen = turtle.Screen()
turtl... | 65,582 |
def netchop_predict(sequences):
"""
Return netChop predictions for each position in each sequence.
Parameters
-----------
sequences : list of string
Amino acid sequences to predict cleavage for
Returns
-----------
list of list of float
The i'th list corresponds to the i'th se... | 65,583 |
def ThetaV(pressures, temps_cent, dewp_temps_cent):
"""Virtual Potential Temperature
INPUTS
temp_k (K)
pres (Pa)
e: Water vapour pressure (Pa) (Optional)
"""
mixr = WaterVapourMixingRatio(pressures, dewp_temps_cent)
theta = Theta(pressures, temps_cent, dewp_temps_cent)
return... | 65,584 |
def build_fluxfile(spec1d_to_sensfunc: Dict[str,str], output_path: str,
spectrograph: str, user_config_lines: List[str]) -> str:
"""
Writes the fluxfile for fluxing.
Uses archived sensitivity function if no standard was reduced.
Args:
spec1d_to_sensfunc (Dict[str,str]): maps spec1d fil... | 65,585 |
def check_image_hdu(data, ext=0, logger=logger):
"""Check if a data is a valid ImageHDU type or convert it."""
if not isinstance(data, imhdus):
if isinstance(data, fits.HDUList):
logger.debug(f"Extracting HDU from ext {ext} of HDUList")
data = data[ext]
elif isinstance(da... | 65,586 |
def batch_predict(args, tag_model_path, chunk_model_path, wt_screen=False):
"""
Predict in batches
Optimized for predicting POS tags in batches and uses multiprocessing
"""
mp_n_procs = min(args.max_processes, N_PROCESSES)
logger.info("N PROCESSES: {}".format(mp_n_procs))
pool = mp.Pool(proc... | 65,587 |
def test_snips_unknown_intent(hass, mqtt_mock):
"""Test calling unknown Intent via Snips."""
event = 'call_service'
events = []
@callback
def record_event(event):
"""Add recorded event to set."""
events.append(event)
result = yield from async_setup_component(hass, "snips", {
... | 65,588 |
def stop(pin=microbit.pin0, music_off=True):
"""Silence the music output on the pin and turn off music mode."""
pin.music_frequency(0)
if music_off:
pin.music_off() | 65,589 |
def cluster_smiles(smiles: list, clustering_cutoff: float = 0.4):
""" Cluster smiles based on their Murcko scaffold using the Butina algorithm:
D Butina 'Unsupervised Database Clustering Based on Daylight's Fingerprint and Tanimoto Similarity:
A Fast and Automated Way to Cluster Small and Large Data Sets',... | 65,590 |
def is_uri(name):
"""Checks whether the name is a URI or not.
:param name: Name of the resource
:returns: True if name is URI, False otherwise
"""
try:
(urn, prod, trailer) = name.split(':', 2)
return (urn == 'urn' and prod == PROD_NAME)
except Exception:
return False | 65,591 |
def query_flask_state():
"""
Query the local state and redis status
:return: flask response
"""
try:
b2d = request.json
if not isinstance(b2d, dict):
logger.warning(ErrorMsg.DATA_TYPE_ERROR).get_msg(
'.The target type is {}, not {}'.format(dict.__name__, t... | 65,592 |
def calc_delta_L_dash_CS_R_d_t_i(i, region, Q, r_A_ufvnt, underfloor_insulation, A_A, A_MR, A_OR, A_HCZ_i, Theta_ex_d_t,
L_dash_H_R_d_t_i, L_dash_CS_R_d_t_i):
"""当該住戸の暖冷房区画iの床下空間を経由して外気を導入する換気方式による冷房顕熱負荷削減量 (MJ/h) (2)
Args:
i(int): 暖冷房区画の番号
region(int): 省エネルギー地域区分
... | 65,593 |
def select_action(state, valueNetwork, episodeNumber, numTakenActions, args):
""" Take action a with ε-greedy policy based on Q(s, a; θ)
return: int
"""
assert isinstance(state, torch.Tensor)
sample = random.random()
if args.mode == 'train':
eps_threshold = args.eps_end + (args.eps_star... | 65,594 |
def playpos(context, songpos):
"""
*musicpd.org, playback section:*
``play [SONGPOS]``
Begins playing the playlist at song number ``SONGPOS``.
*Clarifications:*
- ``playid "-1"`` when playing is ignored.
- ``playid "-1"`` when paused resumes playback.
- ``playid "-1"`` when s... | 65,595 |
def test_create_url(shortcut, tmp_dir):
"""
Make sure we can create url type shortcuts
"""
test_link = str(os.path.join(str(tmp_dir / "test_link.url")))
shortcut.create(
path=test_link,
target="www.google.com",
)
expected = {
"arguments": "",
"description": "... | 65,596 |
def get_text(original, lang="en"):
""" Return a translation of text in the user's language.
@type original: unicode
"""
if original == u"":
return u""
global TRANSLATIONS
if not TRANSLATIONS:
init_i18n(BotConfig)
try:
return TRANSLATIONS[lang][original]
exc... | 65,597 |
def test_bundle_8(base_settings):
"""No. 8 tests collection for Bundle.
Test File: conceptmaps.json
"""
filename = base_settings["unittest_data_dir"] / "conceptmaps.json"
inst = bundle.Bundle.parse_file(
filename, content_type="application/json", encoding="utf-8"
)
assert "Bundle" ==... | 65,598 |
def is_rectangle(coords):
"""
(tuple(tuple(float or int, float or int))) -> Boolean
Takes a tuple of (x, y) coordinate tuples. Returns True if the
coordinates represent a rectangle. Otherwise returns False.
"""
# look for four segments defined by five points
has_four_segments = (len(coords)... | 65,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.