code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def _bnot8(ins):
""" Negates (BITWISE NOT) top of the stack (8 bits in AF)
"""
output = _8bit_oper(ins.quad[2])
output.append('cpl') # Gives carry only if A = 0
output.append('push af')
return output | Negates (BITWISE NOT) top of the stack (8 bits in AF) |
def emit_accepted(self):
"""
Sends signal that the file dialog was closed properly.
Sends:
filename
"""
if self.result():
filename = self.selectedFiles()[0]
if os.path.isdir(os.path.dirname(filename)):
self.dlg_accepted.emit(filena... | Sends signal that the file dialog was closed properly.
Sends:
filename |
def merge_cycles(self):
"""Work on this graph and remove cycles, with nodes containing concatonated lists of payloads"""
while True:
### remove any self edges
own_edges = self.get_self_edges()
if len(own_edges) > 0:
for e in own_edges: self.remove_edge(e)
c = ... | Work on this graph and remove cycles, with nodes containing concatonated lists of payloads |
def process_gatt_service(services, event):
"""Process a BGAPI event containing a GATT service description and add it to a dictionary
Args:
services (dict): A dictionary of discovered services that is updated with this event
event (BGAPIPacket): An event containing a GATT service
"""
l... | Process a BGAPI event containing a GATT service description and add it to a dictionary
Args:
services (dict): A dictionary of discovered services that is updated with this event
event (BGAPIPacket): An event containing a GATT service |
def _get(self, field):
"""
Return the value for the queried field.
Get the value of a given field. The list of all queryable fields is
documented in the beginning of the model class.
>>> out = m._get('graph')
Parameters
----------
field : string
... | Return the value for the queried field.
Get the value of a given field. The list of all queryable fields is
documented in the beginning of the model class.
>>> out = m._get('graph')
Parameters
----------
field : string
Name of the field to be retrieved.
... |
def prox_xline(x, step):
"""Projection onto line in x"""
if not np.isscalar(x):
x= x[0]
if x > 0.5:
return np.array([0.5])
else:
return np.array([x]) | Projection onto line in x |
def read_retry(sensor, pin, retries=15, delay_seconds=2, platform=None):
"""Read DHT sensor of specified sensor type (DHT11, DHT22, or AM2302) on
specified pin and return a tuple of humidity (as a floating point value
in percent) and temperature (as a floating point value in Celsius).
Unlike the read fu... | Read DHT sensor of specified sensor type (DHT11, DHT22, or AM2302) on
specified pin and return a tuple of humidity (as a floating point value
in percent) and temperature (as a floating point value in Celsius).
Unlike the read function, this read_retry function will attempt to read
multiple times (up to ... |
def clone(self):
"""
Create a complete copy of self.
:returns: A MaterialPackage that is identical to self.
"""
result = copy.copy(self)
result.size_class_masses = copy.deepcopy(self.size_class_masses)
return result | Create a complete copy of self.
:returns: A MaterialPackage that is identical to self. |
def generate_csv(path, out):
"""\
Walks through the `path` and generates the CSV file `out`
"""
def is_berlin_cable(filename):
return 'BERLIN' in filename
writer = UnicodeWriter(open(out, 'wb'), delimiter=';')
writer.writerow(('Reference ID', 'Created', 'Origin', 'Subject'))
for cabl... | \
Walks through the `path` and generates the CSV file `out` |
def get(self, request, format=None):
""" get HTTP method """
action = request.query_params.get('action', 'unread')
# action can be only "unread" (default), "count" and "all"
action = action if action == 'count' or action == 'all' else 'unread'
# mark as read parameter, defaults t... | get HTTP method |
def binaryEntropyVectorized(x):
"""
Calculate entropy for a list of binary random variables
:param x: (numpy array) the probability of the variable to be 1.
:return: entropy: (numpy array) entropy
"""
entropy = - x*np.log2(x) - (1-x)*np.log2(1-x)
entropy[x*(1 - x) == 0] = 0
return entropy | Calculate entropy for a list of binary random variables
:param x: (numpy array) the probability of the variable to be 1.
:return: entropy: (numpy array) entropy |
def choice(*es):
"""
Create a PEG function to match an ordered choice.
"""
msg = 'Expected one of: {}'.format(', '.join(map(repr, es)))
def match_choice(s, grm=None, pos=0):
errs = []
for e in es:
try:
return e(s, grm, pos)
except PegreError as... | Create a PEG function to match an ordered choice. |
def _request_api(self, **kwargs):
"""Wrap the calls the url, with the given arguments.
:param str url: Url to call with the given arguments
:param str method: [POST | GET] Method to use on the request
:param int status: Expected status code
"""
_url = kwargs.get('url')
... | Wrap the calls the url, with the given arguments.
:param str url: Url to call with the given arguments
:param str method: [POST | GET] Method to use on the request
:param int status: Expected status code |
def get_description(self):
"""
Tries to get WF description from 'collabration' or 'process' or 'pariticipant'
Returns str: WF description
"""
paths = ['bpmn:collaboration/bpmn:participant/bpmn:documentation',
'bpmn:collaboration/bpmn:documentation',
... | Tries to get WF description from 'collabration' or 'process' or 'pariticipant'
Returns str: WF description |
def _get_descending_key(gettime=time.time):
"""Returns a key name lexically ordered by time descending.
This lets us have a key name for use with Datastore entities which returns
rows in time descending order when it is scanned in lexically ascending order,
allowing us to bypass index building for descending i... | Returns a key name lexically ordered by time descending.
This lets us have a key name for use with Datastore entities which returns
rows in time descending order when it is scanned in lexically ascending order,
allowing us to bypass index building for descending indexes.
Args:
gettime: Used for testing.
... |
def chat_unfurl(
self, *, channel: str, ts: str, unfurls: dict, **kwargs
) -> SlackResponse:
"""Provide custom unfurl behavior for user-posted URLs.
Args:
channel (str): The Channel ID of the message. e.g. 'C1234567890'
ts (str): Timestamp of the message to add unfur... | Provide custom unfurl behavior for user-posted URLs.
Args:
channel (str): The Channel ID of the message. e.g. 'C1234567890'
ts (str): Timestamp of the message to add unfurl behavior to. e.g. '1234567890.123456'
unfurls (dict): a dict of the specific URLs you're offering an u... |
def add_to_linestring(position_data, kml_linestring):
'''add a point to the kml file'''
global kml
# add altitude offset
position_data[2] += float(args.aoff)
kml_linestring.coords.addcoordinates([position_data]) | add a point to the kml file |
def fit_params_to_1d_data(logX):
"""
Fit skewed normal distributions to 1-D capactity data,
and return the distribution parameters.
Args
----
logX:
Logarithm of one-dimensional capacity data,
indexed by module and phase resolution index
"""
m_max = logX.shape[0]
p... | Fit skewed normal distributions to 1-D capactity data,
and return the distribution parameters.
Args
----
logX:
Logarithm of one-dimensional capacity data,
indexed by module and phase resolution index |
def avail(search=None, verbose=False):
'''
Return a list of available images
search : string
search keyword
verbose : boolean (False)
toggle verbose output
CLI Example:
.. code-block:: bash
salt '*' imgadm.avail [percona]
salt '*' imgadm.avail verbose=True
... | Return a list of available images
search : string
search keyword
verbose : boolean (False)
toggle verbose output
CLI Example:
.. code-block:: bash
salt '*' imgadm.avail [percona]
salt '*' imgadm.avail verbose=True |
def pack(self):
'''pack a FD FDM buffer from current values'''
for i in range(len(self.values)):
if math.isnan(self.values[i]):
self.values[i] = 0
return struct.pack(self.pack_string, *self.values) | pack a FD FDM buffer from current values |
def getCompleteFile(self, basepath):
"""Get filename indicating all comics are downloaded."""
dirname = getDirname(self.getName())
return os.path.join(basepath, dirname, "complete.txt") | Get filename indicating all comics are downloaded. |
def execute_javascript(self, *args, **kwargs):
'''
Execute a javascript string in the context of the browser tab.
'''
ret = self.__exec_js(*args, **kwargs)
return ret | Execute a javascript string in the context of the browser tab. |
def word_to_id(self, word):
"""Returns the integer word id of a word string."""
if word in self.vocab:
return self.vocab[word]
else:
return self.unk_id | Returns the integer word id of a word string. |
def node_link_graph(data: Mapping[str, Any]) -> BELGraph:
"""Return graph from node-link data format.
Adapted from :func:`networkx.readwrite.json_graph.node_link_graph`
"""
graph = BELGraph()
graph.graph = data.get('graph', {})
graph.graph[GRAPH_ANNOTATION_LIST] = {
keyword: set(values)... | Return graph from node-link data format.
Adapted from :func:`networkx.readwrite.json_graph.node_link_graph` |
def cmd_ublox(self, args):
'''control behaviour of the module'''
if len(args) == 0:
print(self.usage())
elif args[0] == "status":
print(self.cmd_status())
elif args[0] == "set":
self.ublox_settings.command(args[1:])
elif args[0] == "reset":
... | control behaviour of the module |
def get_user_best(self, username, *, mode=OsuMode.osu, limit=50):
"""Get a user's best scores.
Parameters
----------
username : str or int
A `str` representing the user's username, or an `int` representing the user's id.
mode : :class:`osuapi.enums.OsuMode`
... | Get a user's best scores.
Parameters
----------
username : str or int
A `str` representing the user's username, or an `int` representing the user's id.
mode : :class:`osuapi.enums.OsuMode`
The osu! game mode for which to look up. Defaults to osu!standard.
... |
def solution(self, e, v, extra_constraints=(), exact=None):
"""
Return True if `v` is a solution of `expr` with the extra constraints, False otherwise.
:param e: An expression (an AST) to evaluate
:param v: The proposed solution (an AST)
:para... | Return True if `v` is a solution of `expr` with the extra constraints, False otherwise.
:param e: An expression (an AST) to evaluate
:param v: The proposed solution (an AST)
:param extra_constraints: Extra constraints (as ASTs) to add to the solver for this... |
def add_phenotype(self, ind_obj, phenotype_id):
"""Add a phenotype term to the case."""
if phenotype_id.startswith('HP:') or len(phenotype_id) == 7:
logger.debug('querying on HPO term')
hpo_results = phizz.query_hpo([phenotype_id])
else:
logger.debug('querying... | Add a phenotype term to the case. |
def format_camel_case(text):
"""
Example::
ThisIsVeryGood
**中文文档**
将文本格式化为各单词首字母大写, 拼接而成的长变量名。
"""
text = text.strip()
if len(text) == 0: # if empty string, return it
raise ValueError("can not be empty string!")
else:
text = text.lower() # lower all char
... | Example::
ThisIsVeryGood
**中文文档**
将文本格式化为各单词首字母大写, 拼接而成的长变量名。 |
def _control_vm(self, command, expected=None):
"""
Executes a command with QEMU monitor when this VM is running.
:param command: QEMU monitor command (e.g. info status, stop etc.)
:param expected: An array of expected strings
:returns: result of the command (matched object or N... | Executes a command with QEMU monitor when this VM is running.
:param command: QEMU monitor command (e.g. info status, stop etc.)
:param expected: An array of expected strings
:returns: result of the command (matched object or None) |
def clustered_vert(script, cell_size=1.0, strategy='AVERAGE', selected=False):
""" "Create a new layer populated with a subsampling of the vertexes of the
current mesh
The subsampling is driven by a simple one-per-gridded cell strategy.
Args:
script: the FilterScript object or script filen... | "Create a new layer populated with a subsampling of the vertexes of the
current mesh
The subsampling is driven by a simple one-per-gridded cell strategy.
Args:
script: the FilterScript object or script filename to write
the filter to.
cell_size (float): The size of the cell... |
def execute_nb(fname, metadata=None, save=True, show_doc_only=False):
"Execute notebook `fname` with `metadata` for preprocessing."
# Any module used in the notebook that isn't inside must be in the same directory as this script
with open(fname) as f: nb = nbformat.read(f, as_version=4)
ep_class = Execu... | Execute notebook `fname` with `metadata` for preprocessing. |
def _pull(keys):
"""helper method for implementing `client.pull` via `client.apply`"""
user_ns = globals()
if isinstance(keys, (list,tuple, set)):
for key in keys:
if not user_ns.has_key(key):
raise NameError("name '%s' is not defined"%key)
return map(user_ns.get,... | helper method for implementing `client.pull` via `client.apply` |
def disassociate_failure_node(self, parent, child):
"""Remove a failure node link.
The resulatant 2 nodes will both become root nodes.
=====API DOCS=====
Remove a failure node link.
:param parent: Primary key of parent node to disassociate failure node from.
:type paren... | Remove a failure node link.
The resulatant 2 nodes will both become root nodes.
=====API DOCS=====
Remove a failure node link.
:param parent: Primary key of parent node to disassociate failure node from.
:type parent: int
:param child: Primary key of child node to be di... |
def parse_list_line_windows(self, b):
"""
Parsing Microsoft Windows `dir` output
:param b: response line
:type b: :py:class:`bytes` or :py:class:`str`
:return: (path, info)
:rtype: (:py:class:`pathlib.PurePosixPath`, :py:class:`dict`)
"""
line = b.decode... | Parsing Microsoft Windows `dir` output
:param b: response line
:type b: :py:class:`bytes` or :py:class:`str`
:return: (path, info)
:rtype: (:py:class:`pathlib.PurePosixPath`, :py:class:`dict`) |
def load_balancer_present(name, resource_group, sku=None, frontend_ip_configurations=None, backend_address_pools=None,
load_balancing_rules=None, probes=None, inbound_nat_rules=None, inbound_nat_pools=None,
outbound_nat_rules=None, tags=None, connection_auth=None, **k... | .. versionadded:: 2019.2.0
Ensure a load balancer exists.
:param name:
Name of the load balancer.
:param resource_group:
The resource group assigned to the load balancer.
:param sku:
The load balancer SKU, which can be 'Basic' or 'Standard'.
:param tags:
A dictio... |
def runfile(filename, args=None, wdir=None, namespace=None):
"""
Run filename
args: command line arguments (string)
wdir: working directory
"""
try:
if hasattr(filename, 'decode'):
filename = filename.decode('utf-8')
except (UnicodeError, TypeError):
pass
glob... | Run filename
args: command line arguments (string)
wdir: working directory |
def stop(self, timeout=None):
"""
Send the GET request required to stop the scan
If timeout is not specified we just send the request and return. When
it is the method will wait for (at most) :timeout: seconds until the
scan changes it's status/stops. If the timeout is reached t... | Send the GET request required to stop the scan
If timeout is not specified we just send the request and return. When
it is the method will wait for (at most) :timeout: seconds until the
scan changes it's status/stops. If the timeout is reached then an
exception is raised.
:para... |
def _axis_in_detector(geometry):
"""A vector in the detector plane that points along the rotation axis."""
du, dv = geometry.det_axes_init
axis = geometry.axis
c = np.array([np.vdot(axis, du), np.vdot(axis, dv)])
cnorm = np.linalg.norm(c)
# Check for numerical errors
assert cnorm != 0
... | A vector in the detector plane that points along the rotation axis. |
def init_app(self, app):
"""Flask application initialization."""
self.init_config(app)
app.extensions['invenio-github'] = self
@app.before_first_request
def connect_signals():
"""Connect OAuthClient signals."""
from invenio_oauthclient.models import Remot... | Flask application initialization. |
def pip_install_requirements(requirements, constraints=None, **options):
"""Install a requirements file.
:param constraints: Path to pip constraints file.
http://pip.readthedocs.org/en/stable/user_guide/#constraints-files
"""
command = ["install"]
available_options = ('proxy', 'src', 'log', )
... | Install a requirements file.
:param constraints: Path to pip constraints file.
http://pip.readthedocs.org/en/stable/user_guide/#constraints-files |
def prettify(root, encoding='utf-8'):
"""
Return a pretty-printed XML string for the Element.
@see: http://www.doughellmann.com/PyMOTW/xml/etree/ElementTree/create.html
"""
if isinstance(root, ElementTree.Element):
node = ElementTree.tostring(root, 'utf-8')
else:
node = root
... | Return a pretty-printed XML string for the Element.
@see: http://www.doughellmann.com/PyMOTW/xml/etree/ElementTree/create.html |
def download_user_playlists_by_search(self, user_name):
"""Download user's playlists by his/her name.
:params user_name: user name.
"""
try:
user = self.crawler.search_user(user_name, self.quiet)
except RequestException as exception:
click.echo(exception... | Download user's playlists by his/her name.
:params user_name: user name. |
def abbreviated_interface_name(interface, addl_name_map=None, addl_reverse_map=None):
"""Function to return an abbreviated representation of the interface name.
:param interface: The interface you are attempting to abbreviate.
:param addl_name_map (optional): A dict containing key/value pairs that updates
... | Function to return an abbreviated representation of the interface name.
:param interface: The interface you are attempting to abbreviate.
:param addl_name_map (optional): A dict containing key/value pairs that updates
the base mapping. Used if an OS has specific differences. e.g. {"Po": "PortChannel"} vs
... |
def get_raw_path(self, include_self=False):
"""Retrieves the base mount path of the volume. Typically equals to :func:`Disk.get_fs_path` but may also be the
path to a logical volume. This is used to determine the source path for a mount call.
The value returned is normally based on the parent's... | Retrieves the base mount path of the volume. Typically equals to :func:`Disk.get_fs_path` but may also be the
path to a logical volume. This is used to determine the source path for a mount call.
The value returned is normally based on the parent's paths, e.g. if this volume is mounted to a more specif... |
def create_role(name):
"""
Create a new role.
"""
role = role_manager.create(name=name)
if click.confirm(f'Are you sure you want to create {role!r}?'):
role_manager.save(role, commit=True)
click.echo(f'Successfully created {role!r}')
else:
click.echo('Cancelled.') | Create a new role. |
def handle(self, state, message=False):
"""
Handle a state update.
:param state: the new chat state
:type state: :class:`~aioxmpp.chatstates.ChatState`
:param message: pass true to indicate that we handle the
:data:`ACTIVE` state that is implied by
... | Handle a state update.
:param state: the new chat state
:type state: :class:`~aioxmpp.chatstates.ChatState`
:param message: pass true to indicate that we handle the
:data:`ACTIVE` state that is implied by
sending a content message.
:type ... |
def getmany(self, *keys):
"""
Return a list of values corresponding to the keys in the iterable of
*keys*.
If a key is not present in the collection, its corresponding value will
be :obj:`None`.
.. note::
This method is not implemented by standard Python dict... | Return a list of values corresponding to the keys in the iterable of
*keys*.
If a key is not present in the collection, its corresponding value will
be :obj:`None`.
.. note::
This method is not implemented by standard Python dictionary
classes. |
def _get_listlike_indexer(self, key, axis, raise_missing=False):
"""
Transform a list-like of keys into a new index and an indexer.
Parameters
----------
key : list-like
Target labels
axis: int
Dimension on which the indexing is being made
... | Transform a list-like of keys into a new index and an indexer.
Parameters
----------
key : list-like
Target labels
axis: int
Dimension on which the indexing is being made
raise_missing: bool
Whether to raise a KeyError if some labels are not f... |
def iter_sys(self):
"""
Iterate over sys_name, overall_sys, histo_sys.
overall_sys or histo_sys may be None for any given sys_name.
"""
names = self.sys_names()
for name in names:
osys = self.GetOverallSys(name)
hsys = self.GetHistoSys(name)
... | Iterate over sys_name, overall_sys, histo_sys.
overall_sys or histo_sys may be None for any given sys_name. |
def descend(self, remote, force=False):
""" Descend, possibly creating directories as needed """
remote_dirs = remote.split('/')
for directory in remote_dirs:
try:
self.conn.cwd(directory)
except Exception:
if force:
sel... | Descend, possibly creating directories as needed |
def striter(self):
"""Iterate over each (optionally padded) string element in RangeSet."""
pad = self.padding or 0
for i in self._sorted():
yield "%0*d" % (pad, i) | Iterate over each (optionally padded) string element in RangeSet. |
def make_abstract_dist(req_to_install):
"""Factory to make an abstract dist object.
Preconditions: Either an editable req with a source_dir, or satisfied_by or
a wheel link, or a non-editable req with a source_dir.
:return: A concrete DistAbstraction.
"""
if req_to_install.editable:
re... | Factory to make an abstract dist object.
Preconditions: Either an editable req with a source_dir, or satisfied_by or
a wheel link, or a non-editable req with a source_dir.
:return: A concrete DistAbstraction. |
def download_image(self, image_type, image):
"""
Read file of a project and download it
:param image_type: Image type
:param image: The path of the image
:returns: A file stream
"""
url = self._getUrl("/{}/images/{}".format(image_type, image))
response =... | Read file of a project and download it
:param image_type: Image type
:param image: The path of the image
:returns: A file stream |
def rewrite_kwargs(conn_type, kwargs, module_name=None):
"""
Manipulate connection keywords.
Modifieds keywords based on connection type.
There is an assumption here that the client has
already been created and that these keywords are being
passed into methods for interacting with various ... | Manipulate connection keywords.
Modifieds keywords based on connection type.
There is an assumption here that the client has
already been created and that these keywords are being
passed into methods for interacting with various services.
Current modifications:
- if conn_type is not cloud... |
def get_next_job_by_port(plugin_name, port, verify_job=True, conn=None):
"""
Deprecated - Use get_next_job
"""
return get_next_job(plugin_name, None, port, verify_job, conn) | Deprecated - Use get_next_job |
def contains(ell, p, shell_only=False):
"""
Check to see whether point is inside
conic.
:param exact: Only solutions exactly on conic
are considered (default: False).
"""
v = augment(p)
_ = ell.solve(v)
return N.allclose(_,0) if shell_only else ... | Check to see whether point is inside
conic.
:param exact: Only solutions exactly on conic
are considered (default: False). |
def _update_element(name, element_type, data, server=None):
'''
Update an element, including it's properties
'''
# Urlencode the name (names may have slashes)
name = quote(name, safe='')
# Update properties first
if 'properties' in data:
properties = []
for key, value in dat... | Update an element, including it's properties |
def load(self, context):
"""Returns the debugger plugin, if possible.
Args:
context: The TBContext flags including `add_arguments`.
Returns:
A DebuggerPlugin instance or None if it couldn't be loaded.
"""
if not (context.flags.debugger_data_server_grpc_port > 0 or
context.f... | Returns the debugger plugin, if possible.
Args:
context: The TBContext flags including `add_arguments`.
Returns:
A DebuggerPlugin instance or None if it couldn't be loaded. |
def to_array(self, channels=2):
"""Return the array of multipliers for the dynamic"""
if channels == 1:
return self.volume_frames.reshape(-1, 1)
if channels == 2:
return np.tile(self.volume_frames, (2, 1)).T
raise Exception(
"RawVolume doesn't know wha... | Return the array of multipliers for the dynamic |
async def extend(self, additional_time):
"""
Adds more time to an already acquired lock.
``additional_time`` can be specified as an integer or a float, both
representing the number of seconds to add.
"""
if self.local.token is None:
raise LockError("Cannot ex... | Adds more time to an already acquired lock.
``additional_time`` can be specified as an integer or a float, both
representing the number of seconds to add. |
def readlist(self, fmt, **kwargs):
"""Interpret next bits according to format string(s) and return list.
fmt -- A single string or list of strings with comma separated tokens
describing how to interpret the next bits in the bitstring. Items
can also be integers, for readin... | Interpret next bits according to format string(s) and return list.
fmt -- A single string or list of strings with comma separated tokens
describing how to interpret the next bits in the bitstring. Items
can also be integers, for reading new bitstring of the given length.
k... |
def insert_into_table(table, data):
"""
SQL query for inserting data into table
:return: None
"""
fields = data['fields']
fields['date'] = datetime.datetime.now().date()
query = '('
for key in fields.keys():
query += key + ','
query = query[:-1:] + ")"
client.execute... | SQL query for inserting data into table
:return: None |
def ended(self):
"""We call this method when the function is finished."""
self._end_time = time.time()
if setting(key='memory_profile', expected_type=bool):
self._end_memory = get_free_memory() | We call this method when the function is finished. |
def register_palette(self):
"""Converts pygmets style to urwid palatte"""
default = 'default'
palette = list(self.palette)
mapping = CONFIG['rgb_to_short']
for tok in self.style.styles.keys():
for t in tok.split()[::-1]:
st = self.style.styles[t]
... | Converts pygmets style to urwid palatte |
def compute_eigenvalues(in_prefix, out_prefix):
"""Computes the Eigenvalues using smartpca from Eigensoft.
:param in_prefix: the prefix of the input files.
:param out_prefix: the prefix of the output files.
:type in_prefix: str
:type out_prefix: str
Creates a "parameter file" used by smartpca... | Computes the Eigenvalues using smartpca from Eigensoft.
:param in_prefix: the prefix of the input files.
:param out_prefix: the prefix of the output files.
:type in_prefix: str
:type out_prefix: str
Creates a "parameter file" used by smartpca and runs it. |
def lookup(self, key):
"""
Generate hash code for a key from the Minimal Perfect Hash (MPH)
Parameters
----------
Key : object
The item to generate a key for, this works best for keys that
are strings, or can be transformed fairly directly into bytes
... | Generate hash code for a key from the Minimal Perfect Hash (MPH)
Parameters
----------
Key : object
The item to generate a key for, this works best for keys that
are strings, or can be transformed fairly directly into bytes
Returns : int
The code for... |
def is_installed(config):
"""Check for pindel installation on machine.
:param config: (dict) information from yaml(items[0]['config'])
:returns: (boolean) if pindel is installed
"""
try:
config_utils.get_program("pindel2vcf", config)
config_utils.get_program("pindel", config)
... | Check for pindel installation on machine.
:param config: (dict) information from yaml(items[0]['config'])
:returns: (boolean) if pindel is installed |
def _get_max_subplot_ids(fig):
"""
Given an input figure, return a dict containing the max subplot number
for each subplot type in the figure
Parameters
----------
fig: dict
A plotly figure dict
Returns
-------
dict
A dict from subplot type strings to integers indic... | Given an input figure, return a dict containing the max subplot number
for each subplot type in the figure
Parameters
----------
fig: dict
A plotly figure dict
Returns
-------
dict
A dict from subplot type strings to integers indicating the largest
subplot number in... |
def get_credentials(self, *args, **kwargs):
"""
Retrieves the users from elastic.
"""
arguments, _ = self.argparser.parse_known_args()
if self.is_pipe and self.use_pipe:
return self.get_pipe(self.object_type)
elif arguments.tags or arguments.type or argume... | Retrieves the users from elastic. |
def g(self):
"Hour, 12-hour format without leading zeros; i.e. '1' to '12'"
if self.data.hour == 0:
return 12
if self.data.hour > 12:
return self.data.hour - 12
return self.data.hour | Hour, 12-hour format without leading zeros; i.e. '1' to '12 |
def determine_end_idx_for_adjustment(self,
adjustment_ts,
dates,
upper_bound,
requested_quarter,
sid_estimates):
... | Determines the date until which the adjustment at the given date
index should be applied for the given quarter.
Parameters
----------
adjustment_ts : pd.Timestamp
The timestamp at which the adjustment occurs.
dates : pd.DatetimeIndex
The calendar dates ov... |
def _get_compressed_vlan_list(self, pvlan_ids):
"""Generate a compressed vlan list ready for XML using a vlan set.
Sample Use Case:
Input vlan set:
--------------
1 - s = set([11, 50, 25, 30, 15, 16, 3, 8, 2, 1])
2 - s = set([87, 11, 50, 25, 30, 15, 16, 3, 8, 2, 1, 88])... | Generate a compressed vlan list ready for XML using a vlan set.
Sample Use Case:
Input vlan set:
--------------
1 - s = set([11, 50, 25, 30, 15, 16, 3, 8, 2, 1])
2 - s = set([87, 11, 50, 25, 30, 15, 16, 3, 8, 2, 1, 88])
Returned compressed XML list:
-----------... |
def validate_alias(self, name, cmd):
"""Validate an alias and return the its number of arguments."""
if name in self.no_alias:
raise InvalidAliasError("The name %s can't be aliased "
"because it is a keyword or builtin." % name)
if not (isinstance(... | Validate an alias and return the its number of arguments. |
def get_public_events(self):
"""
:calls: `GET /users/:user/events/public <http://developer.github.com/v3/activity/events>`_
:rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.Event.Event`
"""
return github.PaginatedList.PaginatedList(
github.Event.E... | :calls: `GET /users/:user/events/public <http://developer.github.com/v3/activity/events>`_
:rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.Event.Event` |
def validate_email_with_regex(email_address):
"""
Note that this will only filter out syntax mistakes in emailaddresses.
If a human would think it is probably a valid email, it will most likely pass.
However, it could still very well be that the actual emailaddress has simply
not be claimed by anyon... | Note that this will only filter out syntax mistakes in emailaddresses.
If a human would think it is probably a valid email, it will most likely pass.
However, it could still very well be that the actual emailaddress has simply
not be claimed by anyone (so then this function fails to devalidate). |
def by_version(cls, session, package_name, version):
"""
Get release for a given version.
:param session: SQLAlchemy session
:type session: :class:`sqlalchemy.Session`
:param package_name: package name
:type package_name: unicode
:param version: version
... | Get release for a given version.
:param session: SQLAlchemy session
:type session: :class:`sqlalchemy.Session`
:param package_name: package name
:type package_name: unicode
:param version: version
:type version: unicode
:return: release instance
:rtype... |
def GetHashCode(self):
"""uint32 identifier"""
slice_length = 4 if len(self.Data) >= 4 else len(self.Data)
return int.from_bytes(self.Data[:slice_length], 'little') | uint32 identifier |
def prepend_urls(self):
""" Add the following array of urls to the Tileset base urls """
return [
url(r"^(?P<resource_name>%s)/(?P<pk>\w[\w/-]*)/generate%s$" %
(self._meta.resource_name, trailing_slash()),
self.wrap_view('generate'), name="api_tileset_generate... | Add the following array of urls to the Tileset base urls |
def append_data(file_strings, file_fmt, tag):
""" Load the SuperMAG files
Parameters
-----------
file_strings : array-like
Lists or arrays of strings, where each string contains one file of data
file_fmt : str
String denoting file type (ascii or csv)
tag : string
String ... | Load the SuperMAG files
Parameters
-----------
file_strings : array-like
Lists or arrays of strings, where each string contains one file of data
file_fmt : str
String denoting file type (ascii or csv)
tag : string
String denoting the type of file to load, accepted values are... |
def Tt(CASRN, AvailableMethods=False, Method=None):
r'''This function handles the retrieval of a chemical's triple temperature.
Lookup is based on CASRNs. Will automatically select a data source to use
if no Method is provided; returns None if the data is not available.
Returns data from [1]_, or a che... | r'''This function handles the retrieval of a chemical's triple temperature.
Lookup is based on CASRNs. Will automatically select a data source to use
if no Method is provided; returns None if the data is not available.
Returns data from [1]_, or a chemical's melting point if available.
Parameters
... |
def type_name(value):
"""Returns pseudo-YAML type name of given value."""
return type(value).__name__ if isinstance(value, EncapsulatedNode) else \
"struct" if isinstance(value, dict) else \
"sequence" if isinstance(value, (tuple, list)) else \
type(value).__name__ | Returns pseudo-YAML type name of given value. |
def dot(self, other):
"""Calculates the dot product of this vector and another vector."""
dot_product = 0
a = self.elements
b = other.elements
a_len = len(a)
b_len = len(b)
i = j = 0
while i < a_len and j < b_len:
a_val = a[i]
b_va... | Calculates the dot product of this vector and another vector. |
def sample_following_dist(handle_iter, n, totalf):
"""Samples n passwords following the distribution from the handle
@handle_iter is an iterator that gives (pw,f) @n is the total
number of samle asked for @totalf is the total number of users,
which is euqal to sum(f for pw,f in handle_iter)
As, hand... | Samples n passwords following the distribution from the handle
@handle_iter is an iterator that gives (pw,f) @n is the total
number of samle asked for @totalf is the total number of users,
which is euqal to sum(f for pw,f in handle_iter)
As, handle_iterator is an iterator and can only traverse once.
... |
def FromStream(cls, stream, mime_type, total_size=None, auto_transfer=True,
gzip_encoded=False, **kwds):
"""Create a new Upload object from a stream."""
if mime_type is None:
raise exceptions.InvalidUserInputError(
'No mime_type specified for stream')
... | Create a new Upload object from a stream. |
def stream_buckets(self, bucket_type=None, timeout=None):
"""
Stream list of buckets through an iterator
"""
if not self.bucket_stream():
raise NotImplementedError('Streaming list-buckets is not '
"supported on %s" %
... | Stream list of buckets through an iterator |
def rebin(self, factor):
"""
I robustly rebin your image by a given factor.
You simply specify a factor, and I will eventually take care of a crop to bring
the image to interger-multiple-of-your-factor dimensions.
Note that if you crop your image before, you must directly crop to... | I robustly rebin your image by a given factor.
You simply specify a factor, and I will eventually take care of a crop to bring
the image to interger-multiple-of-your-factor dimensions.
Note that if you crop your image before, you must directly crop to compatible dimensions !
We update th... |
def list_udas(self, database=None, like=None):
"""
Lists all UDAFs associated with a given database
Parameters
----------
database : string
like : string for searching (optional)
"""
if not database:
database = self.current_database
st... | Lists all UDAFs associated with a given database
Parameters
----------
database : string
like : string for searching (optional) |
def get_keys(self, alias_name, key_format):
"""
Retrieves the contents of PKCS12 file in the format specified.
This PKCS12 formatted file contains both the certificate as well as the key file data.
Valid key formats are Base64 and PKCS12.
Args:
alias_name: Key pair a... | Retrieves the contents of PKCS12 file in the format specified.
This PKCS12 formatted file contains both the certificate as well as the key file data.
Valid key formats are Base64 and PKCS12.
Args:
alias_name: Key pair associated with the RabbitMQ
key_format: Valid key fo... |
def set_password(self, password = None):
"""This method is used to set the password.
password must be a string.
"""
if password is None or type(password) is not str:
raise KPError("Need a new image number")
else:
self.password = password
... | This method is used to set the password.
password must be a string. |
def parse_selfsm(self, f):
""" Go through selfSM file and create a dictionary with the sample name as a key, """
#create a dictionary to populate from this sample's file
parsed_data = dict()
# set a empty variable which denotes if the headers have been read
headers = None
# for each line in the file
for l... | Go through selfSM file and create a dictionary with the sample name as a key, |
def _wrapper(func):
"""
Wraps a generated function so that it catches all Type- and ValueErrors
and raises IntoDPValueErrors.
:param func: the transforming function
"""
@functools.wraps(func)
def the_func(expr):
"""
The actual function.
:param object expr: the expr... | Wraps a generated function so that it catches all Type- and ValueErrors
and raises IntoDPValueErrors.
:param func: the transforming function |
def _pollCallStatus(self, expectedState, callId=None, timeout=None):
""" Poll the status of outgoing calls.
This is used for modems that do not have a known set of call status update notifications.
:param expectedState: The internal state we are waiting for. 0 == initiated, 1 == ans... | Poll the status of outgoing calls.
This is used for modems that do not have a known set of call status update notifications.
:param expectedState: The internal state we are waiting for. 0 == initiated, 1 == answered, 2 = hangup
:type expectedState: int
:raise Timeou... |
def get_info_by_tail_number(self, tail_number, page=1, limit=100):
"""Fetch the details of a particular aircraft by its tail number.
This method can be used to get the details of a particular aircraft by its tail number.
Details include the serial number, age etc along with links to the images ... | Fetch the details of a particular aircraft by its tail number.
This method can be used to get the details of a particular aircraft by its tail number.
Details include the serial number, age etc along with links to the images of the aircraft.
It checks the user authentication and returns the dat... |
def _pwm_to_str(self, precision=4):
"""Return string representation of pwm.
Parameters
----------
precision : int, optional, default 4
Floating-point precision.
Returns
-------
pwm_string : str
"""
if not self.pwm:
return ... | Return string representation of pwm.
Parameters
----------
precision : int, optional, default 4
Floating-point precision.
Returns
-------
pwm_string : str |
def _add_domains_xml(self, document):
"""
Generates the XML elements for allowed domains.
"""
for domain, attrs in self.domains.items():
domain_element = document.createElement('allow-access-from')
domain_element.setAttribute('domain', domain)
if attr... | Generates the XML elements for allowed domains. |
def write_composer_operation_log(filename):
"""
Writes the composed operation log from featuremonkey's Composer to a json file.
:param filename:
:return:
"""
from featuremonkey.tracing import serializer
from featuremonkey.tracing.logger import OPERATION_LOG
ol = copy.deepcopy(OPERATION_L... | Writes the composed operation log from featuremonkey's Composer to a json file.
:param filename:
:return: |
def output_tap(self):
"""Output analysis results in TAP format."""
tracker = Tracker(streaming=True, stream=sys.stdout)
for group in self.config.analysis_groups:
n_providers = len(group.providers)
n_checkers = len(group.checkers)
if not group.providers and gro... | Output analysis results in TAP format. |
def target_socket(self, config):
""" This method overrides :meth:`.WNetworkNativeTransport.target_socket` method. Do the same thing as
basic method do, but also checks that the result address is IPv4 multicast address.
:param config: beacon configuration
:return: WIPV4SocketInfo
"""
target = WUDPNetworkNat... | This method overrides :meth:`.WNetworkNativeTransport.target_socket` method. Do the same thing as
basic method do, but also checks that the result address is IPv4 multicast address.
:param config: beacon configuration
:return: WIPV4SocketInfo |
def tree():
"""Example showing tree progress view"""
#############
# Test data #
#############
# For this example, we're obviously going to be feeding fictitious data
# to ProgressTree, so here it is
leaf_values = [Value(0) for i in range(6)]
bd_defaults = dict(type=Bar, kwargs=dict(... | Example showing tree progress view |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.