问:
Changing json to java pojo
Let's say I have a JSON file example.json

```<code>example.json

    {
      "BaggageMaxSize" : {
            "mesurement" : "sum",
            "width" : 70,
            "height" : 50,
            "depth" : 40
        }
    }
</code>```

And create the POJO class:

```<code>    public class pojoexample{
      private BaggageMaxSize BaggageMaxSize;
      // getter
      // setter
    }
</code>```

And then:

```<code>public class BaggageMaxSize
{
    private String height;

    private String width;

    private String depth;

    private String mesurement;

    // getter
    // setter
}
</code>```

Now, I want to use the mapper.readValue to change file to BaggageInfoPolicy.class:

```<code>BaggageInfoPolicy bip = mapper.readValue(file, BaggageInfoPolicy.class);
</code>```

But bip.getBaggageMaxSize().getMesurement() returns null value. Any suggestions?

答:
Actually your JSON represents a pojoexample class instance and not a BaggageInfoPolicy object, which you haven't shared in your post.

So you need to change your code to:

```<code>PojoExample bip = mapper.readValue(file, PojoExample.class);
</code>```

So it reads the PojoExample object correctly.

Note:

Your class should follow the java naming convention and
start with an uppercase, that's why I changed it to PojoExample,
change it in the class definition as well.

And Make sure your class fields have the same types as in the JSON, and their getters and setters are correctly implemented.

Title: Changing json to java pojo

Body:
Let's say I have a JSON file example.json

example.json

    {
      "BaggageMaxSize" : {
            "mesurement" : "sum",
            "width" : 70,
            "height" : 50,
            "depth" : 40
        }
    }

And create the POJO class:

    public class pojoexample{
      private BaggageMaxSize BaggageMaxSize;
      // getter
      // setter
    }

And then:

public class BaggageMaxSize
{
    private String height;

    private String width;

    private String depth;

    private String mesurement;

    // getter
    // setter
}

Now, I want to use the mapper.readValue to change file to BaggageInfoPolicy.class:

BaggageInfoPolicy bip = mapper.readValue(file, BaggageInfoPolicy.class);

But bip.getBaggageMaxSize().getMesurement() returns null value. Any suggestions?

Body:
Actually your JSON represents a pojoexample class instance and not a BaggageInfoPolicy object, which you haven't shared in your post.

So you need to change your code to:

PojoExample bip = mapper.readValue(file, PojoExample.class);

So it reads the PojoExample object correctly.

Note:

Your class should follow the java naming convention and
start with an uppercase, that's why I changed it to PojoExample,
change it in the class definition as well.

And Make sure your class fields have the same types as in the JSON, and their getters and setters are correctly implemented.


来源: stackexchange

问:
How to make the Text item always display fractional parts of numbers?
I have a Text item that display a real number:

```<code>Text { id: txt; ... }

...

txt.text: Math.round(sensor.value*10)/10

...
</code>```

But if sensor.value is the integer number, it's displayed without a fractional part (35 instead 35.0). How to explicitly force txt always display a fractional part of number?

答:
You can use:

```<code>var num = 5.11;
num.toFixed(1);
</code>```

It will round up to 1 place of decimal.

ContentLicense: CC BY-SA 3.0

Body:
I have a Text item that display a real number:

Text { id: txt; ... }

...

txt.text: Math.round(sensor.value*10)/10

...

But if sensor.value is the integer number, it's displayed without a fractional part (35 instead 35.0). How to explicitly force txt always display a fractional part of number?

Body:
You can use:

var num = 5.11;
num.toFixed(1);

It will round up to 1 place of decimal.


问:
How to fill an array with a for loop?
I’m having a lot of trouble learning how to use for loops to fill a new variable. As an example say if I have var year = [2010, 2000, 1992]; and var age = [];.

How would I use a for loop to fill in the age variable?

If this is a bad example, don’t use this. I just would like some help with understanding how to fill in empty arrays.

var names = ["Ace", "yoshi", "Lassie"];
var age = [25, 23, 5];
var u24 = [];
for (var i = 0; i < names.length; i++) {
  if ([age] < 24) {
    u24 += age[i]
    console.log("hello " + names + " " + "you are" + age);
  }
}```

答:
If all you want to do is fill in the age array with a loop, you can try this:

let years = [2010, 2000, 1992],
  age = [],
  d = new Date().getFullYear();

years.forEach(year => age.push(d - year));
console.log(age);```

As regards the relationship between age and names, I think Intervalia has explained that.

Title: How to fill an array with a for loop?

Body:
If all you want to do is fill in the age array with a loop, you can try this:

let years = [2010, 2000, 1992],
  age = [],
  d = new Date().getFullYear();

years.forEach(year => age.push(d - year));
console.log(age);

As regards the relationship between age and names, I think Intervalia has explained that.


问:
Pushing a multidimensional array in javascript
Please check down the code below, I want to push an object multiple times into an array and set a specified path. Hope someone can help. TNX!

To keep it simple I just removed all loops and static addressed my array, but still no success and I don't got any idea why:

wrong result:

```<code>let myObject = {
"version": "2.0",
"worker": {
    "todo": []
 }
};
let myObjectArray = new Array();
myObjectArray.push(myObject);
myObjectArray.push(myObject);
myObjectArray[0]["worker"]["todo"] = "test";
console.log(myObjectArray);
</code>```

-> wrong output array

correct result:

```<code>let myObjectArray = [
{
    "version": "2.0",
    "worker": {
        "todo": []
    }
},
{
    "version": "2.0",
    "worker": {
        "todo": []
    }
}
];
myObjectArray[0]["worker"]["todo"] = "test";
console.log(myObjectArray);
</code>```

-> correct output array

答:
The first example, pushes the same object into the array, so you will have a duplicate of the same object in the array, modifying the first instance will also effect the 2nd instance.

In your second example you are creating two separate objects in the array, modifying the first element has no effect on the second.

Objects are always treated as references in JavaScript.

Body:
Please check down the code below, I want to push an object multiple times into an array and set a specified path. Hope someone can help. TNX!

To keep it simple I just removed all loops and static addressed my array, but still no success and I don't got any idea why:

wrong result:

let myObject = {
"version": "2.0",
"worker": {
    "todo": []
 }
};
let myObjectArray = new Array();
myObjectArray.push(myObject);
myObjectArray.push(myObject);
myObjectArray[0]["worker"]["todo"] = "test";
console.log(myObjectArray);

-> wrong output array

correct result:

let myObjectArray = [
{
    "version": "2.0",
    "worker": {
        "todo": []
    }
},
{
    "version": "2.0",
    "worker": {
        "todo": []
    }
}
];
myObjectArray[0]["worker"]["todo"] = "test";
console.log(myObjectArray);

-> correct output array


问:
Sending a specific email from Woocommerce based on the product
Is it possible in Woocommerce to send a custom email to the customer instead of the regular welcome email when they buy a specific product?</p>

答:
You could do something like this and add some custom text to the new order email that is sent to a customer.</p>

```<code>add_action( 'woocommerce_before_email_order', 'add_product_welcome_email_text', 10, 2 );

function add_product_welcome_email_text( $order, $sent_to_admin ) {

    if ( ! $sent_to_admin ) {

        foreach( $order->get_items() as $item ) {
            $product = wc_get_product( $item['product_id'] );

            // Use the name or product ID here
            if( $product->get_id() == 123 ) {
                echo 'My custom welcome email text.  Thanks for buying ' . $product->get_name();
            }
        }
    }
}
</code>```

Body:
You could do something like this and add some custom text to the new order email that is sent to a customer.

add_action( 'woocommerce_before_email_order', 'add_product_welcome_email_text', 10, 2 );

function add_product_welcome_email_text( $order, $sent_to_admin ) {

    if ( ! $sent_to_admin ) {

        foreach( $order->get_items() as $item ) {
            $product = wc_get_product( $item['product_id'] );

            // Use the name or product ID here
            if( $product->get_id() == 123 ) {
                echo 'My custom welcome email text.  Thanks for buying ' . $product->get_name();
            }
        }
    }
}


问:
Android Resources$NotFoundException on Gradle 3.0 or later
this is my first question so please be merciful.

I have an app that is dependent on the following library: https://github.com/f2prateek/progressbutton

The library was working fine on pre Gradle 3. Now every time I run the app I get the following log:

```<code>___
FATAL EXCEPTION: main
                  Process: com.example.zandrevanheerden.progressbartest, PID: 2829
                  java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.zandrevanheerden.progressbartest/com.example.zandrevanheerden.progressbartest.MainActivity}: android.view.InflateException: Binary XML file line #0: Binary XML file line #0: Error inflating class com.f2prateek.progressbutton.ProgressButton
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java)
                      at android.app.ActivityThread.access$900(ActivityThread.java)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java)
                      at android.os.Handler.dispatchMessage(Handler.java)
                      at android.os.Looper.loop(Looper.java)
                      at android.app.ActivityThread.main(ActivityThread.java)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java)
                   Caused by: android.view.InflateException: Binary XML file line #0: Binary XML file line #0: Error inflating class com.f2prateek.progressbutton.ProgressButton
                      at android.view.LayoutInflater.inflate(LayoutInflater.java)
                      at android.view.LayoutInflater.inflate(LayoutInflater.java)
                      at android.view.LayoutInflater.inflate(LayoutInflater.java)
                      at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:287)
                      at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:139)
                      at com.example.zandrevanheerden.progressbartest.MainActivity.onCreate(MainActivity.java:11)
                      at android.app.Activity.performCreate(Activity.java)
                      at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java)
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java)
                      at android.app.ActivityThread.access$900(ActivityThread.java)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java)
                      at android.os.Handler.dispatchMessage(Handler.java)
                      at android.os.Looper.loop(Looper.java)
                      at android.app.ActivityThread.main(ActivityThread.java)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java)
                   Caused by: android.view.InflateException: Binary XML file line #0: Error inflating class com.f2prateek.progressbutton.ProgressButton
                      at android.view.LayoutInflater.createView(LayoutInflater.java)
                      at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java)
                      at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java)
                      at android.view.LayoutInflater.rInflate(LayoutInflater.java)
                      at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java)
                      at android.view.LayoutInflater.inflate(LayoutInflater.java)
                      at android.view.LayoutInflater.inflate(LayoutInflater.java)
                      at android.view.LayoutInflater.inflate(LayoutInflater.java)
                      at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:287)
                      at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:139)
                      at com.example.zandrevanheerden.progressbartest.MainActivity.onCreate(MainActivity.java:11)
                      at android.app.Activity.performCreate(Activity.java)
                      at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java)
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java)
                      at android.app.ActivityThread.access$900(ActivityThread.java)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java)
                      at android.os.Handler.dispatchMessage(Handler.java)
                      at android.os.Looper.loop(Looper.java)
                      at android.app.ActivityThread.main(ActivityThread.java)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java)
                   Caused by: java.lang.reflect.InvocationTargetException
                      at java.lang.reflect.Constructor.newInstance(Native Method)
                      at android.view.LayoutInflater.createView(LayoutInflater.java)
                      at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java)
                      at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java)
                      at android.view.LayoutInflater.rInflate(LayoutInflater.java)
                      at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java)
                      at android.view.LayoutInflater.inflate(LayoutInflater.java)
                      at android.view.LayoutInflater.inflate(LayoutInflater.java)
                      at android.view.LayoutInflater.inflate(LayoutInflater.java)
                      at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:287)
                      at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:139)
                      at com.example.zandrevanheerden.progressbartest.MainActivity.onCreate(MainActivity.java:11)
                      at android.app.Activity.performCreate(Activity.java)
                      at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java)
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java)
                      at android.app.ActivityThread.access$900(ActivityThread.java)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java)
                      at android.os.Handler.dispatchMessage(Handler.java)
                      at android.os.Looper.loop(Looper.java)
                      at android.app.ActivityThread.main(ActivityThread.java)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java)
                   Caused by: android.content.res.Resources$NotFoundException: Resource "com.example.zandrevanheerden.progressbartest:dimen/progress_inner_size" (7f050067) is not a Drawable (color or path): TypedValue{t=0x5/d=0x1c01 a=4 r=0x7f050067}
                      at android.content.res.Resources.loadDrawableForCookie(Resources.java)
                      at android.content.res.Resources.loadDrawable(Resources.java)
                      at android.content.res.Resources.getDrawable(Resources.java)
                      at android.content.res.Resources.getDrawable(Resources.java)
                      at com.f2prateek.progressbutton.ProgressButton.init(ProgressButton.java:147)
                      at com.f2prateek.progressbutton.ProgressButton.<init>(ProgressButton.java:116)
                      at com.f2prateek.progressbutton.ProgressButton.<init>(ProgressButton.java:111)
                      at java.lang.reflect.Constructor.newInstance(Native Method)
                      at android.view.LayoutInflater.createView(LayoutInflater.java)
                      at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java)
                      at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java)
                      at android.view.LayoutInflater.rInflate(LayoutInflater.java)
                      at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java)
                      at android.view.LayoutInflater.inflate(LayoutInflater.java)
                      at android.view.LayoutInflater.inflate(LayoutInflater.java)
                      at android.view.LayoutInflater.inflate(LayoutInflater.java)
                      at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:287)
                      at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:139)
                      at com.example.zandrevanheerden.progressbartest.MainActivity.onCreate(MainActivity.java:11)
                      at android.app.Activity.performCreate(Activity.java)
                      at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java)
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java)
                      at android.app.ActivityThread.access$900(ActivityThread.java)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java)
                      at android.os.Handler.dispatchMessage(Handler.java)
                      at android.os.Looper.loop(Looper.java)
                      at android.app.ActivityThread.main(ActivityThread.java)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java)
</code>```

Whats bothering me is that Android Studio is referring to a dimension and saying that it is not a drawable. The problem is that it should be pointing towards a dimension.

Is this a bug in the new gradle version or should I try a different library? I would just like to know what is causing this

答:
```<code>com.f2prateek.progressbutton.ProgressButton
</code>```

Do you have this view in this package?

You can also try Clean Project and Invalidate Cache and Restart Android Studio

Body:
this is my first question so please be merciful.

I have an app that is dependent on the following library: https://github.com/f2prateek/progressbutton

The library was working fine on pre Gradle 3. Now every time I run the app I get the following log:

___
FATAL EXCEPTION: main
                  Process: com.example.zandrevanheerden.progressbartest, PID: 2829
                  java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.zandrevanheerden.progressbartest/com.example.zandrevanheerden.progressbartest.MainActivity}: android.view.InflateException: Binary XML file line #0: Binary XML file line #0: Error inflating class com.f2prateek.progressbutton.ProgressButton
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java)
                      at android.app.ActivityThread.access$900(ActivityThread.java)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java)
                      at android.os.Handler.dispatchMessage(Handler.java)
                      at android.os.Looper.loop(Looper.java)
                      at android.app.ActivityThread.main(ActivityThread.java)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java)
                   Caused by: android.view.InflateException: Binary XML file line #0: Binary XML file line #0: Error inflating class com.f2prateek.progressbutton.ProgressButton
                      at android.view.LayoutInflater.inflate(LayoutInflater.java)
                      at android.view.LayoutInflater.inflate(LayoutInflater.java)
                      at android.view.LayoutInflater.inflate(LayoutInflater.java)
                      at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:287)
                      at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:139)
                      at com.example.zandrevanheerden.progressbartest.MainActivity.onCreate(MainActivity.java:11)
                      at android.app.Activity.performCreate(Activity.java)
                      at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java)
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java)
                      at android.app.ActivityThread.access$900(ActivityThread.java)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java)
                      at android.os.Handler.dispatchMessage(Handler.java)
                      at android.os.Looper.loop(Looper.java)
                      at android.app.ActivityThread.main(ActivityThread.java)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java)
                   Caused by: android.view.InflateException: Binary XML file line #0: Error inflating class com.f2prateek.progressbutton.ProgressButton
                      at android.view.LayoutInflater.createView(LayoutInflater.java)
                      at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java)
                      at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java)
                      at android.view.LayoutInflater.rInflate(LayoutInflater.java)
                      at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java)
                      at android.view.LayoutInflater.inflate(LayoutInflater.java)
                      at android.view.LayoutInflater.inflate(LayoutInflater.java)
                      at android.view.LayoutInflater.inflate(LayoutInflater.java)
                      at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:287)
                      at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:139)
                      at com.example.zandrevanheerden.progressbartest.MainActivity.onCreate(MainActivity.java:11)
                      at android.app.Activity.performCreate(Activity.java)
                      at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java)
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java)
                      at android.app.ActivityThread.access$900(ActivityThread.java)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java)
                      at android.os.Handler.dispatchMessage(Handler.java)
                      at android.os.Looper.loop(Looper.java)
                      at android.app.ActivityThread.main(ActivityThread.java)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java)
                   Caused by: java.lang.reflect.InvocationTargetException
                      at java.lang.reflect.Constructor.newInstance(Native Method)
                      at android.view.LayoutInflater.createView(LayoutInflater.java)
                      at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java)
                      at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java)
                      at android.view.LayoutInflater.rInflate(LayoutInflater.java)
                      at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java)
                      at android.view.LayoutInflater.inflate(LayoutInflater.java)
                      at android.view.LayoutInflater.inflate(LayoutInflater.java)
                      at android.view.LayoutInflater.inflate(LayoutInflater.java)
                      at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:287)
                      at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:139)
                      at com.example.zandrevanheerden.progressbartest.MainActivity.onCreate(MainActivity.java:11)
                      at android.app.Activity.performCreate(Activity.java)
                      at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java)
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java)
                      at android.app.ActivityThread.access$900(ActivityThread.java)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java)
                      at android.os.Handler.dispatchMessage(Handler.java)
                      at android.os.Looper.loop(Looper.java)
                      at android.app.ActivityThread.main(ActivityThread.java)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java)
                   Caused by: android.content.res.Resources$NotFoundException: Resource "com.example.zandrevanheerden.progressbartest:dimen/progress_inner_size" (7f050067) is not a Drawable (color or path): TypedValue{t=0x5/d=0x1c01 a=4 r=0x7f050067}
                      at android.content.res.Resources.loadDrawableForCookie(Resources.java)
                      at android.content.res.Resources.loadDrawable(Resources.java)
                      at android.content.res.Resources.getDrawable(Resources.java)
                      at android.content.res.Resources.getDrawable(Resources.java)
                      at com.f2prateek.progressbutton.ProgressButton.init(ProgressButton.java:147)
                      at com.f2prateek.progressbutton.ProgressButton.<init>(ProgressButton.java:116)
                      at com.f2prateek.progressbutton.ProgressButton.<init>(ProgressButton.java:111)
                      at java.lang.reflect.Constructor.newInstance(Native Method)
                      at android.view.LayoutInflater.createView(LayoutInflater.java)
                      at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java)
                      at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java)
                      at android.view.LayoutInflater.rInflate(LayoutInflater.java)
                      at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java)
                      at android.view.LayoutInflater.inflate(LayoutInflater.java)
                      at android.view.LayoutInflater.inflate(LayoutInflater.java)
                      at android.view.LayoutInflater.inflate(LayoutInflater.java)
                      at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:287)
                      at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:139)
                      at com.example.zandrevanheerden.progressbartest.MainActivity.onCreate(MainActivity.java:11)
                      at android.app.Activity.performCreate(Activity.java)
                      at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java)
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java)
                      at android.app.ActivityThread.access$900(ActivityThread.java)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java)
                      at android.os.Handler.dispatchMessage(Handler.java)
                      at android.os.Looper.loop(Looper.java)
                      at android.app.ActivityThread.main(ActivityThread.java)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java)

Whats bothering me is that Android Studio is referring to a dimension and saying that it is not a drawable. The problem is that it should be pointing towards a dimension.

Is this a bug in the new gradle version or should I try a different library? I would just like to know what is causing this

Body:
com.f2prateek.progressbutton.ProgressButton

Do you have this view in this package?

You can also try Clean Project and Invalidate Cache and Restart Android Studio


答:
If you want to push duplicate items then you need to push different instances of object instead of pushing the object reference.

Just check the below solution, it should be working as desired.

