code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
print 'Creating venv...',
run_command(['virtualenv', '-q', '--no-site-packages', VENV])
print 'done.'
print 'Installing pip in virtualenv...',
if not run_command([WITH_VENV, 'easy_install', 'pip']).strip():
die("Failed to install pip.")
print 'done.'
print 'Installing distribute... | def create_virtualenv(venv=VENV) | Creates the virtual environment and installs PIP only into the
virtual environment | 4.815047 | 5.071628 | 0.949409 |
path = str(dataset_path) # Use false_path if needed.
action = self.action_mapper.action(path, dataset_path_type)
if action.staging_needed:
if name is None:
name = os.path.basename(path)
remote_directory = self.__remote_directory(dataset_path_type... | def __remote_path_rewrite(self, dataset_path, dataset_path_type, name=None) | Return remote path of this file (if staging is required) else None. | 4.793854 | 4.379113 | 1.094709 |
retries = 0
interval_range = __fxrange(interval_start,
interval_max + interval_start,
interval_step, repeatlast=True)
for retries in count():
try:
return fun(*args, **kwargs)
except catch as exc:
if ma... | def _retry_over_time(fun, catch, args=[], kwargs={}, errback=None,
max_retries=None, interval_start=2, interval_step=2,
interval_max=30) | Retry the function over and over until max retries is exceeded.
For each retry we sleep a for a while before we try again, this interval
is increased for every retry until the max seconds is reached.
:param fun: The function to try
:param catch: Exceptions to catch, can be either tuple or a single
... | 4.628373 | 5.545827 | 0.834568 |
destination_params = _parse_destination_params(destination_params)
destination_params.update(**kwargs)
job_manager_interface_class = self.job_manager_interface_class
job_manager_interface_args = dict(destination_params=destination_params, **self.job_manager_interface_args)
... | def get_client(self, destination_params, job_id, **kwargs) | Build a client given specific destination parameters and job_id. | 2.595501 | 2.463196 | 1.053713 |
shell = self.get_shell_plugin(shell_params)
job_interface = self.get_job_interface(job_params)
return shell, job_interface | def get_plugins(self, shell_params, job_params) | Return shell and job interface defined by and configured via
specified params. | 3.18808 | 2.235772 | 1.425941 |
destination_dir = os.path.dirname(destination)
destination_name = os.path.basename(destination)
temp_destination = os.path.join(destination_dir, "%s%s" % (destination_name, tmp_suffix))
shutil.move(source, temp_destination)
os.rename(temp_destination, destination) | def atomicish_move(source, destination, tmp_suffix="_TMP") | Move source to destination without risk of partial moves.
> from tempfile import mkdtemp
> from os.path import join, exists
> temp_dir = mkdtemp()
> source = join(temp_dir, "the_source")
> destination = join(temp_dir, "the_dest")
> open(source, "wb").write(b"Hello World!")
> assert exists(s... | 1.716793 | 2.006829 | 0.855476 |
''' Return the abstraction description of an environment variable definition
into a statement for shell script.
>>> env_to_statement(dict(name='X', value='Y'))
'X="Y"; export X'
>>> env_to_statement(dict(name='X', value='Y', raw=True))
'X=Y; export X'
>>> env_to_statement(dict(name='X', val... | def env_to_statement(env) | Return the abstraction description of an environment variable definition
into a statement for shell script.
>>> env_to_statement(dict(name='X', value='Y'))
'X="Y"; export X'
>>> env_to_statement(dict(name='X', value='Y', raw=True))
'X=Y; export X'
>>> env_to_statement(dict(name='X', value='"A",... | 3.152969 | 1.343902 | 2.34613 |
temp_file = NamedTemporaryFile(delete=False)
_copy_and_close(object, temp_file)
return temp_file.name | def copy_to_temp(object) | Copy file-like object to temp file and return
path. | 3.450536 | 2.973157 | 1.160563 |
all_query_params = DEFAULT_QUERY_CLASSAD.copy()
all_query_params.update(query_params)
submit_description = []
for key, value in all_query_params.items():
submit_description.append('%s = %s' % (key, value))
submit_description.append('executable = ' + executable)
submit_description.a... | def build_submit_description(executable, output, error, user_log, query_params) | Build up the contents of a condor submit description file.
>>> submit_args = dict(executable='/path/to/script', output='o', error='e', user_log='ul')
>>> submit_args['query_params'] = dict()
>>> default_description = build_submit_description(**submit_args)
>>> assert 'executable = /path/to/script' in d... | 2.174424 | 2.343961 | 0.92767 |
external_id = None
try:
submit = Popen(('condor_submit', submit_file), stdout=PIPE, stderr=STDOUT)
message, _ = submit.communicate()
if submit.returncode == 0:
external_id = parse_external_id(message, type='condor')
else:
message = PROBLEM_PARSING_EXT... | def condor_submit(submit_file) | Submit a condor job described by the given file. Parse an external id for
the submission or return None and a reason for the failure. | 3.237281 | 2.97809 | 1.087033 |
failure_message = None
try:
check_call(('condor_rm', external_id))
except CalledProcessError:
failure_message = "condor_rm failed"
except Exception as e:
"error encountered calling condor_rm: %s" % e
return failure_message | def condor_stop(external_id) | Stop running condor job and return a failure_message if this
fails. | 3.928631 | 3.424098 | 1.147348 |
if self.lockfile:
return self.lockfile.LockFile(path)
else:
with self.job_locks_lock:
if path not in self.job_locks:
lock = threading.Lock()
self.job_locks[path] = lock
else:
lock... | def get_lock(self, path) | Get a job lock corresponding to the path - assumes parent
directory exists but the file itself does not. | 2.571878 | 2.344326 | 1.097065 |
try:
shutdown_method = self._proxied_manager.shutdown
except AttributeError:
return
shutdown_method(timeout) | def shutdown(self, timeout=None) | Optional. | 6.689794 | 6.92996 | 0.965344 |
# Have defined a remote job directory, lets do the setup locally.
if client.job_directory:
handler = LocalSetupHandler(client, destination_args)
else:
handler = RemoteSetupHandler(client)
return handler | def build(client, destination_args) | Build a SetupHandler object for client from destination parameters. | 11.408287 | 9.031449 | 1.263173 |
template = DrmaaSession.session.createJobTemplate()
try:
for key in kwds:
setattr(template, key, kwds[key])
with DrmaaSession.session_lock:
return DrmaaSession.session.runJob(template)
finally:
DrmaaSession.session.dele... | def run_job(self, **kwds) | Create a DRMAA job template, populate with specified properties,
run the job, and return the external_job_id. | 2.974736 | 2.364015 | 1.258341 |
if url.startswith("pulsar://"):
url = url[len("pulsar://"):]
if not url.endswith("/"):
url += "/"
# Check for private token embedded in the URL. A URL of the form
# https://moo@cow:8913 will try to contact https://cow:8913
# with a private key of moo
private_token_format ... | def url_to_destination_params(url) | Convert a legacy runner URL to a job destination
>>> params_simple = url_to_destination_params("http://localhost:8913/")
>>> params_simple["url"]
'http://localhost:8913/'
>>> params_simple["private_token"] is None
True
>>> advanced_url = "https://1234x@example.com:8914/managers/longqueue"
>... | 4.264085 | 3.632174 | 1.173976 |
atexit.register(_cleanup_ports, bound_addresses, maxtries=maxtries,
sleeptime=sleeptime) | def ensure_port_cleanup(bound_addresses, maxtries=30, sleeptime=2) | This makes sure any open ports are closed.
Does this by connecting to them until they give connection
refused. Servers should call like::
import paste.script
ensure_port_cleanup([80, 443]) | 3.035508 | 4.278369 | 0.709501 |
parser = BoolOptionParser()
if verbose:
parser.add_option('-v', '--verbose',
action='count',
dest='verbose',
default=0)
if quiet:
parser.add_option('-q', '--quiet',
... | def standard_parser(cls, verbose=True,
interactive=False,
no_interactive=False,
simulate=False,
quiet=False,
overwrite=False) | Create a standard ``OptionParser`` instance.
Typically used like::
class MyCommand(Command):
parser = Command.standard_parser()
Subclasses may redefine ``standard_parser``, so use the
nearest superclass's class method. | 1.922443 | 2.042213 | 0.941353 |
if (sys.platform != 'win32'
or ' ' not in arg):
# Problem does not apply:
return arg
try:
import win32api
except ImportError:
raise ValueError(
"The executable %r contains a space, and in order to "
... | def quote_first_command_arg(self, arg) | There's a bug in Windows when running an executable that's
located inside a path with a space in it. This method handles
that case, or on non-Windows systems or an executable with no
spaces, it just leaves well enough alone. | 4.711285 | 4.064234 | 1.159206 |
parser = ConfigParser.ConfigParser()
parser.read([config_file])
if parser.has_section('loggers'):
config_file = os.path.abspath(config_file)
fileConfig(config_file, dict(__file__=config_file,
here=os.path.dirname(config_fi... | def logging_file_config(self, config_file) | Setup logging via the logging module's fileConfig function with the
specified ``config_file``, if applicable.
ConfigParser defaults are specified for the special ``__file__``
and ``here`` variables, similar to PasteDeploy config loading. | 2.997156 | 2.282507 | 1.313099 |
collection_failure_exceptions = []
if job_completed_normally:
output_collector = ClientOutputCollector(client)
action_mapper = FileActionMapper(client)
results_stager = ResultsCollector(output_collector, action_mapper, client_outputs, pulsar_outputs)
collection_failure_excep... | def finish_job(client, cleanup_job, job_completed_normally, client_outputs, pulsar_outputs) | Process for "un-staging" a complete Pulsar job.
This function is responsible for downloading results from remote
server and cleaning up Pulsar staging directory (if needed.) | 4.972898 | 4.724848 | 1.052499 |
source = os.path.abspath(source)
destination = os.path.abspath(destination)
if source != destination:
if not os.path.exists(os.path.dirname(destination)):
os.makedirs(os.path.dirname(destination))
shutil.copyfile(source, destination) | def copy(source, destination) | Copy file from source to destination if needed (skip if source
is destination). | 1.723889 | 1.735819 | 0.993127 |
try:
super(BaseDrmaaManager, self).shutdown(timeout)
except Exception:
pass
self.drmaa_session.close() | def shutdown(self, timeout=None) | Cleanup DRMAA session and call shutdown of parent. | 5.659415 | 3.732976 | 1.51606 |
destination = self.__destination(ip, path)
atomicish_move(local_path, destination) | def cache_file(self, local_path, ip, path) | Move a file from a temporary staging area into the cache. | 14.113071 | 11.825396 | 1.193454 |
# Load default options from config file that apply to all
# managers.
default_options = _get_default_options(conf)
manager_descriptions = ManagerDescriptions()
if "job_managers_config" in conf:
job_managers_config = conf.get("job_managers_config", None)
_populate_manager_descri... | def build_managers(app, conf) | Takes in a config file as outlined in job_managers.ini.sample and builds
a dictionary of job manager objects from them. | 2.412553 | 2.287035 | 1.054883 |
if exc_info is None:
exc_info = sys.exc_info()
if (exc_info[0] != TypeError
or str(exc_info[1]).find('arguments') == -1
or getattr(exc_info[1], '_type_error_fixed', False)):
return exc_info
exc_info[1]._type_error_fixed = True
argspec = inspect.formatargspec(*inspect... | def fix_type_error(exc_info, callable, varargs, kwargs) | Given an exception, this will test if the exception was due to a
signature error, and annotate the error with better information if
so.
Usage::
try:
val = callable(*args, **kw)
except TypeError:
exc_info = fix_type_error(None, callable, args, kw)
raise exc_info[0]... | 2.63078 | 2.703548 | 0.973084 |
try:
val = callable(*args, **kw)
except TypeError:
exc_info = fix_type_error(None, callable, args, kw)
reraise(*exc_info)
return val | def fix_call(callable, *args, **kw) | Call ``callable(*args, **kw)`` fixing any type errors that come out. | 3.571508 | 3.607892 | 0.989915 |
parts, target = spec.split(':') if ':' in spec else (spec, None)
module = __import__(parts)
for part in parts.split('.')[1:] + ([target] if target else []):
module = getattr(module, part)
return module | def lookup_object(spec) | Looks up a module or object from a some.module:func_name specification.
To just look up a module, omit the colon and everything after it. | 3.414447 | 2.997262 | 1.139188 |
if not isinstance(lst, (list, tuple)):
return [lst]
result = []
for item in lst:
result.extend(_flatten(item))
return result | def _flatten(lst) | Flatten a nested list. | 2.050365 | 1.871405 | 1.095629 |
defaults = ConfigParser.defaults(self).copy()
for key, val in iteritems(defaults):
defaults[key] = self.get('DEFAULT', key) or val
return defaults | def defaults(self) | Return the defaults, with their values interpolated (with the
defaults dict itself)
Mainly to support defaults using values such as %(here)s | 5.451375 | 4.826343 | 1.129504 |
possible = []
for name_options in object_type.config_prefixes:
for name_prefix in name_options:
found = self._find_sections(
self.parser.sections(), name_prefix, name)
if found:
possible.extend(found)
... | def find_config_section(self, object_type, name=None) | Return the section name with the given name prefix (following the
same pattern as ``protocol_desc`` in ``config``. It must have the
given name, or for ``'main'`` an empty name is allowed. The
prefix must be followed by a ``:``.
Case is *not* ignored. | 2.621067 | 2.701004 | 0.970405 |
if name is None:
name = 'main'
possible = []
for protocol_options in object_type.egg_protocols:
for protocol in protocol_options:
pkg_resources.require(self.spec)
entry = pkg_resources.get_entry_info(
self.spec,... | def find_egg_entry_point(self, object_type, name=None) | Returns the (entry_point, protocol) for the with the given
``name``. | 3.499435 | 3.421156 | 1.022881 |
directory, allow_nested_files = self._directory_for_file_type(input_type)
return self.path_helper.remote_join(directory, remote_relative_path) | def calculate_path(self, remote_relative_path, input_type) | Only for used by Pulsar client, should override for managers to
enforce security and make the directory if needed. | 7.189718 | 6.728343 | 1.068572 |
job_directory = self._proxied_manager.job_directory(job_id)
with job_directory.lock("status"):
proxy_status, state_change = self.__proxy_status(job_directory, job_id)
if state_change == "to_complete":
self.__deactivate(job_id, proxy_status)
elif state_ch... | def get_status(self, job_id) | Compute status used proxied manager and handle state transitions
and track additional state information needed. | 5.13112 | 4.229001 | 1.213317 |
state_change = None
if job_directory.has_metadata(JOB_FILE_PREPROCESSING_FAILED):
proxy_status = status.FAILED
job_directory.store_metadata(JOB_FILE_FINAL_STATUS, proxy_status)
state_change = "to_complete"
elif not job_directory.has_metadata(JOB_FILE_... | def __proxy_status(self, job_directory, job_id) | Determine state with proxied job manager and if this job needs
to be marked as deactivated (this occurs when job first returns a
complete status from proxy. | 2.404768 | 2.299679 | 1.045697 |
if proxy_status == status.COMPLETE:
if not job_directory.has_metadata(JOB_FILE_POSTPROCESSED):
job_status = status.POSTPROCESSING
else:
job_status = status.COMPLETE
else:
job_status = proxy_status
return job_status | def __status(self, job_directory, proxy_status) | Use proxied manager's status to compute the real
(stateful) status of job. | 3.699018 | 3.76537 | 0.982378 |
output_directory = dirname(output_file)
def local_path(name):
return join(output_directory, self.path_helper.local_name(name))
files_directory = "%s_files%s" % (basename(output_file)[0:-len(".dat")], self.path_helper.separator)
names = filter(lambda o: o.startswith... | def output_extras(self, output_file) | Returns dict mapping local path to remote name. | 4.518196 | 3.890561 | 1.161322 |
user = kwargs.get("user", None)
full_command = [SUDO_PATH, SUDO_PRESERVE_ENVIRONMENT_ARG]
if user:
full_command.extend([SUDO_USER_ARG, user])
full_command.extend(args)
log.info("About to execute the following sudo command - [%s]" % ' '.join(full_command))
p = Popen(full_command, she... | def sudo_popen(*args, **kwargs) | Helper method for building and executing Popen command. This is potentially
sensetive code so should probably be centralized. | 3.406592 | 3.293792 | 1.034246 |
# Normally, we have separate buckets for bugfixes vs features
keys = ['unreleased_bugfix', 'unreleased_feature']
# But unstable prehistorical releases roll all up into just
# 'unreleased'
if major_number == 0 and self.config.releases_unstable_prehistory:
keys... | def add_family(self, major_number) | Expand to a new release line with given ``major_number``.
This will flesh out mandatory buckets like ``unreleased_bugfix`` and do
other necessary bookkeeping. | 11.469995 | 8.991807 | 1.275605 |
nonzeroes = self.stable_families
# Nothing but 0.x releases -> yup we're prehistory
if not nonzeroes:
return False
# Presumably, if there's >1 major family besides 0.x, we're at least
# one release into the 1.0 (or w/e) line.
if len(nonzeroes) > 1:
... | def has_stable_releases(self) | Returns whether stable (post-0.x) releases seem to exist. | 13.416802 | 11.850894 | 1.132134 |
app, doctree = get_doctree(path, **kwargs)
# Have to semi-reproduce the 'find first bullet list' bit from main code,
# which is unfortunately side-effect-heavy (thanks to Sphinx plugin
# design).
first_list = None
for node in doctree[0]:
if isinstance(node, bullet_list):
... | def parse_changelog(path, **kwargs) | Load and parse changelog file from ``path``, returning data structures.
This function does not alter any files on disk; it is solely for
introspecting a Releases ``changelog.rst`` and programmatically answering
questions like "are there any unreleased bugfixes for the 2.3 line?" or
"what was included i... | 9.781712 | 8.245763 | 1.186271 |
root, filename = os.path.split(path)
docname, _ = os.path.splitext(filename)
# TODO: this only works for top level changelog files (i.e. ones where
# their dirname is the project/doc root)
app = make_app(srcdir=root, **kwargs)
# Create & init a BuildEnvironment. Mm, tasty side effects.
... | def get_doctree(path, **kwargs) | Obtain a Sphinx doctree from the RST file at ``path``.
Performs no Releases-specific processing; this code would, ideally, be in
Sphinx itself, but things there are pretty tightly coupled. So we wrote
this.
Any additional kwargs are passed unmodified into an internal `make_app`
call.
:param s... | 7.638913 | 7.545149 | 1.012427 |
path = os.path.join(srcdir, 'conf.py')
mylocals = {'__file__': path}
with open(path) as fd:
exec(fd.read(), mylocals)
return mylocals | def load_conf(srcdir) | Load ``conf.py`` from given ``srcdir``.
:returns: Dictionary derived from the conf module. | 2.78579 | 3.429704 | 0.812254 |
if config.releases_debug:
sys.stderr.write(str(txt) + "\n")
sys.stderr.flush() | def _log(txt, config) | Log debug output if debug setting is on.
Intended to be partial'd w/ config at top of functions. Meh. | 5.394867 | 5.899962 | 0.91439 |
# Both 'spec' formats are wrapped in parens, discard
keyword = keyword.lstrip('(').rstrip(')')
# First, test for intermediate '1.2+' style
matches = release_line_re.findall(keyword)
if matches:
return Spec(">={}".format(matches[0]))
# Failing that, see if Spec can make sense of it
... | def scan_for_spec(keyword) | Attempt to return some sort of Spec from given keyword value.
Returns None if one could not be derived. | 10.151663 | 10.714064 | 0.947508 |
parts = utils.unescape(text).split()
issue_no = parts.pop(0)
# Lol @ access back to Sphinx
config = inliner.document.settings.env.app.config
if issue_no not in ('-', '0'):
ref = None
if config.releases_issue_uri:
# TODO: deal with % vs .format()
ref = con... | def issues_role(name, rawtext, text, lineno, inliner, options={}, content=[]) | Use: :issue|bug|feature|support:`ticket_number`
When invoked as :issue:, turns into just a "#NN" hyperlink to
`releases_issue_uri`.
When invoked otherwise, turns into "[Type] <#NN hyperlink>: ".
Spaces present in the "ticket number" are used as fields for keywords
(major, backported) and/or specs... | 5.950758 | 5.505797 | 1.080817 |
# Make sure year has been specified
match = year_arg_re.match(text)
if not match:
msg = inliner.reporter.error("Must specify release date!")
return [inliner.problematic(rawtext, rawtext, msg)], [msg]
number, date = match.group(1), match.group(2)
# Lol @ access back to Sphinx
... | def release_role(name, rawtext, text, lineno, inliner, options={}, content=[]) | Invoked as :release:`N.N.N <YYYY-MM-DD>`.
Turns into useful release header + link to GH tree for the tag. | 5.564233 | 5.888581 | 0.944919 |
for family, lines in six.iteritems(manager):
for type_ in ('bugfix', 'feature'):
bucket = 'unreleased_{}'.format(type_)
if bucket not in lines: # Implies unstable prehistory + 0.x fam
continue
issues = lines[bucket]
fam_prefix = "{}.x ".fo... | def append_unreleased_entries(app, manager, releases) | Generate new abstract 'releases' for unreleased issues.
There's one for each combination of bug-vs-feature & major release line.
When only one major release line exists, that dimension is ignored. | 8.302969 | 8.357584 | 0.993465 |
order = {'feature': 0, 'bug': 1, 'support': 2}
for release in releases:
entries = release['entries'][:]
release['entries'] = sorted(entries, key=lambda x: order[x.type]) | def reorder_release_entries(releases) | Mutate ``releases`` so the entrylist in each is ordered by feature/bug/etc. | 3.37888 | 2.588592 | 1.305297 |
# It's remotely possible the changelog is totally empty...
if not entries:
return
# Obtain (short-circuiting) first Release obj.
first_release = None
for obj in entries:
if isinstance(obj, Release):
first_release = obj
break
# It's also possible it's ... | def handle_first_release_line(entries, manager) | Set up initial line-manager entry for first encountered release line.
To be called at start of overall process; afterwards, subsequent major
lines are generated by `handle_upcoming_major_release`. | 9.571242 | 9.846697 | 0.972026 |
# TODO: yea deffo need a real object for 'manager', heh. E.g. we do a
# very similar test for "do you have any actual releases yet?"
# elsewhere. (This may be fodder for changing how we roll up
# pre-major-release features though...?)
return [
key for key, va... | def minor_releases(self, manager) | Return all minor release line labels found in ``manager``. | 22.908356 | 21.458511 | 1.067565 |
# TODO: I feel like this + the surrounding bits in add_to_manager()
# could be consolidated & simplified...
specstr = ""
# Make sure truly-default spec skips 0.x if prehistory was unstable.
stable_families = manager.stable_families
if manager.config.releases_unst... | def default_spec(self, manager) | Given the current release-lines structure, return a default Spec.
Specifics:
* For feature-like issues, only the highest major release is used, so
given a ``manager`` with top level keys of ``[1, 2]``, this would
return ``Spec(">=2")``.
* When ``releases_always_forward... | 13.320141 | 8.454879 | 1.575438 |
# Derive version spec allowing us to filter against major/minor buckets
spec = self.spec or self.default_spec(manager)
# Only look in appropriate major version/family; if self is an issue
# declared as living in e.g. >=2, this means we don't even bother
# looking in the ... | def add_to_manager(self, manager) | Given a 'manager' structure, add self to one or more of its 'buckets'. | 12.054793 | 11.713981 | 1.029095 |
reader = Rtf15Reader(source, errors, clean_paragraphs)
return reader.go() | def read(self, source, errors='strict', clean_paragraphs=True) | source: A list of P objects. | 8.99828 | 9.109562 | 0.987784 |
runs = self.block.content
if not runs:
self.block = None
return
if not self.clean_paragraphs:
return
joinedRuns = []
hasContent = False
for run in runs:
if run.content[0]:
hasContent = True
... | def cleanParagraph(self) | Compress text runs, remove whitespace at start and end,
skip empty blocks, etc | 3.71201 | 3.471352 | 1.069327 |
rulesets = self.ruleset_re.findall(css)
for (selector, declarations) in rulesets:
rule = Rule(self.parse_selector(selector))
rule.properties = self.parse_declarations(declarations)
self.rules.append(rule) | def parse_css(self, css) | Parse a css style sheet into the CSS object.
For the moment this will only work for very simple css
documents. It works by using regular expression matching css
syntax. This is not bullet proof. | 3.176522 | 3.48911 | 0.910411 |
declarations = self.declaration_re.findall(declarations)
return dict(declarations) | def parse_declarations(self, declarations) | parse a css declaration list | 7.928678 | 6.245009 | 1.269602 |
tag, klass = self.selector_re.match(selector).groups()
return Selector(tag, klass) | def parse_selector(self, selector) | parse a css selector | 6.127836 | 5.908781 | 1.037073 |
ret = {}
# Try all the rules one by one
for rule in self.rules:
if rule.selector(node):
ret.update(rule.properties)
# Also search for direct 'style' arguments in the html doc
for style_node in node.findParents(attrs={'style': True}):
... | def get_properties(self, node) | return a dict of all the properties of a given BeautifulSoup
node found by applying the css style. | 6.121821 | 5.155756 | 1.187376 |
topLevel = __import__(name)
packages = name.split(".")[1:]
m = topLevel
for p in packages:
m = getattr(m, p)
return m | def namedModule(name) | Return a module given its name. | 3.177574 | 3.050545 | 1.041641 |
classSplit = name.split('.')
module = namedModule('.'.join(classSplit[:-1]))
return getattr(module, classSplit[-1]) | def namedObject(name) | Get a fully named module-global object. | 4.726611 | 4.758472 | 0.993304 |
ret = u"".join(text.content)
if 'url' in text.properties:
return u"`%s`_" % ret
if 'bold' in text.properties:
return u"**%s**" % ret
if 'italic' in text.properties:
return u"*%s*" % ret
if 'sub' in text.properties:
return u... | def text(self, text) | process a pyth text and return the formatted string | 2.813033 | 2.74017 | 1.026591 |
content = []
for text in paragraph.content:
content.append(self.text(text))
content = u"".join(content).encode("utf-8")
for line in content.split("\n"):
self.target.write(" " * self.indent)
self.target.write(prefix)
self.target.w... | def paragraph(self, paragraph, prefix="") | process a pyth paragraph into the target | 2.806448 | 2.733048 | 1.026857 |
self.indent += 1
for (i, entry) in enumerate(list.content):
for (j, paragraph) in enumerate(entry.content):
prefix = "- " if j == 0 else " "
handler = self.paragraphDispatch[paragraph.__class__]
handler(paragraph, prefix)
... | def list(self, list, prefix=None) | Process a pyth list into the target | 4.9511 | 4.682887 | 1.057275 |
# Remove all the newline characters before a closing tag.
for node in soup.findAll(text=True):
if node.rstrip(" ").endswith("\n"):
node.replaceWith(node.rstrip(" ").rstrip("\n"))
# Join the block elements lines into a single long line
for tag in ['p',... | def format(self, soup) | format a BeautifulSoup document
This will transform the block elements content from
multi-lines text into single line.
This allow us to avoid having to deal with further text
rendering once this step has been done. | 3.406382 | 3.200675 | 1.06427 |
a_node = node.findParent('a')
if not a_node:
return None
if self.link_callback is None:
return a_node.get('href')
else:
return self.link_callback(a_node.get('href')) | def url(self, node) | return the url of a BeautifulSoup node or None if there is no
url. | 3.183634 | 2.986357 | 1.06606 |
text = node.string.strip()
if not text:
return
# Set all the properties
properties=dict()
if self.is_bold(node):
properties['bold'] = True
if self.is_italic(node):
properties['italic'] = True
if self.url(node):
... | def process_text(self, node) | Return a pyth Text object from a BeautifulSoup node or None if
the text is empty. | 3.159038 | 3.014474 | 1.047957 |
if isinstance(node, BeautifulSoup.NavigableString):
text = self.process_text(node)
if text:
obj.append(text)
return
if node.name == 'p':
# add a new paragraph into the pyth object
new_obj = document.Paragraph()
... | def process_into(self, node, obj) | Process a BeautifulSoup node and fill its elements into a pyth
base object. | 2.315276 | 2.063983 | 1.121751 |
okay = True
if not isinstance(item, self.contentType):
if hasattr(self.contentType, 'contentType'):
try:
item = self.contentType(content=[item])
except TypeError:
okay = False
else:
... | def append(self, item) | Try to add an item to this element.
If the item is of the wrong type, and if this element has a sub-type,
then try to create such a sub-type and insert the item into that, instead.
This happens recursively, so (in python-markup):
L [ u'Foo' ]
actually creates:
... | 3.597485 | 2.918385 | 1.232697 |
class MagicGetItem(type):
def __new__(mcs, name, bases, dict):
klass = type.__new__(mcs, name, bases, dict)
mcs.__getitem__ = lambda _, k: klass()[k]
return klass
return MagicGetItem | def _MetaPythonBase() | Return a metaclass which implements __getitem__,
allowing e.g. P[...] instead of P()[...] | 4.580749 | 3.848659 | 1.19022 |
writer = LatexWriter(document, target, stylesheet)
return writer.go() | def write(klass, document, target=None, stylesheet="") | convert a pyth document to a latex document
we can specify a stylesheet as a latex document fragment that
will be inserted after the headers. This way we can override
the default style. | 14.064671 | 10.954391 | 1.28393 |
latex_fragment = r % (self.document.properties.get("title"),
self.document.properties.get("author"),
self.document.properties.get("subject"))
return latex_fragment + self.stylesheet | def full_stylesheet(self) | Return the style sheet that will ultimately be inserted into
the latex document.
This is the user given style sheet plus some additional parts
to add the meta data. | 7.021184 | 6.006565 | 1.168918 |
url = self.api_url + '/v2/project/' + self.api_key + '/session/' + session_id + '/stream'
if stream_id:
url = url + '/' + stream_id
return url | def get_stream_url(self, session_id, stream_id=None) | this method returns the url to get streams information | 2.798815 | 2.670093 | 1.048209 |
url = (
self.api_url + '/v2/project/' + self.api_key + '/session/' +
session_id + '/connection/' + connection_id
)
return url | def force_disconnect_url(self, session_id, connection_id) | this method returns the force disconnect url endpoint | 4.019549 | 3.896175 | 1.031666 |
url = self.api_url + '/v2/project/' + self.api_key + '/archive/' + archive_id + '/layout'
return url | def set_archive_layout_url(self, archive_id) | this method returns the url to set the archive layout | 4.082083 | 3.518374 | 1.160219 |
url = self.api_url + '/v2/project/' + self.api_key + '/session/' + session_id + '/stream'
return url | def set_stream_class_lists_url(self, session_id) | this method returns the url to set the stream class list | 4.610386 | 3.952464 | 1.166459 |
url = self.api_url + '/v2/project/' + self.api_key + '/broadcast'
if broadcast_id:
url = url + '/' + broadcast_id
if stop:
url = url + '/stop'
if layout:
url = url + '/layout'
return url | def broadcast_url(self, broadcast_id=None, stop=False, layout=False) | this method returns urls for working with broadcast | 2.406615 | 2.396584 | 1.004185 |
temp_archive = self.sdk.stop_archive(self.id)
for k,v in iteritems(temp_archive.attrs()):
setattr(self, k, v) | def stop(self) | Stops an OpenTok archive that is being recorded.
Archives automatically stop recording after 120 minutes or when all clients have
disconnected from the session being archived. | 8.651783 | 6.809573 | 1.270532 |
return dict((k, v) for k, v in iteritems(self.__dict__) if k is not "sdk") | def attrs(self) | Returns a dictionary of the archive's attributes. | 7.536469 | 7.081398 | 1.064263 |
if not isinstance(output_mode, OutputModes):
raise OpenTokException(u('Cannot start archive, {0} is not a valid output mode').format(output_mode))
if resolution and output_mode == OutputModes.individual:
raise OpenTokException(u('Invalid parameters: Resolution cannot b... | def start_archive(self, session_id, has_audio=True, has_video=True, name=None, output_mode=OutputModes.composed, resolution=None) | Starts archiving an OpenTok session.
Clients must be actively connected to the OpenTok session for you to successfully start
recording an archive.
You can only record one archive at a time for a given session. You can only record archives
of sessions that use the OpenTok Media Router (... | 2.467313 | 2.486338 | 0.992348 |
response = requests.post(self.endpoints.archive_url(archive_id) + '/stop', headers=self.json_headers(), proxies=self.proxies, timeout=self.timeout)
if response.status_code < 300:
return Archive(self, response.json())
elif response.status_code == 403:
raise AuthE... | def stop_archive(self, archive_id) | Stops an OpenTok archive that is being recorded.
Archives automatically stop recording after 90 minutes or when all clients have disconnected
from the session being archived.
@param [String] archive_id The archive ID of the archive you want to stop recording.
:rtype: The Archive objec... | 2.578442 | 2.668213 | 0.966355 |
response = requests.delete(self.endpoints.archive_url(archive_id), headers=self.json_headers(), proxies=self.proxies, timeout=self.timeout)
if response.status_code < 300:
pass
elif response.status_code == 403:
raise AuthError()
elif response.status_code ... | def delete_archive(self, archive_id) | Deletes an OpenTok archive.
You can only delete an archive which has a status of "available" or "uploaded". Deleting an
archive removes its record from the list of archives. For an "available" archive, it also
removes the archive file, making it unavailable for download.
:param String ... | 2.697338 | 2.784897 | 0.968559 |
response = requests.get(self.endpoints.archive_url(archive_id), headers=self.json_headers(), proxies=self.proxies, timeout=self.timeout)
if response.status_code < 300:
return Archive(self, response.json())
elif response.status_code == 403:
raise AuthError()
... | def get_archive(self, archive_id) | Gets an Archive object for the given archive ID.
:param String archive_id: The archive ID.
:rtype: The Archive object. | 2.56777 | 2.67794 | 0.95886 |
params = {}
if offset is not None:
params['offset'] = offset
if count is not None:
params['count'] = count
if session_id is not None:
params['sessionId'] = session_id
endpoint = self.endpoints.archive_url() + "?" + urlencode(params)
... | def get_archives(self, offset=None, count=None, session_id=None) | Returns an ArchiveList, which is an array of archives that are completed and in-progress,
for your API key.
:param int: offset Optional. The index offset of the first archive. 0 is offset
of the most recently started archive. 1 is the offset of the archive that started prior to
the ... | 2.231026 | 2.272151 | 0.9819 |
return self.get_archives(offset, count, session_id) | def list_archives(self, offset=None, count=None, session_id=None) | New method to get archive list, it's alternative to 'get_archives()',
both methods exist to have backwards compatible | 6.154799 | 3.963716 | 1.552785 |
response = requests.post(
self.endpoints.signaling_url(session_id, connection_id),
data=json.dumps(payload),
headers=self.json_headers(),
proxies=self.proxies,
timeout=self.timeout
)
if response.status_code == 204:
... | def signal(self, session_id, payload, connection_id=None) | Send signals to all participants in an active OpenTok session or to a specific client
connected to that session.
:param String session_id: The session ID of the OpenTok session that receives the signal
:param Dictionary payload: Structure that contains both the type and data fields. These
... | 3.300059 | 3.18794 | 1.03517 |
endpoint = self.endpoints.get_stream_url(session_id, stream_id)
response = requests.get(
endpoint, headers=self.json_headers(), proxies=self.proxies, timeout=self.timeout
)
if response.status_code == 200:
return Stream(response.json())
elif respo... | def get_stream(self, session_id, stream_id) | Returns an Stream object that contains information of an OpenTok stream:
-id: The stream ID
-videoType: "camera" or "screen"
-name: The stream name (if one was set when the client published the stream)
-layoutClassList: It's an array of the layout classes for the stream | 3.679168 | 3.761736 | 0.978051 |
endpoint = self.endpoints.get_stream_url(session_id)
response = requests.get(
endpoint, headers=self.json_headers(), proxies=self.proxies, timeout=self.timeout
)
if response.status_code == 200:
return StreamList(response.json())
elif response.st... | def list_streams(self, session_id) | Returns a list of Stream objects that contains information of all
the streams in a OpenTok session, with the following attributes:
-count: An integer that indicates the number of streams in the session
-items: List of the Stream objects | 4.305817 | 4.611124 | 0.933789 |
endpoint = self.endpoints.force_disconnect_url(session_id, connection_id)
response = requests.delete(
endpoint, headers=self.json_headers(), proxies=self.proxies, timeout=self.timeout
)
if response.status_code == 204:
pass
elif response.status_co... | def force_disconnect(self, session_id, connection_id) | Sends a request to disconnect a client from an OpenTok session
:param String session_id: The session ID of the OpenTok session from which the
client will be disconnected
:param String connection_id: The connection ID of the client that will be disconnected | 3.203261 | 3.194299 | 1.002805 |
payload = {
'type': layout_type,
}
if layout_type == 'custom':
if stylesheet is not None:
payload['stylesheet'] = stylesheet
endpoint = self.endpoints.set_archive_layout_url(archive_id)
response = requests.put(
endpo... | def set_archive_layout(self, archive_id, layout_type, stylesheet=None) | Use this method to change the layout of videos in an OpenTok archive
:param String archive_id: The ID of the archive that will be updated
:param String layout_type: The layout type for the archive. Valid values are:
'bestFit', 'custom', 'horizontalPresentation', 'pip' and 'verticalPresentation... | 3.722643 | 3.843911 | 0.968452 |
payload = {
'sessionId': session_id,
'token': token,
'sip': {
'uri': sip_uri
}
}
if 'from' in options:
payload['sip']['from'] = options['from']
if 'headers' in options:
payload['sip']['head... | def dial(self, session_id, token, sip_uri, options=[]) | Use this method to connect a SIP platform to an OpenTok session. The audio from the end
of the SIP call is added to the OpenTok session as an audio-only stream. The OpenTok Media
Router mixes audio from other streams in the session and sends the mixed audio to the SIP
endpoint
:param St... | 2.331556 | 2.176618 | 1.071183 |
items_payload = {'items': payload}
endpoint = self.endpoints.set_stream_class_lists_url(session_id)
response = requests.put(
endpoint,
data=json.dumps(items_payload),
headers=self.json_headers(),
proxies=self.proxies,
timeout=... | def set_stream_class_lists(self, session_id, payload) | Use this method to change layout classes for OpenTok streams. The layout classes
define how the streams are displayed in the layout of a composed OpenTok archive
:param String session_id: The ID of the session of the streams that will be updated
:param List payload: A list defining the class l... | 4.025008 | 4.190212 | 0.960574 |
payload = {
'sessionId': session_id
}
payload.update(options)
endpoint = self.endpoints.broadcast_url()
response = requests.post(
endpoint,
data=json.dumps(payload),
headers=self.json_headers(),
proxies=self.p... | def start_broadcast(self, session_id, options) | Use this method to start a live streaming for an OpenTok session. This broadcasts the
session to an HLS (HTTP live streaming) or to RTMP streams. To successfully start
broadcasting a session, at least one client must be connected to the session. You can only
start live streaming for sessions tha... | 3.955947 | 4.021016 | 0.983818 |
endpoint = self.endpoints.broadcast_url(broadcast_id, stop=True)
response = requests.post(
endpoint,
headers=self.json_headers(),
proxies=self.proxies,
timeout=self.timeout
)
if response.status_code == 200:
return Broa... | def stop_broadcast(self, broadcast_id) | Use this method to stop a live broadcast of an OpenTok session
:param String broadcast_id: The ID of the broadcast you want to stop
:rtype A Broadcast object, which contains information of the broadcast: id, sessionId
projectId, createdAt, updatedAt and resolution | 3.525816 | 3.618922 | 0.974272 |
endpoint = self.endpoints.broadcast_url(broadcast_id)
response = requests.get(
endpoint,
headers=self.json_headers(),
proxies=self.proxies,
timeout=self.timeout
)
if response.status_code == 200:
return Broadcast(respon... | def get_broadcast(self, broadcast_id) | Use this method to get details on a broadcast that is in-progress.
:param String broadcast_id: The ID of the broadcast you want to stop
:rtype A Broadcast object, which contains information of the broadcast: id, sessionId
projectId, createdAt, updatedAt, resolution, broadcastUrls and status | 3.546689 | 3.834526 | 0.924936 |
payload = {
'type': layout_type,
}
if layout_type == 'custom':
if stylesheet is not None:
payload['stylesheet'] = stylesheet
endpoint = self.endpoints.broadcast_url(broadcast_id, layout=True)
response = requests.put(
... | def set_broadcast_layout(self, broadcast_id, layout_type, stylesheet=None) | Use this method to change the layout type of a live streaming broadcast
:param String broadcast_id: The ID of the broadcast that will be updated
:param String layout_type: The layout type for the broadcast. Valid values are:
'bestFit', 'custom', 'horizontalPresentation', 'pip' and 'verticalPre... | 3.572406 | 3.857777 | 0.926027 |
'''Authenticate using XAuth variant of OAuth.
:param str username: Username or email address for the relevant account
:param str password: Password for the account
'''
response = self.request(
ACCESS_TOKEN,
{
'x_auth_mode': 'client_auth',
... | def login(self, username, password) | Authenticate using XAuth variant of OAuth.
:param str username: Username or email address for the relevant account
:param str password: Password for the account | 4.034544 | 2.893011 | 1.394583 |
'''Process a request using the OAuth client's request method.
:param str path: Path fragment to the API endpoint, e.g. "resource/ID"
:param dict params: Parameters to pass to request
:param str method: Optional HTTP method, normally POST for Instapaper
:param str api_version: Op... | def request(self, path, params=None, returns_json=True,
method='POST', api_version=API_VERSION) | Process a request using the OAuth client's request method.
:param str path: Path fragment to the API endpoint, e.g. "resource/ID"
:param dict params: Parameters to pass to request
:param str method: Optional HTTP method, normally POST for Instapaper
:param str api_version: Optional alte... | 4.316513 | 2.91859 | 1.478972 |
path = 'bookmarks/list'
params = {'folder_id': folder, 'limit': limit}
if have:
have_concat = ','.join(str(id_) for id_ in have)
params['have'] = have_concat
response = self.request(path, params)
items = response['data']
bookmarks = []
... | def get_bookmarks(self, folder='unread', limit=25, have=None) | Return list of user's bookmarks.
:param str folder: Optional. Possible values are unread (default),
starred, archive, or a folder_id value.
:param int limit: Optional. A number between 1 and 500, default 25.
:param list have: Optional. A list of IDs to exclude from results
:... | 2.511766 | 2.565731 | 0.978967 |
path = 'folders/list'
response = self.request(path)
items = response['data']
folders = []
for item in items:
if item.get('type') == 'error':
raise Exception(item.get('message'))
elif item.get('type') == 'folder':
fo... | def get_folders(self) | Return list of user's folders.
:rtype: list | 2.984089 | 3.010618 | 0.991188 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.