content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def fake_obj(hey: FakeClass):
"""
Fake object
:param hey: it's a class
:return:
"""
pass | 64,300 |
def get_resize(image, scale):
""" resizes image according to scale"""
if isinstance(scale, int):
if image.shape[0] % scale != 0 or image.shape[1] % scale != 0:
return 1, None
if image.shape[0] < scale or image.shape[1] < scale:
return 2, None
arrays = []
... | 64,301 |
def parse_saml_response_to_roles(saml_response: str) -> List[str]:
"""
Parses a SAML response to a list of role,saml-provider pairs
:param saml_response: the SAML response to parse
:return: a list of role,saml-provider pairs
"""
roles = []
root = ElementTree.fromstring(base64.b64decode(saml... | 64,302 |
def rotate(p, angle, center=(0, 0)):
"""
Rotates given point around specified center.
Args:
p: (float, float)
Point to rotate.
angle: float
Angle in radians.
center: (float, float)
Center of rotation.
"""
dx = p[... | 64,303 |
def export_contourf(
filename, contours, fieldname="level", epsg=None, prj=None, **kwargs
):
"""
Write matplotlib filled contours to shapefile. This utility requires
that shapely is installed.
Parameters
----------
filename : str
name of output shapefile (e.g. myshp.shp)
contou... | 64,304 |
def pendulum(integrator_type, num_samples, num_parts, T_max, dt, srate, noise_std, seed):
"""simple pendulum"""
def hamiltonian_fn(coords):
q, p = np.split(coords, 2)
H = 9 * (1 - cos(q)) + p ** 2 / 2
return H
def dynamics_fn(coords):
dcoords = autograd.grad(hamiltonian_fn)... | 64,305 |
def get_Data(image_path, path_dest, img_name, count):
"""
copy: True if image gets copied
False if image only gets parsed
image: currently chosen image
image_path: path to the currently chosen image
open image and read exif_data if existent if not use mtime
"""
try: ... | 64,306 |
def historical_volatility(maven_asset_code: str, price_type: str,
currency: str, period_start: list,
period_end: list,
lambda_factor: Union[None, float] = None
) -> dict:
"""
:param lambda_factor:
:param ... | 64,307 |
def _merge_clips(clips, dryrun):
"""
ffmpeg plays nicely when the files that are to be concatenated
are written to a text file, and the file is passed to ffmpeg
the new file is written to temp
:param [] clips: list of movie clips to be concatenated
:param bool dryrun:
:returns: {
'... | 64,308 |
def init_app_context(
update: telegram_interface.Update = None
):
"""
Some app methods (decorators, for example) depends
on specific application context (`g.telegram_user`, for example).
This function will create needed application context.
Call this function again if you need to re-init app co... | 64,309 |
async def DatagramReceiver(manager: ManagerAPI,
socket: SocketType,
incoming_datagram_send_channel: SendChannel[IncomingDatagram],
) -> None:
"""Read datagrams from a socket and send them to a channel."""
logger = logging.getLogger... | 64,310 |
def cos(x):
"""Elementwise cosine """
return T.cos(x) | 64,311 |
def flake8(session):
"""Lint code with Flake8."""
session.install("flake8")
session.run("flake8", *SOURCES) | 64,312 |
def write_mesh_users_h(h_users, f):
"""Write user inforation to a header file
users: list of tuples of (username, pin)
f: open file object for the header file to be written
"""
# write users to header file
f.write("""
/*
* This is an automatically generated file by provisionSystem.py
*
*
*/
#i... | 64,313 |
def authenticate(url="ws://localhost:8776", session_key=None, print_callback=print, **kwargs):
"""
Connect to a telekinesis server and call the authenticate method at the entrypoint
url: string - url of the telekinesis Broker. example: "wss://telekinesis.cloud"
session_key: string ... | 64,314 |
def get_inconsistent_resources(context):
"""Get a list of inconsistent resources.
:returns: A list of objects which the revision number from the
ovn_revision_number and standardattributes tables differs.
"""
sort_order = sa.case(value=ovn_models.OVNRevisionNumbers.resource_type,
... | 64,315 |
def ustr(obj):
""" Python 2 and 3 utility method that converts an obj to unicode in python 2 and to a str object in python 3"""
if sys.version_info[0] == 2:
# If we are getting a string, then do an explicit decode
# else, just call the unicode method of the object
if type(obj) in [str, b... | 64,316 |
def ChangePasswordView(request):
"""
Set new password for the user.
"""
post_data = json.loads(request.body)
username = post_data['username']
token = post_data['token']
password = post_data['password']
try:
user = User.objects.get(username=username)
if default_token_gene... | 64,317 |
def create_box_list(
boxes: torch.Tensor,
scores: torch.Tensor,
labels: torch.Tensor,
class_labels: List[str],
label_prefix: str = "",
) -> Iterable[Dict[str, Any]]:
"""Create list with box information for wandb."""
for box, score, label in zip(boxes, scores, labels):
x1, y1, x2, y2 ... | 64,318 |
def pure_water_density_tanaka(t, a5=0.999974950):
"""Equation according Tanaka, M., et. al; Recommended table for the density of water between 0 C and 40 C based on
recent experimental reports, Metrologia, 2001, 38, 301-309
:param t: water temperature (°C)
:param a5: density of SMOW water under one atm... | 64,319 |
def collect_multi_single(ilist, fmt, fmt_dc):
"""Collect camera arrays from multiple files.
Parameters
----------
ilist: sequence
Sequence which elements are formatted into `fmt` and `fmt_dc` to
get paths to measurement files.
fmt : str
Format string for bright frame.
fm... | 64,320 |
def create_credentials(view_password, account, login_name, pass_word):
"""
Function to create a new credential
"""
new_credential = Credential(view_password, account, login_name, pass_word)
return new_credential | 64,321 |
def latest_checkpoint(root_output_dir):
"""Get the latest checkpoint dirname, which is in the format of `ckpt_1`.
Args:
root_output_dir: The directory where all checkpoints stored.
Returns:
Dirname of the lastest checkpoint.
"""
checkpoints = tf.io.gfile.glob(os.path.join(root_output_dir, 'ckpt_*'))... | 64,322 |
def menu(request):
"""餐廳的菜單.
有菜名、價格、說明以及會不會辣。
"""
food1 = {
'name': '番茄炒蛋',
'price': 60,
'comment': '好吃',
'is_spicy': False
}
food2 = {
'name': '番茄炒蛋',
'price': 60,
'comment': '好吃',
'is_spicy': False
}
foods = [food1, food2... | 64,323 |
def load_trained_model(fname: str):
"""
Loads a saved ModelData object from file.
Args:
fname (str): Complete path to the file.
Returns: A ModelData object containing the model, list of titles, list of
authors, list of genres, list of summaries, training corpus, and test
corpus... | 64,324 |
def weather_old(city):
""" 百度天气
"""
try:
city_name = urllib.parse.quote(city.encode('utf-8'))
url_str = f'http://api.map.baidu.com/telematics/v3/weather?location={city_name}&ak={KEY1}&output=json'
response = requests.get(url_str)
data = response.content.decode('utf-8')
... | 64,325 |
def lock_prefix():
"""
Will prefix locks with a Unicode Character 'KEY' (U+1F511)
if the user's stdout supports it
"""
if is_unicode_supported():
return u'\U0001F511 ' # Extra spaces are intentional
return '' | 64,326 |
def identity_belief(reference: dict) -> dict:
"""
Returns an identity function for the beliefs.
This is so that we can debug more easily. Therefore, does almost nothing
but replace values with 1.0 in a data structure.
Parameters
----------
reference : dict
A single reference metada... | 64,327 |
def draw_square(image: Image, center: Int2, radius: int, color: Int4 = (255, 64, 64, 255)):
"""Draw a square at the given point. Used for debugging."""
for i in range(radius * 2):
for j in range(radius * 2):
x: int = center[X] + i - radius
y: int = center[Y] + j - radius
... | 64,328 |
def map2arr(iterator, return_np_array=True, check_nones=True):
"""Function to cast result from `map` to a tuple of stacked results
By default, this returns numpy arrays. Automatically checks if the map object is a tuple, and if not, just one object is returned (instead of a tuple). Be warned, this does not wor... | 64,329 |
def resolve(item):
"""
Get a non-ambiguous string for each item. If it's uncertain, pick a word,
even if it's just THE. This lets us at least try a sort order, although
uncertain answers may be out of place.
"""
if isinstance(item, RegexClue):
return item.resolve()
else:
retu... | 64,330 |
def get_twitter():
""" Twitterインスタンスを取得する """
tw_cfg = yaml.load(open(".tokens"), Loader=yaml.SafeLoader)
oauth = OAuth(
tw_cfg['ACCESS_TOKEN'], tw_cfg['ACCESS_TOKEN_SECRET'],
tw_cfg['CONSUMER_KEY'], tw_cfg['CONSUMER_SECRET'])
tw = Twitter(auth=oauth)
return tw | 64,331 |
def test_panelist_retrieve_all_ids():
"""Testing for :py:meth:`wwdtm.panelist.Panelist.retrieve_all_ids`
"""
panelist = Panelist(connect_dict=get_connect_dict())
ids = panelist.retrieve_all_ids()
assert ids, "No panelist IDs could be retrieved" | 64,332 |
def posix(monkeypatch, no_win, not_android):
"""Set path separator to colon."""
monkeypatch.setattr('pypyr.platform.os.pathsep', ':') | 64,333 |
def elina_texpr0_array_is_interval_polyfrac(texpr_array, size):
"""
Test if an ElinaTexpr0Array is polynomial fraction with possibly interval coefficients, but no rounding.
Parameters
----------
texpr_array : ElinaTexpr0Array
ElinaTexpr0Array that needs to be tested.
size : c_size_t
... | 64,334 |
def create_block():
""" Creates an apple to be eaten """
global BLOCK
posx = SEG_SIZE * random.randint(1, (WIDTH-SEG_SIZE) / SEG_SIZE)
posy = SEG_SIZE * random.randint(1, (HEIGHT-SEG_SIZE) / SEG_SIZE)
BLOCK = c.create_oval(posx, posy,
posx+SEG_SIZE, posy+SEG_SIZE,
... | 64,335 |
def get_client_config(app_config, data_adaptor):
"""
Return the configuration as required by the /config REST route
"""
server_config = app_config.server_config
dataset_config = data_adaptor.dataset_config
annotation = dataset_config.user_annotations
auth = server_config.auth
# FIXME T... | 64,336 |
def requirements(filename, use_python='python', **kwargs):
"""
Require Python packages from a pip `requirements file`_.
.. _requirements file: http://www.pip-installer.org/en/latest/requirements.html
"""
pip(DEFAULT_PIP_VERSION, use_python=use_python)
install_requirements(filename, use_python=u... | 64,337 |
def update(
id_or_url: str,
browser: Optional[str],
limit: Optional[int],
threads: Optional[int],
):
"""
update the novel metadata and downloads any new chapters if not specified otherwise
if url is provided and novel does not exist, a new novel entry will be created.
however if id is p... | 64,338 |
def update_data(d):
"""Performs final steps upon the datastore, including application of overrides"""
d.finalize(parent = True) | 64,339 |
def if_mkl_v1(if_true, if_false = []):
"""Returns `if_true` if MKL-DNN v1.x is used.
Shorthand for select()'ing on whether we're building with
MKL-DNN v1.x open source library only, without depending on MKL binary form.
Returns a select statement which evaluates to if_true if we're building
with M... | 64,340 |
def _pulse_color(color, speed, low, high):
""" Pulse each LED of the defined color at the given speed """
color_setter = getattr(piglow, color)
pulse_range = range(low, high)
wait_for = 1/speed
for c in pulse_range:
color_setter(c)
piglow.show()
sleep(wait_for)
for c in... | 64,341 |
def generate_hostfile(map_, file):
"""
generate hostfile base on map_
"""
for node in map_:
print('node-{}.simgrid.org'.format(node), file=file)
file.flush()
return file.name | 64,342 |
def copy_files(name,
srcs = [],
outs = []):
"""
We have dependencies on data files outside of our project, and the filegroups
provided by that project include extra stuff we don't want. This function
will extract the provided filenames from the provided filegroups and copy them
i... | 64,343 |
def cli(ctx, config_file=None, **kwargs):
"""A CLI for the ramses_rf library."""
if kwargs[DEBUG_MODE]:
import debugpy
debugpy.listen(address=(DEBUG_ADDR, DEBUG_PORT))
_LOGGER.info(f"Debugging is enabled, listening on: {DEBUG_ADDR}:{DEBUG_PORT}.")
_LOGGER.info(" - execution pau... | 64,344 |
def home(request):
"""
Controller for the app home page.
POST requests can be receieved from the CUAHSI HydroClient when exporting data to
HydroShare. These requests include a form describing the reference data exported
from the HydroClient workspace, but should not include any URL query parameter... | 64,345 |
def _delete_server_list(zone):
"""
Delete .bees file
:param zone:
:return:
"""
try:
os.remove(_get_new_state_file_name(zone))
except IOError:
pass | 64,346 |
def run(path='', code=None, rootdir=CURDIR, options=None):
"""Run code checkers with given params.
:param path: (str) A file's path.
:param code: (str) A code source
:return errors: list of dictionaries with error's information
"""
errors = []
fileconfig = dict()
linters = LINTERS
... | 64,347 |
def test_parameter__repr__(parameter: Parameter) -> None:
"""Test parameter serilizable representation."""
output = """Parameter(
name = auto_summer,
value = 1,
min_value = 0,
max_value = 1,
extra = None
)""".strip()
assert repr(parameter) == output | 64,348 |
def nf_dir() -> Path:
"""Root directory for `jax3d/nerfstatic/`."""
return j3d_dir() / 'nerfstatic' | 64,349 |
def publish(request):
"""
Publish page: Simply render the publish form if the request method is GET, or actually publishes (create or modify)
a blog if the request method if POST.
Note that creating and modifying requires different permissions.
"""
# The permission authenticating part is the sam... | 64,350 |
def _populate():
"""Returns a list of sql commands to setup the DB for the fetch tests."""
populate = [
# NOTE NO GOOD using format to bind data
"insert into {} values ('{}')".format(
TABLE1, s)
for s in SAMPLES
]
return populate | 64,351 |
def test_output():
"""
test
"""
file_name = pattern03.__file__
module = ast_util.create_ast(file_name)
pkg, mdn = files.get_package_moduel(file_name)
t_file = files.get_test_file_name(pkg, mdn)
ttt1 = run.make_test_code(module, pkg, mdn, True)
ttt2 = files.read_file(t_file)
as... | 64,352 |
def x2(samples):
"""Get F = <x_j^2>
Args:
samples (array_like): [N_samples, N_x] array of samples
Returns:
feature (array_like): [N_samples, 1] feature
grad_feature (array_like): [N_samples, 1, N_x] gradient of the feature
"""
Nx = samples.shape[-1]
Feature = np.sum(sam... | 64,353 |
def crop_expert(fn, outpath = None, expertpath=None, loader=None, preview=None,
form = None, startfrom = None, name = None, modify=False, reset=False,
review = False, ask=False, help = False, ext = None):
"""
Crop input image and save ROIs
:param fn: file name
:param out... | 64,354 |
def auth_superuser(api_instance, request):
"""
API method middleware to ensure that the current user is a
super user
"""
if not api_instance.current_user:
raise UnauthorizedException
if not api_instance.current_user.is_superuser:
raise ForbiddenException | 64,355 |
def get_birthday_of_contact_day(p_birthday_of_contact_month):
"""Saves the Day of Birth of the Contact. Error Checking is Performed to Determine Validity"""
birthday_of_contact_day = input("Birthday Day | Enter Your Contact's Birthday Day as DD, ex: Type 01 For the First or 15 For the Fifteenth, Then Press Ent... | 64,356 |
def svds(A, k=6, ncv=None, tol=0, which='LM', v0=None,
maxiter=None, return_singular_vectors=True):
"""Compute the largest k singular values/vectors for a sparse matrix.
Parameters
----------
A : {sparse matrix, LinearOperator}
Array to compute the SVD on, of shape (M, N)
k : int, ... | 64,357 |
def sync(
awaitable: typing.Awaitable,
event_loop: typing.Optional[asyncio.events.AbstractEventLoop] = None,
):
"""
Run an awaitable synchronously. Good for calling asyncio code from sync Python.
The usage is as follows:
.. highlight:: python
.. code-block:: python
from ori.asynci... | 64,358 |
def validate_json_envelope(json_response: JSONEnvelope) -> None:
"""
It is not necessary for a fee quote to include a signature, but if there is one we check
it. What does it mean if there isn't one? No idea, but at this time there is no expectation
there will be one.
Raises a `ValueError` to indic... | 64,359 |
def get_plane_infos(p1: np.ndarray, p2:np.ndarray, p3:np.ndarray):
"""Returns the informations of a plane from a 3d region points
Args:
pos (np.ndarray): [description]
ori (np.ndarray): [description]
Returns:
tuple: p, e1, e2, n where p is the reference position of the plane, e1,e2... | 64,360 |
def check_float(a, b, precision=1e-4):
"""
check float data
Args:
a(list): input_data1
b(list): input_data2
precision(float): precision for checking diff for a and b
Returns:
bool
"""
def __adjust_data(num):
if num == 0.0:
return 0.0
r... | 64,361 |
def test_semantic_segmentation_labelling_concise():
"""Test `semantic_segmentation_labelling` function in `generator` module by
considering a concise labelling, *i.e.* the labels correspond to array
values
* as a preliminary verification, check if passing string labels raises an
AttributeError excep... | 64,362 |
def icosahedron_nodes_calculator(order):
"""Calculate the number of nodes
corresponding to the order of an icosahedron graph
Args:
order (int): order of an icosahedron graph
Returns:
int: number of nodes in icosahedron sampling for that order
"""
nodes = 10 * (4 ** order) + 2
... | 64,363 |
def evaluateW(trials_1, trials_2):
"""
Evaluate the spatial filter of the CSP algorithm
Parameters
----------
trials_1 : numpy 3D-matrix
Trials matrix of class 1. The dimensions must be trials x channel x samples
trials_2 : numpy 3D-matrix
Trials matrix of class 2. The dimension... | 64,364 |
def list_publicIP(apiclient, **kwargs):
"""List all Public IPs matching criteria"""
cmd = listPublicIpAddresses.listPublicIpAddressesCmd()
[setattr(cmd, k, v) for k, v in list(kwargs.items())]
return(apiclient.listPublicIpAddresses(cmd)) | 64,365 |
def train():
"""Train a en->fr translation model using WMT data."""
# Prepare WMT data.
print("Preparing WMT data in %s" % FLAGS.data_dir)
en_train, fr_train, en_dev, fr_dev, _, _ = data_utils.prepare_wmt_data(
FLAGS.data_dir, FLAGS.en_vocab_size, FLAGS.fr_vocab_size)
with tf.Session() as sess:
# C... | 64,366 |
def turnOff(hermes, intent_message):
""" Turns off in the indicated location.
:param hermes: The hermes object.
:param intent_message: The intent message with slots.
"""
house_room = getRoom(intent_message)
hermes.skill.light_off(house_room)
current_session_id = intent_message.session_id
... | 64,367 |
def parse_mhdr(mhdr):
"""
MHDR parser
mhdr: 1 byte.
7 6 5 | 4 3 2 | 1 0
MType | RFU | Major
"""
# MHDR parser.
def get_mtype_cmd(mtype):
return {
"000": "Join Request",
"001": "Join Accept",
"010": "Unconfirmed Data Up",
... | 64,368 |
def per_device_batch_size(batch_size, num_gpus):
"""For multi-gpu, batch-size must be a multiple of the number of GPUs.
Note that this should eventually be handled by DistributionStrategies
directly. Multi-GPU support is currently experimental, however,
so doing the work here until that feature is in place.
... | 64,369 |
def sub_top_level_function1(
hoge: int,
fuga: str,
) -> None:
""" Top level function.
signature is multilined.
"""
return | 64,370 |
def log_loss(y_true, y_prob):
"""Compute Logistic loss for classification.
Parameters
----------
y_true : array-like or label indicator matrix
Ground truth (correct) labels.
y_pred : array-like of float, shape = (n_samples, n_classes)
Predicted probabilities, as returned by a class... | 64,371 |
async def test_calling_service_template(hass):
"""Test the calling of a service."""
context = Context()
@callback
def record_call(service):
"""Add recorded event to set."""
calls.append(service)
hass.services.async_register("test", "script", record_call)
schema = cv.SCRIPT_SCH... | 64,372 |
def load_board_state(file_name):
"""
o = food / point thing
X = wall
P = pac man
S = ghost spawn
' ' = empty space
"""
board = []
with open(file_name, 'r') as file:
for line in file:
line = line.strip()
board.append(list(line))
return board | 64,373 |
def dist_version(name):
"""
Returns the version of the installed distribution package,
otherwise returns None.
"""
return metadata.version(name) if name else None | 64,374 |
def validate_profile(context, param, value):
"""
Validates existance of profile.
Returns the profile name if it exists; otherwise throws BadParameter
"""
if value in context.obj.configuration.profiles():
return value
else:
raise click.BadParameter("\"%s\" was not found" % value) | 64,375 |
def iterated_smoother_routine(initial_state: MVNormalParameters,
observations: jnp.ndarray,
transition_function: Callable[[jnp.ndarray, jnp.ndarray], jnp.ndarray],
transition_covariance: jnp.ndarray,
... | 64,376 |
def configure(
log_path: Union[Path, str, None] = None,
log_file_name: Optional[str] = None,
file_log_level: Optional[str] = "DEBUG",
std_out_log_level: Optional[str] = "INFO",
error_only_modules: Optional[
Union[ModuleType, Sequence[ModuleType], str, Sequence[str]]
] = None,
modules... | 64,377 |
def HotellingT2Test(X, robust=True, plot=True):
"""Hotellig T^2 test for abnormallity.
Testing whether the observation is abnormal using Hotellig T^2 test
at confidence level a = 0.01
Parameters
----------
X : array-like
robust : bool, optional
plot : bool, optional
Returns
--... | 64,378 |
def _process_aesthetic_update(time_delta: float):
"""
Update aesthetics, such as entity animations and draw positions.
"""
# move entities screen position towards target
for entity, (
_,
aesthetic,
) in query.active_and_aesthetic:
assert isinstance(aesthetic, Aesthetic)
... | 64,379 |
def export_questions(path='/tmp'):
"""
A script for exporting Ask CFPB Answer content
to a CSV that can be opened easily in Excel.
Run from within cfgov-refresh with:
`python cfgov/manage.py runscript export_ask_data`
CEE staffers use a version of Excel that can't easily import UTF-8
non-a... | 64,380 |
def delete_statement_forwarder(forwarder_id):
"""
Delete a statement forwarder in Learning Locker.
:param forwarder_id: The id of the statement forwarder.
:type forwarder_id: str
"""
connect(f'api/v2/statementforwarding/{forwarder_id}', 204, 'delete') | 64,381 |
def bulk_insert(session, mapper, mappings):
"""Perform a bulk insert into table/statement represented by `mapper`
while utilizing a special syntax that replaces the tradtional
``executemany()`` DBAPI call with a multi-row VALUES clause for a
single INSERT statement.
See :meth:`bulk_insert_many` for... | 64,382 |
def formatPath(a):
"""Format SVG path data from an array"""
return "".join([cmd + " ".join([str(p) for p in params]) for cmd, params in a]) | 64,383 |
def get_subsequent_mask(seq):
"""For masking out the subsequent info."""
len_s = seq.size(1)
subsequent_mask = 1 - torch.triu(
torch.ones((len_s, len_s), device=seq.device), diagonal=1)
subsequent_mask = subsequent_mask.unsqueeze(0).bool()
return subsequent_mask | 64,384 |
def merge_configs(*configs):
"""
Merges dictionaries of dictionaries, by combining top-level dictionaries with last value taking
precedence.
For example:
>>> merge_configs({'a': {'b': 1, 'c': 2}}, {'a': {'b': 2, 'd': 3}})
{'a': {'b': 2, 'c': 2, 'd': 3}}
"""
merged_config = {}
for co... | 64,385 |
def _is_file_uri(uri):
"""Returns True if the passed-in URI is a file:// URI."""
return _FILE_URI_REGEX.match(uri) | 64,386 |
def _dup_right_decompose(f, s, K):
"""Helper function for :func:`_dup_decompose`."""
n = len(f) - 1
lc = dup_LC(f, K)
f = dup_to_raw_dict(f)
g = { s: K.one }
r = n // s
for i in range(1, s):
coeff = K.zero
for j in range(0, i):
if not n + j - i in f:
... | 64,387 |
def DefineNamedRange(sheet, x0, y0, width, height, name):
"""Defines a new (or replaces an existing) named range on a sheet,
using zero-based absolute coordinates
"""
desktop = XSCRIPTCONTEXT.getDesktop()
model = desktop.getCurrentComponent()
# FIXME: Is there some Python-callable API to turn a ... | 64,388 |
def find_in_connection_table(addr):
"""Find a peer address *addr* in the connection table, and return the
socket address."""
# Addresses in /proc/net/tcp are network endian printed as machine endian,
# meaning they get byte swapped on little endian. Ports are machine endian
# printed as machine endi... | 64,389 |
def get_xyz_from_radar(radar):
"""Input radar object, return z from radar (km, 2D)"""
azimuth_1D = radar.azimuth['data']
elevation_1D = radar.elevation['data']
srange_1D = radar.range['data']
sr_2d, az_2d = np.meshgrid(srange_1D, azimuth_1D)
el_2d = np.meshgrid(srange_1D, elevation_1D)[1]
xx... | 64,390 |
def expected_unique(probabilities, sample_size):
"""Get expected number of unique samples.
This computes the expected number of unique samples for a multinomial
distribution from which we sample a fixed number of times.
"""
vals = 1 - (1 - probabilities) ** sample_size
expectation = torch.sum(... | 64,391 |
def addObjMinSumYi(m):
"""Add objective for minimizing building blocks used.
This objective is mainly useful for debugging models.
Fix some (supposed) feasible solution, use this objective,
and see which building blocks were realized.
Args:
m (ConcreteModel): Pyomo model to add objective t... | 64,392 |
def download(*entries):
"""
Download a local cache for Tiled so access is fast and can work offline.
Parameters
----------
*entries : Node(s) or structure client(s)
Examples
--------
Connect a tree and download it in its entirety.
>>> from tiled.client import from_uri
>>> fro... | 64,393 |
def label_tsne(tsne_results, sample_names, tool_label):
"""
Label tSNE results.
Parameters
----------
tsne_results : np.array
Output from run_tsne.
sample_names : list
List of sample names.
tool_label : str
The tool name to use for adding labels.
Returns
---... | 64,394 |
def ensure_activity_is_valid(activity: Activity):
"""
Goes through the activity and checks certain of its properties and raise
:exc:`InvalidActivity` whenever one does not respect the expectations.
An activity must at least take the following key:
* `"type"` the kind of activity, one of `"python"`... | 64,395 |
def get_client():
"""
Returns an authenticated CustomerInsights client.
"""
base_url = GLOBAL_CONFIG.get("endpoint", "base_url", None)
if base_url:
logger.info('Using base url: %s', base_url)
return CustomerInsights(base_url) | 64,396 |
def readNtrim(fastq, threshold, consecutive, verbose, qualities, FASTA, LOG):
"""
Parse a solexa-illumina export file
SOLEXA3_77_30V9CAAXX 4 1 1068 522 1 GGACAGCTGACAGCTGTTAAGAAGGACCCTATGTTAAAGGAAATGGATAC YYYYYYYYYYYJYY
YYYYRYYYYYYYYYYYTTTTTOOOMOOOMMOOOOOG chr13 363117... | 64,397 |
def image_warp(image, flow, interp_method, name='dense_image_warp'):
"""Image warping using per-pixel flow vectors.
Apply a non-linear warp to the image, where the warp is specified by a dense
flow field of offset vectors that define the correspondences of pixel values
in the output image back to locations in t... | 64,398 |
def breadcrumb_scope(parser, token):
"""
Easily allow the breadcrumb to be generated in the admin change templates.
"""
return BreadcrumbScope.parse(parser, token) | 64,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.