_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q43600 | NamespaceLoader2.load_module | train | def load_module(self, name):
"""Load a namespace module as if coming from an empty file.
"""
_verbose_message('namespace module loaded with path {!r}', self.path)
# Adjusting code from LoaderBasics
if name in sys.modules:
mod = sys.modules[name]
self.exec... | python | {
"resource": ""
} |
q43601 | SourceLoader.get_source | train | def get_source(self, name):
"""Concrete implementation of InspectLoader.get_source."""
path = self.get_filename(name)
try:
source_bytes = self.get_data(path)
except OSError as exc:
e = _ImportError('source not available through get_data()',
... | python | {
"resource": ""
} |
q43602 | ImpFileLoader2.exec_module | train | def exec_module(self, module):
"""Execute the module using the old imp."""
path = [os.path.dirname(module.__file__)] # file should have been resolved before (module creation)
file = None
try:
file, pathname, description = imp.find_module(module.__name__.rpartition('.')[-1], ... | python | {
"resource": ""
} |
q43603 | ImpFileLoader2.load_module | train | def load_module(self, name):
"""Load a module from a file.
"""
# Implementation inspired from pytest.rewrite and importlib
# If there is an existing module object named 'name' in
# sys.modules, the loader must use that existing module. (Otherwise,
# the reload() builtin ... | python | {
"resource": ""
} |
q43604 | analyze_xml | train | def analyze_xml(xml):
"""Analyzes `file` against packtools' XMLValidator.
"""
f = StringIO(xml)
try:
xml = packtools.XMLValidator.parse(f, sps_version='sps-1.4')
except packtools.exceptions.PacktoolsError as e:
logger.exception(e)
summary = {}
summary['dtd_is_valid'... | python | {
"resource": ""
} |
q43605 | ServerBase.install | train | def install(self):
"""
install the server
"""
try:
if self.args.server is not None:
server = ServerLists(self.server_type)
DynamicImporter(
'ezhost',
server.name,
args=self.args,
... | python | {
"resource": ""
} |
q43606 | filehandles | train | def filehandles(path, openers_list=openers, pattern='', verbose=False):
"""Main function that iterates over list of openers and decides which opener to use.
:param str path: Path.
:param list openers_list: List of openers.
:param str pattern: Regular expression pattern.
:param verbose: Print additi... | python | {
"resource": ""
} |
q43607 | directory_opener | train | def directory_opener(path, pattern='', verbose=False):
"""Directory opener.
:param str path: Path.
:param str pattern: Regular expression pattern.
:return: Filehandle(s).
"""
if not os.path.isdir(path):
raise NotADirectoryError
else:
openers_list = [opener for opener in open... | python | {
"resource": ""
} |
q43608 | ziparchive_opener | train | def ziparchive_opener(path, pattern='', verbose=False):
"""Opener that opens files from zip archive..
:param str path: Path.
:param str pattern: Regular expression pattern.
:return: Filehandle(s).
"""
with zipfile.ZipFile(io.BytesIO(urlopen(path).read()), 'r') if is_url(path) else zipfile.ZipFi... | python | {
"resource": ""
} |
q43609 | tararchive_opener | train | def tararchive_opener(path, pattern='', verbose=False):
"""Opener that opens files from tar archive.
:param str path: Path.
:param str pattern: Regular expression pattern.
:return: Filehandle(s).
"""
with tarfile.open(fileobj=io.BytesIO(urlopen(path).read())) if is_url(path) else tarfile.open(p... | python | {
"resource": ""
} |
q43610 | gzip_opener | train | def gzip_opener(path, pattern='', verbose=False):
"""Opener that opens single gzip compressed file.
:param str path: Path.
:param str pattern: Regular expression pattern.
:return: Filehandle(s).
"""
source = path if is_url(path) else os.path.abspath(path)
filename = os.path.basename(path)... | python | {
"resource": ""
} |
q43611 | bz2_opener | train | def bz2_opener(path, pattern='', verbose=False):
"""Opener that opens single bz2 compressed file.
:param str path: Path.
:param str pattern: Regular expression pattern.
:return: Filehandle(s).
"""
source = path if is_url(path) else os.path.abspath(path)
filename = os.path.basename(path)
... | python | {
"resource": ""
} |
q43612 | text_opener | train | def text_opener(path, pattern='', verbose=False):
"""Opener that opens single text file.
:param str path: Path.
:param str pattern: Regular expression pattern.
:return: Filehandle(s).
"""
source = path if is_url(path) else os.path.abspath(path)
filename = os.path.basename(path)
if patt... | python | {
"resource": ""
} |
q43613 | random_string | train | def random_string(length, charset):
"""
Return a random string of the given length from the
given character set.
:param int length: The length of string to return
:param str charset: A string of characters to choose from
:returns: A random string
:rtype: str
"""
n = len(charset)
... | python | {
"resource": ""
} |
q43614 | random_alphanum | train | def random_alphanum(length):
"""
Return a random string of ASCII letters and digits.
:param int length: The length of string to return
:returns: A random string
:rtype: str
"""
charset = string.ascii_letters + string.digits
return random_string(length, charset) | python | {
"resource": ""
} |
q43615 | random_hex | train | def random_hex(length):
"""
Return a random hex string.
:param int length: The length of string to return
:returns: A random string
:rtype: str
"""
charset = ''.join(set(string.hexdigits.lower()))
return random_string(length, charset) | python | {
"resource": ""
} |
q43616 | format_obj_keys | train | def format_obj_keys(obj, formatter):
"""
Take a dictionary with string keys and recursively convert
all keys from one form to another using the formatting function.
The dictionary may contain lists as values, and any nested
dictionaries within those lists will also be converted.
:param object ... | python | {
"resource": ""
} |
q43617 | Graph.merge_nodes | train | def merge_nodes(self, keep_node, kill_node):
"""
Merge two nodes in the graph.
Takes two nodes and merges them together, merging their links by
combining the two link lists and summing the weights of links which
point to the same node.
All links in the graph pointing to... | python | {
"resource": ""
} |
q43618 | Graph.add_nodes | train | def add_nodes(self, nodes):
"""
Add a given node or list of nodes to self.node_list.
Args:
node (Node or list[Node]): the node or list of nodes to add
to the graph
Returns: None
Examples:
Adding one node: ::
>>> from blur.marko... | python | {
"resource": ""
} |
q43619 | Graph.feather_links | train | def feather_links(self, factor=0.01, include_self=False):
"""
Feather the links of connected nodes.
Go through every node in the network and make it inherit the links
of the other nodes it is connected to. Because the link weight sum
for any given node can be very different with... | python | {
"resource": ""
} |
q43620 | Graph.apply_noise | train | def apply_noise(self, noise_weights=None, uniform_amount=0.1):
"""
Add noise to every link in the network.
Can use either a ``uniform_amount`` or a ``noise_weight`` weight
profile. If ``noise_weight`` is set, ``uniform_amount`` will be
ignored.
Args:
noise_w... | python | {
"resource": ""
} |
q43621 | Graph.find_node_by_value | train | def find_node_by_value(self, value):
"""
Find and return a node in self.node_list with the value ``value``.
If multiple nodes exist with the value ``value``,
return the first one found.
If no such node exists, this returns ``None``.
Args:
value (Any): The v... | python | {
"resource": ""
} |
q43622 | Graph.remove_node | train | def remove_node(self, node):
"""
Remove a node from ``self.node_list`` and links pointing to it.
If ``node`` is not in the graph, do nothing.
Args:
node (Node): The node to be removed
Returns: None
Example:
>>> from blur.markov.node import Node... | python | {
"resource": ""
} |
q43623 | Graph.remove_node_by_value | train | def remove_node_by_value(self, value):
"""
Delete all nodes in ``self.node_list`` with the value ``value``.
Args:
value (Any): The value to find and delete owners of.
Returns: None
Example:
>>> from blur.markov.node import Node
>>> node_1 = ... | python | {
"resource": ""
} |
q43624 | Graph.has_node_with_value | train | def has_node_with_value(self, value):
"""
Whether any node in ``self.node_list`` has the value ``value``.
Args:
value (Any): The value to find in ``self.node_list``
Returns: bool
Example:
>>> from blur.markov.node import Node
>>> node_1 = No... | python | {
"resource": ""
} |
q43625 | Graph.pick | train | def pick(self, starting_node=None):
"""
Pick a node on the graph based on the links in a starting node.
Additionally, set ``self.current_node`` to the newly picked node.
* if ``starting_node`` is specified, start from there
* if ``starting_node`` is ``None``, start from ``self.... | python | {
"resource": ""
} |
q43626 | Graph.from_string | train | def from_string(cls,
source,
distance_weights=None,
merge_same_words=False,
group_marker_opening='<<',
group_marker_closing='>>'):
"""
Read a string and derive of ``Graph`` from it.
Words and pun... | python | {
"resource": ""
} |
q43627 | Graph.from_file | train | def from_file(cls,
source,
distance_weights=None,
merge_same_words=False,
group_marker_opening='<<',
group_marker_closing='>>'):
"""
Read a string from a file and derive a ``Graph`` from it.
This is a conv... | python | {
"resource": ""
} |
q43628 | ModelNotification.notify | train | def notify(self, force_notify=None, use_email=None, use_sms=None, **kwargs):
"""Overridden to only call `notify` if model matches.
"""
notified = False
instance = kwargs.get("instance")
if instance._meta.label_lower == self.model:
notified = super().notify(
... | python | {
"resource": ""
} |
q43629 | ZooBorg.getList | train | def getList(self, listtype):
'''
listtype must be a Zooborg constant
'''
if listtype not in [ZooConst.CLIENT, ZooConst.WORKER, ZooConst.BROKER]:
raise Exception('Zooborg.getList: invalid type')
self.initconn()
return self.zk.get_children('/distark/' + listtype... | python | {
"resource": ""
} |
q43630 | get_object_or_none | train | def get_object_or_none(model, *args, **kwargs):
"""
Like get_object_or_404, but doesn't throw an exception.
Allows querying for an object that might not exist without triggering
an exception.
"""
try:
return model._default_manager.get(*args, **kwargs)
except model.DoesNotExist:
... | python | {
"resource": ""
} |
q43631 | parse_response | train | async def parse_response(response: ClientResponse, schema: dict) -> Any:
"""
Validate and parse the BMA answer
:param response: Response of aiohttp request
:param schema: The expected response structure
:return: the json data
"""
try:
data = await response.json()
response.cl... | python | {
"resource": ""
} |
q43632 | API.reverse_url | train | def reverse_url(self, scheme: str, path: str) -> str:
"""
Reverses the url using scheme and path given in parameter.
:param scheme: Scheme of the url
:param path: Path of the url
:return:
"""
# remove starting slash in path if present
path = path.lstrip('... | python | {
"resource": ""
} |
q43633 | API.requests_get | train | async def requests_get(self, path: str, **kwargs) -> ClientResponse:
"""
Requests GET wrapper in order to use API parameters.
:param path: the request path
:return:
"""
logging.debug("Request : {0}".format(self.reverse_url(self.connection_handler.http_scheme, path)))
... | python | {
"resource": ""
} |
q43634 | API.requests_post | train | async def requests_post(self, path: str, **kwargs) -> ClientResponse:
"""
Requests POST wrapper in order to use API parameters.
:param path: the request path
:return:
"""
if 'self_' in kwargs:
kwargs['self'] = kwargs.pop('self_')
logging.debug("POST ... | python | {
"resource": ""
} |
q43635 | Client.post | train | async def post(self, url_path: str, params: dict = None, rtype: str = RESPONSE_JSON, schema: dict = None) -> Any:
"""
POST request on self.endpoint + url_path
:param url_path: Url encoded path following the endpoint
:param params: Url query string parameters dictionary
:param rt... | python | {
"resource": ""
} |
q43636 | quote_value | train | def quote_value(value):
"""return the value ready to be used as a value in a SQL string.
For example you can safely do this:
cursor.execute('select * from table where key = %s' % quote_value(val))
and you don't have to worry about possible SQL injections.
"""
adapted = adapt(value)
if... | python | {
"resource": ""
} |
q43637 | Analyze.load | train | def load(self,dset):
'''load a dataset from given filename into the object'''
self.dset_filename = dset
self.dset = nib.load(dset)
self.data = self.dset.get_data()
self.header = self.dset.get_header() | python | {
"resource": ""
} |
q43638 | Analyze.voxel_loop | train | def voxel_loop(self):
'''iterator that loops through each voxel and yields the coords and time series as a tuple'''
# Prob not the most efficient, but the best I can do for now:
for x in xrange(len(self.data)):
for y in xrange(len(self.data[x])):
for z in xrange(len(s... | python | {
"resource": ""
} |
q43639 | Client.payment | train | def payment(self, amount, **kwargs):
"""Get payment URL and new transaction ID
Usage::
>>> import sofort
>>> client = sofort.Client('123456', '123456', '123456',
abort_url='https://mysite.com/abort')
>>> t = client.pay(12, succ... | python | {
"resource": ""
} |
q43640 | load_env | train | def load_env(print_vars=False):
"""Load environment variables from a .env file, if present.
If an .env file is found in the working directory, and the listed
environment variables are not already set, they will be set according to
the values listed in the file.
"""
env_file = os.environ.get('EN... | python | {
"resource": ""
} |
q43641 | get_config | train | def get_config(config_schema, env=None):
"""Parse config from the environment against a given schema
Args:
config_schema:
A dictionary mapping keys in the environment to envpy Schema
objects describing the expected value.
env:
An optional dictionary used to o... | python | {
"resource": ""
} |
q43642 | get_line_matches | train | def get_line_matches(input_file: str,
pattern: str,
max_occurrencies: int = 0,
loose_matching: bool = True) -> dict:
r"""Get the line numbers of matched patterns.
:parameter input_file: the file that needs to be read.
:parameter pattern: the pa... | python | {
"resource": ""
} |
q43643 | insert_string_at_line | train | def insert_string_at_line(input_file: str,
string_to_be_inserted: str,
put_at_line_number: int,
output_file: str,
append: bool = True,
newline_character: str = '\n'):
r"""Write a string ... | python | {
"resource": ""
} |
q43644 | remove_line_interval | train | def remove_line_interval(input_file: str, delete_line_from: int,
delete_line_to: int, output_file: str):
r"""Remove a line interval.
:parameter input_file: the file that needs to be read.
:parameter delete_line_from: the line number from which start deleting.
:parameter delete_... | python | {
"resource": ""
} |
q43645 | upload_dataset | train | def upload_dataset(
dataset_name, file_path, task=None, dataset_attributes=None, **kwargs):
"""Uploads the given file to dataset store.
Parameters
----------
dataset_name : str
The name of the dataset to upload.
file_path : str
The full path to the file to upload
task : ... | python | {
"resource": ""
} |
q43646 | download_dataset | train | def download_dataset(
dataset_name, file_path, task=None, dataset_attributes=None, **kwargs):
"""Downloads the given dataset from dataset store.
Parameters
----------
dataset_name : str
The name of the dataset to upload.
file_path : str
The full path to the file to upload
... | python | {
"resource": ""
} |
q43647 | send_work | train | def send_work(baseurl, work_id=None, filename=None, command="make"):
"""Ask user for a file to send to a work"""
while 1:
if not work_id:
try:
work_id = input("id? ")
except KeyboardInterrupt:
exit(0)
work = get_work(work_id)
if not... | python | {
"resource": ""
} |
q43648 | activate | train | def activate():
"""Install the path-based import components."""
global PathFinder, FileFinder, ff_path_hook
path_hook_index = len(sys.path_hooks)
sys.path_hooks.append(ff_path_hook)
# Resetting sys.path_importer_cache values,
# to support the case where we have an implicit package inside an al... | python | {
"resource": ""
} |
q43649 | BroadcastMessageBuilder.send | train | def send(self):
"""Sends the broadcast message.
:returns: tuple of (:class:`adnpy.models.Message`, :class:`adnpy.models.APIMeta`)
"""
parse_links = self.parse_links or self.parse_markdown_links
message = {
'annotations': [],
'entities': {
... | python | {
"resource": ""
} |
q43650 | archive_compile | train | def archive_compile(filename, command="make"):
"""
Returns if the given archive properly compile.
Extract it in a temporary directory, run the given command, and return True it's result is 0
"""
if not tarfile.is_tarfile(filename):
print("Cannot extract archive")
return False
if ... | python | {
"resource": ""
} |
q43651 | Request.raw | train | def raw(self):
"""Make request to url and return the raw response object.
"""
try:
return urlopen(str(self.url))
except HTTPError as error:
try:
# parse error body as json and use message property as error message
parsed = self._par... | python | {
"resource": ""
} |
q43652 | Request.csv | train | def csv(self):
"""Parse raw response as csv and return row object list.
"""
lines = self._parsecsv(self.raw)
# set keys from header line (first line)
keys = next(lines)
for line in lines:
yield dict(zip(keys, line)) | python | {
"resource": ""
} |
q43653 | Request._parsecsv | train | def _parsecsv(x):
"""Deserialize file-like object containing csv to a Python generator.
"""
for line in x:
# decode as utf-8, whitespace-strip and split on delimiter
yield line.decode('utf-8').strip().split(config.DELIMITER) | python | {
"resource": ""
} |
q43654 | construct_exc_class | train | def construct_exc_class(cls):
"""Constructs proxy class for the exception."""
class ProxyException(cls, BaseException):
__pep3134__ = True
@property
def __traceback__(self):
if self.__fixed_traceback__:
return self.__fixed_traceback__
current_ex... | python | {
"resource": ""
} |
q43655 | BaseBuild.from_url | train | def from_url(cls, url, **kwargs):
"""
Downloads a zipped app source code from an url.
:param url: url to download the app source from
Returns
A project instance.
"""
username = kwargs.get('username')
password = kwargs.get('password')
headers = kwargs.get('headers', {})
auth =... | python | {
"resource": ""
} |
q43656 | BaseBuild.from_path | train | def from_path(cls, path):
"""
Instantiates a project class from a given path.
:param path: app folder path source code
Returns
A project instance.
"""
if os.path.exists(path) is False:
raise errors.InvalidPathError(path)
return cls(path=path) | python | {
"resource": ""
} |
q43657 | BaseBuild.from_zip | train | def from_zip(cls, src='/tmp/app.zip', dest='/app'):
"""
Unzips a zipped app project file and instantiates it.
:param src: zipfile path
:param dest: destination folder to extract the zipfile content
Returns
A project instance.
"""
try:
zf = zipfile.ZipFile(src, 'r')
except F... | python | {
"resource": ""
} |
q43658 | BaseBuild.inspect | train | def inspect(self, tab_width=2, ident_char='-'):
"""
Inspects a project file structure based based on the instance folder property.
:param tab_width: width size for subfolders and files.
:param ident_char: char to be used to show identation level
Returns
A string containing the project struct... | python | {
"resource": ""
} |
q43659 | BaseBuild.log | train | def log(self, ctx='all'):
"""
Gets the build log output.
:param ctx: specifies which log message to show, it can be 'validate', 'build' or 'all'.
"""
path = '%s/%s.log' % (self.path, ctx)
if os.path.exists(path) is True:
with open(path, 'r') as f:
print(f.read())
return
... | python | {
"resource": ""
} |
q43660 | second_order_diff | train | def second_order_diff(arr, x):
"""Compute second order difference of an array.
A 2nd order forward difference is used for the first point, 2nd order
central difference for interior, and 2nd order backward difference for last
point, returning an array the same length as the input array.
"""
# Co... | python | {
"resource": ""
} |
q43661 | _process_json | train | def _process_json(response_body):
"""
Returns a UwPassword objects
"""
data = json.loads(response_body)
uwpassword = UwPassword(uwnetid=data["uwNetID"],
kerb_status=data["kerbStatus"],
interval=None,
last_change=None... | python | {
"resource": ""
} |
q43662 | create_next_tag | train | def create_next_tag():
""" creates a tag based on the date and previous tags """
date = datetime.utcnow()
date_tag = '{}.{}.{}'.format(date.year, date.month, date.day)
if date_tag in latest_tag(): # if there was an update already today
latest = latest_tag().split('.') # split by spaces
i... | python | {
"resource": ""
} |
q43663 | sync_readmes | train | def sync_readmes():
""" just copies README.md into README for pypi documentation """
print("syncing README")
with open("README.md", 'r') as reader:
file_text = reader.read()
with open("README", 'w') as writer:
writer.write(file_text) | python | {
"resource": ""
} |
q43664 | Number.similarity | train | def similarity(self, other):
"""Get similarity as a ratio of the two numbers."""
numerator, denominator = sorted((self.value, other.value))
try:
ratio = float(numerator) / denominator
except ZeroDivisionError:
ratio = 0.0 if numerator else 1.0
similarity =... | python | {
"resource": ""
} |
q43665 | Text.similarity | train | def similarity(self, other):
"""Get similarity as a ratio of the two texts."""
ratio = SequenceMatcher(a=self.value, b=other.value).ratio()
similarity = self.Similarity(ratio)
return similarity | python | {
"resource": ""
} |
q43666 | TextTitle.similarity | train | def similarity(self, other):
"""Get similarity as a ratio of the stripped text."""
logging.debug("comparing %r and %r...", self.stripped, other.stripped)
ratio = SequenceMatcher(a=self.stripped, b=other.stripped).ratio()
similarity = self.Similarity(ratio)
return similarity | python | {
"resource": ""
} |
q43667 | skull_strip | train | def skull_strip(dset,suffix='_ns',prefix=None,unifize=True):
''' use bet to strip skull from given anatomy '''
# should add options to use betsurf and T1/T2 in the future
# Since BET fails on weirdly distributed datasets, I added 3dUnifize in... I realize this makes this dependent on AFNI. Sorry, :)
if ... | python | {
"resource": ""
} |
q43668 | query_sum | train | def query_sum(queryset, field):
"""
Let the DBMS perform a sum on a queryset
"""
return queryset.aggregate(s=models.functions.Coalesce(models.Sum(field), 0))['s'] | python | {
"resource": ""
} |
q43669 | get_env | train | def get_env(env_file='.env'):
"""
Set default environment variables from .env file
"""
try:
with open(env_file) as f:
for line in f.readlines():
try:
key, val = line.split('=', maxsplit=1)
os.environ.setdefault(key.strip(), val.... | python | {
"resource": ""
} |
q43670 | to_dict_formatter | train | def to_dict_formatter(row, cursor):
""" Take a row and use the column names from cursor to turn the row into a
dictionary.
Note: converts column names to lower-case!
:param row: one database row, sequence of column values
:type row: (value, ...)
:param cursor: the cursor which was used to make... | python | {
"resource": ""
} |
q43671 | Query.show | train | def show(self, *args, **kwds):
""" Show how the SQL looks like when executed by the DB.
This might not be supported by all connection types.
For example: PostgreSQL does support it, SQLite does not.
:rtype: str
"""
# Same as in __call__, arguments win over keywords
... | python | {
"resource": ""
} |
q43672 | Select._produce_return | train | def _produce_return(self, cursor):
""" Get the rows from the cursor and apply the row formatter.
:return: sequence of rows, or a generator if a row formatter has to be
applied
"""
results = cursor.fetchall()
# Format rows within a generator?
if self._row_for... | python | {
"resource": ""
} |
q43673 | SelectOne._produce_return | train | def _produce_return(self, cursor):
""" Return the one result.
"""
results = cursor.fetchmany(2)
if len(results) != 1:
return None
# Return the one row, or the one column.
row = results[0]
if self._row_formatter is not None:
row = self._row... | python | {
"resource": ""
} |
q43674 | SelectIterator._row_generator | train | def _row_generator(self, cursor):
""" Yields individual rows until no more rows
exist in query result. Applies row formatter if such exists.
"""
rowset = cursor.fetchmany(self._arraysize)
while rowset:
if self._row_formatter is not None:
rowset = (self... | python | {
"resource": ""
} |
q43675 | Manipulation._produce_return | train | def _produce_return(self, cursor):
""" Return the rowcount property from the used cursor.
Checks the count first, if a count was given.
:raise ManipulationCheckError: if a row count was set but does not
match
"""
rowcount = cursor.rowcount
# Check the row c... | python | {
"resource": ""
} |
q43676 | LinterRunner.get_results | train | def get_results(self):
"""Run the linter, parse, and return result list.
If a linter specified by the user is not found, return an error message
as result.
"""
try:
stdout, stderr = self._lint()
# Can't return a generator from a subprocess
ret... | python | {
"resource": ""
} |
q43677 | LinterRunner._get_command | train | def _get_command(self):
"""Return command with options and targets, ready for execution."""
targets = ' '.join(self.targets)
cmd_str = self._linter.command_with_options + ' ' + targets
cmd_shlex = shlex.split(cmd_str)
return list(cmd_shlex) | python | {
"resource": ""
} |
q43678 | LinterRunner._lint | train | def _lint(self):
"""Run linter in a subprocess."""
command = self._get_command()
process = subprocess.run(command, stdout=subprocess.PIPE, # nosec
stderr=subprocess.PIPE)
LOG.info('Finished %s', ' '.join(command))
stdout, stderr = self._get_outpu... | python | {
"resource": ""
} |
q43679 | Main.lint | train | def lint(self, targets):
"""Run linters in parallel and sort all results.
Args:
targets (list): List of files and folders to lint.
"""
LinterRunner.targets = targets
linters = self._config.get_linter_classes()
with Pool() as pool:
out_err_none = p... | python | {
"resource": ""
} |
q43680 | Main.run_from_cli | train | def run_from_cli(self, args):
"""Read arguments, run and print results.
Args:
args (dict): Arguments parsed by docopt.
"""
if args['--dump-config']:
self._config.print_config()
else:
stdout, stderr = self.lint(args['<path>'])
self.... | python | {
"resource": ""
} |
q43681 | Main.print_results | train | def print_results(cls, stdout, stderr):
"""Print linter results and exits with an error if there's any."""
for line in stderr:
print(line, file=sys.stderr)
if stdout:
if stderr: # blank line to separate stdout from stderr
print(file=sys.stderr)
... | python | {
"resource": ""
} |
q43682 | notification_on_post_create_historical_record | train | def notification_on_post_create_historical_record(
instance, history_date, history_user, history_change_reason, **kwargs
):
"""Checks and processes any notifications for this model.
Processes if `label_lower` is in site_notifications.models.
Note, this is the post_create of the historical model.
"... | python | {
"resource": ""
} |
q43683 | manage_mailists_on_userprofile_m2m_changed | train | def manage_mailists_on_userprofile_m2m_changed(
action, instance, pk_set, sender, **kwargs
):
"""Updates the mail server mailing lists based on the
selections in the UserProfile model.
"""
try:
instance.email_notifications
except AttributeError:
pass
else:
if action =... | python | {
"resource": ""
} |
q43684 | parse | train | def parse(file_contents, file_name):
'''
Takes a list of files which are assumed to be jinja2 templates and tries to
parse the contents of the files
Args:
file_contents (str): File contents of a jinja file
Raises:
Exception: An exception is raised if the contents of the file cannot... | python | {
"resource": ""
} |
q43685 | BaseHttpStreamReader.read_until | train | async def read_until(
self, separator: bytes=b"\n",
*, keep_separator: bool=True) -> bytes:
"""
Read until the separator has been found.
When the max size of the buffer has been reached,
and the separator is not found, this method will raise
a :class:`MaxBuff... | python | {
"resource": ""
} |
q43686 | HttpRequestReader.write_response | train | def write_response(
self, status_code: Union[int, constants.HttpStatusCode], *,
headers: Optional[_HeaderType]=None
) -> "writers.HttpResponseWriter":
"""
Write a response to the client.
"""
self._writer = self.__delegate.write_response(
constants.... | python | {
"resource": ""
} |
q43687 | createDbusProxyObject | train | def createDbusProxyObject(bus_name, object_path, bus=None):
'''
Create dbus proxy object
'''
bus = bus or dbus.SessionBus.get_session()
return bus.get_object(bus_name, object_path) | python | {
"resource": ""
} |
q43688 | translate | train | def translate(text, target_lang='en', source_lang=None):
"""
Use the Google v2 API to translate the text. You had better have set
the API key on this function before calling it.
"""
url_base = 'https://www.googleapis.com/language/translate/v2'
params = dict(
key=translate.API_key,
q=text,
target=target_lang... | python | {
"resource": ""
} |
q43689 | SigningKey.from_credentials | train | def from_credentials(cls: Type[SigningKeyType], salt: Union[str, bytes], password: Union[str, bytes],
scrypt_params: Optional[ScryptParams] = None) -> SigningKeyType:
"""
Create a SigningKey object from credentials
:param salt: Secret salt passphrase credential
... | python | {
"resource": ""
} |
q43690 | SigningKey.save_seedhex_file | train | def save_seedhex_file(self, path: str) -> None:
"""
Save hexadecimal seed file from seed
:param path: Authentication file path
"""
seedhex = convert_seed_to_seedhex(self.seed)
with open(path, 'w') as fh:
fh.write(seedhex) | python | {
"resource": ""
} |
q43691 | SigningKey.from_seedhex_file | train | def from_seedhex_file(path: str) -> SigningKeyType:
"""
Return SigningKey instance from Seedhex file
:param str path: Hexadecimal seed file path
"""
with open(path, 'r') as fh:
seedhex = fh.read()
return SigningKey.from_seedhex(seedhex) | python | {
"resource": ""
} |
q43692 | SigningKey.from_seedhex | train | def from_seedhex(cls: Type[SigningKeyType], seedhex: str) -> SigningKeyType:
"""
Return SigningKey instance from Seedhex
:param str seedhex: Hexadecimal seed string
"""
regex_seedhex = compile("([0-9a-fA-F]{64})")
match = search(regex_seedhex, seedhex)
if not mat... | python | {
"resource": ""
} |
q43693 | SigningKey.from_private_key | train | def from_private_key(path: str) -> SigningKeyType:
"""
Read authentication file
Add public key attribute
:param path: Authentication file path
"""
key = load_key(path)
key.pubkey = Base58Encoder.encode(key.vk)
return key | python | {
"resource": ""
} |
q43694 | SigningKey.decrypt_seal | train | def decrypt_seal(self, data: bytes) -> bytes:
"""
Decrypt bytes data with a curve25519 version of the ed25519 key pair
:param data: Encrypted data
:return:
"""
curve25519_public_key = libnacl.crypto_sign_ed25519_pk_to_curve25519(self.vk)
curve25519_secret_key = ... | python | {
"resource": ""
} |
q43695 | SigningKey.from_wif_or_ewif_file | train | def from_wif_or_ewif_file(path: str, password: Optional[str] = None) -> SigningKeyType:
"""
Return SigningKey instance from Duniter WIF or EWIF file
:param path: Path to WIF of EWIF file
:param password: Password needed for EWIF file
"""
with open(path, 'r') as fh:
... | python | {
"resource": ""
} |
q43696 | SigningKey.from_wif_or_ewif_hex | train | def from_wif_or_ewif_hex(wif_hex: str, password: Optional[str] = None) -> SigningKeyType:
"""
Return SigningKey instance from Duniter WIF or EWIF in hexadecimal format
:param wif_hex: WIF or EWIF string in hexadecimal format
:param password: Password of EWIF encrypted seed
"""
... | python | {
"resource": ""
} |
q43697 | SigningKey.from_wif_hex | train | def from_wif_hex(cls: Type[SigningKeyType], wif_hex: str) -> SigningKeyType:
"""
Return SigningKey instance from Duniter WIF in hexadecimal format
:param wif_hex: WIF string in hexadecimal format
"""
wif_bytes = Base58Encoder.decode(wif_hex)
if len(wif_bytes) != 35:
... | python | {
"resource": ""
} |
q43698 | SigningKey.from_ewif_file | train | def from_ewif_file(path: str, password: str) -> SigningKeyType:
"""
Return SigningKey instance from Duniter EWIF file
:param path: Path to EWIF file
:param password: Password of the encrypted seed
"""
with open(path, 'r') as fh:
wif_content = fh.read()
... | python | {
"resource": ""
} |
q43699 | SigningKey.from_ewif_hex | train | def from_ewif_hex(cls: Type[SigningKeyType], ewif_hex: str, password: str) -> SigningKeyType:
"""
Return SigningKey instance from Duniter EWIF in hexadecimal format
:param ewif_hex: EWIF string in hexadecimal format
:param password: Password of the encrypted seed
"""
ewi... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.