How much chained assignment possible in java? - chained-assignment

For example
int a,b,c,d,e,f,g,h,.........................;
a=b=c=d=e=f=g=h=.............................=1;
so, how long it can be possible in java....

Well, let's try it out!
codegen.sh:
#!/bin/bash
# indentation deliberately weird,
# so that the generated code is legible
N="$1"
echo "public class Chain$N {"
echo " public static void main(String[] args) {"
for i in $(seq 1 $N)
do
echo " int x$i;"
done
echo -n " "
for i in $(seq 1 $N)
do
echo -n "x$i="
done
echo "42;"
echo " }"
echo "}"
WARNING: don't run it in your directory with all the *.java answers for StackOverflow!!!
test.sh:
#!/bin/bash
rm Chain*.java # WARNING! DON'T RUN IT IN NON-EMPTY DIRECTORIES!
rm Chain*.class
for n in 10 100 1000 2000 2025 2037 2050 2075 2100
do
./codegen.sh $n >> "Chain$n.java"
(javac -Xmx1000M Chain$n.java 2> /dev/null) || echo "failed for $n"
(java Chain$n 2> /dev/null) || echo "failed to run for $n"
done
Example Chain10.java:
public class Chain10 {
public static void main(String[] args) {
int x1;
int x2;
int x3;
int x4;
int x5;
int x6;
int x7;
int x8;
int x9;
int x10;
x1=x2=x3=x4=x5=x6=x7=x8=x9=x10=42;
}
}
By simple manual bisection, it's easy to find the point where it fails.
On my setup, it fails for N=2075 with the default settings.
The compiler crashes with the following message:
The system is out of resources.
Consult the following stack trace for details.
java.lang.StackOverflowError
at com.sun.tools.javac.comp.Check.checkType(Check.java:533)
at com.sun.tools.javac.comp.Attr$ResultInfo.check(Attr.java:482)
at com.sun.tools.javac.comp.Attr.check(Attr.java:281)
at com.sun.tools.javac.comp.Attr.checkIdInternal(Attr.java:3642)
at com.sun.tools.javac.comp.Attr.checkId(Attr.java:3490)
at com.sun.tools.javac.comp.Attr.visitIdent(Attr.java:3233)
at com.sun.tools.javac.tree.JCTree$JCIdent.accept(JCTree.java:2011)
at com.sun.tools.javac.comp.Attr.attribTree(Attr.java:576)
at com.sun.tools.javac.comp.Attr.visitAssign(Attr.java:2994)
at com.sun.tools.javac.tree.JCTree$JCAssign.accept(JCTree.java:1686)
at com.sun.tools.javac.comp.Attr.attribTree(Attr.java:576)
at com.sun.tools.javac.comp.Attr.attribExpr(Attr.java:618)
at com.sun.tools.javac.comp.Attr.visitAssign(Attr.java:2996)
at com.sun.tools.javac.tree.JCTree$JCAssign.accept(JCTree.java:1686)
I think that you can easily correct this by increasing the size of the stack for javac.

Related

Unix: using the fork, exec and wait system call for command interpreter

I was able to refine the program further, but still need a little help in terms of storing the now separate words into an array. My current code only takes in the first word/command only. Here's my new code:
#include <unistd.h>
#include <string.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<cstdio>
#include<cstdlib>
#include<iostream>
using namespace std;
int main(){
int pid,status,rs;
char comm[100];
cout<<"Enter command:\n ";
cin.getline(comm,100);
char *token=strtok(comm," ");
pid=fork();
if(pid==-1)
{
perror("fork");
exit(pid);
}
if(pid==0)
{
while(token!=NULL){
char *argv[]={token,0};
rs=execvp(argv[0],argv);
token = strtok(NULL, " ");
}
if(rs==-1)
{
perror("execvp");
exit(rs);
}
}
else
{
cout<<"Done waiting for: "<<wait(&status)<<endl;
}
}
The outcome of the code should be something like this:
% ./z123456
Enter command: mkdir one
Enter command: touch one/file one/other one/more
Enter command: ls -l one
total 0
-rw-r--r-- 1 student student 0 Apr 3 13:03 file
-rw-r--r-- 1 student student 0 Apr 3 13:03 more
-rw-r--r-- 1 student student 0 Apr 3 13:03 other
Enter command: gobly gook
gobly: No such file or directory
Enter command: cd one
cd: No such file or directory
Enter command: exit
%

