content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def _get_requirements_for_lambda(node):
"""
..code:: python
Lambda(arguments args, expr body)
"""
scope = _get_scope_from_arguments(node.args)
for requirement in get_requirements(node.body):
if requirement.name not in scope:
yield requirement | 5,333,800 |
def fix_span(text_context, offsets, span):
"""
find start-end indices of the span in the text_context nearest to the existing token start-end indices
:param text_context: (str) text to search for span in
:param offsets: (List(Tuple[int, int]) list of begins and ends for each token in the text
:param... | 5,333,801 |
def update_moira_lists(
strategy, backend, user=None, **kwargs
): # pylint: disable=unused-argument
"""
Update a user's moira lists
Args:
strategy (social_django.strategy.DjangoStrategy): the strategy used to authenticate
backend (social_core.backends.base.BaseAuth): the backend being ... | 5,333,802 |
def upgrade():
"""Upgrade database schema and/or data, creating a new revision."""
op.execute(
"ALTER TABLE notifications ALTER force_notifications SET DEFAULT 0")
op.execute("ALTER TABLE notifications ALTER repeating SET DEFAULT 0") | 5,333,803 |
def certificate_get_all_by_project(context, project_id):
"""Get all certificates for a project."""
return IMPL.certificate_get_all_by_project(context, project_id) | 5,333,804 |
def simple_list(li):
"""
takes in a list li
returns a sorted list without doubles
"""
return sorted(set(li)) | 5,333,805 |
def test_draw_cursor(cursor: Cursor, offset: IntegerPosition2D, canvas: Canvas,
expected_canvas_after: Canvas) -> None:
"""Test illud.terminal.Terminal.draw_cursor."""
cursor.draw(offset, canvas)
assert canvas == expected_canvas_after | 5,333,806 |
async def test_device_trackers_in_zone(opp):
"""Test for trackers in zone."""
config = {
"proximity": {
"home": {
"ignored_zones": ["work"],
"devices": ["device_tracker.test1", "device_tracker.test2"],
"tolerance": "1",
}
}
... | 5,333,807 |
def create_model(gpu, arch = 'vgg16', input_size = 25088, hidden_layer_size = 512, output_size = 102):
"""Creates a neural network model.
"""
if arch in archs_dict:
model = archs_dict[arch]
else:
print("You haven`t inserted a valid architecture. Check the available architectures at https... | 5,333,808 |
def write_json(object_list, metadata,num_frames, out_file = None):
"""
"""
classes = ["person","bicycle","car","motorbike","NA","bus","train","truck"]
# metadata = {
# "camera_id": camera_id,
# "start_time":start_time,
# "num_frames":num_frames,
# "frame_rate"... | 5,333,809 |
def get_infer_iterator(src_dataset,
src_vocab_table,
batch_size,
eos,
sos,
src_max_len=None):
"""Get dataset for inference."""
# Totol number of examples in src_dataset
# (3003 examples + 69 padding ... | 5,333,810 |
def test_minus_from_step():
"""Test from_step < 0"""
out = CheckOutput(target_log_history_length=6)
loss_plotter = PlotLosses(outputs=[out], from_step=-5)
for idx in range(10):
loss_plotter.update({
'acc': 0.1 * idx,
'loss': 0.69 / (idx + 1),
})
loss_... | 5,333,811 |
def get_num_hearts(image):
"""Returns the number of full and total hearts.
Keyword arguements:
image - image of hearts region
"""
# definitions:
lower_full = np.array([0, 15, 70])
upper_full = np.array([30, 35, 250])
lower_empty = np.array([150, 160, 220])
upper_empty = np.... | 5,333,812 |
async def async_setup_entry(hass, config_entry, async_add_entities):
"""Set up the Fully Kiosk Browser number entities."""
coordinator = hass.data[DOMAIN][config_entry.entry_id]
entities = [
FullyNumberEntity(coordinator, entity)
for entity in ENTITY_TYPES
if entity.key in coordinat... | 5,333,813 |
def _clean_root(tool_xml):
"""XSD assumes macros have been expanded, so remove them."""
clean_tool_xml = copy.deepcopy(tool_xml)
to_remove = []
for macros_el in clean_tool_xml.getroot().findall("macros"):
to_remove.append(macros_el)
for macros_el in to_remove:
clean_tool_xml.getroot(... | 5,333,814 |
def page_not_found(e):
"""Return a custom 404 error."""
logging.error(':: A 404 was thrown a bad URL was requested ::')
logging.error(traceback.format_exc())
return render_template('404.html'), 404 | 5,333,815 |
def find_prime_factors(num):
"""Return prime factors of num."""
validate_integers(num)
zero_divisors_error(num)
potential_factor = 2
prime_factors = set()
while potential_factor <= num:
if num % potential_factor == 0:
prime_factors.add(potential_factor)
num = num/... | 5,333,816 |
def json_serial(obj):
"""JSON serializer for objects not serializable by default json code"""
if isinstance(obj, (datetime, date)):
return obj.isoformat()
elif isinstance(obj, (dict)):
return obj
raise TypeError("Type %s not serializable" % type(obj)) | 5,333,817 |
def read_yaml_files(directories):
"""Read the contents of all yaml files in a directory.
Args:
directories: List of directory names with configuration files
Returns:
config_dict: Dict of yaml read
"""
# Initialize key variables
yaml_found = False
yaml_from_file = ''
al... | 5,333,818 |
def run_command(command, settings):
"""Runs command from rule for passed command."""
if command.side_effect:
command.side_effect(command, settings)
shells.put_to_history(command.script)
print(command.script) | 5,333,819 |
def test_v1_0_workflow_top_level_sf_expr() -> None:
"""Test for the correct error when converting a secondaryFiles expression in a workflow level input."""
with raises(WorkflowException, match=r".*secondaryFiles.*"):
result, modified = traverse0(
parser.load_document(str(HERE / "../testdata/... | 5,333,820 |
def test_measurement():
"""Tests the measurement property of the HMIMap object."""
assert hmi.measurement == "continuum" | 5,333,821 |
def _check_for_crash(project_name, fuzz_target, testcase_path):
"""Check for crash."""
def docker_run(args):
command = ['docker', 'run', '--rm', '--privileged']
if sys.stdin.isatty():
command.append('-i')
return utils.execute(command + args)
logging.info('Checking for crash')
out, err, retu... | 5,333,822 |
def main(translator, source, target, text, api_key, languages):
"""
Use TRANSLATOR to translate source material into another language.
Available translators include: Google, MyMemory, QCRI, Linguee, Pons, Yandex, Microsoft (Bing), and Papago.\n
\f
function responsible for parsing terminal arguments ... | 5,333,823 |
def test_post_global_singleuse_coupons(admin_drf_client, single_use_coupon_json):
""" Test that the correct model objects are created for a batch of single-use coupons (global coupon) """
data = single_use_coupon_json
data["is_global"] = True
resp = admin_drf_client.post(reverse("coupon_api"), type="jso... | 5,333,824 |
def parse_from_compdb(compdb, file_to_parse):
"""Extracts the absolute file path of the file to parse and its arguments from compdb"""
absolute_filepath = None
file_arguments = []
compdb = compdb_parser.load_compdb(compdb)
if compdb:
commands = compdb.getAllCompileCommands()
for com... | 5,333,825 |
def _pyenv_version():
"""Determine which pyenv
Returns:
str: pyenv version
"""
import subprocess
return subprocess.check_output(['pyenv', 'version']).split(' ')[0] | 5,333,826 |
def reset_config_on_routers(tgen, routerName=None):
"""
Resets configuration on routers to the snapshot created using input JSON
file. It replaces existing router configuration with FRRCFG_BKUP_FILE
Parameters
----------
* `tgen` : Topogen object
* `routerName` : router config is to be rese... | 5,333,827 |
def ignore_exception(exception):
"""Check whether we can safely ignore this exception."""
if isinstance(exception, BadRequest):
if 'Query is too old' in exception.message or \
exception.message.startswith('Have no rights to send a message') or \
exception.message.startswith('Messag... | 5,333,828 |
def rmse_loss(prediction, ground_truth, weight_map=None):
"""
:param prediction: the current prediction of the ground truth.
:param ground_truth: the measurement you are approximating with regression.
:param weight_map: a weight map for the cost function. .
:return: sqrt(mean(differences squared))
... | 5,333,829 |
def test_network_config():
"""Test that the `canu generate network config` command runs and generates config."""
with runner.isolated_filesystem():
with open(sls_file, "w") as f:
json.dump(sls_input, f)
result = runner.invoke(
cli,
[
"--cache"... | 5,333,830 |
def start_workflow(base_url, digest_login, workflow_definition, media_package):
"""
Start a workflow on a media package.
:param base_url: The URL for the request
:type base_url: str
:param digest_login: The login credentials for digest authentication
:type digest_login: DigestLogin
:param w... | 5,333,831 |
def get_corrupted_simulation_docs():
"""Returns iterable of simdocs without samples (when num_paticles >0)
When num_particle<=0, no samples are created and the simulation is considered Finished anyway.
These ignored simulations
"""
return db[DBCOLLECTIONS.SIMULATION].find({
'procstatus.stat... | 5,333,832 |
def wait_for_powerpoint(videofile: str):
"""
While Powerpoint exports a video file, the file exists but has zero size.
Only once the export is complete will the contents be copied to the target.
"""
new_size = os.path.getsize(videofile) # will be zero during export
if new_size > 0:
retu... | 5,333,833 |
def scheduler():
"""
A function intended called by systemd timer.
Non-destructive operation, no data will be deleted currently.
Whenever it's called, it will invoke an examination on host and device.
Note:
The operation is in days, which means that if I invoked scheduler today already,
... | 5,333,834 |
def main(args):
"""Main.""" | 5,333,835 |
def example_calculate_slippage_with_bid_mid_spreads():
"""Calculate the slippage for trades given market data as a benchmark
"""
from tcapy.analysis.algos.metric import MetricSlippage
market_df, trade_df = get_sample_data()
metric_slippage = MetricSlippage()
trade_df, _ = metric_slippage.calcu... | 5,333,836 |
def residual_block(x: Tensor, downsample: bool, filters: int, kernel_size: int = 3) -> Tensor:
"""
Parameters
----------
x : Tensor
DESCRIPTION.
downsample : bool
DESCRIPTION.
filters : int
DESCRIPTION.
kernel_size : int, optional
DESCRIPTION. The defaul... | 5,333,837 |
def test_score_hist_splits(spark, df):
"""
test that a dataframe gets processed with non-default splits list
test binwidths and normalised probability densities sum up to 1.0
"""
mysplits = [0.3, 0.6]
res = _calc_probability_density(df, spark=spark, buckets=mysplits)
res = pd.DataFrame(res... | 5,333,838 |
def test_measurement_statistics_povm(ops, state, final_states, probabilities):
""" measurement_statistics_povm: projectors applied to basis states. """
collapsed_states, probs = measurement_statistics_povm(state, ops)
for i, final_state in enumerate(final_states):
collapsed_state = collapsed_states... | 5,333,839 |
def dehaze(img, level):
"""use Otsu to threshold https://scikit-image.org/docs/stable/auto_examples/segmentation/plot_multiotsu.html
n.b. threshold used to mask image: dark values are zeroed, but result is NOT binary
level: value 1..5 with larger values preserving more bright voxels
level: d... | 5,333,840 |
def matthews_correlation_coefficient(tp, tn, fp, fn):
"""Return Matthews correlation coefficient for values from a confusion matrix.
Implementation is based on the definition from wikipedia:
https://en.wikipedia.org/wiki/Matthews_correlation_coefficient
"""
numerator = (tp * tn) - (fp * fn)
den... | 5,333,841 |
def find_graph(hostnames):
"""
Find a graph file contains all devices in testbed.
duts are spcified by hostnames
Parameters:
hostnames: list of duts in the target testbed.
"""
filename = os.path.join(LAB_GRAPHFILE_PATH, LAB_CONNECTION_GRAPH_FILE)
with open(filename) as fd:
f... | 5,333,842 |
def run_analysis(apk_dir, md5_hash, package):
"""Run Dynamic File Analysis."""
analysis_result = {}
logger.info('Dynamic File Analysis')
domains = {}
clipboard = []
# Collect Log data
data = get_log_data(apk_dir, package)
clip_tag = 'I/CLIPDUMP-INFO-LOG'
clip_tag2 = 'I CLIPDUMP-INFO-... | 5,333,843 |
async def quotes(
ticker: str, date: datetime.date,
uow: UoW = fastapi.Depends(dependendies.get_uow),
) -> ListResponse[Ticker]:
"""Return the list of available tickers."""
with uow:
results = uow.quotes.iterator({'ticker': ticker, 'date': date})
return ListResponse(results=results) | 5,333,844 |
def delete_snapshot(client, data_args) -> Tuple[str, dict, Union[list, dict]]:
""" Delete exsisting snapshot from the system.
:type client: ``Client``
:param client: client which connects to api.
:type data_args: ``dict``
:param data_args: request arguments.
:return: human ... | 5,333,845 |
def faster_tikz_time_1c(dependencies: List[pathlib.Path],
targets: List[pathlib.Path]) -> None:
"""FASTER Tikz time plot 1c."""
_faster_tikz_time_1(dependencies, targets, 2) | 5,333,846 |
def api_user_submissions(user_id):
"""Gets the price submissions for a user matching the user_id.
Example Request:
HTTP GET /api/v1/users/56cf848722e7c01d0466e533/submissions
Example Response:
{
"success": "OK",
"user_submissions": [
{
"submitt... | 5,333,847 |
def get_pdf_info(pdf_path: str) -> PdfInfo:
"""Get meta information of a PDF file."""
info: PdfInfo = PdfInfo(path=pdf_path)
keys = get_flat_cfg_file(path="~/.edapy/pdf_keys.csv")
ignore_keys = get_flat_cfg_file(path="~/.edapy/pdf_ignore_keys.csv")
for key in keys:
info.user_attributes[key... | 5,333,848 |
def convert_gz_json_type(value):
"""Provide an ArgumentParser type function to unmarshal a b64 gz JSON string.
"""
return json.loads(zlib.decompress(base64.b64decode(value))) | 5,333,849 |
def get_tag(tag):
"""
Returns a tag object for the string passed to it
If it does not appear in the database then return a new tag object
If it does exisit in the data then return the database object
"""
tag = tag.lower()
try:
return Session.query(Tag).filter_by(name=unicode(tag)).on... | 5,333,850 |
def makeApiCall( url, endpointParams, debug = 'no' ) :
""" Request data from endpoint with params
Args:
url: string of the url endpoint to make request from
endpointParams: dictionary keyed by the names of the url parameters
Returns:
object: data from the endpoint
"""
da... | 5,333,851 |
def get_closest_area(
lat: float, lng: float, locations: t.List[config.Area]
) -> t.Optional[config.Area]:
"""Return area if image taken within 50 km from center of area"""
distances = [
(great_circle((area.lat, area.lng), (lat, lng)).km, area) for area in locations
]
distance, closest_area ... | 5,333,852 |
def saveLocations(filename, model_locations, model_ids):
"""
Save an allocation specified by the parameter.
:param filename: filename to save the allocation to
:param modellocations: allocation to save to file
:param model_ids: all model_ids to model mappings
"""
# Save the locations
f ... | 5,333,853 |
def disable(request):
"""
Disable Pool Member Running Script
"""
try:
auth = AuthSession(request.session)
client = auth.get_clientFactory()
id_server_pool = request.POST.get('id_server_pool')
ids = request.POST.get('ids')
if id_server_pool and ids:
... | 5,333,854 |
def fastapi_native_middleware_factory():
"""Create a FastAPI app that uses native-style middleware."""
app = FastAPI()
# Exception handler for `/client_error_from_handled_exception`
app.add_exception_handler(IndexError, client_induced_exception_handler)
app.add_middleware(BaseHTTPMiddleware, dispa... | 5,333,855 |
def _partial_dependence(
pipeline,
X,
features,
percentiles=(0.05, 0.95),
grid_resolution=100,
kind="average",
custom_range=None,
):
"""Compute the partial dependence for features of X.
Args:
pipeline (PipelineBase): pipeline.
X (pd.DataFrame): Holdout data
f... | 5,333,856 |
def nplog(
a: np.ndarray, deriv: bool = False, eps: float = 1e-30, verbose: bool = False
) -> Union[np.ndarray, Tuple[np.ndarray, np.ndarray]]:
"""$C^2$ extension of $\ln(a)$ below `eps`
Args:
a: a Numpy array
deriv: if `True`, the first derivative is also returned
eps: a lower bou... | 5,333,857 |
def translate_names(recipe_names: List[str], locale: str) -> List[str]:
"""Translates a list of recipe names to the given locale."""
if locale in ['auto', 'en-us']:
return recipe_names
translation_path = os.path.join('recipes', 'translations.json')
with open(translation_path, encoding='utf-8') ... | 5,333,858 |
def _section_to_text(config_section: ConfigSection) -> str:
"""Convert a single config section to text"""
return (f'[{config_section.name}]{LINE_SEP}'
f'{LINE_SEP.join(_option_to_text(option) for option in config_section.options)}{LINE_SEP}') | 5,333,859 |
def TempFileDecorator(func):
"""Populates self.tempfile with path to a temporary writeable file"""
def f(self, *args, **kwargs):
with tempfile.NamedTemporaryFile(dir=self.tempdir, delete=False) as f:
self.tempfile = f.name
return func(self, *args, **kwargs)
f.__name__ = func.__name__
f.__doc__ = ... | 5,333,860 |
def get_random_string(length: int) -> str:
"""
Returns a random string starting with a lower-case letter.
Later parts can contain numbers, lower- and uppercase letters.
Note: Random Seed should be set somewhere in the program!
:param length: How long the required string must be. length > 0 required... | 5,333,861 |
def subset_by_month(prediction_dict, desired_month):
"""Subsets examples by month.
:param prediction_dict: See doc for `write_file`.
:param desired_month: Desired month (integer from 1...12).
:return: prediction_dict: Same as input but with fewer examples.
"""
error_checking.assert_is_integer(... | 5,333,862 |
def build_dataset_mce(platform, dataset_name, columns):
"""
Creates MetadataChangeEvent for the dataset.
"""
actor, sys_time = "urn:li:corpuser:etl", int(time.time())
fields = []
for column in columns:
fields.append({
"fieldPath": column["name"],
"nativeDataType"... | 5,333,863 |
def build_guard(context_info):
"""Convert exceptions to BuildError with the given context information."""
try:
yield
except BuildError: # pylint: disable = try-except-raise
raise
except Exception as exc:
raise BuildError(context_info) from exc | 5,333,864 |
def do_host_stor_delete(cc, args):
"""Delete a stor"""
try:
cc.istor.delete(args.stor)
except exc.HTTPNotFound:
raise exc.CommandError('Delete failed, stor: %s not found'
% args.stor) | 5,333,865 |
def tag_source_file(path):
"""Returns a list of tuples: (line_text, list_of_tags)"""
file = open(path, "r")
# The list of tagged lines
tagged_lines = []
# The list of tags that currently apply
current_tags = []
# Use this to store snapshots of current_tags
from copy impor... | 5,333,866 |
def FindMissingReconstruction(X, track_i):
"""
Find the points that will be newly added
Parameters
----------
X : ndarray of shape (F, 3)
3D points
track_i : ndarray of shape (F, 2)
2D points of the newly registered image
Returns
-------
new_point : ndarray of shape... | 5,333,867 |
def deserialize(iodata):
"""
Turn IOData back into a Python object of the appropriate kind.
An object is deemed deserializable if
1) it is recorded in SERIALIZABLE_REGISTRY and has a `.deserialize` method
2) there exists a function `file_io_serializers.<typename>_deserialize`
Parameters
---... | 5,333,868 |
def _constraints_affecting_columns(self, table_name, columns, type="UNIQUE"):
"""
Gets the names of the constraints affecting the given columns.
If columns is None, returns all constraints of the type on the table.
"""
if self.dry_run:
raise ValueError("Cannot get constraints for column... | 5,333,869 |
def business_day_offset(dates: DateOrDates, offsets: Union[int, Iterable[int]], roll: str= 'raise', calendars: Union[str, Tuple[str, ...]]=(), week_mask: Optional[str]=None) -> DateOrDates:
"""
Apply offsets to the dates and move to the nearest business date
:param dates: The input date or dates
:param... | 5,333,870 |
def set_user_agent(agent):
"""Set User-Agent in the HTTP requests.
:keyword param agent: string
ex. 'test agent 1'
"""
global user_agent
user_agent = agent | 5,333,871 |
def factorial(n):
"""
Return n! - the factorial of n.
>>> factorial(1)
1
>>> factorial(0)
1
>>> factorial(3)
6
"""
if n<=0:
return 0
elif n==1:
return 1
else:
return n*factorial(n-1) | 5,333,872 |
def _load_absorption(freqs):
"""Load molar extinction coefficients."""
# Data from https://omlc.org/spectra/hemoglobin/summary.html
# The text was copied to a text file. The text before and
# after the table was deleted. The the following was run in
# matlab
# extinct_coef=importdata('extinction... | 5,333,873 |
def merge(config, revisions, **kwargs):
"""
Merge one or more revisions.
Takes one or more revisions or "heads" for all heads and merges them into
a single revision.
"""
with alembic_lock(
config.registry["sqlalchemy.engine"], config.alembic_config()
) as alembic_config:
ale... | 5,333,874 |
def lower_volume_listen(vass: VoiceAssistant) -> None:
"""Lower volume when Voice Assistant is listening."""
_lower_volume() | 5,333,875 |
def pw_sin_relaxation(b, x, w, x_pts, relaxation_side=RelaxationSide.BOTH, pw_repn='INC', safety_tol=1e-10):
"""
This function creates piecewise relaxations to relax "w=sin(x)" for -pi/2 <= x <= pi/2.
Parameters
----------
b: pyo.Block
x: pyomo.core.base.var.SimpleVar or pyomo.core.base.var._Ge... | 5,333,876 |
def getAsDateTimeStr(value, offset=0,fmt=_formatTimeStr()):
""" return time as 2004-01-10T00:13:50.000Z """
import sys,time
import types
from datetime import datetime
if (not isinstance(offset,str)):
if isinstance(value, (tuple, time.struct_time,)):
return time.strftime(fmt, val... | 5,333,877 |
def doc_to_tokenlist_no_sents(doc):
""" serializes a spacy DOC object into a python list with tokens grouped by sents
:param doc: spacy DOC element
:return: a list of of token objects/dicts
"""
result = []
for x in doc:
token = {}
if y.has_extension('tokenId'):
parts[... | 5,333,878 |
def _applychange(raw_text: Text, content_change: t.TextDocumentContentChangeEvent):
"""Apply changes in-place"""
# Remove chars
start = content_change.range.start
range_length = content_change.range_length
index = _find_position(raw_text, start)
for _ in range(range_length):
raw_text.pop... | 5,333,879 |
def get_engine():
"""Return a SQLAlchemy engine."""
connection_dict = sqlalchemy.engine.url.make_url(FLAGS.sql_connection)
engine_args = {
"pool_recycle": FLAGS.sql_idle_timeout,
"echo": False,
}
if "sqlite" in connection_dict.drivername:
engine_args["poolclass"] = sqlalche... | 5,333,880 |
def ccw(p0, p1, p2):
"""
Judge whether p0p2 vector is ccw to p0p1 vector.
Return value map: \n
1: p0p2 is ccw to p0p1 (angle to x axis bigger) \n
0: p0p2 and p0p1 on a same line \n
-1: p0p2 is cw to p0p1 (angle to x axis smaller) \n
Args:
p0: base point index 0 and 1 is... | 5,333,881 |
def get_ffmpeg_folder():
# type: () -> str
"""
Returns the path to the folder containing the ffmpeg executable
:return:
"""
return 'C:/ffmpeg/bin' | 5,333,882 |
def test_wrong_code(clean_collection: Callable[[], None]) -> None:
"""Testing when a wrong status code is given."""
sample_res = [
{
"bag": "sample",
"count": 1,
"status": None,
"_key": "dasd165asd46",
}
]
sample_res = pd.DataFrame(sample_r... | 5,333,883 |
def test_add_characteristic():
"""Test adding characteristics to a service."""
service = Service(uuid1(), "Test Service")
chars = get_chars()
service.add_characteristic(*chars)
for char_service, char_original in zip(service.characteristics, chars):
assert char_service == char_original
s... | 5,333,884 |
def decode_typeinfo(typeinfo):
"""Invoke c++filt to decode a typeinfo"""
try:
type_string = subprocess.check_output(["c++filt", typeinfo], stdin=subprocess.DEVNULL)
except FileNotFoundError:
# This happens when c++filt (from package binutils) is not found,
# and with "wine python" on... | 5,333,885 |
def get_nums(image):
"""get the words from an image using pytesseract.
the extracted words are cleaned and all spaces, newlines and non uppercase
characters are removed.
:param image: inpout image
:type image: cv2 image
:return: extracted words
:rtype: list
"""
# pytesseract c... | 5,333,886 |
def create_bag_of_vocabulary_words():
"""
Form the array of words which can be conceived during the game.
This words are stored in hangman/vocabulary.txt
"""
words_array = []
file_object = open("./hangman/vocabulary.txt")
for line in file_object:
for word in line.split():
... | 5,333,887 |
def assert_process_tensor_file(filename: Text) -> None:
"""
Assert that the file is of correct .processTensor form
[see tempo.assert_process_tensor_file() for more details].
Parameters
----------
filename: str
Path to the file.
Raises
------
`AssertionError`:
If the... | 5,333,888 |
def kato_ranking_candidates(identifier: Identifier, params=None):
"""rank candidates based on the method proposed by Kato, S. and Kano, M..
Candidates are the noun phrases in the sentence where the identifier was appeared first.
Args:
identifier (Identifier)
params (dict)
Returns:
... | 5,333,889 |
def _get_bag_of_pos_with_dependency(words, index):
"""Return pos list surrounding index
Args:
words (list): stanfordnlp word list object having pos attributes.
index (int): target index
Return:
pos_list (List[str]): xpos format string list
"""
pos_list = []
def _get_gove... | 5,333,890 |
def fix_time_individual(df):
"""
1. pandas.apply a jit function to add 0 to time
2. concat date + time
3. change to np.datetime64
"""
@jit
def _fix_time(x):
aux = "0" * (8 - len(str(x))) + str(x)
return aux[:2] + ":" + aux[2:4] + ":" + aux[4:6] + "." + aux[6:]
... | 5,333,891 |
def write_sigmf(data_file, data, buffer=None, append=True):
"""
Pack and write binary array to file, with SigMF spec.
Parameters
----------
file : str
A string of filename to be read/unpacked to GPU.
binary : ndarray
Binary array to be written to file.
buffer : ndarray, opti... | 5,333,892 |
def prueba_flujo(regiones, recursos_flujo, flujos, flujos_err, dimension_mesh,\
n_dimension=100, error=1):
"""
Funcion encargada de graficar con matplotlib los vectores eigen versus los
vectores eigen calculados con error.Equivalente a : f12_V_dV_Prueba()
Pametros de entrada:
Salid... | 5,333,893 |
def print_logs(redis_client, threads_stopped, job_id):
"""Prints log messages from workers on all of the nodes.
Args:
redis_client: A client to the primary Redis shard.
threads_stopped (threading.Event): A threading event used to signal to
the thread that it should exit.
job... | 5,333,894 |
def convolve_fft(data, kernel, kernel_fft=False, return_fft=False):
"""
Convolve data with a kernel.
This is inspired by astropy.convolution.convolve_fft, but
stripped down to what's needed for the expected application. That
has the benefit of cutting down on the execution time, but limits
its ... | 5,333,895 |
def segment_nifti(fname_image, folder_model, fname_prior=None, param=None):
"""
Segment a nifti file.
:param fname_image: str: Filename of the image to segment.
:param folder_model: str: Folder that encloses the deep learning model.
:param fname_prior: str: Filename of a previous segmentation that ... | 5,333,896 |
def invoke_alert(browser):
"""fixture to invoke sample alert."""
alert_btn = browser.element('#alert_button')
alert_btn.click()
yield
if browser.alert_present:
alert = browser.get_alert()
alert.dismiss() | 5,333,897 |
def test_another_find():
"""Just to triangulate the search code. We want to make sure
that the implementation can do more than one search, at
least."""
tree = NoAho()
tree.add("Python")
tree.add("PLT Scheme")
tree.compile()
assert (19, 25, None) == tree.find_short(
"I am learnin... | 5,333,898 |
def test_mnnb():
"""
Multinomial Naive Bayes classification.
This checks that MultinomialNB implements fit and predict and returns
correct values for a simple toy dataset.
"""
for X in [X2, scipy.sparse.csr_matrix(X2)]:
# Check the ability to predict the learning set.
clf = Mul... | 5,333,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.