text:
Q: java.lang.VerifyError on XPAthConstants.NODESET in WebSphere but not in Jetty My code works fine in Jetty, but as soon as I deploy in WebSphere, I get a java.lang.VerifyError exception with no extra information at all (not even a message).
The code:
Class c = Class.forName("javax.xml.xpath.XPathConstants"); // This works
System.out.println(c.getDeclaredFields()); // This works
System.out.println(c.getDeclaredField("NODESET")); // This works (public static final javax.xml.namespace.QName javax.xml.xpath.XPathConstants.NODESET)
System.out.println(XPathConstants.NODESET); // This fails with an empty java.lang.VeryfyError

XPathConstants is part of the xml.jar shipped with the JRE. Both Jetty and WebSphere are running with a IBM SDK 7, and code is compiled with the same version.
I have no idea where it could come from. Thank you for the help.
Here is the StackTrace, although it says nothing since the VerifyError is empty
[9/17/15 4:56:01:730 CDT] 000001c0 SystemOut     O java.lang.VerifyError
[9/17/15 4:56:01:731 CDT] 000001c0 SystemOut     O      at com.ibm.idwb.common.filenet.linker.LinkerDocumentLevel.findRelationships(LinkerDocumentLevel.java:1352)
[9/17/15 4:56:01:731 CDT] 000001c0 SystemOut     O      at com.ibm.idwb.common.filenet.linker.LinkerDocumentLevel.buildKeyDefCache(LinkerDocumentLevel.java:1119)
[9/17/15 4:56:01:731 CDT] 000001c0 SystemOut     O      at com.ibm.idwb.common.filenet.linker.LinkerDocumentLevel.checkForKeys(LinkerDocumentLevel.java:748)
[9/17/15 4:56:01:731 CDT] 000001c0 SystemOut     O      at com.ibm.idwb.common.filenet.parallel.cmd.LinkRefreshCommand.refreshLinks(LinkRefreshCommand.java:224)
[9/17/15 4:56:01:732 CDT] 000001c0 SystemOut     O      at com.ibm.idwb.common.filenet.parallel.cmd.LinkRefreshCommand.access$1(LinkRefreshCommand.java:197)
[9/17/15 4:56:01:732 CDT] 000001c0 SystemOut     O      at com.ibm.idwb.common.filenet.parallel.cmd.LinkRefreshCommand$1.call(LinkRefreshCommand.java:161)
[9/17/15 4:56:01:732 CDT] 000001c0 SystemOut     O      at com.ibm.idwb.common.filenet.parallel.cmd.LinkRefreshCommand$1.call(LinkRefreshCommand.java:1)
[9/17/15 4:56:01:732 CDT] 000001c0 SystemOut     O      at com.ibm.idwb.common.parallel.executor.CountableTask.call(Unknown Source)
[9/17/15 4:56:01:733 CDT] 000001c0 SystemOut     O      at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:345)
[9/17/15 4:56:01:733 CDT] 000001c0 SystemOut     O      at java.util.concurrent.FutureTask.run(FutureTask.java:177)
[9/17/15 4:56:01:733 CDT] 000001c0 SystemOut     O      at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1121)
[9/17/15 4:56:01:733 CDT] 000001c0 SystemOut     O      at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:614)
[9/17/15 4:56:01:734 CDT] 000001c0 SystemOut     O      at java.lang.Thread.run(Thread.java:777)

A: The missing VerifyError message is a JVM defect, and you should report it to the Java team.
This is very likely a class linkage error.  You very likely have a JAR in your classpath that contains javax.xml.namespace.QName, and it is being preferred to the copy from Liberty (for example, you could be using <classloader delegation="parentLast"/>).  This is the situation:

*

*Application classes:

*

*com.ibm.idwb.common.filenet.linker.LinkerDocumentLevel

*javax.xml.namespace.QName

*Liberty/JDK

*

*javax.xml.xpath.XPathConstants

*javax.xml.namespace.QName

There are two QName classes, but class loaders may only link to one of them; if you try to link to both, you will get an error.  When you use reflection to access the NODESET field, you're only asking the Liberty/JDK class loader to resolve the QName field on behalf of XPathConstants.  When you use a direct field reference, you're additionally asking your application class loader to resolve the XPathConstants class (which it finds from Liberty/JDK) and also the QName class (which it finds in a different place than the Liberty/JDK class loader found it when linking QName to XPathConstants).
You need to either:

*

*Remove parentLast (or whatever is causing the duplicate QName class load)

*Remove the JAR containing the duplicate javax.xml.namespace.QName class from your application class path

*Add a JAR containing a duplicate javax.xml.xpath.XPathConstants class to the application class path so that you fully (rather than partially) duplicate the class hierarchy

