text:
Q: User can only be linked to one identity for the given provider I am building an application wherein user can log in anonymously and later can choose to login with Google or facebook. I've followed the steps mentioned in firebase site and also this post but still am getting an error which reads -

code: "auth/provider-already-linked",
  message: "User can only be
  linked to one identity for the given provider."

Below are my auth.service.ts contents
@Injectable()
export class AuthService {
  user: Observable<User>;
  constructor(private afAuth: AngularFireAuth,
    private afs: AngularFirestore,
    private router: Router) {
    this.user = this.afAuth.authState
      .switchMap(user => {
        if (user) {
          return this.afs.doc<User>(`usersData/${user.uid}`).valueChanges()
        } else {
          return Observable.of(null)
        }
    });
  }

  anonymousLogin(): Promise<any>{
    return this.afAuth.auth.signInAnonymously();
  }

  get authState(): Observable<User>{
    return this.afAuth.authState.map(data => {
      return data;
    });
  }

  get currentUser(): boolean {
    return this.user !== null;
  }

  getCurrentUser(): User{
    return this.afAuth.auth.currentUser;
  }

  googleLogin() {
    const provider = new firebase.auth.GoogleAuthProvider()
    return this.oAuthLogin(provider);
  }

  facebookLogin(){
    const provider = new firebase.auth.FacebookAuthProvider();
    provider.setCustomParameters({
      'display': 'popup'
    });
    return this.oAuthLogin(provider);
  }

  private oAuthLogin(provider) {
    return this.afAuth.auth.signInWithPopup(provider)
      .then((response) => {
        if(this.getCurrentUser() !== null){
          let cred = null;
          if(response.credential.providerId === 'google.com'){
            cred = firebase.auth.GoogleAuthProvider
                   .credential(response.credential.idToken);
          }else if(response.credential.providerId === 'facebook.com'){
            cred = firebase.auth.FacebookAuthProvider
                   .credential(response.credential.authToken);
          }
          firebase.auth().currentUser
          .linkWithCredential(cred).then(function(user) {
            console.log("Anonymous account successfully upgraded", user);
          }, function(error) {
            console.log("Error upgrading anonymous account", error);
          });
        }
        this.updateUserData(response.user)
      });
  }

  private updateUserData(user) {
    const userRef: AngularFirestoreDocument<any> = this.afs.doc(`usersData/${user.uid}`);
    const data: User = {
      uid: user.uid,
      email: user.email,
      displayName: user.displayName,
      photoURL: user.photoURL,
      isAnonymous: user.isAnonymous,
      roles: {
        customer: true
      }
    };
    return userRef.set(data, {merge: true});
  }
  signOut() {
    this.afAuth.auth.signOut().then(() => {

    });
  }
}

As suggested in other posts referred I've used linkWithCredential method by passing required idToken/accessToken but it is failing to link the accounts on both providers and hence end up creating multiple accounts under Authentication-> Users.
Could anyone please point me in the right direction or am I missing anything here?

A: If you are getting auth/provider-already-linked error code, it means you have already linked the provider to that user. You can only link a provider once. You can't have multiple Facebook accounts to the same user. Only once. If you want to remove that account, you have to unlink it: firebase.auth().currentUser.unlink(firebase.auth.FacebookAuthProvider.PROVIDER_ID).
You can then link a new Facebook credential to that user.

A: You can easily convert an anonymous authenticated user to a paermanent account.
View the docs here for more details.  I believe that for this to work, you'll have to modify your Auth settings to allow users to login in from multiple accounts.


text:
Q: Send a Python 3.x API POST request without killing webserver So I sent a request to a website using an API key and the site (REDCAP) became unresponsive for nearly 10 minutes. The request I made ultimately completed successfully, but I'm unsure of how to prevent this from happening again. Should I have made a bunch of smaller request instead of one large one?
The key and value pairs themselves take up about as many characters are exampled below, but there are many groups of them, about 600 or so being sent in one post request.
[{'KEY1': 'VALUE1', 'KEY2': 'VALUE2', 'KEY3':'VALUE3'},...{x600}]
The knowledge I have about python has been cobbled together over the course of a couple weeks so I not even sure what I need to ask exactly to prevent this from happening again. After a bit of digging I saw that I should have also included a timeout duration in the post request and should add code to handle that when it fails, but that does not help me with my biggest problem, which is not bringing the site to a grinding halt.
I'll provide my code for context, and I'm sure there are 100 things that could be done better or differently, but it worked as intended more or less so I'm not asking for feedback on my code, though will take any advice given. I've obfuscated anything I wasn't comfortable sharing on the web with three hash marks ###.
#!/usr/bin/env python
import requests,json,logging
logging.basicConfig(filename='###.log', \
                    format='%(asctime)s %(message)s', \
                    datefmt='%m/%d/%Y %I:%M:%S %p', \
                    level=logging.DEBUG)

#TOKEN = '###' #Live
TOKEN = '###' #Test
URL = '###'

dload = {
    'token': TOKEN,
    'content': 'record',
    'format': 'json',
    'type': 'flat',
    'fields[0]': '###',
    'rawOrLabel': 'raw',
    'rawOrLabelHeaders': 'raw',
    'exportCheckboxLabel': 'false',
    'exportSurveyFields': 'false',
    'exportDataAccessGroups': 'false',
    'returnFormat': 'json',
    'filterLogic': 'datediff([###],"TODAY","d",true) < 7'
}

dloadget=requests.post(URL,dload)
dmeta=dloadget.json()
logging.debug('Raw exported data: %s \n',dmeta)

if len(dmeta) == 0:
    logging.info('Records up to date')
else:
    for i,tpoints in enumerate(dmeta):
        dmeta[i].update({'###':None})

    logging.debug('Raw imported data: %s \n',dmeta)

    DATA = json.dumps(dmeta)
    fields = {
        'token': TOKEN,
        'content': 'record',
        'format': 'json',
        'type': 'flat',
        'overwriteBehavior': 'overwrite',
        'data': DATA
    }

    r2=requests.post(URL, data=fields)

    if r2.status_code == 200:
        logging.info('global notes log updated')
    else:
        logging.warning('updated failed %s',r2)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Google Chrome breaks when onfocus sets select size The following javascript to resize a select list breaks in Google Chrome. It works when tabbing into the field, but clicking on it results in the "Aw, Snap!" error page.
<select onfocus="this.setAttribute('size', 3);">
<option>selectList with onfocus</option>
<option>2</option>
<option>3</option>
<option>4</option>
</select>

Works fine in FF and IE.
It's some kind of conflict between onfocus (there's no problems if I implement it onClick) and setting the size attribute. I'm told it breaks in Safari too.
Any assistance, ideas or workarounds are greatly appreciated.
(P.S. Yeh I know it's not very nice form to resize a select list, but it's what the boss/client wants)

A: Change the line with the select to this:
<select onfocus="var that = this; setTimeout(function() {that.setAttribute('size', 3);}, 0);">

It works for me in Chrome. I haven't tried in Safari but I suspect it will work as well. Basically all we do here is escaping the call stack with setTimeout, which appears to get around the bug in Webkit.

A: I also found this:

*

*http://code.google.com/p/chromium/issues/detail?id=4579

*http://bugs.webkit.org/show_bug.cgi?id=17648
So it seems this is a WebKit issue and for some reason they don't want to fix it (make it standards-compliant).

A: As far as I can tell, Google Chrome ignores ALL select size attributes for multiple select boxes.
See link:
http://www.w3schools.com/TAGS/tryit.asp?filename=tryhtml_select_size
Use any other browser, then try Google Chrome.   Just basic HTML attributes completely ignored by Chrome.


text:
Q: poles and zeros of control system Does number of poles always equal to number of zeros in a control system? means if number poles is greater than number of zeros then remaining number of zeros lie at "infinity".
I found this concept in the book "Linear Control Systems, with Matlab Applications: B S Manke". But there is no explanation.

A: No, the number of poles does not need to be equal to the number of zeros. One could be greater/lesser than the other. For instance, a differentiator or integrator could have an unequal number of poles and zeros. It is simply the nature of the control system that determines this relation.
The assumption that zeros lie at infinity is done only in the case of root locus plots. These zeros are only introduced to complete the definition of the root locus equation, but do not actually occur when you take a look at the transfer function.

A: Generally no. Whatever your book said, it's not that there are always as many zeros as poles. For instance, if H is a strictly proper transfer function, then unity feedback on H gives
$$H_c = \frac{H}{1+H} = \frac{N_H}{D_H+N_H},$$
where N_H and D_H are the numerator and denominator of H respectively. Since H is strictly proper, deg D_H > deg N_H, hence deg (D_H + N_H) > deg N_H, so the closed loop transfer function is also strictly proper. This always means that the number of the poles, not including their order, is greater than the number of zeros (not including their multiplicity). As order and multiplicity count toward the shape of the frequency response and timescales of the transient response, the overall system is minimum phase.
If you still protest that the poles may not be distinct, not that one may easily find specific H for which each pole is simple and each zero has multiplicity one. This system will be minimum phase.
There is no such thing as a "zero at infinity"--each root of a polynomial over an algebraically closed field is contained in that field, and in the case of the complex numbers there are at most as many zeros as the order of the polynomial.


text:
Q: (Parse -> Firebase) How can I convert this query? I have one last query remaining in my application to complete transferring it from Parse and it seems to be the one that's going to cause the most trouble.
Here's the Parse query:
let potential_query = UserAccounts.query()!
let excluded_objects = [String]()

for(...) excluded_objects.push(...);

potential_query.whereKey('objectId', notContainedIn: excluded_objects);
potential_query.whereKey('question_count', greaterThan: 2);
potential_query.whereKey('deactivated', equalTo: false);
potential_query.whereKey('discovery_enabled', equalTo: true);
potential_query.whereKey('gender', equalTo: 'MALE');
potential_query.whereKey('age', greaterThan: 18);
potential_query.whereKey('age', lessThan: 23);
potential_query.whereKey('location', nearGeoPoint: ..., withinMiles: 15); // User within 15 miles based on location data.
potential_query.limit = 1;

Please note that the values provided are not static and are changed based on the authenticated user. Going through the documentation for Firebase it seems like there's not really any options for advanced querying. objectId would be the uid in Firebase.
Is this even possible?

A: [Background: I'm currently a backend engineer on the Firebase team. I used to be a Parse backend engineer and spent a lot of time on app performance]
The Parse API has a more expressive query language, which is a double edged sword. You're blissfully free to write almost any query and the Parse backend will try its best to guess which indexes will help the best. I actually co-presented F8 last year with a relevant talk "Running at Scale on Parse". You can see some of the bits regarding query performance starting at 16:30. TL;DR: only a few of those query operators are going to help narrow down the database scan at all. The most valuable two in your case are probably the geo query and the age query. Standard database indexes simply cannot index more than one inequality (less than/greater than) or an inequality and sort on different keys. We can talk about how to index on multiple equality fields + one inequality, but equality conditions work best when:

*

*You're (almost) always going to be using these keys in your query. If not, you need separate indexes for when the key is part of your query and when it's not.

*Your equality term greatly narrows down results. E.g. Ignoring non-uniform demographics, age equality should roughly cut your results down 80x whereas gender equality should only cut results down 2x.

For your particular case, I would use GeoFire to build a geographical index and use the standard range operators on the age query:
myRef.orderByChild('age').startAt(18).endAt(23).limit(someGuess)

You need 'someGuess' because you're going to want to run the rest of the query operators client-side. You can (but don't necessarily have to) use limit if there's going to be a lot of false positives with your query.
If you don't know whether it's quicker to use the age or geolocation scan, you can try both with Promise.race


