_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q53400 | ReplaceOldImageModel._replace_old_image | train | def _replace_old_image(self):
''' Override this in subclass if you don't want
image replacing or want to customize image replacing
'''
try:
old_obj = self.__class__.objects.get(pk=self.pk)
if old_obj.image.path != self.image.path:
path = old_ob... | python | {
"resource": ""
} |
q53401 | AbstractAttachedImage.next | train | def next(self):
''' Returns next image for same content_object and None if image is
the last. '''
try:
return self.__class__.objects.for_model(self.content_object,
self.content_type).\
filter(order__lt=se... | python | {
"resource": ""
} |
q53402 | AbstractAttachedImage.previous | train | def previous(self):
''' Returns previous image for same content_object and None if image
is the first. '''
try:
return self.__class__.objects.for_model(self.content_object,
self.content_type).\
filter(ord... | python | {
"resource": ""
} |
q53403 | _memo | train | def _memo(f):
"""Return a function like f but caching its results. Its arguments
must be hashable."""
memos = {}
def memoized(*args):
try: return memos[args]
except KeyError:
result = memos[args] = f(*args)
return result
return memoized | python | {
"resource": ""
} |
q53404 | Parser | train | def Parser(grammar, **actions):
r"""Make a parsing function from a peglet grammar, defining the
grammar's semantic actions with keyword arguments.
The parsing function maps a string to a results tuple or raises
Unparsable. (It can optionally take a rule name to start from, by
default the first in t... | python | {
"resource": ""
} |
q53405 | OneResult | train | def OneResult(parser):
"Parse like parser, but return exactly one result, not a tuple."
def parse(text):
results = parser(text)
assert len(results) == 1, "Expected one result but got %r" % (results,)
return results[0]
return parse | python | {
"resource": ""
} |
q53406 | _dev_encode | train | def _dev_encode(param_dict,drop_name,param_name):
"""
_dev_encode takes the parameter dictionary in, as well as the name of parameter
to drop from design matrix, and the string name of the parameter
it returns the encoded design matrix, list of column name strings, and
and encoder function to encod... | python | {
"resource": ""
} |
q53407 | DesignMatrix.trim_columns | train | def trim_columns(self, columns_to_trim):
"""
remove column in design matrix
"""
# TODO check if trimmed column is actually one of the columns
if len(self._trimmed_columns) == 0:
self._trimmed_columns.append(columns_to_trim)
else:
self._trimmed_colu... | python | {
"resource": ""
} |
q53408 | DesignMatrix.make_param_dict_from_file | train | def make_param_dict_from_file(self,path_to_params):
"""
make param dict from a file on disk
"""
# then we were given a path to a parameter file
param_list = list(csv.reader(open(path_to_params,"rb")))
# delete empty elements (if any)
param_file = [x for x in param... | python | {
"resource": ""
} |
q53409 | DesignMatrix.run_encoder | train | def run_encoder(self,param_dict, encoder_dict):
"""
run the encoder on a supplied param_dict
"""
X_dict = {}
Xcol_dict = {}
# put each column of X in Xbycol_dict
Xbycol_dict = {}
for key in encoder_dict:
if (key != 'twoway') and (key != 'threew... | python | {
"resource": ""
} |
q53410 | ItemsTableDirective.interpret_obj | train | def interpret_obj(
self,
obj,
v_level_indexes,
h_level_indexes,
v_level_visibility,
h_level_visibility,
v_level_sort_keys,
h_level_sort_keys,
v_level_titles,
h_level_titles,
):
"""Interpret the given Python object as a table.
... | python | {
"resource": ""
} |
q53411 | ItemsTableDirective.augment_cells_no_span | train | def augment_cells_no_span(self, rows, source):
"""Convert each cell into a tuple suitable for consumption by build_table.
"""
# TODO: Hardwired str transform.
# 4-tuple: morerows, morecols, offset, cellblock
# - morerows: The number of additional rows this cells spans
# -... | python | {
"resource": ""
} |
q53412 | _save_to_database | train | def _save_to_database(url, property_name, data):
"""
Store `data` under `property_name` in the `url` key in REST API DB.
Args:
url (obj): URL of the resource to which `property_name` will be stored.
property_name (str): Name of the property under which the `data` will
be stored.... | python | {
"resource": ""
} |
q53413 | worker | train | def worker(url_key, property_name, function, function_arguments):
"""
This function usually runs as process on the background.
It runs ``function(*function_arguments)`` and then stores them in REST API
storage.
Warning:
This function puts data into DB, isntead of returning them.
Args:... | python | {
"resource": ""
} |
q53414 | get_ip_address | train | def get_ip_address(domain):
"""
Get IP address for given `domain`. Try to do smart parsing.
Args:
domain (str): Domain or URL.
Returns:
str: IP address.
Raises:
ValueError: If can't parse the domain.
"""
if "://" not in domain:
domain = "http://" + domain
... | python | {
"resource": ""
} |
q53415 | get_whois_tags | train | def get_whois_tags(ip_address):
"""
Get list of tags with `address` for given `ip_address`.
Args:
index_page (str): HTML content of the page you wisht to analyze.
Returns:
list: List of :class:`.SourceString` objects.
"""
whois = IPWhois(ip_address).lookup_whois()
nets = wh... | python | {
"resource": ""
} |
q53416 | get_place_tags | train | def get_place_tags(index_page, domain): #: TODO geoip to docstring
"""
Return list of `place` tags parsed from `meta` and `whois`.
Args:
index_page (str): HTML content of the page you wisht to analyze.
domain (str): Domain of the web, without ``http://`` or other parts.
Returns:
... | python | {
"resource": ""
} |
q53417 | ApiResource.name | train | def name(self):
"""Name of the resource. If conversion to unicode somehow
didn't go well value is returned in base64 encoding."""
return (
self._raw_data.get(ATTR_NAME_UNICODE)
or self._raw_data.get(ATTR_NAME)
or ""
) | python | {
"resource": ""
} |
q53418 | ApiEntryPoint._sanitize_resources | train | def _sanitize_resources(cls, resources):
"""Loops over incoming data looking for base64 encoded data and
converts them to a readable format."""
try:
for resource in cls._loop_raw(resources):
cls._sanitize_resource(resource)
except (KeyError, TypeError):
... | python | {
"resource": ""
} |
q53419 | ApiEntryPoint.get_resources | train | async def get_resources(self, **kwargs) -> dict:
"""Get a list of resources.
:raises PvApiError when an error occurs.
"""
resources = await self.request.get(self._base_path, **kwargs)
self._sanitize_resources(resources)
return resources | python | {
"resource": ""
} |
q53420 | ApiEntryPoint.get_resource | train | async def get_resource(self, resource_id: int) -> dict:
"""Get a single resource.
:raises PvApiError when a hub connection occurs."""
resource = await self.request.get(
join_path(self._base_path, str(resource_id))
)
self._sanitize_resource(self._get_to_actual_data(re... | python | {
"resource": ""
} |
q53421 | ApiEntryPoint.get_instances | train | async def get_instances(self, **kwargs) -> List[ApiResource]:
"""Returns a list of resource instances.
:raises PvApiError when a hub problem occurs."""
raw_resources = await self.get_resources(**kwargs)
_instances = [
self._resource_factory(_raw)
for _raw in self... | python | {
"resource": ""
} |
q53422 | ApiEntryPoint.get_instance | train | async def get_instance(self, resource_id) -> ApiResource:
"""Gets a single instance of a pv resource
:raises PvApiError when a hub problem occurs."""
raw = await self.get_resource(resource_id)
return self._resource_factory(self._get_to_actual_data(raw)) | python | {
"resource": ""
} |
q53423 | multisorted | train | def multisorted(items, *keys):
"""Sort by multiple attributes.
Args:
items: An iterable series to be sorted.
*keys: Key objects which extract key values from the items.
The first key will be the most significant, and the
last key the least significant. If no key function... | python | {
"resource": ""
} |
q53424 | tuplesorted | train | def tuplesorted(items, *keys):
"""Sort by tuples with a different key for each item.
Args:
items: An iterable series of sequences (typically tuples)
*keys: Key objects which transform individual elements of
each tuple into sort keys. The zeroth object
transforms the zerot... | python | {
"resource": ""
} |
q53425 | AuthorPicker.show | train | def show(cls):
"""
Show the author picker.
"""
cls.div_el.style.display = "block"
cls.hide_errors()
cls.overlay.show()
cls.overlay.el.bind("click", lambda x: cls.hide()) | python | {
"resource": ""
} |
q53426 | AuthorPicker.hide_errors | train | def hide_errors(cls):
"""
Hide errors shown by validators.
"""
cls.select_el.style.border = "0"
cls.input_el.style.border = "0" | python | {
"resource": ""
} |
q53427 | AuthorPicker._pick_selected_option | train | def _pick_selected_option(cls):
"""
Select handler for authors.
"""
for option in cls.select_el:
# if the select is empty
if not hasattr(option, "selected"):
return None
if option.selected:
return option.value
... | python | {
"resource": ""
} |
q53428 | AuthorPicker.on_pick_button_pressed | train | def on_pick_button_pressed(cls, ev):
"""
Callback called when the user press the button for accepting the picked
author.
This element calls validations, before accepting the choice.
"""
cls.hide_errors()
selected_code = cls._pick_selected_option()
if not... | python | {
"resource": ""
} |
q53429 | AuthorPicker.bind | train | def bind(cls):
"""
Bind the callbacks to the buttons.
"""
document["show_author_picker"].bind("click", lambda x: cls.show())
cls.storno_btn_el.bind("click", lambda x: cls.hide())
cls.pick_btn_el.bind("click", cls.on_pick_button_pressed) | python | {
"resource": ""
} |
q53430 | AuthorPicker.validate | train | def validate(cls):
"""
Validate required elements.
"""
if not SWITCHER_EL.checked:
return True
if not cls.selected_code:
cls.original_author_el.style.border = "2px solid red"
return False
cls.original_author_el.style.border = "0"
... | python | {
"resource": ""
} |
q53431 | AuthorPickerAdapter.on_complete | train | def on_complete(cls, req):
"""
Callback called when the request was received.
"""
# handle http errors
if not (req.status == 200 or req.status == 0):
alert("Couldn't connect to authority base.")
LogView.add(
"Error when calling Aleph author... | python | {
"resource": ""
} |
q53432 | AuthorPickerAdapter.start | train | def start(cls, ev):
"""
Event handler which starts the request to REST API.
"""
# somehow the first call doesn't stop the propagation
ev.stopPropagation()
ev.preventDefault()
# make sure, that `author` was filled
author = cls.input_el.value.strip()
... | python | {
"resource": ""
} |
q53433 | AuthorPickerAdapter.bind | train | def bind(cls):
"""
Bind the buttons to adapter's event handler.
"""
super(cls, cls).bind()
cls.search_btn_el.bind("click", cls.start)
cls.input_el.bind("keypress", func_on_enter(cls.start)) | python | {
"resource": ""
} |
q53434 | zap_horizontally | train | def zap_horizontally(can, style, pat, x1, y1, x2, y2, xsize, ysize):
"""Draw a horizontal "zapping" symbol on the canvas that shows
that a graph is ripped in the middle.
Parameter <fill_style> specifies the style for the zig-zag lines.
PAT specifies the pattern with which the area is filled.
The sy... | python | {
"resource": ""
} |
q53435 | zap_vertically | train | def zap_vertically(can, style, pat, x1, y1, x2, y2, xsize, ysize):
"""Draw a vertical "zapping" symbol on the canvas that shows
that a graph is ripped in the middle.
Parameter <fill_style> specifies the style for the zig-zag lines.
PAT specifies the pattern with which the area is filled.
The symbol... | python | {
"resource": ""
} |
q53436 | init | train | def init(*, threshold_lvl=1, quiet_stdout=False, log_file):
"""
Initiate the log module
:param threshold_lvl: messages under this level won't be issued/logged
:param to_stdout: activate stdout log stream
"""
global _logger, _log_lvl
# translate lvl to those used by 'logging' module
_lo... | python | {
"resource": ""
} |
q53437 | msg | train | def msg(message):
"""
Log a regular message
:param message: the message to be logged
"""
to_stdout(" --- {message}".format(message=message))
if _logger:
_logger.info(message) | python | {
"resource": ""
} |
q53438 | msg_warn | train | def msg_warn(message):
"""
Log a warning message
:param message: the message to be logged
"""
to_stdout(" (!) {message}".format(message=message),
colorf=yellow, bold=True)
if _logger:
_logger.warn(message) | python | {
"resource": ""
} |
q53439 | msg_err | train | def msg_err(message):
"""
Log an error message
:param message: the message to be logged
"""
to_stdout(" !!! {message}".format(message=message), colorf=red, bold=True)
if _logger:
_logger.error(message) | python | {
"resource": ""
} |
q53440 | msg_debug | train | def msg_debug(message):
"""
Log a debug message
:param message: the message to be logged
"""
if _log_lvl == logging.DEBUG:
to_stdout(" (*) {message}".format(message=message), colorf=cyan)
if _logger:
_logger.debug(message) | python | {
"resource": ""
} |
q53441 | index | train | def index(request, template_name='staffmembers/index.html'):
"""
The list of employees or staff members
"""
return render_to_response(template_name,
{'staff': StaffMember.objects.active()},
context_instance=RequestContext(request)) | python | {
"resource": ""
} |
q53442 | userinfo_json | train | def userinfo_json(request, user_id):
"""
Return the user's information in a json object
"""
data = {'first_name': '',
'last_name': '',
'email': '',
'slug': '',
'bio': '',
'phone': '',
'is_active': False}
try:
member = S... | python | {
"resource": ""
} |
q53443 | contact | train | def contact(request, slug, template_name='staffmembers/contact.html',
success_url='/staff/contact/done/',
email_subject_template='staffmembers/emails/subject.txt',
email_body_template='staffmembers/emails/body.txt'):
"""
Handle a contact request
"""
member = get_objec... | python | {
"resource": ""
} |
q53444 | story_archive | train | def story_archive(request, slug, template_name='staffmembers/story_archive.html'):
"""
Return the list of stories written by this staff member
"""
member = get_object_or_404(StaffMember, slug__iexact=slug, is_active=True)
stories = []
if hasattr(member, 'story_set'):
from story.settings... | python | {
"resource": ""
} |
q53445 | ExpectedValue.save | train | def save( self ):
"""
Save method for the ExpectedValue of a call.
"""
packets = self.__enumerate_packets()
delete_expected_value(self.call_hash)
for packet in packets:
packet['call_hash'] = self.call_hash
insert_expected_value(packet)
re... | python | {
"resource": ""
} |
q53446 | Protocol.sanitize | train | def sanitize(self):
'''
Check and optionally fix properties
'''
# Let the parent do its stuff
super(Protocol, self).sanitize()
# Check if the next header is of the right type, and fix this header
# if we know better (i.e. the payload is a ProtocolElement so we kn... | python | {
"resource": ""
} |
q53447 | register_blueprints | train | def register_blueprints(app):
"""Register blueprints to application.
Currently, Rio registered:
* /api/1
* /dashboard
"""
from .blueprints.event import bp as event_bp
app.register_blueprint(event_bp, url_prefix='/event')
from .blueprints.api_1 import bp as api_1_bp
app.register_b... | python | {
"resource": ""
} |
q53448 | setup_user_manager | train | def setup_user_manager(app):
"""Setup flask-user manager."""
from flask_user import SQLAlchemyAdapter
from rio.models import User
init = dict(
db_adapter=SQLAlchemyAdapter(db, User),
)
user_manager.init_app(app, **init) | python | {
"resource": ""
} |
q53449 | setup_migrate | train | def setup_migrate(app):
"""Setup flask-migrate."""
directory = path.join(path.dirname(__file__), 'migrations')
migrate.init_app(app, db, directory=directory) | python | {
"resource": ""
} |
q53450 | init_core | train | def init_core(app):
"""Init core objects."""
from rio import models # noqa
db.init_app(app)
celery.init_app(app)
redis.init_app(app)
cache.init_app(app)
sentry.init_app(app)
graph.init_app(app)
setup_migrate(app)
setup_user_manager(app) | python | {
"resource": ""
} |
q53451 | remove_empty_dir | train | def remove_empty_dir(path):
""" Function to remove empty folders """
try:
if not os.path.isdir(path):
return
files = os.listdir(path)
# if folder empty, delete it
if len(files) == 0:
os.rmdir(path)
# remove empty subdirectory
elif len(fi... | python | {
"resource": ""
} |
q53452 | Period.from_soup_tag | train | def from_soup_tag(tag):
"Returns a new Period instance from the given beautifulsoup tag."
days = []
for elem in tag.findAll(recursive=False):
if elem.name != 'day':
raise TypeError("Unknown tag found: " + str(elem))
days.append(elem.string)
return ... | python | {
"resource": ""
} |
q53453 | Period.conflicts_with | train | def conflicts_with(self, period):
"Checks this period conflicts with another period."
if self.tba or period.tba:
return False
same_day = False
for i in self.int_days:
if i in period.int_days:
same_day = True
if not same_day:
re... | python | {
"resource": ""
} |
q53454 | Section.from_soup_tag | train | def from_soup_tag(tag):
"Returns an instance from a given soup tag."
periods = []
notes = []
for elem in tag.findAll(recursive=False):
if elem.name not in ('period', 'note'):
raise TypeError("Unknown tag found: " + str(elem))
if elem.name == 'note'... | python | {
"resource": ""
} |
q53455 | Course.credits | train | def credits(self):
"""Returns either a tuple representing the credit range or a
single integer if the range is set to one value.
Use self.cred to always get the tuple.
"""
if self.cred[0] == self.cred[1]:
return self.cred[0]
return self.cred | python | {
"resource": ""
} |
q53456 | Course.from_soup_tag | train | def from_soup_tag(tag):
"Creates an instance from a given soup tag."
sections = [Section.from_soup_tag(s) for s in tag.findAll('section')]
return Course(
tag['name'], tag['dept'], int(tag['num']), tag['credmin'],
tag['credmax'], tag['gradetype'], [s for s in sections if s... | python | {
"resource": ""
} |
q53457 | password_generator | train | def password_generator(length):
"""Generate a random password.
:param length: integer.
"""
return ''.join(random.choice(string.ascii_lowercase + string.digits)
for _ in range(length)) | python | {
"resource": ""
} |
q53458 | DVMBasicBlock.get_instructions | train | def get_instructions(self):
"""
Get all instructions from a basic block.
:rtype: Return all instructions in the current basic block
"""
tmp_ins = []
idx = 0
for i in self.method.get_instructions():
if idx >= self.start and idx < self.end:
... | python | {
"resource": ""
} |
q53459 | Sample.get_reports | train | def get_reports(self):
"""
Retrieve all reports submitted for this Sample.
:return: A list of :class:`.Report`
"""
url = '{}reports/'.format(self.url)
return Report._get_list_from_url(url, append_base_url=False) | python | {
"resource": ""
} |
q53460 | Sample.get_relation_graph | train | def get_relation_graph(self, depth=None):
"""
Get all `SampleRelation`s in the relation graph of the sample.
:param depth: max depth of the returned graph. None retrieves the complete graph.
:return: An iterator over the relations
"""
url = '{}relation_graph/'.format(sel... | python | {
"resource": ""
} |
q53461 | FileSample.download_to_file | train | def download_to_file(self, file):
"""
Download and store the file of the sample.
:param file: A file-like object to store the file.
"""
con = ConnectionManager().get_connection(self._connection_alias)
return con.download_to_file(self.file, file, append_base_url=False) | python | {
"resource": ""
} |
q53462 | VersionInfo.git_remote | train | def git_remote(self):
"""
If the distribution is installed via git, return the first URL of the
'origin' remote if one is configured for the repo, or else the first
URL of the lexicographically-first remote, or else None.
:return: origin or first remote URL
:rtype: :py:o... | python | {
"resource": ""
} |
q53463 | VersionInfo.git_str | train | def git_str(self):
"""
If the distribution is not installed via git, return an empty string.
If the distribution is installed via git and pip recognizes the git
source, return the pip requirement string specifying the git URL and
commit, with an '*' appended if :py:attr:`~.git_i... | python | {
"resource": ""
} |
q53464 | AgencyMiddleBase.call_agent_side | train | def call_agent_side(self, method, *args, **kwargs):
'''
Call the method, wrap it in Deferred and bind error handler.
'''
assert not self._finalize_called, ("Attempt to call agent side code "
"after finalize() method has been "
... | python | {
"resource": ""
} |
q53465 | serialize | train | def serialize(ad_objects, output_format='json', indent=2, attributes_only=False):
"""Serialize the object to the specified format
:param ad_objects list: A list of ADObjects to serialize
:param output_format str: The output format, json or yaml. Defaults to json
:param indent int: The number of spaces... | python | {
"resource": ""
} |
q53466 | Utils.add_url_parameters | train | def add_url_parameters(url, parameters):
""" Add url parameters to URL. """
scheme, netloc, path, query_string, fragment = urlsplit(url)
query = parse_qs(query_string)
query.update(parameters)
return urlunsplit((scheme, netloc, path, urlencode(query), fragment)) | python | {
"resource": ""
} |
q53467 | CoredataClient.edit | train | def edit(self, entity, id, payload, sync=True):
""" Edit a document. """
url = urljoin(self.host, entity.value + '/')
url = urljoin(url, id + '/')
params = {'sync': str(sync).lower()}
url = Utils.add_url_parameters(url, params)
r = requests.put(url, auth=self.auth, data=j... | python | {
"resource": ""
} |
q53468 | CoredataClient.get | train | def get(self, entity, id=None, sub_entity=None, offset=0, limit=20,
search_terms=None, sync=True):
"""
Get all entities that fufill the given filtering if provided.
:todo: Rename search_terms
"""
url = urljoin(self.host, entity.value + '/')
url = urljoin(url,... | python | {
"resource": ""
} |
q53469 | YeelightAPICall.operate_on_bulb | train | def operate_on_bulb(self, method, params=None):
"""
Build socket and send command to the bulb through it
:param method: method you want to use
:param params: parameters needed for this method (can be a string if ony one parameter is needed)
:type method: str
... | python | {
"resource": ""
} |
q53470 | T.__register_font | train | def __register_font(self, name):
"Assign an ID to the font NAME. Return its ID."
if name not in self.__registered_fonts:
self.__registered_fonts[name] = self.__next_font_id
self.__next_font_id += 1
return self.__registered_fonts[name] | python | {
"resource": ""
} |
q53471 | exception_translation | train | def exception_translation(func):
"""
Catch exception and build correct api response for it.
"""
@wraps(func)
def decorator(*arg, **kwargs):
try:
return func(*arg, **kwargs)
except InvalidOperationException, e:
return Response(status=status.HTTP_412_PRECONDITIO... | python | {
"resource": ""
} |
q53472 | DjangoServiceAPI.service | train | def service(self):
'''
Instantiate service class with django http_request
'''
service_class = getattr(self, 'service_class')
service = service_class(self.http_request)
return service | python | {
"resource": ""
} |
q53473 | DjangoServiceAPI.get_object | train | def get_object(self, queryset=None):
"""
Override default to add support for object-level permissions.
"""
try:
pk = self.kwargs.get('pk', None)
# allow serializer without service
obj = self.service.get(pk)
return obj
except self.m... | python | {
"resource": ""
} |
q53474 | AmqpHandler.emit | train | def emit(self, record):
"""
The amqp module also print the log when call publish, this will cause maximum recursion depth exceeded.
"""
if not record.name == "amqp":
data = {}
for k, v in record.__dict__.items():
if (self.__includes and k in self._... | python | {
"resource": ""
} |
q53475 | Connection.get_database_tag | train | def get_database_tag(self):
'''
Each feat database has a unique tag which identifies it. Thanks to it
the mechanism cleaning up the update logs make the difference between
the changes done locally and remotely. The condition for cleaning
those up is different.
'''
... | python | {
"resource": ""
} |
q53476 | generate | train | def generate(categorize=unicodedata.category, group_class=RangeGroup):
'''
Generate a dict of RangeGroups for each unicode character category,
including general ones.
:param categorize: category function, defaults to unicodedata.category.
:type categorize: callable
:param group_class: class for... | python | {
"resource": ""
} |
q53477 | RangeGroup.codes | train | def codes(self):
'''
Get iterator for all unicode code points contained in this range group.
:yields: iterator of character index (int)
:ytype: int
'''
for start, end in self:
for item in range(start, end):
yield item | python | {
"resource": ""
} |
q53478 | locate | train | def locate(connection, agent_id):
'''
Return the hostname of the agency where given agent runs or None.
'''
connection = IDatabaseClient(connection)
log.log('locate', 'Locate called for agent_id: %r', agent_id)
try:
desc = yield connection.get_document(agent_id)
log.log('locate',... | python | {
"resource": ""
} |
q53479 | ping | train | def ping(enode, count, destination, interval=None, quiet=False, shell=None):
"""
Perform a ping and parse the result.
:param enode: Engine node to communicate with.
:type enode: topology.platforms.base.BaseNode
:param int count: Number of packets to send.
:param str destination: The destination... | python | {
"resource": ""
} |
q53480 | RulesView.get_dict | train | def get_dict(self):
"""
Convert all rules to dict and return them.
"""
out = {
property_name: getattr(self, property_name)
for property_name in self._property_names
}
if "frequency" in out:
out["frequency"] = int(out["frequency"])
... | python | {
"resource": ""
} |
q53481 | RulesView.set_dict | train | def set_dict(self, incomming):
"""
Set all rules from the `incomming` dictionary.
"""
for key, val in incomming.items():
if val and key in self._property_names:
setattr(self, key, val) | python | {
"resource": ""
} |
q53482 | _make_style_str | train | def _make_style_str(styledict):
"""
Make an SVG style string from the dictionary. See also _parse_style_str also.
"""
s = ''
for key in list(styledict.keys()):
s += "%s:%s;" % (key, styledict[key])
return s | python | {
"resource": ""
} |
q53483 | assert_valid_arguments | train | def assert_valid_arguments(func, *args, **kwargs):
"""
Validate provided arguments against a function's argspec.
"""
# get the function argspec
argspec = getargspec(func)
func_defaults = argspec.defaults or tuple()
defaults = (Required,) * (len(argspec.args) - len(func_defaults)) + func_def... | python | {
"resource": ""
} |
q53484 | UserPermission.global_permission_set | train | def global_permission_set(self):
'''All users must be authenticated. Only admins can create other admin
users.'''
only_admins_create_admins = Or(
AllowAdmin,
And(
ObjAttrTrue(
lambda r, _: r.data.get('admin') is not True),
... | python | {
"resource": ""
} |
q53485 | HTMLViewerDialog.setDocument | train | def setDocument(self, filename, empty=""):
"""Sets the HTML text to be displayed. """
self._source = QUrl.fromLocalFile(filename)
if os.path.exists(filename):
self.viewer.setSource(self._source)
else:
self.viewer.setText(empty) | python | {
"resource": ""
} |
q53486 | DirectoryListWidget._checkSize | train | def _checkSize(self):
"""Automatically resizes widget to display at most max_height_items items"""
if self._item_height is not None:
sz = min(self._max_height_items, self.count()) * self._item_height + 5
sz = max(sz, 20)
self.setMinimumSize(0, sz)
self.set... | python | {
"resource": ""
} |
q53487 | MainWindow._entryChanged | train | def _entryChanged(self, entry):
"""This is called when a log entry is changed"""
# resave the log
self.purrer.save()
# redo entry item
if entry.tw_item:
number = entry.tw_item._ientry
entry.tw_item = None
self.etw.takeTopLevelItem(number)
... | python | {
"resource": ""
} |
q53488 | sing | train | def sing(a, b, c=False, name='yetone'):
"""sing a song
hehe
:param a: I'm a
:param b: I'm b
:param c: I'm c
:param name: I'm name
"""
print('test0.sing: <a: {}, b: {}, c: {}> by {}'.format(a, b, c, name)) | python | {
"resource": ""
} |
q53489 | _get_deadline | train | def _get_deadline(results, timeout=None):
""" returns the earliest deadline point in time """
start_time = time()
all_deadlines = set(result.get_deadline() for result in results)
all_deadlines.discard(None)
if timeout is not None:
all_deadlines.add(start_time + timeout)
return min(all_d... | python | {
"resource": ""
} |
q53490 | recursive_load | train | def recursive_load(search_root):
"""Recursively loads all fixtures"""
for root, dirs, files in os.walk(search_root):
dir_name = os.path.basename(root)
if dir_name == 'fixtures':
for file_name in files:
fixture_path = os.path.join(root, file_name)
execu... | python | {
"resource": ""
} |
q53491 | run_marionette_script | train | def run_marionette_script(script, chrome=False, async=False, host='localhost', port=2828):
"""Create a Marionette instance and run the provided script"""
m = DeviceHelper.getMarionette(host, port)
m.start_session()
if chrome:
m.set_context(marionette.Marionette.CONTEXT_CHROME)
if not async:
... | python | {
"resource": ""
} |
q53492 | set_permission | train | def set_permission(permission, value, app):
"""Set a permission for the specified app
Value should be 'deny' or 'allow'
"""
# The object created to wrap PermissionSettingsModule is to work around
# an intermittent bug where it will sometimes be undefined.
script = """
const {classes: Cc... | python | {
"resource": ""
} |
q53493 | SqliteWriter.get_log_entries | train | def get_log_entries(self, start_date=None, end_date=None, filters=list(),
limit=None):
'''
See feat.agencies.interface.IJournalReader.get_log_entres
'''
query = text_helper.format_block('''
SELECT "localhost",
logs.message,
lo... | python | {
"resource": ""
} |
q53494 | SqliteWriter._decode | train | def _decode(self, entries, entry_type):
'''
Takes the list of rows returned by sqlite.
Returns rows in readable format. Transforms tuples into dictionaries,
and appends information about entry type to the rows.
'''
def decode_blobs(row):
row = list(row)
... | python | {
"resource": ""
} |
q53495 | SqliteWriter._get_history_id | train | def _get_history_id(self, connection, agent_id, instance_id):
'''
Checks own cache for history_id for agent_id and instance_id.
If information is missing fetch it from database. If it is not there
create the new record.
BEWARE: This method runs in a thread.
'''
c... | python | {
"resource": ""
} |
q53496 | InputController._set_input | train | def _set_input(el, value):
"""
Set content of given `el` to `value`.
Args:
el (obj): El reference to input you wish to set.
value (obj/list): Value to which the `el` will be set.
"""
if isinstance(value, dict):
el.value = value["val"]
... | python | {
"resource": ""
} |
q53497 | InputController._set_textarea | train | def _set_textarea(el, value):
"""
Set content of given textarea element `el` to `value`.
Args:
el (obj): Reference to textarea element you wish to set.
value (obj/list): Value to which the `el` will be set.
"""
if isinstance(value, dict):
el.t... | python | {
"resource": ""
} |
q53498 | InputController._set_typeahead | train | def _set_typeahead(cls, el, value):
"""
Convert given `el` to typeahead input and set it to `value`.
This method also sets the dropdown icons and descriptors.
Args:
el (obj): Element reference to the input you want to convert to
typeahead.
value ... | python | {
"resource": ""
} |
q53499 | InputController._reset_typeaheads | train | def _reset_typeaheads(cls):
"""
Reset all values set by typeahead back to default.
"""
for el_id in cls._set_by_typeahead:
window.destroy_typeahead_tag("#" + el_id)
cls._set_by_typeahead = set() | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.