refresh needed instead of wrefresh? - ncurses

Why this piece of code here:
#include <ncurses.h>
#define WIN 5
#define WI win[0]
#define WC win[1]
int ymax, xmax;
WINDOW *win[WIN];
int main(void)
{
int i;
initscr();
cbreak();
start_color();
curs_set(0);
noecho();
init_pair(1,COLOR_GREEN,COLOR_BLACK);
getmaxyx(stdscr, ymax, xmax);
for(i=0; i<WIN; i++)
win[i]= newwin(ymax, xmax, 0, 0);
keypad(stdscr, TRUE); /* We get F1, F2 etc.. */
keypad(win[0], TRUE); /* We get F1, F2 etc.. */
refresh();
wprintw(WI, "Screen 1\n");
wprintw(WC, "Screen 2\n");
wattrset(WI, COLOR_PAIR(1));
wrefresh(WI);
getch();
endwin();
printf("\nThanks for playing\n");
return 0;
}
does not work if I delete the
refresh();
line?
Also, please, I'm new to this ncurses stuff, so if you see any other misconcept, be kind to point, specially the procedure to exit without leaving loose ends.

The problem is that one cannot mix getch() with other windows. getch() do a refresh(). One should use wgetch(WI) instead.
Still puzzles me why using the refresh() in the begin of the code made the text appear. But I think that to understand this behavior I would need to post the entire code to see how the functions mix all the screens.
Now with wgetch() the problem is gone.

Related

MPI program does nothing - running on linux

