INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Split a line of text with a cursor at the given position. | def split_line(self, line, cursor_pos=None):
"""Split a line of text with a cursor at the given position.
"""
l = line if cursor_pos is None else line[:cursor_pos]
return self._delim_re.split(l)[-1] |
Compute matches when text is a simple name. | def global_matches(self, text):
"""Compute matches when text is a simple name.
Return a list of all keywords, built-in functions and names currently
defined in self.namespace or self.global_namespace that match.
"""
#print 'Completer->global_matches, txt=%r' % text # dbg
... |
Compute matches when text contains a dot. | def attr_matches(self, text):
"""Compute matches when text contains a dot.
Assuming the text is of the form NAME.NAME....[NAME], and is
evaluatable in self.namespace or self.global_namespace, it will be
evaluated and its attributes (as revealed by dir()) are used as
possible com... |
update the splitter and readline delims when greedy is changed | def _greedy_changed(self, name, old, new):
"""update the splitter and readline delims when greedy is changed"""
if new:
self.splitter.delims = GREEDY_DELIMS
else:
self.splitter.delims = DELIMS
if self.readline:
self.readline.set_completer_delims(self.... |
Match filenames expanding ~USER type strings. | def file_matches(self, text):
"""Match filenames, expanding ~USER type strings.
Most of the seemingly convoluted logic in this completer is an
attempt to handle filenames with spaces in them. And yet it's not
quite perfect, because Python's readline doesn't expose all of the
GN... |
Match magics | def magic_matches(self, text):
"""Match magics"""
#print 'Completer->magic_matches:',text,'lb',self.text_until_cursor # dbg
# Get all shell magics now rather than statically, so magics loaded at
# runtime show up too.
lsm = self.shell.magics_manager.lsmagic()
line_magics ... |
Match internal system aliases | def alias_matches(self, text):
"""Match internal system aliases"""
#print 'Completer->alias_matches:',text,'lb',self.text_until_cursor # dbg
# if we are not in the first 'item', alias matching
# doesn't make sense - unless we are starting with 'sudo' command.
main_text = self.te... |
Match attributes or global python names | def python_matches(self,text):
"""Match attributes or global python names"""
#io.rprint('Completer->python_matches, txt=%r' % text) # dbg
if "." in text:
try:
matches = self.attr_matches(text)
if text.endswith('.') and self.omit__names:
... |
Return the list of default arguments of obj if it is callable or empty list otherwise. | def _default_arguments(self, obj):
"""Return the list of default arguments of obj if it is callable,
or empty list otherwise."""
if not (inspect.isfunction(obj) or inspect.ismethod(obj)):
# for classes, check for __init__,__new__
if inspect.isclass(obj):
... |
Match named parameters ( kwargs ) of the last open function | def python_func_kw_matches(self,text):
"""Match named parameters (kwargs) of the last open function"""
if "." in text: # a parameter cannot be dotted
return []
try: regexp = self.__funcParamsRegex
except AttributeError:
regexp = self.__funcParamsRegex = re.compil... |
Find completions for the given text and line context. | def complete(self, text=None, line_buffer=None, cursor_pos=None):
"""Find completions for the given text and line context.
This is called successively with state == 0, 1, 2, ... until it
returns None. The completion should begin with 'text'.
Note that both the text and the line_buffer... |
Return the state - th possible completion for text. | def rlcomplete(self, text, state):
"""Return the state-th possible completion for 'text'.
This is called successively with state == 0, 1, 2, ... until it
returns None. The completion should begin with 'text'.
Parameters
----------
text : string
Text to pe... |
Check if a specific record matches tests. | def _match_one(self, rec, tests):
"""Check if a specific record matches tests."""
for key,test in tests.iteritems():
if not test(rec.get(key, None)):
return False
return True |
Find all the matches for a check dict. | def _match(self, check):
"""Find all the matches for a check dict."""
matches = []
tests = {}
for k,v in check.iteritems():
if isinstance(v, dict):
tests[k] = CompositeFilter(v)
else:
tests[k] = lambda o: o==v
for rec in se... |
extract subdict of keys | def _extract_subdict(self, rec, keys):
"""extract subdict of keys"""
d = {}
d['msg_id'] = rec['msg_id']
for key in keys:
d[key] = rec[key]
return copy(d) |
Add a new Task Record by msg_id. | def add_record(self, msg_id, rec):
"""Add a new Task Record, by msg_id."""
if self._records.has_key(msg_id):
raise KeyError("Already have msg_id %r"%(msg_id))
self._records[msg_id] = rec |
Get a specific Task Record by msg_id. | def get_record(self, msg_id):
"""Get a specific Task Record, by msg_id."""
if not msg_id in self._records:
raise KeyError("No such msg_id %r"%(msg_id))
return copy(self._records[msg_id]) |
Remove a record from the DB. | def drop_matching_records(self, check):
"""Remove a record from the DB."""
matches = self._match(check)
for m in matches:
del self._records[m['msg_id']] |
Find records matching a query dict optionally extracting subset of keys. | def find_records(self, check, keys=None):
"""Find records matching a query dict, optionally extracting subset of keys.
Returns dict keyed by msg_id of matching records.
Parameters
----------
check: dict
mongodb-style query argument
keys: list of strs [optio... |
get all msg_ids ordered by time submitted. | def get_history(self):
"""get all msg_ids, ordered by time submitted."""
msg_ids = self._records.keys()
return sorted(msg_ids, key=lambda m: self._records[m]['submitted']) |
Should we silence the display hook because of ; ? | def quiet(self):
"""Should we silence the display hook because of ';'?"""
# do not print output if input ends in ';'
try:
cell = self.shell.history_manager.input_hist_parsed[self.prompt_count]
if cell.rstrip().endswith(';'):
return True
except Inde... |
Write the output prompt. | def write_output_prompt(self):
"""Write the output prompt.
The default implementation simply writes the prompt to
``io.stdout``.
"""
# Use write, not print which adds an extra space.
io.stdout.write(self.shell.separate_out)
outprompt = self.shell.prompt_manager.r... |
Write the format data dict to the frontend. | def write_format_data(self, format_dict):
"""Write the format data dict to the frontend.
This default version of this method simply writes the plain text
representation of the object to ``io.stdout``. Subclasses should
override this method to send the entire `format_dict` to the
... |
Update user_ns with various things like _ __ _1 etc. | def update_user_ns(self, result):
"""Update user_ns with various things like _, __, _1, etc."""
# Avoid recursive reference when displaying _oh/Out
if result is not self.shell.user_ns['_oh']:
if len(self.shell.user_ns['_oh']) >= self.cache_size and self.do_full_cache:
... |
Log the output. | def log_output(self, format_dict):
"""Log the output."""
if self.shell.logger.log_output:
self.shell.logger.log_write(format_dict['text/plain'], 'output')
self.shell.history_manager.output_hist_reprs[self.prompt_count] = \
format_di... |
Finish up all displayhook activities. | def finish_displayhook(self):
"""Finish up all displayhook activities."""
io.stdout.write(self.shell.separate_out2)
io.stdout.flush() |
Load the extension in IPython. | def load_ipython_extension(ip):
"""Load the extension in IPython."""
global _loaded
if not _loaded:
plugin = StoreMagic(shell=ip, config=ip.config)
ip.plugin_manager.register_plugin('storemagic', plugin)
_loaded = True |
raise InvalidOperationException if is freezed. | def raise_if_freezed(self):
'''raise `InvalidOperationException` if is freezed.'''
if self.is_freezed:
name = type(self).__name__
raise InvalidOperationException('obj {name} is freezed.'.format(name=name)) |
Convert a MySQL TIMESTAMP to a Timestamp object. | def mysql_timestamp_converter(s):
"""Convert a MySQL TIMESTAMP to a Timestamp object."""
# MySQL>4.1 returns TIMESTAMP in the same format as DATETIME
if s[4] == '-': return DateTime_or_None(s)
s = s + "0"*(14-len(s)) # padding
parts = map(int, filter(None, (s[:4],s[4:6],s[6:8],
... |
body_elements: <list > of etree. Elements or <None > | def make_envelope(self, body_elements=None):
"""
body_elements: <list> of etree.Elements or <None>
"""
soap = self.get_soap_el_factory()
body_elements = body_elements or []
body = soap.Body(*body_elements)
header = self.get_soap_header()
if header is not N... |
Embed and start an IPython kernel in a given scope. Parameters ---------- module: ModuleType optional The module to load into IPython globals ( default: caller ) local_ns: dict optional The namespace to load into IPython user namespace ( default: caller ) kwargs: various optional Further keyword args are relayed to the... | def embed_kernel(module=None, local_ns=None, **kwargs):
"""Embed and start an IPython kernel in a given scope.
Parameters
----------
module : ModuleType, optional
The module to load into IPython globals (default: caller)
local_ns : dict, optional
The namespace to load into IPyth... |
schedule call to eventloop from IOLoop | def _eventloop_changed(self, name, old, new):
"""schedule call to eventloop from IOLoop"""
loop = ioloop.IOLoop.instance()
loop.add_timeout(time.time()+0.1, self.enter_eventloop) |
dispatch control requests | def dispatch_control(self, msg):
"""dispatch control requests"""
idents,msg = self.session.feed_identities(msg, copy=False)
try:
msg = self.session.unserialize(msg, content=True, copy=False)
except:
self.log.error("Invalid Control Message", exc_info=True)
... |
dispatch shell requests | def dispatch_shell(self, stream, msg):
"""dispatch shell requests"""
# flush control requests first
if self.control_stream:
self.control_stream.flush()
idents,msg = self.session.feed_identities(msg, copy=False)
try:
msg = self.session.unserialize(... |
enter eventloop | def enter_eventloop(self):
"""enter eventloop"""
self.log.info("entering eventloop")
# restore default_int_handler
signal(SIGINT, default_int_handler)
while self.eventloop is not None:
try:
self.eventloop(self)
except KeyboardInterrupt:
... |
register dispatchers for streams | def start(self):
"""register dispatchers for streams"""
self.shell.exit_now = False
if self.control_stream:
self.control_stream.on_recv(self.dispatch_control, copy=False)
def make_dispatcher(stream):
def dispatcher(msg):
return self.dispatch_shell... |
step eventloop just once | def do_one_iteration(self):
"""step eventloop just once"""
if self.control_stream:
self.control_stream.flush()
for stream in self.shell_streams:
# handle at most one request per iteration
stream.flush(zmq.POLLIN, 1)
stream.flush(zmq.POLLOUT) |
Publish the code request on the pyin stream. | def _publish_pyin(self, code, parent, execution_count):
"""Publish the code request on the pyin stream."""
self.session.send(self.iopub_socket, u'pyin',
{u'code':code, u'execution_count': execution_count},
parent=parent, ident=self._topic('pyin')
... |
send status ( busy/ idle ) on IOPub | def _publish_status(self, status, parent=None):
"""send status (busy/idle) on IOPub"""
self.session.send(self.iopub_socket,
u'status',
{u'execution_state': status},
parent=parent,
ident=self._topic('s... |
handle an execute_request | def execute_request(self, stream, ident, parent):
"""handle an execute_request"""
self._publish_status(u'busy', parent)
try:
content = parent[u'content']
code = content[u'code']
silent = content[u'silent']
except:
self.log... |
abort a specifig msg by id | def abort_request(self, stream, ident, parent):
"""abort a specifig msg by id"""
msg_ids = parent['content'].get('msg_ids', None)
if isinstance(msg_ids, basestring):
msg_ids = [msg_ids]
if not msg_ids:
self.abort_queues()
for mid in msg_ids:
se... |
Clear our namespace. | def clear_request(self, stream, idents, parent):
"""Clear our namespace."""
self.shell.reset(False)
msg = self.session.send(stream, 'clear_reply', ident=idents, parent=parent,
content = dict(status='ok')) |
prefixed topic for IOPub messages | def _topic(self, topic):
"""prefixed topic for IOPub messages"""
if self.int_id >= 0:
base = "engine.%i" % self.int_id
else:
base = "kernel.%s" % self.ident
return py3compat.cast_bytes("%s.%s" % (base, topic)) |
Actions taken at shutdown by the kernel called by python s atexit. | def _at_shutdown(self):
"""Actions taken at shutdown by the kernel, called by python's atexit.
"""
# io.rprint("Kernel at_shutdown") # dbg
if self._shutdown_message is not None:
self.session.send(self.iopub_socket, self._shutdown_message, ident=self._topic('shutdown'))
... |
Enable GUI event loop integration taking pylab into account. | def init_gui_pylab(self):
"""Enable GUI event loop integration, taking pylab into account."""
# Provide a wrapper for :meth:`InteractiveShellApp.init_gui_pylab`
# to ensure that any exception is printed straight to stderr.
# Normally _showtraceback associates the reply with an execution... |
Create equal sized slices of the file. The last slice may be larger than the others. args: * size ( int ): The full size to be sliced. * n ( int ): The number of slices to return. returns: A list of FileSlice objects of length ( n ). | def slices(self, size, n=3):
'''
Create equal sized slices of the file. The last slice may be larger than
the others.
args:
* size (int): The full size to be sliced.
* n (int): The number of slices to return.
returns:
A list o... |
Same as file. seek () but for the slice. Returns a value between self. start and self. size inclusive. raises: ValueError if the new seek position is not between 0 and self. size. | def seek(self, offset, whence=0):
'''
Same as `file.seek()` but for the slice. Returns a value between
`self.start` and `self.size` inclusive.
raises:
ValueError if the new seek position is not between 0 and
`self.size`.
'''
if se... |
Same as file. read () but for the slice. Does not read beyond self. end. | def read(self, size=-1):
'''
Same as `file.read()` but for the slice. Does not read beyond
`self.end`.
'''
if self.closed:
raise ValueError('I/O operation on closed file.')
if size == -1 or size > self.size - self.pos:
size = self... |
Same as file. write () but for the slice. raises: EOFError if the new seek position is > self. size. | def write(self, b):
'''
Same as `file.write()` but for the slice.
raises:
EOFError if the new seek position is > `self.size`.
'''
if self.closed:
raise ValueError('I/O operation on closed file.')
if self.pos + len(b) > s... |
Same as file. writelines () but for the slice. raises: EOFError if the new seek position is > self. size. | def writelines(self, lines):
'''
Same as `file.writelines()` but for the slice.
raises:
EOFError if the new seek position is > `self.size`.
'''
lines = b''.join(lines)
self.write(lines) |
Configure plugin. | def configure(self, options, conf):
"""Configure plugin.
"""
Plugin.configure(self, options, conf)
self._mod_stack = [] |
Copy sys. modules onto my mod stack | def beforeContext(self):
"""Copy sys.modules onto my mod stack
"""
mods = sys.modules.copy()
self._mod_stack.append(mods) |
Pop my mod stack and restore sys. modules to the state it was in when mod stack was pushed. | def afterContext(self):
"""Pop my mod stack and restore sys.modules to the state
it was in when mod stack was pushed.
"""
mods = self._mod_stack.pop()
to_del = [ m for m in sys.modules.keys() if m not in mods ]
if to_del:
log.debug('removing sys modules entrie... |
Return absolute normalized path to directory if it exists ; None otherwise. | def absdir(path):
"""Return absolute, normalized path to directory, if it exists; None
otherwise.
"""
if not os.path.isabs(path):
path = os.path.normpath(os.path.abspath(os.path.join(os.getcwd(),
path)))
if path is None or not os.p... |
Return absolute normalized path to file ( optionally in directory where ) or None if the file can t be found either in where or the current working directory. | def absfile(path, where=None):
"""Return absolute, normalized path to file (optionally in directory
where), or None if the file can't be found either in where or the current
working directory.
"""
orig = path
if where is None:
where = os.getcwd()
if isinstance(where, list) or isinsta... |
A name is file - like if it is a path that exists or it has a directory part or it ends in. py or it isn t a legal python identifier. | def file_like(name):
"""A name is file-like if it is a path that exists, or it has a
directory part, or it ends in .py, or it isn't a legal python
identifier.
"""
return (os.path.exists(name)
or os.path.dirname(name)
or name.endswith('.py')
or not ident_re.match(o... |
Is obj a class? Inspect s isclass is too liberal and returns True for objects that can t be subclasses of anything. | def isclass(obj):
"""Is obj a class? Inspect's isclass is too liberal and returns True
for objects that can't be subclasses of anything.
"""
obj_type = type(obj)
return obj_type in class_types or issubclass(obj_type, type) |
Is this path a package directory? | def ispackage(path):
"""
Is this path a package directory?
>>> ispackage('nose')
True
>>> ispackage('unit_tests')
False
>>> ispackage('nose/plugins')
True
>>> ispackage('nose/loader.py')
False
"""
if os.path.isdir(path):
# at least the end of the path must be a l... |
Find the python source file for a package relative to a particular directory ( defaults to current working directory if not given ). | def getfilename(package, relativeTo=None):
"""Find the python source file for a package, relative to a
particular directory (defaults to current working directory if not
given).
"""
if relativeTo is None:
relativeTo = os.getcwd()
path = os.path.join(relativeTo, os.sep.join(package.split(... |
Find the full dotted package name for a given python source file name. Returns None if the file is not a python source file. | def getpackage(filename):
"""
Find the full dotted package name for a given python source file
name. Returns None if the file is not a python source file.
>>> getpackage('foo.py')
'foo'
>>> getpackage('biff/baf.py')
'baf'
>>> getpackage('nose/util.py')
'nose.util'
Works for dir... |
Draw a 70 - char - wide divider with label in the middle. | def ln(label):
"""Draw a 70-char-wide divider, with label in the middle.
>>> ln('hello there')
'---------------------------- hello there -----------------------------'
"""
label_len = len(label) + 2
chunk = (70 - label_len) // 2
out = '%s %s %s' % ('-' * chunk, label, '-' * chunk)
pad =... |
Given a list of possible method names try to run them with the provided object. Keep going until something works. Used to run setup/ teardown methods for module package and function tests. | def try_run(obj, names):
"""Given a list of possible method names, try to run them with the
provided object. Keep going until something works. Used to run
setup/teardown methods for module, package, and function tests.
"""
for name in names:
func = getattr(obj, name, None)
if func is... |
Find the python source file for a. pyc. pyo or $py. class file on jython. Returns the filename provided if it is not a python source file. | def src(filename):
"""Find the python source file for a .pyc, .pyo or $py.class file on
jython. Returns the filename provided if it is not a python source
file.
"""
if filename is None:
return filename
if sys.platform.startswith('java') and filename.endswith('$py.class'):
return ... |
Sort key function factory that puts items that match a regular expression last. | def regex_last_key(regex):
"""Sort key function factory that puts items that match a
regular expression last.
>>> from nose.config import Config
>>> from nose.pyversion import sort_list
>>> c = Config()
>>> regex = c.testMatch
>>> entries = ['.', '..', 'a_test', 'src', 'lib', 'test', 'foo.p... |
Convert a value that may be a list or a ( possibly comma - separated ) string into a list. The exception: None is returned as None not [ None ]. | def tolist(val):
"""Convert a value that may be a list or a (possibly comma-separated)
string into a list. The exception: None is returned as None, not [None].
>>> tolist(["one", "two"])
['one', 'two']
>>> tolist("hello")
['hello']
>>> tolist("separate,values, with, commas, spaces , are ... |
Make a function imported from module A appear as if it is located in module B. | def transplant_func(func, module):
"""
Make a function imported from module A appear as if it is located
in module B.
>>> from pprint import pprint
>>> pprint.__module__
'pprint'
>>> pp = transplant_func(pprint, __name__)
>>> pp.__module__
'nose.util'
The original function is n... |
Make a class appear to reside in module rather than the module in which it is actually defined. | def transplant_class(cls, module):
"""
Make a class appear to reside in `module`, rather than the module in which
it is actually defined.
>>> from nose.failure import Failure
>>> Failure.__module__
'nose.failure'
>>> Nf = transplant_class(Failure, __name__)
>>> Nf.__module__
'nose.u... |
System virtual memory as a namedtuple. | def virtual_memory():
"""System virtual memory as a namedtuple."""
total, active, inactive, wired, free = _psutil_osx.get_virtual_mem()
avail = inactive + free
used = active + inactive + wired
percent = usage_percent((total - avail), total, _round=1)
return nt_virtmem_info(total, avail, percent,... |
Swap system memory as a ( total used free sin sout ) tuple. | def swap_memory():
"""Swap system memory as a (total, used, free, sin, sout) tuple."""
total, used, free, sin, sout = _psutil_osx.get_swap_mem()
percent = usage_percent(used, total, _round=1)
return nt_swapmeminfo(total, used, free, percent, sin, sout) |
Return system CPU times as a namedtuple. | def get_system_cpu_times():
"""Return system CPU times as a namedtuple."""
user, nice, system, idle = _psutil_osx.get_system_cpu_times()
return _cputimes_ntuple(user, nice, system, idle) |
Return system CPU times as a named tuple | def get_system_per_cpu_times():
"""Return system CPU times as a named tuple"""
ret = []
for cpu_t in _psutil_osx.get_system_per_cpu_times():
user, nice, system, idle = cpu_t
item = _cputimes_ntuple(user, nice, system, idle)
ret.append(item)
return ret |
Return process cmdline as a list of arguments. | def get_process_cmdline(self):
"""Return process cmdline as a list of arguments."""
if not pid_exists(self.pid):
raise NoSuchProcess(self.pid, self._process_name)
return _psutil_osx.get_process_cmdline(self.pid) |
Return a tuple with the process RSS and VMS size. | def get_memory_info(self):
"""Return a tuple with the process' RSS and VMS size."""
rss, vms = _psutil_osx.get_process_memory_info(self.pid)[:2]
return nt_meminfo(rss, vms) |
Return a tuple with the process RSS and VMS size. | def get_ext_memory_info(self):
"""Return a tuple with the process' RSS and VMS size."""
rss, vms, pfaults, pageins = _psutil_osx.get_process_memory_info(self.pid)
return self._nt_ext_mem(rss, vms,
pfaults * _PAGESIZE,
pageins * _PAG... |
Return files opened by process. | def get_open_files(self):
"""Return files opened by process."""
if self.pid == 0:
return []
files = []
rawlist = _psutil_osx.get_process_open_files(self.pid)
for path, fd in rawlist:
if isfile_strict(path):
ntuple = nt_openfile(path, fd)
... |
Return etwork connections opened by a process as a list of namedtuples. | def get_connections(self, kind='inet'):
"""Return etwork connections opened by a process as a list of
namedtuples.
"""
if kind not in conn_tmap:
raise ValueError("invalid %r kind argument; choose between %s"
% (kind, ', '.join([repr(x) for x in co... |
Check if a user is in a certaing group. By default the check is skipped for superusers. | def user_has_group(user, group, superuser_skip=True):
"""
Check if a user is in a certaing group.
By default, the check is skipped for superusers.
"""
if user.is_superuser and superuser_skip:
return True
return user.groups.filter(name=group).exists() |
Load a class by a fully qualified class_path eg. myapp. models. ModelName | def resolve_class(class_path):
"""
Load a class by a fully qualified class_path,
eg. myapp.models.ModelName
"""
modulepath, classname = class_path.rsplit('.', 1)
module = __import__(modulepath, fromlist=[classname])
return getattr(module, classname) |
Calculate percentage usage of used against total. | def usage_percent(used, total, _round=None):
"""Calculate percentage usage of 'used' against 'total'."""
try:
ret = (used / total) * 100
except ZeroDivisionError:
ret = 0
if _round is not None:
return round(ret, _round)
else:
return ret |
A simple memoize decorator for functions. | def memoize(f):
"""A simple memoize decorator for functions."""
cache= {}
def memf(*x):
if x not in cache:
cache[x] = f(*x)
return cache[x]
return memf |
A decorator which can be used to mark functions as deprecated. | def deprecated(replacement=None):
"""A decorator which can be used to mark functions as deprecated."""
def outer(fun):
msg = "psutil.%s is deprecated" % fun.__name__
if replacement is not None:
msg += "; use %s instead" % replacement
if fun.__doc__ is None:
fun.__... |
Same as os. path. isfile () but does not swallow EACCES/ EPERM exceptions see: http:// mail. python. org/ pipermail/ python - dev/ 2012 - June/ 120787. html | def isfile_strict(path):
"""Same as os.path.isfile() but does not swallow EACCES / EPERM
exceptions, see:
http://mail.python.org/pipermail/python-dev/2012-June/120787.html
"""
try:
st = os.stat(path)
except OSError:
err = sys.exc_info()[1]
if err.errno in (errno.EPERM, er... |
Pushes specified directory to git remote: param git_message: commit message: param git_repository: repository address: param git_branch: git branch: param locale_root: path to locale root folder containing directories with languages: return: tuple stdout stderr of completed command | def git_push(git_message=None, git_repository=None, git_branch=None,
locale_root=None):
"""
Pushes specified directory to git remote
:param git_message: commit message
:param git_repository: repository address
:param git_branch: git branch
:param locale_root: path to locale root fol... |
Checkouts branch to last commit: param git_branch: branch to checkout: param locale_root: locale folder path: return: tuple stdout stderr of completed command | def git_checkout(git_branch=None, locale_root=None):
"""
Checkouts branch to last commit
:param git_branch: branch to checkout
:param locale_root: locale folder path
:return: tuple stdout, stderr of completed command
"""
if git_branch is None:
git_branch = settings.GIT_BRANCH
if ... |
Login into Google Docs with user authentication info. | def _login(self):
"""
Login into Google Docs with user authentication info.
"""
try:
self.gd_client = gdata.docs.client.DocsClient()
self.gd_client.ClientLogin(self.email, self.password, self.source)
except RequestError as e:
raise PODocsError(... |
Parse GDocs key from Spreadsheet url. | def _get_gdocs_key(self):
"""
Parse GDocs key from Spreadsheet url.
"""
try:
args = urlparse.parse_qs(urlparse.urlparse(self.url).query)
self.key = args['key'][0]
except KeyError as e:
raise PODocsError(e) |
Make sure temp directory exists and create one if it does not. | def _ensure_temp_path_exists(self):
"""
Make sure temp directory exists and create one if it does not.
"""
try:
if not os.path.exists(self.temp_path):
os.mkdir(self.temp_path)
except OSError as e:
raise PODocsError(e) |
Clear temp directory from created csv and ods files during communicator operations. | def _clear_temp(self):
"""
Clear temp directory from created csv and ods files during
communicator operations.
"""
temp_files = [LOCAL_ODS, GDOCS_TRANS_CSV, GDOCS_META_CSV,
LOCAL_TRANS_CSV, LOCAL_META_CSV]
for temp_file in temp_files:
fil... |
Download csv from GDoc.: return: returns resource if worksheets are present: except: raises PODocsError with info if communication with GDocs lead to any errors | def _download_csv_from_gdocs(self, trans_csv_path, meta_csv_path):
"""
Download csv from GDoc.
:return: returns resource if worksheets are present
:except: raises PODocsError with info if communication
with GDocs lead to any errors
"""
try:
en... |
Uploads file to GDocs spreadsheet. Content type can be provided as argument default is ods. | def _upload_file_to_gdoc(
self, file_path,
content_type='application/x-vnd.oasis.opendocument.spreadsheet'):
"""
Uploads file to GDocs spreadsheet.
Content type can be provided as argument, default is ods.
"""
try:
entry = self.gd_client.GetRes... |
Download csv from GDoc.: return: returns resource if worksheets are present: except: raises PODocsError with info if communication with GDocs lead to any errors | def _merge_local_and_gdoc(self, entry, local_trans_csv,
local_meta_csv, gdocs_trans_csv, gdocs_meta_csv):
"""
Download csv from GDoc.
:return: returns resource if worksheets are present
:except: raises PODocsError with info if communication with GDocs
... |
Synchronize local po files with translations on GDocs Spreadsheet. Downloads two csv files merges them and converts into po files structure. If new msgids appeared in po files this method creates new ods with appended content and sends it to GDocs. | def synchronize(self):
"""
Synchronize local po files with translations on GDocs Spreadsheet.
Downloads two csv files, merges them and converts into po files
structure. If new msgids appeared in po files, this method creates
new ods with appended content and sends it to GDocs.
... |
Download csv files from GDocs and convert them into po files structure. | def download(self):
"""
Download csv files from GDocs and convert them into po files structure.
"""
trans_csv_path = os.path.realpath(
os.path.join(self.temp_path, GDOCS_TRANS_CSV))
meta_csv_path = os.path.realpath(
os.path.join(self.temp_path, GDOCS_META_... |
Upload all po files to GDocs ignoring conflicts. This method looks for all msgids in po_files and sends them as ods to GDocs Spreadsheet. | def upload(self):
"""
Upload all po files to GDocs ignoring conflicts.
This method looks for all msgids in po_files and sends them
as ods to GDocs Spreadsheet.
"""
local_ods_path = os.path.join(self.temp_path, LOCAL_ODS)
try:
po_to_ods(self.languages, ... |
Clear GDoc Spreadsheet by sending empty csv file. | def clear(self):
"""
Clear GDoc Spreadsheet by sending empty csv file.
"""
empty_file_path = os.path.join(self.temp_path, 'empty.csv')
try:
empty_file = open(empty_file_path, 'w')
empty_file.write(',')
empty_file.close()
except IOError ... |
start a new qtconsole connected to our kernel | def new_qt_console(self, evt=None):
"""start a new qtconsole connected to our kernel"""
return connect_qtconsole(self.ipkernel.connection_file, profile=self.ipkernel.profile) |
Check whether the URL accessible and returns HTTP 200 OK or not if not raises ValidationError | def check_url_accessibility(url, timeout=10):
'''
Check whether the URL accessible and returns HTTP 200 OK or not
if not raises ValidationError
'''
if(url=='localhost'):
url = 'http://127.0.0.1'
try:
req = urllib2.urlopen(url, timeout=timeout)
if (req.getcode()==20... |
Check whether the HTML page contains the content or not and return boolean | def url_has_contents(url, contents, case_sensitive=False, timeout=10):
'''
Check whether the HTML page contains the content or not and return boolean
'''
try:
req = urllib2.urlopen(url, timeout=timeout)
except Exception, _:
False
else:
rep = req.read()
if (no... |
Visit the URL and return the HTTP response code in int | def get_response_code(url, timeout=10):
'''
Visit the URL and return the HTTP response code in 'int'
'''
try:
req = urllib2.urlopen(url, timeout=timeout)
except HTTPError, e:
return e.getcode()
except Exception, _:
fail("Couldn't reach the URL '%s'" % url)
else:
... |
Compare the content type header of url param with content_type param and returns boolean | def compare_content_type(url, content_type):
'''
Compare the content type header of url param with content_type param and returns boolean
@param url -> string e.g. http://127.0.0.1/index
@param content_type -> string e.g. text/html
'''
try:
response = urllib2.urlopen(url)
except... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.