text:
Q: Does using final for variables in Java improve garbage collection? Today my colleagues and me have a discussion about the usage of the final keyword in Java to improve the garbage collection.
For example, if you write a method like:
public Double doCalc(final Double value)
{
   final Double maxWeight = 1000.0;
   final Double totalWeight = maxWeight * value;
   return totalWeight;
}

Declaring the variables in the method final would help the garbage collection to clean up the memory from the unused variables in the method after the method exits.
Is this true?

A: Here's a slightly different example, one with final reference-type fields rather than final value-type local variables:
public class MyClass {

   public final MyOtherObject obj;

}

Every time you create an instance of MyClass, you'll be creating an outgoing reference to a MyOtherObject instance, and the GC will have to follow that link to look for live objects.
The JVM uses a mark-sweep GC algorithm, which has to examine all the live refereces in the GC "root" locations (like all the objects in the current call stack). Each live object is "marked" as being alive, and any object referred to by a live object is also marked as being alive.
After the completion of the mark phase, the GC sweeps through the heap, freeing memory for all unmarked objects (and compacting the memory for the remaining live objects).
Also, it's important to recognize that the Java heap memory is partitioned into a "young generation" and an "old generation". All objects are initially allocated in the young generation (sometimes referred to as "the nursery"). Since most objects are short-lived, the GC is more aggressive about freeing recent garbage from the young generation. If an object survives a collection cycle of the young generation, it gets moved into the old generation (sometimes referred to as the "tenured generation"), which is processed less frequently.
So, off the top of my head, I'm going to say "no, the 'final' modifer doesn't help the GC reduce its workload".
In my opinion, the best strategy for optimizing your memory-management in Java is to eliminate spurious references as quickly as possible. You could do that by assigning "null" to an object reference as soon as you're done using it.
Or, better yet, minimize the size of each declaration scope. For example, if you declare an object at the beginning of a 1000-line method, and if the object stays alive until the close of that method's scope (the last closing curly brace), then the object might stay alive for much longer that actually necessary.
If you use small methods, with only a dozen or so lines of code, then the objects declared within that method will fall out of scope more quickly, and the GC will be able to do most of its work within the much-more-efficient young generation. You don't want objects being moved into the older generation unless absolutely necessary.

A: Final variables cannot be changed after initial assignment (enforced by the compiler).
This does not change the behaviour of the garbage collection as such.  Only thing is that these variables cannot be nulled when not being used any more (which may help the garbage collection in memory tight situations).
You should know that final allows the compiler to make assumptions about what to optimize.  Inlining code and not including code known not to be reachable.
final boolean debug = false;

......

if (debug) {
  System.out.println("DEBUG INFO!");
}

The println will not be included in the byte code.

A: There is a not so well known corner case with generational garbage collectors. (For a brief description read the answer by benjismith for a deeper insight read the articles at the end).
The idea in generational GCs is that most of the time only young generations need to be considered. The root location is scanned for references, and then the young generation objects are scanned. During this more frequent sweeps no object in the old generation are checked.
Now, the problem comes from the fact that an object is not allowed to have references to younger objects. When a long lived (old generation) object gets a reference to a new object, that reference must be explicitly tracked by the garbage collector (see article from IBM on the hotspot JVM collector), actually affecting the GC performance.
The reason why an old object cannot refer to a younger one is that, as the old object is not checked in minor collections, if the only reference to the object is kept in the old object, it will not get marked, and would be wrongly deallocated during the sweep stage.
Of course, as pointed by many, the final keyword does not reallly affect the garbage collector, but it does guarantee that the reference will never be changed into a younger object if this object survives the minor collections and makes it to the older heap.
Articles:
IBM on garbage collection: history, in the hotspot JVM and performance. These may no longer be fully valid, as it dates back in 2003/04, but they give some easy to read insight into GCs.
Sun on Tuning garbage collection

A: Declaring a local variable final will not affect garbage collection, it only means you can not modify the variable.  Your example above should not compile as you are modifying the variable totalWeight which has been marked final.  On the other hand, declaring a primitive (double instead of Double) final will allows that variable to be inlined into the calling code, so that could cause some memory and performance improvement.  This is used when you have a number of public static final Strings in a class.
In general, the compiler and runtime will optimize where it can.  It is best to write the code appropriately and not try to be too tricky.  Use final when you do not want the variable to be modified.  Assume that any easy optimizations will be performed by the compiler, and if you are worried about performance or memory use, use a profiler to determine the real problem.

A: GC acts on unreachable refs. This has nothing to do with "final", which is merely an assertion of one-time assignment. Is it possible that some VM's GC can make use of "final"? I don't see how or why.

A: final on local variables and parameters makes no difference to the class files produced, so cannot affect runtime performance. If a class has no subclasses, HotSpot treats that class as if it is final anyway (it can undo later if a class that breaks that assumption is loaded). I believe final on methods is much the same as classes. final on static field may allow the variable to be interpreted as a "compile-time constant" and optimisation to be done by javac on that basis. final on fields allows the JVM some freedom to ignore happens-before relations.

A: No, it is emphatically not true.
Remember that final does not mean constant, it just means you can't change the reference.
final MyObject o = new MyObject();
o.setValue("foo"); // Works just fine
o = new MyObject(); // Doesn't work.

There may be some small optimisation based around the knowledge that the JVM will never have to modify the reference (such as not having check to see if it has changed) but it would be so minor as to not worry about.
Final should be thought of as useful meta-data to the developer and not as a compiler optimisation.

A: There seems to be a lot of answers that are wandering conjectures. The truth is, there is no final modifier for local variables at the bytecode level.  The virtual machine will never know that your local variables were defined as final or not.
The answer to your question is an emphatic no.

A: Some points to clear up:

*

*Nulling out reference should not help GC. If it did, it would indicate that your variables are over scoped. One exception is the case of object nepotism.

*There is no on-stack allocation as of yet in Java.

*Declaring a variable final means you can't (under normal conditions) assign a new value to that variable. Since final says nothing about scope, it doesn't say anything about it's effect on GC.

A: Well, I don't know about the use of the "final" modifier in this case, or its effect on the GC.
But I can tell you this: your use of Boxed values rather than primitives (e.g., Double instead of double) will allocate those objects on the heap rather than the stack, and will produce unnecessary garbage that the GC will have to clean up.
I only use boxed primitives when required by an existing API, or when I need nullable primatives.

A: All method and variable can be overridden bydefault in subclasses.If we want to save the subclasses from overridig the members of superclass,we can declare them as final using the keyword final.
For e.g-
      final int a=10;
final void display(){......}
Making a method final ensures that the functionality defined in the superclass will never be changed anyway. Similarly the value of a final variable can never be changed. Final variables behaves like class variables.

A: Strictly speaking about instance fields, final might improve performance slightly if a particular GC wants to exploit that. When a concurrent GC happens (that means that your application is still running, while GC is in progress), see this for a broader explanation, GCs have to employ certain barriers when writes and/or reads are done. The link I gave you pretty much explains that, but to make it really short: when a GC does some concurrent work, all read and writes to the heap (while that GC is in progress), are "intercepted" and applied later in time; so that the concurrent GC phase can finish it's work.
For final instance fields, since they can not be modified (unless reflection), these barriers can be omitted. And this is not just pure theory.
Shenandoah GC has them in practice (though not for long), and you can do, for example:
-XX:+UnlockExperimentalVMOptions
-XX:+UseShenandoahGC
-XX:+ShenandoahOptimizeInstanceFinals

And there will be optimizations in the GC algorithm that will make it slightly faster. This is because there will be no barriers intercepting final, since no one should modify them, ever. Not even via reflection or JNI.

A: The only thing that I can think of is that the compiler might optimize away the final variables and inline them as constants into the code, thus you end up with no memory allocated.

A: absolutely, as long as make object's life shorter which yield great benefit of memory management, recently we examined export functionality having instance variables on one test and another test having method level local variable. during load testing, JVM throws outofmemoryerror on first test and JVM got halted. but in second test, successfully able to get the report due to better memory management.

A: The only time I prefer declaring local variables as final is when:

*

*I have to make them final so that they can be shared with some anonymous class (for example: creating daemon thread and let it access some value from enclosing method)

*I want to make them final (for example: some value that shouldn't/doesn't get overridden by mistake)

Does they help in fast garbage collection?
      AFAIK a object becomes a candidate of GC collection if it has zero strong references to it and in that case as well there is no guarantee that they will be immediately garbage collected . In general, a strong reference is said to die when it goes out of scope or user explicitly reassign it to null reference, thus, declaring them final means that reference will continue to exists till the method exists (unless its scope is explicitly narrowed down to a specific inner block {}) because you can't reassign final variables (i.e. can't reassign to null). So I think w.r.t Garbage Collection 'final' may introduce a unwanted possible delay so one must be little careful in defining there scope as that controls when they will become candidate for GC.


text:
Q: Dexguard lib environment check in mobile failing for MI, Appo, Yureka devices I have implemented dexguard in my project. When I run an environment check, some devices work fine and pass the check. However in MI, Appo, Yureka devices, the check is returning it that the device is rooted. I am not able to understand why those this happen.
Please help me to figure out this issue.

A: False positives in DexGuard and other root detection libraries are often down to certain binary checks. The "su" binary and the "busybox" binaries are sometimes found on the ROM of certain manufacturers phones. Try the RootBeer library which can be added as a maven dependency.
https://github.com/scottyab/rootbeer

redpajama_set_name: RedPajamaStackExchange


text:
Q: What reasons are there for a returning by value in C++ Since returning by value is most of the times less efficient than returning a reference, what are some examples where returning by value makes sense or is the only possible way to do it?
edit: I phrased my question incorrectly. I know that with built-in types it is often more efficient to return by value I was mostly referring to cases where you are returning a user-defined type that is larger than a pointer.

A: You're missing the big point here - returning by reference doesn't always makes sense, nor is it always legal. Returning a local by reference leads to undefined behavior. You can return by reference a variable that lives beyond the scope of the function, which can be:

*

*dynamically allocated - bad idea, you have to manage the lifetime yourself

*member of a class - this is commonly used with getters that have 2 versions: one that returns a reference & you can modify the member or a const getter that returns a const reference

*a static local variable (or any variable with static storage) - more often than not, this isn't needed in functions just for returning by reference.

NRVO makes return by value feasible in practice, so unless you have clear measurements that indicate return by value is a bottleneck don't worry about it. Worry instead about the semantics of what either imply.

A: Returning by value is no less efficient in two cases: 1 if you're moving an object (C++11) and 2 if the compiler can elide the copy or optimise the return value away (always possible for built-in types, see also JaredPar's answer).
There are several advantages: 1 no variable needs to be declared prior to the function call (which may not always be possible) and the returned variable type is detectable via auto 2 the intent of setting the returned variable is obvious.
void foo(some_type &obj_ref);
some_type bar();

// using reference
some_type A;          // requires default constructor for A
foo(A);               // modification of A is not obvious

// returning a value
auto B = bar();       // move or copy construction of B

Note that the last statement can either use return-value optimisation or move semantics (C++11)

A: This is what g++ produces by default when using the -O3 flag for a method that returns an integer by reference:
void Foo(int& rc) {
    rc = 42;
}

