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
pyfa-org/Pyfa
feaa52c36beeda21ab380fc74d8f871b81d49729
service/market.py
python
Market.getShipListDelayed
(self, id_, callback)
Background version of getShipList
Background version of getShipList
[ "Background", "version", "of", "getShipList" ]
def getShipListDelayed(self, id_, callback): """Background version of getShipList""" self.shipBrowserWorkerThread.queue.put((id_, callback))
[ "def", "getShipListDelayed", "(", "self", ",", "id_", ",", "callback", ")", ":", "self", ".", "shipBrowserWorkerThread", ".", "queue", ".", "put", "(", "(", "id_", ",", "callback", ")", ")" ]
https://github.com/pyfa-org/Pyfa/blob/feaa52c36beeda21ab380fc74d8f871b81d49729/service/market.py#L867-L869
joerick/pyinstrument
d3c45164a385021f366c1081baec18a1a226a573
pyinstrument/util.py
python
file_is_a_tty
(file_obj: IO)
return hasattr(file_obj, "isatty") and file_obj.isatty()
[]
def file_is_a_tty(file_obj: IO) -> bool: return hasattr(file_obj, "isatty") and file_obj.isatty()
[ "def", "file_is_a_tty", "(", "file_obj", ":", "IO", ")", "->", "bool", ":", "return", "hasattr", "(", "file_obj", ",", "\"isatty\"", ")", "and", "file_obj", ".", "isatty", "(", ")" ]
https://github.com/joerick/pyinstrument/blob/d3c45164a385021f366c1081baec18a1a226a573/pyinstrument/util.py#L78-L79
Rapptz/discord.py
45d498c1b76deaf3b394d17ccf56112fa691d160
discord/ext/tasks/__init__.py
python
Loop.seconds
(self)
Optional[:class:`float`]: Read-only value for the number of seconds between each iteration. ``None`` if an explicit ``time`` value was passed instead. .. versionadded:: 2.0
Optional[:class:`float`]: Read-only value for the number of seconds between each iteration. ``None`` if an explicit ``time`` value was passed instead.
[ "Optional", "[", ":", "class", ":", "float", "]", ":", "Read", "-", "only", "value", "for", "the", "number", "of", "seconds", "between", "each", "iteration", ".", "None", "if", "an", "explicit", "time", "value", "was", "passed", "instead", "." ]
def seconds(self) -> Optional[float]: """Optional[:class:`float`]: Read-only value for the number of seconds between each iteration. ``None`` if an explicit ``time`` value was passed instead. .. versionadded:: 2.0 """ if self._seconds is not MISSING: return self._seconds
[ "def", "seconds", "(", "self", ")", "->", "Optional", "[", "float", "]", ":", "if", "self", ".", "_seconds", "is", "not", "MISSING", ":", "return", "self", ".", "_seconds" ]
https://github.com/Rapptz/discord.py/blob/45d498c1b76deaf3b394d17ccf56112fa691d160/discord/ext/tasks/__init__.py#L228-L235
issackelly/wemo
d6c1f502015d21b19fa7e518fe84b697cf58ec3d
wemo.py
python
off
()
return True if tagValue in ['0', 'Error'] else False
Turns off the first switch that it finds. BinaryState is set to 'Error' in the case that it was already off.
Turns off the first switch that it finds.
[ "Turns", "off", "the", "first", "switch", "that", "it", "finds", "." ]
def off(): """ Turns off the first switch that it finds. BinaryState is set to 'Error' in the case that it was already off. """ resp = _send('SetBinaryState', {'BinaryState': (0, 'Boolean')}) tagValue = conn.extractSingleTag(resp, 'BinaryState') return True if tagValue in ['0', 'Error'] else False
[ "def", "off", "(", ")", ":", "resp", "=", "_send", "(", "'SetBinaryState'", ",", "{", "'BinaryState'", ":", "(", "0", ",", "'Boolean'", ")", "}", ")", "tagValue", "=", "conn", ".", "extractSingleTag", "(", "resp", ",", "'BinaryState'", ")", "return", "...
https://github.com/issackelly/wemo/blob/d6c1f502015d21b19fa7e518fe84b697cf58ec3d/wemo.py#L63-L71
securesystemslab/zippy
ff0e84ac99442c2c55fe1d285332cfd4e185e089
zippy/lib-python/3/plat-freebsd4/IN.py
python
IN6_IS_ADDR_MC_ORGLOCAL
(a)
return
[]
def IN6_IS_ADDR_MC_ORGLOCAL(a): return
[ "def", "IN6_IS_ADDR_MC_ORGLOCAL", "(", "a", ")", ":", "return" ]
https://github.com/securesystemslab/zippy/blob/ff0e84ac99442c2c55fe1d285332cfd4e185e089/zippy/lib-python/3/plat-freebsd4/IN.py#L283-L283
weecology/retriever
e5ba505f7b9958c70e60155f3c5495899da27e7e
retriever/lib/scripts.py
python
get_script_citation
(dataset=None)
return citations
Get the citation list for a script
Get the citation list for a script
[ "Get", "the", "citation", "list", "for", "a", "script" ]
def get_script_citation(dataset=None): """Get the citation list for a script""" if dataset is not None: dataset = dataset.strip() if not dataset: return [VERSION] citations = [] scripts = name_matches(reload_scripts(), dataset) if scripts: citations = [] for script in scripts: citations.append(script.citation) return citations
[ "def", "get_script_citation", "(", "dataset", "=", "None", ")", ":", "if", "dataset", "is", "not", "None", ":", "dataset", "=", "dataset", ".", "strip", "(", ")", "if", "not", "dataset", ":", "return", "[", "VERSION", "]", "citations", "=", "[", "]", ...
https://github.com/weecology/retriever/blob/e5ba505f7b9958c70e60155f3c5495899da27e7e/retriever/lib/scripts.py#L302-L314
google/pytype
fa43edc95dd42ade6e3147d6580d63e778c9d506
pytype/tools/xref/callgraph.py
python
FunctionMap.add_param_def
(self, ref, defn)
Add a function parameter definition.
Add a function parameter definition.
[ "Add", "a", "function", "parameter", "definition", "." ]
def add_param_def(self, ref, defn): """Add a function parameter definition.""" fn = self.fmap[ref.ref_scope] for param in fn.params: # Don't override a type inferred from call sites. if param.name == defn.name and param.type in ('nothing', 'typing.Any'): param.type = unwrap_type(self.index.get_pytd(ref.data[0])) break
[ "def", "add_param_def", "(", "self", ",", "ref", ",", "defn", ")", ":", "fn", "=", "self", ".", "fmap", "[", "ref", ".", "ref_scope", "]", "for", "param", "in", "fn", ".", "params", ":", "# Don't override a type inferred from call sites.", "if", "param", "...
https://github.com/google/pytype/blob/fa43edc95dd42ade6e3147d6580d63e778c9d506/pytype/tools/xref/callgraph.py#L159-L166
wistbean/fxxkpython
88e16d79d8dd37236ba6ecd0d0ff11d63143968c
vip/qyxuan/projects/Snake/venv/lib/python3.6/site-packages/pip-19.0.3-py3.6.egg/pip/_vendor/distlib/locators.py
python
SimpleScrapingLocator.get_page
(self, url)
return result
Get the HTML for an URL, possibly from an in-memory cache. XXX TODO Note: this cache is never actually cleared. It's assumed that the data won't get stale over the lifetime of a locator instance (not necessarily true for the default_locator).
Get the HTML for an URL, possibly from an in-memory cache.
[ "Get", "the", "HTML", "for", "an", "URL", "possibly", "from", "an", "in", "-", "memory", "cache", "." ]
def get_page(self, url): """ Get the HTML for an URL, possibly from an in-memory cache. XXX TODO Note: this cache is never actually cleared. It's assumed that the data won't get stale over the lifetime of a locator instance (not necessarily true for the default_locator). """ # http://peak.telecommunity.com/DevCenter/EasyInstall#package-index-api scheme, netloc, path, _, _, _ = urlparse(url) if scheme == 'file' and os.path.isdir(url2pathname(path)): url = urljoin(ensure_slash(url), 'index.html') if url in self._page_cache: result = self._page_cache[url] logger.debug('Returning %s from cache: %s', url, result) else: host = netloc.split(':', 1)[0] result = None if host in self._bad_hosts: logger.debug('Skipping %s due to bad host %s', url, host) else: req = Request(url, headers={'Accept-encoding': 'identity'}) try: logger.debug('Fetching %s', url) resp = self.opener.open(req, timeout=self.timeout) logger.debug('Fetched %s', url) headers = resp.info() content_type = headers.get('Content-Type', '') if HTML_CONTENT_TYPE.match(content_type): final_url = resp.geturl() data = resp.read() encoding = headers.get('Content-Encoding') if encoding: decoder = self.decoders[encoding] # fail if not found data = decoder(data) encoding = 'utf-8' m = CHARSET.search(content_type) if m: encoding = m.group(1) try: data = data.decode(encoding) except UnicodeError: # pragma: no cover data = data.decode('latin-1') # fallback result = Page(data, final_url) self._page_cache[final_url] = result except HTTPError as e: if e.code != 404: logger.exception('Fetch failed: %s: %s', url, e) except URLError as e: # pragma: no cover logger.exception('Fetch failed: %s: %s', url, e) with self._lock: self._bad_hosts.add(host) except Exception as e: # pragma: no cover logger.exception('Fetch failed: %s: %s', url, e) finally: self._page_cache[url] = result # even if None (failure) return result
[ "def", "get_page", "(", "self", ",", "url", ")", ":", "# http://peak.telecommunity.com/DevCenter/EasyInstall#package-index-api", "scheme", ",", "netloc", ",", "path", ",", "_", ",", "_", ",", "_", "=", "urlparse", "(", "url", ")", "if", "scheme", "==", "'file'...
https://github.com/wistbean/fxxkpython/blob/88e16d79d8dd37236ba6ecd0d0ff11d63143968c/vip/qyxuan/projects/Snake/venv/lib/python3.6/site-packages/pip-19.0.3-py3.6.egg/pip/_vendor/distlib/locators.py#L755-L812
krintoxi/NoobSec-Toolkit
38738541cbc03cedb9a3b3ed13b629f781ad64f6
NoobSecToolkit /tools/inject/plugins/dbms/postgresql/enumeration.py
python
Enumeration.getHostname
(self)
[]
def getHostname(self): warnMsg = "on PostgreSQL it is not possible to enumerate the hostname" logger.warn(warnMsg)
[ "def", "getHostname", "(", "self", ")", ":", "warnMsg", "=", "\"on PostgreSQL it is not possible to enumerate the hostname\"", "logger", ".", "warn", "(", "warnMsg", ")" ]
https://github.com/krintoxi/NoobSec-Toolkit/blob/38738541cbc03cedb9a3b3ed13b629f781ad64f6/NoobSecToolkit /tools/inject/plugins/dbms/postgresql/enumeration.py#L16-L18
openshift/openshift-tools
1188778e728a6e4781acf728123e5b356380fe6f
openshift/installer/vendored/openshift-ansible-3.10.0-0.29.0/roles/lib_vendored_deps/library/oc_clusterrole.py
python
Utils._write
(filename, contents)
Actually write the file contents to disk. This helps with mocking.
Actually write the file contents to disk. This helps with mocking.
[ "Actually", "write", "the", "file", "contents", "to", "disk", ".", "This", "helps", "with", "mocking", "." ]
def _write(filename, contents): ''' Actually write the file contents to disk. This helps with mocking. ''' with open(filename, 'w') as sfd: sfd.write(str(contents))
[ "def", "_write", "(", "filename", ",", "contents", ")", ":", "with", "open", "(", "filename", ",", "'w'", ")", "as", "sfd", ":", "sfd", ".", "write", "(", "str", "(", "contents", ")", ")" ]
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_clusterrole.py#L1157-L1161
AppScale/gts
46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9
AppServer/lib/django-1.2/django/contrib/gis/db/backends/postgis/creation.py
python
PostGISCreation.sql_indexes_for_field
(self, model, f, style)
return output
Return any spatial index creation SQL for the field.
Return any spatial index creation SQL for the field.
[ "Return", "any", "spatial", "index", "creation", "SQL", "for", "the", "field", "." ]
def sql_indexes_for_field(self, model, f, style): "Return any spatial index creation SQL for the field." from django.contrib.gis.db.models.fields import GeometryField output = super(PostGISCreation, self).sql_indexes_for_field(model, f, style) if isinstance(f, GeometryField): gqn = self.connection.ops.geo_quote_name qn = self.connection.ops.quote_name db_table = model._meta.db_table if f.geography: # Geogrophy columns are created normally. pass else: # Geometry columns are created by `AddGeometryColumn` # stored procedure. output.append(style.SQL_KEYWORD('SELECT ') + style.SQL_TABLE('AddGeometryColumn') + '(' + style.SQL_TABLE(gqn(db_table)) + ', ' + style.SQL_FIELD(gqn(f.column)) + ', ' + style.SQL_FIELD(str(f.srid)) + ', ' + style.SQL_COLTYPE(gqn(f.geom_type)) + ', ' + style.SQL_KEYWORD(str(f.dim)) + ');') if not f.null: # Add a NOT NULL constraint to the field output.append(style.SQL_KEYWORD('ALTER TABLE ') + style.SQL_TABLE(qn(db_table)) + style.SQL_KEYWORD(' ALTER ') + style.SQL_FIELD(qn(f.column)) + style.SQL_KEYWORD(' SET NOT NULL') + ';') if f.spatial_index: # Spatial indexes created the same way for both Geometry and # Geography columns if f.geography: index_opts = '' else: index_opts = ' ' + style.SQL_KEYWORD(self.geom_index_opts) output.append(style.SQL_KEYWORD('CREATE INDEX ') + style.SQL_TABLE(qn('%s_%s_id' % (db_table, f.column))) + style.SQL_KEYWORD(' ON ') + style.SQL_TABLE(qn(db_table)) + style.SQL_KEYWORD(' USING ') + style.SQL_COLTYPE(self.geom_index_type) + ' ( ' + style.SQL_FIELD(qn(f.column)) + index_opts + ' );') return output
[ "def", "sql_indexes_for_field", "(", "self", ",", "model", ",", "f", ",", "style", ")", ":", "from", "django", ".", "contrib", ".", "gis", ".", "db", ".", "models", ".", "fields", "import", "GeometryField", "output", "=", "super", "(", "PostGISCreation", ...
https://github.com/AppScale/gts/blob/46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9/AppServer/lib/django-1.2/django/contrib/gis/db/backends/postgis/creation.py#L8-L56
clips/clicr
557f6d96a9afe245d9637e7e86315c2838878fc2
dataset-code/json_to_plain.py
python
write_sareader
(i, fh_out)
:param i: {"id": "", "p": "", "q", "", "a", "", "c", [""]}
:param i: {"id": "", "p": "", "q", "", "a", "", "c", [""]}
[ ":", "param", "i", ":", "{", "id", ":", "p", ":", "q", "a", "c", "[", "]", "}" ]
def write_sareader(i, fh_out): """ :param i: {"id": "", "p": "", "q", "", "a", "", "c", [""]} """ fh_out.write(i["q"] + "\n") fh_out.write(plain_to_ent(i["a"]) + "\n") fh_out.write(i["p"] + "\n") fh_out.write(i["id"] + "\n\n")
[ "def", "write_sareader", "(", "i", ",", "fh_out", ")", ":", "fh_out", ".", "write", "(", "i", "[", "\"q\"", "]", "+", "\"\\n\"", ")", "fh_out", ".", "write", "(", "plain_to_ent", "(", "i", "[", "\"a\"", "]", ")", "+", "\"\\n\"", ")", "fh_out", ".",...
https://github.com/clips/clicr/blob/557f6d96a9afe245d9637e7e86315c2838878fc2/dataset-code/json_to_plain.py#L77-L88
home-assistant/core
265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1
homeassistant/components/ecoal_boiler/switch.py
python
EcoalSwitch.invalidate_ecoal_cache
(self)
Invalidate ecoal interface cache. Forces that next read from ecaol interface to not use cache.
Invalidate ecoal interface cache.
[ "Invalidate", "ecoal", "interface", "cache", "." ]
def invalidate_ecoal_cache(self): """Invalidate ecoal interface cache. Forces that next read from ecaol interface to not use cache. """ self._ecoal_contr.status = None
[ "def", "invalidate_ecoal_cache", "(", "self", ")", ":", "self", ".", "_ecoal_contr", ".", "status", "=", "None" ]
https://github.com/home-assistant/core/blob/265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1/homeassistant/components/ecoal_boiler/switch.py#L56-L61
1040003585/WebScrapingWithPython
a770fa5b03894076c8c9539b1ffff34424ffc016
portia_examle/lib/python2.7/site-packages/pip/_vendor/pkg_resources/__init__.py
python
_handle_ns
(packageName, path_item)
return subpath
Ensure that named package includes a subpath of path_item (if needed)
Ensure that named package includes a subpath of path_item (if needed)
[ "Ensure", "that", "named", "package", "includes", "a", "subpath", "of", "path_item", "(", "if", "needed", ")" ]
def _handle_ns(packageName, path_item): """Ensure that named package includes a subpath of path_item (if needed)""" importer = get_importer(path_item) if importer is None: return None loader = importer.find_module(packageName) if loader is None: return None module = sys.modules.get(packageName) if module is None: module = sys.modules[packageName] = types.ModuleType(packageName) module.__path__ = [] _set_parent_ns(packageName) elif not hasattr(module, '__path__'): raise TypeError("Not a package:", packageName) handler = _find_adapter(_namespace_handlers, importer) subpath = handler(importer, path_item, packageName, module) if subpath is not None: path = module.__path__ path.append(subpath) loader.load_module(packageName) _rebuild_mod_path(path, packageName, module) return subpath
[ "def", "_handle_ns", "(", "packageName", ",", "path_item", ")", ":", "importer", "=", "get_importer", "(", "path_item", ")", "if", "importer", "is", "None", ":", "return", "None", "loader", "=", "importer", ".", "find_module", "(", "packageName", ")", "if", ...
https://github.com/1040003585/WebScrapingWithPython/blob/a770fa5b03894076c8c9539b1ffff34424ffc016/portia_examle/lib/python2.7/site-packages/pip/_vendor/pkg_resources/__init__.py#L2070-L2093
giswqs/geemap
ba8de85557a8a1bc9c8d19e75bac69416afe7fea
geemap/eefolium.py
python
Map.center_object
(self, ee_object, zoom=10)
Centers the map view on a given object. Args: ee_object (Element|Geometry): An Earth Engine object to center on - a geometry, image or feature. zoom (int, optional): The zoom level, from 1 to 24. Defaults to 10.
Centers the map view on a given object.
[ "Centers", "the", "map", "view", "on", "a", "given", "object", "." ]
def center_object(self, ee_object, zoom=10): """Centers the map view on a given object. Args: ee_object (Element|Geometry): An Earth Engine object to center on - a geometry, image or feature. zoom (int, optional): The zoom level, from 1 to 24. Defaults to 10. """ lat = 0 lon = 0 if isinstance(ee_object, ee.geometry.Geometry): centroid = ee_object.centroid() lon, lat = centroid.getInfo()["coordinates"] bounds = [[lat, lon], [lat, lon]] elif isinstance(ee_object, ee.featurecollection.FeatureCollection): centroid = ee_object.geometry().centroid() lon, lat = centroid.getInfo()["coordinates"] bounds = [[lat, lon], [lat, lon]] elif isinstance(ee_object, ee.image.Image): geometry = ee_object.geometry() coordinates = geometry.getInfo()["coordinates"][0] bounds = [coordinates[0][::-1], coordinates[2][::-1]] elif isinstance(ee_object, ee.imagecollection.ImageCollection): geometry = ee_object.geometry() coordinates = geometry.getInfo()["coordinates"][0] bounds = [coordinates[0][::-1], coordinates[2][::-1]] else: bounds = [[0, 0], [0, 0]] self.fit_bounds(bounds, max_zoom=zoom)
[ "def", "center_object", "(", "self", ",", "ee_object", ",", "zoom", "=", "10", ")", ":", "lat", "=", "0", "lon", "=", "0", "if", "isinstance", "(", "ee_object", ",", "ee", ".", "geometry", ".", "Geometry", ")", ":", "centroid", "=", "ee_object", ".",...
https://github.com/giswqs/geemap/blob/ba8de85557a8a1bc9c8d19e75bac69416afe7fea/geemap/eefolium.py#L358-L387
npcole/npyscreen
8ce31204e1de1fbd2939ffe2d8c3b3120e93a4d0
npyscreen/wgmultiline.py
python
BufferPager.buffer
(self, lines, scroll_end=True, scroll_if_editing=False)
Add data to be displayed in the buffer.
Add data to be displayed in the buffer.
[ "Add", "data", "to", "be", "displayed", "in", "the", "buffer", "." ]
def buffer(self, lines, scroll_end=True, scroll_if_editing=False): "Add data to be displayed in the buffer." self.values.extend(lines) if scroll_end: if not self.editing: self.start_display_at = len(self.values) - len(self._my_widgets) elif scroll_if_editing: self.start_display_at = len(self.values) - len(self._my_widgets)
[ "def", "buffer", "(", "self", ",", "lines", ",", "scroll_end", "=", "True", ",", "scroll_if_editing", "=", "False", ")", ":", "self", ".", "values", ".", "extend", "(", "lines", ")", "if", "scroll_end", ":", "if", "not", "self", ".", "editing", ":", ...
https://github.com/npcole/npyscreen/blob/8ce31204e1de1fbd2939ffe2d8c3b3120e93a4d0/npyscreen/wgmultiline.py#L842-L849
CouchPotato/CouchPotatoV1
135b3331d1b88ef645e29b76f2d4cc4a732c9232
app/controllers/config.py
python
ConfigController.index
(self)
return self.render({'trailerFormats':trailerFormats, 'foldernameResult':foldernameResult, 'filenameResult':filenameResult, 'config':config})
Config form
Config form
[ "Config", "form" ]
def index(self): ''' Config form ''' config = cherrypy.config.get('config') renamer = self.cron.get('renamer') replacements = { 'cd': ' cd1', 'cdNr': ' 1', 'ext': 'mkv', 'namethe': 'Big Lebowski, The', 'thename': 'The Big Lebowski', 'year': 1998, 'first': 'B', 'original': 'The.Big.Lebowski.1998.1080p.BluRay.x264.DTS-GROUP', 'group':'GROUP', 'audio':'DTS', 'video':'x264', 'quality': '1080p', 'sourcemedia': 'BluRay', 'resolution' : '1920x1080' } trailerFormats = self.cron.get('trailer').formats foldernameResult = renamer.doReplace(config.get('Renamer', 'foldernaming'), replacements) filenameResult = renamer.doReplace(config.get('Renamer', 'filenaming'), replacements) return self.render({'trailerFormats':trailerFormats, 'foldernameResult':foldernameResult, 'filenameResult':filenameResult, 'config':config})
[ "def", "index", "(", "self", ")", ":", "config", "=", "cherrypy", ".", "config", ".", "get", "(", "'config'", ")", "renamer", "=", "self", ".", "cron", ".", "get", "(", "'renamer'", ")", "replacements", "=", "{", "'cd'", ":", "' cd1'", ",", "'cdNr'",...
https://github.com/CouchPotato/CouchPotatoV1/blob/135b3331d1b88ef645e29b76f2d4cc4a732c9232/app/controllers/config.py#L26-L54
IronLanguages/ironpython3
7a7bb2a872eeab0d1009fc8a6e24dca43f65b693
Src/StdLib/Lib/encodings/cp862.py
python
Codec.encode
(self,input,errors='strict')
return codecs.charmap_encode(input,errors,encoding_map)
[]
def encode(self,input,errors='strict'): return codecs.charmap_encode(input,errors,encoding_map)
[ "def", "encode", "(", "self", ",", "input", ",", "errors", "=", "'strict'", ")", ":", "return", "codecs", ".", "charmap_encode", "(", "input", ",", "errors", ",", "encoding_map", ")" ]
https://github.com/IronLanguages/ironpython3/blob/7a7bb2a872eeab0d1009fc8a6e24dca43f65b693/Src/StdLib/Lib/encodings/cp862.py#L11-L12
rasbt/mlxtend
80964e439c1d150a00878f24b51bfeb2c8d2c3df
mlxtend/externals/pyprind/prog_class.py
python
Prog._check_stream
(self)
Determines which output stream (stdout, stderr, or custom) to use
Determines which output stream (stdout, stderr, or custom) to use
[ "Determines", "which", "output", "stream", "(", "stdout", "stderr", "or", "custom", ")", "to", "use" ]
def _check_stream(self): """Determines which output stream (stdout, stderr, or custom) to use""" if self.stream: try: supported = ('PYCHARM_HOSTED' in os.environ or os.isatty(sys.stdout.fileno())) # a fix for IPython notebook "IOStream has no fileno." except(UnsupportedOperation): supported = True else: if self.stream is not None and hasattr(self.stream, 'write'): self._stream_out = self.stream.write self._stream_flush = self.stream.flush if supported: if self.stream == 1: self._stream_out = sys.stdout.write self._stream_flush = sys.stdout.flush elif self.stream == 2: self._stream_out = sys.stderr.write self._stream_flush = sys.stderr.flush else: if self.stream is not None and hasattr(self.stream, 'write'): self._stream_out = self.stream.write self._stream_flush = self.stream.flush else: print('Warning: No valid output stream.')
[ "def", "_check_stream", "(", "self", ")", ":", "if", "self", ".", "stream", ":", "try", ":", "supported", "=", "(", "'PYCHARM_HOSTED'", "in", "os", ".", "environ", "or", "os", ".", "isatty", "(", "sys", ".", "stdout", ".", "fileno", "(", ")", ")", ...
https://github.com/rasbt/mlxtend/blob/80964e439c1d150a00878f24b51bfeb2c8d2c3df/mlxtend/externals/pyprind/prog_class.py#L89-L118
holzschu/Carnets
44effb10ddfc6aa5c8b0687582a724ba82c6b547
Library/lib/python3.7/site-packages/pip/_vendor/ipaddress.py
python
_BaseNetwork.num_addresses
(self)
return int(self.broadcast_address) - int(self.network_address) + 1
Number of hosts in the current subnet.
Number of hosts in the current subnet.
[ "Number", "of", "hosts", "in", "the", "current", "subnet", "." ]
def num_addresses(self): """Number of hosts in the current subnet.""" return int(self.broadcast_address) - int(self.network_address) + 1
[ "def", "num_addresses", "(", "self", ")", ":", "return", "int", "(", "self", ".", "broadcast_address", ")", "-", "int", "(", "self", ".", "network_address", ")", "+", "1" ]
https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/pip/_vendor/ipaddress.py#L847-L849
deepchem/deepchem
054eb4b2b082e3df8e1a8e77f36a52137ae6e375
contrib/DeepMHC/bd13_datasets.py
python
to_one_hot_array
(sequence)
return np.asarray(one_hot_array, dtype=np.int32)
Converts the sequence to one-hot-array.
Converts the sequence to one-hot-array.
[ "Converts", "the", "sequence", "to", "one", "-", "hot", "-", "array", "." ]
def to_one_hot_array(sequence): """Converts the sequence to one-hot-array.""" one_hot_array = list() for letter in sequence: one_hot_array.append([letter == i for i in aa_charset]) return np.asarray(one_hot_array, dtype=np.int32)
[ "def", "to_one_hot_array", "(", "sequence", ")", ":", "one_hot_array", "=", "list", "(", ")", "for", "letter", "in", "sequence", ":", "one_hot_array", ".", "append", "(", "[", "letter", "==", "i", "for", "i", "in", "aa_charset", "]", ")", "return", "np",...
https://github.com/deepchem/deepchem/blob/054eb4b2b082e3df8e1a8e77f36a52137ae6e375/contrib/DeepMHC/bd13_datasets.py#L38-L43
AppScale/gts
46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9
AppServer/google/appengine/_internal/django/utils/http.py
python
int_to_base36
(i)
return ''.join(base36)
Converts an integer to a base36 string
Converts an integer to a base36 string
[ "Converts", "an", "integer", "to", "a", "base36", "string" ]
def int_to_base36(i): """ Converts an integer to a base36 string """ digits = "0123456789abcdefghijklmnopqrstuvwxyz" factor = 0 # Find starting factor while True: factor += 1 if i < 36 ** factor: factor -= 1 break base36 = [] # Construct base36 representation while factor >= 0: j = 36 ** factor base36.append(digits[i / j]) i = i % j factor -= 1 return ''.join(base36)
[ "def", "int_to_base36", "(", "i", ")", ":", "digits", "=", "\"0123456789abcdefghijklmnopqrstuvwxyz\"", "factor", "=", "0", "# Find starting factor", "while", "True", ":", "factor", "+=", "1", "if", "i", "<", "36", "**", "factor", ":", "factor", "-=", "1", "b...
https://github.com/AppScale/gts/blob/46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9/AppServer/google/appengine/_internal/django/utils/http.py#L91-L110
KlugerLab/SpectralNet
e0993413ba4604258f979496e292fdcd26ea7a18
src/core/util.py
python
LearningHandler.on_epoch_end
(self, epoch, logs=None)
return stop_training
Per epoch logic for managing learning rate and early stopping
Per epoch logic for managing learning rate and early stopping
[ "Per", "epoch", "logic", "for", "managing", "learning", "rate", "and", "early", "stopping" ]
def on_epoch_end(self, epoch, logs=None): ''' Per epoch logic for managing learning rate and early stopping ''' stop_training = False # check if we need to stop or increase scheduler stage if isinstance(logs, dict): loss = logs['val_loss'] else: loss = logs if loss <= self.best_loss: self.best_loss = loss self.wait = 0 else: self.wait += 1 if self.wait > self.patience: self.scheduler_stage += 1 self.wait = 0 # calculate and set learning rate lr = self.lr * np.power(self.drop, self.scheduler_stage) K.set_value(self.lr_tensor, lr) # built in stopping if lr is way too small if lr <= 1e-7: stop_training = True # for keras if hasattr(self, 'model') and self.model is not None: self.model.stop_training = stop_training return stop_training
[ "def", "on_epoch_end", "(", "self", ",", "epoch", ",", "logs", "=", "None", ")", ":", "stop_training", "=", "False", "# check if we need to stop or increase scheduler stage", "if", "isinstance", "(", "logs", ",", "dict", ")", ":", "loss", "=", "logs", "[", "'v...
https://github.com/KlugerLab/SpectralNet/blob/e0993413ba4604258f979496e292fdcd26ea7a18/src/core/util.py#L116-L147
keiffster/program-y
8c99b56f8c32f01a7b9887b5daae9465619d0385
src/utils/aiml_generator/generator.py
python
CollectionLoader.__init__
(self, csv_file_name)
[]
def __init__(self, csv_file_name): self.csv_file_name = csv_file_name
[ "def", "__init__", "(", "self", ",", "csv_file_name", ")", ":", "self", ".", "csv_file_name", "=", "csv_file_name" ]
https://github.com/keiffster/program-y/blob/8c99b56f8c32f01a7b9887b5daae9465619d0385/src/utils/aiml_generator/generator.py#L63-L64
edisonlz/fastor
342078a18363ac41d3c6b1ab29dbdd44fdb0b7b3
base/site-packages/piston/oauth.py
python
OAuthSignatureMethod.build_signature
(self, oauth_request, oauth_consumer, oauth_token)
-> str.
-> str.
[ "-", ">", "str", "." ]
def build_signature(self, oauth_request, oauth_consumer, oauth_token): """-> str.""" raise NotImplementedError
[ "def", "build_signature", "(", "self", ",", "oauth_request", ",", "oauth_consumer", ",", "oauth_token", ")", ":", "raise", "NotImplementedError" ]
https://github.com/edisonlz/fastor/blob/342078a18363ac41d3c6b1ab29dbdd44fdb0b7b3/base/site-packages/piston/oauth.py#L591-L593
ChineseGLUE/ChineseGLUE
1591b85cf5427c2ff60f718d359ecb71d2b44879
baselines/models/albert/run_classifier.py
python
iFLYTEKDataProcessor._create_examples
(self, lines, set_type)
return examples
Creates examples for the training and dev sets.
Creates examples for the training and dev sets.
[ "Creates", "examples", "for", "the", "training", "and", "dev", "sets", "." ]
def _create_examples(self, lines, set_type): """Creates examples for the training and dev sets.""" examples = [] for (i, line) in enumerate(lines): if i == 0: continue guid = "%s-%s" % (set_type, i) text_a = tokenization.convert_to_unicode(line[1]) text_b = None label = tokenization.convert_to_unicode(line[0]) examples.append( InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label)) return examples
[ "def", "_create_examples", "(", "self", ",", "lines", ",", "set_type", ")", ":", "examples", "=", "[", "]", "for", "(", "i", ",", "line", ")", "in", "enumerate", "(", "lines", ")", ":", "if", "i", "==", "0", ":", "continue", "guid", "=", "\"%s-%s\"...
https://github.com/ChineseGLUE/ChineseGLUE/blob/1591b85cf5427c2ff60f718d359ecb71d2b44879/baselines/models/albert/run_classifier.py#L285-L297
JimmXinu/FanFicFare
bc149a2deb2636320fe50a3e374af6eef8f61889
fanficfare/requestable.py
python
Requestable.do_decode
(self,data)
[]
def do_decode(self,data): if not hasattr(data,'decode'): ## py3 str() from pickle doesn't have .decode and is ## already decoded. Should always be bytes now(Jan2021), ## but keeping this just in case. return data decode = self.getConfigList('website_encodings', default=["utf8", "Windows-1252", "iso-8859-1"]) for code in decode: try: logger.debug("Encoding:%s"%code) errors=None if ':' in code: (code,errors)=code.split(':') if code == "auto": if not chardet: logger.info("chardet not available, skipping 'auto' encoding") continue detected = chardet.detect(data) #print(detected) if detected['confidence'] > float(self.getConfig("chardet_confidence_limit",0.9)): logger.debug("using chardet detected encoding:%s(%s)"%(detected['encoding'],detected['confidence'])) code=detected['encoding'] else: logger.debug("chardet confidence too low:%s(%s)"%(detected['encoding'],detected['confidence'])) continue if errors == 'ignore': # only allow ignore. return data.decode(code,errors='ignore') else: return data.decode(code) except Exception as e: logger.debug("code failed:"+code) logger.debug(e) logger.info("Could not decode story, tried:%s Stripping non-ASCII."%decode) try: # python2 return "".join([x for x in data if ord(x) < 128]) except TypeError: # python3 return "".join([chr(x) for x in data if x < 128])
[ "def", "do_decode", "(", "self", ",", "data", ")", ":", "if", "not", "hasattr", "(", "data", ",", "'decode'", ")", ":", "## py3 str() from pickle doesn't have .decode and is", "## already decoded. Should always be bytes now(Jan2021),", "## but keeping this just in case.", "r...
https://github.com/JimmXinu/FanFicFare/blob/bc149a2deb2636320fe50a3e374af6eef8f61889/fanficfare/requestable.py#L38-L79
Borda/pyImSegm
7584b40a8d5bba04d3bf46f540f22b5d923e4b03
imsegm/utilities/drawing.py
python
draw_image_segm_points
( ax, img, points, labels=None, slic=None, color_slic='w', lut_label_marker=DICT_LABEL_MARKER, seg_contour=None, )
on plane draw background image or segmentation, overlap with SLIC contours, add contour of adative segmentation like annot. for centers plot point with specific property (shape and colour) according label :param ax: figure axis :param ndarray img: image :param list(tuple(int,int)) points: collection of points :param list(int) labels: LUT labels for superpixels :param ndarray slic: superpixel segmentation :param str color_slic: color dor superpixels :param dict lut_label_marker: dictionary {int: (str, str)} of label and markers :param ndarray seg_contour: segmentation contour >>> img = np.random.randint(0, 256, (100, 100)) >>> points = np.random.randint(0, 100, (25, 2)) >>> labels = np.random.randint(0, 5, len(points)) >>> slic = np.random.randint(0, 256, (100, 100)) >>> draw_image_segm_points(plt.Figure().gca(), img, points, labels, slic)
on plane draw background image or segmentation, overlap with SLIC contours, add contour of adative segmentation like annot. for centers plot point with specific property (shape and colour) according label
[ "on", "plane", "draw", "background", "image", "or", "segmentation", "overlap", "with", "SLIC", "contours", "add", "contour", "of", "adative", "segmentation", "like", "annot", ".", "for", "centers", "plot", "point", "with", "specific", "property", "(", "shape", ...
def draw_image_segm_points( ax, img, points, labels=None, slic=None, color_slic='w', lut_label_marker=DICT_LABEL_MARKER, seg_contour=None, ): """ on plane draw background image or segmentation, overlap with SLIC contours, add contour of adative segmentation like annot. for centers plot point with specific property (shape and colour) according label :param ax: figure axis :param ndarray img: image :param list(tuple(int,int)) points: collection of points :param list(int) labels: LUT labels for superpixels :param ndarray slic: superpixel segmentation :param str color_slic: color dor superpixels :param dict lut_label_marker: dictionary {int: (str, str)} of label and markers :param ndarray seg_contour: segmentation contour >>> img = np.random.randint(0, 256, (100, 100)) >>> points = np.random.randint(0, 100, (25, 2)) >>> labels = np.random.randint(0, 5, len(points)) >>> slic = np.random.randint(0, 256, (100, 100)) >>> draw_image_segm_points(plt.Figure().gca(), img, points, labels, slic) """ # background image or segmentation if img.ndim == 2: ax.imshow(img, alpha=0.3, cmap=plt.cm.gist_earth) else: ax.imshow(img) if slic is not None: ax.contour(slic, levels=np.unique(slic), alpha=0.5, colors=color_slic, linewidths=0.5) # fig.gca().imshow(mark_boundaries(img, slic)) if seg_contour is not None and isinstance(seg_contour, np.ndarray): if img.shape[:2] != seg_contour.shape[:2]: raise ImageDimensionError('image size %r and segm. %r should match' % (img.shape, seg_contour.shape)) ax.contour(seg_contour, linewidths=3, levels=np.unique(seg_contour)) if labels is not None: if len(points) != len(labels): raise ValueError('number of points (%i) and labels (%i) should match' % (len(points), len(labels))) for lb in lut_label_marker: marker, clr = lut_label_marker[lb] ax.plot(points[(labels == lb), 1], points[(labels == lb), 0], marker, color=clr) else: ax.plot(points[:, 1], points[:, 0], 'o', color=COLOR_ORANGE) ax.set(xlim=[0, img.shape[1]], ylim=[img.shape[0], 0])
[ "def", "draw_image_segm_points", "(", "ax", ",", "img", ",", "points", ",", "labels", "=", "None", ",", "slic", "=", "None", ",", "color_slic", "=", "'w'", ",", "lut_label_marker", "=", "DICT_LABEL_MARKER", ",", "seg_contour", "=", "None", ",", ")", ":", ...
https://github.com/Borda/pyImSegm/blob/7584b40a8d5bba04d3bf46f540f22b5d923e4b03/imsegm/utilities/drawing.py#L784-L834
noamraph/dreampie
b09ee546ec099ee6549c649692ceb129e05fb229
dreampielib/gui/odict.py
python
Items.__call__
(self)
return self._main._items()
Pretend to be the items method.
Pretend to be the items method.
[ "Pretend", "to", "be", "the", "items", "method", "." ]
def __call__(self): """Pretend to be the items method.""" return self._main._items()
[ "def", "__call__", "(", "self", ")", ":", "return", "self", ".", "_main", ".", "_items", "(", ")" ]
https://github.com/noamraph/dreampie/blob/b09ee546ec099ee6549c649692ceb129e05fb229/dreampielib/gui/odict.py#L974-L976
mdiazcl/fuzzbunch-debian
2b76c2249ade83a389ae3badb12a1bd09901fd2c
windows/Resources/Python/Core/Lib/mailbox.py
python
_mboxMMDFMessage.set_from
(self, from_, time_=None)
return
Set "From " line, formatting and appending time_ if specified.
Set "From " line, formatting and appending time_ if specified.
[ "Set", "From", "line", "formatting", "and", "appending", "time_", "if", "specified", "." ]
def set_from(self, from_, time_=None): """Set "From " line, formatting and appending time_ if specified.""" if time_ is not None: if time_ is True: time_ = time.gmtime() from_ += ' ' + time.asctime(time_) self._from = from_ return
[ "def", "set_from", "(", "self", ",", "from_", ",", "time_", "=", "None", ")", ":", "if", "time_", "is", "not", "None", ":", "if", "time_", "is", "True", ":", "time_", "=", "time", ".", "gmtime", "(", ")", "from_", "+=", "' '", "+", "time", ".", ...
https://github.com/mdiazcl/fuzzbunch-debian/blob/2b76c2249ade83a389ae3badb12a1bd09901fd2c/windows/Resources/Python/Core/Lib/mailbox.py#L1550-L1557
tracim/tracim
a0e9746fde5a4c45b4e0f0bfa2caf9522b8c4e21
backend/tracim_backend/lib/core/storage.py
python
StorageLib.get_one_page_pdf_preview
( self, depot_file: UploadedFile, page_number: int, filename: str, default_filename: str, original_file_extension: str = "", force_download: bool = None, last_modified: datetime = None, )
return HapicFile( file_path=pdf_preview_path, filename=filename, as_attachment=force_download, last_modified=last_modified, )
Helper to get one page pdf preview for controller
Helper to get one page pdf preview for controller
[ "Helper", "to", "get", "one", "page", "pdf", "preview", "for", "controller" ]
def get_one_page_pdf_preview( self, depot_file: UploadedFile, page_number: int, filename: str, default_filename: str, original_file_extension: str = "", force_download: bool = None, last_modified: datetime = None, ) -> HapicFile: """ Helper to get one page pdf preview for controller """ with self.preview_generator_filepath_context( depot_file=depot_file, original_file_extension=original_file_extension ) as file_path: preview_page_number = self.page_number_validator( preview_generator_page_number=page_number, depot_file=depot_file, file_path=file_path, original_file_extension=original_file_extension, ) pdf_preview_path = self.preview_manager.get_pdf_preview( file_path, page=preview_page_number, file_ext=original_file_extension ) # INFO - G.M - 2019-08-08 - use given filename in all case but none or # "raw", where filename returned will a custom one. if not filename or filename == "raw": filename = default_filename return HapicFile( file_path=pdf_preview_path, filename=filename, as_attachment=force_download, last_modified=last_modified, )
[ "def", "get_one_page_pdf_preview", "(", "self", ",", "depot_file", ":", "UploadedFile", ",", "page_number", ":", "int", ",", "filename", ":", "str", ",", "default_filename", ":", "str", ",", "original_file_extension", ":", "str", "=", "\"\"", ",", "force_downloa...
https://github.com/tracim/tracim/blob/a0e9746fde5a4c45b4e0f0bfa2caf9522b8c4e21/backend/tracim_backend/lib/core/storage.py#L192-L226
taoshen58/BiBloSA
ec67cbdc411278dd29e8888e9fd6451695efc26c
exp_SC/src/utils/tree/shift_reduce.py
python
shift_reduce_constitucy
(parent_idx_seq)
return op_stack
This file is implemented to solve: tree sequence to constituency transition sequence: input is a list of father node idx of constituency tree (1 based) output is a list of element which is a one of [ 1. 1 for reduce and 2 for shift 2. 1 based node index 2. a list of 0-based index to reduce ] @author: Anonymity
This file is implemented to solve: tree sequence to constituency transition sequence:
[ "This", "file", "is", "implemented", "to", "solve", ":", "tree", "sequence", "to", "constituency", "transition", "sequence", ":" ]
def shift_reduce_constitucy(parent_idx_seq): ''' This file is implemented to solve: tree sequence to constituency transition sequence: input is a list of father node idx of constituency tree (1 based) output is a list of element which is a one of [ 1. 1 for reduce and 2 for shift 2. 1 based node index 2. a list of 0-based index to reduce ] @author: Anonymity ''' node_num = len(parent_idx_seq) # all node number in the parsing tree child_and_parent_idx = [(child_idx+1, parent_idx) # list of (child_idx, parent_idx) pair for child_idx,parent_idx in enumerate(parent_idx_seq)] # runtime variable: shifted = [0] * node_num # 0 for shifted and 0 for un-shifted children = [] parents = [] used = [] # 0 for un-used, 1 for used op_stack = [] # to restore the operation as the output while True: # check whether reduce do_reduce = False try: last_idx = parents[-1] # count count=sum([1 for u,p_idx in zip(used,parents) if u==0 and p_idx==last_idx ]) # check if count satisfy the number of 'last_idx''s children num children_num = sum([1 for _,p_idx in child_and_parent_idx if p_idx==last_idx]) if count == children_num: do_reduce = True except IndexError: pass # len(parents) == 0 # reduce or shift if do_reduce: reduce_idx = parents[-1] reduce_parent_idx = child_and_parent_idx[reduce_idx-1][1] # mark used reduce_idxs = [] for idx_n,p in enumerate(parents): if used[idx_n] == 0 and p == reduce_idx: used[idx_n] = 1 reduce_idxs.append(idx_n) shifted[reduce_idx-1] = 1 children.append(reduce_idx) parents.append(reduce_parent_idx) used.append(0) op_stack.append((2,reduce_idx,reduce_idxs)) if reduce_parent_idx == 0: break else: # do shift # get pointer pointer = 0 for idx_s in range(node_num): if shifted[idx_s] == 0: pointer = idx_s shifted[idx_s] = 1 break children.append(child_and_parent_idx[pointer][0]) parents.append(child_and_parent_idx[pointer][1]) used.append(0) #op_stack.append(-child_and_parent_idx[pointer][0]) op_stack.append((1,child_and_parent_idx[pointer][0],[] )) return op_stack
[ "def", "shift_reduce_constitucy", "(", "parent_idx_seq", ")", ":", "node_num", "=", "len", "(", "parent_idx_seq", ")", "# all node number in the parsing tree", "child_and_parent_idx", "=", "[", "(", "child_idx", "+", "1", ",", "parent_idx", ")", "# list of (child_idx, p...
https://github.com/taoshen58/BiBloSA/blob/ec67cbdc411278dd29e8888e9fd6451695efc26c/exp_SC/src/utils/tree/shift_reduce.py#L72-L141
sixty-north/cosmic-ray
cf7fb7c3cc564db1e8d53b8e8848c9f46e61a879
src/cosmic_ray/tools/survival_rate.py
python
format_survival_rate
(estimate, confidence, fail_over, session_file)
Calculate the survival rate of a session.
Calculate the survival rate of a session.
[ "Calculate", "the", "survival", "rate", "of", "a", "session", "." ]
def format_survival_rate(estimate, confidence, fail_over, session_file): """Calculate the survival rate of a session.""" confidence = float(confidence) try: z_score = SUPPORTED_Z_SCORES[int(float(confidence) * 10)] except KeyError: raise ValueError("Unsupported confidence interval: {0}".format(confidence)) with use_db(session_file, WorkDB.Mode.open) as db: rate = survival_rate(db) num_items = db.num_work_items num_complete = db.num_results if estimate: conf_int = math.sqrt(rate * (100 - rate) / num_complete) * z_score * (1 - math.sqrt(num_complete / num_items)) min_rate = rate - conf_int print("{:.2f} {:.2f} {:.2f}".format(min_rate, rate, rate + conf_int)) else: print("{:.2f}".format(rate)) min_rate = rate if fail_over and min_rate > float(fail_over): sys.exit(1)
[ "def", "format_survival_rate", "(", "estimate", ",", "confidence", ",", "fail_over", ",", "session_file", ")", ":", "confidence", "=", "float", "(", "confidence", ")", "try", ":", "z_score", "=", "SUPPORTED_Z_SCORES", "[", "int", "(", "float", "(", "confidence...
https://github.com/sixty-north/cosmic-ray/blob/cf7fb7c3cc564db1e8d53b8e8848c9f46e61a879/src/cosmic_ray/tools/survival_rate.py#L30-L53
number5/cloud-init
19948dbaf40309355e1a2dbef116efb0ce66245c
cloudinit/net/activators.py
python
NetworkManagerActivator.bring_up_interface
(device_name: str)
return _alter_interface(cmd, device_name)
Bring up interface using nmcli. Return True is successful, otherwise return False
Bring up interface using nmcli.
[ "Bring", "up", "interface", "using", "nmcli", "." ]
def bring_up_interface(device_name: str) -> bool: """Bring up interface using nmcli. Return True is successful, otherwise return False """ cmd = ["nmcli", "connection", "up", "ifname", device_name] return _alter_interface(cmd, device_name)
[ "def", "bring_up_interface", "(", "device_name", ":", "str", ")", "->", "bool", ":", "cmd", "=", "[", "\"nmcli\"", ",", "\"connection\"", ",", "\"up\"", ",", "\"ifname\"", ",", "device_name", "]", "return", "_alter_interface", "(", "cmd", ",", "device_name", ...
https://github.com/number5/cloud-init/blob/19948dbaf40309355e1a2dbef116efb0ce66245c/cloudinit/net/activators.py#L135-L141
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_hxb2/lib/python3.5/site-packages/requests/utils.py
python
from_key_val_list
(value)
return OrderedDict(value)
Take an object and test to see if it can be represented as a dictionary. Unless it can not be represented as such, return an OrderedDict, e.g., :: >>> from_key_val_list([('key', 'val')]) OrderedDict([('key', 'val')]) >>> from_key_val_list('string') ValueError: need more than 1 value to unpack >>> from_key_val_list({'key': 'val'}) OrderedDict([('key', 'val')]) :rtype: OrderedDict
Take an object and test to see if it can be represented as a dictionary. Unless it can not be represented as such, return an OrderedDict, e.g.,
[ "Take", "an", "object", "and", "test", "to", "see", "if", "it", "can", "be", "represented", "as", "a", "dictionary", ".", "Unless", "it", "can", "not", "be", "represented", "as", "such", "return", "an", "OrderedDict", "e", ".", "g", "." ]
def from_key_val_list(value): """Take an object and test to see if it can be represented as a dictionary. Unless it can not be represented as such, return an OrderedDict, e.g., :: >>> from_key_val_list([('key', 'val')]) OrderedDict([('key', 'val')]) >>> from_key_val_list('string') ValueError: need more than 1 value to unpack >>> from_key_val_list({'key': 'val'}) OrderedDict([('key', 'val')]) :rtype: OrderedDict """ if value is None: return None if isinstance(value, (str, bytes, bool, int)): raise ValueError('cannot encode objects that are not 2-tuples') return OrderedDict(value)
[ "def", "from_key_val_list", "(", "value", ")", ":", "if", "value", "is", "None", ":", "return", "None", "if", "isinstance", "(", "value", ",", "(", "str", ",", "bytes", ",", "bool", ",", "int", ")", ")", ":", "raise", "ValueError", "(", "'cannot encode...
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_hxb2/lib/python3.5/site-packages/requests/utils.py#L219-L241
Komodo/KomodoEdit
61edab75dce2bdb03943b387b0608ea36f548e8e
src/codeintel/play/core.py
python
UpdateUIEvent_ResetUpdateTime
(*args, **kwargs)
return _core.UpdateUIEvent_ResetUpdateTime(*args, **kwargs)
UpdateUIEvent_ResetUpdateTime()
UpdateUIEvent_ResetUpdateTime()
[ "UpdateUIEvent_ResetUpdateTime", "()" ]
def UpdateUIEvent_ResetUpdateTime(*args, **kwargs): """UpdateUIEvent_ResetUpdateTime()""" return _core.UpdateUIEvent_ResetUpdateTime(*args, **kwargs)
[ "def", "UpdateUIEvent_ResetUpdateTime", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core", ".", "UpdateUIEvent_ResetUpdateTime", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/Komodo/KomodoEdit/blob/61edab75dce2bdb03943b387b0608ea36f548e8e/src/codeintel/play/core.py#L4083-L4085
gabrieleangeletti/Deep-Learning-TensorFlow
ddeb1f2848da7b7bee166ad2152b4afc46bb2086
yadlt/utils/utilities.py
python
expand_args
(**args_to_expand)
return args_to_expand
Expand the given lists into the length of the layers. This is used as a convenience so that the user does not need to specify the complete list of parameters for model initialization. IE the user can just specify one parameter and this function will expand it
Expand the given lists into the length of the layers.
[ "Expand", "the", "given", "lists", "into", "the", "length", "of", "the", "layers", "." ]
def expand_args(**args_to_expand): """Expand the given lists into the length of the layers. This is used as a convenience so that the user does not need to specify the complete list of parameters for model initialization. IE the user can just specify one parameter and this function will expand it """ layers = args_to_expand['layers'] try: items = args_to_expand.iteritems() except AttributeError: items = args_to_expand.items() for key, val in items: if isinstance(val, list) and len(val) != len(layers): args_to_expand[key] = [val[0] for _ in layers] return args_to_expand
[ "def", "expand_args", "(", "*", "*", "args_to_expand", ")", ":", "layers", "=", "args_to_expand", "[", "'layers'", "]", "try", ":", "items", "=", "args_to_expand", ".", "iteritems", "(", ")", "except", "AttributeError", ":", "items", "=", "args_to_expand", "...
https://github.com/gabrieleangeletti/Deep-Learning-TensorFlow/blob/ddeb1f2848da7b7bee166ad2152b4afc46bb2086/yadlt/utils/utilities.py#L207-L224
holzschu/Carnets
44effb10ddfc6aa5c8b0687582a724ba82c6b547
Library/lib/python3.7/site-packages/docutils/utils/math/math2html.py
python
NumberGenerator.create
(self, type)
return counter
Create a counter for the given type.
Create a counter for the given type.
[ "Create", "a", "counter", "for", "the", "given", "type", "." ]
def create(self, type): "Create a counter for the given type." if self.isnumbered(type) and self.getlevel(type) > 1: index = self.orderedlayouts.index(type) above = self.orderedlayouts[index - 1] master = self.getcounter(above) return self.createdependent(type, master) counter = NumberCounter(type) if self.isroman(type): counter.setmode('I') return counter
[ "def", "create", "(", "self", ",", "type", ")", ":", "if", "self", ".", "isnumbered", "(", "type", ")", "and", "self", ".", "getlevel", "(", "type", ")", ">", "1", ":", "index", "=", "self", ".", "orderedlayouts", ".", "index", "(", "type", ")", ...
https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/docutils/utils/math/math2html.py#L3364-L3374
theotherp/nzbhydra
4b03d7f769384b97dfc60dade4806c0fc987514e
libs/passlib/apache.py
python
_CommonFile._encode_user
(self, user)
return self._encode_field(user, "user")
user-specific wrapper for _encode_field()
user-specific wrapper for _encode_field()
[ "user", "-", "specific", "wrapper", "for", "_encode_field", "()" ]
def _encode_user(self, user): """user-specific wrapper for _encode_field()""" return self._encode_field(user, "user")
[ "def", "_encode_user", "(", "self", ",", "user", ")", ":", "return", "self", ".", "_encode_field", "(", "user", ",", "\"user\"", ")" ]
https://github.com/theotherp/nzbhydra/blob/4b03d7f769384b97dfc60dade4806c0fc987514e/libs/passlib/apache.py#L306-L308
FrancoisSchnell/GPicSync
07d7c4b7da44e4e6665abb94bbb9ef6da0e779d1
src/gpicsync-GUI.py
python
GUI.selectTZ
(self, evt)
Choose a selected timezone
Choose a selected timezone
[ "Choose", "a", "selected", "timezone" ]
def selectTZ(self, evt): """Choose a selected timezone""" self.timezone = timezones[evt.GetId()-3000] self.tzButton.SetLabel(self.timezone) self.utcLabel.Disable() self.utcEntry.Disable()
[ "def", "selectTZ", "(", "self", ",", "evt", ")", ":", "self", ".", "timezone", "=", "timezones", "[", "evt", ".", "GetId", "(", ")", "-", "3000", "]", "self", ".", "tzButton", ".", "SetLabel", "(", "self", ".", "timezone", ")", "self", ".", "utcLab...
https://github.com/FrancoisSchnell/GPicSync/blob/07d7c4b7da44e4e6665abb94bbb9ef6da0e779d1/src/gpicsync-GUI.py#L1459-L1464
tensorflow/lattice
784eca50cbdfedf39f183cc7d298c9fe376b69c0
tensorflow_lattice/python/premade_lib.py
python
build_linear_combination_layer
(ensemble_outputs, model_config, dtype)
return linear_layer.Linear( num_input_dims=num_input_dims, monotonicities=['increasing'] * num_input_dims, normalization_order=normalization_order, use_bias=model_config.use_bias, kernel_initializer=kernel_initializer, bias_initializer=bias_initializer, dtype=dtype, name=OUTPUT_LINEAR_COMBINATION_LAYER_NAME)( linear_input)
Creates a `tfl.layers.Linear` layer initialized to be an average. Args: ensemble_outputs: Ensemble outputs to be linearly combined. model_config: Model configuration object describing model architecture. Should be one of the model configs in `tfl.configs`. dtype: dtype Returns: A `tfl.layers.Linear` instance.
Creates a `tfl.layers.Linear` layer initialized to be an average.
[ "Creates", "a", "tfl", ".", "layers", ".", "Linear", "layer", "initialized", "to", "be", "an", "average", "." ]
def build_linear_combination_layer(ensemble_outputs, model_config, dtype): """Creates a `tfl.layers.Linear` layer initialized to be an average. Args: ensemble_outputs: Ensemble outputs to be linearly combined. model_config: Model configuration object describing model architecture. Should be one of the model configs in `tfl.configs`. dtype: dtype Returns: A `tfl.layers.Linear` instance. """ if isinstance(ensemble_outputs, list): num_input_dims = len(ensemble_outputs) linear_input = tf.keras.layers.Concatenate(axis=1)(ensemble_outputs) else: num_input_dims = int(ensemble_outputs.shape[1]) linear_input = ensemble_outputs kernel_initializer = tf.keras.initializers.Constant(1.0 / num_input_dims) bias_initializer = tf.keras.initializers.Constant(0) if (not model_config.output_calibration and model_config.output_min is None and model_config.output_max is None): normalization_order = None else: # We need to use weighted average to keep the output range. normalization_order = 1 # Bias term cannot be used when this layer should have bounded output. if model_config.use_bias: raise ValueError('Cannot use a bias term in linear combination with ' 'output bounds or output calibration') return linear_layer.Linear( num_input_dims=num_input_dims, monotonicities=['increasing'] * num_input_dims, normalization_order=normalization_order, use_bias=model_config.use_bias, kernel_initializer=kernel_initializer, bias_initializer=bias_initializer, dtype=dtype, name=OUTPUT_LINEAR_COMBINATION_LAYER_NAME)( linear_input)
[ "def", "build_linear_combination_layer", "(", "ensemble_outputs", ",", "model_config", ",", "dtype", ")", ":", "if", "isinstance", "(", "ensemble_outputs", ",", "list", ")", ":", "num_input_dims", "=", "len", "(", "ensemble_outputs", ")", "linear_input", "=", "tf"...
https://github.com/tensorflow/lattice/blob/784eca50cbdfedf39f183cc7d298c9fe376b69c0/tensorflow_lattice/python/premade_lib.py#L806-L847
MaurizioFD/RecSys2019_DeepLearning_Evaluation
0fb6b7f5c396f8525316ed66cf9c9fdb03a5fa9b
Base/Incremental_Training_Early_Stopping.py
python
Incremental_Training_Early_Stopping._prepare_model_for_validation
(self)
This function is executed before the evaluation of the current model It should ensure the current object "self" can be passed to the evaluator object E.G. if the epoch is done via Cython or PyTorch, this function should get the new parameter values from the cython or pytorch objects into the self. pyhon object :return:
This function is executed before the evaluation of the current model It should ensure the current object "self" can be passed to the evaluator object
[ "This", "function", "is", "executed", "before", "the", "evaluation", "of", "the", "current", "model", "It", "should", "ensure", "the", "current", "object", "self", "can", "be", "passed", "to", "the", "evaluator", "object" ]
def _prepare_model_for_validation(self): """ This function is executed before the evaluation of the current model It should ensure the current object "self" can be passed to the evaluator object E.G. if the epoch is done via Cython or PyTorch, this function should get the new parameter values from the cython or pytorch objects into the self. pyhon object :return: """ raise NotImplementedError()
[ "def", "_prepare_model_for_validation", "(", "self", ")", ":", "raise", "NotImplementedError", "(", ")" ]
https://github.com/MaurizioFD/RecSys2019_DeepLearning_Evaluation/blob/0fb6b7f5c396f8525316ed66cf9c9fdb03a5fa9b/Base/Incremental_Training_Early_Stopping.py#L66-L75
wizyoung/googletranslate.popclipext
a3c465685a5a75213e2ec8517eb98d336984bc50
src/urllib3/contrib/_securetransport/low_level.py
python
_load_items_from_file
(keychain, path)
return (identities, certificates)
Given a single file, loads all the trust objects from it into arrays and the keychain. Returns a tuple of lists: the first list is a list of identities, the second a list of certs.
Given a single file, loads all the trust objects from it into arrays and the keychain. Returns a tuple of lists: the first list is a list of identities, the second a list of certs.
[ "Given", "a", "single", "file", "loads", "all", "the", "trust", "objects", "from", "it", "into", "arrays", "and", "the", "keychain", ".", "Returns", "a", "tuple", "of", "lists", ":", "the", "first", "list", "is", "a", "list", "of", "identities", "the", ...
def _load_items_from_file(keychain, path): """ Given a single file, loads all the trust objects from it into arrays and the keychain. Returns a tuple of lists: the first list is a list of identities, the second a list of certs. """ certificates = [] identities = [] result_array = None with open(path, "rb") as f: raw_filedata = f.read() try: filedata = CoreFoundation.CFDataCreate( CoreFoundation.kCFAllocatorDefault, raw_filedata, len(raw_filedata) ) result_array = CoreFoundation.CFArrayRef() result = Security.SecItemImport( filedata, # cert data None, # Filename, leaving it out for now None, # What the type of the file is, we don't care None, # what's in the file, we don't care 0, # import flags None, # key params, can include passphrase in the future keychain, # The keychain to insert into ctypes.byref(result_array), # Results ) _assert_no_error(result) # A CFArray is not very useful to us as an intermediary # representation, so we are going to extract the objects we want # and then free the array. We don't need to keep hold of keys: the # keychain already has them! result_count = CoreFoundation.CFArrayGetCount(result_array) for index in range(result_count): item = CoreFoundation.CFArrayGetValueAtIndex(result_array, index) item = ctypes.cast(item, CoreFoundation.CFTypeRef) if _is_cert(item): CoreFoundation.CFRetain(item) certificates.append(item) elif _is_identity(item): CoreFoundation.CFRetain(item) identities.append(item) finally: if result_array: CoreFoundation.CFRelease(result_array) CoreFoundation.CFRelease(filedata) return (identities, certificates)
[ "def", "_load_items_from_file", "(", "keychain", ",", "path", ")", ":", "certificates", "=", "[", "]", "identities", "=", "[", "]", "result_array", "=", "None", "with", "open", "(", "path", ",", "\"rb\"", ")", "as", "f", ":", "raw_filedata", "=", "f", ...
https://github.com/wizyoung/googletranslate.popclipext/blob/a3c465685a5a75213e2ec8517eb98d336984bc50/src/urllib3/contrib/_securetransport/low_level.py#L246-L298
FitMachineLearning/FitML
a60f49fce1799ca4b11b48307441325b6272719a
PolicyGradient/BipedalWalker_v1.0.py
python
actor_experience_replay
()
train_B = train_B[tW.flatten()>0] print("%8d were better results than pr"%np.alen(tX_train)) tX = tX[train_B,:] tY = tY[train_B,:] tW = tW[train_B,:] tR = tR[train_B,:] #print("tW",tW)
train_B = train_B[tW.flatten()>0]
[ "train_B", "=", "train_B", "[", "tW", ".", "flatten", "()", ">", "0", "]" ]
def actor_experience_replay(): tSA = (memorySA) tR = (memoryR) tX = (memoryS) tY = (memoryA) tW = (memoryW) target = tR.mean() #+ math.fabs( tR.mean() - tR.max() )/2 #+ math.fabs( tR.mean() - tR.max() )/4 train_C = np.arange(np.alen(tR)) train_C = train_C[tR.flatten()>target] tX = tX[train_C,:] tY = tY[train_C,:] tW = tW[train_C,:] tR = tR[train_C,:] train_A = np.random.randint(tY.shape[0],size=int(min(experience_replay_size,np.alen(tR) ))) tX = tX[train_A,:] tY = tY[train_A,:] tW = tW[train_A,:] tR = tR[train_A,:] train_B = np.arange(np.alen(tR)) tX_train = np.zeros(shape=(1,num_env_variables)) tY_train = np.zeros(shape=(1,num_env_actions)) for i in range(np.alen(train_B)): #pr = predictTotalRewards(tX[i],tY[i]) ''' YOU CAN"T USE predictTotalRewards IF YOU DON"T TRAIN THE QMODEL if tR[i][0] < pr: tW[i][0] = -1 else: ''' d = math.fabs( memoryR.max() - target) tW[i] = math.fabs(tR[i]-(target+0.000000000005)) / d tW[i] = math.exp(1-(1/tW[i]**2)) if tW[i]> np.random.rand(1): tX_train = np.vstack((tX_train,tX[i])) tY_train = np.vstack((tY_train,tY[i])) #print ("tW",tW[i],"exp", math.exp(1-(1/tW[i]**2))) #tW[i] = math.exp(1-(1/tW[i]**2)) #tW[i] = 1 #print("tW[i] %3.1f tR %3.2f pr %3.2f "%(tW[i],tR[i],pr)) ''' train_B = train_B[tW.flatten()>0] print("%8d were better results than pr"%np.alen(tX_train)) tX = tX[train_B,:] tY = tY[train_B,:] tW = tW[train_B,:] tR = tR[train_B,:] #print("tW",tW) ''' print("%8d were better results than pr"%np.alen(tX_train)) ''' REMOVE FIRST ELEMENT BEFORE TRAINING ''' tX_train = tX_train[1:] tY_train = tY_train[1:] print("%8d were better After removing first element"%np.alen(tX_train)) if np.alen(tX_train)>0: #tW = scale_weights(tR,tW) #print("# setps short listed ", np.alen(tR)) action_predictor_model.fit(tX_train,tY_train, batch_size=mini_batch, nb_epoch=training_epochs,verbose=0)
[ "def", "actor_experience_replay", "(", ")", ":", "tSA", "=", "(", "memorySA", ")", "tR", "=", "(", "memoryR", ")", "tX", "=", "(", "memoryS", ")", "tY", "=", "(", "memoryA", ")", "tW", "=", "(", "memoryW", ")", "target", "=", "tR", ".", "mean", "...
https://github.com/FitMachineLearning/FitML/blob/a60f49fce1799ca4b11b48307441325b6272719a/PolicyGradient/BipedalWalker_v1.0.py#L311-L380
googleads/google-ads-python
2a1d6062221f6aad1992a6bcca0e7e4a93d2db86
google/ads/googleads/v7/services/services/merchant_center_link_service/client.py
python
MerchantCenterLinkServiceClientMeta.get_transport_class
( cls, label: str = None, )
return next(iter(cls._transport_registry.values()))
Return an appropriate transport class. Args: label: The name of the desired transport. If none is provided, then the first transport in the registry is used. Returns: The transport class to use.
Return an appropriate transport class.
[ "Return", "an", "appropriate", "transport", "class", "." ]
def get_transport_class( cls, label: str = None, ) -> Type[MerchantCenterLinkServiceTransport]: """Return an appropriate transport class. Args: label: The name of the desired transport. If none is provided, then the first transport in the registry is used. Returns: The transport class to use. """ # If a specific transport is requested, return that one. if label: return cls._transport_registry[label] # No transport is requested; return the default (that is, the first one # in the dictionary). return next(iter(cls._transport_registry.values()))
[ "def", "get_transport_class", "(", "cls", ",", "label", ":", "str", "=", "None", ",", ")", "->", "Type", "[", "MerchantCenterLinkServiceTransport", "]", ":", "# If a specific transport is requested, return that one.", "if", "label", ":", "return", "cls", ".", "_tran...
https://github.com/googleads/google-ads-python/blob/2a1d6062221f6aad1992a6bcca0e7e4a93d2db86/google/ads/googleads/v7/services/services/merchant_center_link_service/client.py#L54-L72
cloudera/impyla
0c736af4cad2bade9b8e313badc08ec50e81c948
impala/_thrift_gen/hive_metastore/ThriftHiveMetastore.py
python
exchange_partition_args.__eq__
(self, other)
return isinstance(other, self.__class__) and self.__dict__ == other.__dict__
[]
def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__
[ "def", "__eq__", "(", "self", ",", "other", ")", ":", "return", "isinstance", "(", "other", ",", "self", ".", "__class__", ")", "and", "self", ".", "__dict__", "==", "other", ".", "__dict__" ]
https://github.com/cloudera/impyla/blob/0c736af4cad2bade9b8e313badc08ec50e81c948/impala/_thrift_gen/hive_metastore/ThriftHiveMetastore.py#L19282-L19283
krintoxi/NoobSec-Toolkit
38738541cbc03cedb9a3b3ed13b629f781ad64f6
NoobSecToolkit - MAC OSX/tools/inject/thirdparty/xdot/xdot.py
python
ZoomAreaAction.abort
(self)
[]
def abort(self): self.dot_widget.queue_draw()
[ "def", "abort", "(", "self", ")", ":", "self", ".", "dot_widget", ".", "queue_draw", "(", ")" ]
https://github.com/krintoxi/NoobSec-Toolkit/blob/38738541cbc03cedb9a3b3ed13b629f781ad64f6/NoobSecToolkit - MAC OSX/tools/inject/thirdparty/xdot/xdot.py#L1371-L1372
buke/GreenOdoo
3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df
runtime/python/lib/python2.7/site-packages/Jinja2-2.6-py2.7.egg/jinja2/lexer.py
python
TokenStream.skip
(self, n=1)
Got n tokens ahead.
Got n tokens ahead.
[ "Got", "n", "tokens", "ahead", "." ]
def skip(self, n=1): """Got n tokens ahead.""" for x in xrange(n): next(self)
[ "def", "skip", "(", "self", ",", "n", "=", "1", ")", ":", "for", "x", "in", "xrange", "(", "n", ")", ":", "next", "(", "self", ")" ]
https://github.com/buke/GreenOdoo/blob/3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df/runtime/python/lib/python2.7/site-packages/Jinja2-2.6-py2.7.egg/jinja2/lexer.py#L320-L323
gramps-project/gramps
04d4651a43eb210192f40a9f8c2bad8ee8fa3753
gramps/gen/plug/docgen/stylesheet.py
python
StyleSheet.add_paragraph_style
(self, name, style)
Add a paragraph style to the style sheet. :param name: The name of the :class:`.ParagraphStyle` :param style: :class:`.ParagraphStyle` instance to be added.
Add a paragraph style to the style sheet.
[ "Add", "a", "paragraph", "style", "to", "the", "style", "sheet", "." ]
def add_paragraph_style(self, name, style): """ Add a paragraph style to the style sheet. :param name: The name of the :class:`.ParagraphStyle` :param style: :class:`.ParagraphStyle` instance to be added. """ self.para_styles[name] = ParagraphStyle(style)
[ "def", "add_paragraph_style", "(", "self", ",", "name", ",", "style", ")", ":", "self", ".", "para_styles", "[", "name", "]", "=", "ParagraphStyle", "(", "style", ")" ]
https://github.com/gramps-project/gramps/blob/04d4651a43eb210192f40a9f8c2bad8ee8fa3753/gramps/gen/plug/docgen/stylesheet.py#L351-L358
Komodo/KomodoEdit
61edab75dce2bdb03943b387b0608ea36f548e8e
src/codeintel/play/core.py
python
Rect.Set
(*args, **kwargs)
return _core.Rect_Set(*args, **kwargs)
Set(int x=0, int y=0, int width=0, int height=0) Set all rectangle properties.
Set(int x=0, int y=0, int width=0, int height=0)
[ "Set", "(", "int", "x", "=", "0", "int", "y", "=", "0", "int", "width", "=", "0", "int", "height", "=", "0", ")" ]
def Set(*args, **kwargs): """ Set(int x=0, int y=0, int width=0, int height=0) Set all rectangle properties. """ return _core.Rect_Set(*args, **kwargs)
[ "def", "Set", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core", ".", "Rect_Set", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/Komodo/KomodoEdit/blob/61edab75dce2bdb03943b387b0608ea36f548e8e/src/codeintel/play/core.py#L1223-L1229
googleads/google-ads-python
2a1d6062221f6aad1992a6bcca0e7e4a93d2db86
google/ads/googleads/v9/services/services/user_list_service/transports/base.py
python
UserListServiceTransport.__init__
( self, *, host: str = "googleads.googleapis.com", credentials: ga_credentials.Credentials = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, )
Instantiate the transport. Args: host (Optional[str]): The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. client_info (google.api_core.gapic_v1.client_info.ClientInfo): The client info used to send a user-agent string along with API requests. If ``None``, then default info will be used. Generally, you only need to set this if you're developing your own client library.
Instantiate the transport.
[ "Instantiate", "the", "transport", "." ]
def __init__( self, *, host: str = "googleads.googleapis.com", credentials: ga_credentials.Credentials = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: """Instantiate the transport. Args: host (Optional[str]): The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. client_info (google.api_core.gapic_v1.client_info.ClientInfo): The client info used to send a user-agent string along with API requests. If ``None``, then default info will be used. Generally, you only need to set this if you're developing your own client library. """ # Save the hostname. Default to port 443 (HTTPS) if none is specified. if ":" not in host: host += ":443" self._host = host # If no credentials are provided, then determine the appropriate # defaults. if credentials is None: credentials, _ = google.auth.default(scopes=self.AUTH_SCOPES) # Save the credentials. self._credentials = credentials # Lifted into its own function so it can be stubbed out during tests. self._prep_wrapped_messages(client_info)
[ "def", "__init__", "(", "self", ",", "*", ",", "host", ":", "str", "=", "\"googleads.googleapis.com\"", ",", "credentials", ":", "ga_credentials", ".", "Credentials", "=", "None", ",", "client_info", ":", "gapic_v1", ".", "client_info", ".", "ClientInfo", "=",...
https://github.com/googleads/google-ads-python/blob/2a1d6062221f6aad1992a6bcca0e7e4a93d2db86/google/ads/googleads/v9/services/services/user_list_service/transports/base.py#L40-L77
sympy/sympy
d822fcba181155b85ff2b29fe525adbafb22b448
sympy/functions/combinatorial/numbers.py
python
nP
(n, k=None, replacement=False)
return Integer(_nP(n, k, replacement))
Return the number of permutations of ``n`` items taken ``k`` at a time. Possible values for ``n``: integer - set of length ``n`` sequence - converted to a multiset internally multiset - {element: multiplicity} If ``k`` is None then the total of all permutations of length 0 through the number of items represented by ``n`` will be returned. If ``replacement`` is True then a given item can appear more than once in the ``k`` items. (For example, for 'ab' permutations of 2 would include 'aa', 'ab', 'ba' and 'bb'.) The multiplicity of elements in ``n`` is ignored when ``replacement`` is True but the total number of elements is considered since no element can appear more times than the number of elements in ``n``. Examples ======== >>> from sympy.functions.combinatorial.numbers import nP >>> from sympy.utilities.iterables import multiset_permutations, multiset >>> nP(3, 2) 6 >>> nP('abc', 2) == nP(multiset('abc'), 2) == 6 True >>> nP('aab', 2) 3 >>> nP([1, 2, 2], 2) 3 >>> [nP(3, i) for i in range(4)] [1, 3, 6, 6] >>> nP(3) == sum(_) True When ``replacement`` is True, each item can have multiplicity equal to the length represented by ``n``: >>> nP('aabc', replacement=True) 121 >>> [len(list(multiset_permutations('aaaabbbbcccc', i))) for i in range(5)] [1, 3, 9, 27, 81] >>> sum(_) 121 See Also ======== sympy.utilities.iterables.multiset_permutations References ========== .. [1] https://en.wikipedia.org/wiki/Permutation
Return the number of permutations of ``n`` items taken ``k`` at a time.
[ "Return", "the", "number", "of", "permutations", "of", "n", "items", "taken", "k", "at", "a", "time", "." ]
def nP(n, k=None, replacement=False): """Return the number of permutations of ``n`` items taken ``k`` at a time. Possible values for ``n``: integer - set of length ``n`` sequence - converted to a multiset internally multiset - {element: multiplicity} If ``k`` is None then the total of all permutations of length 0 through the number of items represented by ``n`` will be returned. If ``replacement`` is True then a given item can appear more than once in the ``k`` items. (For example, for 'ab' permutations of 2 would include 'aa', 'ab', 'ba' and 'bb'.) The multiplicity of elements in ``n`` is ignored when ``replacement`` is True but the total number of elements is considered since no element can appear more times than the number of elements in ``n``. Examples ======== >>> from sympy.functions.combinatorial.numbers import nP >>> from sympy.utilities.iterables import multiset_permutations, multiset >>> nP(3, 2) 6 >>> nP('abc', 2) == nP(multiset('abc'), 2) == 6 True >>> nP('aab', 2) 3 >>> nP([1, 2, 2], 2) 3 >>> [nP(3, i) for i in range(4)] [1, 3, 6, 6] >>> nP(3) == sum(_) True When ``replacement`` is True, each item can have multiplicity equal to the length represented by ``n``: >>> nP('aabc', replacement=True) 121 >>> [len(list(multiset_permutations('aaaabbbbcccc', i))) for i in range(5)] [1, 3, 9, 27, 81] >>> sum(_) 121 See Also ======== sympy.utilities.iterables.multiset_permutations References ========== .. [1] https://en.wikipedia.org/wiki/Permutation """ try: n = as_int(n) except ValueError: return Integer(_nP(_multiset_histogram(n), k, replacement)) return Integer(_nP(n, k, replacement))
[ "def", "nP", "(", "n", ",", "k", "=", "None", ",", "replacement", "=", "False", ")", ":", "try", ":", "n", "=", "as_int", "(", "n", ")", "except", "ValueError", ":", "return", "Integer", "(", "_nP", "(", "_multiset_histogram", "(", "n", ")", ",", ...
https://github.com/sympy/sympy/blob/d822fcba181155b85ff2b29fe525adbafb22b448/sympy/functions/combinatorial/numbers.py#L1450-L1513
quodlibet/mutagen
399513b167ed00c4b7a9ef98dfe591a276efb701
mutagen/_util.py
python
fileobj_name
(fileobj)
return value
Returns: text: A potential filename for a file object. Always a valid path type, but might be empty or non-existent.
Returns: text: A potential filename for a file object. Always a valid path type, but might be empty or non-existent.
[ "Returns", ":", "text", ":", "A", "potential", "filename", "for", "a", "file", "object", ".", "Always", "a", "valid", "path", "type", "but", "might", "be", "empty", "or", "non", "-", "existent", "." ]
def fileobj_name(fileobj): """ Returns: text: A potential filename for a file object. Always a valid path type, but might be empty or non-existent. """ value = getattr(fileobj, "name", u"") if not isinstance(value, (str, bytes)): value = str(value) return value
[ "def", "fileobj_name", "(", "fileobj", ")", ":", "value", "=", "getattr", "(", "fileobj", ",", "\"name\"", ",", "u\"\"", ")", "if", "not", "isinstance", "(", "value", ",", "(", "str", ",", "bytes", ")", ")", ":", "value", "=", "str", "(", "value", ...
https://github.com/quodlibet/mutagen/blob/399513b167ed00c4b7a9ef98dfe591a276efb701/mutagen/_util.py#L115-L125
jgagneastro/coffeegrindsize
22661ebd21831dba4cf32bfc6ba59fe3d49f879c
App/dist/coffeegrindsize.app/Contents/Resources/lib/python3.7/matplotlib/category.py
python
StrCategoryFormatter._text
(value)
return value
Converts text values into utf-8 or ascii strings.
Converts text values into utf-8 or ascii strings.
[ "Converts", "text", "values", "into", "utf", "-", "8", "or", "ascii", "strings", "." ]
def _text(value): """Converts text values into utf-8 or ascii strings. """ if isinstance(value, bytes): value = value.decode(encoding='utf-8') elif not isinstance(value, str): value = str(value) return value
[ "def", "_text", "(", "value", ")", ":", "if", "isinstance", "(", "value", ",", "bytes", ")", ":", "value", "=", "value", ".", "decode", "(", "encoding", "=", "'utf-8'", ")", "elif", "not", "isinstance", "(", "value", ",", "str", ")", ":", "value", ...
https://github.com/jgagneastro/coffeegrindsize/blob/22661ebd21831dba4cf32bfc6ba59fe3d49f879c/App/dist/coffeegrindsize.app/Contents/Resources/lib/python3.7/matplotlib/category.py#L146-L153
Podshot/MCEdit-Unified
90abfb170c65b877ac67193e717fa3a3ded635dd
frustum.py
python
viewingMatrix
(projection=None, model=None)
return numpy.dot(model, projection)
Calculate the total viewing matrix from given data projection -- the projection matrix, if not provided than the result of glGetDoublev( GL_PROJECTION_MATRIX) will be used. model -- the model-view matrix, if not provided than the result of glGetDoublev( GL_MODELVIEW_MATRIX ) will be used. Note: Unless there is a valid projection and model-view matrix, the function will raise a RuntimeError
Calculate the total viewing matrix from given data
[ "Calculate", "the", "total", "viewing", "matrix", "from", "given", "data" ]
def viewingMatrix(projection=None, model=None): """Calculate the total viewing matrix from given data projection -- the projection matrix, if not provided than the result of glGetDoublev( GL_PROJECTION_MATRIX) will be used. model -- the model-view matrix, if not provided than the result of glGetDoublev( GL_MODELVIEW_MATRIX ) will be used. Note: Unless there is a valid projection and model-view matrix, the function will raise a RuntimeError """ if projection is None: projection = GL.glGetDoublev(GL.GL_PROJECTION_MATRIX) if model is None: model = GL.glGetDoublev(GL.GL_MODELVIEW_MATRIX) # hmm, this will likely fail on 64-bit platforms :( if projection is None or model is None: context_log.warn( """A NULL matrix was returned from glGetDoublev: proj=%s modelView=%s""", projection, model, ) if projection: return projection if model: return model else: return numpy.identity(4, 'd') if numpy.allclose(projection, -1.79769313e+308): context_log.warn( """Attempt to retrieve projection matrix when uninitialised %s, model=%s""", projection, model, ) return model if numpy.allclose(model, -1.79769313e+308): context_log.warn( """Attempt to retrieve model-view matrix when uninitialised %s, projection=%s""", model, projection, ) return projection return numpy.dot(model, projection)
[ "def", "viewingMatrix", "(", "projection", "=", "None", ",", "model", "=", "None", ")", ":", "if", "projection", "is", "None", ":", "projection", "=", "GL", ".", "glGetDoublev", "(", "GL", ".", "GL_PROJECTION_MATRIX", ")", "if", "model", "is", "None", ":...
https://github.com/Podshot/MCEdit-Unified/blob/90abfb170c65b877ac67193e717fa3a3ded635dd/frustum.py#L20-L62
AutoViML/Auto_ViML
3f24c349a1b62612db7835065e25201497408f30
autoviml/Auto_ViML.py
python
return_dictionary_list
(lst_of_tuples)
return orDict
Returns a dictionary of lists if you send in a list of Tuples
Returns a dictionary of lists if you send in a list of Tuples
[ "Returns", "a", "dictionary", "of", "lists", "if", "you", "send", "in", "a", "list", "of", "Tuples" ]
def return_dictionary_list(lst_of_tuples): """ Returns a dictionary of lists if you send in a list of Tuples""" orDict = defaultdict(list) # iterating over list of tuples for key, val in lst_of_tuples: orDict[key].append(val) return orDict
[ "def", "return_dictionary_list", "(", "lst_of_tuples", ")", ":", "orDict", "=", "defaultdict", "(", "list", ")", "# iterating over list of tuples", "for", "key", ",", "val", "in", "lst_of_tuples", ":", "orDict", "[", "key", "]", ".", "append", "(", "val", ")",...
https://github.com/AutoViML/Auto_ViML/blob/3f24c349a1b62612db7835065e25201497408f30/autoviml/Auto_ViML.py#L3894-L3900
IronLanguages/ironpython3
7a7bb2a872eeab0d1009fc8a6e24dca43f65b693
Src/StdLib/Lib/distutils/versionpredicate.py
python
VersionPredicate.__str__
(self)
[]
def __str__(self): if self.pred: seq = [cond + " " + str(ver) for cond, ver in self.pred] return self.name + " (" + ", ".join(seq) + ")" else: return self.name
[ "def", "__str__", "(", "self", ")", ":", "if", "self", ".", "pred", ":", "seq", "=", "[", "cond", "+", "\" \"", "+", "str", "(", "ver", ")", "for", "cond", ",", "ver", "in", "self", ".", "pred", "]", "return", "self", ".", "name", "+", "\" (\""...
https://github.com/IronLanguages/ironpython3/blob/7a7bb2a872eeab0d1009fc8a6e24dca43f65b693/Src/StdLib/Lib/distutils/versionpredicate.py#L123-L128
LouYu2015/analysis_on_the_story_of_a_stone
5acd070d026221bdca26694524e7281d79591c68
dict_creat.py
python
entropy_of_list
(nodes)
return entropy
Calculate entropy from a list of nodes. :return: entropy.
Calculate entropy from a list of nodes.
[ "Calculate", "entropy", "from", "a", "list", "of", "nodes", "." ]
def entropy_of_list(nodes): """ Calculate entropy from a list of nodes. :return: entropy. """ node_counts = [node.counter if str(node)[0] != split_mark else 1. for node in nodes] count_sum = sum(node_counts) probs = [count / count_sum for count in node_counts] entropy = -sum([prob * math.log(prob, 2) for prob in probs]) for node in nodes: if str(node)[0] == split_mark \ and node.counter >= 0.5 * count_sum + node.counter - 1: return max(entropy, MIN_ENTROPY + 0.00001) return entropy
[ "def", "entropy_of_list", "(", "nodes", ")", ":", "node_counts", "=", "[", "node", ".", "counter", "if", "str", "(", "node", ")", "[", "0", "]", "!=", "split_mark", "else", "1.", "for", "node", "in", "nodes", "]", "count_sum", "=", "sum", "(", "node_...
https://github.com/LouYu2015/analysis_on_the_story_of_a_stone/blob/5acd070d026221bdca26694524e7281d79591c68/dict_creat.py#L59-L77
jsvine/pdfplumber
b904dd6a7c5164c5e051fa9b4121f8af6a105ae9
pdfplumber/utils.py
python
merge_bboxes
(bboxes)
return ( min(map(itemgetter(0), bboxes)), min(map(itemgetter(1), bboxes)), max(map(itemgetter(2), bboxes)), max(map(itemgetter(3), bboxes)), )
Given a set of bounding boxes, return the smallest bounding box that contains them all.
Given a set of bounding boxes, return the smallest bounding box that contains them all.
[ "Given", "a", "set", "of", "bounding", "boxes", "return", "the", "smallest", "bounding", "box", "that", "contains", "them", "all", "." ]
def merge_bboxes(bboxes): """ Given a set of bounding boxes, return the smallest bounding box that contains them all. """ return ( min(map(itemgetter(0), bboxes)), min(map(itemgetter(1), bboxes)), max(map(itemgetter(2), bboxes)), max(map(itemgetter(3), bboxes)), )
[ "def", "merge_bboxes", "(", "bboxes", ")", ":", "return", "(", "min", "(", "map", "(", "itemgetter", "(", "0", ")", ",", "bboxes", ")", ")", ",", "min", "(", "map", "(", "itemgetter", "(", "1", ")", ",", "bboxes", ")", ")", ",", "max", "(", "ma...
https://github.com/jsvine/pdfplumber/blob/b904dd6a7c5164c5e051fa9b4121f8af6a105ae9/pdfplumber/utils.py#L193-L203
buke/GreenOdoo
3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df
runtime/python/lib/python2.7/multiprocessing/managers.py
python
BaseManager.connect
(self)
Connect manager object to the server process
Connect manager object to the server process
[ "Connect", "manager", "object", "to", "the", "server", "process" ]
def connect(self): ''' Connect manager object to the server process ''' Listener, Client = listener_client[self._serializer] conn = Client(self._address, authkey=self._authkey) dispatch(conn, None, 'dummy') self._state.value = State.STARTED
[ "def", "connect", "(", "self", ")", ":", "Listener", ",", "Client", "=", "listener_client", "[", "self", ".", "_serializer", "]", "conn", "=", "Client", "(", "self", ".", "_address", ",", "authkey", "=", "self", ".", "_authkey", ")", "dispatch", "(", "...
https://github.com/buke/GreenOdoo/blob/3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df/runtime/python/lib/python2.7/multiprocessing/managers.py#L495-L502
wenxinxu/resnet-in-tensorflow
8ba8d8905e099cd7e1b1cf1f84b89f603f7613a0
cifar10_input.py
python
_read_one_batch
(path, is_random_label)
return data, label
The training data contains five data batches in total. The validation data has only one batch. This function takes the directory of one batch of data and returns the images and corresponding labels as numpy arrays :param path: the directory of one batch of data :param is_random_label: do you want to use random labels? :return: image numpy arrays and label numpy arrays
The training data contains five data batches in total. The validation data has only one batch. This function takes the directory of one batch of data and returns the images and corresponding labels as numpy arrays
[ "The", "training", "data", "contains", "five", "data", "batches", "in", "total", ".", "The", "validation", "data", "has", "only", "one", "batch", ".", "This", "function", "takes", "the", "directory", "of", "one", "batch", "of", "data", "and", "returns", "t...
def _read_one_batch(path, is_random_label): ''' The training data contains five data batches in total. The validation data has only one batch. This function takes the directory of one batch of data and returns the images and corresponding labels as numpy arrays :param path: the directory of one batch of data :param is_random_label: do you want to use random labels? :return: image numpy arrays and label numpy arrays ''' fo = open(path, 'rb') dicts = cPickle.load(fo) fo.close() data = dicts['data'] if is_random_label is False: label = np.array(dicts['labels']) else: labels = np.random.randint(low=0, high=10, size=10000) label = np.array(labels) return data, label
[ "def", "_read_one_batch", "(", "path", ",", "is_random_label", ")", ":", "fo", "=", "open", "(", "path", ",", "'rb'", ")", "dicts", "=", "cPickle", ".", "load", "(", "fo", ")", "fo", ".", "close", "(", ")", "data", "=", "dicts", "[", "'data'", "]",...
https://github.com/wenxinxu/resnet-in-tensorflow/blob/8ba8d8905e099cd7e1b1cf1f84b89f603f7613a0/cifar10_input.py#L52-L72
Dvlv/Tkinter-By-Example
30721f15f7bea41489a7c46819beb5282781e563
Code/Chapter6-3.py
python
Editor.select_all
(self, event=None)
return "break"
[]
def select_all(self, event=None): self.main_text.tag_add("sel", 1.0, tk.END) return "break"
[ "def", "select_all", "(", "self", ",", "event", "=", "None", ")", ":", "self", ".", "main_text", ".", "tag_add", "(", "\"sel\"", ",", "1.0", ",", "tk", ".", "END", ")", "return", "\"break\"" ]
https://github.com/Dvlv/Tkinter-By-Example/blob/30721f15f7bea41489a7c46819beb5282781e563/Code/Chapter6-3.py#L246-L249
TencentCloud/tencentcloud-sdk-python
3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2
tencentcloud/btoe/v20210303/btoe_client.py
python
BtoeClient.CreateVideoDeposit
(self, request)
功能迭代,已上线更高版本的接口2021-05-14 用户通过本接口向BTOE写入待存证的视频的原文件或下载URL,BTOE对视频原文件存储后,将其Hash值存证上链,并生成含有电子签章的区块链存证电子凭证。视频文件支持格式:mp4、avi、mkv、mov、flv,wmv,rmvb,3gp;文件大小限制:直接上传原文件不大于5MB,下载URL文件大小不大于200 MB。 :param request: Request instance for CreateVideoDeposit. :type request: :class:`tencentcloud.btoe.v20210303.models.CreateVideoDepositRequest` :rtype: :class:`tencentcloud.btoe.v20210303.models.CreateVideoDepositResponse`
功能迭代,已上线更高版本的接口2021-05-14
[ "功能迭代,已上线更高版本的接口2021", "-", "05", "-", "14" ]
def CreateVideoDeposit(self, request): """功能迭代,已上线更高版本的接口2021-05-14 用户通过本接口向BTOE写入待存证的视频的原文件或下载URL,BTOE对视频原文件存储后,将其Hash值存证上链,并生成含有电子签章的区块链存证电子凭证。视频文件支持格式:mp4、avi、mkv、mov、flv,wmv,rmvb,3gp;文件大小限制:直接上传原文件不大于5MB,下载URL文件大小不大于200 MB。 :param request: Request instance for CreateVideoDeposit. :type request: :class:`tencentcloud.btoe.v20210303.models.CreateVideoDepositRequest` :rtype: :class:`tencentcloud.btoe.v20210303.models.CreateVideoDepositResponse` """ try: params = request._serialize() body = self.call("CreateVideoDeposit", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.CreateVideoDepositResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message)
[ "def", "CreateVideoDeposit", "(", "self", ",", "request", ")", ":", "try", ":", "params", "=", "request", ".", "_serialize", "(", ")", "body", "=", "self", ".", "call", "(", "\"CreateVideoDeposit\"", ",", "params", ")", "response", "=", "json", ".", "loa...
https://github.com/TencentCloud/tencentcloud-sdk-python/blob/3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2/tencentcloud/btoe/v20210303/btoe_client.py#L239-L266
illidanlab/Simulator
d99e2b1352a1697e5930f9b45c4704db97e33f8f
simulator/envs.py
python
CityReal.construct_map_simulation
(self, M, N, n)
Connect node to its neighbors based on a simulated M by N map :param M: M row index matrix :param N: N column index matrix :param n: n - sided polygon
Connect node to its neighbors based on a simulated M by N map :param M: M row index matrix :param N: N column index matrix :param n: n - sided polygon
[ "Connect", "node", "to", "its", "neighbors", "based", "on", "a", "simulated", "M", "by", "N", "map", ":", "param", "M", ":", "M", "row", "index", "matrix", ":", "param", "N", ":", "N", "column", "index", "matrix", ":", "param", "n", ":", "n", "-", ...
def construct_map_simulation(self, M, N, n): """Connect node to its neighbors based on a simulated M by N map :param M: M row index matrix :param N: N column index matrix :param n: n - sided polygon """ for idx, current_node in enumerate(self.nodes): if current_node is not None: i, j = ids_1dto2d(idx, M, N) current_node.set_neighbors(get_neighbor_list(i, j, M, N, n, self.nodes))
[ "def", "construct_map_simulation", "(", "self", ",", "M", ",", "N", ",", "n", ")", ":", "for", "idx", ",", "current_node", "in", "enumerate", "(", "self", ".", "nodes", ")", ":", "if", "current_node", "is", "not", "None", ":", "i", ",", "j", "=", "...
https://github.com/illidanlab/Simulator/blob/d99e2b1352a1697e5930f9b45c4704db97e33f8f/simulator/envs.py#L123-L132
HymanLiuTS/flaskTs
286648286976e85d9b9a5873632331efcafe0b21
flasky/local/lib/python2.7/warnings.py
python
catch_warnings.__init__
(self, record=False, module=None)
Specify whether to record warnings and if an alternative module should be used other than sys.modules['warnings']. For compatibility with Python 3.0, please consider all arguments to be keyword-only.
Specify whether to record warnings and if an alternative module should be used other than sys.modules['warnings'].
[ "Specify", "whether", "to", "record", "warnings", "and", "if", "an", "alternative", "module", "should", "be", "used", "other", "than", "sys", ".", "modules", "[", "warnings", "]", "." ]
def __init__(self, record=False, module=None): """Specify whether to record warnings and if an alternative module should be used other than sys.modules['warnings']. For compatibility with Python 3.0, please consider all arguments to be keyword-only. """ self._record = record self._module = sys.modules['warnings'] if module is None else module self._entered = False
[ "def", "__init__", "(", "self", ",", "record", "=", "False", ",", "module", "=", "None", ")", ":", "self", ".", "_record", "=", "record", "self", ".", "_module", "=", "sys", ".", "modules", "[", "'warnings'", "]", "if", "module", "is", "None", "else"...
https://github.com/HymanLiuTS/flaskTs/blob/286648286976e85d9b9a5873632331efcafe0b21/flasky/local/lib/python2.7/warnings.py#L340-L350
tensorflow/tensorboard
61d11d99ef034c30ba20b6a7840c8eededb9031c
tensorboard/plugins/mesh/summary.py
python
_get_tensor_summary
( name, display_name, description, tensor, content_type, components, json_config, collections, )
return tensor_summary
Creates a tensor summary with summary metadata. Args: name: Uniquely identifiable name of the summary op. Could be replaced by combination of name and type to make it unique even outside of this summary. display_name: Will be used as the display name in TensorBoard. Defaults to `tag`. description: A longform readable description of the summary data. Markdown is supported. tensor: Tensor to display in summary. content_type: Type of content inside the Tensor. components: Bitmask representing present parts (vertices, colors, etc.) that belong to the summary. json_config: A string, JSON-serialized dictionary of ThreeJS classes configuration. collections: List of collections to add this summary to. Returns: Tensor summary with metadata.
Creates a tensor summary with summary metadata.
[ "Creates", "a", "tensor", "summary", "with", "summary", "metadata", "." ]
def _get_tensor_summary( name, display_name, description, tensor, content_type, components, json_config, collections, ): """Creates a tensor summary with summary metadata. Args: name: Uniquely identifiable name of the summary op. Could be replaced by combination of name and type to make it unique even outside of this summary. display_name: Will be used as the display name in TensorBoard. Defaults to `tag`. description: A longform readable description of the summary data. Markdown is supported. tensor: Tensor to display in summary. content_type: Type of content inside the Tensor. components: Bitmask representing present parts (vertices, colors, etc.) that belong to the summary. json_config: A string, JSON-serialized dictionary of ThreeJS classes configuration. collections: List of collections to add this summary to. Returns: Tensor summary with metadata. """ tensor = tf.convert_to_tensor(value=tensor) shape = tensor.shape.as_list() shape = [dim if dim is not None else -1 for dim in shape] tensor_metadata = metadata.create_summary_metadata( name, display_name, content_type, components, shape, description, json_config=json_config, ) tensor_summary = tf.compat.v1.summary.tensor_summary( metadata.get_instance_name(name, content_type), tensor, summary_metadata=tensor_metadata, collections=collections, ) return tensor_summary
[ "def", "_get_tensor_summary", "(", "name", ",", "display_name", ",", "description", ",", "tensor", ",", "content_type", ",", "components", ",", "json_config", ",", "collections", ",", ")", ":", "tensor", "=", "tf", ".", "convert_to_tensor", "(", "value", "=", ...
https://github.com/tensorflow/tensorboard/blob/61d11d99ef034c30ba20b6a7840c8eededb9031c/tensorboard/plugins/mesh/summary.py#L32-L81
subbarayudu-j/TheAlgorithms-Python
bb29dc55faf5b98b1e9f0b1f11a9dd15525386a3
other/primelib.py
python
getPrimeNumbers
(N)
return ans
input: positive integer 'N' > 2 returns a list of prime numbers from 2 up to N (inclusive) This function is more efficient as function 'sieveEr(...)'
input: positive integer 'N' > 2 returns a list of prime numbers from 2 up to N (inclusive) This function is more efficient as function 'sieveEr(...)'
[ "input", ":", "positive", "integer", "N", ">", "2", "returns", "a", "list", "of", "prime", "numbers", "from", "2", "up", "to", "N", "(", "inclusive", ")", "This", "function", "is", "more", "efficient", "as", "function", "sieveEr", "(", "...", ")" ]
def getPrimeNumbers(N): """ input: positive integer 'N' > 2 returns a list of prime numbers from 2 up to N (inclusive) This function is more efficient as function 'sieveEr(...)' """ # precondition assert isinstance(N,int) and (N > 2), "'N' must been an int and > 2" ans = [] # iterates over all numbers between 2 up to N+1 # if a number is prime then appends to list 'ans' for number in range(2,N+1): if isPrime(number): ans.append(number) # precondition assert isinstance(ans,list), "'ans' must been from type list" return ans
[ "def", "getPrimeNumbers", "(", "N", ")", ":", "# precondition", "assert", "isinstance", "(", "N", ",", "int", ")", "and", "(", "N", ">", "2", ")", ",", "\"'N' must been an int and > 2\"", "ans", "=", "[", "]", "# iterates over all numbers between 2 up to N+1 ", ...
https://github.com/subbarayudu-j/TheAlgorithms-Python/blob/bb29dc55faf5b98b1e9f0b1f11a9dd15525386a3/other/primelib.py#L112-L135
debian-calibre/calibre
020fc81d3936a64b2ac51459ecb796666ab6a051
src/calibre/ebooks/rtf2xml/border_parse.py
python
BorderParse.parse_border
(self, line)
return border_dict
Requires: line -- line with border definition in it Returns: ? Logic:
Requires: line -- line with border definition in it Returns: ? Logic:
[ "Requires", ":", "line", "--", "line", "with", "border", "definition", "in", "it", "Returns", ":", "?", "Logic", ":" ]
def parse_border(self, line): """ Requires: line -- line with border definition in it Returns: ? Logic: """ border_dict = {} border_style_dict = {} border_style_list = [] border_type = self.__border_dict.get(line[6:16]) if not border_type: sys.stderr.write( 'module is border_parse.py\n' 'function is parse_border\n' 'token does not have a dictionary value\n' 'token is "%s"' % line ) return border_dict att_line = line[20:-1] atts = att_line.split('|') # cw<bd<bor-cel-ri<nu< # border has no value--should be no lines if len(atts) == 1 and atts[0] == '': border_dict[border_type] = 'none' return border_dict # border-paragraph-right for att in atts: values = att.split(':') if len(values) ==2: att = values[0] value = values[1] else: value = 'true' style_att = self.__border_style_dict.get(att) if style_att: att = '%s-%s' % (border_type, att) border_style_dict[att] = value border_style_list.append(style_att) else: att = self.__border_dict.get(att) if not att: sys.stderr.write( 'module is border_parse_def.py\n' 'function is parse_border\n' 'token does not have an att value\n' 'line is "%s"' % line ) att = '%s-%s' % (border_type, att) border_dict[att] = value new_border_dict = self.__determine_styles(border_type, border_style_list) border_dict.update(new_border_dict) return border_dict
[ "def", "parse_border", "(", "self", ",", "line", ")", ":", "border_dict", "=", "{", "}", "border_style_dict", "=", "{", "}", "border_style_list", "=", "[", "]", "border_type", "=", "self", ".", "__border_dict", ".", "get", "(", "line", "[", "6", ":", "...
https://github.com/debian-calibre/calibre/blob/020fc81d3936a64b2ac51459ecb796666ab6a051/src/calibre/ebooks/rtf2xml/border_parse.py#L77-L130
DonnchaC/shadowbrokers-exploits
42d8265db860b634717da4faa668b2670457cf7e
windows/fuzzbunch/pluginfinder.py
python
addplugins
(fb, type, location, constructor, manager=pluginmanager.PluginManager, bin=True)
@brief Enumerate available plugins and add them to the fuzzbunch pluginmanager @param fb Fuzzbunch object @param type String with the type of plugin to add (Exploit, Payload, Touch, etc...) @param location The disk location to look for that type of plugin @param constructor Constructor to use to instantiate the plugin
@brief Enumerate available plugins and add them to the fuzzbunch pluginmanager
[ "@brief", "Enumerate", "available", "plugins", "and", "add", "them", "to", "the", "fuzzbunch", "pluginmanager" ]
def addplugins(fb, type, location, constructor, manager=pluginmanager.PluginManager, bin=True): """ @brief Enumerate available plugins and add them to the fuzzbunch pluginmanager @param fb Fuzzbunch object @param type String with the type of plugin to add (Exploit, Payload, Touch, etc...) @param location The disk location to look for that type of plugin @param constructor Constructor to use to instantiate the plugin """ # Get a list of tuples for the available plugins in 'location' # Each entry will be (config, executable, fbfile) # # XXX Should we ensure the directories exist and load nothing, or # fail, in the event the directory doesn't exist already. # plugins = getpluginlist(location, bin) manager = fb.register_manager(type, manager) for plugin in plugins: try: manager.add_plugin(plugin, constructor) except exception.PluginXmlErr: # We encountered an error in the plugin's XML file. We don't want # this to kill execution of Fuzzbunch import os.path (d,f) = os.path.split(plugin[0]) n = f.split('-')[0] fb.io.pre_input(None) fb.io.print_warning("Failed to load %s - XML Error" % (str(n))) fb.io.post_input()
[ "def", "addplugins", "(", "fb", ",", "type", ",", "location", ",", "constructor", ",", "manager", "=", "pluginmanager", ".", "PluginManager", ",", "bin", "=", "True", ")", ":", "# Get a list of tuples for the available plugins in 'location'", "# Each entry will be (conf...
https://github.com/DonnchaC/shadowbrokers-exploits/blob/42d8265db860b634717da4faa668b2670457cf7e/windows/fuzzbunch/pluginfinder.py#L62-L92
CPqD/RouteFlow
3f406b9c1a0796f40a86eb1194990cdd2c955f4d
pox/pox/lib/graph/graph.py
python
Graph.disconnect_node
(self, node1)
Disconnecte node from all neighbours
Disconnecte node from all neighbours
[ "Disconnecte", "node", "from", "all", "neighbours" ]
def disconnect_node(self, node1): """ Disconnecte node from all neighbours """ for neighbor in self.neighbors(node1): self.disconnect_nodes(node1, neighbor)
[ "def", "disconnect_node", "(", "self", ",", "node1", ")", ":", "for", "neighbor", "in", "self", ".", "neighbors", "(", "node1", ")", ":", "self", ".", "disconnect_nodes", "(", "node1", ",", "neighbor", ")" ]
https://github.com/CPqD/RouteFlow/blob/3f406b9c1a0796f40a86eb1194990cdd2c955f4d/pox/pox/lib/graph/graph.py#L544-L547
playframework/play1
0ecac3bc2421ae2dbec27a368bf671eda1c9cba5
python/Lib/logging/__init__.py
python
Filterer.addFilter
(self, filter)
Add the specified filter to this handler.
Add the specified filter to this handler.
[ "Add", "the", "specified", "filter", "to", "this", "handler", "." ]
def addFilter(self, filter): """ Add the specified filter to this handler. """ if not (filter in self.filters): self.filters.append(filter)
[ "def", "addFilter", "(", "self", ",", "filter", ")", ":", "if", "not", "(", "filter", "in", "self", ".", "filters", ")", ":", "self", ".", "filters", ".", "append", "(", "filter", ")" ]
https://github.com/playframework/play1/blob/0ecac3bc2421ae2dbec27a368bf671eda1c9cba5/python/Lib/logging/__init__.py#L593-L598
intrig-unicamp/mininet-wifi
3c8a8f63bd4aa043aa9c1ad16f304dec2916f5ba
mn_wifi/sixLoWPAN/net.py
python
Mininet_IoT.pingAll
(self, timeout=None)
return self.ping6(timeout=timeout)
Ping between all hosts. returns: ploss packet loss percentage
Ping between all hosts. returns: ploss packet loss percentage
[ "Ping", "between", "all", "hosts", ".", "returns", ":", "ploss", "packet", "loss", "percentage" ]
def pingAll(self, timeout=None): """Ping between all hosts. returns: ploss packet loss percentage""" return self.ping6(timeout=timeout)
[ "def", "pingAll", "(", "self", ",", "timeout", "=", "None", ")", ":", "return", "self", ".", "ping6", "(", "timeout", "=", "timeout", ")" ]
https://github.com/intrig-unicamp/mininet-wifi/blob/3c8a8f63bd4aa043aa9c1ad16f304dec2916f5ba/mn_wifi/sixLoWPAN/net.py#L175-L178
shiweibsw/Translation-Tools
2fbbf902364e557fa7017f9a74a8797b7440c077
venv/Lib/site-packages/pip-9.0.3-py3.6.egg/pip/_vendor/distro.py
python
LinuxDistribution.__repr__
(self)
return \ "LinuxDistribution(" \ "os_release_file={0!r}, " \ "distro_release_file={1!r}, " \ "_os_release_info={2!r}, " \ "_lsb_release_info={3!r}, " \ "_distro_release_info={4!r})".format( self.os_release_file, self.distro_release_file, self._os_release_info, self._lsb_release_info, self._distro_release_info)
Return repr of all info
Return repr of all info
[ "Return", "repr", "of", "all", "info" ]
def __repr__(self): """Return repr of all info """ return \ "LinuxDistribution(" \ "os_release_file={0!r}, " \ "distro_release_file={1!r}, " \ "_os_release_info={2!r}, " \ "_lsb_release_info={3!r}, " \ "_distro_release_info={4!r})".format( self.os_release_file, self.distro_release_file, self._os_release_info, self._lsb_release_info, self._distro_release_info)
[ "def", "__repr__", "(", "self", ")", ":", "return", "\"LinuxDistribution(\"", "\"os_release_file={0!r}, \"", "\"distro_release_file={1!r}, \"", "\"_os_release_info={2!r}, \"", "\"_lsb_release_info={3!r}, \"", "\"_distro_release_info={4!r})\"", ".", "format", "(", "self", ".", "os...
https://github.com/shiweibsw/Translation-Tools/blob/2fbbf902364e557fa7017f9a74a8797b7440c077/venv/Lib/site-packages/pip-9.0.3-py3.6.egg/pip/_vendor/distro.py#L597-L611
oracle/graalpython
577e02da9755d916056184ec441c26e00b70145c
graalpython/lib-python/3/asyncio/proactor_events.py
python
_ProactorDatagramTransport.sendto
(self, data, addr=None)
[]
def sendto(self, data, addr=None): if not isinstance(data, (bytes, bytearray, memoryview)): raise TypeError('data argument must be bytes-like object (%r)', type(data)) if not data: return if self._address is not None and addr not in (None, self._address): raise ValueError( f'Invalid address: must be None or {self._address}') if self._conn_lost and self._address: if self._conn_lost >= constants.LOG_THRESHOLD_FOR_CONNLOST_WRITES: logger.warning('socket.sendto() raised exception.') self._conn_lost += 1 return # Ensure that what we buffer is immutable. self._buffer.append((bytes(data), addr)) if self._write_fut is None: # No current write operations are active, kick one off self._loop_writing() # else: A write operation is already kicked off self._maybe_pause_protocol()
[ "def", "sendto", "(", "self", ",", "data", ",", "addr", "=", "None", ")", ":", "if", "not", "isinstance", "(", "data", ",", "(", "bytes", ",", "bytearray", ",", "memoryview", ")", ")", ":", "raise", "TypeError", "(", "'data argument must be bytes-like obje...
https://github.com/oracle/graalpython/blob/577e02da9755d916056184ec441c26e00b70145c/graalpython/lib-python/3/asyncio/proactor_events.py#L476-L502
sametmax/Django--an-app-at-a-time
99eddf12ead76e6dfbeb09ce0bae61e282e22f8a
ignore_this_directory/django/db/migrations/autodetector.py
python
MigrationAutodetector.suggest_name
(cls, ops)
return "auto_%s" % get_migration_name_timestamp()
Given a set of operations, suggest a name for the migration they might represent. Names are not guaranteed to be unique, but put some effort into the fallback name to avoid VCS conflicts if possible.
Given a set of operations, suggest a name for the migration they might represent. Names are not guaranteed to be unique, but put some effort into the fallback name to avoid VCS conflicts if possible.
[ "Given", "a", "set", "of", "operations", "suggest", "a", "name", "for", "the", "migration", "they", "might", "represent", ".", "Names", "are", "not", "guaranteed", "to", "be", "unique", "but", "put", "some", "effort", "into", "the", "fallback", "name", "to...
def suggest_name(cls, ops): """ Given a set of operations, suggest a name for the migration they might represent. Names are not guaranteed to be unique, but put some effort into the fallback name to avoid VCS conflicts if possible. """ if len(ops) == 1: if isinstance(ops[0], operations.CreateModel): return ops[0].name_lower elif isinstance(ops[0], operations.DeleteModel): return "delete_%s" % ops[0].name_lower elif isinstance(ops[0], operations.AddField): return "%s_%s" % (ops[0].model_name_lower, ops[0].name_lower) elif isinstance(ops[0], operations.RemoveField): return "remove_%s_%s" % (ops[0].model_name_lower, ops[0].name_lower) elif ops: if all(isinstance(o, operations.CreateModel) for o in ops): return "_".join(sorted(o.name_lower for o in ops)) return "auto_%s" % get_migration_name_timestamp()
[ "def", "suggest_name", "(", "cls", ",", "ops", ")", ":", "if", "len", "(", "ops", ")", "==", "1", ":", "if", "isinstance", "(", "ops", "[", "0", "]", ",", "operations", ".", "CreateModel", ")", ":", "return", "ops", "[", "0", "]", ".", "name_lowe...
https://github.com/sametmax/Django--an-app-at-a-time/blob/99eddf12ead76e6dfbeb09ce0bae61e282e22f8a/ignore_this_directory/django/db/migrations/autodetector.py#L1291-L1309
kevingo/system-design-primer-zh-tw
d664bbc3dbcde7e8d399a4a579f28ba7822209c4
solutions/system_design/query_cache/query_cache_snippets.py
python
QueryApi.parse_query
(self, query)
Remove markup, break text into terms, deal with typos, normalize capitalization, convert to use boolean operations.
Remove markup, break text into terms, deal with typos, normalize capitalization, convert to use boolean operations.
[ "Remove", "markup", "break", "text", "into", "terms", "deal", "with", "typos", "normalize", "capitalization", "convert", "to", "use", "boolean", "operations", "." ]
def parse_query(self, query): """Remove markup, break text into terms, deal with typos, normalize capitalization, convert to use boolean operations. """ ...
[ "def", "parse_query", "(", "self", ",", "query", ")", ":", "..." ]
https://github.com/kevingo/system-design-primer-zh-tw/blob/d664bbc3dbcde7e8d399a4a579f28ba7822209c4/solutions/system_design/query_cache/query_cache_snippets.py#L9-L13
PyMVPA/PyMVPA
76c476b3de8264b0bb849bf226da5674d659564e
doc/sphinxext/autosummary/__init__.py
python
autosummary_toc_visit_html
(self, node)
Hide autosummary toctree list in HTML output.
Hide autosummary toctree list in HTML output.
[ "Hide", "autosummary", "toctree", "list", "in", "HTML", "output", "." ]
def autosummary_toc_visit_html(self, node): """Hide autosummary toctree list in HTML output.""" raise nodes.SkipNode
[ "def", "autosummary_toc_visit_html", "(", "self", ",", "node", ")", ":", "raise", "nodes", ".", "SkipNode" ]
https://github.com/PyMVPA/PyMVPA/blob/76c476b3de8264b0bb849bf226da5674d659564e/doc/sphinxext/autosummary/__init__.py#L99-L101
triaquae/triaquae
bbabf736b3ba56a0c6498e7f04e16c13b8b8f2b9
TriAquae/models/Ubuntu_12/pyasn1/type/univ.py
python
OctetString.__rmul__
(self, value)
return self * value
[]
def __rmul__(self, value): return self * value
[ "def", "__rmul__", "(", "self", ",", "value", ")", ":", "return", "self", "*", "value" ]
https://github.com/triaquae/triaquae/blob/bbabf736b3ba56a0c6498e7f04e16c13b8b8f2b9/TriAquae/models/Ubuntu_12/pyasn1/type/univ.py#L421-L421
brainiak/brainiak
ee093597c6c11597b0a59e95b48d2118e40394a5
brainiak/funcalign/sssrm.py
python
SSSRM._loss_lr_subject
(self, data, labels, w, theta, bias)
return self.alpha / samples / self.gamma * (sum_exp_values.sum() - aux)
Compute the Loss MLR for a single subject (without regularization) Parameters ---------- data : array, shape=[voxels, samples] The fMRI data of subject i for the classification task. labels : array of int, shape=[samples] The labels for the data samples in data. w : array, shape=[voxels, features] The orthogonal transform (mapping) :math:`W_i` for subject i. theta : array, shape=[classes, features] The MLR class plane parameters. bias : array, shape=[classes] The MLR class biases. Returns ------- loss : float The loss MLR for the subject
Compute the Loss MLR for a single subject (without regularization)
[ "Compute", "the", "Loss", "MLR", "for", "a", "single", "subject", "(", "without", "regularization", ")" ]
def _loss_lr_subject(self, data, labels, w, theta, bias): """Compute the Loss MLR for a single subject (without regularization) Parameters ---------- data : array, shape=[voxels, samples] The fMRI data of subject i for the classification task. labels : array of int, shape=[samples] The labels for the data samples in data. w : array, shape=[voxels, features] The orthogonal transform (mapping) :math:`W_i` for subject i. theta : array, shape=[classes, features] The MLR class plane parameters. bias : array, shape=[classes] The MLR class biases. Returns ------- loss : float The loss MLR for the subject """ if data is None: return 0.0 samples = data.shape[1] thetaT_wi_zi_plus_bias = theta.T.dot(w.T.dot(data)) + bias sum_exp, max_value, _ = utils.sumexp_stable(thetaT_wi_zi_plus_bias) sum_exp_values = np.log(sum_exp) + max_value aux = 0.0 for sample in range(samples): label = labels[sample] aux += thetaT_wi_zi_plus_bias[label, sample] return self.alpha / samples / self.gamma * (sum_exp_values.sum() - aux)
[ "def", "_loss_lr_subject", "(", "self", ",", "data", ",", "labels", ",", "w", ",", "theta", ",", "bias", ")", ":", "if", "data", "is", "None", ":", "return", "0.0", "samples", "=", "data", ".", "shape", "[", "1", "]", "thetaT_wi_zi_plus_bias", "=", "...
https://github.com/brainiak/brainiak/blob/ee093597c6c11597b0a59e95b48d2118e40394a5/brainiak/funcalign/sssrm.py#L703-L743
pyvista/pyvista
012dbb95a9aae406c3cd4cd94fc8c477f871e426
pyvista/core/pointset.py
python
StructuredGrid.dimensions
(self, dims)
Set the dataset dimensions. Pass a length three tuple of integers.
Set the dataset dimensions. Pass a length three tuple of integers.
[ "Set", "the", "dataset", "dimensions", ".", "Pass", "a", "length", "three", "tuple", "of", "integers", "." ]
def dimensions(self, dims): """Set the dataset dimensions. Pass a length three tuple of integers.""" nx, ny, nz = dims[0], dims[1], dims[2] self.SetDimensions(nx, ny, nz) self.Modified()
[ "def", "dimensions", "(", "self", ",", "dims", ")", ":", "nx", ",", "ny", ",", "nz", "=", "dims", "[", "0", "]", ",", "dims", "[", "1", "]", ",", "dims", "[", "2", "]", "self", ".", "SetDimensions", "(", "nx", ",", "ny", ",", "nz", ")", "se...
https://github.com/pyvista/pyvista/blob/012dbb95a9aae406c3cd4cd94fc8c477f871e426/pyvista/core/pointset.py#L1824-L1828
nadineproject/nadine
c41c8ef7ffe18f1853029c97eecc329039b4af6c
nadine/models/membership.py
python
MemberGroups.get_member_groups
()
return group_list
[]
def get_member_groups(): group_list = [] for package in MembershipPackage.objects.filter(enabled=True).order_by('name'): if User.helper.members_by_package(package).count() > 0: package_name = package.name group_list.append((package_name, "%s Members" % package_name)) for g, d in sorted(list(MemberGroups.GROUP_DICT.items()), key=operator.itemgetter(0)): group_list.append((g, d)) return group_list
[ "def", "get_member_groups", "(", ")", ":", "group_list", "=", "[", "]", "for", "package", "in", "MembershipPackage", ".", "objects", ".", "filter", "(", "enabled", "=", "True", ")", ".", "order_by", "(", "'name'", ")", ":", "if", "User", ".", "helper", ...
https://github.com/nadineproject/nadine/blob/c41c8ef7ffe18f1853029c97eecc329039b4af6c/nadine/models/membership.py#L58-L66
oracle/graalpython
577e02da9755d916056184ec441c26e00b70145c
graalpython/com.oracle.graal.python.benchmarks/python/meso/chaos-sized2.py
python
GVector.__str__
(self)
return "<%f, %f, %f>" % (self.x, self.y, self.z)
[]
def __str__(self): return "<%f, %f, %f>" % (self.x, self.y, self.z)
[ "def", "__str__", "(", "self", ")", ":", "return", "\"<%f, %f, %f>\"", "%", "(", "self", ".", "x", ",", "self", ".", "y", ",", "self", ".", "z", ")" ]
https://github.com/oracle/graalpython/blob/577e02da9755d916056184ec441c26e00b70145c/graalpython/com.oracle.graal.python.benchmarks/python/meso/chaos-sized2.py#L75-L76
inkandswitch/livebook
93c8d467734787366ad084fc3566bf5cbe249c51
public/pypyjs/modules/numpy/distutils/misc_util.py
python
get_npy_pkg_dir
()
return d
Return the path where to find the npy-pkg-config directory.
Return the path where to find the npy-pkg-config directory.
[ "Return", "the", "path", "where", "to", "find", "the", "npy", "-", "pkg", "-", "config", "directory", "." ]
def get_npy_pkg_dir(): """Return the path where to find the npy-pkg-config directory.""" # XXX: import here for bootstrapping reasons import numpy d = os.path.join(os.path.dirname(numpy.__file__), 'core', 'lib', 'npy-pkg-config') return d
[ "def", "get_npy_pkg_dir", "(", ")", ":", "# XXX: import here for bootstrapping reasons", "import", "numpy", "d", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "numpy", ".", "__file__", ")", ",", "'core'", ",", "'lib'", "...
https://github.com/inkandswitch/livebook/blob/93c8d467734787366ad084fc3566bf5cbe249c51/public/pypyjs/modules/numpy/distutils/misc_util.py#L2192-L2198
EdinburghNLP/XSum
7b95485c3e861d7caff76a8b4c6b3fd3bf7ee9b1
XSum-Topic-ConvS2S/fairseq/trainer.py
python
Trainer.valid_step
(self, sample)
return agg_logging_output
Do forward pass in evaluation mode.
Do forward pass in evaluation mode.
[ "Do", "forward", "pass", "in", "evaluation", "mode", "." ]
def valid_step(self, sample): """Do forward pass in evaluation mode.""" sample = self._prepare_sample(sample, volatile=True) # forward pass loss, sample_sizes, logging_outputs, ooms_fwd = self._forward(sample, eval=True) assert not ooms_fwd, 'Ran out of memory during validation' # aggregate stats and logging outputs ntokens = sum(log.get('ntokens', 0) for log in logging_outputs) grad_denom = self.criterion.__class__.grad_denom(sample_sizes) agg_logging_output = self.criterion.__class__.aggregate_logging_outputs(logging_outputs) # update loss meters for validation if 'loss' in agg_logging_output: self.meters['valid_loss'].update(agg_logging_output['loss'], grad_denom) # criterions can optionally log the NLL loss too if 'nll_loss' in agg_logging_output: self.meters['valid_nll_loss'].update(agg_logging_output['nll_loss'], ntokens) return agg_logging_output
[ "def", "valid_step", "(", "self", ",", "sample", ")", ":", "sample", "=", "self", ".", "_prepare_sample", "(", "sample", ",", "volatile", "=", "True", ")", "# forward pass", "loss", ",", "sample_sizes", ",", "logging_outputs", ",", "ooms_fwd", "=", "self", ...
https://github.com/EdinburghNLP/XSum/blob/7b95485c3e861d7caff76a8b4c6b3fd3bf7ee9b1/XSum-Topic-ConvS2S/fairseq/trainer.py#L208-L229
SFDO-Tooling/CumulusCI
825ae1f122b25dc41761c52a4ddfa1938d2a4b6e
cumulusci/cli/ui.py
python
CliTable.echo
(self, plain=False, box_style: box.Box = None)
Print this table to the global Console using console.print().
Print this table to the global Console using console.print().
[ "Print", "this", "table", "to", "the", "global", "Console", "using", "console", ".", "print", "()", "." ]
def echo(self, plain=False, box_style: box.Box = None): """ Print this table to the global Console using console.print(). """ orig_box = self._table.box if plain: self._table.box = box.ASCII2 else: self._table.box = box_style or orig_box console = rich.get_console() console.print(self._table) self._table.box = orig_box
[ "def", "echo", "(", "self", ",", "plain", "=", "False", ",", "box_style", ":", "box", ".", "Box", "=", "None", ")", ":", "orig_box", "=", "self", ".", "_table", ".", "box", "if", "plain", ":", "self", ".", "_table", ".", "box", "=", "box", ".", ...
https://github.com/SFDO-Tooling/CumulusCI/blob/825ae1f122b25dc41761c52a4ddfa1938d2a4b6e/cumulusci/cli/ui.py#L89-L100
nicolargo/ubuntupostinstall
a1713c47122ae01e8de7ab1e346815241b520126
ubuntu-14.04-postinstall.py
python
getpassword
(description = "")
Read password (with confirmation)
Read password (with confirmation)
[ "Read", "password", "(", "with", "confirmation", ")" ]
def getpassword(description = ""): """ Read password (with confirmation) """ if (description != ""): sys.stdout.write ("%s\n" % description) password1 = getpass.getpass(_("Password: ")); password2 = getpass.getpass(_("Password (confirm): ")); if (password1 == password2): return password1 else: sys.stdout.write (colors.ORANGE + _("[Warning] Password did not match, please try again") + colors.NO + "\n") return getpassword()
[ "def", "getpassword", "(", "description", "=", "\"\"", ")", ":", "if", "(", "description", "!=", "\"\"", ")", ":", "sys", ".", "stdout", ".", "write", "(", "\"%s\\n\"", "%", "description", ")", "password1", "=", "getpass", ".", "getpass", "(", "_", "("...
https://github.com/nicolargo/ubuntupostinstall/blob/a1713c47122ae01e8de7ab1e346815241b520126/ubuntu-14.04-postinstall.py#L197-L211
dropbox/stone
b7b64320631b3a4d2f10681dca64e0718ebe68ee
stone/frontend/parser.py
python
ParserFactory.p_kw_arg
(self, p)
kw_arg : ID EQ primitive | ID EQ type_ref
kw_arg : ID EQ primitive | ID EQ type_ref
[ "kw_arg", ":", "ID", "EQ", "primitive", "|", "ID", "EQ", "type_ref" ]
def p_kw_arg(self, p): """kw_arg : ID EQ primitive | ID EQ type_ref""" p[0] = {p[1]: p[3]}
[ "def", "p_kw_arg", "(", "self", ",", "p", ")", ":", "p", "[", "0", "]", "=", "{", "p", "[", "1", "]", ":", "p", "[", "3", "]", "}" ]
https://github.com/dropbox/stone/blob/b7b64320631b3a4d2f10681dca64e0718ebe68ee/stone/frontend/parser.py#L240-L243
dronekit/dronekit-python
1d89e82807ce543bae5e36426641b717e187c589
dronekit/__init__.py
python
Vehicle.play_tune
(self, tune)
Play a tune on the vehicle
Play a tune on the vehicle
[ "Play", "a", "tune", "on", "the", "vehicle" ]
def play_tune(self, tune): '''Play a tune on the vehicle''' msg = self.message_factory.play_tune_encode(0, 0, tune) self.send_mavlink(msg)
[ "def", "play_tune", "(", "self", ",", "tune", ")", ":", "msg", "=", "self", ".", "message_factory", ".", "play_tune_encode", "(", "0", ",", "0", ",", "tune", ")", "self", ".", "send_mavlink", "(", "msg", ")" ]
https://github.com/dronekit/dronekit-python/blob/1d89e82807ce543bae5e36426641b717e187c589/dronekit/__init__.py#L2360-L2363
DataDog/dd-agent
526559be731b6e47b12d7aa8b6d45cb8d9ac4d68
checks/__init__.py
python
AgentCheck._roll_up_instance_metadata
(self)
Concatenate and flush instance metadata.
Concatenate and flush instance metadata.
[ "Concatenate", "and", "flush", "instance", "metadata", "." ]
def _roll_up_instance_metadata(self): """ Concatenate and flush instance metadata. """ self.svc_metadata.append(dict((k, v) for (k, v) in self._instance_metadata)) self._instance_metadata = []
[ "def", "_roll_up_instance_metadata", "(", "self", ")", ":", "self", ".", "svc_metadata", ".", "append", "(", "dict", "(", "(", "k", ",", "v", ")", "for", "(", "k", ",", "v", ")", "in", "self", ".", "_instance_metadata", ")", ")", "self", ".", "_insta...
https://github.com/DataDog/dd-agent/blob/526559be731b6e47b12d7aa8b6d45cb8d9ac4d68/checks/__init__.py#L685-L690
beeware/ouroboros
a29123c6fab6a807caffbb7587cf548e0c370296
ouroboros/lib2to3/refactor.py
python
RefactoringTool.traverse_by
(self, fixers, traversal)
Traverse an AST, applying a set of fixers to each node. This is a helper method for refactor_tree(). Args: fixers: a list of fixer instances. traversal: a generator that yields AST nodes. Returns: None
Traverse an AST, applying a set of fixers to each node.
[ "Traverse", "an", "AST", "applying", "a", "set", "of", "fixers", "to", "each", "node", "." ]
def traverse_by(self, fixers, traversal): """Traverse an AST, applying a set of fixers to each node. This is a helper method for refactor_tree(). Args: fixers: a list of fixer instances. traversal: a generator that yields AST nodes. Returns: None """ if not fixers: return for node in traversal: for fixer in fixers[node.type]: results = fixer.match(node) if results: new = fixer.transform(node, results) if new is not None: node.replace(new) node = new
[ "def", "traverse_by", "(", "self", ",", "fixers", ",", "traversal", ")", ":", "if", "not", "fixers", ":", "return", "for", "node", "in", "traversal", ":", "for", "fixer", "in", "fixers", "[", "node", ".", "type", "]", ":", "results", "=", "fixer", "....
https://github.com/beeware/ouroboros/blob/a29123c6fab6a807caffbb7587cf548e0c370296/ouroboros/lib2to3/refactor.py#L484-L505
google/grr
8ad8a4d2c5a93c92729206b7771af19d92d4f915
grr/server/grr_response_server/gui/api_call_router_with_approval_checks.py
python
ApiCallRouterWithApprovalChecks.CreateClientApproval
(self, args, context=None)
return self.delegate.CreateClientApproval(args, context=context)
[]
def CreateClientApproval(self, args, context=None): # Everybody can create a user client approval. return self.delegate.CreateClientApproval(args, context=context)
[ "def", "CreateClientApproval", "(", "self", ",", "args", ",", "context", "=", "None", ")", ":", "# Everybody can create a user client approval.", "return", "self", ".", "delegate", ".", "CreateClientApproval", "(", "args", ",", "context", "=", "context", ")" ]
https://github.com/google/grr/blob/8ad8a4d2c5a93c92729206b7771af19d92d4f915/grr/server/grr_response_server/gui/api_call_router_with_approval_checks.py#L713-L716
misterch0c/shadowbroker
e3a069bea47a2c1009697941ac214adc6f90aa8d
windows/Resources/Python/Core/Lib/mimify.py
python
mimify_part
(ifile, ofile, is_mime)
return
Convert an 8bit part of a MIME mail message to quoted-printable.
Convert an 8bit part of a MIME mail message to quoted-printable.
[ "Convert", "an", "8bit", "part", "of", "a", "MIME", "mail", "message", "to", "quoted", "-", "printable", "." ]
def mimify_part(ifile, ofile, is_mime): """Convert an 8bit part of a MIME mail message to quoted-printable.""" has_cte = is_qp = is_base64 = 0 multipart = None must_quote_body = must_quote_header = has_iso_chars = 0 header = [] header_end = '' message = [] message_end = '' hfile = HeaderFile(ifile) while 1: line = hfile.readline() if not line: break if not must_quote_header and iso_char.search(line): must_quote_header = 1 if mv.match(line): is_mime = 1 if cte.match(line): has_cte = 1 if qp.match(line): is_qp = 1 elif base64_re.match(line): is_base64 = 1 mp_res = mp.match(line) if mp_res: multipart = '--' + mp_res.group(1) if he.match(line): header_end = line break header.append(line) while 1: line = ifile.readline() if not line: break if multipart: if line == multipart + '--\n': message_end = line break if line == multipart + '\n': message_end = line break if is_base64: message.append(line) continue if is_qp: while line[-2:] == '=\n': line = line[:-2] newline = ifile.readline() if newline[:len(QUOTE)] == QUOTE: newline = newline[len(QUOTE):] line = line + newline line = mime_decode(line) message.append(line) if not has_iso_chars: if iso_char.search(line): has_iso_chars = must_quote_body = 1 if not must_quote_body: if len(line) > MAXLEN: must_quote_body = 1 for line in header: if must_quote_header: line = mime_encode_header(line) chrset_res = chrset.match(line) if chrset_res: if has_iso_chars: if chrset_res.group(2).lower() == 'us-ascii': line = '%s%s%s' % (chrset_res.group(1), CHARSET, chrset_res.group(3)) else: line = '%sus-ascii%s' % chrset_res.group(1, 3) if has_cte and cte.match(line): line = 'Content-Transfer-Encoding: ' if is_base64: line = line + 'base64\n' elif must_quote_body: line = line + 'quoted-printable\n' else: line = line + '7bit\n' ofile.write(line) if (must_quote_header or must_quote_body) and not is_mime: ofile.write('Mime-Version: 1.0\n') ofile.write('Content-Type: text/plain; ') if has_iso_chars: ofile.write('charset="%s"\n' % CHARSET) else: ofile.write('charset="us-ascii"\n') if must_quote_body and not has_cte: ofile.write('Content-Transfer-Encoding: quoted-printable\n') ofile.write(header_end) for line in message: if must_quote_body: line = mime_encode(line, 0) ofile.write(line) ofile.write(message_end) line = message_end while multipart: if line == multipart + '--\n': while 1: line = ifile.readline() if not line: return if must_quote_body: line = mime_encode(line, 0) ofile.write(line) if line == multipart + '\n': nifile = File(ifile, multipart) mimify_part(nifile, ofile, 1) line = nifile.peek if not line: break ofile.write(line) continue while 1: line = ifile.readline() if not line: return if must_quote_body: line = mime_encode(line, 0) ofile.write(line) return
[ "def", "mimify_part", "(", "ifile", ",", "ofile", ",", "is_mime", ")", ":", "has_cte", "=", "is_qp", "=", "is_base64", "=", "0", "multipart", "=", "None", "must_quote_body", "=", "must_quote_header", "=", "has_iso_chars", "=", "0", "header", "=", "[", "]",...
https://github.com/misterch0c/shadowbroker/blob/e3a069bea47a2c1009697941ac214adc6f90aa8d/windows/Resources/Python/Core/Lib/mimify.py#L288-L416
AutodeskRoboticsLab/Mimic
85447f0d346be66988303a6a054473d92f1ed6f4
mimic/scripts/extern/pyqtgraph_0_11_0/pyqtgraph/graphicsItems/AxisItem.py
python
AxisItem.generateDrawSpecs
(self, p)
return (axisSpec, tickSpecs, textSpecs)
Calls tickValues() and tickStrings() to determine where and how ticks should be drawn, then generates from this a set of drawing commands to be interpreted by drawPicture().
Calls tickValues() and tickStrings() to determine where and how ticks should be drawn, then generates from this a set of drawing commands to be interpreted by drawPicture().
[ "Calls", "tickValues", "()", "and", "tickStrings", "()", "to", "determine", "where", "and", "how", "ticks", "should", "be", "drawn", "then", "generates", "from", "this", "a", "set", "of", "drawing", "commands", "to", "be", "interpreted", "by", "drawPicture", ...
def generateDrawSpecs(self, p): """ Calls tickValues() and tickStrings() to determine where and how ticks should be drawn, then generates from this a set of drawing commands to be interpreted by drawPicture(). """ profiler = debug.Profiler() #bounds = self.boundingRect() bounds = self.mapRectFromParent(self.geometry()) linkedView = self.linkedView() if linkedView is None or self.grid is False: tickBounds = bounds else: tickBounds = linkedView.mapRectToItem(self, linkedView.boundingRect()) if self.orientation == 'left': span = (bounds.topRight(), bounds.bottomRight()) tickStart = tickBounds.right() tickStop = bounds.right() tickDir = -1 axis = 0 elif self.orientation == 'right': span = (bounds.topLeft(), bounds.bottomLeft()) tickStart = tickBounds.left() tickStop = bounds.left() tickDir = 1 axis = 0 elif self.orientation == 'top': span = (bounds.bottomLeft(), bounds.bottomRight()) tickStart = tickBounds.bottom() tickStop = bounds.bottom() tickDir = -1 axis = 1 elif self.orientation == 'bottom': span = (bounds.topLeft(), bounds.topRight()) tickStart = tickBounds.top() tickStop = bounds.top() tickDir = 1 axis = 1 #print tickStart, tickStop, span ## determine size of this item in pixels points = list(map(self.mapToDevice, span)) if None in points: return lengthInPixels = Point(points[1] - points[0]).length() if lengthInPixels == 0: return # Determine major / minor / subminor axis ticks if self._tickLevels is None: tickLevels = self.tickValues(self.range[0], self.range[1], lengthInPixels) tickStrings = None else: ## parse self.tickLevels into the formats returned by tickLevels() and tickStrings() tickLevels = [] tickStrings = [] for level in self._tickLevels: values = [] strings = [] tickLevels.append((None, values)) tickStrings.append(strings) for val, strn in level: values.append(val) strings.append(strn) ## determine mapping between tick values and local coordinates dif = self.range[1] - self.range[0] if dif == 0: xScale = 1 offset = 0 else: if axis == 0: xScale = -bounds.height() / dif offset = self.range[0] * xScale - bounds.height() else: xScale = bounds.width() / dif offset = self.range[0] * xScale xRange = [x * xScale - offset for x in self.range] xMin = min(xRange) xMax = max(xRange) profiler('init') tickPositions = [] # remembers positions of previously drawn ticks ## compute coordinates to draw ticks ## draw three different intervals, long ticks first tickSpecs = [] for i in range(len(tickLevels)): tickPositions.append([]) ticks = tickLevels[i][1] ## length of tick tickLength = self.style['tickLength'] / ((i*0.5)+1.0) lineAlpha = 255 / (i+1) if self.grid is not False: lineAlpha *= self.grid/255. * np.clip((0.05 * lengthInPixels / (len(ticks)+1)), 0., 1.) for v in ticks: ## determine actual position to draw this tick x = (v * xScale) - offset if x < xMin or x > xMax: ## last check to make sure no out-of-bounds ticks are drawn tickPositions[i].append(None) continue tickPositions[i].append(x) p1 = [x, x] p2 = [x, x] p1[axis] = tickStart p2[axis] = tickStop if self.grid is False: p2[axis] += tickLength*tickDir tickPen = self.pen() color = tickPen.color() color.setAlpha(int(lineAlpha)) tickPen.setColor(color) tickSpecs.append((tickPen, Point(p1), Point(p2))) profiler('compute ticks') if self.style['stopAxisAtTick'][0] is True: minTickPosition = min(map(min, tickPositions)) if axis == 0: stop = max(span[0].y(), minTickPosition) span[0].setY(stop) else: stop = max(span[0].x(), minTickPosition) span[0].setX(stop) if self.style['stopAxisAtTick'][1] is True: maxTickPosition = max(map(max, tickPositions)) if axis == 0: stop = min(span[1].y(), maxTickPosition) span[1].setY(stop) else: stop = min(span[1].x(), maxTickPosition) span[1].setX(stop) axisSpec = (self.pen(), span[0], span[1]) textOffset = self.style['tickTextOffset'][axis] ## spacing between axis and text #if self.style['autoExpandTextSpace'] is True: #textWidth = self.textWidth #textHeight = self.textHeight #else: #textWidth = self.style['tickTextWidth'] ## space allocated for horizontal text #textHeight = self.style['tickTextHeight'] ## space allocated for horizontal text textSize2 = 0 textRects = [] textSpecs = [] ## list of draw # If values are hidden, return early if not self.style['showValues']: return (axisSpec, tickSpecs, textSpecs) for i in range(min(len(tickLevels), self.style['maxTextLevel']+1)): ## Get the list of strings to display for this level if tickStrings is None: spacing, values = tickLevels[i] strings = self.tickStrings(values, self.autoSIPrefixScale * self.scale, spacing) else: strings = tickStrings[i] if len(strings) == 0: continue ## ignore strings belonging to ticks that were previously ignored for j in range(len(strings)): if tickPositions[i][j] is None: strings[j] = None ## Measure density of text; decide whether to draw this level rects = [] for s in strings: if s is None: rects.append(None) else: br = p.boundingRect(QtCore.QRectF(0, 0, 100, 100), QtCore.Qt.AlignCenter, asUnicode(s)) ## boundingRect is usually just a bit too large ## (but this probably depends on per-font metrics?) br.setHeight(br.height() * 0.8) rects.append(br) textRects.append(rects[-1]) if len(textRects) > 0: ## measure all text, make sure there's enough room if axis == 0: textSize = np.sum([r.height() for r in textRects]) textSize2 = np.max([r.width() for r in textRects]) else: textSize = np.sum([r.width() for r in textRects]) textSize2 = np.max([r.height() for r in textRects]) else: textSize = 0 textSize2 = 0 if i > 0: ## always draw top level ## If the strings are too crowded, stop drawing text now. ## We use three different crowding limits based on the number ## of texts drawn so far. textFillRatio = float(textSize) / lengthInPixels finished = False for nTexts, limit in self.style['textFillLimits']: if len(textSpecs) >= nTexts and textFillRatio >= limit: finished = True break if finished: break #spacing, values = tickLevels[best] #strings = self.tickStrings(values, self.scale, spacing) # Determine exactly where tick text should be drawn for j in range(len(strings)): vstr = strings[j] if vstr is None: ## this tick was ignored because it is out of bounds continue vstr = asUnicode(vstr) x = tickPositions[i][j] #textRect = p.boundingRect(QtCore.QRectF(0, 0, 100, 100), QtCore.Qt.AlignCenter, vstr) textRect = rects[j] height = textRect.height() width = textRect.width() #self.textHeight = height offset = max(0,self.style['tickLength']) + textOffset if self.orientation == 'left': textFlags = QtCore.Qt.TextDontClip|QtCore.Qt.AlignRight|QtCore.Qt.AlignVCenter rect = QtCore.QRectF(tickStop-offset-width, x-(height/2), width, height) elif self.orientation == 'right': textFlags = QtCore.Qt.TextDontClip|QtCore.Qt.AlignLeft|QtCore.Qt.AlignVCenter rect = QtCore.QRectF(tickStop+offset, x-(height/2), width, height) elif self.orientation == 'top': textFlags = QtCore.Qt.TextDontClip|QtCore.Qt.AlignCenter|QtCore.Qt.AlignBottom rect = QtCore.QRectF(x-width/2., tickStop-offset-height, width, height) elif self.orientation == 'bottom': textFlags = QtCore.Qt.TextDontClip|QtCore.Qt.AlignCenter|QtCore.Qt.AlignTop rect = QtCore.QRectF(x-width/2., tickStop+offset, width, height) #p.setPen(self.pen()) #p.drawText(rect, textFlags, vstr) textSpecs.append((rect, textFlags, vstr)) profiler('compute text') ## update max text size if needed. self._updateMaxTextSize(textSize2) return (axisSpec, tickSpecs, textSpecs)
[ "def", "generateDrawSpecs", "(", "self", ",", "p", ")", ":", "profiler", "=", "debug", ".", "Profiler", "(", ")", "#bounds = self.boundingRect()", "bounds", "=", "self", ".", "mapRectFromParent", "(", "self", ".", "geometry", "(", ")", ")", "linkedView", "="...
https://github.com/AutodeskRoboticsLab/Mimic/blob/85447f0d346be66988303a6a054473d92f1ed6f4/mimic/scripts/extern/pyqtgraph_0_11_0/pyqtgraph/graphicsItems/AxisItem.py#L849-L1100
magenta/magenta
be6558f1a06984faff6d6949234f5fe9ad0ffdb5
magenta/models/gansynth/lib/networks.py
python
ResolutionSchedule.scale_factor
(self, block_id)
return self._scale_base**(self._num_resolutions - block_id)
Returns the scale factor for network block `block_id`.
Returns the scale factor for network block `block_id`.
[ "Returns", "the", "scale", "factor", "for", "network", "block", "block_id", "." ]
def scale_factor(self, block_id): """Returns the scale factor for network block `block_id`.""" if block_id < 1 or block_id > self._num_resolutions: raise ValueError('`block_id` must be in [1, {}]'.format( self._num_resolutions)) return self._scale_base**(self._num_resolutions - block_id)
[ "def", "scale_factor", "(", "self", ",", "block_id", ")", ":", "if", "block_id", "<", "1", "or", "block_id", ">", "self", ".", "_num_resolutions", ":", "raise", "ValueError", "(", "'`block_id` must be in [1, {}]'", ".", "format", "(", "self", ".", "_num_resolu...
https://github.com/magenta/magenta/blob/be6558f1a06984faff6d6949234f5fe9ad0ffdb5/magenta/models/gansynth/lib/networks.py#L99-L104
google/flax
89e1126cc43588c6946bc85506987dc812909575
flax/core/scope.py
python
Scope.make_rng
(self, name: str)
return random.fold_in(self.rngs[name], self.rng_counters[name])
Generates A PRNGKey from a PRNGSequence with name `name`.
Generates A PRNGKey from a PRNGSequence with name `name`.
[ "Generates", "A", "PRNGKey", "from", "a", "PRNGSequence", "with", "name", "name", "." ]
def make_rng(self, name: str) -> PRNGKey: """Generates A PRNGKey from a PRNGSequence with name `name`.""" if not self.has_rng(name): raise errors.InvalidRngError(f'{self.name} needs PRNG for "{name}"') self._check_valid() self._validate_trace_level() self.rng_counters[name] += 1 return random.fold_in(self.rngs[name], self.rng_counters[name])
[ "def", "make_rng", "(", "self", ",", "name", ":", "str", ")", "->", "PRNGKey", ":", "if", "not", "self", ".", "has_rng", "(", "name", ")", ":", "raise", "errors", ".", "InvalidRngError", "(", "f'{self.name} needs PRNG for \"{name}\"'", ")", "self", ".", "_...
https://github.com/google/flax/blob/89e1126cc43588c6946bc85506987dc812909575/flax/core/scope.py#L567-L574
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/lib/python2.7/sre_compile.py
python
_compile
(code, pattern, flags)
[]
def _compile(code, pattern, flags): # internal: compile a (sub)pattern emit = code.append _len = len LITERAL_CODES = _LITERAL_CODES REPEATING_CODES = _REPEATING_CODES SUCCESS_CODES = _SUCCESS_CODES ASSERT_CODES = _ASSERT_CODES if (flags & SRE_FLAG_IGNORECASE and not (flags & SRE_FLAG_LOCALE) and flags & SRE_FLAG_UNICODE): fixes = _ignorecase_fixes else: fixes = None for op, av in pattern: if op in LITERAL_CODES: if flags & SRE_FLAG_IGNORECASE: lo = _sre.getlower(av, flags) if fixes and lo in fixes: emit(OPCODES[IN_IGNORE]) skip = _len(code); emit(0) if op is NOT_LITERAL: emit(OPCODES[NEGATE]) for k in (lo,) + fixes[lo]: emit(OPCODES[LITERAL]) emit(k) emit(OPCODES[FAILURE]) code[skip] = _len(code) - skip else: emit(OPCODES[OP_IGNORE[op]]) emit(lo) else: emit(OPCODES[op]) emit(av) elif op is IN: if flags & SRE_FLAG_IGNORECASE: emit(OPCODES[OP_IGNORE[op]]) def fixup(literal, flags=flags): return _sre.getlower(literal, flags) else: emit(OPCODES[op]) fixup = None skip = _len(code); emit(0) _compile_charset(av, flags, code, fixup, fixes) code[skip] = _len(code) - skip elif op is ANY: if flags & SRE_FLAG_DOTALL: emit(OPCODES[ANY_ALL]) else: emit(OPCODES[ANY]) elif op in REPEATING_CODES: if flags & SRE_FLAG_TEMPLATE: raise error, "internal: unsupported template operator" emit(OPCODES[REPEAT]) skip = _len(code); emit(0) emit(av[0]) emit(av[1]) _compile(code, av[2], flags) emit(OPCODES[SUCCESS]) code[skip] = _len(code) - skip elif _simple(av) and op is not REPEAT: if op is MAX_REPEAT: emit(OPCODES[REPEAT_ONE]) else: emit(OPCODES[MIN_REPEAT_ONE]) skip = _len(code); emit(0) emit(av[0]) emit(av[1]) _compile(code, av[2], flags) emit(OPCODES[SUCCESS]) code[skip] = _len(code) - skip else: emit(OPCODES[REPEAT]) skip = _len(code); emit(0) emit(av[0]) emit(av[1]) _compile(code, av[2], flags) code[skip] = _len(code) - skip if op is MAX_REPEAT: emit(OPCODES[MAX_UNTIL]) else: emit(OPCODES[MIN_UNTIL]) elif op is SUBPATTERN: if av[0]: emit(OPCODES[MARK]) emit((av[0]-1)*2) # _compile_info(code, av[1], flags) _compile(code, av[1], flags) if av[0]: emit(OPCODES[MARK]) emit((av[0]-1)*2+1) elif op in SUCCESS_CODES: emit(OPCODES[op]) elif op in ASSERT_CODES: emit(OPCODES[op]) skip = _len(code); emit(0) if av[0] >= 0: emit(0) # look ahead else: lo, hi = av[1].getwidth() if lo != hi: raise error, "look-behind requires fixed-width pattern" emit(lo) # look behind _compile(code, av[1], flags) emit(OPCODES[SUCCESS]) code[skip] = _len(code) - skip elif op is CALL: emit(OPCODES[op]) skip = _len(code); emit(0) _compile(code, av, flags) emit(OPCODES[SUCCESS]) code[skip] = _len(code) - skip elif op is AT: emit(OPCODES[op]) if flags & SRE_FLAG_MULTILINE: av = AT_MULTILINE.get(av, av) if flags & SRE_FLAG_LOCALE: av = AT_LOCALE.get(av, av) elif flags & SRE_FLAG_UNICODE: av = AT_UNICODE.get(av, av) emit(ATCODES[av]) elif op is BRANCH: emit(OPCODES[op]) tail = [] tailappend = tail.append for av in av[1]: skip = _len(code); emit(0) # _compile_info(code, av, flags) _compile(code, av, flags) emit(OPCODES[JUMP]) tailappend(_len(code)); emit(0) code[skip] = _len(code) - skip emit(0) # end of branch for tail in tail: code[tail] = _len(code) - tail elif op is CATEGORY: emit(OPCODES[op]) if flags & SRE_FLAG_LOCALE: av = CH_LOCALE[av] elif flags & SRE_FLAG_UNICODE: av = CH_UNICODE[av] emit(CHCODES[av]) elif op is GROUPREF: if flags & SRE_FLAG_IGNORECASE: emit(OPCODES[OP_IGNORE[op]]) else: emit(OPCODES[op]) emit(av-1) elif op is GROUPREF_EXISTS: emit(OPCODES[op]) emit(av[0]-1) skipyes = _len(code); emit(0) _compile(code, av[1], flags) if av[2]: emit(OPCODES[JUMP]) skipno = _len(code); emit(0) code[skipyes] = _len(code) - skipyes + 1 _compile(code, av[2], flags) code[skipno] = _len(code) - skipno else: code[skipyes] = _len(code) - skipyes + 1 else: raise ValueError, ("unsupported operand type", op)
[ "def", "_compile", "(", "code", ",", "pattern", ",", "flags", ")", ":", "# internal: compile a (sub)pattern", "emit", "=", "code", ".", "append", "_len", "=", "len", "LITERAL_CODES", "=", "_LITERAL_CODES", "REPEATING_CODES", "=", "_REPEATING_CODES", "SUCCESS_CODES",...
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/sre_compile.py#L64-L226
eliben/pyelftools
8f7a0becaface09435c4374947548b7851e3d1a2
elftools/construct/adapters.py
python
NoneOf._validate
(self, obj, context)
return obj not in self.invalids
[]
def _validate(self, obj, context): return obj not in self.invalids
[ "def", "_validate", "(", "self", ",", "obj", ",", "context", ")", ":", "return", "obj", "not", "in", "self", ".", "invalids" ]
https://github.com/eliben/pyelftools/blob/8f7a0becaface09435c4374947548b7851e3d1a2/elftools/construct/adapters.py#L469-L470
fortharris/Pcode
147962d160a834c219e12cb456abc130826468e4
rope/refactor/sourceutils.py
python
find_minimum_indents
(source_code)
return result
[]
def find_minimum_indents(source_code): result = 80 lines = source_code.split('\n') for line in lines: if line.strip() == '': continue result = min(result, codeanalyze.count_line_indents(line)) return result
[ "def", "find_minimum_indents", "(", "source_code", ")", ":", "result", "=", "80", "lines", "=", "source_code", ".", "split", "(", "'\\n'", ")", "for", "line", "in", "lines", ":", "if", "line", ".", "strip", "(", ")", "==", "''", ":", "continue", "resul...
https://github.com/fortharris/Pcode/blob/147962d160a834c219e12cb456abc130826468e4/rope/refactor/sourceutils.py#L8-L15
huggingface/transformers
623b4f7c63f60cce917677ee704d6c93ee960b4b
examples/research_projects/bertabs/modeling_bertabs.py
python
TransformerDecoderState.map_batch_fn
(self, fn)
[]
def map_batch_fn(self, fn): def _recursive_map(struct, batch_dim=0): for k, v in struct.items(): if v is not None: if isinstance(v, dict): _recursive_map(v) else: struct[k] = fn(v, batch_dim) self.src = fn(self.src, 0) if self.cache is not None: _recursive_map(self.cache)
[ "def", "map_batch_fn", "(", "self", ",", "fn", ")", ":", "def", "_recursive_map", "(", "struct", ",", "batch_dim", "=", "0", ")", ":", "for", "k", ",", "v", "in", "struct", ".", "items", "(", ")", ":", "if", "v", "is", "not", "None", ":", "if", ...
https://github.com/huggingface/transformers/blob/623b4f7c63f60cce917677ee704d6c93ee960b4b/examples/research_projects/bertabs/modeling_bertabs.py#L644-L655
WolframResearch/WolframClientForPython
27cffef560eea8d16c02fe4086f42363604284b6
wolframclient/serializers/encoders/pandas.py
python
normalized_prop_pandas_series_head
(serializer)
return prop
Check property `pandas_series_head` only if specified (not None).
Check property `pandas_series_head` only if specified (not None).
[ "Check", "property", "pandas_series_head", "only", "if", "specified", "(", "not", "None", ")", "." ]
def normalized_prop_pandas_series_head(serializer): """ Check property `pandas_series_head` only if specified (not None). """ prop = serializer.get_property("pandas_series_head", d=None) if prop and prop not in PANDAS_PROPERTIES["pandas_series_head"]: raise ValueError( "Invalid value for property 'pandas_series_head'. Expecting one of (%s), got %s." % (", ".join(PANDAS_PROPERTIES["pandas_series_head"]), prop) ) return prop
[ "def", "normalized_prop_pandas_series_head", "(", "serializer", ")", ":", "prop", "=", "serializer", ".", "get_property", "(", "\"pandas_series_head\"", ",", "d", "=", "None", ")", "if", "prop", "and", "prop", "not", "in", "PANDAS_PROPERTIES", "[", "\"pandas_serie...
https://github.com/WolframResearch/WolframClientForPython/blob/27cffef560eea8d16c02fe4086f42363604284b6/wolframclient/serializers/encoders/pandas.py#L130-L138