code stringlengths 51 2.38k | docstring stringlengths 4 15.2k |
|---|---|
def get_items(self):
collection = JSONClientValidated('assessment',
collection='Item',
runtime=self._runtime)
result = collection.find(self._view_filter()).sort('_id', DESCENDING)
return objects.ItemList(result, ru... | Gets all ``Items``.
In plenary mode, the returned list contains all known items or
an error results. Otherwise, the returned list may contain only
those items that are accessible through this session.
return: (osid.assessment.ItemList) - a list of ``Items``
raise: OperationFai... |
def extract_bs(self, cutoff, ligcentroid, resis):
return [obres.GetIdx() for obres in resis if self.res_belongs_to_bs(obres, cutoff, ligcentroid)] | Return list of ids from residues belonging to the binding site |
def configuration(ctx):
t = [["Key", "Value"]]
for key in ctx.bitshares.config:
t.append([key, ctx.bitshares.config[key]])
print_table(t) | Show configuration variables |
def local_docker(context: Context):
output = io.StringIO()
with contextlib.redirect_stdout(output):
context.shell('docker-machine', 'ip', 'default')
host_machine_ip = output.getvalue().strip() or socket.gethostbyname(socket.gethostname())
args = ()
if context.verbosity > 1:
args += (... | Runs the app in a docker container; for local development only!
Once performed, `docker-compose up` can be used directly |
def parse(self, *args):
if isinstance(self.dictionary, dict):
return self.dictionary
raise self.subparserException("Argument passed to Dictionary SubParser is not a dict: %s" % type(self.dictionary)) | Return our initialized dictionary arguments. |
def InputAA(seq_length, name=None, **kwargs):
return Input((seq_length, len(AMINO_ACIDS)), name=name, **kwargs) | Input placeholder for array returned by `encodeAA`
Wrapper for: `keras.layers.Input((seq_length, 22), name=name, **kwargs)` |
def _reduction_output_shape(x, output_shape, reduced_dim):
if output_shape is None:
if reduced_dim is None:
return Shape([])
else:
if reduced_dim not in x.shape.dims:
raise ValueError(
"reduced_dim=%s not in x.shape.dims=%s" % (reduced_dim, x.shape))
return x.shape - redu... | Helper function to reduce_sum, etc. |
def set_global_defaults(**kwargs):
valid_options = [
'active', 'selected', 'disabled', 'on', 'off',
'on_active', 'on_selected', 'on_disabled',
'off_active', 'off_selected', 'off_disabled',
'color', 'color_on', 'color_off',
'color_active', 'color_selected', 'color_disabled',
... | Set global defaults for the options passed to the icon painter. |
def _iterate_rules(rules, topology, max_iter):
atoms = list(topology.atoms())
for _ in range(max_iter):
max_iter -= 1
found_something = False
for rule in rules.values():
for match_index in rule.find_matches(topology):
atom = atoms[match_index]
... | Iteratively run all the rules until the white- and backlists converge.
Parameters
----------
rules : dict
A dictionary mapping rule names (typically atomtype names) to
SMARTSGraphs that evaluate those rules.
topology : simtk.openmm.app.Topology
The topology that we are trying to... |
def coerce(self, value):
if not self.is_valid(value):
raise ex.SerializeException('{} is not a valid value for '
'type {}'.format(value, self.__class__.__name__))
return value | Subclasses should override this method for type coercion.
Default version will simply return the argument. If the argument
is not valid, a SerializeException is raised.
For primitives like booleans, ints, floats, and strings, use
this default version to avoid unintended type conversion... |
def upload_from_stream_with_id(self, file_id, filename, source,
chunk_size_bytes=None, metadata=None):
with self.open_upload_stream_with_id(
file_id, filename, chunk_size_bytes, metadata) as gin:
gin.write(source) | Uploads a user file to a GridFS bucket with a custom file id.
Reads the contents of the user file from `source` and uploads
it to the file `filename`. Source can be a string or file-like object.
For example::
my_db = MongoClient().test
fs = GridFSBucket(my_db)
fil... |
def start_parallel(self):
self.num_processes = get_num_processes()
self.task_queue = multiprocessing.Queue(maxsize=Q_MAX_SIZE)
self.result_queue = multiprocessing.Queue()
self.log_queue = multiprocessing.Queue()
self.complete = multiprocessing.Event()
args = (self.compute... | Initialize all queues and start the worker processes and the log
thread. |
def service_timeouts(cls):
timer_manager = cls._timers
while True:
next_end = timer_manager.service_timeouts()
sleep_time = max(next_end - time.time(), 0) if next_end else 10000
cls._new_timer.wait(sleep_time)
cls._new_timer.clear() | cls._timeout_watcher runs in this loop forever.
It is usually waiting for the next timeout on the cls._new_timer Event.
When new timers are added, that event is set so that the watcher can
wake up and possibly set an earlier timeout. |
def hasPESignature(self, rd):
rd.setOffset(0)
e_lfanew_offset = unpack("<L", rd.readAt(0x3c, 4))[0]
sign = rd.readAt(e_lfanew_offset, 2)
if sign == "PE":
return True
return False | Check for PE signature.
@type rd: L{ReadData}
@param rd: A L{ReadData} object.
@rtype: bool
@return: True is the given L{ReadData} stream has the PE signature. Otherwise, False. |
def interpret_expenditure_entry(entry):
try:
expenditure_amount = float(entry['ExpenditureAmount'])
entry['AmountsInterpreted'] = True
entry['ExpenditureAmount'] = expenditure_amount
except ValueError:
entry['AmountsInterpreted'] = False
try:
expenditure_date = parse_... | Interpret data fields within a CO-TRACER expediture report.
Interpret the expenditure amount, expenditure date, filed date, amended,
and amendment fields of the provided entry. All dates (expenditure and
filed) are interpreted together and, if any fails, all will retain their
original value. Likewise, ... |
def kill(self):
BaseShellOperator._close_process_input_stdin(self._batcmd.batch_to_file_s)
BaseShellOperator._wait_process(self._process, self._batcmd.sh_cmd, self._success_exitcodes)
BaseShellOperator._rm_process_input_tmpfiles(self._batcmd.batch_to_file_s)
self._process = None | Kill instantiated process
:raises: `AttributeError` if instantiated process doesn't seem to satisfy `constraints <relshell.daemon_shelloperator.DaemonShellOperator>`_ |
def multiply(x1, x2, output_shape=None, name=None):
if not isinstance(x2, Tensor):
return ScalarMultiplyOperation(x1, x2).outputs[0]
with tf.name_scope(name, default_name="mul"):
x1, x2 = binary_arguments_to_tensors(x1, x2)
return einsum(
[x1, x2],
output_shape=_infer_binary_broadcast_sh... | Binary multiplication with broadcasting.
Args:
x1: a Tensor
x2: a Tensor
output_shape: an optional Shape
name: an optional string
Returns:
a Tensor |
def dmrs(self):
dmrs = self.get('dmrs')
if dmrs is not None:
if isinstance(dmrs, dict):
dmrs = Dmrs.from_dict(dmrs)
return dmrs | Deserialize and return a Dmrs object for JSON-formatted DMRS
data; otherwise return the original string. |
def percentileOfSeries(requestContext, seriesList, n, interpolate=False):
if n <= 0:
raise ValueError(
'The requested percent is required to be greater than 0')
if not seriesList:
return []
name = 'percentileOfSeries(%s,%g)' % (seriesList[0].pathExpression, n)
start, end, ste... | percentileOfSeries returns a single series which is composed of the
n-percentile values taken across a wildcard series at each point.
Unless `interpolate` is set to True, percentile values are actual values
contained in one of the supplied series. |
def _set_time(self, time):
if len(self.time) == 0 :
self.time = np.array(time)
if self.h5 is not None:
self.h5.create_dataset('time', self.time.shape, dtype=self.time.dtype, data=self.time, compression="gzip", shuffle=True, scaleoffset=3)
else:
if(len(... | Set time in both class and hdf5 file |
def should_check_ciphersuites(self):
if isinstance(self.mykey, PrivKeyRSA):
kx = "RSA"
elif isinstance(self.mykey, PrivKeyECDSA):
kx = "ECDSA"
if get_usable_ciphersuites(self.cur_pkt.ciphers, kx):
return
raise self.NO_USABLE_CIPHERSUITE() | We extract cipher suites candidates from the client's proposition. |
def service_unavailable(cls, errors=None):
if cls.expose_status:
cls.response.content_type = 'application/json'
cls.response._status_line = '503 Service Unavailable'
return cls(503, None, errors).to_json | Shortcut API for HTTP 503 `Service Unavailable` response.
Args:
errors (list): Response key/value data.
Returns:
WSResponse Instance. |
def create_event(
title,
event_type,
description='',
start_time=None,
end_time=None,
note=None,
**rrule_params
):
if isinstance(event_type, tuple):
event_type, created = EventType.objects.get_or_create(
abbr=event_type[0],
label=event_type[1]
)
... | Convenience function to create an ``Event``, optionally create an
``EventType``, and associated ``Occurrence``s. ``Occurrence`` creation
rules match those for ``Event.add_occurrences``.
Returns the newly created ``Event`` instance.
Parameters
``event_type``
can be either an ``EventType`` ... |
def read(self, amt=None):
chunk = self._raw_stream.read(amt)
self._amount_read += len(chunk)
return chunk | Read at most amt bytes from the stream.
If the amt argument is omitted, read all data. |
def generate_trajs(P, M, N, start=None, stop=None, dt=1):
sampler = MarkovChainSampler(P, dt=dt)
return sampler.trajectories(M, N, start=start, stop=stop) | Generates multiple realizations of the Markov chain with transition matrix P.
Parameters
----------
P : (n, n) ndarray
transition matrix
M : int
number of trajectories
N : int
trajectory length
start : int, optional, default = None
starting state. If not given, w... |
def set(self, x, y, value):
self._double_buffer[y][x] = value | Set the cell value from the specified location
:param x: The column (x coord) of the character.
:param y: The row (y coord) of the character.
:param value: A 5-tuple of (unicode, foreground, attributes, background, width). |
def is_archive(self):
ns_prefix = self.archive_namespace
if ns_prefix:
if ns_prefix + '_archive' in self.feed.feed:
return True
if ns_prefix + '_current' in self.feed.feed:
return False
rels = collections.defaultdict(list)
for link ... | Given a parsed feed, returns True if this is an archive feed |
def contains(self, item):
check_not_none(item, "Value can't be None")
item_data = self._to_data(item)
return self._encode_invoke(set_contains_codec, value=item_data) | Determines whether this set contains the specified item or not.
:param item: (object), the specified item to be searched.
:return: (bool), ``true`` if the specified item exists in this set, ``false`` otherwise. |
def status(self, jobId=None, jobType=None):
params = {
"f" : "json"
}
if jobType is not None:
params['jobType'] = jobType
if jobId is not None:
params["jobId"] = jobId
url = "%s/status" % self.root
return self._get(url=url,
... | Inquire about status when publishing an item, adding an item in
async mode, or adding with a multipart upload. "Partial" is
available for Add Item Multipart, when only a part is uploaded
and the item is not committed.
Input:
jobType The type of asynchronous job... |
def unblock_all(self):
self.unblock()
for em in self._emitters.values():
em.unblock() | Unblock all emitters in this group. |
def is_imap(self, JPD):
if not isinstance(JPD, JointProbabilityDistribution):
raise TypeError("JPD must be an instance of JointProbabilityDistribution")
factors = [cpd.to_factor() for cpd in self.get_cpds()]
factor_prod = reduce(mul, factors)
JPD_fact = DiscreteFactor(JPD.var... | Checks whether the bayesian model is Imap of given JointProbabilityDistribution
Parameters
-----------
JPD : An instance of JointProbabilityDistribution Class, for which you want to
check the Imap
Returns
--------
boolean : True if bayesian model is Imap for... |
def load_template(name, directory, extension, encoding, encoding_errors):
abs_path = get_abs_template_path(name, directory, extension)
return load_file(abs_path, encoding, encoding_errors) | Load a template and return its contents as a unicode string. |
def _set_seed(self):
if self.flags['SEED'] is not None:
tf.set_random_seed(self.flags['SEED'])
np.random.seed(self.flags['SEED']) | Set random seed for numpy and tensorflow packages |
def restore(self, request):
self._connection.connection.rpush(self._request_key, pickle.dumps(request)) | Push the request back onto the queue.
Args:
request (Request): Reference to a request object that should be pushed back
onto the request queue. |
def emit_save_figure(self):
self.sig_save_figure.emit(self.canvas.fig, self.canvas.fmt) | Emit a signal when the toolbutton to save the figure is clicked. |
def dinfdistdown(np, ang, fel, slp, src, statsm, distm, edgecontamination, wg, dist,
workingdir=None, mpiexedir=None, exedir=None,
log_file=None, runtime_file=None, hostfile=None):
in_params = {'-m': '%s %s' % (TauDEM.convertstatsmethod(statsm),
... | Run D-inf distance down to stream |
def _generate_placeholder(readable_text=None):
name = '_interm_' + str(Cache._counter)
Cache._counter += 1
if readable_text is not None:
assert isinstance(readable_text, str)
name += '_' + readable_text
return name | Generate a placeholder name to use while updating WeldObject.
Parameters
----------
readable_text : str, optional
Appended to the name for a more understandable placeholder.
Returns
-------
str
Placeholder. |
def uuid_to_slug(uuid):
if not isinstance(uuid, int):
raise ArgumentError("Invalid id that is not an integer", id=uuid)
if uuid < 0 or uuid > 0x7fffffff:
raise ArgumentError("Integer should be a positive number and smaller than 0x7fffffff", id=uuid)
return '--'.join(['d', int64gid(uuid)]) | Return IOTile Cloud compatible Device Slug
:param uuid: UUID
:return: string in the form of d--0000-0000-0000-0001 |
def exception_to_github(github_obj_to_comment, summary=""):
context = ExceptionContext()
try:
yield context
except Exception:
if summary:
summary = ": ({})".format(summary)
error_type = "an unknown error"
try:
raise
except CalledProcessError as... | If any exception comes, log them in the given Github obj. |
def submit_action(self, ddata):
self._controller.post(ddata,
url=HOME_ENDPOINT,
referer=HOME_ENDPOINT) | Post data. |
def _write_buildproc_yaml(build_data, env, user, cmd, volumes, app_folder):
buildproc = ProcData({
'app_folder': str(app_folder),
'app_name': build_data.app_name,
'app_repo_url': '',
'app_repo_type': '',
'buildpack_url': '',
'buildpack_version': '',
'config_na... | Write a proc.yaml for the container and return the container path |
def getDefaultTMParams(self, inputSize, numInputBits):
sampleSize = int(1.5 * numInputBits)
if numInputBits == 20:
activationThreshold = 18
minThreshold = 18
elif numInputBits == 10:
activationThreshold = 8
minThreshold = 8
else:
activationThreshold = int(numInputBits * .6)... | Returns a good default set of parameters to use in the TM region. |
def Analyze(self, hashes):
if not self._api_key:
raise RuntimeError('No API key specified for VirusTotal lookup.')
hash_analyses = []
json_response = self._QueryHashes(hashes) or []
if isinstance(json_response, dict):
json_response = [json_response]
for result in json_response:
res... | Looks up hashes in VirusTotal using the VirusTotal HTTP API.
The API is documented here:
https://www.virustotal.com/en/documentation/public-api/
Args:
hashes (list[str]): hashes to look up.
Returns:
list[HashAnalysis]: analysis results.
Raises:
RuntimeError: If the VirusTotal... |
def header_check(self, content):
encode = None
m = RE_HTML_ENCODE.search(content)
if m:
enc = m.group(1).decode('ascii')
try:
codecs.getencoder(enc)
encode = enc
except LookupError:
pass
else:
... | Special HTML encoding check. |
def serialize(self):
pickle = super(ResourceParameter, self).serialize()
pickle['frequency'] = self.frequency
pickle['unit'] = self._unit.serialize()
return pickle | Convert the parameter into a dictionary.
:return: The parameter dictionary.
:rtype: dict |
def migrate(db, name, package, conf={}):
(current_major_version, current_minor_version) = get_version(db, name)
package = importlib.import_module(package)
logging.debug('Migration version for %s is %s.%s',
package.__name__,
current_major_version,
current... | Run all migrations that have not been run
Migrations will be run inside a transaction.
:param db: database connection object
:param name: name associated with the migrations
:param package: package that contains the migrations
:param conf: application con... |
def where_session_id(cls, session_id):
try:
session = cls.query.filter_by(session_id=session_id).one()
return session
except (NoResultFound, MultipleResultsFound):
return None | Easy way to query by session id |
def get_by_symbol(self, symbol: str) -> Commodity:
full_symbol = self.__parse_gc_symbol(symbol)
query = (
self.query
.filter(Commodity.mnemonic == full_symbol["mnemonic"])
)
if full_symbol["namespace"]:
query = query.filter(Commodity.namespace == full_... | Returns the commodity with the given symbol.
If more are found, an exception will be thrown. |
def _update_names(self):
d = dict(
table=self.table_name,
time=self.time,
space=self.space,
grain=self.grain,
variant=self.variant,
segment=self.segment
)
assert self.dataset
name = PartialPartitionName(**d).promote(... | Update the derived names |
def revoke_access_token(self, access_token):
payload = {'access_token': access_token,}
req = requests.post(settings.API_DEAUTHORIZATION_URL, data=payload) | Revokes the Access Token by accessing the De-authorization Endpoint
of Health Graph API.
@param access_token: Access Token for querying Health Graph API. |
def update(self, other):
if type(self) != type(other):
return NotImplemented
else:
if other.bad:
self.error = other.error
self.bad = True
self._fieldDict.update(other._fieldDict) | Adds all the tag-entry pairs from _other_ to the `Grant`. If there is a conflict _other_ takes precedence.
# Parameters
_other_ : `Grant`
> Another `Grant` of the same type as _self_ |
def GetEmail(prompt):
last_email_file_name = os.path.expanduser("~/.last_codereview_email_address")
last_email = ""
if os.path.exists(last_email_file_name):
try:
last_email_file = open(last_email_file_name, "r")
last_email = last_email_file.readline().strip("\n")
last_email_file.close()
prompt += " [%s... | Prompts the user for their email address and returns it.
The last used email address is saved to a file and offered up as a suggestion
to the user. If the user presses enter without typing in anything the last
used email address is used. If the user enters a new address, it is saved
for next time we prompt. |
def bgwrite(fileObj, data, closeWhenFinished=False, chainAfter=None, ioPrio=4):
thread = BackgroundWriteProcess(fileObj, data, closeWhenFinished, chainAfter, ioPrio)
thread.start()
return thread | bgwrite - Start a background writing process
@param fileObj <stream> - A stream backed by an fd
@param data <str/bytes/list> - The data to write. If a list is given, each successive element will be written to the fileObj and flushed. If a string/bytes is provided, it will be chunked accordi... |
def _list_files_in_path(path, pattern="*.stan"):
results = []
for dirname, subdirs, files in os.walk(path):
for name in files:
if fnmatch(name, pattern):
results.append(os.path.join(dirname, name))
return(results) | indexes a directory of stan files
returns as dictionary containing contents of files |
def _wrap_result(name, data, sparse_index, fill_value, dtype=None):
if name.startswith('__'):
name = name[2:-2]
if name in ('eq', 'ne', 'lt', 'gt', 'le', 'ge'):
dtype = np.bool
fill_value = lib.item_from_zerodim(fill_value)
if is_bool_dtype(dtype):
fill_value = bool(fill_value)
... | wrap op result to have correct dtype |
def path_exists(self, path, follow_symlinks=True):
"test if path exists"
return (
self.file_exists(path, follow_symlinks)
or self.symlink_exists(path, follow_symlinks)
or self.directory_exists(path, follow_symlinks)
) | test if path exists |
def get_books_for_schedule(self, schedule):
slns = self._get_slns(schedule)
books = {}
for sln in slns:
try:
section_books = self.get_books_by_quarter_sln(
schedule.term.quarter, sln
)
books[sln] = section_books
... | Returns a dictionary of data. SLNs are the keys, an array of Book
objects are the values. |
def detect_builtin_shadowing_definitions(self, contract):
result = []
for function in contract.functions:
if function.contract == contract:
if self.is_builtin_symbol(function.name):
result.append((self.SHADOWING_FUNCTION, function, None))
r... | Detects if functions, access modifiers, events, state variables, or local variables are named after built-in
symbols. Any such definitions are returned in a list.
Returns:
list of tuple: (type, definition, [local variable parent]) |
def reset(self):
self.rawdata = ''
self.lasttag = '???'
self.interesting = interesting_normal
self.cdata_elem = None
_markupbase.ParserBase.reset(self) | Reset this instance. Loses all unprocessed data. |
def parse(self, output):
output = self._get_lines_with_stems(output)
words = self._make_unique(output)
return self._parse_for_simple_stems(words) | Find stems for a given text. |
def doc(elt):
"Show `show_doc` info in preview window along with link to full docs."
global use_relative_links
use_relative_links = False
elt = getattr(elt, '__func__', elt)
md = show_doc(elt, markdown=False)
if is_fastai_class(elt):
md += f'\n\n<a href="{get_fn_link(elt)}" target="_blan... | Show `show_doc` info in preview window along with link to full docs. |
def _collapse(intervals):
span = None
for start, stop in intervals:
if span is None:
span = _Interval(start, stop)
elif start <= span.stop < stop:
span = _Interval(span.start, stop)
elif start > span.stop:
yield span
span = _Interval(start,... | Collapse an iterable of intervals sorted by start coord. |
def __search_ca_path(self):
if "X509_CERT_DIR" in os.environ:
self._ca_path = os.environ['X509_CERT_DIR']
elif os.path.exists('/etc/grid-security/certificates'):
self._ca_path = '/etc/grid-security/certificates'
else:
raise ClientAuthException("Could not find ... | Get CA Path to check the validity of the server host certificate on the client side |
def update(self, addr, raw_addr, name=None, rssi=None):
if addr in self._devices:
self._devices[addr].update(name, rssi)
return False
else:
self._devices[addr] = ScanResult(addr, raw_addr, name, rssi)
logger.debug('Scan result: {} / {}'.format(addr, name))... | Updates the collection of results with a newly received scan response.
Args:
addr (str): Device hardware address in xx:xx:xx:xx:xx:xx format.
raw_addr (bytearray): Device hardware address as raw bytes.
name (str): Device name (if available) as ASCII text. May be None.
... |
def writegroup(self, auth, entries, defer=False):
return self._call('writegroup', auth, [entries], defer) | Writes the given values for the respective resources in the list, all writes have same
timestamp.
Args:
auth: cik for authentication.
entries: List of key, value lists. eg. [[key, value], [k,v],,,] |
def moving_hfs_rank(h, size, start=0, stop=None):
windows = np.asarray(list(index_windows(h, size=size, start=start,
stop=stop, step=None)))
hr = np.zeros((windows.shape[0], h.shape[1]), dtype='i4')
for i, (window_start, window_stop) in enumerate(windows):
... | Helper function for plotting haplotype frequencies in moving windows.
Parameters
----------
h : array_like, int, shape (n_variants, n_haplotypes)
Haplotype array.
size : int
The window size (number of variants).
start : int, optional
The index at which to start.
stop : i... |
def change_subscription(self, topics):
if self._user_assignment:
raise IllegalStateError(self._SUBSCRIPTION_EXCEPTION_MESSAGE)
if isinstance(topics, six.string_types):
topics = [topics]
if self.subscription == set(topics):
log.warning("subscription unchanged b... | Change the topic subscription.
Arguments:
topics (list of str): topics for subscription
Raises:
IllegalStateErrror: if assign_from_user has been used already
TypeError: if a topic is None or a non-str
ValueError: if a topic is an empty string or
... |
def get_notebook_daemon_command(self, name, action, port=0, *extra):
return [self.python, self.cmd, action, self.get_pid(name), self.get_work_folder(name), port, self.kill_timeout] + list(extra) | Assume we launch Notebook with the same Python which executed us. |
def register(self):
log.info('Installing ssh key, %s' % self.name)
self.consul.create_ssh_pub_key(self.name, self.key) | Registers SSH key with provider. |
def _create_label(self, array):
if len(array.shape) == 3:
bands = array.shape[0]
lines = array.shape[1]
line_samples = array.shape[2]
else:
bands = 1
lines = array.shape[0]
line_samples = array.shape[1]
record_bytes = line_s... | Create sample PDS3 label for NumPy Array.
It is called by 'image.py' to create PDS3Image object
from Numpy Array.
Returns
-------
PVLModule label for the given NumPy array.
Usage: self.label = _create_label(array) |
def first_time_setup(self):
if not self._auto_unlock_key_position():
pw = password.create_passwords()[0]
attrs = {'application': self.keyring}
gkr.item_create_sync(self.default_keyring
,gkr.ITEM_GENERIC_SECRET
,... | First time running Open Sesame?
Create keyring and an auto-unlock key in default keyring. Make sure
these things don't already exist. |
def access_elementusers(self, elementuser_id, access_id=None, tenant_id=None, api_version="v2.0"):
if tenant_id is None and self._parent_class.tenant_id:
tenant_id = self._parent_class.tenant_id
elif not tenant_id:
raise TypeError("tenant_id is required but not set or cached.")
... | Get all accesses for a particular user
**Parameters:**:
- **elementuser_id**: Element User ID
- **access_id**: (optional) Access ID
- **tenant_id**: Tenant ID
- **api_version**: API version to use (default v2.0)
**Returns:** requests.Response object extended ... |
def removepage(self, page):
try:
self._api_entrypoint.removePage(self._session_token, page)
except XMLRPCError as e:
raise ConfluenceError('Failed to delete page: %s' % e) | Deletes a page from confluence.
raises ConfluenceError if the page could not be removed. |
def init_recorder(self, recorder_config):
if not recorder_config:
self.recorder = None
self.recorder_path = None
return
if isinstance(recorder_config, str):
recorder_coll = recorder_config
recorder_config = {}
else:
recorder... | Initialize the recording functionality of pywb. If recording_config is None this function is a no op |
def errorprint():
try:
yield
except ConfigurationError as e:
click.secho('%s' % e, err=True, fg='red')
sys.exit(1) | Print out descriptions from ConfigurationError. |
def prior_neighbor(C, alpha=0.001):
r
if isdense(C):
B = sparse.prior.prior_neighbor(csr_matrix(C), alpha=alpha)
return B.toarray()
else:
return sparse.prior.prior_neighbor(C, alpha=alpha) | r"""Neighbor prior for the given count matrix.
Parameters
----------
C : (M, M) ndarray or scipy.sparse matrix
Count matrix
alpha : float (optional)
Value of prior counts
Returns
-------
B : (M, M) ndarray or scipy.sparse matrix
Prior count matrix
Notes
---... |
def _get_decimal_digits(decimal_number_match, number_of_significant_digits):
assert 'e' not in decimal_number_match.group()
try:
num_of_digits = int(number_of_significant_digits)
except TypeError:
num_of_digits = DEFAULT_NUMBER_OF_SIGNIFICANT_DIGITS
if not decimal_number_match.group(GROU... | Returns the amount of decimal digits of the given regex match, considering the number of significant
digits for the provided column.
@param decimal_number_match: a regex match of a decimal number, resulting from REGEX_MEASURE.match(x).
@param number_of_significant_digits: the number of significant digits r... |
def modSymbolsFromLabelInfo(labelDescriptor):
modSymbols = set()
for labelStateEntry in viewvalues(labelDescriptor.labels):
for labelPositionEntry in viewvalues(labelStateEntry['aminoAcidLabels']):
for modSymbol in aux.toList(labelPositionEntry):
if modSymbol != '':
... | Returns a set of all modiciation symbols which were used in the
labelDescriptor
:param labelDescriptor: :class:`LabelDescriptor` describes the label setup
of an experiment
:returns: #TODO: docstring |
def reparse(self):
self._remove_all_children()
self._parse_context(self._context, self.orb) | Reparse all children of this directory.
This effectively rebuilds the tree below this node.
This operation takes an unbounded time to complete; if there are a lot
of objects registered below this directory's context, they will all
need to be parsed. |
def translate(obj, vec, **kwargs):
if not vec or not isinstance(vec, (tuple, list)):
raise GeomdlException("The input must be a list or a tuple")
if len(vec) != obj.dimension:
raise GeomdlException("The input vector must have " + str(obj.dimension) + " components")
inplace = kwargs.get('inpl... | Translates curves, surface or volumes by the input vector.
Keyword Arguments:
* ``inplace``: if False, operation applied to a copy of the object. *Default: False*
:param obj: input geometry
:type obj: abstract.SplineGeometry or multi.AbstractContainer
:param vec: translation vector
:type v... |
def lookup_subclass(cls, d):
try:
typeid = d["typeid"]
except KeyError:
raise FieldError("typeid not present in keys %s" % list(d))
subclass = cls._subcls_lookup.get(typeid, None)
if not subclass:
raise FieldError("'%s' not a valid typeid" % typeid)
... | Look up a class based on a serialized dictionary containing a typeid
Args:
d (dict): Dictionary with key "typeid"
Returns:
Serializable subclass |
def _set_status_self(self, key=JobDetails.topkey, status=JobStatus.unknown):
fullkey = JobDetails.make_fullkey(self.full_linkname, key)
if fullkey in self.jobs:
self.jobs[fullkey].status = status
if self._job_archive:
self._job_archive.register_job(self.jobs[fullk... | Set the status of this job, both in self.jobs and
in the `JobArchive` if it is present. |
def add_note(note, **kwargs):
note_i = Note()
note_i.ref_key = note.ref_key
note_i.set_ref(note.ref_key, note.ref_id)
note_i.value = note.value
note_i.created_by = kwargs.get('user_id')
db.DBSession.add(note_i)
db.DBSession.flush()
return note_i | Add a new note |
def has_property(obj, name):
if obj == None or name == None:
return False
names = name.split(".")
if names == None or len(names) == 0:
return False
return RecursiveObjectReader._perform_has_property(obj, names, 0) | Checks recursively if object or its subobjects has a property with specified name.
The object can be a user defined object, map or array.
The property name correspondently must be object property, map key or array index.
:param obj: an object to introspect.
:param name: a name of the ... |
def get_namespace_and_tag(name):
if isinstance(name, str):
if name[0] == "{":
uri, ignore, tag = name[1:].partition("}")
else:
uri = None
tag = name
else:
uri = None
tag = None
return uri, tag | Separates the namespace and tag from an element.
:param str name: Tag.
:returns: Namespace URI and Tag namespace.
:rtype: tuple |
def get_credits_by_section_and_regid(section, regid):
deprecation("Use get_credits_by_reg_url")
url = "{}{},{},{},{},{},{},.json".format(
reg_credits_url_prefix,
section.term.year,
section.term.quarter,
re.sub(' ', '%20', section.curriculum_abbr),
section.course_number,
... | Returns a uw_sws.models.Registration object
for the section and regid passed in. |
def destroyManager(self, force=False):
if self.getManager(force=force) is not None:
key = self.getSessionKey()
del self.session[key] | Delete any YadisServiceManager with this starting URL and
suffix from the session.
If there is no service manager or the service manager is for a
different URL, it silently does nothing.
@param force: True if the manager should be deleted regardless
of whether it's a manager fo... |
def thin_samples_for_writing(fp, samples, parameters, last_iteration):
if fp.thinned_by > 1:
if last_iteration is None:
raise ValueError("File's thinned_by attribute is > 1 ({}), "
"but last_iteration not provided."
.format(fp.thinned_by)... | Thins samples for writing to disk.
The thinning interval to use is determined by the given file handler's
``thinned_by`` attribute. If that attribute is 1, just returns the samples.
Parameters
----------
fp : MCMCMetadataIO instance
The file the sampels will be written to. Needed to determ... |
def _parse_shape(self, space):
if isinstance(space, gym.spaces.Discrete):
return ()
if isinstance(space, gym.spaces.Box):
return space.shape
raise NotImplementedError() | Get a tensor shape from a OpenAI Gym space.
Args:
space: Gym space.
Raises:
NotImplementedError: For spaces other than Box and Discrete.
Returns:
Shape tuple. |
def cublasSgbmv(handle, trans, m, n, kl, ku, alpha, A, lda,
x, incx, beta, y, incy):
status = _libcublas.cublasSgbmv_v2(handle,
trans, m, n, kl, ku,
ctypes.byref(ctypes.c_float(alpha)),
... | Matrix-vector product for real general banded matrix. |
def setup(self, redis_conn=None, host='localhost', port=6379):
if redis_conn is None:
if host is not None and port is not None:
self.redis_conn = redis.Redis(host=host, port=port)
else:
raise Exception("Please specify some form of connection "
... | Set up the redis connection |
def fromfilenames(cls, filenames, coltype=LIGOTimeGPS):
cache = cls()
for filename in filenames:
cache.extend(cls.fromfile(open(filename), coltype=coltype))
return cache | Read Cache objects from the files named and concatenate the results into a
single Cache. |
def _get_dvportgroup_dict(pg_ref):
props = salt.utils.vmware.get_properties_of_managed_object(
pg_ref, ['name', 'config.description', 'config.numPorts',
'config.type', 'config.defaultPortConfig'])
pg_dict = {'name': props['name'],
'description': props.get('config.descript... | Returns a dictionary with a distributed virutal portgroup data
pg_ref
Portgroup reference |
def show_customer(self, customer_id):
request = self._get('customers/' + str(customer_id))
return self.responder(request) | Shows an existing customer. |
def _build_layout(self):
" Rebuild a new Container object and return that. "
logger.info('Rebuilding layout.')
if not self.pymux.arrangement.windows:
return Window()
active_window = self.pymux.arrangement.get_active_window()
if active_window.zoom:
return t... | Rebuild a new Container object and return that. |
def to_cli_filter(bool_or_filter):
if not isinstance(bool_or_filter, (bool, CLIFilter)):
raise TypeError('Expecting a bool or a CLIFilter instance. Got %r' % bool_or_filter)
return {
True: _always,
False: _never,
}.get(bool_or_filter, bool_or_filter) | Accept both booleans and CLIFilters as input and
turn it into a CLIFilter. |
def equals(df1, df2, ignore_order=set(), ignore_indices=set(), all_close=False, _return_reason=False):
result = _equals(df1, df2, ignore_order, ignore_indices, all_close)
if _return_reason:
return result
else:
return result[0] | Get whether 2 data frames are equal.
``NaN`` is considered equal to ``NaN`` and `None`.
Parameters
----------
df1 : ~pandas.DataFrame
Data frame to compare.
df2 : ~pandas.DataFrame
Data frame to compare.
ignore_order : ~typing.Set[int]
Axi in which to ignore order.
... |
def parse(timestring):
for parser in _PARSERS:
match = parser['pattern'].match(timestring)
if match:
groups = match.groups()
ints = tuple(map(int, groups))
time = parser['factory'](ints)
return time
raise TimeError('Unsupported time format {}'.form... | Convert a statbank time string to a python datetime object. |
def app0(self):
for m in self._markers:
if m.marker_code == JPEG_MARKER_CODE.APP0:
return m
raise KeyError('no APP0 marker in image') | First APP0 marker in image markers. |
def purge_old_user_tasks():
limit = now() - settings.USER_TASKS_MAX_AGE
UserTaskStatus.objects.filter(created__lt=limit).delete() | Delete any UserTaskStatus and UserTaskArtifact records older than ``settings.USER_TASKS_MAX_AGE``.
Intended to be run as a scheduled task. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.