text:
Q: Show files in tkinter Scrollbar I tried to modify the Scrollbar from Tkdoc (http://www.tkdocs.com/tutorial/morewidgets.html#scrollbar) in order to show the filelist of a folder but it does not work. Can someone explain me why? and how to fix it.
Thanks a lot.
from tkinter import *
from tkinter import ttk
import os

def fileName():
    path="C:\\temp"
    dir=os.listdir(path)
    for fn in dir:
        print(fn)

root = Tk()
l = Listbox(root, height=5)
l.grid(column=0, row=0, sticky=(N,W,E,S))
s = ttk.Scrollbar(root, orient=VERTICAL, command=l.yview)
s.grid(column=1, row=0, sticky=(N,S))
l['yscrollcommand'] = s.set
ttk.Sizegrip().grid(column=1, row=1, sticky=(S,E))
root.grid_columnconfigure(0, weight=1)
root.grid_rowconfigure(0, weight=1)
l.insert(fileName)
root.mainloop()

A: You should specify where to insert
l.insert(END, filename)
In your code, you insert function filename. Insert return value of filename function.
I renamed fileName to get_filename, and modified it to return filename list.
from tkinter import *
from tkinter import ttk
import os

def get_filenames():
    path = r"C:\temp"
    return os.listdir(path)

root = Tk()
l = Listbox(root, height=5)
l.grid(column=0, row=0, sticky=(N,W,E,S))
s = ttk.Scrollbar(root, orient=VERTICAL, command=l.yview)
s.grid(column=1, row=0, sticky=(N,S))
l['yscrollcommand'] = s.set
ttk.Sizegrip().grid(column=1, row=1, sticky=(S,E))
root.grid_columnconfigure(0, weight=1)
root.grid_rowconfigure(0, weight=1)
for filename in get_filenames():
    l.insert(END, filename)
root.mainloop()


text:
Q: fundamental solution of the heat equation on closed manifold - gradient convergence for $t\to 0$ Let $M$ be a compact Riemannian manifold without boundary and $H$ its heat kernel. Given a smooth function $u\colon M\to \mathbb{R}$ let us consider
$v(t,x):=\int_{M} H(x,y,t)v_0(y) dy$
where $dy$ is short for integration on the Riemannian manifold $M$.
$v$ is a solution of $\partial_tv-\Delta v=0$.
Moreover $v(t,.)\to v_0$ in $C^0(M)$ as $t\to 0^+$, i.e. $v(t,.)\to v_0$ uniformly as $t\to 0^+$
Question: Does it hold that $\nabla v(t,.)\to \nabla v_0$ uniformly as $ t\to 0^+$? ($\nabla$ is the gradient with resprect to the Riemannian metric.)
Thanks for any answers.


text:
Q: Universal function pointer There is some class which have methods like:
int getSomething1();
std::string getSomething2();
someClass getSomething3();

There is structure which describes fields of this class like:
{"name of field", pointer to getter, std::type_info}

Then I would like to use it as follows:
if(type == int){
   field_int = (int)getter();
}
else if(type == std::string){
   field_string = (std::string)getter();
}
etc.

How to transform getters like
 int getSomething1();
 std::string getSomething2();
 etc.

to some universal function pointer and then to get the correct value of field?

A: This answer of mine to another question addresses your problem pretty well. With some minor modifications, you get this:
template<class C, class T>
T get_attribute(const C& instance, T (C::*func)() const) {
    return (instance.*func)();
}

Assuming the following:
struct Foo {
    int getSomething1() const;
    std::string getSomething2() const;
    someClass getSomething3() const;
};

You can use it like this:
Foo foo;
int value = get_attribute<Foo, int>(foo, &Foo::getSomething1);
std::string value = get_attribute<Foo, std::string>(foo,  &Foo::getSomething2);
someClass value = get_attribute<Foo, someClass>(foo,  &Foo::getSomething3);

You can of course transform get_attribute to a functor to bind some or all of the arguments.

A: What you are trying to achieve can be better achieved with already existing containers such as a boost fusion sequence. I'd advice that you try this first.

A: There is no formal universal function pointer, the equivalent of void*
for data.  The usual solution is to use void (*)(); you are guaranteed
that you can convert any (non-member) function pointer to this (or any
other function pointer type) and back without loss of information.
If there is a certain similarity in the function signatures (e.g. all
are getters, with no arguments) and how they are used, it may be
possible to handle this with an abstract base class and a set of derived
classes (possibly templated); putting pointers to instances of these
classes in a map would definitely be more elegant than an enormous
switch.

A: Templates to the rescue!
// Create mapping of type to specific function
template <typename T> T getSomething(); // No default implementation
template <> int getSomething<int>() { return getSomething1(); }
template <> std::string getSomething<std::string>() { return getSomething2(); }
template <> someClass getSomething<someClass>() { return getSomething3(); }
// Convenience wrapper
template <typename T> void getSomething(T& t) { t = getSomething<T>(); }
// Use
int i = getSomething<int>();
std::string s;
getSomething(s);

A: As I understand, your difficulty is in storing the function pointers, since they are of different types. You can solve this using Boost.Any and Boost.Function.
#include <boost/any.hpp>
#include <boost/function.hpp>

int getInt() {
    return 0;
}

std::string getString() {
    return "hello";
}

int main()
{
    boost::function<boost::any ()> intFunc(getInt);
    boost::function<boost::any ()> strFunc(getString);

    int i = boost::any_cast<int>(intFunc());
    std::string str = boost::any_cast<std::string>(strFunc());
}


text:
Q: Google Map API how to set marker for current location I'm learning google map API and stuck at this problem when i'm trying to add the current coordinate to an array. Here is my code:
var locations = [];

In initialize() i have:
function initialize() {
    infowindow = new google.maps.InfoWindow();
    var myOptions = {
        zoom: 10,
        mapTypeControl: true,
        navigationControl: true,
    }
    map = new google.maps.Map(document.getElementById("map"), myOptions);

    add_location('Place 1', 37.2846372, -123.3270422);
    set_current_location();
    set_markers(new google.maps.LatLngBounds(), map);
}

The first marker is set, while the set_current_location() doesn't seem to work. Here is the rest of the code:
// add new location to the locations array
function add_location(description, lastitude, longtitude) {
    locations.push([description, lastitude, longtitude]);
}

// Set all the markers in the location arrays and bound/frame the map
function set_markers(bounds, map) {
    for (i = 0; i < locations.length; i++) {
        marker = new google.maps.Marker({
            position: new google.maps.LatLng(locations[i][1], locations[i][2]),
            map: map
        });
        bounds.extend(marker.position);
        google.maps.event.addListener(marker, 'click', (function (marker, i) {
            return function () {
                infowindow.setContent(locations[i][0]);
                infowindow.open(map, marker);
            }
        })(marker, i));
    }
    map.fitBounds(bounds);
}

// Get current location based on the IP Address
function set_current_location() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function (position) {
            var pos = new google.maps.LatLng(position.coords.latitude,
            position.coords.longitude);
            var myLat = position.coords.latitude;
            var myLong = position.coords.longitude;
            add_location('My location', position.coords.latitude, position.coords.longitude);
        });
    } else {
        alert("Geolocation is not supported by this browser.");
    }
}

Can anyone help or give me a hint? I would like to add the current location to the locations array so I can keep track of how many locations I have added. Thank you so much.

A: If you just move set_markers() to the end of success callback of getCurrentPosition() and user refuse to share his location, you won't get the map but just gray area. There is no center set for your map which is required property. Better to define it like:
var myOptions = {
    zoom: 10,
    center: new google.maps.LatLng(37.339386, -121.894955),
    mapTypeControl: true,
    navigationControl: true,
}
map = new google.maps.Map(document.getElementById("map"), myOptions);
...

Additionally, you can also call set_markers() at the end of error callback of getCurrentPosition(), so in case that user refuse sharing of his location, you can show available locations:
// Get current location based on the IP Address
function set_current_location() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function (position) {
            /*
            var pos = new google.maps.LatLng(position.coords.latitude,
                                             position.coords.longitude);
            var myLat = position.coords.latitude;
            var myLong = position.coords.longitude;
            */
            add_location('My location',
                        position.coords.latitude,
                        position.coords.longitude);

            set_markers(new google.maps.LatLngBounds(), map);
        }, function error(err) {
            console.log('error: ' + err.message);
            set_markers(new google.maps.LatLngBounds(), map);
        });
    } else {
        alert("Geolocation is not supported by this browser.");
    }
}

See example at jsbin


text:
Q: I need to check CHAR Fields for numbers How do I do a check of fields in a table to verfiy that the CHAR(X) field contains only numbers, not NULL, and has X digits and returns a specific error for each fault?
Anything I can think of is very clunky.

A: Try using TRY_CONVERT for data validation where the syntax checks for null like
SELECT TRY_CONVERT(int,'21245')

Something like below may help match fields that are incorrect
SELECT * FROM  Table_1 where LTRIM(RTRIM(fieldname)) like '%[^0-9]%'

A: ResultSet
insert into CheckConstraint(Digit)values(1) //Failed

insert into CheckConstraint(Digit)values('ws') //Failed

insert into CheckConstraint(Digit)values(12345) //Passed

For that Your table should be like this to avoid Nullable values
CREATE TABLE CheckConstraint
(
  Digit Char(5) Not Null
)

Create a Function
Create FUNCTION Validations() RETURNS INT AS BEGIN
  DECLARE @ret INT  = 0 ;
  SELECT @ret = IsNull(COUNT(Digit), 0) FROM CheckConstraint
  WHERE Digit not like '[0-9]%'
  RETURN IsNUll(@ret, 0);
END;

Constraints to avoid non numeric characters
alter TABLE CheckConstraint
  add CONSTRAINT CheckValidations CHECK ((dbo.Validations() = 0));

Constraints to avoid less then or greater then 5 characters
ALTER TABLE [dbo].CheckConstraint
ADD CONSTRAINT [MinLengthConstraint] CHECK (DATALENGTH(Digit) = 5)


text:
Q: How to pass and receive the user defined class in REST web services I am learning REST web services. i want to know is there any way to pass user defined class.i am not using spring here and i can able to pass JSON and Xml but is any way to pass user defined class. to pass JSON class am doing by following code.
HttpPost httpPost = new HttpPost("url to REST services method");
List<NameValuePair> postParams = new ArrayList<NameValuePair>();
postParams.add(new BasicNameValuePair("json", jsonObj.toString()));//some json object
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(postParams);
entity.setContentEncoding(HTTP.UTF_8);
entity.setContentType("application/json");

httpPost.setEntity(entity);// here we set param as entity in httpPost

httpPost.setHeader("Content-Type", contentType);
httpPost.setHeader("Accept", contentType);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();

in above example we have set the JSON object into httpPost, but if want to pass user defined class how to set in 'httpPost.setEntity' and what is the contentType i should mention.


text:
Q: slow down scrolling adjustment when selecting a long line I have a long line that I want to select a section in the middle. In Visual Studio, it would scroll all the way to the end of the line, passing where I want the selection to end, when I move pass the text area and move all the way back when I try to move back a little. Is there a way to slow down the Visual Studio scrolling adjustment?

A: If you are talking about selecting text using the mouse you can get fine grained control by combining the the mouse and keyboard.  This should work in any application that allows text selection, not just Visual Studio.
First click the location where you want to begin selecting text.
Next scroll to the location where you want to end selecting text and hold down Shift on the keyboard while clicking with the mouse.  The block of text between the first click and the shift+click will be selected without having to worry about the selection jumping around due to scrolling.
As for actually slowing down the scrolling; I know of no way to do that.  Hopefully my tip should give you an alternate way to do what you actually want.


text:
Q: I didn't find proper solution google-service-plugin version conflict I didn't find proper solution to google-service-plugin version conflict
Error:

