问:
RecyclerAdapter IndexOutOfBoundError on using CustomViewHolder
What i'm trying to do is that, I have an adapter which I'm using for many different activities each having their own ViewHolder. So I'm firstly making an abstract recycler adapter named DimRecyclerAbstractAdapter without a ViewHolder. Then for each different activity I'm making a static inner class named DimCustomAdapter which extends DimRecyclerAbstractAdapter having it's own ViewHolder. But I'm getting this error.

```<code>java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
                                                                                at java.util.ArrayList.get(ArrayList.java:411)
</code>```

This is the abstract adapter class  -

```<code>public abstract class DimRecyclerAbstractAdapter<VHA extends RecyclerView.ViewHolder> extends RecyclerView.Adapter<VHA> {

    private List<tbl_dim_1> mtbldimList1;

    public DimRecyclerAbstractAdapter(List<tbl_dim_1> tblDimList1) {
        this.mtbldimList1 = tblDimList1;
    }

    @Override
    public int getItemCount() {
            return mtbldimList1.size();
    }

    public void addItems(List<tbl_dim_1> tblDimList1) {

        this.mtbldimList1 = tblDimList1;
        notifyDataSetChanged();
    }

    @Override
    public void onDetachedFromRecyclerView(RecyclerView recyclerView) {
        mtbldimList1 = null;
        super.onDetachedFromRecyclerView(recyclerView);
    }

}
</code>```

This is the activity in which I've implemented custom ViewHolder -

```<code>public class DetailActivity1 extends LifecycleActivity{

    DimListViewModel dmvmodel;
    RecyclerView rcView;
    DimCustomAdapter rcAdapter;
    public static final String LOG_TAG = "In DetailActivity1 ";

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

        Intent receivedIntent = getIntent();
        int rid_int = receivedIntent.getIntExtra("mRId",0);
        Log.v(LOG_TAG,"Rid value int == " + rid_int);

        rcView = (RecyclerView) findViewById(R.id.recyclerView);

        rcAdapter = new DimCustomAdapter(new ArrayList<tbl_dim_1>());
        rcView.setLayoutManager(new LinearLayoutManager(DetailActivity1.this));
        Log.v(LOG_TAG, "Layout manager set");
        rcView.setAdapter(rcAdapter);

        dmvmodel = ViewModelProviders.of(this).get(DimListViewModel.class);
        Log.v(LOG_TAG, "View model returned");

        dmvmodel.getDimList2con1(rid_int).observe(DetailActivity1.this, new Observer<List<tbl_dim_1>>() {

            @Override
            public void onChanged(@Nullable List<tbl_dim_1> changedItems) {
                Log.v(LOG_TAG, "onChanged called, items will be added");
                rcAdapter.addItems(changedItems);
            }
        });
    }

    @Override
    protected void onDestroy() {

        rcAdapter = null;
        rcView.setAdapter(null);
        rcView.setLayoutManager(null);
        rcView = null;
        dmvmodel = null;
        super.onDestroy();
        RefWatcher refWatcher = LeakCheckApplication.getRefWatcher(this);
        refWatcher.watch(this);
    }

    public static class DimCustomAdapter extends DimRecyclerAbstractAdapter<DimCustomAdapter.RecyclerViewHolder> {

        private static List<tbl_dim_1> mtbldimCustom;

        DimCustomAdapter(List<tbl_dim_1> tblDimListPassed) {
            super(mtbldimCustom);
            mtbldimCustom = tblDimListPassed;
        }

        @Override
        public DimCustomAdapter.RecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View vw = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.recycler_item, parent, false);

//          vw.setOnClickListener(vwOnClickListener);
            return new DimCustomAdapter.RecyclerViewHolder(vw);
        }

        @Override
        public void onBindViewHolder(final RecyclerViewHolder holder, int position) {
//          Log.v(LOG_TAG, "Inside onBindViewHolder - ");
            if (holder.dataTextView.getText() != null) {
                String LOG_TAG = "DimCustomAdapter:";
                Log.d(LOG_TAG, "holder is not null, i was right");
                holder.dataTextView.setText(null);
                holder.dataTextView.setOnClickListener(null);
            }

            final tbl_dim_1 dimAtPosition = mtbldimCustom.get(position);
            holder.dataTextView.setText(dimAtPosition.mCONTENT);
            holder.dataTextView.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View arg) {

                    Intent dw = new Intent(arg.getContext(), DetailActivity2.class);
                    dw.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    dw.putExtra("mRId", dimAtPosition.mR_ID);
                    arg.getContext().startActivity(dw);
                }
            });
        }

        class RecyclerViewHolder extends RecyclerView.ViewHolder {
            private TextView dataTextView;

            RecyclerViewHolder(View view) {
                super(view);
                dataTextView = (TextView) view.findViewById(R.id.data_text_view);
            }
        }
    }
}
</code>```

And this is how I'm calling this inner class from outer class within same activity -

```<code>DimCustomAdapter rcAdapter = new DimCustomAdapter(new ArrayList<tbl_dim_1>());
</code>```

答:
This is the solution i worked out for my problem( In case anyone face the same problem ).
Modyfying Durga's answer -

Firstly i added the isEmpty() check that he mentioned in comment.

Then in the activity i changed the code to this -

a) Added this new method in DimCustomAdapter -

```<code>public void changeList(List<tbl_dim_1> addedList){
            mtbldimCustom = addedList;
        }
</code>```

b) Called this method in observe method -

```<code>dmvmodel.getDimList2con1(rid_int).observe(DetailActivity1.this, new Observer<List<tbl_dim_1>>() {

            @Override
            public void onChanged(@Nullable List<tbl_dim_1> changedItems) {
                Log.v(LOG_TAG, "onChanged called, items will be added");
                rcAdapter.changeList(changedItems);
                rcAdapter.addItems(changedItems);
            }
        });
</code>```

Body:
What i'm trying to do is that, I have an adapter which I'm using for many different activities each having their own ViewHolder. So I'm firstly making an abstract recycler adapter named DimRecyclerAbstractAdapter without a ViewHolder. Then for each different activity I'm making a static inner class named DimCustomAdapter which extends DimRecyclerAbstractAdapter having it's own ViewHolder. But I'm getting this error.

java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
                                                                                at java.util.ArrayList.get(ArrayList.java:411)

This is the abstract adapter class  -

public abstract class DimRecyclerAbstractAdapter<VHA extends RecyclerView.ViewHolder> extends RecyclerView.Adapter<VHA> {

    private List<tbl_dim_1> mtbldimList1;

    public DimRecyclerAbstractAdapter(List<tbl_dim_1> tblDimList1) {
        this.mtbldimList1 = tblDimList1;
    }

    @Override
    public int getItemCount() {
            return mtbldimList1.size();
    }

    public void addItems(List<tbl_dim_1> tblDimList1) {

        this.mtbldimList1 = tblDimList1;
        notifyDataSetChanged();
    }

    @Override
    public void onDetachedFromRecyclerView(RecyclerView recyclerView) {
        mtbldimList1 = null;
        super.onDetachedFromRecyclerView(recyclerView);
    }

}

This is the activity in which I've implemented custom ViewHolder -

public class DetailActivity1 extends LifecycleActivity{

    DimListViewModel dmvmodel;
    RecyclerView rcView;
    DimCustomAdapter rcAdapter;
    public static final String LOG_TAG = "In DetailActivity1 ";

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

        Intent receivedIntent = getIntent();
        int rid_int = receivedIntent.getIntExtra("mRId",0);
        Log.v(LOG_TAG,"Rid value int == " + rid_int);

        rcView = (RecyclerView) findViewById(R.id.recyclerView);

        rcAdapter = new DimCustomAdapter(new ArrayList<tbl_dim_1>());
        rcView.setLayoutManager(new LinearLayoutManager(DetailActivity1.this));
        Log.v(LOG_TAG, "Layout manager set");
        rcView.setAdapter(rcAdapter);

        dmvmodel = ViewModelProviders.of(this).get(DimListViewModel.class);
        Log.v(LOG_TAG, "View model returned");

        dmvmodel.getDimList2con1(rid_int).observe(DetailActivity1.this, new Observer<List<tbl_dim_1>>() {

            @Override
            public void onChanged(@Nullable List<tbl_dim_1> changedItems) {
                Log.v(LOG_TAG, "onChanged called, items will be added");
                rcAdapter.addItems(changedItems);
            }
        });
    }

    @Override
    protected void onDestroy() {

        rcAdapter = null;
        rcView.setAdapter(null);
        rcView.setLayoutManager(null);
        rcView = null;
        dmvmodel = null;
        super.onDestroy();
        RefWatcher refWatcher = LeakCheckApplication.getRefWatcher(this);
        refWatcher.watch(this);
    }

    public static class DimCustomAdapter extends DimRecyclerAbstractAdapter<DimCustomAdapter.RecyclerViewHolder> {

        private static List<tbl_dim_1> mtbldimCustom;

        DimCustomAdapter(List<tbl_dim_1> tblDimListPassed) {
            super(mtbldimCustom);
            mtbldimCustom = tblDimListPassed;
        }

        @Override
        public DimCustomAdapter.RecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View vw = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.recycler_item, parent, false);

//          vw.setOnClickListener(vwOnClickListener);
            return new DimCustomAdapter.RecyclerViewHolder(vw);
        }

        @Override
        public void onBindViewHolder(final RecyclerViewHolder holder, int position) {
//          Log.v(LOG_TAG, "Inside onBindViewHolder - ");
            if (holder.dataTextView.getText() != null) {
                String LOG_TAG = "DimCustomAdapter:";
                Log.d(LOG_TAG, "holder is not null, i was right");
                holder.dataTextView.setText(null);
                holder.dataTextView.setOnClickListener(null);
            }

            final tbl_dim_1 dimAtPosition = mtbldimCustom.get(position);
            holder.dataTextView.setText(dimAtPosition.mCONTENT);
            holder.dataTextView.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View arg) {

                    Intent dw = new Intent(arg.getContext(), DetailActivity2.class);
                    dw.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    dw.putExtra("mRId", dimAtPosition.mR_ID);
                    arg.getContext().startActivity(dw);
                }
            });
        }

        class RecyclerViewHolder extends RecyclerView.ViewHolder {
            private TextView dataTextView;

            RecyclerViewHolder(View view) {
                super(view);
                dataTextView = (TextView) view.findViewById(R.id.data_text_view);
            }
        }
    }
}

And this is how I'm calling this inner class from outer class within same activity -

DimCustomAdapter rcAdapter = new DimCustomAdapter(new ArrayList<tbl_dim_1>());

Body:
This is the solution i worked out for my problem( In case anyone face the same problem ).
Modyfying Durga's answer -

Firstly i added the isEmpty() check that he mentioned in comment.

Then in the activity i changed the code to this -

