repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
johntruckenbrodt/spatialist
spatialist/vector.py
Vector.convert2wkt
def convert2wkt(self, set3D=True): """ export the geometry of each feature as a wkt string Parameters ---------- set3D: bool keep the third (height) dimension? Returns ------- """ 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.geometry().ExportToWkt() for feature in features]
python
def convert2wkt(self, set3D=True): """ export the geometry of each feature as a wkt string Parameters ---------- set3D: bool keep the third (height) dimension? Returns ------- """ 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.geometry().ExportToWkt() for feature in features]
[ "def", "convert2wkt", "(", "self", ",", "set3D", "=", "True", ")", ":", "features", "=", "self", ".", "getfeatures", "(", ")", "for", "feature", "in", "features", ":", "try", ":", "feature", ".", "geometry", "(", ")", ".", "Set3D", "(", "set3D", ")",...
export the geometry of each feature as a wkt string Parameters ---------- set3D: bool keep the third (height) dimension? Returns -------
[ "export", "the", "geometry", "of", "each", "feature", "as", "a", "wkt", "string" ]
007f49296a156de8d7168ad235b5a5b8e8d3633d
https://github.com/johntruckenbrodt/spatialist/blob/007f49296a156de8d7168ad235b5a5b8e8d3633d/spatialist/vector.py#L244-L265
train
46,300
johntruckenbrodt/spatialist
spatialist/vector.py
Vector.getFeatureByAttribute
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` the feature(s) matching the search query """ 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) field = field.strip() if isinstance(field, str) else field if field == attr: out.append(feature.Clone()) self.layer.ResetReading() if len(out) == 0: return None elif len(out) == 1: return out[0] else: return out
python
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` the feature(s) matching the search query """ 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) field = field.strip() if isinstance(field, str) else field if field == attr: out.append(feature.Clone()) self.layer.ResetReading() if len(out) == 0: return None elif len(out) == 1: return out[0] else: return out
[ "def", "getFeatureByAttribute", "(", "self", ",", "fieldname", ",", "attribute", ")", ":", "attr", "=", "attribute", ".", "strip", "(", ")", "if", "isinstance", "(", "attribute", ",", "str", ")", "else", "attribute", "if", "fieldname", "not", "in", "self",...
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` the feature(s) matching the search query
[ "get", "features", "by", "field", "attribute" ]
007f49296a156de8d7168ad235b5a5b8e8d3633d
https://github.com/johntruckenbrodt/spatialist/blob/007f49296a156de8d7168ad235b5a5b8e8d3633d/spatialist/vector.py#L322-L354
train
46,301
johntruckenbrodt/spatialist
spatialist/vector.py
Vector.init_layer
def init_layer(self): """ initialize a layer object Returns ------- """ self.layer = self.vector.GetLayer() self.__features = [None] * self.nfeatures
python
def init_layer(self): """ initialize a layer object Returns ------- """ self.layer = self.vector.GetLayer() self.__features = [None] * self.nfeatures
[ "def", "init_layer", "(", "self", ")", ":", "self", ".", "layer", "=", "self", ".", "vector", ".", "GetLayer", "(", ")", "self", ".", "__features", "=", "[", "None", "]", "*", "self", ".", "nfeatures" ]
initialize a layer object Returns -------
[ "initialize", "a", "layer", "object" ]
007f49296a156de8d7168ad235b5a5b8e8d3633d
https://github.com/johntruckenbrodt/spatialist/blob/007f49296a156de8d7168ad235b5a5b8e8d3633d/spatialist/vector.py#L433-L442
train
46,302
johntruckenbrodt/spatialist
spatialist/vector.py
Vector.load
def load(self): """ load all feature into memory Returns ------- """ self.layer.ResetReading() for i in range(self.nfeatures): if self.__features[i] is None: self.__features[i] = self.layer[i]
python
def load(self): """ load all feature into memory Returns ------- """ self.layer.ResetReading() for i in range(self.nfeatures): if self.__features[i] is None: self.__features[i] = self.layer[i]
[ "def", "load", "(", "self", ")", ":", "self", ".", "layer", ".", "ResetReading", "(", ")", "for", "i", "in", "range", "(", "self", ".", "nfeatures", ")", ":", "if", "self", ".", "__features", "[", "i", "]", "is", "None", ":", "self", ".", "__feat...
load all feature into memory Returns -------
[ "load", "all", "feature", "into", "memory" ]
007f49296a156de8d7168ad235b5a5b8e8d3633d
https://github.com/johntruckenbrodt/spatialist/blob/007f49296a156de8d7168ad235b5a5b8e8d3633d/spatialist/vector.py#L466-L477
train
46,303
johntruckenbrodt/spatialist
spatialist/vector.py
Vector.reproject
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 ------- """ 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 = self.geomType features = self.getfeatures() feat_def = features[0].GetDefnRef() fields = [feat_def.GetFieldDefn(x) for x in range(0, feat_def.GetFieldCount())] self.__init__() self.addlayer(layername, srs_out, geomType) self.layer.CreateFields(fields) for feature in features: geom = feature.GetGeometryRef() geom.Transform(coordTrans) newfeature = feature.Clone() newfeature.SetGeometry(geom) self.layer.CreateFeature(newfeature) newfeature = None self.init_features()
python
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 ------- """ 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 = self.geomType features = self.getfeatures() feat_def = features[0].GetDefnRef() fields = [feat_def.GetFieldDefn(x) for x in range(0, feat_def.GetFieldCount())] self.__init__() self.addlayer(layername, srs_out, geomType) self.layer.CreateFields(fields) for feature in features: geom = feature.GetGeometryRef() geom.Transform(coordTrans) newfeature = feature.Clone() newfeature.SetGeometry(geom) self.layer.CreateFeature(newfeature) newfeature = None self.init_features()
[ "def", "reproject", "(", "self", ",", "projection", ")", ":", "srs_out", "=", "crsConvert", "(", "projection", ",", "'osr'", ")", "if", "self", ".", "srs", ".", "IsSame", "(", "srs_out", ")", "==", "0", ":", "# create the CoordinateTransformation", "coordTra...
in-memory reprojection Parameters ---------- projection: int, str or :osgeo:class:`osr.SpatialReference` the target CRS. See :func:`spatialist.auxil.crsConvert`. Returns -------
[ "in", "-", "memory", "reprojection" ]
007f49296a156de8d7168ad235b5a5b8e8d3633d
https://github.com/johntruckenbrodt/spatialist/blob/007f49296a156de8d7168ad235b5a5b8e8d3633d/spatialist/vector.py#L523-L560
train
46,304
johntruckenbrodt/spatialist
spatialist/vector.py
Vector.write
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 ------- """ (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: raise RuntimeError('target file already exists') outdataset = driver.CreateDataSource(outfile) outlayer = outdataset.CreateLayer(self.layername, geom_type=self.geomType) outlayerdef = outlayer.GetLayerDefn() for fieldDef in self.fieldDefs: outlayer.CreateField(fieldDef) self.layer.ResetReading() for feature in self.layer: outFeature = ogr.Feature(outlayerdef) outFeature.SetGeometry(feature.GetGeometryRef()) for name in self.fieldnames: outFeature.SetField(name, feature.GetField(name)) # add the feature to the shapefile outlayer.CreateFeature(outFeature) outFeature = None self.layer.ResetReading() if format == 'ESRI Shapefile': srs_out = self.srs.Clone() srs_out.MorphToESRI() with open(os.path.join(outfilepath, basename + '.prj'), 'w') as prj: prj.write(srs_out.ExportToWkt()) outdataset = None
python
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 ------- """ (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: raise RuntimeError('target file already exists') outdataset = driver.CreateDataSource(outfile) outlayer = outdataset.CreateLayer(self.layername, geom_type=self.geomType) outlayerdef = outlayer.GetLayerDefn() for fieldDef in self.fieldDefs: outlayer.CreateField(fieldDef) self.layer.ResetReading() for feature in self.layer: outFeature = ogr.Feature(outlayerdef) outFeature.SetGeometry(feature.GetGeometryRef()) for name in self.fieldnames: outFeature.SetField(name, feature.GetField(name)) # add the feature to the shapefile outlayer.CreateFeature(outFeature) outFeature = None self.layer.ResetReading() if format == 'ESRI Shapefile': srs_out = self.srs.Clone() srs_out.MorphToESRI() with open(os.path.join(outfilepath, basename + '.prj'), 'w') as prj: prj.write(srs_out.ExportToWkt()) outdataset = None
[ "def", "write", "(", "self", ",", "outfile", ",", "format", "=", "'ESRI Shapefile'", ",", "overwrite", "=", "True", ")", ":", "(", "outfilepath", ",", "outfilename", ")", "=", "os", ".", "path", ".", "split", "(", "outfile", ")", "basename", "=", "os",...
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 -------
[ "write", "the", "Vector", "object", "to", "a", "file" ]
007f49296a156de8d7168ad235b5a5b8e8d3633d
https://github.com/johntruckenbrodt/spatialist/blob/007f49296a156de8d7168ad235b5a5b8e8d3633d/spatialist/vector.py#L614-L666
train
46,305
svenkreiss/databench
databench_py/singlethread/meta.py
Meta._init_zmq
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. """ 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 {}' ''.format(self.analysis.id_, port_subscribe)) self.zmq_sub_ctx = zmq.Context() self.zmq_sub = self.zmq_sub_ctx.socket(zmq.SUB) self.zmq_sub.setsockopt(zmq.SUBSCRIBE, self.analysis.id_.encode('utf-8')) self.zmq_sub.connect('tcp://127.0.0.1:{}'.format(port_subscribe)) self.zmq_stream_sub = zmq.eventloop.zmqstream.ZMQStream(self.zmq_sub) self.zmq_stream_sub.on_recv(self.zmq_listener) # send zmq handshakes until a zmq ack is received self.zmq_ack = False self.send_handshake()
python
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. """ 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 {}' ''.format(self.analysis.id_, port_subscribe)) self.zmq_sub_ctx = zmq.Context() self.zmq_sub = self.zmq_sub_ctx.socket(zmq.SUB) self.zmq_sub.setsockopt(zmq.SUBSCRIBE, self.analysis.id_.encode('utf-8')) self.zmq_sub.connect('tcp://127.0.0.1:{}'.format(port_subscribe)) self.zmq_stream_sub = zmq.eventloop.zmqstream.ZMQStream(self.zmq_sub) self.zmq_stream_sub.on_recv(self.zmq_listener) # send zmq handshakes until a zmq ack is received self.zmq_ack = False self.send_handshake()
[ "def", "_init_zmq", "(", "self", ",", "port_publish", ",", "port_subscribe", ")", ":", "log", ".", "debug", "(", "'kernel {} publishing on port {}'", "''", ".", "format", "(", "self", ".", "analysis", ".", "id_", ",", "port_publish", ")", ")", "self", ".", ...
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.
[ "Initialize", "zmq", "messaging", "." ]
99d4adad494b60a42af6b8bfba94dd0c41ba0786
https://github.com/svenkreiss/databench/blob/99d4adad494b60a42af6b8bfba94dd0c41ba0786/databench_py/singlethread/meta.py#L52-L78
train
46,306
svenkreiss/databench
databench_py/singlethread/meta.py
Meta.emit
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. """ 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'))
python
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. """ 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", ")", ":", "log", ".", "debug", "(", "'kernel {} zmq send ({}): {}'", "''", ".", "format", "(", "analysis_id", ",", "signal", ",", "message", ")", ")", "self", ".", "zmq_publish"...
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.
[ "Emit", "signal", "to", "main", "." ]
99d4adad494b60a42af6b8bfba94dd0c41ba0786
https://github.com/svenkreiss/databench/blob/99d4adad494b60a42af6b8bfba94dd0c41ba0786/databench_py/singlethread/meta.py#L191-L206
train
46,307
MLAB-project/pymlab
src/pymlab/sensors/gpio.py
DS4520.set_ports
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.' self.bus.write_byte_data(self.address, self.CONTROL_PORT0, port0) self.bus.write_byte_data(self.address, self.CONTROL_PORT0, port1) return
python
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.' 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", ")", ":", "self", ".", "bus", ".", "write_byte_data", "(", "self", ".", "address", ",", "self", ".", "CONTROL_PORT0", ",", "port0", ")", "self", ".", "bus", ".", ...
Writes specified value to the pins defined as output by method. Writing to input pins has no effect.
[ "Writes", "specified", "value", "to", "the", "pins", "defined", "as", "output", "by", "method", ".", "Writing", "to", "input", "pins", "has", "no", "effect", "." ]
d18d858ae83b203defcf2aead0dbd11b3c444658
https://github.com/MLAB-project/pymlab/blob/d18d858ae83b203defcf2aead0dbd11b3c444658/src/pymlab/sensors/gpio.py#L242-L246
train
46,308
vladsaveliev/TargQC
targqc/utilz/gtf.py
get_gtf_db
def get_gtf_db(gtf, in_memory=False): """ create a gffutils DB """ 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...') infer_extent = guess_infer_extent(gtf) db = gffutils.create_db(gtf, dbfn=db_file, infer_gene_extent=infer_extent) return db else: return gffutils.FeatureDB(db_file)
python
def get_gtf_db(gtf, in_memory=False): """ create a gffutils DB """ 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...') infer_extent = guess_infer_extent(gtf) db = gffutils.create_db(gtf, dbfn=db_file, infer_gene_extent=infer_extent) return db else: return gffutils.FeatureDB(db_file)
[ "def", "get_gtf_db", "(", "gtf", ",", "in_memory", "=", "False", ")", ":", "db_file", "=", "gtf", "+", "'.db'", "if", "gtf", ".", "endswith", "(", "'.gz'", ")", ":", "db_file", "=", "gtf", "[", ":", "-", "3", "]", "+", "'.db'", "if", "file_exists",...
create a gffutils DB
[ "create", "a", "gffutils", "DB" ]
e887c36b2194dbd73c6ea32989b6cb84c6c0e58d
https://github.com/vladsaveliev/TargQC/blob/e887c36b2194dbd73c6ea32989b6cb84c6c0e58d/targqc/utilz/gtf.py#L36-L53
train
46,309
vladsaveliev/TargQC
targqc/utilz/gtf.py
gtf_to_bed
def gtf_to_bed(gtf, alt_out_dir=None): """ create a BED file of transcript-level features with attached gene name or gene ids """ 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_file = os.path.join(alt_out_dir, os.path.basename(out_file)) with open(out_file, "w") as out_handle: db = get_gtf_db(gtf) for feature in db.features_of_type('transcript', order_by=("seqid", "start", "end")): chrom = feature.chrom start = feature.start end = feature.end attributes = feature.attributes.keys() strand = feature.strand name = (feature['gene_name'][0] if 'gene_name' in attributes else feature['gene_id'][0]) line = "\t".join([str(x) for x in [chrom, start, end, name, ".", strand]]) out_handle.write(line + "\n") return out_file
python
def gtf_to_bed(gtf, alt_out_dir=None): """ create a BED file of transcript-level features with attached gene name or gene ids """ 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_file = os.path.join(alt_out_dir, os.path.basename(out_file)) with open(out_file, "w") as out_handle: db = get_gtf_db(gtf) for feature in db.features_of_type('transcript', order_by=("seqid", "start", "end")): chrom = feature.chrom start = feature.start end = feature.end attributes = feature.attributes.keys() strand = feature.strand name = (feature['gene_name'][0] if 'gene_name' in attributes else feature['gene_id'][0]) line = "\t".join([str(x) for x in [chrom, start, end, name, ".", strand]]) out_handle.write(line + "\n") return out_file
[ "def", "gtf_to_bed", "(", "gtf", ",", "alt_out_dir", "=", "None", ")", ":", "out_file", "=", "os", ".", "path", ".", "splitext", "(", "gtf", ")", "[", "0", "]", "+", "'.bed'", "if", "file_exists", "(", "out_file", ")", ":", "return", "out_file", "if"...
create a BED file of transcript-level features with attached gene name or gene ids
[ "create", "a", "BED", "file", "of", "transcript", "-", "level", "features", "with", "attached", "gene", "name", "or", "gene", "ids" ]
e887c36b2194dbd73c6ea32989b6cb84c6c0e58d
https://github.com/vladsaveliev/TargQC/blob/e887c36b2194dbd73c6ea32989b6cb84c6c0e58d/targqc/utilz/gtf.py#L55-L81
train
46,310
vladsaveliev/TargQC
targqc/utilz/gtf.py
tx2genefile
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 """ 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: for k, v in transcript_to_gene(gtf).items(): out_handle.write(",".join([k, v]) + "\n") return out_file
python
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 """ 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: for k, v in transcript_to_gene(gtf).items(): out_handle.write(",".join([k, v]) + "\n") return out_file
[ "def", "tx2genefile", "(", "gtf", ",", "out_file", "=", "None", ")", ":", "installed_tx2gene", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "gtf", ")", ",", "\"tx2gene.csv\"", ")", "if", "file_exists", "(", "install...
write out a file of transcript->gene mappings. use the installed tx2gene.csv if it exists, else write a new one out
[ "write", "out", "a", "file", "of", "transcript", "-", ">", "gene", "mappings", ".", "use", "the", "installed", "tx2gene", ".", "csv", "if", "it", "exists", "else", "write", "a", "new", "one", "out" ]
e887c36b2194dbd73c6ea32989b6cb84c6c0e58d
https://github.com/vladsaveliev/TargQC/blob/e887c36b2194dbd73c6ea32989b6cb84c6c0e58d/targqc/utilz/gtf.py#L183-L197
train
46,311
vladsaveliev/TargQC
targqc/utilz/gtf.py
transcript_to_gene
def transcript_to_gene(gtf): """ return a dictionary keyed by transcript_id of the associated gene_id """ 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
python
def transcript_to_gene(gtf): """ return a dictionary keyed by transcript_id of the associated gene_id """ 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", ")", ":", "gene_lookup", "=", "{", "}", "for", "feature", "in", "complete_features", "(", "get_gtf_db", "(", "gtf", ")", ")", ":", "gene_id", "=", "feature", ".", "attributes", ".", "get", "(", "'gene_id'", ",", "...
return a dictionary keyed by transcript_id of the associated gene_id
[ "return", "a", "dictionary", "keyed", "by", "transcript_id", "of", "the", "associated", "gene_id" ]
e887c36b2194dbd73c6ea32989b6cb84c6c0e58d
https://github.com/vladsaveliev/TargQC/blob/e887c36b2194dbd73c6ea32989b6cb84c6c0e58d/targqc/utilz/gtf.py#L199-L208
train
46,312
MLAB-project/pymlab
src/pymlab/sensors/clkgen.py
CLKGEN01.set_freq
def set_freq(self, fout, freq): """ Sets new output frequency, required parameters are real current frequency at output and new required frequency. """ 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)*1e6/fout) > 3500: # Large change of frequency fdco = fout * hsdiv * n1div # calculate high frequency oscillator fxtal = fdco / self.get_rfreq() # should be fxtal = 114.285 for hsdiv_iter in hsdiv_tuple: # find dividers with minimal power consumption for n1div_iter in n1div_tuple: fdco_new = freq * hsdiv_iter * n1div_iter if (fdco_new >= 4850) and (fdco_new <= 5670): if (fdco_new <= fdco_min): fdco_min = fdco_new hsdiv = hsdiv_iter n1div = n1div_iter rfreq = fdco_min / fxtal self.freeze_dco() # write registers self.set_hs_div(hsdiv) self.set_n1_div(n1div) self.set_rfreq(rfreq) self.unfreeze_dco() self.new_freq() else: # Small change of frequency rfreq = self.get_rfreq() * (freq/fout) self.freeze_m() # write registers self.set_rfreq(rfreq) self.unfreeze_m()
python
def set_freq(self, fout, freq): """ Sets new output frequency, required parameters are real current frequency at output and new required frequency. """ 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)*1e6/fout) > 3500: # Large change of frequency fdco = fout * hsdiv * n1div # calculate high frequency oscillator fxtal = fdco / self.get_rfreq() # should be fxtal = 114.285 for hsdiv_iter in hsdiv_tuple: # find dividers with minimal power consumption for n1div_iter in n1div_tuple: fdco_new = freq * hsdiv_iter * n1div_iter if (fdco_new >= 4850) and (fdco_new <= 5670): if (fdco_new <= fdco_min): fdco_min = fdco_new hsdiv = hsdiv_iter n1div = n1div_iter rfreq = fdco_min / fxtal self.freeze_dco() # write registers self.set_hs_div(hsdiv) self.set_n1_div(n1div) self.set_rfreq(rfreq) self.unfreeze_dco() self.new_freq() else: # Small change of frequency rfreq = self.get_rfreq() * (freq/fout) self.freeze_m() # write registers self.set_rfreq(rfreq) self.unfreeze_m()
[ "def", "set_freq", "(", "self", ",", "fout", ",", "freq", ")", ":", "hsdiv_tuple", "=", "(", "4", ",", "5", ",", "6", ",", "7", ",", "9", ",", "11", ")", "# possible dividers", "n1div_tuple", "=", "(", "1", ",", ")", "+", "tuple", "(", "range", ...
Sets new output frequency, required parameters are real current frequency at output and new required frequency.
[ "Sets", "new", "output", "frequency", "required", "parameters", "are", "real", "current", "frequency", "at", "output", "and", "new", "required", "frequency", "." ]
d18d858ae83b203defcf2aead0dbd11b3c444658
https://github.com/MLAB-project/pymlab/blob/d18d858ae83b203defcf2aead0dbd11b3c444658/src/pymlab/sensors/clkgen.py#L102-L139
train
46,313
svenkreiss/databench
databench/scaffold.py
check_folders
def check_folders(name): """Only checks and asks questions. Nothing is written to disk.""" 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.exists(os.path.join(os.getcwd(), 'analyses')): correct = input('This is the first analysis here. Do ' 'you want to continue? (y/N)') if correct != 'y': return False if os.path.exists(os.path.join(os.getcwd(), 'analyses', name)): correct = input('An analysis with this name exists already. Do ' 'you want to continue? (y/N)') if correct != 'y': return False return True
python
def check_folders(name): """Only checks and asks questions. Nothing is written to disk.""" 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.exists(os.path.join(os.getcwd(), 'analyses')): correct = input('This is the first analysis here. Do ' 'you want to continue? (y/N)') if correct != 'y': return False if os.path.exists(os.path.join(os.getcwd(), 'analyses', name)): correct = input('An analysis with this name exists already. Do ' 'you want to continue? (y/N)') if correct != 'y': return False return True
[ "def", "check_folders", "(", "name", ")", ":", "if", "os", ".", "getcwd", "(", ")", ".", "endswith", "(", "'analyses'", ")", ":", "correct", "=", "input", "(", "'You are in an analyses folder. This will create '", "'another analyses folder inside this one. Do '", "'yo...
Only checks and asks questions. Nothing is written to disk.
[ "Only", "checks", "and", "asks", "questions", ".", "Nothing", "is", "written", "to", "disk", "." ]
99d4adad494b60a42af6b8bfba94dd0c41ba0786
https://github.com/svenkreiss/databench/blob/99d4adad494b60a42af6b8bfba94dd0c41ba0786/databench/scaffold.py#L12-L34
train
46,314
svenkreiss/databench
databench/scaffold.py
create_analyses
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. """ 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_path = os.path.join(os.getcwd(), 'analyses', 'index.yaml') if not os.path.exists(index_path): with open(index_path, 'w') as f: f.write('title: Analyses\n') f.write('description: A short description.\n') f.write('version: 0.1.0\n') f.write('\n') f.write('analyses:\n') if kernel is None: with open(index_path, 'a') as f: f.write(' # automatically inserted by scaffold-databench\n') f.write(' - name: {}\n'.format(name)) f.write(' title: {}\n'.format(name.title())) f.write(' description: A new analysis.\n') f.write(' watch:\n') f.write(' - {}/*.js\n'.format(name)) f.write(' - {}/*.html\n'.format(name))
python
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. """ 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_path = os.path.join(os.getcwd(), 'analyses', 'index.yaml') if not os.path.exists(index_path): with open(index_path, 'w') as f: f.write('title: Analyses\n') f.write('description: A short description.\n') f.write('version: 0.1.0\n') f.write('\n') f.write('analyses:\n') if kernel is None: with open(index_path, 'a') as f: f.write(' # automatically inserted by scaffold-databench\n') f.write(' - name: {}\n'.format(name)) f.write(' title: {}\n'.format(name.title())) f.write(' description: A new analysis.\n') f.write(' watch:\n') f.write(' - {}/*.js\n'.format(name)) f.write(' - {}/*.html\n'.format(name))
[ "def", "create_analyses", "(", "name", ",", "kernel", "=", "None", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "os", ".", "path", ".", "join", "(", "os", ".", "getcwd", "(", ")", ",", "'analyses'", ")", ")", ":", "os", ".", "s...
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.
[ "Create", "an", "analysis", "with", "given", "name", "and", "suffix", "." ]
99d4adad494b60a42af6b8bfba94dd0c41ba0786
https://github.com/svenkreiss/databench/blob/99d4adad494b60a42af6b8bfba94dd0c41ba0786/databench/scaffold.py#L37-L71
train
46,315
svenkreiss/databench
databench/scaffold.py
create_analysis
def create_analysis(name, kernel, src_dir, scaffold_name): """Create analysis files.""" # 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__',) or \ any(f.endswith(ending) for ending in ('.pyc',)): continue copy_scaffold_file(os.path.join(src_dir, f), os.path.join(folder, f), name, scaffold_name)
python
def create_analysis(name, kernel, src_dir, scaffold_name): """Create analysis files.""" # 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__',) or \ any(f.endswith(ending) for ending in ('.pyc',)): continue copy_scaffold_file(os.path.join(src_dir, f), os.path.join(folder, f), name, scaffold_name)
[ "def", "create_analysis", "(", "name", ",", "kernel", ",", "src_dir", ",", "scaffold_name", ")", ":", "# analysis folder", "folder", "=", "os", ".", "path", ".", "join", "(", "os", ".", "getcwd", "(", ")", ",", "'analyses'", ",", "name", ")", "if", "no...
Create analysis files.
[ "Create", "analysis", "files", "." ]
99d4adad494b60a42af6b8bfba94dd0c41ba0786
https://github.com/svenkreiss/databench/blob/99d4adad494b60a42af6b8bfba94dd0c41ba0786/databench/scaffold.py#L100-L117
train
46,316
johntruckenbrodt/spatialist
spatialist/auxil.py
crsConvert
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:`osr.SpatialReference` the output CRS Examples -------- convert an integer EPSG code to PROJ4: >>> crsConvert(4326, 'proj4') '+proj=longlat +datum=WGS84 +no_defs ' convert a PROJ4 string to an opengis URL: >>> crsConvert('+proj=longlat +datum=WGS84 +no_defs ', 'opengis') 'http://www.opengis.net/def/crs/EPSG/0/4326' convert the opengis URL back to EPSG: >>> crsConvert('http://www.opengis.net/def/crs/EPSG/0/4326', 'epsg') 4326 convert an EPSG compound CRS (WGS84 horizontal + EGM96 vertical) >>> crsConvert('EPSG:4326+5773', 'proj4') '+proj=longlat +datum=WGS84 +geoidgrids=egm96_15.gtx +vunits=m +no_defs ' """ 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) except RuntimeError: raise TypeError('crsIn not recognized; must be of type WKT, PROJ4 or EPSG') else: raise TypeError('crsIn must be of type int, str or osr.SpatialReference') if crsOut == 'wkt': return srs.ExportToWkt() elif crsOut == 'prettyWkt': return srs.ExportToPrettyWkt() elif crsOut == 'proj4': return srs.ExportToProj4() elif crsOut == 'epsg': srs.AutoIdentifyEPSG() return int(srs.GetAuthorityCode(None)) elif crsOut == 'opengis': srs.AutoIdentifyEPSG() return 'http://www.opengis.net/def/crs/EPSG/0/{}'.format(srs.GetAuthorityCode(None)) elif crsOut == 'osr': return srs else: raise ValueError('crsOut not recognized; must be either wkt, proj4, opengis or epsg')
python
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:`osr.SpatialReference` the output CRS Examples -------- convert an integer EPSG code to PROJ4: >>> crsConvert(4326, 'proj4') '+proj=longlat +datum=WGS84 +no_defs ' convert a PROJ4 string to an opengis URL: >>> crsConvert('+proj=longlat +datum=WGS84 +no_defs ', 'opengis') 'http://www.opengis.net/def/crs/EPSG/0/4326' convert the opengis URL back to EPSG: >>> crsConvert('http://www.opengis.net/def/crs/EPSG/0/4326', 'epsg') 4326 convert an EPSG compound CRS (WGS84 horizontal + EGM96 vertical) >>> crsConvert('EPSG:4326+5773', 'proj4') '+proj=longlat +datum=WGS84 +geoidgrids=egm96_15.gtx +vunits=m +no_defs ' """ 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) except RuntimeError: raise TypeError('crsIn not recognized; must be of type WKT, PROJ4 or EPSG') else: raise TypeError('crsIn must be of type int, str or osr.SpatialReference') if crsOut == 'wkt': return srs.ExportToWkt() elif crsOut == 'prettyWkt': return srs.ExportToPrettyWkt() elif crsOut == 'proj4': return srs.ExportToProj4() elif crsOut == 'epsg': srs.AutoIdentifyEPSG() return int(srs.GetAuthorityCode(None)) elif crsOut == 'opengis': srs.AutoIdentifyEPSG() return 'http://www.opengis.net/def/crs/EPSG/0/{}'.format(srs.GetAuthorityCode(None)) elif crsOut == 'osr': return srs else: raise ValueError('crsOut not recognized; must be either wkt, proj4, opengis or epsg')
[ "def", "crsConvert", "(", "crsIn", ",", "crsOut", ")", ":", "if", "isinstance", "(", "crsIn", ",", "osr", ".", "SpatialReference", ")", ":", "srs", "=", "crsIn", ".", "Clone", "(", ")", "else", ":", "srs", "=", "osr", ".", "SpatialReference", "(", ")...
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:`osr.SpatialReference` the output CRS Examples -------- convert an integer EPSG code to PROJ4: >>> crsConvert(4326, 'proj4') '+proj=longlat +datum=WGS84 +no_defs ' convert a PROJ4 string to an opengis URL: >>> crsConvert('+proj=longlat +datum=WGS84 +no_defs ', 'opengis') 'http://www.opengis.net/def/crs/EPSG/0/4326' convert the opengis URL back to EPSG: >>> crsConvert('http://www.opengis.net/def/crs/EPSG/0/4326', 'epsg') 4326 convert an EPSG compound CRS (WGS84 horizontal + EGM96 vertical) >>> crsConvert('EPSG:4326+5773', 'proj4') '+proj=longlat +datum=WGS84 +geoidgrids=egm96_15.gtx +vunits=m +no_defs '
[ "convert", "between", "different", "types", "of", "spatial", "references" ]
007f49296a156de8d7168ad235b5a5b8e8d3633d
https://github.com/johntruckenbrodt/spatialist/blob/007f49296a156de8d7168ad235b5a5b8e8d3633d/spatialist/auxil.py#L14-L82
train
46,317
johntruckenbrodt/spatialist
spatialist/auxil.py
haversine
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 Returns ------- float the distance between point 1 and point 2 in meters """ 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
python
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 Returns ------- float the distance between point 1 and point 2 in meters """ 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", ")", ":", "radius", "=", "6371000", "lat1", ",", "lon1", ",", "lat2", ",", "lon2", "=", "map", "(", "math", ".", "radians", ",", "[", "lat1", ",", "lon1", ",", "lat2", ",", ...
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 Returns ------- float the distance between point 1 and point 2 in meters
[ "compute", "the", "distance", "in", "meters", "between", "two", "points", "in", "latlon" ]
007f49296a156de8d7168ad235b5a5b8e8d3633d
https://github.com/johntruckenbrodt/spatialist/blob/007f49296a156de8d7168ad235b5a5b8e8d3633d/spatialist/auxil.py#L85-L110
train
46,318
johntruckenbrodt/spatialist
spatialist/auxil.py
gdal_rasterize
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 ------- """ out = gdal.Rasterize(dst, src, options=gdal.RasterizeOptions(**options)) out = None
python
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 ------- """ out = gdal.Rasterize(dst, src, options=gdal.RasterizeOptions(**options)) out = None
[ "def", "gdal_rasterize", "(", "src", ",", "dst", ",", "options", ")", ":", "out", "=", "gdal", ".", "Rasterize", "(", "dst", ",", "src", ",", "options", "=", "gdal", ".", "RasterizeOptions", "(", "*", "*", "options", ")", ")", "out", "=", "None" ]
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 -------
[ "a", "simple", "wrapper", "for", "gdal", ".", "Rasterize" ]
007f49296a156de8d7168ad235b5a5b8e8d3633d
https://github.com/johntruckenbrodt/spatialist/blob/007f49296a156de8d7168ad235b5a5b8e8d3633d/spatialist/auxil.py#L218-L236
train
46,319
vladsaveliev/TargQC
targqc/utilz/proc_args.py
set_up_dirs
def set_up_dirs(proc_name, output_dir=None, work_dir=None, log_dir=None): """ Creates output_dir, work_dir, and sets up log """ 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 safe_mkdir(join(work_dir, 'log')), proc_name + '.log') return output_dir, work_dir, log_fpath
python
def set_up_dirs(proc_name, output_dir=None, work_dir=None, log_dir=None): """ Creates output_dir, work_dir, and sets up log """ 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 safe_mkdir(join(work_dir, 'log')), proc_name + '.log') return output_dir, work_dir, log_fpath
[ "def", "set_up_dirs", "(", "proc_name", ",", "output_dir", "=", "None", ",", "work_dir", "=", "None", ",", "log_dir", "=", "None", ")", ":", "output_dir", "=", "safe_mkdir", "(", "adjust_path", "(", "output_dir", "or", "join", "(", "os", ".", "getcwd", "...
Creates output_dir, work_dir, and sets up log
[ "Creates", "output_dir", "work_dir", "and", "sets", "up", "log" ]
e887c36b2194dbd73c6ea32989b6cb84c6c0e58d
https://github.com/vladsaveliev/TargQC/blob/e887c36b2194dbd73c6ea32989b6cb84c6c0e58d/targqc/utilz/proc_args.py#L112-L123
train
46,320
python-astrodynamics/spacetrack
spacetrack/base.py
_iter_content_generator
def _iter_content_generator(response, decode_unicode): """Generator used to yield 100 KiB chunks for a given response.""" 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 ['...\r', '\n...'], stril trailing \r chunk = chunk.rstrip('\r') yield chunk
python
def _iter_content_generator(response, decode_unicode): """Generator used to yield 100 KiB chunks for a given response.""" 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 ['...\r', '\n...'], stril trailing \r chunk = chunk.rstrip('\r') yield chunk
[ "def", "_iter_content_generator", "(", "response", ",", "decode_unicode", ")", ":", "for", "chunk", "in", "response", ".", "iter_content", "(", "100", "*", "1024", ",", "decode_unicode", "=", "decode_unicode", ")", ":", "if", "decode_unicode", ":", "# Replace CR...
Generator used to yield 100 KiB chunks for a given response.
[ "Generator", "used", "to", "yield", "100", "KiB", "chunks", "for", "a", "given", "response", "." ]
18f63b7de989a31b983d140a11418e01bd6fd398
https://github.com/python-astrodynamics/spacetrack/blob/18f63b7de989a31b983d140a11418e01bd6fd398/spacetrack/base.py#L640-L649
train
46,321
python-astrodynamics/spacetrack
spacetrack/base.py
SpaceTrackClient.generic_request
def generic_request(self, class_, iter_lines=False, iter_content=False, controller=None, parse_types=False, **kwargs): r"""Generic Space-Track query. The request class methods use this method internally; the public API is as follows: .. code-block:: python st.tle_publish(*args, **kw) st.basicspacedata.tle_publish(*args, **kw) st.file(*args, **kw) st.fileshare.file(*args, **kw) st.spephemeris.file(*args, **kw) They resolve to the following calls respectively: .. code-block:: python st.generic_request('tle_publish', *args, **kw) st.generic_request('tle_publish', *args, controller='basicspacedata', **kw) st.generic_request('file', *args, **kw) st.generic_request('file', *args, controller='fileshare', **kw) st.generic_request('file', *args, controller='spephemeris', **kw) Parameters: class\_: Space-Track request class name iter_lines: Yield result line by line iter_content: Yield result in 100 KiB chunks. controller: Optionally specify request controller to use. parse_types: Parse string values in response according to type given in predicate information, e.g. ``'2017-01-01'`` -> ``datetime.date(2017, 1, 1)``. **kwargs: These keywords must match the predicate fields on Space-Track. You may check valid keywords with the following snippet: .. code-block:: python spacetrack = SpaceTrackClient(...) spacetrack.tle.get_predicates() # or spacetrack.get_predicates('tle') See :func:`~spacetrack.operators._stringify_predicate_value` for which Python objects are converted appropriately. Yields: Lines—stripped of newline characters—if ``iter_lines=True`` Yields: 100 KiB chunks if ``iter_content=True`` Returns: Parsed JSON object, unless ``format`` keyword argument is passed. .. warning:: Passing ``format='json'`` will return the JSON **unparsed**. Do not set ``format`` if you want the parsed JSON object returned! """ if iter_lines and iter_content: raise ValueError('iter_lines and iter_content cannot both be True') if 'format' in kwargs and parse_types: raise ValueError('parse_types can only be used if format is unset.') if controller is None: controller = self._find_controller(class_) else: classes = self.request_controllers.get(controller, None) if classes is None: raise ValueError( 'Unknown request controller {!r}'.format(controller)) if class_ not in classes: raise ValueError( 'Unknown request class {!r} for controller {!r}' .format(class_, controller)) # Decode unicode unless class == download, including conversion of # CRLF newlines to LF. decode = (class_ != 'download') if not decode and iter_lines: error = ( 'iter_lines disabled for binary data, since CRLF newlines ' 'split over chunk boundaries would yield extra blank lines. ' 'Use iter_content=True instead.') raise ValueError(error) self.authenticate() url = ('{0}{1}/query/class/{2}' .format(self.base_url, controller, class_)) offline_check = (class_, controller) in self.offline_predicates valid_fields = {p.name for p in self.rest_predicates} predicates = None if not offline_check: # Validate keyword argument names by querying valid predicates from # Space-Track predicates = self.get_predicates(class_, controller) predicate_fields = {p.name for p in predicates} valid_fields |= predicate_fields else: valid_fields |= self.offline_predicates[(class_, controller)] for key, value in kwargs.items(): if key not in valid_fields: raise TypeError( "'{class_}' got an unexpected argument '{key}'" .format(class_=class_, key=key)) if class_ == 'upload' and key == 'file': continue value = _stringify_predicate_value(value) url += '/{key}/{value}'.format(key=key, value=value) logger.debug(requests.utils.requote_uri(url)) if class_ == 'upload': if 'file' not in kwargs: raise TypeError("missing keyword argument: 'file'") resp = self.session.post(url, files={'file': kwargs['file']}) else: resp = self._ratelimited_get(url, stream=iter_lines or iter_content) _raise_for_status(resp) if resp.encoding is None: resp.encoding = 'UTF-8' if iter_lines: return _iter_lines_generator(resp, decode_unicode=decode) elif iter_content: return _iter_content_generator(resp, decode_unicode=decode) else: # If format is specified, return that format unparsed. Otherwise, # parse the default JSON response. if 'format' in kwargs: if decode: data = resp.text # Replace CRLF newlines with LF, Python will handle platform # specific newlines if written to file. data = data.replace('\r\n', '\n') else: data = resp.content return data else: data = resp.json() if predicates is None or not parse_types: return data else: return self._parse_types(data, predicates)
python
def generic_request(self, class_, iter_lines=False, iter_content=False, controller=None, parse_types=False, **kwargs): r"""Generic Space-Track query. The request class methods use this method internally; the public API is as follows: .. code-block:: python st.tle_publish(*args, **kw) st.basicspacedata.tle_publish(*args, **kw) st.file(*args, **kw) st.fileshare.file(*args, **kw) st.spephemeris.file(*args, **kw) They resolve to the following calls respectively: .. code-block:: python st.generic_request('tle_publish', *args, **kw) st.generic_request('tle_publish', *args, controller='basicspacedata', **kw) st.generic_request('file', *args, **kw) st.generic_request('file', *args, controller='fileshare', **kw) st.generic_request('file', *args, controller='spephemeris', **kw) Parameters: class\_: Space-Track request class name iter_lines: Yield result line by line iter_content: Yield result in 100 KiB chunks. controller: Optionally specify request controller to use. parse_types: Parse string values in response according to type given in predicate information, e.g. ``'2017-01-01'`` -> ``datetime.date(2017, 1, 1)``. **kwargs: These keywords must match the predicate fields on Space-Track. You may check valid keywords with the following snippet: .. code-block:: python spacetrack = SpaceTrackClient(...) spacetrack.tle.get_predicates() # or spacetrack.get_predicates('tle') See :func:`~spacetrack.operators._stringify_predicate_value` for which Python objects are converted appropriately. Yields: Lines—stripped of newline characters—if ``iter_lines=True`` Yields: 100 KiB chunks if ``iter_content=True`` Returns: Parsed JSON object, unless ``format`` keyword argument is passed. .. warning:: Passing ``format='json'`` will return the JSON **unparsed**. Do not set ``format`` if you want the parsed JSON object returned! """ if iter_lines and iter_content: raise ValueError('iter_lines and iter_content cannot both be True') if 'format' in kwargs and parse_types: raise ValueError('parse_types can only be used if format is unset.') if controller is None: controller = self._find_controller(class_) else: classes = self.request_controllers.get(controller, None) if classes is None: raise ValueError( 'Unknown request controller {!r}'.format(controller)) if class_ not in classes: raise ValueError( 'Unknown request class {!r} for controller {!r}' .format(class_, controller)) # Decode unicode unless class == download, including conversion of # CRLF newlines to LF. decode = (class_ != 'download') if not decode and iter_lines: error = ( 'iter_lines disabled for binary data, since CRLF newlines ' 'split over chunk boundaries would yield extra blank lines. ' 'Use iter_content=True instead.') raise ValueError(error) self.authenticate() url = ('{0}{1}/query/class/{2}' .format(self.base_url, controller, class_)) offline_check = (class_, controller) in self.offline_predicates valid_fields = {p.name for p in self.rest_predicates} predicates = None if not offline_check: # Validate keyword argument names by querying valid predicates from # Space-Track predicates = self.get_predicates(class_, controller) predicate_fields = {p.name for p in predicates} valid_fields |= predicate_fields else: valid_fields |= self.offline_predicates[(class_, controller)] for key, value in kwargs.items(): if key not in valid_fields: raise TypeError( "'{class_}' got an unexpected argument '{key}'" .format(class_=class_, key=key)) if class_ == 'upload' and key == 'file': continue value = _stringify_predicate_value(value) url += '/{key}/{value}'.format(key=key, value=value) logger.debug(requests.utils.requote_uri(url)) if class_ == 'upload': if 'file' not in kwargs: raise TypeError("missing keyword argument: 'file'") resp = self.session.post(url, files={'file': kwargs['file']}) else: resp = self._ratelimited_get(url, stream=iter_lines or iter_content) _raise_for_status(resp) if resp.encoding is None: resp.encoding = 'UTF-8' if iter_lines: return _iter_lines_generator(resp, decode_unicode=decode) elif iter_content: return _iter_content_generator(resp, decode_unicode=decode) else: # If format is specified, return that format unparsed. Otherwise, # parse the default JSON response. if 'format' in kwargs: if decode: data = resp.text # Replace CRLF newlines with LF, Python will handle platform # specific newlines if written to file. data = data.replace('\r\n', '\n') else: data = resp.content return data else: data = resp.json() if predicates is None or not parse_types: return data else: return self._parse_types(data, predicates)
[ "def", "generic_request", "(", "self", ",", "class_", ",", "iter_lines", "=", "False", ",", "iter_content", "=", "False", ",", "controller", "=", "None", ",", "parse_types", "=", "False", ",", "*", "*", "kwargs", ")", ":", "if", "iter_lines", "and", "ite...
r"""Generic Space-Track query. The request class methods use this method internally; the public API is as follows: .. code-block:: python st.tle_publish(*args, **kw) st.basicspacedata.tle_publish(*args, **kw) st.file(*args, **kw) st.fileshare.file(*args, **kw) st.spephemeris.file(*args, **kw) They resolve to the following calls respectively: .. code-block:: python st.generic_request('tle_publish', *args, **kw) st.generic_request('tle_publish', *args, controller='basicspacedata', **kw) st.generic_request('file', *args, **kw) st.generic_request('file', *args, controller='fileshare', **kw) st.generic_request('file', *args, controller='spephemeris', **kw) Parameters: class\_: Space-Track request class name iter_lines: Yield result line by line iter_content: Yield result in 100 KiB chunks. controller: Optionally specify request controller to use. parse_types: Parse string values in response according to type given in predicate information, e.g. ``'2017-01-01'`` -> ``datetime.date(2017, 1, 1)``. **kwargs: These keywords must match the predicate fields on Space-Track. You may check valid keywords with the following snippet: .. code-block:: python spacetrack = SpaceTrackClient(...) spacetrack.tle.get_predicates() # or spacetrack.get_predicates('tle') See :func:`~spacetrack.operators._stringify_predicate_value` for which Python objects are converted appropriately. Yields: Lines—stripped of newline characters—if ``iter_lines=True`` Yields: 100 KiB chunks if ``iter_content=True`` Returns: Parsed JSON object, unless ``format`` keyword argument is passed. .. warning:: Passing ``format='json'`` will return the JSON **unparsed**. Do not set ``format`` if you want the parsed JSON object returned!
[ "r", "Generic", "Space", "-", "Track", "query", "." ]
18f63b7de989a31b983d140a11418e01bd6fd398
https://github.com/python-astrodynamics/spacetrack/blob/18f63b7de989a31b983d140a11418e01bd6fd398/spacetrack/base.py#L245-L402
train
46,322
python-astrodynamics/spacetrack
spacetrack/base.py
SpaceTrackClient._ratelimited_get
def _ratelimited_get(self, *args, **kwargs): """Perform get request, handling rate limiting.""" 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 and it is # started again. # # Let's catch this specific instance and retry once if it happens. if resp.status_code == 500: # Let's only retry if the error page tells us it's a rate limit # violation. if 'violated your query rate limit' in resp.text: # Mimic the RateLimiter callback behaviour. until = time.time() + self._ratelimiter.period t = threading.Thread(target=self._ratelimit_callback, args=(until,)) t.daemon = True t.start() time.sleep(self._ratelimiter.period) # Now retry with self._ratelimiter: resp = self.session.get(*args, **kwargs) return resp
python
def _ratelimited_get(self, *args, **kwargs): """Perform get request, handling rate limiting.""" 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 and it is # started again. # # Let's catch this specific instance and retry once if it happens. if resp.status_code == 500: # Let's only retry if the error page tells us it's a rate limit # violation. if 'violated your query rate limit' in resp.text: # Mimic the RateLimiter callback behaviour. until = time.time() + self._ratelimiter.period t = threading.Thread(target=self._ratelimit_callback, args=(until,)) t.daemon = True t.start() time.sleep(self._ratelimiter.period) # Now retry with self._ratelimiter: resp = self.session.get(*args, **kwargs) return resp
[ "def", "_ratelimited_get", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "with", "self", ".", "_ratelimiter", ":", "resp", "=", "self", ".", "session", ".", "get", "(", "*", "args", ",", "*", "*", "kwargs", ")", "# It's possible t...
Perform get request, handling rate limiting.
[ "Perform", "get", "request", "handling", "rate", "limiting", "." ]
18f63b7de989a31b983d140a11418e01bd6fd398
https://github.com/python-astrodynamics/spacetrack/blob/18f63b7de989a31b983d140a11418e01bd6fd398/spacetrack/base.py#L415-L441
train
46,323
python-astrodynamics/spacetrack
spacetrack/base.py
SpaceTrackClient._find_controller
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`) """ for controller, classes in self.request_controllers.items(): if class_ in classes: return controller else: raise ValueError('Unknown request class {!r}'.format(class_))
python
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`) """ 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_", ")", ":", "for", "controller", ",", "classes", "in", "self", ".", "request_controllers", ".", "items", "(", ")", ":", "if", "class_", "in", "classes", ":", "return", "controller", "else", ":", "raise",...
Find first controller that matches given request class. Order is specified by the keys of ``SpaceTrackClient.request_controllers`` (:class:`~collections.OrderedDict`)
[ "Find", "first", "controller", "that", "matches", "given", "request", "class", "." ]
18f63b7de989a31b983d140a11418e01bd6fd398
https://github.com/python-astrodynamics/spacetrack/blob/18f63b7de989a31b983d140a11418e01bd6fd398/spacetrack/base.py#L479-L490
train
46,324
python-astrodynamics/spacetrack
spacetrack/base.py
SpaceTrackClient.get_predicates
def get_predicates(self, class_, controller=None): """Get full predicate information for given request class, and cache for subsequent calls. """ 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( 'Unknown request controller {!r}'.format(controller)) if class_ not in classes: raise ValueError( 'Unknown request class {!r}'.format(class_)) predicates_data = self._download_predicate_data(class_, controller) predicate_objects = self._parse_predicates_data(predicates_data) self._predicates[class_] = predicate_objects return self._predicates[class_]
python
def get_predicates(self, class_, controller=None): """Get full predicate information for given request class, and cache for subsequent calls. """ 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( 'Unknown request controller {!r}'.format(controller)) if class_ not in classes: raise ValueError( 'Unknown request class {!r}'.format(class_)) predicates_data = self._download_predicate_data(class_, controller) predicate_objects = self._parse_predicates_data(predicates_data) self._predicates[class_] = predicate_objects return self._predicates[class_]
[ "def", "get_predicates", "(", "self", ",", "class_", ",", "controller", "=", "None", ")", ":", "if", "class_", "not", "in", "self", ".", "_predicates", ":", "if", "controller", "is", "None", ":", "controller", "=", "self", ".", "_find_controller", "(", "...
Get full predicate information for given request class, and cache for subsequent calls.
[ "Get", "full", "predicate", "information", "for", "given", "request", "class", "and", "cache", "for", "subsequent", "calls", "." ]
18f63b7de989a31b983d140a11418e01bd6fd398
https://github.com/python-astrodynamics/spacetrack/blob/18f63b7de989a31b983d140a11418e01bd6fd398/spacetrack/base.py#L509-L529
train
46,325
python-astrodynamics/spacetrack
spacetrack/base.py
_ControllerProxy.get_predicates
def get_predicates(self, class_): """Proxy ``get_predicates`` to client with stored request controller. """ return self.client.get_predicates( class_=class_, controller=self.controller)
python
def get_predicates(self, class_): """Proxy ``get_predicates`` to client with stored request controller. """ return self.client.get_predicates( class_=class_, controller=self.controller)
[ "def", "get_predicates", "(", "self", ",", "class_", ")", ":", "return", "self", ".", "client", ".", "get_predicates", "(", "class_", "=", "class_", ",", "controller", "=", "self", ".", "controller", ")" ]
Proxy ``get_predicates`` to client with stored request controller.
[ "Proxy", "get_predicates", "to", "client", "with", "stored", "request", "controller", "." ]
18f63b7de989a31b983d140a11418e01bd6fd398
https://github.com/python-astrodynamics/spacetrack/blob/18f63b7de989a31b983d140a11418e01bd6fd398/spacetrack/base.py#L632-L637
train
46,326
pyQode/pyqode.core
pyqode/core/panels/folding.py
FoldingPanel.on_install
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. """ 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_action_toggle) self.context_menu.addAction(action) action = self.action_expand = QtWidgets.QAction(_('Expand'), self.context_menu) action.setShortcut('Shift++') action.triggered.connect(self._on_action_toggle) self.context_menu.addAction(action) self.context_menu.addSeparator() action = self.action_collapse_all = QtWidgets.QAction( _('Collapse all'), self.context_menu) action.setShortcut('Ctrl+Shift+-') action.triggered.connect(self._on_action_collapse_all_triggered) self.context_menu.addAction(action) action = self.action_expand_all = QtWidgets.QAction( _('Expand all'), self.context_menu) action.setShortcut('Ctrl+Shift++') action.triggered.connect(self._on_action_expand_all_triggered) self.context_menu.addAction(action) self.editor.add_menu(self.context_menu)
python
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. """ 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_action_toggle) self.context_menu.addAction(action) action = self.action_expand = QtWidgets.QAction(_('Expand'), self.context_menu) action.setShortcut('Shift++') action.triggered.connect(self._on_action_toggle) self.context_menu.addAction(action) self.context_menu.addSeparator() action = self.action_collapse_all = QtWidgets.QAction( _('Collapse all'), self.context_menu) action.setShortcut('Ctrl+Shift+-') action.triggered.connect(self._on_action_collapse_all_triggered) self.context_menu.addAction(action) action = self.action_expand_all = QtWidgets.QAction( _('Expand all'), self.context_menu) action.setShortcut('Ctrl+Shift++') action.triggered.connect(self._on_action_expand_all_triggered) self.context_menu.addAction(action) self.editor.add_menu(self.context_menu)
[ "def", "on_install", "(", "self", ",", "editor", ")", ":", "super", "(", "FoldingPanel", ",", "self", ")", ".", "on_install", "(", "editor", ")", "self", ".", "context_menu", "=", "QtWidgets", ".", "QMenu", "(", "_", "(", "'Folding'", ")", ",", "self",...
Add the folding menu to the editor, on install. :param editor: editor instance on which the mode has been installed to.
[ "Add", "the", "folding", "menu", "to", "the", "editor", "on", "install", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/panels/folding.py#L180-L209
train
46,327
pyQode/pyqode.core
pyqode/core/panels/folding.py
FoldingPanel._draw_rect
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. """ 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.setColorAt(1, c.lighter(110)) outline = c.darker(110) else: grad.setColorAt(0, c.lighter(110)) grad.setColorAt(1, c.lighter(130)) outline = c.darker(100) painter.fillRect(rect, grad) painter.setPen(QtGui.QPen(outline)) painter.drawLine(rect.topLeft() + QtCore.QPointF(1, 0), rect.topRight() - QtCore.QPointF(1, 0)) painter.drawLine(rect.bottomLeft() + QtCore.QPointF(1, 0), rect.bottomRight() - QtCore.QPointF(1, 0)) painter.drawLine(rect.topRight() + QtCore.QPointF(0, 1), rect.bottomRight() - QtCore.QPointF(0, 1)) painter.drawLine(rect.topLeft() + QtCore.QPointF(0, 1), rect.bottomLeft() - QtCore.QPointF(0, 1))
python
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. """ 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.setColorAt(1, c.lighter(110)) outline = c.darker(110) else: grad.setColorAt(0, c.lighter(110)) grad.setColorAt(1, c.lighter(130)) outline = c.darker(100) painter.fillRect(rect, grad) painter.setPen(QtGui.QPen(outline)) painter.drawLine(rect.topLeft() + QtCore.QPointF(1, 0), rect.topRight() - QtCore.QPointF(1, 0)) painter.drawLine(rect.bottomLeft() + QtCore.QPointF(1, 0), rect.bottomRight() - QtCore.QPointF(1, 0)) painter.drawLine(rect.topRight() + QtCore.QPointF(0, 1), rect.bottomRight() - QtCore.QPointF(0, 1)) painter.drawLine(rect.topLeft() + QtCore.QPointF(0, 1), rect.bottomLeft() - QtCore.QPointF(0, 1))
[ "def", "_draw_rect", "(", "self", ",", "rect", ",", "painter", ")", ":", "c", "=", "self", ".", "_custom_color", "if", "self", ".", "_native", ":", "c", "=", "self", ".", "get_system_bck_color", "(", ")", "grad", "=", "QtGui", ".", "QLinearGradient", "...
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.
[ "Draw", "the", "background", "rectangle", "using", "the", "current", "style", "primitive", "color", "or", "foldIndicatorBackground", "if", "nativeFoldingIndicator", "is", "true", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/panels/folding.py#L284-L323
train
46,328
pyQode/pyqode.core
pyqode/core/panels/folding.py
FoldingPanel.get_system_bck_color
def get_system_bck_color(): """ Gets a system color for drawing the fold scope background. """ 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)) / maxFactor) tmp.setGreen((tmp.green() * factor) / maxFactor + (colorB.green() * (maxFactor - factor)) / maxFactor) tmp.setBlue((tmp.blue() * factor) / maxFactor + (colorB.blue() * (maxFactor - factor)) / maxFactor) return tmp pal = QtWidgets.QApplication.instance().palette() b = pal.window().color() h = pal.highlight().color() return merged_colors(b, h, 50)
python
def get_system_bck_color(): """ Gets a system color for drawing the fold scope background. """ 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)) / maxFactor) tmp.setGreen((tmp.green() * factor) / maxFactor + (colorB.green() * (maxFactor - factor)) / maxFactor) tmp.setBlue((tmp.blue() * factor) / maxFactor + (colorB.blue() * (maxFactor - factor)) / maxFactor) return tmp pal = QtWidgets.QApplication.instance().palette() b = pal.window().color() h = pal.highlight().color() return merged_colors(b, h, 50)
[ "def", "get_system_bck_color", "(", ")", ":", "def", "merged_colors", "(", "colorA", ",", "colorB", ",", "factor", ")", ":", "maxFactor", "=", "100", "colorA", "=", "QtGui", ".", "QColor", "(", "colorA", ")", "colorB", "=", "QtGui", ".", "QColor", "(", ...
Gets a system color for drawing the fold scope background.
[ "Gets", "a", "system", "color", "for", "drawing", "the", "fold", "scope", "background", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/panels/folding.py#L326-L346
train
46,329
pyQode/pyqode.core
pyqode/core/panels/folding.py
FoldingPanel._add_scope_decorations
def _add_scope_decorations(self, block, start, end): """ Show a scope decoration on the editor widget :param start: Start line :param end: End line """ 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: factor_step = 10 factor = 70 else: factor = 100 while parent: # highlight parent scope parent_start, parent_end = parent.get_range() self._add_scope_deco( start, end + 1, parent_start, parent_end, base_color, factor) # next parent scope start = parent_start end = parent_end parent = parent.parent() factor += factor_step # global scope parent_start = 0 parent_end = self.editor.document().blockCount() self._add_scope_deco( start, end + 1, parent_start, parent_end, base_color, factor + factor_step) else: self._clear_scope_decos()
python
def _add_scope_decorations(self, block, start, end): """ Show a scope decoration on the editor widget :param start: Start line :param end: End line """ 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: factor_step = 10 factor = 70 else: factor = 100 while parent: # highlight parent scope parent_start, parent_end = parent.get_range() self._add_scope_deco( start, end + 1, parent_start, parent_end, base_color, factor) # next parent scope start = parent_start end = parent_end parent = parent.parent() factor += factor_step # global scope parent_start = 0 parent_end = self.editor.document().blockCount() self._add_scope_deco( start, end + 1, parent_start, parent_end, base_color, factor + factor_step) else: self._clear_scope_decos()
[ "def", "_add_scope_decorations", "(", "self", ",", "block", ",", "start", ",", "end", ")", ":", "try", ":", "parent", "=", "FoldScope", "(", "block", ")", ".", "parent", "(", ")", "except", "ValueError", ":", "parent", "=", "None", "if", "TextBlockHelper...
Show a scope decoration on the editor widget :param start: Start line :param end: End line
[ "Show", "a", "scope", "decoration", "on", "the", "editor", "widget" ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/panels/folding.py#L460-L497
train
46,330
pyQode/pyqode.core
pyqode/core/panels/folding.py
FoldingPanel._highlight_surrounding_scopes
def _highlight_surrounding_scopes(self, block): """ Highlights the scopes surrounding the current fold scope. :param block: Block that starts the current fold scope. """ 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 start, end = scope.get_range() if not TextBlockHelper.is_collapsed(block): self._add_scope_decorations(block, start, end)
python
def _highlight_surrounding_scopes(self, block): """ Highlights the scopes surrounding the current fold scope. :param block: Block that starts the current fold scope. """ 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 start, end = scope.get_range() if not TextBlockHelper.is_collapsed(block): self._add_scope_decorations(block, start, end)
[ "def", "_highlight_surrounding_scopes", "(", "self", ",", "block", ")", ":", "scope", "=", "FoldScope", "(", "block", ")", "if", "(", "self", ".", "_current_scope", "is", "None", "or", "self", ".", "_current_scope", ".", "get_range", "(", ")", "!=", "scope...
Highlights the scopes surrounding the current fold scope. :param block: Block that starts the current fold scope.
[ "Highlights", "the", "scopes", "surrounding", "the", "current", "fold", "scope", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/panels/folding.py#L499-L513
train
46,331
pyQode/pyqode.core
pyqode/core/panels/folding.py
FoldingPanel.leaveEvent
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. """ 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 = None else: self._block_nbr = -1 self._highlight_caret_scope() self.editor.repaint()
python
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. """ 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 = None else: self._block_nbr = -1 self._highlight_caret_scope() self.editor.repaint()
[ "def", "leaveEvent", "(", "self", ",", "event", ")", ":", "super", "(", "FoldingPanel", ",", "self", ")", ".", "leaveEvent", "(", "event", ")", "QtWidgets", ".", "QApplication", ".", "restoreOverrideCursor", "(", ")", "self", ".", "_highlight_runner", ".", ...
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.
[ "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", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/panels/folding.py#L553-L570
train
46,332
bmwcarit/zubbi
zubbi/views.py
WebhookView.verify_signature
def verify_signature(self, payload, headers): """Verify that the payload was sent from our GitHub instance.""" 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_webhook_secret.encode("utf-8"), payload, hashlib.sha1 ).hexdigest() ) if not hmac.compare_digest(signature, github_signature): json_abort(401, "Request signature does not match calculated signature.")
python
def verify_signature(self, payload, headers): """Verify that the payload was sent from our GitHub instance.""" 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_webhook_secret.encode("utf-8"), payload, hashlib.sha1 ).hexdigest() ) if not hmac.compare_digest(signature, github_signature): json_abort(401, "Request signature does not match calculated signature.")
[ "def", "verify_signature", "(", "self", ",", "payload", ",", "headers", ")", ":", "github_signature", "=", "headers", ".", "get", "(", "\"x-hub-signature\"", ")", "if", "not", "github_signature", ":", "json_abort", "(", "401", ",", "\"X-Hub-Signature header missin...
Verify that the payload was sent from our GitHub instance.
[ "Verify", "that", "the", "payload", "was", "sent", "from", "our", "GitHub", "instance", "." ]
b99dfd6113c0351f13876f4172648c2eb63468ba
https://github.com/bmwcarit/zubbi/blob/b99dfd6113c0351f13876f4172648c2eb63468ba/zubbi/views.py#L293-L307
train
46,333
psphere-project/psphere
psphere/scripting.py
BaseScript.get_options
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. """ (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 if visdkrc_opts: if opt in visdkrc_opts: setattr(options, opt, visdkrc_opts[opt]) # Ensure all the required options are set for opt in self.required_opts: if opt not in dir(options) or getattr(options, opt) == None: self.parser.error('%s must be set!' % opt) return options
python
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. """ (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 if visdkrc_opts: if opt in visdkrc_opts: setattr(options, opt, visdkrc_opts[opt]) # Ensure all the required options are set for opt in self.required_opts: if opt not in dir(options) or getattr(options, opt) == None: self.parser.error('%s must be set!' % opt) return options
[ "def", "get_options", "(", "self", ")", ":", "(", "options", ",", "args", ")", "=", "self", ".", "parser", ".", "parse_args", "(", ")", "# Set values from .visdkrc, but only if they haven't already been set", "visdkrc_opts", "=", "self", ".", "read_visdkrc", "(", ...
Get the options that have been set. Called after the user has added all their own options and is ready to use the variables.
[ "Get", "the", "options", "that", "have", "been", "set", "." ]
83a252e037c3d6e4f18bcd37380998bc9535e591
https://github.com/psphere-project/psphere/blob/83a252e037c3d6e4f18bcd37380998bc9535e591/psphere/scripting.py#L49-L72
train
46,334
bmwcarit/zubbi
zubbi/scraper/repo_parser.py
RepoParser.parse_job_files
def parse_job_files(self): """Check for job definitions in known zuul files.""" 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(jobs), rel_job_file_path) repo_jobs.extend(jobs) if not repo_jobs: LOGGER.info("No job definitions found in repo '%s'", self.repo) else: LOGGER.info( "Found %d job definitions in repo '%s'", len(repo_jobs), self.repo ) # LOGGER.debug(json.dumps(repo_jobs, indent=4)) return repo_jobs
python
def parse_job_files(self): """Check for job definitions in known zuul files.""" 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(jobs), rel_job_file_path) repo_jobs.extend(jobs) if not repo_jobs: LOGGER.info("No job definitions found in repo '%s'", self.repo) else: LOGGER.info( "Found %d job definitions in repo '%s'", len(repo_jobs), self.repo ) # LOGGER.debug(json.dumps(repo_jobs, indent=4)) return repo_jobs
[ "def", "parse_job_files", "(", "self", ")", ":", "repo_jobs", "=", "[", "]", "for", "rel_job_file_path", ",", "job_info", "in", "self", ".", "job_files", ".", "items", "(", ")", ":", "LOGGER", ".", "debug", "(", "\"Checking for job definitions in %s\"", ",", ...
Check for job definitions in known zuul files.
[ "Check", "for", "job", "definitions", "in", "known", "zuul", "files", "." ]
b99dfd6113c0351f13876f4172648c2eb63468ba
https://github.com/bmwcarit/zubbi/blob/b99dfd6113c0351f13876f4172648c2eb63468ba/zubbi/scraper/repo_parser.py#L45-L60
train
46,335
pyQode/pyqode.core
pyqode/core/widgets/terminal.py
Terminal.change_directory
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: """ 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')
python
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: """ 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", ")", ":", "self", ".", "_process", ".", "write", "(", "(", "'cd %s\\n'", "%", "directory", ")", ".", "encode", "(", ")", ")", "if", "sys", ".", "platform", "==", "'win32'", ":", "self", ".", "...
Changes the current directory. Change is made by running a "cd" command followed by a "clear" command. :param directory: :return:
[ "Changes", "the", "current", "directory", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/widgets/terminal.py#L49-L62
train
46,336
pyQode/pyqode.core
pyqode/core/panels/marker.py
Marker.icon
def icon(self): """ Gets the icon file name. Read-only. """ 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[0], QtGui.QIcon(self._icon[1])) elif isinstance(self._icon, QtGui.QIcon): return self._icon return QtGui.QIcon()
python
def icon(self): """ Gets the icon file name. Read-only. """ 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[0], QtGui.QIcon(self._icon[1])) elif isinstance(self._icon, QtGui.QIcon): return self._icon return QtGui.QIcon()
[ "def", "icon", "(", "self", ")", ":", "if", "isinstance", "(", "self", ".", "_icon", ",", "str", ")", ":", "if", "QtGui", ".", "QIcon", ".", "hasThemeIcon", "(", "self", ".", "_icon", ")", ":", "return", "QtGui", ".", "QIcon", ".", "fromTheme", "("...
Gets the icon file name. Read-only.
[ "Gets", "the", "icon", "file", "name", ".", "Read", "-", "only", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/panels/marker.py#L36-L50
train
46,337
pyQode/pyqode.core
pyqode/core/panels/marker.py
MarkerPanel.add_marker
def add_marker(self, marker): """ Adds the marker to the panel. :param marker: Marker to add :type marker: pyqode.core.modes.Marker """ 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: d.set_background(QtGui.QBrush(self._background)) marker.decoration = d self.editor.decorations.append(d) self.repaint()
python
def add_marker(self, marker): """ Adds the marker to the panel. :param marker: Marker to add :type marker: pyqode.core.modes.Marker """ 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: d.set_background(QtGui.QBrush(self._background)) marker.decoration = d self.editor.decorations.append(d) self.repaint()
[ "def", "add_marker", "(", "self", ",", "marker", ")", ":", "self", ".", "_markers", ".", "append", "(", "marker", ")", "doc", "=", "self", ".", "editor", ".", "document", "(", ")", "assert", "isinstance", "(", "doc", ",", "QtGui", ".", "QTextDocument",...
Adds the marker to the panel. :param marker: Marker to add :type marker: pyqode.core.modes.Marker
[ "Adds", "the", "marker", "to", "the", "panel", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/panels/marker.py#L128-L146
train
46,338
pyQode/pyqode.core
pyqode/core/panels/marker.py
MarkerPanel.remove_marker
def remove_marker(self, marker): """ Removes a marker from the panel :param marker: Marker to remove :type marker: pyqode.core.Marker """ self._markers.remove(marker) self._to_remove.append(marker) if hasattr(marker, 'decoration'): self.editor.decorations.remove(marker.decoration) self.repaint()
python
def remove_marker(self, marker): """ Removes a marker from the panel :param marker: Marker to remove :type marker: pyqode.core.Marker """ 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", ")", ":", "self", ".", "_markers", ".", "remove", "(", "marker", ")", "self", ".", "_to_remove", ".", "append", "(", "marker", ")", "if", "hasattr", "(", "marker", ",", "'decoration'", ")", ":", "self...
Removes a marker from the panel :param marker: Marker to remove :type marker: pyqode.core.Marker
[ "Removes", "a", "marker", "from", "the", "panel" ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/panels/marker.py#L148-L159
train
46,339
pyQode/pyqode.core
pyqode/core/panels/marker.py
MarkerPanel._display_tooltip
def _display_tooltip(self, tooltip, top): """ Display tooltip at the specified top position. """ QtWidgets.QToolTip.showText(self.mapToGlobal(QtCore.QPoint( self.sizeHint().width(), top)), tooltip, self)
python
def _display_tooltip(self, tooltip, top): """ Display tooltip at the specified top position. """ QtWidgets.QToolTip.showText(self.mapToGlobal(QtCore.QPoint( self.sizeHint().width(), top)), tooltip, self)
[ "def", "_display_tooltip", "(", "self", ",", "tooltip", ",", "top", ")", ":", "QtWidgets", ".", "QToolTip", ".", "showText", "(", "self", ".", "mapToGlobal", "(", "QtCore", ".", "QPoint", "(", "self", ".", "sizeHint", "(", ")", ".", "width", "(", ")", ...
Display tooltip at the specified top position.
[ "Display", "tooltip", "at", "the", "specified", "top", "position", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/panels/marker.py#L244-L249
train
46,340
pyQode/pyqode.core
pyqode/core/backend/workers.py
finditer_noregex
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 """ 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)] except IndexError: nchar = ' ' if nchar in DocumentWordsProvider.separators and \ pchar in DocumentWordsProvider.separators: yield start start += len(sub) else: yield start start += 1
python
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 """ 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)] except IndexError: nchar = ' ' if nchar in DocumentWordsProvider.separators and \ pchar in DocumentWordsProvider.separators: yield start start += len(sub) else: yield start start += 1
[ "def", "finditer_noregex", "(", "string", ",", "sub", ",", "whole_word", ")", ":", "start", "=", "0", "while", "True", ":", "start", "=", "string", ".", "find", "(", "sub", ",", "start", ")", "if", "start", "==", "-", "1", ":", "return", "if", "who...
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
[ "Search", "occurrences", "using", "str", ".", "find", "instead", "of", "regular", "expressions", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/backend/workers.py#L171-L199
train
46,341
pyQode/pyqode.core
pyqode/core/backend/workers.py
DocumentWordsProvider.complete
def complete(self, code, *args): """ Provides completions based on the document words. :param code: code to complete :param args: additional (unused) arguments. """ completions = [] for word in self.split(code, self.separators): completions.append({'name': word}) return completions
python
def complete(self, code, *args): """ Provides completions based on the document words. :param code: code to complete :param args: additional (unused) arguments. """ completions = [] for word in self.split(code, self.separators): completions.append({'name': word}) return completions
[ "def", "complete", "(", "self", ",", "code", ",", "*", "args", ")", ":", "completions", "=", "[", "]", "for", "word", "in", "self", ".", "split", "(", "code", ",", "self", ".", "separators", ")", ":", "completions", ".", "append", "(", "{", "'name'...
Provides completions based on the document words. :param code: code to complete :param args: additional (unused) arguments.
[ "Provides", "completions", "based", "on", "the", "document", "words", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/backend/workers.py#L158-L168
train
46,342
pyQode/pyqode.core
pyqode/core/modes/checker.py
CheckerMessage.status_to_string
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 """ strings = {CheckerMessages.INFO: "Info", CheckerMessages.WARNING: "Warning", CheckerMessages.ERROR: "Error"} return strings[status]
python
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 """ strings = {CheckerMessages.INFO: "Info", CheckerMessages.WARNING: "Warning", CheckerMessages.ERROR: "Error"} return strings[status]
[ "def", "status_to_string", "(", "cls", ",", "status", ")", ":", "strings", "=", "{", "CheckerMessages", ".", "INFO", ":", "\"Info\"", ",", "CheckerMessages", ".", "WARNING", ":", "\"Warning\"", ",", "CheckerMessages", ".", "ERROR", ":", "\"Error\"", "}", "re...
Converts a message status to a string. :param status: Status to convert (p yqode.core.modes.CheckerMessages) :return: The status string. :rtype: str
[ "Converts", "a", "message", "status", "to", "a", "string", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/modes/checker.py#L37-L48
train
46,343
pyQode/pyqode.core
pyqode/core/modes/checker.py
CheckerMode.add_messages
def add_messages(self, messages): """ Adds a message or a list of message. :param messages: A list of messages or a single message """ # 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) self._pending_msg = messages # start removing messages, new message won't be added until we # checked all message that need to be removed QtCore.QTimer.singleShot(1, self._remove_batch)
python
def add_messages(self, messages): """ Adds a message or a list of message. :param messages: A list of messages or a single message """ # 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) self._pending_msg = messages # start removing messages, new message won't be added until we # checked all message that need to be removed QtCore.QTimer.singleShot(1, self._remove_batch)
[ "def", "add_messages", "(", "self", ",", "messages", ")", ":", "# remove old messages", "if", "len", "(", "messages", ")", ">", "self", ".", "limit", ":", "messages", "=", "messages", "[", ":", "self", ".", "limit", "]", "_logger", "(", "self", ".", "_...
Adds a message or a list of message. :param messages: A list of messages or a single message
[ "Adds", "a", "message", "or", "a", "list", "of", "message", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/modes/checker.py#L181-L197
train
46,344
pyQode/pyqode.core
pyqode/core/modes/checker.py
CheckerMode.remove_message
def remove_message(self, message): """ Removes a message. :param message: Message to remove """ 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 if message.decoration: self.editor.decorations.remove(message.decoration) self._messages.remove(message)
python
def remove_message(self, message): """ Removes a message. :param message: Message to remove """ 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 if message.decoration: self.editor.decorations.remove(message.decoration) self._messages.remove(message)
[ "def", "remove_message", "(", "self", ",", "message", ")", ":", "import", "time", "_logger", "(", "self", ".", "__class__", ")", ".", "log", "(", "5", ",", "'removing message %s'", "%", "message", ")", "t", "=", "time", ".", "time", "(", ")", "usd", ...
Removes a message. :param message: Message to remove
[ "Removes", "a", "message", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/modes/checker.py#L255-L272
train
46,345
pyQode/pyqode.core
pyqode/core/modes/checker.py
CheckerMode.clear_messages
def clear_messages(self): """ Clears all messages. """ 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)
python
def clear_messages(self): """ Clears all messages. """ 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", ")", ":", "while", "len", "(", "self", ".", "_messages", ")", ":", "msg", "=", "self", ".", "_messages", ".", "pop", "(", "0", ")", "usd", "=", "msg", ".", "block", ".", "userData", "(", ")", "if", "usd", "an...
Clears all messages.
[ "Clears", "all", "messages", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/modes/checker.py#L274-L284
train
46,346
pyQode/pyqode.core
pyqode/core/modes/checker.py
CheckerMode._on_work_finished
def _on_work_finished(self, results): """ Display results. :param status: Response status :param results: Response data, messages. """ 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 messages.append(msg) self.add_messages(messages)
python
def _on_work_finished(self, results): """ Display results. :param status: Response status :param results: Response data, messages. """ 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 messages.append(msg) self.add_messages(messages)
[ "def", "_on_work_finished", "(", "self", ",", "results", ")", ":", "messages", "=", "[", "]", "for", "msg", "in", "results", ":", "msg", "=", "CheckerMessage", "(", "*", "msg", ")", "if", "msg", ".", "line", ">=", "self", ".", "editor", ".", "blockCo...
Display results. :param status: Response status :param results: Response data, messages.
[ "Display", "results", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/modes/checker.py#L297-L312
train
46,347
pyQode/pyqode.core
pyqode/core/modes/checker.py
CheckerMode.request_analysis
def request_analysis(self): """ Requests an analysis. """ 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)') QtCore.QTimer.singleShot(500, self.request_analysis)
python
def request_analysis(self): """ Requests an analysis. """ 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)') QtCore.QTimer.singleShot(500, self.request_analysis)
[ "def", "request_analysis", "(", "self", ")", ":", "if", "self", ".", "_finished", ":", "_logger", "(", "self", ".", "__class__", ")", ".", "log", "(", "5", ",", "'running analysis'", ")", "self", ".", "_job_runner", ".", "request_job", "(", "self", ".", ...
Requests an analysis.
[ "Requests", "an", "analysis", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/modes/checker.py#L314-L325
train
46,348
pyQode/pyqode.core
pyqode/core/modes/checker.py
CheckerMode._request
def _request(self): """ Requests a checking of the editor content. """ 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 = { 'code': self.editor.toPlainText(), 'path': self.editor.file.path, 'encoding': self.editor.file.encoding, 'ignore_rules': self.ignore_rules, 'max_line_length': max_line_length, } try: self.editor.backend.send_request( self._worker, request_data, on_receive=self._on_work_finished) self._finished = False except NotRunning: # retry later QtCore.QTimer.singleShot(100, self._request)
python
def _request(self): """ Requests a checking of the editor content. """ 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 = { 'code': self.editor.toPlainText(), 'path': self.editor.file.path, 'encoding': self.editor.file.encoding, 'ignore_rules': self.ignore_rules, 'max_line_length': max_line_length, } try: self.editor.backend.send_request( self._worker, request_data, on_receive=self._on_work_finished) self._finished = False except NotRunning: # retry later QtCore.QTimer.singleShot(100, self._request)
[ "def", "_request", "(", "self", ")", ":", "try", ":", "self", ".", "editor", ".", "toPlainText", "(", ")", "except", "(", "TypeError", ",", "RuntimeError", ")", ":", "return", "try", ":", "max_line_length", "=", "self", ".", "editor", ".", "modes", "."...
Requests a checking of the editor content.
[ "Requests", "a", "checking", "of", "the", "editor", "content", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/modes/checker.py#L327-L351
train
46,349
pyQode/pyqode.core
pyqode/core/widgets/_pty.py
_writen
def _writen(fd, data): """Write all the data to a descriptor.""" while data: n = os.write(fd, data) data = data[n:]
python
def _writen(fd, data): """Write all the data to a descriptor.""" while data: n = os.write(fd, data) data = data[n:]
[ "def", "_writen", "(", "fd", ",", "data", ")", ":", "while", "data", ":", "n", "=", "os", ".", "write", "(", "fd", ",", "data", ")", "data", "=", "data", "[", "n", ":", "]" ]
Write all the data to a descriptor.
[ "Write", "all", "the", "data", "to", "a", "descriptor", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/widgets/_pty.py#L119-L123
train
46,350
psphere-project/psphere
psphere/__init__.py
ManagedObject.flush_cache
def flush_cache(self, properties=None): """Flushes the cache being held for this instance. :param properties: The list of properties to flush from the cache. :type properties: list or None (default). If None, flush entire cache. """ if hasattr(self, '_cache'): if properties is None: del(self._cache) else: for prop in properties: if prop in self._cache: del(self._cache[prop])
python
def flush_cache(self, properties=None): """Flushes the cache being held for this instance. :param properties: The list of properties to flush from the cache. :type properties: list or None (default). If None, flush entire cache. """ if hasattr(self, '_cache'): if properties is None: del(self._cache) else: for prop in properties: if prop in self._cache: del(self._cache[prop])
[ "def", "flush_cache", "(", "self", ",", "properties", "=", "None", ")", ":", "if", "hasattr", "(", "self", ",", "'_cache'", ")", ":", "if", "properties", "is", "None", ":", "del", "(", "self", ".", "_cache", ")", "else", ":", "for", "prop", "in", "...
Flushes the cache being held for this instance. :param properties: The list of properties to flush from the cache. :type properties: list or None (default). If None, flush entire cache.
[ "Flushes", "the", "cache", "being", "held", "for", "this", "instance", "." ]
83a252e037c3d6e4f18bcd37380998bc9535e591
https://github.com/psphere-project/psphere/blob/83a252e037c3d6e4f18bcd37380998bc9535e591/psphere/__init__.py#L138-L151
train
46,351
psphere-project/psphere
psphere/__init__.py
ManagedObject.update
def update(self, properties=None): """Updates the properties being held for this instance. :param properties: The list of properties to update. :type properties: list or None (default). If None, update all currently cached properties. """ if properties is None: try: self.update_view_data(properties=list(self._cache.keys())) except AttributeError: # We end up here and ignore it self._cache doesn't exist pass else: self.update_view_data(properties=properties)
python
def update(self, properties=None): """Updates the properties being held for this instance. :param properties: The list of properties to update. :type properties: list or None (default). If None, update all currently cached properties. """ if properties is None: try: self.update_view_data(properties=list(self._cache.keys())) except AttributeError: # We end up here and ignore it self._cache doesn't exist pass else: self.update_view_data(properties=properties)
[ "def", "update", "(", "self", ",", "properties", "=", "None", ")", ":", "if", "properties", "is", "None", ":", "try", ":", "self", ".", "update_view_data", "(", "properties", "=", "list", "(", "self", ".", "_cache", ".", "keys", "(", ")", ")", ")", ...
Updates the properties being held for this instance. :param properties: The list of properties to update. :type properties: list or None (default). If None, update all currently cached properties.
[ "Updates", "the", "properties", "being", "held", "for", "this", "instance", "." ]
83a252e037c3d6e4f18bcd37380998bc9535e591
https://github.com/psphere-project/psphere/blob/83a252e037c3d6e4f18bcd37380998bc9535e591/psphere/__init__.py#L153-L168
train
46,352
psphere-project/psphere
psphere/__init__.py
ManagedObject.preload
def preload(self, name, properties=None): """Pre-loads the requested properties for each object in the "name" attribute. :param name: The name of the attribute containing the list to preload. :type name: str :param properties: The properties to preload on the objects or the string all to preload all properties. :type properties: list or the string "all" """ if properties is None: raise ValueError("You must specify some properties to preload. To" " preload all properties use the string \"all\".") # Don't do anything if the attribute contains an empty list if not getattr(self, name): return mo_refs = [] # Iterate over each item and collect the mo_ref for item in getattr(self, name): # Make sure the items are ManagedObjectReference's if isinstance(item, ManagedObject) is False: raise ValueError("Only ManagedObject's can be pre-loaded.") mo_refs.append(item._mo_ref) # Send a single query to the server which gets views views = self._client.get_views(mo_refs, properties) # Populate the inst.attr item with the retrieved object/properties self._cache[name] = (views, time.time())
python
def preload(self, name, properties=None): """Pre-loads the requested properties for each object in the "name" attribute. :param name: The name of the attribute containing the list to preload. :type name: str :param properties: The properties to preload on the objects or the string all to preload all properties. :type properties: list or the string "all" """ if properties is None: raise ValueError("You must specify some properties to preload. To" " preload all properties use the string \"all\".") # Don't do anything if the attribute contains an empty list if not getattr(self, name): return mo_refs = [] # Iterate over each item and collect the mo_ref for item in getattr(self, name): # Make sure the items are ManagedObjectReference's if isinstance(item, ManagedObject) is False: raise ValueError("Only ManagedObject's can be pre-loaded.") mo_refs.append(item._mo_ref) # Send a single query to the server which gets views views = self._client.get_views(mo_refs, properties) # Populate the inst.attr item with the retrieved object/properties self._cache[name] = (views, time.time())
[ "def", "preload", "(", "self", ",", "name", ",", "properties", "=", "None", ")", ":", "if", "properties", "is", "None", ":", "raise", "ValueError", "(", "\"You must specify some properties to preload. To\"", "\" preload all properties use the string \\\"all\\\".\"", ")", ...
Pre-loads the requested properties for each object in the "name" attribute. :param name: The name of the attribute containing the list to preload. :type name: str :param properties: The properties to preload on the objects or the string all to preload all properties. :type properties: list or the string "all"
[ "Pre", "-", "loads", "the", "requested", "properties", "for", "each", "object", "in", "the", "name", "attribute", "." ]
83a252e037c3d6e4f18bcd37380998bc9535e591
https://github.com/psphere-project/psphere/blob/83a252e037c3d6e4f18bcd37380998bc9535e591/psphere/__init__.py#L226-L258
train
46,353
psphere-project/psphere
psphere/__init__.py
ManagedObject._set_view_data
def _set_view_data(self, object_content): """Update the local object from the passed in object_content.""" # A debugging convenience, allows inspection of the object_content # that was used to create the object logger.info("Setting view data for a %s", self.__class__) self._object_content = object_content for dynprop in object_content.propSet: # If the class hasn't defined the property, don't use it if dynprop.name not in self._valid_attrs: logger.error("Server returned a property '%s' but the object" " hasn't defined it so it is being ignored." % dynprop.name) continue try: if not len(dynprop.val): logger.info("Server returned empty value for %s", dynprop.name) except TypeError: # This except allows us to pass over: # TypeError: object of type 'datetime.datetime' has no len() # It will be processed in the next code block logger.info("%s of type %s has no len!", dynprop.name, type(dynprop.val)) pass try: # See if we have a cache attribute cache = self._cache except AttributeError: # If we don't create one and use it cache = self._cache = {} # Values which contain classes starting with Array need # to be converted into a nicer Python list if dynprop.val.__class__.__name__.startswith('Array'): # suds returns a list containing a single item, which # is another list. Use the first item which is the real list logger.info("Setting value of an Array* property") logger.debug("%s being set to %s", dynprop.name, dynprop.val[0]) now = time.time() cache[dynprop.name] = (dynprop.val[0], now) else: logger.info("Setting value of a single-valued property") logger.debug("DynamicProperty value is a %s: ", dynprop.val.__class__.__name__) logger.debug("%s being set to %s", dynprop.name, dynprop.val) now = time.time() cache[dynprop.name] = (dynprop.val, now)
python
def _set_view_data(self, object_content): """Update the local object from the passed in object_content.""" # A debugging convenience, allows inspection of the object_content # that was used to create the object logger.info("Setting view data for a %s", self.__class__) self._object_content = object_content for dynprop in object_content.propSet: # If the class hasn't defined the property, don't use it if dynprop.name not in self._valid_attrs: logger.error("Server returned a property '%s' but the object" " hasn't defined it so it is being ignored." % dynprop.name) continue try: if not len(dynprop.val): logger.info("Server returned empty value for %s", dynprop.name) except TypeError: # This except allows us to pass over: # TypeError: object of type 'datetime.datetime' has no len() # It will be processed in the next code block logger.info("%s of type %s has no len!", dynprop.name, type(dynprop.val)) pass try: # See if we have a cache attribute cache = self._cache except AttributeError: # If we don't create one and use it cache = self._cache = {} # Values which contain classes starting with Array need # to be converted into a nicer Python list if dynprop.val.__class__.__name__.startswith('Array'): # suds returns a list containing a single item, which # is another list. Use the first item which is the real list logger.info("Setting value of an Array* property") logger.debug("%s being set to %s", dynprop.name, dynprop.val[0]) now = time.time() cache[dynprop.name] = (dynprop.val[0], now) else: logger.info("Setting value of a single-valued property") logger.debug("DynamicProperty value is a %s: ", dynprop.val.__class__.__name__) logger.debug("%s being set to %s", dynprop.name, dynprop.val) now = time.time() cache[dynprop.name] = (dynprop.val, now)
[ "def", "_set_view_data", "(", "self", ",", "object_content", ")", ":", "# A debugging convenience, allows inspection of the object_content", "# that was used to create the object", "logger", ".", "info", "(", "\"Setting view data for a %s\"", ",", "self", ".", "__class__", ")",...
Update the local object from the passed in object_content.
[ "Update", "the", "local", "object", "from", "the", "passed", "in", "object_content", "." ]
83a252e037c3d6e4f18bcd37380998bc9535e591
https://github.com/psphere-project/psphere/blob/83a252e037c3d6e4f18bcd37380998bc9535e591/psphere/__init__.py#L260-L310
train
46,354
bmwcarit/zubbi
zubbi/scraper/main.py
_initialize_repo_cache
def _initialize_repo_cache(): """Initialize the repository cache used for scraping. Retrieves a list of repositories with their provider and last scraping time from Elasticsearch. This list can be used to check which repos need to be scraped (e.g. after a specific amount of time). """ LOGGER.info("Initializing repository cache") # Initialize Repo Cache repo_cache = {} # Get all repos from Elasticsearch for hit in GitRepo.search().query("match_all").scan(): # TODO (fschmidt): Maybe we can use this list as cache for the whole # scraper-webhook part. # This way, we could reduce the amount of operations needed for GitHub # and ElasticSearch repo_cache[hit.repo_name] = hit.to_dict(skip_empty=False) return repo_cache
python
def _initialize_repo_cache(): """Initialize the repository cache used for scraping. Retrieves a list of repositories with their provider and last scraping time from Elasticsearch. This list can be used to check which repos need to be scraped (e.g. after a specific amount of time). """ LOGGER.info("Initializing repository cache") # Initialize Repo Cache repo_cache = {} # Get all repos from Elasticsearch for hit in GitRepo.search().query("match_all").scan(): # TODO (fschmidt): Maybe we can use this list as cache for the whole # scraper-webhook part. # This way, we could reduce the amount of operations needed for GitHub # and ElasticSearch repo_cache[hit.repo_name] = hit.to_dict(skip_empty=False) return repo_cache
[ "def", "_initialize_repo_cache", "(", ")", ":", "LOGGER", ".", "info", "(", "\"Initializing repository cache\"", ")", "# Initialize Repo Cache", "repo_cache", "=", "{", "}", "# Get all repos from Elasticsearch", "for", "hit", "in", "GitRepo", ".", "search", "(", ")", ...
Initialize the repository cache used for scraping. Retrieves a list of repositories with their provider and last scraping time from Elasticsearch. This list can be used to check which repos need to be scraped (e.g. after a specific amount of time).
[ "Initialize", "the", "repository", "cache", "used", "for", "scraping", "." ]
b99dfd6113c0351f13876f4172648c2eb63468ba
https://github.com/bmwcarit/zubbi/blob/b99dfd6113c0351f13876f4172648c2eb63468ba/zubbi/scraper/main.py#L105-L125
train
46,355
psphere-project/psphere
examples/query_supported_features.py
main
def main(options): """Obtains supported features from the license manager""" client = Client(server=options.server, username=options.username, password=options.password) print('Successfully connected to %s' % client.server) lm_info = client.sc.licenseManager.QuerySupportedFeatures() for feature in lm_info: print('%s: %s' % (feature.featureName, feature.state)) client.logout()
python
def main(options): """Obtains supported features from the license manager""" client = Client(server=options.server, username=options.username, password=options.password) print('Successfully connected to %s' % client.server) lm_info = client.sc.licenseManager.QuerySupportedFeatures() for feature in lm_info: print('%s: %s' % (feature.featureName, feature.state)) client.logout()
[ "def", "main", "(", "options", ")", ":", "client", "=", "Client", "(", "server", "=", "options", ".", "server", ",", "username", "=", "options", ".", "username", ",", "password", "=", "options", ".", "password", ")", "print", "(", "'Successfully connected ...
Obtains supported features from the license manager
[ "Obtains", "supported", "features", "from", "the", "license", "manager" ]
83a252e037c3d6e4f18bcd37380998bc9535e591
https://github.com/psphere-project/psphere/blob/83a252e037c3d6e4f18bcd37380998bc9535e591/examples/query_supported_features.py#L21-L30
train
46,356
pyQode/pyqode.core
pyqode/core/managers/modes.py
ModesManager.append
def append(self, mode): """ Adds a mode to the editor. :param mode: The mode instance to append. """ _logger().log(5, 'adding mode %r', mode.name) self._modes[mode.name] = mode mode.on_install(self.editor) return mode
python
def append(self, mode): """ Adds a mode to the editor. :param mode: The mode instance to append. """ _logger().log(5, 'adding mode %r', mode.name) self._modes[mode.name] = mode mode.on_install(self.editor) return mode
[ "def", "append", "(", "self", ",", "mode", ")", ":", "_logger", "(", ")", ".", "log", "(", "5", ",", "'adding mode %r'", ",", "mode", ".", "name", ")", "self", ".", "_modes", "[", "mode", ".", "name", "]", "=", "mode", "mode", ".", "on_install", ...
Adds a mode to the editor. :param mode: The mode instance to append.
[ "Adds", "a", "mode", "to", "the", "editor", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/managers/modes.py#L22-L32
train
46,357
pyQode/pyqode.core
pyqode/core/managers/modes.py
ModesManager.remove
def remove(self, name_or_klass): """ Removes a mode from the editor. :param name_or_klass: The name (or class) of the mode to remove. :returns: The removed mode. """ _logger().log(5, 'removing mode %r', name_or_klass) mode = self.get(name_or_klass) mode.on_uninstall() self._modes.pop(mode.name) return mode
python
def remove(self, name_or_klass): """ Removes a mode from the editor. :param name_or_klass: The name (or class) of the mode to remove. :returns: The removed mode. """ _logger().log(5, 'removing mode %r', name_or_klass) mode = self.get(name_or_klass) mode.on_uninstall() self._modes.pop(mode.name) return mode
[ "def", "remove", "(", "self", ",", "name_or_klass", ")", ":", "_logger", "(", ")", ".", "log", "(", "5", ",", "'removing mode %r'", ",", "name_or_klass", ")", "mode", "=", "self", ".", "get", "(", "name_or_klass", ")", "mode", ".", "on_uninstall", "(", ...
Removes a mode from the editor. :param name_or_klass: The name (or class) of the mode to remove. :returns: The removed mode.
[ "Removes", "a", "mode", "from", "the", "editor", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/managers/modes.py#L34-L45
train
46,358
pyQode/pyqode.core
pyqode/core/managers/decorations.py
TextDecorationsManager.append
def append(self, decoration): """ Adds a text decoration on a CodeEdit instance :param decoration: Text decoration to add :type decoration: pyqode.core.api.TextDecoration """ if decoration not in self._decorations: self._decorations.append(decoration) self._decorations = sorted( self._decorations, key=lambda sel: sel.draw_order) self.editor.setExtraSelections(self._decorations) return True return False
python
def append(self, decoration): """ Adds a text decoration on a CodeEdit instance :param decoration: Text decoration to add :type decoration: pyqode.core.api.TextDecoration """ if decoration not in self._decorations: self._decorations.append(decoration) self._decorations = sorted( self._decorations, key=lambda sel: sel.draw_order) self.editor.setExtraSelections(self._decorations) return True return False
[ "def", "append", "(", "self", ",", "decoration", ")", ":", "if", "decoration", "not", "in", "self", ".", "_decorations", ":", "self", ".", "_decorations", ".", "append", "(", "decoration", ")", "self", ".", "_decorations", "=", "sorted", "(", "self", "."...
Adds a text decoration on a CodeEdit instance :param decoration: Text decoration to add :type decoration: pyqode.core.api.TextDecoration
[ "Adds", "a", "text", "decoration", "on", "a", "CodeEdit", "instance" ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/managers/decorations.py#L21-L34
train
46,359
pyQode/pyqode.core
pyqode/core/managers/decorations.py
TextDecorationsManager.clear
def clear(self): """ Removes all text decoration from the editor. """ self._decorations[:] = [] try: self.editor.setExtraSelections(self._decorations) except RuntimeError: pass
python
def clear(self): """ Removes all text decoration from the editor. """ self._decorations[:] = [] try: self.editor.setExtraSelections(self._decorations) except RuntimeError: pass
[ "def", "clear", "(", "self", ")", ":", "self", ".", "_decorations", "[", ":", "]", "=", "[", "]", "try", ":", "self", ".", "editor", ".", "setExtraSelections", "(", "self", ".", "_decorations", ")", "except", "RuntimeError", ":", "pass" ]
Removes all text decoration from the editor.
[ "Removes", "all", "text", "decoration", "from", "the", "editor", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/managers/decorations.py#L50-L59
train
46,360
pyQode/pyqode.core
pyqode/core/modes/zoom.py
ZoomMode._on_key_pressed
def _on_key_pressed(self, event): """ Resets editor font size to the default font size :param event: wheelEvent :type event: QKeyEvent """ if (int(event.modifiers()) & QtCore.Qt.ControlModifier > 0 and not int(event.modifiers()) & QtCore.Qt.ShiftModifier): if event.key() == QtCore.Qt.Key_0: self.editor.reset_zoom() event.accept() if event.key() == QtCore.Qt.Key_Plus: self.editor.zoom_in() event.accept() if event.key() == QtCore.Qt.Key_Minus: self.editor.zoom_out() event.accept()
python
def _on_key_pressed(self, event): """ Resets editor font size to the default font size :param event: wheelEvent :type event: QKeyEvent """ if (int(event.modifiers()) & QtCore.Qt.ControlModifier > 0 and not int(event.modifiers()) & QtCore.Qt.ShiftModifier): if event.key() == QtCore.Qt.Key_0: self.editor.reset_zoom() event.accept() if event.key() == QtCore.Qt.Key_Plus: self.editor.zoom_in() event.accept() if event.key() == QtCore.Qt.Key_Minus: self.editor.zoom_out() event.accept()
[ "def", "_on_key_pressed", "(", "self", ",", "event", ")", ":", "if", "(", "int", "(", "event", ".", "modifiers", "(", ")", ")", "&", "QtCore", ".", "Qt", ".", "ControlModifier", ">", "0", "and", "not", "int", "(", "event", ".", "modifiers", "(", ")...
Resets editor font size to the default font size :param event: wheelEvent :type event: QKeyEvent
[ "Resets", "editor", "font", "size", "to", "the", "default", "font", "size" ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/modes/zoom.py#L55-L72
train
46,361
pyQode/pyqode.core
pyqode/core/modes/zoom.py
ZoomMode._on_wheel_event
def _on_wheel_event(self, event): """ Increments or decrements editor fonts settings on mouse wheel event if ctrl modifier is on. :param event: wheel event :type event: QWheelEvent """ try: delta = event.angleDelta().y() except AttributeError: # PyQt4/PySide delta = event.delta() if int(event.modifiers()) & QtCore.Qt.ControlModifier > 0: if delta < self.prev_delta: self.editor.zoom_out() event.accept() else: self.editor.zoom_in() event.accept()
python
def _on_wheel_event(self, event): """ Increments or decrements editor fonts settings on mouse wheel event if ctrl modifier is on. :param event: wheel event :type event: QWheelEvent """ try: delta = event.angleDelta().y() except AttributeError: # PyQt4/PySide delta = event.delta() if int(event.modifiers()) & QtCore.Qt.ControlModifier > 0: if delta < self.prev_delta: self.editor.zoom_out() event.accept() else: self.editor.zoom_in() event.accept()
[ "def", "_on_wheel_event", "(", "self", ",", "event", ")", ":", "try", ":", "delta", "=", "event", ".", "angleDelta", "(", ")", ".", "y", "(", ")", "except", "AttributeError", ":", "# PyQt4/PySide", "delta", "=", "event", ".", "delta", "(", ")", "if", ...
Increments or decrements editor fonts settings on mouse wheel event if ctrl modifier is on. :param event: wheel event :type event: QWheelEvent
[ "Increments", "or", "decrements", "editor", "fonts", "settings", "on", "mouse", "wheel", "event", "if", "ctrl", "modifier", "is", "on", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/modes/zoom.py#L74-L93
train
46,362
pyQode/pyqode.core
pyqode/core/widgets/interactive.py
InteractiveConsole.set_writer
def set_writer(self, writer): """ Changes the writer function to handle writing to the text edit. A writer function must have the following prototype: .. code-block:: python def write(text_edit, text, color) :param writer: write function as described above. """ if self._writer != writer and self._writer: self._writer = None if writer: self._writer = writer
python
def set_writer(self, writer): """ Changes the writer function to handle writing to the text edit. A writer function must have the following prototype: .. code-block:: python def write(text_edit, text, color) :param writer: write function as described above. """ if self._writer != writer and self._writer: self._writer = None if writer: self._writer = writer
[ "def", "set_writer", "(", "self", ",", "writer", ")", ":", "if", "self", ".", "_writer", "!=", "writer", "and", "self", ".", "_writer", ":", "self", ".", "_writer", "=", "None", "if", "writer", ":", "self", ".", "_writer", "=", "writer" ]
Changes the writer function to handle writing to the text edit. A writer function must have the following prototype: .. code-block:: python def write(text_edit, text, color) :param writer: write function as described above.
[ "Changes", "the", "writer", "function", "to", "handle", "writing", "to", "the", "text", "edit", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/widgets/interactive.py#L98-L113
train
46,363
pyQode/pyqode.core
pyqode/core/widgets/interactive.py
InteractiveConsole.start_process
def start_process(self, process, args=None, cwd=None, env=None): """ Starts a process interactively. :param process: Process to run :type process: str :param args: List of arguments (list of str) :type args: list :param cwd: Working directory :type cwd: str :param env: environment variables (dict). """ self.setReadOnly(False) if env is None: env = {} if args is None: args = [] if not self._running: self.process = QProcess() self.process.finished.connect(self._on_process_finished) self.process.started.connect(self.process_started.emit) self.process.error.connect(self._write_error) self.process.readyReadStandardError.connect(self._on_stderr) self.process.readyReadStandardOutput.connect(self._on_stdout) if cwd: self.process.setWorkingDirectory(cwd) e = self.process.systemEnvironment() ev = QProcessEnvironment() for v in e: values = v.split('=') ev.insert(values[0], '='.join(values[1:])) for k, v in env.items(): ev.insert(k, v) self.process.setProcessEnvironment(ev) self._running = True self._process_name = process self._args = args if self._clear_on_start: self.clear() self._user_stop = False self._write_started() self.process.start(process, args) self.process.waitForStarted() else: _logger().warning('a process is already running')
python
def start_process(self, process, args=None, cwd=None, env=None): """ Starts a process interactively. :param process: Process to run :type process: str :param args: List of arguments (list of str) :type args: list :param cwd: Working directory :type cwd: str :param env: environment variables (dict). """ self.setReadOnly(False) if env is None: env = {} if args is None: args = [] if not self._running: self.process = QProcess() self.process.finished.connect(self._on_process_finished) self.process.started.connect(self.process_started.emit) self.process.error.connect(self._write_error) self.process.readyReadStandardError.connect(self._on_stderr) self.process.readyReadStandardOutput.connect(self._on_stdout) if cwd: self.process.setWorkingDirectory(cwd) e = self.process.systemEnvironment() ev = QProcessEnvironment() for v in e: values = v.split('=') ev.insert(values[0], '='.join(values[1:])) for k, v in env.items(): ev.insert(k, v) self.process.setProcessEnvironment(ev) self._running = True self._process_name = process self._args = args if self._clear_on_start: self.clear() self._user_stop = False self._write_started() self.process.start(process, args) self.process.waitForStarted() else: _logger().warning('a process is already running')
[ "def", "start_process", "(", "self", ",", "process", ",", "args", "=", "None", ",", "cwd", "=", "None", ",", "env", "=", "None", ")", ":", "self", ".", "setReadOnly", "(", "False", ")", "if", "env", "is", "None", ":", "env", "=", "{", "}", "if", ...
Starts a process interactively. :param process: Process to run :type process: str :param args: List of arguments (list of str) :type args: list :param cwd: Working directory :type cwd: str :param env: environment variables (dict).
[ "Starts", "a", "process", "interactively", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/widgets/interactive.py#L271-L318
train
46,364
pyQode/pyqode.core
pyqode/core/widgets/interactive.py
InteractiveConsole.write
def write(text_edit, text, color): """ Default write function. Move the cursor to the end and insert text with the specified color. :param text_edit: QInteractiveConsole instance :type text_edit: pyqode.widgets.QInteractiveConsole :param text: Text to write :type text: str :param color: Desired text color :type color: QColor """ try: text_edit.moveCursor(QTextCursor.End) text_edit.setTextColor(color) text_edit.insertPlainText(text) text_edit.moveCursor(QTextCursor.End) except RuntimeError: pass
python
def write(text_edit, text, color): """ Default write function. Move the cursor to the end and insert text with the specified color. :param text_edit: QInteractiveConsole instance :type text_edit: pyqode.widgets.QInteractiveConsole :param text: Text to write :type text: str :param color: Desired text color :type color: QColor """ try: text_edit.moveCursor(QTextCursor.End) text_edit.setTextColor(color) text_edit.insertPlainText(text) text_edit.moveCursor(QTextCursor.End) except RuntimeError: pass
[ "def", "write", "(", "text_edit", ",", "text", ",", "color", ")", ":", "try", ":", "text_edit", ".", "moveCursor", "(", "QTextCursor", ".", "End", ")", "text_edit", ".", "setTextColor", "(", "color", ")", "text_edit", ".", "insertPlainText", "(", "text", ...
Default write function. Move the cursor to the end and insert text with the specified color. :param text_edit: QInteractiveConsole instance :type text_edit: pyqode.widgets.QInteractiveConsole :param text: Text to write :type text: str :param color: Desired text color :type color: QColor
[ "Default", "write", "function", ".", "Move", "the", "cursor", "to", "the", "end", "and", "insert", "text", "with", "the", "specified", "color", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/widgets/interactive.py#L418-L438
train
46,365
pyQode/pyqode.core
pyqode/core/widgets/interactive.py
InteractiveConsole.apply_color_scheme
def apply_color_scheme(self, color_scheme): """ Apply a pygments color scheme to the console. As there is not a 1 to 1 mapping between color scheme formats and console formats, we decided to make the following mapping (it usually looks good for most of the available pygments styles): - stdout_color = normal color - stderr_color = red (lighter if background is dark) - stdin_color = numbers color - app_msg_color = string color - bacgorund_color = background :param color_scheme: pyqode.core.api.ColorScheme to apply """ self.stdout_color = color_scheme.formats['normal'].foreground().color() self.stdin_color = color_scheme.formats['number'].foreground().color() self.app_msg_color = color_scheme.formats[ 'string'].foreground().color() self.background_color = color_scheme.background if self.background_color.lightness() < 128: self.stderr_color = QColor('#FF8080') else: self.stderr_color = QColor('red')
python
def apply_color_scheme(self, color_scheme): """ Apply a pygments color scheme to the console. As there is not a 1 to 1 mapping between color scheme formats and console formats, we decided to make the following mapping (it usually looks good for most of the available pygments styles): - stdout_color = normal color - stderr_color = red (lighter if background is dark) - stdin_color = numbers color - app_msg_color = string color - bacgorund_color = background :param color_scheme: pyqode.core.api.ColorScheme to apply """ self.stdout_color = color_scheme.formats['normal'].foreground().color() self.stdin_color = color_scheme.formats['number'].foreground().color() self.app_msg_color = color_scheme.formats[ 'string'].foreground().color() self.background_color = color_scheme.background if self.background_color.lightness() < 128: self.stderr_color = QColor('#FF8080') else: self.stderr_color = QColor('red')
[ "def", "apply_color_scheme", "(", "self", ",", "color_scheme", ")", ":", "self", ".", "stdout_color", "=", "color_scheme", ".", "formats", "[", "'normal'", "]", ".", "foreground", "(", ")", ".", "color", "(", ")", "self", ".", "stdin_color", "=", "color_sc...
Apply a pygments color scheme to the console. As there is not a 1 to 1 mapping between color scheme formats and console formats, we decided to make the following mapping (it usually looks good for most of the available pygments styles): - stdout_color = normal color - stderr_color = red (lighter if background is dark) - stdin_color = numbers color - app_msg_color = string color - bacgorund_color = background :param color_scheme: pyqode.core.api.ColorScheme to apply
[ "Apply", "a", "pygments", "color", "scheme", "to", "the", "console", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/widgets/interactive.py#L440-L465
train
46,366
pyQode/pyqode.core
pyqode/core/api/folding.py
FoldDetector.process_block
def process_block(self, current_block, previous_block, text): """ Processes a block and setup its folding info. This method call ``detect_fold_level`` and handles most of the tricky corner cases so that all you have to do is focus on getting the proper fold level foreach meaningful block, skipping the blank ones. :param current_block: current block to process :param previous_block: previous block :param text: current block text """ prev_fold_level = TextBlockHelper.get_fold_lvl(previous_block) if text.strip() == '': # blank line always have the same level as the previous line fold_level = prev_fold_level else: fold_level = self.detect_fold_level( previous_block, current_block) if fold_level > self.limit: fold_level = self.limit prev_fold_level = TextBlockHelper.get_fold_lvl(previous_block) if fold_level > prev_fold_level: # apply on previous blank lines block = current_block.previous() while block.isValid() and block.text().strip() == '': TextBlockHelper.set_fold_lvl(block, fold_level) block = block.previous() TextBlockHelper.set_fold_trigger( block, True) # update block fold level if text.strip(): TextBlockHelper.set_fold_trigger( previous_block, fold_level > prev_fold_level) TextBlockHelper.set_fold_lvl(current_block, fold_level) # user pressed enter at the beginning of a fold trigger line # the previous blank line will keep the trigger state and the new line # (which actually contains the trigger) must use the prev state ( # and prev state must then be reset). prev = current_block.previous() # real prev block (may be blank) if (prev and prev.isValid() and prev.text().strip() == '' and TextBlockHelper.is_fold_trigger(prev)): # prev line has the correct trigger fold state TextBlockHelper.set_collapsed( current_block, TextBlockHelper.is_collapsed( prev)) # make empty line not a trigger TextBlockHelper.set_fold_trigger(prev, False) TextBlockHelper.set_collapsed(prev, False)
python
def process_block(self, current_block, previous_block, text): """ Processes a block and setup its folding info. This method call ``detect_fold_level`` and handles most of the tricky corner cases so that all you have to do is focus on getting the proper fold level foreach meaningful block, skipping the blank ones. :param current_block: current block to process :param previous_block: previous block :param text: current block text """ prev_fold_level = TextBlockHelper.get_fold_lvl(previous_block) if text.strip() == '': # blank line always have the same level as the previous line fold_level = prev_fold_level else: fold_level = self.detect_fold_level( previous_block, current_block) if fold_level > self.limit: fold_level = self.limit prev_fold_level = TextBlockHelper.get_fold_lvl(previous_block) if fold_level > prev_fold_level: # apply on previous blank lines block = current_block.previous() while block.isValid() and block.text().strip() == '': TextBlockHelper.set_fold_lvl(block, fold_level) block = block.previous() TextBlockHelper.set_fold_trigger( block, True) # update block fold level if text.strip(): TextBlockHelper.set_fold_trigger( previous_block, fold_level > prev_fold_level) TextBlockHelper.set_fold_lvl(current_block, fold_level) # user pressed enter at the beginning of a fold trigger line # the previous blank line will keep the trigger state and the new line # (which actually contains the trigger) must use the prev state ( # and prev state must then be reset). prev = current_block.previous() # real prev block (may be blank) if (prev and prev.isValid() and prev.text().strip() == '' and TextBlockHelper.is_fold_trigger(prev)): # prev line has the correct trigger fold state TextBlockHelper.set_collapsed( current_block, TextBlockHelper.is_collapsed( prev)) # make empty line not a trigger TextBlockHelper.set_fold_trigger(prev, False) TextBlockHelper.set_collapsed(prev, False)
[ "def", "process_block", "(", "self", ",", "current_block", ",", "previous_block", ",", "text", ")", ":", "prev_fold_level", "=", "TextBlockHelper", ".", "get_fold_lvl", "(", "previous_block", ")", "if", "text", ".", "strip", "(", ")", "==", "''", ":", "# bla...
Processes a block and setup its folding info. This method call ``detect_fold_level`` and handles most of the tricky corner cases so that all you have to do is focus on getting the proper fold level foreach meaningful block, skipping the blank ones. :param current_block: current block to process :param previous_block: previous block :param text: current block text
[ "Processes", "a", "block", "and", "setup", "its", "folding", "info", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/api/folding.py#L66-L118
train
46,367
GoogleCloudPlatform/python-repo-tools
gcp_devrel/tools/pylint.py
read_config
def read_config(contents): """Reads pylintrc config into native ConfigParser object. Args: contents (str): The contents of the file containing the INI config. Returns: ConfigParser.ConfigParser: The parsed configuration. """ file_obj = io.StringIO(contents) config = six.moves.configparser.ConfigParser() config.readfp(file_obj) return config
python
def read_config(contents): """Reads pylintrc config into native ConfigParser object. Args: contents (str): The contents of the file containing the INI config. Returns: ConfigParser.ConfigParser: The parsed configuration. """ file_obj = io.StringIO(contents) config = six.moves.configparser.ConfigParser() config.readfp(file_obj) return config
[ "def", "read_config", "(", "contents", ")", ":", "file_obj", "=", "io", ".", "StringIO", "(", "contents", ")", "config", "=", "six", ".", "moves", ".", "configparser", ".", "ConfigParser", "(", ")", "config", ".", "readfp", "(", "file_obj", ")", "return"...
Reads pylintrc config into native ConfigParser object. Args: contents (str): The contents of the file containing the INI config. Returns: ConfigParser.ConfigParser: The parsed configuration.
[ "Reads", "pylintrc", "config", "into", "native", "ConfigParser", "object", "." ]
87422ba91814529848a2b8bf8be4294283a3e041
https://github.com/GoogleCloudPlatform/python-repo-tools/blob/87422ba91814529848a2b8bf8be4294283a3e041/gcp_devrel/tools/pylint.py#L113-L125
train
46,368
GoogleCloudPlatform/python-repo-tools
gcp_devrel/tools/pylint.py
load_local_config
def load_local_config(filename): """Loads the pylint.config.py file. Args: filename (str): The python file containing the local configuration. Returns: module: The loaded Python module. """ if not filename: return imp.new_module('local_pylint_config') module = imp.load_source('local_pylint_config', filename) return module
python
def load_local_config(filename): """Loads the pylint.config.py file. Args: filename (str): The python file containing the local configuration. Returns: module: The loaded Python module. """ if not filename: return imp.new_module('local_pylint_config') module = imp.load_source('local_pylint_config', filename) return module
[ "def", "load_local_config", "(", "filename", ")", ":", "if", "not", "filename", ":", "return", "imp", ".", "new_module", "(", "'local_pylint_config'", ")", "module", "=", "imp", ".", "load_source", "(", "'local_pylint_config'", ",", "filename", ")", "return", ...
Loads the pylint.config.py file. Args: filename (str): The python file containing the local configuration. Returns: module: The loaded Python module.
[ "Loads", "the", "pylint", ".", "config", ".", "py", "file", "." ]
87422ba91814529848a2b8bf8be4294283a3e041
https://github.com/GoogleCloudPlatform/python-repo-tools/blob/87422ba91814529848a2b8bf8be4294283a3e041/gcp_devrel/tools/pylint.py#L128-L140
train
46,369
GoogleCloudPlatform/python-repo-tools
gcp_devrel/tools/pylint.py
determine_final_config
def determine_final_config(config_module): """Determines the final additions and replacements. Combines the config module with the defaults. Args: config_module: The loaded local configuration module. Returns: Config: the final configuration. """ config = Config( DEFAULT_LIBRARY_RC_ADDITIONS, DEFAULT_LIBRARY_RC_REPLACEMENTS, DEFAULT_TEST_RC_ADDITIONS, DEFAULT_TEST_RC_REPLACEMENTS) for field in config._fields: if hasattr(config_module, field): config = config._replace(**{field: getattr(config_module, field)}) return config
python
def determine_final_config(config_module): """Determines the final additions and replacements. Combines the config module with the defaults. Args: config_module: The loaded local configuration module. Returns: Config: the final configuration. """ config = Config( DEFAULT_LIBRARY_RC_ADDITIONS, DEFAULT_LIBRARY_RC_REPLACEMENTS, DEFAULT_TEST_RC_ADDITIONS, DEFAULT_TEST_RC_REPLACEMENTS) for field in config._fields: if hasattr(config_module, field): config = config._replace(**{field: getattr(config_module, field)}) return config
[ "def", "determine_final_config", "(", "config_module", ")", ":", "config", "=", "Config", "(", "DEFAULT_LIBRARY_RC_ADDITIONS", ",", "DEFAULT_LIBRARY_RC_REPLACEMENTS", ",", "DEFAULT_TEST_RC_ADDITIONS", ",", "DEFAULT_TEST_RC_REPLACEMENTS", ")", "for", "field", "in", "config",...
Determines the final additions and replacements. Combines the config module with the defaults. Args: config_module: The loaded local configuration module. Returns: Config: the final configuration.
[ "Determines", "the", "final", "additions", "and", "replacements", "." ]
87422ba91814529848a2b8bf8be4294283a3e041
https://github.com/GoogleCloudPlatform/python-repo-tools/blob/87422ba91814529848a2b8bf8be4294283a3e041/gcp_devrel/tools/pylint.py#L148-L167
train
46,370
GoogleCloudPlatform/python-repo-tools
gcp_devrel/tools/pylint.py
lint_fileset
def lint_fileset(*dirnames, **kwargs): """Lints a group of files using a given rcfile. Keyword arguments are * ``rc_filename`` (``str``): The name of the Pylint config RC file. * ``description`` (``str``): A description of the files and configuration currently being run. Args: dirnames (tuple): Directories to run Pylint in. kwargs: The keyword arguments. The only keyword arguments are ``rc_filename`` and ``description`` and both are required. Raises: KeyError: If the wrong keyword arguments are used. """ try: rc_filename = kwargs['rc_filename'] description = kwargs['description'] if len(kwargs) != 2: raise KeyError except KeyError: raise KeyError(_LINT_FILESET_MSG) pylint_shell_command = ['pylint', '--rcfile', rc_filename] pylint_shell_command.extend(dirnames) status_code = subprocess.call(pylint_shell_command) if status_code != 0: error_message = _ERROR_TEMPLATE.format(description, status_code) print(error_message, file=sys.stderr) sys.exit(status_code)
python
def lint_fileset(*dirnames, **kwargs): """Lints a group of files using a given rcfile. Keyword arguments are * ``rc_filename`` (``str``): The name of the Pylint config RC file. * ``description`` (``str``): A description of the files and configuration currently being run. Args: dirnames (tuple): Directories to run Pylint in. kwargs: The keyword arguments. The only keyword arguments are ``rc_filename`` and ``description`` and both are required. Raises: KeyError: If the wrong keyword arguments are used. """ try: rc_filename = kwargs['rc_filename'] description = kwargs['description'] if len(kwargs) != 2: raise KeyError except KeyError: raise KeyError(_LINT_FILESET_MSG) pylint_shell_command = ['pylint', '--rcfile', rc_filename] pylint_shell_command.extend(dirnames) status_code = subprocess.call(pylint_shell_command) if status_code != 0: error_message = _ERROR_TEMPLATE.format(description, status_code) print(error_message, file=sys.stderr) sys.exit(status_code)
[ "def", "lint_fileset", "(", "*", "dirnames", ",", "*", "*", "kwargs", ")", ":", "try", ":", "rc_filename", "=", "kwargs", "[", "'rc_filename'", "]", "description", "=", "kwargs", "[", "'description'", "]", "if", "len", "(", "kwargs", ")", "!=", "2", ":...
Lints a group of files using a given rcfile. Keyword arguments are * ``rc_filename`` (``str``): The name of the Pylint config RC file. * ``description`` (``str``): A description of the files and configuration currently being run. Args: dirnames (tuple): Directories to run Pylint in. kwargs: The keyword arguments. The only keyword arguments are ``rc_filename`` and ``description`` and both are required. Raises: KeyError: If the wrong keyword arguments are used.
[ "Lints", "a", "group", "of", "files", "using", "a", "given", "rcfile", "." ]
87422ba91814529848a2b8bf8be4294283a3e041
https://github.com/GoogleCloudPlatform/python-repo-tools/blob/87422ba91814529848a2b8bf8be4294283a3e041/gcp_devrel/tools/pylint.py#L188-L220
train
46,371
GoogleCloudPlatform/python-repo-tools
gcp_devrel/tools/pylint.py
make_rc
def make_rc(base_cfg, target_filename, additions=None, replacements=None): """Combines a base rc and additions into single file. Args: base_cfg (ConfigParser.ConfigParser): The configuration we are merging into. target_filename (str): The filename where the new configuration will be saved. additions (dict): (Optional) The values added to the configuration. replacements (dict): (Optional) The wholesale replacements for the new configuration. Raises: KeyError: if one of the additions or replacements does not already exist in the current config. """ # Set-up the mutable default values. if additions is None: additions = {} if replacements is None: replacements = {} # Create fresh config, which must extend the base one. new_cfg = six.moves.configparser.ConfigParser() # pylint: disable=protected-access new_cfg._sections = copy.deepcopy(base_cfg._sections) new_sections = new_cfg._sections # pylint: enable=protected-access for section, opts in additions.items(): curr_section = new_sections.setdefault( section, collections.OrderedDict()) for opt, opt_val in opts.items(): curr_val = curr_section.get(opt) if curr_val is None: msg = _MISSING_OPTION_ADDITION.format(opt) raise KeyError(msg) curr_val = curr_val.rstrip(',') opt_val = _transform_opt(opt_val) curr_section[opt] = '%s, %s' % (curr_val, opt_val) for section, opts in replacements.items(): curr_section = new_sections.setdefault( section, collections.OrderedDict()) for opt, opt_val in opts.items(): curr_val = curr_section.get(opt) if curr_val is None: # NOTE: This doesn't need to fail, because some options # are present in one version of pylint and not present # in another. For example ``[BASIC].method-rgx`` is # ``(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$`` in # ``1.7.5`` but in ``1.8.0`` the default config has # ``#method-rgx=`` (i.e. it is commented out in the # ``[BASIC]`` section). msg = _MISSING_OPTION_REPLACE.format(opt) print(msg, file=sys.stderr) opt_val = _transform_opt(opt_val) curr_section[opt] = '%s' % (opt_val,) with open(target_filename, 'w') as file_obj: new_cfg.write(file_obj)
python
def make_rc(base_cfg, target_filename, additions=None, replacements=None): """Combines a base rc and additions into single file. Args: base_cfg (ConfigParser.ConfigParser): The configuration we are merging into. target_filename (str): The filename where the new configuration will be saved. additions (dict): (Optional) The values added to the configuration. replacements (dict): (Optional) The wholesale replacements for the new configuration. Raises: KeyError: if one of the additions or replacements does not already exist in the current config. """ # Set-up the mutable default values. if additions is None: additions = {} if replacements is None: replacements = {} # Create fresh config, which must extend the base one. new_cfg = six.moves.configparser.ConfigParser() # pylint: disable=protected-access new_cfg._sections = copy.deepcopy(base_cfg._sections) new_sections = new_cfg._sections # pylint: enable=protected-access for section, opts in additions.items(): curr_section = new_sections.setdefault( section, collections.OrderedDict()) for opt, opt_val in opts.items(): curr_val = curr_section.get(opt) if curr_val is None: msg = _MISSING_OPTION_ADDITION.format(opt) raise KeyError(msg) curr_val = curr_val.rstrip(',') opt_val = _transform_opt(opt_val) curr_section[opt] = '%s, %s' % (curr_val, opt_val) for section, opts in replacements.items(): curr_section = new_sections.setdefault( section, collections.OrderedDict()) for opt, opt_val in opts.items(): curr_val = curr_section.get(opt) if curr_val is None: # NOTE: This doesn't need to fail, because some options # are present in one version of pylint and not present # in another. For example ``[BASIC].method-rgx`` is # ``(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$`` in # ``1.7.5`` but in ``1.8.0`` the default config has # ``#method-rgx=`` (i.e. it is commented out in the # ``[BASIC]`` section). msg = _MISSING_OPTION_REPLACE.format(opt) print(msg, file=sys.stderr) opt_val = _transform_opt(opt_val) curr_section[opt] = '%s' % (opt_val,) with open(target_filename, 'w') as file_obj: new_cfg.write(file_obj)
[ "def", "make_rc", "(", "base_cfg", ",", "target_filename", ",", "additions", "=", "None", ",", "replacements", "=", "None", ")", ":", "# Set-up the mutable default values.", "if", "additions", "is", "None", ":", "additions", "=", "{", "}", "if", "replacements", ...
Combines a base rc and additions into single file. Args: base_cfg (ConfigParser.ConfigParser): The configuration we are merging into. target_filename (str): The filename where the new configuration will be saved. additions (dict): (Optional) The values added to the configuration. replacements (dict): (Optional) The wholesale replacements for the new configuration. Raises: KeyError: if one of the additions or replacements does not already exist in the current config.
[ "Combines", "a", "base", "rc", "and", "additions", "into", "single", "file", "." ]
87422ba91814529848a2b8bf8be4294283a3e041
https://github.com/GoogleCloudPlatform/python-repo-tools/blob/87422ba91814529848a2b8bf8be4294283a3e041/gcp_devrel/tools/pylint.py#L223-L284
train
46,372
GoogleCloudPlatform/python-repo-tools
gcp_devrel/tools/pylint.py
run_command
def run_command(args): """Script entry point. Lints both sets of files.""" library_rc = 'pylintrc' test_rc = 'pylintrc.test' if os.path.exists(library_rc): os.remove(library_rc) if os.path.exists(test_rc): os.remove(test_rc) default_config = read_config(get_default_config()) user_config = load_local_config(args.config) configuration = determine_final_config(user_config) make_rc(default_config, library_rc, additions=configuration.library_additions, replacements=configuration.library_replacements) make_rc(default_config, test_rc, additions=configuration.test_additions, replacements=configuration.test_replacements) lint_fileset(*args.library_filesets, rc_filename=library_rc, description='Library') lint_fileset(*args.test_filesets, rc_filename=test_rc, description='Test')
python
def run_command(args): """Script entry point. Lints both sets of files.""" library_rc = 'pylintrc' test_rc = 'pylintrc.test' if os.path.exists(library_rc): os.remove(library_rc) if os.path.exists(test_rc): os.remove(test_rc) default_config = read_config(get_default_config()) user_config = load_local_config(args.config) configuration = determine_final_config(user_config) make_rc(default_config, library_rc, additions=configuration.library_additions, replacements=configuration.library_replacements) make_rc(default_config, test_rc, additions=configuration.test_additions, replacements=configuration.test_replacements) lint_fileset(*args.library_filesets, rc_filename=library_rc, description='Library') lint_fileset(*args.test_filesets, rc_filename=test_rc, description='Test')
[ "def", "run_command", "(", "args", ")", ":", "library_rc", "=", "'pylintrc'", "test_rc", "=", "'pylintrc.test'", "if", "os", ".", "path", ".", "exists", "(", "library_rc", ")", ":", "os", ".", "remove", "(", "library_rc", ")", "if", "os", ".", "path", ...
Script entry point. Lints both sets of files.
[ "Script", "entry", "point", ".", "Lints", "both", "sets", "of", "files", "." ]
87422ba91814529848a2b8bf8be4294283a3e041
https://github.com/GoogleCloudPlatform/python-repo-tools/blob/87422ba91814529848a2b8bf8be4294283a3e041/gcp_devrel/tools/pylint.py#L287-L312
train
46,373
psphere-project/psphere
psphere/client.py
Client.login
def login(self, username=None, password=None): """Login to a vSphere server. >>> client.login(username='Administrator', password='strongpass') :param username: The username to authenticate as. :type username: str :param password: The password to authenticate with. :type password: str """ if username is None: username = self.username if password is None: password = self.password logger.debug("Logging into server") self.sc.sessionManager.Login(userName=username, password=password) self._logged_in = True
python
def login(self, username=None, password=None): """Login to a vSphere server. >>> client.login(username='Administrator', password='strongpass') :param username: The username to authenticate as. :type username: str :param password: The password to authenticate with. :type password: str """ if username is None: username = self.username if password is None: password = self.password logger.debug("Logging into server") self.sc.sessionManager.Login(userName=username, password=password) self._logged_in = True
[ "def", "login", "(", "self", ",", "username", "=", "None", ",", "password", "=", "None", ")", ":", "if", "username", "is", "None", ":", "username", "=", "self", ".", "username", "if", "password", "is", "None", ":", "password", "=", "self", ".", "pass...
Login to a vSphere server. >>> client.login(username='Administrator', password='strongpass') :param username: The username to authenticate as. :type username: str :param password: The password to authenticate with. :type password: str
[ "Login", "to", "a", "vSphere", "server", "." ]
83a252e037c3d6e4f18bcd37380998bc9535e591
https://github.com/psphere-project/psphere/blob/83a252e037c3d6e4f18bcd37380998bc9535e591/psphere/client.py#L170-L186
train
46,374
psphere-project/psphere
psphere/client.py
Client.logout
def logout(self): """Logout of a vSphere server.""" if self._logged_in is True: self.si.flush_cache() self.sc.sessionManager.Logout() self._logged_in = False
python
def logout(self): """Logout of a vSphere server.""" if self._logged_in is True: self.si.flush_cache() self.sc.sessionManager.Logout() self._logged_in = False
[ "def", "logout", "(", "self", ")", ":", "if", "self", ".", "_logged_in", "is", "True", ":", "self", ".", "si", ".", "flush_cache", "(", ")", "self", ".", "sc", ".", "sessionManager", ".", "Logout", "(", ")", "self", ".", "_logged_in", "=", "False" ]
Logout of a vSphere server.
[ "Logout", "of", "a", "vSphere", "server", "." ]
83a252e037c3d6e4f18bcd37380998bc9535e591
https://github.com/psphere-project/psphere/blob/83a252e037c3d6e4f18bcd37380998bc9535e591/psphere/client.py#L188-L193
train
46,375
psphere-project/psphere
psphere/client.py
Client.invoke
def invoke(self, method, _this, **kwargs): """Invoke a method on the server. >>> client.invoke('CurrentTime', client.si) :param method: The method to invoke, as found in the SDK. :type method: str :param _this: The managed object reference against which to invoke \ the method. :type _this: ManagedObject :param kwargs: The arguments to pass to the method, as \ found in the SDK. :type kwargs: TODO """ if (self._logged_in is False and method not in ["Login", "RetrieveServiceContent"]): logger.critical("Cannot exec %s unless logged in", method) raise NotLoggedInError("Cannot exec %s unless logged in" % method) for kwarg in kwargs: kwargs[kwarg] = self._marshal(kwargs[kwarg]) result = getattr(self.service, method)(_this=_this, **kwargs) if hasattr(result, '__iter__') is False: logger.debug("Returning non-iterable result") return result # We must traverse the result and convert any ManagedObjectReference # to a psphere class, this will then be lazy initialised on use logger.debug(result.__class__) logger.debug("Result: %s", result) logger.debug("Length: %s", len(result)) if type(result) == list: new_result = [] for item in result: new_result.append(self._unmarshal(item)) else: new_result = self._unmarshal(result) logger.debug("Finished in invoke.") #property = self.find_and_destroy(property) #print result # Return the modified result to the caller return new_result
python
def invoke(self, method, _this, **kwargs): """Invoke a method on the server. >>> client.invoke('CurrentTime', client.si) :param method: The method to invoke, as found in the SDK. :type method: str :param _this: The managed object reference against which to invoke \ the method. :type _this: ManagedObject :param kwargs: The arguments to pass to the method, as \ found in the SDK. :type kwargs: TODO """ if (self._logged_in is False and method not in ["Login", "RetrieveServiceContent"]): logger.critical("Cannot exec %s unless logged in", method) raise NotLoggedInError("Cannot exec %s unless logged in" % method) for kwarg in kwargs: kwargs[kwarg] = self._marshal(kwargs[kwarg]) result = getattr(self.service, method)(_this=_this, **kwargs) if hasattr(result, '__iter__') is False: logger.debug("Returning non-iterable result") return result # We must traverse the result and convert any ManagedObjectReference # to a psphere class, this will then be lazy initialised on use logger.debug(result.__class__) logger.debug("Result: %s", result) logger.debug("Length: %s", len(result)) if type(result) == list: new_result = [] for item in result: new_result.append(self._unmarshal(item)) else: new_result = self._unmarshal(result) logger.debug("Finished in invoke.") #property = self.find_and_destroy(property) #print result # Return the modified result to the caller return new_result
[ "def", "invoke", "(", "self", ",", "method", ",", "_this", ",", "*", "*", "kwargs", ")", ":", "if", "(", "self", ".", "_logged_in", "is", "False", "and", "method", "not", "in", "[", "\"Login\"", ",", "\"RetrieveServiceContent\"", "]", ")", ":", "logger...
Invoke a method on the server. >>> client.invoke('CurrentTime', client.si) :param method: The method to invoke, as found in the SDK. :type method: str :param _this: The managed object reference against which to invoke \ the method. :type _this: ManagedObject :param kwargs: The arguments to pass to the method, as \ found in the SDK. :type kwargs: TODO
[ "Invoke", "a", "method", "on", "the", "server", "." ]
83a252e037c3d6e4f18bcd37380998bc9535e591
https://github.com/psphere-project/psphere/blob/83a252e037c3d6e4f18bcd37380998bc9535e591/psphere/client.py#L195-L239
train
46,376
psphere-project/psphere
psphere/client.py
Client._mor_to_pobject
def _mor_to_pobject(self, mo_ref): """Converts a MOR to a psphere object.""" kls = classmapper(mo_ref._type) new_object = kls(mo_ref, self) return new_object
python
def _mor_to_pobject(self, mo_ref): """Converts a MOR to a psphere object.""" kls = classmapper(mo_ref._type) new_object = kls(mo_ref, self) return new_object
[ "def", "_mor_to_pobject", "(", "self", ",", "mo_ref", ")", ":", "kls", "=", "classmapper", "(", "mo_ref", ".", "_type", ")", "new_object", "=", "kls", "(", "mo_ref", ",", "self", ")", "return", "new_object" ]
Converts a MOR to a psphere object.
[ "Converts", "a", "MOR", "to", "a", "psphere", "object", "." ]
83a252e037c3d6e4f18bcd37380998bc9535e591
https://github.com/psphere-project/psphere/blob/83a252e037c3d6e4f18bcd37380998bc9535e591/psphere/client.py#L241-L245
train
46,377
psphere-project/psphere
psphere/client.py
Client._marshal
def _marshal(self, obj): """Walks an object and marshals any psphere object into MORs.""" logger.debug("Checking if %s needs to be marshalled", obj) if isinstance(obj, ManagedObject): logger.debug("obj is a psphere object, converting to MOR") return obj._mo_ref if isinstance(obj, list): logger.debug("obj is a list, recursing it") new_list = [] for item in obj: new_list.append(self._marshal(item)) return new_list if not isinstance(obj, suds.sudsobject.Object): logger.debug("%s is not a sudsobject subclass, skipping", obj) return obj if hasattr(obj, '__iter__'): logger.debug("obj is iterable, recursing it") for (name, value) in obj: setattr(obj, name, self._marshal(value)) return obj # The obj has nothing that we want to marshal or traverse, return it logger.debug("obj doesn't need to be marshalled") return obj
python
def _marshal(self, obj): """Walks an object and marshals any psphere object into MORs.""" logger.debug("Checking if %s needs to be marshalled", obj) if isinstance(obj, ManagedObject): logger.debug("obj is a psphere object, converting to MOR") return obj._mo_ref if isinstance(obj, list): logger.debug("obj is a list, recursing it") new_list = [] for item in obj: new_list.append(self._marshal(item)) return new_list if not isinstance(obj, suds.sudsobject.Object): logger.debug("%s is not a sudsobject subclass, skipping", obj) return obj if hasattr(obj, '__iter__'): logger.debug("obj is iterable, recursing it") for (name, value) in obj: setattr(obj, name, self._marshal(value)) return obj # The obj has nothing that we want to marshal or traverse, return it logger.debug("obj doesn't need to be marshalled") return obj
[ "def", "_marshal", "(", "self", ",", "obj", ")", ":", "logger", ".", "debug", "(", "\"Checking if %s needs to be marshalled\"", ",", "obj", ")", "if", "isinstance", "(", "obj", ",", "ManagedObject", ")", ":", "logger", ".", "debug", "(", "\"obj is a psphere ob...
Walks an object and marshals any psphere object into MORs.
[ "Walks", "an", "object", "and", "marshals", "any", "psphere", "object", "into", "MORs", "." ]
83a252e037c3d6e4f18bcd37380998bc9535e591
https://github.com/psphere-project/psphere/blob/83a252e037c3d6e4f18bcd37380998bc9535e591/psphere/client.py#L247-L273
train
46,378
psphere-project/psphere
psphere/client.py
Client._unmarshal
def _unmarshal(self, obj): """Walks an object and unmarshals any MORs into psphere objects.""" if isinstance(obj, suds.sudsobject.Object) is False: logger.debug("%s is not a suds instance, skipping", obj) return obj logger.debug("Processing:") logger.debug(obj) logger.debug("...with keylist:") logger.debug(obj.__keylist__) # If the obj that we're looking at has a _type key # then create a class of that type and return it immediately if "_type" in obj.__keylist__: logger.debug("obj is a MOR, converting to psphere class") return self._mor_to_pobject(obj) new_object = obj.__class__() for sub_obj in obj: logger.debug("Looking at %s of type %s", sub_obj, type(sub_obj)) if isinstance(sub_obj[1], list): new_embedded_objs = [] for emb_obj in sub_obj[1]: new_emb_obj = self._unmarshal(emb_obj) new_embedded_objs.append(new_emb_obj) setattr(new_object, sub_obj[0], new_embedded_objs) continue if not issubclass(sub_obj[1].__class__, suds.sudsobject.Object): logger.debug("%s is not a sudsobject subclass, skipping", sub_obj[1].__class__) setattr(new_object, sub_obj[0], sub_obj[1]) continue logger.debug("Obj keylist: %s", sub_obj[1].__keylist__) if "_type" in sub_obj[1].__keylist__: logger.debug("Converting nested MOR to psphere class:") logger.debug(sub_obj[1]) kls = classmapper(sub_obj[1]._type) logger.debug("Setting %s.%s to %s", new_object.__class__.__name__, sub_obj[0], sub_obj[1]) setattr(new_object, sub_obj[0], kls(sub_obj[1], self)) else: logger.debug("Didn't find _type in:") logger.debug(sub_obj[1]) setattr(new_object, sub_obj[0], self._unmarshal(sub_obj[1])) return new_object
python
def _unmarshal(self, obj): """Walks an object and unmarshals any MORs into psphere objects.""" if isinstance(obj, suds.sudsobject.Object) is False: logger.debug("%s is not a suds instance, skipping", obj) return obj logger.debug("Processing:") logger.debug(obj) logger.debug("...with keylist:") logger.debug(obj.__keylist__) # If the obj that we're looking at has a _type key # then create a class of that type and return it immediately if "_type" in obj.__keylist__: logger.debug("obj is a MOR, converting to psphere class") return self._mor_to_pobject(obj) new_object = obj.__class__() for sub_obj in obj: logger.debug("Looking at %s of type %s", sub_obj, type(sub_obj)) if isinstance(sub_obj[1], list): new_embedded_objs = [] for emb_obj in sub_obj[1]: new_emb_obj = self._unmarshal(emb_obj) new_embedded_objs.append(new_emb_obj) setattr(new_object, sub_obj[0], new_embedded_objs) continue if not issubclass(sub_obj[1].__class__, suds.sudsobject.Object): logger.debug("%s is not a sudsobject subclass, skipping", sub_obj[1].__class__) setattr(new_object, sub_obj[0], sub_obj[1]) continue logger.debug("Obj keylist: %s", sub_obj[1].__keylist__) if "_type" in sub_obj[1].__keylist__: logger.debug("Converting nested MOR to psphere class:") logger.debug(sub_obj[1]) kls = classmapper(sub_obj[1]._type) logger.debug("Setting %s.%s to %s", new_object.__class__.__name__, sub_obj[0], sub_obj[1]) setattr(new_object, sub_obj[0], kls(sub_obj[1], self)) else: logger.debug("Didn't find _type in:") logger.debug(sub_obj[1]) setattr(new_object, sub_obj[0], self._unmarshal(sub_obj[1])) return new_object
[ "def", "_unmarshal", "(", "self", ",", "obj", ")", ":", "if", "isinstance", "(", "obj", ",", "suds", ".", "sudsobject", ".", "Object", ")", "is", "False", ":", "logger", ".", "debug", "(", "\"%s is not a suds instance, skipping\"", ",", "obj", ")", "return...
Walks an object and unmarshals any MORs into psphere objects.
[ "Walks", "an", "object", "and", "unmarshals", "any", "MORs", "into", "psphere", "objects", "." ]
83a252e037c3d6e4f18bcd37380998bc9535e591
https://github.com/psphere-project/psphere/blob/83a252e037c3d6e4f18bcd37380998bc9535e591/psphere/client.py#L275-L324
train
46,379
psphere-project/psphere
psphere/client.py
Client.create
def create(self, type_, **kwargs): """Create a SOAP object of the requested type. >>> client.create('VirtualE1000') :param type_: The type of SOAP object to create. :type type_: str :param kwargs: TODO :type kwargs: TODO """ obj = self.factory.create("ns0:%s" % type_) for key, value in kwargs.items(): setattr(obj, key, value) return obj
python
def create(self, type_, **kwargs): """Create a SOAP object of the requested type. >>> client.create('VirtualE1000') :param type_: The type of SOAP object to create. :type type_: str :param kwargs: TODO :type kwargs: TODO """ obj = self.factory.create("ns0:%s" % type_) for key, value in kwargs.items(): setattr(obj, key, value) return obj
[ "def", "create", "(", "self", ",", "type_", ",", "*", "*", "kwargs", ")", ":", "obj", "=", "self", ".", "factory", ".", "create", "(", "\"ns0:%s\"", "%", "type_", ")", "for", "key", ",", "value", "in", "kwargs", ".", "items", "(", ")", ":", "seta...
Create a SOAP object of the requested type. >>> client.create('VirtualE1000') :param type_: The type of SOAP object to create. :type type_: str :param kwargs: TODO :type kwargs: TODO
[ "Create", "a", "SOAP", "object", "of", "the", "requested", "type", "." ]
83a252e037c3d6e4f18bcd37380998bc9535e591
https://github.com/psphere-project/psphere/blob/83a252e037c3d6e4f18bcd37380998bc9535e591/psphere/client.py#L326-L340
train
46,380
psphere-project/psphere
psphere/client.py
Client.get_views
def get_views(self, mo_refs, properties=None): """Get a list of local view's for multiple managed objects. :param mo_refs: The list of ManagedObjectReference's that views are \ to be created for. :type mo_refs: ManagedObjectReference :param properties: The properties to retrieve in the views. :type properties: list :returns: A list of local instances representing the server-side \ managed objects. :rtype: list of ManagedObject's """ property_specs = [] for mo_ref in mo_refs: property_spec = self.create('PropertySpec') property_spec.type = str(mo_ref._type) if properties is None: properties = [] else: # Only retrieve the requested properties if properties == "all": property_spec.all = True else: property_spec.all = False property_spec.pathSet = properties property_specs.append(property_spec) object_specs = [] for mo_ref in mo_refs: object_spec = self.create('ObjectSpec') object_spec.obj = mo_ref object_specs.append(object_spec) pfs = self.create('PropertyFilterSpec') pfs.propSet = property_specs pfs.objectSet = object_specs object_contents = self.sc.propertyCollector.RetrieveProperties( specSet=pfs) views = [] for object_content in object_contents: # Update the instance with the data in object_content object_content.obj._set_view_data(object_content=object_content) views.append(object_content.obj) return views
python
def get_views(self, mo_refs, properties=None): """Get a list of local view's for multiple managed objects. :param mo_refs: The list of ManagedObjectReference's that views are \ to be created for. :type mo_refs: ManagedObjectReference :param properties: The properties to retrieve in the views. :type properties: list :returns: A list of local instances representing the server-side \ managed objects. :rtype: list of ManagedObject's """ property_specs = [] for mo_ref in mo_refs: property_spec = self.create('PropertySpec') property_spec.type = str(mo_ref._type) if properties is None: properties = [] else: # Only retrieve the requested properties if properties == "all": property_spec.all = True else: property_spec.all = False property_spec.pathSet = properties property_specs.append(property_spec) object_specs = [] for mo_ref in mo_refs: object_spec = self.create('ObjectSpec') object_spec.obj = mo_ref object_specs.append(object_spec) pfs = self.create('PropertyFilterSpec') pfs.propSet = property_specs pfs.objectSet = object_specs object_contents = self.sc.propertyCollector.RetrieveProperties( specSet=pfs) views = [] for object_content in object_contents: # Update the instance with the data in object_content object_content.obj._set_view_data(object_content=object_content) views.append(object_content.obj) return views
[ "def", "get_views", "(", "self", ",", "mo_refs", ",", "properties", "=", "None", ")", ":", "property_specs", "=", "[", "]", "for", "mo_ref", "in", "mo_refs", ":", "property_spec", "=", "self", ".", "create", "(", "'PropertySpec'", ")", "property_spec", "."...
Get a list of local view's for multiple managed objects. :param mo_refs: The list of ManagedObjectReference's that views are \ to be created for. :type mo_refs: ManagedObjectReference :param properties: The properties to retrieve in the views. :type properties: list :returns: A list of local instances representing the server-side \ managed objects. :rtype: list of ManagedObject's
[ "Get", "a", "list", "of", "local", "view", "s", "for", "multiple", "managed", "objects", "." ]
83a252e037c3d6e4f18bcd37380998bc9535e591
https://github.com/psphere-project/psphere/blob/83a252e037c3d6e4f18bcd37380998bc9535e591/psphere/client.py#L374-L420
train
46,381
psphere-project/psphere
psphere/client.py
Client.get_search_filter_spec
def get_search_filter_spec(self, begin_entity, property_spec): """Build a PropertyFilterSpec capable of full inventory traversal. By specifying all valid traversal specs we are creating a PFS that can recursively select any object under the given entity. :param begin_entity: The place in the MOB to start the search. :type begin_entity: ManagedEntity :param property_spec: TODO :type property_spec: TODO :returns: A PropertyFilterSpec, suitable for recursively searching \ under the given ManagedEntity. :rtype: PropertyFilterSpec """ # The selection spec for additional objects we want to filter ss_strings = ['resource_pool_traversal_spec', 'resource_pool_vm_traversal_spec', 'folder_traversal_spec', 'datacenter_host_traversal_spec', 'datacenter_vm_traversal_spec', 'compute_resource_rp_traversal_spec', 'compute_resource_host_traversal_spec', 'host_vm_traversal_spec', 'datacenter_datastore_traversal_spec'] # Create a selection spec for each of the strings specified above selection_specs = [ self.create('SelectionSpec', name=ss_string) for ss_string in ss_strings ] # A traversal spec for deriving ResourcePool's from found VMs rpts = self.create('TraversalSpec') rpts.name = 'resource_pool_traversal_spec' rpts.type = 'ResourcePool' rpts.path = 'resourcePool' rpts.selectSet = [selection_specs[0], selection_specs[1]] # A traversal spec for deriving ResourcePool's from found VMs rpvts = self.create('TraversalSpec') rpvts.name = 'resource_pool_vm_traversal_spec' rpvts.type = 'ResourcePool' rpvts.path = 'vm' crrts = self.create('TraversalSpec') crrts.name = 'compute_resource_rp_traversal_spec' crrts.type = 'ComputeResource' crrts.path = 'resourcePool' crrts.selectSet = [selection_specs[0], selection_specs[1]] crhts = self.create('TraversalSpec') crhts.name = 'compute_resource_host_traversal_spec' crhts.type = 'ComputeResource' crhts.path = 'host' dhts = self.create('TraversalSpec') dhts.name = 'datacenter_host_traversal_spec' dhts.type = 'Datacenter' dhts.path = 'hostFolder' dhts.selectSet = [selection_specs[2]] dsts = self.create('TraversalSpec') dsts.name = 'datacenter_datastore_traversal_spec' dsts.type = 'Datacenter' dsts.path = 'datastoreFolder' dsts.selectSet = [selection_specs[2]] dvts = self.create('TraversalSpec') dvts.name = 'datacenter_vm_traversal_spec' dvts.type = 'Datacenter' dvts.path = 'vmFolder' dvts.selectSet = [selection_specs[2]] hvts = self.create('TraversalSpec') hvts.name = 'host_vm_traversal_spec' hvts.type = 'HostSystem' hvts.path = 'vm' hvts.selectSet = [selection_specs[2]] fts = self.create('TraversalSpec') fts.name = 'folder_traversal_spec' fts.type = 'Folder' fts.path = 'childEntity' fts.selectSet = [selection_specs[2], selection_specs[3], selection_specs[4], selection_specs[5], selection_specs[6], selection_specs[7], selection_specs[1], selection_specs[8]] obj_spec = self.create('ObjectSpec') obj_spec.obj = begin_entity obj_spec.selectSet = [fts, dvts, dhts, crhts, crrts, rpts, hvts, rpvts, dsts] pfs = self.create('PropertyFilterSpec') pfs.propSet = [property_spec] pfs.objectSet = [obj_spec] return pfs
python
def get_search_filter_spec(self, begin_entity, property_spec): """Build a PropertyFilterSpec capable of full inventory traversal. By specifying all valid traversal specs we are creating a PFS that can recursively select any object under the given entity. :param begin_entity: The place in the MOB to start the search. :type begin_entity: ManagedEntity :param property_spec: TODO :type property_spec: TODO :returns: A PropertyFilterSpec, suitable for recursively searching \ under the given ManagedEntity. :rtype: PropertyFilterSpec """ # The selection spec for additional objects we want to filter ss_strings = ['resource_pool_traversal_spec', 'resource_pool_vm_traversal_spec', 'folder_traversal_spec', 'datacenter_host_traversal_spec', 'datacenter_vm_traversal_spec', 'compute_resource_rp_traversal_spec', 'compute_resource_host_traversal_spec', 'host_vm_traversal_spec', 'datacenter_datastore_traversal_spec'] # Create a selection spec for each of the strings specified above selection_specs = [ self.create('SelectionSpec', name=ss_string) for ss_string in ss_strings ] # A traversal spec for deriving ResourcePool's from found VMs rpts = self.create('TraversalSpec') rpts.name = 'resource_pool_traversal_spec' rpts.type = 'ResourcePool' rpts.path = 'resourcePool' rpts.selectSet = [selection_specs[0], selection_specs[1]] # A traversal spec for deriving ResourcePool's from found VMs rpvts = self.create('TraversalSpec') rpvts.name = 'resource_pool_vm_traversal_spec' rpvts.type = 'ResourcePool' rpvts.path = 'vm' crrts = self.create('TraversalSpec') crrts.name = 'compute_resource_rp_traversal_spec' crrts.type = 'ComputeResource' crrts.path = 'resourcePool' crrts.selectSet = [selection_specs[0], selection_specs[1]] crhts = self.create('TraversalSpec') crhts.name = 'compute_resource_host_traversal_spec' crhts.type = 'ComputeResource' crhts.path = 'host' dhts = self.create('TraversalSpec') dhts.name = 'datacenter_host_traversal_spec' dhts.type = 'Datacenter' dhts.path = 'hostFolder' dhts.selectSet = [selection_specs[2]] dsts = self.create('TraversalSpec') dsts.name = 'datacenter_datastore_traversal_spec' dsts.type = 'Datacenter' dsts.path = 'datastoreFolder' dsts.selectSet = [selection_specs[2]] dvts = self.create('TraversalSpec') dvts.name = 'datacenter_vm_traversal_spec' dvts.type = 'Datacenter' dvts.path = 'vmFolder' dvts.selectSet = [selection_specs[2]] hvts = self.create('TraversalSpec') hvts.name = 'host_vm_traversal_spec' hvts.type = 'HostSystem' hvts.path = 'vm' hvts.selectSet = [selection_specs[2]] fts = self.create('TraversalSpec') fts.name = 'folder_traversal_spec' fts.type = 'Folder' fts.path = 'childEntity' fts.selectSet = [selection_specs[2], selection_specs[3], selection_specs[4], selection_specs[5], selection_specs[6], selection_specs[7], selection_specs[1], selection_specs[8]] obj_spec = self.create('ObjectSpec') obj_spec.obj = begin_entity obj_spec.selectSet = [fts, dvts, dhts, crhts, crrts, rpts, hvts, rpvts, dsts] pfs = self.create('PropertyFilterSpec') pfs.propSet = [property_spec] pfs.objectSet = [obj_spec] return pfs
[ "def", "get_search_filter_spec", "(", "self", ",", "begin_entity", ",", "property_spec", ")", ":", "# The selection spec for additional objects we want to filter", "ss_strings", "=", "[", "'resource_pool_traversal_spec'", ",", "'resource_pool_vm_traversal_spec'", ",", "'folder_tr...
Build a PropertyFilterSpec capable of full inventory traversal. By specifying all valid traversal specs we are creating a PFS that can recursively select any object under the given entity. :param begin_entity: The place in the MOB to start the search. :type begin_entity: ManagedEntity :param property_spec: TODO :type property_spec: TODO :returns: A PropertyFilterSpec, suitable for recursively searching \ under the given ManagedEntity. :rtype: PropertyFilterSpec
[ "Build", "a", "PropertyFilterSpec", "capable", "of", "full", "inventory", "traversal", ".", "By", "specifying", "all", "valid", "traversal", "specs", "we", "are", "creating", "a", "PFS", "that", "can", "recursively", "select", "any", "object", "under", "the", ...
83a252e037c3d6e4f18bcd37380998bc9535e591
https://github.com/psphere-project/psphere/blob/83a252e037c3d6e4f18bcd37380998bc9535e591/psphere/client.py#L422-L519
train
46,382
psphere-project/psphere
psphere/client.py
Client.find_entity_views
def find_entity_views(self, view_type, begin_entity=None, properties=None): """Find all ManagedEntity's of the requested type. :param view_type: The type of ManagedEntity's to find. :type view_type: str :param begin_entity: The MOR to start searching for the entity. \ The default is to start the search at the root folder. :type begin_entity: ManagedObjectReference or None :returns: A list of ManagedEntity's :rtype: list """ if properties is None: properties = [] # Start the search at the root folder if no begin_entity was given if not begin_entity: begin_entity = self.sc.rootFolder._mo_ref property_spec = self.create('PropertySpec') property_spec.type = view_type property_spec.all = False property_spec.pathSet = properties pfs = self.get_search_filter_spec(begin_entity, property_spec) # Retrieve properties from server and update entity obj_contents = self.sc.propertyCollector.RetrieveProperties(specSet=pfs) views = [] for obj_content in obj_contents: logger.debug("In find_entity_view with object of type %s", obj_content.obj.__class__.__name__) obj_content.obj.update_view_data(properties=properties) views.append(obj_content.obj) return views
python
def find_entity_views(self, view_type, begin_entity=None, properties=None): """Find all ManagedEntity's of the requested type. :param view_type: The type of ManagedEntity's to find. :type view_type: str :param begin_entity: The MOR to start searching for the entity. \ The default is to start the search at the root folder. :type begin_entity: ManagedObjectReference or None :returns: A list of ManagedEntity's :rtype: list """ if properties is None: properties = [] # Start the search at the root folder if no begin_entity was given if not begin_entity: begin_entity = self.sc.rootFolder._mo_ref property_spec = self.create('PropertySpec') property_spec.type = view_type property_spec.all = False property_spec.pathSet = properties pfs = self.get_search_filter_spec(begin_entity, property_spec) # Retrieve properties from server and update entity obj_contents = self.sc.propertyCollector.RetrieveProperties(specSet=pfs) views = [] for obj_content in obj_contents: logger.debug("In find_entity_view with object of type %s", obj_content.obj.__class__.__name__) obj_content.obj.update_view_data(properties=properties) views.append(obj_content.obj) return views
[ "def", "find_entity_views", "(", "self", ",", "view_type", ",", "begin_entity", "=", "None", ",", "properties", "=", "None", ")", ":", "if", "properties", "is", "None", ":", "properties", "=", "[", "]", "# Start the search at the root folder if no begin_entity was g...
Find all ManagedEntity's of the requested type. :param view_type: The type of ManagedEntity's to find. :type view_type: str :param begin_entity: The MOR to start searching for the entity. \ The default is to start the search at the root folder. :type begin_entity: ManagedObjectReference or None :returns: A list of ManagedEntity's :rtype: list
[ "Find", "all", "ManagedEntity", "s", "of", "the", "requested", "type", "." ]
83a252e037c3d6e4f18bcd37380998bc9535e591
https://github.com/psphere-project/psphere/blob/83a252e037c3d6e4f18bcd37380998bc9535e591/psphere/client.py#L552-L588
train
46,383
psphere-project/psphere
psphere/client.py
Client.find_entity_view
def find_entity_view(self, view_type, begin_entity=None, filter={}, properties=None): """Find a ManagedEntity of the requested type. Traverses the MOB looking for an entity matching the filter. :param view_type: The type of ManagedEntity to find. :type view_type: str :param begin_entity: The MOR to start searching for the entity. \ The default is to start the search at the root folder. :type begin_entity: ManagedObjectReference or None :param filter: Key/value pairs to filter the results. The key is \ a valid parameter of the ManagedEntity type. The value is what \ that parameter should match. :type filter: dict :returns: If an entity is found, a ManagedEntity matching the search. :rtype: ManagedEntity """ if properties is None: properties = [] kls = classmapper(view_type) # Start the search at the root folder if no begin_entity was given if not begin_entity: begin_entity = self.sc.rootFolder._mo_ref logger.debug("Using %s", self.sc.rootFolder._mo_ref) property_spec = self.create('PropertySpec') property_spec.type = view_type property_spec.all = False property_spec.pathSet = list(filter.keys()) pfs = self.get_search_filter_spec(begin_entity, property_spec) # Retrieve properties from server and update entity #obj_contents = self.propertyCollector.RetrieveProperties(specSet=pfs) obj_contents = self.sc.propertyCollector.RetrieveProperties(specSet=pfs) # TODO: Implement filtering if not filter: logger.warning('No filter specified, returning first match.') # If no filter is specified we just return the first item # in the list of returned objects logger.debug("Creating class in find_entity_view (filter)") view = kls(obj_contents[0].obj._mo_ref, self) logger.debug("Completed creating class in find_entity_view (filter)") #view.update_view_data(properties) return view matched = False # Iterate through obj_contents retrieved for obj_content in obj_contents: # If there are is no propSet, skip this one if not obj_content.propSet: continue matches = 0 # Iterate through each property in the set for prop in obj_content.propSet: for key in filter.keys(): # If the property name is in the defined filter if prop.name == key: # ...and it matches the value specified # TODO: Regex this? if prop.val == filter[prop.name]: # We've found a match matches += 1 else: break else: continue if matches == len(filter): filtered_obj_content = obj_content matched = True break else: continue if matched is not True: # There were no matches raise ObjectNotFoundError("No matching objects for filter") logger.debug("Creating class in find_entity_view") view = kls(filtered_obj_content.obj._mo_ref, self) logger.debug("Completed creating class in find_entity_view") #view.update_view_data(properties=properties) return view
python
def find_entity_view(self, view_type, begin_entity=None, filter={}, properties=None): """Find a ManagedEntity of the requested type. Traverses the MOB looking for an entity matching the filter. :param view_type: The type of ManagedEntity to find. :type view_type: str :param begin_entity: The MOR to start searching for the entity. \ The default is to start the search at the root folder. :type begin_entity: ManagedObjectReference or None :param filter: Key/value pairs to filter the results. The key is \ a valid parameter of the ManagedEntity type. The value is what \ that parameter should match. :type filter: dict :returns: If an entity is found, a ManagedEntity matching the search. :rtype: ManagedEntity """ if properties is None: properties = [] kls = classmapper(view_type) # Start the search at the root folder if no begin_entity was given if not begin_entity: begin_entity = self.sc.rootFolder._mo_ref logger.debug("Using %s", self.sc.rootFolder._mo_ref) property_spec = self.create('PropertySpec') property_spec.type = view_type property_spec.all = False property_spec.pathSet = list(filter.keys()) pfs = self.get_search_filter_spec(begin_entity, property_spec) # Retrieve properties from server and update entity #obj_contents = self.propertyCollector.RetrieveProperties(specSet=pfs) obj_contents = self.sc.propertyCollector.RetrieveProperties(specSet=pfs) # TODO: Implement filtering if not filter: logger.warning('No filter specified, returning first match.') # If no filter is specified we just return the first item # in the list of returned objects logger.debug("Creating class in find_entity_view (filter)") view = kls(obj_contents[0].obj._mo_ref, self) logger.debug("Completed creating class in find_entity_view (filter)") #view.update_view_data(properties) return view matched = False # Iterate through obj_contents retrieved for obj_content in obj_contents: # If there are is no propSet, skip this one if not obj_content.propSet: continue matches = 0 # Iterate through each property in the set for prop in obj_content.propSet: for key in filter.keys(): # If the property name is in the defined filter if prop.name == key: # ...and it matches the value specified # TODO: Regex this? if prop.val == filter[prop.name]: # We've found a match matches += 1 else: break else: continue if matches == len(filter): filtered_obj_content = obj_content matched = True break else: continue if matched is not True: # There were no matches raise ObjectNotFoundError("No matching objects for filter") logger.debug("Creating class in find_entity_view") view = kls(filtered_obj_content.obj._mo_ref, self) logger.debug("Completed creating class in find_entity_view") #view.update_view_data(properties=properties) return view
[ "def", "find_entity_view", "(", "self", ",", "view_type", ",", "begin_entity", "=", "None", ",", "filter", "=", "{", "}", ",", "properties", "=", "None", ")", ":", "if", "properties", "is", "None", ":", "properties", "=", "[", "]", "kls", "=", "classma...
Find a ManagedEntity of the requested type. Traverses the MOB looking for an entity matching the filter. :param view_type: The type of ManagedEntity to find. :type view_type: str :param begin_entity: The MOR to start searching for the entity. \ The default is to start the search at the root folder. :type begin_entity: ManagedObjectReference or None :param filter: Key/value pairs to filter the results. The key is \ a valid parameter of the ManagedEntity type. The value is what \ that parameter should match. :type filter: dict :returns: If an entity is found, a ManagedEntity matching the search. :rtype: ManagedEntity
[ "Find", "a", "ManagedEntity", "of", "the", "requested", "type", "." ]
83a252e037c3d6e4f18bcd37380998bc9535e591
https://github.com/psphere-project/psphere/blob/83a252e037c3d6e4f18bcd37380998bc9535e591/psphere/client.py#L590-L677
train
46,384
psphere-project/psphere
psphere/template.py
load_template
def load_template(name=None): """Loads a template of the specified name. Templates are placed in the <template_dir> directory in YAML format with a .yaml extension. If no name is specified then the function will return the default template (<template_dir>/default.yaml) if it exists. :param name: The name of the template to load. :type name: str or None (default) """ if name is None: name = "default" logger.info("Loading template with name %s", name) try: template_file = open("%s/%s.yaml" % (template_path, name)) except IOError: raise TemplateNotFoundError template = yaml.safe_load(template_file) template_file.close() if "extends" in template: logger.debug("Merging %s with %s", name, template["extends"]) template = _merge(load_template(template["extends"]), template) return template
python
def load_template(name=None): """Loads a template of the specified name. Templates are placed in the <template_dir> directory in YAML format with a .yaml extension. If no name is specified then the function will return the default template (<template_dir>/default.yaml) if it exists. :param name: The name of the template to load. :type name: str or None (default) """ if name is None: name = "default" logger.info("Loading template with name %s", name) try: template_file = open("%s/%s.yaml" % (template_path, name)) except IOError: raise TemplateNotFoundError template = yaml.safe_load(template_file) template_file.close() if "extends" in template: logger.debug("Merging %s with %s", name, template["extends"]) template = _merge(load_template(template["extends"]), template) return template
[ "def", "load_template", "(", "name", "=", "None", ")", ":", "if", "name", "is", "None", ":", "name", "=", "\"default\"", "logger", ".", "info", "(", "\"Loading template with name %s\"", ",", "name", ")", "try", ":", "template_file", "=", "open", "(", "\"%s...
Loads a template of the specified name. Templates are placed in the <template_dir> directory in YAML format with a .yaml extension. If no name is specified then the function will return the default template (<template_dir>/default.yaml) if it exists. :param name: The name of the template to load. :type name: str or None (default)
[ "Loads", "a", "template", "of", "the", "specified", "name", "." ]
83a252e037c3d6e4f18bcd37380998bc9535e591
https://github.com/psphere-project/psphere/blob/83a252e037c3d6e4f18bcd37380998bc9535e591/psphere/template.py#L38-L66
train
46,385
psphere-project/psphere
psphere/template.py
list_templates
def list_templates(): """Returns a list of all templates.""" templates = [f for f in glob.glob(os.path.join(template_path, '*.yaml'))] return templates
python
def list_templates(): """Returns a list of all templates.""" templates = [f for f in glob.glob(os.path.join(template_path, '*.yaml'))] return templates
[ "def", "list_templates", "(", ")", ":", "templates", "=", "[", "f", "for", "f", "in", "glob", ".", "glob", "(", "os", ".", "path", ".", "join", "(", "template_path", ",", "'*.yaml'", ")", ")", "]", "return", "templates" ]
Returns a list of all templates.
[ "Returns", "a", "list", "of", "all", "templates", "." ]
83a252e037c3d6e4f18bcd37380998bc9535e591
https://github.com/psphere-project/psphere/blob/83a252e037c3d6e4f18bcd37380998bc9535e591/psphere/template.py#L69-L72
train
46,386
psphere-project/psphere
examples/vmcreate.py
create_nic
def create_nic(client, target, nic): """Return a NIC spec""" # Iterate through the networks and look for one matching # the requested name for network in target.network: if network.name == nic["network_name"]: net = network break else: return None # Success! Create a nic attached to this network backing = client.create("VirtualEthernetCardNetworkBackingInfo") backing.deviceName = nic["network_name"] backing.network = net connect_info = client.create("VirtualDeviceConnectInfo") connect_info.allowGuestControl = True connect_info.connected = False connect_info.startConnected = True new_nic = client.create(nic["type"]) new_nic.backing = backing new_nic.key = 2 # TODO: Work out a way to automatically increment this new_nic.unitNumber = 1 new_nic.addressType = "generated" new_nic.connectable = connect_info nic_spec = client.create("VirtualDeviceConfigSpec") nic_spec.device = new_nic nic_spec.fileOperation = None operation = client.create("VirtualDeviceConfigSpecOperation") nic_spec.operation = (operation.add) return nic_spec
python
def create_nic(client, target, nic): """Return a NIC spec""" # Iterate through the networks and look for one matching # the requested name for network in target.network: if network.name == nic["network_name"]: net = network break else: return None # Success! Create a nic attached to this network backing = client.create("VirtualEthernetCardNetworkBackingInfo") backing.deviceName = nic["network_name"] backing.network = net connect_info = client.create("VirtualDeviceConnectInfo") connect_info.allowGuestControl = True connect_info.connected = False connect_info.startConnected = True new_nic = client.create(nic["type"]) new_nic.backing = backing new_nic.key = 2 # TODO: Work out a way to automatically increment this new_nic.unitNumber = 1 new_nic.addressType = "generated" new_nic.connectable = connect_info nic_spec = client.create("VirtualDeviceConfigSpec") nic_spec.device = new_nic nic_spec.fileOperation = None operation = client.create("VirtualDeviceConfigSpecOperation") nic_spec.operation = (operation.add) return nic_spec
[ "def", "create_nic", "(", "client", ",", "target", ",", "nic", ")", ":", "# Iterate through the networks and look for one matching", "# the requested name", "for", "network", "in", "target", ".", "network", ":", "if", "network", ".", "name", "==", "nic", "[", "\"n...
Return a NIC spec
[ "Return", "a", "NIC", "spec" ]
83a252e037c3d6e4f18bcd37380998bc9535e591
https://github.com/psphere-project/psphere/blob/83a252e037c3d6e4f18bcd37380998bc9535e591/examples/vmcreate.py#L182-L217
train
46,387
psphere-project/psphere
examples/vmcreate.py
main
def main(name, options): """The main method for this script. :param name: The name of the VM to create. :type name: str :param template_name: The name of the template to use for creating \ the VM. :type template_name: str """ server = config._config_value("general", "server", options.server) if server is None: raise ValueError("server must be supplied on command line" " or in configuration file.") username = config._config_value("general", "username", options.username) if username is None: raise ValueError("username must be supplied on command line" " or in configuration file.") password = config._config_value("general", "password", options.password) if password is None: raise ValueError("password must be supplied on command line" " or in configuration file.") vm_template = None if options.template is not None: try: vm_template = template.load_template(options.template) except TemplateNotFoundError: print("ERROR: Template \"%s\" could not be found." % options.template) sys.exit(1) expected_opts = ["compute_resource", "datastore", "disksize", "nics", "memory", "num_cpus", "guest_id", "host"] vm_opts = {} for opt in expected_opts: vm_opts[opt] = getattr(options, opt) if vm_opts[opt] is None: if vm_template is None: raise ValueError("%s not specified on the command line and" " you have not specified any template to" " inherit the value from." % opt) try: vm_opts[opt] = vm_template[opt] except AttributeError: raise ValueError("%s not specified on the command line and" " no value is provided in the specified" " template." % opt) client = Client(server=server, username=username, password=password) create_vm(client, name, vm_opts["compute_resource"], vm_opts["datastore"], vm_opts["disksize"], vm_opts["nics"], vm_opts["memory"], vm_opts["num_cpus"], vm_opts["guest_id"], host=vm_opts["host"]) client.logout()
python
def main(name, options): """The main method for this script. :param name: The name of the VM to create. :type name: str :param template_name: The name of the template to use for creating \ the VM. :type template_name: str """ server = config._config_value("general", "server", options.server) if server is None: raise ValueError("server must be supplied on command line" " or in configuration file.") username = config._config_value("general", "username", options.username) if username is None: raise ValueError("username must be supplied on command line" " or in configuration file.") password = config._config_value("general", "password", options.password) if password is None: raise ValueError("password must be supplied on command line" " or in configuration file.") vm_template = None if options.template is not None: try: vm_template = template.load_template(options.template) except TemplateNotFoundError: print("ERROR: Template \"%s\" could not be found." % options.template) sys.exit(1) expected_opts = ["compute_resource", "datastore", "disksize", "nics", "memory", "num_cpus", "guest_id", "host"] vm_opts = {} for opt in expected_opts: vm_opts[opt] = getattr(options, opt) if vm_opts[opt] is None: if vm_template is None: raise ValueError("%s not specified on the command line and" " you have not specified any template to" " inherit the value from." % opt) try: vm_opts[opt] = vm_template[opt] except AttributeError: raise ValueError("%s not specified on the command line and" " no value is provided in the specified" " template." % opt) client = Client(server=server, username=username, password=password) create_vm(client, name, vm_opts["compute_resource"], vm_opts["datastore"], vm_opts["disksize"], vm_opts["nics"], vm_opts["memory"], vm_opts["num_cpus"], vm_opts["guest_id"], host=vm_opts["host"]) client.logout()
[ "def", "main", "(", "name", ",", "options", ")", ":", "server", "=", "config", ".", "_config_value", "(", "\"general\"", ",", "\"server\"", ",", "options", ".", "server", ")", "if", "server", "is", "None", ":", "raise", "ValueError", "(", "\"server must be...
The main method for this script. :param name: The name of the VM to create. :type name: str :param template_name: The name of the template to use for creating \ the VM. :type template_name: str
[ "The", "main", "method", "for", "this", "script", "." ]
83a252e037c3d6e4f18bcd37380998bc9535e591
https://github.com/psphere-project/psphere/blob/83a252e037c3d6e4f18bcd37380998bc9535e591/examples/vmcreate.py#L254-L307
train
46,388
pyQode/pyqode.core
pyqode/core/widgets/filesystem_treeview.py
FileSystemTreeView.add_ignore_patterns
def add_ignore_patterns(self, *patterns): """ Adds an ignore pattern to the list for ignore patterns. Ignore patterns are used to filter out unwanted files or directories from the file system model. A pattern is a Unix shell-style wildcards. See :mod:`fnmatch` for a deeper explanation about the shell-style wildcards. """ for ptrn in patterns: if isinstance(ptrn, list): for p in ptrn: self._ignored_patterns.append(p) else: self._ignored_patterns.append(ptrn)
python
def add_ignore_patterns(self, *patterns): """ Adds an ignore pattern to the list for ignore patterns. Ignore patterns are used to filter out unwanted files or directories from the file system model. A pattern is a Unix shell-style wildcards. See :mod:`fnmatch` for a deeper explanation about the shell-style wildcards. """ for ptrn in patterns: if isinstance(ptrn, list): for p in ptrn: self._ignored_patterns.append(p) else: self._ignored_patterns.append(ptrn)
[ "def", "add_ignore_patterns", "(", "self", ",", "*", "patterns", ")", ":", "for", "ptrn", "in", "patterns", ":", "if", "isinstance", "(", "ptrn", ",", "list", ")", ":", "for", "p", "in", "ptrn", ":", "self", ".", "_ignored_patterns", ".", "append", "("...
Adds an ignore pattern to the list for ignore patterns. Ignore patterns are used to filter out unwanted files or directories from the file system model. A pattern is a Unix shell-style wildcards. See :mod:`fnmatch` for a deeper explanation about the shell-style wildcards.
[ "Adds", "an", "ignore", "pattern", "to", "the", "list", "for", "ignore", "patterns", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/widgets/filesystem_treeview.py#L176-L191
train
46,389
pyQode/pyqode.core
pyqode/core/widgets/filesystem_treeview.py
FileSystemTreeView.set_context_menu
def set_context_menu(self, context_menu): """ Sets the context menu of the tree view. :param context_menu: QMenu """ self.context_menu = context_menu self.context_menu.tree_view = self self.context_menu.init_actions() for action in self.context_menu.actions(): self.addAction(action)
python
def set_context_menu(self, context_menu): """ Sets the context menu of the tree view. :param context_menu: QMenu """ self.context_menu = context_menu self.context_menu.tree_view = self self.context_menu.init_actions() for action in self.context_menu.actions(): self.addAction(action)
[ "def", "set_context_menu", "(", "self", ",", "context_menu", ")", ":", "self", ".", "context_menu", "=", "context_menu", "self", ".", "context_menu", ".", "tree_view", "=", "self", "self", ".", "context_menu", ".", "init_actions", "(", ")", "for", "action", ...
Sets the context menu of the tree view. :param context_menu: QMenu
[ "Sets", "the", "context", "menu", "of", "the", "tree", "view", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/widgets/filesystem_treeview.py#L193-L203
train
46,390
pyQode/pyqode.core
pyqode/core/widgets/filesystem_treeview.py
FileSystemTreeView.filePath
def filePath(self, index): """ Gets the file path of the item at the specified ``index``. :param index: item index - QModelIndex :return: str """ return self._fs_model_source.filePath( self._fs_model_proxy.mapToSource(index))
python
def filePath(self, index): """ Gets the file path of the item at the specified ``index``. :param index: item index - QModelIndex :return: str """ return self._fs_model_source.filePath( self._fs_model_proxy.mapToSource(index))
[ "def", "filePath", "(", "self", ",", "index", ")", ":", "return", "self", ".", "_fs_model_source", ".", "filePath", "(", "self", ".", "_fs_model_proxy", ".", "mapToSource", "(", "index", ")", ")" ]
Gets the file path of the item at the specified ``index``. :param index: item index - QModelIndex :return: str
[ "Gets", "the", "file", "path", "of", "the", "item", "at", "the", "specified", "index", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/widgets/filesystem_treeview.py#L269-L277
train
46,391
pyQode/pyqode.core
pyqode/core/widgets/filesystem_treeview.py
FileSystemTreeView.fileInfo
def fileInfo(self, index): """ Gets the file info of the item at the specified ``index``. :param index: item index - QModelIndex :return: QFileInfo """ return self._fs_model_source.fileInfo( self._fs_model_proxy.mapToSource(index))
python
def fileInfo(self, index): """ Gets the file info of the item at the specified ``index``. :param index: item index - QModelIndex :return: QFileInfo """ return self._fs_model_source.fileInfo( self._fs_model_proxy.mapToSource(index))
[ "def", "fileInfo", "(", "self", ",", "index", ")", ":", "return", "self", ".", "_fs_model_source", ".", "fileInfo", "(", "self", ".", "_fs_model_proxy", ".", "mapToSource", "(", "index", ")", ")" ]
Gets the file info of the item at the specified ``index``. :param index: item index - QModelIndex :return: QFileInfo
[ "Gets", "the", "file", "info", "of", "the", "item", "at", "the", "specified", "index", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/widgets/filesystem_treeview.py#L279-L287
train
46,392
pyQode/pyqode.core
pyqode/core/widgets/filesystem_treeview.py
FileSystemHelper.paste_from_clipboard
def paste_from_clipboard(self): """ Pastes files from clipboard. """ to = self.get_current_path() if os.path.isfile(to): to = os.path.abspath(os.path.join(to, os.pardir)) mime = QtWidgets.QApplication.clipboard().mimeData() paste_operation = None if mime.hasFormat(self._UrlListMimeData.format(copy=True)): paste_operation = True elif mime.hasFormat(self._UrlListMimeData.format(copy=False)): paste_operation = False if paste_operation is not None: self._paste( self._UrlListMimeData.list_from(mime, copy=paste_operation), to, copy=paste_operation)
python
def paste_from_clipboard(self): """ Pastes files from clipboard. """ to = self.get_current_path() if os.path.isfile(to): to = os.path.abspath(os.path.join(to, os.pardir)) mime = QtWidgets.QApplication.clipboard().mimeData() paste_operation = None if mime.hasFormat(self._UrlListMimeData.format(copy=True)): paste_operation = True elif mime.hasFormat(self._UrlListMimeData.format(copy=False)): paste_operation = False if paste_operation is not None: self._paste( self._UrlListMimeData.list_from(mime, copy=paste_operation), to, copy=paste_operation)
[ "def", "paste_from_clipboard", "(", "self", ")", ":", "to", "=", "self", ".", "get_current_path", "(", ")", "if", "os", ".", "path", ".", "isfile", "(", "to", ")", ":", "to", "=", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "j...
Pastes files from clipboard.
[ "Pastes", "files", "from", "clipboard", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/widgets/filesystem_treeview.py#L372-L389
train
46,393
pyQode/pyqode.core
pyqode/core/widgets/filesystem_treeview.py
FileSystemHelper._paste
def _paste(self, sources, destination, copy): """ Copies the files listed in ``sources`` to destination. Source are removed if copy is set to False. """ for src in sources: debug('%s <%s> to <%s>' % ( 'copying' if copy else 'cutting', src, destination)) perform_copy = True ext = os.path.splitext(src)[1] original = os.path.splitext(os.path.split(src)[1])[0] filename, status = QtWidgets.QInputDialog.getText( self.tree_view, _('Copy'), _('New name:'), QtWidgets.QLineEdit.Normal, original) if filename == '' or not status: return filename = filename + ext final_dest = os.path.join(destination, filename) if os.path.exists(final_dest): rep = QtWidgets.QMessageBox.question( self.tree_view, _('File exists'), _('File <%s> already exists. Do you want to erase it?') % final_dest, QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No, QtWidgets.QMessageBox.No) if rep == QtWidgets.QMessageBox.No: perform_copy = False if not perform_copy: continue try: if os.path.isfile(src): shutil.copy(src, final_dest) else: shutil.copytree(src, final_dest) except (IOError, OSError) as e: QtWidgets.QMessageBox.warning( self.tree_view, _('Copy failed'), _('Failed to copy "%s" to "%s".\n\n%s' % (src, destination, str(e)))) _logger().exception('failed to copy "%s" to "%s', src, destination) else: debug('file copied %s', src) if not copy: debug('removing source (cut operation)') if os.path.isfile(src): os.remove(src) else: shutil.rmtree(src) self.tree_view.files_renamed.emit([(src, final_dest)])
python
def _paste(self, sources, destination, copy): """ Copies the files listed in ``sources`` to destination. Source are removed if copy is set to False. """ for src in sources: debug('%s <%s> to <%s>' % ( 'copying' if copy else 'cutting', src, destination)) perform_copy = True ext = os.path.splitext(src)[1] original = os.path.splitext(os.path.split(src)[1])[0] filename, status = QtWidgets.QInputDialog.getText( self.tree_view, _('Copy'), _('New name:'), QtWidgets.QLineEdit.Normal, original) if filename == '' or not status: return filename = filename + ext final_dest = os.path.join(destination, filename) if os.path.exists(final_dest): rep = QtWidgets.QMessageBox.question( self.tree_view, _('File exists'), _('File <%s> already exists. Do you want to erase it?') % final_dest, QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No, QtWidgets.QMessageBox.No) if rep == QtWidgets.QMessageBox.No: perform_copy = False if not perform_copy: continue try: if os.path.isfile(src): shutil.copy(src, final_dest) else: shutil.copytree(src, final_dest) except (IOError, OSError) as e: QtWidgets.QMessageBox.warning( self.tree_view, _('Copy failed'), _('Failed to copy "%s" to "%s".\n\n%s' % (src, destination, str(e)))) _logger().exception('failed to copy "%s" to "%s', src, destination) else: debug('file copied %s', src) if not copy: debug('removing source (cut operation)') if os.path.isfile(src): os.remove(src) else: shutil.rmtree(src) self.tree_view.files_renamed.emit([(src, final_dest)])
[ "def", "_paste", "(", "self", ",", "sources", ",", "destination", ",", "copy", ")", ":", "for", "src", "in", "sources", ":", "debug", "(", "'%s <%s> to <%s>'", "%", "(", "'copying'", "if", "copy", "else", "'cutting'", ",", "src", ",", "destination", ")",...
Copies the files listed in ``sources`` to destination. Source are removed if copy is set to False.
[ "Copies", "the", "files", "listed", "in", "sources", "to", "destination", ".", "Source", "are", "removed", "if", "copy", "is", "set", "to", "False", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/widgets/filesystem_treeview.py#L391-L439
train
46,394
pyQode/pyqode.core
pyqode/core/widgets/filesystem_treeview.py
FileSystemHelper.delete
def delete(self): """ Deletes the selected items. """ urls = self.selected_urls() rep = QtWidgets.QMessageBox.question( self.tree_view, _('Confirm delete'), _('Are you sure about deleting the selected files/directories?'), QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No, QtWidgets.QMessageBox.Yes) if rep == QtWidgets.QMessageBox.Yes: deleted_files = [] for fn in urls: try: if os.path.isfile(fn): os.remove(fn) deleted_files.append(fn) else: files = self._get_files(fn) shutil.rmtree(fn) deleted_files += files except OSError as e: QtWidgets.QMessageBox.warning( self.tree_view, _('Delete failed'), _('Failed to remove "%s".\n\n%s') % (fn, str(e))) _logger().exception('failed to remove %s', fn) self.tree_view.files_deleted.emit(deleted_files) for d in deleted_files: debug('%s removed', d) self.tree_view.file_deleted.emit(os.path.normpath(d))
python
def delete(self): """ Deletes the selected items. """ urls = self.selected_urls() rep = QtWidgets.QMessageBox.question( self.tree_view, _('Confirm delete'), _('Are you sure about deleting the selected files/directories?'), QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No, QtWidgets.QMessageBox.Yes) if rep == QtWidgets.QMessageBox.Yes: deleted_files = [] for fn in urls: try: if os.path.isfile(fn): os.remove(fn) deleted_files.append(fn) else: files = self._get_files(fn) shutil.rmtree(fn) deleted_files += files except OSError as e: QtWidgets.QMessageBox.warning( self.tree_view, _('Delete failed'), _('Failed to remove "%s".\n\n%s') % (fn, str(e))) _logger().exception('failed to remove %s', fn) self.tree_view.files_deleted.emit(deleted_files) for d in deleted_files: debug('%s removed', d) self.tree_view.file_deleted.emit(os.path.normpath(d))
[ "def", "delete", "(", "self", ")", ":", "urls", "=", "self", ".", "selected_urls", "(", ")", "rep", "=", "QtWidgets", ".", "QMessageBox", ".", "question", "(", "self", ".", "tree_view", ",", "_", "(", "'Confirm delete'", ")", ",", "_", "(", "'Are you s...
Deletes the selected items.
[ "Deletes", "the", "selected", "items", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/widgets/filesystem_treeview.py#L452-L481
train
46,395
pyQode/pyqode.core
pyqode/core/widgets/filesystem_treeview.py
FileSystemHelper.get_current_path
def get_current_path(self): """ Gets the path of the currently selected item. """ path = self.tree_view.fileInfo( self.tree_view.currentIndex()).filePath() # https://github.com/pyQode/pyQode/issues/6 if not path: path = self.tree_view.root_path return path
python
def get_current_path(self): """ Gets the path of the currently selected item. """ path = self.tree_view.fileInfo( self.tree_view.currentIndex()).filePath() # https://github.com/pyQode/pyQode/issues/6 if not path: path = self.tree_view.root_path return path
[ "def", "get_current_path", "(", "self", ")", ":", "path", "=", "self", ".", "tree_view", ".", "fileInfo", "(", "self", ".", "tree_view", ".", "currentIndex", "(", ")", ")", ".", "filePath", "(", ")", "# https://github.com/pyQode/pyQode/issues/6", "if", "not", ...
Gets the path of the currently selected item.
[ "Gets", "the", "path", "of", "the", "currently", "selected", "item", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/widgets/filesystem_treeview.py#L483-L492
train
46,396
pyQode/pyqode.core
pyqode/core/widgets/filesystem_treeview.py
FileSystemHelper.copy_path_to_clipboard
def copy_path_to_clipboard(self): """ Copies the file path to the clipboard """ path = self.get_current_path() QtWidgets.QApplication.clipboard().setText(path) debug('path copied: %s' % path)
python
def copy_path_to_clipboard(self): """ Copies the file path to the clipboard """ path = self.get_current_path() QtWidgets.QApplication.clipboard().setText(path) debug('path copied: %s' % path)
[ "def", "copy_path_to_clipboard", "(", "self", ")", ":", "path", "=", "self", ".", "get_current_path", "(", ")", "QtWidgets", ".", "QApplication", ".", "clipboard", "(", ")", ".", "setText", "(", "path", ")", "debug", "(", "'path copied: %s'", "%", "path", ...
Copies the file path to the clipboard
[ "Copies", "the", "file", "path", "to", "the", "clipboard" ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/widgets/filesystem_treeview.py#L494-L500
train
46,397
pyQode/pyqode.core
pyqode/core/widgets/filesystem_treeview.py
FileSystemHelper.rename
def rename(self): """ Renames the selected item in the tree view """ src = self.get_current_path() pardir, name = os.path.split(src) new_name, status = QtWidgets.QInputDialog.getText( self.tree_view, _('Rename '), _('New name:'), QtWidgets.QLineEdit.Normal, name) if status: dest = os.path.join(pardir, new_name) old_files = [] if os.path.isdir(src): old_files = self._get_files(src) else: old_files = [src] try: os.rename(src, dest) except OSError as e: QtWidgets.QMessageBox.warning( self.tree_view, _('Rename failed'), _('Failed to rename "%s" into "%s".\n\n%s') % (src, dest, str(e))) else: if os.path.isdir(dest): new_files = self._get_files(dest) else: new_files = [dest] self.tree_view.file_renamed.emit(os.path.normpath(src), os.path.normpath(dest)) renamed_files = [] for old_f, new_f in zip(old_files, new_files): self.tree_view.file_renamed.emit(old_f, new_f) renamed_files.append((old_f, new_f)) # emit all changes in one go self.tree_view.files_renamed.emit(renamed_files)
python
def rename(self): """ Renames the selected item in the tree view """ src = self.get_current_path() pardir, name = os.path.split(src) new_name, status = QtWidgets.QInputDialog.getText( self.tree_view, _('Rename '), _('New name:'), QtWidgets.QLineEdit.Normal, name) if status: dest = os.path.join(pardir, new_name) old_files = [] if os.path.isdir(src): old_files = self._get_files(src) else: old_files = [src] try: os.rename(src, dest) except OSError as e: QtWidgets.QMessageBox.warning( self.tree_view, _('Rename failed'), _('Failed to rename "%s" into "%s".\n\n%s') % (src, dest, str(e))) else: if os.path.isdir(dest): new_files = self._get_files(dest) else: new_files = [dest] self.tree_view.file_renamed.emit(os.path.normpath(src), os.path.normpath(dest)) renamed_files = [] for old_f, new_f in zip(old_files, new_files): self.tree_view.file_renamed.emit(old_f, new_f) renamed_files.append((old_f, new_f)) # emit all changes in one go self.tree_view.files_renamed.emit(renamed_files)
[ "def", "rename", "(", "self", ")", ":", "src", "=", "self", ".", "get_current_path", "(", ")", "pardir", ",", "name", "=", "os", ".", "path", ".", "split", "(", "src", ")", "new_name", ",", "status", "=", "QtWidgets", ".", "QInputDialog", ".", "getTe...
Renames the selected item in the tree view
[ "Renames", "the", "selected", "item", "in", "the", "tree", "view" ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/widgets/filesystem_treeview.py#L502-L536
train
46,398
pyQode/pyqode.core
pyqode/core/widgets/filesystem_treeview.py
FileSystemHelper.create_file
def create_file(self): """ Creates a file under the current directory. """ src = self.get_current_path() name, status = QtWidgets.QInputDialog.getText( self.tree_view, _('Create new file'), _('File name:'), QtWidgets.QLineEdit.Normal, '') if status: fatal_names = ['.', '..', os.sep] for i in fatal_names: if i == name: QtWidgets.QMessageBox.critical( self.tree_view, _("Error"), _("Wrong directory name")) return if os.path.isfile(src): src = os.path.dirname(src) path = os.path.join(src, name) try: with open(path, 'w'): pass except OSError as e: QtWidgets.QMessageBox.warning( self.tree_view, _('Failed to create new file'), _('Failed to create file: "%s".\n\n%s') % (path, str(e))) else: self.tree_view.file_created.emit(os.path.normpath(path))
python
def create_file(self): """ Creates a file under the current directory. """ src = self.get_current_path() name, status = QtWidgets.QInputDialog.getText( self.tree_view, _('Create new file'), _('File name:'), QtWidgets.QLineEdit.Normal, '') if status: fatal_names = ['.', '..', os.sep] for i in fatal_names: if i == name: QtWidgets.QMessageBox.critical( self.tree_view, _("Error"), _("Wrong directory name")) return if os.path.isfile(src): src = os.path.dirname(src) path = os.path.join(src, name) try: with open(path, 'w'): pass except OSError as e: QtWidgets.QMessageBox.warning( self.tree_view, _('Failed to create new file'), _('Failed to create file: "%s".\n\n%s') % (path, str(e))) else: self.tree_view.file_created.emit(os.path.normpath(path))
[ "def", "create_file", "(", "self", ")", ":", "src", "=", "self", ".", "get_current_path", "(", ")", "name", ",", "status", "=", "QtWidgets", ".", "QInputDialog", ".", "getText", "(", "self", ".", "tree_view", ",", "_", "(", "'Create new file'", ")", ",",...
Creates a file under the current directory.
[ "Creates", "a", "file", "under", "the", "current", "directory", "." ]
a99ec6cd22d519394f613309412f8329dc4e90cb
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/widgets/filesystem_treeview.py#L565-L592
train
46,399