(If this analysis is correct, then it's unfortunate that the JVM is throwing VerifyError rather than the more specific LinkageError.)


text:
Q: Getting Invalid Signature error with woocommerce rest api using oauth 1.0a I am getting an invalid signature error in woocommerce rest api. I am also using the oauth 1.0a script from ddo https://github.com/ddo/oauth-1.0a. I generated the api keys twice. Also removed the version parameter inside de oauth script like requested on the woocommerce rest api documentation http://woothemes.github.io/woocommerce-rest-api-docs/
url
test.dev/wc-api/v3/orders/line_items?oauth_consumer_key=ck_858f9cf8cda8085d5677b2b1d4c12d10897e9702&oauth_nonce=MyriSapnWSopIusSjjuqJ8PLi6RWr0L9&oauth_signature=VfgINTX1FWYu551%2FxlLfipFnDQ8%3D&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1443481966

error
{"errors":[{"code":"woocommerce_api_authentication_error","message":"Invalid Signature - provided signature does not match"}]}

js
var oauth = OAuth({
    consumer: {
        public: 'ck_858f9cf8cda8085d5677b2b1d4c12d10897e9702',
        secret: 'cs_7f429ec99905bb444e290bd4852a0c0da2545b21 '
    },
    signature_method: 'HMAC-SHA1'
});

var request_data = {
    url: 'http://test.dev/wc-api/v3/orders/line_items',
    method: 'GET',
}

$http({
    url: request_data.url,
    method: request_data.get,
    params: oauth.authorize(request_data)
}).then(function successCallback(response) {
    console.log(response);
}, function errorCallback(response) {
    console.log(response);
});;

A: I just noticed that your $http method is getting the value of request_data.get instead of request_data.method. I'm sure that's what you were overlooking lol

A: Fixed it by using a service from Abdul Ahmad: httpService.js
angular.module('httpService', []).factory('httpService', httpService);
httpService.$inject = ['$http', '$q'];

function httpService($http, $q) {

    var methods = {
        httpGet : 'GET',
        httpPost : 'POST',
        httpPut : 'PUT',
        httpDelete : 'DELETE'
    };

    function baseGet(url) {
        return $http.get(url).then(
                function (result) {
                    return result.data;
                },
                function (result) {
                    return $q.reject(result);
                }
            );
    }
    function httpWithParams(url, method, params, data) {
        return $http({
                url: url,
                method: method,
                params: params,
                data: data,
                dataType: "json",
                headers: {
                    "Content-Type": "application/json"
                }
            }).then(
                function (result) {
                    return result.data;
                },
                function (result) {
                    return $q.reject(result);
                }
            );
    }
    function handleError(error) {
            console.log(error);
    }

    return {
        baseGet: baseGet,
        httpWithParams: httpWithParams,
        handleError: handleError,
        methods: methods
    }
}

And then used this:
var oauth = OAuth({
    consumer: {
        public: 'ck_000',
        secret: 'cs_000'
    },
    signature_method: 'HMAC-SHA1'
});

function getMyData() {

    var request_data = {
        url: 'http://test.dev/wc-api/v3/products',
        method: 'get',
    }

    return  returnData = httpService.httpWithParams(request_data.url, request_data.method, oauth.authorize(request_data))
    .then(function(data) {
        return data;
    }, function(data) {
        httpService.handleError(data);
        return data;
    });
}

Made some modification in the oauth file:
if (typeof(module) !== 'undefined' && typeof(exports) !== 'undefined') {
    module.exports = OAuth;
    var CryptoJS = require("crypto-js");
}

/**
 * Constructor
 * @param {Object} opts consumer key and secret
 */
function OAuth(opts) {
    if(!(this instanceof OAuth)) {
        return new OAuth(opts);
    }

    if(!opts) {
        opts = {};
    }

    if(!opts.consumer) {
        throw new Error('consumer option is required');
    }

    this.consumer            = opts.consumer;
    this.signature_method    = opts.signature_method || 'HMAC-SHA1';
    this.nonce_length        = opts.nonce_length || 32;
    //this.version             = opts.version || '1.0';
    this.parameter_seperator = opts.parameter_seperator || ', ';

    if(typeof opts.last_ampersand === 'undefined') {
        this.last_ampersand = true;
    } else {
        this.last_ampersand = opts.last_ampersand;
    }

    switch (this.signature_method) {
        case 'HMAC-SHA1':
            this.hash = function(base_string, key) {
                return CryptoJS.HmacSHA1(base_string, key).toString(CryptoJS.enc.Base64);
            };
            break;

        case 'HMAC-SHA256':
            this.hash = function(base_string, key) {
                return CryptoJS.HmacSHA256(base_string, key).toString(CryptoJS.enc.Base64);
            };
            break;

        case 'PLAINTEXT':
            this.hash = function(base_string, key) {
                return key;
            };
            break;

        case 'RSA-SHA1':
            throw new Error('oauth-1.0a does not support this signature method right now. Coming Soon...');
        default:
            throw new Error('The OAuth 1.0a protocol defines three signature methods: HMAC-SHA1, RSA-SHA1, and PLAINTEXT only');
    }
}

/**
 * OAuth request authorize
 * @param  {Object} request data
 * {
 *     method,
 *     url,
 *     data
 * }
 * @param  {Object} public and secret token
 * @return {Object} OAuth Authorized data
 */
OAuth.prototype.authorize = function(request, token) {
    var oauth_data = {
        oauth_consumer_key: this.consumer.public,
        oauth_timestamp: this.getTimeStamp(),
        oauth_nonce: this.getNonce(),
        oauth_signature_method: this.signature_method
        //oauth_version: this.version
    };

    if(!token) {
        token = {};
    }

    if(token.public) {
        oauth_data.oauth_token = token.public;
    }

    if(!request.data) {
        request.data = {};
    }

    oauth_data.oauth_signature = this.getSignature(request, token.secret, oauth_data);

    return oauth_data;
};

/**
 * Create a OAuth Signature
 * @param  {Object} request data
 * @param  {Object} token_secret public and secret token
 * @param  {Object} oauth_data   OAuth data
 * @return {String} Signature
 */
OAuth.prototype.getSignature = function(request, token_secret, oauth_data) {
    return this.hash(this.getBaseString(request, oauth_data), this.getSigningKey(token_secret));
};

/**
 * Base String = Method + Base Url + ParameterString
 * @param  {Object} request data
 * @param  {Object} OAuth data
 * @return {String} Base String
 */
OAuth.prototype.getBaseString = function(request, oauth_data) {
    return request.method.toUpperCase() + '&' + this.percentEncode(this.getBaseUrl(request.url)) + '&' + this.percentEncode(this.getParameterString(request, oauth_data));
};

/**
 * Get data from url
 * -> merge with oauth data
 * -> percent encode key & value
 * -> sort
 *
 * @param  {Object} request data
 * @param  {Object} OAuth data
 * @return {Object} Parameter string data
 */
OAuth.prototype.getParameterString = function(request, oauth_data) {
    var base_string_data = this.sortObject(this.percentEncodeData(this.mergeObject(oauth_data, this.mergeObject(request.data, this.deParamUrl(request.url)))));

    var data_str = '';

    //base_string_data to string
    for(var key in base_string_data) {
        data_str += key + '=' + base_string_data[key] + '&';
    }

    //remove the last character
    data_str = data_str.substr(0, data_str.length - 1);
    return data_str;
};

/**
 * Create a Signing Key
 * @param  {String} token_secret Secret Token
 * @return {String} Signing Key
 */
OAuth.prototype.getSigningKey = function(token_secret) {
    token_secret = token_secret || '';

    if(!this.last_ampersand && !token_secret) {
        return this.percentEncode(this.consumer.secret);
    }

    return this.percentEncode(this.consumer.secret) + '&' + this.percentEncode(token_secret);
};

/**
 * Get base url
 * @param  {String} url
 * @return {String}
 */
OAuth.prototype.getBaseUrl = function(url) {
    return url.split('?')[0];
};

/**
 * Get data from String
 * @param  {String} string
 * @return {Object}
 */
OAuth.prototype.deParam = function(string) {
    var arr = string.split('&');
    var data = {};

    for(var i = 0; i < arr.length; i++) {
        var item = arr[i].split('=');
        data[item[0]] = decodeURIComponent(item[1]);
    }
    return data;
};

/**
 * Get data from url
 * @param  {String} url
 * @return {Object}
 */
OAuth.prototype.deParamUrl = function(url) {
    var tmp = url.split('?');

    if (tmp.length === 1)
        return {};

    return this.deParam(tmp[1]);
};

/**
 * Percent Encode
 * @param  {String} str
 * @return {String} percent encoded string
 */
OAuth.prototype.percentEncode = function(str) {
    return encodeURIComponent(str)
        .replace(/\!/g, "%21")
        .replace(/\*/g, "%2A")
        .replace(/\'/g, "%27")
        .replace(/\(/g, "%28")
        .replace(/\)/g, "%29");
};

/**
 * Percent Encode Object
 * @param  {Object} data
 * @return {Object} percent encoded data
 */
OAuth.prototype.percentEncodeData = function(data) {
    var result = {};

    for(var key in data) {
        result[this.percentEncode(key)] = this.percentEncode(data[key]);
    }

    return result;
};

/**
 * Get OAuth data as Header
 * @param  {Object} oauth_data
 * @return {String} Header data key - value
 */
OAuth.prototype.toHeader = function(oauth_data) {
    oauth_data = this.sortObject(oauth_data);

    var header_value = 'OAuth ';

    for(var key in oauth_data) {
        if (key.indexOf('oauth_') === -1)
            continue;
        header_value += this.percentEncode(key) + '="' + this.percentEncode(oauth_data[key]) + '"' + this.parameter_seperator;
    }

    return {
        Authorization: header_value.substr(0, header_value.length - this.parameter_seperator.length) //cut the last chars
    };
};

/**
 * Create a random word characters string with input length
 * @return {String} a random word characters string
 */
OAuth.prototype.getNonce = function() {
    var word_characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    var result = '';

    for(var i = 0; i < this.nonce_length; i++) {
        result += word_characters[parseInt(Math.random() * word_characters.length, 10)];
    }

    return result;
};

/**
 * Get Current Unix TimeStamp
 * @return {Int} current unix timestamp
 */
OAuth.prototype.getTimeStamp = function() {
    return parseInt(new Date().getTime()/1000, 10);
};

////////////////////// HELPER FUNCTIONS //////////////////////

/**
 * Merge object
 * @param  {Object} obj1
 * @param  {Object} obj2
 * @return {Object}
 */
OAuth.prototype.mergeObject = function(obj1, obj2) {
    var merged_obj = obj1;
    for(var key in obj2) {
        merged_obj[key] = obj2[key];
    }
    return merged_obj;
};

/**
 * Sort object by key
 * @param  {Object} data
 * @return {Object} sorted object
 */
OAuth.prototype.sortObject = function(data) {
    var keys = Object.keys(data);
    var result = {};

    keys.sort();

    for(var i = 0; i < keys.length; i++) {
        var key = keys[i];
        result[key] = data[key];
    }

    return result;
};

redpajama_set_name: RedPajamaStackExchange


text:
Q: Adding prices to my select options javascript/html

 Total
 <input value="£0.00" readonly="readonly" type="text" id="total"/>

Below are the html and js for my website i am building. I am trying to get the values to increase in the total for the tem selected, this will be 1 item from the radio buttons. however everytime i choose an option the total stays at £0. i am new to js and i am having trouble. any help would be appreciated!

function totalIt() {
  var input = document.getElementsByName("size");
  var total = 0;
  for (var i = 0; i < input.length; i++) {
    if (input[i].checked) {
      total += parseFloat(input[i].value);
    }
  }
  document.getElementById("total").value = "£" + total.toFixed(2);
}
Small (£3.99)<input type="radio" name="size" id="s1" value="3.99" onclick="totalIt()"/>
Medium (£4.99)<input type="radio" name="size" id="s2" value="4.99" onclick="totalIt()"/>
Large (£5.99)<input type="radio" name="size" id="s3" value="5.99" onclick="totalIt()"/>

A: Change this document.getElementById("total").value = "£" + total.toFixed(2);
to read
document.getElementById("total").innerHTML = "£" + total.toFixed(2);
You need to use innerHTML to print out to the screen. .value is getting the value of that element.

A: Part of the issue is the missing #total element (presumably an input, given that you are trying to change its value).
But judging from the name of the function & element, I'm assuming you also want total to increment whenever you click one of the radio inputs. For that, you need to move your total variable to outside the function, which will create a closure (i.e. your total variable will retain its value in between calls to totalIt()). Note that I added a break since there's no need to keep checking the other radio boxes once you found your checked one.

// Note this is outside the function
var total = 0;

function totalIt() {
  var input = document.getElementsByName("size");
  for (var i = 0; i < input.length; i++) {
    if (input[i].checked) {
      total += parseFloat(input[i].value);
      // exit loop once checked radio is found
      break;
    }
  }
  document.getElementById("total").value = "£" + total.toFixed(2);
}
Small (£3.99)<input type="radio" name="size" id="s1" value="3.99" onclick="totalIt()"/>
Medium (£4.99)<input type="radio" name="size" id="s2" value="4.99" onclick="totalIt()"/>
Large (£5.99)<input type="radio" name="size" id="s3" value="5.99" onclick="totalIt()"/>

  Total <input type="text" readonly id="total" value="£0.00"/>

Alternatively, you can read & parse the value from your input#total element, in case there are reasons as to why you can't use a closure here.

function totalIt() {
  var input = document.getElementsByName("size");
  var total = parseFloat(document.getElementById("total").value.slice(1));
  for (var i = 0; i < input.length; i++) {
    if (input[i].checked) {
      total += parseFloat(input[i].value);
      // exit loop once checked radio is found
      break;
    }
  }
  document.getElementById("total").value = "£" + total.toFixed(2);
}
Small (£3.99)<input type="radio" name="size" id="s1" value="3.99" onclick="totalIt()"/>
Medium (£4.99)<input type="radio" name="size" id="s2" value="4.99" onclick="totalIt()"/>
Large (£5.99)<input type="radio" name="size" id="s3" value="5.99" onclick="totalIt()"/>

  Total <input type="text" readonly id="total" value="£0.00"/>

In both of the cases above, you don't actually need radio inputs or a loop, since the radios are basically acting like buttons; you can just replace them with regular buttons and call totalIt() (which can be greatly simplified) with an argument for the amount by which to increment.
If you are actually not interested in a running total and just want to display the total of the checked items at any given time, then you're really looking for a checkbox input, and then you don't need to worry about closures, parsing, or breaks.

function totalIt() {
  var input = document.getElementsByName("size");
  var total = 0;
  for (var i = 0; i < input.length; i++) {
    if (input[i].checked) {
      total += parseFloat(input[i].value);
    }
  }
  document.getElementById("total").value = "£" + total.toFixed(2);
}
Small (£3.99)<input type="checkbox" name="size" id="s1" value="3.99" onclick="totalIt()"/>
Medium (£4.99)<input type="checkbox" name="size" id="s2" value="4.99" onclick="totalIt()"/>
Large (£5.99)<input type="checkbox" name="size" id="s3" value="5.99" onclick="totalIt()"/>

  Total <input type="text" readonly id="total" value="£0.00"/>


text:
Q: deleting sqlite row using listview I have a listview which connect to an sqlite database. at first it shows my sqlite fields. but my problem is,I can't delete row by setOnLongClickDelete().
error:
The content of the adapter has changed but ListView did not receive a notification. Make sure the content of your adapter is not modified from a background thread, but only from the UI thread. [in ListView(16908298, class android.widget.ListView) with Adapter(class android.widget.ArrayAdapter)]
        at android.widget.ListView.layoutChildren(ListView.java:1510)

codes:
public class CartList extends ListActivity  {
    private ArrayList<String> results = new ArrayList<String>();
    public void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        setContentView(com.example.easyshopping.R.layout.cart);
        openAndQueryDatabase();
         displayResultList();
        setOnLongClickDelete();
    }
    private void displayResultList() {
       // setListAdapter(new ArrayAdapter<String>(this,R.layout.cartformat,results));
        ArrayAdapter<String> listAdapter = new ArrayAdapter<String>(this, R.layout.cartformat,results);
        setListAdapter(listAdapter);
        listAdapter.notifyDataSetChanged();
        getListView().setTextFilterEnabled(true);
    }
        private void openAndQueryDatabase() {
        try {
            SQLiteDatabase database = openOrCreateDatabase("ORCL", MODE_PRIVATE, null);
            Cursor c = database.rawQuery("SELECT title,qty,price FROM CART;", null);
                         if (c != null ) {
                int totalPrice=0;
                if  (c.moveToFirst()) {
                    do {
                        String title = c.getString(c.getColumnIndex("title"));
                        int qty = c.getInt(c.getColumnIndex("qty"));
                        int price = c.getInt(c.getColumnIndex("price"));
                        int pricePerTitle=price*qty;
                        results.add("Title: " +title+ ",Quantity: "+qty+", Price: $"+pricePerTitle);
                        totalPrice=totalPrice+pricePerTitle;
                    }while (c.moveToNext());
                }
               TextView tTotalPrice=(TextView)findViewById(com.example.easyshopping.R.id.txttotalprice);
                String total= Integer.toString(totalPrice);
               tTotalPrice.setText(total);
            }
        } catch (SQLiteException se ) {
            Log.e(getClass().getSimpleName(), "Could not create or Open the database");
        }

    }

    private void setOnLongClickDelete(){
        getListView().setOnItemLongClickListener(new AdapterView.OnItemLongClickListener(){
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id){
                try{ String currentString = results.get(position);
                    String resultRegexString = "Title\\:([^,]+),Quantity\\: ([^,]+), Price\\: \\$([\\W\\w]+)";
                    Pattern resultRegexPattern = Pattern.compile(resultRegexString);
                    Matcher resultRegexMatcher = resultRegexPattern.matcher(currentString);

                    if(resultRegexMatcher.find()){
                        String whereClause = "title=".concat(DatabaseUtils.sqlEscapeString(resultRegexMatcher.group(1))
                                .concat(" AND qty=").concat(resultRegexMatcher.group(2))
                                .concat(" AND price=").concat(resultRegexMatcher.group(3)));

                       SQLiteDatabase database = openOrCreateDatabase("ORCL", MODE_PRIVATE, null);
                        database.delete("CART", whereClause, null);
                        database.close();
                        Toast.makeText(getApplicationContext(), "Row Delete", Toast.LENGTH_SHORT).show();
                        results.remove(position);
                    }
                    return true;
                }  catch (Exception ex){
                    Toast.makeText(getApplicationContext(), ex.getMessage(), Toast.LENGTH_SHORT).show();
                    return false;
                }
            }

        } );
        displayResultList();
    }
}

