Q: Can anyone suggest how to implement the sorting by price of a product in android Recycler View As I needed to sort the values of an array List, I'm unable to get the sorting algorithms for the different algorithms like Selection sort, quick sort and bubble sort. I'm new to Android app development, please help me to solve this. thanks in advance
public class TestingSort {
public static void main(String args[]){

        ToSort toSort1 = new ToSort(new Float(3), "3");
        ToSort toSort2 = new ToSort(new Float(6), "6");
        ToSort toSort3 = new ToSort(new Float(9), "9");
        ToSort toSort4 = new ToSort(new Float(1), "1");
        ToSort toSort5 = new ToSort(new Float(5), "5");
        ToSort toSort6 = new ToSort(new Float(0), "0");
        ToSort toSort7 = new ToSort(new Float(3), "3");
        ToSort toSort8 = new ToSort(new Float(-3), "-3");

        List<ToSort> sortList = new ArrayList<ToSort>();
        sortList.add(toSort1);
        sortList.add(toSort2);
        sortList.add(toSort3);
        sortList.add(toSort4);
        sortList.add(toSort5);
        sortList.add(toSort6);
        sortList.add(toSort7);
        sortList.add(toSort8);

        Collections.sort(sortList);

        for(ToSort toSort : sortList){
            System.out.println(toSort.toString());
        }
    }

}

     public class ToSort implements Comparable<ToSort> {

    private Float val;
    private String id;

    public ToSort(Float val, String id){
        this.val = val;
        this.id = id;
    }

    @Override
    public int compareTo(ToSort f) {

        if (val.floatValue() > f.val.floatValue()) {
            return 1;
        }
        else if (val.floatValue() <  f.val.floatValue()) {
            return -1;
        }
        else {
            return 0;
        }

    }

    @Override
    public String toString(){
        return this.id;
    }
}

A: You need to use Comparator with Collections.sort()
Collections.sort(YourArraylist, new Comparator<ModelObject>(){
   public int compare(ModelObject o1, ModelObject o2){
      return o1.getPrice() - o2.getPrice();
   }
});

If you are using Java 8, You can use following code.
Collections.sort(YourArraylist, (o1, o2) -> o1.getPrice() - o2.getPrice());


Q: What (classes of) Banach spaces are known to have Schauder basis? Motivation:
I am trying to see for what class of Banach spaces the following result is true:

There exists an increasing sequence of finite dimensional subspace {$V_n$} of a Banach space X (with some property) and corresponding projections $P_n: X \to V_n$ such that
  a) $\cup V_n$ is dense in $X$
  b) $\sup_n ||P_n|| < \infty$

I know if the space has Schauder basis, then the result is automatic. Hence I would appreciate if you can let me know:
i) a reference for the above result (if it exists)
ii) positive results for large class of Banach spaces which has a Schauder basis
I have tried Googling and Wikipedia, but couldn't find systematic information about existence of Schauder basis. The only counterexample I found was given by Per H. Enflo.
Thank you! I apologize if there is any inappropriate etiquette in my post as I am relatively new to the forum.

A: The property you define is usually called the $\pi$ property.
For a good expository article, read Casazza's contribution in the Handbook of the Geometry of Banach Spaces, vol. 1.
Most of the classical separable Banach spaces are known to have a Schauder basis. The book of Albiac and Kalton is good place to start. Singer's two volumes "Bases in Banach Spaces" probably contains more than you would ever want to know.
In [JRZ], which you mentioned in a comment, you will find some results on when the $\pi$ property implies the existence of a finite dimensional decomposition and some results on the existence of bases, such as a separable complemented subspace of an $L_p$ space must have a Schauder basis.


Q: Amazon AWS EC2 Dashboard and SSH - Saving Text Files to Volumes As a new user of SSH and the Amazon AWS EC2 Dashboard, I am trying to test to see whether I can, in one instance, save data onto a volume, then access that data from another instance by adding the volume to the instance (after terminating the first instance).
When I create the first instance, the AMI is "Amazon Linux AMI 2014.03.2 (HVM)" and the family is "general purpose" with EBS storage only. I automatically assign a public IP address to the instance. I configure the root volume so that it does NOT delete on termination.
As soon as the instance is launched, I open up PuTTY and set the host name to the instance's Public IP Address under Port 22, and authenticate using a private key saved onto the disc that I have already generated earlier.
Upon signing into the instance, I create a text file by typing the following code:
echo "testing">test.txt
I then confirm that the text "testing" is saved to the file "test.txt":
less test.txt
I see the text "testing", thus confirming that it is saved to the file. (I am assuming at this point that it is saved onto the volume, but I am not entirely sure.)
I then proceed to terminate the instance. I launch another one using the same AMI, same instance type, and a different public IP address. In addition to the root volume, I attempt to add the volume that was used as the root volume for the previous instance. (Oddly enough, the snapchat IDs for the previous volume and the root volume of the new instance are identical.) In addition, I use the same tag instance, the same security group and the same key pair as the previous instance.
I open up PuTTY again, this time using the Public IP Address of the new instance, but still using the same private key and port used for the previous instance. Opening logging in, I type:
less test.txt
but I am greeted with this message:
test.txt: No such file or directory
Is there any advice that anyone can offer me regarding this issue. Is it even possible to store a text file onto a volume? If so, am I performing this operation incorrectly?

A: As the secondary volume has the same UUID and the Amazon Linux used UUID based identification for root, then there might be a chance that the secondary volume was taken as the root volume. This may be the reason why there would be a mess up in choosing the root volume and the initial attempt to find test.txt would fail.
The reboot might have allowed it to take a different order which is why you were able to find it.


Q: Python cannot import name from some scipy.signal methods import numpy as np
from scipy.integrate import odeint
from scipy.signal import find_peaks

The third line triggers the following error:
ImportError: cannot import name find_peaks

What is going on here? I haven't made any changes to the scipy package that I am aware of. Also it is worth noting that just importing scipy.signal does not produce an error.

A: Check your scipy version:
import scipy
print(scipy.__version__)

find_peaks is new in version 1.1.0.
If you want to update:
pip install scipy --upgrade

A: I just had to reinstall scipy and it worked on Mac OS with M1 and Python 3.9
pip uninstall scipy
and then
pip install scipy


Q: Send email notification when new work item created in Azure DevOps I have a requirement like, send an email notification with work item id when new work item created in Azure DevOps.
Is it possible to configure a notification with new work item id?

A: User ADO service hooks: https://learn.microsoft.com/en-us/azure/devops/extend/develop/add-service-hook?view=azure-devops
Search through available list and there you will see possible actions to react on. API hooks allows you to receive data based on Boards changes (e.g. Task status change etc).


Q: How to recognize a plugin that is good for Vundle ? - Vim I'm in trouble with some plugins, I can't say if they are for Vundle or not, as a consequence I can't say if the problem is Vundle itself or not, most of the vim docs are horribly paginated, so I'm asking, there is a way to know for sure that a plugin is designed to run under Vundle ?

A: Plugins are generally not designed for use with a specific plugin manager. They all use more or less the same mechanisms and standardized file structure and should work the same way whether they are installed manually or "managed" with Vundle, Pathogen or some other script.
You should read Vundle's and your non-working plugin's documentation to see if you can find the why and how of your issue.
Also, what plugins do you have issues with? How did you install them? Are you asking a question with the hope of getting help or just thinking out loud?


Q: FsRtlIsNameInExpression never matches anything I do string matching in a kernel driver using the Boyer-Moore algorithm, but I also need to implement basic wildcard support. This answer on SO mentionned the function FsRtlIsNameInExpression, which looks just right for my needs. It even looks like it handles case insensitivity for Unicode strings.
But it can't even get it to match a simple string with itself.
I tried a few things, but FsRtlIsNameInExpression never matches anything. Here is some code I used to test (I put the call to MyTest at the end of my DriverEntry routine).
NTSTATUS MyTest()
{
    int matches = 0;

    UNICODE_STRING a3times;
    UNICODE_STRING A5times;
    UNICODE_STRING bbb;
    UNICODE_STRING patterna;
    UNICODE_STRING patternb;

    RtlInitUnicodeString(&a3times, L"aaa");
    RtlInitUnicodeString(&A5times, L"AAAAA");
    RtlInitUnicodeString(&bbb, L"bbb");

    RtlInitUnicodeString(&patterna, L"a*a");
    RtlInitUnicodeString(&patternb, L"b*");

    if(FsRtlIsNameInExpression(&patterna, &a3times, TRUE, 0))
        ++matches;            // a*a should match aaa

    if(FsRtlIsNameInExpression(&patterna, &A5times, FALSE, 0))
        ++matches;            // a*a should match (insensitive) AAAAA

    if(FsRtlIsNameInExpression(&a3times, &a3times, TRUE, 0))
        ++matches;            //aaa should match aaa

    if(FsRtlIsNameInExpression(&patternb, &bbb, TRUE, 0))
        ++matches;            //b* should match bbb

    return matches;   //Should be 4, but is 0
}