Error:org.gradle.api.GradleException: Please fix the version conflict
  either by updating the version of the google-services plugin
  (information about the latest version is available at
  https://bintray.com/android/android-tools/com.google.gms.google-services/)
  or updating the version of com.google.android.gms to 10.0.1.

Root level build.gradle
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
    repositories {
        jcenter()
    }
    dependencies {

        classpath 'com.android.tools.build:gradle:2.3.1'
        classpath 'com.google.gms:google-services:3.0.0'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}
allprojects {
    repositories {
        jcenter()
    }
}
task clean(type: Delete) {
    delete rootProject.buildDir
}

dependencies {
}

app level build.gradle
apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.2"
    defaultConfig {
        applicationId "com.sha.agecalculator"
        minSdkVersion 9
        targetSdkVersion 25
        versionCode 11
        versionName "2.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })

    compile 'com.google.gms:google-services:3.0.0'
    compile 'com.google.firebase:firebase-ads:10.0.1'
    compile 'com.google.android.gms:play-services-ads:10.2.1'
    compile 'com.google.android.gms:play-services-analytics:10.2.1'

    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.android.support:design:25.3.1'
    compile 'com.android.support:support-v4:25.3.1'

    compile 'joda-time:joda-time:2.3'
    testCompile 'junit:junit:4.12'
}

apply plugin: 'com.google.gms.google-services'

A: Wrong
 compile 'com.google.gms:google-services:3.0.0' //remove this line from dependencies

Do
compile 'com.google.android.gms:play-services:10.2.1'
compile 'com.google.firebase:firebase-ads:10.2.1'
compile 'com.android.support:appcompat-v7:25.2.0'
compile 'com.android.support:design:25.2.0'
compile 'com.android.support:support-v4:25.2.0'


text:
Q: How to stop or suspend polling after batch job fail? We use spring-batch-integration to process .json files from directory. It's necessary to stop processing after failure, to find out a problem (to change file with problem or other solutions) and then continue. Current configuration continue polling after error. How to change it? or maybe there are different approach for such scenario.
@Configuration
@IntegrationComponentScan
@EnableIntegration
public class IntegrationConfig {

private @Autowired Job job;

@Bean
@ServiceActivator(inputChannel = "jobChannel",
   outputChannel = "errorChannel")
protected JobLaunchingMessageHandler launcher(JobLauncher jobLauncher) {
    return new JobLaunchingMessageHandler(jobLauncher);
}

@Bean
public MessageChannel fileInputChannel() {
    return new DirectChannel();
}

@Bean
@InboundChannelAdapter(value = "fileInputChannel",
                       poller = @Poller(fixedDelay = "5000"))
public MessageSource<File> fileReadingMessageSource() {
    FileReadingMessageSource source = new FileReadingMessageSource();
    source.setDirectory(new File("C:/Temp/myfiles/"));
    source.setFilter(new SimplePatternFileListFilter("*.json"));
    source.setScanEachPoll(true);
    source.setUseWatchService(true);
    return source;
}

@Transformer(inputChannel = "fileInputChannel",
             outputChannel = "jobChannel")
public JobLaunchRequest transform(File aFile) {
    String fileName = aFile.getAbsolutePath();
    JobParameters jobParameters =
    new JobParametersBuilder().addString("input.file.name", fileName)
            .addDate("dateTime", new Date()).toJobParameters();
    JobLaunchRequest request = new JobLaunchRequest(job, jobParameters);
    return request;
}
}

example was from this article
neither outputChannel = "nullChannel" nor outputChannel = "errorChannel" helps

A: You need to stop the inbound channel adapter.
You can autowire a SourcePollingChannelAdapter which is registered by the @InboundChannelAdapter annotation.
When you detect the failure, call stop() on the adapter.

A: I added
@Bean
@DependsOn("fileInputChannel")
@ServiceActivator(inputChannel = "errorChannel",
  outputChannel = "nullChanel")
protected ErrorLogger errorLogger(JobLauncher jobLauncher) {
    return new ErrorLogger();
}

and
public class ErrorLogger {
private static final Logger logger =
LoggerFactory.getLogger(ErrorLogger.class);

@Autowired
private SourcePollingChannelAdapter fileInputChannel;

@ServiceActivator
public void logError(Message<JobExecution> message) {
    JobExecution msgex=message.getPayload();
     if (msgex.getStatus() == BatchStatus.FAILED) {
         logger.error("Exception " +
         msgex.getExitStatus().getExitDescription());
         fileInputChannel.stop();
     }
}
}

But I get autowiring error in ErrorLogger
Unsatisfied dependency expressed through field 'fileInputChannel'; nested
exception is org.springframework.beans.factory.NoSuchBeanDefinitionException:
No qualifying bean of type
'org.springframework.integration.endpoint.SourcePollingChannelAdapter'
available:

Seems like initialization order issue despite of @DependsOn("fileInputChannel"), because i can autoware it in separate controller without error.
It works only with
 @Autowired(required = false)
 private SourcePollingChannelAdapter fileInputChannel;


text:
Q: How to sort a String or 2d Multidimensional array? Basically I have:
String[][] mda = {{"Hello ma", "3"},
                  {"How r u?", "2"},
                  {"i m fine", "5"}};

To be precise I want to sort this Array based on it's numeric value, which would look like:
"How r u?", "2"
"Hello ma", "3"
"i m fine", "5"

Regards <3

A: Something as simple as this should do the trick.
String[][] mda = {{"Hello ma", "3"},
        {"How r u?", "2"},
        {"i m fine", "5"}};

public void test() {
    System.out.println(Arrays.deepToString(mda));
    Arrays.sort(mda, Comparator.comparing(s -> s[1]));
    System.out.println(Arrays.deepToString(mda));
}

A: You should put these in a Map. You can order them by keys (your integers), and access their values (the string) in order.
This would look like:
Map<Integer, String> myMap = new HashMap<>();
for (String[] tmp : myStrings)
{
    myMap.put(Integer.parseInt(tmp[0]), tmp[1]);
}

A: You should use comparator to sort array of particular index
 String[][] mda = {{"Hello ma", "3"},
                {"How r u?", "2"},
                {"i m fine", "5"}};
         Arrays.sort(mda, new Comparator<String[]>() {
                @Override
                public int compare(final String[] data1, final String[] data2) {
                    final String value1 = data1[1];
                    final String value2 = data2[1];
                    return value1.compareTo(value2);
                }
            });

            for (final String[] str : mda) {
                System.out.println(str[0] + " " + str[1]);
            }

A: Arrays.sort(mda, (o1, o2) -> Integer.parseInt(o1[1]) - Integer.parseInt(o2[1]) );

Arrays.stream(mda).forEach(l ->
  {
      System.out.println(Arrays.deepToString(l));
  });

Or if you like the streams:
List<String[]> collect = Arrays.stream(mda)
                               .sorted((o1, o2) -> Integer.parseInt(o1[1]) - Integer.parseInt(o2[1]))
                               .collect(Collectors.toList());

collect.forEach(l ->
  {
      System.out.println(Arrays.deepToString(l));
  });


text:
Q: how can I set a start date and an end date for my script through a form for a user to make changes to? I am building a form where users must select a time interval, from day to day OR month to month or year to year or even a specific day in a month in a year to another date in time...I would use a JS calendar for it but I am unsure of what I would do to check if that specific date has arrive yet or not.
The user is suppose to choose a starting date and an ending date, the user makes certain changes once and those changes apply for the time interval a user has chosen, so once the end date is reached the changes no longer apply and the script is reset to its default...
These changes can be applied to the program, code in the program etc...But basically the program would allow these changes from the interval in time the user chooses on the form but once the date is reached everything is reset to default...
My original idea was to use PHP's date('W') function in order to get the start and end time from the user and store it, then have my script look up the date everyday to see if the end date has reached yet or not. Then my other ideas was to use JS's calendar pop up to get the start and end date and have some sort of script look up the date everyday to see if the deadline has reached yet or not..But all these arent very reliable ways or methods so perhaps someone here has more experience with this...Cron jobs I am not very experienced with but I am not so sure how I would use php or js in the back end of my form to set a cron job for this..

A: If you are using jQuery UI then the data picker control has a maxDate option as follows:
Set a maximum selectable date via a Date object or as a string in the current dateFormat, or a number of days from today (e.g. +7) or a string of values and periods ('y' for years, 'm' for months, 'w' for weeks, 'd' for days, e.g. '+1m +1w'), or null for no limit.
Code examples
Initialize a datepicker with the maxDate option specified.
$( ".selector" ).datepicker({ maxDate: '+1m +1w' });

Get or set the maxDate option, after init.
//getter
var maxDate = $( ".selector" ).datepicker( "option", "maxDate" );
//setter
$( ".selector" ).datepicker( "option", "maxDate", '+1m +1w' );

Since the date is based on today you can ensure it does not go beyond. If you need more validation then use PHP on the server side too.

A: I'd suggest you use a database to store your modified code / date range.  You don't need to worry about a cron job - just place a bit of code at the beginning of your script to check each time its run which version it should use.
SELECT * FROM scripts WHERE user_id = ....
AND start_date < NOW() AND end_date > NOW()

Check for a current change in the database; if it exists, load up that modified script instead of the normal one.


text:
Q: Download threejs model to .stl I came to find this library that downloads stl from threejs.
https://github.com/mrdoob/three.js/blob/master/examples/js/exporters/STLExporter.js
I am new to js / threejs, so I was wondering how could I incorporate this within my script, or how to link it as a library or other file.
Please note that the model I want to download is either one built from scratch in threejs or one that I imported as glb/gltb and changed some of its features in threejs.
Thank you.

A: There is an official example that demonstrates the usage of STLExporter. I suggest you study the respective source code and use it as a foundation for your own app. You can find the mentioned example right here:
https://threejs.org/examples/misc_exporter_stl

Please note that the model I want to download is either one built from scratch in threejs or one that I imported as glb/gltb and changed some of its features in threejs.

Please keep in mind that STL has no concept of materials. It only saves the raw geometry data. STL is also unable to export hierarchical information of a scene (e.g. child-parent relationships). So depending on what you are going to change in your scene, it's likely that the respective data can't be exported as expected.

A: There is two implementation for export,ASCII & Binary,
        function exportASCII() {

            const result = exporter.parse( mesh );
            saveString( result, 'box.stl' );

        }

        function exportBinary() {

            const result = exporter.parse( mesh, { binary: true } );
            saveArrayBuffer( result, 'box.stl' );

        }


text:
Q: how to deploy java project with jenkins I use jenkins to test my java project and it is successful, but I don't know how to deploy my project to tomcat with ant, how to do?

A: just add following code to build.xml:
 <target name="dist" description="Unpack the file to war file" depends="compile">
   <war basedir="${dir.webRoot}" warfile="${webapp.deployPath}/${project.distname}.war"
                                     webxml="${dir.webRoot}/WEB-INF/web.xml">
    <exclude name="WEB-INF/web.xml"/>
    <exclude name="WEB-INF/lib/junit-4.6.jar"/>
   </war>
</target>

A: Now, you need Deploy Plugin.
This plugin takes a war/ear file and deploys that to a running remote application server at the end of a build. The implementation is based on Cargo. The list of currently supported containers include:
Tomcat 4.x/5.x/6.x/7.x
JBoss 3.x/4.x
Glassfish 2.x/3.x

A: There are several defined ant tasks that you can download and incorporate into your flow to do exactly this. Ant has a summary of the steps you would use to configure this.
Incorporate that into you build.xml and setup the steps in a separate deploy job and you should be good to go.
The steps for the above are for Tomcat 5.5 but they aren't dissimilar to what you would use for Tomcat 7. Also, simply doing a copy of the war file to the webapps dir in Tomcat will cause it to deploy if it is scanning for new wars automatically.

A: Just add some code in build.xml
<target name="dist" description="Unpack the file to war file" depends="compile">
   <war basedir="${dir.webRoot}" warfile="${webapp.deployPath}/${project.distname}.war"
                                     webxml="${dir.webRoot}/WEB-INF/web.xml">
    <exclude name="WEB-INF/web.xml"/>
    <exclude name="WEB-INF/lib/junit-4.6.jar"/>
   </war>
</target>


text:
Q: int&b = a; for gcc vs g++ I realised gcc and g++ handle differently for the following codes:
#include <stdio.h>
int main(void)
{
    int a = 0;
    int& b = a;
    return 0;
}

gcc returns "parse error before &", while no error is returned by g++.
I once encountered an interview mentioned C and C++ compilers handles differently for int& b.

A: That's because & has no meaning in a C type declaration - in C++, it means the variable will be a reference, but those do not exist in C.
In other words, int& b = a; simply isn't valid C code.


text:
Q: Animation Happening Immediately I created a custom tableview cell that has pictures inside that the user can tap and highlight. I also want the highlight to be animated radially from the center until it covers the whole button.
However, when the "button" (just the image view) is pressed, the animation happens instantly and is not animated. All of the code gets executed correctly, but just happens instantly instead of the correct duration. Anyone have any ideas? Thanks.
The part where there is the issue is under the function "presetTapped", and under the "if sender == self.flatTap" condition. The "animatedHighlightView" starts in the center of the superview with size 0,0. it then grows to the size of the super view. But instead of it animating, it happens instantly.
import UIKit

class PresetsTableViewCell: UITableViewCell {
    @IBOutlet weak var flatButtonView: UIView!
    @IBOutlet weak var antiSnoreButtonView: UIView!
    @IBOutlet weak var zeroGravityButtonView: UIView!

    @IBOutlet weak var flatButtonBackgroundView: UIView!
    @IBOutlet weak var antiSnoreButtonBackgroundView: UIView!
    @IBOutlet weak var zeroGravityButtonBackgroundView: UIView!

    var flatTap:UITapGestureRecognizer!
    var antiSnoreTap:UITapGestureRecognizer!
    var zeroGravityTap:UITapGestureRecognizer!
    var selectTap:UITapGestureRecognizer!
    var index:Int = -1

    var animatedHighlightView:UIView!

    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
        self.flatButtonView.layer.cornerRadius = 5
        self.antiSnoreButtonView.layer.cornerRadius = 5
        self.zeroGravityButtonView.layer.cornerRadius = 5

        self.flatButtonBackgroundView.layer.cornerRadius = 5
        self.antiSnoreButtonBackgroundView.layer.cornerRadius = 5
        self.zeroGravityButtonBackgroundView.layer.cornerRadius = 5

        self.flatTap = UITapGestureRecognizer(target: self, action: #selector (self.presetTapped(_:)))
        self.flatButtonView.addGestureRecognizer(self.flatTap)
        self.antiSnoreTap = UITapGestureRecognizer(target: self, action: #selector (self.presetTapped(_:)))
        self.antiSnoreButtonView.addGestureRecognizer(self.antiSnoreTap)
        self.zeroGravityTap = UITapGestureRecognizer(target: self, action: #selector (self.presetTapped(_:)))
        self.zeroGravityButtonView.addGestureRecognizer(self.zeroGravityTap)

        self.animatedHighlightView = UIView(frame: CGRect(x: self.flatButtonBackgroundView.frame.origin.x + self.flatButtonBackgroundView.frame.width/2, y: self.flatButtonBackgroundView.frame.origin.y + self.flatButtonBackgroundView.frame.height/2, width: 0, height: 0))
        self.animatedHighlightView.layer.cornerRadius = self.animatedHighlightView.frame.height/2
        self.animatedHighlightView.backgroundColor = kHighlightPrimary
        self.contentView.addSubview(self.animatedHighlightView)
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }

    func presetTapped(_ sender:UITapGestureRecognizer){
        let tb = self.superview as! DashboardTableView
        tb.selectedType = DashboardItems.Presets
        tb.reloadData()
        if sender == self.flatTap {
            UIView.animate(withDuration: 2, delay: 0, options: .curveLinear, animations: {
                self.animatedHighlightView.frame = CGRect(x: self.flatButtonBackgroundView.frame.origin.x, y: self.flatButtonBackgroundView.frame.origin.y, width: self.flatButtonBackgroundView.frame.width, height: self.flatButtonBackgroundView.frame.height)
                self.animatedHighlightView.layer.cornerRadius = self.animatedHighlightView.frame.height/2
            }) { (complete) in
                self.antiSnoreButtonBackgroundView.backgroundColor = kBackgroundColor
                self.zeroGravityButtonBackgroundView.backgroundColor = kBackgroundColor
                tb.reloadData()
            }
            print("dashboard Flat tapped")
        } else if sender == self.antiSnoreTap {
            self.animatedHighlightView.frame = CGRect(x: self.flatButtonBackgroundView.frame.origin.x + self.flatButtonBackgroundView.frame.width/2, y: self.flatButtonBackgroundView.frame.origin.y + self.flatButtonBackgroundView.frame.height/2, width: 0, height: 0)
            self.flatButtonBackgroundView.backgroundColor = kBackgroundColor
            self.antiSnoreButtonBackgroundView.backgroundColor = kHighlightPrimary
            self.zeroGravityButtonBackgroundView.backgroundColor = kBackgroundColor
            tb.reloadData()
            print("dashboard Anti-Snore tapped")
        } else if sender == self.zeroGravityTap {
            self.flatButtonBackgroundView.backgroundColor = kBackgroundColor
            self.antiSnoreButtonBackgroundView.backgroundColor = kBackgroundColor
            self.zeroGravityButtonBackgroundView.backgroundColor = kHighlightPrimary
            tb.reloadData()
            print("dashboard Zero Gravity tapped")
        }
    }
}


text:
Q: Is SQLite in immutable mode safe on non read-only media? In an application that ships with a read-only SQLite database, I've found that opening the database as immutable radically improves query performance. However the SQLite documentation says this (emphasis mine):

The immutable parameter is a boolean query parameter that indicates that the database file is stored on read-only media. When immutable is set, SQLite assumes that the database file cannot be changed, even by a process with higher privilege, and so the database is opened read-only and all locking and change detection is disabled.

This is tripping me up a bit because the media (Windows Program Files) is not read-only and it can be changed, but the expectation is that it won't change. The application itself does not alter the database. A user could alter the databases using external tools (or just open it in Notepad and corrupt it) but we would call that user error and tell them not to do that.
My concern is that this part of the documentation might be hinting at some other process I'm not aware of (like maybe Windows periodically doing something that might result in the database file changing in some way).
If the application itself does not alter the database, and the user doesn't either, and there isn't some other malicious or poorly-coded program on the computer that might be touching files that don't belong to it, is it reasonably safe to open a SQLite database as immutable?

A: Experimentally, the answer appears to be yes, it is safe. I made this change and have not observed any problems with it.


text:
Q: My Realtek 8125 Ethernet card isn't reconized anymore after an apt-get update/dist-upgrade bring Debian 10 from 4.19.0.16 to 4.19.0.17 Linux image My computer is under Debian 10 with this Linux image :
uname -r
4.19.0-16-amd64

and a R8125 Ethernet card.
lspci | egrep -i --color 'network|ethernet'
04:00.0 Ethernet controller: Realtek Semiconductor Co., Ltd. Device 8125 (rev 05)
05:00.0 Network controller: Intel Corporation Device 2723 (rev 1a)

Today, a new Linux image, 4.19.0.17-amd64 appeared through apt-get update and apt-get dist-upgrade.
These done and the computer rebooted, it doesn't recognize the Ethernet card anymore, and an ifconfig respond : no peripheral found.
So, of course, I'm using the 4.19.0.16 boot to write this question...
Once, the reseller of my computer moaned about the installation he has had to do with a
make install

done from a driver directory, /opt/r8125 it appears he has downloaded from https://github.com/tmacro/r8125.
But I didn't really understood what he did.
I've attempted to use his trick, two months ago, on another Debian partition my computer have (with an image 4.19.0-16-amd64), but :

*

*it seems it didn't worked,

ls -l
-rw-r--r-- 1 root root 2511888 avril 24 13:43 r8125.ko

samedi 24 avril 2021, 13:43:55 (UTC+0200)
make -C src/ clean
make[1] : on entre dans le répertoire « /opt/r8125/src »
make -C /lib/modules/4.19.0-16-amd64/build M=/opt/r8125/src clean
make[2] : on entre dans le répertoire « /usr/src/linux-headers-4.19.0-16-amd64 »
make[2] : on quitte le répertoire « /usr/src/linux-headers-4.19.0-16-amd64 »
make[1] : on quitte le répertoire « /opt/r8125/src »
make -C src/ modules
make[1] : on entre dans le répertoire « /opt/r8125/src »
make -C /lib/modules/4.19.0-16-amd64/build M=/opt/r8125/src modules
make[2] : on entre dans le répertoire « /usr/src/linux-headers-4.19.0-16-amd64 »
  CC [M]  /opt/r8125/src/r8125_n.o
  CC [M]  /opt/r8125/src/rtl_eeprom.o
  CC [M]  /opt/r8125/src/rtltool.o
  LD [M]  /opt/r8125/src/r8125.o
  Building modules, stage 2.
  MODPOST 1 modules
  CC      /opt/r8125/src/r8125.mod.o
  LD [M]  /opt/r8125/src/r8125.ko
make[2] : on quitte le répertoire « /usr/src/linux-headers-4.19.0-16-amd64 »
make[1] : on quitte le répertoire « /opt/r8125/src »
make -C src/ install
make[1] : on entre dans le répertoire « /opt/r8125/src »
make -C /lib/modules/4.19.0-16-amd64/build M=/opt/r8125/src INSTALL_MOD_DIR=kernel/drivers/net/ethernet/realtek modules_install
make[2] : on entre dans le répertoire « /usr/src/linux-headers-4.19.0-16-amd64 »
  INSTALL /opt/r8125/src/r8125.ko
  DEPMOD  4.19.0-16-amd64
make[2] : on quitte le répertoire « /usr/src/linux-headers-4.19.0-16-amd64 »
make[1] : on quitte le répertoire « /opt/r8125/src »

*or I haven't done something else that was necessary.

It looks strange to me that the network driver isn't able to follow Linux upgrades, and it's boring, but I have to comply with this event.
I don't want to upgrade my Linux image up to a 5.10 image, but to stay using the current one Debian 10 suggests.

A: The RTL8125B support came with kernel 5.9. Debian 10 is using 4.19 in the stable channel.
You can update your kernel to 5.10 from debian-backports if that's ok for you like described e.g. here.
This is a very common problem with current distributions and this controller. The controller is used by many manufacturers on current boards with AMD-Sockets.
I hope that helps, I had to buy a USB-Ethernet-Adapter because when I bougth my board, 5.9 was not yet released by mainline :/
EDIT: To install the new kernel without Internet, you can download the following packages, transfer them via a usb-stick and install them with the command sudo dpkg -i *.deb && apt install -f and reboot. You should now be able to configure your network.

*

*linux-image-amd64 (download)

*linux-image-5.10.0-0.bpo.5-amd64 (download) (If this version is not available anymore in some future, this package is linked as a dependency from the meta-package above)

Another (maybe easier) way is to connect your mobile via usb and tether its WiFi/LTE-Connection for the kernel-update.

A: You know the story : you only have to post/edit your question, and a few minutes later, it works...
So I wrote here the only things I did but (this time) worked, to help who would stumble upon the same problem I've encountered:

*

*Go on the session where Ethernet connection is still available and
download the Git project https://github.com/tmacro/r8125 (for me, reseller put it in /opt), or put its content on an USB key.

*Boot on the no-working session (here the 4.19.0.17-amd64 for me) and execute:
cd /opt/r8125/
sudo ./autorun.sh

The image 4.19.0.17-amd64 is updated and network works immediately.
(epilogue: I think I was misled by my reseller who told me to do a make install from /opt/r8125 directory when it was a ./autorun.sh that had to be done? Maybe...)


text:
Q: swagger.json link not showing up in swagger page With my setup, I don't have a link on my swagger page to retrieve the swagger.json file. The swagger page appears, and I can see my API and make calls to it through the swagger page, but I have no swagger.json file link. In the image at the bottom has a link (not my page, someone else's). How can I change my setup to get this link to appear? The server is started by the line WebApp.Start<WebApi>(url); and below is my setup a
    public void Configuration(IAppBuilder app)
    {

        var config = new HttpConfiguration();
        config.EnableCors(new EnableCorsAttribute("*", "*", "*"));
        config.MapHttpAttributeRoutes();
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

        config.EnableSwagger(c =>
        {
            c.SingleApiVersion("v1", "stuff");
        })
            .EnableSwaggerUi(c =>
            {
                c.DocumentTitle("Swagger UI");
            });

        app.UseWebApi(config);

        app.UseCors(CorsOptions.AllowAll);
    }

Also screenshot of my UI (notice no link to swagger.json):

A: Swashbuckle for WebAPI uses an older Swagger UI version (2.x) which displays the API definition URL in the header - in your example it's http://localhost:34330/swagger/docs/v1.


text:
Q: why not working SQLiteOpenHelper in this codes my database class is :
public class Database extends SQLiteOpenHelper {
private static final int DB_VERSION = 1;
private static final String DB_NAME = "databse";

public static final String TABLE_SOURCES = "sources";
public static final String ID = "_id";
public static final String COL_TITLE = "title";
public static final String COL_URL = "url";
public static final String COL_UPDATE = "update";
public static final String COL_PERIOD = "period";

private static final String CREATE_TABLE_SOURCES = "CREATE TABLE "
        + TABLE_SOURCES + " (" + ID
        + " integer PRIMARY KEY AUTOINCREMENT, " + COL_TITLE
        + " text NOT NULL ); ";

private static final String DB_SCHEMA = CREATE_TABLE_SOURCES;

public Database(Context context) {
    super(context, DB_NAME, null, DB_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL(DB_SCHEMA);
    Log.d("create db", "create 2 db");
    seedData(db);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_SOURCES);
    onCreate(db);
}

/**
 * Create sample data to use
 *
 * @param db
 *            The open database
 */
private void seedData(SQLiteDatabase db) {
    db.execSQL("insert into sources (title) values ('new');");
    Log.d("insert to db", "insert to db 2 records");

}

// Getting contacts Count
public int getContactsCount() {
    String countQuery = "SELECT  * FROM " + TABLE_SOURCES;
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery(countQuery, null);
    cursor.close();

    // return count
    return cursor.getCount();
}

}
and i use it with :
private Database db = new Database(this);
Toast.makeText(getApplicationContext(), String.valueOf(db.getContactsCount()),
Toast.LENGTH_LONG).show();

but my app not work and unfortunately , myapp stopped.
what,s problems?
logcat :
09-19 06:08:29.090: I/Choreographer(1696): Skipped 55 frames!  The application may be doing too much work on its main thread.
09-19 06:08:41.649: E/Trace(1753): error opening trace file: No such file or directory (2)
09-19 06:08:42.389: I/Choreographer(1753): Skipped 118 frames!  The application may be doing too much work on its main thread.
09-19 06:08:42.450: D/gralloc_goldfish(1753): Emulator without GPU emulation detected.
09-19 06:08:42.570: I/Choreographer(1753): Skipped 70 frames!  The application may be doing too much work on its main thread.
09-19 06:08:44.290: D/AndroidRuntime(1753): Shutting down VM
09-19 06:08:44.290: W/dalvikvm(1753): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
09-19 06:08:44.321: E/AndroidRuntime(1753): FATAL EXCEPTION: main
09-19 06:08:44.321: E/AndroidRuntime(1753): android.database.sqlite.SQLiteException: Can't downgrade database from version 2 to 1
09-19 06:08:44.321: E/AndroidRuntime(1753):     at android.database.sqlite.SQLiteOpenHelper.onDowngrade(SQLiteOpenHelper.java:361)
09-19 06:08:44.321: E/AndroidRuntime(1753):     at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:255)
09-19 06:08:44.321: E/AndroidRuntime(1753):     at android.database.sqlite.SQLiteOpenHelper.getReadableDatabase(SQLiteOpenHelper.java:188)
09-19 06:08:44.321: E/AndroidRuntime(1753):     at com.ironfort.ironf.Database.getContactsCount(Database.java:66)
09-19 06:08:44.321: E/AndroidRuntime(1753):     at com.ironfort.ironf.Main$1.onClick(Main.java:28)
09-19 06:08:44.321: E/AndroidRuntime(1753):     at android.view.View.performClick(View.java:4204)
09-19 06:08:44.321: E/AndroidRuntime(1753):     at android.view.View$PerformClick.run(View.java:17355)
09-19 06:08:44.321: E/AndroidRuntime(1753):     at android.os.Handler.handleCallback(Handler.java:725)
09-19 06:08:44.321: E/AndroidRuntime(1753):     at android.os.Handler.dispatchMessage(Handler.java:92)
09-19 06:08:44.321: E/AndroidRuntime(1753):     at android.os.Looper.loop(Looper.java:137)
09-19 06:08:44.321: E/AndroidRuntime(1753):     at android.app.ActivityThread.main(ActivityThread.java:5041)
09-19 06:08:44.321: E/AndroidRuntime(1753):     at java.lang.reflect.Method.invokeNative(Native Method)
09-19 06:08:44.321: E/AndroidRuntime(1753):     at java.lang.reflect.Method.invoke(Method.java:511)
09-19 06:08:44.321: E/AndroidRuntime(1753):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
09-19 06:08:44.321: E/AndroidRuntime(1753):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
09-19 06:08:44.321: E/AndroidRuntime(1753):     at dalvik.system.NativeStart.main(Native Method)
09-19 06:08:51.490: E/Trace(1769): error opening trace file: No such file or directory (2)
09-19 06:15:07.089: E/Trace(1912): error opening trace file: No such file or directory (2)
09-19 06:15:07.770: I/Choreographer(1912): Skipped 98 frames!  The application may be doing too much work on its main thread.
09-19 06:15:07.839: D/gralloc_goldfish(1912): Emulator without GPU emulation detected.
09-19 06:15:07.980: I/Choreographer(1912): Skipped 90 frames!  The application may be doing too much work on its main thread.
09-19 06:16:38.419: D/AndroidRuntime(1912): Shutting down VM
09-19 06:16:38.419: W/dalvikvm(1912): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
09-19 06:16:38.449: E/AndroidRuntime(1912): FATAL EXCEPTION: main
09-19 06:16:38.449: E/AndroidRuntime(1912): android.database.sqlite.SQLiteException: Can't downgrade database from version 2 to 1
09-19 06:16:38.449: E/AndroidRuntime(1912):     at android.database.sqlite.SQLiteOpenHelper.onDowngrade(SQLiteOpenHelper.java:361)
09-19 06:16:38.449: E/AndroidRuntime(1912):     at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:255)
09-19 06:16:38.449: E/AndroidRuntime(1912):     at android.database.sqlite.SQLiteOpenHelper.getReadableDatabase(SQLiteOpenHelper.java:188)
09-19 06:16:38.449: E/AndroidRuntime(1912):     at com.ironfort.ironf.Database.getContactsCount(Database.java:66)
09-19 06:16:38.449: E/AndroidRuntime(1912):     at com.ironfort.ironf.Main$1.onClick(Main.java:28)
09-19 06:16:38.449: E/AndroidRuntime(1912):     at android.view.View.performClick(View.java:4204)
09-19 06:16:38.449: E/AndroidRuntime(1912):     at android.view.View$PerformClick.run(View.java:17355)
09-19 06:16:38.449: E/AndroidRuntime(1912):     at android.os.Handler.handleCallback(Handler.java:725)
09-19 06:16:38.449: E/AndroidRuntime(1912):     at android.os.Handler.dispatchMessage(Handler.java:92)
09-19 06:16:38.449: E/AndroidRuntime(1912):     at android.os.Looper.loop(Looper.java:137)
09-19 06:16:38.449: E/AndroidRuntime(1912):     at android.app.ActivityThread.main(ActivityThread.java:5041)
09-19 06:16:38.449: E/AndroidRuntime(1912):     at java.lang.reflect.Method.invokeNative(Native Method)
09-19 06:16:38.449: E/AndroidRuntime(1912):     at java.lang.reflect.Method.invoke(Method.java:511)
09-19 06:16:38.449: E/AndroidRuntime(1912):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
09-19 06:16:38.449: E/AndroidRuntime(1912):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
09-19 06:16:38.449: E/AndroidRuntime(1912):     at dalvik.system.NativeStart.main(Native Method)
09-19 06:16:38.770: D/dalvikvm(1912): GC_CONCURRENT freed 141K, 10% free 2610K/2892K, paused 71ms+35ms, total 264ms
09-19 06:16:46.289: E/Trace(1952): error opening trace file: No such file or directory (2)
09-19 06:17:06.619: E/Trace(2001): error opening trace file: No such file or directory (2)
09-19 06:17:07.460: I/Choreographer(2001): Skipped 106 frames!  The application may be doing too much work on its main thread.
09-19 06:17:07.520: D/gralloc_goldfish(2001): Emulator without GPU emulation detected.
09-19 06:17:07.660: I/Choreographer(2001): Skipped 79 frames!  The application may be doing too much work on its main thread.
09-19 06:18:21.050: I/Choreographer(2001): Skipped 92 frames!  The application may be doing too much work on its main thread.
09-19 06:18:21.160: D/AndroidRuntime(2001): Shutting down VM
09-19 06:18:21.160: W/dalvikvm(2001): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
09-19 06:18:21.179: E/AndroidRuntime(2001): FATAL EXCEPTION: main
09-19 06:18:21.179: E/AndroidRuntime(2001): android.database.sqlite.SQLiteException: Can't downgrade database from version 2 to 1
09-19 06:18:21.179: E/AndroidRuntime(2001):     at android.database.sqlite.SQLiteOpenHelper.onDowngrade(SQLiteOpenHelper.java:361)
09-19 06:18:21.179: E/AndroidRuntime(2001):     at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:255)
09-19 06:18:21.179: E/AndroidRuntime(2001):     at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:164)
09-19 06:18:21.179: E/AndroidRuntime(2001):     at com.ironfort.ironf.Database.getContactsCount(Database.java:66)
09-19 06:18:21.179: E/AndroidRuntime(2001):     at com.ironfort.ironf.Main$1.onClick(Main.java:28)
09-19 06:18:21.179: E/AndroidRuntime(2001):     at android.view.View.performClick(View.java:4204)
09-19 06:18:21.179: E/AndroidRuntime(2001):     at android.view.View$PerformClick.run(View.java:17355)
09-19 06:18:21.179: E/AndroidRuntime(2001):     at android.os.Handler.handleCallback(Handler.java:725)
09-19 06:18:21.179: E/AndroidRuntime(2001):     at android.os.Handler.dispatchMessage(Handler.java:92)
09-19 06:18:21.179: E/AndroidRuntime(2001):     at android.os.Looper.loop(Looper.java:137)
09-19 06:18:21.179: E/AndroidRuntime(2001):     at android.app.ActivityThread.main(ActivityThread.java:5041)
09-19 06:18:21.179: E/AndroidRuntime(2001):     at java.lang.reflect.Method.invokeNative(Native Method)
09-19 06:18:21.179: E/AndroidRuntime(2001):     at java.lang.reflect.Method.invoke(Method.java:511)
09-19 06:18:21.179: E/AndroidRuntime(2001):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
09-19 06:18:21.179: E/AndroidRuntime(2001):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
09-19 06:18:21.179: E/AndroidRuntime(2001):     at dalvik.system.NativeStart.main(Native Method)
09-19 06:18:21.439: D/dalvikvm(2001): GC_CONCURRENT freed 149K, 10% free 2610K/2900K, paused 72ms+14ms, total 218ms
09-19 06:18:28.510: E/Trace(2037): error opening trace file: No such file or directory (2)
09-19 06:21:48.310: E/Trace(2135): error opening trace file: No such file or directory (2)
09-19 06:21:49.101: I/Choreographer(2135): Skipped 127 frames!  The application may be doing too much work on its main thread.
09-19 06:21:49.130: D/gralloc_goldfish(2135): Emulator without GPU emulation detected.
09-19 06:21:49.270: I/Choreographer(2135): Skipped 81 frames!  The application may be doing too much work on its main thread.
09-19 06:22:00.459: D/AndroidRuntime(2135): Shutting down VM
09-19 06:22:00.459: W/dalvikvm(2135): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
09-19 06:22:00.480: E/AndroidRuntime(2135): FATAL EXCEPTION: main
09-19 06:22:00.480: E/AndroidRuntime(2135): android.database.sqlite.SQLiteException: Can't downgrade database from version 2 to 1
09-19 06:22:00.480: E/AndroidRuntime(2135):     at android.database.sqlite.SQLiteOpenHelper.onDowngrade(SQLiteOpenHelper.java:361)
09-19 06:22:00.480: E/AndroidRuntime(2135):     at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:255)
09-19 06:22:00.480: E/AndroidRuntime(2135):     at android.database.sqlite.SQLiteOpenHelper.getReadableDatabase(SQLiteOpenHelper.java:188)
09-19 06:22:00.480: E/AndroidRuntime(2135):     at com.ironfort.ironf.Database.getContactsCount(Database.java:66)
09-19 06:22:00.480: E/AndroidRuntime(2135):     at com.ironfort.ironf.Main$1.onClick(Main.java:28)
09-19 06:22:00.480: E/AndroidRuntime(2135):     at android.view.View.performClick(View.java:4204)
09-19 06:22:00.480: E/AndroidRuntime(2135):     at android.view.View$PerformClick.run(View.java:17355)
09-19 06:22:00.480: E/AndroidRuntime(2135):     at android.os.Handler.handleCallback(Handler.java:725)
09-19 06:22:00.480: E/AndroidRuntime(2135):     at android.os.Handler.dispatchMessage(Handler.java:92)
09-19 06:22:00.480: E/AndroidRuntime(2135):     at android.os.Looper.loop(Looper.java:137)
09-19 06:22:00.480: E/AndroidRuntime(2135):     at android.app.ActivityThread.main(ActivityThread.java:5041)
09-19 06:22:00.480: E/AndroidRuntime(2135):     at java.lang.reflect.Method.invokeNative(Native Method)
09-19 06:22:00.480: E/AndroidRuntime(2135):     at java.lang.reflect.Method.invoke(Method.java:511)
09-19 06:22:00.480: E/AndroidRuntime(2135):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
09-19 06:22:00.480: E/AndroidRuntime(2135):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
09-19 06:22:00.480: E/AndroidRuntime(2135):     at dalvik.system.NativeStart.main(Native Method)
09-19 06:22:00.689: D/dalvikvm(2135): GC_CONCURRENT freed 155K, 11% free 2610K/2904K, paused 71ms+4ms, total 192ms
09-19 06:22:07.649: E/Trace(2154): error opening trace file: No such file or directory (2)
09-19 06:28:21.729: E/Trace(2294): error opening trace file: No such file or directory (2)
09-19 06:28:22.429: I/Choreographer(2294): Skipped 100 frames!  The application may be doing too much work on its main thread.
09-19 06:28:22.450: D/gralloc_goldfish(2294): Emulator without GPU emulation detected.
09-19 06:28:22.599: I/Choreographer(2294): Skipped 68 frames!  The application may be doing too much work on its main thread.
09-19 06:28:25.000: I/Choreographer(2294): Skipped 97 frames!  The application may be doing too much work on its main thread.
09-19 06:28:25.160: D/AndroidRuntime(2294): Shutting down VM
09-19 06:28:25.160: W/dalvikvm(2294): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
09-19 06:28:25.279: E/AndroidRuntime(2294): FATAL EXCEPTION: main
09-19 06:28:25.279: E/AndroidRuntime(2294): android.database.sqlite.SQLiteException: Can't downgrade database from version 2 to 1
09-19 06:28:25.279: E/AndroidRuntime(2294):     at android.database.sqlite.SQLiteOpenHelper.onDowngrade(SQLiteOpenHelper.java:361)
09-19 06:28:25.279: E/AndroidRuntime(2294):     at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:255)
09-19 06:28:25.279: E/AndroidRuntime(2294):     at android.database.sqlite.SQLiteOpenHelper.getReadableDatabase(SQLiteOpenHelper.java:188)
09-19 06:28:25.279: E/AndroidRuntime(2294):     at com.ironfort.ironf.Database.getContactsCount(Database.java:66)
09-19 06:28:25.279: E/AndroidRuntime(2294):     at com.ironfort.ironf.Main$1.onClick(Main.java:28)
09-19 06:28:25.279: E/AndroidRuntime(2294):     at android.view.View.performClick(View.java:4204)
09-19 06:28:25.279: E/AndroidRuntime(2294):     at android.view.View$PerformClick.run(View.java:17355)
09-19 06:28:25.279: E/AndroidRuntime(2294):     at android.os.Handler.handleCallback(Handler.java:725)
09-19 06:28:25.279: E/AndroidRuntime(2294):     at android.os.Handler.dispatchMessage(Handler.java:92)
09-19 06:28:25.279: E/AndroidRuntime(2294):     at android.os.Looper.loop(Looper.java:137)
09-19 06:28:25.279: E/AndroidRuntime(2294):     at android.app.ActivityThread.main(ActivityThread.java:5041)
09-19 06:28:25.279: E/AndroidRuntime(2294):     at java.lang.reflect.Method.invokeNative(Native Method)
09-19 06:28:25.279: E/AndroidRuntime(2294):     at java.lang.reflect.Method.invoke(Method.java:511)
09-19 06:28:25.279: E/AndroidRuntime(2294):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
09-19 06:28:25.279: E/AndroidRuntime(2294):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
09-19 06:28:25.279: E/AndroidRuntime(2294):     at dalvik.system.NativeStart.main(Native Method)
09-19 06:28:25.460: D/dalvikvm(2294): GC_CONCURRENT freed 162K, 11% free 2611K/2912K, paused 71ms+5ms, total 269ms
09-19 06:28:34.670: E/Trace(2314): error opening trace file: No such file or directory (2)
09-19 06:32:06.010: I/Choreographer(2314): Skipped 121 frames!  The application may be doing too much work on its main thread.
09-19 06:32:06.060: D/gralloc_goldfish(2314): Emulator without GPU emulation detected.
09-19 06:32:06.209: I/Choreographer(2314): Skipped 65 frames!  The application may be doing too much work on its main thread.
09-19 06:32:07.141: I/Choreographer(2314): Skipped 92 frames!  The application may be doing too much work on its main thread.
09-19 06:32:07.250: D/AndroidRuntime(2314): Shutting down VM
09-19 06:32:07.250: W/dalvikvm(2314): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
09-19 06:32:07.369: E/AndroidRuntime(2314): FATAL EXCEPTION: main
09-19 06:32:07.369: E/AndroidRuntime(2314): android.database.sqlite.SQLiteException: Can't downgrade database from version 2 to 1
09-19 06:32:07.369: E/AndroidRuntime(2314):     at android.database.sqlite.SQLiteOpenHelper.onDowngrade(SQLiteOpenHelper.java:361)
09-19 06:32:07.369: E/AndroidRuntime(2314):     at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:255)
09-19 06:32:07.369: E/AndroidRuntime(2314):     at android.database.sqlite.SQLiteOpenHelper.getReadableDatabase(SQLiteOpenHelper.java:188)
09-19 06:32:07.369: E/AndroidRuntime(2314):     at com.ironfort.ironf.Database.getContactsCount(Database.java:66)
09-19 06:32:07.369: E/AndroidRuntime(2314):     at com.ironfort.ironf.Main$1.onClick(Main.java:28)
09-19 06:32:07.369: E/AndroidRuntime(2314):     at android.view.View.performClick(View.java:4204)
09-19 06:32:07.369: E/AndroidRuntime(2314):     at android.view.View$PerformClick.run(View.java:17355)
09-19 06:32:07.369: E/AndroidRuntime(2314):     at android.os.Handler.handleCallback(Handler.java:725)
09-19 06:32:07.369: E/AndroidRuntime(2314):     at android.os.Handler.dispatchMessage(Handler.java:92)
09-19 06:32:07.369: E/AndroidRuntime(2314):     at android.os.Looper.loop(Looper.java:137)
09-19 06:32:07.369: E/AndroidRuntime(2314):     at android.app.ActivityThread.main(ActivityThread.java:5041)
09-19 06:32:07.369: E/AndroidRuntime(2314):     at java.lang.reflect.Method.invokeNative(Native Method)
09-19 06:32:07.369: E/AndroidRuntime(2314):     at java.lang.reflect.Method.invoke(Method.java:511)
09-19 06:32:07.369: E/AndroidRuntime(2314):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
09-19 06:32:07.369: E/AndroidRuntime(2314):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
09-19 06:32:07.369: E/AndroidRuntime(2314):     at dalvik.system.NativeStart.main(Native Method)
09-19 06:32:07.550: D/dalvikvm(2314): GC_CONCURRENT freed 166K, 11% free 2612K/2920K, paused 71ms+35ms, total 271ms
09-19 06:36:32.140: I/Process(2314): Sending signal. PID: 2314 SIG: 9
09-19 06:44:35.450: I/Choreographer(2621): Skipped 203 frames!  The application may be doing too much work on its main thread.
09-19 06:44:35.499: D/gralloc_goldfish(2621): Emulator without GPU emulation detected.
09-19 06:44:35.619: I/Choreographer(2621): Skipped 70 frames!  The application may be doing too much work on its main thread.
09-19 06:44:43.749: D/AndroidRuntime(2621): Shutting down VM
09-19 06:44:43.749: W/dalvikvm(2621): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
09-19 06:44:43.780: E/AndroidRuntime(2621): FATAL EXCEPTION: main
09-19 06:44:43.780: E/AndroidRuntime(2621): android.database.sqlite.SQLiteException: Can't downgrade database from version 2 to 1
09-19 06:44:43.780: E/AndroidRuntime(2621):     at android.database.sqlite.SQLiteOpenHelper.onDowngrade(SQLiteOpenHelper.java:361)
09-19 06:44:43.780: E/AndroidRuntime(2621):     at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:255)
09-19 06:44:43.780: E/AndroidRuntime(2621):     at android.database.sqlite.SQLiteOpenHelper.getReadableDatabase(SQLiteOpenHelper.java:188)
09-19 06:44:43.780: E/AndroidRuntime(2621):     at com.ironfort.ironf.Database.getContactsCount(Database.java:66)
09-19 06:44:43.780: E/AndroidRuntime(2621):     at com.ironfort.ironf.Main$1.onClick(Main.java:28)
09-19 06:44:43.780: E/AndroidRuntime(2621):     at android.view.View.performClick(View.java:4204)
09-19 06:44:43.780: E/AndroidRuntime(2621):     at android.view.View$PerformClick.run(View.java:17355)
09-19 06:44:43.780: E/AndroidRuntime(2621):     at android.os.Handler.handleCallback(Handler.java:725)
09-19 06:44:43.780: E/AndroidRuntime(2621):     at android.os.Handler.dispatchMessage(Handler.java:92)
09-19 06:44:43.780: E/AndroidRuntime(2621):     at android.os.Looper.loop(Looper.java:137)
09-19 06:44:43.780: E/AndroidRuntime(2621):     at android.app.ActivityThread.main(ActivityThread.java:5041)
09-19 06:44:43.780: E/AndroidRuntime(2621):     at java.lang.reflect.Method.invokeNative(Native Method)
09-19 06:44:43.780: E/AndroidRuntime(2621):     at java.lang.reflect.Method.invoke(Method.java:511)
09-19 06:44:43.780: E/AndroidRuntime(2621):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
09-19 06:44:43.780: E/AndroidRuntime(2621):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
09-19 06:44:43.780: E/AndroidRuntime(2621):     at dalvik.system.NativeStart.main(Native Method)
09-19 06:44:45.720: I/Process(2621): Sending signal. PID: 2621 SIG: 9
09-19 06:44:51.060: E/Trace(2639): error opening trace file: No such file or directory (2)
09-19 06:46:14.880: I/Choreographer(2639): Skipped 205 frames!  The application may be doing too much work on its main thread.
09-19 06:46:14.939: D/gralloc_goldfish(2639): Emulator without GPU emulation detected.
09-19 06:46:15.069: I/Choreographer(2639): Skipped 65 frames!  The application may be doing too much work on its main thread.
09-19 06:46:16.525: I/Choreographer(2639): Skipped 87 frames!  The application may be doing too much work on its main thread.
09-19 06:46:16.630: D/AndroidRuntime(2639): Shutting down VM
09-19 06:46:16.630: W/dalvikvm(2639): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
09-19 06:46:16.649: E/AndroidRuntime(2639): FATAL EXCEPTION: main
09-19 06:46:16.649: E/AndroidRuntime(2639): android.database.sqlite.SQLiteException: Can't downgrade database from version 2 to 1
09-19 06:46:16.649: E/AndroidRuntime(2639):     at android.database.sqlite.SQLiteOpenHelper.onDowngrade(SQLiteOpenHelper.java:361)
09-19 06:46:16.649: E/AndroidRuntime(2639):     at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:255)
09-19 06:46:16.649: E/AndroidRuntime(2639):     at android.database.sqlite.SQLiteOpenHelper.getReadableDatabase(SQLiteOpenHelper.java:188)
09-19 06:46:16.649: E/AndroidRuntime(2639):     at com.ironfort.ironf.Database.getContactsCount(Database.java:66)
09-19 06:46:16.649: E/AndroidRuntime(2639):     at com.ironfort.ironf.Main$1.onClick(Main.java:28)
09-19 06:46:16.649: E/AndroidRuntime(2639):     at android.view.View.performClick(View.java:4204)
09-19 06:46:16.649: E/AndroidRuntime(2639):     at android.view.View$PerformClick.run(View.java:17355)
09-19 06:46:16.649: E/AndroidRuntime(2639):     at android.os.Handler.handleCallback(Handler.java:725)
09-19 06:46:16.649: E/AndroidRuntime(2639):     at android.os.Handler.dispatchMessage(Handler.java:92)
09-19 06:46:16.649: E/AndroidRuntime(2639):     at android.os.Looper.loop(Looper.java:137)
09-19 06:46:16.649: E/AndroidRuntime(2639):     at android.app.ActivityThread.main(ActivityThread.java:5041)
09-19 06:46:16.649: E/AndroidRuntime(2639):     at java.lang.reflect.Method.invokeNative(Native Method)
09-19 06:46:16.649: E/AndroidRuntime(2639):     at java.lang.reflect.Method.invoke(Method.java:511)
09-19 06:46:16.649: E/AndroidRuntime(2639):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
09-19 06:46:16.649: E/AndroidRuntime(2639):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
09-19 06:46:16.649: E/AndroidRuntime(2639):     at dalvik.system.NativeStart.main(Native Method)

