_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q54800 | lessc | train | def lessc(responsive=False):
"""
Compiles all less files.
This is useful if you are using the Twitter Bootstrap Framework.
"""
local('lessc {0}/static/css/bootstrap.less'
' {0}/static/css/bootstrap.css'.format(settings.PROJECT_NAME))
if responsive:
local('lessc {0}/static/css... | python | {
"resource": ""
} |
q54801 | rebuild | train | def rebuild():
"""
Deletes and re-creates your DB. Needs django-extensions and South.
"""
drop_db()
create_db()
if StrictVersion(django.get_version()) < StrictVersion('1.7'):
local('python{} manage.py syncdb --all --noinput'.format(
PYTHON_VERSION))
local('python{} m... | python | {
"resource": ""
} |
q54802 | _Running.g | train | def g(self, id):
"""
If the given id is known, the numerical representation is returned,
otherwise a new running number is assigned to the id and returned"""
if id not in self._m:
if self.orig_ids:
self._m[id] = id
if self.warn:
... | python | {
"resource": ""
} |
q54803 | TeeFile.flush | train | def flush(self):
"""flushes all file contents to disc"""
for fp in self.files:
fp.flush()
if isinstance(fp, int) or hasattr(fp, "fileno"):
try:
os.fsync(fp)
except OSError:
pass | python | {
"resource": ""
} |
q54804 | creatauth | train | def creatauth(name, homedir):
""" Function create user in linux for group and set homedir. Function return gid and uid."""
uid, gid = [None, None]
# get information about user
command = "id %s" % (name)
data = commands.getstatusoutput(command)
if data[0] > 0:
# create new system user
... | python | {
"resource": ""
} |
q54805 | fetch_libzmq | train | def fetch_libzmq(savedir):
"""download and extract libzmq"""
dest = pjoin(savedir, 'zeromq')
if os.path.exists(dest):
info("already have %s" % dest)
return
path = fetch_archive(savedir, libzmq_url, fname=libzmq, checksum=libzmq_checksum)
tf = tarfile.open(path)
with_version = pjo... | python | {
"resource": ""
} |
q54806 | copy_and_patch_libzmq | train | def copy_and_patch_libzmq(ZMQ, libzmq):
"""copy libzmq into source dir, and patch it if necessary.
This command is necessary prior to running a bdist on Linux or OS X.
"""
if sys.platform.startswith('win'):
return
# copy libzmq into zmq for bdist
local = localpath('zmq',libzmq)
... | python | {
"resource": ""
} |
q54807 | ServerApp.check_size_all | train | def check_size_all(self):
"""
Get size of homedir and update data on the server
"""
result = self.rpc_srv.get_all_account(self.token)
print "debug: %s" % result
for it in result:
size = getFolderSize(it["path"])
result = self.rpc_srv.set_account_si... | python | {
"resource": ""
} |
q54808 | read_output | train | def read_output(filename):
"""
Reads in a Tarquin txt results file and returns a dict of the information
:param filename: The filename to read from
:return:
"""
with open(filename) as fin:
data = fin.read()
metabolite_fits = {}
sections = data.split("\n\n")
# ... | python | {
"resource": ""
} |
q54809 | _parse_args | train | def _parse_args() -> argparse.Namespace:
"""Helper function to create the command-line argument parser for faaspact_verifier. Return the
parsed arguments as a Namespace object if successful. Exits the program if unsuccessful or if
the help message is printed.
"""
description = ('Run pact verifier t... | python | {
"resource": ""
} |
q54810 | MongoDBDataStore._store | train | def _store(self, uid, content, data=None):
"""Store the given dict of content at uid. Nothing returned."""
doc = dict(uid=uid)
if data:
gfs = gridfs.GridFS(self.db)
id = gfs.put(data, encoding='utf-8')
doc.update(data_id=id)
doc.update(content)
... | python | {
"resource": ""
} |
q54811 | MongoDBDataStore._retrieve | train | def _retrieve(self, uid):
"""Return a dict with the contents of the paste, including the raw
data, if any, as the key 'data'. Must pass in uid, not shortid."""
query = dict(uid=uid)
doc = self.db.pastes.find_one(query)
if 'data_id' in doc:
data_id = doc.pop('data_id')... | python | {
"resource": ""
} |
q54812 | MongoDBDataStore.lookup | train | def lookup(self, nick):
"""Looks for the most recent paste by a given nick.
Returns the uid or None"""
query = dict(nick=nick)
order = [('time', pymongo.DESCENDING)]
recs = self.db.pastes.find(query).sort(order).limit(1)
try:
return next(recs)['uid']
e... | python | {
"resource": ""
} |
q54813 | Variable_QPushButton.__set_true_state | train | def __set_true_state(self):
"""
Sets the variable button true state.
"""
LOGGER.debug("> Setting variable QPushButton() to 'True' state.")
self.__state = True
palette = QPalette()
palette.setColor(QPalette.Button, foundations.common.get_first_item(self.__colors)... | python | {
"resource": ""
} |
q54814 | Variable_QPushButton.__set_false_state | train | def __set_false_state(self):
"""
Sets the variable QPushButton true state.
"""
LOGGER.debug("> Setting variable QPushButton() to 'False' state.")
self.__state = False
palette = QPalette()
palette.setColor(QPalette.Button, self.__colors[1])
self.setPalet... | python | {
"resource": ""
} |
q54815 | moneyfmt | train | def moneyfmt(value, places=2, curr='', sep=',', dp='.',
pos='', neg='-', trailneg=''):
"""Convert Decimal to a money formatted string.
places: required number of places after the decimal point
curr: optional currency symbol before the sign (may be blank)
sep: optional grouping sepa... | python | {
"resource": ""
} |
q54816 | is_symbols_pair_complete | train | def is_symbols_pair_complete(editor, symbol):
"""
Returns if the symbols pair is complete on current editor line.
:param editor: Document editor.
:type editor: QWidget
:param symbol: Symbol to check.
:type symbol: unicode
:return: Is symbols pair complete.
:rtype: bool
"""
symb... | python | {
"resource": ""
} |
q54817 | perform_completion | train | def perform_completion(editor):
"""
Performs the completion on given editor.
:param editor: Document editor.
:type editor: QWidget
:return: Method success.
:rtype: bool
"""
completion_prefix = editor.get_partial_word_under_cursor()
if not completion_prefix:
return
word... | python | {
"resource": ""
} |
q54818 | indentation_pre_event_input_accelerators | train | def indentation_pre_event_input_accelerators(editor, event):
"""
Implements indentation pre event input accelerators.
:param editor: Document editor.
:type editor: QWidget
:param event: Event being handled.
:type event: QEvent
:return: Process event.
:rtype: bool
"""
process_ev... | python | {
"resource": ""
} |
q54819 | indentation_post_event_input_accelerators | train | def indentation_post_event_input_accelerators(editor, event):
"""
Implements indentation post event input accelerators.
:param editor: Document editor.
:type editor: QWidget
:param event: Event being handled.
:type event: QEvent
:return: Method success.
:rtype: bool
"""
if even... | python | {
"resource": ""
} |
q54820 | completion_pre_event_input_accelerators | train | def completion_pre_event_input_accelerators(editor, event):
"""
Implements completion pre event input accelerators.
:param editor: Document editor.
:type editor: QWidget
:param event: Event being handled.
:type event: QEvent
:return: Process event.
:rtype: bool
"""
process_even... | python | {
"resource": ""
} |
q54821 | completion_post_event_input_accelerators | train | def completion_post_event_input_accelerators(editor, event):
"""
Implements completion post event input accelerators.
:param editor: Document editor.
:type editor: QWidget
:param event: Event being handled.
:type event: QEvent
:return: Process event.
:rtype: bool
"""
if editor.... | python | {
"resource": ""
} |
q54822 | symbols_expanding_pre_event_input_accelerators | train | def symbols_expanding_pre_event_input_accelerators(editor, event):
"""
Implements symbols expanding pre event input accelerators.
:param editor: Document editor.
:type editor: QWidget
:param event: Event being handled.
:type event: QEvent
:return: Process event.
:rtype: bool
"""
... | python | {
"resource": ""
} |
q54823 | ArmedSwitch.switch | train | def switch(self, val=None):
"""
Set the state of the switch. If the armed state is set to False,
the function does nothing.
:param val: Boolean. The value to set the switch state to. When None,
the switch will be set to the opposite of its current state.
:return: Boo... | python | {
"resource": ""
} |
q54824 | read_dir | train | def read_dir(input_dir,input_ext,func):
'''reads all files with extension input_ext
in a directory input_dir and apply function func
to their contents'''
import os
for dirpath, dnames, fnames in os.walk(input_dir):
for fname in fnames:
if not dirpath.endswith(os.sep):
... | python | {
"resource": ""
} |
q54825 | KVParser.parse | train | def parse(self, kv):
"""
Parses key value string into dict
Examples:
>> parser.parse('test1.test2=value')
{'test1': {'test2': 'value'}}
>> parser.parse('test=value')
{'test': 'value'}
"""
key, val = kv.split(self.kv_sep, 1)
... | python | {
"resource": ""
} |
q54826 | ssh | train | def ssh(container, cmd='', user='root', password='root'):
'''
SSH into a running container, using the host as a jump host. This requires
the container to have a running sshd process.
Args:
* container: Container name or ID
* cmd='': Command to run in the container
* user='root':... | python | {
"resource": ""
} |
q54827 | ps | train | def ps():
'''
Print a table of all running containers on a host
'''
containers = get_containers()
containers = [pretty_container(c) for c in containers]
print_table(containers, ['name', 'ip', 'ports', 'created', 'image'], sort='name') | python | {
"resource": ""
} |
q54828 | run | train | def run(image, name=None, command=None, environment=None, ports=None, volumes=None):
'''
Run a docker container.
Args:
* image: Docker image to run, e.g. orchardup/redis, quay.io/hello/world
* name=None: Container name
* command=None: Command to execute
* environment: Comma ... | python | {
"resource": ""
} |
q54829 | kill | train | def kill(container, rm=True):
'''
Kill a container
Args:
* container: Container name or ID
* rm=True: Remove the container or not
'''
container = get_container(container)
if not container:
raise Exception('No such container: %s' % container)
unbind_all(container['ip'... | python | {
"resource": ""
} |
q54830 | py_scanstring | train | def py_scanstring(s, end, encoding=None, strict=True,
_b=BACKSLASH, _m=STRINGCHUNK.match):
r"""Scan the string s for a DSON string. End is the index of the
character in s after the quote that started the DSON string.
Unescapes all valid DSON string escape sequences and raises ValueError
on attem... | python | {
"resource": ""
} |
q54831 | SmtpHealthCheck.run | train | def run(self, host, port=25, with_ssl=False):
"""Executes a single health check against a remote host and port. This
method may only be called once per object.
:param host: The hostname or IP address of the SMTP server to check.
:type host: str
:param port: The port number of th... | python | {
"resource": ""
} |
q54832 | convertShape | train | def convertShape(shapeString):
""" Convert xml shape string into float tuples.
This method converts the 2d or 3d shape string from SUMO's xml file
into a list containing 3d float-tuples. Non existant z coordinates default
to zero. If shapeString is empty, an empty list will be returned.
"""
cs... | python | {
"resource": ""
} |
q54833 | HtmlGenerator.generate_html | train | def generate_html(self, jdoc, schema, schemas):
'''Generates html for a subset of jdoc records
describing objects of specific schema'''
params = {'functions': sorted([j for j in jdoc \
if (j.schema_name == schema.object_name and j.object_type \
in ['fun... | python | {
"resource": ""
} |
q54834 | HtmlGenerator.generate_index | train | def generate_index(self, schemas):
'''Generates html for an index file'''
params = {'schemas': sorted(schemas, key=lambda x: x.object_name),
'project': self.project_name,
'title': '{}: Database schema documentation'\
.format(self.project_name)}
... | python | {
"resource": ""
} |
q54835 | HtmlGenerator.write_files | train | def write_files(self, jdoc, output_dir):
'''Writes all jdoc records into files.
One file per schema plus index file.'''
#get all distinct schema names from jdoc:
schemas = [j for j in jdoc if j.object_type == 'schema']
schemas = [j for j in schemas if len([x for x in jdoc if x.o... | python | {
"resource": ""
} |
q54836 | AssetsInterface.loose_search | train | def loose_search(self, asset_manager_id, query='', **kwargs):
"""
Asset search API.
Possible kwargs:
* threshold: int (default = 0)
* page_no: int (default = 1)
* page_size: int (default = 100)
* sort_fields: list (default = [])
* asset_typ... | python | {
"resource": ""
} |
q54837 | Portfolio.positions_by_asset | train | def positions_by_asset(self):
"""
A dictionary of Position objects keyed by asset_id. If an asset
position exists in more than one book, they are combined into a single
position.
"""
positions = None
for book in self.books():
book_positions = book.pos... | python | {
"resource": ""
} |
q54838 | _drop_none_values | train | def _drop_none_values(dictionary: Dict) -> Dict:
"""Drops fields from a dictionary where value is None.
>>> _drop_none_values({'greeting': 'hello', 'name': None})
{'greeting': 'hello'}
"""
return {key: value for key, value in dictionary.items() if value is not None} | python | {
"resource": ""
} |
q54839 | load | train | def load(*files):
"""
Loads configuration from one or more files by merging right to left.
:Parameters:
*files : `file-like`
A YAML file to read.
:Returns:
`dict` : the configuration document
"""
if len(files) == 0:
raise errors.ConfigError("No config files ... | python | {
"resource": ""
} |
q54840 | elem2json | train | def elem2json(elem, options, strip_ns=1, strip=1):
"""Convert an ElementTree or Element into a JSON string."""
if hasattr(elem, 'getroot'):
elem = elem.getroot()
if options.pretty:
return json.dumps(elem_to_internal(elem, strip_ns=strip_ns, strip=strip), sort_keys=True, indent=4, separato... | python | {
"resource": ""
} |
q54841 | json2elem | train | def json2elem(json_data, factory=ET.Element):
"""Convert a JSON string into an Element.
Whatever Element implementation we could import will be used by
default; if you want to use something else, pass the Element class
as the factory parameter.
"""
return internal_to_elem(json.loads(json_data... | python | {
"resource": ""
} |
q54842 | xml2json | train | def xml2json(xmlstring, options, strip_ns=1, strip=1):
"""Convert an XML string into a JSON string."""
elem = ET.fromstring(xmlstring)
return elem2json(elem, options, strip_ns=strip_ns, strip=strip) | python | {
"resource": ""
} |
q54843 | json2xml | train | def json2xml(json_data, factory=ET.Element):
"""Convert a JSON string into an XML string.
Whatever Element implementation we could import will be used by
default; if you want to use something else, pass the Element class
as the factory parameter.
"""
if not isinstance(json_data, dict):
... | python | {
"resource": ""
} |
q54844 | Sequence.advance_to_checkpoint | train | def advance_to_checkpoint(self, checkpoint):
"""
Advance to the specified checkpoint, passing all preceding checkpoints including the specified checkpoint.
"""
if checkpoint in self._checkpoints:
for cp in self._checkpoints:
self.insert(cp)
if ... | python | {
"resource": ""
} |
q54845 | Parser._process | train | def _process(self, name):
"""Process the current token."""
if self.token.nature == name:
self.token = self.lexer.next_token()
else:
self._error() | python | {
"resource": ""
} |
q54846 | Parser.parse | train | def parse(self):
"""Generic entrypoint of the `Parser` class."""
node = self.program()
if self.token.nature != Nature.EOF:
self._error()
return node | python | {
"resource": ""
} |
q54847 | RecordAPI.list | train | def list(self, domain_id, sub_domain=None):
'''Get a list of records, for a specific domain
:param str domain_id: Domain ID
:param str sub_domain: Optional. Subdomain of domain
:return: list of records
'''
optional_args = {}
if sub_domain != None:
opt... | python | {
"resource": ""
} |
q54848 | RecordAPI.ddns | train | def ddns(self, domain_id, record_id, sub_domain, record_line, value):
'''Update record's value dynamically
If the ``value`` is different from the record's current value, then
perform a dynamic record update. Otherwise, nothing will be done.
:param str domain_id: Domain ID
:para... | python | {
"resource": ""
} |
q54849 | RecordAPI.info | train | def info(self, domain_id, record_id):
'''Get information for a specific record
:param str domain_id: Domain ID
:param str record_id: Record ID
:return: object
'''
r = self._api.do_post('Record.Info', domain_id=domain_id,
record_id=record_id)... | python | {
"resource": ""
} |
q54850 | Survey.length | train | def length(self):
"""Total surveyed cave length, not including splays."""
return sum([shot.length for shot in self.shots if not shot.is_splay]) | python | {
"resource": ""
} |
q54851 | TxtFile.read | train | def read(fname, merge_duplicate_shots=False, encoding='windows-1252'):
"""Read a PocketTopo .TXT file and produce a `TxtFile` object which represents it"""
return PocketTopoTxtParser(fname, merge_duplicate_shots, encoding).parse() | python | {
"resource": ""
} |
q54852 | SplittedDateTime._to_timezone | train | def _to_timezone(self, dt):
"""Takes a naive timezone with an utc value and return it formatted as a
local timezone."""
tz = self._get_tz()
utc_dt = pytz.utc.localize(dt)
return utc_dt.astimezone(tz) | python | {
"resource": ""
} |
q54853 | SplittedDateTime._to_utc | train | def _to_utc(self, dt):
"""Takes a naive timezone with an localized value and return it formatted
as utc."""
tz = self._get_tz()
loc_dt = tz.localize(dt)
return loc_dt.astimezone(pytz.utc) | python | {
"resource": ""
} |
q54854 | SplittedDateTime._str_to_datetime | train | def _str_to_datetime(self, str_value):
"""Parses a `YYYY-MM-DD` string into a datetime object."""
try:
ldt = [int(f) for f in str_value.split('-')]
dt = datetime.datetime(*ldt)
except (ValueError, TypeError):
return None
return dt | python | {
"resource": ""
} |
q54855 | DataExtracter.getAllCols | train | def getAllCols(self, sddsfile=None):
""" get all available column names from sddsfile
:param sddsfile: sdds file name, if not given, rollback to the one that from ``__init__()``
:return: all sdds data column names
:rtype: list
:Example:
>>> dh = DataExtracter('test.out... | python | {
"resource": ""
} |
q54856 | DataExtracter.getAllPars | train | def getAllPars(self, sddsfile=None):
""" get all available parameter names from sddsfile
:param sddsfile: sdds file name, if not given, rollback to the one that from ``__init__()``
:return: all sdds data parameter names
:rtype: list
.. warning:: `sdds` needs to be installed as ... | python | {
"resource": ""
} |
q54857 | DataExtracter.extractData | train | def extractData(self):
""" return `self` with extracted data as `numpy array`
Extract the data of the columns and parameters of `self.kws` and put
them in a :np:func:`array` with all columns as columns or parameters as
columns. If columns and parameters are requested at the same then ea... | python | {
"resource": ""
} |
q54858 | DataExtracter.dump | train | def dump(self):
""" dump extracted data into a single hdf5file,
:return: None
:Example:
>>> # dump data into an hdf5 formated file
>>> datafields = ['s', 'Sx', 'Sy', 'enx', 'eny']
>>> datascript = 'sddsprintdata.sh'
>>> datapath = './tests/tracking'
>... | python | {
"resource": ""
} |
q54859 | includeme | train | def includeme(config):
"""
Add pyramid_htmlmin n your pyramid include list.
"""
log.info('Loading htmlmin pyramid plugin')
for key, val in config.registry.settings.items():
if key.startswith('htmlmin.'):
log.debug('Setup %s = %s' % (key, val))
htmlmin_opts[key[8:]] = ... | python | {
"resource": ""
} |
q54860 | natural_sort | train | def natural_sort(item):
"""
Sort strings that contain numbers correctly.
>>> l = ['v1.3.12', 'v1.3.3', 'v1.2.5', 'v1.2.15', 'v1.2.3', 'v1.2.1']
>>> l.sort(key=natural_sort)
>>> print l
"['v1.2.1', 'v1.2.3', 'v1.2.5', 'v1.2.15', 'v1.3.3', 'v1.3.12']"
"""
if item is None:
return 0... | python | {
"resource": ""
} |
q54861 | GdxFile.close | train | def close(self):
'''Close Gdx file and free up resources.'''
h = self.gdx_handle
gdxcc.gdxClose(h)
gdxcc.gdxFree(h) | python | {
"resource": ""
} |
q54862 | GdxFile.get_sid_info | train | def get_sid_info(self,j):
'''Return a dict of metadata for symbol with ID j.'''
h = self.gdx_handle
r, name, dims, stype = gdxcc.gdxSymbolInfo(h, j)
assert r, '%d is not a valid symbol number' % j
r, records, userinfo, description = gdxcc.gdxSymbolInfoX(h, j)
assert r, '%... | python | {
"resource": ""
} |
q54863 | GdxFile.get_symbols_list | train | def get_symbols_list(self):
'''Return a list of GdxSymb found in the GdxFile.'''
slist = []
rc, nSymb, nElem = gdxcc.gdxSystemInfo(self.gdx_handle)
assert rc, 'Unable to retrieve "%s" info' % self.filename
self.number_symbols = nSymb
self.number_elements = nElem
s... | python | {
"resource": ""
} |
q54864 | GdxFile.query | train | def query(self, name, reshape=RESHAPE_DEFAULT, filt=None, idval=None, idxlower=True):
'''
Query attribute `idval` from symbol `name`, and return a data structure shaped according to `reshape`.
'''
gdx_handle = self.gdx_handle
ret, symNr = gdxcc.gdxFindSymbol(gdx_handle, name)
... | python | {
"resource": ""
} |
q54865 | insert_tag | train | def insert_tag(tag, before, root):
"""
Insert `tag` before `before` tag if present. If not, insert it into `root`.
Args:
tag (obj): HTMLElement instance.
before (obj): HTMLElement instance.
root (obj): HTMLElement instance.
"""
if not before:
root.childs.append(tag)
... | python | {
"resource": ""
} |
q54866 | double_linked_dom | train | def double_linked_dom(str_or_dom):
"""
Create double linked DOM from input.
In case of string, parse it, make it double-linked. In case of DOM, just
make it double-linked.
Args:
str_or_dom (str/HTMLelement): String or HTMLelement instance.
Returns:
obj: HTMLelement with parsed... | python | {
"resource": ""
} |
q54867 | paste | train | def paste(client, event, channel, nick, rest):
"Drop a link to your latest paste"
path = '/last/{nick}'.format(**locals())
paste_root = pmxbot.config.get('librarypaste', 'http://paste.jaraco.com')
url = urllib.parse.urljoin(paste_root, path)
auth = pmxbot.config.get('librarypaste auth')
resp = requests.head(url, ... | python | {
"resource": ""
} |
q54868 | add | train | def add(addon, dev, interactive):
"""Add a dependency.
Examples:
$ django add dynamic-rest==1.5.0
+ dynamic-rest == 1.5.0
"""
application = get_current_application()
application.add(
addon,
dev=dev,
interactive=interactive
) | python | {
"resource": ""
} |
q54869 | propagate_defaults | train | def propagate_defaults(config_doc):
"""
Propagate default values to sections of the doc.
"""
for group_name, group_doc in config_doc.items():
if isinstance(group_doc, dict):
defaults = group_doc.get('defaults', {})
for item_name, item_doc in group_doc.items():
... | python | {
"resource": ""
} |
q54870 | split_by_proportions | train | def split_by_proportions(total, proportions, mininum_values):
"""splits the given total by the given proportions but ensures that each value in
the result has at least the given minimum value"""
assert(len(proportions) == len(mininum_values))
assert(total >= sum(mininum_values))
assert(min(proportio... | python | {
"resource": ""
} |
q54871 | ConfigFactory.lookup | train | def lookup(self, section, name):
"""Lookup config value."""
value = os.environ.get('AMAAS_{}'.format(name.upper()))
if value:
return value
try:
value = self.file_config.get(section, name)
except ConfigParserError:
pass
else:
... | python | {
"resource": ""
} |
q54872 | ConfigFactory.api_config | train | def api_config(self, stage=None):
"""Create api config based on stage."""
if stage in self.known_api_configurations:
return self.known_api_configurations[stage]
if not stage:
section = 'stages.live'
api_url = 'https://api.amaas.com/'
else:
... | python | {
"resource": ""
} |
q54873 | ConfigFactory.auth_config | train | def auth_config(self, stage=None):
"""Create auth config based on stage."""
if stage:
section = 'stages.{}'.format(stage)
else:
section = 'stages.live'
try:
username = self.lookup(section, 'username')
password = self.lookup(section, 'passw... | python | {
"resource": ""
} |
q54874 | SymbolTableBuilder.visit_Program | train | def visit_Program(self, node):
"""Vsitor for `Program` AST node."""
for child in node.children:
if not isinstance(child, FunctionDeclaration):
self.visit(child) | python | {
"resource": ""
} |
q54875 | SymbolTableBuilder.visit_VariableDeclaration | train | def visit_VariableDeclaration(self, node):
"""Visitor for `VariableDeclaration` AST node."""
var_name = node.assignment.left.identifier.name
var_is_mutable = node.assignment.left.is_mutable
var_symbol = VariableSymbol(var_name, var_is_mutable)
if self.table[var_name] is not None... | python | {
"resource": ""
} |
q54876 | SymbolTableBuilder.visit_Variable | train | def visit_Variable(self, node):
"""Visitor for `Variable` AST node."""
var_name = node.identifier.name
var_symbol = self.table[var_name]
if var_symbol is None:
raise SementicError(f"Variable `{var_name}` is not declared.") | python | {
"resource": ""
} |
q54877 | SymbolTableBuilder.visit_IfStatement | train | def visit_IfStatement(self, node):
"""Visitor for `IfStatement` AST node."""
if_conditon, if_body = node.if_compound
self.visit(if_conditon)
self.visit(if_body)
for else_if_compound in node.else_if_compounds:
else_if_condition, else_if_body = else_if_compound
... | python | {
"resource": ""
} |
q54878 | SymbolTableBuilder.build | train | def build(self):
"""Generic entrypoint of `SymbolTableBuilder` class."""
self.load_builtins()
self.load_functions(self.tree)
self.visit(self.tree) | python | {
"resource": ""
} |
q54879 | ISBN.isbn10 | train | def isbn10(self):
'''
Encode ISBN number in ISBN10 format
Raises exception if Bookland number different from 978
@rtype: string
@return: ISBN formated as ISBN10
'''
if self._id[0:3] != '978':
raise ISBNError("Invalid Bookland code: {}".format(self._id... | python | {
"resource": ""
} |
q54880 | parsehttpdate | train | def parsehttpdate(string_):
"""
Parses an HTTP date into a datetime object.
>>> parsehttpdate('Thu, 01 Jan 1970 01:01:01 GMT')
datetime.datetime(1970, 1, 1, 1, 1, 1)
"""
try:
t = time.strptime(string_, "%a, %d %b %Y %H:%M:%S %Z")
except ValueError:
return None
re... | python | {
"resource": ""
} |
q54881 | websafe | train | def websafe(val):
r"""Converts `val` so that it is safe for use in Unicode HTML.
>>> websafe("<'&\">")
u'<'&">'
>>> websafe(None)
u''
>>> websafe(u'\u203d')
u'\u203d'
>>> websafe('\xe2\x80\xbd')
u'\u203d'
"""
if val is None:... | python | {
"resource": ""
} |
q54882 | QuickSettings.setdefaults | train | def setdefaults(self, from_qs):
"""
sets values from a QuickSettings object, only keeping values that
are not already defined on the main object
"""
for k in from_qs.keys():
from_value = from_qs[k]
fv_is_qs = isinstance(from_value, QuickSettings)
... | python | {
"resource": ""
} |
q54883 | getArguments | train | def getArguments():
"""Get the arguments
"""
parser = ArgumentParser(description = 'CA utility')
parser.add_argument('--base', dest = 'basePath', default = '.', help = 'The base working directory')
subParsers = parser.add_subparsers(dest = 'action')
# The init parser
initParser = subParsers.... | python | {
"resource": ""
} |
q54884 | main | train | def main():
"""The main entry
"""
args = getArguments()
try:
if args.action == 'init':
# Ask for init
while True:
print 'Initialize the path [%s] will cause any files or dirs be removed, continue?[y/n]' % args.basePath,
text = raw_input()
... | python | {
"resource": ""
} |
q54885 | MsgPackProxy.begin_call | train | def begin_call(self, method, *args):
"""Perform an asynchronous remote call where the return value is not known yet.
This returns immediately with a Deferred object. The Deferred object may then be
used to attach a callback, force waiting for the call, or check for exceptions.
"""
... | python | {
"resource": ""
} |
q54886 | MsgPackProtocol.response | train | def response(self, msgtype, msgid, error, result):
"""Handle an incoming response."""
self._proxy.response(msgid, error, result) | python | {
"resource": ""
} |
q54887 | MsgPackProtocol.notify | train | def notify(self, msgtype, method, params):
"""Handle an incoming notify request."""
self.dispatch.call(method, params) | python | {
"resource": ""
} |
q54888 | MsgPackProtocol.request | train | def request(self, msgtype, msgid, method, params=[]):
"""Handle an incoming call request."""
result = None
error = None
exception = None
try:
result = self.dispatch.call(method, params)
except Exception as e:
error = (e.__class__.__name__, str(e))... | python | {
"resource": ""
} |
q54889 | MsgPackProtocol.data | train | def data(self, data):
"""Use msgpack's streaming feed feature to build up a set of lists.
The lists should then contain the messagepack-rpc specified items.
This should be outrageously fast.
"""
self.unpacker.feed(data)
for msg in self.unpacker:
sel... | python | {
"resource": ""
} |
q54890 | MsgPackProtocol.proxy | train | def proxy(self):
"""Return a Deferred that will result in a proxy object in the future."""
d = Deferred(self.loop)
self._proxy_deferreds.append(d)
if self._proxy:
d.callback(self._proxy)
return d | python | {
"resource": ""
} |
q54891 | addPlayer | train | def addPlayer(settings):
"""define a new PlayerRecord setting and save to disk file"""
_validate(settings)
player = PlayerRecord(settings)
player.save()
getKnownPlayers()[player.name] = player
return player | python | {
"resource": ""
} |
q54892 | updatePlayer | train | def updatePlayer(name, settings):
"""update an existing PlayerRecord setting and save to disk file"""
player = delPlayer(name) # remove the existing record
_validate(settings)
player.update(settings)
player.save()
getKnownPlayers()[player.name] = player
return player | python | {
"resource": ""
} |
q54893 | getPlayer | train | def getPlayer(name):
"""obtain a specific PlayerRecord settings file"""
if isinstance(name, PlayerRecord): return name
try: return getKnownPlayers()[name.lower()]
except KeyError:
raise ValueError("given player name '%s' is not a known player definition"%(name)) | python | {
"resource": ""
} |
q54894 | delPlayer | train | def delPlayer(name):
"""forget about a previously defined PlayerRecord setting by deleting its disk file"""
player = getPlayer(name)
try: os.remove(player.filename) # delete from disk
except IOError: pass # shouldn't happen, but don't crash if the disk data doesn't exist
try: del getKnownPlaye... | python | {
"resource": ""
} |
q54895 | getKnownPlayers | train | def getKnownPlayers(reset=False):
"""identify all of the currently defined players"""
global playerCache
if not playerCache or reset:
jsonFiles = os.path.join(c.PLAYERS_FOLDER, "*.json")
for playerFilepath in glob.glob(jsonFiles):
filename = os.path.basename(playerFilepath)
... | python | {
"resource": ""
} |
q54896 | getBlizzBotPlayers | train | def getBlizzBotPlayers():
"""identify all of Blizzard's built-in bots"""
ret = {}
for pName,p in iteritems(getKnownPlayers()):
if p.isComputer:
ret[pName] = p
return ret | python | {
"resource": ""
} |
q54897 | LazyRegex._create_regex_if_none | train | def _create_regex_if_none(self):
"""
Private function. Checks to see if the local regular expression
object has been created yet
"""
if self._regex is None:
self._regex = re.compile(self._pattern, re.UNICODE) | python | {
"resource": ""
} |
q54898 | get_html_attrs | train | def get_html_attrs(kwargs=None):
"""Generate HTML attributes from the provided keyword arguments.
The output value is sorted by the passed keys, to provide consistent
output. Because of the frequent use of the normally reserved keyword
`class`, `classes` is used instead. Also, all underscores are tran... | python | {
"resource": ""
} |
q54899 | execution_group | train | def execution_group(id):
"""A decorator designed to be used with both classes and functions. Pass the
decorator some object that represents the Execution Group the decorated object
should be added to. If one test function in an Execution Group fails then no
more tests from that Execution Group will ru... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.