following Toast works:
Toast.makeText(getApplicationContext(), "Row Delete", Toast.LENGTH_SHORT).show();

A: If you are able to successfully remove the data from the SQLite database then you simply make your listAdapter global and then adding the code
listAdapter.notifyDataSetChanged();

after
results.remove(position);

in your onItemLongClick. After this you can remove calling displayResultList(); in setOnLongClickDelete().


text:
Q: Lost updates in Cassandra I am facing problems of lost writes while updating a row in Cassandra. Here's my schema:
create table balances(
id bigint,
balance decimal,
last_transaction_id bigint,
update_timestamp timestamp,
type varchar,
is_balance_valid boolean,
primary key (wallet_id)
)

Total nodes in cluster: 3 in Local DC
Replication factor: 2
Cassandra Version: 2.1.8
I update the value of column "balance" every time user does a transaction by reading the previously set value, adding the transaction amount and issuing the update. I am using Java, Datastax driver (2.1.5).
Once out of about half a million transactions, one particular update would fail. This happens usually when the user has done two transactions in quick succession, down to few milliseconds. Here are logs:

Transaction #1
10 Feb 2016 18:15:16,984 -[pool-11-thread-1]-  INFO -
  ScratchpadMasterStreamProcessor.processMessage(62) - Printing str id:
  1466140282Scratchpad id: 9127013322