A: Try this way
private static final int DB_VERSION = 2; UPDATE HERE

public int getContactsCount() {
    String countQuery = "SELECT  * FROM " + TABLE_SOURCES;
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery(countQuery, null);
    int count = cursor.getCount();
    cursor.close();

    // return count
    return count;
}

private Database db = new Database(this);
Toast.makeText(this, String.valueOf(db.getContactsCount()),
Toast.LENGTH_LONG).show();


text:
Q: How to get cell coordinates when iterating in PHPSpreadsheet? I'm trying to populate and colour some headers in PHPSpreadsheet. The number of columns can be variable. It is recommended in the docs to style cells as a range so I need to know the coordinates of the last cell to do this.
I've tried using getCellByColumnAndRow as I iterate through the columns but this returns the value of the cell instead of the coordinates:
$i = 1;
$lastCellValue = null;

foreach ($headers as $header) {
    $sheet->setCellValueByColumnAndRow($i, 1, $header);
    $lastCellValue = $sheet->getCellByColumnAndRow($i, 1);
    $i++;
}

$spreadsheet->getActiveSheet()->getStyle('A1:'.$lastCellValue)->getFill()
    ->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)
    ->getStartColor()->setARGB('FFFF0000');

How can I get the coordinates of the last cell when iterating?