For the record :

*

*I am using WDK version 7600.16385.1, checked build (my code, not Windows)

*The driver runs in a Virtual Box hosted Windows 7 Pro 64 bits on my Windows 7 Ultimate 64 bits

*The driver is signed by a test certificate

*I trace the code in a kernel debugger

*The code does not crash, but can't be called in user mode

What is the obvious that I am missing ?

A: The documentation says

If IgnoreCase is TRUE, Expression must be uppercase.

Note that, per your comments, you misunderstood the case-sensitivity parameter. It is IgnoreCase not CaseSensitive.
As for the results:

*

*Lower-case expression with IgnoreCase set to TRUE - won't work

*Lower-case expression, IgnoreCase set to FALSE, upper case pattern - won't match

*Lower-case expression with IgnoreCase set to TRUE - won't work

*Lower-case expression with IgnoreCase set to TRUE - won't work

Just really bad luck that not a single one worked :)


Q: Spring Data JDBC - Clob column to String property in POJO not working I have an Oracle database with a table that has a DESCRIPTION column of type CLOB.
My POJO looks like this:
import java.util.Date;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

import org.springframework.data.relational.core.mapping.Column;
import org.springframework.data.relational.core.mapping.Table;
import org.springframework.data.annotation.Id;

import lombok.Data;

@Data
@Table("MY_ITEMS")
@JsonIgnoreProperties(ignoreUnknown = true)
public class MyItem {

    @Column("ID") @Id Long id;
    @Column("DESCRIPTION") String description;
}

And my repository looks like this
import java.util.List;

import com.myapp.mymodel.MyItem;

import org.springframework.data.jdbc.repository.query.Query;
import org.springframework.data.repository.CrudRepository;

public interface MyItemsRepository extends CrudRepository<MyItem, Long> {

    // other methods deleted...

    @Query(
        "select m.ID"
            + ", m.DESCRIPTION"
        + " from MY_ITEM m "
    )
    List<MyItem> findMyItems();
}

When I call the repository method I get an error saying there is no converter for CLOB to String.
Any help is appreciated.

A: There's a very nice example here that solves the problem:
https://github.com/spring-projects/spring-data-examples/tree/master/jdbc/basics
The solution amounts to adding a configuration that registers a converter that can extract the CLOB data to the String property
import java.sql.Clob;
import java.sql.SQLException;
import java.util.Arrays;

import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;
import org.springframework.data.jdbc.core.convert.JdbcCustomConversions;
import org.springframework.data.jdbc.repository.config.AbstractJdbcConfiguration;
import org.springframework.data.jdbc.repository.config.EnableJdbcRepositories;
import org.springframework.data.relational.core.mapping.Embedded.Nullable;

@Configuration
@EnableJdbcRepositories
public class AggregateJdbcConfiguration extends AbstractJdbcConfiguration {

    @Override
    public JdbcCustomConversions jdbcCustomConversions() {

        return new JdbcCustomConversions(Arrays.asList(new Converter<Clob, String>() {

            @Nullable
            @Override
            public String convert(Clob clob) {

                try {

                    return Math.toIntExact(clob.length()) == 0 //
                            ? "" //
                            : clob.getSubString(1, Math.toIntExact(clob.length()));

                } catch (SQLException e) {
                    throw new IllegalStateException("Failed to convert CLOB to String.", e);
                }
            }
        }));
    }
}

Here are a few of my favorite videos on the subject
https://www.youtube.com/watch?v=EaHlancPA14&list=PLsC0nE-wJ1I4ra6KYXTPOXipdrJ_IdhaO&index=3&t=0s
https://www.youtube.com/watch?v=GOSW911Ox6s&list=PLsC0nE-wJ1I4ra6KYXTPOXipdrJ_IdhaO&index=4&t=59s
https://www.youtube.com/watch?v=AnIouYdwxo0&list=PLsC0nE-wJ1I4ra6KYXTPOXipdrJ_IdhaO&index=5&t=2730s
And a couple of blog posts
https://spring.io/blog/2018/09/24/spring-data-jdbc-references-and-aggregates
https://spring.io/blog/2018/09/17/introducing-spring-data-jdbc


Q: I can no longer debug classic asp code with visual studio 2008 I've finally found a way to debug classic asp code in visual studio 2008 ... but...
has anybody been able to debug asp classic code with visual studio 2005 or later?
... but ...
it only lasted a few days...
I'm following these steps
http://www.codeproject.com/KB/debug/DebugVBScriptVS2008.aspx
http://codepagoda.com/2009/04/30/debugging-classic-asp-with-visual-studio-2008-sp1-and-35-framework/
but now, when I do "attach process" I can no longer see the "Script, x86" process anymore...
so I can not debug classic asp code...
I tried restarting the machine, creating a new project, startgin from scrath, the only thing I haven't tried so far is to reinstall IIS...
any idea???
PLEASE HELP!!!!
edit: some info about my environment
Windows XP 2002 SP 3, IIS 5.1, Visual Studio 2008 9.0.30729.1 SP

A: The most likely reason for this is because the process hasn't spun up yet.  You need to hit an ASP page first before IIS spins up the DLLHOST.exe in which it runs an application if you have that application set to have high isolation (recommended for debugging purposes).
Hence debugging bia attachment requires the you use the browser to ping an ASP page in your site first, then open the Attach to process list.

A: I had the same problem. I fixed it out installing Service Pack 1 for my Visual Studio 2008. And now I attach to "inetinfo.exe" process instead of "dllhost.exe".

A: The following steps might help you:

*

*Host the site is IIS and make sure it's running

*Change the Application Configuration to enable debugging

*Then Attach the debugger to w3wp (IIS worker process)


Q: C++ Header files for shared library, which headers to install? (best practice) When creating a shared C++ library, what is best practice for installing header files?  More specifically, I have the following two questions:

*

*I am working on a shared library project with headers which have complex interdependencies, so do I simply install them all, or is there a way of restricting the number of headers needed?

*I plan to install headers to a subdirectory of e.g. /usr/local/include to avoid polluting the top level directory, is this the right thing to do?
Other info: I only really want to provide an interface to the library. The project is an autotools project and I am using the pkginclude_HEADERS command in my Makefile.am files to install the headers in the appropriate subdirectory. I am actually converting this project from a program that used static libraries, to a shared library and small program that links to the library. People are unlikely to use just a small part of the library rather than the whole thing.
Edit:
In response to a vote to close for being opinion based, I would also consider a valid answer that this is purely project-specific, or down to taste, and there is no accepted best practice, but I doubt this to be the case, or I would not have asked.

A: One common approach is to put public header files in a include directory and the rest of the  source files (both hpp and cpp) in a src directory. For example, suppose you're working on a  project called foo. A possible file hierarchy would be the following:
foo
    include
        foo
            x.hpp
            y.hpp
    src
        x.cpp
        y.cpp
        z.cpp
        z.hpp

In this case, you can simply add the include directory to the include path and you'll then be able to include the public header files like this: #include <foo/x.hpp>.

A: I want to share my ideas while I am not sure if I have the right answer:).
A:

*

*If the headers have complex inter-dependencies, it will be safer to simply install them all. Or you might want to read the source codes and clean the inter-dependencies.

*It is the right thing to put all the headers in one discretionary. :)


Q: Timer with read BLE Characteristic I'm building an Android Service. This Service should to connect of BLE device and download all informatio that it have storage in yuor memory.
Now I want that this Service can running in background.
This is my BlePowerService that extends Service
public class BlePowerService extends Service {
    public DbLayer db;
    Setting settingApp;
    List<ScanFilter> filters;
    String[] stringSequence = new String[] {CHARACTERISTIC_FORZA_STRING, CHARACTERISTIC_TEMPERATURA_STRING};
    BluetoothAdapter mBluetoothAdapter;
    BluetoothGatt mGatt;
    BluetoothDevice currDevice;
    static final long SCAN_PERIOD = 500;
    static String SPLIT_CHAR =";";
    BluetoothLeScanner mLEScanner;
    Handler mHandler;
    int ReadQueueIndex;
    List<BluetoothGattCharacteristic> ReadQueue;
    BluetoothGattCharacteristic caratteristicaDaLeggere;
    ScanSettings settings;
    Integer ultimaForzaLetta,ultimaTemperaturaLetta;
    boolean continuaLetturaForza, continuaLetturaTemperatura;
    boolean isReading = true;
    String LOG_CODE = "NOTIFSRV";
    GattClientCallback gattClientCallback;
    private static final int PERMISSION_REQUEST_COARSE_LOCATION = 1;

    public BlePowerService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        //throw new UnsupportedOperationException("Not yet implemented");
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        mHandler = new Handler();