10 Feb 2016 18:15:16,986 -[pool-11-thread-1]- DEBUG -
  SclwBalanceUpdater.updateBalance(43) - Current balance: 0.0
10 Feb 2016 18:15:16,986 -[pool-11-thread-1]- DEBUG -
  SclwBalanceUpdater.updateBalance(44) - Deviation : 200.0
10 Feb 2016 18:15:16,986 -[pool-11-thread-1]- DEBUG -
  UserBalanceManager.updateWalletBalance(70) - Updating user..510978682
10 Feb 2016 18:15:16,987 -[pool-11-thread-1]- DEBUG -
  SclwBalanceUpdater.updateBalance(51) - Final Balance: 200.0
10 Feb 2016 18:15:16,987 -[pool-11-thread-1]- DEBUG -
  ScratchpadMasterStreamProcessor.processMessage(79) - Balance Update
  was successful for wallet 510978682
Transaction #2
10 Feb 2016 18:18:19,157 -[pool-11-thread-1]-  INFO -
  ConsumerThread.run(82) - Event Recieved
10 Feb 2016 18:18:19,159 -[pool-11-thread-1]- DEBUG -
  SclwBalanceUpdater.updateBalance(43) - Current balance: 200.0
10 Feb 2016 18:18:19,159 -[pool-11-thread-1]- DEBUG -
  SclwBalanceUpdater.updateBalance(44) - Deviation : 50.0