Can I link two separate executables with MPI_open_port and share port information in a text file?

I'm trying to create a shared MPI COMM between two executables which are both started independently, e.g.
mpiexec -n 1 ./exe1
mpiexec -n 1 ./exe2
I use MPI_Open_port to generate port details and write these to a file in exe1 and then read with exe2. This is followed by MPI_Comm_connect/MPI_Comm_accept and then send/recv communication (minimal example below).
My question is: can we write port information to file in this way, or is the MPI_Publish_name/MPI_Lookup_name required for MPI to work as in this, this and this? As supercomputers usually share a file system, this file based approach seems simpler and maybe avoids establishing a server.
It seems this should work according to the MPI_Open_Port documentation in the MPI 3.1 standard,
port_name is essentially a network address. It is unique within the communication universe to which it belongs (determined by the implementation), and may be used by any client within that communication universe. For instance, if it is an internet (host:port) address, it will be unique on the internet. If it is a low level switch address on an IBM SP, it will be unique to that SP
In addition, according to documentation on the MPI forum:
The following should be compatible with MPI: The server prints out an address to the terminal, the user gives this address to the client program.
MPI does not require a nameserver
A port_name is a system-supplied string that encodes a low-level network address at which a server can be contacted.
By itself, the port_name mechanism is completely portable ...
Writing the port information to file does work as expected, i.e creates a shared communicator and exchanges information using MPICH (3.2) but hangs at the MPI_Comm_connect/MPI_Comm_accept line when using OpenMPI versions 2.0.1 and 4.0.1 (on my local workstation running Ubuntu 12.04 but eventually needs to work on a tier 1 supercomputer). I have raised as an issue here but welcome a solution or workaround in the meantime.
Further Information
If I use the MPMD mode with OpenMPI,
mpiexec -n 1 ./exe1 : -n 1 ./exe2
this works correctly, so must be an issue with allowing the jobs to share ompi_global_scope as in this question. I've also tried adding,
MPI_Info info;
MPI_Info_create(&info);
MPI_Info_set(info, "ompi_global_scope", "true");
with info passed to all commands, with no success. I'm not running a server/client model as both codes run simultaneously so sharing a URL/PID from one is not ideal, although I cannot get this to work even using the suggested approach, which for OpenMPI 2.0.1,
mpirun -n 1 --report-pid + ./OpenMPI_2.0.1 0
1234
mpirun -n 1 --ompi-server pid:1234 ./OpenMPI_2.0.1 1
gives,
ORTE_ERROR_LOG: Bad parameter in file base/rml_base_contact.c at line 161
This failure appears to be an internal failure;
here's some additional information (which may only be relevant to an
Open MPI developer):
pmix server init failed
--> Returned value Bad parameter (-5) instead of ORTE_SUCCESS
and with OpenMPI 4.0.1,
mpirun -n 1 --report-pid + ./OpenMPI_4.0.1 0
1234
mpirun -n 1 --ompi-server pid:1234 ./OpenMPI_4.0.1 1
gives,
ORTE_ERROR_LOG: Bad parameter in file base/rml_base_contact.c at line 50
...
A publish/lookup server was provided, but we were unable to connect
to it - please check the connection info and ensure the server
is alive:
Using 4.0.1 means the error should not be related to this bug in OpenMPI.
Minimal code
#include "mpi.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <iostream>
#include <fstream>
using namespace std;
int main( int argc, char *argv[] )
{
int num_errors = 0;
int rank, size;
char port1[MPI_MAX_PORT_NAME];
char port2[MPI_MAX_PORT_NAME];
MPI_Status status;
MPI_Comm comm1, comm2;
int data = 0;
char *ptr;
int runno = strtol(argv[1], &ptr, 10);
for (int i = 0; i < argc; ++i)
printf("inputs %d %d %s \n", i,runno, argv[i]);
MPI_Init(&argc, &argv);
MPI_Comm_size(MPI_COMM_WORLD, &size);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
if (runno == 0)
{
printf("0: opening ports.\n");fflush(stdout);
MPI_Open_port(MPI_INFO_NULL, port1);
printf("opened port1: <%s>\n", port1);
//Write port file
ofstream myfile;
myfile.open("port");
if( !myfile )
cout << "Opening file failed" << endl;
myfile << port1 << endl;
if( !myfile )
cout << "Write failed" << endl;
myfile.close();
printf("Port %s written to file \n", port1); fflush(stdout);
printf("Attempt to accept port1.\n");fflush(stdout);
//Establish connection and send data
MPI_Comm_accept(port1, MPI_INFO_NULL, 0, MPI_COMM_WORLD, &comm1);
printf("sending 5 \n");fflush(stdout);
data = 5;
MPI_Send(&data, 1, MPI_INT, 0, 0, comm1);
MPI_Close_port(port1);
}
else if (runno == 1)
{
//Read port file
size_t chars_read = 0;
ifstream myfile;
//Wait until file exists and is avaialble
myfile.open("port");
while(!myfile){
myfile.open("port");
cout << "Opening file failed" << myfile << endl;
usleep(30000);
}
while( myfile && chars_read < 255 ) {
myfile >> port1[ chars_read ];
if( myfile )
++chars_read;
if( port1[ chars_read - 1 ] == '\n' )
break;
}
printf("Reading port %s from file \n", port1); fflush(stdout);
remove( "port" );
//Establish connection and recieve data
MPI_Comm_connect(port1, MPI_INFO_NULL, 0, MPI_COMM_WORLD, &comm1);
MPI_Recv(&data, 1, MPI_INT, 0, 0, comm1, &status);
printf("Received %d 1\n", data); fflush(stdout);
}
//Barrier on intercomm before disconnecting
MPI_Barrier(comm1);
MPI_Comm_disconnect(&comm1);
MPI_Finalize();
return 0;
}
The 0 and 1 simply specify if this code writes a port file or reads it in the example above. This is then run with,
mpiexec -n 1 ./a.out 0
mpiexec -n 1 ./a.out 1

