code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def put_object(self, cont, obj, local_file):
'''
Upload a file to Swift
'''
try:
with salt.utils.files.fopen(local_file, 'rb') as fp_:
self.conn.put_object(cont, obj, fp_)
return True
except Exception as exc:
log.error('There wa... | Upload a file to Swift |
def _match_serializers_by_query_arg(self, serializers):
"""Match serializer by query arg."""
# if the format query argument is present, match the serializer
arg_name = current_app.config.get('REST_MIMETYPE_QUERY_ARG_NAME')
if arg_name:
arg_value = request.args.get(arg_name, N... | Match serializer by query arg. |
def reset_to_flows(self, force=False, _meta=None):
""" Keeps only the absolute values.
This removes all attributes which can not be aggregated and must be
recalculated after the aggregation.
Parameters
----------
force: boolean, optional
If True, reset to f... | Keeps only the absolute values.
This removes all attributes which can not be aggregated and must be
recalculated after the aggregation.
Parameters
----------
force: boolean, optional
If True, reset to flows although the system can not be
recalculated. D... |
def import_all(path):
"""Import all polygons from a .poly file.
Returns a list of the imported polygon filters
"""
plist = []
fid = 0
while True:
try:
p = PolygonFilter(filename=path, fileid=fid)
plist.append(p)
... | Import all polygons from a .poly file.
Returns a list of the imported polygon filters |
def dispatch_event(self, event):
"""
Takes an event dict. Logs the event if needed and cleans up the dict
such as setting the index needed for composits.
"""
if self.config["debug"]:
self.py3_wrapper.log("received event {}".format(event))
# usage variables
... | Takes an event dict. Logs the event if needed and cleans up the dict
such as setting the index needed for composits. |
def GetKernelParams(time, flux, errors, kernel='Basic', mask=[],
giter=3, gmaxf=200, guess=None):
'''
Optimizes the GP by training it on the current de-trended light curve.
Returns the white noise amplitude, red noise amplitude,
and red noise timescale.
:param array_like time: T... | Optimizes the GP by training it on the current de-trended light curve.
Returns the white noise amplitude, red noise amplitude,
and red noise timescale.
:param array_like time: The time array
:param array_like flux: The flux array
:param array_like errors: The flux errors array
:param array_like... |
def _is_attribute_property(name, klass):
""" Check if the given attribute *name* is a property
in the given *klass*.
It will look for `property` calls or for functions
with the given name, decorated by `property` or `property`
subclasses.
Returns ``True`` if the name is a property in the given ... | Check if the given attribute *name* is a property
in the given *klass*.
It will look for `property` calls or for functions
with the given name, decorated by `property` or `property`
subclasses.
Returns ``True`` if the name is a property in the given klass,
``False`` otherwise. |
def make_input(self):
"""Construct and write the input file of the calculation."""
# Set the file paths.
all_files ={"ddkfile_" + str(n + 1): ddk for n, ddk in enumerate(self.ddk_filepaths)}
all_files.update({"wfkfile": self.wfk_filepath})
files_nml = {"FILES": all_files}
... | Construct and write the input file of the calculation. |
def _GetNormalizedTimestamp(self):
"""Retrieves the normalized timestamp.
Returns:
decimal.Decimal: normalized timestamp, which contains the number of
seconds since January 1, 1970 00:00:00 and a fraction of second used
for increased precision, or None if the normalized timestamp cann... | Retrieves the normalized timestamp.
Returns:
decimal.Decimal: normalized timestamp, which contains the number of
seconds since January 1, 1970 00:00:00 and a fraction of second used
for increased precision, or None if the normalized timestamp cannot be
determined. |
def trace_walker(module):
"""
Defines a generator used to walk into modules.
:param module: Module to walk.
:type module: ModuleType
:return: Class / Function / Method.
:rtype: object or object
"""
for name, function in inspect.getmembers(module, inspect.isfunction):
yield None... | Defines a generator used to walk into modules.
:param module: Module to walk.
:type module: ModuleType
:return: Class / Function / Method.
:rtype: object or object |
def get_activations(self):
"""Return a list of activations."""
res = (self.added, self.removed)
self.added = set()
self.removed = set()
return res | Return a list of activations. |
def groups(self):
"""Component groups
Special property which point to a :class:`~pylls.cachet.ComponentGroups`
instance for convenience. This instance is initialized on first call.
"""
if not self._groups:
self._groups = ComponentGroups(self.api_client)
retur... | Component groups
Special property which point to a :class:`~pylls.cachet.ComponentGroups`
instance for convenience. This instance is initialized on first call. |
def read_requirements(path,
strict_bounds,
conda_format=False,
filter_names=None):
"""
Read a requirements.txt file, expressed as a path relative to Zipline root.
Returns requirements with the pinned versions as lower bounds
if `strict_b... | Read a requirements.txt file, expressed as a path relative to Zipline root.
Returns requirements with the pinned versions as lower bounds
if `strict_bounds` is falsey. |
def write(self, data, waitForResponse=True, timeout=5, parseError=True, writeTerm='\r', expectedResponseTermSeq=None):
""" Write data to the modem.
This method adds the ``\\r\\n`` end-of-line sequence to the data parameter, and
writes it to the modem.
:param data: Command/data to be wr... | Write data to the modem.
This method adds the ``\\r\\n`` end-of-line sequence to the data parameter, and
writes it to the modem.
:param data: Command/data to be written to the modem
:type data: str
:param waitForResponse: Whether this method should block and return the response... |
def count(self):
"""Summary
Returns:
TYPE: Description
"""
return LazyOpResult(
grizzly_impl.count(
self.expr,
self.weld_type
),
WeldInt(),
0
) | Summary
Returns:
TYPE: Description |
def _connect_control(self, event, param, arg):
"""
Is the actual callback function for :meth:`init_hw_connect_control_ex`.
:param event:
Event (:data:`CbEvent.EVENT_CONNECT`, :data:`CbEvent.EVENT_DISCONNECT` or
:data:`CbEvent.EVENT_FATALDISCON`).
:param param: Ad... | Is the actual callback function for :meth:`init_hw_connect_control_ex`.
:param event:
Event (:data:`CbEvent.EVENT_CONNECT`, :data:`CbEvent.EVENT_DISCONNECT` or
:data:`CbEvent.EVENT_FATALDISCON`).
:param param: Additional parameter depending on the event.
- CbEvent.EVENT_... |
def get_path_regex(self, path):
""" Evaluate the registered path-alias regular expressions """
for regex, func in self._regex_map:
match = re.match(regex, path)
if match:
return func(match)
return None, None | Evaluate the registered path-alias regular expressions |
def get_previous_request(rid):
"""Return the last ceph broker request sent on a given relation
@param rid: Relation id to query for request
"""
request = None
broker_req = relation_get(attribute='broker_req', rid=rid,
unit=local_unit())
if broker_req:
reque... | Return the last ceph broker request sent on a given relation
@param rid: Relation id to query for request |
def execute(self, arg_list):
"""Main function to parse and dispatch commands by given ``arg_list``
:param arg_list: all arguments provided by the command line
:param type: list
"""
arg_map = self.parser.parse_args(arg_list).__dict__
command = arg_map.pop(self._COMMAND_F... | Main function to parse and dispatch commands by given ``arg_list``
:param arg_list: all arguments provided by the command line
:param type: list |
def class_config_section(cls):
"""Get the config class config section"""
def c(s):
"""return a commented, wrapped block."""
s = '\n\n'.join(wrap_paragraphs(s, 78))
return '# ' + s.replace('\n', '\n# ')
# section header
breaker = '#' + '-'*78
... | Get the config class config section |
def get_all_entity_type_saved_searches(self, entitytype, **kwargs): # noqa: E501
"""Get all saved searches for a specific entity type for a user # noqa: E501
# noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async... | Get all saved searches for a specific entity type for a user # noqa: E501
# noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_all_entity_type_saved_searches(entitytype, async_req=T... |
def descendants(self, node):
""" Returns a :class:`QuerySet` with all descendants for a given
:class:`CTENode` `node`.
:param node: the :class:`CTENode` whose descendants are required.
:returns: A :class:`QuerySet` with all descendants of the given
`node`.
... | Returns a :class:`QuerySet` with all descendants for a given
:class:`CTENode` `node`.
:param node: the :class:`CTENode` whose descendants are required.
:returns: A :class:`QuerySet` with all descendants of the given
`node`. |
def patch_object(obj, attr, value):
"""
Context manager that temporarily patches an object *obj* by replacing its attribute *attr* with
*value*. The original value is set again when the context is closed.
"""
orig = getattr(obj, attr, no_value)
try:
setattr(obj, attr, value)
yi... | Context manager that temporarily patches an object *obj* by replacing its attribute *attr* with
*value*. The original value is set again when the context is closed. |
def load_mnist_dataset(mode='supervised', one_hot=True):
"""Load the MNIST handwritten digits dataset.
:param mode: 'supervised' or 'unsupervised' mode
:param one_hot: whether to get one hot encoded labels
:return: train, validation, test data:
for (X, y) if 'supervised',
for (X... | Load the MNIST handwritten digits dataset.
:param mode: 'supervised' or 'unsupervised' mode
:param one_hot: whether to get one hot encoded labels
:return: train, validation, test data:
for (X, y) if 'supervised',
for (X) if 'unsupervised' |
def open(self, using=None, **kwargs):
"""
Opens the index in elasticsearch.
Any additional keyword arguments will be passed to
``Elasticsearch.indices.open`` unchanged.
"""
return self._get_connection(using).indices.open(index=self._name, **kwargs) | Opens the index in elasticsearch.
Any additional keyword arguments will be passed to
``Elasticsearch.indices.open`` unchanged. |
def x10_all_lights_off(self, housecode):
"""Send the X10 All Lights Off command."""
msg = X10Send.command_msg(housecode, X10_COMMAND_ALL_LIGHTS_OFF)
self.send_msg(msg)
self._x10_command_to_device(housecode, X10_COMMAND_ALL_LIGHTS_OFF, msg) | Send the X10 All Lights Off command. |
def seek_end(fileobj, offset):
"""Like fileobj.seek(-offset, 2), but will not try to go beyond the start
Needed since file objects from BytesIO will not raise IOError and
file objects from open() will raise IOError if going to a negative offset.
To make things easier for custom implementations, instead... | Like fileobj.seek(-offset, 2), but will not try to go beyond the start
Needed since file objects from BytesIO will not raise IOError and
file objects from open() will raise IOError if going to a negative offset.
To make things easier for custom implementations, instead of allowing
both behaviors, we ju... |
def set_querier_mode(self, dpid, server_port):
"""set the datapath to work as a querier. note that you can set
up only the one querier. when you called this method several
times, only the last one becomes effective."""
self.dpid = dpid
self.server_port = server_port
if se... | set the datapath to work as a querier. note that you can set
up only the one querier. when you called this method several
times, only the last one becomes effective. |
def file_mtime(file_path):
"""
Returns the file modified time. This is with regards to the last
modification the file has had in the droopescan repo, rather than actual
file modification time in the filesystem.
@param file_path: file path relative to the executable.
@return datetime.datetime obj... | Returns the file modified time. This is with regards to the last
modification the file has had in the droopescan repo, rather than actual
file modification time in the filesystem.
@param file_path: file path relative to the executable.
@return datetime.datetime object. |
def async_batch_annotate_files(
self,
requests,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Run asynchronous image detection and annotation for a list of generic
files, such as P... | Run asynchronous image detection and annotation for a list of generic
files, such as PDF files, which may contain multiple pages and multiple
images per page. Progress and results can be retrieved through the
``google.longrunning.Operations`` interface. ``Operation.metadata``
contains ``... |
def set_index(self, index):
"""Display the data of the given index
:param index: the index to paint
:type index: QtCore.QModelIndex
:returns: None
:rtype: None
:raises: None
"""
item = index.internalPointer()
note = item.internal_data()
se... | Display the data of the given index
:param index: the index to paint
:type index: QtCore.QModelIndex
:returns: None
:rtype: None
:raises: None |
def addField(self, field) :
"""add a filed to the legend"""
if field.lower() in self.legend :
raise ValueError("%s is already in the legend" % field.lower())
self.legend[field.lower()] = len(self.legend)
if len(self.strLegend) > 0 :
self.strLegend += self.separator + field
else :
self.strLegend += f... | add a filed to the legend |
def get_log_level(args):
# type: (typing.Dict[str, typing.Any]) -> int
"""Get the log level from the CLI arguments.
Removes logging arguments from sys.argv.
Args:
args: The parsed docopt arguments to be used to determine the logging
level.
Returns:
The correct log leve... | Get the log level from the CLI arguments.
Removes logging arguments from sys.argv.
Args:
args: The parsed docopt arguments to be used to determine the logging
level.
Returns:
The correct log level based on the three CLI arguments given.
Raises:
ValueError: Raised ... |
def _init_metadata(self):
"""stub"""
TextAnswerFormRecord._init_metadata(self)
FilesAnswerFormRecord._init_metadata(self)
super(AnswerTextAndFilesMixin, self)._init_metadata() | stub |
def register_class(self, class_type, component_scope=scope.InstancePerDependency, register_as=None):
"""
Registers the given class for creation via its constructor.
:param class_type: The class type.
:param component_scope: The scope of the component, defaults to instance per dependency.... | Registers the given class for creation via its constructor.
:param class_type: The class type.
:param component_scope: The scope of the component, defaults to instance per dependency.
:param register_as: The types to register the class as, defaults to the given class_type. |
def login(request, template_name='registration/login.html',
redirect_field_name=REDIRECT_FIELD_NAME,
authentication_form=AuthenticationForm,
current_app=None, extra_context=None):
"""
Displays the login form and handles the login action.
"""
redirect_to = request.POST.get(r... | Displays the login form and handles the login action. |
def prepare_static_data(self, data):
"""
If user defined static fields, then process them with visiable value
"""
d = data.copy()
for f in self.get_fields():
if f['static'] and f['name'] in d:
d[f['name']] = make_view_field(f, None, self.types_c... | If user defined static fields, then process them with visiable value |
def GET_namespace_info( self, path_info, namespace_id ):
"""
Look up a namespace's info
Reply information about a namespace
Reply 404 if the namespace doesn't exist
Reply 502 for any error in talking to the blocksatck server
"""
if not check_namespace(namespace_id... | Look up a namespace's info
Reply information about a namespace
Reply 404 if the namespace doesn't exist
Reply 502 for any error in talking to the blocksatck server |
def _parse_bool(value):
"""Convert ``string`` or ``bool`` to ``bool``."""
if isinstance(value, bool):
return value
elif isinstance(value, str):
if value == 'True':
return True
elif value == 'False':
return False
raise Exception("Value %s is not boolean."... | Convert ``string`` or ``bool`` to ``bool``. |
def remove(self):
"""Remove or delete the specified object from slick. You specify which one you want by providing the id as
a parameter to the parent object, using it as a function. Example:
slick.projects("4fd8cd95e4b0ee7ba54b9885").remove()
"""
url = self.getUrl()
#... | Remove or delete the specified object from slick. You specify which one you want by providing the id as
a parameter to the parent object, using it as a function. Example:
slick.projects("4fd8cd95e4b0ee7ba54b9885").remove() |
def text_remove_empty_lines(text):
"""
Whitespace normalization:
- Strip empty lines
- Strip trailing whitespace
"""
lines = [ line.rstrip() for line in text.splitlines() if line.strip() ]
return "\n".join(lines) | Whitespace normalization:
- Strip empty lines
- Strip trailing whitespace |
def can_infect(self, event):
"""
Whether the spreading stop can infect using this event.
"""
if event.from_stop_I != self.stop_I:
return False
if not self.has_been_visited():
return False
else:
time_sep = event.dep_time_ut-self.get_min... | Whether the spreading stop can infect using this event. |
def rank2d(X, y=None, ax=None, algorithm='pearson', features=None,
show_feature_names=True, colormap='RdBu_r', **kwargs):
"""Displays pairwise comparisons of features with the algorithm and ranks
them in a lower-left triangle heatmap plot.
This helper function is a quick wrapper to utilize the R... | Displays pairwise comparisons of features with the algorithm and ranks
them in a lower-left triangle heatmap plot.
This helper function is a quick wrapper to utilize the Rank2D Visualizer
(Transformer) for one-off analysis.
Parameters
----------
X : ndarray or DataFrame of shape n x m
... |
def is_ternary(self, keyword):
"""return true if the given keyword is a ternary keyword
for this ControlLine"""
return keyword in {
'if':set(['else', 'elif']),
'try':set(['except', 'finally']),
'for':set(['else'])
}.get(self.keyword, []) | return true if the given keyword is a ternary keyword
for this ControlLine |
def get_cust_cols(path):
"""
Load custom column definitions.
"""
required_keys = ["title", "id", "sType", "visible"]
with open(path, 'r') as f:
try:
cust_cols = ast.literal_eval(f.read())
except Exception as err:
sys.stderr.write("Invalid custom columns file:... | Load custom column definitions. |
def preprocess(self, image, image_format):
"""
Preprocess an image.
An API hook for image pre-processing. Calls any image format specific
pre-processors (if defined). I.E. If `image_format` is 'JPEG', this
method will look for a method named `preprocess_JPEG`, if found
`... | Preprocess an image.
An API hook for image pre-processing. Calls any image format specific
pre-processors (if defined). I.E. If `image_format` is 'JPEG', this
method will look for a method named `preprocess_JPEG`, if found
`image` will be passed to it.
Arguments:
* ... |
def debug_shell(user_ns, user_global_ns, traceback=None, execWrapper=None):
"""
Spawns some interactive shell. Tries to use IPython if available.
Falls back to :func:`pdb.post_mortem` or :func:`simple_debug_shell`.
:param dict[str] user_ns:
:param dict[str] user_global_ns:
:param traceback:
... | Spawns some interactive shell. Tries to use IPython if available.
Falls back to :func:`pdb.post_mortem` or :func:`simple_debug_shell`.
:param dict[str] user_ns:
:param dict[str] user_global_ns:
:param traceback:
:param execWrapper:
:return: nothing |
def from_gaussian_draw(cls,pst,cov,num_reals=1,use_homegrown=True,group_chunks=False,
fill_fixed=True,enforce_bounds=False):
""" instantiate a parameter ensemble from a covariance matrix
Parameters
----------
pst : pyemu.Pst
a control file instance... | instantiate a parameter ensemble from a covariance matrix
Parameters
----------
pst : pyemu.Pst
a control file instance
cov : (pyemu.Cov)
covariance matrix to use for drawing
num_reals : int
number of realizations to generate
use_homeg... |
def limits(self,x1,x2,y1,y2):
"""Set the coordinate boundaries of plot"""
import math
self.x1=x1
self.x2=x2
self.y1=y1
self.y2=y2
self.xscale=(self.cx2-self.cx1)/(self.x2-self.x1)
self.yscale=(self.cy2-self.cy1)/(self.y2-self.y1)
ra1=self.x1
ra2=self.x2... | Set the coordinate boundaries of plot |
def neighbors(self, subid, params=None):
''' v1/server/neighbors
GET - account
Determine what other subscriptions are hosted on the same physical
host as a given subscription.
Link: https://www.vultr.com/api/#server_neighbors
'''
params = update_params(params, {'... | v1/server/neighbors
GET - account
Determine what other subscriptions are hosted on the same physical
host as a given subscription.
Link: https://www.vultr.com/api/#server_neighbors |
def column_lists_equal(a: List[Column], b: List[Column]) -> bool:
"""
Are all columns in list ``a`` equal to their counterparts in list ``b``,
as per :func:`columns_equal`?
"""
n = len(a)
if len(b) != n:
return False
for i in range(n):
if not columns_equal(a[i], b[i]):
... | Are all columns in list ``a`` equal to their counterparts in list ``b``,
as per :func:`columns_equal`? |
def parse(self, node):
"""
Return generator yielding Field objects for a given node
"""
self._attrs = {}
vals = []
yielded = False
for x in self._read_parts(node):
if isinstance(x, Field):
yielded = True
x.attrs = self.... | Return generator yielding Field objects for a given node |
def activatewindow(self, window_name):
"""
Activate window.
@param window_name: Window name to look for, either full name,
LDTP's name convention, or a Unix glob.
@type window_name: string
@return: 1 on success.
@rtype: integer
"""
window_handle ... | Activate window.
@param window_name: Window name to look for, either full name,
LDTP's name convention, or a Unix glob.
@type window_name: string
@return: 1 on success.
@rtype: integer |
def _listen_inbox_messages(self):
"""Start listening to messages, using a separate thread."""
# Collect messages in a queue
inbox_queue = Queue(maxsize=self._n_jobs * 4)
threads = [] # type: List[BotQueueWorker]
try:
# Create n_jobs inbox threads
for i ... | Start listening to messages, using a separate thread. |
def parse(self, text, noprefix=False):
"""Parse date and time from given date string.
:param text:
Any human readable string
:type date_string: str|unicode
:param noprefix:
If set True than doesn't use prefix based date patterns filtering settings
:type n... | Parse date and time from given date string.
:param text:
Any human readable string
:type date_string: str|unicode
:param noprefix:
If set True than doesn't use prefix based date patterns filtering settings
:type noprefix: bool
:return: Returns :class:`d... |
def vlan_classifier_group_groupid(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
vlan = ET.SubElement(config, "vlan", xmlns="urn:brocade.com:mgmt:brocade-vlan")
classifier = ET.SubElement(vlan, "classifier")
group = ET.SubElement(classifier, "gr... | Auto Generated Code |
def get_message(self, id):
"""
Return a Message object for given id.
:param id: The id of the message object to return.
"""
url = self._base_url + "/3/message/{0}".format(id)
resp = self._send_request(url)
return Message(resp, self) | Return a Message object for given id.
:param id: The id of the message object to return. |
def select_from_array(cls, array, identifier):
"""Return a region from a numpy array.
:param array: :class:`numpy.ndarray`
:param identifier: value representing the region to select in the array
:returns: :class:`jicimagelib.region.Region`
"""
base_array = np.ze... | Return a region from a numpy array.
:param array: :class:`numpy.ndarray`
:param identifier: value representing the region to select in the array
:returns: :class:`jicimagelib.region.Region` |
def online(note, github_repository, github_username):
"""Upload the repository to GitHub and enable testing on Travis CI."""
callbacks.git_installed()
try:
repo = git.Repo()
except git.InvalidGitRepositoryError:
LOGGER.critical(
"'memote online' requires a git repository in o... | Upload the repository to GitHub and enable testing on Travis CI. |
def until_state(self, state, timeout=None):
"""Return a tornado Future that will resolve when the requested state is set"""
if state not in self._valid_states:
raise ValueError('State must be one of {0}, not {1}'
.format(self._valid_states, state))
if sta... | Return a tornado Future that will resolve when the requested state is set |
def search(context, keywords, module, raw, kind):
"""Query Windows identifiers and locations.
Windows database must be prepared before using this.
"""
logging.info(_('Entering search mode'))
sense = context.obj['sense']
func = sense.query_names if module else sense.query_info
none = True
... | Query Windows identifiers and locations.
Windows database must be prepared before using this. |
def run_executable(repo, args, includes):
"""
Run the executable and capture the input and output...
"""
# Get platform information
mgr = plugins_get_mgr()
repomgr = mgr.get(what='instrumentation', name='platform')
platform_metadata = repomgr.get_metadata()
print("Obtaining Commit Info... | Run the executable and capture the input and output... |
def _get_video_id(self, url=None):
"""
Extract video id. It will try to avoid making an HTTP request
if it can find the ID in the URL, but otherwise it will try
to scrape it from the HTML document. Returns None in case it's
unable to extract the ID at all.
"""
if ... | Extract video id. It will try to avoid making an HTTP request
if it can find the ID in the URL, but otherwise it will try
to scrape it from the HTML document. Returns None in case it's
unable to extract the ID at all. |
def _apply_decorator_to_methods(cls, decorator):
"""
This helper can apply a given decorator to all methods on the current
Resource.
NOTE: In contrast to ``Resource.method_decorators``, which has a
similar use-case, this method applies decorators directly and override
me... | This helper can apply a given decorator to all methods on the current
Resource.
NOTE: In contrast to ``Resource.method_decorators``, which has a
similar use-case, this method applies decorators directly and override
methods in-place, while the decorators listed in
``Resource.met... |
def _get_handler_set(cls, request, fail_enum, header_proto=None):
"""Goes through the list of ClientSortControls and returns a list of
unique _ValueHandlers. Maintains order, but drops ClientSortControls
that have already appeared to help prevent spamming.
"""
added = set()
... | Goes through the list of ClientSortControls and returns a list of
unique _ValueHandlers. Maintains order, but drops ClientSortControls
that have already appeared to help prevent spamming. |
def save_to_cache(dxobject):
'''
:param dxobject: a dxpy object handler for an object to save to the cache
:raises: :exc:`~dxpy.exceptions.DXError` if this is called with dxpy.JOB_ID not set, or if "DX_PROJECT_CACHE_ID" is not found in the environment variables
Clones the given object to the project ca... | :param dxobject: a dxpy object handler for an object to save to the cache
:raises: :exc:`~dxpy.exceptions.DXError` if this is called with dxpy.JOB_ID not set, or if "DX_PROJECT_CACHE_ID" is not found in the environment variables
Clones the given object to the project cache.
Example::
@dxpy.entry_... |
def get_submission(self, submissionid, user_check=True):
""" Get a submission from the database """
sub = self._database.submissions.find_one({'_id': ObjectId(submissionid)})
if user_check and not self.user_is_submission_owner(sub):
return None
return sub | Get a submission from the database |
def before(self, callback: Union[Callable, str]) -> "Control":
"""Register a control method that reacts before the trigger method is called.
Parameters:
callback:
The control method. If given as a callable, then that function will be
used as the callback. If ... | Register a control method that reacts before the trigger method is called.
Parameters:
callback:
The control method. If given as a callable, then that function will be
used as the callback. If given as a string, then the control will look
up a method ... |
def print_graph(self, format=None, output=sys.stdout, depth=0, **kwargs):
"""
Print the graph for self's nodes.
Args:
format (str): output format (csv, json or text).
output (file): file descriptor on which to write.
depth (int): depth of the graph.
"... | Print the graph for self's nodes.
Args:
format (str): output format (csv, json or text).
output (file): file descriptor on which to write.
depth (int): depth of the graph. |
def i2c_write(self, address, *args):
"""
Write data to an i2c device.
:param address: i2c device address
:param args: A variable number of bytes to be sent to the device
"""
data = [address, self.I2C_WRITE]
for item in args:
data.append(item & 0x7f)
... | Write data to an i2c device.
:param address: i2c device address
:param args: A variable number of bytes to be sent to the device |
def list_namespaced_config_map(self, namespace, **kwargs):
"""
list or watch objects of kind ConfigMap
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_namespaced_config_map(namespace, ... | list or watch objects of kind ConfigMap
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_namespaced_config_map(namespace, async_req=True)
>>> result = thread.get()
:param async_req boo... |
def on_epoch_end(self, epoch, **kwargs:Any)->None:
"Compare the value monitored to its best and maybe reduce lr."
current = self.get_monitor_value()
if current is None: return
if self.operator(current - self.min_delta, self.best): self.best,self.wait = current,0
else:
... | Compare the value monitored to its best and maybe reduce lr. |
def has_device_info(self, key):
"""Return true iff cache has information about the device."""
if _debug: DeviceInfoCache._debug("has_device_info %r", key)
return key in self.cache | Return true iff cache has information about the device. |
def _maybe_limit_chromosomes(data):
"""Potentially limit chromosomes to avoid problematically named HLA contigs.
HLAs have ':' characters in them which confuse downstream processing. If
we have no problematic chromosomes we don't limit anything.
"""
std_chroms = []
prob_chroms = []
noalt_ca... | Potentially limit chromosomes to avoid problematically named HLA contigs.
HLAs have ':' characters in them which confuse downstream processing. If
we have no problematic chromosomes we don't limit anything. |
def SoS_exec(script: str, _dict: dict = None,
return_result: bool = True) -> None:
'''Execute a statement.'''
if _dict is None:
_dict = env.sos_dict.dict()
if not return_result:
exec(
compile(script, filename=stmtHash.hash(script), mode='exec'), _dict)
retur... | Execute a statement. |
def extract_arguments(frame):
"""
Extracts the arguments from given frame.
:param frame: Frame.
:type frame: object
:return: Arguments.
:rtype: tuple
"""
arguments = ([], None, None)
try:
source = textwrap.dedent("".join(inspect.getsourcelines(frame)[0]).replace("\\\n", "")... | Extracts the arguments from given frame.
:param frame: Frame.
:type frame: object
:return: Arguments.
:rtype: tuple |
def save_retinotopy_cache(sdir, sid, hemi, props, alignment='MSMAll', overwrite=False):
'''
Saves the subject's retinotopy cache from the given properties. The first argument is the
subject's directory (not the subjects' directory).
'''
h = hemi[:2]
htype = hemi.split('_')[1]
if _auto_downlo... | Saves the subject's retinotopy cache from the given properties. The first argument is the
subject's directory (not the subjects' directory). |
def delete_event(self, id, **data):
"""
DELETE /events/:id/
Deletes an event if the delete is permitted. In order for a delete to be permitted, there must be no pending or
completed orders. Returns a boolean indicating success or failure of the delete.
"""
return... | DELETE /events/:id/
Deletes an event if the delete is permitted. In order for a delete to be permitted, there must be no pending or
completed orders. Returns a boolean indicating success or failure of the delete. |
def minimum_required(version):
"""Decorator to specify the minimum SDK version required.
Args:
version (str): valid version string
Returns:
A decorator function.
"""
def _minimum_required(func):
"""Internal decorator that wraps around the given f... | Decorator to specify the minimum SDK version required.
Args:
version (str): valid version string
Returns:
A decorator function. |
def _copy_to_configdir(items, out_dir, args):
"""Copy configuration files like PED inputs to working config directory.
"""
out = []
for item in items:
ped_file = tz.get_in(["metadata", "ped"], item)
if ped_file and os.path.exists(ped_file):
ped_config_file = os.path.join(out_... | Copy configuration files like PED inputs to working config directory. |
def write_dict_to_yaml(dictionary, path, **kwargs):
"""
Writes a dictionary to a yaml file
:param dictionary: the dictionary to be written
:param path: the absolute path of the target yaml file
:param kwargs: optional additional parameters for dumper
"""
with open(path, 'w') as f:
y... | Writes a dictionary to a yaml file
:param dictionary: the dictionary to be written
:param path: the absolute path of the target yaml file
:param kwargs: optional additional parameters for dumper |
def _restore_constructor(self, cls):
"""
Restore the original constructor, lose track of class.
"""
cls.__init__ = self._observers[cls].init
del self._observers[cls] | Restore the original constructor, lose track of class. |
def _compute_forearc_backarc_term(self, C, sites, dists):
"""
Computes the forearc/backarc scaling term given by equation (4).
"""
f_faba = np.zeros_like(dists.rhypo)
# Term only applies to backarc sites (F_FABA = 0. for forearc)
max_dist = dists.rhypo[sites.backarc]
... | Computes the forearc/backarc scaling term given by equation (4). |
def as_xml(self,parent):
"""Create vcard-tmp XML representation of the field.
:Parameters:
- `parent`: parent node for the element
:Types:
- `parent`: `libxml2.xmlNode`
:return: xml node with the field data.
:returntype: `libxml2.xmlNode`"""
n=pa... | Create vcard-tmp XML representation of the field.
:Parameters:
- `parent`: parent node for the element
:Types:
- `parent`: `libxml2.xmlNode`
:return: xml node with the field data.
:returntype: `libxml2.xmlNode` |
def clip_box(dataset, bounds=None, invert=True, factor=0.35):
"""Clips a dataset by a bounding box defined by the bounds. If no bounds
are given, a corner of the dataset bounds will be removed.
Parameters
----------
bounds : tuple(float)
Length 6 iterable of floats: ... | Clips a dataset by a bounding box defined by the bounds. If no bounds
are given, a corner of the dataset bounds will be removed.
Parameters
----------
bounds : tuple(float)
Length 6 iterable of floats: (xmin, xmax, ymin, ymax, zmin, zmax)
invert : bool
F... |
def checkout_git_repo(git_url, target_dir=None, commit=None, retry_times=GIT_MAX_RETRIES,
branch=None, depth=None):
"""
clone provided git repo to target_dir, optionally checkout provided commit
yield the ClonedRepoData and delete the repo when finished
:param git_url: str, git re... | clone provided git repo to target_dir, optionally checkout provided commit
yield the ClonedRepoData and delete the repo when finished
:param git_url: str, git repo to clone
:param target_dir: str, filesystem path where the repo should be cloned
:param commit: str, commit to checkout, SHA-1 or ref
:... |
def union(self, other):
"""
Merges this range with a given range.
>>> intrange(1, 5).union(intrange(5, 10))
intrange([1,10))
>>> intrange(1, 10).union(intrange(5, 15))
intrange([1,15))
Two ranges can not be merged if the resulting range would be ... | Merges this range with a given range.
>>> intrange(1, 5).union(intrange(5, 10))
intrange([1,10))
>>> intrange(1, 10).union(intrange(5, 15))
intrange([1,15))
Two ranges can not be merged if the resulting range would be split in
two. This happens when the ... |
def notify(request):
'''
This view gets a POST request from the Javascript part of the
AutoreloadPanel that contains a body that looks like::
template=/full/path/to/template.html&template=/another/template.eml:123456789&
media=/static/url/to/a/file:133456780&media=http://media.localhost.loc... | This view gets a POST request from the Javascript part of the
AutoreloadPanel that contains a body that looks like::
template=/full/path/to/template.html&template=/another/template.eml:123456789&
media=/static/url/to/a/file:133456780&media=http://media.localhost.local/base.css
It is a list of ... |
def insert(conn, qualified_name: str, column_names, records):
"""Insert a collection of namedtuple records."""
query = create_insert_statement(qualified_name, column_names)
with conn:
with conn.cursor(cursor_factory=NamedTupleCursor) as cursor:
for record in records:
cu... | Insert a collection of namedtuple records. |
def post(self, *messages):
"""Executes an HTTP request to create message on the queue.
Creates queue if not existed.
Arguments:
messages -- An array of messages to be added to the queue.
"""
url = "queues/%s/messages" % self.name
msgs = [{'body': msg} if isinsta... | Executes an HTTP request to create message on the queue.
Creates queue if not existed.
Arguments:
messages -- An array of messages to be added to the queue. |
def withSize(cls, minimum, maximum):
"""Creates a subclass with value size constraint.
"""
class X(cls):
subtypeSpec = cls.subtypeSpec + constraint.ValueSizeConstraint(
minimum, maximum)
X.__name__ = cls.__name__
return X | Creates a subclass with value size constraint. |
def create_prj_model(self, ):
"""Create and return a tree model that represents a list of projects
:returns: the creeated model
:rtype: :class:`jukeboxcore.gui.treemodel.TreeModel`
:raises: None
"""
prjs = djadapter.projects.all()
rootdata = treemodel.ListItemDat... | Create and return a tree model that represents a list of projects
:returns: the creeated model
:rtype: :class:`jukeboxcore.gui.treemodel.TreeModel`
:raises: None |
def neo(graph: BELGraph, connection: str, password: str):
"""Upload to neo4j."""
import py2neo
neo_graph = py2neo.Graph(connection, password=password)
to_neo4j(graph, neo_graph) | Upload to neo4j. |
def configure (command = None, condition = None, options = None):
"""
Configures a new resource compilation command specific to a condition,
usually a toolset selection condition. The possible options are:
* <rc-type>(rc|windres) - Indicates the type of options the command
... | Configures a new resource compilation command specific to a condition,
usually a toolset selection condition. The possible options are:
* <rc-type>(rc|windres) - Indicates the type of options the command
accepts.
Even though the arguments are all optional, only when a command... |
def COOKIES(self):
""" A dict-like SimpleCookie instance. This should not be used directly.
See :meth:`set_cookie`. """
depr('The COOKIES dict is deprecated. Use `set_cookie()` instead.') # 0.10
if not self._cookies:
self._cookies = SimpleCookie()
return self._coo... | A dict-like SimpleCookie instance. This should not be used directly.
See :meth:`set_cookie`. |
def process(self, candidates):
"""
:arg list candidates: list of Candidates
:returns: score-sorted list of Candidates
"""
return sorted(candidates, key=attrgetter('score'), reverse=self.reverse) | :arg list candidates: list of Candidates
:returns: score-sorted list of Candidates |
def convert_iou(pinyin):
"""iou 转换,还原原始的韵母
iou,uei,uen前面加声母的时候,写成iu,ui,un。
例如niu(牛),gui(归),lun(论)。
"""
return IU_RE.sub(lambda m: m.group(1) + IU_MAP[m.group(2)], pinyin) | iou 转换,还原原始的韵母
iou,uei,uen前面加声母的时候,写成iu,ui,un。
例如niu(牛),gui(归),lun(论)。 |
def handle_user_post_save(sender, **kwargs): # pylint: disable=unused-argument
"""
Handle User model changes - checks if pending enterprise customer user record exists and upgrades it to actual link.
If there are pending enrollments attached to the PendingEnterpriseCustomerUser, then this signal also take... | Handle User model changes - checks if pending enterprise customer user record exists and upgrades it to actual link.
If there are pending enrollments attached to the PendingEnterpriseCustomerUser, then this signal also takes the
newly-created users and enrolls them in the relevant courses. |
def where(self, predicate):
"""
Returns new Enumerable where elements matching predicate are selected
:param predicate: predicate as a lambda expression
:return: new Enumerable object
"""
if predicate is None:
raise NullArgumentError(u"No predicate given for w... | Returns new Enumerable where elements matching predicate are selected
:param predicate: predicate as a lambda expression
:return: new Enumerable object |
def pipeline(
ctx,
input_fn,
db_save,
db_delete,
output_fn,
rules,
species,
namespace_targets,
version,
api,
config_fn,
):
"""BEL Pipeline - BEL Nanopubs into BEL Edges
This will process BEL Nanopubs into BEL Edges by validating, orthologizing (if requested),
can... | BEL Pipeline - BEL Nanopubs into BEL Edges
This will process BEL Nanopubs into BEL Edges by validating, orthologizing (if requested),
canonicalizing, and then computing the BEL Edges based on the given rule_set.
\b
input_fn:
If input fn has *.gz, will read as a gzip file
If input fn ha... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.