content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def humanize_list(elements):
""""
splits a list and add punctuations to it elements
"""
humanize_string = ''
if len(elements) > 1:
for element in elements:
if element == elements[len(elements)-2]: # second to last item
humanize_string = humanize_string + element.... | 5,303,800 |
def ark(row: typing.Mapping[str, str]) -> str:
"""The item ARK (Archival Resource Key)
Args:
row: An input CSV record.
Returns:
The item ARK.
"""
ark_prefix = "ark:/"
if row["Item ARK"].startswith(ark_prefix, 0):
return row["Item ARK"]
return ark_prefix + row["Item ... | 5,303,801 |
def recon(sino, angles,
weights = None, weight_type = 'unweighted', init_image = 0.0, prox_image = None, init_proj = None,
num_rows = None, num_cols = None, roi_radius = None,
delta_channel = 1.0, delta_pixel = 1.0, center_offset = 0.0,
sigma_y = None, snr_db = 30.0, sigma_x = No... | 5,303,802 |
def decompress(args):
""" Decompress a compressed representation stored in zarr format with the same model used for decompression.
"""
logger = logging.getLogger(args.mode + '_log')
# Open checkpoint from trained model state
state = utils.load_state(args)
decomp_model = models.Synthesizer(... | 5,303,803 |
def log(
text="",
color=None,
filename=None,
end=None,
flush=False,
is_write=True,
where_back=0,
is_code=False,
is_err=False,
is_output=True,
):
"""Print for own settings.
* colors:
__ https://rich.readthedocs.io/en/latest/appendix/colors.html#appendix-colors
"""... | 5,303,804 |
def save_data(df: DataFrame, database_filename: str) -> None:
"""
Saves the given DataFrame into a sqlite database which is created at the given database_filename.
:param df: DataFrame to store
:param database_filename: path where the sqlite db will be created
:return: None
"""
engine = crea... | 5,303,805 |
def gen_grid(n):
"""
Generate coorinates on the nxn grid
"""
for i in range(n):
for j in range(n):
yield (i,j) | 5,303,806 |
def common_member(a, b, natural_sort=True):
"""
Checks if two lists (or sets) have a common member, and if so, returns
the common members.
:param a: First list (or set)
:param b: Second list (or set)
:param bool natural_sort: Sort the resulting items naturally
(default: True)
:return: Tr... | 5,303,807 |
def save_html_report(directory, html, report_name):
"""Save an HTML report.
Args:
directory (str): Path to the directory where the report will be saved.
html (str): HTML report.
report_name (str): Name of the report.
"""
report_path = os.path.join(directory, "reports", report_n... | 5,303,808 |
def parse_args():
"""
parse arguments
"""
parser = argparse.ArgumentParser(
description="PaddlePaddle Youtube Recall Model Example")
parser.add_argument(
'--infer_set_path',
type=str,
required=True,
help="path of the infer set")
parser.add_argument(
... | 5,303,809 |
def lammps_data2xyz(data_path, output_dir=os.getcwd()):
""" Converts lammps.data file into xyz format """
xyz_path = os.path.join(output_dir, '%s.xyz' % os.path.basename(os.path.splitext(data_path)[0]))
with open(data_path, 'r') as d:
data_lines = d.readlines()
for line_index, line in enumerat... | 5,303,810 |
def compute_segment_lengths(conn):
""" Determine segment lengths used for cost normalization. """
cur = conn.cursor()
cur2 = conn.cursor()
cur3 = conn.cursor()
cur4 = conn.cursor()
write_cur = conn.cursor()
write_cur.execute("""BEGIN EXCLUSIVE TRANSACTION;""")
for (segment_pkey, ) in ... | 5,303,811 |
def transforms_description(f):
"""
Decorator which deepcopies the description and extracts ['rnn'][0] from it.
Desperately needs to be obsoleted.
"""
@wraps(f)
def wrapper(description, *args, **kwds):
description = copy.deepcopy(description)
try: desc = description['rnn'][0]
... | 5,303,812 |
async def close(ctx):
"""issueをcloseします。"""
try:
bot.close_issue(ctx.channel.id)
except ValueError:
return await ctx.send("issueがオープンされていません。", delete_after=5)
await ctx.message.add_reaction("\U0001f44d") | 5,303,813 |
def read_data(fname, filter_params, time_windows, time_units, fps, is_manual_index):
"""
Reads the timeseries_data and the blob_features for a given file within every time window.
return:
timeseries_data_list: list of timeseries_data for each time window (length of lists = number of windows)
... | 5,303,814 |
def ack_install_profile(request: DBCommand, device: Device, response: dict):
"""Acknowledge a response to ``InstallProfile``."""
if response.get('Status', None) == 'Error':
pass | 5,303,815 |
def forecast(
precip,
velocity,
timesteps,
threshold,
extrap_method="semilagrangian",
extrap_kwargs=None,
slope=5,
):
"""
Generate a probability nowcast by a local lagrangian approach. The ouput is
the probability of exceeding a given intensity threshold, i.e.
P(precip>=thres... | 5,303,816 |
def daily():
"""
Gets daily quote data using quandl and pandas
"""
# get etf symbols and grab the daily data based on last run
# get daily quandl using the diff file
pass | 5,303,817 |
def train_svm(documents, ntesting=500):
"""
:param documents- politeness-annotated training data
:type documents- list of dicts
each document must be preprocessed and
'sentences' and 'parses' and 'score' fields.
:param ntesting- number of docs to reserve for testing
:type ntesting- ... | 5,303,818 |
def get_logs_for_action(
data: Union[LogData, pd.DataFrame],
log_action: str,
selected_day: Optional[datetime.date] = None,
rows: Optional[Union[str, int, Sequence[int]]] = None,
) -> Union[pd.DataFrame, pd.Series]:
"""Filter log data for a specific action.
Parameters
----------
data : ... | 5,303,819 |
def fill_failed_list(song):
"""
fill the given song into global list 'failed2show'
"""
global failed_list
failed_list.insert(0,song) | 5,303,820 |
def main():
"""Compile *.tf.py files and run Terraform."""
to_process = [ent for ent in os.listdir(os.getcwd()) if ent.endswith(".tf.py")]
if len(to_process) == 0:
print(
"terraformpy - Error loading config: No .tf.py files found in %s"
% os.getcwd()
)
sys.ex... | 5,303,821 |
def is_mc_multiplier(multiplier, modulus):
"""
Checks if multiplier is a MC multiplier w.r.t. modulus.
:param multiplier: an integer in (0, modulus).
:param modulus: a prime number.
:return: True if multiplier is a MC multiplier w.r.t. modulus.
"""
return (modulus % multiplier) < math.floor(... | 5,303,822 |
def test_resample_iterations_dix_no_squeeze(f_prob):
"""Test _resample_iteration_idx with singular dimension.
Currently this fails for dimensions with just a single index as we use `squeeze` in
the code and not using squeeze doesnt maintain functionality. This means that
``_resample_iteration_idx`` sho... | 5,303,823 |
async def buckets_get(buckets: Buckets = Depends(Provide[Container.buckets])) -> List[Bucket]:
""" returns all buckets configured """
return buckets.get_all() | 5,303,824 |
def group_without_decoys(peptides, target_column, proteins):
"""Retrieve the protein group with a target-only FASTA.
Build a dictionary mapping the decoy peptides to a plausible unique
target peptide. Then proceed to map as with the targets.
Parameters
----------
peptides : pandas.DataFrame
... | 5,303,825 |
def get_endpoint_stats(netid: str, client: ShrunkClient) -> Any:
"""``GET /api/stats/endpoint``
Returns visit statistics for each Flask endpoint. Response format:
.. code-block:: json
{ "stats": [ { "endpoint": "string", "total_visits": "number", "unique_visits": "number" } ] }
:param netid:
... | 5,303,826 |
def create_project(project, notify_user=True):
"""
Create an OpenLDAP project.
Args:
project (Project): Project instance - required
notify_user (bool): Issue a notification email to the project technical lead? - optional
"""
url = ''.join([settings.OPENLDAP_HOST, 'project/'])
he... | 5,303,827 |
def _validate_metric(key, value, timestamp, step):
"""
Check that a param with the specified key, value, timestamp is valid and raise an exception if
it isn't.
"""
_validate_metric_name(key)
if not isinstance(value, numbers.Number) or value > np.finfo(np.float64).max \
or value < np.... | 5,303,828 |
def readToTuple(f_path):
"""Reads in a two-col file (tab-delim) and returns a list of tuples"""
f = open(f_path)
ls = []
for l in f:
if l.startswith("#"):
continue
ls.append(tuple(l.strip().split("\t")))
return ls | 5,303,829 |
def _preprocess_file(input_file: str, lang: str) -> List[Tuple[List[str]]]:
"""
Performs initial preprocessing, i.e., urls formatting, removal of "_trans" from Ru set
Args:
input_file: path to a file in google TN format
lang: data language
Returns:
Processed data. Each element ... | 5,303,830 |
def pod_status(logger, pod):
"""
Check health of a pod and returns it's status as result
"""
result = {'criteria': 'pass',
'name': pod.metadata.name,
'namespace': pod.metadata.namespace,
'node': pod.spec.node_name}
if pod.status.container_statuses is None:
... | 5,303,831 |
def predict(image, method_name, **kwargs):
"""
Get descriptor of image with an specific method.
"""
if method_name not in AVAILABLE_METHODS:
raise NotImplementedError(
"Method not currently supported. Implemented methods are:\n" + '\n'.join(AVAILABLE_METHODS))
if method_name ==... | 5,303,832 |
def buildUsageAndRatingByCityJs():
"""Builds several strings defining variables used for visualization.
Reads a CSV file containing the usage-by-city data and uses it
to build a JavaScript string defining a DataTable containing the data.
Returns:
{string} of the form <var_name>=<json>, where |var_name| is... | 5,303,833 |
def add_subparser(parser):
"""Add the subparser that needs to be used for this command"""
test_db_parser = parser.add_parser(
"test", help=SHORT_DESCRIPTION, description=SHORT_DESCRIPTION
)
test_db_parser.add_argument(
"-c",
"--config",
type=argparse.FileType("r"),
... | 5,303,834 |
def _set_progress_hasVoted(user):
"""
Sets Voter.hasVoted = True for the given user.
"""
def txn():
voter = _get_or_create_voter(user)
if not voter.hasVoted:
voter.hasVoted = True
voter.put()
db.run_in_transaction(txn) | 5,303,835 |
def test_behaviour_builder_adds_behaviour_to_sub_mock_when_called(match_ready_behaviour_builder, mock, method_name):
"""
:type match_ready_behaviour_builder: BehaviourBuilder
:type mock: Mock
"""
match_ready_behaviour_builder()
assert match_ready_behaviour_builder.behaviour in getattr(mock, met... | 5,303,836 |
def _get_Abc(c, c0=0, A_ub=None, b_ub=None, A_eq=None, b_eq=None, bounds=None,
x0=None, undo=[]):
"""
Given a linear programming problem of the form:
Minimize::
c @ x
Subject to::
A_ub @ x <= b_ub
A_eq @ x == b_eq
lb <= x <= ub
where ``lb = 0`` and ... | 5,303,837 |
def test_getH_dict3():
"""test field wrapper functions"""
pos_obs = (1, 2, 2)
mag = [[111, 222, 333], [22, 2, 2], [22, -33, -44]]
dim = 3
dic = {"magnetization": mag, "diameter": dim}
B1 = getH("Sphere", pos_obs, **dic)
B2 = []
for i in range(3):
pm = Sphere(mag[i], dim)
... | 5,303,838 |
def test_extra_004():
"""
Test to make sure the wide range of characters meets the GRM/CommonMark encodings.
Note that since % is followed by a 2 digit hex value, it is encoded per the common
mark libraries except for the % and the 2 digit hex value following it.
Another example of this is example ... | 5,303,839 |
def obj2np(obj):
"""Wraps an object into an np.array."""
ar = np.zeros((1,), dtype=np.object_)
ar[0] = obj
return ar | 5,303,840 |
def masking(tokens, p = 0.1, mask='[MASK]'):
"""
Returns a new list by replacing elements in `tokens` by `mask` with probability `p`.
Args:
tokens (list): list of tokens or token ids.
p (float): probability to mask each element in `tokens`.
Returns:
A new list by replacing eleme... | 5,303,841 |
def singlebyte_xor_cipher(hex):
"""
Takes a hex string and finds the best xor key
and returns (ResultString, Confidence)
"""
common = ['n', 'i', 'o', 't', 'e', ' ']
ret = None
score = 0
key=0
if not isinstance(hex, bytearray):
hex = hex.decode('hex')
hex = bytearray(hex)
for i in range(0, 255):
data = b... | 5,303,842 |
def absolute_url(context, route, *args, **kwargs):
"""The absolute url for a request and a route"""
return context.request.build_absolute_uri(reverse(route, args=args, kwargs=kwargs)) | 5,303,843 |
def get_Kernels(test_vectors,img_width):
"""
Creates 3x3 kernel which is operated by the conv2d
Parameters
----------
test_vectors : numpy array
Generated test vectors 3x1.
img_width : integer
with of test matrix.
Returns
-------
Kernel : numpy array
... | 5,303,844 |
def icosahedron(opts, nlev, mesh):
"""
ICOSAHEDRON Nth-level icosahedral mesh of the ellipsoid.
"""
if (not isinstance(opts, jigsaw_jig_t)):
raise Exception("Incorrect type: OPTS.")
if (not isinstance(mesh, jigsaw_msh_t)):
raise Exception("Incorrect type: MESH.")
geom = jigsa... | 5,303,845 |
def get_solc_version() -> Version:
"""
Get the version of the active `solc` binary.
Returns
-------
Version
solc version
"""
solc_binary = get_executable()
return wrapper._get_solc_version(solc_binary) | 5,303,846 |
def epoch2dt64(ep_time):
"""
Convert from epoch time (seconds since 1/1/1970 00:00:00) to
numpy.datetime64 array
Parameters
----------
ep_time : xarray.DataArray
Time coordinate data-array or single time element
Returns
-------
time : numpy.datetime64
The converted... | 5,303,847 |
def get_file_from_recipe_url(url):
"""Downloads file at url and returns tarball"""
r = requests.get(url, timeout=MULLED_SOCKET_TIMEOUT)
return tarfile.open(mode="r:bz2", fileobj=BytesIO(r.content)) | 5,303,848 |
def test20131031a(outputFolder = '/home/k/ARMOR/data_temp/'):
"""
constructing the LoG filtered images of monsoon
* 1. construct the individual filtered images
2. construct the combined images
"""
from armor import objects3
monsoon = objects3.monsoon
monsoon.fix()
#outputFolder = '... | 5,303,849 |
def test_client_deprecation_warn():
"""
Tests that calling ray.client directly raises a deprecation warning with
a copy pasteable replacement for the client().connect() call converted
to ray.init style.
"""
# Test warning when local client mode is used
with warnings.catch_warnings(record=Tru... | 5,303,850 |
def df_to_dict_single(df, curation_id=None):
"""
Purpose:
Convert a single entry pandas DataFrame into a dictionary and strip out
indexing information
:param df: pandas DataFrame with single entry (e.g., use df.loc[] to filter)
:param curation_id: integer providing the curation_id. Default: ... | 5,303,851 |
def check_lines_valid(left_line, right_line, last_left_line=None, last_right_line=None):
"""
Checks validity of two given lines based on there geometry and optionally based on the deviation to the previous
detected lines. Also calculates the Mean Absolute error and the Mean Squared Error of the x values bet... | 5,303,852 |
def get_the_manifest(filter_string, api_url, manifest_file, max_files=None):
"""
This function takes a JSON filter string and uses it to download a manifest from GDC
"""
#
# 1) When putting the size and "return_type" : "manifest" args inside a POST document, the result comes
# back as JSON, not... | 5,303,853 |
def imageseg(Cont_Image):
"""imageseg('Image Name')
This program takes an image that has been pre-proccessed by an edge finding script as its sole input, segments it, and spits out a segmented image file and a pandas dataframe of individual particle positions.
This function works by creating a binary... | 5,303,854 |
def getSisters(tree, t="g"):
"""Some nasty regex to get pairs of sister taxa
(only at terminal branches)"""
if t == "s":
l = re.findall("\(([1-9][0-9]|\d),([1-9][0-9]|\d)\)", tree)
else:
l = re.findall(
"\(([1-9][0-9]|\d):\d\.\d\d\d,([1-9][0-9]|\d):\d\.\d\d\d\)", tree
... | 5,303,855 |
async def test_light_set_hue(hass, init_integration):
"""Test set brightness of the light."""
init_integration
registry = er.async_get(hass)
entity_id = "light.lightbulb"
state = hass.states.get(entity_id)
assert state
assert state.state == STATE_ON
assert state.attributes.get("friendly... | 5,303,856 |
def cluster_ensembles(
labels: np.ndarray,
nclass: Optional[int] = None,
solver: str = 'hbgf',
random_state: Optional[int] = None,
verbose: bool = False) -> np.ndarray:
"""Generate a single consensus clustering label by using base labels
obtained from multiple cluster... | 5,303,857 |
def ReadFromXMLStream (istream,
options = XML_STRICT_HDR | XML_LOAD_DROP_TOP_LEVEL | XML_LOAD_EVAL_CONTENT, # best option for invertibility
array_disposition = ARRAYDISPOSITION_AS_NUMERIC_WRAPPER,
prepend_char=XML_PREPEND_CHAR) :
"""Read XML from... | 5,303,858 |
def enable(obj, source, destination, confirmation):
"""Enables an alias."""
src_username, src_domain = split_email(source)
dest_username, dest_domain = split_email(destination)
conn = get_db_connection(obj)
try:
enable_alias = (
conn.query(Aliases)
.filter_by(
... | 5,303,859 |
def AngleRA (angle,unit=units.hourangle,raise_errors=False):
"""
An object which represents a right ascension angle
see `astropy.coordinates.RA` for more extensive documentation
The primary difference with astropy is that if the call to coordinates.RA
errors you have the option to ignore it an... | 5,303,860 |
def check_private_asset(dest: Path, checksum: Optional[str] = None) -> None:
"""Check and validate assets without a URL (private assets that the user
has to provide themselves) and give feedback about the checksum.
dest (Path): Destination path of the asset.
checksum (Optional[str]): Optional checksum ... | 5,303,861 |
def k_euclidean_neighbors(k, x1, x2, exclude_identity=False, identities=None):
""" For each row vector in x1 the k-nearest neighbors in x2.
:param k:
:param x1: M x Feat-dim
:param x2: N x Feat-dim
:param exclude_identity:
:param identities:
:return: M x k
"""
all_cross_pairwise_dist... | 5,303,862 |
def get_train_feed_dict(model, reviews, win_reviews, batch_length, ote_labels, ts_labels, opn_labels, stm_lm_labels, lr, dropout_rate=1.0, train_flag=True):
"""Construct feed dictionary."""
feed_dict = dict()
feed_dict.update({model.reviews: reviews})
feed_dict.update({model.win_reviews: win_reviews})
... | 5,303,863 |
def pass_through_third_point(marking_points, i, j, thresh):
"""See whether the line between two points pass through a third point."""
x_1 = marking_points[i][1][0]
y_1 = marking_points[i][1][1]
x_2 = marking_points[j][1][0]
y_2 = marking_points[j][1][1]
for point_idx, point in enumerate(marking_... | 5,303,864 |
def increment_ctr(ctr):
"""
Increments one the counter.
Parameters
----------
ctr : string
Counter
Returns
-------
incremented_counter : string
Incremented Counter
"""
ctr_inc_int = int.from_bytes(bytes.fromhex(ctr), byteorder="big") + 1
return bytes.hex(c... | 5,303,865 |
def _instantiate(config: Any, *args: Any, **kwargs: Any) -> Any:
"""
:param config: An config object describing what to call and what params to use.
In addition to the parameters, the config must contain:
_target_ : target class or callable name (str)
And... | 5,303,866 |
def test_emb(
opt,
batch_size=16,
img_size=(1088, 608),
print_interval=40, ):
"""
:param opt:
:param batch_size:
:param img_size:
:param print_interval:
:return:
"""
data_cfg = opt.data_cfg
f = open(data_cfg)
data_cfg_dict = json.load(f)
f.clos... | 5,303,867 |
def is_supported(value, check_all=False, filters=None, iterate=True):
"""Return True if the value is supported, False otherwise"""
assert filters is not None
if not is_editable_type(value):
return False
elif not isinstance(value, filters):
return False
elif iterate:
i... | 5,303,868 |
def assert_testdb_annot_consistency(ibs_gt, ibs2, aid_list1, aid_list2):
"""
just tests uuids
if anything goes wrong this should fix it:
from ibeis.other import ibsfuncs
aid_list1 = ibs_gt.get_valid_aids()
ibs_gt.update_annot_visual_uuids(aid_list1)
ibs2.update_annot_visual_... | 5,303,869 |
def read(*paths):
"""read files"""
with open(os.path.join(*paths)) as filename:
return filename.read() | 5,303,870 |
def box_net(images,
level,
num_anchors,
num_filters,
is_training,
act_type,
repeats=4,
separable_conv=True,
survival_prob=None):
"""Box regression network."""
for i in range(repeats):
orig_images = images
... | 5,303,871 |
def process_folder(repo_path, folder):
"""Find files and send for processing."""
folder_path = repo_path + folder + "\\"
vars()[folder] = dict()
json_queries = enum_json(folder_path)
vars()[folder].update(json_queries)
yaml_queries = enum_yaml(folder_path)
vars()[folder].update(yaml... | 5,303,872 |
def img_to_array(img, data_format=None, dtype=None):
"""Converts a PIL Image instance to a Numpy array.
# Arguments
img: PIL Image instance.
data_format: Image data format, either "channels_first" or "channels_last".
If omitted (`None`), then `backend.image_data_format()` is used.
... | 5,303,873 |
def C3(theta):
"""
Parameters
----------
theta : float
Angle 'theta' to be rotated around the X axis in rad.
Returns
-------
array
Cossine matix (3X3) of a 'theta' rotation around the Z axis.
"""
return array([[cos(theta), sin(theta), 0],
[-sin(theta)... | 5,303,874 |
def deal_hand(n):
"""
Returns a random hand containing n lowercase letters.
ceil(n/3) letters in the hand should be VOWELS (note,
ceil(n/3) means the smallest integer not less than n/3).
Hands are represented as dictionaries. The keys are
letters and the values are the number of times th... | 5,303,875 |
def gen_random(prefix):
"""
:param prefix: string to prefix random key with
:return: prefix plus 16 char alphanumeric (lowercase) random string
"""
# TODO move to utils
p_len = len(prefix)
assert p_len < 5, p_len
return prefix + '-' + base64.b32encode(os.urandom(10))[:19 - p_len].decode(... | 5,303,876 |
def bibman(args=None):
"""Console script for bibman""" | 5,303,877 |
def fit_jigsaw( x, y, grid_size, jigsaw_grid, tiles ):
"""
This function recursively tries to find the solution to the jigsaw puzzle.
*** Heavily inspired by reddit user: u/Fuzzy-Age6814 ***
TODO: Cleanup and improve code readability.
"""
if len( tiles ) == 0:
return jigsaw_grid
... | 5,303,878 |
def open_url(filename, basepath=None):
"""Opens and reads a certain file from a web or remote location.
Opens and reads a certain file from a web or remote location. This
function utilizes the urllib2 module, which means that it is
restricted to the types of remote locations supported by urllib2.
... | 5,303,879 |
def parse_options(description, example_usage, args):
"""Parse training options user can specify in command line.
Parameters
----------
description : str
the description of the script using this parser
example_usage : str
an example of the runner script being used
args : list of ... | 5,303,880 |
def build_login():
""" Construye la ventana del inicio de sesion del usuario"""
layout =[[sg.T("Usuario", size=(8,1)), sg.InputText(key='-USER-')],
[sg.T("Contraseña", size=(8,1)), sg.InputText(key='-PASS-')],
[sg.Submit("LogIn", size=(15,1), pad=(0,15))],
[sg.T("No estas r... | 5,303,881 |
def get_tif_image_layer_count(file_name):
"""
:param file_name:
:return:
"""
with tifffile.TiffFile(file_name) as tif:
return len(tif.pages) | 5,303,882 |
def sonify_chromagram_with_signal(chroma_data, x, frame_rate, Fs, fading_msec=5, stereo=True):
"""Sonify the chroma features from a chromagram together with a corresponding signal
Parameters
----------
chroma_data : NumPy Array
A chromagram (e.g. gathered from a list of note events by lis... | 5,303,883 |
def p_skip_parameters_extra(p):
"""
skip_parameters : LEFT_PARENTHESIS skip_parameters RIGHT_PARENTHESIS skip_parameters
"""
p[0] = '%s%s%s%s' % (p[1], p[2], p[3], p[4]) | 5,303,884 |
def delete_role_from_user(sender: Role, instance: Role, **kwargs) -> None:
"""Unassigns the Role (instance) that is being deleted from every user that has it."""
for user in User.objects.filter(roles__contains=[instance.id]):
del user.roles[user.roles.index(instance.id)]
user.save() | 5,303,885 |
def ensure_binary(s, encoding='utf-8', errors='strict'):
"""Coerce **s** to six.binary_type.
For Python 2:
- `unicode` -> encoded to `str`
- `str` -> `str`
For Python 3:
- `str` -> encoded to `bytes`
- `bytes` -> `bytes`
"""
if isinstance(s, text_type):
return s.encode(encoding, errors)
... | 5,303,886 |
def pytest_pyfunc_call(pyfuncitem):
"""Run coroutines in an event loop instead of a normal function call."""
if asyncio.iscoroutinefunction(pyfuncitem.function):
existing_loop = pyfuncitem.funcargs.get('loop', None)
with _passthrough_loop_context(existing_loop) as _loop:
testargs = {... | 5,303,887 |
def get_forecast_times(forecast_length, forecast_date=None,
forecast_time=None):
"""
Generate a list of python datetime objects specifying the desired forecast
times. This list will be created from input specifications if provided.
Otherwise defaults are to start today at the most... | 5,303,888 |
def _extract_entities_and_relations(
config: dict
) -> Tuple[Union[Dict[str, list], list], Union[Dict[str, list], list]]:
"""
Read matched triples and create sets for all existing subjects, relations and objects to draw negative samples from.
If activated, these sets are additionally grouped by the ... | 5,303,889 |
def human_output():
"""Get request with human output params"""
response = requests.request("GET", BASE_URL, params=querystring)
return response | 5,303,890 |
def print_fixtures(self, fixtures_list, pk_list, fout):
"""
fixtures_list is a list of lists. Each element is a list of
[form name,fixture_dict]. Each element in fixture_dict
is [field, field_val]
function loops through each element in fixtures_list, then each
key(element) in fixtures_li... | 5,303,891 |
def multiset(left, right, pairwise):
"""
Calculate the multiset distance between two vectors.
:arg array_like left, right: Vector.
:arg function pairwise: A pairwise distance function.
:return: The multiset distance between `left` and `right`.
:rtype: float
Note that `function` must be ve... | 5,303,892 |
def add_verbs(ctx, root_map):
"""Add inflected verbs to the database."""
session = ctx.session
vclass = ENUM['vclass']
person = ENUM['person']
number = ENUM['number']
mode = ENUM['mode']
voice = ENUM['voice']
skipped = set()
i = 0
for row in util.read_csv(ctx.config['VERBS']):
... | 5,303,893 |
def json_response(func):
"""
A decorator thats takes a view response and turns it
into json. If a callback is added through GET or POST
the response is JSONP.
"""
def decorator(request, *args, **kwargs):
objects = func(request, *args, **kwargs)
if isinstance(objects, HttpResponse... | 5,303,894 |
def sample_CRP(N, alpha,d =0):
"""
sample from a Pitman-Yor process via the Chinese Restaraunt process, default
value of d=0 samples from a Dirichlet process
Parameters
-----------
N : scalar, integer
number of samples to return
alpha : scalar > -d
concentration parameter
... | 5,303,895 |
def read_obj(tu, call_graph):
"""
Reads the file tu.o and gets the binding (global or local) for each function
:param tu: name of the translation unit (e.g. for main.c, this would be 'main')
:param call_graph: a object used to store information about each function, results go here
"""
symbols = ... | 5,303,896 |
def test_concurrent_requests_not_available_on_http11_connections():
"""
Attempting to issue a request against an already active HTTP/1.1 connection
will raise a `ConnectionNotAvailable` exception.
"""
origin = Origin(b"https", b"example.com", 443)
network_backend = MockBackend(
[
... | 5,303,897 |
def iotest(fh, eof, blocksize=512, t=10):
"""io test"""
io_num = 0
start_ts = time.time()
while time.time() < start_ts+t:
io_num += 1
# freebsd8: need 512B sector alignment and at least one whole block left
pos = random.randint(0, eof - blocksize) & ~0x1ff
fh.seek(pos)
... | 5,303,898 |
def decentralized_registration(raster, win_num=1, reg_block_num=1, iter_num=4):
"""
Decentralized registration
Input: raster plot (poisson denoised)
Output: displacement estimate
"""
D, T = raster.shape
# get windows
window_list = []
if win_num == 1:
window_list.append(... | 5,303,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.