问:
How to use motion layout with recyclerview
trying to use MotionLayout with RecyclerView,

when scrolling up, app is crashing with error:

android.content.res.Resources$NotFoundException: Unable to find
  resource ID #0xffffffff

fragment layout code is

```<code><android.support.constraint.motion.MotionLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    app:layoutDescription="@xml/collapsing_config_order_details"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    ...

<android.support.v7.widget.CardView
        android:id="@+id/cardView"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        app:layout_constraintEnd_toEndOf="@+id/tv_delivery_type"
        app:layout_constraintStart_toStartOf="@+id/imageView15"
        app:layout_constraintTop_toBottomOf="@+id/view4">

     ...

</android.support.v7.widget.CardView>

<android.support.v7.widget.RecyclerView
        android:id="@+id/rv_list"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginBottom="8dp"
        android:layout_marginTop="8dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="@+id/cardView"
        app:layout_constraintStart_toStartOf="@+id/cardView"
        app:layout_constraintTop_toBottomOf="@+id/cardView" />

</android.support.constraint.motion.MotionLayout>
</code>```

and layoutDescription code is:

```<code><MotionScene xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <Transition
        app:constraintSetEnd="@id/collapsed"
        app:constraintSetStart="@id/expanded">

        <OnSwipe
            app:dragDirection="dragUp"
            app:touchAnchorSide="top"
            app:moveWhenScrollAtTop="@+id/rv_list" />

    </Transition>

    <ConstraintSet android:id="@+id/expanded"
            android:id="@+id/cardView"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginTop="8dp"
            app:layout_constraintEnd_toEndOf="@+id/tv_delivery_type"
            app:layout_constraintStart_toStartOf="@+id/imageView15"
            app:layout_constraintTop_toBottomOf="@+id/view4" />
    </ConstraintSet>

    <ConstraintSet android:id="@+id/collapsed">
    <Constraint
            android:id="@+id/cardView"
            android:layout_width="0dp"
            android:layout_height="1dp"
            android:layout_marginTop="8dp"
            app:layout_constraintEnd_toEndOf="@+id/tv_delivery_type"
            app:layout_constraintStart_toStartOf="@+id/imageView15"
            app:layout_constraintTop_toBottomOf="@+id/view4" />
    </ConstraintSet>

</MotionScene>
</code>```

答:
```<code>app:moveWhenScrollAtTop="@+id/rv_list"
</code>```

Vale of app:moveWhenScrollAtTop should be boolean.

Body:
trying to use MotionLayout with RecyclerView,

when scrolling up, app is crashing with error:

android.content.res.Resources$NotFoundException: Unable to find
  resource ID #0xffffffff

fragment layout code is

<android.support.constraint.motion.MotionLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    app:layoutDescription="@xml/collapsing_config_order_details"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    ...

<android.support.v7.widget.CardView
        android:id="@+id/cardView"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        app:layout_constraintEnd_toEndOf="@+id/tv_delivery_type"
        app:layout_constraintStart_toStartOf="@+id/imageView15"
        app:layout_constraintTop_toBottomOf="@+id/view4">

     ...

</android.support.v7.widget.CardView>

<android.support.v7.widget.RecyclerView
        android:id="@+id/rv_list"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginBottom="8dp"
        android:layout_marginTop="8dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="@+id/cardView"
        app:layout_constraintStart_toStartOf="@+id/cardView"
        app:layout_constraintTop_toBottomOf="@+id/cardView" />

</android.support.constraint.motion.MotionLayout>

and layoutDescription code is:

<MotionScene xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <Transition
        app:constraintSetEnd="@id/collapsed"
        app:constraintSetStart="@id/expanded">

        <OnSwipe
            app:dragDirection="dragUp"
            app:touchAnchorSide="top"
            app:moveWhenScrollAtTop="@+id/rv_list" />

    </Transition>

    <ConstraintSet android:id="@+id/expanded"
            android:id="@+id/cardView"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginTop="8dp"
            app:layout_constraintEnd_toEndOf="@+id/tv_delivery_type"
            app:layout_constraintStart_toStartOf="@+id/imageView15"
            app:layout_constraintTop_toBottomOf="@+id/view4" />
    </ConstraintSet>

    <ConstraintSet android:id="@+id/collapsed">
    <Constraint
            android:id="@+id/cardView"
            android:layout_width="0dp"
            android:layout_height="1dp"
            android:layout_marginTop="8dp"
            app:layout_constraintEnd_toEndOf="@+id/tv_delivery_type"
            app:layout_constraintStart_toStartOf="@+id/imageView15"
            app:layout_constraintTop_toBottomOf="@+id/view4" />
    </ConstraintSet>

</MotionScene>

Body:
app:moveWhenScrollAtTop="@+id/rv_list"

Vale of app:moveWhenScrollAtTop should be boolean.


来源: stackexchange

问:
Model association using includes method to associate 3 tables
I have 3 main tables linked together via has_many through: association.

The main tables are recipes, ingredients, and allergens.
recipes is also linked to ingredients through recipe_ingredients, and ingredients is linked to allergens through ingredient_allergens.

So in total, there are 5 tables.

What I'd like to be able to do is to see what allergens a recipe has.

I read the rails documentation and found that I can use the includes option to do something similar but in the example the tables are directly associated. see below.

```<code>class LineItem < ApplicationRecord
 belongs_to :book, -> { includes :author }
end

class Book < ApplicationRecord
 belongs_to :author
 has_many :line_items
end

class Author < ApplicationRecord
 has_many :books
end
</code>```

At the moment my models look like this:

```<code># recipes:
  has_many :recipe_ingredients
  has_many :ingredients, through: :recipe_ingredients

# recipe_ingredients:
  belongs_to :recipe
  belongs_to :ingredient

# ingredients:
  has_many :recipe_ingredients
  has_many :recipes, through: :recipe_ingredients

# ingredient_allergens:
  belongs_to :ingredient
  belongs_to :allergen

# allergens:
  has_many :ingredient_allergens
  has_many :allergens, through: :ingredient_allergens
</code>```

I've been trying to use includes in a number of ways now but none of them work. Does anyone know if includes can even be used in this case? Ideally I'd like to be able to call recipe.allergens to see all allergens associated with that recipe.

Thanks guys!

答:
includes is for eager-loading

Try:

recipe.ingredients.preload(:allergens).map{|ing| ing.allergens.to_a }.flatten.uniq
```

This is straightforward "take all the allergens from all ingredients, put into one array and remove duplicates" and preload is to avoid N+1 problem

ContentLicense: CC BY-SA 4.0

Body:
I have 3 main tables linked together via has_many through: association.

The main tables are recipes, ingredients, and allergens.
recipes is also linked to ingredients through recipe_ingredients, and ingredients is linked to allergens through ingredient_allergens.

So in total, there are 5 tables.

What I'd like to be able to do is to see what allergens a recipe has.

I read the rails documentation and found that I can use the includes option to do something similar but in the example the tables are directly associated. see below.

class LineItem < ApplicationRecord
 belongs_to :book, -> { includes :author }
end

class Book < ApplicationRecord
 belongs_to :author
 has_many :line_items
end

class Author < ApplicationRecord
 has_many :books
end

At the moment my models look like this:

# recipes:
  has_many :recipe_ingredients
  has_many :ingredients, through: :recipe_ingredients

# recipe_ingredients:
  belongs_to :recipe
  belongs_to :ingredient

# ingredients:
  has_many :recipe_ingredients
  has_many :recipes, through: :recipe_ingredients

# ingredient_allergens:
  belongs_to :ingredient
  belongs_to :allergen

# allergens:
  has_many :ingredient_allergens
  has_many :allergens, through: :ingredient_allergens

I've been trying to use includes in a number of ways now but none of them work. Does anyone know if includes can even be used in this case? Ideally I'd like to be able to call recipe.allergens to see all allergens associated with that recipe.

Thanks guys!

Body:
includes is for eager-loading

Try:

recipe.ingredients.preload(:allergens).map{|ing| ing.allergens.to_a }.flatten.uniq

This is straightforward "take all the allergens from all ingredients, put into one array and remove duplicates" and preload is to avoid N+1 problem


问:
Question about DateAdd function and information
I'm currently writing some SQL and have come upon an odd issue.

The code i'm using is:

```<code>select * from #table1
where datefield = DATEADD(day, -2, getdate())
</code>```

The issue i'm running into is it won't pull any information like this. If I add a '>' to the '=' it pulls information. If I put an exact date into teh query instead of the 'dateadd' piece it pulls the correct records.

I've tested the date parameters and there are matching records for 4/10/2011. But for some reason it just does not like the '= dateadd' in this instance.

I have also attempted to use the 'current_timestamp' string instead of 'getdate' as well with the same results.

Any suggestions?

答:
DATEADD(day, -2, getdate()) returns the time component as well, something like 2011-04-10 16:35:23.437

You could use DATEADD(dd, 0, DATEDIFF(dd, 0, DATEADD(day, -2, getdate()))) to get just the date part if your Sql Server version is less than 2008 (when the DATE type was added)

ContentLicense: CC BY-SA 3.0

Body:
I'm currently writing some SQL and have come upon an odd issue.

The code i'm using is:

select * from #table1
where datefield = DATEADD(day, -2, getdate())

The issue i'm running into is it won't pull any information like this. If I add a '>' to the '=' it pulls information. If I put an exact date into teh query instead of the 'dateadd' piece it pulls the correct records.

I've tested the date parameters and there are matching records for 4/10/2011. But for some reason it just does not like the '= dateadd' in this instance.

I have also attempted to use the 'current_timestamp' string instead of 'getdate' as well with the same results.

Any suggestions?


问:
How do I get the average of each similar column value?
Say I have this:

```<code>     tag     value

1    apple    3

2    banana   5

3    apple    4

4    banana   2
</code>```

How can I have a query get the average of each value with respect to the tags?

So like:

```<code>    tag      value

1   apple    3.5

