text:
Q: pass array between 2 activity with intent i'm trying to pass one array
[the array is inizialized by me {1,2,3,4} and i associate the string "txx"]
between two activity but i recive this error
java.lang.runtimeexception: unable to start activity
componentinfo{com.example.android.bluetoothlegatt/com.example.android.bluetoothlegatt.graphcurrentactivity}:
java.lang.nullpointerexception: attempt to read from null array

from debug mode i see that this array doesn't pass between two activity. i think that there can be an error in delcaration private/public variable..
please help me
activity A
public class BluetoothLeService extends Service {
private final static String TAG = BluetoothLeService.class.getSimpleName();

private BluetoothManager mBluetoothManager;
private BluetoothAdapter mBluetoothAdapter;
private String mBluetoothDeviceAddress;
private BluetoothGatt mBluetoothGatt;
private int mConnectionState = STATE_DISCONNECTED;

private static final int STATE_DISCONNECTED = 0;
private static final int STATE_CONNECTING = 1;
private static final int STATE_CONNECTED = 2;

public final static String ACTION_GATT_CONNECTED =
        "com.example.bluetooth.le.ACTION_GATT_CONNECTED";
public final static String ACTION_GATT_DISCONNECTED =
        "com.example.bluetooth.le.ACTION_GATT_DISCONNECTED";
public final static String ACTION_GATT_SERVICES_DISCOVERED =
        "com.example.bluetooth.le.ACTION_GATT_SERVICES_DISCOVERED";
public final static String ACTION_DATA_AVAILABLE =
        "com.example.bluetooth.le.ACTION_DATA_AVAILABLE";
public final static String EXTRA_DATA =
        "com.example.bluetooth.le.EXTRA_DATA";
public final static String EXTRA_DATA2 =
        "com.example.bluetooth.le.EXTRA_DATA2";
public final static String EXTRA_DATA3 =
        "com.example.bluetooth.le.EXTRA_DATA3";
public final static String EXTRA_DATA4 =
        "com.example.bluetooth.le.EXTRA_DATA4";
public final static String EXTRA_DATA5 =
        "com.example.bluetooth.le.EXTRA_DATA5";
public final static String EXTRA_DATA6 =
        "com.example.bluetooth.le.EXTRA_DATA6";
public final static String EXTRA_DATA7 =
        "com.example.bluetooth.le.EXTRA_DATA7";

byte[] value;
int[] data_info = new int[6];
public int[] grap_curr = new int[] {0,0,0,0,0,0,0,0,0,0};
public int[] grap_volt = new int[] {0,0,0,0,0,0,0,0,0,0};
public int[] grap_temp = new int[] {0,0,0,0,0,0,0,0,0,0};
public int[] grap_soc = new int[] {0,0,0,0,0,0,0,0,0,0};
public int[] grap_soh = new int[] {0,0,0,0,0,0,0,0,0,0};
int i = 0;
int j = 0;

public final static UUID UUID_USER_DATA =
        UUID.fromString(SampleGattAttributes.FIRST_NAME);
public ArrayList<String> receivedPackets = new ArrayList<String>();
// Implements callback methods for GATT events that the app cares about.  For example,
// connection change and services discovered.
private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
    @Override
    public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
        String intentAction;
        if (newState == BluetoothProfile.STATE_CONNECTED) {
            intentAction = ACTION_GATT_CONNECTED;
            mConnectionState = STATE_CONNECTED;
            broadcastUpdate(intentAction);
            Log.i(TAG, "Connected to GATT server.");
            // Attempts to discover services after successful connection.
            Log.i(TAG, "Attempting to start service discovery:" +
                    mBluetoothGatt.discoverServices());

        } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
            intentAction = ACTION_GATT_DISCONNECTED;
            mConnectionState = STATE_DISCONNECTED;
            Log.i(TAG, "Disconnected from GATT server.");
            broadcastUpdate(intentAction);
        }
    }

    @Override
    public void onServicesDiscovered(BluetoothGatt gatt, int status) {
        if (status == BluetoothGatt.GATT_SUCCESS) {
            broadcastUpdate(ACTION_GATT_SERVICES_DISCOVERED);
        } else {
            Log.w(TAG, "onServicesDiscovered received: " + status);
        }
    }

    @Override
    public void onCharacteristicRead(BluetoothGatt gatt,
                                     BluetoothGattCharacteristic characteristic,
                                     int status) {
        if (status == BluetoothGatt.GATT_SUCCESS) {
            broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
        }
    }

    @Override
    public void onCharacteristicChanged(BluetoothGatt gatt,
                                        BluetoothGattCharacteristic characteristic) {
        broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
    }
};

private void broadcastUpdate(final String action) {
  final Intent intent = new Intent(action);
sendBroadcast(intent);
}

private void broadcastUpdate(final String action,final BluetoothGattCharacteristic characteristic) {
    final Intent intent = new Intent(action);
    /* Creo le Intent per passare i dati da visualizzare sui grafici alle altre classi */
    Intent intentCurr = new Intent(getApplicationContext(), GraphCurrentActivity.class);
    //final Intent intentVolt = new Intent(getApplicationContext(), GraphVoltageActivity.class);
    //final Intent intentTemp = new Intent(getApplicationContext(), GraphTempActivity.class);
    //final Intent intentSoC = new Intent(getApplicationContext(), GraphSoCActivity.class);
   //final Intent intentSoH = new Intent(getApplicationContext(), GraphSoHActivity.class);

    if (UUID_USER_DATA.equals(characteristic.getUuid())) {
        int flag = characteristic.getProperties();
        int format = -1;
        if ((flag & 0x01) != 0) {
            format = BluetoothGattCharacteristic.FORMAT_UINT16;
            Log.d(TAG, "Value format UINT16.");
        } else {
            format = BluetoothGattCharacteristic.FORMAT_UINT8;
            Log.d(TAG, "Value format UINT8.");
        }

            value = characteristic.getValue();
            ByteBuffer bb = ByteBuffer.wrap(value);
            bb.order(ByteOrder.LITTLE_ENDIAN);

            i++;

        if (value != null && value.length > 0) {
                final StringBuilder stringBuilder = new StringBuilder(value.length);
                for(byte byteChar : value)
                    stringBuilder.append(String.format("%02X ", byteChar));

            //su value ho la stringa ricevuta, quindi posso elaborare il dato per far si che leggo sulla app quello che voglio

            Byte b5 = value[5];
            Byte b6 = value[6];
            Byte b7 = value[7];

            data_info[0] = ((value[1] << 8) | (value [2] & 0xFF));//current
            data_info[1] = ((value[3] << 8) | (value [4] & 0xFF));//voltage
            data_info[2] = b5.intValue();//soc
            data_info[3] = b6.intValue();//temp
            data_info[4] = b7.intValue();//soh
            data_info[5] = ((value[8] << 8) | (value [9] & 0xFF));

            //preparo i dati da passare alle alre activity
            grap_curr[j]=data_info[2];
            grap_volt[j]=data_info[2];
            grap_temp[j]=data_info[2];
            grap_soc[j]=data_info[2];
            grap_soh[j]=data_info[2];
            j++;

            //dopo 10 cicli invio ai grafici
            if (j==3){
                intent.putExtra(EXTRA_DATA7, "Riepilogo temporale disponibile");
                Bundle curr =new  Bundle (); //array da mandare alla activity GraphCurrentActivity
                curr.putIntArray("txxx",new int[] {1,2,3,4});
                intentCurr.putExtras(curr);
                //intentCurr.putExtra("tx",grap_curr);
                //intentCurr.putExtra("datavectorcurr",new int[] {1,2,3,4,5,6,7,8,9,10});
                //intentVolt.putExtra("datavectorvolt",new int[] {1,2,3,4,5,6,7,8,9,10});
                //intentTemp.putExtra("datavectortemp",new int[] {1,2,3,4,5,6,7,8,9,10});
                //intentSoC.putExtra("datavectorsoc",new int[] {1,2,3,4,5,6,7,8,9,10});
                //intentSoH.putExtra("datavectorsoh",new int[] {1,2,3,4,5,6,7,8,9,10});
                j=0;
            }

            //inserisco i dati negli appositi campi
            intent.putExtra(EXTRA_DATA,  "Battery Current: " + Integer.toString(data_info[0]) + " [A]" );
            intent.putExtra(EXTRA_DATA2, "Battery Voltage: " + Integer.toString(data_info[1]) + " [V]" );
            intent.putExtra(EXTRA_DATA3, "SOC: " + Integer.toString(data_info[2]) + " [Ah]" );
            intent.putExtra(EXTRA_DATA4, "SOH: " + Integer.toString(data_info[4]) + " [%]");
            intent.putExtra(EXTRA_DATA5, "average temperature: " + Integer.toString(data_info[3]) + " [°C]");
            intent.putExtra(EXTRA_DATA6, "remaining capacity: " + Integer.toString(data_info[5]) + " [°Ah]");

        }

    }

    sendBroadcast(intent);
}

public class LocalBinder extends Binder {
    BluetoothLeService getService() {
        return BluetoothLeService.this;
    }
}

@Override
public IBinder onBind(Intent intent) {
    return mBinder;
}

@Override
public boolean onUnbind(Intent intent) {
    // After using a given device, you should make sure that BluetoothGatt.close() is called
    // such that resources are cleaned up properly.  In this particular example, close() is
    // invoked when the UI is disconnected from the Service.
    close();
    return super.onUnbind(intent);
}

private final IBinder mBinder = new LocalBinder();

/**
 * Initializes a reference to the local Bluetooth adapter.
 *
 * @return Return true if the initialization is successful.
 */
public boolean initialize() {
    // For API level 18 and above, get a reference to BluetoothAdapter through
    // BluetoothManager.
    if (mBluetoothManager == null) {
        mBluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
        if (mBluetoothManager == null) {
            Log.e(TAG, "Unable to initialize BluetoothManager.");
            return false;
        }
    }

    mBluetoothAdapter = mBluetoothManager.getAdapter();
    if (mBluetoothAdapter == null) {
        Log.e(TAG, "Unable to obtain a BluetoothAdapter.");
        return false;
    }

    return true;
}

/**
 * Connects to the GATT server hosted on the Bluetooth LE device.
 *
 * @param address The device address of the destination device.
 *
 * @return Return true if the connection is initiated successfully. The connection result
 *         is reported asynchronously through the
 *         {@code BluetoothGattCallback#onConnectionStateChange(android.bluetooth.BluetoothGatt, int, int)}
 *         callback.
 */
public boolean connect(final String address) {
    if (mBluetoothAdapter == null || address == null) {
        Log.w(TAG, "BluetoothAdapter not initialized or unspecified address.");
        return false;
    }

    // Previously connected device.  Try to reconnect.
    if (mBluetoothDeviceAddress != null && address.equals(mBluetoothDeviceAddress)
            && mBluetoothGatt != null) {
        Log.d(TAG, "Trying to use an existing mBluetoothGatt for connection.");
        if (mBluetoothGatt.connect()) {
            mConnectionState = STATE_CONNECTING;
            return true;
        } else {
            return false;
        }
    }

    final BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
    if (device == null) {
        Log.w(TAG, "Device not found.  Unable to connect.");
        return false;
    }
    // We want to directly connect to the device, so we are setting the autoConnect
    // parameter to false.
    mBluetoothGatt = device.connectGatt(this, false, mGattCallback);
    Log.d(TAG, "Trying to create a new connection.");
    mBluetoothDeviceAddress = address;
    mConnectionState = STATE_CONNECTING;
    return true;
}

