_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q52100 | CourseCatalog.find_courses | train | def find_courses(self, partial):
"""Finds all courses by a given substring. This is case-insensitive.
"""
partial = partial.lower()
keys = self.courses.keys()
keys = [k for k in keys if k.lower().find(partial) != -1]
courses = [self.courses[k] for k in keys]
retur... | python | {
"resource": ""
} |
q52101 | CourseCatalog.find_course_by_crn | train | def find_course_by_crn(self, crn):
"""Searches all courses by CRNs. Not particularly efficient.
Returns None if not found.
"""
for name, course in self.courses.iteritems():
if crn in course:
return course
return None | python | {
"resource": ""
} |
q52102 | CourseCatalog.find_course_and_crosslistings | train | def find_course_and_crosslistings(self, partial):
"""Returns the given course and all other courses it is
crosslisted with.
"""
course = self.find_course(partial)
crosslisted = self.crosslisted_with(course.crn)
return (course,) + tuple(map(self.find_course_by_crn, crossli... | python | {
"resource": ""
} |
q52103 | cache_hash | train | def cache_hash(*a, **kw):
""" Try to hash an arbitrary object for caching. """
def cache_str(o):
if isinstance(o, (types.FunctionType, types.BuiltinFunctionType,
types.MethodType, types.BuiltinMethodType,
types.UnboundMethodType)):
return ... | python | {
"resource": ""
} |
q52104 | python_mime | train | def python_mime(fn):
"""
Decorator, which adds correct MIME type for python source to the decorated
bottle API function.
"""
@wraps(fn)
def python_mime_decorator(*args, **kwargs):
response.content_type = "text/x-python"
return fn(*args, **kwargs)
return python_mime_decorato... | python | {
"resource": ""
} |
q52105 | download_as_file | train | def download_as_file(fn, data=None):
"""
Download given `data` as file `fn`. This service exists to allow frontend
present user with downloadable files.
"""
if data is None:
raise HTTPError(500, "This service require POST `data` parameter.")
response.set_header("Content-Type", "applicat... | python | {
"resource": ""
} |
q52106 | merge_dicts | train | def merge_dicts(*dicts, **kwargs):
"""Merges dicts and kwargs into one dict"""
result = {}
for d in dicts:
result.update(d)
result.update(kwargs)
return result | python | {
"resource": ""
} |
q52107 | clone | train | def clone(src, **kwargs):
"""Clones object with optionally overridden fields"""
obj = object.__new__(type(src))
obj.__dict__.update(src.__dict__)
obj.__dict__.update(kwargs)
return obj | python | {
"resource": ""
} |
q52108 | setup_pod | train | def setup_pod(build_file_path, manage_dir=None, local_requirements=None):
"""
This must be called by the project's build.py for pyntofdjango to function.
You can specify it directly with the optional manage_dir kwarg.
:param build_file_path: E.g. os.path.abspath(__file__)
:param manage_dir: Optio... | python | {
"resource": ""
} |
q52109 | codify | train | def codify(combination):
"""
Gets escape-codes for flag combinations.
Arguments:
combination (int): Either a single integer-convertible flag
or an OR'd flag-combination.
Returns:
A semi-colon-delimited string of appropriate escape sequences.
Raises:
errors.FlagError if the combination is out-of-r... | python | {
"resource": ""
} |
q52110 | assertSameType | train | def assertSameType(a, b):
"""
Raises an exception if @b is not an instance of type(@a)
"""
if not isinstance(b, type(a)):
raise NotImplementedError("This operation is only supported for " \
"elements of the same type. Instead found {} and {}".
format(type(a), type(b))... | python | {
"resource": ""
} |
q52111 | assertType | train | def assertType(var, *allowedTypes):
"""
Asserts that a variable @var is of an @expectedType. Raises a TypeError
if the assertion fails.
"""
if not isinstance(var, *allowedTypes):
raise NotImplementedError("This operation is only supported for {}. "\
"Instead found {}".format(str(... | python | {
"resource": ""
} |
q52112 | dp | train | def dp(**kwargs):
"""
Debugging print. Prints a list of labels and values, each on their
own line.
"""
for label,value in kwargs.iteritems():
print "{0}\t{1}".format(label, value) | python | {
"resource": ""
} |
q52113 | choice | train | def choice(choices):
"""Test that the data items are members of the set `choices`."""
def decorator(function):
"""Decorate a function with args."""
@functools.wraps(function)
def wrapper(*args, **kwargs):
"""Wrap the function."""
series = function(*args, **kwargs)... | python | {
"resource": ""
} |
q52114 | get_view_doc | train | def get_view_doc(view, html=True):
"""
Build view documentation. Return in html format.
If you want in markdown format, use html=False
"""
try:
description = view.__doc__ or ''
description = formatting.dedent(smart_text(description))
# include filters in description
... | python | {
"resource": ""
} |
q52115 | run | train | def run(cmd, *, args='', timeout=600):
"""
Execute a process
:param cmd(str): name of the executable
:param args(str, optional): arbitrary arguments
:param timeout(int, optional): Execution timeout
:raises OSError: if the execution of cmd fails
"""
# type checks
utils.chkstr(cmd, '... | python | {
"resource": ""
} |
q52116 | freeze_tag | train | def freeze_tag(name):
"""
This is not using decorator.py because we need to access original function
not the wrapper.
"""
def decorator(func):
setattr(func, FREEZING_TAG_ATTRIBUTE, name)
return func
return decorator | python | {
"resource": ""
} |
q52117 | Unserializer.delayed_unpacking | train | def delayed_unpacking(self, container, fun, *args, **kwargs):
"""Should be used when unpacking mutable values.
This allows circular references resolution by pausing serialization."""
try:
self._delayed += 1
blob = self._begin()
try:
fun(*args, ... | python | {
"resource": ""
} |
q52118 | Unserializer.unpack_unordered_pairs | train | def unpack_unordered_pairs(self, pairs):
"""Unpack an unordered list of value pairs taking DelayPacking
exceptions into account to resolve circular references .
Used to unpack dictionary items when the order is not guarennteed
by the serializer. When item order change between packing
... | python | {
"resource": ""
} |
q52119 | NodeDriver_wait_until_running | train | def NodeDriver_wait_until_running(self, node, wait_period=3, timeout=600,
ssh_interface='public_ips', force_ipv4=True):
"""
Block until node is fully booted and has an IP address assigned.
@keyword node: Node instance.
@type node: C{Node}
@keyword wait... | python | {
"resource": ""
} |
q52120 | FileDeployment.run | train | def run(self, node, client):
"""
Upload the file, retaining permissions
See also L{Deployment.run}
"""
perms = os.stat(self.source).st_mode
client.put(path=self.target, chmod=perms,
contents=open(self.source, 'rb').read())
return node | python | {
"resource": ""
} |
q52121 | main | train | def main(api_key, token, board_id):
"""List out the board lists for our client"""
trello_client = TrelloClient(
api_key=api_key,
token=token,
)
board = Board(client=trello_client, board_id=board_id)
print('Lists')
print('-----')
print('Name: Id')
for card_list in board.al... | python | {
"resource": ""
} |
q52122 | JSON.update | train | def update(self, data, key):
"""Update a key's value's in a JSON file."""
og_data = self.read()
og_data[key] = data
self.write(og_data) | python | {
"resource": ""
} |
q52123 | SolveProblemContractor.announced | train | def announced(self, state, announcement):
'''
This part of contract is just to let the guy know we are here.
'''
state.problem = state.factory(state.agent, **announcement.payload)
state.medium.bid(message.Bid()) | python | {
"resource": ""
} |
q52124 | get_pore_surface_parameters | train | def get_pore_surface_parameters(surface_area):
""" Get input parameters for pore surface binary.
Get input parameters for pore_surface binary from zeo++ output,
while keeping data provenance.
"""
PoreSurfaceParameters = DataFactory('phtools.surface')
d = {
'accessible_surface_area': sur... | python | {
"resource": ""
} |
q52125 | store_property | train | def store_property(url, property_name, value):
"""
Look into database and store `value` under `property_name` in `url`.
This is part of the REST API.
"""
logger.debug(
"store_property(): Received property_name=%s value=%s" % (
property_name,
value,
),
... | python | {
"resource": ""
} |
q52126 | remove_if_exists | train | def remove_if_exists(filename):
""" Remove file.
This is like :func:`os.remove` (or :func:`os.unlink`), except that no
error is raised if the file does not exist.
"""
try:
os.unlink(filename)
except OSError as ex:
if ex.errno != errno.ENOENT:
raise | python | {
"resource": ""
} |
q52127 | AnalysisRunnerAdapter.fill_inputs | train | def fill_inputs(values):
"""
Callback called when the data is received. Basically translator from
the REST names to locally used names.
"""
name_map = { # TODO: get rid of this crap
"title_tags": "title",
"subtitle_tags": "subtitle",
"place_ta... | python | {
"resource": ""
} |
q52128 | AlephISSNReaderAdapter._handle_aleph_keyword_view | train | def _handle_aleph_keyword_view(dataset):
"""
Translate the Aleph keywords to locally used data.
"""
# redirect the keywords to Aleph view
adder = ViewController.aleph_kw_handler.add_keyword
for keyword in dataset.get("keyword_tags", []):
adder(keyword["val"])
... | python | {
"resource": ""
} |
q52129 | dsn | train | def dsn():
"""
Return a libpq connection string using the variables defined in this file.
"""
configs = {'host': host,
'port': port,
'dbname': database,
'user': user,
'password': password}
return ' '.join(['{0}={1}'.format(_[0], _[1]) for _... | python | {
"resource": ""
} |
q52130 | use | train | def use(module=None, decode=None, encode=None):
"""Set the JSON library that should be used, either by specifying a known
module name, or by providing a decode and encode function.
The modules "simplejson", "cjson", and "json" are currently supported for
the ``module`` parameter.
If provided, the ... | python | {
"resource": ""
} |
q52131 | by_issn | train | def by_issn(issn):
"""
Query aleph for records with given `issn`. The lookup is directed to the
NTK's Aleph.
Args:
issn (str): ISSN of the periodical.
Returns:
obj: :class:`Model` instances for each record.
"""
# monkeypatched to allow search in NTK's Aleph
old_url = al... | python | {
"resource": ""
} |
q52132 | Author.parse_author | train | def parse_author(cls, marc):
"""
Parse author from `marc` data.
Args:
marc (obj): :class:`.MARCXMLRecord` instance. See module
:mod:`.marcxml_parser` for details.
Returns:
obj: :class:`Author`.
"""
name = None
code = None
... | python | {
"resource": ""
} |
q52133 | Author.search_by_name | train | def search_by_name(cls, name):
"""
Look for author in NK Aleph authority base by `name`.
Args:
name (str): Author's name.
Yields:
obj: :class:`Author` instances.
"""
records = aleph.downloadRecords(
aleph.searchInAleph("aut", name, Fa... | python | {
"resource": ""
} |
q52134 | read | train | def read(sensor):
"""
distance of object in front of sensor in CM.
"""
import time
import RPi.GPIO as GPIO
# Disable any warning message such as GPIO pins in use
GPIO.setwarnings(False)
# use the values of the GPIO pins, and not the actual pin number
# so if you connect to ... | python | {
"resource": ""
} |
q52135 | _get_file_md5 | train | def _get_file_md5(filename):
"""Compute the md5 checksum of a file"""
md5_data = md5()
with open(filename, 'rb') as f:
for chunk in iter(lambda: f.read(128*md5_data.block_size), b''):
md5_data.update(chunk)
return md5_data.hexdigest() | python | {
"resource": ""
} |
q52136 | check_md5 | train | def check_md5(filename, stored_md5):
"""
Computes the md5 of filename and check if it matches with the supplied
string md5
Input
-----
filename : string
Path to a file.
md5 : string
Known md5 of filename to check against.
"""
computed_md5 = _get_file_md5(filename)
... | python | {
"resource": ""
} |
q52137 | fetch_from_sdr | train | def fetch_from_sdr(folder=data_folder, data='test'):
"""
Download MRS data from SDR
Parameters
----------
folder : str
Full path to a location in which to place the data. Per default this
will be a directory under the user's home `.mrs_data`.
data : str
Which data to downloa... | python | {
"resource": ""
} |
q52138 | singleton | train | def singleton(*args, **kwargs):
'''
a lazy init singleton pattern.
usage:
``` py
@singleton()
class X: ...
```
`args` and `kwargs` will pass to ctor of `X` as args.
'''
def decorator(cls: type) -> Callable[[], object]:
if issubclass(type(cls), _SingletonMetaClassBase)... | python | {
"resource": ""
} |
q52139 | filter_conflicts | train | def filter_conflicts(conflicts_list, fields):
"""Use this function to automatically filter all the entries defined for a
given rule.
Params:
conflicts_list(List[Conflict]): the list of conflicts to filter.
fields(List[str]): fields to filter out, using an accessor syntax of
the ... | python | {
"resource": ""
} |
q52140 | filter_records | train | def filter_records(root, head, update, filters=()):
"""Apply the filters to the records."""
root, head, update = freeze(root), freeze(head), freeze(update)
for filter_ in filters:
root, head, update = filter_(root, head, update)
return thaw(root), thaw(head), thaw(update) | python | {
"resource": ""
} |
q52141 | get_true_false_both | train | def get_true_false_both(query_params, field_name, default):
'''Tries to get and return a valid of true, false, or both from the field
name in the query string, raises a ValidationError for invalid values.'''
valid = ('true', 'false', 'both')
value = query_params.get(field_name, default).lower()
if v... | python | {
"resource": ""
} |
q52142 | OrganizationViewSet.destroy | train | def destroy(self, request, pk=None):
'''For DELETE actions, archive the organization, don't delete.'''
org = self.get_object()
org.archived = True
org.save()
return Response(status=status.HTTP_204_NO_CONTENT) | python | {
"resource": ""
} |
q52143 | OrganizationUsersViewSet.update | train | def update(self, request, pk=None, parent_lookup_organization=None):
'''Add a user to an organization.'''
user = get_object_or_404(User, pk=pk)
org = get_object_or_404(
SeedOrganization, pk=parent_lookup_organization)
self.check_object_permissions(request, org)
org.us... | python | {
"resource": ""
} |
q52144 | TeamPermissionViewSet.create | train | def create(
self, request, parent_lookup_seedteam=None,
parent_lookup_seedteam__organization=None):
'''Add a permission to a team.'''
team = self.check_team_permissions(
request, parent_lookup_seedteam,
parent_lookup_seedteam__organization)
serial... | python | {
"resource": ""
} |
q52145 | TeamPermissionViewSet.destroy | train | def destroy(
self, request, pk=None, parent_lookup_seedteam=None,
parent_lookup_seedteam__organization=None):
'''Remove a permission from a team.'''
self.check_team_permissions(
request, parent_lookup_seedteam,
parent_lookup_seedteam__organization)
... | python | {
"resource": ""
} |
q52146 | TeamUsersViewSet.update | train | def update(
self, request, pk=None, parent_lookup_seedteam=None,
parent_lookup_seedteam__organization=None):
'''Add a user to a team.'''
user = get_object_or_404(User, pk=pk)
team = self.check_team_permissions(
request, parent_lookup_seedteam,
pare... | python | {
"resource": ""
} |
q52147 | UserViewSet.get_queryset | train | def get_queryset(self):
'''We want to still be able to modify archived users, but they
shouldn't show up on list views.
We have an archived query param, where 'true' shows archived, 'false'
omits them, and 'both' shows both.'''
if self.action == 'list':
active = get_... | python | {
"resource": ""
} |
q52148 | UserViewSet.destroy | train | def destroy(self, request, pk=None):
'''For DELETE actions, actually deactivate the user, don't delete.'''
user = self.get_object()
user.is_active = False
user.save()
return Response(status=status.HTTP_204_NO_CONTENT) | python | {
"resource": ""
} |
q52149 | TokenView.post | train | def post(self, request):
'''Create a token, given an email and password. Removes all other
tokens for that user.'''
serializer = CreateTokenSerializer(data=request.data)
serializer.is_valid(raise_exception=True)
email = serializer.validated_data.get('email')
password = s... | python | {
"resource": ""
} |
q52150 | UserPermissionsView.get | train | def get(self, request):
'''Get user information, with a list of permissions for that user.'''
user = request.user
serializer = PermissionsUserSerializer(
instance=user, context={'request': request})
return Response(data=serializer.data) | python | {
"resource": ""
} |
q52151 | week_to_datetime | train | def week_to_datetime(iso_year, iso_week):
"datetime instance for the start of the given ISO year and week"
gregorian = iso_to_gregorian(iso_year, iso_week, 0)
return datetime.datetime.combine(gregorian, datetime.time(0)) | python | {
"resource": ""
} |
q52152 | init | train | def init(name, *args, **kwargs):
"""Instantiate a timeframe from the catalog.
"""
if name in _TIMEFRAME_CATALOG:
if rapport.config.get_int("rapport", "verbosity") >= 2:
print("Initialize timeframe {0}: {1} {2}".format(name, args, kwargs))
try:
return _TIMEFRAME_CATALO... | python | {
"resource": ""
} |
q52153 | isimplementation | train | def isimplementation(obj, interfaces):
"""
Returns `True` if `obj` is a class implementing all of `interfaces` or an
instance of such class.
`interfaces` can be a single :term:`interface` class or an iterable of
interface classes.
"""
if not inspect.isclass(obj):
isimplementation(ob... | python | {
"resource": ""
} |
q52154 | mrc_to_marc | train | def mrc_to_marc(mrc):
"""
Convert MRC data format to MARC XML.
Args:
mrc (str): MRC as string.
Returns:
str: XML with MARC.
"""
# ignore blank lines
lines = [
line
for line in mrc.splitlines()
if line.strip()
]
def split_to_parts(lines):
... | python | {
"resource": ""
} |
q52155 | val_to_mrc | train | def val_to_mrc(code, val):
"""
Convert one single `val` to MRC.
This function may be used for control fields in MARC records.
Args:,
code (str): Code of the field.
val (str): Value of the field.
Returns:
str: Correctly padded MRC line with field.
"""
code = str(cod... | python | {
"resource": ""
} |
q52156 | item_to_mrc | train | def item_to_mrc(code, val):
"""
Convert `val` to MRC, whether it is dict or string.
Args:
code (str): Code of the field.
val (str or dict): Value of the field.
Returns:
list: MRC lines for output template.
"""
if isinstance(val, basestring):
return [val_to_mrc(c... | python | {
"resource": ""
} |
q52157 | ModelResource.initiate | train | def initiate(self):
"""
Initiate the resource retrieving all the asynchronous
information needed to support the IWebResource interface.
"""
def deduce_methods(actions):
self._methods.add(http.Methods.GET)
for action in actions:
method = se... | python | {
"resource": ""
} |
q52158 | private_dir_path | train | def private_dir_path(app_name):
"""Returns the private directory path
:param str app_name: the name of the app
:rtype: str
:returns: directory path
"""
_private_dir_path = os.path.expanduser(click.get_app_dir(
app_name,
force_posix=True, # forces to ~/.tigerhost on Mac and Uni... | python | {
"resource": ""
} |
q52159 | ensure_private_dir_exists | train | def ensure_private_dir_exists(app_name):
"""Ensures that the private directory exists and is a directory.
:param str app_name: the name of the app
"""
path = private_dir_path(app_name)
if not os.path.exists(path):
os.makedirs(path)
else:
if not os.path.isdir(path):
r... | python | {
"resource": ""
} |
q52160 | MessageSending.parse_xml_node | train | def parse_xml_node(self, node):
'''Parse an xml.dom Node object representing a message sending object
into this object.
'''
self._targets = []
for c in node.getElementsByTagNameNS(RTS_NS, 'targets'):
if c.getElementsByTagNameNS(RTS_NS, 'WaitTime'):
ne... | python | {
"resource": ""
} |
q52161 | MessageSending.parse_yaml | train | def parse_yaml(self, y):
'''Parse a YAML speficication of a message sending object into this
object.
'''
self._targets = []
if 'targets' in y:
for t in y['targets']:
if 'waitTime' in t['condition']:
new_target = WaitTime()
... | python | {
"resource": ""
} |
q52162 | MessageSending.save_xml | train | def save_xml(self, doc, element):
'''Save this message_sending object into an xml.dom.Element object.'''
for cond in self._targets:
new_element = doc.createElementNS(RTS_NS, RTS_NS_S + 'targets')
new_element.setAttributeNS(XSI_NS, XSI_NS_S + 'type', 'rtsExt:condition_ext')
... | python | {
"resource": ""
} |
q52163 | MessageSending.to_dict | train | def to_dict(self):
'''Save this message sending object into a dictionary.'''
targets = []
for cond in self._targets:
targets.append(cond.to_dict())
if targets:
return {'targets': targets}
else:
return {} | python | {
"resource": ""
} |
q52164 | Condition.parse_xml_node | train | def parse_xml_node(self, node):
'''Parse an xml.dom Node object representing a condition into this
object.
'''
self.sequence = int(node.getAttributeNS(RTS_NS, 'sequence'))
c = node.getElementsByTagNameNS(RTS_NS, 'TargetComponent')
if c.length != 1:
raise Inva... | python | {
"resource": ""
} |
q52165 | Condition.parse_yaml | train | def parse_yaml(self, y):
'''Parse a YAML specification of a condition into this object.'''
self.sequence = int(y['sequence'])
self.target_component = \
TargetExecutionContext().parse_yaml(y['targetComponent'])
if RTS_EXT_NS_YAML + 'properties' in y:
for p in y... | python | {
"resource": ""
} |
q52166 | Condition.save_xml | train | def save_xml(self, doc, element):
'''Save this condition into an xml.dom.Element object.'''
element.setAttributeNS(RTS_NS, RTS_NS_S + 'sequence',
str(self.sequence))
new_element = doc.createElementNS(RTS_NS, RTS_NS_S + 'TargetComponent')
self.target_compone... | python | {
"resource": ""
} |
q52167 | Condition.to_dict | train | def to_dict(self):
'''Save this condition into a dictionary.'''
d = {'sequence': self.sequence,
'targetComponent': self.target_component.to_dict()}
props = []
for name in self.properties:
p = {'name': name}
if self.properties[name]:
... | python | {
"resource": ""
} |
q52168 | Preceding.parse_xml_node | train | def parse_xml_node(self, node):
'''Parse an xml.dom Node object representing a preceding condition into
this object.
'''
super(Preceding, self).parse_xml_node(node)
p_nodes = node.getElementsByTagNameNS(RTS_NS, 'Preceding')
if p_nodes.length != 1:
raise Inval... | python | {
"resource": ""
} |
q52169 | Preceding.parse_yaml | train | def parse_yaml(self, y):
'''Parse a YAML specification of a preceding condition into this
object.
'''
super(Preceding, self).parse_yaml(y)
c = y['condition']['preceding']
if 'timeout' in c:
self.timeout = int(c['timeout'])
else:
self.timeo... | python | {
"resource": ""
} |
q52170 | Preceding.save_xml | train | def save_xml(self, doc, element):
'''Save this preceding condition into an xml.dom.Element object.'''
super(Preceding, self).save_xml(doc, element)
pre_element = doc.createElementNS(RTS_NS, RTS_NS_S + 'Preceding')
if self.timeout:
pre_element.setAttributeNS(RTS_NS, RTS_NS_S +... | python | {
"resource": ""
} |
q52171 | Preceding.to_dict | train | def to_dict(self):
'''Save this preceding condition into a dictionary.'''
d = super(Preceding, self).to_dict()
e = {}
if self.timeout != 0:
e['timeout'] = self.timeout
if self.sending_timing:
e['sendingTiming'] = self.sending_timing
pcs = []
... | python | {
"resource": ""
} |
q52172 | WaitTime.parse_xml_node | train | def parse_xml_node(self, node):
'''Parse an xml.dom Node object representing a wait_time condition into
this object.
'''
super(WaitTime, self).parse_xml_node(node)
wait_time_nodes = node.getElementsByTagNameNS(RTS_NS, 'WaitTime')
if wait_time_nodes.length != 1:
... | python | {
"resource": ""
} |
q52173 | WaitTime.parse_yaml | train | def parse_yaml(self, y):
'''Parse a YAML specification of a wait_time condition into this
object.
'''
super(WaitTime, self).parse_yaml(y)
self.wait_time = int(y['condition']['waitTime']['waitTime'])
return self | python | {
"resource": ""
} |
q52174 | WaitTime.save_xml | train | def save_xml(self, doc, element):
'''Save this wait_time condition into an xml.dom.Element object.'''
super(WaitTime, self).save_xml(doc, element)
new_element = doc.createElementNS(RTS_NS, RTS_NS_S + 'WaitTime')
new_element.setAttributeNS(RTS_NS, RTS_NS_S + 'waitTime',
st... | python | {
"resource": ""
} |
q52175 | WaitTime.to_dict | train | def to_dict(self):
'''Save this wait_time condition into a dictionary.'''
d = super(WaitTime, self).to_dict()
d['condition'] = {'waitTime': {'waitTime': self.wait_time}}
return d | python | {
"resource": ""
} |
q52176 | ImagesAndUserManager.select_with_main_images | train | def select_with_main_images(self, limit=None, **kwargs):
''' Select all objects with filters passed as kwargs.
For each object it's main image instance is accessible as ``object.main_image``.
Results can be limited using ``limit`` parameter.
Selection is performed using on... | python | {
"resource": ""
} |
q52177 | AttachedImageManager.get_main_for | train | def get_main_for(self, model):
'''
Returns main image for given model
'''
try:
return self.for_model(model).get(is_main=True)
except models.ObjectDoesNotExist:
return None | python | {
"resource": ""
} |
q52178 | Context.increment | train | def increment(method):
"""
Static method used to increment the depth of a context belonging to 'method'
:param function method: A method with a context
:rtype: caliendo.hooks.Context
:returns: The context instance for the method.
"""
if not hasattr(method, '__co... | python | {
"resource": ""
} |
q52179 | CallStack.load | train | def load(self):
"""
Loads the state of a previously saved CallStack to this instance.
"""
s = load_stack(self)
if s:
self.hooks = s.hooks
self.calls = s.calls | python | {
"resource": ""
} |
q52180 | CallStack.set_caller | train | def set_caller(self, caller):
"""
Sets the caller after instantiation.
"""
self.caller = caller.__name__
self.module = inspect.getmodule(caller).__name__
self.load() | python | {
"resource": ""
} |
q52181 | CallStack.add | train | def add(self, call_descriptor):
"""
Adds a CallDescriptor hash to the stack. If there is a hook associated with this call it will be executed and passed an instance of the call descriptor.
:param caliendo.call_descriptor.CallDescriptor call_descriptor: The call descriptor to add to the stack.
... | python | {
"resource": ""
} |
q52182 | CallStack.add_hook | train | def add_hook(self, hook):
"""
Adds a hook to the CallStack. Which will be executed next time.
"""
h = hook.hash
self.hooks[h] = hook | python | {
"resource": ""
} |
q52183 | Agency.full_shutdown | train | def full_shutdown(self, stop_process=False):
'''Terminate all the slave agencies and shutdowns itself.'''
return self._shutdown(full_shutdown=True, stop_process=stop_process,
gentle=True) | python | {
"resource": ""
} |
q52184 | Agency.actually_start_agent | train | def actually_start_agent(self, descriptor, **kwargs):
"""
This method will be run only on the master agency.
"""
factory = IAgentFactory(
applications.lookup_agent(descriptor.type_name))
if factory.standalone:
return self.start_standalone_agent(descriptor,... | python | {
"resource": ""
} |
q52185 | Agency.list_slaves | train | def list_slaves(self):
'''Print information about the slave agencies.'''
resp = []
for slave_id, slave in self._broker.slaves.iteritems():
resp += ["#### Slave %s ####" % slave_id]
table = yield slave.callRemote('list_agents')
resp += [table]
resp ... | python | {
"resource": ""
} |
q52186 | key_required | train | def key_required(group=None, perm=None, keytype=None):
"""
Decorator for key authentication
"""
def decorator(f):
def wrapper(request, *args, **kwargs):
try:
validate_key( request, group, perm, keytype )
return f(request, *args, **kwargs)
e... | python | {
"resource": ""
} |
q52187 | item_meta | train | def item_meta(item_name, name, value, scheme=None):
"""
Adds meta information to an already defined item
of the model being defined.
@param item_name: name of the model item the meta data should be added to.
@type item_name: str or unicode
@param name: name of the meta data class
@type name:... | python | {
"resource": ""
} |
q52188 | attribute | train | def attribute(name, value, getter=None, setter=None, deleter=None,
label=None, desc=None, meta=None):
"""
Annotates a model attribute.
@param name: attribute name, unique for a model.
@type name: str or unicode
@param value: attribute type information.
@type value: implementer of L... | python | {
"resource": ""
} |
q52189 | child | train | def child(name, source=None, view=None, model=None,
enabled=None, fetch=None, browse=None,
label=None, desc=None, meta=None):
"""
Annotate a sub-model to the one being defined.
@param name: item name unique for the model being defined.
@type name: str or unicode
@param source: an... | python | {
"resource": ""
} |
q52190 | action | train | def action(name, factory, label=None, desc=None):
"""
Annotate a model's action.
@param name: the name of the model's action.
@type name: str or unicode
@param factory: a factory to create actions.
@type factory: IActionFactory
@param label: the action label if specified.
@type label: st... | python | {
"resource": ""
} |
q52191 | collection | train | def collection(name, child_names=None, child_source=None,
child_view=None, child_model=None, child_label=None,
child_desc=None, child_meta=None,
label=None, desc=None, meta=None, model_meta=None):
"""
Annotate a dynamic collection of sub-models.
@param name: ... | python | {
"resource": ""
} |
q52192 | AbstractModel.initiate | train | def initiate(self, aspect=None, view=None, parent=None, officer=None):
"""Do not keep any reference to its parent,
this way it can be garbage-collected."""
def got_view(view):
if view is None:
return None
return init(view)
def init(view):
... | python | {
"resource": ""
} |
q52193 | BaseModelItem._create_model | train | def _create_model(self, view_getter=None, source_getters=None,
model_factory=None, officer=None):
"""
Creates a model from the model factory after retrieving
the source and the view. The officer is the IOfficer
FOR THE MODEL TO BE CREATED and NO OFFICER CHECKS ARE P... | python | {
"resource": ""
} |
q52194 | ModelItem.initiate | train | def initiate(self):
"""If the returned deferred is fired with None,
the item will be disabled as if did not exists."""
if not self.model.officer.is_item_allowed(self.model, self._name):
return defer.succeed(None)
if not callable(self._enabled):
d = defer.succeed(... | python | {
"resource": ""
} |
q52195 | UnicodePseudoType._transpose | train | def _transpose(cls, char):
"""Convert unicode char to something similar to it."""
try:
loc = ord(char) - 65
if loc < 0 or loc > 56:
return char
return cls.UNICODE_MAP[loc]
except UnicodeDecodeError:
return char | python | {
"resource": ""
} |
q52196 | PLanguagePseudoType._MapVowels | train | def _MapVowels(cls, string, also_p=False):
"""
Return a copy of ``string`` where characters that exist as keys in
cls._VOWELS have been replaced with the corresponding value. If
also_p is True, this function will also change capital P characters
into a Hebrew character Qof.
... | python | {
"resource": ""
} |
q52197 | SiteCrawler.get_genres | train | def get_genres(self):
"""
Grab genre URLs from iTunes Podcast preview
"""
page = r.get(ITUNES_GENRES_URL)
tree = html.fromstring(page.content)
elements = tree.xpath("//a[@class='top-level-genre']")
return [e.attrib['href'] for e in elements] | python | {
"resource": ""
} |
q52198 | SiteCrawler.generate_urls_for_genre | train | def generate_urls_for_genre(self, genre_url):
"""
Generate URL's for genre
"""
letters = list(string.ascii_uppercase)
urls = []
for letter in letters:
base = '{}&letter={}'.format(genre_url, letter)
page = r.get(base)
tree = html.fromstring(page.content)
elements = tree.x... | python | {
"resource": ""
} |
q52199 | SiteCrawler._find_num_pages | train | def _find_num_pages(self, url):
"""
Find the number of pages paginating a genre's letter URL
"""
def _new_url(i):
return '{}&page={}#page'.format(url, i)
i = 0
j = 2000
k = (i + j) / 2
crawler = SeriesCrawler(_new_url(k))
while i < j:
ids = crawler.get_ids()
# If we... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.