content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def expand_for_dithers(indict, verbose=True):
"""Expand a given dictionary to create one entry for each dither.
Supports parallel observations.
Moved here and modified from apt_inputs.py
Parameters
----------
indict : dict
dictionary of observations
Returns
-------
expand... | 73,700 |
def download_trace():
"""Provide the trace of the current exploration to be downloaded.
Note:
The file will be saved in the configured upload folder and WILL NOT be
deleted afterwards. A trick is to use the /tmp directory for them to be
automatically deleted.
Returns:
The t... | 73,701 |
def GenCppCode(kind_names, id_names, f, id_labels=None, kind_labels=None):
"""
Args:
kind_names: List of kind name strings, in display order
id_names: List of list of id name strings, in display order
f: output file
id_labels: optional name to integer
kind_labels: optional name to integer
"""
... | 73,702 |
def discover_oidc_provider_config(oidc_provider_config_endpoint, client_id, mccmnc):
"""
Make an HTTP request to the ZenKey discovery issuer endpoint to access
the carrier’s OIDC configuration
"""
oidc_provider_config_url = '%s?client_id=%s&mccmnc=%s' % (
oidc_provider_config_endpoint,
... | 73,703 |
def response_plain_text_ga(output, continuesession):
""" create a simple json plain text response """
return {
"payload": {
'google': {
"expectUserResponse": continuesession,
"richResponse": {
"items": [
{
... | 73,704 |
def NodeName(node):
"""Produce a string name for a given node.
For a Leaf this is the token name, and for a Node this is the type.
Arguments:
node: a tree node
Returns:
Name as a string.
"""
# Nodes with values < 256 are tokens. Values >= 256 are grammar symbols.
if node.type < 256:
return ... | 73,705 |
def get_current_weather():
"""
returns the lates entry from the weather table
"""
return Weather.query.with_entities(Weather.temp, Weather.weather_id).filter(
Weather.created_at >= (datetime.now() - timedelta(days=2))).order_by(
Weather.id.desc()).first() | 73,706 |
def get_hash(source: Union[str, bytes, BinaryIO],
algorithm: str = 'md5',
prefix: bool = False,
fast: bool = False) -> str:
"""
Calculates the hash for an object.
:param source: string, bytes or FileObject. Files must be opened in binary mode # noqa
:param algori... | 73,707 |
def BuildAndRepackWindows(signer=None):
"""Run buildandrepack for 32/64 dbg/prod."""
build_combos = [
{"arch": "amd64",
"debug_build": True}, {"arch": "amd64",
"debug_build": False}, {"arch": "i386",
"debug_build": True... | 73,708 |
def _GetChangesForMask(config_sed_input):
"""Get changes to config and run scripts for MaskRCNN.
Also update train_mlperf.py if nvprof is used.
Args:
config_sed_input: Input list of sed pairs for config_DGXA100.sh.
Returns:
config_sed_output: Output list of sed pairs for config_DGXA100.sh.
"""
co... | 73,709 |
def reportnulls(df):
"""
Takes a data frame and check de nulls and sum
the resutls and organizes them from highest to lowest
"""
null_counts = df.isnull().sum().sort_values(ascending=False)
# return count of null values
return null_counts | 73,710 |
def generate_manifest_in_from_hg():
"""Generate MANIFEST.in from 'hg manifest'"""
print("generating MANIFEST.in from 'hg manifest'")
cmd = r'''hg manifest | sed 's/\(.*\)/include \1/g' > MANIFEST.in'''
return subprocess.call(cmd, shell=True) | 73,711 |
def fbthrift_library_config(append=None, **kwargs):
"""fbthrift config. """
_blade_config.update_config('fbthrift_config', append, kwargs) | 73,712 |
def toggleado(wea):
"""Aplasta el botón de la página abierta en la GUI"""
if wea.state == 'normal':
wea.state = 'down' | 73,713 |
def decode(data):
"""
Decode a binary string into the original Python types.
"""
buffer = StringIO(data)
try:
value = decoder[buffer.read(1)](buffer)
except KeyError as e:
raise DecodeError("Type prefix not supported. (%s)" % e)
return value | 73,714 |
def getConstrainedTargets(driver, constraint_type='parentConstraint'):
"""
Gets all the transforms the given driver is driving through the giving constraint type.
Args:
driver (PyNode): The transform that is driving the other transform(s) through a constraint.
constraint_type (string): The... | 73,715 |
def get_isbr2_nii_file_paths(dir_paths: List[Path], file_selector: str) -> List[Path]:
"""Returns all the .nii.gz file paths for a given file_selector type.
Arguments:
dir_paths: a list of sample dir paths, each directory holds a full scan
file_selector: a string representing which file type to ... | 73,716 |
def train(model):
"""Train a model."""
# First party modules
import hwrt.train
hwrt.train.main(model) | 73,717 |
def divide_mnist_data(mnist):
"""
load mnist dataset
input:None
output:split these data into train valid and test data.
"""
mnist_X, mnist_y = shuffle(mnist.data, mnist.target, random_state=42)
# normalize
mnist_X = mnist_X/255.0
train_X, test_X, train_y, test_y = train_test_split(m... | 73,718 |
def main(rho, predictors):
"""
Get the cost space partition of given predictors without coverage
"""
# Get the intersection points of predictors
x_points = get_predictors_intersections(rho, predictors)
# Get the best predictor in each interval
interval_best_predictors = get_interval_best_pr... | 73,719 |
def pd_cols(input_df:pd.DataFrame) -> None:
"""Plot all columns of a pandas dataframe
Args:
input_df(pd.DataFrame):
Returns:
Raises:
"""
"Print all pandas columns"
with pd.option_context('display.max_columns', None):
display(input_df.head()) | 73,720 |
def fillPixels(im, N=1):
"""
Fill in the dead pixels. If a dead pixel has a least 4 finite neighbour
pixel, than replace the center pixel with a mean valuse of the neighbours
"""
X = im.shape[0]-1
Y = im.shape[1]-1
imcopy = np.copy(im)
for n in range(N):
# skip = int(np.floor((3+n... | 73,721 |
def get_mac_table(netmiko_session, vdc=None):
"""Get mac-address-table"""
mac_table = []
get_macs = 'show mac address-table'
if vdc is not None:
vdc_command = f"switchto vdc {vdc}"
get_vdcs = send_command(netmiko_session, vdc_command)
table = send_command(netmiko_session... | 73,722 |
def GetBoundaryVertexes( wire = None, tol = 1e-7, single = True, add = True, infa = True ):
"""
Description:
Gets boundary vertexes from a wire and put them into a group.
Arguments:
# wire
Description: The input wire.
Type: Wire
GUI selection: yes
Selection by name: yes
R... | 73,723 |
def WgBin2DFunc(v1, v2, wgs, Nbin1, Nbin2):
"""
Calculate the weighted quantile by given bin numbers
designed for 2D numpy array
"""
# Define the probabilities for the quantiles based on the number of bins
pq1 = np.linspace(0,1.0,Nbin1+1)
pq2 = np.linspace(0,1.0,Nbin2+1)
# Calculat... | 73,724 |
def opcode_8xy2(self, x, y) -> None:
"""8XY2 Set VX to VX AND VY"""
self.v[x] = self.v[x] & self.v[y] | 73,725 |
def train_linevd(
config, savepath, samplesz=-1, max_epochs=130, num_gpus=1, checkpoint_dir=None
):
"""Wrap Pytorch Lightning to pass to RayTune."""
model = lvd.LitGNN(
hfeat=config["hfeat"],
embtype=config["embtype"],
methodlevel=False,
nsampling=True,
model=config["... | 73,726 |
def RunWithVMs(vms, extra_envs=None):
"""Run Horovod on the cluster.
Args:
vms: A list of worker VMs.
extra_envs: A dictionary of environment variables.
Returns:
A list of sample.Sample objects.
"""
vm_util.RunThreaded(lambda vm: vm.RemoteCommand('rm -rf /tmp/models'), vms)
master_vm = vms[0]
... | 73,727 |
def convert_length(length: float, from_unit: Unit, to_unit: Unit) -> float:
"""Changes length measurements between units
Parameters
----------
length : float
measurement to convert
from_unit : Unit
[description]
to_unit : Unit
[description]
Returns
-------
f... | 73,728 |
def set_unmatched_surface(surface, vector):
# type: (EpBunch, Union[Vector2D, Vector3D]) -> None
"""Set boundary conditions for a surface which does not adjoin another one.
:param surface: The surface.
:param vector: The surface normal vector.
"""
if not hasattr(surface, "View_Factor_to_Ground"... | 73,729 |
def update_secret(namespace_name, rule):
"""Updates a single secret in the specified namespace.
"""
api = pykube.HTTPClient(pykube.KubeConfig.from_env())
# Read the source secret to be copied or to be used for update. If
# it doesn't exist, we will fail for just this update. We don't
# raise ... | 73,730 |
def corr_matrix(corr_mat, ax=None, model_names="auto", save_addr=""):
"""Visualize correlation matrix."""
if save_addr:
pathlib.Path(save_addr).parent.mkdir(parents=True, exist_ok=True)
plt.ioff()
if not ax:
fig, ax = plt.subplots(1, 1)
# mask upper triangle
mask = np.zeros... | 73,731 |
def one_hot_encoder(batch_inds, num_categories):
"""Applies one-hot encoding from jax.nn."""
one_hots = jax.nn.one_hot(batch_inds, num_classes=num_categories)
return one_hots | 73,732 |
def get_decks(f):
""" Get card deck categories, colors and text contents from Excel file. Always loads the first sheet i.e. the active one """
wb = openpyxl.load_workbook(f.name)
ws = wb.active
# Pick up deck names from the first row
decks = []
for j in range(1, ws.max_column+1):
i = ws... | 73,733 |
def topic_sample(
review_source: pd.DataFrame,
sample_frame: dict,
topic_number: int,
sample_size: int = 5,
) -> list:
"""
Returns a sample of reviews for a given topic
Args:
review_source - Panda's dataframe: a dataframe with all of the relevant reviews
sample_frame - dict:... | 73,734 |
def do_login():
"""
@api {post} /cookbook/auth/login User Login
@apiName authenticate
@apiDescription Example of an authentication service using sqlite3 and the froggy framework.
@apiGroup Authentication
@apiParam {String} email=kermit@muppets.com Email of the user.
@apiParam {String} ... | 73,735 |
def directory_to_trainer_input(file_names: List[str], text_processor: TextProcessor) -> Dict[str, List]:
"""generate images from example caption_list"""
captions_per_file: Dict[str, List] = {}
for file_name in file_names:
print('Load examples from:', file_name)
caption_list: List[str] = get_... | 73,736 |
async def test_cancelled_receive(network_node):
"""Test the case when a receive request is cancelled."""
private_key_pem_path = os.path.join(CUR_PATH, "data", "priv.pem")
wallet = Wallet({FETCHAI: private_key_pem_path})
oef_connection = OEFConnection(
address=wallet.addresses[FETCHAI],
o... | 73,737 |
def add_livestream(request, key):
""" Returns page to add a livestream VOD article """
data = {
"title": "Tools",
"file": File.objects.get(key=key),
"today": str(datetime.now())[:10],
"series_choices": Series.objects.all()
}
# File choices
data["file_choices"] = File... | 73,738 |
def run_non_ceabac(benchmarker, table_prefix, logger, profile, options):
"""
Runs the non-ceabac configuration files located in
/config/non_ceabac/ in addition to a baseline
Arguments:
benchmarker - the benchmarker that contains the connection
to Accumulo, encryptor, etc
... | 73,739 |
def get_num_gophers(blades, remainders, M):
"""Find no. of gophers given no. of blades and remainders."""
for i in range(1, M + 1):
congruences = all([i % b == r for b, r in zip(blades, remainders)])
if congruences:
return i
return None | 73,740 |
def adata_to_cluster_expression(adata, cluster_label, scale=True, add_density=True):
"""
Convert an AnnData to a new AnnData with cluster expressions. Clusters are based on `label` in `adata.obs`. The returned AnnData has an observation for each cluster, with the cluster-level expression equals to the average ... | 73,741 |
def test_Velocity():
"""Tests the rocket.Velocity function """
from rocketsim.rocket import Velocity
assert 101 == Velocity(100,10,.1)
assert 99.02 == Velocity(100,-9.8,.1)
assert -100.98 == Velocity(-100,-9.8,.1) | 73,742 |
def upgrade_osd(new_version, kick_function=None):
"""Upgrades the current osd
:param new_version: str. The new version to upgrade to
"""
if kick_function is None:
kick_function = noop
current_version = get_version()
status_set("maintenance", "Upgrading osd")
log("Current ceph versi... | 73,743 |
def get_rosetta_features_root():
"""
Get the path to Rosetta features directory through set ROSETTA3_DB env variable.
:rtype: str
"""
return os.getenv('ROSETTA3')+"/../tests/features" | 73,744 |
def export_paper_abstracts_csv(papers, path):
"""
Save paper abstracts in csv file
:param papers: Papers DataFrame
:param path: Path of csv file
"""
logging.info(f"Writing papers to {path}")
columns = ["id", "text"]
papers[columns].to_csv(path, index=False) | 73,745 |
def rtaph_yap(ya, yb, yamc):
"""
For post-CSP data, 'wrap' the YA value for YA in [0,1]. From rtaph.c.
:param ya: Y axis wiggle.
:type ya: numpy.ndarray
:param yb: Y axis coarse clock.
:type yb: numpy.ndarray
:param yamc: Raw Y detector position in FEE pixels.
:type yamc: numpy.nda... | 73,746 |
def correct_drift(data: ForcData, config: Config) -> ForcData:
"""Correct the raw magnetization for drift.
If the measurement space is Hc/Hb, dedicated drift points must have been measured. If the
measurement is H/Hr, the last datapoint along each curve is used. In either case, the points
used for drif... | 73,747 |
def svn_prop_dup(*args):
"""svn_prop_dup( prop, apr_pool_t pool)"""
return _core.svn_prop_dup(*args) | 73,748 |
def __calc_entropy_passphrase(word_count, word_bank_size, pad_length, pad_bank_size):
"""
Approximates the minimum entropy of the passphrase with its possible deviation
:param word_count: Number of words in passphrase
:param word_bank_size: Total number of words in the word bank
:param pad_length: N... | 73,749 |
def test_get_api_exception_parser_custom(mocker, get_parser):
"""Ensure custom parser is returned when setting set."""
settings_mock = mocker.patch(
'exception_dispatcher.dispatchers.rest_framework.settings',
)
settings_mock.EXCEPTION_DISPATCHER_API_EXCEPTION_PARSER = (
'test_parser_gett... | 73,750 |
def masked_softmax(X, valid_lens):
"""通过在最后一个轴上掩蔽元素来执行 softmax 操作"""
if valid_lens is None:
return ops.Softmax(-1)(X)
else:
shape = X.shape
if valid_lens.ndim == 1:
valid_lens = mnp.repeat(valid_lens, shape[1])
else:
valid_lens = valid_lens.reshape(-1)... | 73,751 |
def main(ctx: typer.Context, verbose: bool = typer.Option(False, "--verbose/--silent", "-v/-s"),
config: Path = typer.Option(
"scgs.ini",
exists=False,
file_okay=True,
dir_okay=False,
writable=False,
readable=True,
resolve_path=True,
... | 73,752 |
def test_setup_queue_action_updates_command_intent() -> None:
"""It should update command source correctly."""
queue_cmd = QueueCommandAction(
request=commands.WaitForResumeCreate(
params=commands.WaitForResumeParams(),
intent=commands.CommandIntent.SETUP,
),
crea... | 73,753 |
def any_error_issue(issues):
"""
Just iterate through a list of Issues (of the three types) to check if there is any error
:param issues:
:return:
"""
any_error = False
for i in issues:
from nexinfosys.command_generators import Issue, IType
if isinstance(i, dict):
... | 73,754 |
def do_interactive_clone(repos, url_type):
"""Go through list of repositories and clone some of them according to user response
Args:
repos: List of repositories metadata
"""
url = None
if url_type == "ssh":
url = "ssh_url"
if url_type == "http":
url = "clone_url"
... | 73,755 |
def _log_exception(msg, *args):
"""Log an error and turn on traceback if debug is on."""
_LOGGER.error(msg, *args, exc_info=_LOGGER.getEffectiveLevel() == logging.DEBUG) | 73,756 |
def test_post_ns_descriptors(post_ns_descriptors_keys):
"""Tests API call to onboard NS descriptor resources"""
sonata_vnfpkgm = SONATAClient.VnfPkgm(HOST_URL)
sonata_nsd = SONATAClient.Nsd(HOST_URL)
sonata_auth = SONATAClient.Auth(HOST_URL)
_token = json.loads(sonata_auth.auth(username=USERNAM... | 73,757 |
def main():
"""
Main entry point for Module Progress Script
"""
# Initialization
usr_settings = interface.get_user_settings()
course_ids = usr_settings["course_ids"]
canvas = usr_settings["canvas"]
tableau_dfs = []
# clear any folders that are currently in there (leave tableau fold... | 73,758 |
def join_string(list_string, join_string):
"""
Join string based on join_string
Parameters
----------
list_string : string list
list of string to be join
join_string : string
characters used for the joining
Returns
-------
string joined : string
a string whe... | 73,759 |
def convcensys():
"""
Converts a JSON file with shodan data to the common data model
"""
args = parse_args()
if args.flatten:
convert(args.filepath, from_censys_ipv4_flattened, args.indent)
else:
convert(args.filepath, from_censys_ipv4, args.indent) | 73,760 |
def value_from_example(example, feature_name):
"""Returns the feature as a Python list."""
feature = example.features.feature[feature_name]
feature_type = feature.WhichOneof('kind')
return getattr(feature, feature_type).value[:] | 73,761 |
def refresh_resources_properties(state, output):
"""Store all the resources (state and output) that we created as JSON
in the context."""
resources = {}
for resource in state.get('resources', []):
resources[resource[NAME]] = resource
for module in state.get('modules', []):
for nam... | 73,762 |
def apply_control(sys, u_opt):
""" evaluates the controlled system trajectory """
states = sys.states
# if not MPC:
timesteps = sys.timesteps
x_new = np.zeros([states, timesteps])
x_new[:, 0] = sys.state
cost = 0
for t in range(timesteps - 1):
u = u_opt[:, t]
# retur... | 73,763 |
def xfl_domshape_to_svg(domshape, mask=False):
"""Convert the XFL <DOMShape> element to SVG <path> elements.
Args:
domshape: An XFL <DOMShape> element
mask: If True, all fill colors will be set to #FFFFFF. This ensures
that the resulting mask is fully transparent.
Returns a 3... | 73,764 |
def magma_ccopy(n, dx, incx, dy, incy, queue):
"""
Vector copy.
"""
_libmagma.magma_ccopy(n, int(dx), incx, int(dy), incy, queue) | 73,765 |
async def chained_filter_repositories_labels(
client, headers, account_id, date_from, date_to, exclude_inactive, repos, timezone,
):
"""Chain the request to get filtered repos and labels."""
filtered_repositories, fr_datapoint = await filter_repositories(
client,
headers,
int(account... | 73,766 |
def corpus(input, output, is_sdf=False, requires_clean=True, is_isomerice=False):
""" Constructing dataset with SMILES-based molecules, each molecules will be decomposed
into a series of tokens. In the end, all the tokens will be put into one set as vocaulary.
Arguments:
input (string):... | 73,767 |
def return_value_from_dict_extended(some_dict: dict,
path_string: str) -> Any:
"""
Возвращает значение ключа в словаре по пути ключа "key.subkey.subsubkey"
:param some_dict:
:param path_string:
:return:
"""
check = access_dot_path(some_dict, path_string)
if che... | 73,768 |
def test_send_with_test():
"""
When all messages are test=True, send method never called
"""
q = Queue()
worker = SendWorkerThread(**{
'task_queue': q,
'name': 'test_thread',
'use_sandbox': True,
'cert_file': 'dummy.cert',
'key_file': 'dummy.key'
})
wo... | 73,769 |
def server(ctx, host=None, port=5000, debug=True, gitlogs=False):
"""Run the app server."""
sys.setrecursionlimit(settings.RECURSION_LIMIT) # [GRDM-9050, GRDM-16889]
if os.environ.get('WERKZEUG_RUN_MAIN') == 'true' or not debug:
if os.environ.get('WEB_REMOTE_DEBUG', None):
import pyde... | 73,770 |
def decrypt_workflow(filename, private_key, username):
"""Method to integrate the entire file encryption workflow.
Args-
filename::str: Name(path) of the file
private_key::str: Private key of the user
username::str: Username of the user
Returns-
None
"""
private_key =... | 73,771 |
def search(term, country='UA', media='music', entity=None, attribute=None, limit=50):
"""
Returns the result of the search of the specified term in an array of result_item(s)
:param term: String. The URL-encoded text string you want to search for. Example: Steven Wilson.
The method will tak... | 73,772 |
def returnFiles(path):
"""Collects a list of files within a file
:rtype: list
"""
if path:
onlyFiles = [join(path, f) for f in listdir(path) if isfile(join(path, f))]
# print("onlyFiles: ", onlyFiles)
return onlyFiles
# print("Path: ", listdir(path))
return None | 73,773 |
def maybe_download_and_extract_bz2(root, file_name, data_url):
"""Downloads file from given URL and extracts if bz2
Args:
root (str): The root directory
file_name (str): File name to download to
data_url (str): Url of data
"""
if not os.path.exists(root):
os.makedirs(roo... | 73,774 |
def minus(a: Tuple[int], b: Tuple[int]) -> Tuple[int]:
"""
Vektor a minus Vektor b.
:param a: Von den Werten in dieser Liste wird subtrahiert.
:param b: Diese Werte werden subtrahiert.
:return: Elementweise Differenz.
"""
assert len(a) == len(b)
return tuple(ax - bx for ax, bx in zip(a, ... | 73,775 |
def ccds():
"""
Returns list of Consensus CDS IDs by query paramaters
---
tags:
- Query functions
parameters:
- name: ccdsid
in: query
type: string
required: false
description: 'Consensus CDS ID'
default: 'CCDS13576'
- name: hgnc_symbol
... | 73,776 |
def test_extend_model():
"""
>>> app = make_simple_application(project_dir='.', reuse=False)
>>> U = get_model('user')
>>> U.properties.keys()
['username', 'age', 'id']
>>> U1 = get_model('user1')
>>> U1.properties.keys()
['age', 'id']
""" | 73,777 |
def test_servers_history():
"""Get server history."""
histroy = ethermine.servers_history()
assert isinstance(histroy, list)
assert isinstance(histroy[0], dict)
assert isinstance(histroy[0]["hashrate"], float)
assert isinstance(histroy[0]["time"], int)
assert isinstance(histroy[0]["server"]... | 73,778 |
def today_w_time():
"""
Returns today in format 'Y-m-d H:i:s'
"""
today = datetime.datetime.now()
today = today.replace(microsecond=0)
return today.isoformat(' ') | 73,779 |
def GetLast7DaysYesterday():
"""
Set date range as 7 days before yesteday up to yesterday
Returns
startDate: date object. Start of period.
endDate: date object. End of period.
countOfDays: integer. Number of days between start and end date
"""
# today's date as the time... | 73,780 |
def top_level_nodes(ig_service):
"""test fixture gets the top level navigation nodes"""
response = ig_service.fetch_top_level_navigation_nodes()
return response["nodes"] | 73,781 |
def download(url, download_file, overwrite=False, verbose=False):
"""Download a file from a url
"""
urlcleanup()
if (not os.path.isfile(download_file)) or overwrite:
try:
if verbose:
info('Downloading "{}" to "{}"\n'.format(url, download_file))
urlretrieve... | 73,782 |
def softmax_loss_vectorized(W, X, y, reg):
"""
Softmax loss function, vectorized version.
Inputs and outputs are the same as softmax_loss_naive.
"""
# Initialize the loss and gradient to zero.
loss = 0.0
dW = np.zeros_like(W)
num_classes = W.shape[1]
num_train = X.shape[0]
num_d... | 73,783 |
def _default_handlers(stream, logging_level):
"""Return a list of the default logging handlers to use.
Args:
stream: See the configure_logging() docstring.
"""
# Create the filter.
def should_log(record):
"""Return whether a logging.LogRecord should be logged."""
# FIXME: Ena... | 73,784 |
def walk_packages(packages: List[str]) -> Iterator[str]:
"""Iterates through all packages and sub-packages in the given list.
This uses runtime imports to find both Python and C modules. For Python packages
we simply pass the __path__ attribute to pkgutil.walk_packages() to get the content
of the packa... | 73,785 |
def _add_method_to_class(
target_cls,
method_name,
func,
dataset_name,
dataset,
repeat_suffix,
):
"""
Add the described method to the given class.
:param target_cls:
Test class to which to add a method.
:type target_cls:
`class`
:param... | 73,786 |
def ldap_add_memberuid(email, member_id):
"""
Update an existing LDAP account by adding another memberUid to it.
"""
logger = logging.getLogger('membership.utils.ldap_add_memberuid')
conn = settings.LDAP_CONN
cn = f'cn={email},{settings.LDAP_DOMAIN_CONTROLLER}'
changes = {'memberUid': (ldap... | 73,787 |
def test_linked_list_push_adds_new_item():
"""."""
from linked_list import LinkedList
l = LinkedList()
l.push('val')
assert l.head.data == 'val' | 73,788 |
def test_sister_message_not_in_detail_response(client, project):
"""for a regular project without any sisters projects, the message
about shared reports should not appear.
"""
response = client.get(reverse("project_detail", kwargs={"slug": project.slug}))
content = str(response.content)
msg = ... | 73,789 |
def read_pb2(filename, binary=True):
""" Convert a Protobuf Message file into mb.Compound
Parameters
---------
filename : str
binary: bool, default True
If True, will print a binary file
If False, will print to a text file
Todo: This could be more elegantly detected
Re... | 73,790 |
def is_unique_bloom_filter(bloom_filter, item):
"""
Converts Redis results to boolean representing if item was unique (aka not found).
Keyword arguments:
bloom_filter -- the bloom filter
item -- the item to check
Returns:
boolean -- True if unique (aka not found)
Throws:
Assertion... | 73,791 |
def get_avain_instance_count():
""" Return the number of currently active AVAIN processes """
instance_count = 0
for proc in psutil.process_iter():
try:
for elem in proc.cmdline():
if elem.endswith("/avain.py") or elem == "/usr/local/bin/avain":
insta... | 73,792 |
def split_imageset(original_dataroot, taget_dataroot, n_channels=3, p_size=512, p_overlap=96, p_max=800):
"""
split the large images from original_dataroot into small overlapped images with size (p_size)x(p_size),
and save them into taget_dataroot; only the images with larger size than (p_max)x(p_max)
... | 73,793 |
def incidence_rate_ci(events, time, alpha=0.05):
"""Calculate two-sided (1-alpha)% Wald Confidence interval of Incidence Rate
Returns (incidence rate, lower CL, upper CL, SE)
events:
-number of events/outcomes that occurred
time:
-total person-time contributed in this group
alpha:
... | 73,794 |
def update(connection=None, urls: Iterable[str] = None,
force_download: bool = False, taxids: Iterable[int] = None, silent: bool = False):
"""Updates CTD database
:param urls: list of urls to download
:type urls: iterable
:param connection: custom database connection string
:type connect... | 73,795 |
def extract_embeddings(config, vocab):
"""Extracts GloVe word embeddings for words in vocab.
Arguments:
config (object): Contains dataset & pipeline configuration info
"""
np.random.seed(config["seed"])
embeddings_config = config["embeddings"]
save_path_emb = embeddings_config["path"]
... | 73,796 |
def start_node(c, node=None, all_=False, celery_log_level=None, detached=False):
"""
(Re)Start the node(s) service(s). If a node service is running, stop and start it again.
:param node: The node to start, using the proper file in the `NODES_CONFIG_DIR`.
:param all_: If set, the nodes of which the conf... | 73,797 |
def test_visit_graph_order():
"""Test visit graph order traversal"""
nodes = [ImageTestNode(-1, []) for _ in range(5)]
nodes[2].deps = [nodes[3]]
nodes[1].deps = [nodes[4], nodes[2]]
nodes[0].deps = [nodes[4], nodes[1]]
visit_mock_pre = Mock(side_effect=lambda img: img)
visit_mock_post = Mo... | 73,798 |
def test_edf(_bids_validate):
"""Test write_raw_bids conversion for European Data Format data."""
bids_root = _TempDir()
data_path = op.join(testing.data_path(), 'EDF')
raw_fname = op.join(data_path, 'test_reduced.edf')
raw = mne.io.read_raw_edf(raw_fname)
raw.rename_channels({raw.info['ch_nam... | 73,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.