问:
how to use php scripts in datalife engine template files?
I want to read and display something from the database on the DataLife Engine homepage with php script.
Something like the last few news shows.

But when I call the file containing the PHP script inside the DataLife Engine template files (with the .tpl extension) (like this:{include file="test.tpl"}), this script don't work and don't show anything.

when I call the php file like this ({include file="test.php"}) in .tpl files, Data-Life-Engine show me an error with this description: Include files from root directory is denied.

Please help me to use a PHP script in the DataLife-Engine template file.
Thanks

答:
first you must put your PHP file in the path "engine/modules".
Then call it in your template file as follows:</p>

```<code>{include file="engine/modules/TEST.php"}
</code>```

Body:
first you must put your PHP file in the path "engine/modules".
Then call it in your template file as follows:

{include file="engine/modules/TEST.php"}


来源: stackexchange

问:
Only safe or non-null asserted calls are allowed on a nullable receiver of type String?
I have data class for my api response as below

```<code>data class ApiResponse(
@SerializedName("ErrorCode") @Expose
var errorCode: Int = 0,
@SerializedName("Message")
@Expose
var message: String? = null,

@SerializedName("Token")
@Expose
var token: String? = null,

@SerializedName("UserId")
@Expose
var userId: String? = null,

@SerializedName("DOB")
@Expose
var birthdate: String? = null,

@SerializedName("Mobile")
@Expose
var mobile: String? = null,

@SerializedName("Data")
@Expose
var dataList: MutableList<Data?>? = null
)
</code>```

My api call

```<code>val request = ApiServiceBuilder.buildService(NetworkCall::class.java)
    request.login(apiPost = ApiPost("long","hello")).enqueue(object :Callback<ApiResponse>{
        override fun onResponse(call: Call<ApiResponse>, response: Response<ApiResponse>) {
            Log.e("resopne",response.body().userId)
        }

        override fun onFailure(call: Call<ApiResponse>, t: Throwable) {
            t.printStackTrace()
            Log.e("resopne","error")
        }
    })
</code>```

While try to get userId I get

Only safe  or non-null asserted  calls are allowed on a nullable

答:
You have defined userId in your model class as optional or nullable by putting a ? in the front of the type.

```<code>@SerializedName("UserId")
@Expose
var userId: String? = null
</code>```

So when reading a value from the response.body() it's telling you that the value userId inside your response.body() could be null and will throw a null-pointer exception in runtime. So, to protect it it is giving you two options:

1) Only safe userId? ->
This means that if the value is null then it will not continue execution of that particular line.

2) Non-null asserted userId!! ->
Means you are telling the compiler that it will never be null and you guarantee that so if by any chance this value gets null then it's gonna throw a runtime null-pointer exception.

So, best practices are you put a ? for Only Safe and use it that way because it's not gonna make any difference if it is not-null always.

ContentLicense: CC BY-SA 4.0

Body:
I have data class for my api response as below

data class ApiResponse(
@SerializedName("ErrorCode") @Expose
var errorCode: Int = 0,
@SerializedName("Message")
@Expose
var message: String? = null,

@SerializedName("Token")
@Expose
var token: String? = null,

@SerializedName("UserId")
@Expose
var userId: String? = null,

@SerializedName("DOB")
@Expose
var birthdate: String? = null,

@SerializedName("Mobile")
@Expose
var mobile: String? = null,

@SerializedName("Data")
@Expose
var dataList: MutableList<Data?>? = null
)

My api call

val request = ApiServiceBuilder.buildService(NetworkCall::class.java)
    request.login(apiPost = ApiPost("long","hello")).enqueue(object :Callback<ApiResponse>{
        override fun onResponse(call: Call<ApiResponse>, response: Response<ApiResponse>) {
            Log.e("resopne",response.body().userId)
        }

        override fun onFailure(call: Call<ApiResponse>, t: Throwable) {
            t.printStackTrace()
            Log.e("resopne","error")
        }
    })

While try to get userId I get

Only safe  or non-null asserted  calls are allowed on a nullable

Body:
You have defined userId in your model class as optional or nullable by putting a ? in the front of the type.

@SerializedName("UserId")
@Expose
var userId: String? = null

So when reading a value from the response.body() it's telling you that the value userId inside your response.body() could be null and will throw a null-pointer exception in runtime. So, to protect it it is giving you two options:

1) Only safe userId? ->
This means that if the value is null then it will not continue execution of that particular line.

2) Non-null asserted userId!! ->
Means you are telling the compiler that it will never be null and you guarantee that so if by any chance this value gets null then it's gonna throw a runtime null-pointer exception.

So, best practices are you put a ? for Only Safe and use it that way because it's not gonna make any difference if it is not-null always.


问:
Add empty index when number of index is less then 7
I have two DatePickers one for StartDate and one for EndDate. For example when the user select 5 days I get 5 indexes with the date.

Now my question is how can I fill up this list with a minimum of 7 indexes (the filled up indexes should be empty)?

```<code> var startDate = StartDate;
        var endDate = EndDate;

        List<DateTime> Days = new List<DateTime>();

        for (DateTime counter = startDate; counter <= endDate; counter = counter.AddDays(1))
        {
            if (counter.DayOfWeek == counter.DayOfWeek)
            {
                Days.Add(counter);
            }
        }
</code>```

Here is what I have so fare. In my case this are working but it looks very ugly.
I just fill up the list with DateTime.MinValue on till I have at least 7 indexes. I am sure there is a bether way, just dont know how.

```<code> var startDate = StartDate;
        var endDate = EndDate;
        var standart = DateTime.MinValue;

        List<DateTime> Days = new List<DateTime>();

        for (DateTime counter = startDate; counter <= endDate; counter = counter.AddDays(1))
        {
            if (counter.DayOfWeek == counter.DayOfWeek)
            {
                Days.Add(counter);
            }
        }
        if (Days.Count < 7)
        {
            Days.Insert(Days.Count, standart);
        }
        if (Days.Count < 7)
        {
            Days.Insert(Days.Count, standart);
        }
        if (Days.Count < 7)
        {
            Days.Insert(Days.Count, standart);
        }
        if (Days.Count < 7)
        {
            Days.Insert(Days.Count, standart);
        }
        if (Days.Count < 7)
        {
            Days.Insert(Days.Count, standart);
        }
        if (Days.Count < 7)
        {
            Days.Insert(Days.Count, standart);
        }
</code>```

答:
You can calculate the number of days that you need to add to your list in order to reach 7, and then use it in a for loop to add them:

```<code>var startDate = new DateTime(2020, 01, 01);
var endDate = new DateTime(2020, 01, 05);
var standart = DateTime.MinValue;

List<DateTime> Days = new List<DateTime>();
int RemainingDays = 6 + (int)startDate.Day - (int)endDate.Day;

for (DateTime counter = startDate; counter <= endDate; counter = counter.AddDays(1))
        Days.Add(counter);

if (RemainingDays > 0)
    for (int i = 0; i < RemainingDays; i++)
        Days.Insert(Days.Count, standart);
</code>```

Or if you don't want to go thru another loop you can do:

```<code>if (RemainingDays > 0)
    Days.AddRange(Enumerable.Repeat(standart, RemainingDays).ToList());
</code>```

Note:

I didn't get what is your point with this line   counter.DayOfWeek == counter.DayOfWeek I think that it doesn't make any sens in this context.

Body:
I have two DatePickers one for StartDate and one for EndDate. For example when the user select 5 days I get 5 indexes with the date.

Now my question is how can I fill up this list with a minimum of 7 indexes (the filled up indexes should be empty)?

 var startDate = StartDate;
        var endDate = EndDate;

        List<DateTime> Days = new List<DateTime>();

        for (DateTime counter = startDate; counter <= endDate; counter = counter.AddDays(1))
        {
            if (counter.DayOfWeek == counter.DayOfWeek)
            {
                Days.Add(counter);
            }
        }

Here is what I have so fare. In my case this are working but it looks very ugly.
I just fill up the list with DateTime.MinValue on till I have at least 7 indexes. I am sure there is a bether way, just dont know how.

 var startDate = StartDate;
        var endDate = EndDate;
        var standart = DateTime.MinValue;

        List<DateTime> Days = new List<DateTime>();

        for (DateTime counter = startDate; counter <= endDate; counter = counter.AddDays(1))
        {
            if (counter.DayOfWeek == counter.DayOfWeek)
            {
                Days.Add(counter);
            }
        }
        if (Days.Count < 7)
        {
            Days.Insert(Days.Count, standart);
        }
        if (Days.Count < 7)
        {
            Days.Insert(Days.Count, standart);
        }
        if (Days.Count < 7)
        {
            Days.Insert(Days.Count, standart);
        }
        if (Days.Count < 7)
        {
            Days.Insert(Days.Count, standart);
        }
        if (Days.Count < 7)
        {
            Days.Insert(Days.Count, standart);
        }
        if (Days.Count < 7)
        {
            Days.Insert(Days.Count, standart);
        }

Body:
You can calculate the number of days that you need to add to your list in order to reach 7, and then use it in a for loop to add them:

var startDate = new DateTime(2020, 01, 01);
var endDate = new DateTime(2020, 01, 05);
var standart = DateTime.MinValue;

List<DateTime> Days = new List<DateTime>();
int RemainingDays = 6 + (int)startDate.Day - (int)endDate.Day;

for (DateTime counter = startDate; counter <= endDate; counter = counter.AddDays(1))
        Days.Add(counter);

if (RemainingDays > 0)
    for (int i = 0; i < RemainingDays; i++)
        Days.Insert(Days.Count, standart);

Or if you don't want to go thru another loop you can do:

if (RemainingDays > 0)
    Days.AddRange(Enumerable.Repeat(standart, RemainingDays).ToList());

Note:

I didn't get what is your point with this line   counter.DayOfWeek == counter.DayOfWeek I think that it doesn't make any sens in this context.


问:
Python Kivy-Buildozer APK not installing - running on Android 10?
I finally got to the point where I can build, error-free, a Python Kivy APK with Buildozer 1.0.
I build 2 sample apps, one with basic Python code, another with additional Python package (paho-mqtt).
I can install the APK with mqtt but when run, it closes immediatelly.
The basic Python app will not even install.
The smartphone is a Nokia 6.1 with Android 10.
As said I am using buildozer 1.0, Python 3.8.2, openjdk 1.8.0_252, Android NDK r19c running on Ubuntu 20.04 Desktop 64bit (in VirtualBox 6.1).
Are compatibility issues among above? Can it be solved? How?
NB: As my smartphone is not recognised by Buildozer when hooked up with USB to VM, I download the APK using 'buildozer' serve and the Chrome browser on my smartphone.</p>

答:
Have you tried running it on android 9?
I also have similar issue where app working on 9 but failing on android 10.</p>


问:
getting a tad lost in trying to vertically align text
Display flex works great as the variable height columns all equal one another. I have not really used CSS for many years. So I do apologise if I have missed something obvious. Any help would be massively appreciated.

```<code>.row {
    display: flex;
}
</code>```

I followed some S-O posts to vertically align text, however, I cannot seem to replicate the shared success of others.