A: getCellByColumnAndRow() doesn't return the cell value, it returns the cell object.... and that cell object has a number of methods including getColumn(), getRow() and getCoordinate()
So
foreach ($headers as $header) {
    $sheet->setCellValueByColumnAndRow($i, 1, $header);
    $lastCellAddress = $sheet->getCellByColumnAndRow($i, 1)->getCoordinate();
    $i++;
}

$spreadsheet->getActiveSheet()->getStyle('A1:'.$lastCellAddress)->getFill()
    ->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)
    ->getStartColor()->setARGB('FFFF0000');

A: To retrieve the cell value, you can use this :
$sheet->getCellByColumnAndRow($intColumn, $intRow)->getParent()->getCurrentCoordinate();

In your case, you should try :
enter$lastCellValue = $sheet->getCellByColumnAndRow($i, 1)->getParent()->getCurrentCoordinate();


text:
Q: How to get HP ASM to work under Xen Hypervisor? I have a HP DL560, currently running Debian Squeeze as dom0 on Xen Hypervisor, and the fans constantly run at 100%. In the past this wasn't a problem because I could install HP's ASM which includes fan management. However since I have installed a xen enabled kernel, the hp-health driver (the piece of ASM that controls the fans) won't start (at boot or manually). Anyone know of any way to make it work? (Or any other method of controlling the fans safely.)
Note that the server has four i386 Xeon CPUs, each with its own fan, plus an extra case fan, and all of the fans can be doubled for redundancy. Also everything works fine under Squeeze without the xen-enabled kernel (can still boot the other one and hp-health loads fine on boot).

