content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def get_policy_map(policy, world_shape, mode='human'):
"""
Generates a visualization grid from the policy to be able to print which action is most likely from every state
"""
unicode_arrows = np.array([u'\u2191', u'\u2192', u'\u2193', u'\u2190' # up, right, down, left
u'\u2194', u'... | 5,312,500 |
def test_get_tip_geometry_raises(
decoy: Decoy,
tip_rack_def: LabwareDefinition,
labware_store: LabwareStore,
geometry_store: GeometryStore
) -> None:
"""It should raise LabwareIsNotTipRackError if well is not circular."""
pipette_config: PipetteDict = cast(PipetteDict,
... | 5,312,501 |
def _setup_request(bucket_acl=None, object_acl=None):
"""
add a foo key, and specified key and bucket acls to
a (new or existing) bucket.
"""
bucket = _create_keys(keys=['foo'])
key = bucket.get_key('foo')
if bucket_acl is not None:
bucket.set_acl(bucket_acl)
if object_acl is no... | 5,312,502 |
def test_basic():
"""Verify that urlencode works with four levels."""
d = {"a": {"b": {"c": "d"}}}
expected = quote("a[b][c]=d", safe="=/&")
assert urlencode(d) == expected | 5,312,503 |
def _some_lt(t1: 'Tensor', t2: 'Tensor', only_value: bool) -> bool:
"""
:param t1:
:param t2:
:param only_value:
:return:
"""
res = np.sum(t1.data < t2.data)
if only_value:
if res > 0:
return True
else:
return False
else:
raise NotIm... | 5,312,504 |
def get_folders(parent_id: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetFoldersResult:
"""
Retrieve information about a set of folders based on a parent ID. See the
[REST API](https://cloud.google.com/resource-manager/reference/rest/v3/folders/list)
f... | 5,312,505 |
def bedLine(chrom, chromStart, chromEnd, name, score=None, strand=None,
thickStart=None, thickEnd=None, itemRgb=None, blockCount=None,
blockSizes=None, blockStarts=None):
""" Give the fields, create a bed line string
"""
s = ('%s %d %d %s'
% (chrom, chromStart, chromEnd, name))
i... | 5,312,506 |
def printProgressBar (iteration, total, prefix = '', suffix = '', decimals = 1, length = 100, fill = '█', printEnd = "\r"):
"""
Call in a loop to create terminal progress bar
Source: https://stackoverflow.com/a/34325723/10302137
@params:
iteration - Required : current iteration (Int)
... | 5,312,507 |
def tuning(sortedfile):
"""
Fit r = a0 + a1*f1.
"""
# Load sorted trials
with open(sortedfile) as f:
t, sorted_trials = pickle.load(f)
# Get f1s
f1s = sorted(sorted_trials.keys())
# Active units
units = get_active_units(sorted_trials)
units = range(next(sorted_trials.i... | 5,312,508 |
def execute():
""" command-line entry point """
services.Service().listen() | 5,312,509 |
def test_different_setup():
"""
Test another option how to create a lens.
"""
lens = Lens()
lens.n1 = 1.0003
lens.nL = 1.5
lens.n2 = 1.0003
lens.r1 = 50
lens.r2 = -40
lens.CT = 3
lens.calculate()
assert lens.D1 == (lens.nL - lens.n1) / lens.r1
assert lens.n1 == 1.00... | 5,312,510 |
def balance_conversion_constraint_rule(backend_model, loc_tech, timestep):
"""
Balance energy carrier consumption and production
.. container:: scrolling-wrapper
.. math::
-1 * \\boldsymbol{carrier_{con}}(loc::tech::carrier, timestep)
\\times \\eta_{energy}(loc::tech, time... | 5,312,511 |
def follow(id):
"""Follow a user"""
user = token_auth.current_user()
followed_user = db.session.get(User, id) or abort(404)
if user.is_following(followed_user):
abort(409)
user.follow(followed_user)
db.session.commit()
return {} | 5,312,512 |
def get_rules():
"""
Get the virtual server rules
CLI Example:
.. code-block:: bash
salt '*' lvs.get_rules
"""
cmd = "{} -S -n".format(__detect_os())
ret = __salt__["cmd.run"](cmd, python_shell=False)
return ret | 5,312,513 |
def all_user_tickets(uid, conference):
"""
Cache-friendly version of user_tickets: returns a list of
(ticket_id, fare_type, fare_code, complete)
for each ticket associated to the user.
"""
qs = _user_ticket(User.objects.get(id=uid), conference)
output = []
for t in qs:
output... | 5,312,514 |
def get_titles(url: str = URL) -> List[str]:
"""List titles in feed."""
articles = _feed(url).entries
return [a.title for a in articles] | 5,312,515 |
def fatorial(num):
"""
Calcula a fatorial
:param num:
:return:
"""
fat = 1
if num == 0:
return fat
for i in range(1,num+1,1):
fat *= i # fat = fat * i
return fat | 5,312,516 |
def duplicate_pptx_sheet(filename, slide_number, filename_output=None):
"""
A method that duplicates a slide in a PowerPoint file
Parameters
----------
filename : string
The filename contains the location of the original powerpoint file that
will have a slide duplicated.
slide_... | 5,312,517 |
def test_score_function(daily_data):
"""Checks score function accuracy"""
# with null model
model = AutoArimaEstimator(null_model_params={"strategy": "mean"})
train_df = daily_data["train_df"]
value_col = "y"
time_col = "ts"
model.fit(train_df, time_col=time_col, value_col=value_col)
sco... | 5,312,518 |
def indent_code(*code, indent: int = 1) -> str:
"""Indent multiple lines (`*code`) by the given amount, then join on newlines."""
return "\n".join(indent_str(line, indent, end="") for line in code) + "\n" | 5,312,519 |
def test_del_invite_no_email(client):
"""Super admin deletes invite without specifying email."""
response = client.delete(
tests.DDSEndpoint.USER_DELETE,
headers=tests.UserAuth(tests.USER_CREDENTIALS["superadmin"]).token(client),
json={"is_invite": True},
)
assert response.status... | 5,312,520 |
def evaluate_accuracy_gpu(net, data_iter, device=None):
"""使用GPU计算模型在数据集上的精度。
Defined in :numref:`sec_lenet`"""
if isinstance(net, nn.Module):
net.eval() # 设置为评估模式
if not device:
device = next(iter(net.parameters())).device
# 正确预测的数量,总预测的数量
metric = d2l.Accumulator(2)
... | 5,312,521 |
def get_rdns_from_ip(ip):
"""Basic get RDNS via gethostbyaddr.
:param ip: IP address to lookup
:type ip: str
:return: Returns `hostname` if found, or empty string '' otherwise
:rtype: str
"""
try:
coro = resolver.gethostbyaddr(ip)
result = loop.run_until_complete(coro)
... | 5,312,522 |
def saveData(data,action, mycar,alldistances):
""" Appending game data to the DATA object
0 - position of player (x only)
1 - ennemy distance on the left column
2 - ennemy distance on the center column
3 - ennemy distance on the right column
"""
row = []
row.append(mycar.... | 5,312,523 |
def GePacketOut(egress_port, mcast, padding):
""" Generate packet_out packet with bytearray format """
out1 = "{0:09b}".format(egress_port)
out2 = "{0:016b}".format(mcast)
out3 = "{0:07b}".format(padding)
out = out1+out2+out3
a = bytearray([int(out[0:8],2),int(out[8:16],2),int(out[16:24],2),int... | 5,312,524 |
def generate_tileset(
input_images,
output_c=None,
output_h=None,
output_image=None,
name="TILESET",
dedup=False,
alternative_palette=False,
sprite8x16=False):
"""Function that generates tileset's C file, C header and image from an
input image.
... | 5,312,525 |
def _polyCreateDefaultEdges(poly, boundaryMarker=1, isClosed=True, **kwargs):
"""INTERNAL."""
nEdges = poly.nodeCount() - 1 + isClosed
bm = None
if hasattr(boundaryMarker, '__len__'):
if len(boundaryMarker) == nEdges:
bm = boundaryMarker
else:
raise Exception("mar... | 5,312,526 |
def damage_per_max_ammo(weapon_dic: dict, damage_range_arr: np.ndarray) -> np.ndarray:
"""
Calculate the damage per max ammo at varying distances.
This assumes you were to fire all ammo in the gun and in reserve at a set distance.
Parameters
----------
weapon_dic : dict
Dict of specifi... | 5,312,527 |
def get_PDB_summary(PDB_id, verbose=False):
"""
Similar info to get_meta, but for a PDB entry - returns info about when it was regitered etc.
Parameters
----------
PDB_id :
verbose : Bool, optional, default: False
Flag to turn on verbose output
Returns
-------
See Also
... | 5,312,528 |
def remove_temp():
"""
一時ディレクトリを空にする。
"""
dpath = cw.tempdir
if not os.path.exists(dpath):
os.makedirs(dpath)
removeall = True
for name in os.listdir(dpath):
if name in ("Scenario", "LockFiles"):
removeall = False
else:
path = j... | 5,312,529 |
def main():
"""
:return:
"""
mp.set_start_method('forkserver')
args = parse_command_line()
outbuffer = []
children = []
recv_lines, send_lines = mp.Pipe(duplex=False)
recv_checked, send_checked = mp.Pipe(duplex=False)
recv_blocks, send_blocks = mp.Pipe(duplex=False)
deadcount... | 5,312,530 |
def copy_dir(src: str, dest: str) -> bool:
"""Recursively copy a directory.
Args:
src: The source directory.
dest: The destination directory.
Returns:
Indicate if the copy was success or not.
"""
if os.path.exists(dest):
shutil.rmtree(dest, ignore_errors=True)
... | 5,312,531 |
def beam_search(
model_name='124M',
seed=None,
nsamples=1,
batch_size=1,
length=10,
temperature=1, # .5 usually has numbered steps, .7 usually does not
beam_width=3,
top_k=None,
top_p=1,
models_dir='models',
input_samples=[],
):
"""
Interactively run the model
:mo... | 5,312,532 |
def test_passive_program(tol, depth, width):
"""Tests that a circuit and its compiled version produce the same Gaussian state"""
circuit = sf.Program(width)
T_circuit = np.eye(width, dtype=np.complex128)
with circuit.context as q:
for _ in range(depth):
U = unitary_group.rvs(width)
... | 5,312,533 |
def distance_from_user(beer):
"""
This method is used to calculate distace from user to each store that carry
specific beer that user seached for and return list of store, beer and distance from user to
those stores sorted by distance
"""
# user_lat = 40.8200471
# user_lon = -73.9514611
... | 5,312,534 |
def meshes2system(meshes):
"""
recursively generate system.
"""
from mesh.Triangulation import TrivialSystem, ComposedSystem, State
firstKey = list(meshes.keys())[0]
mm = meshes[firstKey]
state = State(translation=mm['translate'],
rotation=mm['rotate'],
ve... | 5,312,535 |
def save_albums(client: Spotify, album_uris: List[str]):
"""Save a list of albums to the authenticated user's profile.
Args:
client: A spotipy Spotify client.
album_uris: A list of album URIs to save.
"""
client.current_user_saved_albums_add(album_uris) | 5,312,536 |
def cmp_public_numbers(pn1, pn2):
"""
Compare 2 sets of public numbers. These is a way to compare
2 public RSA keys. If the sets are the same then the keys are the same.
:param pn1: The set of values belonging to the 1st key
:param pn2: The set of values belonging to the 2nd key
:return: True i... | 5,312,537 |
def authenticate():
"""Shows basic usage of the Gmail API.
Lists the user's Gmail labels.
"""
creds = None
# The file token.json stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first
# time.
if os.path.exists(token... | 5,312,538 |
def train_test_same(data_path, label_path, *,
test_start=800,
base_output_path="models",
run_name=None,
data_name=None,
net_name="leap_cnn",
clean=False,
box_dset="box",
confmap_dset="confmaps",
train_size=800,
val_size=0.1,
preshuffle=True,
filters=64,
rotate_angle=... | 5,312,539 |
def saveGTiff(ndarray, fileName):
"""
ndarray保存为GTiff格式图片\n
参数:\n
ndarray - (ndarray)图片\n
fileName - (str)文件名\n
返回值:\n
None
"""
ga.SaveArray(ndarray, fileName, format="GTiff")
return | 5,312,540 |
def test_interrupt(storage, monkeypatch, capsys):
"""Test interruption from within user script."""
monkeypatch.chdir(os.path.dirname(os.path.abspath(__file__)))
user_args = ["-x~uniform(-50, 50, precision=5)"]
error_code = orion.core.cli.main(
[
"hunt",
"--config",
... | 5,312,541 |
def fake_os_sles(host, host_os, revert_etc):
"""
Trick Stacki into always seeing the OS (self.os) as SLES
"""
if host_os != "sles":
centos_release = Path("/etc/centos-release")
if centos_release.exists():
centos_release.unlink()
Path("/etc/SuSE-release").touch()
yield | 5,312,542 |
def phred(vals):
""" apply the phred scale to the vals provided """
return -10*np.log10(1-vals)
return -10*np.ma.log10(1-vals).filled(-3) | 5,312,543 |
def __get_useconds_of(stage_idx, block_idx, event_acc, wanted, block_prefix=''):
"""
gets useconds of chan/kernel of specific stage_idx & block_idx, from tensorboard event_acc
:param wanted: 'chan' or 'kernel'
"""
useconds = []
summary_prefix = block_prefix + 'use_%s_' % wanted
idx = 0
... | 5,312,544 |
def create_menu(*args):
"""
create_menu(name, label, menupath=None) -> bool
Create a menu with the given name, label and optional position, either
in the menubar, or as a submenu. If 'menupath' is non-NULL, it
provides information about where the menu should be positioned. First,
IDA will try and resolve ... | 5,312,545 |
def parse_proxy_url(purl):
"""Adapted from UStreamTV plugin (ustreamtv.py)"""
proxy_options = {}
if purl:
p = urlparse(purl)
proxy_options['proxy_type'] = p.scheme
proxy_options['http_proxy_host'] = p.hostname
if p.port:
proxy_options['http_proxy_port'] = p.port
... | 5,312,546 |
def download_content_to_file(file_dict: dict, gdrive_service: Resource):
"""
Download the file content from S3. This modifies the file dict in-place.
"""
file_id = file_dict['id']
request = gdrive_service.files().get_media(fileId=file_id)
fh = io.BytesIO()
downloader = MediaIoBaseDownload... | 5,312,547 |
async def cmd_payout(self, message, user, amount):
"""
`$!_payout <user> <amount>` : Pays tokens to the provided user
Example: `$!_payout some_user_id 12`
"""
async with DBView('players') as db:
if user.id not in db['players']:
db['players'][user.id] = {
'balance'... | 5,312,548 |
def cma(data):
"""
Cumulative Moving Average
:type data: np.ndarray
:rtype: np.ndarray
"""
size = len(data)
out = np.array([np.nan] * size)
last_sum = np.array([np.nan] * size)
last_sum[1] = sum(data[:2])
for i in range(2, size):
last_sum[i] = last_sum[i - 1] +... | 5,312,549 |
def starting_point(conditions, state_variables, phase_records, grid):
"""
Find a starting point for the solution using a sample of the system energy surface.
Parameters
----------
conditions : OrderedDict
Mapping of StateVariable to array of condition values.
state_variables : list
... | 5,312,550 |
def intersects(a0, a1, b0, b1):
"""
Checks whether two line segments, each defined by two end points, will intersect.
"""
# First line is vertical
if a0[0] == a1[0]:
# Both lines are vertical
if b0[0] == b1[0]:
return (a0[0] == b0[0]) and (in_range(b0[1], a0[1], a1[1]) or... | 5,312,551 |
def getAccident(id=None):
""" return the Accident object or None if not exist
return a list of all Accident if no id passed.
return one object if filtered by 'id'"""
if id:
return Accident.query.get(id)
return Accident.query.all() | 5,312,552 |
def stream_blocks():
"""
Start incomming stream for new blocks
"""
#add height
query = iroha.blocks_query()
ic.sign_query(query, user_private_key)
for block in net.send_blocks_stream_query(query):
pprint('The next block arrived: {}'.format(MessageToDict(block)),indent=1) | 5,312,553 |
def ranges(int_list):
"""
Given a sorted list of integers function will return
an array of strings that represent the ranges
"""
begin = 0
end = 0
ranges = []
for i in int_list:
# At the start of iteration set the value of
# `begin` and `end` to equal the first element
... | 5,312,554 |
def format_data(x_data=None,y_data=None):
"""
=============================================================================
Function converts a list of separate x and y coordinates to a format suitable
for plotting in ReportLab
Arguments:
x_data - a list of x coordinates (or any object that can be indexe... | 5,312,555 |
def clean_combined_de_identified_clean_dataset(project_id=None,
dataset_id=None):
"""
Run all clean rules defined for the deidentified ehr and rdr clean dataset.
:param project_id: Name of the BigQuery project.
:param dataset_id: Name of the dataset to cl... | 5,312,556 |
def test_cmdstep_name_required():
"""Cmd Step requires name."""
with pytest.raises(AssertionError):
CmdStep(None, None) | 5,312,557 |
def gaslib_to_network_data(network_file, scenario_file, contract_aux_elements=True, debug=False):
"""Read a gaslib instance from files and create network data.
The function returns data that can be passed immediatley to the
constructor of Network.
Parameters
----------
network_file : str
... | 5,312,558 |
def write_plugins_index(file_name, plugins):
"""
Writes the list of (name, version, description) of the plugins given
into the index file in JSON format.
Returns True if the file was actually updated, or False if it was already
up-to-date.
"""
# separators is given to avoid trailing whitespa... | 5,312,559 |
def concatenate(inputs, axis=None):
"""Wrapper of `numpy.concatenate` and `sparse.concatenate`
Parameters
----------
inputs : sequence of STensor/DTensor
Tensor to be concatenated.
axis : int or None, optional
Axis to operate on, by default None
"""
pass | 5,312,560 |
def removeAllFilesUnder(top,rejecting_re=None,matching_re=None):
""" remove all files under top including folders """
from vyperlogix.misc import ObjectTypeName
isMatchingRe = ObjectTypeName.typeClassName(matching_re) == '_sre.SRE_Pattern'
for root, dirs, files in walk(top, topdown=False, rejecting_re=r... | 5,312,561 |
def set_datasets(relations_program_tag, poa_article):
"""
Add related_item tags for each dataset
"""
for dataset_object in poa_article.datasets:
# Check for at least one identifier before adding the related_item
if not related.do_dataset_related_item(dataset_object):
continue... | 5,312,562 |
def ensure_secret_backend(client):
"""Ensure that vault has a KV backend mounted at secret.
:param client: Client to use to talk to vault
:type client: CharmVaultClient
"""
try:
client.hvac_client.enable_secret_backend(
backend_type='kv',
description='Charm created K... | 5,312,563 |
def explicit_endorsements(user: domain.User) -> List[domain.Category]:
"""
Load endorsed categories for a user.
These are endorsements (including auto-endorsements) that have been
explicitly commemorated.
Parameters
----------
user : :class:`.domain.User`
Returns
-------
list
... | 5,312,564 |
def updateDeadlineParams(courseID, mode, hours_before):
"""
Queries the Django database for the course and updates it with the new variables. \n
:courseID: ID of the course \t
:type: int \n
:mode: mode of operation: True == active, False == inactive \t
:type: bool \t
:timeLimit: Hours before... | 5,312,565 |
def print_header(msg, header_char='='):
"""Print Header."""
header_line = header_char * OUTPUT_WIDTH
print(header_line)
print(msg)
print(header_line) | 5,312,566 |
def detec_apache_root(binPath):
"""
根据apachectl -V 获得apache的安装路径
"""
result = commands.getoutput(binPath + """ -V | grep -i "HTTPD_ROOT"
| awk -F '[="]' '{print $3}'""")
return result | 5,312,567 |
def hindu_zodiac(tee):
"""Return the zodiacal sign of the sun, as integer in range 1..12,
at moment tee."""
return quotient(float(hindu_solar_longitude(tee)), deg(30)) + 1 | 5,312,568 |
def SearchRelativeLongitude(body, targetRelLon, startTime):
"""Searches for when the Earth and another planet are separated by a certain ecliptic longitude.
Searches for the time when the Earth and another planet are separated by a specified angle
in ecliptic longitude, as seen from the Sun.
A relativ... | 5,312,569 |
def _fitFunc2(x, *pfit, verbose=True, follow=[], errs=None):
"""
for curve_fit
"""
global pfitKeys, pfix, _func, Ncalls, verboseTime
Ncalls +=1
params = {}
# -- build dic from parameters to fit and their values:
for i,k in enumerate(pfitKeys):
params[k]=pfit[i]
# -- complete ... | 5,312,570 |
def sendForward(cwt,solver):
"""Use this function to communicate data between nodes"""
if solver.nodeMasterBool:
cwt = io.sweptWrite(cwt,solver)
buff = numpy.copy(solver.sharedArray[:,:,-solver.splitx:,:])
buffer = solver.clusterComm.Sendrecv(sendobj=buff,dest=solver.neighbors[1],source=... | 5,312,571 |
def get_parameters(img_path_complete):
"""
Get the parameters of an hyper-spectral image from file.
:param img_path_complete: complete path of the bil file to get the parameters. Ex. <path>/img.bil
:return: array of totals of [lines, samples, bands]
"""
file_info = img_path_complete + dcube_h #... | 5,312,572 |
def phone_move_handler(pid):
"""
@api {post} /v1/asset/phone/move/{int:id} 流转 资产设备
@apiName MovePhone
@apiGroup 项目
@apiDescription 流转 资产设备
@apiParam {int} id
@apiParam {int} borrow_id 流转人 ID
@apiParamExample {json} Request-Example:
{
"borrow_id": 2
}
@apiSuccessExampl... | 5,312,573 |
def extractLargestRegion(actor):
"""Keep only the largest connected part of a mesh and discard all the smaller pieces.
.. hint:: |largestregion.py|_
"""
conn = vtk.vtkConnectivityFilter()
conn.SetExtractionModeToLargestRegion()
conn.ScalarConnectivityOff()
poly = actor.GetMapper().GetInput(... | 5,312,574 |
def query_stock_concept(code="", date=""):
"""获取概念分类
@param code:股票代码,默认为空。
@param date:查询日期,默认为空。不为空时,格式 XXXX-XX-XX。
"""
data = rs.ResultData()
if code is None or code == "":
code = ""
if code != "" and code is not None:
if len(code) != cons.STOCK_CODE_LENGTH:
... | 5,312,575 |
def create():
"""
Creates the necessary resources for the components test to run.
- Creates a named tunnel with a random name.
- Creates a random CNAME DNS entry for that tunnel.
- Creates a random AAAA DNS entry for a classic tunnel.
Those created resources are added to the config (obtained... | 5,312,576 |
def checkForVideoRetainment(op, graph, frm, to):
"""
Confirm video channel is retained in the resulting media file.
:param op:
:param graph:
:param frm:
:param to:
:return:
@type op: Operation
@type graph: ImageGraph
@type frm: str
... | 5,312,577 |
def test_catching_a_value_error():
"""Temporary test to make sure that we can run tests."""
with pytest.raises(KeyError):
{}['no-matching-key'] | 5,312,578 |
def test_update_travis_file_with_global():
""" Create a standard travis file and update it.
"""
path_old, path_expected = _prepare_old_file("travis_with_globals", ".yml")
args = ['--travisfile', path_old]
command = Command()
command.run(args)
assert _compare_file(path_old, path_expected) | 5,312,579 |
def test_save_amendment(session):
"""Assert that creating an amendment statement on a non-RL financing statement contains all expected elements."""
json_data = copy.deepcopy(AMENDMENT_STATEMENT)
del json_data['createDateTime']
del json_data['amendmentRegistrationNumber']
del json_data['payment']
... | 5,312,580 |
def get_console_scripts(entry_points):
"""pygradle's 'entrypoints' are misnamed: they really mean 'consolescripts'"""
if not entry_points:
return None
if isinstance(entry_points, dict):
return entry_points.get("console_scripts")
if isinstance(entry_points, list):
result = []
... | 5,312,581 |
def create_deepcopied_groupby_dict(orig_df, obs_id_col):
"""
Will create a dictionary where each key corresponds to a unique value in
`orig_df[obs_id_col]` and each value corresponds to all of the rows of
`orig_df` where `orig_df[obs_id_col] == key`.
Parameters
----------
orig_df : pandas D... | 5,312,582 |
def _create_configuration(
user_agent: Optional[str] = None,
user_agent_config_yaml: Optional[str] = None,
user_agent_lookup: Optional[str] = None,
hdx_url: Optional[str] = None,
hdx_site: Optional[str] = None,
hdx_read_only: bool = False,
hdx_key: Optional[str] = None,
hdx_config_json: ... | 5,312,583 |
def import_path(fullpath):
"""
Import a file with full path specification. Allows one to
import from anywhere, something __import__ does not do.
"""
import os,sys
path, filename = os.path.split(fullpath)
filename, ext = os.path.splitext(filename)
sys.path.append(path)
module = __im... | 5,312,584 |
def batch_autocorr(data, lag, starts, ends, threshold, backoffset=0):
"""
Calculate autocorrelation for batch (many time series at once)
:param data: Time series, shape [n_pages, n_days]
:param lag: Autocorrelation lag
:param starts: Start index for each series
:param ends: End index for e... | 5,312,585 |
def merge_yaml(y1, y2):
""" Merge two yaml HOT into one
The parameters, resources and outputs sections are merged.
:param y1: the first yaml
:param y2: the second yaml
:return y: merged yaml
"""
d1 = yaml.load(y1)
d2 = yaml.load(y2)
for key in ('parameters', 'resources', 'outputs')... | 5,312,586 |
def infix(token_list):
"""
Parses Infix notation and returns the equivilant RPN form (Pseudocode used from: https://en.wikipedia.org/wiki/Shunting-yard_algorithm)
Parameters
==========
token_list : list
The list of infix tokens
Returns
--------
output : list
This is t... | 5,312,587 |
def download(isamAppliance, filename, id=None, comment=None, check_mode=False, force=False):
"""
Download one snapshot file to a zip file.
Multiple file download is now supported. Simply pass a list of id.
For backwards compatibility the id parameter and old behaviour is checked at the beginning.
""... | 5,312,588 |
def pre_process_steps(
draw, return_kwargs: bool = False
) -> Union[
st.SearchStrategy[pre_process_step_pb2.PreProcessStep],
st.SearchStrategy[Tuple[pre_process_step_pb2.PreProcessStep, Dict]],
]:
"""Returns a SearchStrategy for a pre_process_step plus maybe the kwargs."""
kwargs: Dict = {}
kwa... | 5,312,589 |
def _decode(hdf5_handle):
"""
Construct the object stored at the given HDF5 location.
"""
if 'symmetries' in hdf5_handle:
return _decode_symgroup(hdf5_handle)
elif 'rotation_matrix' in hdf5_handle:
return _decode_symop(hdf5_handle)
elif 'matrix' in hdf5_handle:
return _de... | 5,312,590 |
def r_network():
"""Loads network from the R library tmlenet for comparison"""
df = pd.read_csv("tests/tmlenet_r_data.csv")
df['IDs'] = df['IDs'].str[1:].astype(int)
df['NETID_split'] = df['Net_str'].str.split()
G = nx.DiGraph()
G.add_nodes_from(df['IDs'])
for i, c in zip(df['IDs'], df['NE... | 5,312,591 |
def _legend_with_triplot_fix(ax: plt.Axes, **kwargs):
"""Add legend for triplot with fix that avoids duplicate labels.
Parameters
----------
ax : matplotlib.axes.Axes
Matplotlib axes to apply legend to.
**kwargs
These parameters are passed to :func:`matplotlib.pyplot.legend`.
R... | 5,312,592 |
def gjson_from_tasks(tasks: Dict[TileIdx_txy, Any],
grid_info: Dict[TileIdx_xy, Any]) -> Dict[str, Dict[str, Any]]:
"""
Group tasks by time period and compute geosjon describing every tile covered by each time period.
Returns time_period -> GeoJSON mapping
Each feature in GeoJSON ... | 5,312,593 |
def getLogLevelNumber(loglevelname):
"""Parses log level name into log level number.
Returns int value of log level. On failure, DEBUG level value is returned."""
number = getattr(logging, loglevelname, None)
if not isinstance(number, int):
module_logger.debug("failed to parse log level name... | 5,312,594 |
def arcz_to_arcs(arcz):
"""Convert a compact textual representation of arcs to a list of pairs.
The text has space-separated pairs of letters. Period is -1, 1-9 are
1-9, A-Z are 10 through 36. The resulting list is sorted regardless of
the order of the input pairs.
".1 12 2." --> [(-1,1), (1,2),... | 5,312,595 |
def bbox_to_radec_grid(wcs, bbox, tol=1e-7):
"""
Create an ra/dec grid aligned with pixels from a bounding box.
Parameters
----------
wcs : `lsst.afw.geom.SkyWcs`
WCS object
bbox : `lsst.geom.Box2I`
Bounding box
tol : `float`
Tolerance for WCS grid approximation
... | 5,312,596 |
def step2(x):
"""Convolution of three step functions."""
y = np.zeros_like(x)
y[x > 0] = 1/2 * x[x > 0]**2
return y | 5,312,597 |
def evtx2json(input_path: str, shift: Union[str, datetime], multiprocess: bool = False, chunk_size: int = 500) -> List[dict]:
"""Convert Windows Eventlog to List[dict].
Args:
input_path (str): Input Eventlog file.
multiprocess (bool): Flag to run multiprocessing.
chunk_size (int): Size ... | 5,312,598 |
def multid_dilution_wrapper(inducers,constructs,fname,avoidedges=[],maxinducer=500,\
wellvol=50,shuffle=False,wellorder="across",mypath=".",start=None):
"""this function contains some helpful pre-sets for doing multiple
inducer sweeps in a 384 well plate.
inducers:
this is a list of list... | 5,312,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.