text:
Q: onCharacteristicChanged() never called I'm attempting to receive data from my Texas sensor tag, but so far I just managed to connect and write characteristics to it.
this is my setCharacteristicNotification();
the part commented below does not work and I didn't managed to use it.
    public void setCharacteristicNotification(BluetoothGattCharacteristic characteristic,
                                              boolean enabled) {
        if(bluetoothAdapter == null || bluetoothGatt == null) return;

        bluetoothGatt.setCharacteristicNotification(characteristic, enabled);

        if(GattUUIDs.containsUuid(characteristic.getUuid())) {
//            BluetoothGattDescriptor descriptor = characteristic.getDescriptor(
//                    UUID.fromString(GattAttributes.CLIENT_CHARACTERISTIC_CONFIG));
            BluetoothGattDescriptor descriptor = new BluetoothGattDescriptor(
                    GattUUIDs.UUID_CLIENT_CHAR_CONFIG, BluetoothGattDescriptor.PERMISSION_WRITE |
                    BluetoothGattDescriptor.PERMISSION_READ);

            descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
            bluetoothGatt.writeDescriptor(descriptor);

        }
    }

When I try to call the commented block, this is what I receive:

java.lang.NullPointerException: Attempt to invoke virtual method
  'boolean android.bluetooth.BluetoothGattDescriptor.setValue(byte[])'
  on a null object reference

This is my Client Characteristic Configuration UUID:
public static final UUID UUID_CLIENT_CHAR_CONFIG =
         UUID.fromString(GattAttributes.CLIENT_CHARACTERISTIC_CONFIG);
public static String CLIENT_CHARACTERISTIC_CONFIG = "f0002902-0451-4000-b000-000000000000";

I think that it has some sort of problem in my descriptor because I can register it but I never got a callback from it.

If it helps, this is my Service:
import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothProfile;
import android.content.Context;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
import java.util.List;
import java.util.UUID;

/**
 * Created by alan on 2/23/16.
 */
public class DeviceService extends Service {

    private final static String TAG = DeviceService.class.getSimpleName();

    private BluetoothGatt bluetoothGatt;
    private String deviceAddress;
    private BluetoothManager bluetoothManager;
    private BluetoothAdapter bluetoothAdapter;
    private int connectionState = STATE_DISCONNECTED;

    public final IBinder binder = new LocalBinder();
    public static final int STATE_DISCONNECTED = 0;
    public static final int STATE_CONNECTING   = 1;
    public static final int STATE_CONNECTED    = 2;

    public static final String ACTION_GATT_SERVICES_DISCOVERED = "action_gatt_services_discovered";
    public static final String ACTION_GATT_DISCONNECTED        = "action_gatt_disconnected";
    public static final String ACTION_GATT_CONNECTED           = "action_gatt_connected";
    public static final String ACTION_DATA_AVAILABLE           = "action_data_available";
    public static final String ACTION_DATA_NOTIFY              = "action_data_notify";
    public static final String ACTION_DATA_WRITE               = "action_data_write";
    public static final String ACTION_DATA_READ                = "action_data_read";
    public static final String EXTRA_DATA                      = "extra_data";

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

    @Override
    public boolean onUnbind(Intent intent) {
        close();
        return super.onUnbind(intent);
    }

    public boolean initialize() {
        if(bluetoothManager == null) {
            bluetoothManager = (BluetoothManager)getSystemService(Context.BLUETOOTH_SERVICE);
            if(bluetoothManager == null) {
                Log.e(TAG,"CANNOT INITIALIZE BLUETOOTH");
                return false;
            }
        }bluetoothAdapter = bluetoothManager.getAdapter();
        if(bluetoothAdapter == null) {
            Log.e(TAG,"CANNOT FIND AN ADAPTER");
            return false;
        }return true;
    }

    public boolean connect(final String address) {
        Log.w(TAG,"CONNECT PROCESS INITIALIZED");
        if(bluetoothAdapter == null || address == null) {
            Log.e(TAG,"ADAPTER NOT INITIALIZED");
            return false;
        }
        //previously connected device, attempt to reconnect
        if(deviceAddress != null && deviceAddress.equals(address)
                &&bluetoothGatt != null) {
            Log.d(TAG, "TRYING TO USE EXISTING GATT");
            if(bluetoothGatt.connect()) {
                connectionState = STATE_CONNECTING;
                bluetoothGatt.connect();
                return true;
            } else
                return false;
        }

        final BluetoothDevice device = bluetoothAdapter.getRemoteDevice(address);
        if(device == null) {
            Log.e(TAG, "DEVICE NOT FOUND");
            return false;
        }
        bluetoothGatt = device.connectGatt(this, false, gattCallback);
        deviceAddress = address;
        connectionState = STATE_CONNECTING;
        return true;
    }

    public void disconnect() {
        if(bluetoothAdapter == null || bluetoothGatt == null) {
            Log.w(TAG, "BLUETOOTH NOT INITIALIZED");
            return;
        }
        bluetoothGatt.disconnect();
    }

    public void close() {
        if(bluetoothGatt == null)
            return;
        bluetoothGatt.close();
        bluetoothGatt = null;
    }

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

    private final BluetoothGattCallback gattCallback = new BluetoothGattCallback() {
        @Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
            String intentAction;
            if(newState == BluetoothProfile.STATE_CONNECTED) {
                intentAction = ACTION_GATT_CONNECTED;
                connectionState = STATE_CONNECTED;
                broadcastUpdate(intentAction);
                Log.i(TAG,"CONNECTED TO GATT SERVER!");
                bluetoothGatt.discoverServices();
            } else if(newState == BluetoothProfile.STATE_DISCONNECTED) {
                intentAction = ACTION_GATT_DISCONNECTED;
                connectionState = STATE_DISCONNECTED;
                Log.i(TAG,"DISCONNECTED FROM GATT SERVER");
                broadcastUpdate(intentAction);
            }
        }

        @Override
        public void onServicesDiscovered(BluetoothGatt gatt, int status) {
            Log.e(TAG,"STATUS: " + String.valueOf(status));
            if (status == BluetoothGatt.GATT_SUCCESS)
                broadcastUpdate(ACTION_GATT_SERVICES_DISCOVERED);
        }

        @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) {
            Log.e(TAG,"CHAR CHANGED \n" + gatt.toString() + "\n" + characteristic.getUuid().toString() + "\n");
            broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
        }

        @Override
        public void onCharacteristicWrite(BluetoothGatt gatt,
                                          BluetoothGattCharacteristic characteristic,
                                          int status) {
            Log.e(TAG,"CHAR WROTE" + gatt.toString() + "\n" + characteristic.getUuid().toString() + "\n");
            if(status == BluetoothGatt.GATT_SUCCESS)
                broadcastUpdate(ACTION_DATA_WRITE, characteristic);
        }
    };

    public void readCharacteristic(BluetoothGattCharacteristic characteristic) {
        if(bluetoothAdapter == null || bluetoothGatt == null) {
            Log.e(TAG, "ADAPTER NOT INITIALIZED");
            return;
        }
        bluetoothGatt.readCharacteristic(characteristic);
    }

    public void writeCharacteristic(BluetoothGattCharacteristic characteristic, byte[] value) {
        if(bluetoothAdapter == null || bluetoothGatt == null) {
            Log.e(TAG, "ADAPTER NOT INITIALIZED");
            return;
        }
        characteristic.setValue(value);
        characteristic.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE);
        bluetoothGatt.writeCharacteristic(characteristic);
        System.out.println("Write value: " + value[0] + " on UUID: " + characteristic.getUuid().toString());
    }

    public void setCharacteristicNotification(BluetoothGattCharacteristic characteristic,
                                              boolean enabled) {
        if(bluetoothAdapter == null || bluetoothGatt == null) return;

        bluetoothGatt.setCharacteristicNotification(characteristic, enabled);

        if(GattUUIDs.containsUuid(characteristic.getUuid())) {
            BluetoothGattDescriptor descriptor = characteristic.getDescriptor(
                    UUID.fromString(GattAttributes.CLIENT_CHARACTERISTIC_CONFIG));
//            BluetoothGattDescriptor descriptor = new BluetoothGattDescriptor(
//                    GattUUIDs.UUID_CLIENT_CHAR_CONFIG, BluetoothGattDescriptor.PERMISSION_WRITE |
//                    BluetoothGattDescriptor.PERMISSION_READ);

            descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
            bluetoothGatt.writeDescriptor(descriptor);

        }
    }

    public void setCharacteristicIndication(BluetoothGattCharacteristic characteristic,
                                            boolean enabled) {
        if(bluetoothAdapter ==null || bluetoothGatt == null) return;

        BluetoothGattDescriptor descriptor = characteristic.getDescriptor(
                UUID.fromString(GattAttributes.CLIENT_CHARACTERISTIC_CONFIG));
        descriptor.setValue(BluetoothGattDescriptor.ENABLE_INDICATION_VALUE);
        bluetoothGatt.writeDescriptor(descriptor);

        bluetoothGatt.setCharacteristicNotification(characteristic, enabled);
    }

    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);
        final UUID uuid = characteristic.getUuid();
        Log.w(TAG,"BROADCAST UPDATE WITH ACTION: " + action);
        if(GattUUIDs.containsUuid(uuid)) {
            Log.e(TAG,"PASSOU AQUI");
            int flag = characteristic.getProperties();
            int format;

            if((flag & 0x01) != 0)
                format = BluetoothGattCharacteristic.FORMAT_UINT16;
            else
                format = BluetoothGattCharacteristic.FORMAT_UINT8;

            byte[] data = characteristic.getValue();

            if (GattUUIDs.UUID_IR_TEMPERATURE_MEASUREMENT.equals(uuid)) {
                float objectTemperature  = ((((float)data[1] * 256 + (float)data[0]) / (float)4)) * (float)0.03125;
                float ambientTemperature = ((((float)data[3] * 256 + (float)data[2]) / (float)4)) * (float)0.03125;

//                final int temp_data = characteristic.getIntValue(format, 1);
                intent.putExtra(EXTRA_DATA, String.format("%.2f %.2f", objectTemperature, ambientTemperature));
            } else if (GattUUIDs.UUID_IR_TEMPERATURE_CONFIG.equals(uuid)) {
                if (data[0] == 0)
                    intent.putExtra(EXTRA_DATA, "IR DISABLED");
                else
                    intent.putExtra(EXTRA_DATA, "IR ENABLED");
            } else if (GattUUIDs.UUID_IR_TEMPERATURE_PERIOD.equals(uuid))
                intent.putExtra(EXTRA_DATA, String.format("%d",data[0]*10));

            else if (GattUUIDs.UUID_OPTICAL_MEASUREMENT.equals(uuid)) {
                int m = (data[1] * 256 + data[0]) & 0x0FFF;
                int e = ((data[1] * 256 + data[0]) & 0xF000) >> 12;
                double lux = m * 0.01 * Math.pow(2.0,e);
                intent.putExtra(EXTRA_DATA, String.format("%.2f",lux));
            } else if (GattUUIDs.UUID_OPTICAL_CONFIG.equals(uuid)) {
                if(data[0] == 0)
                    intent.putExtra(EXTRA_DATA, "OPTICAL DISABLED");
                else
                    intent.putExtra(EXTRA_DATA, "OPTICAL ENABLED");
            } else if (GattUUIDs.UUID_OPTICAL_PERIOD.equals(uuid))
                intent.putExtra(EXTRA_DATA, String.format("%d",data[0] * 10));

            else if (GattUUIDs.UUID_MOVEMENT_MEASUREMENT.equals(uuid))
                intent.putExtra(EXTRA_DATA, String.format("%d %d %d %d %d %d %d %d %d",
                        (data[0] + data[1]*256),
                        (data[2] + data[3]*256),
                        (data[4] + data[5]*256),
                        (data[6] + data[7]*256),
                        (data[8] + data[9]*256),
                        (data[10] + data[11]*256),
                        (data[12] + data[13]*256),
                        (data[14] + data[15]*256),
                        (data[16] + data[17]*256)));
            else if (GattUUIDs.UUID_MOVEMENT_CONFIG.equals(uuid)) {
                if (data[0] == 0)
                    intent.putExtra(EXTRA_DATA, "MOVEMENT DISABLED");
                else
                    intent.putExtra(EXTRA_DATA, "MOVEMENT ENABLEd");
            } else if (GattUUIDs.UUID_MOVEMENT_PERIOD.equals(uuid))
                intent.putExtra(EXTRA_DATA, String.format("%d",data[0] * 10));

            else {
                if (data != null && data.length > 0) {
                    final StringBuilder stringBuilder = new StringBuilder(data.length);
                    for(byte byteChar : data)
                        stringBuilder.append(String.format("%02X ",byteChar));
                    intent.putExtra(EXTRA_DATA, new String(data) + "\n" + stringBuilder.toString());
                }
            }
        }
        sendBroadcast(intent);
    }

    public List<BluetoothGattService> getSupportedGattServices() {
        if(bluetoothGatt == null) return null;

        return bluetoothGatt.getServices();
    }
}