A: Scary... I own an HP ProLiant DL560 G1. It's sitting somewhere. It's very old gear... 2U, 4-socket Pentium 4-era server with two drive bays :) Mine dates back to 2004.
Either way, its fans do respond to the HP health drivers. You mention hpasm. That's an old health driver model. For the past few years, the HP drivers have been packaged as hp-snmp-agents. Try downloading the HP Debian/dpkg driver bundle.
The goal here is that the drivers will compile against your running kernel. The fact that you're on a Xen-enabled kernel should not matter.

A: It seems that it despite their name change, installing hpasm (from HP's repository) actually installs hp-snmp-agents 8.7.0 (which is what is contained in the ISO on the link you sent). As a result it appears that the xen kernel does seem to have an impact on the driver...
The output of /etc/init.d/hp-health start:
root@dom0:~# /etc/init.d/hp-health start
 Starting Proliant System Health Monitor (hpasmd):
            [ SUCCESS ]

root@dom0:~#
Message from syslogd@dom0 at Nov 20 21:41:58 ...
 kernel:[ 1572.521828] general protection fault: 0000 [#3] SMP

Message from syslogd@dom0 at Nov 20 21:41:58 ...
 kernel:[ 1572.522086] last sysfs file: /sys/devices/pci0000:03/0000:03:01.2/class

Message from syslogd@dom0 at Nov 20 21:41:58 ...
 kernel:[ 1572.525785] Process hpasmd (pid: 5981, ti=ec11a000 task=c1ce0880 task.ti=ec11a000)

Message from syslogd@dom0 at Nov 20 21:41:58 ...
 kernel:[ 1572.525785] Stack:

Message from syslogd@dom0 at Nov 20 21:41:58 ...
 kernel:[ 1572.525785] Call Trace:

Message from syslogd@dom0 at Nov 20 21:41:58 ...
 kernel:[ 1572.525785] Code: 00 8d 76 00 f7 44 24 08 00 00 02 80 75 33 50 b8 00 e0 ff ff 21 e0 8b 40 10 8b 04 85 d0 c2 3f c1 8b 80 0c b0 45 c1 f6 44 24 0d 02 <0f> 94 40 01 66 83 38 01 75 04 c6 40 01 01 58 0f 84 44 33 00 00

Message from syslogd@dom0 at Nov 20 21:41:58 ...
 kernel:[ 1572.525785] EIP: [<c10067bf>] xen_iret+0x27/0x2b SS:ESP 0069:ec11bfe0

Followed by hpasmcli:
root@dom0:~# hpasmcli

ERROR: Could not open /dev/cpqhealth/cdt.
Please make sure the Health Monitor is started.

(This should probably be a comment, but I am not allowed to post comments.)


text:
Q: RESTful Laravel API login from application in other domain How to config Laravel 5.0 to login from other domain? Explain, we have a Laravel RESTful API, and some users creates Angular.js apps and host on your own domains.
When try to login through these apps, login returns true, but on next request lose the session.
I think that can be related to CORS, but I set the correct headers.
My Headers:
Hearders setted on apache virtualhost:
Header always set Access-Control-Allow-Origin "*"
Header always set Access-Control-Allow-Methods "POST, GET, OPTIONS, PUT, PATCH, DELETE"
Header always add Access-Control-Allow-Headers "accept, origin, x-requested-with, content-type, x-application-token, x-csrf-token, x-password-reset-token"
Header always add Access-Control-Expose-Headers "x-csrf-token"

A: Setting CORS is only a small step in making this work.  Please give this article a read
The problem you are experiencing is subsequent requests from your other domains aren't sending any kind of token or identifier that laravel can use to decide what user is making the request.  You should look into using a JWT library.
laravel-jwt is pretty solid for accomplishing this.  Simply adding CORS into your app won't be enough for it to work properly.
Laravel needs to know what user is making the request and the above library comes with middleware and methods to easily accomplish this.
From a high level, some of the steps that will need to occur are:
1) Setting up your angular login controller/service
    $scope.login = function () {

        // Send The Login Request
        UserService.authenticate($scope.formData)
            .$promise.then(function(data) {

                // If Successfully Authed
                if (data.success && data.hasOwnProperty('token')) {

                    // Set Cookies
                    UserService.setCurrentUser(data.user);
                    UserService.setUserToken(data.token);

                    // Fire Login Event
                    return authService.loginConfirmed(data);

                } else {
                    // Else Errors Logging In
                    AlertService.addAlert(data.error, 'danger');
                }
            });
        };

2) Handling the auth with laravel-jwt:
public function authenticate()
{
    $credentials = $this->request->only('username', 'password');

    try {
        // Verify Credentials & Create Token for User
        if (! $token = $this->auth->attempt($credentials)) {
            return response()->json(['success' => false, 'error' => 'Invalid Credentials.'], 401);
        }
    } catch(JWTException $e) {
        // Something went wrong encoding the token.
        return response()->json(['success' => false, 'error' => 'Could not create token.'], 401);
    }

    return response()->json(['success' => true, 'user' => $user->toArray());

}

3) Adding an angular interceptor to add the authorization header for subsequent requests:
 //...your interceptor
 return {
    'request': function (config) {

        // Get Current JWT
        var cookieToken = $cookieStore.get('currentToken');

        // If Authed, Tack on Auth Token
        if (cookieToken) {
            config.headers['Authorization'] = 'Bearer: ' + cookieToken;
        }

        return config || $q.when(config);
    }
}
//...remainder of interceptor

