Vala + i18n + gtk, How to make a working app? - gtk

I am trying to create a small demo program to understand how it works, gtk3 + i18n + meson, i would like to translate the window title _ ("Settings") from the normal string from english to italian thanks to it.po and window.vala, but running the sources the program is not translated where am I wrong?
this is the github repository : https://github.com/Fluid-DE/test
window.vala
public class Jarvis.Window : Gtk.ApplicationWindow {
public GLib.Settings settings;
public Window (Application app) {
Object (
application: app
);
}
construct {
title = _("Settings");
//set_title( _("TEST") );
window_position = Gtk.WindowPosition.CENTER;
set_default_size (350, 80);
settings = new GLib.Settings ("com.github.alecaddd.jarvis");
move (settings.get_int ("pos-x"), settings.get_int ("pos-y"));
resize (settings.get_int ("window-width"), settings.get_int ("window-height"));
delete_event.connect (e => {
return before_destroy ();
});
show_all ();
}
public bool before_destroy () {
int width, height, x, y;
get_size (out width, out height);
get_position (out x, out y);
settings.set_int ("pos-x", x);
settings.set_int ("pos-y", y);
settings.set_int ("window-width", width);
settings.set_int ("window-height", height);
return false;
}
}
it.po
#, fuzzy
msgid ""
msgstr ""
"Project-Id-Version: com.github.alecaddd.jarvis\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2020-11-10 09:31+0000\n"
"PO-Revision-Date: 2020-10-23 16:15+0000\n"
"Last-Translator: Fabio Zaramella <fabiozaramella#hotmail.it>\n"
"Language-Team: Italian\n"
"Language: it\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=2; plural=n != 1;\n"
"X-Generator: Poedit 2.0.6\n"
"X-Poedit-SourceCharset: UTF-8\n"
"X-Poedit-Basepath: ../src\n"
"X-Poedit-SearchPath-0: .\n"
#: src/MainWindow.vala:308
msgid "New note"
msgstr "Nuova nota"
#: src/MainWindow.vala:313
msgid "Delete note"
msgstr "Cancella nota"
#: src/MainWindow.vala:327
msgid "White"
msgstr "Bianco"
#: src/MainWindow.vala:338
msgid "Red"
msgstr "Rosso"
#: src/MainWindow.vala:349
msgid "Orange"
msgstr "Oracione"
#: src/MainWindow.vala:360
msgid "Yellow"
msgstr "Giallo"
#: src/MainWindow.vala:371
msgid "Green"
msgstr "Verde"
#: src/MainWindow.vala:382
msgid "Blue"
msgstr "Blu"
#: src/MainWindow.vala:432
msgid "Note Color"
msgstr "Colore Nota"
#: src/MainWindow.vala:448
msgid "Settings"
msgstr "Impostazioni"
meson.build
###########
# Project #
###########
project('com.github.alecaddd.jarvis', ['c', 'vala'],
version: '0.alpha',
meson_version: '>= 0.53.0'
)
###########
# Version #
###########
project_version = meson.project_version()
version_array = project_version.split('.')
project_major_version = version_array[0].to_int()
project_minor_version = version_array[1]
#################
# Default paths #
#################
project_prefix = get_option('prefix')
project_bindir = join_paths(project_prefix, get_option('bindir'))
project_localedir = join_paths(project_prefix, get_option('localedir'))
project_datadir = join_paths(project_prefix, get_option('datadir'))
project_pkgdatadir = join_paths(project_datadir, meson.project_name())
project_schemadir = join_paths(project_datadir, 'glib-2.0', 'schemas')
###########
# Options #
###########
#Compiler
vala_version_required = '0.48.2'
vala = meson.get_compiler('vala')
cc = meson.get_compiler('c')
if not vala.version().version_compare('>= #0#'.format(vala_version_required))
error('Valac >= #0# required!'.format(vala_version_required))
endif
#Argument
add_project_arguments([
'-DGETTEXT_PACKAGE="' + meson.project_name() + '"',
],
language:'c'
)
add_project_arguments([
'--vapidir', join_paths(meson.current_source_dir(), 'vapi'),
'--pkg', 'config',
],
language: 'vala',
)
#Configuration file
config_h = configuration_data()
package_bugreport = 'http://bugzilla.gnome.org/enter_bug.cgi?product=' + meson.project_name()
# package
set_defines = [
['PACKAGE', meson.project_name()],
['PACKAGE_BUGREPORT', package_bugreport],
['PACKAGE_NAME', meson.project_name()],
['PACKAGE_STRING', '#0# #1#'.format(meson.project_name(), project_version)],
['PACKAGE_TARNAME', meson.project_name()],
['PACKAGE_URL', 'https://wiki.gnome.org/Apps/Calendar'],
['PACKAGE_VERSION', project_version],
['VERSION', project_version],
['GETTEXT_PACKAGE', meson.project_name()],
['APPLICATION_ID', meson.project_name()]
]
foreach define: set_defines
config_h.set_quoted(define[0], define[1])
endforeach
# Compiler flags
config_data = configuration_data()
config_data.set('version', meson.project_version())
config_data.set('testdata_dir', join_paths(meson.source_root(), 'data', 'tests'))
config_data.set('app_name', meson.project_name())
config_file = configure_file(
output: 'config.h',
configuration: config_h
)
project_config_dep = declare_dependency(
sources: config_file,
include_directories: include_directories('.')
)
################
# Dependencies #
################
glib_dep = dependency('glib-2.0', version: '>= 2.58.0')
gtk_dep = dependency('gtk+-3.0', version: '>= 3.22.20')
gio_dep = dependency('gio-2.0', version: '>= 2.58.0')
gnome = import('gnome')
i18n = import('i18n')
pkg = import('pkgconfig')
top_inc = include_directories('.')
data_dir = join_paths(meson.source_root(), 'data')
po_dir = join_paths(meson.source_root(), 'po')
src_dir = join_paths(meson.source_root(), 'src')
###########
# Subdirs #
###########
subdir('src')
subdir('po')
subdir('data')
meson.add_install_script('meson/post_install.py')