2   banana   3.5
</code>```

I can get the average of the whole column easily with an inner select, but have no idea how to do so with respect to the tag.

答:
A simple approach is to group by the tag and use the avg() function:

```<code>SELECT AVG(value) FROM table
GROUP BY tag
</code>```

Body:
Say I have this:

     tag     value

1    apple    3

2    banana   5

3    apple    4

4    banana   2

How can I have a query get the average of each value with respect to the tags?

So like:

    tag      value

1   apple    3.5

2   banana   3.5

I can get the average of the whole column easily with an inner select, but have no idea how to do so with respect to the tag.

Body:
A simple approach is to group by the tag and use the avg() function:

SELECT AVG(value) FROM table
GROUP BY tag


问:
pkcs11 exception parsing configuration: Unexpected value Token['(']
I know this is not a new problem (see https://bugs.openjdk.java.net/browse/JDK-8023745 ), but I was hoping someone would have a good workaround we could roll out.

We are deploying an application, which is using pkcs11 and have encountered a problem with parsing config, which is located in "Program Files (x86)". What we're getting is:

sun.security.pkcs11.ConfigurationException: Unexpected value Token['('], line 2

In the dev environment, moving the location to a "clean" path solves the problem, so the issue is definitely the (x86).

What would be a good workaround, with, hopefully, minimum trouble to the end user?

答:
I found a simple workaround for this problem in Windows. In my case I'm trying to load the nss native libraries from Mozilla 32 bits installation directory. If I configure the path this way:

```<code>name = NSS
library = C:\Program Files (x86)\Mozilla Firefox\softokn3.dll
</code>```

I get the Unexpected value Token['('] exception. If instead I trying to add " to enclose the library path:

```<code>name = NSS
library = "C:\Program Files (x86)\Mozilla Firefox\softokn3.dll"
</code>```

Then the error change and I get:

```<code>Caused by: sun.security.pkcs11.ConfigurationException: Absolute path required for library value: C:Program Files (x86)Mozilla Firefoxsoftokn3.dll
</code>```

So seems that " bypass the parenthesis problem however seems that produce that file.separator is lost, so my last attempt was using " and "escaping" file.separator (simply applying replace("\\","\\\\") to the path before putting in the config):

```<code>name = NSS
library = "C:\\Program Files (x86)\\Mozilla Firefox\\softokn3.dll"
</code>```

This way the library is correctly loaded. I test it for java 8 update 141.

Body:
I found a simple workaround for this problem in Windows. In my case I'm trying to load the nss native libraries from Mozilla 32 bits installation directory. If I configure the path this way:

name = NSS
library = C:\Program Files (x86)\Mozilla Firefox\softokn3.dll

I get the Unexpected value Token['('] exception. If instead I trying to add " to enclose the library path:

name = NSS
library = "C:\Program Files (x86)\Mozilla Firefox\softokn3.dll"

Then the error change and I get:

Caused by: sun.security.pkcs11.ConfigurationException: Absolute path required for library value: C:Program Files (x86)Mozilla Firefoxsoftokn3.dll

So seems that " bypass the parenthesis problem however seems that produce that file.separator is lost, so my last attempt was using " and "escaping" file.separator (simply applying replace("\\","\\\\") to the path before putting in the config):

name = NSS
library = "C:\\Program Files (x86)\\Mozilla Firefox\\softokn3.dll"

This way the library is correctly loaded. I test it for java 8 update 141.


问:
I keep getting the "No value associated with key" error when using the JSONDecoder in Swift. Can someone please explain what is going wrong here?
I am trying to read from a local JSON file and populate my tableView with cells to be retrieved from the Decoder. Since my table view was still empty, I added a breakpoint on the JSONDecoder.decode line to see what is going on. I get this error, even though I made sure that my naming convention is the same in both my structs and JSON file. Is there something I am missing here.

Since my naming convention was consistent across the files, at first I did not try add CodingKeys enum inside my structs. After a few failed runs I added that in but it feels kind of obsolete.

Where I run the decoder:

```<code>let fileName = "settings"

...

   if let url = Bundle.main.url(forResource: fileName, withExtension: "json") {
       do {
            let data = try Data(contentsOf: url)
            let list = try JSONDecoder().decode(SettingsPayload.self, from: data)
            completion(list.sections)
       } catch {
            completion(nil)
       }
   }

fileprivate struct SettingsPayload: Decodable {
    let sections: [Section]
}
</code>```

My structs that will be used to store the data when retrieved:

```<code>struct Item: Decodable {
    let title: String
    let type: String
    let url: String

    private enum CodingKeys: String, CodingKey {
        case title = "title"
        case type = "type"
        case url = "url"
    }
}

struct Section: Decodable {
    let title: String
    let items: [Item]

    private enum CodingKeys: String, CodingKey {
        case title = "title"
        case items = "items"
    }
}
</code>```

and my .json file:

```<code>{
    "sections": [{
        "section": {
            "title": "Main Settings",
            "items": [{
                "item": {
                    "title": "Notifications",
                    "type": "notification",
                    "url": ""
                },
                "item": {
                    "title": "Log Out",
                    "type": "",
                    "url": ""
                }
            }]
        },
        "section": {
            "title": "Feedback",
            "items": [{
                "item": {
                    "title": "Contact Us",
                    "type": "email",
                    "url": ""
                },
                "item": {
                    "title": "Rate on App Store",
                    "type": "webView",
                    "url": "https://www.apple.com/uk/ios/app-store/"
                }
            }]
        },
        "section": {
            "title": "About",
            "items": [{
                "item": {
                    "title": "Terms of Service",
                    "type": "webView",
                    "url": ""
                },
                "item": {
                    "title": "Privacy Policy",
                    "type": "webView",
                    "url": "https://www.apple.com/uk/ios/app-store/"
                },
                "item": {
                    "title": "Version Info",
                    "type": "webView",
                    "url": ""
                }
            }]
        }
    }]
}
</code>```

This is the error message I get:

```<code>     - debugDescription : "No value associated with key CodingKeys(stringValue: \"title\", intValue: nil) (\"title\")."
</code>```

答:
I think the problem is that the decoder expects an Array of the item Section, but your json has an Array of dictionaries with a key "section" and an item Section in there.

Maybe try to modify your json like this:

```<code>{
    "sections": [{
            "title": "Main Settings",
            "items": [ {
                    "title": "Notifications",
                    "type": "notification",
                    "url": ""
                }, {
                    "title": "Log Out",
                    "type": "",
                    "url": ""
                }]}, {
            "title": "Feedback",
            "items": [{
                    "title": "Contact Us",
                    "type": "email",
                    "url": ""
                },{
                    "title": "Rate on App Store",
                    "type": "webView",
                    "url": "https://www.apple.com/uk/ios/app-store/"
                }]}, {
            "title": "About",
            "items": [{
                    "title": "Terms of Service",
                    "type": "webView",
                    "url": ""
                }, {
                    "title": "Privacy Policy",
                    "type": "webView",
                    "url": "https://www.apple.com/uk/ios/app-store/"
                }, {
                    "title": "Version Info",
                    "type": "webView",
                    "url": ""
                }
  ]}]
}
</code>```

Update

JSONDecoder doesn't look for the name of your decodable struct in the JSON, it only looks for the name of the properties.

Body:
I am trying to read from a local JSON file and populate my tableView with cells to be retrieved from the Decoder. Since my table view was still empty, I added a breakpoint on the JSONDecoder.decode line to see what is going on. I get this error, even though I made sure that my naming convention is the same in both my structs and JSON file. Is there something I am missing here.

Since my naming convention was consistent across the files, at first I did not try add CodingKeys enum inside my structs. After a few failed runs I added that in but it feels kind of obsolete.

Where I run the decoder:

let fileName = "settings"

...

   if let url = Bundle.main.url(forResource: fileName, withExtension: "json") {
       do {
            let data = try Data(contentsOf: url)
            let list = try JSONDecoder().decode(SettingsPayload.self, from: data)
            completion(list.sections)
       } catch {
            completion(nil)
       }
   }

fileprivate struct SettingsPayload: Decodable {
    let sections: [Section]
}

My structs that will be used to store the data when retrieved:

struct Item: Decodable {
    let title: String
    let type: String
    let url: String

    private enum CodingKeys: String, CodingKey {
        case title = "title"
        case type = "type"
        case url = "url"
    }
}

struct Section: Decodable {
    let title: String
    let items: [Item]

    private enum CodingKeys: String, CodingKey {
        case title = "title"
        case items = "items"
    }
}

and my .json file:

{
    "sections": [{
        "section": {
            "title": "Main Settings",
            "items": [{
                "item": {
                    "title": "Notifications",
                    "type": "notification",
                    "url": ""
                },
                "item": {
                    "title": "Log Out",
                    "type": "",
                    "url": ""
                }
            }]
        },
        "section": {
            "title": "Feedback",
            "items": [{
                "item": {
                    "title": "Contact Us",
                    "type": "email",
                    "url": ""
                },
                "item": {
                    "title": "Rate on App Store",
                    "type": "webView",
                    "url": "https://www.apple.com/uk/ios/app-store/"
                }
            }]
        },
        "section": {
            "title": "About",
            "items": [{
                "item": {
                    "title": "Terms of Service",
                    "type": "webView",
                    "url": ""
                },
                "item": {
                    "title": "Privacy Policy",
                    "type": "webView",
                    "url": "https://www.apple.com/uk/ios/app-store/"
                },
                "item": {
                    "title": "Version Info",
                    "type": "webView",
                    "url": ""
                }
            }]
        }
    }]
}

This is the error message I get:

     - debugDescription : "No value associated with key CodingKeys(stringValue: \"title\", intValue: nil) (\"title\")."

Body:
I think the problem is that the decoder expects an Array of the item Section, but your json has an Array of dictionaries with a key "section" and an item Section in there.

Maybe try to modify your json like this:

{
    "sections": [{
            "title": "Main Settings",
            "items": [ {
                    "title": "Notifications",
                    "type": "notification",
                    "url": ""
                }, {
                    "title": "Log Out",
                    "type": "",
                    "url": ""
                }]}, {
            "title": "Feedback",
            "items": [{
                    "title": "Contact Us",
                    "type": "email",
                    "url": ""
                },{
                    "title": "Rate on App Store",
                    "type": "webView",
                    "url": "https://www.apple.com/uk/ios/app-store/"
                }]}, {
            "title": "About",
            "items": [{
                    "title": "Terms of Service",
                    "type": "webView",
                    "url": ""
                }, {
                    "title": "Privacy Policy",
                    "type": "webView",
                    "url": "https://www.apple.com/uk/ios/app-store/"
                }, {
                    "title": "Version Info",
                    "type": "webView",
                    "url": ""
                }
  ]}]
}

Update

JSONDecoder doesn't look for the name of your decodable struct in the JSON, it only looks for the name of the properties.


问:
How to create a conditional string that's based on two variables without a bunch of if elses (JavaScript)
I am trying to create a custom string to be shown to the user, which is based on two variables.

Here is the example that I am trying to build:

let url1;
let url2;
if (containsData1) {
  url1 = "http://test";
}

if (containsData2) {
  url2 = "http://test2";
}

let finalString = '';
if (url1 && url2) {
  finalString = 'The url 1 is ' + url1 + ' and url 2 is ' + url2;
} else if (!url1 && url2) {
  finalString = 'There isnt data for url1. Url2 is ' + url2;
} else if (url1 && !url2) {
  finalString = 'The url 1 is ' + url1 + '. There isnt data for url2';
} else if (!url1 && !url2) {
  finalString = 'There isnt data for url1. There isnt data for url2';
}
```