```<code>.row {
    display: flex;
    justify-content: center;
    align-items: center;
}
</code>```

Works however not as I intended, the individual divs bgs no longer stretch, to equal heights.

I read some further posts and css-tricks, stumbled across align-self stretch.

[class*='col-'] {
  float: left;
  padding-right: 28px;
  border: 1px solid red;
  align-self: stretch;
}

.row {
  display: flex;
  justify-content: center;
  align-items: center;
}
```

<p>This unfortunately seems to go back to my first image.
<img src="https://i.stack.imgur.com/RAqKf.png" alt="enter image description here"></p>

<p>I read another post, highlighting the use of flex:1.
The columns jump around, in a manner, I am not accustomed to.
<img src="https://i.stack.imgur.com/B5mkF.png" alt="enter image description here"></p>

<pre class="lang-css prettyprint-override"><code>.row {
  display: flex;
  justify-content: center;
  align-items: center;
}

[class*='col-'] {
  float: left;
  padding-right: 28px;
  border: 1px solid red;
  flex: 1;
}
</code>```

If i remove the justify-content and align-items. That does not really help me either.

Here is my markup:

    ☰

Header

    <form>
      <input type='search' placeholder='Search Today' minlength='100'>
      <input type='submit' value='Search'>
    </form>

```

<p>Here is snapshot of my css</p>

<pre class="lang-css prettyprint-override"><code>@media only screen and (min-width: 768px) {
  h1 {
    font-size: 2.4rem;
    /* =24px */
  }

  .col-d-1 {
    width: 8.33%;
  }

  .col-d-2 {
    width: 16.66%;
  }

  .col-d-3 {
    width: 25%
  }

  .col-d-4 {
    width: 33.33%
  }

  .col-d-5 {
    width: 41.66%
  }

  .col-d-6 {
    width: 50%;
  }

  .col-d-7 {
    width: 58.33%;
  }

  .col-d-8 {
    width: 66.66%;
  }

  .col-d-9 {
    width: 75%;
  }

  .col-d-10 {
    width: 83.33%;
  }

  .col-d-11 {
    width: 91.66%
  }

  .col-d-12 {
    width: 100%;
  }

  [class*='col-'] {
    float: left;
    padding-right: 28px;
    border: 1px solid red;
  }
}

[class*='col-']:first-of-type {
  padding-left: 16px;
}

[class*='col-']:last-of-type {
  padding-right: 16px;
}

.row {
  display: flex;
}

.row::after {
  content: "";
  clear: both;
  display: table;
}
</code>```

答:
For posterity, I managed to resolve this problem with the help of this S-O post. </p>

<p>You need to add display flex to the child items; then centre. Thus adding the below snippet to my original post remedies my issue. </p>

```<code>.row [class*='col-'] {
    display: flex;
    align-items: center;
}
</code>```

Body:
Display flex works great as the variable height columns all equal one another. I have not really used CSS for many years. So I do apologise if I have missed something obvious. Any help would be massively appreciated.

.row {
    display: flex;
}

I followed some S-O posts to vertically align text, however, I cannot seem to replicate the shared success of others.

.row {
    display: flex;
    justify-content: center;
    align-items: center;
}

Works however not as I intended, the individual divs bgs no longer stretch, to equal heights.

I read some further posts and css-tricks, stumbled across align-self stretch.

[class*='col-'] {
  float: left;
  padding-right: 28px;
  border: 1px solid red;
  align-self: stretch;
}

.row {
  display: flex;
  justify-content: center;
  align-items: center;
}

This unfortunately seems to go back to my first image.

I read another post, highlighting the use of flex:1.
The columns jump around, in a manner, I am not accustomed to.

.row {
  display: flex;
  justify-content: center;
  align-items: center;
}

[class*='col-'] {
  float: left;
  padding-right: 28px;
  border: 1px solid red;
  flex: 1;
}

If i remove the justify-content and align-items. That does not really help me either.

Here is my markup:

    ☰

Header

    <form>
      <input type='search' placeholder='Search Today' minlength='100'>
      <input type='submit' value='Search'>
    </form>

Here is snapshot of my css

@media only screen and (min-width: 768px) {
  h1 {
    font-size: 2.4rem;
    /* =24px */
  }

  .col-d-1 {
    width: 8.33%;
  }

  .col-d-2 {
    width: 16.66%;
  }

  .col-d-3 {
    width: 25%
  }

  .col-d-4 {
    width: 33.33%
  }

  .col-d-5 {
    width: 41.66%
  }

  .col-d-6 {
    width: 50%;
  }

  .col-d-7 {
    width: 58.33%;
  }

  .col-d-8 {
    width: 66.66%;
  }

  .col-d-9 {
    width: 75%;
  }

  .col-d-10 {
    width: 83.33%;
  }

  .col-d-11 {
    width: 91.66%
  }

  .col-d-12 {
    width: 100%;
  }

  [class*='col-'] {
    float: left;
    padding-right: 28px;
    border: 1px solid red;
  }
}

[class*='col-']:first-of-type {
  padding-left: 16px;
}

[class*='col-']:last-of-type {
  padding-right: 16px;
}

.row {
  display: flex;
}

.row::after {
  content: "";
  clear: both;
  display: table;
}

Body:
For posterity, I managed to resolve this problem with the help of this S-O post.

You need to add display flex to the child items; then centre. Thus adding the below snippet to my original post remedies my issue.

.row [class*='col-'] {
    display: flex;
    align-items: center;
}


问:
main.jsbundle does not exist. this must be a bug with + echo 'react native
I tried to archive my react native project using Product > Archive on XCode9.2. But Xcode produce this error:

```<code>File /Users/louis/Library/Developer/Xcode/DerivedData/Scavenger-evyvzocndqoghkclcbwewolywniz/Build/Products/Release-iphoneos/Scavenger.app/main.jsbundle does not exist. This must be a bug with

My Environment:
  OS: macOS Sierra 10.12.6
  Node: 9.3.0
  npm: 5.5.1
  Watchman: 4.7.0
  Xcode: Xcode 9.2 Build version 9C40b
  Android Studio: 3.0 AI-171.4443003

Packages: (wanted => installed)
  react: ^16.0.0 => 16.2.0
  react-native: ^0.50.3 => 0.50.4
</code>```

I also tried to run on terminal

react-native bundle --entry-file='index.ios.js' --bundle-output='./ios/Scavenger/main.jsbundle' --dev=false --platform='ios' --assets-dest='./ios'but ended up with error Loading dependency graph...
    Unexpected end of JSON input

XCode error.

答:
if you update the xcode and get this error then solution is

in terminal of your root project fire following commands

```<code> 1. sudo xcode-select --reset

 2. npx react-native bundle --entry-file ./index.js --platform ios --bundle-output ios/main.jsbundle
</code>```

during second command if you found any error relative to JS then fix it
After successfully running second command this error will be gone

ContentLicense: CC BY-SA 3.0

Body:
I tried to archive my react native project using Product > Archive on XCode9.2. But Xcode produce this error:

File /Users/louis/Library/Developer/Xcode/DerivedData/Scavenger-evyvzocndqoghkclcbwewolywniz/Build/Products/Release-iphoneos/Scavenger.app/main.jsbundle does not exist. This must be a bug with

My Environment:
  OS: macOS Sierra 10.12.6
  Node: 9.3.0
  npm: 5.5.1
  Watchman: 4.7.0
  Xcode: Xcode 9.2 Build version 9C40b
  Android Studio: 3.0 AI-171.4443003

Packages: (wanted => installed)
  react: ^16.0.0 => 16.2.0
  react-native: ^0.50.3 => 0.50.4

I also tried to run on terminal

react-native bundle --entry-file='index.ios.js' --bundle-output='./ios/Scavenger/main.jsbundle' --dev=false --platform='ios' --assets-dest='./ios'but ended up with error Loading dependency graph...
    Unexpected end of JSON input

XCode error.

Body:
if you update the xcode and get this error then solution is

in terminal of your root project fire following commands

 1. sudo xcode-select --reset

 2. npx react-native bundle --entry-file ./index.js --platform ios --bundle-output ios/main.jsbundle

during second command if you found any error relative to JS then fix it
After successfully running second command this error will be gone


问:
How can I get all unique tags from an array with lodash?
Im using Vuejs and lodash and particular lodash to try and get all uniqe tags for question in my very simple questions "app". But for some reason lodash returs all of the tags, not the uniqe ones. This is how I have design the array of questions and tags (might be a better way but dunno).

```<code>created() {
  this.tags = _.chain(this.fragor).map('tags').uniq().value()
},
data: function() {
    return {
        tags:[],
        fragor:[
        {
            'fraga': "Question 1",
            'svar' : "This is this explanation",
            'tags' : ['knowledge'],
        },
        {
            'fraga': "Question 2",
            'svar' : "This is this explanation for question 2",
            'tags' : ['knowledge', 'code'],
        },
        {
            'fraga': "Question 3",
            'svar' : "This is this explanation for question 3",
            'tags' : ['code'],
        }
        ]
    }
}
</code>```

tags is return [ "knowledge" ] [ "knowledge", "code" ] [ "code" ] when the expected result should be ['knowledge', 'code']. How can i achive this with lodash and vue?

I made a jsfiddle for you guys.

答:
When you want to get a single array of values by extracting
multiple arrays use _.flatMap():

const fragor = [{"fraga":"Question 1","svar":"This is this explanation","tags":["knowledge"]},{"fraga":"Question 2","svar":"This is this explanation for question 2","tags":["knowledge","code"]},{"fraga":"Question 3","svar":"This is this explanation for question 3","tags":["code"]}]

const tags = _(fragor).flatMap('tags').uniq().value()