In your class where the main method is, you should tell the gettext three things:
the translation domain, usually the same as the application name
the location where the compiled translations will be installed
the character encoding of translations, usually UTF-8.
In my case I do this:
Intl.setlocale (LocaleCategory.ALL, "");
string langpack_dir = Path.build_filename (Constants.APP_INSTALL_PREFIX, "share", "locale");
Intl.bindtextdomain (Constants.APP_ID, langpack_dir);
Intl.bind_textdomain_codeset (Constants.APP_ID, "UTF-8");
Intl.textdomain (Constants.APP_ID);
Replace the Constants values with your Config.h file
After doing this you need to regenerate the translation files.
In Gnome Developer have more information about this

Related

py.test capture unhandled exception

We are using py.test 2.8.7 and I have the below method which creates a separate log file for every test-case. However this does not handle unhandled Exceptions. So if a code snippet throws an Exception instead of failing with an assert, the stack-trace of the Exception is not logged into the separate file. Can someone please help me in how I could capture these Exceptions?
def remove_special_chars(input):
"""
Replaces all special characters which ideally shout not be included in the name of a file
Such characters will be replaced with a dot so we know there was something useful there
"""
for special_ch in ["/", "\\", "<", ">", "|", "&", ":", "*", "?", "\"", "'"]:
input = input.replace(special_ch, ".")
return input
def assemble_test_fqn(node):
"""
Assembles a fully-qualified name for our test-case which will be used as its test log file name
"""
current_node = node
result = ""
while current_node is not None:
if current_node.name == "()":
current_node = current_node.parent
continue
if result != "":
result = "." + result
result = current_node.name + result
current_node = current_node.parent
return remove_special_chars(result)
# This fixture creates a logger per test-case
#pytest.yield_fixture(scope="function", autouse=True)
def set_log_file_per_method(request):
"""
Creates a separate file logging handler for each test method
"""
# Assembling the location of the log folder
test_log_dir = "%s/all_test_logs" % (request.config.getoption("--output-dir"))
# Creating the log folder if it does not exist
if not os.path.exists(test_log_dir):
os.makedirs(test_log_dir)
# Adding a file handler
test_log_file = "%s/%s.log" % (test_log_dir, assemble_test_fqn(request.node))
file_handler = logging.FileHandler(filename=test_log_file, mode="w")
file_handler.setLevel("INFO")
log_format = request.config.getoption("--log-format")
log_formatter = logging.Formatter(log_format)
file_handler.setFormatter(log_formatter)
logging.getLogger('').addHandler(file_handler)
yield
# After the test finished, we remove the file handler
file_handler.close()
logging.getLogger('').removeHandler(file_handler)
I have ended-up with a custom plugin:
import io
import os
import pytest
def remove_special_chars(text):
"""
Replaces all special characters which ideally shout not be included in the name of a file
Such characters will be replaced with a dot so we know there was something useful there
"""
for special_ch in ["/", "\\", "<", ">", "|", "&", ":", "*", "?", "\"", "'"]:
text = text.replace(special_ch, ".")
return text
def assemble_test_fqn(node):
"""
Assembles a fully-qualified name for our test-case which will be used as its test log file name
The result will also include the potential path of the log file as the parents are appended to the fqn with a /
"""
current_node = node
result = ""
while current_node is not None:
if current_node.name == "()":
current_node = current_node.parent
continue
if result != "":
result = "/" + result
result = remove_special_chars(current_node.name) + result
current_node = current_node.parent
return result
def as_unicode(text):
"""
Encodes a text into unicode
If it's already unicode, we do not touch it
"""
if isinstance(text, unicode):
return text
else:
return unicode(str(text))
class TestReport:
"""
Holds a test-report
"""
def __init__(self, fqn):
self._fqn = fqn
self._errors = []
self._sections = []
def add_error(self, error):
"""
Adds an error (either an Exception or an assertion error) to the list of errors
"""
self._errors.append(error)
def add_sections(self, sections):
"""
Adds captured sections to our internal list of sections
Since tests can have multiple phases (setup, call, teardown) this will be invoked for all phases
If for a newer phase we already captured a section, we override it in our already existing internal list
"""
interim = []
for current_section in self._sections:
section_to_add = current_section
# If the current section we already have is also present in the input parameter,
# we override our existing section with the one from the input as that's newer
for index, input_section in enumerate(sections):
if current_section[0] == input_section[0]:
section_to_add = input_section
sections.pop(index)
break
interim.append(section_to_add)
# Adding the new sections from the input parameter to our internal list
for input_section in sections:
interim.append(input_section)
# And finally overriding our internal list of sections
self._sections = interim
def save_to_file(self, log_folder):
"""
Saves the current report to a log file
"""
# Adding a file handler
test_log_file = "%s/%s.log" % (log_folder, self._fqn)
# Creating the log folder if it does not exist
if not os.path.exists(os.path.dirname(test_log_file)):
os.makedirs(os.path.dirname(test_log_file))
# Saving the report to the given log file
with io.open(test_log_file, 'w', encoding='UTF-8') as f:
for error in self._errors:
f.write(as_unicode(error))
f.write(u"\n\n")
for index, section in enumerate(self._sections):
f.write(as_unicode(section[0]))
f.write(u":\n")
f.write((u"=" * (len(section[0]) + 1)) + u"\n")
f.write(as_unicode(section[1]))
if index < len(self._sections) - 1:
f.write(u"\n")
class ReportGenerator:
"""
A py.test plugin which collects the test-reports and saves them to a separate file per test
"""
def __init__(self, output_dir):
self._reports = {}
self._output_dir = output_dir
#pytest.hookimpl(tryfirst=True, hookwrapper=True)
def pytest_runtest_makereport(self, item, call):
outcome = yield
# Generating the fully-qualified name of the underlying test
fqn = assemble_test_fqn(item)
# Getting the already existing report for the given test from our internal dict or creating a new one if it's not already present
# We need to do this as this method will be invoked for each phase (setup, call, teardown)
if fqn not in self._reports:
report = TestReport(fqn)
self._reports.update({fqn: report})
else:
report = self._reports[fqn]
result = outcome.result
# Appending the sections for the current phase to the test-report
report.add_sections(result.sections)
# If we have an error, we add that as well to the test-report
if hasattr(result, "longrepr") and result.longrepr is not None:
error = result.longrepr
error_text = ""
if isinstance(error, str) or isinstance(error, unicode):
error_text = as_unicode(error)
elif isinstance(error, tuple):
error_text = u"\n".join([as_unicode(e) for e in error])
elif hasattr(error, "reprcrash") and hasattr(error, "reprtraceback"):
if error.reprcrash is not None:
error_text += str(error.reprcrash)
if error.reprtraceback is not None:
if error_text != "":
error_text += "\n\n"
error_text += str(error.reprtraceback)
else:
error_text = as_unicode(error)
report.add_error(error_text)
# Finally saving the report
# We need to do this for all phases as we don't know if and when a test would fail
# This will essentially override the previous log file for a test if we are in a newer phase
report.save_to_file("%s/all_test_logs" % self._output_dir)
def pytest_configure(config):
config._report_generator = ReportGenerator("result")
config.pluginmanager.register(config._report_generator)