However I would like to this in a proper way, without using this bunch of if elses, any suggestions on how to accomplish this?

Thanks.

答:
It's better to treat that as two different conditional strings and then join them together:

let string1;
if (url1) {
  string1 = 'The url 1 is ' + url1 + '.';
} else {
  string1 = 'There isnt data for url1.';
}

let string2;
if (url2) {
   string2 = 'Url2 is ' + url2;
} else {
  string2 = 'There isnt data for url2';
}

let finalString = string1 + string2;
```

<p>This allows you to reason about the resulting string in a more straight forward way than considering each possible case at once. With only two variables, you have 4 possible outcomes, with 4 you'd have <em>16</em>. </p>

<p>Separating each variable means that you don't need to care what the other possibilities are when you generate each substring.</p>

<p>You can further make that simpler to think about by using templates. In that case you can separate the string generation logic elsewhere so you focus on different things in different areas </p>

<ul>
<li>figuring out what each individual message should be</li>
<li>figuring out how to display them</li>
</ul>

<p>For example you might want to standardise the messages and have something like:</p>

<pre class="lang-js prettyprint-override"><code>function makeSubMessage(url, name) {
  if (url) {
    return `The $[name} is ${url}`;
  } else {
    return `No data for ${name}`;
  }
}
/* ... */
let string1 = makeSubMessage(url1, "Url1");
</code>```

Which will allow you to more easily swap what the format of the messages is without having to touch how they are then presented.

When you're presenting them, you might want to have each message on a separate line, than simply one string, so the result need not rely on what the submessages are:

```<code>function(urls) {
  let finalString = "";
  for (let i = 0; i < urls.length; i++) {
    let subMessage = makeSubMessage(urls[i], "Url" + (i + 1));
    finalString += subMessage;
    finalString += "\n"
  }

  return finalString;
}
</code>```

Or you can change this implementation entirely:

function(urls) {
  let finalString = urls
    .map((url, i) => makeSubMessage(url, "Url" + (i + 1)))
    .join("\n")

  return finalString;
}
```

<p>or change to display them as HTML bulletpoints, perhaps:</p>

<pre class="lang-js prettyprint-override"><code>function(urls) {
  let finalString = urls
    .map((url, i) => makeSubMessage(url, "Url" + (i + 1)))
    .map(subMessage => `<li>${subMessage}</li>`)
    .join("<br/>")

  return `<ul>${finalString}</ul>`;
}
</code>```

Or anything else. Point being that the concerns are now separated.

Body:
I am trying to create a custom string to be shown to the user, which is based on two variables.

Here is the example that I am trying to build:

let url1;
let url2;
if (containsData1) {
  url1 = "http://test";
}

if (containsData2) {
  url2 = "http://test2";
}

let finalString = '';
if (url1 && url2) {
  finalString = 'The url 1 is ' + url1 + ' and url 2 is ' + url2;
} else if (!url1 && url2) {
  finalString = 'There isnt data for url1. Url2 is ' + url2;
} else if (url1 && !url2) {
  finalString = 'The url 1 is ' + url1 + '. There isnt data for url2';
} else if (!url1 && !url2) {
  finalString = 'There isnt data for url1. There isnt data for url2';
}

However I would like to this in a proper way, without using this bunch of if elses, any suggestions on how to accomplish this?

Thanks.

Body:
It's better to treat that as two different conditional strings and then join them together:

let string1;
if (url1) {
  string1 = 'The url 1 is ' + url1 + '.';
} else {
  string1 = 'There isnt data for url1.';
}

let string2;
if (url2) {
   string2 = 'Url2 is ' + url2;
} else {
  string2 = 'There isnt data for url2';
}

let finalString = string1 + string2;

This allows you to reason about the resulting string in a more straight forward way than considering each possible case at once. With only two variables, you have 4 possible outcomes, with 4 you'd have 16.

Separating each variable means that you don't need to care what the other possibilities are when you generate each substring.

You can further make that simpler to think about by using templates. In that case you can separate the string generation logic elsewhere so you focus on different things in different areas

figuring out what each individual message should be

figuring out how to display them

For example you might want to standardise the messages and have something like:

function makeSubMessage(url, name) {
  if (url) {
    return `The $[name} is ${url}`;
  } else {
    return `No data for ${name}`;
  }
}
/* ... */
let string1 = makeSubMessage(url1, "Url1");

Which will allow you to more easily swap what the format of the messages is without having to touch how they are then presented.

When you're presenting them, you might want to have each message on a separate line, than simply one string, so the result need not rely on what the submessages are:

function(urls) {
  let finalString = "";
  for (let i = 0; i < urls.length; i++) {
    let subMessage = makeSubMessage(urls[i], "Url" + (i + 1));
    finalString += subMessage;
    finalString += "\n"
  }

  return finalString;
}

Or you can change this implementation entirely:

function(urls) {
  let finalString = urls
    .map((url, i) => makeSubMessage(url, "Url" + (i + 1)))
    .join("\n")

  return finalString;
}

or change to display them as HTML bulletpoints, perhaps:

function(urls) {
  let finalString = urls
    .map((url, i) => makeSubMessage(url, "Url" + (i + 1)))
    .map(subMessage => `<li>${subMessage}</li>`)
    .join("<br/>")

  return `<ul>${finalString}</ul>`;
}

Or anything else. Point being that the concerns are now separated.


问:
dialogflow hangouts chat integration no response using actions-sdk
When connecting dialogflow with hangouts chat I am getting normal responses set in dialogflow. But messages from the webhook running on google actions sdk is not  returning messages.

```<code>const functions = require('firebase-functions');
const app = dialogflow({debug: true});
const {dialogflow, BasicCard, Permission, Suggestions,} = require('actions-on-google');
app.intent('id', (conv, {name}) =>
 {
  conv.close(`People here are always available.So,you can call ${name} anytime`)
});
</code>```

This works with google assistant and webchat. Only with Google chat the response is empty.

答:
The actions-on-google library only works with the Google Assistant.

For other integrations, including Facebook, Slack, and Hangouts Chat, you need to either use the dialogflow-fulfillment library, or respond with JSON directly.

Body:
When connecting dialogflow with hangouts chat I am getting normal responses set in dialogflow. But messages from the webhook running on google actions sdk is not  returning messages.

const functions = require('firebase-functions');
const app = dialogflow({debug: true});
const {dialogflow, BasicCard, Permission, Suggestions,} = require('actions-on-google');
app.intent('id', (conv, {name}) =>
 {
  conv.close(`People here are always available.So,you can call ${name} anytime`)
});

This works with google assistant and webchat. Only with Google chat the response is empty.


问:
Drawing functions starting from a specific point
I have a problem drawing different functions with PHP (GD, of course).
I managed to draw different functions but whenever the parameters of the function change - the function floats wherever it wants.
Let us say that I have a first function y=x^2 and I have to draw it from -5 to 5. This means that the first point would be at (-5;25). And I can move that to whatever point I want if I know that. But if I choose y=2x^2 with an interval x=(-5;5). The first point is at (-5;50). So I need help in calculating how to move any function to, let's say, (0;0).
The functions are parabola/catenary alike.</p>

答: You first need to determine the bounding box of your function. Then, you calculate the width and the height, and you normalize so it fits into a rectangle whose top left coordinate is (0,0). Maybe you will also need to scale the figure to get it at a specific size.</p>


问:
org.hibernate.lazyinitializationexception after calling getter to a lazy initialised field
I have a class post with a lazy init field comments:

```<code>@Entity
@Table(name = "POSTS")
public class Post {

    @Id
    @GeneratedValue(strategy = IDENTITY)
    @Column(name = "post_id",
            unique = true, nullable = false)
    @JsonView(Views.Public.class)
    private Integer postId;

    @Column(name = "POST_BODY", columnDefinition = "text")
    @JsonView(Views.Public.class)
    private String postBody;

    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "USERNAME")
    private User user;

    @OneToMany(cascade = CascadeType.ALL, mappedBy = "post", fetch = FetchType.LAZY)
    private Set<PostComment> comments = new HashSet<>();
}
</code>```

As I learned from hibernate docs if something is not initialised due to lazy initialisation if you then call its getter method it should be initialised, but when I get my post and try to call getter method for comments, I get an exception.

```<code>@GetMapping(path = {"/post/{id}"})
    public ModelAndView showSpecificPost(@PathVariable(value = "id") Integer id) {
        User currentUser = userService.findByUserName(auth.getName());
        Post post = postService.getPostById(id);
        logger.info(post.getComments().size());
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("postTemplates/specificPost");

        return modelAndView;
    }
</code>```

答:
Most likely the transactional is on this method:

```<code>Post post = postService.getPostById(id);
</code>```

Then you try:

```<code>logger.info(post.getComments().size());
</code>```

which is outside of the transaction which is closed at this point and Post is a detached entity at this point.

One of the options for you would be to annotate the controller request-mapping method with @Transactional(readOnly = true).

Body:
I have a class post with a lazy init field comments:

@Entity
@Table(name = "POSTS")
public class Post {

    @Id
    @GeneratedValue(strategy = IDENTITY)
    @Column(name = "post_id",
            unique = true, nullable = false)
    @JsonView(Views.Public.class)
    private Integer postId;

    @Column(name = "POST_BODY", columnDefinition = "text")
    @JsonView(Views.Public.class)
    private String postBody;

    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "USERNAME")
    private User user;

    @OneToMany(cascade = CascadeType.ALL, mappedBy = "post", fetch = FetchType.LAZY)
    private Set<PostComment> comments = new HashSet<>();
}

As I learned from hibernate docs if something is not initialised due to lazy initialisation if you then call its getter method it should be initialised, but when I get my post and try to call getter method for comments, I get an exception.

@GetMapping(path = {"/post/{id}"})
    public ModelAndView showSpecificPost(@PathVariable(value = "id") Integer id) {
        User currentUser = userService.findByUserName(auth.getName());
        Post post = postService.getPostById(id);
        logger.info(post.getComments().size());
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("postTemplates/specificPost");

        return modelAndView;
    }

Body:
Most likely the transactional is on this method:

Post post = postService.getPostById(id);

Then you try:

logger.info(post.getComments().size());

which is outside of the transaction which is closed at this point and Post is a detached entity at this point.

One of the options for you would be to annotate the controller request-mapping method with @Transactional(readOnly = true).


问:
@Injectable({providedIn: Module}) => Circular dependency (ROUTES)

The VendasModule imports the router

that imports the father component

that imports the child component

That imports the SERVICE (That I want to be @injectable providedIn: VendasModule)

