code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def make_list(cls, item_converter=None, listsep=','):
"""
Create a type converter for a list of items (many := 1..*).
The parser accepts anything and the converter needs to fail on errors.
:param item_converter: Type converter for an item.
:param listsep: List separator to use... | Create a type converter for a list of items (many := 1..*).
The parser accepts anything and the converter needs to fail on errors.
:param item_converter: Type converter for an item.
:param listsep: List separator to use (as string).
:return: Type converter function object for the list... |
def register_path(self, path, modified_time=None):
"""
Registers given path.
:param path: Path name.
:type path: unicode
:param modified_time: Custom modified time.
:type modified_time: int or float
:return: Method success.
:rtype: bool
"""
... | Registers given path.
:param path: Path name.
:type path: unicode
:param modified_time: Custom modified time.
:type modified_time: int or float
:return: Method success.
:rtype: bool |
def __File_Command_lineEdit_set_ui(self):
"""
Fills **File_Command_lineEdit** Widget.
"""
# Adding settings key if it doesn't exists.
self.__settings.get_key(self.__settings_section, "file_command").isNull() and \
self.__settings.set_key(self.__settings_section, "file_co... | Fills **File_Command_lineEdit** Widget. |
def _get_metadata(field, expr, metadata_expr, no_metadata_rule):
"""Find the correct metadata expression for the expression.
Parameters
----------
field : {'deltas', 'checkpoints'}
The kind of metadata expr to lookup.
expr : Expr
The baseline expression.
metadata_expr : Expr, 'a... | Find the correct metadata expression for the expression.
Parameters
----------
field : {'deltas', 'checkpoints'}
The kind of metadata expr to lookup.
expr : Expr
The baseline expression.
metadata_expr : Expr, 'auto', or None
The metadata argument. If this is 'auto', then the... |
def drop(self, format_p, action):
"""Informs the source that a drop event occurred for a pending
drag and drop operation.
in format_p of type str
The mime type the data must be in.
in action of type :class:`DnDAction`
The action to use.
return progress ... | Informs the source that a drop event occurred for a pending
drag and drop operation.
in format_p of type str
The mime type the data must be in.
in action of type :class:`DnDAction`
The action to use.
return progress of type :class:`IProgress`
Progre... |
def compare_modules(file_, imports):
"""Compare modules in a file to imported modules in a project.
Args:
file_ (str): File to parse for modules to be compared.
imports (tuple): Modules being imported in the project.
Returns:
tuple: The modules not imported in the project, but do e... | Compare modules in a file to imported modules in a project.
Args:
file_ (str): File to parse for modules to be compared.
imports (tuple): Modules being imported in the project.
Returns:
tuple: The modules not imported in the project, but do exist in the
specified file. |
def _status_message_0x01_received(self, msg):
"""Handle status received messages.
The following status values can be received:
0x00 = Both Outlets Off
0x01 = Only Top Outlet On
0x02 = Only Bottom Outlet On
0x03 = Both Outlets On
"""
if msg... | Handle status received messages.
The following status values can be received:
0x00 = Both Outlets Off
0x01 = Only Top Outlet On
0x02 = Only Bottom Outlet On
0x03 = Both Outlets On |
def dump(self, f):
"""
Dump data to a file.
:param f: file-like object or path to file
:type f: file or str
"""
self.validate()
with _open_file_obj(f, "w") as f:
parser = self._get_parser()
self.serialize(parser)
self.build_fil... | Dump data to a file.
:param f: file-like object or path to file
:type f: file or str |
def determine_actions(self, request, view):
"""Allow all allowed methods"""
from rest_framework.generics import GenericAPIView
actions = {}
excluded_methods = {'HEAD', 'OPTIONS', 'PATCH', 'DELETE'}
for method in set(view.allowed_methods) - excluded_methods:
view.reque... | Allow all allowed methods |
def draw(obj, plane='3d', inline=False, **kwargs):
'''Draw the morphology using in the given plane
plane (str): a string representing the 2D plane (example: 'xy')
or '3d', '3D' for a 3D view
inline (bool): must be set to True for interactive ipython notebook plotting
'''
if plane.... | Draw the morphology using in the given plane
plane (str): a string representing the 2D plane (example: 'xy')
or '3d', '3D' for a 3D view
inline (bool): must be set to True for interactive ipython notebook plotting |
def rmdir(self, dir_name):
"""Remove cur_dir/name."""
self.check_write(dir_name)
path = normpath_url(join_url(self.cur_dir, dir_name))
# write("REMOVE %r" % path)
shutil.rmtree(path) | Remove cur_dir/name. |
def _create_json(self):
"""
JSON Documentation: https://www.jfrog.com/confluence/display/RTF/Repository+Configuration+JSON
"""
data_json = {
"rclass": "local",
"key": self.name,
"description": self.description,
"packageType": self.packageTy... | JSON Documentation: https://www.jfrog.com/confluence/display/RTF/Repository+Configuration+JSON |
def update(cls, id, memory, cores, console, password, background,
max_memory):
"""Update a virtual machine."""
if not background and not cls.intty():
background = True
vm_params = {}
if memory:
vm_params['memory'] = memory
if cores:
... | Update a virtual machine. |
def probability_density(self, X):
"""Compute probability density.
Arguments:
X: `np.ndarray` of shape (n, 1).
Returns:
np.ndarray
"""
self.check_fit()
return norm.pdf(X, loc=self.mean, scale=self.std) | Compute probability density.
Arguments:
X: `np.ndarray` of shape (n, 1).
Returns:
np.ndarray |
def _put(self, *args, **kwargs):
"""
A wrapper for putting things. It will also json encode your 'data' parameter
:returns: The response of your put
:rtype: dict
:raises: This will raise a
:class:`NewRelicAPIServerException<newrelic_api.exceptions.NewRelicAPIServerE... | A wrapper for putting things. It will also json encode your 'data' parameter
:returns: The response of your put
:rtype: dict
:raises: This will raise a
:class:`NewRelicAPIServerException<newrelic_api.exceptions.NewRelicAPIServerException>`
if there is an error from New ... |
def handle_error(result, exception_class=None):
"""
Extracts the last Windows error message into a python unicode string
:param result:
A function result, 0 or None indicates failure
:param exception_class:
The exception class to use for the exception if an error occurred
:return:... | Extracts the last Windows error message into a python unicode string
:param result:
A function result, 0 or None indicates failure
:param exception_class:
The exception class to use for the exception if an error occurred
:return:
A unicode string error message |
def instances_set(self, root, reservation):
"""Parse instance data out of an XML payload.
@param root: The root node of the XML payload.
@param reservation: The L{Reservation} associated with the instances
from the response.
@return: A C{list} of L{Instance}s.
"""
... | Parse instance data out of an XML payload.
@param root: The root node of the XML payload.
@param reservation: The L{Reservation} associated with the instances
from the response.
@return: A C{list} of L{Instance}s. |
def push(self, value):
"""
SNEAK value TO FRONT OF THE QUEUE
"""
if self.closed and not self.allow_add_after_close:
Log.error("Do not push to closed queue")
with self.lock:
self._wait_for_queue_space()
if not self.closed:
self.... | SNEAK value TO FRONT OF THE QUEUE |
def matches_at_fpr(fg_vals, bg_vals, fpr=0.01):
"""
Computes the hypergeometric p-value at a specific FPR (default 1%).
Parameters
----------
fg_vals : array_like
The list of values for the positive set.
bg_vals : array_like
The list of values for the negative set.
fpr... | Computes the hypergeometric p-value at a specific FPR (default 1%).
Parameters
----------
fg_vals : array_like
The list of values for the positive set.
bg_vals : array_like
The list of values for the negative set.
fpr : float, optional
The FPR (between 0.0 and 1.0).
... |
def p_kwl_kwl(self, p):
''' kwl : kwl SEPARATOR kwl
'''
_LOGGER.debug("kwl -> kwl ; kwl")
if p[3] is not None:
p[0] = p[3]
elif p[1] is not None:
p[0] = p[1]
else:
p[0] = TypedClass(None, TypedClass.UNKNOWN) | kwl : kwl SEPARATOR kwl |
def device_key(self, device_key):
"""
Sets the device_key of this DeviceData.
The fingerprint of the device certificate.
:param device_key: The device_key of this DeviceData.
:type: str
"""
if device_key is not None and len(device_key) > 512:
raise Va... | Sets the device_key of this DeviceData.
The fingerprint of the device certificate.
:param device_key: The device_key of this DeviceData.
:type: str |
def parse(system):
"""
Parse input file with the given format in system.files.input_format
"""
t, _ = elapsed()
input_format = system.files.input_format
add_format = system.files.add_format
# exit when no input format is given
if not input_format:
logger.error(
'No ... | Parse input file with the given format in system.files.input_format |
def normalize_locale(locale):
"""
Normalize locale
Extracts language code from passed in locale string to be used later
for dictionaries loading.
:param locale: string, locale (en, en_US)
:return: string, language code
"""
import r... | Normalize locale
Extracts language code from passed in locale string to be used later
for dictionaries loading.
:param locale: string, locale (en, en_US)
:return: string, language code |
def find_library_darwin(cls):
"""Loads the SEGGER DLL from the installed applications.
This method accounts for the all the different ways in which the DLL
may be installed depending on the version of the DLL. Always uses
the first directory found.
SEGGER's DLL is installed in... | Loads the SEGGER DLL from the installed applications.
This method accounts for the all the different ways in which the DLL
may be installed depending on the version of the DLL. Always uses
the first directory found.
SEGGER's DLL is installed in one of three ways dependent on which
... |
def fix_imports(script):
"""
Replace "from PyQt5 import" by "from pyqode.qt import".
:param script: script path
"""
with open(script, 'r') as f_script:
lines = f_script.read().splitlines()
new_lines = []
for l in lines:
if l.startswith("import "):
l = "from . " +... | Replace "from PyQt5 import" by "from pyqode.qt import".
:param script: script path |
def update_metadata(self, resource, keys_vals):
"""
Updates key-value pairs with the given resource.
Will attempt to update all key-value pairs even if some fail.
Keys must already exist.
Args:
resource (intern.resource.boss.BossResource)
keys_vals (dict... | Updates key-value pairs with the given resource.
Will attempt to update all key-value pairs even if some fail.
Keys must already exist.
Args:
resource (intern.resource.boss.BossResource)
keys_vals (dictionary): Collection of key-value pairs to update on
... |
def remove_from_bin(self, name):
""" Remove an object from the bin folder. """
self.__remove_path(os.path.join(self.root_dir, "bin", name)) | Remove an object from the bin folder. |
def create_archive(path, remove_path=True):
"""
Creates a tar.gz of the path using the path basename + "tar.gz"
The resulting file is in the parent directory of the original path, and
the original path is removed.
"""
root_path = os.path.dirname(path)
relative_path = os.path.basename(path)
... | Creates a tar.gz of the path using the path basename + "tar.gz"
The resulting file is in the parent directory of the original path, and
the original path is removed. |
def update_positions(self, time, xs, ys, zs, vxs, vys, vzs,
ethetas, elongans, eincls,
ds=None, Fs=None, ignore_effects=False):
"""
TODO: add documentation
all arrays should be for the current time, but iterable over all bodies
"""
... | TODO: add documentation
all arrays should be for the current time, but iterable over all bodies |
def RollbackAll(close=None):
"""
Rollback all transactions, according Local.conn
"""
if close:
warnings.simplefilter('default')
warnings.warn("close parameter will not need at all.", DeprecationWarning)
for k, v in engine_manager.items():
session = v.session(create=False)
... | Rollback all transactions, according Local.conn |
def _get_network_interface(name, resource_group):
'''
Get a network interface.
'''
public_ips = []
private_ips = []
netapi_versions = get_api_versions(kwargs={
'resource_provider': 'Microsoft.Network',
'resource_type': 'publicIPAddresses'
}
)
netapi_version = neta... | Get a network interface. |
def secretfile_args(parser):
"""Add Secretfile management command line arguments to parser"""
parser.add_argument('--secrets',
dest='secrets',
help='Path where secrets are stored',
default=os.path.join(os.getcwd(), ".secrets"))
parser.a... | Add Secretfile management command line arguments to parser |
def defaultSTDPKernel(preSynActivation,
postSynActivation,
dt,
inhibitoryPresyn=False,
inhibitoryPostsyn=False):
"""
This function implements a modified version of the STDP kernel from
Widloski & Fiete, 2014.
:param preSynAc... | This function implements a modified version of the STDP kernel from
Widloski & Fiete, 2014.
:param preSynActivation: Vector of pre-synaptic activations
:param postSynActivation: Vector of post-synaptic activations
:param dt: the difference in time between the two (in seconds), positive if
after and ne... |
def assets2s3():
""" Upload assets files to S3 """
import flask_s3
header("Assets2S3...")
print("")
print("Building assets files..." )
print("")
build_assets(application.app)
print("")
print("Uploading assets files to S3 ...")
flask_s3.create_all(application.app)
print("") | Upload assets files to S3 |
def _register_function(func, con):
"""Register a Python callable with a SQLite connection `con`.
Parameters
----------
func : callable
con : sqlalchemy.Connection
"""
nargs = number_of_arguments(func)
con.connection.connection.create_function(func.__name__, nargs, func) | Register a Python callable with a SQLite connection `con`.
Parameters
----------
func : callable
con : sqlalchemy.Connection |
def __add_sentence_root_node(self, sent_number):
"""
adds the root node of a sentence to the graph and the list of sentences
(``self.sentences``). the node has a ``tokens` attribute, which
contains a list of the tokens (token node IDs) of this sentence.
Parameters
------... | adds the root node of a sentence to the graph and the list of sentences
(``self.sentences``). the node has a ``tokens` attribute, which
contains a list of the tokens (token node IDs) of this sentence.
Parameters
----------
sent_number : int
the index of the sentence ... |
def cleanup_relations(self):
"""Cleanup listing relations"""
collections = self.collections
for relation in [x for col in collections.values()
for x in col.model.relations.values()]:
db.session.query(relation)\
.filter(~relation.listing... | Cleanup listing relations |
def FromString(cls, desc):
"""Create a new stimulus from a description string.
The string must have the format:
[time: ][system ]input X = Y
where X and Y are integers. The time, if given must
be a time_interval, which is an integer followed by a
time unit such as seco... | Create a new stimulus from a description string.
The string must have the format:
[time: ][system ]input X = Y
where X and Y are integers. The time, if given must
be a time_interval, which is an integer followed by a
time unit such as second(s), minute(s), etc.
Args:
... |
def RenderWidget(self):
"""Returns a QWidget subclass instance. Exact class depends on self.type"""
t = self.type
if t == int:
ret = QSpinBox()
ret.setMaximum(999999999)
ret.setValue(self.value)
elif t == float:
ret = QLineEdit()
... | Returns a QWidget subclass instance. Exact class depends on self.type |
def list(self, mask=None):
"""List existing placement groups
Calls SoftLayer_Account::getPlacementGroups
"""
if mask is None:
mask = "mask[id, name, createDate, rule, guestCount, backendRouter[id, hostname]]"
groups = self.client.call('Account', 'getPlacementGroups'... | List existing placement groups
Calls SoftLayer_Account::getPlacementGroups |
def get_email_domain(emailaddr):
"""
Return the domain component of an email address. Returns None if the
provided string cannot be parsed as an email address.
>>> get_email_domain('test@example.com')
'example.com'
>>> get_email_domain('test+trailing@example.com')
'example.com'
>>> get_... | Return the domain component of an email address. Returns None if the
provided string cannot be parsed as an email address.
>>> get_email_domain('test@example.com')
'example.com'
>>> get_email_domain('test+trailing@example.com')
'example.com'
>>> get_email_domain('Example Address <test@example.c... |
def draw(self):
""" Draw the Mesh if it's visible, from the perspective of the camera and lit by the light. The function sends the uniforms"""
if not self.vao:
self.vao = VAO(indices=self.array_indices)
self._fill_vao()
if self.visible:
if self.dynamic:
... | Draw the Mesh if it's visible, from the perspective of the camera and lit by the light. The function sends the uniforms |
def time_sp(self):
"""
Writing specifies the amount of time the motor will run when using the
`run-timed` command. Reading returns the current value. Units are in
milliseconds.
"""
self._time_sp, value = self.get_attr_int(self._time_sp, 'time_sp')
return value | Writing specifies the amount of time the motor will run when using the
`run-timed` command. Reading returns the current value. Units are in
milliseconds. |
def load_plugin(self, manifest, *args):
"""
Loads a plugin from the given manifest
:param manifest: The manifest to use to load the plugin
:param args: Arguments to pass to the plugin
"""
if self.get_plugin_loaded(manifest["name"]):
self._logger.debug("Plugin... | Loads a plugin from the given manifest
:param manifest: The manifest to use to load the plugin
:param args: Arguments to pass to the plugin |
def add_index(collection,
name,
fields,
transformer=None,
unique=False,
case_insensitive=False):
"""
Add a secondary index for a collection ``collection`` on one or
more ``fields``.
The values at each of the ``fields`` are loaded fro... | Add a secondary index for a collection ``collection`` on one or
more ``fields``.
The values at each of the ``fields`` are loaded from existing
objects and their object ids added to the index.
You can later iterate the objects of an index via
``each_indexed_object``.
If you update an object an... |
def pysal_G(self, **kwargs):
"""
Compute Getis and Ord’s G for GeoRaster
Usage:
geo.pysal_G(permutations = 1000, rook=True)
arguments passed to raster_weights() and pysal.G
See help(gr.raster_weights), help(pysal.G) for options
"""
if self.weights is Non... | Compute Getis and Ord’s G for GeoRaster
Usage:
geo.pysal_G(permutations = 1000, rook=True)
arguments passed to raster_weights() and pysal.G
See help(gr.raster_weights), help(pysal.G) for options |
def _clean_metadata(self):
"""
the long description doesn't load properly (gets unwanted indents),
so fix it.
"""
desc = self.metadata.get_long_description()
if not isinstance(desc, six.text_type):
desc = desc.decode('utf-8')
lines = io.StringIO(desc)
... | the long description doesn't load properly (gets unwanted indents),
so fix it. |
def write_stream(self, stream, validate=True):
"""
Write :attr:`metainfo` to a file-like object
Before any data is written, `stream` is truncated if possible.
:param stream: Writable file-like object (e.g. :class:`io.BytesIO`)
:param bool validate: Whether to run :meth:`validat... | Write :attr:`metainfo` to a file-like object
Before any data is written, `stream` is truncated if possible.
:param stream: Writable file-like object (e.g. :class:`io.BytesIO`)
:param bool validate: Whether to run :meth:`validate` first
:raises WriteError: if writing to `stream` fails
... |
def text(self, value):
"""Set Text content for Comment (validation of input)"""
if value in (None, '') or value.strip() == "":
raise AttributeError("Empty text value is invalid.")
self._text = value | Set Text content for Comment (validation of input) |
def get(self, copy=False):
"""Return the value of the attribute"""
array = getattr(self.owner, self.name)
if copy:
return array.copy()
else:
return array | Return the value of the attribute |
def retry(retries=10, wait=5, catch=None):
"""
Decorator to retry on exceptions raised
"""
catch = catch or (Exception,)
def real_retry(function):
def wrapper(*args, **kwargs):
for _ in range(retries):
try:
ret = function(*args, **kwargs)
... | Decorator to retry on exceptions raised |
def global_closeness_centrality(g, node=None, normalize=True):
"""
Calculates global closeness centrality for one or all nodes in the network.
See :func:`.node_global_closeness_centrality` for more information.
Parameters
----------
g : networkx.Graph
normalize : boolean
If True, n... | Calculates global closeness centrality for one or all nodes in the network.
See :func:`.node_global_closeness_centrality` for more information.
Parameters
----------
g : networkx.Graph
normalize : boolean
If True, normalizes centrality based on the average shortest path
length. Def... |
def purge(self):
"""Deletes all tasks in the queue."""
try:
return self._api.purge()
except AttributeError:
while True:
lst = self.list()
if len(lst) == 0:
break
for task in lst:
self.delete(task)
self.wait()
return self | Deletes all tasks in the queue. |
def estimate_lmax(self, method='lanczos'):
r"""Estimate the Laplacian's largest eigenvalue (cached).
The result is cached and accessible by the :attr:`lmax` property.
Exact value given by the eigendecomposition of the Laplacian, see
:func:`compute_fourier_basis`. That estimation is muc... | r"""Estimate the Laplacian's largest eigenvalue (cached).
The result is cached and accessible by the :attr:`lmax` property.
Exact value given by the eigendecomposition of the Laplacian, see
:func:`compute_fourier_basis`. That estimation is much faster than the
eigendecomposition.
... |
def format_color(text, color, use_color_setting):
"""Format text with color.
Args:
text - Text to be formatted with color if `use_color`
color - The color start string
use_color_setting - Whether or not to color
"""
if not use_color_setting:
return text
else:
... | Format text with color.
Args:
text - Text to be formatted with color if `use_color`
color - The color start string
use_color_setting - Whether or not to color |
def exam_reliability(x_axis, x_axis_new, reliable_distance, precision=0.0001):
"""When we do linear interpolation on x_axis and derive value for
x_axis_new, we also evaluate how can we trust those interpolated
data points. This is how it works:
For each new x_axis point in x_axis new, let's say xi. F... | When we do linear interpolation on x_axis and derive value for
x_axis_new, we also evaluate how can we trust those interpolated
data points. This is how it works:
For each new x_axis point in x_axis new, let's say xi. Find the closest
point in x_axis, suppose the distance is #dist. Compare this to
... |
def get_reward_and_done(board):
"""Given a representation of the board, returns reward and done."""
# Returns (reward, done) where:
# reward: -1 means lost, +1 means win, 0 means draw or continuing.
# done: True if the game is over, i.e. someone won or it is a draw.
# Sum all rows ...
all_sums = [np.sum(bo... | Given a representation of the board, returns reward and done. |
def connection_made(self, transport: asyncio.transports.Transport):
"""连接建立起来触发的回调函数.
用于设定一些参数,并将监听任务放入事件循环,如果设置了timeout,也会将timeout_callback放入事件循环
Parameters:
transport (asyncio.Transports): - 连接的传输对象
"""
self._transport = transport
self._remote_host = self... | 连接建立起来触发的回调函数.
用于设定一些参数,并将监听任务放入事件循环,如果设置了timeout,也会将timeout_callback放入事件循环
Parameters:
transport (asyncio.Transports): - 连接的传输对象 |
def build_duration_pretty(self):
"""Return the difference between build and build_done states, in a human readable format"""
from ambry.util import pretty_time
from time import time
if not self.state.building:
return None
built = self.state.built or time()
... | Return the difference between build and build_done states, in a human readable format |
def payment_init(self, wallet):
"""
Marks all accounts in wallet as available for being used as a payment
session.
:param wallet: Wallet to init payment in
:type wallet: str
:raises: :py:exc:`nano.rpc.RPCException`
>>> rpc.payment_init(
... wallet="... | Marks all accounts in wallet as available for being used as a payment
session.
:param wallet: Wallet to init payment in
:type wallet: str
:raises: :py:exc:`nano.rpc.RPCException`
>>> rpc.payment_init(
... wallet="000D1BAEC8EC208142C99059B393051BAC8380F9B5A2E6B2489A... |
def default_instance(cls):
"""
For use like a singleton, return the existing instance of the object
or a new instance
"""
if cls._instance is None:
with cls._instance_lock:
if cls._instance is None:
cls._instance = FlowsLogger()
... | For use like a singleton, return the existing instance of the object
or a new instance |
def call_hook(self, name, **kwargs):
""" Call all hooks registered with this name. Returns a list of the returns values of the hooks (in the order the hooks were added)"""
return [y for y in [x(**kwargs) for x, _ in self._hooks.get(name, [])] if y is not None] | Call all hooks registered with this name. Returns a list of the returns values of the hooks (in the order the hooks were added) |
def set_spcPct(self, value):
"""
Set spacing to *value* lines, e.g. 1.75 lines. A ./a:spcPts child is
removed if present.
"""
self._remove_spcPts()
spcPct = self.get_or_add_spcPct()
spcPct.val = value | Set spacing to *value* lines, e.g. 1.75 lines. A ./a:spcPts child is
removed if present. |
def iterrows(self, workbook=None):
"""
Yield rows as lists of data.
The data is exactly as it is in the source pandas DataFrames and
any formulas are not resolved.
"""
resolved_tables = []
max_height = 0
max_width = 0
# while yielding rows __form... | Yield rows as lists of data.
The data is exactly as it is in the source pandas DataFrames and
any formulas are not resolved. |
def _parse_lines(self, diff_lines):
"""
Given the diff lines output from `git diff` for a particular
source file, return a tuple of `(ADDED_LINES, DELETED_LINES)`
where `ADDED_LINES` and `DELETED_LINES` are lists of line
numbers added/deleted respectively.
Raises a `Git... | Given the diff lines output from `git diff` for a particular
source file, return a tuple of `(ADDED_LINES, DELETED_LINES)`
where `ADDED_LINES` and `DELETED_LINES` are lists of line
numbers added/deleted respectively.
Raises a `GitDiffError` if the diff lines are in an invalid format. |
def cape_cin(pressure, temperature, dewpt, parcel_profile):
r"""Calculate CAPE and CIN.
Calculate the convective available potential energy (CAPE) and convective inhibition (CIN)
of a given upper air profile and parcel path. CIN is integrated between the surface and
LFC, CAPE is integrated between the ... | r"""Calculate CAPE and CIN.
Calculate the convective available potential energy (CAPE) and convective inhibition (CIN)
of a given upper air profile and parcel path. CIN is integrated between the surface and
LFC, CAPE is integrated between the LFC and EL (or top of sounding). Intersection points of
the ... |
def find(cls, dtype):
"""Returns the NDS2 type corresponding to the given python type
"""
try:
return cls._member_map_[dtype]
except KeyError:
try:
dtype = numpy.dtype(dtype).type
except TypeError:
for ndstype in cls._me... | Returns the NDS2 type corresponding to the given python type |
def _make_value_pb(value):
"""Helper for :func:`_make_list_value_pbs`.
:type value: scalar value
:param value: value to convert
:rtype: :class:`~google.protobuf.struct_pb2.Value`
:returns: value protobufs
:raises ValueError: if value is not of a known scalar type.
"""
if value is None:... | Helper for :func:`_make_list_value_pbs`.
:type value: scalar value
:param value: value to convert
:rtype: :class:`~google.protobuf.struct_pb2.Value`
:returns: value protobufs
:raises ValueError: if value is not of a known scalar type. |
def same_guid(post, parameter=DEFAULT_SIMILARITY_TIMESPAN):
'''Skip posts with exactly same GUID.
Parameter: comparison timespan, seconds (int, 0 = inf, default: {0}).'''
from feedjack.models import Post
if isinstance(parameter, types.StringTypes): parameter = int(parameter.strip())
similar = Post.objects.filtere... | Skip posts with exactly same GUID.
Parameter: comparison timespan, seconds (int, 0 = inf, default: {0}). |
def _script_names(dist, script_name, is_gui):
"""Create the fully qualified name of the files created by
{console,gui}_scripts for the given ``dist``.
Returns the list of file names
"""
if dist_in_usersite(dist):
bin_dir = bin_user
else:
bin_dir = bin_py
exe_name = os.path.jo... | Create the fully qualified name of the files created by
{console,gui}_scripts for the given ``dist``.
Returns the list of file names |
def bar3_chart(self, title, labels, data1, file_name, data2, data3, legend=["", ""]):
"""
Generate a bar plot with three columns in each x position and save it to file_name
:param title: title to be used in the chart
:param labels: list of labels for the x axis
:param data1: val... | Generate a bar plot with three columns in each x position and save it to file_name
:param title: title to be used in the chart
:param labels: list of labels for the x axis
:param data1: values for the first columns
:param file_name: name of the file in which to save the chart
:p... |
def _UserUpdateIgnoredDirs(self, origIgnoredDirs = []):
"""
Add ignored directories to database table. Always called if the
database table is empty.
User can build a list of entries to add to the database table
(one entry at a time). Once finished they select the finish option
and all entries w... | Add ignored directories to database table. Always called if the
database table is empty.
User can build a list of entries to add to the database table
(one entry at a time). Once finished they select the finish option
and all entries will be added to the table. They can reset the
list at any time b... |
def liquid_precip_ratio(pr, prsn=None, tas=None, freq='QS-DEC'):
r"""Ratio of rainfall to total precipitation
The ratio of total liquid precipitation over the total precipitation. If solid precipitation is not provided,
then precipitation is assumed solid if the temperature is below 0°C.
Parameters
... | r"""Ratio of rainfall to total precipitation
The ratio of total liquid precipitation over the total precipitation. If solid precipitation is not provided,
then precipitation is assumed solid if the temperature is below 0°C.
Parameters
----------
pr : xarray.DataArray
Mean daily precipitation... |
def get_first_language(self, site_id=None):
"""
Return the first language for the current site.
This can be used for user interfaces, where the languages are displayed in tabs.
"""
if site_id is None:
site_id = getattr(settings, 'SITE_ID', None)
try:
... | Return the first language for the current site.
This can be used for user interfaces, where the languages are displayed in tabs. |
async def uint(self, elem, elem_type, params=None):
"""
Integer types
:param elem:
:param elem_type:
:param params:
:return:
"""
if self.writing:
return await x.dump_uint(self.iobj, elem, elem_type.WIDTH)
else:
return await ... | Integer types
:param elem:
:param elem_type:
:param params:
:return: |
def migrateUp(self):
"""
Copy this LoginAccount and all associated LoginMethods from my store
(which is assumed to be a SubStore, most likely a user store) into the
site store which contains it.
"""
siteStore = self.store.parent
def _():
# No convenien... | Copy this LoginAccount and all associated LoginMethods from my store
(which is assumed to be a SubStore, most likely a user store) into the
site store which contains it. |
def linguist_field_names(self):
"""
Returns linguist field names (example: "title" and "title_fr").
"""
return list(self.model._linguist.fields) + list(
utils.get_language_fields(self.model._linguist.fields)
) | Returns linguist field names (example: "title" and "title_fr"). |
def check_suspension(user_twitter_id_list):
"""
Looks up a list of user ids and checks whether they are currently suspended.
Input: - user_twitter_id_list: A python list of Twitter user ids in integer format to be looked-up.
Outputs: - suspended_user_twitter_id_list: A python list of suspended Twitter... | Looks up a list of user ids and checks whether they are currently suspended.
Input: - user_twitter_id_list: A python list of Twitter user ids in integer format to be looked-up.
Outputs: - suspended_user_twitter_id_list: A python list of suspended Twitter user ids in integer format.
- non_suspende... |
def bootstrap_counts_singletraj(dtraj, lagtime, n):
"""
Samples n counts at the given lagtime from the given trajectory
"""
# check if length is sufficient
L = len(dtraj)
if (lagtime > L):
raise ValueError(
'Cannot sample counts with lagtime ' + str(lagtime) + ' from a trajec... | Samples n counts at the given lagtime from the given trajectory |
def tomography_basis(basis, prep_fun=None, meas_fun=None):
"""
Generate a TomographyBasis object.
See TomographyBasis for further details.abs
Args:
prep_fun (callable) optional: the function which adds preparation
gates to a circuit.
meas_fun (callable) optional: the functi... | Generate a TomographyBasis object.
See TomographyBasis for further details.abs
Args:
prep_fun (callable) optional: the function which adds preparation
gates to a circuit.
meas_fun (callable) optional: the function which adds measurement
gates to a circuit.
Returns:... |
def text(self, prompt, default=None):
"""Prompts the user for some text, with optional default"""
prompt = prompt if prompt is not None else 'Enter some text'
prompt += " [{0}]: ".format(default) if default is not None else ': '
return self.input(curry(filter_text, default=default), prom... | Prompts the user for some text, with optional default |
def blank(columns=1, name=None):
"""
Creates the grammar for a blank field.
These are for constant empty strings which should be ignored, as they are
used just as fillers.
:param columns: number of columns, which is the required number of
whitespaces
:param name: name for the field
:re... | Creates the grammar for a blank field.
These are for constant empty strings which should be ignored, as they are
used just as fillers.
:param columns: number of columns, which is the required number of
whitespaces
:param name: name for the field
:return: grammar for the blank field |
def login(self, user, passwd):
'''Logs the user into SecurityCenter and stores the needed token and cookies.'''
resp = self.post('token', json={'username': user, 'password': passwd})
self._token = resp.json()['response']['token'] | Logs the user into SecurityCenter and stores the needed token and cookies. |
def beta_to_uni(text, strict=False):
"""
Converts the given text from betacode to unicode.
Args:
text: The beta code text to convert. All of this text must be betacode.
strict: Flag to allow for flexible diacritic order on input.
Returns:
The converted text.
"""
# Check if the requ... | Converts the given text from betacode to unicode.
Args:
text: The beta code text to convert. All of this text must be betacode.
strict: Flag to allow for flexible diacritic order on input.
Returns:
The converted text. |
def __get_issue_notes(self, issue_id):
"""Get issue notes"""
notes = []
group_notes = self.client.notes(GitLabClient.ISSUES, issue_id)
for raw_notes in group_notes:
for note in json.loads(raw_notes):
note_id = note['id']
note['award_emoji_d... | Get issue notes |
def safe_lshift(a, b):
"""safe version of lshift"""
if b > MAX_SHIFT:
raise RuntimeError("Invalid left shift, max left shift is {}".format(MAX_SHIFT))
return a << b | safe version of lshift |
def load_backend(backend_name):
""" load pool backend."""
try:
if len(backend_name.split(".")) > 1:
mod = import_module(backend_name)
else:
mod = import_module("spamc.backend_%s" % backend_name)
return mod
except ImportError:
error_msg = "%s isn't a sp... | load pool backend. |
def _set_origin(self, v, load=False):
"""
Setter method for origin, mapped from YANG variable /routing_system/route_map/content/set/origin (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_origin is considered as a private
method. Backends looking to popula... | Setter method for origin, mapped from YANG variable /routing_system/route_map/content/set/origin (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_origin is considered as a private
method. Backends looking to populate this variable should
do so via calling this... |
def create_file_api(conf):
""" Creates a SmartlingFileApi from the given config
"""
api_key = conf.config.get('api-key', os.environ.get('SMARTLING_API_KEY'))
project_id = conf.config.get('project-id', os.environ.get('SMARTLING_PROJECT_ID'))
if not project_id or not api_key:
raise Smarterlin... | Creates a SmartlingFileApi from the given config |
def session_hook(exception):
"""
Expects an exception with an authorization_paramaters field in its raw_json
"""
safeprint(
"The resource you are trying to access requires you to "
"re-authenticate with specific identities."
)
params = exception.raw_json["authorization_parameter... | Expects an exception with an authorization_paramaters field in its raw_json |
def wait(self, jobs=None, timeout=-1):
"""waits on one or more `jobs`, for up to `timeout` seconds.
Parameters
----------
jobs : int, str, or list of ints and/or strs, or one or more AsyncResult objects
ints are indices to self.history
strs are msg_ids
... | waits on one or more `jobs`, for up to `timeout` seconds.
Parameters
----------
jobs : int, str, or list of ints and/or strs, or one or more AsyncResult objects
ints are indices to self.history
strs are msg_ids
default: wait on all outstanding me... |
def argument_run(self, sp_r):
"""
.. _argument_run:
Converts Arguments according to ``to_int``
"""
arg_run = []
for line in sp_r:
logging.debug("argument run: handling: " + str(line))
if(line[1] == "data"):
arg_run.append( (line[0], line[1], line[2], line[2].get_words(line[3])))
continue
... | .. _argument_run:
Converts Arguments according to ``to_int`` |
def spawn(self, args, executable=None, stdin=None, stdout=None, stderr=None,
shell=False, cwd=None, env=None, flags=0, extra_handles=None):
"""Spawn a new child process.
The executable to spawn and its arguments are determined by *args*,
*executable* and *shell*.
When *sh... | Spawn a new child process.
The executable to spawn and its arguments are determined by *args*,
*executable* and *shell*.
When *shell* is set to ``False`` (the default), *args* is normally a
sequence and it contains both the program to execute (at index 0), and
its arguments.
... |
def replace_surrogate_encode(mystring, exc):
"""
Returns a (unicode) string, not the more logical bytes, because the codecs
register_error functionality expects this.
"""
decoded = []
for ch in mystring:
# if PY3:
# code = ch
# else:
code = ord(ch)
# ... | Returns a (unicode) string, not the more logical bytes, because the codecs
register_error functionality expects this. |
def _interception(self, joinpoint):
"""Intercept call of joinpoint callee in doing pre/post conditions.
"""
if self.pre_cond is not None:
self.pre_cond(joinpoint)
result = joinpoint.proceed()
if self.post_cond is not None:
joinpoint.exec_ctx[Condition.R... | Intercept call of joinpoint callee in doing pre/post conditions. |
def Betainc(a, b, x):
"""
Complemented, incomplete gamma op.
"""
return sp.special.betainc(a, b, x), | Complemented, incomplete gamma op. |
def merge_insert(ins_chunks, doc):
""" doc is the already-handled document (as a list of text chunks);
here we add <ins>ins_chunks</ins> to the end of that. """
# Though we don't throw away unbalanced_start or unbalanced_end
# (we assume there is accompanying markup later or earlier in the
# docume... | doc is the already-handled document (as a list of text chunks);
here we add <ins>ins_chunks</ins> to the end of that. |
def get_permission_required(cls):
"""
Get permission required property.
Must return an iterable.
"""
if cls.permission_required is None:
raise ImproperlyConfigured(
"{0} is missing the permission_required attribute. "
"Define {0}.permis... | Get permission required property.
Must return an iterable. |
def collapse(self, indices, values):
"""Partly collapse the interval product to single values.
Note that no changes are made in-place.
Parameters
----------
indices : int or sequence of ints
The indices of the dimensions along which to collapse.
values : `ar... | Partly collapse the interval product to single values.
Note that no changes are made in-place.
Parameters
----------
indices : int or sequence of ints
The indices of the dimensions along which to collapse.
values : `array-like` or float
The values to whi... |
def prepare(self, strict=True):
""" preparation for loaded json
:param bool strict: when in strict mode, exception would be raised if not valid.
"""
self.__root = self.prepare_obj(self.raw, self.__url)
self.validate(strict=strict)
if hasattr(self.__root, 'schemes') and... | preparation for loaded json
:param bool strict: when in strict mode, exception would be raised if not valid. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.