How to call a variable inside another function - glade

Hi,i have 2 functions that do a printf of what a i put in a text entry (used glade for GUI).
like this:
void on_adress_activate(GtkWidget * adress, GdkEvent * event, gpointer data)
{
const gchar *adress_text;
adress_text=gtk_entry_get_text (GTK_ENTRY (adress));
printf ("IP Adress: %s\n",adress_text);
}
void on_port_activate(GtkWidget * port, GdkEvent * event, gpointer data)
{
const gchar *port_text;
port_text=gtk_entry_get_text (GTK_ENTRY (port));
printf ("Port Number: %s\n",port_text);
}
Now i need to call the values of port_text and adress_text in another function that when i click a button on gui it should display another printf of them:
void on_connect_clicked(GtkWidget * widget, gpointer user_data)
{
printf("Connection done%s,port%s\n",adress_text,port_text);
}
Is there a way to do this? please correct my code.I hope i was clear.
Thanks in advance

in the function where you put your variable put
global name_of_variable

Related

Raku NativeCall to LibX11 screen and display

Fedora 33
Raku
I am trying to use Raku's NativeCall to talk to libX11.so to print out both my screen and my display:
use NativeCall;
class Display is repr('CStruct') { has Pointer $.DisplayPtr };
# libX11.so --> X11
sub XOpenDisplay(Str $name = ':0') returns Display is native('X11') { * }
sub XDefaultScreen(Display $) returns int32 is native('X11') { * }
my Display $display = XOpenDisplay()
or die "Can not open display";
my int $screen = XDefaultScreen($display);
print "display = <" ~ $display ~ ">\n";
print "screen = <" ~ $screen ~ ">\n";
$ libX11.pl6
display = <Display<90201160>>
screen = <0>
Problem. I am missing something about the class syntax as it is showing me a pointer address instead of my display, which I presume to be ":0". Also I thing the class declaration should show a string somewhere.
You're confusing somewhat a Display, which is an object that you use to interact with X, and a display name, which is a string that you can use to identify and connect to a Display.
Also, you're best off using repr('CPointer'), not repr('CStruct') for an XDisplay *, since the Xlib documentation says that it should be treated as an opaque pointer and everything accessed through functions, and translating the whole struct to Raku would be laborious (and not very useful).
Since it is like an object in that way, you have the option of encapsulating all of the Xlib functions inside of the Display class, and wrapping them in methods, as shown in the pointers section of the NativeCall docs. My translation of the code you have so far to this style would be:
use NativeCall;
class Display is repr('CPointer') {
sub XOpenDisplay(Str) returns Display is native('X11') { * }
method new(Str $name = ':0') {
XOpenDisplay($name);
}
# You can wrap a libX11 function in a method explicitly, like this...
sub XDisplayString(Display) returns Str is native('X11') { * }
method DisplayString {
XDisplayString(self);
}
# Or implicitly, by putting 'is native' on a method declaration
# and using 'is symbol' to match the names
# (self will be passed as the first argument to the libX11 function)
method DefaultScreen() returns int32 is native('X11')
is symbol('XDefaultScreen') { * }
method Str {
"Display({ self.DisplayString })";
}
}
my Display $display .= new
or die "Can not open display";
my int $screen = $display.DefaultScreen;
print "display = <" ~ $display ~ ">\n";
print "screen = <" ~ $screen ~ ">\n";
I provided a method Str for Display, so that it can be printed directly, but again, don't confuse the object with the string that you use to get hold of one. You would go on from here by adding more methods to Display, as well as defining Screen, Window, etc. in the same way. You don't have to do it this way -- you're free to define the subs publicly and use calls to XOpenDisplay and everything else, as if you were writing C, but the OO style tends to be a bit cleaner. The choice is yours.
In the comments #hobbs has pointed me in the right direction, by suggesting a new function, XDisplayString, that can actually be used to turn a pointer into a string describing the display, without actually needing to go into the full structure of the pointer. So this is how it would go:
use NativeCall;
class Display is repr('CPointer') {};
# libX11.so --> X11
sub XOpenDisplay(str $name = ':0') returns Display is native('X11') { * }
sub XDefaultScreen(Str $) returns int32 is native('X11') { * }
sub XDisplayString(Display $display) returns Str is native('X11') { * }
my $display = XOpenDisplay() or die "Can not open display";
my Str $displayStr = XDisplayString($display);
my int $screen = XDefaultScreen( $displayStr );
print "display = <" ~ $displayStr ~ ">\n";
print "screen = <" ~ $screen ~ ">\n";
That would return:
display = <:0>
screen = <64>
At least in my machine. The key here is that you're actually ising the right way of describing the screen, at least as far as XDisplayString is concerned, so you turn the original Pointer into a Str, and then you sna use it in whatever X* need a string description of the display.