console.log(tags)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script></code>```

Body:
Im using Vuejs and lodash and particular lodash to try and get all uniqe tags for question in my very simple questions "app". But for some reason lodash returs all of the tags, not the uniqe ones. This is how I have design the array of questions and tags (might be a better way but dunno).

created() {
  this.tags = _.chain(this.fragor).map('tags').uniq().value()
},
data: function() {
    return {
        tags:[],
        fragor:[
        {
            'fraga': "Question 1",
            'svar' : "This is this explanation",
            'tags' : ['knowledge'],
        },
        {
            'fraga': "Question 2",
            'svar' : "This is this explanation for question 2",
            'tags' : ['knowledge', 'code'],
        },
        {
            'fraga': "Question 3",
            'svar' : "This is this explanation for question 3",
            'tags' : ['code'],
        }
        ]
    }
}

tags is return [ "knowledge" ] [ "knowledge", "code" ] [ "code" ] when the expected result should be ['knowledge', 'code']. How can i achive this with lodash and vue?

I made a jsfiddle for you guys.

Body:
When you want to get a single array of values by extracting
multiple arrays use _.flatMap():

const fragor = [{"fraga":"Question 1","svar":"This is this explanation","tags":["knowledge"]},{"fraga":"Question 2","svar":"This is this explanation for question 2","tags":["knowledge","code"]},{"fraga":"Question 3","svar":"This is this explanation for question 3","tags":["code"]}]

const tags = _(fragor).flatMap('tags').uniq().value()

console.log(tags)

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>


问:
Positioning table elements differently on mobile
I'm creating a table that on desktop has an image on the left and text on the right. On mobile the text needs to act as a header so should sit on top. I've tried floating this to the right but that hasn't worked.

I need the table to be 100% of the width of the screen with all of its elements centered. Here's the code I'm currently using which works fine but places the image on the top.

.site-section-content {
        width: 100%;
    }

    .site-section-wrap {
      width: 100%;
      display: flex;
      background: pink;
      align-items: center;
      justify-content: center;
      flex-flow: row;
      text-align: center;
    }

    @media only screen and (max-width: 900px) {
    .site-section-wrap {
      width: 100%;
      display: table;
      background: pink;
      align-items: center;
      justify-content: center;
      text-align: center;
    }
    }

    .site-section-title-section {
      width: 50%;
      float: right;
    }

    @media only screen and (max-width: 900px) {
    .site-section-title-section {
      width: 100%;
      float: left;
    }
    }

    .site-section-info-section {
      width: 50%;
      float: right;
    }

    @media only screen and (max-width: 900px) {
    .site-section-info-section {
      width: 100%;
      float: left;
    }
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <div class="site-section-content">
       <div class="site-section-wrap">
          <div class="site-section-title-section">
                 <p>Left on Desktop | Bottom on Mobile (when stacked)</p>
          </div>
          <div class="site-section-info-section">
                <p><p>Right on Desktop | Top on Mobile (when stacked)</p></p>
          </div>
       </div>
    </div></code>```

I may alternate the images so that some are on the left and some on the right so I'd change the tags around for that, like this.

