code stringlengths 59 4.4k | docstring stringlengths 5 7.69k |
|---|---|
def hyper_noise_from_contributions(self, noise_map, contributions):
return self.noise_factor * (noise_map * contributions) ** self.noise_power | Compute a scaled galaxy hyper noise-map from a baseline noise-map.
This uses the galaxy contribution map and the *noise_factor* and *noise_power* hyper-parameters.
Parameters
-----------
noise_map : ndarray
The observed noise-map (before scaling).
contributions : nd... |
def register_queries():
return [
dict(
query_name='bucket-file-download-histogram',
query_class=ESDateHistogramQuery,
query_config=dict(
index='stats-file-download',
doc_type='file-download-day-aggregation',
copy_fields=dict... | Register queries. |
def set_scheduled(self):
with self._idle_lock:
if self._idle:
self._idle = False
return True
return False | Returns True if state was successfully changed from idle to scheduled. |
def get_watcher(self):
if not self.watching:
raise StopIteration()
return self.client.eternal_watch(self.prefix, recursive=True) | Return a etcd watching generator which yields events as they happen. |
def FromJsonString(self, value):
self.Clear()
for path in value.split(','):
self.paths.append(path) | Converts string to FieldMask according to proto3 JSON spec. |
def cert_info():
sec_type = security_type()
if sec_type == 'pem':
return get_config_value('pem_path', fallback=None)
if sec_type == 'cert':
cert_path = get_config_value('cert_path', fallback=None)
key_path = get_config_value('key_path', fallback=None)
return cert_path, key_pa... | Path to certificate related files, either a single file path or a
tuple. In the case of no security, returns None. |
def FindFiles(dir_, in_filters=None, out_filters=None, recursive=True, include_root_dir=True, standard_paths=False):
if in_filters is None:
in_filters = ['*']
if out_filters is None:
out_filters = []
result = []
for dir_root, directories, filenames in os.walk(dir_):
for i_directo... | Searches for files in a given directory that match with the given patterns.
:param str dir_: the directory root, to search the files.
:param list(str) in_filters: a list with patterns to match (default = all). E.g.: ['*.py']
:param list(str) out_filters: a list with patterns to ignore (default = none). E.g... |
def has_lambda(src):
module_node = ast.parse(dedent(src))
lambdaexp = [node for node in ast.walk(module_node)
if isinstance(node, ast.Lambda)]
return bool(lambdaexp) | True if only one lambda expression is included |
def hold_exception(method):
@functools.wraps(method)
def wrapper(self, *args, **kwargs):
try:
return method(self, *args, **kwargs)
except Exception:
if self.exc_info:
raise
if not self._stack:
logger.debug('@hold_exception wrapp... | Decorator for glib callback methods of GLibMainLoop used to store the
exception raised. |
def recall(ntp, nfn):
if (ntp+nfn) > 0:
return ntp/(ntp+nfn)
else:
return np.nan | This calculates recall.
https://en.wikipedia.org/wiki/Precision_and_recall
Parameters
----------
ntp : int
The number of true positives.
nfn : int
The number of false negatives.
Returns
-------
float
The precision calculated using `ntp/(ntp + nfn)`. |
def record_add_subfield_into(rec, tag, subfield_code, value,
subfield_position=None,
field_position_global=None,
field_position_local=None):
subfields = record_get_subfields(
rec, tag,
field_position_global=field_... | Add subfield into specified position.
Specify the subfield by tag, field number and optionally by subfield
position. |
def run(command, data=None, timeout=None, kill_timeout=None, env=None, cwd=None):
command = expand_args(command)
history = []
for c in command:
if len(history):
data = history[-1].std_out[0:10*1024]
cmd = Command(c)
try:
out, err = cmd.run(data, timeout, kill_... | Executes a given commmand and returns Response.
Blocks until process is complete, or timeout is reached. |
def start_process_monitor(self):
Log.info("Start process monitor")
while True:
if len(self.processes_to_monitor) > 0:
(pid, status) = os.wait()
with self.process_lock:
if pid in self.processes_to_monitor.keys():
old_process_info = self.processes_to_monitor[pid]
... | Monitor all processes in processes_to_monitor dict,
restarting any if they fail, up to max_runs times. |
def SimplexNoiseAlpha(first=None, second=None, per_channel=False, size_px_max=(2, 16), upscale_method=None,
iterations=(1, 3), aggregation_method="max", sigmoid=True, sigmoid_thresh=None,
name=None, deterministic=False, random_state=None):
upscale_method_default = iap.Cho... | Augmenter to alpha-blend two image sources using simplex noise alpha masks.
The alpha masks are sampled using a simplex noise method, roughly creating
connected blobs of 1s surrounded by 0s. If nearest neighbour upsampling
is used, these blobs can be rectangular with sharp edges.
dtype support::
... |
def write_data(data, filename):
name, ext = get_file_extension(filename)
func = json_write_data if ext == '.json' else yaml_write_data
return func(data, filename) | Call right func to save data according to file extension |
def _check_audience(payload_dict, audience):
if audience is None:
return
audience_in_payload = payload_dict.get('aud')
if audience_in_payload is None:
raise AppIdentityError(
'No aud field in token: {0}'.format(payload_dict))
if audience_in_payload != audience:
raise ... | Checks audience field from a JWT payload.
Does nothing if the passed in ``audience`` is null.
Args:
payload_dict: dict, A dictionary containing a JWT payload.
audience: string or NoneType, an audience to check for in
the JWT payload.
Raises:
AppIdentityError: If ... |
def set_file_atrificat_of_project(self, doc, symbol, value):
if self.has_package(doc) and self.has_file(doc):
self.file(doc).add_artifact(symbol, value)
else:
raise OrderError('File::Artificat') | Sets a file name, uri or home artificat.
Raises OrderError if no package or file defined. |
def _prefix_exists_in_gcs(gcs_prefix, credentials=None):
gcs_service = _get_storage_service(credentials)
bucket_name, prefix = gcs_prefix[len('gs://'):].split('/', 1)
request = gcs_service.objects().list(
bucket=bucket_name, prefix=prefix, maxResults=1)
response = request.execute()
return response.get('... | Check whether there is a GCS object whose name starts with the prefix.
Since GCS doesn't actually have folders, this is how we check instead.
Args:
gcs_prefix: The path; should start with 'gs://'.
credentials: Optional credential to be used to load the file from gcs.
Returns:
True if the prefix mat... |
def _mergeFiles(key, chunkCount, outputFile, fields):
title()
files = [FileRecordStream('chunk_%d.csv' % i) for i in range(chunkCount)]
with FileRecordStream(outputFile, write=True, fields=fields) as o:
files = [FileRecordStream('chunk_%d.csv' % i) for i in range(chunkCount)]
records = [f.getNextRecord() ... | Merge sorted chunk files into a sorted output file
chunkCount - the number of available chunk files
outputFile the name of the sorted output file
_mergeFiles() |
def _data(self):
if self.is_caching:
return self.cache
with open(self.path, "r") as f:
return json.load(f) | A simpler version of data to avoid infinite recursion in some cases.
Don't use this. |
def listen_events(self, reconnects=0):
self.log.info('Listening for events from Marathon...')
self._attached = False
def on_finished(result, reconnects):
self.log.warn('Connection lost listening for events, '
'reconnecting... ({reconnects} so far)',
... | Start listening for events from Marathon, running a sync when we first
successfully subscribe and triggering a sync on API request events. |
def create_file(self, path, fp, force=False, update=False):
if 'b' not in fp.mode:
raise ValueError("File has to be opened in binary mode.")
path = norm_remote_path(path)
directory, fname = os.path.split(path)
directories = directory.split(os.path.sep)
parent = self
... | Store a new file at `path` in this storage.
The contents of the file descriptor `fp` (opened in 'rb' mode)
will be uploaded to `path` which is the full path at
which to store the file.
To force overwrite of an existing file, set `force=True`.
To overwrite an existing file only ... |
def charge_from_formula(formula):
r
negative = '-' in formula
positive = '+' in formula
if positive and negative:
raise ValueError('Both negative and positive signs were found in the formula; only one sign is allowed')
elif not (positive or negative):
return 0
multiplier, sign = ... | r'''Basic formula parser to determine the charge from a formula - given
that the charge is already specified as one element of the formula.
Performs no sanity checking that elements are actually elements.
Parameters
----------
formula : str
Formula string, very simply formats only, end... |
def get_item_metadata(self, item_id, token=None, revision=None):
parameters = dict()
parameters['id'] = item_id
if token:
parameters['token'] = token
if revision:
parameters['revision'] = revision
response = self.request('midas.item.getmetadata', parameter... | Get the metadata associated with an item.
:param item_id: The id of the item for which metadata will be returned
:type item_id: int | long
:param token: (optional) A valid token for the user in question.
:type token: None | string
:param revision: (optional) Revision of the item... |
def get_user_details(user_id):
reasons = []
try:
url = OSM_USERS_API.format(user_id=requests.compat.quote(user_id))
user_request = requests.get(url)
if user_request.status_code == 200:
user_data = user_request.content
xml_data = ET.fromstring(user_data).getchildre... | Get information about number of changesets, blocks and mapping days of a
user, using both the OSM API and the Mapbox comments APIself. |
def fix_hypenation (foo):
i = 0
bar = []
while i < len(foo):
text, lemma, pos, tag = foo[i]
if (tag == "HYPH") and (i > 0) and (i < len(foo) - 1):
prev_tok = bar[-1]
next_tok = foo[i + 1]
prev_tok[0] += "-" + next_tok[0]
prev_tok[1] += "-" + ne... | fix hyphenation in the word list for a parsed sentence |
def getStmgrsRegSummary(self, tmaster, callback=None):
if not tmaster or not tmaster.host or not tmaster.stats_port:
return
reg_request = tmaster_pb2.StmgrsRegistrationSummaryRequest()
request_str = reg_request.SerializeToString()
port = str(tmaster.stats_port)
host = tmaster.host
url = "h... | Get summary of stream managers registration summary |
def reset_colors(self):
for k, e in enumerate(self.g.edges()):
self.g.set_ep(e, 'edge_color', self.edge2queue[k].colors['edge_color'])
for v in self.g.nodes():
self.g.set_vp(v, 'vertex_fill_color', self.colors['vertex_fill_color']) | Resets all edge and vertex colors to their default values. |
def run(data, samples, force, ipyclient):
data.dirs.consens = os.path.join(data.dirs.project, data.name+"_consens")
if not os.path.exists(data.dirs.consens):
os.mkdir(data.dirs.consens)
tmpcons = glob.glob(os.path.join(data.dirs.consens, "*_tmpcons.*"))
tmpcats = glob.glob(os.path.join(data.dirs... | checks if the sample should be run and passes the args |
def get_package_list(self):
os_version = self.os_version
self.vprint('os_version:', os_version)
req_packages1 = self.required_system_packages
if req_packages1:
deprecation('The required_system_packages attribute is deprecated, '
'use the packager_system_packag... | Returns a list of all required packages. |
def p_file_depends(self, f_term, predicate):
for _, _, other_file in self.graph.triples((f_term, predicate, None)):
name = self.get_file_name(other_file)
if name is not None:
self.builder.add_file_dep(six.text_type(name))
else:
self.error = Tru... | Sets file dependencies. |
def main():
if not _curses:
if os.name == 'nt':
raise ValueError('curses is not supported under Windows')
raise ValueError('Your platform does not support curses.')
try:
driver = next(iter(Curses.DRIVERS))
except:
raise ValueError('... | If a project has a Curses driver, the section "main" in the section
"run" must be "bibliopixel.drivers.curses.Curses.main". |
def closure(self, rules):
closure = set()
todo = set(rules)
while todo:
rule = todo.pop()
closure.add(rule)
if rule.at_end:
continue
symbol = rule.rhs[rule.pos]
for production in self.nonterminals[symbol]:
... | Fills out the entire closure based on some initial dotted rules.
Args:
rules - an iterable of DottedRules
Returns: frozenset of DottedRules |
def _getRunningApps(cls):
def runLoopAndExit():
AppHelper.stopEventLoop()
AppHelper.callLater(1, runLoopAndExit)
AppHelper.runConsoleEventLoop()
ws = AppKit.NSWorkspace.sharedWorkspace()
apps = ws.runningApplications()
return apps | Get a list of the running applications. |
def compare_data_model_residuals(s, tile, data_vmin='calc', data_vmax='calc',
res_vmin=-0.1, res_vmax=0.1, edgepts='calc', do_imshow=True,
data_cmap=plt.cm.bone, res_cmap=plt.cm.RdBu):
residuals = s.residuals[tile.slicer].squeeze()
data = s.data[tile.slicer].squeeze()
model = s.model[tile.... | Compare the data, model, and residuals of a state.
Makes an image of any 2D slice of a state that compares the data,
model, and residuals. The upper left portion of the image is the raw
data, the central portion the model, and the lower right portion the
image. Either plots the image using plt.imshow()... |
def UpdateIncludeState(filename, include_dict, io=codecs):
headerfile = None
try:
headerfile = io.open(filename, 'r', 'utf8', 'replace')
except IOError:
return False
linenum = 0
for line in headerfile:
linenum += 1
clean_line = CleanseComments(line)
match = _RE_PATTERN_INCLUDE.search(clean... | Fill up the include_dict with new includes found from the file.
Args:
filename: the name of the header to read.
include_dict: a dictionary in which the headers are inserted.
io: The io factory to use to read the file. Provided for testability.
Returns:
True if a header was successfully added. Fals... |
def gmx_resid(self, resid):
try:
gmx_resid = int(self.offset[resid])
except (TypeError, IndexError):
gmx_resid = resid + self.offset
except KeyError:
raise KeyError("offset must be a dict that contains the gmx resid for {0:d}".format(resid))
return gmx... | Returns resid in the Gromacs index by transforming with offset. |
def star(self, startx, starty, points=20, outer=100, inner=50, draw=True, **kwargs):
self.beginpath(**kwargs)
self.moveto(startx, starty + outer)
for i in range(1, int(2 * points)):
angle = i * pi / points
x = sin(angle)
y = cos(angle)
if i % 2:
... | Draws a star. |
def parse_exponent(source, start):
if not source[start] in {'e', 'E'}:
if source[start] in IDENTIFIER_PART:
raise SyntaxError('Invalid number literal!')
return start
start += 1
if source[start] in {'-', '+'}:
start += 1
FOUND = False
while source[start] in NUMS:
... | returns end of exponential, raises SyntaxError if failed |
def cp_objectinfo_worker(task):
cpf, cpkwargs = task
try:
newcpf = update_checkplot_objectinfo(cpf, **cpkwargs)
return newcpf
except Exception as e:
LOGEXCEPTION('failed to update objectinfo for %s' % cpf)
return None | This is a parallel worker for `parallel_update_cp_objectinfo`.
Parameters
----------
task : tuple
- task[0] = checkplot pickle file
- task[1] = kwargs
Returns
-------
str
The name of the checkplot file that was updated. None if the update
fails for some reason... |
def get_all_accounts(self, start="", stop="", steps=1e3, **kwargs):
lastname = start
while True:
ret = self.blockchain.rpc.lookup_accounts(lastname, steps)
for account in ret:
yield account[0]
if account[0] == stop:
raise StopIt... | Yields account names between start and stop.
:param str start: Start at this account name
:param str stop: Stop at this account name
:param int steps: Obtain ``steps`` ret with a single call from RPC |
def _ClassifyInclude(fileinfo, include, is_system):
is_cpp_h = include in _CPP_HEADERS
if is_system and os.path.splitext(include)[1] in ['.hpp', '.hxx', '.h++']:
is_system = False
if is_system:
if is_cpp_h:
return _CPP_SYS_HEADER
else:
return _C_SYS_HEADER
target_dir, target_base = (
... | Figures out what kind of header 'include' is.
Args:
fileinfo: The current file cpplint is running over. A FileInfo instance.
include: The path to a #included file.
is_system: True if the #include used <> rather than "".
Returns:
One of the _XXX_HEADER constants.
For example:
>>> _ClassifyIn... |
def SETNS(cpu, dest):
dest.write(Operators.ITEBV(dest.size, cpu.SF == False, 1, 0)) | Sets byte if not sign.
:param cpu: current CPU.
:param dest: destination operand. |
def read_images(img_list, path='', n_threads=10, printable=True):
imgs = []
for idx in range(0, len(img_list), n_threads):
b_imgs_list = img_list[idx:idx + n_threads]
b_imgs = tl.prepro.threading_data(b_imgs_list, fn=read_image, path=path)
imgs.extend(b_imgs)
if printable:
... | Returns all images in list by given path and name of each image file.
Parameters
-------------
img_list : list of str
The image file names.
path : str
The image folder path.
n_threads : int
The number of threads to read image.
printable : boolean
Whether to print... |
def _draw(self):
if self.display:
print(self._formatstr.format(**self.__dict__), end='')
sys.stdout.flush() | Interal draw method, simply prints to screen |
def _hashable_bytes(data):
if isinstance(data, bytes):
return data
elif isinstance(data, str):
return data.encode('ascii')
else:
raise TypeError(data) | Coerce strings to hashable bytes. |
def calculate(self, T, method):
r
if method == TEST_METHOD_1:
prop = self.TEST_METHOD_1_coeffs[0] + self.TEST_METHOD_1_coeffs[1]*T
elif method == TEST_METHOD_2:
prop = self.TEST_METHOD_2_coeffs[0] + self.TEST_METHOD_2_coeffs[1]*T
elif method in self.tabular_data:
... | r'''Method to calculate a property with a specified method, with no
validity checking or error handling. Demo function for testing only;
must be implemented according to the methods available for each
individual method. Include the interpolation call here.
Parameters
----------
... |
def parse_node(self, node):
if node.get('id') in self.parsed_nodes:
return self.parsed_nodes[node.get('id')]
(node_parser, spec_class) = self.parser._get_parser_class(node.tag)
if not node_parser or not spec_class:
raise ValidationException(
"There is no s... | Parses the specified child task node, and returns the task spec. This
can be called by a TaskParser instance, that is owned by this
ProcessParser. |
def __convert_response_to_configuration(self, result_blob, dataset_ids):
builder = DataViewBuilder()
builder.dataset_ids(dataset_ids)
for i, (k, v) in enumerate(result_blob['descriptors'].items()):
try:
descriptor = self.__snake_case(v[0])
print(json.d... | Utility function to turn the result object from the configuration builder endpoint into something that
can be used directly as a configuration.
:param result_blob: Nested dicts representing the possible descriptors
:param dataset_ids: Array of dataset identifiers to make search template from
... |
def _hold_block(self, block_id):
managers = self.connected_managers
for manager in managers:
if manager['block_id'] == block_id:
logger.debug("[HOLD_BLOCK]: Sending hold to manager:{}".format(manager['manager']))
self.hold_worker(manager['manager']) | Sends hold command to all managers which are in a specific block
Parameters
----------
block_id : str
Block identifier of the block to be put on hold |
def LDRD(cpu, dest1, dest2, src, offset=None):
assert dest1.type == 'register'
assert dest2.type == 'register'
assert src.type == 'memory'
mem1 = cpu.read_int(src.address(), 32)
mem2 = cpu.read_int(src.address() + 4, 32)
writeback = cpu._compute_writeback(src, offset)
... | Loads double width data from memory. |
def authorize_view(self):
args = request.args.to_dict()
args['scopes'] = request.args.getlist('scopes')
return_url = args.pop('return_url', None)
if return_url is None:
return_url = request.referrer or '/'
flow = self._make_flow(return_url=return_url, **args)
... | Flask view that starts the authorization flow.
Starts flow by redirecting the user to the OAuth2 provider. |
def auto_complete_choices(self, case_sensitive=False):
self_basename = self.basename
self_basename_lower = self.basename.lower()
if case_sensitive:
def match(basename):
return basename.startswith(self_basename)
else:
def match(basename):
... | A command line auto complete similar behavior. Find all item with same
prefix of this one.
:param case_sensitive: toggle if it is case sensitive.
:return: list of :class:`pathlib_mate.pathlib2.Path`. |
def waitForValueToChange(self, timeout=10):
callback = AXCallbacks.returnElemCallback
retelem = None
return self.waitFor(timeout, 'AXValueChanged', callback=callback,
args=(retelem,)) | Convenience method to wait for value attribute of given element to
change.
Some types of elements (e.g. menu items) have their titles change,
so this will not work for those. This seems to work best if you set
the notification at the application level.
Returns: Element or None |
def search_item_by_name_and_folder(self, name, folder_id, token=None):
parameters = dict()
parameters['name'] = name
parameters['folderId'] = folder_id
if token:
parameters['token'] = token
response = self.request('midas.item.searchbynameandfolder', parameters)
... | Return all items with a given name and parent folder id.
:param name: The name of the item to search by.
:type name: string
:param folder_id: The id of the parent folder to search by.
:type folder_id: int | long
:param token: (optional) A valid token for the user in question.
... |
def parse_colors(path):
if path.endswith(".txt"):
return parse_rgb_txt_file(path)
elif path.endswith(".json"):
return parse_json_color_file(path)
raise TypeError("colorful only supports .txt and .json files for colors") | Parse the given color files.
Supported are:
* .txt for X11 colors
* .json for colornames |
def discover_all_plugins(self):
for v in pkg_resources.iter_entry_points('dgit.plugins'):
m = v.load()
m.setup(self) | Load all plugins from dgit extension |
async def _get_or_fetch_conversation(self, conv_id):
conv = self._conv_dict.get(conv_id, None)
if conv is None:
logger.info('Fetching unknown conversation %s', conv_id)
res = await self._client.get_conversation(
hangouts_pb2.GetConversationRequest(
... | Get a cached conversation or fetch a missing conversation.
Args:
conv_id: string, conversation identifier
Raises:
NetworkError: If the request to fetch the conversation fails.
Returns:
:class:`.Conversation` with matching ID. |
def has_implicit_access_to_dashboard(user, obj):
request = get_request_or_stub()
decoded_jwt = get_decoded_jwt_from_request(request)
return request_user_has_implicit_access_via_jwt(decoded_jwt, ENTERPRISE_DASHBOARD_ADMIN_ROLE) | Check that if request user has implicit access to `ENTERPRISE_DASHBOARD_ADMIN_ROLE` feature role.
Returns:
boolean: whether the request user has access or not |
def getSpec(cls):
spec = {
"description":IdentityRegion.__doc__,
"singleNodeOnly":True,
"inputs":{
"in":{
"description":"The input vector.",
"dataType":"Real32",
"count":0,
"required":True,
"regionLevel":False,
... | Return the Spec for IdentityRegion. |
def spanning_2d_grid(length):
ret = nx.grid_2d_graph(length + 2, length)
for i in range(length):
ret.node[(0, i)]['span'] = 0
ret[(0, i)][(1, i)]['span'] = 0
ret.node[(length + 1, i)]['span'] = 1
ret[(length + 1, i)][(length, i)]['span'] = 1
return ret | Generate a square lattice with auxiliary nodes for spanning detection
Parameters
----------
length : int
Number of nodes in one dimension, excluding the auxiliary nodes.
Returns
-------
networkx.Graph
A square lattice graph with auxiliary nodes for spanning cluster
detec... |
def incr(self, key, to_add=1):
if key not in self.value:
self.value[key] = CountMetric()
self.value[key].incr(to_add) | Increments the value of a given key by ``to_add`` |
def write_then_readinto(self, out_buffer, in_buffer, *,
out_start=0, out_end=None, in_start=0, in_end=None, stop=True):
if out_end is None:
out_end = len(out_buffer)
if in_end is None:
in_end = len(in_buffer)
if hasattr(self.i2c, 'writeto_then_... | Write the bytes from ``out_buffer`` to the device, then immediately
reads into ``in_buffer`` from the device. The number of bytes read
will be the length of ``in_buffer``.
Transmits a stop bit after the write, if ``stop`` is set.
If ``out_start`` or ``out_end`` is provided, then the out... |
def get_last_update(op):
last_update = get_end_time(op)
if not last_update:
last_event = get_last_event(op)
if last_event:
last_update = last_event['timestamp']
if not last_update:
last_update = get_create_time(op)
return last_update | Return the most recent timestamp in the operation. |
def parse(self):
for infile in self.infile_list:
logger.info('Processing : %s', infile)
status = True
file_status = naarad.utils.is_valid_file(infile)
if not file_status:
return False
with open(infile) as fh:
for line in fh:
words = line.split()
if n... | Parse the top output file
Return status of the metric parse
The raw log file is like the following:
2014-06-23
top - 00:00:02 up 18 days, 7:08, 19 users, load average: 0.05, 0.03, 0.00
Tasks: 447 total, 1 running, 443 sleeping, 2 stopped, 1 zombie
Cpu(s): 1.6%us, 0.5%sy, 0.0%ni, 97.9... |
def validate(self, data):
user = self._confirmation.email.user
if (
app_settings.EMAIL_VERIFICATION_PASSWORD_REQUIRED
and not user.check_password(data["password"])
):
raise serializers.ValidationError(
_("The provided password is invalid.")
... | Validate the provided data.
Returns:
dict:
The validated data.
Raises:
serializers.ValidationError:
If the provided password is invalid. |
def _get_drug_target_interactions(manager: Optional['bio2bel_drugbank.manager'] = None) -> Mapping[str, List[str]]:
if manager is None:
import bio2bel_drugbank
manager = bio2bel_drugbank.Manager()
if not manager.is_populated():
manager.populate()
return manager.get_drug_to_hgnc_symbo... | Get a mapping from drugs to their list of gene. |
def set_auth(pem=None, cert=None, key=None, aad=False):
if any([cert, key]) and pem:
raise ValueError('Cannot specify both pem and cert or key')
if any([cert, key]) and not all([cert, key]):
raise ValueError('Must specify both cert and key')
if pem:
set_config_value('security', 'pem'... | Set certificate usage paths |
def heappushpop_max(heap, item):
if heap and heap[0] > item:
item, heap[0] = heap[0], item
_siftup_max(heap, 0)
return item | Fast version of a heappush followed by a heappop. |
def PSHUFD(cpu, op0, op1, op3):
size = op0.size
arg0 = op0.read()
arg1 = op1.read()
order = Operators.ZEXTEND(op3.read(), size)
arg0 = arg0 & 0xffffffffffffffffffffffffffffffff00000000000000000000000000000000
arg0 |= ((arg1 >> (((order >> 0) & 3) * 32)) & 0xffffffff)
... | Packed shuffle doublewords.
Copies doublewords from source operand (second operand) and inserts them in the destination operand
(first operand) at locations selected with the order operand (third operand).
:param cpu: current CPU.
:param op0: destination operand.
:param op1: so... |
def release(self, buffer=True):
for key, vao in self.vaos:
vao.release()
if buffer:
for buff in self.buffers:
buff.buffer.release()
if self._index_buffer:
self._index_buffer.release() | Destroy the vao object
Keyword Args:
buffers (bool): also release buffers |
def sim_editex(src, tar, cost=(0, 1, 2), local=False):
return Editex().sim(src, tar, cost, local) | Return the normalized Editex similarity of two strings.
This is a wrapper for :py:meth:`Editex.sim`.
Parameters
----------
src : str
Source string for comparison
tar : str
Target string for comparison
cost : tuple
A 3-tuple representing the cost of the four possible edi... |
def serve_dir(dir_path):
print('Performing first pass index file generation')
created_files = _create_index_files(dir_path, True)
if (PIL_ENABLED):
print('Performing PIL-enchanced optimised index file generation in background')
background_indexer = BackgroundIndexFileGenerator(dir_path)
... | Generate indexes and run server from the given directory downwards.
@param {String} dir_path - The directory path (absolute, or relative to CWD)
@return {None} |
def unpublish(self, registry=None):
return registry_access.unpublish(
self.getRegistryNamespace(),
self.getName(),
self.getVersion(),
registry=registry
) | Try to un-publish the current version. Return a description of any
errors that occured, or None if successful. |
def add_annotation_comment(self, doc, comment):
if len(doc.annotations) != 0:
if not self.annotation_comment_set:
self.annotation_comment_set = True
if validations.validate_annotation_comment(comment):
doc.annotations[-1].comment = str_from_text(co... | Sets the annotation comment. Raises CardinalityError if
already set. OrderError if no annotator defined before.
Raises SPDXValueError if comment is not free form text. |
def send_direct_operate_command(self, command, index, callback=asiodnp3.PrintingCommandCallback.Get(),
config=opendnp3.TaskConfig().Default()):
self.master.DirectOperate(command, index, callback, config) | Direct operate a single command
:param command: command to operate
:param index: index of the command
:param callback: callback that will be invoked upon completion or failure
:param config: optional configuration that controls normal callbacks and allows the user to be specified for SA |
def create_dataset_version(self, dataset_id):
failure_message = "Failed to create dataset version for dataset {}".format(dataset_id)
number = self._get_success_json(self._post_json(routes.create_dataset_version(dataset_id), data={}, failure_message=failure_message))['dataset_scoped_id']
return D... | Create a new data set version.
:param dataset_id: The ID of the dataset for which the version must be bumped.
:type dataset_id: int
:return: The new dataset version.
:rtype: :class:`DatasetVersion` |
def join_path_to_filelist(path, filelist):
return [op.join(path, str(item)) for item in filelist] | Joins path to each line in filelist
Parameters
----------
path: str
filelist: list of str
Returns
-------
list of filepaths |
def verify_jid_against_common_name(self, jid):
if not self.common_names:
return False
for name in self.common_names:
try:
cn_jid = JID(name)
except ValueError:
continue
if jid == cn_jid:
return True
r... | Return `True` if jid is listed in the certificate commonName.
:Parameters:
- `jid`: JID requested (domain part only)
:Types:
- `jid`: `JID`
:Returntype: `bool` |
def to_datetime(when):
if when is None or is_datetime(when):
return when
if is_time(when):
return datetime.combine(epoch.date(), when)
if is_date(when):
return datetime.combine(when, time(0))
raise TypeError("unable to convert {} to datetime".format(when.__class__.__name__)) | Convert a date or time to a datetime. If when is a date then it sets the time to midnight. If
when is a time it sets the date to the epoch. If when is None or a datetime it returns when.
Otherwise a TypeError is raised. Returned datetimes have tzinfo set to None unless when is a
datetime with tzinfo set in ... |
def _clean_up(paths):
print('Cleaning up')
for path in paths:
print('Removing %s' % path)
os.unlink(path) | Clean up after ourselves, removing created files.
@param {[String]} A list of file paths specifying the files we've created
during run. Will all be deleted.
@return {None} |
def main():
logging.basicConfig(level=logging.INFO)
log.setLevel(logging.INFO)
bms_base = get_bms_base()
neurommsig_base = get_neurommsig_base()
neurommsig_excel_dir = os.path.join(neurommsig_base, 'resources', 'excels', 'neurommsig')
nift_values = get_nift_values()
log.info('Starting Alzhei... | Convert the Alzheimer's and Parkinson's disease NeuroMMSig excel sheets to BEL. |
def install_config(local_path=None, remote_path=None, render=True, extra=None, formatter=None):
local_path = find_template(local_path)
if render:
extra = extra or {}
local_path = render_to_file(template=local_path, extra=extra, formatter=formatter)
put_or_dryrun(local_path=local_path, remote... | Returns a template to a remote file.
If no filename given, a temporary filename will be generated and returned. |
def admin_obj_link(obj, display=''):
url = reverse('admin:%s_%s_changelist' % (obj._meta.app_label,
obj._meta.model_name))
url += '?id__exact=%s' % obj.id
text = str(obj)
if display:
text = display
return format_html('<a href="{}">{}</a>', url, text) | Returns a link to the django admin change list with a filter set to
only the object given.
:param obj:
Object to create the admin change list display link for
:param display:
Text to display in the link. Defaults to string call of the object
:returns:
Text containing HTML for a... |
def _publish_edited(self):
record_pid, record = self.fetch_published()
if record.revision_id == self['_deposit']['pid']['revision_id']:
data = dict(self.dumps())
else:
data = self.merge_with_published()
data['$schema'] = self.record_schema
data['_deposit']... | Publish the deposit after for editing. |
def _initializeBucketMap(self, maxBuckets, offset):
self._maxBuckets = maxBuckets
self.minIndex = self._maxBuckets / 2
self.maxIndex = self._maxBuckets / 2
self._offset = offset
self.bucketMap = {}
def _permutation(n):
r = numpy.arange(n, dtype=numpy.uint32)
self.random.shuffle(r)
... | Initialize the bucket map assuming the given number of maxBuckets. |
def save(url, *args, **kwargs):
device = heimdallDevice(kwargs.get('device', None))
kwargs['width'] = kwargs.get('width', None) or device.width
kwargs['height'] = kwargs.get('height', None) or device.height
kwargs['user_agent'] = kwargs.get('user_agent', None) or device.user_agent
screenshot_image =... | Parse the options, set defaults and then fire up PhantomJS. |
def search(self, query):
if self.authSubToken is None:
raise LoginError("You need to login before executing any request")
path = SEARCH_URL + "?c=3&q={}".format(requests.utils.quote(query))
self.toc()
data = self.executeRequestApi2(path)
if utils.hasPrefetch(data):
... | Search the play store for an app.
nb_result (int): is the maximum number of result to be returned
offset (int): is used to take result starting from an index. |
def check_inputs(self, comps):
error = False
compcats = [c.category for c in comps]
for k, v in iteritems(self.varmap):
if k not in self.modelstr['full']:
log.warn('Component (%s : %s) not used in model.' % (k,v))
if v not in compcats:
log.... | Check that the list of components `comp` is compatible with both the
varmap and modelstr for this Model |
def enter_pairs(iloc, pnames, snppad, edg, aseqs, asnps, smask, samplecov, locuscov, start):
LOGGER.info("edges in enter_pairs %s", edg)
seq1 = aseqs[iloc, :, edg[0]:edg[1]+1]
snp1 = asnps[iloc, edg[0]:edg[1]+1, ]
seq2 = aseqs[iloc, :, edg[2]:edg[3]+1]
snp2 = asnps[iloc, edg[2]:edg[3]+1, ]
nalln... | enters funcs for pairs |
def exists(self):
query = (
"SELECT name FROM sqlite_master " + "WHERE type='table' AND name=?",
(self.__tablename__,),
)
connection = sqlite3.connect(self.sqlite_file)
cursor = connection.cursor()
cursor.execute(*query)
return True if cursor.fetch... | Check if the database table exists |
def get_attributes(var):
is_valid = partial(is_valid_in_template, var)
return list(filter(is_valid, dir(var))) | Given a varaible, return the list of attributes that are available inside
of a template |
def copy(self, graph):
l = self.__class__(graph, self.n)
l.i = 0
return l | Returns a copy of the layout for the given graph. |
def hls_palette(n_colors=6, h=.01, l=.6, s=.65):
hues = np.linspace(0, 1, n_colors + 1)[:-1]
hues += h
hues %= 1
hues -= hues.astype(int)
palette = [colorsys.hls_to_rgb(h_i, l, s) for h_i in hues]
return palette | Get a set of evenly spaced colors in HLS hue space.
h, l, and s should be between 0 and 1
Parameters
----------
n_colors : int
number of colors in the palette
h : float
first hue
l : float
lightness
s : float
saturation
Returns
-------
palette ... |
def get_attribute(element, attribute, default=0):
a = element.getAttribute(attribute)
if a == "":
return default
return a | Returns XML element's attribute, or default if none. |
def forward_events_to(self, sink, include_source=False):
assert isinstance(sink, Eventful), f'{sink.__class__.__name__} is not Eventful'
self._forwards[sink] = include_source | This forwards signal to sink |
def _install_packages(path, packages):
def _filter_blacklist(package):
blacklist = ['-i', '
return all(package.startswith(entry) is False for entry in blacklist)
filtered_packages = filter(_filter_blacklist, packages)
for package in filtered_packages:
if package.startswith('-e '):
... | Install all packages listed to the target directory.
Ignores any package that includes Python itself and python-lambda as well
since its only needed for deploying and not running the code
:param str path:
Path to copy installed pip packages to.
:param list packages:
A list of packages ... |
def _generate(self):
n = self._n
w = self._w
assert type(w) is int, "List for w not supported"
for i in xrange(n / w):
pattern = set(xrange(i * w, (i+1) * w))
self._patterns[i] = pattern | Generates set of consecutive patterns. |
def get_attached_cdrom(self, datacenter_id, server_id, cdrom_id):
response = self._perform_request(
'/datacenters/%s/servers/%s/cdroms/%s' % (
datacenter_id,
server_id,
cdrom_id))
return response | Retrieves an attached CDROM.
:param datacenter_id: The unique ID of the data center.
:type datacenter_id: ``str``
:param server_id: The unique ID of the server.
:type server_id: ``str``
:param cdrom_id: The unique ID of the CDROM.
:type ... |
def dixon_price(theta):
x, y = theta
obj = (x - 1) ** 2 + 2 * (2 * y ** 2 - x) ** 2
grad = np.array([
2 * x - 2 - 4 * (2 * y ** 2 - x),
16 * (2 * y ** 2 - x) * y,
])
return obj, grad | Dixon-Price function |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.