a) Added this new method in DimCustomAdapter -

public void changeList(List<tbl_dim_1> addedList){
            mtbldimCustom = addedList;
        }

b) Called this method in observe method -

dmvmodel.getDimList2con1(rid_int).observe(DetailActivity1.this, new Observer<List<tbl_dim_1>>() {

            @Override
            public void onChanged(@Nullable List<tbl_dim_1> changedItems) {
                Log.v(LOG_TAG, "onChanged called, items will be added");
                rcAdapter.changeList(changedItems);
                rcAdapter.addItems(changedItems);
            }
        });


来源: stackexchange

问:
Echo showing wrong variable value in bash after a while block. Why?
I wanted to make a quick script to count the number of lines my .scala files have:

```<code>#!/bin/bash

counter=0;
find -iname "*.scala" | while read f; do
    lc=$(cat $f | wc -l);
    counter=$((counter+lc));
    echo "$lc $counter";
done
echo "final result: $counter";
</code>```

But unfortunately this prints

```<code>20 20
204 224
212 436
final result: 0
</code>```

What's wrong here?

答:
The issue is caused because you use a pipe before your while loop.

By doing so, bash automatically creates a new subshell. All the modifications you do will be executed in the new context, and will not be propagated when the context closes.

Use process substitution instead :

```<code>#!/bin/bash

counter=0;
while read f; do
    lc=$(cat $f | wc -l);
    counter=$((counter+lc));
    echo "$lc $counter";
done < <(find -iname "*.scala")
echo "final result: $counter";
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I wanted to make a quick script to count the number of lines my .scala files have:

#!/bin/bash

counter=0;
find -iname "*.scala" | while read f; do
    lc=$(cat $f | wc -l);
    counter=$((counter+lc));
    echo "$lc $counter";
done
echo "final result: $counter";

But unfortunately this prints

20 20
204 224
212 436
final result: 0

What's wrong here?

Body:
The issue is caused because you use a pipe before your while loop.

By doing so, bash automatically creates a new subshell. All the modifications you do will be executed in the new context, and will not be propagated when the context closes.

Use process substitution instead :

#!/bin/bash

counter=0;
while read f; do
    lc=$(cat $f | wc -l);
    counter=$((counter+lc));
    echo "$lc $counter";
done < <(find -iname "*.scala")
echo "final result: $counter";


问:
SQL Simple Join with two tables, but one is random
I am stuck with this. I have a simple set-up with two tables. One table is holding emailaddresses one table is holding vouchercodes. I want to join them in a third table, so that each emailaddress has one random vouchercode.

Unfortunatly I am stuck with this as there are no identic Ids to match both values. What I have so far brings no result:

```<code>Select
A.Email
B.CouponCode
FROM Emailaddresses as A
JOIN CouponCodes as B
on A.Email = B.CouponCode
</code>```

A hint would be great as search did not bring me any further yet.

Edit -

```<code>Table A (Addresses)
-------------------
Column A         | Column B
-------------------------
email1@gmail.com  True
email2@gmail.com
email3@gmail.com  True
email4@gmail.com

Table B (Voucher)
-------------------
ABCD1234
ABCD5678
ABCD9876
ABCD5432

Table C
-------------------------
column A | column B
-------------------------

email1@gmail.com  ABCD1234
email2@gmail.com  ABCD5678
email3@gmail.com  ABCD9876
email4@gmail.com  ABCD5432
</code>```

Sample Data:

答:
While joining without proper keys is not a good solution, for your case you can try this. (note: not tested, just a quick suggestion)</p>

```<code>;with cte_email as (
    select row_number() over (order by Email) as rownum, Email
    from Emailaddresses
)
;with cte_coupon as (
    select row_number() over (order by CouponCode) as rownum, CouponCode
    from CouponCodes
)

select a.Email,b.CouponCode
from cte_email a
join cte_coupon b
on a.rownum = b.rownum
</code>```

Body:
I am stuck with this. I have a simple set-up with two tables. One table is holding emailaddresses one table is holding vouchercodes. I want to join them in a third table, so that each emailaddress has one random vouchercode.

Unfortunatly I am stuck with this as there are no identic Ids to match both values. What I have so far brings no result:

Select
A.Email
B.CouponCode
FROM Emailaddresses as A
JOIN CouponCodes as B
on A.Email = B.CouponCode

A hint would be great as search did not bring me any further yet.

Edit -

Table A (Addresses)
-------------------
Column A         | Column B
-------------------------
email1@gmail.com  True
email2@gmail.com
email3@gmail.com  True
email4@gmail.com

Table B (Voucher)
-------------------
ABCD1234
ABCD5678
ABCD9876
ABCD5432

Table C
-------------------------
column A | column B
-------------------------

email1@gmail.com  ABCD1234
email2@gmail.com  ABCD5678
email3@gmail.com  ABCD9876
email4@gmail.com  ABCD5432

Sample Data:

Body:
While joining without proper keys is not a good solution, for your case you can try this. (note: not tested, just a quick suggestion)

;with cte_email as (
    select row_number() over (order by Email) as rownum, Email
    from Emailaddresses
)
;with cte_coupon as (
    select row_number() over (order by CouponCode) as rownum, CouponCode
    from CouponCodes
)

select a.Email,b.CouponCode
from cte_email a
join cte_coupon b
on a.rownum = b.rownum


问:
React how to handle OnBlur and 'up' and 'down' arrows are clicked for Input Type is number
I am trying to grab data only when user stops typing and remove cursor from input e.g onBlur along with when Up and down keys are pressed in React</p>

```<code>var ExampleForm = React.createClass({
    getInitialState: function () {
        return {lastName: 1}
    },
    onsChange: function(event) {
        this.setState({lastName: event.target.value});
    },

    render: function() {
       return (<div>
                <input name='lastName'
                    value={this.state.lastName}
                    type={"number"}
                    onChange={this.onsChange.bind(this)}/>
                  </div>

        );
    }
});

ReactDOM.render(
    <ExampleForm/>,
    document.getElementById('view'));
</code>```

答:
for remove cursor you have to use setTimeout. Do like this...

 onsChange(event) {
        this.setState({lastName: event.target.value});
        var currentTarget = event.target;
        setTimeout(function(){
            currentTarget.blur();
        }, 3000);
    }
    render() {
        return (

                <input name='lastName'
                    value={this.state.lastName}
                    type={"number"}
                    onChange={this.onsChange.bind(this)}/>

        );
    }```

Body:
I am trying to grab data only when user stops typing and remove cursor from input e.g onBlur along with when Up and down keys are pressed in React

var ExampleForm = React.createClass({
    getInitialState: function () {
        return {lastName: 1}
    },
    onsChange: function(event) {
        this.setState({lastName: event.target.value});
    },

    render: function() {
       return (

                <input name='lastName'
                    value={this.state.lastName}
                    type={"number"}
                    onChange={this.onsChange.bind(this)}/>

        );
    }
});

ReactDOM.render(
    <ExampleForm/>,
    document.getElementById('view'));

Body:
for remove cursor you have to use setTimeout. Do like this...

 onsChange(event) {
        this.setState({lastName: event.target.value});
        var currentTarget = event.target;
        setTimeout(function(){
            currentTarget.blur();
        }, 3000);
    }
    render() {
        return (
            <div>
                <input name='lastName'
                    value={this.state.lastName}
                    type={"number"}
                    onChange={this.onsChange.bind(this)}/>
            </div>
        );
    }


问:
Why does RDD.getStorageLevel.useMemory return true, but Spark UI storage not displaying cached data?
I am learning Apache Spark and working with the RDD and cache RDD processes.

I got to know that We can check if a RDD is cached or not using rdd.getStorageLevel.useMemory command in scala terminal.

So here is the commands which i followed:

```<code>scala> years.getStorageLevel.useMemory
res12: Boolean = false

scala> years.cache();
res13: years.type = MapPartitionsRDD[2] at filter at <console>:29

scala> years.getStorageLevel.useMemory
res14: Boolean = true
</code>```

So that means the years rdd now got cached.

But when i checked the spark UI storage tab, i could find nothing.
Here is the screenshot:

Is there anything missing? If the command line show it has been cached (as it is returning true), then why does it not showing on the UI?

答:
Calling years.cache() just marks years RDD to be cached the next time an action is executed.

RDD.cache uses MEMORY_ONLY storage level.

cache(): RDD.this.type Persist this RDD with the default storage level (MEMORY_ONLY).

That gives you the answer why you get true when executing the following code:

scala> years.getStorageLevel.useMemory
res14: Boolean = true

It simply "queries" the attributes of MEMORY_AND_DISK storage level and does not tell you whether years was indeed cached already or is about to be.

I think that you'd have to go very deep to know whether a dataset has already been cached or not.

I think the simplest solution would be to use SparkListener API and intercept SparkListenerBlockUpdated, but haven't done it before.

The following is about Dataset API that may or may be relevant (I was mistaken answering the question with Dataset API in mind).

Dataset.cache uses memory and disk when needed since it uses StorageLevel.DISK_AND_MEMORY storage level.

cache(): Dataset.this.type Persist this Dataset with the default storage level (MEMORY_AND_DISK).

That gives you the answer why you get true when executing the following code:

```<code>scala> years.getStorageLevel.useMemory
res14: Boolean = true
</code>```

It simply "queries" the attributes of MEMORY_AND_DISK storage level and does not tell you whether years was indeed cached already or is about to be.

In order to check if a dataset has already been marked to be cached, you can use CacheManager (that is shared across SparkSessions through SharedState and available as spark.sharedState.cacheManager).

It is an internal API so use with caution.

```<code>val cached = spark.range(5).cache
scala> spark.sharedState.cacheManager.lookupCachedData(cached.queryExecution.logical)
res20: Option[org.apache.spark.sql.execution.CachedData] =
Some(CachedData(Range (0, 5, step=1, splits=Some(8))
,InMemoryRelation [id#331L], true, 10000, StorageLevel(disk, memory, deserialized, 1 replicas)
   +- *Range (0, 5, step=1, splits=8)
))
</code>```

As a matter of fact, CacheManager will warn you if you try to cache the same (logical plan of) Dataset twice.

```<code>scala> val cached = spark.range(5).cache
17/12/07 15:00:34 WARN CacheManager: Asked to cache already cached data.
cached: org.apache.spark.sql.Dataset[Long] = [id: bigint]
</code>```

Body:
I am learning Apache Spark and working with the RDD and cache RDD processes.

I got to know that We can check if a RDD is cached or not using rdd.getStorageLevel.useMemory command in scala terminal.

So here is the commands which i followed:

scala> years.getStorageLevel.useMemory
res12: Boolean = false

scala> years.cache();
res13: years.type = MapPartitionsRDD[2] at filter at <console>:29

scala> years.getStorageLevel.useMemory
res14: Boolean = true