Becomes:
__Z3FooRi:
Leh_func_begin1:
    pushq   %rbp
Ltmp0:
    movq    %rsp, %rbp
Ltmp1:
    movl    $42, (%rdi)
    popq    %rbp
    ret
Leh_func_end1:

Here's the same method returning by value:
int Foo() {
  return 42;
}

Becomes:
__Z3Foov:
Leh_func_begin1:
    pushq   %rbp
Ltmp0:
    movq    %rsp, %rbp
Ltmp1:
    movl    $42, %eax
    popq    %rbp
    ret
Leh_func_end1:

As you can see, your premise is flawed.  Both versions result in nearly identical machine code.
People have been producing optimizing compilers for C/C++ for three decades.  You can assume they've thought of any common use cases, and done their damnedest to ensure that any common code pattern will produce optimal code.  Never, ever change your coding style to improve performance unless you are armed with profiling results that definitively prove that it there is a difference.  Far too many of these sorts of "optimizations" not only make code harder to read, but actually make performance worse.
EDIT
Here's a similar comparison with a larger type.  Here, both methods return the following struct:
struct Bar
{
    unsigned int a;
    unsigned int b;
    unsigned int c;
    unsigned int d;
};

This code:
void Foo(Bar& rc) {
    rc.a = 1;
    rc.b = 2;
    rc.c = 3;
    rc.d = 4;
}

produces this output:
__Z3FooR3Bar:
Leh_func_begin1:
    pushq   %rbp
Ltmp0:
    movq    %rsp, %rbp
Ltmp1:
    movl    $1, (%rdi)
    movl    $2, 4(%rdi)
    movl    $3, 8(%rdi)
    movl    $4, 12(%rdi)
    popq    %rbp
    ret

Leh_func_end1:
On the other hand, this return by value version:
Bar Foo() {
    Bar rc;
    rc.a = 1;
    rc.a = 2;
    rc.a = 3;
    rc.a = 4;

    return rc;
}

ends up producing fewer machine code instructions:
__Z3Foov:
Leh_func_begin1:
    pushq   %rbp
Ltmp0:
    movq    %rsp, %rbp
Ltmp1:
    movl    $4, %eax
    xorl    %edx, %edx
    popq    %rbp
    ret
Leh_func_end1:

If you want to do these comparisons yourself in g++, use g++ -S -O3.  Other compilers will have similar methods of producing assembly.

A: I think you are starting this question with the incorrect assumption that returning by value is less efficient than other forms of return.  This is just simply not the case for a few reasons

*

*Simple built-in types like int, char, etc ...  can be returned via a register

*Even large values can be returned by value efficiently due to named return value optimization (NRVO)

There are certainly cases where return by value is inefficient.  However this does not mean that every case is so.

A: A Beginner's Answer:
Returning by value makes sense if I do not need the variables I am passing to be changed but just want the value of the solution of the function for purposes like printing the value and I do not need to store the answer anywhere!
Just trying to help!

A: Your assumption is disputable (comments have been given), but for the question: I recommend reading
Scott Meyers' Effective C++ (Third Edition),
Item 21: Don't try to return a reference when you must return an object.
The example is (slightly modified):
class Rational {
public:
    Rational(int numerator = 0, int denominator = 1)
        : n(numerator), d(denominator) {}

    // ...

private:
    int n, d;

    friend Rational operator*(const Rational& lhs, const Rational& rhs);
};

The use is like this:
    Rational a(1, 2);    // a = 1/2
    Rational b(3, 5);    // b = 3/5

    Rational c = a * b;  // c should be 3/10

And the implementation:
Rational operator*(const Rational& lhs, const Rational& rhs)
{
    Rational result(lhs.n * rhs.n, lhs.d * rhs.d);
    // Would you return that local variable by reference?
    //  You don't want a dangling reference...
    //  Returning by value is the correct thing to do.
    return result;
}

or shorter:
Rational operator*(const Rational& lhs, const Rational& rhs)
{
    return Rational(lhs.n * rhs.n, lhs.d * rhs.d);
}

(you can make it inline and put it in the header).
Read the complete Item for a review of the "alternatives" (dynamic allocation, static variables...) and a detailed argumentation of why they're all bad (that's the point: they're all bad: subtly dangerous or even downright incorrect).
Finally, quoting from there:

The right way to write a function that must return a new object is to
  have that function return a new object.

So: when it's the natural semantics, just return by value.

A: You return by value for example when you want to modify the returned object without affecting the object which member function was called. In the following example you can modify b (which is returned by value) without changing object a (and value _val inside it):
#include<iostream>
using namespace std;

class A{
public:
    A(int val) : _val(val){}
    int val(){return _val;}
private:
    int _val;
};

int main()
{
        A a(3);
        int b = a.val();
        ++b;
        cout << "a.val() = " << a.val() << endl;
        cout << "b = " << b << endl;
}

See more reasons


text:
Q: Show $\lim\limits_{i\to\infty} \mathbb P[e^{\sum_{i=0}^n Z_i}>1]=\frac 1 2$ for $(Z_i)_{i\in \mathbb{N}}$ $iid$ $\mathbb E[Z_i]=0, Var[Z_i]=4$
Show $\lim\limits_{i\to\infty} \mathbb P[\mathrm{e}^{\sum_{i=0}^n Z_i}>1]=\frac 1 2$ for $(Z_i)_{i\in \mathbb{N}}$ $iid$ $\mathbb E[Z_i]=0, Var[Z_i]=4$

I think it is intuitively clear but how am I able to show this rigorously?
Of course $\mathbb P[\mathrm{e}^{\sum_{i=0}^n Z_i}>1]=\mathbb P[\sum_{i=0}^n Z_i>0]$ and tried to use Chebyshev's and Markov's inequality but it didn't work because of the "$0$" and I would have only gotten an inequality either way.
$Var[\sum_{i=0}^n Z_i]=4n$ and $\mathbb E[\sum_{i=0}^n Z_i]=0$ because of independence.
So what would be the correct approach?

A: From Central Limit Theorem, it follows that $$ \lim_{n\to \infty} P \left (\frac{\sum_{i=0}^n Z_i}{2\sqrt{n}}  > 0 \right) = 1 - \Phi (0) = \frac{1}{2}$$


text:
Q: Get old tweets by user using tweepy I am trying to gather the tweets of a user navalny, from 01.11.2017 to 31.01.2018 using tweepy. I have ids of the first and last tweets that I need, so I tried the following code:
import tweepy

consumer_key = ''
consumer_secret = ''
access_token = ''
access_token_secret = ''

auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)

api = tweepy.API(auth)

t = api.user_timeline(screen_name='navalny', since_id = 933000445307518976, max_id = 936533580481814529)

However, the returned value is an empty list.

*

*What is the problem here?

*Are there any restrictions on the history of tweets that I can get?

*What are possible solutions?

A: Quick answer:
Using Tweepy you can only retrieve the last 3200 tweets from the Twitter REST API for a given user.
Unfortunately the tweets you are trying to access are older than this.
Detailed answer:
I did a check using the code below:
import tweepy
from tweepy import OAuthHandler

def tweet_check(user):
    """
    Scrapes a users most recent tweets
    """
    # API keys and initial configuration
    consumer_key = ""
    consumer_secret = ""
    access_token = ""
    access_secret = ""
    # Configure authentication
    authorisation = OAuthHandler(consumer_key, consumer_secret)
    authorisation.set_access_token(access_token, access_secret)
    api = tweepy.API(authorisation)
    # Requests most recent tweets from a users timeline
    tweets = api.user_timeline(screen_name=user, count=2,
                               max_id=936533580481814529)
    for tweet in tweets:
        tid = tweet.id
        print(tid)

twitter_users = ["@navalny"]

for twitter_user in twitter_users:
    tweet_check(twitter_user)

This test returns nothing before 936533580481814529
Using a seperate script I scraped all 3200 tweets, the max Twitter will let you scrape and the youngest tweet id I can find is 943856915536326662
Seems like you have run into Twitter's tweet scraping limit for user timelines here.


text:
Q: Erro: "Não foi possível encontrar o símbolo BookmarkColumns" Tenho um projeto de 3 anos atras e preciso fazer ele voltar a vida, porem é cheio de complicações com atualizações, me deparei com um impace que a Browser Bookmark Changes foi removida.
Alguém sabe como posso resolver isso?
Nessa método que estou usando a chamada do Browser.BookmarkColumns:
@Override
  protected void onListItemClick(ListView l, View view, int position, long id) {
    Adapter adapter = getListAdapter();
    if (position >= 0 && position < adapter.getCount()) {
      String packageName = ((AppInfo) adapter.getItem(position)).getPackageName();
      Intent intent = new Intent();
      intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
      intent.putExtra(Browser.BookmarkColumns.URL, "market://details?id=" + packageName);
      setResult(RESULT_OK, intent);
    } else {
      setResult(RESULT_CANCELED);
    }
    finish();
  }

Em outro lugares eu também faço a chamada desse Browser.BookmarkColumns ou do Browser.BOOKMARKS_URI

A: O problema provavelmente é que, com as "actualizações", foi declarado o compileSdkVersion para a versão 6.0 ou superior.
A versão 6.0 remove a compatibilidade com "favoritos globais".
Extracto da documentação:

Esta versão remove a compatibilidade com favoritos globais. Os métodos android.provider.Browser.getAllBookmarks() e android.provider.Browser.saveBookmark() foram removidos. Da mesma forma, as permissões READ_HISTORY_BOOKMARKS e WRITE_HISTORY_BOOKMARKS foram removidas. Se o aplicativo for voltado ao Android 6.0 (API de nível 23) ou posterior, não acesse as marcações do provedor global nem use as permissões de adição aos favoritos. Em vez disso, o aplicativo deve armazenar internamente os favoritos.

Ou declara compileSdkVersion=22 ou a sua aplicação terá de guardar/gerir os seus Bookmarks


text:
Q: Display in alert window copied HTML element I have this code:
<fieldset>
    <legend>Professional Ditails</legend>

                Institution
                <input type="text" name="inptInstitution" required="required" />

                Qualification
                <select name="cars">
                    <option value="volvo">Volvo</option>
                    <option value="saab">Saab</option>
                    <option value="fiat">Fiat</option>
                    <option value="audi">Audi</option>
                </select>

    <button type="button" name="button" onclick="test()">
        test</button>
</fieldset>


text:
Q: Resize event on multiple select control I have a multiple select html element.
I want to catch the resize event, so I can store the latest value.
<select multiple="multiple" class="ra-multiselect-collection" style="resize: vertical; margin-top: 0px; margin-bottom: 5px; height: 527px;"></select>

The following code doesnt work:
$('.ra-multiselect-collection').on( 'resize', function(){
    alert('resized');
});

Any ideas?

A: Well, I don't think that you can bind a resize event to a DOM element, but check this out:
$("select").on("mouseup", function()
{
    var el = $(this);

    if (el.data("old-height") == null || el.data("old-height") != el.height())
    {
        alert("resized!");
    }

    el.data("old-height", el.height());
}).data("old-height", $("select").height());