What is the best way to read/write objects in a file with the following conditions

I am willing to store objects in a database. The purpose is to be able to read / write these objects with the program. The requirements are the following:
Objects can be complex using Qt classes such as QList, QString ... or even can contain other objects that use QObjects
The database should not be readable or modified by human (no text file, and if I use sqlite database, it has to be encrypted in a way)
I should be able to remove, read an object by its name and count the number of objects in the database, without loading everything in the memory
I asked a question here, to do this with a QDataStream with a minimalist example. But it seems it is not the best way to proceed.
Would you have some suggestions regarding the solutions that exist for this purpose?
I have tried the following but it does not fulfill the requirements:
Storing text in sqlite with QtSQL: but the data is accessible by using sqlitemanager for example, can be modified or removed by humans. Moreover, I have no idea regarding the way to store QList for example or other objects that I created and contain QObject (for example, 2 QList)
Storing binary data using QDataStream: in this case, I cannot count the number of objects in my file, neither read or remove a specific object without loading the entire file in memory.
I would be grateful if you could give me some suggestions or provide example, even if the example is minimalist.
I finally found a solution, especially thanks to Igor Tandetnik and thanks to the topic here
I haven't quite finalized, there is a small imperfection because I have to define an object of my user class that I don't use in order to call the readFromDB function to generate my object from the db.
On the other hand, I get this error message "QSqlDatabasePrivate::addDatabase: duplicate connection name 'qt_sql_default_connection', old connection removed" each time I call my database.
Anyway, it's a bit late now, and I think it might help some people so I post this minimalist imperfect code below. I'll post an update in the next few days.
Thanks again.
#include "QString"
#include "QFile"
#include "QDataStream"
#include "qdebug.h"
#include "QtSql"
#include "QSqlDatabase"
#include "qmessagebox.h"
class User
{
protected:
QString name;
QList<QString> childrens;
public:
QString getName(){ return name;}
QList<QString> getChildrens(){ return childrens;}
void setName(QString x) {name = x;}
void setChildrens(QList<QString> x) {childrens = x;}
friend QDataStream &operator<<(QDataStream &out, const User &t)
{
out << t.name << t.childrens;
return out;
}
friend QDataStream &operator>>(QDataStream &in, User &t)
{
QString inname;
QList<QString> inchildrens;
in >> inname >> inchildrens;
t.name = inname;
t.childrens = inchildrens;
return in;
}
QByteArray object2blob( const User& user )
{
QByteArray result;
QDataStream bWrite( &result, QIODevice::WriteOnly );
bWrite << user;
return result;
}
User blob2object( const QByteArray& buffer )
{
User result;
QDataStream bRead( buffer );
bRead >> result;
return result;
}
int saveToDB( const User& user )
{
QSqlDatabase myDB = QSqlDatabase::addDatabase("QSQLITE");
myDB.setDatabaseName( "file.db");
if (!myDB.open())
{
qDebug()<<"Failed to open SQL database of registered users";
}
else
{
qDebug()<<"Successfully opening SQL database of registered users";
QSqlQuery query;
query.prepare( "CREATE TABLE IF NOT EXISTS users (name TEXT, childrens BLOB)" );
if( !query.exec() )
{
qDebug() << query.lastError();
}
else
{
qDebug() << "Table created!";
query.prepare( "INSERT INTO users (name,childrens) VALUES (:name,:childrens)" );
query.bindValue(":name", name);
query.bindValue( ":childrens", object2blob(user) );
query.exec();
}
query.clear();
myDB.close();
}
QSqlDatabase::removeDatabase("UserConnection");
return 0;
}
User readFromDB( QString name )
{
User result;
QSqlDatabase myDB = QSqlDatabase::addDatabase("QSQLITE");
myDB.setDatabaseName( "file.db");
if (!myDB.open())
{
qDebug()<<"Failed to open SQL database of registered users";
}
else
{
QSqlQuery query;
query.prepare( "SELECT * FROM users WHERE name ='"+ name +"'" );
//query.bindValue( 0, name );
if ( query.exec() && query.next() ) {
result = blob2object( query.value( 1 ).toByteArray() );
}
query.clear();
myDB.close();
}
QSqlDatabase::removeDatabase("UserConnection");
qDebug()<<result.getChildrens();
return result;
}
};
////////////////////////////////////////////////////////////////
int main()
{
User u;
u.setName("Georges");
u.setChildrens(QList<QString>()<<"Jeanne"<<"Jean");
u.saveToDB(u);
User v;
v.setName("Alex");
v.setChildrens(QList<QString>()<<"Matthew");
v.saveToDB(v);
User w;
w.setName("Mario");
w.saveToDB(w);
User to_read; //to improve here
User a = to_read.readFromDB("Georges");
qDebug()<<a.getChildrens();
return 0;
}

