output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
Calculates the approximate Pagerank and residual vectors at a given push node.
Can you tell what is the following Python 3 function doing def pagerank_lazy_push(s, r, w_i, a_i, push_node, rho, lazy): # 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 ...
As a Python code analyst, you investigate and solve complex coding mysteries
This function performs a random step without a self - loop.
How would you explain what the following Python 3 function does def cumulative_pagerank_difference_limit_push(s, r, w_i, a_i, push_node, rho): # Calculate the commute quantity commute = (1-rho)*r[push_node] # Update approximate regularized commute and residual vectors r[push_node] = 0.0 # Update r...
You are a Python code generator, capable of creating scripts from specifications.
def includeme(config): """Include pyramid_multiauth into a pyramid configurator. This function provides a hook for pyramid to include the default settings for auth via pyramid_multiauth. Activate it like so: config.include("pyramid_multiauth") This will pull the list of registered authn poli...
Write a Python 3 function for including pyramid_multiauth into a pyramid configurator.
As a Python code translator, you convert algorithms and pseudocode into Python.
Create a function that returns a function that will be called when the module is loaded.
Make a summary of the following Python 3 code def policy_factory_from_module(config, module): # 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(m...
You are a Python code generator, capable of creating scripts from specifications.
Find all multiauth policy definitions from the settings dict.
Can you generate the documentation for the following Python 3 function def get_policy_definitions(settings): policy_definitions = {} for name in settings: if not name.startswith("multiauth.policy."): continue value = settings[name] name = name[len("multiauth.policy."):] ...
As a Python code translator, you convert algorithms and pseudocode into Python.
Read file to memory.
Explain what the following Python 3 code does def load_file(filename): 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...
You are a Python code architect, reviewing and designing scalable and efficient code
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 """ if code in Main.options['ignore']: return True if any(c in code for c in Main.options['ignore']): return Tru...
Can you write a function in Python 3 where it returns True if code should be ignored False otherwise.
As a Python code translator, you convert algorithms and pseudocode into Python.
def add_options(cls, parser): """Add options to flake8. :param parser: optparse.OptionParser from pycodestyle. """ parser.add_option('--show-pydocstyle', action='store_true', help='show explanation of each PEP 257 error') parser.config_options.append('show-pydocstyle')
Implement a function in Python 3 to add options to flake8.
As a Python code analyst, you investigate and solve complex coding mysteries
Read parsed options from flake8.
Given the following Python 3 function, write the documentation def parse_options(cls, options): # Handle flake8 options. cls.options['explain'] = bool(options.show_pydocstyle) cls.options['ignore'] = options.ignore # Handle pydocstyle options. config = pydocstyle.RawConfigParser...
You are a Python code analyst, evaluating scripts for potential improvements.
def run(self): """Run analysis on a single file.""" 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): ...
Write a Python 3 script to run analysis on a single file.
As a python code expert, you are capable of creating scripts from specifications.
def numbers(self): """" Returns the barcode's number without the verification digit. :return: list(int) """ numstring = '{:011d}{:02d}{:04d}{}{}'.format( self._receipt.point_of_sales.owner.cuit, # 11 digits int(self._receipt.receipt_type.code), # 2 digi...
Write a Python 3 function that can return the barcode s number without the verification digit.
As a python code expert, you are capable of creating scripts from specifications.
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 result...
How would you implement a function in Python 3 that returns the verification digit for a given list of numbers.
You are a Python code architect, reviewing and designing scalable and efficient code
Returns the full number including the verification digit.
Explain what the following Python 3 code does def full_number(self): return '{}{}'.format( ''.join(str(n) for n in self.numbers), ReceiptBarcodeGenerator.verification_digit(self.numbers), )
You are a Python code analyst, evaluating scripts for potential improvements.
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. ",", ...
Write a Python 3 function for reading an adjacency matrix in csv format and returns the adjacency matrix in SciPy Sparse COOrdinate format.
As a Python code translator, you convert algorithms and pseudocode into Python.
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", " ...
Write a Python 3 script to read node - label pairs in csv format and returns a list of tuples and a matrix of node - label pairs.
You are a Python code generator, capable of creating scripts from specifications.
Writes a user name and associated topic names per row.
Can you tell what is the following Python 3 function doing def write_screen_name_to_topics(filepath, user_label_matrix, node_to_id, id_to_name, label_to_lemma, lemma_to_keyword, separator=","): user_label_matrix = spsp.coo_matrix(user_label_matrix) shape = user_label_matrix.shape nnz = user_label_matrix.ge...
As a Python code translator, you convert algorithms and pseudocode into Python.
This function turns a packet into a dictionary.
Can you generate the documentation for the following Python 3 function def packetToDict(pkt): 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': ErrorStatusMs...
You are a Python code architect, reviewing and designing scalable and efficient code
Send a ping packet to the specified ID and returns any returned values.
Here you have a function in Python 3, explain what it does def sweep(port, rate, ID, retry=3): 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...
As a Python code translator, you convert algorithms and pseudocode into Python.
Calculates the effective epsilon threshold for a single node.
Can you generate the documentation for the following Python 3 function def calculate_epsilon_effective(rho, epsilon, seed_degree, neighbor_degrees, mean_degree): # Calculate a weighted neighborhood degree average. # neighborhood_degree = rho*seed_degree + (1-rho)*neighbor_degrees.mean() neighborhood_degree ...
You are a Python code architect, reviewing and designing scalable and efficient code
This function extracts local community features for all graph nodes based on the partitioning of node - centric similarity vectors.
Explain what the following Python 3 code does def arcte_with_lazy_pagerank(adjacency_matrix, rho, epsilon, number_of_threads=None): adjacency_matrix = sparse.csr_matrix(adjacency_matrix) number_of_nodes = adjacency_matrix.shape[0] if number_of_threads is None: number_of_threads = get_threads_number...
As a Python code composer, you craft elegant and concise scripts.
Returns a generator that generates train and test folds for training and testing.
Here you have a function in Python 3, explain what it does def get_folds_generator(node_label_matrix, labelled_node_indices, number_of_categories, dataset_memory_folder, percentage, number_of_folds=10...
As a Python code analyst, you investigate and solve complex coding mysteries
Generates the train and test set folds for training and testing.
Can you generate a brief explanation for the following Python 3 code def generate_folds(node_label_matrix, labelled_node_indices, number_of_categories, percentage, number_of_folds=10): number_of_labeled_nodes = labelled_node_indices.size training_set_size = int(np.ceil(percentage*number_of_labeled_nodes/100)) ...
You are a Python code architect, reviewing and designing scalable and efficient code
This function generates an iterative stratification of the data folds.
Can you generate the documentation for the following Python 3 function def iterative_stratification(node_label_matrix, training_set_size, number_of_categories, random_seed=0): number_of_labelled_nodes = node_label_matrix.shape[0] testing_set_size = number_of_labelled_nodes - training_set_size training_set_p...
You are a Python code generator, capable of creating scripts from specifications.
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 f...
Create a Python 3 function for giving the discriminator distances y_pred and y_test this function forms the node - label prediction matrix.
As a Python code analyst, you investigate and solve complex coding mysteries
Calculates the F - scores and F - score averages given a classification result and ground truth.
Can you tell what is the following Python 3 function doing def calculate_measures(y_pred, y_test): y_pred = y_pred.toarray() y_test = y_test.toarray() macro_precision, macro_recall, macro_F1, macro_support = precision_recall_fscore_support(y_test, ...
You are a Python code analyst, evaluating scripts for potential improvements.
Transforms the raw buffer data read in into a list of bytes
Can you tell what is the following Python 3 function doing def decode(buff): pp = list(map(ord, buff)) if 0 == len(pp) == 1: pp = [] return pp
As a python code expert, you are capable of creating scripts from specifications.
This function reads in data from the RTS pin and returns a list of valid packets.
Can you generate a brief explanation for the following Python 3 code 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.seri...
You are a Python code architect, reviewing and designing scalable and efficient code
This is a simple serial write command. It writes a packet to the serial port and returns the number of bytes written.
Given the following Python 3 function, write the documentation def write(self, pkt): 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, le...
As a python code expert, you are capable of creating scripts from specifications.
sends a packet and waits for a return.
Given the following Python 3 function, write the documentation def sendPkt(self, pkt, retry=5, sleep_time=0.01): 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 ...
As a python code expert, you are capable of creating scripts from specifications.
Writes sparse matrix in separated value format.
Can you generate the documentation for the following Python 3 function def scipy_sparse_to_csv(filepath, matrix, separator=",", directed=False, numbering="matlab"): matrix = spsp.coo_matrix(matrix) shape = matrix.shape nnz = matrix.getnnz() if numbering == "matlab": row = matrix.row + 1 ...
As a Python code composer, you craft elegant and concise scripts.
Reads an adjacency matrix in csv format and returns the adjacency matrix.
Can you generate the documentation for the following Python 3 function def read_adjacency_matrix(file_path, separator, undirected): # 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() ...
You are a Python code analyst, evaluating scripts for potential improvements.
publish the package itself
Can you generate the documentation for the following Python 3 function def publish(build): build.packages.install("wheel") build.packages.install("twine") build.executables.run([ "python", "setup.py", "sdist", "bdist_wheel", "--universal", "--release" ]) build.executables.run([ ...
You are a Python code generator, capable of creating scripts from specifications.
def fast_approximate_personalized_pagerank(s, r, w_i, a_i, out_degree, in_degree, ...
Write a Python 3 script for calculating the approximate personalized PageRank starting from a seed node without self - loops.
As a Python code translator, you convert algorithms and pseudocode into Python.
def lazy_approximate_personalized_pagerank(s, r, w_i, a_i, out_degree, in_degree, ...
Implement a Python 3 function for calculating the approximate personalized PageRank starting from a seed node with self - loops.
You are a Python code generator, capable of creating scripts from specifications.
Reads the Matlab feature matrix from the given array of files.
Here you have a function in Python 3, explain what it does def read_matlab_features(array_paths, number_of_nodes, dimensionality): # 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_da...
As a Python code composer, you craft elegant and concise scripts.
This function extracts hierarchical community features using the MROC method.
Make a summary of the following Python 3 code def mroc(adjacency_matrix, alpha): # Find number of nodes number_of_nodes = adjacency_matrix.shape[0] #################################################################################################################### # Base community calculation #####...
As a Python code analyst, you investigate and solve complex coding mysteries
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:...
Implement a function in Python 3 to find communities with shared nodes to a seed community.
As a Python code composer, you craft elegant and concise scripts.
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. """ nom = np.inter...
Write a Python 3 function for calculating the Jaccard similarity between two communities.
You are a Python code analyst, evaluating scripts for potential improvements.
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 an...
How would you code a function in Python 3 to perform 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: - ...
You are a Python code architect, reviewing and designing scalable and efficient code
This function computes the eigenmaps of the graph symmetrically normalized Laplacian matrix.
Can you generate the documentation for the following Python 3 function def laplacian_eigenmaps(adjacency_matrix, k): # Calculate sparse graph Laplacian. laplacian = get_normalized_laplacian(adjacency_matrix) # Calculate bottom k+1 eigenvalues and eigenvectors of normalized Laplacian. try: eigen...
As a Python code composer, you craft elegant and concise scripts.
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/eigenve...
Create a Python 3 function for performing 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 number of itera...
As a Python code translator, you convert algorithms and pseudocode into Python.
Returns the community indicator normalized feature matrix for any graph.
Can you generate a brief explanation for the following Python 3 code def base_communities(adjacency_matrix): 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(nu...
You are a Python code analyst, evaluating scripts for potential improvements.
Create an embeded PKCS7 signature.
How would you explain what the following Python 3 function does def create_embeded_pkcs7_signature(data, cert, key): assert isinstance(data, bytes) assert isinstance(cert, str) try: pkey = crypto.load_privatekey(crypto.FILETYPE_PEM, key) signcert = crypto.load_certificate(crypto.FILETYPE_P...
You are a Python code generator, capable of creating scripts from specifications.
Create a key and save it into file_.
Explain what the following Python 3 code does def create_key(file_): pkey = crypto.PKey() pkey.generate_key(crypto.TYPE_RSA, 2048) file_.write(crypto.dump_privatekey(crypto.FILETYPE_PEM, pkey)) file_.flush()
As a Python code composer, you craft elegant and concise scripts.
Create a CSR for a key and save it into file.
Can you generate the documentation for the following Python 3 function def create_csr(key_file, organization_name, common_name, serial_number, file_): key = crypto.load_privatekey(crypto.FILETYPE_PEM, key_file.read()) req = crypto.X509Req() subj = req.get_subject() subj.O = organization_name # noqa: ...
You are a Python code analyst, evaluating scripts for potential improvements.
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.OneVsRe...
Write a Python 3 script for fitting a Linear Support Vector Classifier to the labelled graph - based features using the LIBLINEAR library.
As a python code expert, you are capable of creating scripts from specifications.
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 ...
Create a Python 3 function to fit a meta - labeler model to the data.
You are a Python code architect, reviewing and designing scalable and efficient code
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...
Write a Python 3 script for using 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_type...
You are a Python code generator, capable of creating scripts from specifications.
def classify_users(X_test, model, classifier_type, meta_model, upper_cutoff): """ Uses a trained model and the unlabelled features to associate users with labels. The decision is done as per scikit-learn: http://scikit-learn.org/stable/modules/generated/sklearn.multiclass.OneVsRestClassifier.html h...
Write a Python 3 script for classifying the users in a single - class graph based on the unlabelled features.
As a Python code composer, you craft elegant and concise scripts.
Returns a zeep client for a given service.
Can you generate the documentation for the following Python 3 function def get_client(service_name, sandbox=False): key = (service_name.lower(), sandbox,) try: if key not in cached_clients: cached_clients[key] = Client(wsdls[key], transport=transport) return cached_clients[key] ...
As a Python code analyst, you investigate and solve complex coding mysteries
def _extract_seq(extractor, seq): """Convert a sequence to primitive equivalents.""" subtype = Any if seq.__args__ and seq.__args__[0] is not Any: subtype = seq.__args__[0] return _array_type(extractor.extract(subtype))
How would you code a function in Python 3 to convert a sequence to primitive equivalents.
As a Python code composer, you craft elegant and concise scripts.
def _is_sequence(typ): """ returns True if the type in question is a Sequence[] object from the typing module. """ # 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, ...
Implement a function in Python 3 to return True if the type in question is a Sequence object from the typing module.
As a Python code analyst, you investigate and solve complex coding mysteries
def extract(cls, extractor, typ): """ take an attrs based class, and convert it to jsonschema. """ schema = { "title": typ.__name__, "type": "object", "properties": {}, "required": [] } for attribute in attr.fields(t...
Can you implement a function in Python 3 that takes an attrs based class and convert it to jsonschema.
As a Python code composer, you craft elegant and concise scripts.
def readme(): """Try to read README.rst or return empty string if failed. :return: File contents. :rtype: str """ 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(...
How would you implement a function in Python 3 that tries to read README. rst or return empty string if failed.
You are a Python code architect, reviewing and designing scalable and efficient code
def listSerialPorts(): """ http://pyserial.readthedocs.io/en/latest/shortintro.html This calls the command line tool from pyserial to list the available serial ports. """ cmd = 'python -m serial.tools.list_ports' err, ret = commands.getstatusoutput(cmd) if not err: r = ret.split('\n') ret = [] for line i...
Write a Python 3 function for listing available serial ports
As a Python code composer, you craft elegant and concise scripts.
This will pretty print out a packet s fields.
Can you generate a brief explanation for the following Python 3 code def prettyPrintPacket(ctrl_table): print('---------------------------------------') print("{:.<29} {}".format('id', ctrl_table['id'])) ctrl_table.pop('id') for key, value in ctrl_table.items(): print("{:.<29} {}".format(key, value))
As a Python code composer, you craft elegant and concise scripts.
def read(fname): """ Reads a Json file in: file name out: length of file, dictionary """ 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)))
Implement a Python 3 function for reading a Json file and returns a dictionary
You are a Python code generator, capable of creating scripts from specifications.
Writes a Json file with the given data to the given file.
Here you have a function in Python 3, explain what it does def write(fname, data): try: with open(fname, 'w') as f: json.dump(data, f) except IOError: raise Exception('Could not open {0!s} for writing'.format((fname)))
You are a Python code generator, capable of creating scripts from specifications.
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. """ pkt = makePacket(ID, xl320.XL320_WRITE, reg, values) return pkt
Create a Python 3 function for making a write packet that writes a value to the servo ID at the given register.
As a Python code translator, you convert algorithms and pseudocode into Python.
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. """ pkt = makePacket(ID, xl320.XL320_READ, reg, values) return pkt
How would you code a function in Python 3 to make a read packet that reads the register of servo ID at location reg.
You are a Python code analyst, evaluating scripts for potential improvements.
This function creates a packet that is used to reset a servo to one of 3 reset states.
Make a summary of the following Python 3 code def makeResetPacket(ID, param): 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
As a Python code analyst, you investigate and solve complex coding mysteries
def makeServoPacket(ID, angle): """ Commands the servo to an angle (in degrees) """ 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)) p...
How would you implement a function in Python 3 that commands the servo to an angle (in degrees)
You are a Python code generator, capable of creating scripts from specifications.
def makeServoMaxLimitPacket(ID, angle): """ Sets the maximum servo angle (in the CCW direction) """ angle = int(angle/300.0*1023) pkt = makeWritePacket(ID, xl320.XL320_CCW_ANGLE_LIMIT, le(angle)) return pkt
How would you code a function in Python 3 to make a servo max limit packet.
As a Python code translator, you convert algorithms and pseudocode into Python.
Make a servo minimum limit packet.
How would you explain what the following Python 3 function does def makeServoMinLimitPacket(ID, angle): angle = int(angle/300.0*1023) pkt = makeWritePacket(ID, xl320.XL320_CW_ANGLE_LIMIT, le(angle)) return pkt
As a Python code composer, you craft elegant and concise scripts.
Make a servo speed packet.
Here you have a function in Python 3, explain what it does def makeServoSpeedPacket(ID, maxSpeed): 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
As a python code expert, you are capable of creating scripts from specifications.
def makeLEDPacket(ID, color): """ Turn on/off the servo LED and also sets the color. """ # 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
How would you code a function in Python 3 to turn on or off the servo LED.
As a python code expert, you are capable of creating scripts from specifications.
Make a delay packet.
Can you tell what is the following Python 3 function doing def makeDelayPacket(ID, delay): pkt = makeWritePacket(ID, xl320.XL320_DELAY_TIME, delay) return pkt
As a Python code translator, you convert algorithms and pseudocode into Python.
Make a xl - 320 control mode packet.
How would you explain what the following Python 3 function does def makeControlModePacket(ID, mode): pkt = makeWritePacket(ID, xl320.XL320_CONTROL_MODE, le(mode)) return pkt
As a Python code composer, you craft elegant and concise scripts.
makeBaudRatePacket - make baud rate packet
How would you explain what the following Python 3 function does def makeBaudRatePacket(ID, rate): 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
You are a Python code analyst, evaluating scripts for potential improvements.
def makeSyncAnglePacket(info): """ Write sync angle information to servos. info = [[ID, angle], [ID, angle], ...] """ 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 ...
Can you write a function in Python 3 where it makes sync angle packet
You are a Python code analyst, evaluating scripts for potential improvements.
def makeBulkAnglePacket(info): """ Write bulk angle information to servos. info = [[ID, angle], [ID, angle], ...] """ 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(...
Write a Python 3 function for making a bulk angle packet.
As a Python code analyst, you investigate and solve complex coding mysteries
findpkt - Search through a string of binary for a valid xl320 package.
Explain what the following Python 3 code does def findPkt(pkt): # 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') leng...
As a python code expert, you are capable of creating scripts from specifications.
This function turns a packet into a dictionary
Can you tell what is the following Python 3 function doing def packetToDict(pkt): d = { 'id': pkt[4], 'instruction': xl320.InstrToStr[pkt[7]], 'length': (pkt[6] << 8) + pkt[5], 'params': pkt[8:-2], 'crc': pkt[-2:] } return d
As a python code expert, you are capable of creating scripts from specifications.
Fetch and store all metadata from the AFIP.
Can you tell what is the following Python 3 function doing def populate_all(): ReceiptType.objects.populate() ConceptType.objects.populate() DocumentType.objects.populate() VatType.objects.populate() TaxType.objects.populate() CurrencyType.objects.populate()
As a Python code composer, you craft elegant and concise scripts.
Returns the id for the first currency in the not
Can you tell what is the following Python 3 function doing def first_currency(): ct = CurrencyType.objects.filter(code='PES').first() if ct: return ct.pk
As a python code expert, you are capable of creating scripts from specifications.
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. """ ticket = ticket or AuthTicket.objects.get_any_active('wsfe') client = clients.get_client('wsfe', ticke...
Can you implement a function in Python 3 that populates the database with types retrieved from the AFIP.
You are a Python code architect, reviewing and designing scalable and efficient code
def certificate_object(self): """ Returns the certificate as an OpenSSL object Returns the certificate as an OpenSSL object (rather than as a file object). """ if not self.certificate: return None self.certificate.seek(0) return crypto.parse_c...
Write a Python 3 script to return the certificate as an OpenSSL object.
As a Python code analyst, you investigate and solve complex coding mysteries
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 tha...
Implement a Python 3 function for getting the certificate expiration from the certificate file.
As a Python code analyst, you investigate and solve complex coding mysteries
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. """ if self.key and not force: logger...
Create a Python 3 function to generate a key file for this TaxPayer and saves it. Returns True if a key was created False otherwise.
As a Python code composer, you craft elegant and concise scripts.
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. """ csr = BytesIO() crypto.create_csr( self.key.file, ...
Write a Python 3 script for generating a CSR for this TaxPayer s key and returns it
You are a Python code generator, capable of creating scripts from specifications.
def create_ticket(self, service): """Create an AuthTicket for a given service.""" ticket = AuthTicket(owner=self, service=service) ticket.authorize() return ticket
Write a Python 3 function that can create an AuthTicket for a given service.
As a Python code composer, you craft elegant and concise scripts.
Return an existing AuthTicket for a given service.
How would you explain what the following Python 3 function does def get_ticket(self, service): return self.auth_tickets \ .filter(expires__gt=datetime.now(timezone.utc), service=service) \ .last()
You are a Python code generator, capable of creating scripts from specifications.
def fetch_points_of_sales(self, ticket=None): """ Fetch all point of sales objects. Fetch all point of sales from the WS and store (or update) them locally. Returns a list of tuples with the format (pos, created,). """ ticket = ticket or self.get_or_create_ticke...
Create a Python 3 function to fetch all point of sales from the WS and store them locally.
You are a Python code architect, reviewing and designing scalable and efficient code
Send this ticket to AFIP for authorization.
Given the following Python 3 function, write the documentation def authorize(self): request = self.__create_request_xml() request = self.__sign_request(request) request = b64encode(request).decode() client = clients.get_client('wsaa', self.owner.is_sandboxed) try: ra...
You are a Python code analyst, evaluating scripts for potential improvements.
Assign numbers in preparation for validating these receipts.
Can you generate a brief explanation for the following Python 3 code def _assign_numbers(self): first = self.select_related('point_of_sales', 'receipt_type').first() next_num = Receipt.objects.fetch_last_receipt_number( first.point_of_sales, first.receipt_type, ) + 1 ...
You are a Python code architect, reviewing and designing scalable and efficient code
def check_groupable(self): """ Checks that all receipts returned by this queryset are groupable. "Groupable" means that they can be validated together: they have the same POS and receipt type. Returns the same queryset is all receipts are groupable, otherwise, raises :c...
How would you code a function in Python 3 to check that all receipts returned by this queryset are groupable.
As a Python code analyst, you investigate and solve complex coding mysteries
def validate(self, ticket=None): """ Validates all receipts matching this queryset. Note that, due to how AFIP implements its numbering, this method is not thread-safe, or even multiprocess-safe. Because of this, it is possible that not all instances matching this query...
Write a Python 3 function that can validate all receipts matching this queryset and returns a list of validation errors.
As a Python code translator, you convert algorithms and pseudocode into Python.
def fetch_last_receipt_number(self, point_of_sales, receipt_type): """Returns the number for the last validated receipt.""" client = clients.get_client('wsfe', point_of_sales.owner.is_sandboxed) response_xml = client.service.FECompUltimoAutorizado( serializers.serialize_ticket( ...
How would you implement a function in Python 3 that returns the number for the last validated receipt.
You are a Python code generator, capable of creating scripts from specifications.
def total_vat(self): """Returns the sum of all Vat objects.""" q = Vat.objects.filter(receipt=self).aggregate(total=Sum('amount')) return q['total'] or 0
Implement a function in Python 3 to return the sum of all Vat objects.
You are a Python code generator, capable of creating scripts from specifications.
Returns the sum of all Tax objects.
Can you tell what is the following Python 3 function doing def total_tax(self): q = Tax.objects.filter(receipt=self).aggregate(total=Sum('amount')) return q['total'] or 0
As a Python code composer, you craft elegant and concise scripts.
def is_validated(self): """ Returns True if this instance is validated. Note that resolving this property requires a DB query, so if you've a very large amount of receipts you should prefetch (see django's ``select_related``) the ``validation`` field. Even so, a DB query *may* ...
Write a Python 3 script for returning True if this instance is validated.
As a Python code translator, you convert algorithms and pseudocode into Python.
def validate(self, ticket=None, raise_=False): """ Validates this receipt. This is a shortcut to :class:`~.ReceiptQuerySet`'s method of the same name. Calling this validates only this instance. :param AuthTicket ticket: Use this ticket. If None, one will be loaded o...
Write a Python 3 script to validate this receipt. This is a shortcut to :class:`~.ReceiptQuerySet`'s method of the same name. Calling this validates only this instance. :param AuthTicket ticket: Use this ticket. If None, one will be loaded or created automatically. :param bool raise_: If True, an exception will be rais...
You are a Python code generator, capable of creating scripts from specifications.
Creates a ReceiptPDF object for a given receipt. Does not actually generate the related PDF file.
Make a summary of the following Python 3 code def create_for_receipt(self, receipt, **kwargs): try: profile = TaxPayerProfile.objects.get( taxpayer__points_of_sales__receipts=receipt, ) except TaxPayerProfile.DoesNotExist: raise exceptions.DjangoAfipEx...
You are a Python code analyst, evaluating scripts for potential improvements.
Save the receipt as a PDF related to this model instance.
Can you generate a brief explanation for the following Python 3 code def save_pdf(self, save_model=True): from django_afip.views import ReceiptPDFView if not self.receipt.is_validated: raise exceptions.DjangoAfipException( _('Cannot generate pdf for non-authorized receipt') ...
As a python code expert, you are capable of creating scripts from specifications.
Auto - assign and return the total amount for this tax.
Can you generate the documentation for the following Python 3 function def compute_amount(self): self.amount = self.base_amount * self.aliquot / 100 return self.amount
You are a Python code analyst, evaluating scripts for potential improvements.
def get_label_based_random_walk_matrix(adjacency_matrix, labelled_nodes, label_absorption_probability): """ Returns the label-absorbing random walk transition probability matrix. Input: - A: A sparse matrix that contains the adjacency matrix of the graph. Output: - W: A sparse matrix that contains th...
Implement a function in Python 3 to return the label - based random walk transition probability matrix.
As a Python code translator, you convert algorithms and pseudocode into Python.
def get_natural_random_walk_matrix(adjacency_matrix, make_shared=False): """ Returns the natural random walk transition probability matrix given the adjacency matrix. Input: - A: A sparse matrix that contains the adjacency matrix of the graph. Output: - W: A sparse matrix that contains the natural ra...
Create a Python 3 function for returning the natural random walk transition probability matrix given the adjacency matrix.
You are a Python code analyst, evaluating scripts for potential improvements.
def is_middleware(func) -> bool: """ test whether it is a middleware :return: Boolean """ if inspect.isfunction(func): _check = func _name = func.__name__ else: _check = func.__call__ _name = func.__class__.__name__ if not inspect.iscoroutinefunction(_check)...
Create a Python 3 function to test whether the function is a middleware
As a Python code analyst, you investigate and solve complex coding mysteries
def start(st_reg_number): """Checks the number valiaty for the Rondônia state""" divisor = 11 weight = [6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2] if len(st_reg_number) != 9 and len(st_reg_number) != 14: return False if len(st_reg_number) == 9: sum_total = 0 peso = 6 ...
Can you implement a function in Python 3 that checks the number valiaty for the Rondônia state
You are a Python code architect, reviewing and designing scalable and efficient code
Checks the number valiaty for the São Paulo state
Here you have a function in Python 3, explain what it does def start(st_reg_number): divisor = 11 verificador_one = int(st_reg_number[len(st_reg_number)-4]) verificador_two = int(st_reg_number[len(st_reg_number)-1]) weights_first = [1, 3, 4, 5, 6, 7, 8, 10] weights_secund = [3, 2, 10, 9, 8, 7, 6, ...
You are a Python code architect, reviewing and designing scalable and efficient code