That imports the VendasModule (to be used in the @injectable decorator)

Circular dependency detected !

Any Ideas on how to go around this? I need all this imports, don't I?

```<code>VendasModule:
@NgModule({
  imports: [
    CommonModule,
    RouterModule.forChild(VendasRoutes),
    FlexLayoutModule,
    ReactiveFormsModule,
    MatCardModule,
    MatInputModule,
    MatButtonModule,
    MatProgressBarModule,
    MatRadioModule,
    MatSelectModule,
    MatTabsModule,
    MatDatepickerModule,
    MatTableModule,
    MatCheckboxModule,
    MatDialogModule,
    MatIconModule,
    MatStepperModule,
    MatListModule,
    MatAutocompleteModule,
    SharedModule,
    FormsModule,
    NgxCurrencyModule.forRoot(customCurrencyMaskConfig),
    CustomFormsModule,
    MatExpansionModule,
    MatChipsModule,
    MatTooltipModule,
    MatProgressSpinnerModule,
      ], (...)
</code>```

```<code>VendasRouting:
export const VendasRoutes: Routes = [
    {
        path: '',
        canActivateChild: [Menu],
        children: [
            {
                path: 'cadastro-contrato',
                component: CadastroContratoComponent
            },
            {
                path: 'plano-comercial',
                component: PlanoComercialComponent
            },
            {
                path: 'check-list',
                component: CheckListComponent
            },
            {
                path: 'plano-emissoras',
                component: PlanoEmissorasComponent((FATHER COMPONENT))
            }

        ]
    }
]
</code>```

```<code>Father Component:
export class PlanoEmissorasComponent implements OnInit, OnDestroy {
  @ViewChild(ProspectEmissorasComponent) prospectEmissoras: ProspectEmissorasComponent; ((Child Component))
  @ViewChild(NegociacaoEmissorasComponent) negociacaoEmissoras: NegociacaoEmissorasComponent;
  @ViewChild(FinancEmissorasComponent) financEmissoras: FinancEmissorasComponent;
  @ViewChild(ContratoEmissorasComponent) contratoEmissoras: ContratoEmissorasComponent;
</code>```

```<code>Service:
import { VendasModule } from "../../../vendas.module";

@Injectable({
    providedIn: VendasModule
})
export class PlanoEmissorasService { ... }
</code>```

I am getting this error:

```<code>WARNING in Circular dependency detected:
src/app/vendas/vendas.routing.ts -> src/app/vendas/cadastro-contrato/plano-emissoras/plano-emissoras.component.ts -> src/app/vendas/cadastro-contrato/plano-emissoras/prospect-emissoras/prospect-emissoras.component.ts -> src/app/vendas/cadastro-contrato/plano-emissoras/services/plano-emissoras.service.ts -> src/app/vendas/vendas.module.ts -> src/app/vendas/vendas.routing.ts
</code>```

答:
The circular reference is in your code generated by the TypeScript compiler when it tries to resolve the circular imports. You can follow any of the below solutions:

Using the providers array of VendasModule for
providing your service.

make the service injectable at root level: @Injectable({
providedIn: 'root' }) which will help with tree-shaking.

Use providedIn in another module and import it in VendasModule

```<code> @Injectable({ providedIn: SomeModule})
 export class PlanoEmissorasService {}
</code>```

Use this module in your VendasModule

```<code> @NgModule({ imports: [SomeModule]})
 export class VendasModule
</code>```

Check this comment out on angular repo.

Body:
The VendasModule imports the router

that imports the father component

that imports the child component

That imports the SERVICE (That I want to be @injectable providedIn: VendasModule)

That imports the VendasModule (to be used in the @injectable decorator)

Circular dependency detected !

Any Ideas on how to go around this? I need all this imports, don't I?

