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
qutebrowser/qutebrowser
3a2aaaacbf97f4bf0c72463f3da94ed2822a5442
qutebrowser/completion/models/miscmodels.py
python
process
(*, info)
return model
A CompletionModel filled with processes.
A CompletionModel filled with processes.
[ "A", "CompletionModel", "filled", "with", "processes", "." ]
def process(*, info): """A CompletionModel filled with processes.""" utils.unused(info) from qutebrowser.misc import guiprocess model = completionmodel.CompletionModel(column_widths=(10, 10, 80)) for what, processes in itertools.groupby( (p for p in guiprocess.all_processes.values() if p is not None), lambda proc: proc.what): # put successful processes last sorted_processes = sorted( processes, key=lambda proc: proc.outcome.state_str() == 'successful', ) entries = [(str(proc.pid), proc.outcome.state_str(), str(proc)) for proc in sorted_processes] cat = listcategory.ListCategory(what.capitalize(), entries, sort=False) model.add_category(cat) return model
[ "def", "process", "(", "*", ",", "info", ")", ":", "utils", ".", "unused", "(", "info", ")", "from", "qutebrowser", ".", "misc", "import", "guiprocess", "model", "=", "completionmodel", ".", "CompletionModel", "(", "column_widths", "=", "(", "10", ",", "10", ",", "80", ")", ")", "for", "what", ",", "processes", "in", "itertools", ".", "groupby", "(", "(", "p", "for", "p", "in", "guiprocess", ".", "all_processes", ".", "values", "(", ")", "if", "p", "is", "not", "None", ")", ",", "lambda", "proc", ":", "proc", ".", "what", ")", ":", "# put successful processes last", "sorted_processes", "=", "sorted", "(", "processes", ",", "key", "=", "lambda", "proc", ":", "proc", ".", "outcome", ".", "state_str", "(", ")", "==", "'successful'", ",", ")", "entries", "=", "[", "(", "str", "(", "proc", ".", "pid", ")", ",", "proc", ".", "outcome", ".", "state_str", "(", ")", ",", "str", "(", "proc", ")", ")", "for", "proc", "in", "sorted_processes", "]", "cat", "=", "listcategory", ".", "ListCategory", "(", "what", ".", "capitalize", "(", ")", ",", "entries", ",", "sort", "=", "False", ")", "model", ".", "add_category", "(", "cat", ")", "return", "model" ]
https://github.com/qutebrowser/qutebrowser/blob/3a2aaaacbf97f4bf0c72463f3da94ed2822a5442/qutebrowser/completion/models/miscmodels.py#L306-L325
etetoolkit/ete
2b207357dc2a40ccad7bfd8f54964472c72e4726
ete3/phyloxml/_phyloxml.py
python
ProteinDomain.build
(self, node)
[]
def build(self, node): self.buildAttributes(node, node.attrib, []) self.valueOf_ = get_all_text_(node) for child in node: nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] self.buildChildren(child, node, nodeName_)
[ "def", "build", "(", "self", ",", "node", ")", ":", "self", ".", "buildAttributes", "(", "node", ",", "node", ".", "attrib", ",", "[", "]", ")", "self", ".", "valueOf_", "=", "get_all_text_", "(", "node", ")", "for", "child", "in", "node", ":", "nodeName_", "=", "Tag_pattern_", ".", "match", "(", "child", ".", "tag", ")", ".", "groups", "(", ")", "[", "-", "1", "]", "self", ".", "buildChildren", "(", "child", ",", "node", ",", "nodeName_", ")" ]
https://github.com/etetoolkit/ete/blob/2b207357dc2a40ccad7bfd8f54964472c72e4726/ete3/phyloxml/_phyloxml.py#L1997-L2002
RunestoneInteractive/RunestoneServer
b20fcca5f08350224f63838250302771656f0951
controllers/assignments.py
python
student_autograde
()
return json.dumps(res)
This is a safe endpoint that students can call from the assignment page to get a preliminary grade on their assignment. If in coursera_mode, the total for the assignment is calculated and stored in the db, and sent via LTI (if LTI is configured).
This is a safe endpoint that students can call from the assignment page to get a preliminary grade on their assignment. If in coursera_mode, the total for the assignment is calculated and stored in the db, and sent via LTI (if LTI is configured).
[ "This", "is", "a", "safe", "endpoint", "that", "students", "can", "call", "from", "the", "assignment", "page", "to", "get", "a", "preliminary", "grade", "on", "their", "assignment", ".", "If", "in", "coursera_mode", "the", "total", "for", "the", "assignment", "is", "calculated", "and", "stored", "in", "the", "db", "and", "sent", "via", "LTI", "(", "if", "LTI", "is", "configured", ")", "." ]
def student_autograde(): """ This is a safe endpoint that students can call from the assignment page to get a preliminary grade on their assignment. If in coursera_mode, the total for the assignment is calculated and stored in the db, and sent via LTI (if LTI is configured). """ assignment_id = request.vars.assignment_id timezoneoffset = session.timezoneoffset if "timezoneoffset" in session else None is_timed = request.vars.is_timed if assignment_id.isnumeric() is False: aidrow = ( db( (db.assignments.name == assignment_id) & (db.assignments.course == auth.user.course_id) ) .select() .first() ) if aidrow: assignment_id = aidrow.id else: res = {"success": False, "message": "Could not find this assignment"} return json.dumps(res) res = _autograde( student_rownum=auth.user.id, assignment_id=assignment_id, timezoneoffset=timezoneoffset, ) if not res["success"]: session.flash = ( "Failed to autograde questions for user id {} for assignment {}".format( auth.user.id, assignment_id ) ) res = {"success": False} else: if settings.coursera_mode or is_timed: res2 = _calculate_totals( student_rownum=auth.user.id, assignment_id=assignment_id ) if not res2["success"]: session.flash = ( "Failed to compute totals for user id {} for assignment {}".format( auth.user.id, assignment_id ) ) res = {"success": False} else: _try_to_send_lti_grade(auth.user.id, assignment_id) return json.dumps(res)
[ "def", "student_autograde", "(", ")", ":", "assignment_id", "=", "request", ".", "vars", ".", "assignment_id", "timezoneoffset", "=", "session", ".", "timezoneoffset", "if", "\"timezoneoffset\"", "in", "session", "else", "None", "is_timed", "=", "request", ".", "vars", ".", "is_timed", "if", "assignment_id", ".", "isnumeric", "(", ")", "is", "False", ":", "aidrow", "=", "(", "db", "(", "(", "db", ".", "assignments", ".", "name", "==", "assignment_id", ")", "&", "(", "db", ".", "assignments", ".", "course", "==", "auth", ".", "user", ".", "course_id", ")", ")", ".", "select", "(", ")", ".", "first", "(", ")", ")", "if", "aidrow", ":", "assignment_id", "=", "aidrow", ".", "id", "else", ":", "res", "=", "{", "\"success\"", ":", "False", ",", "\"message\"", ":", "\"Could not find this assignment\"", "}", "return", "json", ".", "dumps", "(", "res", ")", "res", "=", "_autograde", "(", "student_rownum", "=", "auth", ".", "user", ".", "id", ",", "assignment_id", "=", "assignment_id", ",", "timezoneoffset", "=", "timezoneoffset", ",", ")", "if", "not", "res", "[", "\"success\"", "]", ":", "session", ".", "flash", "=", "(", "\"Failed to autograde questions for user id {} for assignment {}\"", ".", "format", "(", "auth", ".", "user", ".", "id", ",", "assignment_id", ")", ")", "res", "=", "{", "\"success\"", ":", "False", "}", "else", ":", "if", "settings", ".", "coursera_mode", "or", "is_timed", ":", "res2", "=", "_calculate_totals", "(", "student_rownum", "=", "auth", ".", "user", ".", "id", ",", "assignment_id", "=", "assignment_id", ")", "if", "not", "res2", "[", "\"success\"", "]", ":", "session", ".", "flash", "=", "(", "\"Failed to compute totals for user id {} for assignment {}\"", ".", "format", "(", "auth", ".", "user", ".", "id", ",", "assignment_id", ")", ")", "res", "=", "{", "\"success\"", ":", "False", "}", "else", ":", "_try_to_send_lti_grade", "(", "auth", ".", "user", ".", "id", ",", "assignment_id", ")", "return", "json", ".", "dumps", "(", "res", ")" ]
https://github.com/RunestoneInteractive/RunestoneServer/blob/b20fcca5f08350224f63838250302771656f0951/controllers/assignments.py#L220-L273
omz/PythonistaAppTemplate
f560f93f8876d82a21d108977f90583df08d55af
PythonistaAppTemplate/PythonistaKit.framework/pylib_ext/matplotlib/lines.py
python
Line2D.get_markevery
(self)
return self._markevery
return the markevery setting
return the markevery setting
[ "return", "the", "markevery", "setting" ]
def get_markevery(self): """return the markevery setting""" return self._markevery
[ "def", "get_markevery", "(", "self", ")", ":", "return", "self", ".", "_markevery" ]
https://github.com/omz/PythonistaAppTemplate/blob/f560f93f8876d82a21d108977f90583df08d55af/PythonistaAppTemplate/PythonistaKit.framework/pylib_ext/matplotlib/lines.py#L361-L363
wistbean/learn_python3_spider
73c873f4845f4385f097e5057407d03dd37a117b
stackoverflow/venv/lib/python3.6/site-packages/OpenSSL/crypto.py
python
load_crl
(type, buffer)
return result
Load Certificate Revocation List (CRL) data from a string *buffer*. *buffer* encoded with the type *type*. :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1) :param buffer: The buffer the CRL is stored in :return: The PKey object
Load Certificate Revocation List (CRL) data from a string *buffer*. *buffer* encoded with the type *type*.
[ "Load", "Certificate", "Revocation", "List", "(", "CRL", ")", "data", "from", "a", "string", "*", "buffer", "*", ".", "*", "buffer", "*", "encoded", "with", "the", "type", "*", "type", "*", "." ]
def load_crl(type, buffer): """ Load Certificate Revocation List (CRL) data from a string *buffer*. *buffer* encoded with the type *type*. :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1) :param buffer: The buffer the CRL is stored in :return: The PKey object """ if isinstance(buffer, _text_type): buffer = buffer.encode("ascii") bio = _new_mem_buf(buffer) if type == FILETYPE_PEM: crl = _lib.PEM_read_bio_X509_CRL(bio, _ffi.NULL, _ffi.NULL, _ffi.NULL) elif type == FILETYPE_ASN1: crl = _lib.d2i_X509_CRL_bio(bio, _ffi.NULL) else: raise ValueError("type argument must be FILETYPE_PEM or FILETYPE_ASN1") if crl == _ffi.NULL: _raise_current_error() result = CRL.__new__(CRL) result._crl = _ffi.gc(crl, _lib.X509_CRL_free) return result
[ "def", "load_crl", "(", "type", ",", "buffer", ")", ":", "if", "isinstance", "(", "buffer", ",", "_text_type", ")", ":", "buffer", "=", "buffer", ".", "encode", "(", "\"ascii\"", ")", "bio", "=", "_new_mem_buf", "(", "buffer", ")", "if", "type", "==", "FILETYPE_PEM", ":", "crl", "=", "_lib", ".", "PEM_read_bio_X509_CRL", "(", "bio", ",", "_ffi", ".", "NULL", ",", "_ffi", ".", "NULL", ",", "_ffi", ".", "NULL", ")", "elif", "type", "==", "FILETYPE_ASN1", ":", "crl", "=", "_lib", ".", "d2i_X509_CRL_bio", "(", "bio", ",", "_ffi", ".", "NULL", ")", "else", ":", "raise", "ValueError", "(", "\"type argument must be FILETYPE_PEM or FILETYPE_ASN1\"", ")", "if", "crl", "==", "_ffi", ".", "NULL", ":", "_raise_current_error", "(", ")", "result", "=", "CRL", ".", "__new__", "(", "CRL", ")", "result", ".", "_crl", "=", "_ffi", ".", "gc", "(", "crl", ",", "_lib", ".", "X509_CRL_free", ")", "return", "result" ]
https://github.com/wistbean/learn_python3_spider/blob/73c873f4845f4385f097e5057407d03dd37a117b/stackoverflow/venv/lib/python3.6/site-packages/OpenSSL/crypto.py#L2971-L2998
linxid/Machine_Learning_Study_Path
558e82d13237114bbb8152483977806fc0c222af
Machine Learning In Action/Chapter4-NaiveBayes/venv/Lib/importlib/_bootstrap_external.py
python
_NamespaceLoader.create_module
(self, spec)
Use default semantics for module creation.
Use default semantics for module creation.
[ "Use", "default", "semantics", "for", "module", "creation", "." ]
def create_module(self, spec): """Use default semantics for module creation."""
[ "def", "create_module", "(", "self", ",", "spec", ")", ":" ]
https://github.com/linxid/Machine_Learning_Study_Path/blob/558e82d13237114bbb8152483977806fc0c222af/Machine Learning In Action/Chapter4-NaiveBayes/venv/Lib/importlib/_bootstrap_external.py#L1035-L1036
yongxinz/tech-blog
fb50b7d1abd218df41a937f662964d1d40684a7b
rabbitmq/src/rabbitmq_status.py
python
RabbitMQMoniter.check_server
(self, item, node_name)
return 'Not Found'
check server
check server
[ "check", "server" ]
def check_server(self, item, node_name): """ check server """ node_name = node_name.split('.')[0] for nodeData in self.call_api('nodes'): if node_name in nodeData['name']: return nodeData.get(item, 0) return 'Not Found'
[ "def", "check_server", "(", "self", ",", "item", ",", "node_name", ")", ":", "node_name", "=", "node_name", ".", "split", "(", "'.'", ")", "[", "0", "]", "for", "nodeData", "in", "self", ".", "call_api", "(", "'nodes'", ")", ":", "if", "node_name", "in", "nodeData", "[", "'name'", "]", ":", "return", "nodeData", ".", "get", "(", "item", ",", "0", ")", "return", "'Not Found'" ]
https://github.com/yongxinz/tech-blog/blob/fb50b7d1abd218df41a937f662964d1d40684a7b/rabbitmq/src/rabbitmq_status.py#L110-L118
toxinu/pyhn
c36090e33ae730daa16c276e5f54c49baef2d8fe
pyhn/hnapi.py
python
HackerNewsAPI.get_stories
(self, source)
return news_stories
Looks at source, makes stories from it, returns the stories.
Looks at source, makes stories from it, returns the stories.
[ "Looks", "at", "source", "makes", "stories", "from", "it", "returns", "the", "stories", "." ]
def get_stories(self, source): """ Looks at source, makes stories from it, returns the stories. """ """ <td align=right valign=top class="title">31.</td> """ self.number_of_stories_on_front_page = source.count( 'span class="rank"') # Create the empty stories. news_stories = [] for i in range(0, self.number_of_stories_on_front_page): story = HackerNewsStory() news_stories.append(story) soup = BeautifulSoup(source, "html.parser") # Gives URLs, Domains and titles. story_details = soup.findAll("td", {"class": "title"}) # Gives score, submitter, comment count and comment URL. story_other_details = soup.findAll("td", {"class": "subtext"}) # Get story numbers. story_numbers = [] for i in range(0, len(story_details) - 1, 2): # Otherwise, story_details[i] is a BeautifulSoup-defined object. story = str(story_details[i]) story_number = self.get_story_number(story) story_numbers.append(story_number) story_urls = [] story_domains = [] story_titles = [] story_scores = [] story_submitters = [] story_comment_counts = [] story_comment_urls = [] story_published_time = [] story_ids = [] # Every second cell contains a story. for i in range(1, len(story_details), 2): story = str(story_details[i]) story_urls.append(self.get_story_url(story)) story_domains.append(self.get_story_domain(story)) story_titles.append(self.get_story_title(story)) for s in story_other_details: story = str(s) story_scores.append(self.get_story_score(story)) story_submitters.append(self.get_submitter(story)) story_comment_counts.append(self.get_comment_count(story)) story_comment_urls.append(self.get_comments_url(story)) story_published_time.append(self.get_published_time(story)) story_ids.append(self.get_hn_id(story)) # Associate the values with our newsStories. for i in range(0, self.number_of_stories_on_front_page): news_stories[i].number = story_numbers[i] news_stories[i].url = story_urls[i] news_stories[i].domain = story_domains[i] news_stories[i].title = story_titles[i] news_stories[i].score = story_scores[i] news_stories[i].submitter = story_submitters[i] if news_stories[i].submitter: news_stories[i].submitter_url = ( "https://news.ycombinator.com/user?id={}".format( story_submitters[i])) else: news_stories[i].submitter_url = None news_stories[i].comment_count = story_comment_counts[i] news_stories[i].comments_url = story_comment_urls[i] news_stories[i].published_time = story_published_time[i] news_stories[i].id = story_ids[i] if news_stories[i].id < 0: news_stories[i].url.find('item?id=') + 8 news_stories[i].comments_url = '' news_stories[i].submitter = None news_stories[i].submitter_url = None return news_stories
[ "def", "get_stories", "(", "self", ",", "source", ")", ":", "\"\"\" <td align=right valign=top class=\"title\">31.</td> \"\"\"", "self", ".", "number_of_stories_on_front_page", "=", "source", ".", "count", "(", "'span class=\"rank\"'", ")", "# Create the empty stories.", "news_stories", "=", "[", "]", "for", "i", "in", "range", "(", "0", ",", "self", ".", "number_of_stories_on_front_page", ")", ":", "story", "=", "HackerNewsStory", "(", ")", "news_stories", ".", "append", "(", "story", ")", "soup", "=", "BeautifulSoup", "(", "source", ",", "\"html.parser\"", ")", "# Gives URLs, Domains and titles.", "story_details", "=", "soup", ".", "findAll", "(", "\"td\"", ",", "{", "\"class\"", ":", "\"title\"", "}", ")", "# Gives score, submitter, comment count and comment URL.", "story_other_details", "=", "soup", ".", "findAll", "(", "\"td\"", ",", "{", "\"class\"", ":", "\"subtext\"", "}", ")", "# Get story numbers.", "story_numbers", "=", "[", "]", "for", "i", "in", "range", "(", "0", ",", "len", "(", "story_details", ")", "-", "1", ",", "2", ")", ":", "# Otherwise, story_details[i] is a BeautifulSoup-defined object.", "story", "=", "str", "(", "story_details", "[", "i", "]", ")", "story_number", "=", "self", ".", "get_story_number", "(", "story", ")", "story_numbers", ".", "append", "(", "story_number", ")", "story_urls", "=", "[", "]", "story_domains", "=", "[", "]", "story_titles", "=", "[", "]", "story_scores", "=", "[", "]", "story_submitters", "=", "[", "]", "story_comment_counts", "=", "[", "]", "story_comment_urls", "=", "[", "]", "story_published_time", "=", "[", "]", "story_ids", "=", "[", "]", "# Every second cell contains a story.", "for", "i", "in", "range", "(", "1", ",", "len", "(", "story_details", ")", ",", "2", ")", ":", "story", "=", "str", "(", "story_details", "[", "i", "]", ")", "story_urls", ".", "append", "(", "self", ".", "get_story_url", "(", "story", ")", ")", "story_domains", ".", "append", "(", "self", ".", "get_story_domain", "(", "story", ")", ")", "story_titles", ".", "append", "(", "self", ".", "get_story_title", "(", "story", ")", ")", "for", "s", "in", "story_other_details", ":", "story", "=", "str", "(", "s", ")", "story_scores", ".", "append", "(", "self", ".", "get_story_score", "(", "story", ")", ")", "story_submitters", ".", "append", "(", "self", ".", "get_submitter", "(", "story", ")", ")", "story_comment_counts", ".", "append", "(", "self", ".", "get_comment_count", "(", "story", ")", ")", "story_comment_urls", ".", "append", "(", "self", ".", "get_comments_url", "(", "story", ")", ")", "story_published_time", ".", "append", "(", "self", ".", "get_published_time", "(", "story", ")", ")", "story_ids", ".", "append", "(", "self", ".", "get_hn_id", "(", "story", ")", ")", "# Associate the values with our newsStories.", "for", "i", "in", "range", "(", "0", ",", "self", ".", "number_of_stories_on_front_page", ")", ":", "news_stories", "[", "i", "]", ".", "number", "=", "story_numbers", "[", "i", "]", "news_stories", "[", "i", "]", ".", "url", "=", "story_urls", "[", "i", "]", "news_stories", "[", "i", "]", ".", "domain", "=", "story_domains", "[", "i", "]", "news_stories", "[", "i", "]", ".", "title", "=", "story_titles", "[", "i", "]", "news_stories", "[", "i", "]", ".", "score", "=", "story_scores", "[", "i", "]", "news_stories", "[", "i", "]", ".", "submitter", "=", "story_submitters", "[", "i", "]", "if", "news_stories", "[", "i", "]", ".", "submitter", ":", "news_stories", "[", "i", "]", ".", "submitter_url", "=", "(", "\"https://news.ycombinator.com/user?id={}\"", ".", "format", "(", "story_submitters", "[", "i", "]", ")", ")", "else", ":", "news_stories", "[", "i", "]", ".", "submitter_url", "=", "None", "news_stories", "[", "i", "]", ".", "comment_count", "=", "story_comment_counts", "[", "i", "]", "news_stories", "[", "i", "]", ".", "comments_url", "=", "story_comment_urls", "[", "i", "]", "news_stories", "[", "i", "]", ".", "published_time", "=", "story_published_time", "[", "i", "]", "news_stories", "[", "i", "]", ".", "id", "=", "story_ids", "[", "i", "]", "if", "news_stories", "[", "i", "]", ".", "id", "<", "0", ":", "news_stories", "[", "i", "]", ".", "url", ".", "find", "(", "'item?id='", ")", "+", "8", "news_stories", "[", "i", "]", ".", "comments_url", "=", "''", "news_stories", "[", "i", "]", ".", "submitter", "=", "None", "news_stories", "[", "i", "]", ".", "submitter_url", "=", "None", "return", "news_stories" ]
https://github.com/toxinu/pyhn/blob/c36090e33ae730daa16c276e5f54c49baef2d8fe/pyhn/hnapi.py#L224-L302
stratosphereips/StratosphereLinuxIPS
985ac0f141dd71fe9c6faa8307bcf95a3754951d
modules/ARP/ARP.py
python
Module.detect_unsolicited_arp
(self, profileid, twid, uid, ts, dst_mac, src_mac, dst_hw, src_hw)
Unsolicited ARP is used to update the neighbours' ARP caches but can also be used in ARP spoofing
Unsolicited ARP is used to update the neighbours' ARP caches but can also be used in ARP spoofing
[ "Unsolicited", "ARP", "is", "used", "to", "update", "the", "neighbours", "ARP", "caches", "but", "can", "also", "be", "used", "in", "ARP", "spoofing" ]
def detect_unsolicited_arp(self, profileid, twid, uid, ts, dst_mac, src_mac, dst_hw, src_hw): """ Unsolicited ARP is used to update the neighbours' ARP caches but can also be used in ARP spoofing """ if dst_mac=="ff:ff:ff:ff:ff:ff" and dst_hw=="ff:ff:ff:ff:ff:ff" and src_mac != '00:00:00:00:00:00' and src_hw != '00:00:00:00:00:00': # We're sure this is unsolicited arp confidence = 0.8 threat_level = 'info' description = f'detected sending unsolicited ARP' type_evidence = 'UnsolicitedARP' # This may be ARP spoofing category = 'Information' type_detection = 'srcip' source_target_tag = 'Recon' # srcip description detection_info = profileid.split("_")[1] __database__.setEvidence(type_evidence, type_detection, detection_info, threat_level, confidence, description, ts, category,source_target_tag=source_target_tag, profileid=profileid, twid=twid, uid=uid) return True
[ "def", "detect_unsolicited_arp", "(", "self", ",", "profileid", ",", "twid", ",", "uid", ",", "ts", ",", "dst_mac", ",", "src_mac", ",", "dst_hw", ",", "src_hw", ")", ":", "if", "dst_mac", "==", "\"ff:ff:ff:ff:ff:ff\"", "and", "dst_hw", "==", "\"ff:ff:ff:ff:ff:ff\"", "and", "src_mac", "!=", "'00:00:00:00:00:00'", "and", "src_hw", "!=", "'00:00:00:00:00:00'", ":", "# We're sure this is unsolicited arp", "confidence", "=", "0.8", "threat_level", "=", "'info'", "description", "=", "f'detected sending unsolicited ARP'", "type_evidence", "=", "'UnsolicitedARP'", "# This may be ARP spoofing", "category", "=", "'Information'", "type_detection", "=", "'srcip'", "source_target_tag", "=", "'Recon'", "# srcip description", "detection_info", "=", "profileid", ".", "split", "(", "\"_\"", ")", "[", "1", "]", "__database__", ".", "setEvidence", "(", "type_evidence", ",", "type_detection", ",", "detection_info", ",", "threat_level", ",", "confidence", ",", "description", ",", "ts", ",", "category", ",", "source_target_tag", "=", "source_target_tag", ",", "profileid", "=", "profileid", ",", "twid", "=", "twid", ",", "uid", "=", "uid", ")", "return", "True" ]
https://github.com/stratosphereips/StratosphereLinuxIPS/blob/985ac0f141dd71fe9c6faa8307bcf95a3754951d/modules/ARP/ARP.py#L176-L191
lisa-lab/pylearn2
af81e5c362f0df4df85c3e54e23b2adeec026055
pylearn2/datasets/dense_design_matrix.py
python
DenseDesignMatrix.get_batch_design
(self, batch_size, include_labels=False)
return rx
.. todo:: WRITEME Parameters ---------- batch_size : int WRITEME include_labels : bool WRITEME
.. todo::
[ "..", "todo", "::" ]
def get_batch_design(self, batch_size, include_labels=False): """ .. todo:: WRITEME Parameters ---------- batch_size : int WRITEME include_labels : bool WRITEME """ try: idx = self.rng.randint(self.X.shape[0] - batch_size + 1) except ValueError: if batch_size > self.X.shape[0]: reraise_as(ValueError("Requested %d examples from a dataset " "containing only %d." % (batch_size, self.X.shape[0]))) raise rx = self.X[idx:idx + batch_size, :] if include_labels: if self.y is None: return rx, None ry = self.y[idx:idx + batch_size] return rx, ry rx = np.cast[config.floatX](rx) return rx
[ "def", "get_batch_design", "(", "self", ",", "batch_size", ",", "include_labels", "=", "False", ")", ":", "try", ":", "idx", "=", "self", ".", "rng", ".", "randint", "(", "self", ".", "X", ".", "shape", "[", "0", "]", "-", "batch_size", "+", "1", ")", "except", "ValueError", ":", "if", "batch_size", ">", "self", ".", "X", ".", "shape", "[", "0", "]", ":", "reraise_as", "(", "ValueError", "(", "\"Requested %d examples from a dataset \"", "\"containing only %d.\"", "%", "(", "batch_size", ",", "self", ".", "X", ".", "shape", "[", "0", "]", ")", ")", ")", "raise", "rx", "=", "self", ".", "X", "[", "idx", ":", "idx", "+", "batch_size", ",", ":", "]", "if", "include_labels", ":", "if", "self", ".", "y", "is", "None", ":", "return", "rx", ",", "None", "ry", "=", "self", ".", "y", "[", "idx", ":", "idx", "+", "batch_size", "]", "return", "rx", ",", "ry", "rx", "=", "np", ".", "cast", "[", "config", ".", "floatX", "]", "(", "rx", ")", "return", "rx" ]
https://github.com/lisa-lab/pylearn2/blob/af81e5c362f0df4df85c3e54e23b2adeec026055/pylearn2/datasets/dense_design_matrix.py#L835-L863
grantjenks/free-python-games
3f27c6555e2c72a9b1c668c4dd8506d7b8378d09
freegames/memory.py
python
index
(x, y)
return int((x + 200) // 50 + ((y + 200) // 50) * 8)
Convert (x, y) coordinates to tiles index.
Convert (x, y) coordinates to tiles index.
[ "Convert", "(", "x", "y", ")", "coordinates", "to", "tiles", "index", "." ]
def index(x, y): """Convert (x, y) coordinates to tiles index.""" return int((x + 200) // 50 + ((y + 200) // 50) * 8)
[ "def", "index", "(", "x", ",", "y", ")", ":", "return", "int", "(", "(", "x", "+", "200", ")", "//", "50", "+", "(", "(", "y", "+", "200", ")", "//", "50", ")", "*", "8", ")" ]
https://github.com/grantjenks/free-python-games/blob/3f27c6555e2c72a9b1c668c4dd8506d7b8378d09/freegames/memory.py#L36-L38
CPJKU/madmom
3bc8334099feb310acfce884ebdb76a28e01670d
madmom/audio/signal.py
python
signal_frame
(signal, index, frame_size, hop_size, origin=0, pad=0)
return frame
This function returns frame at `index` of the `signal`. Parameters ---------- signal : numpy array Signal. index : int Index of the frame to return. frame_size : int Size of each frame in samples. hop_size : float Hop size in samples between adjacent frames. origin : int Location of the window center relative to the signal position. pad : int, float or str, optional Pad parts of the frame not covered by the signal with this value. The literal 'repeat' can be used to indicate that the first/last value should be repeated. Returns ------- frame : numpy array Requested frame of the signal. Notes ----- The reference sample of the first frame (index == 0) refers to the first sample of the `signal`, and each following frame is placed `hop_size` samples after the previous one. The window is always centered around this reference sample. Its location relative to the reference sample can be set with the `origin` parameter. Arbitrary integer values can be given: - zero centers the window on its reference sample - negative values shift the window to the right - positive values shift the window to the left An `origin` of half the size of the `frame_size` results in windows located to the left of the reference sample, i.e. the first frame starts at the first sample of the signal. The part of the frame which is not covered by the signal is padded with zeros. This function is totally independent of the length of the signal. Thus, contrary to common indexing, the index '-1' refers NOT to the last frame of the signal, but instead the frame left of the first frame is returned.
This function returns frame at `index` of the `signal`.
[ "This", "function", "returns", "frame", "at", "index", "of", "the", "signal", "." ]
def signal_frame(signal, index, frame_size, hop_size, origin=0, pad=0): """ This function returns frame at `index` of the `signal`. Parameters ---------- signal : numpy array Signal. index : int Index of the frame to return. frame_size : int Size of each frame in samples. hop_size : float Hop size in samples between adjacent frames. origin : int Location of the window center relative to the signal position. pad : int, float or str, optional Pad parts of the frame not covered by the signal with this value. The literal 'repeat' can be used to indicate that the first/last value should be repeated. Returns ------- frame : numpy array Requested frame of the signal. Notes ----- The reference sample of the first frame (index == 0) refers to the first sample of the `signal`, and each following frame is placed `hop_size` samples after the previous one. The window is always centered around this reference sample. Its location relative to the reference sample can be set with the `origin` parameter. Arbitrary integer values can be given: - zero centers the window on its reference sample - negative values shift the window to the right - positive values shift the window to the left An `origin` of half the size of the `frame_size` results in windows located to the left of the reference sample, i.e. the first frame starts at the first sample of the signal. The part of the frame which is not covered by the signal is padded with zeros. This function is totally independent of the length of the signal. Thus, contrary to common indexing, the index '-1' refers NOT to the last frame of the signal, but instead the frame left of the first frame is returned. """ # cast variables to int frame_size = int(frame_size) # length of the signal num_samples = len(signal) # seek to the correct position in the audio signal ref_sample = int(index * hop_size) # position the window start = ref_sample - frame_size // 2 - int(origin) stop = start + frame_size # return the requested portion of the signal # Note: use NumPy's advanced indexing (i.e. trailing comma) in order to # avoid a memory leak (issue #321). This returns a copy of the data, # however, returning a simple copy of the relevant portion of the # signal also leaks memory # Update: removing this hack again, since it seems that it is not needed # any more with recent NumPy versions if start >= 0 and stop <= num_samples: # normal read operation, return appropriate section return signal[start:stop] # part of the frame falls outside the signal, padding needed # Note: np.pad(signal[from: to], (pad_left, pad_right), mode='constant') # always returns a ndarray, not the subclass (and is slower); # usually np.zeros_like(signal[:frame_size]) is exactly what we want # (i.e. zeros of frame_size length and the same type/class as the # signal and not just the dtype), but since we have no guarantee that # the signal is that long, we have to use the np.repeat workaround frame = np.repeat(signal[:1], frame_size, axis=0) # determine how many samples need to be padded from left/right left, right = 0, 0 if start < 0: left = min(stop, 0) - start # repeat beginning of signal frame[:left] = np.repeat(signal[:1], left, axis=0) if pad != 'repeat': frame[:left] = pad start = 0 if stop > num_samples: right = stop - max(start, num_samples) # repeat end of signal frame[-right:] = np.repeat(signal[-1:], right, axis=0) if pad != 'repeat': frame[-right:] = pad stop = num_samples # position signal inside frame frame[left:frame_size - right] = signal[min(start, num_samples): max(stop, 0)] # return the frame return frame
[ "def", "signal_frame", "(", "signal", ",", "index", ",", "frame_size", ",", "hop_size", ",", "origin", "=", "0", ",", "pad", "=", "0", ")", ":", "# cast variables to int", "frame_size", "=", "int", "(", "frame_size", ")", "# length of the signal", "num_samples", "=", "len", "(", "signal", ")", "# seek to the correct position in the audio signal", "ref_sample", "=", "int", "(", "index", "*", "hop_size", ")", "# position the window", "start", "=", "ref_sample", "-", "frame_size", "//", "2", "-", "int", "(", "origin", ")", "stop", "=", "start", "+", "frame_size", "# return the requested portion of the signal", "# Note: use NumPy's advanced indexing (i.e. trailing comma) in order to", "# avoid a memory leak (issue #321). This returns a copy of the data,", "# however, returning a simple copy of the relevant portion of the", "# signal also leaks memory", "# Update: removing this hack again, since it seems that it is not needed", "# any more with recent NumPy versions", "if", "start", ">=", "0", "and", "stop", "<=", "num_samples", ":", "# normal read operation, return appropriate section", "return", "signal", "[", "start", ":", "stop", "]", "# part of the frame falls outside the signal, padding needed", "# Note: np.pad(signal[from: to], (pad_left, pad_right), mode='constant')", "# always returns a ndarray, not the subclass (and is slower);", "# usually np.zeros_like(signal[:frame_size]) is exactly what we want", "# (i.e. zeros of frame_size length and the same type/class as the", "# signal and not just the dtype), but since we have no guarantee that", "# the signal is that long, we have to use the np.repeat workaround", "frame", "=", "np", ".", "repeat", "(", "signal", "[", ":", "1", "]", ",", "frame_size", ",", "axis", "=", "0", ")", "# determine how many samples need to be padded from left/right", "left", ",", "right", "=", "0", ",", "0", "if", "start", "<", "0", ":", "left", "=", "min", "(", "stop", ",", "0", ")", "-", "start", "# repeat beginning of signal", "frame", "[", ":", "left", "]", "=", "np", ".", "repeat", "(", "signal", "[", ":", "1", "]", ",", "left", ",", "axis", "=", "0", ")", "if", "pad", "!=", "'repeat'", ":", "frame", "[", ":", "left", "]", "=", "pad", "start", "=", "0", "if", "stop", ">", "num_samples", ":", "right", "=", "stop", "-", "max", "(", "start", ",", "num_samples", ")", "# repeat end of signal", "frame", "[", "-", "right", ":", "]", "=", "np", ".", "repeat", "(", "signal", "[", "-", "1", ":", "]", ",", "right", ",", "axis", "=", "0", ")", "if", "pad", "!=", "'repeat'", ":", "frame", "[", "-", "right", ":", "]", "=", "pad", "stop", "=", "num_samples", "# position signal inside frame", "frame", "[", "left", ":", "frame_size", "-", "right", "]", "=", "signal", "[", "min", "(", "start", ",", "num_samples", ")", ":", "max", "(", "stop", ",", "0", ")", "]", "# return the frame", "return", "frame" ]
https://github.com/CPJKU/madmom/blob/3bc8334099feb310acfce884ebdb76a28e01670d/madmom/audio/signal.py#L859-L961
sagemath/sage
f9b2db94f675ff16963ccdefba4f1a3393b3fe0d
src/sage/rings/semirings/non_negative_integer_semiring.py
python
NonNegativeIntegerSemiring._repr_
(self)
return "Non negative integer semiring"
r""" EXAMPLES:: sage: NonNegativeIntegerSemiring() Non negative integer semiring
r""" EXAMPLES::
[ "r", "EXAMPLES", "::" ]
def _repr_(self): r""" EXAMPLES:: sage: NonNegativeIntegerSemiring() Non negative integer semiring """ return "Non negative integer semiring"
[ "def", "_repr_", "(", "self", ")", ":", "return", "\"Non negative integer semiring\"" ]
https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/rings/semirings/non_negative_integer_semiring.py#L75-L82
blmoistawinde/HarvestText
fae00fff2088f43a379726ef83d5c85567a9cd74
harvesttext/resources.py
python
get_english_senti_lexicon
(type="LH")
return senti_lexicon
获得英语情感词汇表 目前默认为来自这里的词汇表 https://www.cs.uic.edu/~liub/FBS/sentiment-analysis.html#lexicon If you use this list, please cite the following paper: Minqing Hu and Bing Liu. "Mining and Summarizing Customer Reviews." Proceedings of the ACM SIGKDD International Conference on Knowledge Discovery and Data Mining (KDD-2004), Aug 22-25, 2004, Seattle, Washington, USA, :return: sent_dict = {"pos":[words],"neg":[words]}
获得英语情感词汇表
[ "获得英语情感词汇表" ]
def get_english_senti_lexicon(type="LH"): """ 获得英语情感词汇表 目前默认为来自这里的词汇表 https://www.cs.uic.edu/~liub/FBS/sentiment-analysis.html#lexicon If you use this list, please cite the following paper: Minqing Hu and Bing Liu. "Mining and Summarizing Customer Reviews." Proceedings of the ACM SIGKDD International Conference on Knowledge Discovery and Data Mining (KDD-2004), Aug 22-25, 2004, Seattle, Washington, USA, :return: sent_dict = {"pos":[words],"neg":[words]} """ pwd = os.path.abspath(os.path.dirname(__file__)) with open(pwd + "/resources/LH_senti_lexicon.json", "r", encoding="utf-8") as f: senti_lexicon = json.load(f) return senti_lexicon
[ "def", "get_english_senti_lexicon", "(", "type", "=", "\"LH\"", ")", ":", "pwd", "=", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ")", "with", "open", "(", "pwd", "+", "\"/resources/LH_senti_lexicon.json\"", ",", "\"r\"", ",", "encoding", "=", "\"utf-8\"", ")", "as", "f", ":", "senti_lexicon", "=", "json", ".", "load", "(", "f", ")", "return", "senti_lexicon" ]
https://github.com/blmoistawinde/HarvestText/blob/fae00fff2088f43a379726ef83d5c85567a9cd74/harvesttext/resources.py#L106-L125
winkidney/weixin2py
dd0fc951a592da5afc4fe010da4dc7472455db4b
weixin2py/__init__.py
python
get_atoken
(app_id, app_secret)
return None
Get AccessToken by appid and appsecret. :param app_id: :param app_secret: Tencent appsecret :return: Access token. :rtype str or unicode
Get AccessToken by appid and appsecret. :param app_id: :param app_secret: Tencent appsecret :return: Access token. :rtype str or unicode
[ "Get", "AccessToken", "by", "appid", "and", "appsecret", ".", ":", "param", "app_id", ":", ":", "param", "app_secret", ":", "Tencent", "appsecret", ":", "return", ":", "Access", "token", ".", ":", "rtype", "str", "or", "unicode" ]
def get_atoken(app_id, app_secret): """ Get AccessToken by appid and appsecret. :param app_id: :param app_secret: Tencent appsecret :return: Access token. :rtype str or unicode """ url = """https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%(appid)s&secret=%(appsecret)s""" \ % {'appid': app_id, 'appsecret': app_secret} try: result = urllib2.urlopen(url, timeout=20).read() except urllib2.HTTPError, urllib2.URLError: return None if result: if re.findall('"access_token":"(.*?)"', result): return result[0] return None
[ "def", "get_atoken", "(", "app_id", ",", "app_secret", ")", ":", "url", "=", "\"\"\"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%(appid)s&secret=%(appsecret)s\"\"\"", "%", "{", "'appid'", ":", "app_id", ",", "'appsecret'", ":", "app_secret", "}", "try", ":", "result", "=", "urllib2", ".", "urlopen", "(", "url", ",", "timeout", "=", "20", ")", ".", "read", "(", ")", "except", "urllib2", ".", "HTTPError", ",", "urllib2", ".", "URLError", ":", "return", "None", "if", "result", ":", "if", "re", ".", "findall", "(", "'\"access_token\":\"(.*?)\"'", ",", "result", ")", ":", "return", "result", "[", "0", "]", "return", "None" ]
https://github.com/winkidney/weixin2py/blob/dd0fc951a592da5afc4fe010da4dc7472455db4b/weixin2py/__init__.py#L240-L258
iskandr/parakeet
d9089f999cc4a417d121970b2a447d5e524a3d3b
parakeet/lib/math.py
python
conjugate
(x)
return x
For now we don't have complex numbers so this is just the identity function
For now we don't have complex numbers so this is just the identity function
[ "For", "now", "we", "don", "t", "have", "complex", "numbers", "so", "this", "is", "just", "the", "identity", "function" ]
def conjugate(x): """ For now we don't have complex numbers so this is just the identity function """ return x
[ "def", "conjugate", "(", "x", ")", ":", "return", "x" ]
https://github.com/iskandr/parakeet/blob/d9089f999cc4a417d121970b2a447d5e524a3d3b/parakeet/lib/math.py#L8-L12
pyouroboros/ouroboros
fee45f2dbf6eb3fc3ddab7473ca60df515aedc1f
pyouroboros/dataexporters.py
python
DataManager.add
(self, label, socket)
[]
def add(self, label, socket): if self.config.data_export == "prometheus" and self.enabled: self.prometheus.update(label, socket) elif self.config.data_export == "influxdb" and self.enabled: if label == "all": self.logger.debug("Total containers updated %s", self.total_updated[socket]) self.influx.write_points(label, socket)
[ "def", "add", "(", "self", ",", "label", ",", "socket", ")", ":", "if", "self", ".", "config", ".", "data_export", "==", "\"prometheus\"", "and", "self", ".", "enabled", ":", "self", ".", "prometheus", ".", "update", "(", "label", ",", "socket", ")", "elif", "self", ".", "config", ".", "data_export", "==", "\"influxdb\"", "and", "self", ".", "enabled", ":", "if", "label", "==", "\"all\"", ":", "self", ".", "logger", ".", "debug", "(", "\"Total containers updated %s\"", ",", "self", ".", "total_updated", "[", "socket", "]", ")", "self", ".", "influx", ".", "write_points", "(", "label", ",", "socket", ")" ]
https://github.com/pyouroboros/ouroboros/blob/fee45f2dbf6eb3fc3ddab7473ca60df515aedc1f/pyouroboros/dataexporters.py#L20-L28
chromium/web-page-replay
472351e1122bb1beb936952c7e75ae58bf8a69f1
third_party/ipaddr/ipaddr.py
python
_BaseV6.is_unspecified
(self)
return self._ip == 0 and getattr(self, '_prefixlen', 128) == 128
Test if the address is unspecified. Returns: A boolean, True if this is the unspecified address as defined in RFC 2373 2.5.2.
Test if the address is unspecified.
[ "Test", "if", "the", "address", "is", "unspecified", "." ]
def is_unspecified(self): """Test if the address is unspecified. Returns: A boolean, True if this is the unspecified address as defined in RFC 2373 2.5.2. """ return self._ip == 0 and getattr(self, '_prefixlen', 128) == 128
[ "def", "is_unspecified", "(", "self", ")", ":", "return", "self", ".", "_ip", "==", "0", "and", "getattr", "(", "self", ",", "'_prefixlen'", ",", "128", ")", "==", "128" ]
https://github.com/chromium/web-page-replay/blob/472351e1122bb1beb936952c7e75ae58bf8a69f1/third_party/ipaddr/ipaddr.py#L1647-L1655
nolze/msoffcrypto-tool
01c5b23ee81bd39a37ea090af2656e6891767be7
msoffcrypto/format/ppt97.py
python
_parseCryptSession10Container
(blob)
return CryptSession10Container( rh=rh, data=data, )
[]
def _parseCryptSession10Container(blob): # CryptSession10Container: https://docs.microsoft.com/en-us/openspecs/office_file_formats/ms-ppt/b0963334-4408-4621-879a-ef9c54551fd8 CryptSession10Container = namedtuple( "CryptSession10Container", [ "rh", "data", ], ) # rh (8 bytes): A RecordHeader structure... buf = io.BytesIO(blob.read(8)) rh = _parseRecordHeader(buf) # logger.debug(rh) # ...Sub-fields are further specified in the following table. assert rh.recVer == 0xF # The specified value fails # assert rh.recInstance == 0x000 assert rh.recType == 0x2F14 data = blob.read(rh.recLen) return CryptSession10Container( rh=rh, data=data, )
[ "def", "_parseCryptSession10Container", "(", "blob", ")", ":", "# CryptSession10Container: https://docs.microsoft.com/en-us/openspecs/office_file_formats/ms-ppt/b0963334-4408-4621-879a-ef9c54551fd8", "CryptSession10Container", "=", "namedtuple", "(", "\"CryptSession10Container\"", ",", "[", "\"rh\"", ",", "\"data\"", ",", "]", ",", ")", "# rh (8 bytes): A RecordHeader structure...", "buf", "=", "io", ".", "BytesIO", "(", "blob", ".", "read", "(", "8", ")", ")", "rh", "=", "_parseRecordHeader", "(", "buf", ")", "# logger.debug(rh)", "# ...Sub-fields are further specified in the following table.", "assert", "rh", ".", "recVer", "==", "0xF", "# The specified value fails", "# assert rh.recInstance == 0x000", "assert", "rh", ".", "recType", "==", "0x2F14", "data", "=", "blob", ".", "read", "(", "rh", ".", "recLen", ")", "return", "CryptSession10Container", "(", "rh", "=", "rh", ",", "data", "=", "data", ",", ")" ]
https://github.com/nolze/msoffcrypto-tool/blob/01c5b23ee81bd39a37ea090af2656e6891767be7/msoffcrypto/format/ppt97.py#L413-L440
oracle/oci-python-sdk
3c1604e4e212008fb6718e2f68cdb5ef71fd5793
src/oci/database_tools/database_tools_client.py
python
DatabaseToolsClient.create_database_tools_connection
(self, create_database_tools_connection_details, **kwargs)
Creates a new DatabaseToolsConnection. :param oci.database_tools.models.CreateDatabaseToolsConnectionDetails create_database_tools_connection_details: (required) Details for the new DatabaseToolsConnection. :param str opc_retry_token: (optional) A token that uniquely identifies a request so it can be retried in case of a timeout or server error without risk of executing that same action again. Retry tokens expire after 24 hours, but can be invalidated before then due to conflicting operations. For example, if a resource has been deleted and purged from the system, then a retry of the original creation request might be rejected. :param str opc_request_id: (optional) The client request ID for tracing. :param obj retry_strategy: (optional) A retry strategy to apply to this specific operation/call. This will override any retry strategy set at the client-level. This should be one of the strategies available in the :py:mod:`~oci.retry` module. This operation will not retry by default, users can also use the convenient :py:data:`~oci.retry.DEFAULT_RETRY_STRATEGY` provided by the SDK to enable retries for it. The specifics of the default retry strategy are described `here <https://docs.oracle.com/en-us/iaas/tools/python/latest/sdk_behaviors/retries.html>`__. To have this operation explicitly not perform any retries, pass an instance of :py:class:`~oci.retry.NoneRetryStrategy`. :return: A :class:`~oci.response.Response` object with data of type :class:`~oci.database_tools.models.DatabaseToolsConnection` :rtype: :class:`~oci.response.Response` :example: Click `here <https://docs.cloud.oracle.com/en-us/iaas/tools/python-sdk-examples/latest/databasetools/create_database_tools_connection.py.html>`__ to see an example of how to use create_database_tools_connection API.
Creates a new DatabaseToolsConnection.
[ "Creates", "a", "new", "DatabaseToolsConnection", "." ]
def create_database_tools_connection(self, create_database_tools_connection_details, **kwargs): """ Creates a new DatabaseToolsConnection. :param oci.database_tools.models.CreateDatabaseToolsConnectionDetails create_database_tools_connection_details: (required) Details for the new DatabaseToolsConnection. :param str opc_retry_token: (optional) A token that uniquely identifies a request so it can be retried in case of a timeout or server error without risk of executing that same action again. Retry tokens expire after 24 hours, but can be invalidated before then due to conflicting operations. For example, if a resource has been deleted and purged from the system, then a retry of the original creation request might be rejected. :param str opc_request_id: (optional) The client request ID for tracing. :param obj retry_strategy: (optional) A retry strategy to apply to this specific operation/call. This will override any retry strategy set at the client-level. This should be one of the strategies available in the :py:mod:`~oci.retry` module. This operation will not retry by default, users can also use the convenient :py:data:`~oci.retry.DEFAULT_RETRY_STRATEGY` provided by the SDK to enable retries for it. The specifics of the default retry strategy are described `here <https://docs.oracle.com/en-us/iaas/tools/python/latest/sdk_behaviors/retries.html>`__. To have this operation explicitly not perform any retries, pass an instance of :py:class:`~oci.retry.NoneRetryStrategy`. :return: A :class:`~oci.response.Response` object with data of type :class:`~oci.database_tools.models.DatabaseToolsConnection` :rtype: :class:`~oci.response.Response` :example: Click `here <https://docs.cloud.oracle.com/en-us/iaas/tools/python-sdk-examples/latest/databasetools/create_database_tools_connection.py.html>`__ to see an example of how to use create_database_tools_connection API. """ resource_path = "/databaseToolsConnections" method = "POST" # Don't accept unknown kwargs expected_kwargs = [ "retry_strategy", "opc_retry_token", "opc_request_id" ] extra_kwargs = [_key for _key in six.iterkeys(kwargs) if _key not in expected_kwargs] if extra_kwargs: raise ValueError( "create_database_tools_connection got unknown kwargs: {!r}".format(extra_kwargs)) header_params = { "accept": "application/json", "content-type": "application/json", "opc-retry-token": kwargs.get("opc_retry_token", missing), "opc-request-id": kwargs.get("opc_request_id", missing) } header_params = {k: v for (k, v) in six.iteritems(header_params) if v is not missing and v is not None} retry_strategy = self.base_client.get_preferred_retry_strategy( operation_retry_strategy=kwargs.get('retry_strategy'), client_retry_strategy=self.retry_strategy ) if retry_strategy: if not isinstance(retry_strategy, retry.NoneRetryStrategy): self.base_client.add_opc_retry_token_if_needed(header_params) self.base_client.add_opc_client_retries_header(header_params) retry_strategy.add_circuit_breaker_callback(self.circuit_breaker_callback) return retry_strategy.make_retrying_call( self.base_client.call_api, resource_path=resource_path, method=method, header_params=header_params, body=create_database_tools_connection_details, response_type="DatabaseToolsConnection") else: return self.base_client.call_api( resource_path=resource_path, method=method, header_params=header_params, body=create_database_tools_connection_details, response_type="DatabaseToolsConnection")
[ "def", "create_database_tools_connection", "(", "self", ",", "create_database_tools_connection_details", ",", "*", "*", "kwargs", ")", ":", "resource_path", "=", "\"/databaseToolsConnections\"", "method", "=", "\"POST\"", "# Don't accept unknown kwargs", "expected_kwargs", "=", "[", "\"retry_strategy\"", ",", "\"opc_retry_token\"", ",", "\"opc_request_id\"", "]", "extra_kwargs", "=", "[", "_key", "for", "_key", "in", "six", ".", "iterkeys", "(", "kwargs", ")", "if", "_key", "not", "in", "expected_kwargs", "]", "if", "extra_kwargs", ":", "raise", "ValueError", "(", "\"create_database_tools_connection got unknown kwargs: {!r}\"", ".", "format", "(", "extra_kwargs", ")", ")", "header_params", "=", "{", "\"accept\"", ":", "\"application/json\"", ",", "\"content-type\"", ":", "\"application/json\"", ",", "\"opc-retry-token\"", ":", "kwargs", ".", "get", "(", "\"opc_retry_token\"", ",", "missing", ")", ",", "\"opc-request-id\"", ":", "kwargs", ".", "get", "(", "\"opc_request_id\"", ",", "missing", ")", "}", "header_params", "=", "{", "k", ":", "v", "for", "(", "k", ",", "v", ")", "in", "six", ".", "iteritems", "(", "header_params", ")", "if", "v", "is", "not", "missing", "and", "v", "is", "not", "None", "}", "retry_strategy", "=", "self", ".", "base_client", ".", "get_preferred_retry_strategy", "(", "operation_retry_strategy", "=", "kwargs", ".", "get", "(", "'retry_strategy'", ")", ",", "client_retry_strategy", "=", "self", ".", "retry_strategy", ")", "if", "retry_strategy", ":", "if", "not", "isinstance", "(", "retry_strategy", ",", "retry", ".", "NoneRetryStrategy", ")", ":", "self", ".", "base_client", ".", "add_opc_retry_token_if_needed", "(", "header_params", ")", "self", ".", "base_client", ".", "add_opc_client_retries_header", "(", "header_params", ")", "retry_strategy", ".", "add_circuit_breaker_callback", "(", "self", ".", "circuit_breaker_callback", ")", "return", "retry_strategy", ".", "make_retrying_call", "(", "self", ".", "base_client", ".", "call_api", ",", "resource_path", "=", "resource_path", ",", "method", "=", "method", ",", "header_params", "=", "header_params", ",", "body", "=", "create_database_tools_connection_details", ",", "response_type", "=", "\"DatabaseToolsConnection\"", ")", "else", ":", "return", "self", ".", "base_client", ".", "call_api", "(", "resource_path", "=", "resource_path", ",", "method", "=", "method", ",", "header_params", "=", "header_params", ",", "body", "=", "create_database_tools_connection_details", ",", "response_type", "=", "\"DatabaseToolsConnection\"", ")" ]
https://github.com/oracle/oci-python-sdk/blob/3c1604e4e212008fb6718e2f68cdb5ef71fd5793/src/oci/database_tools/database_tools_client.py#L315-L392
Alfanous-team/alfanous
594514729473c24efa3908e3107b45a38255de4b
src/alfanous/Support/whoosh/filedb/structfile.py
python
StructFile.read_8bitfloat
(self, mantissabits=5, zeroexp=2)
return byte_to_float(self.read_byte(), mantissabits, zeroexp)
Reads a byte-sized representation of a floating point value. :param mantissabits: the number of bits to use for the mantissa (with the rest used for the exponent). :param zeroexp: the zero point for the exponent.
Reads a byte-sized representation of a floating point value. :param mantissabits: the number of bits to use for the mantissa (with the rest used for the exponent). :param zeroexp: the zero point for the exponent.
[ "Reads", "a", "byte", "-", "sized", "representation", "of", "a", "floating", "point", "value", ".", ":", "param", "mantissabits", ":", "the", "number", "of", "bits", "to", "use", "for", "the", "mantissa", "(", "with", "the", "rest", "used", "for", "the", "exponent", ")", ".", ":", "param", "zeroexp", ":", "the", "zero", "point", "for", "the", "exponent", "." ]
def read_8bitfloat(self, mantissabits=5, zeroexp=2): """Reads a byte-sized representation of a floating point value. :param mantissabits: the number of bits to use for the mantissa (with the rest used for the exponent). :param zeroexp: the zero point for the exponent. """ return byte_to_float(self.read_byte(), mantissabits, zeroexp)
[ "def", "read_8bitfloat", "(", "self", ",", "mantissabits", "=", "5", ",", "zeroexp", "=", "2", ")", ":", "return", "byte_to_float", "(", "self", ".", "read_byte", "(", ")", ",", "mantissabits", ",", "zeroexp", ")" ]
https://github.com/Alfanous-team/alfanous/blob/594514729473c24efa3908e3107b45a38255de4b/src/alfanous/Support/whoosh/filedb/structfile.py#L178-L185
davidfoerster/aptsources-cleanup
8ea6b410be2aa7c6fa9382ae25137be71639443d
src/aptsources_cleanup/util/relations.py
python
FrozensetAltRepr.__str__
(self)
return self._str_impl(self)
[]
def __str__(self): return self._str_impl(self)
[ "def", "__str__", "(", "self", ")", ":", "return", "self", ".", "_str_impl", "(", "self", ")" ]
https://github.com/davidfoerster/aptsources-cleanup/blob/8ea6b410be2aa7c6fa9382ae25137be71639443d/src/aptsources_cleanup/util/relations.py#L15-L16
rhinstaller/anaconda
63edc8680f1b05cbfe11bef28703acba808c5174
pyanaconda/ui/gui/spokes/installation_source.py
python
SourceSpoke._get_repo_by_id
(self, repo_id)
return None
Return a repository by given name
Return a repository by given name
[ "Return", "a", "repository", "by", "given", "name" ]
def _get_repo_by_id(self, repo_id): """ Return a repository by given name """ for repo in self._repo_store: if repo[REPO_OBJ].repo_id == repo_id: return repo[REPO_OBJ] return None
[ "def", "_get_repo_by_id", "(", "self", ",", "repo_id", ")", ":", "for", "repo", "in", "self", ".", "_repo_store", ":", "if", "repo", "[", "REPO_OBJ", "]", ".", "repo_id", "==", "repo_id", ":", "return", "repo", "[", "REPO_OBJ", "]", "return", "None" ]
https://github.com/rhinstaller/anaconda/blob/63edc8680f1b05cbfe11bef28703acba808c5174/pyanaconda/ui/gui/spokes/installation_source.py#L1538-L1544
kanzure/nanoengineer
874e4c9f8a9190f093625b267f9767e19f82e6c4
cad/src/commands/BuildAtoms/BuildAtomsPropertyManager.py
python
BuildAtomsPropertyManager._moveSelectedAtom
(self, spinBoxValueJunk = None)
Move the selected atom position based on the value in the X, Y, Z coordinate spinboxes in the Selection GroupBox. @param spinBoxValueJunk: This is the Spinbox value from the valueChanged signal. It is not used. We just want to know that the spinbox value has changed. @type spinBoxValueJunk: double or None
Move the selected atom position based on the value in the X, Y, Z coordinate spinboxes in the Selection GroupBox.
[ "Move", "the", "selected", "atom", "position", "based", "on", "the", "value", "in", "the", "X", "Y", "Z", "coordinate", "spinboxes", "in", "the", "Selection", "GroupBox", "." ]
def _moveSelectedAtom(self, spinBoxValueJunk = None): """ Move the selected atom position based on the value in the X, Y, Z coordinate spinboxes in the Selection GroupBox. @param spinBoxValueJunk: This is the Spinbox value from the valueChanged signal. It is not used. We just want to know that the spinbox value has changed. @type spinBoxValueJunk: double or None """ if self.model_changed_from_glpane: #Model is changed from glpane ,do nothing. Fixes bug 2545 print "bug: self.model_changed_from_glpane seen; should never happen after bug 2564 was fixed." #bruce 071015 return totalAtoms, selectedAtom, atomPosn_junk = self._currentSelectionParams() if not totalAtoms == 1: return #@NOTE: This is important to determine baggage and nobaggage atoms. #Otherwise the bondpoints won't move! See also: # selectMode.atomSetup where this is done. # But that method gets called only when during atom left down. #Its not useful here as user may select that atom using selection lasso #or using other means (ctrl + A if only one atom is present) . Also, #the lists command.baggage and command.nonbaggage seem to get #cleared during left up. So that method is not useful. #There needs to be a method in parentmode (Select_Command or #BuildAtoms_Command) #to do the following (next code cleanup?) -- ninad 2007-09-27 self.command.baggage, self.command.nonbaggage = \ selectedAtom.baggage_and_other_neighbors() xPos= self.xCoordOfSelectedAtom.value() yPos = self.yCoordOfSelectedAtom.value() zPos = self.zCoordOfSelectedAtom.value() newPosition = V(xPos, yPos, zPos) delta = newPosition - selectedAtom.posn() #Don't do selectedAtom.setposn() because it needs to handle #cases where atom has bond points and/or monovalent atoms . It also #needs to modify the neighboring atom baggage. This is already done in #the following method in command so use that. self.command.drag_selected_atom(selectedAtom, delta, computeBaggage = True) self.o.gl_update()
[ "def", "_moveSelectedAtom", "(", "self", ",", "spinBoxValueJunk", "=", "None", ")", ":", "if", "self", ".", "model_changed_from_glpane", ":", "#Model is changed from glpane ,do nothing. Fixes bug 2545", "print", "\"bug: self.model_changed_from_glpane seen; should never happen after bug 2564 was fixed.\"", "#bruce 071015", "return", "totalAtoms", ",", "selectedAtom", ",", "atomPosn_junk", "=", "self", ".", "_currentSelectionParams", "(", ")", "if", "not", "totalAtoms", "==", "1", ":", "return", "#@NOTE: This is important to determine baggage and nobaggage atoms.", "#Otherwise the bondpoints won't move! See also:", "# selectMode.atomSetup where this is done.", "# But that method gets called only when during atom left down.", "#Its not useful here as user may select that atom using selection lasso", "#or using other means (ctrl + A if only one atom is present) . Also,", "#the lists command.baggage and command.nonbaggage seem to get", "#cleared during left up. So that method is not useful.", "#There needs to be a method in parentmode (Select_Command or", "#BuildAtoms_Command)", "#to do the following (next code cleanup?) -- ninad 2007-09-27", "self", ".", "command", ".", "baggage", ",", "self", ".", "command", ".", "nonbaggage", "=", "selectedAtom", ".", "baggage_and_other_neighbors", "(", ")", "xPos", "=", "self", ".", "xCoordOfSelectedAtom", ".", "value", "(", ")", "yPos", "=", "self", ".", "yCoordOfSelectedAtom", ".", "value", "(", ")", "zPos", "=", "self", ".", "zCoordOfSelectedAtom", ".", "value", "(", ")", "newPosition", "=", "V", "(", "xPos", ",", "yPos", ",", "zPos", ")", "delta", "=", "newPosition", "-", "selectedAtom", ".", "posn", "(", ")", "#Don't do selectedAtom.setposn() because it needs to handle", "#cases where atom has bond points and/or monovalent atoms . It also", "#needs to modify the neighboring atom baggage. This is already done in", "#the following method in command so use that.", "self", ".", "command", ".", "drag_selected_atom", "(", "selectedAtom", ",", "delta", ",", "computeBaggage", "=", "True", ")", "self", ".", "o", ".", "gl_update", "(", ")" ]
https://github.com/kanzure/nanoengineer/blob/874e4c9f8a9190f093625b267f9767e19f82e6c4/cad/src/commands/BuildAtoms/BuildAtomsPropertyManager.py#L369-L416
buke/GreenOdoo
3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df
runtime/common/lib/python2.7/site-packages/libxml2.py
python
ValidCtxt.validatePopElement
(self, doc, elem, qname)
return ret
Pop the element end from the validation stack.
Pop the element end from the validation stack.
[ "Pop", "the", "element", "end", "from", "the", "validation", "stack", "." ]
def validatePopElement(self, doc, elem, qname): """Pop the element end from the validation stack. """ if doc is None: doc__o = None else: doc__o = doc._o if elem is None: elem__o = None else: elem__o = elem._o ret = libxml2mod.xmlValidatePopElement(self._o, doc__o, elem__o, qname) return ret
[ "def", "validatePopElement", "(", "self", ",", "doc", ",", "elem", ",", "qname", ")", ":", "if", "doc", "is", "None", ":", "doc__o", "=", "None", "else", ":", "doc__o", "=", "doc", ".", "_o", "if", "elem", "is", "None", ":", "elem__o", "=", "None", "else", ":", "elem__o", "=", "elem", ".", "_o", "ret", "=", "libxml2mod", ".", "xmlValidatePopElement", "(", "self", ".", "_o", ",", "doc__o", ",", "elem__o", ",", "qname", ")", "return", "ret" ]
https://github.com/buke/GreenOdoo/blob/3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df/runtime/common/lib/python2.7/site-packages/libxml2.py#L7121-L7128
kernel1983/NoMagic
4ad6e748cf1ba19857ecacad839a0ff9659e3c31
nomagic/torndb.py
python
Connection.close
(self)
Closes this database connection.
Closes this database connection.
[ "Closes", "this", "database", "connection", "." ]
def close(self): """Closes this database connection.""" if getattr(self, "_db", None) is not None: self._db.close() self._db = None
[ "def", "close", "(", "self", ")", ":", "if", "getattr", "(", "self", ",", "\"_db\"", ",", "None", ")", "is", "not", "None", ":", "self", ".", "_db", ".", "close", "(", ")", "self", ".", "_db", "=", "None" ]
https://github.com/kernel1983/NoMagic/blob/4ad6e748cf1ba19857ecacad839a0ff9659e3c31/nomagic/torndb.py#L104-L108
replit-archive/empythoned
977ec10ced29a3541a4973dc2b59910805695752
dist/lib/python2.7/lib2to3/fixer_util.py
python
String
(string, prefix=None)
return Leaf(token.STRING, string, prefix=prefix)
A string leaf
A string leaf
[ "A", "string", "leaf" ]
def String(string, prefix=None): """A string leaf""" return Leaf(token.STRING, string, prefix=prefix)
[ "def", "String", "(", "string", ",", "prefix", "=", "None", ")", ":", "return", "Leaf", "(", "token", ".", "STRING", ",", "string", ",", "prefix", "=", "prefix", ")" ]
https://github.com/replit-archive/empythoned/blob/977ec10ced29a3541a4973dc2b59910805695752/dist/lib/python2.7/lib2to3/fixer_util.py#L85-L87
kubernetes-client/python
47b9da9de2d02b2b7a34fbe05afb44afd130d73a
kubernetes/client/models/v1_subject_access_review_status.py
python
V1SubjectAccessReviewStatus.__ne__
(self, other)
return self.to_dict() != other.to_dict()
Returns true if both objects are not equal
Returns true if both objects are not equal
[ "Returns", "true", "if", "both", "objects", "are", "not", "equal" ]
def __ne__(self, other): """Returns true if both objects are not equal""" if not isinstance(other, V1SubjectAccessReviewStatus): return True return self.to_dict() != other.to_dict()
[ "def", "__ne__", "(", "self", ",", "other", ")", ":", "if", "not", "isinstance", "(", "other", ",", "V1SubjectAccessReviewStatus", ")", ":", "return", "True", "return", "self", ".", "to_dict", "(", ")", "!=", "other", ".", "to_dict", "(", ")" ]
https://github.com/kubernetes-client/python/blob/47b9da9de2d02b2b7a34fbe05afb44afd130d73a/kubernetes/client/models/v1_subject_access_review_status.py#L202-L207
clips/pattern
d25511f9ca7ed9356b801d8663b8b5168464e68f
pattern/web/__init__.py
python
DBPedia.search
(self, query, type=SPARQL, start=1, count=10, sort=RELEVANCY, size=None, cached=False, **kwargs)
return results
Returns a list of results from DBPedia for the given SPARQL query. - type : SPARQL, - start: no maximum, - count: maximum 1000, There is a limit of 10 requests/second. Maximum query execution time is 120 seconds.
Returns a list of results from DBPedia for the given SPARQL query. - type : SPARQL, - start: no maximum, - count: maximum 1000, There is a limit of 10 requests/second. Maximum query execution time is 120 seconds.
[ "Returns", "a", "list", "of", "results", "from", "DBPedia", "for", "the", "given", "SPARQL", "query", ".", "-", "type", ":", "SPARQL", "-", "start", ":", "no", "maximum", "-", "count", ":", "maximum", "1000", "There", "is", "a", "limit", "of", "10", "requests", "/", "second", ".", "Maximum", "query", "execution", "time", "is", "120", "seconds", "." ]
def search(self, query, type=SPARQL, start=1, count=10, sort=RELEVANCY, size=None, cached=False, **kwargs): """ Returns a list of results from DBPedia for the given SPARQL query. - type : SPARQL, - start: no maximum, - count: maximum 1000, There is a limit of 10 requests/second. Maximum query execution time is 120 seconds. """ if type not in (SPARQL,): raise SearchEngineTypeError if not query or count < 1 or start < 1: return Results(DBPEDIA, query, type) # 1) Construct request URL. url = URL(DBPEDIA, method=GET) url.query = { "format": "json", "query": "%s OFFSET %s LIMIT %s" % (query, (start - 1) * min(count, 1000), (start - 0) * min(count, 1000) ) } # 2) Parse JSON response. try: data = URL(url).download(cached=cached, timeout=30, **kwargs) data = json.loads(data) except HTTP400BadRequest as e: raise DBPediaQueryError(e.src.read().splitlines()[0]) except HTTP403Forbidden: raise SearchEngineLimitError results = Results(DBPEDIA, url.query, type) results.total = None for x in data["results"]["bindings"]: r = Result(url=None) for k in data["head"]["vars"]: t1 = x[k].get("type", "literal") # uri | literal | typed-literal t2 = x[k].get("datatype", "?") # http://www.w3.org/2001/XMLSchema#float | int | date v = x[k].get("value") v = self.format(v) if t1 == "uri": v = DBPediaResource(v) if t2.endswith("float"): v = float(v) if t2.endswith("int"): v = int(v) dict.__setitem__(r, k, v) results.append(r) return results
[ "def", "search", "(", "self", ",", "query", ",", "type", "=", "SPARQL", ",", "start", "=", "1", ",", "count", "=", "10", ",", "sort", "=", "RELEVANCY", ",", "size", "=", "None", ",", "cached", "=", "False", ",", "*", "*", "kwargs", ")", ":", "if", "type", "not", "in", "(", "SPARQL", ",", ")", ":", "raise", "SearchEngineTypeError", "if", "not", "query", "or", "count", "<", "1", "or", "start", "<", "1", ":", "return", "Results", "(", "DBPEDIA", ",", "query", ",", "type", ")", "# 1) Construct request URL.", "url", "=", "URL", "(", "DBPEDIA", ",", "method", "=", "GET", ")", "url", ".", "query", "=", "{", "\"format\"", ":", "\"json\"", ",", "\"query\"", ":", "\"%s OFFSET %s LIMIT %s\"", "%", "(", "query", ",", "(", "start", "-", "1", ")", "*", "min", "(", "count", ",", "1000", ")", ",", "(", "start", "-", "0", ")", "*", "min", "(", "count", ",", "1000", ")", ")", "}", "# 2) Parse JSON response.", "try", ":", "data", "=", "URL", "(", "url", ")", ".", "download", "(", "cached", "=", "cached", ",", "timeout", "=", "30", ",", "*", "*", "kwargs", ")", "data", "=", "json", ".", "loads", "(", "data", ")", "except", "HTTP400BadRequest", "as", "e", ":", "raise", "DBPediaQueryError", "(", "e", ".", "src", ".", "read", "(", ")", ".", "splitlines", "(", ")", "[", "0", "]", ")", "except", "HTTP403Forbidden", ":", "raise", "SearchEngineLimitError", "results", "=", "Results", "(", "DBPEDIA", ",", "url", ".", "query", ",", "type", ")", "results", ".", "total", "=", "None", "for", "x", "in", "data", "[", "\"results\"", "]", "[", "\"bindings\"", "]", ":", "r", "=", "Result", "(", "url", "=", "None", ")", "for", "k", "in", "data", "[", "\"head\"", "]", "[", "\"vars\"", "]", ":", "t1", "=", "x", "[", "k", "]", ".", "get", "(", "\"type\"", ",", "\"literal\"", ")", "# uri | literal | typed-literal", "t2", "=", "x", "[", "k", "]", ".", "get", "(", "\"datatype\"", ",", "\"?\"", ")", "# http://www.w3.org/2001/XMLSchema#float | int | date", "v", "=", "x", "[", "k", "]", ".", "get", "(", "\"value\"", ")", "v", "=", "self", ".", "format", "(", "v", ")", "if", "t1", "==", "\"uri\"", ":", "v", "=", "DBPediaResource", "(", "v", ")", "if", "t2", ".", "endswith", "(", "\"float\"", ")", ":", "v", "=", "float", "(", "v", ")", "if", "t2", ".", "endswith", "(", "\"int\"", ")", ":", "v", "=", "int", "(", "v", ")", "dict", ".", "__setitem__", "(", "r", ",", "k", ",", "v", ")", "results", ".", "append", "(", "r", ")", "return", "results" ]
https://github.com/clips/pattern/blob/d25511f9ca7ed9356b801d8663b8b5168464e68f/pattern/web/__init__.py#L2986-L3032
coderholic/pyradio
cd3ee2d6b369fedfd009371a59aca23ab39b020f
pyradio/radio.py
python
PyRadio._move_cursor_one_down
(self)
[]
def _move_cursor_one_down(self): self._reset_status_bar_right() if self.number_of_items > 0: self.setStation(self.selection + 1) self._handle_cursor_move_down()
[ "def", "_move_cursor_one_down", "(", "self", ")", ":", "self", ".", "_reset_status_bar_right", "(", ")", "if", "self", ".", "number_of_items", ">", "0", ":", "self", ".", "setStation", "(", "self", ".", "selection", "+", "1", ")", "self", ".", "_handle_cursor_move_down", "(", ")" ]
https://github.com/coderholic/pyradio/blob/cd3ee2d6b369fedfd009371a59aca23ab39b020f/pyradio/radio.py#L4481-L4485
plasticityai/magnitude
7ac0baeaf181263b661c3ae00643d21e3fd90216
pymagnitude/third_party/allennlp/nn/regularizers/regularizer_applicator.py
python
RegularizerApplicator.__call__
(self, module )
return accumulator
u""" Parameters ---------- module : torch.nn.Module, required The module to regularize.
u""" Parameters ---------- module : torch.nn.Module, required The module to regularize.
[ "u", "Parameters", "----------", "module", ":", "torch", ".", "nn", ".", "Module", "required", "The", "module", "to", "regularize", "." ]
def __call__(self, module ) : u""" Parameters ---------- module : torch.nn.Module, required The module to regularize. """ accumulator = 0.0 # For each parameter find the first matching regex. for name, parameter in module.named_parameters(): for regex, regularizer in self._regularizers: if re.search(regex, name): penalty = regularizer(parameter) accumulator = accumulator + penalty break return accumulator
[ "def", "__call__", "(", "self", ",", "module", ")", ":", "accumulator", "=", "0.0", "# For each parameter find the first matching regex.", "for", "name", ",", "parameter", "in", "module", ".", "named_parameters", "(", ")", ":", "for", "regex", ",", "regularizer", "in", "self", ".", "_regularizers", ":", "if", "re", ".", "search", "(", "regex", ",", "name", ")", ":", "penalty", "=", "regularizer", "(", "parameter", ")", "accumulator", "=", "accumulator", "+", "penalty", "break", "return", "accumulator" ]
https://github.com/plasticityai/magnitude/blob/7ac0baeaf181263b661c3ae00643d21e3fd90216/pymagnitude/third_party/allennlp/nn/regularizers/regularizer_applicator.py#L27-L43
bitcraze/crazyflie-lib-python
876f0dc003b91ba5e4de05daae9d0b79cf600f81
examples/swarm/hl-commander-swarm.py
python
activate_mellinger_controller
(scf, use_mellinger)
[]
def activate_mellinger_controller(scf, use_mellinger): controller = 1 if use_mellinger: controller = 2 scf.cf.param.set_value('stabilizer.controller', controller)
[ "def", "activate_mellinger_controller", "(", "scf", ",", "use_mellinger", ")", ":", "controller", "=", "1", "if", "use_mellinger", ":", "controller", "=", "2", "scf", ".", "cf", ".", "param", ".", "set_value", "(", "'stabilizer.controller'", ",", "controller", ")" ]
https://github.com/bitcraze/crazyflie-lib-python/blob/876f0dc003b91ba5e4de05daae9d0b79cf600f81/examples/swarm/hl-commander-swarm.py#L46-L50
crocs-muni/roca
df6071d502f68701427f8b1d409cab22055ad1b7
roca/detect.py
python
drop_empty
(arr)
return [x for x in arr if not isinstance(x, list) or len(x) > 0]
Drop empty array element :param arr: :return:
Drop empty array element :param arr: :return:
[ "Drop", "empty", "array", "element", ":", "param", "arr", ":", ":", "return", ":" ]
def drop_empty(arr): """ Drop empty array element :param arr: :return: """ return [x for x in arr if not isinstance(x, list) or len(x) > 0]
[ "def", "drop_empty", "(", "arr", ")", ":", "return", "[", "x", "for", "x", "in", "arr", "if", "not", "isinstance", "(", "x", ",", "list", ")", "or", "len", "(", "x", ")", ">", "0", "]" ]
https://github.com/crocs-muni/roca/blob/df6071d502f68701427f8b1d409cab22055ad1b7/roca/detect.py#L161-L167
dmlc/dgl
8d14a739bc9e446d6c92ef83eafe5782398118de
examples/pytorch/graph_matching/ged.py
python
validate_cost_functions
(G1, G2, node_substitution_cost=None, edge_substitution_cost=None, G1_node_deletion_cost=None, G1_edge_deletion_cost=None, G2_node_insertion_cost=None, G2_edge_insertion_cost=None)
return node_substitution_cost, edge_substitution_cost, \ G1_node_deletion_cost, G1_edge_deletion_cost, \ G2_node_insertion_cost, G2_edge_insertion_cost
Validates cost functions (substitution, insertion, deletion) and initializes them with default=0 for substitution and default=1 for insertion/deletion if the provided ones are None. Parameters : see graph_edit_distance
Validates cost functions (substitution, insertion, deletion) and initializes them with default=0 for substitution and default=1 for insertion/deletion if the provided ones are None.
[ "Validates", "cost", "functions", "(", "substitution", "insertion", "deletion", ")", "and", "initializes", "them", "with", "default", "=", "0", "for", "substitution", "and", "default", "=", "1", "for", "insertion", "/", "deletion", "if", "the", "provided", "ones", "are", "None", "." ]
def validate_cost_functions(G1, G2, node_substitution_cost=None, edge_substitution_cost=None, G1_node_deletion_cost=None, G1_edge_deletion_cost=None, G2_node_insertion_cost=None, G2_edge_insertion_cost=None): """Validates cost functions (substitution, insertion, deletion) and initializes them with default=0 for substitution and default=1 for insertion/deletion if the provided ones are None. Parameters : see graph_edit_distance """ num_G1_nodes = G1.number_of_nodes() num_G2_nodes = G2.number_of_nodes() num_G1_edges = G1.number_of_edges() num_G2_edges = G2.number_of_edges() # if any cost matrix is None, initialize it with default costs if node_substitution_cost is None: node_substitution_cost = np.zeros((num_G1_nodes, num_G2_nodes), dtype=float) else: assert node_substitution_cost.shape == (num_G1_nodes, num_G2_nodes); if edge_substitution_cost is None: edge_substitution_cost = np.zeros((num_G1_edges, num_G2_edges), dtype=float) else: assert edge_substitution_cost.shape == (num_G1_edges, num_G2_edges); if G1_node_deletion_cost is None: G1_node_deletion_cost = np.ones(num_G1_nodes, dtype=float) else: assert G1_node_deletion_cost.shape[0] == num_G1_nodes; if G1_edge_deletion_cost is None: G1_edge_deletion_cost = np.ones(num_G1_edges, dtype=float) else: assert G1_edge_deletion_cost.shape[0] == num_G1_edges; if G2_node_insertion_cost is None: G2_node_insertion_cost = np.ones(num_G2_nodes, dtype=float) else: assert G2_node_insertion_cost.shape[0] == num_G2_nodes; if G2_edge_insertion_cost is None: G2_edge_insertion_cost = np.ones(num_G2_edges, dtype=float) else: assert G2_edge_insertion_cost.shape[0] == num_G2_edges; return node_substitution_cost, edge_substitution_cost, \ G1_node_deletion_cost, G1_edge_deletion_cost, \ G2_node_insertion_cost, G2_edge_insertion_cost;
[ "def", "validate_cost_functions", "(", "G1", ",", "G2", ",", "node_substitution_cost", "=", "None", ",", "edge_substitution_cost", "=", "None", ",", "G1_node_deletion_cost", "=", "None", ",", "G1_edge_deletion_cost", "=", "None", ",", "G2_node_insertion_cost", "=", "None", ",", "G2_edge_insertion_cost", "=", "None", ")", ":", "num_G1_nodes", "=", "G1", ".", "number_of_nodes", "(", ")", "num_G2_nodes", "=", "G2", ".", "number_of_nodes", "(", ")", "num_G1_edges", "=", "G1", ".", "number_of_edges", "(", ")", "num_G2_edges", "=", "G2", ".", "number_of_edges", "(", ")", "# if any cost matrix is None, initialize it with default costs", "if", "node_substitution_cost", "is", "None", ":", "node_substitution_cost", "=", "np", ".", "zeros", "(", "(", "num_G1_nodes", ",", "num_G2_nodes", ")", ",", "dtype", "=", "float", ")", "else", ":", "assert", "node_substitution_cost", ".", "shape", "==", "(", "num_G1_nodes", ",", "num_G2_nodes", ")", "if", "edge_substitution_cost", "is", "None", ":", "edge_substitution_cost", "=", "np", ".", "zeros", "(", "(", "num_G1_edges", ",", "num_G2_edges", ")", ",", "dtype", "=", "float", ")", "else", ":", "assert", "edge_substitution_cost", ".", "shape", "==", "(", "num_G1_edges", ",", "num_G2_edges", ")", "if", "G1_node_deletion_cost", "is", "None", ":", "G1_node_deletion_cost", "=", "np", ".", "ones", "(", "num_G1_nodes", ",", "dtype", "=", "float", ")", "else", ":", "assert", "G1_node_deletion_cost", ".", "shape", "[", "0", "]", "==", "num_G1_nodes", "if", "G1_edge_deletion_cost", "is", "None", ":", "G1_edge_deletion_cost", "=", "np", ".", "ones", "(", "num_G1_edges", ",", "dtype", "=", "float", ")", "else", ":", "assert", "G1_edge_deletion_cost", ".", "shape", "[", "0", "]", "==", "num_G1_edges", "if", "G2_node_insertion_cost", "is", "None", ":", "G2_node_insertion_cost", "=", "np", ".", "ones", "(", "num_G2_nodes", ",", "dtype", "=", "float", ")", "else", ":", "assert", "G2_node_insertion_cost", ".", "shape", "[", "0", "]", "==", "num_G2_nodes", "if", "G2_edge_insertion_cost", "is", "None", ":", "G2_edge_insertion_cost", "=", "np", ".", "ones", "(", "num_G2_edges", ",", "dtype", "=", "float", ")", "else", ":", "assert", "G2_edge_insertion_cost", ".", "shape", "[", "0", "]", "==", "num_G2_edges", "return", "node_substitution_cost", ",", "edge_substitution_cost", ",", "G1_node_deletion_cost", ",", "G1_edge_deletion_cost", ",", "G2_node_insertion_cost", ",", "G2_edge_insertion_cost" ]
https://github.com/dmlc/dgl/blob/8d14a739bc9e446d6c92ef83eafe5782398118de/examples/pytorch/graph_matching/ged.py#L11-L62
hypothesis/h
25ef1b8d94889df86ace5a084f1aa0effd9f4e25
h/migrations/versions/467ea2898660_fix_document_uri_unique_constraint.py
python
delete_conflicting_document_uris
(session)
Delete NULL DocumentURIs where there's already an empty string one. Later we're going to be finding all DocumentURIs with NULL for their type or content_type and changing them to empty strings. But for each one of these NULL DocumentURIs if there is already a matching DocumentURI - same claimant_normalized, uri_normalized, type and content_type but that already has an empty string instead of NULL for the type and/or content_type - then trying to change the NULL DocumentURI to an empty string one will fail with IntegrityError. So find all the DocumentURIs with an empty string for their type and/or content_type and for each one find any matching DocumentURIs but with NULL for the type and/or content_type and delete them. After this it should be safe to change all NULL types and content_types in document_uri to empty strings.
Delete NULL DocumentURIs where there's already an empty string one.
[ "Delete", "NULL", "DocumentURIs", "where", "there", "s", "already", "an", "empty", "string", "one", "." ]
def delete_conflicting_document_uris(session): """ Delete NULL DocumentURIs where there's already an empty string one. Later we're going to be finding all DocumentURIs with NULL for their type or content_type and changing them to empty strings. But for each one of these NULL DocumentURIs if there is already a matching DocumentURI - same claimant_normalized, uri_normalized, type and content_type but that already has an empty string instead of NULL for the type and/or content_type - then trying to change the NULL DocumentURI to an empty string one will fail with IntegrityError. So find all the DocumentURIs with an empty string for their type and/or content_type and for each one find any matching DocumentURIs but with NULL for the type and/or content_type and delete them. After this it should be safe to change all NULL types and content_types in document_uri to empty strings. """ doc_uris = session.query(DocumentURI).filter( sa.or_(DocumentURI.type == "", DocumentURI.content_type == "") ) n = 0 for doc_uri in doc_uris: conflicting_doc_uris = session.query(DocumentURI).filter( DocumentURI.claimant_normalized == doc_uri.claimant_normalized, DocumentURI.uri_normalized == doc_uri.uri_normalized, DocumentURI.id != doc_uri.id, ) if doc_uri.type == "" and doc_uri.content_type == "": conflicting_doc_uris = conflicting_doc_uris.filter( sa.or_(DocumentURI.type == "", DocumentURI.type.is_(None)), sa.or_( DocumentURI.content_type == "", DocumentURI.content_type.is_(None) ), ) elif doc_uri.type == "": conflicting_doc_uris = conflicting_doc_uris.filter( sa.or_(DocumentURI.type == "", DocumentURI.type.is_(None)), DocumentURI.content_type == doc_uri.content_type, ) elif doc_uri.content_type == "": conflicting_doc_uris = conflicting_doc_uris.filter( DocumentURI.type == doc_uri.type, sa.or_( DocumentURI.content_type == "", DocumentURI.content_type.is_(None) ), ) n += batch_delete(conflicting_doc_uris, session) log.info("deleted %d duplicate rows from document_uri (empty string/NULL)" % n)
[ "def", "delete_conflicting_document_uris", "(", "session", ")", ":", "doc_uris", "=", "session", ".", "query", "(", "DocumentURI", ")", ".", "filter", "(", "sa", ".", "or_", "(", "DocumentURI", ".", "type", "==", "\"\"", ",", "DocumentURI", ".", "content_type", "==", "\"\"", ")", ")", "n", "=", "0", "for", "doc_uri", "in", "doc_uris", ":", "conflicting_doc_uris", "=", "session", ".", "query", "(", "DocumentURI", ")", ".", "filter", "(", "DocumentURI", ".", "claimant_normalized", "==", "doc_uri", ".", "claimant_normalized", ",", "DocumentURI", ".", "uri_normalized", "==", "doc_uri", ".", "uri_normalized", ",", "DocumentURI", ".", "id", "!=", "doc_uri", ".", "id", ",", ")", "if", "doc_uri", ".", "type", "==", "\"\"", "and", "doc_uri", ".", "content_type", "==", "\"\"", ":", "conflicting_doc_uris", "=", "conflicting_doc_uris", ".", "filter", "(", "sa", ".", "or_", "(", "DocumentURI", ".", "type", "==", "\"\"", ",", "DocumentURI", ".", "type", ".", "is_", "(", "None", ")", ")", ",", "sa", ".", "or_", "(", "DocumentURI", ".", "content_type", "==", "\"\"", ",", "DocumentURI", ".", "content_type", ".", "is_", "(", "None", ")", ")", ",", ")", "elif", "doc_uri", ".", "type", "==", "\"\"", ":", "conflicting_doc_uris", "=", "conflicting_doc_uris", ".", "filter", "(", "sa", ".", "or_", "(", "DocumentURI", ".", "type", "==", "\"\"", ",", "DocumentURI", ".", "type", ".", "is_", "(", "None", ")", ")", ",", "DocumentURI", ".", "content_type", "==", "doc_uri", ".", "content_type", ",", ")", "elif", "doc_uri", ".", "content_type", "==", "\"\"", ":", "conflicting_doc_uris", "=", "conflicting_doc_uris", ".", "filter", "(", "DocumentURI", ".", "type", "==", "doc_uri", ".", "type", ",", "sa", ".", "or_", "(", "DocumentURI", ".", "content_type", "==", "\"\"", ",", "DocumentURI", ".", "content_type", ".", "is_", "(", "None", ")", ")", ",", ")", "n", "+=", "batch_delete", "(", "conflicting_doc_uris", ",", "session", ")", "log", ".", "info", "(", "\"deleted %d duplicate rows from document_uri (empty string/NULL)\"", "%", "n", ")" ]
https://github.com/hypothesis/h/blob/25ef1b8d94889df86ace5a084f1aa0effd9f4e25/h/migrations/versions/467ea2898660_fix_document_uri_unique_constraint.py#L116-L172
eternnoir/pyTelegramBotAPI
fdbc0e6a619f671c2ac97afa2f694c17c6dce7d9
telebot/__init__.py
python
TeleBot.add_chat_join_request_handler
(self, handler_dict)
Adds a chat_join_request handler :param handler_dict: :return:
Adds a chat_join_request handler :param handler_dict: :return:
[ "Adds", "a", "chat_join_request", "handler", ":", "param", "handler_dict", ":", ":", "return", ":" ]
def add_chat_join_request_handler(self, handler_dict): """ Adds a chat_join_request handler :param handler_dict: :return: """ self.chat_join_request_handlers.append(handler_dict)
[ "def", "add_chat_join_request_handler", "(", "self", ",", "handler_dict", ")", ":", "self", ".", "chat_join_request_handlers", ".", "append", "(", "handler_dict", ")" ]
https://github.com/eternnoir/pyTelegramBotAPI/blob/fdbc0e6a619f671c2ac97afa2f694c17c6dce7d9/telebot/__init__.py#L3316-L3322
osmr/imgclsmob
f2993d3ce73a2f7ddba05da3891defb08547d504
tensorflow2/tf2cv/models/simplepose_coco.py
python
get_simplepose
(backbone, backbone_out_channels, keypoints, model_name=None, data_format="channels_last", pretrained=False, root=os.path.join("~", ".tensorflow", "models"), **kwargs)
return net
Create SimplePose model with specific parameters. Parameters: ---------- backbone : nn.Sequential Feature extractor. backbone_out_channels : int Number of output channels for the backbone. keypoints : int Number of keypoints. model_name : str or None, default None Model name for loading pretrained model. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters.
Create SimplePose model with specific parameters.
[ "Create", "SimplePose", "model", "with", "specific", "parameters", "." ]
def get_simplepose(backbone, backbone_out_channels, keypoints, model_name=None, data_format="channels_last", pretrained=False, root=os.path.join("~", ".tensorflow", "models"), **kwargs): """ Create SimplePose model with specific parameters. Parameters: ---------- backbone : nn.Sequential Feature extractor. backbone_out_channels : int Number of output channels for the backbone. keypoints : int Number of keypoints. model_name : str or None, default None Model name for loading pretrained model. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ channels = [256, 256, 256] net = SimplePose( backbone=backbone, backbone_out_channels=backbone_out_channels, channels=channels, keypoints=keypoints, data_format=data_format, **kwargs) if pretrained: if (model_name is None) or (not model_name): raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.") from .model_store import get_model_file in_channels = kwargs["in_channels"] if ("in_channels" in kwargs) else 3 input_shape = (1,) + (in_channels,) + net.in_size if net.data_format == "channels_first" else\ (1,) + net.in_size + (in_channels,) net.build(input_shape=input_shape) net.load_weights( filepath=get_model_file( model_name=model_name, local_model_store_dir_path=root)) return net
[ "def", "get_simplepose", "(", "backbone", ",", "backbone_out_channels", ",", "keypoints", ",", "model_name", "=", "None", ",", "data_format", "=", "\"channels_last\"", ",", "pretrained", "=", "False", ",", "root", "=", "os", ".", "path", ".", "join", "(", "\"~\"", ",", "\".tensorflow\"", ",", "\"models\"", ")", ",", "*", "*", "kwargs", ")", ":", "channels", "=", "[", "256", ",", "256", ",", "256", "]", "net", "=", "SimplePose", "(", "backbone", "=", "backbone", ",", "backbone_out_channels", "=", "backbone_out_channels", ",", "channels", "=", "channels", ",", "keypoints", "=", "keypoints", ",", "data_format", "=", "data_format", ",", "*", "*", "kwargs", ")", "if", "pretrained", ":", "if", "(", "model_name", "is", "None", ")", "or", "(", "not", "model_name", ")", ":", "raise", "ValueError", "(", "\"Parameter `model_name` should be properly initialized for loading pretrained model.\"", ")", "from", ".", "model_store", "import", "get_model_file", "in_channels", "=", "kwargs", "[", "\"in_channels\"", "]", "if", "(", "\"in_channels\"", "in", "kwargs", ")", "else", "3", "input_shape", "=", "(", "1", ",", ")", "+", "(", "in_channels", ",", ")", "+", "net", ".", "in_size", "if", "net", ".", "data_format", "==", "\"channels_first\"", "else", "(", "1", ",", ")", "+", "net", ".", "in_size", "+", "(", "in_channels", ",", ")", "net", ".", "build", "(", "input_shape", "=", "input_shape", ")", "net", ".", "load_weights", "(", "filepath", "=", "get_model_file", "(", "model_name", "=", "model_name", ",", "local_model_store_dir_path", "=", "root", ")", ")", "return", "net" ]
https://github.com/osmr/imgclsmob/blob/f2993d3ce73a2f7ddba05da3891defb08547d504/tensorflow2/tf2cv/models/simplepose_coco.py#L93-L144
smart-mobile-software/gitstack
d9fee8f414f202143eb6e620529e8e5539a2af56
python/Lib/urllib.py
python
thishost
()
return _thishost
Return the IP address of the current host.
Return the IP address of the current host.
[ "Return", "the", "IP", "address", "of", "the", "current", "host", "." ]
def thishost(): """Return the IP address of the current host.""" global _thishost if _thishost is None: _thishost = socket.gethostbyname(socket.gethostname()) return _thishost
[ "def", "thishost", "(", ")", ":", "global", "_thishost", "if", "_thishost", "is", "None", ":", "_thishost", "=", "socket", ".", "gethostbyname", "(", "socket", ".", "gethostname", "(", ")", ")", "return", "_thishost" ]
https://github.com/smart-mobile-software/gitstack/blob/d9fee8f414f202143eb6e620529e8e5539a2af56/python/Lib/urllib.py#L816-L821
Yonv1943/Python
ecce2153892093d7a13686e4cbfd6b323cb59de8
ElegantRL/Beta/elegantrl/AgentZoo/ElegantRL-PER/agent.py
python
AgentD3QN.__init__
(self, net_dim, state_dim, action_dim, learning_rate=1e-4)
Contribution of D3QN (Dueling Double DQN) There are not contribution of D3QN. Obviously, DoubleDQN is compatible with DuelingDQN. Any beginner can come up with this idea (D3QN) independently.
Contribution of D3QN (Dueling Double DQN) There are not contribution of D3QN. Obviously, DoubleDQN is compatible with DuelingDQN. Any beginner can come up with this idea (D3QN) independently.
[ "Contribution", "of", "D3QN", "(", "Dueling", "Double", "DQN", ")", "There", "are", "not", "contribution", "of", "D3QN", ".", "Obviously", "DoubleDQN", "is", "compatible", "with", "DuelingDQN", ".", "Any", "beginner", "can", "come", "up", "with", "this", "idea", "(", "D3QN", ")", "independently", "." ]
def __init__(self, net_dim, state_dim, action_dim, learning_rate=1e-4): super().__init__(net_dim, state_dim, action_dim, learning_rate) self.explore_rate = 0.25 # epsilon-greedy, the rate of choosing random action self.act = QNetTwinDuel(net_dim, state_dim, action_dim).to(self.device) self.act_target = deepcopy(self.act) self.criterion = torch.nn.SmoothL1Loss() self.optimizer = torch.optim.Adam(self.act.parameters(), lr=learning_rate) """Contribution of D3QN (Dueling Double DQN) There are not contribution of D3QN. Obviously, DoubleDQN is compatible with DuelingDQN. Any beginner can come up with this idea (D3QN) independently. """
[ "def", "__init__", "(", "self", ",", "net_dim", ",", "state_dim", ",", "action_dim", ",", "learning_rate", "=", "1e-4", ")", ":", "super", "(", ")", ".", "__init__", "(", "net_dim", ",", "state_dim", ",", "action_dim", ",", "learning_rate", ")", "self", ".", "explore_rate", "=", "0.25", "# epsilon-greedy, the rate of choosing random action", "self", ".", "act", "=", "QNetTwinDuel", "(", "net_dim", ",", "state_dim", ",", "action_dim", ")", ".", "to", "(", "self", ".", "device", ")", "self", ".", "act_target", "=", "deepcopy", "(", "self", ".", "act", ")", "self", ".", "criterion", "=", "torch", ".", "nn", ".", "SmoothL1Loss", "(", ")", "self", ".", "optimizer", "=", "torch", ".", "optim", ".", "Adam", "(", "self", ".", "act", ".", "parameters", "(", ")", ",", "lr", "=", "learning_rate", ")" ]
https://github.com/Yonv1943/Python/blob/ecce2153892093d7a13686e4cbfd6b323cb59de8/ElegantRL/Beta/elegantrl/AgentZoo/ElegantRL-PER/agent.py#L170-L183
ParmEd/ParmEd
cd763f2e83c98ba9e51676f6dbebf0eebfd5157e
parmed/unit/unit_operators.py
python
_unit_class_rdiv
(self, other)
Divide another object type by a Unit. Returns a new Quantity with a value of other and units of the inverse of self.
Divide another object type by a Unit.
[ "Divide", "another", "object", "type", "by", "a", "Unit", "." ]
def _unit_class_rdiv(self, other): """ Divide another object type by a Unit. Returns a new Quantity with a value of other and units of the inverse of self. """ if is_unit(other): raise NotImplementedError('programmer is surprised __rtruediv__ was called instead of __truediv__') else: # print "R scalar / unit" unit = pow(self, -1.0) value = other return Quantity(value, unit).reduce_unit(self)
[ "def", "_unit_class_rdiv", "(", "self", ",", "other", ")", ":", "if", "is_unit", "(", "other", ")", ":", "raise", "NotImplementedError", "(", "'programmer is surprised __rtruediv__ was called instead of __truediv__'", ")", "else", ":", "# print \"R scalar / unit\"", "unit", "=", "pow", "(", "self", ",", "-", "1.0", ")", "value", "=", "other", "return", "Quantity", "(", "value", ",", "unit", ")", ".", "reduce_unit", "(", "self", ")" ]
https://github.com/ParmEd/ParmEd/blob/cd763f2e83c98ba9e51676f6dbebf0eebfd5157e/parmed/unit/unit_operators.py#L61-L74
maqp/tfc
4bb13da1f19671e1e723db7e8a21be58847209af
src/transmitter/commands.py
python
propagate_setting_effects
(setting: str, queues: 'QueueDict', contact_list: 'ContactList', group_list: 'GroupList', settings: 'Settings', window: 'TxWindow' )
Propagate the effects of the setting.
Propagate the effects of the setting.
[ "Propagate", "the", "effects", "of", "the", "setting", "." ]
def propagate_setting_effects(setting: str, queues: 'QueueDict', contact_list: 'ContactList', group_list: 'GroupList', settings: 'Settings', window: 'TxWindow' ) -> None: """Propagate the effects of the setting.""" if setting == "max_number_of_contacts": contact_list.store_contacts() queues[KEY_MANAGEMENT_QUEUE].put((KDB_UPDATE_SIZE_HEADER, settings)) if setting in ['max_number_of_group_members', 'max_number_of_groups']: group_list.store_groups() if setting == 'traffic_masking': queues[SENDER_MODE_QUEUE].put(settings) queues[TRAFFIC_MASKING_QUEUE].put(settings.traffic_masking) window.deselect() if setting == 'log_file_masking': queues[LOGFILE_MASKING_QUEUE].put(settings.log_file_masking)
[ "def", "propagate_setting_effects", "(", "setting", ":", "str", ",", "queues", ":", "'QueueDict'", ",", "contact_list", ":", "'ContactList'", ",", "group_list", ":", "'GroupList'", ",", "settings", ":", "'Settings'", ",", "window", ":", "'TxWindow'", ")", "->", "None", ":", "if", "setting", "==", "\"max_number_of_contacts\"", ":", "contact_list", ".", "store_contacts", "(", ")", "queues", "[", "KEY_MANAGEMENT_QUEUE", "]", ".", "put", "(", "(", "KDB_UPDATE_SIZE_HEADER", ",", "settings", ")", ")", "if", "setting", "in", "[", "'max_number_of_group_members'", ",", "'max_number_of_groups'", "]", ":", "group_list", ".", "store_groups", "(", ")", "if", "setting", "==", "'traffic_masking'", ":", "queues", "[", "SENDER_MODE_QUEUE", "]", ".", "put", "(", "settings", ")", "queues", "[", "TRAFFIC_MASKING_QUEUE", "]", ".", "put", "(", "settings", ".", "traffic_masking", ")", "window", ".", "deselect", "(", ")", "if", "setting", "==", "'log_file_masking'", ":", "queues", "[", "LOGFILE_MASKING_QUEUE", "]", ".", "put", "(", "settings", ".", "log_file_masking", ")" ]
https://github.com/maqp/tfc/blob/4bb13da1f19671e1e723db7e8a21be58847209af/src/transmitter/commands.py#L647-L668
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_hxb2/lib/python3.5/site-packages/django/db/backends/base/schema.py
python
BaseDatabaseSchemaEditor._rename_field_sql
(self, table, old_field, new_field, new_type)
return self.sql_rename_column % { "table": self.quote_name(table), "old_column": self.quote_name(old_field.column), "new_column": self.quote_name(new_field.column), "type": new_type, }
[]
def _rename_field_sql(self, table, old_field, new_field, new_type): return self.sql_rename_column % { "table": self.quote_name(table), "old_column": self.quote_name(old_field.column), "new_column": self.quote_name(new_field.column), "type": new_type, }
[ "def", "_rename_field_sql", "(", "self", ",", "table", ",", "old_field", ",", "new_field", ",", "new_type", ")", ":", "return", "self", ".", "sql_rename_column", "%", "{", "\"table\"", ":", "self", ".", "quote_name", "(", "table", ")", ",", "\"old_column\"", ":", "self", ".", "quote_name", "(", "old_field", ".", "column", ")", ",", "\"new_column\"", ":", "self", ".", "quote_name", "(", "new_field", ".", "column", ")", ",", "\"type\"", ":", "new_type", ",", "}" ]
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_hxb2/lib/python3.5/site-packages/django/db/backends/base/schema.py#L883-L889
apache/tvm
6eb4ed813ebcdcd9558f0906a1870db8302ff1e0
python/tvm/relay/op/strategy/generic.py
python
wrap_compute_multibox_prior
(topi_compute)
return _compute_multibox_prior
Wrap multibox_prior compute
Wrap multibox_prior compute
[ "Wrap", "multibox_prior", "compute" ]
def wrap_compute_multibox_prior(topi_compute): """Wrap multibox_prior compute""" def _compute_multibox_prior(attrs, inputs, _): """Compute definition of multibox_prior""" sizes = get_float_tuple(attrs.sizes) ratios = get_float_tuple(attrs.ratios) steps = get_float_tuple(attrs.steps) offsets = get_float_tuple(attrs.offsets) clip = bool(get_const_int(attrs.clip)) return [topi_compute(inputs[0], sizes, ratios, steps, offsets, clip)] return _compute_multibox_prior
[ "def", "wrap_compute_multibox_prior", "(", "topi_compute", ")", ":", "def", "_compute_multibox_prior", "(", "attrs", ",", "inputs", ",", "_", ")", ":", "\"\"\"Compute definition of multibox_prior\"\"\"", "sizes", "=", "get_float_tuple", "(", "attrs", ".", "sizes", ")", "ratios", "=", "get_float_tuple", "(", "attrs", ".", "ratios", ")", "steps", "=", "get_float_tuple", "(", "attrs", ".", "steps", ")", "offsets", "=", "get_float_tuple", "(", "attrs", ".", "offsets", ")", "clip", "=", "bool", "(", "get_const_int", "(", "attrs", ".", "clip", ")", ")", "return", "[", "topi_compute", "(", "inputs", "[", "0", "]", ",", "sizes", ",", "ratios", ",", "steps", ",", "offsets", ",", "clip", ")", "]", "return", "_compute_multibox_prior" ]
https://github.com/apache/tvm/blob/6eb4ed813ebcdcd9558f0906a1870db8302ff1e0/python/tvm/relay/op/strategy/generic.py#L1107-L1119
OmkarPathak/pyresparser
36f1242fbc0637a6633371ca81cf1aea4fa7497e
pyresparser/resume_parser.py
python
ResumeParser.__init__
( self, resume, skills_file=None, custom_regex=None )
[]
def __init__( self, resume, skills_file=None, custom_regex=None ): nlp = spacy.load('en_core_web_sm') custom_nlp = spacy.load(os.path.dirname(os.path.abspath(__file__))) self.__skills_file = skills_file self.__custom_regex = custom_regex self.__matcher = Matcher(nlp.vocab) self.__details = { 'name': None, 'email': None, 'mobile_number': None, 'skills': None, 'college_name': None, 'degree': None, 'designation': None, 'experience': None, 'company_names': None, 'no_of_pages': None, 'total_experience': None, } self.__resume = resume if not isinstance(self.__resume, io.BytesIO): ext = os.path.splitext(self.__resume)[1].split('.')[1] else: ext = self.__resume.name.split('.')[1] self.__text_raw = utils.extract_text(self.__resume, '.' + ext) self.__text = ' '.join(self.__text_raw.split()) self.__nlp = nlp(self.__text) self.__custom_nlp = custom_nlp(self.__text_raw) self.__noun_chunks = list(self.__nlp.noun_chunks) self.__get_basic_details()
[ "def", "__init__", "(", "self", ",", "resume", ",", "skills_file", "=", "None", ",", "custom_regex", "=", "None", ")", ":", "nlp", "=", "spacy", ".", "load", "(", "'en_core_web_sm'", ")", "custom_nlp", "=", "spacy", ".", "load", "(", "os", ".", "path", ".", "dirname", "(", "os", ".", "path", ".", "abspath", "(", "__file__", ")", ")", ")", "self", ".", "__skills_file", "=", "skills_file", "self", ".", "__custom_regex", "=", "custom_regex", "self", ".", "__matcher", "=", "Matcher", "(", "nlp", ".", "vocab", ")", "self", ".", "__details", "=", "{", "'name'", ":", "None", ",", "'email'", ":", "None", ",", "'mobile_number'", ":", "None", ",", "'skills'", ":", "None", ",", "'college_name'", ":", "None", ",", "'degree'", ":", "None", ",", "'designation'", ":", "None", ",", "'experience'", ":", "None", ",", "'company_names'", ":", "None", ",", "'no_of_pages'", ":", "None", ",", "'total_experience'", ":", "None", ",", "}", "self", ".", "__resume", "=", "resume", "if", "not", "isinstance", "(", "self", ".", "__resume", ",", "io", ".", "BytesIO", ")", ":", "ext", "=", "os", ".", "path", ".", "splitext", "(", "self", ".", "__resume", ")", "[", "1", "]", ".", "split", "(", "'.'", ")", "[", "1", "]", "else", ":", "ext", "=", "self", ".", "__resume", ".", "name", ".", "split", "(", "'.'", ")", "[", "1", "]", "self", ".", "__text_raw", "=", "utils", ".", "extract_text", "(", "self", ".", "__resume", ",", "'.'", "+", "ext", ")", "self", ".", "__text", "=", "' '", ".", "join", "(", "self", ".", "__text_raw", ".", "split", "(", ")", ")", "self", ".", "__nlp", "=", "nlp", "(", "self", ".", "__text", ")", "self", ".", "__custom_nlp", "=", "custom_nlp", "(", "self", ".", "__text_raw", ")", "self", ".", "__noun_chunks", "=", "list", "(", "self", ".", "__nlp", ".", "noun_chunks", ")", "self", ".", "__get_basic_details", "(", ")" ]
https://github.com/OmkarPathak/pyresparser/blob/36f1242fbc0637a6633371ca81cf1aea4fa7497e/pyresparser/resume_parser.py#L14-L48
Jenyay/outwiker
50530cf7b3f71480bb075b2829bc0669773b835b
plugins/markdown/markdown/markdown_plugin_libs/pygments/formatters/img.py
python
FontManager.get_char_size
(self)
return self.fonts['NORMAL'].getsize('M')
Get the character size.
Get the character size.
[ "Get", "the", "character", "size", "." ]
def get_char_size(self): """ Get the character size. """ return self.fonts['NORMAL'].getsize('M')
[ "def", "get_char_size", "(", "self", ")", ":", "return", "self", ".", "fonts", "[", "'NORMAL'", "]", ".", "getsize", "(", "'M'", ")" ]
https://github.com/Jenyay/outwiker/blob/50530cf7b3f71480bb075b2829bc0669773b835b/plugins/markdown/markdown/markdown_plugin_libs/pygments/formatters/img.py#L205-L209
trakt/Plex-Trakt-Scrobbler
aeb0bfbe62fad4b06c164f1b95581da7f35dce0b
Trakttv.bundle/Contents/Libraries/Shared/sortedcontainers/sortedlist.py
python
recursive_repr
(func)
return wrapper
Decorator to prevent infinite repr recursion.
Decorator to prevent infinite repr recursion.
[ "Decorator", "to", "prevent", "infinite", "repr", "recursion", "." ]
def recursive_repr(func): """Decorator to prevent infinite repr recursion.""" repr_running = set() @wraps(func) def wrapper(self): "Return ellipsis on recursive re-entry to function." key = id(self), get_ident() if key in repr_running: return '...' repr_running.add(key) try: return func(self) finally: repr_running.discard(key) return wrapper
[ "def", "recursive_repr", "(", "func", ")", ":", "repr_running", "=", "set", "(", ")", "@", "wraps", "(", "func", ")", "def", "wrapper", "(", "self", ")", ":", "\"Return ellipsis on recursive re-entry to function.\"", "key", "=", "id", "(", "self", ")", ",", "get_ident", "(", ")", "if", "key", "in", "repr_running", ":", "return", "'...'", "repr_running", ".", "add", "(", "key", ")", "try", ":", "return", "func", "(", "self", ")", "finally", ":", "repr_running", ".", "discard", "(", "key", ")", "return", "wrapper" ]
https://github.com/trakt/Plex-Trakt-Scrobbler/blob/aeb0bfbe62fad4b06c164f1b95581da7f35dce0b/Trakttv.bundle/Contents/Libraries/Shared/sortedcontainers/sortedlist.py#L31-L50
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/lib/python2.7/site-packages/babel/support.py
python
LazyProxy.__rmod__
(self, other)
return other % self.value
[]
def __rmod__(self, other): return other % self.value
[ "def", "__rmod__", "(", "self", ",", "other", ")", ":", "return", "other", "%", "self", ".", "value" ]
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/site-packages/babel/support.py#L218-L219
dpressel/mead-baseline
9987e6b37fa6525a4ddc187c305e292a718f59a9
layers/eight_mile/conlleval.py
python
main
()
Use as a cli tool like conlleval.pl
Use as a cli tool like conlleval.pl
[ "Use", "as", "a", "cli", "tool", "like", "conlleval", ".", "pl" ]
def main(): """Use as a cli tool like conlleval.pl""" usage = "usage: %(prog)s [--span_type {bio,iobes,iob}] [-d delimiterTag] [-v] < file" parser = argparse.ArgumentParser( description="Calculate Span level F1 from the CoNLL-2000 shared task.", usage=usage ) parser.add_argument( "--span_type", default="iobes", choices={"iobes", "iob", "bio"}, help="What tag annotation scheme is this file using.", ) parser.add_argument("--delimiterTag", "-d", help="The separator between items in the file.") parser.add_argument( "--verbose", "-v", action="store_true", help="Output warnings when there is an illegal transition." ) args = parser.parse_args() golds, preds = _read_conll_file(sys.stdin, args.delimiterTag) acc, tokens = _get_accuracy(golds, preds) golds, preds = _get_entities(golds, preds, args.span_type, args.verbose) metrics = per_entity_f1(golds, preds) metrics["acc"] = acc metrics["tokens"] = tokens print(conlleval_output(metrics))
[ "def", "main", "(", ")", ":", "usage", "=", "\"usage: %(prog)s [--span_type {bio,iobes,iob}] [-d delimiterTag] [-v] < file\"", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "\"Calculate Span level F1 from the CoNLL-2000 shared task.\"", ",", "usage", "=", "usage", ")", "parser", ".", "add_argument", "(", "\"--span_type\"", ",", "default", "=", "\"iobes\"", ",", "choices", "=", "{", "\"iobes\"", ",", "\"iob\"", ",", "\"bio\"", "}", ",", "help", "=", "\"What tag annotation scheme is this file using.\"", ",", ")", "parser", ".", "add_argument", "(", "\"--delimiterTag\"", ",", "\"-d\"", ",", "help", "=", "\"The separator between items in the file.\"", ")", "parser", ".", "add_argument", "(", "\"--verbose\"", ",", "\"-v\"", ",", "action", "=", "\"store_true\"", ",", "help", "=", "\"Output warnings when there is an illegal transition.\"", ")", "args", "=", "parser", ".", "parse_args", "(", ")", "golds", ",", "preds", "=", "_read_conll_file", "(", "sys", ".", "stdin", ",", "args", ".", "delimiterTag", ")", "acc", ",", "tokens", "=", "_get_accuracy", "(", "golds", ",", "preds", ")", "golds", ",", "preds", "=", "_get_entities", "(", "golds", ",", "preds", ",", "args", ".", "span_type", ",", "args", ".", "verbose", ")", "metrics", "=", "per_entity_f1", "(", "golds", ",", "preds", ")", "metrics", "[", "\"acc\"", "]", "=", "acc", "metrics", "[", "\"tokens\"", "]", "=", "tokens", "print", "(", "conlleval_output", "(", "metrics", ")", ")" ]
https://github.com/dpressel/mead-baseline/blob/9987e6b37fa6525a4ddc187c305e292a718f59a9/layers/eight_mile/conlleval.py#L87-L111
raveberry/raveberry
df0186c94b238b57de86d3fd5c595dcd08a7c708
backend/core/musiq/spotify_web.py
python
OAuthClient.__init__
( self, base_url, refresh_url, client_id=None, client_secret=None, proxy_config=None, expiry_margin=60, timeout=10, retries=3, retry_statuses=(500, 502, 503, 429), )
[]
def __init__( self, base_url, refresh_url, client_id=None, client_secret=None, proxy_config=None, expiry_margin=60, timeout=10, retries=3, retry_statuses=(500, 502, 503, 429), ): if client_id and client_secret: self._auth = (client_id, client_secret) else: self._auth = None self._base_url = base_url self._refresh_url = refresh_url self._margin = expiry_margin self._expires = 0 self._authorization_failed = False self._timeout = timeout self._number_of_retries = retries self._retry_statuses = retry_statuses self._backoff_factor = 0.5 self._headers = {"Content-Type": "application/json"} self._session = get_requests_session(proxy_config or {})
[ "def", "__init__", "(", "self", ",", "base_url", ",", "refresh_url", ",", "client_id", "=", "None", ",", "client_secret", "=", "None", ",", "proxy_config", "=", "None", ",", "expiry_margin", "=", "60", ",", "timeout", "=", "10", ",", "retries", "=", "3", ",", "retry_statuses", "=", "(", "500", ",", "502", ",", "503", ",", "429", ")", ",", ")", ":", "if", "client_id", "and", "client_secret", ":", "self", ".", "_auth", "=", "(", "client_id", ",", "client_secret", ")", "else", ":", "self", ".", "_auth", "=", "None", "self", ".", "_base_url", "=", "base_url", "self", ".", "_refresh_url", "=", "refresh_url", "self", ".", "_margin", "=", "expiry_margin", "self", ".", "_expires", "=", "0", "self", ".", "_authorization_failed", "=", "False", "self", ".", "_timeout", "=", "timeout", "self", ".", "_number_of_retries", "=", "retries", "self", ".", "_retry_statuses", "=", "retry_statuses", "self", ".", "_backoff_factor", "=", "0.5", "self", ".", "_headers", "=", "{", "\"Content-Type\"", ":", "\"application/json\"", "}", "self", ".", "_session", "=", "get_requests_session", "(", "proxy_config", "or", "{", "}", ")" ]
https://github.com/raveberry/raveberry/blob/df0186c94b238b57de86d3fd5c595dcd08a7c708/backend/core/musiq/spotify_web.py#L52-L83
beetbox/beets
2fea53c34dd505ba391cb345424e0613901c8025
beets/importer.py
python
ArchiveImportTask.extract
(self)
Extracts the archive to a temporary directory and sets `toppath` to that directory.
Extracts the archive to a temporary directory and sets `toppath` to that directory.
[ "Extracts", "the", "archive", "to", "a", "temporary", "directory", "and", "sets", "toppath", "to", "that", "directory", "." ]
def extract(self): """Extracts the archive to a temporary directory and sets `toppath` to that directory. """ for path_test, handler_class in self.handlers(): if path_test(util.py3_path(self.toppath)): break extract_to = mkdtemp() archive = handler_class(util.py3_path(self.toppath), mode='r') try: archive.extractall(extract_to) finally: archive.close() self.extracted = True self.toppath = extract_to
[ "def", "extract", "(", "self", ")", ":", "for", "path_test", ",", "handler_class", "in", "self", ".", "handlers", "(", ")", ":", "if", "path_test", "(", "util", ".", "py3_path", "(", "self", ".", "toppath", ")", ")", ":", "break", "extract_to", "=", "mkdtemp", "(", ")", "archive", "=", "handler_class", "(", "util", ".", "py3_path", "(", "self", ".", "toppath", ")", ",", "mode", "=", "'r'", ")", "try", ":", "archive", ".", "extractall", "(", "extract_to", ")", "finally", ":", "archive", ".", "close", "(", ")", "self", ".", "extracted", "=", "True", "self", ".", "toppath", "=", "extract_to" ]
https://github.com/beetbox/beets/blob/2fea53c34dd505ba391cb345424e0613901c8025/beets/importer.py#L1081-L1096
kivy/plyer
7a71707bdf99979cdacf2240d823aefa13d18f00
plyer/platforms/linux/cpu.py
python
instance
()
return CPU()
Instance for facade proxy.
Instance for facade proxy.
[ "Instance", "for", "facade", "proxy", "." ]
def instance(): ''' Instance for facade proxy. ''' import sys if whereis_exe('nproc'): return LinuxCPU() sys.stderr.write("nproc not found.") return CPU()
[ "def", "instance", "(", ")", ":", "import", "sys", "if", "whereis_exe", "(", "'nproc'", ")", ":", "return", "LinuxCPU", "(", ")", "sys", ".", "stderr", ".", "write", "(", "\"nproc not found.\"", ")", "return", "CPU", "(", ")" ]
https://github.com/kivy/plyer/blob/7a71707bdf99979cdacf2240d823aefa13d18f00/plyer/platforms/linux/cpu.py#L108-L116
sloria/textblob-aptagger
fb98bbd16a83650cab4819c4b89f0973e60fb3fe
textblob_aptagger/_perceptron.py
python
AveragedPerceptron.load
(self, path)
return None
Load the pickled model weights.
Load the pickled model weights.
[ "Load", "the", "pickled", "model", "weights", "." ]
def load(self, path): '''Load the pickled model weights.''' self.weights = pickle.load(open(path)) return None
[ "def", "load", "(", "self", ",", "path", ")", ":", "self", ".", "weights", "=", "pickle", ".", "load", "(", "open", "(", "path", ")", ")", "return", "None" ]
https://github.com/sloria/textblob-aptagger/blob/fb98bbd16a83650cab4819c4b89f0973e60fb3fe/textblob_aptagger/_perceptron.py#L79-L82
holzschu/Carnets
44effb10ddfc6aa5c8b0687582a724ba82c6b547
Library/lib/python3.7/site-packages/pandas-0.24.2-py3.7-macosx-10.9-x86_64.egg/pandas/io/pytables.py
python
HDFStore.remove
(self, key, where=None, start=None, stop=None)
Remove pandas object partially by specifying the where condition Parameters ---------- key : string Node to remove or delete rows from where : list of Term (or convertible) objects, optional start : integer (defaults to None), row number to start selection stop : integer (defaults to None), row number to stop selection Returns ------- number of rows removed (or None if not a Table) Exceptions ---------- raises KeyError if key is not a valid store
Remove pandas object partially by specifying the where condition
[ "Remove", "pandas", "object", "partially", "by", "specifying", "the", "where", "condition" ]
def remove(self, key, where=None, start=None, stop=None): """ Remove pandas object partially by specifying the where condition Parameters ---------- key : string Node to remove or delete rows from where : list of Term (or convertible) objects, optional start : integer (defaults to None), row number to start selection stop : integer (defaults to None), row number to stop selection Returns ------- number of rows removed (or None if not a Table) Exceptions ---------- raises KeyError if key is not a valid store """ where = _ensure_term(where, scope_level=1) try: s = self.get_storer(key) except KeyError: # the key is not a valid store, re-raising KeyError raise except Exception: if where is not None: raise ValueError( "trying to remove a node with a non-None where clause!") # we are actually trying to remove a node (with children) s = self.get_node(key) if s is not None: s._f_remove(recursive=True) return None # remove the node if com._all_none(where, start, stop): s.group._f_remove(recursive=True) # delete from the table else: if not s.is_table: raise ValueError( 'can only remove with where on objects written as tables') return s.delete(where=where, start=start, stop=stop)
[ "def", "remove", "(", "self", ",", "key", ",", "where", "=", "None", ",", "start", "=", "None", ",", "stop", "=", "None", ")", ":", "where", "=", "_ensure_term", "(", "where", ",", "scope_level", "=", "1", ")", "try", ":", "s", "=", "self", ".", "get_storer", "(", "key", ")", "except", "KeyError", ":", "# the key is not a valid store, re-raising KeyError", "raise", "except", "Exception", ":", "if", "where", "is", "not", "None", ":", "raise", "ValueError", "(", "\"trying to remove a node with a non-None where clause!\"", ")", "# we are actually trying to remove a node (with children)", "s", "=", "self", ".", "get_node", "(", "key", ")", "if", "s", "is", "not", "None", ":", "s", ".", "_f_remove", "(", "recursive", "=", "True", ")", "return", "None", "# remove the node", "if", "com", ".", "_all_none", "(", "where", ",", "start", ",", "stop", ")", ":", "s", ".", "group", ".", "_f_remove", "(", "recursive", "=", "True", ")", "# delete from the table", "else", ":", "if", "not", "s", ".", "is_table", ":", "raise", "ValueError", "(", "'can only remove with where on objects written as tables'", ")", "return", "s", ".", "delete", "(", "where", "=", "where", ",", "start", "=", "start", ",", "stop", "=", "stop", ")" ]
https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/pandas-0.24.2-py3.7-macosx-10.9-x86_64.egg/pandas/io/pytables.py#L891-L939
dmlc/gluon-cv
709bc139919c02f7454cb411311048be188cde64
scripts/datasets/ilsvrc_det.py
python
par_crop
(args)
Dataset curation,crop data and transform the format of a label
Dataset curation,crop data and transform the format of a label
[ "Dataset", "curation", "crop", "data", "and", "transform", "the", "format", "of", "a", "label" ]
def par_crop(args): """ Dataset curation,crop data and transform the format of a label """ crop_path = os.path.join(args.download_dir, './crop{:d}'.format(args.instance_size)) if not os.path.isdir(crop_path): makedirs(crop_path) VID_base_path = os.path.join(args.download_dir, './ILSVRC') ann_base_path = os.path.join(VID_base_path, 'Annotations/DET/train/') sub_sets = ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i') for sub_set in sub_sets: sub_set_base_path = os.path.join(ann_base_path, sub_set) if 'a' == sub_set: xmls = sorted(glob.glob(os.path.join(sub_set_base_path, '*', '*.xml'))) else: xmls = sorted(glob.glob(os.path.join(sub_set_base_path, '*.xml'))) n_imgs = len(xmls) sub_set_crop_path = os.path.join(crop_path, sub_set) with futures.ProcessPoolExecutor(max_workers=args.num_threads) as executor: fs = [executor.submit(crop_xml, args, xml, sub_set_crop_path, args.instance_size) for xml in xmls] for i, f in enumerate(futures.as_completed(fs)): printProgress(i, n_imgs, prefix=sub_set, suffix='Done ', barLength=80)
[ "def", "par_crop", "(", "args", ")", ":", "crop_path", "=", "os", ".", "path", ".", "join", "(", "args", ".", "download_dir", ",", "'./crop{:d}'", ".", "format", "(", "args", ".", "instance_size", ")", ")", "if", "not", "os", ".", "path", ".", "isdir", "(", "crop_path", ")", ":", "makedirs", "(", "crop_path", ")", "VID_base_path", "=", "os", ".", "path", ".", "join", "(", "args", ".", "download_dir", ",", "'./ILSVRC'", ")", "ann_base_path", "=", "os", ".", "path", ".", "join", "(", "VID_base_path", ",", "'Annotations/DET/train/'", ")", "sub_sets", "=", "(", "'a'", ",", "'b'", ",", "'c'", ",", "'d'", ",", "'e'", ",", "'f'", ",", "'g'", ",", "'h'", ",", "'i'", ")", "for", "sub_set", "in", "sub_sets", ":", "sub_set_base_path", "=", "os", ".", "path", ".", "join", "(", "ann_base_path", ",", "sub_set", ")", "if", "'a'", "==", "sub_set", ":", "xmls", "=", "sorted", "(", "glob", ".", "glob", "(", "os", ".", "path", ".", "join", "(", "sub_set_base_path", ",", "'*'", ",", "'*.xml'", ")", ")", ")", "else", ":", "xmls", "=", "sorted", "(", "glob", ".", "glob", "(", "os", ".", "path", ".", "join", "(", "sub_set_base_path", ",", "'*.xml'", ")", ")", ")", "n_imgs", "=", "len", "(", "xmls", ")", "sub_set_crop_path", "=", "os", ".", "path", ".", "join", "(", "crop_path", ",", "sub_set", ")", "with", "futures", ".", "ProcessPoolExecutor", "(", "max_workers", "=", "args", ".", "num_threads", ")", "as", "executor", ":", "fs", "=", "[", "executor", ".", "submit", "(", "crop_xml", ",", "args", ",", "xml", ",", "sub_set_crop_path", ",", "args", ".", "instance_size", ")", "for", "xml", "in", "xmls", "]", "for", "i", ",", "f", "in", "enumerate", "(", "futures", ".", "as_completed", "(", "fs", ")", ")", ":", "printProgress", "(", "i", ",", "n_imgs", ",", "prefix", "=", "sub_set", ",", "suffix", "=", "'Done '", ",", "barLength", "=", "80", ")" ]
https://github.com/dmlc/gluon-cv/blob/709bc139919c02f7454cb411311048be188cde64/scripts/datasets/ilsvrc_det.py#L77-L97
mrJean1/PyGeodesy
7da5ca71aa3edb7bc49e219e0b8190686e1a7965
pygeodesy/sphericalNvector.py
python
perimeterOf
(points, closed=False, radius=R_M)
return r if radius is None else (Radius(radius) * r)
Compute the perimeter of a (spherical) polygon (with great circle arcs joining consecutive points). @arg points: The polygon points (L{LatLon}[]). @kwarg closed: Optionally, close the polygon (C{bool}). @kwarg radius: Mean earth radius (C{meter}) or C{None}. @return: Polygon perimeter (C{meter}, same units as B{C{radius}} or C{radians} if B{C{radius}} is C{None}). @raise PointsError: Insufficient number of B{C{points}}. @raise TypeError: Some B{C{points}} are not L{LatLon}. @see: Functions L{pygeodesy.perimeterOf}, L{sphericalTrigonometry.perimeterOf} and L{ellipsoidalKarney.perimeterOf}.
Compute the perimeter of a (spherical) polygon (with great circle arcs joining consecutive points).
[ "Compute", "the", "perimeter", "of", "a", "(", "spherical", ")", "polygon", "(", "with", "great", "circle", "arcs", "joining", "consecutive", "points", ")", "." ]
def perimeterOf(points, closed=False, radius=R_M): '''Compute the perimeter of a (spherical) polygon (with great circle arcs joining consecutive points). @arg points: The polygon points (L{LatLon}[]). @kwarg closed: Optionally, close the polygon (C{bool}). @kwarg radius: Mean earth radius (C{meter}) or C{None}. @return: Polygon perimeter (C{meter}, same units as B{C{radius}} or C{radians} if B{C{radius}} is C{None}). @raise PointsError: Insufficient number of B{C{points}}. @raise TypeError: Some B{C{points}} are not L{LatLon}. @see: Functions L{pygeodesy.perimeterOf}, L{sphericalTrigonometry.perimeterOf} and L{ellipsoidalKarney.perimeterOf}. ''' def _rads(Ps, closed): # angular edge lengths in radians v1 = Ps[0]._N_vector for p in Ps.iterate(closed=closed): v2 = p._N_vector yield v1.angleTo(v2) v1 = v2 r = fsum(_rads(_Nvll.PointsIter(points, loop=1), closed)) return r if radius is None else (Radius(radius) * r)
[ "def", "perimeterOf", "(", "points", ",", "closed", "=", "False", ",", "radius", "=", "R_M", ")", ":", "def", "_rads", "(", "Ps", ",", "closed", ")", ":", "# angular edge lengths in radians", "v1", "=", "Ps", "[", "0", "]", ".", "_N_vector", "for", "p", "in", "Ps", ".", "iterate", "(", "closed", "=", "closed", ")", ":", "v2", "=", "p", ".", "_N_vector", "yield", "v1", ".", "angleTo", "(", "v2", ")", "v1", "=", "v2", "r", "=", "fsum", "(", "_rads", "(", "_Nvll", ".", "PointsIter", "(", "points", ",", "loop", "=", "1", ")", ",", "closed", ")", ")", "return", "r", "if", "radius", "is", "None", "else", "(", "Radius", "(", "radius", ")", "*", "r", ")" ]
https://github.com/mrJean1/PyGeodesy/blob/7da5ca71aa3edb7bc49e219e0b8190686e1a7965/pygeodesy/sphericalNvector.py#L1024-L1050
lovelylain/pyctp
fd304de4b50c4ddc31a4190b1caaeb5dec66bc5d
example/ctp/futures/ApiStruct.py
python
QryCFMMCTradingAccountKey.__init__
(self, BrokerID='', InvestorID='')
[]
def __init__(self, BrokerID='', InvestorID=''): self.BrokerID = '' #经纪公司代码, char[11] self.InvestorID = ''
[ "def", "__init__", "(", "self", ",", "BrokerID", "=", "''", ",", "InvestorID", "=", "''", ")", ":", "self", ".", "BrokerID", "=", "''", "#经纪公司代码, char[11]", "self", ".", "InvestorID", "=", "''" ]
https://github.com/lovelylain/pyctp/blob/fd304de4b50c4ddc31a4190b1caaeb5dec66bc5d/example/ctp/futures/ApiStruct.py#L4712-L4714
fabioz/PyDev.Debugger
0f8c02a010fe5690405da1dd30ed72326191ce63
third_party/pep8/autopep8.py
python
_get_indentword
(source)
return indent_word
Return indentation type.
Return indentation type.
[ "Return", "indentation", "type", "." ]
def _get_indentword(source): """Return indentation type.""" indent_word = ' ' # Default in case source has no indentation try: for t in generate_tokens(source): if t[0] == token.INDENT: indent_word = t[1] break except (SyntaxError, tokenize.TokenError): pass return indent_word
[ "def", "_get_indentword", "(", "source", ")", ":", "indent_word", "=", "' '", "# Default in case source has no indentation", "try", ":", "for", "t", "in", "generate_tokens", "(", "source", ")", ":", "if", "t", "[", "0", "]", "==", "token", ".", "INDENT", ":", "indent_word", "=", "t", "[", "1", "]", "break", "except", "(", "SyntaxError", ",", "tokenize", ".", "TokenError", ")", ":", "pass", "return", "indent_word" ]
https://github.com/fabioz/PyDev.Debugger/blob/0f8c02a010fe5690405da1dd30ed72326191ce63/third_party/pep8/autopep8.py#L1417-L1427
openfisca/openfisca-france
207a58191be6830716693f94d37846f1e5037b51
openfisca_france/model/prelevements_obligatoires/isf.py
python
isf_inv_pme.formula_2008
(foyer_fiscal, period, parameters)
return holdings + fip + fcpi + inv_dir_soc
Réductions pour investissements dans les PME à partir de 2008!
Réductions pour investissements dans les PME à partir de 2008!
[ "Réductions", "pour", "investissements", "dans", "les", "PME", "à", "partir", "de", "2008!" ]
def formula_2008(foyer_fiscal, period, parameters): ''' Réductions pour investissements dans les PME à partir de 2008! ''' b2mt = foyer_fiscal('b2mt', period) b2ne = foyer_fiscal('b2ne', period) b2mv = foyer_fiscal('b2mv', period) b2nf = foyer_fiscal('b2nf', period) b2mx = foyer_fiscal('b2mx', period) b2na = foyer_fiscal('b2na', period) P = parameters(period).taxation_capital.isf_ifi.reduc_invest_don inv_dir_soc = b2mt * P.taux_don_interet_general + b2ne * P.taux_invest_direct_soc_holding holdings = b2mv * P.taux_don_interet_general + b2nf * P.taux_invest_direct_soc_holding fip = b2mx * P.taux_invest_direct_soc_holding fcpi = b2na * P.taux_invest_direct_soc_holding return holdings + fip + fcpi + inv_dir_soc
[ "def", "formula_2008", "(", "foyer_fiscal", ",", "period", ",", "parameters", ")", ":", "b2mt", "=", "foyer_fiscal", "(", "'b2mt'", ",", "period", ")", "b2ne", "=", "foyer_fiscal", "(", "'b2ne'", ",", "period", ")", "b2mv", "=", "foyer_fiscal", "(", "'b2mv'", ",", "period", ")", "b2nf", "=", "foyer_fiscal", "(", "'b2nf'", ",", "period", ")", "b2mx", "=", "foyer_fiscal", "(", "'b2mx'", ",", "period", ")", "b2na", "=", "foyer_fiscal", "(", "'b2na'", ",", "period", ")", "P", "=", "parameters", "(", "period", ")", ".", "taxation_capital", ".", "isf_ifi", ".", "reduc_invest_don", "inv_dir_soc", "=", "b2mt", "*", "P", ".", "taux_don_interet_general", "+", "b2ne", "*", "P", ".", "taux_invest_direct_soc_holding", "holdings", "=", "b2mv", "*", "P", ".", "taux_don_interet_general", "+", "b2nf", "*", "P", ".", "taux_invest_direct_soc_holding", "fip", "=", "b2mx", "*", "P", ".", "taux_invest_direct_soc_holding", "fcpi", "=", "b2na", "*", "P", ".", "taux_invest_direct_soc_holding", "return", "holdings", "+", "fip", "+", "fcpi", "+", "inv_dir_soc" ]
https://github.com/openfisca/openfisca-france/blob/207a58191be6830716693f94d37846f1e5037b51/openfisca_france/model/prelevements_obligatoires/isf.py#L395-L413
davidemms/OrthoFinder
d92c016ccb17be39787614018694844a2c673173
scripts_of/tree.py
python
TreeNode.is_leaf
(self)
return len(self.children) == 0
Return True if current node is a leaf.
Return True if current node is a leaf.
[ "Return", "True", "if", "current", "node", "is", "a", "leaf", "." ]
def is_leaf(self): """ Return True if current node is a leaf. """ return len(self.children) == 0
[ "def", "is_leaf", "(", "self", ")", ":", "return", "len", "(", "self", ".", "children", ")", "==", "0" ]
https://github.com/davidemms/OrthoFinder/blob/d92c016ccb17be39787614018694844a2c673173/scripts_of/tree.py#L944-L948
Tautulli/Tautulli
2410eb33805aaac4bd1c5dad0f71e4f15afaf742
lib/idna/uts46data.py
python
_seg_63
()
return [ (0x1D4FC, 'M', 's'), (0x1D4FD, 'M', 't'), (0x1D4FE, 'M', 'u'), (0x1D4FF, 'M', 'v'), (0x1D500, 'M', 'w'), (0x1D501, 'M', 'x'), (0x1D502, 'M', 'y'), (0x1D503, 'M', 'z'), (0x1D504, 'M', 'a'), (0x1D505, 'M', 'b'), (0x1D506, 'X'), (0x1D507, 'M', 'd'), (0x1D508, 'M', 'e'), (0x1D509, 'M', 'f'), (0x1D50A, 'M', 'g'), (0x1D50B, 'X'), (0x1D50D, 'M', 'j'), (0x1D50E, 'M', 'k'), (0x1D50F, 'M', 'l'), (0x1D510, 'M', 'm'), (0x1D511, 'M', 'n'), (0x1D512, 'M', 'o'), (0x1D513, 'M', 'p'), (0x1D514, 'M', 'q'), (0x1D515, 'X'), (0x1D516, 'M', 's'), (0x1D517, 'M', 't'), (0x1D518, 'M', 'u'), (0x1D519, 'M', 'v'), (0x1D51A, 'M', 'w'), (0x1D51B, 'M', 'x'), (0x1D51C, 'M', 'y'), (0x1D51D, 'X'), (0x1D51E, 'M', 'a'), (0x1D51F, 'M', 'b'), (0x1D520, 'M', 'c'), (0x1D521, 'M', 'd'), (0x1D522, 'M', 'e'), (0x1D523, 'M', 'f'), (0x1D524, 'M', 'g'), (0x1D525, 'M', 'h'), (0x1D526, 'M', 'i'), (0x1D527, 'M', 'j'), (0x1D528, 'M', 'k'), (0x1D529, 'M', 'l'), (0x1D52A, 'M', 'm'), (0x1D52B, 'M', 'n'), (0x1D52C, 'M', 'o'), (0x1D52D, 'M', 'p'), (0x1D52E, 'M', 'q'), (0x1D52F, 'M', 'r'), (0x1D530, 'M', 's'), (0x1D531, 'M', 't'), (0x1D532, 'M', 'u'), (0x1D533, 'M', 'v'), (0x1D534, 'M', 'w'), (0x1D535, 'M', 'x'), (0x1D536, 'M', 'y'), (0x1D537, 'M', 'z'), (0x1D538, 'M', 'a'), (0x1D539, 'M', 'b'), (0x1D53A, 'X'), (0x1D53B, 'M', 'd'), (0x1D53C, 'M', 'e'), (0x1D53D, 'M', 'f'), (0x1D53E, 'M', 'g'), (0x1D53F, 'X'), (0x1D540, 'M', 'i'), (0x1D541, 'M', 'j'), (0x1D542, 'M', 'k'), (0x1D543, 'M', 'l'), (0x1D544, 'M', 'm'), (0x1D545, 'X'), (0x1D546, 'M', 'o'), (0x1D547, 'X'), (0x1D54A, 'M', 's'), (0x1D54B, 'M', 't'), (0x1D54C, 'M', 'u'), (0x1D54D, 'M', 'v'), (0x1D54E, 'M', 'w'), (0x1D54F, 'M', 'x'), (0x1D550, 'M', 'y'), (0x1D551, 'X'), (0x1D552, 'M', 'a'), (0x1D553, 'M', 'b'), (0x1D554, 'M', 'c'), (0x1D555, 'M', 'd'), (0x1D556, 'M', 'e'), (0x1D557, 'M', 'f'), (0x1D558, 'M', 'g'), (0x1D559, 'M', 'h'), (0x1D55A, 'M', 'i'), (0x1D55B, 'M', 'j'), (0x1D55C, 'M', 'k'), (0x1D55D, 'M', 'l'), (0x1D55E, 'M', 'm'), (0x1D55F, 'M', 'n'), (0x1D560, 'M', 'o'), (0x1D561, 'M', 'p'), (0x1D562, 'M', 'q'), ]
[]
def _seg_63() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0x1D4FC, 'M', 's'), (0x1D4FD, 'M', 't'), (0x1D4FE, 'M', 'u'), (0x1D4FF, 'M', 'v'), (0x1D500, 'M', 'w'), (0x1D501, 'M', 'x'), (0x1D502, 'M', 'y'), (0x1D503, 'M', 'z'), (0x1D504, 'M', 'a'), (0x1D505, 'M', 'b'), (0x1D506, 'X'), (0x1D507, 'M', 'd'), (0x1D508, 'M', 'e'), (0x1D509, 'M', 'f'), (0x1D50A, 'M', 'g'), (0x1D50B, 'X'), (0x1D50D, 'M', 'j'), (0x1D50E, 'M', 'k'), (0x1D50F, 'M', 'l'), (0x1D510, 'M', 'm'), (0x1D511, 'M', 'n'), (0x1D512, 'M', 'o'), (0x1D513, 'M', 'p'), (0x1D514, 'M', 'q'), (0x1D515, 'X'), (0x1D516, 'M', 's'), (0x1D517, 'M', 't'), (0x1D518, 'M', 'u'), (0x1D519, 'M', 'v'), (0x1D51A, 'M', 'w'), (0x1D51B, 'M', 'x'), (0x1D51C, 'M', 'y'), (0x1D51D, 'X'), (0x1D51E, 'M', 'a'), (0x1D51F, 'M', 'b'), (0x1D520, 'M', 'c'), (0x1D521, 'M', 'd'), (0x1D522, 'M', 'e'), (0x1D523, 'M', 'f'), (0x1D524, 'M', 'g'), (0x1D525, 'M', 'h'), (0x1D526, 'M', 'i'), (0x1D527, 'M', 'j'), (0x1D528, 'M', 'k'), (0x1D529, 'M', 'l'), (0x1D52A, 'M', 'm'), (0x1D52B, 'M', 'n'), (0x1D52C, 'M', 'o'), (0x1D52D, 'M', 'p'), (0x1D52E, 'M', 'q'), (0x1D52F, 'M', 'r'), (0x1D530, 'M', 's'), (0x1D531, 'M', 't'), (0x1D532, 'M', 'u'), (0x1D533, 'M', 'v'), (0x1D534, 'M', 'w'), (0x1D535, 'M', 'x'), (0x1D536, 'M', 'y'), (0x1D537, 'M', 'z'), (0x1D538, 'M', 'a'), (0x1D539, 'M', 'b'), (0x1D53A, 'X'), (0x1D53B, 'M', 'd'), (0x1D53C, 'M', 'e'), (0x1D53D, 'M', 'f'), (0x1D53E, 'M', 'g'), (0x1D53F, 'X'), (0x1D540, 'M', 'i'), (0x1D541, 'M', 'j'), (0x1D542, 'M', 'k'), (0x1D543, 'M', 'l'), (0x1D544, 'M', 'm'), (0x1D545, 'X'), (0x1D546, 'M', 'o'), (0x1D547, 'X'), (0x1D54A, 'M', 's'), (0x1D54B, 'M', 't'), (0x1D54C, 'M', 'u'), (0x1D54D, 'M', 'v'), (0x1D54E, 'M', 'w'), (0x1D54F, 'M', 'x'), (0x1D550, 'M', 'y'), (0x1D551, 'X'), (0x1D552, 'M', 'a'), (0x1D553, 'M', 'b'), (0x1D554, 'M', 'c'), (0x1D555, 'M', 'd'), (0x1D556, 'M', 'e'), (0x1D557, 'M', 'f'), (0x1D558, 'M', 'g'), (0x1D559, 'M', 'h'), (0x1D55A, 'M', 'i'), (0x1D55B, 'M', 'j'), (0x1D55C, 'M', 'k'), (0x1D55D, 'M', 'l'), (0x1D55E, 'M', 'm'), (0x1D55F, 'M', 'n'), (0x1D560, 'M', 'o'), (0x1D561, 'M', 'p'), (0x1D562, 'M', 'q'), ]
[ "def", "_seg_63", "(", ")", "->", "List", "[", "Union", "[", "Tuple", "[", "int", ",", "str", "]", ",", "Tuple", "[", "int", ",", "str", ",", "str", "]", "]", "]", ":", "return", "[", "(", "0x1D4FC", ",", "'M'", ",", "'s'", ")", ",", "(", "0x1D4FD", ",", "'M'", ",", "'t'", ")", ",", "(", "0x1D4FE", ",", "'M'", ",", "'u'", ")", ",", "(", "0x1D4FF", ",", "'M'", ",", "'v'", ")", ",", "(", "0x1D500", ",", "'M'", ",", "'w'", ")", ",", "(", "0x1D501", ",", "'M'", ",", "'x'", ")", ",", "(", "0x1D502", ",", "'M'", ",", "'y'", ")", ",", "(", "0x1D503", ",", "'M'", ",", "'z'", ")", ",", "(", "0x1D504", ",", "'M'", ",", "'a'", ")", ",", "(", "0x1D505", ",", "'M'", ",", "'b'", ")", ",", "(", "0x1D506", ",", "'X'", ")", ",", "(", "0x1D507", ",", "'M'", ",", "'d'", ")", ",", "(", "0x1D508", ",", "'M'", ",", "'e'", ")", ",", "(", "0x1D509", ",", "'M'", ",", "'f'", ")", ",", "(", "0x1D50A", ",", "'M'", ",", "'g'", ")", ",", "(", "0x1D50B", ",", "'X'", ")", ",", "(", "0x1D50D", ",", "'M'", ",", "'j'", ")", ",", "(", "0x1D50E", ",", "'M'", ",", "'k'", ")", ",", "(", "0x1D50F", ",", "'M'", ",", "'l'", ")", ",", "(", "0x1D510", ",", "'M'", ",", "'m'", ")", ",", "(", "0x1D511", ",", "'M'", ",", "'n'", ")", ",", "(", "0x1D512", ",", "'M'", ",", "'o'", ")", ",", "(", "0x1D513", ",", "'M'", ",", "'p'", ")", ",", "(", "0x1D514", ",", "'M'", ",", "'q'", ")", ",", "(", "0x1D515", ",", "'X'", ")", ",", "(", "0x1D516", ",", "'M'", ",", "'s'", ")", ",", "(", "0x1D517", ",", "'M'", ",", "'t'", ")", ",", "(", "0x1D518", ",", "'M'", ",", "'u'", ")", ",", "(", "0x1D519", ",", "'M'", ",", "'v'", ")", ",", "(", "0x1D51A", ",", "'M'", ",", "'w'", ")", ",", "(", "0x1D51B", ",", "'M'", ",", "'x'", ")", ",", "(", "0x1D51C", ",", "'M'", ",", "'y'", ")", ",", "(", "0x1D51D", ",", "'X'", ")", ",", "(", "0x1D51E", ",", "'M'", ",", "'a'", ")", ",", "(", "0x1D51F", ",", "'M'", ",", "'b'", ")", ",", "(", "0x1D520", ",", "'M'", ",", "'c'", ")", ",", "(", "0x1D521", ",", "'M'", ",", "'d'", ")", ",", "(", "0x1D522", ",", "'M'", ",", "'e'", ")", ",", "(", "0x1D523", ",", "'M'", ",", "'f'", ")", ",", "(", "0x1D524", ",", "'M'", ",", "'g'", ")", ",", "(", "0x1D525", ",", "'M'", ",", "'h'", ")", ",", "(", "0x1D526", ",", "'M'", ",", "'i'", ")", ",", "(", "0x1D527", ",", "'M'", ",", "'j'", ")", ",", "(", "0x1D528", ",", "'M'", ",", "'k'", ")", ",", "(", "0x1D529", ",", "'M'", ",", "'l'", ")", ",", "(", "0x1D52A", ",", "'M'", ",", "'m'", ")", ",", "(", "0x1D52B", ",", "'M'", ",", "'n'", ")", ",", "(", "0x1D52C", ",", "'M'", ",", "'o'", ")", ",", "(", "0x1D52D", ",", "'M'", ",", "'p'", ")", ",", "(", "0x1D52E", ",", "'M'", ",", "'q'", ")", ",", "(", "0x1D52F", ",", "'M'", ",", "'r'", ")", ",", "(", "0x1D530", ",", "'M'", ",", "'s'", ")", ",", "(", "0x1D531", ",", "'M'", ",", "'t'", ")", ",", "(", "0x1D532", ",", "'M'", ",", "'u'", ")", ",", "(", "0x1D533", ",", "'M'", ",", "'v'", ")", ",", "(", "0x1D534", ",", "'M'", ",", "'w'", ")", ",", "(", "0x1D535", ",", "'M'", ",", "'x'", ")", ",", "(", "0x1D536", ",", "'M'", ",", "'y'", ")", ",", "(", "0x1D537", ",", "'M'", ",", "'z'", ")", ",", "(", "0x1D538", ",", "'M'", ",", "'a'", ")", ",", "(", "0x1D539", ",", "'M'", ",", "'b'", ")", ",", "(", "0x1D53A", ",", "'X'", ")", ",", "(", "0x1D53B", ",", "'M'", ",", "'d'", ")", ",", "(", "0x1D53C", ",", "'M'", ",", "'e'", ")", ",", "(", "0x1D53D", ",", "'M'", ",", "'f'", ")", ",", "(", "0x1D53E", ",", "'M'", ",", "'g'", ")", ",", "(", "0x1D53F", ",", "'X'", ")", ",", "(", "0x1D540", ",", "'M'", ",", "'i'", ")", ",", "(", "0x1D541", ",", "'M'", ",", "'j'", ")", ",", "(", "0x1D542", ",", "'M'", ",", "'k'", ")", ",", "(", "0x1D543", ",", "'M'", ",", "'l'", ")", ",", "(", "0x1D544", ",", "'M'", ",", "'m'", ")", ",", "(", "0x1D545", ",", "'X'", ")", ",", "(", "0x1D546", ",", "'M'", ",", "'o'", ")", ",", "(", "0x1D547", ",", "'X'", ")", ",", "(", "0x1D54A", ",", "'M'", ",", "'s'", ")", ",", "(", "0x1D54B", ",", "'M'", ",", "'t'", ")", ",", "(", "0x1D54C", ",", "'M'", ",", "'u'", ")", ",", "(", "0x1D54D", ",", "'M'", ",", "'v'", ")", ",", "(", "0x1D54E", ",", "'M'", ",", "'w'", ")", ",", "(", "0x1D54F", ",", "'M'", ",", "'x'", ")", ",", "(", "0x1D550", ",", "'M'", ",", "'y'", ")", ",", "(", "0x1D551", ",", "'X'", ")", ",", "(", "0x1D552", ",", "'M'", ",", "'a'", ")", ",", "(", "0x1D553", ",", "'M'", ",", "'b'", ")", ",", "(", "0x1D554", ",", "'M'", ",", "'c'", ")", ",", "(", "0x1D555", ",", "'M'", ",", "'d'", ")", ",", "(", "0x1D556", ",", "'M'", ",", "'e'", ")", ",", "(", "0x1D557", ",", "'M'", ",", "'f'", ")", ",", "(", "0x1D558", ",", "'M'", ",", "'g'", ")", ",", "(", "0x1D559", ",", "'M'", ",", "'h'", ")", ",", "(", "0x1D55A", ",", "'M'", ",", "'i'", ")", ",", "(", "0x1D55B", ",", "'M'", ",", "'j'", ")", ",", "(", "0x1D55C", ",", "'M'", ",", "'k'", ")", ",", "(", "0x1D55D", ",", "'M'", ",", "'l'", ")", ",", "(", "0x1D55E", ",", "'M'", ",", "'m'", ")", ",", "(", "0x1D55F", ",", "'M'", ",", "'n'", ")", ",", "(", "0x1D560", ",", "'M'", ",", "'o'", ")", ",", "(", "0x1D561", ",", "'M'", ",", "'p'", ")", ",", "(", "0x1D562", ",", "'M'", ",", "'q'", ")", ",", "]" ]
https://github.com/Tautulli/Tautulli/blob/2410eb33805aaac4bd1c5dad0f71e4f15afaf742/lib/idna/uts46data.py#L6563-L6665
MrH0wl/Cloudmare
65e5bc9888f9d362ab2abfb103ea6c1e869d67aa
thirdparty/bs4/dammit.py
python
UnicodeDammit._to_unicode
(self, data, encoding, errors="strict")
return str(data, encoding, errors)
Given a string and its encoding, decodes the string into Unicode. :param encoding: The name of an encoding.
Given a string and its encoding, decodes the string into Unicode.
[ "Given", "a", "string", "and", "its", "encoding", "decodes", "the", "string", "into", "Unicode", "." ]
def _to_unicode(self, data, encoding, errors="strict"): """Given a string and its encoding, decodes the string into Unicode. :param encoding: The name of an encoding. """ return str(data, encoding, errors)
[ "def", "_to_unicode", "(", "self", ",", "data", ",", "encoding", ",", "errors", "=", "\"strict\"", ")", ":", "return", "str", "(", "data", ",", "encoding", ",", "errors", ")" ]
https://github.com/MrH0wl/Cloudmare/blob/65e5bc9888f9d362ab2abfb103ea6c1e869d67aa/thirdparty/bs4/dammit.py#L521-L526
PaddlePaddle/Parakeet
8705a2a8405e3c63f2174d69880d2b5525a6c9fd
parakeet/modules/conv.py
python
Conv1dCell.start_sequence
(self)
Prepare the layer for a series of incremental forward. Warnings --------- This method should be called before a sequence of calls to ``add_input``. Raises ------ Exception If this method is called when the layer is in training mode.
Prepare the layer for a series of incremental forward. Warnings --------- This method should be called before a sequence of calls to ``add_input``.
[ "Prepare", "the", "layer", "for", "a", "series", "of", "incremental", "forward", ".", "Warnings", "---------", "This", "method", "should", "be", "called", "before", "a", "sequence", "of", "calls", "to", "add_input", "." ]
def start_sequence(self): """Prepare the layer for a series of incremental forward. Warnings --------- This method should be called before a sequence of calls to ``add_input``. Raises ------ Exception If this method is called when the layer is in training mode. """ if self.training: raise Exception("only use start_sequence in evaluation") self._buffer = None # NOTE: call self's weight norm hook expliccitly since self.weight # is visited directly in this method without calling self.__call__ # method. If we do not trigger the weight norm hook, the weight # may be outdated. e.g. after loading from a saved checkpoint # see also: https://github.com/pytorch/pytorch/issues/47588 for hook in self._forward_pre_hooks.values(): hook(self, None) self._reshaped_weight = paddle.reshape(self.weight, (self._out_channels, -1))
[ "def", "start_sequence", "(", "self", ")", ":", "if", "self", ".", "training", ":", "raise", "Exception", "(", "\"only use start_sequence in evaluation\"", ")", "self", ".", "_buffer", "=", "None", "# NOTE: call self's weight norm hook expliccitly since self.weight ", "# is visited directly in this method without calling self.__call__ ", "# method. If we do not trigger the weight norm hook, the weight ", "# may be outdated. e.g. after loading from a saved checkpoint", "# see also: https://github.com/pytorch/pytorch/issues/47588", "for", "hook", "in", "self", ".", "_forward_pre_hooks", ".", "values", "(", ")", ":", "hook", "(", "self", ",", "None", ")", "self", ".", "_reshaped_weight", "=", "paddle", ".", "reshape", "(", "self", ".", "weight", ",", "(", "self", ".", "_out_channels", ",", "-", "1", ")", ")" ]
https://github.com/PaddlePaddle/Parakeet/blob/8705a2a8405e3c63f2174d69880d2b5525a6c9fd/parakeet/modules/conv.py#L103-L128
PyTorchLightning/pytorch-lightning
5914fb748fb53d826ab337fc2484feab9883a104
pytorch_lightning/plugins/environments/lsf_environment.py
python
LSFEnvironment._read_hosts
()
return ret[1:]
Read compute hosts that are a part of the compute job. LSF uses the Job Step Manager (JSM) to manage job steps. Job steps are executed by the JSM from "launch" nodes. Each job is assigned a launch node. This launch node will be the first node in the list contained in ``LSB_DJOB_RANKFILE``.
Read compute hosts that are a part of the compute job.
[ "Read", "compute", "hosts", "that", "are", "a", "part", "of", "the", "compute", "job", "." ]
def _read_hosts() -> List[str]: """Read compute hosts that are a part of the compute job. LSF uses the Job Step Manager (JSM) to manage job steps. Job steps are executed by the JSM from "launch" nodes. Each job is assigned a launch node. This launch node will be the first node in the list contained in ``LSB_DJOB_RANKFILE``. """ var = "LSB_DJOB_RANKFILE" rankfile = os.environ.get(var) if rankfile is None: raise ValueError("Did not find the environment variable `LSB_DJOB_RANKFILE`") if not rankfile: raise ValueError("The environment variable `LSB_DJOB_RANKFILE` is empty") fs = get_filesystem(rankfile) with fs.open(rankfile, "r") as f: ret = [line.strip() for line in f] # remove the launch node (i.e. the first node in LSB_DJOB_RANKFILE) from the list return ret[1:]
[ "def", "_read_hosts", "(", ")", "->", "List", "[", "str", "]", ":", "var", "=", "\"LSB_DJOB_RANKFILE\"", "rankfile", "=", "os", ".", "environ", ".", "get", "(", "var", ")", "if", "rankfile", "is", "None", ":", "raise", "ValueError", "(", "\"Did not find the environment variable `LSB_DJOB_RANKFILE`\"", ")", "if", "not", "rankfile", ":", "raise", "ValueError", "(", "\"The environment variable `LSB_DJOB_RANKFILE` is empty\"", ")", "fs", "=", "get_filesystem", "(", "rankfile", ")", "with", "fs", ".", "open", "(", "rankfile", ",", "\"r\"", ")", "as", "f", ":", "ret", "=", "[", "line", ".", "strip", "(", ")", "for", "line", "in", "f", "]", "# remove the launch node (i.e. the first node in LSB_DJOB_RANKFILE) from the list", "return", "ret", "[", "1", ":", "]" ]
https://github.com/PyTorchLightning/pytorch-lightning/blob/5914fb748fb53d826ab337fc2484feab9883a104/pytorch_lightning/plugins/environments/lsf_environment.py#L146-L164
gammapy/gammapy
735b25cd5bbed35e2004d633621896dcd5295e8b
gammapy/datasets/map.py
python
MapDataset.to_hdulist
(self)
return hdulist
Convert map dataset to list of HDUs. Returns ------- hdulist : `~astropy.io.fits.HDUList` Map dataset list of HDUs.
Convert map dataset to list of HDUs.
[ "Convert", "map", "dataset", "to", "list", "of", "HDUs", "." ]
def to_hdulist(self): """Convert map dataset to list of HDUs. Returns ------- hdulist : `~astropy.io.fits.HDUList` Map dataset list of HDUs. """ # TODO: what todo about the model and background model parameters? exclude_primary = slice(1, None) hdu_primary = fits.PrimaryHDU() hdulist = fits.HDUList([hdu_primary]) if self.counts is not None: hdulist += self.counts.to_hdulist(hdu="counts")[exclude_primary] if self.exposure is not None: hdulist += self.exposure.to_hdulist(hdu="exposure")[exclude_primary] if self.background is not None: hdulist += self.background.to_hdulist(hdu="background")[exclude_primary] if self.edisp is not None: hdulist += self.edisp.to_hdulist()[exclude_primary] if self.psf is not None: hdulist += self.psf.to_hdulist()[exclude_primary] if self.mask_safe is not None: hdulist += self.mask_safe.to_hdulist(hdu="mask_safe")[exclude_primary] if self.mask_fit is not None: hdulist += self.mask_fit.to_hdulist(hdu="mask_fit")[exclude_primary] if self.gti is not None: hdulist.append(fits.BinTableHDU(self.gti.table, name="GTI")) return hdulist
[ "def", "to_hdulist", "(", "self", ")", ":", "# TODO: what todo about the model and background model parameters?", "exclude_primary", "=", "slice", "(", "1", ",", "None", ")", "hdu_primary", "=", "fits", ".", "PrimaryHDU", "(", ")", "hdulist", "=", "fits", ".", "HDUList", "(", "[", "hdu_primary", "]", ")", "if", "self", ".", "counts", "is", "not", "None", ":", "hdulist", "+=", "self", ".", "counts", ".", "to_hdulist", "(", "hdu", "=", "\"counts\"", ")", "[", "exclude_primary", "]", "if", "self", ".", "exposure", "is", "not", "None", ":", "hdulist", "+=", "self", ".", "exposure", ".", "to_hdulist", "(", "hdu", "=", "\"exposure\"", ")", "[", "exclude_primary", "]", "if", "self", ".", "background", "is", "not", "None", ":", "hdulist", "+=", "self", ".", "background", ".", "to_hdulist", "(", "hdu", "=", "\"background\"", ")", "[", "exclude_primary", "]", "if", "self", ".", "edisp", "is", "not", "None", ":", "hdulist", "+=", "self", ".", "edisp", ".", "to_hdulist", "(", ")", "[", "exclude_primary", "]", "if", "self", ".", "psf", "is", "not", "None", ":", "hdulist", "+=", "self", ".", "psf", ".", "to_hdulist", "(", ")", "[", "exclude_primary", "]", "if", "self", ".", "mask_safe", "is", "not", "None", ":", "hdulist", "+=", "self", ".", "mask_safe", ".", "to_hdulist", "(", "hdu", "=", "\"mask_safe\"", ")", "[", "exclude_primary", "]", "if", "self", ".", "mask_fit", "is", "not", "None", ":", "hdulist", "+=", "self", ".", "mask_fit", ".", "to_hdulist", "(", "hdu", "=", "\"mask_fit\"", ")", "[", "exclude_primary", "]", "if", "self", ".", "gti", "is", "not", "None", ":", "hdulist", ".", "append", "(", "fits", ".", "BinTableHDU", "(", "self", ".", "gti", ".", "table", ",", "name", "=", "\"GTI\"", ")", ")", "return", "hdulist" ]
https://github.com/gammapy/gammapy/blob/735b25cd5bbed35e2004d633621896dcd5295e8b/gammapy/datasets/map.py#L999-L1036
matplotlib/matplotlib
8d7a2b9d2a38f01ee0d6802dd4f9e98aec812322
lib/matplotlib/backend_bases.py
python
GraphicsContextBase.set_foreground
(self, fg, isRGBA=False)
Set the foreground color. Parameters ---------- fg : color isRGBA : bool If *fg* is known to be an ``(r, g, b, a)`` tuple, *isRGBA* can be set to True to improve performance.
Set the foreground color.
[ "Set", "the", "foreground", "color", "." ]
def set_foreground(self, fg, isRGBA=False): """ Set the foreground color. Parameters ---------- fg : color isRGBA : bool If *fg* is known to be an ``(r, g, b, a)`` tuple, *isRGBA* can be set to True to improve performance. """ if self._forced_alpha and isRGBA: self._rgb = fg[:3] + (self._alpha,) elif self._forced_alpha: self._rgb = colors.to_rgba(fg, self._alpha) elif isRGBA: self._rgb = fg else: self._rgb = colors.to_rgba(fg)
[ "def", "set_foreground", "(", "self", ",", "fg", ",", "isRGBA", "=", "False", ")", ":", "if", "self", ".", "_forced_alpha", "and", "isRGBA", ":", "self", ".", "_rgb", "=", "fg", "[", ":", "3", "]", "+", "(", "self", ".", "_alpha", ",", ")", "elif", "self", ".", "_forced_alpha", ":", "self", ".", "_rgb", "=", "colors", ".", "to_rgba", "(", "fg", ",", "self", ".", "_alpha", ")", "elif", "isRGBA", ":", "self", ".", "_rgb", "=", "fg", "else", ":", "self", ".", "_rgb", "=", "colors", ".", "to_rgba", "(", "fg", ")" ]
https://github.com/matplotlib/matplotlib/blob/8d7a2b9d2a38f01ee0d6802dd4f9e98aec812322/lib/matplotlib/backend_bases.py#L930-L948
hzdg/django-enumfields
bda0a461657a87601d235d78176add73a8875832
enumfields/enums.py
python
Enum.choices
(cls)
return tuple((m.value, m.label) for m in cls)
Returns a list formatted for use as field choices. (See https://docs.djangoproject.com/en/dev/ref/models/fields/#choices)
Returns a list formatted for use as field choices. (See https://docs.djangoproject.com/en/dev/ref/models/fields/#choices)
[ "Returns", "a", "list", "formatted", "for", "use", "as", "field", "choices", ".", "(", "See", "https", ":", "//", "docs", ".", "djangoproject", ".", "com", "/", "en", "/", "dev", "/", "ref", "/", "models", "/", "fields", "/", "#choices", ")" ]
def choices(cls): """ Returns a list formatted for use as field choices. (See https://docs.djangoproject.com/en/dev/ref/models/fields/#choices) """ return tuple((m.value, m.label) for m in cls)
[ "def", "choices", "(", "cls", ")", ":", "return", "tuple", "(", "(", "m", ".", "value", ",", "m", ".", "label", ")", "for", "m", "in", "cls", ")" ]
https://github.com/hzdg/django-enumfields/blob/bda0a461657a87601d235d78176add73a8875832/enumfields/enums.py#L34-L39
kubernetes-client/python
47b9da9de2d02b2b7a34fbe05afb44afd130d73a
kubernetes/client/models/v1_custom_resource_definition_names.py
python
V1CustomResourceDefinitionNames.kind
(self)
return self._kind
Gets the kind of this V1CustomResourceDefinitionNames. # noqa: E501 kind is the serialized kind of the resource. It is normally CamelCase and singular. Custom resource instances will use this value as the `kind` attribute in API calls. # noqa: E501 :return: The kind of this V1CustomResourceDefinitionNames. # noqa: E501 :rtype: str
Gets the kind of this V1CustomResourceDefinitionNames. # noqa: E501
[ "Gets", "the", "kind", "of", "this", "V1CustomResourceDefinitionNames", ".", "#", "noqa", ":", "E501" ]
def kind(self): """Gets the kind of this V1CustomResourceDefinitionNames. # noqa: E501 kind is the serialized kind of the resource. It is normally CamelCase and singular. Custom resource instances will use this value as the `kind` attribute in API calls. # noqa: E501 :return: The kind of this V1CustomResourceDefinitionNames. # noqa: E501 :rtype: str """ return self._kind
[ "def", "kind", "(", "self", ")", ":", "return", "self", ".", "_kind" ]
https://github.com/kubernetes-client/python/blob/47b9da9de2d02b2b7a34fbe05afb44afd130d73a/kubernetes/client/models/v1_custom_resource_definition_names.py#L102-L110
FederatedAI/FATE
32540492623568ecd1afcb367360133616e02fa3
python/federatedml/model_selection/stepwise/hetero_stepwise.py
python
HeteroStepwise.mask2string
(host_mask, guest_mask)
return string_repr
[]
def mask2string(host_mask, guest_mask): mask = np.append(host_mask, guest_mask) string_repr = ''.join('1' if i else '0' for i in mask) return string_repr
[ "def", "mask2string", "(", "host_mask", ",", "guest_mask", ")", ":", "mask", "=", "np", ".", "append", "(", "host_mask", ",", "guest_mask", ")", "string_repr", "=", "''", ".", "join", "(", "'1'", "if", "i", "else", "'0'", "for", "i", "in", "mask", ")", "return", "string_repr" ]
https://github.com/FederatedAI/FATE/blob/32540492623568ecd1afcb367360133616e02fa3/python/federatedml/model_selection/stepwise/hetero_stepwise.py#L366-L369
loli/medpy
39131b94f0ab5328ab14a874229320efc2f74d98
medpy/features/intensity.py
python
centerdistance_xdminus1
(image, dim, voxelspacing = None, mask = slice(None))
return intensities(o, mask)
r""" Implementation of `centerdistance` that allows to compute sub-volume wise centerdistances. The same notes as for `centerdistance` apply. Parameters ---------- image : array_like or list/tuple of array_like A single image or a list/tuple of images (for multi-spectral case). dim : int or sequence of ints The dimension or dimensions along which to cut the image into sub-volumes. voxelspacing : sequence of floats The side-length of each voxel. mask : array_like A binary mask for the image. Returns ------- centerdistance_xdminus1 : ndarray The distance of each voxel to the images center in the supplied dimensions. Raises ------ ArgumentError If a invalid dim index of number of dim indices were supplied Examples -------- Considering a 3D medical image we want to compute the axial slice-wise centerdistances instead of the ones over the complete image volume. Assuming that the third image dimension corresponds to the axial axes of the image, we call >>> centerdistance_xdminus1(image, 2) Note that the centerdistance of each slice will be equal.
r""" Implementation of `centerdistance` that allows to compute sub-volume wise centerdistances. The same notes as for `centerdistance` apply. Parameters ---------- image : array_like or list/tuple of array_like A single image or a list/tuple of images (for multi-spectral case). dim : int or sequence of ints The dimension or dimensions along which to cut the image into sub-volumes. voxelspacing : sequence of floats The side-length of each voxel. mask : array_like A binary mask for the image. Returns ------- centerdistance_xdminus1 : ndarray The distance of each voxel to the images center in the supplied dimensions. Raises ------ ArgumentError If a invalid dim index of number of dim indices were supplied
[ "r", "Implementation", "of", "centerdistance", "that", "allows", "to", "compute", "sub", "-", "volume", "wise", "centerdistances", ".", "The", "same", "notes", "as", "for", "centerdistance", "apply", ".", "Parameters", "----------", "image", ":", "array_like", "or", "list", "/", "tuple", "of", "array_like", "A", "single", "image", "or", "a", "list", "/", "tuple", "of", "images", "(", "for", "multi", "-", "spectral", "case", ")", ".", "dim", ":", "int", "or", "sequence", "of", "ints", "The", "dimension", "or", "dimensions", "along", "which", "to", "cut", "the", "image", "into", "sub", "-", "volumes", ".", "voxelspacing", ":", "sequence", "of", "floats", "The", "side", "-", "length", "of", "each", "voxel", ".", "mask", ":", "array_like", "A", "binary", "mask", "for", "the", "image", ".", "Returns", "-------", "centerdistance_xdminus1", ":", "ndarray", "The", "distance", "of", "each", "voxel", "to", "the", "images", "center", "in", "the", "supplied", "dimensions", ".", "Raises", "------", "ArgumentError", "If", "a", "invalid", "dim", "index", "of", "number", "of", "dim", "indices", "were", "supplied" ]
def centerdistance_xdminus1(image, dim, voxelspacing = None, mask = slice(None)): r""" Implementation of `centerdistance` that allows to compute sub-volume wise centerdistances. The same notes as for `centerdistance` apply. Parameters ---------- image : array_like or list/tuple of array_like A single image or a list/tuple of images (for multi-spectral case). dim : int or sequence of ints The dimension or dimensions along which to cut the image into sub-volumes. voxelspacing : sequence of floats The side-length of each voxel. mask : array_like A binary mask for the image. Returns ------- centerdistance_xdminus1 : ndarray The distance of each voxel to the images center in the supplied dimensions. Raises ------ ArgumentError If a invalid dim index of number of dim indices were supplied Examples -------- Considering a 3D medical image we want to compute the axial slice-wise centerdistances instead of the ones over the complete image volume. Assuming that the third image dimension corresponds to the axial axes of the image, we call >>> centerdistance_xdminus1(image, 2) Note that the centerdistance of each slice will be equal. """ # pre-process arguments if type(image) == tuple or type(image) == list: image = image[0] if type(dim) is int: dims = [dim] else: dims = list(dim) # check arguments if len(dims) >= image.ndim - 1: raise ArgumentError('Applying a sub-volume extraction of depth {} on a image of dimensionality {} would lead to invalid images of dimensionality <= 1.'.format(len(dims), image.ndim)) for dim in dims: if dim >= image.ndim: raise ArgumentError('Invalid dimension index {} supplied for image(s) of shape {}.'.format(dim, image.shape)) # extract desired sub-volume slicer = [slice(None)] * image.ndim for dim in dims: slicer[dim] = slice(1) subvolume = numpy.squeeze(image[slicer]) # compute centerdistance for sub-volume and reshape to original sub-volume shape (note that normalization and mask are not passed on in this step) o = centerdistance(subvolume, voxelspacing).reshape(subvolume.shape) # re-establish original shape by copying the resulting array multiple times for dim in sorted(dims): o = numpy.asarray([o] * image.shape[dim]) o = numpy.rollaxis(o, 0, dim + 1) # extract intensities / centerdistance values, applying normalization and mask in this step return intensities(o, mask)
[ "def", "centerdistance_xdminus1", "(", "image", ",", "dim", ",", "voxelspacing", "=", "None", ",", "mask", "=", "slice", "(", "None", ")", ")", ":", "# pre-process arguments", "if", "type", "(", "image", ")", "==", "tuple", "or", "type", "(", "image", ")", "==", "list", ":", "image", "=", "image", "[", "0", "]", "if", "type", "(", "dim", ")", "is", "int", ":", "dims", "=", "[", "dim", "]", "else", ":", "dims", "=", "list", "(", "dim", ")", "# check arguments", "if", "len", "(", "dims", ")", ">=", "image", ".", "ndim", "-", "1", ":", "raise", "ArgumentError", "(", "'Applying a sub-volume extraction of depth {} on a image of dimensionality {} would lead to invalid images of dimensionality <= 1.'", ".", "format", "(", "len", "(", "dims", ")", ",", "image", ".", "ndim", ")", ")", "for", "dim", "in", "dims", ":", "if", "dim", ">=", "image", ".", "ndim", ":", "raise", "ArgumentError", "(", "'Invalid dimension index {} supplied for image(s) of shape {}.'", ".", "format", "(", "dim", ",", "image", ".", "shape", ")", ")", "# extract desired sub-volume", "slicer", "=", "[", "slice", "(", "None", ")", "]", "*", "image", ".", "ndim", "for", "dim", "in", "dims", ":", "slicer", "[", "dim", "]", "=", "slice", "(", "1", ")", "subvolume", "=", "numpy", ".", "squeeze", "(", "image", "[", "slicer", "]", ")", "# compute centerdistance for sub-volume and reshape to original sub-volume shape (note that normalization and mask are not passed on in this step)", "o", "=", "centerdistance", "(", "subvolume", ",", "voxelspacing", ")", ".", "reshape", "(", "subvolume", ".", "shape", ")", "# re-establish original shape by copying the resulting array multiple times", "for", "dim", "in", "sorted", "(", "dims", ")", ":", "o", "=", "numpy", ".", "asarray", "(", "[", "o", "]", "*", "image", ".", "shape", "[", "dim", "]", ")", "o", "=", "numpy", ".", "rollaxis", "(", "o", ",", "0", ",", "dim", "+", "1", ")", "# extract intensities / centerdistance values, applying normalization and mask in this step", "return", "intensities", "(", "o", ",", "mask", ")" ]
https://github.com/loli/medpy/blob/39131b94f0ab5328ab14a874229320efc2f74d98/medpy/features/intensity.py#L98-L167
Project-MONAI/MONAI
83f8b06372a3803ebe9281300cb794a1f3395018
monai/networks/nets/efficientnet.py
python
BlockArgs.to_string
(self)
return string
Return a block string notation for current BlockArgs object Returns: A string notation of BlockArgs object arguments. Example: "r1_k3_s11_e1_i32_o16_se0.25_noskip".
Return a block string notation for current BlockArgs object
[ "Return", "a", "block", "string", "notation", "for", "current", "BlockArgs", "object" ]
def to_string(self): """ Return a block string notation for current BlockArgs object Returns: A string notation of BlockArgs object arguments. Example: "r1_k3_s11_e1_i32_o16_se0.25_noskip". """ string = "r{}_k{}_s{}{}_e{}_i{}_o{}_se{}".format( self.num_repeat, self.kernel_size, self.stride, self.stride, self.expand_ratio, self.input_filters, self.output_filters, self.se_ratio, ) if not self.id_skip: string += "_noskip" return string
[ "def", "to_string", "(", "self", ")", ":", "string", "=", "\"r{}_k{}_s{}{}_e{}_i{}_o{}_se{}\"", ".", "format", "(", "self", ".", "num_repeat", ",", "self", ".", "kernel_size", ",", "self", ".", "stride", ",", "self", ".", "stride", ",", "self", ".", "expand_ratio", ",", "self", ".", "input_filters", ",", "self", ".", "output_filters", ",", "self", ".", "se_ratio", ",", ")", "if", "not", "self", ".", "id_skip", ":", "string", "+=", "\"_noskip\"", "return", "string" ]
https://github.com/Project-MONAI/MONAI/blob/83f8b06372a3803ebe9281300cb794a1f3395018/monai/networks/nets/efficientnet.py#L922-L943
mapnik/Cascadenik
82f66859340a31dfcb24af127274f262d4f3ad85
cascadenik/nonposix.py
python
add_drive_by_hash
(drive,valid_posix_path)
[]
def add_drive_by_hash(drive,valid_posix_path): # cache the drive so we can try to recreate later global drives hash = md5(valid_posix_path).hexdigest()[:8] drives[hash] = drive
[ "def", "add_drive_by_hash", "(", "drive", ",", "valid_posix_path", ")", ":", "# cache the drive so we can try to recreate later", "global", "drives", "hash", "=", "md5", "(", "valid_posix_path", ")", ".", "hexdigest", "(", ")", "[", ":", "8", "]", "drives", "[", "hash", "]", "=", "drive" ]
https://github.com/mapnik/Cascadenik/blob/82f66859340a31dfcb24af127274f262d4f3ad85/cascadenik/nonposix.py#L30-L34
Cadene/pretrained-models.pytorch
8aae3d8f1135b6b13fed79c1d431e3449fdbf6e0
pretrainedmodels/models/torchvision_models.py
python
update_state_dict
(state_dict)
return state_dict
[]
def update_state_dict(state_dict): # '.'s are no longer allowed in module names, but pervious _DenseLayer # has keys 'norm.1', 'relu.1', 'conv.1', 'norm.2', 'relu.2', 'conv.2'. # They are also in the checkpoints in model_urls. This pattern is used # to find such keys. pattern = re.compile( r'^(.*denselayer\d+\.(?:norm|relu|conv))\.((?:[12])\.(?:weight|bias|running_mean|running_var))$') for key in list(state_dict.keys()): res = pattern.match(key) if res: new_key = res.group(1) + res.group(2) state_dict[new_key] = state_dict[key] del state_dict[key] return state_dict
[ "def", "update_state_dict", "(", "state_dict", ")", ":", "# '.'s are no longer allowed in module names, but pervious _DenseLayer", "# has keys 'norm.1', 'relu.1', 'conv.1', 'norm.2', 'relu.2', 'conv.2'.", "# They are also in the checkpoints in model_urls. This pattern is used", "# to find such keys.", "pattern", "=", "re", ".", "compile", "(", "r'^(.*denselayer\\d+\\.(?:norm|relu|conv))\\.((?:[12])\\.(?:weight|bias|running_mean|running_var))$'", ")", "for", "key", "in", "list", "(", "state_dict", ".", "keys", "(", ")", ")", ":", "res", "=", "pattern", ".", "match", "(", "key", ")", "if", "res", ":", "new_key", "=", "res", ".", "group", "(", "1", ")", "+", "res", ".", "group", "(", "2", ")", "state_dict", "[", "new_key", "]", "=", "state_dict", "[", "key", "]", "del", "state_dict", "[", "key", "]", "return", "state_dict" ]
https://github.com/Cadene/pretrained-models.pytorch/blob/8aae3d8f1135b6b13fed79c1d431e3449fdbf6e0/pretrainedmodels/models/torchvision_models.py#L98-L111
airbnb/streamalert
26cf1d08432ca285fd4f7410511a6198ca104bbb
streamalert_cli/athena/handler.py
python
rebuild_partitions
(table, bucket, config)
return True
Rebuild an Athena table's partitions Steps: - Get the list of current partitions - Destroy existing table - Re-create tables - Re-create partitions Args: table (str): The name of the table being rebuilt bucket (str): The s3 bucket to be used as the location for Athena data table_type (str): The type of table being refreshed Types of 'data' and 'alert' are accepted, but only 'data' is implemented config (CLIConfig): Loaded StreamAlert config Returns: bool: False if errors occurred, True otherwise
Rebuild an Athena table's partitions
[ "Rebuild", "an", "Athena", "table", "s", "partitions" ]
def rebuild_partitions(table, bucket, config): """Rebuild an Athena table's partitions Steps: - Get the list of current partitions - Destroy existing table - Re-create tables - Re-create partitions Args: table (str): The name of the table being rebuilt bucket (str): The s3 bucket to be used as the location for Athena data table_type (str): The type of table being refreshed Types of 'data' and 'alert' are accepted, but only 'data' is implemented config (CLIConfig): Loaded StreamAlert config Returns: bool: False if errors occurred, True otherwise """ sanitized_table_name = FirehoseClient.sanitized_value(table) athena_client = get_athena_client(config) # Get the current set of partitions partitions = athena_client.get_table_partitions(sanitized_table_name) if not partitions: LOGGER.info('No partitions to rebuild for %s, nothing to do', sanitized_table_name) return False # Drop the table LOGGER.info('Dropping table %s', sanitized_table_name) if not athena_client.drop_table(sanitized_table_name): return False LOGGER.info('Creating table %s', sanitized_table_name) # Re-create the table with previous partitions if not create_table(table, bucket, config): return False new_partitions_statements = helpers.add_partition_statements( partitions, bucket, sanitized_table_name) LOGGER.info('Creating total %d new partitions for %s', len(partitions), sanitized_table_name) for idx, statement in enumerate(new_partitions_statements): success = athena_client.run_query(query=statement) LOGGER.info('Rebuilt partitions part %d', idx+1) if not success: LOGGER.error('Error re-creating new partitions for %s', sanitized_table_name) write_partitions_statements(new_partitions_statements, sanitized_table_name) return False LOGGER.info('Successfully rebuilt all partitions for %s', sanitized_table_name) return True
[ "def", "rebuild_partitions", "(", "table", ",", "bucket", ",", "config", ")", ":", "sanitized_table_name", "=", "FirehoseClient", ".", "sanitized_value", "(", "table", ")", "athena_client", "=", "get_athena_client", "(", "config", ")", "# Get the current set of partitions", "partitions", "=", "athena_client", ".", "get_table_partitions", "(", "sanitized_table_name", ")", "if", "not", "partitions", ":", "LOGGER", ".", "info", "(", "'No partitions to rebuild for %s, nothing to do'", ",", "sanitized_table_name", ")", "return", "False", "# Drop the table", "LOGGER", ".", "info", "(", "'Dropping table %s'", ",", "sanitized_table_name", ")", "if", "not", "athena_client", ".", "drop_table", "(", "sanitized_table_name", ")", ":", "return", "False", "LOGGER", ".", "info", "(", "'Creating table %s'", ",", "sanitized_table_name", ")", "# Re-create the table with previous partitions", "if", "not", "create_table", "(", "table", ",", "bucket", ",", "config", ")", ":", "return", "False", "new_partitions_statements", "=", "helpers", ".", "add_partition_statements", "(", "partitions", ",", "bucket", ",", "sanitized_table_name", ")", "LOGGER", ".", "info", "(", "'Creating total %d new partitions for %s'", ",", "len", "(", "partitions", ")", ",", "sanitized_table_name", ")", "for", "idx", ",", "statement", "in", "enumerate", "(", "new_partitions_statements", ")", ":", "success", "=", "athena_client", ".", "run_query", "(", "query", "=", "statement", ")", "LOGGER", ".", "info", "(", "'Rebuilt partitions part %d'", ",", "idx", "+", "1", ")", "if", "not", "success", ":", "LOGGER", ".", "error", "(", "'Error re-creating new partitions for %s'", ",", "sanitized_table_name", ")", "write_partitions_statements", "(", "new_partitions_statements", ",", "sanitized_table_name", ")", "return", "False", "LOGGER", ".", "info", "(", "'Successfully rebuilt all partitions for %s'", ",", "sanitized_table_name", ")", "return", "True" ]
https://github.com/airbnb/streamalert/blob/26cf1d08432ca285fd4f7410511a6198ca104bbb/streamalert_cli/athena/handler.py#L219-L273
plone/Products.CMFPlone
83137764e3e7e4fe60d03c36dfc6ba9c7c543324
Products/CMFPlone/interfaces/patterns.py
python
IPatternsSettings.__call__
(self)
Return a dict of pattern options
Return a dict of pattern options
[ "Return", "a", "dict", "of", "pattern", "options" ]
def __call__(self): """ Return a dict of pattern options """ pass
[ "def", "__call__", "(", "self", ")", ":", "pass" ]
https://github.com/plone/Products.CMFPlone/blob/83137764e3e7e4fe60d03c36dfc6ba9c7c543324/Products/CMFPlone/interfaces/patterns.py#L8-L12
realpython/book2-exercises
cde325eac8e6d8cff2316601c2e5b36bb46af7d0
web2py/gluon/contrib/feedparser.py
python
_parse_date_iso8601
(dateString)
return time.localtime(time.mktime(tuple(tm)))
Parse a variety of ISO-8601-compatible formats like 20040105
Parse a variety of ISO-8601-compatible formats like 20040105
[ "Parse", "a", "variety", "of", "ISO", "-", "8601", "-", "compatible", "formats", "like", "20040105" ]
def _parse_date_iso8601(dateString): '''Parse a variety of ISO-8601-compatible formats like 20040105''' m = None for _iso8601_match in _iso8601_matches: m = _iso8601_match(dateString) if m: break if not m: return if m.span() == (0, 0): return params = m.groupdict() ordinal = params.get('ordinal', 0) if ordinal: ordinal = int(ordinal) else: ordinal = 0 year = params.get('year', '--') if not year or year == '--': year = time.gmtime()[0] elif len(year) == 2: # ISO 8601 assumes current century, i.e. 93 -> 2093, NOT 1993 year = 100 * int(time.gmtime()[0] / 100) + int(year) else: year = int(year) month = params.get('month', '-') if not month or month == '-': # ordinals are NOT normalized by mktime, we simulate them # by setting month=1, day=ordinal if ordinal: month = 1 else: month = time.gmtime()[1] month = int(month) day = params.get('day', 0) if not day: # see above if ordinal: day = ordinal elif params.get('century', 0) or \ params.get('year', 0) or params.get('month', 0): day = 1 else: day = time.gmtime()[2] else: day = int(day) # special case of the century - is the first year of the 21st century # 2000 or 2001 ? The debate goes on... if 'century' in params: year = (int(params['century']) - 1) * 100 + 1 # in ISO 8601 most fields are optional for field in ['hour', 'minute', 'second', 'tzhour', 'tzmin']: if not params.get(field, None): params[field] = 0 hour = int(params.get('hour', 0)) minute = int(params.get('minute', 0)) second = int(float(params.get('second', 0))) # weekday is normalized by mktime(), we can ignore it weekday = 0 daylight_savings_flag = -1 tm = [year, month, day, hour, minute, second, weekday, ordinal, daylight_savings_flag] # ISO 8601 time zone adjustments tz = params.get('tz') if tz and tz != 'Z': if tz[0] == '-': tm[3] += int(params.get('tzhour', 0)) tm[4] += int(params.get('tzmin', 0)) elif tz[0] == '+': tm[3] -= int(params.get('tzhour', 0)) tm[4] -= int(params.get('tzmin', 0)) else: return None # Python's time.mktime() is a wrapper around the ANSI C mktime(3c) # which is guaranteed to normalize d/m/y/h/m/s. # Many implementations have bugs, but we'll pretend they don't. return time.localtime(time.mktime(tuple(tm)))
[ "def", "_parse_date_iso8601", "(", "dateString", ")", ":", "m", "=", "None", "for", "_iso8601_match", "in", "_iso8601_matches", ":", "m", "=", "_iso8601_match", "(", "dateString", ")", "if", "m", ":", "break", "if", "not", "m", ":", "return", "if", "m", ".", "span", "(", ")", "==", "(", "0", ",", "0", ")", ":", "return", "params", "=", "m", ".", "groupdict", "(", ")", "ordinal", "=", "params", ".", "get", "(", "'ordinal'", ",", "0", ")", "if", "ordinal", ":", "ordinal", "=", "int", "(", "ordinal", ")", "else", ":", "ordinal", "=", "0", "year", "=", "params", ".", "get", "(", "'year'", ",", "'--'", ")", "if", "not", "year", "or", "year", "==", "'--'", ":", "year", "=", "time", ".", "gmtime", "(", ")", "[", "0", "]", "elif", "len", "(", "year", ")", "==", "2", ":", "# ISO 8601 assumes current century, i.e. 93 -> 2093, NOT 1993", "year", "=", "100", "*", "int", "(", "time", ".", "gmtime", "(", ")", "[", "0", "]", "/", "100", ")", "+", "int", "(", "year", ")", "else", ":", "year", "=", "int", "(", "year", ")", "month", "=", "params", ".", "get", "(", "'month'", ",", "'-'", ")", "if", "not", "month", "or", "month", "==", "'-'", ":", "# ordinals are NOT normalized by mktime, we simulate them", "# by setting month=1, day=ordinal", "if", "ordinal", ":", "month", "=", "1", "else", ":", "month", "=", "time", ".", "gmtime", "(", ")", "[", "1", "]", "month", "=", "int", "(", "month", ")", "day", "=", "params", ".", "get", "(", "'day'", ",", "0", ")", "if", "not", "day", ":", "# see above", "if", "ordinal", ":", "day", "=", "ordinal", "elif", "params", ".", "get", "(", "'century'", ",", "0", ")", "or", "params", ".", "get", "(", "'year'", ",", "0", ")", "or", "params", ".", "get", "(", "'month'", ",", "0", ")", ":", "day", "=", "1", "else", ":", "day", "=", "time", ".", "gmtime", "(", ")", "[", "2", "]", "else", ":", "day", "=", "int", "(", "day", ")", "# special case of the century - is the first year of the 21st century", "# 2000 or 2001 ? The debate goes on...", "if", "'century'", "in", "params", ":", "year", "=", "(", "int", "(", "params", "[", "'century'", "]", ")", "-", "1", ")", "*", "100", "+", "1", "# in ISO 8601 most fields are optional", "for", "field", "in", "[", "'hour'", ",", "'minute'", ",", "'second'", ",", "'tzhour'", ",", "'tzmin'", "]", ":", "if", "not", "params", ".", "get", "(", "field", ",", "None", ")", ":", "params", "[", "field", "]", "=", "0", "hour", "=", "int", "(", "params", ".", "get", "(", "'hour'", ",", "0", ")", ")", "minute", "=", "int", "(", "params", ".", "get", "(", "'minute'", ",", "0", ")", ")", "second", "=", "int", "(", "float", "(", "params", ".", "get", "(", "'second'", ",", "0", ")", ")", ")", "# weekday is normalized by mktime(), we can ignore it", "weekday", "=", "0", "daylight_savings_flag", "=", "-", "1", "tm", "=", "[", "year", ",", "month", ",", "day", ",", "hour", ",", "minute", ",", "second", ",", "weekday", ",", "ordinal", ",", "daylight_savings_flag", "]", "# ISO 8601 time zone adjustments", "tz", "=", "params", ".", "get", "(", "'tz'", ")", "if", "tz", "and", "tz", "!=", "'Z'", ":", "if", "tz", "[", "0", "]", "==", "'-'", ":", "tm", "[", "3", "]", "+=", "int", "(", "params", ".", "get", "(", "'tzhour'", ",", "0", ")", ")", "tm", "[", "4", "]", "+=", "int", "(", "params", ".", "get", "(", "'tzmin'", ",", "0", ")", ")", "elif", "tz", "[", "0", "]", "==", "'+'", ":", "tm", "[", "3", "]", "-=", "int", "(", "params", ".", "get", "(", "'tzhour'", ",", "0", ")", ")", "tm", "[", "4", "]", "-=", "int", "(", "params", ".", "get", "(", "'tzmin'", ",", "0", ")", ")", "else", ":", "return", "None", "# Python's time.mktime() is a wrapper around the ANSI C mktime(3c)", "# which is guaranteed to normalize d/m/y/h/m/s.", "# Many implementations have bugs, but we'll pretend they don't.", "return", "time", ".", "localtime", "(", "time", ".", "mktime", "(", "tuple", "(", "tm", ")", ")", ")" ]
https://github.com/realpython/book2-exercises/blob/cde325eac8e6d8cff2316601c2e5b36bb46af7d0/web2py/gluon/contrib/feedparser.py#L3004-L3080
spectacles/CodeComplice
8ca8ee4236f72b58caa4209d2fbd5fa56bd31d62
libs/elementtree/ElementTree.py
python
SubElement
(parent, tag, attrib={}, **extra)
return element
[]
def SubElement(parent, tag, attrib={}, **extra): attrib = attrib.copy() attrib.update(extra) element = parent.makeelement(tag, attrib) parent.append(element) return element
[ "def", "SubElement", "(", "parent", ",", "tag", ",", "attrib", "=", "{", "}", ",", "*", "*", "extra", ")", ":", "attrib", "=", "attrib", ".", "copy", "(", ")", "attrib", ".", "update", "(", "extra", ")", "element", "=", "parent", ".", "makeelement", "(", "tag", ",", "attrib", ")", "parent", ".", "append", "(", "element", ")", "return", "element" ]
https://github.com/spectacles/CodeComplice/blob/8ca8ee4236f72b58caa4209d2fbd5fa56bd31d62/libs/elementtree/ElementTree.py#L471-L476
andresriancho/w3af
cd22e5252243a87aaa6d0ddea47cf58dacfe00a9
w3af/core/ui/gui/history.py
python
HistorySuggestion.get_texts
(self)
return [k for k, v in info]
Provides the texts, ordered by relevance. :return: a generator with the texts
Provides the texts, ordered by relevance.
[ "Provides", "the", "texts", "ordered", "by", "relevance", "." ]
def get_texts(self): """Provides the texts, ordered by relevance. :return: a generator with the texts """ info = sorted( self.history.items(), key=operator.itemgetter(1), reverse=True) return [k for k, v in info]
[ "def", "get_texts", "(", "self", ")", ":", "info", "=", "sorted", "(", "self", ".", "history", ".", "items", "(", ")", ",", "key", "=", "operator", ".", "itemgetter", "(", "1", ")", ",", "reverse", "=", "True", ")", "return", "[", "k", "for", "k", ",", "v", "in", "info", "]" ]
https://github.com/andresriancho/w3af/blob/cd22e5252243a87aaa6d0ddea47cf58dacfe00a9/w3af/core/ui/gui/history.py#L71-L78
mypaint/mypaint
90b36dbc7b8bd2f323383f7edf608a5e0a3a1a33
gui/document.py
python
Document._update_undo_redo
(self, action, stack, cmd_str, plain_str)
Set label, tooltip and sensitivity
Set label, tooltip and sensitivity
[ "Set", "label", "tooltip", "and", "sensitivity" ]
def _update_undo_redo(self, action, stack, cmd_str, plain_str): """Set label, tooltip and sensitivity""" if len(stack) > 0: cmd = stack[-1] desc = cmd_str % cmd.display_name else: desc = plain_str action.set_label(desc) action.set_tooltip(desc) action.set_sensitive(len(stack) > 0)
[ "def", "_update_undo_redo", "(", "self", ",", "action", ",", "stack", ",", "cmd_str", ",", "plain_str", ")", ":", "if", "len", "(", "stack", ")", ">", "0", ":", "cmd", "=", "stack", "[", "-", "1", "]", "desc", "=", "cmd_str", "%", "cmd", ".", "display_name", "else", ":", "desc", "=", "plain_str", "action", ".", "set_label", "(", "desc", ")", "action", ".", "set_tooltip", "(", "desc", ")", "action", ".", "set_sensitive", "(", "len", "(", "stack", ")", ">", "0", ")" ]
https://github.com/mypaint/mypaint/blob/90b36dbc7b8bd2f323383f7edf608a5e0a3a1a33/gui/document.py#L554-L563
makerbot/ReplicatorG
d6f2b07785a5a5f1e172fb87cb4303b17c575d5d
skein_engines/skeinforge-47/fabmetheus_utilities/geometry/creation/linear_bearing_cage.py
python
getGeometryOutput
(elementNode)
return extrude.getGeometryOutputByNegativesPositives(elementNode, negatives, positives)
Get vector3 vertexes from attribute dictionary.
Get vector3 vertexes from attribute dictionary.
[ "Get", "vector3", "vertexes", "from", "attribute", "dictionary", "." ]
def getGeometryOutput(elementNode): 'Get vector3 vertexes from attribute dictionary.' derivation = LinearBearingCageDerivation(elementNode) negatives = [] positives = [] if derivation.typeStringFirstCharacter == 'a': addAssemblyCage(derivation, negatives, positives) else: addCage(derivation, derivation.height, negatives, positives) return extrude.getGeometryOutputByNegativesPositives(elementNode, negatives, positives)
[ "def", "getGeometryOutput", "(", "elementNode", ")", ":", "derivation", "=", "LinearBearingCageDerivation", "(", "elementNode", ")", "negatives", "=", "[", "]", "positives", "=", "[", "]", "if", "derivation", ".", "typeStringFirstCharacter", "==", "'a'", ":", "addAssemblyCage", "(", "derivation", ",", "negatives", ",", "positives", ")", "else", ":", "addCage", "(", "derivation", ",", "derivation", ".", "height", ",", "negatives", ",", "positives", ")", "return", "extrude", ".", "getGeometryOutputByNegativesPositives", "(", "elementNode", ",", "negatives", ",", "positives", ")" ]
https://github.com/makerbot/ReplicatorG/blob/d6f2b07785a5a5f1e172fb87cb4303b17c575d5d/skein_engines/skeinforge-47/fabmetheus_utilities/geometry/creation/linear_bearing_cage.py#L114-L123
AppScale/gts
46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9
AppServer/lib/django-1.3/django/db/backends/mysql/introspection.py
python
DatabaseIntrospection.get_table_list
(self, cursor)
return [row[0] for row in cursor.fetchall()]
Returns a list of table names in the current database.
Returns a list of table names in the current database.
[ "Returns", "a", "list", "of", "table", "names", "in", "the", "current", "database", "." ]
def get_table_list(self, cursor): "Returns a list of table names in the current database." cursor.execute("SHOW TABLES") return [row[0] for row in cursor.fetchall()]
[ "def", "get_table_list", "(", "self", ",", "cursor", ")", ":", "cursor", ".", "execute", "(", "\"SHOW TABLES\"", ")", "return", "[", "row", "[", "0", "]", "for", "row", "in", "cursor", ".", "fetchall", "(", ")", "]" ]
https://github.com/AppScale/gts/blob/46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9/AppServer/lib/django-1.3/django/db/backends/mysql/introspection.py#L31-L34
pyparallel/pyparallel
11e8c6072d48c8f13641925d17b147bf36ee0ba3
Lib/lib2to3/fixer_base.py
python
BaseFix.start_tree
(self, tree, filename)
Some fixers need to maintain tree-wide state. This method is called once, at the start of tree fix-up. tree - the root node of the tree to be processed. filename - the name of the file the tree came from.
Some fixers need to maintain tree-wide state. This method is called once, at the start of tree fix-up.
[ "Some", "fixers", "need", "to", "maintain", "tree", "-", "wide", "state", ".", "This", "method", "is", "called", "once", "at", "the", "start", "of", "tree", "fix", "-", "up", "." ]
def start_tree(self, tree, filename): """Some fixers need to maintain tree-wide state. This method is called once, at the start of tree fix-up. tree - the root node of the tree to be processed. filename - the name of the file the tree came from. """ self.used_names = tree.used_names self.set_filename(filename) self.numbers = itertools.count(1) self.first_log = True
[ "def", "start_tree", "(", "self", ",", "tree", ",", "filename", ")", ":", "self", ".", "used_names", "=", "tree", ".", "used_names", "self", ".", "set_filename", "(", "filename", ")", "self", ".", "numbers", "=", "itertools", ".", "count", "(", "1", ")", "self", ".", "first_log", "=", "True" ]
https://github.com/pyparallel/pyparallel/blob/11e8c6072d48c8f13641925d17b147bf36ee0ba3/Lib/lib2to3/fixer_base.py#L148-L158
meraki/dashboard-api-python
aef5e6fe5d23a40d435d5c64ff30580a28af07f1
meraki_v0/aio/api/traffic_analysis_settings.py
python
AsyncTrafficAnalysisSettings.getNetworkTrafficAnalysisSettings
(self, networkId: str)
return await self._session.get(metadata, resource)
**Return the traffic analysis settings for a network** https://developer.cisco.com/meraki/api/#!get-network-traffic-analysis-settings - networkId (string)
**Return the traffic analysis settings for a network** https://developer.cisco.com/meraki/api/#!get-network-traffic-analysis-settings - networkId (string)
[ "**", "Return", "the", "traffic", "analysis", "settings", "for", "a", "network", "**", "https", ":", "//", "developer", ".", "cisco", ".", "com", "/", "meraki", "/", "api", "/", "#!get", "-", "network", "-", "traffic", "-", "analysis", "-", "settings", "-", "networkId", "(", "string", ")" ]
async def getNetworkTrafficAnalysisSettings(self, networkId: str): """ **Return the traffic analysis settings for a network** https://developer.cisco.com/meraki/api/#!get-network-traffic-analysis-settings - networkId (string) """ metadata = { 'tags': ['Traffic analysis settings'], 'operation': 'getNetworkTrafficAnalysisSettings', } resource = f'/networks/{networkId}/trafficAnalysisSettings' return await self._session.get(metadata, resource)
[ "async", "def", "getNetworkTrafficAnalysisSettings", "(", "self", ",", "networkId", ":", "str", ")", ":", "metadata", "=", "{", "'tags'", ":", "[", "'Traffic analysis settings'", "]", ",", "'operation'", ":", "'getNetworkTrafficAnalysisSettings'", ",", "}", "resource", "=", "f'/networks/{networkId}/trafficAnalysisSettings'", "return", "await", "self", ".", "_session", ".", "get", "(", "metadata", ",", "resource", ")" ]
https://github.com/meraki/dashboard-api-python/blob/aef5e6fe5d23a40d435d5c64ff30580a28af07f1/meraki_v0/aio/api/traffic_analysis_settings.py#L6-L20
friends-of-freeswitch/switchio
dee6e9addcf881b2b411ec1dbb397b0acfbb78cf
switchio/apps/measure/__init__.py
python
Measurers.add
(self, app, name=None, operators={}, **kwargs)
return name
[]
def add(self, app, name=None, operators={}, **kwargs): name = name or utils.get_name(app) prepost = getattr(app, 'prepost', None) if not prepost: raise AttributeError( "'{}' must define a `prepost` method".format(name)) args, ppkwargs = utils.get_args(app.prepost) if 'storer' not in ppkwargs: raise TypeError("'{}' must define a 'storer' kwarg" .format(app.prepost)) ppkwargs = {key: kwargs.pop(key) for key in ppkwargs if key in kwargs} # acquire storer factory factory = getattr(app, 'new_storer', None) storer_kwargs = getattr(app, 'storer_kwargs', {}) storer_kwargs.update(kwargs) storer_kwargs.setdefault('storetype', self.storetype) # app may not define a storer factory method storer = storage.DataStorer( name, dtype=app.fields, **storer_kwargs ) if not factory else factory() self._apps[name] = Measurer(app, ppkwargs, storer, {}) # provide attr access off `self.stores` self._stores[name] = storer setattr( self.stores.__class__, name, # make instance lookups access the `data` attr property(partial(storer.__class__.data.__get__, storer)) ) # add any app defined operator functions ops = getattr(app, 'operators', {}) ops.update(operators) for opname, func in ops.items(): self.add_operator(name, func, opname=opname) return name
[ "def", "add", "(", "self", ",", "app", ",", "name", "=", "None", ",", "operators", "=", "{", "}", ",", "*", "*", "kwargs", ")", ":", "name", "=", "name", "or", "utils", ".", "get_name", "(", "app", ")", "prepost", "=", "getattr", "(", "app", ",", "'prepost'", ",", "None", ")", "if", "not", "prepost", ":", "raise", "AttributeError", "(", "\"'{}' must define a `prepost` method\"", ".", "format", "(", "name", ")", ")", "args", ",", "ppkwargs", "=", "utils", ".", "get_args", "(", "app", ".", "prepost", ")", "if", "'storer'", "not", "in", "ppkwargs", ":", "raise", "TypeError", "(", "\"'{}' must define a 'storer' kwarg\"", ".", "format", "(", "app", ".", "prepost", ")", ")", "ppkwargs", "=", "{", "key", ":", "kwargs", ".", "pop", "(", "key", ")", "for", "key", "in", "ppkwargs", "if", "key", "in", "kwargs", "}", "# acquire storer factory", "factory", "=", "getattr", "(", "app", ",", "'new_storer'", ",", "None", ")", "storer_kwargs", "=", "getattr", "(", "app", ",", "'storer_kwargs'", ",", "{", "}", ")", "storer_kwargs", ".", "update", "(", "kwargs", ")", "storer_kwargs", ".", "setdefault", "(", "'storetype'", ",", "self", ".", "storetype", ")", "# app may not define a storer factory method", "storer", "=", "storage", ".", "DataStorer", "(", "name", ",", "dtype", "=", "app", ".", "fields", ",", "*", "*", "storer_kwargs", ")", "if", "not", "factory", "else", "factory", "(", ")", "self", ".", "_apps", "[", "name", "]", "=", "Measurer", "(", "app", ",", "ppkwargs", ",", "storer", ",", "{", "}", ")", "# provide attr access off `self.stores`", "self", ".", "_stores", "[", "name", "]", "=", "storer", "setattr", "(", "self", ".", "stores", ".", "__class__", ",", "name", ",", "# make instance lookups access the `data` attr", "property", "(", "partial", "(", "storer", ".", "__class__", ".", "data", ".", "__get__", ",", "storer", ")", ")", ")", "# add any app defined operator functions", "ops", "=", "getattr", "(", "app", ",", "'operators'", ",", "{", "}", ")", "ops", ".", "update", "(", "operators", ")", "for", "opname", ",", "func", "in", "ops", ".", "items", "(", ")", ":", "self", ".", "add_operator", "(", "name", ",", "func", ",", "opname", "=", "opname", ")", "return", "name" ]
https://github.com/friends-of-freeswitch/switchio/blob/dee6e9addcf881b2b411ec1dbb397b0acfbb78cf/switchio/apps/measure/__init__.py#L63-L100
datamllab/rlcard
c21ea82519c453a42e3bdc6848bd3356e9b6ac43
rlcard/envs/limitholdem.py
python
LimitholdemEnv.get_payoffs
(self)
return self.game.get_payoffs()
Get the payoff of a game Returns: payoffs (list): list of payoffs
Get the payoff of a game
[ "Get", "the", "payoff", "of", "a", "game" ]
def get_payoffs(self): ''' Get the payoff of a game Returns: payoffs (list): list of payoffs ''' return self.game.get_payoffs()
[ "def", "get_payoffs", "(", "self", ")", ":", "return", "self", ".", "game", ".", "get_payoffs", "(", ")" ]
https://github.com/datamllab/rlcard/blob/c21ea82519c453a42e3bdc6848bd3356e9b6ac43/rlcard/envs/limitholdem.py#L73-L79
numenta/nupic
b9ebedaf54f49a33de22d8d44dff7c765cdb5548
src/nupic/algorithms/backtracking_tm_cpp.py
python
BacktrackingTMCPP.finishLearning
(self)
Overrides :meth:`nupic.algorithms.backtracking_tm.BacktrackingTM.finishLearning`.
Overrides :meth:`nupic.algorithms.backtracking_tm.BacktrackingTM.finishLearning`.
[ "Overrides", ":", "meth", ":", "nupic", ".", "algorithms", ".", "backtracking_tm", ".", "BacktrackingTM", ".", "finishLearning", "." ]
def finishLearning(self): """ Overrides :meth:`nupic.algorithms.backtracking_tm.BacktrackingTM.finishLearning`. """ # Keep weakly formed synapses around because they contain confidence scores # for paths out of learned sequenced and produce a better prediction than # chance. self.trimSegments(minPermanence=0.0001)
[ "def", "finishLearning", "(", "self", ")", ":", "# Keep weakly formed synapses around because they contain confidence scores", "# for paths out of learned sequenced and produce a better prediction than", "# chance.", "self", ".", "trimSegments", "(", "minPermanence", "=", "0.0001", ")" ]
https://github.com/numenta/nupic/blob/b9ebedaf54f49a33de22d8d44dff7c765cdb5548/src/nupic/algorithms/backtracking_tm_cpp.py#L444-L451
rowliny/DiffHelper
ab3a96f58f9579d0023aed9ebd785f4edf26f8af
Tool/SitePackages/nltk/cluster/util.py
python
VectorSpaceClusterer.likelihood_vectorspace
(self, vector, cluster)
return 1.0 if cluster == predicted else 0.0
Returns the likelihood of the vector belonging to the cluster.
Returns the likelihood of the vector belonging to the cluster.
[ "Returns", "the", "likelihood", "of", "the", "vector", "belonging", "to", "the", "cluster", "." ]
def likelihood_vectorspace(self, vector, cluster): """ Returns the likelihood of the vector belonging to the cluster. """ predicted = self.classify_vectorspace(vector) return 1.0 if cluster == predicted else 0.0
[ "def", "likelihood_vectorspace", "(", "self", ",", "vector", ",", "cluster", ")", ":", "predicted", "=", "self", ".", "classify_vectorspace", "(", "vector", ")", "return", "1.0", "if", "cluster", "==", "predicted", "else", "0.0" ]
https://github.com/rowliny/DiffHelper/blob/ab3a96f58f9579d0023aed9ebd785f4edf26f8af/Tool/SitePackages/nltk/cluster/util.py#L92-L97
OpenMined/PySyft
f181ca02d307d57bfff9477610358df1a12e3ac9
packages/syft/src/syft/core/common/serde/serialize.py
python
_serialize
( obj: object, to_proto: bool = True, to_bytes: bool = False, )
Serialize the object according to the parameters. This method can be called directly on the syft module:: import syft as sy serialized_obj = sy.serialize(obj=my_object_to_serialize) This is the primary serialization method, which processes the above flags in a particular order. In general, it is not expected that people will set multiple to_<type> flags to True at the same time. We don't currently have logic which prevents this, because this may affect runtime performance, but if several flags are True, then we will simply take return the type of latest supported flag from the following list: - proto - binary TODO: we could also add "dict" to this list but it's not clear if it would be used. :param to_proto: set this flag to TRUE if you want to return a protobuf object :type to_proto: bool :param to_bytes: set this flag to TRUE if you want to return a binary object :type to_bytes: bool :return: a serialized form of the object on which serialize() is called. :rtype: Union[str, bytes, Message]
Serialize the object according to the parameters.
[ "Serialize", "the", "object", "according", "to", "the", "parameters", "." ]
def _serialize( obj: object, to_proto: bool = True, to_bytes: bool = False, ) -> Union[str, bytes, Message]: """Serialize the object according to the parameters. This method can be called directly on the syft module:: import syft as sy serialized_obj = sy.serialize(obj=my_object_to_serialize) This is the primary serialization method, which processes the above flags in a particular order. In general, it is not expected that people will set multiple to_<type> flags to True at the same time. We don't currently have logic which prevents this, because this may affect runtime performance, but if several flags are True, then we will simply take return the type of latest supported flag from the following list: - proto - binary TODO: we could also add "dict" to this list but it's not clear if it would be used. :param to_proto: set this flag to TRUE if you want to return a protobuf object :type to_proto: bool :param to_bytes: set this flag to TRUE if you want to return a binary object :type to_bytes: bool :return: a serialized form of the object on which serialize() is called. :rtype: Union[str, bytes, Message] """ # relative from ....lib.python.primitive_factory import isprimitive # we have an unboxed primitive type so we need to mirror that on deserialize if isprimitive(obj): # relative from ....lib.python.primitive_factory import PrimitiveFactory obj = PrimitiveFactory.generate_primitive(value=obj, temporary_box=True) if hasattr(obj, "temporary_box"): # TODO: can remove this once all of PrimitiveFactory.generate_primitive # supports temporary_box and is tested obj.temporary_box = True # type: ignore if hasattr(obj, "_sy_serializable_wrapper_type"): is_serializable = obj._sy_serializable_wrapper_type(value=obj) # type: ignore else: is_serializable = obj # traceback_and_raise( # Exception( # f"Object {type(obj)} is not serializable and has no _sy_serializable_wrapper_type" # ) # ) if to_bytes: # debug(f"Serializing {type(is_serializable)}") # indent=None means no white space or \n in the serialized version # this is compatible with json.dumps(x, indent=None) serialized_data = is_serializable._object2proto().SerializeToString() blob: Message = DataMessage( obj_type=get_fully_qualified_name(obj=is_serializable), content=serialized_data, ) return validate_type(blob.SerializeToString(), bytes) elif to_proto: return validate_type(is_serializable._object2proto(), Message) else: traceback_and_raise( Exception( """You must specify at least one deserialization format using one of the arguments of the serialize() method such as: to_proto, to_bytes.""" ) )
[ "def", "_serialize", "(", "obj", ":", "object", ",", "to_proto", ":", "bool", "=", "True", ",", "to_bytes", ":", "bool", "=", "False", ",", ")", "->", "Union", "[", "str", ",", "bytes", ",", "Message", "]", ":", "# relative", "from", ".", ".", ".", ".", "lib", ".", "python", ".", "primitive_factory", "import", "isprimitive", "# we have an unboxed primitive type so we need to mirror that on deserialize", "if", "isprimitive", "(", "obj", ")", ":", "# relative", "from", ".", ".", ".", ".", "lib", ".", "python", ".", "primitive_factory", "import", "PrimitiveFactory", "obj", "=", "PrimitiveFactory", ".", "generate_primitive", "(", "value", "=", "obj", ",", "temporary_box", "=", "True", ")", "if", "hasattr", "(", "obj", ",", "\"temporary_box\"", ")", ":", "# TODO: can remove this once all of PrimitiveFactory.generate_primitive", "# supports temporary_box and is tested", "obj", ".", "temporary_box", "=", "True", "# type: ignore", "if", "hasattr", "(", "obj", ",", "\"_sy_serializable_wrapper_type\"", ")", ":", "is_serializable", "=", "obj", ".", "_sy_serializable_wrapper_type", "(", "value", "=", "obj", ")", "# type: ignore", "else", ":", "is_serializable", "=", "obj", "# traceback_and_raise(", "# Exception(", "# f\"Object {type(obj)} is not serializable and has no _sy_serializable_wrapper_type\"", "# )", "# )", "if", "to_bytes", ":", "# debug(f\"Serializing {type(is_serializable)}\")", "# indent=None means no white space or \\n in the serialized version", "# this is compatible with json.dumps(x, indent=None)", "serialized_data", "=", "is_serializable", ".", "_object2proto", "(", ")", ".", "SerializeToString", "(", ")", "blob", ":", "Message", "=", "DataMessage", "(", "obj_type", "=", "get_fully_qualified_name", "(", "obj", "=", "is_serializable", ")", ",", "content", "=", "serialized_data", ",", ")", "return", "validate_type", "(", "blob", ".", "SerializeToString", "(", ")", ",", "bytes", ")", "elif", "to_proto", ":", "return", "validate_type", "(", "is_serializable", ".", "_object2proto", "(", ")", ",", "Message", ")", "else", ":", "traceback_and_raise", "(", "Exception", "(", "\"\"\"You must specify at least one deserialization format using\n one of the arguments of the serialize() method such as:\n to_proto, to_bytes.\"\"\"", ")", ")" ]
https://github.com/OpenMined/PySyft/blob/f181ca02d307d57bfff9477610358df1a12e3ac9/packages/syft/src/syft/core/common/serde/serialize.py#L14-L90
jython/frozen-mirror
b8d7aa4cee50c0c0fe2f4b235dd62922dd0f3f99
lib-python/2.7/cookielib.py
python
escape_path
(path)
return path
Escape any invalid characters in HTTP URL, and uppercase all escapes.
Escape any invalid characters in HTTP URL, and uppercase all escapes.
[ "Escape", "any", "invalid", "characters", "in", "HTTP", "URL", "and", "uppercase", "all", "escapes", "." ]
def escape_path(path): """Escape any invalid characters in HTTP URL, and uppercase all escapes.""" # There's no knowing what character encoding was used to create URLs # containing %-escapes, but since we have to pick one to escape invalid # path characters, we pick UTF-8, as recommended in the HTML 4.0 # specification: # http://www.w3.org/TR/REC-html40/appendix/notes.html#h-B.2.1 # And here, kind of: draft-fielding-uri-rfc2396bis-03 # (And in draft IRI specification: draft-duerst-iri-05) # (And here, for new URI schemes: RFC 2718) if isinstance(path, unicode): path = path.encode("utf-8") path = urllib.quote(path, HTTP_PATH_SAFE) path = ESCAPED_CHAR_RE.sub(uppercase_escaped_char, path) return path
[ "def", "escape_path", "(", "path", ")", ":", "# There's no knowing what character encoding was used to create URLs", "# containing %-escapes, but since we have to pick one to escape invalid", "# path characters, we pick UTF-8, as recommended in the HTML 4.0", "# specification:", "# http://www.w3.org/TR/REC-html40/appendix/notes.html#h-B.2.1", "# And here, kind of: draft-fielding-uri-rfc2396bis-03", "# (And in draft IRI specification: draft-duerst-iri-05)", "# (And here, for new URI schemes: RFC 2718)", "if", "isinstance", "(", "path", ",", "unicode", ")", ":", "path", "=", "path", ".", "encode", "(", "\"utf-8\"", ")", "path", "=", "urllib", ".", "quote", "(", "path", ",", "HTTP_PATH_SAFE", ")", "path", "=", "ESCAPED_CHAR_RE", ".", "sub", "(", "uppercase_escaped_char", ",", "path", ")", "return", "path" ]
https://github.com/jython/frozen-mirror/blob/b8d7aa4cee50c0c0fe2f4b235dd62922dd0f3f99/lib-python/2.7/cookielib.py#L639-L653
home-assistant/core
265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1
homeassistant/components/qnap/sensor.py
python
QNAPDriveSensor.extra_state_attributes
(self)
Return the state attributes.
Return the state attributes.
[ "Return", "the", "state", "attributes", "." ]
def extra_state_attributes(self): """Return the state attributes.""" if self._api.data: data = self._api.data["smart_drive_health"][self.monitor_device] return { ATTR_DRIVE: data["drive_number"], ATTR_MODEL: data["model"], ATTR_SERIAL: data["serial"], ATTR_TYPE: data["type"], }
[ "def", "extra_state_attributes", "(", "self", ")", ":", "if", "self", ".", "_api", ".", "data", ":", "data", "=", "self", ".", "_api", ".", "data", "[", "\"smart_drive_health\"", "]", "[", "self", ".", "monitor_device", "]", "return", "{", "ATTR_DRIVE", ":", "data", "[", "\"drive_number\"", "]", ",", "ATTR_MODEL", ":", "data", "[", "\"model\"", "]", ",", "ATTR_SERIAL", ":", "data", "[", "\"serial\"", "]", ",", "ATTR_TYPE", ":", "data", "[", "\"type\"", "]", ",", "}" ]
https://github.com/home-assistant/core/blob/265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1/homeassistant/components/qnap/sensor.py#L462-L471
bcj/AttrDict
8c1883162178a124ee29144ca7abcd83cbd9d222
attrdict/default.py
python
AttrDefault.__len__
(self)
return len(self._mapping)
Check the length of the mapping.
Check the length of the mapping.
[ "Check", "the", "length", "of", "the", "mapping", "." ]
def __len__(self): """ Check the length of the mapping. """ return len(self._mapping)
[ "def", "__len__", "(", "self", ")", ":", "return", "len", "(", "self", ".", "_mapping", ")" ]
https://github.com/bcj/AttrDict/blob/8c1883162178a124ee29144ca7abcd83cbd9d222/attrdict/default.py#L63-L67
geekori/pyqt5
49b2538fa5afe43b3b2bdadaa0560d0d6ef4924c
src/dialogs/QColorDialog.py
python
QColorDialogDemo.getBGColor
(self)
[]
def getBGColor(self): color = QColorDialog.getColor() p = QPalette() p.setColor(QPalette.Window,color) self.colorLabel.setAutoFillBackground(True) self.colorLabel.setPalette(p)
[ "def", "getBGColor", "(", "self", ")", ":", "color", "=", "QColorDialog", ".", "getColor", "(", ")", "p", "=", "QPalette", "(", ")", "p", ".", "setColor", "(", "QPalette", ".", "Window", ",", "color", ")", "self", ".", "colorLabel", ".", "setAutoFillBackground", "(", "True", ")", "self", ".", "colorLabel", ".", "setPalette", "(", "p", ")" ]
https://github.com/geekori/pyqt5/blob/49b2538fa5afe43b3b2bdadaa0560d0d6ef4924c/src/dialogs/QColorDialog.py#L44-L49
gramps-project/gramps
04d4651a43eb210192f40a9f8c2bad8ee8fa3753
gramps/gen/datehandler/_dateparser.py
python
DateParser.match_range
(self, text, cal, ny, qual, date)
return 0
Try matching range date. On success, set the date and return 1. On failure return 0.
Try matching range date.
[ "Try", "matching", "range", "date", "." ]
def match_range(self, text, cal, ny, qual, date): """ Try matching range date. On success, set the date and return 1. On failure return 0. """ match = self._range.match(text) if match: text_parser = self.parser[cal] (text1, bc1) = self.match_bce(match.group('start')) start = self._parse_subdate(text1, text_parser, cal) if start == Date.EMPTY and text1 != "": return 0 if bc1: start = self.invert_year(start) (text2, bc2) = self.match_bce(match.group('stop')) stop = self._parse_subdate(text2, text_parser, cal) if stop == Date.EMPTY and text2 != "": return 0 if bc2: stop = self.invert_year(stop) date.set(qual, Date.MOD_RANGE, cal, start + stop, newyear=ny) return 1 return 0
[ "def", "match_range", "(", "self", ",", "text", ",", "cal", ",", "ny", ",", "qual", ",", "date", ")", ":", "match", "=", "self", ".", "_range", ".", "match", "(", "text", ")", "if", "match", ":", "text_parser", "=", "self", ".", "parser", "[", "cal", "]", "(", "text1", ",", "bc1", ")", "=", "self", ".", "match_bce", "(", "match", ".", "group", "(", "'start'", ")", ")", "start", "=", "self", ".", "_parse_subdate", "(", "text1", ",", "text_parser", ",", "cal", ")", "if", "start", "==", "Date", ".", "EMPTY", "and", "text1", "!=", "\"\"", ":", "return", "0", "if", "bc1", ":", "start", "=", "self", ".", "invert_year", "(", "start", ")", "(", "text2", ",", "bc2", ")", "=", "self", ".", "match_bce", "(", "match", ".", "group", "(", "'stop'", ")", ")", "stop", "=", "self", ".", "_parse_subdate", "(", "text2", ",", "text_parser", ",", "cal", ")", "if", "stop", "==", "Date", ".", "EMPTY", "and", "text2", "!=", "\"\"", ":", "return", "0", "if", "bc2", ":", "stop", "=", "self", ".", "invert_year", "(", "stop", ")", "date", ".", "set", "(", "qual", ",", "Date", ".", "MOD_RANGE", ",", "cal", ",", "start", "+", "stop", ",", "newyear", "=", "ny", ")", "return", "1", "return", "0" ]
https://github.com/gramps-project/gramps/blob/04d4651a43eb210192f40a9f8c2bad8ee8fa3753/gramps/gen/datehandler/_dateparser.py#L812-L837
ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework
cb692f527e4e819b6c228187c5702d990a180043
external/Scripting Engine/Xenotix Python Scripting Engine/packages/IronPython.StdLib.2.7.4/content/Lib/shutil.py
python
_make_zipfile
(base_name, base_dir, verbose=0, dry_run=0, logger=None)
return zip_filename
Create a zip file from all the files under 'base_dir'. The output zip file will be named 'base_name' + ".zip". Uses either the "zipfile" Python module (if available) or the InfoZIP "zip" utility (if installed and found on the default search path). If neither tool is available, raises ExecError. Returns the name of the output zip file.
Create a zip file from all the files under 'base_dir'.
[ "Create", "a", "zip", "file", "from", "all", "the", "files", "under", "base_dir", "." ]
def _make_zipfile(base_name, base_dir, verbose=0, dry_run=0, logger=None): """Create a zip file from all the files under 'base_dir'. The output zip file will be named 'base_name' + ".zip". Uses either the "zipfile" Python module (if available) or the InfoZIP "zip" utility (if installed and found on the default search path). If neither tool is available, raises ExecError. Returns the name of the output zip file. """ zip_filename = base_name + ".zip" archive_dir = os.path.dirname(base_name) if not os.path.exists(archive_dir): if logger is not None: logger.info("creating %s", archive_dir) if not dry_run: os.makedirs(archive_dir) # If zipfile module is not available, try spawning an external 'zip' # command. try: import zipfile except ImportError: zipfile = None if zipfile is None: _call_external_zip(base_dir, zip_filename, verbose, dry_run) else: if logger is not None: logger.info("creating '%s' and adding '%s' to it", zip_filename, base_dir) if not dry_run: zip = zipfile.ZipFile(zip_filename, "w", compression=zipfile.ZIP_DEFLATED) for dirpath, dirnames, filenames in os.walk(base_dir): for name in filenames: path = os.path.normpath(os.path.join(dirpath, name)) if os.path.isfile(path): zip.write(path, path) if logger is not None: logger.info("adding '%s'", path) zip.close() return zip_filename
[ "def", "_make_zipfile", "(", "base_name", ",", "base_dir", ",", "verbose", "=", "0", ",", "dry_run", "=", "0", ",", "logger", "=", "None", ")", ":", "zip_filename", "=", "base_name", "+", "\".zip\"", "archive_dir", "=", "os", ".", "path", ".", "dirname", "(", "base_name", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "archive_dir", ")", ":", "if", "logger", "is", "not", "None", ":", "logger", ".", "info", "(", "\"creating %s\"", ",", "archive_dir", ")", "if", "not", "dry_run", ":", "os", ".", "makedirs", "(", "archive_dir", ")", "# If zipfile module is not available, try spawning an external 'zip'", "# command.", "try", ":", "import", "zipfile", "except", "ImportError", ":", "zipfile", "=", "None", "if", "zipfile", "is", "None", ":", "_call_external_zip", "(", "base_dir", ",", "zip_filename", ",", "verbose", ",", "dry_run", ")", "else", ":", "if", "logger", "is", "not", "None", ":", "logger", ".", "info", "(", "\"creating '%s' and adding '%s' to it\"", ",", "zip_filename", ",", "base_dir", ")", "if", "not", "dry_run", ":", "zip", "=", "zipfile", ".", "ZipFile", "(", "zip_filename", ",", "\"w\"", ",", "compression", "=", "zipfile", ".", "ZIP_DEFLATED", ")", "for", "dirpath", ",", "dirnames", ",", "filenames", "in", "os", ".", "walk", "(", "base_dir", ")", ":", "for", "name", "in", "filenames", ":", "path", "=", "os", ".", "path", ".", "normpath", "(", "os", ".", "path", ".", "join", "(", "dirpath", ",", "name", ")", ")", "if", "os", ".", "path", ".", "isfile", "(", "path", ")", ":", "zip", ".", "write", "(", "path", ",", "path", ")", "if", "logger", "is", "not", "None", ":", "logger", ".", "info", "(", "\"adding '%s'\"", ",", "path", ")", "zip", ".", "close", "(", ")", "return", "zip_filename" ]
https://github.com/ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework/blob/cb692f527e4e819b6c228187c5702d990a180043/external/Scripting Engine/Xenotix Python Scripting Engine/packages/IronPython.StdLib.2.7.4/content/Lib/shutil.py#L412-L457
apache/tvm
6eb4ed813ebcdcd9558f0906a1870db8302ff1e0
python/tvm/relay/op/tensor.py
python
concatenate
(data, axis)
return _make.concatenate(Tuple(data), axis)
Concatenate the input tensors along the given axis. Parameters ---------- data : Union(List[relay.Expr], Tuple[relay.Expr]) A list of tensors. axis : int The axis along which the tensors are concatenated. Returns ------- result: relay.Expr The concatenated tensor.
Concatenate the input tensors along the given axis.
[ "Concatenate", "the", "input", "tensors", "along", "the", "given", "axis", "." ]
def concatenate(data, axis): """Concatenate the input tensors along the given axis. Parameters ---------- data : Union(List[relay.Expr], Tuple[relay.Expr]) A list of tensors. axis : int The axis along which the tensors are concatenated. Returns ------- result: relay.Expr The concatenated tensor. """ data = list(data) if not data: raise ValueError("relay.concatenate requires data to be non-empty.") if not isinstance(axis, int): raise ValueError("For now, we only support integer axis") return _make.concatenate(Tuple(data), axis)
[ "def", "concatenate", "(", "data", ",", "axis", ")", ":", "data", "=", "list", "(", "data", ")", "if", "not", "data", ":", "raise", "ValueError", "(", "\"relay.concatenate requires data to be non-empty.\"", ")", "if", "not", "isinstance", "(", "axis", ",", "int", ")", ":", "raise", "ValueError", "(", "\"For now, we only support integer axis\"", ")", "return", "_make", ".", "concatenate", "(", "Tuple", "(", "data", ")", ",", "axis", ")" ]
https://github.com/apache/tvm/blob/6eb4ed813ebcdcd9558f0906a1870db8302ff1e0/python/tvm/relay/op/tensor.py#L1093-L1113
sdaps/sdaps
51d1072185223f5e48512661e2c1e8399d63e876
sdaps/setup/buddies.py
python
Head.validate
(self)
[]
def validate(self): if not self.obj.title: log.warn(_('Head %(l0)i got no title.') % {'l0': self.obj.id[0]})
[ "def", "validate", "(", "self", ")", ":", "if", "not", "self", ".", "obj", ".", "title", ":", "log", ".", "warn", "(", "_", "(", "'Head %(l0)i got no title.'", ")", "%", "{", "'l0'", ":", "self", ".", "obj", ".", "id", "[", "0", "]", "}", ")" ]
https://github.com/sdaps/sdaps/blob/51d1072185223f5e48512661e2c1e8399d63e876/sdaps/setup/buddies.py#L60-L62
golismero/golismero
7d605b937e241f51c1ca4f47b20f755eeefb9d76
tools/sqlmap/thirdparty/odict/odict.py
python
_OrderedDict.insert
(self, index, key, value)
Takes ``index``, ``key``, and ``value`` as arguments. Sets ``key`` to ``value``, so that ``key`` is at position ``index`` in the OrderedDict. >>> d = OrderedDict(((1, 3), (3, 2), (2, 1))) >>> d.insert(0, 4, 0) >>> d OrderedDict([(4, 0), (1, 3), (3, 2), (2, 1)]) >>> d.insert(0, 2, 1) >>> d OrderedDict([(2, 1), (4, 0), (1, 3), (3, 2)]) >>> d.insert(8, 8, 1) >>> d OrderedDict([(2, 1), (4, 0), (1, 3), (3, 2), (8, 1)])
Takes ``index``, ``key``, and ``value`` as arguments.
[ "Takes", "index", "key", "and", "value", "as", "arguments", "." ]
def insert(self, index, key, value): """ Takes ``index``, ``key``, and ``value`` as arguments. Sets ``key`` to ``value``, so that ``key`` is at position ``index`` in the OrderedDict. >>> d = OrderedDict(((1, 3), (3, 2), (2, 1))) >>> d.insert(0, 4, 0) >>> d OrderedDict([(4, 0), (1, 3), (3, 2), (2, 1)]) >>> d.insert(0, 2, 1) >>> d OrderedDict([(2, 1), (4, 0), (1, 3), (3, 2)]) >>> d.insert(8, 8, 1) >>> d OrderedDict([(2, 1), (4, 0), (1, 3), (3, 2), (8, 1)]) """ if key in self: # FIXME: efficiency? del self[key] self._sequence.insert(index, key) dict.__setitem__(self, key, value)
[ "def", "insert", "(", "self", ",", "index", ",", "key", ",", "value", ")", ":", "if", "key", "in", "self", ":", "# FIXME: efficiency?", "del", "self", "[", "key", "]", "self", ".", "_sequence", ".", "insert", "(", "index", ",", "key", ")", "dict", ".", "__setitem__", "(", "self", ",", "key", ",", "value", ")" ]
https://github.com/golismero/golismero/blob/7d605b937e241f51c1ca4f47b20f755eeefb9d76/tools/sqlmap/thirdparty/odict/odict.py#L823-L845
peterbrittain/asciimatics
9a490faddf484ee5b9b845316f921f5888b23b18
samples/maps.py
python
Map._zoom_map
(self, zoom_out=True)
Animate the zoom in/out as appropriate for the displayed map tile.
Animate the zoom in/out as appropriate for the displayed map tile.
[ "Animate", "the", "zoom", "in", "/", "out", "as", "appropriate", "for", "the", "displayed", "map", "tile", "." ]
def _zoom_map(self, zoom_out=True): """Animate the zoom in/out as appropriate for the displayed map tile.""" size_step = 1 / _ZOOM_STEP if zoom_out else _ZOOM_STEP self._next_update = 1 if self._satellite: size_step **= _ZOOM_ANIMATION_STEPS self._size *= size_step if self._size <= _ZOOM_OUT_SIZE: if self._zoom > 0: self._zoom -= 1 self._size = _START_SIZE else: self._size = _ZOOM_OUT_SIZE elif self._size >= _ZOOM_IN_SIZE: if self._zoom < 20: self._zoom += 1 self._size = _START_SIZE else: self._size = _ZOOM_IN_SIZE
[ "def", "_zoom_map", "(", "self", ",", "zoom_out", "=", "True", ")", ":", "size_step", "=", "1", "/", "_ZOOM_STEP", "if", "zoom_out", "else", "_ZOOM_STEP", "self", ".", "_next_update", "=", "1", "if", "self", ".", "_satellite", ":", "size_step", "**=", "_ZOOM_ANIMATION_STEPS", "self", ".", "_size", "*=", "size_step", "if", "self", ".", "_size", "<=", "_ZOOM_OUT_SIZE", ":", "if", "self", ".", "_zoom", ">", "0", ":", "self", ".", "_zoom", "-=", "1", "self", ".", "_size", "=", "_START_SIZE", "else", ":", "self", ".", "_size", "=", "_ZOOM_OUT_SIZE", "elif", "self", ".", "_size", ">=", "_ZOOM_IN_SIZE", ":", "if", "self", ".", "_zoom", "<", "20", ":", "self", ".", "_zoom", "+=", "1", "self", ".", "_size", "=", "_START_SIZE", "else", ":", "self", ".", "_size", "=", "_ZOOM_IN_SIZE" ]
https://github.com/peterbrittain/asciimatics/blob/9a490faddf484ee5b9b845316f921f5888b23b18/samples/maps.py#L406-L424
cloudera/impyla
0c736af4cad2bade9b8e313badc08ec50e81c948
impala/_thrift_gen/beeswax/ttypes.py
python
QueryHandle.__ne__
(self, other)
return not (self == other)
[]
def __ne__(self, other): return not (self == other)
[ "def", "__ne__", "(", "self", ",", "other", ")", ":", "return", "not", "(", "self", "==", "other", ")" ]
https://github.com/cloudera/impyla/blob/0c736af4cad2bade9b8e313badc08ec50e81c948/impala/_thrift_gen/beeswax/ttypes.py#L219-L220
ales-tsurko/cells
4cf7e395cd433762bea70cdc863a346f3a6fe1d0
packaging/macos/python/lib/python3.7/ipaddress.py
python
IPv6Address.is_private
(self)
return any(self in net for net in self._constants._private_networks)
Test if this address is allocated for private networks. Returns: A boolean, True if the address is reserved per iana-ipv6-special-registry.
Test if this address is allocated for private networks.
[ "Test", "if", "this", "address", "is", "allocated", "for", "private", "networks", "." ]
def is_private(self): """Test if this address is allocated for private networks. Returns: A boolean, True if the address is reserved per iana-ipv6-special-registry. """ return any(self in net for net in self._constants._private_networks)
[ "def", "is_private", "(", "self", ")", ":", "return", "any", "(", "self", "in", "net", "for", "net", "in", "self", ".", "_constants", ".", "_private_networks", ")" ]
https://github.com/ales-tsurko/cells/blob/4cf7e395cd433762bea70cdc863a346f3a6fe1d0/packaging/macos/python/lib/python3.7/ipaddress.py#L1966-L1974
home-assistant/core
265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1
homeassistant/components/climate/__init__.py
python
ClimateEntity.fan_modes
(self)
return self._attr_fan_modes
Return the list of available fan modes. Requires SUPPORT_FAN_MODE.
Return the list of available fan modes.
[ "Return", "the", "list", "of", "available", "fan", "modes", "." ]
def fan_modes(self) -> list[str] | None: """Return the list of available fan modes. Requires SUPPORT_FAN_MODE. """ return self._attr_fan_modes
[ "def", "fan_modes", "(", "self", ")", "->", "list", "[", "str", "]", "|", "None", ":", "return", "self", ".", "_attr_fan_modes" ]
https://github.com/home-assistant/core/blob/265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1/homeassistant/components/climate/__init__.py#L415-L420