and this is my device control:
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.Bundle;

import android.os.IBinder;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.CompoundButton;
import android.widget.Switch;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

/**
 * Created by alan on 2/23/16.
 */
public class DeviceControl extends AppCompatActivity {

    private final String TAG = DeviceControl.class.getSimpleName();

    private ArrayList<ArrayList<BluetoothGattCharacteristic>> mGattCharacterics = new ArrayList<>();
    private BluetoothGattCharacteristic bluetoothGattCharacteristic;
    public static String ADDRESS;
    private DeviceService deviceService;
    private boolean connected = false;
    private TextView dataText;
    private Switch temperatureSwitch,
                   movementSwitch,
                   opticalSwitch;

    private final String LIST_NAME = "NAME";
    private final String LIST_UUID = "UUID";

    private final ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.e(TAG,"ONSERVICECONNECTED");
            deviceService = ((DeviceService.LocalBinder)service).getService();
            if(!deviceService.initialize())
                finish();
            deviceService.connect(ADDRESS);
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            deviceService = null;
        }
    };

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

        dataText = (TextView)findViewById(R.id.dataText);
        temperatureSwitch = (Switch)findViewById(R.id.temperatureSwitch);
        movementSwitch    = (Switch)findViewById(R.id.movementSwitch);
        opticalSwitch     = (Switch)findViewById(R.id.opticalSwitch);

        temperatureSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

                if(isChecked && connected)
                    writeCharacteristic(GattUUIDs.UUID_IR_TEMPERATURE_CONFIG, true);
                else if(!isChecked && connected)
                    writeCharacteristic(GattUUIDs.UUID_IR_TEMPERATURE_CONFIG, false);
            }
        });

        Bundle extras = getIntent().getExtras();

        if(extras != null) {
            setTitle(extras.getString("title"));
            ADDRESS = extras.getString("address");

            Intent intent = new Intent(this, DeviceService.class);
            bindService(intent, serviceConnection, BIND_AUTO_CREATE);
        }
        registerReceiver(broadcastReceiver, makeIntentFilter());
    }

    public void writeCharacteristic(UUID toFind, boolean read) {
        BluetoothGattCharacteristic gattCharacteristic = null;
        byte[] enable = {(byte)0x01},
                disable = {(byte)0x00};
        for(int i = 0; i < mGattCharacterics.size(); i++) {
            for(int j = 0; j < mGattCharacterics.get(i).size(); j++) {
                if(mGattCharacterics.get(i).get(j).getUuid().equals(toFind))
                    gattCharacteristic = mGattCharacterics.get(i).get(j);
            }
        }
        if(gattCharacteristic != null) {
            if(read)
                deviceService.writeCharacteristic(gattCharacteristic, enable);
            else
                deviceService.writeCharacteristic(gattCharacteristic, disable);
            deviceService.setCharacteristicNotification(gattCharacteristic, true);
        } else
            Log.e(TAG,"NOTHING FOUND");

    }

    @Override
    protected void onResume() {
        super.onResume();
        registerReceiver(broadcastReceiver, makeIntentFilter());
        Log.w(TAG,"REGISTER RECEIVER");

        if (deviceService != null) {
            final boolean result = deviceService.connect(ADDRESS);
            Log.d(TAG,"CONNECT RESULT = " + result);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver(broadcastReceiver);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        deviceService.disconnect();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbindService(serviceConnection);
        deviceService = null;
    }

    private final BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            final String action = intent.getAction();
            Log.e(TAG,"BROADCAST ACTION"+action);
            switch (action) {
                case DeviceService.ACTION_GATT_CONNECTED:
                    connected = true;
                    break;
                case DeviceService.ACTION_GATT_DISCONNECTED:
                    connected = false;
                    break;
                case DeviceService.ACTION_GATT_SERVICES_DISCOVERED:
                    getGattServices(deviceService.getSupportedGattServices());
                    break;
                case DeviceService.ACTION_DATA_AVAILABLE:
                    displayData(intent.getStringExtra(DeviceService.EXTRA_DATA));
            }
        }
    };

    private void displayData(String data) {
        if(data != null)
            dataText.setText(data);
    }

    private void getGattServices(List<BluetoothGattService> gattServices) {
        if(gattServices == null) return;
        String uuid = null;
        ArrayList<HashMap<String, String>> gattServiceData = new ArrayList<>();
        ArrayList<ArrayList<HashMap<String, String>>> gattCharacteristicData
                = new ArrayList<>();
        mGattCharacterics = new ArrayList<>();

        for (BluetoothGattService gattService : gattServices) {
            HashMap<String, String> currentServiceData = new HashMap<>();
            uuid = gattService.getUuid().toString();
            currentServiceData.put(LIST_NAME, GattAttributes.lookup(uuid, "UnknownService"));
            currentServiceData.put(LIST_UUID, uuid);
            gattServiceData.add(currentServiceData);

            ArrayList<HashMap<String, String>> gattCharacteristicGroupData = new ArrayList<>();
            List<BluetoothGattCharacteristic> gattCharacteristics = gattService.getCharacteristics();
            ArrayList<BluetoothGattCharacteristic> charas = new ArrayList<>();

            for(BluetoothGattCharacteristic gattCharacteristic : gattCharacteristics) {
                charas.add(gattCharacteristic);
                HashMap<String, String> currentCharaData = new HashMap<>();
                uuid = gattCharacteristic.getUuid().toString();
                currentCharaData.put(LIST_NAME, GattAttributes.lookup(uuid, "UnknownCharacteristic"));
                currentCharaData.put(LIST_UUID, uuid);
                gattCharacteristicGroupData.add(currentCharaData);
                //System.out.println("GATTCHAR\n\n" + gattCharacteristic.toString()+"\n");
            }
            mGattCharacterics.add(charas);
            gattCharacteristicData.add(gattCharacteristicGroupData);
        }
    }

    private static IntentFilter makeIntentFilter() {
        final IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(DeviceService.ACTION_GATT_CONNECTED);
        intentFilter.addAction(DeviceService.ACTION_GATT_DISCONNECTED);
        intentFilter.addAction(DeviceService.ACTION_GATT_SERVICES_DISCOVERED);
        intentFilter.addAction(DeviceService.ACTION_DATA_AVAILABLE);
        return intentFilter;
    }
}

Thanks for your attention.


text:
Q: BASH script to catch changes to a file greater than 150MB Need some ideas here.  I was using something along the lines of
if $[$x-$y>1500]
then etc....
to detect the size of the changes to a file.  I've realized that won't work as the files sizes could increase or decrease which could result in a negative number.  Is there a way to use absolute value of x-y?

A: I have done this.  I create a new file (with at ".new" suffix) but before replacing the old I would check the size difference of the files, and abort (sending some type of notification, such as mail) if there are too many changes.
I generally do this in perl,  but bash would be similar.
$file="file_being_updated";
$new=".new";

if ( -f $file ) {
  my $percent_diff = abs( 100 - 100*(-s "$file$new")/(-s $file) );
  if (  $percent_diff > 20 ) {   # more that this to different!
    printf STDERR "File \"$file$new\" differs by more that 20%%! (%.1f%%)\n",  $percent_diff;
    printf STDERR "-------------- ABORTING REPLACMENT -----------\n";
    exit 10;
  }
}

A: diff=$((x - y)
diff=$(( (diff > 0) ? $diff : -1*$diff ))
if [ $diff -gt 1500 ]
then
  echo do something
fi

redpajama_set_name: RedPajamaStackExchange


text:
Q: Variable POS TAG iMacros TAG POS=1 TYPE=SPAN ATTR=TXT:Optionen
ONDOWNLOAD FOLDER=* FILE=+_{{!NOW:yyyymmdd_hhnnss}} WAIT=YES
TAG POS=36 TYPE=SPAN ATTR=TXT:Herunterladen
TAG POS=55 TYPE=I ATTR=TXT:

TAG POS=1 TYPE=SPAN ATTR=TXT:Optionen
ONDOWNLOAD FOLDER=* FILE=+_{{!NOW:yyyymmdd_hhnnss}} WAIT=YES
TAG POS=38 TYPE=SPAN ATTR=TXT:Herunterladen
TAG POS=55 TYPE=I ATTR=TXT:

I have that variable TAG POS in
TAG POS=36 TYPE=SPAN ATTR=TXT:Herunterladen

and want to build a loop. i dont know how i can solve that.

A: You can try the play loop option http://screencast.com/t/7I0rh5OBeL7 . You can also do this using JavaScript like below
for (var i=1;i<=5;i++)
{
iimPlay("CODE:TAG POS=1 TYPE=SPAN ATTR=TXT:Optionen");
iimPlay("CODE:ONDOWNLOAD FOLDER=* FILE=+_{{!NOW:yyyymmdd_hhnnss}} WAIT=YES");
iimPlay("CODE:TAG POS=38 TYPE=SPAN ATTR=TXT:Herunterladen");
iimPlay("CODE:TAG POS=55 TYPE=I ATTR=TXT:");
}


text:
Q: Testing Gamelift in local, can only create 1 game session? I am testing our application in local, and it seems like i can only create 1 game session using Gamelift local.
so what i did is I run gamelift local
java -jar GameLiftLocal.jar -p 9080

run the custom gamelift server i wrote in C# and Unity
and use CLI to create game session
AWS gamelift create-game-session --endpoint-url http://localhost:9080 --maximum-player-session-count 2 --fleet-id fleet-123d

and first run, it succeed and creates the game session.
when I create another gamesession by issuing the same command above it results to
HTTP-Dispatcher - No available process.

Why is this? can we only create one Game Session in local?

A: If you are trying to make another game session, you need to run multiple game server processes.
GameLift can catch the game session's status by receiving Server-side API call from game server process.
I think this diagram can help you.:)
https://docs.aws.amazon.com/gamelift/latest/developerguide/gamelift-sdk-server-api-interaction-vsd.html

