Colored output in Runnig console in IDEA (PyCharm) - intellij-idea

I try log colored messages to PyCharm running console.
Yes, I have read that running console and embedded terminal is different thing, but:
For my code emited log message printed white, but it look colored if I just print() message. So looks like running console support colors, but I don't understand how enable it.
class DefaultHandler(logging.Handler):
def emit(self, record):
log_entry = self.format(record)
m = re.match('^(\[.*?\])', log_entry)
if m:
time = click.style(m.groups()[0], fg='magenta')
msg = click.style(log_entry[m.end():], **get_log_format(record))
click.echo(time + msg) # <- log emit
print(time, msg) # <- just print
else:
click.secho(log_entry, **get_log_format(record))
As you can see log message is white, but printed message is colored.

I'm not positive what your question is, but PyCharm has support for different colors on the console.
Console: Background, Error, output, Standard output, System output, User input
Log Console: Error, Expired entry, Warning
ANSI Colors
You have the ability to look at the defaults and modify them through Settings | Editor | Color Scheme | Console Colors. Is this what you're looking for?

Related

How do I get input from the console in Red language

I'm writing a console program (target MSDOS) in Red language and I need to ask the user to enter a character or a string, then to press Enter.
I can't seem to find how to do it, I've read the docs here (http://www.red-by-example.org/index.html) to no avail.
I tried something like this:
read.red
Red [
]
print "Please make your choice then press Enter"
x: input
print x
It works in the "Red Console" with red read.red but when I compile with red -r -t MSDOS read.red I get an error:
Compiling C:\apps\red-read\read.red ...
*** Compilation Error: undefined word input
*** in file: C:\apps\red-read\read.red
*** near: [
input
]
How do I ask for input from a Red console program?
I'm using Red version: --== Red 0.6.3 ==--.
Okay, I did some testing and got it working on my end. You need 2 things.
1) You need the latest build, not 0.63. You can grab the automated build from master from the downloads page.
2) You need a reference in your file to use the console. Here is the updated code which will work on Windows with the latest version.
Red [
]
#include %environment/console/CLI/input.red
print "Please make your choice then press Enter"
x: input
print x
This info was buried away in an article on github. Also, you were right about MSDOS.

How do you encrypt a message into a picture using Jython

I'm having problems with an assignment and am in no means looking for someone to do my homework for me. Our professor does not answer or provide adequate resources to our questions for our assignments. I have copied an example code that was given to us, but I am unable to make this itself run.
When I run this program all I receive in the command line is an ellipsis and nothing else.
Does anyone have an idea what the ellipsis means?
My code and command line screenshot
Screenshot of my example code
Attached will be the code:
def encode(msgPic,original):
# Assume msgPic and original have same dimensions
# First, make all red pixels even
for pxl in getPixels(original):
# Using modulo operator to test oddness
if (getRed(pxl) % 2) == 1:
setRed(pxl, getRed(pxl) - 1)
# Second, wherever there???s black in msgPic
# make odd the red in the corresponding original pixel
for x in range(0,getWidth(original)):
for y in range(0,getHeight(original)):
msgPxl = getPixel(msgPic,x,y)
origPxl = getPixel(original,x,y)
if (distance(getColor(msgPxl),black) < 100.0):
# It's a message pixel! Make the red value odd.
setRed(origPxl, getRed(origPxl)+1)
Below is the code that the example prompts to input into the command line:
- beach = makePicture(getMediaPath("beach.jpg"))
- explore(beach)"
- msg = makePicture(getMediaPath("msg.jpg"))
- encode(msg,beach)
- explore(beach)
- writePictureTo(beach,getMediaPath("beachHidden.png"))

Display log into console with tf_logging

I'm playing with slim.learning.train and want to display the log in the console. According to the source code this is done using tf_logging module :
if 'should_log' in train_step_kwargs:
if sess.run(train_step_kwargs['should_log']):
logging.info('global step %d: loss = %.4f (%.2f sec)',
np_global_step, total_loss, time_elapsed)
I can run my training loop but there's no logs in the console. How can I enable it ?
tf.logging.info() goes to stderr, not stdout, as mentioned here:
https://groups.google.com/a/tensorflow.org/forum/#!msg/discuss/SO_JRts-VIs/JG1x8vOLDAAJ
and i can verify this from my personal experience, having spent several hours twiddling versions of subprocess.Popen()'s parameters, and not capturing the logging. a simple change to stderr=PIPE worked, as in my specific example, which you should be able to generalize to your problem.
training_results = Popen(cmds,shell=False,stderr=PIPE,bufsize=1,executable="python")
for line in iter(training_results.stderr.readline, b''):
print line
if line.startswith("INFO:tensorflow:Final test accuracy"):
tf_final_acc = line
training_results.wait() # wait for the subprocess to exit