Fiddle
I have used mouseup event checking the old height stored in a data property with the current height on the moment of the event. If they are different, you get a resize event. Not a pretty beautiful workaround, but it seems to work.
I could not test on IE because it doesn't support that property and on Firefox, it works nice but it seems that you can double-click the resize corner and it returns to the initial size and this doesn't trigger the event actually.
In your case, as you're using a class to select those elements, you can do this:
$(".ra-multiselect-collection").each(function()
{
    $(this).on("mouseup", function()
    {
        var el = $(this);

        if (el.data("old-height") == null || el.data("old-height") != el.height())
        {
            alert("resized!");
        }

        el.data("old-height", el.height());
    }).data("old-height", $(this).height());
});

Didn't tested but it should work.

A: Finally I used resizable function from jQuery UI
http://jqueryui.com/resizable/
This is my code:
  $('.ra-multiselect-collection').first().resizable({
    resize: function() {
      alert('resized');
    }
  });

Maybe that .first() isn't necessary

A: You dont have resize event here, but u can store the size on mousedown event, and check if it changed on mouseup event


text:
Q: Can I use a set builder with set builders inside? Say, I have two sets defined as below.
$A = \{(x, y)\ | \ x + y > 2, \ \, x,y \in \mathbb R \}$
$B = \{(y, z)\ | \ y + z < 2, \ \, y,z \in \mathbb R \}$
Now, I'm wondering if it is possible to define a set using the predefined sets as below.
$C = \begin{equation}
\left\{
  (x, y, z) \;\middle|\;
  \begin{aligned}
  & (x, y) \in A \\
  & (y, z) \in B \\
  \end{aligned}
\right\}
\end{equation}
$
My goal is to define the set C with elements of $x, y,$ and $z$ simultaneously satisfying two pairwise relationships as defined in set $A$ and $B$ such that $C=\{(1, 1.1, 0), (-1.1, 4, -2.5), ...\}$.
Thanks for your advice in advance!

A: You can. In fact, you have done it in your first example. $\mathbb{R}$ is a predefined set, in particular, the set of real numbers.


text:
Q: Accessing array inside of Object I have a functional component that renders out the object values
    const MovieItemDetails = (props) => {
  return

      <img key={props.movieDetails.id} src={`https://image.tmdb.org/t/p/w1280${props.movieDetails.backdrop_path}`} alt={props.movieDetails.title} className='header-item-image' />
      {props.movieDetails.title}
      <img src={`https://image.tmdb.org/t/p/w185/${props.movieDetails.poster_path}`} alt={props.movieDetails.title} className='header-item-poster' />

{props.movieDetails.genres[0].name}

}

I'm trying to access the nested array as seen in the image below

What I want is the genre name of the first array, I have tried {props.movieDetails.genres[0].name}
but I get 'TypeError: Cannot read property '0' of undefined'
EDIT: full Object

A: Instead of referring the nested array time and again, better to extract it in const at the start and check for its value before rendering. Please see below:
const MovieItemDetails = (props) => {
      const {movieDetails} = {...props};
      return (movieDetails && movieDetails.genres ?

          <img key={movieDetails.id} src={`https://image.tmdb.org/t/p/w1280${movieDetails.backdrop_path}`} alt={movieDetails.title} className='header-item-image' />
          {movieDetails.title}
          <img src={`https://image.tmdb.org/t/p/w185/${movieDetails.poster_path}`} alt={movieDetails.title} className='header-item-poster' />

{movieDetails.genres[0].name}

 : null);
}

A: I would rather suggest to call it in right way. Please have a look at the following code.
import React from 'react'
import Header from './Header'
import Main from './Main'
const MovieItemDetails = (props) => {
  return

     <img key={props.movieDetails.id} src= {`https://image.tmdb.org/t/p/w1280${props.movieDetails.backdrop_path}`} alt= {props.movieDetails.title} className='header-item-image' />
     {props.movieDetails.title}
     <img src={`https://image.tmdb.org/t/p/w185/${props.movieDetails.poster_path}`} alt={props.movieDetails.title} className='header-item-poster' />

{props.movieDetails.genres[0].name}

}
const movieDetails = {
  id: 1,
  title: 'Movie',
  genres : [
    {id: 0, name : 'Songs'}
  ]
}
const App = () => (

    <MovieItemDetails movieDetails={movieDetails}  />
    {MovieItemDetails({movieDetails})}

)

export default App


text:
Q: pandas.date_range resulting in a repeated 'sticky' warning: "414: FutureWarning: 'summary' is deprecated and will be removed in a future version." EDIT 6/20/18:
As pointed out by @aydow, this is similar to this:
How to suppress Pandas Future warning ?
The solution from that page did get rid of the warning for me:
import warnings
warnings.simplefilter(action='ignore', category=FutureWarning)

However, there is no discussion of why (once I run pd.date_range) I get the warning for every command I enter into the console.
/end edit 6/20/18
First post, so my apologies if I mess anything up or leave out any critical information. I'm also fairly new to python, so its very possible that I'm making a stupid mistake somewhere.  However, I can't find any info on this problem.
I'm calling the warning "sticky" for lack of better vocabulary on my part - once I get the warning once (it shows up after running pandas.date_range), I get the same warning pretty much regardless of what I enter into the python console.  Details of what I'm trying to do and the results are below.
Thanks-in-advance for any help,
-Jeremy
Task:
Given a start year, a number of bins, and a timestep, I'm trying to create a series of timestamps using the pandas date_range function.  Sample code:
import pandas as pd
NumBins = 10
timestep=3
startYr = 2018
BinList =
pd.date_range(start='1/1/'+str(startYr),periods=NumBins,freq=str(timestep)+'min')

While this does result in the expected output (10 timestamps at 3-minute intervals starting at midnight on Jan 1, 2018), I get the following warning message:
C:\Users\mattje\AppData\Local\Continuum\anaconda3\lib\site-packages\spyder\widgets\variableexplorer\utils.py:414: FutureWarning: 'summary' is deprecated and will be removed in a future version.
  display = value.summary()

QUESTION:
Why does this warning message start showing up after I've run the date_range function regardless of what variable I try to inspect?
For example, if I run the first 4 lines of code and then enter 'timestep' into the console I get the following, I get the following (note the lack of warning after the output):
import pandas as pd
NumBins = 10
timestep=3
startYr = 2018

timestep
Out[2]: 3

After I run the
pd.date_range(start='1/1/'+str(startYr),periods=NumBins,freq=str(timestep)+'min')

line, I get the following when I enter 'timestep' into the console:
timestep
Out[4]: 3C:\Users\mattje\AppData\Local\Continuum\anaconda3\lib\site-packages\spyder\widgets\variableexplorer\utils.py:414: FutureWarning: 'summary' is deprecated and will be removed in a future version.
  display = value.summary()

If I make a new variable, I get:
test = 5
C:\Users\mattje\AppData\Local\Continuum\anaconda3\lib\site-packages\spyder\widgets\variableexplorer\utils.py:414: FutureWarning: 'summary' is deprecated and will be removed in a future version.
  display = value.summary()

If I import numpy I get:
import numpy as np
C:\Users\mattje\AppData\Local\Continuum\anaconda3\lib\site-packages\spyder\widgets\variableexplorer\utils.py:414: FutureWarning: 'summary' is deprecated and will be removed in a future version.
  display = value.summary()

OTHER INFO

*

*Closing the console and opening a new one resets the warning and I don't get it until I run the pd.date_range function again

*The warning does not seem to affect operation; I get the outputs and results I'm expecting.  It's just weird and annoying.

*I'm using Anaconda Navigator 1.8.7 and have recently (in the last week) used conda to update all packages

*I'm using spyder 3.2.8 and python 3.6

A: Try the following:
import warnings
warnings.simplefilter(action='ignore', category=FutureWarning)


text:
Q: Ubuntu Touch install failure on Galaxy Nexus The command phablet-flash -b does not give enough time for my device to reboot into recovery mode before it pushes the phablet zip file across. I tried doing the command again once it finally went into recovery mode giving this result:
user/Downloads/phablet-flash/152$ phablet-flash -b
Device detected as /sbin/sh: getprop: not found
Unsupported device, autodetect fails device

But I can understand why that didn't work. I tried to manually push the file across myself but then it wouldn't deploy.
Are there any manual instructions I can perform under terminal to get it to continue once in recovery mode? Or is there a way to magically pause the terminal when it's waiting for the device to reboot into recovery mode? Or where in the code can I change it from, say, Sleep 5 sec to sleep 10 sec.

A: I figured it out. Either it was a coincidence that it just happened to work this time or I was right that I just had to change the sleep time in the script /usr/bin/phablet-flash.
Open phablet-flash through terminal (as root so you can edit it)
sudo -H gedit '/usr/bin/phablet-flash'

and in the area:
@adb_errors
def autodeploy(adb, artifact):
    ''' Pushes artifact to devices sdcard and deploys'''
    if not artifact:
        return
    # Can't wait-for-device here
    sleep(15)
    adb.push(artifact, '/sdcard/autodeploy.zip')
    log.info('Deploying Ubuntu')
    adb.reboot(recovery=True)
    log.info('Installation will complete soon and reboot into Ubuntu')

I changed
sleep(15)

to
sleep(30)

You can then re-run the 'phablet-flash -b' command and it should work

Also if any other noobs like me trying to reinstall Android have the problem of deploying:
./flash-all.sh

and get the error
bash: ./flash-all.sh: Permission denied

Go to your android distribution folder, open flash-all.sh and copy and paste the commands from that script to the terminal and run them separately, simple as.


text:
Q: Can stormpath access token be deleted without knowing the secret api key? I am able to delete stormpath user access token(using access token href) using "rest client" without passing in authorization header, is this intended behaviour?

A: Sorry for asking this one. Seems like my rest client was caching the authentication headers, stormpath seems to be working as intended.


text:
Q: How to order a list in numerical order (with both numbers and words in the same list) I need order a list in numerical order which contains strings with both numbers and words for example : "100 | Bob". Here is my code so far:
List<string> candidate = new List<string>();
candidate.Add("10 | Dave");
candidate.Add("200 | Bob");
candidate.Add("1000 | Larry");

candidate.Sort();

int i = 0;
while(i < candidate.Count)
{
    Console.WriteLine(candidate[i]);
    i++;
}

Console.ReadKey();

It currently outputs:
10 | Dave
1000 | Larry
200 | Bob

But I would like it to output:
10 | Dave
200 | Bob
1000 | Larry

any help or advice would be greatly appreciated.
Thanks Jarvey.

A: I use LINQ for this purpose usually:
var res = candidate.OrderBy(c => int.Parse(string.Join("", c.TakeWhile(char.IsDigit))))
         .ToList();

Another way would be pad with zeroes to the same length just like below:
var res = candidate.OrderBy(c => c.PadLeft(candidate.Max(x => x.Length), '0')).ToList();


