content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def datetime_to_hours(dt):
"""Converts datetime.timedelta to hours
Parameters:
-----------
dt: datetime.timedelta
Returns:
--------
float
"""
return dt.days * 24 + dt.seconds / 3600 | 30,700 |
def create_data_element(ds: "Dataset") -> "DataElement":
"""Return a ``gdcm.DataElement`` for the *Pixel Data*.
Parameters
----------
ds : dataset.Dataset
The :class:`~pydicom.dataset.Dataset` containing the *Pixel
Data*.
Returns
-------
gdcm.DataElement
The convert... | 30,701 |
def thermo_paths(spc_dct, spc_locs_dct, spc_mods, run_prefix):
""" Set up the path for saving the pf input and output.
Placed in a MESSPF, NASA dirs high in run filesys.
"""
thm_path_dct = {}
for spc_name in spc_locs_dct:
spc_thm_path_dct = {}
spc_info = sinfo.from_dct(spc_dct[s... | 30,702 |
def create_da_model_std(filename, eta_rho=10, xi_rho=10, s_rho=1,
reftime=default_epoch, clobber=False,
cdl=None, title="My Model STD"):
"""
Create an time varying model standard deviation file
Parameters
----------
filename : string
name and ... | 30,703 |
def thermoEntry(request, section, subsection, index):
"""
A view for showing an entry in a thermodynamics database.
"""
from rmgpy.chemkin import writeThermoEntry
# Load the thermo database if necessary
loadDatabase('thermo', section)
# Determine the entry we wish to view
try:
... | 30,704 |
def get_clean_iris():
"""
If file exists in data/processed/, recover it
If it doesn't, import and clean it again
Compress it if possible
"""
if os.path.exists(f"{path_}/data/processed/iris.csv"):
print("Retrieving clean data from backup...")
df = pd.read_csv(f"{path_}/data/proces... | 30,705 |
def __string(string, name="", internal=False):
"""
Internal method for basic string validation.
"""
if string is None:
__ex("The %s is missing." % name, internal)
if string == "":
__ex("The %s must not be empty." % name, internal) | 30,706 |
def read_template(filename):
"""[summary]
This function is for reading a template from a file
[description]
Arguments:
filename {[type]} -- [description]
Returns:
[type] -- [description]
"""
with io.open(filename, encoding = 'utf-8') as template_file:
content = template_file.read()
return Template(con... | 30,707 |
def S(a):
"""
Return the 3x3 cross product matrix
such that S(a)*b = a x b.
"""
assert a.shape == (3,) , "Input vector is not a numpy array of size (3,)"
S = np.asarray([[ 0.0 ,-a[2], a[1] ],
[ a[2], 0.0 ,-a[0] ],
[-a[1], a[0], 0.0 ]])
return S | 30,708 |
def bulk_get_subscriber_user_ids(
stream_dicts: Collection[Mapping[str, Any]],
user_profile: UserProfile,
subscribed_stream_ids: Set[int],
) -> Dict[int, List[int]]:
"""sub_dict maps stream_id => whether the user is subscribed to that stream."""
target_stream_dicts = []
for stream_dict in stream... | 30,709 |
def adjust_learning_rate(optimizer, step):
"""Sets the learning rate to the initial LR decayed by 10 every 30 epochs"""
if step == 500000:
for param_group in optimizer.param_groups:
param_group['lr'] = 0.0005
elif step == 1000000:
for param_group in optimizer.param_groups:
... | 30,710 |
def get_menu_permissions(obj):
"""
接收request中user对象的id
:param obj:
:return: 通过表级联得到user或者user所属group对应的菜单信息
"""
menu_obj = Menu.objects # 菜单对象
umids = [x.id for x in UserMenu.objects.get(user=obj).menu.all()]
isgroups = [x.id for x in User.objects.get(id=obj).groups.all()] # 用户所属组
... | 30,711 |
def process_package(
package_path: str,
include_patterns: typing.Optional[typing.List[str]] = None,
exclude_patterns: typing.Optional[typing.List[str]] = None,
) -> SchemaMap:
"""
Recursively process a package source folder and return all json schemas from the top level functions it can find.
Y... | 30,712 |
def plotMaximumElementSize( GraphInstance ):
"""
At the beginning the function cleans the GraphInstance from the previous plot. Then
it adjusts the following lines with corresponding labels and colors on the plot:
MaxElementSize - Lamda
MaxElementSize - Lamda_Eff
MaxElementSize - Ele... | 30,713 |
def find_file(path, include_str='t1', exclude_str='lesion'):
"""finds all the files in the given path which include include_str in their
name and do not include exclude_str
----------
path: path to the directory
path where the files are stored
include_str: string
string which must... | 30,714 |
def init_loopback_devices(loopdevice_numbers):
"""Create and initialize loopback devices."""
for i in six.moves.range(0, loopdevice_numbers):
if not os.path.exists('/dev/loop%s' % i):
subproc.check_call(['mknod', '-m660', '/dev/loop%s' % i, 'b',
'7', str(i)])
... | 30,715 |
def receiver(ip, port, target_loc=None):
"""
receive a file with multi-thread
:param ip: the listening IP
:param port: the listening PORT
:param target_loc: location of file
:return: None
"""
sct = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sct.bind((ip, port))
sct.listen(... | 30,716 |
def parse_datasets(dataset_option, database):
""" Parses dataset names from command line. Valid forms of input:
- None (returns None)
- Comma-delimited list of names
- File of names (One per line)
Also checks to make sure that the datasets are in the database.
"""
... | 30,717 |
def remove_suffix(input_string, suffix):
"""From the python docs, earlier versions of python does not have this."""
if suffix and input_string.endswith(suffix):
return input_string[: -len(suffix)]
return input_string | 30,718 |
def ais_TranslatePointToBound(*args):
"""
:param aPoint:
:type aPoint: gp_Pnt
:param aDir:
:type aDir: gp_Dir
:param aBndBox:
:type aBndBox: Bnd_Box &
:rtype: gp_Pnt
"""
return _AIS.ais_TranslatePointToBound(*args) | 30,719 |
def _shaded_interval_example_1(price_by_date):
"""# Line with datetime x axis"""
# Plot the data
ch = chartify.Chart(blank_labels=True, x_axis_type='datetime')
ch.set_title("Area with second_y_column")
ch.set_subtitle(
"Use alone or combined with line graphs to represent confidence."
)
... | 30,720 |
def set_todays_alarms():
"""This function will set alarms due today
Function takes from a list which stores alarms that were set for a day other than the day they were set.
It check if the alarm is to be set on the current day. If it is it schedules it in the scheduler for the day,
otherwise it does no... | 30,721 |
def unet_deepflash2(pretrained=None, **kwargs):
"""
U-Net model optimized for deepflash2
pretrained (str): specifies the dataset for pretrained weights
"""
model = _unet_deepflash2(pretrained=pretrained, **kwargs)
return model | 30,722 |
def get_bga_game_list():
"""Gets a geeklist containing all games currently on Board Game Arena."""
result = requests.get("https://www.boardgamegeek.com/xmlapi2/geeklist/252354")
return result.text | 30,723 |
def artifact(name: str, path: str):
"""Decorate a step to create a KFP HTML artifact.
Apply this decorator to a step to create a Kubeflow Pipelines artifact
(https://www.kubeflow.org/docs/pipelines/sdk/output-viewer/).
In case the path does not point to a valid file, the step will fail with
an erro... | 30,724 |
async def test_duplicate_device_tracker_removal(hass, mqtt_mock, caplog):
"""Test for a non duplicate component."""
async_fire_mqtt_message(
hass,
"homeassistant/device_tracker/bla/config",
'{ "name": "Beer", "state_topic": "test-topic" }',
)
await hass.async_block_till_done()
... | 30,725 |
def build_status(code: int) -> str:
"""
Builds a string with HTTP status code and reason for given code.
:param code: integer HTTP code
:return: string with code and reason
"""
status = http.HTTPStatus(code)
def _process_word(_word: str) -> str:
if _word == "OK":
retur... | 30,726 |
def pretty_picks_players(picks):
"""Formats a table of players picked for the gameweek, with live score information"""
fields = ["Team", "Position", "Player", "Gameweek score", "Chance of playing next game",
"Player news", "Sub position", "Id"]
table = PrettyTable(field_names=fields)
table... | 30,727 |
def open_path(request):
"""
handles paths authors/
"""
if(request.method == "POST"):
json_data = request.data
new_author = Author(is_active=False)
# Creating new user login information
if "password" in json_data:
password = json_data["password"]
... | 30,728 |
def encode_task(task):
""" Encodes a syllogistic task.
Parameters
----------
task : list(list(str))
List representation of the syllogism (e.g., [['All', 'A', 'B'], ['Some', 'B', 'C']]).
Returns
-------
str
Syllogistic task encoding (e.g., 'AI1').
"""
return Syllog... | 30,729 |
def STOSD(cpu_context: ProcessorContext, instruction: Instruction):
"""Store value in EAX in the address pointed to by EDI"""
value = cpu_context.registers.eax
addr = cpu_context.registers.edi
logger.debug("Storing 0x%X into 0x%X", value, addr)
cpu_context.memory.write(addr, value.to_bytes(4, cpu_co... | 30,730 |
def fuser(name):
"""
A context manager that facilitates switching between
backend fusers.
Valid names:
* ``fuser0`` - enables only legacy fuser
* ``fuser1`` - enables only NNC
* ``fuser2`` - enables only nvFuser
"""
old_cpu_fuse = torch._C._jit_can_fuse_on_cpu()
old_gpu_fuse = t... | 30,731 |
def resize_small(image, resolution):
"""Shrink an image to the given resolution."""
h, w = image.shape[0], image.shape[1]
ratio = resolution / min(h, w)
h = tf.round(h * ratio, tf.int32)
w = tf.round(w * ratio, tf.int32)
return tf.image.resize(image, [h, w], antialias=True) | 30,732 |
def test_01():
"""
Particle on surface.
"""
psf = MicroscopePSF()
rv = numpy.arange(0.0, 1.01, 0.1)
zv = numpy.arange(-1.0, 1.01, 0.2)
fast_rz = psf.gLZRFocalScan(rv, zv)
slow_rz = psf.gLZRFocalScanSlow(rv, zv)
assert numpy.allclose(fast_rz, slow_rz) | 30,733 |
def retry(func_name, max_retry, *args):
"""Retry a function if the output of the function is false
:param func_name: name of the function to retry
:type func_name: Object
:param max_retry: Maximum number of times to be retried
:type max_retry: Integer
:param args: Arguments passed to the functi... | 30,734 |
def test_has_view_change_quorum_number_must_contain_primary_propagate_primary(tconf, tdir):
"""
Checks method _hasViewChangeQuorum of SimpleSelector
It must have f+1 ViewChangeDone and contain a VCD from the next Primary in the case of PrimaryPropagation
Check it for a case of view change (view_change_... | 30,735 |
def configure(
*,
log_callback: Callable[[str], None] = default_log_fn,
connection_pool_max_size: int = DEFAULT_CONNECTION_POOL_MAX_SIZE,
max_connection_pool_count: int = DEFAULT_MAX_CONNECTION_POOL_COUNT,
# https://docs.microsoft.com/en-us/rest/api/storageservices/understanding-block-blobs--ap... | 30,736 |
def encode_randomness(randomness: hints.Buffer) -> str:
"""
Encode the given buffer to a :class:`~str` using Base32 encoding.
The given :class:`~bytes` are expected to represent the last 10 bytes of a ULID, which
are cryptographically secure random values.
.. note:: This uses an optimized strategy... | 30,737 |
def obtain_parameter_values(flow):
"""
Extracts all parameter settings from the model inside a flow in OpenML
format.
Parameters
----------
flow : OpenMLFlow
openml flow object (containing flow ids, i.e., it has to be downloaded
from the server)
Returns
-------
list... | 30,738 |
def logging_sync_ocns(cookie, in_from_or_zero, in_to_or_zero):
""" Auto-generated UCSC XML API Method. """
method = ExternalMethod("LoggingSyncOcns")
method.cookie = cookie
method.in_from_or_zero = str(in_from_or_zero)
method.in_to_or_zero = str(in_to_or_zero)
xml_request = method.to_xml(optio... | 30,739 |
def test_stations_by_distance():
"""Test stations by distance function"""
stations = floodsystem.stationdata.build_station_list()
sorted_list = floodsystem.geo.stations_by_distance(stations, (0, 0))
# check tuple entries are of expected types
for n in sorted_list:
assert type(n[1]) == floa... | 30,740 |
def archive(in_file):
"""
Evaluate the result for the given input parameters, and
archive the results.
"""
(iteration, it_id, result) = process_input(in_file)
archive_output(iteration, it_id, result) | 30,741 |
def story_role(name, rawtext, text, lineno, inliner, options=None, content=None):
"""Link to a JIRA issue.
Returns 2 part tuple containing list of nodes to insert into the
document and a list of system messages.
Both are allowed to be empty.
:param name: The role name used in the document.
:pa... | 30,742 |
def benedict_bornder_constants(g, critical=False):
""" Computes the g,h constants for a Benedict-Bordner filter, which
minimizes transient errors for a g-h filter.
Returns the values g,h for a specified g. Strictly speaking, only h
is computed, g is returned unchanged.
The default formula for the ... | 30,743 |
def enable(configuration_file, section="ispyb"):
"""Enable access to features that are currently under development."""
global _db, _db_cc, _db_config
if _db_config:
if _db_config == configuration_file:
# This database connection is already set up.
return
logging.get... | 30,744 |
def median(f, x, y, a, b):
"""
Return the median value of the `size`-neighbors of the given point.
"""
# Create the sub 2d array
sub_f = f[x - a:x + a + 1, y - b:y + b + 1]
# Return the median
arr = np.sort(np.asarray(sub_f).reshape(-1))
return np.median(arr) | 30,745 |
def build_relevant_api_reference_files(
docstring: str, api_doc_id: str, api_doc_path: str
) -> Set[str]:
"""Builds importable link snippets according to the contents of a docstring's `# Documentation` block.
This method will create files if they do not exist, and will append links to the files that alread... | 30,746 |
def main(args):
"""Load a model with given transforming arguments and transform individual
cases."""
cases = io_functions.load_case_collection(args.data, args.meta)
# cases = cases.sample(1, groups=["CLL", "normal"])
selected_markers = cases.selected_markers
marker_name_only = False
if args... | 30,747 |
def find_zip_entry(zFile, override_file):
"""
Implement ZipFile.getinfo() as case insensitive for systems with a case
insensitive file system so that looking up overrides will work the same
as it does in the Sublime core.
"""
try:
return zFile.getinfo(override_file)
except KeyError:... | 30,748 |
def get_mode(elements):
"""The element(s) that occur most frequently in a data set."""
dictionary = {}
elements.sort()
for element in elements:
if element in dictionary:
dictionary[element] += 1
else:
dictionary[element] = 1
# Get the max value
max_value ... | 30,749 |
def holtWintersAberration(requestContext, seriesList, delta=3):
"""
Performs a Holt-Winters forecast using the series as input data and plots the
positive or negative deviation of the series data from the forecast.
"""
results = []
for series in seriesList:
confidenceBands = holtWintersConfidenceBands(r... | 30,750 |
def get_in_addition_from_start_to_end_item(li, start, end):
"""
获取除开始到结束之外的元素
:param li: 列表元素
:param start: 开始位置
:param end: 结束位置
:return: 返回开始位置到结束位置之间的元素
"""
return li[start:end + 1] | 30,751 |
def remove_special_message(section_content):
"""
Remove special message - "medicinal product no longer authorised"
e.g.
'me di cin al p ro du ct n o lo ng er a ut ho ris ed'
'me dic ina l p rod uc t n o l on ge r a uth ori se d'
:param section_content: content of a section
:return: content... | 30,752 |
def simulate_cash_flow_values(cash_flow_data, number_of_simulations=1):
"""Simulate cash flow values from their mean and standard deviation.
The function returns a list of numpy arrays with cash flow values.
Example:
Input:
cash_flow_data: [[100, 20], [-500, 10]]
number_of_simulations: 3
O... | 30,753 |
def sim_v1(sim_params, prep_result, progress=None, pipeline=None):
"""
Map the simulation over the peptides in prep_result.
This is actually performed twice in order to get a train and (different!) test set
The "train" set includes decoys, the test set does not; furthermore
the the error modes and ... | 30,754 |
def test_normalize_acl_without_acl_attribute():
""" test for resource without __acl__ attribute """
from fastapi_permissions import normalize_acl
assert normalize_acl("without __acl__") == [] | 30,755 |
def apply_function_elementwise_series(ser, func):
"""Apply a function on a row/column basis of a DataFrame.
Args:
ser (pd.Series): Series.
func (function): The function to apply.
Returns:
pd.Series: Series with the applied function.
Examples:
>>> df = pd.Da... | 30,756 |
def is_the_bbc_html(raw_html, is_lists_enabled):
"""
Creates a concatenate string of the article, with or without li elements included from bbc.co.uk.
:param raw_html: resp.content from response.get().
:param is_lists_enabled: Boolean to include <Li> elements.
:return: List where List[0] is a concat... | 30,757 |
def create_empty_module(module_name, origin=None):
"""Creates a blank module.
Args:
module_name: The name to be given to the module.
origin: The origin of the module. Defaults to None.
Returns:
A blank module.
"""
spec = spec_from_loader(module_name, loader=None, origin=ori... | 30,758 |
def _warp_3d_cupy(image, vector_field, mode, block_size: int = 8):
"""
Parameters
----------
image
vector_field
mode
block_size
Returns
-------
"""
xp = Backend.get_xp_module()
source = r"""
extern "C"{
__global__ void warp_3d(float* wa... | 30,759 |
def BitWidth(n: int):
""" compute the minimum bitwidth needed to represent and integer """
if n == 0:
return 0
if n > 0:
return n.bit_length()
if n < 0:
# two's-complement WITHOUT sign
return (n + 1).bit_length() | 30,760 |
def read_many_nam_cube(netcdf_file_names, PREDICTOR_NAMES):
"""Reads storm-centered images from many NetCDF files.
:param netcdf_file_names: 1-D list of paths to input files.
:return: image_dict: See doc for `read_image_file`.
"""
image_dict = None
keys_to_concat = [PREDICTOR_MATRIX_KEY]
fo... | 30,761 |
def logkv(key, val):
"""
Log a value of some diagnostic
Call this once for each diagnostic quantity, each iteration
If called many times, last value will be used.
:param key: (Any) save to log this key
:param val: (Any) save to log this value
"""
Logger.CURRENT.logkv(key, val) | 30,762 |
def test_xapi_connect_singleton(mocker, fake_ansible_module, XenAPI, xenserver):
"""Tests if XAPI.connect() returns singleton."""
mocker.patch('XenAPI.Session')
xapi_session1 = xenserver.XAPI.connect(fake_ansible_module)
xapi_session2 = xenserver.XAPI.connect(fake_ansible_module)
XenAPI.Session.as... | 30,763 |
def rouge_l_summary_level(evaluated_sentences, reference_sentences):
"""
Computes ROUGE-L (summary level) of two text collections of sentences.
http://research.microsoft.com/en-us/um/people/cyl/download/papers/
rouge-working-note-v1.3.1.pdf
Calculated according to:
R_lcs = SUM(1, u)[LCS<union>(... | 30,764 |
def test_id_not_found_delete(flask_client):
"""Tests DELETE with an ID not found"""
response = flask_client.delete(f"/msg-scheduler?id=-10")
assert response.status_code == 200 | 30,765 |
def construct_classifier(cfg,
module_names,
in_features,
slot_machine=False,
k=8,
greedy_selection=True
):
"""
Constructs a sequential model of fully-connected l... | 30,766 |
def size_adjustment(imgs, shape):
"""
Args:
imgs: Numpy array with shape (data, width, height, channel)
= (*, 240, 320, 3).
shape: 256 or None.
256: imgs_adj.shape = (*, 256, 256, 3)
None: No modification of imgs.
Returns:
imgs_adj: Numpy array wit... | 30,767 |
def to_full_model_name(root_key: str) -> str:
"""
Find model name from the root_key in the file.
Args:
root_key: root key such as 'system-security-plan' from a top level OSCAL model.
"""
if root_key not in const.MODEL_TYPE_LIST:
raise TrestleError(f'{root_key} is not a top level mod... | 30,768 |
def is_unique(s: str) -> bool:
"""
Time: O(n)
Space: O(n)
"""
chars: Dict[str, int] = {}
for char in s:
if char in chars:
return False
else:
chars[char] = 1
return True | 30,769 |
def _title(soup):
"""
Accepts a BeautifulSoup object for the APOD HTML page and returns the
APOD image title. Highly idiosyncratic with adaptations for different
HTML structures that appear over time.
"""
LOG.debug('getting the title')
try:
# Handler for later APOD entries
c... | 30,770 |
def is_available() -> bool:
"""Return ``True`` if the handler has its dependencies met."""
return HAVE_RLE | 30,771 |
def test_repr(bond):
"""
Test :meth:`.Bond.__repr__`.
Parameters
----------
bond : :class:`.Bond`
The bond whose representation is tested.
Returns
-------
None : :class:`NoneType`
"""
other = eval(repr(bond), dict(stk.__dict__))
is_equivalent_atom(other.get_atom1(... | 30,772 |
def model_with_buckets(encoder_inputs,
decoder_inputs,
targets,
weights,
buckets,
seq2seq,
softmax_loss_function=None,
per_example_loss=False,
... | 30,773 |
def sqlite_cast(vtype, v):
"""
Returns the casted version of v, for use in
database.
SQLite does not perform any type check or conversion
so this function should be used anytime a data comes
from outstide to be put in database.
This function also handles CoiotDatetime objects and
accept... | 30,774 |
def test_get_atom_infos(case_data):
"""
Test :meth:`.ConstructedMolecule.get_atom_infos`.
Parameters
----------
case_data : :class:`.CaseData`
A test case. Holds the constructed molecule to test and the
correct number of new atoms.
Returns
-------
None : :class:`NoneTyp... | 30,775 |
def test_user_remove_from_team_command(mocker, grafana_client):
"""
Given:
- All relevant arguments for the command that is executed
When:
- user-remove-from-team command is executed
Then:
- The http request is called with the right arguments
"""
http_request = mocker.p... | 30,776 |
def test_references_with_specific_segments(parser, description):
"""
Parse example variants with specifications to a specific annotated segment
of a reference sequence that be given in parentheses directly after the
reference sequence.
"""
parser(description) | 30,777 |
def command_runner(
command, # type: Union[str, List[str]]
valid_exit_codes=None, # type: Optional[List[int]]
timeout=3600, # type: Optional[int]
shell=False, # type: bool
encoding=None, # type: Optional[str]
stdout=None, # type: Optional[Union[int, str]]
stderr=None, # type: Optional... | 30,778 |
def read_table(name):
"""
Mock of IkatsApi.table.read method
"""
return TABLES[name] | 30,779 |
def cosh(x, out=None):
"""
Raises a ValueError if input cannot be rescaled to a dimensionless
quantity.
"""
if not isinstance(x, Quantity):
return np.cosh(x, out)
return Quantity(
np.cosh(x.rescale(dimensionless).magnitude, out),
dimensionless,
copy=False
) | 30,780 |
def dates_from_360cal(time):
"""Convert numpy.datetime64 values in 360 calendar format.
This is because 360 calendar cftime objects are problematic, so we
will use datetime module to re-create all dates using the
available data.
Parameters
----------
time: single or numpy.ndarray of cf... | 30,781 |
def db_queue(**data):
"""Add a record to queue table.
Arguments:
**data: The queue record data.
Returns:
(dict): The inserted queue record.
"""
fields = data.keys()
assert 'request' in fields
queue = Queue(**data)
db.session.add(queue)
db.session.commit()
return... | 30,782 |
def loadMnistData(trainOrTestData='test'):
"""Loads MNIST data from sklearn or web.
:param str trainOrTestData: Must be 'train' or 'test' and specifies which \
part of the MNIST dataset to load.
:return: images, targets
"""
mnist = loadMNIST()
if trainOrTestData == 'train':
X = mni... | 30,783 |
def times_once() -> _Timing:
"""
Expect the request a single time
:return: Timing object
"""
return _Timing(1) | 30,784 |
def test_run_job_batch_as_admin_with_job_reqs(ee2_port, ws_controller, mongo_client):
"""
A test of the run_job method focusing on job requirements and minimizing all other inputs.
Since the batch endpoint uses the same code path as the single job endpoint for processing
job requirements, we only have a... | 30,785 |
def linear_growth(mesh, pos, coefficient):
"""Applies a homotety to a dictionary of coordinates.
Parameters
----------
mesh : Topomesh
Not used in this algorithm
pos : dict(int -> iterable)
Dictionary (pid -> ndarray) of the tissue vertices
coefficient : ... | 30,786 |
def _setup_logging(verbose=False):
"""Initialize logging and set level based on verbose.
:type verbose: bool
:arg verbose: When True, set log level to DEBUG.
"""
log_level = logging.DEBUG if verbose else logging.WARN
logging.basicConfig(format='%(asctime)s [%(levelname)s] %(message)s',
... | 30,787 |
def einstein_t(tini, tfin, npoint, HT_lim=3000,dul=False,model=1):
"""
Computes the *Einstein temperature*
Args:
tini: minimum temperature (K) of the fitting interval
tfin: maximum temperature
npoint: number of points in the T range
HT_lim: high temperature limit where C... | 30,788 |
def normalize_uri(path_uri: str) -> str:
"""Convert any path to URI. If not a path, return the URI."""
if not isinstance(path_uri, pathlib.Path) and is_url(path_uri):
return path_uri
return pathlib.Path(path_uri).resolve().as_uri() | 30,789 |
def RETune(ont: Ontology, training: [Annotation]):
""" Tune the relation extraction class over a range of various values and return the correct
parameters
Params:
ont (RelationExtractor/Ontology) - The ontology of information needed to form the base
training ([Datapoint]) - A collection of ... | 30,790 |
def create_instance(test_id, config, args):
"""
Invoked by TestExecutor class to create a test instance
@test_id - test index number
@config - test parameters from, config
@args - command line args
"""
return TestNodeConnectivity(test_id, config, args) | 30,791 |
def to_me() -> Rule:
"""
:说明:
通过 ``event.is_tome()`` 判断事件是否与机器人有关
:参数:
* 无
"""
return Rule(ToMeRule()) | 30,792 |
def download_process_hook(event: dict):
"""
Allows to handle processes of downloading episode's file.
It is called by `youtube_dl.YoutubeDL`
"""
total_bytes = event.get("total_bytes") or event.get("total_bytes_estimate", 0)
episode_process_hook(
status=EpisodeStatus.DL_EPISODE_DOWNLOADIN... | 30,793 |
def test_divisor_count1():
"""
Tesing for a large number using brute force
"""
num = 12345637
cnt = 0
for i in range(1,num+1):
if(num%i == 0):
cnt = cnt + 1
assert divisor_count(num) == cnt | 30,794 |
def CanonicalPrint(root, stream=sys.stdout, exclusive=False,
inclusivePrefixes=None):
"""
Given a Node instance assumed to be the root of an XML DOM or Domlette
tree, this function serializes the document to the given stream or
stdout, using c14n serialization, according to
http:/... | 30,795 |
def unsaturated_atom_keys(xgr):
""" keys of unsaturated (radical or pi-bonded) atoms
"""
atm_unsat_vlc_dct = atom_unsaturated_valences(xgr, bond_order=False)
unsat_atm_keys = frozenset(dict_.keys_by_value(atm_unsat_vlc_dct, bool))
return unsat_atm_keys | 30,796 |
def recognize_keyword() -> None:
"""
Listens for the keyword, to activate the assistant.
Steps:
1. Listens for audio from the microphone
2. Recognizes the audio using `gTTS`
3. Checks if the keyword (as in `settings.KEYWORD`) is in the audio data (if True, break loop)
"""
g... | 30,797 |
def clip_data(input_file, latlim, lonlim):
"""
Clip the data to the defined extend of the user (latlim, lonlim)
Keyword Arguments:
input_file -- output data, output of the clipped dataset
latlim -- [ymin, ymax]
lonlim -- [xmin, xmax]
"""
try:
if input_file.split('.')[-1] == 'tif... | 30,798 |
async def get_task_authors(url, request_data, session, resp, phid):
"""
:Summary: Get the Phabricator tasks that the user authored.
:param url: URL to be fetched.
:param request_data: Phabricator token and JSON Request Payload.
:param session: ClientSession to perform the API request.
:param res... | 30,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.