content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def main(spec, suffix, out_dir, ray_connect, ray_ncpus, job_ngpus,
job_ngpus_eval, job_nworkers, dry_run, child_xvfb):
"""Execute some experiments with Ray."""
# spin up Ray cluster
if job_nworkers is None:
job_nworkers = min(8, max(1, os.cpu_count() // 2))
assert os.cpu_count() % job_n... | 54,100 |
def GetScaleValue(debug=False, file="CONTCAR"):
"""Return lattice scale from a VASP POSCAR/CONTCAR file"""
try:
f = open(file, 'r')
l = f.readline() # title
scale = float(f.readline().split()[0]) # scale
f.close()
return scale
except IOError as err:
print("ERROR: Failed to open CONTCAR or ... | 54,101 |
def get_max_length(captions):
"""从标题字典计算图像标题里面最长的标题的长度
Args:
captions: 一个dict, key为文件名(不带.jpg后缀), value为图像标题list
Returns:
最长标题的长度
"""
lines = to_list(captions)
return max(len(d.split()) for d in lines) | 54,102 |
def test_demo_grammar(sentence):
"""Use the demo grammar from NLTK to make some test cases."""
print(sentence)
assert isinstance(sentence, str) | 54,103 |
def fetch_weekly_utilisation():
"""
Fetch the weekly utilisation data
"""
allmeta = []
for year, target in [('2014', CAB14), ('2013', CAB13)]:
reportpage = _astree(target)
links = reportpage.cssselect('a')
weekly_links = [l for l in links if 'util' in l.get('href', '')]
... | 54,104 |
def diff_all_filter(trail, key=lambda x: x['pid']):
""" Filter out trails with last key appeared before
"""
return trail if key(trail[-1]) not in set([key(c) for c in trail]) else None | 54,105 |
async def main():
"""
Async main method to initialize objects, get console input,
and gather asycn methods to call and run asynchronously
"""
state = type('', (), {})()
state.nodes = {}
state.broadcast = True
state.coordinator = None
state.my_ip = None
state.current_transpor... | 54,106 |
def test_round_special_cases_one_arg_equal_3(arg1):
"""
Special case test for `round(x, /)`:
- If `x_i` is `-infinity`, the result is `-infinity`.
"""
res = round(arg1)
mask = exactly_equal(arg1, -infinity(arg1.shape, arg1.dtype))
assert_exactly_equal(res[mask], (-infinity(arg1.shape... | 54,107 |
def wrap_jiant_forward(
jiant_model: Union[JiantModel, nn.DataParallel],
batch: BatchMixin,
task: Task,
compute_loss: bool = False,
):
"""Wrapper to repackage model inputs using dictionaries for compatibility with DataParallel.
Wrapper that converts batches (type BatchMixin) to dictionaries bef... | 54,108 |
def get_layout_from_drawing(drawing: str) -> tuple[list[Qubit], list[Coupling]]:
"""
Given a valid `drawing`, return the corresponding qubits and couplings. A
valid `drawing` is a string with `X` representing a qubit and one of the
following token `/\|-` to represent a coupling.
Parameters
----... | 54,109 |
def get_dataset(config: Dict):
""" Returns a pytorch dataset from a config. """
assert 'tokenizer' in config
tokenizer = config['tokenizer']
dataset_config = config['dataset']
tokenization_config = config['model']['tokenization']
def encode(instances):
return tokenizer(instances[text_fi... | 54,110 |
async def handle_webhook(hass, webhook_id, request):
"""Handle incoming webhook from Twilio for inbound messages and calls."""
from twilio.twiml import TwiML
data = dict(await request.post())
data['webhook_id'] = webhook_id
hass.bus.async_fire(RECEIVED_DATA, dict(data))
return TwiML().to_xml() | 54,111 |
def get_path() -> Optional[Path]:
"""Determine the current Python runtime path.
:return: The :class:`~pathlib.Path` instance to the current Python path if found
:rtype: Optional[~pathlib.Path]
"""
path_entry = PythonFinder().which("python")
if not path_entry:
return None
return pa... | 54,112 |
def cleanupRanges(a):
"""Remove any range shenanigans, because Python lets you include unneccessary values"""
if not isinstance(a, ast.AST):
return a
if type(a) == ast.Call:
if type(a.func) == ast.Name:
if a.func.id in ["range"]:
if len(a.args) == 3:
# The step defaults to 1!
if type(a.args[2]) ... | 54,113 |
def slowfast101(**kwargs):
"""Constructs a SlowFast-101 model.
"""
model = SlowFast(Bottleneck, [3, 4, 23, 3], **kwargs)
return model | 54,114 |
def flush_all(ipv6=False):
""" Flush all tables """
for table in ('security', 'raw', 'mangle', 'nat', 'filter'):
flush_table(table, ipv6=ipv6) | 54,115 |
def test_stations_highest_rel_level():
"""Tests subroutine stations_highest_rel_level"""
# Build list of stations and get water levels
stations = build_station_list()
update_water_levels(stations)
# Retrieve N stations with highest relative water level
N = 10
highest_stations = stations_hi... | 54,116 |
def add_lxml_syntax_error_context(full_xml, context):
"""
Augment :class:`lxml.etree.XMLSyntaxError` exceptions for
:func:`format_lxml_syntax_error`.
Usage::
with add_lxml_syntax_error_context(full_xml, 'somefile.xml'):
a_function_that_raises_XMLSyntaxError(full_xml)
"""
i... | 54,117 |
def xy(n, image_size):
"""Returns position of pixel n in 2D array"""
x = int(n % image_size)
y = int(math.floor(n / image_size))
return (x,y) | 54,118 |
def filter_contenttypes_by_app(request):
"""
Accepts an app_label as a query_string and returns its associated model set
as JSON in a format designed to fill an in an HTML dropdown menu.
HTTP GET is required.
"""
# If there is not a GET request throw a 404
if not request.GET:
raise Http404
# Seed the re... | 54,119 |
def cot_to_cot_xml(cot: dict, known_craft: dict = {}) -> str: # NOQA pylint: disable=too-many-locals
"""
Given an input CoT XML Event with an ICAO Hex as the UID, will transform the Event's name, callsign & CoT Event
Type based on known craft input database (CSV file).
"""
uid = str(cot.attrib["uid... | 54,120 |
def server_schema(context, **options):
"""
Get information about the server schemas.
Gets information about the schemas and CIM schemas that define the classes
in each namespace. The information provided includes:
* The released DMTF CIM schema version that was the source for the
qualifie... | 54,121 |
def validator_for(_type):
"""
Utility function to create a Type validator callable.
"""
if isinstance(_type, type(None)):
return NoneValidator()
if inspect.isclass(_type) and issubclass(_type, Schema):
return _type
if isinstance(_type, typing._GenericAlias):
base = _typ... | 54,122 |
def get_db_user():
"""Returns the PostgreSQL database user (please don't use the admin 'postgres'),
can be retrieved from env var or configuration file."""
return Config.get_var_value(
env_var="DB_USER", conf_table="database", conf_value="db_user"
) | 54,123 |
def format_labels(label):
"""
Assumes that the label can be split by the '_' character.
:param label:
:return:
"""
side, anatomy = label.split("_")
if side.lower() in ["l", "left"]:
side = "left"
elif side.lower() in ["r", "right"]:
side = "right"
else:
raise... | 54,124 |
def find_definition(view, location, keyword):
"""Find the local definition of a keyword in the view.
Uses the tuple of scopes to search for the local definition of keyword.
Arguments:
view (sublime.View):
the view the keyword is defined in
location (int):
the text p... | 54,125 |
def hide_scale_and_visibility_attributes(node):
"""
Hides scale and visibility attributes of the given node
:param node: str
"""
raise NotImplementedError() | 54,126 |
def add_datacite(pif, dc):
"""
Add datacite metadata to an existing pif (out-of-place)
:param pif: to which metadata should be added
:param dc: dictionary with datacite metadata
:return: new PIF with metadata added
"""
meta_pif = datacite_to_pif(dc)
return merge(pif, meta_pif) | 54,127 |
def is_root(directory):
"""Check if the directory is the root directory.
Args:
directory: The directory to check.
Return:
Whether the directory is a root directory or not.
"""
# If you're curious as why this works:
# dirname('/') = '/'
# dirname('/home') = '/'
# dirname... | 54,128 |
def squiggle_right(meadors):
"""
Uses turtle to fill a line left to right
"""
for cross_space in range(12):
for first_arc in range(2):
meadors.forward(20)
meadors.right(90)
for second_arc in range(2):
meadors.forward(20)
meadors.left(90) | 54,129 |
def test_change_participation_status(client):
"""Test Client.change_participation_status().
:param Client client: Client instance with test data.
"""
calendar_id = "cal_123"
event_uid = "evt_external_439559854"
status = "accepted"
def request_callback(request):
payload = json.loads... | 54,130 |
def test_async_update(gemd_collection, session):
"""Check that async update returns appropriately returns None on success."""
obj = ProcessTemplate(
"foo",
uids={'id': str(uuid4())}
)
fake_job_status_resp = {
'job_type': 'some_typ',
'status': 'Success',
'tasks': [... | 54,131 |
def uploadpartscsv():
"""upload csv files of compounds to the database"""
form = UploadCSVfile()
if form.validate_on_submit():
filename = secure_filename(form.compounds.data.filename)
form.compounds.data.save("app/uploads/" + filename)
filename_read = "app/uploads/" + filename
... | 54,132 |
def alpha_028(code, end_date=None, fq="pre"):
"""
公式:
3*SMA((CLOSE-TSMIN(LOW,9))/(TSMAX(HIGH,9)-TSMIN(LOW,9))*100,3,1)-2*SMA(SMA((CLOSE-TSMIN(LOW,9))/( MAX(HIGH,9)-TSMAX(LOW,9))*100,3,1),3,1)
Inputs:
code: 股票池
end_date: 查询日期
Outputs:
因子的值
"""
end_date = to_date_st... | 54,133 |
def check_np_array(item, field_name, ndim, parent_class, channel_num=None):
"""
Check a numpy array's shape and dtype against required
specifications.
Parameters
----------
item : ndarray
The numpy array to check
field_name : str
The name of the field to check
ndim : int... | 54,134 |
def out_bat_file():
"""
生成bat批处理文件中的部分内容
:return:
"""
taskname = ['01ny',
'020cf',
'10jqka',
'110',
'123',
'163',
'21jrr',
'35mc',
'3773',
'3news',
... | 54,135 |
def class_of ( object ):
""" Returns a string containing the class name of an object with the
correct indefinite article ('a' or 'an') preceding it (e.g., 'an Image',
'a PlotValue').
"""
if isinstance(object, basestring):
return add_article( object )
return add_article( object.__class__._... | 54,136 |
def mean(input, labels = None, index = None):
"""Calculate the mean of the values of the array.
The index parameter is a single label number or a sequence of
label numbers of the objects to be measured. If index is None, all
values are used where labels is larger than zero.
"""
input = numarray... | 54,137 |
def run_md5sum(cwl_input):
"""Pass a local md5sum cwl to the wes-service server, and return the path of the output file that was created."""
endpoint = 'http://localhost:8080/ga4gh/wes/v1/workflows'
params = {'output_file': {'path': '/tmp/md5sum.txt', 'class': 'File'}, 'input_file': {'path': '../../testdata... | 54,138 |
def calculate_svd(data):
"""Calculate Singular Value Decomposition
This method calculates the Singular Value Decomposition (SVD) of the input
data using SciPy.
Parameters
----------
data : numpy.ndarray
Input data array, 2D matrix
Returns
-------
tuple
Left singula... | 54,139 |
def _resubst(value, resubst_dict = {}):
"""Rename placeholders (substrings like ``$name``) in a string value.
:Parameters:
value
the value to process; if it is string it is passed through
placeholder renaming procedure, otherwise it is returned unaltered,
resubst_dict
... | 54,140 |
def die(msg='Something bad happened'):
"""warn() and exit with error"""
warn(msg)
sys.exit(1) | 54,141 |
async def is_alive():
"""is this character alive?"""
return app.state.hp > 0 | 54,142 |
def test_single_site_blacklist():
"""should return result of 'gospider -s "https://42qwerty42.com/" -c 10 -d 5 --blacklist ".(woff|pdf)"'"""
config = ReadConfig.get_all_settings()
output_file_name = "gospider-test_single_site_blacklist.txt"
try:
command = '{} -s "https://{}/" -c 10 -d {} --black... | 54,143 |
def get_app_name():
""" liefert ressource """
return 'resource' | 54,144 |
def list_folders_from_url(url):
"""
List all folders from a remote directory. Ignores all files and hidden
files and folders.
Assumes the URL returns an HTML directory listing.
"""
request = Request(url)
page = requests.get(url).text
soup = BeautifulSoup(page, 'html.parser')
link... | 54,145 |
def get_volume(module, array):
"""Return Volume or None"""
try:
return array.get_volume(module.params["name"])
except Exception:
return None | 54,146 |
def from_nodlink_dat(basename):
"""
Creates the Kgraph from two ascii files (nodes, and links).
Parameters
----------
basename : string
The base name used for the input files.
The input files are named using the following convention:
- basename_nodes.dat: the matrix of 3D ... | 54,147 |
def write_eol(lines, mat, mf, mt, istart=1):
"""
Add end-of-line flags MAT, MF, MT and line number to list of strings.
Returns
-------
`str`
A string that is the sum of the list of strings, i.e. including
eol falgs, separated by the newline character `\n`.
Warns
-----
T... | 54,148 |
def degree_to_radian(degree: float) -> float:
"""
Fungsi ini digunakan untuk mengonversi derajat ke radian.
Rumus : derajat * (pi / 180 derajat)
>>> degree_to_radian(60)
1.0471975511965976
"""
return degree * (math.pi / 180) | 54,149 |
def get_best_matching_metadata(document_row, metadata, logger):
"""TODO: Docstring for get_matching_metadata.
:document_row: TODO
:metadata: TODO
:returns: TODO
"""
logger.info(f'Starting with a metadata list totalling {len(metadata)} items')
meta = [m for m in metadata if str(m['Type']) =... | 54,150 |
def _contains_unbound_typevar(t: Type) -> bool:
"""Recursively check if `t` or any types contained by `t` is a `TypeVar`.
Examples where we return `True`: `T`, `Optional[T]`, `Tuple[Optional[T], ...]`, ...
Examples where we return `False`: `int`, `Optional[str]`, ...
:param t: Type to evaluate.
:r... | 54,151 |
def test_missing_time(timezone: DstTzInfo):
"""
Test that if the designated time does not exist on a day due to a forward DST shift, the day is
skipped entirely.
"""
schedule = CalendarIntervalSchedule(task_id='task', timezone=timezone, days=1, hour=2,
minute... | 54,152 |
def _extract_exactly_one_check_letter_from_string(a_string: str) -> str:
"""
Extracts the check letter out of string that could be a DNI. Will raise an
exception if the string does not represnt a DNI.
:param a_string: the string that contains the check letter.
:return: the check letter found in the... | 54,153 |
def run_preprocessing_pipeline(
svs_file,
xml_file=None,
npy_mask=None,
annotations=[],
out_zarr="output_zarr.zarr",
out_pkl="output.pkl",
no_zarr=False,
):
"""Run preprocessing pipeline. Store image into zarr format, segmentations maintain as npy, and xml annotations as pickle.
Par... | 54,154 |
def get_locations(
db_session: Session = Depends(get_db), # page: int = 1, itemsPerPage: int = 5, q: str = None
page: int = 1,
items_per_page: int = Query(5, alias="itemsPerPage"),
query_str: str = Query(None, alias="q"),
sort_by: List[str] = Query(None, alias="sortBy[]"),
descending: List[bool... | 54,155 |
def spellchecker(bot, trigger):
"""Checks if the given word is spelled correctly, and suggests corrections."""
if not trigger.group(2):
bot.say('What word am I checking?')
return
if trigger.group(2) == bot.nick:
bot.say('Hey, that\'s my name! Nothing wrong with it.')
return
... | 54,156 |
def general_iterator(pc):
"""pc is a pcap.pcap object that listens to the network and returns a packet object when it hears a packet go by"""
fl = fcntl.fcntl(sys.stdin.fileno(), fcntl.F_GETFL)
fcntl.fcntl(sys.stdin.fileno(), fcntl.F_SETFL, fl | os.O_NONBLOCK)
try:
for ts, pkt in pc: ##il fat... | 54,157 |
def p_ifA(p):
"""
ifA :
"""
global running
# If current state is not running
if not running[-1]:
running.append(False)
# Push evaluated value as running state
else:
running.append(p[-3]) | 54,158 |
def test_get_labware_location(
well_plate_def: LabwareDefinition,
store: StateStore,
) -> None:
"""It should return all labware."""
load_labware(
store=store,
labware_id="plate-id",
location=DeckSlotLocation(slot=DeckSlotName.SLOT_1),
definition=well_plate_def,
ca... | 54,159 |
async def login_by_user_pwd(form_data: OAuth2PasswordRequestForm = Depends()) -> Token:
"""
OAuth2 compatible token login, get an access token for future requests
"""
user: User = authenticate(form_data.username, form_data.password)
logger.info(f'User[{user.name}] signed in.')
access_token_expires = timedelta(min... | 54,160 |
def run_sync(sbl):
"""
Synchronises the local database with the remote google servers.
Takes a SafeBrowsingList Object as an argumant.
"""
try:
sbl.update_hash_prefix_cache()
except (KeyboardInterrupt, SystemExit) as e:
log.info('Shutting down')
sys.exit(0)
except Exc... | 54,161 |
def tudo_separados(dirImagens, folder_name, tipoGrafico, bar_empilha, dirFiles, confTipoGrafico, numPilares, minY, maxY, Freqmax, files):
"""
Le os ficheiros comos valores. Chama ``desenho()`` para fazer o plot. Aplica as especifiçaões do grafico presentes no .conf em ``Specs = {}``.
Guarda os graficos gerados chama... | 54,162 |
def get_news_list():
"""
1.获取参数
2.校验参数
3.查询数据库
4.返回数据
:return:
"""
# 1.获取参数,2. 校验参数
try:
cid = request.args.get('cid', 1, type=int)
page = request.args.get('page', 1, type=int)
per_page = request.args.get('per_page', 10, type=int)
except Exception as e:
... | 54,163 |
def get_tf_map(source, indent_size, indent_level=0):
"""Turn dict object into a tf map"""
outer_line_prefix = "".rjust(indent_level * indent_size)
inner_line_prefix = "".rjust((indent_level + 1) * indent_size)
formatted = "{\n"
tf_items = []
for key in source:
item = get_tf_item(source[k... | 54,164 |
def invoke(name, payload=None, invoke_type=INVOKE_TYPE_REQUEST_RESPONSE, logs=False, context=None):
"""
Invokes a Lambda function.
:param name: The name or ARN of the function
:param payload: A dict or JSON string that you want to provide to the Lambda function
:param invoke_type: The invocation typ... | 54,165 |
def test_close_nonce_zero(
get_accounts,
token_network,
create_channel,
create_balance_proof,
):
""" closeChannel with a balance proof with nonce zero should not change the channel state """
(A, B) = get_accounts(2)
vals_B = ChannelValues(
deposit=20,
transfer... | 54,166 |
def segmentation_blocks_test_b(band_pass_signal_hr, sb, sh, dim):
"""THIS SECTION REMAINS FOR TESTING PURPOSES
Function used for the segmentation of the signal into smaller parts of audio (blocks). This has been implemented
as described in formula F.16 (section F.3.5) of Annex F (ECMA-74). It has some ... | 54,167 |
def _depthwise_conv_block(inputs, pointwise_conv_filters, alpha,
depth_multiplier=1, strides=(1, 1), block_id=1):
"""Adds a depthwise convolution block.
A depthwise convolution block consists of a depthwise conv,
batch normalization, relu6, pointwise convolution,
batch normaliz... | 54,168 |
def _decide_sort_field_args(args):
"""Auto-correct else reject contradictions among which sort column to sort"""
# Reject contradictions
# FIXME: sort by multiple columns
vote_ext = "-X" if args.X else ""
vote_none = "-f" if args.f else ""
vote_size = "-S" if args.S else ""
vote_sort = "--... | 54,169 |
def _ValidateExperimentGroup(experiment_group, create_message_fn):
"""Validates one group of one config in a configuration entry."""
name = experiment_group.get('name', '')
if not name or not isinstance(name, unicode):
return create_message_fn('Missing valid name for experiment')
# Add context to other mes... | 54,170 |
def updater(key, recv, local):
"""use updater: +="""
local += recv | 54,171 |
def multikey_sort(lst, keys, reverses=None, start=None, stop=None):
"""
Sort the given list by the given keys, only evaluating the next key
if the previous led to ties.
"""
if not keys or not lst:
return
if not reverses:
reverses = (False,) * len(keys)
if start is None:
... | 54,172 |
def quit_game():
"""
Quit the game
"""
pg.quit()
quit() | 54,173 |
def read_kml_placemark(kml):
"""
Returns geometry from Google Earth KML file.
:param str kml: KML file name without directory.
:rtype: dict
:return: Geometry dict.
"""
config = seisnn.utils.Config()
kml_file = os.path.join(config.geom, kml)
parser = etree.XMLParser()
root = etr... | 54,174 |
def check_files(file_paths):
"""Verifica todos os arquivos da lista de caminhos de arquivo.
Args:
file_paths (List[str]): Lista com caminho para os arquivos.
"""
for file_path in file_paths:
logging.info(f'Verificando o arquivo {file_path}')
with open(os.path.join(DIR, file_path... | 54,175 |
def ne_groupnodes(n, e):
"""Group nodes with same line number."""
nl = n[n.lineNumber != ""].copy()
nl.lineNumber = nl.lineNumber.astype(int)
nl = nl.sort_values(by="code", key=lambda x: x.str.len(), ascending=False)
nl = nl.groupby("lineNumber").head(1)
el = e.copy()
el.innode = el.line_in
... | 54,176 |
def make_vct_file(res_fn=res_file, outfn=vct_file):
"""
Make vct file for re-formatting lev.
:param res_fn:
:param outfn:
:return:
"""
res_f = xr.open_dataset(res_fn)
hyai = 'hyai'
hybi = 'hybi'
hyai_da = res_f[hyai].values
hybi_da = res_f[hybi].values
outfile = open(str... | 54,177 |
def parse_container(node):
"""Returns containerised data of a node
Reads the imprinted data from `containerise`.
Arguments:
node (nuke.Node): Nuke's node object to read imprinted data
Returns:
container (dict): imprinted container data
"""
data = lib.get_avalon_knob_data(node)... | 54,178 |
def LoginCGI(login_url,
email,
admin,
action,
set_email,
set_admin,
continue_url,
outfile):
"""Runs the login CGI.
This CGI does not care about the method at all. For both POST and GET the
client will be redirected to the ... | 54,179 |
def get_gas_status_plot(solution):
"""
@ solution: a solution list, format [(x, rho, v, p)...]
"""
# prepare list for x, rho, v and p
list_x = []
list_rho = []
list_v = []
list_p = []
for i in solution:
list_x.append(i[0])
list_rho.append(i[1])
list_v.append(i... | 54,180 |
def propagate_masks(
mask,
param_names = WEIGHT_PARAM_NAMES
):
"""Accounts for implicitly pruned neurons in a model's weight masks.
When neurons are randomly ablated in one layer, they can effectively ablate
neurons in the next layer if in effect all incoming weights of a neuron are
zero. This method a... | 54,181 |
def ControlFromPoint(x, y):
"""use IUIAutomation ElementFromPoint x,y, may return 0 if mouse is over cmd's title bar icon"""
element = _AutomationClient.instance().dll.ElementFromPoint(x, y)
return Control.CreateControlFromElement(element) | 54,182 |
def download_file(url, current_dir):
"""
Attempt to download file from URL using sane buffer and write to file
:param file: input URL
:return: full path to downloaded file
"""
file_name = url.split('/')[-1]
response = urlopen(url)
if response.status != 200:
raise DownloadError(
... | 54,183 |
def _get_output_dir(output_dir, chunk_arr, name_arr):
"""Get the directory for the output cutout data."""
# Check the output directory
if not os.path.isdir(output_dir):
raise ValueError("Output directory '{:s}' does not exist".format(output_dir))
return [os.path.join(output_dir, str(chunk),... | 54,184 |
def parse_list(lines):
"""
Iterate over list lines
yields tuples (flags:set, sep:str, name:str)
"""
for line in lines:
match = list_re.match(line)
if match:
flags, sep, name = match.group(1, 2, 3)
yield set(flags.split()), unquoted(sep), name | 54,185 |
def sort_fits_by_keyword(keyword=''):
"""Moves files into directory named for their filter.
Parameters:
keyword : string
The header keyword you want to sort files by.
Returns:
nothing
Outputs:
nothing
"""
keyword = str(keyword)
keyword = keyword.upper()
ke... | 54,186 |
def extract_and_hide_tables_from_image(image: np.ndarray, lang: str) -> Tuple[np.ndarray, List[LocatedTable]]:
"""
Detects and returns tables in images using opencv for structure detection
and pytesseract for cell content detection.
Then hides detected tables from the original image.
Parameters
... | 54,187 |
def execandcombine(command):
"""execute a shell command, and return all output in a single string."""
data = execandcapture(command)
return "\n".join(data) | 54,188 |
def adjacency_matrix_view(request):
"""Renders adjacency matrix.
Uses transmission events data stored in session.
:param request: Contains organism_groups_list.
:return: Render of adjacency matrix.
:rtype: HttpResponse
"""
organism_groups_list = json.loads(request.GET["organism_groups_list... | 54,189 |
def unauthorized(errormsg=''):
"""Create a response with HTTP status code 401 - Unauthorized."""
return make_json_response(
status=401,
success=0,
errormsg=errormsg
) | 54,190 |
def get_revolution_period(accelerator):
"""."""
return 1 / get_revolution_frequency(accelerator) | 54,191 |
def topmost_post(subreddits):
"""Returns the highest-upvoted post of all subreddits."""
tops = all_top_posts(subreddits)
top = tops[0]
for submission in tops:
if submission.score > top.score:
top = submission
return [top] | 54,192 |
def sub(a_t, b_t):
"""
sub operator a-b
"""
return sub_op(a_t, b_t) | 54,193 |
def dog_names_create(dataImagesTrain=os.path.join(cfg.DATA_DIR,
cfg.Dog_DataDir,
'train','*'),
dog_names_path=cfg.Dog_LabelsFile):
"""
Function to create dog_names file based on sub-director... | 54,194 |
def normalize(data, signal_type, carrada_path, norm_type='local'):
"""Function to normalize the input data.
Note that the 'train' and 'tvt' norm methods requires specific files
containing statistics on the dataset.
PARAMETERS
----------
data: torch tensor
Matrix to normalize
signal_... | 54,195 |
def create_sample_db(ntables):
"""
Create a python description of a sample database
"""
rv = {}
for i in range(1, ntables + 1):
rv["table%s" % i] = {
"columns": [
{
"name": "id",
"type": "integer",
"use_s... | 54,196 |
def listflat(path, ext=None):
"""
List files without recursion
"""
if os.path.isdir(path):
if ext:
if ext == 'tif' or ext == 'tiff':
files = glob.glob(os.path.join(path, '*.tif'))
files = files + glob.glob(os.path.join(path, '*.tiff'))
else... | 54,197 |
def get_result(
data: AnnData,
key: str,
params: bool = False,
) -> Union[pd.DataFrame, Tuple[pd.DataFrame, Dict]]:
"""Read spatialtis result from `AnnData.uns` as `pandas.DataFrame` object
To get the params, use `params=True`
Args:
data: The `AnnData` object for storage
key: W... | 54,198 |
def update(
release,
):
""" Update arcus mgr """
click.echo("Updating arcus mgr to version: {}".format(release))
arcus_common.update(release, "mgr") | 54,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.