Modify title of SublimeREPL in tab - sublimetext3

I'm using the SublimeREPL package. The title in the tab where the code is running is very long and makes navigating the tabs a hassle:
Can the title shown in the REPL tab be modified and/or suppressed all together?

In the answer you linked, one of the steps was to create a custom plugin to run your virtualenv REPL. You can customize the tab's title by changing the repl_open method to pass an "external_id" key and value. Here is the modified plugin code:
import sublime_plugin
class ProjectVenvReplCommand(sublime_plugin.TextCommand):
"""
Starts a SublimeREPL, attempting to use project's specified
python interpreter.
"""
def run(self, edit, open_file='$file', name='Python'):
"""Called on project_venv_repl command"""
cmd_list = [self.get_project_interpreter(), '-i', '-u']
if open_file:
cmd_list.append(open_file)
self.repl_open(cmd_list=cmd_list, name=name)
def get_project_interpreter(self):
"""Return the project's specified python interpreter, if any"""
settings = self.view.settings()
return settings.get('python_interpreter', '/usr/bin/python')
def repl_open(self, cmd_list, name):
"""Open a SublimeREPL using provided commands"""
self.view.window().run_command(
'repl_open', {
'encoding': 'utf8',
'type': 'subprocess',
'cmd': cmd_list,
'cwd': '$file_path',
'syntax': 'Packages/Python/Python.sublime-syntax',
'external_id': name
}
)
And here you can modify the arguments you send to the plugin to define the tab's name (the default being Python):
{
"keys": ["f6"],
"command": "project_venv_repl",
"args": {
"open_file": null,
"name": "My Project Name" // insert name of choice here.
}
},

Related

How to pass a string from python to AWS Run Powershell script commands section using boto3

Is there anyway to pass the variable (var) defined in python idle to AWS-RunPowerShellScript commands section ?
Here is my code:
import boto3
ssm = boto3.client("ssm")
var = "test"
res = ssm.send_command(
DocumentName="AWS-RunPowerShellScript",
Targets=[
{
'Key': 'tag:test',
'Values': ['testing']
}
]
Comment="Test",
Parameters={'commands':[
'hostname',
'$var'
]
}
)
In the above code, I am defining variable var in python and the same I want to refer in the commands section of the send_command as $var but it seems like it is not working due to the remote execution. Is there any possibility to pass the variable from python to the commands section ?
You can build the command string before calling send_command with the ssm_client. Then reference the variable in the parameters.
This can be done with any type of send_command including AWS-RunShellScript or AWS-RunPowershellScript
In your example above, note that you have used '$var' which is a actually a string since it is wrapped in ''. Also note that in Python, the $ char is not used to reference variables. That is a PHP thing.
import boto3
ssm_client = boto3.client('ssm')
# build your command string here
command = "echo 'hello world' > testfile.txt"
# send command
response = ssm_client.send_command(
DocumentName="AWS-RunShellScript",
Targets=[
{
'Key': 'tag:test',
'Values': ['testing']
}
],
# the command var is just a string after all
Parameters={'commands': [command]}
)
print(response)

Groovy call another script to set variables

I'm trying to define variables in another groovy script that I want to use in my current script. I have two scripts like this:
script1.groovy
thing = evaluate(new File("script2.groovy"))
thing.setLocalEnv()
println(state)
script2.groovy
static def setLocalEnv(){
def state = "hi"
def item = "hey"
}
When I println(state), I get a missing property exception. Basically I want script2 to have config variables that I can load in the context of script1. How can I do this?
I'm not sure what/how you want to do exactly, but I guess you can achieve your goal using one of the class available in groovy dynamique scripting capabilities: groovy.lang.Binding or GroovyClassLoader or GroovyScriptEngine, here is an example using GroovyShell class:
abstract class MyScript extends Script {
String name
String greet() {
"Hello, $name!"
}
}
import org.codehaus.groovy.control.CompilerConfiguration
def config = new CompilerConfiguration()
config.scriptBaseClass = 'MyScript'
def shell = new GroovyShell(this.class.classLoader, new Binding(), config)
def script = shell.parse('greet()')
assert script instanceof MyScript
script.setName('covfefe')
assert script.run() == 'Hello, covfefe!'
This is one way to bind a variable to an external script file, more examples from the doc:
http://docs.groovy-lang.org/latest/html/documentation/guide-integrating.html
P.S. Loading external file can be done with GroovyClassLoader:
def gcl = new GroovyClassLoader()
def clazz2 = gcl.parseClass(new File(file.absolutePath))
Hope this helps.