P4Python does not check out the file in Perforce

I have following piece of code. I'm trying to check out two files from Perforce and put them in a changelist. But run_add does not check the files out. The only thing I see in Perforce is a empty changelist with no files in it.
""" Checks out files from workspace using P4"""
files = ['analyse-location.cfg', 'CMakeLists.txt']
p4 = P4()
# Connect and disconnect
if (p4.connected()):
p4.disconnect()
p4.port = portp4
p4.user = usernameP4
p4.password = passwordP4
p4.client = clientP4
try:
p4.connect()
if p4.connected():
change = p4.fetch_change()
change['Description'] = "Auto"
change['Files'] = []
changeList = p4.save_change(change)[0].split()[1]
for items in files:
abs_path = script_dir + "\\" + items
p4.run_add("-c", changeList, items)
print("Adding file "+ abs_path + " to "+ changeList)
# Done! Disconnect!
p4.disconnect()
except P4Exception:
print("Something went wrong in P4 connection. The errors are: ")
for e in p4.errors:
print(e)
p4.disconnect()
However, when I have instead p4.run("edit", items) it puts the files in the default changelist.It really gets on my nervs. I don't know I am doing that is wrong. The changes list created as well. I use python 3.7 32 bits on Windows
Your script discards the output of the run_add call. Try changing this:
for items in files:
abs_path = script_dir + "\\" + items
p4.run_add("-c", changeList, items)
print("Adding file "+ abs_path + " to "+ changeList)
to:
for items in files:
abs_path = script_dir + "\\" + items
output = p4.run_add("-c", changeList, items)
print("Adding file "+ abs_path + " to "+ changeList)
if output:
print(output)
if p4.errors:
print(p4.errors)
if p4.warnings:
print(p4.warnings)
That will show you the results of the p4 add commands that you're running. Based on the fact that a p4 edit opens the files, I expect you'll find a message like this:
C:\Perforce\test>p4 add foo
//stream/main/foo - can't add existing file
The p4 add and p4 edit commands are not synonymous; one is for adding a new file, one is for editing an existing file. If your script is editing existing files, it should be calling run_edit, not run_add.
I changed my question to following and it worked.
p4.port = portp4
p4.user = usernameP4
p4.password = passwordP4
p4.client = clientP4
try:
p4.connect()
if p4.connected():
change = p4.fetch_change()
change['Description'] = "Auto"
change['Files'] = []
changeList = p4.save_change(change)[0].split()[1]
for items in files:
abs_path = script_dir + "\\" + items
output = p4.run_edit("-c", changeList, items)
print("Adding file "+ abs_path + " to "+ changeList)
if output:
print(output)
if p4.errors:
print(p4.errors)
if p4.warnings:
print(p4.warnings)
p4.disconnect()
except P4Exception:
print("Something went wrong in P4 connection. The errors are: ")
for e in p4.errors:
print(e)
p4.disconnect()
Thanks to #Sam Stafford for his hint. Now it works just like a charm. The key was to change p4.run_add("-c", changelist, items) to p4.run_edit("-c", changelist, items)

