code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def from_path_by_pattern(dir_path, pattern=list()):
"""Create a new FileCollection, and select all files except file
matching ignore-rule::
dir_path = "your/path"
fc = FileCollection.from_path_by_pattern(
dir_path, pattern=["log"])
:p... | Create a new FileCollection, and select all files except file
matching ignore-rule::
dir_path = "your/path"
fc = FileCollection.from_path_by_pattern(
dir_path, pattern=["log"])
:param dir_path: the root directory you want to start with
... |
def update_now_playing(
self,
artist,
title,
album=None,
album_artist=None,
duration=None,
track_number=None,
mbid=None,
context=None,
):
"""
Used to notify Last.fm that a user has started listening to a track.
Para... | Used to notify Last.fm that a user has started listening to a track.
Parameters:
artist (Required) : The artist name
title (Required) : The track title
album (Optional) : The album name.
album_artist (Optional) : The album artist - if this dif... |
def _build_named_object_ids(parameters):
"""Builds a list of NamedObjectId."""
if isinstance(parameters, str):
return [_build_named_object_id(parameters)]
return [_build_named_object_id(parameter) for parameter in parameters] | Builds a list of NamedObjectId. |
def update_text(self, selector, new_value, by=By.CSS_SELECTOR,
timeout=settings.LARGE_TIMEOUT, retry=False):
""" The shorter version of update_text_value(), which
clears existing text and adds new text into the text field.
We want to keep the old version for backward ... | The shorter version of update_text_value(), which
clears existing text and adds new text into the text field.
We want to keep the old version for backward compatibility. |
def delete_unused_versions(self, versions_to_keep=10):
"""
Deletes unused versions
"""
# get versions in use
environments = self.ebs.describe_environments(application_name=self.app_name, include_deleted=False)
environments = environments['DescribeEnvironmentsResponse']['... | Deletes unused versions |
def _unify_keywords():
'''
Merge /etc/portage/package.keywords and
/etc/portage/package.accept_keywords.
'''
old_path = BASE_PATH.format('keywords')
if os.path.exists(old_path):
if os.path.isdir(old_path):
for triplet in salt.utils.path.os_walk(old_path):
for ... | Merge /etc/portage/package.keywords and
/etc/portage/package.accept_keywords. |
def _parse_method_data(self, method_name, method_data):
'''
Helper function to construct the method request params, models, request_templates and
integration_type values needed to configure method request integration/mappings.
'''
method_params = {}
method_models = {}
... | Helper function to construct the method request params, models, request_templates and
integration_type values needed to configure method request integration/mappings. |
def profile(prof=None, instances=None, opts=None, **kwargs):
'''
Create a cloud vm with the given profile and instances, instances can be a
list or comma-delimited string
CLI Example:
.. code-block:: bash
salt-run cloud.profile prof=my-ec2 instances=node1,node2,node3
'''
if prof i... | Create a cloud vm with the given profile and instances, instances can be a
list or comma-delimited string
CLI Example:
.. code-block:: bash
salt-run cloud.profile prof=my-ec2 instances=node1,node2,node3 |
def update_image_location(self, timeline_json):
"""Update the image location."""
if not timeline_json:
return False
# If we get a list of objects back (likely)
# then we just want the first one as it should be the "newest"
if isinstance(timeline_json, (tuple, list)):... | Update the image location. |
def get_setup(Cnt = {}):
'''Return a dictionary of GPU, mu-map hardware and third party set-up.'''
# the name of the folder for NiftyPET tools
Cnt['DIRTOOLS'] = DIRTOOLS
# additional paramteres for compiling tools with cmake
Cnt['CMAKE_TLS_PAR'] = CMAKE_TLS_PAR
# hardware mu-maps
Cnt[... | Return a dictionary of GPU, mu-map hardware and third party set-up. |
def new_batch(self):
"""
Return a new batch of X and Y by taking a chunk of data from the complete X and Y
"""
i = next(self.slicer)
return self.X_all[i], self.Y_all[i] | Return a new batch of X and Y by taking a chunk of data from the complete X and Y |
def merge(a, b):
"""
Merge all attributes and metadata from I{a} to I{b}.
@param a: A I{source} object
@type a: L{Object}
@param b: A I{destination} object
@type b: L{Object}
"""
for item in a:
setattr(b, item[0], item[1])
b.__metadata__ = b.__metadata__
return b | Merge all attributes and metadata from I{a} to I{b}.
@param a: A I{source} object
@type a: L{Object}
@param b: A I{destination} object
@type b: L{Object} |
def _subscribed_event_count(self) -> int:
""" Returns the total amount of subscribed events.
:return: Integer amount events.
:rtype: int
"""
event_counter = Counter() # type: Dict[Any, int]
for key, values in self._events.items():
event_counter[key] = len(v... | Returns the total amount of subscribed events.
:return: Integer amount events.
:rtype: int |
def app_activate(caption):
"""
use shell to bring the application with caption to front
"""
try:
shell = win32com.client.Dispatch("WScript.Shell")
shell.AppActivate(caption)
except Exception as ex:
print('error calling win32com.client.Dispatch (AppActivate)') | use shell to bring the application with caption to front |
def crs_text_element(crs, feature, parent):
"""Retrieve coordinate reference system text string from definitions.
Example usage: crs_text_element('EPSG:3857').
"""
_ = feature, parent # NOQA
crs_definition = QgsCoordinateReferenceSystem(crs)
crs_description = crs_definition.description()
t... | Retrieve coordinate reference system text string from definitions.
Example usage: crs_text_element('EPSG:3857'). |
def install_program(self, extra_args):
"""Install the app to the virtualenv"""
pip = Command(path.join(self.env, 'bin', 'pip'))
args = ['install', self.raw_name,
'--install-option', '--install-scripts={}'
.format(self.env_bin)] + list(extra_args)
print_pre... | Install the app to the virtualenv |
def quote(c):
"""Quote a single character."""
i = ord(c)
return ESCAPE + HEX[i//16] + HEX[i%16] | Quote a single character. |
def send_reset_password_instructions(self, user):
"""
Sends the reset password instructions email for the specified user.
Sends signal `reset_password_instructions_sent`.
:param user: The user to send the instructions to.
"""
token = self.security_utils_service.generate... | Sends the reset password instructions email for the specified user.
Sends signal `reset_password_instructions_sent`.
:param user: The user to send the instructions to. |
def ticket_macro_apply(self, ticket_id, id, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/macros#show-ticket-after-changes"
api_path = "/api/v2/tickets/{ticket_id}/macros/{id}/apply.json"
api_path = api_path.format(ticket_id=ticket_id, id=id)
return self.call(api_path, **k... | https://developer.zendesk.com/rest_api/docs/core/macros#show-ticket-after-changes |
def tagged_projects(
self,
tag):
"""*return a list of projects contained within this taskpaper object filtered by a given tag*
**Key Arguments:**
- ``tag`` -- the tag to filter the projects by.
**Return:**
- ``projectList`` -- the list of filtere... | *return a list of projects contained within this taskpaper object filtered by a given tag*
**Key Arguments:**
- ``tag`` -- the tag to filter the projects by.
**Return:**
- ``projectList`` -- the list of filtered projects
**Usage:**
To filter the projects r... |
def PrivateToPublicOpenSSH(key, host):
""" Computes the OpenSSH public key format given a private key. """
# Create public key from private key.
ssh_rsa = '00000007' + base64.b16encode('ssh-rsa')
# Exponent.
exponent = '%x' % (key.e,)
if len(exponent) % 2:
exponent = '0' + exponent
ssh_rsa += '%08x'... | Computes the OpenSSH public key format given a private key. |
def getCitations(self, field = None, values = None, pandasFriendly = True, counts = True):
"""Creates a pandas ready dict with each row a different citation the contained Records and columns containing the original string, year, journal, author's name and the number of times it occured.
There are also ... | Creates a pandas ready dict with each row a different citation the contained Records and columns containing the original string, year, journal, author's name and the number of times it occured.
There are also options to filter the output citations with _field_ and _values_
# Parameters
_field... |
def ResourceEnum(ctx):
"""Resource Type Enumeration."""
return Enum(
ctx,
food=0,
wood=1,
stone=2,
gold=3,
decay=12,
fish=17,
default=Pass # lots of resource types exist
) | Resource Type Enumeration. |
def debug_text_simple(self, text: str):
""" Draws a text in the top left corner of the screen (up to a max of 6 messages it seems). Don't forget to add 'await self._client.send_debug'. """
self._debug_texts.append(self.to_debug_message(text)) | Draws a text in the top left corner of the screen (up to a max of 6 messages it seems). Don't forget to add 'await self._client.send_debug'. |
def _parse_contract_headers(self, table):
"""
Parse the years on the contract.
The years are listed as the headers on the contract. The first header
contains 'Team' which specifies the player's current team and should
not be included in the years.
Parameters
---... | Parse the years on the contract.
The years are listed as the headers on the contract. The first header
contains 'Team' which specifies the player's current team and should
not be included in the years.
Parameters
----------
table : PyQuery object
A PyQuery o... |
def wrap_node(self, node, options):
'''\
celery registers tasks by decorating them, and so do we, so the user
can pass a celery task and we'll wrap our code with theirs in a nice
package celery can execute.
'''
if 'celery_task' in options:
return options['cele... | \
celery registers tasks by decorating them, and so do we, so the user
can pass a celery task and we'll wrap our code with theirs in a nice
package celery can execute. |
def _from_dict(cls, _dict):
"""Initialize a Classifier object from a json dictionary."""
args = {}
if 'classifier_id' in _dict:
args['classifier_id'] = _dict.get('classifier_id')
else:
raise ValueError(
'Required property \'classifier_id\' not pres... | Initialize a Classifier object from a json dictionary. |
def _extract_country_code(number):
"""Extracts country calling code from number.
Returns a 2-tuple of (country_calling_code, rest_of_number). It assumes
that the leading plus sign or IDD has already been removed. Returns (0,
number) if number doesn't start with a valid country calling code.
"""
... | Extracts country calling code from number.
Returns a 2-tuple of (country_calling_code, rest_of_number). It assumes
that the leading plus sign or IDD has already been removed. Returns (0,
number) if number doesn't start with a valid country calling code. |
def build_routes(iface, **settings):
'''
Add route scripts for a network interface using up commands.
CLI Example:
.. code-block:: bash
salt '*' ip.build_routes eth0 <settings>
'''
opts = _parse_routes(iface, settings)
try:
template = JINJA.get_template('route_eth.jinja')... | Add route scripts for a network interface using up commands.
CLI Example:
.. code-block:: bash
salt '*' ip.build_routes eth0 <settings> |
def run_on_opencv_image(self, image):
"""
Arguments:
image (np.ndarray): an image as returned by OpenCV
Returns:
prediction (BoxList): the detected objects. Additional information
of the detection properties can be found in the fields of
t... | Arguments:
image (np.ndarray): an image as returned by OpenCV
Returns:
prediction (BoxList): the detected objects. Additional information
of the detection properties can be found in the fields of
the BoxList via `prediction.fields()` |
def GET_blockchain_ops( self, path_info, blockchain_name, blockheight ):
"""
Get the name's historic name operations
Reply the list of nameops at the given block height
Reply 404 for blockchains other than those supported
Reply 502 for any error we have in talking to the blocksta... | Get the name's historic name operations
Reply the list of nameops at the given block height
Reply 404 for blockchains other than those supported
Reply 502 for any error we have in talking to the blockstack server |
def send_message(self,body):
"""
Send a message to the room.
:Parameters:
- `body`: the message body.
:Types:
- `body`: `unicode`
"""
m=Message(to_jid=self.room_jid.bare(),stanza_type="groupchat",body=body)
self.manager.stream.send(m) | Send a message to the room.
:Parameters:
- `body`: the message body.
:Types:
- `body`: `unicode` |
def groupby_field(records, field_name, skip_none=True):
"""
Given a list of objects, group them into a dictionary by
the unique values of a given field name.
"""
return apply_groupby(
records,
lambda obj: getattr(obj, field_name),
skip_none=skip_none) | Given a list of objects, group them into a dictionary by
the unique values of a given field name. |
def _deserialize(self, value, attr, data):
"""Override ``_deserialize`` for customizing the exception raised."""
try:
return super()._deserialize(value, attr, data)
except ValidationError as ex:
if 'deserialization_schema_selector' in ex.messages[0]:
ex.me... | Override ``_deserialize`` for customizing the exception raised. |
def validate_sqs_policy(self, accounts):
"""Given a list of accounts, ensures that the SQS policy allows all the accounts to write to the queue
Args:
accounts (`list` of :obj:`Account`): List of accounts
Returns:
`None`
"""
sqs_queue_name = self.dbconfig... | Given a list of accounts, ensures that the SQS policy allows all the accounts to write to the queue
Args:
accounts (`list` of :obj:`Account`): List of accounts
Returns:
`None` |
def update_window(turn_from, tick_from, turn_to, tick_to, updfun, branchd):
"""Iterate over a window of time in ``branchd`` and call ``updfun`` on the values"""
if turn_from in branchd:
# Not including the exact tick you started from because deltas are *changes*
for past_state in branchd[turn_fr... | Iterate over a window of time in ``branchd`` and call ``updfun`` on the values |
def get_bootstrap_connectivity(self, measure_names, repeats=100, num_samples=None, plot=False, random_state=None):
""" Calculate bootstrap estimates of spectral connectivity measures.
Bootstrapping is performed on trial level.
Parameters
----------
measure_names : {str, list of... | Calculate bootstrap estimates of spectral connectivity measures.
Bootstrapping is performed on trial level.
Parameters
----------
measure_names : {str, list of str}
Name(s) of the connectivity measure(s) to calculate. See :class:`Connectivity` for supported measures.
... |
def add_attempt(self):
"""Add an attempt when a object is a non-ok state
:return: None
"""
self.attempt += 1
self.attempt = min(self.attempt, self.max_check_attempts) | Add an attempt when a object is a non-ok state
:return: None |
def count_reads(self, l):
"""
Iterate over the reads on a particular genome in the bam file.
Parameters
----------
l : str
A location.
"""
if self.__paired:
cmd = [self.__samtools, 'view', '-c', '-f', '3', self.__bam, l]
... | Iterate over the reads on a particular genome in the bam file.
Parameters
----------
l : str
A location. |
def make_table(self, renderable):
"""Makes unique anchor prefixes so that multiple tables may exist
on the same page without conflict."""
self._make_prefix()
diffs = renderable.diff._diff
# set up iterator to wrap lines that exceed desired width
if self._wrapcolumn:
... | Makes unique anchor prefixes so that multiple tables may exist
on the same page without conflict. |
def usb_info(self):
""" The camera's USB information. """
return UsbInformation(self._abilities.usb_vendor,
self._abilities.usb_product,
self._abilities.usb_class,
self._abilities.usb_subclass,
... | The camera's USB information. |
def laid_out_slice_num(self, tensor_shape):
"""A LaidOutTensor with an int32 scalar, identical for identical slices.
This is useful for synchronizing random operations.
Args:
tensor_shape: a TensorShape
Returns:
a LaidOutTensor where each slice is an integer scalar.
"""
ret = self.... | A LaidOutTensor with an int32 scalar, identical for identical slices.
This is useful for synchronizing random operations.
Args:
tensor_shape: a TensorShape
Returns:
a LaidOutTensor where each slice is an integer scalar. |
def _from_stream(cls, stream, blob, filename=None):
"""
Return an instance of the |Image| subclass corresponding to the
format of the image in *stream*.
"""
image_header = _ImageHeaderFactory(stream)
if filename is None:
filename = 'image.%s' % image_header.de... | Return an instance of the |Image| subclass corresponding to the
format of the image in *stream*. |
def _analyze_txt_config(self, config_string=None):
"""
Analyze the given container and return the corresponding job.
If ``config_string`` is ``None``,
try reading it from the TXT config file inside the container.
:param string config_string: the configuration string
:rt... | Analyze the given container and return the corresponding job.
If ``config_string`` is ``None``,
try reading it from the TXT config file inside the container.
:param string config_string: the configuration string
:rtype: :class:`~aeneas.job.Job` |
def _detect_screen_size(use_curses, screen_lines_def):
"""Attempt to work out the number of lines on the screen.
This is called by page(). It can raise an error (e.g. when run in the
test suite), so it's separated out so it can easily be called in a try block.
"""
TERM = os.environ.get('TERM',N... | Attempt to work out the number of lines on the screen.
This is called by page(). It can raise an error (e.g. when run in the
test suite), so it's separated out so it can easily be called in a try block. |
def as_namedtuple(self):
"""
Export color register as namedtuple.
"""
d = self.as_dict()
return namedtuple('ColorRegister', d.keys())(*d.values()) | Export color register as namedtuple. |
def mac_access_list_extended_hide_mac_acl_ext_seq_seq_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
mac = ET.SubElement(config, "mac", xmlns="urn:brocade.com:mgmt:brocade-mac-access-list")
access_list = ET.SubElement(mac, "access-list")
exte... | Auto Generated Code |
def shot_create_task(self, *args, **kwargs):
"""Create a new task
:returns: None
:rtype: None
:raises: None
"""
if not self.cur_shot:
return
task = self.create_task(element=self.cur_shot)
if task:
taskdata = djitemdata.TaskItemData... | Create a new task
:returns: None
:rtype: None
:raises: None |
def make_interface_child(device_name, interface_name, parent_name):
'''
.. versionadded:: 2019.2.0
Set an interface as part of a LAG.
device_name
The name of the device, e.g., ``edge_router``.
interface_name
The name of the interface to be attached to LAG, e.g., ``xe-1/0/2``.
... | .. versionadded:: 2019.2.0
Set an interface as part of a LAG.
device_name
The name of the device, e.g., ``edge_router``.
interface_name
The name of the interface to be attached to LAG, e.g., ``xe-1/0/2``.
parent_name
The name of the LAG interface, e.g., ``ae13``.
CLI Exa... |
def comments(self,minutes=False):
"""
Add comment lines/text to an existing plot. Defaults to seconds.
Call after a plot has been made, and after margins have been set.
"""
if self.comments==0:
return
self.log.debug("adding comments to plot")
for i,t i... | Add comment lines/text to an existing plot. Defaults to seconds.
Call after a plot has been made, and after margins have been set. |
def registergrant(source=None, setspec=None):
"""Harvest grants from OpenAIRE."""
with open(source, 'r') as fp:
data = json.load(fp)
register_grant(data) | Harvest grants from OpenAIRE. |
def get_centers(self):
"""!
@brief Returns list of centers of allocated clusters.
@see process()
@see get_clusters()
"""
if isinstance(self.__centers, list):
return self.__centers
return self.__centers.tolist() | !
@brief Returns list of centers of allocated clusters.
@see process()
@see get_clusters() |
def get_create_api(self, resource):
""" Generates the meta descriptor for the resource listing api. """
create_api = {
'path': '/%s/' % resource.get_api_name(),
'description': 'Operations on %s' % resource.model.__name__,
'operations': [
{
... | Generates the meta descriptor for the resource listing api. |
def installed(name,
pkgs=None,
user=None,
install_global=False,
env=None):
'''
Verify that the given package is installed and is at the correct version
(if specified).
.. code-block:: yaml
ShellCheck-0.3.5:
cabal:
- ... | Verify that the given package is installed and is at the correct version
(if specified).
.. code-block:: yaml
ShellCheck-0.3.5:
cabal:
- installed:
name
The package to install
user
The user to run cabal install with
install_global
Install pack... |
def get_active_window(self):
"""
Get the currently-active window.
Requires your window manager to support this.
Uses ``_NET_ACTIVE_WINDOW`` from the EWMH spec.
"""
window_ret = window_t(0)
_libxdo.xdo_get_active_window(self._xdo, ctypes.byref(window_ret))
... | Get the currently-active window.
Requires your window manager to support this.
Uses ``_NET_ACTIVE_WINDOW`` from the EWMH spec. |
def has_value(cls, value: int) -> bool:
"""True if specified value exists in int enum; otherwise, False."""
return any(value == item.value for item in cls) | True if specified value exists in int enum; otherwise, False. |
def get(self):
"""
*get the namesearch object*
**Return:**
- ``results``
"""
self.log.info('starting the ``get`` method')
# SPLIT THE LIST OF NAMES INTO BATCHES
self.theseBatches, self.theseBatchParams = self._split_incoming_queries_into_batches(
... | *get the namesearch object*
**Return:**
- ``results`` |
def get_list(cache_length=24, map_vendor_oids=True, cert_callback=None):
"""
Retrieves (and caches in memory) the list of CA certs from the OS. Includes
trust information from the OS - purposes the certificate should be trusted
or rejected for.
Trust information is encoded via object identifiers (O... | Retrieves (and caches in memory) the list of CA certs from the OS. Includes
trust information from the OS - purposes the certificate should be trusted
or rejected for.
Trust information is encoded via object identifiers (OIDs) that are sourced
from various RFCs and vendors (Apple and Microsoft). This t... |
def refallele(args):
"""
%prog refallele vcffile > out.refAllele
Make refAllele file which can be used to convert PLINK file to VCF file.
"""
p = OptionParser(refallele.__doc__)
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
vcffile, = args
... | %prog refallele vcffile > out.refAllele
Make refAllele file which can be used to convert PLINK file to VCF file. |
def twopercent(station_code):
"""Two percent high design temperature for a location.
Degrees in Celcius
Args:
station_code (str): Weather Station Code
Returns:
float degrees Celcius
"""
# (DB=>MWB) 2%, MaxDB=
temp = None
try:
fin = open('%s/%s' % (env.WEATHER_D... | Two percent high design temperature for a location.
Degrees in Celcius
Args:
station_code (str): Weather Station Code
Returns:
float degrees Celcius |
def scan_ids(self, *key_ranges):
'''Retrieve content ids in a range of ids.
Returns a generator of ``content_id`` corresponding to the
content identifier ranges given. `key_ranges` can be a possibly
empty list of 2-tuples, where the first element of the tuple
is the beginning of... | Retrieve content ids in a range of ids.
Returns a generator of ``content_id`` corresponding to the
content identifier ranges given. `key_ranges` can be a possibly
empty list of 2-tuples, where the first element of the tuple
is the beginning of a range and the second element is the end
... |
def calc_surface_intensity(self, factor=10):
"""Calculate the surface intensity for each pixel in the interior
region of the ROI. Pixels are adaptively subsampled around the
kernel centroid out to a radius of 'factor * max_pixrad'.
Parameters:
-----------
factor : the ra... | Calculate the surface intensity for each pixel in the interior
region of the ROI. Pixels are adaptively subsampled around the
kernel centroid out to a radius of 'factor * max_pixrad'.
Parameters:
-----------
factor : the radius of the oversample region in units of max_pixrad
... |
def _get_file_version(self, infile):
"""Returns infile version string."""
# Determine file version
for line1 in infile:
if line1.strip() != "[Pyspread save file version]":
raise ValueError(_("File format unsupported."))
break
for line2 in infile:... | Returns infile version string. |
def _send_data(self, data):
"""Send data to the ADB server"""
total_sent = 0
while total_sent < len(data):
# Send only the bytes that haven't been
# sent yet
sent = self.socket.send(data[total_sent:].encode("ascii"))
if sent == 0:
... | Send data to the ADB server |
def to_feature_importances(regressor_type,
regressor_kwargs,
trained_regressor):
"""
Motivation: when the out-of-bag improvement heuristic is used, we cancel the effect of normalization by dividing
by the number of trees in the regression ensemble by mul... | Motivation: when the out-of-bag improvement heuristic is used, we cancel the effect of normalization by dividing
by the number of trees in the regression ensemble by multiplying again by the number of trees used.
This enables prioritizing links that were inferred in a regression where lots of
:param regre... |
def order_by(self, *order_bys):
""" Add a list of ingredients to order by to the query. These can
either be Dimension or Metric objects or strings representing
order_bys on the shelf.
The Order_by expression will be added to the query's order_by statement
:param order_bys: Orde... | Add a list of ingredients to order by to the query. These can
either be Dimension or Metric objects or strings representing
order_bys on the shelf.
The Order_by expression will be added to the query's order_by statement
:param order_bys: Order_bys to add to the recipe. Order_bys can
... |
def get_active_for(self, user, user_agent=_MARK, ip_address=_MARK):
"""Return last known session for given user.
:param user: user session
:type user: `abilian.core.models.subjects.User`
:param user_agent: *exact* user agent string to lookup, or `None` to have
user_agent extrac... | Return last known session for given user.
:param user: user session
:type user: `abilian.core.models.subjects.User`
:param user_agent: *exact* user agent string to lookup, or `None` to have
user_agent extracted from request object. If not provided at all, no
filtering on user_a... |
def date_to_datetime_tz(
cr, table_name, user_field_name, date_field_name, datetime_field_name):
""" Take the related user's timezone into account when converting
date field to datetime in a given table.
This function must be call in post migration script.
:param table_name : Name of the table ... | Take the related user's timezone into account when converting
date field to datetime in a given table.
This function must be call in post migration script.
:param table_name : Name of the table where the field is;
:param user_field_name : The name of the user field (res.users);
:param date_field_na... |
def _execute_handler(self, p_command, p_todo_id=None, p_output=None):
"""
Executes a command, given as a string.
"""
p_output = p_output or self._output
self._console_visible = False
self._last_cmd = (p_command, p_output == self._output)
try:
p_comma... | Executes a command, given as a string. |
def handle_hotmaps_results(permutation_result):
"""Takes in output from multiprocess_permutation function and converts to
a better formatted dataframe.
Parameters
----------
permutation_result : list
output from multiprocess_permutation
Returns
-------
permutation_df : pd.DataF... | Takes in output from multiprocess_permutation function and converts to
a better formatted dataframe.
Parameters
----------
permutation_result : list
output from multiprocess_permutation
Returns
-------
permutation_df : pd.DataFrame
formatted output suitable to save |
def selector_production(self, tokens):
"""Production for a full selector."""
validators = []
# the following productions should return predicate functions.
if self.peek(tokens, 'type'):
type_ = self.match(tokens, 'type')
validators.append(self.type_production(ty... | Production for a full selector. |
def merge_modified_section_data(self):
"""Update the PE image content with any individual section data that has been modified."""
for section in self.sections:
section_data_start = adjust_FileAlignment( section.PointerToRawData,
self.OPTIONAL_HEADER.FileAlignment )
... | Update the PE image content with any individual section data that has been modified. |
def add_feed(self, feedlike, **kwargs):
""" Add a feed to the Symbol
Parameters
----------
feedlike : Feed or bFeed-like
The feed template, or Feed object to be added.
kwargs
Munging instructions
"""
if 'fnum' in kwargs:
... | Add a feed to the Symbol
Parameters
----------
feedlike : Feed or bFeed-like
The feed template, or Feed object to be added.
kwargs
Munging instructions |
def _set_nport_menu(self, v, load=False):
"""
Setter method for nport_menu, mapped from YANG variable /rbridge_id/ag/nport_menu (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_nport_menu is considered as a private
method. Backends looking to populate this... | Setter method for nport_menu, mapped from YANG variable /rbridge_id/ag/nport_menu (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_nport_menu is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_np... |
def GetMessages(self, formatter_mediator, event):
"""Determines the formatted message strings for an event object.
Args:
formatter_mediator (FormatterMediator): mediates the interactions between
formatters and other components, such as storage and Windows EventLog
resources.
eve... | Determines the formatted message strings for an event object.
Args:
formatter_mediator (FormatterMediator): mediates the interactions between
formatters and other components, such as storage and Windows EventLog
resources.
event (EventObject): event.
Returns:
tuple(str, s... |
def auth_uri(self):
"""The authorzation URL that should be provided to the user"""
return self.oauth.auth_uri(redirect_uri=self.redirect_uri, scope=self.scope) | The authorzation URL that should be provided to the user |
def qth_pw(self, q):
"""
returns the qth most probable element in the dawg.
"""
return heapq.nlargest(q + 2, self._T.iteritems(),
key=operator.itemgetter(1))[-1] | returns the qth most probable element in the dawg. |
def then(self, *tasks):
""" Interfaces the GraphNode `then` method
"""
nodes = [x.node for x in tasks]
self.node.then(*nodes)
return self | Interfaces the GraphNode `then` method |
def stringify(obj, trimmable=False):
"""
Convert an object to a stringified version of this object where the
initial object's attribute values have been stringified when these
values are not native Python types.
This function differs from the standard Python ``str`` as the latter
returns a stri... | Convert an object to a stringified version of this object where the
initial object's attribute values have been stringified when these
values are not native Python types.
This function differs from the standard Python ``str`` as the latter
returns a string version of object, while this function returns... |
def makeThumbnail(inputFile, outputFile, thumbnailSize, outputFormat='jpeg'):
"""
Make a thumbnail of the image stored at C{inputPath}, preserving its
aspect ratio, and write the result to C{outputPath}.
@param inputFile: The image file (or path to the file) to thumbnail.
@type inputFile: C{file} o... | Make a thumbnail of the image stored at C{inputPath}, preserving its
aspect ratio, and write the result to C{outputPath}.
@param inputFile: The image file (or path to the file) to thumbnail.
@type inputFile: C{file} or C{str}
@param outputFile: The file (or path to the file) to write the thumbnail
... |
def _S(kappa, alpha, beta):
"""Compute the antiderivative of the Amos-type bound G on the modified
Bessel function ratio.
Note: Handles scalar kappa, alpha, and beta only.
See "S <-" in movMF.R and utility function implementation notes from
https://cran.r-project.org/web/packages/movMF/index.html... | Compute the antiderivative of the Amos-type bound G on the modified
Bessel function ratio.
Note: Handles scalar kappa, alpha, and beta only.
See "S <-" in movMF.R and utility function implementation notes from
https://cran.r-project.org/web/packages/movMF/index.html |
def isdisjoint(self, other):
"""Check whether two Hilbert spaces are disjoint (do not have any
common local factors). Note that `FullSpace` is *not* disjoint with any
other Hilbert space, while `TrivialSpace` *is* disjoint with any other
HilbertSpace (even itself)
"""
if ... | Check whether two Hilbert spaces are disjoint (do not have any
common local factors). Note that `FullSpace` is *not* disjoint with any
other Hilbert space, while `TrivialSpace` *is* disjoint with any other
HilbertSpace (even itself) |
def finish_target(self, name):
"""Finishes progress bar for a specified target."""
# We have to write a msg about finished target
with self._lock:
pbar = self._bar(name, 100, 100)
if sys.stdout.isatty():
self.clearln()
self._print(pbar)
... | Finishes progress bar for a specified target. |
def we_should_stop(self, start, start_):
"""
Checks 'start' to see if we should stop collecting upcoming events.
'start' should be a datetime.datetime, 'start_' should be the same
as 'start', but it should be a datetime.date to allow comparison
w/ end_repeat.
"""
... | Checks 'start' to see if we should stop collecting upcoming events.
'start' should be a datetime.datetime, 'start_' should be the same
as 'start', but it should be a datetime.date to allow comparison
w/ end_repeat. |
def consume_length_prefix(rlp, start):
"""Read a length prefix from an RLP string.
:param rlp: the rlp string to read from
:param start: the position at which to start reading
:returns: a tuple ``(type, length, end)``, where ``type`` is either ``str``
or ``list`` depending on the type of ... | Read a length prefix from an RLP string.
:param rlp: the rlp string to read from
:param start: the position at which to start reading
:returns: a tuple ``(type, length, end)``, where ``type`` is either ``str``
or ``list`` depending on the type of the following payload,
``length`... |
def merge(self, other):
"""
Merges the values
"""
print "MERGING", self, other
other = self.coerce(other)
if self.is_contradictory(other):
raise Contradiction("Cannot merge %s and %s" % (self, other))
elif self.value is None and not other.value is None... | Merges the values |
def accept(self):
"""Accept the option.
Returns
-------
an awaitable of :class:`IssueResult`
"""
return self._issue._nation._accept_issue(self._issue.id, self._id) | Accept the option.
Returns
-------
an awaitable of :class:`IssueResult` |
def update_configs(self, release):
""" Update the fedora-atomic.git repositories for a given release """
git_repo = release['git_repo']
git_cache = release['git_cache']
if not os.path.isdir(git_cache):
self.call(['git', 'clone', '--mirror', git_repo, git_cache])
else:... | Update the fedora-atomic.git repositories for a given release |
def loop(self, events=[]):
'''
Run the loop.
'''
try:
for e in events:
if e.type == METAEVENT:
e = self.MetaEvent(e)
for func in self.event_funcs.get(e.type, []):
func(self, self.gstate, e)
except... | Run the loop. |
def boolValue(self):
"""
returns : (boolean) Value
"""
if self.lastValue == 1 or self.lastValue == "active":
self._key = 1
self._boolKey = True
else:
self._key = 0
self._boolKey = False
return self._boolKey | returns : (boolean) Value |
def checksum(data):
"""
:return: int
"""
assert isinstance(data, bytes)
assert len(data) >= MINIMUM_MESSAGE_SIZE - 2
assert len(data) <= MAXIMUM_MESSAGE_SIZE - 2
__checksum = 0
for data_byte in data:
__checksum += data_byte
__checksum = -(__checksum % 256) + 256
try:
... | :return: int |
def unpack_values(format_string, stream, verifier=None):
"""Helper function to unpack struct data from a stream and update the signature verifier.
:param str format_string: Struct format string
:param stream: Source data stream
:type stream: io.BytesIO
:param verifier: Signature verifier object
... | Helper function to unpack struct data from a stream and update the signature verifier.
:param str format_string: Struct format string
:param stream: Source data stream
:type stream: io.BytesIO
:param verifier: Signature verifier object
:type verifier: aws_encryption_sdk.internal.crypto.Verifier
... |
def put_bits( self, value, count ):
"""Push bits into the target.
value
Integer containing bits to push, ordered from least-significant bit to
most-significant bit.
count
Number of bits to push to the target.
"""
for _ in range( count ):
... | Push bits into the target.
value
Integer containing bits to push, ordered from least-significant bit to
most-significant bit.
count
Number of bits to push to the target. |
def error_removed_option(message: str):
""" Takes a message and returns a callback that raises NoSuchOption
if the value is not None. The message is used as an argument to NoSuchOption. """
def f(_, param, value):
if value is not None:
raise click.NoSuchOption(
f'--{para... | Takes a message and returns a callback that raises NoSuchOption
if the value is not None. The message is used as an argument to NoSuchOption. |
def getPhoneInfo(numb):
'''
Walk the phone info tree to find the best-match info for the given number.
Example:
info = getPhoneInfo(17035551212)
country = info.get('cc')
'''
text = str(numb)
info = {}
node = phonetree
# make decisions down the tree (but only keep inf... | Walk the phone info tree to find the best-match info for the given number.
Example:
info = getPhoneInfo(17035551212)
country = info.get('cc') |
def pad_to_3d(a):
"""Return 1- or 2-dimensional cartesian vectors, converted into a
3-dimensional representation, with additional dimensional coordinates
assumed to be zero.
Parameters
----------
a: array, shape (n, d), d < 3
Returns
-------
ap: array, shape (n, 3)
"""
a_pa... | Return 1- or 2-dimensional cartesian vectors, converted into a
3-dimensional representation, with additional dimensional coordinates
assumed to be zero.
Parameters
----------
a: array, shape (n, d), d < 3
Returns
-------
ap: array, shape (n, 3) |
def parse_debug_object(response):
"Parse the results of Redis's DEBUG OBJECT command into a Python dict"
# The 'type' of the object is the first item in the response, but isn't
# prefixed with a name
response = nativestr(response)
response = 'type:' + response
response = dict([kv.split(':') for ... | Parse the results of Redis's DEBUG OBJECT command into a Python dict |
def is_downloadable(self):
"""Return if rpm is downloadable by the package command.
Check if dnf or yum plugin package exists.
"""
is_plugin_avaiable = False
if self.is_dnf:
is_plugin_avaiable = self.is_package_installed(
'dnf-plugins... | Return if rpm is downloadable by the package command.
Check if dnf or yum plugin package exists. |
def _send_signed_request(url, payload):
"""
Helper function to make signed requests to Boulder
"""
payload64 = _b64(json.dumps(payload).encode('utf8'))
out = parse_account_key()
header = get_boulder_header(out)
protected = copy.deepcopy(header)
protected["nonce"] = urlopen(DEFAULT_CA +... | Helper function to make signed requests to Boulder |
def autodiscover():
"""
Auto-discover INSTALLED_APPS backbone_api.py modules.
"""
# This code is based off django.contrib.admin.__init__
from django.conf import settings
try:
# Django versions >= 1.9
from django.utils.module_loading import import_module
except ImportError:
... | Auto-discover INSTALLED_APPS backbone_api.py modules. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.