_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q53500 | InputController.set_el | train | def set_el(cls, el, value):
"""
Set given `el` tag element to `value`.
Automatically choose proper method to set the `value` based on the type
of the `el`.
Args:
el (obj): Element reference to the input you want to convert to
typeahead.
v... | python | {
"resource": ""
} |
q53501 | InputController.get_el | train | def get_el(el):
"""
Get value of given `el` tag element.
Automatically choose proper method to set the `value` based on the type
of the `el`.
Args:
el (obj): Element reference to the input you want to convert to
typeahead.
Returns:
... | python | {
"resource": ""
} |
q53502 | SceneMembers.create_scene_member | train | async def create_scene_member(self, shade_position, scene_id, shade_id):
"""Adds a shade to an existing scene"""
data = {
ATTR_SCENE_MEMBER: {
ATTR_POSITION_DATA: shade_position,
ATTR_SCENE_ID: scene_id,
ATTR_SHADE_ID: shade_id,
}
... | python | {
"resource": ""
} |
q53503 | SceneMembers.delete_shade_from_scene | train | async def delete_shade_from_scene(self, shade_id, scene_id):
"""Delete a shade from a scene."""
return await self.request.delete(
self._base_path, params={ATTR_SCENE_ID: scene_id, ATTR_SHADE_ID: shade_id}
) | python | {
"resource": ""
} |
q53504 | LogView.show | train | def show(cls, msg=None):
"""
Show the log interface on the page.
"""
if msg:
cls.add(msg)
cls.overlay.show()
cls.overlay.el.bind("click", lambda x: cls.hide())
cls.el.style.display = "block"
cls.bind() | python | {
"resource": ""
} |
q53505 | LogView.hide | train | def hide(cls):
"""
Hide the log interface.
"""
cls.el.style.display = "none"
cls.overlay.hide()
cls.bind() | python | {
"resource": ""
} |
q53506 | main | train | def main():
"""Command-line entry point for running the view server."""
import getopt
from . import __version__ as VERSION
try:
option_list, argument_list = getopt.gnu_getopt(
sys.argv[1:], 'h',
['version', 'help', 'json-module=', 'debug', 'log-file='])
message ... | python | {
"resource": ""
} |
q53507 | KeywordAdder.set_kw_typeahead_input | train | def set_kw_typeahead_input(cls):
"""
Map the typeahead input to remote dataset.
"""
# get reference to parent element
parent_id = cls.intput_el.parent.id
if "typeahead" not in parent_id.lower():
parent_id = cls.intput_el.parent.parent.id
window.make_k... | python | {
"resource": ""
} |
q53508 | Participant.parse_xml_node | train | def parse_xml_node(self, node):
'''Parse an xml.dom Node object representing a participant into this
object.
'''
if node.getElementsByTagNameNS(RTS_NS, 'Participant').length != 1:
raise InvalidParticipantNodeError
self.target_component = TargetComponent().parse_xml_n... | python | {
"resource": ""
} |
q53509 | Participant.parse_yaml_node | train | def parse_yaml_node(self, y):
'''Parse a YAML specification of a participant into this object.'''
if 'participant' not in y:
raise InvalidParticipantNodeError
self.target_component = TargetComponent().parse_yaml_node(y['participant'])
return self | python | {
"resource": ""
} |
q53510 | Participant.save_xml | train | def save_xml(self, doc, element):
'''Save this participant into an xml.dom.Element object.'''
new_element = doc.createElementNS(RTS_NS, RTS_NS_S + 'Participant')
self.target_component.save_xml(doc, new_element)
element.appendChild(new_element) | python | {
"resource": ""
} |
q53511 | WebmailLoginView.form_valid | train | def form_valid(self, form):
"""
This method is executed when submitted form is valid.
It redirects to ``success_url`` if no ``next`` url is provided.
Otherwise it redirects to ``next`` url.
:param form: ``forms.Form`` instance
:return: ``HttpResponse`` instance
... | python | {
"resource": ""
} |
q53512 | GfxPrimitives.draw_line | train | def draw_line(self, x1, y1, x2, y2, color):
"""Draw a line.
Args:
x1 (int): The x coordinate of the start of the line.
y1 (int): The y coordinate of the start of the line.
x2 (int): The x coordinate of the end of the line.
y2 (int): The y coordinate of th... | python | {
"resource": ""
} |
q53513 | Site.cleanup | train | def cleanup(self):
'''
Cleans up existing connections giving them time to finish the currect
request.
'''
self.debug("Cleanup called on Site.")
if not self.connections:
return defer.succeed(None)
self.debug("Waiting for all the connections to close.")
... | python | {
"resource": ""
} |
q53514 | Site.disconnectAll | train | def disconnectAll(self):
'''
Disconnect all the clients NOW, regardless if they process a request
at the moment.
'''
if not self.connections:
return defer.succeed(None)
result = self._notifier.wait('idle')
for connection in self.connections:
... | python | {
"resource": ""
} |
q53515 | Server.negotiate_forced_aspect | train | def negotiate_forced_aspect(self, options, accepts):
"""Order specified options in function of the specified
accept priorities."""
if not options:
return None
priorities = {}
for i, o in enumerate(options):
p = accepts.get(o, None)
if p is No... | python | {
"resource": ""
} |
q53516 | scan | train | def scan(queue, lock=None, ttl=None, max_tries=None, ignore_down=False,
no_open=False, generator=FSQScanGenerator, host=False, hosts=None):
'''Given a queue, generate a list of files in that queue, and pass it to
FSQScanGenerator for iteration. The generator kwarg is provided here
as a means... | python | {
"resource": ""
} |
q53517 | demo | train | def demo(ctx, reset=False):
'''Set up the demo environment and run the server'''
if reset:
rmdb(ctx)
ctx.run('demo check', pty=True)
ctx.run('demo loaddemo', pty=True)
ctx.run('demo runserver', pty=True) | python | {
"resource": ""
} |
q53518 | delay | train | def delay(effect, result=None, delay=0.001):
"""
Returns a new effect that will delay the execution
of the given effect and return the specified result right away.
@param effect: the effect to delay
@type effect: callable
@param result: the value to return right away
@type result: Any
... | python | {
"resource": ""
} |
q53519 | select_param | train | def select_param(param_name, default=None):
"""
Returns an effect that drops the current value and returns the parameter
with the specified name instead, or the specified default value if the
parameter is not specified.
"""
def select_param(_value, _context, **params):
return params.pop... | python | {
"resource": ""
} |
q53520 | local_ref | train | def local_ref(*parts):
"""
Returns an effect that returns a local reference constructed from the
given factory arguments joined with the context's 'key'.
This is a reference builder with a specified base location:
Using getter.local_ref("some", "base") to get a value with context key
"toto" wil... | python | {
"resource": ""
} |
q53521 | context_value | train | def context_value(name):
"""
Returns an effect that drops the current value, and replaces it with
the value from the context with the given name.
"""
def context_value(_value, context, **_params):
return defer.succeed(context[name])
return context_value | python | {
"resource": ""
} |
q53522 | subroutine | train | def subroutine(*effects):
"""
Returns an effect performing a list of effects. The value passed to each
effect is a result of the previous effect.
"""
def subroutine(value, context, *args, **kwargs):
d = defer.succeed(value)
for effect in effects:
d.addCallback(effect, co... | python | {
"resource": ""
} |
q53523 | run | train | def run(args):
"""Main OSLOM runner function."""
# Create an OSLOM runner with a temporary working directory
oslom_runner = OslomRunner(tempfile.mkdtemp())
# (Re-)create OSLOM output directory
shutil.rmtree(args.oslom_output, ignore_errors=True)
os.makedirs(args.oslom_output)
# Read edges ... | python | {
"resource": ""
} |
q53524 | run_in_memory | train | def run_in_memory(args, edges):
"""Run OSLOM with an in-memory list of edges, return in-memory results."""
# Create an OSLOM runner with a temporary working directory
oslom_runner = OslomRunner(tempfile.mkdtemp())
# Write temporary edges file with re-mapped Ids
logging.info("writing temporary edges... | python | {
"resource": ""
} |
q53525 | main | train | def main():
"""Main interface function for the command line."""
# Setup logging for the command line
name = os.path.splitext(os.path.basename(__file__))[0]
logging.basicConfig(
format="%(asctime)s [%(process)s] %(levelname)s {} - %(message)s".format(name),
level=logging.INFO)
# Prog... | python | {
"resource": ""
} |
q53526 | IdRemapper.get_int_id | train | def get_int_id(self, str_id):
"""Get a unique 32 bits signed integer for the given string Id."""
if not str_id in self.mapping:
if self.curr_id == IdRemapper.INT_MAX:
return None # No more 32 bits signed integers available
self.mapping[str_id] = self.curr_id
... | python | {
"resource": ""
} |
q53527 | IdRemapper.store_mapping | train | def store_mapping(self, path):
"""Store the current Id mappings into a TSV file."""
with open(path, "w") as writer:
for key, value in self.mapping.iteritems():
writer.write("{}\t{}\n".format(key, value)) | python | {
"resource": ""
} |
q53528 | OslomRunner.store_edges | train | def store_edges(self, edges):
"""Store the temporary network edges input file with re-mapped Ids."""
with open(self.get_path(OslomRunner.TMP_EDGES_FILE), "w") as writer:
for edge in edges:
writer.write("{}\t{}\t{}\n".format(
self.id_remapper.get_int_id(edg... | python | {
"resource": ""
} |
q53529 | OslomRunner.run | train | def run(self, oslom_exec, oslom_args, log_filename):
"""Run OSLOM and wait for the process to finish."""
args = [oslom_exec, "-f", self.get_path(OslomRunner.TMP_EDGES_FILE)]
args.extend(oslom_args)
with open(log_filename, "w") as logwriter:
start_time = time.time()
... | python | {
"resource": ""
} |
q53530 | OslomRunner.read_clusters | train | def read_clusters(self, min_cluster_size):
"""Read and parse OSLOM clusters output file."""
num_found = 0
clusters = []
with open(self.get_path(OslomRunner.OUTPUT_FILE), "r") as reader:
# Read the output file every two lines
for line1, line2 in itertools.izip_long... | python | {
"resource": ""
} |
q53531 | OslomRunner.store_output_files | train | def store_output_files(self, dir_path):
"""Store OSLOM output files to a directory."""
if self.last_result:
for entry in os.listdir(self.last_result["output_dir"]):
path = os.path.join(self.last_result["output_dir"], entry)
if os.path.isfile(path):
... | python | {
"resource": ""
} |
q53532 | GCM.make_request | train | def make_request(self, data, is_json=True):
"""
Makes a HTTP request to GCM servers with the constructed payload
:param data: return value from construct_payload method
:raises GCMMalformedJsonException: if malformed JSON request found
:raises GCMAuthenticationException: if ther... | python | {
"resource": ""
} |
q53533 | GCM.plaintext_request | train | def plaintext_request(self, registration_id, data=None, collapse_key=None,
delay_while_idle=False, time_to_live=None, retries=5, dry_run=False):
"""
Makes a plaintext request to GCM servers
:param registration_id: string of the registration id
:param data: dict... | python | {
"resource": ""
} |
q53534 | GCM.json_request | train | def json_request(self, registration_ids, data=None, collapse_key=None,
delay_while_idle=False, time_to_live=None, retries=5, dry_run=False):
"""
Makes a JSON request to GCM servers
:param registration_ids: list of the registration ids
:param data: dict mapping of ke... | python | {
"resource": ""
} |
q53535 | backup_file | train | def backup_file(*, file, host):
"""
Perform backup action
:param file: Name of the file to be used by the driver
:param host: Corresponding host name associated with file
"""
log.msg("[{host}] Backing up file '{file}'".format(host=host, file=file)) | python | {
"resource": ""
} |
q53536 | ADQuery.search | train | def search(self, base_dn, search_filter, attributes=()):
"""Perform an AD search
:param str base_dn: The base DN to search within
:param str search_filter: The search filter to apply, such as:
*objectClass=person*
:param list attributes: Object attributes to populate, defaults... | python | {
"resource": ""
} |
q53537 | ADQuery._open | train | def _open(self):
"""Bind, use tls"""
try:
self.ldap.start_tls_s()
#pylint: disable=no-member
except ldap.CONNECT_ERROR:
#pylint: enable=no-member
logging.error('Unable to establish a connection to the LDAP server, ' + \
'please ch... | python | {
"resource": ""
} |
q53538 | DateTime._cast | train | def _cast(self, value, format=None, **opts):
"""Optionally apply a format string."""
if format is not None:
return datetime.strptime(value, format)
return dateutil.parser.parse(value) | python | {
"resource": ""
} |
q53539 | senqueue | train | def senqueue(trg_queue, item_s, *args, **kwargs):
'''Enqueue a string, or string-like object to queue with arbitrary
arguments, senqueue is to enqueue what sprintf is to printf, senqueue
is to vsenqueue what sprintf is to vsprintf.
'''
return vsenqueue(trg_queue, item_s, args, **kwargs) | python | {
"resource": ""
} |
q53540 | vsenqueue | train | def vsenqueue(trg_queue, item_s, args, **kwargs):
'''Enqueue a string, or string-like object to queue with arbitrary
arguments, vsenqueue is to venqueue what vsprintf is to vprintf,
vsenqueue is to senqueue what vsprintf is to sprintf.
'''
charset = kwargs.get('charset', _c.FSQ_CHARSET)
if... | python | {
"resource": ""
} |
q53541 | make_any_items_node | train | def make_any_items_node(rawtext, app, prefixed_name, obj, parent, modname, options):
"""Render a Python sequence as a comma-separated list, with an "or" for the final item.
:param rawtext: Text being replaced with link node.
:param app: Sphinx application context
:param prefixed_name: The dotted Python... | python | {
"resource": ""
} |
q53542 | get_images_filter | train | def get_images_filter():
"""It prints all products with metatada image, and obtain all the
images in all regions.
"""
KEYSTONE = os.environ.get('OS_KEYSTONE')
TENANT_ID = os.environ.get('OS_TENANT_ID')
USERNAME = os.environ.get('OS_USERNAME')
PASSWORD = os.environ.get('OS_PASSWORD')
... | python | {
"resource": ""
} |
q53543 | Rect.enclose_points | train | def enclose_points(points, clip_rect):
"""Return the minimal rectangle enclosing the given set of points
Args:
points (List[Point]): The set of points that the new Rect must enclose.
clip_rect (Rect): A clipping Rect.
Returns:
Rect: A new Rect enclosing the ... | python | {
"resource": ""
} |
q53544 | Rect.has_intersection | train | def has_intersection(self, other):
"""Return whether this rectangle intersects with another rectangle.
Args:
other (Rect): The rectangle to test intersection with.
Returns:
bool: True if there is an intersection, False otherwise.
"""
return bool(lib.SDL_... | python | {
"resource": ""
} |
q53545 | Rect.intersect | train | def intersect(self, other):
"""Calculate the intersection of this rectangle and another rectangle.
Args:
other (Rect): The other rectangle.
Returns:
Rect: The intersection of this rectangle and the given other rectangle, or None if there is no such
inter... | python | {
"resource": ""
} |
q53546 | Rect.union | train | def union(self, other):
"""Calculate the union of this rectangle and another rectangle.
Args:
other (Rect): The other rectangle.
Returns:
Rect: The union of this rectangle and the given other rectangle.
"""
union = Rect()
lib.SDL_UnionRect(self._... | python | {
"resource": ""
} |
q53547 | sanitize_word | train | def sanitize_word(word):
"""
sanitize a word by removing its accents, special characters, etc
"""
# use an unicode string for `unidecode`
if type(word) == str:
try:
word = word.decode()
except AttributeError:
pass # Python3
# remove trailing spaces
w... | python | {
"resource": ""
} |
q53548 | local_list | train | def local_list(timestamps=True):
"""
Return a list of the locally available dictionnaries. Each element is a
tuple of the dictionnary name and its last modification date as a
timestamp.
"""
init_storage()
lst = []
for d in glob(os.path.join(DICTS_PATH, '*.txt')):
name = d.split('... | python | {
"resource": ""
} |
q53549 | get_remote_file | train | def get_remote_file(url):
"""
Wrapper around ``request.get`` which nicely handles connection errors
"""
try:
return requests.get(url)
except requests.exceptions.ConnectionError as e:
print("Connection error!")
print(e.message.reason)
exit(1) | python | {
"resource": ""
} |
q53550 | remote_list | train | def remote_list(timestamps=True):
"""
Return a list of the remotely available dictionnaries. Each element is a
tuple of the dictionnary name and its last modification date as a
timestamp.
"""
r = get_remote_file(DICTS_URL)
lst = []
for f in r.text.split('\n'):
if not f:
... | python | {
"resource": ""
} |
q53551 | update | train | def update(verbose=False):
"""
Update local dictionnaries by downloading the latest version from the
server, if there's one.
"""
local = local_list()
remote = dict(remote_list())
updated = False
for name, date in local:
if name in remote and remote[name] > date:
upd... | python | {
"resource": ""
} |
q53552 | download | train | def download(name, verbose=False):
"""
Download a dictionnary from the remote server into the local cache. Return
the number of new words or -1 on error.
"""
init_storage()
if verbose:
print("Downloading '%s'..." % name)
r = get_remote_file('%s/%s.txt' % (DICTS_URL, name))
if r... | python | {
"resource": ""
} |
q53553 | dpLine.remove | train | def remove(self):
"""Remove duplicate lines from text files"""
num, sp, newfile = 0, "", []
if os.path.isfile(self.filename):
with open(self.filename, "r") as r:
oldfile = r.read().splitlines()
for line in oldfile:
if self.number:
... | python | {
"resource": ""
} |
q53554 | LayoutsManager.get | train | def get(self, layout, default=None):
"""
Returns given layout value.
:param layout: Layout name.
:type layout: unicode
:param default: Default value if layout is not found.
:type default: object
:return: Action.
:rtype: QAction
"""
try:
... | python | {
"resource": ""
} |
q53555 | LayoutsManager.register_layout | train | def register_layout(self, name, layout):
"""
Registers given layout.
:param name: Layout name.
:type name: unicode
:param layout: Layout object.
:type layout: Layout
:return: Method success.
:rtype: bool
"""
if name in self:
r... | python | {
"resource": ""
} |
q53556 | LayoutsManager.unregister_layout | train | def unregister_layout(self, name):
"""
Unregisters given layout.
:param name: Layout name.
:type name: unicode
:param layout: Layout object.
:type layout: Layout
:return: Method success.
:rtype: bool
"""
if not name in self:
r... | python | {
"resource": ""
} |
q53557 | LayoutsManager.restore_layout | train | def restore_layout(self, name, *args):
"""
Restores given layout.
:param name: Layout name.
:type name: unicode
:param \*args: Arguments.
:type \*args: \*
:return: Method success.
:rtype: bool
"""
layout = self.__layouts.get(name)
... | python | {
"resource": ""
} |
q53558 | LayoutsManager.store_layout | train | def store_layout(self, name, *args):
"""
Stores given layout.
:param name: Layout name.
:type name: unicode
:param \*args: Arguments.
:type \*args: \*
:return: Method success.
:rtype: bool
"""
layout = self.__layouts.get(name)
if ... | python | {
"resource": ""
} |
q53559 | LayoutsManager.restore_startup_layout | train | def restore_startup_layout(self):
"""
Restores the startup layout.
:return: Method success.
:rtype: bool
"""
LOGGER.debug("> Restoring startup layout.")
if self.restore_layout(UiConstants.startup_layout):
not self.__restore_geometry_on_layout_change... | python | {
"resource": ""
} |
q53560 | Memory.append_scope | train | def append_scope(self):
"""Create a new scope in the current frame."""
self.stack.current.append(Scope(self.stack.current.current)) | python | {
"resource": ""
} |
q53561 | Memory.pop_scope | train | def pop_scope(self):
"""Delete the current scope in the current scope."""
child_scope = self.stack.current.current.copy()
self.stack.current.pop()
parent_scope = self.stack.current.current.copy()
self.stack.current.current = {
key: child_scope[key] for key in child_sc... | python | {
"resource": ""
} |
q53562 | execute | train | def execute(filename, formatted_name):
"""Renames a file based on the name generated using metadata.
:param str filename: absolute path and filename of original file
:param str formatted_name: absolute path and new filename
"""
if os.path.isfile(formatted_name):
# If the destination exists... | python | {
"resource": ""
} |
q53563 | AssetManagersInterface.deactivate | train | def deactivate(self, asset_manager_id):
"""
Is is only possible to deactivate an asset manager if your client_id is also the client_id that was used
to originally create the asset manager.
:param asset_manager_id:
:return:
"""
self.logger.info('Deactivate Asset M... | python | {
"resource": ""
} |
q53564 | waitForURL | train | def waitForURL(url, max_seconds=None):
"""
Give it a URL. Keep trying to get a HEAD request from it until it works.
If it doesn't work, wait a while and try again
"""
startTime = datetime.now()
while True:
response = None
try:
response = urllib2.urlopen(HEADREQUEST(... | python | {
"resource": ""
} |
q53565 | doWaitWebRequest | train | def doWaitWebRequest(url, method="GET", data=None, headers={}):
"""
Same as doWebRequest, but with built in wait-looping
"""
completed = False
while not completed:
completed = True
try:
response, content = doWebRequest(url, method, data, headers)
except urllib2.U... | python | {
"resource": ""
} |
q53566 | doWebRequest | train | def doWebRequest(url, method="GET", data=None, headers={}):
"""
A urllib2 wrapper to mimic the functionality of http2lib, but with timeout support
"""
# Initialize variables
response = None
content = None
# Find condition that matches request
if method == "HEAD":
request = HEADR... | python | {
"resource": ""
} |
q53567 | sendPREMISEvent | train | def sendPREMISEvent(webRoot, eventType, agentIdentifier, eventDetail,
eventOutcome, eventOutcomeDetail=None, linkObjectList=[],
eventDate=None, debug=False, eventIdentifier=None):
"""
A function to format an event to be uploaded and send it to a particular CODA server
... | python | {
"resource": ""
} |
q53568 | createPREMISEventXML | train | def createPREMISEventXML(eventType, agentIdentifier, eventDetail, eventOutcome,
outcomeDetail=None, eventIdentifier=None,
linkObjectList=[], eventDate=None):
"""
Actually create our PREMIS Event XML
"""
eventXML = etree.Element(PREMIS + "event", nsmap=P... | python | {
"resource": ""
} |
q53569 | deleteQueue | train | def deleteQueue(destinationRoot, queueArk, debug=False):
"""
Delete an entry from the queue
"""
url = urlparse.urljoin(destinationRoot, "APP/queue/" + queueArk + "/")
response, content = doWaitWebRequest(url, "DELETE")
if response.getcode() != 200:
raise Exception(
"Error up... | python | {
"resource": ""
} |
q53570 | updateQueue | train | def updateQueue(destinationRoot, queueDict, debug=False):
"""
With a dictionary that represents a queue entry, update the queue entry with
the values
"""
attrDict = bagatom.AttrDict(queueDict)
url = urlparse.urljoin(destinationRoot, "APP/queue/" + attrDict.ark + "/")
queueXML = bagatom.queu... | python | {
"resource": ""
} |
q53571 | table | train | def table(rows, columns=None, output=None, data_args={}, **kwargs):
"""
Return a formatted string of "list of list" table data.
See: http://pandas.pydata.org/pandas-docs/dev/generated/pandas.DataFrame.html
Examples:
>>> fmt.print([("foo", 1), ("bar", 2)])
0 1
0 foo 1
... | python | {
"resource": ""
} |
q53572 | u_edit | train | def u_edit(*args):
"""
Edits given paths into Umbra.
:param \*args: Arguments.
:type \*args: \*
:return: Definition success.
:rtype: bool
"""
paths = []
for path in args:
if not os.path.exists(path):
continue
paths.append(os.path.abspath(path))
if ... | python | {
"resource": ""
} |
q53573 | _process_exception | train | def _process_exception(e, body, tb):
"""
Process informations about exception and send them thru AMQP.
Args:
e (obj): Exception instance.
body (str): Text which will be sent over AMQP.
tb (obj): Traceback object with informations, which will be put to the
headers.
... | python | {
"resource": ""
} |
q53574 | remote | train | def remote(fn, name=None, types=None):
"""Decorator that adds a remote attribute to a function.
fn -- function being decorated
name -- aliased name of the function, used for remote proxies
types -- a argument type specifier, can be used to ensure
arguments are of the correct type
"""
... | python | {
"resource": ""
} |
q53575 | Dispatch.call | train | def call(self, function, args=(), kwargs={}):
"""Call a method given some args and kwargs.
function -- string containing the method name to call
args -- arguments, either a list or tuple
returns the result of the method.
May raise an exception if the method isn't in the dict.
... | python | {
"resource": ""
} |
q53576 | Dispatch.add | train | def add(self, fn, name=None):
"""Add a function that the dispatcher will know about.
fn -- a callable object
name -- optional alias for the function
"""
if not name:
name = fn.__name__
self.functions[name] = fn | python | {
"resource": ""
} |
q53577 | exit | train | def exit(status=0):
"""
Terminate the program with the given status code.
"""
if status == 0:
lab.io.printf(lab.io.Colours.GREEN, "Done.")
else:
lab.io.printf(lab.io.Colours.RED, "Error {0}".format(status))
sys.exit(status) | python | {
"resource": ""
} |
q53578 | SocketServer.start | train | def start(self):
"""Start the socket server.
The socket server will begin accepting incoming connections.
"""
if self._shutdown:
raise ShutdownError()
self.read_watcher.start()
logger.info("server started listening on {}".format(self.address)... | python | {
"resource": ""
} |
q53579 | SocketServer.shutdown | train | def shutdown(self, reason = ConnectionClosed()):
"""Shutdown the socket server.
The socket server will stop accepting incoming connections.
All connections will be dropped.
"""
if self._shutdown:
raise ShutdownError()
self.stop()
se... | python | {
"resource": ""
} |
q53580 | SocketServer.remove_connection | train | def remove_connection(self, connection):
"""Called by the connections themselves when they have been closed."""
if not self._closing:
self.connections.remove(connection)
logger.debug("removed connection") | python | {
"resource": ""
} |
q53581 | FormatsTree.__initialize_tree | train | def __initialize_tree(self, theme):
"""
Initializes the object formats tree.
:param theme: Theme.
:type theme: dict
"""
for item in sorted(theme):
current_node = self.__root_node
for format in item.split("."):
nodes = [node for no... | python | {
"resource": ""
} |
q53582 | FormatsTree.list_formats | train | def list_formats(self, node, path=(), formats=None):
"""
Lists the object formats in sorted order.
:param node: Root node to start listing the formats from.
:type node: AbstractCompositeNode
:param path: Walked paths.
:type path: tuple
:param formats: Formats.
... | python | {
"resource": ""
} |
q53583 | FormatsTree.get_format | train | def get_format(self, name):
"""
Returns the closest format or closest parent format associated to given name.
:param name: Format name.
:type name: unicode
:return: Format.
:rtype: QTextCharFormat
"""
formats = [format for format in self.list_formats(sel... | python | {
"resource": ""
} |
q53584 | AbstractHighlighter.highlight_text | train | def highlight_text(self, text, start, end):
"""
Highlights given text.
:param text: Text.
:type text: QString
:param start: Text start index.
:type start: int
:param end: Text end index.
:type end: int
:return: Method success.
:rtype: bool... | python | {
"resource": ""
} |
q53585 | DefaultHighlighter.highlight_multiline_block | train | def highlight_multiline_block(self, block, start_pattern, end_pattern, state, format):
"""
Highlights given multiline text block.
:param block: Text block.
:type block: QString
:param pattern: Start regex pattern.
:type pattern: QRegExp
:param pattern: End regex ... | python | {
"resource": ""
} |
q53586 | MultiSelect._clean_data | train | def _clean_data(self, str_value, file_data, obj_value):
"""This overwrite is neccesary for work with multivalues"""
str_value = str_value or None
obj_value = obj_value or None
return (str_value, None, obj_value) | python | {
"resource": ""
} |
q53587 | MultiSelect.as_checks | train | def as_checks(self, tmpl=TMPL, _items=None, **kwargs):
"""Render the field as a series of checkboxes, using the `tmpl`
parameter as the template for each item.
:param tmpl:
HTML template to use for rendering each item.
:param **kwargs:
Named paremeters used to g... | python | {
"resource": ""
} |
q53588 | make_upload_to | train | def make_upload_to(base_path, by_fk_field=None):
"""
Creates ``upload_to`` function that generates hashed paths
for file uploads.
Filename hash is created from instance.pk and current time.
Generated paths consist of:
{base_path}/{optional related field id/value hash}/{hashed filename}.{e... | python | {
"resource": ""
} |
q53589 | BaseFileSystemCleanerCommand._find_files | train | def _find_files(self):
"""Find files recursively in the root path
using provided extensions.
:return: list of absolute file paths
"""
files = []
for ext in self.extensions:
ext_files = util.find_files(self.root, "*" + ext)
log.debug("found {} '*{}... | python | {
"resource": ""
} |
q53590 | BaseFileSystemCleanerCommand._clean_file | train | def _clean_file(self, filename):
"""Clean a file if exists and not in dry run"""
if not os.path.exists(filename):
return
self.announce("removing '{}'".format(filename))
if not self.dry_run:
os.remove(filename) | python | {
"resource": ""
} |
q53591 | BaseFileSystemCleanerCommand._clean_directory | train | def _clean_directory(self, name):
"""Clean a directory if exists and not in dry run"""
if not os.path.exists(name):
return
self.announce(
"removing directory '{}' and all its contents".format(name)
)
if not self.dry_run:
rmtree(name, True) | python | {
"resource": ""
} |
q53592 | CleanPyc.find_compiled_files | train | def find_compiled_files(self):
"""Find compiled Python files recursively in the root path
:return: list of absolute file paths
"""
files = self._find_files()
self.announce(
"found '{}' compiled python files in '{}'".format(
len(files), self.root
... | python | {
"resource": ""
} |
q53593 | CleanJythonClass.find_class_files | train | def find_class_files(self):
"""Find compiled class files recursively in the root path
:return: list of absolute file paths
"""
files = self._find_files()
self.announce(
"found '{}' compiled class files in '{}'".format(
len(files), self.root
... | python | {
"resource": ""
} |
q53594 | CleanAll.clean_egginfo | train | def clean_egginfo(self):
"""Clean .egginfo directory"""
dir_name = os.path.join(self.root, self.get_egginfo_dir())
self._clean_directory(dir_name) | python | {
"resource": ""
} |
q53595 | Zyre.set_header | train | def set_header(self, name, format, *args):
"""
Set node header; these are provided to other nodes during discovery
and come in each ENTER message.
"""
return lib.zyre_set_header(self._as_parameter_, name, format, *args) | python | {
"resource": ""
} |
q53596 | Zyre.gossip_connect | train | def gossip_connect(self, format, *args):
"""
Set-up gossip discovery of other nodes. A node may connect to multiple
other nodes, for redundancy paths. For details of the gossip network
design, see the CZMQ zgossip class.
"""
return lib.zyre_gossip_connect(self._as_parameter_, format, *ar... | python | {
"resource": ""
} |
q53597 | Zyre.gossip_connect_curve | train | def gossip_connect_curve(self, public_key, format, *args):
"""
Set-up gossip discovery with CURVE enabled.
"""
return lib.zyre_gossip_connect_curve(self._as_parameter_, public_key, format, *args) | python | {
"resource": ""
} |
q53598 | Zyre.whisper | train | def whisper(self, peer, msg_p):
"""
Send message to single peer, specified as a UUID string
Destroys message after sending
"""
return lib.zyre_whisper(self._as_parameter_, peer, byref(czmq.zmsg_p.from_param(msg_p))) | python | {
"resource": ""
} |
q53599 | Zyre.shout | train | def shout(self, group, msg_p):
"""
Send message to a named group
Destroys message after sending
"""
return lib.zyre_shout(self._as_parameter_, group, byref(czmq.zmsg_p.from_param(msg_p))) | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.