4) Adding middleware to verify users by token
public function handle($request, \Closure $next)
{
    if (! $token = $this->auth->setRequest($request)->getToken()) {
        return $this->respond('tymon.jwt.absent', 'token_not_provided', 400);
    }

    try {
        $user = $this->auth->authenticate($token);
    } catch (TokenExpiredException $e) {
        return $this->respond('tymon.jwt.expired', 'token_expired', $e->getStatusCode(), [$e]);
    } catch (JWTException $e) {
        return $this->respond('tymon.jwt.invalid', 'token_invalid', $e->getStatusCode(), [$e]);
    }

    if (! $user) {
        return $this->respond('tymon.jwt.user_not_found', 'user_not_found', 404);
    }

    return $next($request);
}

important to note that this code will not work for you as is, and was simply meant to show you what an implementation might look like
The full working implementation of this is way outside of a stackoverflow answer and I suggest reading into this elsewhere online.
If both sites are Laravel applications then you may needs just adjust the cookie domain in your config.


text:
Q: TypeError: __init__() takes from 1 to 2 positional arguments but 3 were given I'm learning Flask and i can't make my form working. The form should get the name of user and print it on the same page
Form:
class LoginForm(FlaskForm):
    name = StringField(
        'What is your name?',
        validators=[Length(min = 4, max = 25), Required])
    submit = SubmitField('Submit')