Creating dashboard for a web site using python

I need to build a dashboard for a website. Could you please give me some suggestion. I want to use python. Thanks in advance.
I would look into the Flask framework.
Per their website:
Flask is a microframework for Python based on Werkzeug, Jinja 2 and good intentions.
The documentation is really good and I've used it at work for several dashboard style projects.
Here is something I have drawn up amending the resources I have around the internet.
This app creates a simple sidebar layout using inline style arguments and the
dbc.Nav component.
dcc.Location is used to track the current location, and a callback uses the
current location to render the appropriate page content.
Each page should have a different chart layout as its content.
The active prop of each NavLink is set automatically according to the current
pathname. To use this feature you must install dash-bootstrap-components >= 0.11.0.
For more details on building multi-page Dash applications, check out the Dash
documentation: https://dash.plot.ly/urls
import dash
from dash import dcc
from dash import html
import dash_bootstrap_components as dbc
from dash.dependencies import Input, Output #for the callbacks
app = dash.Dash(external_stylesheets=[dbc.themes.DARKLY])
# the style arguments for the sidebar. We use position:fixed and a fixed width
SIDEBAR_STYLE = {
"position": "fixed",
"top": 0,
"left": 0,
"bottom": 0,
"width": "16rem",
"padding": "2rem 1rem",
"background-color": "black",
}
# the styles for the main content position it to the right of the sidebar and
# add some padding.
CONTENT_STYLE = {
"margin-left": "18rem",
"margin-right": "2rem",
"padding": "2rem 1rem",
}
sidebar = html.Div(
[
html.H2("Sidebar", className="display-4"),
html.Hr(),
html.P(
"A simple sidebar layout with navigation links", className="lead"
),
dbc.Nav(
[
dbc.NavLink("Home", href="/", active="exact"),
dbc.NavLink("Page 1", href="/page-1", active="exact"),
dbc.NavLink("Page 2", href="/page-2", active="exact"),
dbc.NavLink("Page 3", href="/page-3", active="exact"),
],
vertical=True,
pills=True,
),
],
style=SIDEBAR_STYLE,
)
content = html.Div(id="page-content", style=CONTENT_STYLE)
header = html.H4(
"Side Example.py", className="bg-primary text-white p-2 mb-2 text-center"
)
app.layout = html.Div([dcc.Location(id="url"),sidebar,header,content])
#app.callback(Output("page-content", "children"),[Input("url", "pathname")])
#Output("line-chart", "figure"),
def render_page_content(pathname):
if pathname == "/":
return dbc.NavbarSimple(children=[html.H2('Particular info for HOMEPAGE')],color="grey",dark=True,)
elif pathname == "/page-1":
return dbc.NavbarSimple(children=[html.H2('Particular info for PAGE1')],color="grey",dark=True,)
elif pathname == "/page-2":
return dbc.NavbarSimple(children=[html.H2('Particular info for PAGE2')],color="grey",dark=True,)
# If the user tries to reach a different page, return a 404 message
return dbc.Jumbotron(
[
html.H1("404: Not found", className="text-danger"),
html.Hr(),
html.P(f"The pathname {pathname} was not recognised..."),
]
)
if __name__ == "__main__":
app.run_server(port=8001)