So that means the years rdd now got cached.

But when i checked the spark UI storage tab, i could find nothing.
Here is the screenshot:

Is there anything missing? If the command line show it has been cached (as it is returning true), then why does it not showing on the UI?

Body:
Calling years.cache() just marks years RDD to be cached the next time an action is executed.

RDD.cache uses MEMORY_ONLY storage level.

cache(): RDD.this.type Persist this RDD with the default storage level (MEMORY_ONLY).

That gives you the answer why you get true when executing the following code:

scala> years.getStorageLevel.useMemory
res14: Boolean = true

It simply "queries" the attributes of MEMORY_AND_DISK storage level and does not tell you whether years was indeed cached already or is about to be.

I think that you'd have to go very deep to know whether a dataset has already been cached or not.

I think the simplest solution would be to use SparkListener API and intercept SparkListenerBlockUpdated, but haven't done it before.

The following is about Dataset API that may or may be relevant (I was mistaken answering the question with Dataset API in mind).

Dataset.cache uses memory and disk when needed since it uses StorageLevel.DISK_AND_MEMORY storage level.

cache(): Dataset.this.type Persist this Dataset with the default storage level (MEMORY_AND_DISK).

That gives you the answer why you get true when executing the following code:

scala> years.getStorageLevel.useMemory
res14: Boolean = true

It simply "queries" the attributes of MEMORY_AND_DISK storage level and does not tell you whether years was indeed cached already or is about to be.

In order to check if a dataset has already been marked to be cached, you can use CacheManager (that is shared across SparkSessions through SharedState and available as spark.sharedState.cacheManager).

It is an internal API so use with caution.

val cached = spark.range(5).cache
scala> spark.sharedState.cacheManager.lookupCachedData(cached.queryExecution.logical)
res20: Option[org.apache.spark.sql.execution.CachedData] =
Some(CachedData(Range (0, 5, step=1, splits=Some(8))
,InMemoryRelation [id#331L], true, 10000, StorageLevel(disk, memory, deserialized, 1 replicas)
   +- *Range (0, 5, step=1, splits=8)
))

As a matter of fact, CacheManager will warn you if you try to cache the same (logical plan of) Dataset twice.

scala> val cached = spark.range(5).cache
17/12/07 15:00:34 WARN CacheManager: Asked to cache already cached data.
cached: org.apache.spark.sql.Dataset[Long] = [id: bigint]


问:
Null object reference in Firebase result loop
I want to receive all challenges in Firestore and loop over result to add it to an ArrayList.

```<code>db.collection("challenges")
        .get()
        .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
            @Override
            public void onComplete(@NonNull Task<QuerySnapshot> task) {
                if (task.isSuccessful()) {
                    for (DocumentSnapshot document : task.getResult()) {
                        if (document.exists()) {
                            Log.d(TAG, document.getId() + " => " + document.getData());
                    Error-> Challenge challenge = document.toObject(Challenge.class);
                            Log.d(TAG, challenge.getUid() + " => " + challenge.getText());
                            challengeList.add(document.getData().toString());
                        }
                    }

                    challengeListView.setAdapter(challengeArrayAdapter);
                } else {
                    Log.d(TAG, "Error getting documents: ", task.getException());
                }
            }
        });
</code>```

Error is:

```<code>java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object java.lang.reflect.Constructor.newInstance(java.lang.Object[])' on a null object reference
</code>```

Line:

```<code>Challenge challenge = document.toObject(Challenge.class);
</code>```

The log with Log.d(TAG, document.getId() + " => " + document.getData());
is working.

Reference: https://firebase.google.com/docs/firestore/query-data/get-data#get_all_documents_in_a_collection

This is my my Challenge Class:

```<code>public class Challenge {

    private Date createdAt;
    private Date changedAt;
    private String uid;
    private String text;
    private double longitude;
    private double latitude;

    public Challenge(String uid, String text, double longitude, double latitude) {
        Date currentDate = new Date();
        this.createdAt = currentDate;
        this.changedAt = currentDate;
        this.uid = uid;
        this.text = text;
        this.longitude = longitude;
        this.latitude = latitude; }

    public Date getCreatedAt() { return createdAt; }

    public Date getChangedAt() { return changedAt; }

    public String getUid() { return uid; }

    public String getText() { return text; }

    public double getLongitude() { return longitude; }

    public double getLatitude() { return latitude;}
}
</code>```

答:
You need to change this line of code:

```<code>Challenge challenge = document.toObject(Challenge.class);
</code>```

with

```<code>Map<String, Object> map = task.getResult().getData());
</code>```

To use toObject() method for a single document, please use the following code:

```<code>DocumentReference docRef = db.collection("challenges").document("yourDocument");
docRef.get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
    @Override
    public void onSuccess(DocumentSnapshot documentSnapshot) {
        Challenge challenge = documentSnapshot.toObject(Challenge.class);
    }
});
</code>```

The error is because of your modell class. Your code looks good. Add the no-argument constructor in your model class. Keep that code or use the Map<String, Object> and your problem will be solved.

To add the no-argument constructor, please add the following line of code in your model class:

```<code>public Challenge() {} //Needed for Firebase
</code>```

after the decalaration of class variables.

Body:
I want to receive all challenges in Firestore and loop over result to add it to an ArrayList.

db.collection("challenges")
        .get()
        .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
            @Override
            public void onComplete(@NonNull Task<QuerySnapshot> task) {
                if (task.isSuccessful()) {
                    for (DocumentSnapshot document : task.getResult()) {
                        if (document.exists()) {
                            Log.d(TAG, document.getId() + " => " + document.getData());
                    Error-> Challenge challenge = document.toObject(Challenge.class);
                            Log.d(TAG, challenge.getUid() + " => " + challenge.getText());
                            challengeList.add(document.getData().toString());
                        }
                    }

                    challengeListView.setAdapter(challengeArrayAdapter);
                } else {
                    Log.d(TAG, "Error getting documents: ", task.getException());
                }
            }
        });

Error is:

java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object java.lang.reflect.Constructor.newInstance(java.lang.Object[])' on a null object reference

Line:

Challenge challenge = document.toObject(Challenge.class);

The log with Log.d(TAG, document.getId() + " => " + document.getData());
is working.

Reference: https://firebase.google.com/docs/firestore/query-data/get-data#get_all_documents_in_a_collection

This is my my Challenge Class:

public class Challenge {

    private Date createdAt;
    private Date changedAt;
    private String uid;
    private String text;
    private double longitude;
    private double latitude;

    public Challenge(String uid, String text, double longitude, double latitude) {
        Date currentDate = new Date();
        this.createdAt = currentDate;
        this.changedAt = currentDate;
        this.uid = uid;
        this.text = text;
        this.longitude = longitude;
        this.latitude = latitude; }

    public Date getCreatedAt() { return createdAt; }

    public Date getChangedAt() { return changedAt; }

    public String getUid() { return uid; }

    public String getText() { return text; }

    public double getLongitude() { return longitude; }

    public double getLatitude() { return latitude;}
}

Body:
You need to change this line of code:

Challenge challenge = document.toObject(Challenge.class);

with

Map<String, Object> map = task.getResult().getData());

To use toObject() method for a single document, please use the following code:

DocumentReference docRef = db.collection("challenges").document("yourDocument");
docRef.get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
    @Override
    public void onSuccess(DocumentSnapshot documentSnapshot) {
        Challenge challenge = documentSnapshot.toObject(Challenge.class);
    }
});

The error is because of your modell class. Your code looks good. Add the no-argument constructor in your model class. Keep that code or use the Map<String, Object> and your problem will be solved.

To add the no-argument constructor, please add the following line of code in your model class:

public Challenge() {} //Needed for Firebase

after the decalaration of class variables.


问:
Google Spreadsheet conditional formatting based on another cell Date
I have a Google spreedsheet with multiple columns and I am trying to apply the following two tasks but can't seem to figure out how to do so.

I have two columns C and D, where C present a date picker and D present a drop down list with two values [Complete - In Progress]. I am trying to figure out a way where any cell in column D will display (In Progress) if the corresponding cell date is less than or equal todays date

If column C date is 2 days ahead, change the whole row color to blue

Can the above be done using Google d=Any thoughts how I can complete any of the above two tasks? Thanks in advance for your time and efforts

答:
for example, if your Date is in C3 then like MKM said, the if function is your need

just paste this code into D3

```<code>=IF(C3<=TODAY();"in progress";"done")
</code>```

i think that should do the trick, i tested your wish within this sheet:
https://docs.google.com/spreadsheets/d/1z6mwkxqc2NyLJsH16NFWyL01y0jGcKrNNtuYcJS5dNw/edit#gid=734876188
but i don't really get what you second question is about, hope this helps and answers this questions :)

PS.: may you can share your spreadsheet with us, so we might get a better understanding of your issue within google formatting ;)

Body:
for example, if your Date is in C3 then like MKM said, the if function is your need

just paste this code into D3

=IF(C3<=TODAY();"in progress";"done")

i think that should do the trick, i tested your wish within this sheet:
https://docs.google.com/spreadsheets/d/1z6mwkxqc2NyLJsH16NFWyL01y0jGcKrNNtuYcJS5dNw/edit#gid=734876188
but i don't really get what you second question is about, hope this helps and answers this questions :)

PS.: may you can share your spreadsheet with us, so we might get a better understanding of your issue within google formatting ;)


问:
make column data as hyperlink (dataTable JQUERY)
I am trying to make a column as hyperlink with datatable but no success.

function successCallback(responseObj){

```<code>  $(document).ready(function() {
         $('#example').dataTable( {
        "data":responseObj ,
        "bDestroy": true,
        "deferRender": true ,
        "columns": [
                    { "data": "infomation" },
                    { "data": "weblink" },
                ]
  } );

  } );
</code>```

}

I need the weblink to display the link and be an hyperlink in that column so users can click and be redirected to another page. I looked into render but with less information there on links, i can't succeed to do it.

I also looked into this example but it wasn't very helpful.

答:
If you are looking to add link based on other column data then can use the below approach.

```<code>$('#example').dataTable({
   "data": responseObj,
   "columns": [
      { "data": "information" },
      {
         "data": "weblink",
         "render": function(data, type, row, meta){
            if(type === 'display'){
                data = '<a href="' + row.myid + '">' + data + '</a>';
            }
            return data;
         }
      }
   ]
});
</code>```

I have just changed the render function. data refers to only current column data, while row object refers to entire row of data. Hence we can use this to get any other data for that row.

Body:
I am trying to make a column as hyperlink with datatable but no success.

function successCallback(responseObj){

  $(document).ready(function() {
         $('#example').dataTable( {
        "data":responseObj ,
        "bDestroy": true,
        "deferRender": true ,
        "columns": [
                    { "data": "infomation" },
                    { "data": "weblink" },
                ]
  } );

  } );

}