Views:
@app.route('/login/', methods=['GET','POST'])
def login():
    name = None
    formi = LoginForm()
    if formi.validate_on_submit():
        name = formi.name.data
        formi.name.data = ''
    return render_template('LoginForm.html', formi = formi, name = name)

Template:
<form action="" method="post" name="login">
{{ formi.hidden_tag() }}

Enter your nickname

{{ formi.name(size=25) }}
<input type="submit" value="Submit form">
</form>

Error:
TypeError: __init__() takes from 1 to 2 positional arguments but 3 were given

A: Please check the if the spelling is right > " formi"
@app.route('/login/', methods=['GET','POST'])
def login():
    name = None
    **formi** = LoginForm()
    if formi.validate_on_submit():
        name = formi.name.data
        formi.name.data = ''
    return render_template('LoginForm.html', formi = formi, name = name)


text:
Q: Google Test and Visual Studio 2010 RC Has anyone tried to build gtest 1.4.0 under VS 2010 RC?
I get about 400 errors when I try to build it.
Thanks in advance.

A: it fails on its own tr1::tuple implementation - adding GTEST_USE_OWN_TR1_TUPLE=0 to my preprocessor defines fixed the problem for me (bugtracker issue).


text:
Q: Ruby: Solution to mark modifications on associated objects when something on it changes I'm working on this requirement: I have an object-relational model quite big, where entities are very strongly linked. Let us use, as example, this relationship: a building has many apartments, an apartment has many divisions. Now, what I want: when something changes on any division, I want to "inform" the building, or better, mark the building has being "updated" or "modified".

*

*Current solution: we have a self-written implementation in which we would mark division as "affecting" building, and building's "modified" timestamp would be updated each time a division would be updated.

*Desired solution: an already existing "out-of-the-box" implementation (a gem, a plugin, God, perhaps) which would spare us the work of refactoring our implementation.

*Unwanted solution: please, don't tell me to mark all these associations with :autosave => true. I would like a solution which is queueable.
Solutions which do not comprise the desired solution but are either suggestions to improve the performance of the current solution are of course welcome as well. In lack of a desired solution we will most definitely improve on the existing one.
A small edit:
This behaviour has to be generic. It's not only for buildings cases, but any model with associations can have this behaviour. Which will always be the same: fetch affected associations and update them. Now, I don't want to write different observers with the same routine.
On the performance issue: Updated affected association updates must also trigger its affected associations. Now, let's imagine 1 building affects 100 divisions, and each division affects 100 chairs. Now, the observer solution works only on the business level. That is, I have to instantiate every AR instance so that the observers can act. Which I hold as bad performance. If A affects 100 Bs, I do it with one DB statement. But how can the observers for these 100 be triggered when I do it all with SQL?
So, back to the main update points: this behaviour is generic, and most importantly, the performance has to be top (associations may trigger nxn updates for has_many associations, for instance).

A: You can use observer. Create file with name say audit_observer.rb in app/models
class AuditObserver < ActiveRecord::Observer
  observe :division

  def after_update(division)
    division.logger.info('Division is updated at #{division.updated_at}')
    ######Your logic goes here
  end
end

A: So, the way I solve it was a mixture of the various suggestions concerning observer design pattern implementations. So, to start, none of the base implementations of the pattern work for me. Why? I wanted to have the concept of a model A observing its relation B, B being observed by its relation A, and the routine of this observation being defined somewhere else, in a (lets call it that) notifier.
Why couldn't I use Ruby 'observer' library? In theory I could have achieved that, but the observed objects call a method called "changed" to notify its observers, and "changed" is a method which is overwritten by ActiveRecord, namely by the "dirty" library.
Why couldn't I use AR 'observers'? Because here the observer is what I want the notifier to be. The routine is not implemented in the model, but i couldn't say which other AR models have to be notified. This was an hinderance.
How did I solve it? I created a library myself, using the ActiveModel::Observing library, which allowed me to implement the functionality I wanted. I designed to I would have this DSL:
class A < ActiveRecord
     has_one :b
 observes :b, :on => :create, :notifiers => :update_observer

end
So this means, when b gets created, there is a notifier update_observer which can reach b and a and do something with it. so, in this case:
class UpdateObserverNotifier < Notifier

  def action(observable, observer)
    observer.update_attributes(updated_at: observable.updated_at)
  end
end

the DSL call on the observer will inject 'observer' and 'observable' behaviour in the respective classes. The Notifier base class will have notification behaviour, and it will have access to both the observable and the observer object, in case something from the observable has to be mirrored in the observer. And if your action triggers callbacks on the observer, it will also notify potential observers of the observer itself.
Yup, so this was it. Thanks for the suggestions, otherwise I wouldn't have achieved it.


text:
Q: ArtifactDeployer plugin -remote access denied (Linux to Windows) I am trying to use the ArtifactDeployer plugin to copy the artifacts from WORKSPACE/jobs/ directory into a remote directory on the windows 7 machine .The Jenkins machine OS is linux
However Jenkins never manages to succeed. Throwing errors like:
[ArtifactDeployer] - Starting deployment from the post-action ... [ArtifactDeployer] - [ERROR] - Failed to deploy. Can't create the directory ... Build step [ArtifactDeployer] - Deploy artifacts from workspace to remote directories' changed build result to FAILURE

I am not sure how to use the Remote Directory parameter.
Please check the sample code for how I am trying to specify the remote directory
remote Directory - \ip address of that machine\users\public
Is it possible to copy the artifacts which is on linux machine to windows 7 machine?
Please let me know how to specify the remote directory.

A: Reading the Plugin page doesn't seem to be very helpful when it comes to configuring it. The text seem to hint that you need to have local access (from the node where the job is running) to the (remote) folder you want to deploy too. For a first test, use a local directory (on your Linux box) to see if you get it to work. Second, the correct way to address a windows share is \\servername\sharename\subdirs. Remember that you might need to login to the share.
You might need to install samba or cifs to connect to the windows share from your linux system. There is also a setting in Windows that determines whether your windows box will accept connections to aliases. If that is not the case, you need to use the hostname in order to access the share. So IP and any alias for the server will not work then.
e.g
  hostname: RTS3524
  alias: JENKINSREPO
  ip: 192.168.15.33
  share: temp

For the example above, only \\RTS3524\temp will work but \\192.168.15.33 will not.


text:
Q: prevent jquery mobile from styling element I've got a checkbox that I want hidden on the page.  My obvious first attempt was the following:
<input type='checkbox' style='display:none' />

However, I noticed jquery mobile automagically wraps the checkbox in a div that looks like this:
<div class='ui-checkbox'>
  <input type='checkbox' style='display:none;' />
</div>

I would assume that there's some kind of data- element that would prevent this additional styling, but haven't found it in the docs or elsewhere.  It's easy enough to override the .ui-checkbox in css to hide it as well, but would prefer a more jquery mobile-standard approach.  Does such a thing exist?

A: For future users.
Just in case you want to disable for every form element or your forms are loading dynamically where you cannot edit markup  use this.
        $(document).on('pagebeforecreate', function( e ) {
            $( "input, textarea, select", e.target ).attr( "data-role", "none" );
        });

A: The attribute that prevents styling is data-role="none"
<input type='checkbox' style='display:none' data-role="none" />

See the Jquery doc: "Preventing auto-initialization of form elements"

A: I have too many places to change inputs and add data-role="none"
The following code works for me:
 <script>
        $(document).bind('mobileinit',function(){
            $.mobile.page.prototype.options.keepNative = "select,input";
        });
    </script>
    <script src="http://code.jquery.com/mobile/1.4.2/jquery.mobile-1.4.2.min.js"></script>


text:
Q: Search for model with multiple properties (where properties are in a key => value table) I have a model called Document, and a has_many relation with DocumentProperty.
DocumentProperty has a id, document_id, key, and value columns.
I'm trying to come up with a query that will let me search for a document with two or more key => value pairs, e.g a document with size = A4 and pages = 2, but I can't find a way to do that without writing all of the SQL myself (currently using an ActiveRecord::Relation).
Example table data:
| document_id | key    | value   |
+-------------+--------+---------+
| 1           | size   | A4      |
| 1           | pages  | 2       |
| 2           | size   | A4      |
| 2           | pages  | 3       |
| 3           | size   | A4      |
| 3           | pages  | 2       |
| 3           | author | Brandon |

With my search, document 1 and 3 should be returned.
Does Rails support this?

A: Yep, ActiveRecord supports such queries:
Document.joins(:document_properties)
        .where("document_properties.key = 'size' AND document_properties.value = 'A4' OR document_properties.key = 'pages' AND document_properties.value = 2")
        .group('documents.id')

A: I have build the models in rails. Try this, computed document_ids first,
2.2.3 :002 > document_ids = DocumentProperty.where(key: 'size', value: 'A4').pluck('document_id') & DocumentProperty.where(key: 'pages', value: '2').pluck('document_id')
   (0.3ms)  SELECT `document_properties`.`document_id` FROM `document_properties` WHERE `document_properties`.`key` = 'size' AND `document_properties`.`value` = 'A4'
   (0.3ms)  SELECT `document_properties`.`document_id` FROM `document_properties` WHERE `document_properties`.`key` = 'pages' AND `document_properties`.`value` = '2'
 => [1, 3]
2.2.3 :003 > Document.where(id: document_ids)
  Document Load (1.1ms)  SELECT `documents`.* FROM `documents` WHERE `documents`.`id` IN (1, 3)
 => #<ActiveRecord::Relation [#<Document id: 1, name: "first", created_at: "2016-11-02 14:07:38", updated_at: "2016-11-02 14:07:38">, #<Document id: 3, name: "three", created_at: "2016-11-02 14:07:38", updated_at: "2016-11-02 14:07:38">]>
2.2.3 :004 >