I've written this MPI C program on linux. The master is supposed to send tasks to the slaves and receive data from the slaves (and if there're more tasks to give them to the finished slaves).
After all the tasks are completed, it's supposed to print a solution.
It prints nothing and I can't figure out why. It isn't stuck, it just finishes after a second and doesn't print anything.
P.S-
I've tried debugging by placing a printf in different places in the code.
The only place in the code that printed something was before the MPI_Recv in the master section, and it printed a few times (less than the number of processes).
Here's the full code:
#include <mpi.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define NUMS_TO_CHECK 2000
#define RANGE_MIN -5
#define RANGE_MAX 5
#define PI 3.1415
#define MAX_ITER 100000
double func(double x);
int main (int argc, char *argv[])
{
int numProcs, procId;
int errorCode= MPI_ERR_COMM;
MPI_Init(&argc, &argv);
MPI_Comm_size(MPI_COMM_WORLD, &numProcs);
MPI_Comm_rank(MPI_COMM_WORLD, &procId);
MPI_Status status;
int i;
double recieve=0;
int countPositives=0;
double arr[NUMS_TO_CHECK];
double difference= (RANGE_MAX - RANGE_MIN) / NUMS_TO_CHECK;
int counter = NUMS_TO_CHECK-1; //from end to start...
//Initiallizing the array.
for(i=0; i<NUMS_TO_CHECK; i++){
arr[i]=RANGE_MIN+i*difference;
}
//master
if(procId==0){
//Send tasks to all procs
for(i=1; i<numProcs; i++){
MPI_Send(&arr[counter], 1, MPI_DOUBLE, i, 0, MPI_COMM_WORLD);
counter--;
}
do{
MPI_Recv(&recieve, 1, MPI_DOUBLE, MPI_ANY_SOURCE, 0, MPI_COMM_WORLD, &status);
if(recieve>0)
{
countPositives++;
}
MPI_Send(&arr[counter], 1, MPI_DOUBLE, status.MPI_SOURCE, 0, MPI_COMM_WORLD);
counter--;
}while(counter>0);
printf("Number of positives: %d", countPositives);
MPI_Finalize();
}
//slaves
else{
MPI_Recv(&recieve, 1, MPI_DOUBLE, 0, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
recieve=func(recieve);
MPI_Send(&recieve, 1, MPI_DOUBLE, 0, 0, MPI_COMM_WORLD);
}
}
double func(double x)
{
int i;
double value = x;
int limit = rand() % 3 + 1;
for(i = 0; i < limit * MAX_ITER; i++)
value = sin(exp(sin(exp(sin(exp(value))))) - PI / 2) - 0.5;
return value;
}
I think your slaves need to read data in a while loop. They only do 1 receive and 1 send. Whereas the master starts at 2000. That may be by design, so I may be wrong.
On the principle, your code looks almost fine. Only two things are missing here:
The most obvious one is a loop of a sort on the slaves' side, to receive their instructions from the master, and then send back their work; and
Less obvious but as essential: a mean for the master to tell when the work is done. It could be a special value send, that is tested by the slaves, and which leads them to exist the recv + work + send loop upon reception, or a different tag that you test. In the latter case, you'd have to use MPI_ANY_TAG for the reception call on the slaves' side.
With this in mind, I'm sure you can make your code to work.

Linux, C, Gtk. Close window after some time

Was trying to code. C, Linux. User enter some string and date. If it's today, then program should show a window with his string. Then this window should be closed by code, not user. And then it will pop up again after a short period of time. gtk_widget_destroy and gtk_widget_hide don't work.
`(aa:26429): Gtk-CRITICAL **: IA__gtk_widget_hide: assertion 'GTK_IS_WIDGET (widget)' failed`
#include <gtk/gtk.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
/* numbered markers placed below by msw for reference */
char str[50];
int main( int argc, char *argv[] )
{
printf("Enter your string\n>:");
fgets( str, 50, stdin );
char time_buf[10], date[10];
int a=strlen(time_buf);
int i=0;
time_t endwait;
time_t start = time(NULL);
time_t seconds = 30;
endwait=start+seconds;
printf("Enter date\n>:");
fgets(date, 10, stdin);
time_t now;
time(&now);
strftime(time_buf, 21, "%Y-%m-%d", gmtime(&now));
if (strncmp(time_buf,date,9) == 0) {
printf("TODAY!\n");
while (start < endwait) {
GtkWidget *label;
GtkWidget *window;
gtk_init( &argc, &argv );
window = gtk_window_new( GTK_WINDOW_TOPLEVEL );
gtk_window_set_title( GTK_WINDOW( window ),"ALARM");
label = gtk_label_new( str );
gtk_container_set_border_width(GTK_CONTAINER(window), 50);
gtk_container_add( GTK_CONTAINER( window ), label );
gtk_widget_show_all( window );
g_signal_connect(G_OBJECT(window),"destroy",
G_CALLBACK( gtk_main_quit ),NULL)
gtk_main(); // mark 1 ###
gtk_widget_destroy (label); // mark 2 ###
//gtk_widget_hide(window);
start = time(NULL);
sleep(10);
}
} else {
printf("NOT TODAY");
return 0;
}
}
GTK has an event loop, started with gtk_main. Actually, it is wrapping a glib event loop, to which you can add timeouts using g_timeout_add_full (or simply g_timeout_add). This is the good way to handle your issue (make some GTK signal handler register a Glib timeout which could e.g. call gtk_widget_hide or gtk_exit ...)
The big problem is that after you invoke gtk_main() at mark 1, your program does not get to run again until gtk_main exits. Prior to gtk_main returning, all widgets from the toplevel down will be destroyed. That's why I assume the error happened at mark 2 where you try to destroy a label that's already been destroyed.
It is still not clear to me why you'd want the behavior. Screen-wide popup notification behaves differently than gtk/glib/X11 programs because it is different. If I am running a program and a top-level window comes to the screen I should know what caused it and be able to get rid of it. It is more intuitive for the user if you scrap the popup, put a label below the entry¹ and change its text to "" when you want it to be invisible. And what #BasileStarynkevitch said.
¹What entry? The one that you should have to enter the string in. it would be an odd program that takes input from the console and displays output in a window.

getch() of ncurses doesn't work

I need to create a mainloop for my program and wrote the following function:
void menu(){
int ch;
cbreak();
noecho();
initscr();
refresh();
while (ch != KEY_F(9)){
ch = getch();
cout << ch << endl;
switch (ch){
case KEY_F(1): add();
break;
case KEY_F(2): edit();
break;
case KEY_F(3):
break;
case KEY_F(4):
break;
}
}
endwin();
}
But getch() doesn't work and print -1 in loop. how i do?
May i set special attr or call special func?
You need to call keypad() e.g. keypad(stdscr, TRUE). But beyond that the function keys may not work on your terminal. Check your ncurses.h file for a has_key() function and you can use that to determine if they are available on your terminal.
First, every ncurses function should be used only after initscr() has been called. In your code cbreak() and noecho() are probably ignored.
Second, if you want to use function keys, you have to tell that to ncurses, by calling keypad(stdscr, TRUE). However, since not every computer has got function keys, you should always check if the system support that functionality, using has_key() (same for has_colors() that checks if current terminal supports colors).
Yes, my loop is here:
initscr();
clear();
noecho();
cbreak(); /* Line buffering disabled. pass on everything */
startx = (80 - WIDTH) / 2;
starty = (24 - HEIGHT) / 2;
menu_win = newwin(HEIGHT, WIDTH, starty, startx);
keypad(menu_win, TRUE);
mvprintw(0, 0, "Name of my program");
refresh();
print_menu(menu_win, highlight);
while (true)
{ c = wgetch(menu_win);
switch(c){
TYPE OF KEYS;
}//END OF SWITCH
}//END OF LOOP

GTK window motion animation?

I want to move my GTK_WINDOW across the screen automatically. Currently I have it in a draw/move loop, but that's terribly choppy. I'm very new to GTK programming (and gui programming in general). What am I missing?
You haven't said what sort of path you want the window to follow. If the path is some simple function of time -- that is, if you have a way to compute where you want the window to be at any given time -- you could try the method illustrated in following code. For the quite-simple menu in the example, it works ok on my Linux system and produces fairly smooth motion.
The key to the method is that instead of moving the window a given distance per timer event, it finds out the current time and moves the window to the location it should be at, at that time. Thus, the time derivative of speed of motion should be constant, which avoids ragged or choppy motion even if timer events occur irregularly. (As noted in g-timeout-add() description, irregularity can easily occur.)
In this example, the path is from top left of window to bottom left and back, repeatedly. The constant 'HalfTime' in timerEvent() controls how long it takes to move from corner to corner. The constant 3 in the g_timeout_add() call sets the timer interval to 0.003 seconds, or about 333 moves per second (MPS). (You may want to try more-reasonable rates, such as 20, 30, 40, etc MPS; I used the number 3 because I didn't look up g-timeout-add() before using it, and assumed the delay was hundreths of seconds, for about 33 MPS, rather than milliseconds, for about 333 MPS.) If your window contents are quite complex, fewer MPS will be practical. Also, I tried some slower rates and got more of an impression of choppiness.
/* $Id: app12.c $
Re: animating position of a top-level Gtk window
jiw July 2011 -- Offered without warranty under GPL v3
terms per http://www.gnu.org/licenses/gpl.html */
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <gtk/gtk.h>
typedef struct DATA { GTimer *timer; GtkWidget *window; int w, h; }
DataStruct;
gboolean timerEvent(void *dataset) {
enum { HalfTime=8, CycTime=2*HalfTime };
gulong micros;
DataStruct *data =dataset;
double t = fabs(fmod (g_timer_elapsed (data->timer, &micros), CycTime));
int x = (t*data->w)/HalfTime, y = (t*data->h)/HalfTime;
gtk_window_move (GTK_WINDOW(data->window),
t<HalfTime? x : 2*data->w-x, t<HalfTime? y : 2*data->h-y);
return TRUE; /* Keep timeout running */
}
int main(int argc, char **argv) {
GtkWidget *vbox, *b;
GdkScreen *gds;
DataStruct data;
data.timer = g_timer_new();
gtk_init (&argc, &argv);
data.window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
gtk_window_set_default_size (GTK_WINDOW(data.window), 200, 150);
g_signal_connect (G_OBJECT(data.window), "destroy",
G_CALLBACK(gtk_main_quit), NULL);
vbox = gtk_vbox_new (FALSE, 0);
gtk_container_add (GTK_CONTAINER(data.window), vbox);
b = gtk_button_new_with_label ("Click to Exit");
gtk_box_pack_start (GTK_BOX(vbox), b, TRUE, TRUE, TRUE);
g_signal_connect (b, "clicked", G_CALLBACK(gtk_main_quit), NULL);
gtk_widget_show_all (data.window);
gds = gdk_screen_get_default (); /* Get pointer to screen */
data.w = gdk_screen_get_width (gds); /* Find out screen width */
data.h = gdk_screen_get_height (gds); /* Find out screen height */
printf ("Screen size = %d by %d\n", data.w, data.h); fflush(stdout);
g_timeout_add(3, timerEvent, &data); /* Create .003 sec timer */
gtk_main();
return (0);
}

How do I get the pixel color under the cursor?

I need a fast command line app to return the color of the pixel under the mouse cursor.
How can I build this in VC++, I need something similar to this, but ideally not in .NET so it can be run many times per second?
Off the top of my head, the straightforward way:
#include <stdio.h>
#include <Windows.h>
int main(void) {
POINT p;
COLORREF color;
HDC hDC;
BOOL b;
// Get the device context for the screen
hDC = GetDC(NULL);
if (hDC == NULL)
return 3;
// Get the current cursor position
b = GetCursorPos(&p);
if (!b)
return 2;
// Retrieve the color at that position
color = GetPixel(hDC, p.x, p.y);
if (color == CLR_INVALID)
return 1;
// Release the device context again
ReleaseDC(GetDesktopWindow(), hDC);
printf("%i %i %i", GetRValue(color), GetGValue(color), GetBValue(color));
return 0;
}
ETA: Appears to work, at least for me.
ETA2: Added some error checking
ETA3: Commented code, compiled executable and a Visual Studio Solution can be found in my SVN repository.

Resources