SCP always returns the same error code

I have a problem copying files with scp. I use Qt and copy my files with scp using QProcess. And when something bad happens I always get exitCode=1. It always returns 1. I tried copying files with a terminal. The first time I got the error "Permission denied" and the exit code was 1. Then I unplugged my Ethernet cable and got the error "Network is unreachable". And the return code was still 1. It confuses me very much cause in my application I have to distinct these types of errors.
Any help is appreciated. Thank you so much!
See this code as a working example:
bool Utility::untarScript(QString filename, QString& statusMessages)
{
// Untar tar-bzip2 file, only extract script to temp-folder
QProcess tar;
QStringList arguments;
arguments << "-xvjf";
arguments << filename;
arguments << "-C";
arguments << QDir::tempPath();
arguments << "--strip-components=1";
arguments << "--wildcards";
arguments << "*/folder.*";
// tar -xjf $file -C $tmpDir --strip-components=1 --wildcards
tar.start("tar", arguments);
// Wait for tar to finish
if (tar.waitForFinished(10000) == true)
{
if (tar.exitCode() == 0)
{
statusMessages.append(tar.readAllStandardError());
return true;
}
}
statusMessages.append(tar.readAllStandardError());
statusMessages.append(tar.readAllStandardOutput());
statusMessages.append(QString("Exitcode = %1\n").arg(tar.exitCode()));
return false;
}
It gathers all available process output for you to analyse. Especially look at readAllStandardError().

line 43: syntax error: unexpected end of file

