code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def read_xl(xl_path: str):
""" Return the workbook from the Excel file in `xl_path`."""
xl_path, choice = _check_xl_path(xl_path)
reader = XL_READERS[choice]
return reader(xl_path) | Return the workbook from the Excel file in `xl_path`. |
def hidePopup(self):
"""
Overloads the hide popup method to handle when the user hides
the popup widget.
"""
if self._treePopupWidget and self.showTreePopup():
self._treePopupWidget.close()
super(XOrbRecordBox, self).hidePopup() | Overloads the hide popup method to handle when the user hides
the popup widget. |
def from_response(cls, header_data, ignore_bad_cookies=False,
ignore_bad_attributes=True):
"Construct a Cookies object from response header data."
cookies = cls()
cookies.parse_response(
header_data,
ignore_bad_cookies=ignore_bad_cookies,
... | Construct a Cookies object from response header data. |
def desk_locale(self, locale):
"""Return the Desk-style locale for locale."""
locale = locale.lower().replace('-', '_')
return self.vendor_locale_map.get(locale, locale) | Return the Desk-style locale for locale. |
def paren_change(inputstring, opens=opens, closes=closes):
"""Determine the parenthetical change of level (num closes - num opens)."""
count = 0
for c in inputstring:
if c in opens: # open parens/brackets/braces
count -= 1
elif c in closes: # close parens/brackets/braces
... | Determine the parenthetical change of level (num closes - num opens). |
def _display_tooltip(self, tooltip, top):
"""
Display tooltip at the specified top position.
"""
QtWidgets.QToolTip.showText(self.mapToGlobal(QtCore.QPoint(
self.sizeHint().width(), top)), tooltip, self) | Display tooltip at the specified top position. |
def next(self):
"""Next that shows progress in statusbar for each <freq> cells"""
self.progress_status()
# Check abortes state and raise StopIteration if aborted
if self.aborted:
statustext = _("File loading aborted.")
post_command_event(self.main_window, self.... | Next that shows progress in statusbar for each <freq> cells |
def copy_config(self, original, new):
'''
Copies collection configs into a new folder. Can be used to create new collections based on existing configs.
Basically, copies all nodes under /configs/original to /configs/new.
:param original str: ZK name of original config
:param n... | Copies collection configs into a new folder. Can be used to create new collections based on existing configs.
Basically, copies all nodes under /configs/original to /configs/new.
:param original str: ZK name of original config
:param new str: New name of the ZK config. |
def validate_wrap(self, value):
''' Validates the type and length of ``value`` '''
if not isinstance(value, basestring):
self._fail_validation_type(value, basestring)
if self.max is not None and len(value) > self.max:
self._fail_validation(value, 'Value too long (%d)' % l... | Validates the type and length of ``value`` |
def is_started(self):
'''Return True if debugging is in progress.'''
return (tracer.is_started() and
not self.trace_hook_suspend
and tracer.find_hook(self.trace_dispatch)) | Return True if debugging is in progress. |
def _json_data(x, extraneous):
"""This function calls a json_json method, if the type has one, otherwise
calls back into to_json(). It also check whether the method takes an
'extraneous' argument and passes that through if possible."""
if type(x) in has_json_data and has_json_data[type(x)]:
if... | This function calls a json_json method, if the type has one, otherwise
calls back into to_json(). It also check whether the method takes an
'extraneous' argument and passes that through if possible. |
def hierarchical_redundancy(rdf, fix=False):
"""Check for and optionally remove extraneous skos:broader relations.
:param Graph rdf: An rdflib.graph.Graph object.
:param bool fix: Fix the problem by removing skos:broader relations between
concepts that are otherwise connected by skos:broaderTransit... | Check for and optionally remove extraneous skos:broader relations.
:param Graph rdf: An rdflib.graph.Graph object.
:param bool fix: Fix the problem by removing skos:broader relations between
concepts that are otherwise connected by skos:broaderTransitive. |
def unbuild(self):
"""
Iterates through the views pointed to by self.detail_views, runs
unbuild_object with `self`, and calls _build_extra()
and _build_related().
"""
for detail_view in self.detail_views:
view = self._get_view(detail_view)
view().u... | Iterates through the views pointed to by self.detail_views, runs
unbuild_object with `self`, and calls _build_extra()
and _build_related(). |
def save(self):
""" Saves prefs to disk in dict format """
fpath = self.get_fpath()
if fpath in ['', None]:
if self._tree.parent is not None:
if VERBOSE_PREF:
print('[pref.save] Can my parent save me?') # ...to disk
return self._tr... | Saves prefs to disk in dict format |
def followup_event_significance(ifo, data_reader, bank,
template_id, coinc_times,
coinc_threshold=0.005,
lookback=150, duration=0.095):
""" Followup an event in another detector and determine its significance
"""
... | Followup an event in another detector and determine its significance |
def on_recording_change(self, enable):
"""Triggered when recording settings have changed.
in enable of type bool
TODO
"""
if not isinstance(enable, bool):
raise TypeError("enable can only be an instance of type bool")
self._call("onRecordingChange",
... | Triggered when recording settings have changed.
in enable of type bool
TODO |
def pot_ana(r, rho):
"""Return the analytical potential in distance r over a homogeneous
half-space
"""
I = 1.0
sigma = 1.0 / rho
phi = np.divide(I, (2.0 * np.pi * sigma * r))
return phi | Return the analytical potential in distance r over a homogeneous
half-space |
def truncate(self, index, chain):
"""
Truncate the trace array to some index.
:Parameters:
index : int
The index within the chain after which all values will be removed.
chain : int
The chain index (>=0).
"""
self._trace[chain] = self._trace[c... | Truncate the trace array to some index.
:Parameters:
index : int
The index within the chain after which all values will be removed.
chain : int
The chain index (>=0). |
async def register_storage_library(storage_type: str, c_library: str, entry_point: str) -> None:
"""
Load a wallet storage plug-in.
An indy-sdk wallet storage plug-in is a shared library; relying parties must explicitly
load it before creating or opening a wallet with the plug-in.
... | Load a wallet storage plug-in.
An indy-sdk wallet storage plug-in is a shared library; relying parties must explicitly
load it before creating or opening a wallet with the plug-in.
The implementation loads a dynamic library and calls an entry point; internally,
the plug-in calls the in... |
def dom(self):
"""Parsed lxml tree (Document Object Model) of the given html."""
try:
dom = self._original_document.dom
# cleaning doesn't return, just wipes in place
html_cleaner(dom)
return leaf_div_elements_into_paragraphs(dom)
except ValueError... | Parsed lxml tree (Document Object Model) of the given html. |
def retrieve(self, order_id, id) :
"""
Retrieve a single line item
Returns a single line item of an order, according to the unique line item ID provided
:calls: ``get /orders/{order_id}/line_items/{id}``
:param int order_id: Unique identifier of a Order.
:param int id: ... | Retrieve a single line item
Returns a single line item of an order, according to the unique line item ID provided
:calls: ``get /orders/{order_id}/line_items/{id}``
:param int order_id: Unique identifier of a Order.
:param int id: Unique identifier of a LineItem.
:return: Dicti... |
def get_kwargs(grid, kwargs, phenotypes=False):
"""
Helper function to figure out what denom and palette to use, based on the
kwargs and the grid being plotted. The optional (default: false) argument
indicates whether the grid contains phenotypes, as opposed to resources.
"""
denom = None
if... | Helper function to figure out what denom and palette to use, based on the
kwargs and the grid being plotted. The optional (default: false) argument
indicates whether the grid contains phenotypes, as opposed to resources. |
def dstat(inarr, taxdict, mindict=1, nboots=1000, name=0):
""" private function to perform a single D-stat test"""
#if isinstance(inarr, str):
# with open(inarr, 'r') as infile:
# inarr = infile.read().strip().split("|\n")
# ## get data as an array from loci file
# ## if loci-list th... | private function to perform a single D-stat test |
def startswith(self, event_property, value):
"""A starts-with filter chain.
>>> request_time = EventExpression('request', 'elapsed_ms')
>>> filtered = request_time.startswith('path', '/cube')
>>> print(filtered)
request(elapsed_ms).re(path, "^/cube")
"""
c = self... | A starts-with filter chain.
>>> request_time = EventExpression('request', 'elapsed_ms')
>>> filtered = request_time.startswith('path', '/cube')
>>> print(filtered)
request(elapsed_ms).re(path, "^/cube") |
def text_summary(tag, text):
"""Outputs a `Summary` protocol buffer with audio data.
Parameters
----------
tag : str
A name for the generated summary. Will also serve as a series name in TensorBoard.
text : str
Text data.
Returns
-------
A `Summary` ... | Outputs a `Summary` protocol buffer with audio data.
Parameters
----------
tag : str
A name for the generated summary. Will also serve as a series name in TensorBoard.
text : str
Text data.
Returns
-------
A `Summary` protobuf of the audio data. |
def steepest_descent(f, x, line_search=1.0, maxiter=1000, tol=1e-16,
projection=None, callback=None):
r"""Steepest descent method to minimize an objective function.
General implementation of steepest decent (also known as gradient
decent) for solving
.. math::
\min f(x)
... | r"""Steepest descent method to minimize an objective function.
General implementation of steepest decent (also known as gradient
decent) for solving
.. math::
\min f(x)
The algorithm is intended for unconstrained problems. It needs line
search in order guarantee convergence. With appropri... |
def to_time(arg, format=None, infer_time_format=False, errors='raise'):
"""
Parse time strings to time objects using fixed strptime formats ("%H:%M",
"%H%M", "%I:%M%p", "%I%M%p", "%H:%M:%S", "%H%M%S", "%I:%M:%S%p",
"%I%M%S%p")
Use infer_time_format if all the strings are in the same format to speed... | Parse time strings to time objects using fixed strptime formats ("%H:%M",
"%H%M", "%I:%M%p", "%I%M%p", "%H:%M:%S", "%H%M%S", "%I:%M:%S%p",
"%I%M%S%p")
Use infer_time_format if all the strings are in the same format to speed
up conversion.
Parameters
----------
arg : string in time format, ... |
def _value_length(self, value, t):
"""Given an integer or list of them, convert it to an array of bytes."""
if isinstance(value, int):
fmt = '<%s' % (type_codes[t])
output = struct.pack(fmt, value)
return len(output)
elif isinstance(value, str):
r... | Given an integer or list of them, convert it to an array of bytes. |
def save_one_data(self, data, table):
'''
将一条记录保存到数据库
Args:
table: 表名字 str
data: 记录 dict
return:
成功: 1
失败: -1 并打印返回报错信息
每条记录都以一个字典的形式传进来
'''
key_map = {}
if len(data) == 0:
print('请确保data被正确传入了')... | 将一条记录保存到数据库
Args:
table: 表名字 str
data: 记录 dict
return:
成功: 1
失败: -1 并打印返回报错信息
每条记录都以一个字典的形式传进来 |
def _calculate_feature_stats(feature_list, prepared, serialization_file): # pylint: disable=R0914
"""Calculate min, max and mean for each feature. Store it in object."""
# Create feature only list
feats = [x for x, _ in prepared] # Label is not necessary
# Calculate all means / mins / maxs
means ... | Calculate min, max and mean for each feature. Store it in object. |
def access_time(self):
"""dfdatetime.DateTimeValues: access time or None if not available."""
if self._stat_info is None:
return None
timestamp = int(self._stat_info.st_atime)
return dfdatetime_posix_time.PosixTime(timestamp=timestamp) | dfdatetime.DateTimeValues: access time or None if not available. |
def _archive_self(self, logfile, key=JobDetails.topkey, status=JobStatus.unknown):
"""Write info about a job run by this `Link` to the job archive"""
self._register_self(logfile, key, status)
if self._job_archive is None:
return
self._job_archive.register_jobs(self.get_jobs()... | Write info about a job run by this `Link` to the job archive |
def clear_copyright(self):
"""Removes the copyright.
raise: NoAccess - ``Metadata.isRequired()`` is ``true`` or
``Metadata.isReadOnly()`` is ``true``
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for osid.repository... | Removes the copyright.
raise: NoAccess - ``Metadata.isRequired()`` is ``true`` or
``Metadata.isReadOnly()`` is ``true``
*compliance: mandatory -- This method must be implemented.* |
def tcp(self):
"""
- An TCPHeader instance, if the packet is valid TCP.
- None, otherwise.
"""
ipproto, proto_start = self.protocol
if ipproto == Protocol.TCP:
return TCPHeader(self, proto_start) | - An TCPHeader instance, if the packet is valid TCP.
- None, otherwise. |
def get_all_languages(self, sort='code'):
"""
Retrieve all the language objects for a country. Language objects will be annotated with
the country and culturecode attributes when applicable.
:param sort: code|name_en|name_native
:return:
"""
langs = list(self.culturecode_set.all().as_langua... | Retrieve all the language objects for a country. Language objects will be annotated with
the country and culturecode attributes when applicable.
:param sort: code|name_en|name_native
:return: |
def begin_update(self, x_data, h_0=None, drop=0.0):
"""Return the output of the wrapped PyTorch model for the given input,
along with a callback to handle the backward pass.
"""
x_var = torch.autograd.Variable(xp2torch(x_data), requires_grad=True)
# Make prediction
out, ... | Return the output of the wrapped PyTorch model for the given input,
along with a callback to handle the backward pass. |
def repr_part(self):
"""String usable in a space's ``__repr__`` method."""
optargs = [('weighting', array_str(self.array, nprint=10), ''),
('exponent', self.exponent, 2.0)]
return signature_string([], optargs, sep=',\n',
mod=[[], ['!s', ':.4']]) | String usable in a space's ``__repr__`` method. |
def _get_args_and_defaults(args, defaults):
"""Return a list of 2-tuples - the argument name and its default value or
a special value that indicates there is no default value.
Args:
args: list of argument name
defaults: tuple of default values
"""
defaults = defaults or []
a... | Return a list of 2-tuples - the argument name and its default value or
a special value that indicates there is no default value.
Args:
args: list of argument name
defaults: tuple of default values |
def minutes_for_session(self, session_label):
"""
Given a session label, return the minutes for that session.
Parameters
----------
session_label: pd.Timestamp (midnight UTC)
A session label whose session's minutes are desired.
Returns
-------
... | Given a session label, return the minutes for that session.
Parameters
----------
session_label: pd.Timestamp (midnight UTC)
A session label whose session's minutes are desired.
Returns
-------
pd.DateTimeIndex
All the minutes for the given sessi... |
def scene_color(frames):
"""parse a scene.color message"""
# "scene.color" <scene_id> <color>
reader = MessageReader(frames)
results = reader.string("command").uint32("scene_id").uint8_3("color").assert_end().get()
if results.command != "scene.color":
raise MessagePar... | parse a scene.color message |
def update(self, id):
"""PUT /mapfiles/id: Update an existing item."""
map = self._get_map_from_user_by_id(c.user, id)
if map is None:
abort(404)
# get json content from PUT request
content = request.environ['wsgi.input'].read(int(request.environ['CONTENT_LENGTH']))
... | PUT /mapfiles/id: Update an existing item. |
def convert(self):
"""
Return :attr:`metainfo` with all keys encoded to :class:`bytes` and all
values encoded to :class:`bytes`, :class:`int`, :class:`list` or
:class:`OrderedDict`
:raises MetainfoError: on values that cannot be converted properly
"""
try:
... | Return :attr:`metainfo` with all keys encoded to :class:`bytes` and all
values encoded to :class:`bytes`, :class:`int`, :class:`list` or
:class:`OrderedDict`
:raises MetainfoError: on values that cannot be converted properly |
def _add_edges(self, features):
""" Adds an edge to the graph for each item in 'features' using
the GraphEdges from the editor factory.
"""
graph = self._graph
if graph is not None:
for feature in features:
for graph_edge in self.factory.edges:
... | Adds an edge to the graph for each item in 'features' using
the GraphEdges from the editor factory. |
def exists(self, name):
"""
Check if a group exists.
"""
with self.settings(hide('running', 'stdout', 'warnings'), warn_only=True):
return self.run('getent group %(name)s' % locals()).succeeded | Check if a group exists. |
def insert(self, context):
"""
Build the image.
:param resort.engine.execution.Context context:
Current execution context.
"""
try:
current_dir = os.getcwd()
os.chdir(os.path.join(context.profile_dir(), self.__base_dir))
args = [
"packer",
"build",
self.__template_path
]
... | Build the image.
:param resort.engine.execution.Context context:
Current execution context. |
def do_mailfy(self, query, **kwargs):
"""
Verifying a mailfy query in this platform.
This might be redefined in any class inheriting from Platform. The only
condition is that any of this should return an equivalent array.
Args:
-----
query: The element to be... | Verifying a mailfy query in this platform.
This might be redefined in any class inheriting from Platform. The only
condition is that any of this should return an equivalent array.
Args:
-----
query: The element to be searched.
Return:
-------
A ... |
def add_view(self, request, **kwargs):
"""
For the ``Page`` model, redirect to the add view for the
first page model, based on the ``ADD_PAGE_ORDER`` setting.
"""
if self.model is Page:
return HttpResponseRedirect(self.get_content_models()[0].add_url)
return s... | For the ``Page`` model, redirect to the add view for the
first page model, based on the ``ADD_PAGE_ORDER`` setting. |
def refresh_db(root=None, **kwargs):
'''
Just run a ``pacman -Sy``, return a dict::
{'<database name>': Bool}
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
'''
# Remove rtag file to keep multiple refreshes from happening in pkg states
salt.utils.pkg.clear_rtag... | Just run a ``pacman -Sy``, return a dict::
{'<database name>': Bool}
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db |
def gdcs_fai(sample, analysistype='GDCS'):
"""
GDCS analyses need to use the .fai file supplied in the targets folder rather than the one created following
reverse baiting
:param sample: sample object
:param analysistype: current analysis being performed
"""
try:
... | GDCS analyses need to use the .fai file supplied in the targets folder rather than the one created following
reverse baiting
:param sample: sample object
:param analysistype: current analysis being performed |
def addSourceLocation(self, sourceLocationUri, weight):
"""
add a list of relevant sources by identifying them by their geographic location
@param sourceLocationUri: uri of the location where the sources should be geographically located
@param weight: importance of the provided list of s... | add a list of relevant sources by identifying them by their geographic location
@param sourceLocationUri: uri of the location where the sources should be geographically located
@param weight: importance of the provided list of sources (typically in range 1 - 50) |
def get_visibility(name):
"""return the visibility from a name: public, protected, private or special
"""
if SPECIAL.match(name):
visibility = "special"
elif PRIVATE.match(name):
visibility = "private"
elif PROTECTED.match(name):
visibility = "protected"
else:
vi... | return the visibility from a name: public, protected, private or special |
def get(self, interface_id):
"""
Get the interface from engine json
:param str interface_id: interface ID to find
:raises InterfaceNotFound: Cannot find interface
"""
# From within engine, skips nested iterators for this find
# Make sure were dealing with... | Get the interface from engine json
:param str interface_id: interface ID to find
:raises InterfaceNotFound: Cannot find interface |
def begin(self):
"""Initialize communication with the PN532. Must be called before any
other calls are made against the PN532.
"""
# Assert CS pin low for a second for PN532 to be ready.
self._gpio.set_low(self._cs)
time.sleep(1.0)
# Call GetFirmwareVersion to sy... | Initialize communication with the PN532. Must be called before any
other calls are made against the PN532. |
def __get_descendants(node, dfs_data):
"""Gets the descendants of a node."""
list_of_descendants = []
stack = deque()
children_lookup = dfs_data['children_lookup']
current_node = node
children = children_lookup[current_node]
dfs_current_node = D(current_node, dfs_data)
for n in childr... | Gets the descendants of a node. |
def _process_execute_ok(self, msg):
""" Process a reply for a successful execution request.
"""
payload = msg['content']['payload']
for item in payload:
if not self._process_execute_payload(item):
warning = 'Warning: received unknown payload of type %s'
... | Process a reply for a successful execution request. |
def ungrab_key(conn, wid, modifiers, key):
"""
Ungrabs a key that was grabbed by ``grab_key``. Similarly, it will return
True on success and False on failure.
When ungrabbing a key, the parameters to this function should be
*precisely* the same as the parameters to ``grab_key``.
:param wid: A ... | Ungrabs a key that was grabbed by ``grab_key``. Similarly, it will return
True on success and False on failure.
When ungrabbing a key, the parameters to this function should be
*precisely* the same as the parameters to ``grab_key``.
:param wid: A window identifier.
:type wid: int
:param modifi... |
def make_subquery_heading(self):
"""
Create a new heading with removed attribute sql_expressions.
Used by subqueries, which resolve the sql_expressions.
"""
return Heading(dict(v.todict(), sql_expression=None) for v in self.attributes.values()) | Create a new heading with removed attribute sql_expressions.
Used by subqueries, which resolve the sql_expressions. |
def field_items(self, path=str(), **options):
""" Returns a **flatten** list of ``('field path', field item)`` tuples
for the `Pointer` field itself and for each :class:`Field` *nested* in the
:attr:`data` object referenced by the `Pointer` field.
:param str path: path of the `Pointer` ... | Returns a **flatten** list of ``('field path', field item)`` tuples
for the `Pointer` field itself and for each :class:`Field` *nested* in the
:attr:`data` object referenced by the `Pointer` field.
:param str path: path of the `Pointer` field.
:keyword bool nested: if ``True`` all :clas... |
def calcavg_avgstrlen_subtrees(subtrees, dbg=False):
"""In the effort of not using external libraries (like scipy, numpy, etc),
I've written some harmless code for basic statistical calculations
"""
ttl = 0
for subtree in subtrees:
ttl += subtree.avg_strlen
crd = len(subtrees)
... | In the effort of not using external libraries (like scipy, numpy, etc),
I've written some harmless code for basic statistical calculations |
def assign_literal(element, value):
u"""Assigns a literal.
If a given node doesn't exist, it will be created.
:param etree.Element element: element to which we assign.
:param value: the value to assign
"""
# Searches for a conversion method specific to the type of value... | u"""Assigns a literal.
If a given node doesn't exist, it will be created.
:param etree.Element element: element to which we assign.
:param value: the value to assign |
def _submit_bundle(cmd_args, app):
"""Submit an existing bundle to the service"""
sac = streamsx.rest.StreamingAnalyticsConnection(service_name=cmd_args.service_name)
sas = sac.get_streaming_analytics()
sr = sas.submit_job(bundle=app.app, job_config=app.cfg[ctx.ConfigParams.JOB_CONFIG])
if 'exceptio... | Submit an existing bundle to the service |
def remove_binding(self, function):
"""
Remove a key binding.
This expects a function that was given to `add_binding` method as
parameter. Raises `ValueError` when the given function was not
registered before.
"""
assert callable(function)
for b in self.... | Remove a key binding.
This expects a function that was given to `add_binding` method as
parameter. Raises `ValueError` when the given function was not
registered before. |
def serve_forever(self):
"""Call the main loop."""
# Set the server login/password (if -P/--password tag)
if self.args.password != "":
self.add_user(self.args.username, self.args.password)
# Serve forever
self.server.serve_forever() | Call the main loop. |
def major(self):
""" Major inbox feed, contains major activities such as notes and images. """
url = self._subfeed("major")
if "major" in self.url or "minor" in self.url:
return self
if self._major is None:
self._major = self.__class__(url, pypump=self._pump)
... | Major inbox feed, contains major activities such as notes and images. |
def load_torch(path, bigdl_type="float"):
"""
Load a pre-trained Torch model.
:param path: The path containing the pre-trained model.
:return: A pre-trained model.
"""
jmodel = callBigDlFunc(bigdl_type, "loadTorch", path)
return Layer.of(jmodel) | Load a pre-trained Torch model.
:param path: The path containing the pre-trained model.
:return: A pre-trained model. |
def download_scans(sc, age=0, unzip=False, path='scans'):
'''Scan Downloader
Here we will attempt to download all of the scans that have completed between
now and AGE days ago.
sc = SecurityCenter5 object
age = how many days back do we want to pull? (default: 0)
unzip = Do we want to uncompress... | Scan Downloader
Here we will attempt to download all of the scans that have completed between
now and AGE days ago.
sc = SecurityCenter5 object
age = how many days back do we want to pull? (default: 0)
unzip = Do we want to uncompress the nessus files? (default: False)
path = Path where the res... |
def run(self):
"""The thread's main activity. Call start() instead."""
self.socket = self.context.socket(zmq.DEALER)
self.socket.setsockopt(zmq.IDENTITY, self.session.bsession)
self.socket.connect('tcp://%s:%i' % self.address)
self.stream = zmqstream.ZMQStream(self.socket, self.... | The thread's main activity. Call start() instead. |
def deepSetAttr(obj, path, val):
"""
Sets a deep attribute on an object by resolving a dot-delimited
path. If path does not exist an `AttributeError` will be raised`.
"""
first, _, rest = path.rpartition('.')
return setattr(deepGetAttr(obj, first) if first else obj, rest, val) | Sets a deep attribute on an object by resolving a dot-delimited
path. If path does not exist an `AttributeError` will be raised`. |
def file_change_rates(self, branch='master', limit=None, coverage=False, days=None, ignore_globs=None, include_globs=None):
"""
This function will return a DataFrame containing some basic aggregations of the file change history data, and
optionally test coverage data from a coverage_data.py .cov... | This function will return a DataFrame containing some basic aggregations of the file change history data, and
optionally test coverage data from a coverage_data.py .coverage file. The aim here is to identify files in the
project which have abnormal edit rates, or the rate of changes without growing the... |
def handle_internal(msg):
"""Process an internal message."""
internal = msg.gateway.const.Internal(msg.sub_type)
handler = internal.get_handler(msg.gateway.handlers)
if handler is None:
return None
return handler(msg) | Process an internal message. |
def run(self):
"""Executes the tasks in the lane in the order in which they have been added, unless
`self.run_parallel` is True, then a thread is spawned for each task and executed in
parallel (note that task threads are still spawned in the order in which they were added).
"""
l... | Executes the tasks in the lane in the order in which they have been added, unless
`self.run_parallel` is True, then a thread is spawned for each task and executed in
parallel (note that task threads are still spawned in the order in which they were added). |
def _resolve_time(value):
'''
Resolve the time in seconds of a configuration value.
'''
if value is None or isinstance(value,(int,long)):
return value
if NUMBER_TIME.match(value):
return long(value)
simple = SIMPLE_TIME.match(value)
if SIMPLE_TIME.match(value):
multiplier = long( simple.grou... | Resolve the time in seconds of a configuration value. |
def djfrontend_twbs_js(version=None, files=None):
"""
Returns Twitter Bootstrap JavaScript file(s).
all returns concatenated file; full file for TEMPLATE_DEBUG, minified otherwise.
Other choice are:
affix,
alert,
button,
carousel,
collapse,
dropdown,
... | Returns Twitter Bootstrap JavaScript file(s).
all returns concatenated file; full file for TEMPLATE_DEBUG, minified otherwise.
Other choice are:
affix,
alert,
button,
carousel,
collapse,
dropdown,
modal,
popover (adds tooltip if not included),
... |
def check_funds_for_tx_gas(self, safe_address: str, safe_tx_gas: int, data_gas: int, gas_price: int,
gas_token: str) -> bool:
"""
Check safe has enough funds to pay for a tx
:param safe_address: Address of the safe
:param safe_tx_gas: Start gas
:par... | Check safe has enough funds to pay for a tx
:param safe_address: Address of the safe
:param safe_tx_gas: Start gas
:param data_gas: Data gas
:param gas_price: Gas Price
:param gas_token: Gas Token, to use token instead of ether for the gas
:return: True if enough funds, F... |
def fix_lamdaline(source):
"""Remove the last redundant token from lambda expression
lambda x: return x)
^
Return string without irrelevant tokens
returned from inspect.getsource on lamda expr returns
"""
# Using undocumented generate_tokens due to a tokenize.tokenize bug... | Remove the last redundant token from lambda expression
lambda x: return x)
^
Return string without irrelevant tokens
returned from inspect.getsource on lamda expr returns |
def websocket(
self, uri, host=None, strict_slashes=None, version=None, name=None
):
"""Create a blueprint websocket route from a decorated function.
:param uri: endpoint at which the route will be accessible.
:param host: IP Address of FQDN for the sanic server to use.
:par... | Create a blueprint websocket route from a decorated function.
:param uri: endpoint at which the route will be accessible.
:param host: IP Address of FQDN for the sanic server to use.
:param strict_slashes: Enforce the API urls are requested with a
training */*
:param version... |
def saveFile(self, filename):
"""Dump an XML document to a file. Will use compression if
compiled in and enabled. If @filename is "-" the stdout
file is used. """
ret = libxml2mod.xmlSaveFile(filename, self._o)
return ret | Dump an XML document to a file. Will use compression if
compiled in and enabled. If @filename is "-" the stdout
file is used. |
def format_and_strip(template, params, strip_string=strip_string):
"""Format a string containing %s for placeholders and call `strip_string`
on each parameter. The string template itself does not have a maximum
length.
TODO: handle other placeholders, not just %s
"""
chunks = template.split(u"%... | Format a string containing %s for placeholders and call `strip_string`
on each parameter. The string template itself does not have a maximum
length.
TODO: handle other placeholders, not just %s |
def execute(self):
"""Execute git clean to remove untracked/build files."""
clean_cmd = ['git', 'clean', '-X', '-d']
if 'CI' not in os.environ:
LOGGER.info('The following files/directories will be deleted:')
LOGGER.info('')
LOGGER.info(check_output(clean_cmd +... | Execute git clean to remove untracked/build files. |
def _handleRenderResult(self, request, result):
"""
Handle the result from `IResource.render`.
If the result is a `Deferred` then return `NOT_DONE_YET` and add
a callback to write the result to the request when it arrives.
"""
def _requestFinished(result, cancel):
... | Handle the result from `IResource.render`.
If the result is a `Deferred` then return `NOT_DONE_YET` and add
a callback to write the result to the request when it arrives. |
def _appendpath_unique(list_, path):
"""Append path to list if not already in list"""
for p in list_:
if p == path:
return
list_.append(path) | Append path to list if not already in list |
def overlay_gateway_ip_interface_loopback_loopback_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
overlay_gateway = ET.SubElement(config, "overlay-gateway", xmlns="urn:brocade.com:mgmt:brocade-tunnels")
name_key = ET.SubElement(overlay_gateway, "name... | Auto Generated Code |
def create_data_element(self, mapped_class=None):
"""
Returns a new data element for the given mapped class.
:returns: object implementing :class:`IResourceDataElement`.
"""
if not mapped_class is None and mapped_class != self.__mapped_cls:
mp = self.__mp_reg.find_or... | Returns a new data element for the given mapped class.
:returns: object implementing :class:`IResourceDataElement`. |
def _handle_request(self, request):
"""Process the headers and get the file"""
# Check if this is a persistent connection.
if request['version'] == 'HTTP/1.1':
self.keepalive = not request.get('Connection') == 'close'
elif request['version'] == 'HTTP/1.0':
self.k... | Process the headers and get the file |
def transform(graph):
'''core transform function for graph.
'''
graphs = []
for _ in range(Constant.N_NEIGHBOURS * 2):
random_num = randrange(3)
temp_graph = None
if random_num == 0:
temp_graph = to_deeper_graph(deepcopy(graph))
elif random_num == 1:
... | core transform function for graph. |
def put_pidfile( pidfile_path, pid ):
"""
Put a PID into a pidfile
"""
with open( pidfile_path, "w" ) as f:
f.write("%s" % pid)
os.fsync(f.fileno())
return | Put a PID into a pidfile |
def url(self, request):
'''
Return absolute URL for assignment description.
'''
if self.pk:
if self.has_description():
return request.build_absolute_uri(reverse('assignment_description_file', args=[self.pk]))
else:
return self.d... | Return absolute URL for assignment description. |
def requestJob(self, CorpNum, Type, SDate, EDate, UserID=None):
""" 수집 요청
args
CorpNum : 팝빌회원 사업자번호
Type : 문서형태, SELL-매출, BUY-매입,
SDate : 시작일자, 표시형식(yyyyMMdd)
EDate : 종료일자, 표시형식(yyyyMMdd)
UserID : 팝빌회원 아이디
re... | 수집 요청
args
CorpNum : 팝빌회원 사업자번호
Type : 문서형태, SELL-매출, BUY-매입,
SDate : 시작일자, 표시형식(yyyyMMdd)
EDate : 종료일자, 표시형식(yyyyMMdd)
UserID : 팝빌회원 아이디
return
작업아이디 (jobID)
raise
Popbill... |
def connect_params_async(self):
"""Connection parameters for `aiomysql.Connection`
"""
kwargs = self.connect_params.copy()
kwargs.update({
'minsize': self.min_connections,
'maxsize': self.max_connections,
'autocommit': True,
})
return k... | Connection parameters for `aiomysql.Connection` |
def complete(self):
"""
Custom completion check that invokes the task's *workflow_complete* if it is callable, or
just does the default completion check otherwise.
"""
if callable(self.task.workflow_complete):
return self.task.workflow_complete()
else:
... | Custom completion check that invokes the task's *workflow_complete* if it is callable, or
just does the default completion check otherwise. |
def decode_endpoint_props(input_props):
# type: (Dict) -> Dict[str, Any]
"""
Decodes the endpoint properties from the given dictionary
"""
ed_props = decode_osgi_props(input_props)
ed_props[ECF_ENDPOINT_CONTAINERID_NAMESPACE] = input_props[
ECF_ENDPOINT_CONTAINERID_NAMESPACE
]
ed... | Decodes the endpoint properties from the given dictionary |
def build_import_pattern(mapping1, mapping2):
u"""
mapping1: A dict mapping py3k modules to all possible py2k replacements
mapping2: A dict mapping py2k modules to the things they do
This builds a HUGE pattern to match all ways that things can be imported
"""
# py3k: urllib.request, py2k: ('urll... | u"""
mapping1: A dict mapping py3k modules to all possible py2k replacements
mapping2: A dict mapping py2k modules to the things they do
This builds a HUGE pattern to match all ways that things can be imported |
def modify_meta(uid, data_dic, extinfo=None):
'''
update meta of the rec.
'''
if extinfo is None:
extinfo = {}
title = data_dic['title'].strip()
if len(title) < 2:
return False
cur_info = MPost.get_by_uid(uid)
if cur_info:
... | update meta of the rec. |
def _title_for_slice(self, truncate=50):
"""
If the dataarray has 1 dimensional coordinates or comes from a slice
we can show that info in the title
Parameters
----------
truncate : integer
maximum number of characters for title
Returns
-----... | If the dataarray has 1 dimensional coordinates or comes from a slice
we can show that info in the title
Parameters
----------
truncate : integer
maximum number of characters for title
Returns
-------
title : string
Can be used for plot ti... |
def _auto_complete_filename(self, location):
"""
Args:
location (str | unicode | None): Location to auto-complete with {basename}, if it points to a folder
Returns:
str | None: {location}/{basename}
"""
path = formatted(location, self)
if path:
... | Args:
location (str | unicode | None): Location to auto-complete with {basename}, if it points to a folder
Returns:
str | None: {location}/{basename} |
def _on_complete(self, my_task):
"""
Return True on success, False otherwise. Should not be overwritten,
overwrite _on_complete_hook() instead.
:type my_task: Task
:param my_task: The associated task in the task tree.
:rtype: boolean
:returns: True on success, ... | Return True on success, False otherwise. Should not be overwritten,
overwrite _on_complete_hook() instead.
:type my_task: Task
:param my_task: The associated task in the task tree.
:rtype: boolean
:returns: True on success, False otherwise. |
def physicaliam(aoi, n=1.526, K=4., L=0.002):
'''
Determine the incidence angle modifier using refractive index,
extinction coefficient, and glazing thickness.
physicaliam calculates the incidence angle modifier as described in
De Soto et al. "Improvement and validation of a model for
photovolt... | Determine the incidence angle modifier using refractive index,
extinction coefficient, and glazing thickness.
physicaliam calculates the incidence angle modifier as described in
De Soto et al. "Improvement and validation of a model for
photovoltaic array performance", section 3. The calculation is base... |
def mprocess(name, config_path, port=None, timeout=180, silence_stdout=True):
"""start 'name' process with params from config_path.
Args:
name - process name or path
config_path - path to file where should be stored configuration
port - process's port
timeout - specify how long, ... | start 'name' process with params from config_path.
Args:
name - process name or path
config_path - path to file where should be stored configuration
port - process's port
timeout - specify how long, in seconds, a command can take before times out.
if timeout <=0 - d... |
def call_handlers(event):
"""
Invoke all handlers for the provided event type/sub-type.
The handlers are invoked in the following order:
1. Global handlers
2. Event type handlers
3. Event sub-type handlers
Handlers within each group are invoked in order of registration.
:param event: The event model object.... | Invoke all handlers for the provided event type/sub-type.
The handlers are invoked in the following order:
1. Global handlers
2. Event type handlers
3. Event sub-type handlers
Handlers within each group are invoked in order of registration.
:param event: The event model object.
:type event: ``djstripe.models... |
def load_name(self, offset):
"""
Load a timezone name from a DLL offset (integer).
>>> from dateutil.tzwin import tzres
>>> tzr = tzres()
>>> print(tzr.load_name(112))
'Eastern Standard Time'
:param offset:
A positive integer value referring to a str... | Load a timezone name from a DLL offset (integer).
>>> from dateutil.tzwin import tzres
>>> tzr = tzres()
>>> print(tzr.load_name(112))
'Eastern Standard Time'
:param offset:
A positive integer value referring to a string from the tzres dll.
..note:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.