text:
Q: ¿Cómo mostrar un SplashScreen para decir que la aplicación está "cargando"? Necesito mostrar un progressbar estilo loading, me explico:
EL primer activity que se lanza es un splashscreen, luego de este viene un activity en donde automáticamente comienza a funcionar la clase mplayer con una url externa. Sucede que tarda un tiempo variable (según estado de la red y otras condiciones) en aparecer el segundo activity y en ese lapsus muestra una pantalla negra. Es en ese momento que deseo agregar un loadig por mientras se obtiene la información de la url externa de la clase mplayer.
Muestro el código del layout de mi activity donde tengo el player.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.streamingcoop.MainActivity">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <TextView
        android:id="@+id/txt_noticias"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="NOTICIAS"
        android:textSize="@dimen/abc_action_bar_progress_bar_size" />

</LinearLayout>

<TableLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_weight="1">

    <TableRow
        android:id="@+id/tableRow1"
        android:layout_weight="1"
        android:gravity="center"
        android:paddingLeft="20dp"
        android:paddingRight="20dp">

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_weight="1"
            android:orientation="vertical">

            <Button
                android:id="@+id/button1"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Deportes" />

            <Button
                android:id="@+id/button2"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Política" />
        </LinearLayout>

    </TableRow>

    <ProgressBar
        android:id="@+id/mi_loading"
        android:layout_width="748dp"
        android:layout_height="102dp"
        android:indeterminate="false" />

    <TableRow
        android:id="@+id/tableRow2"
        android:layout_weight="1"
        android:gravity="center"
        android:paddingBottom="10dp"
        android:paddingLeft="20dp"
        android:paddingRight="20dp"
        android:paddingTop="20dp">

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_weight="1"
            android:gravity="center"
            android:orientation="vertical"
            android:paddingLeft="20dp">

            <Button
                android:id="@+id/button3"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Economía" />

            <Button
                android:id="@+id/button4"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:singleLine="false"
                android:text="Entretención" />

        </LinearLayout>

    </TableRow>
</TableLayout>

<RelativeLayout
    android:id="@+id/reproductor"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom"
    android:orientation="vertical">

    <ImageButton
        android:id="@+id/stop"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:src="@android:drawable/ic_media_pause" />

    <ImageButton
        android:id="@+id/play"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom"
        android:src="@android:drawable/ic_media_play"
        android:visibility="invisible"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

</RelativeLayout>

Muestro el código del activity donde está el player.
public class MainActivity extends Activity implements OnClickListener {
    static MediaPlayer mPlayer;
    ImageButton buttonPlay;
    ImageButton buttonStop;
    String url = "url";
    Button btn_politica, btn_deportes, btn_espectaculo, btn_entretencion;
    ProgressBar progressbar;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //setContentView(R.layout.splash);//analiza el archivo XML, traduce a objetos cada componente,
        //le asigna los atributos, establece contenedores y todas las relaciones
        //padre e hijo necesarias.

        progressbar = (ProgressBar) findViewById(R.id.mi_loading);
       // progressbar_splash=(ProgressBar) findViewById(R.id.mi_loading_splash);
        progressbar.setVisibility(View.VISIBLE);

        //Bloque de codigo para el streaming al cargar el activity
        mPlayer = new MediaPlayer();
        mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        mPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                progressbar.setVisibility(View.INVISIBLE);
               // progressbar_splash.setVisibility(View.INVISIBLE);
                 //Toast.makeText(getApplicationContext(), "Ya cargó!!", Toast.LENGTH_LONG).show();

            }
        });
        try {
            mPlayer.setDataSource(url);
        } catch (IllegalArgumentException e) {
            Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
        } catch (SecurityException e) {
            Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
        } catch (IllegalStateException e) {
            Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            mPlayer.prepare();

        } catch (IllegalStateException e) {
            Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
        } catch (IOException e) {
            Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
        }
        mPlayer.start();
        //Finaliza bloque de codigo para cargar el streaming al inicio de la aplicacion+

        initialize();

        //Bloque de codigo para el streaming al presionar play
        buttonPlay = (ImageButton) findViewById(R.id.play);
        buttonPlay.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                mPlayer = new MediaPlayer();
                mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                mPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                    @Override
                    public void onPrepared(MediaPlayer mp) {
                    progressbar.setVisibility(View.INVISIBLE);

                      //Toast.makeText(getApplicationContext(), "Cargandooooooo", Toast.LENGTH_LONG).show();

                    }
                });
                try {
                    mPlayer.setDataSource(url);
                } catch (IllegalArgumentException e) {
                    Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
                } catch (SecurityException e) {
                    Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
                } catch (IllegalStateException e) {
                    Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                try {
                    mPlayer.prepare();
                    // progressbar = (ProgressBar) findViewById(R.id.mi_loading);
                    //progressbar.setVisibility(View.GONE);
                } catch (IllegalStateException e) {
                    Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
                } catch (IOException e) {
                    Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
                }
                mPlayer.start();
                // progressbar.setVisibility(View.INVISIBLE);
                buttonPlay.setVisibility(View.INVISIBLE);
                buttonStop.setVisibility(View.VISIBLE);

            }
        });

        //Bloque de codigo para el streaming al presionar pause
        buttonStop = (ImageButton) findViewById(R.id.stop);
        buttonStop.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                // TODO Auto-generated method stub
                if (mPlayer != null && mPlayer.isPlaying()) {
                    mPlayer.stop();
                    //buttonPlay.setEnabled(true);
                    buttonPlay.setVisibility(View.VISIBLE);
                    buttonStop.setVisibility(View.INVISIBLE);
                   // progressbar.setVisibility(View.INVISIBLE);
                }
            }
        });
    }

    private void initialize() {
        btn_deportes = (Button) findViewById(R.id.button1);
        btn_deportes.setOnClickListener(this);

        btn_politica = (Button) findViewById(R.id.button2);
        btn_politica.setOnClickListener(this);

        btn_espectaculo = (Button) findViewById(R.id.button3);
        btn_espectaculo.setOnClickListener(this);

        btn_entretencion = (Button) findViewById(R.id.button4);
        btn_entretencion.setOnClickListener(this);
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.button1:
                startActivity(new Intent(this, Activity_Noticias_Deportes.class));
                break;
            case R.id.button2:
                startActivity(new Intent(this, Activity_Noticias_Politica.class));
                break;
            case R.id.button3:
                startActivity(new Intent(this, Activity_Noticias_Economia.class));
                break;
            case R.id.button4:
                startActivity(new Intent(this, Activity_Noticias_Entretencion.class));
                break;
        }
    }
    protected void onDestroy() {
        super.onDestroy();
        // TODO Auto-generated method stub
        if (mPlayer != null) {
            mPlayer.release();
            mPlayer = null;
        }
    }
}

Muestro el código del primer Activity, el Splash
public class Splash extends Activity {
    private AlertDialog.Builder mBuilderWait;
    private static final long SPLASH_SCREEN_DELAY = 2000;
@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);

    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.splash);
   // progressbar = (ProgressBar) findViewById(R.id.mi_loading);
   // lanzarthread();
    TimerTask task = new TimerTask() {
        @Override
        public void run() {
            // Start the next activity

            Intent mainIntent = new Intent().setClass(
                    Splash.this, MainActivity.class);
            startActivity(mainIntent);

            // Close the activity so the user won't able to go back this
            // activity pressing Back button
            finish();
        }
    };
    // Simulate a long loading process on application startup.
    Timer timer = new Timer();
    timer.schedule(task, SPLASH_SCREEN_DELAY);
}
private void lanzarthread() {
    Thread timer = new Thread() {
        public void run() {
            try {
                sleep(2000); //se duerme por 2 segundos
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();//muestra error de ejecucion en consola
            } finally {//pase lo que pase debe saltar a la siguiente pantalla.
                Intent intent = new Intent(Splash.this, MainActivity.class); //instanciamos el objeto Intent y lo inicializamos desde splash hasta MainActivity
                startActivity(intent);
            }
        }

    };
    timer.start();
}

}

A: Simplemente podrías agregar un progressBar en tu Activity, por ejemplo:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".SplashScreenActivity" >

                    <ProgressBar
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerInParent="true" />

</RelativeLayout>

y cuando tu video/mp3 este listo por medio del listener setOnPreparedListener() has el progressBar invisible:
mediaPlayer.setOnPreparedListener(new OnPreparedListener(){

    @Override
        public void onPrepared(MediaPlayer mp) {
            progressBar.setVisibility(View.INVISIBLE); // esconde el progressBar.
        }
    });

En el caso de tu ejemplo creas varias instancias de MediaPlayer lo cual es incorrecto, puedes tener sola una instancia durante la vida de la actividad, ve este ejemplo :
  progressbar.setVisibility(View.VISIBLE);

            try {
                //Bloque de codigo para el streaming al cargar el activity
                mPlayer = new MediaPlayer();
                mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                mPlayer.setDataSource(url);
                mPlayer.prepare();
            } catch (IOException e) {
                Log.e("ERROR",e.getMessage());
                Toast.makeText(getApplicationContext(), "Ocurrio un ERROR!!", Toast.LENGTH_LONG).show();
            }

            mPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    progressbar.setVisibility(View.INVISIBLE);
                    Toast.makeText(getApplicationContext(), "Ya cargó!!", Toast.LENGTH_LONG).show();
                    progressbar.setVisibility(View.INVISIBLE);
                    mPlayer.start();
                }
            });

Esto sería tu código corregido:
public class VideoActivity extends Activity implements View.OnClickListener {

        static MediaPlayer mPlayer;
        ImageButton buttonPlay;
        ImageButton buttonStop;
        String url = "http://programmerguru.com/android-tutorial/wp-content/uploads/2013/04/hosannatelugu.mp3";
        Button btn_politica, btn_deportes, btn_espectaculo, btn_entretencion;
        ProgressBar progressbar;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            //setContentView(R.layout.splash);//analiza el archivo XML, traduce a objetos cada componente,
            //le asigna los atributos, establece contenedores y todas las relaciones
            //padre e hijo necesarias.

            progressbar = (ProgressBar) findViewById(R.id.mi_loading);
            // progressbar_splash=(ProgressBar) findViewById(R.id.mi_loading_splash);
            progressbar.setVisibility(View.VISIBLE);

            try {
                //Bloque de codigo para el streaming al cargar el activity
                mPlayer = new MediaPlayer();
                mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                mPlayer.setDataSource(url);
                mPlayer.prepare();
            } catch (IOException e) {
                Log.e("ERROR",e.getMessage());
                Toast.makeText(getApplicationContext(), "Ocurrio un ERROR!!", Toast.LENGTH_LONG).show();
            }

            mPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    progressbar.setVisibility(View.INVISIBLE);
                    Toast.makeText(getApplicationContext(), "Ya cargó!!", Toast.LENGTH_LONG).show();
                    Log.i("VIDEO", "ProgressBar Invisible!");
                    progressbar.setVisibility(View.INVISIBLE);
                    mPlayer.start();
                }
            });
            //Finaliza bloque de codigo para cargar el streaming al inicio de la aplicacion+
            initialize();
            //Bloque de codigo para el streaming al presionar play
            buttonPlay = (ImageButton) findViewById(R.id.play);
            buttonPlay.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    if (mPlayer != null && !mPlayer.isPlaying()) {
                        try {
                            Log.i("INFO", "ProgressBar Visible! =) ");
                            // Aquí se hace el progressBar visible y cuando                      este preparado el video para reproducción se ejectua onPrepared() que hace el progressBar invisible.
                            progressbar.setVisibility(View.VISIBLE);
                            mPlayer.prepare();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        buttonPlay.setVisibility(View.INVISIBLE);
                        buttonStop.setVisibility(View.VISIBLE);
                    }

                }
            });

            //Bloque de codigo para el streaming al presionar pause
            buttonStop = (ImageButton) findViewById(R.id.stop);
            buttonStop.setOnClickListener(new View.OnClickListener() {

                public void onClick(View v) {
                    if (mPlayer != null && mPlayer.isPlaying()) {
                        mPlayer.stop();
                        buttonPlay.setVisibility(View.VISIBLE);
                        buttonStop.setVisibility(View.INVISIBLE);
                    }
                }
            });
        }

        private void initialize() {
            btn_deportes = (Button) findViewById(R.id.button1);
            btn_deportes.setOnClickListener(this);

            btn_politica = (Button) findViewById(R.id.button2);
            btn_politica.setOnClickListener(this);

            btn_espectaculo = (Button) findViewById(R.id.button3);
            btn_espectaculo.setOnClickListener(this);

            btn_entretencion = (Button) findViewById(R.id.button4);
            btn_entretencion.setOnClickListener(this);
        }

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.button1:
                    startActivity(new Intent(this, Activity_Noticias_Deportes.class));
                    break;
                case R.id.button2:
                    startActivity(new Intent(this, Activity_Noticias_Politica.class));
                    break;
                case R.id.button3:
                    startActivity(new Intent(this, Activity_Noticias_Economia.class));
                    break;
                case R.id.button4:
                     startActivity(new Intent(this, Activity_Noticias_Entretencion.class));
                    break;
            }
        }

        protected void onDestroy() {
            super.onDestroy();
            if (mPlayer != null) {
                mPlayer.release();
                mPlayer = null;
            }
        }
    }

Recuerda el permiso
 <uses-permission android:name="android.permission.INTERNET"/>

ya que estas cargando tu recurso desde internet.

A: Lo que puedes hacer es crear un Alert Dialog para mostrar un mensaje de espera utilizando un Thread.
Primero crearias tu AlertDialog declarándolo fuera de tu clase
private AlertDialog.Builder mBuilderWait;

Después inicializandolo, es importante no dejar la posibilidad de que pueda cancelarse el Dialog
mBuilderWait = new AlertDialog.Builder(this);

mBuilderWait.setTitle(getString("Titulo del Alert"))
            .setMessage(getString("Tu texto de espera.."))
            .setCancelable(false);

Ahora mostraras el AlertDialog antes de que inicies el proceso
mBuilderWait.show();

y cuando termine
mBuilderWait.dismiss();

El Thread es para realizar un cambio a la interfaz en el mismo tiempo de ejecución, esto es mas que nada si hay un error.
Ejemplo:
try{

    //Tu codigo de carga con el AlertDialog de espera

}catch(Exception e){

    //En caso de error cambio al dialog en mismo tiempo de ejecucion

    runOnUiThread(new Runnable() {
                    public void run() {
                    mBuilderWait.setTitle(getString("Error"))
                                .setMessage(getString("Error de conexion al servidor"))
                                .setCancelable(false);
                                .setPositiveButton("Aceptar", new DialogInterface.OnClickListener() {
                                        public void onClick(DialogInterface dialog, int id) {
                                            dialog.cancel();
                                        }
                                 });
                mBuilderWait.show();

                }
    });

}

Referencias:

*

*runOnUiThread

*AlertDialog


text:
Q: semop : Bad file descriptor #define MAX 2

int main(){

    int mutex = semget(ftok("/usr",'P'),1,IPC_CREAT|0666);
    int wrt = semget(ftok("/usr",'Q'),1,IPC_CREAT|0666);

    if(mutex <= 0) perror("mutex");
    if(wrt <= 0) perror("wrt");

    if(semctl(mutex,0,SETVAL,1) <= 0) perror("mutex semctl");
    if(semctl(wrt,0,SETVAL,1) <= 0) perror("wrt semctl");

    struct sembuf sops;
    int pid1,pid2,readcount = 0,var=0;
    FILE* fp = fopen("buffer.txt","w");
    fprintf(fp,"%d",var);
    fclose(fp);
    printf("File created. VAR is %d\n",var);
    pid1 = fork();

   if(!pid1){

        while(1){
            sleep(1);
            sops.sem_num = 0; sops.sem_op = -1; sops.sem_flg = 0;
        semop(mutex,&sops,1);

        // if(readcount == 0)
        if(readcount == 0){
            //  wait(wrt)
            sops.sem_num = 0; sops.sem_op = -1; sops.sem_flg = 0;
            if(semop(wrt,&sops,1) <= 0) perror("wrt in reader 1");
        }
        // readcount++
        readcount++;
        // signal(mutex)
        sops.sem_num = 0; sops.sem_op = 1; sops.sem_flg = 0;
        semop(mutex,&sops,1);

        // read()
        sleep(1.5);
        printf("First reader enters \n");
        fp = fopen("buffer.txt","r");
        fscanf(fp,"%d",&var);
        printf("Reader (%d) reads the value %d\n",getpid(),var);
        fclose(fp);
        printf("First reader leaves\n");
        sleep(1.5);

        // wait(mutex)
        sops.sem_num = 0; sops.sem_op = -1; sops.sem_flg = 0;
        semop(mutex,&sops,1);
        // readcount--;
        readcount--;
        // if(readcount == 0)
        if(readcount == 0){
            //  signal(wrt)
            sops.sem_num = 0; sops.sem_op = 1; sops.sem_flg = 0;
            semop(wrt,&sops,1);
        }
        // signal(mutex)
        sops.sem_num = 0; sops.sem_op = 1; sops.sem_flg = 0;
        semop(mutex,&sops,1);
    }

}
else{
    pid2 = fork();
    if(!pid2){

        while(1){
            sleep(1);
            // wait(mutex)
            sops.sem_num = 0; sops.sem_op = -1; sops.sem_flg = 0;
            semop(mutex,&sops,1);
            // if(readcount == 0)
            if(readcount == 0){
                //  wait(wrt)
                sops.sem_num = 0; sops.sem_op = -1; sops.sem_flg = 0;
                if(semop(wrt,&sops,1) <= 0) perror("wrt in reader 1");
            }
            // readcount++
            readcount++;
            // signal(mutex)
            sops.sem_num = 0; sops.sem_op = 1; sops.sem_flg = 0;
            semop(mutex,&sops,1);

            // read()
            sleep(1);
            printf("Second reader enters\n");
            sleep(1);
            fp = fopen("buffer.txt","r");
            fscanf(fp,"%d",&var);
            printf("Reader (%d) reads the value %d\n",getpid(),var);
            sleep(1);
            fclose(fp);
            printf("Second reader leaves\n");
            sleep(1);

            // wait(mutex)
            sops.sem_num = 0; sops.sem_op = -1; sops.sem_flg = 0;
            semop(mutex,&sops,1);
            // readcount--;
            readcount--;
            // if(readcount == 0)
            if(readcount == 0){
                //  signal(wrt)
                sops.sem_num = 0; sops.sem_op = 1; sops.sem_flg = 0;
                semop(wrt,&sops,1);
            }
            // signal(mutex)
            sops.sem_num = 0; sops.sem_op = 1; sops.sem_flg = 0;
            semop(mutex,&sops,1);
        }
    }
    else{
        //struct sembuf sop;

        while(1){

            // wait(wrt)
            sops.sem_num = 0; sops.sem_op = -1; sops.sem_flg = 0;
            semop(wrt,&sops,1);

            // write
            sleep(1);
            //printf("%d Writer enters\n",time(0)%100);
            fp = fopen("buffer.txt","w");
            fscanf(fp,"%d",&var);
            var++;
            sleep(1);
            printf("Writer (%d) writes the value %d\n",getpid(),var);
            fprintf(fp,"%d",&var);
            fclose(fp);
            sleep(1);
            printf("Writer leaves wrt %d\n",semctl(wrt,0,GETVAL,0));

            // signal(wrt)
            sops.sem_num = 0; sops.sem_op = 1; sops.sem_flg = 0;
            printf("wrt just before semop %d and op is %d\n",semctl(wrt,0,GETVAL,0),sops.sem_op);
            if(semop(wrt,&sops,1) <= 0) perror("wrt signal");
            printf("wrt %d\n",semctl(wrt,0,GETVAL,0));
        }
    }

}
}

The following code a slight variation of the readers - writers problem. In this program I try to create two child process (two readers). There is a parent process (writer). The readers just read the value from a file named buffer.txt, while the writer writes a value in that file.
But in the writer code the // signal(wrt) code, which uses semop(), is getting the error Bad File descriptor. As a result, the value of wrt is not incremented. Please help.