A: According to the docs:

Each server process should only host a single game session.
...
When testing locally with GameLift Local, you can start multiple server processes. Each process will connect to GameLift Local.

Sounds like you need to run multiple instances of GameLiftLocal.
Source: https://docs.aws.amazon.com/gamelift/latest/developerguide/integration-testing-local.html


text:
Q: Debian installation hangs at final GRUB install: "Looking for other operating systems" I used Rufus to burn Debian 9.2 NetInstall ISO to a USB. No matter what options I choose on Rufus, I always run into the same problem when installing Debian. When it gets to installing GRUB, it hangs at 16% on "Looking for other operating systems."
I even tried burning the ISO file to the USB on another computer running Debian, using dd. Same problem.
When the installation hangs, I press 'Ctrl + Alt + F4' to bring up the terminal.  It showed an extremely fast scrolling of errors and messages. I used my iPhone to take slow-motion video of the terminal messages as they zoomed by.
Here are a few stills showing the messages and errors I get: https://imgur.com/a/kpNiq.
The errors seem to be about being unable to find certain directories? I'm on a Dell Inspiron 13 7000 Series laptop.
Why does the install hang? What do these errors means? How do I fix this and get on with the Debian installation?

A: Looks like the ESP partition on your system disk is slightly corrupted: the directory entry /EFI/dell/logs has a pointer back to itself, creating an apparently infinitely deep directory tree. This is a relatively common problem on FAT-type filesystems. (The filesystem on the ESP partition is essentially FAT32.)
The installer is trying to search through all the directories on the ESP partition, but because of the corrupted directory, this search is stuck in an infinite loop.
You should try booting from the install media to rescue mode, identify the ESP partition and then run a filesystem check (fsck.vfat) on it. The filesystem check tool is likely to report a problem with either the /EFI/dell or /EFI/dell/logs directory. It might even suggest deleting the directory: deleting /EFI/dell/logs is probably fine, but you might want to recreate it afterwards, just to be sure.
In a rescue environment, the full path would be something like /target/boot/efi/EFI/dell/logs, as the root filesystem is mounted under /target while in rescue mode, and the ESP partition is mounted under /boot/efi while the system is running normally.
If the ESP filesystem is read-only in rescue mode, that's another indication that something is wrong with it. Typically ESP is the first partition on the first disk, or /dev/sda1. Run cat /proc/mounts in rescue mode to see the device name mounted to /target/boot/efi, then umount /target/boot/efi to unmount it, and then e.g. fsck.vfat /dev/sda1 to check it for errors.

A: *

*Alt + F2

*ps | grep grub-mount

*kill the process

*if hangs again,repeat 2. 3.


text:
Q: Syntax for class constructors I have this code:
data SafeValue a = SafeValue a a a deriving Eq

class Safe a where
  check::a->Bool
  (+++)::a->a->a

instance (Num a, Eq a) => Safe (SafeValue a) where
  check (SafeValue x y z) | x == y = True
                          | x == z = True
                          | y == z = True
                          | otherwise = False
  (SafeValue a b c)+++(SafeValue x y z) = let new_val = SafeValue (a+x) (b+y) (c+z)
                                          in if check new_val then new_val
                                                              else error "Error"

I would like to add to class Safe a function such as:
make_new 3 --> SafeValue 3 3 3

I don't know how to add it, since the tipy should be something like:
make_new::b->a

but in the istance declaration ghci claims that it is not sure about what b is.
Can someone help, please?