/**
 * Disconnects an existing connection or cancel a pending connection. The disconnection result
 * is reported asynchronously through the
 * {@code BluetoothGattCallback#onConnectionStateChange(android.bluetooth.BluetoothGatt, int, int)}
 * callback.
 */
public void disconnect() {
    if (mBluetoothAdapter == null || mBluetoothGatt == null) {
        Log.w(TAG, "BluetoothAdapter not initialized");
        return;
    }
    mBluetoothGatt.disconnect();
}

/**
 * After using a given BLE device, the app must call this method to ensure resources are
 * released properly.
 */
public void close() {
    if (mBluetoothGatt == null) {
        return;
    }
    mBluetoothGatt.close();
    mBluetoothGatt = null;
}

/**
 * Request a read on a given {@code BluetoothGattCharacteristic}. The read result is reported
 * asynchronously through the {@code BluetoothGattCallback#onCharacteristicRead(android.bluetooth.BluetoothGatt, android.bluetooth.BluetoothGattCharacteristic, int)}
 * callback.
 *
 * @param characteristic The characteristic to read from.
 */
public void readCharacteristic(BluetoothGattCharacteristic characteristic) {
    if (mBluetoothAdapter == null || mBluetoothGatt == null) {
        Log.w(TAG, "BluetoothAdapter not initialized");
        return;
    }
    mBluetoothGatt.readCharacteristic(characteristic);
}

/**
 * Enables or disables notification on a give characteristic.
 *
 * @param characteristic Characteristic to act on.
 * @param enabled If true, enable notification.  False otherwise.
 */
public void setCharacteristicNotification(BluetoothGattCharacteristic characteristic,
                                          boolean enabled) {
    if (mBluetoothAdapter == null || mBluetoothGatt == null) {
        Log.w(TAG, "BluetoothAdapter not initialized");
        return;
    }
    mBluetoothGatt.setCharacteristicNotification(characteristic, enabled);

    // This is specific to Heart Rate Measurement.
    if (UUID_USER_DATA.equals(characteristic.getUuid())) {
        BluetoothGattDescriptor descriptor = characteristic.getDescriptor(
                UUID.fromString(SampleGattAttributes.CLIENT_CHARACTERISTIC_CONFIG));
        descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
        mBluetoothGatt.writeDescriptor(descriptor);
    }
}

/**
 * Retrieves a list of supported GATT services on the connected device. This should be
 * invoked only after {@code BluetoothGatt#discoverServices()} completes successfully.
 *
 * @return A {@code List} of supported services.
 */
public List<BluetoothGattService> getSupportedGattServices() {
    if (mBluetoothGatt == null) return null;

    return mBluetoothGatt.getServices();
}

public void readCustomCharacteristic() {
    if (mBluetoothAdapter == null || mBluetoothGatt == null) {
        Log.w(TAG, "BluetoothAdapter not initialized");
        return;
    }
    /*check if the service is available on the device*/
    BluetoothGattService mCustomService = mBluetoothGatt.getService(UUID.fromString("0000181c-0000-1000-8000-00805f9b34fb"));
    if(mCustomService == null){
        Log.w(TAG, "Custom BLE Service not found");
        return;
    }

    BluetoothGattCharacteristic mNotifyCharacteristic = mCustomService.getCharacteristic(UUID.fromString("00002a8a-0000-1000-8000-00805f9b34fb"));
    UUID uuid = UUID.fromString("00002902-0000-1000-8000-00805f9b34fb");
    BluetoothGattDescriptor descriptor = mNotifyCharacteristic.getDescriptor(uuid);
    descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
    mBluetoothGatt.writeDescriptor(descriptor);
    //To receive notification in Android is mandatory to set characteristic notification to true
    mBluetoothGatt.setCharacteristicNotification(mNotifyCharacteristic, true);

    /*get the read characteristic from the service*/
    BluetoothGattCharacteristic mReadCharacteristic = mCustomService.getCharacteristic(UUID.fromString("00002A8A-0000-1000-8000-00805F9B34FB"));
    if(mBluetoothGatt.readCharacteristic(mReadCharacteristic) == false){
        Log.w(TAG, "Failed to read characteristic");
    }
}

public void writeCustomCharacteristic(int value) {
    if (mBluetoothAdapter == null || mBluetoothGatt == null) {
        Log.w(TAG, "BluetoothAdapter not initialized");
        return;
    }
    /*check if the service is available on the device*/
    BluetoothGattService mCustomService = mBluetoothGatt.getService(UUID.fromString("0000181c-0000-1000-8000-00805f9b34fb"));
    if(mCustomService == null){
        Log.w(TAG, "Custom BLE Service not found");
        return;
    }
    /*get the write characteristic from the service*/
    BluetoothGattCharacteristic mWriteCharacteristic = mCustomService.getCharacteristic(UUID.fromString("00002a8a-0000-1000-8000-00805f9b34fb"));
    mWriteCharacteristic.setValue(value,android.bluetooth.BluetoothGattCharacteristic.FORMAT_UINT8,0);
    if(mBluetoothGatt.writeCharacteristic(mWriteCharacteristic) == false){
        Log.w(TAG, "Failed to write characteristic");
    }
}

}
activty B
public class GraphCurrentActivity extends Activity {

private XYPlot plot;
private GoogleApiClient client;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.layout);

    // initialize our XYPlot reference:
    plot = (XYPlot) findViewById(R.id.plot);

    Bundle b=this.getIntent().getExtras();
    int[] arraydata;
    arraydata = b.getIntArray("txxx");//array that i don't recive

    // create a couple arrays of y-values to plot:
    final Number[] domainLabels = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    //Number[] series1Numbers = {plottdata[0], plottdata[1], plottdata[2], plottdata[3], plottdata[4], plottdata[5], plottdata[6], plottdata[7], plottdata[8], plottdata[9]};
    Number[] series1Numbers = {11, 12, 13, 14, 0, 5, 8, 7, 1, 11};
    // turn the above arrays into XYSeries':
    // (Y_VALS_ONLY means use the element index as the x value)
    XYSeries series1 = new SimpleXYSeries(
            Arrays.asList(series1Numbers), SimpleXYSeries.ArrayFormat.Y_VALS_ONLY, "Battery Current Plot");

    LineAndPointFormatter series1Format = new LineAndPointFormatter(Color.RED, Color.GREEN, Color.BLUE, null);

    series1Format.setInterpolationParams(
            new CatmullRomInterpolator.Params(10, CatmullRomInterpolator.Type.Centripetal));

    // add a new series' to the xyplot:
    plot.addSeries(series1, series1Format);

    plot.getGraph().getLineLabelStyle(XYGraphWidget.Edge.BOTTOM).setFormat(new Format() {
        @Override
        public StringBuffer format(Object obj, StringBuffer toAppendTo, FieldPosition pos) {
            int i = Math.round(((Number) obj).floatValue());
            return toAppendTo.append(domainLabels[i]);
        }

        @Override
        public Object parseObject(String source, ParsePosition pos) {
            return null;
        }
    });
    client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}

public Action getIndexApiAction() {
    Thing object = new Thing.Builder()
            .setName("GraphCurrent Page") // TODO: Define a title for the content shown.
            // TODO: Make sure this auto-generated URL is correct.
            .setUrl(Uri.parse("http://[ENTER-YOUR-URL-HERE]"))
            .build();
    return new Action.Builder(Action.TYPE_VIEW)
            .setObject(object)
            .setActionStatus(Action.STATUS_TYPE_COMPLETED)
            .build();
}

@Override
public void onStart() {
    super.onStart();

    client.connect();
    AppIndex.AppIndexApi.start(client, getIndexApiAction());
}

@Override
public void onStop() {
    super.onStop();

    AppIndex.AppIndexApi.end(client, getIndexApiAction());
    client.disconnect();
}
}

A: Best solution I can suggest is define your array as
public static int[] xyz=new int[]{1,2,3,4};

And now that static int array can be called or used from any activity provided if they are in the same package.
Here for your example in GraphCurrentActivity,
Add this import statement:
import static yourpackagename.BluetoothLeService.xyz;

//And these lines to read that array:
int[] arraydata;
    arraydata = xyz;

And let me know if this was wrong.


text:
Q: Can not figure out why mysqli_num_rows is not working on my query function userexists($username){
    $query=$mysqli->query("SELECT username FROM accounts WHERE username='$username' AND exists=1");
    return mysqli_num_rows($query);
}

This function should be returning 1 or 0 but I can not figure out why the query is not being interpreted. What's wrong?
Edit: the error being returned by php is that $query is a boolean being fed into mysqli_num_rows, not an object.

A: In your query:
SELECT username FROM accounts WHERE username='$username' AND exists=1"

exists is a MySQL keyword. If you've used it as a column name then you'll get a syntax error. You could enclose the column name in back-ticks like this:
SELECT username FROM accounts WHERE username='$username' AND `exists`=1"

It's probably safer to change the column name and your query.
Be careful of possible SQL Injection attacks. At the very least you should escape any user-supplied data with mysqli_real_escape_string($username)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Display * for password in  in VF page I am using following code to display the password on the VF page:
<apex:pageBlockSectionItem helpText="Docusign Password">
                        <apex:outputLabel value="Password" />
                        <apex:inputSecret value="{!docusignTestPassword}" label="Password"/>
                    </apex:pageBlockSectionItem>

But, on VF page, the password field is displayed as blank. I want password fields to display *.

A: In order to render the previously entered value in the masked format, you will have to set the redisplay attribute of <apex:inputSecret> to true. By setting this attribute to true, it will display your value from controller in masked format.
From the salesforce documentation at this link, redisplay attribute on <apex:inputSecret> is

A Boolean value that specifies whether a previously entered password
  is rendered in this form. If set to true, the previously entered value
  is displayed with its mask. If not specified, this value defaults to
  false.

So, your visualforce page should be
<apex:pageBlockSectionItem helpText="Docusign Password">
    <apex:outputLabel value="Password" />
    <apex:inputSecret value="{!docusignTestPassword}" label="Password" redisplay="true"/>
</apex:pageBlockSectionItem>

Ideally, it should display you an input box with masked values.

A: <apex:inputSecret value="{!docusignTestPassword}" label="Password" redisplay="true"/>
Be advised that if the merge variable docusignTestPassword has a value and anyone displays the contents of the page in HTML, they will see the value="" attribute on the page with the old value.  So, unless you mask the old value on the back end after retrieving it, the tag only protects against a look-over-the-shoulder take of an attack.  Anyone getting to the page will have access to the prior value.
It's also rather annoying in that when you start typing in the field, it doesn't completely erase the prior value.


text:
Q: Computing intersections between a large number of sets: doing it sequentially vs. sending everything to Intersection[...] Say we want to compute the largest common subset among a very large number of sets $Q_i$.  One option would be to simply run the command:
Intersection[Q1, Q2, Q3, Q4, Q5, Q6, Q7, ...];

However, this seems to choke for very large numbers of input sets ($10^4$ or so with on-order $10^2$ elements each).  Another option would be compute Q12 = Intersection[Q1,Q2], then Q123 = Intersection[Q12,Q3], then Q1234 = Intersection[Q123,Q4], and so forth.
Are these two procedures equivalent?  Is there a better way?

A: As Kuba notes using Fold is the most canonical way to implement your "sequential" algorithm in Mathematica.  Performance it best determined by simply Timing your operation.
SeedRandom[1]
sets = RandomInteger[200, {10000, 1600}];

