content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def main() :
"""
Main function for parsing Kindle JSON export to markdown.
"""
try :
( input_filename, output_filename ) = parse_command_line_arguments()
kindle_data = parse_json_file( input_filename )
markdown_text = kindle_to_md( kindle_data )
write_output( markdown_tex... | 68,500 |
def get_block_header_by_hash(block_hash, db):
"""
Returns the header for the parent block.
"""
return db.get_block_header_by_hash(block_hash) | 68,501 |
def extract_meta_lang(html):
"""
Returns the meta_lang of the HTML provided or None if unsuccessful
:param html:
:return: meta_lang | None
"""
meta_lang = None
try:
goose_config = {'enable_image_fetching': False}
goose = Goose(goose_config)
article = goose.extract(r... | 68,502 |
def import_file(name, location):
"""
Imports the specified python file as a module, without explicitly
registering it to `sys.modules`.
While puzzle-solvers uses Python 3 features, you are free to try to
install it in a Python 2 environment.
"""
if sys.version_info[0] == 2:
# Python... | 68,503 |
def collect_data(post_id, duration):
"""
Collects data every 30 secs for {duration} hours on post with {post_id}.
Stores data as a list of objects. Each object contains the number of likes
the post has and the time in secs.
Args:
post_id: String -- id of the post to track
duration: Int -- A... | 68,504 |
def clean_up():
"""
Try to clean up after a test failure.
:return: None
"""
_StratisCli.destroy_all()
assert _StratisCli.pool_list() == [] | 68,505 |
def filter_tags(tags: dict, tag_filter: dict) -> bool:
"""filter tags based on a tag filter"""
including = False
includes = tag_filter['includes']
if 'tag-keys' in includes:
including = any(key in tags for key in includes['tag-keys'])
if not including:
if 'tag-key-values' in include... | 68,506 |
def load_ls(ls_path,px_size=1.):
"""Loads a linescan file
Args:
ls_path (str): path of the average linescan file to be loaded
px_size (float): pixel size in microns
Returns:
x (numpy array): the positions (in microns)
i (numpy array): the intensities
"""
ls_data =... | 68,507 |
def add_frame_div_parent(cell_info):
"""
Adds the frame a cells parent divides on to cell info.
Args:
cell_info (dict): dict that maps cells to cell info
Returns:
dict: cell info with added frame_div_parent
"""
new_info = cell_info.copy()
for info in new_info.values():
... | 68,508 |
def _binary_search(alloc, p, d):
"""Compute step length using the binary search long step from BGKL.
Parameters
----------
alloc: AllocationProblem
Allocation problem instance
p: np.ndarray
Price vector.
d: np.ndarray
direction vector s.t. d in {0,1}^n.
Retu... | 68,509 |
def feature_engg(df: pd.DataFrame) -> pd.DataFrame:
"""Feature engineering function"""
numeric_feats = df.dtypes[df.dtypes != "object"].index
skewed_feats = df[numeric_feats].apply(
lambda x: skew(x.dropna())
) # compute skewness
skewed_feats = skewed_feats[skewed_feats > 0.75]
skewed_f... | 68,510 |
def upsample(layer, k, s, layer_name):
""" Return the output of transpose convolution given kernel_size k and strides s """
return tf.layers.conv2d_transpose(inputs = layer,
filters = NUMBER_OF_CLASSES,
kernel_size = (k, k),
... | 68,511 |
def get_data_size_recursively(data) -> int:
"""
Deprecated (Only for revision 2 and below).
Returns size of data(input data or deploying content) by recursive traversal
:param data: input data or deploying content
:return: size of data
"""
size = 0
if data:
if isinstance(data, d... | 68,512 |
def print_genres(genres_list):
"""
Печатает в форматированном виде список доступных жанров,
полученный из функции get_genres()
genres: ответ от функции get_genres(), который нужно распечатать
"""
print("Список жанров, в которых можно продолжить фразу:")
for genre_info in genres_list:
... | 68,513 |
def _to_array_1d(scalar_or_array, arrlen, dtype=float):
"""
A helper function for writing forces that can accept either a single parameter,
or an array of per-particle parameters.
If passed a scalar, it converts it to an array of the length arrlen.
If passed an iterable, it verifies that its leng... | 68,514 |
def train(BATCH_SIZE):
"""Train the model."""
(X_train, y_train), (X_test, y_test) = load_cifar_10()
X_train = 2 * X_train - 1 # fall in the interval [-1, 1]
discriminator = discriminator_model()
generator = generator_model()
discriminator.trainable = False
discriminator_on_generat... | 68,515 |
def generate_entropy(strength: int = 128) -> str:
"""
Generate entropy hex string.
:param strength: Entropy strength, default to 128.
:type strength: int
:returns: str -- Entropy hex string.
>>> from pybytom.utils import generate_entropy
>>> generate_entropy(strength=128)
"ee535b143b0... | 68,516 |
def add_datafile2session(db_session, date_obs, data_provider, data_type, fname_raw,
fname_hdf="", flag=0):
"""
:param db_session: sqlalchemy.orm.session.Session
SQLAlchemy session object
:param date_obs: datetime.datetime
The observation ... | 68,517 |
def build_objects(object_layers, object_surfs, object_tags, object_name, add_subd_mod, skel_to_arm, use_existing_materials):
"""Using the gathered data, create the objects."""
ob_dict= {} # Used for the parenting setup.
print("Adding %d Materials" % len(object_surfs))
for surf_key in object_surfs:
... | 68,518 |
def currentTime(*args, **kwargs):
""" Current time """
pass | 68,519 |
def gingerbreadman(n_points: int = 10**6, x_0: float = 1.5, y_0: float = 2.6) -> PlotData:
"""
Calculates a list of (x, y) points according to the Gingerbreadman Map
https://en.wikipedia.org/wiki/Gingerbreadman_map
:param n_points: The number of (x, y) plot points to calculate
:param x_0: The horiz... | 68,520 |
def focal_starting_points(
recording_meta: dict,
seizure_types: list = None):
"""Return a list of dictionaries which contain the focal events.
Here the interest is only on the starting points.
Args:
recording_meta: a dictionary which contains the metadata
of the recording.
... | 68,521 |
def nanmean(arr, dim=None, keepdim=False):
"""
Compute the mean of an array ignoring any NaNs.
RH 2021
"""
if dim is None:
kwargs = {}
else:
kwargs = {
'dim': dim,
'keepdim': keepdim,
}
nan_mask = torch.isnan(arr)
arr_no_nan = arr.mask... | 68,522 |
def max_area_index(labels, num=None):
"""
Return index of maxmum labeled area
"""
mx = 0
mxi = -1
un = np.unique(labels)
# kick out zero
un = un[un != 0]
for l in un:
mxtmp = np.sum(labels == l)
if mxtmp > mx:
mx = mxtmp
mxi = l
return mxi | 68,523 |
def build_docker(c, nocache=False, pull=False, ros_distro="foxy", image_name=MODULE_NAME):
"""
Build Docker image of this component
"""
col = Collection()
col.add_task(build_env)
col['build_env'](c, nocache=nocache, pull=pull, ros_distro=ros_distro, image_name=image_name)
iname, tag = g... | 68,524 |
def basic_cell(args, i, unit_mul):
""" Construct the basic cell. """
c = tf.contrib.rnn.LSTMCell(
args['num_units']*unit_mul,
# dropout_keep_prob=args['dropout']
)
c = tf.contrib.rnn.DropoutWrapper(
cell=c, input_keep_prob=(1.0 - args['dropout']))
if i > 1:
c = ... | 68,525 |
def pathToApp(location, app):
"""Return path to the app in the given location/repository."""
return os.path.join(repositoryRoot(), location, 'apps', app) | 68,526 |
def get_msg_time(msg, zerotime):
""" Переводит бортовое время сообщения в текущее
С учетом того, что когда на борту было 0, на земле было (какбудто) zerotime
и с учетом того, что настоящее время тикает в дробных секундах
"""
if hasattr(msg, "time_boot_ms"):
return msg.time_boot_ms /... | 68,527 |
def print_stats(report_count, file_stats, severity_stats):
"""Print summary of the report statistics."""
print("\n----==== Summary ====----")
if file_stats:
vals = [[os.path.basename(k), v] for k, v in
list(dict(file_stats).items())]
vals.sort(key=itemgetter(0))
keys ... | 68,528 |
def mari_normalise_background(background_int, white_int, second_white_int=None):
"""Normalize the background integrals"""
if second_white_int is None:
if background_int.getNumberHistograms() == 919 and white_int.getNumberHistograms() == 918:
background_int = CropWorkspace(background_int, Sta... | 68,529 |
def check_modules():
""" This verifies modules are installed"""
pass | 68,530 |
def getAuditLogsWithDecision(decisionUuid, user):
"""
expected: decisionUuid(string), user(object)
result: all audit logs objects that attached to a decision \
would be returned in a json.
"""
data = dict()
if decisionUuid == '' or not user:
msg = "checklistUuid or user == None"
... | 68,531 |
def db_create(db_path="main.db"): # noqa: D205, D400
"""Check that the database doesn't exist, create the database, create the
tables, finally connect to the database.
Use os.path.isfile() on the database path to check if the file exists.
Connect to the database. Set the conn.isolation_level to No... | 68,532 |
def signal_wrapper(func):
"""
Signal fail-safe wrapper
:param func: original signal
:return: fail-safe signal function
"""
@functools.wraps(func)
def _signal_wrapper(*args, **kwargs):
"""
Wraps original signal wrapper with try
"""
try:
return func(... | 68,533 |
def event_owned_by_current_user(instance_id: int):
"""Preprocessor for api event DELETE endpoint.
Ensures event can only be deleted by a user with role 'owner'
:param instance_id: id of instance to be deleted
:raises ProcessingException: if current_user is not an owner of the event
:return:None
... | 68,534 |
def test_file_discovery(musicdir):
"""Test all files in the directory are found."""
all_files_in_dir = sorted(str(file_) for file_ in musicdir.visit()
if file_.check(dir=0))
found_files_in_dir = sorted(collect_files(str(musicdir)))
assert all_files_in_dir == found_files_in_... | 68,535 |
def kml_to_dict(kml_file):
"""
Reads the supplied KML file and returns a dictionary with datetime
keys and descriptions/coordinates (lists of (lon,lat,ele) tuples) as
values. Can contain one level of subfolders as subdictionaries.
"""
print(f"Reading KML from \"{kml_file}\"...")
def placema... | 68,536 |
def test_get_shapes_from_elem(initialize_maya): # @UnusedVariable
""" Test for the get_shapes_from_elem method """
# create a sphere with a skin cluster
mesh = cmds.polySphere(name='my_test_sphere_MESH', ch=True)
skin_joint = cmds.createNode('joint', name='my_test_joint')
cmds.skinCluster(skin_joi... | 68,537 |
def _harvest_files(prospectors, logger):
"""Traverse all specified prospector paths and determine uncataloged files."""
discovered_files = []
# List of files specified explicitly in the prospectors
absolute_file_paths = [path for x in prospectors for path in x['paths'] if isfile(path)]
for prospect... | 68,538 |
def parse_result_file(result_file: str) -> float:
"""Load mIoU from .txt result file."""
if not os.path.isfile(result_file):
if VERBOSE:
print(result_file + " does not exist!")
return 100000
with open(result_file, "r") as f:
tmp = f.readlines()[0]
miou = tmp.spli... | 68,539 |
def get_stock_data(manager, ticker, unwantedFields, function=api.iex_5y):
"""
Adds 5-year technicals to the 'AlgoTradingDB' database
for the specified stock.
:param ticker: stock ticker
:return: None
"""
stockData = function(ticker)
for datapoint in stockData:
newDoc = MongoDocum... | 68,540 |
def test_empty_servers(client_l):
"""Start with a blank DB"""
rv = client_l.get('/api/servers')
assert len(rv.json['payload']['items']) == 0 | 68,541 |
def read_bam(bamfilePath):
"""Reads a .bam line by line"""
logging.debug(
'[DEBUG] (read_bam) Launching samtools in subprocess to yield the lines of the bamfile {}'.format(bamfilePath))
# Samtools must be installed !
cmd = 'samtools view '+os.path.realpath(bamfilePath)
logging.debug('[DEBUG]... | 68,542 |
def load_intron_vector(table, session):
"""
load intron vector entries for this gene. Wrapper for generic_gene_query.
:param table: One of the intron vector tables
:param session: Active sqlalchemy session.
:return: DataFrame
"""
assert any(table == cls for cls in (TmIntronSupport, AugCgpInt... | 68,543 |
def load_class_info(splits_dir):
"""
Load list of class names
Returns
-------
Numpy array of shape (N) containing strs with class names
"""
print("Loading class info...")
class_info = np.genfromtxt(os.path.join(splits_dir, 'info.txt'), dtype='str', delimiter='/n')
return class_info | 68,544 |
def polar_err(r, phi, r_e, phi_e):
"""polar errors for r and phi"""
# print(r, phi, r_e, phi_e)
dxdr = np.cos(phi)
dxdphi = r * np.sin(phi)
dydr = np.sin(phi)
dydphi = -r * np.cos(phi)
x_e = np.sqrt((dxdr * r_e) ** 2 + (dxdphi * phi_e) ** 2)
y_e = np.sqrt((dydr * r_e) ** 2 + (dydphi * ph... | 68,545 |
async def get_textchannel_chatlog(text_channel: discord.TextChannel, limit: int = None):
"""
Returns a TextChannel chatlog
:param text_channel: The text channel for the data to be gathered from
:param limit: An integer to limit the amount of messages retrieved.
:return: String
"""
all_messa... | 68,546 |
def clean_sort(words):
"""A function for cleaning and prepping words for techniques.
Args:
words (list): The list of words
Returns:
list: An updated word list with words cleaned and sorted.
"""
if isinstance(words, basestring):
return words
chars = '!"#$%\'()*+,._/:;<=>... | 68,547 |
def add_request_logger(logger):
"""
Add logging functionality to a request function.
Only shows logs for `JINA_LOG_LEVEL` > info.
You can set this as an env variable before starting your `Jina` application.
Example usages:
>>> from jina import Executor, requests
>>> my_logger = JinaLogger('... | 68,548 |
def source_to_neutrino_direction(azimuth, zenith, radian=True):
"""Flip the direction.
Parameters
----------
zenith : float
neutrino origin
azimuth: float
neutrino origin
radian: bool [default=True]
receive + return angles in radian? (if false, use degree)
"""
a... | 68,549 |
def _process_stubs_section(segstart, make_thunk, next_stub):
"""Process all the functions in a __stubs section."""
segend = idc.SegEnd(segstart)
# We'll go through each address and check if it has a reference. If it does, it is likely a
# stub. As long as the address doesn't already have a stub name, pr... | 68,550 |
def __virtual__():
"""
Only return if all the modules are available
"""
log.debug("rapyutaio proxy __virtual__() called...")
return True | 68,551 |
def update(
cipd,
package_files,
root_install_dir,
cache_dir,
env_vars=None,
):
"""Grab the tools listed in ensure_files."""
if not check_auth(cipd):
return False
# TODO(mohrr) use os.makedirs(..., exist_ok=True).
if not os.path.isdir(root_install_dir):
os.makedirs(... | 68,552 |
def preprocess(
x: np.ndarray, y: np.ndarray, nb_classes: int = 10, clip_values: Optional["CLIP_VALUES_TYPE"] = None,
) -> Tuple[np.ndarray, np.ndarray]:
"""
Scales `x` to [0, 1] and converts `y` to class categorical confidences.
:param x: Data instances.
:param y: Labels.
:param nb_classes: Nu... | 68,553 |
def partition_softmax(logits: ArrayTree,
partitions: jnp.ndarray,
sum_partitions: Optional[int] = None):
"""Compute a softmax within partitions of an array.
For example::
logits = jnp.ndarray([1.0, 2.0, 3.0, 1.0, 2.0])
partitions = jnp.ndarray([3, 2])
... | 68,554 |
def split_pem_chain(pem_text):
"""
splits a PEM chain into multiple certs
"""
_certs = CERT_PEM_REGEX.findall(pem_text.encode())
certs = [cleanup_pem_text(i.decode("utf8")) for i in _certs]
return certs | 68,555 |
def logser_ll(x, p, upper_trunc = False, upper_bound = None):
"""Log-likelihood of a logseries distribution
x - quantiles
p - lower or upper tail probability
upper_trunc - whether the distribution is upper truncated
upper_bound - the upper bound of the distribution, if upper_trunc is True
... | 68,556 |
def ecm_list_market_update(ecm_folder, active_list, inactive_list,
filters, market_cat):
"""Update the active and inactive lists based on the user-selected filters
Based on the filters identified by the user for a given baseline
market parameter, this function opens each ECM and ... | 68,557 |
def get_instances_of(cls, context):
"""从 context 中获取所有类型为 cls 的实例"""
if type(context) is not dict:
names = dir(context)
context = {k: getattr(context, k) for k in names}
objects = []
for name, value in context.items():
value_type = type(value)
if inspect.isclass(value_ty... | 68,558 |
def find_all_files_in_directory(AFileClass, root_dir, excluded_directories, search_extensions, gauge_update_function=None):
"""Recursively searches a directory for files. search_extensions is a dictionary of extension lists"""
global TEXT_FILE_SIZE_LIMIT
all_extensions = [ext for ext_list in search_ex... | 68,559 |
def parse_edges_graphml(fin):
""" Turns a GraphML (.graphml) file into a list of edges
Args:
filename (str): Full path to the *.insts file
Returns:
list[Graph]: Graph objects parsed from the *.insts file
Note: This only expects the file format generated from a specific script
See:... | 68,560 |
def GetEffectiveEndpoint(version, region, is_prediction=False):
"""Returns regional AI Platform endpoint, or raise an error if the region not set."""
endpoint = apis.GetEffectiveApiEndpoint(
constants.AI_PLATFORM_API_NAME,
constants.AI_PLATFORM_API_VERSION[version])
return DeriveAiplatformRegionalEndp... | 68,561 |
def global_avg_pool2d(attrs, args):
"""Check if the external ACL codegen for global_avgpool2d should be used."""
typ = args[0].checked_type
if typ.dtype not in ["float32"]:
return False
if attrs.layout != "NHWC":
return False
return True | 68,562 |
def modifyPathsForEnvVar(action, env_var_name, path, should_set_env_var=False):
""" Modify the set of paths for the given environment variable
and returns a string to be used to set the environment variable.
"""
logger.debug("Modifying path for '%s' with action '%s' (%s)..." % (env_var_name, action,... | 68,563 |
def scraping_mg_initial_period(masp, senha, stop_period, headless, pdf):
"""
Função responsável pela busca de informações dos contracheques dos servidores do Estado de Minas Gerais até o período desejado.
Parâmetros:
-------
masp: string
Masp do servidor do Estado de Minas Gerais
senha: string
Senha... | 68,564 |
def purpleair_us_corr(df, param):
"""US-Wide Correction equation of Barkjohn et al. 2021 for PurpleAir PA-II
sensors.
Publication Link:
https://amt.copernicus.org/articles/14/4617/2021/
Args:
df (pandas dataframe):
Dataframe with PurpleAir PA-II concentration values for PM2... | 68,565 |
def _validate(address, userid, password, device_type, ssh_key=None):
""" Validate the password, address and userid information
Args:
address: ip v4 address for the device to validate
userid: userid of the device to validate
password: password for the device
device_type: devic... | 68,566 |
def generate_querystring(params):
"""
Generate a querystring suitable for use in the v2 api.
The Requests library doesn't know how to generate querystrings that encode dictionaries using square brackets:
https://api.mollie.com/v2/methods?amount[value]=100.00&amount[currency]=USD
Note: we use `sort... | 68,567 |
def mobilenet(images, depth_multiplier=1.0):
"""
Arguments:
images: a float tensor with shape [batch_size, height, width, 3],
a batch of RGB images with pixel values in the range [0, 1].
depth_multiplier: a float number, multiplier for the number of filters in a layer.
Returns:
... | 68,568 |
def test_extract_subgraph_from_sequence_position():
"""Tests subgraph extraction from sequence position."""
file_path = Path(__file__).parent / "test_data/4hhb.pdb"
G = construct_graph(pdb_path=str(file_path))
SEQ_POS = list(range(1, 50, 2))
s_g = extract_subgraph_by_sequence_position(
G,
... | 68,569 |
def PIsA (inFitRegion):
"""
Tells if input really a Python Obit FitRegion
return True, False
* inFitRegion = Python FitRegion object
"""
################################################################
if not isinstance(inFitRegion, FitRegion):
print("Actually is",inFitRegion.... | 68,570 |
def igre_test(config, shift, output):
"""
Information gain and registration test works with registered inputs. For testing registration layer, input pixels
are shifted by shift[0] in x axis and by shift[1] in y axis.
:param config: configuration of IGRE run
:param shift: tuple containing shift in x ... | 68,571 |
def GetStyleSheetInspectorClass():
"""
Indirection mostly to simplify tests.
"""
try:
from qt_style_sheet_inspector import StyleSheetInspector
except ImportError as error:
msg = 'You need to Install qt_style_sheet_inspector.'
raise RuntimeError(msg)
return StyleSheetInspe... | 68,572 |
def densenet_100_24(**kwargs):
"""
Constructs a DenseNet {L = 100, k = 24} model.
"""
return DenseNet(BasicBlock, 100, [[16, 16], [32]], 24, 1, **kwargs) | 68,573 |
def test_wallet_init():
"""
Test a wallet instance is initialized
inner variables wallet and amounts are default dicts (list and D("0"))
inner variable _walletCost is a decimal 0
"""
test_wallet = wallet()
assert type(test_wallet.wallet) is defaultdict
assert test_wallet.wallet.default... | 68,574 |
def setResolution(standart):
"""
:param str standart: NTSC of PAL
"""
global width, height
if standart == "NTSC":
width = 720
height = 576
elif standart == "PAL":
width = 640
height = 480
Capture.capture.set(cv.CAP_PROP_FRAME_WIDTH,width)
Capture.capture.... | 68,575 |
def arrow_3d(arrow_length=10, x_label="x", y_label="y", z_label="z"):
"""
Create 3d arrow with labels
:param arrow_length: specify arrow length
:param x_label: label for x axis
:param y_label: label for y axis
:param z_label: label for z axis
:return: return 3d arrow as an actor. Can be tran... | 68,576 |
def apply_phases(params, input_pairs, model_vis=1.0):
"""Apply relevant antenna phases to model visibility to estimate measurements.
This corrupts the ideal model visibilities by adding a set of per-antenna
phases to them.
Parameters
----------
params : array of float, shape (N - 1,)
A... | 68,577 |
def main():
"""Main CLI entrypoint."""
from idftags.idf_tag import tag_idfs
options = docopt(__doc__, version=VERSION)
# Call the tagged with the right options
if options['<idf_path>']:
tag_idfs(idf_path=options['<idf_path>'])
else:
tag_idfs(recursive=options['--recursive']) | 68,578 |
def test_shutdown(ray_8_node_2_cpu):
"""Tests if placement group is removed when worker group is shut down."""
assert ray.available_resources()["CPU"] == 16
placement_group_table = ray.state.state.placement_group_table()
assert len(placement_group_table) == 0
trainer = TorchTrainer(
trainin... | 68,579 |
def use_svg_display():
"""Use the svg format to display a plot in Jupyter.
Defined in :numref:`sec_calculus`"""
display.set_matplotlib_formats('svg') | 68,580 |
def point_face_distance_truncated(meshes: Meshes, pcls: Pointclouds):
"""
`point_face_distance_truncated(mesh, pcl)`:
Computes the squared distance of each point p in pcl
to the closest triangular face in mesh and averages across all points in pcl
The above distance function is applied for all ... | 68,581 |
def read_data(item):
"""reads data """
mesh_filename = glob.glob(os.path.join(item, '*.obj'))[0] # assumes one .obj file
mesh = trimesh.load(mesh_filename)
return mesh | 68,582 |
def init_props(config):
"""Initialize module-level variables.
:param dict config: Webrecorder configuration
"""
global FULL_WARC_PREFIX
FULL_WARC_PREFIX = config['full_warc_prefix'] | 68,583 |
def R1g():
"""
"""
A = Ugde(b,t1)*Uedg(b,t1+t2)*Ugde(a,t1+t2+t3)
return evaluate_cumulant(A, positive_times=(t1, t2, t3),
leading_index=a, arrays=["gg"]) | 68,584 |
def calc_raster_sum(raster_path):
"""Return the sum of the values in raster_path."""
nodata = pygeoprocessing.get_raster_info(raster_path)['nodata'][0]
raster_sum = 0.0
for _, raster_array in pygeoprocessing.iterblocks((raster_path, 1)):
raster_sum += numpy.sum(
raster_array[~numpy.i... | 68,585 |
def schema_maker(db, meta):
"""
create a Schema class with db bind
:param db:
:param meta: dict key value in class Meta
:return:
"""
# meta["db"] = db
meta = make_meta(meta)
return NewSchemaMeta("BaseSchema", (BaseSchema,), dict(Meta=meta, db=db)) | 68,586 |
def kpc_comoving_per_arcmin(z, cosmo=None):
""" Separation in transverse comoving kpc corresponding to an
arcminute at redshift `z`.
Parameters
----------
z : array_like
Input redshifts.
Returns
-------
d : astropy.units.Quantity
The distance in comoving kpc corresponding t... | 68,587 |
def standard_run(args):
"""
High-level function to run a standard analysis
Args:
:args: (obj) Instance of form 'StdRunArgs'
Returns:
:results: (dict) Results from static analysis
"""
# ===== Logging =====
hlogger.init(log_filename="log.txt", level=args)
logger = loggin... | 68,588 |
def get_plot_savepath(file_name, extension=".pdf"):
"""Get savepath for some result of the evaluation named `file_name`."""
savedir = get_plot_savedir()
return os.path.join(savedir, f"{file_name}{extension}") | 68,589 |
def find(parameter, value, identifier_pattern):
""" Finds all locally registered peripherals that match parameter=value
:param parameter: name of the parameter to search for
:param value: value of that parameter
:param identifier_pattern: regex expression to limit the search query to peripherals matchi... | 68,590 |
def debug_logger(output_filename="debug.log"):
"""Logger for printing time-stamped messages, DEBUG and higher, to file."""
debugfile_logger = logging.getLogger("debugfile_logger")
debugfile_logger.setLevel(logging.DEBUG)
debugfile_logger_handler = logging.FileHandler(output_filename, mode="w")
debug... | 68,591 |
def replace_mesh_as_connection():
""" 最後に選択したオブジェクトの形状を inmesh-outmesh 接続でそれ以外のオブジェクトにコピーする
複数のオブジェクトを選択して実行
"""
selections = [x for x in pm.selected()]
dst_objects = selections[0:-1]
src_object = selections[-1]
print(dst_objects)
print(src_object)
for dst in dst_obj... | 68,592 |
async def test_gather_timeout(event_loop: asyncio.AbstractEventLoop) -> None:
"""
Test the standard fixture timeout.
"""
class GatherTimeoutFixture(nanaimo.fixtures.Fixture):
@classmethod
def on_visit_test_arguments(cls, arguments: nanaimo.Arguments) -> None:
pass
a... | 68,593 |
def unbox_interval(typ, obj, c):
"""
Convert a Interval object to a native interval structure.
"""
lo_obj = c.pyapi.object_getattr_string(obj, "lo")
hi_obj = c.pyapi.object_getattr_string(obj, "hi")
data_obj = c.pyapi.object_getattr_string(obj, "_arr")
interval = cgutils.create_struct_proxy(... | 68,594 |
def blocks(file, blocksize=None, overlap=0, frames=-1, start=0, stop=None,
dtype='float64', always_2d=False, fill_value=None, out=None,
samplerate=None, channels=None,
format=None, subtype=None, endian=None, closefd=True):
"""Return a generator for block-wise reading.
By defaul... | 68,595 |
def findBranchByScanBusCk(mirror, ScanBus, Ck):
"""Return mirror bus object if possible"""
tic = time.time()
# required to use find functions during mirror creation before searchDict made
if not mirror.branchDict:
for branch in mirror.Branch:
if branch.ScanBus == ScanBus:
... | 68,596 |
def serialize_index_binary(index):
""" convert an index to a numpy uint8 array """
writer = VectorIOWriter()
write_index_binary(index, writer)
return vector_to_array(writer.data) | 68,597 |
def aggregate_all_tables(table_list, max_number=1000):
"""
Examples
--------
>>> table = Table({'a': [1, 2], 'b': [5, 6]})
>>> newt = aggregate_all_tables([table])[0]
>>> len(newt)
2
>>> np.all(newt['a'] == table['a'])
True
>>> np.all(newt['b'] == table['b'])
True
"""
... | 68,598 |
def hook(hook_api):
"""
SQLAlchemy 0.9 introduced the decorator 'util.dependencies'. This decorator does imports. E.g.:
@util.dependencies("sqlalchemy.sql.schema")
This hook scans for included SQLAlchemy modules and then scans those modules for any util.dependencies and marks
those module... | 68,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.