code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def is_square_matrix(mat):
"""Test if an array is a square matrix."""
mat = np.array(mat)
if mat.ndim != 2:
return False
shape = mat.shape
return shape[0] == shape[1] | Test if an array is a square matrix. |
def _login(session):
"""Login to UPS."""
resp = session.get(LOGIN_URL, params=_get_params(session.auth.locale))
parsed = BeautifulSoup(resp.text, HTML_PARSER)
csrf = parsed.find(CSRF_FIND_TAG, CSRF_FIND_ATTR).get(VALUE_ATTR)
resp = session.post(LOGIN_URL, {
'userID': session.auth.username,
... | Login to UPS. |
def view_sbo(self):
"""View slackbuild.org
"""
sbo_url = self.sbo_url.replace("/slackbuilds/", "/repository/")
br1, br2, fix_sp = "", "", " "
if self.meta.use_colors in ["off", "OFF"]:
br1 = "("
br2 = ")"
fix_sp = ""
print("") # new l... | View slackbuild.org |
def match(self, path):
"""Return route handler with arguments if path matches this route.
Arguments:
path (str): Request path
Returns:
tuple or None: A tuple of three items:
1. Route handler (callable)
2. Positional arguments (list)
3. K... | Return route handler with arguments if path matches this route.
Arguments:
path (str): Request path
Returns:
tuple or None: A tuple of three items:
1. Route handler (callable)
2. Positional arguments (list)
3. Keyword arguments (dict)
... |
def del_application(self, application, sync=True):
"""
delete application from this team
:param application: the application to be deleted from this team
:param sync: If sync=True(default) synchronize with Ariane server. If sync=False,
add the application object on list to be rem... | delete application from this team
:param application: the application to be deleted from this team
:param sync: If sync=True(default) synchronize with Ariane server. If sync=False,
add the application object on list to be removed on next save().
:return: |
def dataframe(self):
"""
Returns a pandas DataFrame containing all other class properties and
values. The index for the DataFrame is the string abbreviation of the
team, such as 'PURDUE'.
"""
fields_to_include = {
'abbreviation': self.abbreviation,
... | Returns a pandas DataFrame containing all other class properties and
values. The index for the DataFrame is the string abbreviation of the
team, such as 'PURDUE'. |
def DictReader(file_obj, columns=None): # pylint: disable=invalid-name
"""
Reader for a parquet file object.
This function is a generator returning an OrderedDict for each row
of data in the parquet file. Nested values will be flattend into the
top-level dict and can be referenced with '.' notatio... | Reader for a parquet file object.
This function is a generator returning an OrderedDict for each row
of data in the parquet file. Nested values will be flattend into the
top-level dict and can be referenced with '.' notation (e.g. 'foo' -> 'bar'
is referenced as 'foo.bar')
:param file_obj: the fil... |
def restore_event(self, requestId):
"""restore an event based on the requestId.
For example if the user app had to shutdown with pending requests.
The user can rebuild the Events they were waiting for based on the requestId(s).
"""
with self.__requests:
if requestId ... | restore an event based on the requestId.
For example if the user app had to shutdown with pending requests.
The user can rebuild the Events they were waiting for based on the requestId(s). |
def on_persist_completed(self, block):
"""
Called when a block has been persisted to disk. Used as a hook to persist notification data.
Args:
block (neo.Core.Block): the currently persisting block
"""
if len(self._events_to_write):
addr_db = self.db.pref... | Called when a block has been persisted to disk. Used as a hook to persist notification data.
Args:
block (neo.Core.Block): the currently persisting block |
def create_json_archive(self):
"""create_json_archive"""
archive_data = {"packets": self.recv_msgs,
"dataset": self.dataset_name,
"num_packets": len(self.recv_msgs),
"created": rnow()}
self.write_to_file(archive_data,
... | create_json_archive |
def smart_convert(original, colorkey, pixelalpha):
"""
this method does several tests on a surface to determine the optimal
flags and pixel format for each tile surface.
this is done for the best rendering speeds and removes the need to
convert() the images on your own
"""
tile_size = origi... | this method does several tests on a surface to determine the optimal
flags and pixel format for each tile surface.
this is done for the best rendering speeds and removes the need to
convert() the images on your own |
def run(self, executable: Executable,
memory_map: Dict[str, List[Union[int, float]]] = None) -> np.ndarray:
"""
Run a quil executable. If the executable contains declared parameters, then a memory
map must be provided, which defines the runtime values of these parameters.
:p... | Run a quil executable. If the executable contains declared parameters, then a memory
map must be provided, which defines the runtime values of these parameters.
:param executable: The program to run. You are responsible for compiling this first.
:param memory_map: The mapping of declared parame... |
def edit( cls, record, parent = None, uifile = '', commit = True ):
"""
Prompts the user to edit the inputed record.
:param record | <orb.Table>
parent | <QWidget>
:return <bool> | accepted
"""
# create the dialog
... | Prompts the user to edit the inputed record.
:param record | <orb.Table>
parent | <QWidget>
:return <bool> | accepted |
def __set_rouge_dir(self, home_dir=None):
"""
Verfify presence of ROUGE-1.5.5.pl and data folder, and set
those paths.
"""
if not home_dir:
self._home_dir = self.__get_rouge_home_dir_from_settings()
else:
self._home_dir = home_dir
self... | Verfify presence of ROUGE-1.5.5.pl and data folder, and set
those paths. |
def thumbnail(self, size):
'''Get the thumbnail filename for a given size'''
if size in self.thumbnail_sizes:
return self.thumbnails.get(str(size))
else:
raise ValueError('Unregistered thumbnail size {0}'.format(size)) | Get the thumbnail filename for a given size |
def getContactItems(self, person):
"""
Return all L{EmailAddress} instances associated with the given person.
@type person: L{Person}
"""
return person.store.query(
EmailAddress,
EmailAddress.person == person) | Return all L{EmailAddress} instances associated with the given person.
@type person: L{Person} |
def setColor(self, typeID, color):
"""setColor(string, (integer, integer, integer, integer)) -> None
Sets the color of this type.
"""
self._connection._beginMessage(
tc.CMD_SET_VEHICLETYPE_VARIABLE, tc.VAR_COLOR, typeID, 1 + 1 + 1 + 1 + 1)
self._connection._string +=... | setColor(string, (integer, integer, integer, integer)) -> None
Sets the color of this type. |
def create_db_user(username, password=None, flags=None):
"""Create a databse user."""
flags = flags or u'-D -A -R'
sudo(u'createuser %s %s' % (flags, username), user=u'postgres')
if password:
change_db_user_password(username, password) | Create a databse user. |
def search(
self, query, accept_language=None, pragma=None, user_agent=None, client_id=None, client_ip=None, location=None, answer_count=None, country_code=None, count=None, freshness=None, market="en-us", offset=None, promote=None, response_filter=None, safe_search=None, set_lang=None, text_decorations=Non... | The Web Search API lets you send a search query to Bing and get back
search results that include links to webpages, images, and more.
:param query: The user's search query term. The term may not be empty.
The term may contain Bing Advanced Operators. For example, to limit
results to a... |
def _encrypt_message(self, msg, nonce, timestamp=None):
"""将公众号回复用户的消息加密打包
:param msg: 待回复用户的消息,xml格式的字符串
:param nonce: 随机串,可以自己生成,也可以用URL参数的nonce
:param timestamp: 时间戳,可以自己生成,也可以用URL参数的timestamp,如为None则自动用当前时间
:return: 加密后的可以直接回复用户的密文,包括msg_signature, timestamp, nonce, encrypt的... | 将公众号回复用户的消息加密打包
:param msg: 待回复用户的消息,xml格式的字符串
:param nonce: 随机串,可以自己生成,也可以用URL参数的nonce
:param timestamp: 时间戳,可以自己生成,也可以用URL参数的timestamp,如为None则自动用当前时间
:return: 加密后的可以直接回复用户的密文,包括msg_signature, timestamp, nonce, encrypt的xml格式的字符串 |
def getBurstingColumnsStats(self):
"""
Gets statistics on the Temporal Memory's bursting columns. Used as a metric
of Temporal Memory's learning performance.
:return: mean, standard deviation, and max of Temporal Memory's bursting
columns over time
"""
traceData = self.tm.mmGetTraceUnpredict... | Gets statistics on the Temporal Memory's bursting columns. Used as a metric
of Temporal Memory's learning performance.
:return: mean, standard deviation, and max of Temporal Memory's bursting
columns over time |
def _method_response_handler(self, response: Dict[str, Any]):
"""处理200~399段状态码,为对应的响应设置结果.
Parameters:
(response): - 响应的python字典形式数据
Return:
(bool): - 准确地说没有错误就会返回True
"""
code = response.get("CODE")
if code in (200, 300):
self._resu... | 处理200~399段状态码,为对应的响应设置结果.
Parameters:
(response): - 响应的python字典形式数据
Return:
(bool): - 准确地说没有错误就会返回True |
def _brute_force_install_pip(self):
"""A brute force install of pip itself."""
if os.path.exists(self.pip_installer_fname):
logger.debug("Using pip installer from %r", self.pip_installer_fname)
else:
logger.debug(
"Installer for pip not found in %r, downlo... | A brute force install of pip itself. |
def find_one(self, cls, id):
"""Required functionality."""
one = self._find(cls, {"_id": id})
if not one:
return None
return one[0] | Required functionality. |
def from_packed(cls, packed):
"""Unpack diploid genotypes that have been bit-packed into single
bytes.
Parameters
----------
packed : ndarray, uint8, shape (n_variants, n_samples)
Bit-packed diploid genotype array.
Returns
-------
g : Genotyp... | Unpack diploid genotypes that have been bit-packed into single
bytes.
Parameters
----------
packed : ndarray, uint8, shape (n_variants, n_samples)
Bit-packed diploid genotype array.
Returns
-------
g : GenotypeArray, shape (n_variants, n_samples, 2)
... |
def radio_status_encode(self, rssi, remrssi, txbuf, noise, remnoise, rxerrors, fixed):
'''
Status generated by radio and injected into MAVLink stream.
rssi : Local signal strength (uint8_t)
remrssi : Remote signal st... | Status generated by radio and injected into MAVLink stream.
rssi : Local signal strength (uint8_t)
remrssi : Remote signal strength (uint8_t)
txbuf : Remaining free buffer space in percent. (uint8_t)
... |
def wait_until_visible(self, timeout=None):
"""Search element and wait until it is visible
:param timeout: max time to wait
:returns: page element instance
"""
try:
self.utils.wait_until_element_visible(self, timeout)
except TimeoutException as exception:
... | Search element and wait until it is visible
:param timeout: max time to wait
:returns: page element instance |
def process_rdfgraph(self, rg, ont=None):
"""
Transform a skos terminology expressed in an rdf graph into an Ontology object
Arguments
---------
rg: rdflib.Graph
graph object
Returns
-------
Ontology
"""
# TODO: ontology metad... | Transform a skos terminology expressed in an rdf graph into an Ontology object
Arguments
---------
rg: rdflib.Graph
graph object
Returns
-------
Ontology |
def plot_macadam(
ellipse_scaling=10,
plot_filter_positions=False,
plot_standard_deviations=False,
plot_rgb_triangle=True,
plot_mesh=True,
n=1,
xy_to_2d=lambda xy: xy,
axes_labels=("x", "y"),
):
"""See <https://en.wikipedia.org/wiki/MacAdam_ellipse>,
<https://doi.org/10.1364%2FJO... | See <https://en.wikipedia.org/wiki/MacAdam_ellipse>,
<https://doi.org/10.1364%2FJOSA.32.000247>. |
def _handle_tag_definetext2(self):
"""Handle the DefineText2 tag."""
obj = _make_object("DefineText2")
self._generic_definetext_parser(obj, self._get_struct_rgba)
return obj | Handle the DefineText2 tag. |
def exit_config_mode(self, exit_config="return", pattern=r">"):
"""Exit configuration mode."""
return super(HuaweiBase, self).exit_config_mode(
exit_config=exit_config, pattern=pattern
) | Exit configuration mode. |
def classmethod(self, encoding):
"""Function decorator for class methods."""
# Add encodings for hidden self and cmd arguments.
encoding = ensure_bytes(encoding)
typecodes = parse_type_encoding(encoding)
typecodes.insert(1, b'@:')
encoding = b''.join(typecodes)
d... | Function decorator for class methods. |
def column_signs_(self):
"""
Return a numpy array with expected signs of features.
Values are
* +1 when all known terms which map to the column have positive sign;
* -1 when all known terms which map to the column have negative sign;
* ``nan`` when there are both positiv... | Return a numpy array with expected signs of features.
Values are
* +1 when all known terms which map to the column have positive sign;
* -1 when all known terms which map to the column have negative sign;
* ``nan`` when there are both positive and negative known terms
for this... |
def get_distance_metres(aLocation1, aLocation2):
"""
Returns the ground distance in metres between two LocationGlobal objects.
This method is an approximation, and will not be accurate over large distances and close to the
earth's poles. It comes from the ArduPilot test code:
https://github.com/d... | Returns the ground distance in metres between two LocationGlobal objects.
This method is an approximation, and will not be accurate over large distances and close to the
earth's poles. It comes from the ArduPilot test code:
https://github.com/diydrones/ardupilot/blob/master/Tools/autotest/common.py |
def download(self):
"""Downloads the data associated with this instance
Return:
mp3_directory (os.path): The directory into which the associated mp3's were downloaded
"""
mp3_directory = self._pre_download()
self.data.swifter.apply(func=lambda arg: self._download(*arg, ... | Downloads the data associated with this instance
Return:
mp3_directory (os.path): The directory into which the associated mp3's were downloaded |
def download_task(url, headers, destination, download_type='layer'):
'''download an image layer (.tar.gz) to a specified download folder.
This task is done by using local versions of the same download functions
that are used for the client.
core stream/download functions of the parent client.
... | download an image layer (.tar.gz) to a specified download folder.
This task is done by using local versions of the same download functions
that are used for the client.
core stream/download functions of the parent client.
Parameters
==========
image_id: the shasum id of the la... |
def function(self, x, y, sigma0, Rs, center_x=0, center_y=0):
"""
lensing potential
:param x:
:param y:
:param sigma0: sigma0/sigma_crit
:param a:
:param s:
:param center_x:
:param center_y:
:return:
"""
x_ = x - center_x
... | lensing potential
:param x:
:param y:
:param sigma0: sigma0/sigma_crit
:param a:
:param s:
:param center_x:
:param center_y:
:return: |
def add(self, *args, **kwargs):
"""Add Cookie objects by their names, or create new ones under
specified names.
Any unnamed arguments are interpreted as existing cookies, and
are added under the value in their .name attribute. With keyword
arguments, the key is interpreted as th... | Add Cookie objects by their names, or create new ones under
specified names.
Any unnamed arguments are interpreted as existing cookies, and
are added under the value in their .name attribute. With keyword
arguments, the key is interpreted as the cookie name and the
value as the ... |
def get_ranks(self):
'''
Returns
-------
pd.DataFrame
'''
if self._use_non_text_features:
return self._term_doc_matrix.get_metadata_freq_df()
else:
return self._term_doc_matrix.get_term_freq_df() | Returns
-------
pd.DataFrame |
def _fix_example_namespace(self):
"""Attempts to resolve issues where our samples use
'http://example.com/' for our example namespace but python-stix uses
'http://example.com' by removing the former.
"""
example_prefix = 'example' # Example ns prefix
idgen_prefix = idgen... | Attempts to resolve issues where our samples use
'http://example.com/' for our example namespace but python-stix uses
'http://example.com' by removing the former. |
def process_warn_strings(arguments):
"""Process string specifications of enabling/disabling warnings,
as passed to the --warn option or the SetOption('warn') function.
An argument to this option should be of the form <warning-class>
or no-<warning-class>. The warning class is munged in order
... | Process string specifications of enabling/disabling warnings,
as passed to the --warn option or the SetOption('warn') function.
An argument to this option should be of the form <warning-class>
or no-<warning-class>. The warning class is munged in order
to get an actual class name from the classes... |
def add(self, component: Union[Component, Sequence[Component]]) -> None:
"""Add a widget to the grid in the next available cell.
Searches over columns then rows for available cells.
Parameters
----------
components : bowtie._Component
A Bowtie widget instance.
... | Add a widget to the grid in the next available cell.
Searches over columns then rows for available cells.
Parameters
----------
components : bowtie._Component
A Bowtie widget instance. |
def flatatt(self, **attr):
'''Return a string with attributes to add to the tag'''
cs = ''
attr = self._attr
classes = self._classes
data = self._data
css = self._css
attr = attr.copy() if attr else {}
if classes:
cs = ' '.join(classes)
... | Return a string with attributes to add to the tag |
def _process_thread(self, client):
"""Process a single GRR client.
Args:
client: a GRR client object.
"""
system_type = client.data.os_info.system
print('System type: {0:s}'.format(system_type))
# If the list is supplied by the user via a flag, honor that.
artifact_list = []
if s... | Process a single GRR client.
Args:
client: a GRR client object. |
def serialize(self, queryset, **options):
"""
Serialize a queryset.
"""
self.options = options
self.stream = options.get("stream", StringIO())
self.primary_key = options.get("primary_key", None)
self.properties = options.get("properties")
self.geometry_fi... | Serialize a queryset. |
def in_file(self, filename: str) -> Iterator[FunctionDesc]:
"""
Returns an iterator over all of the functions definitions that are
contained within a given file.
"""
yield from self.__filename_to_functions.get(filename, []) | Returns an iterator over all of the functions definitions that are
contained within a given file. |
def _write_response(self, response):
"""Write the response back to the client
Arguments:
response -- the dictionary containing the response.
"""
status = '{} {} {}\r\n'.format(response['version'],
response['code'],
... | Write the response back to the client
Arguments:
response -- the dictionary containing the response. |
def set_python(self, value):
"""Expect list of record instances, convert to a SortedDict for internal representation"""
if not self.multiselect:
if value and not isinstance(value, list):
value = [value]
value = value or []
records = SortedDict()
for... | Expect list of record instances, convert to a SortedDict for internal representation |
def qteRemoveMode(self, mode: str):
"""
Remove ``mode`` and associated label.
If ``mode`` does not exist then nothing happens and the method
returns **False**, otherwise **True**.
|Args|
* ``pos`` (**QRect**): size and position of new window.
* ``windowID`` (**... | Remove ``mode`` and associated label.
If ``mode`` does not exist then nothing happens and the method
returns **False**, otherwise **True**.
|Args|
* ``pos`` (**QRect**): size and position of new window.
* ``windowID`` (**str**): unique window ID.
|Returns|
* ... |
def send_emission(self):
"""
emit and remove the first emission in the queue
"""
if self._emit_queue.empty():
return
emit = self._emit_queue.get()
emit() | emit and remove the first emission in the queue |
def check_tx_with_confirmations(self, tx_hash: str, confirmations: int) -> bool:
"""
Check tx hash and make sure it has the confirmations required
:param w3: Web3 instance
:param tx_hash: Hash of the tx
:param confirmations: Minimum number of confirmations required
:retur... | Check tx hash and make sure it has the confirmations required
:param w3: Web3 instance
:param tx_hash: Hash of the tx
:param confirmations: Minimum number of confirmations required
:return: True if tx was mined with the number of confirmations required, False otherwise |
def pad_length(s):
"""
Appends characters to the end of the string to increase the string length per
IBM Globalization Design Guideline A3: UI Expansion.
https://www-01.ibm.com/software/globalization/guidelines/a3.html
:param s: String to pad.
:returns: Padded string.
"""
padding_chars... | Appends characters to the end of the string to increase the string length per
IBM Globalization Design Guideline A3: UI Expansion.
https://www-01.ibm.com/software/globalization/guidelines/a3.html
:param s: String to pad.
:returns: Padded string. |
def entries(self):
"""A list of :class:`PasswordEntry` objects."""
timer = Timer()
passwords = []
logger.info("Scanning %s ..", format_path(self.directory))
listing = self.context.capture("find", "-type", "f", "-name", "*.gpg", "-print0")
for filename in split(listing, "\... | A list of :class:`PasswordEntry` objects. |
def get_fun(fun):
'''
Return a dict of the last function called for all minions
'''
with _get_serv(ret=None, commit=True) as cur:
sql = '''SELECT s.id,s.jid, s.full_ret
FROM `salt_returns` s
JOIN ( SELECT MAX(`jid`) as jid
from `salt_returns` ... | Return a dict of the last function called for all minions |
def set(self, key, value, *, section=DataStoreDocumentSection.Data):
""" Store a value under the specified key in the given section of the document.
This method stores a value into the specified section of the workflow data store
document. Any existing value is overridden. Before storing a valu... | Store a value under the specified key in the given section of the document.
This method stores a value into the specified section of the workflow data store
document. Any existing value is overridden. Before storing a value, any linked
GridFS document under the specified key is deleted.
... |
def has_column(self, table, column):
"""
Determine if the given table has a given column.
:param table: The table
:type table: str
:type column: str
:rtype: bool
"""
column = column.lower()
return column in list(map(lambda x: x.lower(), self.ge... | Determine if the given table has a given column.
:param table: The table
:type table: str
:type column: str
:rtype: bool |
def encode_ulid(value: hints.Buffer) -> str:
"""
Encode the given buffer to a :class:`~str` using Base32 encoding.
.. note:: This uses an optimized strategy from the `NUlid` project for encoding ULID
bytes specifically and is not meant for arbitrary encoding.
:param value: Bytes to encode
... | Encode the given buffer to a :class:`~str` using Base32 encoding.
.. note:: This uses an optimized strategy from the `NUlid` project for encoding ULID
bytes specifically and is not meant for arbitrary encoding.
:param value: Bytes to encode
:type value: :class:`~bytes`, :class:`~bytearray`, or :cl... |
def addRnaQuantificationSet(self):
"""
Adds an rnaQuantificationSet into this repo
"""
self._openRepo()
dataset = self._repo.getDatasetByName(self._args.datasetName)
if self._args.name is None:
name = getNameFromPath(self._args.filePath)
else:
... | Adds an rnaQuantificationSet into this repo |
def EXTRA_LOGGING(self):
"""
lista modulos con los distintos niveles a logear y su
nivel de debug
Por ejemplo:
[Logs]
EXTRA_LOGGING = oscar.paypal:DEBUG, django.db:INFO
"""
input_text = get('EXTRA_LOGGING', '')
modules = input_text.spli... | lista modulos con los distintos niveles a logear y su
nivel de debug
Por ejemplo:
[Logs]
EXTRA_LOGGING = oscar.paypal:DEBUG, django.db:INFO |
def update(self, allow_partial=True, force=False, **kwargs):
"""Updates record and returns True if record is complete after update, else False."""
if kwargs:
self.__init__(partial=allow_partial, force=force, **kwargs)
return not self._partial
if not force and CACHE.get(h... | Updates record and returns True if record is complete after update, else False. |
def order(self, *args):
"""Return a new Query with additional sort order(s) applied."""
# q.order(Employee.name, -Employee.age)
if not args:
return self
orders = []
o = self.orders
if o:
orders.append(o)
for arg in args:
if isinstance(arg, model.Property):
orders.ap... | Return a new Query with additional sort order(s) applied. |
def signature(self, value):
"""
:type value: any
:rtype: HMAC
"""
h = HMAC(self.key, self.digest, backend=settings.CRYPTOGRAPHY_BACKEND)
h.update(force_bytes(value))
return h | :type value: any
:rtype: HMAC |
def find_packages_parents_requirements_dists(pkg_names, working_set=None):
"""
Leverages the `find_packages_requirements_dists` but strip out the
distributions that matches pkg_names.
"""
dists = []
# opting for a naive implementation
targets = set(pkg_names)
for dist in find_packages_r... | Leverages the `find_packages_requirements_dists` but strip out the
distributions that matches pkg_names. |
def split_token(output):
"""
Split an output into token tuple, real output tuple.
:param output:
:return: tuple, tuple
"""
output = ensure_tuple(output)
flags, i, len_output, data_allowed = set(), 0, len(output), True
while i < len_output and isflag(output[i]):
if output[i].mu... | Split an output into token tuple, real output tuple.
:param output:
:return: tuple, tuple |
def failure_count(self):
"""
Amount of failed test cases in this list.
:return: integer
"""
return len([i for i, result in enumerate(self.data) if result.failure]) | Amount of failed test cases in this list.
:return: integer |
def save_neighbour_info(self, cache_dir, mask=None, **kwargs):
"""Cache resampler's index arrays if there is a cache dir."""
if cache_dir:
mask_name = getattr(mask, 'name', None)
filename = self._create_cache_filename(
cache_dir, mask=mask_name, **kwargs)
... | Cache resampler's index arrays if there is a cache dir. |
def list_user_access(self, user):
"""
Returns a list of all database names for which the specified user
has access rights.
"""
user = utils.get_name(user)
uri = "/%s/%s/databases" % (self.uri_base, user)
try:
resp, resp_body = self.api.method_get(uri)
... | Returns a list of all database names for which the specified user
has access rights. |
def _align_header(header, alignment, width, visible_width, is_multiline=False,
width_fn=None):
"Pad string header to width chars given known visible_width of the header."
if is_multiline:
header_lines = re.split(_multiline_codes, header)
padded_lines = [_align_header(h, alignme... | Pad string header to width chars given known visible_width of the header. |
def save(self, path="speech"):
"""Save data in file.
Args:
path (optional): A path to save file. Defaults to "speech".
File extension is optional. Absolute path is allowed.
Returns:
The path to the saved file.
"""
if self._data is None:
... | Save data in file.
Args:
path (optional): A path to save file. Defaults to "speech".
File extension is optional. Absolute path is allowed.
Returns:
The path to the saved file. |
def _collect_masters_map(self, response):
'''
Collect masters map from the network.
:return:
'''
while True:
try:
data, addr = self._socket.recvfrom(0x400)
if data:
if addr not in response:
re... | Collect masters map from the network.
:return: |
def makeParameterTable(filename, params):
'''
Makes the parameter table for the paper, saving it to a tex file in the tables folder.
Also makes two partial parameter tables for the slides.
Parameters
----------
filename : str
Name of the file in which to save output (in the tables dire... | Makes the parameter table for the paper, saving it to a tex file in the tables folder.
Also makes two partial parameter tables for the slides.
Parameters
----------
filename : str
Name of the file in which to save output (in the tables directory).
Suffix .tex is automatically added.
... |
def do_bash_complete(cli, prog_name):
"""Do the completion for bash
Parameters
----------
cli : click.Command
The main click Command of the program
prog_name : str
The program name on the command line
Returns
-------
bool
True if the completion was successful, F... | Do the completion for bash
Parameters
----------
cli : click.Command
The main click Command of the program
prog_name : str
The program name on the command line
Returns
-------
bool
True if the completion was successful, False otherwise |
def set(self, stype, sid, fields):
"""
Send a request to the API to modify something in the database if logged in.
:param str stype: What are we modifying? One of: votelist, vnlist, wishlist
:param int sid: The ID that we're modifying.
:param dict fields: A dictionary of the fie... | Send a request to the API to modify something in the database if logged in.
:param str stype: What are we modifying? One of: votelist, vnlist, wishlist
:param int sid: The ID that we're modifying.
:param dict fields: A dictionary of the fields and their values
:raises ServerError: Raise... |
def to_prettytable(df):
"""Convert DataFrame into ``PrettyTable``.
"""
pt = PrettyTable()
pt.field_names = df.columns
for tp in zip(*(l for col, l in df.iteritems())):
pt.add_row(tp)
return pt | Convert DataFrame into ``PrettyTable``. |
def swap(tokens, maxdist=2):
"""Perform a swap operation on a sequence of tokens, exhaustively swapping all tokens up to the maximum specified distance. This is a subset of all permutations."""
assert maxdist >= 2
tokens = list(tokens)
if maxdist > len(tokens):
maxdist = len(tokens)
l = len(... | Perform a swap operation on a sequence of tokens, exhaustively swapping all tokens up to the maximum specified distance. This is a subset of all permutations. |
def implied_local_space(*, arg_index=None, keys=None):
"""Return a simplification that converts the positional argument
`arg_index` from (str, int) to a subclass of :class:`.LocalSpace`, as well
as any keyword argument with one of the given keys.
The exact type of the resulting Hilbert space is determi... | Return a simplification that converts the positional argument
`arg_index` from (str, int) to a subclass of :class:`.LocalSpace`, as well
as any keyword argument with one of the given keys.
The exact type of the resulting Hilbert space is determined by
the `default_hs_cls` argument of :func:`init_algebr... |
def cancel(self, consumer_tag):
"""Cancel a channel by consumer tag."""
if not self.channel.connection:
return
self.channel.basic_cancel(consumer_tag) | Cancel a channel by consumer tag. |
def update_dependency(self, tile, depinfo, destdir=None):
"""Attempt to install or update a dependency to the latest version.
Args:
tile (IOTile): An IOTile object describing the tile that has the dependency
depinfo (dict): a dictionary from tile.dependencies specifying the depe... | Attempt to install or update a dependency to the latest version.
Args:
tile (IOTile): An IOTile object describing the tile that has the dependency
depinfo (dict): a dictionary from tile.dependencies specifying the dependency
destdir (string): An optional folder into which to... |
def set_parameter(name, parameter, value, path=None):
'''
Set the value of a cgroup parameter for a container.
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.set... | Set the value of a cgroup parameter for a container.
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.set_parameter name parameter value |
def get_group_category(self, category):
"""
Get a single group category.
:calls: `GET /api/v1/group_categories/:group_category_id \
<https://canvas.instructure.com/doc/api/group_categories.html#method.group_categories.show>`_
:param category: The object or ID of the category.
... | Get a single group category.
:calls: `GET /api/v1/group_categories/:group_category_id \
<https://canvas.instructure.com/doc/api/group_categories.html#method.group_categories.show>`_
:param category: The object or ID of the category.
:type category: :class:`canvasapi.group.GroupCategory... |
def sharedInterfaces():
"""
This attribute is the public interface for code which wishes to discover
the list of interfaces allowed by this Share. It is a list of
Interface objects.
"""
def get(self):
if not self.sharedInterfaceNames:
return (... | This attribute is the public interface for code which wishes to discover
the list of interfaces allowed by this Share. It is a list of
Interface objects. |
def lower(self):
"""Lower bound"""
if self._reaction in self._view._flipped:
return -super(FlipableFluxBounds, self).upper
return super(FlipableFluxBounds, self).lower | Lower bound |
def match_tracks(self, set_a, set_b, closest_matches=False):
"""
Find the optimal set of matching assignments between set a and set b. This function supports optimal 1:1
matching using the Munkres method and matching from every object in set a to the closest object in set b.
In this situ... | Find the optimal set of matching assignments between set a and set b. This function supports optimal 1:1
matching using the Munkres method and matching from every object in set a to the closest object in set b.
In this situation set b accepts multiple matches from set a.
Args:
set_a... |
def build_polygons(self, polygons):
""" Process data to construct polygons
This method is built from the assumption that the polygons parameter
is a list of:
list of lists or tuples : a list of path points, each one
indicating the point coordinates --
[lat,ln... | Process data to construct polygons
This method is built from the assumption that the polygons parameter
is a list of:
list of lists or tuples : a list of path points, each one
indicating the point coordinates --
[lat,lng], [lat, lng], (lat, lng), ...
tup... |
def untrigger(queue, trigger=_c.FSQ_TRIGGER):
'''Uninstalls the trigger for the specified queue -- if a queue has no
trigger, this function is a no-op.'''
trigger_path = fsq_path.trigger(queue, trigger=trigger)
_queue_ok(os.path.dirname(trigger_path))
try:
os.unlink(trigger_path)
exce... | Uninstalls the trigger for the specified queue -- if a queue has no
trigger, this function is a no-op. |
def assert_200(response, max_len=500):
""" Check that a HTTP response returned 200. """
if response.status_code == 200:
return
raise ValueError(
"Response was {}, not 200:\n{}\n{}".format(
response.status_code,
json.dumps(dict(response.headers), indent=2),
response.content... | Check that a HTTP response returned 200. |
def read_pure_water_absorption_from_file(self, file_name):
"""Read the pure water absorption from a csv formatted file
:param file_name: filename and path of the csv file
"""
lg.info('Reading water absorption from file')
try:
self.a_water = self._read_iop_from_file(f... | Read the pure water absorption from a csv formatted file
:param file_name: filename and path of the csv file |
def encoded_to_array(encoded):
"""
Turn a dictionary with base64 encoded strings back into a numpy array.
Parameters
------------
encoded : dict
Has keys:
dtype: string of dtype
shape: int tuple of shape
base64: base64 encoded string of flat array
binary: deco... | Turn a dictionary with base64 encoded strings back into a numpy array.
Parameters
------------
encoded : dict
Has keys:
dtype: string of dtype
shape: int tuple of shape
base64: base64 encoded string of flat array
binary: decode result coming from numpy.tostring
R... |
def toy_heaviside(seed=default_seed, max_iters=100, optimize=True, plot=True):
"""
Simple 1D classification example using a heavy side gp transformation
:param seed: seed value for data generation (default is 4).
:type seed: int
"""
try:import pods
except ImportError:print('pods unavailab... | Simple 1D classification example using a heavy side gp transformation
:param seed: seed value for data generation (default is 4).
:type seed: int |
def RABC(self):
""" Return ABC
轉折點 ABC
"""
A = self.raw_data[-3]*2 - self.raw_data[-6]
B = self.raw_data[-2]*2 - self.raw_data[-5]
C = self.raw_data[-1]*2 - self.raw_data[-4]
return '(%.2f,%.2f,%.2f)' % (A,B,C) | Return ABC
轉折點 ABC |
def complete(self, uio, dropped=False):
"""Query for all missing information in the transaction"""
if self.dropped and not dropped:
# do nothing for dropped xn, unless specifically told to
return
for end in ['src', 'dst']:
if getattr(self, end):
... | Query for all missing information in the transaction |
def get_finder(import_path):
"""Get a process finder."""
finder_class = import_string(import_path)
if not issubclass(finder_class, BaseProcessesFinder):
raise ImproperlyConfigured(
'Finder "{}" is not a subclass of "{}"'.format(finder_class, BaseProcessesFinder))
return finder_class(... | Get a process finder. |
def as_dict(self):
"""
Json-serializable dict representation of CompletePhononDos.
"""
d = {"@module": self.__class__.__module__,
"@class": self.__class__.__name__,
"structure": self.structure.as_dict(),
"frequencies": list(self.frequencies),
... | Json-serializable dict representation of CompletePhononDos. |
def to_fmt(self) -> str:
"""
Provide a useful representation of the register.
"""
infos = fmt.end(";\n", [])
s = fmt.sep(', ', [])
for ids in sorted(self.states.keys()):
s.lsdata.append(str(ids))
infos.lsdata.append(fmt.block('(', ')', [s]))
in... | Provide a useful representation of the register. |
def create_simple_tear_sheet(returns,
positions=None,
transactions=None,
benchmark_rets=None,
slippage=None,
estimate_intraday='infer',
live_start... | Simpler version of create_full_tear_sheet; generates summary performance
statistics and important plots as a single image.
- Plots: cumulative returns, rolling beta, rolling Sharpe, underwater,
exposure, top 10 holdings, total holdings, long/short holdings,
daily turnover, transaction time dist... |
def check_support_user_port(cls, hw_info_ex):
"""
Checks whether the module supports a user I/O port.
:param HardwareInfoEx hw_info_ex:
Extended hardware information structure (see method :meth:`get_hardware_info`).
:return: True when the module supports a user I/O port, oth... | Checks whether the module supports a user I/O port.
:param HardwareInfoEx hw_info_ex:
Extended hardware information structure (see method :meth:`get_hardware_info`).
:return: True when the module supports a user I/O port, otherwise False.
:rtype: bool |
async def send_photo(self, path, entity):
"""Sends the file located at path to the desired entity as a photo"""
await self.send_file(
entity, path,
progress_callback=self.upload_progress_callback
)
print('Photo sent!') | Sends the file located at path to the desired entity as a photo |
def solve_limited(self, assumptions=[]):
"""
Solve internal formula using given budgets for conflicts and
propagations.
"""
if self.maplesat:
if self.use_timer:
start_time = time.clock()
# saving default SIGINT handler
... | Solve internal formula using given budgets for conflicts and
propagations. |
def remove_properties(self):
"""
Removes the property layer (if exists) of the object (in memory)
"""
if self.features_layer is not None:
self.features_layer.remove_properties()
if self.header is not None:
self.header.remove_lp('features') | Removes the property layer (if exists) of the object (in memory) |
def quaternion_from_axis_rotation(angle, axis):
"""Return quaternion for rotation about given axis.
Args:
angle (float): Angle in radians.
axis (str): Axis for rotation
Returns:
Quaternion: Quaternion for axis rotation.
Raises:
ValueError: Invalid input axis.
"""
... | Return quaternion for rotation about given axis.
Args:
angle (float): Angle in radians.
axis (str): Axis for rotation
Returns:
Quaternion: Quaternion for axis rotation.
Raises:
ValueError: Invalid input axis. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.