code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
rng = self.rev_range(from_revision, to_revision)
GIT_COMMIT_FIELDS = ['id', 'subject', 'body']
GIT_LOG_FORMAT = ['%h', '%s', '%b']
GIT_LOG_FORMAT = '%x1f'.join(GIT_LOG_FORMAT) + '%x1e'
log_out = self('log', '--format=%s' % GIT_LOG_FORMAT, rng,
log_... | def get_commit_bzs(self, from_revision, to_revision=None) | Return a list of tuples, one per commit. Each tuple is (sha1, subject,
bz_list). bz_list is a (possibly zero-length) list of numbers. | 3.007662 | 2.881431 | 1.043809 |
'''Return the value of a git configuration option. This will
return the value of the default parameter (which defaults to
None) if the given option does not exist.'''
try:
return self("config", "--get", param,
log_fail=False, log_cmd=False)
e... | def config_get(self, param, default=None) | Return the value of a git configuration option. This will
return the value of the default parameter (which defaults to
None) if the given option does not exist. | 6.917081 | 3.248989 | 2.128995 |
parser = configparser.ConfigParser()
if config_file is None:
# fallback to default user config file
config_file = os.path.join(os.getenv("HOME"), DEFAULT_USER_INI)
if not os.path.isfile(config_file):
config_file = None
else:
if not os.path.isfile(config_file)... | def get_configuration(config_file=None) | Return an initialized ConfigParser.
If no config filename is presented, `DEFAULT_USER_INI` is used if present.
Also reads the built-in presets.
:param config_file: string path | 2.953373 | 2.723575 | 1.084374 |
client_names = cfg.get("dyndnsc", "configs").split(",")
_preset_prefix = "preset:"
_use_preset = "use_preset"
for client_name in (x.strip() for x in client_names if x.strip()):
client_cfg_dict = dict(cfg.items(client_name))
if cfg.has_option(client_name, _use_preset):
pr... | def _iraw_client_configs(cfg) | Generate (client_name, client_cfg_dict) tuples from the configuration.
Conflates the presets and removes traces of the preset configuration
so that the returned dict can be used directly on a dyndnsc factory.
:param cfg: ConfigParser | 3.458791 | 3.104806 | 1.114012 |
collected_configs = {}
_updater_str = "updater"
_detector_str = "detector"
_dash = "-"
for client_name, client_cfg_dict in _iraw_client_configs(cfg):
detector_name = None
detector_options = {}
updater_name = None
updater_options = {}
collected_config = {}... | def collect_config(cfg) | Construct configuration dictionary from configparser.
Resolves presets and returns a dictionary containing:
.. code-block:: bash
{
"client_name": {
"detector": ("detector_name", detector_opts),
"updater": [
("updater_name", updater_opts)... | 2.694217 | 2.582974 | 1.043068 |
if PY3: # py23
import subprocess # noqa: S404 @UnresolvedImport pylint: disable=import-error
else:
import commands as subprocess # @UnresolvedImport pylint: disable=import-error
try:
theip = subprocess.getoutput(self.opts_command) # noqa: S605
... | def detect(self) | Detect and return the IP address. | 5.199809 | 4.41595 | 1.177506 |
flavours = {
"opendns": {
AF_INET: {
"@": ("resolver1.opendns.com", "resolver2.opendns.com"),
"qname": "myip.opendns.com",
"rdtype": "A",
},
AF_INET6: {
"@": ("resolver1.ipv6-sandbox.opendns.com", "resol... | def find_ip(family=AF_INET, flavour="opendns") | Find the publicly visible IP address of the current system.
This uses public DNS infrastructure that implement a special DNS "hack" to
return the IP address of the requester rather than some other address.
:param family: address family, optional, default AF_INET (ipv4)
:param flavour: selector for pub... | 3.007882 | 3.319486 | 0.906129 |
theip = find_ip(family=self.opts_family)
self.set_current_value(theip)
return theip | def detect(self) | Detect the WAN IP of the current process through DNS.
Depending on the 'family' option, either ipv4 or ipv6 resolution is
carried out.
:return: ip address | 17.110733 | 12.700471 | 1.347252 |
self._oldvalue = self.get_current_value()
self._currentvalue = value
if self._oldvalue != value:
# self.notify_observers("new_ip_detected", {"ip": value})
LOG.debug("%s.set_current_value(%s)", self.__class__.__name__, value)
return value | def set_current_value(self, value) | Set the detected IP in the current run (if any). | 4.621615 | 3.633312 | 1.272012 |
if args is None:
raise ValueError("args must not be None")
parsed_args = {}
for kls in classes:
prefix = kls.configuration_key_prefix()
name = kls.configuration_key
if getattr(args, "%s_%s" % (prefix, name), False):
logging.debug(
"Gathering i... | def parse_cmdline_args(args, classes) | Parse all updater and detector related arguments from args.
Returns a list of ("name", { "k": "v"})
:param args: argparse arguments | 2.807605 | 2.8603 | 0.981577 |
if hasattr(cls, "_dont_register_arguments"):
return
prefix = cls.configuration_key_prefix()
cfgkey = cls.configuration_key
parser.add_argument("--%s-%s" % (prefix, cfgkey),
action="store_true",
dest="%s_%s" % (p... | def register_arguments(cls, parser) | Register command line options.
Implement this method for normal options behavior with protection from
OptionConflictErrors. If you override this method and want the default
--$name option(s) to be registered, be sure to call super(). | 2.240632 | 2.331981 | 0.960828 |
vr = specfile.Spec().get_vr(epoch=False)
nvr_tag = package + '-' + vr
tag_cmd = ['tag', nvr_tag, local_patches_branch]
if force:
tag_cmd.append('-f')
git(*tag_cmd)
if push:
patches_remote = patches_branch.partition('/')[0]
git('push', patches_remote, nvr_tag)
els... | def tag_patches_branch(package, local_patches_branch, patches_branch,
force=False, push=False) | Tag the local_patches_branch with this package's NVR. | 5.093003 | 4.654778 | 1.094145 |
try:
plugmod = import_module(module_name)
except Exception as exc:
warn("Importing built-in plugin %s.%s raised an exception: %r" %
(module_name, class_name, repr(exc)), ImportWarning)
return None
else:
return getattr(plugmod, class_name) | def load_class(module_name, class_name) | Return class object specified by module name and class name.
Return None if module failed to be imported.
:param module_name: string module name
:param class_name: string class name | 4.106705 | 4.444875 | 0.923919 |
name = name.lower()
cls = next((c for c in classes if c.configuration_key == name), None)
if cls is None:
raise ValueError("No class named '%s' could be found" % name)
return cls | def find_class(name, classes) | Return class in ``classes`` identified by configuration key ``name``. | 3.574036 | 2.712941 | 1.317403 |
if string:
string = " ".join(
[re.sub(r'\W+', '', word) for word in string.split()]
)
string = decamel_to_snake(string)
return string | def alphasnake(string) | Convert to snakecase removing non alpha numerics
Word #word -> word_word. | 4.499789 | 3.541261 | 1.270674 |
regex = re.compile(r'(\B[A-Z][a-z]*)')
return regex.sub(r' \1', string) | def decamel(string) | Split CamelCased words.
CamelCase -> Camel Case, dromedaryCase -> dromedary Case. | 3.333241 | 3.923075 | 0.84965 |
strings = [decamel(word) if not word.isupper() else word.lower()
for word in string.split()]
return "_".join([snake(dstring)for dstring in strings]) | def decamel_to_snake(string) | Convert to lower case, join camel case with underscore.
CamelCase -> camel_case. Camel Case -> camel_case. | 5.623935 | 5.468898 | 1.028349 |
if not distro:
distro = cfg['DISTRO']
info_file_conf = distro.upper() + 'INFO_FILE'
try:
return cfg[info_file_conf]
except KeyError:
raise exception.InvalidUsage(
why="Couldn't find config option %s for distro: %s"
% (info_file_conf, distro)) | def info_file(distro=None) | Return default distroinfo info file | 4.214541 | 3.962765 | 1.063535 |
if not distro:
distro = cfg['DISTRO']
_info_file = info_file(distro)
# prefer git fetcher if available
git_info_url_conf = distro.upper() + 'INFO_REPO'
try:
remote_git_info = cfg[git_info_url_conf]
return DistroInfo(_info_file, remote_git_info=remote_git_info)
except... | def get_distroinfo(distro=None) | Get DistroInfo initialized from configuration | 3.494374 | 3.378448 | 1.034314 |
# Remove .rpm suffix
if filename.endswith('.rpm'):
filename = filename.split('.rpm')[0]
# is there an epoch?
components = filename.split(':')
if len(components) > 1:
epoch = components[0]
else:
epoch = ''
# Arch is the last item after .
arch = filename.rsp... | def split_filename(filename) | Received a standard style rpm fullname and returns
name, version, release, epoch, arch
Example: foo-1.0-1.i386.rpm returns foo, 1.0, 1, i386
1:bar-9-123a.ia64.rpm returns bar, 9, 123a, 1, ia64
This function replaces rpmUtils.miscutils.splitFilename, see
https://bugzilla.redhat.com/1452801 | 3.428227 | 3.016942 | 1.136325 |
# is there an epoch?
components = verstring.split(':')
if len(components) > 1:
epoch = components[0]
else:
epoch = 0
remaining = components[:2][0].split('-')
version = remaining[0]
release = remaining[1]
return (epoch, version, release) | def string_to_version(verstring) | Return a tuple of (epoch, version, release) from a version string
This function replaces rpmUtils.miscutils.stringToVersion, see
https://bugzilla.redhat.com/1364504 | 4.002267 | 3.673981 | 1.089354 |
specs = [f for f in os.listdir(spec_dir)
if os.path.isfile(f) and f.endswith('.spec')]
if not specs:
raise exception.SpecFileNotFound()
if len(specs) != 1:
raise exception.MultipleSpecFilesFound()
return specs[0] | def spec_fn(spec_dir='.') | Return the filename for a .spec file in this directory. | 2.622715 | 2.199879 | 1.192209 |
m = re.match(r'(\d+(?:\.\d+)*)([.%]|$)(.*)', version)
if m:
numver = m.group(1)
rest = m.group(2) + m.group(3)
return numver, rest
else:
return version, '' | def version_parts(version) | Split a version string into numeric X.Y.Z part and the rest (milestone). | 3.471728 | 3.032072 | 1.145002 |
numver, tail = version_parts(version)
if numver and not re.match(r'\d', numver):
# entire release is macro a la %{release}
tail = numver
numver = ''
m = re.match(r'(\.?(?:%\{\?milestone\}|[^%.]+))(.*)$', tail)
if m:
milestone = m.group(1)
rest = m.group(2)
... | def release_parts(version) | Split RPM Release string into (numeric X.Y.Z part, milestone, rest).
:returns: a three-element tuple (number, milestone, rest). If we cannot
determine the "milestone" or "rest", those will be an empty
string. | 5.977989 | 5.396599 | 1.107733 |
match = re.search(r'^#\s*?%s\s?=\s?(\S+)' % re.escape(name),
self.txt, flags=re.M)
if not match:
return None
val = match.group(1)
if expand_macros and has_macros(val):
# don't parse using rpm unless required
val = se... | def get_magic_comment(self, name, expand_macros=False) | Return a value of # name=value comment in spec or None. | 4.659868 | 4.386522 | 1.062315 |
match = re.search(r'(?<=patches_base=)[\w.+?%{}]+', self.txt)
if not match:
return None, 0
patches_base = match.group()
if expand_macros and has_macros(patches_base):
# don't parse using rpm unless required
patches_base = self.expand_macro(pa... | def get_patches_base(self, expand_macros=False) | Return a tuple (version, number_of_commits) that are parsed
from the patches_base in the specfile. | 4.574454 | 3.984384 | 1.148096 |
match = re.search(r'# *patches_ignore=([\w *.+?[\]|{,}\-_]+)',
self.txt)
if not match:
return None
regex_string = match.group(1)
try:
return re.compile(regex_string)
except Exception:
return None | def get_patches_ignore_regex(self) | Returns a string representing a regex for filtering out patches
This string is parsed from a comment in the specfile that contains the
word filter-out followed by an equal sign.
For example, a comment as such:
# patches_ignore=(regex)
would mean this method returns the str... | 7.027739 | 6.054207 | 1.160803 |
_, _, rest = self.get_release_parts()
# If "rest" is not a well-known value here, then this package is
# using a Release value pattern we cannot recognize.
if rest == '' or re.match(r'%{\??dist}', rest):
return True
return False | def recognized_release(self) | Check if this Release value is something we can parse.
:rtype: bool | 19.695831 | 16.440067 | 1.198038 |
version = self.get_tag('Version', expand_macros=True)
e = None
if epoch is None or epoch:
try:
e = self.get_tag('Epoch')
except exception.SpecFileParseError:
pass
if epoch is None and e:
epoch = True
if ... | def get_vr(self, epoch=None) | get VR string from .spec Version, Release and Epoch
epoch is None: prefix epoch if present (default)
epoch is True: prefix epoch even if not present (0:)
epoch is False: omit epoch even if present | 4.600386 | 4.067327 | 1.131059 |
name = self.get_tag('Name', expand_macros=True)
vr = self.get_vr(epoch=epoch)
return '%s-%s' % (name, vr) | def get_nvr(self, epoch=None) | get NVR string from .spec Name, Version, Release and Epoch | 6.067626 | 5.302334 | 1.144331 |
if not self.txt:
# no changes
return
if not self.fn:
raise exception.InvalidAction(
"Can't save .spec file without its file name specified.")
f = codecs.open(self.fn, 'w', encoding='utf-8')
f.write(self.txt)
f.close()
... | def save(self) | Write the textual content (self._txt) to .spec file (self.fn). | 6.018719 | 4.437847 | 1.356225 |
if kind not in (IPV4, IPV6_PUBLIC, IPV6_TMP, IPV6_ANY):
raise ValueError("invalid kind specified")
# We create an UDP socket and connect it to a public host.
# We query the OS to know what our address is.
# No packet will really be sent since we are using UDP.
af = socket.AF_INET if ki... | def detect_ip(kind) | Detect IP address.
kind can be:
IPV4 - returns IPv4 address
IPV6_ANY - returns any IPv6 address (no preference)
IPV6_PUBLIC - returns public IPv6 address
IPV6_TMP - returns temporary IPV6 address (privacy extensions)
This function either returns an IP address (str) or
raise... | 3.251188 | 2.847667 | 1.141702 |
opts = koji.read_config(profile)
for k, v in opts.iteritems():
opts[k] = os.path.expanduser(v) if type(v) is str else v
kojiclient = koji.ClientSession(opts['server'], opts=opts)
kojiclient.ssl_login(opts['cert'], None, opts['serverca'])
return kojiclient | def setup_kojiclient(profile) | Setup koji client session | 3.348946 | 3.24176 | 1.033064 |
spectool = find_executable('spectool')
if not spectool:
log.warn('spectool is not installed')
return
try:
specfile = spec_fn()
except Exception:
return
cmd = [spectool, "-g", specfile]
output = subprocess.check_output(' '.join(cmd), shell=True)
log.warn(... | def retrieve_sources() | Retrieve sources using spectool | 4.545062 | 3.591766 | 1.265411 |
if not RPM_AVAILABLE:
raise RpmModuleNotAvailable()
path = os.getcwd()
try:
specfile = spec_fn()
spec = Spec(specfile)
except Exception:
return
rpmdefines = ["--define 'dist .{}'".format(dist),
"--define '_sourcedir {}'".format(path),
... | def create_srpm(dist='el7') | Create an srpm
Requires that sources are available in local directory
dist: set package dist tag (default: el7) | 4.238367 | 4.402524 | 0.962713 |
import sys
if sys.version_info >= (3, 0):
return hashlib.sha1(b"|".join((userid.encode("ascii"), # noqa: S303
password.encode("ascii")))).hexdigest()
return hashlib.sha1("|".join((userid, password))).hexdigest() | def compute_auth_key(userid, password) | Compute the authentication key for freedns.afraid.org.
This is the SHA1 hash of the string b'userid|password'.
:param userid: ascii username
:param password: ascii password
:return: ascii authentication key (SHA1 at this point) | 3.164908 | 2.812171 | 1.125432 |
params = {"action": "getdyndns", "sha": credentials.sha}
req = requests.get(
url, params=params, headers=constants.REQUEST_HEADERS_DEFAULT, timeout=60)
for record_line in (line.strip() for line in req.text.splitlines()
if len(line.strip()) > 0):
yield AfraidDynDN... | def records(credentials, url="https://freedns.afraid.org/api/") | Yield the dynamic DNS records associated with this account.
:param credentials: an AfraidCredentials instance
:param url: the service URL | 4.640787 | 4.420618 | 1.049805 |
req = requests.get(
url, headers=constants.REQUEST_HEADERS_DEFAULT, timeout=60)
req.close()
# Response must contain an IP address, or else we can't parse it.
# Also, the IP address in the response is the newly assigned IP address.
ipregex = re.compile(r"\b(?P<ip>(?:[0-9]{1,3}\.){3}[0-9]... | def update(url) | Update remote DNS record by requesting its special endpoint URL.
This automatically picks the IP address using the HTTP connection: it is not
possible to specify the IP address explicitly.
:param url: URL to retrieve for triggering the update
:return: IP address | 4.272908 | 4.31146 | 0.991058 |
if self._sha is None:
self._sha = compute_auth_key(self.userid, self.password)
return self._sha | def sha(self) | Return sha, lazily compute if not done yet. | 4.933004 | 3.954682 | 1.247383 |
# first find the update_url for the provided account + hostname:
update_url = next((r.update_url for r in
records(self._credentials, self._url)
if r.hostname == self.hostname), None)
if update_url is None:
LOG.warning("Co... | def update(self, *args, **kwargs) | Update the IP on the remote service. | 6.134574 | 5.699023 | 1.076426 |
if events is not None and not isinstance(events, (tuple, list)):
events = (events,)
if observer in self._observers:
LOG.warning("Observer '%r' already registered, overwriting for events"
" %r", observer, events)
self._observers[observer] ... | def register_observer(self, observer, events=None) | Register a listener function.
:param observer: external listener function
:param events: tuple or list of relevant events (default=None) | 3.396743 | 3.797171 | 0.894546 |
for observer, events in list(self._observers.items()):
# LOG.debug("trying to notify the observer")
if events is None or event is None or event in events:
try:
observer(self, event, msg)
except (Exception,) as ex: # pylint: di... | def notify_observers(self, event=None, msg=None) | Notify observers. | 4.008922 | 4.016354 | 0.998149 |
if self.opts_family == AF_INET6:
kind = IPV6_PUBLIC
else: # 'INET':
kind = IPV4
theip = None
try:
theip = detect_ip(kind)
except GetIpException:
LOG.exception("socket detector raised an exception:")
self.set_curren... | def detect(self) | Detect the IP address. | 11.386101 | 9.563749 | 1.190548 |
theip = None
try:
if self.opts_family == AF_INET6:
addrlist = netifaces.ifaddresses(self.opts_iface)[netifaces.AF_INET6]
else:
addrlist = netifaces.ifaddresses(self.opts_iface)[netifaces.AF_INET]
except ValueError as exc:
... | def _detect(self) | Use the netifaces module to detect ifconfig information. | 3.646964 | 3.433895 | 1.062049 |
tempdir = getattr(context, 'tempdir', None)
if tempdir and scenario.status == 'passed':
shutil.rmtree(tempdir)
del(context.tempdir) | def clean_tempdir(context, scenario) | Clean up temporary test dirs for passed tests.
Leave failed test dirs for manual inspection. | 3.362919 | 3.26844 | 1.028906 |
theip = ipaddress(ip)
for res in self._reserved_netmasks:
if theip in ipnetwork(res):
return True
return False | def is_reserved_ip(self, ip) | Check if the given ip address is in a reserved ipv4 address space.
:param ip: ip address
:return: boolean | 6.63589 | 7.423862 | 0.89386 |
randomip = random_ip()
while self.is_reserved_ip(randomip):
randomip = random_ip()
return randomip | def random_public_ip(self) | Return a randomly generated, public IPv4 address.
:return: ip address | 3.782654 | 4.681728 | 0.807961 |
for theip in self.rips:
LOG.debug("detected %s", str(theip))
self.set_current_value(str(theip))
return str(theip) | def detect(self) | Detect IP and return it. | 8.758658 | 6.286801 | 1.393182 |
timeout = 60
LOG.debug("Updating '%s' to '%s' at service '%s'", self.hostname, ip, self._updateurl)
params = {"myip": ip, "hostname": self.hostname}
req = requests.get(self._updateurl, params=params, headers=constants.REQUEST_HEADERS_DEFAULT,
auth=(sel... | def update(self, ip) | Update the IP on the remote service. | 5.350792 | 5.061954 | 1.057061 |
ref = None
try:
spec = specfile.Spec()
ref, _ = spec.get_patches_base(expand_macros=True)
if ref:
ref, _ = tag2version(ref)
else:
ref = spec.get_tag('Version', expand_macros=True)
milestone = spec.get_milestone()
if milestone:
... | def patches_base_ref(default=exception.CantGuess) | Return a git reference to patches branch base.
Returns first part of .spec's patches_base is found,
otherwise return Version(+%{milestone}). | 4.945493 | 4.439169 | 1.114058 |
'''Displays a list of items along with the index to enable a user
to select an item.
'''
if (len(items) == 2 and items[0].get_label() == '..'
and items[1].get_played()):
display_video(items)
else:
label_width = get_max_len(item.get_label() for item in items)
num_width... | def display_listitems(items, url) | Displays a list of items along with the index to enable a user
to select an item. | 3.336557 | 2.963325 | 1.125951 |
'''Prints a message for a playing video and displays the parent
listitem.
'''
parent_item, played_item = items
title_line = 'Playing Media %s (%s)' % (played_item.get_label(),
played_item.get_path())
parent_line = '[0] %s (%s)' % (parent_item.get_labe... | def display_video(items) | Prints a message for a playing video and displays the parent
listitem. | 4.458446 | 3.096969 | 1.439616 |
'''Returns the selected item from provided items or None if 'q' was
entered for quit.
'''
choice = raw_input('Choose an item or "q" to quit: ')
while choice != 'q':
try:
item = items[int(choice)]
print # Blank line for readability between interactive views
... | def get_user_choice(items) | Returns the selected item from provided items or None if 'q' was
entered for quit. | 5.743832 | 4.442565 | 1.292909 |
if isinstance(data, unicode):
return data
# Detect standard unicode BOMs.
for bom, encoding in UNICODE_BOMS:
if data.startswith(bom):
return data[len(bom):].decode(encoding, errors='ignore')
# Try straight UTF-8.
try:
return data.decode('utf-8')
except... | def decode(data) | Decode data employing some charset detection and including unicode BOM
stripping. | 3.344159 | 2.973621 | 1.124608 |
'Returns a tuple containing the context for a line'
line -= 1 # The line is one-based
# If there is no data in the file, there can be no context.
datalen = len(self.data)
if datalen <= line:
return None
build = [self.data[line]]
# Add surrounding ... | def get_context(self, line=1, column=0) | Returns a tuple containing the context for a line | 3.586251 | 3.510231 | 1.021656 |
'Formats a line from the data to be the appropriate length'
line_length = len(data)
if line_length > 140:
if rel_line == 0:
# Trim from the beginning
data = '... %s' % data[-140:]
elif rel_line == 1:
# Trim surrounding the ... | def _format_line(self, data, column=0, rel_line=1) | Formats a line from the data to be the appropriate length | 3.184653 | 2.825801 | 1.126991 |
'Returns the line number that the given string position is found on'
datalen = len(self.data)
count = len(self.data[0])
line = 1
while count < position:
if line >= datalen:
break
count += len(self.data[line]) + 1
line += 1
... | def get_line(self, position) | Returns the line number that the given string position is found on | 4.824369 | 3.623577 | 1.331383 |
'''This is not an official XBMC method, it is here to faciliate
mocking up the other methods when running outside of XBMC.'''
def get_strings(fn):
xml = parse(fn)
strings = dict((tag.getAttribute('id'), tag.firstChild.data) for tag in xml.getElementsByTagName('string'))
#strings = {}... | def load_addon_strings(addon, filename) | This is not an official XBMC method, it is here to faciliate
mocking up the other methods when running outside of XBMC. | 4.753185 | 2.573379 | 1.84706 |
'''Parses an addon id from the given addon.xml filename.'''
xml = parse(addonxml)
addon_node = xml.getElementsByTagName('addon')[0]
return addon_node.getAttribute('id') | def get_addon_id(addonxml) | Parses an addon id from the given addon.xml filename. | 5.025977 | 3.142459 | 1.599377 |
'''Parses an addon name from the given addon.xml filename.'''
xml = parse(addonxml)
addon_node = xml.getElementsByTagName('addon')[0]
return addon_node.getAttribute('name') | def get_addon_name(addonxml) | Parses an addon name from the given addon.xml filename. | 4.910497 | 3.170336 | 1.548889 |
'''Creates necessary directories for the given path or does nothing
if the directories already exist.
'''
try:
os.makedirs(path)
except OSError, exc:
if exc.errno == errno.EEXIST:
pass
else:
raise | def _create_dir(path) | Creates necessary directories for the given path or does nothing
if the directories already exist. | 3.514551 | 2.26952 | 1.548588 |
'''Creates folders in the OS's temp directory. Doesn't touch any
possible XBMC installation on the machine. Attempting to do as
little work as possible to enable this function to work seamlessly.
'''
valid_dirs = ['xbmc', 'home', 'temp', 'masterprofile', 'profile',
'subtitles', 'userdata', '... | def translatePath(path) | Creates folders in the OS's temp directory. Doesn't touch any
possible XBMC installation on the machine. Attempting to do as
little work as possible to enable this function to work seamlessly. | 7.780254 | 4.649312 | 1.673421 |
'''Handles setup of the plugin state, including request
arguments, handle, mode.
This method never needs to be called directly. For testing, see
plugin.test()
'''
# To accomdate self.redirect, we need to be able to parse a full url as
# well
if url is Non... | def _parse_request(self, url=None, handle=None) | Handles setup of the plugin state, including request
arguments, handle, mode.
This method never needs to be called directly. For testing, see
plugin.test() | 8.377906 | 3.64443 | 2.298825 |
'''Registers a module with a plugin. Requires a url_prefix that
will then enable calls to url_for.
:param module: Should be an instance `xbmcswift2.Module`.
:param url_prefix: A url prefix to use for all module urls,
e.g. '/mymodule'
'''
module... | def register_module(self, module, url_prefix) | Registers a module with a plugin. Requires a url_prefix that
will then enable calls to url_for.
:param module: Should be an instance `xbmcswift2.Module`.
:param url_prefix: A url prefix to use for all module urls,
e.g. '/mymodule' | 7.598765 | 2.200085 | 3.45385 |
'''A decorator to add a route to a view and also apply caching. The
url_rule, name and options arguments are the same arguments for the
route function. The TTL argument if given will passed along to the
caching decorator.
'''
route_decorator = self.route(url_rule, name=na... | def cached_route(self, url_rule, name=None, options=None, TTL=None) | A decorator to add a route to a view and also apply caching. The
url_rule, name and options arguments are the same arguments for the
route function. The TTL argument if given will passed along to the
caching decorator. | 4.075296 | 1.936502 | 2.104462 |
'''A decorator to add a route to a view. name is used to
differentiate when there are multiple routes for a given view.'''
# TODO: change options kwarg to defaults
def decorator(f):
view_name = name or f.__name__
self.add_url_rule(url_rule, f, name=view_name, opti... | def route(self, url_rule, name=None, options=None) | A decorator to add a route to a view. name is used to
differentiate when there are multiple routes for a given view. | 4.927773 | 2.882172 | 1.709743 |
'''This method adds a URL rule for routing purposes. The
provided name can be different from the view function name if
desired. The provided name is what is used in url_for to build
a URL.
The route decorator provides the same functionality.
'''
rule = UrlRule(ur... | def add_url_rule(self, url_rule, view_func, name, options=None) | This method adds a URL rule for routing purposes. The
provided name can be different from the view function name if
desired. The provided name is what is used in url_for to build
a URL.
The route decorator provides the same functionality. | 4.445511 | 2.596274 | 1.712266 |
'''Returns a valid XBMC plugin URL for the given endpoint name.
endpoint can be the literal name of a function, or it can
correspond to the name keyword arguments passed to the route
decorator.
Raises AmbiguousUrlException if there is more than one possible
view for the ... | def url_for(self, endpoint, **items) | Returns a valid XBMC plugin URL for the given endpoint name.
endpoint can be the literal name of a function, or it can
correspond to the name keyword arguments passed to the route
decorator.
Raises AmbiguousUrlException if there is more than one possible
view for the given endpo... | 6.522802 | 3.496149 | 1.865711 |
'''Used when you need to redirect to another view, and you only
have the final plugin:// url.'''
# TODO: Should we be overriding self.request with the new request?
new_request = self._parse_request(url=url, handle=self.request.handle)
log.debug('Redirecting %s to %s', self.reques... | def redirect(self, url) | Used when you need to redirect to another view, and you only
have the final plugin:// url. | 7.434143 | 4.092026 | 1.816739 |
'''The main entry point for a plugin.'''
self._request = self._parse_request()
log.debug('Handling incoming request for %s', self.request.path)
items = self._dispatch(self.request.path)
# Close any open storages which will persist them to disk
if hasattr(self, '_unsynced... | def run(self, test=False) | The main entry point for a plugin. | 6.588319 | 6.119477 | 1.076615 |
'''The entry point for the console script xbmcswift2.
The 'xbcmswift2' script is command bassed, so the second argument is always
the command to execute. Each command has its own parser options and usages.
If no command is provided or the -h flag is used without any other
commands, the general help... | def main() | The entry point for the console script xbmcswift2.
The 'xbcmswift2' script is command bassed, so the second argument is always
the command to execute. Each command has its own parser options and usages.
If no command is provided or the -h flag is used without any other
commands, the general help messag... | 5.704076 | 3.144302 | 1.814099 |
# Take note of where the escape sequences are.
rnormal = text.rfind('<<NORMAL')
rany = text.rfind('<<')
# Put in the escape sequences.
for color, code in self.colors.items():
text = text.replace('<<%s>>' % color, code)
# Make sure that the last seq... | def colorize_text(self, text) | Adds escape sequences to colorize text and make it
beautiful. To colorize text, prefix the text you want to color
with the color (capitalized) wrapped in double angle brackets
(i.e.: <<GREEN>>). End your string with <<NORMAL>>. If you
don't, it will be done for you (assuming you used a c... | 5.797642 | 4.843101 | 1.197093 |
'Uses curses to print in the fanciest way possible.'
# Add color to the terminal.
if not self.no_color:
text = self.colorize_text(text)
else:
pattern = re.compile('\<\<[A-Z]*?\>\>')
text = pattern.sub('', text)
text += '\n'
self.buff... | def write(self, text) | Uses curses to print in the fanciest way possible. | 7.531414 | 5.421628 | 1.389142 |
params = self._get_params(input, kwargs)
try:
reply = self.session.get(
self.url, params=params, timeout=self.timeout)
except requests.Timeout:
raise Timeout(self.timeout)
else:
try:
data = reply.json()
... | def say(self, input=None, **kwargs) | Talk to Cleverbot.
Arguments:
input: The input argument is what you want to say to Cleverbot,
such as "hello".
tweak1-3: Changes Cleverbot's mood.
**kwargs: Keyword arguments to update the request parameters with.
Returns:
Cleverbot's rep... | 2.762572 | 2.545581 | 1.085242 |
try:
kill(int(pid), 0)
return pid
except OSError as e:
if e.errno == errno.EPERM:
return pid
return None | def live_pidfile(pidfile): # pragma: no cover
pid = read_pidfile(pidfile)
if pid | (pidfile:str) -> int | None
Returns an int found in the named file, if there is one,
and if there is a running process with that process id.
Return None if no such process exists. | 6.145803 | 4.723279 | 1.301173 |
import signal
except ImportError:
return
def handle_term(signo, frame):
raise SystemExit
signal.signal(signal.SIGTERM, handle_term) | def _turn_sigterm_into_systemexit(): # pragma: no cover
try | Attempts to turn a SIGTERM exception into a SystemExit exception. | 3.764971 | 3.610139 | 1.042888 |
import ssl
class SecureWSGIServer(WSGIServer):
def get_request(self):
socket, client_address = WSGIServer.get_request(self)
socket = ssl.wrap_socket(socket,
server_side=True,
... | def wsgiref_server_runner(wsgi_app, global_conf, **kw): # pragma: no cover
from wsgiref.simple_server import make_server, WSGIServer
host = kw.get('host', '0.0.0.0')
port = int(kw.get('port', 8080))
threaded = asbool(kw.get('wsgiref.threaded', False))
server_class = WSGIServer
certfile = ... | Entry point for wsgiref's WSGI server
Additional parameters:
``certfile``, ``keyfile``
Optional SSL certificate file and host key file names. You can
generate self-signed test files as follows:
$ openssl genrsa 1024 > keyfile
$ chmod 400 keyfile
$ openssl ... | 2.335806 | 2.470164 | 0.945608 |
port = port or 4443
is_ssl = True
if not port:
if ':' in host:
host, port = host.split(':', 1)
else:
port = 8080
bind_addr = (host, int(port))
kwargs = {}
for var_name in ('numthreads', 'max', 'request_queue_size', 'timeout'):
var = local... | def cherrypy_server_runner(
app, global_conf=None, host='127.0.0.1', port=None,
ssl_pem=None, protocol_version=None, numthreads=None,
server_name=None, max=None, request_queue_size=None,
timeout=None
): # pragma: no cover
is_ssl = False
if ssl_pem | Entry point for CherryPy's WSGI server
Serves the specified WSGI app via CherryPyWSGIServer.
``app``
The WSGI 'application callable'; multiple WSGI applications
may be passed as (script_name, callable) pairs.
``host``
This is the ipaddress to bind to (or a hostname if your
... | 2.518573 | 2.528694 | 0.995998 |
result = {}
for arg in args:
if '=' not in arg:
raise ValueError(
'Variable assignment %r invalid (no "=")'
% arg)
name, value = arg.split('=', 1)
result[name] = value
return result | def parse_vars(self, args) | Given variables like ``['a=b', 'c=d']`` turns it into ``{'a':
'b', 'c': 'd'}`` | 3.170944 | 2.987306 | 1.061473 |
argv.insert(0, sys.executable)
return argv | def get_fixed_argv(self): # pragma: no cover
argv = sys.argv[:]
if sys.platform == 'win32' and argv[0].endswith('.py') | Get proper arguments for re-running the command.
This is primarily for fixing some issues under Windows.
First, there was a bug in Windows when running an executable
located at a path with a space in it. This has become a
non-issue with current versions of Python and Windows,
s... | 11.479543 | 14.606774 | 0.785905 |
'Main function. Handles delegation to other functions.'
logging.basicConfig()
type_choices = {'any': constants.PACKAGE_ANY,
'extension': constants.PACKAGE_EXTENSION,
'theme': constants.PACKAGE_THEME,
'dictionary': constants.PACKAGE_DICTIONARY,
... | def main() | Main function. Handles delegation to other functions. | 3.083949 | 3.017164 | 1.022135 |
'Returns a dictionary of file information'
if self.contents_cache:
return self.contents_cache
# Get a list of ZipInfo objects.
files = self.zf.infolist()
out_files = {}
# Iterate through each file in the XPI.
for file_ in files:
file_do... | def package_contents(self) | Returns a dictionary of file information | 3.551601 | 3.477389 | 1.021342 |
if isinstance(data, StringIO):
self.zf.writestr(name, data.getvalue())
else:
self.zf.writestr(name, to_utf8(data)) | def write(self, name, data) | Write a blob of data to the XPI manager. | 2.904081 | 2.922463 | 0.99371 |
if path is None:
path = name
self.zf.write(path, name) | def write_file(self, name, path=None) | Write the contents of a file from the disk to the XPI. | 6.718805 | 5.793152 | 1.159784 |
'''Appends key/val pairs to the end of a URL. Useful for passing arbitrary
HTTP headers to XBMC to be used when fetching a media resource, e.g.
cookies.
'''
optionstring = urllib.urlencode(options)
if optionstring:
return url + '|' + optionstring
return url | def xbmc_url(url, **options) | Appends key/val pairs to the end of a URL. Useful for passing arbitrary
HTTP headers to XBMC to be used when fetching a media resource, e.g.
cookies. | 9.186921 | 2.657422 | 3.45708 |
'''An enum class to mirror XBMC constatns. All args and kwargs.keys are
added as atrrs on the returned object.
>>> States = enum('NEW_JERSEY', NY='NEW_YORK')
>>> States.NY
'NEW_YORK'
>>> States.NEW_JERSEY
'NEW_JERSEY'
>>> States._fields
['NY', 'NEW_JERSEY']
'''
kwargs.update... | def enum(*args, **kwargs) | An enum class to mirror XBMC constatns. All args and kwargs.keys are
added as atrrs on the returned object.
>>> States = enum('NEW_JERSEY', NY='NEW_YORK')
>>> States.NY
'NEW_YORK'
>>> States.NEW_JERSEY
'NEW_JERSEY'
>>> States._fields
['NY', 'NEW_JERSEY'] | 5.687638 | 1.628315 | 3.49296 |
'''Returns a dict where items with a None value are removed'''
return dict((key, val) for key, val in dct.items() if val is not None) | def clean_dict(dct) | Returns a dict where items with a None value are removed | 3.828895 | 2.590742 | 1.477914 |
'''Returns a new dictionary where values which aren't instances of
basestring are pickled. Also, a new key '_pickled' contains a comma
separated list of keys corresponding to the pickled values.
'''
ret = {}
pickled_keys = []
for key, val in items.items():
if isinstance(val, basestri... | def pickle_dict(items) | Returns a new dictionary where values which aren't instances of
basestring are pickled. Also, a new key '_pickled' contains a comma
separated list of keys corresponding to the pickled values. | 3.048873 | 1.58671 | 1.921505 |
'''Takes a dict and unpickles values whose keys are found in
'_pickled' key.
>>> unpickle_args({'_pickled': ['foo']. 'foo': ['I3%0A.']})
{'foo': 3}
'''
# Technically there can be more than one _pickled value. At this point
# we'll just use the first one
pickled= items.pop('_pickled', No... | def unpickle_args(items) | Takes a dict and unpickles values whose keys are found in
'_pickled' key.
>>> unpickle_args({'_pickled': ['foo']. 'foo': ['I3%0A.']})
{'foo': 3} | 5.040073 | 2.344145 | 2.150068 |
'''Returns a dict pickled with pickle_dict'''
pickled_keys = items.pop('_pickled', '').split(',')
ret = {}
for key, val in items.items():
if key in pickled_keys:
ret[key] = pickle.loads(val)
else:
ret[key] = val
return ret | def unpickle_dict(items) | Returns a dict pickled with pickle_dict | 3.594371 | 2.940861 | 1.222217 |
'''Returns the response for the given url. The optional data argument is
passed directly to urlopen.'''
conn = urllib2.urlopen(url, data)
resp = conn.read()
conn.close()
return resp | def download_page(url, data=None) | Returns the response for the given url. The optional data argument is
passed directly to urlopen. | 4.455132 | 2.2606 | 1.970774 |
'''unquote(r'abc\x20def') -> 'abc def'.'''
res = inp.split(r'\x')
for i in xrange(1, len(res)):
item = res[i]
try:
res[i] = _hextochr[item[:2]] + item[2:]
except KeyError:
res[i] = '%' + item
except UnicodeDecodeError:
res[i] = unichr(int(i... | def unhex(inp) | unquote(r'abc\x20def') -> 'abc def'. | 2.950404 | 2.259142 | 1.305985 |
for ep in pkg_resources.iter_entry_points(namespace):
LOG.debug('found command %r', ep.name)
cmd_name = (ep.name.replace('_', ' ')
if self.convert_underscores
else ep.name)
self.commands[cmd_name] = ep
return | def load_commands(self, namespace) | Load all the commands from an entrypoint | 3.915232 | 3.465088 | 1.129908 |
search_args = argv[:]
name = ''
while search_args:
if search_args[0].startswith('-'):
name = '%s %s' % (name, search_args[0])
raise ValueError('Invalid command %r' % name)
next_val = search_args.pop(0)
name = '%s %s' % ... | def find_command(self, argv) | Given an argument list, find a command and
return the processor and any remaining arguments. | 3.232809 | 3.19926 | 1.010486 |
path, _ = _getpathsec(config_uri, None)
parser = configparser.ConfigParser()
parser.read([path])
if parser.has_section('loggers'):
config_file = os.path.abspath(path)
config_options = dict(
__file__=config_file,
here=os.path.dirname(config_file)
)
... | def setup_logging(config_uri, fileConfig=fileConfig,
configparser=configparser) | Set up logging via the logging module's fileConfig function with the
filename specified via ``config_uri`` (a string in the form
``filename#sectionname``).
ConfigParser defaults are specified for the special ``__file__``
and ``here`` variables, similar to PasteDeploy config loading. | 3.443529 | 3.485798 | 0.987874 |
package = None
try:
# Test that the package actually exists. I consider this Tier 0
# since we may not even be dealing with a real file.
if not os.path.isfile(path):
err.error(('main', 'prepare_package', 'not_found'),
'The package could not be foun... | def prepare_package(err, path, expectation=0, for_appversions=None,
timeout=-1) | Prepares a file-based package for validation.
timeout is the number of seconds before validation is aborted.
If timeout is -1 then no timeout checking code will run. | 4.154919 | 4.133422 | 1.005201 |
"Loads the chrome.manifest if it's present"
if 'chrome.manifest' in xpi_package:
chrome_data = xpi_package.read('chrome.manifest')
chrome = ChromeManifest(chrome_data, 'chrome.manifest')
chrome_recursion_buster = set()
# Handle the case of manifests linked from the manifest.
... | def populate_chrome_manifest(err, xpi_package) | Loads the chrome.manifest if it's present | 3.868473 | 3.761954 | 1.028315 |
# The types in the install.rdf don't pair up 1:1 with the type
# system that we're using for expectations and the like. This is
# to help translate between the two.
translated_types = {'2': PACKAGE_EXTENSION,
'4': PACKAGE_THEME,
'8': PACKAGE_LANGPACK... | def detect_type(err, install_rdf=None, xpi_package=None) | Determines the type of add-on being validated based on
install.rdf, file extension, and other properties. | 6.088385 | 6.079062 | 1.001534 |
if name.startswith('.'):
return 'Skipping hidden file %(filename)s'
if name.endswith('~') or name.endswith('.bak'):
return 'Skipping backup file %(filename)s'
if name.endswith('.pyc') or name.endswith('.pyo'):
return 'Skipping %s file ' % os.path.splitext(name)[1] + '%(filename)... | def should_skip_file(name) | Checks if a file should be skipped based on its name.
If it should be skipped, returns the reason, otherwise returns
None. | 2.667688 | 2.664446 | 1.001217 |
'''Takes any actions necessary based on command line options'''
if opts.quiet:
logger.log.setLevel(logging.WARNING)
logger.GLOBAL_LOG_LEVEL = logging.WARNING
if opts.verbose:
logger.log.setLevel(logging.DEBUG)
logger.GLOBAL_LOG_LEVEL = logging.DEBUG | def setup_options(opts) | Takes any actions necessary based on command line options | 4.143658 | 2.727735 | 1.519084 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.