code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def on_m_open_file(self,event):
'''
open orient.txt
read the data
display the data from the file in a new grid
'''
dlg = wx.FileDialog(
self, message="choose orient file",
defaultDir=self.WD,
defaultFile="",
style=wx.FD_OPEN... | open orient.txt
read the data
display the data from the file in a new grid |
def _set_mpls_reopt_lsp(self, v, load=False):
"""
Setter method for mpls_reopt_lsp, mapped from YANG variable /brocade_mpls_rpc/mpls_reopt_lsp (rpc)
If this variable is read-only (config: false) in the
source YANG file, then _set_mpls_reopt_lsp is considered as a private
method. Backends looking to ... | Setter method for mpls_reopt_lsp, mapped from YANG variable /brocade_mpls_rpc/mpls_reopt_lsp (rpc)
If this variable is read-only (config: false) in the
source YANG file, then _set_mpls_reopt_lsp is considered as a private
method. Backends looking to populate this variable should
do so via calling thisOb... |
def upload_site(self):
"""Upload a previously-built site to LSST the Docs."""
if not os.path.isdir(self._config['build_dir']):
message = 'Site not built at {0}'.format(self._config['build_dir'])
self._logger.error(message)
raise RuntimeError(message)
ltdclien... | Upload a previously-built site to LSST the Docs. |
def density(a_M, *args, **kwargs):
"""
ARGS
a_M matrix to analyze
*args[0] optional mask matrix; if passed, calculate
density of a_M using non-zero elements of
args[0] as a mask.
DESC
Determine the "dens... | ARGS
a_M matrix to analyze
*args[0] optional mask matrix; if passed, calculate
density of a_M using non-zero elements of
args[0] as a mask.
DESC
Determine the "density" of a passed matrix. Two densities are retu... |
def compute_venn3_colors(set_colors):
'''
Given three base colors, computes combinations of colors corresponding to all regions of the venn diagram.
returns a list of 7 elements, providing colors for regions (100, 010, 110, 001, 101, 011, 111).
>>> compute_venn3_colors(['r', 'g', 'b'])
(array([ 1.,... | Given three base colors, computes combinations of colors corresponding to all regions of the venn diagram.
returns a list of 7 elements, providing colors for regions (100, 010, 110, 001, 101, 011, 111).
>>> compute_venn3_colors(['r', 'g', 'b'])
(array([ 1., 0., 0.]),..., array([ 0.4, 0.2, 0.4])) |
def get_parsed_content(metadata_content):
"""
Parses any of the following types of content:
1. XML string or file object: parses XML content
2. MetadataParser instance: deep copies xml_tree
3. Dictionary with nested objects containing:
- name (required): the name of the element tag
-... | Parses any of the following types of content:
1. XML string or file object: parses XML content
2. MetadataParser instance: deep copies xml_tree
3. Dictionary with nested objects containing:
- name (required): the name of the element tag
- text: the text contained by element
- tail: t... |
def add_legend(self, labels=None, **kwargs):
"""Specify legend for a plot.
Adds labels and basic legend specifications for specific plot.
For the optional Args, refer to
https://matplotlib.org/api/_as_gen/matplotlib.pyplot.legend.html
for more information.
# TODO: Add ... | Specify legend for a plot.
Adds labels and basic legend specifications for specific plot.
For the optional Args, refer to
https://matplotlib.org/api/_as_gen/matplotlib.pyplot.legend.html
for more information.
# TODO: Add legend capabilities for Loss/Gain plots. This is possibl... |
def deploy_script(self, synchronous=True, **kwargs):
"""Helper for Config's deploy_script method.
:param synchronous: What should happen if the server returns an HTTP
202 (accepted) status code? Wait for the task to complete if
``True``. Immediately return the server's response ... | Helper for Config's deploy_script method.
:param synchronous: What should happen if the server returns an HTTP
202 (accepted) status code? Wait for the task to complete if
``True``. Immediately return the server's response otherwise.
:param kwargs: Arguments to pass to requests.... |
def unhexlify(blob):
"""
Takes a hexlified script and turns it back into a string of Python code.
"""
lines = blob.split('\n')[1:]
output = []
for line in lines:
# Discard the address, length etc. and reverse the hexlification
output.append(binascii.unhexlify(line[9:-2]))
# C... | Takes a hexlified script and turns it back into a string of Python code. |
def _increment_504_stat(self, request):
'''
Increments the 504 stat counters
@param request: The scrapy request in the spider
'''
for key in self.stats_dict:
if key == 'lifetime':
unique = request.url + str(time.time())
self.stats_dict... | Increments the 504 stat counters
@param request: The scrapy request in the spider |
def get_record(self, **kwargs):
# type: (str) -> Union[dr.DirectoryRecord, udfmod.UDFFileEntry]
'''
Get the directory record for a particular path.
Parameters:
iso_path - The absolute path on the ISO9660 filesystem to get the
record for.
rr_path - T... | Get the directory record for a particular path.
Parameters:
iso_path - The absolute path on the ISO9660 filesystem to get the
record for.
rr_path - The absolute path on the Rock Ridge filesystem to get the
record for.
joliet_path - The absolute ... |
def _clone_block_and_wires(block_in):
"""
This is a generic function to copy the WireVectors for another round of
synthesis This does not split a WireVector with multiple wires.
:param block_in: The block to change
:param synth_name: a name to prepend to all new copies of a wire
:return: the re... | This is a generic function to copy the WireVectors for another round of
synthesis This does not split a WireVector with multiple wires.
:param block_in: The block to change
:param synth_name: a name to prepend to all new copies of a wire
:return: the resulting block and a WireVector map |
def create(self, create_missing=None):
"""Do extra work to fetch a complete set of attributes for this entity.
For more information, see `Bugzilla #1301658
<https://bugzilla.redhat.com/show_bug.cgi?id=1301658>`_.
"""
return UserGroup(
self._server_config,
... | Do extra work to fetch a complete set of attributes for this entity.
For more information, see `Bugzilla #1301658
<https://bugzilla.redhat.com/show_bug.cgi?id=1301658>`_. |
def update_dist_caches(dist_path, fix_zipimporter_caches):
"""
Fix any globally cached `dist_path` related data
`dist_path` should be a path of a newly installed egg distribution (zipped
or unzipped).
sys.path_importer_cache contains finder objects that have been cached when
importing data fro... | Fix any globally cached `dist_path` related data
`dist_path` should be a path of a newly installed egg distribution (zipped
or unzipped).
sys.path_importer_cache contains finder objects that have been cached when
importing data from the original distribution. Any such finders need to be
cleared si... |
def check_exists(subreddit):
"""Make sure that a subreddit actually exists."""
req = get('http://www.reddit.com/r/%s/about.json' % subreddit, headers={'User-Agent': 'CslBot/1.0'})
if req.json().get('kind') == 'Listing':
# no subreddit exists, search results page is shown
return False
ret... | Make sure that a subreddit actually exists. |
def CheckForQuestionPending(task):
"""
Check to see if VM needs to ask a question, throw exception
"""
vm = task.info.entity
if vm is not None and isinstance(vm, vim.VirtualMachine):
qst = vm.runtime.question
if qst is not None:
raise TaskBlocked("Task blocked, User Inte... | Check to see if VM needs to ask a question, throw exception |
def make_token(cls, ephemeral_token: 'RedisEphemeralTokens') -> str:
"""
Returns a token to be used x number of times to allow a user account to access
certain resource.
"""
value = ephemeral_token.key
if ephemeral_token.scope:
value += ''.join(ephemeral_token... | Returns a token to be used x number of times to allow a user account to access
certain resource. |
def fprint(self, obj, stream=None, **kwargs):
"""Prints the formatted representation of the object on stream"""
if stream is None:
stream = sys.stdout
options = self.options
options.update(kwargs)
if isinstance(obj, dimod.SampleSet):
self._print_samplese... | Prints the formatted representation of the object on stream |
def get_branding_metadata(self):
"""Gets the metadata for the asset branding.
return: (osid.Metadata) - metadata for the asset branding.
*compliance: mandatory -- This method must be implemented.*
"""
metadata = dict(self._branding_metadata)
metadata.update({'existing_i... | Gets the metadata for the asset branding.
return: (osid.Metadata) - metadata for the asset branding.
*compliance: mandatory -- This method must be implemented.* |
def require(self, path=None, contents=None, source=None, url=None, md5=None,
use_sudo=False, owner=None, group='', mode=None, verify_remote=True,
temp_dir='/tmp'):
"""
Require a file to exist and have specific contents and properties.
You can provide either:
- *conten... | Require a file to exist and have specific contents and properties.
You can provide either:
- *contents*: the required contents of the file::
from fabtools import require
require.file('/tmp/hello.txt', contents='Hello, world')
- *source*: the local path of a file to u... |
def list_all_zones_by_name(region=None, key=None, keyid=None, profile=None):
'''
List, by their FQDNs, all hosted zones in the bound account.
region
Region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
profile
A dict with region, key a... | List, by their FQDNs, all hosted zones in the bound account.
region
Region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
profile
A dict with region, key and keyid, or a pillar key (string) that
contains a dict with region, key and keyi... |
def cli(ctx, config, debug, language, verbose):
"""
Cucco allows to apply normalizations to a given text or file.
This normalizations include, among others, removal of accent
marks, stop words an extra white spaces, replacement of
punctuation symbols, emails, emojis, etc.
For more info on how t... | Cucco allows to apply normalizations to a given text or file.
This normalizations include, among others, removal of accent
marks, stop words an extra white spaces, replacement of
punctuation symbols, emails, emojis, etc.
For more info on how to use and configure Cucco, check the
project website at ... |
def format_row(self, row, key, color):
"""For a given row from the table, format it (i.e. floating
points and color if applicable).
"""
value = row[key]
if isinstance(value, bool) or value is None:
return '+' if value else ''
if not isinstance(value, Number... | For a given row from the table, format it (i.e. floating
points and color if applicable). |
def authorize_application(
request,
redirect_uri = 'https://%s/%s' % (FACEBOOK_APPLICATION_DOMAIN, FACEBOOK_APPLICATION_NAMESPACE),
permissions = FACEBOOK_APPLICATION_INITIAL_PERMISSIONS
):
"""
Redirect the user to authorize the application.
Redirection is done by rendering a JavaScript sni... | Redirect the user to authorize the application.
Redirection is done by rendering a JavaScript snippet that redirects the parent
window to the authorization URI, since Facebook will not allow this inside an iframe. |
def end_namespace(self, prefix):
""" Undeclare a namespace prefix. """
del self._ns[prefix]
self._g.endPrefixMapping(prefix) | Undeclare a namespace prefix. |
def redraw(self, reset_camera=False):
"""
Redraw the render window.
Args:
reset_camera: Set to True to reset the camera to a
pre-determined default for each structure. Defaults to False.
"""
self.ren.RemoveAllViewProps()
self.picker = None
... | Redraw the render window.
Args:
reset_camera: Set to True to reset the camera to a
pre-determined default for each structure. Defaults to False. |
def validate(self):
"""
Validate the current file against the SLD schema. This first normalizes
the SLD document, then validates it. Any schema validation error messages
are logged at the INFO level.
@rtype: boolean
@return: A flag indicating if the SLD is valid.
... | Validate the current file against the SLD schema. This first normalizes
the SLD document, then validates it. Any schema validation error messages
are logged at the INFO level.
@rtype: boolean
@return: A flag indicating if the SLD is valid. |
def get_local_lb(self, loadbal_id, **kwargs):
"""Returns a specified local load balancer given the id.
:param int loadbal_id: The id of the load balancer to retrieve
:returns: A dictionary containing the details of the load balancer
"""
if 'mask' not in kwargs:
kwar... | Returns a specified local load balancer given the id.
:param int loadbal_id: The id of the load balancer to retrieve
:returns: A dictionary containing the details of the load balancer |
def autobuild_release(family=None):
"""Copy necessary files into build/output so that this component can be used by others
Args:
family (ArchitectureGroup): The architecture group that we are targeting. If not
provided, it is assumed that we are building in the current directory and the
... | Copy necessary files into build/output so that this component can be used by others
Args:
family (ArchitectureGroup): The architecture group that we are targeting. If not
provided, it is assumed that we are building in the current directory and the
module_settings.json file is read... |
def query_singleton_edges_from_network(self, network: Network) -> sqlalchemy.orm.query.Query:
"""Return a query selecting all edge ids that only belong to the given network."""
ne1 = aliased(network_edge, name='ne1')
ne2 = aliased(network_edge, name='ne2')
singleton_edge_ids_for_network ... | Return a query selecting all edge ids that only belong to the given network. |
def ec_number(self, ec_number=None, entry_name=None, limit=None, as_df=False):
"""Method to query :class:`.models.ECNumber` objects in database
:param ec_number: Enzyme Commission number(s)
:type ec_number: str or tuple(str) or None
:param entry_name: name(s) in :class:`.models.Entry`
... | Method to query :class:`.models.ECNumber` objects in database
:param ec_number: Enzyme Commission number(s)
:type ec_number: str or tuple(str) or None
:param entry_name: name(s) in :class:`.models.Entry`
:type entry_name: str or tuple(str) or None
:param limit:
- i... |
def new(cls, package):
"""Return newly created footer part."""
partname = package.next_partname("/word/footer%d.xml")
content_type = CT.WML_FOOTER
element = parse_xml(cls._default_footer_xml())
return cls(partname, content_type, element, package) | Return newly created footer part. |
def fit(self, Z):
"""
Fit linear model.
Parameters
----------
Z : DictRDD with (X, y) values
X containing numpy array or sparse matrix - The training data
y containing the target values
Returns
-------
self : returns an instance o... | Fit linear model.
Parameters
----------
Z : DictRDD with (X, y) values
X containing numpy array or sparse matrix - The training data
y containing the target values
Returns
-------
self : returns an instance of self. |
def value(self) -> Decimal:
"""
Value of the holdings in exchange currency.
Value = Quantity * Price
"""
assert isinstance(self.price, Decimal)
return self.quantity * self.price | Value of the holdings in exchange currency.
Value = Quantity * Price |
def _handle_response(self, response):
"""Logs dropped chunks and updates dynamic settings"""
if isinstance(response, Exception):
logging.error("dropped chunk %s" % response)
elif response.json().get("limits"):
parsed = response.json()
self._api.dynamic_setting... | Logs dropped chunks and updates dynamic settings |
def calc_point_distance(self, chi_coords):
"""
Calculate distance between point and the bank. Return the closest
distance.
Parameters
-----------
chi_coords : numpy.array
The position of the point in the chi coordinates.
Returns
--------
... | Calculate distance between point and the bank. Return the closest
distance.
Parameters
-----------
chi_coords : numpy.array
The position of the point in the chi coordinates.
Returns
--------
min_dist : float
The smallest **SQUARED** metri... |
def run_sphinx():
"""Runs Sphinx via it's `make html` command"""
old_dir = here_directory()
os.chdir(str(doc_directory()))
doc_status = subprocess.check_call(['make', 'html'], shell=True)
os.chdir(str(old_dir)) # go back to former working directory
if doc_status is not 0:
exit(Fore.RED ... | Runs Sphinx via it's `make html` command |
def __get_state_by_id(cls, job_id):
"""Get job state by id.
Args:
job_id: job id.
Returns:
model.MapreduceState for the job.
Raises:
ValueError: if the job state is missing.
"""
state = model.MapreduceState.get_by_job_id(job_id)
if state is None:
raise ValueError("... | Get job state by id.
Args:
job_id: job id.
Returns:
model.MapreduceState for the job.
Raises:
ValueError: if the job state is missing. |
def from_twodim_list(cls, datalist, tsformat=None):
"""Creates a new TimeSeries instance from the data stored inside a two dimensional list.
:param list datalist: List containing multiple iterables with at least two values.
The first item will always be used as timestamp in the predefine... | Creates a new TimeSeries instance from the data stored inside a two dimensional list.
:param list datalist: List containing multiple iterables with at least two values.
The first item will always be used as timestamp in the predefined format,
the second represents the value. All othe... |
def display_message(
self, subject='Find My iPhone Alert', message="This is a note",
sounds=False
):
""" Send a request to the device to play a sound.
It's possible to pass a custom message by changing the `subject`.
"""
data = json.dumps(
{
... | Send a request to the device to play a sound.
It's possible to pass a custom message by changing the `subject`. |
def chebyshev(x, y):
"""Chebyshev or l-infinity distance.
..math::
D(x, y) = \max_i |x_i - y_i|
"""
result = 0.0
for i in range(x.shape[0]):
result = max(result, np.abs(x[i] - y[i]))
return result | Chebyshev or l-infinity distance.
..math::
D(x, y) = \max_i |x_i - y_i| |
def collect_loaded_packages() -> List[Tuple[str, str]]:
"""
Return the currently loaded package names and their versions.
"""
dists = get_installed_distributions()
get_dist_files = DistFilesFinder()
file_table = {}
for dist in dists:
for file in get_dist_files(dist):
file... | Return the currently loaded package names and their versions. |
def unique(seq):
"""Return the unique values in a sequence.
Parameters
----------
seq : sequence
Sequence with (possibly duplicate) elements.
Returns
-------
unique : list
Unique elements of ``seq``.
Order is guaranteed to be the same as in seq.
Examples
--... | Return the unique values in a sequence.
Parameters
----------
seq : sequence
Sequence with (possibly duplicate) elements.
Returns
-------
unique : list
Unique elements of ``seq``.
Order is guaranteed to be the same as in seq.
Examples
--------
Determine uni... |
def human_or_11(X, y, model_generator, method_name):
""" OR (true/true)
This tests how well a feature attribution method agrees with human intuition
for an OR operation combined with linear effects. This metric deals
specifically with the question of credit allocation for the following function
whe... | OR (true/true)
This tests how well a feature attribution method agrees with human intuition
for an OR operation combined with linear effects. This metric deals
specifically with the question of credit allocation for the following function
when all three inputs are true:
if fever: +2 points
if c... |
async def trigger_all(self, *args, **kwargs):
'''Trigger all agents in the environment to act asynchronously.
:returns: A list of agents' :meth:`act` return values.
Given arguments and keyword arguments are passed down to each agent's
:meth:`creamas.core.agent.CreativeAgent.act`.
... | Trigger all agents in the environment to act asynchronously.
:returns: A list of agents' :meth:`act` return values.
Given arguments and keyword arguments are passed down to each agent's
:meth:`creamas.core.agent.CreativeAgent.act`.
.. note::
By design, the environment's m... |
def get_log_hierarchy_id(self):
"""Gets the hierarchy ``Id`` associated with this session.
return: (osid.id.Id) - the hierarchy ``Id`` associated with this
session
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
... | Gets the hierarchy ``Id`` associated with this session.
return: (osid.id.Id) - the hierarchy ``Id`` associated with this
session
*compliance: mandatory -- This method must be implemented.* |
def upload_file(self, body,
key=None,
metadata=None,
headers=None,
access_key=None,
secret_key=None,
queue_derive=None,
verbose=None,
verify=None,
... | Upload a single file to an item. The item will be created
if it does not exist.
:type body: Filepath or file-like object.
:param body: File or data to be uploaded.
:type key: str
:param key: (optional) Remote filename.
:type metadata: dict
:param metadata: (opt... |
def do_child_count(self, params):
"""
\x1b[1mNAME\x1b[0m
child_count - Prints the child count for paths
\x1b[1mSYNOPSIS\x1b[0m
child_count [path] [depth]
\x1b[1mOPTIONS\x1b[0m
* path: the path (default: cwd)
* max_depth: max recursion limit (0 is no limit) (default: 1)
\x1b[1m... | \x1b[1mNAME\x1b[0m
child_count - Prints the child count for paths
\x1b[1mSYNOPSIS\x1b[0m
child_count [path] [depth]
\x1b[1mOPTIONS\x1b[0m
* path: the path (default: cwd)
* max_depth: max recursion limit (0 is no limit) (default: 1)
\x1b[1mEXAMPLES\x1b[0m
> child-count /
... |
def _get_phrase_list_from_words(self, word_list):
"""Method to create contender phrases from the list of words that form
a sentence by dropping stopwords and punctuations and grouping the left
words into phrases. Only phrases in the given length range (both limits
inclusive) would be con... | Method to create contender phrases from the list of words that form
a sentence by dropping stopwords and punctuations and grouping the left
words into phrases. Only phrases in the given length range (both limits
inclusive) would be considered to build co-occurrence matrix. Ex:
Sentence:... |
def gene_ids(self, contig=None, strand=None):
"""
What are all the gene IDs
(optionally restrict to a given chromosome/contig and/or strand)
"""
return self._all_feature_values(
column="gene_id",
feature="gene",
contig=contig,
stran... | What are all the gene IDs
(optionally restrict to a given chromosome/contig and/or strand) |
def model(self):
"""Return the model name of the printer."""
try:
return self.data.get('identity').get('model_name')
except (KeyError, AttributeError):
return self.device_status_simple('') | Return the model name of the printer. |
def db_parse( block_id, txid, vtxindex, op, data, senders, inputs, outputs, fee, db_state=None, **virtualchain_hints ):
"""
(required by virtualchain state engine)
Parse a blockstack operation from a transaction. The transaction fields are as follows:
* `block_id` is the blockchain height at which this... | (required by virtualchain state engine)
Parse a blockstack operation from a transaction. The transaction fields are as follows:
* `block_id` is the blockchain height at which this transaction occurs
* `txid` is the transaction ID
* `data` is the scratch area of the transaction that contains the actual ... |
def trimmed(self, n_peaks):
"""
:param n_peaks: number of peaks to keep
:returns: an isotope pattern with removed low-intensity peaks
:rtype: CentroidedSpectrum
"""
result = self.copy()
result.trim(n_peaks)
return result | :param n_peaks: number of peaks to keep
:returns: an isotope pattern with removed low-intensity peaks
:rtype: CentroidedSpectrum |
def make_parent_dirs(path, mode=0o777):
"""
Ensure parent directories of a file are created as needed.
"""
parent = os.path.dirname(path)
if parent:
make_all_dirs(parent, mode)
return path | Ensure parent directories of a file are created as needed. |
def next(self):
"""Goes one item ahead and returns it."""
rv = self.current
self.pos = (self.pos + 1) % len(self.items)
return rv | Goes one item ahead and returns it. |
def get_band_qpoints(band_paths, npoints=51, rec_lattice=None):
"""Generate qpoints for band structure path
Note
----
Behavior changes with and without rec_lattice given.
Parameters
----------
band_paths: list of array_likes
Sets of end points of paths
dtype='double'
... | Generate qpoints for band structure path
Note
----
Behavior changes with and without rec_lattice given.
Parameters
----------
band_paths: list of array_likes
Sets of end points of paths
dtype='double'
shape=(sets of paths, paths, 3)
example:
[[[0, ... |
def diff(self, n, axis=1):
""" return block for the diff of the values """
new_values = algos.diff(self.values, n, axis=axis)
return [self.make_block(values=new_values)] | return block for the diff of the values |
def _configure(self, *args):
"""Configure viewport
This method is called when the widget is resized or something triggers a redraw. The method configures the
view to show all elements in an orthogonal perspective.
"""
# Obtain a reference to the OpenGL drawable
# and ren... | Configure viewport
This method is called when the widget is resized or something triggers a redraw. The method configures the
view to show all elements in an orthogonal perspective. |
def update(self, request, id):
""" Read the GeoJSON feature from the request body and update the
corresponding object in the database. """
if self.readonly:
return HTTPMethodNotAllowed(headers={'Allow': 'GET, HEAD'})
session = self.Session()
obj = session.query(self.m... | Read the GeoJSON feature from the request body and update the
corresponding object in the database. |
def _submit_and_wait(cmd, cores, config, output_dir):
"""Submit command with batch script specified in configuration, wait until finished
"""
batch_script = "submit_bcl2fastq.sh"
if not os.path.exists(batch_script + ".finished"):
if os.path.exists(batch_script + ".failed"):
os.remove... | Submit command with batch script specified in configuration, wait until finished |
def splitext( filename ):
""" Return the filename and extension according to the first dot in the filename.
This helps date stamping .tar.bz2 or .ext.gz files properly.
"""
index = filename.find('.')
if index == 0:
index = 1+filename[1:].find('.')
if index == -1:
return filen... | Return the filename and extension according to the first dot in the filename.
This helps date stamping .tar.bz2 or .ext.gz files properly. |
def _bdd(node):
"""Return a unique BDD."""
try:
bdd = _BDDS[node]
except KeyError:
bdd = _BDDS[node] = BinaryDecisionDiagram(node)
return bdd | Return a unique BDD. |
def _make_file_dict(self, f):
"""Make a dictionary with filename and base64 file data"""
if isinstance(f, dict):
file_obj = f['file']
if 'filename' in f:
file_name = f['filename']
else:
file_name = file_obj.name
else:
... | Make a dictionary with filename and base64 file data |
def generate_listall_output(lines, resources, aws_config, template, arguments, nodup = False):
"""
Format and print the output of ListAll
:param lines:
:param resources:
:param aws_config:
:param template:
:param arguments:
:param nodup:
:return:
"""
for line in lines:
... | Format and print the output of ListAll
:param lines:
:param resources:
:param aws_config:
:param template:
:param arguments:
:param nodup:
:return: |
def is_ancestor_of_objective_bank(self, id_, objective_bank_id):
"""Tests if an ``Id`` is an ancestor of an objective bank.
arg: id (osid.id.Id): an ``Id``
arg: objective_bank_id (osid.id.Id): the ``Id`` of an
objective bank
return: (boolean) - ``true`` if this ``i... | Tests if an ``Id`` is an ancestor of an objective bank.
arg: id (osid.id.Id): an ``Id``
arg: objective_bank_id (osid.id.Id): the ``Id`` of an
objective bank
return: (boolean) - ``true`` if this ``id`` is an ancestor of
``objective_bank_id,`` ``false`` other... |
def equals(df1, df2, ignore_order=set(), ignore_indices=set(), all_close=False, _return_reason=False):
'''
Get whether 2 data frames are equal.
``NaN`` is considered equal to ``NaN`` and `None`.
Parameters
----------
df1 : ~pandas.DataFrame
Data frame to compare.
df2 : ~pandas.Data... | Get whether 2 data frames are equal.
``NaN`` is considered equal to ``NaN`` and `None`.
Parameters
----------
df1 : ~pandas.DataFrame
Data frame to compare.
df2 : ~pandas.DataFrame
Data frame to compare.
ignore_order : ~typing.Set[int]
Axi in which to ignore order.
... |
def get_default_pandas_converters() -> List[Union[Converter[Any, pd.DataFrame],
Converter[pd.DataFrame, Any]]]:
"""
Utility method to return the default converters associated to dataframes (from dataframe to other type,
and from other type to dataframe)
... | Utility method to return the default converters associated to dataframes (from dataframe to other type,
and from other type to dataframe)
:return: |
def grasstruth(args):
"""
%prog grasstruth james-pan-grass.txt
Prepare truth pairs for 4 grasses.
"""
p = OptionParser(grasstruth.__doc__)
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
james, = args
fp = open(james)
pairs = set()
f... | %prog grasstruth james-pan-grass.txt
Prepare truth pairs for 4 grasses. |
def add_username(user, apps):
"""When using broser login, username was not stored so look it up"""
if not user:
return None
apps = [a for a in apps if a.instance == user.instance]
if not apps:
return None
from toot.api import verify_credentials
creds = verify_credentials(apps.... | When using broser login, username was not stored so look it up |
def translate_y(self, d):
"""Translate mesh for y-direction
:param float d: Amount to translate
"""
mat = numpy.array([
[1, 0, 0, 0],
[0, 1, 0, 0],
[0, 0, 1, 0],
[0, d, 0, 1]
])
self.vectors = self.vectors.dot(mat)
... | Translate mesh for y-direction
:param float d: Amount to translate |
def evaluate(self, env, engine, parser, term_type, eval_in_python):
"""Evaluate a binary operation *before* being passed to the engine.
Parameters
----------
env : Scope
engine : str
parser : str
term_type : type
eval_in_python : list
Returns
... | Evaluate a binary operation *before* being passed to the engine.
Parameters
----------
env : Scope
engine : str
parser : str
term_type : type
eval_in_python : list
Returns
-------
term_type
The "pre-evaluated" expression as an... |
def find_path_package(thepath):
"""
Takes a file system path and returns the module object of the python
package the said path belongs to. If the said path can not be
determined, it returns None.
"""
pname = find_path_package_name(thepath)
if not pname:
return None
fr... | Takes a file system path and returns the module object of the python
package the said path belongs to. If the said path can not be
determined, it returns None. |
def sample_stats_to_xarray(self):
"""Extract sample_stats from fit."""
dtypes = {"divergent__": bool, "n_leapfrog__": np.int64, "treedepth__": np.int64}
# copy dims and coords
dims = deepcopy(self.dims) if self.dims is not None else {}
coords = deepcopy(self.coords) if self.coor... | Extract sample_stats from fit. |
def removed(self):
'''
Returns all keys that have been removed.
If the keys are in child dictionaries they will be represented with
. notation
'''
def _removed(diffs, prefix):
keys = []
for key in diffs.keys():
if isinstance(diffs[... | Returns all keys that have been removed.
If the keys are in child dictionaries they will be represented with
. notation |
def int_to_bin(i):
""" Integer to two bytes """
# devide in two parts (bytes)
i1 = i % 256
i2 = int(i / 256)
# make string (little endian)
return chr(i1) + chr(i2) | Integer to two bytes |
def get_one_over_n_factorial(counter_entry):
r"""
Calculates the :math:`\frac{1}{\mathbf{n!}}` of eq. 6 (see Ale et al. 2013).
That is the invert of a product of factorials.
:param counter_entry: an entry of counter. That is an array of integers of length equal to the number of variables.
For insta... | r"""
Calculates the :math:`\frac{1}{\mathbf{n!}}` of eq. 6 (see Ale et al. 2013).
That is the invert of a product of factorials.
:param counter_entry: an entry of counter. That is an array of integers of length equal to the number of variables.
For instance, `counter_entry` could be `[1,0,1]` for three... |
def _set_range(self, init):
""" Reset the view.
"""
#PerspectiveCamera._set_range(self, init)
# Stop moving
self._speed *= 0.0
# Get window size (and store factor now to sync with resizing)
w, h = self._viewbox.size
w, h = float(w), float(h)
# ... | Reset the view. |
def __select_alternatives (self, property_set_, debug):
""" Returns the best viable alternative for this property_set
See the documentation for selection rules.
# TODO: shouldn't this be 'alternative' (singular)?
"""
# When selecting alternatives we have to consider defau... | Returns the best viable alternative for this property_set
See the documentation for selection rules.
# TODO: shouldn't this be 'alternative' (singular)? |
def get_template_names(self):
"""
datagrid的默认模板
"""
names = super(EasyUIDatagridView, self).get_template_names()
names.append('easyui/datagrid.html')
return names | datagrid的默认模板 |
def sg_input(shape=None, dtype=sg_floatx, name=None):
r"""Creates a placeholder.
Args:
shape: A tuple/list of integers. If an integers is given, it will turn to a list.
dtype: A data type. Default is float32.
name: A name for the placeholder.
Returns:
A wrapped placeholder `Tensor`... | r"""Creates a placeholder.
Args:
shape: A tuple/list of integers. If an integers is given, it will turn to a list.
dtype: A data type. Default is float32.
name: A name for the placeholder.
Returns:
A wrapped placeholder `Tensor`. |
def check_extracted_paths(namelist, subdir=None):
"""
Check whether zip file paths are all relative, and optionally in a
specified subdirectory, raises an exception if not
namelist: A list of paths from the zip file
subdir: If specified then check whether all paths in the zip file are
under t... | Check whether zip file paths are all relative, and optionally in a
specified subdirectory, raises an exception if not
namelist: A list of paths from the zip file
subdir: If specified then check whether all paths in the zip file are
under this subdirectory
Python docs are unclear about the securi... |
def replace_header(self, name, value):
"""
replace header with new value or add new header
return old header value, if any
"""
name_lower = name.lower()
for index in range(len(self.headers) - 1, -1, -1):
curr_name, curr_value = self.headers[index]
... | replace header with new value or add new header
return old header value, if any |
def images(arrays, labels=None, domain=None, w=None):
"""Display a list of images with optional labels.
Args:
arrays: A list of NumPy arrays representing images
labels: A list of strings to label each image.
Defaults to show index if None
domain: Domain of pixel values, inferred from min & max va... | Display a list of images with optional labels.
Args:
arrays: A list of NumPy arrays representing images
labels: A list of strings to label each image.
Defaults to show index if None
domain: Domain of pixel values, inferred from min & max values if None
w: width of output image, scaled using nea... |
def p_subind_strTO(p):
""" substr : LP TO expr RP
"""
p[0] = (make_typecast(TYPE.uinteger, make_number(0, lineno=p.lineno(2)),
p.lineno(1)),
make_typecast(TYPE.uinteger, p[3], p.lineno(2))) | substr : LP TO expr RP |
def participants(self):
"""
Access the participants
:returns: twilio.rest.api.v2010.account.conference.participant.ParticipantList
:rtype: twilio.rest.api.v2010.account.conference.participant.ParticipantList
"""
if self._participants is None:
self._participan... | Access the participants
:returns: twilio.rest.api.v2010.account.conference.participant.ParticipantList
:rtype: twilio.rest.api.v2010.account.conference.participant.ParticipantList |
def from_object(self, obj: Union[str, Any]) -> None:
"""Load values from an object."""
if isinstance(obj, str):
obj = importer.import_object_str(obj)
for key in dir(obj):
if key.isupper():
value = getattr(obj, key)
self._setattr(key, value... | Load values from an object. |
def users_text(self):
"""Return connected users information and collect if not available."""
if self._users_text is None:
self.chain.connection.log("Getting connected users text")
self._users_text = self.driver.get_users_text()
if self._users_text:
sel... | Return connected users information and collect if not available. |
def update_from_delta(self, delta, *args):
"""Apply the changes described in the dict ``delta``."""
for (node, extant) in delta.get('nodes', {}).items():
if extant:
if node in delta.get('node_val', {}) \
and 'location' in delta['node_val'][node]\
... | Apply the changes described in the dict ``delta``. |
def load_country_map_data():
"""Loading data for map with country map"""
csv_bytes = get_example_data(
'birth_france_data_for_country_map.csv', is_gzip=False, make_bytes=True)
data = pd.read_csv(csv_bytes, encoding='utf-8')
data['dttm'] = datetime.datetime.now().date()
data.to_sql( # pylint... | Loading data for map with country map |
def _sanity_check_all_marked_locations_are_registered(ir_blocks, query_metadata_table):
"""Assert that all locations in MarkLocation blocks have registered and valid metadata."""
# Grab all the registered locations, then make sure that:
# - Any location that appears in a MarkLocation block is also registere... | Assert that all locations in MarkLocation blocks have registered and valid metadata. |
def cancel_capture(self):
"""
cancel capturing finger
:return: bool
"""
command = const.CMD_CANCELCAPTURE
cmd_response = self.__send_command(command)
return bool(cmd_response.get('status')) | cancel capturing finger
:return: bool |
def check_base(path, base, os_sep=os.sep):
'''
Check if given absolute path is under or given base.
:param path: absolute path
:type path: str
:param base: absolute base path
:type base: str
:param os_sep: path separator, defaults to os.sep
:return: wether path is under given base or no... | Check if given absolute path is under or given base.
:param path: absolute path
:type path: str
:param base: absolute base path
:type base: str
:param os_sep: path separator, defaults to os.sep
:return: wether path is under given base or not
:rtype: bool |
def get_source_var_declaration(self, var):
""" Return the source mapping where the variable is declared
Args:
var (str): variable name
Returns:
(dict): sourceMapping
"""
return next((x.source_mapping for x in self.variables if x.name == var)) | Return the source mapping where the variable is declared
Args:
var (str): variable name
Returns:
(dict): sourceMapping |
def calc_A(Z, x):
""" Calculate the A matrix (coefficients) from Z and x
Parameters
----------
Z : pandas.DataFrame or numpy.array
Symmetric input output table (flows)
x : pandas.DataFrame or numpy.array
Industry output column vector
Returns
-------
pandas.DataFrame or ... | Calculate the A matrix (coefficients) from Z and x
Parameters
----------
Z : pandas.DataFrame or numpy.array
Symmetric input output table (flows)
x : pandas.DataFrame or numpy.array
Industry output column vector
Returns
-------
pandas.DataFrame or numpy.array
Symmet... |
def as_cpf(numero):
"""Formata um número de CPF. Se o número não for um CPF válido apenas
retorna o argumento sem qualquer modificação.
"""
_num = digitos(numero)
if is_cpf(_num):
return '{}.{}.{}-{}'.format(_num[:3], _num[3:6], _num[6:9], _num[9:])
return numero | Formata um número de CPF. Se o número não for um CPF válido apenas
retorna o argumento sem qualquer modificação. |
def to_array(self):
"""
Serializes this ContactMessage to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
"""
array = super(ContactMessage, self).to_array()
array['phone_number'] = u(self.phone_number) # py2: type unicode, py3: type... | Serializes this ContactMessage to a dictionary.
:return: dictionary representation of this object.
:rtype: dict |
def build_archive_file(archive_contents, zip_file):
"""Build a Tableau-compatible archive file."""
# This is tested against Desktop and Server, and reverse engineered by lots
# of trial and error. Do not change this logic.
for root_dir, _, files in os.walk(archive_contents):
relative_dir = os.p... | Build a Tableau-compatible archive file. |
def process_request(self, method, data=None):
"""Process request over HTTP to ubersmith instance.
method: Ubersmith API method string
data: dict of method arguments
"""
# make sure requested method is valid
self._validate_request_method(method)
# attemp... | Process request over HTTP to ubersmith instance.
method: Ubersmith API method string
data: dict of method arguments |
def push(self, task, func, *args, **kwargs):
"""
Pushes a configured task onto the queue.
Typically, you'll favor using the ``Gator.task`` method or
``Gator.options`` context manager for creating a task. Call this
only if you have specific needs or know what you're doing.
... | Pushes a configured task onto the queue.
Typically, you'll favor using the ``Gator.task`` method or
``Gator.options`` context manager for creating a task. Call this
only if you have specific needs or know what you're doing.
If the ``Task`` has the ``async = False`` option, the task wil... |
def delete(self, path, payload=None, headers=None):
"""HTTP DELETE operation.
:param path: URI Path
:param payload: HTTP Body
:param headers: HTTP Headers
:raises ApiError: Raises if the remote server encountered an error.
:raises ApiConnectionError: Raises if there was... | HTTP DELETE operation.
:param path: URI Path
:param payload: HTTP Body
:param headers: HTTP Headers
:raises ApiError: Raises if the remote server encountered an error.
:raises ApiConnectionError: Raises if there was a connectivity issue.
:return: Response |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.