10 Feb 2016 18:18:19,159 -[pool-11-thread-1]- DEBUG -
  UserBalanceManager.updateWalletBalance(70) - Updating user..510978682
10 Feb 2016 18:18:19,160 -[pool-11-thread-1]- DEBUG -
  SclwBalanceUpdater.updateBalance(51) - Final Balance: 250.0
10 Feb 2016 18:18:19,160 -[pool-11-thread-1]- DEBUG -
  ScratchpadMasterStreamProcessor.processMessage(79) - Balance Update
  was successful for wallet 510978682
Transaction #3 (This is lost)
10 Feb 2016 18:18:19,160 -[pool-11-thread-1]-  INFO -
  ScratchpadMasterStreamProcessor.processMessage(62) - Printing str id:
  1466162182Scratchpad id: 9127117934
10 Feb 2016 18:18:19,161 -[pool-11-thread-1]- DEBUG -
  SclwBalanceUpdater.updateBalance(43) - Current balance: 250.0
10 Feb 2016 18:18:19,161 -[pool-11-thread-1]- DEBUG -
  SclwBalanceUpdater.updateBalance(44) - Deviation : -250.0
10 Feb 2016 18:18:19,161 -[pool-11-thread-1]- DEBUG -
  UserBalanceManager.updateWalletBalance(70) - Updating user..510978682
10 Feb 2016 18:18:19,162 -[pool-11-thread-1]- DEBUG -
  SclwBalanceUpdater.updateBalance(51) - Final Balance: 0.0
10 Feb 2016 18:18:19,162 -[pool-11-thread-1]- DEBUG -
  ScratchpadMasterStreamProcessor.processMessage(79) - Balance Update
  was successful for wallet 510978682
Transaction #4 Read stale balance, oops
10 Feb 2016 18:18:23,140 -[pool-11-thread-1]-  INFO -
  ConsumerThread.run(82) - Event Recieved
10 Feb 2016 18:18:23,140 -[pool-11-thread-1]-  INFO -
  ScratchpadMasterStreamProcessor.processMessage(62) - Printing str id:
  1466162730Scratchpad id: 9127120830