VendasModule:
@NgModule({
  imports: [
    CommonModule,
    RouterModule.forChild(VendasRoutes),
    FlexLayoutModule,
    ReactiveFormsModule,
    MatCardModule,
    MatInputModule,
    MatButtonModule,
    MatProgressBarModule,
    MatRadioModule,
    MatSelectModule,
    MatTabsModule,
    MatDatepickerModule,
    MatTableModule,
    MatCheckboxModule,
    MatDialogModule,
    MatIconModule,
    MatStepperModule,
    MatListModule,
    MatAutocompleteModule,
    SharedModule,
    FormsModule,
    NgxCurrencyModule.forRoot(customCurrencyMaskConfig),
    CustomFormsModule,
    MatExpansionModule,
    MatChipsModule,
    MatTooltipModule,
    MatProgressSpinnerModule,
      ], (...)

VendasRouting:
export const VendasRoutes: Routes = [
    {
        path: '',
        canActivateChild: [Menu],
        children: [
            {
                path: 'cadastro-contrato',
                component: CadastroContratoComponent
            },
            {
                path: 'plano-comercial',
                component: PlanoComercialComponent
            },
            {
                path: 'check-list',
                component: CheckListComponent
            },
            {
                path: 'plano-emissoras',
                component: PlanoEmissorasComponent((FATHER COMPONENT))
            }

        ]
    }
]

Father Component:
export class PlanoEmissorasComponent implements OnInit, OnDestroy {
  @ViewChild(ProspectEmissorasComponent) prospectEmissoras: ProspectEmissorasComponent; ((Child Component))
  @ViewChild(NegociacaoEmissorasComponent) negociacaoEmissoras: NegociacaoEmissorasComponent;
  @ViewChild(FinancEmissorasComponent) financEmissoras: FinancEmissorasComponent;
  @ViewChild(ContratoEmissorasComponent) contratoEmissoras: ContratoEmissorasComponent;

Service:
import { VendasModule } from "../../../vendas.module";

@Injectable({
    providedIn: VendasModule
})
export class PlanoEmissorasService { ... }

I am getting this error:

WARNING in Circular dependency detected:
src/app/vendas/vendas.routing.ts -> src/app/vendas/cadastro-contrato/plano-emissoras/plano-emissoras.component.ts -> src/app/vendas/cadastro-contrato/plano-emissoras/prospect-emissoras/prospect-emissoras.component.ts -> src/app/vendas/cadastro-contrato/plano-emissoras/services/plano-emissoras.service.ts -> src/app/vendas/vendas.module.ts -> src/app/vendas/vendas.routing.ts

Body:
The circular reference is in your code generated by the TypeScript compiler when it tries to resolve the circular imports. You can follow any of the below solutions:

Using the providers array of VendasModule for
providing your service.

make the service injectable at root level: @Injectable({
providedIn: 'root' }) which will help with tree-shaking.

Use providedIn in another module and import it in VendasModule

 @Injectable({ providedIn: SomeModule})
 export class PlanoEmissorasService {}

Use this module in your VendasModule

 @NgModule({ imports: [SomeModule]})
 export class VendasModule

Check this comment out on angular repo.


问:
How to solve the "Array indices must be positive integers or logical values" when using optimization toolbox?
I am trying to implement this optimization problem through optimization toolbox:

where N = 60 ﬁles and K = 130 users when 1/K ≤ M ≤ t∗N/K, for which t∗ =3.
so I wrote this code:

```<code> clear all;
    close all;
    clc;
    N=60;
    t=3;
    K=130;
    for M=0:0.1:1.4
        r=zeros(size(1:M));
        f=le(1/K,M);
        c=le(M,3*N/K);
        if f || c
        R2 = @(s) -(s-(s./ floor(N./s)).*M);
        LB = 1;
        UB = min(N, K);
        options = optimoptions('fmincon','Algorithm','interior-point'); % run interior-point algorithm
        [sopt, ropt] = fmincon(R2,1,[],[],[],[],LB,UB,[],options);
        r(M) = -ropt;
        end
    end
    plot(0:1.4,r(M),'r-','LineWidth',2);
    xlabel('Cache Capacity (M)');
    ylabel('Delivery Rate (R)');
</code>```

However the output should be as shown in the graph the one of cut-set bound

The error is as follows:

Array indices must be positive integers or logical values.

Error in try (line 17)
r(M) = -ropt;

答:
First define r outside of the for loop

```<code> r =zeros(size(0:0.1:1.4));
</code>```

To index r inside the for loop you need integer, M is a float Number.

you can just define an additional index i

Also you don't need to specify r indices while plotting if you want
to plot the entire array, and remember to keep the abscissa as
0:0.1:1.4

The code is as follow

```<code>N=60;
t=3;
K=130;
i = 0;
r = zeros(size(0:0.1:1.4));
for M=0:0.1:1.4
    i = i+1;

    f=le(1/K,M);
    c=le(M,3*N/K);
    if f || c
       R2 = @(s) -(s-(s./ floor(N./s)).*M);
       LB = 1;
       UB = min(N, K);
       options = optimoptions('fmincon','Algorithm','interior-point'); % run interior-point algorithm
       [sopt, ropt] = fmincon(R2,1,[],[],[],[],LB,UB,[],options);
       r(i) = -ropt;
     end

    end
plot(0:0.1:1.4,r,'r-','LineWidth',2);
xlabel('Cache Capacity (M)');
ylabel('Delivery Rate (R)');

</code>```

Alternatively you just can predefine all M elements as M = 0:0.1:1.4, then loop around using integer index, that can be used also in indexing r

The corresponding code is as follow

```<code>N=60;
t=3;
K=130;
M = 0:0.1:1.4;
r = zeros(size(M));

for i = 1:length(M)

    f=le(1/K,M(i));
    c=le(M(i),3*N/K);
    if f || c
        R2 = @(s) -(s-(s./ floor(N./s)).*M(i));
        LB = 1;
        UB = min(N, K);
        options = optimoptions('fmincon','Algorithm','interior-point'); % run interior-point algorithm
        [sopt, ropt] = fmincon(R2,1,[],[],[],[],LB,UB,[],options);
        r(i) = -ropt;
    end

end
plot(0:0.1:1.4,r,'r-','LineWidth',2);
xlabel('Cache Capacity (M)');
ylabel('Delivery Rate (R)');
</code>```

Graph

Body:
I am trying to implement this optimization problem through optimization toolbox:

where N = 60 ﬁles and K = 130 users when 1/K ≤ M ≤ t∗N/K, for which t∗ =3.
so I wrote this code:

 clear all;
    close all;
    clc;
    N=60;
    t=3;
    K=130;
    for M=0:0.1:1.4
        r=zeros(size(1:M));
        f=le(1/K,M);
        c=le(M,3*N/K);
        if f || c
        R2 = @(s) -(s-(s./ floor(N./s)).*M);
        LB = 1;
        UB = min(N, K);
        options = optimoptions('fmincon','Algorithm','interior-point'); % run interior-point algorithm
        [sopt, ropt] = fmincon(R2,1,[],[],[],[],LB,UB,[],options);
        r(M) = -ropt;
        end
    end
    plot(0:1.4,r(M),'r-','LineWidth',2);
    xlabel('Cache Capacity (M)');
    ylabel('Delivery Rate (R)');

However the output should be as shown in the graph the one of cut-set bound

The error is as follows:

Array indices must be positive integers or logical values.

Error in try (line 17)
r(M) = -ropt;

Body:
First define r outside of the for loop

 r =zeros(size(0:0.1:1.4));

To index r inside the for loop you need integer, M is a float Number.

you can just define an additional index i

Also you don't need to specify r indices while plotting if you want
to plot the entire array, and remember to keep the abscissa as
0:0.1:1.4

The code is as follow

N=60;
t=3;
K=130;
i = 0;
r = zeros(size(0:0.1:1.4));
for M=0:0.1:1.4
    i = i+1;

    f=le(1/K,M);
    c=le(M,3*N/K);
    if f || c
       R2 = @(s) -(s-(s./ floor(N./s)).*M);
       LB = 1;
       UB = min(N, K);
       options = optimoptions('fmincon','Algorithm','interior-point'); % run interior-point algorithm
       [sopt, ropt] = fmincon(R2,1,[],[],[],[],LB,UB,[],options);
       r(i) = -ropt;
     end

    end
plot(0:0.1:1.4,r,'r-','LineWidth',2);
xlabel('Cache Capacity (M)');
ylabel('Delivery Rate (R)');

Alternatively you just can predefine all M elements as M = 0:0.1:1.4, then loop around using integer index, that can be used also in indexing r

The corresponding code is as follow

N=60;
t=3;
K=130;
M = 0:0.1:1.4;
r = zeros(size(M));

for i = 1:length(M)

    f=le(1/K,M(i));
    c=le(M(i),3*N/K);
    if f || c
        R2 = @(s) -(s-(s./ floor(N./s)).*M(i));
        LB = 1;
        UB = min(N, K);
        options = optimoptions('fmincon','Algorithm','interior-point'); % run interior-point algorithm
        [sopt, ropt] = fmincon(R2,1,[],[],[],[],LB,UB,[],options);
        r(i) = -ropt;
    end

end
plot(0:0.1:1.4,r,'r-','LineWidth',2);
xlabel('Cache Capacity (M)');
ylabel('Delivery Rate (R)');

Graph


问:
textAlign justify property not working in react native
I have try to use textAlign: 'justify' property in react native.TextAlign justify doesn't work on Android.
React native version: "react-native": "0.59.5"</p>

```<code>import React from 'react';
import { Image, View } from 'react-native';
import { Text, Button } from 'native-base';
import { connect } from 'react-redux';
import EStyleSheet from 'react-native-extended-stylesheet';
import { colors } from '../styles';

class Login extends React.Component {
  render() {
    return (
        <View style={styles.container}>
            <View style={styles.contentCenter}>
                <Text style={[styles.titleContent,styles.fontBold]}>Simple Secure</Text>
                <Text style={[styles.titleContent,styles.fontBold]}>Reliable Messaging</Text>
            </View>
        </View>
    );
  }
}

const styles = EStyleSheet.create({
    titleContent: {
        color:'#62778c',
        fontSize: '1.4rem',
        textAlign: 'justify',
      }
});

const mapStateToProps = (state) => {
  return {};
};

export default connect(mapStateToProps)(Login);
</code>```

答:
As mentioned above android does not support text justification but you can go around this by adding the html text inside WebView like this:</p>

```<code><WebView
    source={{ html: "<p style='text-align:justify;'>Your justified text</p>" }}
/>
</code>```

Body:
I have try to use textAlign: 'justify' property in react native.TextAlign justify doesn't work on Android.
React native version: "react-native": "0.59.5"

import React from 'react';
import { Image, View } from 'react-native';
import { Text, Button } from 'native-base';
import { connect } from 'react-redux';
import EStyleSheet from 'react-native-extended-stylesheet';
import { colors } from '../styles';

class Login extends React.Component {
  render() {
    return (
        <View style={styles.container}>
            <View style={styles.contentCenter}>
                <Text style={[styles.titleContent,styles.fontBold]}>Simple Secure</Text>
                <Text style={[styles.titleContent,styles.fontBold]}>Reliable Messaging</Text>
            </View>
        </View>
    );
  }
}

const styles = EStyleSheet.create({
    titleContent: {
        color:'#62778c',
        fontSize: '1.4rem',
        textAlign: 'justify',
      }
});

const mapStateToProps = (state) => {
  return {};
};

export default connect(mapStateToProps)(Login);

Body:
As mentioned above android does not support text justification but you can go around this by adding the html text inside WebView like this:

<WebView
    source={{ html: "<p style='text-align:justify;'>Your justified text</p>" }}
/>


问:
Places Autocomplete automatically closes on click of my trigger button to show it
I created an app that will set the current location, and the text of the location is in the button.. Then, when I click that button, it will show the PlaceAutocomplete. But, what happens is when I clicked that button, it will only show the PlaceAutocomplete for 1 second then closes automatically.. and when I'm looking in my logcat there's no error

I got my API Key from google, and put it in my google_maps_api.xml file.

```<code><string name="google_maps_key" templateMergeStrategy="preserve" translatable="false">API_KEY</string>
</code>```

and in my manifest I added this:

```<code><meta-data
        android:name="com.google.android.geo.API_KEY"
        android:value="@string/google_maps_key" />
</code>```

Now below is the button I created. I'm confused where is my mistake.

```<code>b4_sourceButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            try {
                Intent i = new PlaceAutocomplete.IntentBuilder(PlaceAutocomplete.MODE_OVERLAY).build(MainPageActivity.this);
                startActivityForResult(i,200);
            } catch (GooglePlayServicesNotAvailableException e) {
                e.printStackTrace();
            } catch (GooglePlayServicesRepairableException e) {
                e.printStackTrace();
            }
        }
    });
</code>```

It should just show the PlaceAutoComplete on click of my button. That's all..

答:
This may happen due to wrong dependency in gradle or wrong initialise of PLACES API, Kindly follow the
  instructions in the below link

https://stackoverflow.com/a/55045772/10579969

Body:
I created an app that will set the current location, and the text of the location is in the button.. Then, when I click that button, it will show the PlaceAutocomplete. But, what happens is when I clicked that button, it will only show the PlaceAutocomplete for 1 second then closes automatically.. and when I'm looking in my logcat there's no error

I got my API Key from google, and put it in my google_maps_api.xml file.

<string name="google_maps_key" templateMergeStrategy="preserve" translatable="false">API_KEY</string>

and in my manifest I added this:

<meta-data
        android:name="com.google.android.geo.API_KEY"
        android:value="@string/google_maps_key" />

Now below is the button I created. I'm confused where is my mistake.

b4_sourceButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            try {
                Intent i = new PlaceAutocomplete.IntentBuilder(PlaceAutocomplete.MODE_OVERLAY).build(MainPageActivity.this);
                startActivityForResult(i,200);
            } catch (GooglePlayServicesNotAvailableException e) {
                e.printStackTrace();
            } catch (GooglePlayServicesRepairableException e) {
                e.printStackTrace();
            }
        }
    });

It should just show the PlaceAutoComplete on click of my button. That's all..


问:
Work out the type of c# application a class contained in a DLL is being used by
Is there any way to know in C# the type of application that is running.

Windows Service
ASP.NET
Windows Form
Console

I would like to react to the application type but cannot find a way to determine it.

答:
You should have the client code tell your code what the context is and then work from that.  At best, you will be able to guess based on external factors.

If you must guess, this is what I would look for:

For ASP.NET, I would look for HttpContext.Current

For Windows Forms, I see if the static OpenForms collection on the Application class has any items in it.

For Windows Presentation Foundation, see if the static Current property on the Application class is not null.

For a service, there really is no way to determine this, since services do not have to register process handles, thread handles, or the like.

For console windows, if none of the above is true, then I would assume this is a console.

OwnerDisplayName: John Selkirk

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: casperOne


问:
How is the web.config handled by the ConfigurationManager from .NET?
On a project I am working on, we usually keep our application settings defined in a separate file.  This is how it has been done for many years, and going forward we would like to keep all system configurations in one file.  I was considering to use the web.config  section so I can just load the configurations that I need from my C# code running on the server using the ConfigurationManager class.

If I use our own way for the application settings, I would load it in a session and have it available for the application by loading values from the session.  After some reading online it looks like some of the performance issues behind using the session is that we have to deserialize the values from the session object.

Does IIS deserialize the web.config values each time we read values using the ConfigurationManager?

Thank you,
Vijay Selvaraj

答: Web.config is read once upon loading of the AppDomain. It is refreshed if any changes are made to it or any referenced files (you can put sections into external files by using the configsection= attribute on a section)</p>


问:
How to group arrays in array by first element object key
Got an array of arrays like this:

```<code>    let arr = [
      [
        {"key":2, "other":123},
        {"key":2, "other":222}
      ],
      [
        {"key":3, "other":0}
      ],
      [
        {"key":1, "other":11},
        {"key":1, "other":23}
      ],
      [
        {"key":1, "other":22}
      ]
    ]
</code>```

I need to get this arr but with grouped arrays with the same "key" value of the first element so it will be look like:

```<code>  let arr = [
      [
        {"key":2, "other":123},
        {"key":2, "other":222}
      ],
      [
        {"key":3, "other":0}
      ],
      [
        [
          {"key":1, "other":11},
          {"key":1, "other":23}
        ],
        [
          {"key":1, "other":22}
        ]
      ],

    ]
</code>```

I tried to use reduce function, but the result was totally different.

```<code>let final = []
  for (let i=0; i<arr.length; i++) {

    let arr1 = i==0?arr:arr.slice(i)

    let final1 = arr1.reduce((acc,x)=> {

      acc = acc[0].key==x[0].key?acc.concat(x):acc
      return acc
    })
    arr1.length>1&&final.push(final1)
  }
</code>```

In this code the problem is that it compares arr[1] with arr[2], arr[3] and then again arr[2] with arr[3] and groups it(even though arr[1].key and arr[2].key and arr[3].key are the same) Can you give some tips or give the final function to do this?

答:
This solution doesn't produce the exact result you're looking for, but it is nice and clean. The result you want is most likely going to give you some trouble in the future, since some elements are further nested than others.

This answer assumes that each array always has at least one element, since the question is to group by the first element key.

let arr = [[{"key":2, "other":123}, {"key":2, "other":222}], [{"key":3, "other":0}], [{"key":1, "other":11}, {"key":1, "other":23}], [{"key":1, "other":22}]];

let groups = {};
let group = key => groups[key] || (groups[key] = []);
arr.forEach(arr => group(arr[0].key).push(arr));

