text:
Q: Android Button Can Be Click Once Only I'm creating an on and off app controller for a led which is connected to my arduino microcontroller. Everythings seems to be okay already except for the bottons, both in ON and OFF. It works but it can only be click once. I have read some forums related with my problem and one of it said to remove static from some statements I have but I cannot remove it since there will be errors then.
Here are some of my codes in my MainActivity.java:
//@@@@@@@@@@for the controller
        btn_d1_on = (Button) findViewById(R.id.device1_on);
        btn_d1_off = (Button) findViewById(R.id.device1_off);

//@@@@@@@@@@for the controller
        btn_d1_on.setOnClickListener(new OnClickListener()
        {
            public void onClick(View v)
            {
                //sendData("1");
                //Toast msg = Toast.makeText(getBaseContext(), "The device is now On", Toast.LENGTH_SHORT);
                //msg.show()
                btn_d1_on.setEnabled(false);
                try {
                    sendData("1");
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            }
        });

        //@@@@@@@@@@for the controller
        btn_d1_off.setOnClickListener(new OnClickListener()
        {
            public void onClick(View v)
            {
                //sendData("0");
                //Toast msg = Toast.makeText(getBaseContext(), "The device is now On", Toast.LENGTH_SHORT);
                //msg.show();
                btn_d1_off.setEnabled(false);
                try {
                    sendData("0");
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        });

  private void sendData(String message) throws IOException
  //public void sendData(String message)
  {
      byte[] msgBuffer = message.getBytes();

      Log.d(tagStateCTRL, "...Sending data: " + message + "...");

      //outStream.write(msgBuffer);
      BluetoothCommandService.write(msgBuffer);
  }

While here is my BluetoothCommandService.java where write(byte[] out) was change into public static void write(byte[] out) instead of public void write(byte[] out)...
import java.util.UUID;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
//import android.widget.Button;

public class BluetoothCommandService {

    private final BluetoothAdapter BTAdapter;
    private final Handler bluetoothHandler;
    private static int connectionState;
    private ConnectThread connectThread;
    //private ConnectedThread connectedThread;
    public static ConnectedThread connectedThread;
    //***Added 12/27/13
    private AcceptThread mainAcceptThread;

    //connection states of the Bluetooth
    public static final int stateNothing = 0; //doing nothing
    public static final int stateListen = 1; //listening for incoming connections
    public static final int stateConnecting = 2; //initiating an outgoing connection
    public static final int stateConnected = 3;

    //constants that indicate command to computer
    public static final int exitCMD = -1;
    public static final int VOL_UP = 1;
    public static final int VOL_DOWN = 2;

    private static final boolean D = true;
    private static final String tagState = "BluetoothCommandService";

    //universally unique identifier (UUID)
    //The intent of UUIDs is to enable distributed systems to uniquely identify information without significant central coordination
    //private static final UUID myUUID = UUID.fromString("04c6093b-0000-1000-8000-00805f9b34fb");
     private static final UUID myUUID = UUID.fromString("fa87c0d0-afac-11de-8a39-0800200c9a66");
    // ---------> ************* fa87c0d0-afac-11de-8a39-0800200c9a66  ***************** <-----------------
    //********************** HC-05 UUID; try this w/ the HC-05 present ***********************************

    //Name for the SDP (don;t know what is it) record when creating server socket
    private static final String name = "BluetoothCommand";
    private static final String BluetoothCommandService = null;

    public BluetoothCommandService(Context context, Handler handler) { // context == UI Activity Context && handler == send message back to the UI Activity
        BTAdapter = BluetoothAdapter.getDefaultAdapter();
        connectionState = stateNothing;
        bluetoothHandler = handler;
    }

    private  synchronized void setState(int state) { // state == current connection state; an integer
        if (D) Log.d(tagState, "setState() " + connectionState + " -> " + state);
        connectionState = state;

        //Give the new state to the Handler so that the UI Activity can update
        //bluetoothHandler.obtainMessage(what, arg1, arg2)
        bluetoothHandler.obtainMessage(MainActivity.MESSAGE_STATE_CHANGE, state, -1).sendToTarget();
    }

    public synchronized int getState() { //return the current connection state
        return connectionState;
    }

    public synchronized void start() {
        if (D) Log.d(tagState, "start");

        // Cancel any thread attempting to make a connection
        if (connectThread != null)
        {
            connectThread.cancel();
            connectThread = null;
        }

        // Cancel any thread currently running a connection
        if (connectedThread != null)
        {
            connectedThread.cancel();
            connectedThread = null;
        }

        //********************************************************
        //****Added 12/27/13
        // Start the thread to listen on a BluetoothServerSocket
        if (mainAcceptThread == null)
        {
            mainAcceptThread = new AcceptThread();
            mainAcceptThread.start();
        }

        setState(stateListen);
    }

    //device == the BluetoothDevice to connect
    public synchronized void connect(BluetoothDevice device) {
        if (D) Log.d(tagState, "connect to: " + device);

        // Cancel any thread attempting to make a connection
        if (connectionState == stateConnecting) {
            if (connectThread != null)
            {
                connectThread.cancel();
                connectThread = null;
            }
        }

        // Cancel any thread currently running a connection
        if (connectedThread != null)
        {
            connectedThread.cancel();
            connectedThread = null;
        }

     // Cancel the accept thread because we only want to connect to one device
        if (mainAcceptThread != null)
        {
            mainAcceptThread.cancel();
            mainAcceptThread = null;
        }

        // Start the thread to connect with the given device
        connectThread = new ConnectThread(device);
        connectThread.start();
        setState(stateConnecting);
    }

    public synchronized void connected(BluetoothSocket socket, BluetoothDevice device) {
        if (D) Log.d(tagState, "connected");

        // Cancel the thread that completed the connection
        if (connectThread != null)
        {
            connectThread.cancel();
            connectThread = null;
        }

        // Cancel any thread currently running a connection
        if (connectedThread != null)
        {
            connectedThread.cancel();
            connectedThread = null;
        }

        //*********************************************
        //****Added 12/27/13
        // Cancel the accept thread because we only want to connect to one device
        if (mainAcceptThread != null)
        {
            mainAcceptThread.cancel();
            mainAcceptThread = null;
        }

        // Start the thread to manage the connection and perform transmissions
        connectedThread = new ConnectedThread(socket);
        connectedThread.start();

        // Send the name of the connected device back to the UI Activity
        Message msg = bluetoothHandler.obtainMessage(MainActivity.MESSAGE_DEVICE_NAME);
        Bundle bundle = new Bundle();
        bundle.putString(MainActivity.DEVICENAME, device.getName());
        msg.setData(bundle);
        bluetoothHandler.sendMessage(msg);

        setState(stateConnected);
    }

    public synchronized void stop() {
        if (D) Log.d(tagState, "stop");

        if (connectThread != null)
        {
            connectThread.cancel();
            connectThread = null;
        }

        if (connectedThread != null)
        {
            connectedThread.cancel();
            connectedThread = null;
        }

        //*****************************************
        //****Added 12/27/13
        if (mainAcceptThread != null)
        {
            mainAcceptThread.cancel();
            mainAcceptThread = null;
        }

        setState(stateNothing);
    }

    public static void write(byte[] out) {
        // Create temporary object
        ConnectedThread r;
        // Synchronize a copy of the ConnectedThread
        //synchronized (this) {
        //synchronized (ConnectedThread) {
          //  if (connectionState != stateConnected) return;
            r = connectedThread;
        //}
        // Perform the write unsynchronized
        r.write(out);
    }

    public void write(int out) {
        // Create temporary object
        ConnectedThread r;
        // Synchronize a copy of the ConnectedThread
        synchronized (this) {
            if (connectionState != stateConnected) return;
            r = connectedThread;
        }
        // Perform the write unsynchronized
        r.write(out);
    }

    private void connectionFailed() {
        setState(stateListen);

        // Send a failure message back to the Activity
        Message msg = bluetoothHandler.obtainMessage(MainActivity.MESSAGE_TOAST);
        Bundle bundle = new Bundle();
        bundle.putString(MainActivity.TOAST, "Unable to connect device");
        msg.setData(bundle);
        bluetoothHandler.sendMessage(msg);
    }

    /**
     * Indicate that the connection was lost and notify the UI Activity.
     */
    private void connectionLost() {
            setState(stateListen);
            // Send a failure message back to the Activity
            Message msg = bluetoothHandler.obtainMessage(MainActivity.MESSAGE_TOAST);
            Bundle bundle = new Bundle();
            bundle.putString(MainActivity.TOAST, "Device connection was lost");
            msg.setData(bundle);
            bluetoothHandler.sendMessage(msg);
    }

    //ConnectThread runs while attempting to amke an outgoing connection w/ device
    //private class ConnectThread extends Thread {
        //private final BluetoothSocket connectThread_socket;
        //private final BluetoothDevice connectThread_device;

    public class ConnectThread extends Thread {
        public final BluetoothSocket connectThread_socket;
        public final BluetoothDevice connectThread_device;

        public ConnectThread(BluetoothDevice device) {
            connectThread_device = device;
            BluetoothSocket tmp = null;

            //Get a BluetoothSocket for a connection w/ the given BT device
            //try {
                //tmp = device.createRfcommSocketToServiceRecord(myUUID);} //ready to start a secure outgoing connection to this remote device using SDP lookup of uuid

            //catch (IOException e) {
                //Log.e(tag, msg, tr)
                //Log.e(tagState, "create() failed", e);}

            //Added 12/28/13
            Method m;
            try {
                    m = device.getClass().getMethod("createRfcommSocket", new Class[] {int.class});
                    tmp = (BluetoothSocket) m.invoke(device, 1);

            } catch (SecurityException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
            } catch (NoSuchMethodException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
            } catch (IllegalArgumentException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
            } catch (IllegalAccessException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
            } catch (InvocationTargetException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
            }

            connectThread_socket = tmp;
        }

        public void run() {
            Log.i(tagState, "BEGIN ConnectThread");
            setName("ConnectThread");

            // Always cancel discovery because it will slow down a connection
            BTAdapter.cancelDiscovery();

            // Make a connection to the BluetoothSocket
            try {
                // This is a blocking call and will only return on a
                // successful connection or an exception
                connectThread_socket.connect();}
            catch (IOException e) {
                connectionFailed();
                // Close the socket
                try {
                    connectThread_socket.close();
                } catch (IOException e2) {
                    Log.e(tagState, "Unable to close() socket during connection failure", e2);
                }
                // Start the service over to restart listening mode
                BluetoothCommandService.this.start();
                return;
            }

            // Reset the ConnectThread because we're done
            synchronized (BluetoothCommandService.this) {
                connectThread = null;
            }

            // Start the connected thread
            connected(connectThread_socket, connectThread_device); //ERROR: will still create "connected"
        }

        public void cancel() {
            try {
                connectThread_socket.close();
            } catch (IOException e) {
                Log.e(tagState, "close() of connect socket failed", e);
            }
        }

    }

    //ConnectedThread runs while theres a connection w/ other remote device
    ///private class ConnectedThread extends Thread {
        //private final BluetoothSocket connectedThread_socket;
        //private final InputStream connectedThread_inStream;
        //private final OutputStream connectedThread_outStream;

    public class ConnectedThread extends Thread {
        public final BluetoothSocket connectedThread_socket;
        public final InputStream connectedThread_inStream;
        public final OutputStream connectedThread_outStream;

        public ConnectedThread(BluetoothSocket socket) {
            Log.d(tagState, "create ConnectedThread");
            connectedThread_socket = socket;

            InputStream tmpIn = null;
            OutputStream tmpOut = null;

         // Get the BluetoothSocket input and output streams
            try {
                tmpIn = socket.getInputStream();
                tmpOut = socket.getOutputStream();
            } catch (IOException e) {
                Log.e(tagState, "temp sockets not created", e);
            }

            connectedThread_inStream = tmpIn;
            connectedThread_outStream = tmpOut;
        }

        public void run() {
            Log.i(tagState, "BEGIN ConnectedThread");
            byte[] buffer = new byte[1024]; // WALA JUD KO KASABOT ANI MAN :D
                                            //buffer == the bytes to write
                                            //buffer store for the stream

            // Keep listening to the InputStream while connected
            while (true) {
                try {
                    // Read from the InputStream
                    int bytes = connectedThread_inStream.read(buffer);

                    // Send the obtained bytes to the UI Activity
                    bluetoothHandler.obtainMessage(MainActivity.MESSAGE_READ, bytes, -1, buffer) //WA KO KASABOT SA SYNTAX YOT!!!!! >_<
                            .sendToTarget();
                } catch (IOException e) {
                    Log.e(tagState, "disconnected", e);
                    connectionLost(); //ERROR: will still create "private void CONNECTIONLOST"
                    break;
                }
            }
        }

        public void write(byte[] buffer) {
            try {
                connectedThread_outStream.write(buffer);

                // Share the sent message back to the UI Activity
//                mHandler.obtainMessage(BluetoothChat.MESSAGE_WRITE, -1, -1, buffer)
//                        .sendToTarget();
            } catch (IOException e) {
                Log.e(tagState, "Exception during write", e);
            }
        }

        public void write(int out) {
            try {
                connectedThread_outStream.write(out);

                // Share the sent message back to the UI Activity
//                mHandler.obtainMessage(BluetoothChat.MESSAGE_WRITE, -1, -1, buffer)
//                        .sendToTarget();
            } catch (IOException e) {
                Log.e(tagState, "Exception during write", e);
            }
        }

        public void cancel() {
            try {
                connectedThread_outStream.write(exitCMD);
                connectedThread_socket.close();
            } catch (IOException e) {
                Log.e(tagState, "close() of connect socket failed", e);
            }
        }

    }

    //*************************************************************************
    //*************************************************************************
    //***Added 12/27/13
    //***THis thread runs while listening for incoming connections.
    //***It behaves like a server-side client. It runs until a connection is accepted (or until cancelled).
    private class AcceptThread extends Thread {
        // The local server socket
        private final BluetoothServerSocket acceptThread_ServerSocket;

        public AcceptThread() {
            BluetoothServerSocket tmp = null;

            // Create a new listening server socket
            try {
                tmp = BTAdapter.listenUsingRfcommWithServiceRecord(name, myUUID);
            } catch (IOException e) {
                Log.e(tagState, "listen() failed", e);
            }
            acceptThread_ServerSocket = tmp;
        }

        public void run() {
            if (D) Log.d(tagState, "BEGIN mainAcceptThread" + this);
            setName("AcceptThread");
            BluetoothSocket socket = null;

            // Listen to the server socket if we're not connected
            while (connectionState != stateConnected) {
                try {
                    // This is a blocking call and will only return on a
                    // successful connection or an exception
                    socket = acceptThread_ServerSocket.accept();
                } catch (IOException e) {
                    Log.e(tagState, "accept() failed", e);
                    break;
                }

                // If a connection was accepted
                if (socket != null) {
                    synchronized (BluetoothCommandService.this) {
                        switch (connectionState) {
                        case stateListen:
                        case stateConnecting:
                            // Situation normal. Start the connected thread.
                            connected(socket, socket.getRemoteDevice());
                            break;
                        case stateNothing:
                        case stateConnected:
                            // Either not ready or already connected. Terminate new socket.
                            try {
                                socket.close();
                            } catch (IOException e) {
                                Log.e(tagState, "Could not close unwanted socket", e);
                            }
                            break;
                        }
                    }
                }
            }
            if (D) Log.i(tagState, "END mainAcceptThread");
        }

        public void cancel() {
            if (D) Log.d(tagState, "cancel " + this);
            try {
                acceptThread_ServerSocket.close();
            } catch (IOException e) {
                Log.e(tagState, "close() of server failed", e);
            }
        }
    }

}

I check already the LogCat but there were no related errors with this problem. Any help, suggestions, or clarifications about my problem with be so much appreciated. You will be a big help for this project. Thank you.

A: Add btn_d1_off.setEnabled(true);
After btn_d1_on.setEnabled(false);
In btn_d1_on.setOnClickListener(new OnClickListener()
And same in   btn_d1_off.setOnClickListener(new OnClickListener()
Add btn_d1_on.setEnabled(true);
After btn_d1_off.setEnabled(false);
Hope this work.


text:
Q: facebook api, is event id universally unique The user's event data is as below. I'm wonder the id 157881474402440 is unique among all events (private, public, belong to any person) in Facebook graph since I'm intending to use it to export to a calendar system as the UID of event (I'll append it with something like "_facebook"). Tks
"events": {
    "data": [
      {
        "name": "Return match vs Wollongong",
        "start_time": "2013-08-10T14:00:00+1000",
        "end_time": "2013-08-10T17:00:00+1000",
        "timezone": "Australia/Sydney",
        "location": "Wentworth park field 1",
        "rsvp_status": "attending",
        "id": "157881474402440"
      }
    ],

A: Every object on facebook has unique object id.  you can verify it by getting the event details from two different facebook accounts having access to the event.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Gradient ALONG a CGPath I am drawing an arc that is an almost complete circle:
    CGContextSetFillColorWithColor(context, [UIColor whiteColor].CGColor);
    CGMutablePathRef path = CGPathCreateMutable();
    CGPathMoveToPoint(path, NULL, centerPoint.x, centerPoint.y);
    CGPathAddArc(path, NULL, centerPoint.x, centerPoint.y, radius, (float)(3.0f * M_PI_2), radians, !clockwise);
    CGPathCloseSubpath(path);
    CGContextAddPath(context, path);
    CGContextFillPath(context);
    CGPathRelease(path);

I have an arc like path that is an almost complete circle. In this code it is all one color, however, I want one end to be a solid white color and the other to be a [UIColor clearColor] so that it smoothly fades out.
Every example of code I have found uses a linear gradient. This will not work. I don't want a linear gradient, but a gradient that travels along the path so that one end is colorA and the other colorB.
It seems like this should be possible. Is it possible with CoreGraphics? Or if not, another method?


text:
Q: How to standardize observations in a variable using Stata Using Stata/SE 13.1, I am trying to standardize my variable: ID- changing all ID numbers in the data set from "ES0001_2" to "ES0001." Not all records have ID numbers with "_2". Is there a command I can use to accomplish this? Many thanks.

A: Please provide code and your failed attempts for future questions. Just asking for code to do this or that is considered off-topic by some of us at this site. It also shows you've done your part of the job; mainly research your question before asking for help.
Depending of the structure of the values in your data set, this might or might not work (your example data might be too simple):
clear
set more off

*----- example data -----

input ///
str15 id
ES0001_2
ES0003
ES0004_2
ES0008_2
end

list

*----- what you want -----

gen id2 = subinstr(id, "_2", "", .)

list

See help string functions.


text:
Q: how capture a moving customcontrol I try to explain my problem:
I got many customcontrols of same type on a panel.
At runtime I'm free to move any custumcontrol ( mousedown  and mousemove events) in the form with mouse over any others customcontrols using bringtofront() to have it over all.
Now I need to know when the control I'm moving is over any other control and  which control is under.
So far I've tryed to use drag-n-drop events but without success, there's some other way to do this or I've to re elaborate it with drag events?
thank you all for help
and sorry for my English.
EDIT:
The controls are cards game and my final goal is to use cards to create logical sequence following rules based on card value and/or color.

A: You can't solve the problem with drag-and-drop because you're not actually dropping one control onto the other control. You're merely moving them around in the form.
You need to become familiar with Z order, which is the front-to-back arrangement of objects in a virtual 3D space. To adjust the Z order, you can call the BringToFront and SendToBack methods of any object that derives from System.Windows.Forms.Control.
The Z order is also exposed by the parent (container) control's Controls collection. Using the GetChildIndex method, you can determine the position of any control within the Z order.
So now, all you need to do is figure out which control the control you're dragging is over. Do that by comparing the Location properties of the two controls. When you know that the locations of two controls overlap, check their respective Z order indices to see which one is on top.


text:
Q: Configuring rsnapshot to only backup local file systems I'm currently using rsnapshot to backup a server farm where NFS is used heavily. Unfortunately, the current setup has us backing up the same files multiple times due to the NFS mounts.
For example, /etc/rsnapshot.conf has this:
backup backupuser@machine1:/local_directory/       machine1
backup backupuser@machine2:/exported_directory/       machine2

Now, machine1 has /local_directory/exported_directory mounted -- so I end up with backups of both machine1/local_directory/exported_directory AND machine2/exported_directory.
While I could work around this by either mounting things differently on the clients or by manually excluding the directories, I'd rather find a cleaner approach (which is probably a rsnapshot or rsync option).

A: Found it! I knew I should've perused the man pages one last time before posting :)
It's -x or --one-file-system option to rsync.
  -x, --one-file-system
              This tells rsync  not  to  cross  filesystem  boundaries   when
              recursing.   This   is  useful for transferring the contents of
              only one filesystem.


text:
Q: On average of percents I have read some pages about how to calculate the average of percents. However, still I don't understand something...
Assume data points are organized in the following manner: We have two categories and each category contains some malware files. We run a virus detection program to see how many files are detected as malware. So, for SET1, there are 30 files and we have detected 25 viruses. The coverage is then 83.3%. The same is true for SET2.
          items         detected          percent
 set1      30              25              83.3%
 set2      80              40              50%

Now, we want to know what is the average coverage for this program. We have two methods:
1- We can say, there are totally 110 files (30+80) and totally 65 files (25+40) are detected. So, the average coverage is 65*100/110 which is 66.6%
2- We can calculate (83.3+50)/2 which is 59%.
Which one is more meaningful?

A: 59% is correct.
You can caluclate it like this: (30 * 83.3% + 80 * 50%)/110 = 59%
The problem with averaging percentages directly is that you don't take into account the numbers that these percentages refer to. If you had the equal number of elements in set1 and set2, you'd get the same result, but since one set has more elements than the other, the percentage has to be weighted.


text:
Q: Is a number between the 2 square brackets necessary regarding char variables I just started programming in C and I see on the internet people declaring chars like, for example, char name[], without putting any number between the 2 square brackets. I used to code in C++ in high school and we always used to put a number when declaring char. Can someone explain when do we put a number, or if it is even necessary to use one when declaring a char variable?
I used to do it like this:
char name[20] = "John";

but I've seen on the internet people doing it like this:
char name[] = "John";

A: char curse[] = "fie! cometh h're and englut mine own coxcomb thee distemperate fooleth!";

In this case, the compiler automatically computes the number of bytes, including the null-terminator. The size of the array is equal to the length of the string, plus the null-byte.
char curse[100] = "fie! cometh h're and englut mine own coxcomb thee distemperate fooleth!";

Whereas, this defines an array of 100 chars, and initializes it with a string of 70 or so bytes. The rest of the bytes are initialized to 0¹. The size of the array is 100 bytes, whereas the length of the string can be determined with strlen. NB that the size of the array and the length of the string it contains are not the same.
Aside: It's better to define the array size as a macro instead of having magic numbers all over your code. It's easier to maintain that way.
[1] From C11:

If there are fewer initializers in a brace-enclosed list than there
are elements or members of an aggregate, or fewer characters in a
string literal used to initialize an array of known size than there
are elements in the array, the remainder of the aggregate shall be
initialized implicitly the same as objects that have static storage
duration.

i.e. 0.

A: char name[] = "John"; will define a char array long enough to accommodate "John" (5 chars).
char name1[20] = "John"; defined an array of 20 char and initialization string only takes 5 bytes (abstracting from the rest of bytes) So you can use those remaining 15 bytes for example by appending another string to it.
strcat(name1, " Travolta");
`

A: From the C Standard (6.7.9 Initialization)

22 If an array of unknown size is initialized, its size is determined
by the largest indexed element with an explicit initializer. The array
type is completed at the end of its initializer list.

and

14 An array of character type may be initialized by a character string
literal or UTF−8 string literal, optionally enclosed in braces.
Successive bytes of the string literal (including the terminating null
character if there is room or if the array is of unknown size)
initialize the elements of the array.

So in this declaration of a character array
char name[] = "John";

that is according to the second quote from the C Standard equivalent to
char name[] = { "John" );

the array name is initialized by the string literal "John".
According to the first quote from the C Standard the size of the array is determined by the number of characters (including the terminating zero character '\0') in the string literal. In fact the above declaration has the same effect as the following declaration
char name[] = { 'J', 'o', 'h', 'n', '\0' };

So as the number of characters in the string literal is equal to 5 then the array has exactly 5 elements and its size is also equal to 5 because sizeof( char ) is always equal to 1.
In this declaration
char name[20] = "John";

that again may be written like
char name[20] = { "John" };

the array is declared specifying explicitly 20 elements. The first 5 elements of the array have corresponding explicit initializers (characters of the string literal). All other elements of the array are implicitly initialized by 0.
Pay attention to that in C you may write
char name[4] = "John";

that is you may exclude the terminating zero character '\0' of the string literal from the list of initializers of the array. In this case the array name will not contain a string. In C++ such an initialization is incorrect and the C++ compiler will issue an error for such a declaration.
To output a character array that contains a string you can write for example
printf( "name = %s\n", name );

For the last shown declaration where the declared array does not contain a string you can write
printf( "name = %.*s\n", ( int )sizeof( name ), name );

A: If an array is declared without a size but with an initializer, then the size of the array is taken from the number of elements in the initializer:
int foo[] = {0, 1, 2, 3};

In this case, foo will be 4 elements wide.
char bar[] = "fred";
char bar[] = { 'f', 'r', 'e', 'd', 0 };

In this case, bar will be 5 elements wide - the initializers "fred" and { 'f', 'r', 'e', 'd', 0 } are equivalent to each other.
If you declare an array with a size and an initializer, then the size will be taken from the size expression.  If there are fewer elements in the initializer than the size, then remaining elements will be initialized to 0:
int foo[10] = {1, 2, 3}; // elements 3 through 9 will be initialized to 0

If there are more elements in the initializer than the array is sized for, then that's a constraint violation and the compiler will yell at you:
int foo[3] = {1, 2, 3, 4}; // constraint violation, too many elements
                           // in the initializer

If you use designated initializers, then the size will either be taken from the number of initializers or the largest designated initializer:
int foo[] = {[0] = 1, [9] = 2};

foo will be 10 elements wide, element 0 will be initialized to 1, element 9 will be initialized to 2, and the remaining elements will be initialized to 0.
If an array is declared without a size and without an initializer, then the array type is incomplete, and you can't create an instance of an incomplete type.
Note that array sizes are fixed for the lifetime of the array.  C has something called a variable-length array where the size of the array is determined by a runtime variable:
size_t x = some_size();
int arr[x];

However, "variable" in this context only means that the size of the array isn't fixed from definition to definition, not that the array can be resized after it is defined.
In the context of a function parameter declaration, T a[N] and T a[] are "adjusted" to T *a - you cannot pass arrays as function parameters, because array expressions "decay" to pointer expressions under most circumstances and what the function actually receives is a pointer.


text:
Q: How to create a global plugin in React? VueJS supports global plugins with the ability to use a mixin that can be applied to every component life-cycle. For example, every time a component renders I could log "Hello Dave" without even touching any existing components in an application.
Has anyone attempted anything similar in React?

Note: I know mixins are bad and I'm not generally advocating for them here.

A: Here's an ugly approach I've just cooked up. I'm essentially hijacking the React.createElement function:

let origCreateElement = React.createElement;

React.createElement = function (element, props, ...children) {
  if (typeof element.metaData !== 'undefined') {
    return origCreateElement.apply(React, [function (...rest) {
      let origElementOutput = element.apply(React, [...rest]);

      console.log(element.metaData);

      // **** To access Parent/Ancestors ****
      // React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner.current.type = element;
      // React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner.current.return.type

      return origElementOutput;
    }, props, ...children]);
  }

  return origCreateElement.apply(React, [element, props, ...children]);
};

function Hello({name}) {
  const [state, setState] = React.useState({
    first: name, last: 'Doe',
  });

  Hello.metaData = state;

  React.useEffect(() => {
    setTimeout(() => {
      setState({first: 'Dave', last: 'Dave'});
    }, 2000);
  }, []);

  return (

      Hello { state.first }

  );
}

Hello.metaData = null;

ReactDOM.render(<Hello name="John" />, document.querySelector('#app'));


text:
Q: Can LogParser output to Azure SQL? Azure SQL tables require a clustered index and will not accept insertions if one is not present. If one is present LogParser is complaining about a mismatch on the number of columns in the select list vs. the target table.
Is there any way to square this circle? Perhaps embed an expression in LP's select list like '"SELECT DateTime,Thread,Level,Logger,Message,Exception,(select max(id)+1 from loggerTbl)...
It's becoming amazingly difficult to parse plain old azure logs into sql where god intends them to be.

A:
Azure SQL tables require a clustered index and will not accept insertions if one is not present.

That is no longer true. Azure SQL DB v12 no longer has this restrictions. Move your DB to one of the new tiers (Basic, Standard) and your DB will be upgraded to v12.


text:
Q: Cannot Read Configuration File Because it Exceeds the Maximum File Size Cannot read configuration file because it exceeds the maximum file size.
I'm getting above error because my rewritemap.config file size is more than 250KB (Windows 2008 R2 SP1 server with IIS 7.5

A: If you have access to registry and if you really need file greater than 250kb, you can change value in Registry Key.
For an x32 system:
Create the Key:
HKLM\Software\Microsoft\InetStp\Configuration\

Add the DWORD value:
MaxWebConfigFileSizeInKB

For an x64 system:
Create the Key:
HKLM\Software\Wow6432Node\Microsoft\InetStp\Configuration\

Add the DWORD Value:
MaxWebConfigFileSizeInKB

Be sure to reboot or restart the application pool. This answer to a related question may also inspire.
Note: If there are not the key, you can just create it. how to create a key on regedit
Other alternative is to split the .config files.
http://forums.asp.net/t/1961321.aspx?Split+web+config+rewrite+rules+in+separate+file


text:
Q: AdMob in Canvas So, i have separated class for drawing , and i want to draw there adMob , I call it from game class and pass activity as parameter :
public void drawAddMob(Activity a){
LinearLayout ll = new LinearLayout(a);
ll.setPadding(0, 50, 0, 0);
adView = new AdView(a, AdSize.BANNER,  "a15140cd49b6e7b");
AdRequest request = new AdRequest();
adView.loadAd(request);
adView.setVisibility(View.VISIBLE);

ll.addView(adView);

ll.draw(canvas);
}

but when i do this i get error:
03-21 23:35:09.646: W/System.err(333):
java.lang.RuntimeException: Can't create handler
inside thread that has not called Looper.prepare()
03-21 23:35:09.656: W/System.err(333):
at com.google.ads.internal.AdWebView.<init>  (SourceFile:69)

A: You need to run this code on the UI thread, since it alters your UI. Try the following for your method body:
a.runOnUiThread(new Runnable() {
    public void run() {
        LinearLayout ll = new LinearLayout(a);
        ll.setPadding(0, 50, 0, 0);
        adView = new AdView(a, AdSize.BANNER,  "a15140cd49b6e7b");
        AdRequest request = new AdRequest();
        adView.loadAd(request);
        adView.setVisibility(View.VISIBLE);

        ll.addView(adView);

        ll.draw(canvas);
    }
});


text:
Q: USB Debugging: How to revoke the "Always allow from this computer" option I've started developing for android. I'm using different computers with different operating systems. (A Windows desktop PC and a Macintosh at home and a Windows Notebook at work)
Most of the time I am using my desktop pc for development but since yesterday my Nexus 4 is displayed as offline in the Eclipse ADT Devices view. This problem only occurs on my desktop pc. On the other computers I don't have any problems getting the device online in eclipse.
I already tried a lot of things like:
- unplugging/plugging the nexus 4
- switching off/on usb debugging
- restarting computer, nexus 4 and the adb server
- reinstalling nexus 4 usb drivers (I'm using the Android Composite ADB Interface Drivers from the Android SDK)
I was about to give up but then I remembered something. After connecting the nexus via usb the "Allow USB debugging" dialog shows up and on my desktop pc I checked the "Always allow from this computer" option.
My hope is that disabling this "Always Allow"-permission could help to get my device back online. I already searched in the developer options to find a way to reset the "Always Allow" permission without success. Maybe it is possible to reset the permission by clearing the data of the App/Service (Settings->Apps(All)) which stores this information but I didn't find the name of it in Google.
So does anyone know the name of the App/Service whose data has to be cleared to reset the permission? Or is there another way to get the device back online that I have not tought of?

A: You can use your device with multiple computers with that enabled as well. I can use my Nexus 7 and Galaxy Nexus, both running 4.2.2 and having checked the always allow option on 3 machines right now.
Make sure all your machines are running the latest update for ADT and the SDK Tools, as the adb in the previous versions does not support the 4.2.2 security measures. One of my machines had the same problem, and it got fixed when I updated my tools.
Also, sometimes you have multiple Eclipse installs (I have about 11, for various reasons). If all of them aren't updated with the latest tools, make sure your PATH points to the adb in the newest update, and not any other.


text:
Q: XAMARIN, WCF with Custom User Name/Password and Principal I am developing a WCF service that will provide data to a Xamarin client.  I am trying to utilize custom user name/password and custom principle so I can attach usable information for the service to the identity.  After many tries I have not been able to get anything but different error messages on the client.  I believe the problem is in the WCF configuration, but I can not figure out what the problem is.  My web.config code is below.  Any help or tips on where to go would be greatly appreciated!
<system.serviceModel>

<diagnostics wmiProviderEnabled="true">
  <messageLogging
       logEntireMessage="true"
       logMalformedMessages="true"
       logMessagesAtServiceLevel="true"
       logMessagesAtTransportLevel="true"
       maxSizeOfMessageToLog="65535000"
       maxMessagesToLog="3000"
   />
</diagnostics>
<behaviors>
  <serviceBehaviors>
    <behavior name="Behavior">
      <!-- To avoid disclosing metadata information, set the values below
to false before deployment -->
      <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
      <!-- To receive exception details in faults for debugging purposes,
set the value below to true.  Set to false before deployment to avoid
disclosing exception information -->
      <serviceDebug includeExceptionDetailInFaults="true"/>
      <serviceCredentials>
        <serviceCertificate findValue="Cert" storeLocation="LocalMachine"
storeName="My" x509FindType="FindBySubjectName"/>
        <userNameAuthentication userNamePasswordValidationMode="Custom"
customUserNamePasswordValidatorType="Service.ServiceAuthenticator,
Service"/>
      </serviceCredentials>
      <serviceAuthorization
serviceAuthorizationManagerType="Service.CustomAuthorizationManager,
Service" principalPermissionMode="Custom">
        <authorizationPolicies>
          <add policyType="Service.AuthorizationPolicy, Service"/>
        </authorizationPolicies>
      </serviceAuthorization>
      <serviceSecurityAudit
auditLogLocation="Application"
serviceAuthorizationAuditLevel="Failure"

messageAuthenticationAuditLevel="Failure"
suppressAuditFailure="true" />
    </behavior>
  </serviceBehaviors>
</behaviors>
<services>
  <service name="Service" behaviorConfiguration="Behavior">
    <endpoint address="" binding="basicHttpBinding"
contract="Service.IService" bindingConfiguration="Secure"/>
    <endpoint address="mex" binding="mexHttpBinding"
contract="IMetadataExchange"/>
  </service>
</services>
<bindings>
  <basicHttpBinding>
    <binding name="Secure">
      <security mode="Transport">
        <transport clientCredentialType="Basic"
proxyCredentialType="None" realm=""/>
        <message clientCredentialType="UserName"
algorithmSuite="Default"/>
      </security>
    </binding>
  </basicHttpBinding>
</bindings>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"
multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
<!--
    To browse web app root directory during debugging, set the value
below to true.
    Set to false before deployment to avoid disclosing web app folder
information.
  -->
<directoryBrowse enabled="true"/>
<httpErrors errorMode="Detailed" />
</system.webServer>

I'm using the WFC service as a connected service in the main project of the Xamarin solution. The service is being called with the code below:
        Service.ServiceClient _client;

        _client = new Service.ServiceClient();

        _client.ClientCredentials.UserName.UserName =
"username";
        _client.ClientCredentials.UserName.Password = "password";

        //To allow service to connect even though certificate was not
validated.
        ServicePointManager.ServerCertificateValidationCallback =
MyRemoteCertificateValidationCallback;

        lci = await _client.WCFTestMethod();

To update the post on the comments below.  wsHttpBinding is not supported by Xamarin, so I do have to use basicHttpBinding.  I have gotten the checkAccessCore procedure to execute when I set the authentication to Anonymous on the IIS site, but it throws this error "No Identity Found" when the AuthorizationPolicy is executing GetClientIdentity. Is there a way to assign an identity in checkAccessCore?

A: I was able to get the service to work the way I wanted it to, by making sure the authentication method on IIS was set to Anonymous and in the Evaluate method of the AuthorizationPolicy I created a GenericIdentity and used it (example code below) instead of calling the GetClientIdentity method.  The service seems to be working now and is authenticating the user in the checkAccessCore method.
    Dim client As IIdentity = New GenericIdentity("User")

    Dim cp As CustomPrincipal = New CustomPrincipal(client)

    evaluationContext.Properties("Identities") = l

    evaluationContext.Properties("Principal") = cp


text:
Q: Two part of different font size text bottom aligned Pls see: Demo
What I want to do is: horizontally, put the first sentence on the left, and put the other one right.  Vertically, I want to align them to the bottom.  The two sentences are not the same font size.  I searched this topic for a while and think display:table-cell should work, but you see, the two sentences are not bottom aligned.  Any help will be appreciated!
HTML

I'm left

I'm right

CSS
.di_header{
    display:table;
    width:100%;
}

.di_h_en{
    width:30%;
    display:table-cell;
    vertical-align:bottom;
    text-align:left;
    border:solid 1px red;
}

.di_h_cn{
    width:70%;
    display:table-cell;
    vertical-align: bottom;
    text-align:right;
    border:solid 1px red;
}

.di_h_en p{
    font-size:32px;
}

.di_h_cn p{
    font-size:24px;
}

A: Remove margin and you will get your desired output
.di_h_cn p {
   font-size: 24px;
   margin: 0;
}

as p tag has these two rules to add margin
-webkit-margin-before: 1em;
-webkit-margin-after: 1em;

A: Use this only to solve your issue
p{margin:0;}

A: check this Fiddle
*{
margin:0px !important;
}

You need to remove the auto generated margins. i've specified the height of your table cells to see the effect of bottom alignment

A: When you write HTML you should know that most of HTML tags takes default margin and padding. To remove those margin and padding you should use one of the following techniques:

*

*Use CSS Reset [recommended]

*Use following CSS
body, p, h1, h2, h3, h4, h5, h5, h6, form, input, blockqoute {
    margin: 0;
    padding: 0;
    line-height: normal;
}
By using one the above techniques your HTML elements behaves same in cross browsers.


text:
Q: Strange networking issue: good software/hardware troubleshooting tools? I'm posting this question with the hope of getting some guidance from others because at this point I'm completely stumped.
I'm trying to troubleshoot a mid 2011 iMac (11,2) running Mavericks that is unable to ping or communicate with any other host, despite appearing to connect to my home router without issue (it associates and gets an IP address from DHCP).  The router is an Asus RT-N65U with both 2.4GHz and 5GHz radios.  Wireless clients mostly connect to the 2.4GHz radio since it has better range, WPA2 authentication is used on both.  There are numerous other devices on the LAN - both wired and wireless - that all work fine.  Furthermore, the iMac in question seems to only have developed problems within the last couple of days though nothing has changed on the router and nothing has changed on the machine either...or so I'm told.
After some initial troubleshooting I went ahead and reinstalled Mavericks from a USB stick I had on-hand, figuring that would eliminate any software related issues that might have otherwise been hard to track down.  However the problem persisted even after the re-install, which made me think the wireless card was flaking out.  I'm skeptical of this however because

*

*The machine doesn't have any problem establishing a network connection

*The signal strength is what I'd expect to see

*I ran a packet sniffer and that showed link layer packets going back and forth, but IP packets of any kind are ignored (as far as I can tell).

*I set up an ad-hoc network with the iMac and joined it with my MBP, both machines could ping each other.

The only thing I've seen that seems sort of suspect is an error message from the kernel in the wifi log: Unsupported ioctl 181 but I haven't been able to determine what this means beyond the kernel asking the wireless driver to do something it can't, so it may or may not be significant.  The other potentially significant thing is that at one point this machine was restored from a time machine backup of a completely different computer (a MBP).  It's my understanding that time machine backs up the entire drive, so restoring a backup from a different hardware configuration seems like it could break things, but nothing that a clean install of OSX couldn't fix.  I've tried to do the built in hardware test but it doesn't work for some reason, maybe because this machine has an after-market hard drive upgrade (the original failed).
So this brings me back to wondering whether it's a software issue, particularly something to do with the router but that seems strange since nothing has changed on the router and I'm the only one who could change anything to begin with.
This all brings me to my question: what else could I look into that could provide more info to work with so I narrow down what's going on here?
UPDATE
Some more info and clarification of some things:  When I say the machine "connects" to the router, I meant associate.  It associates to the wireless network, but will not ping the router's IP address.
I have not tried a wired connection but I did try one of these and it works flawlessly, so this is specific to the built in wireless.  Are there any other tools for testing the hardware besides the Apple diagnostics?

A: Apple ships with some pretty good tools to check wifi network.
Look in /System/Library/CoreServices/Applications for

*

*Network Utility.app

*Wireless Diagnostics.app

You can also access them by holding Opt/Alt while clicking on the WiFi icon in the menu bar.
Then there is lots of Terminal commands to do that as well, if you prefer the Terminal.


text:
Q: Determining what AppleScript commands an application responds to Is it possible to ask an OSX application which applescript commands it responds to, and if so, how?

A: You need to look at the Dictionary for an application to see all of the classes and commands the application supports. To get to an application's Dictionary in the the Applescript Editor go to File > Open Dictionary.... A list of all the applications that the OS knows supports Applescript will appear, but the OS won't catch them all so you can use the Browse button. If an application doesn't support Applescript, then it won't be selectable in the dialog window.
The caveat to this is that there are certain commands that an application is supposed to support but don't, or an application may only support the minimum requirements. These are all very, very simple like open, quit, etc. Your mileage may vary.


text:
Q: How to pass data using delegates and protocols I have this first viewController which has UILabel in it and secondViewController which has UItextField and Add button. They are embedded in tabbar. I want to pass data from text field when add button is clicked to uilabel of first view controller.
protocol SendDelagate
{
func setData(string:String)
}

First View Controller is
class ViewController: UIViewController,SendDelagate{

@IBOutlet weak var label: UILabel!

override func viewDidLoad() {
    super.viewDidLoad()
    let vc = SecondViewController()
    vc.delegates = self
}
func setData(string: String) {
    label.text = string
  }
}

And second ViewController is
class SecondViewController: UIViewController {

var delegates:SendDelagate?

@IBOutlet weak var textField: UITextField!
override func viewDidLoad() {
    super.viewDidLoad()

}

@IBAction func addButton(_ sender: UIButton) {
    let text = textField.text!
    delegates?.setData(string: text)
     }
}

A: SecondViewController is embedded in UITabbarController?
You can find SecondViewController instance via TabbarController
class ViewController: UIViewController, SendDelagate {

    @IBOutlet weak var label: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()

        if let secondViewController = tabBarController?.viewControllers?.first(where: { $0 is SecondViewController }) as? SecondViewController {
            secondViewController.delegates = self
        }
    }

    func setData(string: String) {
        label.text = string
    }
}

A: You can use User Defaults. So you save with your Add Button into User Defaults, and on viewDidLoad on the other view, you can load it.


text:
Q: How to stop previous page controller from working when changing page? I am applying pagination on scroll on every page. Everytime I change page, pagination function reloads from previous page as well. This way as I traverse different pages , pagination functions get called everytime from all those page controllers. How can I stop previous page controller functions from working.
Pagination logic is that on window scroll to bottom, trigger pagination function & the page gets more content.
Here is the code:
angular.element($window).bind("scroll",function() {
      var windowHeight = "innerHeight" in window ? window.innerHeight: document.documentElement.offsetHeight;
      var body = document.body,
           html = document.documentElement;
      var docHeight = Math.max(body.scrollHeight,body.offsetHeight, html.clientHeight,html.scrollHeight, html.offsetHeight);
      windowBottom = windowHeight + window.pageYOffset;
      if (windowBottom >= docHeight) {

          if($scope.moredataleft==true && $scope.loadingLoader==false)
            {

                if($scope.drugnameScroll==true&&$scope.drugSearchScroll==false)
              {
                  if($scope.page==0)
                  {
                    $scope.page=2;
                  }
                  else{
                      $scope.page=$scope.page+1;
                      }
                  $scope.pagination();
              }

            }
          }

       });

A: I got the solution using $destroy event in angularjs.
I had to unbind the scroll event handler as suggested by @Nikos in comment to stop its working when controller is destroyed.
$scope.$on('$destroy',function(){
  angular.element($window).unbind("scroll");
});


text:
Q: when starting jenkins it is starting but when checking status of jenkins it is saying active(exited) I had changed the permissions of /home/centos to sudo chmod -R 777 /home on which jenkins is hosted after that i'm not able to login to the machine then i had created one more instance and detached the jenkins disk attached to new machine changed the permissions then attached the disk to the jenkins machine. From then i'm able to login but when starting the jenkins it is saying active(exited).

A: As it is regarding with the permission' i tried to run 'jenkinsuser=root' it worked fine.


text:
Q: git: Pushing changes in particular commit I've checked out particular commit:
git checkout xx
#made changes
...
git add .
git commit -m "abcd"
git push

But I don't see anything updated back in github site.
Please help me to push successfully to my forked repo.

A: You have checkout a commit instead of a branch: you are in a detached HEAD mode, and a git push refuses to push a detached head.
See "Why did my Git repo enter a detached HEAD state?"

You need to make a new branch based on your current commit, or to reset one existing branch on that commit.
See "git: switch branch without detaching head".
Once your commit is referenced by a branch (as shown by the git branch command), you will be able to push that branch on your remote repo.

Note: with Git 2.23 (August 2019), you can use git restore and update your working tree without detaching HEAD (since you do not switch branch).
To switch branch, you now have (again, Git 2.23) git switch.


text:
Q: AWS send http request through elastic load balancer I am a beginner and trying to send http requests through elastic load balancer. Could anybody explain briefly about the steps that I need?

*

*set up Elastic Load Balancer A

*get DNS of the Elastic Load Balancer A

*register EC2 instances to the Elastic Load Balancer A

*send traffic to the DNS of Elastic Load Balancer A
But I have no idea what kind of configuration or set up I need to put in the EC2 instances that are to be attached to this Elastic Load Balancer A. Do I need to set up Listener? If so, how do I set this?
I just want to send http request under the ip of EC2s and Elastic Load Balancer A so that I get different IPs assigned to each requests.
Thanks a lot!

A: By default, Amazon EC2 instances behind an Elastic Load Balancer serve traffic on port 80 (HTTP). When creating the Load Balancer, you can configure which ports should receive traffic (80, 442, 1024+).
Think of it this way... The Load Balancer simply sits "in front" of the EC2 instances. If a user was to go directly to your EC2 instance directly (eg enter its IP Address in a web browser), they should see a website. Going to the Load Balancer does the same thing, but it distributes the requests amongst multiple EC2 instances.
So, in most cases, it's just a matter of running a web server or app on your EC2 instance running on port 80.


text:
Q: What is usage of angular.bootstrap i am learning angular js.from this site https://docs.angularjs.org/api/ng/function/angular.bootstrap it is saying Use this function to manually start up angular application.

  {{greeting}}

what is the meaning of this line angular.bootstrap(document, ['demo']); ?
the above program just create a module and controller but it use bootstrap.......without bootstrap controller can not be instantiated ?.
looking for guidance. thanks

A: angular.bootstrap is used as an alternative approach to initializing your application without using ng-app. In the above example, you can see that there is no ng-app directive added anywhere in the document. Therefore, using angular.bootstrap you defined the app module to be associated with the document which is demo in the above example.
You can also define the modules to be used with any element that can be identified by using document.getElementById() function in the first parameter of angular.bootstrap.
Using angular.bootstrap

   {{greeting}}

A: For running multiple apps in an HTML document you need to manually bootstrap them using angular.bootstrap


text:
Q: How to scroll to an element in TableView in Appium (Java)? I have to scroll down to a element and then tap this element.
I have tried using TouchAction, but it does not work.
P.S I'm new to Appium

A: Try this:
driver.ScrollTo("String"); and then click on that element.


text:
Q: TinyMCE buttons that launch Ajax-generated forms if i follow the tutorials on how to add tinyMCE buttons for shortcodes
( for instance: http://www.garyc40.com/2010/03/how-to-make-shortcodes-user-friendly/ )
if i create a button that launches a form in a thickbox there is always this bit of code to create the launched form:
// executes this when the DOM is ready
    jQuery(function(){
        // creates a form to be displayed everytime the button is clicked
        // you should achieve this using AJAX instead of direct html code like this
        var form = jQuery('

\

\
                Columns	\
                <input type="text" id="mygallery-columns" name="columns" value="3" />
\
                specify the number of columns.	\

\

\

\
            <input type="button" id="mygallery-submit" class="button-primary" value="Insert Gallery" name="submit" />\

\

');

        var table = form.find('table');
        form.appendTo('body').hide();

but i am curious about this  part in particular :
// you should achieve this using AJAX instead of direct html code like this
i've seen this on other tutorials, and in other plugins.... but all i've seen continue to do it this hard-coded way.  does anyone have any insight into how to do this via ajax?
i'd like to popular a select drop-down with values from get_options().. which i cannot do in jquery/java and the js file can't process the php either, so i figured ajax is the solution i'm just not sure how to start

A: by using jQuery.ajax():
so, instead of that big form variable:
$.ajax({
  type: 'GET',
  url: 'admin-ajax.php',
  data: { action: 'get_my_form' },
  success: function(response){
    var table = $(response).find('table'); // you don't seem to use this "table" var
    $(response).appendTo('body').hide();
    // ...
  }
});

Now, the php:
add_action('wp_ajax_get_my_form',  'get_my_form');

function get_my_form(){
  // build your form here and echo it to the screen
  exit;
}


text:
Q: Removing NAN elements from multidimensional numpy array I would like to know how to removing nan elements from multidimensional numpy array.
For example, I want to convert this array
x = array([[ 1., nan,  2.],
          [ 3.,  4., nan]])

to
x = array([[ 1.,  2.],
           [ 3.,  4.]])

I found some similar ways, but looks different what I want:
1.
x = x[~np.isnan(x)]

But this way remove array shape information.
>>> x[~np.isnan(x)]
array([1., 2., 3., 4.])

*

These are similar questions, but I don't want remove row or column including nan's, I want to just remove nan elements.

*

*Removing NaNs in numpy arrays

*How to remove all rows in a numpy.ndarray that contain non-numeric values


text:
Q: Is it bad form to not answer questions? Put simply, I ask far more questions than I answer.
Not for any lack of motivation or interest, I put a good deal of effort into questions and answers making sure they are well explained and that I've done my own research beforehand; it's just that typically by the time I've come up with a solution the question has already been answered.
On top of that, frankly the people answering have far more specialized knowledge in their respective sections, and so I feel like my answers would only be muddying the page up.
I do -look- for questions that have been left alone, or that could use help and provide a fair answer, but for the most part I use the site to get practiced opinions as to the best methodology to accomplish a given task.
Even with my questions it's not so much that I couldn't -find- the answer, but that I want a persons opinion on how to implement it, and not a reference page with an agnostic list of functions.
Just curious if it's considered bad form to have a much higher Q-2-A ratio.

A: I don't see why it should be a bad idea at all. Heck, if people didn't post many questions, I'd be pretty bored on SO :)
If you're putting effort into asking good questions (making sure they're not duplicate, maybe following my suggestions) then I can't see what anyone would have against that.

A: A lot of people feel this way, myself included. But it's totally natural for the ratio to be unbalanced. Knowing less about a topic means that you can't answer as many questions, and that you have more questions to ask.
The reverse is also true: the more you learn, the more questions you'll be able to answer, and the fewer questions you'll have for asking others.


text:
Q: An uncountable subset in $\Bbb{R}^n$ in which each $n$ elemented subset is a base Using Zorn's Lemma I can show that there is an uncountable subset in $\Bbb{R}^n$ such that any $n$-elemented subset is independent. Can you construct such a set ??

A: $$\{\,(1,t,\ldots,t^{n-1})\mid t\in\mathbb R\,\}$$

A: Based on Hagen's answer, this one also works for $n=1$:
$$\left\{(t,t^2,\ldots,t^n)\mid t\in\mathbb{R}\setminus\{0\}\right\}$$

A: On repeated request by user dimo, here is a generalization. Again, kudos to Hagen without whose answer this would not have been given by me.
Generalization: Let $p_1,\ldots,p_n$ be polynomials from $\mathbb{R}[X]$ where $\deg p_i = i$ and $p_i(0)=0$ for $i=1,\ldots,n$. Then
$$\left\{\left(p_1(t),p_2(t),\ldots,p_n(t)\right)\mid t\in\mathbb{R}\setminus\{0\}\right\}$$
has the requested property, as we can reduce the determinants in question to a Vandermonde determinant with nonzero multipliers, and the restrictions given exclude the zero tuple.
Edit: All $p_i$ must have $p_i(0)=0$, not just $p_1$, otherwise the reduction does not work completely.


text:
Q: The roots of $ax^2+bx+c$ are 6 and $P$. The roots of $cx^2+bx+a$ are $Q$ and $R$ what is the value of $P\times Q\times R$ Problem
The roots of $ax^2+bx+c$ are 6 and $P$. The roots of $cx^2+bx+a$ are $Q$ and $R$
And we are asked to find $P\times Q\times R$ by using the identities:
$P(x)=Q(x)\times D(x)+R(x)$
where $P(x)$ is the equations and $Q(x)$ is the quotient and $D(x)$ is the divisor and $R(x)$ is the remainder.
My thought process
so I had set $$ax^2+bx+c=Q(x)\times(x-6)\times(x-P)+0$$
and in the next equation:
$$cx^2+bx+a=Q(x)\times(x-P)(x-Q)+0$$
I really don't know where to go from here

A: Hint:
Think of Vieta's relations.

A: $$ax^{ 2 }+bx+c=0\\ 6p=\frac { c }{ a } \\ cx^{ 2 }+bx+a=0\\ \\ qr=\frac { a }{ c } \\ 6pqr=1\Rightarrow \quad pqr=\frac { 1 }{ 6 } $$

A: It is true that $x=0$ is not a root of $ax^2+bx+c$, since if so then $c$ would be zero, and the second polynomial $cy^2+by+a$ is linear with at most one root. Similarly, $y=0$ is not a root of $cy^2+by+a$.
Consider
$$cy^2+by+a = y^2 \left(c+\frac by + \frac a{y^2}\right)$$
If $x=0$ is not a root of $ax^2+bx+c$, i.e. $p\ne 0$, then $y=\dfrac16$ and $y=\dfrac1p$ are the two roots of $cy^2+by+a$. Then
$$pqr = p\cdot \frac 16\cdot \frac1p$$

A: Considering roots of $ax^2+bx+c$ as $\frac{-b\pm \delta}{2a}$ the roots of $cx^2+bx+a$ will be $\frac{-b\pm \delta}{2c}$. So, the product of all the four roots are $$6PQR=\frac{(-b+ \delta)(-b-\delta)}{2a}\times\frac{(-b+ \delta)(-b-\delta)}{2c}=\frac{4ac}{4ac}=1$$ Thus, we have $$PQR=\frac16$$


text:
Q: Add remotely WordPress Posts to my blog, but how to add picture? I have this blog post on my blog:
http://lifepearls.herobo.com/2011/06/tom-hardy-is-bane/
I make posts from my php code with this:
function wpPostXMLRPC($title,$body,$rpcurl,$username,$password,$category,$keywords='',$encoding='UTF-8') {
    $title = htmlentities($title,ENT_NOQUOTES,$encoding);
    $keywords = htmlentities($keywords,ENT_NOQUOTES,$encoding);

    $content = array(
        'title'=>$title,
        'description'=>$body,
        'mt_allow_comments'=>0,  // 1 to allow comments
        'mt_allow_pings'=>0,  // 1 to allow trackbacks
        'post_type'=>'post',
        'mt_keywords'=>$keywords,
        'categories'=>array($category)
    );
    $params = array(0,$username,$password,$content,true);
    $request = xmlrpc_encode_request('metaWeblog.newPost',$params);
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
    curl_setopt($ch, CURLOPT_URL, $rpcurl);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_TIMEOUT, 1);
    $results = curl_exec($ch);
    curl_close($ch);
    return $results;

}

However, I dont know how to add the image, and what field.
Here is the image from the dashboard for the image:
http://lifepearls.herobo.com/path.jpg
This is the manual way to add my image to the post, since it is a
part of the specific template.
How do I add my image remotely, any idea?

A: We've created a plugin ( WP Remote Connections ) that can send posts, pages, and media from one WordPress installation to one or many other WordPress :) It might be what you are looking for.

A: The MetaWebLog API has no ways to transmit images or other resources. You're lost, except you transfer the images via ftp/sftp and just <img>-include them.


text:
Q: Can we customize the design of buttons in cards in microsoft bot framework I know that we can modify the design by making changes to botchat.css as per our requirement. Now, I want to know that can each button be of different color as shown in the image.

[button1] [button2] [button3]
All the buttons must be of different colors.

A: In your custom.css or whatever your custom CSS file name is you can address this by using CSS like this to account for the maximum amount of buttons you will produce on a card:
.wc-card button:nth-of-type(3) {
    background-color: green;
    color: #0078d7;
    min-height: 32px;
    width: 100%;
    padding: 0 16px;
}
.wc-card button:nth-of-type(2) {
    background-color: red;
    color: #0078d7;
    min-height: 32px;
    width: 100%;
    padding: 0 16px;
}
.wc-card button:nth-of-type(1) {
    background-color: orange;
    color: #0078d7;
    min-height: 32px;
    width: 100%;
    padding: 0 16px;
}
...

This CSS will produce this result:


text:
Q: npm permission issue in laravel docker setup If I try and run the following in my docker setup
    docker-compose run --rm npm run dev

I get the following error
> dev
> npm run development

glob error [Error: EACCES: permission denied, scandir '/root/.npm/_logs'] {
errno: -13,
code: 'EACCES',
syscall: 'scandir',
path: '/root/.npm/_logs'
 }

> development
 > cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-
 modules --config=node_modules/laravel-mix/setup/webpack.config.js

sh: 1: cross-env: not found
npm ERR! code 127
npm ERR! path /var/www/html
npm ERR! command failed
npm ERR! command sh -c cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --
progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js

Seems like a permissions issue but where how do I give permission for this, for root, uncertain where it is
This is the docker-compose.yml where I'm adding npm in docker
so not sure where to give permission to /root/.npm/_logs as that seems to be in  the application outside docker?
  version: '3'

  networks:
  laravel:

services:
 nginx:
image: nginx:stable-alpine
container_name: nginx
ports:
  - "8080:80"
volumes:
  - ./src:/var/www/html
  - ./nginx/default.conf:/etc/nginx/conf.d/default.conf
depends_on:
  - php
  - mysql
networks:
  - laravel

mysql:
image: mysql:5.7.22
container_name: mysql
restart: unless-stopped
tty: true
ports:
  - "3307:3306"
env_file:
  - src/.env
networks:
  - laravel

php:
build:
  context: .
  dockerfile: Dockerfile
container_name: php
volumes:
  - ./src:/var/www/html
ports:
  - "9000:9000"
networks:
  - laravel
npm:
 image: node:latest
container_name: npm
volumes:
  - ./src:/var/www/html
working_dir: /var/www/html
entrypoint: [ 'npm', '--no-bin-links' ]
networks:
  - laravel

A: I faced the same issue while compiling assets form inside a docker container running a laravel app.
Background:
I created the app to run as a docker container(following instructions on laravel docs), which uses laravel sail to build the containers.
After creating and running the containers, i logged into the app container(i.e.;laravel.test).

*

*Inside, I ran npm install to install node dependencies.

*Ran npm run dev
While webpack was able to successfully compile the assets, it also produced an error:

    glob error [Error: EACCES: permission denied, scandir '/root/.npm/_logs'] {
      errno: -13,
      code: 'EACCES',
      syscall: 'scandir',
      path: '/root/.npm/_logs'
    }

Since the assets were successfully compiled, i assumed it's a notice-ish error, nothing major. Still i wanted to see if i could get rid of it.
How i got rid of it:
When I entered the container, I was logged in as root. I looked up to see what other users are available in the system. I run cat /etc/passwd and noticed this line:
sail:x:1000:1000::/home/sail:/bin/bash
Which means sail was a user on the system.
So on the shell, i ran su sail to change into sail user.
Then ran npm run dev and the process finished successfully without producing that error.
    root@f0fec81c3439:/var/www/html# su sail
    sail@f0fec81c3439:/var/www/html$ npm run dev

A: In your dockerfile, add a line with:
npm config set cache /tmp --global

Or any cache folder of choice.

A: I tried it with npm run --cache /var/cache/ COMMAND and the problem was fixed!

A: In my case, npm has been ugraded, I have to downgrade npm version


text:
Q: IE not showing PDFs with object tag correctly In my application I show pdf files. In order to do it, inside a html page I use object tag inside a div tag .
The problem is that the pdf viewer in IE8 is shown on top of all other components. In other words, the pdf file hides all popups, dialogs, etc...
anyone can helps thx!
<body>
  <div>
    <object data="abc.pdf" type='application/pdf'/>
  </div>
</body>


text:
Q: Posting Objects to Facebook openGraph I'm trying to create and post custom objects to a facebook timeline via opengraph. Have followed the tutorial on facebook for developers.
I've run into a couple of errors - the first is that if i try to post the object in the suggested way from the tutorial ( using the js SDK), i get the following error message:
OG: (#3502) Object at URL http://markaprice.co.uk/2012dev/fb-ojects/dow.html has og:type of 'website'. The property 'travel_goal' requires an object of og:type 'mp-object-ns:travel_goal'
(The type is correctly set in the meta)
Having done some research, it seems that this may be due to simultaneous http requests, and one suggestion i read stated that you could force openGraph to scrape the page, then carry out your post to avoid that issue -
I have tried that, except i now hit a different error:
scrape: (#803) Some of the aliases you requested do not exist: id=http:
I have set up a very crude working example at :
http://www.markaprice.co.uk/2012dev/fb-objects/dow.html
Please could someone advise me what i am doing wrong, as i am not sure what to attempt next - thank you very much.
My code is here :
// JavaScript Document
// first things first - make call to fb.init with app id to get initial authorisation
window.fbAsyncInit = function () {
    FB.init({
        appId: 'xxxxxxxxxxxxxx',
        // App ID
        status: true,
        // check login status
        cookie: true,
        // enable cookies to allow the server to access the session
        xfbml: true // parse XFBML
    });
    // call function below
    getSocial()

};

// Load the SDK Asynchronously
(function (d) {
    var js, id = 'facebook-jssdk';
    if (d.getElementById(id)) {
        return;
    }
    js = d.createElement('script');
    js.id = id;
    js.async = true;
    js.src = "//connect.facebook.net/en_US/all.js";
    d.getElementsByTagName('head')[0].appendChild(js);
}(document));

function getSocial() {

    var elements = jQuery('.fb-ac-el-hd');

    // call to fb.getLoginStatus, and pass result tyo handleSessionResponse function
    FB.getLoginStatus(handleSessionResponse);

    // bind login click to fb.login process, pass response to function, and get required permissions as parameters of fb.login method - the scope method is used to define the permissions sought
    $('#fb-login').bind('click', function () {
        FB.login(function (response) {
            handleSessionResponse(response);
        }, {
            scope: 'user_about_me, user_hometown, user_interests, user_activities, user_likes, user_birthday, user_photos, friends_likes, publish_actions'
        });

    });

    // bind logout to fb.logout, and pass response to handleSessionResponse
    $('#logout').bind('click', function () {
        FB.logout(handleSessionResponse);

    });

    // disconnect from graphAPI completely, and revoke app authorisation - user needs to be offered the opportunity to
    $('#fb-disconnect').bind('click', function () {
        FB.api({
            method: 'Auth.revokeAuthorization'
        }, function (response) {
            clearDisplay();
        });
    });

    // handle a session response from any of the auth related calls
    function handleSessionResponse(response) {
        console.log(response);
        // if we have a connect session run the getResponse function
        if (response.status === 'connected') {
            getResponse();
            // else run the clear display function, we no longer have auth to display the users information
        } else {
            clearDisplay();
            return;
        }

    }

    // diagnostic - see what happens when shutting down machine etc
    FB.Event.subscribe('auth.authResponseChange', function (response) {
        console.log(response); // do something with response
    });

    function clearDisplay() {

        jQuery(elements).fadeOut();

        jQuery('#fb-login').fadeIn();

    }

    function getResponse() {

        // different, more flexible method of connection this time - fql.multiquery
        //can run multiple queries against the graphAPI to return data objects
        FB.api({
            method: 'fql.multiquery',
            queries: {
                queryA: 'select name, first_name, pic_square, birthday, activities, movies, books, hometown_location FROM user WHERE uid=me()',
                queryB: 'select uid, page_id, type from page_fan WHERE uid=me() and page_id = "xxxxxxxxx"',
                queryC: 'select name, pic_square from user where uid in (select uid from page_fan where page_id ="xxxxxxxxxxx" and uid in (select uid2 from friend where uid1 = me()))'
            }
        }, function (response) {

            //disagnostic only - want to see the responses for now - no need for this in a live environment
            //for (var i = 0; i < response.length; i++) {
            //console.log(response[i]);
            //}

            if (!jQuery(elements).is(':visible')) {

                jQuery(elements).fadeIn();

            }

            // reference the first object returned - response[0].fql_result_set[0]
            var user = response[0].fql_result_set[0];

            var notGiven = "This Information is not provided by this user";

            var fbUname = 'Hello,' + user.first_name;

            jQuery('#fb-name').text(fbUname);

            // grab the users big pic
            var picture = user.pic_square;
            // inject it into the iterface
            jQuery('.fb-pfl-pic').html('');

            var likesAvios = response[1].fql_result_set[0];

            /// display appropriate result
            if (likesAvios) {

            } else {

            }

            // friends list
            var friendsList = $('#fb-friends-list');

            var noFriends = "At present none of your friends like Euro Miles. Why not recommend Euro Miles to them";

            var friendResults = response[2].fql_result_set;

            if (friendResults.length < 1) {

                friendsList.append(jQuery('
' + noFriends + '
'));

            } else {

                if (jQuery('div.frnd-grid-item').length < 1) {

                    for (i = 0; i < friendResults.length; i++) {

                        friendName = friendResults[i].name;
                        friendPic = friendResults[i].pic_square;
                        friendsList.append(jQuery('

 ' + friendName + '

'));

                    }

                }

            }

        }); // close api call

        jQuery('#fb-login').fadeOut();

    } // close function

    jQuery('#postBtn').click(function () {

        postGoal();

    });

    function postGoal() {
        // set up the variables for the openGrapUrl
        var OG_NAMESPACE = 'mp-object-ns';
        var OG_ACTION = 'set';
        var OG_OBJECT = 'travel_goal';
        var siteURL = 'http://markaprice.co.uk/2012dev/fb-ojects/dow.html';
        var appid = '';

        var openGraphUrl = '/me/' + OG_NAMESPACE + ':' + OG_ACTION + '?' + OG_OBJECT + '=' + siteURL;

        // set up the scrape url
        var scrapeUrl = '/id=' + siteURL + '&scrape=true';

        function postFB() {
            // get the fb api to scrape the url first
            FB.api(scrapeUrl, 'post', function (response) {

                if (!response || response.error) {
                    console.log('scrape: ' + response.error.message);
                } else {
                    // once that is done, post the object out to to the api
                    FB.api(openGraphUrl, 'post', function (response) {
                        if (!response || response.error) {
                            console.log('OG: ' + response.error.message);
                        } else {
                            console.log('Successful! Action ID: ' + response.id);
                        }
                    });
                }

            });

        } // close postFB
        var fbPost = setTimeout(postFB, 5000);

    } // closePostGoal

} // close getSocial function


text:
Q: No source control option in SQL Server 2017 Management Studio
Screenshot above is from my SSMS 2017.
I want begin to use tfs on SQL server and I googled how to use it and apparently there should be an option for source control in tools-->option but there is no option for source control. How can I fix it?
I have VS 2017 and 2015 and I'm using tfs on vs 2017 right now. No problem there.
I have team foundation server 2018 installed too.
Thank you in advance

A: By default the packages which source control needed are not as part of SSMS.
However you can try to enable the Visual Studio packages manually. See Source Control in SQL Server Management Studio (SSMS) for details.

To enable TFS integration in SSMS, follow these steps:
1) Close SSMS if it is running.
2) Install Visual Studio 2015 on your SSMS machine. If you don't
  already have Visual Studio, Community Edition will work fine. This is
  a large download but you can save some space by unselecting all
  languages during the Visual Studio install if your only purpose is to
  enable Source Control in SSMS.
3) Edit the ssms.pkgundef file found at C:\Program Files
  (x86)\Microsoft SQL
  Server\130\Tools\Binn\ManagementStudio\ssms.pkgundef.
At the top of this file there are a series of packages grouped
  together related to TFS Source Control features. These packages must
  be removed from the pkgundef file. This can be done by either deleting
  the section or commenting out each line using '//'. Here is an example
  of what the section should look like if commented out:// TFS SCC
  Configuration entries. The TFS entries block Team Explorer from
  loading.
// Microsoft.VisualStudio.TeamFoundation.Lab
//[$RootKey$\Packages\{17c5d08a-602c-4dfb-82b5-8e0f7f50c9d7}]
// GitHub Package
//[$RootKey$\Packages\{c3d3dc68-c977-411f-b3e8-03b0dccf7dfc}]
// Team Foundation Server Provider Package
//[$RootKey$\Packages\{5BF14E63-E267-4787-B20B-B814FD043B38}]
// Microsoft.VisualStudio.TeamFoundation.WorkItemTracking.WitPcwPackage
//[$RootKey$\Packages\{6238f138-0c0c-49ec-b24b-215ee59d84f0}]
// Microsoft.VisualStudio.TeamFoundation.Build.BuildPackage
//[$RootKey$\Packages\{739f34b3-9ba6-4356-9178-ac3ea81bdf47}]
// Microsoft.VisualStudio.TeamFoundation.WorkItemTracking
//[$RootKey$\Packages\{ca39e596-31ed-4b34-aa36-5f0240457a7e}]
// Microsoft.VisualStudio.TeamFoundation
//[$RootKey$\Packages\{b80b010d-188c-4b19-b483-6c20d52071ae}]
// Microsoft.TeamFoundation.Git.Provider.SccProviderPackage
//[$RootKey$\Packages\{7fe30a77-37f9-4cf2-83dd-96b207028e1b}]
// Microsoft.VisualStudio.TeamFoundation.VersionControl.SccPcwPluginPackage
//[$RootKey$\Packages\{1b4f495a-280a-3ba4-8db0-9c9b735e98ce}]
// Microsoft.VisualStudio.TeamFoundation.VersionControl.HatPackage
//[$RootKey$\Packages\{4CA58AB2-18FA-4F8D-95D4-32DDF27D184C}]
// Visual SourceSafe Provider Package
//[$RootKey$\Packages\{AA8EB8CD-7A51-11D0-92C3-00A0C9138C45}]
// Visual SourceSafe Provider Stub Package
  [$RootKey$\Packages\{53544C4D-B03D-4209-A7D0-D9DD13A4019B}]
// Microsoft.VisualStudio.TeamFoundation.Initialization.InitializationPackage
  [$RootKey$\Packages\{75DF55D4-EC28-47FC-88AC-BE56203C9012}]
// Team Foundation Server Provider Stub Package
  [$RootKey$\Packages\{D79B7E0A-F994-4D4D-8FAE-CAE147279E21}]
// Microsoft.VisualStudio.Services.SccDisplayInformationPackage
  [$RootKey$\Packages\{D7BB9305-5804-4F92-9CFE-119F4CB0563B}]
// Microsoft.VisualStudio.TeamFoundation.Lab.LabPcwPluginPackage
   [$RootKey$\Packages\{e0910062-da1f-411c-b152-a3fc6392ee1f}]
   [$RootKey$\ToolsOptionsPages\Source Control]
   [$RootKey$\AutoLoadPackages\{11b8e6d7-c08b-4385-b321-321078cdd1f8}]
// TFS SCC Configuration entries.

Once completed, start SSMS and the "Team" menu should be visible in
  the SSMS menu bar. This menu and related features are the standard
  Visual Studio functionality. This enables connections to TFS servers
  or Git servers.


text:
Q: "Decline" text box automatically focuses and breaks tab-navigation Normally the forms used on Stack Exchange are quite handy to be used with keyboard navigation, since they respect tab order and the buttons can be activated, for example, with Space.
When you enter text in the "other" field for decline messages, and Tab to the decline button, the focus is automatically put back on the "other" field.

The same happens when you try to ShiftTab back to one of the predefined reasons. It is therefore impossible to use this form with the keyboard.
Please remove the event handler that is causing this – there is no obvious reason for forcing the user to stay in the input field.
It'd also be nice to have the focus lay on one of the elements already, so that I can start tabbing through the form right away.


text:
Q: Can I cross compile Java code that optionally uses classes from Java 8 but is compiled to Java 6? I know that cross compiled Java code cannot use new language features, IE no features like lambdas from Java 8 or try-with-resources from Java 7.
But is it possible to refer to new classes that are added in new Java versions?
Say I have a library that supports Java 6+ and I have some method that accepts a date as an argument.
For Java 6 I offer an API using java.util.Date, but for users of Java 8 I wanted to offer the option of using java.time.Instant.
I would expect the Java 6 users to be able to use the library but encounter a ClassNotFoundException if they try using the Instant method.
Is there an accepted way of doing something like this, and how would it be achieved with common build tools like Gradle or Maven?
The example given is contrived, please don't give answers on alternative approaches to dealing with time.

A: It is not possible to do cleanly.  APIs that mention Java 8 types cannot be loaded on a Java 6 JRE.
If your API uses Java 8 classes, then a Java 6 client cannot compile against it.  In theory, you could replace the Java 8 classes with (say) java.lang.Object and require the client code to cast to either java.util.Date or java.time.Instant depending on the execution platform.  But I don't see how that would be acceptable, let alone useful to programmers trying to use your libraries.
And you'd need to change your APIs anyway.

If you really need to support Java 6 and you also want to start using Java 8 features in your APIs, I would advise supporting two separate APIs:

*

*one for Java 6 that uses only Java 6, and

*another that uses Java 8 types as well.

You may be able to share some of the code behind the two versions of your APIs, but it depends on how "deep" the Java 8 dependencies go.
However, a better idea would be to bite the bullet and stop supporting Java 6 compatibility.  Java 6 reached its end-of-life in February 2013.  IMO, you are justified in putting a freeze on your Java 6 API, and then treating your Java 8 API as a new release that requires your client to switch to Java 8.

A: I think if you compile with javac (or Gradle or Maven) from Java 8 with target version Java 6 but without setting the classpaths from Java 6 it should work. But you might need to split on class level, not on method level.

A: Backporting
As the other Answers explain, basically the answer is "No". A workaround is to use code that back-ports functionality to an earlier version of Java.
Regarding the java.time classes specifically:

*

*ThreeTen-BackportMuch of the java.time functionality is back-ported to Java 6 & 7 in the ThreeTen-Backport project.

*ThreeTenABPThe above back-port is further adapted to Android in the ThreeTenABP project.


text:
Q: Data truncation: Data too long for column 'Phone' at row 1 I am inserting data into temp table in MYSQL database.I have given size of 'Phone' column as VARCHAR(20) and have inserted data of exactly 10 character and it is constant.
Here is my code:
java.sql.PreparedStatement insertStmt = null;

                 String insertQuery = "insert into "+tableName+"(";
                 for(String col : columnList){
                             insertQuery+=col+",";
                         }
                insertQuery = insertQuery.substring(0,insertQuery.lastIndexOf(","));
                         insertQuery+=") values (";
                         for(String col : columnList){
                             insertQuery+="?,";
                         }
                insertQuery = insertQuery.substring(0,insertQuery.lastIndexOf(","));
                            insertQuery+=")";
                         insertStmt = mysqlConn.prepareStatement(insertQuery);

                while(rs.next())
                     {
                    for(int j=1;j<=columnList.size();j++)
                    {
                        insertStmt.setString(j,rs.getString(j).trim());
                        System.out.println(rs.getString(j).trim());
                    }
                    insertStmt.addBatch();
                    i++;

                    }
                insertStmt.executeBatch();

                mysqlConn.setAutoCommit(true);
                rs = null;

and i am getting below error :
java.sql.BatchUpdateException: Data truncation: Data too long for column 'Phone' at row 1
Completed Temp tables 1&2
    at com.mysql.jdbc.PreparedStatement.executeBatchSerially(PreparedStatement.java:1269)
    at com.mysql.jdbc.PreparedStatement.executeBatch(PreparedStatement.java:955)
    at MultipleDataExtraction.addDataToTempTable(MultipleDataExtraction.java:132)
    at MultipleDataExtraction.addDataToFinalTempTable(MultipleDataExtraction.java:94)

Table definition :
EmpNo varchar(15) YES NULL,   Name varchar(18) YES NULL,   Address varchar(40) YES NULL,   Phone varchar(20) YES NULL,   Age varchar(4) YES NULL,  DeptNo varchar(20) YES NULL

Insert statement:
insert into temp__final_table(Name,Address,Phone,EmpNo,Age,DeptNo) values ('Clerk#000000959','Skye Norling','2112 Ravine Drive','7091581728','Clerk#000000959','26')

Please help..

A: This is your problem :
'2112 Ravine Drive'
in the insert query.
insert into temp__final_table(Name,Address,Phone,EmpNo,Age,DeptNo) values ('Clerk#000000959','Skye Norling','2112 Ravine Drive','7091581728','Clerk#000000959','26')

You are inserting address in the phone field.
Also, 'Clerk#000000959' seems to be the EmpNo. You seem to be inserting it in multiple columns in the same row.
Also, a suggestion would be to use numeric fields where necessary. Your DeptNo looks like a perfect candidate for integer type. You don't need to use varchar for all columns.
Hope this helps!!!


text:
Q: open()/Path.open(): only create the file on actual writing Is there a way to "lazy" open a file in Python?
If I do Path("my_path").open("wb"), the file will be created and be empty until I write on it. What I want is for the file to not be created until I actually call the write() function on it.
In my specific case, I am opening a streaming request and heuristically determining the filetype from the first chunk, and if I don't open the file before iterating through the chunks I'll have to open and close the handler continuously. Right now I have to unlink the file and open a separate one if I determine that the url's extension is wrong, but I was looking for a more elegant solution.


text:
Q: Why "this.setState()" thows a warning for unmounted component? I get the Warning "Can only update a mounted or mounting component. This usually means you called setState, replaceState, or forceUpdate on an unmounted component. This is a no-op" at following code. At GitHub you can find the full working react-navigation example with firebase and Redux. I think the problem could be seen if a more skilled person than me looks at the code.
I not know how to compensate this warning, when i jump beck from "roles2" to the "home" navigation. Could you find the bug?
import React, { Component } from "react";
import { Text, View, TouchableHighlight, TouchableOpacity, ListView, StatusBar, ScrollView, StyleSheet } from "react-native";
import Styles from "./../../App.scss";
import Firebase from "./../Util/database";
import Item from "./item";
const Uuid = require('uuid/v1');
import FontAwesome from 'react-native-vector-icons/FontAwesome';
import { NavigationActions, SafeAreaView } from "react-navigation";
import { connect } from "react-redux";

var db = Firebase.firestore();

const list = ['Loading...']

export default class Empty extends Component {

constructor(props) {
  super(props);
  this.ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2})

  this.state = {
    dataSource: this.ds.cloneWithRows(list),
  };

  this.roles = db.collection("roles").get();
  this.renderItem = this.renderItem.bind(this)
  this.setItemsFromFirestore = this.setItemsFromFirestore.bind(this);
}

setItemsFromFirestore(roles) {
  roles.then((querySnapshot) => {
  // get children as an array
  var items = [];
  querySnapshot.forEach((child) => {
    items.push({
      label: `${child.data().label}`,
      description: `${child.data().description}`,
      id: `${child.id}`
    });
  });

  this.setState({
    dataSource: this.ds.cloneWithRows(items),
  });
});
}

componentWillUpdate(nextProps, nextState) {
  this.roles = db.collection("roles").get();
  this.setItemsFromFirestore(this.roles);
}

componentDidMount() {
  this.setItemsFromFirestore(this.roles);
}

renderItem(item, navigation) {
  return (
   <Item key={Uuid()} label={item.label} description={item.description} onPress={ () => {
    const param = item.param;
    const route = item.route;
    const navigateAction = NavigationActions.navigate({
      routeName: 'role',
      params: {
        label: `${item.label}`,
        description: `${item.description}`,
        id: `${item.id}`
      }
    });
    navigation.dispatch(navigateAction);
  }} />
 )
}

static navigationOptions = props => {
  const { navigation } = props;
  const { state, setParams } = navigation;
  const { params } = state;
  return {
  title: "Rollen (Cloud)",
  headerTintColor: Styles.ci_Header.color,
  headerStyle: {
    height: Styles.ci_Header.height,
    backgroundColor: Styles.ci_Header.backgroundColor
  },
  headerRight: (
    <FontAwesome
      name= {'plus'}
      size={18}
      style={{ color: Styles.ci_Header.color, paddingHorizontal: 5}}
      onPress={() => {
        const id = `${Uuid()}`;
        var data = {
          id: {id},
          label: `Neue Rolle (${id.substring(0,6)}...)`,
          description: ''
        };
        var setDoc = db.collection('roles').doc(id).set(data);
      }}
    />
  )
 };
};

render() {
 return (
  <View style={{ flex: 1 }}>
    <ListView
        dataSource={this.state.dataSource}
        renderRow={item => this.renderItem(item, this.props.navigation)} />
    <StatusBar barStyle="light-content" />
  </View>
  );
 }
}

I am new to react-native with navigation and did not get what i did wrong.
Could you find the bug?

A: This error means you are calling the setState method even after the component is unmounted. This is usually caused by the asynchronous API call. So your API call returned result after you have moved to a different page. To avoid this warning, you can set a variable to true in the component class in componentDidMount and check if that variable has true value before calling the setState method.
componentDidMount(){
  this.isMounted = true;
}

fetchData(){
 if(this.isMounted){
  this.setState();
 }
}

A: I found a solution, but am not satisfied. I use
this.mounted = false;
this.state = {
  isMounted: true,
  ...
};

On unmount i use
componentWillUnmount() {
   this.mounted = false;
   this.setState( {isMounted: false} );
   console.log('Will Unmount '+componentName);
}

And now watch. On componentWillUpdate i log
 console.log("mounted?: "+this.state.isMounted +" (isMounted-Stat) - "+this.mounted+" (mounted)");

and the console throws
13:28:53: Will Update roles2
13:28:53: Will Unmount roles2
13:28:53: mounted?: true (isMounted-Stat) - false (mounted)

That means i can use this.mounted when i define it as parameter inside the component, but the State is NOT updated with Unmount. This is not logical in my point of view, but i live with it. With this solution (constructor, componentWillUnmount, componentWillUpdate) it works and the warning ist gone.
I really like to prefer a better way, because the warning is throws when the component was left AFTER the Unmount. So somewhere the function setState is called even if the component was left an unmounted. And when i call setState in unmount the parameter is NOT set.