10 Feb 2016 18:18:23,141 -[pool-11-thread-1]- DEBUG -
  SclwBalanceUpdater.updateBalance(43) - Current balance: 250.0
10 Feb 2016 18:18:23,141 -[pool-11-thread-1]- DEBUG -
  SclwBalanceUpdater.updateBalance(44) - Deviation : 200.0
10 Feb 2016 18:18:23,141 -[pool-11-thread-1]- DEBUG -
  UserBalanceManager.updateWalletBalance(70) - Updating user..510978682
10 Feb 2016 18:18:23,142 -[pool-11-thread-1]- DEBUG -
  SclwBalanceUpdater.updateBalance(51) - Final Balance: 450.0
10 Feb 2016 18:18:23,142 -[pool-11-thread-1]- DEBUG -
  ScratchpadMasterStreamProcessor.processMessage(79) - Balance Update
  was successful for wallet 510978682

I have set consistency level to LOCAL_QUORUM for both reads and writes, and the three cassandra node servers have same time (using NTP). What could be the problem?

A: Cassandra is very good with immutable data and idempotent operations. Not so much with transactions or frequent updates/deletes.
One quick check is if you are using light weight transactions. They come at a performance cost but maybe necessary in important data. For example,
UPDATE balances
SET balance = <new_balance>
WHERE id = <wallet_id>
IF balance = <old_balance>

A: First, please take a look on Codo's comment that describes very well why do you have a problem.
However I'd like to suggest a solution without moving to other DB.
You can use counter type for your balance field. The update statement of counter works differently. It sends to cassandra command to increase/decrease the field by cirtain value, so you will not have a problem of inconsistency.
The counter based solution however is not good for all applications. For example it is limited to integer type. Probably more common solution is to create a kind of transaction programmatically: save update requests in separate table and create asynchronous procedure that aggregates all update requests done during certain period of time and applies them to the balance value.

A: It seems you have a race condition for update operations. Cassandra does not update data, but inserts a new one with another timestamp. Data with the last timestamp is the actual version of the data.
Do you specify timestamps for update queries?
Timestamps allow you to provide the correct sequence for a mutation operation.
If you don't specify the timestamp result of Transaction#3, it can be overwritten by Transaction#2 because they are done in quick succession.


text:
Q: Dropdown focus is not working in jquery I tried whenever alert is fired i want to set focus on that control. For that, I wrote something like below
 var checkIfUserRequesterApprover = document.getElementById('hdnSessionValue').value;

if (checkIfUserRequesterApprover == "VSAT Approver") {
    var ddlSiteApproved = $('#ddlSiteApproved').val();
    if (ddlSiteApproved == "Site Not Approved") {
        jAlert('Site cannot be Approved if marked as Site Not Approved in Site Approved/Not Approved', 'INFORMATION');
        return false;
        $("#ddlSiteApproved").focus();
    }
}

A: Since I'm not having an external link for jAlert, I cant post the fiddle here.
Also I'm not sure which version or file you are using for jAlert.
$(function(){
  jAlert('Site cannot be Approved if marked as Site Not Approved in Site Approved/Not Approved', 'INFORMATION', function(){
    $("#ddlSiteApproved").focus();
  });
});

Please check whether this will work for you.
In your case :
var checkIfUserRequesterApprover = document.getElementById('hdnSessionValue').value;

if (checkIfUserRequesterApprover == "VSAT Approver") {
  var ddlSiteApproved = $('#ddlSiteApproved').val();
  if (ddlSiteApproved == "Site Not Approved") {
    jAlert('Site cannot be Approved if marked as Site Not Approved in Site Approved/Not Approved', 'INFORMATION', function() {
      $("#ddlSiteApproved").focus();
    });
  }
}


text:
Q: Accessing Values From Object property that is an array How can I access values from an object property that is an array?
For example:
$myObject = new MyClass;

$myObject->myproperty = array(1 => 'English', 2 => 'French', 3 => 'German');

How can I get individual property values using the array keys from $myObject->mypropery? Using $myObject->myproperty[3] does not work.
EDIT: Using $myObject->myproperty[3] does in fact work.  Where I find a problem is when doing it like this:
$myproperty = 'myproperty';

echo $myObject->$myproperty[3]

// result : 'r'

Yet if I do a var_dump on $myObject->$myproperty I see my array.

A: try this:
$myObject->myproperty[3]

instead of this:
$myObject->$myproperty[3]

A: $tmp = $myObject->$myproperty;
echo $tmp[1];
//or
echo $myObject->{$myproperty}[1];

A: To access your myproperty array values try this:
$myObject->{$myproperty}[3]

Instead of:
$myObject->$myproperty[3]

These are referred to as Variables Variable, for more information visit: http://php.net/manual/en/language.variables.variable.php
The reason your echo result was r is because your $mypropery value is mypropery and you executed this echo $myObject->$myproperty[3] which translate to saying you want the third character array keys value. Since arrays are zero based this means you will get the character r as a result. Hope this clears up why your result was r.


text:
Q: Css animation In/out I'm trying to recreate the dropdown animation of the "new" google developers webpage (you can see here just click over the input search:https://developers.google.com/analytics/devguides/collection/android/v4/app)
I can create the "in" animation and the dropdown goes down. But i'm not able to create the "out" animation and make go up the dropdown like in the Google Developers page. Here's a jsfiddle i created:
http://jsfiddle.net/8y48q/53/
I poste some code btw:

      <form id="form" class="uk-form uk-width-1-1 center-form">

              <input id="input" data-ng-click="openSearch()" hide-search="hideSearchContainer()" type="text" placeholder="text" class="uk-width-1-1 uk-vertical-align-middle">

                      Hello i'm a dropdown!

       </form>