I am getting a syntax error on line 43 when compiling the unix script code. This code is to search through a folder of textfile and match any word from the input.txt.
code still hasn't finish yet though
#!/bin/bash
findkeyword () {
file="$1"
keyword="$2"
value="$3"
int count = 0
cat $file | awk '{
while read line
do
for (ii=1;ii<=NF;ii++) {
if ($ii == $keyword)
count++
fi
}
done
}'
echo "Profile: " $file
scorefile $value $count
scorefile () {
value="$1"
count="$2"
echo "Score: " $value*$count
}
cat input.txt | awk '{
while read line
do
keyword=$1
value=$2
for xx in `ls submissions/*`
do
filename=$xx
findkeyword $filename $keyword $value
done
done
}'
#!/bin/bash
findkeyword () {
file="$1"
keyword="$2"
value="$3"
int count = 0
while read line; do
for word in $line; do
if [[ $word = $keyword ]]; then
$((count++))
fi
done
done <$file
echo "Profile: " $file
scorefile $value $count
} # missing closing brace here
scorefile () {
value="$1"
count="$2"
echo "Score: " $(($value*$count)) # Math evaluation broken
}
while read line
do
keyword=$1
value=$2
for xx in `ls submissions/*`
do
filename=$xx
findkeyword $filename $keyword $value
done
done<input.txt

How do I determine if a terminal is color-capable?

I would like to change a program to automatically detect whether a terminal is color-capable or not, so when I run said program from within a non-color capable terminal (say M-x shell in (X)Emacs), color is automatically turned off.
I don't want to hardcode the program to detect TERM={emacs,dumb}.
I am thinking that termcap/terminfo should be able to help with this, but so far I've only managed to cobble together this (n)curses-using snippet of code, which fails badly when it can't find the terminal:
#include <stdlib.h>
#include <curses.h>
int main(void) {
int colors=0;
initscr();
start_color();
colors=has_colors() ? 1 : 0;
endwin();
printf(colors ? "YES\n" : "NO\n");
exit(0);
}
I.e. I get this:
$ gcc -Wall -lncurses -o hep hep.c
$ echo $TERM
xterm
$ ./hep
YES
$ export TERM=dumb
$ ./hep
NO
$ export TERM=emacs
$ ./hep
Error opening terminal: emacs.
$
which is... suboptimal.
A friend pointed me towards tput(1), and I cooked up this solution:
#!/bin/sh
# ack-wrapper - use tput to try and detect whether the terminal is
# color-capable, and call ack-grep accordingly.
OPTION='--nocolor'
COLORS=$(tput colors 2> /dev/null)
if [ $? = 0 ] && [ $COLORS -gt 2 ]; then
OPTION=''
fi
exec ack-grep $OPTION "$#"
which works for me. It would be great if I had a way to integrate it into ack, though.
You almost had it, except that you need to use the lower-level curses function setupterm instead of initscr. setupterm just performs enough initialization to read terminfo data, and if you pass in a pointer to an error result value (the last argument) it will return an error value instead of emitting error messages and exiting (the default behavior for initscr).
#include <stdlib.h>
#include <curses.h>
int main(void) {
char *term = getenv("TERM");
int erret = 0;
if (setupterm(NULL, 1, &erret) == ERR) {
char *errmsg = "unknown error";
switch (erret) {
case 1: errmsg = "terminal is hardcopy, cannot be used for curses applications"; break;
case 0: errmsg = "terminal could not be found, or not enough information for curses applications"; break;
case -1: errmsg = "terminfo entry could not be found"; break;
}
printf("Color support for terminal \"%s\" unknown (error %d: %s).\n", term, erret, errmsg);
exit(1);
}
bool colors = has_colors();
printf("Terminal \"%s\" %s colors.\n", term, colors ? "has" : "does not have");
return 0;
}
Additional information about using setupterm is available in the curs_terminfo(3X) man page (x-man-page://3x/curs_terminfo) and Writing Programs with NCURSES.
Look up the terminfo(5) entry for the terminal type and check the Co (max_colors) entry. That's how many colors the terminal supports.

Resources