Jenkins Plugin Installation

I have written a Jenkins Groovy Script for installing Jenkins plugin at startup. Groovy scripts are named after the Hook that is used to invoke my scripts. E.g. init.groovy is triggered inside the init-Hook. This Hook is triggered in post-initialization.
During initialization I have no access to the UpdateCenter and cannot install the plugins. What other Jenkins Hooks can I use? In my opinion I need a post-startup Hook.
This script works in script console but not inside post-initialization hook:
import jenkins.model.*
def pluginParameter="gitlab-plugin hipchat swarm"
def plugins = pluginParameter.split()
println(plugins)
def instance = Jenkins.getInstance()
def pm = instance.getPluginManager()
def uc = instance.getUpdateCenter()
def installed = false
plugins.each {
if (!pm.getPlugin(it)) {
def plugin = uc.getPlugin(it)
if (plugin) {
println("Installing " + it)
plugin.deploy()
installed = true
}
}
}
instance.save()
if (installed)
instance.doSafeRestart()
I need a hook where system is started and uc.getPlugin(it) does not return null.
Solved this by asking the jenkins-irc channel. I needed to initialize the UpdateCenter's list of update sites. The result can be found here:
blacklabelops/jenkins

cherrypy - 'module' object has no attribute session when run with uWSGI

