code stringlengths 52 7.75k | docs stringlengths 1 5.85k |
|---|---|
def validate_openssl():
try:
open_ssl_exe = which("openssl")
if not open_ssl_exe:
raise Exception("No openssl exe found in path")
try:
# execute a an invalid command to get output with available options
# since openssl does not have a --help option u... | Validates OpenSSL to ensure it has TLS_FALLBACK_SCSV supported |
def validate_against_current_config(self, current_rs_conf):
# if rs is not configured yet then there is nothing to validate
if not current_rs_conf:
return
my_host = self.get_host()
current_member_confs = current_rs_conf['members']
err = None
for cur... | Validates the member document against current rs conf
1- If there is a member in current config with _id equals to my id
then ensure hosts addresses resolve to the same host
2- If there is a member in current config with host resolving to my
host then ensure that ... |
def get_dump_best_secondary(self, max_repl_lag=None):
secondary_lag_tuples = []
primary_member = self.get_primary_member()
if not primary_member:
raise MongoctlException("Unable to determine primary member for"
" cluster '%s'" % self.id)
... | Returns the best secondary member to be used for dumping
best = passives with least lags, if no passives then least lag |
def is_replicaset_initialized(self):
# it's possible isMaster returns an "incomplete" result if we
# query a replica set member while it's loading the replica set config
# https://jira.mongodb.org/browse/SERVER-13458
# let's try to detect this state before proceeding
# ... | iterate on all members and check if any has joined the replica |
def match_member_id(self, member_conf, current_member_confs):
if current_member_confs is None:
return None
for curr_mem_conf in current_member_confs:
if is_same_address(member_conf['host'], curr_mem_conf['host']):
return curr_mem_conf['_id']
ret... | Attempts to find an id for member_conf where fom current members confs
there exists a element.
Returns the id of an element of current confs
WHERE member_conf.host and element.host are EQUAL or map to same host |
def setup_server_users(server):
"""if not should_seed_users(server):
log_verbose("Not seeding users for server '%s'" % server.id)
return"""
log_info("Checking if there are any users that need to be added for "
"server '%s'..." % server.id)
seed_users = server.get_seed_use... | Seeds all users returned by get_seed_users() IF there are no users seed yet
i.e. system.users collection is empty |
def prepend_global_admin_user(other_users, server):
cred0 = get_global_login_user(server, "admin")
if cred0 and cred0["username"] and cred0["password"]:
log_verbose("Seeding : CRED0 to the front of the line!")
return [cred0] + other_users if other_users else [cred0]
else:
return... | When making lists of administrative users -- e.g., seeding a new server --
it's useful to put the credentials supplied on the command line at the head
of the queue. |
def get_os_dist_info():
distribution = platform.dist()
dist_name = distribution[0].lower()
dist_version_str = distribution[1]
if dist_name and dist_version_str:
return dist_name, dist_version_str
else:
return None, None | Returns the distribution info |
def export_cmd_options(self, options_override=None, standalone=False):
cmd_options = super(MongosServer, self).export_cmd_options(
options_override=options_override)
# Add configServers arg
cluster = self.get_validate_cluster()
cmd_options["configdb"] = cluster.get... | Override!
:return: |
def get_mongo_version(self):
if self._mongo_version:
return self._mongo_version
mongo_version = self.read_current_mongo_version()
if not mongo_version:
mongo_version = self.get_configured_mongo_version()
self._mongo_version = mongo_version
ret... | Gets mongo version of the server if it is running. Otherwise return
version configured in mongoVersion property |
def get_server_build_info(self):
if self.is_online():
try:
return self.get_mongo_client().server_info()
except OperationFailure, ofe:
log_exception(ofe)
if "there are no users authenticated" in str(ofe):
# this ... | issues a buildinfo command |
def authenticate_db(self, db, dbname, retry=True):
log_verbose("Server '%s' attempting to authenticate to db '%s'" % (self.id, dbname))
login_user = self.get_login_user(dbname)
username = None
password = None
auth_success = False
if login_user:
use... | Returns True if we manage to auth to the given db, else False. |
def get_working_login(self, database, username=None, password=None):
login_user = None
# this will authenticate and update login user
self.get_db(database, username=username, password=password,
never_auth_with_admin=True)
login_user = self.get_login_user(... | authenticate to the specified database starting with specified
username/password (if present), try to return a successful login
within 3 attempts |
def needs_to_auth(self, dbname):
log_debug("Checking if server '%s' needs to auth on db '%s'...." %
(self.id, dbname))
try:
client = self.get_mongo_client()
db = client.get_database(dbname)
db.collection_names()
result = False
... | Determines if the server needs to authenticate to the database.
NOTE: we stopped depending on is_auth() since its only a configuration
and may not be accurate |
def needs_repl_key(self):
cluster = self.get_cluster()
return (self.supports_repl_key() and
cluster is not None and cluster.get_repl_key() is not None) | We need a repl key if you are auth + a cluster member +
version is None or >= 2.0.0 |
def exact_or_minor_exe_version_match(executable_name,
exe_version_tuples,
version):
exe = exact_exe_version_match(executable_name,
exe_version_tuples,
version)
if n... | IF there is an exact match then use it
OTHERWISE try to find a minor version match |
def is_server_or_cluster_db_address(value):
# check if value is an id string
id_path = value.split("/")
id = id_path[0]
return len(id_path) <= 2 and (repository.lookup_server(id) or
repository.lookup_cluster(id)) | checks if the specified value is in the form of
[server or cluster id][/database] |
def until(time):
end = time
# Convert datetime to unix timestamp and adjust for locality
if isinstance(time, datetime):
zoneDiff = pytime.time() - (datetime.now()- datetime(1970, 1, 1)).total_seconds()
end = (time - datetime(1970, 1, 1)).total_seconds() + zoneDiff
# Type check
... | Pause your program until a specific end time.
'time' is either a valid datetime object or unix timestamp in seconds (i.e. seconds since Unix epoch) |
def seconds(num):
now = pytime.time()
end = now + num
until(end) | Pause for this many seconds |
def _pre_mongod_server_start(server, options_override=None):
lock_file_path = server.get_lock_file_path()
no_journal = (server.get_cmd_option("nojournal") or
(options_override and "nojournal" in options_override))
if (os.path.exists(lock_file_path) and
server.is_arbiter_... | Does necessary work before starting a server
1- An efficiency step for arbiters running with --no-journal
* there is a lock file ==>
* server must not have exited cleanly from last run, and does not know
how to auto-recover (as a journalled server would)
* however: this is an arb... |
def prepare_mongod_server(server):
log_info("Preparing server '%s' for use as configured..." %
server.id)
cluster = server.get_cluster()
# setup the local users if server supports that
if server.supports_local_users():
users.setup_server_local_users(server)
if not server.... | Contains post start server operations |
def _rlimit_min(one_val, nother_val):
if one_val < 0 or nother_val < 0 :
return max(one_val, nother_val)
else:
return min(one_val, nother_val) | Returns the more stringent rlimit value. -1 means no limit. |
def generate_start_command(server, options_override=None, standalone=False):
command = []
if mongod_needs_numactl():
log_info("Running on a NUMA machine...")
command = apply_numactl(command)
# append the mongod executable
command.append(get_server_executable(server))
# create... | Check if we need to use numactl if we are running on a NUMA box.
10gen recommends using numactl on NUMA. For more info, see
http://www.mongodb.org/display/DOCS/NUMA |
def get_server_home(self):
home_dir = super(MongodServer, self).get_server_home()
if not home_dir:
home_dir = self.get_db_path()
return home_dir | Override!
:return: |
def export_cmd_options(self, options_override=None, standalone=False):
cmd_options = super(MongodServer, self).export_cmd_options(
options_override=options_override)
# reset some props to exporting vals
cmd_options['dbpath'] = self.get_db_path()
if 'repairpath' in ... | Override!
:return: |
def get_seed_users(self):
seed_users = super(MongodServer, self).get_seed_users()
# exempt database users for config servers
if seed_users and self.is_config_server():
for dbname in seed_users.keys():
if dbname not in ["admin", "local", "config"]:
... | Override!
:return: |
def get_repl_lag(self, master_status):
member_status = self.get_member_rs_status()
if not member_status:
raise MongoctlException("Unable to determine replicaset status for"
" member '%s'" %
self.id)
re... | Given two 'members' elements from rs.status(),
return lag between their optimes (in secs). |
def mongo_client(*args, **kwargs):
kwargs = kwargs or {}
connection_timeout_ms = kwargs.get("connectTimeoutMS") or CONN_TIMEOUT_MS
kwargs.update({
"socketTimeoutMS": connection_timeout_ms,
"connectTimeoutMS": connection_timeout_ms,
"maxPoolSize": 1
})
if pymongo.get_v... | wrapper around mongo client
:param args:
:param kwargs:
:return: |
def parse(self, data):
graph = self._init_graph()
# ensure is NetJSON NetworkGraph object
if 'type' not in data or data['type'] != 'NetworkGraph':
raise ParserError('Parse error, not a NetworkGraph object')
# ensure required keys are present
required_keys = [... | Converts a NetJSON 'NetworkGraph' object
to a NetworkX Graph object,which is then returned.
Additionally checks for protocol version, revision and metric. |
def parse(self, data):
# initialize graph and list of aggregated nodes
graph = self._init_graph()
server = self._server_common_name
# add server (central node) to graph
graph.add_node(server)
# data may be empty
if data is None:
clients = []
... | Converts a OpenVPN JSON to a NetworkX Graph object
which is then returned. |
def to_python(self, data):
try:
return super(BatmanParser, self).to_python(data)
except ConversionException as e:
return self._txtinfo_to_python(e.data) | Adds support for txtinfo format |
def _txtinfo_to_python(self, data):
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 = [... | Converts txtinfo format to python |
def _get_primary_address(self, mac_address, node_list):
for local_addresses in node_list:
if mac_address in local_addresses:
return local_addresses[0]
return mac_address | Uses the _get_aggregated_node_list structure to find
the primary mac address associated to a secondary one,
if none is found returns itself. |
def _get_aggregated_node_list(self, data):
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 | Returns list of main and secondary mac addresses. |
def parse(self, data):
method = getattr(self, '_parse_{0}'.format(self._format))
return method(data) | Calls the right method depending on the format,
which can be one of the wollowing:
* alfred_vis
* txtinfo |
def _parse_alfred_vis(self, data):
# 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')
... | 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. |
def _parse_txtinfo(self, data):
graph = self._init_graph()
for link in data:
graph.add_edge(link['source'],
link['target'],
weight=link['cost'])
return graph | Converts the python list returned by self._txtinfo_to_python()
to a NetworkX Graph object, which is then returned. |
def to_python(self, data):
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('C... | 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 ... |
def json(self, dict=False, **kwargs):
try:
graph = self.graph
except AttributeError:
raise NotImplementedError()
return _netjson_networkgraph(self.protocol,
self.version,
self.revision,
... | Outputs NetJSON format |
def diff(old, new):
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 = _... | Returns differences of two network topologies old and new
in NetJSON NetworkGraph compatible format |
def _make_diff(old, new, both):
# 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 ne... | 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 |
def _find_unchanged(old, new):
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 | returns edges that are in both old and new |
def _find_changed(old, new, both):
# 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 rec... | returns links that have changed cost |
def parse(self, data):
# 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 gr... | Converts a BMX6 b6m JSON to a NetworkX Graph object
which is then returned. |
def parse(self, data):
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
interf... | Converts a CNML structure to a NetworkX Graph object
which is then returned. |
def to_python(self, data):
try:
return super(OlsrParser, self).to_python(data)
except ConversionException as e:
return self._txtinfo_to_jsoninfo(e.data) | Adds support for txtinfo format |
def parse(self, data):
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
... | 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. |
def _txtinfo_to_jsoninfo(self, data):
# 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('... | converts olsr 1 txtinfo format to jsoninfo |
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... |
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:
| ... |
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... |
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... |
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) | ... |
def format(self, record):
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(re... | :param logging.LogRecord record: |
def get_releases(data, **kwargs):
if "versions" in data:
return sorted(data["versions"].keys(), key=lambda v: parse(v), reverse=True)
return [] | Gets all releases from pypi meta data.
:param data: dict, meta data
:return: list, str releases |
def get_urls(session, name, data, find_changelogs_fn, **kwargs):
# 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 "h... | 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)) |
def parse(name, content, releases, get_head_fn):
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] = ""
... | 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 |
def parse_commit_log(name, content, releases, get_head_fn):
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-page... | 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 |
def _load_custom_functions(vendor, name):
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__)), #... | 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 |
def check_for_launchpad(old_vendor, name, urls):
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?://la... | 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. |
def check_switch_vendor(old_vendor, name, urls, _depth=0):
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 "", "" | 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)) |
def get(name, vendor="pypi", functions={}, _depth=0):
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=sess... | 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 |
def get_commit_log(name, vendor='pypi', functions={}, _depth=0):
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 funct... | 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) |
def get_content(session, urls):
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
... | Loads the content from URLs, ignoring connection errors.
:param session: requests Session instance
:param urls: list, str URLs
:return: str, content |
def clone_repo(session, urls):
repos = []
for url in urls:
dir = mkdtemp()
call = ["git", "clone", url, dir]
subprocess.call(call)
repos.append((dir, url))
return repos | Clones the given repos in temp directories
:param session: requests Session instance
:param urls: list, str URLs
:return: tuple, (str -> directory, str -> URL) |
def unknown(*args, **kwargs):
name = kwargs.get('name', '')
return "%s(%s)" % (name, ', '.join(str(a) for a in args)) | Unknow scss function handler.
Simple return 'funcname(args)' |
def check_pil(func):
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 | PIL module checking decorator. |
def _rgba(r, g, b, a, **kwargs):
return ColorValue((float(r), float(g), float(b), float(a))) | Converts an rgba(red, green, blue, alpha) quadruplet into a color. |
def _mix(color1, color2, weight=0.5, **kwargs):
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 = [... | Mixes two colors together. |
def _hsla(h, s, l, a, **kwargs):
res = colorsys.hls_to_rgb(float(h), float(l), float(s))
return ColorValue([x * 255.0 for x in res] + [float(a)]) | HSL with alpha channel color value. |
def _hue(color, **kwargs):
h = colorsys.rgb_to_hls(*[x / 255.0 for x in color.value[:3]])[0]
return NumberValue(h * 360.0) | Get hue value of HSL color. |
def _lightness(color, **kwargs):
l = colorsys.rgb_to_hls(*[x / 255.0 for x in color.value[:3]])[1]
return NumberValue((l * 100, '%')) | Get lightness value of HSL color. |
def _saturation(color, **kwargs):
s = colorsys.rgb_to_hls(*[x / 255.0 for x in color.value[:3]])[2]
return NumberValue((s * 100, '%')) | Get saturation value of HSL color. |
def _invert(color, **kwargs):
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 | Returns the inverse (negative) of a color.
The red, green, and blue values are inverted, while the opacity is left alone. |
def load(path, cache=None, precache=False):
parser = Stylesheet(cache)
return parser.load(path, precache=precache) | Parse from file. |
def parse(self, target):
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]]... | Parse nested rulesets
and save it in cache. |
def parse(self, target):
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):
... | Parse nested declaration. |
def parse(self, target):
super(VarDefinition, self).parse(target)
if isinstance(self.parent, ParseNode):
self.parent.ctx.update({self.name: self.expression.value})
self.root.set_var(self) | Update root and parent context. |
def set_var(self, vardef):
if not(vardef.default and self.cache['ctx'].get(vardef.name)):
self.cache['ctx'][vardef.name] = vardef.expression.value | Set variable to global stylesheet context. |
def set_opt(self, name, value):
self.cache['opts'][name] = value
if name == 'compress':
self.cache['delims'] = self.def_delims if not value else (
'',
'',
'') | Set option. |
def update(self, cache):
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()) | Update self cache from other. |
def scan(src):
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... | Scan scss from string and return nodes. |
def loads(self, src):
assert isinstance(src, (unicode_, bytes_))
nodes = self.scan(src.strip())
self.parse(nodes)
return ''.join(map(str, nodes)) | Compile css from scss string. |
def load(self, f, precache=None):
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(pa... | Compile scss from file.
File is string path of file object. |
def load_config(filename, filepath=''):
FILE = path.join(filepath, filename)
try:
cfg.read(FILE)
global _loaded
_loaded = True
except:
print("configfile not found.") | Loads config file
Parameters
----------
filename: str
Filename of config file (incl. file extension
filepath: str
Absolute path to directory of desired config file |
def get_metadata(session, name):
resp = session.get(
"https://api.launchpad.net/1.0/{}/releases".format(name))
if resp.status_code == 200:
return resp.json()
return {} | Gets meta data from launchpad for the given package.
:param session: requests Session instance
:param name: str, package
:return: dict, meta data |
def get_content(session, urls):
for url in urls:
resp = session.get(url)
if resp.ok:
return resp.json()
return {} | Loads the content from URLs, ignoring connection errors.
:param session: requests Session instance
:param urls: list, str URLs
:return: str, content |
def parse(name, content, releases, get_head_fn):
try:
return {e["version"]: e["changelog"] for e in content["entries"]
if e["changelog"]}
except KeyError:
return {} | 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 |
def init_app(self, app, add_context_processor=True):
# 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 ... | Initialize with app configuration |
def login_url(self, params=None, **kwargs):
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(','))
i... | 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... |
def unauthorized_callback(self):
return redirect(self.login_url(params=dict(next=request.url))) | Redirect to login url with next param set as request.url |
def exchange_code(self, code, redirect_uri):
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,
... | Exchanges code for token/s |
def get_access_token(self, refresh_token):
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 to... | Use a refresh token to obtain a new access token |
def oauth2callback(self, view_func):
@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... | Decorator for OAuth2 callback. Calls `GoogleLogin.login` then
passes results to `view_func`. |
def parse(name, content, releases, get_head_fn):
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"):
... | 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 |
def validate_url(url):
if validators.url(url):
return url
elif validators.domain(url):
return "http://{}".format(url)
return "" | Validates the URL
:param url:
:return: |
def validate_repo_url(url):
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 ... | 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 |
def contains_project_name(name, link):
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(replac... | 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 |
def find_repo_urls(session, name, candidates):
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:
fo... | 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 |
def filter_repo_urls(candidates):
# 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(_... | Filters down a list of URL candidates
:param candidates: list, URL candidates
:return: set, Repo URLs |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.