content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def _learn_individual_mixture_weights(n_users, alpha, multinomials, max_iter, tol, val_mat, prior_strength, num_proc):
"""
Learns the mixing weights for each individual user, uses multiple-processes to make it faster.
:param n_users: Int, total number of users.
:param alpha: prior (learned through glob... | 47,500 |
def SetDebugMode(enabled=True):
"""Enable Debug mode globally.
It will disable all memory sharing optimizations.
Parameters
----------
enabled : boolean
Whether to enable debug mode.
Returns
-------
None
"""
global option
option['debug_mode'] = enabled | 47,501 |
def banana(cls):
"""
A decorator for a class that adds the ability to create Permissions and Handlers
from their Checks.
"""
cls.__checks = set()
# Basically tell checks that we are the class, not a medium to pass things through
cls.__banana = True
cls_annotations = cls.__dict__.get("_... | 47,502 |
def residual_v2_conv(
kernel_size: int,
stride: int,
depth: int,
is_deconv: bool,
add_max_pool: bool,
add_bias: bool,
is_train: bool,
input_op: tf.Tensor,
name: str = None,
) -> tf.Tensor:
"""Creates a residual convolution in the style of He et al. April 2016.
This is the second... | 47,503 |
def run_tests(handle_fail=False):
"""Run all tests."""
for test in test_functions:
print_args = [test.__name__]
if handle_fail:
child_pid = os.fork()
if child_pid == 0:
if test():
print_success(*print_args)
else:
... | 47,504 |
def dump_cups_with_first(cups: list[int]) -> str:
"""Dump list of cups with highlighting the first one
:param cups: list of digits
:return: list of cups in string format
"""
dump_cup = lambda i, cup: f'({cup})' if i == 0 else f' {cup} '
ret_val = ''.join([dump_cup(i, cup) for i, cup in enumerat... | 47,505 |
def test_check_consistency1():
"""Test check consistency, with label and lr data."""
roi = ROI()
labels = ['a', 'b', 'c']
lrs = ['l', 'r', 'l']
roi.set_labels(labels, lrs)
roi.check_consistency()
roi.labels.pop()
with raises(InconsistentDataError):
assert roi.check_consiste... | 47,506 |
def filter_plt(system,mn=-1,mx=3,npts=1000,yticks=False,forceticks=False,gtitle="",
xlim=False,ylim=False,ysize=10,xticks=False,xsize=False,sv=False):
""" Filter Plotting Function:
Purpose: Generates a magnitude only bode plot specifically for filter design.
Required Arguments:
-------------------
system: ... | 47,507 |
def init(strKernel, iKernelPar=1, iALDth=1e-4, iMaxDict=1e3):
"""
Function initializes krls dictionary. |br|
Args:
strKernel (string): Type of the kernel
iKernelPar (float): Kernel parameter [default = 1]
iALDth (float): ALD threshold [default = 1e-4]
iMaxDict (int): Max... | 47,508 |
def update_config_param(source_file,pairs,v=0,file_log=sys.stdout):
"""
Updates a list of pairs [parameter,value] in a configuration file. Should be valid to any .ini file, but this is
used to override the configuration on the CorrelX configuration file.
Parameters
----------
source_file... | 47,509 |
def prune_scope():
"""Provides a scope in which Pruned layers and models can be deserialized.
For TF 2.X: this is not needed for SavedModel or TF checkpoints, which are
the recommended serialization formats.
For TF 1.X: if a tf.keras h5 model or layer has been pruned, it needs to be
within this
scope to b... | 47,510 |
async def test_convert_timedelta_to_auto_off(
event_loop: AbstractEventLoop,
) -> None:
"""Test the convert_timedelta_to_auto_off tool."""
with raises(EncodingError) as exc_info_min:
await convert_timedelta_to_auto_off(
event_loop, TEST_TIMEDELTA_MIN_FAILURE
)
asser... | 47,511 |
def _find_chrome(user_given_executable=None):
""" Finds a Chrome executable.
Search Chrome on a given path. If no path given,
try to find Chrome or Chromium-browser on a Windows or Unix system.
Parameters
----------
- `user_given_executable`: str (optional)
+ A filepath leading to a Ch... | 47,512 |
def is_valid_br_cnpj(cnpj):
"""
Accept an string parameter cnpj and
Check if is brazilian CNPJ valid.
Return True or False
"""
# Extract dots, stroke, slash
cnpj = re.sub('[.|\-/|/]', '', str(cnpj))
# if does not contain numerical characters
if not re.match(r'^\d{14}$', cnpj) or cn... | 47,513 |
def get_supported_locales():
"""
Returns a list of Locale objects that the Web Interfaces supports
"""
locales = BABEL.list_translations()
locales.append(Locale("en"))
sorted_locales = sorted(locales, key=lambda x: x.language)
return sorted_locales | 47,514 |
def get_pipx_user_bin_path() -> Optional[Path]:
"""Returns None if pipx is not installed using `pip --user`
Otherwise returns parent dir of pipx binary
"""
# NOTE: using this method to detect pip user-installed pipx will return
# None if pipx was installed as editable using `pip install --user -e`... | 47,515 |
def _normalize_int_key(key, length, axis_name=None):
"""
Normalizes an integer signal key.
Leaves a nonnegative key as it is, but converts a negative key to
the equivalent nonnegative one.
"""
axis_text = '' if axis_name is None else axis_name + ' '
if key < -length o... | 47,516 |
async def _send_status_update(guild: disnake.Guild, message: str) -> None:
"""Inform the events lead with a status update when the command is ran."""
channel: disnake.TextChannel = guild.get_channel(Channels.code_jam_planning)
await channel.send(f"<@&{Roles.events_lead}>\n\n{message}") | 47,517 |
def create_interview_in_jobma(interview):
"""
Create a new interview on Jobma
Args:
interview (Interview): An interview object
"""
client = get_jobma_client()
url = urljoin(settings.JOBMA_BASE_URL, "interviews")
job = interview.job
first_name, last_name = get_first_and_last_name... | 47,518 |
def get_solutions(N, K, W_hat, x):
"""
Get valid indices of x that sum up to S
"""
# Scalar form of y = W_hat * x
S = scalar(W_hat @ x)
# print(f'Scalar value = {S}')
solutions = []
for partition in sum_to_S(S, K):
if len(set(partition)) == len(partition) and max(partition) < N:
... | 47,519 |
def test_get_engagement__reuses_engagement_when_cached_engagement_unexpired__using_endpoint_id(
client_configuration: QCSClientConfiguration,
):
"""
Assert that endpoint ID is correctly used to engage against an endpoint.
"""
engagement_manager = EngagementManager(client_configuration=client_configu... | 47,520 |
def get_actual_order(geometry, order):
"""
Return the actual integration order for given geometry.
Parameters
----------
geometry : str
The geometry key describing the integration domain,
see the keys of `quadrature_tables`.
Returns
-------
order : int
If `order... | 47,521 |
def getcwd(*args,**kw):
"""getcwd() -> path
Return a unicode string representing the current working directory."""
return __BRYTHON__.brython_path | 47,522 |
def print_terms(terms, parent):
""" Prints a list of flattened dictionary keys """
for term in terms:
if type(terms[term]) != dict:
print('\t' + parent + term)
else:
print_terms(terms[term], parent + term + '.') | 47,523 |
def sample_graph(B, logvars, n_samp):
"""
Generate data given B matrix, variances
"""
p = len(logvars)
N = np.random.normal(0, np.sqrt(np.exp(logvars)), size=(n_samp, p))
return (np.linalg.inv(np.eye(p) - B.T)@N.T).T | 47,524 |
def unittest(path=TESTS_PATH):
"""Run tests using the unittest module
"""
local("python -m unittest discover -s %s" % path) | 47,525 |
def rotate_ne_rt(n, e, ba):
"""
Rotates horizontal components of a seismogram.
The North- and East-Component of a seismogram will be rotated in Radial
and Transversal Component. The angle is given as the back-azimuth, that is
defined as the angle measured between the vector pointing from the statio... | 47,526 |
def pwgen(pw_len=16):
""" Generate a random password with the given length.
Allowed chars does not have "I" or "O" or letters and
digits that look similar -- just to avoid confusion.
"""
return get_random_string(pw_len, 'abcdefghjkmnpqrstuvwxyz'
'ABCDEFGH... | 47,527 |
def run_zeopp(structure: Structure) -> dict:
"""Run zeopp with network -ha -res (http://www.zeoplusplus.org/examples.html)
to find the pore diameters
Args:
structure (Structure): pymatgen Structure object
Returns:
dict: pore analysis results
"""
if is_tool("network"):
w... | 47,528 |
def get_property_data(sch=""):
"""Get property id and return dictionary with data
Attributes:
sch: property id
"""
property_url = "http://ats.jeffco.us/ats/displaygeneral.do?sch={0}".format(sch)
r = requests.get(property_url)
property_page = BeautifulSoup(r.text, "lxml")
prop... | 47,529 |
def sanitize_fname(fname):
"""
Ensures that fname is a path under the current working directory.
"""
root_dir = os.getcwd()
return opath.join(
bytes(root_dir, encoding='ascii'),
opath.normpath(
b'/' + fname).lstrip(b'/')) | 47,530 |
def tcl_delta_remote(curef):
"""
Prepare remote version for delta scanning.
:param curef: PRD of the phone variant to check.
:type curef: str
"""
remotedict = networkutilstcl.remote_prd_info()
fvver = remotedict.get(curef, "AAA000")
if fvver == "AAA000":
print("NO REMOTE VERSION... | 47,531 |
def prodi(items: Iterable[float]) -> float:
"""Imperative product
>>> prodi( [1,2,3,4,5,6,7] )
5040
"""
p: float = 1
for n in items:
p *= n
return p | 47,532 |
def unpack(series):
"""Make the names in `series` available as globals.
series: Series with variables names in the index
"""
# TODO: Make this a context manager, so the syntax is
# with series:
# and maybe even add an __exit__ that copies changes back
frame = inspect.currentframe()
call... | 47,533 |
def transformer_prepare_encoder(inputs, target_space, hparams):
"""Prepare one shard of the model for the encoder.
Args:
inputs: a Tensor.
target_space: a Tensor.
hparams: run hyperparameters
Returns:
encoder_input: a Tensor, bottom of encoder stack
encoder_self_attention_bias: a Tensor, con... | 47,534 |
def get_bottom_left_coords(
text_width: int,
text_height: int,
text_x: int,
text_y: int,
) -> Tuple[TextOrg, BoxCoords]:
"""Get coordinates for text and background in bottom left corner.
Args:
text_width: Width of the text to be drawn.
text_height: Height of the text to be drawn... | 47,535 |
def read_gcs_zarr(zarr_url, token='/opt/gcsfuse_tokens/impactlab-data.json', check=False):
"""
takes in a GCSFS zarr url, bucket token, and returns a dataset
Note that you will need to have the proper bucket authentication.
"""
fs = gcsfs.GCSFileSystem(token=token)
store_path = fs.get_map... | 47,536 |
def bor(*args: int) -> int:
"""Bitwise or.
Example:
bor(0x01, 0x10) == 0x01 | 0x10
Returns:
int: Inputs.
"""
return list(accumulate(args, operator.or_))[-1] | 47,537 |
def mlnet_components_kinds():
"""
Retrieves all kinds.
"""
from Scikit.ML.DocHelperMlExt import MamlHelper
kinds = list(MamlHelper.GetAllKinds())
kinds += ["argument", "command"]
kinds = list(set(kinds))
titles = {
'anomalydetectortrainer': 'Anomaly Detection',
'binaryc... | 47,538 |
def get_model(model_name, recompile=False):
""" Get compiled StanModel
This will compile the stan model if a cached pickle does not exist.
Args:
model_name (str): model name without `.stan`
recompile (bool): Force force recompilation.
"""
model_file = model_path(model_name)
cach... | 47,539 |
def get_pkr_path(raise_if_not_found=True):
"""Return the path of the pkr folder
If the env. var 'PKR_PATH' is specified, it is returned, otherwise a
KeyError exception is raised.
"""
full_path = Path(os.environ.get(PATH_ENV_VAR, os.getcwd())).absolute()
pkr_path = full_path
while pkr_path.... | 47,540 |
def wait_for_aee_finish_v1(cfs_name, cfs_namespace): # noqa: C901
"""
Consults k8s API for status information about our CFS/AEE instance; returns
its exit code.
"""
try:
config.load_incluster_config()
except ConfigException: # pragma: no cover
config.load_kube_config() # Devel... | 47,541 |
def hexString(s):
"""
Output s' bytes in HEX
s -- string
return -- string with hex value
"""
return ":".join("{:02x}".format(ord(c)) for c in s) | 47,542 |
def hydrate_board_from_model(a, radius, rect_width):
"""
:type a: ndarray
:type radius: int
:return: Board
"""
b = Board(radius)
for cellId in b.cells:
thid = get_thid_from_cellId(cellId, rect_width)
value = a[thid.y][thid.x]
b.change_ownership(cellId, get_player_name_from_resource(value), in... | 47,543 |
def tree_walk():
"""Walk the source folder using pathlib. Populate 3 dicts, a folder dict,
a file dict, and a stats dict.
- Returns:
- [dict]: k: folders; v: size
- [dict]: k: files; v: size
- [dict]:
'file_size'
'num_dirs'
'num_files'
"""
... | 47,544 |
def extract_events(
fpath,
outdir=None,
photons=tuple(),
pulses=tuple(),
recos=tuple(),
triggers=tuple(),
truth=False
):
"""Extract event information from an i3 file.
Parameters
----------
fpath : str
Path to I3 file
outdir : str, optional
Directory in w... | 47,545 |
def test_011_parseType_legal():
"""Check parsing of the report type."""
assert Metar.Metar("METAR").type, "METAR"
assert Metar.Metar("SPECI").type, "SPECI"
assert Metar.Metar("METAR").correction is None
assert Metar.Metar("METAR COR").correction == "COR"
raisesParserError("TAF") | 47,546 |
def StiffnessOn(proxy):
"""Turn stiffness on.
Keyword arguments:
proxy -- Nao proxy
"""
# We use the "Body" name to signify the collection of all joints
pNames = "Body"
pStiffnessLists = 1.0
pTimeLists = 1.0
proxy.stiffnessInterpolation(pNames, pStiffnessLists, pTimeLists) | 47,547 |
def handle_response(response, content_type, file_path=None):
"""handle response. Extract, transform and emit/write to file"""
if content_type == "application/json":
if file_path is None:
return response.json()
else:
save_json(response.json(), file_path)
elif conte... | 47,548 |
def test_integer_with_wrong_type():
"""Incorrect type"""
with pytest.raises(TypeError) as e:
val.is_integer('a', desc='test')
assert str(e.value) == 'Expected test to be an integer' | 47,549 |
def test_tool_version_put_success():
"""Test `PUT /tools/{id}/versions/{version_id}` for updating tool version
data given tool `id` and `version_id`.
"""
endpoint = f"/tools/{test_obj_id}/versions/{test_version_obj_id}"
response = requests.put(
base_url + endpoint, json=MOCK_VERSION_NO_ID, h... | 47,550 |
def parse_request(env) -> tuple[str, dict]:
""" Parse request: resolve method, load method config, merge request method params with defaults.
Return: method name string, method params dict """
request_method = env['REQUEST_METHOD'].upper()
url_parts = urlparse(unquote(env['REQUEST_URI']))
loggin... | 47,551 |
def randomCaptchaText(char_set=CAPTCHA_LIST, captcha_size=CAPTCHA_LENGTH):
"""
随机生成定长字符串
:param char_set: 备选字符串列表
:param captcha_size: 字符串长度
:return: 字符串
"""
captcha_text = [random.choice(char_set) for _ in range(captcha_size)]
return ''.join(captcha_text) | 47,552 |
def integral_total(Nstrips):
"""
The total integral.
"""
return integral_4(Nstrips) + integral_1(Nstrips) | 47,553 |
def calculate_amplitude(dem, Template, scale, age, angle):
"""Calculate amplitude and SNR of features using a template
Parameters
----------
dem : DEMGrid
Grid object of elevation data
Template : WindowedTemplate
Class representing template function
scale : float
Scale o... | 47,554 |
def app(request):
"""Session-wide Testable Flask Application
"""
_app.config.from_mapping(
TESTING=True,
SECRET_KEY=os.environ.get('SECRET_KEY'),
SQLALCHEMY_DATABASE_URI=os.getenv('TEST_DATABASE_URL'),
SQLALCHEMY_TRACK_MODIFICATIONS=False,
WTF_CSRF_ENABLED=False,
... | 47,555 |
async def test_fanv2_read_state(hass, utcnow):
"""Test that we can read the state of a HomeKit fan accessory."""
sensor = create_fanv2_service()
helper = await setup_test_component(hass, [sensor])
helper.characteristics[V2_ACTIVE].value = False
state = await helper.poll_and_get_state()
assert s... | 47,556 |
def number_limit_sub_validator(entity_config: OrderedDict) -> OrderedDict:
"""Validate a number entity configurations dependent on configured value type."""
value_type = entity_config[CONF_TYPE]
min_config: float | None = entity_config.get(NumberSchema.CONF_MIN)
max_config: float | None = entity_config.... | 47,557 |
def patch_2D_aggregator(
patches: np.ndarray,
orig_shape: Tuple[int],
patch_loc: np.array,
count_ndarray: Union[np.array, None] = None,
) -> np.ndarray:
"""
Aggregate patches to a whole 2D image.
Args:
patches: shape is [patch_num, Channel, patch_size, patch_size]
orig_shape... | 47,558 |
def vmap_grad(forward_fn: Callable, params: PyTree, samples: Array) -> PyTree:
"""
compute the jacobian of forward_fn(params, samples) w.r.t params
as a pytree using vmapped gradients for efficiency
"""
complex_output = nkjax.is_complex(jax.eval_shape(forward_fn, params, samples))
real_params = ... | 47,559 |
def test_mir_remember_me_in_read(mir_data_object):
"""
Mir in_read checker.
Make sure that certain values in the in_read file of the test data set match what
we know to be 'true' at the time of observations, including that spare values are
stored as zero.
"""
mir_data = mir_data_object
... | 47,560 |
def random_crop_list(images, size, pad_size=0, order="CHW", boxes=None):
"""
Perform random crop on a list of images.
Args:
images (list): list of images to perform random crop.
size (int): size to crop.
pad_size (int): padding size.
order (string): order of the 'height', 'wi... | 47,561 |
def normalize_resource_paths(resource_paths: List[str]) -> List[str]:
"""
Takes a list of resource relative paths and normalizes to lowercase
and with the "ed-fi" namespace prefix removed.
Parameters
----------
resource_paths : List[str]
The list of resource relative paths
Returns
... | 47,562 |
def split_json_data(df, folder, column = "truthScale"):
"""
Split data into two subset according to the label
dataframe: the original dataframe
column: the name of the columns that contain labels
folder: the path to the folder containing new data file
Return the path to the new file
"... | 47,563 |
def GetDegenerateSites(seq1, seq2,
degeneracy=4,
position=3):
"""returns two new sequenes containing only degenerate sites.
Only unmutated positions are counted.
"""
new_seq1 = []
new_seq2 = []
for x in range(0, len(seq1), 3):
c1 = seq1[x:... | 47,564 |
def test_crop():
"""Test of crop of epochs."""
raw, events, picks = _get_data()
epochs = Epochs(raw, events[:5], event_id, tmin, tmax, picks=picks,
preload=False, reject=reject, flat=flat)
pytest.raises(RuntimeError, epochs.crop, None, 0.2) # not preloaded
data_normal = epochs.g... | 47,565 |
def ransac(a, b, model: str ='rigid', inlier_threshold: float = 1.0, ransac_it: int = 100):
"""Estimates parameters of given model by applying RANSAC on corresponding point sets A and B
(preserves handedness).
:param a: nx4 array of points
:param b: nx4 array of points
:param model: Specify the mod... | 47,566 |
def create_telescope_types(session: scoped_session, telescope_types: List, created: datetime):
"""Create a list of TelescopeType objects.
:param session: the SQLAlchemy session.
:param telescope_types: a list of tuples of telescope type id and names.
:param created:the created datetime in UTC.
:ret... | 47,567 |
def update(*p):
""" Update dicts given in params with its precessor param dict
in reverse order """
return reduce(lambda x, y: x.update(y) or x,
(p[i] for i in range(len(p)-1,-1,-1)), {}) | 47,568 |
def alphabet_to_use(three_letter_code, parity, direction):
"""Return tuple of alphabet to be used for glue in given direction on tile of
given parity.
Note that this refers to the alphabet used for the CANONICAL direction, which
may be the opposite of direction."""
if not parity in (0,1):
r... | 47,569 |
def inject_marker_data(mark: models.PsqlgraphDataMark, item: p.Function) -> None:
"""Resolves data for the custom psqlgraph data
Examples:
.. code-block::
@pytest.mark.psqlgraph_data(
name="pg_data",
driver_name="pg_driver",
data_dir=here,
reso... | 47,570 |
def get_tipranks_sentiment(collection):
"""
:param collection: "100-most-popular", "upcoming-earnings", "new-on-robinhood", "technology", "oil-and-gas",
"finance", "software-service", "energy", "manufacturing", "consumer-products", "etf", "video-games", "social-media",
"health", "entertainme... | 47,571 |
def lBoundedForward(x, lower):
"""
Transform from transformed (unconstrained) parameters to physical ones with upper limit
Args:
x (float): vector of transformed parameters
lower (float): vector with lower limits
Returns:
Float: transformed variables and log Jacobian
... | 47,572 |
async def test_update_automated_pool(
snapshot,
fixt_launch_workers,
fixt_db,
fixt_create_automated_pool, # noqa
fixt_auth_context,
): # noqa
"""Create automated pool, update this pool, remove this pool"""
# check that pool was successfully created'
assert fixt_create_automated_pool["... | 47,573 |
def mostrar(s: str) -> None:
"""Muestra una frase letra por letra."""
for c in s:
print(c, end="", flush=True)
sleep(0.5)
print() | 47,574 |
def date_range(begin_date, end_date):
"""
:param begin_date: 起始日期,string
:param end_date: 结束日期,string
:return: dates: 指定日期范围内日期列表,元素类型string
"""
dates = []
dt = datetime.datetime.strptime(begin_date, "%Y-%m-%d")
date = begin_date[:]
while date <= end_date:
dates.append(da... | 47,575 |
def in_water(latitude: float, longitude: float) -> bool:
"""
Simple function to parse a shapefile from OpenStreet Maps.
Returns a boolean signifying a location is or is not over
water.
LRU Caching provided via functools.lru_cache. Uses memoization
to cache recently scanned results and provide l... | 47,576 |
def createNeighDict(rP, lP, b, c):
"""Finds the neighbours nearest to a lost packet in a particular tensor plane
# Arguments
rP: packets received in that tensor plane
lp: packets lost in that tensor plane
b,c : batch and channel number denoting the tensor plane
# Returns
Di... | 47,577 |
def path_rollout(agent,
env,
path_num,
require_q,
recv_q,
noise,
render,
action_repeat,
process_id=0):
"""
Generates several paths for each worker.
Args:
agent: th... | 47,578 |
def get_norm_3d(norm: str, out_channels: int, bn_momentum: float = 0.1) -> nn.Module:
"""Get the specified normalization layer for a 3D model.
Args:
norm (str): one of ``'bn'``, ``'sync_bn'`` ``'in'``, ``'gn'`` or ``'none'``.
out_channels (int): channel number.
bn_momentum (float): the ... | 47,579 |
def cancel_cheque():
"""取消支票"""
user_id = '96355632'
sn = request.values['sn']
result = pay_client.app_cancel_cheque(user_id, sn, ret_result=True)
return render_template('sample/info.html', title='取消支票结果',
msg=json.dumps({'status_code': result.status_code, 'data': result.... | 47,580 |
def to_relative_engagement(lookup_table, duration, wp_score, lookup_keys=None):
""" Convert watch percentage to relative engagement.
:param lookup_table: duration ~ watch percentage table, in format of dur: [1st percentile, ..., 1000th percentile]
:param duration: target input duration
:param wp_score: ... | 47,581 |
def validate_statistic(value):
"""Statistic currently supported"""
if not value in astatic.DP_STATS_CHOICES:
CL_CHOICES_str = ', '.join(astatic.DP_STATS_CHOICES)
user_msg = f'{VALIDATE_MSG_UNSUPPORTED_STATISTIC} {CL_CHOICES_str}'
raise ValidationError(user_msg) | 47,582 |
def factory(ptype, **kwargs):
"""Factory method to build `DenityProfile` objects
Keyword arguments are passed to class c'tor
Parameters
----------
ptype : str
Density profile type
Returns
-------
profile : `DensityProfile`
Newly created object
"""
import dmsk... | 47,583 |
def _search_signals(name, stype, intf):
""" Given a port name and signal type find a match in the inteface.
:param name: name of the port
:param stype: the port signal type
:param intf: the interface to search for matching signal
:return:
@todo: this function is hackery, not much thought was p... | 47,584 |
def generate_salatch(laygen, objectname_pfix, placement_grid,
routing_grid_m1m2, routing_grid_m1m2_thick, routing_grid_m2m3, routing_grid_m2m3_thick, routing_grid_m3m4,
devname_ptap_boundary, devname_ptap_body,
devname_nmos_boundary, devname_nmos_body, devname_nmos_dmy,
devname_pmos_boundary, devname_p... | 47,585 |
def r2_score(y, y_predicted):
"""Calculate the R2 score.
Parameters
----------
y : array-like of shape = number_of_outputs
Represent the target values.
y_predicted : array-like of shape = number_of_outputs
Target values predicted by the model.
Returns
-------
... | 47,586 |
def correct_ancils(lfrac, mask_ancil, frac_ancil, outdir):
"""
Create new UM ancil files by replacing the land fraction and mask fields in
``mask_ancil`` and ``frac_ancil`` with the values from ``lfrac``
Creates new files ``qrparm.mask`` and ``qrparm.landfrac`` in ``outdir``
Args:
lfrac (x... | 47,587 |
def vcg_solve(goal):
"""Compute the verification conditions for a hoare triple, then
solves the verification conditions using SMT.
"""
assert goal.is_comb("Valid", 3), "vcg_solve"
P, c, Q = goal.args
T = Q.get_type().domain_type()
pt = vcg_norm(T, goal)
vc_pt = [ProofTerm("z3", vc,... | 47,588 |
def ism_extinction(av_mag: float,
rv_red: float,
wavelengths: np.ndarray) -> np.ndarray:
"""
Function for calculating the optical and IR extinction with the empirical relation from
Cardelli et al. (1989).
Parameters
----------
av_mag : float
Extinct... | 47,589 |
def rangify(values):
"""
Given a list of integers, returns a list of tuples of ranges (interger pairs).
:param values:
:return:
"""
previous = None
start = None
ranges = []
for r in values:
if previous is None:
previous = r
start = r
elif r ==... | 47,590 |
def load_balancers_with_instance(ec2_id):
"""
@param ec2_id: ec2 instance id
@return: list of elb names with the ec2 instance attached
"""
elbs = []
client = boto3.client('elb')
paginator = client.get_paginator('describe_load_balancers')
for resp in paginator.paginate():
for elb ... | 47,591 |
def sino_processing(input_folder, output_folder, sample_name, value_scale, alpha, row_range):
"""Compute scattering for a certain range of rows for all slices of a given apple
Arguments:
input_folder -- path to the projections saved in tif files.
output_folder -- path to the output: photon count di... | 47,592 |
def main():
"""Entry point of the *becmd* program."""
parser = get_argparser()
opts = parse_args(parser, sys.argv[1:], partial=True)
try:
cfg = read_config(opts.get('config'), update={PROG_NAME: opts})
except becmd.errors.ValidationError:
sys.exit(1)
logging_from_config(cfg, upd... | 47,593 |
def parse_json_frequency_high(df, column, key):
"""
Takes a JETS dataframe and column containing JSON strings
and finds the highest 'Mode' or 'Config' frequency.
Excludes intermediate frequencies
Parameters
----------
df : pandas dataframe
JETS dataframe
column : str
... | 47,594 |
def adapter_checker(read, args):
"""
Retrieves the end sequences and sorts adapter information for each end.
"""
cigar = read.cigartuples
seq = read.query_sequence
leftend, check_in_softl, left_match = get_left_end(seq, cigar, args)
rightend, check_in_softr, right_match = get_right_end(seq, ... | 47,595 |
def copy_setup(profiles, host, remote_path, settings=None):
"""
Copy scripts needed for configuration onto the remote machine.
"""
if settings is None:
settings = {}
pythondir = os.path.dirname(os.path.dirname(__file__))
basedir = os.path.dirname(os.path.dirname(os.path.dirname(pythondir... | 47,596 |
def create_pane(widgets, horizontal, parent_widget=None, compact=False,
compact_spacing=2):
"""Create a widget containing an aligned set of widgets.
Args:
widgets (list of `QWidget`).
horizontal (bool).
align (str): One of:
- 'left', 'right' (horizontal);
... | 47,597 |
def filterbyasn(ips: List[Dict], max_per_asn: Dict, max_per_net: int) -> List[Dict]:
""" Prunes `ips` by
(a) trimming ips to have at most `max_per_net` ips from each net (e.g. ipv4, ipv6); and
(b) trimming ips to have at most `max_per_asn` ips from each asn in each net.
"""
# Sift out ips by type
... | 47,598 |
def image_TOKEN_search_by_word_query_TOKEN(query_snd_ix, multi_distances,
snd_fnames, img_fnames,
id2pic):
"""map a word token query into the embedding space and find images in the same space
return rank of first neighbor whos... | 47,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.