console.log(groups);
console.log(Object.values(groups));

// If you want to get the result you're looking for (not looking at the
// order), you can simply flatten all groups of 1 element. Although
// depending on your use case I recommend sticking with the above.

console.log(Object.values(groups).map(group => group.length === 1 ? group[0] : group));```

Body:
Got an array of arrays like this:

    let arr = [
      [
        {"key":2, "other":123},
        {"key":2, "other":222}
      ],
      [
        {"key":3, "other":0}
      ],
      [
        {"key":1, "other":11},
        {"key":1, "other":23}
      ],
      [
        {"key":1, "other":22}
      ]
    ]

I need to get this arr but with grouped arrays with the same "key" value of the first element so it will be look like:

  let arr = [
      [
        {"key":2, "other":123},
        {"key":2, "other":222}
      ],
      [
        {"key":3, "other":0}
      ],
      [
        [
          {"key":1, "other":11},
          {"key":1, "other":23}
        ],
        [
          {"key":1, "other":22}
        ]
      ],

    ]

I tried to use reduce function, but the result was totally different.

let final = []
  for (let i=0; i<arr.length; i++) {

    let arr1 = i==0?arr:arr.slice(i)

    let final1 = arr1.reduce((acc,x)=> {

      acc = acc[0].key==x[0].key?acc.concat(x):acc
      return acc
    })
    arr1.length>1&&final.push(final1)
  }

In this code the problem is that it compares arr[1] with arr[2], arr[3] and then again arr[2] with arr[3] and groups it(even though arr[1].key and arr[2].key and arr[3].key are the same) Can you give some tips or give the final function to do this?


问:
AWS IAM User with access to a folder in an Amazon EC2 instance
I have created an ubuntu instance in Amazon EC2. The instance has 3 project folders in the root directory:

```<code>/var/www/html/project_1
/var/www/html/project_2
/var/www/html/project_3
</code>```

I would like to add an IAM user for a developer with access to only project_1 folder and not the others. The developer can connect to the folder in the instance from ssh or sftp through Filezilla or ssh client but get access to only project_1 folder.

答:
One way to  achieve what you want is you can put files in S3 and mount that S3 bucket in EC2. You can mount by syncing the folder in /var/www/html/ with your S3 bucket. For reference use this link.

Now you can configure your IAM user to have access only to that bucket and make whatever changes you want in it and this will be reflected in EC2. You can access S# bucket using FTP as well now.

Body:
I have created an ubuntu instance in Amazon EC2. The instance has 3 project folders in the root directory:

/var/www/html/project_1
/var/www/html/project_2
/var/www/html/project_3

I would like to add an IAM user for a developer with access to only project_1 folder and not the others. The developer can connect to the folder in the instance from ssh or sftp through Filezilla or ssh client but get access to only project_1 folder.


问:
Convert float to String and String to float in Java
How could I convert from float to string or string to float?

In my case I need to make the assertion between 2 values string (value that I have got from table) and float value that I have calculated.

```<code>String valueFromTable = "25";
Float valueCalculated =25.0;
</code>```

I tried from float to string:

```<code>String sSelectivityRate = String.valueOf(valueCalculated);
</code>```

but the assertion fails

答:
If you're looking for, say two decimal places..

    Float f = (float)12.34;
    String s = new DecimalFormat ("#.00").format (f);

Body:
How could I convert from float to string or string to float?

In my case I need to make the assertion between 2 values string (value that I have got from table) and float value that I have calculated.

String valueFromTable = "25";
Float valueCalculated =25.0;

I tried from float to string:

String sSelectivityRate = String.valueOf(valueCalculated);

but the assertion fails


问:
Android - Make an envelope shape background in xml/vector
I'm trying to do a shape as this one in xml:

It is a simple rectangle, with a solid color and a little transparent triangle in the top-center, from the inner side.

Can this be achieved using vectors?

答:
This is a bit of a hack using ConstraintLayout and a vector drawable, but it works! It will expand to fill the width of its container.

dimens.xml

```<code><dimen name="toolbar_height">200dp</dimen>
<dimen name="toolbar_notch_width">100dp</dimen>
</code>```

notch.xml

```<code><vector
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="24dp"
    android:height="12dp"
    android:viewportWidth="24"
    android:viewportHeight="12">

    <path
        android:fillColor="#000000"
        android:pathData="m0 0 12 12 12 -12 v12 h-24 v-12 z"/>

</vector>
</code>```

toolbar.xml

```<code><androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="@dimen/toolbar_height"
    tools:layout_gravity="bottom">

    <View
        android:id="@+id/left"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:background="#F44336"
        app:layout_constraintEnd_toStartOf="@id/notch"
        app:layout_constraintStart_toStartOf="parent"/>

    <View
        android:id="@+id/notch"
        android:layout_width="@dimen/toolbar_notch_width"
        android:layout_height="0dp"
        android:background="@drawable/notch"
        android:backgroundTint="#4CAF50"
        app:layout_constraintDimensionRatio="1:0.5"
        app:layout_constraintEnd_toStartOf="@id/right"
        app:layout_constraintStart_toEndOf="@id/left"
        app:layout_constraintTop_toTopOf="parent"/>

    <View
        android:id="@+id/center"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:background="#FFEB3B"
        app:layout_constraintTop_toBottomOf="@id/notch"
        app:layout_constraintStart_toStartOf="@id/notch"
        app:layout_constraintEnd_toEndOf="@id/notch"
        app:layout_constraintBottom_toBottomOf="parent"/>

    <View
        android:id="@+id/right"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:background="#3F51B5"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@id/notch"/>

</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

Result

Body:
This is a bit of a hack using ConstraintLayout and a vector drawable, but it works! It will expand to fill the width of its container.

dimens.xml

<dimen name="toolbar_height">200dp</dimen>
<dimen name="toolbar_notch_width">100dp</dimen>

notch.xml

<vector
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="24dp"
    android:height="12dp"
    android:viewportWidth="24"
    android:viewportHeight="12">

    <path
        android:fillColor="#000000"
        android:pathData="m0 0 12 12 12 -12 v12 h-24 v-12 z"/>

</vector>

toolbar.xml

<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="@dimen/toolbar_height"
    tools:layout_gravity="bottom">

    <View
        android:id="@+id/left"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:background="#F44336"
        app:layout_constraintEnd_toStartOf="@id/notch"
        app:layout_constraintStart_toStartOf="parent"/>

    <View
        android:id="@+id/notch"
        android:layout_width="@dimen/toolbar_notch_width"
        android:layout_height="0dp"
        android:background="@drawable/notch"
        android:backgroundTint="#4CAF50"
        app:layout_constraintDimensionRatio="1:0.5"
        app:layout_constraintEnd_toStartOf="@id/right"
        app:layout_constraintStart_toEndOf="@id/left"
        app:layout_constraintTop_toTopOf="parent"/>

    <View
        android:id="@+id/center"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:background="#FFEB3B"
        app:layout_constraintTop_toBottomOf="@id/notch"
        app:layout_constraintStart_toStartOf="@id/notch"
        app:layout_constraintEnd_toEndOf="@id/notch"
        app:layout_constraintBottom_toBottomOf="parent"/>

    <View
        android:id="@+id/right"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:background="#3F51B5"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@id/notch"/>

</androidx.constraintlayout.widget.ConstraintLayout>

Result


问:
IE Flexbox doesnt respect child flexbox size
We have parent flexbox with flex-basis: auto; Inside of last parent container we have some count of flexboxes with flex-basis: 0;
The issue is that last parent container behaves like he is empty. That happens only in IE(11).

Please, share some hack to fix it.

Fiddler: https://fiddle.sencha.com/#view/editor&fiddle/2slv

Here is text example:

```<code>-div:flex-basis=auto
-div:flex-basis=auto
-div:flex-basis=auto
    --div:flex-basis=0
</code>```

IE11 doesnt respect second level div content width when calculate top level div`s width.

.container {
        display: flex;
        background: #cccccc;
        width: 50%;
    }

    .container > * {
        flex: 1 1 auto;
    }

    .first {
        background: #00ffff;
    }

    .last {
        background: #ff00ff;
        display: flex;
    }

    .btn {
        flex: 1 1 0%;
        display: flex;
        height: 30px;
    }

    .btn-inner {
        flex: 1 1 0px;
        background: rgba(0,0,0,0.2);
        display: flex;
    }

    .inner-inner {
        flex: 1 1 auto;
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
    <div class="first">
        <input type="text" \>
    </div>
    <div class="empty"></div>
    <div class="last">
        <div class="btn">
            <div class="btn-inner">
                first item item
            </div>
        </div>
        <div class="btn">
            <div class="btn-inner">
                second item item
            </div>
        </div>
    </div>
</div></code>```

答:
Try to set the min-width property of the .container class, and change the flex-basis property from 0 to "auto" for the IE browser.

Code as below:

```<code><style>
    .container {
        display: flex;
        background: #cccccc;
        width: 50%;
        min-width:300px;
    }

        .container > * {
            flex: 1 1 auto;
        }

    .first {
        background: #00ffff;
    }

    .last {
        background: #ff00ff;
        display: flex;
    }

    .btn {
        flex: 1 1 0%;
        display: flex;
        height: 30px;
    }

    .btn-inner {
        flex: 1 1 0px;
        background: rgba(0,0,0,0.2);
        display: flex;
    }

    _:-ms-fullscreen, :root .IE-FlexAuto {
        flex-basis: auto;
    }
    .inner-inner {
        flex: 1 1 auto;
    }
</style>
</code>```

and

```<code><div class="container">
    <div class="first">
        <input type="text" \>
    </div>
    <div class="empty"></div>
    <div class="last">
        <div class="btn IE-FlexAuto">
            <div class="btn-inner IE-FlexAuto">
                first item item
            </div>
        </div>
        <div class="btn IE-FlexAuto">
            <div class="btn-inner IE-FlexAuto">
                second item item
            </div>
        </div>
    </div>
</div>
</code>```

The result as below:

Body:
We have parent flexbox with flex-basis: auto; Inside of last parent container we have some count of flexboxes with flex-basis: 0;
The issue is that last parent container behaves like he is empty. That happens only in IE(11).

Please, share some hack to fix it.

Fiddler: https://fiddle.sencha.com/#view/editor&fiddle/2slv

Here is text example:

-div:flex-basis=auto
-div:flex-basis=auto
-div:flex-basis=auto
    --div:flex-basis=0