        Context sharedContext = null;
        try {
            sharedContext = this.createPackageContext(
                    "com.care.devicesensor",
                    Context.CONTEXT_INCLUDE_CODE);
            if (sharedContext == null) {
                return;
            }
            db=new DbLayer(sharedContext);
            db.open();
        } catch (Exception e) {
            String error = e.getMessage();
          //  Log.d(LOG_CODE,"DB error : " + error);
            return;
        }
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        try {
            //RECUPERO LE IMPOSTAZIONI SETTATE DALL'UTENTE
            settingApp = db.fetchSetting();
            if (settingApp != null && settingApp.getAddressBleSX()!=null) {
                //POSSO FILTRARE DIRETTAMENTE PER L'UUID DEL DISPOSITIVO MEMORIZZATO
                //DALL'UTENTE
                ScanFilter.Builder scanFilterMac =
                        null;
                    scanFilterMac = new ScanFilter.Builder().setDeviceAddress(settingApp.getAddressBleSX());
                if(filters==null)
                    filters = new ArrayList<ScanFilter>();
                //if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                filters.add(scanFilterMac.build());
                //}
                //FILTRO ANCHE PER LA CARATTERISTICA DI FORZA
                ScanFilter filter = null;
                    filter = new ScanFilter.Builder().setServiceUuid(ParcelUuid.fromString(CHARACTERISTIC_FORZA_STRING)).build();
                filters.add(filter);

                final BluetoothManager bluetoothManager =
                        (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
                    mBluetoothAdapter = bluetoothManager.getAdapter();
                //mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
                    mLEScanner = mBluetoothAdapter.getBluetoothLeScanner();
                    settings = new ScanSettings.Builder()
                            .setScanMode(ScanSettings.SCAN_MODE_LOW_POWER)
                            .build();
                scanLeDevice(true);
                mTimer = new Timer();
                //ogni 2 ore
                continuaLetturaForza = true;
                continuaLetturaTemperatura = true;

                int nSecondi = settingApp.getFrequenzaDownload()!= null ? settingApp.getFrequenzaDownload() : 1;
                mTimer.schedule(timerTask, 10000, 1000 * nSecondi);
            }
        } catch (Exception e) {
           // Log.e("POWER_SERVICE", e.getMessage());
        }
        return super.onStartCommand(intent, flags, startId);
    }

    private Timer mTimer;