Intersection @@ sets // Timing
Fold[Intersection, #, {##2}] & @@ sets // Timing

{0.983, {12, 90, 94, 101, 164}}

{1.045, {12, 90, 94, 101, 164}}

(Timings performed in Mathematica 7 under Windows 7.)
So we see that the sequential method is if anything slightly slower than the direct application of Intersection.  I think it is probable that Intersection is already using this algorithm.
Regarding your second question:  Is there a better way?  There can be, depending on your data.  In the example above there is a lot of duplication within each set, and eliminating this beforehand greatly speeds the operation of Intersection:
Intersection @@ (DeleteDuplicates /@ sets) // Timing

{0.172, {12, 90, 94, 101, 164}}


text:
Q: What is the best way to update a group of rows in laravel think my table is like this
+--------+-------------------+-----------+
| ID     | Type              |  nOrder   |
+--------+-------------------+-----------+
| 1      | A                 | 0         |
| 2      | A                 | 1         |
| 3      | A                 | 2         |
| 4      | B                 | 0         |
| 5      | B                 | 1         |
| 6      | B                 | 2         |
| 7      | B                 | 3         |
| 8      | B                 | 4         |
| 9      | C                 | 0         |
| 10     | C                 | 1         |
+--------+-------------------+-----------+

and i have an array like this
+--------+-------------------+-----------+
| ID     | Type              |  nOrder   |
+--------+-------------------+-----------+
| 5      | A                 | 0         |
| 4      | A                 | 1         |
+--------+-------------------+-----------+

i want to update my table with these new rows in laravel,
is there any way to this in laravel without a loop? if not how can i do it with sql statment.
in php and mysqli i could create a query of all of my updates query, then sending them in a query , a query with 10 update statement , now how could i do this in laravel???

A: What about Mass updates
Model::where('type', 'A')->where('nOrder', '<', 2)->update(['foo' => 'bar'])

Your attributes have to be set in $fillable in your model. In other words, you must add $fillable = ['foo'] to your model.

A: IMO There is no "laravel way" of doing something like this, At some level like this you have to iterate over Array or Laravel Collection to update individual records. Because these are updates and each having different Identity Column.
On the other hand if your identity column matches multiple records laravel supports Mass Update, i.e. in case your where clause matches more then one elements.
App\Flight::where('active', 1)
          ->where('destination', 'San Diego')
          ->update(['delayed' => 1]);

A: You can only update with same values for each record.
$values = [['Type' => 'A'],['nOrder' => '0']];
DB::table('table_name')->whereIn('id', [4, 5])->update($values);

A: If you want to do this using a single query in mySQL, you have 2 options.
Option 1: Use the replace into mysql construct like so:
$query = "replace into {$table} values (?, ?, ?), (?, ?, ?)";
$insertArray = [[5, "A", 0], [4, "A", 1]];
DB::insert($query, array_flatten($insertArray));

Option 2: Use the insert into on duplicate key mysql construct like so:
$query = "insert into {$table} values (?, ?, ?), (?, ?, ?) on duplicate key update ID = VALUES(ID), Type = VALUES(Type), nOrder = VALUES(nOrder)";
$insertArray = [[5, "A", 0], [4, "A", 1]];
DB::insert($query, array_flatten($insertArray));

The difference between the 2 constructs is that replace into either
  inserts (for a new row) or deletes then inserts (for an existing row).
  However, insert into on duplicate key performs an insert for a new row
  and update for an existing row

You may use this package for both options
An alternative, if you need speed of execution but also don't want to use raw queries like this is to use database transactions


text:
Q: os x gui api clarification If I wanted to write my own window manager for OS X (please dont respond with "whats the point"??), what APIs should I be looking at?

A: There is no such thing as a "window manager" in OS X, and no public interface to implement one.  The functions that an X11 window manager would perform are split between the GUI toolkit (Carbon/Cocoa), the Dock application and the window server.
Your only real choice if you want to change OS X's windowing behavior is to patch individual applications, the Dock (which has a privileged connection to the window server) and/or the window server.  It'd involve a great deal of reverse engineering and almost certainly break in 10.6, but it's certainly possible.

A: At the hardware level, write your own APIs.
Otherwise, there are various graphics architectures in which to plug in your window manager:

*

*OpenGL

*Quartz

*Quicktime

*X11


text:
Q: set image size for thumbnail image generated using AVAssetImageGenerator ios I was using AVAssetImageGenerator class for generating thumbnail image but problem is i need to fit that thumbnail image into UITableViewCell having UIImageView of size (320,239).
I specified AVAssetImageGenerator maximum size property as (320,239) but i was not getting desired size what i specified please any help thanks in advance. Please look at the following code for quick reference.
    AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:self.consenteeVideoUrl options:nil];

AVAssetImageGenerator *gen = [[AVAssetImageGenerator alloc] initWithAsset:asset];

gen.maximumSize = CGSizeMake(320, 239);

gen.apertureMode = AVAssetImageGeneratorApertureModeProductionAperture;

gen.appliesPreferredTrackTransform = YES;

CMTime time = CMTimeMakeWithSeconds(0.0, 600);

NSError *error = nil;

CMTime actualTime;

CGImageRef image = [gen copyCGImageAtTime:time actualTime:&actualTime error:&error];

UIImage *thumbnailImage = [[UIImage alloc] initWithCGImage:image];
//thumbnailImage = [CSUtilities imageWithImage:thumbnailImage scaledToSize:CGSizeMake(320, 239)];
CGImageRelease(image);