I need the weblink to display the link and be an hyperlink in that column so users can click and be redirected to another page. I looked into render but with less information there on links, i can't succeed to do it.

I also looked into this example but it wasn't very helpful.

Body:
If you are looking to add link based on other column data then can use the below approach.

$('#example').dataTable({
   "data": responseObj,
   "columns": [
      { "data": "information" },
      {
         "data": "weblink",
         "render": function(data, type, row, meta){
            if(type === 'display'){
                data = '<a href="' + row.myid + '">' + data + '</a>';
            }
            return data;
         }
      }
   ]
});

I have just changed the render function. data refers to only current column data, while row object refers to entire row of data. Hence we can use this to get any other data for that row.


问:
Declaration or Definition in C
From External Variables Wiki:

If neither the extern keyword nor an
  initialization value are present, the
  statement can be either a declaration
  or a definition. It is up to the
  compiler to analyse the modules of the
  program and decide.

I was not able to fully grasp the meaning of this statement with respect to C. For example, does it imply that:

```<code>int i;
</code>```

is not necessarily a declaration (as I have been assuming until now), but could be a definition as well (by definition of Definition & Declaration on the same webpage, no puns intended)?

In a nutshell, is the above statement:
a. just a declaration, or
b. declaration +  definition?

Reference: Variable declaration and definition

Summary of answers received:

```<code>                         Declaration    Definition    Tentative Definition   Initialized
int i;   (inside a block)    Yes           Yes                No                No
int i=5; (inside a block)    Yes           Yes                No               Yes(to 5)
int i;   (otherwise)         Yes            No               Yes               Yes(to 0)
extern int i;                Yes            No                No                No

All definitions are declarations but not vice-versa.
</code>```

答:
In the context of variables:

A declaration of a variable is a statement which describes how this variable looks like. So:

```<code>extern int x;
</code>```

in global scope translates to: "somewhere in the code, there's a variable called x which has type int and extern linkage. A declaration is necessary before you ever refer to x. (The same goes to function declarations.)

A definition is a statement which creates an instance of this variable. So:

```<code>int x;
</code>```

in global scope creates a single variable of type int with extern linkage. So if you'd put that line in a header, every translation unit including that header would try to create its own copy of x, which is undesirable - that's why we only have declarations in header files. The same goes to functions: if you provide the function body, it's a definition.

Also, formally, every definition is a kind of declaration, as it also has to specify how this variable/function looks like - so if a definition already exists in a given scope, you don't need any additional declarations to use it.

ContentLicense: CC BY-SA 2.5

Title: Declaration or Definition in C

Body:
From External Variables Wiki:

If neither the extern keyword nor an
  initialization value are present, the
  statement can be either a declaration
  or a definition. It is up to the
  compiler to analyse the modules of the
  program and decide.

I was not able to fully grasp the meaning of this statement with respect to C. For example, does it imply that:

int i;

is not necessarily a declaration (as I have been assuming until now), but could be a definition as well (by definition of Definition & Declaration on the same webpage, no puns intended)?

In a nutshell, is the above statement:
a. just a declaration, or
b. declaration +  definition?

Reference: Variable declaration and definition

Summary of answers received:

                         Declaration    Definition    Tentative Definition   Initialized
int i;   (inside a block)    Yes           Yes                No                No
int i=5; (inside a block)    Yes           Yes                No               Yes(to 5)
int i;   (otherwise)         Yes            No               Yes               Yes(to 0)
extern int i;                Yes            No                No                No

All definitions are declarations but not vice-versa.

Body:
In the context of variables:

A declaration of a variable is a statement which describes how this variable looks like. So:

extern int x;

in global scope translates to: "somewhere in the code, there's a variable called x which has type int and extern linkage. A declaration is necessary before you ever refer to x. (The same goes to function declarations.)

A definition is a statement which creates an instance of this variable. So:

int x;

in global scope creates a single variable of type int with extern linkage. So if you'd put that line in a header, every translation unit including that header would try to create its own copy of x, which is undesirable - that's why we only have declarations in header files. The same goes to functions: if you provide the function body, it's a definition.

Also, formally, every definition is a kind of declaration, as it also has to specify how this variable/function looks like - so if a definition already exists in a given scope, you don't need any additional declarations to use it.


问:
How to create a Zookeeper node from a file?
Using zkCli.sh,

create -s /myznode “Hello World!” null

creates a znode using the string "Hello World!"

How do I get it to use the contents of a file instead of a string?

答:
With a multi line file containing spaces or line breaks, try something like this:</p>

```<code>./bin/zkCli.sh create /test-node "`cat my-znode-content.xml`"
</code>```

Body:
With a multi line file containing spaces or line breaks, try something like this:

./bin/zkCli.sh create /test-node "`cat my-znode-content.xml`"


问:
Understanding Sort on query in solr
I am new to solr and trying to understand a solr sort criteria that goes like this -

```<code>bQ01=2859969
bQ02={!term f=prdId v=$bQ01}
bQ03={!lucene} {!v=$bQ02}^=6

buryClearanceQuery={!parent which=$pq score=min v=$matchAllQueryRef2}
matchAllQueryRef2= ({!query v=$cq})  ({!simpleFilter v=$priceTypeClearance})
priceTypeClearance={!term f=priceType_refine v=$matchAllQueryRef3}
matchAllQueryRef3=Clearance
cq= {!simpleFilter v=docType:pdf}   {!docValues v='shelf_873:1'}
sort=query($bQ03,0) desc, query($buryClearanceQuery) asc
</code>```

I am facing issues understanding how the sort criteria is made above and how will query(some_expression, 0) desc will work.

Any help is greatly appreciated.

答:
The parameters to the sort clause get there via parameter passing. So, basically in the Solr query you could reference it via $ sign.

Simpler example from the Solr documentation

```<code>q={!type=dismax qf=myfield v=$qq}&qq=solr rocks
</code>```

Similar stuff is happening in your query and in sort clause particularly. Sorting by query is working as following:

Solr can sort query responses according to document scores or the
  value of any field with a single value

than in the sort clause you could specify the field by which you're sorting, or the query (it could be either normal query or function query) - which produce single "pseudo" field (score)

Title: Understanding Sort on query in solr

Body:
I am new to solr and trying to understand a solr sort criteria that goes like this -

bQ01=2859969
bQ02={!term f=prdId v=$bQ01}
bQ03={!lucene} {!v=$bQ02}^=6

buryClearanceQuery={!parent which=$pq score=min v=$matchAllQueryRef2}
matchAllQueryRef2= ({!query v=$cq})  ({!simpleFilter v=$priceTypeClearance})
priceTypeClearance={!term f=priceType_refine v=$matchAllQueryRef3}
matchAllQueryRef3=Clearance
cq= {!simpleFilter v=docType:pdf}   {!docValues v='shelf_873:1'}
sort=query($bQ03,0) desc, query($buryClearanceQuery) asc

I am facing issues understanding how the sort criteria is made above and how will query(some_expression, 0) desc will work.

Any help is greatly appreciated.

Body:
The parameters to the sort clause get there via parameter passing. So, basically in the Solr query you could reference it via $ sign.

Simpler example from the Solr documentation

q={!type=dismax qf=myfield v=$qq}&qq=solr rocks

Similar stuff is happening in your query and in sort clause particularly. Sorting by query is working as following:

Solr can sort query responses according to document scores or the
  value of any field with a single value

than in the sort clause you could specify the field by which you're sorting, or the query (it could be either normal query or function query) - which produce single "pseudo" field (score)


问:
How do I get the server timestamp in Cloud Functions for Firebase?
I know you can pull the server timestamp in web, ios, and android - but what about the new Cloud Functions for Firebase?  I can't figure out how to get the server timestamp there?  Use case is me wanting to timestamp an email when it arrives.

On web it is Firebase.database.ServerValue.TIMESTAMP

But that doesn't seem to be available in the functions node server interface?

I think it is late and I may be missing the point here...

EDIT

I am initializing like this

```<code>admin.initializeApp(functions.config().firebase);
const fb = admin.database()
</code>```

Then, it is being called like this..

```<code>Firebase.database.ServerValue.TIMESTAMP
</code>```

But, that is from a client side integration.  On Functions, Firebase isn't initialized like this.  I've tried

```<code>admin.database().ServerValue.TIMESTAMP
</code>```

and

```<code>fb.ServerValue.TIMESTAMP
</code>```

答:
If you use the Firebase Admin SDK, here is the correct syntax:

2023

```<code>// Cloud Firestore
import { Timestamp } from 'firebase-admin/firestore';

// usage
Timestamp.now()
</code>```

(2021-2022)

```<code>// Cloud Firestore
admin.firestore.Timestamp.now();
</code>```

(Checked 2019-08-27):

```<code>const admin = require('firebase-admin');
// or
// import * as admin from 'firebase-admin';

// Using Cloud Firestore
admin.firestore.FieldValue.serverTimestamp()

// Using Realtime Database
admin.database.ServerValue.TIMESTAMP
</code>```

Body:
I know you can pull the server timestamp in web, ios, and android - but what about the new Cloud Functions for Firebase?  I can't figure out how to get the server timestamp there?  Use case is me wanting to timestamp an email when it arrives.

On web it is Firebase.database.ServerValue.TIMESTAMP

But that doesn't seem to be available in the functions node server interface?

I think it is late and I may be missing the point here...

EDIT

I am initializing like this

admin.initializeApp(functions.config().firebase);
const fb = admin.database()

Then, it is being called like this..

Firebase.database.ServerValue.TIMESTAMP

But, that is from a client side integration.  On Functions, Firebase isn't initialized like this.  I've tried

admin.database().ServerValue.TIMESTAMP

and

fb.ServerValue.TIMESTAMP

Body:
If you use the Firebase Admin SDK, here is the correct syntax:

2023

// Cloud Firestore
import { Timestamp } from 'firebase-admin/firestore';

// usage
Timestamp.now()

(2021-2022)

// Cloud Firestore
admin.firestore.Timestamp.now();

(Checked 2019-08-27):

const admin = require('firebase-admin');
// or
// import * as admin from 'firebase-admin';

// Using Cloud Firestore
admin.firestore.FieldValue.serverTimestamp()

// Using Realtime Database
admin.database.ServerValue.TIMESTAMP

ContentLicense: CC BY-SA 4.0


问:
Python Image Uploading with AjaxUpload
I'm trying to use AjaxUpload with Python:
http://valums.com/ajax-upload/

I would like to know how to access the uploaded file with Python.  On the web site, it says:

```<code>* PHP: $_FILES['userfile']
* Rails: params[:userfile]
</code>```

What is the Syntax for Python?

request.params['userfile'] doesn't seem to work.

Thanks in advance!  Here is my current code (using PIL imported as Image)

```<code>im = Image.open(request.params['myFile'].file)
</code>```