.site-section-content {
        width: 100%;
    }

    .site-section-wrap {
      width: 100%;
      display: flex;
      background: pink;
      align-items: center;
      justify-content: center;
      flex-flow: row;
      text-align: center;
    }

    @media only screen and (max-width: 900px) {
    .site-section-wrap {
      width: 100%;
      display: table;
      background: pink;
      align-items: center;
      justify-content: center;
      text-align: center;
    }
    }

    .site-section-title-section {
      width: 50%;
      float: right;
    }

    @media only screen and (max-width: 900px) {
    .site-section-title-section {
      width: 100%;
      float: left;
    }
    }

    .site-section-info-section {
      width: 50%;
      float: right;
    }

    @media only screen and (max-width: 900px) {
    .site-section-info-section {
      width: 100%;
      float: left;
    }
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
<div class="site-section-content">
   <div class="site-section-wrap">
      <div class="site-section-title-section">
         <p>Left on Desktop | Bottom on Mobile (when stacked)</p>
      </div>
      <div class="site-section-info-section">
         <p>
         <p>Right on Desktop | Top on Mobile (when stacked)</p>
         </p>
      </div>
   </div>
   <div class="site-section-wrap">
      <div class="site-section-info-section">
         <p>
         <p>Left on Desktop | Bottom on Mobile (when stacked)</p>
         </p>
      </div>
      <div class="site-section-title-section">
         <p>Right on Desktop | Top on Mobile (when stacked)</p>
      </div>
   </div>
</div></code>```

So ideally the desktop site would look like this:

The mobile version like this:

And have this potential ideally (although all images could be on the left, it wouldn't look as good)

I could just name the outer wrappers left and right then place content accordingly but the text would always need to be on top. I've attempted to use a mix of flex (to center things) and table (for mobile) but I'm open to alternative approaches if they'd make more sense.

答:
no need of using floats, just do it with flex-direction

.site-section-content {
        width: 100%;
    }

    .site-section-wrap {
      width: 100%;
      display: flex;
      background: pink;
      align-items: center;
      justify-content: center;
      text-align: center;
    }

    @media only screen and (max-width: 900px) {
      .site-section-wrap {flex-direction: column-reverse;}
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
<div class="site-section-content">
   <div class="site-section-wrap">
      <div class="site-section-title-section">
         <p>Left on Desktop | Bottom on Mobile (when stacked)</p>
      </div>
      <div class="site-section-info-section">
         <p>Right on Desktop | Top on Mobile (when stacked)</p>
         </p>
      </div>
   </div>
   <div class="site-section-wrap">
      <div class="site-section-info-section">
         <p>
         <p>Left on Desktop | Bottom on Mobile (when stacked)</p>
         </p>
      </div>
      <div class="site-section-title-section">
         <p>Right on Desktop | Top on Mobile (when stacked)</p>
      </div>
   </div>
</div></code>```

Body:
I'm creating a table that on desktop has an image on the left and text on the right. On mobile the text needs to act as a header so should sit on top. I've tried floating this to the right but that hasn't worked.

I need the table to be 100% of the width of the screen with all of its elements centered. Here's the code I'm currently using which works fine but places the image on the top.

.site-section-content {
        width: 100%;
    }

    .site-section-wrap {
      width: 100%;
      display: flex;
      background: pink;
      align-items: center;
      justify-content: center;
      flex-flow: row;
      text-align: center;
    }

    @media only screen and (max-width: 900px) {
    .site-section-wrap {
      width: 100%;
      display: table;
      background: pink;
      align-items: center;
      justify-content: center;
      text-align: center;
    }
    }

    .site-section-title-section {
      width: 50%;
      float: right;
    }

    @media only screen and (max-width: 900px) {
    .site-section-title-section {
      width: 100%;
      float: left;
    }
    }

    .site-section-info-section {
      width: 50%;
      float: right;
    }

    @media only screen and (max-width: 900px) {
    .site-section-info-section {
      width: 100%;
      float: left;
    }
    }

<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">

Left on Desktop | Bottom on Mobile (when stacked)

Right on Desktop | Top on Mobile (when stacked)

I may alternate the images so that some are on the left and some on the right so I'd change the tags around for that, like this.

.site-section-content {
        width: 100%;
    }

    .site-section-wrap {
      width: 100%;
      display: flex;
      background: pink;
      align-items: center;
      justify-content: center;
      flex-flow: row;
      text-align: center;
    }

    @media only screen and (max-width: 900px) {
    .site-section-wrap {
      width: 100%;
      display: table;
      background: pink;
      align-items: center;
      justify-content: center;
      text-align: center;
    }
    }

    .site-section-title-section {
      width: 50%;
      float: right;
    }

    @media only screen and (max-width: 900px) {
    .site-section-title-section {
      width: 100%;
      float: left;
    }
    }

    .site-section-info-section {
      width: 50%;
      float: right;
    }

    @media only screen and (max-width: 900px) {
    .site-section-info-section {
      width: 100%;
      float: left;
    }
    }

<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">

Left on Desktop | Bottom on Mobile (when stacked)

Right on Desktop | Top on Mobile (when stacked)

Left on Desktop | Bottom on Mobile (when stacked)

Right on Desktop | Top on Mobile (when stacked)

So ideally the desktop site would look like this:

The mobile version like this:

And have this potential ideally (although all images could be on the left, it wouldn't look as good)

I could just name the outer wrappers left and right then place content accordingly but the text would always need to be on top. I've attempted to use a mix of flex (to center things) and table (for mobile) but I'm open to alternative approaches if they'd make more sense.

Body:
no need of using floats, just do it with flex-direction

.site-section-content {
        width: 100%;
    }

    .site-section-wrap {
      width: 100%;
      display: flex;
      background: pink;
      align-items: center;
      justify-content: center;
      text-align: center;
    }

    @media only screen and (max-width: 900px) {
      .site-section-wrap {flex-direction: column-reverse;}
    }

<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
<div class="site-section-content">
   <div class="site-section-wrap">
      <div class="site-section-title-section">
         <p>Left on Desktop | Bottom on Mobile (when stacked)</p>
      </div>
      <div class="site-section-info-section">
         <p>Right on Desktop | Top on Mobile (when stacked)</p>
         </p>
      </div>
   </div>
   <div class="site-section-wrap">
      <div class="site-section-info-section">
         <p>
         <p>Left on Desktop | Bottom on Mobile (when stacked)</p>
         </p>
      </div>
      <div class="site-section-title-section">
         <p>Right on Desktop | Top on Mobile (when stacked)</p>
      </div>
   </div>
</div>


问:
php echo an element of an array
I have a variable $var. On var_dump($var); it shows:

```<code>array(1) { [0]=> object(stdClass)#23 (2) { ["stop_id"]=> string(1) "1" ["flag"]=> string(1) "1" } }
</code>```

I want the element 'flag' to access from $var. How to do it?

I tried:

```<code>echo $var[0]["flag"];
</code>```

It shows:

Message: Cannot use object of type stdClass as array

Please help

答:
The first element of the array is an object, so you have to use this code:</p>

```<code>echo $var[0]->flag;
</code>```

Title: php echo an element of an array

Body:
I have a variable $var. On var_dump($var); it shows:

array(1) { [0]=> object(stdClass)#23 (2) { ["stop_id"]=> string(1) "1" ["flag"]=> string(1) "1" } }

I want the element 'flag' to access from $var. How to do it?

I tried:

echo $var[0]["flag"];

It shows:

Message: Cannot use object of type stdClass as array

Please help

Body:
The first element of the array is an object, so you have to use this code:

echo $var[0]->flag;


问:
Where Is the AVD manager in android studio 4.0
I just updated my android studio to version 4.0.

Before the update (version 3.6), if I wanted to open the AVD manager all I needed to do was

 Tools > AVD Manager

Now I cannot open the avd manager with Tools > AVD Manager because the option is not there anymore

According to the documentation all needed to be done is Tools > AVD Manager

How it looks in Android studio:

Where can I find the "AVD manager" option on android studio 4.0?

答: Updated my answer. You can find here avd manager.


问:
LARAVEL - Undefined variable: imageName
Seeking for your help again. I'm having trouble on uploading multiple images. I'm getting this error Undefined variable: imageName. Please help.

Controller:

```<code>            if ($request->hasFile('image')){
            $imageName =  $request->image->store('public');
            }

            if ($request->hasFile('image2')){
              $imageName2 =  $request->image2->store('public');
            }

            if ($request->hasFile('image3')){
              $imageName3 =  $request->image3->store('public');
            }

            if ($request->hasFile('image4')){
              $imageName4 =  $request->image4->store('public');
            }

            if ($request->hasFile('image5')){
            $imageName5 =  $request->image5->store('public');
            }

             $post = new post;

          $post->image = $imageName;
          $post->image2 = $imageName2;
          $post->image3 = $imageName3;
          $post->image4 = $imageName4;
          $post->image5 = $imageName5;
</code>```

Need your help please. Thanks in advance!

答:
Before accessing a variable you need to declare it first. So, before all your if conditions, declare them like this:</p>

```<code>$imageName = $imageName2 = $imageName3 = ... = null;

if ($request->hasFile('image')) {
.
.
</code>```

Title: LARAVEL - Undefined variable: imageName

Body:
Seeking for your help again. I'm having trouble on uploading multiple images. I'm getting this error Undefined variable: imageName. Please help.

Controller:

            if ($request->hasFile('image')){
            $imageName =  $request->image->store('public');
            }

            if ($request->hasFile('image2')){
              $imageName2 =  $request->image2->store('public');
            }

            if ($request->hasFile('image3')){
              $imageName3 =  $request->image3->store('public');
            }

            if ($request->hasFile('image4')){
              $imageName4 =  $request->image4->store('public');
            }

            if ($request->hasFile('image5')){
            $imageName5 =  $request->image5->store('public');
            }

             $post = new post;

          $post->image = $imageName;
          $post->image2 = $imageName2;
          $post->image3 = $imageName3;
          $post->image4 = $imageName4;
          $post->image5 = $imageName5;

Need your help please. Thanks in advance!

Body:
Before accessing a variable you need to declare it first. So, before all your if conditions, declare them like this:

$imageName = $imageName2 = $imageName3 = ... = null;

if ($request->hasFile('image')) {
.
.


问:
Removing substring of from a list of strings
There are several countries with numbers and/or parenthesis in my list. How I  remove these?

e.g.

'Bolivia (Plurinational State of)' should be 'Bolivia',

'Switzerland17' should be 'Switzerland'.

答:
Using Regex and simple List Operation

Go through the list items, find the regex matching in each item, and replace the values in place. This regex "[a-zA-Z]{2,}" works for only string matching with the minimum size of two or more. It gives your freedom based on parenthesis. The better approach for Regex is to use Matching string based on your input domain (i.e country in your case) and a Country name cannot have a number in its name or Parenthesis. SO you should use the following.

```<code>import re
list_of_country_strings = ["Switzerland17", "America290","Korea(S)"]
for index in range(len(list_of_country_strings)):
    x = re.match("[a-zA-Z]{2,}",string = list_of_country_strings[index])
    if x:
        list_of_country_strings[index] = list_of_country_strings[index][x.start():x.end()]

print(list_of_country_strings)
</code>```

Output
['Switzerland', 'America', 'Korea']

Body:
Using Regex and simple List Operation

Go through the list items, find the regex matching in each item, and replace the values in place. This regex "[a-zA-Z]{2,}" works for only string matching with the minimum size of two or more. It gives your freedom based on parenthesis. The better approach for Regex is to use Matching string based on your input domain (i.e country in your case) and a Country name cannot have a number in its name or Parenthesis. SO you should use the following.

import re
list_of_country_strings = ["Switzerland17", "America290","Korea(S)"]
for index in range(len(list_of_country_strings)):
    x = re.match("[a-zA-Z]{2,}",string = list_of_country_strings[index])
    if x:
        list_of_country_strings[index] = list_of_country_strings[index][x.start():x.end()]

print(list_of_country_strings)

Output
['Switzerland', 'America', 'Korea']


问:
PHP not displaying username after login
I'm learning php and html from scratch, and I have this project in which I'd like to display the username after logging in.

I've stated that:

```<code><a>Hello, <?php
                        if(isset($_SESSION['username'])){
                            echo $_SESSION['username'];
                        } else {
                            echo "user";
                        }

                        ?>
                        </a>
</code>```

at the html field in which I want the username to show. It worked before.
However, after logging out, the username is no longer there.

This is the code for the logout:

```<code><?php

     session_start();
     session_unset();
     header("location:index.php");
     exit();

?>
</code>```

And the one for logging in:

```<code><?php
session_start();

$user = $_POST['login'];
$pass = md5($_POST['pword']);
$entrar = $_POST['entrar'];
$conn = mysqli_connect("localhost","root", "", "pdsys", "3308");

if(isset($entrar)){
    $verifica = mysqli_query($conn,"SELECT * FROM users WHERE username = '$user' AND pword = '$pass'") or die ("Usuário ou senha incorretos");
    if (mysqli_num_rows($verifica)<=0){
        echo "<script language='javascript' type='text/javascript'>
        alert('Login e/ou senha incorretos');window.location
        .href='index.php';</script>";
        die();
    } else {
        setcookie("login", $user);
        header("location: main.php");
    }
}?>
</code>```

I figure it might have something to do with the session_destroy(), but I can't figure it out how to make it work again. It just displays "user".

Everything else is functional = the connection with the database, the login system etc.

答:
Use

```<code>session_destroy();
</code>```

in logout functionality.

Title: PHP not displaying username after login

Body:
I'm learning php and html from scratch, and I have this project in which I'd like to display the username after logging in.

I've stated that:

Hello, <?php
                        if(isset($_SESSION['username'])){
                            echo $_SESSION['username'];
                        } else {
                            echo "user";
                        }

                        ?>

at the html field in which I want the username to show. It worked before.
However, after logging out, the username is no longer there.

This is the code for the logout:

<?php

     session_start();
     session_unset();
     header("location:index.php");
     exit();

?>

And the one for logging in:

<?php
session_start();

$user = $_POST['login'];
$pass = md5($_POST['pword']);
$entrar = $_POST['entrar'];
$conn = mysqli_connect("localhost","root", "", "pdsys", "3308");

if(isset($entrar)){
    $verifica = mysqli_query($conn,"SELECT * FROM users WHERE username = '$user' AND pword = '$pass'") or die ("Usuário ou senha incorretos");
    if (mysqli_num_rows($verifica)<=0){
        echo "";
        die();
    } else {
        setcookie("login", $user);
        header("location: main.php");
    }
}?>

I figure it might have something to do with the session_destroy(), but I can't figure it out how to make it work again. It just displays "user".

Everything else is functional = the connection with the database, the login system etc.

Body:
Use

session_destroy();

in logout functionality.


问:
Error when checking target: expected dense_2 to have shape (3,) but got array with shape (1,)
I changed the data type but I could not resolve the error.

I tried One-Hot Encoding but it doesn't work too.

I don't know what's wrong:(

```<code>seed = 0
np.random.seed(seed)
tf.set_random_seed(seed)

df = pd.read_csv('HW01_dataset_tae.txt', sep=',' ,header=None, names = ["Native", "Instructor", "Course", "Semester", "Class Size", "Evaluation"])

dataset = df.values # dataframe to int64
X = dataset[:,0:5] # attribute
Y_Eva = dataset[:,5] # class

e = LabelEncoder()
e.fit(Y_Eva)
Y = e.transform(Y_Eva)

K = 10
kFold = StratifiedKFold(n_splits=K, shuffle=True, random_state=seed)

accuracy = []

for train_index, test_index in kFold.split(X,Y):
    model = Sequential()
    model.add(Dense(16, input_dim=5, activation='relu'))
    model.add(Dense(10, activation='relu'))
    model.add(Dense(3, activation='softmax'))
    model.compile(loss='mean_squared_error',
              optimizer='adam',
              metrics=['accuracy'])
    model.fit(X[train_index], Y[train_index], epochs=100, batch_size=2)

</code>```

the error ; Error when checking target: expected dense_2 to have shape (3,) but got array with shape (1,)

is detected at here ; model.fit(X[train_index], Y[train_index], epochs=100, batch_size=2).

What shout I do?

答:
I solved the problem.

At this code,

```<code>model.fit(X[train_index], Y[train_index], epochs=100, batch_size=2)
</code>```

the number of rows in 'Y[train_index]' must be three because the classes are three.

The error came out since each Y[train_index] has only one row.

So, I used One-Hot Encoding and changed the code like this.

```<code>e = LabelEncoder()
e.fit(Y_Eva)
Y = e.transform(Y_Eva)
Y_encoded = np_utils.to_categorical(Y) # changed code

K = 10
kFold = StratifiedKFold(n_splits=K, shuffle=True, random_state=seed)

accuracy = []

for train_index, test_index in kFold.split(X,Y):
    model = Sequential()
    model.add(Dense(32, input_dim=5, activation='relu'))
    model.add(Dense(16, activation='relu'))
    model.add(Dense(3, activation='softmax'))
    model.compile(loss='categorical_crossentropy',
              optimizer='adam',
              metrics=['accuracy'])
    model.fit(X[train_index], Y_encoded[train_index], epochs=100, batch_size=2) # changed code
</code>```

Finally, I was able to run the code.

Body:
I changed the data type but I could not resolve the error.

I tried One-Hot Encoding but it doesn't work too.

I don't know what's wrong:(

seed = 0
np.random.seed(seed)
tf.set_random_seed(seed)

df = pd.read_csv('HW01_dataset_tae.txt', sep=',' ,header=None, names = ["Native", "Instructor", "Course", "Semester", "Class Size", "Evaluation"])

dataset = df.values # dataframe to int64
X = dataset[:,0:5] # attribute
Y_Eva = dataset[:,5] # class

e = LabelEncoder()
e.fit(Y_Eva)
Y = e.transform(Y_Eva)

K = 10
kFold = StratifiedKFold(n_splits=K, shuffle=True, random_state=seed)

accuracy = []

for train_index, test_index in kFold.split(X,Y):
    model = Sequential()
    model.add(Dense(16, input_dim=5, activation='relu'))
    model.add(Dense(10, activation='relu'))
    model.add(Dense(3, activation='softmax'))
    model.compile(loss='mean_squared_error',
              optimizer='adam',
              metrics=['accuracy'])
    model.fit(X[train_index], Y[train_index], epochs=100, batch_size=2)

the error ; Error when checking target: expected dense_2 to have shape (3,) but got array with shape (1,)

is detected at here ; model.fit(X[train_index], Y[train_index], epochs=100, batch_size=2).

What shout I do?

Body:
I solved the problem.

At this code,

model.fit(X[train_index], Y[train_index], epochs=100, batch_size=2)

the number of rows in 'Y[train_index]' must be three because the classes are three.

The error came out since each Y[train_index] has only one row.

So, I used One-Hot Encoding and changed the code like this.

e = LabelEncoder()
e.fit(Y_Eva)
Y = e.transform(Y_Eva)
Y_encoded = np_utils.to_categorical(Y) # changed code

K = 10
kFold = StratifiedKFold(n_splits=K, shuffle=True, random_state=seed)

accuracy = []

for train_index, test_index in kFold.split(X,Y):
    model = Sequential()
    model.add(Dense(32, input_dim=5, activation='relu'))
    model.add(Dense(16, activation='relu'))
    model.add(Dense(3, activation='softmax'))
    model.compile(loss='categorical_crossentropy',
              optimizer='adam',
              metrics=['accuracy'])
    model.fit(X[train_index], Y_encoded[train_index], epochs=100, batch_size=2) # changed code

Finally, I was able to run the code.


问:
facing a problem Dividing the maximum length of a string using substr PHP
I'm facing a problem with dividing the maximum number by itself.
Example, the number is

```<code>6667880025043855
</code>```

which is max length is 16, so I will divide it into four digits with four breaks in every number

Example:

```<code>6667
8800
2504
3855
</code>```

So what I did is using substr and dividing it by four.

The code:

```<code>if (strlen($number) == 16) { // instaces if the max length is 16.
  echo $number1 = substr($number, 0, 4)."</br>";
   echo $number2 = substr($number, 4, 8)."</br>";
   echo $number3 = substr($number, 8, 12)."</br>";
   echo $number4 = substr($number, 12, 16)."</br>";
}
</code>```

But my output would be:

```<code>6667
88002504
25043855
3855
</code>```

Am I doing it wrong?
P.S:
I'm still in the beginner's phase.

答:
Why not use chunk_split to split the number into pieces?

```<code>$number=6667880025043855;
$length=4;
$chunks=chunk_split( strval($number), $length );

printf('```%s```',print_r($chunks,true));
</code>```

Will yield:

```<code>6667
8800
2504
3855
</code>```

Or, if you need as separate variables:

```<code>$chunks=explode( PHP_EOL, chunk_split( strval( $number ), $length ) );
</code>```

then you can access each number, like this:

```<code>echo $chunks[1];// yields 8800 etc
</code>```

Body:
I'm facing a problem with dividing the maximum number by itself.
Example, the number is

6667880025043855

which is max length is 16, so I will divide it into four digits with four breaks in every number

Example:

6667
8800
2504
3855

So what I did is using substr and dividing it by four.

The code:

if (strlen($number) == 16) { // instaces if the max length is 16.
  echo $number1 = substr($number, 0, 4)."
";
   echo $number2 = substr($number, 4, 8)."
";
   echo $number3 = substr($number, 8, 12)."
";
   echo $number4 = substr($number, 12, 16)."
";
}

But my output would be:

6667
88002504
25043855
3855

Am I doing it wrong?
P.S:
I'm still in the beginner's phase.

Body:
Why not use chunk_split to split the number into pieces?

$number=6667880025043855;
$length=4;
$chunks=chunk_split( strval($number), $length );

printf('<pre>%s</pre>',print_r($chunks,true));

Will yield:

6667
8800
2504
3855

Or, if you need as separate variables:

$chunks=explode( PHP_EOL, chunk_split( strval( $number ), $length ) );

then you can access each number, like this:

echo $chunks[1];// yields 8800 etc


问:
Create a New Column by evaluating multiple columns
I have a data.frame dt_info that looks like the following:

```<code>date       col_1     col_2    col_3  ... col_100
d/m/y       info1     n/a      n/a   ...  n/a
d/m/y       n/a       n/a     info2  ...  n/a
d/m/y       n/a       n/a       n/a  ...  infon
</code>```

The output I'm looking for should be like this:

```<code>date       col_1     col_2    col_3  ... col_100    new_col
d/m/y       info1     n/a      n/a   ...  n/a         info1
d/m/y       n/a       n/a     info2  ...  n/a         info2
d/m/y       n/a       n/a       n/a  ...  infon       infon
</code>```

I'm using this code line

```<code>dt_info$new_col <- apply(dt_info[2],1, function(x){
ifelse(x != "n/a", x, "")})
</code>```

That kinda do what I want but I have two issues
I'm not able to go do it for each column using [1:n]
If I change Manually the [] index and run the code, the whole column got replaced.

What am I lacking in my script?
Is there another way to achieve what I'm trying to do?

答:
You were close, the apply function takes a MARGIN = argument, when you set it to MARGIN = 1 you can apply your functions to rows - so you do not need to pass your indices. What happens when you use ifelse is that you get a vector of length = ncol(dt_info) which you try to assign to an entry of length = 1. To avoid it you need to collpase it into a single value -  the name or "" :

```<code>    dt_info$new_col <- apply(dt_info,1, function(x){
                                                    if(sum(x != "n/a")){
                                                        x[x!="n/a"]
                                                    }else{
                                                     ""
                                                    }})
</code>```

Body:
I have a data.frame dt_info that looks like the following:

date       col_1     col_2    col_3  ... col_100
d/m/y       info1     n/a      n/a   ...  n/a
d/m/y       n/a       n/a     info2  ...  n/a
d/m/y       n/a       n/a       n/a  ...  infon

The output I'm looking for should be like this:

date       col_1     col_2    col_3  ... col_100    new_col
d/m/y       info1     n/a      n/a   ...  n/a         info1
d/m/y       n/a       n/a     info2  ...  n/a         info2
d/m/y       n/a       n/a       n/a  ...  infon       infon

I'm using this code line

dt_info$new_col <- apply(dt_info[2],1, function(x){
ifelse(x != "n/a", x, "")})

That kinda do what I want but I have two issues
I'm not able to go do it for each column using [1:n]
If I change Manually the [] index and run the code, the whole column got replaced.

What am I lacking in my script?
Is there another way to achieve what I'm trying to do?

Body:
You were close, the apply function takes a MARGIN = argument, when you set it to MARGIN = 1 you can apply your functions to rows - so you do not need to pass your indices. What happens when you use ifelse is that you get a vector of length = ncol(dt_info) which you try to assign to an entry of length = 1. To avoid it you need to collpase it into a single value -  the name or "" :

    dt_info$new_col <- apply(dt_info,1, function(x){
                                                    if(sum(x != "n/a")){
                                                        x[x!="n/a"]
                                                    }else{
                                                     ""
                                                    }})


问:
Does Scipy recognize the special structure of this matrix to decompose it faster?
I have a matrix whose many rows are already in the upper triangular form. I would like to ask if the command scipy.linalg.lu recognize this special structure to faster decompose it. If I decompose this matrix on paper, I only use Gaussian elimination on those rows that are not in the upper triangular form. For example, I will only make transformations on the last row of matrix B.

```<code>import numpy as np
A = np.array([[2, 5, 8, 7, 8],
              [5, 2, 2, 8, 9],
              [7, 5, 6, 6, 10],
              [5, 4, 4, 8, 10]])
B = np.array([[2, 5, 8, 7, 8],
              [0, 2, 2, 8, 9],
              [0, 0, 6, 6, 10],
              [5, 4, 4, 8, 10]])
</code>```

Because my square matrix is of very large dimension and this procedure is repeated thousands of times. I would like to make use of this special structure to reduce the computational complexity.

Thank you so much for your elaboration!

答:
Not automatically.

You'll need to use the structure yourself if want to. Whether you can make it faster then the built-in implementation depends on many factors (the number of zeros etc)

Body:
I have a matrix whose many rows are already in the upper triangular form. I would like to ask if the command scipy.linalg.lu recognize this special structure to faster decompose it. If I decompose this matrix on paper, I only use Gaussian elimination on those rows that are not in the upper triangular form. For example, I will only make transformations on the last row of matrix B.

import numpy as np
A = np.array([[2, 5, 8, 7, 8],
              [5, 2, 2, 8, 9],
              [7, 5, 6, 6, 10],
              [5, 4, 4, 8, 10]])
B = np.array([[2, 5, 8, 7, 8],
              [0, 2, 2, 8, 9],
              [0, 0, 6, 6, 10],
              [5, 4, 4, 8, 10]])

Because my square matrix is of very large dimension and this procedure is repeated thousands of times. I would like to make use of this special structure to reduce the computational complexity.

Thank you so much for your elaboration!


问:
Redux Thunk Submit to Action
I been stuck to this quite a bit, I am trying to pass in my state to the redux but it seems like I am doing it wrong.

This are my code:

This is my submit function

```<code> popForm() {
    let states = this.state.orders;
    let d = states.filter((data) => {
      return data !== null && data !== undefined
    });
    // console.log("d",d);

    this.props.LogInClick(d);
    // LogInClick(state);
  }

</code>```

This is my mapToDispatch

```<code>const mapDispatchToProps = (dispatch) => {
  return {
    LogInClick : (data) => dispatch(Actions.addDynamic(data)),
  }
}
</code>```

Action call

```<code>export const addDynamic = ({data}) => {
    console.log("Manage to get to here");
    console.log("dataInAction",data);

}
</code>```

My reducer

```<code>case Actions.ADD_DYNAMIC: {
            return {
                ...state,
                data: action.payload
            };
        }
</code>```

答:
Your synchronous action should to return an object with type and payload.

When dealing with async actions, you need thunk(or saga etc) middleware. Your code seem to dispatch normal action (not async). So just make sure that your action returns type and payload.

Like this

export const addDynamic = ({data}) => {
    console.log("Manage to get to here");
    console.log("dataInAction",data);
    return {
        type: Action.ADD_DYNAMIC,
        payload: data
    }

}
```

Title: Redux Thunk Submit to Action

Body:
I been stuck to this quite a bit, I am trying to pass in my state to the redux but it seems like I am doing it wrong.

This are my code:

This is my submit function

 popForm() {
    let states = this.state.orders;
    let d = states.filter((data) => {
      return data !== null && data !== undefined
    });
    // console.log("d",d);

    this.props.LogInClick(d);
    // LogInClick(state);
  }

This is my mapToDispatch

const mapDispatchToProps = (dispatch) => {
  return {
    LogInClick : (data) => dispatch(Actions.addDynamic(data)),
  }
}

Action call

export const addDynamic = ({data}) => {
    console.log("Manage to get to here");
    console.log("dataInAction",data);

}

My reducer

case Actions.ADD_DYNAMIC: {
            return {
                ...state,
                data: action.payload
            };
        }


问:
Difference between dynamically allocated arrays and static arrays
I am getting an introduction to dynamic memory allocation, and I learned that a dynamic array ( the one like int *p = new int[n] \\ where n is the user input describing the number of elements is used when you do not know how many elements the user requires/ declaring an array of a size that the user wants. However, instead of doing that, why can't we declare a static array like this:

```<code>int n;
    cout << "Enter the size : " <<endl;
    cin>>n;
    int a[n];
</code>```

What is the advantage of dynamic arrays in this case then? I am not understanding this concept.

Edit : Thanks for your answers. Some users responded by saying that declaring an array by typing a[n] is not allowed. However, why does my program run fine when I type the following code :

```<code>int main(){
    int n;
    cout << "Enter the size : " <<endl;
    cin>>n;
    int a[n];
    cout << "Enter your numbers : " <<endl;
    for (int i=0;i<=n;i++){
        cin>>a[i];
    }
    for (int i=0;i<=n;i++){
        cout<<a[i]<<endl;
    }
}
</code>```

答:
Now, people have already stated that int a[n] is not valid c++. But Perhaps I could help you with the answer you're looking for.

What is the advantage of dynamic arrays in this case then?

The syntax int a[n] is called a VLA (Variable Length Array). These are illegal in C++ but allowed in C. So let's focus on the technical differences, or rather disadvantages of VLAs.

Let's get the obvious thing out of the way first. C89 and before did not have VLA and hence dynamic allocation was the only way for allocating variable length memory.

One more thing, static arrays and even VLAs are allocated on the stack (although this is implementation defined, but more often than not, it will be on the stack). Whereas dynamic arrays are allocated on the heap. For more information on the stack and the heap, read this

Now, VLAs are banned in C++ for a very good reason. VLAs can cause all sorts of undefined behaviours and should always be avoided unless you know exactly what you're doing. And by "you know exactly what you're doing", I mean you know that the size argument of that VLA will not overflow the stack.

Suppose VLAs were allowed in C++, this line in your code-

cin>>n;
int a[n];
```

What if the user enters a massive n, way more than the stack size? That's a guaranteed stack overflow. Notice the problem? As compared to the heap, the stack is very tiny. This is also explained here and also here

And this is the primary reason VLAs should be avoided at all costs. Though VLAs actually come with much more boom than the aforementioned. Infact I always keep a list of UBs associated with VLAs handy, there just is that many problems.

So going back to my point of

[VLAs] should always be avoided unless you know exactly what you're doing

Honestly, you should never use VLAs, and you really can't because that's not even standard C++. But stack allocation is often faster than heap allocation. Though not for reasons one might consider obvious. Read this. So sometimes, if you're on C (not C++), the only times using a VLA is safe is when you know the max size of n in int a[n] will not overflow the stack and the declaration of the VLA is at the top of the scope you are currently declaring it at. The creator of alloca (which used to be the only way to use VLA prior to c99) seems to agree.

Excerpt from here-

You may use alloca() in the form of:

pointer_variable = alloca(expression);

as an expression statement in the outermost block of a function.

Oh and just to answer your edit:

Thanks for your answers. Some users responded by saying that declaring an array by typing a[n] is not allowed. However, why does my program run fine when I type the following code :

It's because your compiler allows it. But remember, the standard does not. So these kinds of things can give birth to the good ol' "It worked on my machine!"

Body:
I am getting an introduction to dynamic memory allocation, and I learned that a dynamic array ( the one like int *p = new int[n] \\ where n is the user input describing the number of elements is used when you do not know how many elements the user requires/ declaring an array of a size that the user wants. However, instead of doing that, why can't we declare a static array like this:

int n;
    cout << "Enter the size : " <<endl;
    cin>>n;
    int a[n];

What is the advantage of dynamic arrays in this case then? I am not understanding this concept.

Edit : Thanks for your answers. Some users responded by saying that declaring an array by typing a[n] is not allowed. However, why does my program run fine when I type the following code :

int main(){
    int n;
    cout << "Enter the size : " <<endl;
    cin>>n;
    int a[n];
    cout << "Enter your numbers : " <<endl;
    for (int i=0;i<=n;i++){
        cin>>a[i];
    }
    for (int i=0;i<=n;i++){
        cout<<a[i]<<endl;
    }
}

Body:
Now, people have already stated that int a[n] is not valid c++. But Perhaps I could help you with the answer you're looking for.

What is the advantage of dynamic arrays in this case then?

The syntax int a[n] is called a VLA (Variable Length Array). These are illegal in C++ but allowed in C. So let's focus on the technical differences, or rather disadvantages of VLAs.

Let's get the obvious thing out of the way first. C89 and before did not have VLA and hence dynamic allocation was the only way for allocating variable length memory.

One more thing, static arrays and even VLAs are allocated on the stack (although this is implementation defined, but more often than not, it will be on the stack). Whereas dynamic arrays are allocated on the heap. For more information on the stack and the heap, read this

Now, VLAs are banned in C++ for a very good reason. VLAs can cause all sorts of undefined behaviours and should always be avoided unless you know exactly what you're doing. And by "you know exactly what you're doing", I mean you know that the size argument of that VLA will not overflow the stack.

Suppose VLAs were allowed in C++, this line in your code-

cin>>n;
int a[n];

What if the user enters a massive n, way more than the stack size? That's a guaranteed stack overflow. Notice the problem? As compared to the heap, the stack is very tiny. This is also explained here and also here

And this is the primary reason VLAs should be avoided at all costs. Though VLAs actually come with much more boom than the aforementioned. Infact I always keep a list of UBs associated with VLAs handy, there just is that many problems.

So going back to my point of

[VLAs] should always be avoided unless you know exactly what you're doing

Honestly, you should never use VLAs, and you really can't because that's not even standard C++. But stack allocation is often faster than heap allocation. Though not for reasons one might consider obvious. Read this. So sometimes, if you're on C (not C++), the only times using a VLA is safe is when you know the max size of n in int a[n] will not overflow the stack and the declaration of the VLA is at the top of the scope you are currently declaring it at. The creator of alloca (which used to be the only way to use VLA prior to c99) seems to agree.

Excerpt from here-

You may use alloca() in the form of:

pointer_variable = alloca(expression);

as an expression statement in the outermost block of a function.

Oh and just to answer your edit:

Thanks for your answers. Some users responded by saying that declaring an array by typing a[n] is not allowed. However, why does my program run fine when I type the following code :

It's because your compiler allows it. But remember, the standard does not. So these kinds of things can give birth to the good ol' "It worked on my machine!"


答:
uniq() is a lodash method, not a method on array.

_(this.fragor).map('tags').uniq().value()

Your way is wrong because lodash doesn't modify prototypes. Hope this might be helpful.

Title: How can I get all unique tags from an array with lodash?

Body:
Im using Vuejs and lodash and particular lodash to try and get all uniqe tags for question in my very simple questions "app". But for some reason lodash returs all of the tags, not the uniqe ones. This is how I have design the array of questions and tags (might be a better way but dunno).

created() {
  this.tags = _.chain(this.fragor).map('tags').uniq().value()
},
data: function() {
    return {
        tags:[],
        fragor:[
        {
            'fraga': "Question 1",
            'svar' : "This is this explanation",
            'tags' : ['knowledge'],
        },
        {
            'fraga': "Question 2",
            'svar' : "This is this explanation for question 2",
            'tags' : ['knowledge', 'code'],
        },
        {
            'fraga': "Question 3",
            'svar' : "This is this explanation for question 3",
            'tags' : ['code'],
        }
        ]
    }
}

tags is return [ "knowledge" ] [ "knowledge", "code" ] [ "code" ] when the expected result should be ['knowledge', 'code']. How can i achive this with lodash and vue?

I made a jsfiddle for you guys.


问:
support vector machines - a simple explanation?
So, i'm trying to understand how the SVM algorithm works but i just cannot figure out how you transform some datasets in points of n-dimensional plane that would have a mathematical meaning in order to separate the points through a hyperplane and clasify them.

There's an example here, they are trying to clasify pictures of tigers and elephants, they say "We digitize them into 100x100 pixel images, so we have x in n-dimensional plane, where n=10,000", but my question is how do they transform the matrices that actually represent just some color codes IN points that have a methematical meaning in order to clasify them in 2 categories?

Probably someone can explain me this in a 2D example because any graphical representation i see it's just 2D, not nD.

答:
The short answer is: they don't transform the matrices, but treat each element in the matrix as a dimension (in machine learning each element would be called a Feature).
Thus, they need classify elements with 100x100 = 10000 features each. In the linear SVM case, they do so using a hyperplane, which divides the 10,000-dimensional space into two distinct regions.

A longer answer would be:
Consider your 2D case. Now, you want to separate a set of two-dimensional elements. This means that each element in your set can be described mathematically as a 2-tuple, namely: e = (x1, x2). For example, in your figure, some full dots might be: {(1,3), (2,4)}, and some hollow ones might be {(4,2), (5,1)}. Note that in order to classify them with a linear classifier, you need a 2-dimensional linear classifier, which would yield a decision rule which might look like this:

e = (x1, x2)

if (w1 * x1 + w2 * x2) > C : decide that e is a full dot.

otherwise : e is hollow.

Note that the classifier is linear, as it is a linear combination of the elements of e. The 'w's are called 'weights', and 'C' is the decision threshold. a linear function with 2-elements as above is simply a line, that's why in your figures the H's are lines.

Now, back to our n-dimensional case, you can probably figure our that a line will not do the trick. In the 3D case, we would need a plane: (w1 * x1 + w2 * x2 + w2 * x3) > C, and in the n-dimensional case, we would need a hyperplane: (w1 * x1 + w2 * x2 + ... + wn * xn) > C, which is damn hard to imagine, none the less to draw :-).


问:
Networkx node positioning in a complete graph
I want to draw an undirected, weighted, and complete graph with networkx library. My aim is to draw this graph in a way that edge weights represent the distance between nodes.

For example, consider the set of nodes and edges below:

A, B, weight = 5.0

A, C, weight = 50.0

B, C, weight = 0.5

In this case, the distance between A-C is the smallest and B-C is the largest.

I was able to draw this with (after adding edges and nodes to G)

nx.draw(G, pos=None)

but, as the number of nodes gets bigger (above 6), inconsistencies occur. What I mean by this is that some nodes get closer although the weight of the edge connecting them is very low.

I assume some of the node positions don't get updated after some point, but I am not sure.

Any suggestions ?

答:
You can generate the layout of the graph, and compute distances based on the layout. Then, you can assign 1/distance as edge weight. Close edges will have stronger connections, edges that are further away will have fainter connections.

```<code>import networkx as nx
import numpy as np
import matplotlib.pyplot as plt

G = nx.complete_graph(15)

# generate positions
pos = nx.spring_layout(G)

# calculate distances and store as weights
from scipy.spatial.distance import euclidean
edge_updates = {}
edge_widths = []
for (a,b,_) in G.edges(data=True):
    distance = euclidean(pos[a], pos[b])
    edge_updates[a,b] = {'distance': distance}
    edge_widths.append(1/distance)
nx.set_edge_attributes(G, edge_updates)

nx.draw_networkx_nodes(G, pos=pos)
a = nx.draw_networkx_edges(G, pos=pos, edge_cmap=plt.cm.magma, width=edge_widths)
</code>```

Body:
You can generate the layout of the graph, and compute distances based on the layout. Then, you can assign 1/distance as edge weight. Close edges will have stronger connections, edges that are further away will have fainter connections.

import networkx as nx
import numpy as np
import matplotlib.pyplot as plt

G = nx.complete_graph(15)

# generate positions
pos = nx.spring_layout(G)

# calculate distances and store as weights
from scipy.spatial.distance import euclidean
edge_updates = {}
edge_widths = []
for (a,b,_) in G.edges(data=True):
    distance = euclidean(pos[a], pos[b])
    edge_updates[a,b] = {'distance': distance}
    edge_widths.append(1/distance)
nx.set_edge_attributes(G, edge_updates)

nx.draw_networkx_nodes(G, pos=pos)
a = nx.draw_networkx_edges(G, pos=pos, edge_cmap=plt.cm.magma, width=edge_widths)


问:
Incompatible Recaptcha V2 with IE
I have tried adding meta tag to the header :

But it didn't work.

I tried this option, still didn't work infact there is no google.com present inside compatible view.

Could anyone help me out?

```<code><!DOCTYPE html> <html lang="en"> <head> <title>How to Integrate Google “No CAPTCHA reCAPTCHA” on Your Website</title> <script src='google.com/recaptcha/api.js'></script> </head> <body> <form action="" method="post"> <label for="name">Name:</label> <input name="name" required><br /> <label for="email">Email:</label> <input name="email" type="email" required><br /> <div class="g-recaptcha" data-sitekey="###"></div> <input type="submit" value="Submit" /> </form>
</code>```

答:
Actually it was loading  loading first time in IE. So, I tried with making url different everytime by appending current datetime.

"https://www.google.com/recaptcha/api.js?render=" + EncodeUrl(SiteKey) + "&time="+CurrTime()

It started working.

Title: Incompatible Recaptcha V2 with IE

Body:
I have tried adding meta tag to the header :

But it didn't work.

I tried this option, still didn't work infact there is no google.com present inside compatible view.

Could anyone help me out?

<!DOCTYPE html>   <title>How to Integrate Google “No CAPTCHA reCAPTCHA” on Your Website</title>    <form action="" method="post"> Name: <input name="name" required>
 Email: <input name="email" type="email" required>

 <input type="submit" value="Submit" /> </form>


问:
getDatabase called recursively using Room
I am getting an error when I try initialize my database. I am using Android Room and I want use the RoomDatabaseBuilder to execute the callback and fill my database.

I execute getDatabase method in my Activity class, but then I use the dao to get info from database and the app crashes. It is my first contact with Android Room maybe I am forgeting some important to do. Any can help me with this?

Database Class:

```<code>static RoomDatabase.Callback rdc = new RoomDatabase.Callback() {

    @Override
    public void onOpen(@NonNull SupportSQLiteDatabase db) {
        super.onOpen(db);
        Log.d(TAG, "Debug: onOpen");

        //Borramos todos los sonidos de la base de datos
        INSTANCE.soundsDao().deleteAllSounds(); // Instance is "private static DatabaseSounds INSTANCE;"
</code>```

Activity line source of crash:

```<code>db = DatabaseSounds.getDatabase(getApplicationContext());
   AsyncTask task = new LoadGridAsyncTask().execute(); **

   private class LoadGridAsyncTask extends AsyncTask<Void, Void, Integer> {

        @Override
        protected Integer doInBackground(Void... voids) {
            //Extraemos el listado de sonidos y los convertimos a DTO
            List<EntitySounds> listSounds = db.soundsDao().getAll(); **** THIS is the line of crash
</code>```

This is the error

```<code>java.lang.RuntimeException: An error occurred while executing doInBackground()
        at android.os.AsyncTask$3.done(AsyncTask.java:325)
        at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
        at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
        at java.util.concurrent.FutureTask.run(FutureTask.java:242)
        at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:243)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
        at java.lang.Thread.run(Thread.java:761)
     Caused by: java.lang.IllegalStateException: getDatabase called recursively
        at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:203)
        at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:163)
        at android.arch.persistence.db.framework.FrameworkSQLiteOpenHelper$OpenHelper.getWritableSupportDatabase(FrameworkSQLiteOpenHelper.java:96)
        at android.arch.persistence.db.framework.FrameworkSQLiteOpenHelper.getWritableDatabase(FrameworkSQLiteOpenHelper.java:54)
        at android.arch.persistence.room.RoomDatabase.compileStatement(RoomDatabase.java:244)
        at android.arch.persistence.room.SharedSQLiteStatement.createNewStatement(SharedSQLiteStatement.java:65)
        at android.arch.persistence.room.SharedSQLiteStatement.getStmt(SharedSQLiteStatement.java:72)
        at android.arch.persistence.room.SharedSQLiteStatement.acquire(SharedSQLiteStatement.java:87)
        at com.genaut.myapp.database.dao.DaoSounds_Impl.deleteAllSounds(DaoSounds_Impl.java:140)
        at com.genaut.myapp.database.DatabaseSounds$1.onOpen(DatabaseSounds.java:57)
        at com.genaut.myapp.database.DatabaseSounds_Impl$1.onOpen(DatabaseSounds_Impl.java:65)
        at android.arch.persistence.room.RoomOpenHelper.onOpen(RoomOpenHelper.java:111)
        at android.arch.persistence.db.framework.FrameworkSQLiteOpenHelper$OpenHelper.onOpen(FrameworkSQLiteOpenHelper.java:149)
        at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:266)
        at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:163)
        at android.arch.persistence.db.framework.FrameworkSQLiteOpenHelper$OpenHelper.getWritableSupportDatabase(FrameworkSQLiteOpenHelper.java:96)
        at android.arch.persistence.db.framework.FrameworkSQLiteOpenHelper.getWritableDatabase(FrameworkSQLiteOpenHelper.java:54)
        at android.arch.persistence.room.RoomDatabase.query(RoomDatabase.java:233)
        at com.genaut.myapp.database.dao.DaoSounds_Impl.getAll(DaoSounds_Impl.java:155)
        at com.genaut.myapp.Home$LoadGridAsyncTask.doInBackground(Home.java:83)
        at com.genaut.myapp.Home$LoadGridAsyncTask.doInBackground(Home.java:78)
        at android.os.AsyncTask$2.call(AsyncTask.java:305)
        at java.util.concurrent.FutureTask.run(FutureTask.java:237)
        at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:243)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
        at java.lang.Thread.run(Thread.java:761)
</code>```

This is the Dao method:

```<code>@Query("SELECT * FROM entitysounds")
    List<EntitySounds> getAll();
</code>```

答:
run it in a new separate thread</p>

```<code>Executors.newSingleThreadExecutor().execute {
    INSTANCE.soundsDao().deleteAllSounds();
}
</code>```

Body:
I am getting an error when I try initialize my database. I am using Android Room and I want use the RoomDatabaseBuilder to execute the callback and fill my database.

I execute getDatabase method in my Activity class, but then I use the dao to get info from database and the app crashes. It is my first contact with Android Room maybe I am forgeting some important to do. Any can help me with this?

Database Class:

static RoomDatabase.Callback rdc = new RoomDatabase.Callback() {

    @Override
    public void onOpen(@NonNull SupportSQLiteDatabase db) {
        super.onOpen(db);
        Log.d(TAG, "Debug: onOpen");

        //Borramos todos los sonidos de la base de datos
        INSTANCE.soundsDao().deleteAllSounds(); // Instance is "private static DatabaseSounds INSTANCE;"

Activity line source of crash:

db = DatabaseSounds.getDatabase(getApplicationContext());
   AsyncTask task = new LoadGridAsyncTask().execute(); **

   private class LoadGridAsyncTask extends AsyncTask<Void, Void, Integer> {

        @Override
        protected Integer doInBackground(Void... voids) {
            //Extraemos el listado de sonidos y los convertimos a DTO
            List<EntitySounds> listSounds = db.soundsDao().getAll(); **** THIS is the line of crash

This is the error

java.lang.RuntimeException: An error occurred while executing doInBackground()
        at android.os.AsyncTask$3.done(AsyncTask.java:325)
        at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
        at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
        at java.util.concurrent.FutureTask.run(FutureTask.java:242)
        at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:243)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
        at java.lang.Thread.run(Thread.java:761)
     Caused by: java.lang.IllegalStateException: getDatabase called recursively
        at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:203)
        at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:163)
        at android.arch.persistence.db.framework.FrameworkSQLiteOpenHelper$OpenHelper.getWritableSupportDatabase(FrameworkSQLiteOpenHelper.java:96)
        at android.arch.persistence.db.framework.FrameworkSQLiteOpenHelper.getWritableDatabase(FrameworkSQLiteOpenHelper.java:54)
        at android.arch.persistence.room.RoomDatabase.compileStatement(RoomDatabase.java:244)
        at android.arch.persistence.room.SharedSQLiteStatement.createNewStatement(SharedSQLiteStatement.java:65)
        at android.arch.persistence.room.SharedSQLiteStatement.getStmt(SharedSQLiteStatement.java:72)
        at android.arch.persistence.room.SharedSQLiteStatement.acquire(SharedSQLiteStatement.java:87)
        at com.genaut.myapp.database.dao.DaoSounds_Impl.deleteAllSounds(DaoSounds_Impl.java:140)
        at com.genaut.myapp.database.DatabaseSounds$1.onOpen(DatabaseSounds.java:57)
        at com.genaut.myapp.database.DatabaseSounds_Impl$1.onOpen(DatabaseSounds_Impl.java:65)
        at android.arch.persistence.room.RoomOpenHelper.onOpen(RoomOpenHelper.java:111)
        at android.arch.persistence.db.framework.FrameworkSQLiteOpenHelper$OpenHelper.onOpen(FrameworkSQLiteOpenHelper.java:149)
        at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:266)
        at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:163)
        at android.arch.persistence.db.framework.FrameworkSQLiteOpenHelper$OpenHelper.getWritableSupportDatabase(FrameworkSQLiteOpenHelper.java:96)
        at android.arch.persistence.db.framework.FrameworkSQLiteOpenHelper.getWritableDatabase(FrameworkSQLiteOpenHelper.java:54)
        at android.arch.persistence.room.RoomDatabase.query(RoomDatabase.java:233)
        at com.genaut.myapp.database.dao.DaoSounds_Impl.getAll(DaoSounds_Impl.java:155)
        at com.genaut.myapp.Home$LoadGridAsyncTask.doInBackground(Home.java:83)
        at com.genaut.myapp.Home$LoadGridAsyncTask.doInBackground(Home.java:78)
        at android.os.AsyncTask$2.call(AsyncTask.java:305)
        at java.util.concurrent.FutureTask.run(FutureTask.java:237)
        at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:243)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
        at java.lang.Thread.run(Thread.java:761)

This is the Dao method:

@Query("SELECT * FROM entitysounds")
    List<EntitySounds> getAll();

Body:
run it in a new separate thread

Executors.newSingleThreadExecutor().execute {
    INSTANCE.soundsDao().deleteAllSounds();
}


问:
ng serve error: getaddrinfo ENOTFOUND localhost
I was getting this error:

```<code>getaddrinfo ENOTFOUND localhost
Error: getaddrinfo ENOTFOUND localhost
    at errnoException (dns.js:28:10)
    at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:76:26)
</code>```

when running ng serve. After web lookup, the proposed answer to this problem is to run this command instead:

```<code>ng serve --port 4200 --host 0.0.0.0
</code>```

Unfortunately, the instructions came without explanation.

This works and the Angular project compiled successfully. I am not sure why. Can someone explain why this works and what has happened in the background? Thanks

答:
The issue for me was the host entry:

Since I was on MAC
I cmd+space bar type terminal
then

```<code>sudo nano /private/etc/hosts
</code>```

add the localhost entry
^ + O to save  and
^ + x to exit

and then my problem was resolved

Body:
I was getting this error:

getaddrinfo ENOTFOUND localhost
Error: getaddrinfo ENOTFOUND localhost
    at errnoException (dns.js:28:10)
    at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:76:26)

when running ng serve. After web lookup, the proposed answer to this problem is to run this command instead:

ng serve --port 4200 --host 0.0.0.0

Unfortunately, the instructions came without explanation.

This works and the Angular project compiled successfully. I am not sure why. Can someone explain why this works and what has happened in the background? Thanks

Body:
The issue for me was the host entry:

Since I was on MAC
I cmd+space bar type terminal
then

sudo nano /private/etc/hosts

add the localhost entry
^ + O to save  and
^ + x to exit

and then my problem was resolved


问:
Oracle Regular Expression for Date
I have the following anonymous block. I've written a small regular expression to accept the date. It is able to validate the day, month, and year.
Now I want to consider the only century year, and regexp should also allow year in RR format (Century year). Also, I want to accept a day without a zero in the prefix; currently, it is accepting this for the month only. Please see the scenarios below:

```<code>> 01/12/2154 (Do not accept, It's not a century year)
> 11/12/1996 (Do not accept, It's not a century year)
> 11/2/24 (Accept, and a plsql logic in IF condition could change it to 2024; Add 20 to it)
> 1/9/2020 (Accept)
> 01/02/2020 (Accept)
> 1/29/20 (Accept)
> 01/11/25 (Accept)
> 1/09/2021 (Accept)
</code>```

**

```<code>declare
date_v varchar2(40):= '01/01/2025';
date_n date;
begin
if regexp_like (date_v, '([0-9]|1[0-2])/([0-2][0-9]|3[0-1])/[0-9]{4}') then
-- logic
date_n:= TO_DATE(date_v,'MM/DD/YYYY');
dbms_output.put_line(date_n);
end if;
end;
</code>```

答:
Date validation with regular expression is difficult, very difficult. THr problem being that months have differing number of days, and 29-Feb is valid only in certain years. Your request is to have multiple valid formats greatly compounding.

The following function validates dates in the ISO-8601 format (YYYY-MM-DD), and only that format, but it does validate the correct number of days in each month for the dates 0001-01-01 through 9999-12-31, including leap days (29-Feb) when valid. but again just 1 format. Recommendation do not try validating dates with regular expression, esp multiple formats.

```<code>create or replace function valid_iso_date (iso_date_string varchar2)
   return date
is
   iso_date_pattern constant varchar2(256) :=
       '^((0[0-9]{2}[1-9]|[1-9][0-9]{3})-((0[13578]|10|12)-(0[1-9]|[12][0-9]|3[01])|02-(0[1-9]|1[0-9]|2[0-8])|(0[469]|11)-(0[1-9]|[12][0-9]|30))$)|^(\d\d(0[48]|[2468][048]|[13579][26])-02-29$)';

   result_date date := null;
begin
   if regexp_like(iso_date_string, iso_data_pattern)
   then
      result_date := to_date(iso_date_string,'yyyy-mm-dd');
   end if;
   return result_date;
end valid_iso_date;
</code>```

Title: Oracle Regular Expression for Date

Body:
I have the following anonymous block. I've written a small regular expression to accept the date. It is able to validate the day, month, and year.
Now I want to consider the only century year, and regexp should also allow year in RR format (Century year). Also, I want to accept a day without a zero in the prefix; currently, it is accepting this for the month only. Please see the scenarios below:

> 01/12/2154 (Do not accept, It's not a century year)
> 11/12/1996 (Do not accept, It's not a century year)
> 11/2/24 (Accept, and a plsql logic in IF condition could change it to 2024; Add 20 to it)
> 1/9/2020 (Accept)
> 01/02/2020 (Accept)
> 1/29/20 (Accept)
> 01/11/25 (Accept)
> 1/09/2021 (Accept)

**

declare
date_v varchar2(40):= '01/01/2025';
date_n date;
begin
if regexp_like (date_v, '([0-9]|1[0-2])/([0-2][0-9]|3[0-1])/[0-9]{4}') then
-- logic
date_n:= TO_DATE(date_v,'MM/DD/YYYY');
dbms_output.put_line(date_n);
end if;
end;

Body:
Date validation with regular expression is difficult, very difficult. THr problem being that months have differing number of days, and 29-Feb is valid only in certain years. Your request is to have multiple valid formats greatly compounding.

The following function validates dates in the ISO-8601 format (YYYY-MM-DD), and only that format, but it does validate the correct number of days in each month for the dates 0001-01-01 through 9999-12-31, including leap days (29-Feb) when valid. but again just 1 format. Recommendation do not try validating dates with regular expression, esp multiple formats.

create or replace function valid_iso_date (iso_date_string varchar2)
   return date
is
   iso_date_pattern constant varchar2(256) :=
       '^((0[0-9]{2}[1-9]|[1-9][0-9]{3})-((0[13578]|10|12)-(0[1-9]|[12][0-9]|3[01])|02-(0[1-9]|1[0-9]|2[0-8])|(0[469]|11)-(0[1-9]|[12][0-9]|30))$)|^(\d\d(0[48]|[2468][048]|[13579][26])-02-29$)';

   result_date date := null;
begin
   if regexp_like(iso_date_string, iso_data_pattern)
   then
      result_date := to_date(iso_date_string,'yyyy-mm-dd');
   end if;
   return result_date;
end valid_iso_date;


问:
url shortening in python
I am trying to find the simplest way to shorten my URLs using python 3. The libraries that I have seen so far are outdated and no longer maintained. People will see these URLs so I want to use something trustworthy like tinyurl or bit.ly or goog.gl

Given a URL, how can I pass it into a function that will shorten it?

What is the best way to programmatically shorten URLs in 2020?

答:
Try this script.

http://code.activestate.com/recipes/576918/

Usage:

```<code>>>> import short_url
>>> url = short_url.encode_url(12)
>>> print url
LhKA
>>> key = short_url.decode_url(url)
>>> print key
12
</code>```

Title: url shortening in python

Body:
Try this script.

http://code.activestate.com/recipes/576918/

Usage:

>>> import short_url
>>> url = short_url.encode_url(12)
>>> print url
LhKA
>>> key = short_url.decode_url(url)
>>> print key
12


问:
Next.js: one page that match root '/' and dynamic route '/param'
I have a website as a single page that is using Next.js. I have the home page on route / that show a list of products. The code of this page is located in pages/index.js. Each product has an id so I can jump to it using /#product-id.

To make it more url friendly I replicate this behaviour using the product-id as a second param in the route like that: /product-id.

What I do is simply looking on the product-id param using useRouter():

const selectedProductId = useRouter().query['product-id']
```

<p>And then scroll to the element with this id using <code>js</code>:</p>

<pre class="lang-js prettyprint-override"><code>document.getElementById(selectedProductId ).scrollIntoView()
</code>```

So I to change my script name from /pages/index.js to /pages/[product-id].js.

So now the route /1234 work has expected but if I go to / I get error 404.

So has someone an idea how I can match / and /param using one js file?

答:
Option 1: Extract the shared code

You could extract a Page component to a separate file and then import it in both /pages/index.js and /pages/[product-id].js, so the code is not duplicated.

Option 2: Use experimental rewrites feature

Assuming you have /pages/[product-id].js you can show this page when a user requests /.

You would need to add next.config.js.

```<code>module.exports = {
  experimental: {
    async rewrites() {
      return [
        { source: "/", destination: "/[product-id]" },
      ];
    }
  }
}
</code>```

So, when a user requests / they would see the content of /[product-id], just with the empty product id.

Note, that at the moment rewrite doesn't support auto-rendered dynamic pages, so you have to disable auto-rendering for the dynamic page.

You can do that by adding getServerSideProps to /pages/[product-id].js.

```<code>export async function getServerSideProps() {
  return {
    props: {},
  }
}
</code>```

Body:
I have a website as a single page that is using Next.js. I have the home page on route / that show a list of products. The code of this page is located in pages/index.js. Each product has an id so I can jump to it using /#product-id.

To make it more url friendly I replicate this behaviour using the product-id as a second param in the route like that: /product-id.

What I do is simply looking on the product-id param using useRouter():

const selectedProductId = useRouter().query['product-id']

And then scroll to the element with this id using js:

document.getElementById(selectedProductId ).scrollIntoView()

So I to change my script name from /pages/index.js to /pages/[product-id].js.

So now the route /1234 work has expected but if I go to / I get error 404.

So has someone an idea how I can match / and /param using one js file?

Body:
Option 1: Extract the shared code

You could extract a Page component to a separate file and then import it in both /pages/index.js and /pages/[product-id].js, so the code is not duplicated.

Option 2: Use experimental rewrites feature

Assuming you have /pages/[product-id].js you can show this page when a user requests /.

You would need to add next.config.js.

module.exports = {
  experimental: {
    async rewrites() {
      return [
        { source: "/", destination: "/[product-id]" },
      ];
    }
  }
}

So, when a user requests / they would see the content of /[product-id], just with the empty product id.

Note, that at the moment rewrite doesn't support auto-rendered dynamic pages, so you have to disable auto-rendering for the dynamic page.

You can do that by adding getServerSideProps to /pages/[product-id].js.

export async function getServerSideProps() {
  return {
    props: {},
  }
}


问:
c++ std::future is not getting called
I am working with std::async and std::future in c++, but am having a bit of trouble.
When I run this code, i expect to see (in the stdout) "hello world" but, instead I get nothing:

```<code>#include <iostream>
#include <future>
using namespace std;

struct A {
  future<string>* test;
};

string getStr() {
  return "hello world";
}

A callA() {

  future<string> a = async(&getStr);

  return A{ &a };
}

int main() {
  A a = callA();
  cout << a.test->get() << endl;
}

</code>```

I am using a pointer to a future because in my real program, i have another struct in place of the std::string:

```<code>struct A;
struct B;

typedef struct A {
  future<B>* b;
} A;

typedef struct B {
  A a;
} B;
</code>```

and even if i don't use a pointer it will give me this error:

```<code>error: use of deleted function 'std::future<_Res>::future(const std::future<_Res>&) [with _Res = std::__cxx11::basic_string<char>]'
</code>```

(For the above error, i know that i can use std::move to fix it as seen here, but i need to use the pointer)

So how can i actually get the output of "hello world" from this program?

答:
you use a pointer to a temporary object. the temporary object is destroyed at the exit of the function. so you can move your future object to your struct:

```<code>#include <iostream>
#include <future>
using namespace std;

struct A {
  future<string> test;
};

string getStr() {
  return "hello world";
}

A callA() {

  future<string> a = async(&getStr);

  return A{ std::move(a) };
}

int main() {
  A a = callA();
  cout << a.test.get() << endl;
}
</code>```

if for some reason you have to use a pointer - then you should prolong the lifetime of your future. (e.g. add the future to a container and later remove from it after the usage of the future)

Title: c++ std::future is not getting called

Body:
I am working with std::async and std::future in c++, but am having a bit of trouble.
When I run this code, i expect to see (in the stdout) "hello world" but, instead I get nothing:

#include <iostream>
#include <future>
using namespace std;

struct A {
  future<string>* test;
};

string getStr() {
  return "hello world";
}

A callA() {

  future<string> a = async(&getStr);

  return A{ &a };
}

int main() {
  A a = callA();
  cout <get() << endl;
}

I am using a pointer to a future because in my real program, i have another struct in place of the std::string:

struct A;
struct B;

typedef struct A {
  future* b;
} A;

typedef struct B {
  A a;
} B;

and even if i don't use a pointer it will give me this error:

error: use of deleted function 'std::future<_Res>::future(const std::future<_Res>&) [with _Res = std::__cxx11::basic_string<char>]'

(For the above error, i know that i can use std::move to fix it as seen here, but i need to use the pointer)

So how can i actually get the output of "hello world" from this program?

Body:
you use a pointer to a temporary object. the temporary object is destroyed at the exit of the function. so you can move your future object to your struct:

#include <iostream>
#include <future>
using namespace std;

struct A {
  future<string> test;
};

string getStr() {
  return "hello world";
}

A callA() {

  future<string> a = async(&getStr);

  return A{ std::move(a) };
}

int main() {
  A a = callA();
  cout << a.test.get() << endl;
}

if for some reason you have to use a pointer - then you should prolong the lifetime of your future. (e.g. add the future to a container and later remove from it after the usage of the future)