One more solution i got from "stackoverflow" but not much helpful in my scenario.`
AVURLAsset *asset=[[AVURLAsset alloc] initWithURL:self.consenteeVideoUrl options:nil];
AVAssetImageGenerator *generator = [[AVAssetImageGenerator alloc] initWithAsset:asset];
generator.appliesPreferredTrackTransform=TRUE;

CMTime thumbTime = CMTimeMakeWithSeconds(30,30);

AVAssetImageGeneratorCompletionHandler handler = ^(CMTime requestedTime, CGImageRef im, CMTime actualTime, AVAssetImageGeneratorResult result, NSError *error){
    if (result != AVAssetImageGeneratorSucceeded) {
        NSLog(@"couldn't generate thumbnail, error:%@", error);
    }

    UIImage *thumbnailImage = [[UIImage alloc] initWithCGImage:im];
    //save image to application directory...
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *folderPath = [documentsDirectory stringByAppendingPathComponent:self.uniqueCodeString];
    if (![[NSFileManager defaultManager] fileExistsAtPath:folderPath])
        [[NSFileManager defaultManager] createDirectoryAtPath:folderPath  withIntermediateDirectories:NO attributes:nil error:&error];

    NSString *savedImagePath = [folderPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.png",self.uniqueCodeString]];
    NSData *imageData = UIImagePNGRepresentation(thumbnailImage);
    BOOL success = [imageData writeToFile:savedImagePath atomically:YES];
    if (success) {
        CSLog(@"sucess");
    }
    partnerEvent.thumbnailImageStr = [self getImagePath];
    [self.ibPartnerEventTableView reloadData];
 };

 CGSize maxSize = CGSizeMake(320, 239);
 generator.maximumSize = maxSize;
 [generator generateCGImagesAsynchronouslyForTimes:[NSArray arrayWithObject:[NSValue valueWithCMTime:thumbTime]] completionHandler:handler];

A: Nothing is wrong in your code, but as stated in the documentation

AVAssetImageGenerator scales images such that they fit within the
  defined bounding box. Images are never scaled up. The aspect ratio of
  the scaled image is defined by the apertureMode property.

Since the apertureMode is set to AVAssetImageGeneratorApertureModeProductionAperture images generated keeps the aspect ratio. it will only fit the maximum size if the the video and the size set have the same aspect ratio, and this will unlikely to happen with the size specified.
Try to change the UIImageView contentMode to UIViewContentModeScaleAspectFill some content could be cropped but you will fill the entire imageView


text:
Q: Not able to print the data with getData() Function I am trying to join two tables with join operation
$layoutscoll = Mage::getModel('pdp/pdplayouts')->getCollection();
$query = $layoutscoll->getSelect()
    ->join(array('layoutsides'=>'mst_pdp_multisides'), 'main_table.id= layoutsides.id', array());
echo $query;
print_r($query->getData());

When I print this $query using echo it shows an "SQL query" it's works on PhpMyadmin SQL queries. But I want print this in blocks or templates by using getData() it shows error. I think that getData() function not works here

A: $query in your case is an instance of Zend_Db_Select that does not have the method getData.
I assume you want to print the results of the query.
You can do that with print_r($layoutscoll->getIterator()).
That might not work either. You may get a long object printed. if it does not work try with
foreach ($layoutscoll as $item) {
    print_r($item->getData());
}


text:
Q: Extract substring that starts and ends with symbol and replace with variable in Python I'm trying to extract a word from a string in Python that's padded with %% on each side, and replace it with a variable value based on the value of the substring.
Something like this:
 name1 = "Alice"
 name2 = "Bob"
 date = datetime.datetime.now()

 input = "Hi, my name is %%name1%%. Today is %%date%%"
 output = ##Find and Replace Line Here
 print output

which would result in "Hi, my name is Bob. Today is 2015-10-19 23:07:17.342105".
I found the replace() method, I'm only able to find and replace the whole substring with a preset value, like this:
print input.replace("%%name0%%", "name1")

Is there a way to first extract the value of a substring before replacing it?

A: Any reason you wouldn't just use python's format string substitution?
>>> args = {
...     'name1': "Alice",
...     'name2': "Bob",
...     'date': datetime.datetime.now()
... }
>>> print "Hi, my name is {name1}. Today is {date}".format(**args)
Hi, my name is Alice. Today is 2015-10-20 01:21:36.020427

You could always map %%name1%% to {name1} and do the above if you must use %%name1%%


text:
Q: RaisePropertyChanged of dependent property is called only once I'm programming a WPF application with VS 2015.
In my window i have per example a TextBox and a ToggleButton for switching between FontWeights.Bold and FontWeights.Normal.
In my ViewModel i have two properties. One for the IsChecked-property of the ToggleButton and the other for the FontWeight of the TextBox.
/// <summary>
/// Gets or sets if the button setFontBold is checked.
/// </summary>
private bool? setFontBoldIsChecked = false;
public bool? SetFontBoldIsChecked
{
    get { return setFontBoldIsChecked; }
    set
    {
        setFontBoldIsChecked = value;
        RaisePropertyChanged("SetFontBoldIsChecked");
        RaisePropertyChanged("TextFontWeight");
    }
}

/// <summary>
/// Gets the fontweight depending on SetFontBoldIsChecked.
/// </summary>
public FontWeight TextFontWeight
{
    get { return (setFontBoldIsChecked == true) ? FontWeights.Bold : FontWeights.Normal; }
}

The FontWeight-property of the TextBox is bound like that:
<TextBox x:Name="textbox1" FontWeight="{Binding TextFontWeight}"/>

And the IsChecked-property of the ToggleButton is bound to SetFontBoldIsChecked:
<ToggleButton x:Name="setFontBold" IsChecked="{Binding SetFontBoldIsChecked}"/>

When i start the application and click the ToggleButton, so IsEnabled is true, the text appears bold.
But if i try this one more time, RaisePropertyChanged("TextFontWeight") doesn't call the Getter of TextFontWeight.
Why does this happen?
Thanks in advance!
Patrick

A: Thanks to a colleague i have found it out!
In the XAML all attributes have to be set:
<TextBox x:Name="textForTextProperty" FontWeight="{Binding TextFontWeight, Mode=TwoWay, NotifyOnSourceUpdated=True, UpdateSourceTrigger=PropertyChanged}"/>

And the properties in the viewmodel have to be changed a little bit:
/// <summary>
/// Gets or sets if the button setFontBold is checked.
/// </summary>
private bool? setFontBoldIsChecked = false;
public bool? SetFontBoldIsChecked
{
    get { return setFontBoldIsChecked; }
    set
    {
        setFontBoldIsChecked = value;
        RaisePropertyChanged("SetFontBoldIsChecked");
        RaisePropertyChanged("TextFontWeight");
    }
}

/// <summary>
/// Gets the fontweight depending on SetFontBoldIsChecked.
/// </summary>
private FontWeight textFontWeight;
public FontWeight TextFontWeight
{
    //get { return textFontWeight; }
    get
    {
        textFontWeight = (SetFontBoldIsChecked == true) ? FontWeights.Bold : FontWeights.Normal;
        return textFontWeight;
    }
    set
    {
        textFontWeight = value;
        RaisePropertyChanged("TextFontWeight");
    }
}

Now it works.


text:
Q: Is it possible to compute income percentile, given the median and the average? In Romania, the median net income in 2013 was 284 EUR/month, the average net income (unfortunately, in 2014, not in 2013 as the previous data point, but lets assume the same amount for 2013 for simplicity) was 423 EUR/month.
Is it possible from these 2 data points to compute the percentile rank of a net income of, lets say, 2000 EUR/month?
I've googled for an algorithm to compute this, but unfortunately I couldn't find any.

A: In short, no. It could be consistent with a wide variety of different values.
If you make some assumptions about the distributional form, then in some cases you could estimate it, but you'll be almost wholly reliant on the correctness of the assumption and being without any data to check it against, it would seem like a highly risky thing to do.
Sometimes income is modelled using a lognormal distribution, for example, but it's at best a very rough approximation, and it isn't always suitable. For example, sometimes income distributions are multimodal, but most of the common models are not.
If you have some other information about Romanian income distribution, you may be able to do better.


text:
Q: Route call to external db host to internal docker container I have a legacy codebase which I've put into a Docker container (phph:7.4.30-apache-buster) to run locally along with a separate database container. The codebase has various db calls to an external database. For unfortunate reasons the database host is hard coded and can't be updated/modified at this time to a better solution.
My solution is to route the database host IP to the Docker database container.
I tried:

docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' <database_container_id>

iptables -t nat -A OUTPUT -d <external_database_ip> -j DNAT --to-destination <container_ip>

This isn't working. I'm getting Access denied for user when I run mysql from the shell inside the app container.


text:
Q: Can i change the number of cells in collectionView based on the tableView Section iOS Swift? I have 2 arrays
var list3:Array< String > = Array < String >()
var list4:Array< String > = Array < String >()

I need to return the count of list 3 if the tableview Section is 0
and
I need to return the count of list 4 if the tableview Section is 4
How can i do this ?
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        switch(section){
             case 0 : return list3.count
             case 1 : return list4.count
             default : return 0
          }
    }

it is not working...

A: In the overrided func of the UITableViewController when you create the UITableViewCell you will get from the indexPath the section and the row and you will set up your collection view inside the cell
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
  let cell = ...
  if(indexPath.row == 3 && indexPath.section == 1){
     cell.numberOfCells = 123
   }
  }

A: Reading your question and some of the comments and your answers, I understand is :

you have a table view; in that table view one of the tableview cell (TVC) has a collection view. And based on whether this TVC is in section 0 or 1, you need yo decide number of elements that collection view.

You can achieve this by:

*

*Setting tag value of collection view to appropriate section number
when you are creating the TVC.

*Then based on this tag, you can
decide whether to populate the collection view using list3 or list4.

*If my understanding on your problem and suggested solution looks fine
and you need code snippet, do let me know and I will add it. Thanks.


text:
Q: How to add default selected element in Symfony forms? I want to add a default selected option in the select tag
Here's the code:
->add('datefinProjet', 'date', array(
'label'=>'Date fin Projet :',
'years' => range(date('Y') - 20, date('Y') - 100),
'empty_value' => array('years'=>'' , 'month' => '', 'day' =>'' )))

I want the select list to start with the empty value ''

A: You have a error in your empty_value parameter. Should be 'year', not 'years'
    $builder->add('datefinProjet', 'date', array(
        'label'=>'Date fin Projet :',
        'years' => range(date('Y') - 20, date('Y') - 100),
        'empty_value' => array('year' => '', 'month' => '', 'day' => '')
    ));

Source: Docs


text:
Q: Express/MongoDB - Unexpected behavior during a database operation I have a list of users that I try to store/update into my mongoDB database.
But only the last element from my list is taken into account, the others users don't enter into then function.
I'm newbie in Nodejs and this seems to be due to a synchronicity behavior that I don't understand.
var User = require('../to/path/user-service');
....
userList.forEach(function(user) {
    try {
            User.updateUser(user);
    } catch(err) {
        return console.error(err);
    }

});

user-service
...
var User = mongoose.model('User', userSchema);
console.log(user.name);
export.updateUser = function (user) {
    Issue.findOne({name: user.name})
        .then((user) => {
            if(user) console.log(user.name + ' has been updated');
            else console.log(user.name + ' has been created');
    }).catch((err) => console.error(err));
};

Ouput
John
Paul
Alex
Alex has been created
Alex has been created
Alex has been created

A: The problem has to do with JavaScript closures. When you add a function to the function queue, it and its variables are added. In this case the variable user is added. When the function terminates and the updateUser() functions are called, the user variable is Alex, so Alex gets added three times. Read more about closures here: https://developer.mozilla.org/en/docs/Web/JavaScript/Closures
Here is one way to fix your issue:
userList.forEach(function(user) {
    var closureUser = user;
    try {
            console.log(closureUser.name);
            closureUser.updateUser(closureUser);
    } catch(err) {
        return console.error(err);
    }
});


text:
Q: Why have I got MySQL sleeping connections when not using mysql_pconnect() An Apache Bench test revealed that high throughput on the database caused the following...

*

*Apache threads stuck in "Sending Reply" state, all related to a particular PHP file (as seen in Apache extended status).

*MySQL sleeping connections with the same user as used by the PHP file.

Note: Apache Bench was used from a remote location as a mechanism for stressing the database only, ie a script just connected to the DB and ran 5 queries per load.
Running the same Apache Bench tests, but introducing a mysql_close() at the end of the script solved the problem. What I'd like to understand is why this happens.
A popular theory internally we have is that:

*

*The increased throughput on the database somehow prevented Apache from serving its requests properly. A buffer somewhere, either in MySQL or at the OS level got filled up.

*The Apache requests therefore got stuck in a Sending Reply state, and because there was no mysql_close() at the end of the PHP file a database connection remained open - probably only to expire once MySQL's connection timeout limit was reached and the MySQL connection was closed. To be clear, we are not using mysql_pconnect(), but we are using mysql_connect().

As above, whilst we've 'solved' the problem we'd love to get to the bottom of this with a solid answer rather than an educated guess.
Anyone experienced this before and know of a solution? Any tricks/thoughts/methods of identifying this.


text:
Q: Set static text color Win32 I am making a dll that controls a dialogue box.  I like to get a certain area to have red text.  This code does compile, but the effect is not seen.  Here is the area where the dialogProc is done:
LRESULT CALLBACK DialogProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
    switch(message)
    {
    case WM_INITDIALOG:
        CheckDlgButton(hDlg, IDC_CHECK, FALSE);
        EnableWindow(GetDlgItem(hDlg, IDOK), FALSE);
        return TRUE;

    case WM_COMMAND:
        switch (LOWORD(wParam))
        {
        case IDC_CHECK:
            if (IsDlgButtonChecked(hDlg, IDC_CHECK))
            {
                EnableWindow(GetDlgItem(hDlg, IDOK), TRUE);
                EnableWindow(GetDlgItem(hDlg, IDCANCEL), FALSE);
            }
            else
            {
                EnableWindow(GetDlgItem(hDlg, IDOK), FALSE);
                EnableWindow(GetDlgItem(hDlg, IDCANCEL), TRUE);
            }
            break;
        case IDOK:
            {
                EndDialog(hDlg, TRUE);
                return FALSE;
            }
        case IDCANCEL:
            {
                EndDialog(hDlg, FALSE);
                return FALSE;
            }
        case WM_CTLCOLORSTATIC:
            // Set the colour of the text for our URL
            if ((HWND)lParam == GetDlgItem(hDlg,IDC_WARNING))
            {
                // we're about to draw the static
                // set the text colour in (HDC)lParam
                SetBkMode((HDC)wParam,TRANSPARENT);
                SetTextColor((HDC)wParam, RGB(255,0,0));
                return (BOOL)CreateSolidBrush (GetSysColor(COLOR_MENU));
            }
    return TRUE;
        }
    }
    return FALSE;
}

A: WM_CTLCOLORSTATIC is a separate message from WM_COMMAND. Your desired handling of the message appears to be correct except that the check for the message is inside your check for WM_COMMAND specific items. Try reorganizing your outer switch statement. Perhaps something like the following:
LRESULT CALLBACK DialogProc(HWND hDlg, UINT message,
                            WPARAM wParam, LPARAM lParam)
{
    switch(message)
    {
    case WM_INITDIALOG:
        // ...
        break;
    case WM_COMMAND:
        switch (LOWORD(wParam))
        {
        case IDC_CHECK:
            // ...
            break;
        case IDOK:
            // ...
            break;
        case IDCANCEL:
            // ...
            break;
        }
        break;
    case WM_CTLCOLORSTATIC:
        // Set the colour of the text for our URL
        if ((HWND)lParam == GetDlgItem(hDlg, IDC_WARNING))
        {
                // we're about to draw the static
                // set the text colour in (HDC)lParam
                SetBkMode((HDC)wParam,TRANSPARENT);
                SetTextColor((HDC)wParam, RGB(255,0,0));
                // NOTE: per documentation as pointed out by selbie, GetSolidBrush would leak a GDI handle.
                return (BOOL)GetSysColorBrush(COLOR_MENU);
        }
        break;
    }
    return FALSE;
}

Also note that it would be kinda weird to filter WM_COMMAND's wParam argument when wParam is supposed to provide the HDC for WM_CTLCOLORSTATIC.
WM_CTLCOLORSTATIC Notification at MSDN


text:
Q: im having trouble figuring out how this nested functions get the values. can someone pls explain it to me. the code works btw im having trouble figuring out how this works. can someone pls explain it to me. the code works btw.
def foo(x, y):
def goo(x, y):

    x = 2*x

    y = 3*y

    z = x+y

    print('x =', x, '; y =', y, '; z =', z)

    return z

def hoo(x, y):

    x = x//2

    y = y//3

    z = x+y

    print('x =', x, '; y =', y, '; z =', z)

    return z

z = hoo(x,y) + goo(y,x)

print('x =', x, '; y =', y, '; z =', z)

return z

x = 10

y = 20

z = 30

print('x =', x, '; y =', y, '; z =', z)

z = foo(x,y)

print('x =', x, '; y =', y, '; z =', z)

A: To understand how a code works, just follow the functions.
foo is called. Since integer types are immutable  (wikipedia) in foo(x,y) x and y are copies of the x and y you gave as parameters.
In python expression are evaluated from left to right therefore.
First function hoo is called (same remark about parameters) the value of x and y are changed and z is computed you get ('x =', 5, '; y =', 6, '; z =', 11) and  the value z (11) is returned.
Once outside hoo function x and y at this level are respectively 10 and 20 because they were not changed (immutable thing… see above) . Then function goo is called.  (same remark about parameters) (warning you enter y for parameter x of goo and x for parameter y of goo) the value of x and y are changed and z is computed you get ('x =', 40, '; y =', 30, '; z =', 70) and  the value z (70) is returned.
Once outside goo function x and y at this level are respectively 10 and 20 because they were not changed (immutable thing… see above).
The sum function between the two values returned by hoo and goo is done. z= 11 + 70. you get ('x =', 10, '; y =', 20, '; z =', 81) and z is returned.
Then outside foo function. x and y at this level are respectively 10 and 20 because they were not changed (immutable thing… see above) . z is given the value of the return function foo therefore z=81
And you get ('x =', 10, '; y =', 20, '; z =', 81)


text:
Q: Why does this realloc() fail? My first C project is a simple cURL-like HTTP client that retrieves the headers, content, and status of a request sent to a server. It's been working out so far, but it is not finished and I need some help. Memory allocation has been a bit of a hurdle for me and this current issue is one I cannot solve by myself.
In a function called HTTPresponse *requestHTTPresponse(URLdata *requestDestination), the reallocation of a string that holds the raw HTTP response headers and contents fails for some unknown reason. The pointer for the raw HTTP response string is set to NULL, and I'm forced to exit my program. Why is this behavior happening and how do I solve it? Additionally, when I compile my program, it sometimes just freezes and refuses to print out text as intended or to exit, which could be the result of DNS hanging up or some other odd network issue. Any other advice is also welcome.
The full C source code can be found here.
HTTPresponse *requestHTTPresponse(URLdata *requestDestination) {
    char ip[INET6_ADDRSTRLEN], *request, *response = malloc(1), *headerTerminator = NULL, *responseTerminator = NULL, *headerString, *contentString, buffer[100];
    int sockfd, bufferLength, responseLength;
    struct addrinfo hints, *servinfo, *p;

    /* Initialize HTTP response structure */
    HTTPresponse *returnresponse = malloc(sizeof(HTTPresponse));
    returnresponse->status = 0;
    returnresponse->headers = NULL;
    returnresponse->content = NULL;

    /* Retrieve IP address of host */
    memset(&hints, 0, sizeof hints);
    hints.ai_family = AF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;
    if (getaddrinfo(requestDestination->host, requestDestination->port, &hints, &servinfo) != 0) {
        return returnresponse;
    }

    /* Loop through all possible connections */
    for (p = servinfo; p != NULL; p = p->ai_next) {
        if ((sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) {
            continue;
        }
        if (connect(sockfd, p->ai_addr, p->ai_addrlen) == -1) {
            close(sockfd);
            continue;
        }
        break;
    }

    if (p == NULL) {
        return returnresponse;
    }

    /* Print IP address & free server information */
    inet_ntop(p->ai_family, get_in_addr((struct sockaddr*)p->ai_addr), ip, sizeof(ip));
    //printf("The IP address is: %s\n", ip);
    freeaddrinfo(servinfo);

    /* Format HTTP request */
    request = malloc(27 + (int)strlen(requestDestination->path) + (int)strlen(requestDestination->host) * sizeof(char));
    if (request == NULL) {
        printf("Failure to allocate memory.\n");
        exit(1);
    }
    sprintf(request, "GET %s HTTP/1.1\r\nHost: %s\r\n\r\n", (*(requestDestination->path) == 0)?"/":requestDestination->path, requestDestination->host);

    /* Send HTTP request */
    send(sockfd, request, 26 + strlen(requestDestination->path) + strlen(requestDestination->host), 0);
    free(request);

    /* Receive HTTP response */
    do {
        bufferLength = recv(sockfd, buffer, 99, 0);
        if (bufferLength == -1) {
            break;
        }
        responseLength += bufferLength;
        response = realloc(response, (responseLength + 1) * sizeof(char)); //Source of issues
        if (response == NULL) {
            printf("Failure to allocate memory.\n");
            exit(2);
        }
        strncpy(response + responseLength - bufferLength, buffer, bufferLength);
        if (headerTerminator) {
            responseTerminator = strstr(response, "\r\n\r\n");
        } else {
            headerTerminator = strstr(response, "\r\n\r\n");
        }
    } while (responseTerminator == NULL);

    /* Store data in structs */
    headerString = malloc((headerTerminator - response + 1) * sizeof(char));
    if (headerString == NULL) {
        printf("Failure to allocate memory.\n");
        exit(1);
    }
    strncpy(headerString, response, headerTerminator - response);
    contentString = malloc((responseTerminator - headerTerminator) * sizeof(char));
    if (contentString == NULL) {
        printf("Failure to allocate memory.\n");
        exit(1);
    }
    strncpy(contentString, headerTerminator, responseTerminator - headerTerminator);
    returnresponse->headers = generateHeaderList(headerString);
    returnresponse->content = contentString;
    free(response);

    /* Close connection & return HTTP response */
    close(sockfd);
    return returnresponse;
}

A: Make sure your variables are initialized.  In the original question, you were trying to realloc a null pointer, and you need to be sure your responselength variable is initialized to 0.
----- EDIT -----
Also, when grabbing data from a network connection, be sure your strings are zero-terminated if you use functions like strcpy.


text:
Q: Regex to identify Aadhaar Number I have been facing some challenges in writing regex to search Aadhaar number in DLP.
Actually the inbuilt pattern is as below :
\b[2-9][0-9]{11}\b
\b[2-9][0-9]{3} [0-9]{4} [0-9]{4}\b

However above pattern works fine but it gives many false cases by reading digits in vertical manner also.
Below will be treated as Aadhaar by reading it vertically which I don't want it to happen.
Eg.
2355(New Line)
2345(New Line)
7868

Also I want it to restrict search for 12 digits only , if digits are 13 or 11 then do not count it.
I tried below please suggest if it is fine to search entire document if it has Aadhaar number
^[2-9][0-9]{3}\s[0-9]{4}\s[0-9]{4}$

A: Your RegEx looks right to me.
But keep in mind that your solution is for multi-line search (^ and $ match start/end of the line).
You can experiment with it in this regex101 share link.
Also, you can check this geeksforgeeks.org post for more details.

After reading the comment below I revised my answer to this:

\b[2-9][0-9]{3}[^\S\r\n][0-9]{4}[^\S\r\n][0-9]{4}\b

I used Greg Bacon's answer for matching whitespace but not newlines and combined it with yours. Check the updated regex101 share link to test it furthermore.

Good luck.


text:
Q: Join navigation property with line I try to join a navigation property by using LINQ.
This is my code
    var activities = Using<GetActivitiesForUser>()
        .Execute(User.DisplayAs, User.MarketId);

    var contacts = Using<GetContactsForUser>()
        .Execute(User.DisplayAs, User.MarketId);

    var model = from activity in activities
                join contact in contacts
                on activity.ContactId equals contact.ContactId
                select activity;

This code will only select the activity without any join.
The activity has a property named Contact, and i want to join that property from Contacts.
UPDATE
Example to solve it
foreach(var activity in activities)
{
activity = from contact in contacts
where contact.ContactId=activity.ContactId
select contact
}

But i want to do this with a join.

A: It looks like you are using the Entity Framework
try
var model = activities.Include("Contact");

A: You must include both activities and contacts in the query result:
from activity in activities
join contact in contacts
on activity.ContactId equals contact.ContactId
select new { activity, contact };

or select individual properties of both objects.
Edit After your comment:
You won't be able to let Dapper populate activity.contact, it is deliberately kept simple. What you can do is loop through the results and set the property yourself:
foreach(var anon in model)
{
    anon.activity.contact = anon.contact;
}

where model is the query .ToList().
Another effective, but ugly way could be:
model.Select(x => { x.activity.contact = x.contact; return activity; }).ToList();

Which immediately returns the modified activities. It is ugly because it abuses a method that is intended to be stateless (Select), but yeah...


text:
Q: Facing Bootstrap Icons alignment issue I am using bootstrap navbar, it has brand name on left and 2 icons glyphicon glyphicon-user and glyphicon glyphicon-bell on right.
When i am changing the resolution to less than 768, the brand name and both the icons are getting vertically aligned and height of navbar increases.

I do no want a collapse bar. and i want the icons to be fixed at right.

A: Use pull-left and pull-right with 2 navbar-header div's, since they do not attached to any @media queries.
Try this

  Brand

  <button type="button" class="btn btn-default navbar-btn"></button>
  <button type="button" class="btn btn-default navbar-btn"></button>

Working Codepen

A: @Lior G is right, you can use default bootstrap styles (classes) to resolve your issue!

      Brand

jsfiddle-link


text:
Q: How to close dropdown checklist when clicked outside of it but prevent it from closing when textarea is selected? I created a dropdown checklist which opens a textarea when the last option is checked.
I need to be able to close the dropdown when I click outside of it.
I'm using this code for it
    <!DOCTYPE html>

    <meta charset="utf-8">
    <title>Title</title>
    <meta name="author" content="">

                                    -- Selecteer uw reparatie --

                                            <input id="dropdown-check-list-01" type="checkbox" />
                                            option 1

                                            <input id="dropdown-check-list-02" type="checkbox" />
                                            option 2

                                            <input id="dropdown-check-list-07" type="checkbox" name="messagetick" />
                                            Other

                                                <textarea name="setmessage" cols="25" rows="5"></textarea>

This part of the script is what I use to close the dropdown when clicked outside.
checkList.on( "blur", function(){
    element.removeClass('visible');
});

The problem I have is that it also closes the dropdown when I try to write into the textarea. How do I set this up so it doesn't close the dropdown when textarea is selected?

A: A friend of mine helped me solve this, so I'll post it here for anyone who encounters the same problem.
$(document).mouseup(function (e) {
    var container = $('.dropdown-check-list');

    if (!container.is(e.target) && container.has(e.target).length === 0) {
        container.removeClass('visible');
    }
});

A: Not sure to really understand.
I made a few cleanups for testing and everything seems fine : http://jsfiddle.net/xp1fv43b/
HTML :

    -- Selecteer uw reparatie --

            <input id="dropdown-check-list-01" type="checkbox" />
            Option 1

            <input id="dropdown-check-list-02" type="checkbox" />
            Option 2

            <input id="messagetick" type="checkbox" name="messagetick" />
            Other

                <textarea name="setmessage" cols="25" rows="5"></textarea>

JS :
$(document).ready(function(){
     $('input[name="messagetick"]').click(function() {
         $('.contactmessage').toggle(this.checked);
     });

    $('input[name="messagetick"]').change(function(){
        if($(this).is(":checked")) {
        $('li.other').addClass("checked");
       } else {
       $('li.other').removeClass("checked");
    }
   });
}


text:
Q: Django running on Postgre extremely slow on only 100 data Recently I added 100 fake data to one of my models in Django, however, now the age is taking forever, to load. for getting Post objects in my view I do:
posts = Post.objects.select_related('author').all().order_by('-last_edited')

my Post model is:
class Post(models.Model):
    title = models.CharField(max_length=100)
    guid_url = models.CharField(max_length=255,unique=True, null=True)
    content = models.TextField(validators=[MaxLengthValidator(1200)])
    author = models.ForeignKey(Profile, on_delete=models.CASCADE)
    date_posted = models.DateTimeField(auto_now_add=True)
    last_edited= models.DateTimeField(auto_now=True)
    tags = TaggableManager(help_text="Tags", blank=True)
    likes= models.ManyToManyField(Profile, blank=True, related_name='post_likes')

I am using Postgre SQL as my database but I do not know what's causing this issue. Since I believe 100 data should be easily handled. Can it be because of something in my template?
Now inside my template (It is very long so I do not want the question to get messy) I have for instance liking the post, images, ... ) But I am not doing any heavy queries inside the template.
EDIT
I also want to add that every time my template loads I keep getting this error.
Exception happened during processing of request from ('127.0.0.1', 65283)
Traceback (most recent call last):
  File "/Users/apple/opt/anaconda3/lib/python3.7/socketserver.py", line 650, in process_request_thread
    self.finish_request(request, client_address)
  File "/Users/apple/opt/anaconda3/lib/python3.7/socketserver.py", line 360, in finish_request
    self.RequestHandlerClass(request, client_address, self)
  File "/Users/apple/opt/anaconda3/lib/python3.7/socketserver.py", line 720, in __init__
    self.handle()
  File "/Users/apple/Documents/Project/stumatch/denvx/lib/python3.7/site-packages/django/core/servers/basehttp.py", line 174, in handle
    self.handle_one_request()
  File "/Users/apple/Documents/Project/stumatch/denvx/lib/python3.7/site-packages/django/core/servers/basehttp.py", line 182, in handle_one_request
    self.raw_requestline = self.rfile.readline(65537)
  File "/Users/apple/opt/anaconda3/lib/python3.7/socket.py", line 589, in readinto
    return self._sock.recv_into(b)
ConnectionResetError: [Errno 54] Connection reset by peer

I'd like to add that on the debugger toolbar my CPU time is 95000ms while my querytime is only 1000, I do not know if that is a lot or not?
I believe these are the additional queries:
In my template which loads every post I have:
{% include 'home/posts/likes.html' with post=post %}
{% include 'main/bookmark/bookmark_dropdown.html' with hid=post.get_hashid t="post" %}

Now inside likes.html:
I have this which I believe is accessing the database:
{% if request.user in post.likes.all %}

and in bookmarks.html:
{% is_bookmarked as bookmarked %}

Which is bookmarked is a template tag which does the following:
@register.simple_tag(takes_context=True)
def is_bookmarked(context):
    request = context['request']
    id =  hashids.decode(context['hid'])[0]
    if context['t'] == 'post':
        return BookmarkPost.objects.filter(user__id=request.user.id, obj__id=id).exists()
    elif context['t'] == 'blog':
        return BookmarkBlog.objects.filter(user__id=request.user.id, obj__id=id).exists()
    elif context['t'] == 'buzz':
        return BookmarkBuzz.objects.filter(user__id=request.user.id, obj__id=id).exists()

Which I believe is accessing the database as well.


text:
Q: Integration by parts of a normalized function - [copied from Physics.SE] By using integration by parts, I need to show for $$A = \frac{\mathrm d}{\mathrm dx} + \tanh x, \qquad A^{\dagger} = - \frac{\mathrm d}{\mathrm dx} + \tanh x,$$  that

$$\int_{-\infty}^{\infty}\psi^* A^{\dagger}A\psi\;\mathrm dx = \int_{-\infty}^{\infty}(A\psi)^*(A\psi)\;\mathrm dx $$

Where $\psi$ is a normalized wavefunction. I thought that this was the definition of the Hermitian conjugate of an operator $A$, but the problem asks for me to use integration by parts. I don't really see where the result is going to come from here, surely it is not messy calculation, since it is true in general, right?
I started by by integrating by parts, noting that the surface terms must vanish since $\psi$ is normalized, but after that I just get into a big mess...

I asked this question of Physics.SE and didn't get an answer. I then asked in the Maths meta if it would be OK for me to post the question here and I was told that it would be fine to do so, so here it is. Thank you.


text:
Q: jacob - Can't co-create object My environment is Java 7, on Windows 7 - 64 bit. So here's my requirement and procedures I followed

*

*I wanted to execute a library called test.dll from Java

*I first downloaded the latest version of jacob, and put them within a folder, which is included in the Windows environment variable PATH.

*I registered the test.dll using regsvr32.exe under C:\Windows\SysWOW64 (it was successful!)

*I am running jacob from a webapp, so I made sure that WEB-INF/lib has jacob.jar in it.

*I also set a java System property - -Djava.library.path=c:/dev/jacob/jacob-1.17-x64.dll (This is where I have kept the jacob-1.17-x64.dll)

still I am facing
com.jacob.com.ComFailException: Can't co-create object
    at com.jacob.com.Dispatch.createInstanceNative(Native Method)
    at com.jacob.com.Dispatch.<init>(Dispatch.java:99)

I have gone through many of the SO posts but none of them have helped me so far
can anyone please guide me to the solution?

A: A similar problem for me was solved by changing the jdk from a 64-bit to 32-bit.

A: Looking at the source code of Jacob Dispatch, line 99 (http://jacob-project.cvs.sourceforge.net/viewvc/jacob-project/jacob/src/com/jacob/com/Dispatch.java?revision=1.18&view=markup), the error is not within Jacob (at least not the Java code).
Before digging into the Jacob native code, I would try to create this COM object in another container, say an Excel macro or Windows Scripting Host. I believe you will find the same error, or at least will be able to determine if Jacob is the culprit or not. I suspect not.


text:
Q: How to emulate lists in HTML? I'm converting a word document into HTML by hand so that it'll look nice when published on the Amazon Kindle. However, I'm having trouble getting the table of contents to look right.
Basically, I want the TOC to look something like what you'd get with an ordered list, but with custom list items:
Table of Contents
Preface: My Example

*

*The First Chapter

*Apples

*Yadda Yadda...

Epiogue: The End
Appendix
How can I get the "Preface", "Epilogue", and "Appendix" labels to align themselves with the "1", "2" and "3" in the list? How can I get the preface and epilogue titles (i.e., "My Example", and "The End") to align with all the rest of the chapter titles? I realize it probably can't be an actual HTML list tag, but how might I achieve the appearance?
Note - this must render on a Kindle. No javascript or anything fancy.

*

*EDIT:

I'm sorry if something like this has been asked before. I can't figure out a concise way to phrase this question, which makes searching for it difficult.

A: I can't say I've had experience formatting HTML specifically for rendering on the Kindle but the follwing basic HTML and CSS should work.
HTML:

Table of Contents

Preface: My Example

The First Chapter

Apples

Yadda Yadda...

Epilogue: The End

Appendix

CSS:
#toc {margin:0; padding:0; }
#toc li { margin:0 0 .5em 1.25em; }
#toc li.no { margin-left:0; list-style:none; }

Demo: jsfiddle.net/BdfEE
It uses a deprecated value attribute on the second
 but if it works then great. If not you can try the CSS method of changing the numbering of an ordered list, however I'd imagine this possibly not working, depending on Kindle's CSS capabilities.

A: put them in an unordered list with no bullet marker then they should align with the other list


text:
Q: How to draw polygon on Google Maps using API v3 with SQL Server and Visual Studio 2008 C#? I had uploaded my shapefile to SQL Server by using Shape2SQL and now I have this table with a column named "geom" and the data is in this format:
POLYGON(Longitude,Latitude)
Now I do not know where to start. I want to use the data in "geom" to draw polygons on Google Maps using C# and Google Maps API v3. I had googled about this but still unable to get a clear idea on how to do it.
Can you guys please help?

A: You should use Javascript.
This shouldn't be too hard to learn with a few examples as Google has this well documented. HereIs the section on overlaying polygons.
Full reference guide is here.
There are some third party API wrappers, like Google Maps API for .NET, but these are unlikely to be as full featured. Using Javascript is going to be the easiest way to accomplish what you are after, even if you already know some C#.


text:
Q: Python function taking a lot longer than before? I had used gensim and Word Mover's distance to generate a distance matrix for my text of ~4000. The first time I ran it, it took about a day or so. I am trying to run it again and it is taking more than 4 days so far. Another function that runs KMedoids usually takes minutes but now takes days. I have tried using garbage collector to clear up some memory but that hasn't solved anything.
import gc
gc.collect()

I've tried restarting my computer but that also didn't help. I'm not sure what to do to fix this.


text:
Q: House keeping removing 30+ days old files using shell script So I have to bit of housekeeping for old backups and have the following code working on sh:
find /home/backups -mtime +30 -type f -exec rm -rf {} \;

This works fine as know the location/path, so if the path is diff on another machine how can I modify the command to work on all machines?
If I use the command below that will delete all files 30 days old but I'm only looking to clean up these unique set of backup files only:
find . -mtime +3 -exec rm {} ';'

Thanks

A: I don't know how would you execute the command on all machines, automatically via ssh? or manually?
anyway, if you want to save the effort of typing path, you may consider that on each machine create a variable with same name, e.g. BACKUP_DIR, it saves the path you need to do the cleaning job.
Then, in your find command, don't hardcode any path, but use the variable.
if you do it automatically via ssh, you know the path when you establish the connection. then just add the path in your find.


text:
Q: Why does tensor product in Ab(V) require colimits in V? In Tom Leinster's book on operads, he gives Ab(V), the category of abelian groups in a symmetric monoidal category V, as an example of a multicategory that doesn't arise from a monoidal category, since Ab(V) will not generally have a tensor product. Example 2.1.5 on page 37.
I can't quite understand this. Why do you need colimits in V to define tensor product in Ab(V)? What is the definition exactly of a tensor product? I know it as the universal object representing bilinear morphisms in some multicategory, and from that definition it's not clear how colimits in some category help it exist.
Actually I have a more basic question about this setup: Can you define group objects in an arbitrary symmetric monoidal category? I thought you could only define monoid objects, and you needed a Cartesian monoidal category to define a group object. Cartesian monoidal categories have the diagonal morphism which you need to define inverses, whereas general monoidal categories do not, right?

A: It is easy to define the tensor product as being the object that represents the bilinear maps functor, but to prove that tensor products exist requires something extra. If you have free abelian groups, then it is enough to have coequalisers of abelian groups to construct the tensor product, but even the construction of coequalisers of abelian groups can be quite non-trivial.
I'm more familiar with the case where the base category $\mathcal{V}$ is cartesian closed, so I'll briefly mention the extra structures we need to get tensor products in $\textbf{Ab}(\mathcal{V})$:

*

*If $\mathcal{V}$ has countable colimits and is a well-powered regular category, then the forgetful functor $\textbf{Ab}(\mathcal{V}) \to \mathcal{V}$ is strictly monadic. (In particular, it has a left adjoint.) A proof can be extracted by chasing the references in theorem 2.4.21 of my notes. Moreover these hypotheses suffice to show $\textbf{Ab}(\mathcal{V})$ has coequalisers for all parallel pairs: combine proposition 2.4.7 (ii) and theorem 2.4.21 (ii).

*Once we know that $\textbf{Ab}(\mathcal{V})$ has coequalisers of reflexive pairs and that $\textbf{Ab}(\mathcal{V}) \to \mathcal{V}$ is monadic, we can construct tensor products the usual way using generators and relations.
As for your second question: you are quite right in saying that we need some kind of diagonal map $\delta_X : X \to X \otimes X$ in order to even define inverses. But that's OK: we just build that into the definition of a group object in a symmetric monoidal category. More accurately, what we are doing is expressing the axioms for a Hopf algebra in diagrammatic form: so a group object in a general symmetric monoidal category will consist of

*

*an object $X$, and

*morphisms $\eta : I \to X$, $\mu : X \otimes X \to X$, $\epsilon : X \to I$, $\delta : X \to X \otimes X$, and $\sigma : X \to X$

satisfying the following axioms:

*

*$(X, \eta, \mu)$ is a monoid.

*$(X, \epsilon, \delta)$ is a comonoid.

*$\sigma$ gives left inverses: $\mu \circ (\sigma \otimes \textrm{id}_S) \circ \delta = \eta \circ \epsilon$

*$\sigma$ gives right inverses: $\mu \circ (\textrm{id}_S \otimes \sigma) \circ \delta = \eta \circ \epsilon$

This is a generalisation of the usual definition of group object in a cartesian monoidal category because every object in a cartesian monoidal category is a comonoid in a unique way. (This is a fun exercise.) The coordinate ring of any affine group scheme (over $\operatorname{Spec} A$) will also give examples in the category of $A$-modules.


text:
Q: Filtering SQL query based on parameters with more than one value I am trying to build a SQL that needs to be filtered by two parameters (2 columns), and the second column needs to match multiple values.
Given below is the SQL I have build thus far (thanks for the help of Martijn Pieters)
import psycopg2
import pandas as pd
import datetime

# Connecting to db

con = psycopg2.connect(db_details)
cur = con.cursor()
cur.execute("select * from sales limit 10")
rows = cur.fetchall()

params = {'earliest': datetime.datetime.today() - datetime.timedelta(days=7),
      'store_name': 'store_1', 'store_2'}

df = pd.read_sql("""
     select store_name,count(*) from sales
     where created_at >= %(earliest)s
     and store_name = %(store_name)s""",
 params=params, con=con)

The above SQL has one date parameter which is used in the where clause and I added  one more parameter namely the store_name, where rows match either one of two values.
Would like to know how could I add in this additional parameter to the existing query.
I tried to create a the parameter (similar to the date filter) and pass that to the existing query but get a syntax error when I give it two values:
    'store_name': 'store_1', 'store_2'}
                                      ^
SyntaxError: invalid syntax

pointing to the params field.

A: You have two problems:

*

*You used invalid Python syntax; the comma in a dictionary separates key-value pairs, so the 'store_2' string would be another key-value pair but is missing the : value parts. If you want to define a value with more than one string, you'd have to use a tuple or a list there, were you explicitly use either (...) or [...] to separate that syntax from the key: value, key: value notation:
params = {
    'earliest': datetime.datetime.today() - datetime.timedelta(days=7),
    'store_name': ('store_1', 'store_2'),  # tuple with two values
}

*Generally speaking, SQL parameters can only work with single values. The store_name parameter can only be given a single value, not a sequence of values. That's because SQL parameters are a bridge between the SQL query and the dynamic values to be used in that query, with parameters designed to act as placeholder for each individual dynamic value.
That said, the psycopg2 library specifically supports tuples, this is an exception to most Python database libraries however.
Next, if you want to filter rows on matching either 'store_1' or 'store_2', the correct SQL syntax would be to use two store_name = ... tests with OR between them and parentheses around (to keep that part separate from the date test connected with AND to the store name test), or by using store_name IN ('store_1', 'store_2'). An IN test compares a column name against multiple values listed in the (...) parentheses.
Given that you are using psycopg2 here, you can get away with the store_name key referencing a tuple value, but you do need to use IN for your query:
params = {
    'earliest': datetime.datetime.today() - datetime.timedelta(days=7),
    'store_name': ('store_1', 'store_2')
}

df = pd.read_sql("""
     SELECT store_name, count(*) FROM sales
     WHERE created_at >= %(earliest)s
     AND store_name IN %(store_name)s""",
     params=params, con=con)

On a separate note: the pd.read_sql() function [explicitly states that only sqlite is supported when using a DBAPI connection](If a DBAPI2 object, only sqlite3 is supported):

If a DBAPI2 object, only sqlite3 is supported.

You are using such an object; most Python database adapters are DBAPI2 libraries; DBAPI2 is a Python standard for such libraries.
You should really use a SQLAlchemy connection string instead. Your code happens to work because you never attempt to write any data back to the database and the psycopg connection and cursor objects are largely compatible with the sqlite3 library versions, but you could run into problems down the road.

A: I don't see why this would not work :
params = {'earliest': datetime.datetime.today() - datetime.timedelta(days=7),
          'store_name': '<put what you want here>'}

df = pd.read_sql("""
         select store_name,count(*) from sales
         where created_at >= %(earliest)s
         and store_name = %(store_name)s""",
     params=params, con=con)

Because you want two stores this is a bit more complex.
This should work :
params = {'earliest': datetime.datetime.today() - datetime.timedelta(days=7),
          'store_names': ','.join(('store_1', 'store_2'))}

df = pd.read_sql("""
         select store_name,count(*) from sales
         where created_at >= %(earliest)s
         and store_name in (%(store_names)s)""",
     params=params, con=con)


text:
Q: PowerShell script to cut paste the folder content in Windows 2012 R2 How can I delete all the contents of one folder (present in C drive) and copy it in another new folder present in different drive (say F).
Example:
C drive→window→ users →temp (make it empty).
move all the content in
F drive→ Temp_backup

A: You can use:
Move-Item -Path "from" -Destination "to"
like described here:
https://social.technet.microsoft.com/Forums/windows/en-US/848b28c2-1ec2-405a-aebd-48bf79a9594f/how-to-move-files-from-one-location-to-another-location-using-powershell?forum=winserverpowershell


text:
Q: Service with multiple ports/protocols per route (e.g. HTTP and HTTPS) possible in OpenShift? I am currently evaluating OpenShift for use in our company.
We have a web application in a container, which exposes both port 80 http and port 443 https. Is it possible to run this container in OpenShift, using both ports over the SAME hostname? The OpenShift GUI lets me select only one port per service, if I try to create a route, and either http or https, not both. My use-case is, that my application is reachable on http://my-app as well as on https://my-app (in my opinion a quite common use-case)

A: It is not possible to have multiple routes with the same hostname and path. Only first such route will be admitted to the router.
The routes with paths will work as mentioned by @Graham
You can put all 3 below in a single project without problem:

*

*example.com

*example.com/hello

*example.com/world

They can have different protocols. Adding a duplicate route with different protocol will not work.
Additionally if you have Project B, you won't be able to use example.com host again. So, none of the below will be accepted to a router:

*

*example.com

*example.com/hello

*example.com/world

*example.com/path

Which makes sense, as you don't want someone else to use your domain.
What usually happens when you have https exposed is that all http traffic is redirected to https.
You can achieve it by creating edge terminated route (over UI) and selecting Insecure Traffic: Redirect. There is also an option to set it to Allow.
More documentation and yaml examples if you would like to create route from command line: OpenShift Origin: Secured routes


text:
Q: Codeigniter Cannot submit an ip adres on a form. Throws a Forbidden error Here is my html form.
   <?php echo form_open(base_url('admin/subeler/add'), 'class="form-horizontal"');  ?>

            Grup Adı

                    <input type="text" id="grup" required name="grup" value="<?php echo set_value('grup'); ?>" class="form-control">

            Şube Adı

                    <input type="text" id="name" required name="name" value="<?php echo set_value('name'); ?>"class="form-control">

            İp Adresi

                    <input type="text" id="ip" required name="ip" value="<?php echo set_value("ip"); ?>"class="form-control">

            Database Adı

                    <input type="text" id="path" required name="path" value="<?php echo set_value('path'); ?>"class="form-control">

            Lisans Tarihi

                    <input type="text" id="lisans" required name="lisans" value="<?php echo set_value('lisans'); ?>"class="form-control">

            İl

                    <input type="text" id="il" name="il" value="<?php echo set_value('il'); ?>"class="form-control">

            İlçe

                    <input type="text" id="ilce" name="ilce" value="<?php echo set_value('ilce'); ?>"class="form-control">

            <input type="submit" name="submit" value="EKLE" class="btn btn-success m-t-15 waves-effect">

  <?php echo form_close();?>

When I enter an ip adres to the input field like (http://xxx.xxx.xx.xx:xx/) redirect me to the 403 Forbidden page but when I put " (like "http://xxx.xxx.xx.xx:xx") to the ip adres it work fine. I tried to disable xss-filter disable in config files but result is same. Can anyone give some advice. How to submit an ip adres correctly with Codeigniter?
Server-Side
public function add()
{
    if ($this->input->post("submit")) {
        $this->form_validation->set_rules('grup', 'Grup Adı', 'trim|required');
        $this->form_validation->set_rules('name', 'Şube Adı', 'trim|required');
        $this->form_validation->set_rules('ip', 'İp Adresi', 'trim|required');
        $this->form_validation->set_rules('path', 'Database Yolu', 'trim|required');
        $this->form_validation->set_rules('lisans', 'Lisans Tarihi', 'trim|required');
        if ($this->form_validation->run() == true) {
            $data = array(
                'name' => $this->input->post('name'),
                'marka' => $this->input->post('grup'),
                'ip' => $this->input->post('ip'),
                'il' => $this->input->post('il'),
                'ilce' => $this->input->post('ilce'),
                'databasePath' => $this->input->post('path'),
                'lisanse_date'=>$this->input->post('lisans')
            );
            $data = $this->security->xss_clean($data);
            $result = $this->sube_model->add_sube($data);
            if ($result) {
                $this->session->set_flashdata('msg', 'Şube başarılı bir şekilde eklendi!');
                redirect(base_url('admin/subeler'));
            }
        } else {
            $data['view'] = 'admin/subeler/sube_ekle';
            $this->load->view('layout', $data);
        }
    } else {
        $data['view'] = 'admin/subeler/sube_ekle';
        $this->load->view('layout', $data);
    }
}

A: Unfortunately I could not test the code exactly as provided as I don't make use of CodeIgniter 3 anymore, so I translated it into CodeIgniter 4.
Also, I could not test what $this->sube_model->add_sube does.
This, plus the form view you provided is working when setting http://xx.xx.xx.xx:xx on every form field.
You should trace when the 403 forbidden is triggered.
If you make use of XDebug i'd recommend you to trace step by step where the execution fails.
Otherwise I'd just start removing code to find out at which point of the execution the exception is occurring.
If you are making use of a shared hosting, there could be any rule in the http server that is blocking the request, if that's the case, run it locally using a WAMP/LAMP bundle.
    // CodeIgniter 4 approach
    public function add() {
        if ($this->request->getMethod() == 'post') {
            $validation =  \Config\Services::validation();
            $validation->setRule('grup', 'Grup Adı', 'trim|required');
            $validation->setRule('name', 'Şube Adı', 'trim|required');
            $validation->setRule('ip', 'İp Adresi', 'trim|required');
            $validation->setRule('path', 'Database Yolu', 'trim|required');
            $validation->setRule('lisans', 'Lisans Tarihi', 'trim|required');
            if ($validation->withRequest($this->request)->run() == true) {
                $data = array(
                    'name' => $this->request->getPost('name'),
                    'marka' => $this->request->getPost('grup'),
                    'ip' => $this->request->getPost('ip'),
                    'il' => $this->request->getPost('il'),
                    'ilce' => $this->request->getPost('ilce'),
                    'databasePath' => $this->request->getPost('path'),
                    'lisanse_date'=>$this->request->getPost('lisans')
                );
                // $data = $this->security->xss_clean($data);
                $result = $this->sube_model->add_sube($data);
                $result = 1;
                if ($result) {
                    session()->setFlashdata('msg', 'Şube başarılı bir şekilde eklendi!');
                    return redirect(base_url('admin/subeler'));
                }
            } else {
                $data['view'] = 'admin/subeler/sube_ekle';
                return view('layout', $data);
            }
        } else {
            $data['view'] = 'admin/subeler/sube_ekle';
            return view('layout', $data);
        }
    }


text:
Q: Creating R loop/apply function to iterate by unique participant ID and calculate midpoint between dates My dataset looks something like this
dat <- data.frame(id=c(100,100,100,101,101,101,102,102,102,103,103,103),
visit = c(1,2,3,1,2,3,1,2,3,1,2,3),
visit.date = c(9/15/2020,11/29/2020,12/23/2020,9/7/2020,11/16/2020,12/9/2020,9/16/2020,12/6/2020,1/6/2021,10/4/2020,11/30/2020,12/23/2020),
delivery.date = c(NA,NA,NA,NA,11/2/2020,NA,NA,11/21/2020,NA,NA,11/15/2020,NA),
death = c(0,1,NA,0,0,0,0,0,1,0,0,1))

Essentially, I have three different visits for each participant with a unique ID. What I need to do is create a variable that states the date of death for each participant who reported a death (death=1). The date of death should be the midpoint between the visit date when the baby was reported dead and the last visit date that the baby was reported alive. Then, if the midpoint date is before the delivery date, I need that newly created variable column to list the delivery date as the day of death.
I've tried creating my own function and applying it using lapply as below, but I end up getting a separate report for each row that lists the participant ID, and the value is null. Here is the code I've tried. Ultimately, I will need to calculate person time at risk in days which is why I was trying to use difftime here. The dates are in POSIXct format as well to be compatible with the difftime function. Any help here would be very appreciated!
risktime <- function(id,dat) {
     a<- difftime(dat$visit.date[max(dat$visit)],dat$delivery.date,units="days")[dat["id"]=="id"]
a}
risktime1 <- lapply(unique(dat$id),risktime,dat)
riktime1

A: I'm not sure why you use difftime, IMO you should use mean.Date instead which already gives the midpoint between two dates. Also works with "Date" class, that we create first.
dat <- transform(dat, visit.date=as.Date(visit.date, '%m/%d/%Y'),
                 delivery.date=as.Date(delivery.date, '%m/%d/%Y'))

Simply wrap mean.Date in a function. There is some case handling involved, whether there's 1. a death, 2.a delivery date which is earlier than reported death, 2.b if the latter is later.
f <- \(x) {
  if (any(x$death == 1)) {
    last_alive <- with(x, which.max(cumsum(death == 0)))
    first_dead <- with(x, which.max(cumsum(death == 1)))
    u <- mean(c(x$visit.date[last_alive], x$visit.date[first_dead]))
    dd <- x$delivery.date[!is.na(x$delivery.date)]
    if (!length(dd) == 0) {
      if (u < dd) {
        x$est_death <- dd
      } else {
        x$est_death <- u
      }
    } else {
      x$est_death <- u
    }
  } else {
    x$est_death <- as.Date(NA_integer_)
  }
  return(x)
}

Finally use function in by.
by(dat, dat$id, f) |> do.call(what=rbind)
#         id visit visit.date delivery.date death  est_death
# 100.1  100     1 2020-09-15          <NA>     0 2020-10-22
# 100.2  100     2 2020-11-29          <NA>     1 2020-10-22
# 100.3  100     3 2020-12-23          <NA>    NA 2020-10-22
# 101.4  101     1 2020-09-07          <NA>     0       <NA>
# 101.5  101     2 2020-11-16    2020-11-02     0       <NA>
# 101.6  101     3 2020-12-09          <NA>     0       <NA>
# 102.7  102     1 2020-09-16          <NA>     0 2020-12-21
# 102.8  102     2 2020-12-06    2020-11-21     0 2020-12-21
# 102.9  102     3 2021-01-06          <NA>     1 2020-12-21
# 103.10 103     1 2020-10-04          <NA>     0 2020-12-11
# 103.11 103     2 2020-11-30    2020-11-15     0 2020-12-11
# 103.12 103     3 2020-12-23          <NA>     1 2020-12-11

Data:
dat <- structure(list(id = c(100, 100, 100, 101, 101, 101, 102, 102,
102, 103, 103, 103), visit = c(1, 2, 3, 1, 2, 3, 1, 2, 3, 1,
2, 3), visit.date = structure(c(18520, 18595, 18619, 18512, 18582,
18605, 18521, 18602, 18633, 18539, 18596, 18619), class = "Date"),
    delivery.date = structure(c(NA, NA, NA, NA, 18568, NA, NA,
    18587, NA, NA, 18581, NA), class = "Date"), death = c(0,
    1, NA, 0, 0, 0, 0, 0, 1, 0, 0, 1)), class = "data.frame", row.names = c(NA,
-12L))

A: I personally find dplyr to be more expressive with these kinds of grouped
operations than base R. Here's how I would write this (using @jay.sf's data):
library(dplyr, warn.conflicts = FALSE)

dat %>%
  group_by(id) %>%
  # Create a cumulative indicator for survival status
  mutate(
    dead = cummax(replace(death, is.na(death), 0))
  ) %>%
  # Estimate date of death
  summarise(
    delivery.date = first(na.omit(delivery.date)),
    last.alive = last(visit.date[dead == 0]),
    first.dead = first(visit.date[dead == 1]),
    death.date = mean(c(last.alive, first.dead))
  ) %>%
  # Ensure estimated death date is not before delivery
  mutate(
    death.date = replace(death.date, which(delivery.date > death.date), delivery.date)
  )
#> # A tibble: 4 x 5
#>      id delivery.date last.alive first.dead death.date
#>   <dbl> <date>        <date>     <date>     <date>
#> 1   100 NA            2020-09-15 2020-11-29 2020-10-22
#> 2   101 2020-11-02    2020-12-09 NA         NA
#> 3   102 2020-11-21    2020-12-06 2021-01-06 2020-12-21
#> 4   103 2020-11-15    2020-11-30 2020-12-23 2020-12-11


text:
Q: Return 1 in javascript function power(base, exponent) {
  if (exponent == 0)
    return 1;
  else
    return base * power(base, exponent - 1);
}

If I change it to return 2, it doubles the answer, 3 triples etc.
I understand what it's doing, but I haven't learned how it knows to produce a multiple of the return from the 'else' part. Please explain.
EDIT: While I'm here, how is the else working? I would assume base is being multiplied by base, and then the exponent is subtracting from itself, but when I do something like: base * (2, 5-1) it multiplies base by 4... I must be missing something simple.

A: If you return 1, then calling power(7, 3) will result in:
7 * 7 * 7 * 1

If you return 2, then it will result in:
7 * 7 * 7 * 2

where the last number is the number that you are returning.
Do you now see why changing the return value doubles the result?
To answer your second question, this due to the behavior of the comma operator, which evaluates to the value of the expression after the last comma so:
base * (2, 5 - 1)
base * (5 - 1)
base * (4)

This is completely unrelated to calling a function with the parameters 2 and 5 - 1.

A: It doesn't have to "know" anything. It keeps recurring until the exponent is zero.

how is the else working?

If exponent != 0 it runs, its the opposite of the if.

A: This is a recursive function that calls itself over and over until it finds the correct answer. Tracing the way the function works should help you understand it.
Take power(2, 5) for example.
power(2, 5) = 2 * power(2, 4)
            = 2 * 2 * power(2, 3)
            = 2 * 2 * 2 * power(2, 2)
            = 2 * 2 * 2 * 2 * power(2, 1)
            = 2 * 2 * 2 * 2 * 2 * power(2, 0)
            = 2 * 2 * 2 * 2 * 2 * 1

All together, you end up with 2 * 2 * 2 * 2 * 2 * 1 which is 25, as expected. The else in your function gets triggered when the exponent parameter (the 5 in the example) is greater than zero. Since 5 is greater than 0, the else part is triggered and the function is called again with 4 as the exponent. Since 4 is greater than 0, the else part is triggered and the function is called again with 3 as the exponent. The same thing happens with 2, then 1, then 0. When power(2, 0) is finally called, the function just returns 1.


text:
Q: Import my own files into the electron renderer process This seems really dumb, but I need help for importing some source code into the renderer process in electron:
I have an electron app:
index.html (loads window.js with a  tag)
- index.js
- window.js
- useful_functions.js
In window.js, I want to import some functions from useful_functions.js, so I've tried the following:
// fails with: Uncaught SyntaxError: Unexpected identifier
import { very_useful } from './useful_functions.js';

// fails with: Uncaught ReferenceError: require is not defined
const { very_useful } = require('./useful_functions.js');

// fails with: Uncaught ReferenceError: require is not defined
require('electron').remote.require('./useful_functions.js')

I also tried the nodeIntegration flag, but that didn't help either
Note: I'm not trying to import npm modules but my own code, in an other file right next to it.
I'm looking for examples, but I only find super small samples with just the basic files. (Or huge apps like atom that would take me a while to figure out)
I don't have webpack setup for this project yet, but I'm sure there is a simpler way to do this very basic task...
Thanks for any help.

A: In index.html, use require() instead of loading window.js with a tag, i.e., replace:
<script src="window.js"></script>

with:
<script>require('./window.js');</script>

Then, in window.js, the following statement should work too:
const { very_useful } = require('./useful_functions.js');

Note that nodeIntegration: true is needed in the options passed to new BrowserWindow() anyway:
webPreferences:
{
    nodeIntegration: true
}

See:

*

*Node Modules

Functions and objects are added to the root of a module by
  specifying additional properties on the special exports object.
Variables local to the module will be private, because the module is
  wrapped in a function by Node.js (see module wrapper).

*

*Module Wrapper

Before a module's code is executed, Node.js will wrap it with a
  function wrapper that looks like the following:
(function(exports, require, module, __filename, __dirname) {
  // Module code actually lives in here
  });


text:
Q: IS jmdns is working on Android? i am getting these errors when i run the jmdns class after calling it I am working on android application, and I am using JMDNS for the service discovery. I used it successfully in a desktop application, but when I try to use it for android, it does not work. I simply made a class in main activity to start JmDNS:
class ClientThread implements Runnable {
        @Override
        public void run() {

            try {

                System.out.println("Opening JmDNS");
                JmDNS jmdns = JmDNS.create();
               System.out.println("Opened JmDNS");

                ServiceInfo info1 = ServiceInfo.create("_tcp.local.", "SongsList",
                                                       1269, 0, 0,"Song" );

                jmdns.registerService(info1);

                 System.out.println("\nRegistered Service as "+info1);

            } catch (IOException e) {
                e.printStackTrace();
            }
        }}

Then start it in main:
new Thread(new ClientThread()).start();

It does not work, here is the exception stack trace:
FATAL EXCEPTION: Thread-1280
java.lang.NoClassDefFoundError: javax.jmdns.JmDNS
at com.example.testme.MainActivityClientThread.run(MainActivity.java:38)
at java.lang.Thread.run(Thread.java:856)

What am I doing wrong?

A: You need to include the jmdns.jar in your project's build (class) path.