content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def jd_from_datetime_utc(datetime_utc=None):
""" Converts a UTC datetime to Julian date. Imported from photrix (E. Dose).
:param datetime_utc: date and time (in UTC) to convert [python datetime object]
:return: Julian date corresponding to date and time [float].
"""
if datetime_utc is None:
... | 59,700 |
def reanalyze_callers(*args):
"""reanalyze_callers(ea_t ea, bool noret)"""
return _idaapi.reanalyze_callers(*args) | 59,701 |
def parallel(*layers):
"""Combinator for composing layers in parallel.
The layer resulting from this combinator is often used with the `FanOut` and
`FanInSum`/`FanInConcat` layers. Based on `jax.experimental.stax.parallel`.
Args:
:layers: a sequence of layers, each an `(init_fn, apply_fn, kernel_fn)`
... | 59,702 |
def get_datastore_identifier(datastore):
"""Revieve the NAA identifiers for the requested datastore object.
Args:
ds(vim.Datastore): Datastore object that the NAA is needed for.
Returns:
naa_ids(set): Returns a set of NAA(s) associated with the datastore.
"""
# The variable 'device... | 59,703 |
def _dataset_factory(pth, task: str) -> object:
"""データセット名に合わせて作成されたディレクトリ内のファイルを読みだす関数
Args:
data_source (str): DataCatalog に保存されているデータセット名と同じ文字列
task (str): 実行するタスク名.例: 'classify'
Returns:
object: 引数で指定した python ソースファイル内に記述されている関数
"""
pth = os.path.join(pth.LIB_DIR, "data... | 59,704 |
def run_pca(mt: hl.MatrixTable, out_prefix: str, overwrite: bool = False):
"""
Run PCA on a dataset
:param mt: dataset to run PCA on
:param out_prefix: directory and filename prefix for where to put PCA output
:return:
"""
pca_evals, pca_scores, pca_loadings = hl.hwe_normalized_pca(mt.GT, k=... | 59,705 |
def get_coeff_eq3(hybrid_category):
"""係数d,e,f
Args:
hybrid_category(str): 電気ヒートポンプ・ガス瞬間式併用型給湯温水暖房機の区分
Returns:
tuple: 式(3)における係数 d,e,f
"""
if hybrid_category == '区分1':
return get_table_g_3()[0][0], get_table_g_3()[1][0], get_table_g_3()[2][0]
elif hybrid_category == '区分2'... | 59,706 |
def bw2sdtrf(bwvol):
"""
computes the signed distance transform from the surface between the
binary True/False elements of logical bwvol
Note: the distance transform on either side of the surface will be +1/-1
- i.e. there are no voxels for which the dst should be 0.
Runtime: currently the funct... | 59,707 |
def kzInterp(data_stack_in, kz_stack_in, kz0, pol_name):
"""
It generates a synthetic SLC stack of acquisitions by interpolating the
original stack of SLC data_stack defined over the kz axis specified by
kz_stack in correspondence of the desired phase-to-height.
Parameters
----------
da... | 59,708 |
def reply_handler(bot, update):
"""Reply message."""
text = update.message.text
user_id = update.message.from_user.id
reply = Olami().nli(text, user_id)
update.message.reply_text(reply) | 59,709 |
def handler(event, context):
"""
This function fetches content from mysql RDS instance
"""
item_count = 0
with conn.cursor() as cur:
cur.execute("select * from package")
for row in cur:
item_count += 1
logger.info(row)
return "selected %d items from RDS p... | 59,710 |
def _map_ragged_tensor_impl(root, root_path,
paths,
operation,
is_repeated, dtype,
new_field_name
):
"""Maps a ragged tensor.
Args:
root: the root of the expression.
ro... | 59,711 |
def test_components():
"""Test components setter."""
assert CompositionBounds().components == set()
assert CompositionBounds(components={"foo", "bar"}).components == {"foo", "bar"}
assert CompositionBounds(components=["foo", "bar"]).components == {"foo", "bar"} | 59,712 |
def ceil(number) -> int:
"""
>>> import math
>>> numbers = [-3.14, 3.14, -3, 3, 0, 0.0, -0.0, -1234.567, 1234.567]
>>> all(math.ceil(num) == ceil(num) for num in numbers)
True
"""
return int(number) if number - int(number) <= 0 else int(number) + 1 | 59,713 |
def update_activity_link_parent_child(data):
"""Update exchange activity links from parent to child (i.e. the current) dataset.
Correct an error in ecoinvent master data production.
In a few cases, an exchange in a child dataset includes an ``activityLink``
to the parent dataset, from which the datase... | 59,714 |
def get_all_areas():
"""Get a dictionary with all findable areas
"""
return sattools.ptc.get_all_areas(["satpy", "fcitools"]) | 59,715 |
def is_valid_unique_product_ids(document: dict) -> bool:
"""Temporary implementation of rule for unique product ids."""
prod_ids = []
for path in uni_pro_ids.CONDITION_JMES_PATHS:
pids = jmespath.search(path, document)
if pids is not None:
prod_ids.extend(pids)
probe = jmespa... | 59,716 |
def cont(i,f,p):
"""
-> Faz uma contagem e mostra na tela
:param i: início da contagem
:param f: fim da contagem
:param p: passo da contagem
:return: sem retorno
"""
c = i
while c <= f:
print(c)
c += p | 59,717 |
def pipe(pvalue, command, **options):
"""
对于给定的PCollection/PTable,返回通过command处理后的PCollection
Args:
pvalue (PCollection/PTable): 输入
command: 命令行
**options: 可配置选项
type: pipe类型,目前支持streaming和bistreaming,默认为streaming
buffer_size: 缓存大小(单条数据),默认64MB
input_fields_num: ... | 59,718 |
def download():
"""
Separate download function so that download can be run separately if there is no internet.
"""
if (not os.path.isfile('ci8b00785_si_001.zip')):
integrative_utilities.download_save(
'https://pubs.acs.org/doi/suppl/10.1021/acs.jcim.8b00785/suppl_file/ci8b00785_si_00... | 59,719 |
def welcome():
"""List all available api routes."""
return (
f"Available Routes:<br/>"
f"/api/v1.0/precipitation<br/>"
f"/api/v1.0/stations<br/>"
f"/api/v1.0/tobs<br/>"
f"/api/v1.0/temp_stats_start/yyyy-mm-dd<br/>"
f"/api/v1.0/temp_stats_start_end/yyyy-mm-dd/yyyy-... | 59,720 |
def reset_ranking_rules(
index: str = Argument(..., help="The name of the index for which to reset the ranking rules"),
url: Optional[str] = URL_OPTION,
master_key: Optional[str] = MASTER_KEY_OPTION,
wait: bool = WAIT_OPTION,
raw: bool = RAW_OPTION,
) -> None:
"""Reset ranking rules of an index.... | 59,721 |
def remove_strange_chars(text):
"""Remove funky characters that don't belong in a URL."""
return re.sub(STRANGE_CHAR_PATTERN, "", text) | 59,722 |
def load_tfrecords(filenames, batch_size=64):
"""Loads a set of TFRecord files
Args:
filenames (str / str[]): TFRecord file(s) extracted
by rosbag_to_tfrecord
Returns:
tf.data.MapDataset
"""
if not filenames or len(filenames) < 1 or filenames[0] == "... | 59,723 |
def train_pretrained(
model_name: str,
from_pretrained: str,
log_name: str,
model_config: None,
data_config: Dict[str, Any],
log_dir: str,
fp16: bool,
device: torch.device,
) -> Tuple[float, float, float]:
"""Train."""
# save model_config, data_config
with open(os.path.join(l... | 59,724 |
def build_projection_operator(l_x, n_dir=None, l_det=None, subpix=1,
offset=0, pixels_mask=None):
"""
Compute the tomography design matrix.
Parameters
----------
l_x : int
linear size of image array
n_dir : int, default l_x
number of angles at whi... | 59,725 |
def check_permissions(accountid, command):
"""
Checks The Permission To Player To Executive Command
Parameters:
accountid : str
command : str
Returns:
Boolean
"""
roles = pdata.get_roles()
if is_server(accountid):
return True
for role in roles:
if accountid in roles[role]["ids"]... | 59,726 |
def validate_cwl_doc(cwl_doc):
"""
This is adapted from cwltool.main.main and avoids the unnecessary stuff by using cwltool.main.main directly.
:param cwl_doc_path:
:return:
"""
if isinstance(cwl_doc, (Path, str)): # Can also be CWLObjectType
cwl_doc = str(cwl_doc)
if not (urlpa... | 59,727 |
def console():
"""Constantly read from stdin and discard"""
try:
while 1:
a = input()
if a == "d":
s.delall()
except (KeyboardInterrupt, EOFError):
socket.socket().connect((socket.gethostname()+".home",80)) | 59,728 |
def train(model, train_loader, optimizer, criterion, step):
"""
train one epoch
"""
for batch in train_loader:
step += 1
optimizer.zero_grad()
left_img = batch['left'].to(device)
right_img = batch['right'].to(device)
target_disp = batch['disp'].to(devic... | 59,729 |
def get_group_followers(group, ignore_permission=False):
"""Returns a list of group member Contacts owned by the members."""
if not ignore_permission:
assert_group_permission(group, 'Group Permission denied')
if not group.is_group:
return []
return _get_follower_contacts(group.user_id... | 59,730 |
def getCensFeatures(XAudio, Fs, hopSize, squareRoot = False):
"""
Wrap around librosa to compute CENs features
:param XAudio: A flat array of raw audio samples
:param Fs: Sample rate
:param hopSize: Hop size between STFT windows
:param squareRoot: Do square root compression?
:returns X: A (1... | 59,731 |
def make_redundant(fastafile,chunk,threads,outdir,tmpdir):
"""
read a non-redundant fasta file, duplicate sequences where necessary and
write one sequence file per taxid
"""
global by_tax
fiter = fasta_chunks(fastafile,chunk)
if not tmpdir:
tmpdir = outdir
for i in range(0,100):
... | 59,732 |
def test_run_zero_coverage():
"""test run when all alleles have zero coverage"""
gtyper = genotyper.Genotyper(20, 40, 0.01)
allele_combination_cov = {}
allele_groups_dict = {"1": {0}, "2": {1}, "3": {0, 1}, "4": {2}}
allele_per_base_cov = [[0], [0, 0]]
gtyper.run(allele_combination_cov, allele_p... | 59,733 |
def comet_magnitude_power_law(h=10., n=4., delta=1., r=1.):
"""The conventional power-law formula to predict a comet's brightness.
Parameters
----------
h : float
Absolute magnitude.
n : float
Activity parameter.
delta : float
Comet's geocentric distance in AU.
r : f... | 59,734 |
def _match_single_exposure_against_pyephem_db(
exposure,
log):
"""*summary of function*
**Key Arguments:**
- ``exposure`` -- the atlas expsosure metadata
- ``log`` -- logger
**Return:**
- None
**Usage:**
.. todo::
add usage info
... | 59,735 |
def setFilterType(filter_type : Literal[0, 1]):
"""
Set Filter Type (1 byte)
filter_type:
- 0 = FILTER_INCLUSIVE
- 1 = FILTER_EXCLUSIVE
Used for:
- RP1210_Set_J1708_Filter_Type (24)
- RP1210_Set_J1939_Filter_Type (25)
- RP1210_Set_CAN_Filter_Type (26)
- RP1210_Set_J1850_Filter_... | 59,736 |
def test_irreg_topo():
"""Test D8 routing on a toy irregular topo."""
fr = FlowRouter(mg)
fr.route_flow()
assert_array_equal(A_target_D8, mg.at_node['drainage_area'])
assert_array_equal(frcvr_target_D8, mg.at_node['flow__receiver_node'])
assert_array_equal(upids_target_D8, mg.at_node['flow__upst... | 59,737 |
def nrms(data_fit, data_true):
"""
Normalized root mean square error.
See: https://nl.mathworks.com/help/ident/ref/goodnessoffit.html
"""
# root_mean_squared_error = np.mean(np.linalg.norm(data_fit - data_true, axis=0), dtype=numpy.float16) # RMSE
# normalization_factor = 2 * np.linalg.norm(da... | 59,738 |
def import_module(rootm, filename, log_function, additional_sys_path=None,
first_try=True):
"""
Imports a module using its filename.
@param rootm root of the module (for relative import)
@param filename file name of the module
@param ... | 59,739 |
def test_from_file_decorator(tmp_path):
""" Test the from_file decorator. """
# create a temp yaml file
yaml_content = """
---
get:
summary: Hello
operationId: hello
responses:
200:
content:
application/json:
schema:
type:... | 59,740 |
def assert_dg_hash(
dg_file: bytes, data_group_hash_values: bytes, hash_alg: str, dg_number_bytes: bytes
) -> bool:
"""
Calculate the hash over the DG file and compare that in the EF.SOD.
"""
dg_number = int.from_bytes(dg_number_bytes, byteorder="big")
# Only hashes for DG1-DG16 exist
if dg_... | 59,741 |
def isPlayerValid(player_id):
"""
check whether player id is valid in the DB
"""
try:
Player.objects.get(id=player_id)
except Player.DoesNotExist:
return False
else:
return True | 59,742 |
def str_format(s, *args, **kwargs):
"""Return a formatted version of S, using substitutions from args and kwargs.
(Roughly matches the functionality of str.format but ensures compatibility with Python 2.5)
"""
args = list(args)
x = 0
while x < len(s):
# Skip non-start token characters... | 59,743 |
def __private_function_example():
"""This is a private function example, which is indicated by the leading
under scores.
:return: tmp_bool"""
tmp_bool = True
return tmp_bool | 59,744 |
def _sympysage_lgamma(self):
"""
EXAMPLES::
sage: from sympy import Symbol, loggamma
sage: assert log_gamma(x)._sympy_() == loggamma(Symbol('x'))
sage: assert log_gamma(x) == loggamma(Symbol('x'))._sage_()
"""
from sage.functions.other import log_gamma
return log_gamma(self.... | 59,745 |
def initialize_raylab(func):
"""Wrap cli to register raylab's algorithms and environments."""
@functools.wraps(func)
def wrapped(*args, **kwargs):
import raylab
raylab.register_all()
return func(*args, **kwargs)
return wrapped | 59,746 |
def drawTree(size, lastX, lastY, angle):
""" Recursively draws the tree, branch by branch, until the branches are shorter than 15 in length """
lineWidth = size * 0.1
angleInRadians = angle * math.pi / 180
nextY = lastY - size * math.cos(angleInRadians)
nextX = lastX + size *... | 59,747 |
def test_cdm_cluster_connection_state_command_when_invalid_arguments_are_provided(client, args, error):
"""Tests invalid arguments for rubrik-cdm-cluster-connection-state."""
from RubrikPolaris import cdm_cluster_connection_state_command
with pytest.raises(ValueError) as e:
cdm_cluster_connection_s... | 59,748 |
def test_show_usage():
""" Test that no subcommand shows the usage """
osa.utils.mktestdir(folder_overrides)
result = click.testing.CliRunner().invoke(
osa.cli.entrypoint, ['dynamic_inventory'])
assert "Usage:" in result.output | 59,749 |
async def pessoa_projeto_edit(
request: Request,
pessoa_projeto_id: int,
pessoa_projeto: PessoaProjetoEdit,
db=Depends(get_db),
pessoa=Depends(get_current_active_pessoa),
):
"""
Update pessoa_projeto
"""
return await edit_pessoa_projeto(db, pessoa_projeto_id, pessoa_projeto, pessoa) | 59,750 |
def ingest(
dtype, shape, colors, data_split, get_buffer, get_local_colors=None
):
"""
Construct a single-column Table backed by a collection of buffers
distributed across the machine.
Each buffer is assumed to cover a disjoint dense subset of a rectangular
n-dimensional domain, and is identifi... | 59,751 |
def add_context_args(parser):
"""Add common workspace and profile args to an argparse parser.
:param parser: The python argparse parser object (or subparser)
:type parser: ArgumentParser
"""
add = parser.add_argument
add_workspace_arg(parser)
add('--profile', default=None,
help='Th... | 59,752 |
def described_as(description: str, matcher: Matcher[Any], *values) -> Matcher[Any]:
"""Adds custom failure description to a given matcher.
:param description: Overrides the matcher's description.
:param matcher: The matcher to satisfy.
:param value1,...: Optional comma-separated list of substitution va... | 59,753 |
def master_CSHORE_run(inputDict):
"""will run CSHORE with any version prefix given start, end, and a simulation duration
Args:
inputDict: keys are:
:key pFlag - plots or not (boolean)
:key analyzeFlag - analyze results or not (boolean)
:key generateFlag - generate input files or not (boolean)... | 59,754 |
def _render_json_dict_jinja(json_dict):
"""Render jinja-templated choice variables in cookiecutter.json dictionary
.. note::
This function only modifies dictionary values that are strings containing
double curly bracket jinja variables such as '{{ varname }}'. All other
dictionary values ... | 59,755 |
def ExpectationTest(test_data_dir): # pylint: disable=invalid-name
"""Mixin for test output generation/comparison."""
class Mixin:
"""Mixin."""
def _load_expected(self, expected_name, actual):
"""Load expected data."""
expected_path = os.path.join(
test_data_dir, f'{self.__class__._... | 59,756 |
def get_random_noise() -> Tuple[Callable[..., Any], int]:
"""Get a random noise augmentation."""
f, (a, b) = choice(NOISE) # noqa S311
return f, choice(range(a, b + 1)) | 59,757 |
def write_section(opts, data):
"""
Writes the data for a credentials section.
Args:
opts (Namespace): Options passed to the utility.
data (dict): Contains the data to be written, indexed by CredentialValue.
"""
with open_base_key(opts) as base_key:
with open_section_key(opts... | 59,758 |
def any_true(iterable) -> bool:
"""Recursive version of the all() function"""
for element in iterable:
if isinstance(element, Iterable):
if not any_true(element):
return True
elif element:
return True
return False | 59,759 |
def test_inherited_constructor():
"""Test that items with an inherited constructor can be deserialized."""
test_cases = [
{"one": 1, "two": 2, "four": 4},
{"one": 1, "two": 2, "three": None, "four": 4},
{"one": 1, "two": 2, "three": 3, "four": 4},
]
for test_case in test_cases:
... | 59,760 |
def load_jhu_data():
"""Wrap load_jhu_data_raw, to make data more useful."""
# vaccine data (from owid)
vac_data = load_owid_vaccinations_data_raw()
country_to_date_to_vac_data = {}
for country_data in vac_data:
country_alpha_3 = country_data['iso_code']
date_to_vac_data = {}
... | 59,761 |
def PrintStartTime(printString):
"""
Print the current time since execution and a msg (printString)
"""
endTime = time.time() - startTime
print str(int(endTime)) + ' s: ' + printString + ' .......'
return endTime | 59,762 |
def metadata_client():
"""Client with metadata interceptor."""
intr = MetadataInterceptor([("this_key", "this_value")])
interceptors = [intr]
special_cases = {
"metadata": lambda _, c: ",".join(
f"{key}:{value}" for key, value in c.invocation_metadata()
)
}
with dumm... | 59,763 |
async def test_emulated_color_temp_group(hass, enable_custom_integrations):
"""Test emulated color temperature in a group."""
platform = getattr(hass.components, "test.light")
platform.init(empty=True)
platform.ENTITIES.append(platform.MockLight("test1", STATE_ON))
platform.ENTITIES.append(platform... | 59,764 |
def __get_type_from_resource(resource_arn):
"""
Récupère le type d'une ressource donnée
:param resource_arn: Ressource AWS arn
:type resource_arn: str
:return: default/maintenance
:rtype: str
"""
return __get_tag_value_from_resource(resource_arn, con... | 59,765 |
def random_gaussian(gene):
"""
Random float from gaussian dist.
Args:
gene (Gene): A gene with a set `mu` and `sig`.
Returns:
float: Random number.
"""
stepped_value = random.normal(loc=gene.mu, scale=gene.sig)
while stepped_value > gene.gene_max or stepped_value < gene.ge... | 59,766 |
def imgshow(img, unnormalize=True):
"""
显示图片
imgshow(image)
imgshow(mask, unnormalize=False)
imgshow(segmap[:, 0:1, ...], unnormalize=False),segmap 每一个通道代表一个面部特征的mask
:param img:输入图片格式的 B,C,H,W.其中C可以为 1
:param unnormalize:去归一化
:return:None
"""
img = torchvision.utils.make_grid(im... | 59,767 |
def group_get_object_permissions_as_int_list(self, instance):
"""
Get a list of strings representing the user's permissions for this object
"""
return self.get_object_perm(instance, 'int_list') | 59,768 |
def put_device(sn):
"""PUT a device"""
data = request.json
i = Instrument.query.filter_by(sn=sn).first()
if i is None:
abort(400)
# Don't update the sn
if 'sn' in data.keys():
data.pop('sn')
# Update the device
i.from_dict(data, partial_update=True)
db.session.add... | 59,769 |
def deserialize(stream_or_string, **options):
"""
Deserialize any string of stream like object into a Python data structure.
:param stream_or_string: stream or string to deserialize.
:param options: options given to lower yaml module.
"""
options.setdefault('Loader', BaseLoader)
try:
... | 59,770 |
def ReadDir(*args):
"""ReadDir(char const * utf8_path) -> char **"""
return _gdal.ReadDir(*args) | 59,771 |
def test_calculate_chpi_positions():
"""Test calculation of cHPI positions."""
# Check to make sure our fits match MF decently
mf_quats = read_head_pos(pos_fname)
raw = read_raw_fif(chpi_fif_fname, allow_maxshield='yes', preload=True)
# This is a little hack (aliasing while decimating) to make it mu... | 59,772 |
def clocks(now=posix_safe_datetimes()):
"""
Build ``twisted.internet.task.Clock`` instances set to a time built by
``now``.
"""
def clock_at_time(when):
c = Clock()
c.advance((when - _POSIX_EPOCH).total_seconds())
return c
return now.map(clock_at_time) | 59,773 |
def loadImages():
"""
Initialize a global directory of images.
This will be called exactly once in the main.
"""
pieces = ['wp', 'wR', 'wN', 'wB', 'wK', 'wQ', 'bp', 'bR', 'bN', 'bB', 'bK', 'bQ']
for piece in pieces:
IMAGES[piece] = p.transform.scale(p.image.load("images/" + p... | 59,774 |
def fetch_matches_loop(url, skill, start_at_match_id, hero):
"""Loop until we find matches. There is a bug in valve API with load
balancing, sometimes the API returns no matches, so we'll re-try a few
times if we expect more matches.
"""
resp = {}
for retry in range(20):
resp = fetch_url... | 59,775 |
def get_recorded_functions_legend_fig():
"""Get Plotly figure used as recorded functions legend.
i.e., whether a mutation has recorded functions
:return: Plotly figure containing indel legend
:rtype: go.Figure
"""
ret = go.Figure(get_recorded_functions_legend_graph_obj())
ret.update_layout... | 59,776 |
def test_add_patch_to_sitecustomize():
"""
Test adding monkey patch snippet to sitecustomize.py (using TestPipEnvironment)
"""
env = reset_env(sitecustomize=patch_urlopen)
if uses_pycache:
# caught py32 with an outdated __pycache__ file after a sitecustomize update (after python should hav... | 59,777 |
def _del_files(fs):
"""Delete files if they exist"""
for f in fs:
try:
os.remove(f)
except OSError:
pass | 59,778 |
def quote_string(s, force=True):
"""Places a string in double quotes, returning the quoted string.
force
Always quote the string, defaults to True. If False then valid
tokens are not quoted but returned as-is.
This is the reverse of :py:func:`decode_quoted_string`. Note that
only the... | 59,779 |
def getMatrix3(eulerdata, inplane=False):
"""
math from http://mathworld.wolfram.com/EulerAngles.html
EMAN conventions - could use more testing
tested by independently rotating object with EMAN eulers and with the
matrix that results from this function
"""
#theta is a rotation about the x-axis, i.e. latitude
# ... | 59,780 |
def constant_value(value_or_tensor_or_var, dtype=None):
"""Returns value if value_or_tensor_or_var has a constant value.
Args:
value_or_tensor_or_var: A value, a `Tensor` or a `Variable`.
dtype: Optional `tf.dtype`, if set it would check it has the right
dtype.
Returns:
The constant value or N... | 59,781 |
def generate_data_batch(batch_size=100, max_seq_length=150, vocabulary=None, embeddings=None, training_split=0.8, train=True):
"""
Generate a random training batch of size batch_size.
"""
df = load_split_amzn_reviews()
train_test_split_idx = int(training_split * len(df))
if train:
df = d... | 59,782 |
def setup_paths():
"""Sets up the necessary paths to collect videos."""
assert FLAGS.dataset
assert FLAGS.mode
assert FLAGS.num_views
# Setup directory for final images used to create videos for this sequence.
tmp_imagedir = os.path.join(FLAGS.tmp_imagedir, FLAGS.dataset, FLAGS.mode)
if not os.path.exist... | 59,783 |
def resourcehandler_backend(env, start_response):
"""Function to handle new wsgi requests
"""
mimetype, extension = _pick_mimetype(env)
headers = [('Content-Type', mimetype), ('Cache-Control', 'no-store'),
('Pragma', 'no-cache'),
('X-Content-Type-Options', 'nosniff'),
... | 59,784 |
def upper_camel(name, split_char="_"):
"""Converts a given name into upper camel case
:param name: The name to be converted
:type name: str
:param split_char: The character that separates words in the name.
:type split_char: str
:return: str
"""
return "".join(w.capitalize() for w in na... | 59,785 |
def _py_gaussian_kernel(ksize=3, sigma=-1.0):
"""Returns a 2D Gaussian kernel.
See cv2.getGaussianKernel for details.
Args:
ksize: aperture size, it should be odd and positive.
sigma: Gaussian standard deviation. If it is non-positive, it is computed
from ksize as sigma = 0.3 * ((ksize - 1) * 0.5 ... | 59,786 |
def abundant(n):
""" A number n is called abundant if the sum of its proper divisors is more
than n. Returns True if n is an abundant number, False otherwise.
"""
return sum(primes.divisors_proper(n)) > n | 59,787 |
def test_attributes_to_openff_molecule():
"""Round trip a molecule to and from its attributes."""
mol: Molecule = Molecule.from_smiles("CC")
attributes = MoleculeAttributes.from_openff_molecule(molecule=mol)
mol2 = attributes.to_openff_molecule()
isomorphic, atom_map = Molecule.are_isomorphic(mo... | 59,788 |
def appres_phase_from_data(survey):
"""
Compute apparent resistivity and phase given impedances
(real and imaginary components)
and the frequency.
"""
data = survey.dobs
frequency = survey.frequency
# data are arranged (Zxy_real, Zxy_imag) for each frequency
Zxy_real = data.reshape((... | 59,789 |
async def test_notebook_no_schema(starter_manager, tmp_notebook):
""" does a notebook without a schema still work?
https://github.com/deathbeds/jupyterlab-starters/issues/26
"""
name = "tmp-notebook"
starter_manager.extra_starters[name] = {
"type": "notebook",
"src": str(tmp_not... | 59,790 |
def get_local_nb_data_storage_writer() -> pickleutils.PickledMapWriter:
"""
Returns a PickledMap writer for the local notebook storage.
"""
path = get_local_nb_data_storage_path()
with pickleutils.PickledMapWriter(path, overwrite_existing=False) as writer:
yield writer | 59,791 |
def ensure_config_path(config_dir, conf_name=berm_const.CONFIG_PATH):
"""Check if config file exists."""
if not os.path.isdir(config_dir):
print((berm_const.ERR_CONFIG).format(config_dir))
sys.exit(1)
config_file = os.path.join(config_dir, conf_name)
if not os.path.isfile(config_file):
... | 59,792 |
def initialize_configurations():
""" Create all files, config and json, that are needed for the project
"""
initialize_json()
initialize_config() | 59,793 |
def remove_space(toks: Collection):
"""
Do not include space for bag-of-word models.
:param list[str] toks: list of tokens
:return: list of tokens where space tokens (" ") are filtered out
:rtype: list[str]
"""
res = []
for t in toks:
if t != " ":
res.append(t)
... | 59,794 |
def defaultkeys(root):
"""keydefs lezen uit keyboard.txt - mapping maken van deze op ...
vooralsnog alleen omschrijving
"""
data = {}
ky = []
ky_desc = ''
join_keys = False
temp = read_lines(root)
for x in temp[6:]:
x = x.rstrip()
if x == "":
b... | 59,795 |
def load_since_ids(cache):
"""Loads most recent Tweet IDs from database to cache"""
since_ids = dict()
db_filenames = glob.glob(os.path.join(DIR_PATH, "data/tweet_sentiment_*.db"))
for db_filename in db_filenames:
conn = sqlite3.connect(db_filename)
conn.row_factory = sqlite3.Row
... | 59,796 |
def _decompose_unit(unit):
"""unit should be a Quantities Dimensionality object
Returns (conversion, base_unit_str)
"""
assert isinstance(unit, pq.dimensionality.Dimensionality)
if len(unit) != 1:
raise NotImplementedError("Compound units not yet supported") # e.g. volt-metre
uq, n = u... | 59,797 |
def run_test(options, argv):
""" Define the test environment and compile the p4 target
Optional: Run the generated model """
assert isinstance(options, Options)
tmpdir = tempfile.mkdtemp(dir=os.path.abspath("./"))
os.chmod(tmpdir, 0o744)
basename = os.path.basename(options.p4filename) # Na... | 59,798 |
def unknown_method_request():
"""Sample unknwon/invalid method request for testing purposes."""
return json.dumps(
{
"method": "some_random_method",
"params": {},
}
) | 59,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.