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
malwaredllc/byob
3924dd6aea6d0421397cdf35f692933b340bfccf
web-gui/buildyourownbotnet/core/util.py
python
public_ip
()
return urlopen('http://api.ipify.org').read().decode()
Return public IP address of host machine
Return public IP address of host machine
[ "Return", "public", "IP", "address", "of", "host", "machine" ]
def public_ip(): """ Return public IP address of host machine """ import sys if sys.version_info[0] > 2: from urllib.request import urlopen else: from urllib import urlopen return urlopen('http://api.ipify.org').read().decode()
[ "def", "public_ip", "(", ")", ":", "import", "sys", "if", "sys", ".", "version_info", "[", "0", "]", ">", "2", ":", "from", "urllib", ".", "request", "import", "urlopen", "else", ":", "from", "urllib", "import", "urlopen", "return", "urlopen", "(", "'h...
https://github.com/malwaredllc/byob/blob/3924dd6aea6d0421397cdf35f692933b340bfccf/web-gui/buildyourownbotnet/core/util.py#L74-L84
OCA/l10n-spain
99050907670a70307fcd8cdfb6f3400d9e120df4
l10n_es_vat_book/models/l10n_es_vat_book.py
python
L10nEsVatBook._prepare_vat_book_tax_summary
(self, tax_lines, book_type)
return tax_summary_data_recs
[]
def _prepare_vat_book_tax_summary(self, tax_lines, book_type): tax_summary_data_recs = {} for tax_line in tax_lines: if tax_line.tax_id not in tax_summary_data_recs: tax_summary_data_recs[tax_line.tax_id] = { "book_type": book_type, "base_amount": 0.0, "tax_amount": 0.0, "total_amount": 0.0, "tax_id": tax_line.tax_id.id, "vat_book_id": self.id, "special_tax_group": tax_line.special_tax_group, } tax_summary_data_recs[tax_line.tax_id][ "base_amount" ] += tax_line.base_amount tax_summary_data_recs[tax_line.tax_id]["tax_amount"] += tax_line.tax_amount tax_summary_data_recs[tax_line.tax_id][ "total_amount" ] += tax_line.total_amount return tax_summary_data_recs
[ "def", "_prepare_vat_book_tax_summary", "(", "self", ",", "tax_lines", ",", "book_type", ")", ":", "tax_summary_data_recs", "=", "{", "}", "for", "tax_line", "in", "tax_lines", ":", "if", "tax_line", ".", "tax_id", "not", "in", "tax_summary_data_recs", ":", "tax...
https://github.com/OCA/l10n-spain/blob/99050907670a70307fcd8cdfb6f3400d9e120df4/l10n_es_vat_book/models/l10n_es_vat_book.py#L121-L141
mozillazg/pypy
2ff5cd960c075c991389f842c6d59e71cf0cb7d0
pypy/objspace/std/bytearrayobject.py
python
BytearrayDocstrings.__init__
()
x.__init__(...) initializes x; see help(type(x)) for signature
x.__init__(...) initializes x; see help(type(x)) for signature
[ "x", ".", "__init__", "(", "...", ")", "initializes", "x", ";", "see", "help", "(", "type", "(", "x", "))", "for", "signature" ]
def __init__(): """x.__init__(...) initializes x; see help(type(x)) for signature"""
[ "def", "__init__", "(", ")", ":" ]
https://github.com/mozillazg/pypy/blob/2ff5cd960c075c991389f842c6d59e71cf0cb7d0/pypy/objspace/std/bytearrayobject.py#L691-L692
pwnieexpress/pwn_plug_sources
1a23324f5dc2c3de20f9c810269b6a29b2758cad
src/metagoofil/pdfminer/pdffont.py
python
PDFFont.decode
(self, bytes)
return map(ord, bytes)
[]
def decode(self, bytes): return map(ord, bytes)
[ "def", "decode", "(", "self", ",", "bytes", ")", ":", "return", "map", "(", "ord", ",", "bytes", ")" ]
https://github.com/pwnieexpress/pwn_plug_sources/blob/1a23324f5dc2c3de20f9c810269b6a29b2758cad/src/metagoofil/pdfminer/pdffont.py#L472-L473
telegraphic/hickle
a5aac2db4e236d90990e3387c5822b466e8e84fa
hickle/lookup.py
python
ExpandReferenceContainer.convert
(self)
return self._content[0]
returns the object the reference was pointing to
returns the object the reference was pointing to
[ "returns", "the", "object", "the", "reference", "was", "pointing", "to" ]
def convert(self): """ returns the object the reference was pointing to """ return self._content[0]
[ "def", "convert", "(", "self", ")", ":", "return", "self", ".", "_content", "[", "0", "]" ]
https://github.com/telegraphic/hickle/blob/a5aac2db4e236d90990e3387c5822b466e8e84fa/hickle/lookup.py#L1447-L1452
tendenci/tendenci
0f2c348cc0e7d41bc56f50b00ce05544b083bf1d
tendenci/apps/recurring_payments/authnet/cim.py
python
CIMCustomerPaymentProfile.delete
(self, **kwargs)
return self.process_request(xml_root)
Delete a customer payment profile from an existing customer profile. Input fields: ref_id - optional customer_profile_id customer_payment_profile_id Output fields: ref_id - if included in the input
Delete a customer payment profile from an existing customer profile.
[ "Delete", "a", "customer", "payment", "profile", "from", "an", "existing", "customer", "profile", "." ]
def delete(self, **kwargs): """ Delete a customer payment profile from an existing customer profile. Input fields: ref_id - optional customer_profile_id customer_payment_profile_id Output fields: ref_id - if included in the input """ if not self.customer_profile_id or not self.customer_payment_profile_id: raise AttributeError(_("Missing customer_profile_id or customer_payment_profile_id.")) root_name = 'deleteCustomerPaymentProfileRequest' xml_root = self.create_base_xml(root_name) customer_profile_id_node = ET.SubElement(xml_root, 'customerProfileId') customer_profile_id_node.text = self.customer_profile_id customer_payment_profile_id_node = ET.SubElement(xml_root, 'customerPaymentProfileId') customer_payment_profile_id_node.text = self.customer_payment_profile_id return self.process_request(xml_root)
[ "def", "delete", "(", "self", ",", "*", "*", "kwargs", ")", ":", "if", "not", "self", ".", "customer_profile_id", "or", "not", "self", ".", "customer_payment_profile_id", ":", "raise", "AttributeError", "(", "_", "(", "\"Missing customer_profile_id or customer_pay...
https://github.com/tendenci/tendenci/blob/0f2c348cc0e7d41bc56f50b00ce05544b083bf1d/tendenci/apps/recurring_payments/authnet/cim.py#L526-L551
feedly/transfer-nlp
85515b73165c299b7a9b96d3608bd4e8ee567154
transfer_nlp/embeddings/utils.py
python
pretty_print
(results: List[Tuple[str, torch.Tensor]])
Pretty print embedding results.
Pretty print embedding results.
[ "Pretty", "print", "embedding", "results", "." ]
def pretty_print(results: List[Tuple[str, torch.Tensor]]): """ Pretty print embedding results. """ for item in results: print("...[%.2f] - %s" % (item[1], item[0]))
[ "def", "pretty_print", "(", "results", ":", "List", "[", "Tuple", "[", "str", ",", "torch", ".", "Tensor", "]", "]", ")", ":", "for", "item", "in", "results", ":", "print", "(", "\"...[%.2f] - %s\"", "%", "(", "item", "[", "1", "]", ",", "item", "[...
https://github.com/feedly/transfer-nlp/blob/85515b73165c299b7a9b96d3608bd4e8ee567154/transfer_nlp/embeddings/utils.py#L6-L11
baidu/Senta
e5294c00a6ffc4b1284f38000f0fbf24d6554c22
pretraining.py
python
PretrainingTrainer.__init__
(self, params, data_set_reader, model_class)
:param params: :param data_set_reader: :param model_class:
:param params: :param data_set_reader: :param model_class:
[ ":", "param", "params", ":", ":", "param", "data_set_reader", ":", ":", "param", "model_class", ":" ]
def __init__(self, params, data_set_reader, model_class): """ :param params: :param data_set_reader: :param model_class: """ BaseTrainer.__init__(self, params, data_set_reader, model_class)
[ "def", "__init__", "(", "self", ",", "params", ",", "data_set_reader", ",", "model_class", ")", ":", "BaseTrainer", ".", "__init__", "(", "self", ",", "params", ",", "data_set_reader", ",", "model_class", ")" ]
https://github.com/baidu/Senta/blob/e5294c00a6ffc4b1284f38000f0fbf24d6554c22/pretraining.py#L146-L152
google/grr
8ad8a4d2c5a93c92729206b7771af19d92d4f915
grr/server/grr_response_server/gui/api_call_router_with_approval_checks.py
python
ApiCallRouterWithApprovalChecks.CreateHuntApproval
(self, args, context=None)
return self.delegate.CreateHuntApproval(args, context=context)
[]
def CreateHuntApproval(self, args, context=None): # Everybody can request a hunt approval. return self.delegate.CreateHuntApproval(args, context=context)
[ "def", "CreateHuntApproval", "(", "self", ",", "args", ",", "context", "=", "None", ")", ":", "# Everybody can request a hunt approval.", "return", "self", ".", "delegate", ".", "CreateHuntApproval", "(", "args", ",", "context", "=", "context", ")" ]
https://github.com/google/grr/blob/8ad8a4d2c5a93c92729206b7771af19d92d4f915/grr/server/grr_response_server/gui/api_call_router_with_approval_checks.py#L742-L745
TencentCloud/tencentcloud-sdk-python
3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2
tencentcloud/tke/v20180525/models.py
python
DeleteClusterRouteTableRequest.__init__
(self)
r""" :param RouteTableName: 路由表名称 :type RouteTableName: str
r""" :param RouteTableName: 路由表名称 :type RouteTableName: str
[ "r", ":", "param", "RouteTableName", ":", "路由表名称", ":", "type", "RouteTableName", ":", "str" ]
def __init__(self): r""" :param RouteTableName: 路由表名称 :type RouteTableName: str """ self.RouteTableName = None
[ "def", "__init__", "(", "self", ")", ":", "self", ".", "RouteTableName", "=", "None" ]
https://github.com/TencentCloud/tencentcloud-sdk-python/blob/3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2/tencentcloud/tke/v20180525/models.py#L2946-L2951
Pymol-Scripts/Pymol-script-repo
bcd7bb7812dc6db1595953dfa4471fa15fb68c77
modules/pdb2pqr/contrib/numpy-1.1.0/numpy/distutils/system_info.py
python
system_info.check_libs
(self,lib_dir,libs,opt_libs =[])
return info
If static or shared libraries are available then return their info dictionary. Checks for all libraries as shared libraries first, then static (or vice versa if self.search_static_first is True).
If static or shared libraries are available then return their info dictionary.
[ "If", "static", "or", "shared", "libraries", "are", "available", "then", "return", "their", "info", "dictionary", "." ]
def check_libs(self,lib_dir,libs,opt_libs =[]): """If static or shared libraries are available then return their info dictionary. Checks for all libraries as shared libraries first, then static (or vice versa if self.search_static_first is True). """ exts = self.library_extensions() info = None for ext in exts: info = self._check_libs(lib_dir,libs,opt_libs,[ext]) if info is not None: break if not info: log.info(' libraries %s not found in %s', ','.join(libs), lib_dir) return info
[ "def", "check_libs", "(", "self", ",", "lib_dir", ",", "libs", ",", "opt_libs", "=", "[", "]", ")", ":", "exts", "=", "self", ".", "library_extensions", "(", ")", "info", "=", "None", "for", "ext", "in", "exts", ":", "info", "=", "self", ".", "_che...
https://github.com/Pymol-Scripts/Pymol-script-repo/blob/bcd7bb7812dc6db1595953dfa4471fa15fb68c77/modules/pdb2pqr/contrib/numpy-1.1.0/numpy/distutils/system_info.py#L523-L538
chribsen/simple-machine-learning-examples
dc94e52a4cebdc8bb959ff88b81ff8cfeca25022
venv/lib/python2.7/site-packages/scipy/interpolate/fitpack2.py
python
SphereBivariateSpline.__call__
(self, theta, phi, dtheta=0, dphi=0, grid=True)
return _BivariateSplineBase.__call__(self, theta, phi, dx=dtheta, dy=dphi, grid=grid)
Evaluate the spline or its derivatives at given positions. Parameters ---------- theta, phi : array_like Input coordinates. If `grid` is False, evaluate the spline at points ``(theta[i], phi[i]), i=0, ..., len(x)-1``. Standard Numpy broadcasting is obeyed. If `grid` is True: evaluate spline at the grid points defined by the coordinate arrays theta, phi. The arrays must be sorted to increasing order. dtheta : int, optional Order of theta-derivative .. versionadded:: 0.14.0 dphi : int Order of phi-derivative .. versionadded:: 0.14.0 grid : bool Whether to evaluate the results on a grid spanned by the input arrays, or at points specified by the input arrays. .. versionadded:: 0.14.0
Evaluate the spline or its derivatives at given positions.
[ "Evaluate", "the", "spline", "or", "its", "derivatives", "at", "given", "positions", "." ]
def __call__(self, theta, phi, dtheta=0, dphi=0, grid=True): """ Evaluate the spline or its derivatives at given positions. Parameters ---------- theta, phi : array_like Input coordinates. If `grid` is False, evaluate the spline at points ``(theta[i], phi[i]), i=0, ..., len(x)-1``. Standard Numpy broadcasting is obeyed. If `grid` is True: evaluate spline at the grid points defined by the coordinate arrays theta, phi. The arrays must be sorted to increasing order. dtheta : int, optional Order of theta-derivative .. versionadded:: 0.14.0 dphi : int Order of phi-derivative .. versionadded:: 0.14.0 grid : bool Whether to evaluate the results on a grid spanned by the input arrays, or at points specified by the input arrays. .. versionadded:: 0.14.0 """ theta = np.asarray(theta) phi = np.asarray(phi) if theta.size > 0 and (theta.min() < 0. or theta.max() > np.pi): raise ValueError("requested theta out of bounds.") if phi.size > 0 and (phi.min() < 0. or phi.max() > 2. * np.pi): raise ValueError("requested phi out of bounds.") return _BivariateSplineBase.__call__(self, theta, phi, dx=dtheta, dy=dphi, grid=grid)
[ "def", "__call__", "(", "self", ",", "theta", ",", "phi", ",", "dtheta", "=", "0", ",", "dphi", "=", "0", ",", "grid", "=", "True", ")", ":", "theta", "=", "np", ".", "asarray", "(", "theta", ")", "phi", "=", "np", ".", "asarray", "(", "phi", ...
https://github.com/chribsen/simple-machine-learning-examples/blob/dc94e52a4cebdc8bb959ff88b81ff8cfeca25022/venv/lib/python2.7/site-packages/scipy/interpolate/fitpack2.py#L1221-L1261
oracle/oci-python-sdk
3c1604e4e212008fb6718e2f68cdb5ef71fd5793
src/oci/_vendor/urllib3/_collections.py
python
HTTPHeaderDict.__setitem__
(self, key, val)
return self._container[key.lower()]
[]
def __setitem__(self, key, val): self._container[key.lower()] = [key, val] return self._container[key.lower()]
[ "def", "__setitem__", "(", "self", ",", "key", ",", "val", ")", ":", "self", ".", "_container", "[", "key", ".", "lower", "(", ")", "]", "=", "[", "key", ",", "val", "]", "return", "self", ".", "_container", "[", "key", ".", "lower", "(", ")", ...
https://github.com/oracle/oci-python-sdk/blob/3c1604e4e212008fb6718e2f68cdb5ef71fd5793/src/oci/_vendor/urllib3/_collections.py#L157-L159
vaguileradiaz/tinfoleak
c45c33ec8faaff8cf8be4423e1d52533d8a45a96
tinfoleak.py
python
get_information_for_timeline
()
Search info about the global timeline
Search info about the global timeline
[ "Search", "info", "about", "the", "global", "timeline" ]
def get_information_for_timeline(): """Search info about the global timeline""" try: source = Sources() hashtag = Hashtags() mentions = Mentions() user_images = User_Images() geolocation = Geolocation() user = User() search = Search_GeoTweets() user_tweets = User_Tweets() user_conversations = User_Conversations() user_relations = User_Relations() social_networks = Social_Networks() followers = Followers() friends = Friends() lists = Lists() collections = Collections() favorites = Favorites() top_words = Words_Tweets() activity = Activity() coordinates = ui.tb_place_lat.text() + "," + ui.tb_place_lon.text() + "," + ui.tb_place_km.text() + "km" show_ui_message("Looking info at <b>global timeline</b>:", "INFO", 1) show_ui_message("Getting timeline information...", "INFO", 1) tmp_api = api.get_user("vaguileradiaz") user.set_user_information(tmp_api) results = search.set_search_information(hashtag, mentions, user_images, user_tweets, source, activity, top_words) show_ui_message("Timeline information: OK", "INFO", 1) if results: if ui.cb_hashtags.isChecked(): hashtag.set_global_information() if ui.cb_mentions.isChecked(): mentions.set_global_information() if ui.cb_source_apps.isChecked(): # Get info about the source apps show_ui_message("Getting source apps...", "INFO", br=1) source.set_global_information() show_ui_message("Source apps: OK", "INFO", br=1) if ui.cb_activity.isChecked(): # Get info about the user activity show_ui_message("Getting user activity...", "INFO", br=1) activity.set_global_information() show_ui_message("User activity: OK", "INFO", br=1) if ui.cb_words_frequency.isChecked(): # Get words most used if not ui.tb_words_frequency_number.text(): show_alert_field(field=ui.tb_words_frequency_number, message="You need to specify a words number", type="WARNING", br=1) else: show_ui_message("Getting words...", "INFO", br=1) wordlist = sorted(top_words.top_words.items(), key=operator.itemgetter(1)) wordlist.reverse() max = int(ui.tb_words_frequency_number.text()) if max > len(wordlist) - 1: max = len(wordlist) - 1 top_words.ordered_words = wordlist[0:max] for n in top_words.ordered_words: top_words.total_occurrences += n[1] show_ui_message("Words: OK", "INFO", br=1) parameters = Parameters() show_ui_message("Generating report...", "INFO", 1) # Generates HTML file generates_HTML_file(parameters, user, source, social_networks, hashtag, mentions, geolocation, user_images, user_tweets, search, user_conversations, favorites, top_words, activity, user_relations) strPath = os.path.dirname(os.path.abspath(__file__)) strDir = parameters.html_output_directory strFile = str(ui.tb_report_filename.text()) html_dir = strPath + "/" + strDir + "/" + strFile show_ui_message("Report: OK", "INFO", 1) show_ui_message("Your HTML report: <b>" + html_dir + "</b><br>", "INFO", 1) except Exception as e: show_ui_message(str(e) + "<br>", "ERROR", 1)
[ "def", "get_information_for_timeline", "(", ")", ":", "try", ":", "source", "=", "Sources", "(", ")", "hashtag", "=", "Hashtags", "(", ")", "mentions", "=", "Mentions", "(", ")", "user_images", "=", "User_Images", "(", ")", "geolocation", "=", "Geolocation",...
https://github.com/vaguileradiaz/tinfoleak/blob/c45c33ec8faaff8cf8be4423e1d52533d8a45a96/tinfoleak.py#L4128-L4214
daid/LegacyCura
eceece558df51845988bed55a4e667638654f7c4
Cura/avr_isp/stk500v2.py
python
main
()
Entry point to call the stk500v2 programmer from the commandline.
Entry point to call the stk500v2 programmer from the commandline.
[ "Entry", "point", "to", "call", "the", "stk500v2", "programmer", "from", "the", "commandline", "." ]
def main(): """ Entry point to call the stk500v2 programmer from the commandline. """ import threading if sys.argv[1] == 'AUTO': print portList() for port in portList(): threading.Thread(target=runProgrammer, args=(port,sys.argv[2])).start() time.sleep(5) else: programmer = Stk500v2() programmer.connect(port = sys.argv[1]) programmer.programChip(intelHex.readHex(sys.argv[2])) sys.exit(1)
[ "def", "main", "(", ")", ":", "import", "threading", "if", "sys", ".", "argv", "[", "1", "]", "==", "'AUTO'", ":", "print", "portList", "(", ")", "for", "port", "in", "portList", "(", ")", ":", "threading", ".", "Thread", "(", "target", "=", "runPr...
https://github.com/daid/LegacyCura/blob/eceece558df51845988bed55a4e667638654f7c4/Cura/avr_isp/stk500v2.py#L201-L213
spesmilo/electrum
bdbd59300fbd35b01605e66145458e5f396108e8
electrum/gui/qt/util.py
python
ElectrumItemDelegate.__init__
(self, tv: 'MyTreeView')
[]
def __init__(self, tv: 'MyTreeView'): super().__init__(tv) self.tv = tv self.opened = None def on_closeEditor(editor: QLineEdit, hint): self.opened = None self.tv.is_editor_open = False if self.tv._pending_update: self.tv.update() def on_commitData(editor: QLineEdit): new_text = editor.text() idx = QModelIndex(self.opened) row, col = idx.row(), idx.column() edit_key = self.tv.get_edit_key_from_coordinate(row, col) assert edit_key is not None, (idx.row(), idx.column()) self.tv.on_edited(idx, edit_key=edit_key, text=new_text) self.closeEditor.connect(on_closeEditor) self.commitData.connect(on_commitData)
[ "def", "__init__", "(", "self", ",", "tv", ":", "'MyTreeView'", ")", ":", "super", "(", ")", ".", "__init__", "(", "tv", ")", "self", ".", "tv", "=", "tv", "self", ".", "opened", "=", "None", "def", "on_closeEditor", "(", "editor", ":", "QLineEdit", ...
https://github.com/spesmilo/electrum/blob/bdbd59300fbd35b01605e66145458e5f396108e8/electrum/gui/qt/util.py#L498-L515
mudpi/mudpi-core
fb206b1136f529c7197f1e6b29629ed05630d377
mudpi/extensions/char_display/__init__.py
python
CharDisplay.get_next_message
(self)
return self.cached_message if self.persist_display else \ {'message': '', 'duration': 1}
Get the next message from queue
Get the next message from queue
[ "Get", "the", "next", "message", "from", "queue" ]
def get_next_message(self): """ Get the next message from queue """ if len(self.queue) > 0: self.message_expired = False self.reset_duration() return self.queue.pop(0) self.cached_message['duration'] = 1 self.message_expired = False self.reset_duration() return self.cached_message if self.persist_display else \ {'message': '', 'duration': 1}
[ "def", "get_next_message", "(", "self", ")", ":", "if", "len", "(", "self", ".", "queue", ")", ">", "0", ":", "self", ".", "message_expired", "=", "False", "self", ".", "reset_duration", "(", ")", "return", "self", ".", "queue", ".", "pop", "(", "0",...
https://github.com/mudpi/mudpi-core/blob/fb206b1136f529c7197f1e6b29629ed05630d377/mudpi/extensions/char_display/__init__.py#L201-L211
yuxiaokui/Intranet-Penetration
f57678a204840c83cbf3308e3470ae56c5ff514b
proxy/XX-Net/code/default/gae_proxy/server/lib/google/appengine/api/appinfo.py
python
ValidateHandlers
(handlers, is_include_file=False)
Validates a list of handler (URLMap) objects. Args: handlers: A list of a handler (URLMap) objects. is_include_file: If true, indicates the we are performing validation for handlers in an AppInclude file, which may contain special directives.
Validates a list of handler (URLMap) objects.
[ "Validates", "a", "list", "of", "handler", "(", "URLMap", ")", "objects", "." ]
def ValidateHandlers(handlers, is_include_file=False): """Validates a list of handler (URLMap) objects. Args: handlers: A list of a handler (URLMap) objects. is_include_file: If true, indicates the we are performing validation for handlers in an AppInclude file, which may contain special directives. """ if not handlers: return for handler in handlers: handler.FixSecureDefaults() handler.WarnReservedURLs() if not is_include_file: handler.ErrorOnPositionForAppInfo()
[ "def", "ValidateHandlers", "(", "handlers", ",", "is_include_file", "=", "False", ")", ":", "if", "not", "handlers", ":", "return", "for", "handler", "in", "handlers", ":", "handler", ".", "FixSecureDefaults", "(", ")", "handler", ".", "WarnReservedURLs", "(",...
https://github.com/yuxiaokui/Intranet-Penetration/blob/f57678a204840c83cbf3308e3470ae56c5ff514b/proxy/XX-Net/code/default/gae_proxy/server/lib/google/appengine/api/appinfo.py#L2145-L2160
n1nj4sec/pupy
a5d766ea81fdfe3bc2c38c9bdaf10e9b75af3b39
pupy/packages/all/pupyutils/netcreds.py
python
Netcreds.get_http_searches
(self, http_url_req, body, host)
Find search terms from URLs. Prone to false positives but rather err on that side than false negatives search, query, ?s, &q, ?q, search?p, searchTerm, keywords, command
Find search terms from URLs. Prone to false positives but rather err on that side than false negatives search, query, ?s, &q, ?q, search?p, searchTerm, keywords, command
[ "Find", "search", "terms", "from", "URLs", ".", "Prone", "to", "false", "positives", "but", "rather", "err", "on", "that", "side", "than", "false", "negatives", "search", "query", "?s", "&q", "?q", "search?p", "searchTerm", "keywords", "command" ]
def get_http_searches(self, http_url_req, body, host): ''' Find search terms from URLs. Prone to false positives but rather err on that side than false negatives search, query, ?s, &q, ?q, search?p, searchTerm, keywords, command ''' false_pos = ['i.stack.imgur.com'] searched = None if http_url_req is not None: searched = re.search(http_search_re, http_url_req, re.IGNORECASE) if searched is None: searched = re.search(http_search_re, body, re.IGNORECASE) if searched is not None and host not in false_pos: searched = searched.group(3) # Eliminate some false+ try: # if it doesn't decode to utf8 it's probably not user input searched = searched.decode('utf8') except UnicodeDecodeError: return # some add sites trigger this function with single digits if searched in [str(num) for num in range(0,10)]: return # nobody's making >100 character searches if len(searched) > 100: return msg = 'Searched %s: %s' % (host, unquote(searched.encode('utf8')).replace('+', ' ')) return msg
[ "def", "get_http_searches", "(", "self", ",", "http_url_req", ",", "body", ",", "host", ")", ":", "false_pos", "=", "[", "'i.stack.imgur.com'", "]", "searched", "=", "None", "if", "http_url_req", "is", "not", "None", ":", "searched", "=", "re", ".", "searc...
https://github.com/n1nj4sec/pupy/blob/a5d766ea81fdfe3bc2c38c9bdaf10e9b75af3b39/pupy/packages/all/pupyutils/netcreds.py#L692-L720
kubernetes-client/python
47b9da9de2d02b2b7a34fbe05afb44afd130d73a
kubernetes/client/models/v1_service_status.py
python
V1ServiceStatus.__eq__
(self, other)
return self.to_dict() == other.to_dict()
Returns true if both objects are equal
Returns true if both objects are equal
[ "Returns", "true", "if", "both", "objects", "are", "equal" ]
def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, V1ServiceStatus): return False return self.to_dict() == other.to_dict()
[ "def", "__eq__", "(", "self", ",", "other", ")", ":", "if", "not", "isinstance", "(", "other", ",", "V1ServiceStatus", ")", ":", "return", "False", "return", "self", ".", "to_dict", "(", ")", "==", "other", ".", "to_dict", "(", ")" ]
https://github.com/kubernetes-client/python/blob/47b9da9de2d02b2b7a34fbe05afb44afd130d73a/kubernetes/client/models/v1_service_status.py#L136-L141
Fizzadar/pyinfra
ff0913d6a172966760b63fe59e55dff9ea852e0d
pyinfra/api/connectors/sshuserclient/client.py
python
SSHClient.connect
( self, hostname, _pyinfra_force_forward_agent=None, _pyinfra_ssh_config_file=None, **kwargs )
[]
def connect( self, hostname, _pyinfra_force_forward_agent=None, _pyinfra_ssh_config_file=None, **kwargs ): hostname, config, forward_agent = self.parse_config( hostname, kwargs, ssh_config_file=_pyinfra_ssh_config_file, ) config.update(kwargs) super(SSHClient, self).connect(hostname, **config) if _pyinfra_force_forward_agent is not None: forward_agent = _pyinfra_force_forward_agent if forward_agent: # Enable SSH forwarding session = self.get_transport().open_session() AgentRequestHandler(session)
[ "def", "connect", "(", "self", ",", "hostname", ",", "_pyinfra_force_forward_agent", "=", "None", ",", "_pyinfra_ssh_config_file", "=", "None", ",", "*", "*", "kwargs", ")", ":", "hostname", ",", "config", ",", "forward_agent", "=", "self", ".", "parse_config"...
https://github.com/Fizzadar/pyinfra/blob/ff0913d6a172966760b63fe59e55dff9ea852e0d/pyinfra/api/connectors/sshuserclient/client.py#L38-L59
omz/PythonistaAppTemplate
f560f93f8876d82a21d108977f90583df08d55af
PythonistaAppTemplate/PythonistaKit.framework/pylib/site-packages/werkzeug/debug/tbtools.py
python
Frame.sourcelines
(self)
return source.decode(charset, 'replace').splitlines()
The sourcecode of the file as list of unicode strings.
The sourcecode of the file as list of unicode strings.
[ "The", "sourcecode", "of", "the", "file", "as", "list", "of", "unicode", "strings", "." ]
def sourcelines(self): """The sourcecode of the file as list of unicode strings.""" # get sourcecode from loader or file source = None if self.loader is not None: try: if hasattr(self.loader, 'get_source'): source = self.loader.get_source(self.module) elif hasattr(self.loader, 'get_source_by_code'): source = self.loader.get_source_by_code(self.code) except Exception: # we munch the exception so that we don't cause troubles # if the loader is broken. pass if source is None: try: f = open(self.filename) except IOError: return [] try: source = f.read() finally: f.close() # already unicode? return right away if isinstance(source, text_type): return source.splitlines() # yes. it should be ascii, but we don't want to reject too many # characters in the debugger if something breaks charset = 'utf-8' if source.startswith(UTF8_COOKIE): source = source[3:] else: for idx, match in enumerate(_line_re.finditer(source)): match = _line_re.search(match.group()) if match is not None: charset = match.group(1) break if idx > 1: break # on broken cookies we fall back to utf-8 too try: codecs.lookup(charset) except LookupError: charset = 'utf-8' return source.decode(charset, 'replace').splitlines()
[ "def", "sourcelines", "(", "self", ")", ":", "# get sourcecode from loader or file", "source", "=", "None", "if", "self", ".", "loader", "is", "not", "None", ":", "try", ":", "if", "hasattr", "(", "self", ".", "loader", ",", "'get_source'", ")", ":", "sour...
https://github.com/omz/PythonistaAppTemplate/blob/f560f93f8876d82a21d108977f90583df08d55af/PythonistaAppTemplate/PythonistaKit.framework/pylib/site-packages/werkzeug/debug/tbtools.py#L446-L495
SamSchott/maestral
a32653bac7b5a76cb326d4fd5a4fb2c11f19a2fc
src/maestral/client.py
python
DropboxClient.namespace_id
(self)
return self._namespace_id
The namespace ID of the path root currently used by the DropboxClient. All file paths will be interpreted as relative to the root namespace. Use :meth:`update_path_root` to update the root namespace after the user joins or leaves a team with a Team Space.
The namespace ID of the path root currently used by the DropboxClient. All file paths will be interpreted as relative to the root namespace. Use :meth:`update_path_root` to update the root namespace after the user joins or leaves a team with a Team Space.
[ "The", "namespace", "ID", "of", "the", "path", "root", "currently", "used", "by", "the", "DropboxClient", ".", "All", "file", "paths", "will", "be", "interpreted", "as", "relative", "to", "the", "root", "namespace", ".", "Use", ":", "meth", ":", "update_pa...
def namespace_id(self) -> str: """The namespace ID of the path root currently used by the DropboxClient. All file paths will be interpreted as relative to the root namespace. Use :meth:`update_path_root` to update the root namespace after the user joins or leaves a team with a Team Space.""" return self._namespace_id
[ "def", "namespace_id", "(", "self", ")", "->", "str", ":", "return", "self", ".", "_namespace_id" ]
https://github.com/SamSchott/maestral/blob/a32653bac7b5a76cb326d4fd5a4fb2c11f19a2fc/src/maestral/client.py#L348-L353
demisto/content
5c664a65b992ac8ca90ac3f11b1b2cdf11ee9b07
Packs/MongoDB/Integrations/MongoDBLog/MongoDBLog.py
python
read_log_json
()
return 'MongoDB - no documents/records - Log collection is empty', {}, {}
Get all log documents/records from MondoDB
Get all log documents/records from MondoDB
[ "Get", "all", "log", "documents", "/", "records", "from", "MondoDB" ]
def read_log_json(): """ Get all log documents/records from MondoDB """ limit = int(demisto.args().get('limit')) # Point to all the documents cursor = COLLECTION.find({}, {'_id': False}).limit(limit) # Create an empty log list entries = [] # Iterate through those documents if cursor is not None: for i in cursor: # Append log entry to list entries.append(i) return_json = {COLLECTION_NAME: entries} human_readable = tableToMarkdown(f'The log documents/records for collection "{COLLECTION_NAME}"', return_json) return human_readable, {}, {} return 'MongoDB - no documents/records - Log collection is empty', {}, {}
[ "def", "read_log_json", "(", ")", ":", "limit", "=", "int", "(", "demisto", ".", "args", "(", ")", ".", "get", "(", "'limit'", ")", ")", "# Point to all the documents", "cursor", "=", "COLLECTION", ".", "find", "(", "{", "}", ",", "{", "'_id'", ":", ...
https://github.com/demisto/content/blob/5c664a65b992ac8ca90ac3f11b1b2cdf11ee9b07/Packs/MongoDB/Integrations/MongoDBLog/MongoDBLog.py#L81-L96
Nuitka/Nuitka
39262276993757fa4e299f497654065600453fc9
nuitka/build/inline_copy/lib/scons-3.1.2/SCons/Executor.py
python
get_NullEnvironment
()
return nullenv
Use singleton pattern for Null Environments.
Use singleton pattern for Null Environments.
[ "Use", "singleton", "pattern", "for", "Null", "Environments", "." ]
def get_NullEnvironment(): """Use singleton pattern for Null Environments.""" global nullenv if nullenv is None: nullenv = NullEnvironment() return nullenv
[ "def", "get_NullEnvironment", "(", ")", ":", "global", "nullenv", "if", "nullenv", "is", "None", ":", "nullenv", "=", "NullEnvironment", "(", ")", "return", "nullenv" ]
https://github.com/Nuitka/Nuitka/blob/39262276993757fa4e299f497654065600453fc9/nuitka/build/inline_copy/lib/scons-3.1.2/SCons/Executor.py#L584-L590
iduta/iresnet
babdc4f5946f64905710cd64a5bd6c164a805c9e
models/iresnet.py
python
iresnet200
(pretrained=False, **kwargs)
return model
Constructs a iResNet-200 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet
Constructs a iResNet-200 model.
[ "Constructs", "a", "iResNet", "-", "200", "model", "." ]
def iresnet200(pretrained=False, **kwargs): """Constructs a iResNet-200 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ model = iResNet(Bottleneck, [3, 24, 36, 3], **kwargs) if pretrained: os.makedirs(default_cache_path, exist_ok=True) model.load_state_dict(torch.load(download_from_url(model_urls['iresnet200'], root=default_cache_path))) return model
[ "def", "iresnet200", "(", "pretrained", "=", "False", ",", "*", "*", "kwargs", ")", ":", "model", "=", "iResNet", "(", "Bottleneck", ",", "[", "3", ",", "24", ",", "36", ",", "3", "]", ",", "*", "*", "kwargs", ")", "if", "pretrained", ":", "os", ...
https://github.com/iduta/iresnet/blob/babdc4f5946f64905710cd64a5bd6c164a805c9e/models/iresnet.py#L340-L351
plaid/plaid-python
8c60fca608e426f3ff30da8857775946d29e122c
plaid/model/processor_balance_get_response.py
python
ProcessorBalanceGetResponse.__init__
(self, account, request_id, *args, **kwargs)
ProcessorBalanceGetResponse - a model defined in OpenAPI Args: account (AccountBase): request_id (str): A unique identifier for the request, which can be used for troubleshooting. This identifier, like all Plaid identifiers, is case sensitive. Keyword Args: _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be raised if the wrong type is input. Defaults to True _path_to_item (tuple/list): This is a list of keys or values to drill down to the model in received_data when deserializing a response _spec_property_naming (bool): True if the variable names in the input data are serialized names, as specified in the OpenAPI document. False if the variable names in the input data are pythonic names, e.g. snake case (default) _configuration (Configuration): the instance to use when deserializing a file_type parameter. If passed, type conversion is attempted If omitted no type conversion is done. _visited_composed_classes (tuple): This stores a tuple of classes that we have traveled through so that if we see that class again we will not use its discriminator again. When traveling through a discriminator, the composed schema that is is traveled through is added to this set. For example if Animal has a discriminator petType and we pass in "Dog", and the class Dog allOf includes Animal, we move through Animal once using the discriminator, and pick Dog. Then in Dog, we will make an instance of the Animal class but this time we won't travel through its discriminator because we passed in _visited_composed_classes = (Animal,)
ProcessorBalanceGetResponse - a model defined in OpenAPI
[ "ProcessorBalanceGetResponse", "-", "a", "model", "defined", "in", "OpenAPI" ]
def __init__(self, account, request_id, *args, **kwargs): # noqa: E501 """ProcessorBalanceGetResponse - a model defined in OpenAPI Args: account (AccountBase): request_id (str): A unique identifier for the request, which can be used for troubleshooting. This identifier, like all Plaid identifiers, is case sensitive. Keyword Args: _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be raised if the wrong type is input. Defaults to True _path_to_item (tuple/list): This is a list of keys or values to drill down to the model in received_data when deserializing a response _spec_property_naming (bool): True if the variable names in the input data are serialized names, as specified in the OpenAPI document. False if the variable names in the input data are pythonic names, e.g. snake case (default) _configuration (Configuration): the instance to use when deserializing a file_type parameter. If passed, type conversion is attempted If omitted no type conversion is done. _visited_composed_classes (tuple): This stores a tuple of classes that we have traveled through so that if we see that class again we will not use its discriminator again. When traveling through a discriminator, the composed schema that is is traveled through is added to this set. For example if Animal has a discriminator petType and we pass in "Dog", and the class Dog allOf includes Animal, we move through Animal once using the discriminator, and pick Dog. Then in Dog, we will make an instance of the Animal class but this time we won't travel through its discriminator because we passed in _visited_composed_classes = (Animal,) """ _check_type = kwargs.pop('_check_type', True) _spec_property_naming = kwargs.pop('_spec_property_naming', False) _path_to_item = kwargs.pop('_path_to_item', ()) _configuration = kwargs.pop('_configuration', None) _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) if args: raise ApiTypeError( "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( args, self.__class__.__name__, ), path_to_item=_path_to_item, valid_classes=(self.__class__,), ) self._data_store = {} self._check_type = _check_type self._spec_property_naming = _spec_property_naming self._path_to_item = _path_to_item self._configuration = _configuration self._visited_composed_classes = _visited_composed_classes + (self.__class__,) self.account = account self.request_id = request_id for var_name, var_value in kwargs.items(): if var_name not in self.attribute_map and \ self._configuration is not None and \ self._configuration.discard_unknown_keys and \ self.additional_properties_type is None: # discard variable. continue setattr(self, var_name, var_value)
[ "def", "__init__", "(", "self", ",", "account", ",", "request_id", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "_check_type", "=", "kwargs", ".", "pop", "(", "'_check_type'", ",", "True", ")", "_spec_property_naming", "=", "kwargs"...
https://github.com/plaid/plaid-python/blob/8c60fca608e426f3ff30da8857775946d29e122c/plaid/model/processor_balance_get_response.py#L111-L183
demisto/content
5c664a65b992ac8ca90ac3f11b1b2cdf11ee9b07
Packs/PrismaCloudCompute/Integrations/PaloAltoNetworks_PrismaCloudCompute/PaloAltoNetworks_PrismaCloudCompute.py
python
get_container_profile_list
(client: PrismaCloudComputeClient, args: dict)
return CommandResults( outputs_prefix='PrismaCloudCompute.ProfileContainer', outputs_key_field='_id', outputs=containers_info, readable_output=table, raw_response=containers_info )
Get information about the containers and their profile events. Implement the command 'prisma-cloud-compute-profile-container-list' Args: client (PrismaCloudComputeClient): prisma-cloud-compute client. args (dict): prisma-cloud-compute-profile-container-list command arguments. Returns: CommandResults: command-results object.
Get information about the containers and their profile events. Implement the command 'prisma-cloud-compute-profile-container-list'
[ "Get", "information", "about", "the", "containers", "and", "their", "profile", "events", ".", "Implement", "the", "command", "prisma", "-", "cloud", "-", "compute", "-", "profile", "-", "container", "-", "list" ]
def get_container_profile_list(client: PrismaCloudComputeClient, args: dict) -> CommandResults: """ Get information about the containers and their profile events. Implement the command 'prisma-cloud-compute-profile-container-list' Args: client (PrismaCloudComputeClient): prisma-cloud-compute client. args (dict): prisma-cloud-compute-profile-container-list command arguments. Returns: CommandResults: command-results object. """ if "image_id" in args: args["imageID"] = args.pop("image_id") args["limit"], args["offset"] = parse_limit_and_offset_values( limit=args.get("limit", "15"), offset=args.get("offset", "0") ) if containers_info := client.get_container_profiles(params=assign_params(**args)): container_description_headers = ["ContainerID", "Image", "Os", "State", "Created", "EntryPoint"] if len(containers_info) == 1: # means we have only one container container_info = containers_info[0] container_description_table = tableToMarkdown( name="Container Description", t=get_container_description_info(container_info=container_info), headers=container_description_headers, removeNull=True ) processes_table = tableToMarkdown( name="Processes", t=[ { "Type": process_type, "Md5": process.get("md5"), "Path": process.get("path"), "DetectionTime": parse_date_string_format(date_string=process.get("time")) } for process_type in ["static", "behavioral"] for process in container_info.get("processes", {}).get(process_type, "") ], headers=["Type", "Path", "DetectionTime", "Md5"], removeNull=True ) table = container_description_table + processes_table else: table = tableToMarkdown( name="Container Description", t=[get_container_description_info(container_info=container_info) for container_info in containers_info], headers=container_description_headers, removeNull=True ) else: table = "No results found." return CommandResults( outputs_prefix='PrismaCloudCompute.ProfileContainer', outputs_key_field='_id', outputs=containers_info, readable_output=table, raw_response=containers_info )
[ "def", "get_container_profile_list", "(", "client", ":", "PrismaCloudComputeClient", ",", "args", ":", "dict", ")", "->", "CommandResults", ":", "if", "\"image_id\"", "in", "args", ":", "args", "[", "\"imageID\"", "]", "=", "args", ".", "pop", "(", "\"image_id...
https://github.com/demisto/content/blob/5c664a65b992ac8ca90ac3f11b1b2cdf11ee9b07/Packs/PrismaCloudCompute/Integrations/PaloAltoNetworks_PrismaCloudCompute/PaloAltoNetworks_PrismaCloudCompute.py#L653-L716
3b1b/manim
3ffe300f9625fea563553c4f7d16cbee81e4844e
manimlib/utils/color.py
python
get_colormap_list
(map_name="viridis", n_colors=9)
return resize_with_interpolation(np.array(rgbs), n_colors)
Options for map_name: 3b1b_colormap magma inferno plasma viridis cividis twilight twilight_shifted turbo
Options for map_name: 3b1b_colormap magma inferno plasma viridis cividis twilight twilight_shifted turbo
[ "Options", "for", "map_name", ":", "3b1b_colormap", "magma", "inferno", "plasma", "viridis", "cividis", "twilight", "twilight_shifted", "turbo" ]
def get_colormap_list(map_name="viridis", n_colors=9): """ Options for map_name: 3b1b_colormap magma inferno plasma viridis cividis twilight twilight_shifted turbo """ from matplotlib.cm import get_cmap if map_name == "3b1b_colormap": rgbs = [color_to_rgb(color) for color in COLORMAP_3B1B] else: rgbs = get_cmap(map_name).colors # Make more general? return resize_with_interpolation(np.array(rgbs), n_colors)
[ "def", "get_colormap_list", "(", "map_name", "=", "\"viridis\"", ",", "n_colors", "=", "9", ")", ":", "from", "matplotlib", ".", "cm", "import", "get_cmap", "if", "map_name", "==", "\"3b1b_colormap\"", ":", "rgbs", "=", "[", "color_to_rgb", "(", "color", ")"...
https://github.com/3b1b/manim/blob/3ffe300f9625fea563553c4f7d16cbee81e4844e/manimlib/utils/color.py#L118-L137
CGCookie/retopoflow
3d8b3a47d1d661f99ab0aeb21d31370bf15de35e
retopoflow/rf/rf_ui.py
python
RetopoFlow_UI.update_main_tiny_ui_windows
(self)
[]
def update_main_tiny_ui_windows(self): if self.ui_hide: return pre = self._ui_windows_updating self._ui_windows_updating = True self.ui_main.is_visible = options['show main window'] self.ui_tiny.is_visible = not options['show main window'] self._ui_windows_updating = pre
[ "def", "update_main_tiny_ui_windows", "(", "self", ")", ":", "if", "self", ".", "ui_hide", ":", "return", "pre", "=", "self", ".", "_ui_windows_updating", "self", ".", "_ui_windows_updating", "=", "True", "self", ".", "ui_main", ".", "is_visible", "=", "option...
https://github.com/CGCookie/retopoflow/blob/3d8b3a47d1d661f99ab0aeb21d31370bf15de35e/retopoflow/rf/rf_ui.py#L260-L267
trakt/Plex-Trakt-Scrobbler
aeb0bfbe62fad4b06c164f1b95581da7f35dce0b
Trakttv.bundle/Contents/Libraries/Linux/armv5_hf/ucs4/cryptography/x509/base.py
python
CertificateBuilder.public_key
(self, key)
return CertificateBuilder( self._issuer_name, self._subject_name, key, self._serial_number, self._not_valid_before, self._not_valid_after, self._extensions )
Sets the requestor's public key (as found in the signing request).
Sets the requestor's public key (as found in the signing request).
[ "Sets", "the", "requestor", "s", "public", "key", "(", "as", "found", "in", "the", "signing", "request", ")", "." ]
def public_key(self, key): """ Sets the requestor's public key (as found in the signing request). """ if not isinstance(key, (dsa.DSAPublicKey, rsa.RSAPublicKey, ec.EllipticCurvePublicKey)): raise TypeError('Expecting one of DSAPublicKey, RSAPublicKey,' ' or EllipticCurvePublicKey.') if self._public_key is not None: raise ValueError('The public key may only be set once.') return CertificateBuilder( self._issuer_name, self._subject_name, key, self._serial_number, self._not_valid_before, self._not_valid_after, self._extensions )
[ "def", "public_key", "(", "self", ",", "key", ")", ":", "if", "not", "isinstance", "(", "key", ",", "(", "dsa", ".", "DSAPublicKey", ",", "rsa", ".", "RSAPublicKey", ",", "ec", ".", "EllipticCurvePublicKey", ")", ")", ":", "raise", "TypeError", "(", "'...
https://github.com/trakt/Plex-Trakt-Scrobbler/blob/aeb0bfbe62fad4b06c164f1b95581da7f35dce0b/Trakttv.bundle/Contents/Libraries/Linux/armv5_hf/ucs4/cryptography/x509/base.py#L418-L432
Pymol-Scripts/Pymol-script-repo
bcd7bb7812dc6db1595953dfa4471fa15fb68c77
modules/pdb2pqr/contrib/ZSI-2.1-a1/ZSI/twisted/client.py
python
Binding.Receive
(self, replytype, chain=None, **kw)
return pyobj
This method allows code to act in a synchronous manner, it waits to return until the deferred fires but it doesn't prevent other queued calls from being executed. Send must be called first, which sets up the chain/factory. WARNING: If defer is set to True, must either call Receive immediately after Send (ie. no intervening Sends) or pass chain in as a paramter. Parameters: replytype -- TypeCode KeyWord Parameters: chain -- processing chain, optional
This method allows code to act in a synchronous manner, it waits to return until the deferred fires but it doesn't prevent other queued calls from being executed. Send must be called first, which sets up the chain/factory. WARNING: If defer is set to True, must either call Receive immediately after Send (ie. no intervening Sends) or pass chain in as a paramter. Parameters: replytype -- TypeCode KeyWord Parameters: chain -- processing chain, optional
[ "This", "method", "allows", "code", "to", "act", "in", "a", "synchronous", "manner", "it", "waits", "to", "return", "until", "the", "deferred", "fires", "but", "it", "doesn", "t", "prevent", "other", "queued", "calls", "from", "being", "executed", ".", "Se...
def Receive(self, replytype, chain=None, **kw): """This method allows code to act in a synchronous manner, it waits to return until the deferred fires but it doesn't prevent other queued calls from being executed. Send must be called first, which sets up the chain/factory. WARNING: If defer is set to True, must either call Receive immediately after Send (ie. no intervening Sends) or pass chain in as a paramter. Parameters: replytype -- TypeCode KeyWord Parameters: chain -- processing chain, optional """ chain = chain or self.chain d = chain.flow.deferred if self.trace: def trace(soapdata): print >>self.trace, "_" * 33, time.ctime(time.time()), "RESPONSE:" print >>self.trace, soapdata return soapdata d.addCallback(trace) chain.processResponse(d, replytype, **kw) if self.defer: return d failure = [] append = failure.append def errback(result): """Used with Response method to suppress 'Unhandled error in Deferred' messages by adding an errback. """ append(result) return None d.addErrback(errback) # spin reactor while not d.called: reactor.runUntilCurrent() t2 = reactor.timeout() t = reactor.running and t2 reactor.doIteration(t) pyobj = d.result if len(failure): failure[0].raiseException() return pyobj
[ "def", "Receive", "(", "self", ",", "replytype", ",", "chain", "=", "None", ",", "*", "*", "kw", ")", ":", "chain", "=", "chain", "or", "self", ".", "chain", "d", "=", "chain", ".", "flow", ".", "deferred", "if", "self", ".", "trace", ":", "def",...
https://github.com/Pymol-Scripts/Pymol-script-repo/blob/bcd7bb7812dc6db1595953dfa4471fa15fb68c77/modules/pdb2pqr/contrib/ZSI-2.1-a1/ZSI/twisted/client.py#L283-L335
FabriceSalvaire/CodeReview
c48433467ac2a9a14b9c9026734f8c494af4aa95
CodeReview/Diff/RawTextDocument.py
python
RawTextDocumentAbc.__init__
(self, text_buffer, flat_slice, line_start_locations, line_separators)
r"""The parameter *text_buffer* specifies the text buffer. It must implement the method **__getitem__** to index and slice the characters. The parameter *flat_slice* specifies the flat slice corresponding to the text chunk. The list *line_start_locations* contains the position of the new lines in the text chunk and the list *line_separators* contains the corresponding new line separators. The standard separators (``\r\n``, ``\r``, ``\n``) are supported. The list *line_start_locations* ends by a sentinel that corresponds to the number of characters in the text chunk and the list *line_separators* by an empty string. This sentinel corresponds to a virtual line at the end of the text buffer.
r"""The parameter *text_buffer* specifies the text buffer. It must implement the method **__getitem__** to index and slice the characters.
[ "r", "The", "parameter", "*", "text_buffer", "*", "specifies", "the", "text", "buffer", ".", "It", "must", "implement", "the", "method", "**", "__getitem__", "**", "to", "index", "and", "slice", "the", "characters", "." ]
def __init__(self, text_buffer, flat_slice, line_start_locations, line_separators): r"""The parameter *text_buffer* specifies the text buffer. It must implement the method **__getitem__** to index and slice the characters. The parameter *flat_slice* specifies the flat slice corresponding to the text chunk. The list *line_start_locations* contains the position of the new lines in the text chunk and the list *line_separators* contains the corresponding new line separators. The standard separators (``\r\n``, ``\r``, ``\n``) are supported. The list *line_start_locations* ends by a sentinel that corresponds to the number of characters in the text chunk and the list *line_separators* by an empty string. This sentinel corresponds to a virtual line at the end of the text buffer. """ self._text_buffer = text_buffer self._flat_slice = flat_slice self._line_start_locations = line_start_locations self._line_separators = line_separators
[ "def", "__init__", "(", "self", ",", "text_buffer", ",", "flat_slice", ",", "line_start_locations", ",", "line_separators", ")", ":", "self", ".", "_text_buffer", "=", "text_buffer", "self", ".", "_flat_slice", "=", "flat_slice", "self", ".", "_line_start_location...
https://github.com/FabriceSalvaire/CodeReview/blob/c48433467ac2a9a14b9c9026734f8c494af4aa95/CodeReview/Diff/RawTextDocument.py#L85-L104
riga/tfdeploy
22aea652fe12f081be43414e0f1f76c7d9aaf53c
tfdeploy.py
python
Unique
(a, t)
return np.copy(a)[np.sort(idxs)], idxs[inv].astype(dtype_map[t])
Unique op.
Unique op.
[ "Unique", "op", "." ]
def Unique(a, t): """ Unique op. """ _, idxs, inv = np.unique(a, return_index=True, return_inverse=True) return np.copy(a)[np.sort(idxs)], idxs[inv].astype(dtype_map[t])
[ "def", "Unique", "(", "a", ",", "t", ")", ":", "_", ",", "idxs", ",", "inv", "=", "np", ".", "unique", "(", "a", ",", "return_index", "=", "True", ",", "return_inverse", "=", "True", ")", "return", "np", ".", "copy", "(", "a", ")", "[", "np", ...
https://github.com/riga/tfdeploy/blob/22aea652fe12f081be43414e0f1f76c7d9aaf53c/tfdeploy.py#L1988-L1993
pika/pika
12dcdf15d0932c388790e0fa990810bfd21b1a32
pika/adapters/utils/selector_ioloop_adapter.py
python
_SelectorIOLoopIOHandle.cancel
(self)
return self._cancel()
Cancel pending operation :returns: False if was already done or cancelled; True otherwise :rtype: bool
Cancel pending operation
[ "Cancel", "pending", "operation" ]
def cancel(self): """Cancel pending operation :returns: False if was already done or cancelled; True otherwise :rtype: bool """ return self._cancel()
[ "def", "cancel", "(", "self", ")", ":", "return", "self", ".", "_cancel", "(", ")" ]
https://github.com/pika/pika/blob/12dcdf15d0932c388790e0fa990810bfd21b1a32/pika/adapters/utils/selector_ioloop_adapter.py#L455-L462
vmware/pyvcloud
d72c615fa41b8ea5ab049a929e18d8ba6460fc59
pyvcloud/vcd/vdc.py
python
VDC.add_access_settings
(self, access_settings_list=None)
return acl.add_access_settings(access_settings_list)
Add access settings to the vdc. :param list access_settings_list: list of dictionaries, where each dictionary represents a single access setting. The dictionary structure is as follows, - type: (str): type of the subject. One of 'org' or 'user'. - name: (str): name of the user or org. - access_level: (str): access_level of the particular subject. Allowed values are 'ReadOnly', 'Change' or 'FullControl'. :return: an object containing EntityType.CONTROL_ACCESS_PARAMS XML data representing the updated Access Control List of the vdc. :rtype: lxml.objectify.ObjectifiedElement
Add access settings to the vdc.
[ "Add", "access", "settings", "to", "the", "vdc", "." ]
def add_access_settings(self, access_settings_list=None): """Add access settings to the vdc. :param list access_settings_list: list of dictionaries, where each dictionary represents a single access setting. The dictionary structure is as follows, - type: (str): type of the subject. One of 'org' or 'user'. - name: (str): name of the user or org. - access_level: (str): access_level of the particular subject. Allowed values are 'ReadOnly', 'Change' or 'FullControl'. :return: an object containing EntityType.CONTROL_ACCESS_PARAMS XML data representing the updated Access Control List of the vdc. :rtype: lxml.objectify.ObjectifiedElement """ acl = Acl(self.client, self.get_resource()) return acl.add_access_settings(access_settings_list)
[ "def", "add_access_settings", "(", "self", ",", "access_settings_list", "=", "None", ")", ":", "acl", "=", "Acl", "(", "self", ".", "client", ",", "self", ".", "get_resource", "(", ")", ")", "return", "acl", ".", "add_access_settings", "(", "access_settings_...
https://github.com/vmware/pyvcloud/blob/d72c615fa41b8ea5ab049a929e18d8ba6460fc59/pyvcloud/vcd/vdc.py#L1226-L1244
cloudera/impyla
0c736af4cad2bade9b8e313badc08ec50e81c948
impala/_thrift_gen/hive_metastore/ThriftHiveMetastore.py
python
abort_txns_result.__eq__
(self, other)
return isinstance(other, self.__class__) and self.__dict__ == other.__dict__
[]
def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__
[ "def", "__eq__", "(", "self", ",", "other", ")", ":", "return", "isinstance", "(", "other", ",", "self", ".", "__class__", ")", "and", "self", ".", "__dict__", "==", "other", ".", "__dict__" ]
https://github.com/cloudera/impyla/blob/0c736af4cad2bade9b8e313badc08ec50e81c948/impala/_thrift_gen/hive_metastore/ThriftHiveMetastore.py#L32456-L32457
cisco/mindmeld
809c36112e9ea8019fe29d54d136ca14eb4fd8db
mindmeld/components/dialogue.py
python
DialogueFlow._apply_flow_handler_sync
(self, request, responder)
return {"dialogue_state": dialogue_state, "directives": responder.directives}
Applies the dialogue state handler for the dialogue flow and set the target dialogue state to the flow state. Args: request (Request): The request object. responder (DialogueResponder): The responder object. Returns: (dict): A dict containing the dialogue state and directives.
Applies the dialogue state handler for the dialogue flow and set the target dialogue state to the flow state.
[ "Applies", "the", "dialogue", "state", "handler", "for", "the", "dialogue", "flow", "and", "set", "the", "target", "dialogue", "state", "to", "the", "flow", "state", "." ]
def _apply_flow_handler_sync(self, request, responder): """Applies the dialogue state handler for the dialogue flow and set the target dialogue state to the flow state. Args: request (Request): The request object. responder (DialogueResponder): The responder object. Returns: (dict): A dict containing the dialogue state and directives. """ dialogue_state = self._get_dialogue_state(request) handler = self._get_dialogue_handler(dialogue_state) if dialogue_state not in self.exit_flow_states: responder.params.target_dialogue_state = self.flow_state handler(request, responder) return {"dialogue_state": dialogue_state, "directives": responder.directives}
[ "def", "_apply_flow_handler_sync", "(", "self", ",", "request", ",", "responder", ")", ":", "dialogue_state", "=", "self", ".", "_get_dialogue_state", "(", "request", ")", "handler", "=", "self", ".", "_get_dialogue_handler", "(", "dialogue_state", ")", "if", "d...
https://github.com/cisco/mindmeld/blob/809c36112e9ea8019fe29d54d136ca14eb4fd8db/mindmeld/components/dialogue.py#L651-L669
HoverHell/RedditImageGrab
eb23ee516c98bccaa0904b9b420d603109dac37e
redditdownload/img_scrap_stuff.py
python
setdiff
(set_a, set_b)
return set_a - set_b, set_a & set_b, set_b - set_a
RTFS
RTFS
[ "RTFS" ]
def setdiff(set_a, set_b): """ RTFS """ set_a, set_b = set(set_a), set(set_b) return set_a - set_b, set_a & set_b, set_b - set_a
[ "def", "setdiff", "(", "set_a", ",", "set_b", ")", ":", "set_a", ",", "set_b", "=", "set", "(", "set_a", ")", ",", "set", "(", "set_b", ")", "return", "set_a", "-", "set_b", ",", "set_a", "&", "set_b", ",", "set_b", "-", "set_a" ]
https://github.com/HoverHell/RedditImageGrab/blob/eb23ee516c98bccaa0904b9b420d603109dac37e/redditdownload/img_scrap_stuff.py#L169-L172
tendenci/tendenci
0f2c348cc0e7d41bc56f50b00ce05544b083bf1d
tendenci/apps/accounts/views.py
python
password_reset
(request)
return auth_password_reset(request, extra_context=extra_context)
[]
def password_reset(request): from_registration = request.GET.get('registration', False) extra_context = { 'from_registration': from_registration, } auth_password_reset = PasswordResetView.as_view( form_class = PasswordResetForm, template_name='accounts/password_reset_form.html', email_template_name='registration/password_reset_email_user_list.html') return auth_password_reset(request, extra_context=extra_context)
[ "def", "password_reset", "(", "request", ")", ":", "from_registration", "=", "request", ".", "GET", ".", "get", "(", "'registration'", ",", "False", ")", "extra_context", "=", "{", "'from_registration'", ":", "from_registration", ",", "}", "auth_password_reset", ...
https://github.com/tendenci/tendenci/blob/0f2c348cc0e7d41bc56f50b00ce05544b083bf1d/tendenci/apps/accounts/views.py#L215-L224
PreOS-Security/fwaudit
f38d8ace3c1be487edc2d66d689aa5bb9ff07f56
fwaudit.py
python
chipsec_test_memconfig
(toolns, tool, prd, ptd, erc)
return spawn_process(cmd, ptd, erc, toolns)
Call chipsec_main -m memconfig
Call chipsec_main -m memconfig
[ "Call", "chipsec_main", "-", "m", "memconfig" ]
def chipsec_test_memconfig(toolns, tool, prd, ptd, erc): '''Call chipsec_main -m memconfig''' info('Executing ' + toolns + ' variation of tool: ' + tool) cmd = ['python', '-i', '-m', 'chipsec_main', '-m', 'memconfig'] return spawn_process(cmd, ptd, erc, toolns)
[ "def", "chipsec_test_memconfig", "(", "toolns", ",", "tool", ",", "prd", ",", "ptd", ",", "erc", ")", ":", "info", "(", "'Executing '", "+", "toolns", "+", "' variation of tool: '", "+", "tool", ")", "cmd", "=", "[", "'python'", ",", "'-i'", ",", "'-m'",...
https://github.com/PreOS-Security/fwaudit/blob/f38d8ace3c1be487edc2d66d689aa5bb9ff07f56/fwaudit.py#L3980-L3984
keiffster/program-y
8c99b56f8c32f01a7b9887b5daae9465619d0385
src/programy/storage/stores/nosql/mongo/store/maps.py
python
MongoMapsStore.load_all
(self, collector)
[]
def load_all(self, collector): YLogger.info(self, "Loading all maps from Mongo") collection = self.collection() collector.empty() maps = collection.find({}) for amap in maps: self.load(collector, amap[MongoMapsStore.NAME])
[ "def", "load_all", "(", "self", ",", "collector", ")", ":", "YLogger", ".", "info", "(", "self", ",", "\"Loading all maps from Mongo\"", ")", "collection", "=", "self", ".", "collection", "(", ")", "collector", ".", "empty", "(", ")", "maps", "=", "collect...
https://github.com/keiffster/program-y/blob/8c99b56f8c32f01a7b9887b5daae9465619d0385/src/programy/storage/stores/nosql/mongo/store/maps.py#L79-L85
fffonion/xeHentai
26063154a238d4df280f8d17f14d090e679084ec
xeHentai/filters.py
python
login_exhentai
(r, suc, fail)
[]
def login_exhentai(r, suc, fail): # input login response # add cookies if suc; log error fail try: coo = r.headers.get('set-cookie') cooid = re.findall('ipb_member_id=(.*?);', coo)[0] coopw = re.findall('ipb_pass_hash=(.*?);', coo)[0] except (IndexError, ) as ex: errmsg = re.findall('<span class="postcolor">([^<]+)</span>', r.text) if errmsg: fail(errmsg[0]) else: fail("ex: %s" % ex) return FAIL else: suc({'ipb_member_id':cooid, 'ipb_pass_hash':coopw}) return SUC
[ "def", "login_exhentai", "(", "r", ",", "suc", ",", "fail", ")", ":", "# input login response", "# add cookies if suc; log error fail", "try", ":", "coo", "=", "r", ".", "headers", ".", "get", "(", "'set-cookie'", ")", "cooid", "=", "re", ".", "findall", "("...
https://github.com/fffonion/xeHentai/blob/26063154a238d4df280f8d17f14d090e679084ec/xeHentai/filters.py#L15-L31
gramps-project/gramps
04d4651a43eb210192f40a9f8c2bad8ee8fa3753
gramps/plugins/view/pedigreeview.py
python
PedigreeView.attach_widget
(self, table, widget, xmax, right, left, top, bottom)
Attach a widget to the table.
Attach a widget to the table.
[ "Attach", "a", "widget", "to", "the", "table", "." ]
def attach_widget(self, table, widget, xmax, right, left, top, bottom): """ Attach a widget to the table. """ if self.tree_direction == 0: # Vertical (top to bottom) table.attach(widget, top, right, bottom-top, left-right) elif self.tree_direction == 1: # Vertical (bottom to top) table.attach(widget, top, xmax - left + 1, bottom-top, left - right) elif self.tree_direction == 2: # Horizontal (left to right) table.attach(widget, right, top, left-right, bottom-top) elif self.tree_direction == 3: # Horizontal (right to left) table.attach(widget, xmax - left + 1, top, left - right, bottom-top)
[ "def", "attach_widget", "(", "self", ",", "table", ",", "widget", ",", "xmax", ",", "right", ",", "left", ",", "top", ",", "bottom", ")", ":", "if", "self", ".", "tree_direction", "==", "0", ":", "# Vertical (top to bottom)", "table", ".", "attach", "(",...
https://github.com/gramps-project/gramps/blob/04d4651a43eb210192f40a9f8c2bad8ee8fa3753/gramps/plugins/view/pedigreeview.py#L1330-L1341
veusz/veusz
5a1e2af5f24df0eb2a2842be51f2997c4999c7fb
veusz/setting/controls.py
python
_EditBox.closeEvent
(self, event)
Tell the calling widget that we are closing, and provide the new text.
Tell the calling widget that we are closing, and provide the new text.
[ "Tell", "the", "calling", "widget", "that", "we", "are", "closing", "and", "provide", "the", "new", "text", "." ]
def closeEvent(self, event): """Tell the calling widget that we are closing, and provide the new text.""" text = self.toPlainText() text = text.replace('\n', '') self.closing.emit(text) event.accept()
[ "def", "closeEvent", "(", "self", ",", "event", ")", ":", "text", "=", "self", ".", "toPlainText", "(", ")", "text", "=", "text", ".", "replace", "(", "'\\n'", ",", "''", ")", "self", ".", "closing", ".", "emit", "(", "text", ")", "event", ".", "...
https://github.com/veusz/veusz/blob/5a1e2af5f24df0eb2a2842be51f2997c4999c7fb/veusz/setting/controls.py#L149-L156
jbjorne/TEES
caf19a4a1352ac59f5dc13a8684cc42ce4342d9d
Utils/Libraries/progressbar.py
python
Bar.update
(self, pbar, width)
return bar
[]
def update(self, pbar, width): percent = pbar.percentage() cwidth = width - len(self.left) - len(self.right) marked_width = int(percent * cwidth / 100) m = self._format_marker(pbar) bar = (self.left + (m*marked_width).ljust(cwidth) + self.right) return bar
[ "def", "update", "(", "self", ",", "pbar", ",", "width", ")", ":", "percent", "=", "pbar", ".", "percentage", "(", ")", "cwidth", "=", "width", "-", "len", "(", "self", ".", "left", ")", "-", "len", "(", "self", ".", "right", ")", "marked_width", ...
https://github.com/jbjorne/TEES/blob/caf19a4a1352ac59f5dc13a8684cc42ce4342d9d/Utils/Libraries/progressbar.py#L162-L168
thu-coai/ConvLab-2
ad32b76022fa29cbc2f24cbefbb855b60492985e
convlab2/evaluator/evaluator.py
python
Evaluator.add_goal
(self, goal)
init goal and array. args: goal: dict[domain] dict['info'/'book'/'reqt'] dict/dict/list[slot]
init goal and array.
[ "init", "goal", "and", "array", "." ]
def add_goal(self, goal): """init goal and array. args: goal: dict[domain] dict['info'/'book'/'reqt'] dict/dict/list[slot] """ raise NotImplementedError
[ "def", "add_goal", "(", "self", ",", "goal", ")", ":", "raise", "NotImplementedError" ]
https://github.com/thu-coai/ConvLab-2/blob/ad32b76022fa29cbc2f24cbefbb855b60492985e/convlab2/evaluator/evaluator.py#L8-L15
dulwich/dulwich
1f66817d712e3563ce1ff53b1218491a2eae39da
dulwich/repo.py
python
BaseRepo.get_refs
(self)
return self.refs.as_dict()
Get dictionary with all refs. Returns: A ``dict`` mapping ref names to SHA1s
Get dictionary with all refs.
[ "Get", "dictionary", "with", "all", "refs", "." ]
def get_refs(self) -> Dict[bytes, bytes]: """Get dictionary with all refs. Returns: A ``dict`` mapping ref names to SHA1s """ return self.refs.as_dict()
[ "def", "get_refs", "(", "self", ")", "->", "Dict", "[", "bytes", ",", "bytes", "]", ":", "return", "self", ".", "refs", ".", "as_dict", "(", ")" ]
https://github.com/dulwich/dulwich/blob/1f66817d712e3563ce1ff53b1218491a2eae39da/dulwich/repo.py#L589-L594
wikimedia/pywikibot
81a01ffaec7271bf5b4b170f85a80388420a4e78
scripts/archivebot.py
python
PageArchiver.should_archive_thread
(self, thread: DiscussionThread )
return None
Check whether a thread has to be archived. :return: the archivation reason as a tuple of localization args
Check whether a thread has to be archived.
[ "Check", "whether", "a", "thread", "has", "to", "be", "archived", "." ]
def should_archive_thread(self, thread: DiscussionThread ) -> Optional[ShouldArchive]: """ Check whether a thread has to be archived. :return: the archivation reason as a tuple of localization args """ # Archived by timestamp algo = self.get_attr('algo') re_t = re.fullmatch(r'old\((.*)\)', algo) if re_t: if not thread.timestamp: return None # TODO: handle unsigned maxage = str2time(re_t.group(1), thread.timestamp) if self.now - thread.timestamp > maxage: duration = str2localized_duration(self.site, re_t.group(1)) return ('duration', duration) # TODO: handle marked with template return None
[ "def", "should_archive_thread", "(", "self", ",", "thread", ":", "DiscussionThread", ")", "->", "Optional", "[", "ShouldArchive", "]", ":", "# Archived by timestamp", "algo", "=", "self", ".", "get_attr", "(", "'algo'", ")", "re_t", "=", "re", ".", "fullmatch"...
https://github.com/wikimedia/pywikibot/blob/81a01ffaec7271bf5b4b170f85a80388420a4e78/scripts/archivebot.py#L617-L636
dimagi/commcare-hq
d67ff1d3b4c51fa050c19e60c3253a79d3452a39
corehq/apps/app_manager/management/commands/build_apps.py
python
record_performance_stats
(filepath, slug)
[]
def record_performance_stats(filepath, slug): hp = hpy() before = hp.heap() start = time.clock() try: yield finally: end = time.clock() after = hp.heap() leftover = after - before with open(filepath, 'a', encoding='utf-8') as f: f.write('{},{},{}\n'.format(slug, leftover.size, end - start))
[ "def", "record_performance_stats", "(", "filepath", ",", "slug", ")", ":", "hp", "=", "hpy", "(", ")", "before", "=", "hp", ".", "heap", "(", ")", "start", "=", "time", ".", "clock", "(", ")", "try", ":", "yield", "finally", ":", "end", "=", "time"...
https://github.com/dimagi/commcare-hq/blob/d67ff1d3b4c51fa050c19e60c3253a79d3452a39/corehq/apps/app_manager/management/commands/build_apps.py#L28-L39
JaniceWuo/MovieRecommend
4c86db64ca45598917d304f535413df3bc9fea65
movierecommend/venv1/Lib/site-packages/django/contrib/admin/filters.py
python
SimpleListFilter.value
(self)
return self.used_parameters.get(self.parameter_name)
Returns the value (in string format) provided in the request's query string for this filter, if any. If the value wasn't provided then returns None.
Returns the value (in string format) provided in the request's query string for this filter, if any. If the value wasn't provided then returns None.
[ "Returns", "the", "value", "(", "in", "string", "format", ")", "provided", "in", "the", "request", "s", "query", "string", "for", "this", "filter", "if", "any", ".", "If", "the", "value", "wasn", "t", "provided", "then", "returns", "None", "." ]
def value(self): """ Returns the value (in string format) provided in the request's query string for this filter, if any. If the value wasn't provided then returns None. """ return self.used_parameters.get(self.parameter_name)
[ "def", "value", "(", "self", ")", ":", "return", "self", ".", "used_parameters", ".", "get", "(", "self", ".", "parameter_name", ")" ]
https://github.com/JaniceWuo/MovieRecommend/blob/4c86db64ca45598917d304f535413df3bc9fea65/movierecommend/venv1/Lib/site-packages/django/contrib/admin/filters.py#L84-L90
ZhihengCV/Bayesian-Crowd-Counting
5f10bfc50ff3cb6e424e17fa970600d55094dd9f
datasets/crowd_sh.py
python
Crowd.train_transform
(self, img, keypoints)
return self.trans(img), torch.from_numpy(keypoints.copy()).float(), \ torch.from_numpy(target.copy()).float(), st_size
random crop image patch and find people in it
random crop image patch and find people in it
[ "random", "crop", "image", "patch", "and", "find", "people", "in", "it" ]
def train_transform(self, img, keypoints): """random crop image patch and find people in it""" wd, ht = img.size st_size = min(wd, ht) assert st_size >= self.c_size assert len(keypoints) > 0 i, j, h, w = random_crop(ht, wd, self.c_size, self.c_size) img = F.crop(img, i, j, h, w) nearest_dis = np.clip(0.8*keypoints[:, 2], 4.0, 40.0) points_left_up = keypoints[:, :2] - nearest_dis[:, None] / 2.0 points_right_down = keypoints[:, :2] + nearest_dis[:, None] / 2.0 bbox = np.concatenate((points_left_up, points_right_down), axis=1) inner_area = cal_innner_area(j, i, j+w, i+h, bbox) origin_area = nearest_dis * nearest_dis ratio = np.clip(1.0 * inner_area / origin_area, 0.0, 1.0) mask = (ratio >= 0.5) keypoints = keypoints[mask] keypoints = keypoints[:, :2] - [j, i] # change coodinate target = np.ones(len(keypoints)) if len(keypoints) > 0: if random.random() > 0.5: img = F.hflip(img) keypoints[:, 0] = w - keypoints[:, 0] else: if random.random() > 0.5: img = F.hflip(img) return self.trans(img), torch.from_numpy(keypoints.copy()).float(), \ torch.from_numpy(target.copy()).float(), st_size
[ "def", "train_transform", "(", "self", ",", "img", ",", "keypoints", ")", ":", "wd", ",", "ht", "=", "img", ".", "size", "st_size", "=", "min", "(", "wd", ",", "ht", ")", "assert", "st_size", ">=", "self", ".", "c_size", "assert", "len", "(", "keyp...
https://github.com/ZhihengCV/Bayesian-Crowd-Counting/blob/5f10bfc50ff3cb6e424e17fa970600d55094dd9f/datasets/crowd_sh.py#L72-L101
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_hxb2/lib/python3.5/site-packages/pip/_vendor/requests/packages/urllib3/util/ssl_.py
python
_const_compare_digest_backport
(a, b)
return result == 0
Compare two digests of equal length in constant time. The digests must be of type str/bytes. Returns True if the digests match, and False otherwise.
Compare two digests of equal length in constant time.
[ "Compare", "two", "digests", "of", "equal", "length", "in", "constant", "time", "." ]
def _const_compare_digest_backport(a, b): """ Compare two digests of equal length in constant time. The digests must be of type str/bytes. Returns True if the digests match, and False otherwise. """ result = abs(len(a) - len(b)) for l, r in zip(bytearray(a), bytearray(b)): result |= l ^ r return result == 0
[ "def", "_const_compare_digest_backport", "(", "a", ",", "b", ")", ":", "result", "=", "abs", "(", "len", "(", "a", ")", "-", "len", "(", "b", ")", ")", "for", "l", ",", "r", "in", "zip", "(", "bytearray", "(", "a", ")", ",", "bytearray", "(", "...
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_hxb2/lib/python3.5/site-packages/pip/_vendor/requests/packages/urllib3/util/ssl_.py#L25-L35
numba/numba
bf480b9e0da858a65508c2b17759a72ee6a44c51
numba/core/ir.py
python
SetAttr.__init__
(self, target, attr, value, loc)
[]
def __init__(self, target, attr, value, loc): assert isinstance(target, Var) assert isinstance(attr, str) assert isinstance(value, Var) assert isinstance(loc, Loc) self.target = target self.attr = attr self.value = value self.loc = loc
[ "def", "__init__", "(", "self", ",", "target", ",", "attr", ",", "value", ",", "loc", ")", ":", "assert", "isinstance", "(", "target", ",", "Var", ")", "assert", "isinstance", "(", "attr", ",", "str", ")", "assert", "isinstance", "(", "value", ",", "...
https://github.com/numba/numba/blob/bf480b9e0da858a65508c2b17759a72ee6a44c51/numba/core/ir.py#L659-L667
quantOS-org/JAQS
959762a518c22592f96433c573d1f99ec0c89152
jaqs/trade/tradeapi/trade_api.py
python
TradeApi.query_net_position
(self, mode="all", securities="", format="")
return utils.extract_result(cr, data_format=data_format, class_name="NetPosition")
securities: seperate by "," return pd.dataframe
securities: seperate by "," return pd.dataframe
[ "securities", ":", "seperate", "by", "return", "pd", ".", "dataframe" ]
def query_net_position(self, mode="all", securities="", format=""): """ securities: seperate by "," return pd.dataframe """ r, msg = self._check_session() if not r: return (None, msg) rpc_params = {"mode" : mode, "security" : securities} data_format = self._get_format(format, "pandas") if data_format == "pandas": rpc_params["format"] = "columnset" cr = self._remote.call("oms.query_net_position", rpc_params) return utils.extract_result(cr, data_format=data_format, class_name="NetPosition")
[ "def", "query_net_position", "(", "self", ",", "mode", "=", "\"all\"", ",", "securities", "=", "\"\"", ",", "format", "=", "\"\"", ")", ":", "r", ",", "msg", "=", "self", ".", "_check_session", "(", ")", "if", "not", "r", ":", "return", "(", "None", ...
https://github.com/quantOS-org/JAQS/blob/959762a518c22592f96433c573d1f99ec0c89152/jaqs/trade/tradeapi/trade_api.py#L396-L414
thenetcircle/dino
1047c3458e91a1b4189e9f48f1393b3a68a935b3
dino/cache/__init__.py
python
ICache.set_global_ban_timestamp
(self, user_id: str, duration: str, timestamp: str, username: str)
set the global ban timestamp for a user to a given timestamp :param user_id: the id of the user :param duration: the duration, e.g. 12d :param timestamp: the timestamp :param username: the username of this user :return: nothing
set the global ban timestamp for a user to a given timestamp
[ "set", "the", "global", "ban", "timestamp", "for", "a", "user", "to", "a", "given", "timestamp" ]
def set_global_ban_timestamp(self, user_id: str, duration: str, timestamp: str, username: str) -> None: """ set the global ban timestamp for a user to a given timestamp :param user_id: the id of the user :param duration: the duration, e.g. 12d :param timestamp: the timestamp :param username: the username of this user :return: nothing """
[ "def", "set_global_ban_timestamp", "(", "self", ",", "user_id", ":", "str", ",", "duration", ":", "str", ",", "timestamp", ":", "str", ",", "username", ":", "str", ")", "->", "None", ":" ]
https://github.com/thenetcircle/dino/blob/1047c3458e91a1b4189e9f48f1393b3a68a935b3/dino/cache/__init__.py#L715-L724
openstack/cinder
23494a6d6c51451688191e1847a458f1d3cdcaa5
cinder/volume/drivers/ibm/ibm_storage/ds8k_proxy.py
python
DS8KProxy.terminate_connection
(self, volume, connector, force=False, **kwargs)
Detach a volume from a host.
Detach a volume from a host.
[ "Detach", "a", "volume", "from", "a", "host", "." ]
def terminate_connection(self, volume, connector, force=False, **kwargs): """Detach a volume from a host.""" ret_info = { 'driver_volume_type': 'fibre_channel', 'data': {} } lun = Lun(volume) if (lun.group and lun.failed_over) and not self._active_backend_id: backend_helper = self._replication.get_target_helper() else: backend_helper = self._helper if isinstance(backend_helper, helper.DS8KECKDHelper): LOG.info('Detach the volume %s.', lun.ds_id) return backend_helper.terminate_connection(lun.ds_id, connector, force, **kwargs) else: vol_mapped, host_id, map_info = ( backend_helper.check_vol_mapped_to_host(connector, lun.ds_id)) if host_id is None or not vol_mapped: if host_id is None and not lun.type_replication: LOG.warning('Failed to find the Host information.') return ret_info if host_id and not lun.type_replication and not vol_mapped: LOG.warning("Volume %(vol)s is already not mapped to " "host %(host)s.", {'vol': lun.ds_id, 'host': host_id}) return ret_info if lun.type_replication: if backend_helper == self._replication.get_target_helper(): backend_helper = self._replication.get_source_helper() else: backend_helper = self._replication.get_target_helper() try: if backend_helper.lun_exists(lun.replica_ds_id): LOG.info('Detaching volume %s from the ' 'Secondary site.', lun.replica_ds_id) mapped, host_id, map_info = ( backend_helper.check_vol_mapped_to_host( connector, lun.replica_ds_id)) else: msg = (_('Failed to find the attached ' 'Volume %s.') % lun.ds_id) LOG.error(msg) raise exception.VolumeDriverException(message=msg) except Exception as ex: LOG.warning('Failed to get host mapping for volume ' '%(volume)s in the secondary site. ' 'Exception: %(err)s.', {'volume': lun.replica_ds_id, 'err': ex}) return ret_info if not mapped: return ret_info else: LOG.info('Detach the volume %s.', lun.replica_ds_id) return backend_helper.terminate_connection( lun.replica_ds_id, host_id, connector, map_info) elif host_id and vol_mapped: LOG.info('Detaching volume %s.', lun.ds_id) return backend_helper.terminate_connection(lun.ds_id, host_id, connector, map_info)
[ "def", "terminate_connection", "(", "self", ",", "volume", ",", "connector", ",", "force", "=", "False", ",", "*", "*", "kwargs", ")", ":", "ret_info", "=", "{", "'driver_volume_type'", ":", "'fibre_channel'", ",", "'data'", ":", "{", "}", "}", "lun", "=...
https://github.com/openstack/cinder/blob/23494a6d6c51451688191e1847a458f1d3cdcaa5/cinder/volume/drivers/ibm/ibm_storage/ds8k_proxy.py#L1103-L1162
kensho-technologies/graphql-compiler
4318443b7b2512a059f3616112bfc40bbf8eec06
graphql_compiler/cost_estimation/statistics.py
python
LocalStatistics.__init__
( self, class_counts: Dict[str, int], *, vertex_edge_vertex_counts: Optional[Dict[Tuple[str, str, str], int]] = None, distinct_field_values_counts: Optional[Dict[Tuple[str, str], int]] = None, field_quantiles: Optional[Dict[Tuple[str, str], List[Any]]] = None, sampling_summaries: Optional[Dict[str, VertexSamplingSummary]] = None, )
Initialize statistics with the given data. Args: class_counts: dict, str -> int, mapping vertex/edge class name to count of instances of that class. vertex_edge_vertex_counts: optional dict, (str, str, str) -> int, mapping tuple of (vertex source class name, edge class name, vertex target class name) to count of edge instances of given class connecting instances of two vertex classes. distinct_field_values_counts: optional dict, (str, str) -> int, mapping vertex class name and property field name to the count of distinct values of that vertex class's property field. field_quantiles: optional dict, (str, str) -> list, mapping vertex class name and property field name to a list of N quantiles, a sorted list of values separating the values of the field into N-1 groups of almost equal size. The first element of the list is the smallest known value, and the last element is the largest known value. The i-th element is a value greater than or equal to i/N of all present values. The number N can be different for each entry. N has to be at least 2 for every entry present in the dict. sampling_summaries: optional SamplingSummaries for some classes TODO(bojanserafimov): Enforce a canonical representation for quantile values and sampling summaries. Datetimes should be in utc, decimals should have type float, etc. TODO(bojanserafimov): Validate class_counts against sample_ratio * num_samples
Initialize statistics with the given data.
[ "Initialize", "statistics", "with", "the", "given", "data", "." ]
def __init__( self, class_counts: Dict[str, int], *, vertex_edge_vertex_counts: Optional[Dict[Tuple[str, str, str], int]] = None, distinct_field_values_counts: Optional[Dict[Tuple[str, str], int]] = None, field_quantiles: Optional[Dict[Tuple[str, str], List[Any]]] = None, sampling_summaries: Optional[Dict[str, VertexSamplingSummary]] = None, ): """Initialize statistics with the given data. Args: class_counts: dict, str -> int, mapping vertex/edge class name to count of instances of that class. vertex_edge_vertex_counts: optional dict, (str, str, str) -> int, mapping tuple of (vertex source class name, edge class name, vertex target class name) to count of edge instances of given class connecting instances of two vertex classes. distinct_field_values_counts: optional dict, (str, str) -> int, mapping vertex class name and property field name to the count of distinct values of that vertex class's property field. field_quantiles: optional dict, (str, str) -> list, mapping vertex class name and property field name to a list of N quantiles, a sorted list of values separating the values of the field into N-1 groups of almost equal size. The first element of the list is the smallest known value, and the last element is the largest known value. The i-th element is a value greater than or equal to i/N of all present values. The number N can be different for each entry. N has to be at least 2 for every entry present in the dict. sampling_summaries: optional SamplingSummaries for some classes TODO(bojanserafimov): Enforce a canonical representation for quantile values and sampling summaries. Datetimes should be in utc, decimals should have type float, etc. TODO(bojanserafimov): Validate class_counts against sample_ratio * num_samples """ if vertex_edge_vertex_counts is None: vertex_edge_vertex_counts = dict() if distinct_field_values_counts is None: distinct_field_values_counts = dict() if field_quantiles is None: field_quantiles = dict() if sampling_summaries is None: sampling_summaries = dict() # Validate arguments for (vertex_name, field_name), quantile_list in six.iteritems(field_quantiles): if len(quantile_list) < 2: raise AssertionError( f"The number of quantiles should be at least 2. Field " f"{vertex_name}.{field_name} has {len(quantile_list)}." ) for quantile in quantile_list: if isinstance(quantile, datetime.datetime): if quantile.tzinfo is not None: raise NotImplementedError( f"Range reasoning for tz-aware datetimes is not implemented. " f"found tz-aware quantiles for {vertex_name}.{field_name}." ) self._class_counts = class_counts self._vertex_edge_vertex_counts = vertex_edge_vertex_counts self._distinct_field_values_counts = distinct_field_values_counts self._field_quantiles = field_quantiles self._sampling_summaries = sampling_summaries
[ "def", "__init__", "(", "self", ",", "class_counts", ":", "Dict", "[", "str", ",", "int", "]", ",", "*", ",", "vertex_edge_vertex_counts", ":", "Optional", "[", "Dict", "[", "Tuple", "[", "str", ",", "str", ",", "str", "]", ",", "int", "]", "]", "=...
https://github.com/kensho-technologies/graphql-compiler/blob/4318443b7b2512a059f3616112bfc40bbf8eec06/graphql_compiler/cost_estimation/statistics.py#L143-L207
Bitmessage/PyBitmessage
97612b049e0453867d6d90aa628f8e7b007b4d85
src/network/bmobject.py
python
BMObject.checkObjectByType
(self)
Call a object type specific check (objects can have additional checks based on their types)
Call a object type specific check (objects can have additional checks based on their types)
[ "Call", "a", "object", "type", "specific", "check", "(", "objects", "can", "have", "additional", "checks", "based", "on", "their", "types", ")" ]
def checkObjectByType(self): """Call a object type specific check (objects can have additional checks based on their types)""" if self.objectType == protocol.OBJECT_GETPUBKEY: self.checkGetpubkey() elif self.objectType == protocol.OBJECT_PUBKEY: self.checkPubkey() elif self.objectType == protocol.OBJECT_MSG: self.checkMessage() elif self.objectType == protocol.OBJECT_BROADCAST: self.checkBroadcast()
[ "def", "checkObjectByType", "(", "self", ")", ":", "if", "self", ".", "objectType", "==", "protocol", ".", "OBJECT_GETPUBKEY", ":", "self", ".", "checkGetpubkey", "(", ")", "elif", "self", ".", "objectType", "==", "protocol", ".", "OBJECT_PUBKEY", ":", "self...
https://github.com/Bitmessage/PyBitmessage/blob/97612b049e0453867d6d90aa628f8e7b007b4d85/src/network/bmobject.py#L122-L132
sagemath/sage
f9b2db94f675ff16963ccdefba4f1a3393b3fe0d
src/sage/calculus/transforms/dft.py
python
IndexedSequence.list
(self)
return self._list
Return the list of ``self``. EXAMPLES:: sage: J = list(range(10)) sage: A = [1/10 for j in J] sage: s = IndexedSequence(A,J) sage: s.list() [1/10, 1/10, 1/10, 1/10, 1/10, 1/10, 1/10, 1/10, 1/10, 1/10]
Return the list of ``self``.
[ "Return", "the", "list", "of", "self", "." ]
def list(self): """ Return the list of ``self``. EXAMPLES:: sage: J = list(range(10)) sage: A = [1/10 for j in J] sage: s = IndexedSequence(A,J) sage: s.list() [1/10, 1/10, 1/10, 1/10, 1/10, 1/10, 1/10, 1/10, 1/10, 1/10] """ return self._list
[ "def", "list", "(", "self", ")", ":", "return", "self", ".", "_list" ]
https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/calculus/transforms/dft.py#L161-L173
stopstalk/stopstalk-deployment
10c3ab44c4ece33ae515f6888c15033db2004bb1
aws_lambda/spoj_aws_lambda_function/lambda_code/pip/_internal/utils/misc.py
python
consume
(iterator)
Consume an iterable at C speed.
Consume an iterable at C speed.
[ "Consume", "an", "iterable", "at", "C", "speed", "." ]
def consume(iterator): """Consume an iterable at C speed.""" deque(iterator, maxlen=0)
[ "def", "consume", "(", "iterator", ")", ":", "deque", "(", "iterator", ",", "maxlen", "=", "0", ")" ]
https://github.com/stopstalk/stopstalk-deployment/blob/10c3ab44c4ece33ae515f6888c15033db2004bb1/aws_lambda/spoj_aws_lambda_function/lambda_code/pip/_internal/utils/misc.py#L842-L844
robhagemans/pcbasic
c3a043b46af66623a801e18a38175be077251ada
pcbasic/basic/devices/devicebase.py
python
TextFileBase.__init__
(self, fhandle, filetype, mode)
Setup the basic properties of the file.
Setup the basic properties of the file.
[ "Setup", "the", "basic", "properties", "of", "the", "file", "." ]
def __init__(self, fhandle, filetype, mode): """Setup the basic properties of the file.""" RawFile.__init__(self, fhandle, filetype, mode) # width=255 means line wrap self.width = 255 self.col = 1 # allow first char to be specified (e.g. already read) self._readahead = [] self._current, self._previous = b'', b''
[ "def", "__init__", "(", "self", ",", "fhandle", ",", "filetype", ",", "mode", ")", ":", "RawFile", ".", "__init__", "(", "self", ",", "fhandle", ",", "filetype", ",", "mode", ")", "# width=255 means line wrap", "self", ".", "width", "=", "255", "self", "...
https://github.com/robhagemans/pcbasic/blob/c3a043b46af66623a801e18a38175be077251ada/pcbasic/basic/devices/devicebase.py#L244-L252
Asana/python-asana
9b54ab99423208bd6aa87dbfaa628c069430b127
asana/client.py
python
Client.get_collection
(self, path, query, **options)
Get a collection from a collection endpoint. Parses GET request options for a collection endpoint and dispatches a request.
Get a collection from a collection endpoint.
[ "Get", "a", "collection", "from", "a", "collection", "endpoint", "." ]
def get_collection(self, path, query, **options): """Get a collection from a collection endpoint. Parses GET request options for a collection endpoint and dispatches a request. """ options = self._merge_options(options) if options['iterator_type'] == 'items': return CollectionPageIterator(self, path, query, options).items() if options['iterator_type'] is None: return self.get(path, query, **options) raise Exception('Unknown value for "iterator_type" option: {}'.format( str(options['iterator_type'])))
[ "def", "get_collection", "(", "self", ",", "path", ",", "query", ",", "*", "*", "options", ")", ":", "options", "=", "self", ".", "_merge_options", "(", "options", ")", "if", "options", "[", "'iterator_type'", "]", "==", "'items'", ":", "return", "Collec...
https://github.com/Asana/python-asana/blob/9b54ab99423208bd6aa87dbfaa628c069430b127/asana/client.py#L175-L188
home-assistant/core
265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1
homeassistant/components/cast/helpers.py
python
CastStatusListener.multizone_new_media_status
(self, group_uuid, media_status)
Handle reception of a new MediaStatus for a group.
Handle reception of a new MediaStatus for a group.
[ "Handle", "reception", "of", "a", "new", "MediaStatus", "for", "a", "group", "." ]
def multizone_new_media_status(self, group_uuid, media_status): """Handle reception of a new MediaStatus for a group.""" if self._valid: self._cast_device.multizone_new_media_status(group_uuid, media_status)
[ "def", "multizone_new_media_status", "(", "self", ",", "group_uuid", ",", "media_status", ")", ":", "if", "self", ".", "_valid", ":", "self", ".", "_cast_device", ".", "multizone_new_media_status", "(", "group_uuid", ",", "media_status", ")" ]
https://github.com/home-assistant/core/blob/265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1/homeassistant/components/cast/helpers.py#L134-L137
microsoft/azure-devops-python-api
451cade4c475482792cbe9e522c1fee32393139e
azure-devops/azure/devops/v5_1/service_hooks/service_hooks_client.py
python
ServiceHooksClient.list_subscriptions
(self, publisher_id=None, event_type=None, consumer_id=None, consumer_action_id=None)
return self._deserialize('[Subscription]', self._unwrap_collection(response))
ListSubscriptions. Get a list of subscriptions. :param str publisher_id: ID for a subscription. :param str event_type: The event type to filter on (if any). :param str consumer_id: ID for a consumer. :param str consumer_action_id: ID for a consumerActionId. :rtype: [Subscription]
ListSubscriptions. Get a list of subscriptions. :param str publisher_id: ID for a subscription. :param str event_type: The event type to filter on (if any). :param str consumer_id: ID for a consumer. :param str consumer_action_id: ID for a consumerActionId. :rtype: [Subscription]
[ "ListSubscriptions", ".", "Get", "a", "list", "of", "subscriptions", ".", ":", "param", "str", "publisher_id", ":", "ID", "for", "a", "subscription", ".", ":", "param", "str", "event_type", ":", "The", "event", "type", "to", "filter", "on", "(", "if", "a...
def list_subscriptions(self, publisher_id=None, event_type=None, consumer_id=None, consumer_action_id=None): """ListSubscriptions. Get a list of subscriptions. :param str publisher_id: ID for a subscription. :param str event_type: The event type to filter on (if any). :param str consumer_id: ID for a consumer. :param str consumer_action_id: ID for a consumerActionId. :rtype: [Subscription] """ query_parameters = {} if publisher_id is not None: query_parameters['publisherId'] = self._serialize.query('publisher_id', publisher_id, 'str') if event_type is not None: query_parameters['eventType'] = self._serialize.query('event_type', event_type, 'str') if consumer_id is not None: query_parameters['consumerId'] = self._serialize.query('consumer_id', consumer_id, 'str') if consumer_action_id is not None: query_parameters['consumerActionId'] = self._serialize.query('consumer_action_id', consumer_action_id, 'str') response = self._send(http_method='GET', location_id='fc50d02a-849f-41fb-8af1-0a5216103269', version='5.1', query_parameters=query_parameters) return self._deserialize('[Subscription]', self._unwrap_collection(response))
[ "def", "list_subscriptions", "(", "self", ",", "publisher_id", "=", "None", ",", "event_type", "=", "None", ",", "consumer_id", "=", "None", ",", "consumer_action_id", "=", "None", ")", ":", "query_parameters", "=", "{", "}", "if", "publisher_id", "is", "not...
https://github.com/microsoft/azure-devops-python-api/blob/451cade4c475482792cbe9e522c1fee32393139e/azure-devops/azure/devops/v5_1/service_hooks/service_hooks_client.py#L325-L347
liaopeiyuan/ml-arsenal-public
f8938ce3cb58b35fc7cc20d096c39a85ec9780b2
external/heng/tgs/code/sync_batchnorm/batchnorm.py
python
_unsqueeze_ft
(tensor)
return tensor.unsqueeze(0).unsqueeze(-1)
add new dementions at the front and the tail
add new dementions at the front and the tail
[ "add", "new", "dementions", "at", "the", "front", "and", "the", "tail" ]
def _unsqueeze_ft(tensor): """add new dementions at the front and the tail""" return tensor.unsqueeze(0).unsqueeze(-1)
[ "def", "_unsqueeze_ft", "(", "tensor", ")", ":", "return", "tensor", ".", "unsqueeze", "(", "0", ")", ".", "unsqueeze", "(", "-", "1", ")" ]
https://github.com/liaopeiyuan/ml-arsenal-public/blob/f8938ce3cb58b35fc7cc20d096c39a85ec9780b2/external/heng/tgs/code/sync_batchnorm/batchnorm.py#L34-L36
hfaran/piazza-api
48756f4150c94276d14c2504f1c2d09a330efb20
piazza_api/network.py
python
Network.create_reply
(self, post, content, anonymous=False)
return self._rpc.content_create(params)
Create a reply to a followup It seems like if the post has `<p>` tags, then it's treated as HTML, but is treated as text otherwise. You'll want to provide `content` accordingly. :type post: dict|str|int :param post: Either the post dict returned by another API method, or the `cid` field of that post. :type subject: str :param content: The content of the followup. :type anonymous: bool :param anonymous: Whether or not to post anonymously. :rtype: dict :returns: Dictionary with information about the created follow-up.
Create a reply to a followup
[ "Create", "a", "reply", "to", "a", "followup" ]
def create_reply(self, post, content, anonymous=False): """Create a reply to a followup It seems like if the post has `<p>` tags, then it's treated as HTML, but is treated as text otherwise. You'll want to provide `content` accordingly. :type post: dict|str|int :param post: Either the post dict returned by another API method, or the `cid` field of that post. :type subject: str :param content: The content of the followup. :type anonymous: bool :param anonymous: Whether or not to post anonymously. :rtype: dict :returns: Dictionary with information about the created follow-up. """ try: cid = post["id"] except KeyError: cid = post params = { "cid": cid, "type": "feedback", # For replies, the content is actually put into the subject. "subject": content, "content": "", "anonymous": "yes" if anonymous else "no", } return self._rpc.content_create(params)
[ "def", "create_reply", "(", "self", ",", "post", ",", "content", ",", "anonymous", "=", "False", ")", ":", "try", ":", "cid", "=", "post", "[", "\"id\"", "]", "except", "KeyError", ":", "cid", "=", "post", "params", "=", "{", "\"cid\"", ":", "cid", ...
https://github.com/hfaran/piazza-api/blob/48756f4150c94276d14c2504f1c2d09a330efb20/piazza_api/network.py#L218-L249
lovelylain/pyctp
fd304de4b50c4ddc31a4190b1caaeb5dec66bc5d
stock/ctp/Level2ApiStruct.py
python
L2MarketDataBid8.__init__
(self, BidPx8=0.0, BidOrderQty8=0, BidNumOrder8=0)
[]
def __init__(self, BidPx8=0.0, BidOrderQty8=0, BidNumOrder8=0): self.BidPx8 = 'Price' #申买价八, double self.BidOrderQty8 = 'Volume' #申买量八, int self.BidNumOrder8 = 'Volume'
[ "def", "__init__", "(", "self", ",", "BidPx8", "=", "0.0", ",", "BidOrderQty8", "=", "0", ",", "BidNumOrder8", "=", "0", ")", ":", "self", ".", "BidPx8", "=", "'Price'", "#申买价八, double", "self", ".", "BidOrderQty8", "=", "'Volume'", "#申买量八, int", "self", ...
https://github.com/lovelylain/pyctp/blob/fd304de4b50c4ddc31a4190b1caaeb5dec66bc5d/stock/ctp/Level2ApiStruct.py#L337-L340
POSTECH-CVLab/PyTorch-StudioGAN
bebb33f612759b86a224392f6fe941d0cc81d3c4
src/models/big_resnet.py
python
DiscBlock.forward
(self, x)
return out
[]
def forward(self, x): x0 = x if not self.apply_d_sn: x = self.bn1(x) x = self.activation(x) x = self.conv2d1(x) if not self.apply_d_sn: x = self.bn2(x) x = self.activation(x) x = self.conv2d2(x) if self.downsample: x = self.average_pooling(x) if self.downsample or self.ch_mismatch: if not self.apply_d_sn: x0 = self.bn0(x0) x0 = self.conv2d0(x0) if self.downsample: x0 = self.average_pooling(x0) out = x + x0 return out
[ "def", "forward", "(", "self", ",", "x", ")", ":", "x0", "=", "x", "if", "not", "self", ".", "apply_d_sn", ":", "x", "=", "self", ".", "bn1", "(", "x", ")", "x", "=", "self", ".", "activation", "(", "x", ")", "x", "=", "self", ".", "conv2d1",...
https://github.com/POSTECH-CVLab/PyTorch-StudioGAN/blob/bebb33f612759b86a224392f6fe941d0cc81d3c4/src/models/big_resnet.py#L214-L235
awslabs/aws-servicebroker
c301912e7df3a2f09a9c34d3ae7ffe67c55aa3a0
sample-apps/rds/sample-app/src/pymysql/connections.py
python
Connection.commit
(self)
Commit changes to stable storage
Commit changes to stable storage
[ "Commit", "changes", "to", "stable", "storage" ]
def commit(self): """Commit changes to stable storage""" self._execute_command(COMMAND.COM_QUERY, "COMMIT") self._read_ok_packet()
[ "def", "commit", "(", "self", ")", ":", "self", ".", "_execute_command", "(", "COMMAND", ".", "COM_QUERY", ",", "\"COMMIT\"", ")", "self", ".", "_read_ok_packet", "(", ")" ]
https://github.com/awslabs/aws-servicebroker/blob/c301912e7df3a2f09a9c34d3ae7ffe67c55aa3a0/sample-apps/rds/sample-app/src/pymysql/connections.py#L785-L788
IdentityPython/pysaml2
6badb32d212257bd83ffcc816f9b625f68281b47
src/saml2/schema/wsdl.py
python
TFault_.__init__
(self, name=None, message=None, documentation=None, text=None, extension_elements=None, extension_attributes=None, )
[]
def __init__(self, name=None, message=None, documentation=None, text=None, extension_elements=None, extension_attributes=None, ): TExtensibleAttributesDocumented_.__init__(self, documentation=documentation, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes, ) self.name=name self.message=message
[ "def", "__init__", "(", "self", ",", "name", "=", "None", ",", "message", "=", "None", ",", "documentation", "=", "None", ",", "text", "=", "None", ",", "extension_elements", "=", "None", ",", "extension_attributes", "=", "None", ",", ")", ":", "TExtensi...
https://github.com/IdentityPython/pysaml2/blob/6badb32d212257bd83ffcc816f9b625f68281b47/src/saml2/schema/wsdl.py#L255-L270
google/grr
8ad8a4d2c5a93c92729206b7771af19d92d4f915
grr/server/grr_response_server/gui/api_call_router.py
python
ApiCallRouterStub.ListKbFields
(self, args, context=None)
List all available KnowledgeBase fields.
List all available KnowledgeBase fields.
[ "List", "all", "available", "KnowledgeBase", "fields", "." ]
def ListKbFields(self, args, context=None): """List all available KnowledgeBase fields.""" raise NotImplementedError()
[ "def", "ListKbFields", "(", "self", ",", "args", ",", "context", "=", "None", ")", ":", "raise", "NotImplementedError", "(", ")" ]
https://github.com/google/grr/blob/8ad8a4d2c5a93c92729206b7771af19d92d4f915/grr/server/grr_response_server/gui/api_call_router.py#L1428-L1431
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/Python-2.7.9/Mac/Demo/mlte/mlted.py
python
Mlted.clear
(self, *args)
[]
def clear(self, *args): if self.active: self.active.menu_clear() else: EasyDialogs.Message("No active window?")
[ "def", "clear", "(", "self", ",", "*", "args", ")", ":", "if", "self", ".", "active", ":", "self", ".", "active", ".", "menu_clear", "(", ")", "else", ":", "EasyDialogs", ".", "Message", "(", "\"No active window?\"", ")" ]
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/Python-2.7.9/Mac/Demo/mlte/mlted.py#L349-L353
fmoralesc/vim-pad
2a39b6857ada72f1f81b12c85baf7f067cb90739
pythonx/pad/vim_interface.py
python
Vim.__add__
(self, cmd)
The idea is to allow using Vim() + command to execute vim commands, instead of using vim.command(). Mainly aesthetics, but it cleans up the python code. Note: Vim() + "string" + var doesn't work as expected, you need to use Vim() + ("string" + var)
The idea is to allow using
[ "The", "idea", "is", "to", "allow", "using" ]
def __add__(self, cmd): """ The idea is to allow using Vim() + command to execute vim commands, instead of using vim.command(). Mainly aesthetics, but it cleans up the python code. Note: Vim() + "string" + var doesn't work as expected, you need to use Vim() + ("string" + var) """ if isinstance(cmd, str): vim.command(cmd)
[ "def", "__add__", "(", "self", ",", "cmd", ")", ":", "if", "isinstance", "(", "cmd", ",", "str", ")", ":", "vim", ".", "command", "(", "cmd", ")" ]
https://github.com/fmoralesc/vim-pad/blob/2a39b6857ada72f1f81b12c85baf7f067cb90739/pythonx/pad/vim_interface.py#L5-L24
InvestmentSystems/static-frame
0b19d6969bf6c17fb0599871aca79eb3b52cf2ed
static_frame/core/index_hierarchy.py
python
IndexHierarchy.from_tree
(cls: tp.Type[IH], tree: TreeNodeT, *, name: NameType = None )
return cls(cls._LEVEL_CONSTRUCTOR.from_tree(tree), name=name)
Convert into a ``IndexHierarchy`` a dictionary defining keys to either iterables or nested dictionaries of the same. Returns: :obj:`static_frame.IndexHierarchy`
Convert into a ``IndexHierarchy`` a dictionary defining keys to either iterables or nested dictionaries of the same.
[ "Convert", "into", "a", "IndexHierarchy", "a", "dictionary", "defining", "keys", "to", "either", "iterables", "or", "nested", "dictionaries", "of", "the", "same", "." ]
def from_tree(cls: tp.Type[IH], tree: TreeNodeT, *, name: NameType = None ) -> IH: ''' Convert into a ``IndexHierarchy`` a dictionary defining keys to either iterables or nested dictionaries of the same. Returns: :obj:`static_frame.IndexHierarchy` ''' return cls(cls._LEVEL_CONSTRUCTOR.from_tree(tree), name=name)
[ "def", "from_tree", "(", "cls", ":", "tp", ".", "Type", "[", "IH", "]", ",", "tree", ":", "TreeNodeT", ",", "*", ",", "name", ":", "NameType", "=", "None", ")", "->", "IH", ":", "return", "cls", "(", "cls", ".", "_LEVEL_CONSTRUCTOR", ".", "from_tre...
https://github.com/InvestmentSystems/static-frame/blob/0b19d6969bf6c17fb0599871aca79eb3b52cf2ed/static_frame/core/index_hierarchy.py#L197-L208
edisonlz/fastor
342078a18363ac41d3c6b1ab29dbdd44fdb0b7b3
base/site-packages/androguard/core/bytecodes/dvm.py
python
EncodedAnnotation.get_size
(self)
return self.size
Return the number of name-value mappings in this annotation :rtype:int
Return the number of name-value mappings in this annotation
[ "Return", "the", "number", "of", "name", "-", "value", "mappings", "in", "this", "annotation" ]
def get_size(self) : """ Return the number of name-value mappings in this annotation :rtype:int """ return self.size
[ "def", "get_size", "(", "self", ")", ":", "return", "self", ".", "size" ]
https://github.com/edisonlz/fastor/blob/342078a18363ac41d3c6b1ab29dbdd44fdb0b7b3/base/site-packages/androguard/core/bytecodes/dvm.py#L1594-L1600
pybliometrics-dev/pybliometrics
26ad9656e5a1d4c80774937706a0df85776f07d0
pybliometrics/scopus/abstract_retrieval.py
python
AbstractRetrieval.confsponsor
(self)
return sponsors
Sponsor(s) of the conference the document belongs to.
Sponsor(s) of the conference the document belongs to.
[ "Sponsor", "(", "s", ")", "of", "the", "conference", "the", "document", "belongs", "to", "." ]
def confsponsor(self) -> Optional[Union[List[str], str]]: """Sponsor(s) of the conference the document belongs to.""" path = ['confsponsors', 'confsponsor'] sponsors = chained_get(self._confevent, path, []) if len(sponsors) == 0: return None if isinstance(sponsors, list): return [s['$'] for s in sponsors] return sponsors
[ "def", "confsponsor", "(", "self", ")", "->", "Optional", "[", "Union", "[", "List", "[", "str", "]", ",", "str", "]", "]", ":", "path", "=", "[", "'confsponsors'", ",", "'confsponsor'", "]", "sponsors", "=", "chained_get", "(", "self", ".", "_confeven...
https://github.com/pybliometrics-dev/pybliometrics/blob/26ad9656e5a1d4c80774937706a0df85776f07d0/pybliometrics/scopus/abstract_retrieval.py#L180-L188
laughingman7743/PyAthena
417749914247cabca2325368c6eda337b28b47f0
pyathena/common.py
python
CursorIterator.__next__
(self)
[]
def __next__(self): row = self.fetchone() if row is None: raise StopIteration else: return row
[ "def", "__next__", "(", "self", ")", ":", "row", "=", "self", ".", "fetchone", "(", ")", "if", "row", "is", "None", ":", "raise", "StopIteration", "else", ":", "return", "row" ]
https://github.com/laughingman7743/PyAthena/blob/417749914247cabca2325368c6eda337b28b47f0/pyathena/common.py#L65-L70
acm5656/ssd_pytorch
95bab2f080f4d7b9beb1ba0f5f9163ec84a110f2
utils.py
python
nms
(boxes, scores, overlap=0.5, top_k=200)
return keep, count
Apply non-maximum suppression at test time to avoid detecting too many overlapping bounding boxes for a given object. Args: boxes: (tensor) The location preds for the img, Shape: [num_priors,4]. scores: (tensor) The class predscores for the img, Shape:[num_priors]. overlap: (float) The overlap thresh for suppressing unnecessary boxes. top_k: (int) The Maximum number of box preds to consider. Return: The indices of the kept boxes with respect to num_priors.
Apply non-maximum suppression at test time to avoid detecting too many overlapping bounding boxes for a given object. Args: boxes: (tensor) The location preds for the img, Shape: [num_priors,4]. scores: (tensor) The class predscores for the img, Shape:[num_priors]. overlap: (float) The overlap thresh for suppressing unnecessary boxes. top_k: (int) The Maximum number of box preds to consider. Return: The indices of the kept boxes with respect to num_priors.
[ "Apply", "non", "-", "maximum", "suppression", "at", "test", "time", "to", "avoid", "detecting", "too", "many", "overlapping", "bounding", "boxes", "for", "a", "given", "object", ".", "Args", ":", "boxes", ":", "(", "tensor", ")", "The", "location", "preds...
def nms(boxes, scores, overlap=0.5, top_k=200): """Apply non-maximum suppression at test time to avoid detecting too many overlapping bounding boxes for a given object. Args: boxes: (tensor) The location preds for the img, Shape: [num_priors,4]. scores: (tensor) The class predscores for the img, Shape:[num_priors]. overlap: (float) The overlap thresh for suppressing unnecessary boxes. top_k: (int) The Maximum number of box preds to consider. Return: The indices of the kept boxes with respect to num_priors. """ keep = scores.new(scores.size(0)).zero_().long() if boxes.numel() == 0: return keep,0 x1 = boxes[:, 0] y1 = boxes[:, 1] x2 = boxes[:, 2] y2 = boxes[:, 3] area = torch.mul(x2 - x1, y2 - y1) v, idx = scores.sort(0) # sort in ascending order # I = I[v >= 0.01] idx = idx[-top_k:] # indices of the top-k largest vals xx1 = boxes.new() yy1 = boxes.new() xx2 = boxes.new() yy2 = boxes.new() w = boxes.new() h = boxes.new() # keep = torch.Tensor() count = 0 while idx.numel() > 0: i = idx[-1] # index of current largest val # keep.append(i) keep[count] = i count += 1 if idx.size(0) == 1: break idx = idx[:-1] # remove kept element from view # load bboxes of next highest vals torch.index_select(x1, 0, idx, out=xx1) torch.index_select(y1, 0, idx, out=yy1) torch.index_select(x2, 0, idx, out=xx2) torch.index_select(y2, 0, idx, out=yy2) # store element-wise max with next highest score xx1 = torch.clamp(xx1, min=x1[i]) yy1 = torch.clamp(yy1, min=y1[i]) xx2 = torch.clamp(xx2, max=x2[i]) yy2 = torch.clamp(yy2, max=y2[i]) w.resize_as_(xx2) h.resize_as_(yy2) w = xx2 - xx1 h = yy2 - yy1 # check sizes of xx1 and xx2.. after each iteration w = torch.clamp(w, min=0.0) h = torch.clamp(h, min=0.0) inter = w*h # IoU = i / (area(a) + area(b) - i) rem_areas = torch.index_select(area, 0, idx) # load remaining areas) union = (rem_areas - inter) + area[i] IoU = inter/union # store result in iou # keep only elements with an IoU <= overlap idx = idx[IoU.le(overlap)] return keep, count
[ "def", "nms", "(", "boxes", ",", "scores", ",", "overlap", "=", "0.5", ",", "top_k", "=", "200", ")", ":", "keep", "=", "scores", ".", "new", "(", "scores", ".", "size", "(", "0", ")", ")", ".", "zero_", "(", ")", ".", "long", "(", ")", "if",...
https://github.com/acm5656/ssd_pytorch/blob/95bab2f080f4d7b9beb1ba0f5f9163ec84a110f2/utils.py#L150-L214
ganeti/ganeti
d340a9ddd12f501bef57da421b5f9b969a4ba905
lib/tools/cfgupgrade.py
python
CfgUpgrade.UpgradeDiskDevType
(self, disk)
Upgrades the disks' device type.
Upgrades the disks' device type.
[ "Upgrades", "the", "disks", "device", "type", "." ]
def UpgradeDiskDevType(self, disk): """Upgrades the disks' device type.""" self.ChangeDiskDevType(disk, DEV_TYPE_OLD_NEW)
[ "def", "UpgradeDiskDevType", "(", "self", ",", "disk", ")", ":", "self", ".", "ChangeDiskDevType", "(", "disk", ",", "DEV_TYPE_OLD_NEW", ")" ]
https://github.com/ganeti/ganeti/blob/d340a9ddd12f501bef57da421b5f9b969a4ba905/lib/tools/cfgupgrade.py#L404-L406
TencentCloud/tencentcloud-sdk-python
3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2
tencentcloud/cwp/v20180228/models.py
python
ExportVulDetectionExcelRequest.__init__
(self)
r""" :param TaskId: 本次漏洞检测任务id(不同于出参的导出本次漏洞检测Excel的任务Id) :type TaskId: int
r""" :param TaskId: 本次漏洞检测任务id(不同于出参的导出本次漏洞检测Excel的任务Id) :type TaskId: int
[ "r", ":", "param", "TaskId", ":", "本次漏洞检测任务id(不同于出参的导出本次漏洞检测Excel的任务Id)", ":", "type", "TaskId", ":", "int" ]
def __init__(self): r""" :param TaskId: 本次漏洞检测任务id(不同于出参的导出本次漏洞检测Excel的任务Id) :type TaskId: int """ self.TaskId = None
[ "def", "__init__", "(", "self", ")", ":", "self", ".", "TaskId", "=", "None" ]
https://github.com/TencentCloud/tencentcloud-sdk-python/blob/3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2/tencentcloud/cwp/v20180228/models.py#L14901-L14906
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/Python-2.7.9/Lib/_osx_support.py
python
_read_output
(commandstring)
Output from successful command execution or None
Output from successful command execution or None
[ "Output", "from", "successful", "command", "execution", "or", "None" ]
def _read_output(commandstring): """Output from successful command execution or None""" # Similar to os.popen(commandstring, "r").read(), # but without actually using os.popen because that # function is not usable during python bootstrap. # tempfile is also not available then. import contextlib try: import tempfile fp = tempfile.NamedTemporaryFile() except ImportError: fp = open("/tmp/_osx_support.%s"%( os.getpid(),), "w+b") with contextlib.closing(fp) as fp: cmd = "%s 2>/dev/null >'%s'" % (commandstring, fp.name) return fp.read().strip() if not os.system(cmd) else None
[ "def", "_read_output", "(", "commandstring", ")", ":", "# Similar to os.popen(commandstring, \"r\").read(),", "# but without actually using os.popen because that", "# function is not usable during python bootstrap.", "# tempfile is also not available then.", "import", "contextlib", "try", ...
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/Python-2.7.9/Lib/_osx_support.py#L55-L71
openmc-dev/openmc
0cf7d9283786677e324bfbdd0984a54d1c86dacc
openmc/filter_expansion.py
python
SphericalHarmonicsFilter.to_xml_element
(self)
return element
Return XML Element representing the filter. Returns ------- element : xml.etree.ElementTree.Element XML element containing spherical harmonics filter data
Return XML Element representing the filter.
[ "Return", "XML", "Element", "representing", "the", "filter", "." ]
def to_xml_element(self): """Return XML Element representing the filter. Returns ------- element : xml.etree.ElementTree.Element XML element containing spherical harmonics filter data """ element = super().to_xml_element() element.set('cosine', self.cosine) return element
[ "def", "to_xml_element", "(", "self", ")", ":", "element", "=", "super", "(", ")", ".", "to_xml_element", "(", ")", "element", ".", "set", "(", "'cosine'", ",", "self", ".", "cosine", ")", "return", "element" ]
https://github.com/openmc-dev/openmc/blob/0cf7d9283786677e324bfbdd0984a54d1c86dacc/openmc/filter_expansion.py#L306-L317
apple/ccs-calendarserver
13c706b985fb728b9aab42dc0fef85aae21921c3
twistedcaldav/directory/augment.py
python
AugmentDB.refresh
(self)
return None
Refresh any cached data. @return: L{Deferred}
Refresh any cached data.
[ "Refresh", "any", "cached", "data", "." ]
def refresh(self): """ Refresh any cached data. @return: L{Deferred} """ self.cachedRecords.clear() return None
[ "def", "refresh", "(", "self", ")", ":", "self", ".", "cachedRecords", ".", "clear", "(", ")", "return", "None" ]
https://github.com/apple/ccs-calendarserver/blob/13c706b985fb728b9aab42dc0fef85aae21921c3/twistedcaldav/directory/augment.py#L231-L239
scikit-image/scikit-image
ed642e2bc822f362504d24379dee94978d6fa9de
skimage/future/manual_segmentation.py
python
manual_lasso_segmentation
(image, alpha=0.4, return_all=False)
Return a label image based on freeform selections made with the mouse. Parameters ---------- image : (M, N[, 3]) array Grayscale or RGB image. alpha : float, optional Transparency value for polygons drawn over the image. return_all : bool, optional If True, an array containing each separate polygon drawn is returned. (The polygons may overlap.) If False (default), latter polygons "overwrite" earlier ones where they overlap. Returns ------- labels : array of int, shape ([Q, ]M, N) The segmented regions. If mode is `'separate'`, the leading dimension of the array corresponds to the number of regions that the user drew. Notes ----- Press and hold the left mouse button to draw around each object. Examples -------- >>> from skimage import data, future, io >>> camera = data.camera() >>> mask = future.manual_lasso_segmentation(camera) # doctest: +SKIP >>> io.imshow(mask) # doctest: +SKIP >>> io.show() # doctest: +SKIP
Return a label image based on freeform selections made with the mouse.
[ "Return", "a", "label", "image", "based", "on", "freeform", "selections", "made", "with", "the", "mouse", "." ]
def manual_lasso_segmentation(image, alpha=0.4, return_all=False): """Return a label image based on freeform selections made with the mouse. Parameters ---------- image : (M, N[, 3]) array Grayscale or RGB image. alpha : float, optional Transparency value for polygons drawn over the image. return_all : bool, optional If True, an array containing each separate polygon drawn is returned. (The polygons may overlap.) If False (default), latter polygons "overwrite" earlier ones where they overlap. Returns ------- labels : array of int, shape ([Q, ]M, N) The segmented regions. If mode is `'separate'`, the leading dimension of the array corresponds to the number of regions that the user drew. Notes ----- Press and hold the left mouse button to draw around each object. Examples -------- >>> from skimage import data, future, io >>> camera = data.camera() >>> mask = future.manual_lasso_segmentation(camera) # doctest: +SKIP >>> io.imshow(mask) # doctest: +SKIP >>> io.show() # doctest: +SKIP """ import matplotlib import matplotlib.pyplot as plt list_of_vertex_lists = [] polygons_drawn = [] if image.ndim not in (2, 3): raise ValueError('Only 2D grayscale or RGB images are supported.') fig, ax = plt.subplots() fig.subplots_adjust(bottom=0.2) ax.imshow(image, cmap="gray") ax.set_axis_off() def _undo(*args, **kwargs): if list_of_vertex_lists: list_of_vertex_lists.pop() # Remove last polygon from list of polygons... last_poly = polygons_drawn.pop() # ... then from the plot last_poly.remove() fig.canvas.draw_idle() undo_pos = fig.add_axes([0.85, 0.05, 0.075, 0.075]) undo_button = matplotlib.widgets.Button(undo_pos, u'\u27F2') undo_button.on_clicked(_undo) def _on_lasso_selection(vertices): if len(vertices) < 3: return list_of_vertex_lists.append(vertices) polygon_object = _draw_polygon(ax, vertices, alpha=alpha) polygons_drawn.append(polygon_object) plt.draw() matplotlib.widgets.LassoSelector(ax, _on_lasso_selection) plt.show(block=True) labels = (_mask_from_vertices(vertices, image.shape[:2], i) for i, vertices in enumerate(list_of_vertex_lists, start=1)) if return_all: return np.stack(labels) else: return reduce(np.maximum, labels, np.broadcast_to(0, image.shape[:2]))
[ "def", "manual_lasso_segmentation", "(", "image", ",", "alpha", "=", "0.4", ",", "return_all", "=", "False", ")", ":", "import", "matplotlib", "import", "matplotlib", ".", "pyplot", "as", "plt", "list_of_vertex_lists", "=", "[", "]", "polygons_drawn", "=", "["...
https://github.com/scikit-image/scikit-image/blob/ed642e2bc822f362504d24379dee94978d6fa9de/skimage/future/manual_segmentation.py#L149-L227
readthedocs/readthedocs.org
0852d7c10d725d954d3e9a93513171baa1116d9f
readthedocs/projects/tasks.py
python
UpdateDocsTaskStep.run_setup
(self, record=True)
return True
Run setup in a build environment. Return True if successful.
Run setup in a build environment.
[ "Run", "setup", "in", "a", "build", "environment", "." ]
def run_setup(self, record=True): """ Run setup in a build environment. Return True if successful. """ # Reset build only if it has some commands already. if self.build.get('commands'): api_v2.build(self.build['id']).reset.post() if settings.DOCKER_ENABLE: env_cls = DockerBuildEnvironment else: env_cls = LocalBuildEnvironment environment = env_cls( project=self.project, version=self.version, build=self.build, record=record, update_on_success=False, environment=self.get_vcs_env_vars(), ) self.build_start_time = environment.start_time # TODO: Remove. # There is code that still depends of this attribute # outside this function. Don't use self.setup_env for new code. self.setup_env = environment # Environment used for code checkout & initial configuration reading with environment: before_vcs.send(sender=self.version, environment=environment) if self.project.skip: raise ProjectBuildsSkippedError try: with self.project.repo_nonblockinglock(version=self.version): self.pull_cached_environment() self.setup_vcs(environment) except vcs_support_utils.LockTimeout as e: self.task.retry(exc=e, throw=False) raise VersionLockedError try: self.config = load_yaml_config(version=self.version) except ConfigError as e: raise YAMLParseError( YAMLParseError.GENERIC_WITH_PARSE_EXCEPTION.format( exception=str(e), ), ) self.save_build_config() self.additional_vcs_operations(environment) if environment.failure or self.config is None: log.info( 'Failing build because of setup failure.', failure=environment.failure, project_slug=self.project.slug, version_slug=self.version.slug, ) # Send notification to users only if the build didn't fail because # of VersionLockedError: this exception occurs when a build is # triggered before the previous one has finished (e.g. two webhooks, # one after the other) if not isinstance(environment.failure, VersionLockedError): self.send_notifications( self.version.pk, self.build['id'], event=WebHookEvent.BUILD_FAILED, ) return False if environment.successful and not self.project.has_valid_clone: self.set_valid_clone() return True
[ "def", "run_setup", "(", "self", ",", "record", "=", "True", ")", ":", "# Reset build only if it has some commands already.", "if", "self", ".", "build", ".", "get", "(", "'commands'", ")", ":", "api_v2", ".", "build", "(", "self", ".", "build", "[", "'id'",...
https://github.com/readthedocs/readthedocs.org/blob/0852d7c10d725d954d3e9a93513171baa1116d9f/readthedocs/projects/tasks.py#L631-L709
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_hxb2/lib/python3.5/site-packages/django/db/backends/oracle/features.py
python
DatabaseFeatures.introspected_boolean_field_type
(self, field=None, created_separately=False)
return super(DatabaseFeatures, self).introspected_boolean_field_type(field, created_separately)
Some versions of Oracle -- we've seen this on 11.2.0.1 and suspect it goes back -- have a weird bug where, when an integer column is added to an existing table with a default, its precision is later reported on introspection as 0, regardless of the real precision. For Django introspection, this means that such columns are reported as IntegerField even if they are really BigIntegerField or BooleanField. The bug is solved in Oracle 11.2.0.2 and up.
Some versions of Oracle -- we've seen this on 11.2.0.1 and suspect it goes back -- have a weird bug where, when an integer column is added to an existing table with a default, its precision is later reported on introspection as 0, regardless of the real precision. For Django introspection, this means that such columns are reported as IntegerField even if they are really BigIntegerField or BooleanField.
[ "Some", "versions", "of", "Oracle", "--", "we", "ve", "seen", "this", "on", "11", ".", "2", ".", "0", ".", "1", "and", "suspect", "it", "goes", "back", "--", "have", "a", "weird", "bug", "where", "when", "an", "integer", "column", "is", "added", "t...
def introspected_boolean_field_type(self, field=None, created_separately=False): """ Some versions of Oracle -- we've seen this on 11.2.0.1 and suspect it goes back -- have a weird bug where, when an integer column is added to an existing table with a default, its precision is later reported on introspection as 0, regardless of the real precision. For Django introspection, this means that such columns are reported as IntegerField even if they are really BigIntegerField or BooleanField. The bug is solved in Oracle 11.2.0.2 and up. """ if self.connection.oracle_full_version < '11.2.0.2' and field and field.has_default() and created_separately: return 'IntegerField' return super(DatabaseFeatures, self).introspected_boolean_field_type(field, created_separately)
[ "def", "introspected_boolean_field_type", "(", "self", ",", "field", "=", "None", ",", "created_separately", "=", "False", ")", ":", "if", "self", ".", "connection", ".", "oracle_full_version", "<", "'11.2.0.2'", "and", "field", "and", "field", ".", "has_default...
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_hxb2/lib/python3.5/site-packages/django/db/backends/oracle/features.py#L47-L60
holoviz/param
c4a9e3252456ad368146140e1fc52cf6bba9f1f0
param/version.py
python
OldDeprecatedVersion.abbrev
(self,dev_suffix="")
return '.'.join(str(el) for el in self.release) + \ (dev_suffix if self.commit_count > 0 or self.dirty else "")
Abbreviated string representation, optionally declaring whether it is a development version.
Abbreviated string representation, optionally declaring whether it is a development version.
[ "Abbreviated", "string", "representation", "optionally", "declaring", "whether", "it", "is", "a", "development", "version", "." ]
def abbrev(self,dev_suffix=""): """ Abbreviated string representation, optionally declaring whether it is a development version. """ return '.'.join(str(el) for el in self.release) + \ (dev_suffix if self.commit_count > 0 or self.dirty else "")
[ "def", "abbrev", "(", "self", ",", "dev_suffix", "=", "\"\"", ")", ":", "return", "'.'", ".", "join", "(", "str", "(", "el", ")", "for", "el", "in", "self", ".", "release", ")", "+", "(", "dev_suffix", "if", "self", ".", "commit_count", ">", "0", ...
https://github.com/holoviz/param/blob/c4a9e3252456ad368146140e1fc52cf6bba9f1f0/param/version.py#L711-L717
alan-turing-institute/CleverCSV
a7c7c812f2dc220b8f45f3409daac6e933bc44a2
clevercsv/break_ties.py
python
tie_breaker
(data, dialects)
return None
Break ties between dialects. This function is used to break ties where possible between two, three, or four dialects that receive the same value for the data consistency measure. Parameters ---------- data: str The data as a single string dialects: list Dialects that are tied Returns ------- dialect: SimpleDialect One of the dialects from the list provided or None.
Break ties between dialects.
[ "Break", "ties", "between", "dialects", "." ]
def tie_breaker(data, dialects): """ Break ties between dialects. This function is used to break ties where possible between two, three, or four dialects that receive the same value for the data consistency measure. Parameters ---------- data: str The data as a single string dialects: list Dialects that are tied Returns ------- dialect: SimpleDialect One of the dialects from the list provided or None. """ if len(dialects) == 2: return break_ties_two(data, dialects[0], dialects[1]) elif len(dialects) == 3: return break_ties_three(data, dialects[0], dialects[1], dialects[2]) elif len(dialects) == 4: return break_ties_four(data, dialects) return None
[ "def", "tie_breaker", "(", "data", ",", "dialects", ")", ":", "if", "len", "(", "dialects", ")", "==", "2", ":", "return", "break_ties_two", "(", "data", ",", "dialects", "[", "0", "]", ",", "dialects", "[", "1", "]", ")", "elif", "len", "(", "dial...
https://github.com/alan-turing-institute/CleverCSV/blob/a7c7c812f2dc220b8f45f3409daac6e933bc44a2/clevercsv/break_ties.py#L14-L41
kpe/bert-for-tf2
55f6a6fd5d8ea14f96ee19938b7a1bf0cb26aaea
bert/tokenization/albert_tokenization.py
python
BasicTokenizer._run_split_on_punc
(self, text)
return ["".join(x) for x in output]
Splits punctuation on a piece of text.
Splits punctuation on a piece of text.
[ "Splits", "punctuation", "on", "a", "piece", "of", "text", "." ]
def _run_split_on_punc(self, text): """Splits punctuation on a piece of text.""" chars = list(text) i = 0 start_new_word = True output = [] while i < len(chars): char = chars[i] if _is_punctuation(char): output.append([char]) start_new_word = True else: if start_new_word: output.append([]) start_new_word = False output[-1].append(char) i += 1 return ["".join(x) for x in output]
[ "def", "_run_split_on_punc", "(", "self", ",", "text", ")", ":", "chars", "=", "list", "(", "text", ")", "i", "=", "0", "start_new_word", "=", "True", "output", "=", "[", "]", "while", "i", "<", "len", "(", "chars", ")", ":", "char", "=", "chars", ...
https://github.com/kpe/bert-for-tf2/blob/55f6a6fd5d8ea14f96ee19938b7a1bf0cb26aaea/bert/tokenization/albert_tokenization.py#L347-L365
unknown-horizons/unknown-horizons
7397fb333006d26c3d9fe796c7bd9cb8c3b43a49
horizons/ai/aiplayer/villagebuilder.py
python
VillageBuilder.remove_building
(self, building)
Called when a building is removed from the area (the building still exists during the call).
Called when a building is removed from the area (the building still exists during the call).
[ "Called", "when", "a", "building", "is", "removed", "from", "the", "area", "(", "the", "building", "still", "exists", "during", "the", "call", ")", "." ]
def remove_building(self, building): """Called when a building is removed from the area (the building still exists during the call).""" if building.id == BUILDINGS.RESIDENTIAL: self._recreate_tent_queue(building.position.origin.to_tuple()) super().remove_building(building)
[ "def", "remove_building", "(", "self", ",", "building", ")", ":", "if", "building", ".", "id", "==", "BUILDINGS", ".", "RESIDENTIAL", ":", "self", ".", "_recreate_tent_queue", "(", "building", ".", "position", ".", "origin", ".", "to_tuple", "(", ")", ")",...
https://github.com/unknown-horizons/unknown-horizons/blob/7397fb333006d26c3d9fe796c7bd9cb8c3b43a49/horizons/ai/aiplayer/villagebuilder.py#L824-L829
wucng/TensorExpand
4ea58f64f5c5082b278229b799c9f679536510b7
TensorExpand/Object detection/faster rcnn/CharlesShang-TFFRCNN-master/lib/datasets/kittivoc.py
python
kittivoc._write_voc_results_file
(self, all_boxes)
[]
def _write_voc_results_file(self, all_boxes): for cls_ind, cls in enumerate(self.classes): if cls == '__background__': continue print 'Writing {} VOC results file'.format(cls) filename = self._get_voc_results_file_template().format(cls) with open(filename, 'wt') as f: for im_ind, index in enumerate(self.image_index): dets = all_boxes[cls_ind][im_ind] if dets == []: continue # the VOCdevkit expects 1-based indices for k in xrange(dets.shape[0]): f.write('{:s} {:.3f} {:.1f} {:.1f} {:.1f} {:.1f}\n'. format(index, dets[k, -1], # filename(stem), score dets[k, 0] + 1, dets[k, 1] + 1, # x1, y1, x2, y2 dets[k, 2] + 1, dets[k, 3] + 1))
[ "def", "_write_voc_results_file", "(", "self", ",", "all_boxes", ")", ":", "for", "cls_ind", ",", "cls", "in", "enumerate", "(", "self", ".", "classes", ")", ":", "if", "cls", "==", "'__background__'", ":", "continue", "print", "'Writing {} VOC results file'", ...
https://github.com/wucng/TensorExpand/blob/4ea58f64f5c5082b278229b799c9f679536510b7/TensorExpand/Object detection/faster rcnn/CharlesShang-TFFRCNN-master/lib/datasets/kittivoc.py#L292-L308
rlworkgroup/garage
b4abe07f0fa9bac2cb70e4a3e315c2e7e5b08507
src/garage/tf/models/model.py
python
Model.network_output_spec
(self)
return []
Network output spec. Return: list[str]: List of key(str) for the network outputs.
Network output spec.
[ "Network", "output", "spec", "." ]
def network_output_spec(self): """Network output spec. Return: list[str]: List of key(str) for the network outputs. """ return []
[ "def", "network_output_spec", "(", "self", ")", ":", "return", "[", "]" ]
https://github.com/rlworkgroup/garage/blob/b4abe07f0fa9bac2cb70e4a3e315c2e7e5b08507/src/garage/tf/models/model.py#L309-L316
LeGoffLoic/Nodz
0ee255c62883f7a374a9de6cbcf555e3352e5dec
nodz_main.py
python
NodeScene.dropEvent
(self, event)
Create a node from the dropped item.
Create a node from the dropped item.
[ "Create", "a", "node", "from", "the", "dropped", "item", "." ]
def dropEvent(self, event): """ Create a node from the dropped item. """ # Emit signal. self.signal_Dropped.emit(event.scenePos()) event.accept()
[ "def", "dropEvent", "(", "self", ",", "event", ")", ":", "# Emit signal.", "self", ".", "signal_Dropped", ".", "emit", "(", "event", ".", "scenePos", "(", ")", ")", "event", ".", "accept", "(", ")" ]
https://github.com/LeGoffLoic/Nodz/blob/0ee255c62883f7a374a9de6cbcf555e3352e5dec/nodz_main.py#L1008-L1016
apple/coremltools
141a83af482fcbdd5179807c9eaff9a7999c2c49
coremltools/converters/keras/_layers2.py
python
default_skip
(builder, layer, input_names, output_names, keras_layer, respect_train)
return
Layers that can be skipped.
Layers that can be skipped.
[ "Layers", "that", "can", "be", "skipped", "." ]
def default_skip(builder, layer, input_names, output_names, keras_layer, respect_train): """ Layers that can be skipped. """ return
[ "def", "default_skip", "(", "builder", ",", "layer", ",", "input_names", ",", "output_names", ",", "keras_layer", ",", "respect_train", ")", ":", "return" ]
https://github.com/apple/coremltools/blob/141a83af482fcbdd5179807c9eaff9a7999c2c49/coremltools/converters/keras/_layers2.py#L1581-L1585
pwnieexpress/pwn_plug_sources
1a23324f5dc2c3de20f9c810269b6a29b2758cad
src/wifitap/scapy.py
python
IPoptionsField.getfield
(self, pkt, s)
return s[opsz:],s[:opsz]
[]
def getfield(self, pkt, s): opsz = (pkt.ihl-5)*4 if opsz < 0: warning("bad ihl (%i). Assuming ihl=5"%pkt.ihl) opsz = 0 return s[opsz:],s[:opsz]
[ "def", "getfield", "(", "self", ",", "pkt", ",", "s", ")", ":", "opsz", "=", "(", "pkt", ".", "ihl", "-", "5", ")", "*", "4", "if", "opsz", "<", "0", ":", "warning", "(", "\"bad ihl (%i). Assuming ihl=5\"", "%", "pkt", ".", "ihl", ")", "opsz", "=...
https://github.com/pwnieexpress/pwn_plug_sources/blob/1a23324f5dc2c3de20f9c810269b6a29b2758cad/src/wifitap/scapy.py#L4497-L4502
geopython/OWSLib
414375413c9e2bab33a2d09608ab209875ce6daf
owslib/ogcapi/__init__.py
python
Collections.collection
(self, collection_id: str)
return self._request(path)
implements /collections/{collectionId} @type collection_id: string @param collection_id: id of collection @returns: `dict` of feature collection metadata
implements /collections/{collectionId}
[ "implements", "/", "collections", "/", "{", "collectionId", "}" ]
def collection(self, collection_id: str) -> dict: """ implements /collections/{collectionId} @type collection_id: string @param collection_id: id of collection @returns: `dict` of feature collection metadata """ path = 'collections/{}'.format(collection_id) return self._request(path)
[ "def", "collection", "(", "self", ",", "collection_id", ":", "str", ")", "->", "dict", ":", "path", "=", "'collections/{}'", ".", "format", "(", "collection_id", ")", "return", "self", ".", "_request", "(", "path", ")" ]
https://github.com/geopython/OWSLib/blob/414375413c9e2bab33a2d09608ab209875ce6daf/owslib/ogcapi/__init__.py#L204-L215
facebookresearch/detectron2
cb92ae1763cd7d3777c243f07749574cdaec6cb8
detectron2/modeling/roi_heads/keypoint_head.py
python
keypoint_rcnn_inference
(pred_keypoint_logits: torch.Tensor, pred_instances: List[Instances])
Post process each predicted keypoint heatmap in `pred_keypoint_logits` into (x, y, score) and add it to the `pred_instances` as a `pred_keypoints` field. Args: pred_keypoint_logits (Tensor): A tensor of shape (R, K, S, S) where R is the total number of instances in the batch, K is the number of keypoints, and S is the side length of the keypoint heatmap. The values are spatial logits. pred_instances (list[Instances]): A list of N Instances, where N is the number of images. Returns: None. Each element in pred_instances will contain extra "pred_keypoints" and "pred_keypoint_heatmaps" fields. "pred_keypoints" is a tensor of shape (#instance, K, 3) where the last dimension corresponds to (x, y, score). The scores are larger than 0. "pred_keypoint_heatmaps" contains the raw keypoint logits as passed to this function.
Post process each predicted keypoint heatmap in `pred_keypoint_logits` into (x, y, score) and add it to the `pred_instances` as a `pred_keypoints` field.
[ "Post", "process", "each", "predicted", "keypoint", "heatmap", "in", "pred_keypoint_logits", "into", "(", "x", "y", "score", ")", "and", "add", "it", "to", "the", "pred_instances", "as", "a", "pred_keypoints", "field", "." ]
def keypoint_rcnn_inference(pred_keypoint_logits: torch.Tensor, pred_instances: List[Instances]): """ Post process each predicted keypoint heatmap in `pred_keypoint_logits` into (x, y, score) and add it to the `pred_instances` as a `pred_keypoints` field. Args: pred_keypoint_logits (Tensor): A tensor of shape (R, K, S, S) where R is the total number of instances in the batch, K is the number of keypoints, and S is the side length of the keypoint heatmap. The values are spatial logits. pred_instances (list[Instances]): A list of N Instances, where N is the number of images. Returns: None. Each element in pred_instances will contain extra "pred_keypoints" and "pred_keypoint_heatmaps" fields. "pred_keypoints" is a tensor of shape (#instance, K, 3) where the last dimension corresponds to (x, y, score). The scores are larger than 0. "pred_keypoint_heatmaps" contains the raw keypoint logits as passed to this function. """ # flatten all bboxes from all images together (list[Boxes] -> Rx4 tensor) bboxes_flat = cat([b.pred_boxes.tensor for b in pred_instances], dim=0) pred_keypoint_logits = pred_keypoint_logits.detach() keypoint_results = heatmaps_to_keypoints(pred_keypoint_logits, bboxes_flat.detach()) num_instances_per_image = [len(i) for i in pred_instances] keypoint_results = keypoint_results[:, :, [0, 1, 3]].split(num_instances_per_image, dim=0) heatmap_results = pred_keypoint_logits.split(num_instances_per_image, dim=0) for keypoint_results_per_image, heatmap_results_per_image, instances_per_image in zip( keypoint_results, heatmap_results, pred_instances ): # keypoint_results_per_image is (num instances)x(num keypoints)x(x, y, score) # heatmap_results_per_image is (num instances)x(num keypoints)x(side)x(side) instances_per_image.pred_keypoints = keypoint_results_per_image instances_per_image.pred_keypoint_heatmaps = heatmap_results_per_image
[ "def", "keypoint_rcnn_inference", "(", "pred_keypoint_logits", ":", "torch", ".", "Tensor", ",", "pred_instances", ":", "List", "[", "Instances", "]", ")", ":", "# flatten all bboxes from all images together (list[Boxes] -> Rx4 tensor)", "bboxes_flat", "=", "cat", "(", "[...
https://github.com/facebookresearch/detectron2/blob/cb92ae1763cd7d3777c243f07749574cdaec6cb8/detectron2/modeling/roi_heads/keypoint_head.py#L99-L132
XX-net/XX-Net
a9898cfcf0084195fb7e69b6bc834e59aecdf14f
python3.8.2/Lib/site.py
python
_init_pathinfo
()
return d
Return a set containing all existing file system items from sys.path.
Return a set containing all existing file system items from sys.path.
[ "Return", "a", "set", "containing", "all", "existing", "file", "system", "items", "from", "sys", ".", "path", "." ]
def _init_pathinfo(): """Return a set containing all existing file system items from sys.path.""" d = set() for item in sys.path: try: if os.path.exists(item): _, itemcase = makepath(item) d.add(itemcase) except TypeError: continue return d
[ "def", "_init_pathinfo", "(", ")", ":", "d", "=", "set", "(", ")", "for", "item", "in", "sys", ".", "path", ":", "try", ":", "if", "os", ".", "path", ".", "exists", "(", "item", ")", ":", "_", ",", "itemcase", "=", "makepath", "(", "item", ")",...
https://github.com/XX-net/XX-Net/blob/a9898cfcf0084195fb7e69b6bc834e59aecdf14f/python3.8.2/Lib/site.py#L135-L145
nucleic/enaml
65c2a2a2d765e88f2e1103046680571894bb41ed
enaml/widgets/image_view.py
python
ImageView._update_proxy
(self, change)
An observer which sends state change to the proxy.
An observer which sends state change to the proxy.
[ "An", "observer", "which", "sends", "state", "change", "to", "the", "proxy", "." ]
def _update_proxy(self, change): """ An observer which sends state change to the proxy. """ # The superclass handler implementation is sufficient. super(ImageView, self)._update_proxy(change)
[ "def", "_update_proxy", "(", "self", ",", "change", ")", ":", "# The superclass handler implementation is sufficient.", "super", "(", "ImageView", ",", "self", ")", ".", "_update_proxy", "(", "change", ")" ]
https://github.com/nucleic/enaml/blob/65c2a2a2d765e88f2e1103046680571894bb41ed/enaml/widgets/image_view.py#L77-L82