text:
Q: TypeError: unsupported operand type(s) for -=: 'str' and 'float' I've tried to write a program which converts decimal to binary and vice versa but when I try 23, it flags line 17 (answer2 -= x) as a type error.
    import math

    x = 4096
    y = ""
    z = 10
    q = 1
    final_answer = 0

    answer1 = str(input("Do you want to convert decimal into binary (1) or binary into decimal      (2)?"))
    if answer1 == "1":
        answer2 = input("What number do you want to convert to binary? It can't be larger than   4096")
        p = answer2.isdigit()
        if p:
            for i in range(13):
                if int(answer2) >= x:
                    y = y + "1"
                    answer2 -= x
                else:
                    y = y + "0"

                x /= 2

            print(y)
        elif not p:
            print("That's not a number")

I tried to convert the variables of answer2 and x to float and int but the same problem still comes up.

A: Your variable is still a string when you apply an operation involving a numeric value. In your case, you still need to convert the variable to a float:
answer2 = float(answer2)

Furthermore, I do not know if isdigit() catches floats (involving a decimal point). This post might help out if you get stuck there: Using isdigit for floats?


text:
Q: "Error opening associated documents" message when loading VS When loading up a solution in VS2008 I get this message:

An error was encountered while opening
  associated documents the last time
  this solution was loaded. Document
  load is being skipped during this
  solution load in order to avoid that
  error.

It shut down immediately the first time I opened it.  The next time I opened it, VS popped up a message box but did not shut down at first; however, it did shut down when I clicked a usercontrol or ASPX page.
How can I find which document is causing the problem?
Thanks...

A: This seems to be related to other view-launch bugs that have been in Visual Studio since VS6.0, by my recollection.
One workaround that usually works for me for VS2003-VS2010 is to delete the .SUO file corresponding to the solution file. In VS6.0, you may also have to delete the .NCB file as well.
There are other reports of similar VS solution launch bugs in Microsoft Connect. Here's a ticket relating to a similar bug in VS2010, which I believe is the same as your issue.
"error on loading solution 100% of the time" @ Microsoft Connect

A: Open your documents one at a time until it crashes.
Once you isolate the crash, you can open a second copy of VS and attach its debugger to the first copy, then crash it and look at the exception in the second one.  (Use Debug, Exceptions to break on all exceptions)

A: There is a lot going on in VS, especially when a bunch of designers are open when you closed last or perhaps a dirty close.
Try to keep the number of documents you have open when you close a solution to a reasonable number.
Bottom line is: It happens. Unless it becomes a regular occurrence you should not worry too much. If you consistently crash follow SLaks advice.


text:
Q: Why does this code print a result of '7'? I recently start to learn PHP.
   <?php
    echo (int) ( (0.1+0.7) * 10 ); // prints '7', why not '8' ?
    ?>

Please convince me of this type-conversion process.

A: You are running into floating point inaccuracy.
0.1 + 0.7 is not exactly 0.8, but slightly less. The cast to int simply truncates the value and yields 7 as the result.
To get the correct result use rounding:
<?php
    echo (int) round( (0.1+0.7) * 10 );
?>

A: From PHP.net

It is typical that simple decimal fractions like 0.1 or 0.7 cannot be converted into their internal binary counterparts without a small loss of precision. This can lead to confusing results: for example, floor((0.1+0.7)*10) will usually return 7 instead of the expected 8, since the internal representation will be something like 7.9.
This is due to the fact that it is impossible to express some fractions in decimal notation with a finite number of digits. For instance, 1/3 in decimal form becomes 0.3.

A: From http://php.net/manual/en/language.types.float.php

It is typical that simple decimal
  fractions like 0.1 or 0.7 cannot be
  converted into their internal binary
  counterparts without a small loss of
  precision. This can lead to confusing
  results: for example,
  floor((0.1+0.7)*10) will usually
  return 7 instead of the expected 8,
  since the internal representation will
  be something like 7.9.

A: As others have said, it's due to a loss of precision, as revealed by:
<?php
printf("%30.27f\n", (0.1 + 0.7) );
printf("%d\n", (int) (0.1 + 0.7) );
printf("%30.27f\n",  ( (0.1+0.7) * 10 ) );
printf("%d\n", (int) ((0.1 + 0.7) * 10) );
?>

which outputs:

0.799999999999999933386618522
     0
     7.999999999999999111821580300
     7

A: You're probably seeing a floating point rounding error, and when you int() it, it goes from being 7...9 to 7.

A: I am not sure, but this is probably because the int cast is truncating.
.1 + .7 might result in .799999999999999999999999 and
multiplying this by 10 = 7.9999999999999999999
(int) truncates this to 7.


text:
Q: Is (,$arrr) the best way to pass a single array as an argument list to a powershell invoke-command cmdlet? I want to pass an array to a PowerShell script block. This is the accepted method:
$arr = 1..4;
invoke-command -ScriptBlock { Param($li); $li | %{$_}} -ArgumentList (,$arr)

From my investigations, these alternatives work too:
invoke-command -ScriptBlock { Param($li); $li | %{$_}} -ArgumentList $arr,$arr
invoke-command -ScriptBlock { Param($li); $li | %{$_}} -ArgumentList $arr,$null

And the same issue applies when used list this
$arr = 1..4;
$sb = { Param($li); $li | %{$_}}
$sb.Invoke((,$arr))

I understand the reason for the (,$arr) syntax is that the -ArgumentList parameter is expecting an array of parameters to pass to the script block, and if it gets a single array as its value, it will unpack the array and pass the contents to the script block as multiple parameters. I credit these answers how and why for helping me through this.
The accepted solution looks very ugly to me and I wonder it there is a cleaner way that might be closer to what the designers of PowerShell intended. Please comment.
Perhaps the answer is
& $sb $arr.

Please comment.


text:
Q: Keep jQuery modal open on C# button click I have a modal on a page that was suposed to remain open when I click a link on a ASP.NET GridView row. The click of this link fires the click of another button that calls a function on server-side. My idea was to keep my modal open, so I could fill it with what I need, using code behind. The problem is that after the modal is opened and the button is fired, the modal closes (if I remove the button click, everything works fine). I would like to know if it's possible to make it remain open. Here's what I have:
The function that open the modal and fire the button:
function showDetails()
{
    $("#modalDetails").dialog("open");

    var btnEmbedDetails = document.getElementById('<%=btnEmbedDetails.ClientID %>');
    btnShowDetails.click();
}

The link inside the GridView row:
<asp:TemplateField ItemStyle-Width="100px" HeaderText="Details">
    <ItemTemplate>
        Open it
    </ItemTemplate>
</asp:TemplateField>

The button that calls the function on code behind:
<asp:Button ID="btnEmbedDetails" runat="server" OnClick="EmbedDetails" style="display:none;" />

The function on code behind:
public void EmbedDetails(object sender, EventArgs e)
{
    string ok = "ok";
}


text:
Q: How to compute a knee in k-distance plot? I want to implement some kind of improvement of DBSCAN algorithm, where user do not need to enter input parameters (minPts and Eps). My idea is to use the K-distances plot, but what is the best method to compute the 'knee' of this plot? How to count when there are 2 or more knees on the plot?
Where I can find the source code for some DBSCAN improvement, like AUTODBSCAN, VDBSCAN, PDBSCAN or DBSCAN-DLP? Im looking for some basics, but nowhere I can find a good help. Maybe you've seen somewhere sample source codes?

A: DBSCAN has already been improved to death.
In Google Scholar, it has 5361 citations, and probably 1000+ of these "improve" DBSCAN. And probably a dozen of these use the k-distance plot. But none of these are used in practise.
If you want to continue this line of research, best get updated on what has been done since.
In particular, have a look at OPTICS which does away with the Epsilon parameter completely (except for performance reasons when using indexes).
Also have a look at HDBSCAN* by one of the original DBSCAN authors, Joerg Sander. That will likely be the most important DBSCAN extension besides his work on OPTICS and GDBSCAN.


text:
Q: How to create bootable Windows 10 installer USB for PC? I've downloaded Windows 10 from Microsoft and want to create a bootable USB stick for a PC. I've tried to flash the image with dd, but the stick did not boot.
Then I've flashed the image with bootcamp, it didn't boot either on my PC; it did however boot on my Mac.
How can I create a bootable Windows 10 USB stick to be bootable not on a Mac, but on a PC?

A: From Create a bootable Windows 10 installation USB on macOS
Step 1: download Windows 10 ISO
Step 2: install Homebrew
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"

Step 3: install wimlib
brew install wimlib

Step 4: format USB flash drive as "MS-DOS (FAT)" with "Master Boot Record" scheme
Step 5: open Win10_21H1_English_x64.iso and copy files to USB flash drive skipping install.wim found at sources/install.wim (which is larger than 4GB FAT32 limit)
rsync -rv --exclude install.wim" /Volumes/CCCOMA_X64FRE_EN-US_DV9/ /Volumes/WINDOWS10/

Step 6: split install.wim

Heads-up: replace CCCOMA_X64FRE_EN-US_DV9 with actual Windows 10 ISO volume name and UNTITLED with USB flash drive volume name.

wimlib-imagex split /Volumes/CCCOMA_X64FRE_EN-US_DV9/sources/install.wim /Volumes/WINDOWS10/sources/install.swm 4000

Done

A: I followed the instructions in Create a bootable Windows 10 installation USB on macOS:

*

*Preparing The USB drive
Well, this was simple for my Windows 11 laptop:

*

*You firstly plug the USB drive into your Mac,

*Open Finder.

*Open the Applications folder (for example by selecting Go > Applications from the menu bar) and look for a folder named "Utilities".

*Double-click it and search for the Disk Utility app.