IE11 doesnt respect second level div content width when calculate top level div`s width.

.container {
        display: flex;
        background: #cccccc;
        width: 50%;
    }

    .container > * {
        flex: 1 1 auto;
    }

    .first {
        background: #00ffff;
    }

    .last {
        background: #ff00ff;
        display: flex;
    }

    .btn {
        flex: 1 1 0%;
        display: flex;
        height: 30px;
    }

    .btn-inner {
        flex: 1 1 0px;
        background: rgba(0,0,0,0.2);
        display: flex;
    }

    .inner-inner {
        flex: 1 1 auto;
    }

        <input type="text" \>

                first item item

                second item item

Body:
Try to set the min-width property of the .container class, and change the flex-basis property from 0 to "auto" for the IE browser.

Code as below:

<style>
    .container {
        display: flex;
        background: #cccccc;
        width: 50%;
        min-width:300px;
    }

        .container > * {
            flex: 1 1 auto;
        }

    .first {
        background: #00ffff;
    }

    .last {
        background: #ff00ff;
        display: flex;
    }

    .btn {
        flex: 1 1 0%;
        display: flex;
        height: 30px;
    }

    .btn-inner {
        flex: 1 1 0px;
        background: rgba(0,0,0,0.2);
        display: flex;
    }

    _:-ms-fullscreen, :root .IE-FlexAuto {
        flex-basis: auto;
    }
    .inner-inner {
        flex: 1 1 auto;
    }
</style>

and

<div class="container">
    <div class="first">
        <input type="text" \>
    </div>
    <div class="empty"></div>
    <div class="last">
        <div class="btn IE-FlexAuto">
            <div class="btn-inner IE-FlexAuto">
                first item item
            </div>
        </div>
        <div class="btn IE-FlexAuto">
            <div class="btn-inner IE-FlexAuto">
                second item item
            </div>
        </div>
    </div>
</div>

The result as below:


问:
Vim highlighting breaks after upgrading from 7.4 to 8.1
I had to update from VIM version 7.4 to 8.1 to make some functions work, but for some reason all highlighting is broken.
I use Ubuntu 18.04 and updated Vim via:

```<code>sudo add-apt-repository ppa:jonathonf/vim
sudo apt-get install vim
</code>```

Default color schemes (blue, desert, delek) disappeared. I downloaded few to try, but effect is very strange. For example, this is https://github.com/whatyouhide/vim-gotham

As you can see, it has some colors (background, numbers, font), but surely not the ones intended.

UPD: I found this thread https://ubuntuforums.org/showthread.php?t=1203649, which has somewhat solution via:

```<code>:source /usr/share/vim/vim81/syntax/sh.vim
</code>```

In the provided thread, issue was connected with manual setting for runtimepath. But the provided solution doesn't work for me

答:
Ok, I finally managed to solve the issue. Apparently it has something to do with upgrading existing vim under Ubuntu.
I added the following lines to explicitly set correct rtp:

set rtp=~/.vim,/var/lib/vim/addons,/usr/share/vim/vim81

And it worked.

Body:
I had to update from VIM version 7.4 to 8.1 to make some functions work, but for some reason all highlighting is broken.
I use Ubuntu 18.04 and updated Vim via:

sudo add-apt-repository ppa:jonathonf/vim
sudo apt-get install vim

Default color schemes (blue, desert, delek) disappeared. I downloaded few to try, but effect is very strange. For example, this is https://github.com/whatyouhide/vim-gotham

As you can see, it has some colors (background, numbers, font), but surely not the ones intended.

UPD: I found this thread https://ubuntuforums.org/showthread.php?t=1203649, which has somewhat solution via:

:source /usr/share/vim/vim81/syntax/sh.vim

In the provided thread, issue was connected with manual setting for runtimepath. But the provided solution doesn't work for me


问:
javascript SyntaxError: Identifier 'img' has already been declared
I am trying to take a picture from local notebook camera with this code:

```<code>function takePhoto(img)
{
  const img = img || document.querySelector('img');

  imageCapture.takePhoto()
  .then(blob => {
    let url = window.URL.createObjectURL(blob);
    img.src = url;
    window.URL.revokeObjectURL(url);
  })
  .catch(error);
};

takePhoto();
</code>```

but getting the following error:

```<code>SyntaxError: Identifier 'img' has already been declared
</code>```

I checked, there is no any declaration of img in the code above (also tried to rename it to something like image_local, no use). Any ideas how to fix it would be welcome. Thank you.

答: You can't declare a constant with the same name as an existing variable. In this case, img in your function parameters. Call one of the two something different.</p>

Body:
I am trying to take a picture from local notebook camera with this code:

function takePhoto(img)
{
  const img = img || document.querySelector('img');

  imageCapture.takePhoto()
  .then(blob => {
    let url = window.URL.createObjectURL(blob);
    img.src = url;
    window.URL.revokeObjectURL(url);
  })
  .catch(error);
};

takePhoto();

but getting the following error:

SyntaxError: Identifier 'img' has already been declared

I checked, there is no any declaration of img in the code above (also tried to rename it to something like image_local, no use). Any ideas how to fix it would be welcome. Thank you.


问:
Docker "ERROR: could not find an available, non-overlapping IPv4 address pool among the defaults to assign to the network"
I have a directory apkmirror-scraper-compose with the following structure:

```<code>.
├── docker-compose.yml
├── privoxy
│   ├── config
│   └── Dockerfile
├── scraper
│   ├── Dockerfile
│   ├── newnym.py
│   └── requirements.txt
└── tor
    └── Dockerfile
</code>```

I'm trying to run the following docker-compose.yml:

```<code>version: '3'

services:
  privoxy:
    build: ./privoxy
    ports:
      - "8118:8118"
    links:
      - tor

  tor:
    build:
      context: ./tor
      args:
        password: ""
    ports:
      - "9050:9050"
      - "9051:9051"

  scraper:
    build: ./scraper
    links:
      - tor
      - privoxy
</code>```

where the Dockerfile for tor is

```<code>FROM alpine:latest
EXPOSE 9050 9051
ARG password
RUN apk --update add tor
RUN echo "ControlPort 9051" >> /etc/tor/torrc
RUN echo "HashedControlPassword $(tor --quiet --hash-password $password)" >> /etc/tor/torrc
CMD ["tor"]
</code>```

that for privoxy is

```<code>FROM alpine:latest
EXPOSE 8118
RUN apk --update add privoxy
COPY config /etc/privoxy/config
CMD ["privoxy", "--no-daemon"]
</code>```

where config consists of the two lines

```<code>listen-address 0.0.0.0:8118
forward-socks5 / tor:9050 .
</code>```

and the Dockerfile for scraper is

```<code>FROM python:2.7-alpine
ADD . /scraper
WORKDIR /scraper
RUN pip install -r requirements.txt
CMD ["python", "newnym.py"]
</code>```

where requirements.txt contains the single line requests. Finally, the program newnym.py is designed to simply test whether changing the IP address using Tor is working:

```<code>from time import sleep, time

import requests as req
import telnetlib

def get_ip():
    IPECHO_ENDPOINT = 'http://ipecho.net/plain'
    HTTP_PROXY = 'http://privoxy:8118'
    return req.get(IPECHO_ENDPOINT, proxies={'http': HTTP_PROXY}).text

def request_ip_change():
    tn = telnetlib.Telnet('tor', 9051)
    tn.read_until("Escape character is '^]'.", 2)
    tn.write('AUTHENTICATE ""\r\n')
    tn.read_until("250 OK", 2)
    tn.write("signal NEWNYM\r\n")
    tn.read_until("250 OK", 2)
    tn.write("quit\r\n")
    tn.close()

if __name__ == '__main__':
    dts = []
    try:
        while True:
            ip = get_ip()
            t0 = time()
            request_ip_change()
            while True:
                new_ip = get_ip()
                if new_ip == ip:
                    sleep(1)
                else:
                    break
            dt = time() - t0
            dts.append(dt)
            print("{} -> {} in ~{}s".format(ip, new_ip, int(dt)))
    except KeyboardInterrupt:
        print("Stopping...")
        print("Average: {}".format(sum(dts) / len(dts)))
