content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def test_exempt_watts_mpe():
"""We are not (yet) asserting return vals. No external FCC ref
available.
"""
n = 0
for meters, mhz in mpe_usable_values():
fcc.exempt_watts_mpe(meters, mhz) # throwaway
n += 1
for meters, mhz, dummy in mpe_exception_values():
with pytest.rai... | 68,700 |
def compute_interestingness_conjunct(trace, ltl_name, ltl_props, vocab):
"""
Computes the interestingness for a conjunct LTL over trace
:param trace: execution trace in the form of a list of states over time
:param ltl_name: the ltl formula name (global, eventual, etc.) for which interestingness metric ... | 68,701 |
def vts_proxy_world_topo_thunderforest(
layer: str, z: int, x: int, y: int
) -> FlaskResponse:
"""
Tunneling map requests to the Thunderforest servers in order to hide the API key.
Other tile layer URLs:
https://manage.thunderforest.com/dashboard
Args:
layer (str): Tile layer.
z... | 68,702 |
def download_key():
"""Download security key
**Example request**
.. sourcecode:: http
POST /downloadKey HTTP/1.1
{
"token": "<token>",
}
**Example response**
.. sourcecode:: http
HTTP/1.1 200 OK
Content-Encoding: gzip
Content-Type: a... | 68,703 |
def getAll(namespaces=None):
"""
Gets all the controls found in the control set with the given namespace.
Args:
namespaces (Iterable): Names of namespace to append as prefix to the control set name.
Returns:
(list): All controls sorted.
"""
if namespaces:
sets = [pm.PyN... | 68,704 |
def get_module_files(src_directory, blacklist):
"""given a package directory return a list of all available python
module's files in the package and its subpackages
:type src_directory: str
:param src_directory:
path of the directory corresponding to the package
:type blacklist: list or tupl... | 68,705 |
def build_tag_push():
"""Build, Tag, & Push all services to your docker registry."""
click.echo(subprocess.getoutput('honcho run python bin/build-tag-push.py')) | 68,706 |
def create_grouped_word_list(words, group_span_indices, join_string):
"""Group together words with join_string string and return updated token list."""
adjusted_words = []
curr_group = []
group_idx = 0
curr_group_start_idx, curr_group_end_idx = group_span_indices[group_idx]
for i, token in enume... | 68,707 |
def get_next_object(table, remote_id, provider_id):
"""Check if object already exists in NEXT and return it."""
query_filter = {"remote_id": remote_id}
if table == "user_mapping":
query_filter["provider_id"] = provider_id
conn = connect_to_db()
result = r.table(table).filter(query_filter).co... | 68,708 |
def clean_data(df):
"""
Input:
df: Dataframe containing messages and respective categories. [dataframe]
Output:
df: Dataframe containing cleaned messages and categories. [dataframe]
Description:
Cleans dataframe with removing unneccesary columns, duplicates and text artifacts.
"""
... | 68,709 |
def connects_to_emergency_number(number, region_code):
"""Returns whether the number might be used to connect to an emergency
service in the given region.
This function takes into account cases where the number might contain
formatting, or might have additional digits appended (when it is okay to
d... | 68,710 |
def split_on(delimiter, text):
"""Split text based on a delimiter."""
return filter(None, map(strip, text.split(delimiter))) | 68,711 |
def evtparse():
"""Function to collect event logs"""
print("\n[+] Parsing key events from APP, SEC, SYS, & PowerShell event logs\n", flush=True)
si_dir = os.path.realpath('.') + "\\sysinternals\\"
si_psloglist_app_evt_list = "1022,1033,1034,11707,11708,11724"
si_psloglist_sec_evt_list = "1102,4624,4... | 68,712 |
def notify(recipient_email: str, notification_type: NotificationType, payload=None):
"""Sends a notification to the specified user."""
notification_group = type_to_group[notification_type]
channel = db.session.query(
# pylint: disable=unsubscriptable-object
Account.notification_settings[noti... | 68,713 |
def format_time_input(time_in, return_seconds=False,
return_milliseconds=False):
"""Format timestamp as seconds/milliseconds for use in REST requests.
:param time_in: timestamp -- int/float
:param return_seconds: return time in seconds -- bool
:param return_milliseconds: ret... | 68,714 |
def fetch_consumption(
zone_key=ZONE_KEY, session=None, target_datetime=None, logger=None
) -> dict:
"""Fetch Chhattisgarh consumption"""
if target_datetime:
raise NotImplementedError("This parser is not yet able to parse past dates")
zonekey.assert_zone_key(zone_key, ZONE_KEY)
html = web.... | 68,715 |
def is_not_instance_of_type(param: T, typeof: Any, param_name: str = None, message=None):
"""
Guards the specified :param param type from being different from the :param typeof by throwing an
exception of type ArgumentNotInstanceOfException with a specific :param message when the precondition
has not be... | 68,716 |
def extract_stops(route_data):
"""
Extracts a dataframe of stops info
Returns the main stops dataframe, and a list of inbound and outbound stops
in the order they are intended to be on the route
"""
stops = pd.DataFrame(route_data['stop'])
directions = pd.DataFrame(route_data['direction'])... | 68,717 |
def uu_get_industry():
"""
查询股票所属行业
:param :security:标的代码,类型为字符串,形式如"000001.XSHE";或为包含标的代码字符串的列表,形如["000001.XSHE", "000002.XSHE"]
date:查询的日期。类型为字符串,形如"2018-06-01"或"2018-06-01 09:00:00";或为datetime.datetime对象和datetime.date。注意传入对象的时分秒将被忽略。
:rtype :dict
:return:
"""
return get_indust... | 68,718 |
async def test_available_tones_dict(hass):
"""Test that valid tones from available_tones dict will get passed in."""
siren = MockSirenEntity(SirenEntityFeature.TONES, {1: "a", 2: "b"})
siren.hass = hass
assert process_turn_on_params(siren, {"tone": "a"}) == {"tone": 1}
assert process_turn_on_params(... | 68,719 |
def test_dependencies_detection_free_variable(dummy_nb_config):
"""Test dependencies detection with free variables."""
pipeline = Pipeline(dummy_nb_config)
_source = ['''
x = 5
''']
pipeline.add_step(Step(name="step1", source=_source))
_source = ['''
def foo():
print(x)
''']
pipeline.add_st... | 68,720 |
def computePhasesCOMValues(cs,DEFAULT_HEIGHT, overwrite = False):
"""
Generate c, dc and ddc initial and final values for the contactSequence if not provided or if overwrite = True
With null dc and ddc and c position in the center of the support polygone for each phase
:param cs: the contact sequence
... | 68,721 |
def Z_theta(theta:float, unit='deg'):
"""
PTM of rotation of theta degrees along the X axis
"""
if unit=='deg':
theta = np.deg2rad(theta)
Z = np.array([[1, 0, 0, 0],
[0, np.cos(theta), -np.sin(theta), 0],
[0, np.sin(theta), np.cos(theta), 0],
... | 68,722 |
def test_list():
""" Test list functions """
print('List all items:')
print(fob.list_items(limit=0))
print('Limit=3:')
print(fob.list_items(limit=3))
print("Prefix='BBB':")
print(fob.list_items(prefix='BBB', limit=TESTLIMIT))
print("Suffix='.bin':")
print(fob.list_items(suffix='.... | 68,723 |
def configs(ctx, list_, generate_config, kind):
"""Manage configuration values and files."""
if list_:
conf_str = yaml.dump(unmunchify(ctx.obj.CONFIG), default_flow_style=False)
echo(conf_str)
exit(0)
factory_resets = FACTORY_RESETS
default_files = {"all": factory_resets.glob('*... | 68,724 |
def test_non_unicode_slash_u():
""" Ensure \ u doesn't cause a unicode decode error """
fd = open(TEMP_FILE_PATH, 'wb')
fd.write('"""Example: C:\\foobar\\unit-tests\\test.py"""'.encode('ascii'))
fd.close()
d = run_frosted([TEMP_FILE_PATH])
assert d == ('', '', 0) | 68,725 |
def str_2_vec(str):
"""
Convert vector of integers to string.
:param str: string
:return: [int, int, int, ...]
"""
return [ord(i) for i in str] | 68,726 |
def db_connection(host, user, dbname, charset = "utf8mb4"):
"""
Connect to a MySQL Database Server
"""
key = pwdutil.get_key()
encoded = pwdutil.get_pwd()
password = pwdutil.decode(key,encoded)
connection = pymysql.connect(host = host
, user = user
... | 68,727 |
def cli_certify_complex_dict(
config, schema, key_certifier, value_certifier, allow_extra,
include_collections, value,
):
"""Console script for certify_dict."""
schema = load_json_pickle(schema, config)
key_certifier = create_certifier(load_json_pickle(key_certifier, config))
value_certifier = c... | 68,728 |
def locate_libpython_2(python_version: str):
"""Get path to the python library associated with the current python
interpreter."""
# https://stackoverflow.com/questions/47423246/get-pythons-lib-path
import itertools
from distutils import sysconfig
# determine direct path to libpython
python_... | 68,729 |
def getAttributes(obj):
"""Get non hidden and built-in type object attributes that can be persisted"""
d={}
allowed = [str,int,float,list,tuple,bool]
for key in obj.__dict__:
if key.startswith('_'):
continue
item = obj.__dict__[key]
if type(item) in allowed:
... | 68,730 |
def norm_except(param, dim, power):
"""Computes the norm over all dimensions except dim.
It differs from pytorch implementation that it does not keep dim.
This difference is related with the broadcast mechanism in paddle.
Read elementeise_mul for more.
"""
shape = param.shape
ndim = len(shap... | 68,731 |
def file_hasher(file_path: Path, hash_method: str) -> FileHash:
"""
Convenience method to hash a file path.
Parameters
----------
file_path : Path
The `pathlib.Path` to a file.
hash_method : {'blake2b','blake2s','md5','sha1','sha224','sha256','sha384','sha512','sha3_224','sha3_256',... | 68,732 |
def unconfigure_ipv6_object_group_network(
device,
og_name
):
""" unconfigure ipv6 object-group network
Args:
device (`obj`): Device object
og_name ('str'): object-group name
Returns:
None
Raises:
SubCommandFailure
"""
... | 68,733 |
def test_setext_headings_extra_c1():
"""
Test case extra c1: SetExt with collapsed image label text split over 2 lines
"""
# Arrange
source_markdown = """a![li
nk][]a
---
[li\nnk]: /url 'title'"""
expected_tokens = [
"[setext(3,1):-:3::(1,1)]",
"[text(1,1):a:]",
"[imag... | 68,734 |
def ClusterRemoveNodes(node_ips,
by_node,
remove_drives,
mvip,
username,
password):
"""
Remove nodes from the cluster
Args:
node_ips: the MIPs of the active nodes to remove
... | 68,735 |
def get_network_detach_config_spec(client_factory, device, port_index):
"""Builds the vif detach config spec."""
config_spec = client_factory.create('ns0:VirtualMachineConfigSpec')
virtual_device_config = client_factory.create(
'ns0:VirtualDeviceConfigSpec')
virtual_device_co... | 68,736 |
def details(ui, layout, pool):
"""
Display details on an individual selected pool.
:Args:
- ui (blender :class:`.Interface`): The instance of the Interface
panel class.
- layout (blender :class:`bpy.types.UILayout`): The layout object,
derived from the Interface pane... | 68,737 |
def sec_title(default_str: str) -> str:
"""Reads in a section title"""
name = input('What would you like to title this section? '
+ '(default is ' + default_str + ')\n')
if name:
return name
return default_str | 68,738 |
def _binary(ctx, srcs, tags, substitutions):
"""Shared implementation for the “elisp_binary” and “elisp_test” rules.
The rule should define a “_template” attribute containing the C++ template
file to be expanded.
Args:
ctx: rule context
srcs: list of File objects denoting the source files ... | 68,739 |
def e_timeToString(dateString):
"""
input: string
output: string
description: format dateString to yyyymmddHHMM
example: Wed Aug 29 07:23:03 CST 2018 ->> 201808290723
"""
# define month list for get digital
month = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep",
... | 68,740 |
def bayesdb_variable_number(bdb, population_id, generator_id, name):
"""Return the column number of a population variable."""
cursor = bdb.sql_execute('''
SELECT colno FROM bayesdb_variable
WHERE population_id = ?
AND (generator_id IS NULL OR generator_id = ?)
... | 68,741 |
def test_invalid_config_16():
"""Invalid schema column configuration: Wait for table requires create_table and delete_table to be False."""
_logger.debug(stack()[0][3])
config = deepcopy(_CONFIG)
config['data_files'] = ['invalid']
try:
raw_table(config)
except ValueError as e:
as... | 68,742 |
def continue_mof():
"""
Update ASE Atoms object after failed job
Returns:
mof (ASE Atoms object): reset ASE Atoms object
"""
try:
mof = read('CONTCAR')
mof = continue_failed_magmoms(mof)
except:
mof = reset_mof()
return mof | 68,743 |
def tachycardic_detector(patient_age, patient_heart_rate):
"""
Determines if patient is tachycardic based on their age and heart rate
Args:
patient_age: integer extracted from patient database entry
patient_heart_rate: integer posted to patient database entry
Returns:
tach... | 68,744 |
def sync(infile, outfile):
"""
Sync (download) latest policies from the Anchore.io service.
"""
ecode = 0
try:
rc, ret = anchore_policy.sync_policymeta(bundlefile=infile, outfile=outfile)
if not rc:
anchore_print_err(ret['text'])
ecode = 1
elif outfi... | 68,745 |
def bond_repo_zh_tick(code="sz131802", trade_date="20201028"):
"""
成交明细-每个交易日16:00提供当日数据
http://stockhtm.finance.qq.com/sstock/ggcx/131802.shtml
:param code: 带市场标识的债券-质押式回购代码
:type code: str
:param trade_date: 需要提取数据的日期
:type trade_date: str
:return: 返回指定交易日债券-质押式回购成交明细的数据
:rtype: pa... | 68,746 |
def _put_default_list(list_data: List[Any]) -> None:
"""Helper function to replace RuntimeParameter with its default value."""
for index, item in enumerate(list_data):
if isinstance(item, dict):
_put_default_dict(item)
elif isinstance(item, list):
_put_default_list(item)
elif item.__class__.... | 68,747 |
def test_suite(name, tests = [], tags = []):
"""Constructs a test suite for a list of unittests.
"""
native.test_suite(
name = name,
tests = tests,
tags = tags,
) | 68,748 |
def linear_bn_lrelu_dropout_block(in_feat, out_feat, normalize=True, alpha=0.2, p=0.5):
""" linear + batchnorm + leaky relu """
layers = [nn.Linear(in_feat, out_feat)]
if normalize:
layers.append(nn.BatchNorm1d(out_feat))
layers.append(nn.LeakyReLU(alpha, inplace=True))
layers.append(nn.Drop... | 68,749 |
def detect_style(docstr):
"""Detect docstr style from existing docstring
Parameters:
docstr (str): docstring whose style we want to know
Returns:
class: one of [GoogleDocstring, NumpyDocstring, None]; None
means no match
"""
docstr = dedent_docstr(docstr)
for c in ... | 68,750 |
def worker2(num):
"""thread worker function"""
print 'Worker: %s' % num
return | 68,751 |
async def prepare_mail(client: Facade, recipient: Portfolio) -> Mail:
"""Generate one mail to recipient using a facade saving the mail to the outbox."""
message = CreateMail().perform(client.data.portfolio, recipient).message(
Generate.lipsum_sentence(), Generate.lipsum(100).decode()).done()
envelop... | 68,752 |
def questions(difficulty):
"""This function branches to the desired difficulty"""
if difficulty == "easy":
ask(4) # the number passed is the number of questions that will be asked
elif difficulty == "medium":
ask(6)
else: # means hard difficulty
ask(8)
return | 68,753 |
def check_pkgs():
"""."""
global arduino_info
is_changed = False
arduino_dir_path = arduino_info['arduino_app_path']
for key in arduino_info['package_index'].get_keys():
url = arduino_info['package_index'].get(key)
remote_etag = downloader.get_remote_etag(url)
if remote_etag:... | 68,754 |
def resolve_doi(rec):
"""Resolve the doi of a given record"""
doi = _get_doi(rec)
if doi is not None:
res = None
try:
res = urlopen(DOI_ORG + doi)
except HTTPError as e:
res = e
return res.url | 68,755 |
def parse_args():
"""
parsing and configuration
:return: parse_args
"""
desc = "TensorFlow implementation of fast-style-GAN"
parser = argparse.ArgumentParser(description=desc)
parser.add_argument('--module', type=str, default='test',
help='Module to select: ... | 68,756 |
def reject():
""" Reject the Tic-Tac-Toe Challenge """
global currentGame, resp, slackResponse, message, srb
status = None
obj = {"response_type": "ephemeral"}
challenger = None
opponent = None
if slackResponse is not None:
challenger = "@"+slackResponse['user_name']
oppon... | 68,757 |
def make_string(seq):
"""
Don't throw an exception when given an out of range character.
"""
string = ''
for c in seq:
# Screen out non-printing characters
try:
if 32 <= c and c < 256:
string += chr(c)
except TypeError:
pass
# I... | 68,758 |
def subvolume_garbage_collector(argv):
"""
IMPORTANT:
- Multiple copies of this function can run concurrently, subject to the
KEY ASSUMPTIONS in the file's docblock.
- The garbage-collection pass must be robust against failures in the
middle of the code (imagine somebody hitting Ctrl-C... | 68,759 |
def cmis_env(request):
"""Initialize a cmis environement with
* CmisClient
* repo
* rootFolder
* test folder name
* test folder
All these attributes are reset after each test method
"""
cmis_conf(request)
param = request.param
request.cls._cmisClient = CmisClient(
par... | 68,760 |
def verify_params(
handler: Any, request: HttpRequest, may_path_params: Dict[str, Any]
) -> Dict[str, Any]:
"""
Verify the parameters, and convert the parameters to the corresponding type.
"""
if is_class_view(handler):
return _verify_params(
getattr(
handler.view... | 68,761 |
def get_short_name_for_type(instance):
"""
<class 'datatypes.strings.Smiles'> to smiles
:return: short name
"""
try:
return (re.search('\w+\'', str(instance)).group(0)[:-1].lower())
except:
return None | 68,762 |
def _CalcOrderedCorners(orig, inc, size, gpiline, gpxline, gpx, gpy):
"""
Convert three arbitrary control points to 4 ordered corner points ordered
first il, first xl; last il, first xl, first il, last xl, last il, last xl.
Also return the same 4 corners in annotation- and ordinal coordinates.
The l... | 68,763 |
def save_to_pkl(pkl, obj):
"""Save experiment resource to file."""
with open(pkl, 'wb') as f:
pickle.dump(obj, f)
return obj | 68,764 |
def beta_reposync(runtime, output, cachedir, arch, repo_type, names, dry_run):
"""Sync yum repos listed in group.yaml to local directory.
See `doozer --help` for more.
Examples:
Perform reposync operation for ppc64le architecture, preferring unsigned repos:
$ doozer --group=openshift-4.0 beta... | 68,765 |
def _from_json(dct):
"""convert string keys back to tuples"""
if not isinstance(dct, dict): return dct
for key in dct:
break
if isinstance(key, str) and key.startswith('('):
return {_str2inttuple(key): dct[key] for key in dct}
return dct | 68,766 |
def pen(turtle, pen=None):
"""Return or set the pen's attributes.
Arguments:
turtle -- the turtle
pen -- a dictionary with some or all of the below listed keys.
**pendict -- one or more keyword-arguments with the below
listed keys as keywords.
... | 68,767 |
def upsample(cam, im_hw):
""" Upsamples CAM to appropriate size
Params:
- cam: a x_x_ tf.Tensor
- im_hw: target size in [H, W] format
Returns:
- Upsampled CAM with size _xHxW
"""
'''TODO: upsampling function call. Hint: look at resize functions in tf.image'''
... | 68,768 |
def get_temp_exposure(fname):
"""Given a filename of a phenocam image
Returns the temperature and exposure extracted from the image.
"""
title, temperature_line, exposure_line = _get_lines(fname)
binary_temperature = _get_binary(temperature_line)
temp_str = _extract_digits(binary_temperatu... | 68,769 |
def test_API_doc():
"""Should work as expected."""
app = proxy.API(name="test")
@app.route("/test", methods=["POST"])
def _post(body: str) -> Tuple[str, str, str]:
"""Return something."""
return ("OK", "text/plain", "Yo")
@app.route("/<user>", methods=["GET"], tag=["users"], descri... | 68,770 |
def get_scores():
"""Cacluates the BLEU and ROUGE scores for the configurations selected."""
opt = Opt.get_instance()
read_in_jsons()
mkdir()
preprocess_json()
write_source_and_target()
perfect_trans_summary()
if opt.proper_method:
model = load_translator()
opt.k = 10
... | 68,771 |
def gelu_fast(x):
""" Faster approximate form of GELU activation function
"""
return 0.5 * x * (1.0 + torch.tanh(x * 0.7978845608 * (1.0 + 0.044715 * x * x))) | 68,772 |
def get_pr_from_gh(pr_name, all_prs):
"""try to obtain existing open PR with name in GH"""
prs = [
pr for pr in all_prs
if pr_name in pr.title
]
if len(prs) > 1:
print(f'Warning: Too many PRs matched query "{pr_name}": {[p.html_url for p in prs]}. Returning first.')
retur... | 68,773 |
def handle_after_execution(
context: ExecutionContext, event: events.AfterExecution, warnings: FrozenSet[str]
) -> None:
"""Display the execution result + current progress at the same line with the method / endpoint names."""
context.endpoints_processed += 1
context.results.append(event.result)
disp... | 68,774 |
def _validate_relation_by_interface_and_direction(
charm: CharmBase,
relation_name: str,
expected_relation_interface: str,
expected_relation_role: RelationRole,
):
"""Verifies that a relation has the necessary characteristics.
Verifies that the `relation_name` provided: (1) exists in metadata.y... | 68,775 |
def get_status_before_execution(exclude_labels=None):
"""
Set the environment status and assign it into ENV_STATUS_PRE dictionary
Args:
exclude_labels (list): App labels to ignore leftovers
"""
get_environment_status(ENV_STATUS_PRE, exclude_labels=exclude_labels) | 68,776 |
def mme_matches(case_obj, institute_obj, mme_base_url, mme_token):
"""Show Matchmaker submission data for a sample and eventual matches.
Args:
case_obj(dict): a scout case object
institute_obj(dict): an institute object
mme_base_url(str) base url of the MME server
mme_token(str)... | 68,777 |
def test_d3_3_9v01_d3_3_9v01ci(mode, save_output, output_format):
"""
1a: chameleon include on unqualified names in XPath expressions 1b: A
calendar day with a very early timezone may be completely disjoint
from a calendar day with a very late timezone. 1c: A time in a
timezone may convert to a UTC ... | 68,778 |
def size(archiveentry_handle, p5_connection=None):
"""
Syntax: ArchiveEntry <handle> size
Description: Returns the list of sizes in bytes for each instance of the
given archive entry.
Return Values:
-On Success: the list of file sizes
"""
method_name = "size"
return exec_nsdchat([... | 68,779 |
def run_tntblast(nproc,
fwd_list,
rev_list,
output_name,
database_name,
min_tm,
max_tm,
primer_conc,
mv_conc,
dntp_conc = 0.8,
dv_conc = 1.5,
... | 68,780 |
def projects(request):
"""Display projects."""
return {} | 68,781 |
def manage_github_orgs_add(request):
"""
Add an organization slot if the plan allows
"""
# # Redir https
# if request.headers.get('X-Forwarded-Proto') is not None:
# if request.headers['X-Forwarded-Proto'] != 'https':
# return HTTPMovedPermanently(location="https://%s%s" % (
# ... | 68,782 |
def test_main(monkeypatch, fail_case: bool) -> None:
"""Check -m command."""
full_main_fpath: str = str(helpers.ROOT_PATH.joinpath("__main__.py"))
monkeypatch.setattr(
"sys.argv",
[
full_main_fpath,
"non_existen.HAHAHA.LOL.bin" if fail_case else str(helpers.DATA_PATH.... | 68,783 |
def test_FastqParser():
"""
Write your unit test for your FastqParser
class here. You should generate an instance of
your FastqParser class and assert that it properly
reads in the example Fastq File.
"""
FastqParser_instance = FastqParser("data/test.fq")
for record in FastqParser_instan... | 68,784 |
def get_args():
""" function to parse command line arguments
Returns:
_type_: parsed arguments
"""
parser = argparse.ArgumentParser()
model_group = parser.add_mutually_exclusive_group(required=True)
model_group.add_argument("--ckpt-path", type=str, default="", help="Checkpoint path.")
... | 68,785 |
def an(state, i, s, N):
"""Application of c_i,s on a given state (a linear superposition of |m>). Spin should be 0 for up and 1 for down."""
new_state = {}
for basis_state in state:
prefactor_an, state_an = fmulti_an(basis_state, i, s, N)
if state_an != None:
try:
new_state[state_an] += prefactor_an * ... | 68,786 |
def worker_function(event_type, assignment_id, participant_id):
"""Process the notification."""
db.logger.debug("rq: worker_function working on job id: %s",
get_current_job().id)
db.logger.debug('rq: Received Queue Length: %d (%s)', len(q),
', '.join(q.job_ids))
... | 68,787 |
def load_data(database_filepath):
""" Load the CLEAN_MESSAGES table from the given SQLite Database """
# load data from database
engine = create_engine('sqlite:///' + database_filepath)
df = pd.read_sql_table("CLEAN_MESSAGES", engine)
X = df['message']
Y = df.iloc[:,4:]
return X, Y, Y.colu... | 68,788 |
def create_client(config, logger: Logger):
"""Generates an athena client object
Args:
config ([type]): [description]
logger (Logger): [description]
Returns:
cursor: athena client object
"""
logger.info("Attempting to create Athena session")
# Get the required paramete... | 68,789 |
def load_library(lib_location: Optional[str] = None):
"""Loads the `snap7.dll` library.
Returns:
cdll: a ctypes cdll object with the snap7 shared library loaded.
"""
return Snap7Library(lib_location).cdll | 68,790 |
def _interval_index(intervals: List[Interval], interval: Interval) -> int:
"""Find the index of an interval.
Args:
intervals: A sorted list of non-overlapping Intervals.
interval: The interval for which the index into intervals will be found.
Returns:
The index of the interval.
... | 68,791 |
def diff_field(field1, field2):
"""returns true if field1 == field2"""
return field1 == field2 | 68,792 |
def up(ctx, restart):
"""Start AiiDAlab on this host."""
# Check for an '.env' file. The file can be automatically created via the
# `configure` command.
msg_warn_up_without_env_file = "\n".join(
wrap(
"Warning: Did not find an '.env' file in the current working directory. It "
... | 68,793 |
def block_layer(inputs, filters, bottleneck, block_fn, blocks, strides,
training, name, data_format):
"""Creates one layer of blocks for the ResNet model.
Args:
inputs: A tensor of size [batch, channels, height_in, width_in] or [batch,
height_in, width_in, channels] depending on data_form... | 68,794 |
def unlock(password):
"""Unlock vault
Returns: session (bytes) or False on error, Error message
"""
res = run(["bw", "unlock", "--raw", password], capture_output=True, check=False)
if not res.stdout:
logging.error(res)
return (False, res.stderr)
return res.stdout, None | 68,795 |
def update_latency(
*,
ms: float,
timestamp: int = None,
metric: str = METRIC_LATENCY,
key: str = API_KEY,
):
"""
Updates the latency-metric on StatusPage.io.
Parameters
----------
ms: float
The latency in ms.
timestamp:
The timestamp for the latency.
met... | 68,796 |
def test_class_instance_variables() -> None:
"""Class and instance variables."""
fido = Dog("Fido")
dido = Dog("Dido")
fido.add_shared_trick("roll over")
dido.add_shared_trick("play dead")
assert fido.shared_tricks == dido.shared_tricks == ["roll over", "play dead"]
fido.add_trick("roll ov... | 68,797 |
def example_classifier(
task_info,
mode="demo",
default_split_prob={
"train": 0.9,
"dev": 0.01,
"test": 0.09,
},
):
"""
This will return the split this data belongs to.
"""
if mode == "demo" or mode == "all":
if random.random() < default_split_prob["train... | 68,798 |
def login():
"""Prompt the user to log in via SAML"""
pass | 68,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.