答:
I'm working with Pyramid, and I was trying to do the same thing. After some time I came up with this solution.

```<code>from cStringIO import StringIO
from cgi import FieldStorage

fs = FieldStorage(fp=request['wsgi.input'], environ=request)
f = StringIO(fs.value)

im = Image.open(f)
</code>```

I'm not sure if it's the "right" one, but it seems to work.

Title: Python Image Uploading with AjaxUpload

Body:
I'm trying to use AjaxUpload with Python:
http://valums.com/ajax-upload/

I would like to know how to access the uploaded file with Python.  On the web site, it says:

* PHP: $_FILES['userfile']
* Rails: params[:userfile]

What is the Syntax for Python?

request.params['userfile'] doesn't seem to work.

Thanks in advance!  Here is my current code (using PIL imported as Image)

im = Image.open(request.params['myFile'].file)

Body:
I'm working with Pyramid, and I was trying to do the same thing. After some time I came up with this solution.

from cStringIO import StringIO
from cgi import FieldStorage

fs = FieldStorage(fp=request['wsgi.input'], environ=request)
f = StringIO(fs.value)

im = Image.open(f)

I'm not sure if it's the "right" one, but it seems to work.


问:
JavaScript function that takes a random argument each time
I'm working on a Canvas API game and I want to create some enemies, each time I create a new instance of the enemy I want it to be create in a new position (not randomly, but rather 3 specific positions.

So let's say I have this function:

```<code>var enemy = new Enemy(0, Math.random() * 184 + 50, Math.random() * 256);
</code>```

This creates a new enemy with an Y position of 0, an X position which is random and a Speed argument that's also random.

This works fine but I want the enemies to be be created in only 3 specific positons and the speed to only increase by 10 each time new enemy instance is being created.

More info: new enemies are being called once the player get's to the final position of winning, like so:

```<code>var increaseDifficulty = function(numEnemies) {
    // remove all previous enemies on canvas
    allEnemies.length = 0;

    // load new set of enemies
    for (var i = 0; i <= numEnemies; i++) {
        var enemy = new Enemy(0, Math.random() * 184 + 50, Math.random() * 256);

        allEnemies.push(enemy);
    }
};
</code>```

What I want is a way to create a new enemy with a different argument each time. Only for the position and speed.

Something like:

```<code>var enemy = new Enemy(0, 1, 1);
</code>```

The second time it is being called it'll be different so:

```<code>var enemy = new Enemy(0, 3, 2);
</code>```

Of course the values won't be 1, 2 and 3 but you get the idea.

UPDATE:

The new enemy calls upon this:

```<code>var Enemy = function(x, y, speed) {
    this.x = x;
    this.y = y;
    this.speed = speed;
    this.sprite = 'images/enemy-bug.png';
};

Enemy.prototype.update = function(dt) {
    this.x += this.speed * dt;
    if (this.x >= 505) {
        this.x = 0;
    }

    checkCollision(this);
};
Enemy.prototype.render = function() {
    ctx.drawImage(Resources.get(this.sprite), this.x, this.y);
};
</code>```

答:
Y is always 0 so there is no point passing it to the constructor, speed has some starting value and then is always increased by 10 so there is no point passing it too. X is the only thing that is random, and there is some point to pass it to the constructor, but I would not do that too. I would create an array of possible values of X and choose one of them randomly inside the constructor.

const xValues = [20, 60, 100];

//The Enemy "class":
function Enemy() {
    this.y = 0;
    this.x = xValues[Math.floor(Math.random() * xValues.length)];
    Enemy.speed = (Enemy.speed += 10) || 10;
    this.speed = Enemy.speed;
    this.sprite = 'images/enemy-bug.png';
}

let e1 = new Enemy;
console.log(e1);
let e2 = new Enemy;
console.log(e2);
let e3 = new Enemy;
console.log(e3);```
</div>
</div>
</p>

<p><em>Note 1:</em> <code>Math.floor(Math.random() * xValues.length)</code> creates a random <em>integer</em> (thanks to the <code>Math.floor</code>) number between 0 and the length on my <code>xValues</code> array. This number is used to choose a random value from the <code>xValues</code> array.</p>

<p><em>Note 2:</em> on this line I create something like a class variable <code>Enemy.speed</code> with the starting value of 10.  At first <code>Enemy.speed</code> does not exist so <code>Enemy.speed += 10</code> evaluates to <code>NaN</code>, since <code>NaN</code> is falsy the evaluating continues to <code>10</code>;</p>

```Enemy.speed = (Enemy.speed += 10) || 10;
```

<p>Then I copy the value to the instance.</p>

```this.speed = Enemy.speed;
```

Body:
I'm working on a Canvas API game and I want to create some enemies, each time I create a new instance of the enemy I want it to be create in a new position (not randomly, but rather 3 specific positions.

So let's say I have this function:

var enemy = new Enemy(0, Math.random() * 184 + 50, Math.random() * 256);

This creates a new enemy with an Y position of 0, an X position which is random and a Speed argument that's also random.

This works fine but I want the enemies to be be created in only 3 specific positons and the speed to only increase by 10 each time new enemy instance is being created.

More info: new enemies are being called once the player get's to the final position of winning, like so:

var increaseDifficulty = function(numEnemies) {
    // remove all previous enemies on canvas
    allEnemies.length = 0;

    // load new set of enemies
    for (var i = 0; i <= numEnemies; i++) {
        var enemy = new Enemy(0, Math.random() * 184 + 50, Math.random() * 256);

        allEnemies.push(enemy);
    }
};

What I want is a way to create a new enemy with a different argument each time. Only for the position and speed.

Something like:

var enemy = new Enemy(0, 1, 1);

The second time it is being called it'll be different so:

var enemy = new Enemy(0, 3, 2);

Of course the values won't be 1, 2 and 3 but you get the idea.

UPDATE:

The new enemy calls upon this:

var Enemy = function(x, y, speed) {
    this.x = x;
    this.y = y;
    this.speed = speed;
    this.sprite = 'images/enemy-bug.png';
};

Enemy.prototype.update = function(dt) {
    this.x += this.speed * dt;
    if (this.x >= 505) {
        this.x = 0;
    }

    checkCollision(this);
};
Enemy.prototype.render = function() {
    ctx.drawImage(Resources.get(this.sprite), this.x, this.y);
};

Body:
Y is always 0 so there is no point passing it to the constructor, speed has some starting value and then is always increased by 10 so there is no point passing it too. X is the only thing that is random, and there is some point to pass it to the constructor, but I would not do that too. I would create an array of possible values of X and choose one of them randomly inside the constructor.

const xValues = [20, 60, 100];

//The Enemy "class":
function Enemy() {
    this.y = 0;
    this.x = xValues[Math.floor(Math.random() * xValues.length)];
    Enemy.speed = (Enemy.speed += 10) || 10;
    this.speed = Enemy.speed;
    this.sprite = 'images/enemy-bug.png';
}

let e1 = new Enemy;
console.log(e1);
let e2 = new Enemy;
console.log(e2);
let e3 = new Enemy;
console.log(e3);

Note 1: Math.floor(Math.random() * xValues.length) creates a random integer (thanks to the Math.floor) number between 0 and the length on my xValues array. This number is used to choose a random value from the xValues array.

Note 2: on this line I create something like a class variable Enemy.speed with the starting value of 10.  At first Enemy.speed does not exist so Enemy.speed += 10 evaluates to NaN, since NaN is falsy the evaluating continues to 10;

Enemy.speed = (Enemy.speed += 10) || 10;

Then I copy the value to the instance.

this.speed = Enemy.speed;


问:
Cleanthesis TeX Theme wont create pdf
Im trying to build a (the thesis-example.tex) PDF with the cleanthesis theme (http://cleanthesis.der-ric.de/) and it wont work

The last failure is:

```<code>! pdfTeX error (font expansion): auto expansion is only possible with scalable
fonts.
\AtBegShi@Output ...ipout \box \AtBeginShipoutBox
                                                  \fi \fi
l.107 \cleardoublepage

!  ==> Fatal error occurred, no output PDF file produced!
Transcript written on thesis-example.log.
</code>```

Im currently on a Fed26 System with 5928 installed texlive packages.
(dnf install texlive-scheme-full, dnf install texlive-*)

If i try this with a complete stock Ubuntu 16.04 and texlive-publisher and texlive-full packages it works. So i guess there is no missing package.

I you need specific parts of thesis-example.log, let me know i cant paste it because its too large

答:
So i installed a clean Fed26 and loaded all texlive packages i had on the main pc. I compared /etc/texlive/web2c/updmap.cfg and i saw that my updmap.cfg was currupted.

I copied the working updmap.cfg to my main system and did a "updmap-sys --force" and now it works

Title: Cleanthesis TeX Theme wont create pdf

Body:
Im trying to build a (the thesis-example.tex) PDF with the cleanthesis theme (http://cleanthesis.der-ric.de/) and it wont work

The last failure is:

! pdfTeX error (font expansion): auto expansion is only possible with scalable
fonts.
\AtBegShi@Output ...ipout \box \AtBeginShipoutBox
                                                  \fi \fi
l.107 \cleardoublepage

!  ==> Fatal error occurred, no output PDF file produced!
Transcript written on thesis-example.log.

Im currently on a Fed26 System with 5928 installed texlive packages.
(dnf install texlive-scheme-full, dnf install texlive-*)

If i try this with a complete stock Ubuntu 16.04 and texlive-publisher and texlive-full packages it works. So i guess there is no missing package.

I you need specific parts of thesis-example.log, let me know i cant paste it because its too large


问:
Project is not built
Information:Gradle tasks [:aFileDialog:generateDebugSources, :aFileDialog:generateDebugAndroidTestSources, :aFileDialog:mockableAndroidJar, :aFileDialog:prepareDebugUnitTestDependencies, :app:generateDebugSources, :app:generateDebugAndroidTestSources, :app:mockableAndroidJar, :app:prepareDebugUnitTestDependencies, :core:generateDebugSources, :core:generateDebugAndroidTestSources, :core:mockableAndroidJar, :core:prepareDebugUnitTestDependencies, :zxing:generateDebugSources, :zxing:generateDebugAndroidTestSources, :zxing:mockableAndroidJar, :zxing:prepareDebugUnitTestDependencies]
C:\Users\zainm\Desktop\latest\newlatest\kalikoe-wallet\app\build\intermediates\res\merged\debug\values-v26\values-v26.xml
Error:Execution failed for task ':app:processDebugResources'.

com.android.ide.common.process.ProcessException: Failed to execute aapt
  Information:BUILD FAILED

答:
If you use facebook sdk, try this in gradle.

```<code>compile ("com.facebook.android:facebook-android-sdk:[4,5)"){
        exclude group: 'com.android.support'
    }
