code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
property_map = {'line-pattern-file': 'file', 'line-pattern-width': 'width', 'line-pattern-height': 'height', 'line-pattern-type': 'type', 'line-pattern-meta-output': 'meta-output', 'line-pattern-meta-writer': 'meta-writer'} property_names = property_map.keys() ...
def get_line_pattern_rules(declarations, dirs)
Given a list of declarations, return a list of output.Rule objects. Optionally provide an output directory for local copies of image files.
2.930073
2.808593
1.043253
element_tag = element.tag element_id = element.get('id', None) element_classes = element.get('class', '').split() return [dec for dec in declarations if dec.selector.matches(element_tag, element_id, element_classes)]
def get_applicable_declarations(element, declarations)
Given an XML element and a list of declarations, return the ones that match as a list of (property, value, selector) tuples.
2.948456
3.187457
0.925018
# support latest mapnik features of auto-detection # of image sizes and jpeg reading support... # http://trac.mapnik.org/ticket/508 mapnik_requires_absolute_paths = (MAPNIK_VERSION < 601) shp_href = urljoin(dirs.source.rstrip('/')+'/', shp_href) scheme, host, path, p, q, f = urlparse(shp_...
def localize_shapefile(shp_href, dirs)
Given a shapefile href and a set of directories, modify the shapefile name so it's correct with respect to the output and cache directories.
7.35075
7.395515
0.993947
# support latest mapnik features of auto-detection # of image sizes and jpeg reading support... # http://trac.mapnik.org/ticket/508 mapnik_requires_absolute_paths = (MAPNIK_VERSION < 601) file_href = urljoin(dirs.source.rstrip('/')+'/', file_href) scheme, n, path, p, q, f = urlparse(file_...
def localize_file_datasource(file_href, dirs)
Handle localizing file-based datasources other than shapefiles. This will only work for single-file based types.
8.087216
8.14452
0.992964
# make sure it is a valid posix format path = to_posix(path_name) assert (path == path_name), "path_name passed to output_path must be in posix format" if posixpath.isabs(path): if self.output == self.cache: # worth seeing if...
def output_path(self, path_name)
Modify a path so it fits expectations. Avoid returning relative paths that start with '../' and possibly return relative paths when output and cache directories match.
5.815651
5.026809
1.156927
minpoint = self.leftedge if self.leftop is gt: minpoint += 1 maxpoint = self.rightedge if self.rightop is lt: maxpoint -= 1 if minpoint is None: return maxpoint elif maxpoint is None: return min...
def midpoint(self)
Return a point guranteed to fall within this range, hopefully near the middle.
4.267142
3.841504
1.1108
if self.leftedge and self.rightedge and self.leftedge > self.rightedge: return False if self.leftedge == self.rightedge: if self.leftop is gt or self.rightop is lt: return False return True
def isOpen(self)
Return true if this range has any room in it.
5.718235
4.832463
1.183296
if self.leftedge == self.rightedge and self.leftop is ge and self.rightop is le: # equivalent to == return Filter(style.SelectorAttributeTest(property, '=', self.leftedge)) try: return Filter(style.SelectorAttributeTest(property, opstr[self.leftop], self...
def toFilter(self, property)
Convert this range to a Filter with a tests having a given property.
2.992062
2.822127
1.060215
equals = {} nequals = {} for test in self.tests: if test.op == '=': if equals.has_key(test.property) and test.value != equals[test.property]: # we've already stated that this arg must equal something else retur...
def isOpen(self)
Return true if this filter is not trivially false, i.e. self-contradictory.
2.537991
2.439228
1.04049
assert self.isOpen() trimmed = self.clone() equals = {} for test in trimmed.tests: if test.op == '=': equals[test.property] = test.value extras = [] for (i, test) in enumerate(trimmed.tests): if...
def minusExtras(self)
Return a new Filter that's equal to this one, without extra terms that don't add meaning.
3.766203
3.592741
1.048281
chunk_size = get_chunk_size(N, n) for start in range(0, N, chunk_size): yield slice(start, min(start + chunk_size, N))
def chunk_generator(N, n)
Returns a generator of slice objects. Parameters ---------- N : int The size of one of the dimensions of a two-dimensional array. n : int The number of arrays of shape ('N', 'get_chunk_size(N, n)') that fit into memory. Returns ------- Slice objects of...
2.765074
2.14362
1.289909
parser = optparse.OptionParser( usage = "Usage: %prog [options] file_name\n\n" "file_name denotes the path where the data to be " "processed by affinity propagation clustering is stored" ) parser.add_option('-m...
def parse_options()
Specify the command line options to parse. Returns ------- opts : optparse.Values instance Contains the option values in its 'dict' member variable. args[0] : string or file-handler The name of the file storing the data-set submitted for Affinity Propagation clustering.
3.01946
2.88188
1.04774
Worker.hdf5_lock.acquire() with tables.open_file(hdf5_file, 'r+') as fileh: if not hasattr(fileh.root, 'aff_prop_group'): fileh.create_group(fileh.root, "aff_prop_group") atom = tables.Float32Atom() filters = None #filters = tables.Filters(5, 'blosc') ...
def check_HDF5_arrays(hdf5_file, N, convergence_iter)
Check that the HDF5 data structure of file handle 'hdf5_file' has all the required nodes organizing the various two-dimensional arrays required for Affinity Propagation clustering ('Responsibility' matrix, 'Availability', etc.). Parameters ---------- hdf5_file : string or fil...
3.520882
3.192527
1.102851
Worker.hdf5_lock.acquire() with tables.open_file(hdf5_file, 'r+') as fileh: hdf5_array = fileh.get_node(path) tmp = hdf5_array[rows_slice, ...] Worker.hdf5_lock.release() szum = np.sum(tmp, axis = 0) with out_lock: array_out += szum ...
def get_sum(hdf5_file, path, array_out, out_lock, rows_slice)
Access an array at node 'path' of the 'hdf5_file', compute the sums along a slice of rows specified by 'rows_slice' and add the resulting vector to 'array_out'. Parameters ---------- hdf5_file : string or file handle The location of the HDF5 data structure containing the matri...
3.818628
4.147133
0.920787
for proc in psutil.process_iter(): if proc.pid in pid_list: proc.terminate()
def terminate_processes(pid_list)
Terminate a list of processes by sending to each of them a SIGTERM signal, pre-emptively checking if its PID might have been reused. Parameters ---------- pid_list : list A list of process identifiers identifying active processes.
2.771477
3.250781
0.852557
slice_queue = multiprocessing.JoinableQueue() pid_list = [] for i in range(N_processes): worker = Similarities_worker(hdf5_file, '/aff_prop_group/similarities', data, slice_queue) worker.daemon = True worker.start() pid_list.app...
def compute_similarities(hdf5_file, data, N_processes)
Compute a matrix of pairwise L2 Euclidean distances among samples from 'data'. This computation is to be done in parallel by 'N_processes' distinct processes. Those processes (which are instances of the class 'Similarities_worker') are prevented from simultaneously accessing the HDF5 data stru...
3.896607
3.754184
1.037937
Worker.hdf5_lock.acquire() with tables.open_file(hdf5_file, 'r+') as fileh: S = fileh.root.aff_prop_group.similarities diag_ind = np.diag_indices(S.nrows) S[diag_ind] = preference Worker.hdf5_lock.release()
def add_preference(hdf5_file, preference)
Assign the value 'preference' to the diagonal entries of the matrix of similarities stored in the HDF5 data structure at 'hdf5_file'.
5.902234
4.662803
1.265812
random_state = np.random.RandomState(0) slice_queue = multiprocessing.JoinableQueue() pid_list = [] for i in range(N_processes): worker = Fluctuations_worker(hdf5_file, '/aff_prop_group/similarities', random_state, N_columns, slice_q...
def add_fluctuations(hdf5_file, N_columns, N_processes)
This procedure organizes the addition of small fluctuations on top of a matrix of similarities at 'hdf5_file' across 'N_processes' different processes. Each of those processes is an instance of the class 'Fluctuations_Worker' defined elsewhere in this module.
4.068514
4.099319
0.992485
slice_queue = multiprocessing.JoinableQueue() pid_list = [] for i in range(N_processes): worker = Responsibilities_worker(hdf5_file, '/aff_prop_group', N_columns, damping, slice_queue) worker.daemon = True worker.start() pid_list.append(worker.pi...
def compute_responsibilities(hdf5_file, N_columns, damping, N_processes)
Organize the computation and update of the responsibility matrix for Affinity Propagation clustering with 'damping' as the eponymous damping parameter. Each of the processes concurrently involved in this task is an instance of the class 'Responsibilities_worker' defined above.
3.637737
3.371032
1.079117
global g_hdf5_file, g_path, g_out, g_out_lock g_hdf5_file, g_path, g_out_lock = hdf5_file, path, out_lock g_out = to_numpy_array(*numpy_args)
def rows_sum_init(hdf5_file, path, out_lock, *numpy_args)
Create global variables sharing the same object as the one pointed by 'hdf5_file', 'path' and 'out_lock'. Also Create a NumPy array copy of a multiprocessing.Array ctypes array specified by '*numpy_args'.
2.896114
2.838174
1.020415
return np.frombuffer(multiprocessing_array.get_obj(), dtype = dtype).reshape(shape)
def to_numpy_array(multiprocessing_array, shape, dtype)
Convert a share multiprocessing array to a numpy array. No data copying involved.
3.578636
4.461458
0.802123
assert isinstance(method, str), "parameter 'method' must consist in a string of characters" assert method in ('Ordinary', 'Pool'), "parameter 'method' must be set to either of 'Ordinary' or 'Pool'" if method == 'Ordinary': rows_sum = np.zeros(N_columns, dtype = float) ...
def compute_rows_sum(hdf5_file, path, N_columns, N_processes, method = 'Process')
Parallel computation of the sums across the rows of two-dimensional array accessible at the node specified by 'path' in the 'hdf5_file' hierarchical data format.
3.267903
3.285814
0.994549
slice_queue = multiprocessing.JoinableQueue() pid_list = [] for i in range(N_processes): worker = Availabilities_worker(hdf5_file, '/aff_prop_group', N_columns, damping, slice_queue, rows_sum) worker.daemon = True worker.start() pid_list.appe...
def compute_availabilities(hdf5_file, N_columns, damping, N_processes, rows_sum)
Coordinates the computation and update of the availability matrix for Affinity Propagation clustering. Parameters ---------- hdf5_file : string or file handle Specify access to the hierarchical data format used throughout all the iterations of message-passing between data-point...
3.649944
3.673585
0.993565
Worker.hdf5_lock.acquire() with tables.open_file(hdf5_file, 'r+') as fileh: A = fileh.root.aff_prop_group.availabilities R = fileh.root.aff_prop_group.responsibilities P = fileh.root.aff_prop_group.parallel_updates N = A.nrows diag_ind = np.diag_indice...
def check_convergence(hdf5_file, iteration, convergence_iter, max_iter)
If the estimated number of clusters has not changed for 'convergence_iter' consecutive iterations in a total of 'max_iter' rounds of message-passing, the procedure herewith returns 'True'. Otherwise, returns 'False'. Parameter 'iteration' identifies the run of message-passing t...
4.969406
4.989672
0.995938
with Worker.hdf5_lock: with tables.open_file(hdf5_file, 'r+') as fileh: S = fileh.root.aff_prop_group.similarities s = S[rows_slice, ...] s = np.argmax(s[:, I], axis = 1) with lock: c[rows_slice] = s[:] del s
def cluster_labels_A(hdf5_file, c, lock, I, rows_slice)
One of the task to be performed by a pool of subprocesses, as the first step in identifying the cluster labels and indices of the cluster centers for Affinity Propagation clustering.
7.687288
7.456984
1.030884
with Worker.hdf5_lock: with tables.open_file(hdf5_file, 'r+') as fileh: S = fileh.root.aff_prop_group.similarities s = S[rows_slice, ...] s = s[:, ii] s = s[iix[rows_slice]] with lock: s_reduced += s[:].sum(axis = 0) ...
def cluster_labels_B(hdf5_file, s_reduced, lock, I, ii, iix, rows_slice)
Second task to be performed by a pool of subprocesses before the cluster labels and cluster center indices can be identified.
7.243147
7.927268
0.9137
with Worker.hdf5_lock: with tables.open_file(hdf5_file, 'r+') as fileh: A = fileh.root.aff_prop_group.availabilities R = fileh.root.aff_prop_group.responsibilities N = A.nrows diag_ind = np.diag_indices(N) a = A[diag_ind] ...
def get_cluster_labels(hdf5_file, N_processes)
Returns ------- cluster_centers_indices : array of shape (n_clusters,) Indices of cluster centers labels : array of shape (n_samples,) Specify the label of the cluster to which each point has been assigned.
2.789983
2.809873
0.992921
here = os.getcwd() try: output_directory = os.path.join(here, 'concurrent_AP_output') os.makedirs(output_directory) except OSError: if not os.path.isdir(output_directory): print("ERROR: concurrent_AP: output_clusters: cannot create a directory " ...
def output_clusters(labels, cluster_centers_indices)
Write in tab-separated files the vectors of cluster identities and of indices of cluster centers.
2.746243
2.792058
0.983591
N_samples, N_features = data.shape rng = np.arange(0, N_samples, dtype = int) medians = [] for i in range(15): selected_samples = np.random.choice(N_samples, size = chunk_size, replace = False) samples = data[selected_samples, :] S = - euclidean_d...
def set_preference(data, chunk_size)
Return the median of the distribution of pairwise L2 Euclidean distances between samples (the rows of 'data') as the default preference parameter for Affinity Propagation clustering. Parameters ---------- data : array of shape (N_samples, N_features) The data-set submitted for Affi...
3.51882
2.980026
1.180802
return self._terms.getTerm(self._retina, term, getFingerprint, startIndex, maxResults)
def getTerms(self, term=None, getFingerprint=None, startIndex=0, maxResults=10)
Get term objects Args: term, str: A term in the retina (optional) getFingerprint, bool: Configure if the fingerprint should be returned as part of the results (optional) startIndex, int: The start-index for pagination (optional) maxResults, int: Max results per pa...
9.386055
8.461681
1.109242
return self._terms.getContextsForTerm(self._retina, term, getFingerprint, startIndex, maxResults)
def getContextsForTerm(self, term, getFingerprint=None, startIndex=0, maxResults=5)
Get the contexts for a given term Args: term, str: A term in the retina (required) getFingerprint, bool: Configure if the fingerprint should be returned as part of the results (optional) startIndex, int: The start-index for pagination (optional) maxResults, int: M...
7.124102
7.27245
0.979601
return self._terms.getSimilarTerms(self._retina, term, contextId, posType, getFingerprint, startIndex, maxResults)
def getSimilarTermsForTerm(self, term, contextId=None, posType=None, getFingerprint=None, startIndex=0, maxResults=10)
Get the similar terms of a given term Args: term, str: A term in the retina (required) contextId, int: The identifier of a context (optional) posType, str: Part of speech (optional) getFingerprint, bool: Configure if the fingerprint should be returned as part of t...
5.17096
4.937635
1.047254
return self._text.getTokensForText(self._retina, body, POStags)
def getTokensForText(self, body, POStags=None)
Get tokenized input text Args: body, str: The text to be tokenized (required) POStags, str: Specify desired POS types (optional) Returns: list of str Raises: CorticalioException: if the request was not successful
11.01147
14.47611
0.760665
return self._text.getSlicesForText(self._retina, body, getFingerprint, startIndex, maxResults)
def getSlicesForText(self, body, getFingerprint=None, startIndex=0, maxResults=10)
Get a list of slices of the text Args: body, str: The text to be evaluated (required) getFingerprint, bool: Configure if the fingerprint should be returned as part of the results (optional) startIndex, int: The start-index for pagination (optional) maxResults, int...
6.34283
10.309629
0.615234
body = [{"text": s} for s in strings] return self._text.getRepresentationsForBulkText(self._retina, json.dumps(body), sparsity)
def getFingerprintsForTexts(self, strings, sparsity=1.0)
Bulk get Fingerprint for text. Args: strings, list(str): A list of texts to be evaluated (required) sparsity, float: Sparsify the resulting expression to this percentage (optional) Returns: list of Fingerprint Raises: CorticalioException: if the re...
12.015514
13.807231
0.870233
return self._expressions.resolveExpression(self._retina, body, sparsity)
def getFingerprintForExpression(self, body, sparsity=1.0)
Resolve an expression Args: body, ExpressionOperation: The JSON encoded expression to be evaluated (required) sparsity, float: Sparsify the resulting expression to this percentage (optional) Returns: Fingerprint Raises: CorticalioException: if the ...
19.182676
22.72423
0.844151
return self._expressions.getContextsForExpression(self._retina, body, getFingerprint, startIndex, maxResults, sparsity)
def getContextsForExpression(self, body, getFingerprint=None, startIndex=0, maxResults=5, sparsity=1.0)
Get semantic contexts for the input expression Args: body, ExpressionOperation: The JSON encoded expression to be evaluated (required) getFingerprint, bool: Configure if the fingerprint should be returned as part of the results (optional) startIndex, int: The start-index for ...
4.941117
7.630217
0.647572
return self._expressions.getSimilarTermsForExpressionContext(self._retina, body, contextId, posType, getFingerprint, startIndex, maxResults, sparsity)
def getSimilarTermsForExpression(self, body, contextId=None, posType=None, getFingerprint=None, startIndex=0, maxResults=10, sparsity=1.0)
Get similar terms for the contexts of an expression Args: body, ExpressionOperation: The JSON encoded expression to be evaluated (required) contextId, int: The identifier of a context (optional) posType, str: Part of speech (optional) getFingerprint, bool: Configu...
4.875685
6.784864
0.718612
return self._expressions.resolveBulkExpression(self._retina, body, sparsity)
def getFingerprintsForExpressions(self, body, sparsity=1.0)
Bulk resolution of expressions Args: body, ExpressionOperation: The JSON encoded expression to be evaluated (required) sparsity, float: Sparsify the resulting expression to this percentage (optional) Returns: list of Fingerprint Raises: CorticalioE...
24.228891
26.536732
0.913032
return self._expressions.getContextsForBulkExpression(self._retina, body, getFingerprint, startIndex, maxResults, sparsity)
def getContextsForExpressions(self, body, getFingerprint=None, startIndex=0, maxResults=5, sparsity=1.0)
Bulk get contexts for input expressions Args: body, ExpressionOperation: The JSON encoded expression to be evaluated (required) getFingerprint, bool: Configure if the fingerprint should be returned as part of the results (optional) startIndex, int: The start-index for paginat...
7.716563
10.534874
0.732478
return self._expressions.getSimilarTermsForBulkExpressionContext(self._retina, body, contextId, posType, getFingerprint, startIndex, maxResults, sparsity)
def getSimilarTermsForExpressions(self, body, contextId=None, posType=None, getFingerprint=None, startIndex=0, maxResults=10, sparsity=1.0)
Bulk get similar terms for input expressions Args: body, ExpressionOperation: The JSON encoded expression to be evaluated (required) contextId, int: The identifier of a context (optional) posType, str: Part of speech (optional) getFingerprint, bool: Configure if t...
6.640415
8.899077
0.746191
return self._image.getImageForExpression(self._retina, body, imageScalar, plotShape, imageEncoding, sparsity)
def getImage(self, body, imageScalar=2, plotShape="circle", imageEncoding="base64/png", sparsity=1.0)
Get images for expressions Args: body, ExpressionOperation: The JSON encoded expression to be evaluated (required) imageScalar, int: The scale of the image (optional) plotShape, str: The image shape (optional) imageEncoding, str: The encoding of the returned image...
6.857286
9.686229
0.707942
return self._image.getOverlayImage(self._retina, body, plotShape, imageScalar, imageEncoding)
def compareImage(self, body, plotShape="circle", imageScalar=2, imageEncoding="base64/png")
Get an overlay image for two expressions Args: body, ExpressionOperation: The JSON encoded comparison array to be evaluated (required) plotShape, str: The image shape (optional) imageScalar, int: The scale of the image (optional) imageEncoding, str: The encoding o...
8.772525
13.041076
0.672684
return self._image.getImageForBulkExpressions(self._retina, body, getFingerprint, imageScalar, plotShape, sparsity)
def getImages(self, body, getFingerprint=None, imageScalar=2, plotShape="circle", sparsity=1.0)
Bulk get images for expressions Args: body, ExpressionOperation: The JSON encoded expression to be evaluated (required) getFingerprint, bool: Configure if the fingerprint should be returned as part of the results (optional) imageScalar, int: The scale of the image (optional) ...
10.709076
11.937513
0.897094
samples = {"positiveExamples": [{"text": s} for s in positiveExamples], "negativeExamples": [{"text": s} for s in negativeExamples]} body = json.dumps(samples) return self._classify.createCategoryFilter(self._retina, filterName, body)
def createCategoryFilter(self, filterName, positiveExamples, negativeExamples=[])
Get a classifier filter (fingerprint) for positive and negative text samples Args: filterName, str: A unique name for the filter. (required) positiveExamples, list(str): The list of positive example texts. (required) negativeExamples, list(str): The list of negative example t...
4.78581
4.6328
1.033028
resourcePath = '/terms/contexts' method = 'GET' queryParams = {} headerParams = {'Accept': 'Application/json', 'Content-Type': 'application/json'} postData = None queryParams['retina_name'] = retina_name queryParams['term'] = term queryParams['...
def getContextsForTerm(self, retina_name, term, get_fingerprint=None, start_index=0, max_results=5)
Get the contexts for a given term Args: retina_name, str: The retina name (required) term, str: A term in the retina (required) get_fingerprint, bool: Configure if the fingerprint should be returned as part of the results (optional) start_index, int: The start-ind...
2.319866
2.251559
1.030338
resourcePath = '/terms/similar_terms' method = 'GET' queryParams = {} headerParams = {'Accept': 'Application/json', 'Content-Type': 'application/json'} postData = None queryParams['retina_name'] = retina_name queryParams['term'] = term queryPar...
def getSimilarTerms(self, retina_name, term, context_id=None, pos_type=None, get_fingerprint=None, start_index=0, max_results=10)
Get the similar terms of a given term Args: retina_name, str: The retina name (required) term, str: A term in the retina (required) context_id, int: The identifier of a context (optional) (optional) pos_type, str: Part of speech (optional) (optional) g...
2.054404
2.023178
1.015435
resourcePath = '/classify/create_category_filter' method = 'POST' queryParams = {} headerParams = {'Accept': 'Application/json', 'Content-Type': 'application/json'} postData = None queryParams['retina_name'] = retina_name queryParams['filter_name'] = f...
def createCategoryFilter(self, retina_name, filter_name, body, )
get filter for classifier Args: filter_name, str: A unique name for the filter. (required) body, FilterTrainingObject: The list of positive and negative (optional) example items. (required) retina_name, str: The retina name (required) Returns: CategoryFilter
3.078962
2.982797
1.03224
resourcePath = '/image' method = 'POST' queryParams = {} headerParams = {'Accept': 'image/png', 'Content-Type': 'application/json'} postData = None queryParams['retina_name'] = retina_name queryParams['image_scalar'] = image_scalar queryParams[...
def getImageForExpression(self, retina_name, body, image_scalar=2, plot_shape="circle", image_encoding="base64/png", sparsity=1.0)
Get images for expressions Args: retina_name, str: The retina name (required) body, ExpressionOperation: The JSON encoded expression to be evaluated (required) image_scalar, int: The scale of the image (optional) (optional) plot_shape, str: The image shape (option...
2.045466
2.050973
0.997315
resourcePath = '/image/bulk' method = 'POST' queryParams = {} headerParams = {'Accept': 'Application/json', 'Content-Type': 'application/json'} postData = None queryParams['retina_name'] = retina_name queryParams['image_scalar'] = image_scalar ...
def getImageForBulkExpressions(self, retina_name, body, get_fingerprint=None, image_scalar=2, plot_shape="circle", sparsity=1.0)
Bulk get images for expressions Args: retina_name, str: The retina name (required) body, ExpressionOperation: The JSON encoded expression to be evaluated (required) get_fingerprint, bool: Configure if the fingerprint should be returned as part of the results (optional) ...
2.43447
2.263946
1.075322
resourcePath = '/text/keywords' method = 'POST' queryParams = {} headerParams = {'Accept': 'Application/json', 'Content-Type': 'application/json'} postData = None queryParams['retina_name'] = retina_name postData = body response = self.apiClien...
def getKeywordsForText(self, retina_name, body, )
Get a list of keywords from the text Args: retina_name, str: The retina name (required) body, str: The text to be evaluated (required) Returns: Array[str]
3.132985
2.798984
1.119329
resourcePath = '/text/slices' method = 'POST' queryParams = {} headerParams = {'Accept': 'Application/json', 'Content-Type': 'application/json'} postData = None queryParams['retina_name'] = retina_name queryParams['start_index'] = start_index q...
def getSlicesForText(self, retina_name, body, get_fingerprint=None, start_index=0, max_results=10)
Get a list of slices of the text Args: retina_name, str: The retina name (required) body, str: The text to be evaluated (required) get_fingerprint, bool: Configure if the fingerprint should be returned as part of the results (optional) start_index, int: The start-...
2.683858
2.424961
1.106763
resourcePath = '/text/detect_language' method = 'POST' queryParams = {} headerParams = {'Accept': 'Application/json', 'Content-Type': 'application/json'} postData = None postData = body response = self.apiClient._callAPI(resourcePath, method, queryPara...
def getLanguage(self, body, )
Detect the language of a text Args: body, str: Your input text (UTF-8) (required) Returns: LanguageRest
4.777243
3.639447
1.312629
# everything is display: map by default display_map = Declaration(Selector(SelectorElement(['*'], [])), Property('display'), Value('map', False), (False, (0, 0, 0), (0, 0))) declarations = [display_map] tokens = cssTokenizer().tokeni...
def stylesheet_declarations(string, is_merc=False, scale=1)
Parse a string representing a stylesheet into a list of declarations. Required boolean is_merc indicates whether the projection should be interpreted as spherical mercator, so we know what to do with zoom/scale-denominator in parse_rule().
7.61029
7.776343
0.978646
# # Local helper functions # def next_scalar(tokens, op): while True: tname, tvalue, line, col = tokens.next() if tname == 'NUMBER': try: value = int(tvalue) except ValueError: value = ...
def parse_attribute(tokens, is_merc)
Parse a token stream from inside an attribute selector. Enter this function after a left-bracket is found: http://www.w3.org/TR/CSS2/selector.html#attribute-selectors
2.299888
2.270415
1.012981
# convert single coins input to single element lists if not isinstance(coins, list) and coins != 'all': coins = [coins] # load data url = build_url('coinlist') data = load_data(url)['Data'] # coins specified if coins != 'all': data = {c: data[c] for c in coins} return data
def get_coin_list(coins='all')
Get general information about all the coins available on cryptocompare.com. Args: coins: Default value of 'all' returns information about all the coins available on the site. Otherwise a single string or list of coin symbols can be used. Returns: The function returns a dictionairy containing individua...
4.107813
3.699169
1.110469
# load data url = build_url('coinsnapshot', fsym=fsym, tsym=tsym) data = load_data(url)['Data'] return data
def get_coin_snapshot(fsym, tsym)
Get blockchain information, aggregated data as well as data for the individual exchanges available for the specified currency pair. Args: fsym: FROM symbol. tsym: TO symbol. Returns: The function returns a dictionairy containing blockain as well as trading information from the different exchanges were t...
4.545786
4.721524
0.962779
resourcePath = '/compare/bulk' method = 'POST' queryParams = {} headerParams = {'Accept': 'Application/json', 'Content-Type': 'application/json'} postData = None queryParams['retina_name'] = retina_name postData = body response = self.apiClient...
def compareBulk(self, retina_name, body)
Bulk compare Args: retina_name, str: The retina name (required) body, ExpressionOperation: Bulk comparison of elements 2 by 2 (required) Returns: Array[Metric]
3.613119
2.874599
1.256912
resourcePath = '/retinas' method = 'GET' queryParams = {} headerParams = {'Accept': 'Application/json', 'Content-Type': 'application/json'} postData = None queryParams['retina_name'] = retina_name response = self.apiClient._callAPI(resourcePath, method...
def getRetinas(self, retina_name=None)
Information about retinas Args: retina_name, str: The retina name (optional) (optional) Returns: Array[Retina]
3.178699
2.604014
1.220692
ids = sum(a.countIDs() for a in self.elements) non_ids = sum((a.countNames() - a.countIDs()) for a in self.elements) tests = sum(len(a.tests) for a in self.elements) return (ids, non_ids, tests)
def specificity(self)
Loosely based on http://www.w3.org/TR/REC-CSS2/cascade.html#specificity
4.825267
4.610443
1.046595
element = self.elements[0] unmatched_ids = [name[1:] for name in element.names if name.startswith('#')] unmatched_classes = [name[1:] for name in element.names if name.startswith('.')] unmatched_tags = [name for name in element.names if name is not '*' and not name.startswith('#...
def matches(self, tag, id, classes)
Given an id and a list of classes, return True if this selector would match.
2.141809
2.07976
1.029835
scaled = deepcopy(self) for test in scaled.elements[0].tests: if type(test.value) in (int, float): if test.property == 'scale-denominator': test.value /= scale elif test.property == 'zoom': test.value += lo...
def scaledBy(self, scale)
Return a new Selector with scale denominators scaled by a number.
6.222954
4.960624
1.25447
scaled = deepcopy(self) if type(scaled.value) in (int, float): scaled.value *= scale elif isinstance(scaled.value, numbers): scaled.value.values = tuple(v * scale for v in scaled.value.values) return scaled
def scaledBy(self, scale)
Return a new Value scaled by a given number for ints and floats.
4.864614
4.025999
1.2083
scheme, n, path, p, q, f = urlparse(src_file) if scheme in ('file', ''): assert exists(src_file), "We'd prefer an input file that exists to one that doesn't" if cache_dir is None: cache_dir = expanduser(CACHE_DIR) # only make the cache dir if it wasn't user-pr...
def load_map(map, src_file, output_dir, scale=1, cache_dir=None, datasources_cfg=None, user_styles=[], verbose=False)
Apply a stylesheet source file to a given mapnik Map instance, like mapnik.load_map(). Parameters: map: Instance of mapnik.Map. src_file: Location of stylesheet .mml file. Can be relative path, absolute path, or fully-qualified URL o...
5.567254
5.004792
1.112385
expression = self._createDictionary(textOrFingerprint) terms = self._fullClient.getSimilarTermsForExpression(json.dumps(expression), maxResults=20) return [t.term for t in terms]
def getSimilarTerms(self, textOrFingerprint)
Get the similar terms for a given text or fingerprint Args: textOrFingerprint, str OR list of integers Returns: list of str: the 20 most similar terms Raises: CorticalioException: if the request was not successful
8.633341
9.088037
0.949968
fp = self._fullClient.getFingerprintForText(text) return fp.positions
def getFingerprint(self, text)
Get the semantic fingerprint of the input text. Args: text, str: The text to be evaluated Returns: list of str: the positions of the semantic fingerprint Raises: CorticalioException: if the request was not successful
24.205334
19.467747
1.243356
compareList = [self._createDictionary(textOrFingerprint1), self._createDictionary(textOrFingerprint2)] metric = self._fullClient.compare(json.dumps(compareList)) return metric.cosineSimilarity
def compare(self, textOrFingerprint1, textOrFingerprint2)
Returns the semantic similarity of texts or fingerprints. Each argument can be eiter a text or a fingerprint. Args: textOrFingerprint1, str OR list of integers textOrFingerprint2, str OR list of integers Returns: float: the semantic similarity in the range [0;1] ...
7.936321
9.432999
0.841336
categoryFilter = self._fullClient.createCategoryFilter("CategoryFilter", positiveExamples) return categoryFilter.positions
def createCategoryFilter(self, positiveExamples)
Creates a filter fingerprint. Args: positiveExamples, list(str): The list of positive example texts. Returns: list of int: the positions representing the filter representing the texts Raises: CorticalioException: if the request was not successful
15.477695
12.744191
1.21449
# load data url = build_url('miningcontracts') data = load_data(url) coin_data = data['CoinData'] mining_data = data['MiningData'] return coin_data, mining_data
def get_mining_contracts()
Get all the mining contracts information available. Returns: This function returns two major dictionaries. The first one contains information about the coins for which mining contracts data is available: coin_data: {symbol1: {'BlockNumber': ..., 'BlockReward': ..., 'B...
4.477577
3.332374
1.34366
# load data url = build_url('miningequipment') data = load_data(url) coin_data = data['CoinData'] mining_data = data['MiningData'] return coin_data, mining_data
def get_mining_equipment()
Get all the mining equipment information available. Returns: This function returns two major dictionaries. The first one contains information about the coins for which mining equipment data is available. coin_data: {symbol1: {'BlockNumber': ..., 'BlockReward': ..., 'BlockRewardRe...
4.506059
3.946335
1.141834
if self._defaults: fp.write("[%s]\n" % ConfigParser.DEFAULTSECT) for (key, value) in sorted(self._defaults.items(), key=lambda x: x[0]): fp.write("%s = %s\n" % (key, str(value).replace('\n', '\n\t'))) fp.write("\n") for section in sorted(self....
def write(self, fp)
Write an .ini-format representation of the configuration state.
1.733313
1.616551
1.072229
mmap = mapnik.Map(1, 1) # allow [zoom] filters to work mmap.srs = '+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null' load_kwargs = dict([(k, v) for (k, v) in kwargs.items() if k in ('cache_dir', 'scale', 'verbose', 'datasources_cfg', 'user_styl...
def main(src_file, dest_file, **kwargs)
Given an input layers file and a directory, print the compiled XML file to stdout and save any encountered external image files to the named directory.
3.240754
3.254554
0.99576
resourcePath = '/expressions' method = 'POST' queryParams = {} headerParams = {'Accept': 'Application/json', 'Content-Type': 'application/json'} postData = None queryParams['retina_name'] = retina_name queryParams['sparsity'] = sparsity postDat...
def resolveExpression(self, retina_name, body, sparsity=1.0)
Resolve an expression Args: retina_name, str: The retina name (required) body, ExpressionOperation: The JSON formatted encoded to be evaluated (required) sparsity, float: Sparsify the resulting expression to this percentage (optional) Returns: Fingerprint
3.386975
2.82206
1.200178
resourcePath = '/expressions/contexts' method = 'POST' queryParams = {} headerParams = {'Accept': 'Application/json', 'Content-Type': 'application/json'} postData = None queryParams['retina_name'] = retina_name queryParams['start_index'] = start_index ...
def getContextsForExpression(self, retina_name, body, get_fingerprint=None, start_index=0, max_results=5, sparsity=1.0)
Get semantic contexts for the input expression Args: retina_name, str: The retina name (required) body, ExpressionOperation: The JSON encoded expression to be evaluated (required) get_fingerprint, bool: Configure if the fingerprint should be returned as part of the results (o...
2.582016
2.251799
1.146646
# load data url = build_url('exchanges', fsym=fsym, tsym=tsym, limit=limit) data = load_data(url) # price_data = data['Data'] # return [{'exchange': p['exchange'], # 'volume24hto': p['volume24hTo']} for p in price_data] return data['Data']
def get_top_exchanges(fsym, tsym, limit=5)
Get top exchanges by 24 hour trading volume for the currency pair. Args: fsym: FROM symbol. tsym: TO symbol. limit: Number of results. Default value returns top 5 exchanges. Returns: Function returns a list containing a dictionary for each result: [{'exchange': ..., 'fromSymbol': ..., 'toSymbole': ..., ...
4.060448
3.710705
1.094252
# load data url = build_url('volumes', tsym=tsym, limit=limit) data = load_data(url) return data['Data']
def get_top_coins(tsym, limit=20)
Get top coins by 24 hour trading volume value in the requested currency. Args: tsym: TO symbol. limit: Number of results. Default value returns top 20 coins. Returns: Function returns a list containing a dictionary for each result: [{'SUPPLY': ..., 'SYMBOL': ..., 'VOLUME24HOURTO': ...}, {...}, .....
5.94312
6.436819
0.923301
# load data url = build_url('pairs', fsym=fsym, limit=limit) data = load_data(url) return data['Data']
def get_top_pairs(fsym, limit=5)
Get top trading pairs by 24 hour aggregated volume for a currency. Args: fsym: FROM symbol. limit: Number of results. Default value returns top 5 pairs. Returns: Function returns a list containing a dictionary for each result: [{'exchange': ..., 'fromSymbol': ..., 'toSymbol': ..., 'volume24h': ..., ...
4.513932
5.572565
0.810028
for root, dirs, files in os.walk(base, topdown=False): for file in files: yield os.path.join(root, file)
def key(base)
get a list of all *leaf* directories as strings
2.162591
2.01196
1.074868
chunks = lambda l, n: [l[x: x+n] for x in xrange(0, len(l), n)] url_64 = base64.urlsafe_b64encode(url) return chunks(url_64, 255)
def chunk(url)
create filesystem-safe places for url-keyed data to be stored
2.895483
2.947075
0.982494
input = open(filename, 'r').read() declarations = cascadenik.stylesheet_declarations(input, is_merc=True) for dec in declarations: print dec.selector, print '{', print dec.property.name+':', if cascadenik.style.properties[dec.property.name] in (cascadenik.s...
def main(filename)
Given an input file containing nothing but styles, print out an unrolled list of declarations in cascade order.
2.945665
2.80162
1.051415
try: latitude, longitude, altitude = value.split(',') vol.Coerce(float)(latitude) vol.Coerce(float)(longitude) vol.Coerce(float)(altitude) except (TypeError, ValueError, vol.Invalid): raise vol.Invalid( 'GPS value should be of format "latitude,longitude,a...
def validate_gps(value)
Validate GPS value.
2.691507
2.571536
1.046654
if ((self.tcp_disconnect_timer + 2 * self.reconnect_timeout) < time.time()): self.tcp_disconnect_timer = time.time() raise OSError('No response from {}. Disconnecting'.format( self.server_address)) if (self.tcp_check_timer + self.reconnect...
def _check_connection(self)
Check if connection is alive every reconnect_timeout seconds.
5.792139
5.180855
1.117989
host, _ = self.server_address try: ip_address = ipaddress.ip_address(host) except ValueError: # Only hosts using ip address supports unique id. return None if ip_address.version == 6: mac = get_mac_address(ip6=host) else: ...
def get_gateway_id(self)
Return a unique id for the gateway.
5.063643
4.354948
1.162733
while self.protocol: _LOGGER.info('Trying to connect to %s', self.server_address) try: sock = socket.create_connection( self.server_address, self.reconnect_timeout) except socket.timeout: _LOGGER.error( ...
def _connect(self)
Connect to socket. This should be run in a new thread.
2.688432
2.559704
1.05029
try: while True: _LOGGER.info('Trying to connect to %s', self.server_address) try: yield from asyncio.wait_for( self.loop.create_connection( lambda: self.protocol, *self.server_address), ...
def _connect(self)
Connect to the socket.
2.191263
2.13109
1.028236
try: super()._check_connection() except OSError as exc: _LOGGER.error(exc) self.protocol.transport.close() self.protocol.conn_lost_callback() return task = self.loop.call_later( self.reconnect_timeout + 0.1, self._c...
def _check_connection(self)
Check if connection is alive every reconnect_timeout seconds.
4.600913
3.797071
1.2117
_LOGGER.debug('Connection lost with %s', self.transport) if self.gateway.cancel_check_conn: self.gateway.cancel_check_conn() self.gateway.cancel_check_conn = None if exc: _LOGGER.error(exc) self.conn_lost_callback() self.transport ...
def connection_lost(self, exc)
Handle lost connection.
3.879043
3.533487
1.097794
sock = self.sock available_socks = select.select([sock], [sock], [sock], timeout) if available_socks[2]: raise OSError return available_socks
def _check_socket(self, timeout=None)
Check if socket is readable/writable.
5.230528
4.725691
1.106828
# pylint: disable=broad-except self.protocol = self.protocol_factory() try: self.protocol.connection_made(self) except Exception as exc: self.alive = False self.protocol.connection_lost(exc) self._connection_made.set() ...
def run(self)
Transport thread loop.
3.005554
2.877508
1.044499
def decorator(func): self[name] = func return func return decorator
def register(self, name)
Return decorator to register item with a specific name.
7.709597
4.669106
1.651193
if not isinstance(topics, list): topics = [topics] for topic in topics: topic_levels = topic.split('/') try: qos = int(topic_levels[-2]) except ValueError: qos = 0 try: _LOGGER.debug('Sub...
def _handle_subscription(self, topics)
Handle subscription of topics.
2.729956
2.567139
1.063424
_LOGGER.info('Setting up initial MQTT topic subscription') init_topics = [ '{}/+/+/0/+/+'.format(self._in_prefix), '{}/+/+/3/+/+'.format(self._in_prefix), ] self._handle_subscription(init_topics) if not self.persistence: return ...
def _init_topics(self)
Set up initial subscription of mysensors topics.
3.513595
3.207975
1.095269
topic_levels = topic.split('/') topic_levels = not_prefix = topic_levels[-5:] prefix_end_idx = topic.find('/'.join(not_prefix)) - 1 prefix = topic[:prefix_end_idx] if prefix != self._in_prefix: return None if qos and qos > 0: ack = '1' ...
def _parse_mqtt_to_message(self, topic, payload, qos)
Parse a MQTT topic and payload. Return a mysensors command string.
4.301419
4.242954
1.013779
msg = Message(data, self) payload = str(msg.payload) msg.payload = '' # prefix/node/child/type/ack/subtype : payload return ('{}/{}'.format(self._out_prefix, msg.encode('/'))[:-2], payload, msg.ack)
def _parse_message_to_mqtt(self, data)
Parse a mysensors command string. Return a MQTT topic, payload and qos-level as a tuple.
16.425922
15.818953
1.03837
ret_msg = handle_presentation(msg) if msg.child_id == 255 or ret_msg is None: return # this is a presentation of a child sensor topics = [ '{}/{}/{}/{}/+/+'.format( self._in_prefix, str(msg.node_id), str(msg.child_id), msg_...
def _handle_presentation(self, msg)
Process a MQTT presentation message.
4.996714
4.808559
1.039129
data = self._parse_mqtt_to_message(topic, payload, qos) if data is None: return _LOGGER.debug('Receiving %s', data) self.add_job(self.logic, data)
def recv(self, topic, payload, qos)
Receive a MQTT message. Call this method when a message is received from the MQTT broker.
5.57355
5.748717
0.969529
if not message: return topic, payload, qos = self._parse_message_to_mqtt(message) try: _LOGGER.debug('Publishing %s', message.strip()) self._pub_callback(topic, payload, qos, self._retain) except Exception as exception: # pylint: disable=broa...
def send(self, message)
Publish a command string to the gateway via MQTT.
3.725686
3.541003
1.052155
self._init_topics() poll_thread = threading.Thread(target=self._poll_queue) poll_thread.start()
def start(self)
Start the connection to a transport.
5.575982
5.722237
0.974441
super(RegexField, self).contribute_to_class(cls, name, virtual_only) setattr(cls, name, CastOnAssignDescriptor(self))
def contribute_to_class(self, cls, name, virtual_only=False)
Cast to the correct value every
5.842377
6.356836
0.91907
if isinstance(value, type(re.compile(''))): return value else: if value is None and self.null: return None else: try: return self.get_compiled_regex(value) except: raise V...
def to_python(self, value)
Handles the following cases: 1. If the value is already the proper type (a regex), return it. 2. If the value is a string, compile and return the regex. Raises: A ValidationError if the regex cannot be compiled.
3.661185
3.307702
1.106866