*Launch it and in the sidebar, search for your USB drive by name and select it (NOTE: the USB drive's name is originally "Unnamed" unless changed by a user).

*You then must find the Erase button located on the top right. Click it and select FAT/FAT32 as the format and "Master Boot Record" as scheme.

*When done, double-click the USB drive icon on the desktop to open it.

*Preparing The Media
Next, head to this link and download the ISO file. Once this file is downloaded, mount it by double-clicking it.

*Moving Files
Follow these instructions carefully:

*

*On the ISO file window, open the folder named 'sources'.

*Once in the folder, do Cmd+A and search for the file named install.wim and do Cmd+click to deselect it.

*Do Cmd+C

*Switch to the USB drive window and make a folder named 'sources', double-click it, and do Cmd+V.

*Now, on both the ISO file and USB drive windows, click the back button to go to the root folder and move all files except the 'source' folder from the ISO file window to the USB drive window. When the file moving is done, you can eject and unplug the USB drive.

*Installation Process

*

*Plug the USB drive into the corrupted or empty computer and go to your boot selector by turning on your device and holding Esc down.

*After you see the startup menu, use the key combination that it says beside select boot device or boot selector or boot options.

*When you're done, then select the USB drive. Once down click Continue and unplug the USB drive.

*Plug the USB drive into the Mac, open Disk Utility again select the USB drive, erase it but this time choose ExFAT as the format. Once done, copy all the files from the ISO drive into the USB drive.

*Eject the USB drive and plug it into the Windows machine again.

*Then Click Install or the button in the middle of the screen and keep the USB plugged in until you have finished setup and are at the Desktop.

*Final Setup
Finish setting up Windows and done!

A: Step 1----------------------------
Get an 8GB USB Flash Drive as this is easily to make on it even though it may seem small, but Windows USB Flash Drive Install/Windows Install via USB Flash Drive only takes about 4GB to 7GB of space.
SAVE FILES THAT ARE IMPORTANT TO YOU IF YOU ARE FORMATTING A USB FLASH DRIVE IN USE
You Need to format this USB Flash Drive to FAT32, as come computer do not support exFat on BIOS or when booting up from my experience. Once Formatted you have prepared the USB Flash Drive to add files to it.
Step 2----------------------------
You now need a separate computer, a computer that you can download and move files. Not a phone. Examples:

*

*Windows PC

*MacBook (Air, Pro, or Regular Will Work)

*Friend's Computer

Windows PC ____________

*

*Install Windows 10/11
After, you have to plug in the USB Flash Drive in the computer, open your browser (Firefox, Microsoft Edge, Chrome) and
download Windows 10 or Windows 11. MAKE SURE YOUR PC IS COMPATIBLE WITH WINDOWS 11 Download the Media Install Media Creation Tool for WINDOWS ONLY (Required for Windows 10 install), after downloading the tool installer, download it, run the new exe file. Once running click Setup, then click create installation media. Click next and select USB Flash Drive, wait until downloaded and done!  You have made a WIU (Windows Installer USB) on a Windows PC!
MacBook________________

*

*Install Windows 10/11
YOU WILL REQUIRE A WINDOWS EXE RUNNER/EMULATOR LIKE WINE
Download Wine if necessary. and Load the EXE File From WINDOWS MEDIA CREATION TOOl to download WMCT and open it using wine as well. Now You May continue the steps above that are for Windows PC, This is an extra step you NEED TO take to download on MacBook!


text:
Q: Set temporary variable and reuse it further down in pug template I am trying to pass along some values from my nodejs/express backend into the template (using res.render({...})), store it in some variables, then pass it further up until the front end (The usecase is that I need to do some mild calculation on the passed values and stored them in some intermediate variables)
I know I can do this in the pug file
block append script
  script.
    const foo = parseInt(#{stat.get('fooStat')}, 10);

But then later it seems that I can not refer to this later in my pug template, say here
  span #{foo}

The value is empty, I guess because it is undefined... What's the usual way to accomplish that.

A: Adding the period after the script tag signals to pug that its contents should be treated as plain text. This is handy when you want to write javascript for client-side consumption, but any variables declared are inaccessible to pug.
script.
  const foo = 10;

span #{foo} // foo is undefined here

If you want to define a variable that pug can use later in the template, do so using unbuffered code.
- const foo = 10

span #{foo} // renders 10


text: Q: WaveSurfer.js - Edit the Bottom Half of the Waveform I have WaveSurfer.js working. I want to make the bottom half more compact so that it looks more like the SoundCloud waveform. I've tried to look at the source code of the WaveSurfer.js but couldn't figure out where and how to edit the source code to make it work.


text:
Q: file writing is not performing in android I need to write the registration credentials into a file during registration and during login will check that file for credentials. but on registration button click nothing is performing.
Manifest file contains this permission:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

the registration.java part:
reg.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            String user=username.getText().toString();
            String pwd=password.getText().toString();
            String cpwd=confirm.getText().toString();

            if(user.equals("")||pwd.equals("")||cpwd.equals("")){
                Toast.makeText(getApplicationContext(), "Fields cannot be Blank", Toast.LENGTH_SHORT).show();
            }
            else if(pwd.equals(cpwd)){
                String data=user+","+pwd+":";

                try {
                    FileOutputStream fout = new FileOutputStream(Environment.getExternalStorageDirectory()+"/myapp/userregister.txt/", true);
                    fout.write(data.getBytes());
                    Toast.makeText(getApplicationContext(), "Succesfully Register", Toast.LENGTH_SHORT).show();
                    Intent a=new Intent(getApplicationContext(),LoginActivity.class);
                    startActivity(a);
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
                else if(!pwd.equals(cpwd)){
                    Toast.makeText(getApplicationContext(), "Password not match.. Try again!", Toast.LENGTH_SHORT).show();
                }

        }
    });

In LoginActivity.java
if(username.equals("") || password.equals("")){

        Toast.makeText(getApplicationContext(), "Fields Cannot be Blank", Toast.LENGTH_SHORT).show();
    }else{
         String reply=FileManipulator.authenticateUser(username, password);
                 if(reply.equals("user")){
                     Intent gotoNextActivity=new Intent(getApplicationContext(),HomeActivity.class);
                        startActivity(gotoNextActivity);

                 }else{
        Toast.makeText(getApplicationContext(), "Invalid User.... Try again",Toast.LENGTH_SHORT).show();
           }
    }

FileManipulator class authenticateUser function:
public static String authenticateUser(String user, String pass){
    String data="";
    String data1 = "";
    try{
        FileInputStream fin=new FileInputStream(Path.userregister);
        byte[] b=new byte[fin.available()];
        fin.read(b);
        data=new String(b);
        String st=user+","+pass+":";
        if(data.contains(st)){
            data1="user";
        }
    }catch(Exception e){
        e.printStackTrace();
    }

    return data1;

}

The log cat shows
09-02 05:48:06.292: D/dalvikvm(1964): GC_CONCURRENT freed 240K, 12% free 2838K/3200K, paused 5ms+32ms, total 177ms
09-02 05:48:06.802: I/Choreographer(1964): Skipped 36 frames!  The application may be doing too much work on its main thread.
09-02 05:48:10.362: I/Choreographer(1964): Skipped 32 frames!  The application may be doing too much work on its main thread.
09-02 05:48:20.872: W/System.err(1964): java.io.FileNotFoundException: /mnt/sdcard/myapp/userregister.txt: open failed: EACCES (Permission denied)
09-02 05:48:20.872: W/System.err(1964):     at libcore.io.IoBridge.open(IoBridge.java:416)
09-02 05:48:20.882: W/System.err(1964):     at java.io.FileOutputStream.<init>(FileOutputStream.java:88)
09-02 05:48:20.882: W/System.err(1964):     at java.io.FileOutputStream.<init>(FileOutputStream.java:128)
 09-02 05:48:20.882: W/System.err(1964):    at com.example.text.RegActivity$1.onClick(RegActivity.java:49)
 09-02 05:48:20.892: W/System.err(1964):    at android.view.View.performClick(View.java:4204)
 09-02 05:48:20.892: W/System.err(1964):    at android.view.View$PerformClick.run(View.java:17355)
 09-02 05:48:20.902: W/System.err(1964):    at android.os.Handler.handleCallback(Handler.java:725)
 09-02 05:48:20.912: W/System.err(1964):    at android.os.Handler.dispatchMessage(Handler.java:92)
 09-02 05:48:20.912: W/System.err(1964):    at android.os.Looper.loop(Looper.java:137)
 09-02 05:48:20.912: W/System.err(1964):    at android.app.ActivityThread.main(ActivityThread.java:5041)
 09-02 05:48:20.922: W/System.err(1964):    at java.lang.reflect.Method.invokeNative(Native Method)
 09-02 05:48:20.922: W/System.err(1964):    at java.lang.reflect.Method.invoke(Method.java:511)
 09-02 05:48:20.922: W/System.err(1964):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
 09-02 05:48:20.922: W/System.err(1964):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
 09-02 05:48:20.922: W/System.err(1964):    at dalvik.system.NativeStart.main(Native Method)
 09-02 05:48:20.932: W/System.err(1964): Caused by: libcore.io.ErrnoException: open failed: EACCES (Permission denied)
 09-02 05:48:20.942: W/System.err(1964):    at libcore.io.Posix.open(Native Method)
 09-02 05:48:20.942: W/System.err(1964):    at libcore.io.BlockGuardOs.open(BlockGuardOs.java:110)
 09-02 05:48:20.952: W/System.err(1964):    at libcore.io.IoBridge.open(IoBridge.java:400)
 09-02 05:48:20.952: W/System.err(1964):    ... 14 more

I'm a newbie to android and java..please help me to find the error.

A: 1) Add android.permission.WRITE_EXTERNAL_STORAGE in AndroidManifest.xml file.
2) Always check for the availability of external storage before writing/reading by :
 String state = Environment.getExternalStorageState();
 if (Environment.MEDIA_MOUNTED.equals(state)) {
        // Can read and write the media

    } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
        // Can only read the media

    } else {
        // Can't read or write
    }

3) Create a directory, then make your file in it.
 File dir = new File (Environment.getExternalStorageDirectory().getAbsolutePath() + "/myapp");
        dir.mkdirs();
        File file = new File(dir, "userregister.txt");

NOTE :
If you are using Android 4.4 KitKat, Apps are not allowed to write to secondary external storage devices, except in their package-specific directories
The reason from http://source.android.com/devices/tech/storage/index.html
The WRITE_EXTERNAL_STORAGE permission must only grant write access to the primary external storage on a device. Apps must not be allowed to write to secondary external storage devices, except in their package-specific directories as allowed by synthesized permissions. Restricting writes in this way ensures the system can clean up files when applications are uninstalled.


text:
Q: IntelliJ: Dependencies in classpath but not in Fat Jar? I have a Spark application (Scala) written in IntelliJ and thereby used Maven as dependency management.
My aim is to execute the application right from IntelliJ and package it into a JAR that includes some dependencies (using Maven obviously).
In m pom.xml I declared the dependencies I want to include in the Fat Jar without specifying a scope and the one I do not want in the Fat Jar with scope provided.
This packages the fat jar as I intend (the "missing" dependencies are then added to the classpath with the spark-submit script upon execution).
But when I execute the application from IntelliJ (using IntelliJ default run mechanism) it is giving me the error that certain classes cannot be found.
How can I change my pom.xml and/or IntelliJ configuration to have both working at the same time?
Thanks and regards!


text:
Q: Does Sharepoint use the wWWHomePage attribute in AD? I have been working with synchronizing users into Active Directory, from an external data source, and one of the attributes of interest is wWWHomePage, and the AD folk have noticed that many users have this set to their SharePoint home page.
There is a belief but they cannot prove (nor find) why this is getting set.  They believe that they may have SharePoint set up (another group manages SharePoint) to set this.
Is this normal SharePoint behavior, and is there any downside to changing this for users?

A: When the user first provisions or accesses their MySite they are prompted if the want Microsoft Office to remember the location of their MySite. I believe if the user selects "Yes" it writes the value to AD, but I have never reverse engineered this to see how it actually works. I believe the value is being updated directly into AD and is not using User Profile Sync to write it. This behavior has been in SharePoint since 2003.


text:
Q: ADB Shell get Live GPS Location (not last known location) The adb command: adb shell dumpsys location
It retrieves me "the last known location" plus other information.
But the GPS location seems to be stuck, even I move somewhere still the gps doesn't change.
Is there an additional command to get the Just GPS or also the GPS? or make the GPS change? (flush cache memory, update, etc?).
Thanks