Update current line with command line tool in Swift

I built a OS X command line tool in Swift (same problem in Objective-C) for downloading certain files. I am trying to update the command line with download progress. Unfortunately, I cannot prevent the print statement to jump to the next line.
According to my research, the carriage return \r should jump to the beginning of the same line (while \n would insert a new line).
All tests have been performed in the OS X Terminal app, not the Xcode console.
let logString = String(format: "%2i%% %.2fM \r", percentage, megaBytes)
print(logString)
Still, the display inserts a new line. How to prevent this?
Note: This won't work in Xcode's debugger window because it's not a real terminal emulator and doesn't fully support escape sequences. So, to test things, you have to compile it and then manually run it in a Terminal window.
\r should work to move to the beginning of the current line in most terminals, but you should also take a look at VT100 Terminal Control Escape Sequences. They work by sending an escape character, \u{1B} in Swift, and then a command. (Warning: they make some pretty ugly string definitions)
One that you'll probably need is \u{1B}[K which clears the line from the current cursor position to the end. If you don't do this and your progress output varies in length at all, you'll get artifacts left over from previous print statements.
Some other useful ones are:
Move to any (x, y) position: \u{1B}[\(y);\(x)H Note: x and y are Ints inserted with string interpolation.
Save cursor state and position: \u{1B}7
Restore cursor state and position: \u{1B}8
Clear screen: \u{1B}[2J
You can also do interesting things like set text foreground and background colors.
If for some reason you can't get \r to work, you could work around it by saving the cursor state/position just before you print your logString and then restoring it after:
let logString = String(format: "\u{1B}7%2i%% %.2fM \u{1B}8", percentage, megaBytes)
print(logString)
Or by moving to a pre-defined (x, y) position, before printing it:
let x = 0
let y = 1 // Rows typically start at 1 not 0, but it depends on the terminal and shell
let logString = String(format: "\u{1B}[\(y);\(x)H%2i%% %.2fM ", percentage, megaBytes)
print(logString)
Here's an example assuming some async task is taking place with callbacks that pass a Progress type.
// Print an empty string first otherwise whichever line is above the printed out progress will be removed
print("")
let someProgressCallback: ExampleAsyncCallbackType = { progress in
let percentage = Int(progress.fractionCompleted * 100)
print("\u{1B}[1A\u{1B}[KDownloaded: \(percentage)%")
}
The key part is \u{1B}[1A\u{1B}[K and then whatever you want to print out to the screen following.
Your example will only work on the actual command line, not in the debugger console. And you also need to flush stdout for every iteration, like this:
var logString = String(format: "%2i%% %.2fM \r", 10, 5)
print(logString)
fflush(__stdoutp)

Is it possible to ack nagios alerts from the terminal?

I have nagios alerts set up to come through jabber with an http link to ack.
Is is possible there is a script I can run from a terminal on a remote workstation that takes the hostname as a parameter and acks the alert?
./ack hostname
The benefit, while seemingly mundane, is threefold. First, take http load off nagios. Secondly, nagios http pages can take up to 10-20 seconds to load, so I want to save time there. Thirdly, avoiding slower use of mouse + web interface + firefox/other annoyingly slow browser.
Ideally, I would like a script bound to a keyboard shortcut that simply acks the most recent alert. Finally, I want to take the inputs from a joystick, buttons and whatnot, and connect one to a big red button bound to the script so I can just ack the most recent nagios alert by hitting the button lol. (It would be rad too if the button had a screen on the enclosure that showed the text of the alert getting acked lol)
Make fun of me all you want, but this is actually something that would be useful to me. If I can save five seconds per alert, and I get 200 alerts per day I need to ack, that's saving me 15 minutes a day. And isn't the whole point of the sysadmin to automate what can be automated?
Thanks!
Yes, it's possible to ack nagios by parsing /var/lib/nagios3/retention.dat file.
See :
#!/usr/bin/env python
# -*- coding: utf8 -*-
# vim:ts=4:sw=4
import sys
file = "/var/lib/nagios3/retention.dat"
try:
sys.argv[1]
except:
print("Usage:\n"+sys.argv[0]+" <HOST>\n")
sys.exit(1)
f = open(file, "r")
line = f.readline()
c=0
name = {}
state = {}
host = {}
while line:
if "service_description=" in line:
name[c] = line.split("=", 2)[1]
elif "current_state=" in line:
state[c] = line.split("=", 2)[1]
elif "host_name=" in line:
host[c] = line.split("=", 2)[1]
elif "}" in line:
c+=1
line = f.readline()
for i in name:
num = int(state[i])
if num > 0 and sys.argv[1] == host[i].strip():
print(name[i].strip("\n"))
You simply have to put the host as parameter, and the script will displays the broken services.