A: The core problem is that you're promising that make_new works for all types b to produce a value of a. However, this doesn't make sense given how SafeValue a works: given some type a, you get a SafeValue a out. So what you really want is for make_new to take a value of some type a but give you a value of SafeValue a. More generally, you want the result to be of some type s a where s is the actual type you're writing an instance for and a can be any type.
What you need to do is make the class accept values of a "higher-kinded" type. (What this means is that the class should expect a type like SafeValue that takes a further parameter. You can do that like this:
class Safe s where
  check :: s a -> Bool
  (+++) :: s a -> s a -> s a
  make_new :: a ->  s a

Then your instance will look like this:
instance Safe SafeValue where ...

Note the important difference: instead of making an instance for SafeValue a, you're making on for SafeValue without the type parameter.
However, this has another problem: now you cannot constrain a to be part of Num and Eq!
You can solve this with an extension called multi-parameter type classes. So your final version would be:
class Safe s a where
  check :: s a -> Bool
  (+++) :: s a -> s a -> s a
  make_new :: a -> s a

and your instance would be:
instance (Num a, Eq a) => Safe SafeValue a where ...

To make all this work, you need to enable two extensions:
{-# LANGUAGE FlexibleInstances     #-}
{-# LANGUAGE MultiParamTypeClasses #-}

The first one lets you write instances in more ways. Normally, you can only write instances for a type that looks like T a b c where T is a type and a b c are type variables; with this extension, the restriction is lifted and you can write instances like the one I showed.
The multiparameter typeclass extension allows typeclasses that act on more than one type. This allows you to make a class that depends on both s and a.
A final note: using typeclasses at all may not be the right choice for your example. Are you planning to write any more types for the Safe class? If you aren't, then you shouldn't use a typeclass at all. However, learning a bit about multiparameter typeclasses is still useful, so you should consider playing around with them at some point.


text:
Q: Java 8 Grouping elements in groups of X My question is very straightforward... I have a list of elements and I want to make  subgroups of certain amount... Could that be done in Java with an API ?... Or I should start playing with counters etc...

A: Not really necessary to find an API just for this.
Here's a simple method to do what you want:
public static <T> List<List<T>> splitList(int groupSize, List<T> list) {
    List<List<T>> subLists = new ArrayList<>();
    for (int i = 0; i < list.size();) {
        subLists.add(list.subList(i, i = Math.min(i + groupSize, list.size())));
    }
    return subLists;
}

public static void main(String[] args) throws Exception {
    List<Integer> list = List.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13);
    List<List<Integer>> subLists = splitList(3, list);
    System.out.println(subLists);
    // prints [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12], [13]]
}


text:
Q: Can I add a picture while sharing a post from a different website on twitter? Javascript:
window.open('http://www.twitter.com/share?text=xxxxxxxx');

For facebook we can use
<meta property="og:image" content="http://www.somedomain.ext/skin/images/my-img.jpg" />

order to add a picture with the content of the post.
So I'm wondering if I could do something similar for twitter.

A: You can add Twitter specific meta-data to your post, as described on the Twitter cards site.
For examples (replace images & names with your own values):
<meta name="twitter:card" content="photo" />
<meta name="twitter:site" content="@flickr" />
<meta name="twitter:title" content="Mountain sunset" />
<meta name="twitter:image" content="http://farm8.staticflickr.com/7334/11858349453_e3f18e5881_z.jpg" />
<meta name="twitter:url" content="https://www.flickr.com/photos/reza-sina/11858349453/" />

You will also need to run your site through the Twitter Card Validator.


text:
Q: arch linux: sublime text text not alligned vertically so instead of my code being vertically aligned like usual and in any other code text editor it has weird vertical alignment like i am typing in Microsoft Word or something. anyone have an idea what this could be?
ps its a fresh install not me messing up some unknown setting

EDIT: solution i forgot to install a default font library during my arch linux install, if you have this problem, do this and restart your X server

A: Since your screenshot doesn't illustrate any obvious problems, I'm going to assume using a variable-width font is giving you troubles. Commonly,  monospaced fonts are used for coding.

A monospaced font, also called a fixed-pitch, fixed-width, or non-proportional font, is a font whose letters and characters each occupy the same amount of horizontal space. This contrasts with variable-width fonts, where the letters and spacings have different widths. –Wikipedia

Popular examples for monospaced fonts are Fira Mono, Source Code Pro, Inconsolata, or system-default fonts like Courier New, Lucida Console (both Windows), Monaco (Mac OS X), or Ubuntu Mono (Ubuntu Linux).
You can change the font in your user settings (Preferences > Settings, or "Preferences: Settings" from the command palette).
Example:
{
  "font_face": "Fira Mono"
}

A: forgot to install a default font library during my arch linux install, if you have this problem, do this and restart your X server


text:
Q: What is ntree mean in the randomForst model in R? I am confused with value of ntree in RandonForest model. If I only have one test condition like sex, which is a categorical takes value of 0 or 1. What is the meaning of the ntree in the model? How is it possible to have the number of tress defind by ntree?  I have set ntree = 1000, ntree = 1 and ntree=3 for exmaple. the results seems
model<- randomForest(Survived ~ Sex, data = trainData, importance=TRUE, ntree = 1)
importance(model)

I set ntree = 1: and get
        0     1 MeanDecreaseAccuracy MeanDecreaseGini
Sex 0.191 0.254                0.218               91

ntree = 2:
        0     1 MeanDecreaseAccuracy MeanDecreaseGini
Sex 0.252 0.327                0.285             85.7

ntree = 3
        0    1 MeanDecreaseAccuracy MeanDecreaseGini
Sex 27.7 15.5                 27.5             81.7

ntree = 500
 0   1 MeanDecreaseAccuracy MeanDecreaseGini
Sex 137 140                  145             89.4

What is the results mean?
I want know:

*

*The relationship between the number of test conditions with the set up of ntree numbers.

*ntree numbers with the computation needed

Anyone can help?

A: Ntree = number of trees used in aggregation. Given you only have one variable, it will always used for all trees. However, using Random Forest will also bootstrap resample subsets of the original dataset for each tree. So there is still some randomisation, which may help model non-linear relationships. Hence your results with the increased ntrees improves the mean decrease values because using a single tree is volatile depending on the sample.


text:
Q: struct as a type for function in C++ I am learning C++ and am trying to create a function with a return type of "my_message_t" that was defined in the class definition. However when I tried to compile it, compiler informed me that error: 'my_message_t' does not name a type
I have the following code (protocols.h and protocols.cpp)
    namespace Protocols {
                class Messages {
                    public:

                        typedef struct _my_message_t {
                            //stuffs
                        } my_message_t;

                        typedef enum {
                                //stuffs
                        } my_message_e;

                private:
                    my_message_t                            my_msg;
                    my_message_e                            msg_en;

                public:
                    Messages();
                    ~Messages();

                    my_message_t create_message(const my_message__e);

            };
        };

with the class definition is below:
            namespace Protocols {

                    Messages::Messages(){
                        //stuff
                    };

                    Messages::~Messages(){
                        //stuffs
                    }

                    my_message_t Messages::create_message(my_message_e type){
                        my_message_t msg;

                        //do stuffs

                        return msg;
                    }
            }

Why I can not create a function with a type of my_message_t ? How do I fix that code above?

A: my_message_t is scoped inside the Messages class, so it needs to be qualified when used outside a member of the class:
Messages::my_message_t Messages::create_message(my_message_e type){
^^^^^^^^^^
    // do stuffs
}

Note that you don't need that in the function parameter list, only the return type; a quirk of the language means that the parameter list is scoped inside the function, and the return type outside.

A: Change:
my_message_t Messages::create_message(my_message_type_e type)

to:
Messages::my_message_t Messages::create_message(my_message_e type)
^^^^^^^^^^

A: my_message_t is a type defined inside of class Messages, so you need:
Messages::my_message_t Messages::create_message(my_message_type_e type)


text:
Q: Python Class Inheritance : dict how to pickle(save, load) I'm playing around with class inheritances and I'm stuck on how to pickle data in the class dictionary.
If dump only the dictionary part of self, when I load the dictionary back to self, self takes on a dict type instead of a class. But if I pickle the whole class then I get an error.
Error
pickle.PicklingError: Can't pickle <class 'main.model'>: it's not the same object as main.model

Code
import os, pickle

class model(dict):
    def __init__( self ):
        pass

    def add( self, id, val ):
        self[id] = val

    def delete( self, id ):
        del self[id]

    def save( self ):
        print type(self)
        pickle.dump( dict(self), open( "model.dict", "wb" ) )

    def load( self ):
        print 'Before upacking model.dic, self ==',type(self)
        self = pickle.load( open( "model.dict", "rb" ) )
        print 'After upacking model.dic, self ==',type(self)

if __name__ == '__main__':
    model = model()
    #uncomment after first run
    #model.load()

    #comment after first run
    model.add( 'South Park', 'Comedy Central' )
    model.save()

A: If all you want to do is have a class called model that is a subclass of dict and can be properly pickled and unpickled back to an object that is also of type model then you don't have to do anything special. The methods you have defined in your example to add and delete are unnecessary you can just do them directly on model instances as you would do with any other dict. The save and load methods can be done using the pickle module instead of on the class itself.
code
import pickle

class model(dict):
    pass

a = model()
pickled = pickle.dumps(a)
b = pickle.loads(pickled)

print type(a), a
print type(b), b

output
<class '__main__.model'> {}
<class '__main__.model'> {}

below is another version which is maybe more in line with what you were trying to achieve. But you should NOT do things this way. The load method is weird so is the save. I put the code below to show it can be done but not really something you want to do because it will end up being very confusing.
another version (don't do this)
import pickle

class model(dict):
    def save(self):
        with open("model.dict", "wb") as f:
            pickle.dump(self, f)

    def load(self):
        with open("model.dict") as f:
            return pickle.load(f)

#comment after first run
test = model()
test['South Park'] = 'Comedy Central'
test.save()
print type(test), test

#uncomment after first run
test2 = model().load()
print type(test2), test2

Further Reading
A great example of a subclass of dict that is is picklable is collections.OrderedDict. It is part of the python standard library and is implemented in python so you can have a peak at the source. The definition is 172 lines of code so it's not too much code to look through. It also had to implement the __reduce__ method to achieve pickling because it has information about the order of items that also needs to be pickled and unpickled. It's a good example of why you might want to make your own subclass of dict, it adds the very useful feature of respecting the order of values added to the dict.


text:
Q: Spring Data JPA Specification using CriteriaBuilder with a one to many relationship I have a User entity, a UserToApplication entity, and an Application entity.
A single User can have access to more than one Application. And a single Application can be used by more than one User.
Here is the User entity.
@Entity
@Table(name = "USER", schema = "UDB")
public class User {
    private Long userId;
    private Collection<Application> applications;
    private String firstNm;
    private String lastNm;
    private String email;

    @SequenceGenerator(name = "generator", sequenceName = "UDB.USER_SEQ", initialValue = 1, allocationSize = 1)
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "generator")
    @Column(name = "USER_ID", unique = true, nullable = false)
    public Long getUserId() {
        return userId;
    }

    public void setUserId(Long userId) {
        this.userId = userId;
    }

    @OneToMany(mappedBy = "user", fetch = FetchType.LAZY)
    public Collection<Application> getApplications() {
        return applications;
    }

    public void setApplications(Collection<Application> applications) {
        this.applications = applications;
    }

    /* Other getters and setters omitted for brevity */
}

Here is the UserToApplication entity.
@Entity
@Table(name = "USER_TO_APPLICATION", schema = "UDB")
public class Application {
    private Long userToApplicationId;
    private User user;
    private Application application;

    @SequenceGenerator(name = "generator", sequenceName = "UDB.USER_TO_APP_SEQ", initialValue = 0, allocationSize = 1)
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "generator")
    @Column(name = "USER_TO_APPLICATION_ID", unique = true, nullable = false)
    public Long getUserToApplicationId() {
        return userToApplicationId;
    }

    public void setUserToApplicationId(Long userToApplicationId) {
        this.userToApplicationId = userToApplicationId;
    }

    @ManyToOne
    @JoinColumn(name = "USER_ID", referencedColumnName = "USER_ID", nullable = false)
    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    @ManyToOne
    @JoinColumn(name = "APPLICATION_ID", nullable = false)
    public Application getApplication() {
        return application;
    }
}

And here is the Application entity.
@Entity
@Table(name = "APPLICATION", schema = "UDB")
public class Application {
    private Long applicationId;
    private String name;
    private String code;

    /* Getters and setters omitted for brevity */
}

I have the following Specification that I use to search for a User by firstNm, lastNm, and email.
public class UserSpecification {

    public static Specification<User> findByFirstNmLastNmEmail(String firstNm, String lastNm, String email) {
        return new Specification<User>() {
            @Override
            public Predicate toPredicate(Root<User> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                final Predicate firstNmPredicate = null;
                final Predicate lastNmPredicate = null;
                final Predicate emailPredicate = null;

                if (!StringUtils.isEmpty(firstNm)) {
                    firstNmPredicate = cb.like(cb.lower(root.get(User_.firstNm), firstNm));
                }
                if (!StringUtils.isEmpty(lastNm)) {
                    lastNmPredicate = cb.like(cb.lower(root.get(User_.lastNm), lastNm));
                }
                if (!StringUtils.isEmpty(email)) {
                    emailPredicate = cb.like(cb.lower(root.get(User_.email), email));
                }
                return cb.and(firstNmPredicate, lastNmPredicate, emailPredicate);
            }
        };
    }

}

And here is the User_ metamodel that I have so far.
@StaticMetamodel(User.class)
public class User_ {
    public static volatile SingularAttribute<User, String> firstNm;
    public static volatile SingularAttribute<User, String> lastNm;
    public static volatile SingularAttribute<User, String> email;
}

Now, I would like to also pass in a list of application IDs to the Specification, such that its method signature would be:
public static Specification<User> findByFirstNmLastNmEmailApp(String firstNm, String lastNm, String email, Collection<Long> appIds)

So, my question is, if I add the @OneToMany mapping to the User_ metamodel for the Collection<Application> applications field of my User entity, then how would I reference it in the Specification?
My current Specification would be similar to the following SQL query:
select * from user u
where lower(first_nm) like '%firstNm%'
and lower(last_nm) like '%lastNm%'
and lower(email) like '%email%';

And what I would like to achieve in the new Specification would be something like this:
select * from user u
join user_to_application uta on uta.user_id = u.user_id
where lower(u.first_nm) like '%firstNm%'
and lower(u.last_nm) like '%lastNm%'
and lower(u.email) like '%email%'
and uta.application_id in (appIds);

Is it possible to do this kind of mapping in the metamodel, and how could I achieve this result in my Specification?

A: I found a solution. To map a one to many attribute, in the metamodel I added the following:
public static volatile CollectionAttribute<User, Application> applications;

I also needed to add a metamodel for the Application entity.
@StaticMetamodel(Application.class)
public class Application_ {
    public static volatile SingularAttribute<Application, Long> applicationId;
}

Then in my Specification, I could access the applications for a user, using the .join() method on the Root<User> instance. Here is the Predicate I formed.
final Predicate appPredicate = root.join(User_.applications).get(Application_.applicationId).in(appIds);

Also, it is worth noting that my Specification as it is written in the question will not work if any of the input values are empty. A null Predicate passed to the .and() method of CriteriaBuilder will cause a NullPointerException. So, I created an ArrayList of type Predicate, then added each Predicate to the list if the corresponding parameter was non-empty. Finally, I convert the ArrayList to an array to pass it to the .and() function of the CriteriaBuilder. Here is the final Specification:
public class UserSpecification {

    public static Specification<User> findByFirstNmLastNmEmailApp(String firstNm, String lastNm, String email, Collection<Long> appIds) {
        return new Specification<User>() {
            @Override
            public Predicate toPredicate(Root<User> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                final Collection<Predicate> predicates = new ArrayList<>();
                if (!StringUtils.isEmpty(firstNm)) {
                    final Predicate firstNmPredicate = cb.like(cb.lower(root.get(User_.firstNm), firstNm));
                    predicates.add(firstNmPredicate);
                }
                if (!StringUtils.isEmpty(lastNm)) {
                    final Predicate lastNmPredicate = cb.like(cb.lower(root.get(User_.lastNm), lastNm));
                    predicates.add(lastNmPredicate);
                }
                if (!StringUtils.isEmpty(email)) {
                    final Predicate emailPredicate = cb.like(cb.lower(root.get(User_.email), email));
                    predicates.add(emailPredicate);
                }
                if (!appIds.isEmpty()) {
                    final Predicate appPredicate = root.join(User_.applications).get(Application_.applicationId).in(appIds);
                    predicates.add(appPredicate);
                }

                return cb.and(predicates.toArray(new Predicate[predicates.size()]));
            }
        };
    }

}


text:
Q: to_char equivalent that should work in both oracle and mysql select to_char(systimestamp-1/24,'dd-mm-yy hh24:mi:ss') from dual;

Above query works in oracle. But I also need to work it in mysql as my application should work in both databases with out changing query everytime. So is there any equivalent query for the above that would give same result and should work in both databases.

A: As mentioned in a comment, when working with two different DBMS one should accept that queries differ, because of differences in the SQL dialects.
CURRENT_TIMESTAMP, however is standard SQL and available in both DBMS. FROM DUAL is not standard SQL, but both DBMS feature it.  So simply do
select current_timestamp from dual;

and use your client app to subtract an hour and display the data according to your wishes.
Another option would be to write a view in both DBMS
create view current_datetime_string as
select ... as value from dual;

and then select the string as
select value from current_datetime_string;

A: This will work in both Oracle and MySQL:
SELECT CURRENT_TIMESTAMP - INTERVAL '1' HOUR
FROM   DUAL;

(Please note the difference between SYSTIMESTAMP and CURRENT_TIMESTAMP)
However, formatting it as a string requires TO_CHAR() in Oracle:
SELECT TO_CHAR( CURRENT_TIMESTAMP - INTERVAL '1' HOUR, 'dd-mm-yy hh24:mi:ss' )
FROM   DUAL;

and DATE_FORMAT() in MySQL:
SELECT DATE_FORMAT( CURRENT_TIMESTAMP - INTERVAL '1' HOUR, '%d-%m-%y %H:%i:%s' )
FROM   DUAL;

You can create a function in Oracle (or MySQL) that will convert one to the other:
CREATE FUNCTION DATE_FORMAT( value DATE, mask VARCHAR2 )
  RETURN VARCHAR2 DETERMINISTIC
AS
  p_mask VARCHAR2(4000) := mask;
BEGIN
  p_mask := REPLACE( p_mask, '%Y', 'YYYY' );
  p_mask := REPLACE( p_mask, '%y', 'YY' );
  p_mask := REPLACE( p_mask, '%b', 'MON' );
  p_mask := REPLACE( p_mask, '%M', 'MONTH' );
  p_mask := REPLACE( p_mask, '%m', 'MM' );
  p_mask := REPLACE( p_mask, '%a', 'DY' );
  p_mask := REPLACE( p_mask, '%d', 'DD' );
  p_mask := REPLACE( p_mask, '%H', 'HH24' );
  p_mask := REPLACE( p_mask, '%h', 'HH12' );
  p_mask := REPLACE( p_mask, '%i', 'MI' );
  p_mask := REPLACE( p_mask, '%s', 'SS' );
  RETURN TO_CHAR( value, p_mask );
END;
/

Then you can use the MySQL query in Oracle (or vice-versa, if you implement the inverse function).
If you really don't want to use a function to assist in conversion then this should work in both MySQL and Oracle:
SELECT CONCAT(
         CASE WHEN MOD( EXTRACT( YEAR   FROM CURRENT_TIMESTAMP - INTERVAL '1' HOUR ), 100 ) < 10
              THEN CONCAT( '0', MOD( EXTRACT( YEAR   FROM CURRENT_TIMESTAMP - INTERVAL '1' HOUR ), 100 ) )
              ELSE CONCAT( '',  MOD( EXTRACT( YEAR   FROM CURRENT_TIMESTAMP - INTERVAL '1' HOUR ), 100 ) )
              END,
         '-',
         CASE WHEN EXTRACT( MONTH  FROM CURRENT_TIMESTAMP - INTERVAL '1' HOUR ) < 10
              THEN CONCAT( '0', EXTRACT( MONTH  FROM CURRENT_TIMESTAMP - INTERVAL '1' HOUR ) )
              ELSE CONCAT( '',  EXTRACT( MONTH  FROM CURRENT_TIMESTAMP - INTERVAL '1' HOUR ) )
              END,
         '-',
         CASE WHEN EXTRACT( DAY    FROM CURRENT_TIMESTAMP - INTERVAL '1' HOUR ) < 10
              THEN CONCAT( '0', EXTRACT( DAY    FROM CURRENT_TIMESTAMP - INTERVAL '1' HOUR ) )
              ELSE CONCAT( '',  EXTRACT( DAY    FROM CURRENT_TIMESTAMP - INTERVAL '1' HOUR ) )
              END,
         ' ',
         CASE WHEN EXTRACT( HOUR   FROM CURRENT_TIMESTAMP - INTERVAL '1' HOUR ) < 10
              THEN CONCAT( '0', EXTRACT( HOUR   FROM CURRENT_TIMESTAMP - INTERVAL '1' HOUR ) )
              ELSE CONCAT( '',  EXTRACT( HOUR   FROM CURRENT_TIMESTAMP - INTERVAL '1' HOUR ) )
              END,
         ':',
         CASE WHEN EXTRACT( MINUTE FROM CURRENT_TIMESTAMP - INTERVAL '1' HOUR ) < 10
              THEN CONCAT( '0', EXTRACT( MINUTE FROM CURRENT_TIMESTAMP - INTERVAL '1' HOUR ) )
              ELSE CONCAT( '',  EXTRACT( MINUTE FROM CURRENT_TIMESTAMP - INTERVAL '1' HOUR ) )
              END,
         ':',
         CASE WHEN EXTRACT( SECOND FROM CURRENT_TIMESTAMP - INTERVAL '1' HOUR ) < 10
              THEN CONCAT( '0', EXTRACT( SECOND FROM CURRENT_TIMESTAMP - INTERVAL '1' HOUR ) )
              ELSE CONCAT( '',  EXTRACT( SECOND FROM CURRENT_TIMESTAMP - INTERVAL '1' HOUR ) )
              END
       ) AS formatted_date
FROM DUAL;


text:
Q: Add a gitignore file how can I create a gitignore file in a repository that already have a project in it? I started a project at the university and I forgot to add the gitignore file at the beginning.

A: you can simply go inside the folder, for instance using the terminal (Mac) or Prompt (Windows), then create a .gitignore with the command:

touch .gitignore

or you can follow this instructions in the link.

A: In order to place the .gitignore file to the existing git repository, follow the steps below.
Note: Make sure to Commit any local changes and push to remote before placing the .gitignore file, otherwise, you will lose control of all the changed files while following further steps.
Start from a clean codebase.
git reset --hard HEAD # force reset local codebase to HEAD revision, removes any local changes.
git clean -fdx # remove any untracked/new files

Prepare your .gitignore file (See template repo) and place it in the root directory.
To untrack every files/paths that are now in your .gitignore file
git rm -r --cached . # This removes any changed files from the staging area.

git add .

git commit -m "Adding .gitignore to the repository"

This could be a duplicate question, I couldn't make it duplicate, the option is not available to me.


text:
Q: Is every finite group a proper quotient of a finite primitive group? Let $G$ be a finite group.  Is there necessarily a finite primitive permutation group $P$ and a normal subgroup $N>1$ of $P$ such that $P/N \cong G$?
If not, what restrictions are there on quotients of finite primitive permutation groups?

A: Yes. We can assume that $G$ is a transitive permutation group. Let $S$ be any primitive finite simple group, such as $A_5$ in its natural representation. Now let $P$ be the wreath product of $S$ with $G$ using the product action, which has degree $d(P) = d(S)^{d(G)}$. This gives a primitive group, and the quotient of $P$ with the base group $S^{d(G)}$ of the wreath product is isomorphic to $G$.
Note that the primitive wreath product action of $S \wr G$ can also be described as its action by multiplication on the cosets of its maximal subgroup $T \wr G$, where $T$ is a point stabilizer in $S$.


text:
Q: Applying multiple conditional formatting to the same column with help of macro I have a formula to conditionally format text in a column based on the value from another cell (not in same column):
=SUM(COUNTIF(A1,"*" & $B$1:$E$1 & "*")) = 1

More detailed description can be found here.
I ran into problem while trying to apply this formula with the help of a macro I've recorded with "Record a macro" in Excel 2010.
Here is the process I do:
1) First I select the entire column (by clicking on column letter on top).
2) Then I go to "Conditional Formatting > New rule > Use a formula to determine which cells to format", enter my formula and choose a fill color for my formatting.
3) I then repeat the step 2 for 3 other conditional formattings with different formulas as well as different fill colors:
=SUM(COUNTIF(A1,"*" & $B$1:$E$1 & "*")) = 2