Is there a way to convert juniper "json" or "xml" config to "set" or "show" config?

We use juniper hardware with junos version 15. In this version we can export our config as "json" or "xml" which we want to use to edit it with our automation tooling.
Importing however is only possible in "set" or "show" format.
Is there a tool to convert "json" or "xml" format to "set" or "show" format?
I can only find converters between "show" and "set".
We can't upgrade to version 16 where the import of "json" would be possible.
Here's a script I made at work, throw it in your bin and you can it via providing a filename or piping output. This assumes linux or mac so the os.isatty function works, but the logic can work anywhere:
usage demo:
person#laptop ~ > head router.cfg
## Last commit: 2021-04-20 21:21:39 UTC by vit
version 15.1X12.2;
groups {
BACKBONE-PORT {
interfaces {
<*> {
mtu 9216;
unit <*> {
family inet {
mtu 9150;
person#laptop ~ > convert.py router.cfg | head
set groups BACKBONE-PORT interfaces <*> mtu 9216
set groups BACKBONE-PORT interfaces <*> unit <*> family inet mtu 9150
set groups BACKBONE-PORT interfaces <*> unit <*> family inet6 mtu 9150
set groups BACKBONE-PORT interfaces <*> unit <*> family mpls maximum-labels 5
<... output removed... >
convert.py:
#!/usr/bin/env python3
# Class that attempts to parse out Juniper JSON into set format
# I think it works? still testing
#
# TODO:
# accumulate annotations and provide them as commands at the end. Will be weird as annotations have to be done after an edit command
from argparse import ArgumentParser, RawTextHelpFormatter
import sys, os, re
class TokenStack():
def __init__(self):
self._tokens = []
def push(self, token):
self._tokens.append(token)
def pop(self):
if not self._tokens:
return None
item = self._tokens[-1]
self._tokens = self._tokens[:-1]
return item
def peek(self):
if not self._tokens:
return None
return self._tokens[-1]
def __str__(self):
return " ".join(self._tokens)
def __repr__(self):
return " ".join(self._tokens)
def main():
# get file
a = ArgumentParser(prog="convert_jpr_json",
description="This program takes in Juniper style JSON (blah { format) and prints it in a copy pastable display set format",
epilog=f"Either supply with a filename or pipe config contents into this program and it'll print out the display set view.\nEx:\n{B}convert_jpr_json <FILENAME>\ncat <FILENAME> | convert_jpr_json{WHITE}",
formatter_class=RawTextHelpFormatter)
a.add_argument('file', help="juniper config in JSON format", nargs="?")
args = a.parse_args()
if not args.file and os.isatty(0):
a.print_help()
die("Please supply filename or provide piped input")
file_contents = None
if args.file:
try:
file_contents = open(args.file, "r").readlines()
except IOError as e:
die(f"Issue opening file {args.file}: {e}")
print(output_text)
else:
file_contents = sys.stdin.readlines()
tokens = TokenStack()
in_comment = False
new_config = []
for line_num, line in enumerate(file_contents):
if line.startswith("version ") or len(line) == 0:
continue
token = re.sub(r"^(.+?)#+[^\"]*$", r"\1", line.strip())
token = token.strip()
if (any(token.startswith(_) for _ in ["!", "#"])):
# annotations currently not supported
continue
if token.startswith("/*"):
# we're in a comment now until the next token (this will break if a multiline comment with # style { happens, but hopefully no-one is that dumb
in_comment = True
continue
if "inactive: " in token:
token = token.split("inactive: ")[1]
new_config.append(f"deactivate {tokens} {token}")
if token[-1] == "{":
in_comment = False
tokens.push(token.strip("{ "))
elif token[-1] == "}":
if not tokens.pop():
die("Invalid json supplied: unmatched closing } encountered on line " + f"{line_num}")
elif token[-1] == ";":
new_config.append(f"set {tokens} {token[:-1]}")
if tokens.peek():
print(tokens)
die("Unbalanced JSON: expected closing }, but encountered EOF")
print("\n".join(new_config))
def die(msg): print(f"\n{B}{RED}FATAL ERROR{WHITE}: {msg}"); exit(1)
RED = "\033[31m"; GREEN = "\033[32m"; YELLOW = "\033[33m"; B = "\033[1m"; WHITE = "\033[0m"
if __name__ == "__main__": main()
You can load XML configuration using edit-config RPC or load-configuration RPC. For more details:
https://www.juniper.net/documentation/en_US/junos/topics/reference/tag-summary/netconf-edit-config.html
https://www.juniper.net/documentation/en_US/junos/topics/reference/tag-summary/junos-xml-protocol-load-configuration.html
XML content can be loaded via an "op" script by placing the content inside a call to junos:load-configuration() template defined in "junos.xsl". Something like the following:
version 1.1;
ns jcs = "http://xml.juniper.net/junos/commit-scripts/1.0";
import "../import/junos.xsl";
var $arguments = {
<argument> {
<name> "file";
<description> "Filename of XML content to load";
}
<argument> {
<name> "action";
<description> "Mode for the load (override, replace, merge)";
}
}
param $file;
param $action = "replace";
match / {
<op-script-results> {
var $configuration = slax:document($file);
var $connection = jcs:open();
call jcs:load-configuration($connection, $configuration, $action);
}
}
Thanks,
Phil

Yocto's ROOTFS_POSTPROCESS_COMMAND not working?

I'm trying to use this variable in order to remove a few unwanted init files after my root FS is generated, following the documentation at:
http://www.yoctoproject.org/docs/1.8/ref-manual/ref-manual.html#migration-1.6-variable-changes-variable-entry-behavior
I've added exactly the same snippet to my recipe (.bb) file, without any luck... what's wrong? This is the code I'm putting in my .bb file:
my_postprocess_function() {
echo "hello" > ${IMAGE_ROOTFS}/hello.txt
}
ROOTFS_POSTPROCESS_COMMAND += "my_postprocess_function; "
The logs don't show any kind of error or warning, just my_postprocess_function is not executed.
I believe there is a bug that manifests itself based on which column you put the closing curly bracket in. Initially, I could not believe that this is the behaviour, but after I tested and confirmed it, here are my results:
$ bitbake --version
BitBake Build Tool Core version 1.28.0
I'm modifying core-image-minimal.bb as follows:
FAILING CASE
SUMMARY = "G5 - A small image just capable of allowing a device to boot."
IMAGE_INSTALL = "packagegroup-core-boot ${ROOTFS_PKGMANAGE_BOOTSTRAP} ${CORE_IMAGE_EXTRA_INSTALL}"
IMAGE_LINGUAS = " "
LICENSE = "MIT"
IMAGE_ROOTFS_SIZE ?= "8192"
IMAGE_ROOTFS_EXTRA_SPACE_append = "${#bb.utils.contains("DISTRO_FEATURES", "systemd", " + 4096", "" ,d)}"
inherit core-image
my_postprocess_function() {
echo "hello" > ${IMAGE_ROOTFS}/hello.txt
}
ROOTFS_POSTPROCESS_COMMAND += "my_postprocess_function; "
The above fails silently and does not generate hello.txt
Notice how the } is indented by one space (indenting by any amount other than once space will also fail).
However, if you modify it as follows:
SUCCEEDING CASE
SUMMARY = "G5 - A small image just capable of allowing a device to boot."
IMAGE_INSTALL = "packagegroup-core-boot ${ROOTFS_PKGMANAGE_BOOTSTRAP} ${CORE_IMAGE_EXTRA_INSTALL}"
IMAGE_LINGUAS = " "
LICENSE = "MIT"
IMAGE_ROOTFS_SIZE ?= "8192"
IMAGE_ROOTFS_EXTRA_SPACE_append = "${#bb.utils.contains("DISTRO_FEATURES", "systemd", " + 4096", "" ,d)}"
inherit core-image
my_postprocess_function() {
echo "hello" > ${IMAGE_ROOTFS}/hello.txt
}
ROOTFS_POSTPROCESS_COMMAND += "my_postprocess_function; "
then, hello.txt is generated.
The way I found this bug is by moving the 'inherit core-image' line to the end of the file as follows:
DIAGNOSIS
SUMMARY = "G5 - A small image just capable of allowing a device to boot."
IMAGE_INSTALL = "packagegroup-core-boot ${ROOTFS_PKGMANAGE_BOOTSTRAP} ${CORE_IMAGE_EXTRA_INSTALL}"
IMAGE_LINGUAS = " "
LICENSE = "MIT"
IMAGE_ROOTFS_SIZE ?= "8192"
IMAGE_ROOTFS_EXTRA_SPACE_append = "${#bb.utils.contains("DISTRO_FEATURES", "systemd", " + 4096", "" ,d)}"
my_postprocess_function() {
echo "hello" > ${IMAGE_ROOTFS}/hello.txt
}
ROOTFS_POSTPROCESS_COMMAND += "my_postprocess_function; "
inherit core-image
In which case, I got the error:
ERROR: ParseError at ......./recipes-core/images/core-image-minimal.bb:13: Shell function my_postprocess_function is never closed
I mentioned this last part in case anyone else is having weird behaviour and you have exhausted all debugging possibilities.
cyberguijarro only says that his code exists in a .bb recipe but didn't say if that recipe was an image recipe or not.
Since he didn't accept any of the given answers, I'll suggest that his issue was that his code was not in an image recipe.
This is working for me:
my_postprocess_function() {
echo "hello" > ${IMAGE_ROOTFS}/hello.txt
}
ROOTFS_POSTPROCESS_COMMAND_append = " \
my_postprocess_function; \
"

NameError: global name 'Carnage' is not defined

I know it was asked a million times before, but I need a little help getting this working, as the code is not mine.
so like that i update a code hope it will make some undarstands of it
# coding=utf-8
import urllib, re, sys, threading, cookielib, urllib2
from BeautifulSoup import BeautifulSoup
### Головная функция
def main():
agent = 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)'
aCarnage = Carnage('YourNick', 'YourPass', 'arkaim.carnage.ru', 'cp1251', agent)
aCarnage.login()
me = aCarnage.inf(aCarnage.user)
# Если ранен - выйти
if me['inj']:
aCarnage.logout()
exit(1)
aCarnage.urlopen('main.pl')
# Подождать пока здоровье восстановится
while(me['hp_wait']):
time.sleep(me['hp_wait'])
me = aCarnage.inf(aCarnage.user)
# Найти подходящую заявку
aCarnage.find()
me = aCarnage.inf(aCarnage.user)
# Если заявка состоялась - в бой!
if me['battle']: aCarnage.fight()
# После боя - выход из игры
aCarnage.logout()
class Opener:
def __init__(self, host, encoding, agent):
self.host = host
self.encoding = encoding
self.agent = agent
self.opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookielib.CookieJar()))
def urlopen(self, goto, data = None):
f = self.opener.open(urllib2.Request(
"http://%s/%s" % (self.host, goto),
self.urlencode(data),
{"User-agent" : self.agent}
))
result = f.read()
self.soup = BeautifulSoup(result)
def urlencode(self, data):
if data is None: return None
for key in data:
data[key] = data[key].encode(self.encoding, 'ignore')
return urllib.urlencode(data)
class CarnageBot(Opener):
### Конструктор принимает логин, пароль, кодировку (cp1251) и идентификатор браузера
def __init__(self, user, password, host, encoding, agent):
self.user = user
self.password = password
Opener.__init__(self, host, encoding, agent)
### Получить информацию об игроке - например о самом себе
def inf(self, user):
self.urlopen('inf.pl?' + self.urlencode({'user': user}))
# Кол-во жизни
onmouseover = self.soup.find('img', onmouseover = re.compile(unicode('Уровень жизни:', 'utf8')))
m = re.search('([0-9]+).([0-9]+)', onmouseover['onmouseover'])
hp = int(m.group(1))
hp_max = int(m.group(2))
hp_wait = (100 - (hp * 100) / hp_max) * 18
# Уровень
td = self.soup.find('td', text = re.compile(unicode('Уровень:', 'utf8')))
level = int(td.next.string)
# Ранен или нет
inj = 0
if self.soup.find(src = re.compile(unicode('travma.gif', 'utf8'))): inj = 1
# В бою или нет
battle = 0
if self.soup.find(text = re.compile(unicode('Персонаж находится в бою', 'utf8'))): battle = 1
hero = {'level': level, 'hp': hp, 'hp_max': hp_max, 'hp_wait': hp_wait, 'inj': inj, 'battle': battle}
return hero
### Войти в игру
def login(self):
data = {'action': 'enter', 'user_carnage': self.user, 'pass_carnage': self.password}
self.urlopen('enter.pl', data)
self.urlopen('main.pl')
### Выйти из игры
def logout(self):
self.urlopen('main.pl?action=exit')
### В бой!!!
def fight(self):
self.urlopen('battle.pl')
while True:
# Добить по таймауту
if self.soup.find(text = re.compile(unicode('Противник потерял сознание', 'utf8'))):
self.urlopen('battle.pl?cmd=timeout&status=win')
break
if self.soup.find(text = re.compile(unicode('Бой закончен.', 'utf8'))):
break
reg = re.compile(unicode('Для вас бой закончен. Ждите окончания боя.', 'utf8'))
if self.soup.find(text = reg):
break
cmd = self.soup.find('input', {'name' : 'cmd', 'type' : 'hidden'})
to = self.soup.find('input', {'name' : 'to', 'type' : 'hidden'})
# Есть ли по кому бить?!
if cmd and to:
a = random.randint(1, 4)
b0 = random.randint(1, 4)
b1 = random.randint(1, 4)
while b1 == b0: b1 = random.randint(1, 4)
pos = 2
arg = (cmd['value'], to['value'], pos, a, a, b0, b0, b1, b1)
self.urlopen('battle.pl?cmd=%s&to=%s&pos=%s&A%s=%s&D%s=%s&D%s=%s' % arg)
else:
self.urlopen('battle.pl')
time.sleep(random.randint(5, 30))
### Найти заявку - подающий заявку должен быть на 1 уровень ниже нашего
def find(self):
me = self.inf(self.user)
while True:
v = ''
self.urlopen('zayavka.pl?cmd=haot.show')
reg = re.compile(unicode('Текущие заявки на бой', 'utf8'))
script = self.soup.find('fieldset', text = reg).findNext('script')
m = re.findall('.*', script.string)
for value in m:
if value.find('group.gif') < 0: continue
if value.find('(%i-%i)' % (me['level'] - 2, me['level'])) < 0: continue
t = re.search(',([0-9]{1,2}),u', value)
if not t: continue
t = int(t.group(1))
v = re.search('tr\(([0-9]+)', value).group(1)
print 'Found battle t=%i v=%s' % (t, v)
break
if v: break
time.sleep(80)
nd = self.soup.find('input', {'name' : 'nd', 'type' : 'hidden'})
self.urlopen('zayavka.pl?cmd=haot.accept&nd=%s&battle_id=%s' % (nd['value'], v))
time.sleep(t + 30)
if __name__ == '__main__': main()
The error is:
NameError: global name 'Carnage' is not defined
The cause of your error is that Carnage has not been defined. Maybe you forgot to import a library which provides Carnage?
Also, your code as posted is incorrectly indented, which is a syntax error.
Update: Apparently you took this code from http://github.com/Ejz/Common/tree/master/carnage-bot . Reading that source, it looks like the line
aCarnage = Carnage('YourNick', 'YourPass', 'arkaim.carnage.ru', 'cp1251', agent)
Should be
aCarnage = CarnageBot('YourNick', 'YourPass', 'arkaim.carnage.ru', 'cp1251', agent)
Because the methods called on aCarnage are defined further down the file for class CarnageBot.