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
openshift/openshift-tools
1188778e728a6e4781acf728123e5b356380fe6f
openshift/installer/vendored/openshift-ansible-3.10.0-0.29.0/roles/openshift_health_checker/action_plugins/openshift_health_check.py
python
describe_tags
(check_classes)
return sorted(tags)
Return a sorted list of strings describing tags and the checks they include.
Return a sorted list of strings describing tags and the checks they include.
[ "Return", "a", "sorted", "list", "of", "strings", "describing", "tags", "and", "the", "checks", "they", "include", "." ]
def describe_tags(check_classes): """Return a sorted list of strings describing tags and the checks they include.""" tag_checks = defaultdict(list) for cls in check_classes: for tag in cls.tags: tag_checks[tag].append(cls.name) tags = [ '@{} = {}'.format(tag, ','.join(sorted(checks))) for tag, checks in tag_checks.items() ] return sorted(tags)
[ "def", "describe_tags", "(", "check_classes", ")", ":", "tag_checks", "=", "defaultdict", "(", "list", ")", "for", "cls", "in", "check_classes", ":", "for", "tag", "in", "cls", ".", "tags", ":", "tag_checks", "[", "tag", "]", ".", "append", "(", "cls", ...
https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/openshift/installer/vendored/openshift-ansible-3.10.0-0.29.0/roles/openshift_health_checker/action_plugins/openshift_health_check.py#L130-L140
pydoit/doit
cf7edfbe73fafebd1b2a6f1d3be8b69fde41383d
doit/dependency.py
python
JsonDB.remove_all
(self)
remove saved dependencies from DB for all tasks
remove saved dependencies from DB for all tasks
[ "remove", "saved", "dependencies", "from", "DB", "for", "all", "tasks" ]
def remove_all(self): """remove saved dependencies from DB for all tasks""" self._db = {}
[ "def", "remove_all", "(", "self", ")", ":", "self", ".", "_db", "=", "{", "}" ]
https://github.com/pydoit/doit/blob/cf7edfbe73fafebd1b2a6f1d3be8b69fde41383d/doit/dependency.py#L128-L130
NoGameNoLife00/mybolg
afe17ea5bfe405e33766e5682c43a4262232ee12
libs/flask_admin/form/rules.py
python
RuleSet.__iter__
(self)
Iterate through registered rules.
Iterate through registered rules.
[ "Iterate", "through", "registered", "rules", "." ]
def __iter__(self): """ Iterate through registered rules. """ for r in self.rules: yield r
[ "def", "__iter__", "(", "self", ")", ":", "for", "r", "in", "self", ".", "rules", ":", "yield", "r" ]
https://github.com/NoGameNoLife00/mybolg/blob/afe17ea5bfe405e33766e5682c43a4262232ee12/libs/flask_admin/form/rules.py#L378-L383
jython/jython3
def4f8ec47cb7a9c799ea4c745f12badf92c5769
Lib/datetime.py
python
time.__hash__
(self)
return self._hashcode
Hash.
Hash.
[ "Hash", "." ]
def __hash__(self): """Hash.""" if self._hashcode == -1: tzoff = self._utcoffset() if not tzoff: # zero or None self._hashcode = hash(self._getstate()[0]) else: h, m = divmod(self.hour * 60 + self.minute - tzoff, 60) if 0 <= h < 24: self._hashcode = hash(time(h, m, self.second, self.microsecond)) else: self._hashcode = hash((h, m, self.second, self.microsecond)) return self._hashcode
[ "def", "__hash__", "(", "self", ")", ":", "if", "self", ".", "_hashcode", "==", "-", "1", ":", "tzoff", "=", "self", ".", "_utcoffset", "(", ")", "if", "not", "tzoff", ":", "# zero or None", "self", ".", "_hashcode", "=", "hash", "(", "self", ".", ...
https://github.com/jython/jython3/blob/def4f8ec47cb7a9c799ea4c745f12badf92c5769/Lib/datetime.py#L1306-L1318
hzlzh/AlfredWorkflow.com
7055f14f6922c80ea5943839eb0caff11ae57255
Sources/Workflows/alfred-pushbullet/lib/requests/packages/urllib3/util/connection.py
python
create_connection
(address, timeout=socket._GLOBAL_DEFAULT_TIMEOUT, source_address=None, socket_options=None)
Connect to *address* and return the socket object. Convenience function. Connect to *address* (a 2-tuple ``(host, port)``) and return the socket object. Passing the optional *timeout* parameter will set the timeout on the socket instance before attempting to connect. If no *timeout* is supplied, the global default timeout setting returned by :func:`getdefaulttimeout` is used. If *source_address* is set it must be a tuple of (host, port) for the socket to bind as a source address before making the connection. An host of '' or port 0 tells the OS to use the default.
Connect to *address* and return the socket object.
[ "Connect", "to", "*", "address", "*", "and", "return", "the", "socket", "object", "." ]
def create_connection(address, timeout=socket._GLOBAL_DEFAULT_TIMEOUT, source_address=None, socket_options=None): """Connect to *address* and return the socket object. Convenience function. Connect to *address* (a 2-tuple ``(host, port)``) and return the socket object. Passing the optional *timeout* parameter will set the timeout on the socket instance before attempting to connect. If no *timeout* is supplied, the global default timeout setting returned by :func:`getdefaulttimeout` is used. If *source_address* is set it must be a tuple of (host, port) for the socket to bind as a source address before making the connection. An host of '' or port 0 tells the OS to use the default. """ host, port = address if host.startswith('['): host = host.strip('[]') err = None for res in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM): af, socktype, proto, canonname, sa = res sock = None try: sock = socket.socket(af, socktype, proto) # If provided, set socket level options before connecting. # This is the only addition urllib3 makes to this function. _set_socket_options(sock, socket_options) if timeout is not socket._GLOBAL_DEFAULT_TIMEOUT: sock.settimeout(timeout) if source_address: sock.bind(source_address) sock.connect(sa) return sock except socket.error as e: err = e if sock is not None: sock.close() sock = None if err is not None: raise err raise socket.error("getaddrinfo returns an empty list")
[ "def", "create_connection", "(", "address", ",", "timeout", "=", "socket", ".", "_GLOBAL_DEFAULT_TIMEOUT", ",", "source_address", "=", "None", ",", "socket_options", "=", "None", ")", ":", "host", ",", "port", "=", "address", "if", "host", ".", "startswith", ...
https://github.com/hzlzh/AlfredWorkflow.com/blob/7055f14f6922c80ea5943839eb0caff11ae57255/Sources/Workflows/alfred-pushbullet/lib/requests/packages/urllib3/util/connection.py#L49-L93
tp4a/teleport
1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad
server/www/packages/packages-windows/x86/pyasn1/type/constraint.py
python
AbstractConstraint.isSubTypeOf
(self, otherConstraint)
return (otherConstraint is self or not self or otherConstraint == self or otherConstraint in self._valueMap)
[]
def isSubTypeOf(self, otherConstraint): return (otherConstraint is self or not self or otherConstraint == self or otherConstraint in self._valueMap)
[ "def", "isSubTypeOf", "(", "self", ",", "otherConstraint", ")", ":", "return", "(", "otherConstraint", "is", "self", "or", "not", "self", "or", "otherConstraint", "==", "self", "or", "otherConstraint", "in", "self", ".", "_valueMap", ")" ]
https://github.com/tp4a/teleport/blob/1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad/server/www/packages/packages-windows/x86/pyasn1/type/constraint.py#L93-L97
kozec/sc-controller
ce92c773b8b26f6404882e9209aff212c4053170
scc/lib/daemon.py
python
Daemon.write_pid
(self)
Write pid file
Write pid file
[ "Write", "pid", "file" ]
def write_pid(self): """Write pid file""" atexit.register(self.delpid) pid = str(os.getpid()) with open(self.pidfile, 'w+') as fd: fd.write(pid + '\n')
[ "def", "write_pid", "(", "self", ")", ":", "atexit", ".", "register", "(", "self", ".", "delpid", ")", "pid", "=", "str", "(", "os", ".", "getpid", "(", ")", ")", "with", "open", "(", "self", ".", "pidfile", ",", "'w+'", ")", "as", "fd", ":", "...
https://github.com/kozec/sc-controller/blob/ce92c773b8b26f6404882e9209aff212c4053170/scc/lib/daemon.py#L65-L71
metapensiero/metapensiero.pj
0e243d70bfb8aabfa8fe45bd1338e2959fc667c3
src/metapensiero/pj/api.py
python
translate_file
(src_filename, dst_filename=None, map_filename=None, enable_es6=False, enable_stage3=False, inline_map=False)
Translate the given python source file to ES6 Javascript.
Translate the given python source file to ES6 Javascript.
[ "Translate", "the", "given", "python", "source", "file", "to", "ES6", "Javascript", "." ]
def translate_file(src_filename, dst_filename=None, map_filename=None, enable_es6=False, enable_stage3=False, inline_map=False): """Translate the given python source file to ES6 Javascript.""" dst_filename, map_filename, src_relpath, map_relpath = _calc_file_names( src_filename, dst_filename, map_filename ) src_text = open(src_filename).readlines() js_text, src_map = translates(src_text, True, src_relpath, enable_es6=enable_es6, enable_stage3=enable_stage3) if inline_map: js_text += src_map.stringify(inline_comment=True) else: js_text += '\n//# sourceMappingURL=%s\n' % map_relpath with open(dst_filename, 'w') as dst: dst.write(js_text) if not inline_map: with open(map_filename, 'w') as map: map.write(src_map.stringify())
[ "def", "translate_file", "(", "src_filename", ",", "dst_filename", "=", "None", ",", "map_filename", "=", "None", ",", "enable_es6", "=", "False", ",", "enable_stage3", "=", "False", ",", "inline_map", "=", "False", ")", ":", "dst_filename", ",", "map_filename...
https://github.com/metapensiero/metapensiero.pj/blob/0e243d70bfb8aabfa8fe45bd1338e2959fc667c3/src/metapensiero/pj/api.py#L61-L80
ilius/pyglossary
d599b3beda3ae17642af5debd83bb991148e6425
pyglossary/plugins/appledict/__init__.py
python
abspath_or_None
(path)
return os.path.abspath(os.path.expanduser(path)) if path else None
[]
def abspath_or_None(path): return os.path.abspath(os.path.expanduser(path)) if path else None
[ "def", "abspath_or_None", "(", "path", ")", ":", "return", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "expanduser", "(", "path", ")", ")", "if", "path", "else", "None" ]
https://github.com/ilius/pyglossary/blob/d599b3beda3ae17642af5debd83bb991148e6425/pyglossary/plugins/appledict/__init__.py#L102-L103
sahana/eden
1696fa50e90ce967df69f66b571af45356cc18da
modules/s3db/hrm.py
python
HRSkillModel.hrm_certification_onaccept
(form)
Ensure that Skills are Populated from Certifications - called both onaccept & ondelete
Ensure that Skills are Populated from Certifications - called both onaccept & ondelete
[ "Ensure", "that", "Skills", "are", "Populated", "from", "Certifications", "-", "called", "both", "onaccept", "&", "ondelete" ]
def hrm_certification_onaccept(form): """ Ensure that Skills are Populated from Certifications - called both onaccept & ondelete """ # Deletion and update have a different format delete = False try: record_id = form.vars.id except AttributeError: # Delete record_id = form.id delete = True # Read the full record db = current.db table = db.hrm_certification record = db(table.id == record_id).select(table.person_id, table.training_id, table.number, limitby = (0, 1), ).first() if delete: person_id = form.person_id training_id = form.training_id else: person_id = record.person_id training_id = record.training_id if not person_id: # This record is being created as a direct component of the Training, # in order to set the Number (RMS usecase). # Find the other record (created onaccept of training) query = (table.training_id == training_id) & \ (table.id != record_id) original = db(query).select(table.id, limitby = (0, 1), ).first() if original: # Update it with the number number = record.number original.update_record(number = number) # Delete this extraneous record db(table.id == record_id).delete() # Don't update any competencies return ctable = db.hrm_competency cstable = db.hrm_certificate_skill # Drop all existing competencies which came from certification # - this is a lot easier than selective deletion # @ToDo: Avoid this method as it will break Inline Component Updates # if we ever use those (see hrm_training_onaccept) query = (ctable.person_id == person_id) & \ (ctable.from_certification == True) db(query).delete() # Figure out which competencies we're _supposed_ to have. # FIXME unlimited select query = (table.person_id == person_id) & \ (table.certificate_id == cstable.certificate_id) & \ (cstable.skill_id == db.hrm_skill.id) certifications = db(query).select() # Add these competencies back in. # FIXME unlimited select inside loop # FIXME multiple implicit db queries inside nested loop # FIXME db.delete inside nested loop # FIXME unnecessary select (sub-select in Python loop) for certification in certifications: skill = certification["hrm_skill"] cert = certification["hrm_certificate_skill"] query = (ctable.person_id == person_id) & \ (ctable.skill_id == skill.id) existing = db(query).select() better = True for e in existing: if e.competency_id.priority > cert.competency_id.priority: db(ctable.id == e.id).delete() else: better = False break if better: ctable.update_or_insert(person_id = person_id, competency_id = cert.competency_id, skill_id = skill.id, comments = "Added by certification", from_certification = True, )
[ "def", "hrm_certification_onaccept", "(", "form", ")", ":", "# Deletion and update have a different format", "delete", "=", "False", "try", ":", "record_id", "=", "form", ".", "vars", ".", "id", "except", "AttributeError", ":", "# Delete", "record_id", "=", "form", ...
https://github.com/sahana/eden/blob/1696fa50e90ce967df69f66b571af45356cc18da/modules/s3db/hrm.py#L3787-L3881
huggingface/transformers
623b4f7c63f60cce917677ee704d6c93ee960b4b
src/transformers/utils/dummy_pt_objects.py
python
AutoModelForSpeechSeq2Seq.__init__
(self, *args, **kwargs)
[]
def __init__(self, *args, **kwargs): requires_backends(self, ["torch"])
[ "def", "__init__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "requires_backends", "(", "self", ",", "[", "\"torch\"", "]", ")" ]
https://github.com/huggingface/transformers/blob/623b4f7c63f60cce917677ee704d6c93ee960b4b/src/transformers/utils/dummy_pt_objects.py#L594-L595
googlearchive/appengine-flask-skeleton
8c25461d003a0bd99a9ff3b339c2791ee6919242
lib/werkzeug/wrappers.py
python
BaseRequest.values
(self)
return CombinedMultiDict(args)
Combined multi dict for :attr:`args` and :attr:`form`.
Combined multi dict for :attr:`args` and :attr:`form`.
[ "Combined", "multi", "dict", "for", ":", "attr", ":", "args", "and", ":", "attr", ":", "form", "." ]
def values(self): """Combined multi dict for :attr:`args` and :attr:`form`.""" args = [] for d in self.args, self.form: if not isinstance(d, MultiDict): d = MultiDict(d) args.append(d) return CombinedMultiDict(args)
[ "def", "values", "(", "self", ")", ":", "args", "=", "[", "]", "for", "d", "in", "self", ".", "args", ",", "self", ".", "form", ":", "if", "not", "isinstance", "(", "d", ",", "MultiDict", ")", ":", "d", "=", "MultiDict", "(", "d", ")", "args", ...
https://github.com/googlearchive/appengine-flask-skeleton/blob/8c25461d003a0bd99a9ff3b339c2791ee6919242/lib/werkzeug/wrappers.py#L496-L503
pyg-team/pytorch_geometric
b920e9a3a64e22c8356be55301c88444ff051cae
benchmark/runtime/dgl/train.py
python
train_runtime
(model, data, epochs, device)
return t_end - t_start
[]
def train_runtime(model, data, epochs, device): if hasattr(data, 'features'): x = torch.tensor(data.features, dtype=torch.float, device=device) else: x = None mask = data.train_mask if hasattr(data, 'train_mask') else data.train_idx y = torch.tensor(data.labels, dtype=torch.long, device=device)[mask] model = model.to(device) model.train() optimizer = torch.optim.Adam(model.parameters(), lr=0.01) if torch.cuda.is_available(): torch.cuda.synchronize() t_start = time.perf_counter() for epoch in range(epochs): optimizer.zero_grad() out = model(x) loss = F.nll_loss(out[mask], y.view(-1)) loss.backward() optimizer.step() if torch.cuda.is_available(): torch.cuda.synchronize() t_end = time.perf_counter() return t_end - t_start
[ "def", "train_runtime", "(", "model", ",", "data", ",", "epochs", ",", "device", ")", ":", "if", "hasattr", "(", "data", ",", "'features'", ")", ":", "x", "=", "torch", ".", "tensor", "(", "data", ".", "features", ",", "dtype", "=", "torch", ".", "...
https://github.com/pyg-team/pytorch_geometric/blob/b920e9a3a64e22c8356be55301c88444ff051cae/benchmark/runtime/dgl/train.py#L7-L34
tendenci/tendenci
0f2c348cc0e7d41bc56f50b00ce05544b083bf1d
tendenci/apps/corporate_memberships/templatetags/corporate_memberships_tags.py
python
corpmemb_current_app
(context, user, corp_memb=None)
return context
[]
def corpmemb_current_app(context, user, corp_memb=None): context.update({ 'app_object': corp_memb, "user": user }) return context
[ "def", "corpmemb_current_app", "(", "context", ",", "user", ",", "corp_memb", "=", "None", ")", ":", "context", ".", "update", "(", "{", "'app_object'", ":", "corp_memb", ",", "\"user\"", ":", "user", "}", ")", "return", "context" ]
https://github.com/tendenci/tendenci/blob/0f2c348cc0e7d41bc56f50b00ce05544b083bf1d/tendenci/apps/corporate_memberships/templatetags/corporate_memberships_tags.py#L75-L80
munificent/magpie
f5138e3d316ec1a664b5eadba1bcc8573d3faca3
dep/gyp/pylib/gyp/generator/make.py
python
MakefileWriter.Absolutify
(self, path)
return os.path.normpath(os.path.join(self.path, path))
Convert a subdirectory-relative path into a base-relative path. Skips over paths that contain variables.
Convert a subdirectory-relative path into a base-relative path. Skips over paths that contain variables.
[ "Convert", "a", "subdirectory", "-", "relative", "path", "into", "a", "base", "-", "relative", "path", ".", "Skips", "over", "paths", "that", "contain", "variables", "." ]
def Absolutify(self, path): """Convert a subdirectory-relative path into a base-relative path. Skips over paths that contain variables.""" if '$(' in path: # Don't call normpath in this case, as it might collapse the # path too aggressively if it features '..'. However it's still # important to strip trailing slashes. return path.rstrip('/') return os.path.normpath(os.path.join(self.path, path))
[ "def", "Absolutify", "(", "self", ",", "path", ")", ":", "if", "'$('", "in", "path", ":", "# Don't call normpath in this case, as it might collapse the", "# path too aggressively if it features '..'. However it's still", "# important to strip trailing slashes.", "return", "path", ...
https://github.com/munificent/magpie/blob/f5138e3d316ec1a664b5eadba1bcc8573d3faca3/dep/gyp/pylib/gyp/generator/make.py#L1846-L1854
ConsenSys/mythril
d00152f8e4d925c7749d63b533152a937e1dd516
mythril/plugin/discovery.py
python
PluginDiscovery.is_installed
(self, plugin_name: str)
return plugin_name in self.installed_plugins.keys()
Returns whether there is python package with a plugin with plugin_name
Returns whether there is python package with a plugin with plugin_name
[ "Returns", "whether", "there", "is", "python", "package", "with", "a", "plugin", "with", "plugin_name" ]
def is_installed(self, plugin_name: str) -> bool: """Returns whether there is python package with a plugin with plugin_name""" return plugin_name in self.installed_plugins.keys()
[ "def", "is_installed", "(", "self", ",", "plugin_name", ":", "str", ")", "->", "bool", ":", "return", "plugin_name", "in", "self", ".", "installed_plugins", ".", "keys", "(", ")" ]
https://github.com/ConsenSys/mythril/blob/d00152f8e4d925c7749d63b533152a937e1dd516/mythril/plugin/discovery.py#L29-L31
linxid/Machine_Learning_Study_Path
558e82d13237114bbb8152483977806fc0c222af
Machine Learning In Action/Chapter5-LogisticRegression/venv/Lib/site-packages/pip/commands/show.py
python
search_packages_info
(query)
Gather details from installed distributions. Print distribution name, version, location, and installed files. Installed files requires a pip generated 'installed-files.txt' in the distributions '.egg-info' directory.
Gather details from installed distributions. Print distribution name, version, location, and installed files. Installed files requires a pip generated 'installed-files.txt' in the distributions '.egg-info' directory.
[ "Gather", "details", "from", "installed", "distributions", ".", "Print", "distribution", "name", "version", "location", "and", "installed", "files", ".", "Installed", "files", "requires", "a", "pip", "generated", "installed", "-", "files", ".", "txt", "in", "the...
def search_packages_info(query): """ Gather details from installed distributions. Print distribution name, version, location, and installed files. Installed files requires a pip generated 'installed-files.txt' in the distributions '.egg-info' directory. """ installed = {} for p in pkg_resources.working_set: installed[canonicalize_name(p.project_name)] = p query_names = [canonicalize_name(name) for name in query] for dist in [installed[pkg] for pkg in query_names if pkg in installed]: package = { 'name': dist.project_name, 'version': dist.version, 'location': dist.location, 'requires': [dep.project_name for dep in dist.requires()], } file_list = None metadata = None if isinstance(dist, pkg_resources.DistInfoDistribution): # RECORDs should be part of .dist-info metadatas if dist.has_metadata('RECORD'): lines = dist.get_metadata_lines('RECORD') paths = [l.split(',')[0] for l in lines] paths = [os.path.join(dist.location, p) for p in paths] file_list = [os.path.relpath(p, dist.location) for p in paths] if dist.has_metadata('METADATA'): metadata = dist.get_metadata('METADATA') else: # Otherwise use pip's log for .egg-info's if dist.has_metadata('installed-files.txt'): paths = dist.get_metadata_lines('installed-files.txt') paths = [os.path.join(dist.egg_info, p) for p in paths] file_list = [os.path.relpath(p, dist.location) for p in paths] if dist.has_metadata('PKG-INFO'): metadata = dist.get_metadata('PKG-INFO') if dist.has_metadata('entry_points.txt'): entry_points = dist.get_metadata_lines('entry_points.txt') package['entry_points'] = entry_points if dist.has_metadata('INSTALLER'): for line in dist.get_metadata_lines('INSTALLER'): if line.strip(): package['installer'] = line.strip() break # @todo: Should pkg_resources.Distribution have a # `get_pkg_info` method? feed_parser = FeedParser() feed_parser.feed(metadata) pkg_info_dict = feed_parser.close() for key in ('metadata-version', 'summary', 'home-page', 'author', 'author-email', 'license'): package[key] = pkg_info_dict.get(key) # It looks like FeedParser cannot deal with repeated headers classifiers = [] for line in metadata.splitlines(): if line.startswith('Classifier: '): classifiers.append(line[len('Classifier: '):]) package['classifiers'] = classifiers if file_list: package['files'] = sorted(file_list) yield package
[ "def", "search_packages_info", "(", "query", ")", ":", "installed", "=", "{", "}", "for", "p", "in", "pkg_resources", ".", "working_set", ":", "installed", "[", "canonicalize_name", "(", "p", ".", "project_name", ")", "]", "=", "p", "query_names", "=", "["...
https://github.com/linxid/Machine_Learning_Study_Path/blob/558e82d13237114bbb8152483977806fc0c222af/Machine Learning In Action/Chapter5-LogisticRegression/venv/Lib/site-packages/pip/commands/show.py#L47-L117
keiffster/program-y
8c99b56f8c32f01a7b9887b5daae9465619d0385
src/programy/clients/restful/flask/kik/config.py
python
KikConfiguration.bot_name
(self)
return self._bot_name
[]
def bot_name(self): return self._bot_name
[ "def", "bot_name", "(", "self", ")", ":", "return", "self", ".", "_bot_name" ]
https://github.com/keiffster/program-y/blob/8c99b56f8c32f01a7b9887b5daae9465619d0385/src/programy/clients/restful/flask/kik/config.py#L31-L32
Trinkle23897/tuixue.online-visa
36860ac2214630986435a42bf13345bcfcab81e4
backend/url.py
python
URLQueryParam.set
(self, key, value=None)
URLSearchParam.set
URLSearchParam.set
[ "URLSearchParam", ".", "set" ]
def set(self, key, value=None): """ URLSearchParam.set""" if value is None: return self.query_param[key] = value
[ "def", "set", "(", "self", ",", "key", ",", "value", "=", "None", ")", ":", "if", "value", "is", "None", ":", "return", "self", ".", "query_param", "[", "key", "]", "=", "value" ]
https://github.com/Trinkle23897/tuixue.online-visa/blob/36860ac2214630986435a42bf13345bcfcab81e4/backend/url.py#L64-L69
cloudant/bigcouch
8e9c1ec0ed1676ff152f10658f5c83a1a91fa8fe
couchjs/scons/scons-local-2.0.1/SCons/SConf.py
python
CheckHeader
(context, header, include_quotes = '<>', language = None)
return not res
A test for a C or C++ header file.
A test for a C or C++ header file.
[ "A", "test", "for", "a", "C", "or", "C", "++", "header", "file", "." ]
def CheckHeader(context, header, include_quotes = '<>', language = None): """ A test for a C or C++ header file. """ prog_prefix, hdr_to_check = \ createIncludesFromHeaders(header, 1, include_quotes) res = SCons.Conftest.CheckHeader(context, hdr_to_check, prog_prefix, language = language, include_quotes = include_quotes) context.did_show_result = 1 return not res
[ "def", "CheckHeader", "(", "context", ",", "header", ",", "include_quotes", "=", "'<>'", ",", "language", "=", "None", ")", ":", "prog_prefix", ",", "hdr_to_check", "=", "createIncludesFromHeaders", "(", "header", ",", "1", ",", "include_quotes", ")", "res", ...
https://github.com/cloudant/bigcouch/blob/8e9c1ec0ed1676ff152f10658f5c83a1a91fa8fe/couchjs/scons/scons-local-2.0.1/SCons/SConf.py#L930-L940
home-assistant/core
265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1
homeassistant/components/vasttrafik/sensor.py
python
VasttrafikDepartureSensor.get_station_id
(self, location)
return station_info
Get the station ID.
Get the station ID.
[ "Get", "the", "station", "ID", "." ]
def get_station_id(self, location): """Get the station ID.""" if location.isdecimal(): station_info = {"station_name": location, "station_id": location} else: station_id = self._planner.location_name(location)[0]["id"] station_info = {"station_name": location, "station_id": station_id} return station_info
[ "def", "get_station_id", "(", "self", ",", "location", ")", ":", "if", "location", ".", "isdecimal", "(", ")", ":", "station_info", "=", "{", "\"station_name\"", ":", "location", ",", "\"station_id\"", ":", "location", "}", "else", ":", "station_id", "=", ...
https://github.com/home-assistant/core/blob/265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1/homeassistant/components/vasttrafik/sensor.py#L98-L105
pupil-labs/pupil
a712f94c9f38afddd64c841362e167b8ce293769
pupil_src/shared_modules/gaze_mapping/gazer_3d/utils.py
python
find_rigid_transform
(A, B)
return rotation_matrix, translation_vector
Calculates the transformation between two coordinate systems using SVD. This function determines the rotation matrix (R) and the translation vector (L) for a rigid body after the following transformation [1]_, [2]_: B = R*A + L + err, where A and B represents the rigid body in different instants and err is an aleatory noise (which should be zero for a perfect rigid body). Adapted from: https://github.com/demotu/BMC/blob/master/functions/svdt.py
Calculates the transformation between two coordinate systems using SVD. This function determines the rotation matrix (R) and the translation vector (L) for a rigid body after the following transformation [1]_, [2]_: B = R*A + L + err, where A and B represents the rigid body in different instants and err is an aleatory noise (which should be zero for a perfect rigid body).
[ "Calculates", "the", "transformation", "between", "two", "coordinate", "systems", "using", "SVD", ".", "This", "function", "determines", "the", "rotation", "matrix", "(", "R", ")", "and", "the", "translation", "vector", "(", "L", ")", "for", "a", "rigid", "b...
def find_rigid_transform(A, B): """Calculates the transformation between two coordinate systems using SVD. This function determines the rotation matrix (R) and the translation vector (L) for a rigid body after the following transformation [1]_, [2]_: B = R*A + L + err, where A and B represents the rigid body in different instants and err is an aleatory noise (which should be zero for a perfect rigid body). Adapted from: https://github.com/demotu/BMC/blob/master/functions/svdt.py """ assert A.shape == B.shape and A.ndim == 2 and A.shape[1] == 3 A_centroid = np.mean(A, axis=0) B_centroid = np.mean(B, axis=0) M = np.dot((B - B_centroid).T, (A - A_centroid)) U, S, Vt = np.linalg.svd(M) rotation_matrix = np.dot( U, np.dot(np.diag([1, 1, np.linalg.det(np.dot(U, Vt))]), Vt) ) translation_vector = B_centroid - np.dot(rotation_matrix, A_centroid) return rotation_matrix, translation_vector
[ "def", "find_rigid_transform", "(", "A", ",", "B", ")", ":", "assert", "A", ".", "shape", "==", "B", ".", "shape", "and", "A", ".", "ndim", "==", "2", "and", "A", ".", "shape", "[", "1", "]", "==", "3", "A_centroid", "=", "np", ".", "mean", "("...
https://github.com/pupil-labs/pupil/blob/a712f94c9f38afddd64c841362e167b8ce293769/pupil_src/shared_modules/gaze_mapping/gazer_3d/utils.py#L78-L100
facebookresearch/TaBERT
74aa4a88783825e71b71d1d0fdbc6b338047eea9
preprocess/WikiExtractor.py
python
replaceExternalLinks
(text)
return s + text[cur:]
https://www.mediawiki.org/wiki/Help:Links#External_links [URL anchor text]
https://www.mediawiki.org/wiki/Help:Links#External_links [URL anchor text]
[ "https", ":", "//", "www", ".", "mediawiki", ".", "org", "/", "wiki", "/", "Help", ":", "Links#External_links", "[", "URL", "anchor", "text", "]" ]
def replaceExternalLinks(text): """ https://www.mediawiki.org/wiki/Help:Links#External_links [URL anchor text] """ s = '' cur = 0 for m in ExtLinkBracketedRegex.finditer(text): s += text[cur:m.start()] cur = m.end() url = m.group(1) label = m.group(3) # # The characters '<' and '>' (which were escaped by # # removeHTMLtags()) should not be included in # # URLs, per RFC 2396. # m2 = re.search('&(lt|gt);', url) # if m2: # link = url[m2.end():] + ' ' + link # url = url[0:m2.end()] # If the link text is an image URL, replace it with an <img> tag # This happened by accident in the original parser, but some people used it extensively m = EXT_IMAGE_REGEX.match(label) if m: label = makeExternalImage(label) # Use the encoded URL # This means that users can paste URLs directly into the text # Funny characters like ö aren't valid in URLs anyway # This was changed in August 2004 s += makeExternalLink(url, label) # + trail return s + text[cur:]
[ "def", "replaceExternalLinks", "(", "text", ")", ":", "s", "=", "''", "cur", "=", "0", "for", "m", "in", "ExtLinkBracketedRegex", ".", "finditer", "(", "text", ")", ":", "s", "+=", "text", "[", "cur", ":", "m", ".", "start", "(", ")", "]", "cur", ...
https://github.com/facebookresearch/TaBERT/blob/74aa4a88783825e71b71d1d0fdbc6b338047eea9/preprocess/WikiExtractor.py#L2460-L2494
pygments/pygments
cd3ad20dfc8a6cb43e2c0b22b14446dcc0a554d7
pygments/lexers/parsers.py
python
AntlrCppLexer.analyse_text
(text)
return AntlrLexer.analyse_text(text) and \ re.search(r'^\s*language\s*=\s*C\s*;', text, re.M)
[]
def analyse_text(text): return AntlrLexer.analyse_text(text) and \ re.search(r'^\s*language\s*=\s*C\s*;', text, re.M)
[ "def", "analyse_text", "(", "text", ")", ":", "return", "AntlrLexer", ".", "analyse_text", "(", "text", ")", "and", "re", ".", "search", "(", "r'^\\s*language\\s*=\\s*C\\s*;'", ",", "text", ",", "re", ".", "M", ")" ]
https://github.com/pygments/pygments/blob/cd3ad20dfc8a6cb43e2c0b22b14446dcc0a554d7/pygments/lexers/parsers.py#L528-L530
meetbill/zabbix_manager
739e5b51facf19cc6bda2b50f29108f831cf833e
ZabbixTool/lib_zabbix/w_lib/argparse.py
python
HelpFormatter._join_parts
(self, part_strings)
return ''.join([part for part in part_strings if part and part is not SUPPRESS])
[]
def _join_parts(self, part_strings): return ''.join([part for part in part_strings if part and part is not SUPPRESS])
[ "def", "_join_parts", "(", "self", ",", "part_strings", ")", ":", "return", "''", ".", "join", "(", "[", "part", "for", "part", "in", "part_strings", "if", "part", "and", "part", "is", "not", "SUPPRESS", "]", ")" ]
https://github.com/meetbill/zabbix_manager/blob/739e5b51facf19cc6bda2b50f29108f831cf833e/ZabbixTool/lib_zabbix/w_lib/argparse.py#L312-L315
joaoricardo000/whatsapp-bot-seed
99ea85ec509ffe8b1429e82261b12a1614f5cb7a
src/utils/media_sender.py
python
MediaSender.__init__
(self, interface_layer, storage_path=config.media_storage_path)
The construction method receives the interface_layer (RouteLayer), so it can access the protocol methods to upload and send the media files
The construction method receives the interface_layer (RouteLayer), so it can access the protocol methods to upload and send the media files
[ "The", "construction", "method", "receives", "the", "interface_layer", "(", "RouteLayer", ")", "so", "it", "can", "access", "the", "protocol", "methods", "to", "upload", "and", "send", "the", "media", "files" ]
def __init__(self, interface_layer, storage_path=config.media_storage_path): """ The construction method receives the interface_layer (RouteLayer), so it can access the protocol methods to upload and send the media files """ self.interface_layer = interface_layer self.storage_path = storage_path self.file_extension_regex = re.compile("^.*\.([0-9a-z]+)(?:[\?\/][^\s]*)?$") self.MEDIA_TYPE = None
[ "def", "__init__", "(", "self", ",", "interface_layer", ",", "storage_path", "=", "config", ".", "media_storage_path", ")", ":", "self", ".", "interface_layer", "=", "interface_layer", "self", ".", "storage_path", "=", "storage_path", "self", ".", "file_extension_...
https://github.com/joaoricardo000/whatsapp-bot-seed/blob/99ea85ec509ffe8b1429e82261b12a1614f5cb7a/src/utils/media_sender.py#L37-L45
mu-editor/mu
5a5d7723405db588f67718a63a0ec0ecabebae33
mu/logic.py
python
DeviceList.check_usb
(self)
Ensure connected USB devices are polled. If there's a change and a new recognised device is attached, inform the user via a status message. If a single device is found and Mu is in a different mode ask the user if they'd like to change mode.
Ensure connected USB devices are polled. If there's a change and a new recognised device is attached, inform the user via a status message. If a single device is found and Mu is in a different mode ask the user if they'd like to change mode.
[ "Ensure", "connected", "USB", "devices", "are", "polled", ".", "If", "there", "s", "a", "change", "and", "a", "new", "recognised", "device", "is", "attached", "inform", "the", "user", "via", "a", "status", "message", ".", "If", "a", "single", "device", "...
def check_usb(self): """ Ensure connected USB devices are polled. If there's a change and a new recognised device is attached, inform the user via a status message. If a single device is found and Mu is in a different mode ask the user if they'd like to change mode. """ devices = [] device_types = set() # Detect connected devices. for mode_name, mode in self.modes.items(): if hasattr(mode, "find_devices"): # The mode can detect attached devices. detected = mode.find_devices(with_logging=False) if detected: device_types.add(mode_name) devices.extend(detected) # Remove no-longer connected devices. for device in self: if device not in devices: self.remove_device(device) self.device_disconnected.emit(device) logger.info( ( "{} device disconnected on port: {}" "(VID: 0x{:04X}, PID: 0x{:04X}, manufacturer {})" ).format( device.short_mode_name, device.port, device.vid, device.pid, device.manufacturer, ) ) # Add newly connected devices. for device in devices: if device not in self: self.add_device(device) self.device_connected.emit(device) logger.info( ( "{} device connected on port: {}" "(VID: 0x{:04X}, PID: 0x{:04X}, manufacturer: '{}')" ).format( device.short_mode_name, device.port, device.vid, device.pid, device.manufacturer, ) )
[ "def", "check_usb", "(", "self", ")", ":", "devices", "=", "[", "]", "device_types", "=", "set", "(", ")", "# Detect connected devices.", "for", "mode_name", ",", "mode", "in", "self", ".", "modes", ".", "items", "(", ")", ":", "if", "hasattr", "(", "m...
https://github.com/mu-editor/mu/blob/5a5d7723405db588f67718a63a0ec0ecabebae33/mu/logic.py#L708-L758
gy20073/BDD_Driving_Model
110b56474d45c274a9227c1666059e6eb0d63819
eval.py
python
plot_confusion_matrix
(cm, classes, normalize=False, title='Confusion matrix', cmap=plt.cm.Blues)
This function prints and plots the confusion matrix. Normalization can be applied by setting `normalize=True`.
This function prints and plots the confusion matrix. Normalization can be applied by setting `normalize=True`.
[ "This", "function", "prints", "and", "plots", "the", "confusion", "matrix", ".", "Normalization", "can", "be", "applied", "by", "setting", "normalize", "=", "True", "." ]
def plot_confusion_matrix(cm, classes, normalize=False, title='Confusion matrix', cmap=plt.cm.Blues): """ This function prints and plots the confusion matrix. Normalization can be applied by setting `normalize=True`. """ plt.imshow(cm, interpolation='nearest', cmap=cmap) plt.title(title) plt.colorbar() tick_marks = np.arange(len(classes)) plt.xticks(tick_marks, classes, rotation=45) plt.yticks(tick_marks, classes) if normalize: cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis] print("Normalized confusion matrix") else: print('Confusion matrix, without normalization') print(cm) thresh = cm.max() / 2. for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])): plt.text(j, i, "%.2f" % cm[i, j], horizontalalignment="center", color="white" if cm[i, j] > thresh else "black") plt.tight_layout() plt.ylabel('True label') plt.xlabel('Predicted label')
[ "def", "plot_confusion_matrix", "(", "cm", ",", "classes", ",", "normalize", "=", "False", ",", "title", "=", "'Confusion matrix'", ",", "cmap", "=", "plt", ".", "cm", ".", "Blues", ")", ":", "plt", ".", "imshow", "(", "cm", ",", "interpolation", "=", ...
https://github.com/gy20073/BDD_Driving_Model/blob/110b56474d45c274a9227c1666059e6eb0d63819/eval.py#L185-L216
securesystemslab/zippy
ff0e84ac99442c2c55fe1d285332cfd4e185e089
zippy/lib-python/3/logging/__init__.py
python
exception
(msg, *args, **kwargs)
Log a message with severity 'ERROR' on the root logger, with exception information. If the logger has no handlers, basicConfig() is called to add a console handler with a pre-defined format.
Log a message with severity 'ERROR' on the root logger, with exception information. If the logger has no handlers, basicConfig() is called to add a console handler with a pre-defined format.
[ "Log", "a", "message", "with", "severity", "ERROR", "on", "the", "root", "logger", "with", "exception", "information", ".", "If", "the", "logger", "has", "no", "handlers", "basicConfig", "()", "is", "called", "to", "add", "a", "console", "handler", "with", ...
def exception(msg, *args, **kwargs): """ Log a message with severity 'ERROR' on the root logger, with exception information. If the logger has no handlers, basicConfig() is called to add a console handler with a pre-defined format. """ kwargs['exc_info'] = True error(msg, *args, **kwargs)
[ "def", "exception", "(", "msg", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'exc_info'", "]", "=", "True", "error", "(", "msg", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/securesystemslab/zippy/blob/ff0e84ac99442c2c55fe1d285332cfd4e185e089/zippy/lib-python/3/logging/__init__.py#L1737-L1744
CvvT/dumpDex
92ab3b7e996194a06bf1dd5538a4954e8a5ee9c1
python/idaapi.py
python
f_hasValue
(*args)
return _idaapi.f_hasValue(*args)
f_hasValue(f, arg2) -> bool
f_hasValue(f, arg2) -> bool
[ "f_hasValue", "(", "f", "arg2", ")", "-", ">", "bool" ]
def f_hasValue(*args): """ f_hasValue(f, arg2) -> bool """ return _idaapi.f_hasValue(*args)
[ "def", "f_hasValue", "(", "*", "args", ")", ":", "return", "_idaapi", ".", "f_hasValue", "(", "*", "args", ")" ]
https://github.com/CvvT/dumpDex/blob/92ab3b7e996194a06bf1dd5538a4954e8a5ee9c1/python/idaapi.py#L21612-L21616
secdev/scapy
65089071da1acf54622df0b4fa7fc7673d47d3cd
scapy/arch/common.py
python
get_if
(iff, cmd)
Ease SIOCGIF* ioctl calls
Ease SIOCGIF* ioctl calls
[ "Ease", "SIOCGIF", "*", "ioctl", "calls" ]
def get_if(iff, cmd): # type: (Union[NetworkInterface, str], int) -> bytes """Ease SIOCGIF* ioctl calls""" iff = network_name(iff) sck = socket.socket() try: return ioctl(sck, cmd, struct.pack("16s16x", iff.encode("utf8"))) finally: sck.close()
[ "def", "get_if", "(", "iff", ",", "cmd", ")", ":", "# type: (Union[NetworkInterface, str], int) -> bytes", "iff", "=", "network_name", "(", "iff", ")", "sck", "=", "socket", ".", "socket", "(", ")", "try", ":", "return", "ioctl", "(", "sck", ",", "cmd", ",...
https://github.com/secdev/scapy/blob/65089071da1acf54622df0b4fa7fc7673d47d3cd/scapy/arch/common.py#L58-L67
number5/cloud-init
19948dbaf40309355e1a2dbef116efb0ce66245c
cloudinit/net/cmdline.py
python
InitramfsNetworkConfigSource.is_applicable
(self)
Is this initramfs config source applicable to the current system?
Is this initramfs config source applicable to the current system?
[ "Is", "this", "initramfs", "config", "source", "applicable", "to", "the", "current", "system?" ]
def is_applicable(self) -> bool: """Is this initramfs config source applicable to the current system?"""
[ "def", "is_applicable", "(", "self", ")", "->", "bool", ":" ]
https://github.com/number5/cloud-init/blob/19948dbaf40309355e1a2dbef116efb0ce66245c/cloudinit/net/cmdline.py#L30-L31
graphcore/examples
46d2b7687b829778369fc6328170a7b14761e5c6
applications/tensorflow/contrastive_divergence_vae/models/vae/vcd_vae.py
python
VCDVAE.get_control_var
(self, i_tr)
Get the control_variate variable and, if using local control_variate, the elements indexed by i_tr
Get the control_variate variable and, if using local control_variate, the elements indexed by i_tr
[ "Get", "the", "control_variate", "variable", "and", "if", "using", "local", "control_variate", "the", "elements", "indexed", "by", "i_tr" ]
def get_control_var(self, i_tr): """Get the control_variate variable and, if using local control_variate, the elements indexed by i_tr""" cv_shp = (self.experiment.data_meta['train_size'],) if self.use_local_control_variate else () with self.control_var_device(): with tf.variable_scope('cv_scope', reuse=tf.AUTO_REUSE, use_resource=True): cv_var = tf.get_variable('control_variate', shape=cv_shp, dtype=self.experiment.dtype, initializer=tf.zeros_initializer(), use_resource=True, trainable=False) cv_idxed = tf.gather(cv_var, i_tr) if self.use_local_control_variate else cv_var return cv_var, cv_idxed
[ "def", "get_control_var", "(", "self", ",", "i_tr", ")", ":", "cv_shp", "=", "(", "self", ".", "experiment", ".", "data_meta", "[", "'train_size'", "]", ",", ")", "if", "self", ".", "use_local_control_variate", "else", "(", ")", "with", "self", ".", "con...
https://github.com/graphcore/examples/blob/46d2b7687b829778369fc6328170a7b14761e5c6/applications/tensorflow/contrastive_divergence_vae/models/vae/vcd_vae.py#L211-L223
oaubert/python-vlc
908ffdbd0844dc1849728c456e147788798c99da
generated/2.2/vlc.py
python
memoize_parameterless.__get__
(self, obj, objtype)
return functools.partial(self.__call__, obj)
Support instance methods.
Support instance methods.
[ "Support", "instance", "methods", "." ]
def __get__(self, obj, objtype): """Support instance methods. """ return functools.partial(self.__call__, obj)
[ "def", "__get__", "(", "self", ",", "obj", ",", "objtype", ")", ":", "return", "functools", ".", "partial", "(", "self", ".", "__call__", ",", "obj", ")" ]
https://github.com/oaubert/python-vlc/blob/908ffdbd0844dc1849728c456e147788798c99da/generated/2.2/vlc.py#L235-L238
meduza-corp/interstellar
40a801ccd7856491726f5a126621d9318cabe2e1
gsutil/gslib/parallelism_framework_util.py
python
AtomicIncrementDict.Update
(self, key, inc, default_value=0)
Atomically update the stored value associated with the given key. Performs the atomic equivalent of self.put(key, self.get(key, default_value) + inc). Args: key: lookup key for the value of the first operand of the "+" operation. inc: Second operand of the "+" operation. default_value: Default value if there is no existing value for the key. Returns: Incremented value.
Atomically update the stored value associated with the given key.
[ "Atomically", "update", "the", "stored", "value", "associated", "with", "the", "given", "key", "." ]
def Update(self, key, inc, default_value=0): """Atomically update the stored value associated with the given key. Performs the atomic equivalent of self.put(key, self.get(key, default_value) + inc). Args: key: lookup key for the value of the first operand of the "+" operation. inc: Second operand of the "+" operation. default_value: Default value if there is no existing value for the key. Returns: Incremented value. """ with self.lock: return super(AtomicIncrementDict, self).Update(key, inc, default_value)
[ "def", "Update", "(", "self", ",", "key", ",", "inc", ",", "default_value", "=", "0", ")", ":", "with", "self", ".", "lock", ":", "return", "super", "(", "AtomicIncrementDict", ",", "self", ")", ".", "Update", "(", "key", ",", "inc", ",", "default_va...
https://github.com/meduza-corp/interstellar/blob/40a801ccd7856491726f5a126621d9318cabe2e1/gsutil/gslib/parallelism_framework_util.py#L70-L85
krintoxi/NoobSec-Toolkit
38738541cbc03cedb9a3b3ed13b629f781ad64f6
NoobSecToolkit - MAC OSX/tools/inject/thirdparty/odict/odict.py
python
Items.__cmp__
(self, other)
return cmp(self._main.items(), other)
[]
def __cmp__(self, other): return cmp(self._main.items(), other)
[ "def", "__cmp__", "(", "self", ",", "other", ")", ":", "return", "cmp", "(", "self", ".", "_main", ".", "items", "(", ")", ",", "other", ")" ]
https://github.com/krintoxi/NoobSec-Toolkit/blob/38738541cbc03cedb9a3b3ed13b629f781ad64f6/NoobSecToolkit - MAC OSX/tools/inject/thirdparty/odict/odict.py#L1029-L1029
NTMC-Community/MatchZoo-py
0e5c04e1e948aa9277abd5c85ff99d9950d8527f
matchzoo/data_pack/data_pack.py
python
DataPack.append_text_length
(self, verbose=1)
Append `length_left` and `length_right` columns. :param inplace: `True` to modify inplace, `False` to return a modified copy. (default: `False`) :param verbose: Verbosity. Example: >>> import matchzoo as mz >>> data_pack = mz.datasets.toy.load_data() >>> 'length_left' in data_pack.frame[0].columns False >>> new_data_pack = data_pack.append_text_length(verbose=0) >>> 'length_left' in new_data_pack.frame[0].columns True >>> 'length_left' in data_pack.frame[0].columns False >>> data_pack.append_text_length(inplace=True, verbose=0) >>> 'length_left' in data_pack.frame[0].columns True
Append `length_left` and `length_right` columns.
[ "Append", "length_left", "and", "length_right", "columns", "." ]
def append_text_length(self, verbose=1): """ Append `length_left` and `length_right` columns. :param inplace: `True` to modify inplace, `False` to return a modified copy. (default: `False`) :param verbose: Verbosity. Example: >>> import matchzoo as mz >>> data_pack = mz.datasets.toy.load_data() >>> 'length_left' in data_pack.frame[0].columns False >>> new_data_pack = data_pack.append_text_length(verbose=0) >>> 'length_left' in new_data_pack.frame[0].columns True >>> 'length_left' in data_pack.frame[0].columns False >>> data_pack.append_text_length(inplace=True, verbose=0) >>> 'length_left' in data_pack.frame[0].columns True """ self.apply_on_text(len, rename=('length_left', 'length_right'), inplace=True, verbose=verbose)
[ "def", "append_text_length", "(", "self", ",", "verbose", "=", "1", ")", ":", "self", ".", "apply_on_text", "(", "len", ",", "rename", "=", "(", "'length_left'", ",", "'length_right'", ")", ",", "inplace", "=", "True", ",", "verbose", "=", "verbose", ")"...
https://github.com/NTMC-Community/MatchZoo-py/blob/0e5c04e1e948aa9277abd5c85ff99d9950d8527f/matchzoo/data_pack/data_pack.py#L317-L341
pytroll/satpy
09e51f932048f98cce7919a4ff8bd2ec01e1ae98
satpy/scene.py
python
Scene.copy
(self, datasets=None)
return new_scn
Create a copy of the Scene including dependency information. Args: datasets (list, tuple): `DataID` objects for the datasets to include in the new Scene object.
Create a copy of the Scene including dependency information.
[ "Create", "a", "copy", "of", "the", "Scene", "including", "dependency", "information", "." ]
def copy(self, datasets=None): """Create a copy of the Scene including dependency information. Args: datasets (list, tuple): `DataID` objects for the datasets to include in the new Scene object. """ new_scn = self.__class__() new_scn.attrs = self.attrs.copy() new_scn._dependency_tree = self._dependency_tree.copy() if datasets is None: datasets = self.keys() self._copy_datasets_and_wishlist(new_scn, datasets) return new_scn
[ "def", "copy", "(", "self", ",", "datasets", "=", "None", ")", ":", "new_scn", "=", "self", ".", "__class__", "(", ")", "new_scn", ".", "attrs", "=", "self", ".", "attrs", ".", "copy", "(", ")", "new_scn", ".", "_dependency_tree", "=", "self", ".", ...
https://github.com/pytroll/satpy/blob/09e51f932048f98cce7919a4ff8bd2ec01e1ae98/satpy/scene.py#L508-L522
cobbler/cobbler
eed8cdca3e970c8aa1d199e80b8c8f19b3f940cc
cobbler/items/system.py
python
System.virt_cpus
(self)
return self._virt_cpus
virt_cpus property. :getter: Returns the value for ``virt_cpus``. :setter: Sets the value for the property ``virt_cpus``. :return:
virt_cpus property.
[ "virt_cpus", "property", "." ]
def virt_cpus(self) -> int: """ virt_cpus property. :getter: Returns the value for ``virt_cpus``. :setter: Sets the value for the property ``virt_cpus``. :return: """ return self._virt_cpus
[ "def", "virt_cpus", "(", "self", ")", "->", "int", ":", "return", "self", ".", "_virt_cpus" ]
https://github.com/cobbler/cobbler/blob/eed8cdca3e970c8aa1d199e80b8c8f19b3f940cc/cobbler/items/system.py#L1525-L1533
cmbruns/pyopenvr
ac4847a8a05cda0d4bcf7c4f243008b2a191c7a5
src/openvr/__init__.py
python
IVRRenderModels.renderModelHasComponent
(self, renderModelName: str, componentName: str)
return result
Returns true if the render model has a component with the specified name
Returns true if the render model has a component with the specified name
[ "Returns", "true", "if", "the", "render", "model", "has", "a", "component", "with", "the", "specified", "name" ]
def renderModelHasComponent(self, renderModelName: str, componentName: str): """Returns true if the render model has a component with the specified name""" fn = self.function_table.renderModelHasComponent if renderModelName is not None: renderModelName = bytes(renderModelName, encoding='utf-8') if componentName is not None: componentName = bytes(componentName, encoding='utf-8') result = fn(renderModelName, componentName) return result
[ "def", "renderModelHasComponent", "(", "self", ",", "renderModelName", ":", "str", ",", "componentName", ":", "str", ")", ":", "fn", "=", "self", ".", "function_table", ".", "renderModelHasComponent", "if", "renderModelName", "is", "not", "None", ":", "renderMod...
https://github.com/cmbruns/pyopenvr/blob/ac4847a8a05cda0d4bcf7c4f243008b2a191c7a5/src/openvr/__init__.py#L6000-L6008
ethereum/py-evm
026ee20f8d9b70d7c1b6a4fb9484d5489d425e54
eth/db/backends/level.py
python
LevelDBWriteBatch.decommission
(self)
Prevent any further actions to be taken on this write batch, called after leaving context
Prevent any further actions to be taken on this write batch, called after leaving context
[ "Prevent", "any", "further", "actions", "to", "be", "taken", "on", "this", "write", "batch", "called", "after", "leaving", "context" ]
def decommission(self) -> None: """ Prevent any further actions to be taken on this write batch, called after leaving context """ self._track_diff = None
[ "def", "decommission", "(", "self", ")", "->", "None", ":", "self", ".", "_track_diff", "=", "None" ]
https://github.com/ethereum/py-evm/blob/026ee20f8d9b70d7c1b6a4fb9484d5489d425e54/eth/db/backends/level.py#L138-L142
mchristopher/PokemonGo-DesktopMap
ec37575f2776ee7d64456e2a1f6b6b78830b4fe0
app/pylibs/osx64/gevent/_sslgte279.py
python
SSLSocket.version
(self)
return self._sslobj.version()
Return a string identifying the protocol version used by the current SSL channel, or None if there is no established channel.
Return a string identifying the protocol version used by the current SSL channel, or None if there is no established channel.
[ "Return", "a", "string", "identifying", "the", "protocol", "version", "used", "by", "the", "current", "SSL", "channel", "or", "None", "if", "there", "is", "no", "established", "channel", "." ]
def version(self): """ Return a string identifying the protocol version used by the current SSL channel, or None if there is no established channel. """ if self._sslobj is None: return None return self._sslobj.version()
[ "def", "version", "(", "self", ")", ":", "if", "self", ".", "_sslobj", "is", "None", ":", "return", "None", "return", "self", ".", "_sslobj", ".", "version", "(", ")" ]
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/ec37575f2776ee7d64456e2a1f6b6b78830b4fe0/app/pylibs/osx64/gevent/_sslgte279.py#L653-L660
xonsh/xonsh
b76d6f994f22a4078f602f8b386f4ec280c8461f
xonsh/pretty.py
python
PrettyPrinter.text
(self, obj)
Add literal text to the output.
Add literal text to the output.
[ "Add", "literal", "text", "to", "the", "output", "." ]
def text(self, obj): """Add literal text to the output.""" width = len(obj) if self.buffer: text = self.buffer[-1] if not isinstance(text, Text): text = Text() self.buffer.append(text) text.add(obj, width) self.buffer_width += width self._break_outer_groups() else: self.output.write(obj) self.output_width += width
[ "def", "text", "(", "self", ",", "obj", ")", ":", "width", "=", "len", "(", "obj", ")", "if", "self", ".", "buffer", ":", "text", "=", "self", ".", "buffer", "[", "-", "1", "]", "if", "not", "isinstance", "(", "text", ",", "Text", ")", ":", "...
https://github.com/xonsh/xonsh/blob/b76d6f994f22a4078f602f8b386f4ec280c8461f/xonsh/pretty.py#L206-L219
azavea/raster-vision
fc181a6f31f085affa1ee12f0204bdbc5a6bf85a
rastervision_core/rastervision/core/data/label/tfod_utils/np_box_list_ops.py
python
intersection
(boxlist1, boxlist2)
return np_box_ops.intersection(boxlist1.get(), boxlist2.get())
Compute pairwise intersection areas between boxes. Args: boxlist1: BoxList holding N boxes boxlist2: BoxList holding M boxes Returns: a numpy array with shape [N*M] representing pairwise intersection area
Compute pairwise intersection areas between boxes. Args: boxlist1: BoxList holding N boxes boxlist2: BoxList holding M boxes Returns: a numpy array with shape [N*M] representing pairwise intersection area
[ "Compute", "pairwise", "intersection", "areas", "between", "boxes", ".", "Args", ":", "boxlist1", ":", "BoxList", "holding", "N", "boxes", "boxlist2", ":", "BoxList", "holding", "M", "boxes", "Returns", ":", "a", "numpy", "array", "with", "shape", "[", "N", ...
def intersection(boxlist1, boxlist2): """Compute pairwise intersection areas between boxes. Args: boxlist1: BoxList holding N boxes boxlist2: BoxList holding M boxes Returns: a numpy array with shape [N*M] representing pairwise intersection area """ return np_box_ops.intersection(boxlist1.get(), boxlist2.get())
[ "def", "intersection", "(", "boxlist1", ",", "boxlist2", ")", ":", "return", "np_box_ops", ".", "intersection", "(", "boxlist1", ".", "get", "(", ")", ",", "boxlist2", ".", "get", "(", ")", ")" ]
https://github.com/azavea/raster-vision/blob/fc181a6f31f085affa1ee12f0204bdbc5a6bf85a/rastervision_core/rastervision/core/data/label/tfod_utils/np_box_list_ops.py#L47-L55
plotly/plotly.py
cfad7862594b35965c0e000813bd7805e8494a5b
packages/python/plotly/plotly/graph_objs/_funnelarea.py
python
Funnelarea.visible
(self)
return self["visible"]
Determines whether or not this trace is visible. If "legendonly", the trace is not drawn, but can appear as a legend item (provided that the legend itself is visible). The 'visible' property is an enumeration that may be specified as: - One of the following enumeration values: [True, False, 'legendonly'] Returns ------- Any
Determines whether or not this trace is visible. If "legendonly", the trace is not drawn, but can appear as a legend item (provided that the legend itself is visible). The 'visible' property is an enumeration that may be specified as: - One of the following enumeration values: [True, False, 'legendonly']
[ "Determines", "whether", "or", "not", "this", "trace", "is", "visible", ".", "If", "legendonly", "the", "trace", "is", "not", "drawn", "but", "can", "appear", "as", "a", "legend", "item", "(", "provided", "that", "the", "legend", "itself", "is", "visible",...
def visible(self): """ Determines whether or not this trace is visible. If "legendonly", the trace is not drawn, but can appear as a legend item (provided that the legend itself is visible). The 'visible' property is an enumeration that may be specified as: - One of the following enumeration values: [True, False, 'legendonly'] Returns ------- Any """ return self["visible"]
[ "def", "visible", "(", "self", ")", ":", "return", "self", "[", "\"visible\"", "]" ]
https://github.com/plotly/plotly.py/blob/cfad7862594b35965c0e000813bd7805e8494a5b/packages/python/plotly/plotly/graph_objs/_funnelarea.py#L1220-L1234
kevoreilly/CAPEv2
6cf79c33264624b3604d4cd432cde2a6b4536de6
lib/cuckoo/core/database.py
python
Database.demux_sample_and_add_to_db
( self, file_path, timeout=0, package="", options="", priority=1, custom="", machine="", platform="", tags=None, memory=False, enforce_timeout=False, clock=None, shrike_url=None, shrike_msg=None, shrike_sid=None, shrike_refer=None, parent_id=None, sample_parent_id=None, tlp=None, static=False, source_url=False, only_extraction=False, tags_tasks=False, route=None, cape=False, user_id=0, username=False, )
return task_ids, details
Handles ZIP file submissions, submitting each extracted file to the database Returns a list of added task IDs
Handles ZIP file submissions, submitting each extracted file to the database Returns a list of added task IDs
[ "Handles", "ZIP", "file", "submissions", "submitting", "each", "extracted", "file", "to", "the", "database", "Returns", "a", "list", "of", "added", "task", "IDs" ]
def demux_sample_and_add_to_db( self, file_path, timeout=0, package="", options="", priority=1, custom="", machine="", platform="", tags=None, memory=False, enforce_timeout=False, clock=None, shrike_url=None, shrike_msg=None, shrike_sid=None, shrike_refer=None, parent_id=None, sample_parent_id=None, tlp=None, static=False, source_url=False, only_extraction=False, tags_tasks=False, route=None, cape=False, user_id=0, username=False, ): """ Handles ZIP file submissions, submitting each extracted file to the database Returns a list of added task IDs """ task_id = False task_ids = [] config = {} sample_parent_id = None # force auto package for linux files if platform == "linux": package = "" original_options = options # extract files from the (potential) archive extracted_files = demux_sample(file_path, package, options) # check if len is 1 and the same file, if diff register file, and set parent if not isinstance(file_path, bytes): file_path = file_path.encode() if extracted_files and file_path not in extracted_files: sample_parent_id = self.register_sample(File(file_path), source_url=source_url) if conf.cuckoo.delete_archive: os.remove(file_path) # Check for 'file' option indicating supporting files needed for upload; otherwise create task for each file opts = get_options(options) if "file" in opts: runfile = opts["file"].lower() if isinstance(runfile, str): runfile = runfile.encode() for xfile in extracted_files: if runfile in xfile.lower(): extracted_files = [xfile] break # create tasks for each file in the archive for file in extracted_files: if static: # we don't need to process extra file if we already have it and config config = static_config_lookup(file) if config: task_ids.append(config["id"]) else: config = static_extraction(file) if config or static_extraction: task_ids += self.add_static( file_path=file, priority=priority, tlp=tlp, user_id=user_id, username=username, options=options ) if not config and not only_extraction: if not package: f = SflockFile.from_path(file) tmp_package = sflock_identify(f) if tmp_package and tmp_package in sandbox_packages: package = tmp_package else: log.info("Does sandbox packages need an update? Sflock identifies as: %s - %s", tmp_package, file) del f """ if package == "dll" and "function" not in options: dll_exports = File(file).get_dll_exports() if "DllRegisterServer" in dll_exports: package = "regsvr" elif "xlAutoOpen" in dll_exports: package = "xls" """ # ToDo better solution? - Distributed mode here: # Main node is storage so try to extract before submit to vm isn't propagated to workers options = original_options if static and not config and repconf.distributed.enabled: if options: options += ",dist_extract=1" else: options = "dist_extract=1" task_id = self.add_path( file_path=file.decode(), timeout=timeout, priority=priority, options=options, package=package, machine=machine, platform=platform, memory=memory, custom=custom, enforce_timeout=enforce_timeout, tags=tags, clock=clock, shrike_url=shrike_url, shrike_msg=shrike_msg, shrike_sid=shrike_sid, shrike_refer=shrike_refer, parent_id=parent_id, sample_parent_id=sample_parent_id, tlp=tlp, source_url=source_url, route=route, tags_tasks=tags_tasks, cape=cape, user_id=user_id, username=username, ) if task_id: task_ids.append(task_id) details = {} if config and isinstance(config, dict): details = {"config": config.get("cape_config", {})} # this is aim to return custom data, think of this as kwargs return task_ids, details
[ "def", "demux_sample_and_add_to_db", "(", "self", ",", "file_path", ",", "timeout", "=", "0", ",", "package", "=", "\"\"", ",", "options", "=", "\"\"", ",", "priority", "=", "1", ",", "custom", "=", "\"\"", ",", "machine", "=", "\"\"", ",", "platform", ...
https://github.com/kevoreilly/CAPEv2/blob/6cf79c33264624b3604d4cd432cde2a6b4536de6/lib/cuckoo/core/database.py#L1458-L1596
angr/angr
4b04d56ace135018083d36d9083805be8146688b
angr/analyses/cfg/cfb.py
python
CFBlanketView.__init__
(self, cfb)
[]
def __init__(self, cfb): self._cfb = cfb
[ "def", "__init__", "(", "self", ",", "cfb", ")", ":", "self", ".", "_cfb", "=", "cfb" ]
https://github.com/angr/angr/blob/4b04d56ace135018083d36d9083805be8146688b/angr/analyses/cfg/cfb.py#L20-L21
cslarsen/wpm
6e48d8b750c7828166b67a532ff03d62584fb953
wpm/screen.py
python
Screen.highlight_progress
(self, position, incorrect)
Colors finished and incorrectly typed parts of the quote.
Colors finished and incorrectly typed parts of the quote.
[ "Colors", "finished", "and", "incorrectly", "typed", "parts", "of", "the", "quote", "." ]
def highlight_progress(self, position, incorrect): """Colors finished and incorrectly typed parts of the quote.""" if incorrect: color = Screen.COLOR_INCORRECT else: color = Screen.COLOR_CORRECT # Highlight correct / incorrect character in quote ixpos, iypos = self.quote_coords[position + incorrect - 1] color = Screen.COLOR_INCORRECT if incorrect else Screen.COLOR_CORRECT self.chgat(max(ixpos, 0), 2 + iypos, 1, color) # Highlight next as correct, in case of backspace xpos, ypos = self.quote_coords[position + incorrect] self.chgat(xpos, 2 + ypos, 1, Screen.COLOR_QUOTE)
[ "def", "highlight_progress", "(", "self", ",", "position", ",", "incorrect", ")", ":", "if", "incorrect", ":", "color", "=", "Screen", ".", "COLOR_INCORRECT", "else", ":", "color", "=", "Screen", ".", "COLOR_CORRECT", "# Highlight correct / incorrect character in qu...
https://github.com/cslarsen/wpm/blob/6e48d8b750c7828166b67a532ff03d62584fb953/wpm/screen.py#L478-L492
HymanLiuTS/flaskTs
286648286976e85d9b9a5873632331efcafe0b21
flasky/lib/python2.7/site-packages/coverage/plugin.py
python
FileTracer.source_filename
(self)
The source file name for this file. This may be any file name you like. A key responsibility of a plugin is to own the mapping from Python execution back to whatever source file name was originally the source of the code. See :meth:`CoveragePlugin.file_tracer` for details about static and dynamic file names. Returns the file name to credit with this execution.
The source file name for this file.
[ "The", "source", "file", "name", "for", "this", "file", "." ]
def source_filename(self): """The source file name for this file. This may be any file name you like. A key responsibility of a plugin is to own the mapping from Python execution back to whatever source file name was originally the source of the code. See :meth:`CoveragePlugin.file_tracer` for details about static and dynamic file names. Returns the file name to credit with this execution. """ _needs_to_implement(self, "source_filename")
[ "def", "source_filename", "(", "self", ")", ":", "_needs_to_implement", "(", "self", ",", "\"source_filename\"", ")" ]
https://github.com/HymanLiuTS/flaskTs/blob/286648286976e85d9b9a5873632331efcafe0b21/flasky/lib/python2.7/site-packages/coverage/plugin.py#L118-L131
eirannejad/pyRevit
49c0b7eb54eb343458ce1365425e6552d0c47d44
site-packages/pathlib.py
python
Path.lstat
(self)
return self._accessor.lstat(self)
Like stat(), except if the path points to a symlink, the symlink's status information is returned, rather than its target's.
Like stat(), except if the path points to a symlink, the symlink's status information is returned, rather than its target's.
[ "Like", "stat", "()", "except", "if", "the", "path", "points", "to", "a", "symlink", "the", "symlink", "s", "status", "information", "is", "returned", "rather", "than", "its", "target", "s", "." ]
def lstat(self): """ Like stat(), except if the path points to a symlink, the symlink's status information is returned, rather than its target's. """ return self._accessor.lstat(self)
[ "def", "lstat", "(", "self", ")", ":", "return", "self", ".", "_accessor", ".", "lstat", "(", "self", ")" ]
https://github.com/eirannejad/pyRevit/blob/49c0b7eb54eb343458ce1365425e6552d0c47d44/site-packages/pathlib.py#L1139-L1144
knownsec/VxPwn
6555f49675f0317d4a48568a89d0ec4332658402
sulley/process_monitor_unix.py
python
debugger_thread.isAlive
(self)
return self.alive
[]
def isAlive(self): return self.alive
[ "def", "isAlive", "(", "self", ")", ":", "return", "self", ".", "alive" ]
https://github.com/knownsec/VxPwn/blob/6555f49675f0317d4a48568a89d0ec4332658402/sulley/process_monitor_unix.py#L89-L90
beville/ComicStreamer
62eb914652695ea41a5e1f0cfbd044cbc6854e84
libs/rumps/utils.py
python
ListDict.__insertion
(self, link_prev, key_value)
[]
def __insertion(self, link_prev, key_value): key, value = key_value if link_prev[2] != key: if key in self: del self[key] link_next = link_prev[1] self._OrderedDict__map[key] = link_prev[1] = link_next[0] = [link_prev, link_next, key] dict.__setitem__(self, key, value)
[ "def", "__insertion", "(", "self", ",", "link_prev", ",", "key_value", ")", ":", "key", ",", "value", "=", "key_value", "if", "link_prev", "[", "2", "]", "!=", "key", ":", "if", "key", "in", "self", ":", "del", "self", "[", "key", "]", "link_next", ...
https://github.com/beville/ComicStreamer/blob/62eb914652695ea41a5e1f0cfbd044cbc6854e84/libs/rumps/utils.py#L14-L21
oracle/oci-python-sdk
3c1604e4e212008fb6718e2f68cdb5ef71fd5793
examples/showoci/showoci_service.py
python
ShowOCIService.get_network_vcn
(self, vcn_id)
[]
def get_network_vcn(self, vcn_id): try: result = self.search_unique_item(self.C_NETWORK, self.C_NETWORK_VCN, 'id', vcn_id) if result: if result != "": return result['name'] return "" except Exception as e: self.__print_error("get_network_vcn", e)
[ "def", "get_network_vcn", "(", "self", ",", "vcn_id", ")", ":", "try", ":", "result", "=", "self", ".", "search_unique_item", "(", "self", ".", "C_NETWORK", ",", "self", ".", "C_NETWORK_VCN", ",", "'id'", ",", "vcn_id", ")", "if", "result", ":", "if", ...
https://github.com/oracle/oci-python-sdk/blob/3c1604e4e212008fb6718e2f68cdb5ef71fd5793/examples/showoci/showoci_service.py#L643-L652
UniversalDependencies/tools
74faa47086440d03e06aa26bc7a8247878737c18
compat/argparse.py
python
_AppendConstAction.__call__
(self, parser, namespace, values, option_string=None)
[]
def __call__(self, parser, namespace, values, option_string=None): items = _copy.copy(_ensure_value(namespace, self.dest, [])) items.append(self.const) setattr(namespace, self.dest, items)
[ "def", "__call__", "(", "self", ",", "parser", ",", "namespace", ",", "values", ",", "option_string", "=", "None", ")", ":", "items", "=", "_copy", ".", "copy", "(", "_ensure_value", "(", "namespace", ",", "self", ".", "dest", ",", "[", "]", ")", ")"...
https://github.com/UniversalDependencies/tools/blob/74faa47086440d03e06aa26bc7a8247878737c18/compat/argparse.py#L973-L976
bruderstein/PythonScript
df9f7071ddf3a079e3a301b9b53a6dc78cf1208f
PythonLib/full/multiprocessing/util.py
python
ForkAwareThreadLock._at_fork_reinit
(self)
[]
def _at_fork_reinit(self): self._lock._at_fork_reinit()
[ "def", "_at_fork_reinit", "(", "self", ")", ":", "self", ".", "_lock", ".", "_at_fork_reinit", "(", ")" ]
https://github.com/bruderstein/PythonScript/blob/df9f7071ddf3a079e3a301b9b53a6dc78cf1208f/PythonLib/full/multiprocessing/util.py#L375-L376
xtiankisutsa/MARA_Framework
ac4ac88bfd38f33ae8780a606ed09ab97177c562
tools/lobotomy/core/include/androguard/androguard/core/bytecodes/dvm.py
python
MapList.get_item_type
(self, ttype)
return None
Get a particular item type :param ttype: a string which represents the desired type :rtype: None or the item object
Get a particular item type
[ "Get", "a", "particular", "item", "type" ]
def get_item_type(self, ttype) : """ Get a particular item type :param ttype: a string which represents the desired type :rtype: None or the item object """ for i in self.map_item : if TYPE_MAP_ITEM[ i.get_type() ] == ttype : return i.get_item() return None
[ "def", "get_item_type", "(", "self", ",", "ttype", ")", ":", "for", "i", "in", "self", ".", "map_item", ":", "if", "TYPE_MAP_ITEM", "[", "i", ".", "get_type", "(", ")", "]", "==", "ttype", ":", "return", "i", ".", "get_item", "(", ")", "return", "N...
https://github.com/xtiankisutsa/MARA_Framework/blob/ac4ac88bfd38f33ae8780a606ed09ab97177c562/tools/lobotomy/core/include/androguard/androguard/core/bytecodes/dvm.py#L6764-L6775
LexPredict/lexpredict-contraxsuite
1d5a2540d31f8f3f1adc442cfa13a7c007319899
sdk/python/sdk/openapi_client/model/upload.py
python
Upload.additional_properties_type
()
return (bool, date, datetime, dict, float, int, list, str, none_type,)
This must be a method because a model may have properties that are of type self, this must run after the class is loaded
This must be a method because a model may have properties that are of type self, this must run after the class is loaded
[ "This", "must", "be", "a", "method", "because", "a", "model", "may", "have", "properties", "that", "are", "of", "type", "self", "this", "must", "run", "after", "the", "class", "is", "loaded" ]
def additional_properties_type(): """ This must be a method because a model may have properties that are of type self, this must run after the class is loaded """ return (bool, date, datetime, dict, float, int, list, str, none_type,)
[ "def", "additional_properties_type", "(", ")", ":", "return", "(", "bool", ",", "date", ",", "datetime", ",", "dict", ",", "float", ",", "int", ",", "list", ",", "str", ",", "none_type", ",", ")" ]
https://github.com/LexPredict/lexpredict-contraxsuite/blob/1d5a2540d31f8f3f1adc442cfa13a7c007319899/sdk/python/sdk/openapi_client/model/upload.py#L81-L86
materialsproject/pymatgen
8128f3062a334a2edd240e4062b5b9bdd1ae6f58
pymatgen/electronic_structure/core.py
python
Magmom.are_collinear
(magmoms)
return True
Method checks to see if a set of magnetic moments are collinear with each other. :param magmoms: list of magmoms (Magmoms, scalars or vectors) :return: bool
Method checks to see if a set of magnetic moments are collinear with each other. :param magmoms: list of magmoms (Magmoms, scalars or vectors) :return: bool
[ "Method", "checks", "to", "see", "if", "a", "set", "of", "magnetic", "moments", "are", "collinear", "with", "each", "other", ".", ":", "param", "magmoms", ":", "list", "of", "magmoms", "(", "Magmoms", "scalars", "or", "vectors", ")", ":", "return", ":", ...
def are_collinear(magmoms): """ Method checks to see if a set of magnetic moments are collinear with each other. :param magmoms: list of magmoms (Magmoms, scalars or vectors) :return: bool """ magmoms = [Magmom(magmom) for magmom in magmoms] if not Magmom.have_consistent_saxis(magmoms): magmoms = Magmom.get_consistent_set_and_saxis(magmoms)[0] # convert to numpy array for convenience magmoms = np.array([list(magmom) for magmom in magmoms]) magmoms = magmoms[np.any(magmoms, axis=1)] # remove zero magmoms if len(magmoms) == 0: return True # use first moment as reference to compare against ref_magmom = magmoms[0] # magnitude of cross products != 0 if non-collinear with reference num_ncl = np.count_nonzero(np.linalg.norm(np.cross(ref_magmom, magmoms), axis=1)) if num_ncl > 0: return False return True
[ "def", "are_collinear", "(", "magmoms", ")", ":", "magmoms", "=", "[", "Magmom", "(", "magmom", ")", "for", "magmom", "in", "magmoms", "]", "if", "not", "Magmom", ".", "have_consistent_saxis", "(", "magmoms", ")", ":", "magmoms", "=", "Magmom", ".", "get...
https://github.com/materialsproject/pymatgen/blob/8128f3062a334a2edd240e4062b5b9bdd1ae6f58/pymatgen/electronic_structure/core.py#L368-L391
theQRL/QRL
e751c790c1d8e01b51b26735009a2607ac548773
versioneer.py
python
render_pep440_old
(pieces)
return rendered
TAG[.postDISTANCE[.dev0]] . The ".dev0" means dirty. Eexceptions: 1: no tags. 0.postDISTANCE[.dev0]
TAG[.postDISTANCE[.dev0]] .
[ "TAG", "[", ".", "postDISTANCE", "[", ".", "dev0", "]]", "." ]
def render_pep440_old(pieces): """TAG[.postDISTANCE[.dev0]] . The ".dev0" means dirty. Eexceptions: 1: no tags. 0.postDISTANCE[.dev0] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += ".post%d" % pieces["distance"] if pieces["dirty"]: rendered += ".dev0" else: # exception #1 rendered = "0.post%d" % pieces["distance"] if pieces["dirty"]: rendered += ".dev0" return rendered
[ "def", "render_pep440_old", "(", "pieces", ")", ":", "if", "pieces", "[", "\"closest-tag\"", "]", ":", "rendered", "=", "pieces", "[", "\"closest-tag\"", "]", "if", "pieces", "[", "\"distance\"", "]", "or", "pieces", "[", "\"dirty\"", "]", ":", "rendered", ...
https://github.com/theQRL/QRL/blob/e751c790c1d8e01b51b26735009a2607ac548773/versioneer.py#L1304-L1323
wangzhecheng/DeepSolar
39643e97d628c9317aca398d28e37ed25472a7f6
train_classification.py
python
load_image
(path)
return image
[]
def load_image(path): # load image and prepocess. rotate_angle_list = [0, 90, 180, 270] img = skimage.io.imread(path) resized_img = skimage.transform.resize(img, (IMAGE_SIZE, IMAGE_SIZE)) if resized_img.shape[2] != 3: resized_img = resized_img[:, :, 0:3] rotate_angle = random.choice(rotate_angle_list) image = skimage.transform.rotate(resized_img, rotate_angle) return image
[ "def", "load_image", "(", "path", ")", ":", "# load image and prepocess.", "rotate_angle_list", "=", "[", "0", ",", "90", ",", "180", ",", "270", "]", "img", "=", "skimage", ".", "io", ".", "imread", "(", "path", ")", "resized_img", "=", "skimage", ".", ...
https://github.com/wangzhecheng/DeepSolar/blob/39643e97d628c9317aca398d28e37ed25472a7f6/train_classification.py#L64-L73
omz/PythonistaAppTemplate
f560f93f8876d82a21d108977f90583df08d55af
PythonistaAppTemplate/PythonistaKit.framework/pylib_ext/numpy/ma/core.py
python
MaskedArray.__str__
(self)
return str(res)
String representation.
String representation.
[ "String", "representation", "." ]
def __str__(self): """String representation. """ if masked_print_option.enabled(): f = masked_print_option if self is masked: return str(f) m = self._mask if m is nomask: res = self._data else: if m.shape == (): if m.dtype.names: m = m.view((bool, len(m.dtype))) if m.any(): r = np.array(self._data.tolist(), dtype=object) np.copyto(r, f, where=m) return str(tuple(r)) else: return str(self._data) elif m: return str(f) else: return str(self._data) # convert to object array to make filled work names = self.dtype.names if names is None: res = self._data.astype("O") res[m] = f else: rdtype = _recursive_make_descr(self.dtype, "O") res = self._data.astype(rdtype) _recursive_printoption(res, m, f) else: res = self.filled(self.fill_value) return str(res)
[ "def", "__str__", "(", "self", ")", ":", "if", "masked_print_option", ".", "enabled", "(", ")", ":", "f", "=", "masked_print_option", "if", "self", "is", "masked", ":", "return", "str", "(", "f", ")", "m", "=", "self", ".", "_mask", "if", "m", "is", ...
https://github.com/omz/PythonistaAppTemplate/blob/f560f93f8876d82a21d108977f90583df08d55af/PythonistaAppTemplate/PythonistaKit.framework/pylib_ext/numpy/ma/core.py#L3568-L3604
simons-public/protonfixes
24ecb378bc4e99bfe698090661d255dcbb5b677f
protonfixes/gamefixes/default.py
python
main
()
global defaults
global defaults
[ "global", "defaults" ]
def main(): """ global defaults """ # Steam commandline def use_steam_commands(): """ Parse aliases from Steam launch options """ pf_alias_list = list(filter(lambda item: '-pf_' in item, sys.argv)) for pf_alias in pf_alias_list: sys.argv.remove(pf_alias) if pf_alias == '-pf_winecfg': util.winecfg() elif pf_alias == '-pf_regedit': util.regedit() elif pf_alias.split('=')[0] == '-pf_tricks': param = str(pf_alias.replace('-pf_tricks=', '')) util.protontricks(param) elif pf_alias.split('=')[0] == '-pf_dxvk_set': param = str(pf_alias.replace('-pf_dxvk_set=', '')) dxvk_opt = param.split('=') util.set_dxvk_option(str(dxvk_opt[0]), str(dxvk_opt[1])) use_steam_commands()
[ "def", "main", "(", ")", ":", "# Steam commandline", "def", "use_steam_commands", "(", ")", ":", "\"\"\" Parse aliases from Steam launch options\n \"\"\"", "pf_alias_list", "=", "list", "(", "filter", "(", "lambda", "item", ":", "'-pf_'", "in", "item", ",", "...
https://github.com/simons-public/protonfixes/blob/24ecb378bc4e99bfe698090661d255dcbb5b677f/protonfixes/gamefixes/default.py#L7-L31
wistbean/learn_python3_spider
73c873f4845f4385f097e5057407d03dd37a117b
stackoverflow/venv/lib/python3.6/site-packages/pip-19.0.3-py3.6.egg/pip/_vendor/cachecontrol/caches/redis_cache.py
python
RedisCache.close
(self)
Redis uses connection pooling, no need to close the connection.
Redis uses connection pooling, no need to close the connection.
[ "Redis", "uses", "connection", "pooling", "no", "need", "to", "close", "the", "connection", "." ]
def close(self): """Redis uses connection pooling, no need to close the connection.""" pass
[ "def", "close", "(", "self", ")", ":", "pass" ]
https://github.com/wistbean/learn_python3_spider/blob/73c873f4845f4385f097e5057407d03dd37a117b/stackoverflow/venv/lib/python3.6/site-packages/pip-19.0.3-py3.6.egg/pip/_vendor/cachecontrol/caches/redis_cache.py#L31-L33
feeluown/FeelUOwn
ec104689add09c351e6ca4133a5d0632294b3784
mpv_old.py
python
MPV.playlist_move
(self, index1, index2)
Mapped mpv playlist_move command, see man mpv(1).
Mapped mpv playlist_move command, see man mpv(1).
[ "Mapped", "mpv", "playlist_move", "command", "see", "man", "mpv", "(", "1", ")", "." ]
def playlist_move(self, index1, index2): """Mapped mpv playlist_move command, see man mpv(1).""" self.command('playlist_move', index1, index2)
[ "def", "playlist_move", "(", "self", ",", "index1", ",", "index2", ")", ":", "self", ".", "command", "(", "'playlist_move'", ",", "index1", ",", "index2", ")" ]
https://github.com/feeluown/FeelUOwn/blob/ec104689add09c351e6ca4133a5d0632294b3784/mpv_old.py#L743-L745
glutanimate/review-heatmap
c758478125b60a81c66c87c35b12b7968ec0a348
src/review_heatmap/libaddon/gui/basic/interface.py
python
CommonWidgetInterface._removeListValues
(self, list_widget, item_tuples)
return self._removeListItemsByData([item[1] for item in item_tuples])
Remove items by list of (item_text, item_data) tuples
Remove items by list of (item_text, item_data) tuples
[ "Remove", "items", "by", "list", "of", "(", "item_text", "item_data", ")", "tuples" ]
def _removeListValues(self, list_widget, item_tuples): """ Remove items by list of (item_text, item_data) tuples """ return self._removeListItemsByData([item[1] for item in item_tuples])
[ "def", "_removeListValues", "(", "self", ",", "list_widget", ",", "item_tuples", ")", ":", "return", "self", ".", "_removeListItemsByData", "(", "[", "item", "[", "1", "]", "for", "item", "in", "item_tuples", "]", ")" ]
https://github.com/glutanimate/review-heatmap/blob/c758478125b60a81c66c87c35b12b7968ec0a348/src/review_heatmap/libaddon/gui/basic/interface.py#L947-L951
sagemath/sage
f9b2db94f675ff16963ccdefba4f1a3393b3fe0d
src/sage/combinat/tableau.py
python
Tableaux_size.an_element
(self)
return self.element_class(self, [[1]*(self.size-1),[1]])
r""" Return a particular element of the class. TESTS:: sage: T = sage.combinat.tableau.Tableaux_size(3) sage: T.an_element() [[1, 1], [1]] sage: T = sage.combinat.tableau.Tableaux_size(0) sage: T.an_element() []
r""" Return a particular element of the class.
[ "r", "Return", "a", "particular", "element", "of", "the", "class", "." ]
def an_element(self): r""" Return a particular element of the class. TESTS:: sage: T = sage.combinat.tableau.Tableaux_size(3) sage: T.an_element() [[1, 1], [1]] sage: T = sage.combinat.tableau.Tableaux_size(0) sage: T.an_element() [] """ if self.size==0: return self.element_class(self, []) if self.size==1: return self.element_class(self, [[1]]) return self.element_class(self, [[1]*(self.size-1),[1]])
[ "def", "an_element", "(", "self", ")", ":", "if", "self", ".", "size", "==", "0", ":", "return", "self", ".", "element_class", "(", "self", ",", "[", "]", ")", "if", "self", ".", "size", "==", "1", ":", "return", "self", ".", "element_class", "(", ...
https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/combinat/tableau.py#L5634-L5653
VirtueSecurity/aws-extender
d123b7e1a845847709ba3a481f11996bddc68a1c
BappModules/boto/rds/__init__.py
python
RDSConnection.delete_option_group
(self, name)
return self.get_status('DeleteOptionGroup', params)
Delete an OptionGroup from your account. :type key_name: string :param key_name: The name of the OptionGroup to delete
Delete an OptionGroup from your account.
[ "Delete", "an", "OptionGroup", "from", "your", "account", "." ]
def delete_option_group(self, name): """ Delete an OptionGroup from your account. :type key_name: string :param key_name: The name of the OptionGroup to delete """ params = {'OptionGroupName': name} return self.get_status('DeleteOptionGroup', params)
[ "def", "delete_option_group", "(", "self", ",", "name", ")", ":", "params", "=", "{", "'OptionGroupName'", ":", "name", "}", "return", "self", ".", "get_status", "(", "'DeleteOptionGroup'", ",", "params", ")" ]
https://github.com/VirtueSecurity/aws-extender/blob/d123b7e1a845847709ba3a481f11996bddc68a1c/BappModules/boto/rds/__init__.py#L1528-L1536
marcua/tweeql
eb8c61fb001e0b9755929f3b19be9fa16358187e
old/redis/client.py
python
Redis.sismember
(self, name, value)
return self.format_bulk('SISMEMBER', name, value)
Return a boolean indicating if ``value`` is a member of set ``name``
Return a boolean indicating if ``value`` is a member of set ``name``
[ "Return", "a", "boolean", "indicating", "if", "value", "is", "a", "member", "of", "set", "name" ]
def sismember(self, name, value): "Return a boolean indicating if ``value`` is a member of set ``name``" return self.format_bulk('SISMEMBER', name, value)
[ "def", "sismember", "(", "self", ",", "name", ",", "value", ")", ":", "return", "self", ".", "format_bulk", "(", "'SISMEMBER'", ",", "name", ",", "value", ")" ]
https://github.com/marcua/tweeql/blob/eb8c61fb001e0b9755929f3b19be9fa16358187e/old/redis/client.py#L771-L773
CouchPotato/CouchPotatoV1
135b3331d1b88ef645e29b76f2d4cc4a732c9232
library/sqlalchemy/util.py
python
flatten_iterator
(x)
Given an iterator of which further sub-elements may also be iterators, flatten the sub-elements into a single iterator.
Given an iterator of which further sub-elements may also be iterators, flatten the sub-elements into a single iterator.
[ "Given", "an", "iterator", "of", "which", "further", "sub", "-", "elements", "may", "also", "be", "iterators", "flatten", "the", "sub", "-", "elements", "into", "a", "single", "iterator", "." ]
def flatten_iterator(x): """Given an iterator of which further sub-elements may also be iterators, flatten the sub-elements into a single iterator. """ for elem in x: if not isinstance(elem, basestring) and hasattr(elem, '__iter__'): for y in flatten_iterator(elem): yield y else: yield elem
[ "def", "flatten_iterator", "(", "x", ")", ":", "for", "elem", "in", "x", ":", "if", "not", "isinstance", "(", "elem", ",", "basestring", ")", "and", "hasattr", "(", "elem", ",", "'__iter__'", ")", ":", "for", "y", "in", "flatten_iterator", "(", "elem",...
https://github.com/CouchPotato/CouchPotatoV1/blob/135b3331d1b88ef645e29b76f2d4cc4a732c9232/library/sqlalchemy/util.py#L359-L369
ustayready/CredKing
68b612e4cdf01d2b65b14ab2869bb8a5531056ee
plugins/gmail/requests/utils.py
python
dict_from_cookiejar
(cj)
return cookie_dict
Returns a key/value dictionary from a CookieJar. :param cj: CookieJar object to extract cookies from. :rtype: dict
Returns a key/value dictionary from a CookieJar.
[ "Returns", "a", "key", "/", "value", "dictionary", "from", "a", "CookieJar", "." ]
def dict_from_cookiejar(cj): """Returns a key/value dictionary from a CookieJar. :param cj: CookieJar object to extract cookies from. :rtype: dict """ cookie_dict = {} for cookie in cj: cookie_dict[cookie.name] = cookie.value return cookie_dict
[ "def", "dict_from_cookiejar", "(", "cj", ")", ":", "cookie_dict", "=", "{", "}", "for", "cookie", "in", "cj", ":", "cookie_dict", "[", "cookie", ".", "name", "]", "=", "cookie", ".", "value", "return", "cookie_dict" ]
https://github.com/ustayready/CredKing/blob/68b612e4cdf01d2b65b14ab2869bb8a5531056ee/plugins/gmail/requests/utils.py#L364-L376
evilhero/mylar
dbee01d7e48e8c717afa01b2de1946c5d0b956cb
lib/httplib2/socks.py
python
wrapmodule
(module)
wrapmodule(module) Attempts to replace a module's socket library with a SOCKS socket. Must set a default proxy using setdefaultproxy(...) first. This will only work on modules that import socket directly into the namespace; most of the Python Standard Library falls into this category.
wrapmodule(module) Attempts to replace a module's socket library with a SOCKS socket. Must set a default proxy using setdefaultproxy(...) first. This will only work on modules that import socket directly into the namespace; most of the Python Standard Library falls into this category.
[ "wrapmodule", "(", "module", ")", "Attempts", "to", "replace", "a", "module", "s", "socket", "library", "with", "a", "SOCKS", "socket", ".", "Must", "set", "a", "default", "proxy", "using", "setdefaultproxy", "(", "...", ")", "first", ".", "This", "will", ...
def wrapmodule(module): """wrapmodule(module) Attempts to replace a module's socket library with a SOCKS socket. Must set a default proxy using setdefaultproxy(...) first. This will only work on modules that import socket directly into the namespace; most of the Python Standard Library falls into this category. """ if _defaultproxy != None: module.socket.socket = socksocket else: raise GeneralProxyError((4, "no proxy specified"))
[ "def", "wrapmodule", "(", "module", ")", ":", "if", "_defaultproxy", "!=", "None", ":", "module", ".", "socket", ".", "socket", "=", "socksocket", "else", ":", "raise", "GeneralProxyError", "(", "(", "4", ",", "\"no proxy specified\"", ")", ")" ]
https://github.com/evilhero/mylar/blob/dbee01d7e48e8c717afa01b2de1946c5d0b956cb/lib/httplib2/socks.py#L104-L114
phaethon/kamene
bf679a65d456411942ee4a907818ba3d6a183bfe
kamene/contrib/gsm_um.py
python
startDtmf
()
return packet
START DTMF Section 9.3.24
START DTMF Section 9.3.24
[ "START", "DTMF", "Section", "9", ".", "3", ".", "24" ]
def startDtmf(): """START DTMF Section 9.3.24""" a = TpPd(pd=0x3) b = MessageType(mesType=0x35) # 00110101 c = KeypadFacilityHdr(ieiKF=0x2C, eightBitKF=0x0) packet = a / b / c return packet
[ "def", "startDtmf", "(", ")", ":", "a", "=", "TpPd", "(", "pd", "=", "0x3", ")", "b", "=", "MessageType", "(", "mesType", "=", "0x35", ")", "# 00110101", "c", "=", "KeypadFacilityHdr", "(", "ieiKF", "=", "0x2C", ",", "eightBitKF", "=", "0x0", ")", ...
https://github.com/phaethon/kamene/blob/bf679a65d456411942ee4a907818ba3d6a183bfe/kamene/contrib/gsm_um.py#L2236-L2242
meduza-corp/interstellar
40a801ccd7856491726f5a126621d9318cabe2e1
gsutil/third_party/boto/boto/s3/resumable_download_handler.py
python
get_cur_file_size
(fp, position_to_eof=False)
return cur_file_size
Returns size of file, optionally leaving fp positioned at EOF.
Returns size of file, optionally leaving fp positioned at EOF.
[ "Returns", "size", "of", "file", "optionally", "leaving", "fp", "positioned", "at", "EOF", "." ]
def get_cur_file_size(fp, position_to_eof=False): """ Returns size of file, optionally leaving fp positioned at EOF. """ if isinstance(fp, KeyFile) and not position_to_eof: # Avoid EOF seek for KeyFile case as it's very inefficient. return fp.getkey().size if not position_to_eof: cur_pos = fp.tell() fp.seek(0, os.SEEK_END) cur_file_size = fp.tell() if not position_to_eof: fp.seek(cur_pos, os.SEEK_SET) return cur_file_size
[ "def", "get_cur_file_size", "(", "fp", ",", "position_to_eof", "=", "False", ")", ":", "if", "isinstance", "(", "fp", ",", "KeyFile", ")", "and", "not", "position_to_eof", ":", "# Avoid EOF seek for KeyFile case as it's very inefficient.", "return", "fp", ".", "getk...
https://github.com/meduza-corp/interstellar/blob/40a801ccd7856491726f5a126621d9318cabe2e1/gsutil/third_party/boto/boto/s3/resumable_download_handler.py#L73-L86
limodou/ulipad
4c7d590234f39cac80bb1d36dca095b646e287fb
acp/python/import_utils.py
python
getConstructor
(object)
return None
Return constructor for class object, or None if there isn't one.
Return constructor for class object, or None if there isn't one.
[ "Return", "constructor", "for", "class", "object", "or", "None", "if", "there", "isn", "t", "one", "." ]
def getConstructor(object): """Return constructor for class object, or None if there isn't one.""" try: return object.__init__.im_func except AttributeError: for base in object.__bases__: constructor = getConstructor(base) if constructor is not None: return constructor return None
[ "def", "getConstructor", "(", "object", ")", ":", "try", ":", "return", "object", ".", "__init__", ".", "im_func", "except", "AttributeError", ":", "for", "base", "in", "object", ".", "__bases__", ":", "constructor", "=", "getConstructor", "(", "base", ")", ...
https://github.com/limodou/ulipad/blob/4c7d590234f39cac80bb1d36dca095b646e287fb/acp/python/import_utils.py#L151-L160
joeferraro/MavensMate-SublimeText
af36de7ffaa9b0541f446145736a48b1c66ac0cf
lib/response_handler.py
python
MavensMateResponseHandler.__handle_delete_metadata_result
(self, **kwargs)
[]
def __handle_delete_metadata_result(self, **kwargs): debug('HANDLING DELETE!') debug(self.response) self.__handle_compile_response()
[ "def", "__handle_delete_metadata_result", "(", "self", ",", "*", "*", "kwargs", ")", ":", "debug", "(", "'HANDLING DELETE!'", ")", "debug", "(", "self", ".", "response", ")", "self", ".", "__handle_compile_response", "(", ")" ]
https://github.com/joeferraro/MavensMate-SublimeText/blob/af36de7ffaa9b0541f446145736a48b1c66ac0cf/lib/response_handler.py#L118-L121
securesystemslab/zippy
ff0e84ac99442c2c55fe1d285332cfd4e185e089
zippy/benchmarks/src/benchmarks/sympy/sympy/functions/elementary/piecewise.py
python
Piecewise._eval_derivative
(self, x)
return self.func(*[(diff(e, x), c) for e, c in self.args])
[]
def _eval_derivative(self, x): return self.func(*[(diff(e, x), c) for e, c in self.args])
[ "def", "_eval_derivative", "(", "self", ",", "x", ")", ":", "return", "self", ".", "func", "(", "*", "[", "(", "diff", "(", "e", ",", "x", ")", ",", "c", ")", "for", "e", ",", "c", "in", "self", ".", "args", "]", ")" ]
https://github.com/securesystemslab/zippy/blob/ff0e84ac99442c2c55fe1d285332cfd4e185e089/zippy/benchmarks/src/benchmarks/sympy/sympy/functions/elementary/piecewise.py#L192-L193
parkouss/webmacs
35f174303af8c9147825c45ad41ff35706fa8bfa
webmacs/commands/content_edit.py
python
cancel
(ctx)
If a mark is active, clear that but keep the focus. If there is no active mark, then just unfocus the editable js object.
If a mark is active, clear that but keep the focus. If there is no active mark, then just unfocus the editable js object.
[ "If", "a", "mark", "is", "active", "clear", "that", "but", "keep", "the", "focus", ".", "If", "there", "is", "no", "active", "mark", "then", "just", "unfocus", "the", "editable", "js", "object", "." ]
def cancel(ctx): """ If a mark is active, clear that but keep the focus. If there is no active mark, then just unfocus the editable js object. """ if ctx.buffer.hasSelection(): run_js(ctx, "textedit.clear_mark();") else: run_js(ctx, "textedit.blur();") ctx.buffer.set_text_edit_mark(False)
[ "def", "cancel", "(", "ctx", ")", ":", "if", "ctx", ".", "buffer", ".", "hasSelection", "(", ")", ":", "run_js", "(", "ctx", ",", "\"textedit.clear_mark();\"", ")", "else", ":", "run_js", "(", "ctx", ",", "\"textedit.blur();\"", ")", "ctx", ".", "buffer"...
https://github.com/parkouss/webmacs/blob/35f174303af8c9147825c45ad41ff35706fa8bfa/webmacs/commands/content_edit.py#L49-L58
edisonlz/fastor
342078a18363ac41d3c6b1ab29dbdd44fdb0b7b3
base/site-packages/tencentcloud/tbm/v20180129/models.py
python
MoviePortraitInfo.__init__
(self)
:param PortraitSet: 用户喜好电影画像数组 :type PortraitSet: list of MoviePortrait
:param PortraitSet: 用户喜好电影画像数组 :type PortraitSet: list of MoviePortrait
[ ":", "param", "PortraitSet", ":", "用户喜好电影画像数组", ":", "type", "PortraitSet", ":", "list", "of", "MoviePortrait" ]
def __init__(self): """ :param PortraitSet: 用户喜好电影画像数组 :type PortraitSet: list of MoviePortrait """ self.PortraitSet = None
[ "def", "__init__", "(", "self", ")", ":", "self", ".", "PortraitSet", "=", "None" ]
https://github.com/edisonlz/fastor/blob/342078a18363ac41d3c6b1ab29dbdd44fdb0b7b3/base/site-packages/tencentcloud/tbm/v20180129/models.py#L861-L866
arthurdejong/python-stdnum
02dec52602ae0709b940b781fc1fcebfde7340b7
stdnum/isan.py
python
split
(number)
Split the number into a root, an episode or part, a check digit a version and another check digit. If any of the parts are missing an empty string is returned.
Split the number into a root, an episode or part, a check digit a version and another check digit. If any of the parts are missing an empty string is returned.
[ "Split", "the", "number", "into", "a", "root", "an", "episode", "or", "part", "a", "check", "digit", "a", "version", "and", "another", "check", "digit", ".", "If", "any", "of", "the", "parts", "are", "missing", "an", "empty", "string", "is", "returned", ...
def split(number): """Split the number into a root, an episode or part, a check digit a version and another check digit. If any of the parts are missing an empty string is returned.""" number = clean(number, ' -').strip().upper() if len(number) == 17 or len(number) == 26: return number[0:12], number[12:16], number[16], number[17:25], number[25:] elif len(number) > 16: return number[0:12], number[12:16], '', number[16:24], number[24:] else: return number[0:12], number[12:16], number[16:], '', ''
[ "def", "split", "(", "number", ")", ":", "number", "=", "clean", "(", "number", ",", "' -'", ")", ".", "strip", "(", ")", ".", "upper", "(", ")", "if", "len", "(", "number", ")", "==", "17", "or", "len", "(", "number", ")", "==", "26", ":", "...
https://github.com/arthurdejong/python-stdnum/blob/02dec52602ae0709b940b781fc1fcebfde7340b7/stdnum/isan.py#L55-L65
duduainankai/zhihu-terminal
cd57efc606138eee84385a6425998814a0029043
login.py
python
login
(account=None, password=None, debug=False)
result: {"result": True} {"error": {"code": 19855555, "message": "unknown.", "data": "data" } } {"error": {"code": -1, "message": u"unknown error"} }
result: {"result": True} {"error": {"code": 19855555, "message": "unknown.", "data": "data" } } {"error": {"code": -1, "message": u"unknown error"} }
[ "result", ":", "{", "result", ":", "True", "}", "{", "error", ":", "{", "code", ":", "19855555", "message", ":", "unknown", ".", "data", ":", "data", "}", "}", "{", "error", ":", "{", "code", ":", "-", "1", "message", ":", "u", "unknown", "error"...
def login(account=None, password=None, debug=False): if islogin() == True: Logging.success(u"你已经登录过咯") return True if account == None: (account, password) = read_account_from_config_file() if account == None: sys.stdout.write(u"请输入登录账号: ") account = raw_input() password = getpass("请输入登录密码: ") form_data = build_form(account, password) """ result: {"result": True} {"error": {"code": 19855555, "message": "unknown.", "data": "data" } } {"error": {"code": -1, "message": u"unknown error"} } """ result = upload_form(form_data) if "error" in result: if result["error"]['code'] == 1991829: # 验证码错误 Logging.error(u"验证码输入错误,请准备重新输入。" ) return login(debug=True) elif result["error"]['code'] == 100005: # 密码错误 Logging.error(u"密码输入错误,请准备重新输入。" ) return login() else: Logging.warn(u"unknown error." ) return False elif "result" in result and result['result'] == True: # 登录成功 Logging.success(u"登录成功!" ) if debug: print termcolor.colored("执行python zhihu.py, 可以体验在终端中刷知乎咯.^_^", "cyan") session.cookies.save() return True
[ "def", "login", "(", "account", "=", "None", ",", "password", "=", "None", ",", "debug", "=", "False", ")", ":", "if", "islogin", "(", ")", "==", "True", ":", "Logging", ".", "success", "(", "u\"你已经登录过咯\")", "", "return", "True", "if", "account", "==...
https://github.com/duduainankai/zhihu-terminal/blob/cd57efc606138eee84385a6425998814a0029043/login.py#L215-L253
reahl/reahl
86aac47c3a9b5b98e9f77dad4939034a02d54d46
reahl-tofu/reahl/tofu/files.py
python
AutomaticallyDeletedDirectory.file_with
(self, name, contents, mode='w+')
return f
Returns a file inside this directory with the given `name` and `contents`.
Returns a file inside this directory with the given `name` and `contents`.
[ "Returns", "a", "file", "inside", "this", "directory", "with", "the", "given", "name", "and", "contents", "." ]
def file_with(self, name, contents, mode='w+'): """Returns a file inside this directory with the given `name` and `contents`.""" if name is None: handle, full_name = tempfile.mkstemp(dir=self.name) name = os.path.basename(full_name) f = AutomaticallyDeletedFile('%s/%s' % (self.name, name), contents, mode) self.entries.append(f) return f
[ "def", "file_with", "(", "self", ",", "name", ",", "contents", ",", "mode", "=", "'w+'", ")", ":", "if", "name", "is", "None", ":", "handle", ",", "full_name", "=", "tempfile", ".", "mkstemp", "(", "dir", "=", "self", ".", "name", ")", "name", "=",...
https://github.com/reahl/reahl/blob/86aac47c3a9b5b98e9f77dad4939034a02d54d46/reahl-tofu/reahl/tofu/files.py#L101-L108
bbfamily/abu
2de85ae57923a720dac99a545b4f856f6b87304b
abupy/FactorSellBu/ABuFactorSellBase.py
python
AbuFactorSellXD._init_self
(self, **kwargs)
kwargs中必须包含: 突破参数xd 比如20,30,40天...突破
kwargs中必须包含: 突破参数xd 比如20,30,40天...突破
[ "kwargs中必须包含", ":", "突破参数xd", "比如20,30,40天", "...", "突破" ]
def _init_self(self, **kwargs): """kwargs中必须包含: 突破参数xd 比如20,30,40天...突破""" # 向下突破参数 xd, 比如20,30,40天...突破 self.xd = kwargs['xd'] # 在输出生成的orders_pd中显示的名字 self.sell_type_extra = '{}:{}'.format(self.__class__.__name__, self.xd)
[ "def", "_init_self", "(", "self", ",", "*", "*", "kwargs", ")", ":", "# 向下突破参数 xd, 比如20,30,40天...突破", "self", ".", "xd", "=", "kwargs", "[", "'xd'", "]", "# 在输出生成的orders_pd中显示的名字", "self", ".", "sell_type_extra", "=", "'{}:{}'", ".", "format", "(", "self", "...
https://github.com/bbfamily/abu/blob/2de85ae57923a720dac99a545b4f856f6b87304b/abupy/FactorSellBu/ABuFactorSellBase.py#L180-L185
pydicom/pynetdicom
f57d8214c82b63c8e76638af43ce331f584a80fa
pynetdicom/apps/common.py
python
ElementPath.parent
(self)
return self._parent
Return the current object's parent ElementPath. Returns ------- ElementPath or None If the current component was part of a larger path then returns the previous component as an ``ElementPath``, otherwise returns ``None``.
Return the current object's parent ElementPath.
[ "Return", "the", "current", "object", "s", "parent", "ElementPath", "." ]
def parent(self): """Return the current object's parent ElementPath. Returns ------- ElementPath or None If the current component was part of a larger path then returns the previous component as an ``ElementPath``, otherwise returns ``None``. """ return self._parent
[ "def", "parent", "(", "self", ")", ":", "return", "self", ".", "_parent" ]
https://github.com/pydicom/pynetdicom/blob/f57d8214c82b63c8e76638af43ce331f584a80fa/pynetdicom/apps/common.py#L261-L271
MDAnalysis/mdanalysis
3488df3cdb0c29ed41c4fb94efe334b541e31b21
package/MDAnalysis/core/groups.py
python
GroupBase.difference
(self, other)
return self._derived_class(np.setdiff1d(self._ix, o_ix), self._u)
Elements from this Group that do not appear in another This method removes duplicate elements and sorts the result. As such, it is different from :meth:`subtract`. :meth:`difference` is synomymous to the `-` operator. Parameters ---------- other : Group or Component Group or Component with `other.level` same as `self.level` Returns ------- Group Group with the elements of `self` that are not in `other`, without duplicate elements See Also -------- subtract, symmetric_difference .. versionadded:: 0.16
Elements from this Group that do not appear in another
[ "Elements", "from", "this", "Group", "that", "do", "not", "appear", "in", "another" ]
def difference(self, other): """Elements from this Group that do not appear in another This method removes duplicate elements and sorts the result. As such, it is different from :meth:`subtract`. :meth:`difference` is synomymous to the `-` operator. Parameters ---------- other : Group or Component Group or Component with `other.level` same as `self.level` Returns ------- Group Group with the elements of `self` that are not in `other`, without duplicate elements See Also -------- subtract, symmetric_difference .. versionadded:: 0.16 """ o_ix = other.ix_array return self._derived_class(np.setdiff1d(self._ix, o_ix), self._u)
[ "def", "difference", "(", "self", ",", "other", ")", ":", "o_ix", "=", "other", ".", "ix_array", "return", "self", ".", "_derived_class", "(", "np", ".", "setdiff1d", "(", "self", ".", "_ix", ",", "o_ix", ")", ",", "self", ".", "_u", ")" ]
https://github.com/MDAnalysis/mdanalysis/blob/3488df3cdb0c29ed41c4fb94efe334b541e31b21/package/MDAnalysis/core/groups.py#L2123-L2149
datalad/datalad
d8c8383d878a207bb586415314219a60c345f732
datalad/utils.py
python
swallow_logs
(new_level=None, file_=None, name='datalad')
Context manager to consume all logs.
Context manager to consume all logs.
[ "Context", "manager", "to", "consume", "all", "logs", "." ]
def swallow_logs(new_level=None, file_=None, name='datalad'): """Context manager to consume all logs. """ lgr = logging.getLogger(name) # Keep old settings old_level = lgr.level old_handlers = lgr.handlers # Let's log everything into a string # TODO: generalize with the one for swallow_outputs class StringIOAdapter(object): """Little adapter to help getting out values And to stay consistent with how swallow_outputs behaves """ def __init__(self): if file_ is None: kw = get_tempfile_kwargs({}, prefix="logs") self._out = NamedTemporaryFile(mode='a', delete=False, **kw) else: out_file = file_ # PY3 requires clearly one or another. race condition possible self._out = open(out_file, 'a') self._final_out = None def _read(self, h): with open(h.name) as f: return f.read() @property def out(self): if self._final_out is not None: # we closed and cleaned up already return self._final_out else: self._out.flush() return self._read(self._out) @property def lines(self): return self.out.split('\n') @property def handle(self): return self._out def cleanup(self): # store for access while object exists self._final_out = self.out self._out.close() out_name = self._out.name del self._out gc.collect() if not file_: rmtemp(out_name) def assert_logged(self, msg=None, level=None, regex=True, **kwargs): """Provide assertion on whether a msg was logged at a given level If neither `msg` nor `level` provided, checks if anything was logged at all. Parameters ---------- msg: str, optional Message (as a regular expression, if `regex`) to be searched. If no msg provided, checks if anything was logged at a given level. level: str, optional String representing the level to be logged regex: bool, optional If False, regular `assert_in` is used **kwargs: str, optional Passed to `assert_re_in` or `assert_in` """ from datalad.tests.utils import assert_re_in from datalad.tests.utils import assert_in if regex: match = r'\[%s\] ' % level if level else r"\[\S+\] " else: match = '[%s] ' % level if level else '' if msg: match += msg if match: (assert_re_in if regex else assert_in)(match, self.out, **kwargs) else: assert not kwargs, "no kwargs to be passed anywhere" assert self.out, "Nothing was logged!?" adapter = StringIOAdapter() # TODO: it does store messages but without any formatting, i.e. even without # date/time prefix etc. IMHO it should preserve formatting in case if file_ is # set swallow_handler = logging.StreamHandler(adapter.handle) # we want to log levelname so we could test against it swallow_handler.setFormatter( logging.Formatter('[%(levelname)s] %(message)s')) swallow_handler.filters = sum([h.filters for h in old_handlers], []) lgr.handlers = [swallow_handler] if old_level < logging.DEBUG: # so if HEAVYDEBUG etc -- show them! lgr.handlers += old_handlers if isinstance(new_level, str): new_level = getattr(logging, new_level) if new_level is not None: lgr.setLevel(new_level) try: yield adapter # TODO: if file_ and there was an exception -- most probably worth logging it? # although ideally it should be the next log outside added to that file_ ... oh well finally: lgr.handlers = old_handlers lgr.setLevel(old_level) adapter.cleanup()
[ "def", "swallow_logs", "(", "new_level", "=", "None", ",", "file_", "=", "None", ",", "name", "=", "'datalad'", ")", ":", "lgr", "=", "logging", ".", "getLogger", "(", "name", ")", "# Keep old settings", "old_level", "=", "lgr", ".", "level", "old_handlers...
https://github.com/datalad/datalad/blob/d8c8383d878a207bb586415314219a60c345f732/datalad/utils.py#L1403-L1523
Komodo/KomodoEdit
61edab75dce2bdb03943b387b0608ea36f548e8e
src/codeintel/play/core.py
python
MouseEvent.GetLogicalPosition
(*args, **kwargs)
return _core.MouseEvent_GetLogicalPosition(*args, **kwargs)
GetLogicalPosition(DC dc) -> Point
GetLogicalPosition(DC dc) -> Point
[ "GetLogicalPosition", "(", "DC", "dc", ")", "-", ">", "Point" ]
def GetLogicalPosition(*args, **kwargs): """GetLogicalPosition(DC dc) -> Point""" return _core.MouseEvent_GetLogicalPosition(*args, **kwargs)
[ "def", "GetLogicalPosition", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core", ".", "MouseEvent_GetLogicalPosition", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/Komodo/KomodoEdit/blob/61edab75dce2bdb03943b387b0608ea36f548e8e/src/codeintel/play/core.py#L3413-L3415
openhatch/oh-mainline
ce29352a034e1223141dcc2f317030bbc3359a51
vendor/packages/twisted/twisted/internet/interfaces.py
python
IResolver.lookupMailRename
(name, timeout = 10)
Lookup the MR records associated with C{name}.
Lookup the MR records associated with C{name}.
[ "Lookup", "the", "MR", "records", "associated", "with", "C", "{", "name", "}", "." ]
def lookupMailRename(name, timeout = 10): """ Lookup the MR records associated with C{name}. """
[ "def", "lookupMailRename", "(", "name", ",", "timeout", "=", "10", ")", ":" ]
https://github.com/openhatch/oh-mainline/blob/ce29352a034e1223141dcc2f317030bbc3359a51/vendor/packages/twisted/twisted/internet/interfaces.py#L131-L134
smart-mobile-software/gitstack
d9fee8f414f202143eb6e620529e8e5539a2af56
python/Lib/platform.py
python
python_compiler
()
return _sys_version()[6]
Returns a string identifying the compiler used for compiling Python.
Returns a string identifying the compiler used for compiling Python.
[ "Returns", "a", "string", "identifying", "the", "compiler", "used", "for", "compiling", "Python", "." ]
def python_compiler(): """ Returns a string identifying the compiler used for compiling Python. """ return _sys_version()[6]
[ "def", "python_compiler", "(", ")", ":", "return", "_sys_version", "(", ")", "[", "6", "]" ]
https://github.com/smart-mobile-software/gitstack/blob/d9fee8f414f202143eb6e620529e8e5539a2af56/python/Lib/platform.py#L1515-L1521
rhinstaller/anaconda
63edc8680f1b05cbfe11bef28703acba808c5174
pyanaconda/modules/payloads/payload/live_os/live_os.py
python
LiveOSModule.install_with_tasks
(self)
return [task]
Install the payload with tasks.
Install the payload with tasks.
[ "Install", "the", "payload", "with", "tasks", "." ]
def install_with_tasks(self): """Install the payload with tasks.""" image_source = self._get_source(SourceType.LIVE_OS_IMAGE) if not image_source: log.debug("No Live OS image is available.") return [] task = InstallFromImageTask( sysroot=conf.target.system_root, mount_point=image_source.mount_point ) task.succeeded_signal.connect( lambda: self._update_kernel_version_list(image_source) ) return [task]
[ "def", "install_with_tasks", "(", "self", ")", ":", "image_source", "=", "self", ".", "_get_source", "(", "SourceType", ".", "LIVE_OS_IMAGE", ")", "if", "not", "image_source", ":", "log", ".", "debug", "(", "\"No Live OS image is available.\"", ")", "return", "[...
https://github.com/rhinstaller/anaconda/blob/63edc8680f1b05cbfe11bef28703acba808c5174/pyanaconda/modules/payloads/payload/live_os/live_os.py#L56-L73
python-gitlab/python-gitlab
4a000b6c41f0a7ef6121c62a4c598edc20973799
gitlab/v4/objects/commits.py
python
ProjectCommit.revert
( self, branch: str, **kwargs: Any )
return self.manager.gitlab.http_post(path, post_data=post_data, **kwargs)
Revert a commit on a given branch. Args: branch: Name of target branch **kwargs: Extra options to send to the server (e.g. sudo) Raises: GitlabAuthenticationError: If authentication is not correct GitlabRevertError: If the revert could not be performed Returns: The new commit data (*not* a RESTObject)
Revert a commit on a given branch.
[ "Revert", "a", "commit", "on", "a", "given", "branch", "." ]
def revert( self, branch: str, **kwargs: Any ) -> Union[Dict[str, Any], requests.Response]: """Revert a commit on a given branch. Args: branch: Name of target branch **kwargs: Extra options to send to the server (e.g. sudo) Raises: GitlabAuthenticationError: If authentication is not correct GitlabRevertError: If the revert could not be performed Returns: The new commit data (*not* a RESTObject) """ path = f"{self.manager.path}/{self.get_id()}/revert" post_data = {"branch": branch} return self.manager.gitlab.http_post(path, post_data=post_data, **kwargs)
[ "def", "revert", "(", "self", ",", "branch", ":", "str", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "Union", "[", "Dict", "[", "str", ",", "Any", "]", ",", "requests", ".", "Response", "]", ":", "path", "=", "f\"{self.manager.path}/{self.get_id()}...
https://github.com/python-gitlab/python-gitlab/blob/4a000b6c41f0a7ef6121c62a4c598edc20973799/gitlab/v4/objects/commits.py#L109-L127
awni/speech
a5909a3e18c072150101aeaf9103e03b69e5b53b
speech/models/model.py
python
Model.infer
(self, x)
Must be overridden by subclasses.
Must be overridden by subclasses.
[ "Must", "be", "overridden", "by", "subclasses", "." ]
def infer(self, x): """ Must be overridden by subclasses. """ raise NotImplementedError
[ "def", "infer", "(", "self", ",", "x", ")", ":", "raise", "NotImplementedError" ]
https://github.com/awni/speech/blob/a5909a3e18c072150101aeaf9103e03b69e5b53b/speech/models/model.py#L101-L105
tp4a/teleport
1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad
server/www/packages/packages-darwin/x64/mako/template.py
python
Template.cache
(self)
return cache.Cache(self)
[]
def cache(self): return cache.Cache(self)
[ "def", "cache", "(", "self", ")", ":", "return", "cache", ".", "Cache", "(", "self", ")" ]
https://github.com/tp4a/teleport/blob/1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad/server/www/packages/packages-darwin/x64/mako/template.py#L435-L436
chribsen/simple-machine-learning-examples
dc94e52a4cebdc8bb959ff88b81ff8cfeca25022
venv/lib/python2.7/site-packages/pandas/core/frame.py
python
DataFrame.info
(self, verbose=None, buf=None, max_cols=None, memory_usage=None, null_counts=None)
Concise summary of a DataFrame. Parameters ---------- verbose : {None, True, False}, optional Whether to print the full summary. None follows the `display.max_info_columns` setting. True or False overrides the `display.max_info_columns` setting. buf : writable buffer, defaults to sys.stdout max_cols : int, default None Determines whether full summary or short summary is printed. None follows the `display.max_info_columns` setting. memory_usage : boolean/string, default None Specifies whether total memory usage of the DataFrame elements (including index) should be displayed. None follows the `display.memory_usage` setting. True or False overrides the `display.memory_usage` setting. A value of 'deep' is equivalent of True, with deep introspection. Memory usage is shown in human-readable units (base-2 representation). null_counts : boolean, default None Whether to show the non-null counts - If None, then only show if the frame is smaller than max_info_rows and max_info_columns. - If True, always show counts. - If False, never show counts.
Concise summary of a DataFrame.
[ "Concise", "summary", "of", "a", "DataFrame", "." ]
def info(self, verbose=None, buf=None, max_cols=None, memory_usage=None, null_counts=None): """ Concise summary of a DataFrame. Parameters ---------- verbose : {None, True, False}, optional Whether to print the full summary. None follows the `display.max_info_columns` setting. True or False overrides the `display.max_info_columns` setting. buf : writable buffer, defaults to sys.stdout max_cols : int, default None Determines whether full summary or short summary is printed. None follows the `display.max_info_columns` setting. memory_usage : boolean/string, default None Specifies whether total memory usage of the DataFrame elements (including index) should be displayed. None follows the `display.memory_usage` setting. True or False overrides the `display.memory_usage` setting. A value of 'deep' is equivalent of True, with deep introspection. Memory usage is shown in human-readable units (base-2 representation). null_counts : boolean, default None Whether to show the non-null counts - If None, then only show if the frame is smaller than max_info_rows and max_info_columns. - If True, always show counts. - If False, never show counts. """ from pandas.formats.format import _put_lines if buf is None: # pragma: no cover buf = sys.stdout lines = [] lines.append(str(type(self))) lines.append(self.index.summary()) if len(self.columns) == 0: lines.append('Empty %s' % type(self).__name__) _put_lines(buf, lines) return cols = self.columns # hack if max_cols is None: max_cols = get_option('display.max_info_columns', len(self.columns) + 1) max_rows = get_option('display.max_info_rows', len(self) + 1) if null_counts is None: show_counts = ((len(self.columns) <= max_cols) and (len(self) < max_rows)) else: show_counts = null_counts exceeds_info_cols = len(self.columns) > max_cols def _verbose_repr(): lines.append('Data columns (total %d columns):' % len(self.columns)) space = max([len(pprint_thing(k)) for k in self.columns]) + 4 counts = None tmpl = "%s%s" if show_counts: counts = self.count() if len(cols) != len(counts): # pragma: no cover raise AssertionError('Columns must equal counts (%d != %d)' % (len(cols), len(counts))) tmpl = "%s non-null %s" dtypes = self.dtypes for i, col in enumerate(self.columns): dtype = dtypes.iloc[i] col = pprint_thing(col) count = "" if show_counts: count = counts.iloc[i] lines.append(_put_str(col, space) + tmpl % (count, dtype)) def _non_verbose_repr(): lines.append(self.columns.summary(name='Columns')) def _sizeof_fmt(num, size_qualifier): # returns size in human readable format for x in ['bytes', 'KB', 'MB', 'GB', 'TB']: if num < 1024.0: return "%3.1f%s %s" % (num, size_qualifier, x) num /= 1024.0 return "%3.1f%s %s" % (num, size_qualifier, 'PB') if verbose: _verbose_repr() elif verbose is False: # specifically set to False, not nesc None _non_verbose_repr() else: if exceeds_info_cols: _non_verbose_repr() else: _verbose_repr() counts = self.get_dtype_counts() dtypes = ['%s(%d)' % k for k in sorted(compat.iteritems(counts))] lines.append('dtypes: %s' % ', '.join(dtypes)) if memory_usage is None: memory_usage = get_option('display.memory_usage') if memory_usage: # append memory usage of df to display size_qualifier = '' if memory_usage == 'deep': deep = True else: # size_qualifier is just a best effort; not guaranteed to catch # all cases (e.g., it misses categorical data even with object # categories) deep = False if 'object' in counts or is_object_dtype(self.index): size_qualifier = '+' mem_usage = self.memory_usage(index=True, deep=deep).sum() lines.append("memory usage: %s\n" % _sizeof_fmt(mem_usage, size_qualifier)) _put_lines(buf, lines)
[ "def", "info", "(", "self", ",", "verbose", "=", "None", ",", "buf", "=", "None", ",", "max_cols", "=", "None", ",", "memory_usage", "=", "None", ",", "null_counts", "=", "None", ")", ":", "from", "pandas", ".", "formats", ".", "format", "import", "_...
https://github.com/chribsen/simple-machine-learning-examples/blob/dc94e52a4cebdc8bb959ff88b81ff8cfeca25022/venv/lib/python2.7/site-packages/pandas/core/frame.py#L1669-L1798
gramps-project/gramps
04d4651a43eb210192f40a9f8c2bad8ee8fa3753
gramps/gen/proxy/proxybase.py
python
ProxyDbBase.get_family_relation_types
(self)
return self.db.get_family_relation_types()
returns a list of all relationship types associated with Family instances in the database
returns a list of all relationship types associated with Family instances in the database
[ "returns", "a", "list", "of", "all", "relationship", "types", "associated", "with", "Family", "instances", "in", "the", "database" ]
def get_family_relation_types(self): """returns a list of all relationship types associated with Family instances in the database""" return self.db.get_family_relation_types()
[ "def", "get_family_relation_types", "(", "self", ")", ":", "return", "self", ".", "db", ".", "get_family_relation_types", "(", ")" ]
https://github.com/gramps-project/gramps/blob/04d4651a43eb210192f40a9f8c2bad8ee8fa3753/gramps/gen/proxy/proxybase.py#L772-L775
IronLanguages/main
a949455434b1fda8c783289e897e78a9a0caabb5
External.LCA_RESTRICTED/Languages/IronPython/27/Lib/mailbox.py
python
_singlefileMailbox._post_message_hook
(self, f)
return
Called after writing each message to file f.
Called after writing each message to file f.
[ "Called", "after", "writing", "each", "message", "to", "file", "f", "." ]
def _post_message_hook(self, f): """Called after writing each message to file f.""" return
[ "def", "_post_message_hook", "(", "self", ",", "f", ")", ":", "return" ]
https://github.com/IronLanguages/main/blob/a949455434b1fda8c783289e897e78a9a0caabb5/External.LCA_RESTRICTED/Languages/IronPython/27/Lib/mailbox.py#L716-L718
implus/PytorchInsight
2864528f8b83f52c3df76f7c3804aa468b91e5cf
detection/mmdet/models/backbones/resnet_gc.py
python
Bottleneck.forward
(self, x)
return out
[]
def forward(self, x): def _inner_forward(x): identity = x out = self.conv1(x) out = self.norm1(out) out = self.relu(out) if not self.with_dcn: out = self.conv2(out) elif self.with_modulated_dcn: offset_mask = self.conv2_offset(out) offset = offset_mask[:, :18, :, :] mask = offset_mask[:, -9:, :, :].sigmoid() out = self.conv2(out, offset, mask) else: offset = self.conv2_offset(out) out = self.conv2(out, offset) out = self.norm2(out) out = self.relu(out) out = self.conv3(out) out = self.norm3(out) out = self.gc(out) if self.downsample is not None: identity = self.downsample(x) out += identity return out if self.with_cp and x.requires_grad: out = cp.checkpoint(_inner_forward, x) else: out = _inner_forward(x) out = self.relu(out) return out
[ "def", "forward", "(", "self", ",", "x", ")", ":", "def", "_inner_forward", "(", "x", ")", ":", "identity", "=", "x", "out", "=", "self", ".", "conv1", "(", "x", ")", "out", "=", "self", ".", "norm1", "(", "out", ")", "out", "=", "self", ".", ...
https://github.com/implus/PytorchInsight/blob/2864528f8b83f52c3df76f7c3804aa468b91e5cf/detection/mmdet/models/backbones/resnet_gc.py#L193-L234
davidhalter/parso
ee5edaf22ff3941cbdfa4efd8cb3e8f69779fd56
parso/python/tokenize.py
python
tokenize
( code: str, *, version_info: PythonVersionInfo, start_pos: Tuple[int, int] = (1, 0) )
return tokenize_lines(lines, version_info=version_info, start_pos=start_pos)
Generate tokens from a the source code (string).
Generate tokens from a the source code (string).
[ "Generate", "tokens", "from", "a", "the", "source", "code", "(", "string", ")", "." ]
def tokenize( code: str, *, version_info: PythonVersionInfo, start_pos: Tuple[int, int] = (1, 0) ) -> Iterator[PythonToken]: """Generate tokens from a the source code (string).""" lines = split_lines(code, keepends=True) return tokenize_lines(lines, version_info=version_info, start_pos=start_pos)
[ "def", "tokenize", "(", "code", ":", "str", ",", "*", ",", "version_info", ":", "PythonVersionInfo", ",", "start_pos", ":", "Tuple", "[", "int", ",", "int", "]", "=", "(", "1", ",", "0", ")", ")", "->", "Iterator", "[", "PythonToken", "]", ":", "li...
https://github.com/davidhalter/parso/blob/ee5edaf22ff3941cbdfa4efd8cb3e8f69779fd56/parso/python/tokenize.py#L342-L347
uber-archive/plato-research-dialogue-system
1db30be390df6903be89fdf5a515debc7d7defb4
plato/agent/component/dialogue_policy/deep_learning/reinforce_policy.py
python
ReinforcePolicy.initialize
(self, args)
Initialize internal structures at the beginning of each dialogue :return: Nothing
Initialize internal structures at the beginning of each dialogue
[ "Initialize", "internal", "structures", "at", "the", "beginning", "of", "each", "dialogue" ]
def initialize(self, args): """ Initialize internal structures at the beginning of each dialogue :return: Nothing """ if 'is_training' in args: self.is_training = bool(args['is_training']) if self.agent_role == 'user' and self.warmup_simulator: if 'goal' in args: self.warmup_simulator.initialize({args['goal']}) else: print('WARNING ! No goal provided for Reinforce policy ' 'user simulator @ initialize') self.warmup_simulator.initialize({}) if 'policy_path' in args: self.policy_path = args['policy_path'] if 'learning_rate' in args: self.alpha = args['learning_rate'] if 'learning_decay_rate' in args: self.alpha_decay_rate = args['learning_decay_rate'] if 'discount_factor' in args: self.gamma = args['discount_factor'] if 'exploration_rate' in args: self.alpha = args['exploration_rate'] if 'exploration_decay_rate' in args: self.exploration_decay_rate = args['exploration_decay_rate'] if self.weights is None: self.weights = np.random.rand(self.NStateFeatures, self.NActions)
[ "def", "initialize", "(", "self", ",", "args", ")", ":", "if", "'is_training'", "in", "args", ":", "self", ".", "is_training", "=", "bool", "(", "args", "[", "'is_training'", "]", ")", "if", "self", ".", "agent_role", "==", "'user'", "and", "self", "."...
https://github.com/uber-archive/plato-research-dialogue-system/blob/1db30be390df6903be89fdf5a515debc7d7defb4/plato/agent/component/dialogue_policy/deep_learning/reinforce_policy.py#L222-L259
Samsung/cotopaxi
d19178b1235017257fec20d0a41edc918de55574
cotopaxi/coap_utils.py
python
CoAPTester.protocol_full_name
()
return "Constrained Application Protocol"
Provide full (not abbreviated) name of protocol.
Provide full (not abbreviated) name of protocol.
[ "Provide", "full", "(", "not", "abbreviated", ")", "name", "of", "protocol", "." ]
def protocol_full_name(): """Provide full (not abbreviated) name of protocol.""" return "Constrained Application Protocol"
[ "def", "protocol_full_name", "(", ")", ":", "return", "\"Constrained Application Protocol\"" ]
https://github.com/Samsung/cotopaxi/blob/d19178b1235017257fec20d0a41edc918de55574/cotopaxi/coap_utils.py#L232-L234
pyinstaller/pyinstaller
872312500a8a324d25fb405f85117f7966a0ebd5
PyInstaller/depend/imphookapi.py
python
PostGraphAPI.node
(self)
return self.module
Graph node for the currently hooked module. **This property has been deprecated by the `module` property.**
Graph node for the currently hooked module.
[ "Graph", "node", "for", "the", "currently", "hooked", "module", "." ]
def node(self): """ Graph node for the currently hooked module. **This property has been deprecated by the `module` property.** """ return self.module
[ "def", "node", "(", "self", ")", ":", "return", "self", ".", "module" ]
https://github.com/pyinstaller/pyinstaller/blob/872312500a8a324d25fb405f85117f7966a0ebd5/PyInstaller/depend/imphookapi.py#L391-L397