let myObject = {
"version": "2.0",
"worker": {
    "todo": []
 }
};
let myObjectArray = new Array();
myObjectArray.push(JSON.parse(JSON.stringify(myObject)));
myObjectArray.push(JSON.parse(JSON.stringify(myObject)));
myObjectArray[0]["worker"]["todo"] = "test";
console.log(myObjectArray);```

Title: Pushing a multidimensional array in javascript


问:
Group calls in Callkit
I've developed a VoIP app. I'm integrating now with callkit framework. Everything works well except conference.

The situation is the following:

1.) I make a call.

2.) Put first call on hold and make another.

3.) I click Conference button to merge both calls.

If I manually remove hold for first call, automatically second call is on hold.

I've read about CXSetGroupCallAction, but there is no match documentation.

Can someone help me?

Thanks.

答:
Call perform merge call action

```<code>    let call1UUID = UUID(uuidString: call1.callUUID)!
    let call2UUID = UUID(uuidString: call2.callUUID)!
    let mergeCallAction = CXSetGroupCallAction(call: call1UUID, callUUIDToGroupWith: call2UUID)

    let transaction = CXTransaction()
    transaction.addAction(mergeCallAction)

    callController.request(transaction) { (_) in

    }
</code>```

This will call provider delegate:

```<code>func provider(_ provider: CXProvider, perform action: CXSetGroupCallAction) {
    // perform merge call here where you merge ports of two call audio i/o
    action.fulfill()
}
</code>```

Title: Group calls in Callkit

Body:
Call perform merge call action

    let call1UUID = UUID(uuidString: call1.callUUID)!
    let call2UUID = UUID(uuidString: call2.callUUID)!
    let mergeCallAction = CXSetGroupCallAction(call: call1UUID, callUUIDToGroupWith: call2UUID)

    let transaction = CXTransaction()
    transaction.addAction(mergeCallAction)

    callController.request(transaction) { (_) in

    }

This will call provider delegate:

func provider(_ provider: CXProvider, perform action: CXSetGroupCallAction) {
    // perform merge call here where you merge ports of two call audio i/o
    action.fulfill()
}


问:
Is there a way to include duplicates from MySQL query: select..from..where..id in (list)
I am trying to get the results for the query type

```<code>SELECT * FROM table WHERE id IN(2,4,6,1,1,2) ORDER BY field (id,2,4,6,1,1,2)
</code>```

and I want to get results in the same order as the list including : the duplicates. The above query retains the order but cuts out duplicates. I know I can post-process the results but just wondering if there is an easier way.

Thanks

答:
How are you building the query?  If you're not opposed to doing a little manual work (which you could later wrap in some code), unions should get you what you need:

```<code>select id from table where id in (1, 2, 4, 6)
union all
select id from table where id in (6, 8);
</code>```

Returns:

```<code>------
| id |
|====|
| 1  |
| 2  |
| 4  |
| 6  |
| 6  |
| 8  |
------
</code>```

EDIT: Actually, I don't think that helps your ordering, though.  Let me play with this some more.

ContentLicense: CC BY-SA 2.5

Body:
I am trying to get the results for the query type

SELECT * FROM table WHERE id IN(2,4,6,1,1,2) ORDER BY field (id,2,4,6,1,1,2)

and I want to get results in the same order as the list including : the duplicates. The above query retains the order but cuts out duplicates. I know I can post-process the results but just wondering if there is an easier way.

Thanks

Body:
How are you building the query?  If you're not opposed to doing a little manual work (which you could later wrap in some code), unions should get you what you need:

select id from table where id in (1, 2, 4, 6)
union all
select id from table where id in (6, 8);

Returns:

------
| id |
|====|
| 1  |
| 2  |
| 4  |
| 6  |
| 6  |
| 8  |
------

EDIT: Actually, I don't think that helps your ordering, though.  Let me play with this some more.


问:
Browse Files and folders uploaded on Google Drive
I'm writing from Italy (sorry for mistakes), my question is about GOOGLE DRIVE API and
I'm writing here because the G-Suite support wrote me to contact you, I'm not a programmer.

The big question is: how can I browse folders and files uploaded on my Google Drive Api?

I write you what apppened.

I wanted to use a backup program to save in a planned way files and folders an Google Drive.
I downloaded the program (Iperius Backup) and followed the instructions.
To understand on what I did, I paste the link of the instructions below:

http://www.iperiusbackup.net/en/backup-to-google-drive/

http://www.iperiusbackup.net/en/how-to-enable-google-drive-api-and-get-client-credentials/

I tried the software and everything worked.

So I opened Google Drive but the back-upped files weren't there.

Seen that there was something not clear, I have erased all the files on my Google Drive. I wanted  to make sure that it was empty, hoping to erase also “hidden files”(...even if I thought it wouldn't have been so simple...)

To make sure that everything was erased (also  “hidden files”), I tried to restore files from the backup software but unfortunately, the software worked well...the files were still there, somewhere...

This means that I have saved through the backup software files and folders on Google Drive “Api”, but I cannot manage them.

How can I have access to my space in Google Drive Api and erase all my files and folders that are still there?

Thank you in advance for the help,

best regards,

Stefano

答:
To list all files in your drive, you can use Files: list.

This method accepts the q parameter, which is a search query
  combining one or more search terms. For more information, see the
  Search for Files and Team Drives guide.

You can use the Try it now or use the sample code given in a specific language you are using.

To delete/erase a file, use Files: delete.

Permanently deletes a file by ID. Skips the trash. The currently
  authenticated user must own the file or be an organizer on the parent
  for Team Drive files. Try it now or see an example.


问:
Global variable at top of the JavaScript file
Say I declare a global JavaScript variable at the top of a JavaScript file to equal 0

i.e.

```<code>var jVar=0;
</code>```

Then I call a function in the JavaScript to set that variable to 1
ie.

```<code>function setVarToOne(){
    jVar=1;
}
</code>```

If I then reload the page what will the variable equal before the setVarToOne function is called ?

Will the jVar keep the value it was set to in the function or will it be re-initialised to 0?

What I need to understand is, what happens to JavaScript variables when the page is reloaded?

Thanks

答:
Your variable will be set to 0.

When you reload the page the whole script start running again from the beginning - thus running var jVar=0 first.

If you need to save your data you can use local storage, session storage, cookies or persist it on a server.

Take a look at this question that talks about persisting variables between page loads.

Body:
Say I declare a global JavaScript variable at the top of a JavaScript file to equal 0

i.e.

var jVar=0;

Then I call a function in the JavaScript to set that variable to 1
ie.

function setVarToOne(){
    jVar=1;
}

If I then reload the page what will the variable equal before the setVarToOne function is called ?

Will the jVar keep the value it was set to in the function or will it be re-initialised to 0?

What I need to understand is, what happens to JavaScript variables when the page is reloaded?

Thanks


Title: json to DataFrame conversion issues

Body:
{'endDate': '2017-12-31',
 'results': [{'data': [{'period': '2017-01-01', 'ratio': 26.91301},
    {'period': '2017-02-01', 'ratio': 19.77063},
    {'period': '2017-03-01', 'ratio': 20.40775},
    {'period': '2017-04-01', 'ratio': 16.02843},
    {'period': '2017-05-01', 'ratio': 10.38159},
    {'period': '2017-06-01', 'ratio': 8.2087},
    {'period': '2017-07-01', 'ratio': 8.67815},
    {'period': '2017-08-01', 'ratio': 19.58956},
    {'period': '2017-09-01', 'ratio': 36.94587},
    {'period': '2017-10-01', 'ratio': 36.28194},
    {'period': '2017-11-01', 'ratio': 16.64543},
    {'period': '2017-12-01', 'ratio': 1.67661}],
   'keywords': ['Data_spec'],
   'title': 'Data_spec'},
  {'data': [{'period': '2017-01-01', 'ratio': 17.65139},
    {'period': '2017-02-01', 'ratio': 14.52618},
    {'period': '2017-03-01', 'ratio': 15.00234},
    {'period': '2017-04-01', 'ratio': 12.1521},
    {'period': '2017-05-01', 'ratio': 10.63644},
    {'period': '2017-06-01', 'ratio': 8.59767},
    {'period': '2017-07-01', 'ratio': 8.95312},
    {'period': '2017-08-01', 'ratio': 13.05747},
    {'period': '2017-09-01', 'ratio': 48.00482},
    {'period': '2017-10-01', 'ratio': 23.7811},
    {'period': '2017-11-01', 'ratio': 16.90027},
    {'period': '2017-12-01', 'ratio': 0.89866}],
   'keywords': ['Data_rate'],
   'title': 'Date_rate'},
  {'data': [], 'keywords': ['Data_over'], 'title': 'Data_over'},
  {'data': [{'period': '2017-01-01', 'ratio': 79.17644},
    {'period': '2017-02-01', 'ratio': 84.01851},
    {'period': '2017-03-01', 'ratio': 100.0},
    {'period': '2017-04-01', 'ratio': 91.19442},
    {'period': '2017-05-01', 'ratio': 93.21976},
    {'period': '2017-06-01', 'ratio': 93.42096},
    {'period': '2017-07-01', 'ratio': 89.14895},
    {'period': '2017-08-01', 'ratio': 91.85165},
    {'period': '2017-09-01', 'ratio': 91.24136},
    {'period': '2017-10-01', 'ratio': 90.35611},
    {'period': '2017-11-01', 'ratio': 81.88585},
    {'period': '2017-12-01', 'ratio': 7.49111}],
   'keywords': ['Data_under'],
   'title': 'Data_under'},
  {'data': [{'period': '2017-01-01', 'ratio': 0.70417},
    {'period': '2017-02-01', 'ratio': 1.11997},
    {'period': '2017-03-01', 'ratio': 1.81074},
    {'period': '2017-04-01', 'ratio': 1.38823},
    {'period': '2017-05-01', 'ratio': 0.97914},
    {'period': '2017-06-01', 'ratio': 1.14009},
    {'period': '2017-07-01', 'ratio': 0.78465},
    {'period': '2017-08-01', 'ratio': 1.07973},
    {'period': '2017-09-01', 'ratio': 0.94561},
    {'period': '2017-10-01', 'ratio': 0.85172},
    {'period': '2017-11-01', 'ratio': 1.27422},
    {'period': '2017-12-01', 'ratio': 0.08718}],
   'keywords': ['Data_tune'],
   'title': 'Data_tune'}],
 'startDate': '2017-01-01',
 'timeUnit': 'month'}

Above is 'my_dict = json.loads(js)' where js is string. I am trying to put these data to Pandas DataFrame. I used code below.

lst = [pd.DataFrame.from_dict(r['data']).set_index('period').rename(columns={'ratio' : r['title']})
           for r in d['results']]
df = pd.concat(lst, 1)

My code worked perfectly until this js set have empty value.
One problem is that you have noticed the 'keyworks' : ['Data_over'] has empty 'data'. So I cannot set index as 'period'. I still want the 'Data_over' in my pandas DF but empty. Is it possible to set the DataFrame with 'Data_over' as column name but empty on the value? so my final code can convert json to df with or with out 'Data'.

Below is the output that I want. (actual values are different, but you got the concept)

    Data_spec    Data_rate   Data_over   Data_under   Data_tune
2017-01-01  0.55116     NaN     NaN         7.12056     2.25329
2017-02-01  0.32016     0.08915     NaN         6.43161     1.19959
2017-03-01  0.32421     0.10131     NaN         6.48024     1.30091
2017-04-01  0.33232     0.01215     NaN         6.05471     1.26038
2017-05-01  0.39311     0.12968     NaN         6.19655     1.21985
2017-06-01  0.47011     0.03647     NaN         5.71023     1.03748
2017-07-01  4.32016     NaN     NaN         11.85005    0.84295
2017-08-01  8.81053     0.04052     NaN         51.44072    0.89564
2017-09-01  14.46808    0.02836     NaN         100.00000   0.85511
2017-10-01  4.27152     0.10942     NaN         34.65451    0.87132
2017-11-01  0.29989     0.05673     NaN         13.02127    0.77811
2017-12-01  0.00810     0.06079     NaN         0.80243     NaN

Body:
There is possible check length by len(r['data']) > 0 and filter out empty DataFrames in list comprehension:

lst = [pd.DataFrame(r['data']).set_index('period').rename(columns={'ratio' : r['title']})
           for r in d['results'] if len(r['data']) > 0]
df = pd.concat(lst, 1)
print (df)

            Data_spec  Date_rate  Data_under  Data_tune
period
2017-01-01   26.91301   17.65139    79.17644    0.70417
2017-02-01   19.77063   14.52618    84.01851    1.11997
2017-03-01   20.40775   15.00234   100.00000    1.81074
2017-04-01   16.02843   12.15210    91.19442    1.38823
2017-05-01   10.38159   10.63644    93.21976    0.97914
2017-06-01    8.20870    8.59767    93.42096    1.14009
2017-07-01    8.67815    8.95312    89.14895    0.78465
2017-08-01   19.58956   13.05747    91.85165    1.07973
2017-09-01   36.94587   48.00482    91.24136    0.94561
2017-10-01   36.28194   23.78110    90.35611    0.85172
2017-11-01   16.64543   16.90027    81.88585    1.27422
2017-12-01    1.67661    0.89866     7.49111    0.08718

EDIT:

There si possible create custom DataFrame if r['data'] are empty, for align index is used d['startDate']:

lst = [pd.DataFrame(r['data']).set_index('period').rename(columns={'ratio' : r['title']})
        if len(r['data']) > 0
        else pd.DataFrame([np.nan], columns=[r['title']], index=[d['startDate']])
        for r in d['results'] ]
df = pd.concat(lst, 1)
print (df)
            Data_spec  Date_rate  Data_over  Data_under  Data_tune
2017-01-01   26.91301   17.65139        NaN    79.17644    0.70417
2017-02-01   19.77063   14.52618        NaN    84.01851    1.11997
2017-03-01   20.40775   15.00234        NaN   100.00000    1.81074
2017-04-01   16.02843   12.15210        NaN    91.19442    1.38823
2017-05-01   10.38159   10.63644        NaN    93.21976    0.97914
2017-06-01    8.20870    8.59767        NaN    93.42096    1.14009
2017-07-01    8.67815    8.95312        NaN    89.14895    0.78465
2017-08-01   19.58956   13.05747        NaN    91.85165    1.07973
2017-09-01   36.94587   48.00482        NaN    91.24136    0.94561
2017-10-01   36.28194   23.78110        NaN    90.35611    0.85172
2017-11-01   16.64543   16.90027        NaN    81.88585    1.27422
2017-12-01    1.67661    0.89866        NaN     7.49111    0.08718


问:
Failed to import new Gradle project: failed to find Build Tools revision *.0.0
When I boot up Android Studio and select "New Project..." and go through creating a new project, I get this popup error:

Failed to import new Gradle project: failed to find Build Tools revision 17.0.0

Consult IDE log for more details (Help | Show Log)

I would love to consult the IDE log, but I haven't even managed to get into the application to do much of anything. I've went through the preferences multiple times to see if I can set a path for the Build Tools, but I can't find much of anything. How do I fix this, or how do I get into the application without opening a project so I can at least see the logs?

答: Uninstall the Android SDK Tools and then reinstall them from Tools > SDK Manager.


问:
Debugging firebase cloud functions
How do I debug with visual studio code firebase-database trigger functions?
I tried the emulator, but I get an error when I call this

```<code>functions debug myMethod