Does perl6 have a class method equivalent to the MAIN sub?

Or similar to java's main() method? In other words a method that executes first, with the possibility of reading one or more parameters from the terminal.
Yes, and it's called MAIN and it has autoparsing for terminal parameters. Futhermore, it can even be a multi sub (supporting different signatures), have defaults, mark as required and do type validation, e.g.:
#|(optional description for USAGE message)
sub MAIN( Int :$length = 24,
:file($data) where { .IO.f // die "file not found in $*CWD" } = 'file.dat',
Bool :v(:$verbose) #`( -verbose, --verbose, -v or --v ) )
{
say $length if $length.defined;
say $data if $data.defined;
say 'Verbosity ', ($verbose ?? 'on' !! 'off');
exit 1;
}

Multiple thenApply in a completableFuture

I have a situation where I want to execute some methods in different threads but want to pass the result of one thread to another. I have following methods in my class.
public static int addition(int a, int b){
System.out.println((a+b));
return (a+b);
}
public static int subtract(int a, int b){
System.out.println((a-b));
return (a-b);
}
public static int multiply(int a, int b){
System.out.println((a*b));
return (a*b);
}
public static String convert(Integer a){
System.out.println((a));
return a.toString();
}
here is main method:
public static void main(String[] args) {
int a = 10;
int b = 5;
CompletableFuture<String> cf = new CompletableFuture<>();
cf.supplyAsync(() -> addition(a, b))
.thenApply(r ->subtract(20,r)
.thenApply(r1 ->multiply(r1, 10))
.thenApply(r2 ->convert(r2))
.thenApply(finalResult ->{
System.out.println(cf.complete(finalResult));
}));
System.out.println(cf.complete("Done"));
}
I am trying to pass result of addition to subtraction to multiplication to printing result. But I am getting compilation error. Looks like we can't do nested thenApply(). Is there any way we can do this? Searched it over google and found one helpful link- http://kennethjorgensen.com/blog/2016/introduction-to-completablefutures But didn't find much help.
A couple of things are wrong with your snippet:
Parenthesis: you have to start the next thenApply after the end of the one before, not after the substract method.
supplyAsync() is a static method. Use it as such.
If you just want to print out the result in the last operation, use thenAccept instead of thenApply
You do not need to complete the CF in thenAccept (neither you would have to do it in thenApply before.
This piece of code compiles, and it may be close to what you want to achieve:
CompletableFuture<Void> cf = CompletableFuture
.supplyAsync(() -> addition(a, b))
.thenApply(r -> subtract(20, r))
.thenApply(r1 -> multiply(r1, 10))
.thenApply(r2 -> convert(r2))
.thenAccept(finalResult -> {
System.out.println("this is the final result: " + finalResult);
});
//just to wait until the cf is completed - do not use it on your program
cf.join();

How to use the value of a return statement in a different method?

I recently started codeing java, so this question might be a little, well, stupid, but i created a small program that averages 5 numbers. I know the program is very over complicated, i have just been trying out some of the new things i've learned.My problem is i would like to get the variable "Answer" up in my main program. I dont want to change around the program if i dont have to.I have returned the value in the average method, and set this answer to the variable Answer, but how can i use System.out.print(Answer) or print the return. Heres the code! Sorry if its not in a code block, i indented 4 spaces, but it doesnt say anything.
package Tests;
import java.util.*;
public class average_Test {
static double Total=0;
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
int temp;
int count[]={5,1,2,3,4};
for(int x:count){
System.out.print("Please enter 5 numbers: ");
temp=scan.nextInt();
average(temp);
}
}
public static double average(int n){
for(int c=0;c<1;c++){
Total+=n;
}
double average=Total/5;
System.out.println(average);
double Answer = Total/5;
return Total/5;
}
}
You can use variable binding, or print result of function:
double a = average(temp);
System.out.println(a);
or:
System.out.println(average(temp));
At the end it will look like this:
double result = 0;
System.out.print("Please enter 5 numbers: ");
for (int x : count) {
temp = scan.nextInt();
result = average(temp);
}
System.out.println(result);
P.S. code looks weird, consider implementing double average(int[] numbers)