</code>```

Or search the dependency using V26.

Title: Project is not built

Body:
If you use facebook sdk, try this in gradle.

compile ("com.facebook.android:facebook-android-sdk:[4,5)"){
        exclude group: 'com.android.support'
    }

Or search the dependency using V26.


问:
What is the cost comparison of allocating memory for a reference type vs. a value type in the CLR?
Numerous times I have come across allusions to the effect that allocating an object is expensive.

Most references are either:

oblique, or

are incomplete in that they explain no further as to specifically what that cost is and how it compares to anything that isn't an object, either because the reference is contextual and wants to get on with the main topic it is discussing or is outright dishonest.

Or it is that the references leave out by implication what it is they are comparing the cost of allocating memory for an object with. Okay, creating an object is expensive, but against what? And why? And how? And how much?

I cannot find all the references I have come across in the past but one sudden occurrence has given way to my motivation (and accompanying frustration) to ask this question. It isn't an authoritative source but here it goes:

Example 1

This article on structs says:

With structs you avoid the overhead of objects in the C# language. You
  can combine multiple fields. This reduces memory pressure. And it
  (sometimes) improves performance.

Now, I have no idea what this is talking about. Sure, even the simplest object in the CLR takes up 12 bytes as follows:

4 bytes for something I forget, I presume some kind of a header;

4 bytes for a pointer to the object's method table; and

4 bytes for the first field the object contains, even if the object contains no fields or properties.

Are structs and value types laid out differently? Surely, structs also must have a method table and a header. Then what is the comparative cost of declaring a struct as against an object? Or for that matter, what is the cost comparison of allocating an object as against declaring any value type?

Example 2

Consider another example wherein the underlying motivation is to avoid the allocation of memory for creating a new object.

In the example below, the code caches a StringBuilder so as to avoid creating it afresh, even though all the contents of the object are erased to make place for new contents. It's just the creation of the new object, i.e. the allocation of memory for the new object that is avoided.

From the source of KeyValuePair<TKey, TValue>:

```<code>public override string ToString()
{
    StringBuilder sb = StringBuilderCache.Acquire(0x10);
    sb.Append('[');
    if (this.Key != null)
    {
        sb.Append(this.Key.ToString());
    }
    sb.Append(", ");
    if (this.Value != null)
    {
        sb.Append(this.Value.ToString());
    }
    sb.Append(']');
    return StringBuilderCache.GetStringAndRelease(sb);
}
</code>```

Note the first line of the code calls StringBuilderCache.Acquire. Below is the code for the StringBuilderCache class, whose purpose is to cache an instance of a StringBuilder object so as to avoid re-creating it.

```<code>internal static class StringBuilderCache
{
    // Fields
    [ThreadStatic]
    private static StringBuilder CachedInstance;
    private const int MAX_BUILDER_SIZE = 360;

    // Methods
    public static StringBuilder Acquire(int capacity = 0x10);
    public static string GetStringAndRelease(StringBuilder sb);
    public static void Release(StringBuilder sb);
}
</code>```

And below is the source of the Acquire method on this class. Note that it simply returns a cached instance of StringBuilder, if an instance was previously available, after emptying its contents.

```<code>public static StringBuilder Acquire(int capacity = 0x10)
{
    if (capacity <= 360)
    {
        StringBuilder cachedInstance = CachedInstance;
        if ((cachedInstance != null) && (capacity <= cachedInstance.Capacity))
        {
            CachedInstance = null;
            cachedInstance.Clear();
            return cachedInstance;
        }
    }
    return new StringBuilder(capacity);
}
</code>```

Example 3

I just found an authoritative source alluding to the above said.

The Using Structs page from the C# Programming Guide on the MSDN, almost at the very beginning of the article, states as follows:

Although it is just as convenient to represent a point as a class with
  Auto-Implemented Properties, a struct might be more efficient in some
  scenarios. For example, if you declare an array of 1000 Point objects,
  you will allocate additional memory for referencing each object; in
  this case, a struct would be less expensive.

So, what's this hush-hush much ado about creating new objects?

答:
Based on my reading of the answers linked in Polyfun's comment to the question, I infer that the cost difference incurred in the allocation of new objects as against allocating memory for value-types is due to the difference in the number of CPU instructions.

While traversing a stack or allocating new memory on the stack is a matter of dereferencing the stack pointer by those many number of bytes, each allocation on the heap might involve traversing large portions of the heap because heaps are usually fragmented.

I have to admit this isn't new knowledge to me and I seem to have forgotten this bit while posting this question.

Yet, I want to wait for someone to provide a more rounded-up, educated answer to this question.

Body:
Numerous times I have come across allusions to the effect that allocating an object is expensive.

Most references are either:

oblique, or

are incomplete in that they explain no further as to specifically what that cost is and how it compares to anything that isn't an object, either because the reference is contextual and wants to get on with the main topic it is discussing or is outright dishonest.

Or it is that the references leave out by implication what it is they are comparing the cost of allocating memory for an object with. Okay, creating an object is expensive, but against what? And why? And how? And how much?

I cannot find all the references I have come across in the past but one sudden occurrence has given way to my motivation (and accompanying frustration) to ask this question. It isn't an authoritative source but here it goes:

Example 1

This article on structs says:

With structs you avoid the overhead of objects in the C# language. You
  can combine multiple fields. This reduces memory pressure. And it
  (sometimes) improves performance.

Now, I have no idea what this is talking about. Sure, even the simplest object in the CLR takes up 12 bytes as follows:

4 bytes for something I forget, I presume some kind of a header;

4 bytes for a pointer to the object's method table; and

4 bytes for the first field the object contains, even if the object contains no fields or properties.

Are structs and value types laid out differently? Surely, structs also must have a method table and a header. Then what is the comparative cost of declaring a struct as against an object? Or for that matter, what is the cost comparison of allocating an object as against declaring any value type?

Example 2

Consider another example wherein the underlying motivation is to avoid the allocation of memory for creating a new object.

In the example below, the code caches a StringBuilder so as to avoid creating it afresh, even though all the contents of the object are erased to make place for new contents. It's just the creation of the new object, i.e. the allocation of memory for the new object that is avoided.

From the source of KeyValuePair<TKey, TValue>:

public override string ToString()
{
    StringBuilder sb = StringBuilderCache.Acquire(0x10);
    sb.Append('[');
    if (this.Key != null)
    {
        sb.Append(this.Key.ToString());
    }
    sb.Append(", ");
    if (this.Value != null)
    {
        sb.Append(this.Value.ToString());
    }
    sb.Append(']');
    return StringBuilderCache.GetStringAndRelease(sb);
}

Note the first line of the code calls StringBuilderCache.Acquire. Below is the code for the StringBuilderCache class, whose purpose is to cache an instance of a StringBuilder object so as to avoid re-creating it.

internal static class StringBuilderCache
{
    // Fields
    [ThreadStatic]
    private static StringBuilder CachedInstance;
    private const int MAX_BUILDER_SIZE = 360;

    // Methods
    public static StringBuilder Acquire(int capacity = 0x10);
    public static string GetStringAndRelease(StringBuilder sb);
    public static void Release(StringBuilder sb);
}

And below is the source of the Acquire method on this class. Note that it simply returns a cached instance of StringBuilder, if an instance was previously available, after emptying its contents.

public static StringBuilder Acquire(int capacity = 0x10)
{
    if (capacity <= 360)
    {
        StringBuilder cachedInstance = CachedInstance;
        if ((cachedInstance != null) && (capacity <= cachedInstance.Capacity))
        {
            CachedInstance = null;
            cachedInstance.Clear();
            return cachedInstance;
        }
    }
    return new StringBuilder(capacity);
}

Example 3

I just found an authoritative source alluding to the above said.

The Using Structs page from the C# Programming Guide on the MSDN, almost at the very beginning of the article, states as follows:

Although it is just as convenient to represent a point as a class with
  Auto-Implemented Properties, a struct might be more efficient in some
  scenarios. For example, if you declare an array of 1000 Point objects,
  you will allocate additional memory for referencing each object; in
  this case, a struct would be less expensive.

So, what's this hush-hush much ado about creating new objects?


问:
PHP filters combining into one SQL query
I'm trying to filter through my database according to filters done by visitors.

```<code>$query = "select * from Sheet1 where";

//filter query start
if (!empty($brand)) {
  $branddata = implode("','", $brand);
  //testing removing query
  $query .= " Brand in('$branddata') and";
}

if (!empty($model)) {
  $modeldata = implode("','", $model);
  //testing removing query
  $query .= " Model in('$modeldata') and";
}

/* if(!empty($model) && empty($brand)){

} */

if (!empty($spower) && !empty($epower)) {
  $query .= " Power>='$spower' and Power<='$epower' and";
}

if (!empty($sprice) && !empty($eprice)) {
  $query .= " Doors>='$sprice' and Doors<='$eprice'";
}

$rs = mysqli_query($conn, $query) or die("Error : " . mysqli_error($conn));
</code>```

The result I wish to get is a sql query that works and has correct syntax. Such as select * from Sheet1 where Doors>='$sprice' and Doors<='$eprice', if the visitor is filtering by price.

Currently, my code is made so that it simply adds a certain string to the variable. This means that if you don't filter by model, it skips model, because the model variable is empty. The problem comes to if you filter by power, the SQL will become select * from Sheet1 where Power>='$spower' and Power<='$epower' and. Obviously this doesn't work, so I need help in making the code make sure it works for every combination of filters.

答:
Append $query .= " 1 = 1"; at the end. I did some modification in your given code. Have a look.

```<code><?php
$query = "SELECT * FROM `Sheet1` WHERE";

//filter query start
if(!empty($brand)){
  $branddata = implode("','",$brand);
  $query  .= " (Brand in('$branddata')) AND";
}

if(!empty($model)){
  $modeldata = implode("','",$model);
  $query  .= " (Model in('$modeldata')) AND";
}

if(!empty($spower) && !empty($epower)){
  $query  .= " (Power>='$spower' AND Power<='$epower') AND";
}

if(!empty($sprice) && !empty($eprice)){
  $query  .= " (Doors>='$sprice' AND Doors<='$eprice') AND"; //Added 'AND'
}

$query .= " 1 = 1"; //Added new line