text:
Q: CNN model accuracy maxing out at 99%, then dropping to 50% epochs later I'm creating a CNN that can classify CT scans as positive for COVID-19 induced pnemonia and negative for healthy CT. I tested my model for 50 epochs; from epoch 1 - 10, it incrementally increases and maxes out at 99% accuracy at epoch 10. However, a couple epochs later, it drops tremendously to 44%, which is awful for a binary classification CNN. Here's my model:
# Loading in the dataset
traindata = ImageDataGenerator(rescale=1/255)
trainingdata = traindata.flow_from_directory(
    directory="Covid-19CT/TrainingData",
    target_size=(128,128),
    batch_size=16,
    class_mode="binary")
testdata = ImageDataGenerator(rescale=1/255)
testingdata = testdata.flow_from_directory(
    directory="Covid-19CT/TestingData",
    target_size=(128,128),
    batch_size=16,
    class_mode="binary")

# Initialize the model w/ Sequential & add layers + input and output <- will refer to the VGG 16 model architecture
model = Sequential()

model.add(Conv2D(input_shape=(128,128,3),filters=64,kernel_size=(2,2),padding="same", activation="relu"))
model.add(Conv2D(filters=64, kernel_size=(3,3), padding="same", activation ="relu"))
model.add(MaxPool2D(pool_size=(2,2), strides=2))

model.add(Conv2D(filters=128, kernel_size=(3,3), padding="same", activation="relu"))
model.add(Conv2D(filters=128, kernel_size=(3,3), padding="same", activation="relu"))
model.add(MaxPool2D(pool_size=(2,2), strides=2))

model.add(Conv2D(filters=256, kernel_size=(3,3), padding="same", activation="relu"))
model.add(Conv2D(filters=256, kernel_size=(3,3), padding="same", activation="relu"))
model.add(Conv2D(filters=256, kernel_size=(3,3), padding="same", activation="relu"))
model.add(MaxPool2D(pool_size=(2,2), strides=2))

model.add(Conv2D(filters=512, kernel_size=(3,3), padding="same", activation="relu"))
model.add(Conv2D(filters=512, kernel_size=(3,3), padding="same", activation="relu"))
model.add(Conv2D(filters=512, kernel_size=(3,3), padding="same", activation="relu"))
model.add(MaxPool2D(pool_size=(2,2), strides=2))

model.add(Conv2D(filters=512, kernel_size=(3,3), padding="same", activation="relu"))
model.add(Conv2D(filters=512, kernel_size=(3,3), padding="same", activation="relu"))
model.add(Conv2D(filters=512, kernel_size=(3,3), padding="same", activation="relu"))
model.add(MaxPool2D(pool_size=(2,2), strides=2))

model.add(Flatten())
model.add(Dense(units=1000, activation="relu"))
model.add(Dense(units=1, activation="sigmoid"))

# Compile the model
model_optimizer = Adam(lr=0.001)
model.compile(optimizer=model_optimizer, loss=keras.losses.binary_crossentropy, metrics=['accuracy'])
# Add the callbacks
checkpoint = ModelCheckpoint(filepath="Covid-19.hdf5", monitor='accuracy', verbose=1, save_best_only=True, save_weights_only=False, mode='auto')
early = EarlyStopping(monitor='accuracy', min_delta=0, patience=50, verbose=1, mode='auto')
reduceLR = ReduceLROnPlateau(monitor='val_loss', factor=.5, patience=2, min_delta=0.01, mode="auto")
fit = model.fit_generator(steps_per_epoch=25, generator=trainingdata, validation_data=testingdata, validation_steps=10,epochs=50,callbacks=[checkpoint,early])

Here's the training accuracies:
Epoch 1/50
24/25 [===========================>..] - ETA: 12s - loss: 0.7703 - accuracy: 0.5495
Epoch 00001: accuracy improved from -inf to 0.54500, saving model to Covid-19.hdf5
25/25 [==============================] - 360s 14s/step - loss: 0.7646 - accuracy: 0.5450 - val_loss: 0.6984 - val_accuracy: 0.4313
Epoch 2/50
24/25 [===========================>..] - ETA: 13s - loss: 0.8016 - accuracy: 0.7240
Epoch 00002: accuracy improved from 0.54500 to 0.73250, saving model to Covid-19.hdf5
25/25 [==============================] - 374s 15s/step - loss: 0.7868 - accuracy: 0.7325 - val_loss: 4.4926 - val_accuracy: 0.6375
Epoch 3/50
24/25 [===========================>..] - ETA: 11s - loss: 0.3555 - accuracy: 0.8960
Epoch 00003: accuracy improved from 0.73250 to 0.89003, saving model to Covid-19.hdf5
25/25 [==============================] - 344s 14s/step - loss: 0.3941 - accuracy: 0.8900 - val_loss: 3.2895 - val_accuracy: 0.7000
Epoch 4/50
24/25 [===========================>..] - ETA: 13s - loss: 0.2441 - accuracy: 0.9297
Epoch 00004: accuracy improved from 0.89003 to 0.93000, saving model to Covid-19.hdf5
25/25 [==============================] - 385s 15s/step - loss: 0.2387 - accuracy: 0.9300 - val_loss: 1.2085 - val_accuracy: 0.6687
Epoch 5/50
24/25 [===========================>..] - ETA: 13s - loss: 0.1788 - accuracy: 0.9714
Epoch 00005: accuracy improved from 0.93000 to 0.97250, saving model to Covid-19.hdf5
25/25 [==============================] - 381s 15s/step - loss: 0.1755 - accuracy: 0.9725 - val_loss: 2.5818 - val_accuracy: 0.7125
Epoch 6/50
24/25 [===========================>..] - ETA: 12s - loss: 0.0642 - accuracy: 0.9844
Epoch 00006: accuracy improved from 0.97250 to 0.98000, saving model to Covid-19.hdf5
25/25 [==============================] - 363s 15s/step - loss: 0.0670 - accuracy: 0.9800 - val_loss: 4.4083 - val_accuracy: 0.7125
Epoch 7/50
24/25 [===========================>..] - ETA: 12s - loss: 0.0947 - accuracy: 0.9479
Epoch 00007: accuracy did not improve from 0.98000
25/25 [==============================] - 362s 14s/step - loss: 0.0937 - accuracy: 0.9500 - val_loss: 4.2777 - val_accuracy: 0.7000
Epoch 8/50
24/25 [===========================>..] - ETA: 13s - loss: 0.1298 - accuracy: 0.9505
Epoch 00008: accuracy did not improve from 0.98000
25/25 [==============================] - 375s 15s/step - loss: 0.1301 - accuracy: 0.9475 - val_loss: 1.5817 - val_accuracy: 0.4688
Epoch 9/50
24/25 [===========================>..] - ETA: 13s - loss: 0.0506 - accuracy: 0.9740
Epoch 00009: accuracy did not improve from 0.98000
25/25 [==============================] - 378s 15s/step - loss: 0.0486 - accuracy: 0.9750 - val_loss: 4.3898 - val_accuracy: 0.7125
Epoch 10/50
24/25 [===========================>..] - ETA: 12s - loss: 0.0263 - accuracy: 0.9922
Epoch 00010: accuracy improved from 0.98000 to 0.99250, saving model to Covid-19.hdf5
25/25 [==============================] - 368s 15s/step - loss: 0.0252 - accuracy: 0.9925 - val_loss: 4.3956 - val_accuracy: 0.6875
Epoch 11/50
24/25 [===========================>..] - ETA: 12s - loss: 0.1428 - accuracy: 0.9714
Epoch 00011: accuracy did not improve from 0.99250
25/25 [==============================] - 346s 14s/step - loss: 0.1378 - accuracy: 0.9725 - val_loss: 2.3141 - val_accuracy: 0.5188
Epoch 12/50
24/25 [===========================>..] - ETA: 11s - loss: 0.2058 - accuracy: 0.9479
Epoch 00012: accuracy did not improve from 0.99250
25/25 [==============================] - 343s 14s/step - loss: 0.2006 - accuracy: 0.9500 - val_loss: 2.2401 - val_accuracy: 0.6750
Epoch 13/50
24/25 [===========================>..] - ETA: 12s - loss: 0.0434 - accuracy: 0.9818
Epoch 00013: accuracy did not improve from 0.99250
25/25 [==============================] - 363s 15s/step - loss: 0.0417 - accuracy: 0.9825 - val_loss: 4.3546 - val_accuracy: 0.7000
Epoch 14/50
24/25 [===========================>..] - ETA: 12s - loss: 0.0242 - accuracy: 0.9974
Epoch 00014: accuracy improved from 0.99250 to 0.99750, saving model to Covid-19.hdf5
25/25 [==============================] - 361s 14s/step - loss: 0.0256 - accuracy: 0.9975 - val_loss: 4.4083 - val_accuracy: 0.7125
Epoch 15/50
24/25 [===========================>..] - ETA: 12s - loss: 0.0298 - accuracy: 0.9922
Epoch 00015: accuracy did not improve from 0.99750
25/25 [==============================] - 367s 15s/step - loss: 0.0286 - accuracy: 0.9925 - val_loss: 3.9429 - val_accuracy: 0.7125
Epoch 16/50
24/25 [===========================>..] - ETA: 11s - loss: 0.0045 - accuracy: 0.9974
Epoch 00016: accuracy did not improve from 0.99750
25/25 [==============================] - 338s 14s/step - loss: 0.0043 - accuracy: 0.9975 - val_loss: 4.4335 - val_accuracy: 0.7063
Epoch 17/50
24/25 [===========================>..] - ETA: 11s - loss: 0.2831 - accuracy: 0.9479
Epoch 00017: accuracy did not improve from 0.99750
25/25 [==============================] - 336s 13s/step - loss: 0.2750 - accuracy: 0.9500 - val_loss: 2.4855 - val_accuracy: 0.6625
Epoch 18/50
24/25 [===========================>..] - ETA: 14s - loss: 1.4282 - accuracy: 0.9036
Epoch 00018: accuracy did not improve from 0.99750
25/25 [==============================] - 400s 16s/step - loss: 1.6394 - accuracy: 0.8900 - val_loss: 6.6125 - val_accuracy: 0.5688
Epoch 19/50
24/25 [===========================>..] - ETA: 12s - loss: 8.0488 - accuracy: 0.4693
Epoch 00019: accuracy did not improve from 0.99750
25/25 [==============================] - 349s 14s/step - loss: 7.9984 - accuracy: 0.4731 - val_loss: 6.6125 - val_accuracy: 0.5688
Epoch 20/50
24/25 [===========================>..] - ETA: 11s - loss: 7.6267 - accuracy: 0.5026
Epoch 00020: accuracy did not improve from 0.99750
25/25 [==============================] - 342s 14s/step - loss: 7.5900 - accuracy: 0.5050 - val_loss: 6.6125 - val_accuracy: 0.5688
Epoch 21/50
24/25 [===========================>..] - ETA: 12s - loss: 8.2656 - accuracy: 0.4609
I think I'll end up replacing Early Stopping with a dropout layer, but can't understand the reason for such a drop in accuracy. While the model was probably overfitting with the 99% accuracy, why the sudden drop?