A very simple angularjs
var myApp = angular.module('myApp', []);

myApp.controller('TestCtrl', function ($scope) {

    $scope.openSearch = function(){
            $scope.userSearch = true;
        };
        $scope.hideSearchContainer = function(){
            $scope.userSearch = false;
        };

});

myApp.directive('hideSearch', function($document){
    return {
        restrict: 'A',
        link: function(scope, elem, attr, ctrl) {
            elem.bind('click', function(e) {
                e.stopPropagation();
            });
            $document.bind('click', function() {
                scope.$apply(attr.hideSearch);
            })
        }
    }
});

A: Add transition to .search-results-closed too:
.search-results-closed {
  transition: all 0.5s ease 0s, visibility 0.5s ease 0s;
}

FIDDLE: https://jsfiddle.net/lmgonzalves/8y48q/54/

A: You could do this with css animations and :focus states.

p{
  border: 1px solid gray;
  width: 200px;
  text-align: center;
  height: 0;
  overflow: hidden;
  animation: hide 1s ease forwards;
  -webkit-animation: hide 1s ease forwards;
}
input:focus + p{
  display: block;
  -webkit-animation: show 1s ease forwards;
  animation: show 1s ease forwards;
}
@-webkit-keyframes show{
  0%{
    height: 0px;
  }
  100%{
    height: 50px;
  }
}
@-webkit-keyframes hide{
  0%{
    height: 50px;
  }
  100%{
    height: 0px;
  }
}
@keyframes show{
  0%{
    height: 0px;
  }
  100%{
    height: 50px;
  }
}
@keyframes hide{
  0%{
    height: 50px;
  }
  100%{
    height: 0px;
  }
}
<input type="text" id="box" placeholder="text">

Hello, I'm an alert


text:
Q: How to upload a file to a shared drive with Google API Drive v3 ruby gem I am trying to upload a file to a shared drive, however; if I set my drive_id in the options parameters, it still used my default drive, which is "My Drive".
What am I doing wrong? (The drive_id is just an example)
google_file = Google::Apis::DriveV3::File.new(drive_id: "123456789", name: 'test.txt')
drive = Google::Apis::DriveV3::DriveService.new
source_file Tempfile.new("text.txt")
drive.create_file(google_file, upload_source: file)

I have also tried setting the parent_ids when I create a file and am getting an error as well. See below:
Google::Apis::DriveV3::File.new(drive_id: '123456789', name: 'test.txt', parents: ['123456789'])

results in:
Google::Apis::ClientError: notFound: File not found: 123456789.

Any help here will be greatly appreciated!

A: I believe your goal is as follows.

*

*You want to upload a file to the specific folder in the shared Drive using Drive API v3.

*You want to achieve this using googleaspif ro ruby.

In this case, how about the following modification?
Modified script:
google_file = Google::Apis::DriveV3::File.new(name: 'test.txt', parents: ['###'])
drive = Google::Apis::DriveV3::DriveService.new
drive.create_file(google_file, upload_source: "text.txt", supports_team_drives: true)

*

*Here, please set the folder ID to ### of parents: ['###']. If you want to upload the file to the root folder of the shared Drive, please set the drive ID to ### of parents: ['###'].

Note:

*

*This modification suppoges that your drive can be used for uploading the file to the shared Drive. Please be careful about this.

References:

*

*Files: create

*Class: Google::Apis::DriveV3::DriveService


text:
Q: how to pass php array as a parameter to the external js function i have sample array $arras below. when we click on the button, the function user_info() will be called and this array will be passed to ajax request.my script looks like
<?php
   $arr = array(
            array(
               "first_name" => "Darian",
               "last_name" => "Brown",
               "age" => "28",
               "email" => "darianbr@example.com"
          ),
         array(
              "first_name" => "John",
              "last_name" => "Doe",
              "age" => "47",
              "email" => "john_doe@example.com"
         )
      );

   $encoded =json_encode($arr);

?>

<button onclick="user_info()">click here</button>

and my js function is
  function user_info()
  {
    var my_arr = '<?php echo $encoded; ?>';
    var data='';
    $.ajax({
        data: {arr: my_arr},
        type: 'POST',
        url: site_url+'admin/profile/users/',
        success: function(response)
        {
            var JSONObject = $.parseJSON(response);
            for (var key in JSONObject) {
                if (JSONObject.hasOwnProperty(key)) {
                   data += (JSONObject[key]["first_name"] + ", " + JSONObject[key]["age"])+"
";
                }
              }
            $('#result_view').html(data);
          }
      });
    }

my php code and js function are on the same php file and it's working. now i want to put this js function to my external js file. and i need to pass my array as a parameter on function call. i tried to pass the array as a parameter like this
<button onclick="user_info(<?php echo $encoded;?>)">click here</button>

and my external js function look like this
function user_info(my_arr)
{
 ...
}

but it's not working.
how can i pass my array as a parameter on external function call?  I would appreciate for any help. thank you.

A: HTML file

<button onclick="user_info()">click here</button>

External JS file
function user_info()
{
    ...
    //use enc var here
    ...
}

Just make sure the external JS file is included after the little script tag.

A: Use single quotes in your array to prevent conflict with double quotes in html attributes. e.g.
   array(
               'first_name' => 'Darian',
               'last_name' => 'Brown',
               'age' => '28',
               'email' => 'darianbr@example.com'
          )

A: Pass it as string
<button onclick="user_info('<?php echo $encoded;?>')">click here</button>

A: You shouldn't put quotes around <?php echo $encoded ?>. That's creating a string instead of an object. So it should be:
var my_arr = <?php echo $encoded; ?>;


