code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
with Vector(infile) as vec:
srs = vec.srs
feat = vec.layer[0]
d = feat.GetFieldDefnRef(field)
width = d.width
type = d.type
feat = None
layername = layername if layername is not None else os.path.splitext(os.path.basename(infile))[0]
# the follo... | def dissolve(infile, outfile, field, layername=None) | dissolve the polygons of a vector file by an attribute field
Parameters
----------
infile: str
the input vector file
outfile: str
the output shapefile
field: str
the field name to merge the polygons by
layername: str
the name of the output vector layer;
If... | 4.105157 | 4.202279 | 0.976888 |
features = feature if isinstance(feature, list) else [feature]
layername = layername if layername is not None else ref.layername
vec = Vector(driver='Memory')
vec.addlayer(layername, ref.srs, ref.geomType)
feat_def = features[0].GetDefnRef()
fields = [feat_def.GetFieldDefn(x) for x in range... | def feature2vector(feature, ref, layername=None) | create a Vector object from ogr features
Parameters
----------
feature: list of :osgeo:class:`ogr.Feature` or :osgeo:class:`ogr.Feature`
a single feature or a list of features
ref: Vector
a reference Vector object to retrieve geo information from
layername: str or None
the n... | 3.315092 | 3.180066 | 1.04246 |
if not isinstance(obj1, Vector) or not isinstance(obj2, Vector):
raise RuntimeError('both objects must be of type Vector')
obj1 = obj1.clone()
obj2 = obj2.clone()
obj1.reproject(obj2.srs)
#######################################################
# create basic overlap
... | def intersect(obj1, obj2) | intersect two Vector objects
Parameters
----------
obj1: Vector
the first vector object; this object is reprojected to the CRS of obj2 if necessary
obj2: Vector
the second vector object
Returns
-------
Vector
the intersect of obj1 and obj2 | 2.607097 | 2.581909 | 1.009756 |
feature = ogr.Feature(self.layerdef)
feature.SetGeometry(geometry)
if fields is not None:
for fieldname, value in fields.items():
if fieldname not in self.fieldnames:
raise IOError('field "{}" is missing'.format(fieldname... | def addfeature(self, geometry, fields=None) | add a feature to the vector object from a geometry
Parameters
----------
geometry: :osgeo:class:`ogr.Geometry`
the geometry to add as a feature
fields: dict or None
the field names and values to assign to the new feature
Returns
------- | 2.578871 | 2.630843 | 0.980245 |
fieldDefn = ogr.FieldDefn(name, type)
if type == ogr.OFTString:
fieldDefn.SetWidth(width)
self.layer.CreateField(fieldDefn) | def addfield(self, name, type, width=10) | add a field to the vector layer
Parameters
----------
name: str
the field name
type: int
the OGR Field Type (OFT), e.g. ogr.OFTString.
See `Module ogr <https://gdal.org/python/osgeo.ogr-module.html>`_.
width: int
the width of the n... | 2.482029 | 2.557673 | 0.970425 |
self.vector.CreateLayer(name, srs, geomType)
self.init_layer() | def addlayer(self, name, srs, geomType) | add a layer to the vector layer
Parameters
----------
name: str
the layer name
srs: int, str or :osgeo:class:`osr.SpatialReference`
the spatial reference system. See :func:`spatialist.auxil.crsConvert` for options.
geomType: int
an OGR well-kn... | 5.457139 | 5.957188 | 0.91606 |
vec.layer.ResetReading()
for feature in vec.layer:
self.layer.CreateFeature(feature)
self.init_features()
vec.layer.ResetReading() | def addvector(self, vec) | add a vector object to the layer of the current Vector object
Parameters
----------
vec: Vector
the vector object to add
merge: bool
merge overlapping polygons?
Returns
------- | 7.210796 | 8.983326 | 0.802687 |
if outname is None:
return bbox(self.extent, self.srs)
else:
bbox(self.extent, self.srs, outname=outname, format=format, overwrite=overwrite) | def bbox(self, outname=None, format='ESRI Shapefile', overwrite=True) | create a bounding box from the extent of the Vector object
Parameters
----------
outname: str or None
the name of the vector file to be written; if None, a Vector object is returned
format: str
the name of the file format to write
overwrite: bool
... | 2.7162 | 3.958266 | 0.68621 |
features = self.getfeatures()
for feature in features:
try:
feature.geometry().Set3D(set3D)
except AttributeError:
dim = 3 if set3D else 2
feature.geometry().SetCoordinateDimension(dim)
return [feature.geom... | def convert2wkt(self, set3D=True) | export the geometry of each feature as a wkt string
Parameters
----------
set3D: bool
keep the third (height) dimension?
Returns
------- | 3.945603 | 3.812834 | 1.034822 |
attr = attribute.strip() if isinstance(attribute, str) else attribute
if fieldname not in self.fieldnames:
raise KeyError('invalid field name')
out = []
self.layer.ResetReading()
for feature in self.layer:
field = feature.GetField(fieldname)
... | def getFeatureByAttribute(self, fieldname, attribute) | get features by field attribute
Parameters
----------
fieldname: str
the name of the queried field
attribute: int or str
the field value of interest
Returns
-------
list of :osgeo:class:`ogr.Feature` or :osgeo:class:`ogr.Feature`
... | 2.292406 | 2.313551 | 0.99086 |
feature = self.layer[index]
if feature is None:
feature = self.getfeatures()[index]
return feature | def getFeatureByIndex(self, index) | get features by numerical (positional) index
Parameters
----------
index: int
the queried index
Returns
-------
:osgeo:class:`ogr.Feature`
the requested feature | 5.807758 | 7.814201 | 0.743231 |
self.layer = self.vector.GetLayer()
self.__features = [None] * self.nfeatures | def init_layer(self) | initialize a layer object
Returns
------- | 14.225389 | 15.890771 | 0.895198 |
self.layer.ResetReading()
for i in range(self.nfeatures):
if self.__features[i] is None:
self.__features[i] = self.layer[i] | def load(self) | load all feature into memory
Returns
------- | 5.187448 | 5.801037 | 0.894228 |
srs_out = crsConvert(projection, 'osr')
if self.srs.IsSame(srs_out) == 0:
# create the CoordinateTransformation
coordTrans = osr.CoordinateTransformation(self.srs, srs_out)
layername = self.layername
geomType = s... | def reproject(self, projection) | in-memory reprojection
Parameters
----------
projection: int, str or :osgeo:class:`osr.SpatialReference`
the target CRS. See :func:`spatialist.auxil.crsConvert`.
Returns
------- | 2.897242 | 3.101938 | 0.934011 |
# try to convert the input crs to osr.SpatialReference
srs_out = crsConvert(crs, 'osr')
# save all relevant info from the existing vector object
layername = self.layername
geomType = self.geomType
layer_definition = ogr.Feature(self.layer.GetLayerDefn())... | def setCRS(self, crs) | directly reset the spatial reference system of the vector object.
This is not going to reproject the Vector object, see :meth:`reproject` instead.
Parameters
----------
crs: int, str or :osgeo:class:`osr.SpatialReference`
the input CRS
Returns
-------
... | 4.001109 | 4.317711 | 0.926674 |
(outfilepath, outfilename) = os.path.split(outfile)
basename = os.path.splitext(outfilename)[0]
driver = ogr.GetDriverByName(format)
if os.path.exists(outfile):
if overwrite:
driver.DeleteDataSource(outfile)
else:
... | def write(self, outfile, format='ESRI Shapefile', overwrite=True) | write the Vector object to a file
Parameters
----------
outfile:
the name of the file to write
format: str
the output file format
overwrite: bool
overwrite an already existing file?
Returns
------- | 1.930348 | 2.083062 | 0.926688 |
return self.smbus.write_byte_data(address, register, value) | def write_byte_data(self, address, register, value) | SMBus Read Byte: i2c_smbus_read_byte_data()
============================================
This reads a single byte from a device, from a designated register.
The register is specified through the Comm byte.
S Addr Wr [A] Comm [A] S Addr Rd [A] [Data] NA P
Functionality flag: I... | 4.146533 | 6.368746 | 0.651075 |
return self.smbus.write_word_data(address, register, value) | def write_word_data(self, address, register, value) | SMBus Write Word: i2c_smbus_write_word_data()
==============================================
This is the opposite of the Read Word operation. 16 bits
of data is written to a device, to the designated register that is
specified through the Comm byte.
S Addr Wr [A] Comm [A] Data... | 4.216514 | 4.537783 | 0.929201 |
return self.smbus.write_block_data(address, register, value) | def write_block_data(self, address, register, value) | SMBus Block Write: i2c_smbus_write_block_data()
================================================
The opposite of the Block Read command, this writes up to 32 bytes to
a device, to a designated register that is specified through the
Comm byte. The amount of data is specified in the Coun... | 4.398003 | 6.058659 | 0.725904 |
return self.smbus.block_process_call(address, register, value) | def block_process_call(self, address, register, value) | SMBus Block Write - Block Read Process Call
===========================================
SMBus Block Write - Block Read Process Call was introduced in
Revision 2.0 of the specification.
This command selects a device register (through the Comm byte), sends
1 to 31 bytes of data t... | 4.700629 | 7.575693 | 0.620488 |
return self.smbus.write_i2c_block_data(address, register, value) | def write_i2c_block_data(self, address, register, value) | I2C block transactions do not limit the number of bytes transferred
but the SMBus layer places a limit of 32 bytes.
I2C Block Write: i2c_smbus_write_i2c_block_data()
==================================================
The opposite of the Block Read command, this writes bytes to
... | 2.980638 | 4.290291 | 0.69474 |
return self.smbus.read_i2c_block_data(address, register, length) | def read_i2c_block_data(self, address, register, length) | I2C block transactions do not limit the number of bytes transferred
but the SMBus layer places a limit of 32 bytes.
I2C Block Read: i2c_smbus_read_i2c_block_data()
================================================
This command reads a block of bytes from a device, from a
design... | 2.713116 | 4.428479 | 0.612652 |
log.debug('kernel {} publishing on port {}'
''.format(self.analysis.id_, port_publish))
self.zmq_publish = zmq.Context().socket(zmq.PUB)
self.zmq_publish.connect('tcp://127.0.0.1:{}'.format(port_publish))
log.debug('kernel {} subscribed on port {}'
... | def _init_zmq(self, port_publish, port_subscribe) | Initialize zmq messaging.
Listen on sub_port. This port might at
some point receive the message to start publishing on a certain
port, but until then, no publishing. | 2.249922 | 2.275204 | 0.988888 |
# detect process_id
process_id = None
if isinstance(message, dict) and '__process_id' in message:
process_id = message['__process_id']
del message['__process_id']
if process_id:
analysis.emit('__process', {'id': process_id, 'status': 'start'... | def run_process(self, analysis, action_name, message='__nomessagetoken__') | Executes an process in the analysis with the given message.
It also handles the start and stop signals in case an process_id
is given.
This method is similar to the method in databench.Analysis. | 3.416978 | 3.347821 | 1.020657 |
try:
zmq.eventloop.ioloop.IOLoop.current().start()
except KeyboardInterrupt:
zmq.eventloop.ioloop.IOLoop.current().stop() | def event_loop(self) | Event loop. | 2.371006 | 2.206804 | 1.074407 |
log.debug('kernel {} zmq send ({}): {}'
''.format(analysis_id, signal, message))
self.zmq_publish.send(json.dumps({
'analysis_id': analysis_id,
'frame': {'signal': signal, 'load': message},
}, default=json_encoder_default).encode('utf-8')) | def emit(self, signal, message, analysis_id) | Emit signal to main.
Args:
signal: Name of the signal to be emitted.
message: Message to be sent.
analysis_id: Identifies the instance of this analysis. | 5.86784 | 6.256757 | 0.937841 |
'Writes specified value to the pins defined as output by config_ports() method. Writing to input pins has no effect.'
self.bus.write_byte_data(self.address, self.OUTPUT_PORT0, port0)
self.bus.write_byte_data(self.address, self.OUTPUT_PORT1, port1)
return True | def set_ports(self, port0 = 0x00, port1 = 0x00) | Writes specified value to the pins defined as output by config_ports() method. Writing to input pins has no effect. | 4.874341 | 2.123941 | 2.294951 |
'Reads logical values at pins.'
return (self.bus.read_byte_data(self.address, self.STATUS_PORT0), self.bus.read_byte_data(self.address, self.STATUS_PORT1)); | def get_ports(self) | Reads logical values at pins. | 7.889652 | 4.243702 | 1.859144 |
'Reads logical values at pins.'
return (self.bus.read_byte_data(self.address, self.CONTROL_PORT0), self.bus.read_byte_data(self.address, self.CONTROL_PORT1)); | def get_config(self) | Reads logical values at pins. | 8.545826 | 4.48496 | 1.905441 |
'Sets INPUT (1) or OUTPUT (0) direction on pins. Inversion setting is applicable for input pins 1-inverted 0-noninverted input polarity.'
self.bus.write_byte_data(self.address, self.PULLUP_PORT0, port0)
self.bus.write_byte_data(self.address, self.PULLUP_PORT1, port1)
return | def set_pullups(self, port0 = 0x00, port1 = 0x00) | Sets INPUT (1) or OUTPUT (0) direction on pins. Inversion setting is applicable for input pins 1-inverted 0-noninverted input polarity. | 6.75043 | 1.840838 | 3.667042 |
'Writes specified value to the pins defined as output by method. Writing to input pins has no effect.'
self.bus.write_byte_data(self.address, self.CONTROL_PORT0, port0)
self.bus.write_byte_data(self.address, self.CONTROL_PORT0, port1)
return | def set_ports(self, port0 = 0x00, port1 = 0x00) | Writes specified value to the pins defined as output by method. Writing to input pins has no effect. | 5.570971 | 2.4372 | 2.285808 |
db_file = gtf + '.db'
if gtf.endswith('.gz'):
db_file = gtf[:-3] + '.db'
if file_exists(db_file):
return gffutils.FeatureDB(db_file)
db_file = ':memory:' if in_memory else db_file
if in_memory or not file_exists(db_file):
debug('GTF database does not exist, creating...')... | def get_gtf_db(gtf, in_memory=False) | create a gffutils DB | 2.731704 | 2.533293 | 1.078321 |
out_file = os.path.splitext(gtf)[0] + '.bed'
if file_exists(out_file):
return out_file
if not os.access(os.path.dirname(out_file), os.W_OK | os.X_OK):
if not alt_out_dir:
raise IOError('Cannot write transcript BED output file %s' % out_file)
else:
out_fil... | def gtf_to_bed(gtf, alt_out_dir=None) | create a BED file of transcript-level features with attached gene name
or gene ids | 2.119216 | 2.064327 | 1.026589 |
installed_tx2gene = os.path.join(os.path.dirname(gtf), "tx2gene.csv")
if file_exists(installed_tx2gene):
return installed_tx2gene
if file_exists(out_file):
return out_file
with file_transaction(out_file) as tx_out_file:
with open(tx_out_file, "w") as out_handle:
... | def tx2genefile(gtf, out_file=None) | write out a file of transcript->gene mappings.
use the installed tx2gene.csv if it exists, else write a new one out | 2.220839 | 2.036225 | 1.090665 |
gene_lookup = {}
for feature in complete_features(get_gtf_db(gtf)):
gene_id = feature.attributes.get('gene_id', [None])[0]
transcript_id = feature.attributes.get('transcript_id', [None])[0]
gene_lookup[transcript_id] = gene_id
return gene_lookup | def transcript_to_gene(gtf) | return a dictionary keyed by transcript_id of the associated gene_id | 2.532399 | 2.4336 | 1.040598 |
hsdiv_tuple = (4, 5, 6, 7, 9, 11) # possible dividers
n1div_tuple = (1,) + tuple(range(2,129,2)) #
fdco_min = 5670.0 # set maximum as minimum
hsdiv = self.get_hs_div() # read curent dividers
n1div = self.get_n1_div() #
if abs((freq-fout)... | def set_freq(self, fout, freq) | Sets new output frequency, required parameters are real current frequency at output and new required frequency. | 4.990073 | 4.943255 | 1.009471 |
if len(file.data) <= 0x20:
return 0
bom = file.data[0xc:0xc+2]
if bom != b'\xff\xfe' and bom != b'\xfe\xff':
return 0
be = bom == b'\xfe\xff'
file_size: int = struct.unpack_from(_get_unpack_endian_character(be) + 'I', file.data, 0x1c)[0]
... | def _get_file_alignment_for_new_binary_file(self, file: File) -> int | Detects alignment requirements for binary files with new nn::util::BinaryFileHeader. | 3.715864 | 3.579016 | 1.038236 |
if os.getcwd().endswith('analyses'):
correct = input('You are in an analyses folder. This will create '
'another analyses folder inside this one. Do '
'you want to continue? (y/N)')
if correct != 'y':
return False
if not os.path.... | def check_folders(name) | Only checks and asks questions. Nothing is written to disk. | 2.51351 | 2.47294 | 1.016406 |
if not os.path.exists(os.path.join(os.getcwd(), 'analyses')):
os.system("mkdir analyses")
# __init__.py
init_path = os.path.join(os.getcwd(), 'analyses', '__init__.py')
if not os.path.exists(init_path):
with open(init_path, 'w') as f:
pass
# index.yaml
index_p... | def create_analyses(name, kernel=None) | Create an analysis with given name and suffix.
If it does not exist already, it creates the top level analyses folder
and it's __init__.py and index.yaml file. | 2.096291 | 2.020247 | 1.037641 |
# analysis folder
folder = os.path.join(os.getcwd(), 'analyses', name)
if not os.path.exists(folder):
os.makedirs(folder)
else:
log.warning('Analysis folder {} already exists.'.format(folder))
# copy all other files
for f in os.listdir(src_dir):
if f in ('__pycache... | def create_analysis(name, kernel, src_dir, scaffold_name) | Create analysis files. | 2.666141 | 2.667883 | 0.999347 |
if isinstance(crsIn, osr.SpatialReference):
srs = crsIn.Clone()
else:
srs = osr.SpatialReference()
if isinstance(crsIn, int):
crsIn = 'EPSG:{}'.format(crsIn)
if isinstance(crsIn, str):
try:
srs.SetFromUserInput(crsIn)... | def crsConvert(crsIn, crsOut) | convert between different types of spatial references
Parameters
----------
crsIn: int, str or :osgeo:class:`osr.SpatialReference`
the input CRS
crsOut: {'wkt', 'proj4', 'epsg', 'osr', 'opengis' or 'prettyWkt'}
the output CRS type
Returns
-------
int, str or :osgeo:class:`o... | 1.95553 | 1.758879 | 1.111805 |
radius = 6371000
lat1, lon1, lat2, lon2 = map(math.radians, [lat1, lon1, lat2, lon2])
a = math.sin((lat2 - lat1) / 2) ** 2 + math.cos(lat1) * math.cos(lat2) * math.sin((lon2 - lon1) / 2) ** 2
c = 2 * math.asin(math.sqrt(a))
return radius * c | def haversine(lat1, lon1, lat2, lon2) | compute the distance in meters between two points in latlon
Parameters
----------
lat1: int or float
the latitude of point 1
lon1: int or float
the longitude of point 1
lat2: int or float
the latitude of point 2
lon2: int or float
the longitude of point 2
Re... | 1.437683 | 1.531842 | 0.938532 |
try:
out = gdal.Warp(dst, src, options=gdal.WarpOptions(**options))
except RuntimeError as e:
raise RuntimeError('{}:\n src: {}\n dst: {}\n options: {}'.format(str(e), src, dst, options))
out = None | def gdalwarp(src, dst, options) | a simple wrapper for :osgeo:func:`gdal.Warp`
Parameters
----------
src: str, :osgeo:class:`ogr.DataSource` or :osgeo:class:`gdal.Dataset`
the input data set
dst: str
the output data set
options: dict
additional parameters passed to gdal.Warp; see :osgeo:func:`gdal.WarpOption... | 2.587839 | 2.876508 | 0.899646 |
options = {} if options is None else options
if 'outputBounds' in options.keys() and gdal.__version__ < '2.4.0':
warnings.warn('\ncreating VRT files with subsetted extent is very likely to cause problems. '
'Please use GDAL version >= 2.4.0, which fixed the problem.\n'
... | def gdalbuildvrt(src, dst, options=None, void=True) | a simple wrapper for :osgeo:func:`gdal.BuildVRT`
Parameters
----------
src: str, list, :osgeo:class:`ogr.DataSource` or :osgeo:class:`gdal.Dataset`
the input data set(s)
dst: str
the output data set
options: dict
additional parameters passed to gdal.BuildVRT; see :osgeo:func... | 4.750401 | 5.167506 | 0.919283 |
out = gdal.Translate(dst, src, options=gdal.TranslateOptions(**options))
out = None | def gdal_translate(src, dst, options) | a simple wrapper for `gdal.Translate <https://gdal.org/python/osgeo.gdal-module.html#Translate>`_
Parameters
----------
src: str, :osgeo:class:`ogr.DataSource` or :osgeo:class:`gdal.Dataset`
the input data set
dst: str
the output data set
options: dict
additional parameters ... | 3.3283 | 5.207945 | 0.639081 |
out = gdal.VectorTranslate(dst, src, options=gdal.VectorTranslateOptions(**options))
out = None | def ogr2ogr(src, dst, options) | a simple wrapper for gdal.VectorTranslate aka `ogr2ogr <https://www.gdal.org/ogr2ogr.html>`_
Parameters
----------
src: str or :osgeo:class:`ogr.DataSource`
the input data set
dst: str
the output data set
options: dict
additional parameters passed to gdal.VectorTranslate;
... | 4.24125 | 4.834465 | 0.877294 |
out = gdal.Rasterize(dst, src, options=gdal.RasterizeOptions(**options))
out = None | def gdal_rasterize(src, dst, options) | a simple wrapper for gdal.Rasterize
Parameters
----------
src: str or :osgeo:class:`ogr.DataSource`
the input data set
dst: str
the output data set
options: dict
additional parameters passed to gdal.Rasterize; see :osgeo:func:`gdal.RasterizeOptions`
Returns
------- | 3.64877 | 5.559519 | 0.65631 |
source = crsConvert(s_crs, 'osr')
target = crsConvert(t_crs, 'osr')
transform = osr.CoordinateTransformation(source, target)
point = transform.TransformPoint(x, y)[:2]
return point | def coordinate_reproject(x, y, s_crs, t_crs) | reproject a coordinate from one CRS to another
Parameters
----------
x: int or float
the X coordinate component
y: int or float
the Y coordinate component
s_crs: int, str or :osgeo:class:`osr.SpatialReference`
the source CRS. See :func:`~spatialist.auxil.crsConvert` for ... | 2.491791 | 3.242119 | 0.768568 |
output_dir = safe_mkdir(adjust_path(output_dir or join(os.getcwd(), proc_name)), 'output_dir')
debug('Saving results into ' + output_dir)
work_dir = safe_mkdir(work_dir or join(output_dir, 'work'), 'working directory')
info('Using work directory ' + work_dir)
log_fpath = set_up_log(log_dir or... | def set_up_dirs(proc_name, output_dir=None, work_dir=None, log_dir=None) | Creates output_dir, work_dir, and sets up log | 3.219928 | 3.206123 | 1.004306 |
for chunk in response.iter_content(100 * 1024, decode_unicode=decode_unicode):
if decode_unicode:
# Replace CRLF newlines with LF, Python will handle
# platform specific newlines if written to file.
chunk = chunk.replace('\r\n', '\n')
# Chunk could be ['.... | def _iter_content_generator(response, decode_unicode) | Generator used to yield 100 KiB chunks for a given response. | 6.042408 | 5.605286 | 1.077984 |
pending = None
for chunk in _iter_content_generator(response, decode_unicode=decode_unicode):
if pending is not None:
chunk = pending + chunk
lines = chunk.splitlines()
if lines and lines[-1] and chunk and lines[-1][-1] == chunk[-1]:
pending = lines.pop()... | def _iter_lines_generator(response, decode_unicode) | Iterates over the response data, one line at a time. When
stream=True is set on the request, this avoids reading the
content at once into memory for large responses.
The function is taken from :meth:`requests.models.Response.iter_lines`, but
modified to use our :func:`~spacetrack.base._iter_content_ge... | 2.130196 | 2.436531 | 0.874274 |
http_error_msg = ''
if 400 <= response.status_code < 500:
http_error_msg = '%s Client Error: %s for url: %s' % (
response.status_code, response.reason, response.url)
elif 500 <= response.status_code < 600:
http_error_msg = '%s Server Error: %s for url: %s' % (
... | def _raise_for_status(response) | Raises stored :class:`HTTPError`, if one occurred.
This is the :meth:`requests.models.Response.raise_for_status` method,
modified to add the response from Space-Track, if given. | 1.837058 | 1.63485 | 1.123686 |
with self._ratelimiter:
resp = self.session.get(*args, **kwargs)
# It's possible that Space-Track will return HTTP status 500 with a
# query rate limit violation. This can happen if a script is cancelled
# before it has finished sleeping to satisfy the rate limit an... | def _ratelimited_get(self, *args, **kwargs) | Perform get request, handling rate limiting. | 4.791734 | 4.72199 | 1.01477 |
for controller, classes in self.request_controllers.items():
if class_ in classes:
return controller
else:
raise ValueError('Unknown request class {!r}'.format(class_)) | def _find_controller(self, class_) | Find first controller that matches given request class.
Order is specified by the keys of
``SpaceTrackClient.request_controllers``
(:class:`~collections.OrderedDict`) | 4.442422 | 4.026473 | 1.103304 |
self.authenticate()
url = ('{0}{1}/modeldef/class/{2}'
.format(self.base_url, controller, class_))
logger.debug(requests.utils.requote_uri(url))
resp = self._ratelimited_get(url)
_raise_for_status(resp)
return resp.json()['data'] | def _download_predicate_data(self, class_, controller) | Get raw predicate information for given request class, and cache for
subsequent calls. | 5.303711 | 5.207833 | 1.01841 |
if class_ not in self._predicates:
if controller is None:
controller = self._find_controller(class_)
else:
classes = self.request_controllers.get(controller, None)
if classes is None:
raise ValueError(
... | def get_predicates(self, class_, controller=None) | Get full predicate information for given request class, and cache
for subsequent calls. | 2.737826 | 2.444499 | 1.119995 |
return self.client.get_predicates(
class_=class_, controller=self.controller) | def get_predicates(self, class_) | Proxy ``get_predicates`` to client with stored request
controller. | 10.018574 | 5.816948 | 1.722307 |
super(FoldingPanel, self).on_install(editor)
self.context_menu = QtWidgets.QMenu(_('Folding'), self.editor)
action = self.action_collapse = QtWidgets.QAction(
_('Collapse'), self.context_menu)
action.setShortcut('Shift+-')
action.triggered.connect(self._on_ac... | def on_install(self, editor) | Add the folding menu to the editor, on install.
:param editor: editor instance on which the mode has been installed to. | 1.663409 | 1.665928 | 0.998488 |
c = self._custom_color
if self._native:
c = self.get_system_bck_color()
grad = QtGui.QLinearGradient(rect.topLeft(),
rect.topRight())
if sys.platform == 'darwin':
grad.setColorAt(0, c.lighter(100))
grad.set... | def _draw_rect(self, rect, painter) | Draw the background rectangle using the current style primitive color
or foldIndicatorBackground if nativeFoldingIndicator is true.
:param rect: The fold zone rect to draw
:param painter: The widget's painter. | 1.808239 | 1.820883 | 0.993056 |
def merged_colors(colorA, colorB, factor):
maxFactor = 100
colorA = QtGui.QColor(colorA)
colorB = QtGui.QColor(colorB)
tmp = colorA
tmp.setRed((tmp.red() * factor) / maxFactor +
(colorB.red() * (maxFactor - factor)) / ma... | def get_system_bck_color() | Gets a system color for drawing the fold scope background. | 2.330027 | 2.269914 | 1.026483 |
rect = QtCore.QRect(0, top, self.sizeHint().width(),
self.sizeHint().height())
if self._native:
if os.environ['QT_API'].lower() not in PYQT5_API:
opt = QtGui.QStyleOptionViewItemV2()
else:
opt = QtWidgets.QStyle... | def _draw_fold_indicator(self, top, mouse_over, collapsed, painter) | Draw the fold indicator/trigger (arrow).
:param top: Top position
:param mouse_over: Whether the mouse is over the indicator
:param collapsed: Whether the trigger is collapsed or not.
:param painter: QPainter | 2.797259 | 2.921602 | 0.95744 |
color = self.editor.background
if color.lightness() < 128:
color = drift_color(color, 130)
else:
color = drift_color(color, 105)
return color | def _get_scope_highlight_color(self) | Gets the base scope highlight color (derivated from the editor
background) | 5.157841 | 4.167916 | 1.237511 |
color = drift_color(base_color, factor=factor)
# upper part
if start > 0:
d = TextDecoration(self.editor.document(),
start_line=parent_start, end_line=start)
d.set_full_width(True, clear=False)
d.draw_order = 2
... | def _add_scope_deco(self, start, end, parent_start, parent_end, base_color,
factor) | Adds a scope decoration that enclose the current scope
:param start: Start of the current scope
:param end: End of the current scope
:param parent_start: Start of the parent scope
:param parent_end: End of the parent scope
:param base_color: base color for scope decoration
... | 2.596494 | 2.784195 | 0.932583 |
try:
parent = FoldScope(block).parent()
except ValueError:
parent = None
if TextBlockHelper.is_fold_trigger(block):
base_color = self._get_scope_highlight_color()
factor_step = 5
if base_color.lightness() < 128:
... | def _add_scope_decorations(self, block, start, end) | Show a scope decoration on the editor widget
:param start: Start line
:param end: End line | 3.513876 | 3.545116 | 0.991188 |
scope = FoldScope(block)
if (self._current_scope is None or
self._current_scope.get_range() != scope.get_range()):
self._current_scope = scope
self._clear_scope_decos()
# highlight surrounding parent scopes with a darker color
star... | def _highlight_surrounding_scopes(self, block) | Highlights the scopes surrounding the current fold scope.
:param block: Block that starts the current fold scope. | 5.178672 | 5.493744 | 0.942649 |
super(FoldingPanel, self).leaveEvent(event)
QtWidgets.QApplication.restoreOverrideCursor()
self._highlight_runner.cancel_requests()
if not self.highlight_caret_scope:
self._clear_scope_decos()
self._mouse_over_line = None
self._current_scope =... | def leaveEvent(self, event) | Removes scope decorations and background from the editor and the panel
if highlight_caret_scope, else simply update the scope decorations to
match the caret scope. | 7.71191 | 5.299732 | 1.455151 |
deco = TextDecoration(block)
deco.signals.clicked.connect(self._on_fold_deco_clicked)
deco.tooltip = region.text(max_lines=25)
deco.draw_order = 1
deco.block = block
deco.select_line()
deco.set_outline(drift_color(
self._get_scope_highlight_co... | def _add_fold_decoration(self, block, region) | Add fold decorations (boxes arround a folded block in the editor
widget). | 5.19803 | 5.039361 | 1.031486 |
if not TextBlockHelper.is_fold_trigger(block):
return
region = FoldScope(block)
if region.collapsed:
region.unfold()
if self._mouse_over_line is not None:
self._add_scope_decorations(
region._trigger, *region.get_ra... | def toggle_fold_trigger(self, block) | Toggle a fold trigger block (expand or collapse it).
:param block: The QTextBlock to expand/collapse | 6.854232 | 7.207311 | 0.951011 |
if state:
self.editor.key_pressed.connect(self._on_key_pressed)
if self._highlight_caret:
self.editor.cursorPositionChanged.connect(
self._highlight_caret_scope)
self._block_nbr = -1
self.editor.new_text_set.connect... | def on_state_changed(self, state) | On state changed we (dis)connect to the cursorPositionChanged signal | 2.668843 | 2.532282 | 1.053928 |
delete_request = event.key() in [QtCore.Qt.Key_Backspace,
QtCore.Qt.Key_Delete]
if event.text() or delete_request:
cursor = self.editor.textCursor()
if cursor.hasSelection():
# change selection to encompass the who... | def _on_key_pressed(self, event) | Override key press to select the current scope if the user wants
to deleted a folded scope (without selecting it). | 3.436329 | 3.146558 | 1.092091 |
if not event.isAccepted():
if event.key() == Qt.Key_Return or event.key() == Qt.Key_Enter:
cursor = self.editor.textCursor()
pre, post = self._get_indent(cursor)
cursor.beginEditBlock()
cursor.insertText("%s\n%s" % (pre, post))... | def _on_key_pressed(self, event) | Auto indent if the released key is the return key.
:param event: the key event | 3.120832 | 3.122151 | 0.999577 |
github_signature = headers.get("x-hub-signature")
if not github_signature:
json_abort(401, "X-Hub-Signature header missing.")
gh_webhook_secret = current_app.config["GITHUB_WEBHOOK_SECRET"]
signature = "sha1={}".format(
hmac.new(
gh_webho... | def verify_signature(self, payload, headers) | Verify that the payload was sent from our GitHub instance. | 2.263666 | 2.10722 | 1.074243 |
(options, args) = self.parser.parse_args()
# Set values from .visdkrc, but only if they haven't already been set
visdkrc_opts = self.read_visdkrc()
for opt in self.config_vars:
if not getattr(options, opt):
# Try and use value from visdkrc
... | def get_options(self) | Get the options that have been set.
Called after the user has added all their own options
and is ready to use the variables. | 3.291748 | 3.294635 | 0.999124 |
repo_jobs = []
for rel_job_file_path, job_info in self.job_files.items():
LOGGER.debug("Checking for job definitions in %s", rel_job_file_path)
jobs = self.parse_job_definitions(rel_job_file_path, job_info)
LOGGER.debug("Found %d job definitions in %s", len(j... | def parse_job_files(self) | Check for job definitions in known zuul files. | 2.272688 | 2.043925 | 1.111923 |
self._process.write(('cd %s\n' % directory).encode())
if sys.platform == 'win32':
self._process.write((os.path.splitdrive(directory)[0] + '\r\n').encode())
self.clear()
else:
self._process.write(b'\x0C') | def change_directory(self, directory) | Changes the current directory.
Change is made by running a "cd" command followed by a "clear" command.
:param directory:
:return: | 3.631298 | 3.262304 | 1.113108 |
if isinstance(self._icon, str):
if QtGui.QIcon.hasThemeIcon(self._icon):
return QtGui.QIcon.fromTheme(self._icon)
else:
return QtGui.QIcon(self._icon)
elif isinstance(self._icon, tuple):
return QtGui.QIcon.fromTheme(self._icon[... | def icon(self) | Gets the icon file name. Read-only. | 1.842522 | 1.816881 | 1.014113 |
self._markers.append(marker)
doc = self.editor.document()
assert isinstance(doc, QtGui.QTextDocument)
block = doc.findBlockByLineNumber(marker._position)
marker.block = block
d = TextDecoration(block)
d.set_full_width()
if self._background:
... | def add_marker(self, marker) | Adds the marker to the panel.
:param marker: Marker to add
:type marker: pyqode.core.modes.Marker | 4.154117 | 4.151318 | 1.000674 |
self._markers.remove(marker)
self._to_remove.append(marker)
if hasattr(marker, 'decoration'):
self.editor.decorations.remove(marker.decoration)
self.repaint() | def remove_marker(self, marker) | Removes a marker from the panel
:param marker: Marker to remove
:type marker: pyqode.core.Marker | 4.133329 | 4.017268 | 1.028891 |
markers = []
for marker in self._markers:
if line == marker.position:
markers.append(marker)
return markers | def marker_for_line(self, line) | Returns the marker that is displayed at the specified line number if
any.
:param line: The marker line.
:return: Marker of None
:rtype: pyqode.core.Marker | 3.848851 | 5.517889 | 0.697522 |
QtWidgets.QToolTip.showText(self.mapToGlobal(QtCore.QPoint(
self.sizeHint().width(), top)), tooltip, self) | def _display_tooltip(self, tooltip, top) | Display tooltip at the specified top position. | 3.81171 | 3.798882 | 1.003377 |
start = 0
while True:
start = string.find(sub, start)
if start == -1:
return
if whole_word:
if start:
pchar = string[start - 1]
else:
pchar = ' '
try:
nchar = string[start + len(sub)]
... | def finditer_noregex(string, sub, whole_word) | Search occurrences using str.find instead of regular expressions.
:param string: string to parse
:param sub: search string
:param whole_word: True to select whole words only | 2.834725 | 3.409515 | 0.831416 |
if not sub:
return
if regex:
flags = re.MULTILINE
if not case_sensitive:
flags |= re.IGNORECASE
for val in re.finditer(sub, string, flags):
yield val.span()
else:
if not case_sensitive:
string = string.lower()
sub =... | def findalliter(string, sub, regex=False, case_sensitive=False,
whole_word=False) | Generator that finds all occurrences of ``sub`` in ``string``
:param string: string to parse
:param sub: string to search
:param regex: True to search using regex
:param case_sensitive: True to match case, False to ignore case
:param whole_word: True to returns only whole words
:return: | 2.3179 | 2.493044 | 0.929747 |
return list(findalliter(
data['string'], data['sub'], regex=data['regex'],
whole_word=data['whole_word'], case_sensitive=data['case_sensitive'])) | def findall(data) | Worker that finds all occurrences of a given string (or regex)
in a given text.
:param data: Request data dict::
{
'string': string to search in text
'sub': input text
'regex': True to consider string as a regular expression
'whole_word': True to match wh... | 6.150455 | 4.020741 | 1.529682 |
# replace all possible separators with a default sep
default_sep = seps[0]
for sep in seps[1:]:
if sep:
txt = txt.replace(sep, default_sep)
# now we can split using the default_sep
raw_words = txt.split(default_sep)
words = set()
... | def split(txt, seps) | Splits a text in a meaningful list of words based on a list of word
separators (define in pyqode.core.settings)
:param txt: Text to split
:param seps: List of words separators
:return: A **set** of words found in the document (excluding
punctuations, numbers, ...) | 3.397833 | 3.560479 | 0.954319 |
completions = []
for word in self.split(code, self.separators):
completions.append({'name': word})
return completions | def complete(self, code, *args) | Provides completions based on the document words.
:param code: code to complete
:param args: additional (unused) arguments. | 7.164122 | 6.933118 | 1.033319 |
strings = {CheckerMessages.INFO: "Info",
CheckerMessages.WARNING: "Warning",
CheckerMessages.ERROR: "Error"}
return strings[status] | def status_to_string(cls, status) | Converts a message status to a string.
:param status: Status to convert (p yqode.core.modes.CheckerMessages)
:return: The status string.
:rtype: str | 5.005545 | 3.570641 | 1.401862 |
# remove old messages
if len(messages) > self.limit:
messages = messages[:self.limit]
_logger(self.__class__).log(5, 'adding %s messages' % len(messages))
self._finished = False
self._new_messages = messages
self._to_check = list(self._messages)
... | def add_messages(self, messages) | Adds a message or a list of message.
:param messages: A list of messages or a single message | 6.125125 | 6.877932 | 0.890548 |
import time
_logger(self.__class__).log(5, 'removing message %s' % message)
t = time.time()
usd = message.block.userData()
if usd:
try:
usd.messages.remove(message)
except (AttributeError, ValueError):
pass
... | def remove_message(self, message) | Removes a message.
:param message: Message to remove | 5.754939 | 5.668507 | 1.015248 |
while len(self._messages):
msg = self._messages.pop(0)
usd = msg.block.userData()
if usd and hasattr(usd, 'messages'):
usd.messages[:] = []
if msg.decoration:
self.editor.decorations.remove(msg.decoration) | def clear_messages(self) | Clears all messages. | 5.194419 | 5.118902 | 1.014753 |
messages = []
for msg in results:
msg = CheckerMessage(*msg)
if msg.line >= self.editor.blockCount():
msg.line = self.editor.blockCount() - 1
block = self.editor.document().findBlockByNumber(msg.line)
msg.block = block
... | def _on_work_finished(self, results) | Display results.
:param status: Response status
:param results: Response data, messages. | 3.533982 | 3.939826 | 0.896989 |
if self._finished:
_logger(self.__class__).log(5, 'running analysis')
self._job_runner.request_job(self._request)
elif self.editor:
# retry later
_logger(self.__class__).log(
5, 'delaying analysis (previous analysis not finished)')... | def request_analysis(self) | Requests an analysis. | 6.643767 | 6.61435 | 1.004447 |
try:
self.editor.toPlainText()
except (TypeError, RuntimeError):
return
try:
max_line_length = self.editor.modes.get(
'RightMarginMode').position
except KeyError:
max_line_length = 79
request_data = {
... | def _request(self) | Requests a checking of the editor content. | 4.058424 | 3.873272 | 1.047802 |
try:
return os.openpty()
except (AttributeError, OSError):
pass
master_fd, slave_name = _open_terminal()
slave_fd = slave_open(slave_name)
return master_fd, slave_fd | def openpty() | openpty() -> (master_fd, slave_fd)
Open a pty master/slave pair, using os.openpty() if possible. | 3.842326 | 3.104084 | 1.237829 |
try:
master_fd, slave_fd = os.openpty()
except (AttributeError, OSError):
pass
else:
slave_name = os.ttyname(slave_fd)
os.close(slave_fd)
return master_fd, slave_name
return _open_terminal() | def master_open() | master_open() -> (master_fd, slave_name)
Open a pty master and return the fd, and the filename of the slave end.
Deprecated, use openpty() instead. | 2.942183 | 2.344769 | 1.254786 |
for x in 'pqrstuvwxyzPQRST':
for y in '0123456789abcdef':
pty_name = '/dev/pty' + x + y
try:
fd = os.open(pty_name, os.O_RDWR)
except OSError:
continue
return (fd, '/dev/tty' + x + y)
raise OSError('out of pty devices') | def _open_terminal() | Open pty master and return (master_fd, tty_name). | 3.546121 | 2.757404 | 1.286036 |
result = os.open(tty_name, os.O_RDWR)
try:
from fcntl import ioctl, I_PUSH
except ImportError:
return result
try:
ioctl(result, I_PUSH, "ptem")
ioctl(result, I_PUSH, "ldterm")
except OSError:
pass
return result | def slave_open(tty_name) | slave_open(tty_name) -> slave_fd
Open the pty slave and acquire the controlling terminal, returning
opened filedescriptor.
Deprecated, use openpty() instead. | 4.001425 | 3.806487 | 1.051212 |
try:
pid, fd = os.forkpty()
except (AttributeError, OSError):
pass
else:
if pid == CHILD:
try:
os.setsid()
except OSError:
# os.forkpty() already set us session leader
pass
return pid, fd
maste... | def fork() | fork() -> (pid, master_fd)
Fork and make the child a session leader with a controlling terminal. | 3.079499 | 2.802325 | 1.098908 |
while data:
n = os.write(fd, data)
data = data[n:] | def _writen(fd, data) | Write all the data to a descriptor. | 2.857711 | 3.056977 | 0.934816 |
fds = [master_fd, STDIN_FILENO]
while True:
rfds, wfds, xfds = select(fds, [], [])
if master_fd in rfds:
data = master_read(master_fd)
if not data: # Reached EOF.
return
else:
os.write(STDOUT_FILENO, data)
if STDIN... | def _copy(master_fd, master_read=_read, stdin_read=_read) | Parent copy loop.
Copies
pty master -> standard output (master_read)
standard input -> pty master (stdin_read) | 2.018039 | 1.968475 | 1.025179 |
if type(argv) == type(''):
argv = (argv,)
pid, master_fd = fork()
if pid == CHILD:
try:
os.execlp(argv[0], *argv)
except:
# If we wanted to be really clever, we would use
# the same method as subprocess() to pass the error
# back t... | def spawn(argv, master_read=_read, stdin_read=_read) | Create a spawned process. | 3.750967 | 3.71428 | 1.009877 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.