code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
'''asset_update asset_id, [name], [description], [visibility], [group], [users], [ips], [rules], [dns] The Asset Update function will update the Asset ID defined with the values that have been specified. Only those specified will be updated as a query is first ma...
def asset_update(self, asset_id, name=None, description=None, visibility=None, group=None, users=None, ips=None, rules=None, dns=None)
asset_update asset_id, [name], [description], [visibility], [group], [users], [ips], [rules], [dns] The Asset Update function will update the Asset ID defined with the values that have been specified. Only those specified will be updated as a query is first made to pre-p...
3.002275
2.358991
1.272694
payload = None # First we pull the credentials and populate the payload if we # find a match. for cred in self.credentials()['credentials']: if cred['id'] == str(cred_id): payload = { 'id': cred_id, 'type': cre...
def credential_update(self, cred_id, **options)
credential_update cred_id **options Updates the specified values of the credential ID specified.
2.51212
2.510911
1.000482
return self.raw_query("credential", "shareSimulate", data={ 'id': cred_id, 'users': [{'id': i} for i in user_ids], })
def credential_share_simulate(self, cred_id, *user_ids)
Shares a given credential to the specified Users. :param cred_id: Credential ID :param user_ids: List of User IDs
4.766842
5.601022
0.851066
return self.raw_query("credential", "share", data={ 'id': cred_id, 'users': [{'id': i} for i in user_ids], })
def credential_share(self, cred_id, *user_ids)
Shares a given credential to the specified Users. :param cred_id: Credential ID :param user_ids: List of User IDs
4.560775
5.357948
0.851217
return self.raw_query("credential", "deleteSimulate", data={ "credentials": [{"id": str(id)} for id in ids] })
def credential_delete_simulate(self, *ids)
Show the relationships and dependencies for one or more credentials. :param ids: one or more credential ids
5.838868
8.163041
0.715281
return self.raw_query("credential", "delete", data={ "credentials": [{"id": str(id)} for id in ids] })
def credential_delete(self, *ids)
Delete one or more credentials. :param ids: one or more credential ids
5.409771
7.144069
0.757239
plugins = [] # First we need to generate the basic payload that we will be augmenting # to build the payload = { 'size': size, 'offset': offset, 'type': plugin_type, 'sortField': sort, 'sortDirection': direction.upper(...
def plugins(self, plugin_type='all', sort='id', direction='asc', size=1000, offset=0, all=True, loops=0, since=None, **filterset)
plugins Returns a list of of the plugins and their associated families. For simplicity purposes, the plugin family names will be injected into the plugin data so that only 1 list is returned back with all of the information.
5.592664
5.411057
1.033562
ret = { 'total': 0, } # As ususal, we need data before we can actually do anything ;) data = self.raw_query('plugin', 'init') # For backwards compatability purposes, we will be handling this a bit # differently than I would like. We are going to ch...
def plugin_counts(self)
plugin_counts Returns the plugin counts as dictionary with the last updated info if its available.
8.159441
7.87729
1.035818
if not repository_ids: repository_ids = [] repos = [] for rid in repository_ids: repos.append({'id': rid}) return self.raw_query('vuln', 'getIP', data={ 'ip': ip, 'repositories': repos})
def ip_info(self, ip, repository_ids=None)
ip_info Returns information about the IP specified in the repository ids defined.
4.365223
4.307892
1.013308
try: end_time = datetime.utcfromtimestamp(int(end_time)) except TypeError: if end_time is None: end_time = datetime.utcnow() try: start_time = datetime.utcfromtimestamp(int(start_time)) except TypeError: if start_...
def scan_list(self, start_time=None, end_time=None, **kwargs)
List scans stored in Security Center in a given time range. Time is given in UNIX timestamps, assumed to be UTC. If a `datetime` is passed it is converted. If `end_time` is not specified it is NOW. If `start_time` is not specified it is 30 days previous from `end_time`. :param start_ti...
2.235437
2.211018
1.011044
payload = { 'downloadType': format, 'scanResultID': scan_id, } data = self.raw_query('scanResult', 'download', data=payload, dejson=False) bobj = StringIO() bobj.write(data) zfile = ZipFile(bobj) return zfile.read(zfile.namelist()[...
def scan_download(self, scan_id, format='v2')
scan_download scan_id [format] Will download an individual scan and return a string with the results.
4.265907
4.231307
1.008177
data = self._upload(fileobj) return self.raw_query('dashboard', 'importTab', data={ 'filename': data['filename'], 'name': name, })
def dashboard_import(self, name, fileobj)
dashboard_import Dashboard_Name, filename Uploads a dashboard template to the current user's dashboard tabs. UN-DOCUMENTED CALL: This function is not considered stable.
7.516056
7.317077
1.027194
data = self._upload(filename) return self.raw_query('report', 'import', data={ 'filename': data['filename'], 'name': name, })
def report_import(self, name, filename)
report_import Report_Name, filename Uploads a report template to the current user's reports UN-DOCUMENTED CALL: This function is not considered stable.
6.682604
6.333813
1.055068
'''asset_create_static name, ips, tags, description Create a new asset list with the defined information. UN-DOCUMENTED CALL: This function is not considered stable. :param name: asset list name (must be unique) :type name: string :param items: list of IP Addresses, CID...
def asset_create(self, name, items, tag='', description='', atype='static')
asset_create_static name, ips, tags, description Create a new asset list with the defined information. UN-DOCUMENTED CALL: This function is not considered stable. :param name: asset list name (must be unique) :type name: string :param items: list of IP Addresses, CIDR, and Netw...
4.486038
1.950809
2.299579
'''asset_create_combo name, combination, tag, description Creates a new combination asset list. Operands can be either asset list IDs or be a nested combination asset list. UN-DOCUMENTED CALL: This function is not considered stable. AND = intersection OR = union ...
def asset_create_combo(self, name, combo, tag='', description='')
asset_create_combo name, combination, tag, description Creates a new combination asset list. Operands can be either asset list IDs or be a nested combination asset list. UN-DOCUMENTED CALL: This function is not considered stable. AND = intersection OR = union operand =...
5.522228
1.430378
3.860676
'''accept_risk rule_type, rule_value, port, proto, plugin_id, comment Creates an accept rick rule based on information provided. UN-DOCUMENTED CALL: This function is not considered stable. :param rule_type: Valid options: ip, asset, all. :type rule_type: string :param r...
def risk_rule(self, rule_type, rule_value, port, proto, plugin_id, repo_ids, comment='', expires='-1', severity=None)
accept_risk rule_type, rule_value, port, proto, plugin_id, comment Creates an accept rick rule based on information provided. UN-DOCUMENTED CALL: This function is not considered stable. :param rule_type: Valid options: ip, asset, all. :type rule_type: string :param rule_value: ...
3.785307
1.656439
2.285207
'''group_add name, restrict, repos ''' return self.raw_query('group', 'add', data={ 'lces': [{'id': i} for i in lces], 'assets': [{'id': i} for i in assets], 'queries': [{'id': i} for i in queries], 'policies': [{'id': i} for i in policies], ...
def group_add(self, name, restrict, repos, lces=[], assets=[], queries=[], policies=[], dashboards=[], credentials=[], description='')
group_add name, restrict, repos
2.659039
2.580314
1.03051
''' Gets information from a Raster data set ''' sourceds = gdal.Open(filename, GA_ReadOnly) ndv = sourceds.GetRasterBand(band).GetNoDataValue() xsize = sourceds.RasterXSize ysize = sourceds.RasterYSize geot = sourceds.GetGeoTransform() projection = osr.SpatialReference() projection.I...
def get_geo_info(filename, band=1)
Gets information from a Raster data set
2.292861
2.10814
1.087623
''' Usage: map_pixel(xcoord, ycoord, x_cell_size, y_cell_size, xmin, ymax) where: xmin is leftmost X coordinate in system ymax is topmost Y coordinate in system Example: raster = HMISea.tif ndv, xsize, ysize, geot, projection, datatype = get_geo_info(r...
def map_pixel(point_x, point_y, cellx, celly, xmin, ymax)
Usage: map_pixel(xcoord, ycoord, x_cell_size, y_cell_size, xmin, ymax) where: xmin is leftmost X coordinate in system ymax is topmost Y coordinate in system Example: raster = HMISea.tif ndv, xsize, ysize, geot, projection, datatype = get_geo_info(raster) ...
4.075919
1.411993
2.886642
''' Usage: map_pixel(xcoord, ycoord, x_cell_size, y_cell_size, xmin, ymax) where: xmin is leftmost X coordinate in system ymax is topmost Y coordinate in system Example: raster = HMISea.tif ndv, xsize, ysize, geot, projection, datatype = get_g...
def map_pixel_inv(row, col, cellx, celly, xmin, ymax)
Usage: map_pixel(xcoord, ycoord, x_cell_size, y_cell_size, xmin, ymax) where: xmin is leftmost X coordinate in system ymax is topmost Y coordinate in system Example: raster = HMISea.tif ndv, xsize, ysize, geot, projection, datatype = get_geo_info(rast...
5.629875
1.59205
3.536243
''' Aggregate raster to smaller resolution, by adding cells. Usage: aggregate(raster, ndv, block_size) where: raster is a Numpy array created by importing the raster (e.g. geotiff) ndv is the NoData Value for the raster (can be read using the get_geo_info function) ...
def aggregate(raster, ndv, block_size)
Aggregate raster to smaller resolution, by adding cells. Usage: aggregate(raster, ndv, block_size) where: raster is a Numpy array created by importing the raster (e.g. geotiff) ndv is the NoData Value for the raster (can be read using the get_geo_info function) ...
7.861408
1.451011
5.417881
''' Creates new geotiff from array ''' if isinstance(datatype, np.int) == False: if datatype.startswith('gdal.GDT_') == False: datatype = eval('gdal.GDT_'+datatype) newfilename = name+'.tif' # Set nans to the original No Data Value Array[np.isnan(Array)] = ndv # Set u...
def create_geotiff(name, Array, driver, ndv, xsize, ysize, geot, projection, datatype, band=1)
Creates new geotiff from array
3.292642
3.102403
1.06132
ndv, xsize, ysize, geot, projection, datatype = get_geo_info(file) data = gdalnumeric.LoadFile(file) data = np.ma.masked_array(data, mask=data == ndv, fill_value=ndv) return data
def load_tiff(file)
Load a geotiff raster keeping ndv values using a masked array Usage: data = load_tiff(file)
3.572482
3.238532
1.103118
if sum([rasters[0].x_cell_size == i.x_cell_size for i in rasters]) == len(rasters) \ and sum([rasters[0].y_cell_size == i.y_cell_size for i in rasters]) == len(rasters)\ and sum([rasters[0].projection.ExportToProj4() == i.projection.ExportToProj4() for i in rasters]) == len(rasters): if s...
def union(rasters)
Union of rasters Usage: union(rasters) where: rasters is a list of GeoRaster objects
1.986055
2.031217
0.977766
ndv, xsize, ysize, geot, projection, datatype = get_geo_info(filename, **kwargs) data = gdalnumeric.LoadFile(filename, **kwargs) data = np.ma.masked_array(data, mask=data == ndv, fill_value=ndv) return GeoRaster(data, geot, nodata_value=ndv, projection=projection, datatype=datatype)
def from_file(filename, **kwargs)
Create a GeoRaster object from a file
3.399883
2.815855
1.207407
if not cellx: cellx = (df.sort_values(x)[x]-df.sort_values(x).shift(1)[x]).max() if not celly: celly = (df.sort_values(y, ascending=False)[y]-df.sort_values(y, ascending=False).shift(1)[y]).drop_duplicates().replace(0).max() if not xmin: xmin = df[x].min() if not ymax: ...
def from_pandas(df, value='value', x='x', y='y', cellx=None, celly=None, xmin=None, ymax=None, geot=None, nodata_value=None, projection=None, datatype=None)
Creates a GeoRaster from a Pandas DataFrame. Useful to plot or export data to rasters. Usage: raster = from_pandas(df, value='value', x='x', y='y', cellx= cellx, celly=celly, xmin=xmin, ymax=ymax, geot=geot, nodata_value=ndv, projection=projection, d...
2.268941
2.249628
1.008585
df = pd.DataFrame(raster.raster) df = df.stack() df = df.reset_index() df.columns = ['row', 'col', name] df['x'] = df.col.apply(lambda col: raster.geot[0]+(col)*raster.geot[1]) df['y'] = df.row.apply(lambda row: raster.geot[3]+(row)*raster.geot[-1]) return df
def to_pandas(raster, name='value')
Convert GeoRaster to Pandas DataFrame, which can be easily exported to other types of files The DataFrame has the row, col, value, x, and y values for each cell Usage: df = gr.to_pandas(raster)
2.442166
2.370112
1.030401
df = to_pandas(raster, **kwargs) df['geometry'] = df.apply(squares, georaster=raster, axis=1) df = gp.GeoDataFrame(df, crs=from_string(raster.projection.ExportToProj4())) return df
def to_geopandas(raster, **kwargs)
Convert GeoRaster to GeoPandas DataFrame, which can be easily exported to other types of files and used to do other types of operations. The DataFrame has the geometry (Polygon), row, col, value, x, and y values for each cell Usage: df = gr.to_geopandas(raster)
4.985898
5.582498
0.89313
rasterf = raster.flatten() if len(raster.shape) == 1: shape = (np.sqrt(raster.shape[0]) * np.array([1,1])).astype(int) else: shape = raster.shape w = pysal.lat2W(*shape, rook=rook, **kwargs) # Identify missing/no data if isinstance(rasterf, np.ma.core.MaskedArray): ...
def raster_weights(raster, rook=False, transform='r', **kwargs)
Construct PySal weights for rasters It drops weights for all cells that have no data or are Inf/NaN Usage: w = raster_weights(raster, rook=False, transform='r', **kwargs) where raster: (Masked) Numpy array for which weights are to be constructed rook: Boolean, type of contiguity. Defau...
3.377943
3.237952
1.043235
y = raster.copy() y.raster[y.raster.mask == False] = x return y
def map_vector(x, raster, **kvars)
Create new GeoRaster, which has its data replaced by x Useful to map output of PySal analyses, e.g. spatial autocorrelation values, etc. Usage: raster2 = map_vector(x, raster) where raster: GeoRaster x: Numpy array of data with same length as non-missing values in raster, i.e., l...
6.775486
7.787811
0.870012
return GeoRaster(self.raster.copy(), self.geot, nodata_value=self.nodata_value, projection=self.projection, datatype=self.datatype)
def copy(self)
Returns copy of itself
5.829851
5.442168
1.071237
''' geo.to_tiff(filename) Saves GeoRaster as geotiff filename.tif with type datatype If GeoRaster does not have datatype, then it tries to assign a type. You can assign the type yourself by setting geo.datatype = 'gdal.GDT_'+type ''' if self.datatype is...
def to_tiff(self, filename)
geo.to_tiff(filename) Saves GeoRaster as geotiff filename.tif with type datatype If GeoRaster does not have datatype, then it tries to assign a type. You can assign the type yourself by setting geo.datatype = 'gdal.GDT_'+type
3.50483
1.969886
1.779204
''' geo.plot() Returns plot of raster data ''' if ax is None: fig, ax = plt.subplots(figsize=figsize) ax.set_aspect('equal') ax.matshow(self.raster, **kwargs) plt.draw() return ax
def plot(self, figsize=None, ax=None, **kwargs)
geo.plot() Returns plot of raster data
4.798753
2.974676
1.613202
''' geo.median(axis=None, out=None, overwrite_input=False) axis : int, optional Axis along which the medians are computed. The default (axis=None) is to compute the median along a flattened version of the array. out : ndarray, optional Alternative out...
def median(self, *args, **kwargs)
geo.median(axis=None, out=None, overwrite_input=False) axis : int, optional Axis along which the medians are computed. The default (axis=None) is to compute the median along a flattened version of the array. out : ndarray, optional Alternative output array in which t...
3.426501
1.245567
2.750957
''' Clip raster using shape, where shape is either a GeoPandas DataFrame, shapefile, or some other geometry format used by python-raster-stats Returns list of GeoRasters or Pandas DataFrame with GeoRasters and additional information Usage: clipped = geo.clip(shape, kee...
def clip(self, shp, keep=False, *args, **kwargs)
Clip raster using shape, where shape is either a GeoPandas DataFrame, shapefile, or some other geometry format used by python-raster-stats Returns list of GeoRasters or Pandas DataFrame with GeoRasters and additional information Usage: clipped = geo.clip(shape, keep=False) wh...
3.891572
2.302092
1.69045
''' Compute raster statistics for a given geometry in shape, where shape is either a GeoPandas DataFrame, shapefile, or some other geometry format used by python-raster-stats. Runs python-raster-stats in background (additional help and info can be found there) Returns da...
def stats(self, shp, stats='mean', add_stats=None, raster_out=True, *args, **kwargs)
Compute raster statistics for a given geometry in shape, where shape is either a GeoPandas DataFrame, shapefile, or some other geometry format used by python-raster-stats. Runs python-raster-stats in background (additional help and info can be found there) Returns dataframe with statist...
4.723115
2.446035
1.930927
if self.count()>1: xsort = sorted(self.raster.data[self.raster.mask == False].flatten()) # increasing order y = np.cumsum(xsort) B = sum(y) / (y[-1] * len(xsort)) return 1 + 1./len(xsort) - 2*B else: return 1
def gini(self)
geo.gini() Return computed Gini coefficient.
6.199479
5.951502
1.041666
''' geo.apply(func, *args, **kwargs) Returns the value of applying function func on the raster data func: Python function *args: Arguments of function **kwargs: Additional arguments of function ''' return func(self.raster, *args, **kwargs)
def apply(self, func, *args, **kwargs)
geo.apply(func, *args, **kwargs) Returns the value of applying function func on the raster data func: Python function *args: Arguments of function **kwargs: Additional arguments of function
7.113945
2.19488
3.241155
''' geo.map_pixel(point_x, point_y) Return value of raster in location Note: (point_x, point_y) must belong to the geographic coordinate system and the coverage of the raster ''' row, col = map_pixel(point_x, point_y, self.x_cell_size...
def map_pixel(self, point_x, point_y)
geo.map_pixel(point_x, point_y) Return value of raster in location Note: (point_x, point_y) must belong to the geographic coordinate system and the coverage of the raster
6.241649
2.976285
2.097128
''' geo.map_pixel(point_x, point_y) Return value of raster in location ''' row, col = map_pixel(point_x, point_y, self.x_cell_size, self.y_cell_size, self.xmin, self.ymax) return np.array([row, col])
def map_pixel_location(self, point_x, point_y)
geo.map_pixel(point_x, point_y) Return value of raster in location
5.846416
3.297071
1.773215
''' geo.extract(x, y, radius=r) Return subraster of raster geo around location (x,y) with radius r where (x,y) and r are in the same coordinate system as geo ''' row, col = map_pixel(point_x, point_y, self.x_cell_size, self.y_cell_size, self....
def extract(self, point_x, point_y, radius=0)
geo.extract(x, y, radius=r) Return subraster of raster geo around location (x,y) with radius r where (x,y) and r are in the same coordinate system as geo
3.749619
2.366749
1.584291
''' geo.align(geo2, how=np.mean) Returns both georasters aligned and with the same pixelsize ''' return align_georasters(self, alignraster, how=how, cxsize=cxsize, cysize=cysize)
def align(self, alignraster, how=np.mean, cxsize=None, cysize=None)
geo.align(geo2, how=np.mean) Returns both georasters aligned and with the same pixelsize
6.639177
2.893231
2.294728
''' geo.aggregate(block_size) Returns copy of raster aggregated to smaller resolution, by adding cells. ''' raster2 = block_reduce(self.raster, block_size, func=np.ma.sum) geot = self.geot geot = (geot[0], block_size[0] * geot[1], geot[2], geot[3], geot[4], ...
def aggregate(self, block_size)
geo.aggregate(block_size) Returns copy of raster aggregated to smaller resolution, by adding cells.
4.724781
2.87993
1.640589
''' geo.block_reduce(block_size, how=func) Returns copy of raster aggregated to smaller resolution, by adding cells. Default: func=np.ma.mean ''' raster2 = block_reduce(self.raster, block_size, func=how) geot = self.geot geot = (geot[0], block_size[0] * g...
def block_reduce(self, block_size, how=np.ma.mean)
geo.block_reduce(block_size, how=func) Returns copy of raster aggregated to smaller resolution, by adding cells. Default: func=np.ma.mean
4.850006
2.552854
1.899837
''' geo.resize(new_shape, order=0, mode='constant', cval=np.nan, preserve_range=True) Returns resized georaster ''' if not cval: cval = np.nan raster2 = resize(self.raster.data, block_size, order=order, mode=mode, cval=cval, preserve_...
def resize(self, block_size, order=0, mode='constant', cval=False, preserve_range=True)
geo.resize(new_shape, order=0, mode='constant', cval=np.nan, preserve_range=True) Returns resized georaster
2.860151
2.517956
1.135902
''' geo.resize(new_shape, order=0, mode='constant', cval=np.nan, preserve_range=True) Returns resized georaster ''' if not cval: cval = np.nan if (self.raster.dtype.name.find('float') != -1 and np.max(np.abs([self.max(), self.min()])) > 1): ...
def resize_old(self, block_size, order=0, mode='constant', cval=False)
geo.resize(new_shape, order=0, mode='constant', cval=np.nan, preserve_range=True) Returns resized georaster
2.741434
2.438435
1.124259
if self.weights is None: self.weights = raster_weights(self.raster, **kwargs) pass
def raster_weights(self, **kwargs)
Compute neighbor weights for GeoRaster. See help(gr.raster_weights) for options Usage: geo.raster_weights(rook=True)
5.218822
5.650836
0.923549
if self.weights is None: self.raster_weights(**kwargs) rasterf = self.raster.flatten() rasterf = rasterf[rasterf.mask==False] self.G = pysal.G(rasterf, self.weights, **kwargs)
def pysal_G(self, **kwargs)
Compute Getis and Ord’s G for GeoRaster Usage: geo.pysal_G(permutations = 1000, rook=True) arguments passed to raster_weights() and pysal.G See help(gr.raster_weights), help(pysal.G) for options
5.003106
4.127388
1.212172
if self.weights is None: self.raster_weights(**kwargs) rasterf = self.raster.flatten() rasterf = rasterf[rasterf.mask==False] self.Gamma = pysal.Gamma(rasterf, self.weights, **kwargs)
def pysal_Gamma(self, **kwargs)
Compute Gamma Index of Spatial Autocorrelation for GeoRaster Usage: geo.pysal_Gamma(permutations = 1000, rook=True, operation='c') arguments passed to raster_weights() and pysal.Gamma See help(gr.raster_weights), help(pysal.Gamma) for options
5.144052
4.257839
1.208137
if self.weights is None: self.raster_weights(**kwargs) rasterf = self.raster.flatten() rasterf = rasterf[rasterf.mask==False] self.Join_Counts = pysal.Join_Counts(rasterf, self.weights, **kwargs)
def pysal_Join_Counts(self, **kwargs)
Compute join count statistics for GeoRaster Usage: geo.pysal_Join_Counts(permutations = 1000, rook=True) arguments passed to raster_weights() and pysal.Join_Counts See help(gr.raster_weights), help(pysal.Join_Counts) for options
4.886645
3.966851
1.23187
if self.weights is None: self.raster_weights(**kwargs) rasterf = self.raster.flatten() rasterf = rasterf[rasterf.mask==False] self.Moran = pysal.Moran(rasterf, self.weights, **kwargs)
def pysal_Moran(self, **kwargs)
Compute Moran's I measure of global spatial autocorrelation for GeoRaster Usage: geo.pysal_Moran(permutations = 1000, rook=True) arguments passed to raster_weights() and pysal.Moran See help(gr.raster_weights), help(pysal.Moran) for options
4.388669
3.925318
1.118042
if self.weights is None: self.raster_weights(**kwargs) rasterf = self.raster.flatten() rasterf = rasterf[rasterf.mask==False] self.Geary = pysal.Geary(rasterf, self.weights, **kwargs)
def pysal_Geary(self, **kwargs)
Compute Geary’s C for GeoRaster Usage: geo.pysal_C(permutations = 1000, rook=True) arguments passed to raster_weights() and pysal.Geary See help(gr.raster_weights), help(pysal.Geary) for options
4.682378
4.376385
1.069919
if self.weights is None: self.raster_weights(**kwargs) rasterf = self.raster.flatten() rasterf = rasterf[rasterf.mask==False] self.Moran_Local = pysal.Moran_Local(rasterf, self.weights, **kwargs) for i in self.Moran_Local.__dict__.keys(): if (isin...
def pysal_Moran_Local(self, **kwargs)
Compute Local Moran's I measure of local spatial autocorrelation for GeoRaster Usage: geo.pysal_Moran_Local(permutations = 1000, rook=True) arguments passed to raster_weights() and pysal.Moran_Local See help(gr.raster_weights), help(pysal.Moran_Local) for options
2.757798
2.707042
1.01875
# Create Cost surface to work on self.mcp_cost = graph.MCP_Geometric(self.raster, *args, **kwargs)
def mcp(self, *args, **kwargs)
Setup MCP_Geometric object from skimage for optimal travel time computations
21.182665
12.017354
1.762673
log.debug('Sending notification: %s %s', method, params) message = { 'jsonrpc': JSONRPC_VERSION, 'method': method, } if params is not None: message['params'] = params self._consumer(message)
def notify(self, method, params=None)
Send a JSON RPC notification to the client. Args: method (str): The method name of the notification to send params (any): The payload of the notification
3.427401
3.585013
0.956036
msg_id = self._id_generator() log.debug('Sending request with id %s: %s %s', msg_id, method, params) message = { 'jsonrpc': JSONRPC_VERSION, 'id': msg_id, 'method': method, } if params is not None: message['params'] = para...
def request(self, method, params=None)
Send a JSON RPC request to the client. Args: method (str): The method name of the message to send params (any): The payload of the message Returns: Future that will resolve once a response has been received
2.696833
2.775128
0.971787
def callback(future): if future.cancelled(): self.notify(CANCEL_METHOD, {'id': request_id}) future.set_exception(JsonRpcRequestCancelled()) return callback
def _cancel_callback(self, request_id)
Construct a cancellation callback for the given request ID.
7.827446
7.37085
1.061946
if 'jsonrpc' not in message or message['jsonrpc'] != JSONRPC_VERSION: log.warn("Unknown message type %s", message) return if 'id' not in message: log.debug("Handling notification from client %s", message) self._handle_notification(message['method...
def consume(self, message)
Consume a JSON RPC message from the client. Args: message (dict): The JSON RPC message sent by the client
2.055426
2.063488
0.996093
if method == CANCEL_METHOD: self._handle_cancel_notification(params['id']) return try: handler = self._dispatcher[method] except KeyError: log.warn("Ignoring notification for unknown method %s", method) return try: ...
def _handle_notification(self, method, params)
Handle a notification from the client.
2.75648
2.700122
1.020872
def callback(future): try: future.result() log.debug("Successfully handled async notification %s %s", method, params) except Exception: # pylint: disable=broad-except log.exception("Failed to handle async notification %s %s", meth...
def _notification_callback(method, params)
Construct a notification callback for the given request ID.
3.156833
3.196158
0.987696
request_future = self._client_request_futures.pop(msg_id, None) if not request_future: log.warn("Received cancel notification for unknown message id %s", msg_id) return # Will only work if the request hasn't started executing if request_future.cancel():...
def _handle_cancel_notification(self, msg_id)
Handle a cancel notification from the client.
3.805654
3.520723
1.08093
try: handler = self._dispatcher[method] except KeyError: raise JsonRpcMethodNotFound.of(method) handler_result = handler(params) if callable(handler_result): log.debug("Executing async request handler %s", handler_result) request...
def _handle_request(self, msg_id, method, params)
Handle a request from the client.
3.040927
2.978419
1.020987
def callback(future): # Remove the future from the client requests map self._client_request_futures.pop(request_id, None) if future.cancelled(): future.set_exception(JsonRpcRequestCancelled()) message = { 'jsonrpc': JSONR...
def _request_callback(self, request_id)
Construct a request callback for the given request ID.
2.881747
2.82905
1.018627
request_future = self._server_request_futures.pop(msg_id, None) if not request_future: log.warn("Received response to unknown message id %s", msg_id) return if error is not None: log.debug("Received error response to message %s: %s", msg_id, error) ...
def _handle_response(self, msg_id, result=None, error=None)
Handle a response from the client.
2.285557
2.211781
1.033356
while not self._rfile.closed: request_str = self._read_message() if request_str is None: break try: message_consumer(json.loads(request_str.decode('utf-8'))) except ValueError: log.exception("Failed to par...
def listen(self, message_consumer)
Blocking call to listen for messages on the rfile. Args: message_consumer (fn): function that is passed each message as it is read off the socket.
3.791685
3.557689
1.065772
line = self._rfile.readline() if not line: return None content_length = self._content_length(line) # Blindly consume all header lines while line and line.strip(): line = self._rfile.readline() if not line: return None ...
def _read_message(self)
Reads the contents of a message. Returns: body of message if parsable else None
3.920905
3.802933
1.031021
if line.startswith(b'Content-Length: '): _, value = line.split(b'Content-Length: ') value = value.strip() try: return int(value) except ValueError: raise ValueError("Invalid Content-Length header: {}".format(value)) ...
def _content_length(line)
Extract the content length from an input line.
2.228332
2.118515
1.051837
if index is None: return (hostapi_info(i) for i in range(_pa.Pa_GetHostApiCount())) else: info = _pa.Pa_GetHostApiInfo(index) if not info: raise RuntimeError("Invalid host API") assert info.structVersion == 1 return {'name': ffi.string(info.name).decode(e...
def hostapi_info(index=None)
Return a generator with information about each host API. If index is given, only one dictionary for the given host API is returned.
3.883948
4.041557
0.961003
if index is None: return (device_info(i) for i in range(_pa.Pa_GetDeviceCount())) else: info = _pa.Pa_GetDeviceInfo(index) if not info: raise RuntimeError("Invalid device") assert info.structVersion == 2 if 'DirectSound' in hostapi_info(info.hostApi)['na...
def device_info(index=None)
Return a generator with information about each device. If index is given, only one dictionary for the given device is returned.
2.91426
2.91651
0.999229
if device is None: if kind == 'input': device = _pa.Pa_GetDefaultInputDevice() elif kind == 'output': device = _pa.Pa_GetDefaultOutputDevice() info = device_info(device) if channels is None: channels = info['max_' + kind + '_channels'] dtype = np.dty...
def _get_stream_parameters(kind, device, channels, dtype, latency, samplerate)
Generate PaStreamParameters struct.
3.194245
3.020615
1.057482
framesize = channels * dtype.itemsize data = np.frombuffer(ffi.buffer(ptr, frames * framesize), dtype=dtype) data.shape = -1, channels return data
def _frombuffer(ptr, frames, channels, dtype)
Create NumPy array from a pointer to some memory.
2.838761
2.889376
0.982482
if isinstance(value, str): # iterable, but not meant for splitting return value, value try: invalue, outvalue = value except TypeError: invalue = outvalue = value except ValueError: raise ValueError("Only single values and pairs are allowed") return inval...
def _split(value)
Split input/output value into two values.
6.321546
5.46119
1.15754
err = _pa.Pa_StartStream(self._stream) if err == _pa.paStreamIsNotStopped: return self._handle_error(err)
def start(self)
Commence audio processing. If successful, the stream is considered active.
12.073878
11.12407
1.085383
err = _pa.Pa_StopStream(self._stream) if err == _pa.paStreamIsStopped: return self._handle_error(err)
def stop(self)
Terminate audio processing. This waits until all pending audio buffers have been played before it returns. If successful, the stream is considered inactive.
8.480246
8.488276
0.999054
err = _pa.Pa_AbortStream(self._stream) if err == _pa.paStreamIsStopped: return self._handle_error(err)
def abort(self)
Terminate audio processing immediately. This does not wait for pending audio buffers. If successful, the stream is considered inactive.
9.749523
8.528738
1.143138
channels, _ = _split(self.channels) dtype, _ = _split(self.dtype) data = ffi.new("signed char[]", channels * dtype.itemsize * frames) self._handle_error(_pa.Pa_ReadStream(self._stream, data, frames)) if not raw: data = np.frombuffer(ffi.buffer(data), dtype=dt...
def read(self, frames, raw=False)
Read samples from an input stream. The function does not return until the required number of frames has been read. This may involve waiting for the operating system to supply the data. If raw data is requested, the raw cffi data buffer is returned. Otherwise, a numpy array of t...
4.411391
4.112578
1.072658
frames = len(data) _, channels = _split(self.channels) _, dtype = _split(self.dtype) if (not isinstance(data, np.ndarray) or data.dtype != dtype): data = np.array(data, dtype=dtype) if len(data.shape) == 1: # play mono signals on all channels ...
def write(self, data)
Write samples to an output stream. As much as one blocksize of audio data will be played without blocking. If more than one blocksize was provided, the function will only return when all but one blocksize has been played. Data will be converted to a numpy matrix. Multichannel d...
3.306676
3.049934
1.08418
args = ("--interactive",) + args return supervisorctl.main(("-c",cfg_file) + args)
def _handle_shell(self,cfg_file,*args,**options)
Command 'supervisord shell' runs the interactive command shell.
12.049372
9.970817
1.208464
if args: raise CommandError("supervisor getconfig takes no arguments") print cfg_file.read() return 0
def _handle_getconfig(self,cfg_file,*args,**options)
Command 'supervisor getconfig' prints merged config to stdout.
8.411907
4.222671
1.992082
if args: raise CommandError("supervisor autoreload takes no arguments") live_dirs = self._find_live_code_dirs() reload_progs = self._get_autoreload_programs(cfg_file) def autoreloader(): if os.fork() == 0: sys.exit(self.handl...
def _handle_autoreload(self,cfg_file,*args,**options)
Command 'supervisor autoreload' watches for code changes. This command provides a simulation of the Django dev server's auto-reloading mechanism that will restart all supervised processes. It's not quite as accurate as Django's autoreloader because it runs in a separate process, so it ...
4.945875
4.895948
1.010198
cfg = RawConfigParser() cfg.readfp(cfg_file) reload_progs = [] for section in cfg.sections(): if section.startswith("program:"): try: if cfg.getboolean(section,"autoreload"): reload_progs.append(section.spli...
def _get_autoreload_programs(self,cfg_file)
Get the set of programs to auto-reload when code changes. Such programs will have autoreload=true in their config section. This can be affected by config file sections or command-line arguments, so we need to read it out of the merged config.
2.301068
2.254771
1.020533
live_dirs = [] for mod in sys.modules.values(): # Get the directory containing that module. # This is deliberately casting a wide net. try: dirnm = os.path.dirname(mod.__file__) except AttributeError: continue ...
def _find_live_code_dirs(self)
Find all directories in which we might have live python code. This walks all of the currently-imported modules and adds their containing directory to the list of live dirs. After normalization and de-duplication, we get a pretty good approximation of the directories on sys.path that ar...
3.218415
3.084833
1.043303
djsupervisor_tags.current_context = ctx data = "{% load djsupervisor_tags %}" + data t = template.Template(data) c = template.Context(ctx) return t.render(c).encode("ascii")
def render_config(data,ctx)
Render the given config data using Django's template system. This function takes a config data string and a dict of context variables, renders the data through Django's template system, and returns the result.
6.580713
4.598302
1.431118
data = [] # Set whether or not to daemonize. # Unlike supervisord, our default is to stay in the foreground. data.append("[supervisord]\n") if options.get("daemonize",False): data.append("nodaemon=false\n") else: data.append("nodaemon=true\n") if options.get("pidfile",...
def get_config_from_options(**options)
Get config file fragment reflecting command-line options.
2.379074
2.328734
1.021617
projname = settings.SETTINGS_MODULE.split(".",1)[0] projmod = import_module(projname) projdir = os.path.dirname(projmod.__file__) # For Django 1.3 and earlier, the manage.py file was located # in the same directory as the settings file. if os.path.isfile(os.path.join(projdir,"manage.py")):...
def guess_project_dir()
Find the top-level Django project directory. This function guesses the top-level Django project directory based on the current environment. It looks for module containing the currently- active settings module, in both pre-1.4 and post-1.4 layours.
2.623929
2.482075
1.057151
try: cfg.get(section,option) except NoSectionError: cfg.add_section(section) cfg.set(section,option,value) except NoOptionError: cfg.set(section,option,value)
def set_if_missing(cfg,section,option,value)
If the given option is missing, set to the given value.
1.593088
1.615476
0.986142
args = [] for name,value in options.iteritems(): name = name.replace("_","-") if value is None: pass elif isinstance(value,bool): if value: args.append("--%s" % (name,)) elif isinstance(value,list): for item in value: ...
def rerender_options(options)
Helper function to re-render command-line options. This assumes that command-line options use the same name as their key in the options dictionary.
1.795894
1.829902
0.981415
if user is not None: data = {'login': user, 'password': password} elif email is not None: data = {'email': email, 'password': password} else: raise ValueError('Neither username nor email provided to login') self.headers = {'connection': 'clos...
def login(self, email=None, password=None, user=None)
Logs the user in and setups the header with the private token :param email: Gitlab user Email :param user: Gitlab username :param password: Gitlab user password :return: True if login successful :raise: HttpError :raise: ValueError
3.050076
2.682382
1.137078
if search: return self.get('/users', page=page, per_page=per_page, search=search, **kwargs) return self.get('/users', page=page, per_page=per_page, **kwargs)
def get_users(self, search=None, page=1, per_page=20, **kwargs)
Returns a list of users from the Gitlab server :param search: Optional search query :param page: Page number (default: 1) :param per_page: Number of items to list per page (default: 20, max: 100) :return: List of Dictionaries containing users :raise: HttpError if invalid respons...
2.00941
2.392564
0.839857
return self.get_users(search=search, page=page, per_page=per_page, **kwargs)
def getusers(self, search=None, page=1, per_page=20, **kwargs)
Returns a list of users from the Gitlab server .. warning:: Warning this is being deprecated please use :func:`gitlab.Gitlab.get_users` :param search: Optional search query :param page: Page number (default: 1) :param per_page: Number of items to list per page (default: 20, max: 100) ...
2.404337
3.175108
0.757246
request = requests.get( '{0}/{1}'.format(self.users_url, user_id), headers=self.headers, verify=self.verify_ssl, auth=self.auth, timeout=self.timeout) if request.status_code == 200: return request.json() else: return False
def getuser(self, user_id)
Get info for a user identified by id :param user_id: id of the user :return: False if not found, a dictionary if found
2.434298
2.49679
0.974971
data = {'name': name, 'username': username, 'password': password, 'email': email} if kwargs: data.update(kwargs) request = requests.post( self.users_url, headers=self.headers, data=data, verify=self.verify_ssl, auth=self.auth, timeout=self.timeout) ...
def createuser(self, name, username, password, email, **kwargs)
Create a user :param name: Obligatory :param username: Obligatory :param password: Obligatory :param email: Obligatory :param kwargs: Any param the the Gitlab API supports :return: True if the user was created,false if it wasn't(already exists)
2.063233
2.198198
0.938602
deleted = self.delete_user(user_id) if deleted is False: return False else: return True
def deleteuser(self, user_id)
Deletes a user. Available only for administrators. This is an idempotent function, calling this function for a non-existent user id still returns a status code 200 OK. The JSON response differs if the user was actually deleted or not. In the former the user is returned and in the latter ...
4.040902
6.511796
0.620551
request = requests.get( '{0}/api/v3/user'.format(self.host), headers=self.headers, verify=self.verify_ssl, auth=self.auth, timeout=self.timeout) return request.json()
def currentuser(self)
Returns the current user parameters. The current user is linked to the secret token :return: a list with the current user properties
3.492985
3.382711
1.032599
data = {} if kwargs: data.update(kwargs) request = requests.put( '{0}/{1}'.format(self.users_url, user_id), headers=self.headers, data=data, timeout=self.timeout, verify=self.verify_ssl, auth=self.auth) if request.status_code == 200: ...
def edituser(self, user_id, **kwargs)
Edits an user data. :param user_id: id of the user to change :param kwargs: Any param the the Gitlab API supports :return: Dict of the user
2.458329
2.732524
0.899655
request = requests.get( self.keys_url, headers=self.headers, verify=self.verify_ssl, auth=self.auth, timeout=self.timeout) if request.status_code == 200: return request.json() else: return False
def getsshkeys(self)
Gets all the ssh keys for the current user :return: a dictionary with the lists
2.840823
3.043492
0.933409
data = {'title': title, 'key': key} request = requests.post( self.keys_url, headers=self.headers, data=data, verify=self.verify_ssl, auth=self.auth, timeout=self.timeout) if request.status_code == 201: return True else: return Fa...
def addsshkey(self, title, key)
Add a new ssh key for the current user :param title: title of the new key :param key: the key itself :return: true if added, false if it didn't add it (it could be because the name or key already exists)
2.445968
2.710929
0.902262
data = {'title': title, 'key': key} request = requests.post( '{0}/{1}/keys'.format(self.users_url, user_id), headers=self.headers, data=data, verify=self.verify_ssl, auth=self.auth, timeout=self.timeout) if request.status_code == 201: return True ...
def addsshkeyuser(self, user_id, title, key)
Add a new ssh key for the user identified by id :param user_id: id of the user to add the key to :param title: title of the new key :param key: the key itself :return: true if added, false if it didn't add it (it could be because the name or key already exists)
2.420259
2.593491
0.933205
request = requests.delete( '{0}/{1}'.format(self.keys_url, key_id), headers=self.headers, verify=self.verify_ssl, auth=self.auth, timeout=self.timeout) if request.content == b'null': return False else: return True
def deletesshkey(self, key_id)
Deletes an sshkey for the current user identified by id :param key_id: the id of the key :return: False if it didn't delete it, True if it was deleted
3.374645
3.507254
0.96219
url = self.api_url + uri response = requests.get(url, params=kwargs, headers=self.headers, verify=self.verify_ssl, auth=self.auth, timeout=self.timeout) return self.success_or_raise(response, default_response=default_respo...
def get(self, uri, default_response=None, **kwargs)
Call GET on the Gitlab server >>> gitlab = Gitlab(host='http://localhost:10080', verify_ssl=False) >>> gitlab.login(user='root', password='5iveL!fe') >>> gitlab.get('/users/5') :param uri: String with the URI for the endpoint to GET from :param default_response: Return value if...
2.765803
3.235864
0.854734