C:\functions\functions>functions debug createUserChat
ERROR: Error: Function myMethod in location us-central1 in project myProject does not exist
at C:\Users\Dev\AppData\Roaming\npm\node_modules\@google-cloud\functions-emulator\node_modules\grpc\src\client.js:554:15
</code>```

This code I want to debug

```<code>require('@google-cloud/debug-agent').start({ allowExpressions: true });;

const functions = require('firebase-functions'),
        admin = require('firebase-admin'),
        logging = require('@google-cloud/logging')();
        admin.initializeApp(functions.config().firebase);

exports.myMethod= functions.database.ref('Tasks/{taskID}/taskStatus').onUpdate(event =>{
       // do sth.
});
</code>```

this is my launch file

```<code>{
"version": "0.2.0",
"configurations": [
    {
        "name": "Debug Function",
        "type": "node",
        "request": "attach",
        "port": 5858
    }
]
}
</code>```

答:
debug-agent required only for remote debugging. If you want to debug function locally use Cloud Functions Emulator.

https://cloud.google.com/functions/docs/emulator

Title: Debugging firebase cloud functions

Body:
How do I debug with visual studio code firebase-database trigger functions?
I tried the emulator, but I get an error when I call this

functions debug myMethod

C:\functions\functions>functions debug createUserChat
ERROR: Error: Function myMethod in location us-central1 in project myProject does not exist
at C:\Users\Dev\AppData\Roaming\npm\node_modules\@google-cloud\functions-emulator\node_modules\grpc\src\client.js:554:15

This code I want to debug

require('@google-cloud/debug-agent').start({ allowExpressions: true });;

const functions = require('firebase-functions'),
        admin = require('firebase-admin'),
        logging = require('@google-cloud/logging')();
        admin.initializeApp(functions.config().firebase);

exports.myMethod= functions.database.ref('Tasks/{taskID}/taskStatus').onUpdate(event =>{
       // do sth.
});

this is my launch file

{
"version": "0.2.0",
"configurations": [
    {
        "name": "Debug Function",
        "type": "node",
        "request": "attach",
        "port": 5858
    }
]
}


问:
Android Realm openTransaction doesn't return
I'm trying to update Realm in my app from version 0.85 to version 4.1.1. In some cases, realm.beginTransaction doesn't return. I tried to replace it by realm.executeTransaction with no effect. Here are the verbose logs of Realm:

```<code>V/REALM_JNI:  --> Java_io_realm_internal_OsSchemaInfo_nativeCreateFromList
V/REALM_JNI:  --> Java_io_realm_internal_OsRealmConfig_nativeCreate
V/REALM_JNI:  --> Java_io_realm_internal_OsRealmConfig_nativeSetInMemory -1605354496
V/REALM_JNI:  --> Java_io_realm_internal_OsRealmConfig_nativeEnableChangeNotification -1605354496
V/REALM_JNI:  --> Java_io_realm_internal_OsRealmConfig_nativeSetSchemaConfig -1605354496
V/REALM_JNI:  --> Java_io_realm_internal_SharedRealm_nativeGetSharedRealm -1605354496
V/REALM_JNI:  --> Java_io_realm_internal_SharedRealm_nativeGetSchemaInfo -1605349584
V/REALM_JNI:  --> Java_io_realm_internal_SharedRealm_nativeSetAutoRefresh -1605349584
V/REALM_JNI:  --> Java_io_realm_internal_SharedRealm_nativeRegisterSchemaChangedCallback -1605349584
V/REALM_JNI:  --> Java_io_realm_internal_SharedRealm_nativeIsClosed -1605349584
V/REALM_JNI:  --> Java_io_realm_internal_SharedRealm_nativeBeginTransaction -1605349584
</code>```

So it looks to me that Relam is stuck while calling SharedRealm.nativeBeginTransaction, which matches what I saw when debugging.

Here's my project build.gradle

```<code>buildscript {
    repositories {
        jcenter()
        maven { url "https://jitpack.io" }
        google()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0'
        classpath 'com.google.gms:google-services:3.1.0'
        classpath ('io.realm:realm-gradle-plugin:4.1.1'){
            exclude group: 'com.google.guava'
        }
        classpath ('com.google.firebase:firebase-plugins:1.1.0'){
            exclude group: 'com.google.guava', module: 'guava-jdk5'
        }

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}
</code>```

And my module build.gradle

```<code>apply plugin: 'com.android.application'
apply plugin: 'com.google.firebase.firebase-crash'
apply plugin: 'realm-android'

// increment code and change version name on every released build
def code = 93
def version = "1.1.8"

android {
    compileSdkVersion 26
    buildToolsVersion "26.0.2"

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    defaultConfig {
        minSdkVersion 15
        targetSdkVersion 26
        versionCode code
        versionName "$version"

        multiDexEnabled true
    }

    aaptOptions {
        additionalParameters "--no-version-vectors"
    }

    buildTypes {
        release {
            buildConfigField "boolean", "DEV", "false"
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            signingConfig signingConfigs.release
            multiDexEnabled false
        }
        debug {
            buildConfigField "boolean", "DEV", "true"
            signingConfig signingConfigs.release
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:multidex:1.0.2'
    implementation 'com.android.support:appcompat-v7:26.1.0'
    implementation 'com.android.support:cardview-v7:26.1.0'
    implementation 'com.android.support:customtabs:26.1.0'
    implementation 'com.android.support:recyclerview-v7:26.1.0'
    implementation 'com.android.support:design:26.1.0'
    implementation 'com.google.guava:guava:23.4-android'
    implementation 'uk.co.chrisjenx:calligraphy:2.2.0'
    implementation 'com.makeramen:roundedimageview:2.0.1'
    implementation 'com.davemorrissey.labs:subsampling-scale-image-view:3.6.0'
    implementation 'com.google.android.gms:play-services-analytics:11.6.0'
    implementation 'com.google.firebase:firebase-messaging:11.6.0'
    implementation 'com.google.android.gms:play-services-location:11.6.0'
    implementation 'com.google.firebase:firebase-crash:11.6.0'
    implementation 'net.hockeyapp.android:HockeySDK:5.0.3'
    implementation 'com.squareup.picasso:picasso:2.5.2'
    implementation 'com.squareup.okhttp3:okhttp:3.9.0'
    implementation 'com.squareup.okio:okio:1.13.0'
    implementation 'com.squareup:otto:1.3.8'
    implementation 'com.google.code.gson:gson:2.8.2'
    implementation 'com.github.JakeWharton:ViewPagerIndicator:2.4.1'
    implementation 'com.facebook.android:facebook-android-sdk:4.28.0'
}

apply plugin: 'com.google.gms.google-services'
</code>```

I'm using Android Studio 3.0 and had to enable D8 for building

Any idea about what's happening?

答: Issue happened because realm.beginTransaction() doesn't return if it's blocked by a write transaction that is occurring on a different thread at the same time. In my case, this was due to a call to RealmResults.clear(). It was fixed by replacing it by deleteAllFromRealm()</p>

Body:
I'm trying to update Realm in my app from version 0.85 to version 4.1.1. In some cases, realm.beginTransaction doesn't return. I tried to replace it by realm.executeTransaction with no effect. Here are the verbose logs of Realm:

V/REALM_JNI:  --> Java_io_realm_internal_OsSchemaInfo_nativeCreateFromList
V/REALM_JNI:  --> Java_io_realm_internal_OsRealmConfig_nativeCreate
V/REALM_JNI:  --> Java_io_realm_internal_OsRealmConfig_nativeSetInMemory -1605354496
V/REALM_JNI:  --> Java_io_realm_internal_OsRealmConfig_nativeEnableChangeNotification -1605354496
V/REALM_JNI:  --> Java_io_realm_internal_OsRealmConfig_nativeSetSchemaConfig -1605354496
V/REALM_JNI:  --> Java_io_realm_internal_SharedRealm_nativeGetSharedRealm -1605354496
V/REALM_JNI:  --> Java_io_realm_internal_SharedRealm_nativeGetSchemaInfo -1605349584
V/REALM_JNI:  --> Java_io_realm_internal_SharedRealm_nativeSetAutoRefresh -1605349584
V/REALM_JNI:  --> Java_io_realm_internal_SharedRealm_nativeRegisterSchemaChangedCallback -1605349584
V/REALM_JNI:  --> Java_io_realm_internal_SharedRealm_nativeIsClosed -1605349584
V/REALM_JNI:  --> Java_io_realm_internal_SharedRealm_nativeBeginTransaction -1605349584

So it looks to me that Relam is stuck while calling SharedRealm.nativeBeginTransaction, which matches what I saw when debugging.

Here's my project build.gradle

buildscript {
    repositories {
        jcenter()
        maven { url "https://jitpack.io" }
        google()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0'
        classpath 'com.google.gms:google-services:3.1.0'
        classpath ('io.realm:realm-gradle-plugin:4.1.1'){
            exclude group: 'com.google.guava'
        }
        classpath ('com.google.firebase:firebase-plugins:1.1.0'){
            exclude group: 'com.google.guava', module: 'guava-jdk5'
        }

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

And my module build.gradle

apply plugin: 'com.android.application'
apply plugin: 'com.google.firebase.firebase-crash'
apply plugin: 'realm-android'

// increment code and change version name on every released build
def code = 93
def version = "1.1.8"

android {
    compileSdkVersion 26
    buildToolsVersion "26.0.2"

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    defaultConfig {
        minSdkVersion 15
        targetSdkVersion 26
        versionCode code
        versionName "$version"

        multiDexEnabled true
    }

    aaptOptions {
        additionalParameters "--no-version-vectors"
    }

    buildTypes {
        release {
            buildConfigField "boolean", "DEV", "false"
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            signingConfig signingConfigs.release
            multiDexEnabled false
        }
        debug {
            buildConfigField "boolean", "DEV", "true"
            signingConfig signingConfigs.release
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:multidex:1.0.2'
    implementation 'com.android.support:appcompat-v7:26.1.0'
    implementation 'com.android.support:cardview-v7:26.1.0'
    implementation 'com.android.support:customtabs:26.1.0'
    implementation 'com.android.support:recyclerview-v7:26.1.0'
    implementation 'com.android.support:design:26.1.0'
    implementation 'com.google.guava:guava:23.4-android'
    implementation 'uk.co.chrisjenx:calligraphy:2.2.0'
    implementation 'com.makeramen:roundedimageview:2.0.1'
    implementation 'com.davemorrissey.labs:subsampling-scale-image-view:3.6.0'
    implementation 'com.google.android.gms:play-services-analytics:11.6.0'
    implementation 'com.google.firebase:firebase-messaging:11.6.0'
    implementation 'com.google.android.gms:play-services-location:11.6.0'
    implementation 'com.google.firebase:firebase-crash:11.6.0'
    implementation 'net.hockeyapp.android:HockeySDK:5.0.3'
    implementation 'com.squareup.picasso:picasso:2.5.2'
    implementation 'com.squareup.okhttp3:okhttp:3.9.0'
    implementation 'com.squareup.okio:okio:1.13.0'
    implementation 'com.squareup:otto:1.3.8'
    implementation 'com.google.code.gson:gson:2.8.2'
    implementation 'com.github.JakeWharton:ViewPagerIndicator:2.4.1'
    implementation 'com.facebook.android:facebook-android-sdk:4.28.0'
}

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

I'm using Android Studio 3.0 and had to enable D8 for building

Any idea about what's happening?


问:
How can I enable Pascal casing by default when using Jackson JSON in Spring MVC?
I have a project that uses Spring MVC to create and handle multiple REST endpoints. I'm currently working on using Jackson to automatically handle the seralization/deserialization of JSON using the @RequestBody and @ResponseBody annotations.

I have gotten Jackson working, so I've got a starting point. My problem is that our old serialization was done manually and used Pascal casing instead of Camel casing ("MyVariable" instead of "myVariable"), and Jackson does Camel casing by default.

I know that I can manually change the name for a variable using @JsonProperty. That being said, I do not consider adding @JsonProperty to all of my variables to be a viable long-term solution.

Is there a way to make Jackson use Pascal casing when serializing and deserializing other than using the @JsonProperty annotation?

EDIT: It looks like there's not a clean way to do this externally. A couple people have suggested overriding different classes as a way to accomplish my goal. I'm open to suggestions on what I can override that will change the casing. At the moment I have made a custom ObjectMapper that sets some properties I want (namely Inclusion.NON_NULL). I haven't found any place yet that would let me change the casing behavior. Any thoughts?

答:
I ended up solving the issue by overriding the (de)serializers. For those interested, here's how you can do it yourself:

Step 1. Extend BeanSerializerFactory.

Override the _constructWriter(SerializationConfig config, TypeBindings typeContext, PropertyBuilder pb, boolean staticTyping, String name, AnnotatedMember propertyMember) method. Inside that method, modify name in any way you see fit. To implement Pascal casing, I used this line: String formattedName = name.substring(0, 1).toUpperCase() + name.substring(1);. After modifying name, call super._constructWriter.

Step 2. Extend BeanDeserializationFactory.

Override the constructSettableProperty(DeserializationConfig config, BasicBeanDescription beanDesc, String name, AnnotatedMethod setter) method. Do the same thing with the name parameter that you did inside your custom BeanSerializerFactory.

Step 3. Create an ObjectMapper.

Set the serializer factory to be your custom bean serializer factory. Set the deserializer provider (I used this line: objectMapper.setDeserializerProvider(new StdDeserializerProvider(new CustomJacksonBeanDeserializerFactory()))).

That's it. The ObjectMapper you created will use your new naming scheme when serializing or deserializing JSON.


问:
Hibernate-search elasticsearch data indexing is synchronous or Asynchronous
We are implementing hibernate-search elasticsearch in our project and need a clarification.

After em.persist if the transaction is committed, is the data indexed into elasticsearch in a sync mode or async mode. Basically will the method return after the em.persist commit or will it ensure the data is indexed in elasticsearch. In the following video https://www.youtube.com/watch?v=_NGnbON3xAo at 17:30 I hear that the data is put on a queue and will be indexed in es in batch after db commit. So if elasticsearch indexing fails for some reason I might want to implement a manual db rollback so that the data is in consistent state in both the stores

Thanks in advance

答:
Data is sent to Elasticsearch on commit, either synchronously or asynchronously depending on your settings.

If you're interested in changing those settings, have a look at the documentation: https://docs.jboss.org/hibernate/stable/search/reference/en-US/html_single/#configuration-worker

EDIT: Also, even in synchronous mode, Elasticsearch is "near-real-time", meaning even if the changes have been processed, they won't be visible until a small period of time after your changes. So you might also have a look at the hibernate.search.default.elasticsearch.refresh_after_write configuration setting. From the docs:

Whether to perform an explicit refresh after a set of operations has been executed against a
  specific index (true or false)

hibernate.search.default.elasticsearch.refresh_after_write false
  (default)

This is useful in unit tests to ensure that a write is visible by a
  query immediately without delay. This keeps unit tests simpler. You
  should not rely on the synchronous behaviour for your production code
  except in rare cases as Elasticsearch is optimised for asynchronous
  writes: leave at false for optimal performance.


问:
iOS Register for notifications in background
I need to refresh push token if user don't run app for long time. I tried to use background mode and     application:performFetchWithCompletionHandler:
method. Inside this method I call - registerUserNotificationSettings:(UIUserNotificationSettings )notificationSettings. And then I expect that didRegisterUserNotificationSettings (UIUserNotificationSettings)notificationSettings will be called but this not happen. Is there any way to register in APNS without running app?

答:
Simple Answer is No

APNs can issue a new device token for a variety of reasons:

User installs your app on a new device
User restores device from a backup
User reinstalls the operating system
Other system-defined events
As a result, apps must request the device token at launch time, as described in APNs-to-Device Connection Trust and Device Tokens. For code examples, see Registering to Receive Remote Notifications.

Apple Documentation : https://developer.apple.com/library/content/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/APNSOverview.html


问:
Group array by inner value in PHP
I'm quite new in PHP and I'm having problems to even start to solve this issue.

Having this kind of array:

```<code>Array (
   [0] => Array (
          [title] => "Test string"
          [lat] => "40.4211"
          [long] => "-3.70118"
          )
   [1] => Array (
          [title] => "Test string 2"
          [lat] => "10.0"
          [long] => "-23.0"
          )
   [2] => Array (
          [title] => "Test string 3"
          [lat] => "10.0"
          [long] => "-23.0"
          )
   [3] => Array (
          [cust] => "Test string 4"
          [type] => "5.0"
          [level] => "-1.34"
          )
)
</code>```

I would like to create a new inner array for the ones that contains the same lat and long. In the example above the ones of #1 and #2 have the same lat and log (10.0 and -23.0).

```<code>Array (
   [0] => Array (
          [title] => "Test string"
          [lat] => "40.4211"
          [long] => "-3.70118"
          )
   [1] => Array (
            [0] => Array (
                  [title] => "Test string 2"
                  [lat] => "10.0"
                  [long] => "-23.0"
                  )
            [1] => Array (
                  [title] => "Test string 3"
                  [lat] => "10.0"
                  [long] => "-23.0"
                  )
          )
   [2] => Array (
          [cust] => "Test string 4"
          [type] => "5.0"
          [level] => "-1.34"
          )
)
</code>```

How can I archieve this? Thanks in advance.

答:
Use this:</p>

```<code>  $result = array();
    foreach ($yourArrayList as $data) {
        $id = $data['lat'];
        if (isset($result[$id])) {
            $result[$id][] = $data;
        } else {
            $result[$id] = array($data);
        }
    }
</code>```

Title: Group array by inner value in PHP

Body:
I'm quite new in PHP and I'm having problems to even start to solve this issue.

Having this kind of array:

Array (
   [0] => Array (
          [title] => "Test string"
          [lat] => "40.4211"
          [long] => "-3.70118"
          )
   [1] => Array (
          [title] => "Test string 2"
          [lat] => "10.0"
          [long] => "-23.0"
          )
   [2] => Array (
          [title] => "Test string 3"
          [lat] => "10.0"
          [long] => "-23.0"
          )
   [3] => Array (
          [cust] => "Test string 4"
          [type] => "5.0"
          [level] => "-1.34"
          )
)

I would like to create a new inner array for the ones that contains the same lat and long. In the example above the ones of #1 and #2 have the same lat and log (10.0 and -23.0).

Array (
   [0] => Array (
          [title] => "Test string"
          [lat] => "40.4211"
          [long] => "-3.70118"
          )
   [1] => Array (
            [0] => Array (
                  [title] => "Test string 2"
                  [lat] => "10.0"
                  [long] => "-23.0"
                  )
            [1] => Array (
                  [title] => "Test string 3"
                  [lat] => "10.0"
                  [long] => "-23.0"
                  )
          )
   [2] => Array (
          [cust] => "Test string 4"
          [type] => "5.0"
          [level] => "-1.34"
          )
)

How can I archieve this? Thanks in advance.

Body:
Use this:

  $result = array();
    foreach ($yourArrayList as $data) {
        $id = $data['lat'];
        if (isset($result[$id])) {
            $result[$id][] = $data;
        } else {
            $result[$id] = array($data);
        }
    }


答:
It will be 0.

Javascript can't persist state in between 2 page loads by default. You could try first saving and then reading data from some store. Either by API call or by saving it to localStorage, cookie or some other data storage.

Title: Global variable at top of the JavaScript file


问:
Error in installation and loading of the "scales" packages in R studio server version 1.0.153
I am using R Studio Server version 1.0.153. I just got the "scales" package installed version 0.5.0 . But when loading the package library(scales), I get the following error:

```<code>Error in [[3L]](cond):
Package 'scales' version 0.4.1 cannot be unloaded:
Error in unloadNamespace(package) : namespace 'scales' is imported by
'ggplot2' so cannot be unloaded.
</code>```

Please help me with a possible solution.Thanks a lot.

答:
Also install the ggplot2 library in the R studio
Any don't forget to import library in the console before using it</p>

Body:
I am using R Studio Server version 1.0.153. I just got the "scales" package installed version 0.5.0 . But when loading the package library(scales), I get the following error:

Error in [[3L]](cond):
Package 'scales' version 0.4.1 cannot be unloaded:
Error in unloadNamespace(package) : namespace 'scales' is imported by
'ggplot2' so cannot be unloaded.

Please help me with a possible solution.Thanks a lot.


问:
list sorting case insensitive using operator.attrgetter
hi i have list of dictionaries .. and i want to sort it case insensitive

```<code>members = Person.objects.filter(person=person_id)
members_list = list(members)

members_list.sort( key = operator.attrgetter( sort_by ), reverse = False )
</code>```

here sort_by have attribute name by whom i want to sort.
Now how can i sort with case insensitive ??

Please help..

答:
If sort_by is a variable containing a string with the name of the attribute you want to use for sorting and you want to use operator.attrgetter(), you could use this which converts the value of the attribute it fetches to all lowercase characters for comparisons during the sort:

```<code>members_list.sort( key = lambda mbr: operator.attrgetter( sort_by )( mbr ).lower(),
                   reverse = False )
</code>```

Although something like the following is easier to read as well as more efficient:

```<code>get_key = operator.attrgetter( sort_by )
members_list.sort( key = lambda mbr: get_key( mbr ).lower(), reverse = False )
</code>```

Body:
hi i have list of dictionaries .. and i want to sort it case insensitive

members = Person.objects.filter(person=person_id)
members_list = list(members)

members_list.sort( key = operator.attrgetter( sort_by ), reverse = False )

here sort_by have attribute name by whom i want to sort.
Now how can i sort with case insensitive ??

Please help..

Body:
If sort_by is a variable containing a string with the name of the attribute you want to use for sorting and you want to use operator.attrgetter(), you could use this which converts the value of the attribute it fetches to all lowercase characters for comparisons during the sort:

members_list.sort( key = lambda mbr: operator.attrgetter( sort_by )( mbr ).lower(),
                   reverse = False )

Although something like the following is easier to read as well as more efficient:

get_key = operator.attrgetter( sort_by )
members_list.sort( key = lambda mbr: get_key( mbr ).lower(), reverse = False )


问:
nmap deploy on AWS Server
Is it possible to deploy nmap on AWS server. If yes, please guide me how I will do that. Nmap will run for a port scanning on our internet facing servers.

Please let me know if any other details is required.

答: You can do network scans from AWS services, but you need to fill out a request form; otherwise, you will breach their acceptable use policy. You can find more information about the actual request process here </p>

Title: nmap deploy on AWS Server


问:
Pyglet GL_QUADS and GL_POLYGON not working properly
I'm trying to write a simple game and for some reason the graphics primitives aren't working properly on my machine (Win7/NVIDIA Quadro K2100M). I'm trying to draw a rectangle but whenever I use GL_QUADS or GL_POLYGON it comes with a weird bend in it. It works with GL_QUAD_STRIP, oddly, but that's really not ideal since I don't want the ones I"m drawing to be connected. I really have no idea what the problem could be...

Example code:

```<code>import pyglet

window = pyglet.window.Window(width=400, height=400)
batch = pyglet.graphics.Batch()
white = [255]*4
batch.add(4, pyglet.gl.GL_QUADS, None, ('v2i',[10,10,10,50,390,10,390,50]), ('c4B',white*4))

batch.add(4, pyglet.gl.GL_POLYGON, None, ('v2i',[10,60,10,110,390,60,390,110]), ('c4B',white*4))
batch.add(4, pyglet.gl.GL_QUAD_STRIP, None, ('v2i',[10,120,10,170,390,120,390,170]), ('c4B',white*4))

@window.event
def on_draw():
    batch.draw()

pyglet.app.run()
</code>```

答: I'm so stupid: I put the points in the wrong order so it drew (top left, bottom left, top right, bottom right) and of course this would be the result X_X</p>

Body:
I'm trying to write a simple game and for some reason the graphics primitives aren't working properly on my machine (Win7/NVIDIA Quadro K2100M). I'm trying to draw a rectangle but whenever I use GL_QUADS or GL_POLYGON it comes with a weird bend in it. It works with GL_QUAD_STRIP, oddly, but that's really not ideal since I don't want the ones I"m drawing to be connected. I really have no idea what the problem could be...

Example code:

import pyglet

window = pyglet.window.Window(width=400, height=400)
batch = pyglet.graphics.Batch()
white = [255]*4
batch.add(4, pyglet.gl.GL_QUADS, None, ('v2i',[10,10,10,50,390,10,390,50]), ('c4B',white*4))

batch.add(4, pyglet.gl.GL_POLYGON, None, ('v2i',[10,60,10,110,390,60,390,110]), ('c4B',white*4))
batch.add(4, pyglet.gl.GL_QUAD_STRIP, None, ('v2i',[10,120,10,170,390,120,390,170]), ('c4B',white*4))

@window.event
def on_draw():
    batch.draw()

pyglet.app.run()


答:
When you reload the page, everything in JavaScript will be lost and the code will execute like when you load the page for the first time.

That means, your variable will be initialized to 0, and when the function is called, the variable will be set to 1.


问:
Dynamic Programming: Counting numbers in between
Given two numbers X and Y, how many numbers exist between them inclusive that have at least half their digits the same? For example, 1122 and 4444 would work, while 11234 and 112233 would not work.

Obviously, the most straightforward way is to start at X and increment by 1 all the way to Y, and then check each number, but that is way too slow, as the boundaries for X and Y are between 100 and 10^18. I know that it is some form of dynamic programming, and that I should use strings to represent the numbers, but I can't get much further.

Any help would be accepted. Thanks!

答:
I will explain you in some steps:

First step:

For solving this kind of range problems between X and Y always make it simple by counting between 0 to X and 0 to Y-1, then subtract the result. i.e. if you have a function like f(N) that calculates the numbers that have at least half their digits the same between 0 and N, then your final result is:

```<code>f(X) - f(Y-1)
</code>```

Second step:

Next we have to compute f(N). We split this function into 2 sub functions, one for calculating the result for numbers having the same number of digits with N (lets call it f_equal), and the other for counting the qualified numbers having digits less the N (let's call it f_less). E.g. if N is 19354, we count the qualified numbers between 0 to 9999, then in another method count the favorite numbers between 10000 to 19354, after that we sum up the result. Next, I'll explain you how to implement these two methods.

Third step:

Here, we want to compute f_less method. you can do it by some math, but I always prefer to write a simple DP for solving these tasks. I will write the recursive function whether you can use memoization or you can make it bottom-up with some loops (I'll leave it as a practice for you).

```<code>long long f_less(int curDigit, int favNum, int favNumCountSoFar, int nonFavNum, int nonFavNumCountSoFar, int maxDigit){
    if(curDigit == maxDigit ){
        //for numbers with even maxDigit there may be a case when we have 2 favorite numbers
        //and we should count them only once. like 522552
        if(favNumCountSoFar*2 == maxDigit && favNumCountSoFar == nonFavNumCountSoFar) return 1;
        if(2*favNumCountSoFar >= maxDigit) return 2;
        return 0;
    }
    long long res = 0;
    for(int i=(curDigit==0?1:0);i<=9;++i) //skip the leading zero
        if(i==favNum)
            res += f_less(curDigit+1, favNum, favNumCountSoFar + 1, nonFavNum, nonFavNumCountSoFar,maxDigit);
        else
            res += f_less(curDigit+1, favNum, favNumCountSoFar, i, (i==nonFavNum?nonFavNumCountSoFar+1:1),maxDigit);
    return res;
}
</code>```

And call it for all numbers through 0 to 9:

```<code>long long res = 0;
for(int maxDigit = 1; maxDigit < NUMBER_OF_DIGITS(N); ++maxDigit)
    for(int favNumber = 0; favNumber < 10; ++favNumber)
        res += f_less(0, favNumber, 0, -1, 0, maxDigit);
</code>```

Fourth Step:

Finally we have to compute f_equal. Here we have to keep the number in a string to always check whether we are still in the range below N or not in the recursive function. Here is the implementation of f_equal (again use memoization or make it bottom-up):

```<code>string s = NUM_TO_STRING(N);
int maxDigit = s.size();
long long f_equal(int curDigit, int favNum, int favNumCountSoFar,int nonFavNum, int nonFavNumCountSoFar, bool isEqual){ //isEqual checks that whether our number is equal to N or it's lesser than it
    if(curDigit == maxDigit ){
        //for numbers with even maxDigit there may be a case when we have 2 favorite numbers
        //and we should count them only once. like 522552
        if(favNumCountSoFar*2 == maxDigit && favNumCountSoFar == nonFavNumCountSoFar) return 1;
        if(2*favNumCountSoFar >= maxDigit) return 2;
        return 0;
    }
    long long res = 0;
    for(int i=(curDigit==0?1:0);i<=9;++i){ //skip the leading zero
        if(isEqual && i>(s[curDigit]-'0')) break;
        if(i==favNum)
            res += f_equal(curDigit+1, favNum, favNumCountSoFar + 1, nonFavNum, nonFavNumCountSoFar, isEqual && (i==(s[curDigit]-'0')));
        else
            res += f_equal(curDigit+1, favNum, favNumCountSoFar, i, (i==nonFavNum?nonFavNumCountSoFar+1:1), isEqual && (i==(s[curDigit]-'0')));
    }
    return res;
}
</code>```

And call it:

```<code>long long res = 0;
for(int favNumber = 0; favNumber < 10; ++favNumber)
    res += f_equal(0, favNumber,0, -1, 0, true);
</code>```

The final result is res/2. The code is tested and works well.

Body:
I will explain you in some steps:

First step:

For solving this kind of range problems between X and Y always make it simple by counting between 0 to X and 0 to Y-1, then subtract the result. i.e. if you have a function like f(N) that calculates the numbers that have at least half their digits the same between 0 and N, then your final result is:

f(X) - f(Y-1)

Second step:

Next we have to compute f(N). We split this function into 2 sub functions, one for calculating the result for numbers having the same number of digits with N (lets call it f_equal), and the other for counting the qualified numbers having digits less the N (let's call it f_less). E.g. if N is 19354, we count the qualified numbers between 0 to 9999, then in another method count the favorite numbers between 10000 to 19354, after that we sum up the result. Next, I'll explain you how to implement these two methods.

Third step:

Here, we want to compute f_less method. you can do it by some math, but I always prefer to write a simple DP for solving these tasks. I will write the recursive function whether you can use memoization or you can make it bottom-up with some loops (I'll leave it as a practice for you).

long long f_less(int curDigit, int favNum, int favNumCountSoFar, int nonFavNum, int nonFavNumCountSoFar, int maxDigit){
    if(curDigit == maxDigit ){
        //for numbers with even maxDigit there may be a case when we have 2 favorite numbers
        //and we should count them only once. like 522552
        if(favNumCountSoFar*2 == maxDigit && favNumCountSoFar == nonFavNumCountSoFar) return 1;
        if(2*favNumCountSoFar >= maxDigit) return 2;
        return 0;
    }
    long long res = 0;
    for(int i=(curDigit==0?1:0);i<=9;++i) //skip the leading zero
        if(i==favNum)
            res += f_less(curDigit+1, favNum, favNumCountSoFar + 1, nonFavNum, nonFavNumCountSoFar,maxDigit);
        else
            res += f_less(curDigit+1, favNum, favNumCountSoFar, i, (i==nonFavNum?nonFavNumCountSoFar+1:1),maxDigit);
    return res;
}

And call it for all numbers through 0 to 9:

long long res = 0;
for(int maxDigit = 1; maxDigit < NUMBER_OF_DIGITS(N); ++maxDigit)
    for(int favNumber = 0; favNumber < 10; ++favNumber)
        res += f_less(0, favNumber, 0, -1, 0, maxDigit);

Fourth Step:

Finally we have to compute f_equal. Here we have to keep the number in a string to always check whether we are still in the range below N or not in the recursive function. Here is the implementation of f_equal (again use memoization or make it bottom-up):

string s = NUM_TO_STRING(N);
int maxDigit = s.size();
long long f_equal(int curDigit, int favNum, int favNumCountSoFar,int nonFavNum, int nonFavNumCountSoFar, bool isEqual){ //isEqual checks that whether our number is equal to N or it's lesser than it
    if(curDigit == maxDigit ){
        //for numbers with even maxDigit there may be a case when we have 2 favorite numbers
        //and we should count them only once. like 522552
        if(favNumCountSoFar*2 == maxDigit && favNumCountSoFar == nonFavNumCountSoFar) return 1;
        if(2*favNumCountSoFar >= maxDigit) return 2;
        return 0;
    }
    long long res = 0;
    for(int i=(curDigit==0?1:0);i<=9;++i){ //skip the leading zero
        if(isEqual && i>(s[curDigit]-'0')) break;
        if(i==favNum)
            res += f_equal(curDigit+1, favNum, favNumCountSoFar + 1, nonFavNum, nonFavNumCountSoFar, isEqual && (i==(s[curDigit]-'0')));
        else
            res += f_equal(curDigit+1, favNum, favNumCountSoFar, i, (i==nonFavNum?nonFavNumCountSoFar+1:1), isEqual && (i==(s[curDigit]-'0')));
    }
    return res;
}

And call it:

long long res = 0;
for(int favNumber = 0; favNumber < 10; ++favNumber)
    res += f_equal(0, favNumber,0, -1, 0, true);

The final result is res/2. The code is tested and works well.


问:
Finding the correct orientation for the normal
I am trying to implement a collision system for my three js racing game. I am following this guide to implement the system which calculates the final linear and angular velocities following a collision between two cars.

https://www.myphysicslab.com/engine2D/collision-en.html#resting_contact

However I have troubling when it comes to finding the correct direction for the normal. According to the link: Let the vector n be normal (perpendicular) to the edge of body B that is being impacted, and pointing outward from body B. I am using the following method for finding this normal.

How do I calculate the normal vector of a line segment?

Finding the numerical value of the normal is easy but I have trouble making my program use the correct direction. For instance i want the blue normal and not the red one.

Here is a picture that explains what i mean more clearly I hope:

答:
No formula can guess what side of the surface you are interested in, so it is up to you to provide this hint.

You can select the right orientation that by using one of Rap x Rbp or Rbp x Rap, but it is up to you to choose depending on the orientation conventions used in your model. (With the little information provided, I can't tell you more.)


答:
```<code>var jVar=0;
document.write(jVar+'<br>');

function setVarToOne(){
    jVar=1;
}

setVarToOne();
document.write(jVar);
</code>```

result:
1°document.write: 0
2°document.write: 1

every time you load/reload the page, the variable 'jVar' will be set to 0 then to 1

jsfiddle

Body:
var jVar=0;
document.write(jVar+'<br>');

function setVarToOne(){
    jVar=1;
}

setVarToOne();
document.write(jVar);

result:
1°document.write: 0
2°document.write: 1

every time you load/reload the page, the variable 'jVar' will be set to 0 then to 1

jsfiddle


问:
Disk space not available in RabbitMQ Management plugin
I have 2 RabbitMQ nodes in the cluster.

I decided to change Disk Space Free Limit in the configuration file to be memory relative as opposed to hard-coded value.

{disk_free_limit, {mem_relative, 2.0}}

What I understand is: set a disk free limit (before alarm and block for messages being published) should be 2*RAM memory, in my case 2GB

RabbitMQ seems to work well etc.

The only strange thing is that in the RabbitMQ Management Pluggin Disk space column is showing value (not available)

Is there a problem that I might not be aware? Or maybe it's just the behavior of RabbitMQ for that configuration?

Thank you.

Some information about version:

RabbitMQ version: 3.6.0

Erlang version: 7.2.1

Operating System and version: Windows Server 2012R2 Standard

答:
Problem solved.

Few things that happened to me.

When RabbitMQ Management Plugin disable Disk Space as (not available) it won't control the disk space at all.

I think the problem was with setting mem_relative on Windows. I changed it to a hardcoded value.

How serious lack of that setting is I found out recently.

Here is the scenario:
Something happened to our Consumers, so they stopped to accept any messages. Publishers were working normally though. As the result, RabbitMQ used all the space available on the box and then failed-over, due to lack of HDD space.

Disk space low watermark supposed to block all the publishers if space on HDD is dropping below, so technically, that prevents RabbitMQ from taking all the resources.


问:
Laravel Dompdf - Maximum execution time of 30 seconds exceeded
In My Laravel Application, I using DOMPDF to generate pdf files. When i convert Portrait Invoices its working properly. When i convert Landscape Invoices Its Display following Error Maximum execution time of 30 seconds exceeded in Frame.php (line 0)

My Controller Code is :

```<code>return \PDF::loadView('pdf/invoice', compact('salesinvoiceData','companyData','salesitemsData'))->setPaper('a4', 'landscape')->setWarnings(false)->download($salesinvoiceData->id.'.pdf');
</code>```

答:
I think includes css & js is the cause of slow load when generating pdf.

This is my code before:

```<code>@extends('layouts.master')
@section('content')
test
@endsection
</code>```

After remove @extends problem is fixed

```<code>test
</code>```

Body:
In My Laravel Application, I using DOMPDF to generate pdf files. When i convert Portrait Invoices its working properly. When i convert Landscape Invoices Its Display following Error Maximum execution time of 30 seconds exceeded in Frame.php (line 0)

My Controller Code is :

return \PDF::loadView('pdf/invoice', compact('salesinvoiceData','companyData','salesitemsData'))->setPaper('a4', 'landscape')->setWarnings(false)->download($salesinvoiceData->id.'.pdf');

Body:
I think includes css & js is the cause of slow load when generating pdf.

This is my code before:

@extends('layouts.master')
@section('content')
test
@endsection

After remove @extends problem is fixed

test


问:
PHP Security - Sanitize & Clean
I have a built a script around class.upload from http://www.verot.net/php_class_upload.htm

Basically what it is that all my images are stored on the server in a directory called /images/

The script I built basically takes some parameters from my website such as /xyzDir/tomnjerry.jpg?w=100&h=100&fill=1&color=fff

Then I have mod_rewrite which reads the file from /xyzDir/ into a php script which then translates the width and height and returns the image.

Lately I have noticed some idiots from Turkey trying to input weird characters into the parameters w= and h=

On my script I do check to make sure only integer is allowed in width and heigh and fill can be either 1 or 2 and color can only be certain values which i check via array.

I just want to see if there is anything else I should be doing in order to avoid getting hacked.

Thanks

答:
create a validation class to validate your post params like so.

```<code>class MyValidation
{
    public function is_interger($val)
    {
       return is_int($val);
    }

    public function within_range($val,$min,$max)
    {
        if($this->is_interger($val))
        {
            return ($val < $max && $val > $min);
        }
        return false;
    }

    public function is_hex($val)
    {
        return preg_match("/^([a-f0-9]{3}){1,2}$/",$val);
    }
}
</code>```

And use to validate your values.

Example:

```<code>$Validator = new MyValidation();

if($Validator->is_hex($_POST['color']))
{
    //Sweet.
}
</code>```

Title: PHP Security - Sanitize & Clean

Body:
create a validation class to validate your post params like so.

class MyValidation
{
    public function is_interger($val)
    {
       return is_int($val);
    }

    public function within_range($val,$min,$max)
    {
        if($this->is_interger($val))
        {
            return ($val < $max && $val > $min);
        }
        return false;
    }

    public function is_hex($val)
    {
        return preg_match("/^([a-f0-9]{3}){1,2}$/",$val);
    }
}

And use to validate your values.

Example:

$Validator = new MyValidation();

if($Validator->is_hex($_POST['color']))
{
    //Sweet.
}


问:
Ending Group Calls in Callkit
I am working on a VoIP app. I have integrated the callkit framework but having some trouble with Group calls.

The situation is the following:

Made a call.

Put first call on hold and made another.

Clicked Merge button to merge both calls. Called CXSetGroupCallAction to merge both calls. It is successfully done.

Now while ending the conference call, I am trying to end both the ongoing calls reported to callkit as the user pressed EndCall button.

Created separate CXEndCallAction for both calls and executed the transaction. End call transaction is successful for both but callkit keeps on showing the red banner at the top.

What may be the reason? Is there a different procedure to follow to end a CXGroupCall?

答:
Red banner means AVAudioSession is still active. Use CallKit's provider method to deactivate your audio engine</p>

```<code>func provider(_ provider: CXProvider, didDeactivate audioSession: AVAudioSession) {
</code>```

Title: Ending Group Calls in Callkit

Body:
Red banner means AVAudioSession is still active. Use CallKit's provider method to deactivate your audio engine

func provider(_ provider: CXProvider, didDeactivate audioSession: AVAudioSession) {


问:
"component is not a known element" - after moving a component to parent module
In order to re-use a component, I'm trying to move a component from a module to its parent with no success (Multiple child modules are supposed to use it).

Originally, the child module had the following code inside (I want to move MyDesiredComponent):

```<code>import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { Routes, RouterModule } from '@angular/router';
import { FormsModule } from '@angular/forms';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { ClickOutsideModule } from 'ng-click-outside';

import { NgbModule } from '@ng-bootstrap/ng-bootstrap';

import { ChildComponent } from './child.component';
import { MyDesiredComponent } from '../common/timeline/timeline.component';

export const routes: Routes = [
  { path: 'child', component: ChildComponent },
];

@NgModule({
  imports: [
    CommonModule,
    NgbModule,
    RouterModule.forChild(routes),
    FormsModule,
    BrowserAnimationsModule,
    ClickOutsideModule,
  ],
  declarations: [
    ChildComponent,
    MyDesiredComponent
  ]

})

export class ChildModule   { }
</code>```

I moved the declaration into a parent module, as follows:

```<code>import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';

import { ChildModule } from './child/child.module';
import { DesiredComponent } from './common/desired/desired.component';

@NgModule({
  imports: [
    ChildModule
  ],
  declarations: [DesiredComponent],
  exports: [DesiredComponent]
})
export class ParentModule { }
</code>```

After moving the component, the app fails to load, presenting the following error: 'desired-component' is not a known element.

What am I missing here?

答:
The best way to achieve this would be by "lazy loading" the component in a shared module, and import that inside your app.module.ts

shared.module.ts

```<code>import { NgModule, ModuleWithProviders } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { RouterModule } from '@angular/router';

import { DesiredComponent } from '';

@NgModule({
  imports: [CommonModule, RouterModule],
  declarations: [DesiredComponent, LoadingComponent],
  exports: [DesiredComponent,
    CommonModule, FormsModule, RouterModule]
})
export class SharedModule {
  static forRoot(): ModuleWithProviders {
    return {
      ngModule: SharedModule,
      providers: []
    };
  }
}
</code>```

app.module.ts

```<code>import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { SharedModule } from '';
import { AppComponent } from '';

@NgModule({
  imports: [BrowserModule, SharedModule.forRoot()],
  declarations: [AppComponent],
  providers: [],
  bootstrap: [AppComponent]

})
export class AppModule { }
</code>```

Body:
In order to re-use a component, I'm trying to move a component from a module to its parent with no success (Multiple child modules are supposed to use it).

Originally, the child module had the following code inside (I want to move MyDesiredComponent):

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { Routes, RouterModule } from '@angular/router';
import { FormsModule } from '@angular/forms';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { ClickOutsideModule } from 'ng-click-outside';

import { NgbModule } from '@ng-bootstrap/ng-bootstrap';

import { ChildComponent } from './child.component';
import { MyDesiredComponent } from '../common/timeline/timeline.component';

export const routes: Routes = [
  { path: 'child', component: ChildComponent },
];

@NgModule({
  imports: [
    CommonModule,
    NgbModule,
    RouterModule.forChild(routes),
    FormsModule,
    BrowserAnimationsModule,
    ClickOutsideModule,
  ],
  declarations: [
    ChildComponent,
    MyDesiredComponent
  ]

})

export class ChildModule   { }

I moved the declaration into a parent module, as follows:

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';

import { ChildModule } from './child/child.module';
import { DesiredComponent } from './common/desired/desired.component';

@NgModule({
  imports: [
    ChildModule
  ],
  declarations: [DesiredComponent],
  exports: [DesiredComponent]
})
export class ParentModule { }

After moving the component, the app fails to load, presenting the following error: 'desired-component' is not a known element.

What am I missing here?

Body:
The best way to achieve this would be by "lazy loading" the component in a shared module, and import that inside your app.module.ts

shared.module.ts

import { NgModule, ModuleWithProviders } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { RouterModule } from '@angular/router';

import { DesiredComponent } from '';

@NgModule({
  imports: [CommonModule, RouterModule],
  declarations: [DesiredComponent, LoadingComponent],
  exports: [DesiredComponent,
    CommonModule, FormsModule, RouterModule]
})
export class SharedModule {
  static forRoot(): ModuleWithProviders {
    return {
      ngModule: SharedModule,
      providers: []
    };
  }
}

app.module.ts

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { SharedModule } from '';
import { AppComponent } from '';

@NgModule({
  imports: [BrowserModule, SharedModule.forRoot()],
  declarations: [AppComponent],
  providers: [],
  bootstrap: [AppComponent]

})
export class AppModule { }