    TimerTask timerTask = new TimerTask() {

        @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
        @Override
        public void run() {
            //LEGGO TUTTI I DATI DAL SENSORE FINCHE CI SONO VALORI

            int counter = 0;
            while(continuaLetturaForza || continuaLetturaTemperatura){
                counter++;
                Log.v("CICLO WHILE", counter+"");
                if (currDevice != null) {

                    if(ReadQueue!= null && ReadQueue.size()>0){
                        int index =0;
                        for(index=0; index < ReadQueue.size(); index++){
                            isReading = mGatt.readCharacteristic(ReadQueue.get(index));
                            while(isReading){
                                try {
                                   Thread.sleep(1);
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }
                            }

                        }
                    }

                }else{
                    //provo a ricollegarmi al dispositivo probabile, abbia perso la connessione con esso
                    scanLeDevice(true);
                    try {
                        Thread.sleep(2500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    if(currDevice == null && counter == 25){
                        //in questo caso non è riuscito a trovare il dispositivo BLE
                        //esco dal ciclo
                        continuaLetturaForza = false;
                        continuaLetturaTemperatura = false;
                        continue;
                    }
                }

            }

            if(gattClientCallback!=null && mGatt != null)
                gattClientCallback.disconnectGattServer();
        }
    };

    public void connectToDevice(BluetoothDevice device) {
        //VERIFICO SE IL DEVICE è QUELLO CHE VOGLIO IO
        if (mGatt == null && settingApp != null
                && device.getAddress().equals(settingApp.getAddressBleSX())) {
            currDevice = device;
            gattClientCallback = new GattClientCallback();
            mGatt = currDevice.connectGatt(getBaseContext(), false, gattClientCallback);
            scanLeDevice(false);// will stop after first device detection
        }
    }

    private BluetoothAdapter.LeScanCallback mLeScanCallback =
            new BluetoothAdapter.LeScanCallback() {
                @Override
                public void onLeScan(final BluetoothDevice device, int rssi,
                                     byte[] scanRecord) {
                    Handler h = new Handler(getApplicationContext().getMainLooper());
                    // Although you need to pass an appropriate context
                    h.post(new Runnable() {
                        @Override
                        public void run() {
                          //  Log.i("onLeScan", device.toString());
                                connectToDevice(device);

                        }
                    });
                }
            };

    private void scanLeDevice(final boolean enable) {
        if (enable) {
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (Build.VERSION.SDK_INT < 21) {
                        mBluetoothAdapter.stopLeScan(mLeScanCallback);
                    } else {
                        mLEScanner.stopScan(mScanCallback);

                    }
                }
            }, SCAN_PERIOD);
            if (Build.VERSION.SDK_INT < 21) {
                mBluetoothAdapter.startLeScan(mLeScanCallback);
            } else {
                mLEScanner.startScan(filters, settings, mScanCallback);
            }
        } else {
            if (Build.VERSION.SDK_INT < 21) {
                mBluetoothAdapter.stopLeScan(mLeScanCallback);
            } else {
                mLEScanner.stopScan(mScanCallback);
            }
        }
    }

    private ScanCallback mScanCallback = new ScanCallback() {
        @Override
        public void onScanResult(int callbackType, ScanResult result) {
           // Log.i("callbackType", String.valueOf(callbackType));
           // Log.i("result", result.toString());
            BluetoothDevice btDevice = null;
               btDevice = result.getDevice();
            connectToDevice(btDevice);
        }

        @Override
        public void onBatchScanResults(List<ScanResult> results) {
            for (ScanResult sr : results) {
                Log.i("ScanResult - Results", sr.toString());
            }
        }

        @Override
        public void onScanFailed(int errorCode) {
           Log.e("Scan Failed", "Error Code: " + errorCode);
        }
    };

    private class GattClientCallback extends BluetoothGattCallback {

        @Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
            try{
                super.onConnectionStateChange(gatt, status, newState);
                Log.i("tag", "onConnectionStateChange newState: " + newState);

                if (status == BluetoothGatt.GATT_FAILURE) {
                    Log.e("ERROR_SERVICE", "Connection Gatt failure status " + status);
                    if(mGatt == null){

                    }else{
                        try {
                            gatt.close();
                        } catch (Exception e) {
                            Log.d("", "close ignoring: " + e);
                        }
                        mGatt = null;
                    }
                    return;
                } else if (status != BluetoothGatt.GATT_SUCCESS) {
                    // handle anything not SUCCESS as failure
                    Log.e("ERROR_SERVICE", "Connection not GATT sucess status " + status);
                    if(mGatt == null){

                    }else{
                        try {
                            gatt.close();
                        } catch (Exception e) {
                            Log.d("", "close ignoring: " + e);
                        }
                        mGatt = null;
                    }
                    return;
                }

                if (newState == BluetoothProfile.STATE_CONNECTED) {
                    //Log.i("INFO", "Connected to device " + gatt.getDevice().getAddress());
                    gatt.discoverServices();
                } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
                    Log.i("INFO", "Disconnected from device");
                    if(mGatt == null){

                    }else{
                        try {
                            gatt.close();
                        } catch (Exception e) {
                            Log.d("", "close ignoring: " + e);
                        }
                        mGatt = null;
                    }

                }
            }catch(Exception e){
                Log.e("tag", e.getMessage());
                continuaLetturaForza = true;
                continuaLetturaTemperatura = true;
            }
        }

        public void disconnectGattServer() {
            //Log.i("INFo", "Closing Gatt connection");
            //  clearLogs();
            //mConnected = false;
            //mEchoInitialized = false;
            continuaLetturaForza = false;
            continuaLetturaTemperatura = false;
            if (mGatt == null) {

            }
            else{
                try{
                    mGatt.disconnect();
                   // mGatt.close();
                }catch(Exception e){
                    mGatt = null;
                }

            }
            //mGatt = null;
            //currDevice = null;
        }

        @Override
        public void onServicesDiscovered(BluetoothGatt gatt, int status) {
            super.onServicesDiscovered(gatt, status);

            if (status != BluetoothGatt.GATT_SUCCESS) {
             //   Log.i("INFO", "Device service discovery unsuccessful, status " + status);
                return;
            }

            List<BluetoothGattCharacteristic> matchingCharacteristics =
                    BluetoothUtils.findCharacteristics(gatt,stringSequence);
            if (matchingCharacteristics.isEmpty()) {
              //  Log.e("ERROR_SERVICE","Unable to find characteristics.");
                return;
            }else {

                //INIZIALIZZO LA LISTA DI CARATTERISTICHE CHE DEVO ANDARE A LEGGERE
                ReadQueue = new ArrayList<>();
                for (BluetoothGattCharacteristic characterist : matchingCharacteristics) {
                    ReadQueue.add(characterist);
                }
            }

        }

        @Override
        public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
            super.onCharacteristicRead(gatt, characteristic, status);
            if (status == BluetoothGatt.GATT_SUCCESS) {
                Log.v("INSERT_DB", "*****************************************");
                Log.v("INSERT_DB", "*****************************************");
                Log.v("INSERT_DB", "*****************************************");
                Log.v("INSERT_DB", "INSERISCO LE CARATTERISTICHE LETTE SUL DB");
                //readCharacteristic(characteristic);
                String valoreRestituito = characteristic.getStringValue(0);
                if(valoreRestituito==null){
                    int i = 0;
                    i = i + 1;
                    return;
                }
                //SPLITTO PER IL CARATTERE ;
                String[] arrayValori = valoreRestituito.split(SPLIT_CHAR);
                //1 valore è l ID
                try{
                    int id = new Integer(arrayValori[0]);
                    //VERIFICO SE STO LEGGENDO TEMPERATURA O FORZA
                    if(characteristic.getUuid().equals(CHARACTERISTIC_FORZA_UUID)){
                        Log.v("CARATTERISTICA", "*****************************************");
                        Log.v("FORZA", "*****************************************");
                        if(ultimaForzaLetta!= null && ultimaForzaLetta == id){
                            continuaLetturaForza = false;
                            isReading = false;
                            return;
                        }
                        ultimaForzaLetta = id;
                    }else if(characteristic.getUuid().equals( CHARACTERISTIC_TEMPERATURA_UUID)){
                        Log.v("CARATTERISTICA", "*****************************************");
                        Log.v("TEMPERATURA", "*****************************************");
                        if(ultimaTemperaturaLetta!= null && ultimaTemperaturaLetta == id){
                            continuaLetturaTemperatura = false;
                            isReading = false;
                            return;
                        }
                        ultimaTemperaturaLetta = id;
                    }

                    SensorData mSenData = new SensorData();
                    mSenData.setIdType(id);
                    mSenData.setValue1(arrayValori[1]);
                    mSenData.setValue2(arrayValori[2]);
                    mSenData.setValue3(arrayValori[3]);
                    mSenData.setValue4(arrayValori[4]);
                    mSenData.setValue5(arrayValori[5]);
                    mSenData.setValue6(arrayValori[6]);
                    mSenData.setValue7(arrayValori[7]);
                    mSenData.setValue8(arrayValori[8]);
                    //TO-DO HO COMMENTATO QUESTA RIGA DI CODICE
                    // mSenData.setIdType(st.getId());
                    mSenData.setCharacteristic(characteristic.getUuid().toString());
                    mSenData.setValueTimestamp(db.getDateTime(true));
                    //inserisco i dati nel db
                    Log.v("INSERT_DB",valoreRestituito);
                    Log.v("INSERT_DB", "*****************************************");
                    Log.v("INSERT_DB", "*****************************************");
                    Log.v("INSERT_DB", "*****************************************");
                    Log.v("INSERT_DB", "*****************************************");
                    Log.v("INSERT_DB", "*****************************************");
                    Log.v("INSERT_DB", "*****************************************");
                    Log.v("INSERT_DB", "FINE LE CARATTERISTICHE LETTE SUL DB");
                    db.insertSensorData(mSenData);

                    EventBus.getDefault().post(new MessageEvent("update"));

                    //EventBus.getDefault().post(new UnfriendEvent(userId));
                }catch (Exception e){
                    Log.e("ERROR", e.getMessage());
                }
                isReading = false;

            } else {
                isReading = false;
                Log.e("ERROR_SERVICE", "Characteristic read unsuccessful, status: " + status);
                Log.e("ERROR_SERVICE", "Characteristic read unsuccessful, status: " + status);
                Log.e("ERROR_SERVICE", "Characteristic read unsuccessful, status: " + status);
                Log.e("ERROR_SERVICE", "Characteristic read unsuccessful, status: " + status);
                Log.e("ERROR_SERVICE", "Characteristic read unsuccessful, status: " + status);
                Log.e("ERROR_SERVICE", "Characteristic read unsuccessful, status: " + status);
                Log.e("ERROR_SERVICE", "Characteristic read unsuccessful, status: " + status);
                Log.e("ERROR_SERVICE", "Characteristic read unsuccessful, status: " + status);
                Log.e("ERROR_SERVICE", "Characteristic read unsuccessful, status: " + status);

                // Trying to read from the Time Characteristic? It doesnt have the property or permissions
                // set to allow this. Normally this would be an error and you would want to:
                disconnectGattServer();

                return;
            }
        }
    }

    public void onDestroy() {
        try {
            db.close();
            Log.d(LOG_CODE,"DB connection closed" );

            mTimer.cancel();
            timerTask.cancel();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

In the onStartCommand method I create a Timer that run the service every X time.
The "cycle while" can download all information of BLE device, throught onCharacteristicRead method.
Now the question is, if unit I can to read a characteristic, I turn off the BLE device, I can rileve this status change connection by onConnectionStateChange method, but the Timer it is never performed again.
Why the Timer is not execute again?


Q: Basic loop and totaling positive inputs Consider:
print("Welcome to the number program")
number = input("Please give me a number \n")
number = int(number)
total_number = 0
entries = 0

while number > 0:
    total_number = total_number + number
    print(total_number)
    number = input("Please give me another number! \n")
    number = int(number)
    entries = int(entries) + 1
if number < 0:
    print("Sorry, this value needs to be positive. Please enter a
different number.")

if number == -999:
    print(total_number)
    print(entries)
    print(total_number/entries)

I'm in a beginners programming class, and the book is not very helpful at times. I'm trying to write a basic program that takes positive numbers, totals them, and averages them out at the end. It also rejects negative numbers, and asks if -999 is entered. I print the average of all entries, amount of entries, and the value tally.
The program runs ok, but it just doesn't write out some things I wanted.

A: From what you wrote and the comments in your code I am guessing that you want the program to continue running and asking for input if you enter a non-positive number. In that case I would rewrite it as:
print("Welcome to the number program")
total_number = 0
entries = 0

while True:
    number = input("Please give me a number \n")
    number = int(number)

    if number == -999:
        break

    if number <= 0:
        print("Sorry, this value needs to be positive. Please enter a different number.")
        continue

    total_number = total_number + number
    entries += 1
    print(total_number)

print(total_number)
print(entries)
print(total_number / entries)

Also, you can increment numbers with entries += 1

A: *

*In most cases you should NOT create variables first, however this case you should. Create number = 0, tally = 0 and total_number = 0 first

*Accept your first number inside your while loop and handle all of the logic in there as well.

*Your while loop should continue to loop until the final condition is met which seems to be number == -999

*Should tally be incremented if you enter a negative number? I assume not. What about a 0? Wrap the increment for tally and the addition to total_number in an if number > -1: condition. Use an if else to check for number == -999, and an else for handling invalid entries.

*Finally, move your print statements outside of your while loop. It also doesn't need a condition around it because now, if you've exited your while loop, that condition has been satisfied.

Final note here, and this is just a nice to know/have and purely syntactic sugar, MOST languages support abbreviated incrementing. Theres a better word for it, but the gist is simply this.
total_number += number
# is exactly the same as
total_number = total_number + number
# but way nicer to read and write :)

    print("Welcome to the number program")
    number = 0
    total_number = 0
    entries = 0

    while number != -999:
        number = input("Please enter a number! \n")

        number = int(number)

        if number >= 0
            total_number += number
            entries += 1
            print("Current sum: " + total_number)
        elif number == -999:
            break
        else
            print("Sorry, this value needs to be positive.")

    print("Sum of entries: "+str(total_number))
    print("Number of entries: " + str(entries))
    print("Average entry: " +str(total_number/entries))

A: I have rewritten your code. But I am not sure what the goal was. Anyways, if the value were ever to be under 0 the loop would have been exited and a new value would have never been accepted from an input.
Also some things I have written more elegant.
print("Welcome to the number program")
number=int(input("Please give me a number \n"))
total_number=0
entries=0

while number > 0:
    total_number += number
    print(total_number)
    number = int(input("Please give me another number! \n"))
    entries += 1
    if number == -999:
        print(total_number)
        print(entries)
        print(total_number/entries)
        break
    elif number < 0:
        number = input("Sorry, this value needs to be positive. Please enter a different number!")


Q: Find and replace multiple character in a string VBA I have a large amount of data which i want to replace with the help of macro. I am using code below right now but problem is that it will only replace one value which is D in below code.
Sub Replace()

what = "D"
replc = ""

Sheets("Sheet1").Select

Cells.replace What:=word, Replacement:=replc, LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=True, SearchFormat:=False, _
ReplaceFormat:=False

End Sub

My sample data is below. As you can see that some value have alphabetical characters, symbol or combination of character at the end or as a cell value, which i want to replace or remove and also some value will be replaced with other values. I create macro with all possibilities to find the required value and replace it.
0065D   2089    2797    3270    3315
0066D   2095    2799    3300    3334
0067D   2105    2802    3582aX a
2089    –   2812    3307    3383
2095    2111    1164D   3315    3385
2105    2112    1165D   3334    3400
2110    2114    2841    3336F   3507
0771N   2121    2881    3365    3515N
*0908P*   2130    2883    3372X   3548
0913P   2131    2913    3373    3559
2111    2143    2915    3373    3574
You also notice that there are some lower case characters as well. Right now i was trying to use IF condition with Find but could not succeed. I am making above macro with every possible condition to replace and run it from another macro which is something like below algo.
IF  find "D"  Then

Run macro "Replace"

Elseif  find "X"

Run macro "Replace"

Elseif  find "F"

Run macro "Replace"

and so on....

but if the macro didn't find required character in the sheet then it skips to next step and so on. I want this so bad. I have to perform this replace routine on number of times.
So any help will be appreciated.
Thanks

A: You can add/remove necessary characters from the toRemove() array.
Sub replaceChars()
Dim toRemove()

toRemove() = Array("D", "X", "F")

For Each itm In toRemove()
    For Each iCell In ActiveSheet.UsedRange
        iCell.Replace What:=itm, Replacement:="", MatchCase:=True
    Next iCell
Next itm

End Sub


Q: Groovy regex when replacing tokens in file I have a text file that has the token "%%#%" located all over the place inside of it. I am trying to write a quick-and-dirty Groovy shell script to replace all instances of "%%#%" with a dollar sign "$".
So far I have:
#!/usr/bin/env groovy
File f = new File('path/to/my/file.txt')
f.withWriter{ it << f.text.replace("%%#%", "$") }

But when I run this script, nothing happens (no exceptions and no string replacement). I wonder if any of the characters I'm searching for, or the dollar sign itself, is being interpreted as a special char by the regex engine under the hood. In any event, Where am I going awry?

A: I had to read the file content first, and then write on the file. Seems like withWriter erases the file contents:
def f = new File('/tmp/file.txt')
text = f.text
f.withWriter { w ->
  w << text.replaceAll("(?s)%%#%", /\$/)
}

You might want to do a per line read if the file is too large. Otherwise, you can use that multiline (?s) regex.
Note I escaped $, because replace and replaceAll behaves differently, in a sense that replace accepts a char and, thus, will be unaffected by regex strings, whereas replaceAll will need escaping.
Here is my test:
$ echo "%%#%
aaaa
bbbb
cccc%%#%dddd" > file.txt && groovy Subst.groovy && cat file.txt
$
aaaa
bbbb
cccc$dddd


Q: Is it safe when compare 2 float/double directly in Java? Is it safe if I use comparision like this (a is int, b and c is float/double):
a == b
b == c

It may hear ridiculous, but in my old programing language, sometimes 1 + 2 == 3 is false (because left side returns 2.99999999999...). And, what about this:
Math.sqrt(b) == Math.sqrt(c)
b / 3 == 10 / 3 //In case b = 10, does it return true?

A: You do need to exercise some care.
1.0 + 2.0 == 3.0

is true because integers are exactly representable.
Math.sqrt(b) == Math.sqrt(c)

if b == c.
b / 3.0 == 10.0 / 3.0

if b == 10.0 which is what I think you meant.
The last two examples compare two different instances of the same calculation. When you have different calculations with non representable numbers then exact equality testing fails.
If you are testing the results of a calculation that is subject to floating point approximation then equality testing should be done up to a tolerance.
Do you have any specific real world examples? I think you will find that it is rare to want to test equality with floating point.

A: b / 3 != 10 / 3 - if b is a floating point variable like b = 10.0f, so b / 3 is 3.3333, while 10 / 3 is integer division, so is equal to 3.
If b == c, then Math.sqrt(b) == Math.sqrt(c) - this is because the sqrt function returns double anyways.
In general, you shouldn't be comparing doubles/floats for equation, because they are floating point numbers so you might get errors. You almost always want to compare them with a given precision, i.e.:
b - c < 0.000001

A: The safest way to compare a float/double with something else is actually to use see if their difference is a small number.
e.g.
Math.abs(a - b) < EPS

where EPS can be something like 0.0000001.
In this way you make sure that precision errors do not affect your results.

A: == comparison is not particularly safe for doubles/floats in basically any language.  An epsilon comparison method (where you check that the difference between two floats is reasonably small) is your best bet.
For:
Math.sqrt(b) == Math.sqrt(c)

I'm not sure why you wouldn't just compare b and c, but an epsilon comparison would work here too.
For:
b / 3 == 10 / 3

Since 10/3 = 3 because of integer division, this will not necessarily give the results you're looking for.  You could use 10.0 / 3, though i'm still not sure why you wouldn't just compare b and 10 (using the epsilon comparison method in either case).

A: In general, no it is not safe due to the fact that so many decimal numbers cannot be precisely represented as float or double values.  The often stated solution is test if the difference between the numbers is less than some "small" value (often denoted by a greek 'epsilon' character in the maths literature).
However - you need to be a bit careful how you do the test.  For instance, if you write:
if (Math.abs(a - b) < 0.000001) {
    System.err.println("equal");
}

where a and b are supposed to be "the same", you are testing the absolute error.  If you do this, you can get into trouble if a and b are (say_ 1,999,999.99 and 2,000,000.00 respectively.  The difference between these two numbers is less than the smallest representable value at that scale for a float, and yet it is much bigger than our chosen epsilon.
Arguably, a better approach is to use the relative error; e.g. coded (defensively) as
if (a == b ||
    Math.abs(a - b) / Math.max(Math.abs(a), Math.abs(b)) < 0.000001) {
    System.err.println("close enough to be equal");
}

But even this is not the complete answer, because it does not take account of the way that certain calculations cause the errors to build up to unmanageable proportions.  Take a look at this Wikipedia link for more details.
The bottom line is that dealing with errors in floating point calculations is a lot more difficult than it appears at first glance.

The other point to note is (as others have explained) integer arithmetic behaves very differently to floating point arithmetic in a couple of respects:

*

*integer division will truncate if the result is not integral

*integer addition subtraction and multiplication will overflow.

Both of these happen without any warning, either at compile time or at runtime.

A: Float wrapper class's compare method can be used to compare two float values.
Float.compare(float1,float2)==0

It will compare integer bits corresponding to each float object.

A: In java you can compare a float with another float,and a double with another double.And you will get true when comparing a double with a float when their precision is equal

A: b is float and 10 is integer then if you compare both with your this critearia then it will give false because...
b = flaot (meance ans 3.33333333333333333333333)
10 is integer so that make sence.

A: If you want a more complete explanation, here there is a good one: http://download.oracle.com/docs/cd/E19957-01/806-3568/ncg_goldberg.html (but it is a little bit long)


Q: HA-Proxy balancing by source doesnt appear consistent Using HA-Proxy 1.4.18 I am using balance source as the option to balance a tcp stream to 2 servers. However from an admittedly very small sample set of connections it appears that they all just go to the one server - the server listed first in the haproxy config.

*

*listen videos *:1935

*balance source

*mode tcp

*server  server1 192.168.0.1:1935

*server  server2 192.168.0.2:1935

I have not seen it split the load onto the 2 boxes. This does work when I use balance roundrobin however for this particular application I cannot use this method.
Any ideas for an otherwise persistent session loadbalanced between these 2 machines from the clients?
Cheers

A: How did you test the balance ?, the doc says :

The source IP address is hashed and divided by the total
  weight of the running servers to designate which server will
  receive the request. This ensures that the same client IP
  address will always reach the same server as long as no
  server goes down or up. If the hash result changes due to the
  number of running servers changing, many clients will be
  directed to a different server. This algorithm is generally
  used in TCP mode where no cookie may be inserted. It may also
  be used on the Internet to provide a best-effort stickiness
  to clients which refuse session cookies. This algorithm is
  static by default, which means that changing a server's
  weight on the fly will have no effect, but this can be
  changed using "hash-type"

If you tested with just 2 different IP source you maybe fall in a particular case.


Q: Android - Erasing view above fragment introduces delay in touch event The context
I'm developing an application where the user can reveal a content (mapfragment) through erasing with its fingers the view in front.
I've created a customView (similar to google fingerpaint - erasing sample) handling the drawing and I add this view in front of my content.
I've added a function to log the time between two ontouchevent moves.
case MotionEvent.ACTION_MOVE:
  mTime = System.currentTimeMillis()-mTime;
  mTimeList.add(mTime);
  mTime = System.currentTimeMillis();
  [...]
  path.lineTo(event.getX(), event.getY());
  invalidate();
  break;
case MotionEvent.ACTION_UP:
  int listSize = mTimeList.size();
  long value =0;
  for (Long time : mTimeList) {
  value = value+time;
  }
  int finalvalue = (int) ((value/listSize));
  Log.i("MotionEvent", "Average time : "+Long.toString(finalvalue));
break;

My problem

*

*When I create my activity and set layout to my custom view, it works very well. There is only my customView, and the time between two moves is around 17ms.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(new MyView(this));

*When I create my activity and add my custom view to an empty mainlayout (relativelayout), the time between two moves is almost the same.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mapfullscreen_hotcold);
RelativeLayout mainLayout = (RelativeLayout)findViewById(R.id.mapfullscreen_relativeLayout);
MyView view = new MyView(this);
mainLayout.addView(view);

*When I create my activity and add my custom view to a mainlayout (relativelayout) which includes a mapfragment, the time between two moves is around 47ms.
---ACTIVITY---
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mapfullscreen_hotcold);
RelativeLayout mainLayout = (RelativeLayout)findViewById(R.id.mapfullscreen_relativeLayout);
MyView view = new MyView(this);
mainLayout.addView(view);

---XML---
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/mapfullscreen_relativeLayout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment
android:id="@+id/mapfullscree_mapLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:name="com.google.android.gms.maps.MapFragment" />
</RelativeLayout>

What can I do to make it faster?
When I touch the view, the content below should not impact my view-motionevent, right?
EDIT:
And when I add my custom view to a mainlayout (relativelayout) which includes an imageView populated with mapsStaticAPI, the time between two moves is around 17ms/19ms.
What are the solutions to keep a googleMapsFragment with a short delay between two moves?


Q: Doctrine: merge 2 requests in 1 I would like to merge these 2 requests in 1 but I have no clue on how to do this. Any idea ?
$productsCount = Doctrine::getTable('Product')
            ->createQuery('p')
            ->where('p.store_id = ?', $store_id)
            ->andWhere('p.collection = ?', $this->product->getCollection())
            ->andWhere('p.image_path IS NOT NULL')
            ->count();

$productsCollection = Doctrine::getTable('Product')
            ->createQuery('p')
            ->where('p.store_id = ?', $store_id)
            ->andWhere('p.collection = ?', $this->product->getCollection())
            ->andWhere('p.status_id = ?', Product::_ONLINE)
            ->andWhere('p.id<>?', $this->product_id)
            ->offset(rand(0, $productsCount - 1))
            ->execute();

*

*Doctrine: 1.2

*Symfony: 1.4

*PHP: 5.3

A: You can use subquery, because your query is not identical. Here DQL: Doctrine Query Language some example. And here is pseudocode, I do not know if it will work at once.
$q = Doctrine_Query::create()
            ->from('Product p')
            ->select('id, sum(id) as sumEntries')
            ->addSelect('(SELECT id, name) // and else fields that you need
                        FROM Product a
                        WHERE (
                        a.store_id  = '.$store_id.'
                        AND
                        a.collection = '.$this->product->getCollection().'
                        AND
                        a.id<>= '.$this->product_id.'
                        )
                        OFFSET '.rand(0, $productsCount - 1).') // I am not sure in this line
                        as resultSubquery')

            ->where('p.store_id = ?', $store_id)
            ->andWhere('p.collection = ?', $this->product->getCollection())
            ->andWhere('p.image_path IS NOT NULL')

  $result =  $q->execute(array(), Doctrine_Core::HYDRATE_ARRAY); //This greatly speeds up query

You get an array in $result. Do var_dump() and check its contents. I'm not sure that this code will work at once, but I advise you to move in this direction.
p.s: I recommend you this interesting presentation about Doctrine query optimization: Doctrine 1.2 Optimization


Q: Create custom object array with jQuery.map() function

I have table as seen above and I want to create a custom array to pass values.
Currently I am using the following lines of code:
var arr = $('input[type=text].editfield').map(function () {
        return this;
    }).get();
    var objArr = jQuery.map(arr, function (i) {
        return {
            myDate: i.parentElement.previousSibling.previousSibling.previousSibling.previousSibling.previousSibling.previousSibling.childNodes[0].textContent,
            myValue: i.value
        }
    }).get();

and I expect to have an array of objects of all items in my grid with Date and Value as properties respectively.
But something is wrong and I can not solve. For example the code above says "jQuery.map(...).get is not a function"
How can I correct my code to perform the correct action?

A: There is no need to use .get() on the static jQuery.map() function, it returns a proper array, while the plugin method .map() returns a jQuery object on which you have to call .get() to get an array.

Also there is no need to use 2 loops,
var objArr = $('input[type=text].editfield').map(function (idx, i) {
    //the element selection used here is cruel, if you can share the html used we can help you to clean it
    return {
        // you can try myDate: $(this).parent().prevAll().eq(5).text() - not testable without the html and what is the expected output
        myDate: i.parentElement.previousSibling.previousSibling.previousSibling.previousSibling.previousSibling.previousSibling.childNodes[0].textContent,
        myValue: i.value
    };
}).get();


Q: Exception ActiveRecord::AdapterNotSpecified occurs when connecting Heroku <-> Postgres (EC2) I've a Heroku app that is trying to connect to a Postgres DB on EC2. Here is the issue that I'm getting:
2011-05-30T23:07:48+00:00 app[web.1]: /app/.bundle/gems/ruby/1.8/gems/activerecord-3.0.0/lib/active_record/connection_adapters/abstract/connection_specification.rb:66:in `establish_connection': database configuration does not specify adapter (ActiveRecord::AdapterNotSpecified)

2011-05-30T23:07:48+00:00 app[web.1]:   from /app/.bundle/gems/ruby/1.8/gems/activerecord-3.0.0/lib/active_record/connection_adapters/abstract/connection_specification.rb:60:in `establish_connection'

I've followed the heroku instructions described here to set up the database configurations on the heroku app. Here are some other things that might help:

*

*I can connect to the postgresql db using a psgql admin on my computer (showcasing that the port forwarding and listening to hosts is set up correctly ..and no I'm not allowing ONLY my IP to enter - its wild carded so that all ips can connect)

*The version of postgresql that i'm running on EC2 is 8.4 while Heroku normally uses 9.0 on their shared databases. Could this be the problem? (the reason I've not fixed this is because I don't know where to find pg_upgrade...)
Thanks in advance!

A: @amehta, no, 8.4 and 9.0 is not your problem. My naive guess is that your configuration is missing:
adapter: postgresql

The problem is entirely local inside of your Heroku setup. Try manually connecting from Heroku to EC2:
require 'postgres'
conn = PGconn.connect('amazone-host', 5432, '', '', 'dbname', 'username', 'pass')
puts conn.exec('SELECT version()')[0]

to see if you can further isolate the problem.

A: the problem is that heroku overwrites the database.yml....so when you call ActiveRecord::Base.establish_connection(:external_db)  there is no .yml definition for that db


Q: call activity from service It has been asked a few times before but the solution provided couldn't solve my problem. I am working on the app which has several classes: mainactivity, SMS, and MService. service has a timer. I am trying to call SMS to send a text message every time timer is over. Can please someone help me ....
Thanks for consideration...
public class MService extends Service {

    private Handler HandleIt = new Handler();
    private final int INTERVAL = 60 * 1000;
    private Timer timer = new Timer();
    boolean timeout = false;

    public interface SmsService
    {
        void SmsServiceSenter();
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return null;
    }

    class TimeDisplayTimerTask extends TimerTask {

        @Override
        public void run() {
            HandleIt.post(new Runnable(){
               public void run(){
                   Toast.makeText(getApplicationContext(), TextonScreen(), Toast.LENGTH_SHORT).show();
                  // Intent smsintent = new Intent(getBaseContext(), SMS.class);
                  // startService(smsintent);
               }
            });
        }

   }

    private String TextonScreen()
    {
        timeout = true;
        return "it is running";

    }
    boolean isTimeout()
    {
        return timeout;
    }

    @Override
    public void onCreate() {
        // TODO Auto-generated method stub
        super.onCreate();
        Toast.makeText(this, "Service is created", Toast.LENGTH_SHORT).show();

    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // TODO Auto-generated method stub
        // Display the Toast Message
        Toast.makeText(this, "Start it", Toast.LENGTH_SHORT).show();
        // Execute an action after period time
        //comes from the TimeDisplayTimerTask class
        timer.scheduleAtFixedRate(new TimeDisplayTimerTask(), 0, INTERVAL);

        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        // Display the Toast Message
        Toast.makeText(this, "Stop it", Toast.LENGTH_SHORT).show();
        super.onDestroy();
    }

}

public class SMS extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        message();;

    }

    boolean issent = false;
    String text = "I am here";
    String num = "2085578209";
    SmsManager smsManager = SmsManager.getDefault();

    public void message()
    {
       // if(Timeout.isTimeout()) {
            smsManager.sendTextMessage(num, null, text, null, null);
            issent = true;
      //  }
    }
    boolean isSent()
    {
    return issent;
    }
}

A: It is really simple.
After you create your Intent variable, before starting activity add a flag to it like below
Intent launch = new Intent(this, MyActivity.class);
launch.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(launch);

With this above code you can call activity from service


Q: I want to create a persistent mapped network drive with ftp I want to create a persistent mapped network drive with ftp. I have mounted already a ftp path with the file explorer of windows in order to not input the credentials again. What is the solution please?
Here is my code:
New-PSDrive -Persist -Name "X" -PSProvider "FileSystem" -Root "ftp://localhost/"

I have this error:

New-PSDrive: D:\powershell\Untitled-2.ps1:1:1
Line 1
New-PSDrive -Persist -Name "X" -PSProvider "FileSystem" -Root "ftp:// …
When you use the Persist parameter, the root must be a file system location on a remote computer.

A: Let me clarify few of the things.
Mapped network drives are saved in Windows on the local computer. They're persistent, not session-specific,and can be viewed and managed in File Explorer and other tools.
When you scope the command locally, without dot-sourcing, the Persist parameter doesn't persist the creation of a PSDrive beyond the scope in which you run the command. If you run New-PSDrive inside a script, and you want the new drive to persist indefinitely, you must dot-source the script. For best results, to force a new drive to persist, specify Global as the value of the Scope parameter and include Persist in your command.
The name of the drive must be a letter, such as D or E. The value of Root parameter must be a UNC path of a different computer. The PSProvider parameter's value must be FileSystem.
So technically, you dont need to persist, you just need to specify the -Root properly:
New-PSDrive -PSProvider filesystem -Root C:\full\path\ -Name anyname

In your case the full path would be an UNC path \\remoteserver\full\path of FTP


Q: Combining information from multiple lists I have multiple string[] that are defined like this:
var allEntities = new[] { "a", "b", "c", "d", "e", "f", "g", "h", "i" }
var entitiesWithPriority = new[] { "c", "d", "g" }
var entitiesWithIssue = new [] { "d", "h", "i" }
var entitiesWith... = new [] { ... }

Now I'd like to compile a single list from those arrays by using the following class structure:
class Entity {
    public string Name { get; set; }
    public bool HasPriority { get; set; }
    public bool HasIssue { get; set; }
}

The result of the operation should therefore be something like this:
[
    { "name": "a", "hasPriority": false, "hasIssue": false }
    { "name": "b", "hasPriority": false, "hasIssue": false }
    { "name": "c", "hasPriority": true, "hasIssue": false }
    { "name": "d", "hasPriority": true, "hasIssue": true }
    { "name": "e", "hasPriority": false, "hasIssue": false }
    { "name": "f", "hasPriority": false, "hasIssue": false }
    { "name": "g", "hasPriority": true, "hasIssue": false }
    { "name": "h", "hasPriority": false, "hasIssue": true }
    { "name": "i", "hasPriority": false, "hasIssue": true }
]

I could do something in the lines of the following code, but I think this solution is not perfect at all:
var result = allEntities.Select(entityName => new Entity()
{
    Name = entityName,
    HasPriority = entitiesWithPriority.Contains(entityName),
    HasIssue = entitiesWithIssue.Contains(entityName)
});

How can I compile such a list while being performance efficient.

A: You can use a Dictionary or a Hashset to reduce Any and Contains complexity from O(n) to O(1):
The idea above can still be used for large lists to replace list/array/IEnumarable<> Contains which is O(n) with Hashset's Contains which is O(1).
var entitiesWithPriorityMap = entitiesWithPriority.ToDictionary(e => e.entityName, e => true);
var entitiesWithIssueMap = entitiesWithIssue.ToDictionary(e => e.entityName, e => true);

var result = allEntities.Select(entityName => new Entity()
{
    Name = entityName,
    HasPriority = entitiesWithPriorityMap.ContainsKey(entityName),
    HasIssue = entitiesWithIssueMap.ContainsKey(entityName)
});

Note: This works when dealing with Linq2Object nor Linq2Sql (cannot generate SQL out of Contains in this scenario).
Hashset version
var entitiesWithPriorityMap = new HashSet<Entity>(entitiesWithPriority);
var entitiesWithIssueMap = new HashSet<Entity>(entitiesWithIssue);

// replace ContainsKey with Contains

A: You could join them together:
var entities =
     from name in allEntities
     join pr in entitiesWithPriority on name equals pr into np
     from priority in np.DefaultIfEmpty()
     join iss in entitiesWithIssue on name equals iss into npi
     from issue in npi.DefaultIfEmpty()
     select new Entity
     {
         Name = name,
         HasPriority = !string.IsNullOrEmpty(priority),
         HasIssue = !string.IsNullOrEmpty(issue)
     };

A: First create a dictionary <string>,<entity> and populate it from all entities with all hasXXX defaults to false
After that, lookup is O(1)
foreach (var key in EntitiesWithPriority)
{
   dict[key].hasPriority = true
}

and so on

A: If the construction can be List<> instead from an array, we can create a List<> with the following generic type: List<Dictionary<string, dynamic>>
To achieve such construction you need to create following method:
public List<List<Dictionary<string, dynamic>>> MethodName()
    {
        var list = new List<List<Dictionary<string, dynamic>>>();

        HasPriority = false;
        HasIssue = false;

        foreach (var item in allEntities)
        {
            if (entitiesWithPriority.Contains(item.ToString()))
                HasPriority = true;
            if (entitiesWithIssue.Contains(item.ToString()))
                HasIssue = true;
            list.Add(new List<Dictionary<string, dynamic>>()
            {
                (new Dictionary<string, dynamic>() { { "name", item } }),
                (new Dictionary<string, dynamic>() { { "hasPriority", HasPriority } }),
                (new Dictionary<string, dynamic>() { { "hasIssue", HasIssue } })
            });
        }

        return list;
    }

I'm not sure if all properties in your class are necessary. In case you'd want to add more arrays with conditions you should modify foreach loop.


Q: how to prevent idea auto resolve maven dependency I am new to idea and maven ,I  find that every time, when I am edit the dependency in the pom.xml ,before I finished writing, idea tryed to resolve the dependency and create some folder in my native repo , for example , when I am edit the dependency, and it looks like this now
     <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-a</artifactId>
    </dependency>

idea has create a folder in my native repo like this,how to prevent it and I have set my setting like this,but it seems no use, and the file is auto saved as usual

A: I'm guessing you have enabled the "Import Maven projects automatically" option. To disable it, go to Preferences... > Build, Execution, Deployment > Build Tools > Maven > Importing, then uncheck the option from there, like so:

After doing so, it will be up to you to run the imports when you're ready. To import manually, right-click your project in the Project view, then click Maven > Reimport:


Q: check for valid date which is declared in varchar2 My table looks like below which is declared in VARCHAR2:
YMD
20101010
20101112
20100231
20150101
20160101

I have to check for valid dates and filter future dates from sysdate, which are in valid format.
I write the function as below to check for valid dates:
create or replace FUNCTION VALIDATE_DATE (p_string in string) return date is
begin
    return to_date(p_string, 'YYYYMMDD');
exception when others then
    begin
        return to_date(p_string, 'YYYY-MM-DD');
    exception when others then
        begin
            return to_date(p_string, 'RR-MON-DD');
        exception when others then
            return null;
        end;
    end;
end;

and written this query to check for valid dates and replace with null for invalid dates
select ymd, VALIDATE_DATE(ymd) as Valid
from temp

and to check future dates I wrote the following query, but it throws error

ORA-01839

select ymd
from temp
where validate_date(ymd)='YES'
and to_date(ymd,'yyyymmdd')>sysdate

How to check future dates in my table if exists?

A: I will rather fix the design issue as a permanent fix rather than wasting time on the workaround.
Firstly, NEVER store DATE as VARCHAR2. All this overhead is due to the fact that your design is flawed.

'20100231'

How on earth could that be a valid date? Which calendar has a 31 days in FEBRUARY?
Follow these steps:

*

*Add a new column with DATE DATA TYPE.

*Update the new column with date values from the old column using TO_DATE.

*Do the required DATE arithmetic on the new DATE column, or handle this in the UPDATE statement in step 2 itself.

*Drop the old column.

*Rename the new column to the old column.

UPDATE Adding a demo
Setup
SQL> CREATE TABLE t
  2      (ymd varchar2(8));

Table created.

SQL>
SQL> INSERT ALL
  2      INTO t (ymd)
  3           VALUES ('20101112')
  4      --INTO t (ymd)
  5      --     VALUES ('20100231')
  6      INTO t (ymd)
  7           VALUES ('20150101')
  8      INTO t (ymd)
  9           VALUES ('20160101')
 10  SELECT * FROM dual;

3 rows created.

SQL>
SQL> COMMIT;

Commit complete.

SQL>

Add new column:
SQL> ALTER TABLE t ADD (dt DATE);

Table altered.

SQL>

DO the required update
SQL> UPDATE t
  2  SET dt =
  3    CASE
  4      WHEN to_date(ymd, 'YYYYMMDD') > SYSDATE
  5      THEN NULL
  6      ELSE to_date(ymd, 'YYYYMMDD')
  7    END;

3 rows updated.

SQL>
SQL> COMMIT;

Commit complete.

SQL>

Let's check:
SQL> SELECT * FROM t;

YMD      DT
-------- ---------
20101112 12-NOV-10
20150101 01-JAN-15
20160101

SQL>

Drop the old column:
SQL> ALTER TABLE t DROP COLUMN ymd;

Table altered.

SQL>

Rename the new column to old column name
SQL> ALTER TABLE t RENAME COLUMN dt TO ymd;

Table altered.

SQL>

You have just fixed the issue
SQL> SELECT * FROM t;

YMD
---------
12-NOV-10
01-JAN-15

SQL>


Q: Count particular values in a Spark DF column combined with window functions Sample DF:
var some_df = Seq(
("A", "no"),
("B", "yes"),
("B", "yes"),
("B", "no")
).toDF(
"user_id", "phone_number")

some_df.show()
+-------+------------+
|user_id|phone_number|
+-------+------------+
|      A|          no|
|      B|         yes|
|      B|         yes|
|      B|          no|
+-------+------------+

I am trying to count the number of "yes" for each user_id.
Code:
val omg_window = Window.partitionBy($"user_id")
some_df = some_df.withColumn("my_col",
count($"phone_number"==="yes").over(omg_window)).drop("phone_number")
some_df.show()

My OP:
 +-------+------+
 |user_id|my_col|
 +-------+------+
 |      B|     3|
 |      B|     3|
 |      B|     3|
 |      A|     1|
 +-------+------+

Expected OP:
User Id .   my_col
 B .         2
 A .         0

Any suggestions on where I am going wrong will be highly helpful

A: Since you are reducing the data frame, use groupBy.agg instead of window function; Here you compare the phone_number column with yes string ($"phone_number" === "yes") and convert the result to integer which turns true into 1 and false into 0 and then we count 1s by suming up the column:
some_df.groupBy("user_id").agg(
    sum(($"phone_number" === "yes").cast("integer")).as("my_col")
).show
+-------+------+
|user_id|my_col|
+-------+------+
|      B|     2|
|      A|     0|
+-------+------+


Q: angularjs ui-router : How to change state or page from inside controller I am using Angularjs and Ui-router. I am able to call the pages with ui-sref from HTML. I want to call for a new page from controller when using ui-router. How to do you do it.  I have given the code below.
var app = angular.module('starter', ['ionic'])

app.config(function($stateProvider, $urlRouterProvider) {
  $urlRouterProvider.otherwise('/')

  $stateProvider.state('home', {
  url: '/home',
  views: {
    home: {
      templateUrl: 'home.html'
    }
  }
})

  $stateProvider.state('results', {
  url: '/results',
  views: {
    results: {
      templateUrl: 'results.html'
    }
  }
})

$stateProvider.state('help', {
  url: '/help',
  views: {
    help: {
      templateUrl: 'help.html'
    }
  }
})
})
.run(function($ionicPlatform) {
  $ionicPlatform.ready(function() {
    if(window.cordova && window.cordova.plugins.Keyboard) {
      // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
      // for form inputs)
      cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);

      // Don't remove this line unless you know what you are doing. It stops the viewport
      // from snapping when text inputs are focused. Ionic handles this internally for
      // a much nicer keyboard experience.
      cordova.plugins.Keyboard.disableScroll(true);
    }
    if(window.StatusBar) {
      StatusBar.styleDefault();
    }
  });
})
.controller ("mainCtrl", function($scope) {
    $scope.devList1 = [
    {text:'Most Accurate', checked: false},
    {text:'Accurate', checked: false},
    {text:'Neutral', checked: false},
    {text:'Inaccurate', checked: false},
    {text:'Most Inaccurate', checked: false}];
    $scope.indexToShow = 0;
    $scope.questionlist = ["one", "two" , "three", "four", "five"];

     $scope.imChanged = function(isChecked, index){
             angular.forEach($scope.devList1, function (items) {
                items.checked= false;
            });
            $scope.devList1[index].checked=true;
            $scope.okaychecked = true;
        }
    $scope.nextquestion =  function(){
        $scope.okaychecked = false;
        angular.forEach($scope.devList1, function (items) {
                items.checked= false;
            });
        if (($scope.indexToShow) < ($scope.questionlist.length - 1)){
            $scope.indexToShow = ($scope.indexToShow + 1) % $scope.questionlist.length;
            }
        else {
            $state.go('home',"");

        }
        }
    })