</code>```

The docker-compose build builds successfully, but if I try docker-compose up, I get the following error message:

```<code>Creating network "apkmirrorscrapercompose_default" with the default driver
ERROR: could not find an available, non-overlapping IPv4 address pool among the defaults to assign to the network
</code>```

I tried searching for help on this error message, but couldn't find any. What is causing this error?

答:
I fixed this issue by steps :

turn off your network (wireless or wired...).

reboot your system.

before turning on your network on PC, execute command docker-compose up, it's going to create new network.

then you can turn network on and go on ...

Body:
I have a directory apkmirror-scraper-compose with the following structure:

.
├── docker-compose.yml
├── privoxy
│   ├── config
│   └── Dockerfile
├── scraper
│   ├── Dockerfile
│   ├── newnym.py
│   └── requirements.txt
└── tor
    └── Dockerfile

I'm trying to run the following docker-compose.yml:

version: '3'

services:
  privoxy:
    build: ./privoxy
    ports:
      - "8118:8118"
    links:
      - tor

  tor:
    build:
      context: ./tor
      args:
        password: ""
    ports:
      - "9050:9050"
      - "9051:9051"

  scraper:
    build: ./scraper
    links:
      - tor
      - privoxy

where the Dockerfile for tor is

FROM alpine:latest
EXPOSE 9050 9051
ARG password
RUN apk --update add tor
RUN echo "ControlPort 9051" >> /etc/tor/torrc
RUN echo "HashedControlPassword $(tor --quiet --hash-password $password)" >> /etc/tor/torrc
CMD ["tor"]

that for privoxy is

FROM alpine:latest
EXPOSE 8118
RUN apk --update add privoxy
COPY config /etc/privoxy/config
CMD ["privoxy", "--no-daemon"]

where config consists of the two lines

listen-address 0.0.0.0:8118
forward-socks5 / tor:9050 .

and the Dockerfile for scraper is

FROM python:2.7-alpine
ADD . /scraper
WORKDIR /scraper
RUN pip install -r requirements.txt
CMD ["python", "newnym.py"]

where requirements.txt contains the single line requests. Finally, the program newnym.py is designed to simply test whether changing the IP address using Tor is working:

from time import sleep, time

import requests as req
import telnetlib

def get_ip():
    IPECHO_ENDPOINT = 'http://ipecho.net/plain'
    HTTP_PROXY = 'http://privoxy:8118'
    return req.get(IPECHO_ENDPOINT, proxies={'http': HTTP_PROXY}).text

def request_ip_change():
    tn = telnetlib.Telnet('tor', 9051)
    tn.read_until("Escape character is '^]'.", 2)
    tn.write('AUTHENTICATE ""\r\n')
    tn.read_until("250 OK", 2)
    tn.write("signal NEWNYM\r\n")
    tn.read_until("250 OK", 2)
    tn.write("quit\r\n")
    tn.close()

if __name__ == '__main__':
    dts = []
    try:
        while True:
            ip = get_ip()
            t0 = time()
            request_ip_change()
            while True:
                new_ip = get_ip()
                if new_ip == ip:
                    sleep(1)
                else:
                    break
            dt = time() - t0
            dts.append(dt)
            print("{} -> {} in ~{}s".format(ip, new_ip, int(dt)))
    except KeyboardInterrupt:
        print("Stopping...")
        print("Average: {}".format(sum(dts) / len(dts)))

The docker-compose build builds successfully, but if I try docker-compose up, I get the following error message:

Creating network "apkmirrorscrapercompose_default" with the default driver
ERROR: could not find an available, non-overlapping IPv4 address pool among the defaults to assign to the network

I tried searching for help on this error message, but couldn't find any. What is causing this error?


问:
What programming language would be most beneficial to have the most proficiency with?
I still have a lot to learn in terms of programming and currently only know a decent amount of C++.  I'm aware that different languages have different uses, but I was just wondering if there was perhaps one that stood out as a superior language or a language that would be applicable to more tasks?

Thanks

答:
Every language has its own set of prons, but mostly languages have same coding rules. Its better to have knowledge of multiple languages so, that you can choose which is perfect for your project, like I prefer c# for desktop application development and PHP for web applications so In the end you should be master of one. Mostly developers starts with C++ which is perfect for amateurs.

Top 5 Languages

Java popularity: 18.482% +1.13%

C popularity: 14.986% -1.62%

C++ popularity: 8.187% -1.26%

Python popularity: 7.038% +2.72%

PHP popularity: 6.973% -3.03%

This what I found but not sure its correct.

Best :)
Waqar Alamgir


问:
Datatables button through React App
I've been having issues trying to add an excel export button when working in React. I assume it has something to do with an import but I can't find much help online related to React and DataTables.net in this regard. I just want a user to be able to download to excel.

these are my imports related to jquery and datatables

```<code>const $ = require('jquery');
$.DataTable = require('datatables.net');
import 'datatables.net-dt/css/jquery.dataTables.css'
</code>```

here is where the table is defined. It works except for the buttons

```<code>componentDidMount() {
    this.$el = $(this.el);
    this.$el.DataTable({
          dom: 'Bfrtip',
          data: this.makeArray(),
          columns: this.getColumns(),
          pageLength:this.props.json.length,
          buttons: [
                {
                    extend: 'excel',
                    text: 'Save current page',
                    fileName:  "data.xlsx",
                    exportOptions: {
                       modifier: {
                            page: 'current'
                           }
                    }
                 }]});
}
</code>```

this is the render method

```<code>render() {
    return (
        <div>
            <table className="display" width="100%" ref={el=>this.el=el} />
        </div>);
}
</code>```

any help is appreciated

答:
Following the bvmcode answer I've been able to solve the problem, but instead of use requires I'm only using imports. To know what imports and components to install: https://datatables.net/download/

My imports:

```<code>import * as jzip from 'jszip';
import 'pdfmake';
import 'datatables.net-dt';
import 'datatables.net-buttons-dt';
import 'datatables.net-buttons/js/buttons.html5.js';
import 'datatables.net-fixedheader-dt';
import 'datatables.net-rowgroup-dt';
window.JSZip = jzip;
</code>```

Title: Datatables button through React App

Body:
I've been having issues trying to add an excel export button when working in React. I assume it has something to do with an import but I can't find much help online related to React and DataTables.net in this regard. I just want a user to be able to download to excel.

these are my imports related to jquery and datatables

const $ = require('jquery');
$.DataTable = require('datatables.net');
import 'datatables.net-dt/css/jquery.dataTables.css'

here is where the table is defined. It works except for the buttons

componentDidMount() {
    this.$el = $(this.el);
    this.$el.DataTable({
          dom: 'Bfrtip',
          data: this.makeArray(),
          columns: this.getColumns(),
          pageLength:this.props.json.length,
          buttons: [
                {
                    extend: 'excel',
                    text: 'Save current page',
                    fileName:  "data.xlsx",
                    exportOptions: {
                       modifier: {
                            page: 'current'
                           }
                    }
                 }]});
}

this is the render method

render() {
    return (

this.el=el} />

);
}

any help is appreciated

Body:
Following the bvmcode answer I've been able to solve the problem, but instead of use requires I'm only using imports. To know what imports and components to install: https://datatables.net/download/

My imports:

import * as jzip from 'jszip';
import 'pdfmake';
import 'datatables.net-dt';
import 'datatables.net-buttons-dt';
import 'datatables.net-buttons/js/buttons.html5.js';
import 'datatables.net-fixedheader-dt';
import 'datatables.net-rowgroup-dt';
window.JSZip = jzip;


问:
Angularjs http catch block response status is 0 from custom server
To simulate and debug a failing HTTP request, I started a nodejs server that only returns 503, but in all the cases, the status property on failure object is 0, even though the network tab shows the correct statusCode and message.

Following is the angularjs code that makes the http call:

$http.get( Url )
        .then( function( res ) {
            //regular code
            })
        .catch( function onFail ( reason ) {
            var errorMsg = "Error from server: " + reason.status + reason.statusText );
        })
        .finally( function onFinally() {
        });
```

Inspecting the reason object.

What could be the reason for the status being 0?

答:
The reason is the request was aborted. Probably you don't have connection with internet, or maybe for some reason your web aplication could't read your return status (like test bellow with status 'failed') or your server is not returning error.

In angular documentation they mention the status 0 "Also, status codes less than -1 are normalized to zero. -1 usually means the request was aborted, e.g. using a config.timeout"

https://docs.angularjs.org/api/ng/service/$http#get

You can set a custom message when you got status 0 or -1 for lost internet connection.

```<code>.catch(function(error){

                //status = HTTP code
                if(error.status == -1 || error.status == 0)
                    error.statusText = "Failed to connect to internet";

                var errorMessage = "Ocurred an connection error. Status: '" + error.status + "', message: '" + error.statusText + "'";

                return {
                    success: false,
                    message: errorMessage
                };
            });
</code>```

You can validate your return in your browser as you can see in my test bellow.

Test with wrong url, you can notice below column status '404'

Test offline, you can notice below column status 'failed'

Body:
To simulate and debug a failing HTTP request, I started a nodejs server that only returns 503, but in all the cases, the status property on failure object is 0, even though the network tab shows the correct statusCode and message.

Following is the angularjs code that makes the http call:

$http.get( Url )
        .then( function( res ) {
            //regular code
            })
        .catch( function onFail ( reason ) {
            var errorMsg = "Error from server: " + reason.status + reason.statusText );
        })
        .finally( function onFinally() {
        });

Inspecting the reason object.

What could be the reason for the status being 0?

Body:
The reason is the request was aborted. Probably you don't have connection with internet, or maybe for some reason your web aplication could't read your return status (like test bellow with status 'failed') or your server is not returning error.

In angular documentation they mention the status 0 "Also, status codes less than -1 are normalized to zero. -1 usually means the request was aborted, e.g. using a config.timeout"

https://docs.angularjs.org/api/ng/service/$http#get

You can set a custom message when you got status 0 or -1 for lost internet connection.

.catch(function(error){

                //status = HTTP code
                if(error.status == -1 || error.status == 0)
                    error.statusText = "Failed to connect to internet";

                var errorMessage = "Ocurred an connection error. Status: '" + error.status + "', message: '" + error.statusText + "'";

                return {
                    success: false,
                    message: errorMessage
                };
            });

You can validate your return in your browser as you can see in my test bellow.

Test with wrong url, you can notice below column status '404'

Test offline, you can notice below column status 'failed'


问:
Logging best practices and thoughts
I'm about to do some refactoring off my app and I came to think about this simple yet complex topic, logging, how can it be so hard to do clean, effective and informative logging...

When you read documentation on logging you often see this snippet

```<code>if (BuildConfig.DEBUG) {
    Log.d(TAG + "message");
}
</code>```

and it makes me wonder what the purpose is with it? According to the documentation, Android Developer - Log, the debug log messages are compiled in but stripped at runtime, so you wouldn't need to have the log call within that if statement. Or am I missunderstanding anything?

Then I'm also kind of wondering what the real benefit is with using any other Log.x() calls except debug as the log entries will not be seen by the user or logged into some errorfile, so they will be compiled in and executed in the production environment for no purpose at all? This is maybe a use case for the if statement before?

I mentioned earlier that the log entry isn't logged into a file. Why isn't this a built in feature in Android? Is it because of performance issues, unnecessary permission usage or something else? I have implemented this functionality in my own logging class, but now I wonder if it's bad practice? But it's also nice to have logs with important log entries?

So to wrap it up, to implement clean, effective and informative logging, both during development and in production. What's the best practices?

答:
Standard outputs should not be used directly to log anything (squid:S106)

When logging a message there are several important requirements which must be fulfilled:

The user must be able to easily retrieve the logs

The format of all logged message must be uniform to allow the user to easily read
the log

Logged data must actually be recorded

Sensitive data must only be logged securely

If a program directly writes to the standard outputs, there is absolutely no way to comply with those requirements. That's why defining and using a dedicated logger is highly recommended.

Source: Sonarcloud

Title: Logging best practices and thoughts

Body:
I'm about to do some refactoring off my app and I came to think about this simple yet complex topic, logging, how can it be so hard to do clean, effective and informative logging...

When you read documentation on logging you often see this snippet

if (BuildConfig.DEBUG) {
    Log.d(TAG + "message");
}

and it makes me wonder what the purpose is with it? According to the documentation, Android Developer - Log, the debug log messages are compiled in but stripped at runtime, so you wouldn't need to have the log call within that if statement. Or am I missunderstanding anything?

Then I'm also kind of wondering what the real benefit is with using any other Log.x() calls except debug as the log entries will not be seen by the user or logged into some errorfile, so they will be compiled in and executed in the production environment for no purpose at all? This is maybe a use case for the if statement before?

I mentioned earlier that the log entry isn't logged into a file. Why isn't this a built in feature in Android? Is it because of performance issues, unnecessary permission usage or something else? I have implemented this functionality in my own logging class, but now I wonder if it's bad practice? But it's also nice to have logs with important log entries?

So to wrap it up, to implement clean, effective and informative logging, both during development and in production. What's the best practices?


答:
Change:

const img = img || document.querySelector('img');

to:

img = img || document.querySelector('img');

Explanation:

Your function definition includes the img parameter

function takePhoto(img)

This is effectively declaring a variable called img to be used within the function with whatever value was passed in at the time of the function call. You are then trying to redeclare the img variable as a constant inside the function:

const img ...

You can't do this, as noted by the SyntaxError that you received.

Title: javascript SyntaxError: Identifier 'img' has already been declared