A: You can do as suggested about early stopping or training for less epochs if you wish, I notice you are monitoring "accuracy" in your callbacks. It is usually best to monitor the validation loss and save the model with the lowest loss. Validation loss is an indication of how well your model generalizes to unseen images. Just an FYI I notice you are saving the entire model. That's fine but it greatly slows down the time it takes to complete training. Try just saving the weights in the checkpoint callback. It is much faster especially if you have a large model.  Then after training is complete run model.load_weights to do predictions. Then you can save the entire model with model.save. All this does not address the issue of why your model training loss starts to sky rocket after the tenth epoch. I can't figure it out. Point me to the location of the data set in a comment and I will see if I can duplicate the problem. As a quick check how many training samples and how many test samples do you have? You want to go through your validation set once per epoch. So you need to set the validation_batch_size such that the number of validation samples divided by the validation_batch_size is an integer. Use that integer as validation_steps. Below is a piece of code that given a directory path and a maximum batch size you can allow based on memory capacity (b_max) will give you the batch_size and steps. It goes through the directory (for example test_dir) and adds up the count of all the files within all the sub directories (variable length) then determines the batch size and steps.
def get_bs(dir,b_max):
    # dir is the directory containing the samples, b_max is maximum batch size to allow based on your memory capacity
    # you only want to go through test and validation set once per epoch this function determines needed batch size ans steps per epoch
    length=0
    dir_list=os.listdir(dir)
    for d in dir_list:
        d_path=os.path.join (dir,d)
        length=length + len(os.listdir(d_path))
    batch_size=sorted([int(length/n) for n in range(1,length+1) if length % n ==0 and length/n<=b_max],reverse=True)[0]
    return batch_size,int(length/batch_size), length

If you run this on your test directory you should get batch_size=79, steps= 14 and length = 1106 with b_max set to 80.


text:
Q: Geopandas Mollweide projection I´ve a .gpkg file in Mollweide projection. When I open it in geopandas, it shows me  the correct crs information:
df1.crs
>>>>> {'init': 'epsg:54009'}

I´d like to re-project it to EPSG 4326, in a way to cross this layer with a global map in lat/long. If I try:
df1.to_crs(epsg=4326)

I get the error message:

pyproj.exceptions.CRSError: Invalid projection: +init=epsg:54009 +type=crs

How can I proceed to reproject those layers in a way I could intersect them?

A: The Mollweide CRS projection is not "EPSG:54009" but "ESRI:54009". You should try:
df1.to_crs("ESRI:54009")


text:
Q: Error: Must call google.charts.load before google.charts.setOnLoadCallback I have the following imports in HTML:
    <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.7.3/socket.io.js"></script>
    <script type="text/javascript" src="https://www.google.com/jsapi"></script>
    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>

And some of my js code:
// load google charts library
google.load("visualization", "1", {packages: ["corechart"]});
// Set a callback to run when the Google Visualization API is loaded.
google.charts.setOnLoadCallback(drawChart);

// for rest, walk, fast_walk data
var data, options, chart;

var i = 0;

/* initialize chart1 - rest, walk, fast_walk data */
function drawChart(data, options) {
    var chart = new google.visualization.LineChart(document.getElementById('data-container'));
    chart.draw(data, options);
    return(chart);
}

However I am getting Error: Must call google.charts.load before google.charts.setOnLoadCallback
How can I solve this error? Thank you!

A: I solved the error by removing the following code:
// Set a callback to run when the Google Visualization API is loaded.
google.charts.setOnLoadCallback(drawChart);

Thank you!


text:
Q: How to make app like night mode How can make app which will dim screen light.
I want to make simple application which is do screen brightness very low
Dim screen brightness by programatically

A:   Settings.System
            .putInt(this.getContentResolver(),
                    Settings.System.SCREEN_BRIGHTNESS, newBrightnessValue);

Use This method. Pass int value at  "newBrightnessValue". you can also pass 0 or 1 for low & high brightness respectivily

A: The screen design is presented based on Application Theme. By default, we specify the application theme in manifest file. It uses the theme in our application
<application
        android:name=".MainApplication"
        android:allowBackup="true"
        android:theme="@style/AppTheme">

You can change Dark theme during run time
setTheme(android.R.style.Theme_Dark);

enter image description here
Also you can define your own theme in styles.xml file


text:
Q: I'm struggling to do citations in my Latex work [references, bibliography] Please guys how can I do refrences in my LaTex work, I have TexMaker, Texworks and didn't know how to deal with it. I found some videos on Youtube but they were using Bibdesk to run their bibliography and I do not seem to find this bibdesk app anywhere. a link to a Youtube video will do. Thanks in advance.

A: packages are downloaded on the fly -- you requested for links --
https://libguides.rhul.ac.uk/referencing/latex
https://www.overleaf.com/learn/latex/bibliography_management_with_bibtex
http://gottscott.github.io/2016/08/30/how-to-do-citations-in-latex.html


text:
Q: After updating RecyclerView library from 23.3.0 to 24.2.0, getting java.util.concurrent.RejectedExecutionException error I am using couple of RecyclerView around my app. I wanted to update support library I've been using which was 23.3.0 to 24.2.0 and suddenly app started to crash with the java.util.concurrent.RejectedExecutionException error.
Stack trace points to my base activity classes onResume method.
Here is the stack trace:
Failed to submit events task
java.util.concurrent.RejectedExecutionException: Task java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask@ac47c5f rejected from java.util.concurrent.ScheduledThreadPoolExecutor@40816ac[Shutting down, pool size = 1, active threads = 0, queued tasks = 1, completed tasks = 5]
                                                       at java.util.concurrent.ThreadPoolExecutor$AbortPolicy.rejectedExecution(ThreadPoolExecutor.java:2011)
                                                       at java.util.concurrent.ThreadPoolExecutor.reject(ThreadPoolExecutor.java:793)
                                                       at java.util.concurrent.ScheduledThreadPoolExecutor.delayedExecute(ScheduledThreadPoolExecutor.java:298)
                                                       at java.util.concurrent.ScheduledThreadPoolExecutor.schedule(ScheduledThreadPoolExecutor.java:503)
                                                       at java.util.concurrent.ScheduledThreadPoolExecutor.submit(ScheduledThreadPoolExecutor.java:602)
                                                       at java.util.concurrent.Executors$DelegatedExecutorService.submit(Executors.java:593)
                                                       at com.crashlytics.android.answers.AnswersEventsHandler.executeAsync(AnswersEventsHandler.java:182)
                                                       at com.crashlytics.android.answers.AnswersEventsHandler.processEvent(AnswersEventsHandler.java:168)
                                                       at com.crashlytics.android.answers.AnswersEventsHandler.processEventAsync(AnswersEventsHandler.java:44)
                                                       at com.crashlytics.android.answers.SessionAnalyticsManager.onLifecycle(SessionAnalyticsManager.java:128)
                                                       at com.crashlytics.android.answers.AnswersLifecycleCallbacks.onActivityStarted(AnswersLifecycleCallbacks.java:26)
                                                       at io.fabric.sdk.android.ActivityLifecycleManager$ActivityLifecycleCallbacksWrapper$1.onActivityStarted(ActivityLifecycleManager.java:111)
                                                       at android.app.Application.dispatchActivityStarted(Application.java:223)
                                                       at android.app.Activity.onStart(Activity.java:1245)
                                                       at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:592)
                                                       at com.myApp.base.BaseActivity.onStart(BaseActivity.java:173)
                                                       at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1234)
                                                       at android.app.Activity.performStart(Activity.java:6329)
                                                       at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2665)
                                                       at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2767)
                                                       at android.app.ActivityThread.access$900(ActivityThread.java:177)
                                                       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1449)
                                                       at android.os.Handler.dispatchMessage(Handler.java:102)
                                                       at android.os.Looper.loop(Looper.java:145)
                                                       at android.app.ActivityThread.main(ActivityThread.java:5951)
                                                       at java.lang.reflect.Method.invoke(Native Method)
                                                       at java.lang.reflect.Method.invoke(Method.java:372)
                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1400)
                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1195)

here is my build.gradle sdk versions
compileSdkVersion 24
buildToolsVersion '22.0.1'
dataBinding {
    enabled = true
}
defaultConfig {
    minSdkVersion 14
    targetSdkVersion 22
    multiDexEnabled true
}

and google related dependencies
compile 'com.android.support:appcompat-v7:24.2.0'
compile 'com.android.support:recyclerview-v7:24.2.0'
compile 'com.android.support:support-v4:23.1.1'
compile 'com.android.support:multidex:1.0.0'
compile 'com.google.android.gms:play-services-analytics:8.3.0'
compile 'com.google.android.gms:play-services-gcm:8.3.0'
compile 'com.google.android.gms:play-services-appindexing:8.3.0'
compile 'com.google.android.gms:play-services-plus:8.3.0'

Do you have any idea why I might be facing the problem?


text:
Q: Sending static files in Flask After reading this question and the documentation here I've written a function that should return a static resource(html, css and javascript files):
server.py
import json
import random
import string
import re

import os
import sys

sys.path.append(os.path.join(os.path.dirname(__file__), '..'))

from app import app
from flask import Flask, jsonify, request, render_template
from database_helpers import query_db, insert_db
from werkzeug.security import generate_password_hash, check_password_hash

# set the project root directory as the static folder, you can set others.
# cwd = os.path.dirname(os.path.realpath(__file__))
app = Flask(__name__, static_url_path='')
# url_for('static', filename='style.css')

@app.route('/')
def index():
    # This works
    # return "Test test test."
    # This doesn't
    return app.send_static_file('welcome.html')

The project layout directory is:

Does the static path have to be absolute or relative to the current working directory? I'm working on windows. Does this imply that slashes backward slashes should be added to all paths present in server.py?
Each request receives a 404 response.

A: Commenting out the line that defines the static URL path fixed the issue:
server.py
import json
import random
import string
import re

import os
import sys

sys.path.append(os.path.join(os.path.dirname(__file__), '..'))

from app import app
from flask import Flask, jsonify, request, render_template
from database_helpers import query_db, insert_db
from werkzeug.security import generate_password_hash, check_password_hash

@app.route('/')
def index():
    # This works
    # return "Test test test."
    # This doesn't
    return app.send_static_file('welcome.html')

However, the styles and images are not sent.
In order to send the static content required by an html file, it must be referenced relatively to the root path. For example, if index.html has an image:

then its source must be changed so as to point in the static directory where favicon.ico is located:


text:
Q: why does Firestore reflect the last field value? Like this, I call the 3 functions:
DbMain db = new DbMain();

        db.openAccount("YOO","key_1",false);

        db.deposit(70, "Bank");
        db.deposit(70, "Bank");

The openAccount function, make an account and its balance is initialized as 0:
void openAccount(String ownerOfAccount, String key ,boolean savingsOrNot) //
     {
         mAuth.signInAnonymously();

         Account account = new Account(ownerOfAccount, key,"Account Number",0);
         if (savingsOrNot == true)
             db.collection("Info/Account/SavingsAccount").document(mAuth.getUid()).set(account);
         else
             db.collection("Info/Account/BankAccount").document(mAuth.getUid()).set(account);

     }