and html below

<ion-nav-bar class="bar-positive">
</ion-nav-bar>

  <ion-tabs class="tabs-positive" tabs-icon-top>
    <ion-tab icon="ion-home" ui-sref="home">
      <ion-nav-view name="home"></ion-nav-view>
    </ion-tab>
    <ion-tab icon="ion-help" ui-sref="help">
      <ion-nav-view name="help"></ion-nav-view>
    </ion-tab>
  </ion-tabs>

I hv to call the state change or call new page at
 $state.go('results',""); position. How do you do it.
$state.go don't seem to work. I want to go to results page

A: You have to inject $state in your controller
.controller ("mainCtrl", function($scope, $state) {

Then, you can use it
$state.go('results');

A: You have to use $state.go('results'); in stead of $state.go('results', "");. The second field is for setting the options of the $state.go method. I guess it's not working because you leave this as an empty string. If you don't put anything there, it will use the default values.


Q: How to map two Oberservable arrays based on a value? I have two observable arrays.
habits$: Observable<Habit[]>;
status$: Observable<Status[]>;

The habit has the following structure:
export interface Habit {
  habitId: number;
  name: string;
  repeatVal: number;
  notification: string;
  color: string;
  question: string;
  id: number;
}

The status array has the habitId, date and status as keys.
I want to merge both habits$ and status$ into one Observable array based on the habitId attribute present in both of them.
I have done some research and a combination of mergeMap() and forkJoin() seems to be the way to go, like shown here
Combine multiple observable arrays into new object array
But I can't figure out a syntax that will work for me.
This is how my code looks at the moment:
ngOnInit() {
this.habits$ = this.habitService.fetchAllById(this.authService.userId);
console.log(this.habits$);
this.status$ = this.statusService.fetchAll();
this.habits$.pipe(
  mergeMap(habits => {
  this.status$ = this.statusService.fetchAll().filter(status => status.habitId == habits.habitId);
}));
console.log(this.joined$);}

A: I would use forkJoin in the following fashion:
ngOnInit() {
  forkJoin([
    this.habitService.fetchAllById(this.authService.userId),
    this.status$ = this.statusService.fetchAll()
  ]).subscribe(([habits, statuses]) => {
    this.joined = habits.map(habit => ({
      ...statuses.find(t => t.habitId === habit.habitId),
      ...habit
    }));
  });
}

see simple demo


Q: How can I change the position of an  element? I just started in web dev and my first project is a resume website. I am trying to separate the education and experience sections with an hr element. It was working, then I used the float property in CSS to align education descriptions to the left and corresponding dates to the right. Now, the line that came after the education section is in the wrong area. Here is some code:

EDUCATION

M.A. in Teaching, University of North Carolina

June 2021 - May 2022

B.A., Human Development & Family Studies major & Education minor, University of North Carolina

EXPERIENCE

The id e1 just floats left, and the id e2 floats right. How can I get the hr element to actually appear between the two sections, instead of in the middle of the education section?

A:

.edu{
            display: flex;
            flex-direction: row;
            align-self: flex-start;
        }

EDUCATION

M.A. in Teaching, University of North Carolina

June 2021 - May 2022

B.A., Human Development & Family Studies major & Education minor, University of North Carolina

EXPERIENCE

A: *

*id should be unique so change #e1 from third p element to your choice but diff.

*Used clear:left so that float property on left of hr is cleared

*You can also use cleafix hack to
 , by adding clearfix class to
 and add this CSS

.clearfix::after {
  content: "";
  clear: both;
  display: table;
}

*

*You can also add vertical rules using border-right as I specified in code

* {
  box-sizing: border-box/*So that padding used below don't effect width*/
}

hr {
  clear: left
}

#e1 {
  float: left;
  width: 33%; /*Width so that content is divided in 3colums*/

  height: 100px;
  /*Height specified so that border become equal for all others and act as a vertical rule*/

  border-right: 2px solid red;
  padding: 5px;
}

#e2 {
  float: right;
  width: 33%;
  height: 100px;
  padding: 5px;
}

#e3 {
  float: left;
  width: 33%;
  height: 100px;
  border-right: 2px solid red;
  padding: 5px;
}

EDUCATION

M.A. in Teaching, University of North Carolina

June 2021 - May 2022

B.A., Human Development & Family Studies major & Education minor, University of North Carolina

EXPERIENCE