code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
from flask import jsonify
if attachments is None:
attachments = []
data = {
'response_type': response_type,
'text': text,
'attachments': attachments,
}
return jsonify(**data) | def response(self, text, response_type='ephemeral', attachments=None) | Return a response with json format
:param text: the text returned to the client
:param response_type: optional. When `in_channel` is assigned,
both the response message and the initial
message typed by the user will be shared
... | 2.660074 | 3.031008 | 0.87762 |
try:
with open(self.pidfile, 'r') as pidfile:
try:
pid = int(pidfile.read().strip())
except ValueError:
return None
try:
os.kill(pid, 0)
except OSError as e:
... | def pid(self) | Get the pid which represents a daemonized process.
The result should be None if the process is not running. | 2.580796 | 2.529937 | 1.020103 |
try:
with open(self.pidfile, "w+") as pidfile:
pidfile.write("{0}\n".format(pidnum))
except IOError:
LOG.exception("Failed to write pidfile {0}).".format(self.pidfile))
sys.exit(exit.PIDFILE_INACCESSIBLE) | def pid(self, pidnum) | Set the pid for a running process. | 4.022727 | 4.031705 | 0.997773 |
try:
os.remove(self.pidfile)
except IOError:
if not os.path.isfile(self.pidfile):
return None
LOG.exception("Failed to clear pidfile {0}).".format(self.pidfile))
sys.exit(exit.PIDFILE_INACCESSIBLE) | def pid(self) | Stop managing the current pid. | 5.54886 | 5.144792 | 1.078539 |
self._pool = self._pool or gevent.pool.Pool(size=self.pool_size)
return self._pool | def pool(self) | Get an gevent pool used to dispatch requests. | 3.882018 | 2.565114 | 1.51339 |
interface = _get_bytes(interface)
essid = _get_bytes(essid)
wrq = ffi.new('struct iwreq*')
with iwlib_socket() as sock:
if essid.lower() in (b'off', b'any'):
wrq.u.essid.flags = 0
essid = b''
elif essid.lower() == b'on':
buf = ffi.new('char []',... | def set_essid(interface, essid) | Set the ESSID of a given interface
Arguments:
interface - device to work on (e.g. eth1, wlan0).
essid - ESSID to set. Must be no longer than IW_ESSID_MAX_SIZE (typically 32 characters). | 2.874845 | 2.86259 | 1.004281 |
# Open file
file_row_generator = get_file_row_generator(file_path, separator)
# Initialize lists for row and column sparse matrix arguments
row = list()
col = list()
append_row = row.append
append_col = col.append
# Read all file rows
for file_row in file_row_generator:
... | def read_adjacency_matrix(file_path, separator) | Reads an edge list in csv format and returns the adjacency matrix in SciPy Sparse COOrdinate format.
Inputs: - file_path: The path where the adjacency matrix is stored.
- separator: The delimiter among values (e.g. ",", "\t", " ")
Outputs: - adjacency_matrix: The adjacency matrix in SciPy Sparse... | 2.671042 | 2.70558 | 0.987234 |
# Open file
file_row_generator = get_file_row_generator(file_path, separator)
# Initialize lists for row and column sparse matrix arguments
row = list()
col = list()
append_row = row.append
append_col = col.append
# Populate the arrays
for file_row in file_row_generator:
... | def read_node_label_matrix(file_path, separator, number_of_nodes) | Reads node-label pairs in csv format and returns a list of tuples and a node-label matrix.
Inputs: - file_path: The path where the node-label matrix is stored.
- separator: The delimiter among values (e.g. ",", "\t", " ")
- number_of_nodes: The number of nodes of the full graph. It is po... | 2.776087 | 2.511229 | 1.105469 |
'''
Ensure that the Garuda directory and files
'''
if not os.path.exists(GARUDA_DIR):
os.makedirs(GARUDA_DIR)
Path(f'{GARUDA_DIR}/__init__.py').touch() | def ensure_data() | Ensure that the Garuda directory and files | 5.018067 | 2.951911 | 1.699938 |
'''
Construct protobuf compiler arguments
'''
proto_include = resource_filename('grpc_tools', '_proto')
return [
protoc.__file__, '-I', GARUDA_DIR, f'--python_out={GARUDA_DIR}',
f'--grpc_python_out={GARUDA_DIR}', GARUDA_PROTO_PATH,
f'-I{proto_include}'] | def protoc_arguments() | Construct protobuf compiler arguments | 5.478564 | 4.855814 | 1.128248 |
'''
Snippet to fix the gRPC import path
'''
with open(GARUDA_GRPC_PATH, 'r') as f:
filedata = f.read()
filedata = filedata.replace(
'import garuda_pb2 as garuda__pb2',
f'import {GARUDA_DIR}.garuda_pb2 as garuda__pb2')
with open(GARUDA_GRPC_PATH, 'w') as f:
f.write... | def fix_grpc_import() | Snippet to fix the gRPC import path | 3.165003 | 2.795378 | 1.132227 |
row = "--" + score_name + "--"
fp.write(row)
for vector in scores:
row = list(vector)
row = [str(score) for score in row]
row = "\n" + "\t".join(row)
fp.write(row) | def write_average_score_row(fp, score_name, scores) | Simple utility function that writes an average score row in a file designated by a file pointer.
Inputs: - fp: A file pointer.
- score_name: What it says on the tin.
- scores: An array of average score values corresponding to each of the training set percentages. | 3.33756 | 3.77714 | 0.883621 |
@functools.wraps(f)
def wrapper(self, request, *args, **kwargs):
try:
return f(self, request, *args, **kwargs)
except exceptions.CertificateExpired:
self.message_user(
request,
_('The AFIP Taxpayer certificate has expired.'),
... | def catch_errors(f) | Catches specific errors in admin actions and shows a friendly error. | 2.259774 | 2.12757 | 1.062139 |
number_of_documents = attribute_matrix.shape[0]
max_term_frequencies = np.ones(number_of_documents, dtype=np.float64)
idf_array = np.ones(attribute_matrix.shape[1], dtype=np.float64)
# Calculate inverse document frequency
attribute_matrix = attribute_matrix.tocsc()
for j in range(attribut... | def augmented_tf_idf(attribute_matrix) | Performs augmented TF-IDF normalization on a bag-of-words vector representation of data.
Augmented TF-IDF introduced in: Manning, C. D., Raghavan, P., & Schütze, H. (2008).
Introduction to information retrieval (Vol. 1, p. 6).
Cambridge: Cambr... | 2.081375 | 2.121395 | 0.981135 |
with open(file_path, encoding=encoding) as file_object:
for line in file_object:
words = line.strip().split(separator)
yield words | def get_file_row_generator(file_path, separator, encoding=None) | Reads an separated value file row by row.
Inputs: - file_path: The path of the separated value format file.
- separator: The delimiter among values (e.g. ",", "\t", " ")
- encoding: The encoding used in the stored text.
Yields: - words: A list of strings corresponding to each of the fi... | 2.403155 | 2.576004 | 0.9329 |
pkl_file = open(file_path, 'wb')
pickle.dump(data, pkl_file)
pkl_file.close() | def store_pickle(file_path, data) | Pickle some data to a given path.
Inputs: - file_path: Target file path.
- data: The python object to be serialized via pickle. | 1.881791 | 2.120705 | 0.887342 |
pkl_file = open(file_path, 'rb')
data = pickle.load(pkl_file)
pkl_file.close()
return data | def load_pickle(file_path) | Unpickle some data from a given path.
Input: - file_path: Target file path.
Output: - data: The python object that was serialized and stored in disk. | 1.842781 | 2.290269 | 0.804613 |
pkt = Packet.makeWritePacket(curr_id, xl320.XL320_ID, [new_id])
return pkt | def makeServoIDPacket(curr_id, new_id) | Given the current ID, returns a packet to set the servo to a new ID | 6.467144 | 6.559388 | 0.985937 |
# Normalize each row of term frequencies to 1
features = features.tocsr()
features = normalize(features, norm="l2")
# for i in range(features.shape[0]):
# term_frequency = features.getrow(i).data
# if term_frequency.size > 0:
# features.data[features.indptr[i]: features.... | def normalize_rows(features) | This performs row normalization to 1 of community embedding features.
Input: - X in R^(nxC_n): The community indicator matrix.
Output: - X_norm in R^(nxC_n): The row normalized community indicator matrix. | 2.475379 | 2.70186 | 0.916176 |
# Calculate inverse document frequency.
features = features.tocsc()
for j in range(features.shape[1]):
document_frequency = features.getcol(j).data.size
if document_frequency > 1:
features.data[features.indptr[j]: features.indptr[j + 1]] =\
features.data[feat... | def normalize_columns(features) | This performs column normalization of community embedding features.
Input: - X in R^(nxC_n): The community indicator matrix.
Output: - X_norm in R^(nxC_n): The tf-idf + row normalized community indicator matrix. | 3.040191 | 3.073772 | 0.989075 |
# Calculate the A and B quantities to infinity
A_inf = rho*r[push_node]
B_inf = (1-rho)*r[push_node]
# Update approximate Pagerank and residual vectors
s[push_node] += A_inf
r[push_node] = 0.0
# Update residual vector at push node's adjacent nodes
r[a_i] += B_inf * w_i | def pagerank_limit_push(s, r, w_i, a_i, push_node, rho) | Performs a random step without a self-loop. | 5.595778 | 5.933829 | 0.94303 |
# Calculate the A, B and C quantities
A = rho*r[push_node]
B = (1-rho)*(1 - lazy)*r[push_node]
C = (1-rho)*lazy*(r[push_node])
# Update approximate Pagerank and residual vectors
s[push_node] += A
r[push_node] = C
# Update residual vector at push node's adjacent nodes
r[a_i] +=... | def pagerank_lazy_push(s, r, w_i, a_i, push_node, rho, lazy) | Performs a random step with a self-loop.
Introduced in: Andersen, R., Chung, F., & Lang, K. (2006, October).
Local graph partitioning using pagerank vectors.
In Foundations of Computer Science, 2006. FOCS'06. 47th Annual IEEE Symposium on (pp. 475-486). IEEE. | 5.113768 | 5.614247 | 0.910856 |
# Calculate the commute quantity
commute = (1-rho)*r[push_node]
# Update approximate regularized commute and residual vectors
r[push_node] = 0.0
# Update residual vector at push node's adjacent nodes
commute_probabilities = commute * w_i
s[a_i] += commute_probabilities
r[a_i] += c... | def cumulative_pagerank_difference_limit_push(s, r, w_i, a_i, push_node, rho) | Performs a random step without a self-loop.
Inputs: - s: A NumPy array that contains the approximate absorbing random walk cumulative probabilities.
- r: A NumPy array that contains the residual probability distribution.
- w_i: A NumPy array of probability transition weights from the see... | 7.810774 | 7.332592 | 1.065213 |
# Remember the policy that's active before including the module, if any.
orig_policy = config.registry.queryUtility(IAuthenticationPolicy)
# Include the module, so we get any default views etc.
config.include(module)
# That might have registered and commited a new policy object.
policy = co... | def policy_factory_from_module(config, module) | Create a policy factory that works by config.include()'ing a module.
This function does some trickery with the Pyramid config system. Loosely,
it does config.include(module), and then sucks out information about the
authn policy that was registered. It's complicated by pyramid's delayed-
commit system... | 5.415569 | 4.866449 | 1.112838 |
policy_definitions = {}
for name in settings:
if not name.startswith("multiauth.policy."):
continue
value = settings[name]
name = name[len("multiauth.policy."):]
policy_name, setting_name = name.split(".", 1)
if policy_name not in policy_definitions:
... | def get_policy_definitions(settings) | Find all multiauth policy definitions from the settings dict.
This function processes the paster deployment settings looking for items
that start with "multiauth.policy.<policyname>.". It pulls them all out
into a dict indexed by the policy name. | 2.221055 | 1.786019 | 1.243579 |
if filename in ('stdin', '-', None):
instances = [i for i in gc.get_objects() if isinstance(i, pycodestyle.Checker) or isinstance(i, pep8.Checker)]
if len(instances) != 1:
raise ValueError('Expected only 1 instance of pycodestyle.Checker, got {0} instead.'.format(len(instances)))
... | def load_file(filename) | Read file to memory.
For stdin sourced files, this function does something super duper incredibly hacky and shameful. So so shameful. I'm
obtaining the original source code of the target module from the only instance of pycodestyle.Checker through the
Python garbage collector. Flake8's API doesn't give me ... | 3.734205 | 3.119884 | 1.196905 |
if code in Main.options['ignore']:
return True
if any(c in code for c in Main.options['ignore']):
return True
return False | def ignore(code) | Should this code be ignored.
:param str code: Error code (e.g. D201).
:return: True if code should be ignored, False otherwise.
:rtype: bool | 5.031788 | 6.630223 | 0.758917 |
parser.add_option('--show-pydocstyle', action='store_true', help='show explanation of each PEP 257 error')
parser.config_options.append('show-pydocstyle') | def add_options(cls, parser) | Add options to flake8.
:param parser: optparse.OptionParser from pycodestyle. | 7.691546 | 7.11744 | 1.080662 |
# Handle flake8 options.
cls.options['explain'] = bool(options.show_pydocstyle)
cls.options['ignore'] = options.ignore
# Handle pydocstyle options.
config = pydocstyle.RawConfigParser()
for file_name in pydocstyle.ConfigurationParser.PROJECT_CONFIG_FILES:
... | def parse_options(cls, options) | Read parsed options from flake8.
:param options: Options to add to flake8's command line options. | 3.04793 | 2.965965 | 1.027635 |
pydocstyle.Error.explain = self.options['explain']
filename, source = load_file(self.filename)
for error in pydocstyle.PEP257Checker().check_source(source, filename):
if not hasattr(error, 'code') or ignore(error.code):
continue
lineno = error.lin... | def run(self) | Run analysis on a single file. | 6.275024 | 6.036502 | 1.039513 |
numstring = '{:011d}{:02d}{:04d}{}{}'.format(
self._receipt.point_of_sales.owner.cuit, # 11 digits
int(self._receipt.receipt_type.code), # 2 digits
self._receipt.point_of_sales.number, # point of sales
self._receipt.validation.cae, # 14 digits
... | def numbers(self) | Returns the barcode's number without the verification digit.
:return: list(int) | 5.142937 | 4.973772 | 1.034011 |
a = sum(numbers[::2])
b = a * 3
c = sum(numbers[1::2])
d = b + c
e = d % 10
if e == 0:
return e
return 10 - e | def verification_digit(numbers) | Returns the verification digit for a given numbre.
The verification digit is calculated as follows:
* A = sum of all even-positioned numbers
* B = A * 3
* C = sum of all odd-positioned numbers
* D = B + C
* The results is the smallset number N, such that (D + N) % 10 ==... | 2.778849 | 2.139714 | 1.298701 |
return '{}{}'.format(
''.join(str(n) for n in self.numbers),
ReceiptBarcodeGenerator.verification_digit(self.numbers),
) | def full_number(self) | Returns the full number including the verification digit.
:return: str | 10.586714 | 8.575492 | 1.234531 |
# Open file
file_row_generator = get_file_row_generator(file_path, separator)
file_row = next(file_row_generator)
number_of_rows = file_row[1]
number_of_columns = file_row[3]
directed = file_row[7]
if directed == "True":
directed = True
elif directed == "False":
dir... | def read_adjacency_matrix(file_path, separator, numbering="matlab") | Reads an edge list in csv format and returns the adjacency matrix in SciPy Sparse COOrdinate format.
Inputs: - file_path: The path where the adjacency matrix is stored.
- separator: The delimiter among values (e.g. ",", "\t", " ")
- numbering: Array numbering style: * "matlab"
... | 2.047075 | 2.006212 | 1.020368 |
# Open file
file_row_generator = get_file_row_generator(file_path, separator)
file_row = next(file_row_generator)
number_of_rows = file_row[1]
number_of_categories = int(file_row[3])
# Initialize lists for row and column sparse matrix arguments
row = list()
col = list()
append... | def read_node_label_matrix(file_path, separator, numbering="matlab") | Reads node-label pairs in csv format and returns a list of tuples and a node-label matrix.
Inputs: - file_path: The path where the node-label matrix is stored.
- separator: The delimiter among values (e.g. ",", "\t", " ")
- number_of_nodes: The number of nodes of the full graph. It is po... | 2.374907 | 2.162979 | 1.09798 |
user_label_matrix = spsp.coo_matrix(user_label_matrix)
shape = user_label_matrix.shape
nnz = user_label_matrix.getnnz()
row = user_label_matrix.row
col = user_label_matrix.col
data = user_label_matrix.data
name_to_topic_set = defaultdict(set)
for edge in range(row.size):
... | def write_screen_name_to_topics(filepath, user_label_matrix, node_to_id, id_to_name, label_to_lemma, lemma_to_keyword, separator=",") | Writes a user name and associated topic names per row. | 2.256714 | 2.217846 | 1.017525 |
d = {
'id': pkt[4],
# 'instruction': xl320.InstrToStr[pkt[7]],
# 'length': (pkt[6] << 8) + pkt[5],
# 'params': pkt[8:-2],
'Model Number': (pkt[10] << 8) + pkt[9],
'Firmware Ver': pkt[11],
'Error': ErrorStatusMsg[pkt[8]],
# 'crc': pkt[-2:]
}
return d | def packetToDict(pkt) | Given a packet, this turns it into a dictionary ... is this useful?
in: packet, array of numbers
out: dictionary (key, value) | 4.96178 | 4.709842 | 1.053492 |
if port == 'dummy':
s = ServoSerial(port, rate, fake=True)
else:
s = ServoSerial(port, rate)
if ID < 0:
ID = xl320.XL320_BROADCAST_ADDR
try:
s.open()
except SerialException as e:
# print('Error opening serial port:')
print('-'*40)
print(sys.argv[0], ':')
print(e)
exit(1)
pkt = makePingPacke... | def sweep(port, rate, ID, retry=3) | Sends a ping packet to ID's from 0 to maximum and prints out any returned
messages.
Actually send a broadcast and will retry (resend) the ping 3 times ... | 4.64673 | 4.71502 | 0.985517 |
# Calculate a weighted neighborhood degree average.
# neighborhood_degree = rho*seed_degree + (1-rho)*neighbor_degrees.mean()
neighborhood_degree = neighbor_degrees.mean()
# Calculate the seed neighborhood normalized effective epsilon.
epsilon_effective = (epsilon*np.log(1 + seed_degree))/np.l... | def calculate_epsilon_effective(rho, epsilon, seed_degree, neighbor_degrees, mean_degree) | Semi-automatic effective epsilon threshold calculation. | 3.688024 | 3.641779 | 1.012698 |
number_of_labeled_nodes = labelled_node_indices.size
training_set_size = int(np.ceil(percentage*number_of_labeled_nodes/100))
####################################################################################################################
# Read or generate folds
##########################... | def get_folds_generator(node_label_matrix,
labelled_node_indices,
number_of_categories,
dataset_memory_folder,
percentage,
number_of_folds=10) | Read or form and store the seed nodes for training and testing.
Inputs: - node_label_matrix: The node-label ground truth in a SciPy sparse matrix format.
- labelled_node_indices: A NumPy array containing the labelled node indices.
- number_of_categories: The number of categories/classes in ... | 1.903651 | 1.927508 | 0.987623 |
number_of_labeled_nodes = labelled_node_indices.size
training_set_size = int(np.ceil(percentage*number_of_labeled_nodes/100))
####################################################################################################################
# Generate folds
##################################... | def generate_folds(node_label_matrix, labelled_node_indices, number_of_categories, percentage, number_of_folds=10) | Form the seed nodes for training and testing.
Inputs: - node_label_matrix: The node-label ground truth in a SciPy sparse matrix format.
- labelled_node_indices: A NumPy array containing the labelled node indices.
- number_of_categories: The number of categories/classes in the learning.
... | 2.260191 | 2.272308 | 0.994667 |
number_of_labelled_nodes = node_label_matrix.shape[0]
testing_set_size = number_of_labelled_nodes - training_set_size
training_set_proportion = training_set_size/number_of_labelled_nodes
testing_set_proportion = testing_set_size/number_of_labelled_nodes
# Calculate the desired number of exampl... | def iterative_stratification(node_label_matrix, training_set_size, number_of_categories, random_seed=0) | Iterative data fold stratification/balancing for two folds.
Based on: Sechidis, K., Tsoumakas, G., & Vlahavas, I. (2011).
On the stratification of multi-label data.
In Machine Learning and Knowledge Discovery in Databases (pp. 145-158).
Springer Berlin Heidelberg.
Inp... | 2.210795 | 2.215205 | 0.998009 |
number_of_test_nodes = y_pred.shape[0]
# We calculate the number of true labels for each node.
true_number_of_labels = np.squeeze(y_test.sum(axis=1))
# We sort the prediction array for each node.
index = np.argsort(y_pred, axis=1)
row = np.empty(y_test.getnnz(), dtype=np.int64)
col =... | def form_node_label_prediction_matrix(y_pred, y_test) | Given the discriminator distances, this function forms the node-label prediction matrix.
It is assumed that the number of true labels is known.
Inputs: - y_pred: A NumPy array that contains the distance from the discriminator for each label for each user.
- y_test: The node-label ground truth fo... | 2.39548 | 2.254279 | 1.062637 |
y_pred = y_pred.toarray()
y_test = y_test.toarray()
macro_precision, macro_recall, macro_F1, macro_support = precision_recall_fscore_support(y_test,
y_pred,
... | def calculate_measures(y_pred, y_test) | Calculates the F-scores and F-score averages given a classification result and a ground truth.
Inputs: - y_pred: The node-label prediction for the test set in a SciPy sparse CSR matrix format.
- y_test: The node-label ground truth for the test set in a SciPy sparse CSR matrix format.
Outputs: - ... | 1.772696 | 1.823721 | 0.972022 |
pp = list(map(ord, buff))
if 0 == len(pp) == 1:
pp = []
return pp | def decode(buff) | Transforms the raw buffer data read in into a list of bytes | 6.417875 | 6.168816 | 1.040374 |
# time.sleep(0.001)
# print('waiting:', self.serial.in_waiting)
# else:
# print('waiting:', self.serial.in_waiting)
data = self.serial.read(how_much)
# print('read() data', data, 'len(data)', len(data))
if data:
data = self.decode(data)
# print('decode', data)
ret = Packet.findPkt(data)
# ... | def read(self, how_much=128): # FIXME: 128 might be too much ... what is largest?
# ret = self.readPkts(how_much)
# return ret
ret = []
self.setRTS(self.DD_READ)
# this in_waiting is wrong ... i can read more than is there
# if self.serial.in_waiting < 12 | This toggles the RTS pin and reads in data. It also converts the buffer
back into a list of bytes and searches through the list to find valid
packets of info. If there is more than one packet, this returns an
array of valid packets. | 2.650488 | 2.590735 | 1.023064 |
b = self.serial.read(1)
if not b:
return None
b = ord(b)
print('b', b)
if b == header[ptr]:
ptr += 1
ret.append(b)
if ptr == 3: # found header
print('found header')
d = self.serial.read(1) # ID
ret.append(ord(d))
l, h = self.serial.read(2) # length
l = ord(l)
... | def read2(self, how_much=128): # FIXME: 128 might be too much ... what is largest?
ret = []
self.setRTS(self.DD_READ)
header = [0xFF, 0xFD, 0x00]
ptr = 0
while True | This toggles the RTS pin and reads in data. It also converts the buffer
back into a list of bytes and searches through the list to find valid
packets of info. If there is more than one packet, this returns an
array of valid packets. | 2.37794 | 2.405239 | 0.98865 |
self.setRTS(self.DD_WRITE)
self.flushInput()
# prep data array for transmition
pkt = bytearray(pkt)
pkt = bytes(pkt)
num = self.serial.write(pkt)
# self.serial.flush()
# print('wrote {} of len(pkt) = {}'.format(num, len(pkt)))
return num | def write(self, pkt) | This is a simple serial write command. It toggles the RTS pin and formats
all of the data into bytes before it writes. | 6.062834 | 5.213465 | 1.162918 |
for cnt in range(retry):
self.serial.flushInput()
self.write(pkt) # send packet to servo
ans = self.read() # get return status packet
if ans:
# check for error and resend
return ans
else:
# print('>> retry {} <<'.format(cnt))
time.sleep(sleep_time)
return None | def sendPkt(self, pkt, retry=5, sleep_time=0.01) | Sends a packet and waits for a return. If no return is given, then it
resends the packet. If an error occurs, it also resends the packet.
in:
pkt - command packet to send to servo
cnt - how many retries should this do? default = 5
out:
array of packets | 5.074014 | 4.857857 | 1.044496 |
matrix = spsp.coo_matrix(matrix)
shape = matrix.shape
nnz = matrix.getnnz()
if numbering == "matlab":
row = matrix.row + 1
col = matrix.col + 1
data = matrix.data
elif numbering == "c":
row = matrix.row
col = matrix.col
data = matrix.data
el... | def scipy_sparse_to_csv(filepath, matrix, separator=",", directed=False, numbering="matlab") | Writes sparse matrix in separated value format. | 2.105823 | 2.091777 | 1.006715 |
# Open file
file_row_generator = get_file_row_generator(file_path, separator)
# Initialize lists for row and column sparse matrix arguments.
row = list()
col = list()
data = list()
append_row = row.append
append_col = col.append
append_data = data.append
# Initialize node ... | def read_adjacency_matrix(file_path, separator, undirected) | Reads an edge list in csv format and returns the adjacency matrix in SciPy Sparse COOrdinate format.
Inputs: - file_path: The path where the adjacency matrix is stored.
- separator: The delimiter among values (e.g. ",", "\t", " ")
- undirected: If True, create the reciprocal edge for eac... | 1.959812 | 1.890421 | 1.036707 |
build.packages.install("wheel")
build.packages.install("twine")
build.executables.run([
"python", "setup.py",
"sdist", "bdist_wheel", "--universal", "--release"
])
build.executables.run([
"twine", "upload", "dist/*"
]) | def publish(build) | publish the package itself | 3.022441 | 2.935934 | 1.029465 |
# Initialize approximate PageRank and residual distributions
# s = np.zeros(number_of_nodes, dtype=np.float64)
# r = np.zeros(number_of_nodes, dtype=np.float64)
r[seed_node] = 1.0
# Initialize queue of nodes to be pushed
pushable = deque()
pushable.append(seed_node)
# Do one push ... | def fast_approximate_personalized_pagerank(s,
r,
w_i,
a_i,
out_degree,
in_degree,
... | Calculates the approximate personalized PageRank starting from a seed node without self-loops. | 2.451018 | 2.498124 | 0.981143 |
# Initialize approximate PageRank and residual distributions
# s = np.zeros(number_of_nodes, dtype=np.float64)
# r = np.zeros(number_of_nodes, dtype=np.float64)
r[seed_node] = 1.0
# Initialize queue of nodes to be pushed
pushable = deque()
pushable.append(seed_node)
# Do one push ... | def lazy_approximate_personalized_pagerank(s,
r,
w_i,
a_i,
out_degree,
in_degree,
... | Calculates the approximate personalized PageRank starting from a seed node with self-loops.
Introduced in: Andersen, R., Chung, F., & Lang, K. (2006, October).
Local graph partitioning using pagerank vectors.
In Foundations of Computer Science, 2006. FOCS'06. 47th Annual IEEE ... | 1.955032 | 2.004767 | 0.975191 |
# Read the data array
file_row_gen = get_file_row_generator(array_paths[0], "\t")
data = list()
append_data = data.append
for file_row in file_row_gen:
append_data(float(file_row[0]))
# Read the row array
file_row_gen = get_file_row_generator(array_paths[1], "\t")
row = lis... | def read_matlab_features(array_paths, number_of_nodes, dimensionality) | Returns a sparse feature matrix as calculated by a Matlab routine. | 1.997134 | 1.982059 | 1.007605 |
indices = list()
extend = indices.extend
for node in c_j:
extend(reverse_index_rows[node])
indices = np.array(indices)
indices = np.setdiff1d(indices, unavailable_communities[:unavailable_communities_counter+1])
return indices | def community_neighbors(c_j, reverse_index_rows, unavailable_communities, unavailable_communities_counter) | Finds communities with shared nodes to a seed community. Called by mroc.
Inputs: - c_j: The seed community for which we want to find which communities overlap.
- reverse_index_rows: A node to community indicator matrix.
- unavailable_communities: A set of communities that have already ei... | 3.74167 | 3.801398 | 0.984288 |
nom = np.intersect1d(c_1, c_2).size
denom = np.union1d(c_1, c_2).size
return nom/denom | def jaccard(c_1, c_2) | Calculates the Jaccard similarity between two sets of nodes. Called by mroc.
Inputs: - c_1: Community (set of nodes) 1.
- c_2: Community (set of nodes) 2.
Outputs: - jaccard_similarity: The Jaccard similarity of these two communities. | 2.362372 | 3.45298 | 0.684154 |
# Convert to networkx undirected graph.
adjacency_matrix = nx.from_scipy_sparse_matrix(adjacency_matrix, create_using=nx.Graph())
# Call LOUVAIN algorithm to calculate a hierarchy of communities.
tree = community.generate_dendogram(adjacency_matrix, part_init=None)
# Embed communities
row... | def louvain(adjacency_matrix) | Performs community embedding using the LOUVAIN method.
Introduced in: Blondel, V. D., Guillaume, J. L., Lambiotte, R., & Lefebvre, E. (2008).
Fast unfolding of communities in large networks.
Journal of Statistical Mechanics: Theory and Experiment, 2008(10), P10008.
Inputs... | 2.959169 | 3.017738 | 0.980592 |
# Calculate sparse graph Laplacian.
laplacian = get_normalized_laplacian(adjacency_matrix)
# Calculate bottom k+1 eigenvalues and eigenvectors of normalized Laplacian.
try:
eigenvalues, eigenvectors = spla.eigsh(laplacian,
k=k,
... | def laplacian_eigenmaps(adjacency_matrix, k) | Performs spectral graph embedding using the graph symmetric normalized Laplacian matrix.
Introduced in: Belkin, M., & Niyogi, P. (2003).
Laplacian eigenmaps for dimensionality reduction and data representation.
Neural computation, 15(6), 1373-1396.
Inputs: - A in R^(nx... | 2.880238 | 3.029201 | 0.950824 |
number_of_nodes = adjacency_matrix.shape[0]
max_eigenvalue = spla.eigsh(adjacency_matrix,
k=1,
which='LM',
return_eigenvectors=False)
# Calculate Replicator matrix
eye_matrix = sparse.eye(number_of_nod... | def replicator_eigenmaps(adjacency_matrix, k) | Performs spectral graph embedding on the centrality reweighted adjacency matrix
Inputs: - A in R^(nxn): Adjacency matrix of an undirected network represented as a scipy.sparse.coo_matrix
- k: The number of social dimensions/eigenvectors to extract
- max_iter: The maximum ... | 2.680537 | 2.885629 | 0.928927 |
number_of_nodes = adjacency_matrix.shape[0]
# X = A + I
adjacency_matrix = adjacency_matrix.tocsr()
adjacency_matrix = adjacency_matrix.transpose()
features = sparse.csr_matrix(sparse.eye(number_of_nodes, number_of_nodes)) + adjacency_matrix.tocsr()
features = features.tocsr()
features... | def base_communities(adjacency_matrix) | Forms the community indicator normalized feature matrix for any graph.
Inputs: - A in R^(nxn): Adjacency matrix of an undirected network represented as a SciPy Sparse COOrdinate matrix.
Outputs: - X in R^(nxC_n): The latent space embedding represented as a SciPy Sparse COOrdinate matrix. | 2.73526 | 2.894857 | 0.944869 |
# noqa: E501
assert isinstance(data, bytes)
assert isinstance(cert, str)
try:
pkey = crypto.load_privatekey(crypto.FILETYPE_PEM, key)
signcert = crypto.load_certificate(crypto.FILETYPE_PEM, cert)
except crypto.Error as e:
raise exceptions.CorruptCertificate from e
bi... | def create_embeded_pkcs7_signature(data, cert, key) | Creates an embeded ("nodetached") pkcs7 signature.
This is equivalent to the output of::
openssl smime -sign -signer cert -inkey key -outform DER -nodetach < data
:type data: bytes
:type cert: str
:type key: str | 2.619853 | 2.658416 | 0.985494 |
pkey = crypto.PKey()
pkey.generate_key(crypto.TYPE_RSA, 2048)
file_.write(crypto.dump_privatekey(crypto.FILETYPE_PEM, pkey))
file_.flush() | def create_key(file_) | Create a key and save it into ``file_``.
Note that ``file`` must be opened in binary mode. | 2.054263 | 2.218784 | 0.925851 |
key = crypto.load_privatekey(crypto.FILETYPE_PEM, key_file.read())
req = crypto.X509Req()
subj = req.get_subject()
subj.O = organization_name # noqa: E741 (we can't do anything about this)
subj.CN = common_name
subj.serialNumber = serial_number
req.set_pubkey(key)
req.sign(key, ... | def create_csr(key_file, organization_name, common_name, serial_number, file_) | Create a CSR for a key, and save it into ``file``. | 2.076215 | 2.051342 | 1.012125 |
if classifier_type == "LinearSVC":
if X_train.shape[0] > X_train.shape[1]:
dual = False
else:
dual = True
model = OneVsRestClassifier(LinearSVC(C=svm_hardness, random_state=0, dual=dual,
fit_intercept=fit_intercept),... | def model_fit(X_train, y_train, svm_hardness, fit_intercept, number_of_threads, classifier_type="LinearSVC") | Fits a Linear Support Vector Classifier to the labelled graph-based features using the LIBLINEAR library.
One-vs-All: http://scikit-learn.org/stable/modules/generated/sklearn.multiclass.OneVsRestClassifier.html
LinearSVC: http://scikit-learn.org/stable/modules/generated/sklearn.svm.LinearSVC.html
Inputs:... | 1.644698 | 1.609264 | 1.022018 |
if regressor_type == "LinearSVR":
if X_train.shape[0] > X_train.shape[1]:
dual = False
else:
dual = True
model = LinearSVR(C=svm_hardness, random_state=0, dual=dual,
fit_intercept=fit_intercept)
y_train_meta = y_train.sum(axis=1... | def meta_model_fit(X_train, y_train, svm_hardness, fit_intercept, number_of_threads, regressor_type="LinearSVR") | Trains meta-labeler for predicting number of labels for each user.
Based on: Tang, L., Rajan, S., & Narayanan, V. K. (2009, April).
Large scale multi-label classification via metalabeler.
In Proceedings of the 18th international conference on World wide web (pp. 211-220). ACM. | 2.57854 | 2.637581 | 0.977616 |
if classifier_type == "LinearSVC":
decision_weights = model.decision_function(X_test)
elif classifier_type == "LogisticRegression":
decision_weights = model.predict_proba(X_test)
elif classifier_type == "RandomForest":
# if issparse(X_test):
# decision_weights = np.h... | def weigh_users(X_test, model, classifier_type="LinearSVC") | Uses a trained model and the unlabelled features to produce a user-to-label distance matrix.
Inputs: - feature_matrix: The graph based-features in either NumPy or SciPy sparse array format.
- model: A trained scikit-learn One-vs-All multi-label scheme of linear SVC models.
- classifier_t... | 1.791307 | 1.711505 | 1.046627 |
key = (service_name.lower(), sandbox,)
try:
if key not in cached_clients:
cached_clients[key] = Client(wsdls[key], transport=transport)
return cached_clients[key]
except KeyError:
raise ValueError('Unknown service name, {}'.format(service_name)) | def get_client(service_name, sandbox=False) | Returns a client for a given service.
The `sandbox` argument should only be necessary if a the client will be
used to make a request. If it will only be used to serialize objects, it is
irrelevant. Avoid the overhead of determining the sandbox mode in the
calling context if only serialization operatio... | 4.571388 | 4.926957 | 0.927832 |
subtype = Any
if seq.__args__ and seq.__args__[0] is not Any:
subtype = seq.__args__[0]
return _array_type(extractor.extract(subtype)) | def _extract_seq(extractor, seq) | Convert a sequence to primitive equivalents. | 6.895595 | 5.27679 | 1.306778 |
# PEP_560 deprecates issubclass for
# List types, for the time being
# we'll support a specific escape hatch.
if PEP_560: # pragma: no cover
return isinstance(typ, _GenericAlias) and typ.__origin__ is list
else: # pragma: no cover
return issubclass(typ, Sequence) | def _is_sequence(typ) | returns True if the type in question
is a Sequence[] object from the typing module. | 8.08109 | 6.884161 | 1.173867 |
schema = {
"title": typ.__name__,
"type": "object",
"properties": {},
"required": []
}
for attribute in attr.fields(typ):
details = cls._extract_attribute(extractor, attribute)
if details.is_required:
... | def extract(cls, extractor, typ) | take an attrs based class, and convert it
to jsonschema. | 2.596377 | 2.405202 | 1.079484 |
path = os.path.realpath(os.path.join(os.path.dirname(__file__), 'README.rst'))
handle = None
url_prefix = 'https://raw.githubusercontent.com/Robpol86/{name}/v{version}/'.format(name=NAME, version=VERSION)
try:
handle = codecs.open(path, encoding='utf-8')
return handle.read(131072).r... | def readme() | Try to read README.rst or return empty string if failed.
:return: File contents.
:rtype: str | 3.277956 | 3.461678 | 0.946927 |
cmd = 'python -m serial.tools.list_ports'
err, ret = commands.getstatusoutput(cmd)
if not err:
r = ret.split('\n')
ret = []
for line in r:
if line.find('/dev/') >= 0:
line = line.replace(' ', '')
ret.append(line)
return err, ret | def listSerialPorts() | http://pyserial.readthedocs.io/en/latest/shortintro.html
This calls the command line tool from pyserial to list the available
serial ports. | 2.61815 | 2.579027 | 1.01517 |
print('---------------------------------------')
print("{:.<29} {}".format('id', ctrl_table['id']))
ctrl_table.pop('id')
for key, value in ctrl_table.items():
print("{:.<29} {}".format(key, value)) | def prettyPrintPacket(ctrl_table) | This will pretty print out a packet's fields.
in: dictionary of a packet
out: nothing ... everything is printed to screen | 3.19405 | 3.385486 | 0.943454 |
try:
with open(fname, 'r') as f:
data = json.load(f)
return data
except IOError:
raise Exception('Could not open {0!s} for reading'.format((fname))) | def read(fname) | Reads a Json file
in: file name
out: length of file, dictionary | 3.223295 | 3.260992 | 0.98844 |
try:
with open(fname, 'w') as f:
json.dump(data, f)
except IOError:
raise Exception('Could not open {0!s} for writing'.format((fname))) | def write(fname, data) | Writes a Json file
in: fname - file name
data - dictionary of data to put into the file
out: nothing, everything is written to a file | 3.420357 | 3.292969 | 1.038685 |
pkt = []
pkt += [0xFF, 0xFF, 0xFD] # header
pkt += [0x00] # reserved byte
pkt += [ID]
pkt += [0x00, 0x00] # length placeholder
pkt += [instr] # instruction
if reg:
pkt += le(reg) # not everything has a register
if params:
pkt += params # not everything has parameters
length = le(len(pkt) - 5) #... | def makePacket(ID, instr, reg=None, params=None) | This makes a generic packet.
TODO: look a struct ... does that add value using it?
0xFF, 0xFF, 0xFD, 0x00, ID, LEN_L, LEN_H, INST, PARAM 1, PARAM 2, ..., PARAM N, CRC_L, CRC_H]
in:
ID - servo id
instr - instruction
reg - register
params - instruction parameter values
out: packet | 3.489952 | 3.101953 | 1.125082 |
pkt = makePacket(ID, xl320.XL320_WRITE, reg, values)
return pkt | def makeWritePacket(ID, reg, values=None) | Creates a packet that writes a value(s) to servo ID at location reg. Make
sure the values are in little endian (use Packet.le() if necessary) for 16 b
(word size) values. | 5.795636 | 7.352689 | 0.788234 |
pkt = makePacket(ID, xl320.XL320_READ, reg, values)
return pkt | def makeReadPacket(ID, reg, values=None) | Creates a packet that reads the register(s) of servo ID at location reg. Make
sure the values are in little endian (use Packet.le() if necessary) for 16 b
(word size) values. | 6.092706 | 7.593674 | 0.80234 |
if param not in [0x01, 0x02, 0xff]:
raise Exception('Packet.makeResetPacket invalide parameter {}'.format(param))
# pkt = makePacket(ID, xl320.XL320_RESET, None, [param])
pkt = makePacket(ID, xl320.XL320_RESET, None, [1])
return pkt | def makeResetPacket(ID, param) | Resets a servo to one of 3 reset states:
XL320_RESET_ALL = 0xFF
XL320_RESET_ALL_BUT_ID = 0x01
XL320_RESET_ALL_BUT_ID_BAUD_RATE = 0x02 | 3.793475 | 3.529812 | 1.074696 |
if not (0.0 <= angle <= 300.0):
raise Exception('makeServoPacket(), angle out of bounds: {}'.format(angle))
val = int(angle/300*1023)
# lo, hi = le(val)
# print('servo cmd {} deg : {} : L {} H {}'.format(angle, val, lo, hi))
pkt = makeWritePacket(ID, xl320.XL320_GOAL_POSITION, le(val))
return pkt | def makeServoPacket(ID, angle) | Commands the servo to an angle (in degrees) | 5.684825 | 5.976481 | 0.951199 |
angle = int(angle/300.0*1023)
pkt = makeWritePacket(ID, xl320.XL320_CCW_ANGLE_LIMIT, le(angle))
return pkt | def makeServoMaxLimitPacket(ID, angle) | Sets the maximum servo angle (in the CCW direction) | 6.290226 | 6.237436 | 1.008463 |
angle = int(angle/300.0*1023)
pkt = makeWritePacket(ID, xl320.XL320_CW_ANGLE_LIMIT, le(angle))
return pkt | def makeServoMinLimitPacket(ID, angle) | Sets the minimum servo angle (in the CW direction) | 6.230587 | 6.588329 | 0.945701 |
if 0.0 > maxSpeed > 1.0:
raise Exception('makeServoSpeed: max speed is a percentage (0.0-1.0)')
speed = int(maxSpeed*1023)
pkt = makeWritePacket(ID, xl320.XL320_GOAL_VELOCITY, le(speed))
return pkt | def makeServoSpeedPacket(ID, maxSpeed) | Run servo between 0.0 to 1.0, where 1.0 is 100% (full) speed. | 4.730493 | 4.532857 | 1.043601 |
# pkt = [255, 255, 253, 0, ID, 11, 0, 3, 25, 0, 2 crc_l, crc_h]
pkt = makeWritePacket(ID, xl320.XL320_LED, [color])
return pkt | def makeLEDPacket(ID, color) | Turn on/off the servo LED and also sets the color. | 6.421332 | 6.287842 | 1.02123 |
pkt = makeWritePacket(ID, xl320.XL320_DELAY_TIME, delay)
return pkt | def makeDelayPacket(ID, delay) | It is the delay time per data value that takes from the transmission of
Instruction Packet until the return of Status Packet.
0 to 254 (0xFE) can be used, and the delay time per data value is 2 usec.
That is to say, if the data value is 10, 20 usec is delayed. The initial
value is 250 (0xFA) (i.e., 0.5 msec). | 8.034785 | 13.030195 | 0.616628 |
pkt = makeWritePacket(ID, xl320.XL320_CONTROL_MODE, le(mode))
return pkt | def makeControlModePacket(ID, mode) | Sets the xl-320 to either servo or wheel mode | 8.192304 | 6.864631 | 1.193408 |
if rate not in [0, 1, 2, 3]:
raise Exception('Packet.makeBaudRatePacket: wrong rate {}'.format(rate))
pkt = makeWritePacket(ID, xl320.XL320_BAUD_RATE, [rate])
return pkt | def makeBaudRatePacket(ID, rate) | Set baud rate of servo.
in: rate - 0: 9600, 1:57600, 2:115200, 3:1Mbps
out: write packet | 4.258946 | 4.29262 | 0.992156 |
addr = le(xl320.XL320_GOAL_POSITION)
data = []
# since all servo angles have the same register addr (XL320_GOAL_POSITION)
# and data size (2), a sinc packet is smart choice
# compare bulk vs sync for the same commands:
# bulk = 94 bytes
# sync = 50 bytes
data.append(addr[0]) # LSB
data.append(addr[1]) # M... | def makeSyncAnglePacket(info) | Write sync angle information to servos.
info = [[ID, angle], [ID, angle], ...] | 5.258639 | 5.029486 | 1.045562 |
addr = le(xl320.XL320_GOAL_POSITION)
data = []
for pkt in info:
data.append(pkt[0]) # ID
data.append(addr[0]) # LSB
data.append(addr[1]) # MSB
data.append(2) # 2 bytes
data.append(0)
angle = le(int(pkt[1]/300*1023))
data.append(angle[0]) # LSB
data.append(angle[1]) # MSB
ID = xl320.XL320_BR... | def makeBulkAnglePacket(info) | Write bulk angle information to servos.
info = [[ID, angle], [ID, angle], ...] | 3.573942 | 3.414092 | 1.046821 |
s = 'packet ID: {} instr: {} len: {}'.format(pkt[4], pkt[7], int((pkt[6] << 8) + pkt[5]))
if len(s) > 10:
params = pkt[8:-2]
s += ' params: {}'.format(params)
return s | def prettyPrintPacket(pkt) | not done | 4.51332 | 4.529659 | 0.996393 |
# print('findpkt', pkt)
# print('-----------------------')
ret = []
while len(pkt)-10 >= 0:
if pkt[0:4] != [0xFF, 0xFF, 0xFD, 0x00]:
pkt.pop(0) # get rid of the first index
# print(' - pop:', pkt)
continue
# print(' > good packet')
length = (pkt[6] << 8) + pkt[5]
# print(' > length', length)
c... | def findPkt(pkt) | Search through a string of binary for a valid xl320 package.
in: buffer to search through
out: a list of valid data packet | 3.181361 | 3.145542 | 1.011387 |
d = {
'id': pkt[4],
'instruction': xl320.InstrToStr[pkt[7]],
'length': (pkt[6] << 8) + pkt[5],
'params': pkt[8:-2],
'crc': pkt[-2:]
}
return d | def packetToDict(pkt) | Given a packet, this turns it into a dictionary ... is this useful?
in: packet, array of numbers
out: dictionary (key, value) | 4.574083 | 4.249293 | 1.076434 |
ReceiptType.objects.populate()
ConceptType.objects.populate()
DocumentType.objects.populate()
VatType.objects.populate()
TaxType.objects.populate()
CurrencyType.objects.populate() | def populate_all() | Fetch and store all metadata from the AFIP. | 4.273785 | 4.851371 | 0.880944 |
ct = CurrencyType.objects.filter(code='PES').first()
if ct:
return ct.pk | def first_currency() | Returns the id for the first currency
The `default` parameter of a foreign key *MUST* be a primary key (and not
an instance), else migrations break. This helper method exists solely for
that purpose. | 8.112635 | 9.63099 | 0.842347 |
ticket = ticket or AuthTicket.objects.get_any_active('wsfe')
client = clients.get_client('wsfe', ticket.owner.is_sandboxed)
service = getattr(client.service, self.__service_name)
response_xml = service(serializers.serialize_ticket(ticket))
check_response(response_xml)
... | def populate(self, ticket=None) | Populate the database with types retrieved from the AFIP.
If no ticket is provided, the most recent available one will be used. | 6.705861 | 6.350382 | 1.055977 |
if not self.certificate:
return None
self.certificate.seek(0)
return crypto.parse_certificate(self.certificate.read()) | def certificate_object(self) | Returns the certificate as an OpenSSL object
Returns the certificate as an OpenSSL object (rather than as a file
object). | 5.618801 | 5.263386 | 1.067526 |
datestring = self.certificate_object.get_notAfter().decode()
dt = datetime.strptime(datestring, '%Y%m%d%H%M%SZ')
return dt.replace(tzinfo=timezone.utc) | def get_certificate_expiration(self) | Gets the certificate expiration from the certificate
Gets the certificate expiration from the certificate file. Note that
this value is stored into ``certificate_expiration`` when an instance
is saved, so you should generally prefer that method (since this one
requires reading and pars... | 2.895481 | 2.807267 | 1.031424 |
if self.key and not force:
logger.warning(
'Tried to generate key for a taxpayer that already had one'
)
return False
with NamedTemporaryFile(suffix='.key') as file_:
crypto.create_key(file_)
self.key = File(file_, nam... | def generate_key(self, force=False) | Creates a key file for this TaxPayer
Creates a key file for this TaxPayer if it does not have one, and
immediately saves it.
Returns True if and only if a key was created. | 4.848256 | 3.962367 | 1.223576 |
csr = BytesIO()
crypto.create_csr(
self.key.file,
self.name,
'{}{}'.format(basename, int(datetime.now().timestamp())),
'CUIT {}'.format(self.cuit),
csr,
)
csr.seek(0)
return csr | def generate_csr(self, basename='djangoafip') | Creates a CSR for this TaxPayer's key
Creates a file-like object that contains the CSR which can be used to
request a new certificate from AFIP. | 5.205181 | 5.222984 | 0.996591 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.