content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def show_set(data_set):
"""
显示集合数据
:param data_set: 数据集
:return: None
"""
data_list = list(data_set)
show_string(data_list) | 15,900 |
def get_high_accuracy_voronoi_nodes(structure, rad_dict, probe_rad=0.1):
"""
Analyze the void space in the input structure using high accuracy
voronoi decomposition.
Calls Zeo++ for Voronoi decomposition.
Args:
structure: pymatgen.core.structure.Structure
rad_dict (optional): Dictio... | 15,901 |
def setUpBlobDetector():
"""
Configure parameters for a cv2 blob detector, and returns the detector.
"""
params = cv2.SimpleBlobDetector_Params()
params.minThreshold = 0
params.maxThreshold = 255
params.filterByArea = True
params.minArea = 1500
params.maxArea = 25000
params.f... | 15,902 |
def upload_image(picBase64, album, name, title, description, access_token):
"""
POST. Needs auth token. Basic Response.
Uploads all images in given directory to specific album ID
"""
url = 'https://api.imgur.com/3/image'
request = urllib2.Request(url, headers={'Authorization' : 'Bearer {}... | 15,903 |
def raise_keymap():
"""
! @ # $ % || ^ & * ( )
DEL ESC || PGDN PGUP PSCR
CAPS volup ENT reset || UP
voldn super shift space bspc|| alt ent LEFT DOWN RGHT
"""
lef... | 15,904 |
def runetl(config, log):
""" run etl """
log.info('run ETL')
genres = import_otrgenres(config, log)
""" loop back for 10 days and import"""
iterdate = datetime.now().date() - timedelta(days=10)
startdate = datetime.now().date() - timedelta(days=8)
enddate = datetime.now().date()
whil... | 15,905 |
def sample_cmd() -> Command:
"""Useful for testing constraints against a variety of parameter kinds.
Parameters have names that should make easy to remember their "kind"
without the need for looking up this code."""
@cloup.command()
# Optional arguments
@click.argument('arg1', required=False)
... | 15,906 |
def get_linenos(obj):
"""Get an object’s line numbers in its source code file"""
try:
lines, start = inspect.getsourcelines(obj)
except TypeError: # obj is an attribute or None
return None, None
except OSError: # obj listing cannot be found
# This happens for methods that are n... | 15,907 |
def enter_user_trigger_critical_section(user_id):
"""Set semaphore noting users trigger state is actively being processed
A number of asynchronous tasks are involved in processing a users results
and determining their trigger state. This endpoint is used to set the
semaphore used by other parts of the... | 15,908 |
def create_solution_board(width=6, height=6):
"""Randomly generates a new board
with width by height size
"""
if type(width) != int or type(height) != int:
raise TypeError('Arguments must be int type')
boxes = width * height
if boxes % 2 != 0:
raise ValueError('Number of boxes ... | 15,909 |
def _getE(s,R,W,V = None):
"""The sum of the energies for the states present in the solution.
Args:
s (list of int): The number of samples points along each
basis vector.
R (numpy.ndarray): The basis vectors for the unit cell.
W (numpy.ndarray): A matrix containing the expans... | 15,910 |
def get_gt_list(request):
""" This view returns the list of groundtruths associated to a user and a specific configuration of institute,
usecase and language.
.js files: InfoAboutConfiguration.js DownloadGT.js"""
groundTruths = 0
json_resp = {}
ins = request.GET.get('inst',None)
lang = re... | 15,911 |
def to_dict(item: Any) -> MutableMapping[Hashable, Any]:
"""Converts 'item' to a MutableMapping.
Args:
item (Any): item to convert to a MutableMapping.
Raises:
TypeError: if 'item' is a type that is not registered.
Returns:
MutableMapping: derived from 'item'.
"""
... | 15,912 |
def node(*args, **kwargs):
"""
args[0] -- a XML tag
args[1:] -- an array of children to append to the newly created node
or if a unicode arg is supplied it will be used to make a text node
kwargs -- attributes
returns a xml.dom.minidom.Element
"""
blocked_attributes = ['tag']
... | 15,913 |
def get_volume_uuid(path: str) -> str:
"""Returns the volume UUID for the given path or None if not found"""
try:
output = subprocess.check_output(["diskutil", "info", "-plist", path])
plist = plistlib.loads(output)
return plist.get("VolumeUUID", None)
except subprocess.CalledProcess... | 15,914 |
def prob_calibration_1d(Y_obs, Y_sample, title="", save_addr="", fontsize=12):
"""Plots the reliability diagram (i.e. CDF for F^{-1}(y) ) for 1D prediction.
Args:
Y_obs: (np.ndarray of float32) N observations of dim (N, 1)
Y_sample: (np.ndarray of float32) Samples of size M corresponding
... | 15,915 |
def test_reveal_extra_to_args():
"""
Test `reveal_extra_to_args()` function.
"""
text_config = """
reveal_extra:
key0: value0
key1: value1
"""
config = yaml.safe_load(text_config)
args = reveal_extra_to_args(config)
assert len(args) == 4
assert args[::2] == ['-V', '-V']
asser... | 15,916 |
def smart_open(filename=None, fmode=None):
"""Context manager to handle both stdout & files in the same manner.
:param filename: Filename to open.
:type filename: ``str`` or ``None``
:param fmode: Mode in which to open a given file.
:type fmode: ``str`` or ``None``
"""
if filename and filen... | 15,917 |
def test_omit_default_roundtrip(cl_and_vals):
"""
Omit default on the converter works.
"""
converter = Converter(omit_if_default=True)
cl, vals = cl_and_vals
@attr.s
class C(object):
a: int = attr.ib(default=1)
b: cl = attr.ib(factory=lambda: cl(*vals))
inst = C()
u... | 15,918 |
def test_all():
"""
测试测试模块下所有的测试脚本
:return:
"""
suite = unittest.TestSuite()
all_cases = unittest.defaultTestLoader.discover('.', 'test_*.py')
for case in all_cases:
suite.addTests(case)
runner = xmlrunner.XMLTestRunner(output='report')
runner.run(suite) | 15,919 |
def mylog10(x):
"""Return the base-10 logarithm of x."""
return math.log10(x) | 15,920 |
def get_RGB_to_RGB_matrix(in_colorspace, out_colorspace, primaries_only=False):
"""Return RGB to RGB conversion matrix.
Args:
in_colorspace (str): input colorspace.
out_colorspace (str): output colorspace.
Kwargs:
primaries_only (bool): primaries matrix only, doesn't include white ... | 15,921 |
def one_hot_arbitrary_bins(value_to_bin=104):
"""Creates OHE numpy array using an arbitrary array of binning thresholds.
Args:
value_to_bin (int, optional): Number to convert to OHE array. Defaults to 104.
"""
bins = np.array([-10000., -5000., -1000., -500.,
-250., -150., -... | 15,922 |
def test_get_sections(test_dict: FullTestDict):
"""
- GIVEN an html section
- WHEN the subsections are extracted
- THEN check the array of subsections is correct
"""
htmls = test_dict['ojad']['htmls']
parsed_htmls = [Soup(html, "html.parser") for html in htmls]
expected_sections = test_d... | 15,923 |
def normalize_string(s):
"""Lower text and remove punctuation, articles and extra whitespace."""
def remove_articles(text):
regex = re.compile(r'\b(a|an|the)\b', re.UNICODE)
return re.sub(regex, ' ', text)
def white_space_fix(text):
return ' '.join(text.split())
def remove_punc(text):
exclude = ... | 15,924 |
def sub_band_as_numpy(band, y_limits, data_type=None):
"""Read subsets of the dataset so that we don't hold the whole thing
in memory. It seems wasteful to reread parts, but GDAL keeps its own cache.
"""
data_type = data_type if data_type else INT32
y_size = y_limits[1] - y_limits[0]
LOGGER.debu... | 15,925 |
def full_reverse(viewname, urlconf=None, args=None, kwargs=None, current_app=None,
scheme=None, domain=None, subdomain=None):
"""
First, obtains the absolute path of the URL matching given
``viewname`` with its parameters.
Then, prepends the path with the scheme name and the authority
... | 15,926 |
def draw_lrtb_rectangle_filled(left: float, right: float, top: float,
bottom: float, color: Color):
"""
Draw a rectangle by specifying left, right, top, and bottom edges.
Args:
:left: The x coordinate of the left edge of the rectangle.
:right: The x coordinate... | 15,927 |
def test_regexp_on_index_out_of_range():
"""Test regexp when group indeces are out of range."""
regexp = apply_regexp(
'Hard work',
{'search': 'r', 'group': [1, 2, 3]},
)
assert isinstance(regexp.failure(), IndexError) is True
assert regexp.failure().args == ('list index out of range... | 15,928 |
def get_object_or_none(model_class, **kwargs):
"""Identical to get_object_or_404, except instead of returning Http404,
this returns None.
"""
try:
return model_class.objects.get(**kwargs)
except model_class.DoesNotExist:
return None | 15,929 |
def GenerateTests():
"""Generate all tests."""
filelist = []
for ii in range(len(_GROUPS)):
filename = GenerateFilename(_GROUPS[ii])
filelist.append(filename)
WriteTest(filename, ii, ii + 1)
return filelist | 15,930 |
def shift_df_generator(empty_df, day_lower_hr_lim, day_upper_hr_lim):
"""Generate day and night dataframe.
Parameters
----------
empty_df : DataFrame
A DataFrame with timestamp and 'Temperature (Celsius)' with all zeros.
day_lower_hr_lim : int
The lower hour limit that constitutes t... | 15,931 |
def json_loads(data, handle=False):
"""
封装的json load
:param data:
:param handle: 补丁, False: 默认不特殊处理: True: 不走正则
:return:
"""
if handle:
return json.loads(data.strip())
return json.loads(regex.sub(r"\\\\", data.strip())) | 15,932 |
def elina_linexpr0_size(linexpr):
"""
Return the size of an ElinaLinexpr0.
Parameters
----------
linexpr : ElinaLinexpr0Ptr
Pointer to the ElinaLinexpr0 that needs to be checked for its size.
Returns
-------
size_linexpr = c_size_t
Size of the ElinaLinexpr0.
""... | 15,933 |
def app():
"""
Setup our flask test app, this only gets executed once.
:return: Flask app
"""
# params = {"DEBUG": False, "TESTING": True, "WTF_CSRF_ENABLED": False}
_app = create_app("config.settings_test")
# Establish an application context before running the tests.
ctx = _app.app_c... | 15,934 |
def _make_index(df, cols=META_IDX, unique=True):
"""Create an index from the columns/index of a dataframe or series"""
def _get_col(c):
try:
return df.index.get_level_values(c)
except KeyError:
return df[c]
index = list(zip(*[_get_col(col) for col in cols]))
if ... | 15,935 |
def handler(event, context):
""" Lambda Handler.
Returns Hello World and the event and context objects
"""
print(event)
print(context)
return {
"body": json.dumps('Hello World!')
} | 15,936 |
def latex_table(arrays, here=False):
"""Prints the code for a latex table with empty headings,
inserting the data provided into rows.
Args:
arrays: The list of arrays for the table.
here: True if here tag is to be included.
"""
# Define a 4-space tab (latex uses 4 space tabs).
... | 15,937 |
def flatten_concat(tensors: List[tf.Tensor], batch_dims: int = 1) -> tf.Tensor:
"""Flatten given inputs and concatenate them."""
# tensors [(B, ...), (B, ...)]
flattened: List[tf.Tensor] = list() # [(B, X), (B, Y) ...]
for tensor in tensors:
final_dim = -1
if all(i is not None for i in ... | 15,938 |
def test_pos_tag(parser, text, method_name, ptb_pos_tags):
"""Tests that produced POS tags are valid PTB POS tags.
Args:
parser (SpacyBistParser)
text (str): Input test case.
method_name (str): Parse method to test.
ptb_pos_tags (set of str): Valid PTB POS tags.
"""
pars... | 15,939 |
async def test_discovered_by_dhcp_or_homekit(hass, source, data):
"""Test we can setup when discovered from dhcp or homekit."""
mocked_bulb = _mocked_bulb()
with _patch_discovery(), _patch_discovery_interval(), patch(
f"{MODULE_CONFIG_FLOW}.AsyncBulb", return_value=mocked_bulb
):
result... | 15,940 |
def analyze_friends (names,phones,all_areacodes,all_places):
"""
names: tuple of names
phones: tuple of phone numbers (cleaned)
all_areacodes: tuple of area codes (3char ints)
all_places: tuple of places
Goal: Print out how many friends you have and every unique state
"""
# For TES... | 15,941 |
def fast_autoregressive_predict_fn(context, seq_len):
"""Given a context, autoregressively generate the rest of a sine wave."""
core = hk.LSTM(32)
dense = hk.Linear(1)
state = core.initial_state(context.shape[0])
# Unroll over the context using `hk.dynamic_unroll`.
# As before, we `hk.BatchApply... | 15,942 |
def get_entities(corpus_name):
""" Load the dataset from the filesystem corresponding to corpus_name
(to see the list of allowed names, use utils.list_corpora() ), and extract
all annotated entities.
Returns a dict, in which each key is an entity type, which contains a list
of entity mentions in th... | 15,943 |
def _reporthook(t):
"""``reporthook`` to use with ``urllib.request`` that prints the
process of the download.
Uses ``tqdm`` for progress bar.
**Reference:**
https://github.com/tqdm/tqdm
"""
last_b = [0]
def inner(b: int = 1, bsize: int = 1, tsize: int = None):
"""
... | 15,944 |
def serial_rx(sysclk, reset_n, n_stop_bits_i, half_baud_rate_tick_i, baud_rate_tick_i, recieve_i, data_o, ready_o):
""" Serial
This module implements a reciever serial interface
Ports:
-----
sysclk: sysclk input
reset_n: reset input
half_baud_rate_tick_i: half baud rate tick
baud_rate_... | 15,945 |
def zpad(x, l):
""" Left zero pad value `x` at least to length `l`.
>>> zpad('', 1)
'\x00'
>>> zpad('\xca\xfe', 4)
'\x00\x00\xca\xfe'
>>> zpad('\xff', 1)
'\xff'
>>> zpad('\xca\xfe', 2)
'\xca\xfe'
"""
return b'\x00' * max(0, l - len(x)) + x | 15,946 |
def websocket_node_status(hass, connection, msg):
"""Get the status for a Z-Wave node."""
manager = hass.data[DOMAIN][MANAGER]
node = manager.get_instance(msg[OZW_INSTANCE]).get_node(msg[NODE_ID])
if not node:
connection.send_message(
websocket_api.error_message(
msg... | 15,947 |
def clf2D_slope_intercept(coef=None, intercept=None, clf=None):
"""
Gets the slop an intercept for the separating hyperplane of a linear
classifier fit on a two dimensional dataset.
Parameters
----------
coef:
The classification normal vector.
intercept:
The classifier inte... | 15,948 |
def _get_imgpaths(datasets: list, verbose=True):
""" get image paths
Args:
datasets (list): dataset names
verbose (bool, optional): . Defaults to True.
"""
img_paths = []
for dname in datasets:
img_dir = Path(dname.format(DATASETS_DIR=DATASETS_DIR))
assert img_dir.is... | 15,949 |
def build_driver_for_task(task):
"""Builds a composable driver for a given task.
Starts with a `BareDriver` object, and attaches implementations of the
various driver interfaces to it. They come from separate
driver factories and are configurable via the database.
:param task: The task containing ... | 15,950 |
def evaluate(eval_model, criterion, ntokens, data_source, cnf):
"""
Evaluates the training loss of the given model
"""
eval_model.eval() # Turn on the evaluation mode
total_loss = 0.0
src_mask = generate_square_subsequent_mask(cnf.input_length).to(cnf.device)
with torch.no_grad():
f... | 15,951 |
def km_to_meters(kilometers):
"""
(int or float) -> float
Takes a distance in kilometers and returns the distance in meters.
"""
return kilometers * 1000.0 | 15,952 |
def build(plan: List[Step], instances_stock: Optional[Dict[Callable, Any]] = None):
""" Build instances dictionary from a plan """
instances_stock = instances_stock or {}
instances = {}
for cls, kwargs_spec in plan:
if cls in instances_stock:
instances[cls] = instances_stock[cls]
... | 15,953 |
def make_module_spec(options, weight_file):
"""Makes a module spec.
Args:
options: LM hyperparameters.
weight_file: location of the hdf5 file with LM weights.
Returns:
A module spec object used for constructing a TF-Hub module.
"""
def module_fn():
"""Spec function for a ... | 15,954 |
def get_initial_scoreboard():
"""
Retrieve the initial scoreboard (first pages of global and student views).
If a user is logged in, the initial pages will instead be those on which
that user appears, and their group scoreboards will also be returned.
Returns: dict of scoreboard information
""... | 15,955 |
async def resolve(qname, rdtype=dns.rdatatype.A, rdclass=dns.rdataclass.IN,
tcp=False, source=None, raise_on_no_answer=True,
source_port=0, lifetime=None, search=None, backend=None):
"""Query nameservers asynchronously to find the answer to the question.
This is a convenienc... | 15,956 |
def compare_xml(want, got):
"""Tries to do a 'xml-comparison' of want and got. Plain string
comparison doesn't always work because, for example, attribute
ordering should not be important. Comment nodes are not considered in the
comparison.
Based on http://codespeak.net/svn/lxml/trunk/src/lxml/doct... | 15,957 |
def _tf_equal(a, b):
"""Overload of "equal" for Tensors."""
return gen_math_ops.equal(a, b) | 15,958 |
def faq():
"""FAQ page for SciNet"""
return render_template("faq.html") | 15,959 |
def test_produces_fst_analysis_string(na_layout: ParadigmLayout):
"""
It should produce a valid FST analysis string.
"""
lemma = "minôs"
expected_lines = {
# Basic
f"{lemma}+N+A+Sg",
f"{lemma}+N+A+Pl",
f"{lemma}+N+A+Obv",
f"{lemma}+N+A+Loc",
f"{lemma}... | 15,960 |
def test_config_ca_cert_as_file(mock_va, mock_connections, mock_isfile):
"""
Tests that the instantiation of a config.VaultConfig object results in the correct configuration.
"""
sample_config = {
"elastic": {
"user": "elastic_user",
"pwd": "elastic_password",
... | 15,961 |
def requirements(filename, pip_cmd='pip', python_cmd='python', **kwargs):
"""
Require Python packages from a pip `requirements file`_.
.. _requirements file: http://www.pip-installer.org/en/latest/requirements.html
"""
pip(MIN_PIP_VERSION, python_cmd=python_cmd)
install_requirements(filename, p... | 15,962 |
def render_table(sheet, header, width, data, header_style, data_style, tt_id_style):
"""Рендерим страницу"""
# Render table header
for i in range(len(header)):
sheet.write(0, i, header[i], header_style)
sheet.col(i).width = width[i]
sheet.row(1).height = 2500
# Render table data
... | 15,963 |
def texsafe(value):
""" Returns a string with LaTeX special characters stripped/escaped out """
special = [
[ "\\xc5", 'A'], #'\\AA'
[ "\\xf6", 'o'],
[ "&", 'and'], #'\\"{o}'
]
for char in ['\\', '^', '~', '%', "'", '"']: # these mess up things
value = value.replace(char... | 15,964 |
def match_against_host_software_profile(db_session, hostname, software_packages):
"""
Given a software package list, return an array of dictionaries indicating if the
software package matches any software package defined in the host software profile package list.
"""
results = []
system_option =... | 15,965 |
def get_inputs_by_op(op: Op, store: Mapping[str, Any], copy_on_write: bool = False) -> Any:
"""Retrieve the necessary input data from the data dictionary in order to run an `op`.
Args:
op: The op to run.
store: The system's data dictionary to draw inputs out of.
copy_on_write: Whether t... | 15,966 |
def test_warn_bad_formatting(eo_validator: ValidateRunner, example_metadata: Dict):
"""A warning if fields aren't formatted in standard manner."""
example_metadata["properties"]["eo:platform"] = example_metadata["properties"][
"eo:platform"
].upper()
eo_validator.warnings_are_errors = True
e... | 15,967 |
def cleanup_gcp_instances(neo4j_session, common_job_parameters):
"""
Delete out-of-date GCP instance nodes and relationships
:param neo4j_session: The Neo4j session
:param common_job_parameters: dict of other job parameters to pass to Neo4j
:return: Nothing
"""
run_cleanup_job('gcp_compute_i... | 15,968 |
def finalize_post(func, store: Type['ParameterStore']):
"""Finalizes the store prior to executing the function
Parameters
----------
func : callable
The function to wrap.
store : ParameterStore
The parameter store to finalize.
Returns
-------
callable
The wrappe... | 15,969 |
def searchaftertext(filename, startterm, searchterm):
"""Start search after a certain text in a file"""
#print startterm
#print searchterm
startline = findLastString (filename, startterm)
searchtermfound = findLastString (filename, searchterm)
if searchtermfound > startline:
return True
... | 15,970 |
def ilcd_flow_generator(archive=ELCD, **kwargs):
"""
This generates flows from the current reference ELCD archive.
:param archive:
:param kwargs:
:return:
"""
i = IlcdLcia(archive, **kwargs)
count = 0
for f in i.list_objects('Flow'):
o = i.objectify(f, dtype='Flow')
i... | 15,971 |
def export_mobilenetv2():
""" export_mobilenetv2 """
print('\nconfig: \n', config)
if not config.device_id:
config.device_id = get_device_id()
context_device_init(config)
_, _, net = define_net(config, config.is_training)
load_ckpt(net, config.ckpt_file)
input_shp = [config.batch_si... | 15,972 |
def process_new_table(args, syn):
"""
Function: process_new_table
Purpose: Create an annotations table with the specified name under the
specified Synapse parent ID using the specified JSON schema. This
function is called when the "new_table" option is specified when
... | 15,973 |
def vec_list_to_tensor(vec_list):
"""Convert list to vector tensor."""
return jnp.stack(vec_list, axis=-1) | 15,974 |
def to_ecma_datetime_string(dt, default_timezone=local):
"""
Convert a python datetime into the string format defined by ECMA-262.
See ECMA international standard: ECMA-262 section 15.9.1.15
``assume_local_time`` if true will assume the date time is in local time if the object is a naive date time obj... | 15,975 |
def WmiAddClassQualifiers(grph, conn_wmi, wmi_class_node, class_name, with_props):
"""This adds information to a WMI class."""
try:
# No need to print this, at the moment.
if False:
klass_descr = str(dir(getattr(conn_wmi, class_name)))
grph.add((wmi_class_node, lib_common... | 15,976 |
def _logfile_readme() -> str:
"""Returns a string containing a 'how to read this logfile' message.
Returns
-------
str
Returns a formatted paragraph-long message with tips on reading log file output.
"""
line1 = "Messages are displayed below in the format"
line2 = " <DATE> <TIME>... | 15,977 |
def taxon_lookup(es, body, index, taxonomy_index_template, opts, return_type):
"""Query elasticsearch for a taxon."""
taxa = []
with tolog.DisableLogger():
res = es.search_template(body=body, index=index, rest_total_hits_as_int=True)
if "hits" in res and res["hits"]["total"] > 0:
if retu... | 15,978 |
async def get_south_services(request):
"""
Args:
request:
Returns:
list of all south services with tracked assets and readings count
:Example:
curl -X GET http://localhost:8081/fledge/south
"""
if 'cached' in request.query and request.query['cached'].lower() == ... | 15,979 |
def polySpinEdge(*args, **kwargs):
"""
Flags:
- caching : cch (bool) []
- constructionHistory : ch (bool) []
- frozen : fzn (bool) []
- name : n (unicode) []
- nodeSt... | 15,980 |
def filter_bam_file(bamfile, chromosome, outfile):
"""
filter_bam_file uses samtools to read a <bamfile> and read only
the reads that are mapped to <chromosome>.
It saves the filtered reads into <outfile>.
"""
inputs = [bamfile]
outputs = [outfile]
options = {
'cores': 1,
... | 15,981 |
def import_teachers():
"""
Import the teachers from Moodle.
:return: Amount of imported users.
:rtype: int
"""
course_list = dict(Course.objects.values_list("courseId", "pk"))
teachers_list = parse_get_teachers(get_teachers(list(course_list.keys())))
teacher_group = create_auth_group()
... | 15,982 |
def baryvel(dje, deq):
"""
Calculate helio- and barycentric velocity.
.. note:: The "JPL" option present in IDL is not provided here.
Parameters
----------
dje : float
Julian ephemeris date
deq : float
Epoch of mean equinox of helio- and barycentric velocity output.
... | 15,983 |
def uniform(low=0.0, high=1.0, size=None):
"""This function has the same `nlcpy.random.RandomState.uniform`
See Also
--------
nlcpy.random.RandomState.uniform : Draws samples from a uniform distribution.
"""
rs = generator._get_rand()
return rs.uniform(low, high, size=size) | 15,984 |
def test_post_model_predict_bool_param_missing_status_code_equals_400():
"""Verify that calling /api/model/predict with no bool_param fails with 400 and flags missing
properties as required."""
response = _post_request_good_json_with_overrides("bool_param", None)
assert response.status_code == HTTPStatu... | 15,985 |
def parse_time_interval(interval_str):
"""Convert a human-readable time interval to a tuple of start and end value.
Args:
interval_str: (`str`) A human-readable str representing an interval
(e.g., "[10us, 20us]", "<100s", ">100ms"). Supported time suffixes are
us, ms, s.
Returns:
... | 15,986 |
def submatrix(M, x):
"""If x is an array of integer row/col numbers and M a matrix,
extract the submatrix which is the all x'th rows and cols.
i.e. A = submatrix(M,x) => A_ij = M_{x_i}{x_j}
"""
return M[np.ix_(x,x)] | 15,987 |
def inventory_report(products: list) -> str:
"""Gives a detailed report on created products"""
unique_names, average_price, average_weight, average_flam = _build_report_metrics(products)
report = f'''ACME CORPORATION OFFICIAL INVENTORY REPORT
Unique product names: {unique_names}
Average price... | 15,988 |
def iou(a, b):
""" Calculates intersection over union (IOU) over two tuples """
(a_x1, a_y1), (a_x2, a_y2) = a
(b_x1, b_y1), (b_x2, b_y2) = b
a_area = (a_x2 - a_x1) * (a_y2 - a_y1)
b_area = (b_x2 - b_x1) * (b_y2 - b_y1)
dx = min(a_x2, b_x2) - max(a_x1, b_x1)
dy = min(a_y2, b_y2)... | 15,989 |
def svn_path_is_empty(*args):
"""svn_path_is_empty(char path) -> int"""
return _core.svn_path_is_empty(*args) | 15,990 |
def main(args=None):
"""
CphdConsistency CLI tool. Prints results to stdout.
Parameters
----------
args: None|List[str]
List of CLI argument strings. If None use sys.argv
"""
parser = argparse.ArgumentParser(description="Analyze a CPHD and display inconsistencies")
parser.add_... | 15,991 |
def compute_lorentz(Phi, omega, sigma):
"""In a time-harmonic discretization with quantities
.. math::
\\begin{align}
A &= \\Re(a \\exp(\\text{i} \\omega t)),\\\\
B &= \\Re(b \\exp(\\text{i} \\omega t)),
\\end{align}
the time-average of :math:`A\\times B` over one ... | 15,992 |
def test_model_finder_regression_residual_error(model_finder_regression):
"""Testing if prediction_errors raises an error when there are no search results available (regression)."""
with pytest.raises(ModelsNotSearchedError) as excinfo:
_ = model_finder_regression.residuals(1)
assert "Search Results... | 15,993 |
def play_db(cursor, query_string, lookup_term):
"""
Given a query string and a term, retrieve the list of plays associated with
that term
"""
play_list = []
try:
cursor.execute(query_string, [lookup_term])
play_res = cursor.fetchall()
except DatabaseError as err:
LOG... | 15,994 |
def list_banks(bot, update):
"""Show user names of banks that are supported"""
chat_id = update.message.chat_id
parser_classes = utils.get_parser_classes()
bank_names = "\n".join(
parser_cls.name + "\t:\t" + parser_cls.short_name
for parser_cls in parser_classes
)
msg = _("Sup... | 15,995 |
def find_nocc(two_arr, n):
"""
Given two sorted arrays of the SAME lengths and a number,
find the nth smallest number a_n and use two indices to indicate
the numbers that are no larger than a_n.
n can be real. Take the floor.
"""
l = len(two_arr[0])
if n >= 2 * l: return l, l
if n ... | 15,996 |
def get_dict(str_of_dict: str, order_key='', sort_dict=False) -> list:
"""Function returns the list of dicts:
:param str_of_dict: string got form DB
(e.g. {"genre_id": 10, "genre_name": "name1"}, {"genre_id": 11, "genre_name": "name12"},...),
:param order_key: the key by which dictionaries will be sorte... | 15,997 |
def pyz_repositories():
"""Rules to be invoked from WORKSPACE to load remote dependencies."""
excludes = native.existing_rules()
WHEEL_BUILD_CONTENT = wheel_build_content()
if 'pypi_atomicwrites' not in excludes:
http_archive(
name = 'pypi_atomicwrites',
url = 'https://... | 15,998 |
def get_richpe_hash(pe):
"""Computes the RichPE hash given a file path or data.
If the RichPE hash is unable to be computed, returns None.
Otherwise, returns the computed RichPE hash.
If both file_path and data are provided, file_path is used by default.
Source : https://github.com/RichHeaderResearc... | 15,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.