void deposit(int amount, String savingsOrBank) //     {
        DocumentReference accountRef;

            accountRef = db.collection("Info/Account/"+savingsOrBank+"Account").document(mAuth.getUid());

            accountRef.update("balance", FieldValue.increment(amount));

            accountRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>()
        {
            @Override
            public void onComplete(@NonNull Task<DocumentSnapshot> task)
            {

                DocumentSnapshot documentSnapshot = task.getResult();

                Log.d("here!!!_deposit_1",documentSnapshot.get("balance").toString());

                AccountLog log = new AccountLog(true, amount,Integer.valueOf(documentSnapshot.get("balance").toString()), LocalDate.now(), LocalTime.now());
                addAccountLog( log, false);

                Log.d("here!!!_deposit_2",documentSnapshot.get("balance").toString());

            }
        });
    }

And the 'deposit' function add a money to field 'balance' as 'amount'
But the result here:
enter image description here
after first calling deposit, the field 'balance' already shows 140.
as expected, 'balance' value maybe is [openAccount]->0, [first deposit] ->70, [second deposit] ->140
But at three points, all 'balance' value are same as '140'.
I don't understand why.


text:
Q: Serialization: Change the name of the root node without changing the class name Goal
Take a class named "Item" and output its serialized XML as:
<Template><!--some properties --></Template>

Problem
The root node is derived off the class name that is implementing IXmlSerializable.
    // By the time I get here 'writer' already has a root node
    public void WriteXml(XmlWriter writer)
    {
        writer.WriteStartElement("Template");
         // write out the properties
        writer.WriteEndElement();
    }

So I wind up with XML that looks like
<Item><Template><!-- some properties --></Template></Item>

Question
Is there an attribute, a property I can override, or anything to get my desired effect (aside from changing the class name)?
Thanks!
Resolution thanks to Frederik!
Since the question is sort of answered in my comment of @Frederik Gheysels answer, I thought I would put it here so it doesn't get buried.
Just add an XmlRoot attribute to your class and this will change the output xml of the root node.
Example:
[XmlRoot("Template")]
public class Item : IXmlSerializable
{
   //Item's properties
}

A: check the XmlRootAttribute class.


text:
Q: How Can I Use AirPlay Globally for System Sound? Is it possible (and how) to have all the system sound played on AirPlay? Or at least for some specific (random) application (e.g. Songbird)?

A: What you want is AirFoil by Rogue Amoeba. Plays any audio from your system via AirPlay.

A: If you have a newer Mac with Mountain Lion you can also use it's built in AirPlay functionality.
Go to System Preferences->Sound and select Apple TV from the Output tab. This will play all system sound from your Mac.

A: An easy way to do this in Mountain Lion is to hold down the option key and click on the speaker icon in the menu bar. You then get a list of possible outputs, and will be able to send all audio to your Apple TV or other AirPlay device by selecting it.


text:
Q: Facebook Open Graph Issues / OAuth Connection I've been recently switching over to Open crash for all stream_publish actions and I've noticed a recurring issue:
Object titles are not showing when viewing a post on Mobile, or the Web. I usually see this on the mobile app/web - where the object title isn't being shown, but on the desktop web - it's always there. Is there a character limit on mobile?
OAuth Connection Issues
In addition - some users are unable to login via Facebook. Every attempt to run through the traditional OAuth server side logic presents this URL:
error_code=2000&error_message=The+specified+feature+has+been+temporarily+disabled
This happens for at least a handful of users. Are there specific permissions that users can block for all OAuth requests?


text:
Q: Add condition to AngularJS map function I'm using the below to loop through an array and add a property to each item of the array.
$scope.addresses = $scope.addresses.map(function(address) {
      address.location = "X";
      return address;
});

this at the end will return all the items. How can I add a condition to the loop? so I can check a property and the based on that property return only certain addresses where that property is true?
Any help appreciated!

A: You should use the filter function
You can read about it here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
Basically filter is a function the gets a boolean function as a parameter (let's call it f), and returns an array with all the items that the f returns true for.
For example:
var mapped = $scope.addresses = $scope.addresses.map(function(address) {
      address.location = "X";
      return address;
});

var filtered = mapped.filter(function (address) {
    return address.location.length > 5;
});

filtered  will hold a collection of the addresses that have a location with more than 5 characters.

A: use filter
$scope.addresses = $scope.addresses.filter(function(address){
  return address.location === x;
})


text:
Q: core dump file sometimes not created I am running Fedora core 14.  I have a program that occasionally (rarely) segfaults.  When this happened most recently I noticed to my consternation that there was no core file generated after the segfault, so I was unable to retroactively gdb the program and core file.
I added an interactive command so that I could intentionally generate a fault that is supposed to generate a core file, and what I found was that sometimes a core file is generated and sometimes it is not generated.  I have set the coredumpsize limit to "unlimited" and have plenty of disk space, and a writeable current working directory.
I would like to debug this issue of not generating core files reliably.  (I'm sure there will be some simple solution, but as of now it eludes me.)
Could someone tell me where to find the source code that generates core dump files when a gcc/g++ program under Linux segfaults or does a floating exception?  I'm hoping that having a look at the source code for how core dump files get generated will help me figure out why I don't get one sometimes.  I am running FC 14, linux kernel 2.6.35.11-83.
Thanks in advance for any help!
Greg Johnson

A: I always use lxr when I'm trying to track down whats going in the kernel.
exec.c has info in it relating to core dumps.
That may be useful to you.
http://lxr.free-electrons.com/source/fs/exec.c


text:
Q: MVC 5 Highcjarts ajax call I'm trying to load the data into simple Highcharts by Ajax call. In the controller I have :
public ActionResult GetDailyOutput()
    {
        string result = repository.GetGraphData("spCTGetDailyOutput");

        return Json(result);
    }

and my View looks like that:

So the controller have value result = "[[1,12],[2,5],[3,18],[4,13],[5,7],[6,4],[7,9],[8,10],[9,15],[10,22]]"
But the chart doesn't contain any data

A: Check below code. Here is working fiddle - http://jsfiddle.net/ar886smr/
I used $.parseJSON() to parse incoming string of array of arrays to JS Array.
        $.getJSON('@Url.Action("GetDailyOutput", "Highcharts")', function (data) {
               $('#container').highcharts({
                 series: [{
                    name: 'Name',
                    data: $.parseJSON(data)
                  }]
               });
            });
        });

A: Try to do like this:

I'm not sure if this is enough when it comes to HighCharts (maybe also You need to set up the type of chart (it goes to "series", above "data"); maybe the Y/X-axis as well).


text:
Q: How to Recompose Simple LazyColumn List Example I'm new to Jetpack Compose and I'm trying to figure out how to recompose a LazyColumn list when user clicks a FloatingActionButton.
As the picture shows, I have a basic Scaffold layout with a LazyColumn for content.  Toward the bottom is a FloatingActionButton.  I'd like to be able to click that FloatingActionButton, add "Molly" to my list of names, have the app recompose my list, and display the full list including Molly.  Code below picture.

Here's my code:
package com.learning.lazylistexample

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.*
import androidx.compose.runtime.Composable
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import com.learning.lazylistexample.ui.theme.LazyListExampleTheme
import kotlinx.coroutines.launch

data class ListItem(val name: String)

private var listItems: MutableList<ListItem> = mutableListOf(
    ListItem("Al"),
    ListItem("Barb"),
    ListItem("Cheryl"),
    ListItem("Dave"),
    ListItem("Ed"),
    ListItem("Frank"),
    ListItem("Gloria"),
    ListItem("Henry"),
    ListItem("Ingrid"),
    ListItem("Jack"),
    ListItem("Kayla"),
    ListItem("Larry")
)

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            LazyListExampleTheme {
                // A surface container using the 'background' color from the theme
                Surface(
                    modifier = Modifier.fillMaxSize(),
                    color = MaterialTheme.colors.background
                ) {
                    myApp()
                }
            }
        }
    }
}

@Composable
fun myApp() {

    val scaffoldState = rememberScaffoldState(rememberDrawerState(DrawerValue.Closed))

    val coroutineScope = rememberCoroutineScope()

    Scaffold(
        scaffoldState = scaffoldState,
        topBar = { TopBar() },
        bottomBar = { BottomBar() },
        content = { DisplayList(itemsList = listItems) },
        floatingActionButton = {
            FloatingActionButton(

                onClick = {
                    // When clicked open Snackbar
                    coroutineScope.launch {
                        when (scaffoldState.snackbarHostState.showSnackbar(
                            // Message In the snack bar
                            message = "Snack Bar",
                            actionLabel = "Dismiss"
                        )) {
                            SnackbarResult.Dismissed -> {
                                // do something when snack bar is dismissed
                            }

                            SnackbarResult.ActionPerformed -> {
                                // do something when snack bar is activated
                                // ****** UPDATE LIST *******
                                val newListItem = ListItem(name = "Molly")
                                listItems.add(newListItem)
                                // ****** HOW TO RECOMPOSE LAZYCOLUMN? ******
                            }
                        }
                    }
                }) {
                // Text inside FloatingActionButton
                Text(text = "Add Molly")
            }
        }

    )

}

@Composable
fun TopBar() {
    TopAppBar(
        title = { Text(text = "Lazy List Example", color = Color.White) }
    )
}

@Composable
fun BottomBar() {
    BottomAppBar() {
        Text(text = "", color = Color.White)
    }
}

@Composable
fun DisplayList(itemsList: List<ListItem>) {
    LazyColumn(modifier = Modifier.fillMaxHeight()) {
        items(items = itemsList, itemContent = { item ->
            Text(text = item.name)
        } )
    }
}

I know this has something to do with state, but I can't figure out where to begin.  Can anyone help me with this?
THANK YOU!

A: Change
private var listItems: MutableList<ListItem> = mutableListOf(
    ListItem("Al"),
    ListItem("Barb"),
    ListItem("Cheryl"),
    ListItem("Dave"),
    ListItem("Ed"),
    ListItem("Frank"),
    ListItem("Gloria"),
    ListItem("Henry"),
    ListItem("Ingrid"),
    ListItem("Jack"),
    ListItem("Kayla"),
    ListItem("Larry")
)

to
val listItems = remember { mutableStateListOf(
     ListItem("Al"),
        ListItem("Barb"),
        ListItem("Cheryl"),
        ListItem("Dave"),
        ListItem("Ed"),
        ListItem("Frank"),
        ListItem("Gloria"),
        ListItem("Henry"),
        ListItem("Ingrid"),
        ListItem("Jack"),
        ListItem("Kayla"),
        ListItem("Larry")
) }

And you will have a SnapshotStateList, an instance of MutableList that is observable and can be snapshot, that will trigger recomposition when you add or remove any items.


text:
Q: What is the difference between pkcs v1.5 padding and pkcs v2.1 padding? I have just a basic knowledge about padding techniques. For RSA padding these two padding techniques are available.

*

*Can anyone explain clearly about these two padding schemes, their own pros and cons?

*Also which padding is suitable for which type of situations?

A: PKCS#1 v1.5: https://www.rfc-editor.org/rfc/rfc8017#section-9.2
PKCS#1 v2.x: https://www.rfc-editor.org/rfc/rfc8017#section-9.1
You can use PKCS#1 v1.5 for signatures, but do not use it for encryption due to Bleichenbacher attack (https://crypto.stackexchange.com/questions/12688/can-you-explain-bleichenbachers-cca-attack-on-pkcs1-v1-5).