I am using cherrypy 3.6.0, nginx 1.6.2 and uWSGI 2.0.9 on amazon linux.
uwsgi.json config:
{
"uwsgi": {
"socket": ["127.0.0.1:8080"],
"master": True,
"processes": 1,
"threads": 24,
"uid": "ec2-user",
"protocol": "http",
"vacuum": True
"chdir": "/usr/local/src/myapp",
"wsgi-file": "/usr/local/src/myapp/wsgi.py",
"logto": "/var/log/uwsgi.log"
}
}
I try enabling sessions:
cherrypy.config.update({
'server.socket_host': '0.0.0.0',
'engine.autoreload.on': False,
'server.socket_port': 8080,
'request.dispatch': cherrypy.dispatch.MethodDispatcher(),
'tools.sessions.on' : True,
'tools.sessions.storage_type': "file",
'tools.sessions.storage_path': "/home/ec2-user/.cherrypy_sessions",
'tools.sessions.timeout': 60
})
to use them here:
import cherrypy
import random
import string
import json
import urllib.parse
class IdentityApi(object):
#cherrypy.expose
def gen_crosssite(self):
crsf = ''.join(random.choice(string.ascii_uppercase + string.digits) for x in range(32))
cherrypy.session['my_state'] = crsf;
return json.dumps({'crsf': crsf})
I get the following exception:
[25/Feb/2015:15:51:36] HTTP Traceback (most recent call last):
File "/usr/local/lib/python3.4/site-packages/cherrypy/_cprequest.py", line 670, in respond
response.body = self.handler()
File "/usr/local/lib/python3.4/site-packages/cherrypy/lib/encoding.py", line 217, in __call__
self.body = self.oldhandler(*args, **kwargs)
File "/usr/local/lib/python3.4/site-packages/cherrypy/_cpdispatch.py", line 61, in __call__
return self.callable(*self.args, **self.kwargs)
File "./api/IdentityApi.py", line 25, in gen_crsf
cherrypy.session['my_state'] = crsf;
AttributeError: 'module' object has no attribute 'session'
update: Running it from the commandline 'python3 wsgi.py' and WITHOUT uWSGI works.
Had to comment out:
cherrypy.server.unsubscribe()
cherrypy.engine.start()
updated wsgi.py:
if __name__ == '__main__':
cherrypy.log('jobtagr log file = %s', cherrypy.log.access_file)
setup_logging()
cherrypy.config.update({
'server.socket_host': '0.0.0.0',
'engine.autoreload.on': False,
'server.socket_port': 8080,
'request.dispatch': cherrypy.dispatch.MethodDispatcher(),
'tools.sessions.on' : True,
'tools.sessions.storage_type': "file",
'tools.sessions.storage_path': "/home/ec2-user/.cherrypy_sessions",
'tools.sessions.timeout': 60
})
# cherrypy.server.unsubscribe()
# cherrypy.engine.start()
cherrypy.quickstart(application)
How do I get sessions to work under uWSGI?
Observations:
cherrypy.session attribute doesn't exist unless sessions.init is called by the session tool,
Don't mix global (server, engine) and application (tools, dispatch) configs,
Don't mess with routing. You've declared HTTP verb dispatch, but I see non-verb gen_crosssite.
Update
I've modelled your case and see the problem now. It's documented behaviour but it is a little subtle anyway. It happens when you switch from cherrypy.quickstart which is more demo thing, to managing real setup with cherrypy.tree.mount without paying attention to what happens with configuration. Here's cherrypy.quickstart, it's small:
def quickstart(root=None, script_name="", config=None):
if config:
_global_conf_alias.update(config)
tree.mount(root, script_name, config)
engine.signals.subscribe()
engine.start()
engine.block()
As you see, it sets both, server (global) config and application config in tree.mount. Here's the warning from Basics documentation section about global config:
cherrypy.config.update() is not meant to be used to configure the application. It is a common mistake. It is used to configure the server and engine.
And here's Combined Configuration Files section:
If you are only deploying a single application, you can make a single config file that contains both global and app entries. Just stick the global entries into a config section named [global] (or top level key global), and pass the same file to both config.update and tree.mount. If you’re calling cherrypy.quickstart(app root, script name, config), it will pass the config to both places for you. But as soon as you decide to add another application to the same site, you need to separate the two config files/dicts.
Here goes your case modelled with two applications:
#!/usr/bin/env python3
import random
import string
import cherrypy
class Api:
def __init__(self):
self.string = String()
# ...
class String:
exposed = True
def GET(self):
return cherrypy.session.get('mystring', '')
def POST(self, length=8):
result = ''.join(random.sample(string.hexdigits, int(length)))
cherrypy.session['mystring'] = result
return result
def PUT(self, new):
cherrypy.session['mystring'] = new
def DELETE(self):
cherrypy.session.pop('mystring', None)
class Token:
#cherrypy.expose
def csrf(self):
crsf = ''.join(random.choice(string.ascii_uppercase + string.digits) for x in range(32))
cherrypy.session['csrf'] = crsf
return {'crsf': crsf}
if __name__ == '__main__':
# global server config
cherrypy.config.update({
'server.socket_host' : '0.0.0.0',
'server.socket_port' : 8080,
})
# applicaton config is provided
cherrypy.tree.mount(Api(), '/api', {
'/' : {
'tools.sessions.on' : True,
'request.dispatch' : cherrypy.dispatch.MethodDispatcher(),
},
'/string' : {
'tools.response_headers.on' : True,
'tools.response_headers.headers' : [('Content-Type', 'text/plain')]
}
})
# applicaton config is provided
cherrypy.tree.mount(Token(), '/token', {'/' : {
'tools.sessions.on' : True,
'tools.json_out.on' : True,
}})
cherrypy.engine.signals.subscribe()
cherrypy.engine.start()
cherrypy.engine.block()
I got this error very recently, it turned out to be a problem with my uwsgi configuration. I suggest checking your uwsgi error log and pasting the last few lines here.
Here's my config file; perhaps compare it to yours and make sure you have correct values for each.
chdir=/root/Dropbox/QUTE_deployment
module=QUTE:app
master=True
vacuum=True
socket=/tmp/qute.sock
pidfile=/tmp/qute.pid
processes=1
threads=24
daemonize=/var/log/uwsgi.log
wsgi-file=/root/Dropbox/QUTE_deployment/QUTE.py

Resources