code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def create_logstore(self, project_name, logstore_name,
ttl=30,
shard_count=2,
enable_tracking=False,
append_meta=False,
auto_split=True,
max_split_shard=64,
... | create log store
Unsuccessful opertaion will cause an LogException.
:type project_name: string
:param project_name: the Project name
:type logstore_name: string
:param logstore_name: the logstore name
:type ttl: int
:param ttl: the life cycle of log... |
def normalize_underscore_case(name):
"""Normalize an underscore-separated descriptor to something more readable.
i.e. 'NAGIOS_SERVER' becomes 'Nagios Server', and 'host_components' becomes
'Host Components'
"""
normalized = name.lower()
normalized = re.sub(r'_(\w)',
lamb... | Normalize an underscore-separated descriptor to something more readable.
i.e. 'NAGIOS_SERVER' becomes 'Nagios Server', and 'host_components' becomes
'Host Components' |
def socks_username(self, value):
"""
Sets socks proxy username setting.
:Args:
- value: The socks proxy username value.
"""
self._verify_proxy_type_compatibility(ProxyType.MANUAL)
self.proxyType = ProxyType.MANUAL
self.socksUsername = value | Sets socks proxy username setting.
:Args:
- value: The socks proxy username value. |
def _add_thousand_g(self, variant_obj, info_dict):
"""Add the thousand genomes frequency
Args:
variant_obj (puzzle.models.Variant)
info_dict (dict): A info dictionary
"""
thousand_g = info_dict.get('1000GAF')
if thousand_g:
lo... | Add the thousand genomes frequency
Args:
variant_obj (puzzle.models.Variant)
info_dict (dict): A info dictionary |
def to_snake(camel):
"""TimeSkill -> time_skill"""
if not camel:
return camel
return ''.join('_' + x if 'A' <= x <= 'Z' else x for x in camel).lower()[camel[0].isupper():] | TimeSkill -> time_skill |
def create_type_variant(cls, type_name, type_converter):
"""
Create type variants for types with a cardinality field.
The new type converters are based on the type converter with
cardinality=1.
.. code-block:: python
import parse
@parse.with_pattern(r'\... | Create type variants for types with a cardinality field.
The new type converters are based on the type converter with
cardinality=1.
.. code-block:: python
import parse
@parse.with_pattern(r'\d+')
def parse_number(text):
return int(text)
... |
def array_to_csv(array_like): # type: (np.array or Iterable or int or float) -> str
"""Convert an array like object to CSV.
To understand better what an array like object is see:
https://docs.scipy.org/doc/numpy/user/basics.creation.html#converting-python-array-like-objects-to-numpy-arrays
Args:
... | Convert an array like object to CSV.
To understand better what an array like object is see:
https://docs.scipy.org/doc/numpy/user/basics.creation.html#converting-python-array-like-objects-to-numpy-arrays
Args:
array_like (np.array or Iterable or int or float): array like object to be converted to ... |
def get_view(self, columns: Sequence[str], query: str=None) -> PopulationView:
"""Return a configured PopulationView
Notes
-----
Client code should only need this (and only through the version exposed as
``population_view`` on the builder during setup) if it uses dynamically
... | Return a configured PopulationView
Notes
-----
Client code should only need this (and only through the version exposed as
``population_view`` on the builder during setup) if it uses dynamically
generated column names that aren't known at definition time. Otherwise
compon... |
def yzy_to_zyz(xi, theta1, theta2, eps=1e-9): # pylint: disable=invalid-name
"""Express a Y.Z.Y single qubit gate as a Z.Y.Z gate.
Solve the equation
.. math::
Ry(theta1).Rz(xi).Ry(theta2) = Rz(phi).Ry(theta).Rz(lambda)
for theta, phi, and lambda.
Return a solution ... | Express a Y.Z.Y single qubit gate as a Z.Y.Z gate.
Solve the equation
.. math::
Ry(theta1).Rz(xi).Ry(theta2) = Rz(phi).Ry(theta).Rz(lambda)
for theta, phi, and lambda.
Return a solution theta, phi, and lambda. |
def host(environ): # pragma: no cover
"""
Reconstruct host from environment. A modified version
of http://www.python.org/dev/peps/pep-0333/#url-reconstruction
"""
url = environ['wsgi.url_scheme'] + '://'
if environ.get('HTTP_HOST'):
url += environ['HTTP_HOST']
else:
url +=... | Reconstruct host from environment. A modified version
of http://www.python.org/dev/peps/pep-0333/#url-reconstruction |
def zip_built(outdir):
"""Packages the build folder into a zip"""
print("Zipping the built files!")
config_file_dir = os.path.join(cwd, "config.py")
if not os.path.exists(config_file_dir):
sys.exit(
"There dosen't seem to be a configuration file. Have you run the init command?")
... | Packages the build folder into a zip |
def count_empty(self, field):
"""
List of empty row indices
"""
try:
df2 = self.df[[field]]
vals = where(df2.applymap(lambda x: x == ''))
num = len(vals[0])
except Exception as e:
self.err(e, "Can not count empty values")
... | List of empty row indices |
def tryMatchedAnchor(self, block, autoIndent):
"""
find out whether we pressed return in something like {} or () or [] and indent properly:
{}
becomes:
{
|
}
"""
oposite = { ')': '(',
'}': '{',
']': '[... | find out whether we pressed return in something like {} or () or [] and indent properly:
{}
becomes:
{
|
} |
def _transform_variable_to_expression(expression, node, context):
"""Transform a Variable compiler expression into its SQLAlchemy expression representation.
Args:
expression: expression, Variable compiler expression.
node: SqlNode, the SqlNode the expression applies to.
context: Compila... | Transform a Variable compiler expression into its SQLAlchemy expression representation.
Args:
expression: expression, Variable compiler expression.
node: SqlNode, the SqlNode the expression applies to.
context: CompilationContext, global compilation state and metadata.
Returns:
... |
def _get_template_texts(source_list=None,
template='jinja',
defaults=None,
context=None,
**kwargs):
'''
Iterate a list of sources and process them as templates.
Returns a list of 'chunks' containing the rendered ... | Iterate a list of sources and process them as templates.
Returns a list of 'chunks' containing the rendered templates. |
def bottom(self):
"""
The row index that marks the bottom extent of the vertical span of
this cell. This is one greater than the index of the bottom-most row
of the span, similar to how a slice of the cell's rows would be
specified.
"""
if self.vMerge is not None:... | The row index that marks the bottom extent of the vertical span of
this cell. This is one greater than the index of the bottom-most row
of the span, similar to how a slice of the cell's rows would be
specified. |
def frequency(data, output='spectraldensity', scaling='power', sides='one',
taper=None, halfbandwidth=3, NW=None, duration=None,
overlap=0.5, step=None, detrend='linear', n_fft=None,
log_trans=False, centend='mean'):
"""Compute the
power spectral density (PSD, output='s... | Compute the
power spectral density (PSD, output='spectraldensity', scaling='power'), or
energy spectral density (ESD, output='spectraldensity', scaling='energy') or
the complex fourier transform (output='complex', sides='two')
Parameters
----------
data : instance of ChanTime
one of the... |
def choose(self):
"""Marks the item as the one the user is in."""
if not self.choosed:
self.choosed = True
self.pos = self.pos + Sep(5, 0) | Marks the item as the one the user is in. |
def pkcs7_unpad(buf):
# type: (bytes) -> bytes
"""Removes PKCS7 padding a decrypted object
:param bytes buf: buffer to remove padding
:rtype: bytes
:return: buffer without PKCS7_PADDING
"""
unpadder = cryptography.hazmat.primitives.padding.PKCS7(
cryptography.hazmat.primitives.cipher... | Removes PKCS7 padding a decrypted object
:param bytes buf: buffer to remove padding
:rtype: bytes
:return: buffer without PKCS7_PADDING |
def _validate_gain_A_value(self, gain_A):
"""
validate a given value for gain_A
:type gain_A: int
:raises: ValueError
"""
if gain_A not in self._valid_gains_for_channel_A:
raise ParameterValidationError("{gain_A} is not a valid gain".format(gain_A=gain_A)) | validate a given value for gain_A
:type gain_A: int
:raises: ValueError |
def server_prepare_root_bin_dir():
'''Install custom commands for user root at '/root/bin/'.'''
commands = ['run_backup']
for command in commands:
install_file_legacy(flo('/root/bin/{command}'), sudo=True)
sudo(flo('chmod 755 /root/bin/{command}'))
if command == 'run_backup':
... | Install custom commands for user root at '/root/bin/'. |
def opt(self, x_init, f_fp=None, f=None, fp=None):
"""
Run the TNC optimizer
"""
tnc_rcstrings = ['Local minimum', 'Converged', 'XConverged', 'Maximum number of f evaluations reached',
'Line search failed', 'Function is constant']
assert f_fp != None, "TNC requires... | Run the TNC optimizer |
def indent(text, num=4):
"""Indet the given string"""
str_indent = ' ' * num
return str_indent + ('\n' + str_indent).join(text.splitlines()) | Indet the given string |
def bezier_point(p, t):
"""Evaluates the Bezier curve given by it's control points, p, at t.
Note: Uses Horner's rule for cubic and lower order Bezier curves.
Warning: Be concerned about numerical stability when using this function
with high order curves."""
# begin arc support block #############... | Evaluates the Bezier curve given by it's control points, p, at t.
Note: Uses Horner's rule for cubic and lower order Bezier curves.
Warning: Be concerned about numerical stability when using this function
with high order curves. |
def set_socket_address(self):
"""
Set a random port to be used by zmq
"""
Global.LOGGER.debug('defining socket addresses for zmq')
random.seed()
default_port = random.randrange(5001, 5999)
internal_0mq_address = "tcp://127.0.0.1"
internal_0mq_port... | Set a random port to be used by zmq |
def filter_since_tag(self, all_tags):
"""
Filter tags according since_tag option.
:param list(dict) all_tags: All tags.
:rtype: list(dict)
:return: Filtered tags.
"""
tag = self.detect_since_tag()
if not tag or tag == REPO_CREATED_TAG_NAME:
r... | Filter tags according since_tag option.
:param list(dict) all_tags: All tags.
:rtype: list(dict)
:return: Filtered tags. |
def parse_function(fn):
"""Get the source of a function and return its AST."""
try:
return parse_string(inspect.getsource(fn))
except (IOError, OSError) as e:
raise ValueError(
'Cannot differentiate function: %s. Tangent must be able to access the '
'source code of the function. Functions ... | Get the source of a function and return its AST. |
def extractall(self, directory, auto_create_dir=False, patool_path=None):
'''
:param directory: directory to extract to
:param auto_create_dir: auto create directory
:param patool_path: the path to the patool backend
'''
log.debug('extracting %s into %s (backend=%s)', sel... | :param directory: directory to extract to
:param auto_create_dir: auto create directory
:param patool_path: the path to the patool backend |
def get_object(self, obj_class, data=None, subset=None):
"""Return a subclassed JSSObject instance by querying for
existing objects or posting a new object.
Args:
obj_class: The JSSObject subclass type to search for or
create.
data: The data parameter per... | Return a subclassed JSSObject instance by querying for
existing objects or posting a new object.
Args:
obj_class: The JSSObject subclass type to search for or
create.
data: The data parameter performs different operations
depending on the type pas... |
def getHeight(self):
'''
Gets the height.
'''
if self.useUiAutomator:
return self.map['bounds'][1][1] - self.map['bounds'][0][1]
else:
try:
return int(self.map[self.heightProperty])
except:
return 0 | Gets the height. |
def _head(self, client_kwargs):
"""
Returns object HTTP header.
Args:
client_kwargs (dict): Client arguments.
Returns:
dict: HTTP header.
"""
return _handle_http_errors(
self.client.request(
'HEAD', timeout=self._TIMEO... | Returns object HTTP header.
Args:
client_kwargs (dict): Client arguments.
Returns:
dict: HTTP header. |
def reduced_chi2(self, model, error_map=0):
"""
returns reduced chi2
:param model:
:param error_map:
:return:
"""
chi2 = self.reduced_residuals(model, error_map)
return np.sum(chi2**2) / self.num_data_evaluate() | returns reduced chi2
:param model:
:param error_map:
:return: |
def set_value(self, index, value):
"""Set value"""
self._data[ self.keys[index.row()] ] = value
self.showndata[ self.keys[index.row()] ] = value
self.sizes[index.row()] = get_size(value)
self.types[index.row()] = get_human_readable_type(value)
self.sig_setting_data.... | Set value |
def destroy_dns(app='', env='dev', **_):
"""Destroy DNS records.
Args:
app (str): Spinnaker Application name.
env (str): Deployment environment.
regions (str): AWS region.
Returns:
bool: True upon successful completion.
"""
client = boto3.Session(profile_name=env).c... | Destroy DNS records.
Args:
app (str): Spinnaker Application name.
env (str): Deployment environment.
regions (str): AWS region.
Returns:
bool: True upon successful completion. |
def enable(self, ospf_profile=None, router_id=None):
"""
Enable OSPF on this engine. For master engines, enable
OSPF on the virtual firewall.
Once enabled on the engine, add an OSPF area to an interface::
engine.dynamic_routing.ospf.enable()
interface = engine.r... | Enable OSPF on this engine. For master engines, enable
OSPF on the virtual firewall.
Once enabled on the engine, add an OSPF area to an interface::
engine.dynamic_routing.ospf.enable()
interface = engine.routing.get(0)
interface.add_ospf_area(OSPFArea('myarea'))
... |
def compute_deflections_at_next_plane(plane_index, total_planes):
"""This function determines whether the tracer should compute the deflections at the next plane.
This is True if there is another plane after this plane, else it is False..
Parameters
-----------
plane_index : int
The index ... | This function determines whether the tracer should compute the deflections at the next plane.
This is True if there is another plane after this plane, else it is False..
Parameters
-----------
plane_index : int
The index of the plane we are deciding if we should compute its deflections.
to... |
def append(self, row):
"""Append a result row and check its length.
>>> x = Results(['title', 'type'])
>>> x.append(('Konosuba', 'TV'))
>>> x
Results(['title', 'type'], [('Konosuba', 'TV')])
>>> x.append(('Konosuba',))
Traceback (most recent call last):
... | Append a result row and check its length.
>>> x = Results(['title', 'type'])
>>> x.append(('Konosuba', 'TV'))
>>> x
Results(['title', 'type'], [('Konosuba', 'TV')])
>>> x.append(('Konosuba',))
Traceback (most recent call last):
...
ValueError: Wrong ... |
def takeChild(self, index):
"""
Removes the child at the given index from this item.
:param index | <int>
"""
item = super(XGanttWidgetItem, self).takeChild(index)
if item:
item.removeFromScene()
return it... | Removes the child at the given index from this item.
:param index | <int> |
def _new_pivot_query(self):
"""
Create a new query builder for the pivot table.
:rtype: eloquent.orm.Builder
"""
query = super(MorphToMany, self)._new_pivot_query()
return query.where(self._morph_type, self._morph_class) | Create a new query builder for the pivot table.
:rtype: eloquent.orm.Builder |
def style_defs(cls):
"""
Return the CSS style definitions required
by the formatted snippet.
"""
formatter = HtmlFormatter()
formatter.style.highlight_color = cls.VIOLATION_COLOR
return formatter.get_style_defs() | Return the CSS style definitions required
by the formatted snippet. |
def pub_view(request, docid, configuration):
"""The initial view, does not provide the document content yet"""
if 'autodeclare' in settings.CONFIGURATIONS[configuration]:
for annotationtype, set in settings.CONFIGURATIONS['configuration']['autodeclare']:
try:
r = flat.comm.qu... | The initial view, does not provide the document content yet |
def set_debug(self, debuglevel):
"""
Change the debug level of the API
**Returns:** No item returned.
"""
if isinstance(debuglevel, int):
self._debuglevel = debuglevel
if self._debuglevel == 1:
logging.basicConfig(level=logging.INFO,
... | Change the debug level of the API
**Returns:** No item returned. |
def _lsm_load_pages(self):
"""Load and fix all pages from LSM file."""
# cache all pages to preserve corrected values
pages = self.pages
pages.cache = True
pages.useframes = True
# use first and second page as keyframes
pages.keyframe = 1
pages.keyframe = ... | Load and fix all pages from LSM file. |
def get_end_date(self, obj):
"""
Returns the end date for a model instance
"""
obj_date = getattr(obj, self.get_end_date_field())
try:
obj_date = obj_date.date()
except AttributeError:
# It's a date rather than datetime, so we use it as is
... | Returns the end date for a model instance |
def generate_api_doc(self, uri):
'''Make autodoc documentation template string for a module
Parameters
----------
uri : string
python location of module - e.g 'sphinx.builder'
Returns
-------
head : string
Module name, table of contents.
... | Make autodoc documentation template string for a module
Parameters
----------
uri : string
python location of module - e.g 'sphinx.builder'
Returns
-------
head : string
Module name, table of contents.
body : string
Function a... |
def _double_fork(self):
"""Do the UNIX double-fork magic.
See Stevens' "Advanced Programming in the UNIX Environment" for details
(ISBN 0201563177)
http://www.erlenstar.demon.co.uk/unix/faq_2.html#SEC16
"""
try:
pid = os.fork()
if pid > 0:
... | Do the UNIX double-fork magic.
See Stevens' "Advanced Programming in the UNIX Environment" for details
(ISBN 0201563177)
http://www.erlenstar.demon.co.uk/unix/faq_2.html#SEC16 |
def ip_shell_after_exception(frame):
"""
Launches an IPython embedded shell in the namespace where an exception occurred.
:param frame:
:return:
"""
# let the user know, where this shell is 'waking up'
# construct frame list
# this will be printed in the header
frame_info_list = []... | Launches an IPython embedded shell in the namespace where an exception occurred.
:param frame:
:return: |
def business_hours_schedule_delete(self, id, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/schedules#delete-a-schedule"
api_path = "/api/v2/business_hours/schedules/{id}.json"
api_path = api_path.format(id=id)
return self.call(api_path, method="DELETE", **kwargs) | https://developer.zendesk.com/rest_api/docs/core/schedules#delete-a-schedule |
def _convertEntities(self, match):
"""Used in a call to re.sub to replace HTML, XML, and numeric
entities with the appropriate Unicode characters. If HTML
entities are being converted, any unrecognized entities are
escaped."""
x = match.group(1)
if self.convertHTMLEntitie... | Used in a call to re.sub to replace HTML, XML, and numeric
entities with the appropriate Unicode characters. If HTML
entities are being converted, any unrecognized entities are
escaped. |
def train(X_train, y_train, **kwargs):
'''
>>> corpus = CorpusReader('annot.opcorpora.xml')
>>> X_train, x_test, y_train, y_test = get_train_data(corpus, test_size=0.33, random_state=42)
>>> crf = train(X_train, y_train)
'''
crf = Trainer()
crf.set_params({
'c1': 1.0,
'c2': 0... | >>> corpus = CorpusReader('annot.opcorpora.xml')
>>> X_train, x_test, y_train, y_test = get_train_data(corpus, test_size=0.33, random_state=42)
>>> crf = train(X_train, y_train) |
def getDatastreamProfile(self, dsid, date=None):
"""Get information about a particular datastream belonging to this object.
:param dsid: datastream id
:rtype: :class:`DatastreamProfile`
"""
# NOTE: used by DatastreamObject
if self._create:
return None
... | Get information about a particular datastream belonging to this object.
:param dsid: datastream id
:rtype: :class:`DatastreamProfile` |
def _explore(self, node, visited, skip_father=None):
"""
Explore the CFG and look for re-entrancy
Heuristic: There is a re-entrancy if a state variable is written
after an external call
node.context will contains the external calls executed
... | Explore the CFG and look for re-entrancy
Heuristic: There is a re-entrancy if a state variable is written
after an external call
node.context will contains the external calls executed
It contains the calls executed in father nodes
if node.context... |
def remove_item(self, **kwargs):
"""
Delete movies from a list that the user created.
A valid session id is required.
Args:
media_id: A movie id.
Returns:
A dict respresentation of the JSON returned from the API.
"""
path = self._get_id_... | Delete movies from a list that the user created.
A valid session id is required.
Args:
media_id: A movie id.
Returns:
A dict respresentation of the JSON returned from the API. |
def _proxy(self):
"""
Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: RecordingSettingsContext for this RecordingSettingsInstance
:rtype: twilio.rest.video.v1.recordin... | Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: RecordingSettingsContext for this RecordingSettingsInstance
:rtype: twilio.rest.video.v1.recording_settings.RecordingSettingsContext |
def _check_is_chained_assignment_possible(self):
"""
Check if we are a view, have a cacher, and are of mixed type.
If so, then force a setitem_copy check.
Should be called just near setting a value
Will return a boolean if it we are a view and are cached, but a
single-d... | Check if we are a view, have a cacher, and are of mixed type.
If so, then force a setitem_copy check.
Should be called just near setting a value
Will return a boolean if it we are a view and are cached, but a
single-dtype meaning that the cacher should be updated following
sett... |
def add_pos_indicator(self):
"""Adds a new position indicator."""
body = new_body(name="pos_indicator")
body.append(
new_geom(
"sphere",
[0.03],
rgba=[1, 0, 0, 0.5],
group=1,
contype="0",
... | Adds a new position indicator. |
def set(self, **kargs):
""" Reset default keyword parameters.
Assigns new default values from dictionary ``kargs`` to the fitter's
keyword parameters. Keywords for the underlying :mod:`lsqfit` fitters
can also be included (or grouped together in dictionary
``fitterargs``).
... | Reset default keyword parameters.
Assigns new default values from dictionary ``kargs`` to the fitter's
keyword parameters. Keywords for the underlying :mod:`lsqfit` fitters
can also be included (or grouped together in dictionary
``fitterargs``).
Returns tuple ``(kargs, oldkarg... |
def _make_parser_func(sep):
"""Creates a parser function from the given sep.
Args:
sep: The separator default to use for the parser.
Returns:
A function object.
"""
def parser_func(
filepath_or_buffer,
sep=sep,
delimiter=None,
header="infer",
... | Creates a parser function from the given sep.
Args:
sep: The separator default to use for the parser.
Returns:
A function object. |
def beautify(string, *args, **kwargs):
"""
Convenient interface to the ecstasy package.
Arguments:
string (str): The string to beautify with ecstasy.
args (list): The positional arguments.
kwargs (dict): The keyword ('always') arguments.
"""
parser = Parser(args, kwargs)
return parser.beautify(string... | Convenient interface to the ecstasy package.
Arguments:
string (str): The string to beautify with ecstasy.
args (list): The positional arguments.
kwargs (dict): The keyword ('always') arguments. |
def get_environ(self, key, default=None, cast=None):
"""Get value from environment variable using os.environ.get
:param key: The name of the setting value, will always be upper case
:param default: In case of not found it will be returned
:param cast: Should cast in to @int, @float, @bo... | Get value from environment variable using os.environ.get
:param key: The name of the setting value, will always be upper case
:param default: In case of not found it will be returned
:param cast: Should cast in to @int, @float, @bool or @json ?
or cast must be true to use cast inferenc... |
def randomLocation(cls, radius, width, height, origin=None):
'''
:param: radius - float
:param: width - float
:param: height - float
:param: origin - optional Point subclass
:return: Rectangle
'''
return cls(width,
height,
... | :param: radius - float
:param: width - float
:param: height - float
:param: origin - optional Point subclass
:return: Rectangle |
def _set_medians_and_extremes(self):
"""
Sets median values for rtt and the offset of result packets.
"""
rtts = sorted([p.rtt for p in self.packets if p.rtt is not None])
if rtts:
self.rtt_min = rtts[0]
self.rtt_max = rtts[-1]
self.rtt_median... | Sets median values for rtt and the offset of result packets. |
def backtick (cmd, encoding='utf-8'):
"""Return decoded output from command."""
data = subprocess.Popen(cmd, stdout=subprocess.PIPE).communicate()[0]
return data.decode(encoding) | Return decoded output from command. |
def batch_qs(qs, batch_size=1000):
"""
Returns a (start, end, total, queryset) tuple for each batch in the given
queryset.
Usage:
# Make sure to order your queryset
article_qs = Article.objects.order_by('id')
for start, end, total, qs in batch_qs(article_qs):
print "... | Returns a (start, end, total, queryset) tuple for each batch in the given
queryset.
Usage:
# Make sure to order your queryset
article_qs = Article.objects.order_by('id')
for start, end, total, qs in batch_qs(article_qs):
print "Now processing %s - %s of %s" % (start + 1, end... |
def receiveds_parsing(receiveds):
"""
This function parses the receiveds headers.
Args:
receiveds (list): list of raw receiveds headers
Returns:
a list of parsed receiveds headers with first hop in first position
"""
parsed = []
receiveds = [re.sub(JUNK_PATTERN, " ", i).st... | This function parses the receiveds headers.
Args:
receiveds (list): list of raw receiveds headers
Returns:
a list of parsed receiveds headers with first hop in first position |
def fetch(context, data):
"""Do an HTTP GET on the ``url`` specified in the inbound data."""
url = data.get('url')
attempt = data.pop('retry_attempt', 1)
try:
result = context.http.get(url, lazy=True)
rules = context.get('rules', {'match_all': {}})
if not Rule.get_rule(rules).app... | Do an HTTP GET on the ``url`` specified in the inbound data. |
def decode_jwt_token(token, secret):
"""
Validates and decodes the JWT token
Token checked for
- signature of JWT token
- token issued date is valid
:param token: jwt token
:param secret: client specific secret
:return boolean: True if valid token, False otherwise
:raises To... | Validates and decodes the JWT token
Token checked for
- signature of JWT token
- token issued date is valid
:param token: jwt token
:param secret: client specific secret
:return boolean: True if valid token, False otherwise
:raises TokenIssuerError: if iss field not present
:rai... |
def _get_version_from_git_tag(path):
"""Return a PEP440-compliant version derived from the git status.
If that fails for any reason, return the changeset hash.
"""
m = GIT_DESCRIBE_REGEX.match(_git_describe_tags(path) or '')
if m is None:
return None
version, post_commit, hash = m.groups... | Return a PEP440-compliant version derived from the git status.
If that fails for any reason, return the changeset hash. |
def assign_params(sess, params, network):
"""Assign the given parameters to the TensorLayer network.
Parameters
----------
sess : Session
TensorFlow Session.
params : list of array
A list of parameters (array) in order.
network : :class:`Layer`
The network to be assigned... | Assign the given parameters to the TensorLayer network.
Parameters
----------
sess : Session
TensorFlow Session.
params : list of array
A list of parameters (array) in order.
network : :class:`Layer`
The network to be assigned.
Returns
--------
list of operation... |
def send_messages(self, email_messages):
"""
Queue one or more EmailMessage objects and returns the number of
email messages sent.
"""
from .mail import create
from .utils import create_attachments
if not email_messages:
return
for email_mess... | Queue one or more EmailMessage objects and returns the number of
email messages sent. |
def check_for_launchpad(old_vendor, name, urls):
"""Check if the project is hosted on launchpad.
:param name: str, name of the project
:param urls: set, urls to check.
:return: the name of the project on launchpad, or an empty string.
"""
if old_vendor != "pypi":
# XXX This might work f... | Check if the project is hosted on launchpad.
:param name: str, name of the project
:param urls: set, urls to check.
:return: the name of the project on launchpad, or an empty string. |
def _get_asconv_headers(mosaic):
"""
Getter for the asconv headers (asci header info stored in the dicom)
"""
asconv_headers = re.findall(r'### ASCCONV BEGIN(.*)### ASCCONV END ###',
mosaic[Tag(0x0029, 0x1020)].value.decode(encoding='ISO-8859-1'),
... | Getter for the asconv headers (asci header info stored in the dicom) |
def _activate_organization(organization):
"""
Activates an inactivated (soft-deleted) organization as well as any inactive relationships
"""
[_activate_organization_course_relationship(record) for record
in internal.OrganizationCourse.objects.filter(organization_id=organization.id, active=False)]
... | Activates an inactivated (soft-deleted) organization as well as any inactive relationships |
def from_compact(cls: Type[TransactionType], currency: str, compact: str) -> TransactionType:
"""
Return Transaction instance from compact string format
:param currency: Name of the currency
:param compact: Compact format string
:return:
"""
lines = compact.split... | Return Transaction instance from compact string format
:param currency: Name of the currency
:param compact: Compact format string
:return: |
def _all_indexes_same(indexes):
"""
Determine if all indexes contain the same elements.
Parameters
----------
indexes : list of Index objects
Returns
-------
bool
True if all indexes contain the same elements, False otherwise.
"""
first = indexes[0]
for index in ind... | Determine if all indexes contain the same elements.
Parameters
----------
indexes : list of Index objects
Returns
-------
bool
True if all indexes contain the same elements, False otherwise. |
def listen_tta(self, target, timeout):
"""Listen as Type A Target in 106 kbps.
Restrictions:
* It is not possible to send short frames that are required
for ACK and NAK responses. This means that a Type 2 Tag
emulation can only implement a single sector memory model.
... | Listen as Type A Target in 106 kbps.
Restrictions:
* It is not possible to send short frames that are required
for ACK and NAK responses. This means that a Type 2 Tag
emulation can only implement a single sector memory model.
* It can not be avoided that the chipset respon... |
def list_absent(name, acl_type, acl_names=None, recurse=False):
'''
Ensure a Linux ACL list does not exist
Takes a list of acl names and remove them from the given path
name
The acl path
acl_type
The type of the acl is used for, it can be 'user' or 'group'
acl_names
T... | Ensure a Linux ACL list does not exist
Takes a list of acl names and remove them from the given path
name
The acl path
acl_type
The type of the acl is used for, it can be 'user' or 'group'
acl_names
The list of users or groups
perms
Remove the permissions eg.: rw... |
def set_version(request, response):
"""Set version and revision to response
"""
settings = request.registry.settings
resolver = DottedNameResolver()
# get version config
version_header = settings.get(
'api.version_header',
'X-Version',
)
version_header_value = settings.... | Set version and revision to response |
def p_expr_function(p):
'expr : FUNCTION is_reference LPAREN parameter_list RPAREN lexical_vars LBRACE inner_statement_list RBRACE'
p[0] = ast.Closure(p[4], p[6], p[8], p[2], lineno=p.lineno(1)) | expr : FUNCTION is_reference LPAREN parameter_list RPAREN lexical_vars LBRACE inner_statement_list RBRACE |
def _check_operators(self, operators):
""" Check Inputs
This method cheks that the input operators and weights are correctly
formatted
Parameters
----------
operators : list, tuple or np.ndarray
List of linear operator class instances
Returns
... | Check Inputs
This method cheks that the input operators and weights are correctly
formatted
Parameters
----------
operators : list, tuple or np.ndarray
List of linear operator class instances
Returns
-------
np.array operators
Raise... |
def land_cover_analysis_summary_report(feature, parent):
"""Retrieve an HTML land cover analysis table report from a multi exposure
analysis.
"""
_ = feature, parent # NOQA
analysis_dir = get_analysis_dir(exposure_land_cover['key'])
if analysis_dir:
return get_impact_report_as_string(an... | Retrieve an HTML land cover analysis table report from a multi exposure
analysis. |
def to_workspace_value(self, result, assets):
"""
Called with the result of a pipeline. This needs to return an object
which can be put into the workspace to continue doing computations.
This is the inverse of :func:`~zipline.pipeline.term.Term.postprocess`.
"""
if self.... | Called with the result of a pipeline. This needs to return an object
which can be put into the workspace to continue doing computations.
This is the inverse of :func:`~zipline.pipeline.term.Term.postprocess`. |
def name(self, node, children):
'name = ~"[a-z]+" _'
return self.env.get(node.text.strip(), -1) | name = ~"[a-z]+" _ |
def upsert(self, body, raise_exc=True, headers=False, files=None):
'''Performs an HTTP PUT to the server. This is an idempotent
call that will create the resource this navigator is pointing
to, or will update it if it already exists.
`body` may either be a string or a dictionary represe... | Performs an HTTP PUT to the server. This is an idempotent
call that will create the resource this navigator is pointing
to, or will update it if it already exists.
`body` may either be a string or a dictionary representing json
`headers` are additional headers to send in the request |
def save_current(self):
"""
Save current editor. If the editor.file.path is None, a save as dialog
will be shown.
"""
if self.current_widget() is not None:
editor = self.current_widget()
self._save(editor) | Save current editor. If the editor.file.path is None, a save as dialog
will be shown. |
def link_source_files(generator):
"""
Processes each article/page object and formulates copy from and copy
to destinations, as well as adding a source file URL as an attribute.
"""
# Get all attributes from the generator that are articles or pages
posts = [
getattr(generator, attr, None)... | Processes each article/page object and formulates copy from and copy
to destinations, as well as adding a source file URL as an attribute. |
def get_end_offset( self, value, parent=None, index=None ):
"""Return the end offset of the Field's data. Useful for chainloading.
value
Input Python object to process.
parent
Parent block object where this Field is defined. Used for e.g.
evaluating Refs.
... | Return the end offset of the Field's data. Useful for chainloading.
value
Input Python object to process.
parent
Parent block object where this Field is defined. Used for e.g.
evaluating Refs.
index
Index of the Python object to measure from. Us... |
def _split(self, iterator, tmp_dir):
"""
Splits the file into several chunks.
If the original file is too big to fit in the allocated space, the sorting will be split into several chunks,
then merged.
:param tmp_dir: Where to put the intermediate sorted results.
:param o... | Splits the file into several chunks.
If the original file is too big to fit in the allocated space, the sorting will be split into several chunks,
then merged.
:param tmp_dir: Where to put the intermediate sorted results.
:param orig_lines: The lines read before running out of space.
... |
def get(self, sid):
"""
Constructs a UserContext
:param sid: The unique string that identifies the resource
:returns: twilio.rest.chat.v2.service.user.UserContext
:rtype: twilio.rest.chat.v2.service.user.UserContext
"""
return UserContext(self._version, service_... | Constructs a UserContext
:param sid: The unique string that identifies the resource
:returns: twilio.rest.chat.v2.service.user.UserContext
:rtype: twilio.rest.chat.v2.service.user.UserContext |
def unwrap(self):
'''
Returns a nested python sequence.
'''
red = [self.red[i]/65535.0 for i in range(self.size)]
green = [self.green[i]/65535.0 for i in range(self.size)]
blue = [self.blue[i]/65535.0 for i in range(self.size)]
return red, green, blue | Returns a nested python sequence. |
def get_flash_crypt_config(self):
""" bit 3 in efuse_rd_disable[3:0] is mapped to flash_crypt_config
this bit is at position 19 in EFUSE_BLK0_RDATA0_REG """
word0 = self.read_efuse(0)
rd_disable = (word0 >> 19) & 0x1
if rd_disable == 0:
""" we can read the flash_cryp... | bit 3 in efuse_rd_disable[3:0] is mapped to flash_crypt_config
this bit is at position 19 in EFUSE_BLK0_RDATA0_REG |
def set_prewarp(self, prewarp):
"""
Updates the prewarp configuration used to skew images in OpenALPR before
processing.
:param prewarp: A unicode/ascii string (Python 2/3) or bytes array (Python 3)
:return: None
"""
prewarp = _convert_to_charp(prewarp)
s... | Updates the prewarp configuration used to skew images in OpenALPR before
processing.
:param prewarp: A unicode/ascii string (Python 2/3) or bytes array (Python 3)
:return: None |
def open(self, key):
"""Implementation of :meth:`~simplekv.KeyValueStore.open`.
If a cache miss occurs, the value is retrieved, stored in the cache,
then then another open is issued on the cache.
If the cache raises an :exc:`~exceptions.IOError`, the cache is
ignored, and the b... | Implementation of :meth:`~simplekv.KeyValueStore.open`.
If a cache miss occurs, the value is retrieved, stored in the cache,
then then another open is issued on the cache.
If the cache raises an :exc:`~exceptions.IOError`, the cache is
ignored, and the backing store is consulted direct... |
def _acceptance_prob(self, position, position_bar, momentum, momentum_bar):
"""
Returns the acceptance probability for given new position(position) and momentum
"""
# Parameters to help in evaluating Joint distribution P(position, momentum)
_, logp = self.grad_log_pdf(position, ... | Returns the acceptance probability for given new position(position) and momentum |
def select_specimen(self, specimen):
"""
Goes through the calculations necessary to plot measurement data for
specimen and sets specimen as current GUI specimen, also attempts to
handle changing current fit.
"""
try:
fit_index = self.pmag_results_data['specime... | Goes through the calculations necessary to plot measurement data for
specimen and sets specimen as current GUI specimen, also attempts to
handle changing current fit. |
def _get_inline_translations(self, request, language_code, obj=None):
"""
Fetch the inline translations
"""
inline_instances = self.get_inline_instances(request, obj=obj)
for inline in inline_instances:
if issubclass(inline.model, TranslatableModelMixin):
... | Fetch the inline translations |
def insert_text(self, s, from_undo=False):
"""Natural numbers only."""
return super().insert_text(
''.join(c for c in s if c in '0123456789'),
from_undo
) | Natural numbers only. |
def _inject_closure_values_fix_code(c, injected, **kwargs):
"""
Fix code objects, recursively fixing any closures
"""
# Add more closure variables
c.freevars += injected
# Replace LOAD_GLOBAL with LOAD_DEREF (fetch from closure cells)
# for named variables
for i, (opcode, value) in enum... | Fix code objects, recursively fixing any closures |
def _open_list(self, list_type):
"""
Add an open list tag corresponding to the specification in the
parser's LIST_TYPES.
"""
if list_type in LIST_TYPES.keys():
tag = LIST_TYPES[list_type]
else:
raise Exception('CustomSlackdownHTMLParser:_open_list:... | Add an open list tag corresponding to the specification in the
parser's LIST_TYPES. |
def _drag_col(self, event):
"""Continue dragging a column"""
x = self._dx + event.x # get dragged column new left x coordinate
self._visual_drag.place_configure(x=x) # update column preview position
# if one border of the dragged column is beyon the middle of the
# neighboring ... | Continue dragging a column |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.