text:
Q: How to get Usage ID or a similer attribute for a USB (HID Usage ID) connected device in Linux Is there a way to get HID Usage ID for a USB device in Linux ?
I can use lsusb to get PID and VID but in device driver development we cannot use PID as it is different in different devices which are run in a particularly same mode. When thinking from windows developments point of view HID Usage ID is unique for this level.

A: The usage pages supported by a device must be parsed out of the device's report descriptor. Windows does this for you when you call HidD_GetPreparsedData. There are two ways to get the report descriptor from the device:

*

*Open the /dev/hidrawN device node and use the HIDIOCGRDESCSIZE and HIDIOCGRDESC ioctls to get the report descriptor.

*Read the report descriptor out of sysfs by opening the report_descriptor file in the device's sysfs directory. This property is also available through the udev library.

Once you have the raw report descriptor you can use a library like hidrd to parse it.


text:
Q: Forum message thread in asp.net MVC My goal is to create a simple forum from scratch in ASP.net MVC.
Why? Because I want to learn how to.
Also relatively new to ASP.net MVC I would like to do the following.
I have a messageRepository which communicates to my message table in my DB.
I have function here called named
public IQueryable<Message> FindAllMessages()
    {
        return db.Messages;
    }

Now I also want to create an overload function which takes a message id as a parameter and then returns a list of all messages containing this parameter.
sort of like this.
public IQueryable<Message> FindAllMessages(int id)
    {
        //take the id here and make it so that it returns a list
        //with all messages containing this id
        return db.Messages;
    }

So my question : Does anyone know how to do this?
Also if you think my approach is wrong please tell me.
UPDATE:
Ok I made some changes so right now I'm using a linq statement to fill a message variable like so
  public IQueryable<Message> FindAllMessages(int id)
    {
        var messages = from p in db.Messages
                       where p.ThreadReplyID == id
                       select p;
        return messages;
    }

Which is roughly what I asked for.
So my solution I'm giving all my threadReplyIDs  the same id as my ThreadID.

A: What is the id parameter? If it the primary key then each message will have a unique ID value. Also are you using Entity framework? With EF you can easily do a find via
yourdbcontext.Messages.Find(id)


text:
Q: How to make a smoother slide_up/down animation on a Text View? I have 3 Text Views representing the information belonging to 3 categories. I also have 3 other Text Views that represent the title of each category.
These Text Views are constrained against each other (Text View A Title is constrained above Text View A Information, which is constrained Text View B Title, which is constrained above Text View B Information). Looks like this:

I have written code so that when a Text View title is clicked, the corresponding Text View information slides down and shows information.
My issue here is that when, for example, Text View B information populates with data, Text View C Title appears where the end of Text View B information will shortly be, but in a sudden and Jerky movement (the order of Text Views is still correct, it is the jerky movement I don't want). After 2 seconds (the time of the slide_down) Text View B information is filled and is plush above Text View C title:

Similarily, when the title is clicked again the scroll_up is triggered but Text View C Title appears directly under Text View B Information in a teleport. Then the sliding occurs and the text goes through Text View C Title:

Is there any way so that the Text View below the Text Viewing that is sliding, will be pushed in the sliding motion of the slide up or slide_down, rather than this teleportation that is occurring?
I've been fiddling with the code for a while now and I am stuck.
The method that calls the animation:
public void ShowWeekly(View view) {

    if(WeeklyTextView.isShown()){
        slide_up(this, WeeklyTextView);
        WeeklyTextView.setVisibility(View.GONE);
    }
    else{
        WeeklyTextView.setVisibility(View.VISIBLE);
        slide_down(this, WeeklyTextView);
    }
}

The slide_up xml:
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">

android:fillAfter="false">
<scale
    android:duration="2000"
    android:fromXScale="1.0"
    android:fromYScale="1.0"
    android:interpolator="@android:anim/test"
    android:toXScale="0.0"
    android:toYScale="0.0" />

Slide_down xml:
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">

android:fillAfter="true">
<scale
    android:duration="200"
    android:fromXScale="1.0"
    android:fromYScale="0.0"
    android:interpolator="@android:anim/linear_interpolator"
    android:toXScale="1.0"
    android:toYScale="1.0" />

Text Views are in a constraint layout within a Scroll View. Here are the text views:
<ScrollView

    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingBottom="16dp"
    android:id="@+id/scroll"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/OverallButton">

    <android.support.constraint.ConstraintLayout
        android:id="@+id/constraint"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toBottomOf="@id/OverallButton"
        >

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textSize="20dp"
            android:id="@+id/OverallTextView"
            android:text="Overall Statistics\n"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintTop_toBottomOf="parent"
            android:onClick="ShowDistance"
        />
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/OverallTextViewContent"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/OverallTextView"
            />
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Weekly Statistics\n"
            android:textSize="20dp"
            android:id="@+id/WeeklyTextView"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/OverallTextViewContent"
            android:onClick="ShowWeekly"
            />

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/WeeklyTextViewContent"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/WeeklyTextView"
            />

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Best Statistics\n"
            android:textSize="20dp"
            android:id="@+id/BestTextView"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/WeeklyTextViewContent"
            android:onClick="ShowBest"
            />

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/BestTextViewContent"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/BestTextView"
            />

</android.support.constraint.ConstraintLayout>

</ScrollView>

A: I managed to give it a quick fix by using a runnable thread that waits for a period of time (the time you set the animation length) before the Text View C title moves back. This gives the Text View B content time to fully shrink, before Text View C title snaps back to it's original position before the list scrolled down.
Text View C title still has the snap jerky motion when returning, but it actually looks good
Here is the new method:
if(OverallTextViewContent.isShown()){

        slide_up(this, OverallTextViewContent);

        view.postDelayed(new Runnable() {
            @Override
            public void run() {
                OverallTextViewContent.setVisibility(View.GONE);
            }
        }, 500);
    }