$rs = mysqli_query($conn,$query) or die("Error : ".mysqli_error($conn));
?>
</code>```

Add AND on each query appended in if conditions. Then, at last add $query .= " 1 = 1";. Which will save you from extra AND coming at the end. If none of the conditions satisfy, then your query will be SELECT * FROM Sheet1 WHERE 1 = 1. Simple. And, don't forget to differentiate between conditions in query. Differentiate your conditions like how I did by opening and closing brackets.

Body:
I'm trying to filter through my database according to filters done by visitors.

$query = "select * from Sheet1 where";

//filter query start
if (!empty($brand)) {
  $branddata = implode("','", $brand);
  //testing removing query
  $query .= " Brand in('$branddata') and";
}

if (!empty($model)) {
  $modeldata = implode("','", $model);
  //testing removing query
  $query .= " Model in('$modeldata') and";
}

/* if(!empty($model) && empty($brand)){

} */

if (!empty($spower) && !empty($epower)) {
  $query .= " Power>='$spower' and Power<='$epower' and";
}

if (!empty($sprice) && !empty($eprice)) {
  $query .= " Doors>='$sprice' and Doors<='$eprice'";
}

$rs = mysqli_query($conn, $query) or die("Error : " . mysqli_error($conn));

The result I wish to get is a sql query that works and has correct syntax. Such as select * from Sheet1 where Doors>='$sprice' and Doors<='$eprice', if the visitor is filtering by price.

Currently, my code is made so that it simply adds a certain string to the variable. This means that if you don't filter by model, it skips model, because the model variable is empty. The problem comes to if you filter by power, the SQL will become select * from Sheet1 where Power>='$spower' and Power<='$epower' and. Obviously this doesn't work, so I need help in making the code make sure it works for every combination of filters.

Body:
Append $query .= " 1 = 1"; at the end. I did some modification in your given code. Have a look.

<?php
$query = "SELECT * FROM `Sheet1` WHERE";

//filter query start
if(!empty($brand)){
  $branddata = implode("','",$brand);
  $query  .= " (Brand in('$branddata')) AND";
}

if(!empty($model)){
  $modeldata = implode("','",$model);
  $query  .= " (Model in('$modeldata')) AND";
}

if(!empty($spower) && !empty($epower)){
  $query  .= " (Power>='$spower' AND Power<='$epower') AND";
}

if(!empty($sprice) && !empty($eprice)){
  $query  .= " (Doors>='$sprice' AND Doors<='$eprice') AND"; //Added 'AND'
}

$query .= " 1 = 1"; //Added new line

$rs = mysqli_query($conn,$query) or die("Error : ".mysqli_error($conn));
?>

Add AND on each query appended in if conditions. Then, at last add $query .= " 1 = 1";. Which will save you from extra AND coming at the end. If none of the conditions satisfy, then your query will be SELECT * FROM Sheet1 WHERE 1 = 1. Simple. And, don't forget to differentiate between conditions in query. Differentiate your conditions like how I did by opening and closing brackets.


答:
Give a row number for both the tables and join it with row number.

Query

```<code>;with cte as(
    select [rn] = row_number() over(
        order by [Column_A]
    ), *
    from [Table_A]
),
cte2 as(
    select [rn] = row_number() over(
        order by [Column_A]
    ), *
    from [Table_B]
)
select t1.[Column_A] as [Email_Id], t2.[Column_A] as [Coupon]
from cte t1
join cte2 t2
on t1.rn = t2.rn;
</code>```

Find a demo here

Title: SQL Simple Join with two tables, but one is random

Body:
I am stuck with this. I have a simple set-up with two tables. One table is holding emailaddresses one table is holding vouchercodes. I want to join them in a third table, so that each emailaddress has one random vouchercode.

Unfortunatly I am stuck with this as there are no identic Ids to match both values. What I have so far brings no result:

Select
A.Email
B.CouponCode
FROM Emailaddresses as A
JOIN CouponCodes as B
on A.Email = B.CouponCode

A hint would be great as search did not bring me any further yet.

Edit -

Table A (Addresses)
-------------------
Column A         | Column B
-------------------------
email1@gmail.com  True
email2@gmail.com
email3@gmail.com  True
email4@gmail.com

Table B (Voucher)
-------------------
ABCD1234
ABCD5678
ABCD9876
ABCD5432

Table C
-------------------------
column A | column B
-------------------------

email1@gmail.com  ABCD1234
email2@gmail.com  ABCD5678
email3@gmail.com  ABCD9876
email4@gmail.com  ABCD5432

Sample Data:

Body:
Give a row number for both the tables and join it with row number.

Query

;with cte as(
    select [rn] = row_number() over(
        order by [Column_A]
    ), *
    from [Table_A]
),
cte2 as(
    select [rn] = row_number() over(
        order by [Column_A]
    ), *
    from [Table_B]
)
select t1.[Column_A] as [Email_Id], t2.[Column_A] as [Coupon]
from cte t1
join cte2 t2
on t1.rn = t2.rn;

Find a demo here


答:
I would first pivot the data with pivot_table() and group the data afterward:

```<code>df['Value'] = df['Length']*df['Retry']
df2 = pd.pivot_table(df, index=df.index, columns='Receiver', values='Value')
df2 = df2.groupby([pd.Grouper(freq='1S')]).sum()
</code>```

Title: Pandas Time grouping columns

Body:
I have a df as below:

Index                                Receiver     Length         Retry
1970-01-01 00:00:00.000000000         R1          10             0
1970-01-01 00:00:00.800000000         R1          10             1
1970-01-01 00:00:01.000287000         R2          10             0
1970-01-01 00:00:01.600896000         R2          10             0
1970-01-01 00:00:02.001388000         R1          10             1
1970-01-01 00:00:02.004698000         R1          10             1
1970-01-01 00:00:02.006706000         R2          10             0
1970-01-01 00:00:02.501351000         R2          10             0
1970-01-01 00:00:02.810382000         R1          10             0
1970-01-01 00:00:03.001981000         R1          10             1
1970-01-01 00:00:03.377116000         R1          10             1
1970-01-01 00:00:03.701811000         R2          10             1
1970-01-01 00:00:03.910326000         R2          10             0
1970-01-01 00:00:03.951355000         R2          10             1

I need to group the df by time (1S), and then in each group, add the Length column values if Retry==1 for each R1 and R2.

I used below code, but it seems it ignore rows when there is no Retry=1 for R1 and R2 (i.e. condition is not met).

df2 = df.query("Retry == 1").groupby([pd.Grouper(freq='1S'), 'Receiver']).Length.sum().unstack().fillna(0)

Desired Output is:

Index                        R1    R2
1970-01-01 00:00:00          10    0
1970-01-01 00:00:01          0     0
1970-01-01 00:00:02          20    0
1970-01-01 00:00:03          20    20

Similar problem can be found here.

Body:
I would first pivot the data with pivot_table() and group the data afterward:

df['Value'] = df['Length']*df['Retry']
df2 = pd.pivot_table(df, index=df.index, columns='Receiver', values='Value')
df2 = df2.groupby([pd.Grouper(freq='1S')]).sum()


问:
onPause(); for SwipeRefreshLayout not working
i have a ViewPager with 3 lists in view pager and every list have an simple SwipeRefreshLayout its working well but when RefreshLayout is reffreshing and you press the back button (onPause i think?) the program will crashed andthe error is you cant set null object i know the problem i dont know how to fix it
pls help this is my code

```<code>    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
   View view= inflater.inflate(R.layout.activity_fragment1,container,false);

    mListView = (ListView) view.findViewById(R.id.list_news);
    refresh = (SwipeRefreshLayout) view.findViewById(R.id.refresh);
    refresh.setColorSchemeColors(
            R.color.material_green_200,
            R.color.material_green_400,
            R.color.material_green_600,
            R.color.material_green_800
    );
    refresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            String uri = "http://192.168.1.101/mySite/Flowers/flowers.json";
            JsonArrayRequest request = new JsonArrayRequest(uri,
                    new Response.Listener<JSONArray>() {
                        @Override
                        public void onResponse(JSONArray response) {
                            JsonParser parser = new JsonParser();
                            ArrayList items = parser.parseJson(response);
                            FlowerAdapter adapter = new FlowerAdapter(getContext(),
                                    R.layout.activity_last_news_fragment,items);
                            mListView.setAdapter(adapter);

                        }
                    },
                    new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            Toast.makeText(getContext(), "error", Toast.LENGTH_SHORT).show();
                        }
                    });
            RequestQueue quew = Volley.newRequestQueue(getActivity().getApplicationContext());
            quew.add(request);
            refresh.setRefreshing(false);
        }
    });

   String uri = "http://192.168.1.101/mySite/Flowers/flowers.json";
    JsonArrayRequest request = new JsonArrayRequest(uri,
            new Response.Listener<JSONArray>() {
                @Override
                public void onResponse(JSONArray response) {
                    JsonParser parser = new JsonParser();
                    ArrayList items = parser.parseJson(response);
                    FlowerAdapter adapter = new FlowerAdapter(getContext(),
                            R.layout.activity_last_news_fragment,items);
                    mListView.setAdapter(adapter);

                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Toast.makeText(getContext(), "error", Toast.LENGTH_SHORT).show();
                }
            });

    RequestQueue quew = Volley.newRequestQueue(getActivity().getApplicationContext());
    quew.add(request);
    return view;

}

@Override
public void onPause() {
    if (refresh.isRefreshing()){
        refresh.setEnabled(false);
    }else {
        super.onPause();
    }

}
</code>```

how can i override onpause method to when it called first stop refreshing then pause?

and this is compelete error Log

```<code>12-07 17:11:41.942 13992-13992/app.mma.introsliderproject E/AndroidRuntime: FATAL EXCEPTION: main
                                                                        Process: app.mma.introsliderproject, PID: 13992
                                                                        java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.support.v4.app.FragmentActivity.getApplicationContext()' on a null object reference
                                                                            at app.mma.PokerInfo.twitch.TwitchFragment$2.onResponse(TwitchFragment.java:73)
                                                                            at app.mma.PokerInfo.twitch.TwitchFragment$2.onResponse(TwitchFragment.java:67)
                                                                            at com.android.volley.toolbox.JsonRequest.deliverResponse(JsonRequest.java:65)
                                                                            at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
                                                                            at android.os.Handler.handleCallback(Handler.java:739)
                                                                            at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                            at android.os.Looper.loop(Looper.java:148)
                                                                            at android.app.ActivityThread.main(ActivityThread.java:7409)
                                                                            at java.lang.reflect.Method.invoke(Native Method)
                                                                            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
                                                                            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
</code>```

答:
This is causing issue  Volley.newRequestQueue(getActivity().getApplicationContext()); inside onRefresh(). You will need to check is your activity is in running state i.e is the context null or not.

```<code>@Override
    public void onRefresh () {
        if (YourFragment.this.isVisible()) {
            String uri = "http://192.168.1.101/mySite/Flowers/flowers.json";
            JsonArrayRequest request = new JsonArrayRequest(uri,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        JsonParser parser = new JsonParser();
                        ArrayList items = parser.parseJson(response);
                        FlowerAdapter adapter = new FlowerAdapter(getContext(),
                                R.layout.activity_last_news_fragment,items);
                        mListView.setAdapter(adapter);

                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(getContext(), "error", Toast.LENGTH_SHORT).show();
                    }
                });
        RequestQueue quew = Volley.newRequestQueue(getActivity().getApplicationContext());
        quew.add(request);
        refresh.setRefreshing(false);
        }
    }
