nwo
stringlengths
5
106
sha
stringlengths
40
40
path
stringlengths
4
174
language
stringclasses
1 value
identifier
stringlengths
1
140
parameters
stringlengths
0
87.7k
argument_list
stringclasses
1 value
return_statement
stringlengths
0
426k
docstring
stringlengths
0
64.3k
docstring_summary
stringlengths
0
26.3k
docstring_tokens
list
function
stringlengths
18
4.83M
function_tokens
list
url
stringlengths
83
304
MDAnalysis/mdanalysis
3488df3cdb0c29ed41c4fb94efe334b541e31b21
package/MDAnalysis/analysis/hole2/utils.py
python
create_vmd_surface
(sphpdb='hole.sph', filename=None, sph_process='sph_process', sos_triangle='sos_triangle', dot_density=15)
return filename
Create VMD surface file from sphpdb file. Parameters ---------- sphpdb: str, optional sphpdb file to read. Default: 'hole.sph' filename: str, optional output VMD surface file. If ``None``, a temporary file is generated. Default: ``None`` sph_process: str, optional Executable for ``sph_process`` program. Default: 'sph_process' sos_triangle: str, optional Executable for ``sos_triangle`` program. Default: 'sos_triangle' dot_density: int, optional density of facets for generating a 3D pore representation. The number controls the density of dots that will be used. A sphere of dots is placed on each centre determined in the Monte Carlo procedure. The actual number of dots written is controlled by ``dot_density`` and the ``sample`` level of the original analysis. ``dot_density`` should be set between 5 (few dots per sphere) and 35 (many dots per sphere). Default: 15 Returns ------- str the output filename for the VMD surface
Create VMD surface file from sphpdb file.
[ "Create", "VMD", "surface", "file", "from", "sphpdb", "file", "." ]
def create_vmd_surface(sphpdb='hole.sph', filename=None, sph_process='sph_process', sos_triangle='sos_triangle', dot_density=15): """Create VMD surface file from sphpdb file. Parameters ---------- sphpdb: str, optional sphpdb file to read. Default: 'hole.sph' filename: str, optional output VMD surface file. If ``None``, a temporary file is generated. Default: ``None`` sph_process: str, optional Executable for ``sph_process`` program. Default: 'sph_process' sos_triangle: str, optional Executable for ``sos_triangle`` program. Default: 'sos_triangle' dot_density: int, optional density of facets for generating a 3D pore representation. The number controls the density of dots that will be used. A sphere of dots is placed on each centre determined in the Monte Carlo procedure. The actual number of dots written is controlled by ``dot_density`` and the ``sample`` level of the original analysis. ``dot_density`` should be set between 5 (few dots per sphere) and 35 (many dots per sphere). Default: 15 Returns ------- str the output filename for the VMD surface """ fd, tmp_sos = tempfile.mkstemp(suffix=".sos", text=True) os.close(fd) sph_process_path = util.which(sph_process) if sph_process_path is None: raise OSError(errno.ENOENT, exe_err.format(name=sph_process, kw='sph_process')) base_path = os.path.dirname(sph_process_path) sos_triangle_path = util.which(sos_triangle) if sos_triangle_path is None: path = os.path.join(base_path, sos_triangle) sos_triangle_path = util.which(path) if sos_triangle_path is None: raise OSError(errno.ENOENT, exe_err.format(name=sos_triangle, kw='sos_triangle')) try: output = subprocess.check_output([sph_process_path, "-sos", "-dotden", str(dot_density), "-color", sphpdb, tmp_sos], stderr=subprocess.STDOUT) except subprocess.CalledProcessError as err: os.unlink(tmp_sos) logger.fatal("sph_process failed ({0})".format(err.returncode)) raise OSError(err.returncode, "sph_process failed") from None except: os.unlink(tmp_sos) raise if filename is None: fd, filename = tempfile.mkstemp(suffix=".sos", text=True) os.close(fd) try: # Could check: os.devnull if subprocess.DEVNULL not available (>3.3) # Suppress stderr messages of sos_triangle with open(tmp_sos) as sos, open(filename, "w") as triangles, \ open(os.devnull, 'w') as FNULL: subprocess.check_call( [sos_triangle_path, "-s"], stdin=sos, stdout=triangles, stderr=FNULL) except subprocess.CalledProcessError as err: logger.fatal("sos_triangle failed ({0})".format(err.returncode)) raise OSError(err.returncode, "sos_triangle failed") from None finally: os.unlink(tmp_sos) return filename
[ "def", "create_vmd_surface", "(", "sphpdb", "=", "'hole.sph'", ",", "filename", "=", "None", ",", "sph_process", "=", "'sph_process'", ",", "sos_triangle", "=", "'sos_triangle'", ",", "dot_density", "=", "15", ")", ":", "fd", ",", "tmp_sos", "=", "tempfile", ...
https://github.com/MDAnalysis/mdanalysis/blob/3488df3cdb0c29ed41c4fb94efe334b541e31b21/package/MDAnalysis/analysis/hole2/utils.py#L479-L559
jim-schwoebel/voicebook
0e8eae0f01487f15589c0daa2cf7ca3c6f3b8ad3
chapter_2_collection/pyAudioAnalysis3/audioBasicIO.py
python
convertFsDirWavToWav
(dirName, Fs, nC)
This function converts the WAV files stored in a folder to WAV using a different sampling freq and number of channels. ARGUMENTS: - dirName: the path of the folder where the WAVs are stored - Fs: the sampling rate of the generated WAV files - nC: the number of channesl of the generated WAV files
This function converts the WAV files stored in a folder to WAV using a different sampling freq and number of channels. ARGUMENTS: - dirName: the path of the folder where the WAVs are stored - Fs: the sampling rate of the generated WAV files - nC: the number of channesl of the generated WAV files
[ "This", "function", "converts", "the", "WAV", "files", "stored", "in", "a", "folder", "to", "WAV", "using", "a", "different", "sampling", "freq", "and", "number", "of", "channels", ".", "ARGUMENTS", ":", "-", "dirName", ":", "the", "path", "of", "the", "...
def convertFsDirWavToWav(dirName, Fs, nC): ''' This function converts the WAV files stored in a folder to WAV using a different sampling freq and number of channels. ARGUMENTS: - dirName: the path of the folder where the WAVs are stored - Fs: the sampling rate of the generated WAV files - nC: the number of channesl of the generated WAV files ''' types = (dirName+os.sep+'*.wav',) # the tuple of file types filesToProcess = [] for files in types: filesToProcess.extend(glob.glob(files)) newDir = dirName + os.sep + "Fs" + str(Fs) + "_" + "NC"+str(nC) if os.path.exists(newDir) and newDir!=".": shutil.rmtree(newDir) os.makedirs(newDir) for f in filesToProcess: _, wavFileName = ntpath.split(f) command = "avconv -i \"" + f + "\" -ar " +str(Fs) + " -ac " + str(nC) + " \"" + newDir + os.sep + wavFileName + "\""; print(command) os.system(command)
[ "def", "convertFsDirWavToWav", "(", "dirName", ",", "Fs", ",", "nC", ")", ":", "types", "=", "(", "dirName", "+", "os", ".", "sep", "+", "'*.wav'", ",", ")", "# the tuple of file types", "filesToProcess", "=", "[", "]", "for", "files", "in", "types", ":"...
https://github.com/jim-schwoebel/voicebook/blob/0e8eae0f01487f15589c0daa2cf7ca3c6f3b8ad3/chapter_2_collection/pyAudioAnalysis3/audioBasicIO.py#L41-L65
edisonlz/fastor
342078a18363ac41d3c6b1ab29dbdd44fdb0b7b3
base/site-packages/util/cache/memcache.py
python
Client.forget_dead_hosts
(self)
Reset every host in the pool to an "alive" state.
Reset every host in the pool to an "alive" state.
[ "Reset", "every", "host", "in", "the", "pool", "to", "an", "alive", "state", "." ]
def forget_dead_hosts(self): """ Reset every host in the pool to an "alive" state. """ for s in self.servers: s.deaduntil = 0
[ "def", "forget_dead_hosts", "(", "self", ")", ":", "for", "s", "in", "self", ".", "servers", ":", "s", ".", "deaduntil", "=", "0" ]
https://github.com/edisonlz/fastor/blob/342078a18363ac41d3c6b1ab29dbdd44fdb0b7b3/base/site-packages/util/cache/memcache.py#L316-L321
mila-iqia/myia
56774a39579b4ec4123f44843ad4ca688acc859b
myia/compile/vm.py
python
FinalVM.inst_env_getitem
(self, env, idx, default)
Get an item from a grad environment.
Get an item from a grad environment.
[ "Get", "an", "item", "from", "a", "grad", "environment", "." ]
def inst_env_getitem(self, env, idx, default): """Get an item from a grad environment.""" env = self._ref(env) if len(env) < idx + 1 or env[idx] is None: self._push(self._ref(default)) return self._push(env[idx])
[ "def", "inst_env_getitem", "(", "self", ",", "env", ",", "idx", ",", "default", ")", ":", "env", "=", "self", ".", "_ref", "(", "env", ")", "if", "len", "(", "env", ")", "<", "idx", "+", "1", "or", "env", "[", "idx", "]", "is", "None", ":", "...
https://github.com/mila-iqia/myia/blob/56774a39579b4ec4123f44843ad4ca688acc859b/myia/compile/vm.py#L300-L306
keiffster/program-y
8c99b56f8c32f01a7b9887b5daae9465619d0385
src/programy/rdf/collection.py
python
RDFCollection.get_unify_vars
(self, variables)
return unified_vars
[]
def get_unify_vars(self, variables): unified_vars = {} for var in variables: unified_vars[var] = None return unified_vars
[ "def", "get_unify_vars", "(", "self", ",", "variables", ")", ":", "unified_vars", "=", "{", "}", "for", "var", "in", "variables", ":", "unified_vars", "[", "var", "]", "=", "None", "return", "unified_vars" ]
https://github.com/keiffster/program-y/blob/8c99b56f8c32f01a7b9887b5daae9465619d0385/src/programy/rdf/collection.py#L434-L438
travisgoodspeed/goodfet
1750cc1e8588af5470385e52fa098ca7364c2863
client/GoodFETMAXUSB.py
python
GoodFETMAXUSB.readbytesAS
(self,reg,length)
return toret
Peek some bytes from a register, acking prior transfer.
Peek some bytes from a register, acking prior transfer.
[ "Peek", "some", "bytes", "from", "a", "register", "acking", "prior", "transfer", "." ]
def readbytesAS(self,reg,length): """Peek some bytes from a register, acking prior transfer.""" data=[(reg<<3)|1]+range(0,length); self.writecmd(self.MAXUSBAPP,0x00,len(data),data); toret=self.data[1:len(self.data)]; ashex=""; for foo in toret: ashex=ashex+(" %02x"%ord(foo)); if self.usbverbose: print "GETAS %02x==%s" % (reg,ashex); return toret;
[ "def", "readbytesAS", "(", "self", ",", "reg", ",", "length", ")", ":", "data", "=", "[", "(", "reg", "<<", "3", ")", "|", "1", "]", "+", "range", "(", "0", ",", "length", ")", "self", ".", "writecmd", "(", "self", ".", "MAXUSBAPP", ",", "0x00"...
https://github.com/travisgoodspeed/goodfet/blob/1750cc1e8588af5470385e52fa098ca7364c2863/client/GoodFETMAXUSB.py#L299-L308
softlayer/softlayer-python
cdef7d63c66413197a9a97b0414de9f95887a82a
SoftLayer/CLI/loadbal/detail.py
python
get_member_table
(this_lb, pools)
return member_table
Generates a members table from a list of LBaaS devices
Generates a members table from a list of LBaaS devices
[ "Generates", "a", "members", "table", "from", "a", "list", "of", "LBaaS", "devices" ]
def get_member_table(this_lb, pools): """Generates a members table from a list of LBaaS devices""" # https://sldn.softlayer.com/reference/datatypes/SoftLayer_Network_LBaaS_Member/ member_col = ['UUID', 'Address', 'Weight', 'Modify', 'Active'] counter = 0 for uuid in pools.values(): member_col.append(f'P{counter}-> {uuid}') counter += 1 member_table = formatting.Table(member_col) for member in this_lb.get('members', []): row = [ member.get('uuid'), member.get('address'), member.get('weight'), utils.clean_time(member.get('modifyDate')), member.get('provisioningStatus') ] for uuid in pools: row.append(get_member_hp(this_lb.get('health'), member.get('uuid'), uuid)) member_table.add_row(row) return member_table
[ "def", "get_member_table", "(", "this_lb", ",", "pools", ")", ":", "# https://sldn.softlayer.com/reference/datatypes/SoftLayer_Network_LBaaS_Member/", "member_col", "=", "[", "'UUID'", ",", "'Address'", ",", "'Weight'", ",", "'Modify'", ",", "'Active'", "]", "counter", ...
https://github.com/softlayer/softlayer-python/blob/cdef7d63c66413197a9a97b0414de9f95887a82a/SoftLayer/CLI/loadbal/detail.py#L74-L94
StackStorm/st2
85ae05b73af422efd3097c9c05351f7f1cc8369e
st2common/st2common/util/action_db.py
python
get_runnertype_by_id
(runnertype_id)
return runnertype
Get RunnerType by id. On error, raise StackStormDBObjectNotFoundError
Get RunnerType by id.
[ "Get", "RunnerType", "by", "id", "." ]
def get_runnertype_by_id(runnertype_id): """ Get RunnerType by id. On error, raise StackStormDBObjectNotFoundError """ try: runnertype = RunnerType.get_by_id(runnertype_id) except (ValueError, ValidationError) as e: LOG.warning( 'Database lookup for runnertype with id="%s" resulted in ' "exception: %s", runnertype_id, e, ) raise StackStormDBObjectNotFoundError( "Unable to find runnertype with " 'id="%s"' % runnertype_id ) return runnertype
[ "def", "get_runnertype_by_id", "(", "runnertype_id", ")", ":", "try", ":", "runnertype", "=", "RunnerType", ".", "get_by_id", "(", "runnertype_id", ")", "except", "(", "ValueError", ",", "ValidationError", ")", "as", "e", ":", "LOG", ".", "warning", "(", "'D...
https://github.com/StackStorm/st2/blob/85ae05b73af422efd3097c9c05351f7f1cc8369e/st2common/st2common/util/action_db.py#L84-L102
researchmm/tasn
5dba8ccc096cedc63913730eeea14a9647911129
tasn-mxnet/python/mxnet/ndarray/sparse.py
python
CSRNDArray.__setitem__
(self, key, value)
x.__setitem__(i, y) <=> x[i]=y Set self[key] to value. Only slice key [:] is supported. Parameters ---------- key : mxnet.ndarray.NDArray.slice The indexing key. value : NDArray or CSRNDArray or numpy.ndarray The value to set. Examples -------- >>> src = mx.nd.sparse.zeros('csr', (3,3)) >>> src.asnumpy() array([[ 0., 0., 0.], [ 0., 0., 0.], [ 0., 0., 0.]], dtype=float32) >>> # assign CSRNDArray with same storage type >>> x = mx.nd.ones((3,3)).tostype('csr') >>> x[:] = src >>> x.asnumpy() array([[ 1., 1., 1.], [ 1., 1., 1.], [ 1., 1., 1.]], dtype=float32) >>> # assign NDArray to CSRNDArray >>> x[:] = mx.nd.ones((3,3)) * 2 >>> x.asnumpy() array([[ 2., 2., 2.], [ 2., 2., 2.], [ 2., 2., 2.]], dtype=float32)
x.__setitem__(i, y) <=> x[i]=y
[ "x", ".", "__setitem__", "(", "i", "y", ")", "<", "=", ">", "x", "[", "i", "]", "=", "y" ]
def __setitem__(self, key, value): """x.__setitem__(i, y) <=> x[i]=y Set self[key] to value. Only slice key [:] is supported. Parameters ---------- key : mxnet.ndarray.NDArray.slice The indexing key. value : NDArray or CSRNDArray or numpy.ndarray The value to set. Examples -------- >>> src = mx.nd.sparse.zeros('csr', (3,3)) >>> src.asnumpy() array([[ 0., 0., 0.], [ 0., 0., 0.], [ 0., 0., 0.]], dtype=float32) >>> # assign CSRNDArray with same storage type >>> x = mx.nd.ones((3,3)).tostype('csr') >>> x[:] = src >>> x.asnumpy() array([[ 1., 1., 1.], [ 1., 1., 1.], [ 1., 1., 1.]], dtype=float32) >>> # assign NDArray to CSRNDArray >>> x[:] = mx.nd.ones((3,3)) * 2 >>> x.asnumpy() array([[ 2., 2., 2.], [ 2., 2., 2.], [ 2., 2., 2.]], dtype=float32) """ if not self.writable: raise ValueError('Failed to assign to a readonly CSRNDArray') if isinstance(key, py_slice): if key.step is not None or key.start is not None or key.stop is not None: raise ValueError('Assignment with slice for CSRNDArray is not ' \ 'implemented yet.') if isinstance(value, NDArray): # avoid copying to itself if value.handle is not self.handle: value.copyto(self) elif isinstance(value, numeric_types): raise ValueError("Assigning numeric types to CSRNDArray is " \ "not implemented yet.") elif isinstance(value, (np.ndarray, np.generic)): # TODO(haibin/anisub) check scipy.sparse and use _sync_copy_from to # avoid the temporary copy warnings.warn('Assigning non-NDArray object to CSRNDArray is not efficient', RuntimeWarning) tmp = _array(value) tmp.copyto(self) else: raise TypeError('type %s not supported' % str(type(value))) else: assert(isinstance(key, (int, tuple))) raise Exception('CSRNDArray only supports [:] for assignment')
[ "def", "__setitem__", "(", "self", ",", "key", ",", "value", ")", ":", "if", "not", "self", ".", "writable", ":", "raise", "ValueError", "(", "'Failed to assign to a readonly CSRNDArray'", ")", "if", "isinstance", "(", "key", ",", "py_slice", ")", ":", "if",...
https://github.com/researchmm/tasn/blob/5dba8ccc096cedc63913730eeea14a9647911129/tasn-mxnet/python/mxnet/ndarray/sparse.py#L385-L442
python-attrs/attrs
5f36ba9b89d4d196f80147d4f2961fb2f97ae2e5
src/attr/validators.py
python
set_disabled
(disabled)
Globally disable or enable running validators. By default, they are run. :param disabled: If ``True``, disable running all validators. :type disabled: bool .. warning:: This function is not thread-safe! .. versionadded:: 21.3.0
Globally disable or enable running validators.
[ "Globally", "disable", "or", "enable", "running", "validators", "." ]
def set_disabled(disabled): """ Globally disable or enable running validators. By default, they are run. :param disabled: If ``True``, disable running all validators. :type disabled: bool .. warning:: This function is not thread-safe! .. versionadded:: 21.3.0 """ set_run_validators(not disabled)
[ "def", "set_disabled", "(", "disabled", ")", ":", "set_run_validators", "(", "not", "disabled", ")" ]
https://github.com/python-attrs/attrs/blob/5f36ba9b89d4d196f80147d4f2961fb2f97ae2e5/src/attr/validators.py#L46-L61
angr/angr
4b04d56ace135018083d36d9083805be8146688b
angr/misc/bug_report.py
python
get_venv
()
return None
[]
def get_venv(): if 'VIRTUAL_ENV' in os.environ: return os.environ['VIRTUAL_ENV'] return None
[ "def", "get_venv", "(", ")", ":", "if", "'VIRTUAL_ENV'", "in", "os", ".", "environ", ":", "return", "os", ".", "environ", "[", "'VIRTUAL_ENV'", "]", "return", "None" ]
https://github.com/angr/angr/blob/4b04d56ace135018083d36d9083805be8146688b/angr/misc/bug_report.py#L25-L28
TencentCloud/tencentcloud-sdk-python
3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2
tencentcloud/ses/v20201002/models.py
python
DNSAttributes.__init__
(self)
r""" :param Type: 记录类型 CNAME | A | TXT | MX :type Type: str :param SendDomain: 域名 :type SendDomain: str :param ExpectedValue: 需要配置的值 :type ExpectedValue: str :param CurrentValue: 腾讯云目前检测到的值 :type CurrentValue: str :param Status: 检测是否通过,创建时默认为false :type Status: bool
r""" :param Type: 记录类型 CNAME | A | TXT | MX :type Type: str :param SendDomain: 域名 :type SendDomain: str :param ExpectedValue: 需要配置的值 :type ExpectedValue: str :param CurrentValue: 腾讯云目前检测到的值 :type CurrentValue: str :param Status: 检测是否通过,创建时默认为false :type Status: bool
[ "r", ":", "param", "Type", ":", "记录类型", "CNAME", "|", "A", "|", "TXT", "|", "MX", ":", "type", "Type", ":", "str", ":", "param", "SendDomain", ":", "域名", ":", "type", "SendDomain", ":", "str", ":", "param", "ExpectedValue", ":", "需要配置的值", ":", "typ...
def __init__(self): r""" :param Type: 记录类型 CNAME | A | TXT | MX :type Type: str :param SendDomain: 域名 :type SendDomain: str :param ExpectedValue: 需要配置的值 :type ExpectedValue: str :param CurrentValue: 腾讯云目前检测到的值 :type CurrentValue: str :param Status: 检测是否通过,创建时默认为false :type Status: bool """ self.Type = None self.SendDomain = None self.ExpectedValue = None self.CurrentValue = None self.Status = None
[ "def", "__init__", "(", "self", ")", ":", "self", ".", "Type", "=", "None", "self", ".", "SendDomain", "=", "None", "self", ".", "ExpectedValue", "=", "None", "self", ".", "CurrentValue", "=", "None", "self", ".", "Status", "=", "None" ]
https://github.com/TencentCloud/tencentcloud-sdk-python/blob/3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2/tencentcloud/ses/v20201002/models.py#L356-L373
kevin1024/vcrpy
8c0bb73658e300065eddfafc569e656e1ef6f7bf
vcr/cassette.py
python
Cassette.__contains__
(self, request)
return False
Return whether or not a request has been stored
Return whether or not a request has been stored
[ "Return", "whether", "or", "not", "a", "request", "has", "been", "stored" ]
def __contains__(self, request): """Return whether or not a request has been stored""" for index, response in self._responses(request): if self.play_counts[index] == 0 or self.allow_playback_repeats: return True return False
[ "def", "__contains__", "(", "self", ",", "request", ")", ":", "for", "index", ",", "response", "in", "self", ".", "_responses", "(", "request", ")", ":", "if", "self", ".", "play_counts", "[", "index", "]", "==", "0", "or", "self", ".", "allow_playback...
https://github.com/kevin1024/vcrpy/blob/8c0bb73658e300065eddfafc569e656e1ef6f7bf/vcr/cassette.py#L351-L356
makerbot/ReplicatorG
d6f2b07785a5a5f1e172fb87cb4303b17c575d5d
skein_engines/skeinforge-50/skeinforge_application/skeinforge_plugins/craft_plugins/widen.py
python
getIntersectingWithinLoops
(loop, loopList, outsetLoop)
return intersectingWithinLoops
Get the loops which are intersecting or which it is within.
Get the loops which are intersecting or which it is within.
[ "Get", "the", "loops", "which", "are", "intersecting", "or", "which", "it", "is", "within", "." ]
def getIntersectingWithinLoops(loop, loopList, outsetLoop): 'Get the loops which are intersecting or which it is within.' intersectingWithinLoops = [] for otherLoop in loopList: if getIsIntersectingWithinLoop(loop, otherLoop, outsetLoop): intersectingWithinLoops.append(otherLoop) return intersectingWithinLoops
[ "def", "getIntersectingWithinLoops", "(", "loop", ",", "loopList", ",", "outsetLoop", ")", ":", "intersectingWithinLoops", "=", "[", "]", "for", "otherLoop", "in", "loopList", ":", "if", "getIsIntersectingWithinLoop", "(", "loop", ",", "otherLoop", ",", "outsetLoo...
https://github.com/makerbot/ReplicatorG/blob/d6f2b07785a5a5f1e172fb87cb4303b17c575d5d/skein_engines/skeinforge-50/skeinforge_application/skeinforge_plugins/craft_plugins/widen.py#L74-L80
GoogleCloudPlatform/professional-services
0c707aa97437f3d154035ef8548109b7882f71da
tools/ml-auto-eda/ml_eda/preprocessing/analysis_query/query_builder.py
python
build_anova_query
( table: Text, categorical_column: Text, numeric_column: Text, sampling_rate: float = 1 )
return query
Construct SQL query for extracting ANOVA data Args: table: (string), name of the table categorical_column: (string), name of the categorical attribute numeric_column: (string), name of the numerical attribute sampling_rate: (float), sampling rate Returns: string
Construct SQL query for extracting ANOVA data
[ "Construct", "SQL", "query", "for", "extracting", "ANOVA", "data" ]
def build_anova_query( table: Text, categorical_column: Text, numeric_column: Text, sampling_rate: float = 1 ) -> Text: """Construct SQL query for extracting ANOVA data Args: table: (string), name of the table categorical_column: (string), name of the categorical attribute numeric_column: (string), name of the numerical attribute sampling_rate: (float), sampling rate Returns: string """ anova_template = query_templates.ANOVA_TEMPLATE if sampling_rate < 1: where_condition = add_random_sampling(sampling_rate) else: where_condition = DUMMY_WHERE query = anova_template \ .format(table=table, categorical_column=categorical_column, numeric_column=numeric_column, anova_categorical=query_constants.ANOVA_CATEGORICAL, anova_count_per_class=query_constants.ANOVA_COUNT_PER_CLASS, anova_mean_per_class=query_constants.ANOVA_MEAN_PER_CLASS, anova_variance_per_class=query_constants.ANOVA_VARIANCE_PER_CLASS, anova_df_group=query_constants.ANOVA_DF_GROUP, anova_df_error=query_constants.ANOVA_DF_ERROR, where_condition=where_condition) return query
[ "def", "build_anova_query", "(", "table", ":", "Text", ",", "categorical_column", ":", "Text", ",", "numeric_column", ":", "Text", ",", "sampling_rate", ":", "float", "=", "1", ")", "->", "Text", ":", "anova_template", "=", "query_templates", ".", "ANOVA_TEMPL...
https://github.com/GoogleCloudPlatform/professional-services/blob/0c707aa97437f3d154035ef8548109b7882f71da/tools/ml-auto-eda/ml_eda/preprocessing/analysis_query/query_builder.py#L56-L91
dask/dask
c2b962fec1ba45440fe928869dc64cfe9cc36506
dask/dataframe/categorical.py
python
CategoricalAccessor.codes
(self)
return self._property_map("codes")
The codes of this categorical. If categories are unknown, an error is raised
The codes of this categorical.
[ "The", "codes", "of", "this", "categorical", "." ]
def codes(self): """The codes of this categorical. If categories are unknown, an error is raised""" if not self.known: msg = ( "`df.column.cat.codes` with unknown categories is not " "supported. Please use `column.cat.as_known()` or " "`df.categorize()` beforehand to ensure known categories" ) raise NotImplementedError(msg) return self._property_map("codes")
[ "def", "codes", "(", "self", ")", ":", "if", "not", "self", ".", "known", ":", "msg", "=", "(", "\"`df.column.cat.codes` with unknown categories is not \"", "\"supported. Please use `column.cat.as_known()` or \"", "\"`df.categorize()` beforehand to ensure known categories\"", ")...
https://github.com/dask/dask/blob/c2b962fec1ba45440fe928869dc64cfe9cc36506/dask/dataframe/categorical.py#L231-L242
selfboot/LeetCode
473c0c5451651140d75cbd143309c51cd8fe1cf1
Backtracking/22_GenerateParentheses.py
python
generateParenthesis
(self, n)
return solution
:type n: int :rtype: List[str]
:type n: int :rtype: List[str]
[ ":", "type", "n", ":", "int", ":", "rtype", ":", "List", "[", "str", "]" ]
def generateParenthesis(self, n): """ :type n: int :rtype: List[str] """ # node = [leftchild, rightchild, count"(", count")", current str] if not n: return [""] solution = [] root = [None, None, 1, 0, "("] self.generate_child_tree(root, n, solution) return solution
[ "def", "generateParenthesis", "(", "self", ",", "n", ")", ":", "# node = [leftchild, rightchild, count\"(\", count\")\", current str]", "if", "not", "n", ":", "return", "[", "\"\"", "]", "solution", "=", "[", "]", "root", "=", "[", "None", ",", "None", ",", "1...
https://github.com/selfboot/LeetCode/blob/473c0c5451651140d75cbd143309c51cd8fe1cf1/Backtracking/22_GenerateParentheses.py#L5-L17
BMW-InnovationLab/BMW-TensorFlow-Training-GUI
4f10d1f00f9ac312ca833e5b28fd0f8952cfee17
training_api/research/object_detection/predictors/heads/mask_head.py
python
WeightSharedConvolutionalMaskHead.predict
(self, features, num_predictions_per_location)
return mask_predictions
Predicts boxes. Args: features: A float tensor of shape [batch_size, height, width, channels] containing image features. num_predictions_per_location: Number of box predictions to be made per spatial location. Returns: mask_predictions: A tensor of shape [batch_size, num_anchors, num_classes, mask_height, mask_width] representing the mask predictions for the proposals.
Predicts boxes.
[ "Predicts", "boxes", "." ]
def predict(self, features, num_predictions_per_location): """Predicts boxes. Args: features: A float tensor of shape [batch_size, height, width, channels] containing image features. num_predictions_per_location: Number of box predictions to be made per spatial location. Returns: mask_predictions: A tensor of shape [batch_size, num_anchors, num_classes, mask_height, mask_width] representing the mask predictions for the proposals. """ mask_predictions_net = features if self._masks_are_class_agnostic: num_masks = 1 else: num_masks = self._num_classes num_mask_channels = num_masks * self._mask_height * self._mask_width if self._use_dropout: mask_predictions_net = slim.dropout( mask_predictions_net, keep_prob=self._dropout_keep_prob) mask_predictions = slim.conv2d( mask_predictions_net, num_predictions_per_location * num_mask_channels, [self._kernel_size, self._kernel_size], activation_fn=None, stride=1, padding='SAME', normalizer_fn=None, scope='MaskPredictor') batch_size = features.get_shape().as_list()[0] if batch_size is None: batch_size = tf.shape(features)[0] mask_predictions = tf.reshape( mask_predictions, [batch_size, -1, num_masks, self._mask_height, self._mask_width]) return mask_predictions
[ "def", "predict", "(", "self", ",", "features", ",", "num_predictions_per_location", ")", ":", "mask_predictions_net", "=", "features", "if", "self", ".", "_masks_are_class_agnostic", ":", "num_masks", "=", "1", "else", ":", "num_masks", "=", "self", ".", "_num_...
https://github.com/BMW-InnovationLab/BMW-TensorFlow-Training-GUI/blob/4f10d1f00f9ac312ca833e5b28fd0f8952cfee17/training_api/research/object_detection/predictors/heads/mask_head.py#L298-L334
GoogleCloudPlatform/PerfKitBenchmarker
6e3412d7d5e414b8ca30ed5eaf970cef1d919a67
perfkitbenchmarker/linux_packages/speccpu.py
python
_PrepareWithIsoFile
(vm, speccpu_vm_state)
Prepares the VM to run using the iso file. Copies the iso to the VM, mounts it, and extracts the contents. Copies the config file to the VM. Runs the SPEC install.sh script on the VM. Args: vm: BaseVirtualMachine. Recipient of the iso file. speccpu_vm_state: SpecInstallConfigurations. Modified by this function to reflect any changes to the VM that may need to be cleaned up.
Prepares the VM to run using the iso file.
[ "Prepares", "the", "VM", "to", "run", "using", "the", "iso", "file", "." ]
def _PrepareWithIsoFile(vm, speccpu_vm_state): """Prepares the VM to run using the iso file. Copies the iso to the VM, mounts it, and extracts the contents. Copies the config file to the VM. Runs the SPEC install.sh script on the VM. Args: vm: BaseVirtualMachine. Recipient of the iso file. speccpu_vm_state: SpecInstallConfigurations. Modified by this function to reflect any changes to the VM that may need to be cleaned up. """ scratch_dir = vm.GetScratchDir() # Make cpu2006 or cpu2017 directory on the VM. vm.RemoteCommand('mkdir {0}'.format(speccpu_vm_state.spec_dir)) # Copy the iso to the VM. local_iso_file_path = data.ResourcePath(speccpu_vm_state.base_iso_file_path) vm.PushFile(local_iso_file_path, scratch_dir) # Extract files from the iso to the cpu2006 or cpu2017 directory. vm.RemoteCommand('mkdir {0}'.format(speccpu_vm_state.mount_dir)) vm.RemoteCommand('sudo mount -t iso9660 -o loop {0} {1}'.format( speccpu_vm_state.iso_file_path, speccpu_vm_state.mount_dir)) vm.RemoteCommand('cp -r {0}/* {1}'.format(speccpu_vm_state.mount_dir, speccpu_vm_state.spec_dir)) # cpu2017 iso does not come with config directory nor clang.xml if speccpu_vm_state.clang_flag_file_path: vm.RemoteCommand('mkdir -p {0}'.format( os.path.dirname(speccpu_vm_state.clang_flag_file_path))) vm.PushFile(data.ResourcePath(speccpu_vm_state.base_clang_flag_file_path), speccpu_vm_state.clang_flag_file_path) vm.RemoteCommand('chmod -R 777 {0}'.format(speccpu_vm_state.spec_dir)) # Copy the cfg to the VM. local_cfg_file_path = data.ResourcePath(speccpu_vm_state.runspec_config) vm.PushFile(local_cfg_file_path, speccpu_vm_state.cfg_file_path) # Run SPEC CPU2006 or 2017 installation. install_script_path = posixpath.join(speccpu_vm_state.spec_dir, 'install.sh') vm.RobustRemoteCommand('yes | {0}'.format(install_script_path))
[ "def", "_PrepareWithIsoFile", "(", "vm", ",", "speccpu_vm_state", ")", ":", "scratch_dir", "=", "vm", ".", "GetScratchDir", "(", ")", "# Make cpu2006 or cpu2017 directory on the VM.", "vm", ".", "RemoteCommand", "(", "'mkdir {0}'", ".", "format", "(", "speccpu_vm_stat...
https://github.com/GoogleCloudPlatform/PerfKitBenchmarker/blob/6e3412d7d5e414b8ca30ed5eaf970cef1d919a67/perfkitbenchmarker/linux_packages/speccpu.py#L349-L391
kivy/kivy
fbf561f73ddba9941b1b7e771f86264c6e6eef36
kivy/tools/pep8checker/pep8.py
python
extraneous_whitespace
(logical_line)
r"""Avoid extraneous whitespace. Avoid extraneous whitespace in these situations: - Immediately inside parentheses, brackets or braces. - Immediately before a comma, semicolon, or colon. Okay: spam(ham[1], {eggs: 2}) E201: spam( ham[1], {eggs: 2}) E201: spam(ham[ 1], {eggs: 2}) E201: spam(ham[1], { eggs: 2}) E202: spam(ham[1], {eggs: 2} ) E202: spam(ham[1 ], {eggs: 2}) E202: spam(ham[1], {eggs: 2 }) E203: if x == 4: print(x, y); x, y = y , x E203: if x == 4: print(x, y); x, y = y, x E203: if x == 4 : print(x, y); x, y = y, x
r"""Avoid extraneous whitespace.
[ "r", "Avoid", "extraneous", "whitespace", "." ]
def extraneous_whitespace(logical_line): r"""Avoid extraneous whitespace. Avoid extraneous whitespace in these situations: - Immediately inside parentheses, brackets or braces. - Immediately before a comma, semicolon, or colon. Okay: spam(ham[1], {eggs: 2}) E201: spam( ham[1], {eggs: 2}) E201: spam(ham[ 1], {eggs: 2}) E201: spam(ham[1], { eggs: 2}) E202: spam(ham[1], {eggs: 2} ) E202: spam(ham[1 ], {eggs: 2}) E202: spam(ham[1], {eggs: 2 }) E203: if x == 4: print(x, y); x, y = y , x E203: if x == 4: print(x, y); x, y = y, x E203: if x == 4 : print(x, y); x, y = y, x """ line = logical_line for match in EXTRANEOUS_WHITESPACE_REGEX.finditer(line): text = match.group() char = text.strip() found = match.start() if text == char + ' ': # assert char in '([{' yield found + 1, "E201 whitespace after '%s'" % char elif line[found - 1] != ',': code = ('E202' if char in '}])' else 'E203') # if char in ',;:' yield found, "%s whitespace before '%s'" % (code, char)
[ "def", "extraneous_whitespace", "(", "logical_line", ")", ":", "line", "=", "logical_line", "for", "match", "in", "EXTRANEOUS_WHITESPACE_REGEX", ".", "finditer", "(", "line", ")", ":", "text", "=", "match", ".", "group", "(", ")", "char", "=", "text", ".", ...
https://github.com/kivy/kivy/blob/fbf561f73ddba9941b1b7e771f86264c6e6eef36/kivy/tools/pep8checker/pep8.py#L301-L330
tensorflow/tensor2tensor
2a33b152d7835af66a6d20afe7961751047e28dd
tensor2tensor/data_generators/algorithmic.py
python
random_number_lower_endian
(length, base)
return prefix + [np.random.randint(base - 1) + 1]
Helper function: generate a random number as a lower-endian digits list.
Helper function: generate a random number as a lower-endian digits list.
[ "Helper", "function", ":", "generate", "a", "random", "number", "as", "a", "lower", "-", "endian", "digits", "list", "." ]
def random_number_lower_endian(length, base): """Helper function: generate a random number as a lower-endian digits list.""" if length == 1: # Last digit can be 0 only if length is 1. return [np.random.randint(base)] prefix = [np.random.randint(base) for _ in range(length - 1)] return prefix + [np.random.randint(base - 1) + 1]
[ "def", "random_number_lower_endian", "(", "length", ",", "base", ")", ":", "if", "length", "==", "1", ":", "# Last digit can be 0 only if length is 1.", "return", "[", "np", ".", "random", ".", "randint", "(", "base", ")", "]", "prefix", "=", "[", "np", ".",...
https://github.com/tensorflow/tensor2tensor/blob/2a33b152d7835af66a6d20afe7961751047e28dd/tensor2tensor/data_generators/algorithmic.py#L344-L349
Syncplay/syncplay
5b93aeb20e80d3c208a766583363e87ea61ee85b
syncplay/vendor/qt5reactor.py
python
posixinstall
()
Install the Qt reactor.
Install the Qt reactor.
[ "Install", "the", "Qt", "reactor", "." ]
def posixinstall(): """Install the Qt reactor.""" from twisted.internet.main import installReactor p = QtReactor() installReactor(p)
[ "def", "posixinstall", "(", ")", ":", "from", "twisted", ".", "internet", ".", "main", "import", "installReactor", "p", "=", "QtReactor", "(", ")", "installReactor", "(", "p", ")" ]
https://github.com/Syncplay/syncplay/blob/5b93aeb20e80d3c208a766583363e87ea61ee85b/syncplay/vendor/qt5reactor.py#L368-L372
jython/frozen-mirror
b8d7aa4cee50c0c0fe2f4b235dd62922dd0f3f99
Lib/pydoc.py
python
HTMLDoc.bigsection
(self, title, *args)
return self.section(title, *args)
Format a section with a big heading.
Format a section with a big heading.
[ "Format", "a", "section", "with", "a", "big", "heading", "." ]
def bigsection(self, title, *args): """Format a section with a big heading.""" title = '<big><strong>%s</strong></big>' % title return self.section(title, *args)
[ "def", "bigsection", "(", "self", ",", "title", ",", "*", "args", ")", ":", "title", "=", "'<big><strong>%s</strong></big>'", "%", "title", "return", "self", ".", "section", "(", "title", ",", "*", "args", ")" ]
https://github.com/jython/frozen-mirror/blob/b8d7aa4cee50c0c0fe2f4b235dd62922dd0f3f99/Lib/pydoc.py#L469-L472
rasterio/rasterio
a66f8731d30399ff6a6a640510139550792d4d2b
rasterio/windows.py
python
bounds
(window, transform, height=0, width=0)
return left, bottom, right, top
Get the spatial bounds of a window. Parameters ---------- window: Window The input window. transform: Affine an affine transform matrix. Returns ------- left, bottom, right, top: float A tuple of spatial coordinate bounding values.
Get the spatial bounds of a window.
[ "Get", "the", "spatial", "bounds", "of", "a", "window", "." ]
def bounds(window, transform, height=0, width=0): """Get the spatial bounds of a window. Parameters ---------- window: Window The input window. transform: Affine an affine transform matrix. Returns ------- left, bottom, right, top: float A tuple of spatial coordinate bounding values. """ window = evaluate(window, height=height, width=width) row_min = window.row_off row_max = row_min + window.height col_min = window.col_off col_max = col_min + window.width left, bottom = transform * (col_min, row_max) right, top = transform * (col_max, row_min) return left, bottom, right, top
[ "def", "bounds", "(", "window", ",", "transform", ",", "height", "=", "0", ",", "width", "=", "0", ")", ":", "window", "=", "evaluate", "(", "window", ",", "height", "=", "height", ",", "width", "=", "width", ")", "row_min", "=", "window", ".", "ro...
https://github.com/rasterio/rasterio/blob/a66f8731d30399ff6a6a640510139550792d4d2b/rasterio/windows.py#L356-L380
KalleHallden/AutoTimer
2d954216700c4930baa154e28dbddc34609af7ce
env/lib/python2.7/site-packages/pip/_internal/vcs/versioncontrol.py
python
RevOptions.__repr__
(self)
return '<RevOptions {}: rev={!r}>'.format(self.vc_class.name, self.rev)
[]
def __repr__(self): return '<RevOptions {}: rev={!r}>'.format(self.vc_class.name, self.rev)
[ "def", "__repr__", "(", "self", ")", ":", "return", "'<RevOptions {}: rev={!r}>'", ".", "format", "(", "self", ".", "vc_class", ".", "name", ",", "self", ".", "rev", ")" ]
https://github.com/KalleHallden/AutoTimer/blob/2d954216700c4930baa154e28dbddc34609af7ce/env/lib/python2.7/site-packages/pip/_internal/vcs/versioncontrol.py#L82-L83
pvlib/pvlib-python
1ab0eb20f9cd9fb9f7a0ddf35f81283f2648e34a
pvlib/irradiance.py
python
get_ground_diffuse
(surface_tilt, ghi, albedo=.25, surface_type=None)
return diffuse_irrad
Estimate diffuse irradiance from ground reflections given irradiance, albedo, and surface tilt. Function to determine the portion of irradiance on a tilted surface due to ground reflections. Any of the inputs may be DataFrames or scalars. Parameters ---------- surface_tilt : numeric Surface tilt angles in decimal degrees. Tilt must be >=0 and <=180. The tilt angle is defined as degrees from horizontal (e.g. surface facing up = 0, surface facing horizon = 90). ghi : numeric Global horizontal irradiance. [W/m^2] albedo : numeric, default 0.25 Ground reflectance, typically 0.1-0.4 for surfaces on Earth (land), may increase over snow, ice, etc. May also be known as the reflection coefficient. Must be >=0 and <=1. Will be overridden if surface_type is supplied. surface_type: None or string, default None If not None, overrides albedo. String can be one of 'urban', 'grass', 'fresh grass', 'snow', 'fresh snow', 'asphalt', 'concrete', 'aluminum', 'copper', 'fresh steel', 'dirty steel', 'sea'. Returns ------- grounddiffuse : numeric Ground reflected irradiance. [W/m^2] References ---------- .. [1] Loutzenhiser P.G. et. al. "Empirical validation of models to compute solar irradiance on inclined surfaces for building energy simulation" 2007, Solar Energy vol. 81. pp. 254-267. The calculation is the last term of equations 3, 4, 7, 8, 10, 11, and 12. .. [2] albedos from: http://files.pvsyst.com/help/albedo.htm and http://en.wikipedia.org/wiki/Albedo and https://doi.org/10.1175/1520-0469(1972)029<0959:AOTSS>2.0.CO;2
Estimate diffuse irradiance from ground reflections given irradiance, albedo, and surface tilt.
[ "Estimate", "diffuse", "irradiance", "from", "ground", "reflections", "given", "irradiance", "albedo", "and", "surface", "tilt", "." ]
def get_ground_diffuse(surface_tilt, ghi, albedo=.25, surface_type=None): ''' Estimate diffuse irradiance from ground reflections given irradiance, albedo, and surface tilt. Function to determine the portion of irradiance on a tilted surface due to ground reflections. Any of the inputs may be DataFrames or scalars. Parameters ---------- surface_tilt : numeric Surface tilt angles in decimal degrees. Tilt must be >=0 and <=180. The tilt angle is defined as degrees from horizontal (e.g. surface facing up = 0, surface facing horizon = 90). ghi : numeric Global horizontal irradiance. [W/m^2] albedo : numeric, default 0.25 Ground reflectance, typically 0.1-0.4 for surfaces on Earth (land), may increase over snow, ice, etc. May also be known as the reflection coefficient. Must be >=0 and <=1. Will be overridden if surface_type is supplied. surface_type: None or string, default None If not None, overrides albedo. String can be one of 'urban', 'grass', 'fresh grass', 'snow', 'fresh snow', 'asphalt', 'concrete', 'aluminum', 'copper', 'fresh steel', 'dirty steel', 'sea'. Returns ------- grounddiffuse : numeric Ground reflected irradiance. [W/m^2] References ---------- .. [1] Loutzenhiser P.G. et. al. "Empirical validation of models to compute solar irradiance on inclined surfaces for building energy simulation" 2007, Solar Energy vol. 81. pp. 254-267. The calculation is the last term of equations 3, 4, 7, 8, 10, 11, and 12. .. [2] albedos from: http://files.pvsyst.com/help/albedo.htm and http://en.wikipedia.org/wiki/Albedo and https://doi.org/10.1175/1520-0469(1972)029<0959:AOTSS>2.0.CO;2 ''' if surface_type is not None: albedo = SURFACE_ALBEDOS[surface_type] diffuse_irrad = ghi * albedo * (1 - np.cos(np.radians(surface_tilt))) * 0.5 try: diffuse_irrad.name = 'diffuse_ground' except AttributeError: pass return diffuse_irrad
[ "def", "get_ground_diffuse", "(", "surface_tilt", ",", "ghi", ",", "albedo", "=", ".25", ",", "surface_type", "=", "None", ")", ":", "if", "surface_type", "is", "not", "None", ":", "albedo", "=", "SURFACE_ALBEDOS", "[", "surface_type", "]", "diffuse_irrad", ...
https://github.com/pvlib/pvlib-python/blob/1ab0eb20f9cd9fb9f7a0ddf35f81283f2648e34a/pvlib/irradiance.py#L541-L603
mchristopher/PokemonGo-DesktopMap
ec37575f2776ee7d64456e2a1f6b6b78830b4fe0
app/pywin/Lib/decimal.py
python
Decimal.__float__
(self)
return float(s)
Float representation.
Float representation.
[ "Float", "representation", "." ]
def __float__(self): """Float representation.""" if self._isnan(): if self.is_snan(): raise ValueError("Cannot convert signaling NaN to float") s = "-nan" if self._sign else "nan" else: s = str(self) return float(s)
[ "def", "__float__", "(", "self", ")", ":", "if", "self", ".", "_isnan", "(", ")", ":", "if", "self", ".", "is_snan", "(", ")", ":", "raise", "ValueError", "(", "\"Cannot convert signaling NaN to float\"", ")", "s", "=", "\"-nan\"", "if", "self", ".", "_s...
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/ec37575f2776ee7d64456e2a1f6b6b78830b4fe0/app/pywin/Lib/decimal.py#L1581-L1589
pwnieexpress/pwn_plug_sources
1a23324f5dc2c3de20f9c810269b6a29b2758cad
src/goodfet/GoodFET.py
python
GoodFET.flash
(self,file)
Flash an intel hex file to code memory.
Flash an intel hex file to code memory.
[ "Flash", "an", "intel", "hex", "file", "to", "code", "memory", "." ]
def flash(self,file): """Flash an intel hex file to code memory.""" print "Flash not implemented.";
[ "def", "flash", "(", "self", ",", "file", ")", ":", "print", "\"Flash not implemented.\"" ]
https://github.com/pwnieexpress/pwn_plug_sources/blob/1a23324f5dc2c3de20f9c810269b6a29b2758cad/src/goodfet/GoodFET.py#L401-L403
zake7749/Chatbot
209d8b9fc68958e21bf9cae262727c2629527efd
Chatbot/RuleMatcher/rulebase.py
python
Rule.match
(self, sentence, threshold=0)
return [max_sim, self.id_term, matchee]
Calculate the similarity between the input and concept term. Args: threshold: a threshold to ignore the low similarity. sentence : a list of words. Returns: a struct : [similarity, domain_name, matchee in the sentence]
Calculate the similarity between the input and concept term.
[ "Calculate", "the", "similarity", "between", "the", "input", "and", "concept", "term", "." ]
def match(self, sentence, threshold=0): """ Calculate the similarity between the input and concept term. Args: threshold: a threshold to ignore the low similarity. sentence : a list of words. Returns: a struct : [similarity, domain_name, matchee in the sentence] """ max_sim = 0.0 matchee = "" for word in sentence: for term in self.terms: try: sim = self.model.similarity(term,word) if sim > max_sim and sim > threshold: max_sim = sim matchee = word except Exception as e: if term == word: max_sim = 1 matchee = word return [max_sim, self.id_term, matchee]
[ "def", "match", "(", "self", ",", "sentence", ",", "threshold", "=", "0", ")", ":", "max_sim", "=", "0.0", "matchee", "=", "\"\"", "for", "word", "in", "sentence", ":", "for", "term", "in", "self", ".", "terms", ":", "try", ":", "sim", "=", "self",...
https://github.com/zake7749/Chatbot/blob/209d8b9fc68958e21bf9cae262727c2629527efd/Chatbot/RuleMatcher/rulebase.py#L68-L94
linxid/Machine_Learning_Study_Path
558e82d13237114bbb8152483977806fc0c222af
Machine Learning In Action/Chapter8-Regression/venv/Lib/site-packages/pip-9.0.1-py3.6.egg/pip/_vendor/html5lib/_tokenizer.py
python
HTMLTokenizer.doctypeSystemIdentifierSingleQuotedState
(self)
return True
[]
def doctypeSystemIdentifierSingleQuotedState(self): data = self.stream.char() if data == "'": self.state = self.afterDoctypeSystemIdentifierState elif data == "\u0000": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "invalid-codepoint"}) self.currentToken["systemId"] += "\uFFFD" elif data == ">": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "unexpected-end-of-doctype"}) self.currentToken["correct"] = False self.tokenQueue.append(self.currentToken) self.state = self.dataState elif data is EOF: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "eof-in-doctype"}) self.currentToken["correct"] = False self.tokenQueue.append(self.currentToken) self.state = self.dataState else: self.currentToken["systemId"] += data return True
[ "def", "doctypeSystemIdentifierSingleQuotedState", "(", "self", ")", ":", "data", "=", "self", ".", "stream", ".", "char", "(", ")", "if", "data", "==", "\"'\"", ":", "self", ".", "state", "=", "self", ".", "afterDoctypeSystemIdentifierState", "elif", "data", ...
https://github.com/linxid/Machine_Learning_Study_Path/blob/558e82d13237114bbb8152483977806fc0c222af/Machine Learning In Action/Chapter8-Regression/venv/Lib/site-packages/pip-9.0.1-py3.6.egg/pip/_vendor/html5lib/_tokenizer.py#L1636-L1658
awslabs/aws-ec2rescue-linux
8ecf40e7ea0d2563dac057235803fca2221029d2
lib/python2/yaml/__init__.py
python
emit
(events, stream=None, Dumper=Dumper, canonical=None, indent=None, width=None, allow_unicode=None, line_break=None)
Emit YAML parsing events into a stream. If stream is None, return the produced string instead.
Emit YAML parsing events into a stream. If stream is None, return the produced string instead.
[ "Emit", "YAML", "parsing", "events", "into", "a", "stream", ".", "If", "stream", "is", "None", "return", "the", "produced", "string", "instead", "." ]
def emit(events, stream=None, Dumper=Dumper, canonical=None, indent=None, width=None, allow_unicode=None, line_break=None): """ Emit YAML parsing events into a stream. If stream is None, return the produced string instead. """ getvalue = None if stream is None: from StringIO import StringIO stream = StringIO() getvalue = stream.getvalue dumper = Dumper(stream, canonical=canonical, indent=indent, width=width, allow_unicode=allow_unicode, line_break=line_break) try: for event in events: dumper.emit(event) finally: dumper.dispose() if getvalue: return getvalue()
[ "def", "emit", "(", "events", ",", "stream", "=", "None", ",", "Dumper", "=", "Dumper", ",", "canonical", "=", "None", ",", "indent", "=", "None", ",", "width", "=", "None", ",", "allow_unicode", "=", "None", ",", "line_break", "=", "None", ")", ":",...
https://github.com/awslabs/aws-ec2rescue-linux/blob/8ecf40e7ea0d2563dac057235803fca2221029d2/lib/python2/yaml/__init__.py#L103-L123
almarklein/visvis
766ed97767b44a55a6ff72c742d7385e074d3d55
wobjects/textures.py
python
BaseTexture.shader
(self)
return self._shader
Get the shader object for the texture. This can be used to add code of your own and customize the vertex and fragment part of the shader.
Get the shader object for the texture. This can be used to add code of your own and customize the vertex and fragment part of the shader.
[ "Get", "the", "shader", "object", "for", "the", "texture", ".", "This", "can", "be", "used", "to", "add", "code", "of", "your", "own", "and", "customize", "the", "vertex", "and", "fragment", "part", "of", "the", "shader", "." ]
def shader(self): """ Get the shader object for the texture. This can be used to add code of your own and customize the vertex and fragment part of the shader. """ return self._shader
[ "def", "shader", "(", "self", ")", ":", "return", "self", ".", "_shader" ]
https://github.com/almarklein/visvis/blob/766ed97767b44a55a6ff72c742d7385e074d3d55/wobjects/textures.py#L229-L234
python-streamz/streamz
8744c83a0fad1fbd9ee9318d1a79ee538415a4e4
streamz/river.py
python
RiverPredict.update
(self, x, who=None, metadata=None)
return self._emit(out, metadata=metadata)
[]
def update(self, x, who=None, metadata=None): out = self.model.predict_one(x) return self._emit(out, metadata=metadata)
[ "def", "update", "(", "self", ",", "x", ",", "who", "=", "None", ",", "metadata", "=", "None", ")", ":", "out", "=", "self", ".", "model", ".", "predict_one", "(", "x", ")", "return", "self", ".", "_emit", "(", "out", ",", "metadata", "=", "metad...
https://github.com/python-streamz/streamz/blob/8744c83a0fad1fbd9ee9318d1a79ee538415a4e4/streamz/river.py#L60-L62
Cog-Creators/Red-DiscordBot
b05933274a11fb097873ab0d1b246d37b06aa306
redbot/core/rpc.py
python
RPC.close
(self)
Closes the RPC server.
Closes the RPC server.
[ "Closes", "the", "RPC", "server", "." ]
async def close(self): """ Closes the RPC server. """ if self._started: await self.app.shutdown() await self._runner.cleanup()
[ "async", "def", "close", "(", "self", ")", ":", "if", "self", ".", "_started", ":", "await", "self", ".", "app", ".", "shutdown", "(", ")", "await", "self", ".", "_runner", ".", "cleanup", "(", ")" ]
https://github.com/Cog-Creators/Red-DiscordBot/blob/b05933274a11fb097873ab0d1b246d37b06aa306/redbot/core/rpc.py#L97-L103
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_hxb2/lib/python3.5/site-packages/idna/uts46data.py
python
_seg_17
()
return [ (0x1E4B, 'V'), (0x1E4C, 'M', u'ṍ'), (0x1E4D, 'V'), (0x1E4E, 'M', u'ṏ'), (0x1E4F, 'V'), (0x1E50, 'M', u'ṑ'), (0x1E51, 'V'), (0x1E52, 'M', u'ṓ'), (0x1E53, 'V'), (0x1E54, 'M', u'ṕ'), (0x1E55, 'V'), (0x1E56, 'M', u'ṗ'), (0x1E57, 'V'), (0x1E58, 'M', u'ṙ'), (0x1E59, 'V'), (0x1E5A, 'M', u'ṛ'), (0x1E5B, 'V'), (0x1E5C, 'M', u'ṝ'), (0x1E5D, 'V'), (0x1E5E, 'M', u'ṟ'), (0x1E5F, 'V'), (0x1E60, 'M', u'ṡ'), (0x1E61, 'V'), (0x1E62, 'M', u'ṣ'), (0x1E63, 'V'), (0x1E64, 'M', u'ṥ'), (0x1E65, 'V'), (0x1E66, 'M', u'ṧ'), (0x1E67, 'V'), (0x1E68, 'M', u'ṩ'), (0x1E69, 'V'), (0x1E6A, 'M', u'ṫ'), (0x1E6B, 'V'), (0x1E6C, 'M', u'ṭ'), (0x1E6D, 'V'), (0x1E6E, 'M', u'ṯ'), (0x1E6F, 'V'), (0x1E70, 'M', u'ṱ'), (0x1E71, 'V'), (0x1E72, 'M', u'ṳ'), (0x1E73, 'V'), (0x1E74, 'M', u'ṵ'), (0x1E75, 'V'), (0x1E76, 'M', u'ṷ'), (0x1E77, 'V'), (0x1E78, 'M', u'ṹ'), (0x1E79, 'V'), (0x1E7A, 'M', u'ṻ'), (0x1E7B, 'V'), (0x1E7C, 'M', u'ṽ'), (0x1E7D, 'V'), (0x1E7E, 'M', u'ṿ'), (0x1E7F, 'V'), (0x1E80, 'M', u'ẁ'), (0x1E81, 'V'), (0x1E82, 'M', u'ẃ'), (0x1E83, 'V'), (0x1E84, 'M', u'ẅ'), (0x1E85, 'V'), (0x1E86, 'M', u'ẇ'), (0x1E87, 'V'), (0x1E88, 'M', u'ẉ'), (0x1E89, 'V'), (0x1E8A, 'M', u'ẋ'), (0x1E8B, 'V'), (0x1E8C, 'M', u'ẍ'), (0x1E8D, 'V'), (0x1E8E, 'M', u'ẏ'), (0x1E8F, 'V'), (0x1E90, 'M', u'ẑ'), (0x1E91, 'V'), (0x1E92, 'M', u'ẓ'), (0x1E93, 'V'), (0x1E94, 'M', u'ẕ'), (0x1E95, 'V'), (0x1E9A, 'M', u'aʾ'), (0x1E9B, 'M', u'ṡ'), (0x1E9C, 'V'), (0x1E9E, 'M', u'ss'), (0x1E9F, 'V'), (0x1EA0, 'M', u'ạ'), (0x1EA1, 'V'), (0x1EA2, 'M', u'ả'), (0x1EA3, 'V'), (0x1EA4, 'M', u'ấ'), (0x1EA5, 'V'), (0x1EA6, 'M', u'ầ'), (0x1EA7, 'V'), (0x1EA8, 'M', u'ẩ'), (0x1EA9, 'V'), (0x1EAA, 'M', u'ẫ'), (0x1EAB, 'V'), (0x1EAC, 'M', u'ậ'), (0x1EAD, 'V'), (0x1EAE, 'M', u'ắ'), (0x1EAF, 'V'), (0x1EB0, 'M', u'ằ'), (0x1EB1, 'V'), (0x1EB2, 'M', u'ẳ'), (0x1EB3, 'V'), ]
[]
def _seg_17(): return [ (0x1E4B, 'V'), (0x1E4C, 'M', u'ṍ'), (0x1E4D, 'V'), (0x1E4E, 'M', u'ṏ'), (0x1E4F, 'V'), (0x1E50, 'M', u'ṑ'), (0x1E51, 'V'), (0x1E52, 'M', u'ṓ'), (0x1E53, 'V'), (0x1E54, 'M', u'ṕ'), (0x1E55, 'V'), (0x1E56, 'M', u'ṗ'), (0x1E57, 'V'), (0x1E58, 'M', u'ṙ'), (0x1E59, 'V'), (0x1E5A, 'M', u'ṛ'), (0x1E5B, 'V'), (0x1E5C, 'M', u'ṝ'), (0x1E5D, 'V'), (0x1E5E, 'M', u'ṟ'), (0x1E5F, 'V'), (0x1E60, 'M', u'ṡ'), (0x1E61, 'V'), (0x1E62, 'M', u'ṣ'), (0x1E63, 'V'), (0x1E64, 'M', u'ṥ'), (0x1E65, 'V'), (0x1E66, 'M', u'ṧ'), (0x1E67, 'V'), (0x1E68, 'M', u'ṩ'), (0x1E69, 'V'), (0x1E6A, 'M', u'ṫ'), (0x1E6B, 'V'), (0x1E6C, 'M', u'ṭ'), (0x1E6D, 'V'), (0x1E6E, 'M', u'ṯ'), (0x1E6F, 'V'), (0x1E70, 'M', u'ṱ'), (0x1E71, 'V'), (0x1E72, 'M', u'ṳ'), (0x1E73, 'V'), (0x1E74, 'M', u'ṵ'), (0x1E75, 'V'), (0x1E76, 'M', u'ṷ'), (0x1E77, 'V'), (0x1E78, 'M', u'ṹ'), (0x1E79, 'V'), (0x1E7A, 'M', u'ṻ'), (0x1E7B, 'V'), (0x1E7C, 'M', u'ṽ'), (0x1E7D, 'V'), (0x1E7E, 'M', u'ṿ'), (0x1E7F, 'V'), (0x1E80, 'M', u'ẁ'), (0x1E81, 'V'), (0x1E82, 'M', u'ẃ'), (0x1E83, 'V'), (0x1E84, 'M', u'ẅ'), (0x1E85, 'V'), (0x1E86, 'M', u'ẇ'), (0x1E87, 'V'), (0x1E88, 'M', u'ẉ'), (0x1E89, 'V'), (0x1E8A, 'M', u'ẋ'), (0x1E8B, 'V'), (0x1E8C, 'M', u'ẍ'), (0x1E8D, 'V'), (0x1E8E, 'M', u'ẏ'), (0x1E8F, 'V'), (0x1E90, 'M', u'ẑ'), (0x1E91, 'V'), (0x1E92, 'M', u'ẓ'), (0x1E93, 'V'), (0x1E94, 'M', u'ẕ'), (0x1E95, 'V'), (0x1E9A, 'M', u'aʾ'), (0x1E9B, 'M', u'ṡ'), (0x1E9C, 'V'), (0x1E9E, 'M', u'ss'), (0x1E9F, 'V'), (0x1EA0, 'M', u'ạ'), (0x1EA1, 'V'), (0x1EA2, 'M', u'ả'), (0x1EA3, 'V'), (0x1EA4, 'M', u'ấ'), (0x1EA5, 'V'), (0x1EA6, 'M', u'ầ'), (0x1EA7, 'V'), (0x1EA8, 'M', u'ẩ'), (0x1EA9, 'V'), (0x1EAA, 'M', u'ẫ'), (0x1EAB, 'V'), (0x1EAC, 'M', u'ậ'), (0x1EAD, 'V'), (0x1EAE, 'M', u'ắ'), (0x1EAF, 'V'), (0x1EB0, 'M', u'ằ'), (0x1EB1, 'V'), (0x1EB2, 'M', u'ẳ'), (0x1EB3, 'V'), ]
[ "def", "_seg_17", "(", ")", ":", "return", "[", "(", "0x1E4B", ",", "'V'", ")", ",", "(", "0x1E4C", ",", "'M'", ",", "u'ṍ'),", "", "", "(", "0x1E4D", ",", "'V'", ")", ",", "(", "0x1E4E", ",", "'M'", ",", "u'ṏ'),", "", "", "(", "0x1E4F", ",", ...
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_hxb2/lib/python3.5/site-packages/idna/uts46data.py#L1776-L1878
dephell/dephell
de96f01fcfd8dd620b049369a8ec30dde566c5de
dephell/actions/_editorconfig.py
python
make_editorconfig
(path: Path)
return HEADER + '\n\n'.join(map(str, matched)) + '\n'
[]
def make_editorconfig(path: Path) -> str: matched = [] non_matched = [] for rule in RULES: if rule.match(path): matched.append(rule) else: non_matched.append(rule) return HEADER + '\n\n'.join(map(str, matched)) + '\n'
[ "def", "make_editorconfig", "(", "path", ":", "Path", ")", "->", "str", ":", "matched", "=", "[", "]", "non_matched", "=", "[", "]", "for", "rule", "in", "RULES", ":", "if", "rule", ".", "match", "(", "path", ")", ":", "matched", ".", "append", "("...
https://github.com/dephell/dephell/blob/de96f01fcfd8dd620b049369a8ec30dde566c5de/dephell/actions/_editorconfig.py#L100-L109
morganstanley/treadmill
f18267c665baf6def4374d21170198f63ff1cde4
lib/python/treadmill/fs/__init__.py
python
create_excl
(filename, size=0, mode=(stat.S_IRUSR | stat.S_IWUSR))
return False
Create a file if it doesn't already exists Perform a open/3 limited to the user and create|excl. Securely create a file with S_IRUSR|S_IWUSR permissions and truncate to a specific size. :param filename: Path name to the file which is to be created. :type filename: ``str`` :param size: Size in bytes of the new file (defaults to 0) :type size: ``int`` :param mode: Permission flag for the new file (defaults to read|write to the owner only) :type mode: ``int`` :returns: ``bool`` -- True if the file creation was successful, False if the file already existed.
Create a file if it doesn't already exists
[ "Create", "a", "file", "if", "it", "doesn", "t", "already", "exists" ]
def create_excl(filename, size=0, mode=(stat.S_IRUSR | stat.S_IWUSR)): """Create a file if it doesn't already exists Perform a open/3 limited to the user and create|excl. Securely create a file with S_IRUSR|S_IWUSR permissions and truncate to a specific size. :param filename: Path name to the file which is to be created. :type filename: ``str`` :param size: Size in bytes of the new file (defaults to 0) :type size: ``int`` :param mode: Permission flag for the new file (defaults to read|write to the owner only) :type mode: ``int`` :returns: ``bool`` -- True if the file creation was successful, False if the file already existed. """ openflags = os.O_WRONLY | os.O_CREAT | os.O_EXCL try: fd = -1 orig_umask = os.umask(0) fd = os.open(filename, openflags, mode) with os.fdopen(fd, 'wb') as f: f.truncate(size) return True except OSError as err: if fd != -1: os.close(fd) # If file already exists, no problem. Otherwise raise if err.errno != errno.EEXIST: raise finally: os.umask(orig_umask) return False
[ "def", "create_excl", "(", "filename", ",", "size", "=", "0", ",", "mode", "=", "(", "stat", ".", "S_IRUSR", "|", "stat", ".", "S_IWUSR", ")", ")", ":", "openflags", "=", "os", ".", "O_WRONLY", "|", "os", ".", "O_CREAT", "|", "os", ".", "O_EXCL", ...
https://github.com/morganstanley/treadmill/blob/f18267c665baf6def4374d21170198f63ff1cde4/lib/python/treadmill/fs/__init__.py#L195-L236
openstack/openstacksdk
58384268487fa854f21c470b101641ab382c9897
openstack/network/v2/_proxy.py
python
Proxy.insert_rule_into_policy
(self, firewall_policy_id, firewall_rule_id, insert_after=None, insert_before=None)
return policy.insert_rule(self, **body)
Insert a firewall_rule into a firewall_policy in order :param firewall_policy_id: The ID of the firewall policy. :param firewall_rule_id: The ID of the firewall rule. :param insert_after: The ID of the firewall rule to insert the new rule after. It will be worked only when insert_before is none. :param insert_before: The ID of the firewall rule to insert the new rule before. :returns: The updated firewall policy :rtype: :class:`~openstack.network.v2.firewall_policy.FirewallPolicy`
Insert a firewall_rule into a firewall_policy in order
[ "Insert", "a", "firewall_rule", "into", "a", "firewall_policy", "in", "order" ]
def insert_rule_into_policy(self, firewall_policy_id, firewall_rule_id, insert_after=None, insert_before=None): """Insert a firewall_rule into a firewall_policy in order :param firewall_policy_id: The ID of the firewall policy. :param firewall_rule_id: The ID of the firewall rule. :param insert_after: The ID of the firewall rule to insert the new rule after. It will be worked only when insert_before is none. :param insert_before: The ID of the firewall rule to insert the new rule before. :returns: The updated firewall policy :rtype: :class:`~openstack.network.v2.firewall_policy.FirewallPolicy` """ body = {'firewall_rule_id': firewall_rule_id, 'insert_after': insert_after, 'insert_before': insert_before} policy = self._get_resource(_firewall_policy.FirewallPolicy, firewall_policy_id) return policy.insert_rule(self, **body)
[ "def", "insert_rule_into_policy", "(", "self", ",", "firewall_policy_id", ",", "firewall_rule_id", ",", "insert_after", "=", "None", ",", "insert_before", "=", "None", ")", ":", "body", "=", "{", "'firewall_rule_id'", ":", "firewall_rule_id", ",", "'insert_after'", ...
https://github.com/openstack/openstacksdk/blob/58384268487fa854f21c470b101641ab382c9897/openstack/network/v2/_proxy.py#L3437-L3457
geospace-code/georinex
4d27ebefad8518df3d38abca58bb8674c90b2cf9
src/georinex/obs3.py
python
obsheader3
(f: T.TextIO, use: set[str] = None, meas: list[str] = None)
return hdr
get RINEX 3 OBS types, for each system type optionally, select system type and/or measurement type to greatly speed reading and save memory (RAM, disk)
get RINEX 3 OBS types, for each system type optionally, select system type and/or measurement type to greatly speed reading and save memory (RAM, disk)
[ "get", "RINEX", "3", "OBS", "types", "for", "each", "system", "type", "optionally", "select", "system", "type", "and", "/", "or", "measurement", "type", "to", "greatly", "speed", "reading", "and", "save", "memory", "(", "RAM", "disk", ")" ]
def obsheader3(f: T.TextIO, use: set[str] = None, meas: list[str] = None) -> dict[str, T.Any]: """ get RINEX 3 OBS types, for each system type optionally, select system type and/or measurement type to greatly speed reading and save memory (RAM, disk) """ if isinstance(f, (str, Path)): with opener(f, header=True) as h: return obsheader3(h, use, meas) fields = {} Fmax = 0 # %% first line hdr = rinexinfo(f) for ln in f: if "END OF HEADER" in ln: break hd = ln[60:80] c = ln[:60] if "SYS / # / OBS TYPES" in hd: k = c[0] fields[k] = c[6:60].split() N = int(c[3:6]) # %% maximum number of fields in a file, to allow fast Numpy parse. Fmax = max(N, Fmax) n = N - 13 while n > 0: # Rinex 3.03, pg. A6, A7 ln = f.readline() assert "SYS / # / OBS TYPES" in ln[60:] fields[k] += ln[6:60].split() n -= 13 assert len(fields[k]) == N continue if hd.strip() not in hdr: # Header label hdr[hd.strip()] = c # don't strip for fixed-width parsers # string with info else: # concatenate to the existing string hdr[hd.strip()] += " " + c # %% list with x,y,z cartesian (OPTIONAL) # Rinex 3.03, pg. A6, Table A2 try: # some RINEX files have bad headers with mulitple APPROX POSITION XYZ. # we choose to use the first such header. hdr["position"] = [float(j) for j in hdr["APPROX POSITION XYZ"].split()][:3] if ecef2geodetic is not None and len(hdr["position"]) == 3: hdr["position_geodetic"] = ecef2geodetic(*hdr["position"]) except (KeyError, ValueError): pass # %% time try: t0s = hdr["TIME OF FIRST OBS"] # NOTE: must do second=int(float()) due to non-conforming files hdr["t0"] = datetime( year=int(t0s[:6]), month=int(t0s[6:12]), day=int(t0s[12:18]), hour=int(t0s[18:24]), minute=int(t0s[24:30]), second=int(float(t0s[30:36])), microsecond=int(float(t0s[30:43]) % 1 * 1000000), ) except (KeyError, ValueError): pass try: hdr["interval"] = float(hdr["INTERVAL"][:10]) except (KeyError, ValueError): pass # %% select specific satellite systems only (optional) if use: if not set(fields.keys()).intersection(use): raise KeyError(f"system type {use} not found in RINEX file") fields = {k: fields[k] for k in use if k in fields} # perhaps this could be done more efficiently, but it's probably low impact on overall program. # simple set and frozenset operations do NOT preserve order, which would completely mess up reading! sysind: dict[str, T.Any] = {} if isinstance(meas, (tuple, list, np.ndarray)): for sk in fields: # iterate over each system # ind = np.isin(fields[sk], meas) # boolean vector ind = np.zeros(len(fields[sk]), dtype=bool) for m in meas: for i, field in enumerate(fields[sk]): if field.startswith(m): ind[i] = True fields[sk] = np.array(fields[sk])[ind].tolist() sysind[sk] = np.empty(Fmax * 3, dtype=bool) # *3 due to LLI, SSI for j, i in enumerate(ind): sysind[sk][j * 3 : j * 3 + 3] = i else: sysind = {k: np.s_[:] for k in fields} hdr["fields"] = fields hdr["fields_ind"] = sysind hdr["Fmax"] = Fmax return hdr
[ "def", "obsheader3", "(", "f", ":", "T", ".", "TextIO", ",", "use", ":", "set", "[", "str", "]", "=", "None", ",", "meas", ":", "list", "[", "str", "]", "=", "None", ")", "->", "dict", "[", "str", ",", "T", ".", "Any", "]", ":", "if", "isin...
https://github.com/geospace-code/georinex/blob/4d27ebefad8518df3d38abca58bb8674c90b2cf9/src/georinex/obs3.py#L269-L375
leancloud/satori
701caccbd4fe45765001ca60435c0cb499477c03
satori-rules/plugin/libs/gevent/pywsgi.py
python
Input.__read_chunk_length
(self, rfile)
[]
def __read_chunk_length(self, rfile): # Read and return the next integer chunk length. If no # chunk length can be read, raises _InvalidClientInput. # Here's the production for a chunk: # (http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html) # chunk = chunk-size [ chunk-extension ] CRLF # chunk-data CRLF # chunk-size = 1*HEX # chunk-extension= *( ";" chunk-ext-name [ "=" chunk-ext-val ] ) # chunk-ext-name = token # chunk-ext-val = token | quoted-string # To cope with malicious or broken clients that fail to send valid # chunk lines, the strategy is to read character by character until we either reach # a ; or newline. If at any time we read a non-HEX digit, we bail. If we hit a # ;, indicating an chunk-extension, we'll read up to the next # MAX_REQUEST_LINE characters # looking for the CRLF, and if we don't find it, we bail. If we read more than 16 hex characters, # (the number needed to represent a 64-bit chunk size), we bail (this protects us from # a client that sends an infinite stream of `F`, for example). buf = BytesIO() while 1: char = rfile.read(1) if not char: self._chunked_input_error = True raise _InvalidClientInput("EOF before chunk end reached") if char == b'\r': break if char == b';': break if char not in _HEX: self._chunked_input_error = True raise _InvalidClientInput("Non-hex data", char) buf.write(char) if buf.tell() > 16: self._chunked_input_error = True raise _InvalidClientInput("Chunk-size too large.") if char == b';': i = 0 while i < MAX_REQUEST_LINE: char = rfile.read(1) if char == b'\r': break i += 1 else: # we read more than MAX_REQUEST_LINE without # hitting CR self._chunked_input_error = True raise _InvalidClientInput("Too large chunk extension") if char == b'\r': # We either got here from the main loop or from the # end of an extension char = rfile.read(1) if char != b'\n': self._chunked_input_error = True raise _InvalidClientInput("Line didn't end in CRLF") return int(buf.getvalue(), 16)
[ "def", "__read_chunk_length", "(", "self", ",", "rfile", ")", ":", "# Read and return the next integer chunk length. If no", "# chunk length can be read, raises _InvalidClientInput.", "# Here's the production for a chunk:", "# (http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html)", "# ch...
https://github.com/leancloud/satori/blob/701caccbd4fe45765001ca60435c0cb499477c03/satori-rules/plugin/libs/gevent/pywsgi.py#L189-L250
cea-hpc/clustershell
c421133ed4baa69e35ff76c476d4097201485344
lib/ClusterShell/Topology.py
python
TopologyGraph.to_tree
(self, root)
return tree
convert the routing table to a topology tree of nodegroups
convert the routing table to a topology tree of nodegroups
[ "convert", "the", "routing", "table", "to", "a", "topology", "tree", "of", "nodegroups" ]
def to_tree(self, root): """convert the routing table to a topology tree of nodegroups""" # convert the routing table into a table of linked TopologyNodeGroup's self._routes_to_tng() # ensure this is a valid pseudo-tree self._validate(root) tree = TopologyTree() tree.load(self._nodegroups[self._root]) return tree
[ "def", "to_tree", "(", "self", ",", "root", ")", ":", "# convert the routing table into a table of linked TopologyNodeGroup's", "self", ".", "_routes_to_tng", "(", ")", "# ensure this is a valid pseudo-tree", "self", ".", "_validate", "(", "root", ")", "tree", "=", "Top...
https://github.com/cea-hpc/clustershell/blob/c421133ed4baa69e35ff76c476d4097201485344/lib/ClusterShell/Topology.py#L357-L365
OpenBazaar/OpenBazaar-Server
6bfd8f0c899d7133dadd38d1afdd537a2e182ff1
market/contracts.py
python
Contract.on_tx_received
(self, address_version, address_hash, height, block_hash, tx)
Fire when the libbitcoin server tells us we received a payment to this funding address. While unlikely, a user may send multiple transactions to the funding address to reach the funding level. We need to keep a running balance and increment it when a new transaction is received. If the contract is fully funded, we push a notification to the websockets.
Fire when the libbitcoin server tells us we received a payment to this funding address. While unlikely, a user may send multiple transactions to the funding address to reach the funding level. We need to keep a running balance and increment it when a new transaction is received. If the contract is fully funded, we push a notification to the websockets.
[ "Fire", "when", "the", "libbitcoin", "server", "tells", "us", "we", "received", "a", "payment", "to", "this", "funding", "address", ".", "While", "unlikely", "a", "user", "may", "send", "multiple", "transactions", "to", "the", "funding", "address", "to", "re...
def on_tx_received(self, address_version, address_hash, height, block_hash, tx): """ Fire when the libbitcoin server tells us we received a payment to this funding address. While unlikely, a user may send multiple transactions to the funding address to reach the funding level. We need to keep a running balance and increment it when a new transaction is received. If the contract is fully funded, we push a notification to the websockets. """ try: # decode the transaction self.log.info("Bitcoin transaction detected") transaction = BitcoinTransaction.from_serialized(tx, self.testnet) # get the amount (in satoshi) the user is expected to pay amount_to_pay = int(float(self.contract["buyer_order"]["order"]["payment"]["amount"]) * 100000000) if tx not in self.received_txs: # make sure we aren't parsing the same tx twice. outpoints = transaction.check_for_funding( self.contract["buyer_order"]["order"]["payment"]["address"]) if outpoints is not None: for outpoint in outpoints: self.amount_funded += outpoint["value"] self.received_txs.append(tx) self.outpoints.append(outpoint) if self.amount_funded >= amount_to_pay: # if fully funded self.payment_received() else: order_id = digest(json.dumps(self.contract, indent=4)).encode("hex") notification_json = { "notification": { "type": "partial payment", "amount_funded": round(self.amount_funded / float(100000000), 8), "order_id": order_id } } self.notification_listener.push_ws(notification_json) except Exception as e: self.log.critical("Error processing bitcoin transaction: %s" % e.message)
[ "def", "on_tx_received", "(", "self", ",", "address_version", ",", "address_hash", ",", "height", ",", "block_hash", ",", "tx", ")", ":", "try", ":", "# decode the transaction", "self", ".", "log", ".", "info", "(", "\"Bitcoin transaction detected\"", ")", "tran...
https://github.com/OpenBazaar/OpenBazaar-Server/blob/6bfd8f0c899d7133dadd38d1afdd537a2e182ff1/market/contracts.py#L871-L907
tobegit3hub/deep_image_model
8a53edecd9e00678b278bb10f6fb4bdb1e4ee25e
java_predict_client/src/main/proto/tensorflow/python/ops/nn_ops.py
python
_flatten_outer_dims
(logits)
return output
Flattens logits' outer dimensions and keep its last dimension.
Flattens logits' outer dimensions and keep its last dimension.
[ "Flattens", "logits", "outer", "dimensions", "and", "keep", "its", "last", "dimension", "." ]
def _flatten_outer_dims(logits): """Flattens logits' outer dimensions and keep its last dimension.""" rank = array_ops.rank(logits) last_dim_size = array_ops.slice( array_ops.shape(logits), [math_ops.sub(rank, 1)], [1]) output = array_ops.reshape(logits, array_ops.concat(0, [[-1], last_dim_size])) # Set output shape if known. shape = logits.get_shape() if shape is not None and shape.dims is not None: shape = shape.as_list() product = 1 product_valid = True for d in shape[:-1]: if d is None: product_valid = False break else: product *= d if product_valid: output_shape = [product, shape[-1]] output.set_shape(output_shape) return output
[ "def", "_flatten_outer_dims", "(", "logits", ")", ":", "rank", "=", "array_ops", ".", "rank", "(", "logits", ")", "last_dim_size", "=", "array_ops", ".", "slice", "(", "array_ops", ".", "shape", "(", "logits", ")", ",", "[", "math_ops", ".", "sub", "(", ...
https://github.com/tobegit3hub/deep_image_model/blob/8a53edecd9e00678b278bb10f6fb4bdb1e4ee25e/java_predict_client/src/main/proto/tensorflow/python/ops/nn_ops.py#L1248-L1271
wistbean/learn_python3_spider
73c873f4845f4385f097e5057407d03dd37a117b
stackoverflow/venv/lib/python3.6/site-packages/pip-19.0.3-py3.6.egg/pip/_internal/req/req_file.py
python
parse_requirements
( filename, # type: str finder=None, # type: Optional[PackageFinder] comes_from=None, # type: Optional[str] options=None, # type: Optional[optparse.Values] session=None, # type: Optional[PipSession] constraint=False, # type: bool wheel_cache=None, # type: Optional[WheelCache] use_pep517=None # type: Optional[bool] )
Parse a requirements file and yield InstallRequirement instances. :param filename: Path or url of requirements file. :param finder: Instance of pip.index.PackageFinder. :param comes_from: Origin description of requirements. :param options: cli options. :param session: Instance of pip.download.PipSession. :param constraint: If true, parsing a constraint file rather than requirements file. :param wheel_cache: Instance of pip.wheel.WheelCache :param use_pep517: Value of the --use-pep517 option.
Parse a requirements file and yield InstallRequirement instances.
[ "Parse", "a", "requirements", "file", "and", "yield", "InstallRequirement", "instances", "." ]
def parse_requirements( filename, # type: str finder=None, # type: Optional[PackageFinder] comes_from=None, # type: Optional[str] options=None, # type: Optional[optparse.Values] session=None, # type: Optional[PipSession] constraint=False, # type: bool wheel_cache=None, # type: Optional[WheelCache] use_pep517=None # type: Optional[bool] ): # type: (...) -> Iterator[InstallRequirement] """Parse a requirements file and yield InstallRequirement instances. :param filename: Path or url of requirements file. :param finder: Instance of pip.index.PackageFinder. :param comes_from: Origin description of requirements. :param options: cli options. :param session: Instance of pip.download.PipSession. :param constraint: If true, parsing a constraint file rather than requirements file. :param wheel_cache: Instance of pip.wheel.WheelCache :param use_pep517: Value of the --use-pep517 option. """ if session is None: raise TypeError( "parse_requirements() missing 1 required keyword argument: " "'session'" ) _, content = get_file_content( filename, comes_from=comes_from, session=session ) lines_enum = preprocess(content, options) for line_number, line in lines_enum: req_iter = process_line(line, filename, line_number, finder, comes_from, options, session, wheel_cache, use_pep517=use_pep517, constraint=constraint) for req in req_iter: yield req
[ "def", "parse_requirements", "(", "filename", ",", "# type: str", "finder", "=", "None", ",", "# type: Optional[PackageFinder]", "comes_from", "=", "None", ",", "# type: Optional[str]", "options", "=", "None", ",", "# type: Optional[optparse.Values]", "session", "=", "N...
https://github.com/wistbean/learn_python3_spider/blob/73c873f4845f4385f097e5057407d03dd37a117b/stackoverflow/venv/lib/python3.6/site-packages/pip-19.0.3-py3.6.egg/pip/_internal/req/req_file.py#L73-L113
HuobiRDCenter/huobi_Python
c75a7fa8b31e99ffc1c173d74dcfcad83682e943
huobi/model/margin/margin_account_balance.py
python
MarginAccountBalance.__init__
(self)
[]
def __init__(self): self.id = 0 self.type = AccountType.INVALID self.state = AccountState.INVALID self.symbol = "" self.fl_price = 0.0 self.fl_type = 0.0 self.risk_rate = 0.0 self.list = []
[ "def", "__init__", "(", "self", ")", ":", "self", ".", "id", "=", "0", "self", ".", "type", "=", "AccountType", ".", "INVALID", "self", ".", "state", "=", "AccountState", ".", "INVALID", "self", ".", "symbol", "=", "\"\"", "self", ".", "fl_price", "=...
https://github.com/HuobiRDCenter/huobi_Python/blob/c75a7fa8b31e99ffc1c173d74dcfcad83682e943/huobi/model/margin/margin_account_balance.py#L19-L27
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_hxb2/lib/python3.5/site-packages/redis/client.py
python
StrictRedis.pubsub_channels
(self, pattern='*')
return self.execute_command('PUBSUB CHANNELS', pattern)
Return a list of channels that have at least one subscriber
Return a list of channels that have at least one subscriber
[ "Return", "a", "list", "of", "channels", "that", "have", "at", "least", "one", "subscriber" ]
def pubsub_channels(self, pattern='*'): """ Return a list of channels that have at least one subscriber """ return self.execute_command('PUBSUB CHANNELS', pattern)
[ "def", "pubsub_channels", "(", "self", ",", "pattern", "=", "'*'", ")", ":", "return", "self", ".", "execute_command", "(", "'PUBSUB CHANNELS'", ",", "pattern", ")" ]
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_hxb2/lib/python3.5/site-packages/redis/client.py#L2036-L2040
dieseldev/diesel
8d48371fce0b79d6631053594bce06e4b9628499
diesel/util/process.py
python
ProcessPool.__init__
(self, concurrency, handler)
Creates a new ProcessPool with subprocesses that run the handler. Args: concurrency (int): The number of subprocesses to spawn. handler (callable): A callable that the subprocesses will execute.
Creates a new ProcessPool with subprocesses that run the handler.
[ "Creates", "a", "new", "ProcessPool", "with", "subprocesses", "that", "run", "the", "handler", "." ]
def __init__(self, concurrency, handler): """Creates a new ProcessPool with subprocesses that run the handler. Args: concurrency (int): The number of subprocesses to spawn. handler (callable): A callable that the subprocesses will execute. """ self.concurrency = concurrency self.handler = handler self.available_procs = Queue() self.all_procs = []
[ "def", "__init__", "(", "self", ",", "concurrency", ",", "handler", ")", ":", "self", ".", "concurrency", "=", "concurrency", "self", ".", "handler", "=", "handler", "self", ".", "available_procs", "=", "Queue", "(", ")", "self", ".", "all_procs", "=", "...
https://github.com/dieseldev/diesel/blob/8d48371fce0b79d6631053594bce06e4b9628499/diesel/util/process.py#L158-L169
huggingface/datasets
249b4a38390bf1543f5b6e2f3dc208b5689c1c13
datasets/competition_math/competition_math.py
python
CompetitionMathDataset._split_generators
(self, dl_manager)
return [ datasets.SplitGenerator( name=datasets.Split.TRAIN, gen_kwargs={"math_dir": math_dir, "split": "train"}, ), datasets.SplitGenerator( name=datasets.Split.TEST, gen_kwargs={"math_dir": math_dir, "split": "test"}, ), ]
Returns SplitGenerators.
Returns SplitGenerators.
[ "Returns", "SplitGenerators", "." ]
def _split_generators(self, dl_manager): """Returns SplitGenerators.""" download_dir = dl_manager.download_and_extract(_URL) math_dir = os.path.join(download_dir, "MATH") return [ datasets.SplitGenerator( name=datasets.Split.TRAIN, gen_kwargs={"math_dir": math_dir, "split": "train"}, ), datasets.SplitGenerator( name=datasets.Split.TEST, gen_kwargs={"math_dir": math_dir, "split": "test"}, ), ]
[ "def", "_split_generators", "(", "self", ",", "dl_manager", ")", ":", "download_dir", "=", "dl_manager", ".", "download_and_extract", "(", "_URL", ")", "math_dir", "=", "os", ".", "path", ".", "join", "(", "download_dir", ",", "\"MATH\"", ")", "return", "[",...
https://github.com/huggingface/datasets/blob/249b4a38390bf1543f5b6e2f3dc208b5689c1c13/datasets/competition_math/competition_math.py#L68-L81
pymedusa/Medusa
1405fbb6eb8ef4d20fcca24c32ddca52b11f0f38
ext/github/Gist.py
python
Gist.description
(self)
return self._description.value
:type: string
:type: string
[ ":", "type", ":", "string" ]
def description(self): """ :type: string """ self._completeIfNotSet(self._description) return self._description.value
[ "def", "description", "(", "self", ")", ":", "self", ".", "_completeIfNotSet", "(", "self", ".", "_description", ")", "return", "self", ".", "_description", ".", "value" ]
https://github.com/pymedusa/Medusa/blob/1405fbb6eb8ef4d20fcca24c32ddca52b11f0f38/ext/github/Gist.py#L89-L94
entropy1337/infernal-twin
10995cd03312e39a48ade0f114ebb0ae3a711bb8
Modules/build/pip/pip/_vendor/html5lib/treebuilders/etree_lxml.py
python
tostring
(element)
return "".join(rv)
Serialize an element and its child nodes to a string
Serialize an element and its child nodes to a string
[ "Serialize", "an", "element", "and", "its", "child", "nodes", "to", "a", "string" ]
def tostring(element): """Serialize an element and its child nodes to a string""" rv = [] finalText = None def serializeElement(element): if not hasattr(element, "tag"): if element.docinfo.internalDTD: if element.docinfo.doctype: dtd_str = element.docinfo.doctype else: dtd_str = "<!DOCTYPE %s>" % element.docinfo.root_name rv.append(dtd_str) serializeElement(element.getroot()) elif element.tag == comment_type: rv.append("<!--%s-->" % (element.text,)) else: # This is assumed to be an ordinary element if not element.attrib: rv.append("<%s>" % (element.tag,)) else: attr = " ".join(["%s=\"%s\"" % (name, value) for name, value in element.attrib.items()]) rv.append("<%s %s>" % (element.tag, attr)) if element.text: rv.append(element.text) for child in element: serializeElement(child) rv.append("</%s>" % (element.tag,)) if hasattr(element, "tail") and element.tail: rv.append(element.tail) serializeElement(element) if finalText is not None: rv.append("%s\"" % (' ' * 2, finalText)) return "".join(rv)
[ "def", "tostring", "(", "element", ")", ":", "rv", "=", "[", "]", "finalText", "=", "None", "def", "serializeElement", "(", "element", ")", ":", "if", "not", "hasattr", "(", "element", ",", "\"tag\"", ")", ":", "if", "element", ".", "docinfo", ".", "...
https://github.com/entropy1337/infernal-twin/blob/10995cd03312e39a48ade0f114ebb0ae3a711bb8/Modules/build/pip/pip/_vendor/html5lib/treebuilders/etree_lxml.py#L137-L179
JonathonLuiten/PReMVOS
2666acaae0f1b4bd7d88a0cfb9b7cf5c5de12a4b
code/proposal_net/model.py
python
sample_fast_rcnn_targets
(boxes, gt_boxes, gt_labels)
return tf.stop_gradient(ret_boxes), tf.stop_gradient(ret_labels), fg_inds_wrt_gt, bg_inds
Sample some ROIs from all proposals for training. Args: boxes: nx4 region proposals, floatbox gt_boxes: mx4, floatbox gt_labels: m, int32 Returns: sampled_boxes: tx4 floatbox, the rois sampled_labels: t labels, in [0, #class-1]. Positive means foreground. fg_inds_wrt_gt: #fg indices, each in range [0, m-1]. It contains the matching GT of each foreground roi.
Sample some ROIs from all proposals for training.
[ "Sample", "some", "ROIs", "from", "all", "proposals", "for", "training", "." ]
def sample_fast_rcnn_targets(boxes, gt_boxes, gt_labels): """ Sample some ROIs from all proposals for training. Args: boxes: nx4 region proposals, floatbox gt_boxes: mx4, floatbox gt_labels: m, int32 Returns: sampled_boxes: tx4 floatbox, the rois sampled_labels: t labels, in [0, #class-1]. Positive means foreground. fg_inds_wrt_gt: #fg indices, each in range [0, m-1]. It contains the matching GT of each foreground roi. """ iou = pairwise_iou(boxes, gt_boxes) # nxm proposal_metrics(iou) # add ground truth as proposals as well boxes = tf.concat([boxes, gt_boxes], axis=0) # (n+m) x 4 iou = tf.concat([iou, tf.eye(tf.shape(gt_boxes)[0])], axis=0) # (n+m) x m # #proposal=n+m from now on def sample_fg_bg(iou): fg_mask = tf.reduce_max(iou, axis=1) >= config.FASTRCNN_FG_THRESH fg_inds = tf.reshape(tf.where(fg_mask), [-1]) num_fg = tf.minimum(int( config.FASTRCNN_BATCH_PER_IM * config.FASTRCNN_FG_RATIO), tf.size(fg_inds), name='num_fg') fg_inds = tf.random_shuffle(fg_inds)[:num_fg] bg_inds = tf.reshape(tf.where(tf.logical_not(fg_mask)), [-1]) num_bg = tf.minimum( config.FASTRCNN_BATCH_PER_IM - num_fg, tf.size(bg_inds), name='num_bg') bg_inds = tf.random_shuffle(bg_inds)[:num_bg] add_moving_summary(num_fg, num_bg) return fg_inds, bg_inds fg_inds, bg_inds = sample_fg_bg(iou) # fg,bg indices w.r.t proposals best_iou_ind = tf.argmax(iou, axis=1) # #proposal, each in 0~m-1 fg_inds_wrt_gt = tf.gather(best_iou_ind, fg_inds) # num_fg all_indices = tf.concat([fg_inds, bg_inds], axis=0) # indices w.r.t all n+m proposal boxes ret_boxes = tf.gather(boxes, all_indices, name='sampled_proposal_boxes') ret_labels = tf.concat( [tf.gather(gt_labels, fg_inds_wrt_gt), tf.zeros_like(bg_inds, dtype=tf.int64)], axis=0, name='sampled_labels') # stop the gradient -- they are meant to be ground-truth return tf.stop_gradient(ret_boxes), tf.stop_gradient(ret_labels), fg_inds_wrt_gt, bg_inds
[ "def", "sample_fast_rcnn_targets", "(", "boxes", ",", "gt_boxes", ",", "gt_labels", ")", ":", "iou", "=", "pairwise_iou", "(", "boxes", ",", "gt_boxes", ")", "# nxm", "proposal_metrics", "(", "iou", ")", "# add ground truth as proposals as well", "boxes", "=", "tf...
https://github.com/JonathonLuiten/PReMVOS/blob/2666acaae0f1b4bd7d88a0cfb9b7cf5c5de12a4b/code/proposal_net/model.py#L243-L297
JaniceWuo/MovieRecommend
4c86db64ca45598917d304f535413df3bc9fea65
movierecommend/venv1/Lib/site-packages/pip-9.0.1-py3.6.egg/pip/_vendor/distlib/_backport/tarfile.py
python
TarFile.extractall
(self, path=".", members=None)
Extract all members from the archive to the current working directory and set owner, modification time and permissions on directories afterwards. `path' specifies a different directory to extract to. `members' is optional and must be a subset of the list returned by getmembers().
Extract all members from the archive to the current working directory and set owner, modification time and permissions on directories afterwards. `path' specifies a different directory to extract to. `members' is optional and must be a subset of the list returned by getmembers().
[ "Extract", "all", "members", "from", "the", "archive", "to", "the", "current", "working", "directory", "and", "set", "owner", "modification", "time", "and", "permissions", "on", "directories", "afterwards", ".", "path", "specifies", "a", "different", "directory", ...
def extractall(self, path=".", members=None): """Extract all members from the archive to the current working directory and set owner, modification time and permissions on directories afterwards. `path' specifies a different directory to extract to. `members' is optional and must be a subset of the list returned by getmembers(). """ directories = [] if members is None: members = self for tarinfo in members: if tarinfo.isdir(): # Extract directories with a safe mode. directories.append(tarinfo) tarinfo = copy.copy(tarinfo) tarinfo.mode = 0o700 # Do not set_attrs directories, as we will do that further down self.extract(tarinfo, path, set_attrs=not tarinfo.isdir()) # Reverse sort directories. directories.sort(key=lambda a: a.name) directories.reverse() # Set correct owner, mtime and filemode on directories. for tarinfo in directories: dirpath = os.path.join(path, tarinfo.name) try: self.chown(tarinfo, dirpath) self.utime(tarinfo, dirpath) self.chmod(tarinfo, dirpath) except ExtractError as e: if self.errorlevel > 1: raise else: self._dbg(1, "tarfile: %s" % e)
[ "def", "extractall", "(", "self", ",", "path", "=", "\".\"", ",", "members", "=", "None", ")", ":", "directories", "=", "[", "]", "if", "members", "is", "None", ":", "members", "=", "self", "for", "tarinfo", "in", "members", ":", "if", "tarinfo", "."...
https://github.com/JaniceWuo/MovieRecommend/blob/4c86db64ca45598917d304f535413df3bc9fea65/movierecommend/venv1/Lib/site-packages/pip-9.0.1-py3.6.egg/pip/_vendor/distlib/_backport/tarfile.py#L2126-L2162
saltstack/salt
fae5bc757ad0f1716483ce7ae180b451545c2058
salt/states/rbenv.py
python
_check_rbenv
(ret, user=None)
return ret
Check to see if rbenv is installed.
Check to see if rbenv is installed.
[ "Check", "to", "see", "if", "rbenv", "is", "installed", "." ]
def _check_rbenv(ret, user=None): """ Check to see if rbenv is installed. """ if not __salt__["rbenv.is_installed"](user): ret["result"] = False ret["comment"] = "Rbenv is not installed." return ret
[ "def", "_check_rbenv", "(", "ret", ",", "user", "=", "None", ")", ":", "if", "not", "__salt__", "[", "\"rbenv.is_installed\"", "]", "(", "user", ")", ":", "ret", "[", "\"result\"", "]", "=", "False", "ret", "[", "\"comment\"", "]", "=", "\"Rbenv is not i...
https://github.com/saltstack/salt/blob/fae5bc757ad0f1716483ce7ae180b451545c2058/salt/states/rbenv.py#L59-L66
nonebot/aiocqhttp
eaa850e8d7432e04394194b3d82bb88570390732
aiocqhttp/message.py
python
MessageSegment.xml
(data: str)
return MessageSegment(type_='xml', data={'data': data})
XML 消息。
XML 消息。
[ "XML", "消息。" ]
def xml(data: str) -> 'MessageSegment': """XML 消息。""" return MessageSegment(type_='xml', data={'data': data})
[ "def", "xml", "(", "data", ":", "str", ")", "->", "'MessageSegment'", ":", "return", "MessageSegment", "(", "type_", "=", "'xml'", ",", "data", "=", "{", "'data'", ":", "data", "}", ")" ]
https://github.com/nonebot/aiocqhttp/blob/eaa850e8d7432e04394194b3d82bb88570390732/aiocqhttp/message.py#L388-L390
securesystemslab/zippy
ff0e84ac99442c2c55fe1d285332cfd4e185e089
zippy/benchmarks/src/benchmarks/sympy/sympy/printing/jscode.py
python
JavascriptCodePrinter._print_NegativeInfinity
(self, expr)
return 'Number.NEGATIVE_INFINITY'
[]
def _print_NegativeInfinity(self, expr): return 'Number.NEGATIVE_INFINITY'
[ "def", "_print_NegativeInfinity", "(", "self", ",", "expr", ")", ":", "return", "'Number.NEGATIVE_INFINITY'" ]
https://github.com/securesystemslab/zippy/blob/ff0e84ac99442c2c55fe1d285332cfd4e185e089/zippy/benchmarks/src/benchmarks/sympy/sympy/printing/jscode.py#L173-L174
andreikop/enki
3170059e5cb46dcc77d7fb1457c38a8a5f13af66
enki/core/workspace.py
python
Workspace._openSingleFile
(self, filePath)
return document
Open 1 file. Helper method, used by openFile() and openFiles()
Open 1 file. Helper method, used by openFile() and openFiles()
[ "Open", "1", "file", ".", "Helper", "method", "used", "by", "openFile", "()", "and", "openFiles", "()" ]
def _openSingleFile(self, filePath): """Open 1 file. Helper method, used by openFile() and openFiles() """ # Close 'untitled' if len(self.documents()) == 1 and \ self.documents()[0].fileName() is None and \ not self.documents()[0].filePath() and \ not self.documents()[0].qutepart.text and \ not self.documents()[0].qutepart.document().isModified(): self.closeDocument(self.documents()[0]) # check if file is already opened alreadyOpenedDocument = self.findDocumentForPath(filePath) if alreadyOpenedDocument is not None: self.setCurrentDocument(alreadyOpenedDocument) return alreadyOpenedDocument # Check if exists, get stat try: statInfo = os.stat(filePath) except (OSError, IOError) as ex: QMessageBox.critical(self._mainWindow(), "Failed to stat the file", str(ex)) return None # Check if is a directory if stat.S_ISDIR(statInfo.st_mode): QMessageBox.critical(self._mainWindow(), "Can not open a directory", "{} is a directory".format(filePath)) return None # Check if too big if statInfo.st_size > _MAX_SUPPORTED_FILE_SIZE: msg = ("<html>" + "{} file size is {}.<br/>" + "I am a text editor, but not a data dump editor. " + " I'm sory but I don't know how to open such a big files" + "</html>") .format(filePath, statInfo.st_size) QMessageBox.critical(self._mainWindow(), "Too big file", msg) return None # Check if have access to read if not os.access(filePath, os.R_OK): QMessageBox.critical(self._mainWindow(), "Don't have the access", "You don't have the read permission for {}".format(filePath)) return None # open the file document = Document(self, filePath) self._handleDocument(document) if not os.access(filePath, os.W_OK): core.mainWindow().appendMessage( self.tr("File '%s' is not writable" % filePath), 4000) # todo fix return document
[ "def", "_openSingleFile", "(", "self", ",", "filePath", ")", ":", "# Close 'untitled'", "if", "len", "(", "self", ".", "documents", "(", ")", ")", "==", "1", "and", "self", ".", "documents", "(", ")", "[", "0", "]", ".", "fileName", "(", ")", "is", ...
https://github.com/andreikop/enki/blob/3170059e5cb46dcc77d7fb1457c38a8a5f13af66/enki/core/workspace.py#L519-L578
vulnersCom/api
1a2537abea0535694b00138a40e85378b199e0d5
vulners/api.py
python
Vulners.__autocomplete
(self, query)
return self.vulners_post_request('autocomplete', {"query":query})
Tech wrapper for the Autocomplete call :param type: Search query. :param field_name: How much bulletins to skip. :return: List of possible values
Tech wrapper for the Autocomplete call
[ "Tech", "wrapper", "for", "the", "Autocomplete", "call" ]
def __autocomplete(self, query): """ Tech wrapper for the Autocomplete call :param type: Search query. :param field_name: How much bulletins to skip. :return: List of possible values """ if not isinstance(query, string_types): raise TypeError("Query expected to be a string") return self.vulners_post_request('autocomplete', {"query":query})
[ "def", "__autocomplete", "(", "self", ",", "query", ")", ":", "if", "not", "isinstance", "(", "query", ",", "string_types", ")", ":", "raise", "TypeError", "(", "\"Query expected to be a string\"", ")", "return", "self", ".", "vulners_post_request", "(", "'autoc...
https://github.com/vulnersCom/api/blob/1a2537abea0535694b00138a40e85378b199e0d5/vulners/api.py#L402-L412
holzschu/Carnets
44effb10ddfc6aa5c8b0687582a724ba82c6b547
Library/lib/python3.7/site-packages/astropy-4.0-py3.7-macosx-10.9-x86_64.egg/astropy/coordinates/representation.py
python
PhysicsSphericalRepresentation.phi
(self)
return self._phi
The azimuth of the point(s).
The azimuth of the point(s).
[ "The", "azimuth", "of", "the", "point", "(", "s", ")", "." ]
def phi(self): """ The azimuth of the point(s). """ return self._phi
[ "def", "phi", "(", "self", ")", ":", "return", "self", ".", "_phi" ]
https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/astropy-4.0-py3.7-macosx-10.9-x86_64.egg/astropy/coordinates/representation.py#L1752-L1756
GluuFederation/community-edition-setup
d0c9427ed9e3ea3d95691677b73c1402ed9ca4db
pylib/ldif3/ldif3.py
python
LDIFWriter._unparse_entry_record
(self, entry)
:type entry: Dict[string, List[string]] :param entry: Dictionary holding an entry
:type entry: Dict[string, List[string]] :param entry: Dictionary holding an entry
[ ":", "type", "entry", ":", "Dict", "[", "string", "List", "[", "string", "]]", ":", "param", "entry", ":", "Dictionary", "holding", "an", "entry" ]
def _unparse_entry_record(self, entry): """ :type entry: Dict[string, List[string]] :param entry: Dictionary holding an entry """ for attr_type in sorted(entry.keys()): for attr_value in entry[attr_type]: self._unparse_attr(attr_type, attr_value)
[ "def", "_unparse_entry_record", "(", "self", ",", "entry", ")", ":", "for", "attr_type", "in", "sorted", "(", "entry", ".", "keys", "(", ")", ")", ":", "for", "attr_value", "in", "entry", "[", "attr_type", "]", ":", "self", ".", "_unparse_attr", "(", "...
https://github.com/GluuFederation/community-edition-setup/blob/d0c9427ed9e3ea3d95691677b73c1402ed9ca4db/pylib/ldif3/ldif3.py#L139-L146
giswqs/whitebox-python
b4df0bbb10a1dee3bd0f6b3482511f7c829b38fe
whitebox/whitebox_tools.py
python
WhiteboxTools.prewitt_filter
(self, i, output, clip=0.0, callback=None)
return self.run_tool('prewitt_filter', args, callback)
Performs a Prewitt edge-detection filter on an image. Keyword arguments: i -- Input raster file. output -- Output raster file. clip -- Optional amount to clip the distribution tails by, in percent. callback -- Custom function for handling tool text outputs.
Performs a Prewitt edge-detection filter on an image.
[ "Performs", "a", "Prewitt", "edge", "-", "detection", "filter", "on", "an", "image", "." ]
def prewitt_filter(self, i, output, clip=0.0, callback=None): """Performs a Prewitt edge-detection filter on an image. Keyword arguments: i -- Input raster file. output -- Output raster file. clip -- Optional amount to clip the distribution tails by, in percent. callback -- Custom function for handling tool text outputs. """ args = [] args.append("--input='{}'".format(i)) args.append("--output='{}'".format(output)) args.append("--clip={}".format(clip)) return self.run_tool('prewitt_filter', args, callback)
[ "def", "prewitt_filter", "(", "self", ",", "i", ",", "output", ",", "clip", "=", "0.0", ",", "callback", "=", "None", ")", ":", "args", "=", "[", "]", "args", ".", "append", "(", "\"--input='{}'\"", ".", "format", "(", "i", ")", ")", "args", ".", ...
https://github.com/giswqs/whitebox-python/blob/b4df0bbb10a1dee3bd0f6b3482511f7c829b38fe/whitebox/whitebox_tools.py#L5931-L5945
midgetspy/Sick-Beard
171a607e41b7347a74cc815f6ecce7968d9acccf
lib/oauth2/__init__.py
python
Token.from_string
(s)
return token
Deserializes a token from a string like one returned by `to_string()`.
Deserializes a token from a string like one returned by `to_string()`.
[ "Deserializes", "a", "token", "from", "a", "string", "like", "one", "returned", "by", "to_string", "()", "." ]
def from_string(s): """Deserializes a token from a string like one returned by `to_string()`.""" if not len(s): raise ValueError("Invalid parameter string.") params = parse_qs(s, keep_blank_values=False) if not len(params): raise ValueError("Invalid parameter string.") try: key = params['oauth_token'][0] except Exception: raise ValueError("'oauth_token' not found in OAuth request.") try: secret = params['oauth_token_secret'][0] except Exception: raise ValueError("'oauth_token_secret' not found in " "OAuth request.") token = Token(key, secret) try: token.callback_confirmed = params['oauth_callback_confirmed'][0] except KeyError: pass # 1.0, no callback confirmed. return token
[ "def", "from_string", "(", "s", ")", ":", "if", "not", "len", "(", "s", ")", ":", "raise", "ValueError", "(", "\"Invalid parameter string.\"", ")", "params", "=", "parse_qs", "(", "s", ",", "keep_blank_values", "=", "False", ")", "if", "not", "len", "(",...
https://github.com/midgetspy/Sick-Beard/blob/171a607e41b7347a74cc815f6ecce7968d9acccf/lib/oauth2/__init__.py#L193-L220
holzschu/Carnets
44effb10ddfc6aa5c8b0687582a724ba82c6b547
Library/lib/python3.7/site-packages/docutils/utils/math/math2html.py
python
MacroParser.parseheader
(self, reader)
return ['inline']
See if the formula is inlined
See if the formula is inlined
[ "See", "if", "the", "formula", "is", "inlined" ]
def parseheader(self, reader): "See if the formula is inlined" self.begin = reader.linenumber + 1 return ['inline']
[ "def", "parseheader", "(", "self", ",", "reader", ")", ":", "self", ".", "begin", "=", "reader", ".", "linenumber", "+", "1", "return", "[", "'inline'", "]" ]
https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/docutils/utils/math/math2html.py#L2566-L2569
TensorMSA/tensormsa
c36b565159cd934533636429add3c7d7263d622b
cluster/neuralnet/neuralnet_node_seq2seq.py
python
NeuralNetNodeSeq2Seq._set_weight_vectors
(self)
set weight vecotrs seperatly for sharing weight with preidicts logic :return:
set weight vecotrs seperatly for sharing weight with preidicts logic :return:
[ "set", "weight", "vecotrs", "seperatly", "for", "sharing", "weight", "with", "preidicts", "logic", ":", "return", ":" ]
def _set_weight_vectors(self): """ set weight vecotrs seperatly for sharing weight with preidicts logic :return: """ # Weigths with tf.variable_scope('rnnlm') as scope: self.softmax_w = tf.get_variable("softmax_w", [self.cell_size, self.vocab_size]) self.softmax_b = tf.get_variable("softmax_b", [self.vocab_size])
[ "def", "_set_weight_vectors", "(", "self", ")", ":", "# Weigths", "with", "tf", ".", "variable_scope", "(", "'rnnlm'", ")", "as", "scope", ":", "self", ".", "softmax_w", "=", "tf", ".", "get_variable", "(", "\"softmax_w\"", ",", "[", "self", ".", "cell_siz...
https://github.com/TensorMSA/tensormsa/blob/c36b565159cd934533636429add3c7d7263d622b/cluster/neuralnet/neuralnet_node_seq2seq.py#L303-L311
EtienneCmb/visbrain
b599038e095919dc193b12d5e502d127de7d03c9
visbrain/io/rw_utils.py
python
safety_save
(path, limit=100)
return path
If a file exist, avoid erasing it when saving. Parameters ---------- path : string Path to the file. limit : int | 100 Limit for the filename occurence. Returns ------- name : string Unique filename.
If a file exist, avoid erasing it when saving.
[ "If", "a", "file", "exist", "avoid", "erasing", "it", "when", "saving", "." ]
def safety_save(path, limit=100): """If a file exist, avoid erasing it when saving. Parameters ---------- path : string Path to the file. limit : int | 100 Limit for the filename occurence. Returns ------- name : string Unique filename. """ k = 1 while os.path.isfile(path) and (k < limit): fname, fext = os.path.splitext(path) if fname.find('(') + 1: path = fname[0:fname.find('(') + 1] + str(k) + ')' + fext else: path = fname + '(' + str(k) + ')' + fext k += 1 return path
[ "def", "safety_save", "(", "path", ",", "limit", "=", "100", ")", ":", "k", "=", "1", "while", "os", ".", "path", ".", "isfile", "(", "path", ")", "and", "(", "k", "<", "limit", ")", ":", "fname", ",", "fext", "=", "os", ".", "path", ".", "sp...
https://github.com/EtienneCmb/visbrain/blob/b599038e095919dc193b12d5e502d127de7d03c9/visbrain/io/rw_utils.py#L38-L61
francisck/DanderSpritz_docs
86bb7caca5a957147f120b18bb5c31f299914904
Python/Core/Lib/logging/__init__.py
python
setLoggerClass
(klass)
Set the class to be used when instantiating a logger. The class should define __init__() such that only a name argument is required, and the __init__() should call Logger.__init__()
Set the class to be used when instantiating a logger. The class should define __init__() such that only a name argument is required, and the __init__() should call Logger.__init__()
[ "Set", "the", "class", "to", "be", "used", "when", "instantiating", "a", "logger", ".", "The", "class", "should", "define", "__init__", "()", "such", "that", "only", "a", "name", "argument", "is", "required", "and", "the", "__init__", "()", "should", "call...
def setLoggerClass(klass): """ Set the class to be used when instantiating a logger. The class should define __init__() such that only a name argument is required, and the __init__() should call Logger.__init__() """ global _loggerClass if klass != Logger: if not issubclass(klass, Logger): raise TypeError('logger not derived from logging.Logger: ' + klass.__name__) _loggerClass = klass
[ "def", "setLoggerClass", "(", "klass", ")", ":", "global", "_loggerClass", "if", "klass", "!=", "Logger", ":", "if", "not", "issubclass", "(", "klass", ",", "Logger", ")", ":", "raise", "TypeError", "(", "'logger not derived from logging.Logger: '", "+", "klass"...
https://github.com/francisck/DanderSpritz_docs/blob/86bb7caca5a957147f120b18bb5c31f299914904/Python/Core/Lib/logging/__init__.py#L869-L879
mozilla-services/socorro
8bff4a90e9e3320eabe7e067adbe0e89f6a39ba7
socorro/external/crashstorage_base.py
python
CrashStorageBase.__init__
(self, config, namespace="")
Initializer :param config: configman DotDict holding configuration information :param namespace: namespace for this crashstorage instance; used for metrics prefixes and logging
Initializer
[ "Initializer" ]
def __init__(self, config, namespace=""): """Initializer :param config: configman DotDict holding configuration information :param namespace: namespace for this crashstorage instance; used for metrics prefixes and logging """ self.config = config self.namespace = namespace # Collection of non-fatal exceptions that can be raised by a given storage # implementation. This may be fetched by a client of the crashstorge so that it # can determine if it can try a failed storage operation again. self.exceptions_eligible_for_retry = () self.redactor = config.redactor_class(config) self.logger = logging.getLogger(__name__ + "." + self.__class__.__name__)
[ "def", "__init__", "(", "self", ",", "config", ",", "namespace", "=", "\"\"", ")", ":", "self", ".", "config", "=", "config", "self", ".", "namespace", "=", "namespace", "# Collection of non-fatal exceptions that can be raised by a given storage", "# implementation. Thi...
https://github.com/mozilla-services/socorro/blob/8bff4a90e9e3320eabe7e067adbe0e89f6a39ba7/socorro/external/crashstorage_base.py#L159-L175
home-assistant/core
265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1
homeassistant/components/homekit_controller/cover.py
python
HomeKitGarageDoorCover.set_door_state
(self, state)
Send state command.
Send state command.
[ "Send", "state", "command", "." ]
async def set_door_state(self, state): """Send state command.""" await self.async_put_characteristics( {CharacteristicsTypes.DOOR_STATE_TARGET: TARGET_GARAGE_STATE_MAP[state]} )
[ "async", "def", "set_door_state", "(", "self", ",", "state", ")", ":", "await", "self", ".", "async_put_characteristics", "(", "{", "CharacteristicsTypes", ".", "DOOR_STATE_TARGET", ":", "TARGET_GARAGE_STATE_MAP", "[", "state", "]", "}", ")" ]
https://github.com/home-assistant/core/blob/265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1/homeassistant/components/homekit_controller/cover.py#L109-L113
mesalock-linux/mesapy
ed546d59a21b36feb93e2309d5c6b75aa0ad95c9
lib-python/2.7/_abcoll.py
python
Sequence.count
(self, value)
return sum(1 for v in self if v == value)
S.count(value) -> integer -- return number of occurrences of value
S.count(value) -> integer -- return number of occurrences of value
[ "S", ".", "count", "(", "value", ")", "-", ">", "integer", "--", "return", "number", "of", "occurrences", "of", "value" ]
def count(self, value): 'S.count(value) -> integer -- return number of occurrences of value' return sum(1 for v in self if v == value)
[ "def", "count", "(", "self", ",", "value", ")", ":", "return", "sum", "(", "1", "for", "v", "in", "self", "if", "v", "==", "value", ")" ]
https://github.com/mesalock-linux/mesapy/blob/ed546d59a21b36feb93e2309d5c6b75aa0ad95c9/lib-python/2.7/_abcoll.py#L630-L632
ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework
cb692f527e4e819b6c228187c5702d990a180043
external/Scripting Engine/Xenotix Python Scripting Engine/bin/x86/Debug/Lib/site-packages/Crypto/Signature/PKCS1_PSS.py
python
PSS_SigScheme.verify
(self, mhash, S)
return result
Verify that a certain PKCS#1 PSS signature is authentic. This function checks if the party holding the private half of the given RSA key has really signed the message. This function is called ``RSASSA-PSS-VERIFY``, and is specified in section 8.1.2 of RFC3447. :Parameters: mhash : hash object The hash that was carried out over the message. This is an object belonging to the `Crypto.Hash` module. S : string The signature that needs to be validated. :Return: True if verification is correct. False otherwise.
Verify that a certain PKCS#1 PSS signature is authentic. This function checks if the party holding the private half of the given RSA key has really signed the message. This function is called ``RSASSA-PSS-VERIFY``, and is specified in section 8.1.2 of RFC3447. :Parameters: mhash : hash object The hash that was carried out over the message. This is an object belonging to the `Crypto.Hash` module. S : string The signature that needs to be validated. :Return: True if verification is correct. False otherwise.
[ "Verify", "that", "a", "certain", "PKCS#1", "PSS", "signature", "is", "authentic", ".", "This", "function", "checks", "if", "the", "party", "holding", "the", "private", "half", "of", "the", "given", "RSA", "key", "has", "really", "signed", "the", "message", ...
def verify(self, mhash, S): """Verify that a certain PKCS#1 PSS signature is authentic. This function checks if the party holding the private half of the given RSA key has really signed the message. This function is called ``RSASSA-PSS-VERIFY``, and is specified in section 8.1.2 of RFC3447. :Parameters: mhash : hash object The hash that was carried out over the message. This is an object belonging to the `Crypto.Hash` module. S : string The signature that needs to be validated. :Return: True if verification is correct. False otherwise. """ # TODO: Verify the key is RSA # Set defaults for salt length and mask generation function if self._saltLen == None: sLen = mhash.digest_size else: sLen = self._saltLen if self._mgfunc: mgf = self._mgfunc else: mgf = lambda x,y: MGF1(x,y,mhash) modBits = Crypto.Util.number.size(self._key.n) # See 8.1.2 in RFC3447 k = ceil_div(modBits,8) # Convert from bits to bytes # Step 1 if len(S) != k: return False # Step 2a (O2SIP), 2b (RSAVP1), and partially 2c (I2OSP) # Note that signature must be smaller than the module # but RSA.py won't complain about it. # TODO: Fix RSA object; don't do it here. em = self._key.encrypt(S, 0)[0] # Step 2c emLen = ceil_div(modBits-1,8) em = bchr(0x00)*(emLen-len(em)) + em # Step 3 try: result = EMSA_PSS_VERIFY(mhash, em, modBits-1, mgf, sLen) except ValueError: return False # Step 4 return result
[ "def", "verify", "(", "self", ",", "mhash", ",", "S", ")", ":", "# TODO: Verify the key is RSA", "# Set defaults for salt length and mask generation function", "if", "self", ".", "_saltLen", "==", "None", ":", "sLen", "=", "mhash", ".", "digest_size", "else", ":", ...
https://github.com/ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework/blob/cb692f527e4e819b6c228187c5702d990a180043/external/Scripting Engine/Xenotix Python Scripting Engine/bin/x86/Debug/Lib/site-packages/Crypto/Signature/PKCS1_PSS.py#L148-L199
dmarnerides/pydlt
b018f75b68af29645d0a5dae10b6d7255e53f867
dlt/util/logger.py
python
Logger.__call__
(self, values)
Same as :meth:`log`
Same as :meth:`log`
[ "Same", "as", ":", "meth", ":", "log" ]
def __call__(self, values): """Same as :meth:`log`""" self.log(values)
[ "def", "__call__", "(", "self", ",", "values", ")", ":", "self", ".", "log", "(", "values", ")" ]
https://github.com/dmarnerides/pydlt/blob/b018f75b68af29645d0a5dae10b6d7255e53f867/dlt/util/logger.py#L39-L41
nipy/nipype
cd4c34d935a43812d1756482fdc4034844e485b8
nipype/interfaces/freesurfer/preprocess.py
python
ReconAll._list_outputs
(self)
return outputs
See io.FreeSurferSource.outputs for the list of outputs returned
See io.FreeSurferSource.outputs for the list of outputs returned
[ "See", "io", ".", "FreeSurferSource", ".", "outputs", "for", "the", "list", "of", "outputs", "returned" ]
def _list_outputs(self): """ See io.FreeSurferSource.outputs for the list of outputs returned """ if isdefined(self.inputs.subjects_dir): subjects_dir = self.inputs.subjects_dir else: subjects_dir = self._gen_subjects_dir() if isdefined(self.inputs.hemi): hemi = self.inputs.hemi else: hemi = "both" outputs = self._outputs().get() outputs.update( FreeSurferSource( subject_id=self.inputs.subject_id, subjects_dir=subjects_dir, hemi=hemi )._list_outputs() ) outputs["subject_id"] = self.inputs.subject_id outputs["subjects_dir"] = subjects_dir return outputs
[ "def", "_list_outputs", "(", "self", ")", ":", "if", "isdefined", "(", "self", ".", "inputs", ".", "subjects_dir", ")", ":", "subjects_dir", "=", "self", ".", "inputs", ".", "subjects_dir", "else", ":", "subjects_dir", "=", "self", ".", "_gen_subjects_dir", ...
https://github.com/nipy/nipype/blob/cd4c34d935a43812d1756482fdc4034844e485b8/nipype/interfaces/freesurfer/preprocess.py#L1510-L1533
volatilityfoundation/volatility3
168b0d0b053ab97a7cb096ef2048795cc54d885f
volatility3/framework/plugins/mac/list_files.py
python
List_Files._vnode_name
(cls, vnode: interfaces.objects.ObjectInterface)
return v_name
[]
def _vnode_name(cls, vnode: interfaces.objects.ObjectInterface) -> Optional[str]: # roots of mount points have special name handling if vnode.v_flag & 1 == 1: v_name = vnode.full_path() else: try: v_name = utility.pointer_to_string(vnode.v_name, 255) except exceptions.InvalidAddressException: v_name = None return v_name
[ "def", "_vnode_name", "(", "cls", ",", "vnode", ":", "interfaces", ".", "objects", ".", "ObjectInterface", ")", "->", "Optional", "[", "str", "]", ":", "# roots of mount points have special name handling", "if", "vnode", ".", "v_flag", "&", "1", "==", "1", ":"...
https://github.com/volatilityfoundation/volatility3/blob/168b0d0b053ab97a7cb096ef2048795cc54d885f/volatility3/framework/plugins/mac/list_files.py#L32-L42
holzschu/Carnets
44effb10ddfc6aa5c8b0687582a724ba82c6b547
Library/lib/python3.7/site-packages/jedi/evaluate/docstrings.py
python
_execute_types_in_stmt
(module_context, stmt)
return ContextSet.from_sets( _execute_array_values(module_context.evaluator, d) for d in definitions )
Executing all types or general elements that we find in a statement. This doesn't include tuple, list and dict literals, because the stuff they contain is executed. (Used as type information).
Executing all types or general elements that we find in a statement. This doesn't include tuple, list and dict literals, because the stuff they contain is executed. (Used as type information).
[ "Executing", "all", "types", "or", "general", "elements", "that", "we", "find", "in", "a", "statement", ".", "This", "doesn", "t", "include", "tuple", "list", "and", "dict", "literals", "because", "the", "stuff", "they", "contain", "is", "executed", ".", "...
def _execute_types_in_stmt(module_context, stmt): """ Executing all types or general elements that we find in a statement. This doesn't include tuple, list and dict literals, because the stuff they contain is executed. (Used as type information). """ definitions = module_context.eval_node(stmt) return ContextSet.from_sets( _execute_array_values(module_context.evaluator, d) for d in definitions )
[ "def", "_execute_types_in_stmt", "(", "module_context", ",", "stmt", ")", ":", "definitions", "=", "module_context", ".", "eval_node", "(", "stmt", ")", "return", "ContextSet", ".", "from_sets", "(", "_execute_array_values", "(", "module_context", ".", "evaluator", ...
https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/jedi/evaluate/docstrings.py#L235-L245
onelogin/python3-saml
b4199c5364d4b4c00d9930d9e4dab655ecdfaf81
src/onelogin/saml2/utils.py
python
OneLogin_Saml2_Utils.format_private_key
(key, heads=True)
return private_key
Returns a private key (adding header & footer if required). :param key A private key :type: string :param heads: True if we want to include head and footer :type: boolean :returns: Formated private key :rtype: string
Returns a private key (adding header & footer if required).
[ "Returns", "a", "private", "key", "(", "adding", "header", "&", "footer", "if", "required", ")", "." ]
def format_private_key(key, heads=True): """ Returns a private key (adding header & footer if required). :param key A private key :type: string :param heads: True if we want to include head and footer :type: boolean :returns: Formated private key :rtype: string """ private_key = key.replace('\x0D', '') private_key = private_key.replace('\r', '') private_key = private_key.replace('\n', '') if len(private_key) > 0: if private_key.find('-----BEGIN PRIVATE KEY-----') != -1: private_key = private_key.replace('-----BEGIN PRIVATE KEY-----', '') private_key = private_key.replace('-----END PRIVATE KEY-----', '') private_key = private_key.replace(' ', '') if heads: private_key = "-----BEGIN PRIVATE KEY-----\n" + "\n".join(wrap(private_key, 64)) + "\n-----END PRIVATE KEY-----\n" else: private_key = private_key.replace('-----BEGIN RSA PRIVATE KEY-----', '') private_key = private_key.replace('-----END RSA PRIVATE KEY-----', '') private_key = private_key.replace(' ', '') if heads: private_key = "-----BEGIN RSA PRIVATE KEY-----\n" + "\n".join(wrap(private_key, 64)) + "\n-----END RSA PRIVATE KEY-----\n" return private_key
[ "def", "format_private_key", "(", "key", ",", "heads", "=", "True", ")", ":", "private_key", "=", "key", ".", "replace", "(", "'\\x0D'", ",", "''", ")", "private_key", "=", "private_key", ".", "replace", "(", "'\\r'", ",", "''", ")", "private_key", "=", ...
https://github.com/onelogin/python3-saml/blob/b4199c5364d4b4c00d9930d9e4dab655ecdfaf81/src/onelogin/saml2/utils.py#L159-L188
pabigot/pyxb
14737c23a125fd12c954823ad64fc4497816fae3
pyxb/binding/content.py
python
AutomatonConfiguration.__resetPreferredSequence
(self, instance)
return preferred_sequence
[]
def __resetPreferredSequence (self, instance): self.__preferredSequenceIndex = 0 self.__preferredPendingSymbol = None self.__pendingNonElementContent = None vc = instance._validationConfig preferred_sequence = None if (vc.ALWAYS == vc.contentInfluencesGeneration) or (instance._ContentTypeTag == instance._CT_MIXED and vc.MIXED_ONLY == vc.contentInfluencesGeneration): preferred_sequence = instance.orderedContent() if instance._ContentTypeTag == instance._CT_MIXED: self.__pendingNonElementContent = [] return preferred_sequence
[ "def", "__resetPreferredSequence", "(", "self", ",", "instance", ")", ":", "self", ".", "__preferredSequenceIndex", "=", "0", "self", ".", "__preferredPendingSymbol", "=", "None", "self", ".", "__pendingNonElementContent", "=", "None", "vc", "=", "instance", ".", ...
https://github.com/pabigot/pyxb/blob/14737c23a125fd12c954823ad64fc4497816fae3/pyxb/binding/content.py#L504-L514
openshift/openshift-tools
1188778e728a6e4781acf728123e5b356380fe6f
openshift/installer/vendored/openshift-ansible-3.10.0-0.29.0/roles/lib_vendored_deps/library/oc_adm_policy_group.py
python
RoleBinding.update_subject
(self, inc_subject)
return True
update a subject
update a subject
[ "update", "a", "subject" ]
def update_subject(self, inc_subject): ''' update a subject ''' try: # pylint: disable=no-member index = self.subjects.index(inc_subject) except ValueError as _: return self.add_subject(inc_subject) self.subjects[index] = inc_subject return True
[ "def", "update_subject", "(", "self", ",", "inc_subject", ")", ":", "try", ":", "# pylint: disable=no-member", "index", "=", "self", ".", "subjects", ".", "index", "(", "inc_subject", ")", "except", "ValueError", "as", "_", ":", "return", "self", ".", "add_s...
https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/openshift/installer/vendored/openshift-ansible-3.10.0-0.29.0/roles/lib_vendored_deps/library/oc_adm_policy_group.py#L1669-L1679
nosmokingbandit/Watcher3
0217e75158b563bdefc8e01c3be7620008cf3977
lib/infi/pkg_resources/_vendor/packaging/specifiers.py
python
BaseSpecifier.__hash__
(self)
Returns a hash value for this Specifier like object.
Returns a hash value for this Specifier like object.
[ "Returns", "a", "hash", "value", "for", "this", "Specifier", "like", "object", "." ]
def __hash__(self): """ Returns a hash value for this Specifier like object. """
[ "def", "__hash__", "(", "self", ")", ":" ]
https://github.com/nosmokingbandit/Watcher3/blob/0217e75158b563bdefc8e01c3be7620008cf3977/lib/infi/pkg_resources/_vendor/packaging/specifiers.py#L31-L34
OpenNMT/OpenNMT-py
4815f07fcd482af9a1fe1d3b620d144197178bc5
onmt/transforms/misc.py
python
FilterTooLongStats.update
(self, other: "FilterTooLongStats")
[]
def update(self, other: "FilterTooLongStats"): self.filtered += other.filtered
[ "def", "update", "(", "self", ",", "other", ":", "\"FilterTooLongStats\"", ")", ":", "self", ".", "filtered", "+=", "other", ".", "filtered" ]
https://github.com/OpenNMT/OpenNMT-py/blob/4815f07fcd482af9a1fe1d3b620d144197178bc5/onmt/transforms/misc.py#L13-L14
holzschu/Carnets
44effb10ddfc6aa5c8b0687582a724ba82c6b547
Library/lib/python3.7/site-packages/docutils/utils/math/math2html.py
python
Trace.show
(cls, message, channel)
Show a message out of a channel
Show a message out of a channel
[ "Show", "a", "message", "out", "of", "a", "channel" ]
def show(cls, message, channel): "Show a message out of a channel" if sys.version_info < (3,0): message = message.encode('utf-8') channel.write(message + '\n')
[ "def", "show", "(", "cls", ",", "message", ",", "channel", ")", ":", "if", "sys", ".", "version_info", "<", "(", "3", ",", "0", ")", ":", "message", "=", "message", ".", "encode", "(", "'utf-8'", ")", "channel", ".", "write", "(", "message", "+", ...
https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/docutils/utils/math/math2html.py#L63-L67
apple/ccs-calendarserver
13c706b985fb728b9aab42dc0fef85aae21921c3
txdav/common/datastore/sql.py
python
CommonHome.initMetaDataFromStore
(self)
Load up the metadata and property store
Load up the metadata and property store
[ "Load", "up", "the", "metadata", "and", "property", "store" ]
def initMetaDataFromStore(self): """ Load up the metadata and property store """ queryCacher = self._txn._queryCacher if queryCacher: # Get cached copy cacheKey = queryCacher.keyForHomeMetaData(self._resourceID) data = yield queryCacher.get(cacheKey) else: data = None if data is None: # Don't have a cached copy data = (yield self._metaDataQuery.on(self._txn, resourceID=self._resourceID))[0] if queryCacher: # Cache the data yield queryCacher.setAfterCommit(self._txn, cacheKey, data) for attr, value in zip(self.metadataAttributes(), data): setattr(self, attr, value) self._created = parseSQLTimestamp(self._created) self._modified = parseSQLTimestamp(self._modified)
[ "def", "initMetaDataFromStore", "(", "self", ")", ":", "queryCacher", "=", "self", ".", "_txn", ".", "_queryCacher", "if", "queryCacher", ":", "# Get cached copy", "cacheKey", "=", "queryCacher", ".", "keyForHomeMetaData", "(", "self", ".", "_resourceID", ")", "...
https://github.com/apple/ccs-calendarserver/blob/13c706b985fb728b9aab42dc0fef85aae21921c3/txdav/common/datastore/sql.py#L1660-L1682
balanced/status.balancedpayments.com
e51a371079a8fa215732be3cfa57497a9d113d35
venv/lib/python2.7/site-packages/httplib2/socks.py
python
socksocket.__recvall
(self, count)
return data
__recvall(count) -> data Receive EXACTLY the number of bytes requested from the socket. Blocks until the required number of bytes have been received.
__recvall(count) -> data Receive EXACTLY the number of bytes requested from the socket. Blocks until the required number of bytes have been received.
[ "__recvall", "(", "count", ")", "-", ">", "data", "Receive", "EXACTLY", "the", "number", "of", "bytes", "requested", "from", "the", "socket", ".", "Blocks", "until", "the", "required", "number", "of", "bytes", "have", "been", "received", "." ]
def __recvall(self, count): """__recvall(count) -> data Receive EXACTLY the number of bytes requested from the socket. Blocks until the required number of bytes have been received. """ data = self.recv(count) while len(data) < count: d = self.recv(count-len(data)) if not d: raise GeneralProxyError((0, "connection closed unexpectedly")) data = data + d return data
[ "def", "__recvall", "(", "self", ",", "count", ")", ":", "data", "=", "self", ".", "recv", "(", "count", ")", "while", "len", "(", "data", ")", "<", "count", ":", "d", "=", "self", ".", "recv", "(", "count", "-", "len", "(", "data", ")", ")", ...
https://github.com/balanced/status.balancedpayments.com/blob/e51a371079a8fa215732be3cfa57497a9d113d35/venv/lib/python2.7/site-packages/httplib2/socks.py#L133-L143
OpenNMT/OpenNMT-py
4815f07fcd482af9a1fe1d3b620d144197178bc5
onmt/models/model.py
python
LanguageModel.__init__
(self, encoder=None, decoder=None)
[]
def __init__(self, encoder=None, decoder=None): super(LanguageModel, self).__init__(encoder, decoder) if encoder is not None: raise ValueError("LanguageModel should not be used" "with an encoder") self.decoder = decoder
[ "def", "__init__", "(", "self", ",", "encoder", "=", "None", ",", "decoder", "=", "None", ")", ":", "super", "(", "LanguageModel", ",", "self", ")", ".", "__init__", "(", "encoder", ",", "decoder", ")", "if", "encoder", "is", "not", "None", ":", "rai...
https://github.com/OpenNMT/OpenNMT-py/blob/4815f07fcd482af9a1fe1d3b620d144197178bc5/onmt/models/model.py#L107-L112
aws-samples/aws-kube-codesuite
ab4e5ce45416b83bffb947ab8d234df5437f4fca
src/click/core.py
python
Parameter.process_value
(self, ctx, value)
Given a value and context this runs the logic to convert the value as necessary.
Given a value and context this runs the logic to convert the value as necessary.
[ "Given", "a", "value", "and", "context", "this", "runs", "the", "logic", "to", "convert", "the", "value", "as", "necessary", "." ]
def process_value(self, ctx, value): """Given a value and context this runs the logic to convert the value as necessary. """ # If the value we were given is None we do nothing. This way # code that calls this can easily figure out if something was # not provided. Otherwise it would be converted into an empty # tuple for multiple invocations which is inconvenient. if value is not None: return self.type_cast_value(ctx, value)
[ "def", "process_value", "(", "self", ",", "ctx", ",", "value", ")", ":", "# If the value we were given is None we do nothing. This way", "# code that calls this can easily figure out if something was", "# not provided. Otherwise it would be converted into an empty", "# tuple for multiple...
https://github.com/aws-samples/aws-kube-codesuite/blob/ab4e5ce45416b83bffb947ab8d234df5437f4fca/src/click/core.py#L1346-L1355
GNS3/gns3-server
aff06572d4173df945ad29ea8feb274f7885d9e4
gns3server/controller/topology.py
python
_convert_2_0_0
(topo, topo_path)
return topo
Convert topologies from GNS3 2.0.0 to 2.1 Changes: * Remove startup_script_path from VPCS and base config file for IOU and Dynamips
Convert topologies from GNS3 2.0.0 to 2.1
[ "Convert", "topologies", "from", "GNS3", "2", ".", "0", ".", "0", "to", "2", ".", "1" ]
def _convert_2_0_0(topo, topo_path): """ Convert topologies from GNS3 2.0.0 to 2.1 Changes: * Remove startup_script_path from VPCS and base config file for IOU and Dynamips """ topo["revision"] = 8 for node in topo.get("topology", {}).get("nodes", []): if "properties" in node: if node["node_type"] == "vpcs": if "startup_script_path" in node["properties"]: del node["properties"]["startup_script_path"] if "startup_script" in node["properties"]: del node["properties"]["startup_script"] elif node["node_type"] == "dynamips" or node["node_type"] == "iou": if "startup_config" in node["properties"]: del node["properties"]["startup_config"] if "private_config" in node["properties"]: del node["properties"]["private_config"] if "startup_config_content" in node["properties"]: del node["properties"]["startup_config_content"] if "private_config_content" in node["properties"]: del node["properties"]["private_config_content"] return topo
[ "def", "_convert_2_0_0", "(", "topo", ",", "topo_path", ")", ":", "topo", "[", "\"revision\"", "]", "=", "8", "for", "node", "in", "topo", ".", "get", "(", "\"topology\"", ",", "{", "}", ")", ".", "get", "(", "\"nodes\"", ",", "[", "]", ")", ":", ...
https://github.com/GNS3/gns3-server/blob/aff06572d4173df945ad29ea8feb274f7885d9e4/gns3server/controller/topology.py#L235-L260
entropy1337/infernal-twin
10995cd03312e39a48ade0f114ebb0ae3a711bb8
Modules/build/pip/build/lib.linux-i686-2.7/pip/_vendor/distlib/_backport/tarfile.py
python
TarInfo._proc_gnusparse_01
(self, next, pax_headers)
Process a GNU tar extended sparse header, version 0.1.
Process a GNU tar extended sparse header, version 0.1.
[ "Process", "a", "GNU", "tar", "extended", "sparse", "header", "version", "0", ".", "1", "." ]
def _proc_gnusparse_01(self, next, pax_headers): """Process a GNU tar extended sparse header, version 0.1. """ sparse = [int(x) for x in pax_headers["GNU.sparse.map"].split(",")] next.sparse = list(zip(sparse[::2], sparse[1::2]))
[ "def", "_proc_gnusparse_01", "(", "self", ",", "next", ",", "pax_headers", ")", ":", "sparse", "=", "[", "int", "(", "x", ")", "for", "x", "in", "pax_headers", "[", "\"GNU.sparse.map\"", "]", ".", "split", "(", "\",\"", ")", "]", "next", ".", "sparse",...
https://github.com/entropy1337/infernal-twin/blob/10995cd03312e39a48ade0f114ebb0ae3a711bb8/Modules/build/pip/build/lib.linux-i686-2.7/pip/_vendor/distlib/_backport/tarfile.py#L1496-L1500
Billwilliams1952/PiCameraApp
61802b367d620aafb6b4e0bb84ea1ebd0dbd42c0
Source/Tooltip.py
python
ToolTip.hide
( self, event=None )
Hides the ToolTip. Usually this is caused by leaving the widget Arguments: event: The event that called this function
Hides the ToolTip. Usually this is caused by leaving the widget Arguments: event: The event that called this function
[ "Hides", "the", "ToolTip", ".", "Usually", "this", "is", "caused", "by", "leaving", "the", "widget", "Arguments", ":", "event", ":", "The", "event", "that", "called", "this", "function" ]
def hide( self, event=None ): """ Hides the ToolTip. Usually this is caused by leaving the widget Arguments: event: The event that called this function """ self.visible = 0 self.withdraw()
[ "def", "hide", "(", "self", ",", "event", "=", "None", ")", ":", "self", ".", "visible", "=", "0", "self", ".", "withdraw", "(", ")" ]
https://github.com/Billwilliams1952/PiCameraApp/blob/61802b367d620aafb6b4e0bb84ea1ebd0dbd42c0/Source/Tooltip.py#L199-L206
cylc/cylc-flow
5ec221143476c7c616c156b74158edfbcd83794a
cylc/flow/exceptions.py
python
PlatformError.__str__
(self)
return ret
[]
def __str__(self): # matches cylc.flow.platforms.log_platform_event format if self.platform_name: ret = f'platform: {self.platform_name} - {self.msg}' else: ret = f'{self.msg}' for label, item in [ ('COMMAND', self.cmd), ('RETURN CODE', self.ret_code), ('STDOUT', self.out), ('STDERR', self.err) ]: if item is not None: ret += f'\n{label}:' for line in str(item).splitlines(True): # keep newline chars ret += f"\n {line}" return ret
[ "def", "__str__", "(", "self", ")", ":", "# matches cylc.flow.platforms.log_platform_event format", "if", "self", ".", "platform_name", ":", "ret", "=", "f'platform: {self.platform_name} - {self.msg}'", "else", ":", "ret", "=", "f'{self.msg}'", "for", "label", ",", "ite...
https://github.com/cylc/cylc-flow/blob/5ec221143476c7c616c156b74158edfbcd83794a/cylc/flow/exceptions.py#L203-L219
bjmayor/hacker
e3ce2ad74839c2733b27dac6c0f495e0743e1866
venv/lib/python3.5/site-packages/PIL/Hdf5StubImagePlugin.py
python
register_handler
(handler)
Install application-specific HDF5 image handler. :param handler: Handler object.
Install application-specific HDF5 image handler.
[ "Install", "application", "-", "specific", "HDF5", "image", "handler", "." ]
def register_handler(handler): """ Install application-specific HDF5 image handler. :param handler: Handler object. """ global _handler _handler = handler
[ "def", "register_handler", "(", "handler", ")", ":", "global", "_handler", "_handler", "=", "handler" ]
https://github.com/bjmayor/hacker/blob/e3ce2ad74839c2733b27dac6c0f495e0743e1866/venv/lib/python3.5/site-packages/PIL/Hdf5StubImagePlugin.py#L17-L24
sharppy/SHARPpy
19175269ab11fe06c917b5d10376862a4716e1db
sharppy/viz/analogues.py
python
plotAnalogues.clearData
(self)
Handles the clearing of the pixmap in the frame.
Handles the clearing of the pixmap in the frame.
[ "Handles", "the", "clearing", "of", "the", "pixmap", "in", "the", "frame", "." ]
def clearData(self): ''' Handles the clearing of the pixmap in the frame. ''' self.plotBitMap = QtGui.QPixmap(self.width(), self.height()) self.plotBitMap.fill(self.bg_color)
[ "def", "clearData", "(", "self", ")", ":", "self", ".", "plotBitMap", "=", "QtGui", ".", "QPixmap", "(", "self", ".", "width", "(", ")", ",", "self", ".", "height", "(", ")", ")", "self", ".", "plotBitMap", ".", "fill", "(", "self", ".", "bg_color"...
https://github.com/sharppy/SHARPpy/blob/19175269ab11fe06c917b5d10376862a4716e1db/sharppy/viz/analogues.py#L286-L292
evanbrumley/django-report-tools
3347705c6f7880a9766ac827ff7575e5a0b5bcb7
report_tools/renderers/googlecharts/__init__.py
python
GoogleChartsDataConverter.convert_standard_chartdata_to_datatable_json
(cls, data)
return cls.convert_generic_to_datatable_json(data)
Converts a ChartData object to a datatable json blob assuming that the first column is a label and all subsequent columns are numbers
Converts a ChartData object to a datatable json blob assuming that the first column is a label and all subsequent columns are numbers
[ "Converts", "a", "ChartData", "object", "to", "a", "datatable", "json", "blob", "assuming", "that", "the", "first", "column", "is", "a", "label", "and", "all", "subsequent", "columns", "are", "numbers" ]
def convert_standard_chartdata_to_datatable_json(cls, data): """ Converts a ChartData object to a datatable json blob assuming that the first column is a label and all subsequent columns are numbers """ cols = data.get_columns() label_col = cols[0] data_cols = cols[1:] if 'datatype' not in label_col.metadata: label_col.metadata['datatype'] = 'string' for col in data_cols: if 'datatype' not in col.metadata: col.metadata['datatype'] = 'number' return cls.convert_generic_to_datatable_json(data)
[ "def", "convert_standard_chartdata_to_datatable_json", "(", "cls", ",", "data", ")", ":", "cols", "=", "data", ".", "get_columns", "(", ")", "label_col", "=", "cols", "[", "0", "]", "data_cols", "=", "cols", "[", "1", ":", "]", "if", "'datatype'", "not", ...
https://github.com/evanbrumley/django-report-tools/blob/3347705c6f7880a9766ac827ff7575e5a0b5bcb7/report_tools/renderers/googlecharts/__init__.py#L108-L125
xhtml2pdf/xhtml2pdf
3eef378f869e951448bbf95b7be475f22b659dae
xhtml2pdf/reportlab_paragraph.py
python
_drawBullet
(canvas, offset, cur_y, bulletText, style)
return offset
draw a bullet text could be a simple string or a frag list
draw a bullet text could be a simple string or a frag list
[ "draw", "a", "bullet", "text", "could", "be", "a", "simple", "string", "or", "a", "frag", "list" ]
def _drawBullet(canvas, offset, cur_y, bulletText, style): """ draw a bullet text could be a simple string or a frag list """ tx2 = canvas.beginText(style.bulletIndent, cur_y + getattr(style, "bulletOffsetY", 0)) tx2.setFont(style.bulletFontName, style.bulletFontSize) tx2.setFillColor(hasattr(style, 'bulletColor') and style.bulletColor or style.textColor) if isinstance(bulletText, basestring): tx2.textOut(bulletText) else: for f in bulletText: if hasattr(f, "image"): image = f.image width = image.drawWidth height = image.drawHeight gap = style.bulletFontSize * 0.25 img = image.getImage() # print style.bulletIndent, offset, width canvas.drawImage( img, style.leftIndent - width - gap, cur_y + getattr(style, "bulletOffsetY", 0), width, height) else: tx2.setFont(f.fontName, f.fontSize) tx2.setFillColor(f.textColor) tx2.textOut(f.text) canvas.drawText(tx2) #AR making definition lists a bit less ugly #bulletEnd = tx2.getX() bulletEnd = tx2.getX() + style.bulletFontSize * 0.6 offset = max(offset, bulletEnd - style.leftIndent) return offset
[ "def", "_drawBullet", "(", "canvas", ",", "offset", ",", "cur_y", ",", "bulletText", ",", "style", ")", ":", "tx2", "=", "canvas", ".", "beginText", "(", "style", ".", "bulletIndent", ",", "cur_y", "+", "getattr", "(", "style", ",", "\"bulletOffsetY\"", ...
https://github.com/xhtml2pdf/xhtml2pdf/blob/3eef378f869e951448bbf95b7be475f22b659dae/xhtml2pdf/reportlab_paragraph.py#L534-L568
saltstack/salt
fae5bc757ad0f1716483ce7ae180b451545c2058
salt/modules/vagrant.py
python
list_inactive_vms
(cwd=None)
return vms
Return a list of machine names for inactive virtual machine on the host, which are defined in the Vagrantfile at the indicated path. CLI Example: .. code-block:: bash salt '*' virt.list_inactive_vms cwd=/projects/project_1
Return a list of machine names for inactive virtual machine on the host, which are defined in the Vagrantfile at the indicated path.
[ "Return", "a", "list", "of", "machine", "names", "for", "inactive", "virtual", "machine", "on", "the", "host", "which", "are", "defined", "in", "the", "Vagrantfile", "at", "the", "indicated", "path", "." ]
def list_inactive_vms(cwd=None): """ Return a list of machine names for inactive virtual machine on the host, which are defined in the Vagrantfile at the indicated path. CLI Example: .. code-block:: bash salt '*' virt.list_inactive_vms cwd=/projects/project_1 """ vms = [] cmd = "vagrant status" reply = __salt__["cmd.shell"](cmd, cwd=cwd) log.info("--->\n%s", reply) for line in reply.split("\n"): # build a list of the text reply tokens = line.strip().split() if len(tokens) > 1 and tokens[-1].endswith(")"): if tokens[1] != "running": vms.append(tokens[0]) return vms
[ "def", "list_inactive_vms", "(", "cwd", "=", "None", ")", ":", "vms", "=", "[", "]", "cmd", "=", "\"vagrant status\"", "reply", "=", "__salt__", "[", "\"cmd.shell\"", "]", "(", "cmd", ",", "cwd", "=", "cwd", ")", "log", ".", "info", "(", "\"--->\\n%s\"...
https://github.com/saltstack/salt/blob/fae5bc757ad0f1716483ce7ae180b451545c2058/salt/modules/vagrant.py#L247-L267
eleurent/highway-env
9d63973da854584fe51b00ccee7b24b1bf031418
highway_env/interval.py
python
integrator_interval
(x: Interval, k: Interval)
return interval_gain*x
Compute the interval of an integrator system: dx = -k*x :param x: state interval :param k: gain interval, must be positive :return: interval for dx
Compute the interval of an integrator system: dx = -k*x
[ "Compute", "the", "interval", "of", "an", "integrator", "system", ":", "dx", "=", "-", "k", "*", "x" ]
def integrator_interval(x: Interval, k: Interval) -> np.ndarray: """ Compute the interval of an integrator system: dx = -k*x :param x: state interval :param k: gain interval, must be positive :return: interval for dx """ if x[0] >= 0: interval_gain = np.flip(-k, 0) elif x[1] <= 0: interval_gain = -k else: interval_gain = -np.array([k[0], k[0]]) return interval_gain*x
[ "def", "integrator_interval", "(", "x", ":", "Interval", ",", "k", ":", "Interval", ")", "->", "np", ".", "ndarray", ":", "if", "x", "[", "0", "]", ">=", "0", ":", "interval_gain", "=", "np", ".", "flip", "(", "-", "k", ",", "0", ")", "elif", "...
https://github.com/eleurent/highway-env/blob/9d63973da854584fe51b00ccee7b24b1bf031418/highway_env/interval.py#L62-L77
buke/GreenOdoo
3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df
runtime/python/lib/python2.7/imaplib.py
python
IMAP4.setannotation
(self, *args)
return self._untagged_response(typ, dat, 'ANNOTATION')
(typ, [data]) = <instance>.setannotation(mailbox[, entry, attribute]+) Set ANNOTATIONs.
(typ, [data]) = <instance>.setannotation(mailbox[, entry, attribute]+) Set ANNOTATIONs.
[ "(", "typ", "[", "data", "]", ")", "=", "<instance", ">", ".", "setannotation", "(", "mailbox", "[", "entry", "attribute", "]", "+", ")", "Set", "ANNOTATIONs", "." ]
def setannotation(self, *args): """(typ, [data]) = <instance>.setannotation(mailbox[, entry, attribute]+) Set ANNOTATIONs.""" typ, dat = self._simple_command('SETANNOTATION', *args) return self._untagged_response(typ, dat, 'ANNOTATION')
[ "def", "setannotation", "(", "self", ",", "*", "args", ")", ":", "typ", ",", "dat", "=", "self", ".", "_simple_command", "(", "'SETANNOTATION'", ",", "*", "args", ")", "return", "self", ".", "_untagged_response", "(", "typ", ",", "dat", ",", "'ANNOTATION...
https://github.com/buke/GreenOdoo/blob/3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df/runtime/python/lib/python2.7/imaplib.py#L671-L676
nats-io/nats.py
49635bf58b1c888c66fa37569a9248b1a83a6c0a
nats/aio/client.py
python
Client._attempt_reconnect
(self)
[]
async def _attempt_reconnect(self): if self._reading_task is not None and not self._reading_task.cancelled( ): self._reading_task.cancel() if self._ping_interval_task is not None and not self._ping_interval_task.cancelled( ): self._ping_interval_task.cancel() if self._flusher_task is not None and not self._flusher_task.cancelled( ): self._flusher_task.cancel() if self._io_writer is not None: self._io_writer.close() try: await self._io_writer.wait_closed() except Exception as e: await self._error_cb(e) self._err = None if self._disconnected_cb is not None: await self._disconnected_cb() if self.is_closed: return if "dont_randomize" not in self.options or not self.options[ "dont_randomize"]: shuffle(self._server_pool) # Create a future that the client can use to control waiting # on the reconnection attempts. self._reconnection_task_future = asyncio.Future() while True: try: # Try to establish a TCP connection to a server in # the cluster then send CONNECT command to it. await self._select_next_server() await self._process_connect_init() # Consider a reconnect to be done once CONNECT was # processed by the server successfully. self.stats["reconnects"] += 1 # Reset reconnect attempts for this server # since have successfully connected. self._current_server.did_connect = True self._current_server.reconnects = 0 # Replay all the subscriptions in case there were some. subs_to_remove = [] for sid, sub in self._subs.items(): max_msgs = 0 if sub._max_msgs > 0: # If we already hit the message limit, remove the subscription and don't resubscribe if sub._received >= sub._max_msgs: subs_to_remove.append(sid) continue # auto unsubscribe the number of messages we have left max_msgs = sub._max_msgs - sub._received sub_cmd = prot_command.sub_cmd( sub._subject, sub._queue, sid ) self._io_writer.write(sub_cmd) if max_msgs > 0: unsub_cmd = prot_command.unsub_cmd(sid, max_msgs) self._io_writer.write(unsub_cmd) for sid in subs_to_remove: self._subs.pop(sid) await self._io_writer.drain() # Flush pending data before continuing in connected status. # FIXME: Could use future here and wait for an error result # to bail earlier in case there are errors in the connection. await self._flush_pending() self._status = Client.CONNECTED await self.flush() if self._reconnected_cb is not None: await self._reconnected_cb() self._reconnection_task_future = None break except nats.errors.NoServersError as e: self._err = e await self.close() break except (OSError, Error, TimeoutError) as e: self._err = e await self._error_cb(e) self._status = Client.RECONNECTING self._current_server.last_attempt = time.monotonic() self._current_server.reconnects += 1 except asyncio.CancelledError: break if self._reconnection_task_future is not None and not self._reconnection_task_future.cancelled( ): self._reconnection_task_future.set_result(True)
[ "async", "def", "_attempt_reconnect", "(", "self", ")", ":", "if", "self", ".", "_reading_task", "is", "not", "None", "and", "not", "self", ".", "_reading_task", ".", "cancelled", "(", ")", ":", "self", ".", "_reading_task", ".", "cancel", "(", ")", "if"...
https://github.com/nats-io/nats.py/blob/49635bf58b1c888c66fa37569a9248b1a83a6c0a/nats/aio/client.py#L1168-L1269
veusz/veusz
5a1e2af5f24df0eb2a2842be51f2997c4999c7fb
veusz/widgets/axis.py
python
Axis.addSettings
(klass, s)
Construct list of settings.
Construct list of settings.
[ "Construct", "list", "of", "settings", "." ]
def addSettings(klass, s): """Construct list of settings.""" widget.Widget.addSettings(s) s.add( setting.Str( 'label', '', descr=_('Axis label text'), usertext=_('Label')) ) s.add( setting.AxisBound( 'min', 'Auto', descr=_('Minimum value of axis'), usertext=_('Min')) ) s.add( setting.AxisBound( 'max', 'Auto', descr=_('Maximum value of axis'), usertext=_('Max')) ) s.add( setting.Bool( 'log', False, descr=_('Whether axis is logarithmic'), usertext=_('Log')) ) s.add( AutoRange( 'autoRange', 'next-tick') ) s.add( setting.Choice( 'mode', ('numeric', 'datetime', 'labels'), 'numeric', descr=_('Type of ticks to show on on axis'), usertext=_('Mode')) ) s.add( setting.SettingBackwardCompat( 'autoExtend', 'autoRange', True, translatefn = lambda x: ('exact', 'next-tick')[x], formatting=True ) ) # this setting no longer used s.add( setting.Bool( 'autoExtendZero', True, descr=_('Extend axis to zero if close (UNUSED)'), usertext=_('Zero extend'), hidden=True, formatting=True) ) s.add( setting.Bool( 'autoMirror', True, descr=_('Place axis on opposite side of graph if none'), usertext=_('Auto mirror'), formatting=True) ) s.add( setting.Bool( 'reflect', False, descr=_('Place axis text and ticks on other side of axis'), usertext=_('Reflect'), formatting=True) ) s.add( setting.Bool( 'outerticks', False, descr=_('Place ticks on outside of graph'), usertext=_('Outer ticks'), formatting=True) ) s.add( setting.Float( 'datascale', 1., descr=_('Scale data plotted by this factor'), usertext=_('Scale')) ) s.add( setting.Choice( 'direction', ['horizontal', 'vertical'], 'horizontal', descr=_('Direction of axis'), usertext=_('Direction')) ) s.add( setting.Float( 'lowerPosition', 0., descr=_('Fractional position of lower end of axis on graph'), usertext=_('Min position')) ) s.add( setting.Float( 'upperPosition', 1., descr=_('Fractional position of upper end of axis on graph'), usertext=_('Max position')) ) s.add( setting.Float( 'otherPosition', 0., descr=_('Fractional position of axis in its perpendicular direction'), usertext=_('Axis position')) ) s.add( setting.WidgetPath( 'match', '', descr=_('Match the scale of this axis to the axis specified'), usertext=_('Match'), allowedwidgets=[Axis] )) s.add( setting.Line( 'Line', descr=_('Axis line settings'), usertext=_('Axis line')), pixmap='settings_axisline' ) s.add( AxisLabel( 'Label', descr=_('Axis label settings'), usertext=_('Axis label')), pixmap='settings_axislabel' ) s.add( TickLabel( 'TickLabels', descr=_('Tick label settings'), usertext=_('Tick labels')), pixmap='settings_axisticklabels' ) s.add( MajorTick( 'MajorTicks', descr=_('Major tick line settings'), usertext=_('Major ticks')), pixmap='settings_axismajorticks' ) s.add( MinorTick( 'MinorTicks', descr=_('Minor tick line settings'), usertext=_('Minor ticks')), pixmap='settings_axisminorticks' ) s.add( GridLine( 'GridLines', descr=_('Grid line settings'), usertext=_('Grid lines')), pixmap='settings_axisgridlines' ) s.add( MinorGridLine( 'MinorGridLines', descr=_('Minor grid line settings'), usertext=_('Grid lines for minor ticks')), pixmap='settings_axisminorgridlines' )
[ "def", "addSettings", "(", "klass", ",", "s", ")", ":", "widget", ".", "Widget", ".", "addSettings", "(", "s", ")", "s", ".", "add", "(", "setting", ".", "Str", "(", "'label'", ",", "''", ",", "descr", "=", "_", "(", "'Axis label text'", ")", ",", ...
https://github.com/veusz/veusz/blob/5a1e2af5f24df0eb2a2842be51f2997c4999c7fb/veusz/widgets/axis.py#L356-L477
google/grr
8ad8a4d2c5a93c92729206b7771af19d92d4f915
grr/client/grr_response_client/unprivileged/filesystem/tsk.py
python
_GetDataStream
(fd: pytsk3.File, stream_name: Optional[str])
[]
def _GetDataStream(fd: pytsk3.File, stream_name: Optional[str]) -> Optional[pytsk3.Attribute]: if stream_name is None: return None for attribute in fd: if (attribute.info.name is not None and _DecodeName(attribute.info.name) == stream_name and attribute.info.type == pytsk3.TSK_FS_ATTR_TYPE_NTFS_DATA): return attribute raise IOError(f"Failed to open data stream {stream_name}.")
[ "def", "_GetDataStream", "(", "fd", ":", "pytsk3", ".", "File", ",", "stream_name", ":", "Optional", "[", "str", "]", ")", "->", "Optional", "[", "pytsk3", ".", "Attribute", "]", ":", "if", "stream_name", "is", "None", ":", "return", "None", "for", "at...
https://github.com/google/grr/blob/8ad8a4d2c5a93c92729206b7771af19d92d4f915/grr/client/grr_response_client/unprivileged/filesystem/tsk.py#L265-L274
AppScale/gts
46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9
AppServer/google/appengine/ext/db/djangoforms.py
python
_ReverseReferenceProperty.get_form_field
(self, **kwargs)
return None
Return a Django form field appropriate for a reverse reference. This always returns None, since reverse references are always automatic.
Return a Django form field appropriate for a reverse reference.
[ "Return", "a", "Django", "form", "field", "appropriate", "for", "a", "reverse", "reference", "." ]
def get_form_field(self, **kwargs): """Return a Django form field appropriate for a reverse reference. This always returns None, since reverse references are always automatic. """ return None
[ "def", "get_form_field", "(", "self", ",", "*", "*", "kwargs", ")", ":", "return", "None" ]
https://github.com/AppScale/gts/blob/46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9/AppServer/google/appengine/ext/db/djangoforms.py#L650-L656
naftaliharris/tauthon
5587ceec329b75f7caf6d65a036db61ac1bae214
Lib/numbers.py
python
Real.__rmod__
(self, other)
other % self
other % self
[ "other", "%", "self" ]
def __rmod__(self, other): """other % self""" raise NotImplementedError
[ "def", "__rmod__", "(", "self", ",", "other", ")", ":", "raise", "NotImplementedError" ]
https://github.com/naftaliharris/tauthon/blob/5587ceec329b75f7caf6d65a036db61ac1bae214/Lib/numbers.py#L232-L234
Azure/azure-devops-cli-extension
11334cd55806bef0b99c3bee5a438eed71e44037
azure-devops/azext_devops/devops_sdk/v6_0/member_entitlement_management/member_entitlement_management_client.py
python
MemberEntitlementManagementClient.get_user_entitlement
(self, user_id)
return self._deserialize('UserEntitlement', response)
GetUserEntitlement. [Preview API] Get User Entitlement for a user. :param str user_id: ID of the user. :rtype: :class:`<UserEntitlement> <azure.devops.v6_0.member_entitlement_management.models.UserEntitlement>`
GetUserEntitlement. [Preview API] Get User Entitlement for a user. :param str user_id: ID of the user. :rtype: :class:`<UserEntitlement> <azure.devops.v6_0.member_entitlement_management.models.UserEntitlement>`
[ "GetUserEntitlement", ".", "[", "Preview", "API", "]", "Get", "User", "Entitlement", "for", "a", "user", ".", ":", "param", "str", "user_id", ":", "ID", "of", "the", "user", ".", ":", "rtype", ":", ":", "class", ":", "<UserEntitlement", ">", "<azure", ...
def get_user_entitlement(self, user_id): """GetUserEntitlement. [Preview API] Get User Entitlement for a user. :param str user_id: ID of the user. :rtype: :class:`<UserEntitlement> <azure.devops.v6_0.member_entitlement_management.models.UserEntitlement>` """ route_values = {} if user_id is not None: route_values['userId'] = self._serialize.url('user_id', user_id, 'str') response = self._send(http_method='GET', location_id='8480c6eb-ce60-47e9-88df-eca3c801638b', version='6.0-preview.3', route_values=route_values) return self._deserialize('UserEntitlement', response)
[ "def", "get_user_entitlement", "(", "self", ",", "user_id", ")", ":", "route_values", "=", "{", "}", "if", "user_id", "is", "not", "None", ":", "route_values", "[", "'userId'", "]", "=", "self", ".", "_serialize", ".", "url", "(", "'user_id'", ",", "user...
https://github.com/Azure/azure-devops-cli-extension/blob/11334cd55806bef0b99c3bee5a438eed71e44037/azure-devops/azext_devops/devops_sdk/v6_0/member_entitlement_management/member_entitlement_management_client.py#L242-L255