content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import pickle
def load_ontology(ontology_file):
""" loads an ontology pickle file """
ontology = pickle.load(open(ontology_file, 'rb'))
return ontology | 8e3e9c9017bee76795a98435a68d3f01fa0d40e9 | 56,860 |
def plot_target_belief(g, folder_name, my_layout, b_target: dict, t: int):
"""Plot target belief"""
V, n = ext.get_set_vertices(g)
rgba_color = (255, 0, 0, 1)
g.vs["color"] = "white"
for v in V:
v_idx = ext.get_python_idx(v)
b = b_target[v, t]
c = b/1
if 0.001 < c <... | 6a00a74e600241929d5cb9993ec1a07867ddf41a | 56,861 |
def ToPropertyPb(name, values):
"""Creates type-specific entity_pb.PropertyValues.
Determines the type and meaning of the PropertyValue based on the Python
type of the input value(s).
NOTE: This function does not validate anything!
Args:
name: string or unicode; the property name
values: The values... | f12d69b39607882ed8fe20d2c4ad9b14696a15c2 | 56,862 |
def proc_nslkdd(df_tr, df_te):
"""Load the NSL-KDD dataset from the data/ folder. Note you need to download the data
and add it to the folder.
:return Four Numpy arrays with X_tr, y_tr, X_te and y_te
"""
df_tr = df_tr.sample(frac=1).reset_index(drop=True).rename(columns={"class": "target"})
df... | 76463f6621c7beb09966793ef4954cf711be290d | 56,863 |
def recode_factor(
_x,
*args,
_default=None,
_missing=None,
_ordered=False,
**kwargs,
):
"""Recode a factor
see recode().
"""
values = _args_to_recodings(*args, **kwargs)
recoded = recode.dispatched.dispatch(Series)(
_x,
values,
_default=_default,
... | 820de4a8c29f3efd121d907d63c9715c2ca06ae4 | 56,864 |
def randomly_sample_window_from_signal(original_signal, window_len, random_seed_val=None):
"""
data_preprocessing_utils.randomly_sample_window_from_signal: returns the data sample referenced by index in self.curr_subset_sample_index_map
- Inputs:
* original_signal (numpy ndarray): an array o... | bc887309ad1955a67fa245eb20db45d5c43ccb1e | 56,865 |
def num_atom_features():
"""
This function returns the number of atomic features that are available by this module.
Returns
-------
n_features : int
length of atomic feature vector.
"""
m = Chem.MolFromSmiles('CC')
alist = m.GetAtoms()
a = alist[0]
return len(atom_featur... | 92a7b6cc16505a49b03033c560815a3f49e4f089 | 56,866 |
from oggm.core.massbalance import LinearMassBalance, ConstantMassBalance
from oggm.core.centerlines import line_inflows
def gridded_mb_attributes(gdir):
"""Adds mass-balance related attributes to the gridded data file.
This could be useful for distributed ice thickness models.
The raster data are added t... | 60d690036450376f8f9209754225028663f0faff | 56,867 |
from typing import Iterator
def get_variable_slices(
source_code: str,
lang: Lang,
slice_predicate: SlicePredicate = None,
include_noneffective: bool = True) -> Iterator[ProgramSlice]:
"""
For each function and variable in a specified source code generate list of Program Slices... | c74cb5c586bdd208f904c4209b80018524440a6a | 56,868 |
def NECout():
"""Test read of NEC .out file."""
basefile = 'Lofar-dipole-FREE.out'
fileloc = NECdir+basefile
atvfd = NECread.readNECout_tvecfuns(fileloc)
antFF = RadFarField(atvfd)
return antFF | 2049fe87c25c961fd6f69431fc76de4d13f150cc | 56,869 |
def exsafeSlot(*slargs, **slkwargs):
"""Wrapper around ``PyQt5.QtCore.pyqtSlot`` which intercepts exceptions and stops the execution in a controlled manner"""
def wrapper(func):
return QtCore.pyqtSlot(*slargs,**slkwargs)(exsafe(func))
return wrapper | 0353cffc87b94b6387af9c89103ecd6c1bb32c2f | 56,871 |
def goto(avIdShort):
""" Teleport to the avId specified. """
avId = 100000000+avIdShort # To get target doId.
toon = simbase.air.doId2do.get(avId)
if not toon:
return "Unable to teleport to target, they are not currently on this district."
spellbook.getInvoker().magicWordTeleportRequests.app... | b064727d8cfbbc20102e2e8fd9b1e07ec24141b0 | 56,872 |
def _get_mongo_expression_for_type_filter(requested_file_types):
"""
Construct and return pymongo expression dict for the named content type categories.
The named content categories are the keys of the FILES_AND_UPLOAD_TYPE_FILTERS setting that are not 'OTHER':
'Images', 'Documents', 'Audio', and 'Code... | 094732cdc9f204ab110c14a87687064773d7d089 | 56,873 |
def segs2nodes(segs, logFileName, error = False):
"""inputs a segment dataframe, brings in references that were calculated, and calculates x,y, and z values for base and top"""
""" If no rows need calculating the code skips the calculation process and outputs the input dataframe, this is to be efficient when wh... | ed6d0ff211bf94e39b8508c67671711f35956e73 | 56,875 |
def _run_cmd(cmd):
"""Run a shell command `cmd` and return its output."""
return check_output(cmd, shell=True).decode("utf-8") | b936b294ac14e163dca60a9d925f6714b7e0b12e | 56,876 |
import random
def new_viable_indiv(payload):
"""
Return a new indiv, create from given individuals
crossing in given configuration, eventually mutated.
Indiv is viable.
Payload argument must be a 2tuple that contain individuals and configuration.
(multithreading compatibility)
"""
in... | 3c6e324d1574143f1c69016891a1e981e0ec3281 | 56,877 |
def get_filename(name):
"""Return absolute path to a picture located in the current package.
:param name: name of an image located in language folders
:type name: str
:return: absolute image path
:rtype: str
"""
return osp.join(osp.dirname(osp.abspath(__file__)), 'assets', name) | 3529aaa089257ab5e394081456a57931bcbc49b2 | 56,879 |
def _setup_browser(dl_dir, mime_type):
"""Setup Firefox headless browser.
Parameters
----------
dl_dir : str
Path to the download dir.
mime_type : str
MIME-type that can be automatically downloaded.
Returns
-------
browser : selenium.webdriver.firefox.webdriver.WebDrive... | a759a8bf05217f93caf587017b39ae2ea7e47725 | 56,880 |
import re
def get_csrf_token(res):
"""Extract the CSRF token from a response."""
for header in res.headers:
m = re.search('token=(.+?);', header[1])
if m:
return m.group(1)
raise RuntimeError('Could not find CSRF token in response headers: ' + str(res.headers)) | 2c2670a6909ed87d60b44a5cf1cbaeffdc4fc653 | 56,881 |
def interpolate_evaluation_dose_at_distance(
evaluation_interpolation,
axes_reference_to_be_checked,
coordinates_at_distance_shell,
):
"""Determine the evaluation dose for the points a given distance away for
each reference coordinate.
"""
all_points = add_shells_to_ref_coords(
axes_... | 64e2be10cf04436d90789487cdb9c66cbafe3927 | 56,882 |
from typing import Union
def _auto_prefix_kg(value: float, power: Union[int, float]) -> str:
"""
Just like _auto_prefix but handles the one special case for "kg" because it already
has a prefix of "k" as an SI base unit. The difference is the comparison of
'power_of_ten'/1000 vs 'power_of_ten'.
""... | 3f9ec2dbc1cbde25b3865d5ce4617f7064354348 | 56,884 |
from typing import OrderedDict
def wrap_estimator(cls,
bases,
name=None,
module=None,
default_params=None,
is_generic=True,
custom_params=None):
"""
Creates a `sklearn`-compatible wrapper class fr... | b4ba0415864ba4ae652c8eca04b5aa1d3e92beec | 56,887 |
def create_flat_view(array):
"""返回数组的一维视图"""
flat_view = array.view()
flat_view.shape = array.size
return flat_view | 694953f72ad279f347bdc666f73ca21d843046e3 | 56,888 |
def create_to_idx_dict(source):
""" Creates a dictionary of item-specific indices form a tuple of lists. """
idx_dict = dict()
for i in source:
if i not in idx_dict:
idx_dict[i] = len(idx_dict)
return idx_dict | 0c8de2455b4fa78b4c29b75879c87f1ee2a2de40 | 56,889 |
from scipy.dsp import correlate
def xcorr(data, target, **kwargs):
"""
Cross-correlate two 1D.dsps.
Notes
-----
Detrend / taper first?
"""
shift = np.argmax(correlate(data, target)) - len(target) #+ 10
datan = np.zeros(len(data))# - shift)
if shift > 0:
datan[ :-shift] = data[shift: ... | 46a0be27758a25f4e24634a1a33b6bd38d41c906 | 56,890 |
def read(path):
"""
read wave data like matlab's audioread
"""
return sf.read(path)[0] | e781ba05cfd50a6b0fb7537c65d5f424f2f5f16a | 56,892 |
def decode(token):
"""Decode data in jwt token."""
return jwt.decode(token, app.config['JWT_SECRET'], algorithms=['HS256']) | ec62f6ced3778604ec35bc9e95ea18b5bdc5d7ee | 56,893 |
def get_reduce_out_shape(src_shape, axis=None, keepdims=False):
"""Get the output shape for the reduction OPs
Parameters
----------
src_shape : tuple of int or tvm.expr.IntImm
axis : None or int or tuple of int
keepdims : bool
Returns
-------
dst_shape : tuple of int or tvm.expr.... | 99d8bf7cbf4217d2cdeb511ca3c9ffd1d74c6b3c | 56,894 |
def init_mps_allzero(nsites, physdim, left_label='left',
right_label='right', phys_label='phys'):
"""
Create an MPS with `nsites` sites in the "all zero" state |00..0>.
Parameters
----------
nsites : int
physdim : int or list of ints
left_label : str
right_label : s... | 9bc7483d329fb15ee0f56c11e7fea7c8ad4c8e84 | 56,895 |
def get_input_geo(geo):
"""Similar to get_input_peer, but for geo points"""
if not isinstance(geo, TLObject):
_raise_cast_fail(geo, 'InputGeoPoint')
if type(geo).SUBCLASS_OF_ID == 0x430d225: # crc32(b'InputGeoPoint')
return geo
if isinstance(geo, GeoPoint):
return InputGeoPoin... | 82c3f8b59d331c018359f8500f1635b9bbfd9579 | 56,896 |
import inspect
def post_process_subclass_of(response, verbose=0):
"""
postprocess the response of the "subclass of" query
:param dict response: api response
:rtype: set of tuples
:return: {(wd_uri, wd_uri)}
"""
set_of_relations = set()
for info in response['results']['bindings']:
... | f7fa3b689ab9ddbfbcf69d8035ed4efa34576173 | 56,897 |
def _Fprime(mu, r0, vr0, inv_a, x):
"""Compute the first derivative of the Kepler equation in Universal
variables formulation
Parameters
----------
mu : float
Gravitational parameter [AU^3/days^2][description]
r0 : float
Modulus of the initial radio vector
vr0 : float
... | 8eac6cc6a8ed57565bf97313358ab6fc5c046186 | 56,898 |
def homepage():
"""List all available api routes."""
return (
f"Welcome to Hawaii - Climate Page<br/>"
f"<br/>"
f"This site has data from 01-01-2010 to 08-23-2017<br/>"
f"<br/>"
f"Available Pages:<br/>"
f"<br/>"
f"<br/>"
f" Station Information<br/... | 5c781d229d475ab4253b21c8f5002a020928fae9 | 56,899 |
def SourceRef(filename: str) -> FileSourceRef:
"""
Deprecated callable that provides a compatible stand-in for the old-style
SourceRef class constructor
"""
return FileSourceRef(filename) | af6edbf6dde68bb64f5519d57113df49d3904eae | 56,900 |
def service_interface_point (sip_uuid):
"""Retrieve ServiceInterfacePoint by ID
:param sip_uuid: ID of ServiceInterfacePoint
:type sip_uuid: str
:rtype: ServiceInterfacePoint
"""
for sip in context.service_interface_point:
if sip.uuid == sip_uuid:
return sip | 44ddc6b799b4a619c73d23f90f6c63075cf90b23 | 56,901 |
def addError(e, parser):
"""
assumes errors are lists, and
that the state is a position
"""
return bind(getState,
lambda pos: mapError(lambda es: [(e, pos)] + es, parser)) | eeabe120be337e1b05584348cf62933856d908f6 | 56,902 |
from typing import Optional
def get_group(api_management_name: Optional[str] = None,
name: Optional[str] = None,
resource_group_name: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetGroupResult:
"""
Use this data source to access info... | b57060641ffa913c117187f6dbeae21140e0b8c2 | 56,903 |
async def delete_topic(
topic_id: str, usecase: TopicUsecase = Depends(deps.get_topic_usecase)
) -> JSONResponse:
"""Delete a topic."""
try:
deleted: bool = await usecase.delete(topic_id)
except TopicCanNotBeChanged as err:
return JSONResponse(
status_code=status.HTTP_422_UNP... | d1ec1d32ac9f54d09f60702f70ed0a176980ea72 | 56,904 |
def _disc_disc(dynamod, measmod):
"""Check whether the state space model is discrete-discrete."""
dyna_is_disc = issubclass(type(dynamod), DiscreteModel)
meas_is_disc = issubclass(type(measmod), DiscreteModel)
return dyna_is_disc and meas_is_disc | 8fa546a78abe278d3c435686c8f5e09b5c3c65a0 | 56,905 |
def reduceby(key, binop, seq, init=no_default):
""" Perform a simultaneous groupby and reduction
The computation:
>>> result = reduceby(key, binop, seq, init) # doctest: +SKIP
is equivalent to the following:
>>> def reduction(group): # doctest: +SKIP
... re... | 698abf3587e1d54313bb40193534d0af82010fa6 | 56,906 |
def padaxis(array, new_size, axis, pad_value=0, pad_right=True):
"""
Padds one axis of an array to a new size
This is just a wrapper for np.pad, more usefull when only padding a single axis
Parameters
----------
array: ndarray
the array to pad
new_size: int
the new size of ... | 3f3f09de43e5c810797973cc2a57974ec65294bd | 56,907 |
def chomp_empty(seq):
"""Return slice of sequence seq without trailing empty tuples."""
n = len(seq)
while (n > 0) and seq[n - 1] == ():
n -= 1
return seq[:n] | 1c6f5f58bb2e73d44b2638d796b1b0a38bba414c | 56,908 |
def _logit(x):
"""
Logit function in Theano. Useful for parameterizing alpha.
"""
return np.log(x/(1. - x)) | 1dce705a78d7e4084cbb6f1a417517c5d0a17f74 | 56,909 |
def nvidia_model(input_shape=(160, 320, 3), drop_out = 0.5, drop_out_sp = 0.2):
"""
NVIDIA Architecture
src:[http://images.nvidia.com/content/tegra/automotive/images/2016/solutions/pdf/end-to-end-dl-using-px.pdf]
"""
print('\n\n ')
print('>> Building the model (NVIDIA Architecture)...')
... | a7365f69a09143f1c17b382f3ee3495e20ff30df | 56,910 |
def rmv_extra_channels(img):
"""
If a greyscale image is stored as some color image, it will have 3 (RGB) color channels. Since we assume it is really greyscale, all the channels will have equal value so we create a new image of same width and height, but with just 1 color channel.
Parameters
---------... | d4e4d5ca985294219be08dda882d4bed2fcbd0a9 | 56,911 |
from typing import Dict
import logging
from typing import List
def get_recommended_channels(**kwargs):
"""Show some of our Community's favorite channels you can join
see https://api.slack.com/methods/channels.list as well as https://api.slack.com/methods/channels.info for API info
"""
_, text = kwargs... | c61fb77a68d22afe03633f97b02a415d5795b227 | 56,912 |
def main(args=None):
"""
Actually runs Pedal from the command line.
Args:
args (argparse.Namespace): The arguments parsed from the command line.
"""
# Get command line arguments, unless we were explicitly given them.
if args is None:
args = parse_args()
pipeline = MODES.PIPE... | b1082e49e0c6e5aa33ac6cf709ae0717eb29918f | 56,914 |
def tessdata_to_df(tessdata, keep_garbage=False):
"""Ingests a string repr of tesseract output and spits out a dataframe"""
rows = [r.split("\t") for r in tessdata.split("\n")[:-1]]
h = rows[0]
rows = rows[1:]
df = pd.DataFrame(rows)
df.columns = h
# set types
dtypes = [int] * 10 + [fl... | a55320c90fe848b555e44c447fe95d762756b707 | 56,915 |
def find_best_match(gts, pred, pred_idx, threshold=0.5, form='pascal_voc', ious=None) -> int:
"""Returns the index of the 'best match' between the
ground-truth boxes and the prediction. The 'best match'
is the highest IoU. (0.0 IoUs are ignored).
Args:
gts: (List[List[Union[int, float]]]) Coord... | 83ccbb67565e92d6b2420d38ac8e90fb6456cc5c | 56,916 |
def rotation(v1, v2 = None, dim = 3):
"""
Rotation Matrix
rotates one matrix onto another
"""
if not isinstance(v1, Point):
if (isinstance(v1, np.ndarray) or isinstance(v1, list)):
v1 = Point(*v1)
else:
raise ValueError("Point must be Point Ojbect or list")
else:
v1 = Point(*v1.euclidean)
if not ... | 371979d44a916c0d6d5e9d6ac6fa3423bcd3fdcd | 56,917 |
import secrets
async def redirect(request: Request) -> Response:
"""Return plain password if user follows redirect chain."""
url = request.url_for("level:redirect")
secret = request.query_params.get("secret", "")
# If secret is not given, use first secret in redirect chain
if not secret:
... | a46829391aa543669238835aa0f149d8c41348c2 | 56,918 |
def get_time_signature_confidence(h5,songidx=0):
"""
Get signature confidence from a HDF5 song file, by default the first song in it
"""
return h5.root.analysis.songs.cols.time_signature_confidence[songidx] | 578992f3a3261555fc9003166c725bc82eb00d5c | 56,919 |
def remove_duplicates(probs, curr_teams, classes):
""" Iterates through algorithm predictions and if any prediction is the
same as a player's current team, replaces it with the next highest
scoring team.
Parameters:
probs (np
array): array of probabi... | f72932fa00c4ad291a4195d99b1334ffea9cc080 | 56,920 |
from typing import Optional
from typing import Sequence
def _render(
self,
frames: Optional[Sequence[int]] = None,
*,
num_frames: int,
) -> dict[str, np.ndarray]:
"""Mocked render."""
del frames
batch_shape = (num_frames, *self.scene.resolution)
return {
k: make_array_fn(batch_shape=batc... | 6b5a088235fcbb86614998e688c59d3c867e832c | 56,921 |
def tag_id(user_id, tag, escape=False):
"""tag to feedly ``:tag_id`` format
:param user_id: ``:user_id`` format data
:type user_id: :class:`basestring`
:param tag:
:type tag: :class:`basestring`
:param escape:
:type escape: :class:`bool`
:returns:
:rtype: :class:`basestring`
... | 379320f577e14cfdee892931049481cd6af11514 | 56,923 |
def read_replica_or_default():
"""
If there is a database called "read_replica",
return "read_replica", otherwise return "default".
This function is similiar to `use_read_replica_if_available`,
but is be more syntactically convenient for method call chaining.
Also, it always falls back to "defa... | d0b2391e0fbbe0c32e682b2e43d892a6737c8055 | 56,925 |
def _delta(x, y):
"""Computes |y|/|x|."""
return max(float(len(y))/float(len(x)), 1.0) | 22a55950406daeb3e7653d9a0a232d52a7bd76e4 | 56,926 |
import re
def compile(text, **variables):
"""Compile a table text to a ``Table`` object.
:param text: a table text
:param variables: values passed to the table
:type text: string
:type variables: dict
:return: a table object
:rtype: Table
:raise TableMarkupError: the text format is in... | 7014d8a07051123cb2df7abffced241fc5dcd2c6 | 56,927 |
def emphasized_url(
name: str, rawtext: str, text: str, lineno: int, inliner: docutils.parsers.rst.states.Inliner, *__
) -> tuple[list, list]:
"""
Sphinx role to add hyperlinked literals.
ReST: :literal-url:`Google <https://google.com>`
Markdown equivalent: [`Google`](https://google.com)
Refer... | 50c744063c6b65e02044d0711236e3058cec4ebb | 56,928 |
def choose_named_type(*args):
"""
choose_named_type(out_sym, root_til, title, ntf_flags, predicate=None) -> bool
Choose a type from a type library.
@param out_sym: pointer to be filled with the chosen type (C++:
til_symbol_t *)
@param root_til: pointer to starting til (the function wil... | 75d5bbc1179149d12e03992f4d91e551d9dd8a65 | 56,929 |
from datetime import date
def voto(ano):
"""
-> Função recebe o ano de nascimento do usuário .
:return: A idade e a verificação se o usuário está em idade eleitoral.
"""
atual = date.today().year
idade = atual - anonasc
if idade < 16:
return f'Você tem {idade} e não voto'
elif ... | b392efba24d943f591ca0ba3060bfc06313006e5 | 56,930 |
def quiet_call(cmd, devnull):
"""Calls an external command while suppressing stdout.
Args:
cmd (str): The command to run
devnull (object): File-like object
Returns:
bool: True if the commabd return code was zero, else otherwise
Examples:
>>> with open(os.devnull, 'wb')... | b24a68f7abe7b51feb44290aa15805a93d31e502 | 56,931 |
def _l2_clogistic_gradient_intercept(IL, Y, alpha):
""" Gradient of penalized loglikelihood with respect to the intercept parameters
Args:
IL : array_like. See _l2_clogistic_gradient_IL
Y : array_like. response matrix
alpha : array_like. intercepts. must have shape == one less than the ... | 3e818e7d010a6261a14df2c2b666d55ab86c5257 | 56,932 |
def dict_to_margins(margin_dict):
"""Convert a dictionary with margins informations into a list of distributions.
Parameters
----------
margin_dict : dict
A dictionary of information on the margins
Returns
-------
margins
"""
margins = []
for i in sorted(margin_dict.key... | ad82c5f4748d1e3b9b9128c33632aecca85e338d | 56,933 |
def omp_in_parallel():
"""Return 1 if the active-levels-var ICV is greater than zero; \
otherwise, return 0.
The effect of the omp_in_parallel routine is to return 1 if the current
task is enclosed by an active parallel region, and the parallel region is
enclosed by the outermost initial task... | ab2203bfe4f22b2ece40b469267fd94953ab7637 | 56,934 |
def get_token_time(token_index, sentence, duration):
"""
Linearly interpolate to guess the time a token was utterred
"""
return (token_index + 1) / max(1, len(sentence)) * duration | d227e782083ae6265e1bc4e286269c421e809985 | 56,935 |
def is_ip_addr(candidate):
"""Check a string to see if it is a valid v4 or v6 IP address
:param candidate: string to check
:return boolean
"""
return is_ipv4_addr(candidate) or is_ipv6_addr(candidate) | 31f531fc2279713376c327c360fcdbf61086701a | 56,936 |
def get_voxel_file(category, model_id):
"""Get the voxel absolute filepath for the model specified by category
and model_id.
Args:
category: Category of the model as a string (eg. '03001627')
model_id: Model ID of the model as a string
(eg. '587ee5822bb56bd07b11ae648ea92233')
... | 7a2934267ff43df56e553b92b94e2b4658ff4d2d | 56,938 |
from ..scene import SceneCanvas
from vispy.app import use_app
def TestingCanvas(bgcolor='black', size=(100, 100), dpi=None, decorate=None,
**kwargs):
"""Avoid importing scene until necessary."""
# On Windows decorations can force windows to be an incorrect size
# (e.g., instead of 100x10... | a41e399adcdff4bb68385ccb824a966b0ff65855 | 56,940 |
def bold(string, *funcs, **additional):
"""Text effect - bold. (see sgr_combiner())."""
return sgr_combiner(string, ansi.BOLD, *funcs, **additional) | 45804a5ea85b0bc0cc213054f37403a0429122b9 | 56,941 |
def forward_method_kwargs(**kwargs) -> dict:
"""Return all the keyword-arguments of a method, excluding the 'self' argument"""
retval = {}
for key, value in kwargs.items():
if key == 'self' or key.startswith('_'):
continue
elif key == 'kwargs':
retval.update(value)
... | 571ad0c61f33e608ce253c16f452e488257cbf31 | 56,942 |
def esc_ansicolor (color):
"""convert a named color definition to an escaped ANSI color"""
control = ''
if ";" in color:
control, color = color.split(";", 1)
control = AnsiControl.get(control, '')+";"
cnum = AnsiColor.get(color, '0')
return AnsiEsc % (control+cnum) | 71737fbd83a39b220e7e283da2978a1f12c6cd65 | 56,943 |
def load_inputs_twitter_(input_file, word_id_file, sentence_len, type_='', is_r=True, target_len=10, encoding='utf8'):
"""
Method obtained from Trusca et al. (2020). NOTE: not used in this project
:param input_file:
:param word_id_file:
:param sentence_len:
:param type_:
:param is_r:
:p... | 386b769b5fb3467ecb1164d309fe9b479e23445d | 56,944 |
def log_softmax(x):
"""
Compute log-domain softmax of logits
Args:
x: tensor, here logits
Returns:
tensor, log-domain softmax of input
"""
x_dev = x - tf.reduce_max(x, 1, keepdims=True)
logsoftmax = x_dev - tf.math.log(tf.reduce_sum(tf.exp(x_dev), 1, keepdims=True))
r... | 469c2fb6999c370e6926531480ddad8c106f70f9 | 56,945 |
def percent_identity(perc_indentities):
"""Plots read percent identity as a distribution/histogram plot.
Args:
perc_indentities: A list of the percentage identity figures.
Returns:
A matplotlib figure object containing the plot.
"""
bins = 100
xlabel = 'Read percent identity'
... | 43f8c0f49ce1ad8e5f3bdf8eebbf4d47a9412fdd | 56,947 |
def vel_disp_function_CPV2007(vel_disp_grid):
"""Evaluate the velocity dispersion function from the fit on SDSS DR6
by [1]_ on a provided grid and normalizes the result to unity, so it can
be used as a PMF from which to draw the velocity dispersion.
Parameters
----------
vel_disp_grid : array-... | c5e82a485a169ccb9c47ece39e4d1ab07e5f3b6a | 56,948 |
def match_json(json, mongo_filter):
"""
Returns the json that matches the given filter
:param json: json dict or list of json dicts
:param mongo_filter: json dict in mongo query syntax
:return: list of json dicts that match
"""
if type(json) is list:
fset = make_filter_chain(json, mo... | 5115d88c3b68e00a40599d3c6ab7a708a8bc13ce | 56,949 |
def mask_to_3ch(mask, r=True, g=True, b=True):
"""
Convert binary mask to 3 channel image. (for visualization purposes)
:param mask: binary 1-channel mask
:param r: fill red channel with 255 where mask==1
:param g: fill green channel with 255 where mask==1
:param b: fill blue channel with 255 w... | e0a3bd992fc2be291b8e372597113e8021cb6dd5 | 56,950 |
def load_cs(
src_file: str,
dhis2_instance: str,
dhis2_username: str,
dhis2_password: str,
dhis2_groups: str,
) -> gpd.GeoDataFrame:
"""Load cases de santé geometries from source file or DHIS2."""
# from source file
if src_file:
cs = gpd.read_file(src_file)
n_geoms = sum(... | e3cfa9795543fbeac9f4a54e048c208cd3d15577 | 56,951 |
def get_fs_info():
"""return a list containing the info returned by 'df -k', i.e,
file systems size and occupation, in Mb. And the filesystem type:
[dev, size, used, available, use%, mount point, fs type]"""
try:
buf = os.popen('df -k').readlines()
except (IOError, os.error), (errno, strerr... | 16952d7bf76639fb92c6b01b5a714dbea6cbc3ec | 56,952 |
import json
def get_details(details_string):
"""Return details content.
* If JSON as a formatted string
* Otherwise as a string as-is.
"""
content = details_string
rv = ''
try:
details = json.loads(content)
rv = ''.join(['<li>{k}: {v}</li>'.format(k=k, v=get_str_value(v))... | 6b2737b2f5c90b564842760ec55ecade5f49576f | 56,953 |
def calc_load_matrix(M,Minv=None,isSparse=False):
"""
Assembles _load matrix_ as used in state-space representation of
equation of motion
$$ B = [[0],[M^{-1}]] $$
where **M** is the system mass matrix.
***
Required:
* `M`, mass matrix, shape [n x n]. Unused i... | 2f2274691c44edb993c810fecc0cc51e4a6402ce | 56,956 |
def _get_keywords_with_score(extracted_lemmas, lemma_to_word):
"""Get words of `extracted_lemmas` and its scores, words contains in `lemma_to_word`.
Parameters
----------
extracted_lemmas : list of (float, str)
Given lemmas with scores
lemma_to_word : dict
Lemmas and corresponding w... | 385a54878e508a56ab772fec31f4ff9838048492 | 56,957 |
def url_scan_sync(url, timeout):
"""
Execute SlashNext's url/scansync API against the requested URL scan sync with the given parameters
:param url: URL to be scanned
:param timeout: Timeout value in seconds
:return: Response of the SlashNext url/scansync API
"""
# Create the required data di... | feb60c21124ca61cd4776f0fc2c067310b37cafe | 56,958 |
def create_app(config_object='webfront_service.settings.__init__'):
"""An application factory, as explained here: http://flask.pocoo.org/docs/patterns/appfactories/.
:param config_object: The configuration object to use.
"""
app = Flask(__name__.split('.')[0])
app.config.from_object(config_object)
... | ce01d13da269063d3886f4614426ec69d14802c8 | 56,959 |
def get_user_friend_profiles(proxies, auth, limit=None, user_id='', screen_name='', skip_status='', include_user_entities=''):
"""
Returns a list of user dictionaries for every user the specified user is following (otherwise known as their
'friends'). Either either user ID or screen name, if both are specif... | 0dd00c095b366088c4c17d9b7cab44266bfb09d6 | 56,960 |
def _file_metadata_by_replacing_path(f, new_path, new_is_dir=None):
"""Returns a copy of the f _file_metadata struct with the given path."""
root_path = _get_opt_attr(f, 'rootPath')
if new_is_dir == None:
new_is_dir = f.is_dir
return _struct_omitting_none(
path=new_path,
src=f.src,
root=r... | c38930f17664843525cad6afe0eb580282abac49 | 56,963 |
import re
def tokenize(text):
""""
Tokenization function for use in TfidfVectorizer in build_model()
1. Normalizes text (converts to lowercase)
2. Removes punctuation
3. Removes stop_words
4. Splits sentence into words (tokens)
5. Performs POS tagging
Parameters:
text: string to b... | f1903b3151a3a42622ec8ee3f9cf31ff51d64b63 | 56,964 |
def transform_gcp_firewall(fw_response):
"""
Adjust the firewall response objects into a format that is easy to write to Neo4j.
Also see _transform_fw_entry and _parse_port_string_to_rule().
:param fw_response: Firewall response object from the GCP API
:return: List of transformed firewall rule obje... | d9d6d1a9dfcbd0e7eb2b51a67c0d35ab55768384 | 56,965 |
import requests
def export_highlights_to_readwise(readwise_token, highlight_objects):
""" Submits highlights to Readwise via their API and return the API response.
The function takes 2 parameters:
- readwise_token: the token used for accessing the user's Readwise highlights through the Readwise API.
... | c6b2928aa488fb62d40470e441232ed67d61a020 | 56,966 |
def test_reddit():
"""The ShareOnReddit link enables sharing a link to an url on Reddit. Here we test that
- The link can be instantiated with a link to https://awesome-panel.org
- It works when clicked
"""
return TestApp(
test_reddit,
ShareOnReddit(url="https://awesome-panel.org").... | 5035521ae933ad1b433fc91348f587e730dd1ed7 | 56,967 |
from typing import List
def filter_relative_import_names(import_names: List[str]) -> List[str]:
"""Given a list of import names, filters out the relative import names."""
return list(name for name in import_names if is_relative_import_name(name)) | d4d4c43584f496d9d3392861dbb5cbf559a97f1e | 56,968 |
import pickle
def make_pred_dataframe(key, mask, image):
"""Takes an image id and a mask
and returns a dataframe with all cells"""
classes = ["tumor", "immune cells"]
with open(c.MODEL_DIR / "cell_classifier.pickle", "rb") as f:
features, model = pickle.load(f)
df_pred = pd.DataFrame(
... | 9148ecd9f7428aebe77e29b309d3398b92cc3e4a | 56,969 |
def initialize_omlet_config(cfg: DictConfig):
"""
See _omlet_config_schema()
"""
assert isinstance(cfg, DictConfig)
OmegaConf.set_struct(cfg, False)
om = _omlet_config_schema()
om.update(cfg.get('omlet', {}))
cfg.omlet = om # this is a copy operation
om = cfg.omlet
om._internal... | d041d844aca394bf43825cd1ab37820f1d868c8e | 56,970 |
def h(p1, p2):
"""Heuristic function"""
x1, y1 = p1
x2, y2 = p2
return abs(x1 - x2) + abs(y1 - y2) | 0d7522a3f92ae851bfa9b1a316a1fa97baccf98f | 56,972 |
import torch
def pdist(X, Y):
""" Computes all the pairwise distances
Parameters
----------
X : torch.tensor
shape [n, d]
Y : torch.tensor
shape [m, d]
Returns
-------
torch.tensor
shape [n, m] of all pairwise distances
"""
n, m = X.shape[0], Y.shape[0... | 10fce38b390211999344bd1b0daf0a4484aee2a8 | 56,973 |
def detab(self, elem="", lab="", v1="", v2="", v3="", v4="", v5="", v6="",
**kwargs):
"""Modifies element table results in the database.
APDL Command: DETAB
Parameters
----------
elem
Element for which results are to be modified. If ALL, modify all
selected elements [ESE... | 01f13f7e971c2c24e291712a7e634838e2e2ac5a | 56,974 |
from typing import Optional
def retriever_factory(
opt: Opt, dictionary: DictionaryAgent, shared=None
) -> Optional[RagRetriever]:
"""
Build retriever.
Override to build special BB2 Search Retrievers, if necessary
:param opt:
ParlAI Opt
:param dictionary:
dictionary agent
... | aa37babfffabf5491c542fa173352080b702f180 | 56,975 |
import pathlib
import json
def import_skin_data(mesh_name: str, path: pathlib.Path, import_type: ImportType = ImportType.order):
"""
Load skin data from disk and apply it to the given mesh.
"""
with open(path, "wb") as path_data:
skin_data = json.load(path_data)
return set_skin_weights(mesh_name, skin_data)
... | ef34bbe580000ead33a427c1f45c22243cad4398 | 56,977 |
from typing import List
from typing import Dict
def combine_fields(
fields: List[xr.DataArray],
field_record: Dict,
dim: str="valid_time",
) -> xr.DataArray:
"""
按维度 step 合并
"""
field = xr.concat(fields, dim=dim)
return field | df1973443eadd18730b0cb195bc41539ba53da72 | 56,978 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.