=SUM(COUNTIF(A1,"*" & $B$1:$E$1 & "*")) = 3

=SUM(COUNTIF(A1,"*" & $B$1:$E$1 & "*")) = 4

So here is the problem: while recording the macro I get the desired formatting, i.e. all the cells in A column are color coded depending on how many values from cells B1, C1, D1 and E1 match it's contents.
However when I try to run previously recorded macro on unformated column it doesn't work as intended, only changing color of some cells and only in one color.
So the question is: How do I apply multiple conditional formatting to the same column with help of macro in Excel 2010?
Below is a full macro code for your references:
Sub Macro6()
'
' Macro6 Macro
'

'
    Columns("A:A").Select
    Selection.FormatConditions.Add Type:=xlExpression, Formula1:= _
        "=SUM(COUNTIF(A1,""*"" & $B$1:$E$1 & ""*"")) = 1"
    Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
    With Selection.FormatConditions(1).Interior
        .PatternColorIndex = xlAutomatic
        .Color = 49407
        .TintAndShade = 0
    End With
    Selection.FormatConditions(1).StopIfTrue = False

    Selection.FormatConditions.Add Type:=xlExpression, Formula1:= _
        "=SUM(COUNTIF(A1,""*"" & $B$1:$E$1 & ""*"")) = 2"
    Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
    With Selection.FormatConditions(1).Interior
        .PatternColorIndex = xlAutomatic
        .Color = 5296274
        .TintAndShade = 0
    End With
    Selection.FormatConditions(1).StopIfTrue = False

    Selection.FormatConditions.Add Type:=xlExpression, Formula1:= _
        "=SUM(COUNTIF(A1,""*"" & $B$1:$E$1 & ""*"")) = 3"
    Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
    With Selection.FormatConditions(1).Interior
        .PatternColorIndex = xlAutomatic
        .Color = 15773696
        .TintAndShade = 0
    End With
    Selection.FormatConditions(1).StopIfTrue = False

    Selection.FormatConditions.Add Type:=xlExpression, Formula1:= _
        "=SUM(COUNTIF(A1,""*"" & $B$1:$E$1 & ""*"")) = 4"
    Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
    With Selection.FormatConditions(1).Interior
        .PatternColorIndex = xlAutomatic
        .Color = 255
        .TintAndShade = 0
    End With
    Selection.FormatConditions(1).StopIfTrue = False

End Sub

A: Changing your formula from =SUM(COUNTIF(A1,"*" & $B$1:$E$1 & "*")) = 1 (used with array entry) to =SUMPRODUCT(COUNTIF(A1,"*" & $B$1:$E$1 & "*")) = 1 (used without array entry) fixes the issue. Actually thouse formulas give you the same result. So, this code works:
With Columns("A:A").FormatConditions
    .Add Type:=xlExpression, Formula1:= _
        "=SUMPRODUCT(COUNTIF(A1,""*"" & $B$1:$E$1 & ""*"")) = 1"
    With .Item(.Count).Interior
        .Color = 49407
    End With

    .Add Type:=xlExpression, Formula1:= _
        "=SUMPRODUCT(COUNTIF(A1,""*"" & $B$1:$E$1 & ""*"")) = 2"
    With .Item(.Count).Interior
        .Color = 5296274
    End With

    .Add Type:=xlExpression, Formula1:= _
        "=SUMPRODUCT(COUNTIF(A1,""*"" & $B$1:$E$1 & ""*"")) = 3"
    With .Item(.Count).Interior
        .Color = 15773696
    End With

    .Add Type:=xlExpression, Formula1:= _
        "=SUMPRODUCT(COUNTIF(A1,""*"" & $B$1:$E$1 & ""*"")) = 4"
    With .Item(.Count).Interior
        .Color = 255
    End With
End With

Not sure why, but when using your code, I should explicitly goto FormatConditions on the sheet and press "Apply" button for each rule to make it work. The most lakely issue is that thouse formulas are array formuas.


