Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
From c4ca027 Mon Sep 17 00:00:00 2001
From: apidwalin 84679338+Apidwalin@users.noreply.github.com
Date: Fri, 23 Jul 2021 09:16:58 +0700
Subject: [PATCH 1/4] Create codeql-analysis.yml
.github/workflows/codeql-analysis.yml | 71 +++++++++++++++++++++++++++
1 file changed, 71 insertions(+)
create mode 100644 .github/workflows/codeql-analysis.yml
diff --git a/.github/workflows/codeql-analysis.yml b/.github/workflows/codeql-analysis.yml
new file mode 100644
index 0000000..09200e8
--- /dev/null
+++ b/.github/workflows/codeql-analysis.yml
@@ -0,0 +1,71 @@
+# For most projects, this workflow file will not need changing; you simply need
+# to commit it to your repository.
+#
+# You may wish to alter this file to override the set of languages analyzed,
+# or to provide custom queries or build logic.
+#
+# ******** NOTE ********
+# We have attempted to detect the languages in your repository. Please check
+# the
language
matrix defined below to confirm you have the correct set of+# supported CodeQL languages.
+#
+name: "CodeQL"
+
+on:
The branches below must be a subset of the branches above
+jobs:
Initializes the CodeQL tools for scanning.
Autobuild attempts to build any compiled languages (C/C++, C#, or Java).
If this step fails, then you should remove it and run the build manually (see below)
ℹ️ Command-line programs to run using the OS shell.
📚 https://git.io/JvXDl
✏️ If the Autobuild fails above, remove it and uncomment the following three lines
and modify them (or add more) to build your code if your project
uses a compiled language
make bootstrap
make release
From 83a461c Mon Sep 17 00:00:00 2001
From: apidwalin 84679338+Apidwalin@users.noreply.github.com
Date: Fri, 23 Jul 2021 09:19:40 +0700
Subject: [PATCH 2/4] SECURITY.md
Security Policy
Supported Versions
Use this section to tell people about which versions of your project are
currently being supported with security updates.
Reporting a Vulnerability
Use this section to tell people how to report a vulnerability.
Tell them where to go, how often they can expect to get an update on a
reported vulnerability, what to expect if the vulnerability is accepted or
declined, etc.
SECURITY.md | 21 +++++++++++++++++++++
1 file changed, 21 insertions(+)
create mode 100644 SECURITY.md
diff --git a/SECURITY.md b/SECURITY.md
new file mode 100644
index 0000000..034e848
--- /dev/null
+++ b/SECURITY.md
@@ -0,0 +1,21 @@
+# Security Policy
+
+## Supported Versions
+
+Use this section to tell people about which versions of your project are
+currently being supported with security updates.
+
+| Version | Supported |
+| ------- | ------------------ |
+| 5.1.x | ✅ |
+| 5.0.x | ❌ |
+| 4.0.x | ✅ |
+| < 4.0 | ❌ |
+
+## Reporting a Vulnerability
+
+Use this section to tell people how to report a vulnerability.
+
+Tell them where to go, how often they can expect to get an update on a
+reported vulnerability, what to expect if the vulnerability is accepted or
+declined, etc.
From b52b6dc Mon Sep 17 00:00:00 2001
From: apidwalin 84679338+Apidwalin@users.noreply.github.com
Date: Fri, 23 Jul 2021 11:13:28 +0700
Subject: [PATCH 3/4] Create blank.yml
.github/workflows/blank.yml | 36 ++++++++++++++++++++++++++++++++++++
1 file changed, 36 insertions(+)
create mode 100644 .github/workflows/blank.yml
diff --git a/.github/workflows/blank.yml b/.github/workflows/blank.yml
new file mode 100644
index 0000000..f937a06
--- /dev/null
+++ b/.github/workflows/blank.yml
@@ -0,0 +1,36 @@
+# This is a basic workflow to help you get started with Actions
+
+name: CI
+
+# Controls when the workflow will run
+on:
Triggers the workflow on push or pull request events but only for the master branch
Allows you to run this workflow manually from the Actions tab
+# A workflow run is made up of one or more jobs that can run sequentially or in parallel
+jobs:
This workflow contains a single job called "build"
The type of runner that the job will run on
Steps represent a sequence of tasks that will be executed as part of the job
From 2130ca7 Mon Sep 17 00:00:00 2001
From: apidwalin 84679338+Apidwalin@users.noreply.github.com
Date: Fri, 23 Jul 2021 11:17:57 +0700
Subject: [PATCH 4/4] Add files via upload
.DS_Store | Bin 0 -> 6148 bytes
app_authKey.py | 177 +++
key_api.txt | 3 +
models.py | 3107 ++++++++++++++++++++++++++++++++++++++++++++++++
4 files changed, 3287 insertions(+)
create mode 100644 .DS_Store
create mode 100644 app_authKey.py
create mode 100644 key_api.txt
create mode 100644 models.py
diff --git a/.DS_Store b/.DS_Store
new file mode 100644
index 0000000000000000000000000000000000000000..a8976cb5df6626a8825a8a2092e19def77bbb6de
GIT binary patch
literal 6148
zcmeHKI|>3p3{6x-u(7n9D|mxJ^aNhOA7~civ3oe%cJ@7L6Fr(u#p!?-b^NMmVL!$
zBOGzZYLrm5gEV@<z}I6c5dFXPG%Gc#
pjQY%iO``glCFs^2G!+n1f3WhJLC0sCJ zmI_b-DnJFO02TP8fc0M3U>L|q1*iZOcq(AuhXOaOiA|t?IuLvW0QQh}!
f#FV6g<SzCN_b{z%;19plXg78g%4K*44x&FzBK=d}uydb3##nI_@uCE?NT_sQ?vtRiGQ&k@f#M
z{KNeJO5%<RP=UWvKzp;rY>HRP-r9OO>$L^Ggj>xWZicl}5WF1&y&Yp??Re}(QCDn@
X^P1QMIvshZ1Nk#xy3nY=uN8Oz`K%R
literal 0
HcmV?d00001
diff --git a/app_authKey.py b/app_authKey.py
new file mode 100644
index 0000000..3d415c1
--- /dev/null
+++ b/app_authKey.py
@@ -0,0 +1,177 @@
+from flask import Flask, request, render_template, jsonify
+from io import BytesIO
+from captchaModel.model import load_model, inference
+# from waitress import serve
+import numpy as np
+import base64
+from PIL import Image
+from waitress import serve
+from paste.translogger import TransLogger
+import time
+import math
+
+sess, dectection_graph = load_model()
+app = Flask(name)
+
+# app.config['SECRET_KEY'] = 'secret key here'
+# app.config['HOST'] = '0.0.0.0'
+# app.config['DEBUG'] = True
+# app.config["CACHE_TYPE"] = "null"
+
+# change to "redis" and restart to cache again
+
+# some time later
+# cache.init_app(app)
+
+
+# @app.route('/')
+# def home():
+# return "Hello World"
+
+# def shutdown_server():
+# func = request.environ.get('werkzeug.server.shutdown')
+# if func is None:
+# raise RuntimeError('Not running with the Werkzeug Server')
+# func()
+
+# @app.route('/shutdown', methods=['POST'])
+# def shutdown():
+# shutdown_server()
+# return 'Server shutting down...'
+
+
+@app.route('/api/predict/', methods=['GET', 'POST','DELETE', 'PATCH'])
+def api_predict():
print(request.is_json)
image_base64 = request.form['image']
image = base64.b64decode(image_base64)
image = Image.open(BytesIO(image))
if image.mode != "RGB":
image.convert("RGB")
image_arr = np.array(image, dtype=np.uint8)
# print(image_arr)
start_date = time.time()
res = inference(sess, dectection_graph, image_arr)
end_date = time.time()
result_date = start_date - end_date
# print(res)
return jsonify(answer=res, status=True, captcha=res, time=format(math.floor(result_date)).replace("-","") + "s")
return {
"captcha": res,
"time": format(math.floor(result_date)).replace("-","") + "s"}
return jsonify(answer=res, status=True)
print(apiKey)
apiKey = 'Pong11299'
+@app.route('/' , methods=['GET', 'POST','DELETE', 'PATCH'])
+def home():
+@app.route('/api/images/', methods=['POST'])
+def api_images():
+@app.route('/api/imgArr/', methods=['POST'])
+def api_imgArr():
+if name == "main":
app.run(debug=True)
app.config["CACHE_TYPE"] = "null"
serve(TransLogger(app, setup_console_handler=False), threads=20, host = '0.0.0.0',port=5000)
serve(TransLogger(app, setup_console_handler=False), threads=40, host = '0.0.0.0',port=5000)
diff --git a/key_api.txt b/key_api.txt
new file mode 100644
index 0000000..227d6a4
--- /dev/null
+++ b/key_api.txt
@@ -0,0 +1,3 @@
+Pong11299
+Apidwalin
+bas2563
diff --git a/models.py b/models.py
new file mode 100644
index 0000000..20da8b9
--- /dev/null
+++ b/models.py
@@ -0,0 +1,3107 @@
+_instance = None
+
+ast_transformers = List([], help=
+).tag(config=True)
+autocall = Enum((0,1,2), default_value=0, help=
+).tag(config=True)
+# TODO: remove all autoindent logic and put into frontends.
+# We can't do this yet because even runlines uses the autoindent.
+autoindent = Bool(True, help=
+).tag(config=True)
+automagic = Bool(True, help=
+).tag(config=True)
+banner1 = Unicode(default_banner,
+).tag(config=True)
+banner2 = Unicode('',
+).tag(config=True)
+cache_size = Integer(1000, help=
+).tag(config=True)
+color_info = Bool(True, help=
+).tag(config=True)
+colors = CaselessStrEnum(('Neutral', 'NoColor','LightBG','Linux'),
+).tag(config=True)
+debug = Bool(False).tag(config=True)
+disable_failing_post_execute = Bool(False,
+).tag(config=True)
+display_formatter = Instance(DisplayFormatter, allow_none=True)
+displayhook_class = Type(DisplayHook)
+display_pub_class = Type(DisplayPublisher)
+sphinxify_docstring = Bool(False, help=
+@observe("sphinxify_docstring")
+def _sphinxify_docstring_changed(self, change):
+enable_html_pager = Bool(False, help=
+@observe("enable_html_pager")
+def _enable_html_pager_changed(self, change):
+data_pub_class = None
+
+exit_now = Bool(False)
+exiter = Instance(ExitAutocall)
+@default('exiter')
+def _exiter_default(self):
+# Monotonically increasing execution counter
+execution_count = Integer(1)
+filename = Unicode("")
+ipython_dir= Unicode('').tag(config=True) # Set to get_ipython_dir() in init
+# Input splitter, to transform input line by line and detect when a block
+# is ready to be executed.
+input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
+# This InputSplitter instance is used to transform completed cells before
+# running them. It allows cell magics to contain blank lines.
+input_transformer_manager = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
+logstart = Bool(False, help=
logappend
to specify a log file to append logs to.+).tag(config=True)
+logfile = Unicode('', help=
+).tag(config=True)
+logappend = Unicode('', help=
logfile
to specify a log file to overwrite logs to.+).tag(config=True)
+object_info_string_level = Enum((0,1,2), default_value=0,
+).tag(config=True)
+pdb = Bool(False, help=
+).tag(config=True)
+display_page = Bool(False,
+).tag(config=True)
+# deprecated prompt traits:
+
+prompt_in1 = Unicode('In [\#]: ',
+).tag(config=True)
+prompt_in2 = Unicode(' .\D.: ',
+).tag(config=True)
+prompt_out = Unicode('Out[\#]: ',
+).tag(config=True)
+prompts_pad_left = Bool(True,
+).tag(config=True)
+@observe('prompt_in1', 'prompt_in2', 'prompt_out', 'prompt_pad_left')
+def _prompt_trait_changed(self, change):
protect against weird cases where self.config may not exist:
+show_rewritten_input = Bool(True,
+).tag(config=True)
+quiet = Bool(False).tag(config=True)
+
+history_length = Integer(10000,
+).tag(config=True)
+history_load_length = Integer(1000, help=
+).tag(config=True)
+ast_node_interactivity = Enum(['all', 'last', 'last_expr', 'none', 'last_expr_or_assign'],
+).tag(config=True)
+# TODO: this part of prompt management should be moved to the frontends.
+# Use custom TraitTypes that convert '0'->'' and '\n'->'\n'
+separate_in = SeparateUnicode('\n').tag(config=True)
+separate_out = SeparateUnicode('').tag(config=True)
+separate_out2 = SeparateUnicode('').tag(config=True)
+wildcards_case_sensitive = Bool(True).tag(config=True)
+xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
+# Subcomponents of InteractiveShell
+alias_manager = Instance('IPython.core.alias.AliasManager', allow_none=True)
+prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager', allow_none=True)
+builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap', allow_none=True)
+display_trap = Instance('IPython.core.display_trap.DisplayTrap', allow_none=True)
+extension_manager = Instance('IPython.core.extensions.ExtensionManager', allow_none=True)
+payload_manager = Instance('IPython.core.payload.PayloadManager', allow_none=True)
+history_manager = Instance('IPython.core.history.HistoryAccessorBase', allow_none=True)
+magics_manager = Instance('IPython.core.magic.MagicsManager', allow_none=True)
+
+profile_dir = Instance('IPython.core.application.ProfileDir', allow_none=True)
+@Property
+def profile(self):
+# Private interface
+_post_execute = Dict()
+
+# Tracks any GUI loop loaded for pylab
+pylab_gui_select = None
+
+last_execution_succeeded = Bool(True, help='Did last executed command succeeded')
+
+last_execution_result = Instance('IPython.core.interactiveshell.ExecutionResult', help='Result of executing the last command', allow_none=True)
+
+def init(self, ipython_dir=None, profile_dir=None,
This is where traits with a config_key argument are updated
from the values on config.
These are relatively independent and stateless
Check if we're in a virtualenv, and set up sys.path.
Create namespaces (user_ns, user_global_ns, etc.)
This has to be done after init_create_namespaces because it uses
something in self.user_ns, but before init_sys_modules, which
is the first thing to modify sys.
TODO: When we override sys.stdout and sys.stderr before this class
is created, we are saving the overridden ones here. Not sure if this
is what we want to do.
While we're trying to have each part of the code directly access what
it needs without keeping redundant references to objects, we have too
much legacy code that expects ip.db to exist.
The following was in post_config_initialization
TODO: init_io() needs to happen before init_traceback handlers
because the traceback handlers hardcode the stdout/stderr streams.
This logic in in debugger.Pdb and should eventually be changed.
+def get_ipython(self):
+#-------------------------------------------------------------------------
+# Trait changed handlers
+#-------------------------------------------------------------------------
+@observe('ipython_dir')
+def _ipython_dir_changed(self, change):
+def set_autoindent(self,value=None):
+#-------------------------------------------------------------------------
+# init_* methods called by init
+#-------------------------------------------------------------------------
+
+def init_ipython_dir(self, ipython_dir):
+def init_profile_dir(self, profile_dir):
+def init_instance_attrs(self):
command compiler
Make an empty namespace, which extension writers can rely on both
existing and NEVER being used by ipython itself. This gives them a
convenient location for storing additional information and state
their extensions may require, without fear of collisions with other
ipython names that may develop later.
Temporary files used for various purposes. Deleted at exit.
keep track of where we started running (mainly for crash post-mortem)
This is not being used anywhere currently.
Indentation management
Dict to track post-execution functions that have been registered
+def init_environment(self):
+def init_encoding(self):
Get system encoding at startup time. Certain terminals (like Emacs
under Win32 have it set to None, and we need to have a known valid
encoding to use in the raw_input() method
+@observe('colors')
+def init_syntax_highlighting(self, changes=None):
Python source parser/formatter for syntax highlighting
+def refresh_style(self):
No-op here, used in subclass
+def init_pushd_popd_magic(self):
for pushd/popd management
+def init_logger(self):
+def init_logstart(self):
+def init_deprecation_warnings(self):
+def init_builtins(self):
A single, static flag that we set to True. Its presence indicates
that an IPython shell has been created, and we make no attempts at
removing on exit or representing the existence of more than one
IPython at a time.
+@observe('colors')
+def init_inspector(self, changes=None):
Object inspector
+def init_io(self):
This will just use sys.stdout and sys.stderr. If you want to
override sys.stdout and sys.stderr themselves, you need to do that
before instantiating this class, because io holds onto
references to the underlying streams.
io.std* are deprecated, but don't show our own deprecation warnings
during initialization of the deprecated API.
+def init_prompts(self):
Set system prompts, so that scripts can decide if they are running
interactively.
+def init_display_formatter(self):
+def init_display_pub(self):
+def init_data_pub(self):
+def init_displayhook(self):
Initialize displayhook, set in/out prompts and printing system
This is a context manager that installs/revmoes the displayhook at
the appropriate time.
+def init_virtualenv(self):
executable path should end like /bin/python or \scripts\python.exe
fallback venv detection:
stdlib venv may symlink sys.executable, so we can't use realpath.
but others can symlink to the venv Python, so we can't just use sys.executable.
So we just check every item in the symlink tree (generally <= 3)
In Cygwin paths like "c:..." and '\cygdrive\c...' are possible
+#-------------------------------------------------------------------------
+# Things related to injections into the sys module
+#-------------------------------------------------------------------------
+
+def save_sys_module_state(self):
+def restore_sys_module_state(self):
Reset what what done in self.init_sys_modules
+#-------------------------------------------------------------------------
+# Things related to the banner
+#-------------------------------------------------------------------------
+
+@Property
+def banner(self):
+def show_banner(self, banner=None):
+#-------------------------------------------------------------------------
+# Things related to hooks
+#-------------------------------------------------------------------------
+
+def init_hooks(self):
hooks holds pointers used for user-side customizations
Set all default hooks, defined in the IPython.hooks module.
+def set_hook(self,name,hook, priority=50, str_key=None, re_key=None,
At some point in the future, this should validate the hook before it
accepts it. Probably at least check that the hook takes the number
of args it's supposed to.
check if the hook is for strdispatcher first
+#-------------------------------------------------------------------------
+# Things related to events
+#-------------------------------------------------------------------------
+
+def init_events(self):
+def register_post_execute(self, func):
+def _clear_warning_registry(self):
clear the warning registry, so that different code blocks with
overlapping line number ranges don't cause spurious suppression of
warnings (see gh-6611 for details)
+#-------------------------------------------------------------------------
+# Things related to the "main" module
+#-------------------------------------------------------------------------
+
+def new_main_mod(self, filename, modname):
filename
should be the path of the script which will be run in themodname
should be the module name - normally either 'main' orIt seems pydoc (and perhaps others) needs any module instance to
implement a nonzero method
+def clear_main_mod_cache(self):
+#-------------------------------------------------------------------------
+# Things related to debugging
+#-------------------------------------------------------------------------
+
+def init_pdb(self):
Set calling of pdb on exceptions
self.call_pdb is a property
+def _get_call_pdb(self):
+def _set_call_pdb(self,val):
+
store value in instance
notify the actual exception handlers
+call_pdb = property(_get_call_pdb,_set_call_pdb,None,
+def debugger(self,force=False):
+#-------------------------------------------------------------------------
+# Things related to IPython's various namespaces
+#-------------------------------------------------------------------------
+default_user_namespaces = True
+
+def init_create_namespaces(self, user_module=None, user_ns=None):
Create the namespace where the user will operate. user_ns is
normally the only one used, and it is passed to the exec calls as
the locals argument. But we do carry a user_global_ns namespace
given as the exec 'globals' argument, This is useful in embedding
situations where the ipython shell opens in a context where the
distinction between locals and globals is meaningful. For
non-embedded contexts, it is just the same object as the user_ns dict.
FIXME. For some strange reason, builtins is showing up at user
level as a dict instead of a module. This is a manual fix, but I
should really track down where the problem is coming from. Alex
Schmolck reported this problem first.
A useful post by Alex Martelli on this topic:
Re: inconsistent value from builtins
Von: Alex Martelli aleaxit@yahoo.com
Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
Gruppen: comp.lang.python
Michael Hohn hohn@hooknose.lbl.gov wrote:
> >>> print type(builtin_check.get_global_binding('builtins'))
> <type 'dict'>
> >>> print type(builtins)
> <type 'module'>
> Is this difference in return value intentional?
Well, it's documented that 'builtins' can be either a dictionary
or a module, and it's been that way for a long time. Whether it's
intentional (or sensible), I don't know. In any case, the idea is
that if you need to access the built-in namespace directly, you
should start with "import builtin" (note, no 's') which will
definitely give you a module. Yeah, it's somewhat confusing:-(.
These routines return a properly built module and dict as needed by
the rest of the code, and can also be used by extension writers to
generate properly initialized namespaces.
A record of hidden variables we have added to the user namespace, so
we can list later only variables defined in actual interactive use.
Now that FakeModule produces a real module, we've run into a nasty
problem: after script execution (via %run), the module where the user
code ran is deleted. Now that this object is a true module (needed
so doctest and other tools work correctly), the Python module
teardown mechanism runs over it, and sets to None every variable
present in that module. Top-level references to objects from the
script survive, because the user_ns is updated with them. However,
calling functions defined in the script that use other things from
the script will fail, because the function's closure had references
to the original objects, which are now all None. So we must protect
these modules from deletion by keeping a cache.
To avoid keeping stale modules around (we only need the one from the
last run), we use a dict keyed with the full path to the script, so
only the last version of the module is held in the cache. Note,
however, that we must cache the module namespace contents (their
dict). Because if we try to cache the actual modules, old ones
(uncached) could be destroyed while still holding references (such as
those held by GUI objects that tend to be long-lived)>
The %reset command will flush this cache. See the cache_main_mod()
and clear_main_mod_cache() methods for details on use.
This is the cache used for 'main' namespaces
A table holding all the namespaces IPython deals with, so that
introspection facilities can search easily.
+@Property
+def user_global_ns(self):
+def prepare_user_module(self, user_module=None, user_ns=None):
We must ensure that builtin (without the final 's') is always
available and pointing to the builtin module. For more details:
http://mail.python.org/pipermail/python-dev/2001-April/014068.html
+def init_sys_modules(self):
We need to insert into sys.modules something that looks like a
module but which accesses the IPython namespace, for shelve and
pickle to work interactively. Normally they rely on getting
everything out of main, but for embedding purposes each IPython
instance has its own private namespace, so we can't go shoving
everything into main.
note, however, that we should only do this for non-embedded
ipythons, which really mimic the main.dict with their own
namespace. Embedded instances, on the other hand, should not do
this because they need to manage the user local/global namespaces
only, but they live within a 'normal' main (meaning, they
shouldn't overtake the execution environment of the script they're
embedded in).
This is overridden in the InteractiveShellEmbed subclass to a no-op.
+def init_user_ns(self):
This function works in two parts: first we put a few things in
user_ns, and we sync that contents into user_ns_hidden so that these
initial variables aren't shown by %who. After the sync, we add the
rest of what we do want the user to see with %who even on a new
session (probably nothing, so they really only see their own stuff)
The user dict must always have a builtin reference to the
Python standard builtin namespace, which must be imported.
This is so that certain operations in prompt evaluation can be
reliably executed with builtins. Note that we can NOT use
builtins (note the 's'), because that can either be a dict or a
module, and can even mutate at runtime, depending on the context
(Python makes no guarantees on it). In contrast, builtin is
always a module object, though it must be explicitly imported.
For more details:
http://mail.python.org/pipermail/python-dev/2001-April/014068.html
make global variables for user access to the histories
user aliases to input and output histories. These shouldn't show up
in %who, as they can have very large reprs.
Store myself as the public api!!!
Sync what we've added so far to user_ns_hidden so these aren't seen
by %who
Anything put into ns now would show up in %who. Think twice before
putting anything here, as we really want %who to show the user their
stuff, not our variables.
Finally, update the real user's namespace
+@Property
+def all_ns_refs(self):
+def reset(self, new_session=True):
Clear histories
Reset counter used to index all histories
Reset last execution result
Flush cached output items
The main execution namespaces must be cleared very carefully,
skipping the deletion of the builtin-related keys, because doing so
would cause errors in many object's del methods.
Restore the user namespaces to minimal usability
Restore the default and user aliases
Flush the private list of module references kept for script
execution protection
+def del_var(self, varname, by_name=False):
+def reset_selective(self, regex=None):
+def push(self, variables, interactive=True):
We need a dict of name/value pairs to do namespace updates.
Propagate variables to user namespace
And configure interactive visibility
+def drop_by_id(self, variables):
+#-------------------------------------------------------------------------
+# Things related to object introspection
+#-------------------------------------------------------------------------
+
+def _ofind(self, oname, namespaces=None):
Look for the given name by splitting it in parts. If the head is
found, then we look for all the remaining parts as members, and only
declare success if we can find them all.
Try to see if it's magic
Last try: special-case some literals like '', [], {}, etc:
+@staticmethod
+def _getattr_property(obj, attrname):
Nothing helped, fall back.
+def _object_find(self, oname, namespaces=None):
+def _inspect(self, meth, oname, namespaces=None, **kw):
+def object_inspect(self, oname, detail_level=0):
+def object_inspect_text(self, oname, detail_level=0):
+def object_inspect_mime(self, oname, detail_level=0):
'text/plain'
.+#-------------------------------------------------------------------------
+# Things related to history management
+#-------------------------------------------------------------------------
+
+def init_history(self):
+#-------------------------------------------------------------------------
+# Things related to exception handling and tracebacks (not debugging)
+#-------------------------------------------------------------------------
+
+debugger_cls = Pdb
+
+def init_traceback_handlers(self, custom_exceptions):
Syntax error handler.
The interactive one is initialized with an offset, meaning we always
want to remove the topmost item in the traceback, which is our own
internal code. Valid modes: ['Plain','Context','Verbose']
The instance will store a pointer to the system-wide exception hook,
so that runtime code (such as magics) can access it. This is because
during the read-eval loop, it may get temporarily overwritten.
and add any custom exception handlers the user may have specified
Set the exception mode
+def set_custom_exc(self, exc_tuple, handler):
+def excepthook(self, etype, value, tb):
+def _get_exc_info(self, exc_tuple=None):
Now store the exception info in sys.last_type etc.
WARNING: these variables are somewhat deprecated and not
necessarily safe to use in a threaded environment, but tools
like pdb depend on their existence, so let's set them. If we
find problems in the field, we'll need to revisit their use.
+def show_usage_error(self, exc):
+def get_exception_only(self, exc_tuple=None):
+def showtraceback(self, exc_tuple=None, filename=None, tb_offset=None,
+def _showtraceback(self, etype, evalue, stb):
+def showsyntaxerror(self, filename=None, running_compiled_code=False):
If the error occurred when executing compiled code, we should provide full stacktrace.
+# This is overridden in TerminalInteractiveShell to show a message about
+# the %paste magic.
+def showindentationerror(self):
+#-------------------------------------------------------------------------
+# Things related to readline
+#-------------------------------------------------------------------------
+
+def init_readline(self):
Set a number of methods that depend on readline to be no-op
init_readline
is no-op since IPython 5.0 and is Deprecated',+@skip_doctest
+def set_next_input(self, s, replace=False):
+def _indent_current_str(self):
+#-------------------------------------------------------------------------
+# Things related to text completion
+#-------------------------------------------------------------------------
+
+def init_completer(self):
Add custom completers to the basic ones built into IPCompleter
+@skip_doctest
+def complete(self, text, line=None, cursor_pos=None):
Inject names into builtin so we can complete on the added names.
+def set_custom_completer(self, completer, pos=0):
+def set_completer_frame(self, frame=None):
+#-------------------------------------------------------------------------
+# Things related to magics
+#-------------------------------------------------------------------------
+
+def init_magics(self):
Expose as public API from the magics manager
Register Magic Aliases
FIXME: magic aliases should be defined by the Magics classes
or in MagicsManager, not here
FIXME: Move the color initialization to the DisplayHook, which
should be split into a prompt manager and displayhook. We probably
even need a centralize colors management object.
+# Defined here so that it's included in the documentation
+@functools.wraps(magic.MagicsManager.register_function)
+def register_magic_function(self, func, magic_kind='line', magic_name=None):
+def run_line_magic(self, magic_name, line, _stack_depth=1):
+def run_cell_magic(self, magic_name, line, cell):
+def find_line_magic(self, magic_name):
+def find_cell_magic(self, magic_name):
+def find_magic(self, magic_name, magic_kind='line'):
+def magic(self, arg_s):
TODO: should we issue a loud deprecation warning here?
+#-------------------------------------------------------------------------
+# Things related to macros
+#-------------------------------------------------------------------------
+
+def define_macro(self, name, themacro):
+#-------------------------------------------------------------------------
+# Things related to the running of system commands
+#-------------------------------------------------------------------------
+
+def system_piped(self, cmd):
we explicitly do NOT return the subprocess status code, because
a non-None value would trigger :func:
sys.displayhook
calls.Instead, we store the exit_code in user_ns.
+def system_raw(self, cmd):
protect os.system from UNC paths on Windows, which it can't handle:
We explicitly do NOT return the subprocess status code, because
a non-None value would trigger :func:
sys.displayhook
calls.Instead, we store the exit_code in user_ns. Note the semantics
of _exit_code: for control-c, _exit_code == -signal.SIGNIT,
but raising SystemExit(_exit_code) will give status 254!
+# use piped system by default, because it is better behaved
+system = system_piped
+
+def getoutput(self, cmd, split=True, depth=0):
+#-------------------------------------------------------------------------
+# Things related to aliases
+#-------------------------------------------------------------------------
+
+def init_alias(self):
+#-------------------------------------------------------------------------
+# Things related to extensions
+#-------------------------------------------------------------------------
+
+def init_extension_manager(self):
+#-------------------------------------------------------------------------
+# Things related to payloads
+#-------------------------------------------------------------------------
+
+def init_payload(self):
+#-------------------------------------------------------------------------
+# Things related to the prefilter
+#-------------------------------------------------------------------------
+
+def init_prefilter(self):
Ultimately this will be refactored in the new interpreter code, but
for now, we should expose the main prefilter method (there's legacy
code out there that may rely on this).
+def auto_rewrite_input(self, cmd):
This is overridden in TerminalInteractiveShell to use fancy prompts
+#-------------------------------------------------------------------------
+# Things related to extracting values/expressions from kernel and user_ns
+#-------------------------------------------------------------------------
+
+def _user_obj_error(self):
+def _format_user_obj(self, obj):
+def user_expressions(self, expressions):
+#-------------------------------------------------------------------------
+# Things related to the running of code
+#-------------------------------------------------------------------------
+
+def ex(self, cmd):
+def ev(self, expr):
+def safe_execfile(self, fname, *where, exit_ignore=False, raise_exceptions=False, shell_futures=False):
Make sure we can open the file
Find things also in current directory. This is needed to mimic the
behavior of running a script from the system command line, where
Python inserts the script's directory into sys.path
+def safe_execfile_ipy(self, fname, shell_futures=False, raise_exceptions=False):
Make sure we can open the file
Find things also in current directory. This is needed to mimic the
behavior of running a script from the system command line, where
Python inserts the script's directory into sys.path
+def safe_run_module(self, mod_name, where):
SystemExit
exceptions with status code 0 or None are ignored.+def run_cell(self, raw_cell, store_history=False, silent=False, shell_futures=True):
ExecutionResult
+def _run_cell(self, raw_cell, store_history, silent, shell_futures):
ExecutionResult
If any of our input transformation (input_transformer_manager or
prefilter_manager) raises an exception, we store it in this variable
so that we can display the error after logging the input and storing
it in the history.
Store raw and processed history
Display the exception if input processing failed.
Our own compiler remembers the future environment. If we want to
run code with a separate future environment, use the default
compiler
+def transform_ast(self, node):
+def run_ast_nodes(self, nodelist:ListType[AST], cell_name:str, interactivity='last_expr',
+def run_code(self, code_obj, result=None):
Set our own excepthook in case the user code tries to call it
directly, so that the IPython crash handler doesn't get triggered
we save the original sys.excepthook in the instance, in case config
code (such as magics) needs access to it.
+# For backwards compatibility
+runcode = run_code
+
+def check_complete(self, code):
+#-------------------------------------------------------------------------
+# Things related to GUI support and pylab
+#-------------------------------------------------------------------------
+
+active_eventloop = None
+
+def enable_gui(self, gui=None):
+def enable_matplotlib(self, gui=None):
Now we must activate the gui pylab wants to use, and fix %run to take
plot updates into account
+def enable_pylab(self, gui=None, import_all=True, welcome_message=False):
gui
argument.We want to prevent the loading of pylab to pollute the user's
namespace as shown by the %who* magics, so we execute the activation
code in an empty namespace, and we update both user_ns and
user_ns_hidden with this information.
warn about clobbered names
+#-------------------------------------------------------------------------
+# Utilities
+#-------------------------------------------------------------------------
+
+def var_expand(self, cmd, depth=0, formatter=DollarFormatter()):
+def mktempfile(self, data=None, prefix='ipython_edit_'):
+@undoc
+def write(self,data):
+@undoc
+def write_err(self,data):
+def ask_yes_no(self, prompt, default=None, interrupt=None):
+def show_usage(self):
+def extract_input_lines(self, range_str, raw=False):
N:M
-> standard python form, means including items N...(M-1).N-M
-> include items N..M (closed endpoint).+def find_user_code(self, target, raw=True, py_only=False, skip_encoding_cookie=True, search_ns=False):
+#-------------------------------------------------------------------------
+# Things related to IPython exiting
+#-------------------------------------------------------------------------
+def atexit_operations(self):
Close the history session (this stores the end time and line count)
this must be before the tempfile cleanup, in case of temporary
history db
Cleanup all tempfiles and folders left around
Clear all user namespaces to release all references cleanly.
Run user hooks
+def cleanup(self):
+# Overridden in terminal subclass to change prompts
+def switch_doctest_mode(self, mode):