A: After a long hardship of 10 hours , I have come up with a solution that runs perfectly without any deadlock of error .
Change 1 :
In code for writer , first of all open the file in read mode , read the value , then open the file in write mode and then write the incremented value .
This is not sufficient , it may further have deadlock problems.
Change 2 :
we need to also create a semaphore for readcount as they have to be used by both the child processes.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Best way to change the innerHTML for an entire class or arrray? When I run this code it is changing all of the volunteersName and only the first set of the other items. Once it loops it doesn't change the other values. Hopefully someone can help me find my issue. I'm guessing I can't use a loop for this and maybe need to use forEach? Not sure exactly how to do this properly. Thanks in advance.
EDIT: I'm getting this console error below
Uncaught TypeError: Cannot read property 'value' of null
function invite() {
    for (index = 1; index >= volunteersName.length; index++) {
            var names = [document.getElementById("volunteersName" + index).value];
            document.getElementById("name" + index).innerHTML = names
            document.querySelector(".organizationName2").innerHTML = document.getElementById("organizationName").value;
            document.querySelector(".eventDate2").innerHTML = document.getElementById("eventDate").value;
            document.querySelector(".websiteURL2").innerHTML = document.getElementById("websiteURL").value;
            document.querySelector(".hostName2").innerHTML = document.getElementById("hostName").value;
    }

A: The problem is your loop syntax.
for (index = 1; index >= volunteersName.length; index++) {

This says the loop should run for as long as index is equal to or greater than the length of your array.
So unless your array has 1 or 0 items in it, it will never run, since index starts at 1.
Change to:
for (index = 1; index <= volunteersName.length; index++) {

...so the loop runs as long as index is equal to or less than the length of the array.

A: Instead of using querySelector you can use querySelectorAll and iterate through index.
function invite() {
    for (index = 1; index <= volunteersName.length; index++) {
            var names = [document.getElementById("volunteersName" + index).value];
            document.getElementById("name" + index).innerHTML = names
            document.querySelectorAll(".organizationName2")[index-1].innerHTML = document.getElementById("organizationName").value;
            document.querySelectorAll(".eventDate2")[index-1].innerHTML = document.getElementById("eventDate").value;
            document.querySelectorAll(".websiteURL2")[index-1].innerHTML = document.getElementById("websiteURL").value;
            document.querySelectorAll(".hostName2")[index-1].innerHTML = document.getElementById("hostName").value;
    }

A: Okay, so I got it working properly with the querySelectorAll answer but for some reason I need to keep index >= volunteersName
This is the code that makes it execute properly below
function invite() {
    for (index = 1; index >= volunteersName.length; index++) {
            var names = [document.getElementById("volunteersName" + index).value];
            document.getElementById("name" + index).innerHTML = names
            document.querySelectorAll(".organizationName2")[index-1].innerHTML = document.getElementById("organizationName").value;
            document.querySelectorAll(".eventDate2")[index-1].innerHTML = document.getElementById("eventDate").value;
            document.querySelectorAll(".websiteURL2")[index-1].innerHTML = document.getElementById("websiteURL").value;
            document.querySelectorAll(".hostName2")[index-1].innerHTML = document.getElementById("hostName").value;
    }

}


text:
Q: Decimal not recognized ASP.NET I'm trying to insert a decimal number in one form but with no success. Everytime, I get this:

My entity is declared like this:
public class Serie
{
    public int Id { get; set; }
    public string Name { get; set; }

    [RegularExpression(@"^\d+\.\d{0,2}$")]
    [Range(0, 9999999999999999.99)]
    public decimal Price { get; set; }
    public string Description { get; set; }
    public List<Season> Seasons { get; set; }
    public List<Rental> Rentals { get; set; }
    public List<Assessment> Assessments { get; set; }

}

On my razor page I have this on html side:
@page
@model Shows4All.Pages.Series.CreateModel

@{
    ViewData["Title"] = "Create";
}

Create

Serie

        <form method="post">

                <input asp-for="Serie.Name" class="form-control" />

                <input type="number" asp-for="Serie.Price" class="form-control" />

                <input asp-for="Serie.Description" class="form-control" />

                <input type="submit" value="Create" class="btn btn-primary" />

        </form>

    Back to List

@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}

I already tried without Data annotation and withou type="number" on html side...but it doesn't work. Any idea how can it be solved?

A: Try to add locale configuration in your aspet.config file like this:
  <configuration>
      <system.web>
          <globalization culture ="en-US" />
      </system.web>
  </configuration>

If didn't work, try remove the Regex attribute and test it again.


text:
Q: User triggered event in libevent I am currently writing a multi-threaded application using libevent.
Some events are triggered by IO, but I need a couple of events that are triggered accross threads by the code itself, using event_active().
I have tried to write a simple program that shows where my problem is:
The event is created using event_new(), and the fd set to -1.
When calling event_add(), if a timeout struct is used, the event is later properly handled by event_base_dispatch.
If event_add(ev, NULL) is used instead, it returns 0 (apparently successful), but event_base_dispatch() returns 1 (which means no the event was not properly registered.)
This behavior can be tested using the following code and swapping the event_add lines:
#include <event2/event.h>
#include <unistd.h>

void cb_func (evutil_socket_t fd, short flags, void * _param) {
  puts("Callback function called!");
}

void run_base_with_ticks(struct event_base *base)
{
  struct timeval one_sec;

  one_sec.tv_sec = 1;
  one_sec.tv_usec = 0;
  struct event * ev1;
  ev1 = event_new(base, -1, EV_PERSIST, cb_func, NULL);
  //int result = event_add(ev1, NULL);
  int result = event_add(ev1, &one_sec);
  printf("event_add result: %d\n",result);

  while (1) {
     result = event_base_dispatch(base);
     if (result == 1) {
       printf("Failed: event considered as not pending dispite successful event_add\n");
       sleep(1);
     } else {
       puts("Tick");
     }
  }
}

int main () {
  struct event_base *base = event_base_new();
  run_base_with_ticks(base);
  return 0;
}

Compilation: g++ sample.cc -levent
The thing is, I do not need the timeout, and do not want to use a n-years timeout as a workaround. So if this is not the right way to use user-triggered events, I would like to know how it is done.

A: Your approach is sound.  In Libevent 2.0, you can use event_active() to activate an event from another thread.  Just make sure that you use evthread_use_windows_threads() or evthread_use_pthreads() as appropriate beforehand, to tell Libevent to use the right threading library.
As for needing an extra event: in Libevent 2.0 and earlier, an event loop will exit immediately when there are no pending events added.  Your best bet there is probably the timeout trick you discovered.
If you don't like that, you can use the internal "event_base_add_virtual" function to tell the event_base that it has a virtual event.  This function isn't exported, though, so you'll have to say something like:
    void event_base_add_virtual(struct event_base *);
    // ...
    base = event_base_new();
    event_base_add_virtual(base); // keep it from exiting

That's a bit of a hack, though, and it uses an undocumented function, so you'd need to watch out in case it doesn't work with a later version of Libevent.
Finally, this method won't help you now, but there's a patch pending for future versions of Libevent (2.1 and later) to add a new flag to event_base_loop() to keep it from exiting when the loop is out of events.  The patch is over on Github; it is mainly waiting for code review, and for a better name for the option.

A: I just got burned by this with libevent-2.0.21-stable.  It is quite clearly a bug.  I hope they fix it in a future release.  In the meantime, updating the docs to warn us about it would be helpful.
The best workaround seems to be the fake timeout as described in the question.
@nickm, you didn't read the question. His example code uses event_new() like you described; there is a bug in libevent that causes it to fail when using a NULL timeout (but return 0 when you call event_add()).


text:
Q: Possibility of upvote bombing to suspend account Could it be possible for someone to get numerous people to upvote all of your questions/answers in an attempt to make it look like voting fraud is going on and suspending/deleting accounts?
For example, if you had (say) 20 questions and someone who had a grudge on you created 50 different "sock-puppet" accounts to upvote each and everyone of them, wouldn't there be some sort of automatic system detecting this "fraud" and placing punishments where it's actually not the fault of the upvoted account's owner?

A: I've seen a number of people be worried about this, or flag about serial upvoting on their account because they're afraid that they'll be suspended as a result. This is not something that should cause you concern.
Suspensions always require manual action by moderators, so a human will always be the one to make a decision on whether or not there is a suspicious pattern to any voting. As Mad Scientist indicates, we have some very detailed tools that allow us to identify these patterns and determine if fake accounts are being coordinated to benefit another. Only when we have very solid evidence that indicates these accounts are related to yours do we remove them and suspend. If there's any doubt, we don't.
I've even started experimenting with not suspending people for minor incidents of sock puppetry, to see if a suspension is needed in those cases to reform user behavior. Results have been mostly positive so far.
It would be really, really hard for someone to attack a person in this manner in a convincing way. They'd almost have to be someone you're related to or work with, and you would most likely know exactly who tried this if they did. Even in a case like that, odds are that we'd simply invalidate the votes and warn the people involved instead of suspending.
If you do see a coordinated ring of people voting for your account, flag it and we'll take a look. Frankly, I've only seen this once, but I've seen coordinated downvote attacks several times. You're far more likely to be hit with one of those.

A: The automatic system will only reverse the votes; it won't perform any other punishments.  Such other punishments would only be given by a human moderator (who would likely be notified of a possible action to take by the automatic script).  For that human moderator there's a pretty good chance that they would be able to determine what was going on, and that it wasn't you who was voting yourself up.  You would also have an opportunity to explain yourself in the event that a moderator did take some further action against you and be able to explain that the other accounts were not yours and that you were not complicit in their actions.

A: There's a bit more to sock puppet detection than that, and while this kind of attack would be theoretically possible, it would be very hard to make it convincing enough. The tools moderators have available are not public though, so you probably won't get a more specific answer than that.
The votes themselves would likely be removed automatically by the serial voting script, but any further action is done manually by a moderator or SE staff. There are no automatic suspension or account removals.


text:
Q: Shared memory between process prime number returning zero at child process I'm studying concepts of processes and memory sharing between processes. so I took an example code and I'm trying to adapt it to calculate if a number is prime by memory sharing. The code compiles and correctly returns whether a number is prime or not. however I noticed that in case the number is Primo, instead of printing the number is always coming to zero. where am i going wrong in memory sharing?
thank you very much for the support
#include <stdio.h>
#include <math.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/shm.h>

int main(){

    int i, j;
    int prime;
    int count = 0;
    int *n;
    int shmid;
    int pid;

        printf("Enter a number:");
        scanf("%d", &prime);

    if(prime < 0){
        printf("Not a prime number!");
    }
    else if(prime == 0){
        printf("Not a prime number!");
    }
    else{
        shmid = shmget(5, 2*sizeof(float), IPC_CREAT | 0600 );

        n = shmat(shmid, 0, 0);

        pid = fork();
        if(pid > 0){
            count = 0;
            for(j = 2; j < prime; j++){
                if(prime % j == 0){
                    n[0] = prime;
                    count++;
                    wait(NULL);
                }
            }
            if(count == 0){
                printf("%d Is a prime number!\n", n[0]);
                shmdt(n);
            }
            else{
                printf("%d Not a prime number!\n", n[0]);
                shmdt(n);
            }
        }
    }
}

A: You only write to the shared memory in the event that a number is not prime
if(prime % j == 0){
    n[0] = prime;

when count is incremented (possibly repeatedly).
Place n[0] = prime somewhere outside the loop, so both branches that test count can access the integer via the shared memory.
Or just print prime directly, seeing as both the shared memory and fork serve no practical purpose in this program. The child process does nothing except immediately exit. The shared memory is just a copy of existing data.
Note, you are allocating 2 * sizeof (float) for a single int.
Do not forget to remove shared memory segments from the system with shmctl, and check the return values of all shm* functions for failure.


text:
Q: Default install of vue-cli-plugin-cordova will not run on ios simulator The steps outlined include
vue create my-app
vue add cordova
npm run cordova-prepare
npm run cordova-serve-browser

This works OK
npm run cordova-serve-ios

Many sites recommend variations changing this
new Vue({
    el:'#app',

    mounted:{
       alert("Vue is running");
    }
})

To this
const app = new Vue({
    el:'#app',

    methods:{
        init:function() {
            alert("Vue is running");
        }
    }
})

document.addEventListener('deviceready', app.init);

My site still come up blank on IOS simulator. FYI: Android does not have this problem.

A: While it is important to get
document.addEventListener('deviceready', app.init);

working right, this issue turned out to be that the ios simulator wanted to use a secure connection the the generated js files. It never even loaded in anything related to VueJS.
I had to change vue.config.js from
module.exports = {
  publicPath: '',
  pluginOptions: {
    cordovaPath: 'src-cordova'
  }
}

To
module.exports = {
  publicPath: '',
  pluginOptions: {
    cordovaPath: 'src-cordova'
  },
  devServer: {
    https: false
  }
}

Credit needs to go to: https://github.com/m0dch3n/vue-cli-plugin-cordova/issues/85

A: Step 2 from This article shows how to add cordova using vue cli

Integrate Cordova into Vue Cli, you can install the cli integration plugin separately with npm install vue-cli-plugin-cordova but by adding Cordova to Vue, vue-cli-plugin-cordova is installed in the process.


text:
Q: While cloning ohmyzh in the terminal, it says, "file not found." Why?
Which is:
 <machine>:~ techmick$ $ sh -c "$(curl -fsSL https://...)"
 bash: $: command not found

There seems to be an error.
Not sure why. What could possibly be wrong?

A: Make sure you don't have copied the $ in front of the command.
It is a shell prompt maker, and should not be part of it.
You should only copy and execute:
sh -c ...

Not:
$ sh -c ...


text:
Q: Which port should I be using when using express on cPanel? I've been trying to use nodeJS on cPanel, but I can only seem to access pages sent via 'vanilla' nodeJS.
The default app.js file works fine and displays the message in the browser:
var http = require('http');
var server = http.createServer(function(req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    var message = 'It works!\n',
        version = 'NodeJS ' + process.versions.node + '\n',
        response = [message, version].join('\n');
    res.end(response);
});
server.listen();

However, simple express code like this doesn't work:
var app = require('express')();
var http = require('http').createServer(app);

app.get('/', (req, res) => {
  res.send('Hello world');
});

const port = process.env.PORT || 3000;
http.listen(port, () => console.log(`listening on port ${port}`));

The server will log that it's listening, but going to the same page as before (and adding :3000) results in a 404.
The port is also falling back to 3000, so process.env.PORT isn't set. This makes me think it could be a port issue.
I've tried redirecting the port in a .htaccess file, with no luck.
Does anyone know why the standard express code isn't working/what port I'm supposed to use?

A: You may need to configure the port through .htaccess.
RewriteEngine On
RewriteRule ^$ http://127.0.0.1:XXXXX/ [P,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ http://127.0.0.1:XXXXX/$1 [P,L]

where XXXX is your desired port.


text:
Q: Reshaping Data with Multiple Sets of Column Variables I am trying to reshape some of my data and haven't had any luck with the reshape2 package.  Nothing I've tried is quite what I'm looking for given my data.
I have a data.frame that looks like this (where name1 corresponds to age1, and name2 corresponds to age2, etc):
city <- c("New York", "Philadelphia", "Chicago")
state <- c("NY", "PA", "IL")
name1 <- c("Tim", NA, NA)
name2 <- c("Bob", "Jim", "Bill")
name3 <- c(NA, NA, "Jeff")
age1 <- c(40, NA, NA)
age2 <- c(30, 29, 34)
age3 <- c(NA, NA, 27)

df <- data.frame(city, state, name1, name2, name3, age1, age2, age3)

          city state name1 name2 name3 age1 age2 age3
1     New York    NY   Tim   Bob  <NA>   40   30   NA
2 Philadelphia    PA  <NA>   Jim  <NA>   NA   29   NA
3      Chicago    IL  <NA>  Bill  Jeff   NA   34   27

In my actual data set, I have about 50 "name" and "age" variables each.
Ultimately, I'm aiming for 4 variables:  city, state, name, age.  I also don't want the NA's in my finished data set.  So what I'm looking to achieve is this:
          city state name age
1     New York    NY  Tim  40
2     New York    NY  Bob  30
3 Philadelphia    PA  Jim  29
4      Chicago    IL Bill  34
5      Chicago    IL Jeff  27

Any help would be greatly appreciated!  I've tried the reshape2 and tidyR packages, but no luck yet!
Thanks!

A: melt from "reshape2" presently can't handle this nicely since the "name" and "age" columns are of different types. However, a later version of "data.table" (which will also implement melt) will let you do such a transformation by supplying a list of the measure variables. (See Issue #828, which has the feature launching in V1.9.8 of "data.table".)
In the meantime, other than reshape in base R, you can also try merged.stack from my "splitstackshape" package:
library(splitstackshape)
na.omit(merged.stack(df, var.stubs = c("name", "age"), sep = "var.stubs"))
#            city state .id .t1 name age
# 1:      Chicago    IL   2   2 Bill  34
# 2:      Chicago    IL   3   3 Jeff  27
# 3:     New York    NY   1   1  Tim  40
# 4:     New York    NY   2   2  Bob  30
# 5: Philadelphia    PA   2   2  Jim  29

sep = "var.stubs" is a way of saying that there is no separator between the variable stub and the "time" of measurement.
If you also wanted to drop the unnecessary columns, you can compound that into the previous statement (or use subset as @MrFlick did).
na.omit(
  merged.stack(df, var.stubs = c("name", "age"),
               sep = "var.stubs")[, c(
                 "city", "state", "name", "age"), with = FALSE])
#            city state name age
# 1:      Chicago    IL Bill  34
# 2:      Chicago    IL Jeff  27
# 3:     New York    NY  Tim  40
# 4:     New York    NY  Bob  30
# 5: Philadelphia    PA  Jim  29

A: Just using base R functions, you can do
subset(reshape(df, list(paste0("name", 1:3), paste0("age", 1:3)),
    v.names=c("name","age"),
    direction="long"), !is.na(name), select=-c(time, id))

to get
            city state name age
1.1     New York    NY  Tim  40
1.2     New York    NY  Bob  30
2.2 Philadelphia    PA  Jim  29
3.2      Chicago    IL Bill  34
3.3      Chicago    IL Jeff  27


text:
Q: Before-filter for all POST requests in Sinatra? Is there a way to create a "before" filter to capture and pre-process all POST requests in Sinatra?

A: I came up with this:
before do
    if request.request_method == "POST"
        puts "pre-process POST"
    end
end

... but if anyone knows a better way, please share.

A: One way of doing this would be to create a custom condition to use in the filter:
set(:method) do |method|
  method = method.to_s.upcase
  condition { request.request_method == method }
end

before :method => :post do
  puts "pre-process POST"
end

A: Your solution is fully valid.
I would do it like this:
before do
  next unless request.post?
  puts "post it is!"
end

Or, you can also use a catch-all post route that then hands on the request (needs to be first post route):
post '*' do
  puts "post it is!"
  pass
end

A: +1 on matt's answer above... I ended up expanding it to include support for one or many methods like so:
set :method do |*methods|
    methods = methods.map { |m| m.to_s.upcase }
    condition { methods.include?(request.request_method) }
end

before method: [:post, :patch] do
    # something
end


text:
Q: Fixing quote error in invalid XML A remote service generates invalid XML with attribute values without quotation marks. Example:
<abc invalid=105 valid="105">

In PHP, how can I patch up such errors in the output? Just passing it to SimpleXML results in an error.
Thanks.

A: You are looking for tidy:
$input = '<abc invalid=105 valid="105">';
$tidy = new tidy();
$config = array('output-xml' => true);
$cleanXML = $tidy->repairString($input, $config);


text:
Q: Parse JSON arrays using OPENJSON to table I am confused how to shred my JSON data into a table because is not formatted with names for the arrays
The actual JSON file is much bigger (19K lines) so I only pulled a small portion of it out (the first two of top level and a few from within those.
DECLARE @txt1 varchar(max) = '{ "Rv0005": { "p.Glu540Asp": { "annotations": [ { "type": "drug", "drug": "moxifloxacin", "literature": "10.1128/AAC.00825-17;10.1128/JCM.06860-11", "confers": "resistance" } ], "genome_positions": [ 6857, 6858, 6859 ] }, "p.Ala504Thr": { "annotations": [ { "type": "drug", "drug": "ciprofloxacin", "confers": "resistance" }, { "type": "drug", "drug": "fluoroquinolones", "confers": "resistance" }, { "type": "drug", "drug": "levofloxacin", "confers": "resistance" }, { "type": "drug", "drug": "moxifloxacin", "confers": "resistance" }, { "type": "drug", "drug": "ofloxacin", "confers": "resistance" } ], "genome_positions": [ 6749, 6750, 6751 ] }, "p.Ala504Val": { "annotations": [ { "type": "drug", "drug": "ciprofloxacin", "confers": "resistance" }, { "type": "drug", "drug": "fluoroquinolones", "confers": "resistance" }, { "type": "drug", "drug": "levofloxacin", "confers": "resistance" }, { "type": "drug", "drug": "moxifloxacin", "confers": "resistance" }, { "type": "drug", "drug": "ofloxacin", "confers": "resistance" } ], "genome_positions": [ 6749, 6750, 6751 ] } }, "Rv2043c": { "p.Thr100Ile": { "annotations": [ { "type": "drug", "drug": "pyrazinamide", "literature": "10.1128/JCM.01214-17", "confers": "resistance" } ], "genome_positions": [ 2288942, 2288943, 2288944 ] }, "p.Thr160Ala": { "annotations": [ { "type": "drug", "drug": "pyrazinamide", "literature": "10.1128/JCM.01214-17", "confers": "resistance" } ], "genome_positions": [ 2288762, 2288763, 2288764 ] }, "c.101_102insT": { "annotations": [ { "type": "drug", "drug": "pyrazinamide", "confers": "resistance" } ], "genome_positions": [ 2289140, 2289141 ] } } }'

SELECT * FROM OPENJSON(@txt1)

The top level is a gene and this is just the data from two genes (Rv0005 = gene 1, Rv2043c = gene 2).  Each gene can have multiple mutations (e.g. Rv0005 has a mutation at p.Glu540Asp and p.Ala504Thr) and each of those mutations have some data associated with it (literature, resistance, genomic positions, etc.). I know I can parse portions of the JSON and JSON array out via
SELECT * FROM OPENJSON(@txt1)
SELECT * FROM OPENJSON(@txt1, '$.Rv0005."p.Glu540Asp".genome_positions')

But I don't know how to shred the whole thing out without knowing what the keys/values are. In particular there are 35 unique genes (the top of the JSON tree) and each of the mutations are named under them but are unique (e.g. p.Glu540Asp, etc).
Ultimately I'd either like to pull the data into multiple normalized tables but honestly one big table would be fine like this
CREATE TABLE #Muts (gene varchar(max), mutations varchar(max), annotation_type varchar(max), annotation_drug varchar(max), annotation_literature varchar(max), annotation_confers  varchar(max), genome_positions int )

and the data for the first couple of values would look like this (notice that some mutations confer resistance to multiple drugs)

gene
mutations
annotation_type
annotation_drug
annotation_literature
annotation_confers
genome_positions

Rv0005
p.Glu540Asp
drug
moxifloxacin
10.1128/AAC.00825-17;10.1128/JCM.06860-11
resistance
6857

Rv0005
p.Glu540Asp
drug
moxifloxacin
10.1128/AAC.00825-17;10.1128/JCM.06860-11
resistance
6858

Rv0005
p.Glu540Asp
drug
moxifloxacin
10.1128/AAC.00825-17;10.1128/JCM.06860-11
resistance
6859

Rv0005
p.Ala504Thr
drug
ciprofloxacin
10.1128/AAC.00825-17;10.1128/JCM.06860-11
resistance
6849

Rv0005
p.Ala504Thr
drug
fluoroquinolones
10.1128/AAC.00825-17;10.1128/JCM.06860-11
resistance
6849

Rv0005
p.Ala504Thr
drug
levofloxacin
10.1128/AAC.00825-17;10.1128/JCM.06860-11
resistance
6849

Rv0005
p.Ala504Thr
drug
moxifloxacin
10.1128/AAC.00825-17;10.1128/JCM.06860-11
resistance
6849

Rv0005
p.Ala504Thr
drug
ofloxacin
10.1128/AAC.00825-17;10.1128/JCM.06860-11
resistance
6849

Rv0005
p.Ala504Thr
drug
ciprofloxacin
10.1128/AAC.00825-17;10.1128/JCM.06860-11
resistance
6850

Rv0005
p.Ala504Thr
drug
fluoroquinolones
10.1128/AAC.00825-17;10.1128/JCM.06860-11
resistance
6850

Rv0005
p.Ala504Thr
drug
levofloxacin
10.1128/AAC.00825-17;10.1128/JCM.06860-11
resistance
6850

Rv0005
p.Ala504Thr
drug
moxifloxacin
10.1128/AAC.00825-17;10.1128/JCM.06860-11
resistance
6850

Rv0005
p.Ala504Thr
drug
ofloxacin
10.1128/AAC.00825-17;10.1128/JCM.06860-11
resistance
6850

Rv0005
p.Ala504Thr
drug
ciprofloxacin
10.1128/AAC.00825-17;10.1128/JCM.06860-11
resistance
6851

Rv0005
p.Ala504Thr
drug
fluoroquinolones
10.1128/AAC.00825-17;10.1128/JCM.06860-11
resistance
6851

Rv0005
p.Ala504Thr
drug
levofloxacin
10.1128/AAC.00825-17;10.1128/JCM.06860-11
resistance
6851

Rv0005
p.Ala504Thr
drug
moxifloxacin
10.1128/AAC.00825-17;10.1128/JCM.06860-11
resistance
6851

Rv0005
p.Ala504Thr
drug
ofloxacin
10.1128/AAC.00825-17;10.1128/JCM.06860-11
resistance
6851

A: You have to use CROSS APPLY with OPENJSON when you want to "pivot" a JSON array to a tabular table.
The following query return the expected result:
SELECT a.[key] as gene, b.[key] as mutations, c.*, d.value as genome_positions
FROM OPENJSON(@txt1) a
CROSS APPLY OPENJSON(a.value) b
CROSS APPLY OPENJSON(b.value,'$.annotations')
WITH (
    annotation_type nvarchar(100) '$.type'
    , annotation_drug nvarchar(100) '$.drug'
    , annotation_literature nvarchar(100) '$.literature'
    , annotation_confers nvarchar(100) '$.confers'
) c
CROSS APPLY OPENJSON(b.value,'$.genome_positions') d

Result:

db<>fiddle

A: Please try the following solution.
SQL
DECLARE @json NVARCHAR(MAX) =
N'{
    "Rv0005": {
        "p.Glu540Asp": {
            "annotations": [
                {
                    "type": "drug",
                    "drug": "moxifloxacin",
                    "literature": "10.1128/AAC.00825-17;10.1128/JCM.06860-11",
                    "confers": "resistance"
                }
            ],
            "genome_positions": [
                6857,
                6858,
                6859
            ]
        },
        "p.Ala504Thr": {
            "annotations": [
                {
                    "type": "drug",
                    "drug": "ciprofloxacin",
                    "confers": "resistance"
                },
                {
                    "type": "drug",
                    "drug": "fluoroquinolones",
                    "confers": "resistance"
                },
                {
                    "type": "drug",
                    "drug": "levofloxacin",
                    "confers": "resistance"
                },
                {
                    "type": "drug",
                    "drug": "moxifloxacin",
                    "confers": "resistance"
                },
                {
                    "type": "drug",
                    "drug": "ofloxacin",
                    "confers": "resistance"
                }
            ],
            "genome_positions": [
                6749,
                6750,
                6751
            ]
        },
        "p.Ala504Val": {
            "annotations": [
                {
                    "type": "drug",
                    "drug": "ciprofloxacin",
                    "confers": "resistance"
                },
                {
                    "type": "drug",
                    "drug": "fluoroquinolones",
                    "confers": "resistance"
                },
                {
                    "type": "drug",
                    "drug": "levofloxacin",
                    "confers": "resistance"
                },
                {
                    "type": "drug",
                    "drug": "moxifloxacin",
                    "confers": "resistance"
                },
                {
                    "type": "drug",
                    "drug": "ofloxacin",
                    "confers": "resistance"
                }
            ],
            "genome_positions": [
                6749,
                6750,
                6751
            ]
        }
    },
    "Rv2043c": {
        "p.Thr100Ile": {
            "annotations": [
                {
                    "type": "drug",
                    "drug": "pyrazinamide",
                    "literature": "10.1128/JCM.01214-17",
                    "confers": "resistance"
                }
            ],
            "genome_positions": [
                2288942,
                2288943,
                2288944
            ]
        },
        "p.Thr160Ala": {
            "annotations": [
                {
                    "type": "drug",
                    "drug": "pyrazinamide",
                    "literature": "10.1128/JCM.01214-17",
                    "confers": "resistance"
                }
            ],
            "genome_positions": [
                2288762,
                2288763,
                2288764
            ]
        },
        "c.101_102insT": {
            "annotations": [
                {
                    "type": "drug",
                    "drug": "pyrazinamide",
                    "confers": "resistance"
                }
            ],
            "genome_positions": [
                2289140,
                2289141
            ]
        }
    }
}';

-- test if it is a legit JSON
SELECT ISJSON(@json) AS Result;

SELECT genes.[Key] AS gene
    , mutations.[Key] AS mutation
    , annotations.*
    , JSON_VALUE(mutations.value, '$.genome_positions[0]') as [gen_pos1]
    , JSON_VALUE(mutations.value, '$.genome_positions[1]') as [gen_pos2]
    , JSON_VALUE(mutations.value, '$.genome_positions[2]') as [gen_pos3]
FROM OPENJSON (@json) AS genes
CROSS APPLY OPENJSON(genes.value) AS mutations
CROSS APPLY OPENJSON(mutations.value, '$.annotations')
WITH
(
    [type] VARCHAR(20)              '$.type'
    , [drug] VARCHAR(20)            '$.drug'
    , [literature] VARCHAR(200)     '$.literature'
    , [confers] VARCHAR(20)         '$.confers'
) AS annotations

Output
+---------+---------------+------+------------------+-------------------------------------------+------------+----------+----------+----------+
|  gene   |   mutation    | type |       drug       |                literature                 |  confers   | gen_pos1 | gen_pos2 | gen_pos3 |
+---------+---------------+------+------------------+-------------------------------------------+------------+----------+----------+----------+
| Rv0005  | p.Glu540Asp   | drug | moxifloxacin     | 10.1128/AAC.00825-17;10.1128/JCM.06860-11 | resistance |     6857 |     6858 | 6859     |
| Rv0005  | p.Ala504Thr   | drug | ciprofloxacin    | NULL                                      | resistance |     6749 |     6750 | 6751     |
| Rv0005  | p.Ala504Thr   | drug | fluoroquinolones | NULL                                      | resistance |     6749 |     6750 | 6751     |
| Rv0005  | p.Ala504Thr   | drug | levofloxacin     | NULL                                      | resistance |     6749 |     6750 | 6751     |
| Rv0005  | p.Ala504Thr   | drug | moxifloxacin     | NULL                                      | resistance |     6749 |     6750 | 6751     |
| Rv0005  | p.Ala504Thr   | drug | ofloxacin        | NULL                                      | resistance |     6749 |     6750 | 6751     |
| Rv0005  | p.Ala504Val   | drug | ciprofloxacin    | NULL                                      | resistance |     6749 |     6750 | 6751     |
| Rv0005  | p.Ala504Val   | drug | fluoroquinolones | NULL                                      | resistance |     6749 |     6750 | 6751     |
| Rv0005  | p.Ala504Val   | drug | levofloxacin     | NULL                                      | resistance |     6749 |     6750 | 6751     |
| Rv0005  | p.Ala504Val   | drug | moxifloxacin     | NULL                                      | resistance |     6749 |     6750 | 6751     |
| Rv0005  | p.Ala504Val   | drug | ofloxacin        | NULL                                      | resistance |     6749 |     6750 | 6751     |
| Rv2043c | p.Thr100Ile   | drug | pyrazinamide     | 10.1128/JCM.01214-17                      | resistance |  2288942 |  2288943 | 2288944  |
| Rv2043c | p.Thr160Ala   | drug | pyrazinamide     | 10.1128/JCM.01214-17                      | resistance |  2288762 |  2288763 | 2288764  |
| Rv2043c | c.101_102insT | drug | pyrazinamide     | NULL                                      | resistance |  2289140 |  2289141 | NULL     |
+---------+---------------+------+------------------+-------------------------------------------+------------+----------+----------+----------+

A: Using a temporary table will make it easier to pivot the data from the unfolded json.

DECLARE @txt1 varchar(max) = '{...}'

IF OBJECT_ID('tempdb..#tmpJsonUnfolded', 'U') IS NOT NULL
DROP TABLE #tmpJsonUnfolded;

SELECT
  lvl1.[key] as gene
, lvl2.[key] as mutations
, lvl3.[key] as data_class
, lvl4.[key] as num
, lvl5.[key] as col
, case
  when lvl3.[key] = 'genome_positions'
  then lvl4.[value]
  when lvl3.[key] = 'annotations'
  then lvl5.[value]
  end as [value]
--, lvl4.[value] as value4
--, lvl5.[value] as value5
INTO #tmpJsonUnfolded
FROM OPENJSON(@txt1) lvl1
CROSS APPLY OPENJSON(lvl1.value) lvl2
CROSS APPLY OPENJSON(lvl2.value) lvl3
CROSS APPLY OPENJSON(lvl3.value) lvl4
OUTER APPLY (
  SELECT *
  FROM OPENJSON(lvl4.value)
  WHERE lvl3.[key] = 'annotations'
) lvl5;

select
  gene
, mutations
, [type] as annotation_type
, [num] as annotation_num
, [drug] as annotation_drug
, [literature] as annotation_literature
, [confers] as annotation_confers
, [genome_positions]
from (
  select
    gene
  , mutations
  , num
  , [col]
  , [value]
  from #tmpJsonUnfolded
  where data_class = 'annotations'

  union all

  select
    gene
  , mutations
  , 0
  , data_class as [col]
  , string_agg([value], ', ') as [value]
  from #tmpJsonUnfolded
  where data_class = 'genome_positions'
  group by gene, mutations, data_class
) src
pivot (
  max([value])
  for [col] in ([type], [drug], [literature], [confers], [genome_positions])
) pvt

gene    | mutations     | annotation_type | annotation_num | annotation_drug  | annotation_literature                     | annotation_confers | genome_positions
:------ | :------------ | :-------------- | -------------: | :--------------- | :---------------------------------------- | :----------------- | :------------------------
Rv0005  | p.Ala504Thr   | drug            |              0 | ciprofloxacin    | null                                      | resistance         | 6749, 6750, 6751
Rv0005  | p.Ala504Thr   | drug            |              1 | fluoroquinolones | null                                      | resistance         | null
Rv0005  | p.Ala504Thr   | drug            |              2 | levofloxacin     | null                                      | resistance         | null
Rv0005  | p.Ala504Thr   | drug            |              3 | moxifloxacin     | null                                      | resistance         | null
Rv0005  | p.Ala504Thr   | drug            |              4 | ofloxacin        | null                                      | resistance         | null
Rv0005  | p.Ala504Val   | drug            |              0 | ciprofloxacin    | null                                      | resistance         | 6749, 6750, 6751
Rv0005  | p.Ala504Val   | drug            |              1 | fluoroquinolones | null                                      | resistance         | null
Rv0005  | p.Ala504Val   | drug            |              2 | levofloxacin     | null                                      | resistance         | null
Rv0005  | p.Ala504Val   | drug            |              3 | moxifloxacin     | null                                      | resistance         | null
Rv0005  | p.Ala504Val   | drug            |              4 | ofloxacin        | null                                      | resistance         | null
Rv0005  | p.Glu540Asp   | drug            |              0 | moxifloxacin     | 10.1128/AAC.00825-17;10.1128/JCM.06860-11 | resistance         | 6857, 6858, 6859
Rv2043c | c.101_102insT | drug            |              0 | pyrazinamide     | null                                      | resistance         | 2289140, 2289141
Rv2043c | p.Thr100Ile   | drug            |              0 | pyrazinamide     | 10.1128/JCM.01214-17                      | resistance         | 2288942, 2288943, 2288944
Rv2043c | p.Thr160Ala   | drug            |              0 | pyrazinamide     | 10.1128/JCM.01214-17                      | resistance         | 2288762, 2288763, 2288764

Demo on db<>fiddle here


text:
Q: how to link php, sql, and Javascript together, I'm doing a log in page, i have javascript doing validations ( checking if field is blank) sql storing the data and php doing what php does (idk).... anyway when I press submit it tells me Cannot POST /login.php
is there away to test it on a website and see if it actually works or is the code completely wrong.
<?php

$server = 'localhost';
$username = 'root';
$passowrd = 'cosc_453';
$dbname = 'login'

if(!empty($_POST['user']))

{ $query = mysql_query("SELECT * FROM UserName where userName ='$_POST[user]' AND pass = '$_POST[pass]'") or die(mysql_error());

$row = mysql_fetch_array($query) or die(mysql_error());

{ $_SESSION['userName'] = $row['pass']; echo "SUCCESSFULLY LOGIN TO USER PROFILE PAGE..."; }

else { echo "SORRY... YOU ENTERD WRONG ID AND PASSWORD... PLEASE RETRY...";
    }
  }
 }

if(isset($_POST['submit']))

{ SignIn();

 } ?>

php external
     function validate(){

   if ( document.getElementById (user).value=="")
      {
       alert ("Please enter your user name");
   }
   else if ( document.getElementById(pass).value=="")
alert("Please enter you password");
 else {
alert("Processing Login........");
}
      }

javscript external
  CREATE TABLE UserName (
 UserNameID int(9) NOT NULL auto_increment,
userName VARCHAR(40) NOT NULL,
 pass VARCHAR(40) NOT NULL,
PRIMARY KEY(UserNameID) );

 INSERT INTO
UserName (userName, pass)
VALUES
 ("cosc" , "453");

sql external
<!DOCTYPE HTML>

<title>Sign-In</title>
<link rel="stylesheet" type="text/css" href="home.css">

<fieldset style="width:30%">
<legend>LOG-IN HERE</legend>

<form method="Post" action="login.php" submit =" validate()">

User:
<input type="text" name="user" size="40">

Password:
<input type="password" name="pass" size="40">

<input id="button" type="submit" name="submit" value="Log-In">

   </form>
  < /fieldset>

A: Your mysql do not have a connection to database. And please stop using mysql, use mysqli instead
<?php

    $con = mysqli_connect("localhost","root","cosc_453","login");

    // Check connection
    if (mysqli_connect_errno())
    {
       echo "Failed to connect to MySQL: " . mysqli_connect_error();
    }

    $sql = "SELECT * FROM UserName WHERE userName ='".$_POST[user]."' AND pass = '".$_POST[pass]."'";
    $result = mysqli_query($conn,$sql);
    $count_result = mysqli_num_rows($result);

    // Login Success URL

    if($count_result  == 1)
    {
        // If you validate the user you may set the user cookies/sessions here
        #setcookie("logged_in", "user_id");
        #$_SESSION["logged_user"] = "user_id";

        $_SESSION["secret_id"] = $row['secret_id'];

        if($row['level'] == 1)
        {
            // Set the redirect url after successful login for admin
            $resp['redirect_url'] = 'admin/';
        }

        else if($row['level'] == 2)
        {
            // Set the redirect url after successful login for user
            $resp['redirect_url'] = 'user/';
        }

    }
    else
    {
         echo "Invalid username or pass";
    }

?>

A: To add onto what Eh Ezani stated, you have an issue in your HTML. Your form attribute reads submit when I believe what you meant is onsubmit. Might want to try something like.
<form method="Post" action="login.php" onsubmit ="return validate()">

     User:
<input type="text" name="user" size="40">

     Password:
<input type="password" name="pass" size="40">

     <input id="button" type="submit" name="submit" value="Log-In">

</form>

Also, "Use MySQLi over the older MySQL functions. The "i" stands for "improved". The list of improvements can be found in the docs.
-credited to
Difference between mysqli and mysql?


text:
Q: Webpack doesn't generate app.bundle.css I have the following webpack file, however, when I run npm run dev the name.bundle.css file doesn't get generated: (no errors either)
const path = require('path');
const webpack = require('webpack');
const ExtractTextPlugin = require('extract-text-webpack-plugin');

module.exports = {
    context: path.resolve(__dirname, './resources/'),
    entry: {
        app: './index.jsx'
    },
    output: {
        filename: '[name].bundle.js',
        path: path.resolve(__dirname, './public/assets/'),
        publicPath: '/assets/'
    },
    module: {
        rules: [
            {
                test: /\.css$/,
                use:  ExtractTextPlugin.extract({
                    use: [{
                        loader: 'css-loader'
                    }],
                }),
            },
            {
              test: /\.jsx|js$/,
              exclude: [/node-modules/],
              use: [
                {
                  loader: "babel-loader",
                  options: { presets: ['react', 'es2015', 'stage-1'] }
                }
              ]
            },
            {
              test: /\.(sass|scss)$/,
              use: ["style-loader", "css-loader", "sass-loader"]
            },
            {
                test: /\.(jpe?g|png|gif|svg)$/i,
                use: ['file-loader?name=[name].[ext]']
            },
            {
                test: /\.(eot|svg|ttf|woff|woff2)$/,
                loader: 'file-loader?name=public/fonts/[name].[ext]'
            }
        ]
    },
    resolve: {
        modules: [
            path.resolve(__dirname, './resources/'),
            'node_modules'
        ]
    },
    plugins: [
        new webpack.optimize.CommonsChunkPlugin({
            name: 'common'
        }),
        new ExtractTextPlugin({
            filename: '[name].bundle.css'
        })
    ]
}

my CSS folder is:
CSS
    - app.scss
    COMPONENTS
        comp1.scss
        comp2.scss

it works this way "import styles from './css/app.scss';" but I would expect this to generate a app.bundle.css:
    new ExtractTextPlugin({
        filename: '[name].bundle.css'
    })

A: You have 2 rules for both css and sass.
I think in your case you only need one:
test: /\.(sass|scss)$/,
use: ExtractTextPlugin.extract({
     use: [{
         loader: "css-loader"
     }, {
         loader: "sass-loader"
     }],
     fallback: "style-loader"
})

and like you said, you should import the scss files in the js files import './css/app.scss'


text:
Q: add an image right after the total in the checkout page @shopify I want to add an image right after the total price at the checkout page, look at the example:

I tried to add the img directly in the checkout.liquid in this section:

but that displays my image at the very bottom of the whole order-summary__section
update: I tried the suggested answer, but it didnt work

A: If you have access to the Checkout.liquid you can add this in with a javascript function just target .order-summary__section--total-lines and insert your image after that element.
You can't add it in as liquid because as you've seen the whole order summary content area is contained in the {{ content_for_order_summary }} tag
      (() => {

        'use strict';

          const selectors = {
            targetTotalLines : '.order-summary__section--total-lines',
          };

          const injectImage = function() {
            let htmlContentToInject = `<img src="https://cdn.shopify.com/s/files/1/0177/9856/666/files/ICON.png?v=1663076456" />`;
            document.querySelector(selectors.targetTotalLines).insertAdjacentHTML('afterend', htmlContentToInject);
          };

          document.addEventListener('DOMContentLoaded', (e) => {
            injectImage();
          });

      })()
    </script> ```

  [1]: https://i.stack.imgur.com/1qcNA.png


text:
Q: Reading 1 GB binary file taking too long in C I'm reading a file where the number of tuples "n_tups" and length of individual tuple or its dimension "d" are inputs. I've allocated the memory as follows,for a two dimensional array "tuple".
When I run the code my computer hangs and I don't know why.
if((fpp = fopen("in2.bin", "rb"))==NULL)
   printf("file in2.bin doesn't exist!");
else
{
 int **tuple;
 unsigned long i;

 tuple = malloc(n_tups * sizeof(int *));

 if(tuple == NULL)
   {
      fprintf(stderr, "out of memory\n");
      return;
   }
 for(i=0;i<n_tups;i++){
        tuple[i]=malloc(d * sizeof(int));
        if(tuple[i] == NULL)
        {
           fprintf(stderr, "out of memory\n");
           return;
         }
  }

 fseek( fpp , 0 , SEEK_SET );
 printf("reading step");
 for(i=0;i<n_tups;i++){
         fread(&tuple[i],4,d,fpp);
         fread(&score[i],8,1,fpp);
    }

 fclose(fpp);
 }

I tried to check if the program ever reaches the "reading step" and it doesn't. Turns out its busy allocating the memory!
I'm passing d=3 n_tups=85013600 and my computer has 4 GBs of RAM.

A: There are two performance problems with the code itself.

*

*You are needlessly using a pointer-to-pointer lookup table even though all dimensions are the same. It would be much better to use a 2D array, so that all data is allocated in adjacent memory. That way the CPU doesn't have to go digging through the RAM for every read of the heap, but can utilize the data cache memory instead.
Like this:
int (*tuple)[d] = malloc( sizeof(int[n_tups][d]) );
...
free(tuple);

*Each call to fread will be expensive. Try to read as large chunks as possible per call. What's optimal in your case, I don't know - it is system-dependent. But calling it for small chunks of data will be ineffective. Especially since a properly-written program will always check the result of every single fread call.
Ideally, assuming you followed my previous advise about using a 2D array, you would only need to do:
result = fread(tuple, sizeof(int[n_tups][d]), 1, fpp);

However, it appears that the file contains unrelated data that you wish to store elsewhere. Consider replacing the two int arrays with a single array of structs instead, so that you can read longer chunks of memory each time. (However, mind struct padding.)
Be aware that reading very large chunks of data from disk might be time-consuming, so consider doing it from a different thread and not from the main (GUI?) thread.


text:
Q: Не получается создать проект C++ в Visual Studio 2017 Когда я пытаюсь создать/открыть проект Visual C++, я получаю такое сообщение:

Была ли у кого-нибудь такая же проблема?

A: Решено с помощью простого обновления пакетов в Visual Studio 2017 Community. Спасибо всем :)


text:
Q: Conflicting declarations in XC8 when using extern struct I have a variable that is a struct, defined in a .c file:
struct {
    int write_cursor;
    int read_cursor;
    message messages[10];
} out_messages = {0, 0};

To make it available in other files I have an .h file with:
extern struct {
    int write_cursor;
    int read_cursor;
    message messages[10];
} out_messages;

This worked with the Microchip C18 compiler. The XC8 compiler gives an error:
communications.c:24: error: type redeclared
communications.c:24: error: conflicting declarations for variable "out_messages" (communications.h:50)

A: The notation isn't correct, you can do:
typedef struct {
    int write_cursor;
    int read_cursor;
    message messages[10];
} Struct_out_messages;

extern Struct_out_messages out_messages;

and in a .c make the initialization.
Struct_out_messages out_messages = {0, 0, {0}};

This compiles in XC16 without any problem, hope it does also on XC8.

A: If you need to access the contents of the struct in multiple files, you could change the declaration in the header file to:
struct out_messages_t {
    int write_cursor;
    int read_cursor;
    message messages[10];
};

extern struct out_messages_t out_messages;

and then in your .c file, define and initialise:
struct out_messages_t out_messages = {0, 0};

(and include the header)


text:
Q: Can't load my js file with js file that bootstrap want me to import for Carousel If I put index.js to the top of the other js file than my js file works but not the carousel functionality, if it I put the index.js in the bottom then the carousel functionality works but not my index.js.... Any thoughts how to fix it.

 alert("I am an alert box!");
h1{

 margin-left:  25%;
 padding-left: 5%;
}
.carousel-item{
 margin-left: 25%;
 margin-top: 10%;
}

body {
    background-color: lightblue;
}
<!DOCTYPE html>

 <title>ChrisDWebAPP</title>
 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">
 <link rel="stylesheet" type="text/css" href="index.css">

Connected To Boot Strap

    Previous

    Next

Thank you...

A: your code

should be

                      ^


text:
Q: Clickhouse: Is it possible to specify OFFSET n in SQL query? I want to skip 1M records in the output. How can I do it?

A: you could try LIMIT 1000000,1
and see documentation https://clickhouse.yandex/docs/en/query_language/select/#limit-clause
and maybe you need side autoincrement atomic counter (i.e. via REDIS INCR command) and insert this counter with your data
and use WHERE id BETWEEN 1000000 AND 1000001


text:
Q: Ubuntu 15.10 And Samba share I just installed Ubuntu 15.10 with mate, I am connected to my home network, but it seems like it's not possible to access Samba shared drive on the network.
I correctly see the network resources but when I try to mount a disk with caja, after a while I get an error message saying "Not-possible to access the disk"
Can someone help me?


text:
Q: how to validate credit cards using jquery.validation creditcard2? I was hoping someone can point me in the right direction. I am looking to use this plugin along with jquery.validation plugin in my forms but from what I see I would need to use a select tag in order for creditcard2 to function correctly.
What I currently have is this:

     You must select a credit card from one of the following.

     <input type="radio" value="1000" id="card_type_1000" name="card_type" style="outline:none; border:none;" />

        <input type="radio" value="1002" id="card_type_1002" name="card_type" style="outline:none; border:none;" />

        <input type="radio" value="1006" id="card_type_1006" name="card_type" style="outline:none; border:none;" />

        <input type="radio" value="1004" id="card_type_1004" name="card_type" style="outline:none; border:none;" />

value = 1000 is "Visa"
value = 1002 is "MasterCard"
value = 1006 is "Discover"
value = 1004 is "AmEx"
The plugin site mentions creating a lookup hash. I don't know how to create one. Also the documentation that is on the site only shows examples using <select></select>. I am using inputs.
How can I get this to work with the set up that I currently have.
any suggestions?

A: A lookup hash would look like
var hash = {
    1000: "Visa",
    1002: "MasterCard",
    1004: "AmEx",
    1006: "Discover"
};

Then you could use the following validation function, of course built into your current setup:
$("#myform").validate({
    rules: {
        cardnum: { // this should be the id of the card number field
            creditcard2: function(){ return hash[$('.ccType > input:checked').val()]; }
        }
    }
});

This rather concise code first looks for all the inputs in your .ccType element. Then it selects the one that is checked (if any) and gets its value. Then the value is pushed through the hash to change it to a value the plugin likes. And... let's hope this works.


text:
Q: How to add a menu bar and a push button in the same UI using Qt? I am trying to program a interface that has a push button and a menu bar using Qt 5.15.
Problem: The main issue is even though a menu bar (menuBar) is instantiated it is not visible in the .ui output window. Also, a push button (quitButton) is instantiated it is visible in the .ui output window. I might be missing something. I am getting a feeling that in Qt either you get a menu bar or a push button widgets but not both. Is it right? Moreover, how can I get both the menu bar and push button in the same .ui window?
This is my QtNotepad.cpp code
#include "qtnotepad.h"

QtNotepad::QtNotepad(QWidget *parent)
    : QWidget(parent)
{
    openAction = new QAction(tr("&Open"), this);
    saveAction = new QAction(tr("&Save"), this);
    exitAction = new QAction(tr("&Exit"), this);

    connect(openAction, SIGNAL(triggered()), this, SLOT(open()));
    connect(saveAction, SIGNAL(triggered()), this, SLOT(save()));
    connect(exitAction, SIGNAL(triggered()), this, SLOT(quit()));

    QMenuBar* menuBar = new QMenuBar(nullptr);

    fileMenu = menuBar->addMenu(tr("&File"));

    fileMenu->addAction(openAction);
    fileMenu->addAction(saveAction);
    fileMenu->addSeparator();
    fileMenu->addAction(exitAction);

    textEdit = new QTextEdit;
    quitButton = new QPushButton(tr("Quit"));

    connect(quitButton, SIGNAL(clicked()), this, SLOT(quit()));

    QHBoxLayout* layout = new QHBoxLayout;
    layout->addWidget(textEdit);
    layout->addWidget(quitButton);

    setLayout(layout);

    setWindowTitle(tr("Notepad"));

}

void QtNotepad::open()
{
    QString fileName = QFileDialog::getOpenFileName(this, tr("Open File"), "", tr("Text Files (*.txt);; C++ Files(*.cpp *.h);;.dat Files(*.dat)"));

    if (fileName != "")
    {
        QFile file(fileName);
        if (!file.open(QIODevice::ReadOnly))
        {
            QMessageBox::critical(this, tr("Error"), tr("Could not open file"));
            return;
        }
        QTextStream in(&file);
        textEdit->setText(in.readAll());
        file.close();
    }
}

void QtNotepad::save()
{
    QString fileName = QFileDialog::getSaveFileName(this, tr("Save File"), ""), tr("Text Files (*.txt);;C++ Files (*.cpp *.h)");

    if (fileName != "")
    {
        QFile file(fileName);
        if (!file.open(QIODevice::WriteOnly))
        {
            //error message
        }
        else
        {
            QTextStream stream(&file);
            stream << textEdit->toPlainText();
            stream.flush();
            file.close();
        }
    }
}

void QtNotepad::quit()
{
    QMessageBox messageBox;
    messageBox.setWindowTitle(tr("Notepad"));
    messageBox.setText(tr("Do you really want to quit?"));
    messageBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
    messageBox.setDefaultButton(QMessageBox::No);
    if (messageBox.exec() == QMessageBox::Yes)
        qApp->quit();
}

This is my QtNotepad.h code
#include <QtWidgets/QMainWindow>
#include "ui_qtnotepad.h"
#include<qtextedit.h>
#include<qpushbutton.h>
#include<qlayout.h>
#include<qobject.h>
#include<qmessagebox.h>
#include<qwidget.h>
#include<qdialog.h>
#include<qfiledialog.h>
#include<qtextstream.h>
#include<qmenubar.h>

class QtNotepad : public QWidget
{
    Q_OBJECT

public:
    QtNotepad(QWidget *parent = Q_NULLPTR);

private slots:
    void quit();
    void open();
    void save();

private:
    Ui::QtNotepadClass ui;
    QTextEdit* textEdit;
    QPushButton* quitButton;
    QAction* openAction;
    QAction* saveAction;
    QAction* exitAction;

    QMenu* fileMenu;

};

This is my main function code.
#include "qtnotepad.h"
#include <QtWidgets/QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    QtNotepad  window;
    window.show();
    return a.exec();
}

This is my .ui output window.

A: QMenuBar* menuBar = new QMenuBar(nullptr);

This line may be the problem. There is one way to approach this -

*

*Add a QMenuBar menuBar as a member of the class QtNotepad

*Initialise the menu bar in constructor with parent as this, not nullptr
Since the menuBar is initialised with a nullptr parent, The Window will not take ownership of the menuBar.


text:
Q: Why are the meanings of .. and ... flipped between git diff and git log? Take for instance an example repo with this history graph:
$ git log --all --graph --oneline
* 691d454 (HEAD -> branch-b) branch-b-2
* c3bd488 branch-b
| * f5756ff (branch-a) branch-a-2
| * de00ec4 branch-a
|/
* 5ad3b15 (root) root

Now, compare git diff branch-a..branch-b
diff --git a/f b/f
index af31a64..e7791f3 100644
--- a/f
+++ b/f
@@ -1 +1 @@
-branch-a-2
+branch-b-2

with git diff branch-a...branch-b
diff --git a/f b/f
index d8649da..e7791f3 100644
--- a/f
+++ b/f
@@ -1 +1 @@
-root
+branch-b-2

with git log --oneline branch-a..branch-b
691d454 (HEAD -> branch-b) branch-b-2
c3bd488 branch-b

with git log --oneline branch-a...branch-b
691d454 (HEAD -> branch-b) branch-b-2
c3bd488 branch-b
de00ec4 branch-a
f5756ff (branch-a) branch-a-2

Basically, we're seeing this:
|------+--------------------------------------+--------------------------------------|
|      | branch-a..branch-b                   | branch-a...branch-b                  |
|------+--------------------------------------+--------------------------------------|
| log  | root -> branch-b                     | branch-a -> branch-b                 |
|      | (root, branch-b]                     | [branch-a, branch-b]                 |
|      | changes introduced in branch-b       | difference from branch-a to branch-b |
|------+--------------------------------------+--------------------------------------|
| diff | branch-a -> branch-b                 | root -> branch-b                     |
|      | [branch-a, branch-b]                 | (root, branch-b]                     |
|      | difference from branch-a to branch-b | changes introduced in branch-b       |
|------+--------------------------------------+--------------------------------------|

What this implies is that if you want to see the changes done in a branch that forks off from master as a list of commits, git log master..branch will show you. However, if you want to see those same changes as a diff that combines those commits, you'll have to switch to ... like so, git diff master...branch. This is something that I find myself doing very frequently, and so is a minor annoyance I've been wondering about for a while.
Is there a design reason? It seems to only be an inconsistency.
EDIT: To clarify, I know what .. and ... translate to in both diff and log. My question could be rephrased as: Wouldn't it make more sense for either to be flipped so they'd be consistent with one another? For example, if git diff branch-a..branch-b meant git diff $(git merge-base branch-a branch-b) branch-b and git diff branch-a...branch-b meant git diff branch-a branch-b, then diff would be consistent with log. So, why was this not the case?
EDIT 2: In the paragraph below the table, I gave a practical example of how git diff master...branch is the analogous of git log master..branch. For the other case, if you want to get the listing of commits that separates master from branch (i.e. the commits that represent the difference between the 2), you'd use git log master...branch, and if you want the diff that represents that same difference, you'd use git diff master..branch.
EDIT 3: I tried to make the table more clear. The use of brackets and parenthesis is math interval notation.
EDIT 4: Transposed the table so it fits better.

A: They're not (flipped).  Rather, .. in git diff has the special meaning that it has no meaning, and ... in git diff has a special meaning unique to git diff, not found in any other Git command.
Your particular input graph is ... was, before the edit :-) ... too small to show the real difference.  If you had more commits after the two branches diverged, you could see more.
Long
Let's look at git diff first because it is simpler.  What git diff does, in these particular cases—there are special cases for combined diffs but they do not apply here; and we can diff a commit vs our work-tree or vs our index, which we're not doing here—is pick two individual commits and compare them.
To name the two commits to compare, I prefer to write:
git diff <commit1> <commit2>

However, you can, if you prefer, write:
git diff <commit1>..<commit2>

These mean exactly the same thing, always.1  Git just pretends you did not write the .. after all.  This is true whether you use hash IDs here, or branch names like master, or remote-tracking names like origin/master, or any mix of these.
Note that the order of the two commit name-or-hash-IDs matters: the output of git diff is a set of instructions, telling you how to change the first commit so that you would get the second commit, if you followed all the instructions.
If you write:
git diff <commit1>...<commit2>

Git will still compare two commits:2 Git will find the merge base between the two given commits, then compare that merge base commit to the second listed commit.  That is, this is the same as the shell-style expansion:
git diff $(git merge-base <commit1> <commit2>) commit2

Here, as before, the order matters: the merge base is the same,3 regardless of the order of the two commits, but that merge base is compared with the second-listed commit.

1Well, almost always!  There are some corner cases you can tickle if you list a third commit on the command line, where it acts like you used the three-dot syntax.  I would argue that these are a bug in git diff, although it's always possible that someone has come to depend on them.
2There's another corner case here, and it definitely is a bug: if there is more than one merge base, git diff produces a combined diff.  That's not the intent of the three-dot syntax, which is why it's a bug.
3This assumes you do not tickle the bug in footnote 2.  When there is a single merge base for multiple commits, the order is irrelevant, but when there are multiple merge bases, the order of the inputs may affect the order of the outputs.

For git log and most other Git commands, though, .. and ... have quite a different meaning.  As you no doubt know by now, <commit1>..<commit2> is shorthand for <commit2> ^<commit1>.  We can see this with git rev-parse:
$ git rev-parse master..origin/maint
468165c1d8a442994a825f3684528361727cd8c0
^ccdcbd54c4475c2238b310f7113ab3075b5abc9c

Here origin/maint translates to the first (un-negated) hash ID, and master translates to the second (negated) one.  These tell Git that, as it walks the commit graph, it should select commits that are reachable from 468165c1d8a442994a825f3684528361727cd8c0 (the positive reference) while rejecting commits that are reachable from ccdcbd54c4475c2238b310f7113ab3075b5abc9c (the negative reference).  That means all such commits, which may be many commits.  A command like git log, walking through the commit graph, will show all selected commits.
The three-dot notation is trickier, but translates internally into the same kind of positive and negative reference:
$ git rev-parse master...origin/maint
468165c1d8a442994a825f3684528361727cd8c0
ccdcbd54c4475c2238b310f7113ab3075b5abc9c
^468165c1d8a442994a825f3684528361727cd8c0

Here, the two positive references are the hash IDs associated with origin/maint and master as before, and the negative reference is a result of the point(s) where the subgraphs selected by these start-points rejoin.  There is only one such point in this particular case—so this matches the output from git merge-base as we will see in a moment—though some sub-graphs that diverge and merge in complex ways can have multiple such points:
$ git merge-base master origin/maint
468165c1d8a442994a825f3684528361727cd8c0

(It's these same kinds of complex graphs that can result in multiple merge bases, though the code that implements ... is simpler than the code that finds merge bases.)
If you have a graph like this one:
     C--D   <-- br1
    /
A--B
    \
     E--F   <-- br2

the three-dot syntax br1...br2 selects commits C-D and E-F for commands that walk the graph like git log, but selects commits B and F respectively for git diff (and only for git diff).  The two-dot syntax br1..br2 selects commits E-F for git log and the like, and compares commits D and F respectively for git diff (and only for git diff).


text:
Q: Inconsistently getting net::ERR_TIMED_OUT I'm hosting a webpage on my server via Apache. From there i'm using jquery.ajax() to request data.
function get_trials() {
$.ajax(
{method:"POST",
url:"https://annotatie01.io.tudelft.nl:80/get_trial",
success: function(response) {

    data = response;
    data_holder = data;
    trials = {};
    for(count=0;count < data_holder['trials'].length;count++)
            {trials[count] = {'meta':{}};
             trials[count]['meta'] = {'url':data_holder['trials'][count][0]};}
    }
})

}
On the server side i have Flask running.
@app.route('/send_data',methods=['POST'])
def send_data(): # is actually receiving data here
    data = request.json['data']
    print(data)
    write_data_to_database(data)
    return jsonify(reply = 'Ok')

My code appears to be working properly most of the time. Yet, every now and then, for reasons I've not been able to pin-point my server returns ERR_TIMED_OUT. When it does, it'll keep doing so consistently for a while, after which it'll 'work' again. It seems to be somewhat related to using get_trials() from different machines, as it appears to be more likely to return a time-out when calling from different machines. Yet, this is also not consistent, since at other times i can successfully call it from 3 different machines.
When it returns the time-out, the post request is never received by the server.
How can i trace and solve this error?


text:
Q: Azure Resource Manager Site-to-site VPN Data In 0B I have a few questions regarding establishing Site-to-Site VPN connection to my local network and Azure Virtual Network (Resource Manager)
To begin, I'll give you some context. I had an environment before (classic), and it was working just fine. I decided to migrate everything to Resource Manager; the connection is up, but my local network is not sending data to Azure network.
The only thing I changed in my previous VPN is the IP address on Phase 1 settings. I used the same shared key.
The status is up, but the incoming data to the virtual network is 0B. Am I missing something?
Cheers


text:
Q: Full Build, Incremental Build and Deploy within Powerbuilder What is the difference between a Full Build, an Incremental Build and Deploy within Powerbuilder? The only difference I can see is that Deploy allows you to update the PBDs for, well, deployment.

A: Full Build regenerates every object. Incremental Build regenerates changed objects and objects that reference changed objects. (Reality is that incremental is a little more complex than that, but that is the intended idea.) Deploy launches whichever project is selected in the properties for the target, so it can do an incremental or full build, depending on what is defined in the project, plus generate whatever executables are defined by the project.
Good luck,
Terry.

A: I set my projects to Full build.  It seems to be more reliable than incremental.  Full build is very fast even on LARGE projects anyways.  There is not a lot of time savings using incremental build.
Deploy is used when you want to build the project AND run it immediately after the build.


text:
Q: nodejs express- server's get method gets 3 arguments Can you please help me understand the following code? It seems that here the get method receives 3 arguments instead of 2.. What does it do with the object that is given to it as the third argument?
app.get('/query', function(req, res) {
                console.error('we shouldn't be here');
                res.writeHead(500);
                res.end('we shouldn't be here' + req.url);
            },
            {
                id: 'my_id',
                name: 'query',
                usage: 'get query',
                example: 'get query',
                params: {},
                broadcast: true,
                response: { representations : [ 'application/json' ] }
            }
        );

Thanks,
Li

A: This doesn't appear to be correctly written. In Express, a request handler can take a third paramater which is a function (commonly called next() which will be called if the handler decides not to handle the request (thus passing the request down to the next handler you defined). In your example, however, the third parameter is on object rather than a function, and it's not actually being passed to your request handler..
It's possible that you're basing your code on an example that uses a very early, now obsolete, version of Express.