_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q44900 | simple_locking | train | def simple_locking(lock_id, expiration=None):
"""
A decorator that wraps a function in a single lock getting algorithm
"""
def inner_decorator(function):
def wrapper(*args, **kwargs):
try:
# Trying to acquire lock
lock = Lock.acquire_lock(lock_id, expi... | python | {
"resource": ""
} |
q44901 | adjust_locations | train | def adjust_locations(ast_node, first_lineno, first_offset):
"""
Adjust the locations of the ast nodes, offsetting them
to the new lineno and column offset
"""
line_delta = first_lineno - 1
def _fix(node):
if 'lineno' in node._attributes:
lineno = node.lineno
col... | python | {
"resource": ""
} |
q44902 | coalesce_outputs | train | def coalesce_outputs(tree):
"""
Coalesce the constant output expressions
__output__('foo')
__output__('bar')
__output__(baz)
__output__('xyzzy')
into
__output__('foobar', baz, 'xyzzy')
"""
coalesce_all_outputs = True
if coalesce_all_outputs:
sh... | python | {
"resource": ""
} |
q44903 | remove_locations | train | def remove_locations(node):
"""
Removes locations from the given AST tree completely
"""
def fix(node):
if 'lineno' in node._attributes and hasattr(node, 'lineno'):
del node.lineno
if 'col_offset' in node._attributes and hasattr(node, 'col_offset'):
del node.col... | python | {
"resource": ""
} |
q44904 | Character.from_content | train | def from_content(cls, content):
"""Creates an instance of the class from the html content of the character's page.
Parameters
----------
content: :class:`str`
The HTML content of the page.
Returns
-------
:class:`Character`
The character ... | python | {
"resource": ""
} |
q44905 | Character._parse_account_information | train | def _parse_account_information(self, rows):
"""
Parses the character's account information
Parameters
----------
rows: :class:`list` of :class:`bs4.Tag`, optional
A list of all rows contained in the table.
"""
acc_info = {}
if not rows:
... | python | {
"resource": ""
} |
q44906 | Character._parse_achievements | train | def _parse_achievements(self, rows):
"""
Parses the character's displayed achievements
Parameters
----------
rows: :class:`list` of :class:`bs4.Tag`
A list of all rows contained in the table.
"""
for row in rows:
cols = row.find_all('td')
... | python | {
"resource": ""
} |
q44907 | Character._parse_character_information | train | def _parse_character_information(self, rows):
"""
Parses the character's basic information and applies the found values.
Parameters
----------
rows: :class:`list` of :class:`bs4.Tag`
A list of all rows contained in the table.
"""
int_rows = ["level", ... | python | {
"resource": ""
} |
q44908 | Character._parse_deaths | train | def _parse_deaths(self, rows):
"""
Parses the character's recent deaths
Parameters
----------
rows: :class:`list` of :class:`bs4.Tag`
A list of all rows contained in the table.
"""
for row in rows:
cols = row.find_all('td')
dea... | python | {
"resource": ""
} |
q44909 | Character._parse_killer | train | def _parse_killer(cls, killer):
"""Parses a killer into a dictionary.
Parameters
----------
killer: :class:`str`
The killer's raw HTML string.
Returns
-------
:class:`dict`: A dictionary containing the killer's info.
"""
# If the kill... | python | {
"resource": ""
} |
q44910 | Character._parse_other_characters | train | def _parse_other_characters(self, rows):
"""
Parses the character's other visible characters.
Parameters
----------
rows: :class:`list` of :class:`bs4.Tag`
A list of all rows contained in the table.
"""
for row in rows:
cols_raw = row.find... | python | {
"resource": ""
} |
q44911 | Character._parse_tables | train | def _parse_tables(cls, parsed_content):
"""
Parses the information tables contained in a character's page.
Parameters
----------
parsed_content: :class:`bs4.BeautifulSoup`
A :class:`BeautifulSoup` object containing all the content.
Returns
-------
... | python | {
"resource": ""
} |
q44912 | Character._split_list | train | def _split_list(cls, items, separator=",", last_separator=" and "):
"""
Splits a string listing elements into an actual list.
Parameters
----------
items: :class:`str`
A string listing elements.
separator: :class:`str`
The separator between each i... | python | {
"resource": ""
} |
q44913 | create_many_to_many_intermediary_model | train | def create_many_to_many_intermediary_model(field, klass):
"""
Copied from django, but uses FKToVersion for the
'from' field. Fields are also always called 'from' and 'to'
to avoid problems between version combined models.
"""
managed = True
if (isinstance(field.remote_field.to, basestring) a... | python | {
"resource": ""
} |
q44914 | FKToVersion.deconstruct | train | def deconstruct(self):
"""
FK to version always points to a version table
"""
name, path, args, kwargs = super(FKToVersion, self).deconstruct()
if not kwargs['to'].endswith('_version'):
kwargs['to'] = '{0}_version'.format(kwargs['to'])
return name, path, args,... | python | {
"resource": ""
} |
q44915 | M2MFromVersion.update_rel_to | train | def update_rel_to(self, klass):
"""
If we have a string for a model, see if we know about it yet,
if so use it directly otherwise take the lazy approach.
This check is needed because this is called before
the main M2M field contribute to class is called.
"""
if i... | python | {
"resource": ""
} |
q44916 | M2MFromVersion.contribute_to_class | train | def contribute_to_class(self, cls, name):
"""
Because django doesn't give us a nice way to provide
a through table without losing functionality. We have to
provide our own through table creation that uses the
FKToVersion field to be used for the from field.
"""
s... | python | {
"resource": ""
} |
q44917 | Bucket.metas | train | def metas(self, prefix=None, limit=None, delimiter=None):
"""
RETURN THE METADATA DESCRIPTORS FOR EACH KEY
"""
limit = coalesce(limit, TOO_MANY_KEYS)
keys = self.bucket.list(prefix=prefix, delimiter=delimiter)
prefix_len = len(prefix)
output = []
for i, k ... | python | {
"resource": ""
} |
q44918 | make_middleware | train | def make_middleware(app=None, *args, **kw):
""" Given an app, return that app wrapped in RaptorizeMiddleware """
app = RaptorizeMiddleware(app, *args, **kw)
return app | python | {
"resource": ""
} |
q44919 | RaptorizeMiddleware.should_raptorize | train | def should_raptorize(self, req, resp):
""" Determine if this request should be raptorized. Boolean. """
if resp.status != "200 OK":
return False
content_type = resp.headers.get('Content-Type', 'text/plain').lower()
if not 'html' in content_type:
return False
... | python | {
"resource": ""
} |
q44920 | bind | train | def bind(context, block=False):
"""
Given the context, returns a decorator wrapper;
the binder replaces the wrapped func with the
value from the context OR puts this function in
the context with the name.
"""
if block:
def decorate(func):
name = func.__name__.replace('__... | python | {
"resource": ""
} |
q44921 | build_homogeneisation_vehicules | train | def build_homogeneisation_vehicules(temporary_store = None, year = None):
assert temporary_store is not None
"""Compute vehicule numbers by type"""
assert year is not None
# Load data
bdf_survey_collection = SurveyCollection.load(
collection = 'budget_des_familles', config_files_directory =... | python | {
"resource": ""
} |
q44922 | Client.get_projects_list | train | def get_projects_list(self):
""" Get projects list """
try:
result = self._request('/getprojectslist/')
return [TildaProject(**p) for p in result]
except NetworkError:
return [] | python | {
"resource": ""
} |
q44923 | Client.get_project | train | def get_project(self, project_id):
""" Get project info """
try:
result = self._request('/getproject/',
{'projectid': project_id})
return TildaProject(**result)
except NetworkError:
return [] | python | {
"resource": ""
} |
q44924 | Client.get_project_export | train | def get_project_export(self, project_id):
""" Get project info for export """
try:
result = self._request('/getprojectexport/',
{'projectid': project_id})
return TildaProject(**result)
except NetworkError:
return [] | python | {
"resource": ""
} |
q44925 | Client.get_pages_list | train | def get_pages_list(self, project_id):
""" Get pages list """
try:
result = self._request('/getpageslist/',
{'projectid': project_id})
return [TildaPage(**p) for p in result]
except NetworkError:
return [] | python | {
"resource": ""
} |
q44926 | Client.get_page | train | def get_page(self, page_id):
""" Get short page info and body html code """
try:
result = self._request('/getpage/',
{'pageid': page_id})
return TildaPage(**result)
except NetworkError:
return [] | python | {
"resource": ""
} |
q44927 | Client.get_page_full | train | def get_page_full(self, page_id):
""" Get full page info and full html code """
try:
result = self._request('/getpagefull/',
{'pageid': page_id})
return TildaPage(**result)
except NetworkError:
return [] | python | {
"resource": ""
} |
q44928 | Client.get_page_export | train | def get_page_export(self, page_id):
""" Get short page info for export and body html code """
try:
result = self._request('/getpageexport/',
{'pageid': page_id})
return TildaPage(**result)
except NetworkError:
return [] | python | {
"resource": ""
} |
q44929 | Client.get_page_full_export | train | def get_page_full_export(self, page_id):
""" Get full page info for export and body html code """
try:
result = self._request('/getpagefullexport/',
{'pageid': page_id})
return TildaPage(**result)
except NetworkError:
return ... | python | {
"resource": ""
} |
q44930 | _flatten | train | def _flatten(l):
"""helper to flatten a list of lists
"""
res = []
for sublist in l:
if isinstance(sublist, whaaaaat.Separator):
res.append(sublist)
else:
for item in sublist:
res.append(item)
return res | python | {
"resource": ""
} |
q44931 | read_thrift | train | def read_thrift(file_obj, ttype):
"""Read a thrift structure from the given fo."""
from thrift.transport.TTransport import TFileObjectTransport, TBufferedTransport
starting_pos = file_obj.tell()
# set up the protocol chain
ft = TFileObjectTransport(file_obj)
bufsize = 2 ** 16
# for accelera... | python | {
"resource": ""
} |
q44932 | write_thrift | train | def write_thrift(fobj, thrift):
"""Write binary compact representation of thiftpy structured object
Parameters
----------
fobj: open file-like object (binary mode)
thrift: thriftpy object to write
Returns
-------
Number of bytes written
"""
t0 = fobj.tell()
pout = TCompactP... | python | {
"resource": ""
} |
q44933 | thrift_print | train | def thrift_print(structure, offset=0):
"""
Handy recursive text ouput for thrift structures
"""
if not is_thrift_item(structure):
return str(structure)
s = str(structure.__class__) + '\n'
for key in dir(structure):
if key.startswith('_') or key in ['thrift_spec', 'read', 'write',... | python | {
"resource": ""
} |
q44934 | macho_dependencies_list | train | def macho_dependencies_list(target_path, header_magic=None):
""" Generates a list of libraries the given Mach-O file depends on.
In that list a single library is represented by its "install path": for some
libraries it would be a full file path, and for others it would be a relative
path (sometimes with dyld templ... | python | {
"resource": ""
} |
q44935 | insert_load_command_into_header | train | def insert_load_command_into_header(header, load_command):
""" Inserts the given load command into the header and adjust its size. """
lc, cmd, path = load_command
header.commands.append((lc, cmd, path))
header.header.ncmds += 1
header.changedHeaderSizeBy(lc.cmdsize) | python | {
"resource": ""
} |
q44936 | SignupModelForm.clean_username | train | def clean_username(self):
"""
Validate that the username is alphanumeric and is not already in use.
Also validates that the username is not listed in
ACCOUNTS_FORBIDDEN_USERNAMES list.
"""
try:
get_user_model().objects.get(
username__iexact=sel... | python | {
"resource": ""
} |
q44937 | CustomResponse.get_authenticate_header | train | def get_authenticate_header(self, request):
"""
If a request is unauthenticated, determine the WWW-Authenticate
header to use for 401 responses, if any.
"""
authenticators = self.get_authenticators()
if authenticators:
return authenticators[0].authenticate_hea... | python | {
"resource": ""
} |
q44938 | create_dir | train | def create_dir(dst):
"""create directory if necessary
:param dst:
"""
directory = os.path.dirname(dst)
if directory and not os.path.exists(directory):
os.makedirs(directory) | python | {
"resource": ""
} |
q44939 | Clogger.recompute_table_revnums | train | def recompute_table_revnums(self):
'''
Recomputes the revnums for the csetLog table
by creating a new table, and copying csetLog to
it. The INTEGER PRIMARY KEY in the temp table auto increments
as rows are added.
IMPORTANT: Only call this after acquiring the
... | python | {
"resource": ""
} |
q44940 | getPathOfExecutable | train | def getPathOfExecutable(executable):
"""
Returns the full path of the executable, or None if the executable
can not be found.
"""
exe_paths = os.environ['PATH'].split(':')
for exe_path in exe_paths:
exe_file = os.path.join(exe_path, executable)
if os.path.isfile(exe_file) and os.... | python | {
"resource": ""
} |
q44941 | runCommandReturnOutput | train | def runCommandReturnOutput(cmd):
"""
Runs a shell command and return the stdout and stderr
"""
splits = shlex.split(cmd)
proc = subprocess.Popen(
splits, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = proc.communicate()
if proc.returncode != 0:
raise subproc... | python | {
"resource": ""
} |
q44942 | getYamlDocument | train | def getYamlDocument(filePath):
"""
Return a yaml file's contents as a dictionary
"""
with open(filePath) as stream:
doc = yaml.load(stream)
return doc | python | {
"resource": ""
} |
q44943 | zipLists | train | def zipLists(*lists):
"""
Checks to see if all of the lists are the same length, and throws
an AssertionError otherwise. Returns the zipped lists.
"""
length = len(lists[0])
for i, list_ in enumerate(lists[1:]):
if len(list_) != length:
msg = "List at index {} has length {} ... | python | {
"resource": ""
} |
q44944 | getLinesFromLogFile | train | def getLinesFromLogFile(stream):
"""
Returns all lines written to the passed in stream
"""
stream.flush()
stream.seek(0)
lines = stream.readlines()
return lines | python | {
"resource": ""
} |
q44945 | getFilePathsWithExtensionsInDirectory | train | def getFilePathsWithExtensionsInDirectory(dirTree, patterns, sort=True):
"""
Returns all file paths that match any one of patterns in a
file tree with its root at dirTree. Sorts the paths by default.
"""
filePaths = []
for root, dirs, files in os.walk(dirTree):
for filePath in files:
... | python | {
"resource": ""
} |
q44946 | performInDirectory | train | def performInDirectory(dirPath):
"""
Change the current working directory to dirPath before performing
an operation, then restore the original working directory after
"""
originalDirectoryPath = os.getcwd()
try:
os.chdir(dirPath)
yield
finally:
os.chdir(originalDirect... | python | {
"resource": ""
} |
q44947 | Par2File.filenames | train | def filenames(self):
"""Returns the filenames that this par2 file repairs."""
return [p.name for p in self.packets if isinstance(p, FileDescriptionPacket)] | python | {
"resource": ""
} |
q44948 | Domain._set_slots_to_null | train | def _set_slots_to_null(self, cls):
"""
WHY ARE SLOTS NOT ACCESIBLE UNTIL WE ASSIGN TO THEM?
"""
if hasattr(cls, "__slots__"):
for s in cls.__slots__:
self.__setattr__(s, Null)
for b in cls.__bases__:
self._set_slots_to_null(b) | python | {
"resource": ""
} |
q44949 | main | train | def main():
"""Play Conway's Game of Life on the terminal."""
def die((x, y)):
"""Pretend any out-of-bounds cell is dead."""
if 0 <= x < width and 0 <= y < height:
return x, y
LOAD_FACTOR = 9 # Smaller means more crowded.
NUDGING_LOAD_FACTOR = LOAD_FACTOR * 3 # Smaller mea... | python | {
"resource": ""
} |
q44950 | cell_strings | train | def cell_strings(term):
"""Return the strings that represent each possible living cell state.
Return the most colorful ones the terminal supports.
"""
num_colors = term.number_of_colors
if num_colors >= 16:
funcs = term.on_bright_red, term.on_bright_green, term.on_bright_cyan
elif num_... | python | {
"resource": ""
} |
q44951 | random_board | train | def random_board(max_x, max_y, load_factor):
"""Return a random board with given max x and y coords."""
return dict(((randint(0, max_x), randint(0, max_y)), 0) for _ in
xrange(int(max_x * max_y / load_factor))) | python | {
"resource": ""
} |
q44952 | clear | train | def clear(board, term, height):
"""Clear the droppings of the given board."""
for y in xrange(height):
print term.move(y, 0) + term.clear_eol, | python | {
"resource": ""
} |
q44953 | draw | train | def draw(board, term, cells):
"""Draw a board to the terminal."""
for (x, y), state in board.iteritems():
with term.location(x, y):
print cells[state], | python | {
"resource": ""
} |
q44954 | next_board | train | def next_board(board, wrap):
"""Given a board, return the board one interation later.
Adapted from Jack Diedrich's implementation from his 2012 PyCon talk "Stop
Writing Classes"
:arg wrap: A callable which takes a point and transforms it, for example
to wrap to the other edge of the screen. Re... | python | {
"resource": ""
} |
q44955 | BoredomDetector.is_bored_of | train | def is_bored_of(self, board):
"""Return whether the simulation is probably in a loop.
This is a stochastic guess. Basically, it detects whether the
simulation has had the same number of cells a lot lately. May have
false positives (like if you just have a screen full of gliders) or
... | python | {
"resource": ""
} |
q44956 | Queue.push | train | def push(self, value):
"""
SNEAK value TO FRONT OF THE QUEUE
"""
if self.closed and not self.allow_add_after_close:
Log.error("Do not push to closed queue")
with self.lock:
self._wait_for_queue_space()
if not self.closed:
self.... | python | {
"resource": ""
} |
q44957 | Queue._wait_for_queue_space | train | def _wait_for_queue_space(self, timeout=DEFAULT_WAIT_TIME):
"""
EXPECT THE self.lock TO BE HAD, WAITS FOR self.queue TO HAVE A LITTLE SPACE
"""
wait_time = 5
(DEBUG and len(self.queue) > 1 * 1000 * 1000) and Log.warning("Queue {{name}} has over a million items")
now = t... | python | {
"resource": ""
} |
q44958 | PriorityQueue.pop | train | def pop(self, till=None, priority=None):
"""
WAIT FOR NEXT ITEM ON THE QUEUE
RETURN THREAD_STOP IF QUEUE IS CLOSED
RETURN None IF till IS REACHED AND QUEUE IS STILL EMPTY
:param till: A `Signal` to stop waiting and return None
:return: A value, or a THREAD_STOP or None... | python | {
"resource": ""
} |
q44959 | Random.weight | train | def weight(weights):
"""
RETURN RANDOM INDEX INTO WEIGHT ARRAY, GIVEN WEIGHTS
"""
total = sum(weights)
p = SEED.random()
acc = 0
for i, w in enumerate(weights):
acc += w / total
if p < acc:
return i
return len(weigh... | python | {
"resource": ""
} |
q44960 | AESCipher.cipher_block | train | def cipher_block (self, state):
"""Perform AES block cipher on input"""
# PKCS7 Padding
state=state+[16-len(state)]*(16-len(state))# Fails test if it changes the input with +=
self._add_round_key(state, 0)
for i in range(1, self._Nr):
self._sub_bytes(state)
... | python | {
"resource": ""
} |
q44961 | AESCipher.decipher_block | train | def decipher_block (self, state):
"""Perform AES block decipher on input"""
if len(state) != 16:
Log.error(u"Expecting block of 16")
self._add_round_key(state, self._Nr)
for i in range(self._Nr - 1, 0, -1):
self._i_shift_rows(state)
self._i_sub_bytes... | python | {
"resource": ""
} |
q44962 | path | train | def path(name):
"""Print path to root."""
try:
coll = Collection.query.filter(Collection.name == name).one()
tr = LeftAligned(
traverse=CollTraversalPathToRoot(coll.path_to_root().all()))
click.echo(tr(coll))
except NoResultFound:
raise click.UsageError('Collectio... | python | {
"resource": ""
} |
q44963 | create | train | def create(name, dry_run, verbose, query=None, parent=None):
"""Create new collection."""
if parent is not None:
parent = Collection.query.filter_by(name=parent).one().id
collection = Collection(name=name, dbquery=query, parent_id=parent)
db.session.add(collection)
if verbose:
click.... | python | {
"resource": ""
} |
q44964 | delete | train | def delete(name, dry_run, verbose):
"""Delete a collection."""
collection = Collection.query.filter_by(name=name).one()
if verbose:
tr = LeftAligned(traverse=AttributeTraversal())
click.secho(tr(collection), fg='red')
db.session.delete(collection) | python | {
"resource": ""
} |
q44965 | query | train | def query(name):
"""Print the collection query."""
collection = Collection.query.filter_by(name=name).one()
click.echo(collection.dbquery) | python | {
"resource": ""
} |
q44966 | StyleMixin.get_text | train | def get_text(self, node):
"""Get node text representation."""
return click.style(
repr(node), fg='green' if node.level > 1 else 'red'
) | python | {
"resource": ""
} |
q44967 | cli_char | train | def cli_char(name, tibiadata, json):
"""Displays information about a Tibia character."""
name = " ".join(name)
char = _fetch_and_parse(Character.get_url, Character.from_content,
Character.get_url_tibiadata, Character.from_tibiadata,
tibiadata, name)
... | python | {
"resource": ""
} |
q44968 | cli_guild | train | def cli_guild(name, tibiadata, json):
"""Displays information about a Tibia guild."""
name = " ".join(name)
guild = _fetch_and_parse(Guild.get_url, Guild.from_content,
Guild.get_url_tibiadata, Guild.from_tibiadata,
tibiadata, name)
if json and gu... | python | {
"resource": ""
} |
q44969 | cli_guilds | train | def cli_guilds(world, tibiadata, json):
"""Displays the list of guilds for a specific world"""
world = " ".join(world)
guilds = _fetch_and_parse(ListedGuild.get_world_list_url, ListedGuild.list_from_content,
ListedGuild.get_world_list_url_tibiadata, ListedGuild.list_from_tibiad... | python | {
"resource": ""
} |
q44970 | _unseen_event_ids | train | def _unseen_event_ids(medium):
"""
Return all events that have not been seen on this medium.
"""
query = '''
SELECT event.id
FROM entity_event_event AS event
LEFT OUTER JOIN (SELECT *
FROM entity_event_eventseen AS seen
WHERE seen.medium_... | python | {
"resource": ""
} |
q44971 | EventQuerySet.mark_seen | train | def mark_seen(self, medium):
"""
Creates EventSeen objects for the provided medium for every event
in the queryset.
Creating these EventSeen objects ensures they will not be
returned when passing ``seen=False`` to any of the medium
event retrieval functions, ``events``, ... | python | {
"resource": ""
} |
q44972 | EventManager.create_event | train | def create_event(self, actors=None, ignore_duplicates=False, **kwargs):
"""
Create events with actors.
This method can be used in place of ``Event.objects.create``
to create events, and the appropriate actors. It takes all the
same keywords as ``Event.objects.create`` for the ev... | python | {
"resource": ""
} |
q44973 | FormView.get_object_url | train | def get_object_url(self):
"""
Returns the url where this object can be edited.
"""
if self.kwargs.get(self.slug_url_kwarg, False) == \
unicode(getattr(self.object, self.slug_field, "")) \
and not self.force_add:
url = self.request.buil... | python | {
"resource": ""
} |
q44974 | FormView.get_cancel_url | train | def get_cancel_url(self):
"""
Returns the cancel url for this view.
if `self.cancel_view` is None the current url will
be used. Otherwise the get_view_url will be called with
the current bundle using `self.cancel_view` as the
view name.
"""
if self.cancel... | python | {
"resource": ""
} |
q44975 | FormView.get_success_url | train | def get_success_url(self):
"""
Returns the url to redirect to after a successful update.
if `self.redirect_to_view` is None the current url will
be used. Otherwise the get_view_url will be called
on the current bundle using `self.redirect_to_view` as the
view name. If th... | python | {
"resource": ""
} |
q44976 | FormView.get_object | train | def get_object(self):
"""
Get the object we are working with. Makes sure
get_queryset is called even when in add mode.
"""
if not self.force_add and self.kwargs.get(self.slug_url_kwarg, None):
return super(FormView, self).get_object()
else:
self.q... | python | {
"resource": ""
} |
q44977 | FormView.get_fieldsets | train | def get_fieldsets(self):
"""
Hook for specifying fieldsets. If 'self.fieldsets' is
empty this will default to include all the fields in
the form with a title of None.
"""
if self.fieldsets:
return self.fieldsets
form_class = self.get_form_class()
... | python | {
"resource": ""
} |
q44978 | FormView.get_form_class | train | def get_form_class(self):
"""
Returns the form class to use in this view. Makes
sure that the form_field_callback is set to use
the `formfield_for_dbfield` method and that any
custom form classes are prepared by the
`customize_form_widgets` method.
"""
if ... | python | {
"resource": ""
} |
q44979 | FormView.save_form | train | def save_form(self, form):
"""
Save a valid form. If there is a parent attribute,
this will make sure that the parent object is added
to the saved object. Either as a relationship before
saving or in the case of many to many relations after
saving. Any forced instance val... | python | {
"resource": ""
} |
q44980 | FormView.save_formsets | train | def save_formsets(self, form, formsets, auto_tags=None):
"""
Hook for saving formsets. Loops through
all the given formsets and calls their
save method.
"""
for formset in formsets.values():
tag_handler.set_auto_tags_for_formset(formset, auto_tags)
... | python | {
"resource": ""
} |
q44981 | FormView.form_valid | train | def form_valid(self, form, formsets):
"""
Response for valid form. In one transaction this will
save the current form and formsets, log the action
and message the user.
Returns the results of calling the `success_response` method.
"""
# check if it's a new object... | python | {
"resource": ""
} |
q44982 | FormView.success_response | train | def success_response(self, message=None):
"""
Returns a 'render redirect' to the result of the
`get_success_url` method.
"""
return self.render(self.request,
redirect_url=self.get_success_url(),
obj=self.object,
... | python | {
"resource": ""
} |
q44983 | FormView.render | train | def render(self, request, **kwargs):
"""
Renders this view. Adds cancel_url to the context.
If the request get parameters contains 'popup' then
the `render_type` is set to 'popup'.
"""
if request.GET.get('popup'):
self.render_type = 'popup'
kwargs[... | python | {
"resource": ""
} |
q44984 | FormView.get | train | def get(self, request, *args, **kwargs):
"""
Method for handling GET requests.
Calls the `render` method with the following
items in context.
* **adminForm** - The main form wrapped in an helper class \
that helps with fieldset iteration and html attributes.
* **... | python | {
"resource": ""
} |
q44985 | FormView.post | train | def post(self, request, *args, **kwargs):
"""
Method for handling POST requests.
Validates submitted form and
formsets. Saves if valid, re displays
page with errors if invalid.
"""
self.object = self.get_object()
form_class = self.get_form_class()
... | python | {
"resource": ""
} |
q44986 | PreviewWrapper.get_preview_kwargs | train | def get_preview_kwargs(self, **kwargs):
"""
Gets the url keyword arguments to pass to the
`preview_view` callable. If the `pass_through_kwarg`
attribute is set the value of `pass_through_attr` will
be looked up on the object.
So if you are previewing an item Obj<id=2> an... | python | {
"resource": ""
} |
q44987 | PreviewWrapper.get | train | def get(self, request, *args, **kwargs):
"""
Method for handling GET requests.
Sets the renderer to be a RenderResponse instance
that uses `default_template` as the template.
The `preview_view` callable is called and passed to `render`
method as the data keyword argument... | python | {
"resource": ""
} |
q44988 | VersionsList.revert | train | def revert(self, version, url):
"""
Set the given version to be the active draft.
This is done by calling the object's `make_draft` method.
Logs the revert as a 'save' and messages the user.
"""
message = "Draft replaced with %s version. This revert has not been published... | python | {
"resource": ""
} |
q44989 | VersionsList.delete | train | def delete(self, version):
"""
Deletes the given version, not the object itself.
No log entry is generated but the user is notified
with a message.
"""
# Shouldn't be able to delete live or draft version
if version.state != version.DRAFT and \
... | python | {
"resource": ""
} |
q44990 | VersionsList.post | train | def post(self, request, *args, **kwargs):
"""
Method for handling POST requests.
Expects the 'vid' of the version to act on
to be passed as in the POST variable 'version'.
If a POST variable 'revert' is present this will
call the revert method and then return a 'render
... | python | {
"resource": ""
} |
q44991 | Collection.validate_parent_id | train | def validate_parent_id(self, key, parent_id):
"""Parent has to be different from itself."""
id_ = getattr(self, 'id', None)
if id_ is not None and parent_id is not None:
assert id_ != parent_id, 'Can not be attached to itself.'
return parent_id | python | {
"resource": ""
} |
q44992 | _to_encoded_string | train | def _to_encoded_string(o):
"""
Build an encoded string suitable for use as a URL component. This includes double-escaping the string to
avoid issues with escaped backslash characters being automatically converted by WSGI or, in some cases
such as default Apache servers, blocked entirely.
:param o: ... | python | {
"resource": ""
} |
q44993 | MeteorClient.list_observatories | train | def list_observatories(self):
"""
Get the IDs of all observatories with have stored observations on this server.
:return: a sequence of strings containing observatories IDs
"""
response = requests.get(self.base_url + '/obstories').text
return safe_load(response) | python | {
"resource": ""
} |
q44994 | MeteorClient.get_observatory_status | train | def get_observatory_status(self, observatory_id, status_time=None):
"""
Get details of the specified camera's status
:param string observatory_id:
a observatory ID, as returned by list_observatories()
:param float status_time:
optional, if specified attempts to g... | python | {
"resource": ""
} |
q44995 | Scheme.build_defaults | train | def build_defaults(self):
"""Build a dictionary of default values from the `Scheme`.
Returns:
dict: The default configurations as set by the `Scheme`.
Raises:
errors.InvalidSchemeError: The `Scheme` does not contain
valid options.
"""
def... | python | {
"resource": ""
} |
q44996 | Scheme.flatten | train | def flatten(self):
"""Flatten the scheme into a dictionary where the keys are
compound 'dot' notation keys, and the values are the corresponding
options.
Returns:
dict: The flattened `Scheme`.
"""
if self._flat is None:
flat = {}
for a... | python | {
"resource": ""
} |
q44997 | Scheme.validate | train | def validate(self, config):
"""Validate the given config against the `Scheme`.
Args:
config (dict): The configuration to validate.
Raises:
errors.SchemeValidationError: The configuration fails
validation against the `Schema`.
"""
if not i... | python | {
"resource": ""
} |
q44998 | Option.cast | train | def cast(self, value):
"""Cast a value to the type required by the option, if one is set.
This is used to cast the string values gathered from environment
variable into their required type.
Args:
value: The value to cast.
Returns:
The value casted to th... | python | {
"resource": ""
} |
q44999 | medianscore | train | def medianscore(inlist):
"""
Returns the 'middle' score of the passed list. If there is an even
number of scores, the mean of the 2 middle scores is returned.
Usage: lmedianscore(inlist)
"""
newlist = copy.deepcopy(inlist)
newlist.sort()
if len(newlist) % 2 == 0: # if even number of scores, avera... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.