code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
self._format = 'txtinfo'
# find interesting section
lines = data.split('\n')
try:
start = lines.index('Table: Topology') + 2
except ValueError:
raise ParserError('Unrecognized format')
topology_lines = [line for line in lines[start:] if li... | def _txtinfo_to_python(self, data) | Converts txtinfo format to python | 4.125743 | 3.876591 | 1.064271 |
for local_addresses in node_list:
if mac_address in local_addresses:
return local_addresses[0]
return mac_address | def _get_primary_address(self, mac_address, node_list) | Uses the _get_aggregated_node_list structure to find
the primary mac address associated to a secondary one,
if none is found returns itself. | 3.547456 | 3.197193 | 1.109553 |
node_list = []
for node in data:
local_addresses = [node['primary']]
if 'secondary' in node:
local_addresses += node['secondary']
node_list.append(local_addresses)
return node_list | def _get_aggregated_node_list(self, data) | Returns list of main and secondary mac addresses. | 3.208458 | 2.851122 | 1.125332 |
method = getattr(self, '_parse_{0}'.format(self._format))
return method(data) | def parse(self, data) | Calls the right method depending on the format,
which can be one of the wollowing:
* alfred_vis
* txtinfo | 5.730766 | 4.828696 | 1.186814 |
# initialize graph and list of aggregated nodes
graph = self._init_graph()
if 'source_version' in data:
self.version = data['source_version']
if 'vis' not in data:
raise ParserError('Parse error, "vis" key not found')
node_list = self._get_aggrega... | def _parse_alfred_vis(self, data) | Converts a alfred-vis JSON object
to a NetworkX Graph object which is then returned.
Additionally checks for "source_vesion" to determine the batman-adv version. | 5.247772 | 4.811096 | 1.090764 |
graph = self._init_graph()
for link in data:
graph.add_edge(link['source'],
link['target'],
weight=link['cost'])
return graph | def _parse_txtinfo(self, data) | Converts the python list returned by self._txtinfo_to_python()
to a NetworkX Graph object, which is then returned. | 4.583431 | 3.509974 | 1.30583 |
if isinstance(data, dict):
return data
elif isinstance(data, six.string_types):
# assuming is JSON
try:
return json.loads(data)
except ValueError:
pass
raise ConversionException('Could not recognize format',... | def to_python(self, data) | Parses the input data and converts it into a Python data structure
Input data might be:
* a path which points to a JSON file
* a URL which points to a JSON file
(supported schemes: http, https, telnet)
* a JSON formatted string
* a dict representing ... | 4.279243 | 4.180304 | 1.023668 |
try:
graph = self.graph
except AttributeError:
raise NotImplementedError()
return _netjson_networkgraph(self.protocol,
self.version,
self.revision,
self... | def json(self, dict=False, **kwargs) | Outputs NetJSON format | 5.798 | 5.155668 | 1.124588 |
protocol = new.protocol
version = new.version
revision = new.revision
metric = new.metric
# calculate differences
in_both = _find_unchanged(old.graph, new.graph)
added_nodes, added_edges = _make_diff(old.graph, new.graph, in_both)
removed_nodes, removed_edges = _make_diff(new.graph,... | def diff(old, new) | Returns differences of two network topologies old and new
in NetJSON NetworkGraph compatible format | 2.410292 | 2.291637 | 1.051778 |
# make a copy of old topology to avoid tampering with it
diff_edges = new.copy()
not_different = [tuple(edge) for edge in both]
diff_edges.remove_edges_from(not_different)
# repeat operation with nodes
diff_nodes = new.copy()
not_different = []
for new_node in new.nodes():
i... | def _make_diff(old, new, both) | calculates differences between topologies 'old' and 'new'
returns a tuple with two network graph objects
the first graph contains the added nodes, the secnod contains the added links | 4.157109 | 3.450941 | 1.20463 |
edges = []
old_edges = [set(edge) for edge in old.edges()]
new_edges = [set(edge) for edge in new.edges()]
for old_edge in old_edges:
if old_edge in new_edges:
edges.append(set(old_edge))
return edges | def _find_unchanged(old, new) | returns edges that are in both old and new | 2.312814 | 1.937751 | 1.193556 |
# create two list of sets of old and new edges including cost
old_edges = []
for edge in old.edges(data=True):
# skip links that are not in both
if set((edge[0], edge[1])) not in both:
continue
# wrap cost in tuple so it will be recognizable
cost = (edge[2]['... | def _find_changed(old, new, both) | returns links that have changed cost | 2.458177 | 2.386481 | 1.030043 |
# initialize graph and list of aggregated nodes
graph = self._init_graph()
if len(data) != 0:
if "links" not in data[0]:
raise ParserError('Parse error, "links" key not found')
# loop over topology section and create networkx graph
# this data... | def parse(self, data) | Converts a BMX6 b6m JSON to a NetworkX Graph object
which is then returned. | 5.00598 | 5.049371 | 0.991407 |
graph = self._init_graph()
# loop over links and create networkx graph
# Add only working nodes with working links
for link in data.get_inner_links():
if link.status != libcnml.libcnml.Status.WORKING:
continue
interface_a, interface_b = li... | def parse(self, data) | Converts a CNML structure to a NetworkX Graph object
which is then returned. | 7.251851 | 6.201432 | 1.169383 |
try:
return super(OlsrParser, self).to_python(data)
except ConversionException as e:
return self._txtinfo_to_jsoninfo(e.data) | def to_python(self, data) | Adds support for txtinfo format | 11.340767 | 7.928584 | 1.430365 |
graph = self._init_graph()
if 'topology' not in data:
raise ParserError('Parse error, "topology" key not found')
elif 'mid' not in data:
raise ParserError('Parse error, "mid" key not found')
# determine version and revision
if 'config' in data:
... | def parse(self, data) | Converts a dict representing an OLSR 0.6.x topology
to a NetworkX Graph object, which is then returned.
Additionally checks for "config" data in order to determine version and revision. | 4.02389 | 3.635482 | 1.106838 |
# replace INFINITE with inf, which is convertible to float
data = data.replace('INFINITE', 'inf')
# find interesting section
lines = data.split('\n')
# process links in topology section
try:
start = lines.index('Table: Topology') + 2
end ... | def _txtinfo_to_jsoninfo(self, data) | converts olsr 1 txtinfo format to jsoninfo | 3.13558 | 3.095662 | 1.012895 |
def connect_to_jira(self, JIRAUsername=None,
JIRAPassword=None, options=None):
if JIRAUsername is not None and (JIRAPassword is "" or JIRAPassword is None):
JIRAPassword = getpass.getpass("\nJIRA Password: ")
print JIRAUsername
JIRAOptio... | Connect to a JIRA server.
Arguments:
| JIRAUsername (string) | (Optional) A JIRA Username you wish to authenticate with, will authorise with anonymous account if left empty |
| JIRAPassword (string) | (Optional) If a username was specified and a password... | null | null | null | |
def create_issue(self, issue_field_dict, assign_current_user=False):
issue_field_dict = eval(str(issue_field_dict))
print issue_field_dict
new_issue = self.jira.create_issue(issue_field_dict)
if assign_current_user is True:
self.assign_user_to_issue(new_issue... | Creates a new JIRA issue.
Arguments:
| issue_field_dict (string) | A dictionary in the form of a string that the user can specify the issues fields and field values |
| assign_current_user (string/bool) | (Optional) A flag to assign the current user to the iss... | null | null | null | |
def create_issue_link(self, link_type, inwardissue,
outwardissue, comment=None):
self.jira.create_issue_link(type=link_type,
inwardIssue=str(inwardissue),
outwardIssue=str(outwardissue)) | Create a link between two issues.
Arguments:
| link_type (string) | The type of link |
| inwardissue (string) | The issue to link from |
| outwardissue (string) | The issue to link to |
| comment (string... | null | null | null | |
def assign_user_to_issue(self, issue, JIRAUsername):
# TODO: Review docs
self.jira.assign_issue(issue=issue, assignee=JIRAUsername) | Adds a user to a specified issue's watcher list
Arguments:
| issue (string) | A JIRA Issue that a user needs to be assigned to, can be an issue ID or Key |
| JIRAUsername (string) | A JIRA Username to assign a user to an issue |
Example:
| ... | null | null | null | |
def add_watcher_to_issue(self, issue, JIRAUsername):
self.jira.add_watcher(issue=issue, watcher=JIRAUsername) | Adds a user to a specified issue's watcher list.
Arguments:
| issue (string) | A JIRA Issue that a watcher needs added to, can be an issue ID or Key |
| JIRAUsername (string) | A JIRA Username to add as a watcher to an issue |
Example:
| *Keyw... | null | null | null | |
def add_comment_to_issue(self, issue, comment, visibility=None):
self.jira.add_comment(issue=issue, body=comment) | Adds a comment to a specified issue from the current user.
Arguments:
| issue (string) | A JIRA Issue that a watcher needs added to, can be an issue ID or Key |
| comment (string) | A body of text to add as a comment to an issue |
| visi... | null | null | null | |
def add_attachment_to_issue(self, issue, attachment, filename=None):
self.jira.add_attachment(issue=issue, attachment=attachment,
filename=filename) | Uploads and attaches a file a specified issue. (Note: include the file extention when using the 'filename' option or this will change the file type.)
Arguments:
| issue (string) | A JIRA Issue that a watcher needs added to, can be an issue ID or Key |
| attachment (string) | ... | null | null | null | |
super(HtmlFormatter, self).format(record)
if record.funcName:
record.funcName = escape_html(str(record.funcName))
if record.name:
record.name = escape_html(str(record.name))
if record.msg:
record.msg = escape_html(record.getMessage())
... | def format(self, record) | :param logging.LogRecord record: | 2.466634 | 2.406827 | 1.024849 |
if "versions" in data:
return sorted(data["versions"].keys(), key=lambda v: parse(v), reverse=True)
return [] | def get_releases(data, **kwargs) | Gets all releases from pypi meta data.
:param data: dict, meta data
:return: list, str releases | 4.299784 | 4.44869 | 0.966528 |
# if this package has valid meta data, build up a list of URL candidates we can possibly
# search for changelogs on
if "versions" in data:
candidates = set()
for version, item in data["versions"].items():
if "homepage" in item and item["homepage"] is not None:
... | def get_urls(session, name, data, find_changelogs_fn, **kwargs) | Gets URLs to changelogs.
:param session: requests Session instance
:param name: str, package name
:param data: dict, meta data
:param find_changelogs_fn: function, find_changelogs
:return: tuple, (set(changelog URLs), set(repo URLs)) | 2.866617 | 2.659642 | 1.077821 |
changelog = {}
releases = frozenset(releases)
head = False
for line in content.splitlines():
new_head = get_head_fn(name=name, line=line, releases=releases)
if new_head:
head = new_head
changelog[head] = ""
continue
if not head:
... | def parse(name, content, releases, get_head_fn) | Parses the given content for a valid changelog
:param name: str, package name
:param content: str, content
:param releases: list, releases
:param get_head_fn: function
:return: dict, changelog | 2.740893 | 2.825571 | 0.970031 |
if not line:
return False
# if this line begins with an invalid starting character, return early.
# invalid characters are those used by various markup languages to introduce a new
# new list item
for char in INVALID_LINE_START:
# markdown uses ** for bold text, we also want to ... | def get_head(name, line, releases) | Checks if `line` is a head
:param name: str, package name
:param line: str, line
:param releases: list, releases
:return: str, version if this is a valid head, False otherwise | 5.57865 | 5.559416 | 1.00346 |
log = ""
raw_log = ""
for path, _ in content:
log += "\n".join(changelog(repository=GitRepos(path), tag_filter_regexp=r"v?\d+\.\d+(\.\d+)?"))
raw_log += "\n" + subprocess.check_output(
["git", "-C", path, "--no-pager", "log", "--decorate"]).decode("utf-8")
shutil.rmt... | def parse_commit_log(name, content, releases, get_head_fn) | Parses the given commit log
:param name: str, package name
:param content: list, directory paths
:param releases: list, releases
:param get_head_fn: function
:return: dict, changelog | 4.449386 | 4.483943 | 0.992293 |
functions = {}
# Some packages have dash in their name, replace them with underscore
# E.g. python-ldap to python_ldap
filename = "{}.py".format(name.replace("-", "_").lower())
path = os.path.join(
os.path.dirname(os.path.realpath(__file__)), # current working dir
"custom", # ... | def _load_custom_functions(vendor, name) | Loads custom functions from custom/{vendor}/{name}.py. This allows to quickly override any
function that is used to retrieve and parse the changelog.
:param name: str, package name
:param vendor: str, vendor
:return: dict, functions | 3.461837 | 3.347005 | 1.034309 |
# load default functions
from . import parser
from . import finder
fns = {
"get_content": get_content,
"parse": parser.parse,
"get_head": parser.get_head,
"find_changelogs": finder.find_changelogs
}
# load vendor functions
if vendor == "pypi":
fr... | def _bootstrap_functions(name, vendor, functions) | Loads all functions, including custom functions, for the given package/vendor and updates it
with the functions passed to this function. [:)]
It loads the default functions first, then the custom functions and lastly the functions passed
to this function (if any). [:)]
:param name: str, package name
... | 2.304121 | 2.192348 | 1.050983 |
if old_vendor != "pypi":
# XXX This might work for other starting vendors
# XXX but I didn't check. For now only allow
# XXX pypi -> launchpad.
return ''
for url in urls:
try:
return re.match(r"https?://launchpad.net/([\w.\-]+)",
... | def check_for_launchpad(old_vendor, name, urls) | Check if the project is hosted on launchpad.
:param name: str, name of the project
:param urls: set, urls to check.
:return: the name of the project on launchpad, or an empty string. | 7.220709 | 7.914466 | 0.912343 |
if _depth > 3:
# Protect against recursive things vendors here.
return ""
new_name = check_for_launchpad(old_vendor, name, urls)
if new_name:
return "launchpad", new_name
return "", "" | def check_switch_vendor(old_vendor, name, urls, _depth=0) | Check if the project should switch vendors. E.g
project pushed on pypi, but changelog on launchpad.
:param name: str, name of the project
:param urls: set, urls to check.
:return: tuple, (str(new vendor name), str(new project name)) | 7.830703 | 7.682481 | 1.019294 |
fns = _bootstrap_functions(name=name, vendor=vendor, functions=functions)
session = Session()
# get meta data for the given package and use this metadata to
# find urls pointing to a possible changelog
data = fns["get_metadata"](session=session, name=name)
releases = fns["get_releases"](nam... | def get(name, vendor="pypi", functions={}, _depth=0) | Tries to find a changelog for the given package.
:param name: str, package name
:param vendor: str, vendor
:param functions: dict, custom functions
:return: dict, changelog | 3.995039 | 3.873982 | 1.031249 |
if "find_changelogs" not in functions:
from .finder import find_git_repo
functions["find_changelogs"] = find_git_repo
if "get_content" not in functions:
functions["get_content"] = clone_repo
if "parse" not in functions:
from .parser import parse_commit_log
functi... | def get_commit_log(name, vendor='pypi', functions={}, _depth=0) | Tries to parse a changelog from the raw commit log.
:param name: str, package name
:param vendor: str, vendor
:param functions: dict, custom functions
:return: tuple, (dict -> commit log, str -> raw git log) | 3.238601 | 3.102602 | 1.043834 |
content = ""
for url in urls:
try:
logger.debug("GET changelog from {url}".format(url=url))
if "https://api.github.com" in url and url.endswith("releases"):
# this is a github API release page, fetch it if token is set
if not GITHUB_API_TOKEN... | def get_content(session, urls) | Loads the content from URLs, ignoring connection errors.
:param session: requests Session instance
:param urls: list, str URLs
:return: str, content | 3.014118 | 2.978076 | 1.012103 |
repos = []
for url in urls:
dir = mkdtemp()
call = ["git", "clone", url, dir]
subprocess.call(call)
repos.append((dir, url))
return repos | def clone_repo(session, urls) | Clones the given repos in temp directories
:param session: requests Session instance
:param urls: list, str URLs
:return: tuple, (str -> directory, str -> URL) | 3.354551 | 3.269923 | 1.025881 |
name = kwargs.get('name', '')
return "%s(%s)" % (name, ', '.join(str(a) for a in args)) | def unknown(*args, **kwargs) | Unknow scss function handler.
Simple return 'funcname(args)' | 3.629309 | 3.339755 | 1.086699 |
def __wrapper(*args, **kwargs):
root = kwargs.get('root')
if not Image:
if root and root.get_opt('warn'):
warn("Images manipulation require PIL")
return 'none'
return func(*args, **kwargs)
return __wrapper | def check_pil(func) | PIL module checking decorator. | 6.592397 | 6.594186 | 0.999729 |
return ColorValue((float(r), float(g), float(b), float(a))) | def _rgba(r, g, b, a, **kwargs) | Converts an rgba(red, green, blue, alpha) quadruplet into a color. | 4.913249 | 4.804485 | 1.022638 |
weight = float(weight)
c1 = color1.value
c2 = color2.value
p = 0.0 if weight < 0 else 1.0 if weight > 1 else weight
w = p * 2 - 1
a = c1[3] - c2[3]
w1 = ((w if (w * a == -1) else (w + a) / (1 + w * a)) + 1) / 2.0
w2 = 1 - w1
q = [w1, w1, w1, p]
r = [w2, w2, w2, 1 - p]
r... | def _mix(color1, color2, weight=0.5, **kwargs) | Mixes two colors together. | 2.554843 | 2.440189 | 1.046985 |
res = colorsys.hls_to_rgb(float(h), float(l), float(s))
return ColorValue([x * 255.0 for x in res] + [float(a)]) | def _hsla(h, s, l, a, **kwargs) | HSL with alpha channel color value. | 3.812485 | 3.593551 | 1.060924 |
h = colorsys.rgb_to_hls(*[x / 255.0 for x in color.value[:3]])[0]
return NumberValue(h * 360.0) | def _hue(color, **kwargs) | Get hue value of HSL color. | 3.899886 | 3.492927 | 1.116509 |
l = colorsys.rgb_to_hls(*[x / 255.0 for x in color.value[:3]])[1]
return NumberValue((l * 100, '%')) | def _lightness(color, **kwargs) | Get lightness value of HSL color. | 4.886686 | 4.526094 | 1.07967 |
s = colorsys.rgb_to_hls(*[x / 255.0 for x in color.value[:3]])[2]
return NumberValue((s * 100, '%')) | def _saturation(color, **kwargs) | Get saturation value of HSL color. | 5.124557 | 4.369111 | 1.172906 |
col = ColorValue(color)
args = [
255.0 - col.value[0],
255.0 - col.value[1],
255.0 - col.value[2],
col.value[3],
]
inverted = ColorValue(args)
return inverted | def _invert(color, **kwargs) | Returns the inverse (negative) of a color.
The red, green, and blue values are inverted, while the opacity is left alone. | 3.118018 | 3.450621 | 0.903611 |
parser = Stylesheet(cache)
return parser.load(path, precache=precache) | def load(path, cache=None, precache=False) | Parse from file. | 8.86006 | 7.00792 | 1.264292 |
if isinstance(target, ContentNode):
if target.name:
self.parent = target
self.name.parse(self)
self.name += target.name
target.ruleset.append(self)
self.root.cache['rset'][str(self.name).split()[0]].add(self)
super(... | def parse(self, target) | Parse nested rulesets
and save it in cache. | 8.28294 | 6.970761 | 1.18824 |
if not isinstance(target, Node):
parent = ContentNode(None, None, [])
parent.parse(target)
target = parent
super(Declaration, self).parse(target)
self.name = str(self.data[0])
while isinstance(target, Declaration):
self.name = '-'... | def parse(self, target) | Parse nested declaration. | 4.938028 | 4.536479 | 1.088516 |
super(VarDefinition, self).parse(target)
if isinstance(self.parent, ParseNode):
self.parent.ctx.update({self.name: self.expression.value})
self.root.set_var(self) | def parse(self, target) | Update root and parent context. | 7.365346 | 5.720172 | 1.287609 |
if not(vardef.default and self.cache['ctx'].get(vardef.name)):
self.cache['ctx'][vardef.name] = vardef.expression.value | def set_var(self, vardef) | Set variable to global stylesheet context. | 6.763057 | 5.920398 | 1.142332 |
self.cache['opts'][name] = value
if name == 'compress':
self.cache['delims'] = self.def_delims if not value else (
'',
'',
'') | def set_opt(self, name, value) | Set option. | 9.454777 | 9.012328 | 1.049094 |
self.cache['delims'] = cache.get('delims')
self.cache['opts'].update(cache.get('opts'))
self.cache['rset'].update(cache.get('rset'))
self.cache['mix'].update(cache.get('mix'))
map(self.set_var, cache['ctx'].values()) | def update(self, cache) | Update self cache from other. | 5.167327 | 4.512511 | 1.145111 |
assert isinstance(src, (unicode_, bytes_))
try:
nodes = STYLESHEET.parseString(src, parseAll=True)
return nodes
except ParseBaseException:
err = sys.exc_info()[1]
print(err.line, file=sys.stderr)
print(" " * (err.column - 1) + ... | def scan(src) | Scan scss from string and return nodes. | 3.300273 | 3.054226 | 1.08056 |
assert isinstance(src, (unicode_, bytes_))
nodes = self.scan(src.strip())
self.parse(nodes)
return ''.join(map(str, nodes)) | def loads(self, src) | Compile css from scss string. | 7.741475 | 6.928305 | 1.117369 |
precache = precache or self.get_opt('cache') or False
nodes = None
if isinstance(f, file_):
path = os.path.abspath(f.name)
else:
path = os.path.abspath(f)
f = open(f)
cache_path = os.path.splitext(path)[0] + '.ccss'
if preca... | def load(self, f, precache=None) | Compile scss from file.
File is string path of file object. | 2.889781 | 2.805306 | 1.030113 |
FILE = path.join(filepath, filename)
try:
cfg.read(FILE)
global _loaded
_loaded = True
except:
print("configfile not found.") | def load_config(filename, filepath='') | Loads config file
Parameters
----------
filename: str
Filename of config file (incl. file extension
filepath: str
Absolute path to directory of desired config file | 7.294333 | 8.980164 | 0.812272 |
resp = session.get(
"https://api.launchpad.net/1.0/{}/releases".format(name))
if resp.status_code == 200:
return resp.json()
return {} | def get_metadata(session, name) | Gets meta data from launchpad for the given package.
:param session: requests Session instance
:param name: str, package
:return: dict, meta data | 3.275191 | 2.925259 | 1.119624 |
for url in urls:
resp = session.get(url)
if resp.ok:
return resp.json()
return {} | def get_content(session, urls) | Loads the content from URLs, ignoring connection errors.
:param session: requests Session instance
:param urls: list, str URLs
:return: str, content | 2.985345 | 4.196622 | 0.711368 |
try:
return {e["version"]: e["changelog"] for e in content["entries"]
if e["changelog"]}
except KeyError:
return {} | def parse(name, content, releases, get_head_fn) | Parses the given content for a valid changelog
:param name: str, package name
:param content: str, content
:param releases: list, releases
:param get_head_fn: function
:return: dict, changelog | 6.86109 | 6.527909 | 1.05104 |
'''emot.emoji is use to detect emoji from text
>>> text = "I love python 👨 :-)"
>>> emot.emoji(text)
>>> {'value': ['👨'], 'mean': [':man:'], 'location': [[14, 14]], 'flag': True}
'''
__entities = {}
__value = []
__mean = []
__location = []
flag = True
try:
... | def emoji(string) | emot.emoji is use to detect emoji from text
>>> text = "I love python 👨 :-)"
>>> emot.emoji(text)
>>> {'value': ['👨'], 'mean': [':man:'], 'location': [[14, 14]], 'flag': True} | 4.329098 | 2.488215 | 1.739841 |
'''emot.emoticons is use to detect emoticons from text
>>> text = "I love python 👨 :-)"
>>> emot.emoticons(text)
>>> {'value': [':-)'], 'location': [[16, 19]], 'mean': ['Happy face smiley'], 'flag': True}
'''
__entities = []
flag = True
try:
pattern = u'(' + u'|'.jo... | def emoticons(string) | emot.emoticons is use to detect emoticons from text
>>> text = "I love python 👨 :-)"
>>> emot.emoticons(text)
>>> {'value': [':-)'], 'location': [[16, 19]], 'mean': ['Happy face smiley'], 'flag': True} | 4.735954 | 2.787644 | 1.698909 |
# Check if login manager has been initialized
if not hasattr(app, 'login_manager'):
self.login_manager.init_app(
app,
add_context_processor=add_context_processor)
# Clear flashed messages since we redirect to auth immediately
self.lo... | def init_app(self, app, add_context_processor=True) | Initialize with app configuration | 3.579759 | 3.681499 | 0.972365 |
kwargs.setdefault('response_type', 'code')
kwargs.setdefault('access_type', 'online')
if 'prompt' not in kwargs:
kwargs.setdefault('approval_prompt', 'auto')
scopes = kwargs.pop('scopes', self.scopes.split(','))
if USERINFO_PROFILE_SCOPE not in scopes:
... | def login_url(self, params=None, **kwargs) | Return login url with params encoded in state
Available Google auth server params:
response_type: code, token
prompt: none, select_account, consent
approval_prompt: force, auto
access_type: online, offline
scopes: string (separated with commas) or list
redirect_u... | 2.674233 | 2.617336 | 1.021738 |
return redirect(self.login_url(params=dict(next=request.url))) | def unauthorized_callback(self) | Redirect to login url with next param set as request.url | 9.288171 | 5.189285 | 1.789875 |
token = requests.post(GOOGLE_OAUTH2_TOKEN_URL, data=dict(
code=code,
redirect_uri=redirect_uri,
grant_type='authorization_code',
client_id=self.client_id,
client_secret=self.client_secret,
)).json()
if not token or token.get('... | def exchange_code(self, code, redirect_uri) | Exchanges code for token/s | 2.276317 | 2.210287 | 1.029874 |
token = requests.post(GOOGLE_OAUTH2_TOKEN_URL, data=dict(
refresh_token=refresh_token,
grant_type='refresh_token',
client_id=self.client_id,
client_secret=self.client_secret,
)).json()
if not token or token.get('error'):
retu... | def get_access_token(self, refresh_token) | Use a refresh token to obtain a new access token | 2.413001 | 2.370859 | 1.017775 |
@wraps(view_func)
def decorated(*args, **kwargs):
params = {}
# Check sig
if 'state' in request.args:
params.update(**self.parse_state(request.args.get('state')))
if params.pop('sig', None) != make_secure_token(**params):
... | def oauth2callback(self, view_func) | Decorator for OAuth2 callback. Calls `GoogleLogin.login` then
passes results to `view_func`. | 3.314633 | 3.324455 | 0.997046 |
changelog = {}
releases = frozenset(releases)
head = False
date_line = None
for line in content.splitlines():
if DATE_RE.match(line):
date_line = line
continue
if line.strip().startswith("PyAudio"):
try:
head = line.strip().spl... | def parse(name, content, releases, get_head_fn) | Parses the given content for a valid changelog
:param name: str, package name
:param content: str, content
:param releases: list, releases
:param get_head_fn: function
:return: dict, changelog | 3.69162 | 3.837492 | 0.961988 |
if validators.url(url):
return url
elif validators.domain(url):
return "http://{}".format(url)
return "" | def validate_url(url) | Validates the URL
:param url:
:return: | 3.028711 | 4.074283 | 0.743373 |
try:
if "github.com" in url:
return re.findall(r"https?://w?w?w?.?github.com/[\w\-]+/[\w.-]+", url)[0]
elif "bitbucket.org" in url:
return re.findall(r"https?://bitbucket.org/[\w.-]+/[\w.-]+", url)[0] + "/src/"
elif "launchpad.net" in url:
return re.f... | def validate_repo_url(url) | Validates and formats `url` to be valid URL pointing to a repo on bitbucket.org or github.com
:param url: str, URL
:return: str, valid URL if valid repo, emptry string otherwise | 2.699372 | 2.717561 | 0.993307 |
def unclutter(string):
# strip out all python references and remove all excessive characters
string = string.lower().replace("_", "-").replace(".", "-")
for replace in ["python-", "py-", "-py", "-python"]:
string = string.replace(replace, "")
return re.sub("[^0123456... | def contains_project_name(name, link) | Checks if the given link `somewhat` contains the project name.
:param name: str, project name
:param link: str, link
:return: bool, True if the link contains the project name | 5.187822 | 5.59585 | 0.927084 |
for _url in candidates:
if validate_url(_url):
try:
resp = session.get(_url)
if resp.status_code == 200:
tree = etree.HTML(resp.content)
if tree:
for link in frozenset([str(l) for l in tree.xpath... | def find_repo_urls(session, name, candidates) | Visits the given URL candidates and searches the page for valid links to a repository.
:param session: requests Session instance
:param name: str, project name
:param candidates: list, list of URL candidates
:return: str, URL to a repo | 4.823815 | 4.816776 | 1.001461 |
logger.debug("Trying to find changelog on repo {}".format(repo_url))
resp = session.get(repo_url)
if resp.status_code == 200:
# build up a list of URLs on this repo. xpath() isn't returning raw strings, so we have to
# convert them first. We also need to strip out all GET parameters if ... | def find_changelog(session, repo_url, deep=True) | Tries to find changelogs on the given `repo_url`.
:param session: requests Session instance
:param repo_url: str, URL to the repo
:param deep: bool, deep search
:return: str, URL to the raw changelog content | 3.611847 | 3.583501 | 1.00791 |
# first, we are going to filter down the URL candidates to be all valid urls
candidates = set(url for url in [validate_url(_url) for _url in candidates] if url)
logger.info("Got repo candidates {}".format(candidates))
repos = set(url for url in [validate_repo_url(_url) for _url in candidates] if ur... | def filter_repo_urls(candidates) | Filters down a list of URL candidates
:param candidates: list, URL candidates
:return: set, Repo URLs | 5.426107 | 5.142573 | 1.055135 |
repos = filter_repo_urls(candidates=candidates)
# if we are lucky and there isn't a valid repo URL in our URL candidates, we need to go deeper
# and check the URLs if they contain a link to a repo
if not repos:
logger.info("No repo found, trying to find one on related sites {}".format(candi... | def find_changelogs(session, name, candidates) | Tries to find changelogs on the given URL candidates
:param session: requests Session instance
:param name: str, project name
:param candidates: list, URL candidates
:return: tuple, (set(changelog URLs), set(repo URLs)) | 5.34703 | 5.001447 | 1.069097 |
repos = filter_repo_urls(candidates=candidates)
# if we are lucky and there isn't a valid repo URL in our URL candidates, we need to go deeper
# and check the URLs if they contain a link to a repo
if not repos:
logger.info("No repo found, trying to find one on related sites {}".format(can... | def find_git_repo(session, name, candidates) | Tries to find git repos on the given URL candidates
:param session: requests Session instance
:param name: str, project name
:param candidates: list, URL candidates
:return: tuple, (set(git URLs), set(repo URLs)) | 3.425352 | 3.144635 | 1.089269 |
# if this package has valid meta data, build up a list of URL candidates we can possibly
# search for changelogs on
candidates = [
url for url in
[data.get(attr) for attr in (
"project_uri", "homepage_uri", "wiki_uri", "documentation_uri", "mailing_list_uri",
"so... | def get_urls(session, name, data, find_changelogs_fn, **kwargs) | Gets URLs to changelogs.
:param session: requests Session instance
:param name: str, package name
:param data: dict, meta data
:param find_changelogs_fn: function, find_changelogs
:return: tuple, (set(changelog URLs), set(repo URLs)) | 5.082128 | 5.088158 | 0.998815 |
for cmd in COMMANDS:
if cmd.startswith(text):
if not state:
return cmd
else:
state -= 1 | def complete(text, state) | Auto complete scss constructions in interactive mode. | 4.372799 | 4.471637 | 0.977897 |
cfg = cp.ConfigParser()
cfg.read(filepath)
if not cfg.has_section(section):
print('The section "{sec}" is not in the config file {file}.'
.format(sec=section,
file=filepath))
cfg = create_oedb_config_file(filepath, section)
return cfg | def readcfg(filepath, section) | Reads the configuration file. If section is not available, calls
create_oedb_config_file to add the new section to an existing config.ini.
Parameters
----------
filepath : str
Absolute path of config file including the filename itself
section : str
Section in config file which c... | 4.399241 | 3.176012 | 1.385146 |
print('Please enter your connection details:')
dialect = input('Enter input value for `dialect` (default: psycopg2): ') or 'psycopg2'
username = input('Enter value for `username`: ')
database = input('Enter value for `database`: ')
host = input('Enter value for `host`: ')
port = input('Ente... | def get_connection_details(section) | Asks the user for the database connection details and returns them as a
ConfigParser-object.
Parameters
----------
None
Returns
-------
cfg : configparser.ConfigParser
Used for configuration file parser language. | 2.679169 | 2.669915 | 1.003466 |
# define default filepath if not provided
if filepath is None:
filepath = os.path.join(os.path.expanduser("~"), '.egoio', 'config.ini')
# does the file exist?
if not os.path.isfile(filepath):
print('DB config file {file} not found. '
'This might be the first run of the t... | def connection(filepath=None, section='oep') | Instantiate a database connection (for the use with SQLAlchemy).
The keyword argument `filepath` specifies the location of the config file
that contains database connection information. If not given, the default
of `~/.egoio/config.ini` applies.
Parameters
----------
filepath : str
Abs... | 2.909476 | 2.729907 | 1.065779 |
map = {}
path = os.path.join(
os.path.dirname(os.path.realpath(__file__)), # current working dir ../
"custom", # ../custom/
"pypi", # ../custom/pypi/
"map.txt" # ../custom/pypi/map.txt
)
with open(path) as f:
for line in f.readlines():
package... | def get_url_map() | Loads custom/pypi/map.txt and builds a dict where map[package_name] = url
:return: dict, urls | 3.073361 | 2.354841 | 1.305124 |
# check if there's a changelog in ../custom/pypi/map.txt
map = get_url_map()
if name.lower().replace("_", "-") in map:
logger.info("Package {name}'s URL is in pypi/map.txt, returning".format(name=name))
return [map[name.lower().replace("_", "-")]], set()
# if this package has valid ... | def get_urls(session, name, data, find_changelogs_fn, **kwargs) | Gets URLs to changelogs.
:param session: requests Session instance
:param name: str, package name
:param data: dict, meta data
:param find_changelogs_fn: function, find_changelogs
:return: tuple, (set(changelog URLs), set(repo URLs)) | 4.620085 | 4.334664 | 1.065846 |
from ..mixins import ModelMixin
for arg in ("instance", "decider", "identifier", "fields", "default_language"):
if getattr(self, arg) is None:
raise AttributeError("%s must not be None" % arg)
if not isinstance(self.instance, (ModelMixin,)):
rai... | def validate_args(self) | Validates arguments. | 4.421925 | 4.263998 | 1.037037 |
# Current instance language (if user uses activate_language() method)
if self._language is not None:
return self._language
# Current site language (translation.get_language())
current = utils.get_language()
if current in self.supported_languages:
... | def active_language(self) | Returns active language. | 7.331949 | 6.843433 | 1.071385 |
return [
instance
for k, v in six.iteritems(self.instance._linguist_translations)
for instance in v.values()
] | def translation_instances(self) | Returns translation instances. | 8.040078 | 7.005819 | 1.147629 |
is_new = bool(instance.pk is None)
try:
cached_obj = instance._linguist_translations[field_name][language]
if not cached_obj.field_name:
cached_obj.field_name = field_name
if not cached_obj.language:
cached_obj.language = lang... | def get_cache(
self,
instance,
translation=None,
language=None,
field_name=None,
field_value=None,
) | Returns translation from cache. | 2.253147 | 2.210541 | 1.019274 |
if instance is not None and translation is not None:
cached_obj = CachedTranslation.from_object(translation)
instance._linguist_translations[translation.field_name][
translation.language
] = cached_obj
return cached_obj
if instanc... | def set_cache(
self,
instance=None,
translation=None,
language=None,
field_name=None,
field_value=None,
) | Add a new translation into the cache. | 2.554368 | 2.492587 | 1.024786 |
from .models import Translation
new_args = self.get_cleaned_args(args)
new_kwargs = self.get_cleaned_kwargs(kwargs)
translation_args = self.get_translation_args(args)
translation_kwargs = self.get_translation_kwargs(kwargs)
has_linguist_args = self.has_linguis... | def _filter_or_exclude(self, negate, *args, **kwargs) | Overrides default behavior to handle linguist fields. | 2.648231 | 2.510273 | 1.054957 |
return [
(f, f.model if f.model != self.model else None)
for f in self.model._meta.get_fields()
if f.concrete
and (
not f.is_relation or f.one_to_one or (f.many_to_one and f.related_model)
)
] | def _get_concrete_fields_with_model(self) | For compatibility with Django<=1.10. Replace old
`_meta.get_concrete_fields_with_model`.
https://docs.djangoproject.com/en/1.10/ref/models/meta/ | 2.708025 | 2.372975 | 1.141194 |
return list(self.model._linguist.fields) + list(
utils.get_language_fields(self.model._linguist.fields)
) | def linguist_field_names(self) | Returns linguist field names (example: "title" and "title_fr"). | 6.788896 | 5.973482 | 1.136506 |
for k in kwargs:
if self.is_linguist_lookup(k):
return True
return False | def has_linguist_kwargs(self, kwargs) | Parses the given kwargs and returns True if they contain
linguist lookups. | 4.62127 | 3.253162 | 1.420547 |
linguist_args = []
for arg in args:
condition = self._get_linguist_condition(arg)
if condition:
linguist_args.append(condition)
return bool(linguist_args) | def has_linguist_args(self, args) | Parses the given args and returns True if they contain
linguist lookups. | 2.760706 | 2.642679 | 1.044662 |
translation_args = []
for arg in args:
condition = self._get_linguist_condition(arg, transform=True)
if condition:
translation_args.append(condition)
return translation_args | def get_translation_args(self, args) | Returns linguist args from model args. | 4.524775 | 3.658611 | 1.236747 |
lks = []
for k, v in six.iteritems(kwargs):
if self.is_linguist_lookup(k):
lks.append(
utils.get_translation_lookup(self.model._linguist.identifier, k, v)
)
translation_kwargs = {}
for lk in lks:
for k,... | def get_translation_kwargs(self, kwargs) | Returns linguist lookup kwargs (related to Translation model). | 3.559089 | 3.070948 | 1.158955 |
field = utils.get_field_name_from_lookup(lookup)
# To keep default behavior with "FieldError: Cannot resolve keyword".
if (
field not in self.concrete_field_names
and field in self.linguist_field_names
):
return True
return False | def is_linguist_lookup(self, lookup) | Returns true if the given lookup is a valid linguist lookup. | 10.279919 | 10.185798 | 1.00924 |
# We deal with a node
if isinstance(condition, Q):
children = []
for child in condition.children:
parsed = self._get_linguist_condition(
condition=child, reverse=reverse, transform=transform
)
if parsed ... | def _get_linguist_condition(self, condition, reverse=False, transform=False) | Parses Q tree and returns linguist lookups or model lookups
if reverse is True. | 3.693046 | 3.380685 | 1.092396 |
if not args:
return args
cleaned_args = []
for arg in args:
condition = self._get_linguist_condition(arg, True)
if condition:
cleaned_args.append(condition)
return cleaned_args | def get_cleaned_args(self, args) | Returns positional arguments for related model query. | 4.038644 | 3.501689 | 1.153342 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.