text:
Q: Program in C who reads a file and transform his characters produces a double free or corruption error When executing my program, I have this error:
*** Error in `./xorcipher': double free or corruption (!prev): 0x00000000024a1010 ***
======= Backtrace: =========
/lib/x86_64-linux-gnu/libc.so.6(+0x777e5)[0x7fe869b317e5]
/lib/x86_64-linux-gnu/libc.so.6(+0x8037a)[0x7fe869b3a37a]
/lib/x86_64-linux-gnu/libc.so.6(cfree+0x4c)[0x7fe869b3e53c]
/lib/x86_64-linux-gnu/libc.so.6(fclose+0x103)[0x7fe869b27363]
./xorcipher[0x4009de]
./xorcipher[0x400d68]
/lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xf0)[0x7fe869ada830]
./xorcipher[0x4007b9]
======= Memory map: ========
00400000-00402000 r-xp 00000000 fd:01 1056628                            /home/user1/Dropbox/SCOLARITY/L2Informatique/S3/Projet/Projet xorcipher/Code/programme final/test/xorcipher
00601000-00602000 r--p 00001000 fd:01 1056628                            /home/user1/Dropbox/SCOLARITY/L2Informatique/S3/Projet/Projet xorcipher/Code/programme final/test/xorcipher
00602000-00603000 rw-p 00002000 fd:01 1056628                            /home/user1/Dropbox/SCOLARITY/L2Informatique/S3/Projet/Projet xorcipher/Code/programme final/test/xorcipher
024a1000-024c2000 rw-p 00000000 00:00 0                                  [heap]
7fe864000000-7fe864021000 rw-p 00000000 00:00 0
7fe864021000-7fe868000000 ---p 00000000 00:00 0
7fe8698a4000-7fe8698ba000 r-xp 00000000 fd:01 136064                     /lib/x86_64-linux-gnu/libgcc_s.so.1
7fe8698ba000-7fe869ab9000 ---p 00016000 fd:01 136064                     /lib/x86_64-linux-gnu/libgcc_s.so.1
7fe869ab9000-7fe869aba000 rw-p 00015000 fd:01 136064                     /lib/x86_64-linux-gnu/libgcc_s.so.1
7fe869aba000-7fe869c7a000 r-xp 00000000 fd:01 137277                     /lib/x86_64-linux-gnu/libc-2.23.so
7fe869c7a000-7fe869e7a000 ---p 001c0000 fd:01 137277                     /lib/x86_64-linux-gnu/libc-2.23.so
7fe869e7a000-7fe869e7e000 r--p 001c0000 fd:01 137277                     /lib/x86_64-linux-gnu/libc-2.23.so
7fe869e7e000-7fe869e80000 rw-p 001c4000 fd:01 137277                     /lib/x86_64-linux-gnu/libc-2.23.so
7fe869e80000-7fe869e84000 rw-p 00000000 00:00 0
7fe869e84000-7fe869eaa000 r-xp 00000000 fd:01 137058                     /lib/x86_64-linux-gnu/ld-2.23.so
7fe86a089000-7fe86a08c000 rw-p 00000000 00:00 0
7fe86a0a6000-7fe86a0a9000 rw-p 00000000 00:00 0
7fe86a0a9000-7fe86a0aa000 r--p 00025000 fd:01 137058                     /lib/x86_64-linux-gnu/ld-2.23.so
7fe86a0aa000-7fe86a0ab000 rw-p 00026000 fd:01 137058                     /lib/x86_64-linux-gnu/ld-2.23.so
7fe86a0ab000-7fe86a0ac000 rw-p 00000000 00:00 0
7ffea9648000-7ffea9669000 rw-p 00000000 00:00 0                          [stack]
7ffea96b5000-7ffea96b7000 r--p 00000000 00:00 0                          [vvar]
7ffea96b7000-7ffea96b9000 r-xp 00000000 00:00 0                          [vdso]
ffffffffff600000-ffffffffff601000 r-xp 00000000 00:00 0                  [vsyscall]
Aborted

The problem seems to be in the xor function but I can't figure what is the  problem. According to this, my problem seems to be caused by a dereferenced pointer. But according to valgrind, it is a open no cancel error (which I don't know what it is and can't find anything relevant on google). On the other hand, I have no compilation errors.
What is wrong with my code?
Here is the program:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

void xor(char* name_file_in,char* name_file_out,char* name_key)
{
    FILE *file_in;//file to encrypt
    FILE *file_out;//encrypted file
    unsigned char read_char;//character of the file
    int count_char=0;//count number of characters in file
    file_in=fopen(name_file_in,"r");
    file_out=fopen(name_file_out,"w");

    while ( fscanf(file_in,"%c",&read_char) != EOF)//each character of in file is read
    {
        read_char=read_char^name_key[count_char%strlen(name_key)];//read_char is encrypted according to key's length's modulo
        fputc(read_char,file_out);//writing character to out file
        count_char++;
    }
    fclose(file_in);
    fclose(file_in);
}

int main(int argc,char* argv[])
{
    xor(argv[1],argv[2],argv[3]);
    return(0);
}

A: You are closing your file twice:
fclose(file_in);
fclose(file_in);

This is undefined behavior.
Note: I only take 5s with valgrind to see that... use -g when you compile for debugging !

A: You must read and write the file in binary, even if it is text file. This is because XOR operator can result in zero bytes, this breaks the read routine in text mode.
file_in = fopen(name_file_in, "rb");
file_out = fopen(name_file_out, "wb");

In addition you have to check to make sure input is valid
if (!name_file_in) return;
if (!name_file_out) return;
if (!name_key) return;

And don't proceed if file handle is invalid
void xor(char* name_file_in, char* name_file_out, char* name_key)
{
    if (!name_file_in) return;
    if (!name_file_out) return;
    if (!name_key) return;

    FILE *file_in;
    FILE *file_out;
    unsigned char read_char;
    int count_char = 0;

    file_in = fopen(name_file_in, "rb");
    file_out = fopen(name_file_out, "wb");

    if(file_in && file_out)
    {
        while(fscanf(file_in, "%c", &read_char) > 0)
        {
            read_char ^= name_key[count_char%strlen(name_key)];
            fputc(read_char, file_out);//writing character to out file
            count_char++;
        }
    }

    if (file_in)
        fclose(file_in);

    if (file_out)
        fclose(file_out);
}

You can change the loop to for(int i = 0; i < argc - 1; i++){...} because you are accessing argv[i+1] in each iteration.


text:
Q: How to add a button at the bottom in sidemenu swift? I have a design in which the sign-out button is placed at the bottom and should not scroll, side menu has a tableview controller in which we can add rows but my requirement is to add the sign-out button at the bottom. I have tried by adding the sign-out button in the footer view to side menu tableview controller, but showing just bellow the rows which I don't want.
import UIKit
import SideMenu

class ProfileViewController: UIViewController {
    var menu:SideMenuNavigationController?
    override func viewDidLoad() {
        super.viewDidLoad()
        configureSideMenu()
    }

    func configureSideMenu() {
        menu = SideMenuNavigationController(rootViewController: MenuListController())
        menu?.navigationBar.setBackgroundImage(UIImage(named: "top_navbrBG"), for: .default)
        let firstFrame = CGRect(x: 20, y: 0, width: menu?.navigationBar.frame.width ?? 0/2, height: menu?.navigationBar.frame.height ?? 0)
            let firstLabel = UILabel(frame: firstFrame)
            firstLabel.text = "Settings"

        menu?.navigationBar.addSubview(firstLabel)
        SideMenuManager.default.addPanGestureToPresent(toView: self.view)

        let screenSize = UIScreen.main.bounds
        let screenHeight = screenSize.height + 40

        let leftBorderView = UIView(frame: CGRect(x: 1, y: -40, width: 1, height: screenHeight))
        leftBorderView.backgroundColor = UIColor.init(hexString: "#cfcfcf")
        menu?.navigationBar.addSubview(leftBorderView)

    }

    @IBAction func menuButtonAction(_ sender: UIButton) {
        if let menu = menu {
            present(menu, animated: true)
        }
    }

}

// functions
extension ProfileViewController {

    @objc func signOutButtonTapped(_ sender: AnyObject?) {
        print("sigin out")
    }
    func getSignOutButton()->UIButton {
        let button = UIButton()
        button.setTitle("Sign out", for: .normal)
        let color = UIColor.init(hexString: "#1A73E9")
        button.setTitleColor(color, for: .normal)
        button.addTarget(self, action: #selector(signOutButtonTapped), for: .touchUpInside)
        return button
    }

    func setConstraintsForSignOutButton(button: UIButton) {
        let screenSize = UIScreen.main.bounds
        let screenHeight = screenSize.height
        guard let menuTopAnchor = menu?.navigationBar.topAnchor else { return  }
        guard let menuLeadingAnchor = menu?.navigationBar.leadingAnchor else { return  }
        guard let menuTrailingAnchor = menu?.navigationBar.trailingAnchor else { return  }

        guard let menuWidth = menu?.menuWidth else { return  }
        button.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate([
            button.leadingAnchor.constraint(equalTo: menuLeadingAnchor, constant: 0),
            button.trailingAnchor.constraint(equalTo: menuTrailingAnchor, constant: 0),
            button.widthAnchor.constraint(equalToConstant: menuWidth),
            button.heightAnchor.constraint(equalToConstant: 40),
            button.bottomAnchor.constraint(equalTo: menuTopAnchor, constant: 300)
        ])

    }
}

// Menu Items
class MenuListController: UITableViewController {
    var menuItems = [[String: String]]()

    override func viewDidLoad() {
        super.viewDidLoad()
        menuItems.append(["name": "Privacy", "img": "privacy", "key" : "privacy"])
        menuItems.append(["name": "Report issue", "img": "report_issue", "key": "report_issue"])
        tableView.dataSource = self
        tableView.delegate = self
        tableView.separatorStyle = .none
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")

        tableView.tableFooterView = getSignOutButton()

    }

    @objc func signOutButtonTapped(_ sender: AnyObject?) {
        print("sigin out")
    }
    func getSignOutButton()->UIButton {
        let button = UIButton()
        button.height = 20
        button.width = 100
        button.setTitle("Sign out", for: .normal)
        let color = UIColor.init(hexString: "#1A73E9")
        button.setTitleColor(color, for: .normal)
        button.addTarget(self, action: #selector(signOutButtonTapped), for: .touchUpInside)
        return button
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        menuItems.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
        if menuItems.indices.contains(indexPath.row) {
            let dict = menuItems[indexPath.row]
            cell.textLabel?.text = dict["name"]
            if let img = dict["img"] {
                cell.imageView?.image = UIImage(named: img)
            }

        }
        return cell
    }

}

desired design

A: Replace this "tableView.tableFooterView = getSignOutButton()" with
    self.getSignOutButton() in viewDidLoad.

Next replace your function "getSignOutButton()->UIButton {}" with below code.
func getSignOutButton() {
    let button = UIButton()
    button.setTitle("Sign out", for: .normal)
    button.setTitleColor(.blue, for: .normal)
    button.addTarget(self, action: #selector(signOutButtonTapped), for: .touchUpInside)
    view.addSubview(button)
    button.translatesAutoresizingMaskIntoConstraints = false

    NSLayoutConstraint.activate([
        button.leadingAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.leadingAnchor),
        button.trailingAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.trailingAnchor),
        button.topAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.bottomAnchor,constant: -20),
        button.bottomAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.bottomAnchor),
    ])
}


text:
Q: force mandrill API send mails, not django with smtp Can django send data to Mandrill, so it will take care about sending mails?
When i do with SMTP, I need to wait to page send mails(over 1000 mails).
I use django framework.
Is this possible?

A: Fixed it with bcc and preserve recipients:
msg = EmailMultiAlternatives(subject, plain_body, from_email, emails, headers={'X-MC-PreserveRecipients': False})
msg.attach_alternative(html_body, "text/html")
msg.send()


text:
Q: SSL mutual authentication with pfx certificate and Alamofire Swift I've to send a client certificate in PFX format for mutual auth to my server through web request.
I'm using Alamofire 4 with Swift 3, but I can't find a good tutorial to achieve my goal.
Has anyone ever had to deal with this type of problem in the past?
Thanks.


text:
Q: How to avoid argument name collision in R snow/ snowfall package, sfSapply? I'm trying to use the snow and snowfall packages, specifically the sfSapply() function to extract data from multiple raster files. It looks something like this:
queue <- list(rast1, rast2, rast3)
sfInit(parallel=TRUE, cpus=3)
sfLibrary(raster)
sfLibrary(rgdal)
sfLibrary(sp)
a <- sfSapply(queue, extract, sp=TRUE, fun=mean, y=tracts)
sfStop()

The fun argument passed to sfSapply() is intended for the extract() function (in the raster library). However, sfSapply() also takes a fun argument (extract()); in this example, I've provided it as the second positional argument.
How can I specify a fun argument for the passed function and not have it confused with the fun argument expected by sfSapply()?

A: One workaround is to create a custom extract function that has these arguments built in:
sfRasterExtract=function(raster_obj){
extract(raster_obj, sp=TRUE, fun=mean, y=tracts)
}

Make sure to use sfExportAll() after sfInit to import the function to all instances you will use, then run
a <- sfSapply(queue, sfRasterExtract)


text:
Q: OutOfMemoryError: PermGen space in debug mode on Jboss AS 7 and IntelliJ IDEA I am using IntelliJ IDEA and JBOSS AS 7. When I am trying to deploy my app in debug mode I occur this exception java.lang.OutOfMemoryError: PermGen space and server is not answering. But if I am using Eclipse, there is no such problem with the same server! How I can solve this problem?

A: This should help:

Just add -Xmx512m -XX:MaxPermSize=300m to the VM options field.


text:
Q: Spring specify implementation in configuration I'm writing application using spring mvc/boot, and I have two storage implementations: database storage and in memory storage. My global idea is choose in configuration file what storage application should use.
My idea is

*

*put @Qualifier annotation on each storage implementation

*create two configurations, like databaseStorageConfiguration and InMemoryStorageConfiguration

*depends on profile, apply first or second configuration

The thing is I don't know how to bind implementation and configuration.
I tried something like this:

@Configuration
public class InMemoryStorageConfig {

    @Autowired
    @Qualifier("inMemoryStorage")
    private Storage storage;

    @Bean
    public Storage getStorage() {
        return storage;
    }
}

But I get an error, that 3 beans were found: 2 beans with dfferent implementation and the 3rd one - in config
UPDATE 1
I've added @Profile("InMemory") to Configuration and activated that profile in properties. That gave no changes but looks more logical now
UPDATE 2
Full configuration:
@SpringBootApplication
@ImportResource("classpath:spring-config.xml")
public class Application {
    public static void main(String... args) {
        SpringApplication.run(Application.class, args);
    }
}

@Service
public class WidgetService {

    private WidgetCache widgetCache;

    @Autowired
    public WidgetService(WidgetCache widgetCache) {
        this.widgetCache = widgetCache;
    }
....

@Qualifier("databaseWidgetCache")
@Transactional
@Repository
public class DatabaseWidgetCache implements WidgetCache {

    private WidgetRepository widgetRepository;

    @Autowired
    public DatabaseWidgetCache(WidgetRepository widgetRepository) {
        this.widgetRepository = widgetRepository;
    }

@Qualifier("inMemoryWidgetCache")
@Repository
public class InMemoryWidgetCache implements WidgetCache {

    private WidgetLayersStorage widgetLayersStorage;

    @Autowired
    public InMemoryWidgetCache(WidgetLayersStorage widgetLayersStorage) {
        this.widgetLayersStorage = widgetLayersStorage;
    }

@Profile("InMemory")
@Configuration
public class InMemoryStorageConfig {

    @Autowired
    @Qualifier("inMemoryWidgetCache")
    private WidgetCache widgetCache;

    @Bean
    public WidgetCache getWidgetCache() {
        return widgetCache;
    }
}

Stacktrace:
 Parameter 0 of constructor in
 com.widgets.service.widget.WidgetService required a single
 bean, but 3 were found:
    - inMemoryWidgetCache: defined in file [..../MemoryWidgetCache.class]
    - databaseWidgetCache: defined in file [..../DatabaseWidgetCache.class]
    - getWidgetCache: defined by method 'getWidgetCache' in class path resource
 [......../InMemoryStorageConfig.class]

 Action:

 Consider marking one of the beans as @Primary, updating the consumer
 to accept multiple beans, or using @Qualifier to identify the bean
 that should be consumed

A: Your WidgetService should be changed to
    @Service
    public class WidgetService {

        private WidgetCache widgetCache;

        /** or
        private List<WidgetCache> widgetCaches;
        public WidgetService(List<WidgetCache> widgetCaches) {
            this.widgetCaches = widgetCaches;
        }
        */
        public WidgetService(@Qualifier(<desired impl>) WidgetCache widgetCache) {
            this.widgetCache = widgetCache;
        }
    }

and need to annotate your InMemoryWidgetCache and DatabaseWidgetCache with @Qualifier annotation. since you are using default convention.
and please remove
    @Bean
    public WidgetCache getWidgetCache() {
        return widgetCache;
    }

i don't see a real use there

A: In order to specify implementation in Configuration class, you don't need "Qualifier" annotation, and configuration should be changed to:
@Profile("inMemoryStorage")
@Import(InMemoryWidgetCache.class)
@Configuration
public class InMemoryStorageConfig {

}

thus, by activating profile, you choose the desire implementation


text:
Q: Cache key organization problem My entity has two unique ids (yes this is wrong but it is a requirement). I want to organize a cache of such instances. The search in cache could be made by id1 OR id2 OR id1 and id2. Search by both id1 and id2 is ok - I will make composite key. But how to deal with just search by one of ids. What should be the cache key? I'm using ehcache.
I have a situation where several key may refer the same
object.
Like ehcache does not suport this feature, the same
object will be stored for each key (n instances of the
same object, where n is the number of diferent keys
that that object may be refered from).
At some point i have the knowledge to calculate the
other keys, but not before i need them.
Situation :
GEN KEY (1)
Check if object is in cache (2)
TRUE : Retreve it
FALSE : Process the new object (3)
Place it in ehcache
return OBJECT
At point (1) just know one of the keys. At the point
(3) there is the possibility to know all keys that the
object may have associated to it in ehcache.
The problem is that the keys are needed at point (2).
Thx

A: I can't tell for ehcache, but I've been having a similar problem for HashMap used as cache. I simply put each value twice in the Map, it's not that expensive and it worked well.
Because of my keys being of different types, I used Map<Object, V>.

A: One option would be to use two Maps.  One for each id set, but both would point to the same set of values.
If the search is on id1 just lookup the value in the first map, if on id2, just lookup in the second map.  If you need to search both, lookup both values and see if the values are identical.
Updated based on updates to your question and comments below:
Use both keys in your ecache. Yes this will take up more space and there might be times that the object you are looking for is already in the cache under the other key.  However, the cache should store common looked up keys. It should not care that the value might exist under another key.  So I would not stress yourself with trying to optimize your cache to lookup based on two keys.

A: To accomplish what you want you can do it by transitivity storing not only the object in the cache, but storing also the index that points to your object using each of the keys.
e.g.:
cache["key1"]=theIndex;
cache["key2"]=theIndex;
cache[theIndex]=object;
So, when you request for cache["key1"] you'd get an index (you have to know it's an index), and then get the actual object using that index.
The code could go something like:
 public class CacheUtil {

   ... any necessary code here

   public static void put(String key, Serializable obj) {
    if (obj instance of Cacheable) {
      //Cacheable interface identifies the cacheable object that has the getKeys method
      String[] keys = obj.getKeys();
      if (keys != null && keys.length > 0) {

        for (String myKey : keys) {
          //CacheIndex identifies the index
          cache.put(new Element(myKey, new CacheIndex(hashCode)));
        }
        key = hashCode(keys); //change the key. Can be a hashcode of the keys
      }
    }

    cache.put(new Element(key, obj));
  }

  public static Serializable get(String key) {

    Serializable obj = cache.get(key);

    return ((null != serializable) && (serializable instanceof CacheIndex)) ?
            get(((CacheIndex)serializable).getIndex(), area) : obj;
  }

}


text:
Q: Can someone help me, tell me the meaning of this code? I tried to modify the Wiimote Whiteboard app for my final project.
but my experience in the programming language C # is very little.
I do not know what is the meaning of a few lines of code:
can anyone help me?
    [DllImport("bthprops.cpl", CharSet = CharSet.Auto, SetLastError = true)]
    static extern IntPtr BluetoothFindFirstDevice(ref BLUETOOTH_DEVICE_SEARCH_PARAMS SearchParams, ref BLUETOOTH_DEVICE_INFO DeviceInfo);

    [DllImport("bthprops.cpl", CharSet = CharSet.Auto, SetLastError = true)]
    static extern bool BluetoothFindNextDevice(IntPtr hFind, ref BLUETOOTH_DEVICE_INFO DeviceInfo);

    [DllImport("bthprops.cpl", CharSet = CharSet.Auto, SetLastError = true)]
    static extern bool BluetoothFindDeviceClose(IntPtr hFind);

    [DllImport("bthprops.cpl", CharSet = CharSet.Auto, SetLastError = true)]
    static extern uint BluetoothSetServiceState(IntPtr hRadio, ref BLUETOOTH_DEVICE_INFO DeviceInfo, ref Guid guid, int ServiceFlags);

    [DllImport("bthprops.cpl", CharSet = CharSet.Auto, SetLastError = true)]
    static extern uint BluetoothRemoveDevice(ref BLUETOOTH_ADDRESS Address);

I am very grateful if you are willing to help me.
I am looking for someone who has mastered the C # programming language to guide me in this project.
I hope someone is willing to help me.
I am sorry for my english is very weak.

A: This statements that you have shown are importing function entry points from a DLL. These function entry points are all "C" language calls. The DLL in this case is called: "bthprops.cpl". Which is the windows Blue Tooth control panel control.
In each case the statement specifies the name of the DLL followed by a declaration of the function signature. For example:
static extern IntPtr BluetoothFindFirstDevice(ref BLUETOOTH_DEVICE_SEARCH_PARAMS SearchParams, ref BLUETOOTH_DEVICE_INFO DeviceInfo);

The effect of these DLLImport statements is that the  function is now callable from within your C# application. In this case it is a function that allows you to start iterating over all Blue Tooth devices.


text:
Q: 3rd party library for Qt QNetworkConfiguration and QNetworkConfigurationManager classes Our dev environment:
OS: Windows 10 and Mac OS latest
Qt: 5.15.2
QNetworkConfiguatoin and QNetworkConfiguratoinManager, these classes are obsolete in Qt 5.15.2. Last week I had posted a query here.
Is there any 3rd party C++ library which provides the same functionalities? As our application is for both Mac and Windows, it will be good to have a library supported for both the platform.


text:
Q: When a mail is sent from live mail with chinese content message body is displaying with some special charachers I am using php mailer in my project. When I sent mail from live mail with chinese and Japanese content, message body is displaying as
$BF;2DF;Hs>oF;!$L>2DL>Hs>oL>F;2DF;Hs>oF;!$L>2DL>Hs>oL>(B.
I'm unable to decode this. Which encoding technique it is and can we sent any parameter to live mail so that it can convert given chinese content to utf-8.

A: Try to send the mail UTF-8 encoded, so set your headers to :
$headers = 'MIME-Version: 1.0' . "\r\n" . 'Content-type: text/plain; charset=UTF-8' . "\r\n";

For subject encode it base64 :
$subject = '=?UTF-8?B?'.base64_encode($subject).'?='


text:
Q: How to I access this particular class? The class in question is sun.security.tools.KeyTool and I'm using OpenJDK 7. I keep getting "cannot find symbol" though, and I'm no Java expert so I can't figure out through documentation why that could be or if it's gone. Any ideas?
Exact error message:
Main.java:1: error: cannot find symbol
import sun.security.tools.KeyTool;
                         ^
  symbol:   class KeyTool
  location: package sun.security.tools

Code:
import sun.security.tools.KeyTool;

public class Main {
    public static void main(String[] args) {
    }
}

A: Try using javac -XDignore.symbol.file ....
By default javac restricts the classes it exposes to users. This generally helps users avoid accidentally depending on (unsupported) classes that are not public Java API but happen to be available in the current JRE/JDK. The list of "safe" classes is described in ct.sym file. The ignorel.symbol.file system property tells javac to ignore that file and make use of all classes available in the JDK/JRE.
And make sure you add tools.jar, where this class is defined to the classpath for javac.


text:
Q: Use the same database in Django and C++ I'm looking for a way to use the same database backend in both Django and C++. I've searched on the Internet, but couldn't found much information. What I need is to make some inserts in the database from a C++ application and use django for displaying some collected data. It would be mostly a simple demo application.
It would be ideal if I could use an ORM in C++ instead of raw queries. I want to maintain portability with different database backends. I imagine this should work by defining the database models for both applications.
Is there any library which can help me with this ? I've found something called QDjango, but nowhere in the documentation is mentioned if such a thing is possible.

A: There're some ORM classes for C++, like this one: http://www.qxorm.com/qxorm_en/quick_sample.html
You just need to follow the same name conventions used in Django.
Table name example: myapp_tablename, id as pk, and so on.


text:
Q: Why can't I call a union of functions with a union of parameters? I expect arg to be an union but it turns out to be an intersection.
interface Foo { a: string }
interface Bar { b: string }
type Func<T> = (arg: T) => void;
function foo(func: Func<Foo> | Func<Bar>, arg: Foo | Bar) {
  func(arg); // error!
  // Argument of type 'Foo | Bar' is not assignable to parameter of type 'Foo & Bar'.
}

A: The compiler's behavior here is intentional and preserves type safety.  Before TypeScript 3.3 you couldn't even call a union of functions unless the parameter types were identical.  TypeScript 3.3 introduced improved behavior for calling union types and made it possible to call a union of functions with an intersection of parameters.  It would be unsafe to allow such a call with a union of functions.  From your example:
interface Foo { a: string }
interface Bar { b: string }
type Func<T> = (arg: T) => void;

function baz(func: Func<Foo> | Func<Bar>, arg: Foo | Bar) {
  func(arg); // error!
}

Let's imagine that the above code had no error in func(arg).  Let's see what happens with particular func and arg values:
const func: Func<Foo> | Func<Bar> =
  Math.random() < 0.01 ?
    (arg: Foo) => console.log(arg.a.toUpperCase()) :
    (arg: Bar) => console.log(arg.b.toUpperCase());

const unionArg: Foo | Bar = Math.random() < 0.99 ?
  { a: "hello" } :
  { b: "goodbye" }

func(unionArg); // imagine no compiler error
// very likely runtime error like arg.b is undefined
// (occasionally HELLO or GOODBYE)

Here, func is a Func<Foo> | Func<Bar>.  There is a 1% chance it will be a Func<Foo> and a 99% chance it will be a Func<Bar>, and we don't know which.  And unionArg is a Foo | Bar.  There is a 99% chance it will be a Foo, and a 1% chance it will be a Bar.  If there were no compiler error in func(unionArg), you'd happily assume that everything is fine.
But of course, at runtime, there is about a 98% chance that you are calling a Func<Bar> with a Foo input and a runtime error of the form arg.b is undefined will occur.  Oops.

The problem here is that a union of functions is more restrictive than either function type separately.  It's only safe to pass in a Foo to a Func<Foo>, and it's only safe to pass in a Bar to a Func<Bar>.  And if you don't know if your function is a Func<Foo> or a Func<Bar>, the only safe thing you could possibly pass in would have to be both a Foo and a Bar.  That is, Foo & Bar, the intersection:
const intersectionArg: Foo & Bar = { a: "hello", b: "goodbye" }
func(intersectionArg) // probably GOODBYE, occasionally HELLO, never runtime error

The intersectionArg is both a Foo and a Bar because it has both a string-valued a property and a string-valued b property.  Calling func(intersectionArg) is always safe, because no matter which function body ends up being executed, the parameter will definitely have the expected property.

Hence the intentional and useful conversion from a union-of-functions to an intersection-of-parameters.
Playground link to code


text:
Q: TF save/restore graph fails at tf.GraphDef.ParseFromString() Based on this converting-trained-tensorflow-model-to-protobuf I am trying to save/restore TF graph without success.
Here is saver:
with tf.Graph().as_default():
    variable_node = tf.Variable(1.0, name="variable_node")
    output_node = tf.mul(variable_node, 2.0, name="output_node")
    sess = tf.Session()
    init = tf.initialize_all_variables()
    sess.run(init)
    output = sess.run(output_node)
    tf.train.write_graph(sess.graph.as_graph_def(), summ_dir, 'model_00_g.pbtxt', as_text=True)
    #self.assertNear(2.0, output, 0.00001)
    saver = tf.train.Saver()
    saver.save(sess, saver_path)

which produces model_00_g.pbtxt with text graph description. Pretty much copy paste from freeze_graph_test.py.
Here is reader:
with tf.Session() as sess:

    with tf.Graph().as_default():
        graph_def = tf.GraphDef()
        graph_path = '/mnt/code/test_00/log/2016-02-11.22-37-46/model_00_g.pbtxt'
        with open(graph_path, "rb") as f:
            proto_b = f.read()
            #print proto_b   # -> I can see it
            graph_def.ParseFromString(proto_b) # no luck..
            _ = tf.import_graph_def(graph_def, name="")

    print sess.graph_def

which fails at graph_def.ParseFromString() with DecodeError: Tag had invalid wire type.
I am on docker container b.gcr.io/tensorflow/tensorflow:latest-devel in case it makes any difference.

A: The GraphDef.ParseFromString() method (and, in general, the ParseFromString() method on any Python protobuf wrapper) expects a string in the binary protocol buffer format. If you pass as_text=False to tf.train.write_graph(), then the file will be in the appropriate format.
Otherwise you can do the following to read the text-based format:
from google.protobuf import text_format
# ...
graph_def = tf.GraphDef()
text_format.Merge(proto_b, graph_def)

A: ParseFromString needs binary serialized protocol buffer, for human-readable representation you need to use text_format.Merge as used here

A: I tried to load model via the java API which accepts only binary. But in the python where we uses contrib.Estimator produces textual model file format.
I found a model file converter online, seems it's working fine.
This might solve the original issue too (use the binary model loader) if you have an existing text format model file.


text:
Q: Confused about core data one-to-many configuration Essentially I am creating an app that tracks packages - 1 tracking number to many - detailed updates for that tracking number.
For example:
Parent: Tracking #: 102391249
Tracking Updates:
Child1: Departed Location
Child2: At Local Fedex Facility
Child3: Delivered
The following is my current setup, the image on the left being the parent and right being the child:
Was this setup correctly? I am new to CoreData but coming from my knowledge of relational databases I am trying to make sure the id in the parent in the trackingid of the child to create the connection between the 2 "tables"

A: Set the one to many relationship between the Numbers and Details entities to connect the two entities. When you create an instance of the Details entity in your code, set its relationship to a Numbers entity.
child.numbers = parent

Where child is an instance of the Details entity and parent is an instance of the Numbers entity.
The numbers (changing the name to number would be clearer) relationship that you have in the Details entity gives you access to the tracking number. You can access the tracking number using the relationship and the Numbers entity's tracking number attribute.
let trackingNumber = child.numbers.trackingnumber

Since you have access to the tracking number from the relationship, you can remove the trackingid attribute from the Details entity.
By the way consider using clearer entity names than Numbers and Details. Your app deals with tracking shipping updates to packages. I recommend renaming Numbers to Package and Details to TrackingUpdates or ShippingDetails.


text:
Q: Interfacing Eclipse Workbench UI with GNU debugger functions I want to know how the Eclipse Workbench UI communicates with the GNU debugger.
What I mean is in the Eclipse for C/C++, when we press the step over or resume or continue buttons in the menu, what happens behind the scenes?
As in how is the GNU gdb invoked? How does gdb know which function to execute? How does the UI communicate with gdb?
I have added a custom function to the gdb(does not matter what the function is..) and I want to add a button to the Eclipse workbench such that pressing the button will call the gdb and that function in particular.
I want to know how Eclipse workbench UI interacts with the GNU gdb.
How do I go about doing this?
Thanks,
Rohit

A: See the "Accessing gdb with the Eclipse CDT and MI" article.

The GNU Debugger (gdb) is the most popular open source debugger in use. It's generally used as a command-line executable, but it can be accessed through software using the little-known MI protocol.

*

*The C/C++ Debugger Interface (CDI) was created by Eclipse/CDT developers so CDT can access external debuggers.

*The Machine Interface (MI) was created by gdb developers so external applications can access the gdb.

  In many cases, the MI result record is followed by (gdb) and an out-of-band (OOB) record. These records provide additional information about the status of the target or the debugging environment.
  The *stopped message after -exec-step is an OOB record that provides information about breakpoints, watchpoints, and why the target has halted or finished.
  In the previous session, gdb returns *stopped,reason="end-stepping-range" after each -exec-step, along with the status of the target.
gdb/MI is hard for humans to understand, but it's ideal for communication between software processes.
The CDT enables this communication by creating a pseudo-terminal (pty) that sends and receives data. Then, it starts gdb and creates two session objects to manage debug data.
The MI-CDI-wrapper-Eclipse communication is useful only if it updates Eclipse's graphical display with proper debug data.

When you right-click an entry in the Signals View, the Resume with Signal  context-menu option lets you continue the target's execution and send the selected signal to the process.
  This option calls on the SignalsActionDelegate.
  When this option is selected, the delegate calls on the CDI target to resume its execution with the ICDISignal corresponding to the selected signal.
  The target creates an MI command for the signal and invokes MISession.postCommand(), which sends the command to gdb.
When gdb responds, the process of updating the Signals View takes five steps:

*

*The MISession analyzes the MI output from gdb and determines whether a signal setting is being changed. If so, it fires an MISignalChangedEvent.

*The CDI EventManager listens for the MISignalChangedEvent and responds by creating a CDI event: ChangedEvent. Then it fires the event and alerts all ICDIEventListeners.

*The CDebugTarget receives the event from the EventManager and determines whether the ChangedEvent relates to a signal change. If so, it calls on its CSignalManager to process the CDI event.

*The CSignalManager updates its model elements and fires a DebugEvent whose type is given by DebugEvent.CHANGE.

*The SignalViewEventHandler receives the DebugEvent, checks to make sure it deals with signals, and refreshes the Signals View.

  Understanding the involved operation of the Signals View is important for two reasons;

*

*It serves as a concrete example of how the different model elements work together, and

*it shows how you can build similar views that interact with Eclipse, gdb, and the CDI.

  Conclusion

*

*Two session objects (MISession and Session),

*two targets (CDebugTarget and Target), and

*two completely different hierarchies of model elements