content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def fill_dates_daily(X, date_column='date'):
""" Add missing days in time series
:param X: pd.DataFrame with column `date_column`
:param date_column: columns with dates
:return: pd.DataFrame
"""
X = pd.DataFrame(X)
X[date_column] = pd.to_datetime(X[date_column])
idx = pd.date_range(star... | 5,302,200 |
def pandas_df_to_temporary_csv(tmp_path):
"""Provides a function to write a pandas dataframe to a temporary csv file with function scope."""
def _pandas_df_to_temporary_csv(pandas_df, sep=",", filename="temp.csv"):
temporary_csv_path = tmp_path / filename
pandas_df.to_csv(temporary_csv_path, se... | 5,302,201 |
def is_polar_hydrogen(atom_name: str, res_name: str) -> bool:
"""Check if the atom in a given residue has polar hydrogens.
Parameters:
atom_name: str
Name of the atom
res_name: str
Residue name
"""
if atom_name in POLAR_HYDROGENS[res_name]:
return True
... | 5,302,202 |
def df(n):
"""Gives the double factorial of *n*"""
return 1.0 if n <= 0 else 1.0 * n * df(n - 2) | 5,302,203 |
def cli(ctx, job_id):
"""Resume a job if it is paused.
Output:
dict containing output dataset associations
.. note::
This method is only supported by Galaxy 18.09 or later.
"""
return ctx.gi.jobs.resume_job(job_id) | 5,302,204 |
def queue_exists(queue_id):
"""Returns true if the queue ID belongs to a valid queue."""
return True | 5,302,205 |
def arrays(
fn, arrays_dict, _batch_size=None, _stack=False, _limit_slice=None, **kwargs,
):
"""
Split an array by its first dimension and send each row to fn.
The array_dict is one or more parallel arrays that will
be passed to fn(). **kwargs will end up as (constant) kwargs
to fn().
Examp... | 5,302,206 |
def track_num_to_int(track_num_str):
""" Convert a track number tag value to an int.
This function exists because the track number may be
something like 01/12, i.e. first of 12 tracks,
so we need to strip off the / and everything after.
If the string can't be parsed as a number, -1 i... | 5,302,207 |
def get_choices_as_case_expression(model, field_name, lookup_field=None):
"""
Gets an SQL expression that returns the display name for a field with choices.
Usage example:
InvestmentProject.objects.annotate(
status_name=get_choices_as_case_expression(InvestmentProject, 'status'),
... | 5,302,208 |
def elt1(list, context):
"""return second member"""
return list[1] | 5,302,209 |
def test_find_affiliated_entities_by_org_id_no_affiliation(session, auth_mock): # pylint:disable=unused-argument
"""Assert that an Affiliation can not be find without affiliation."""
org_service = factory_org_service()
org_dictionary = org_service.as_dict()
org_id = org_dictionary['id']
with patch... | 5,302,210 |
def write_dmar_data(sysnode, config):
"""Write the DMAR data to board info
:param sysnode: the system device node of acpi table, such as: /sys/firmware/acpi/tables/DMAR
:param config: file pointer that opened for writing board information
"""
dmar_hw_list = DmarHwList()
dmar_dev_list = DmarDevL... | 5,302,211 |
async def take_screen_shot(
video_file: str, duration: int, path: str = ""
) -> Optional[str]:
""" take a screenshot """
print(
"[[[Extracting a frame from %s ||| Video duration => %s]]]",
video_file,
duration,
)
ttl = duration // 2
thumb_image_path = path or os... | 5,302,212 |
def gather_PIM_data_leakage(x) :
"""
@param x : a VMAnalysis instance
@rtype : a list strings for the concerned category, for exemple [ 'This application makes phone calls', "This application sends an SMS message 'Premium SMS' to the '12345' phone number" ]
"""
result = []
result.extend( detect_ContactAcces... | 5,302,213 |
def cli(ctx, type, view):
"""List entry from Teampass."""
try:
data = ctx.tp.list(type)
except Exception as ex:
ctx.logerr(ex)
sys.exit(1)
else:
if view == 'table':
ctx.log(ctx.tp.print_result_table(data))
elif view == 'list':
ctx.log(ctx.t... | 5,302,214 |
def node_ping(node, timeout=True, count=2, all_workers=True, all_up=True):
"""Ping all relevant node workers to check if node is UP"""
up = 0
queues = [node.fast_queue, node.image_queue] # Base workers
if all_workers: # Additional workers depend on node capabilities
if node.is_compute:
... | 5,302,215 |
def clustermap(df, ax=None, **kwargs):
"""Plot a clustermap by pivoting the last 3 columns of `df`.
The `df` is typically returned from an ESTIMATE PAIRWISE query in BQL.
"""
if len(df.columns) < 3:
raise ValueError('At least three columns requried: %s' % (df.columns,))
# Pivot the matrix.
... | 5,302,216 |
def generate_bam_file(bam_file_name, reference_file, regions):
"""
Create a new BAM file and write reads to that file. The number and details
of the reads are specified in the 'regions' parameter.
"""
references = sorted(set(x[0] for x in regions if x[0] is not None))
lengths = [max(2 * (x[1] + ... | 5,302,217 |
def _get_detail(exc, exception_key: Union[str, List[str]] = "") -> str:
"""
Returns the human-friendly detail text for a specific insight exception.
"""
if hasattr(exc, "detail"):
# Get exception details if explicitly set. We don't obtain exception information
# from base Python excepti... | 5,302,218 |
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
"""Set up a SimpliSafe alarm control panel based on existing config."""
pass | 5,302,219 |
def seed_to_entropy(seed: Iterable[str], wordlist: Wordlist) -> bytes:
"""Derive entropy from seed phrase.
Algorithm is specified in BIP-0039:
https://github.com/bitcoin/bips/blob/master/bip-0039.mediawiki
>>> wordlist = Wordlist()
If the checksum is wrong, a ChecksumError is raised:
>>> seed... | 5,302,220 |
def sort_list(player_data_list):
"""Sort list based on qualifer.
Args:
player_data_list: player data list
Returns:
player data list properly sorted
"""
return sorted(player_data_list, key=lambda x: x[-1]) | 5,302,221 |
def AddLabelsFlag(parser, resource_type):
"""Adds labels flags for service-directory commands."""
return base.Argument(
'--labels',
metavar='KEY=VALUE',
type=arg_parsers.ArgDict(),
help="""\
Resource labels associated with the {}.
""".format(resource_type)).AddToParser(... | 5,302,222 |
def _newton_soft_erf_kernel(rmax, r_soft, npts=500, rsmult=4.5):
"""
Newtonian force modified with the error function to match at r=rmax, i.e.
d/dr [ -erfc(r/2r_s) / r ] term rather than the Newtonian 1/r^2.
d/dr -> erfc(r/2r_s)/r^2 + exp(-(r/2r_s)^2) / sqrt(pi) r r_s
Optional short-range softenin... | 5,302,223 |
def test_particles_jc005_particles_jc005_v(mode, save_output, output_format):
"""
TEST :3.9.1 The Particle Schema Component [ check length of element
information items ] : Particle Derivation OK (elt:Any) element R
drived by restriction from wildcard (any) B : B's namespace=##any, R's
targetNamespac... | 5,302,224 |
def evaluateRandomly(encoder, decoder, pairs, vocabulario, n=10):
"""
:param encoder:
:param decoder:
:param pairs:
:param vocabulario:
:param n:
:return:
"""
for i in range(n):
pair = random.choice(pairs)
print('>', pair[0])
print('=', pair[1])
outpu... | 5,302,225 |
def is_alive(worker_dict):
""" Test if worker is alive and running | None --> Bool """
return worker_dict['worker'].is_alive() | 5,302,226 |
def plotWav(wav, f, ratio, start, end, title, mode='t'):
"""
This function will plot a segment of wav data
if mode is 't', by default, the start& end means second
if mode is 'i', they means index
ratio & title is the params for plotting
"""
width, height = plt.figaspect(ratio)
fig = plt.... | 5,302,227 |
def dispatch():
"""
Checks initial arugments (MODE and ARGUMENT) and dispatches to the correct function for further processing
"""
if len(sys.argv) < 2:
print(usage)
return
elif sys.argv[1].lower() == 'help':
print(usage)
nl()
LongTextDisplayObject('{0}{1} use... | 5,302,228 |
def categorical_type_transformer(df: pd.DataFrame, ordered: bool = None):
"""
COnverts all objects dtypes into categorical dtypes and returns its
dataframe with the corresponding categorical codes
:params df: pd.DataFrame
:params ordered: bool
:return: pd.DataFrame
"""
df = df.copy()
for cols in df... | 5,302,229 |
def transform_cylindrical_to_cartesian(radial, axial, theta):
"""Assumes that axial direction coincides with the z-axis"""
x = radial*np.cos(theta)
y = radial*np.sin(theta)
z = axial
return [x, y, z] | 5,302,230 |
def create_context(context, key):
"""Create a new context having checked the key does not already exist."""
headers = get_headers(key)
data = {
'name': context
}
req = requests.put('https://apps.upfold.org.uk/StatusReporter/context', headers=headers, json=data)
assert req.status_code ... | 5,302,231 |
def sample_decode(
model,
size: int,
encoder_output,
masks: Dict[str, Tensor],
max_output_length: int,
labels: dict = None):
"""
Sample size sequences from the model
In each decoding step, find the k most likely partial hypotheses.
:param decoder:
:p... | 5,302,232 |
def modify_patch_info(
input_info_db="patch_info.db",
slide_labels=pd.DataFrame(),
pos_annotation_class="",
patch_size=224,
segmentation=False,
other_annotations=[],
target_segmentation_class=-1,
target_threshold=0.0,
classify_annotations=False,
):
"""Modify the patch information... | 5,302,233 |
def sort(array: list[int]) -> list[int]:
"""Naive bubble sort implementation.
"""
for i in range(len(array)):
for j in range(len(array) - 1, i, -1):
if array[j] < array[j - 1]:
array[j], array[j - 1] = array[j - 1], array[j]
return array | 5,302,234 |
def get_console_handler(logging_formatter=LOGGING_FORMATTER):
"""
Return a logging handler that sends logging output to the system's
standard output.
:param logging_formatter: An object `Formatter` to set for this handler.
:return: An instance of the `StreamHandler` class.
"""
console_ha... | 5,302,235 |
def organizar(exp, lista=False, dentro=False):
"""
Função responsável por adaptar o input do usuário, que é em formato de string para uma lista de cláusulas,
assim como aceita pela função "resolução".
:param exp: expressão a ser organizada
:param lista: se é ou não uma lista a ser organizada ... | 5,302,236 |
def delete_tasks(
client: GMPClient, task_name=None, states=['obsolete'], ultimate=False):
"""
Deletes a set of tasks.
:param task_name: name of the task to delete.
:param states: the tasks in `states` will be deleted.
:param ultimate: move to trash or delete permanently.
:return: list ... | 5,302,237 |
def box_teamnames(page):
"""
A @ H always
"""
teams = page.find_all("span", {"class": "short-name"})
destinations = page.find_all("span", {"class": "long-name"})
names = [team.text for team in teams]
cities = [destination.text for destination in destinations]
if not names or not cities:
... | 5,302,238 |
def test_cs_save_verification_document(session):
"""Assert that saving a mail verification statement document to google cloud storage works as expected."""
raw_data = None
with open(TEST_VERIFICATION_DATAFILE, 'rb') as data_file:
raw_data = data_file.read()
data_file.close()
response = ... | 5,302,239 |
def login():
"""Logging in user"""
email = str(request.get_json().get('email'))
password = str(request.get_json().get('password'))
if not (email and password):
response = jsonify({
"message": "Enter required details correctly"
})
response.status_code = 400
ret... | 5,302,240 |
def quadvgk(feval, fmin, fmax, tol1=1e-5, tol2=1e-5):
"""
numpy implementation makes use of the code here: http://se.mathworks.com/matlabcentral/fileexchange/18801-quadvgk
We here use gaussian kronrod integration already used in gpstuff for evaluating one dimensional integrals.
This is vectorised quadra... | 5,302,241 |
def exploreAMDBins(experiment, elec_bin=None):
"""
"""
cluster_results = readResults()
if elec_bin is None:
exc = cluster_results[['experiment_name','som_dim','n_clust','elec_bin',
'dbi','mia','silhouette','score','total_sample']]
else:
exc = clust... | 5,302,242 |
def test_twineUpload_open(empty_packdir, port, package, uploader, pypirc):
"""Test twine upload with no authentication"""
user, pswd = 'foo', 'bar'
update_pypirc(pypirc, port, user=user, pswd=pswd)
with new_server(empty_packdir, port):
uploader.upload([package.strpath], repository='test',
... | 5,302,243 |
def collect_artifact_metrics(data):
"""Run CollectSequencingArtifacts to collect pre-adapter ligation artifact metrics
https://gatk.broadinstitute.org/hc/en-us/articles/360037429491-CollectSequencingArtifactMetrics-Picard-
"""
OUT_SUFFIXES = [".bait_bias_detail_metrics", ".error_summary_metrics",
... | 5,302,244 |
def prepare_packed_data(radius_packet, packed_req_authenticator):
"""
Pack RADIUS data prior computing the authentication MAC
"""
packed_hdr = struct.pack("!B", radius_packet.code)
packed_hdr += struct.pack("!B", radius_packet.id)
packed_hdr += struct.pack("!H", radius_packet.len)
packed_a... | 5,302,245 |
def test_usage() -> None:
""" Usage """
for flag in ['-h', '--help']:
retval, out = getstatusoutput(f'{PRG} {flag}')
assert retval == 0
assert out.lower().startswith('usage:') | 5,302,246 |
def _call_bool_filter(context, value):
"""Pass a value through the 'bool' filter.
:param context: Jinja2 Context object.
:param value: Value to pass through bool filter.
:returns: A boolean.
"""
return context.environment.call_filter("bool", value, context=context) | 5,302,247 |
def getNormalMask(coco, imageObj, filterClasses):
"""
iscrowd is set to None, therefore it only works for single
mask : (height, width)
Parameters
------------------------------------
"""
# Load categorical ids for filterclasses
catIds = coco.getCatIds(catNms=filterClasses)
input_im... | 5,302,248 |
def lbp_cmp(f, g, O):
"""
Compare two labeled polynomials.
f < g iff
- Sign(f) < Sign(g)
or
- Sign(f) == Sign(g) and Num(f) > Num(g)
f > g otherwise
"""
if sig_cmp(Sign(f), Sign(g), O) == -1:
return -1
if Sign(f) == Sign(g):
if Num(f) > Num(g):
... | 5,302,249 |
def findpatterns(spec, points, segments):
""" Method to search for patterns in the peaks. Specifically it is
looking for pairs of peaks that are the same distance apart (within
the tolerance). These can be an indicator of rotation/infall/etc.
Only two patterns are allowed to overlap. See the... | 5,302,250 |
def delete_user_group(connection, id, error_msg=None):
"""Delete user group for specific user group id.
Args:
connection: MicroStrategy REST API connection object
id (string): ID of user group containing your required privileges
error_msg (string, optional): Custom Error Message for Err... | 5,302,251 |
def hmean(a, axis=0, dtype=None):
"""
Calculate the harmonic mean along the specified axis.
That is: n / (1/x1 + 1/x2 + ... + 1/xn)
Parameters
----------
a : array_like
Input array, masked array or object that can be converted to an array.
axis : int or None, optional
Axis... | 5,302,252 |
def filepath():
""" ask for file path"""
filepath = hou.ui.selectFile()
return filepath | 5,302,253 |
def press(key):
"""
This function prints the keybooard presses and calls the control()
function.
Inputs:
1. key - Pressed keyboard Key
"""
print(f"'{key}' is pressed")
# Sending Control Inputs
control(value = key) | 5,302,254 |
def is_all_pass_testharness_result(content_text):
"""Returns whether |content_text| is a testharness result that only contains PASS lines."""
return (is_testharness_output(content_text) and
is_testharness_output_passing(content_text) and
not has_console_errors_or_warnings(content_text)) | 5,302,255 |
def _getDefaultSlurmAccount():
"""Returns the default Slurm account for the current user.
"""
if system.existsExecutable("sacctmgr"):
user = system.run_output("whoami")
result = system.run_output("sacctmgr show User "+user + " -p")
s = re.search(user+r"\|((\S)+?)\|", result)
... | 5,302,256 |
def source_slice(request_data) -> str:
"""Write an entry source slice and return the updated sha256sum."""
return g.ledger.file.save_entry_slice(
request_data.get("entry_hash"),
request_data.get("source"),
request_data.get("sha256sum"),
) | 5,302,257 |
def test_atomic_integer_min_inclusive_3_nistxml_sv_iv_atomic_integer_min_inclusive_4_3(mode, save_output, output_format):
"""
Type atomic/integer is restricted by facet minInclusive with value
-183640263935870295.
"""
assert_bindings(
schema="nistData/atomic/integer/Schema+Instance/NISTSchem... | 5,302,258 |
def remove_nan_amp_rows(df: pd.DataFrame) -> None:
"""
Can only use rows that have a N and E p-p amplitude,
therefore rows without both are not useful.
Returns: None
"""
df.dropna(subset=['AmpE', 'AmpN'], inplace=True)
df.reset_index(drop=True, inplace=True) | 5,302,259 |
def create_dependencies_tree_by_req_file(
requirements_file,
allow_missing=False,
only_provenance=False
):
"""Create dist dependencies tree from file
:param str requirements_file: path to the dependencies file (e.g. requirements.txt)
:param bool allow_missing: ignore uninstalled d... | 5,302,260 |
def send_super(receiver, selName, *args, **kwargs):
"""Send a message named selName to the super of the receiver.
This is the equivalent of [super selname:args].
"""
try:
receiver = receiver._as_parameter_
except AttributeError:
pass
if isinstance(receiver, objc_id):
pa... | 5,302,261 |
def disable_availability_zones_for_load_balancer(LoadBalancerName=None, AvailabilityZones=None):
"""
Removes the specified Availability Zones from the set of Availability Zones for the specified load balancer in EC2-Classic or a default VPC.
For load balancers in a non-default VPC, use DetachLoadBalancerFr... | 5,302,262 |
def preprocess_fundus(fundus_dir, manual_dir, mask_dir, all_filenames) :
"""
Load fundus images and return the followings:
inputImages = raw green channel of the fundus images
histEnhancedImages = green channel enhanced by CLAHE
stdImages = local standard deviation images
entropyTsallisImages = ... | 5,302,263 |
def incremental_replication(serveur, localzname, tgtzname):
"""
do incremental replication using latest tgt and latest src
find latest snap on target
use same date on source
find latest snap on source
if latest target is less than latest src : replicate snapshot(s)
""... | 5,302,264 |
def test_scan(ln, tokenize, byte, remaining_line, char_maps):
"""
Unit test to check that function scan() is properly converting the start
of each passed in line to a tokenized byte for BASIC keywords, petcat
special characters, and alphanumeric characters.
"""
assert scan(ln, char_maps, tokeni... | 5,302,265 |
def discontinuous_match(biluov, sentence):
"""
>>> discontinuous_match(['B','V','L'],['la', 'enfermedad', 'renal'])
[['la', 'enfermedad', 'renal'], ['enfermedad']]
>>> discontinuous_match(['O','V','I','L','O','I','L'],['el','cancer','de','pulmon','y','de','mama'])
[['cancer', 'de', 'pulmon'], ['canc... | 5,302,266 |
def metric_transpose_theorem(model):
"""
Metric for how close encoder and decoder.T are
:param model: LinearAE model
:return: ||W1 - W2^T||_F^2 / hidden_dim
"""
# encoder_weight = get_weight_tensor_from_seq(model.encoder)
# decoder_weight = get_weight_tensor_from_seq(model.decoder)
encod... | 5,302,267 |
def find_performance_space_price(package, size):
"""Find the price in the given package with the specified size
:param package: The product package of the performance storage type
:param size: The size for which a price is desired
:return: Returns the price for the given size, or an error if not found
... | 5,302,268 |
def do_operationlog_list(cs, args):
"""Lists all operation_logs."""
all_tenants = 1 if args.tenant else \
int(os.environ.get("ALL_TENANTS", args.all_tenants))
search_opts = {
'all_tenants': all_tenants,
'project_id': args.tenant,
'status': args.status,
}
if args.sor... | 5,302,269 |
def train(config_path, cuda):
"""
Training DeepLab by v2 protocol
"""
# Configuration
CONFIG = Dict(yaml.load(config_path))
device = get_device(cuda)
# Allow PyTorch to search for the quickest optimization algorithm
torch.backends.cudnn.benchmark = True
# Dataset
dataset = get_... | 5,302,270 |
def run_tcp_uplink(ue, s1ap_wrapper, duration=1):
"""
Given a configured UE, run a TCP uplink test for the specified duration.
"""
print("************************* Running UE uplink (TCP) for UE id ",
ue.ue_id)
with s1ap_wrapper.configUplinkTest(ue, duration=duration) as test:
test... | 5,302,271 |
def find_region_pos(regions, pos):
"""Find the first region that starts after 'pos' in sorted 'regions'"""
low, top = util.binsearch(regions, pos-1, lambda a, b: cmp(a.start, b))
return top | 5,302,272 |
def print_table(table):
"""
prints all records in a table
:param table: name of the table
:return: None
"""
print("Data for table '{}'".format(table))
print("----------------------------------------------------")
con = sqlite3.connect(DB_PATH)
cur = con.cursor()
cur.execute("SELE... | 5,302,273 |
def runCommand(userhome, userconfig, argv):
"""
Run program with supplied configuration base directory,
configuration directory and command arguments.
This is called by main function (below), and also by test suite routines.
Returns exit status.
"""
options = parseCommandArgs(argv[1:])
... | 5,302,274 |
def commands_post(cmd, base_url=DEFAULT_BASE_URL):
"""Commands POST.
Using the same syntax as Cytoscape's Command Line Dialog, this function converts a command string into a CyREST
query URL, executes a POST request, and parses the result content into a dict object.
Args:
cmd_string (str): com... | 5,302,275 |
def ensure_single_primary(queryset):
"""
ensure that at most one item of the queryset is primary
"""
primary_items = queryset.filter(primary=True)
if primary_items.count() > 1:
for item in primary_items[1:]:
item.primary = False
item.save()
elif primary_items.coun... | 5,302,276 |
def rowify(columns: Dict[Any, Any]) -> List[Dict[str, Any]]:
"""Converts columnar input to row data.
We treat the first dimension of each input tensor as `batch` dimension and
and break into single instance based on the `batch` dimension.
Consider the following code:
columns = {"prediction": np.array([1,... | 5,302,277 |
def post(handler, parameters, url_parameters, *ids_parameters):
"""POST method"""
token = handler.session.query(Token).where(Token.session_token == handler.session_token).first()
if not token:
handler.logger.debug("Invalid token")
handler.send_json(401, "This token doesn't exist.")
r... | 5,302,278 |
def get_attr(attrs, key):
""" Get the attribute that corresponds to the given key"""
path = key.split('.')
d = attrs
for p in path:
if p.isdigit():
p = int(p)
# Let it raise the appropriate exception
d = d[p]
return d | 5,302,279 |
def constant(n):
""" Return the constant random variable *n*. """
return DiscreteRandomVariable(name=str(n), xs=[n], ps=[1.0]) | 5,302,280 |
def test_update_profile_override_cli(mock_aws_stack_exists):
"""Update an existing stack"""
with cfhelper_mocks() as (boto3_mock, session_mock, client_mock):
call_cfhelper(
[
"stack",
"--aws-profile",
"MyOtherProfile",
"--config... | 5,302,281 |
def reduce_(
accumulator: Accumulator[_TState, _T], seed: Union[_TState, Type[NotSet]] = NotSet
) -> Callable[[Observable[_T]], Observable[Any]]:
"""Applies an accumulator function over an observable sequence,
returning the result of the aggregation as a single element in the
result sequence. The specif... | 5,302,282 |
def config_by_search():
"""Create a RDF Graph configuration file by searching for Orcid user."""
orcid_profile = orcid_search(sandbox=False)
turtle_data = orcid_profile.get_turtle()
config_file = ConfigManager()
config_file.get_config(_id=orcid_profile.orcid_id, _data=turtle_data)
config_file.wr... | 5,302,283 |
def beta_binomial_experiment(number_images, result_path, latent_dim, hidden_dim, model, path):
"""
Run a beta binomial experiment with the given model
"""
seed = 0
rng = RandomState(seed)
image_count = number_images
prior_precision = 8
beta_binomial_precision = 14
q_precision = 14
... | 5,302,284 |
def ch(i, A):
"""The children of i in A.
Parameters
----------
A : np.array
the adjacency matrix of the graph, where A[i,j] != 0 => i -> j
and A[i,j] != 0 & A[j,i] != 0 => i - j.
Returns
-------
nodes : set of ints
the children nodes
"""
return set(np.where... | 5,302,285 |
def get_rays(H, W, focal, c2w):
"""Get ray origins, directions from a pinhole camera."""
# Tensorflow version
i, j = tf.meshgrid(tf.range(W, dtype=tf.float32),
tf.range(H, dtype=tf.float32), indexing='xy')
dirs = tf.stack([(i-W*.5)/focal, -(j-H*.5)/focal, -tf.ones_like(i)], -1)
... | 5,302,286 |
def get_wbo(offmol, dihedrals):
"""
Returns the specific wbo of the dihedral bonds
Parameters
----------
offmol: openforcefield molecule
dihedrals: list of atom indices in dihedral
Returns
-------
bond.fractional_bond_order: wiberg bond order calculated using openforcefield toolkit ... | 5,302,287 |
def MCFG(val):
"""Create class based on decode of an MCFG table from address or filename."""
addr = val
if isinstance(val, str):
data = open(val).read()
buf = ctypes.create_string_buffer(data, len(data))
addr = ctypes.addressof(buf)
hdr = TableHeader.from_address(addr)
num_ta... | 5,302,288 |
def get_iot_connector_fhir_destination(fhir_destination_name: Optional[str] = None,
iot_connector_name: Optional[str] = None,
resource_group_name: Optional[str] = None,
workspace_name: Optional[str] = No... | 5,302,289 |
def script(script, infiles = []):
"""Run a Yosys script given a path to the script
Inputs
-------
script : path to Yosys script to run
infiles : list of input files
"""
params = ["-q", "-s", script] + infiles
return get_output(params) | 5,302,290 |
def sample_histogram(histogram, sample_fraction=0.05):
"""Sample a sample_fraction of colors from histogram"""
colors = np.fromiter(histogram.keys(), dtype='i8,i8,i8', count=-1)
counts = np.fromiter(histogram.values(), dtype=np.float32, count=-1)
size = counts.sum()
samples = (k * v for k, v in hist... | 5,302,291 |
def upgrade():
"""Migrations for the upgrade."""
# pylint: disable=unused-variable
connection = op.get_bind()
profile = op.get_context().opts['aiida_profile']
repo_path = profile.repository_path
node_tbl = sa.table(
'db_dbnode',
sa.column('id', sa.Integer),
sa.column('uu... | 5,302,292 |
def rename_volume(session, volume_id, display_name, return_type=None,
**kwargs):
"""
Sets the "display_name" volume parameter to a new value.
:type session: zadarapy.session.Session
:param session: A valid zadarapy.session.Session object. Required.
:type volume_id: str
:para... | 5,302,293 |
def updateLink(soup, url, session):
"""
update all relative url path in <a> tag in the html to absolute url path
Example:
Update href="/codegame/index.html" to href="https://www.w3schools.com/codegame/index.html"
"""
for res in soup.findAll('a'):
try:
if not res.has_attr... | 5,302,294 |
def filter(
data: utils.URLPath,
filters: json.loads,
output: utils.URLPath = None,
meta: utils.URLPath = None,
sample: int = 0,
move_samples: bool = False,
):
"""Filter data on the given filters and output resulting dataset metadata
to destination.
Args:
... | 5,302,295 |
def test_autoclass_pickle_inheritance():
"""Tests that pickle can work with autoclass-ed classes"""
from ._test_autoclass_pickle import Bar
a = Bar(2, 'th')
assert a == {'bar': 2, 'foo1': 'th', 'foo2': 0}
assert a['foo1'] == 'th'
# iteration order is fixed
assert list(a.keys()) == ['bar',... | 5,302,296 |
def generation():
"""
this is the main function of generate marker transform color.
"""
data=open(data_path+'calibration_marker_transforms.txt','w')
for i in range(num_pic): #total of 18 pics
data2=open(data_path+'data/calibration_pt_'+str(i)+'.txt','r')
columnPts=[]
for line in data2:
line=line.rstrip()
... | 5,302,297 |
def p_add_op(p):
"""add_op : PLUS
| MINUS
"""
pass | 5,302,298 |
def test_sae_pk_modes(dev, apdev):
"""SAE-PK modes"""
check_sae_pk_capab(dev[0])
dev[0].set("sae_groups", "")
params = hostapd.wpa2_params(ssid=SAE_PK_SSID)
params['wpa_key_mgmt'] = 'SAE'
params["ieee80211w"] = "2"
params['sae_password'] = ['%s|pk=%s:%s' % (SAE_PK_SEC2_PW, SAE_PK_SEC2_M,
... | 5,302,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.