code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
result = self.find_message(msg)
if result is None:
return
self.index += 1
images_path = 'images'
if self.directory:
images_path = os.path.join(self.directory, images_path)
if not os.path.isdir(images_path):
os.makedirs(imag... | def build_image(self, msg) | Convert base64 encoding to png.
Strips msg of the base64 image encoding and outputs
the images to the specified directory. | 2.893722 | 2.838751 | 1.019364 |
cairosvg.svg2png(bytestring=msg.encode('utf-8'), write_to=fh) | def write_image_to_disk(self, msg, result, fh) | Decode message to PNG and write to disk. | 3.594595 | 3.165725 | 1.135473 |
if 'result' in paragraph and paragraph['result']['msg']:
msg = paragraph['result']['msg']
self.output_options[paragraph['result']['type']](msg) | def process_results(self, paragraph) | Route Zeppelin output types to corresponding handlers. | 7.51624 | 5.151357 | 1.45908 |
fh.write(base64.b64decode(result.group(1).encode('utf-8'))) | def write_image_to_disk(self, msg, result, fh) | Decode message to PNG and write to disk. | 4.608777 | 3.924619 | 1.174325 |
if 'editorMode' in paragraph['config']:
mode = paragraph['config']['editorMode'].split('/')[-1]
if 'results' in paragraph and paragraph['results']['msg']:
msg = paragraph['results']['msg'][0]
if mode not in ('text', 'markdown'):
... | def process_results(self, paragraph) | Routes Zeppelin output types to corresponding handlers. | 6.690277 | 5.825505 | 1.148446 |
try:
if bottle.request.method == 'GET':
# Just return what we currenty have cached as the route spec
data = CURRENT_STATE.route_spec
if not data:
bottle.response.status = 404
msg = "Route spec not found!"
else:
... | def handle_route_spec_request() | Process request for route spec.
Either a new one is posted or the current one is to be retrieved. | 2.834651 | 2.777533 | 1.020564 |
# Store reference to message queue in module global variable, so that
# our Bottle app handler functions have easy access to it.
global _Q_ROUTE_SPEC
_Q_ROUTE_SPEC = self.q_route_spec
logging.info("Http watcher plugin: "
"Starting to watch for route... | def start(self) | Start the HTTP change monitoring thread. | 13.064863 | 11.614766 | 1.124849 |
def save_to_permacache():
update_from_permacache()
try:
with open(filename, 'wb') as fp:
pickle.dump(cache, fp, pickle.HIGHEST_PROTOCOL)
except IOError:
pass # Ignore permacache saving exceptions
def update_from_permacache():
... | def cache_results(function) | Return decorated function that caches the results. | 2.984867 | 2.977482 | 1.00248 |
# Source modified from
# http://stackoverflow.com/a/5164027/176978
diff = datetime.utcnow() - the_datetime
if diff.days > 7 or diff.days < 0:
return the_datetime.strftime('%A %B %d, %Y')
elif diff.days == 1:
return '1 day ago'
elif diff.days > 1:
return '{0} days ago... | def pretty_date(the_datetime) | Attempt to return a human-readable time delta string. | 1.750928 | 1.695696 | 1.032572 |
checker = UpdateChecker(url)
checker.bypass_cache = bypass_cache
result = checker.check(package_name, package_version, **extra_data)
if result:
print(result) | def update_check(package_name, package_version, bypass_cache=False, url=None,
**extra_data) | Convenience method that outputs to stdout if an update is available. | 3.088852 | 2.743123 | 1.126035 |
data = extra_data
data['package_name'] = package_name
data['package_version'] = package_version
data['python_version'] = sys.version.split()[0]
data['platform'] = platform.platform(True) or 'Unspecified'
try:
headers = {'connection': 'close',
... | def check(self, package_name, package_version, **extra_data) | Return a UpdateResult object if there is a newer version. | 3.40642 | 3.154485 | 1.079865 |
url = self.baseUrl
url += "newMonitor?apiKey=%s" % self.apiKey
url += "&monitorFriendlyName=%s" % monitorFriendlyName
url += "&monitorURL=%s&monitorType=1" % monitorURL
url += "&monitorAlertContacts=%s" % monitorAlertContacts
url += "&noJsonCallback=1&format=json... | def addMonitor(self, monitorFriendlyName, monitorURL) | Returns True if Monitor was added, otherwise False. | 3.604743 | 3.458012 | 1.042432 |
url = self.baseUrl
url += "getMonitors?apiKey=%s" % (self.apiKey)
url += "&noJsonCallback=1&format=json"
# responseTimes - optional (defines if the response time data of each
# monitor will be returned. Should be set to 1 for getting them. Default
# is 0)
... | def getMonitors(self, response_times=0, logs=0, uptime_ratio='') | Returns status and response payload for all known monitors. | 3.685143 | 3.680499 | 1.001262 |
url = self.baseUrl
url += "getMonitors?apiKey=%s&monitors=%s" % (self.apiKey, monitorId)
url += "&noJsonCallback=1&format=json"
success, response = self.requestApi(url)
if success:
status = response.get('monitors').get('monitor')[0].get('status')
... | def getMonitorById(self, monitorId) | Returns monitor status and alltimeuptimeratio for a MonitorId. | 3.602734 | 2.587186 | 1.39253 |
url = self.baseUrl
url += "getMonitors?apiKey=%s" % self.apiKey
url += "&noJsonCallback=1&format=json"
success, response = self.requestApi(url)
if success:
monitors = response.get('monitors').get('monitor')
for i in range(len(monitors)):
... | def getMonitorByName(self, monitorFriendlyName) | Returns monitor status and alltimeuptimeratio for a MonitorFriendlyName. | 3.341663 | 2.511374 | 1.330611 |
url = self.baseUrl
url += "editMonitor?apiKey=%s" % self.apiKey
url += "&monitorID=%s" % monitorID
if monitorStatus:
# Pause, Start Montir
url += "&monitorStatus=%s" % monitorStatus
if monitorFriendlyName:
# Update their FriendlyName
... | def editMonitor(self, monitorID, monitorStatus=None, monitorFriendlyName=None, monitorURL=None, monitorType=None,
monitorSubType=None, monitorPort=None, monitorKeywordType=None, monitorKeywordValue=None,
monitorHTTPUsername=None, monitorHTTPPassword=None, monitorAlertContacts=Non... | monitorID is the only required object. All others are optional and must be quoted.
Returns Response object from api. | 1.963511 | 1.973121 | 0.99513 |
url = self.baseUrl
url += "deleteMonitor?apiKey=%s" % self.apiKey
url += "&monitorID=%s" % monitorID
url += "&noJsonCallback=1&format=json"
success, response = self.requestApi(url)
if success:
return True
else:
return False | def deleteMonitorById(self, monitorID) | Returns True or False if monitor is deleted | 3.928729 | 3.824068 | 1.027369 |
url = self.baseUrl
url += "getAlertContacts?apiKey=%s" % self.apiKey
if alertContacts:
url += "&alertContacts=%s" % alertContacts
if offset:
url += "&offset=%s" % offset
if limit:
url += "&limit=%s" ... | def getAlertContacts(self, alertContacts=None, offset=None, limit=None) | Get Alert Contacts | 2.159233 | 2.1893 | 0.986266 |
close_file = False
if not hasattr(file_, 'read'):
file_ = open(file_, 'rb')
close_file = True
try:
header_data = file_.read(BlockStorageRAM._index_offset)
block_size, block_count, user_header_size, locked = \
struct.unpack(... | def fromfile(file_,
threadpool_size=None,
ignore_lock=False) | Instantiate BlockStorageRAM device from a file saved in block
storage format. The file_ argument can be a file object or a
string that represents a filename. If called with a file
object, it should be opened in binary mode, and the caller is
responsible for closing the file.
Thi... | 2.967901 | 2.739849 | 1.083235 |
close_file = False
if not hasattr(file_, 'write'):
file_ = open(file_, 'wb')
close_file = True
file_.write(self._f)
if close_file:
file_.close() | def tofile(self, file_) | Dump all storage data to a file. The file_ argument can be a
file object or a string that represents a filename. If called
with a file object, it should be opened in binary mode, and
the caller is responsible for closing the file.
The method should only be called after the storage devic... | 2.803462 | 2.935484 | 0.955026 |
parser = argparse.ArgumentParser()
parser.add_argument('-i', dest='path_to_notebook_json', required=True,
help='Zeppelin notebook input file (.json)')
parser.add_argument('-o', dest='output_path', default=sys.stdout,
help='Path to save rendered output fil... | def main() | Entry point.
- Execute notebook
- Save output to either file or display it in stderr
- Display errors during the run if they exist | 2.527416 | 2.483756 | 1.017578 |
@wraps(fn)
def _log_to_logger(*args, **kwargs):
actual_response = fn(*args, **kwargs)
# modify this to log exactly what you need:
logger.info('%s %s %s %s' % (bottle.request.remote_addr,
bottle.request.method,
... | def log_to_logger(fn) | Wrap a Bottle request so that a log line is emitted after it's handled. | 2.908737 | 2.485128 | 1.170457 |
accept = bottle.request.get_header("accept", default="text/plain")
bottle.response.status = 200
try:
if "text/html" in accept:
ret = CURRENT_STATE.as_html(path=path)
bottle.response.content_type = "text/html"
elif "application/json" in accept:
ret ... | def handle_request(path) | Return the current status. | 2.855127 | 2.792814 | 1.022312 |
logging.info("HTTP server: "
"Starting to listen for requests on '%s:%s'..." %
(self.conf['addr'], self.conf['port']))
self.my_server = MyWSGIRefServer(host=self.conf['addr'],
port=self.conf['port'],
... | def start(self) | Start the HTTP server thread. | 5.486199 | 5.223758 | 1.05024 |
self.my_server.stop()
self.http_thread.join()
logging.info("HTTP server: Stopped") | def stop(self) | Stop the HTTP server thread. | 7.723885 | 5.502515 | 1.403701 |
slowest_rtt = 0.0
slowest_ip = None
fastest_rtt = 9999999.9
fastest_ip = None
rtt_total = 0.0
for ip, rtt in responses.items():
rtt_total += rtt
if rtt > slowest_rtt:
slowest_rtt = rtt
slowest_ip = ip
... | def update_stats(self, responses, no_responses) | Maintain some stats about our requests. | 1.946051 | 1.946197 | 0.999925 |
# Calculate a decent overall timeout time for a ping attempt: 3/4th of
# the monitoring interval. That way, we know we're done with this ping
# attempt before the next monitoring attempt is started.
ping_timeout = self.get_monitor_interval() * 0.75
# Calculate a decent ... | def do_health_checks(self, list_of_ips) | Perform a health check on a list of IP addresses, using ICMPecho.
Return tuple with list of failed IPs and questionable IPs. | 6.565531 | 6.607013 | 0.993722 |
super(Icmpecho, self).stop()
self.monitor_thread.join()
logging.info("ICMPecho health monitor plugin: Stopped") | def stop(self) | Stop the monitoring thread of the plugin.
The super-class will send the stop signal on the monitor-IP queue,
which prompts the loop to stop. | 15.575874 | 13.20977 | 1.179118 |
return {
self.get_plugin_name() : {
"version" : self.get_version(),
"params" : {
"icmp_check_interval" : self.conf['icmp_check_interval'],
},
"stats" : self.get_stats()
}
} | def get_info(self) | Return plugin information. | 4.587821 | 3.919803 | 1.170422 |
parser.add_argument('--icmp_check_interval',
dest='icmp_check_interval',
required=False, default=2, type=float,
help="ICMPecho interval in seconds, default 2 "
"(only for 'icmpecho' heal... | def add_arguments(cls, parser, sys_arg_list=None) | Arguments for the ICMPecho health monitor plugin. | 7.478589 | 4.412687 | 1.694793 |
try:
if netmask_expected:
if "/" not in ip:
raise netaddr.core.AddrFormatError()
netaddr.IPNetwork(ip)
else:
netaddr.IPAddress(ip)
except netaddr.core.AddrFormatError:
if netmask_expected:
raise ArgsError("Not a valid C... | def ip_check(ip, netmask_expected=False) | Sanity check that the specified string is indeed an IP address or mask. | 2.274231 | 2.312115 | 0.983615 |
is_ip = True
if "/" in val:
ip_check(val, netmask_expected=True)
is_ip = False
else:
ip_check(val, netmask_expected=False)
if return_as_cidr and is_ip:
# Convert a plain IP to a CIDR
if val == "0.0.0.0":
# Special case for the default route
... | def check_valid_ip_or_cidr(val, return_as_cidr=False) | Checks that the value is a valid IP address or a valid CIDR.
Returns the specified value.
If 'return_as_cidr' is set then the return value will always be in the form
of a CIDR, even if a plain IP address was specified. | 3.012382 | 3.25578 | 0.925241 |
# The default route (0.0.0.0/0) is handled differently, since every route
# would always be contained in there. Instead, only a small CIDR of
# "0.0.0.0/0" can match against it. Other small CIDRs will always result in
# 'False' (not contained).
if small_cidr == "0.0.0.0/0":
return big_c... | def is_cidr_in_cidr(small_cidr, big_cidr) | Return True if the small CIDR is contained in the big CIDR. | 3.52693 | 3.294232 | 1.070638 |
msg = None
while True:
try:
# The list of IPs is always a full list.
msg = q.get_nowait()
q.task_done()
except Queue.Empty:
# No more messages, all done for now
return msg | def read_last_msg_from_queue(q) | Read all messages from a queue and return the last one.
This is useful in many cases where all messages are always the complete
state of things. Therefore, intermittent messages can be ignored.
Doesn't block, returns None if there is no message waiting in the queue. | 6.068556 | 6.413667 | 0.946191 |
val = default
for i, a in enumerate(args):
# Long form may use "--xyz=foo", so need to split on '=', but it
# doesn't necessarily do that, can also be "--xyz foo".
elems = a.split("=", 1)
if elems[0] in [short_form, long_form]:
# At least make sure that an actual... | def param_extract(args, short_form, long_form, default=None) | Quick extraction of a parameter from the command line argument list.
In some cases we need to parse a few arguments before the official
arg-parser starts.
Returns parameter value, or None if not present. | 4.829443 | 5.0855 | 0.94965 |
if not (2 <= k <= max_k_labeled):
raise ValueError("k must be in range [2, %d]: %s"
% (max_k_labeled, k))
return ((x == 0) and numerals[0]) or \
(base10_integer_to_basek_string(k, x // k).\
lstrip(numerals[0]) + numerals[x % k]) | def base10_integer_to_basek_string(k, x) | Convert an integer into a base k string. | 3.907541 | 3.889109 | 1.004739 |
assert 1 < k <= max_k_labeled
return sum(numeral_index[c]*(k**i)
for i, c in enumerate(reversed(x))) | def basek_string_to_base10_integer(k, x) | Convert a base k string into an integer. | 9.416077 | 9.48632 | 0.992595 |
assert k >= 2
if k == 2:
return log2floor(b+1)
v = (k - 1) * (b + 1) + 1
h = 0
while k**(h+1) < v:
h += 1
return h | def calculate_bucket_level(k, b) | Calculate the level in which a 0-based bucket
lives inside of a k-ary heap. | 4.561872 | 4.238883 | 1.076197 |
l1 = calculate_bucket_level(k, b1)
l2 = calculate_bucket_level(k, b2)
while l1 > l2:
b1 = (b1-1)//k
l1 -= 1
while l2 > l1:
b2 = (b2-1)//k
l2 -= 1
while b1 != b2:
b1 = (b1-1)//k
b2 = (b2-1)//k
l1 -= 1
return l1 | def calculate_last_common_level(k, b1, b2) | Calculate the highest level after which the
paths from the root to these buckets diverge. | 1.888815 | 1.842145 | 1.025335 |
"Write the tree in the dot language format to f."
assert (max_levels is None) or (max_levels >= 0)
def visit_node(n, levels):
lbl = "{"
if data is None:
if self.k <= max_k_labeled:
lbl = repr(n.label()).\
repla... | def write_as_dot(self, f, data=None, max_levels=None) | Write the tree in the dot language format to f. | 3.395426 | 3.283374 | 1.034127 |
"Write the heap as PDF file."
assert (max_levels is None) or (max_levels >= 0)
import os
if not filename.endswith('.pdf'):
filename = filename+'.pdf'
tmpfd, tmpname = tempfile.mkstemp(suffix='dot')
with open(tmpname, 'w') as f:
self.write_as_dot(f,... | def save_image_as_pdf(self, filename, data=None, max_levels=None) | Write the heap as PDF file. | 3.457668 | 3.168544 | 1.091248 |
denominator = sum( [pow(2.0*efficiency, -Ci) for Ci in seq] )
return log(len(seq)/denominator)/log(2.0*efficiency) | def average_cq(seq, efficiency=1.0) | Given a set of Cq values, return the Cq value that represents the
average expression level of the input.
The intent is to average the expression levels of the samples,
since the average of Cq values is not biologically meaningful.
:param iterable seq: A sequence (e.g. list, array, or Series) of Cq val... | 6.44751 | 7.986967 | 0.807254 |
if not isinstance(sample_frame, pd.core.frame.DataFrame):
raise TypeError("Expected a pandas DataFrame, received {}".format(type(sample_frame)))
for col in ['Sample', 'Target', 'Cq']:
if col not in sample_frame:
raise ValueError("Missing column {} in sample frame".format(col))
... | def validate_sample_frame(sample_frame) | Makes sure that `sample_frame` has the columns we expect.
:param DataFrame sample_frame: A sample data frame.
:return: True (or raises an exception)
:raises TypeError: if sample_frame is not a pandas DataFrame
:raises ValueError: if columns are missing or the wrong type | 3.000623 | 2.966863 | 1.011379 |
ntcs = sample_frame.loc[ sample_frame['Sample'].apply(lambda x: x in ntc_samples), ]
if ntcs.empty:
return sample_frame
g = ntcs.groupby('Target')
min_ntcs = g['Cq'].min()
# if a target has no NTC, min_ntcs.loc[sample] is NaN
# we should retain all values from targets with no NTC
... | def censor_background(sample_frame, ntc_samples=['NTC'], margin=log2(10)) | Selects rows from the sample data frame that fall `margin` or greater
cycles earlier than the NTC for that target. NTC wells are recognized by
string matching against the Sample column.
:param DataFrame sample_frame: A sample data frame.
:param iterable ntc_samples: A sequence of strings giving the sam... | 6.279366 | 6.031818 | 1.04104 |
# It might be more correct to replace asarray calls (to discard indexes)
# with proper joins.
ref_target_df = sample_frame.ix[sample_frame['Target'] == ref_target, ['Sample', 'Cq']]
ref_target_grouped = ref_target_df.groupby('Sample')
ref_target_mean_by_sample = ref_target_grouped['Cq'].aggr... | def expression_ddcq(sample_frame, ref_target, ref_sample) | Calculates expression of samples in a sample data frame relative to a
single reference gene and reference sample using the ∆∆Cq method.
For best results, the ref_sample should be defined for all targets and the
ref_target should be defined for all samples, or else the series you get
back will have lots... | 3.074263 | 2.924106 | 1.051352 |
ref_sample_df = sample_frame.ix[sample_frame['Sample'] == ref_sample, ['Target', 'Cq']]
ref_sample_cq = ref_sample_df.groupby('Target')['Cq'].aggregate(average_cq)
delta = -sample_frame['Cq'] + asarray(ref_sample_cq.ix[sample_frame['Target']])
rel = power(2, delta) / asarray(nf_n.ix[sample_frame['... | def expression_nf(sample_frame, nf_n, ref_sample) | Calculates expression of samples in a sample data frame relative to
pre-computed normalization factors.
ref_sample should be defined for all targets or the result will contain
many NaNs.
:param DataFrame sample_frame: A sample data frame.
:param Series nf_n: A Series of normalization factors index... | 5.034623 | 4.909532 | 1.025479 |
by_gene = {'Sample': sample_frame['Sample'], 'Target': sample_frame['Target']}
for target in ref_targets:
by_gene[target] = expression_ddcq(sample_frame, target, ref_sample)
return pd.DataFrame(by_gene) | def collect_expression(sample_frame, ref_targets, ref_sample) | Calculates the expression of all rows in the sample_frame relative to
each of the ref_targets. Used in rank_targets.
:param DataFrame sample_frame: A sample data frame.
:param iterable ref_targets: A sequence of targets from the Target column of
the sample frame.
:param string ref_sample: The n... | 4.441419 | 5.1331 | 0.865251 |
table = collect_expression(sample_frame, ref_targets, ref_sample)
all_samples = sample_frame['Sample'].unique()
t = table.groupby(['Sample', 'Target']).mean()
logt = log2(t)
ref_targets = set(ref_targets)
worst = []
worst_m = []
while len(ref_targets) - len(worst) > 1:
M = ... | def rank_targets(sample_frame, ref_targets, ref_sample) | Uses the geNorm algorithm to determine the most stably expressed
genes from amongst ref_targets in your sample.
See Vandesompele et al.'s 2002 Genome Biology paper for information about
the algorithm: http://dx.doi.org/10.1186/gb-2002-3-7-research0034
:param DataFrame sample_frame: A sample data frame... | 3.076695 | 2.949513 | 1.04312 |
# Returns a DataFrame, where rows represent samples and columns represent a number of reference genes.
grouped = sample_frame.groupby(['Target', 'Sample'])['Cq'].aggregate(average_cq)
samples = sample_frame['Sample'].unique()
nfs = {}
for i in xrange(1, len(ranked_targets)+1):
nfs[i] =... | def calculate_all_nfs(sample_frame, ranked_targets, ref_sample) | For a set of n ranked_genes, calculates normalization factors NF_1,
NF_2, ..., NF_n. NF_i represents the normalization factor generated by
considering the first i targets in ranked_targets.
calculate_nf (which returns only NF_n) is probably more
useful for routine analysis.
:param DataFrame sa... | 6.283154 | 5.793166 | 1.08458 |
grouped = sample_frame.groupby(['Target', 'Sample'])['Cq'].aggregate(average_cq)
samples = sample_frame['Sample'].unique()
nfs = gmean([pow(2, -grouped.ix[zip(repeat(ref_gene), samples)] + grouped.ix[ref_gene, ref_sample]) for ref_gene in ref_targets])
return pd.Series(nfs, index=samples) | def calculate_nf(sample_frame, ref_targets, ref_sample) | Calculates a normalization factor from the geometric mean of the
expression of all ref_targets, normalized to a reference sample.
:param DataFrame sample_frame: A sample data frame.
:param iterable ref_targets: A list or Series of target names.
:param string ref_sample: The name of the sample to normal... | 7.638924 | 7.285351 | 1.048532 |
v = []
if (nfs.columns != range(1, nfs.columns[-1]+1)).any():
raise ValueError("Column names invalid in nf_v_frame")
for i in nfs.columns[:-1]:
v.append(std(log2(nfs[i]/nfs[i+1]), ddof=1))
return pd.Series(v, index=nfs.columns[:-1]) | def calculate_v(nfs) | Calculates V(n+1/n) values. Useful for establishing the quality of
your normalization regime. See Vandesompele 2002 for advice on
interpretation.
:param DataFrame nfs: A matrix of all normalization factors, produced by
`calculate_all_nfs`.
:return: a Series of values [V(2/1), V(3/2), V(4/3), ...... | 5.31068 | 4.961036 | 1.070478 |
parser = argparse.ArgumentParser()
parser.add_argument('-i', dest='in_filename', required=True,
help='Zeppelin notebook input file (.json)')
parser.add_argument('-o', dest='out_filename',
help='Markdown output file (.md) (optional)')
args = parser.par... | def main() | Entry point.
- Loads in Zeppelin notebook
- Gets the version of the notebook
- Converts it into markdown format | 2.461027 | 2.339622 | 1.051891 |
# The timeout is just for the connection attempt, but between retries there
# is an exponential back off in seconds. So, too many retries and it can
# possibly block for a very long time here. Main contributor to waiting
# time here is the number of retries, rather than the timeout time.
try:
... | def get_ec2_meta_data() | Get meta data about ourselves, if we are on an EC2 instance.
In particular, this returns the VPC ID and region of this instance.
If we are not on an EC2 instance it returns an empty dict. | 7.653087 | 7.047733 | 1.085893 |
logging.debug("Connecting to AWS region '%s'" % region_name)
con = boto.vpc.connect_to_region(region_name)
if not con:
raise VpcRouteSetError("Could not establish connection to "
"region '%s'." % region_name)
return con | def connect_to_region(region_name) | Establish connection to AWS API. | 3.809363 | 3.794451 | 1.00393 |
# We create a reverse lookup from the instances private IP addresses to the
# subnets they are associated with. This is used later on in order to
# determine whether routes should be set in an RT: Is the RT's subnet
# associated with ANY of the IP addresses in the route spec? To make this
# eas... | def _make_ip_subnet_lookup(vpc_info) | Updates the vpc-info object with a lookup for IP -> subnet. | 5.851579 | 5.786331 | 1.011276 |
logging.debug("Retrieving information for VPC '%s'" % vpc_id)
d = {}
d['zones'] = con.get_all_zones()
# Find the specified VPC, or just use the first one
all_vpcs = con.get_all_vpcs()
if not all_vpcs:
raise VpcRouteSetError("Cannot find any VPCs.")
if not vpc_id:
# ... | def get_vpc_overview(con, vpc_id, region_name) | Retrieve information for the specified VPC.
If no VPC ID was specified then just pick the first VPC we find.
Returns a dict with the VPC's zones, subnets, route tables and
instances. | 3.521862 | 3.405684 | 1.034113 |
for instance in vpc_info['instances']:
for eni in instance.interfaces:
for pa in eni.private_ip_addresses:
if pa.private_ip_address == ip:
return instance, eni
raise VpcRouteSetError("Could not find instance/eni for '%s' "
"... | def find_instance_and_eni_by_ip(vpc_info, ip) | Given a specific IP address, find the EC2 instance and ENI.
We need this information for setting the route.
Returns instance and emi in a tuple. | 3.671779 | 3.644316 | 1.007536 |
ipaddr = None
for eni in instance.interfaces:
if eni.id == route.interface_id:
ipaddr = eni.private_ip_address
break
return ipaddr, eni if ipaddr else None | def get_instance_private_ip_from_route(instance, route) | Find the private IP and ENI of an instance that's pointed to in a route.
Returns (ipaddr, eni) tuple. | 3.837787 | 3.028112 | 1.267386 |
if not ip_list:
# We don't have any hosts to choose from.
return None
ip_set = set(ip_list)
failed_set = set(failed_ips)
# Consider only those questionable IPs that aren't also failed and make
# sure all of the ones in the questionable list are at least also pre... | def _choose_different_host(old_ip, ip_list, failed_ips, questionable_ips) | Randomly choose a different host from a list of hosts.
Pick from fully healthy IPs first (neither failed nor questionable).
If we don't have any of those, pick from questionable ones next.
If no suitable hosts can be found in the list (if it's empty or all hosts
are in the failed_ips list) it will ret... | 5.048268 | 4.878643 | 1.034769 |
buf = "inst: %s, eni: %s, r_ip: %-15s, o_r_ip: %-15s, msg: %s" % \
(instance_id, eni_id, router_ip, old_router_ip, msg)
CURRENT_STATE.vpc_state.setdefault('route_tables', {}). \
setdefault(route_table_id, {})[dcidr] = buf | def _rt_state_update(route_table_id, dcidr, router_ip="(none)",
instance_id="(none)", eni_id="(none)",
old_router_ip="(none)", msg="(none)") | Store a message about a VPC route in the current state. | 3.927376 | 3.891816 | 1.009137 |
instance = eni = None
try:
instance, eni = find_instance_and_eni_by_ip(vpc_info, router_ip)
logging.info("--- updating existing route in RT '%s' "
"%s -> %s (%s, %s) (old IP: %s, reason: %s)" %
(route_table_id, dcidr, router_ip,
... | def _update_route(dcidr, router_ip, old_router_ip,
vpc_info, con, route_table_id, update_reason) | Update an existing route entry in the route table. | 3.005946 | 3.007008 | 0.999647 |
try:
instance, eni = find_instance_and_eni_by_ip(vpc_info, router_ip)
# Only set the route if the RT is associated with any of the subnets
# used for the cluster.
rt_subnets = \
set(vpc_info['rt_subnet_lookup'].get(route_table_id, []))
clust... | def _add_new_route(dcidr, router_ip, vpc_info, con, route_table_id) | Add a new route to the route table. | 2.860575 | 2.863348 | 0.999031 |
# Careful! A route may be a black-hole route, which still has instance and
# ENI information for an instance that doesn't exist anymore. If a host was
# terminated and a new host got the same IP then this route won't be
# updated and will keep pointing to a non-existing node. So we find the
# i... | def _get_real_instance_if_mismatch(vpc_info, ipaddr, instance, eni) | Return the real instance for the given IP address, if that instance is
different than the passed in instance or has a different eni.
If the ipaddr belongs to the same instance and eni that was passed in then
this returns None. | 5.75858 | 5.874951 | 0.980192 |
class _CouldNotIdentifyHost(Exception):
# If we can't find both the instance as well as an eni for the route,
# we will raise this exception. In that case, we'll return None/unknown
# values, which indicate to the calling code that a new instance should
# be found.
pass
... | def _get_host_for_route(vpc_info, route, route_table, dcidr) | Given a specific route, return information about the instance to which it
points.
Returns 3-tuple: instance-id, ipaddr, eni-id
Need to take care of scenarios where the instance isn't set anymore in the
route (the instance may have disappeared). | 3.978151 | 3.775342 | 1.053719 |
for ignore_cidr in CURRENT_STATE.ignore_routes:
if is_cidr_in_cidr(cidr, ignore_cidr):
return True
return False | def _is_cidr_in_ignore_routes(cidr) | Checks the CIDR to see if it falls into any CIDRs specified via the
ignore_routes parameter.
This is used mostly to protect special routes to specific instances (for
example proxies, etc.), so that the vpc-router does not clean those up.
Only used to govern cleanup of routes, is not consulted when cre... | 4.267507 | 5.072438 | 0.841313 |
for dcidr, hosts in route_spec.items():
new_router_ip = chosen_routers.get(dcidr)
# Look at the routes we have seen in each of the route tables.
for rt_id, dcidr_list in routes_in_rts.items():
if dcidr not in dcidr_list:
if not new_router_ip:
... | def _add_missing_routes(route_spec, failed_ips, questionable_ips,
chosen_routers, vpc_info, con, routes_in_rts) | Iterate over route spec and add all the routes we haven't set yet.
This relies on being told what routes we HAVE already. This is passed
in via the routes_in_rts dict.
Furthermore, some routes may be set in some RTs, but not in others. In that
case, we may already have seen which router was chosen for... | 5.859241 | 6.151111 | 0.95255 |
if CURRENT_STATE._stop_all:
logging.debug("Routespec processing. Stop requested, abort operation")
return
if failed_ips:
logging.debug("Route spec processing. Failed IPs: %s" %
",".join(failed_ips))
else:
logging.debug("Route spec processing. No fa... | def process_route_spec_config(con, vpc_info, route_spec,
failed_ips, questionable_ips) | Look through the route spec and update routes accordingly.
Idea: Make sure we have a route for each CIDR.
If we have a route to any of the IP addresses for a given CIDR then we are
good. Otherwise, pick one (usually the first) IP and create a route to that
IP.
If a route points at a failed or que... | 6.678261 | 6.809391 | 0.980743 |
# VPC-info already contains a lookup between the EC2 instances of the VPC
# and their subnets ('ip_subnet_lookup'). This may also contain some
# non-cluster nodes, but we can use this to look up the subnet for each IP
# address of cluster nodes.
subnets = set()
for cidr_ignore, hosts in rou... | def make_cluster_node_subnet_list(vpc_info, route_spec) | Create a list of subnets, which are associated with nodes in the current
route spec (cluster).
This is needed when later on we set routes, but only want to set routes in
those route tables, which are associated with a subnet that in turn is
associated with a cluster node (to avoid having to set the rou... | 5.450525 | 5.43493 | 1.002869 |
if CURRENT_STATE._stop_all:
logging.debug("handle_spec: Stop requested, abort operation")
return
if not route_spec:
logging.debug("handle_spec: No route spec provided")
return
logging.debug("Handle route spec")
try:
con = connect_to_region(region_name... | def handle_spec(region_name, vpc_id, route_spec, failed_ips, questionable_ips) | Connect to region and update routes according to route spec. | 4.561818 | 4.415439 | 1.033152 |
"Calculates signature for local file."
kwargs = {}
if block_size:
kwargs['block_size'] = block_size
return librsync.signature(open(self.path, 'rb'), **kwargs) | def signature(self, block_size=None) | Calculates signature for local file. | 6.36924 | 5.267331 | 1.209197 |
"Applies remote delta to local file."
# Create a temp file in which to store our synced copy. We will handle
# deleting it manually, since we may move it instead.
with (tempfile.NamedTemporaryFile(prefix='.sync',
suffix=os.path.basename(self.path),
dir=os.path... | def patch(self, delta) | Applies remote delta to local file. | 4.62572 | 4.392266 | 1.053151 |
"Requests a signature for remote file via API."
kwargs = {}
if block_size:
kwargs['block_size'] = block_size
return self.api.get('path/sync/signature', self.path, **kwargs) | def signature(self, block_size=None) | Requests a signature for remote file via API. | 8.262564 | 4.713765 | 1.752859 |
"Generates delta for remote file via API using local file's signature."
return self.api.post('path/sync/delta', self.path, signature=signature) | def delta(self, signature) | Generates delta for remote file via API using local file's signature. | 22.415661 | 7.329861 | 3.058129 |
"Applies delta for local file to remote file via API."
return self.api.post('path/sync/patch', self.path, delta=delta) | def patch(self, delta) | Applies delta for local file to remote file via API. | 18.689159 | 7.361434 | 2.538793 |
return dst.patch(src.delta(dst.signature(block_size=self.block_size))) | def sync(self, src, dst) | Performs synchronization from source to destination. Performs the three
steps:
1. Calculate signature of destination.
2. Generate delta from source.
3. Apply delta to destination. | 15.582691 | 12.63539 | 1.233258 |
self.sync(LocalFile(local), RemoteFile(remote, self.api)) | def upload(self, local, remote) | Performs synchronization from a local file to a remote file. The local
path is the source and remote path is the destination. | 11.5169 | 8.178442 | 1.408202 |
self.sync(RemoteFile(remote, self.api), LocalFile(local)) | def download(self, local, remote) | Performs synchronization from a remote file to a local file. The
remote path is the source and the local path is the destination. | 12.897017 | 7.958941 | 1.620444 |
if value in validators.EMPTY_VALUES:
return None
if isinstance(value, datetime.datetime):
return value.date()
if isinstance(value, datetime.date):
return value
if isinstance(value, list):
# Input comes from a 2 SplitDateWidgets, fo... | def to_python(self, value) | Validates that the input can be converted to a date. Returns a
Python datetime.date object. | 2.524465 | 2.484294 | 1.01617 |
if value in validators.EMPTY_VALUES:
return None
if isinstance(value, datetime.datetime):
return value
if isinstance(value, datetime.date):
return datetime.datetime(value.year, value.month, value.day)
if isinstance(value, list):
# ... | def to_python(self, value) | Validates that the input can be converted to a datetime. Returns a
Python datetime.datetime object. | 2.306288 | 2.264896 | 1.018275 |
if value in validators.EMPTY_VALUES:
return None
if isinstance(value, datetime.datetime):
return value.time()
if isinstance(value, datetime.time):
return value
if isinstance(value, list):
# Input comes from a 2 SplitTimeWidgets, fo... | def to_python(self, value) | Validates that the input can be converted to a time. Returns a
Python datetime.time object. | 2.262504 | 2.205114 | 1.026026 |
if not hasattr(self, '_docs_client'):
client = DocsClient()
client.ClientLogin(self.google_user, self.google_password,
SOURCE_NAME)
self._docs_client = client
return self._docs_client | def docs_client(self) | A DocsClient singleton, used to look up spreadsheets
by name. | 4.373194 | 3.396367 | 1.287609 |
if not hasattr(self, '_sheets_service'):
service = SpreadsheetsService()
service.email = self.google_user
service.password = self.google_password
service.source = SOURCE_NAME
service.ProgrammaticLogin()
self._sheets_service = servi... | def sheets_service(self) | A SpreadsheetsService singleton, used to perform
operations on the actual spreadsheet. | 3.728718 | 3.379191 | 1.103435 |
pid_field = current_app.config['PIDSTORE_RECID_FIELD']
return FetchedPID(
provider=RecordIdProvider,
pid_type=RecordIdProvider.pid_type,
pid_value=str(data[pid_field]),
) | def recid_fetcher(record_uuid, data) | Fetch a record's identifiers.
:param record_uuid: The record UUID.
:param data: The record metadata.
:returns: A :data:`invenio_pidstore.fetchers.FetchedPID` instance. | 3.946147 | 4.172286 | 0.9458 |
# Don't call this directly.
assert self.headers is not None
cols = 0
if len(self._headers) > 0:
cols = max([int(c.cell.col) for c in self._headers])
new_col = cols + 1
if int(self._ws.col_count.text) < new_col:
self._ws.col_count.text = st... | def _add_column(self, label, field) | Add a new column to the table. It will have the header
text ``label``, but for data inserts and queries, the
``field`` name must be used. If necessary, this will expand
the size of the sheet itself to allow for the new column. | 5.030517 | 4.8642 | 1.034192 |
if self._headers is None:
query = CellQuery()
query.max_row = '1'
feed = self._service.GetCellsFeed(self._ss.id, self.id,
query=query)
self._headers = feed.entry
return [normalize_header(h.cell.text) f... | def headers(self) | Return the name of all headers currently defined for the
table. | 6.948861 | 6.518897 | 1.065956 |
data = self._convert_value(row)
self._service.InsertRow(data, self._ss.id, self.id) | def insert(self, row) | Insert a new row. The row will be added to the end of the
spreadsheet. Before inserting, the field names in the given
row will be normalized and values with empty field names
removed. | 10.877927 | 10.888924 | 0.99899 |
for entry in self._find_entries(_query=_query, **kwargs):
self._service.DeleteRow(entry) | def remove(self, _query=None, **kwargs) | Remove all rows matching the current query. If no query
is given, this will truncate the entire table. | 9.532985 | 9.479131 | 1.005681 |
def has_role_func(self, role):
if role not in roles:
msg = "Evaluating has_role('%s'), Role '%s' does not exist."
self.logger.warn(msg % (role, self.user_id))
return False
for group in roles[role]:
if s... | def generate_has_role_function(cls, roles) | Generate a `class.has_role('role_name')` method for a class.
:param class cls: The python class to be modified.
:param dict roles: The roles to use for generation.
This method is intended to be used by an inheriting class to
generate the has_role method based on the roles provided.
... | 3.824744 | 3.992158 | 0.958064 |
for access_role in roles.keys():
is_role_func = cls.generate_is_role_function(access_role)
setattr(cls, "is_" + access_role, is_role_func) | def generate_is_role_functions(cls, roles) | Generate `class.is_{role}()` methods for a class.
:param class cls: The python class to be modified.
:param dict roles: The roles to use for generation.
This method is intended to be used by an inheriting class to
generate `is_{role}()` methods based on the roles provided
durin... | 2.92238 | 3.043365 | 0.960246 |
name = re.sub('\W+', '', name, flags=re.UNICODE).lower()
# TODO handle multiple columns with the same name.
return name | def normalize_header(name, existing=[]) | Try to emulate the way in which Google does normalization
on the column names to transform them into headers. | 7.302916 | 6.210448 | 1.175908 |
allElements=[]
for element in self.getAllElements():
allElements.append(element)
if isinstance(element, BaseElement):
allElements.extend(element.getAllElementsOfHirarchy())
return allElements | def getAllElementsOfHirarchy(self) | returns ALL elements of the complete hirarchy as a flat list | 2.595032 | 2.396051 | 1.083046 |
pos=0
for element in self._subElements:
if element.get_id()==id:
return (element,pos)
pos+=1 | def getElementByID(self, id) | returns an element with the specific id and the position of that element within the svg elements array | 5.220103 | 4.305294 | 1.212485 |
foundElements=[]
for element in self.getAllElementsOfHirarchy():
if isinstance(element, type):
foundElements.append(element)
return foundElements | def getElementsByType(self, type) | retrieves all Elements that are of type type
@type type: class
@param type: type of the element | 5.885892 | 6.17803 | 0.952713 |
xml='<'+self._elementName+' '
for key,value in list(self._attributes.items()):
if value != None:
xml+=key+'="'+self.quote_attrib(str(value))+'" '
if len(self._subElements)==0: #self._textContent==None and
xml+=' />\n'
else:
xm... | def getXML(self) | Return a XML representation of the current element.
This function can be used for debugging purposes. It is also used by getXML in SVG
@return: the representation of the current element as an xml string | 3.183046 | 3.106625 | 1.024599 |
for key in list(kwargs.keys()):
#try:
f = getattr(self,'set_' + key)
f(kwargs[key]) | def setKWARGS(self, **kwargs) | Used to set all attributes given in a **kwargs parameter.
Might throw an Exception if attribute was not found.
#TODO: check if we should fix this using "setAttribute" | 4.515801 | 4.153636 | 1.087192 |
header = '''<?xml version="1.0" encoding="%s" standalone="%s"?>''' %(encoding, standalone)
return header+xml | def wrap_xml(self, xml, encoding ='ISO-8859-1', standalone='no') | Method that provides a standard svg header string for a file | 3.435937 | 3.255745 | 1.055346 |
f = codecs.open(filename, 'w', encoding)
s = self.wrap_xml(self.getXML(), encoding, standalone)
#s = s.replace("&", "&")
f.write(s)
f.close() | def save(self, filename, encoding ='ISO-8859-1', standalone='no') | Stores any element in a svg file (including header).
Calling this method only makes sense if the root element is an svg elemnt | 3.147313 | 3.586232 | 0.87761 |
s1 = (isinstance(inStr, str) and inStr or
'%s' % inStr)
s1 = s1.replace('&', '&')
s1 = s1.replace('<', '<')
s1 = s1.replace('>', '>')
if '"' in s1:
# if "'" in s1:
s1 = '%s' % s1.replace('"', """)
# else:
... | def quote_attrib(self, inStr) | Transforms characters between xml notation and python notation. | 1.870382 | 1.735476 | 1.077734 |
dt = datetime.strptime(time_str, "%Y-%m-%dT%H:%M:%SZ")
return int(time.mktime(dt.utctimetuple())) | def _convert_time(self, time_str) | Convert a string representation of the time (as returned by blockr.io api) into unix
timestamp
:param time_utc_str: string representation of the time
:return: unix timestamp | 2.613543 | 2.832651 | 0.922649 |
url = '{}/block/raw/{}'.format(self._url, block)
return self.make_request(url) | def get_block_raw(self, block) | Args:
block: block number (eg: 223212)
block hash (eg: 0000000000000000210b10d620600dc1cc2380bb58eb2408f9767eb792ed31fa)
word "last" - this will always return the latest block
word "first" - this will always return the first block
Returns:
... | 5.170115 | 6.082629 | 0.84998 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.