</code>```

Put everything inside if(){} to avoid crash

Body:
i have a ViewPager with 3 lists in view pager and every list have an simple SwipeRefreshLayout its working well but when RefreshLayout is reffreshing and you press the back button (onPause i think?) the program will crashed andthe error is you cant set null object i know the problem i dont know how to fix it
pls help this is my code

    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
   View view= inflater.inflate(R.layout.activity_fragment1,container,false);

    mListView = (ListView) view.findViewById(R.id.list_news);
    refresh = (SwipeRefreshLayout) view.findViewById(R.id.refresh);
    refresh.setColorSchemeColors(
            R.color.material_green_200,
            R.color.material_green_400,
            R.color.material_green_600,
            R.color.material_green_800
    );
    refresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            String uri = "http://192.168.1.101/mySite/Flowers/flowers.json";
            JsonArrayRequest request = new JsonArrayRequest(uri,
                    new Response.Listener<JSONArray>() {
                        @Override
                        public void onResponse(JSONArray response) {
                            JsonParser parser = new JsonParser();
                            ArrayList items = parser.parseJson(response);
                            FlowerAdapter adapter = new FlowerAdapter(getContext(),
                                    R.layout.activity_last_news_fragment,items);
                            mListView.setAdapter(adapter);

                        }
                    },
                    new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            Toast.makeText(getContext(), "error", Toast.LENGTH_SHORT).show();
                        }
                    });
            RequestQueue quew = Volley.newRequestQueue(getActivity().getApplicationContext());
            quew.add(request);
            refresh.setRefreshing(false);
        }
    });

   String uri = "http://192.168.1.101/mySite/Flowers/flowers.json";
    JsonArrayRequest request = new JsonArrayRequest(uri,
            new Response.Listener<JSONArray>() {
                @Override
                public void onResponse(JSONArray response) {
                    JsonParser parser = new JsonParser();
                    ArrayList items = parser.parseJson(response);
                    FlowerAdapter adapter = new FlowerAdapter(getContext(),
                            R.layout.activity_last_news_fragment,items);
                    mListView.setAdapter(adapter);

                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Toast.makeText(getContext(), "error", Toast.LENGTH_SHORT).show();
                }
            });

    RequestQueue quew = Volley.newRequestQueue(getActivity().getApplicationContext());
    quew.add(request);
    return view;

}

@Override
public void onPause() {
    if (refresh.isRefreshing()){
        refresh.setEnabled(false);
    }else {
        super.onPause();
    }

}

how can i override onpause method to when it called first stop refreshing then pause?

and this is compelete error Log

12-07 17:11:41.942 13992-13992/app.mma.introsliderproject E/AndroidRuntime: FATAL EXCEPTION: main
                                                                        Process: app.mma.introsliderproject, PID: 13992
                                                                        java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.support.v4.app.FragmentActivity.getApplicationContext()' on a null object reference
                                                                            at app.mma.PokerInfo.twitch.TwitchFragment$2.onResponse(TwitchFragment.java:73)
                                                                            at app.mma.PokerInfo.twitch.TwitchFragment$2.onResponse(TwitchFragment.java:67)
                                                                            at com.android.volley.toolbox.JsonRequest.deliverResponse(JsonRequest.java:65)
                                                                            at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
                                                                            at android.os.Handler.handleCallback(Handler.java:739)
                                                                            at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                            at android.os.Looper.loop(Looper.java:148)
                                                                            at android.app.ActivityThread.main(ActivityThread.java:7409)
                                                                            at java.lang.reflect.Method.invoke(Native Method)
                                                                            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
                                                                            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)

Body:
This is causing issue  Volley.newRequestQueue(getActivity().getApplicationContext()); inside onRefresh(). You will need to check is your activity is in running state i.e is the context null or not.

@Override
    public void onRefresh () {
        if (YourFragment.this.isVisible()) {
            String uri = "http://192.168.1.101/mySite/Flowers/flowers.json";
            JsonArrayRequest request = new JsonArrayRequest(uri,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        JsonParser parser = new JsonParser();
                        ArrayList items = parser.parseJson(response);
                        FlowerAdapter adapter = new FlowerAdapter(getContext(),
                                R.layout.activity_last_news_fragment,items);
                        mListView.setAdapter(adapter);

                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(getContext(), "error", Toast.LENGTH_SHORT).show();
                    }
                });
        RequestQueue quew = Volley.newRequestQueue(getActivity().getApplicationContext());
        quew.add(request);
        refresh.setRefreshing(false);
        }
    }

Put everything inside if(){} to avoid crash


问:
Django url.py regex not working
I am trying to catch all URLs from the safer app and send them to a catch all view; for example:
http://127.0.0.1:8000/saferdb/123

http://127.0.0.1:8000/saferdb/12

I think I have an issue with my reg ex in url.py:

```<code>from django.conf.urls import url
from . import views

app_name = 'saferdb'
urlpatterns = [
    url(r'^/$', views.index, name='index'),
    url(r'^(?P<pk>[0-9]+)/$', views.detail, name='detail'),
]
</code>```

Views.py is the sample code from the django tutorial:

```<code>from django.shortcuts import render

# Create your views here.
from django.http import HttpResponse
from .models import Question

def index(request):
    latest_question_list = Question.objects.all()[:5]
    output = ', '.join([q.DOT_Number for q in latest_question_list])
    return HttpResponse(output)

def detail(request, question_id):
    return HttpResponse("You're looking at question %s." % question_id)
</code>```

I noticed that /saferdb/ will not work unless the reg ex contains a slash:
r'^/$' instead of r'^$' as shown in the django tutorial.

答:
Please add '/' at the end of url in root urls.py of 'safer' app, something similar to this:</p>

```<code>url(r'^saferdb/', include('saferdb.urls', namespace='saferdb'))
</code>```

Title: Django url.py regex not working

Body:
I am trying to catch all URLs from the safer app and send them to a catch all view; for example:
http://127.0.0.1:8000/saferdb/123

http://127.0.0.1:8000/saferdb/12

I think I have an issue with my reg ex in url.py:

from django.conf.urls import url
from . import views

app_name = 'saferdb'
urlpatterns = [
    url(r'^/$', views.index, name='index'),
    url(r'^(?P<pk>[0-9]+)/$', views.detail, name='detail'),
]

Views.py is the sample code from the django tutorial:

from django.shortcuts import render

# Create your views here.
from django.http import HttpResponse
from .models import Question

def index(request):
    latest_question_list = Question.objects.all()[:5]
    output = ', '.join([q.DOT_Number for q in latest_question_list])
    return HttpResponse(output)

def detail(request, question_id):
    return HttpResponse("You're looking at question %s." % question_id)

I noticed that /saferdb/ will not work unless the reg ex contains a slash:
r'^/$' instead of r'^$' as shown in the django tutorial.

Body:
Please add '/' at the end of url in root urls.py of 'safer' app, something similar to this:

url(r'^saferdb/', include('saferdb.urls', namespace='saferdb'))


问:
Retrieving a set of model objects that are indirectly related
I have 4 models:

```<code>class TransitLine(models.Model):
    name = models.CharField(max_length=32)

class Stop(models.Model):
    line = models.ForeignKey(TransitLine, related_name='stops')

class ExitType(models.Model):
    name = models.CharField(max_length=32)
    people_limit = models.PositiveSmallIntegerField()

class Exits(models.Model):
    TOKEN_BOOTH     = 0
    GATE            = 1
    REVOLVING_DOOR  = 2

    EXIT_TYPES = (
        (TOKEN_BOOTH, 'Token booth'),
        (GATE, 'Gate'),
        (REVOLVING_DOOR, 'Revolving door'),
    )
    name = models.CharField(max_length=32)
    stop = models.ForeignKey(Stop, related_name='exits')
    type = models.ForeignKey(ExitType, related_name='exits')
</code>```

I have one TransitLine object. I want to retrieve all the unique ExitType objects that are related to the Stop objects of the TransitLine (that was a mouth full).

Some semi-pseudo code of what I want to do:

```<code>tl = TransitLine.objects.get(id=1)
exit_types = []
for s in tl.stops:
    exit_types.append([e.type for e in s.exits])
unique_exit_types = list(set(exit_types))
</code>```

Obviously, prefer to do this in one QuerySet call. Any suggestions?

答:
I would try something like this:</p>

```<code>ExitType.objects.filter(exits__stop__line=line).distinct()
</code>```

Body:
I have 4 models:

class TransitLine(models.Model):
    name = models.CharField(max_length=32)

class Stop(models.Model):
    line = models.ForeignKey(TransitLine, related_name='stops')

class ExitType(models.Model):
    name = models.CharField(max_length=32)
    people_limit = models.PositiveSmallIntegerField()

class Exits(models.Model):
    TOKEN_BOOTH     = 0
    GATE            = 1
    REVOLVING_DOOR  = 2

    EXIT_TYPES = (
        (TOKEN_BOOTH, 'Token booth'),
        (GATE, 'Gate'),
        (REVOLVING_DOOR, 'Revolving door'),
    )
    name = models.CharField(max_length=32)
    stop = models.ForeignKey(Stop, related_name='exits')
    type = models.ForeignKey(ExitType, related_name='exits')

I have one TransitLine object. I want to retrieve all the unique ExitType objects that are related to the Stop objects of the TransitLine (that was a mouth full).

Some semi-pseudo code of what I want to do:

tl = TransitLine.objects.get(id=1)
exit_types = []
for s in tl.stops:
    exit_types.append([e.type for e in s.exits])
unique_exit_types = list(set(exit_types))

Obviously, prefer to do this in one QuerySet call. Any suggestions?

Body:
I would try something like this:

ExitType.objects.filter(exits__stop__line=line).distinct()


问:
Hide/Show Select2
I want to hide or show my select2, but I can't find a method in the API. I'm using a workaround, hiding the parent, like this:

```<code>$(document).on('change', '.country', function () {
    if ($(this).val() == $(this).data('current-countryCode')) {
        $('#states').parent().show();
    }
    else {
        $('#states').parent().hide();
    }
});
</code>```

But I'd like to know if anyone could help or if even exists such a method in the API.

答:
The problem is that you have to hide all the items associated with the select2 dropdown (all that the plugin generates to do the magic).

I solved using a div that contains the select2 dropdown and show/hide this div.

Title: Hide/Show Select2

Body:
I want to hide or show my select2, but I can't find a method in the API. I'm using a workaround, hiding the parent, like this:

$(document).on('change', '.country', function () {
    if ($(this).val() == $(this).data('current-countryCode')) {
        $('#states').parent().show();
    }
    else {
        $('#states').parent().hide();
    }
});

But I'd like to know if anyone could help or if even exists such a method in the API.