content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def target_mask(image, path, num_grid_corners):
"""
Arguments:
image: grayscale image of shape (N, M)
path: pathlib.Path object for the image
Returns: Boolean mask of shape (N, M), which is True for pixels that
we think are on the calibration target.
"""
ret, corners = get_c... | 5,338,900 |
def boddef(name, code):
"""
Define a body name/ID code pair for later translation via
:func:`bodn2c` or :func:`bodc2n`.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/boddef_c.html
:param name: Common name of some body.
:type name: str
:param code: Integer code for that body.
... | 5,338,901 |
def write_tar(archive_url, manifest_path, tar_path, strip_prefix=None, progress_bar=False, overwrite=False):
"""
Write all objects from archive_url to tar_path.
Write list of objects to manifest_path.
"""
if not overwrite:
if exists(tar_path):
raise IOError("%s already ex... | 5,338,902 |
def read_data(spec: dict) -> (dict, DataFrame):
"""Creates Pandas DataFrame by reading file at path.
Appropriate read_* pandas method will be called based
on the extension of the input file specified."""
path = spec['input']['file']
ext = Path(path).suffix
kwargs = build_kwargs_read(spec,... | 5,338,903 |
def bunk_choose(bot, update, user_data):
"""Removes keyboardMarkup sent in previous handler.
Stores the response (for Lectures/Practicals message sent in previous handler) in a ``user_data``
dictionary with the key `"stype"`.
``user_data`` is a user relative dictionary which holds data between differen... | 5,338,904 |
def schema_instance():
"""JSONSchema schema instance."""
schema_instance = JsonSchema(
schema=LOADED_SCHEMA_DATA,
filename="dns.yml",
root=os.path.join(FIXTURES_DIR, "schema", "schemas"),
)
return schema_instance | 5,338,905 |
def module_of(obj):
"""Return the Module given object is contained within.
"""
if isinstance(obj, Module):
return obj
elif isinstance(obj, (Function, Class)):
return obj.module
elif isinstance(obj, Method):
return module_of(obj.klass)
elif isinstance(obj, TestCase):
... | 5,338,906 |
def day(date, atmos=atmos):
"""
Returns a dataframe of daily aggregated data
Parameters
-------
date: str
Format yyyy/mm/dd
"""
path = f"{get_day_folder_path(date)}{date.replace('/','')}_daily_agg.csv.gz"
return load_agg(path, atmos) | 5,338,907 |
async def find_deck_position(hcapi: OT3API, mount: OT3Mount) -> float:
"""
Find the true position of the deck in this mount's frame of reference.
The deck nominal position in deck coordinates is 0 (that's part of the
definition of deck coordinates) but if we have not yet calibrated a
particular too... | 5,338,908 |
def assert_pipeline_notify_output_is(pipeline_name, expected_notify_output):
"""Assert that the pipeline has the expected output to NOTIFY log.
Args:
pipeline_name: str. Name of pipeline to run. Relative to ./tests/
expected_notify_output: list of str. Entirety of strings expected in
... | 5,338,909 |
def safe_get_request(url, auth):
"""Sends HTTP GET request.
Safetly sends HTTP GET request and handles exceptions.
Args:
url (str): The URL to send request to
auth (tuple): The username and password
Yields:
requests.models.Request: The request object
Raises:
... | 5,338,910 |
def load_measure_defs(measure_ids=None):
"""Load measure definitions from JSON files.
Since the lpzomnibus measure depends on other LP measures having already been
calculated, it is important that the measures are returned in alphabetical order.
(This is a bit of a hack...)
"""
measures = []
... | 5,338,911 |
def test_stop_tcp_with_delay(sdc_builder, sdc_executor):
"""Make sure that the origin can properly be started after stopping it with long batch times."""
builder = sdc_builder.get_pipeline_builder()
tcp_server = builder.add_stage('TCP Server')
tcp_server.configuration.update({'conf.dataFormat': 'TEXT',... | 5,338,912 |
def setup_logger(name, warninglevel=logging.WARNING, logfilepath=path_to_log,
logformat='%(asctime)s %(levelname)s - %(name)-6s - %(message)s'):
"""Basic setup function to create a standard logging config. Default output
is to file in /tmp/dir."""
logfile=os.path.join(logfilepath,'magpy.l... | 5,338,913 |
def create_symbol_id(path_to_db: str) -> str:
"""
When creating a new symbol, need to ensure
that ID is not already used in the Physics Derivation Graph
Args:
path_to_db: filename of the SQL database containing
a JSON entry that returns a nested dictionary
Returns:
... | 5,338,914 |
def zeros_bitonic(mz, i):
"""Cluster based on zeros and bitonic intensities.
Args:
mz (iterable): m/z ratios.
i (iterable): Intensiities (contains the zero intensities),
Yields:
Tuples of m/z ratios and intensities within clusters.
"""
M = []
I = []
i__ = -2
... | 5,338,915 |
def get_file_name(content_disposition: str, ) -> str:
"""Content-Disposition has the filename between the `"`. get it.
Args:
content_disposition: the content disposition from download header
Returns:
the file name
"""
if match := re.search(r'"(.*?)"', content_disposition):
... | 5,338,916 |
def authenticate(connect=True):
"""
Generally you will not need to call this directly; passing in your
credentials via set_credentials() and set_credential_file() will call
authenticate() on the identity object by default. But for situations where
you set your credentials manually or otherwise need ... | 5,338,917 |
def test__data_series__reaction_trunk():
""" test data_series.reaction_trunk
"""
prefix = os.path.join(PREFIX, 'reaction_trunk')
os.mkdir(prefix)
# without a root directory
ds_ = autofile.schema.data_series.reaction_trunk(prefix)
assert not ds_.exists()
ds_.create()
assert ds_.exis... | 5,338,918 |
def get_object(node):
""" Parse rebaron AtomTrailers node into Python object (taken from ongoing conversion object)
Works for object and local scope """
if len(node) > 1 and (node[0].value == 'self' or node[0].value == 'self_next'):
var_t = super_getattr(convert_obj, str(node))
else:
#... | 5,338,919 |
def read_label_from_txt(label_path):
"""Read label from txt file."""
text = np.fromfile(label_path)
bounding_box = []
with open(label_path, "r") as f:
labels = f.read().split("\n")
for label in labels:
if not label:
continue
label = label.split(" "... | 5,338,920 |
def _load_recipe(module, baked: bool = False) -> Union[BakedRecipe, Recipe]:
# load entry-point DAG
"""Load Queenbee plugin from Python package.
Usually you should not be using this function directly. Use ``load`` function
instead.
args:
module: Python module object for a Queenbee Recipe.
... | 5,338,921 |
def run(editor: str = "", edit_args: str = ""):
"""
execute
execute Custom PHP code by notepad / vi as default or your own editor, edit_args split by space.
eg: execute {editor=""} {edit_args=""} execute code '"--wait"'
"""
file_name = str(uuid4()) + ".php"
real_file_path = newfile(file_n... | 5,338,922 |
def test_no_threshold_coordinate(probability_cube):
"""Test an exception is raised if no threshold coordinate is found."""
cube = probability_cube[0]
threshold = cube.coord(var_name="threshold")
cube.remove_coord(threshold)
with pytest.raises(ValueError, match="Cube does not have a threshold coord... | 5,338,923 |
def compute_coeffs(shape, Aref, alfa):
"""Computes the lift and drag coefficients of the given shape at the given
angle of attack using the given reference area"""
alfa_vect = np.array([-np.sin(alfa),0,-np.cos(alfa)])
Fvect = np.array([0,0,0]) #Force coefficient vector
for panel in shape:
p... | 5,338,924 |
def draw_pitch(axis, rotate=False):
"""
Plots the lines of a soccer pitch using matplotlib.
Arguments
---------
axis : matplotlib.axes._subplots.AxesSubplot
- matplotlib axis object on which to plot shot freeze frame
rotate : bool
- if set to True, pitch is horizontal,
d... | 5,338,925 |
def end_scan_setup(start_time):
"""Process results and deactivate specific buttons on each scan end."""
process_results(start_time)
stop_bt.set_sensitive(False)
cb_display.set_sensitive(True) | 5,338,926 |
def step_impl(context, url):
"""
:type context: behave.runner.Context
:type url: str
"""
context.api_url = 'http://localhost:8080'
context.resource = url | 5,338,927 |
def test_cache(app, dir_factory):
"""Test cached schema loading."""
m = mock_open
with mock.patch('invenio_jsonschemas.ext.open', m):
ext = InvenioJSONSchemas(app, entry_point_group=None)
schema_files = build_schemas(1)
with dir_factory(schema_files) as directory:
ext.re... | 5,338,928 |
async def test_setup_config_flow(hass):
"""Test for successfully setting up the IPMA platform."""
with patch(
"homeassistant.components.ipma.weather.async_get_location",
return_value=MockLocation(),
):
entry = MockConfigEntry(domain="ipma", data=TEST_CONFIG)
await hass.config... | 5,338,929 |
def test_next_events(hass):
"""Test retrieving next sun events."""
utc_now = datetime(2016, 11, 1, 8, 0, 0, tzinfo=dt_util.UTC)
from astral import Astral
astral = Astral()
utc_today = utc_now.date()
latitude = hass.config.latitude
longitude = hass.config.longitude
mod = -1
while T... | 5,338,930 |
def plot_dist(distances, filename):
"""
Plot the average distance between a fish and its neighbors
over the course of a simulation and save this graph
Arguements:
distances {flot list} -- the average distance at each timestep
filename {string} -- name of file in which to save graph
... | 5,338,931 |
def file(filename, searchspec=None, searchtype=None, list_images=False,
sort_by=None, fields=None):
"""Examine images from a local file."""
if not list_images:
if searchtype is None or searchspec is None:
raise click.BadParameter(
'SEARCHTYPE and SEARCHSPEC must be s... | 5,338,932 |
def clip_to_norm(array, clip):
"""Clips the examples of a 2-dimensional array to a given maximum norm.
Parameters
----------
array : np.ndarray
Array to be clipped. After clipping, all examples have a 2-norm of at most `clip`.
clip : float
Norm at which to clip each example
R... | 5,338,933 |
def test_bench_day_4(benchmark):
"""pytest-benchmark function"""
benchmark(main) | 5,338,934 |
def getlineno(frame):
"""Get the line number from a frame object, allowing for optimization."""
# FrameType.f_lineno is now a descriptor that grovels co_lnotab
return frame.f_lineno | 5,338,935 |
def _process_sample(sample, fwd, rev, common_args, out):
"""Constructs assembly command for MEGAHIT and runs the assembly.
Args:
sample: Name of the sample to be processed.
fwd: Location of the forward reads.
rev: Location of the reverse reads. If set to None, single-end reads
... | 5,338,936 |
def _batch_sum(F, loss, batch_axis):
"""Return sum on the specified batch axis, not keeping the axis"""
if is_np_array():
axes = list(range(loss.ndim))
del axes[batch_axis]
return F.np.sum(loss, axis=axes)
else:
return F.sum(loss, axis=batch_axis, exclude=True) | 5,338,937 |
def _ExpandSections(section_names, name_to_symbol_infos,
offset_to_symbol_infos, section_to_symbols_map,
symbol_to_sections_map, suffixed_sections):
"""Gets an ordered set of section matching rules for a list of sections.
Rules will not be repeated.
Args:
section_name... | 5,338,938 |
async def test_device_registry(opp, config_entry, config, soco):
"""Test sonos device registered in the device registry."""
await setup_platform(opp, config_entry, config)
device_registry = dr.async_get(opp)
reg_device = device_registry.async_get_device(
identifiers={("sonos", "RINCON_test")}
... | 5,338,939 |
def tree_cons(a, tree: Pytree) -> Pytree:
"""
Prepend ``a`` in all tuples of the given tree.
"""
return jax.tree_map(
lambda x: _OpaqueSequence((a,) + tuple(x)),
tree,
is_leaf=lambda x: isinstance(x, tuple),
) | 5,338,940 |
def add(moment: datetime) -> datetime:
"""Add one gigasecond to a given date and time."""
return moment + GIGASECOND | 5,338,941 |
def get_test_hooks(test_files, cfg, tracer=None):
"""Returns a list of test hooks from a given list of test modules."""
results = []
dirs = set(map(os.path.dirname, test_files))
for dir in list(dirs):
if os.path.basename(dir) == 'ftests':
dirs.add(os.path.join(os.path.dirname(dir), '... | 5,338,942 |
def convert_to_short_log(log_level, message):
"""Convert a log message to its shorter format.
:param log_level: enum - 'LogLevel.<level>' e.g. 'LogLevel.Error'
:param message: str - log message
:return: enum - 'LogLevelInt.<value>` e.g. 'LogLevelInt.5'
"""
return f'{LogLevelInt[log_level.na... | 5,338,943 |
def load_map(path, callback=None, meta_override=None):
"""Load a set of zipped csv AFM workshop data
If you are recording quantitative force-maps (i.e. multiple
curves on an x-y-grid) with AFM workshop setups, then you
might have realized that you get *multiple* .csv files (one
file per indentation... | 5,338,944 |
def _asthetics(fig, axs, lines):
"""
Extra formatting tasks
:param `matplotlib.figure.Figure` fig: mpl figure
:param list axs: list of `matplotlib.axes.Axes`
:param `matplotlib.lines.Line2D` lines: ROC lines
:return:
"""
# format axes
axs[0][0].set_yticks([0, 0.5, 1])
yticks = ... | 5,338,945 |
def format_len(x):
"""
>>> format_len('abc')
3
>>> format_len(('(', ('(', 'def', ')'), 'yz', ')'))
11
"""
if not isinstance(x, (list, tuple)): return len(x)
if len(x) > 3: sep_len = 2 * (len(x) - 3)
else: sep_len = 0
return sum(map(format_len, x)) + sep_len | 5,338,946 |
def build_user_agent():
"""Build the charmcraft's user agent."""
if any(key.startswith(prefix) for prefix in TESTING_ENV_PREFIXES for key in os.environ.keys()):
testing = " (testing) "
else:
testing = " "
os_platform = "{0.system}/{0.release} ({0.machine})".format(utils.get_os_platform()... | 5,338,947 |
def test_presun_tam_a_zpet():
"""Zkontroluje přesouvání karet tam a zpátky"""
from klondike import presun_nekolik_karet
zdroj = [
(3, 'Kr', False),
(4, 'Sr', False),
(5, 'Kr', False),
]
cil = [
(11, 'Pi', True),
(12, 'Ka', True),
(13, 'Pi', True),
... | 5,338,948 |
def set_doi_ark(page_number, records_per_page, sort_on, doi_ark_value):
"""
Retrieve all metadata records for admin view. Retrieval is done
via POST because we must pass a session id so that the user is
authenticated.
Access control is done here. A user can modify only their own records
because... | 5,338,949 |
def check_datetime(value):
"""
Check and convert "value" to a datetime object. Value can have multiple formats,
according to the argparse.ArgumentParser doc (defined in :func:`parse_cmd_args`)
Args:
value (str): The input value
Returns:
datetime.datetime: the input value converted to a datetime object
Rais... | 5,338,950 |
def empiriline(x,p,L):
"""
Use the line L (which is an EmissionLine object) as a template.
The line is shifted, then interpolated, then rescaled, and allowed
to float.
"""
xnew = x - p[1]
yout = sp.zeros(len(xnew))
m = (xnew >= L.wv.min())*(xnew <= L.wv.max() )
ynew,znew = L.interp(x... | 5,338,951 |
def _get_z_slice_fn(z, data_dir):
"""Get array slice map to be applied to z dimension
Args:
z: String or 1-based index selector for z indexes constructed as any of the following:
- "best": Indicates that z slices should be inferred based on focal quality
- "all": Indicates that ... | 5,338,952 |
def test_stem_context_manager(tokenize, benchmark_text):
"""Использование морфологического анализатора в контекстном менеджере"""
with stemming.jstem_ctx() as stem:
jstem = stem
tokens = tokenize(benchmark_text)
result = stem.analyze([t[0] for t in tokens])
assert type(result) ... | 5,338,953 |
def fit_and_print_all(model, model_name):
"""Fits the model against all data instances
Args:
model: model to fit to the data sets
model_name: identifier for the outcomes
"""
for data_set, x in data_sets.items():
selector, method = data_set
train, test = x
key = ','.joi... | 5,338,954 |
def bar_data_wrapper(func):
"""Standardizes column names for any bar data"""
def wrapper(*args, **kwargs):
assert Ticker(args[0])
res: pd.DataFrame = func(*args, **kwargs)
return res.rename(columns=COL_NAMES).iterrows()
return wrapper | 5,338,955 |
def rgb_to_grayscale(
image: Tensor, rgb_weights: list[float] = [0.299, 0.587, 0.114]
) -> Tensor:
"""Convert an RGB image to grayscale version of image. Image data is
assumed to be in the range of [0.0, 1.0].
Args:
image (Tensor[B, 3, H, W]):
RGB image to be converted to grayscale.... | 5,338,956 |
def parse(msg: str) -> Dict[str, Union[str, int, float, bool, datetime]]:
"""Parse message from the feed output by dump1090 on port 30003
A dict is returned withAn SBS-1 message has the following attributes:
messageType : string
transmissionType : sbs1.TransmissionType
sessionID : int
... | 5,338,957 |
def test_phrase_tag():
"""
test for phrase POS tagger
"""
text = 'Lionel Messi pergi ke pasar di area Jakarta Pusat.'
expected_result =[
('Lionel Messi', 'NP'),
('pergi', 'VP'),
('ke', 'IN'),
('pasar', 'NN'),
('di', 'IN'),
('area', 'NN'),
('Jak... | 5,338,958 |
def _aware_to_agnostic(fr: NDFrame) -> NDFrame:
"""Recalculate values in tz-aware series or dataframe, to get a tz-agnostic one.
(i.e., A to B)."""
if not fr.index.tz:
raise ValueError("``fr`` must be tz-aware.")
idx_out = _idx_after_conversion(fr, None)
# Convert daily or longer.
if s... | 5,338,959 |
def cumulative_prob_to_value(prob, hp):
"""Convert a value from [0, 1] to a hyperparameter value."""
if isinstance(hp, Fixed):
return hp.value
elif isinstance(hp, Boolean):
return bool(prob >= 0.5)
elif isinstance(hp, Choice):
ele_prob = 1 / len(hp.values)
index = math.fl... | 5,338,960 |
def sms_confirm_payment(user):
""" Mark your deposit as paid after you have deposited the money
:param msg: A full telerivet message object
:param parts: 'done'
:returns: A message letting you know the status of the deposit
"""
connections = lookup_connections(backend="telerivet", identities=[u... | 5,338,961 |
def get_ui_node_spec(module=None, category="default"):
"""
Returns a dictionary describing the specifications for each Node in a module.
Parameters
-----------
module: module
The Python module for which the ui specs should be summarized. Only the top-level
classes will be included i... | 5,338,962 |
def validate_remote_id(value):
"""make sure the remote_id looks like a url"""
if not value or not re.match(r"^http.?:\/\/[^\s]+$", value):
raise ValidationError(
_("%(value)s is not a valid remote_id"),
params={"value": value},
) | 5,338,963 |
def parse_branch_name(branch_name):
"""Split up a branch name of the form 'ocm-X.Y[-mce-M.N].
:param branch_name: A branch name. If of the form [remote/]ocm-X.Y[-mce-M.N] we will parse
it as noted below; otherwise the first return will be False.
:return parsed (bool): True if the branch_name was pa... | 5,338,964 |
def form_update(form, node_xyz, trail_forces, reaction_forces):
"""
Update the node and edge attributes of a form after equilibrating it.
"""
# assign nodes' coordinates
for node, xyz in node_xyz.items():
form.node_xyz(node, xyz)
# form.node_attributes(key=node, names=["x", "y", "z"]... | 5,338,965 |
def symmetric_padding(
arr,
width):
"""
Pad an array using symmetric values.
This is equivalent to `np.pad(mode='symmetric')`, but should be faster.
Also, the `width` parameter is interpreted in a more general way.
Args:
arr (np.ndarray): The input array.
width (int... | 5,338,966 |
def main():
"""Will strip metadata and optionally randomize filenames from a
directory of videos."""
args = docopt(__doc__)
vid_paths = get_video_paths(args["INDIR"])
outdir = Path(args["OUTDIR"])
try:
outdir.mkdir()
except FileExistsError:
print(f"OUTDIR {outdir} must not a... | 5,338,967 |
def start(app_component="Main"):
"""
Starts the script
"""
global t0
t0 = round(time.time()*1000, 0).__int__()
log_to_disk('Start', msg=app_name+':'+app_component+' starting invocation', kv=kvalue(t0=t0)) | 5,338,968 |
def _uid_or_str(node_or_entity):
""" Helper function to support the transition from `Entitie`s to `Node`s.
"""
return (
node_or_entity.uid
if hasattr(node_or_entity, "uid")
else str(node_or_entity)
) | 5,338,969 |
def run(ctx):
""" Run the application. """
ctx.run("python manage.py run", echo=True) | 5,338,970 |
def main(src_fn, dst_fn, defect_net_name='minnie_mip2_defect_v03'):
"""Add defect annotations to a training dataset
Args:
* src_fn: path to H5 to be processed
* dst_fn: path where the new H5 will be written
"""
defect_net = ModelArchive(defect_net_name)
down = downsample(2)
print('Proce... | 5,338,971 |
def power(maf=0.5,beta=0.1, N=100, cutoff=5e-8):
"""
estimate power for a given allele frequency, effect size beta and sample size N
Assumption:
z-score = beta_ML distributed as p(0) = N(0,1.0(maf*(1-maf)*N))) under the null hypothesis
the actual beta_ML is distributed as p(alt) = N( beta , 1.0/(maf*(1-maf)N) )... | 5,338,972 |
def test_bheap_pop_twice_push(build_heap_of_ten):
"""Test popping twice and pushing."""
popped1 = build_heap_of_ten.pop()
popped2 = build_heap_of_ten.pop()
build_heap_of_ten.push(10)
assert popped1 == 1.5
assert popped2 == 2
assert build_heap_of_ten._list == [3, 6, 15, 7, 9, 16, 27, 8, 10] | 5,338,973 |
def get_rotation_matrix(angle: float, direction: np.ndarray, point: np.ndarray = None) -> np.ndarray:
"""Compute rotation matrix relative to point and direction
Args:
angle (float): angle of rotation in radian
direction (np.ndarray): axis of rotation
point (np.ndarray, optional): ... | 5,338,974 |
def assert_check(args: dict = None, log_level: str = LOG_LEVEL) -> bool:
""" assert caller function args """
if args is None:
logger.critical("Arguments dict is empty or does not exist!")
return False
else:
logging.debug("Args dictionary exists, processing assertion check...")
... | 5,338,975 |
def establish_github_connection(store: dict[str, Any]) -> ValidationStepResult:
"""
Establishes the connection to GitHub.
If the name of the environment variable storing the GitHub PAT is not given,
then it will default to searching for one named "GH_TOKEN". If provided,
can help rate-limiting be ... | 5,338,976 |
def recreate():
"""
Recreate elasticsearch indices and request docs.
"""
delete_index()
create_index()
create_docs() | 5,338,977 |
def answer(panel_array):
""" Returns the maximum product of positive and (odd) negative numbers."""
print("panel_array=", panel_array)
# Edge case I: no panels :]
if (len(panel_array) == 0):
return str(0)
# Get zero panels.
zero_panels = list(filter(lambda x: x == 0 , panel_arra... | 5,338,978 |
def load_fromh5(filepath, dir_structure, slice_num, strt_frm=0):
"""
load_fromh5 will extract the sinogram from the h5 file
Output: the sinogram
filepath: where the file is located in the system
dir_structure: the h5 file directory structure
slice_num: the slice where the singoram wil... | 5,338,979 |
def lqr_6_2(time_limit=_DEFAULT_TIME_LIMIT, random=None, environment_kwargs=None):
"""Returns an LQR environment with 6 bodies of which first 2 are actuated."""
return _make_lqr(
n_bodies=6,
n_actuators=2,
control_cost_coef=_CONTROL_COST_COEF,
time_limit=time_limit,
rando... | 5,338,980 |
def machine_stop(request, tenant, machine):
"""
Stop (power off) the specified machine.
"""
with request.auth.scoped_session(tenant) as session:
serializer = serializers.MachineSerializer(
session.stop_machine(machine),
context = { "request": request, "tenant": tenant }
... | 5,338,981 |
def exec_command_rc(*cmdargs, **kwargs):
"""
Return the exit code of the command specified by the passed positional arguments, optionally configured by the
passed keyword arguments.
Parameters
----------
cmdargs : list
Variadic list whose:
1. Mandatory first element is the absol... | 5,338,982 |
def _get_input_value(arg: Tuple[str, GraphQLArgument]) -> Dict[str, Any]:
"""Compute data for the InputValue fragment of the introspection query for a particular arg."""
return {
"name": __InputValue.fields["name"].resolve(arg, None),
"description": __InputValue.fields["description"].resolve(arg... | 5,338,983 |
def wrapper(X_mixture,X_component):
""" Takes in 2 arrays containing the mixture and component data as
numpy arrays, and prints the estimate of kappastars using the two gradient
thresholds as detailed in the paper as KM1 and KM2"""
N=X_mixture.shape[0] ... | 5,338,984 |
def plot_abnormal_cumulative_return_with_errors(abnormal_volatility, abnormal_returns, events):
"""
Capturing volatility of abnormal returns
"""
pyplot.figure(figsize=FIGURE_SIZE)
pyplot.errorbar(
abnormal_returns.index,
abnormal_returns,
xerr=0,
yerr=abnormal_volati... | 5,338,985 |
def iou(
outputs: torch.Tensor,
targets: torch.Tensor,
eps: float = 1e-7,
threshold: float = 0.5,
activation: str = "sigmoid"
):
"""
Args:
outputs (torch.Tensor): A list of predicted elements
targets (torch.Tensor): A list of elements that are to be predicted
eps (fl... | 5,338,986 |
def readCoords(f):
"""Read XYZ file and return as MRChem JSON friendly string."""
with open(f) as file:
return '\n'.join([line.strip() for line in file.readlines()[2:]]) | 5,338,987 |
def fetch_hillstrom(target_col='visit', data_home=None, dest_subdir=None, download_if_missing=True,
return_X_y_t=False, as_frame=True):
"""Load and return Kevin Hillstrom Dataset MineThatData (classification or regression).
This dataset contains 64,000 customers who last purchased within tw... | 5,338,988 |
def test_format(name, value):
"""Format test results."""
RESULTS[name] = value
value = 'OK' if value else 'FAIL'
print(name.ljust(40, '.'), value) | 5,338,989 |
def api_update_note(note_id: int):
"""Update a note"""
db = get_db()
title = request.form["title"] if "title" in request.form.keys() else None
content = request.form["content"] if "content" in request.form.keys() else None
note = db.update_note(note_id, title, content)
return jsonify(note.__dict... | 5,338,990 |
def padding_oracle(decrypt, cipher, *, bs, unknown=b"\x00", iv=None):
"""Padding Oracle Attack
Given a ciphersystem such that:
- The padding follows the format of PKCS7
- The mode of the block cipher is CBC
- We can check if the padding of a given cipher is correct
- We can try to decrypt ciphe... | 5,338,991 |
def pixels():
"""
Raspberry Pi pixels
"""
return render_template("pixels.html") | 5,338,992 |
def env_break_shooter(pack: PackList, ent: Entity):
"""Special behaviour on the 'model' KV."""
if conv_int(ent['modeltype']) == 1: # MODELTYPE_MODEL
pack.pack_file(ent['model'], FileType.MODEL)
# Otherwise, a template name or a regular gib. | 5,338,993 |
async def get_song_info(id: str):
"""
获取歌曲详情
"""
params = {'ids': id}
return get_json(base_url + '/song/detail', params=params) | 5,338,994 |
def test_dicom_sender_cli(test_dataset):
"""Test the command line interface to the DicomSender"""
scp_ae_title = "PYMEDPHYSTEST"
with tempfile.TemporaryDirectory() as tmp_directory:
test_directory = pathlib.Path(tmp_directory)
send_directory = test_directory.joinpath("send")
send_... | 5,338,995 |
def save_data(
discord_id,
bga_userid="",
username="",
password="",
purge_data=False,
bga_global_options=[],
tfm_global_options=[],
bga_game_options={},
):
"""save data."""
user_json = get_all_logins()
if purge_data:
# Keep username. User can rename themselves if they... | 5,338,996 |
def _find_odf_idx(map, position):
"""Find odf_idx in the map from the position (col or row).
"""
odf_idx = bisect_left(map, position)
if odf_idx < len(map):
return odf_idx
return None | 5,338,997 |
def get_or_create(session, model, **kwargs):
"""
Creates and returns an instance of the model with given kwargs,
if it does not yet exist. Otherwise, get instance and return.
Parameters:
session: Current database session
model: The Class of the database model
**kw... | 5,338,998 |
def pack_asn1(tag_class, constructed, tag_number, b_data):
"""Pack the value into an ASN.1 data structure.
The structure for an ASN.1 element is
| Identifier Octet(s) | Length Octet(s) | Data Octet(s) |
"""
b_asn1_data = bytearray()
if tag_class < 0 or tag_class > 3:
raise ValueError(... | 5,338,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.