问:
Sub list of a list in taking the second element
Suppose I have the following list of tuple [("a", "b"); ("c", "d"); ("e", "f"); ("g", "h"); ("i", "j")]. I would like to create a sub list from that list by taking the second element of each tuple of that list. In other words, I want to obtain ["a"; "d"; "f", "h"].

I tried iter (fun (x,y) -> liste@[y]) old_list;; but I got

```<code>Error: This expression has type (string * string) list
       but an expression was expected of type unit
</code>```

Do I have to use a recursive function? Is there a workaround?

答:
The type of List.iter is ('a -> unit) -> 'a list -> unit. In other words, it returns unit, which is the way in OCaml to return nothing (or nothing interesting anyway).

Since you want your function to return a result, you can't use List.iter. Instead, you want to transform each element of a list in some way. The function that does this is List.map.

Here's a function that changes a list of ints into a list of bools according to whether each int is odd or even:

```<code>let is_even list = List.map (fun x -> x mod 2 = 0) list
</code>```

It works like this:

```<code># is_even [3;4;5;6;7];;
- : bool list = [false; true; false; true; false]
</code>```

You want something like this with a different fun expression.

As a side comment, your result isn't what would usually be called a sublist of the original list. A sublist is a new list containing some of the elements of the old list. You could call it a projection more accurately I think.

Body:
Suppose I have the following list of tuple [("a", "b"); ("c", "d"); ("e", "f"); ("g", "h"); ("i", "j")]. I would like to create a sub list from that list by taking the second element of each tuple of that list. In other words, I want to obtain ["a"; "d"; "f", "h"].

I tried iter (fun (x,y) -> liste@[y]) old_list;; but I got

Error: This expression has type (string * string) list
       but an expression was expected of type unit

Do I have to use a recursive function? Is there a workaround?

Body:
The type of List.iter is ('a -> unit) -> 'a list -> unit. In other words, it returns unit, which is the way in OCaml to return nothing (or nothing interesting anyway).

Since you want your function to return a result, you can't use List.iter. Instead, you want to transform each element of a list in some way. The function that does this is List.map.

Here's a function that changes a list of ints into a list of bools according to whether each int is odd or even:

let is_even list = List.map (fun x -> x mod 2 = 0) list

It works like this:

# is_even [3;4;5;6;7];;
- : bool list = [false; true; false; true; false]

You want something like this with a different fun expression.

As a side comment, your result isn't what would usually be called a sublist of the original list. A sublist is a new list containing some of the elements of the old list. You could call it a projection more accurately I think.


来源: stackexchange

问:
How to correctly use axios params with arrays
How to add indexes to array in query string?

I tried send data like this:

```<code>axios.get('/myController/myAction', { params: { storeIds: [1,2,3] })
</code>```

And I got this url:

```<code>http://localhost/api/myController/myAction?storeIds[]=1&storeIds[]=2&storeIds[]=3
</code>```

So, I should to get this url:

```<code>http://localhost/api/myController/myAction?storeIds[0]=1&storeIds[1]=2&storeIds[2]=3
</code>```

What I should add in my params options to get this url?

答:
In my case, I am using someting like this

```<code>const params = array.map((v)=>{
            return `p=${v}&`
        })
</code>```

Only concat params.join('') to the URL where you get data:

```<code>`url_to_get?${params.join('')`
</code>```

In my back-end in ASP.net I receive this

```<code>[FromUri] string [] p
</code>```

ContentLicense: CC BY-SA 3.0

Body:
How to add indexes to array in query string?

I tried send data like this:

axios.get('/myController/myAction', { params: { storeIds: [1,2,3] })

And I got this url:

http://localhost/api/myController/myAction?storeIds[]=1&storeIds[]=2&storeIds[]=3

So, I should to get this url:

http://localhost/api/myController/myAction?storeIds[0]=1&storeIds[1]=2&storeIds[2]=3

What I should add in my params options to get this url?

Body:
In my case, I am using someting like this

const params = array.map((v)=>{
            return `p=${v}&`
        })

Only concat params.join('') to the URL where you get data:

`url_to_get?${params.join('')`

In my back-end in ASP.net I receive this

[FromUri] string [] p

ContentLicense: CC BY-SA 4.0


问:
How do i get the guild ID of a joined user/member (Discord.js)
```<code>client.on("guildMemberAdd", member => {

settingss.findOne({
  guildID: guild.ID // <---- Trying to figure out what i want over here
}, async (err, settings) => {

    var role = member.guild.roles.cache.get(role => role.name === settingss.joinrolename);

    if (!role) return;

    member.roles.add(role);

    const channel = member.guild.channels.cache.get(channel => channel.name === settingss.welcomechannelname);

    if (!channel) return;

    channel.send(`Welcome to the server, ${member}`);

  });

});
</code>```

i cant seem to figuere out how to get guild ID over here.
 I tried guild.memberCount this didnt work either.

答: I think that member.guild.id should do the trick :)

Body:
client.on("guildMemberAdd", member => {

settingss.findOne({
  guildID: guild.ID // <---- Trying to figure out what i want over here
}, async (err, settings) => {

    var role = member.guild.roles.cache.get(role => role.name === settingss.joinrolename);

    if (!role) return;

    member.roles.add(role);

    const channel = member.guild.channels.cache.get(channel => channel.name === settingss.welcomechannelname);

    if (!channel) return;

    channel.send(`Welcome to the server, ${member}`);

  });

});

i cant seem to figuere out how to get guild ID over here.
 I tried guild.memberCount this didnt work either.


问:
Installing the Java ZeroMQ binding (jzmq) using Maven, Missing Native Code Library
I am attempting to install jzmq, the Java ZeroMQ binding, from the Maven repository (http://search.maven.org/#search|ga|1|a%3A%22jzmq%22).  When added as a dependency to my pom.xml[1] Maven downloads the main jar, which provides a Java library, as expected. In addition to the main library, jzmq requires a native code library which Maven does not appear to download. At run time the Java library raises an exception due to the missing native code library.

The native library is provided in the repository and the pom.xml[2] file for jzmq appears to specify that the native library (libjzmq.so) should be downloaded. If I download the library and set the native library location manually it all works, I would however prefer if this could be automated via Maven.

I am unsure as to why Maven is not downloading and installing the native library, any advice or suggestions as to how to resolve this problem would be greatly appreciated.

I am running the latest Ubuntu release using OpenJDK and Apache Maven 3.0.4

[0] The exception that is raised when using jzmq as provided by Maven, sans the crucial native code library.

```<code>Exception in thread "main" java.lang.UnsatisfiedLinkError: no jzmq in java.library.path
    at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1874)
    at java.lang.Runtime.loadLibrary0(Runtime.java:849)
    at java.lang.System.loadLibrary(System.java:1087)
    at org.zeromq.ZMQ.<clinit>(ZMQ.java:39)
</code>```

[1] My pom.xml where jzmq is added as a dependency

```<code><dependency>
<GroupId>org.zeromq</groupId>
<artifactId>jzmq</artifactId>
version>2.2.2</version>
</dependency>
</code>```

[2] The pom.xml for jzmq where the native library is referred to

```<code><profile>
<id>Linux</id>
<activation>
<property>
<name>os.name</name>
<value>Linux</value>
</property></activation>
<properties>
<native.os>${os.name}</native.os>
<native.path>src/.libs/libjzmq.so</native.path>
<!-- Use platform-specific path separators here: -->
<native.library-path>src/.libs/</native.library-path>
</properties>
</profile>
</code>```

答:
Alternatively, if you prefer not to use the native library and you just want to get started quickly you can opt to use the java equivalent of zeromq library by adding below to your pom.xml

```<code> <dependency>
    <groupId>org.zeromq</groupId>
    <artifactId>jeromq</artifactId>
    <version>0.5.2</version>
 </dependency>
</code>```

For more details in the difference you may refer to an answered question here:

For an up to date list of jeromq versions see the mvnrepository here

Body:
I am attempting to install jzmq, the Java ZeroMQ binding, from the Maven repository (http://search.maven.org/#search|ga|1|a%3A%22jzmq%22).  When added as a dependency to my pom.xml[1] Maven downloads the main jar, which provides a Java library, as expected. In addition to the main library, jzmq requires a native code library which Maven does not appear to download. At run time the Java library raises an exception due to the missing native code library.

The native library is provided in the repository and the pom.xml[2] file for jzmq appears to specify that the native library (libjzmq.so) should be downloaded. If I download the library and set the native library location manually it all works, I would however prefer if this could be automated via Maven.

I am unsure as to why Maven is not downloading and installing the native library, any advice or suggestions as to how to resolve this problem would be greatly appreciated.

I am running the latest Ubuntu release using OpenJDK and Apache Maven 3.0.4

[0] The exception that is raised when using jzmq as provided by Maven, sans the crucial native code library.

Exception in thread "main" java.lang.UnsatisfiedLinkError: no jzmq in java.library.path
    at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1874)
    at java.lang.Runtime.loadLibrary0(Runtime.java:849)
    at java.lang.System.loadLibrary(System.java:1087)
    at org.zeromq.ZMQ.<clinit>(ZMQ.java:39)

[1] My pom.xml where jzmq is added as a dependency

<dependency>
<GroupId>org.zeromq</groupId>
<artifactId>jzmq</artifactId>
version>2.2.2</version>
</dependency>

[2] The pom.xml for jzmq where the native library is referred to

<profile>
<id>Linux</id>
<activation>
<property>
<name>os.name</name>
<value>Linux</value>
</property></activation>
<properties>
<native.os>${os.name}</native.os>
<native.path>src/.libs/libjzmq.so</native.path>

<native.library-path>src/.libs/</native.library-path>
</properties>
</profile>

Body:
Alternatively, if you prefer not to use the native library and you just want to get started quickly you can opt to use the java equivalent of zeromq library by adding below to your pom.xml

 <dependency>
    <groupId>org.zeromq</groupId>
    <artifactId>jeromq</artifactId>
    <version>0.5.2</version>
 </dependency>

For more details in the difference you may refer to an answered question here:

For an up to date list of jeromq versions see the mvnrepository here


问:
Optional arguments and InteropServices
I'm using for the firs time optional arguments but I cannot understand difference between those two method definitions:

```<code>private void method1([Optional, DefaultParameterValue(string.Empty)] string testString)
{
    //do something
}

private void method2(string testString = "")
{
    //do something
}
</code>```

definition of method1 needs:

```<code>using System.Runtime.InteropServices;
</code>```

Method2 definition is smaller and needs no import.

Have I to consider something before using one of those method syntax?

答:
Method 1 was present since .NET 1.1.

Method 2 was introduced with C# 4 (C# did not support optional parameters until then).

Title: Optional arguments and InteropServices

Body:
I'm using for the firs time optional arguments but I cannot understand difference between those two method definitions:

private void method1([Optional, DefaultParameterValue(string.Empty)] string testString)
{
    //do something
}

private void method2(string testString = "")
{
    //do something
}

definition of method1 needs:

using System.Runtime.InteropServices;

Method2 definition is smaller and needs no import.

Have I to consider something before using one of those method syntax?


问:
415 Unsupported Media Type Error being returned when posting to API through C# class
I am trying to write a class that will post a json object to an API.  If I post the following through Postman (passing it as raw json), the API responds with a 200:

```<code>[{"Id":"1","Name":"First of Two","obdOdometer":{"Time":"2020-01-01","Value":"112233"}},{"Id":"2","Name":"Second of Two","obdOdometer":{"Time":"2020-02-03","Value":"45506"}}]
</code>```

However, I am getting errors when using my class.

Here is the class I am trying to use:

```<code>        public async Task TransmitobdOdometer(string json)
        {

            string bearerToken = _config.GetSection("PilotTmwApiSettings:BearerToken").Value;

            using (var client = new HttpClient())
            {

                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", bearerToken);
                var res = client.PostAsync("https://localhost:44308/TestDev", new StringContent(Newtonsoft.Json.JsonConvert.SerializeObject( new { json } )));

                try
                {
                    res.Result.EnsureSuccessStatusCode();
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.ToString());
                }
            }

        }
</code>```

The string being passed into TransmitobdOdometer() is formatted like so:

```<code>string odometerValues = "[{\"Id\":\"1\",\"Name\":\"First of Two\",\"obdOdometer\":{\"Time\":\"2020-01-01\",\"Value\":\"112233\"}},{\"Id\":\"2\",\"Name\":\"Second of Two\",\"obdOdometer\":{\"Time\":\"2020-02-03\",\"Value\":\"45506\"}}]";

</code>```

This returns the error message: "Response status code does not indicate success: 415 (Unsupported Media Type)."  I tried adjusting the format of the string being passed in, but I get the same error, so I figured I'd ask for insight into what I may be doing wrong before proceeding further.

答:
Changing the line to </p>

```<code>var res = client.PostAsync("localhost:44308/TestDev", new StringContent(Newtonsoft.Json.JsonConvert.SerializeObject( new { json } ), Encoding.UTF8, "application/json"));
</code>```

<p>... fixed the error 415.  I am still getting an error, but will move that to a new discussion.</p>

Body:
I am trying to write a class that will post a json object to an API.  If I post the following through Postman (passing it as raw json), the API responds with a 200:

[{"Id":"1","Name":"First of Two","obdOdometer":{"Time":"2020-01-01","Value":"112233"}},{"Id":"2","Name":"Second of Two","obdOdometer":{"Time":"2020-02-03","Value":"45506"}}]

However, I am getting errors when using my class.

Here is the class I am trying to use:

        public async Task TransmitobdOdometer(string json)
        {

            string bearerToken = _config.GetSection("PilotTmwApiSettings:BearerToken").Value;

            using (var client = new HttpClient())
            {

                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", bearerToken);
                var res = client.PostAsync("https://localhost:44308/TestDev", new StringContent(Newtonsoft.Json.JsonConvert.SerializeObject( new { json } )));

                try
                {
                    res.Result.EnsureSuccessStatusCode();
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.ToString());
                }
            }

        }

The string being passed into TransmitobdOdometer() is formatted like so:

string odometerValues = "[{\"Id\":\"1\",\"Name\":\"First of Two\",\"obdOdometer\":{\"Time\":\"2020-01-01\",\"Value\":\"112233\"}},{\"Id\":\"2\",\"Name\":\"Second of Two\",\"obdOdometer\":{\"Time\":\"2020-02-03\",\"Value\":\"45506\"}}]";

This returns the error message: "Response status code does not indicate success: 415 (Unsupported Media Type)."  I tried adjusting the format of the string being passed in, but I get the same error, so I figured I'd ask for insight into what I may be doing wrong before proceeding further.

Body:
Changing the line to

var res = client.PostAsync("localhost:44308/TestDev", new StringContent(Newtonsoft.Json.JsonConvert.SerializeObject( new { json } ), Encoding.UTF8, "application/json"));

... fixed the error 415.  I am still getting an error, but will move that to a new discussion.


问:
Navigation drawer - logo in header
I made a Navigation Drawer. I added ImageView in header.xml but it doesn't display on the screen.

```<code><com.google.android.material.navigation.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:fitsSystemWindows="true"
        app:headerLayout="@layout/nav_header"
        app:menu="@menu/menu_main_activity">
    </com.google.android.material.navigation.NavigationView>
</code>```

header.xml

```<code><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="200dp"
    android:background="@color/colorPrimaryDark">
    <ImageView
        android:id="@+id/iv_logo"
        android:layout_width="20dp"
        android:layout_height="20dp"
        android:layout_marginStart="32dp"
        android:layout_marginTop="24dp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:src="@drawable/ic_menu"
        android:contentDescription="@string/logo" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        style="@style/Text"
        android:text="@string/slogan"
        app:layout_constraintStart_toStartOf="@+id/iv_logo"
        app:layout_constraintTop_toBottomOf="@+id/iv_logo" />
</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

答:
Just replace:

```<code>tools:src="@drawable/ic_menu"
</code>```

with

```<code>android:src="@drawable/ic_menu"
</code>```

Title: Navigation drawer - logo in header

Body:
I made a Navigation Drawer. I added ImageView in header.xml but it doesn't display on the screen.

<com.google.android.material.navigation.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:fitsSystemWindows="true"
        app:headerLayout="@layout/nav_header"
        app:menu="@menu/menu_main_activity">
    </com.google.android.material.navigation.NavigationView>

header.xml

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="200dp"
    android:background="@color/colorPrimaryDark">
    <ImageView
        android:id="@+id/iv_logo"
        android:layout_width="20dp"
        android:layout_height="20dp"
        android:layout_marginStart="32dp"
        android:layout_marginTop="24dp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:src="@drawable/ic_menu"
        android:contentDescription="@string/logo" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        style="@style/Text"
        android:text="@string/slogan"
        app:layout_constraintStart_toStartOf="@+id/iv_logo"
        app:layout_constraintTop_toBottomOf="@+id/iv_logo" />
</androidx.constraintlayout.widget.ConstraintLayout>

Body:
Just replace:

tools:src="@drawable/ic_menu"

with

android:src="@drawable/ic_menu"


问:
ng command not found everytime i logged to GCP Cloud Shell
I noticed everytime i login Google Cloud Shell, my 'ng' command is not recognized

```<code>weilies@cloudshell:~/dev (cloud-xp)$ cd sunny-app/
weilies@cloudshell:~/dev/sunny-app (cloud-xp)$ ng serve -disable-host-check
-bash: ng: command not found
</code>```

I have to reinstall them with command then i got back my ng command.
weilies@cloudshell:~ (cloud-xp)$ ng --version

```<code>     _                      _                 ____ _     ___
    / \   _ __   __ _ _   _| | __ _ _ __     / ___| |   |_ _|
   / △ \ | '_ \ / _` | | | | |/ _` | '__|   | |   | |    | |
  / ___ \| | | | (_| | |_| | | (_| | |      | |___| |___ | |
 /_/   \_\_| |_|\__, |\__,_|_|\__,_|_|       \____|_____|___|
                |___/

Angular CLI: 9.1.7
Node: 10.14.2
OS: linux x64

Angular:
...
Ivy Workspace:

Package                      Version
------------------------------------------------------
@angular-devkit/architect    0.901.7
@angular-devkit/core         9.1.7
@angular-devkit/schematics   9.1.7
@schematics/angular          9.1.7
@schematics/update           0.901.7
rxjs                         6.5.4
</code>```

But one thing i noticed, the installation return with error (but it doesn't stop me running my angular app, so i simply ignored)

```<code>weilies@cloudshell:~ (cloud-xp)$ npm install -g @angular/cli
npm WARN deprecated request@2.88.2: request has been deprecated, see https://github.com/request/request/issues/3142
/usr/local/nvm/versions/node/v10.14.2/bin/ng -> /usr/local/nvm/versions/node/v10.14.2/lib/node_modules/@angular/cli/bin/ng

> @angular/cli@9.1.7 postinstall /usr/local/nvm/versions/node/v10.14.2/lib/node_modules/@angular/cli
> node ./bin/postinstall/script.js

+ @angular/cli@9.1.7
added 271 packages from 206 contributors in 15.296s
</code>```

It is just annoying i need to install angular/cli everytime i login GCP Clould shell. Isn't ng installed globally with a -g flag?

答:
This is due to the fact that, when you run npm install -g @angular/cli, it is installed globally (in the /usr/local/ directory).

Cloud Shell, however, has some limitations, one of them being that it is a "volatile" instance and any modifications that you made to it outside your $HOME are lost after the session is terminated.

Cloud Shell is meant for quick testing or administrative commands. You may rather use a Compute Engine instance (you can have 1 F1-micro instance for free) for development needs.

Body:
I noticed everytime i login Google Cloud Shell, my 'ng' command is not recognized

weilies@cloudshell:~/dev (cloud-xp)$ cd sunny-app/
weilies@cloudshell:~/dev/sunny-app (cloud-xp)$ ng serve -disable-host-check
-bash: ng: command not found

I have to reinstall them with command then i got back my ng command.
weilies@cloudshell:~ (cloud-xp)$ ng --version

     _                      _                 ____ _     ___
    / \   _ __   __ _ _   _| | __ _ _ __     / ___| |   |_ _|
   / △ \ | '_ \ / _` | | | | |/ _` | '__|   | |   | |    | |
  / ___ \| | | | (_| | |_| | | (_| | |      | |___| |___ | |
 /_/   \_\_| |_|\__, |\__,_|_|\__,_|_|       \____|_____|___|
                |___/

Angular CLI: 9.1.7
Node: 10.14.2
OS: linux x64

Angular:
...
Ivy Workspace:

Package                      Version
------------------------------------------------------
@angular-devkit/architect    0.901.7
@angular-devkit/core         9.1.7
@angular-devkit/schematics   9.1.7
@schematics/angular          9.1.7
@schematics/update           0.901.7
rxjs                         6.5.4

But one thing i noticed, the installation return with error (but it doesn't stop me running my angular app, so i simply ignored)

weilies@cloudshell:~ (cloud-xp)$ npm install -g @angular/cli
npm WARN deprecated request@2.88.2: request has been deprecated, see https://github.com/request/request/issues/3142
/usr/local/nvm/versions/node/v10.14.2/bin/ng -> /usr/local/nvm/versions/node/v10.14.2/lib/node_modules/@angular/cli/bin/ng

> @angular/cli@9.1.7 postinstall /usr/local/nvm/versions/node/v10.14.2/lib/node_modules/@angular/cli
> node ./bin/postinstall/script.js

+ @angular/cli@9.1.7
added 271 packages from 206 contributors in 15.296s

It is just annoying i need to install angular/cli everytime i login GCP Clould shell. Isn't ng installed globally with a -g flag?


问:
React typescript with react-redux component requires all passed props
So I've just started to combine react, redux (react-redux) and typescript. But I can't seem to figure out something here, namely, why the child components inside of the App component require all of the props that I pass into the App component.

App component:

```<code>const App = ({contacts, user, activeUserId}: ApplicationState) => (
    <div className="App">
        <Sidebar contacts={contacts} />
        <Main user={user} activeUserId={activeUserId}/>
    </div>
);

const getContacts = ({contacts, user, activeUserId}: ApplicationState) => ({contacts, user, activeUserId});
export default connect(getContacts)(App);
</code>```

Sidebar component:

```<code>const Sidebar = ({contacts}: ApplicationState) => {
    let contactsValues: Array<Contacts> = contacts && Object.values(contacts);

    return (
        <aside className="Sidebar">
            {contactsValues && contactsValues.map((contact: Contacts) => <User user={contact} key={contact.user_id}/>)}
        </aside>
    )
}
</code>```

I don't think there's any reason to list the Main component here as well since its only an empty component but gives the same errors, so I will just go ahead an list the Interfaces:

```<code>export default interface Contacts {
    email: string,
    name: string,
    profile_pic: string,
    status: string,
    user_id: string
}

export default interface ApplicationState {
    contacts: Contacts,
    user: object,
    activeUserId: string | null
}
</code>```

Actual error code: "TS2739: Type '{ contacts: Contacts; }' is missing the following properties from type 'ApplicationState': user, activeUserId"

So, both components ask to have all the props injected into them, even though they are not required inside the component itself. If I supply the components the everything works and I get no errors.

I'm pretty sure there's something wrong with my syntax or 'wiring' of the types.

Can we also get a explanation or a decent link to docs/materials that help us understand why this is happening?

If there is anything else that I should be including please let me know and I will provide!

Edit:

I've actually realized that its important to show the Main component too because this one also causes problems and some of the fixes you guys have suggested only fix the Sidebar component but not the Main.

Main component:

```<code>import React from "react";
import "./Main.scss";

import ApplicationState from "../../models/ApplicationState";

const Main = ({user, activeUserId}: ApplicationState) => {
    return (
        <main className="Main">
            Main Stuff
        </main>
    )
}

</code>```

Edit:

From what I've experimented with all of these answers I think the best solution would be to make everything in the interfaces optional, but if I do this then the contactsValues variable inside the Sidebar component throws: TS2322: Type 'any[] | undefined' is not assignable to type 'Contacts[]'.   Type 'undefined' is not assignable to type 'Contacts[]'..

答:
Replace the Applicationstate interface with this :</p>

```<code> export default interface ApplicationState {
   contacts?: Contacts,
   user?: object,
   activeUserId?: string | null
}
</code>```

Body:
So I've just started to combine react, redux (react-redux) and typescript. But I can't seem to figure out something here, namely, why the child components inside of the App component require all of the props that I pass into the App component.

App component:

const App = ({contacts, user, activeUserId}: ApplicationState) => (

        <Sidebar contacts={contacts} />

);

const getContacts = ({contacts, user, activeUserId}: ApplicationState) => ({contacts, user, activeUserId});
export default connect(getContacts)(App);

Sidebar component:

const Sidebar = ({contacts}: ApplicationState) => {
    let contactsValues: Array<Contacts> = contacts && Object.values(contacts);

    return (

            {contactsValues && contactsValues.map((contact: Contacts) => <User user={contact} key={contact.user_id}/>)}

    )
}

I don't think there's any reason to list the Main component here as well since its only an empty component but gives the same errors, so I will just go ahead an list the Interfaces:

export default interface Contacts {
    email: string,
    name: string,
    profile_pic: string,
    status: string,
    user_id: string
}

export default interface ApplicationState {
    contacts: Contacts,
    user: object,
    activeUserId: string | null
}

Actual error code: "TS2739: Type '{ contacts: Contacts; }' is missing the following properties from type 'ApplicationState': user, activeUserId"

So, both components ask to have all the props injected into them, even though they are not required inside the component itself. If I supply the components the everything works and I get no errors.

I'm pretty sure there's something wrong with my syntax or 'wiring' of the types.

Can we also get a explanation or a decent link to docs/materials that help us understand why this is happening?

If there is anything else that I should be including please let me know and I will provide!

Edit:

I've actually realized that its important to show the Main component too because this one also causes problems and some of the fixes you guys have suggested only fix the Sidebar component but not the Main.

Main component:

import React from "react";
import "./Main.scss";

import ApplicationState from "../../models/ApplicationState";

const Main = ({user, activeUserId}: ApplicationState) => {
    return (

            Main Stuff

    )
}

Edit:

From what I've experimented with all of these answers I think the best solution would be to make everything in the interfaces optional, but if I do this then the contactsValues variable inside the Sidebar component throws: TS2322: Type 'any[] | undefined' is not assignable to type 'Contacts[]'.   Type 'undefined' is not assignable to type 'Contacts[]'..

Body:
Replace the Applicationstate interface with this :

 export default interface ApplicationState {
   contacts?: Contacts,
   user?: object,
   activeUserId?: string | null
}


问:
Uncaught (in promise) TypeError: _this is not a function
I'm making a simple axios call and on success, call a toast. The toast function is also there and working fine because I am using it at 100 different places.

console log shows {data: "Payment Successful", status: 200, statusText: "OK", headers: {…}, config: {…}, …} means the call is working fine, it's just the this is not ...

```<code>this.razorPayOptions = {
    'key': process.env.MIX_RAZORPAY_KEY,
    'name': process.env.MIX_APP_NAME,
    'description': 'Details ...',
    'handler': function (request) {
        axios.post('/api/transaction/complete', request)
            .then(response => {
                console.log(response);
                this.toast(response.data, response.status); // this is where the error occurs
            });
    }
}
</code>```

Error: Uncaught (in promise) TypeError: _this.toast is not a function

I've searched on internet for past 2 days but couldn't find anything. Some suggested to use async/await but no luck either. As always, stack overflow is my last resort. If you need more info, please add a comment below.

Thank You.

答:
You can either switch to an arrow function, or capture this before you define your callback:

```<code>this.razorPayOptions = {
    'key': process.env.MIX_RAZORPAY_KEY,
    'name': process.env.MIX_APP_NAME,
    'description': 'Details ...',
    'handler': function (request) {
        const that = this;
        axios.post('/api/transaction/complete', request)
            .then(response => {
                console.log(response);
                that.toast(response.data, response.status); // this is where the error occurs
            });
    }
}
</code>```

Body:
I'm making a simple axios call and on success, call a toast. The toast function is also there and working fine because I am using it at 100 different places.

console log shows {data: "Payment Successful", status: 200, statusText: "OK", headers: {…}, config: {…}, …} means the call is working fine, it's just the this is not ...

this.razorPayOptions = {
    'key': process.env.MIX_RAZORPAY_KEY,
    'name': process.env.MIX_APP_NAME,
    'description': 'Details ...',
    'handler': function (request) {
        axios.post('/api/transaction/complete', request)
            .then(response => {
                console.log(response);
                this.toast(response.data, response.status); // this is where the error occurs
            });
    }
}

Error: Uncaught (in promise) TypeError: _this.toast is not a function

I've searched on internet for past 2 days but couldn't find anything. Some suggested to use async/await but no luck either. As always, stack overflow is my last resort. If you need more info, please add a comment below.

Thank You.

Body:
You can either switch to an arrow function, or capture this before you define your callback:

this.razorPayOptions = {
    'key': process.env.MIX_RAZORPAY_KEY,
    'name': process.env.MIX_APP_NAME,
    'description': 'Details ...',
    'handler': function (request) {
        const that = this;
        axios.post('/api/transaction/complete', request)
            .then(response => {
                console.log(response);
                that.toast(response.data, response.status); // this is where the error occurs
            });
    }
}


问:
How to split dataset as train and test data into rows using date, pandas and python?
How to split dataset as train and test data into rows using date like first 90%(from 2018-01-01 until 2019-02-01) would be train & last 10%(from 2019-02-02 ) would be test data in python?Not splitting randomly?</p>

答:
As explained in this SO post you can split it with np.split:

```<code>import numpy as np
df = df.sort_values('date')
data = df.values
train_set, test_set= np.split(data, [int(.9 * len(data))])
</code>```

Body:
As explained in this SO post you can split it with np.split:

import numpy as np
df = df.sort_values('date')
data = df.values
train_set, test_set= np.split(data, [int(.9 * len(data))])


问:
connecting to network registry
In Windows you can launch the registry and them connect to another registry; does anyone know how to accomplish this in c#? or if you know how of an api call that would be helpful.

Thanks

答:
Try suggestion about half way down on this page: http://vbcity.com/forums/p/42161/170595.aspx

You will need the proper permissions on the machine, of course.

Title: connecting to network registry


问:
Why is @typescript-eslint/parser including files outside of those configured in my tsconfig.json?
I am getting the error: -

```<code>Parsing error: "parserOptions.project" has been set for u/typescript-eslint/parser.

The file does not match your project config: .eslintrc.js.

The file must be included in at least one of the projects provided.
</code>```

IDE - WebStorm 20.1.1

Project structure: -

```<code>node_modules

src

--- testfile.js

.eslintrc.js

.prettierrc.js

baseeslint.js

package.json

tsconfig.json
</code>```

.eslintrc.js: -

```<code>module.exports = {
extends: ['./baseeslint'],
parserOptions: {
project: './tsconfig.json'
},
rules: {}
}
</code>```

baseeslint.js: -

```<code>module.exports = {

parser: '@typescript-eslint/parser'

}
</code>```

tsconfig.json: -

```<code>{

"include": [

"/src/**/*.ts",

"/src/**/*.tsx"

],

"exclude": ["node_modules"],

"compilerOptions": {

"outDir": "./lib",

"types": ["styled-components", "react", "@types/react-router-dom", "reactstrap"]

}

}
</code>```

I have absolutely no idea why this is happening? I would assume it would ignore files in the root, especially with include specified in my tsconfg.json?

Any help would be greatly appreciated.

EDIT: -

My solution, should it help others...

I added the ignorePatterns configuration to my .eslintrc.js file: -

```<code>module.exports = {
  extends: ["mycustom/eslint-config"],
  parserOptions: {
    project: './tsconfig.json'
  },
  ignorePatterns: ["/*.*"],
  rules: {}
}
</code>```

This can also be done via .eslintignore (see Anton Bessonov's response below).

Another thing relating to this which maybe of use to others here is the VScode config I used (I switched from WebStorm to VSCode after posting the original question). I am a big fan of running eslint fix on save but I do not want it attempting to do this with all files. My project files (and only my project files) are all .ts/.tsx. The options below in settings.json allow fix on save without it including every file in my repo: -

```<code>{
    "editor.codeActionsOnSave": {
        "source.fixAll.eslint": true
    },
    "eslint.probe": [
        "typescript",
        "typescriptreact"
    ],
}
</code>```

If eslint.probe is not specified, it defaults to: -

["javascript", "javascriptreact", "typescript", "typescriptreact", "html", "vue"]

More about the VSCode ESLint extension settings can be found here.

答:
You can also ignore .eslintrc.js in .eslintrc.js itself, saving you an additional file:</p>

```<code>"ignorePatterns": [
    ".eslintrc.js"
],
</code>```

Body:
I am getting the error: -

Parsing error: "parserOptions.project" has been set for u/typescript-eslint/parser.

The file does not match your project config: .eslintrc.js.

The file must be included in at least one of the projects provided.

IDE - WebStorm 20.1.1

Project structure: -

node_modules

src

--- testfile.js

.eslintrc.js

.prettierrc.js

baseeslint.js

package.json

tsconfig.json

.eslintrc.js: -

module.exports = {
extends: ['./baseeslint'],
parserOptions: {
project: './tsconfig.json'
},
rules: {}
}

baseeslint.js: -

module.exports = {

parser: '@typescript-eslint/parser'

}

tsconfig.json: -

{

"include": [

"/src/**/*.ts",

"/src/**/*.tsx"

],

"exclude": ["node_modules"],

"compilerOptions": {

"outDir": "./lib",

"types": ["styled-components", "react", "@types/react-router-dom", "reactstrap"]

}

}

I have absolutely no idea why this is happening? I would assume it would ignore files in the root, especially with include specified in my tsconfg.json?

Any help would be greatly appreciated.

EDIT: -

My solution, should it help others...

I added the ignorePatterns configuration to my .eslintrc.js file: -

module.exports = {
  extends: ["mycustom/eslint-config"],
  parserOptions: {
    project: './tsconfig.json'
  },
  ignorePatterns: ["/*.*"],
  rules: {}
}

This can also be done via .eslintignore (see Anton Bessonov's response below).

Another thing relating to this which maybe of use to others here is the VScode config I used (I switched from WebStorm to VSCode after posting the original question). I am a big fan of running eslint fix on save but I do not want it attempting to do this with all files. My project files (and only my project files) are all .ts/.tsx. The options below in settings.json allow fix on save without it including every file in my repo: -

{
    "editor.codeActionsOnSave": {
        "source.fixAll.eslint": true
    },
    "eslint.probe": [
        "typescript",
        "typescriptreact"
    ],
}

If eslint.probe is not specified, it defaults to: -

["javascript", "javascriptreact", "typescript", "typescriptreact", "html", "vue"]

More about the VSCode ESLint extension settings can be found here.

Body:
You can also ignore .eslintrc.js in .eslintrc.js itself, saving you an additional file:

"ignorePatterns": [
    ".eslintrc.js"
],


问:
keras combine pretrained model
I trained a single model and want to combine it with another keras model using the functional api (backend is tensorflow version 1.4)

My first model looks like this:

```<code>import tensorflow.contrib.keras.api.keras as keras

model = keras.models.Sequential()
input = Input(shape=(200,))
dnn = Dense(400, activation="relu")(input)
dnn = Dense(400, activation="relu")(dnn)
output = Dense(5, activation="softmax")(dnn)
model = keras.models.Model(inputs=input, outputs=output)
</code>```

after I trained this model I save it using the keras model.save() method. I can also load the model and retrain it without problems.

Now I want to use the output of this model as additional input for a second model:

```<code># load first model
old_model = keras.models.load_model(path_to_old_model)

input_1 = Input(shape=(200,))
input_2 = Input(shape=(200,))
output_old_model = old_model(input_2)

merge_layer = concatenate([input_1, output_old_model])
dnn_layer = Dense(200, activation="relu")(merge_layer)
dnn_layer = Dense(200, activation="relu")(dnn_layer)
output = Dense(10, activation="sigmoid")(dnn_layer)
new_model = keras.models.Model(inputs=[input_1, input_2], outputs=output)
new_model.compile(loss="binary_crossentropy", optimizer="adam", metrics=["accuracy"]
new_model.fit(inputs=[x1,x2], labels=labels, epochs=50, batch_size=32)
</code>```

when I try this I get the following error message:

```<code>FailedPreconditionError (see above for traceback): Attempting to use uninitialized value dense_1/kernel
 [[Node: dense_1/kernel/read = Identity[T=DT_FLOAT, _class=["loc:@dense_1/kernel"], _device="/job:localhost/replica:0/task:0/device:GPU:0"](dense_1/kernel)]]
 [[Node: model_1_1/dense_3/BiasAdd/_79 = _Recv[client_terminated=false, recv_device="/job:localhost/replica:0/task:0/device:CPU:0", send_device="/job:localhost/replica:0/task:0/device:GPU:0", send_device_incarnation=1, tensor_name="edge_68_model_1_1/dense_3/BiasAdd", tensor_type=DT_FLOAT, _device="/job:localhost/replica:0/task:0/device:CPU:0"]()]]
</code>```

答:
Let's say you have a pre-trained/saved CNN model called pretrained_model and you want to add a densely connected layers to it, then using the functional API you can write something like this:

from keras import models, layers

kmodel = layers.Flatten()(pretrained_model.output)
kmodel = layers.Dense(256, activation='relu')(kmodel)
kmodel_out = layers.Dense(1, activation='sigmoid')(kmodel)
model = models.Model(pretrained_model.input, kmodel_out)
```

Title: keras combine pretrained model

Body:
I trained a single model and want to combine it with another keras model using the functional api (backend is tensorflow version 1.4)

My first model looks like this:

import tensorflow.contrib.keras.api.keras as keras

model = keras.models.Sequential()
input = Input(shape=(200,))
dnn = Dense(400, activation="relu")(input)
dnn = Dense(400, activation="relu")(dnn)
output = Dense(5, activation="softmax")(dnn)
model = keras.models.Model(inputs=input, outputs=output)

after I trained this model I save it using the keras model.save() method. I can also load the model and retrain it without problems.

Now I want to use the output of this model as additional input for a second model:

# load first model
old_model = keras.models.load_model(path_to_old_model)

input_1 = Input(shape=(200,))
input_2 = Input(shape=(200,))
output_old_model = old_model(input_2)

merge_layer = concatenate([input_1, output_old_model])
dnn_layer = Dense(200, activation="relu")(merge_layer)
dnn_layer = Dense(200, activation="relu")(dnn_layer)
output = Dense(10, activation="sigmoid")(dnn_layer)
new_model = keras.models.Model(inputs=[input_1, input_2], outputs=output)
new_model.compile(loss="binary_crossentropy", optimizer="adam", metrics=["accuracy"]
new_model.fit(inputs=[x1,x2], labels=labels, epochs=50, batch_size=32)

when I try this I get the following error message:

FailedPreconditionError (see above for traceback): Attempting to use uninitialized value dense_1/kernel
 [[Node: dense_1/kernel/read = Identity[T=DT_FLOAT, _class=["loc:@dense_1/kernel"], _device="/job:localhost/replica:0/task:0/device:GPU:0"](dense_1/kernel)]]
 [[Node: model_1_1/dense_3/BiasAdd/_79 = _Recv[client_terminated=false, recv_device="/job:localhost/replica:0/task:0/device:CPU:0", send_device="/job:localhost/replica:0/task:0/device:GPU:0", send_device_incarnation=1, tensor_name="edge_68_model_1_1/dense_3/BiasAdd", tensor_type=DT_FLOAT, _device="/job:localhost/replica:0/task:0/device:CPU:0"]()]]


问:
How to prevent calling a function depending on generic constraints in typescript?
As an exercise I'm implementing simple algebraic data types in typescript.
I would like to implement the ap function, in such a way that it is only callable when the wrapper contains a function.
This is how I would have liked to use it:

```<code>Identity.of(x => x + 1).ap(Identity.of(5)); // This should work and return an Identity(6)

Identity.of(5).ap(...); // This should make the compiler emit an error
</code>```

I tried to define it with generic conditional like this:

```<code>type Func<T, U> = (p: T) => U;

interface Identity<T> {
  map<U>(fn: Func<T, U>): Identity<U>;
  ap<U, V>(id: Identity<U>): T extends Func<U, V> ? Identity<V> : never;
}

function of<T>(value: T): Identity<T> {
  return {
    map: fn => of(fn(value)),
    ap: id => id.map(value)
  };
}
</code>```

But I get the following error:

```<code>Type 'Identity<V>' is not assignable to type 'T extends Func<U, V> ? Identity<V> : never'.(2322)
input.ts(5, 3): The expected type comes from the return type of this signature.

Argument of type 'T' is not assignable to parameter of type 'Func<U, V>'.
</code>```

Is this in any way possible to do in typescript?

答:
After brute forcing for a long time, I have found a way to make this type safe:

```<code>type Func<T, U> = (p: T) => U;

interface Identity<T> {
  map<U>(fn: Func<T, U>): Identity<U>;
  ap(id: T extends Func<infer U, any> ? Identity<U> : never): T extends Func<any, infer U> ? Identity<U> : never;
}

function of<T>(value: T): Identity<T> {
  return {
    map: fn => of(fn(value)),
    ap: id => {
      const fn: unknown = value;

      return id.map(fn as Func<unknown, unknown>) as T extends Func<any, infer U> ? Identity<U> : never;
    }
  };
}
</code>```

Infering the types in the interface definition helps typescript save types when chaining operations and makes everything type safe.
When writing the implementation we have to help typescript by using typecasts.

Body:
As an exercise I'm implementing simple algebraic data types in typescript.
I would like to implement the ap function, in such a way that it is only callable when the wrapper contains a function.
This is how I would have liked to use it:

Identity.of(x => x + 1).ap(Identity.of(5)); // This should work and return an Identity(6)

Identity.of(5).ap(...); // This should make the compiler emit an error

I tried to define it with generic conditional like this:

type Func<T, U> = (p: T) => U;

interface Identity<T> {
  map(fn: Func<T, U>): Identity;
  ap(id: Identity): T extends Func ? Identity<V> : never;
}

function of<T>(value: T): Identity<T> {
  return {
    map: fn => of(fn(value)),
    ap: id => id.map(value)
  };
}

But I get the following error:

Type 'Identity<V>' is not assignable to type 'T extends Func ? Identity<V> : never'.(2322)
input.ts(5, 3): The expected type comes from the return type of this signature.

Argument of type 'T' is not assignable to parameter of type 'Func'.

Is this in any way possible to do in typescript?

Body:
After brute forcing for a long time, I have found a way to make this type safe:

type Func<T, U> = (p: T) => U;

interface Identity<T> {
  map<U>(fn: Func<T, U>): Identity<U>;
  ap(id: T extends Func<infer U, any> ? Identity<U> : never): T extends Func<any, infer U> ? Identity<U> : never;
}

function of<T>(value: T): Identity<T> {
  return {
    map: fn => of(fn(value)),
    ap: id => {
      const fn: unknown = value;

      return id.map(fn as Func<unknown, unknown>) as T extends Func<any, infer U> ? Identity<U> : never;
    }
  };
}

Infering the types in the interface definition helps typescript save types when chaining operations and makes everything type safe.
When writing the implementation we have to help typescript by using typecasts.


问:
Getting file names sorted by time using scandir
I am creating files and setting it's names to be hashed representation of time() using md5 function:

```<code>$encoded_data = ['some_data'];
$file_name = md5(time()).'.json';
$path = base_path("../some_folder/");
file_put_contents($path.$file_name, $encoded_data);
</code>```

What I do not understand is if I use scandir with sorting order parameter to get those files:

```<code>foreach(array_diff(scandir($path, 1), ['.', '..']) as $file_name) {
    $files[] = base_path('../some_folder/').$file_name;
}
</code>```

will $files array be really be sorted by date and time which is used as a file name?

答:
Since hashing function like md5 are one-way only, the filename is useless as a sorting criteria. If you want to keep track of the very same timestamp you used for generating the md5 value, you'd have to keep a hash:timestamp table on record. If you did that, you wouldn't need to run scandir to begin with -- you could simply read the file list from the reference table you've saved. (Assuming you keep it up to date with deleted files. Otherwise, it would show obsolete files.)

Is there a particular reason you need to use a md5-hash of the timestamp? Why not simply use the timestamp (with a prefix or otherwise) as the filename? Then you could simply sort alphabetically, ascending or descending, and have the files automatically in timewise order. This would be by far the simplest and most light-weight option.

If md5-hashes as file names is a must, and writing a reference table is not what you prefer, then you will have to loop through the files, or use usort, and check the date of the file's creation/modification (filemtime). You can find solutions in the answers to sort files by date in PHP. Be aware that this will lead to plenty more disk activity (even if the results are cached).

Body:
I am creating files and setting it's names to be hashed representation of time() using md5 function:

$encoded_data = ['some_data'];
$file_name = md5(time()).'.json';
$path = base_path("../some_folder/");
file_put_contents($path.$file_name, $encoded_data);

What I do not understand is if I use scandir with sorting order parameter to get those files:

foreach(array_diff(scandir($path, 1), ['.', '..']) as $file_name) {
    $files[] = base_path('../some_folder/').$file_name;
}

will $files array be really be sorted by date and time which is used as a file name?


问:
Unable to access property of eloquent model query result
I am encountering what I would assume to be a common issue but I have not found a relevant solution.

In my Laravel application, I have a relationship setup between two models: BarterReview and BarterReviewFeedback.

BarterReview.php

```<code>public function barterReviewFeedback () {
    return $this->hasOne(BarterReviewFeedback::class, 'barter_review_id');
}
</code>```

BarterReviewFeedback.php

```<code>public function barterReview () {
    return $this->belongsTo(BarterReview::class);
}
</code>```

The Following returns a BarterReview with the associated BarterReviewFeedback:

```<code>$review = \App\BarterReview::with('barterReviewFeedback')->find(1);
return $review;
</code>```

The result ($review) looks like this when formatted:

```<code>{
  "id": 1,
  "created_at": "2020-04-06T20:13:15.000000Z",
  "updated_at": "2020-04-06T20:13:15.000000Z",
  "rating": 5,
  "comment": "Five out of Five!",
  "user_id": 2,
  "barter_id": 1,
  "barter_review_feedback": {
    "id": 3,
    "created_at": "2020-06-02T16:34:41.000000Z",
    "updated_at": "2020-06-02T16:34:41.000000Z",
    "barter_review_id": 1,
    "user_id": 1,
    "content": "test"
  }
}
</code>```

The ISSUE is that I am unable to access "barter_review_feedback" inside the object - $review->barter_review_feedback doesn't display anything.

Additionally, attempting to directly access a property inside of $review->barter_review_feedback such as $review->barter_review_feedback->id yields the following error: Trying to get property 'id' of non-object

Any ideas as to why this would be?

答:
You can access relationship like this

```<code>$review->barterReviewFeedback->id
</code>```

Because your relationship is barterReviewFeedback not barter_review_feedback

Body:
I am encountering what I would assume to be a common issue but I have not found a relevant solution.

In my Laravel application, I have a relationship setup between two models: BarterReview and BarterReviewFeedback.

BarterReview.php

public function barterReviewFeedback () {
    return $this->hasOne(BarterReviewFeedback::class, 'barter_review_id');
}

BarterReviewFeedback.php

public function barterReview () {
    return $this->belongsTo(BarterReview::class);
}

The Following returns a BarterReview with the associated BarterReviewFeedback:

$review = \App\BarterReview::with('barterReviewFeedback')->find(1);
return $review;

The result ($review) looks like this when formatted:

{
  "id": 1,
  "created_at": "2020-04-06T20:13:15.000000Z",
  "updated_at": "2020-04-06T20:13:15.000000Z",
  "rating": 5,
  "comment": "Five out of Five!",
  "user_id": 2,
  "barter_id": 1,
  "barter_review_feedback": {
    "id": 3,
    "created_at": "2020-06-02T16:34:41.000000Z",
    "updated_at": "2020-06-02T16:34:41.000000Z",
    "barter_review_id": 1,
    "user_id": 1,
    "content": "test"
  }
}

The ISSUE is that I am unable to access "barter_review_feedback" inside the object - $review->barter_review_feedback doesn't display anything.

Additionally, attempting to directly access a property inside of $review->barter_review_feedback such as $review->barter_review_feedback->id yields the following error: Trying to get property 'id' of non-object

Any ideas as to why this would be?

Body:
You can access relationship like this

$review->barterReviewFeedback->id

Because your relationship is barterReviewFeedback not barter_review_feedback


答:
You can use the member parameter to get the guild ID using member.guild.id:

client.on("guildMemberAdd", member => {

  settingss.findOne({
    guildID: member.guild.id
  }, async (err, settings) => {

    var role = member.guild.roles.cache.get(role => role.name === settingss.joinrolename);

    if (!role) return;

    member.roles.add(role);

    const channel = member.guild.channels.cache.get(channel => channel.name === settingss.welcomechannelname);

    if (!channel) return;

    channel.send(`Welcome to the server, ${member}`);

  });

});
```

Title: How do i get the guild ID of a joined user/member (Discord.js)

Body:
client.on("guildMemberAdd", member => {

settingss.findOne({
  guildID: guild.ID // <---- Trying to figure out what i want over here
}, async (err, settings) => {

    var role = member.guild.roles.cache.get(role => role.name === settingss.joinrolename);

    if (!role) return;

    member.roles.add(role);

    const channel = member.guild.channels.cache.get(channel => channel.name === settingss.welcomechannelname);

    if (!channel) return;

    channel.send(`Welcome to the server, ${member}`);

  });

});

i cant seem to figuere out how to get guild ID over here.
 I tried guild.memberCount this didnt work either.


问:
How to transform CSV rows with the same keys into hash
I have parsed the .csv file and received the following headers:

```<code>"Date":"Start" "Date":"Due" "Amount":"Total" "Amount":"Left"
</code>```

There are values for each. I need to map it to hash dynamically in the following way:

```<code>{date => {start: value, due: value}, amount => {total: value, left: value}}
</code>```

Please, could you suggest a way. I've tried to use it as an array like:

```<code>[["Date", "Start"], ["Date", "Due"], ["Amount", "Total"], ["Amount", "Left"]]
</code>```

and then

```<code>.each_slice(2)
</code>```

but after that I got stuck. Thanks in advance

答:
you can try something like:</p>

```<code>rows.map do |row|
  {
    date: { start: row[1], end: row[3] },
    amount: { total: row[4], left: row[6] }
  }
end
</code>```

Body:
I have parsed the .csv file and received the following headers:

"Date":"Start" "Date":"Due" "Amount":"Total" "Amount":"Left"

There are values for each. I need to map it to hash dynamically in the following way:

{date => {start: value, due: value}, amount => {total: value, left: value}}

Please, could you suggest a way. I've tried to use it as an array like:

[["Date", "Start"], ["Date", "Due"], ["Amount", "Total"], ["Amount", "Left"]]

and then

.each_slice(2)

but after that I got stuck. Thanks in advance

Body:
you can try something like:

rows.map do |row|
  {
    date: { start: row[1], end: row[3] },
    amount: { total: row[4], left: row[6] }
  }
end


问:
Most efficient way in Python to iterate over a large file (10GB+)
I'm working on a Python script to go through two files - one containing a list of UUIDs, the other containing a large amount of log entries - each line containing one of the UUIDs from the other file. The purpose of the program is to create a list of the UUIDS from file1, then for each time that UUID is found in the log file, increment the associated value for each time a match is found.

So long story short, count how many times each UUID appears in the log file.
At the moment, I have a list which is populated with UUID as the key, and 'hits' as the value. Then another loop which iterates over each line of the log file, and checking if the UUID in the log matches a UUID in the UUID list. If it matches, it increments the value.

```<code>    for i, logLine in enumerate(logHandle):         #start matching UUID entries in log file to UUID from rulebase
        if logFunc.progress(lineCount, logSize):    #check progress
            print logFunc.progress(lineCount, logSize)  #print progress in 10% intervals
        for uid in uidHits:
            if logLine.count(uid) == 1:             #for each UUID, check the current line of the log for a match in the UUID list
                uidHits[uid] += 1                   #if matched, increment the relevant value in the uidHits list
                break                                #as we've already found the match, don't process the rest
        lineCount += 1
</code>```

It works as it should - but I'm sure there is a more efficient way of processing the file. I've been through a few guides and found that using 'count' is faster than using a compiled regex. I thought reading files in chunks rather than line by line would improve performance by reducing the amount of disk I/O time but the performance difference on a test file ~200MB was neglible. If anyone has any other methods I would be very grateful :)

答:
Think functionally!

Write a function which will take a line of the log file and return the uuid. Call it uuid, say.

Apply this function to every line of the log file. If you are using Python 3 you can use the built-in function map; otherwise, you need to use itertools.imap.

Pass this iterator to a collections.Counter.

```<code>collections.Counter(map(uuid, open("log.txt")))
</code>```

This will be pretty much optimally efficient.

A couple comments:

This completely ignores the list of UUIDs and just counts the ones that appear in the log file. You will need to modify the program somewhat if you don't want this.

Your code is slow because you are using the wrong data structures. A dict is what you want here.

Body:
I'm working on a Python script to go through two files - one containing a list of UUIDs, the other containing a large amount of log entries - each line containing one of the UUIDs from the other file. The purpose of the program is to create a list of the UUIDS from file1, then for each time that UUID is found in the log file, increment the associated value for each time a match is found.

So long story short, count how many times each UUID appears in the log file.
At the moment, I have a list which is populated with UUID as the key, and 'hits' as the value. Then another loop which iterates over each line of the log file, and checking if the UUID in the log matches a UUID in the UUID list. If it matches, it increments the value.

    for i, logLine in enumerate(logHandle):         #start matching UUID entries in log file to UUID from rulebase
        if logFunc.progress(lineCount, logSize):    #check progress
            print logFunc.progress(lineCount, logSize)  #print progress in 10% intervals
        for uid in uidHits:
            if logLine.count(uid) == 1:             #for each UUID, check the current line of the log for a match in the UUID list
                uidHits[uid] += 1                   #if matched, increment the relevant value in the uidHits list
                break                                #as we've already found the match, don't process the rest
        lineCount += 1

It works as it should - but I'm sure there is a more efficient way of processing the file. I've been through a few guides and found that using 'count' is faster than using a compiled regex. I thought reading files in chunks rather than line by line would improve performance by reducing the amount of disk I/O time but the performance difference on a test file ~200MB was neglible. If anyone has any other methods I would be very grateful :)

Body:
Think functionally!

Write a function which will take a line of the log file and return the uuid. Call it uuid, say.

Apply this function to every line of the log file. If you are using Python 3 you can use the built-in function map; otherwise, you need to use itertools.imap.

Pass this iterator to a collections.Counter.

collections.Counter(map(uuid, open("log.txt")))

This will be pretty much optimally efficient.

A couple comments:

This completely ignores the list of UUIDs and just counts the ones that appear in the log file. You will need to modify the program somewhat if you don't want this.

Your code is slow because you are using the wrong data structures. A dict is what you want here.


问:
Can't access ngx.var in rewrite_by_lua_block
I'm trying to set the value to nginx variable, but getting an error:

```<code>[error] 47#47: *382 lua entry thread aborted: runtime error: rewrite_by_lua(myconf.conf:23):2: attempt to index field 'var' (a nil value)
stack traceback:
coroutine 0:
        rewrite_by_lua(myconf.conf:23): in function <rewrite_by_lua(myconf.conf:23):1>, client: ip, server: *.host, request: "GET / HTTP/1.1", host: "host"
</code>```

The part of my config:

```<code>        set $upstream_new '';
        rewrite_by_lua_block {
        ngx.var.upstream_new = "8.8.8.8";
}
</code>```

I'm running nginx in docker if it matters. Compiled with:

```<code> --prefix=/var/www/nginx --conf-path=/etc/nginx/nginx.conf --sbin-path=/usr/sbin --modules-path=/usr/lib/nginx/modules --http-log-path=/var/log/nginx/access.log --error-log-path=/var/log/nginx/error.log --lock-path=/var/lock/nginx.lock --pid-path=/tmp/nginx.pid --http-client-body-temp-path=/var/cache/nginx/body --http-fastcgi-temp-path=/var/cache/nginx/fastcgi --http-proxy-temp-path=/var/cache/nginx/proxy --http-scgi-temp-path=/var/cache/nginx/scgi --http-uwsgi-temp-path=/var/cache/nginx/uwsgi --with-pcre --with-pcre-jit --with-http_ssl_module --with-http_stub_status_module --with-http_realip_module --with-http_auth_request_module --with-http_secure_link_module --with-http_random_index_module --with-http_addition_module --with-http_dav_module --with-http_geoip_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_degradation_module --with-http_v2_module --with-http_sub_module --with-http_flv_module --with-http_mp4_module --with-http_slice_module --with-stream --with-stream_ssl_module --with-stream_ssl_preread_module --with-stream_realip_module --with-stream_geoip_module=dynamic --with-mail --with-mail_ssl_module --with-threads --with-file-aio --with-compat --with-http_xslt_module=dynamic --with-http_image_filter_module=dynamic --with-http_geoip_module=dynamic --with-http_perl_module=dynamic --add-dynamic-module=/usr/src/nginx/ngx_devel_kit-0.3.1 --add-module=/usr/src/nginx/ngx_cache_purge-2.3 --add-dynamic-module=/usr/src/nginx/nginx_upstream_check_module-master --add-dynamic-module=/usr/src/nginx/lua-nginx-module-0.10.16rc5 --add-dynamic-module=/usr/src/nginx/headers-more-nginx-module-0.33 --add-dynamic-module=/usr/src/nginx/ngx_brotli --add-dynamic-module=/usr/src/nginx/ngx_http_auth_pam_module-1.5.1 --add-dynamic-module=/usr/src/nginx/echo-nginx-module-0.62rc1 --add-dynamic-module=/usr/src/nginx/ngx-fancyindex-0.4.4 --add-dynamic-module=/usr/src/nginx/nginx-dav-ext-module-3.0.0 --add-dynamic-module=/usr/src/nginx/ngx_http_substitutions_filter_module-0.6.4 --add-dynamic-module=/usr/src/nginx/nginx-upload-progress-module-0.9.2 --add-dynamic-module=/usr/src/nginx/nchan-1.2.7
</code>```

答:
It is possible that the compilation was not properly done. Try this post and compile accordingly again with adding all your modules.

If you're using Docker then this is OpenResty with Naxsi module compilation. You can safely add your modules and remove unwanted ones.

Check using nginx -V for all the compilation flags and if you see all the Lua modules.

I tried with following blocks on OpenResty and working properly.

set $upstream_new '';
rewrite_by_lua_block {
    ngx.var.upstream_new = "8.8.8.8";
}
```

<p>and</p>

<pre class="lang-lua prettyprint-override"><code>set $upstream_new '';
access_by_lua '
    ngx.var.upstream_new = "8.8.8.8";
';
</code>```

agentzh's Nginx Tutorials might be helpful if you're new.

Body:
I'm trying to set the value to nginx variable, but getting an error:

[error] 47#47: *382 lua entry thread aborted: runtime error: rewrite_by_lua(myconf.conf:23):2: attempt to index field 'var' (a nil value)
stack traceback:
coroutine 0:
        rewrite_by_lua(myconf.conf:23): in function <rewrite_by_lua(myconf.conf:23):1>, client: ip, server: *.host, request: "GET / HTTP/1.1", host: "host"

The part of my config:

        set $upstream_new '';
        rewrite_by_lua_block {
        ngx.var.upstream_new = "8.8.8.8";
}

I'm running nginx in docker if it matters. Compiled with:

 --prefix=/var/www/nginx --conf-path=/etc/nginx/nginx.conf --sbin-path=/usr/sbin --modules-path=/usr/lib/nginx/modules --http-log-path=/var/log/nginx/access.log --error-log-path=/var/log/nginx/error.log --lock-path=/var/lock/nginx.lock --pid-path=/tmp/nginx.pid --http-client-body-temp-path=/var/cache/nginx/body --http-fastcgi-temp-path=/var/cache/nginx/fastcgi --http-proxy-temp-path=/var/cache/nginx/proxy --http-scgi-temp-path=/var/cache/nginx/scgi --http-uwsgi-temp-path=/var/cache/nginx/uwsgi --with-pcre --with-pcre-jit --with-http_ssl_module --with-http_stub_status_module --with-http_realip_module --with-http_auth_request_module --with-http_secure_link_module --with-http_random_index_module --with-http_addition_module --with-http_dav_module --with-http_geoip_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_degradation_module --with-http_v2_module --with-http_sub_module --with-http_flv_module --with-http_mp4_module --with-http_slice_module --with-stream --with-stream_ssl_module --with-stream_ssl_preread_module --with-stream_realip_module --with-stream_geoip_module=dynamic --with-mail --with-mail_ssl_module --with-threads --with-file-aio --with-compat --with-http_xslt_module=dynamic --with-http_image_filter_module=dynamic --with-http_geoip_module=dynamic --with-http_perl_module=dynamic --add-dynamic-module=/usr/src/nginx/ngx_devel_kit-0.3.1 --add-module=/usr/src/nginx/ngx_cache_purge-2.3 --add-dynamic-module=/usr/src/nginx/nginx_upstream_check_module-master --add-dynamic-module=/usr/src/nginx/lua-nginx-module-0.10.16rc5 --add-dynamic-module=/usr/src/nginx/headers-more-nginx-module-0.33 --add-dynamic-module=/usr/src/nginx/ngx_brotli --add-dynamic-module=/usr/src/nginx/ngx_http_auth_pam_module-1.5.1 --add-dynamic-module=/usr/src/nginx/echo-nginx-module-0.62rc1 --add-dynamic-module=/usr/src/nginx/ngx-fancyindex-0.4.4 --add-dynamic-module=/usr/src/nginx/nginx-dav-ext-module-3.0.0 --add-dynamic-module=/usr/src/nginx/ngx_http_substitutions_filter_module-0.6.4 --add-dynamic-module=/usr/src/nginx/nginx-upload-progress-module-0.9.2 --add-dynamic-module=/usr/src/nginx/nchan-1.2.7

Body:
It is possible that the compilation was not properly done. Try this post and compile accordingly again with adding all your modules.

If you're using Docker then this is OpenResty with Naxsi module compilation. You can safely add your modules and remove unwanted ones.

Check using nginx -V for all the compilation flags and if you see all the Lua modules.

I tried with following blocks on OpenResty and working properly.

set $upstream_new '';
rewrite_by_lua_block {
    ngx.var.upstream_new = "8.8.8.8";
}

and

set $upstream_new '';
access_by_lua '
    ngx.var.upstream_new = "8.8.8.8";
';

agentzh's Nginx Tutorials might be helpful if you're new.


问:
Flutter: How to make my dialog box scrollable?
I'm just new in flutter and now I have a problem in my dialog box. The problem is that my dialog box is becoming overflowed because of texts. So, now I want to make it scrollable so that texts still can be viewed. I already put a "SingleChildScrollView" on it but still doesn't work Please help.

My code:

```<code>_viewingRequest(dynamic data) async {
return showDialog(
    barrierDismissible: false,
    context: _scaffoldKey.currentContext,
    builder: (context) {
      return SingleChildScrollView(
        child: AlertDialog(
          contentPadding: EdgeInsets.only(left: 25, right: 25),
          title: Center(child: Text("Information")),
          shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.all(Radius.circular(20.0))),
          content: Container(
            height: 200,
            width: 300,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.stretch,
              children: <Widget>[
                SizedBox(
                  height: 20,
                ),
                Text(
                    'Name of requestor: ${data['Name_ofUser']}'
                ),
                Text(
                  'Description:',
                ),
                Text(
                  '${data['Help_Description']}',
                ),
                Text(
                  'Type of help needed: ${data['Help_TypeNeeded']}',
                )
              ],
            ),
          ),
          actions: <Widget>[
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Container(
                  width: MediaQuery.of(context).size.width * 0.20,
                  child: RaisedButton(
                    child: new Text(
                      'Fund',
                      style: TextStyle(color: Colors.white),
                    ),
                    color: Color(0xFF121A21),
                    shape: new RoundedRectangleBorder(
                      borderRadius: new BorderRadius.circular(30.0),
                    ),
                    onPressed: () {
                      saveIssue();
                      Navigator.of(context).pop();
                    },
                  ),
                ),
                SizedBox(
                  width: MediaQuery.of(context).size.width * 0.01,
                ),
                Padding(
                  padding: const EdgeInsets.only(right: 70.0),
                  child: Container(
                    width: MediaQuery.of(context).size.width * 0.20,
                    child: RaisedButton(
                      child: new Text(
                        'Cancel',
                        style: TextStyle(color: Colors.white),
                      ),
                      color: Color(0xFF121A21),
                      shape: new RoundedRectangleBorder(
                        borderRadius: new BorderRadius.circular(30.0),
                      ),
                      onPressed: () {
                        Navigator.of(context).pop();
                      },
                    ),
                  ),
                ),
                SizedBox(
                  height: MediaQuery.of(context).size.height * 0.02,
                ),
              ],
            )
          ],
        ),
      );
    });
 }
</code>```

My UI:

Link for my UI

答:
define the future dialog

```<code> Future<bool>_loadForm(BuildContext context) async {
  return await showDialog<bool>(
    context: context,
    builder: (context) {
      return Dialog(child: MyWidget(params));
    });
  }
</code>```

from a card in a list view call dialog from an onPressed event

```<code>  onPressed: () =>
  _loadChecklistForm(context).then((values)=>{})
</code>```

in myWidget in the build return a Dialog

```<code> final _formKey = GlobalKey<FormState>();
 List<Widget> formWidgetList = new List();

 formWidgetList.add(new Text('Hello world'));

 return Dialog(
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(20),
      ),
      elevation: 0.0,
      child: SingleChildScrollView(
        child:     Column(children:formWidgetList) ));
</code>```

Body:
I'm just new in flutter and now I have a problem in my dialog box. The problem is that my dialog box is becoming overflowed because of texts. So, now I want to make it scrollable so that texts still can be viewed. I already put a "SingleChildScrollView" on it but still doesn't work Please help.

My code:

_viewingRequest(dynamic data) async {
return showDialog(
    barrierDismissible: false,
    context: _scaffoldKey.currentContext,
    builder: (context) {
      return SingleChildScrollView(
        child: AlertDialog(
          contentPadding: EdgeInsets.only(left: 25, right: 25),
          title: Center(child: Text("Information")),
          shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.all(Radius.circular(20.0))),
          content: Container(
            height: 200,
            width: 300,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.stretch,
              children: <Widget>[
                SizedBox(
                  height: 20,
                ),
                Text(
                    'Name of requestor: ${data['Name_ofUser']}'
                ),
                Text(
                  'Description:',
                ),
                Text(
                  '${data['Help_Description']}',
                ),
                Text(
                  'Type of help needed: ${data['Help_TypeNeeded']}',
                )
              ],
            ),
          ),
          actions: <Widget>[
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Container(
                  width: MediaQuery.of(context).size.width * 0.20,
                  child: RaisedButton(
                    child: new Text(
                      'Fund',
                      style: TextStyle(color: Colors.white),
                    ),
                    color: Color(0xFF121A21),
                    shape: new RoundedRectangleBorder(
                      borderRadius: new BorderRadius.circular(30.0),
                    ),
                    onPressed: () {
                      saveIssue();
                      Navigator.of(context).pop();
                    },
                  ),
                ),
                SizedBox(
                  width: MediaQuery.of(context).size.width * 0.01,
                ),
                Padding(
                  padding: const EdgeInsets.only(right: 70.0),
                  child: Container(
                    width: MediaQuery.of(context).size.width * 0.20,
                    child: RaisedButton(
                      child: new Text(
                        'Cancel',
                        style: TextStyle(color: Colors.white),
                      ),
                      color: Color(0xFF121A21),
                      shape: new RoundedRectangleBorder(
                        borderRadius: new BorderRadius.circular(30.0),
                      ),
                      onPressed: () {
                        Navigator.of(context).pop();
                      },
                    ),
                  ),
                ),
                SizedBox(
                  height: MediaQuery.of(context).size.height * 0.02,
                ),
              ],
            )
          ],
        ),
      );
    });
 }

My UI:

Link for my UI

Body:
define the future dialog

 Future<bool>_loadForm(BuildContext context) async {
  return await showDialog<bool>(
    context: context,
    builder: (context) {
      return Dialog(child: MyWidget(params));
    });
  }

from a card in a list view call dialog from an onPressed event

  onPressed: () =>
  _loadChecklistForm(context).then((values)=>{})

in myWidget in the build return a Dialog

 final _formKey = GlobalKey<FormState>();
 List<Widget> formWidgetList = new List();

 formWidgetList.add(new Text('Hello world'));

 return Dialog(
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(20),
      ),
      elevation: 0.0,
      child: SingleChildScrollView(
        child:     Column(children:formWidgetList) ));


问:
Replacing a button
I tried to search my problem's solution but i couldnt't find it because of my bad english so i apologize if my question have an answer already.

I want place my button to there that i showed you in image. If possibly i want to do this with 'flex'. But doesn't matter.

Here is the code (i wrote just this section)

    *{
        padding:0;
        margin:0;
        box-sizing: border-box;
    }

    body{
        background-image: url('img/bg.png');
        font-family: 'Roboto', 'sans-serif';
    }

    a{
        text-decoration: none;
    }

    ul{
        list-style: none;
    }

    .container{
        padding-left:2rem;
        padding-right:2rem;
    }

    .container-deep{
        padding-left:8rem;
        padding-right:8rem;
    }

    /*about-me start*/

    .about-me .card{
        background:white;
        box-shadow:2px 2px 15px rgba(0,0,0,0.4);
        padding:4rem;
        display:flex;
        border-radius:10px;
    }

    .about-me .card-info{
        margin-left:5rem;
        display:flex;
        flex-direction: column;
    }

    .about-me .card .card-info h3{
        margin-top:.3rem;
        margin-bottom:1rem;
        font-size:.8rem;
        font-weight: bold;
    }

    .about-me .card .card-info p{
        opacity:.8;
        margin-bottom:1rem;
    }

    .about-me .card .card-info a{
        background:black;
        border: 1px solid black;
        color:white;
        padding: .7rem 1.5rem .7rem 1.5rem;
        align-self: flex-end;
        justify-self: center;
    }

    .about-me .card .card-info a:hover{
        background:white;
        color:black;
        border: 1px solid black;
    }

    .about-me .card .card-image img{
      width:125vh;
    }

    /*about-me end*/```
<pre class="snippet-code-html lang-html prettyprint-override"><code>    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta name="author" content="Emir">
        <meta name="keywords" content="full, stack, web, development">
        <meta name="description" content="Full Stack Web Development">
        <title>Full-Stack Web Site</title>
        <link rel="stylesheet" href="style.css">
        <link href="https://fonts.googleapis.com/css2?family=Roboto&display=swap" rel="stylesheet">
    </head>
    <body>
        <section>
            <div class="about-me container">
                <div class="card">
                    <div class="card-image">
                        <img src="https://images.pexels.com/photos/2941570/pexels-photo-2941570.jpeg?auto=compress&cs=tinysrgb&h=750&w=1260">
                    </div>
                    <div class="card-info">
                        <h1>About Me</h1>
                        <h3>Full-Stack Web Developer</h3>
                        <p>
                            Merhaba, ben Emir.
                            Kendimi web alanında geliştirebilmek adına sürekli araştırmalar yaparak full-stack developer olmayı hedefliyorum.
                            Yaptığım çalışmaları ve sahip olduğum referansları sunabilmek adına bu siteyi yazdım.
                        </p>
                        <p>Lorem ipsum, dolor sit amet consectetur adipisicing elit. Natus illo deleniti nostrum praesentium dignissimos pariatur magnam ipsum perferendis aut ab. Voluptatum, ut sapiente. Fuga dolor corporis quis temporibus quos qui.</p>

                        Visit My Blog
                    </div>
                </div>
            </div>
        </section>

    </body>
    </html></code>```

答:
Using propriety position:relative|absolute to reslove your problem.
Add this in your code :

```<code>//Your button "Visit My Blog"
a{
    position: absolute;
    bottom: 0;
    right: 0;
}

//Your content
div.card-info{
    position: relative;
}
</code>```

Title: Replacing a button

Body:
I tried to search my problem's solution but i couldnt't find it because of my bad english so i apologize if my question have an answer already.

I want place my button to there that i showed you in image. If possibly i want to do this with 'flex'. But doesn't matter.

Here is the code (i wrote just this section)

    *{
        padding:0;
        margin:0;
        box-sizing: border-box;
    }

    body{
        background-image: url('img/bg.png');
        font-family: 'Roboto', 'sans-serif';
    }

    a{
        text-decoration: none;
    }

    ul{
        list-style: none;
    }

    .container{
        padding-left:2rem;
        padding-right:2rem;
    }

    .container-deep{
        padding-left:8rem;
        padding-right:8rem;
    }

    /*about-me start*/

    .about-me .card{
        background:white;
        box-shadow:2px 2px 15px rgba(0,0,0,0.4);
        padding:4rem;
        display:flex;
        border-radius:10px;
    }

    .about-me .card-info{
        margin-left:5rem;
        display:flex;
        flex-direction: column;
    }

    .about-me .card .card-info h3{
        margin-top:.3rem;
        margin-bottom:1rem;
        font-size:.8rem;
        font-weight: bold;
    }

    .about-me .card .card-info p{
        opacity:.8;
        margin-bottom:1rem;
    }

    .about-me .card .card-info a{
        background:black;
        border: 1px solid black;
        color:white;
        padding: .7rem 1.5rem .7rem 1.5rem;
        align-self: flex-end;
        justify-self: center;
    }

    .about-me .card .card-info a:hover{
        background:white;
        color:black;
        border: 1px solid black;
    }

    .about-me .card .card-image img{
      width:125vh;
    }

    /*about-me end*/

    <!DOCTYPE html>

        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta name="author" content="Emir">
        <meta name="keywords" content="full, stack, web, development">
        <meta name="description" content="Full Stack Web Development">
        <title>Full-Stack Web Site</title>
        <link rel="stylesheet" href="style.css">
        <link href="https://fonts.googleapis.com/css2?family=Roboto&display=swap" rel="stylesheet">

About Me

Full-Stack Web Developer

                            Merhaba, ben Emir.
                            Kendimi web alanında geliştirebilmek adına sürekli araştırmalar yaparak full-stack developer olmayı hedefliyorum.
                            Yaptığım çalışmaları ve sahip olduğum referansları sunabilmek adına bu siteyi yazdım.

Lorem ipsum, dolor sit amet consectetur adipisicing elit. Natus illo deleniti nostrum praesentium dignissimos pariatur magnam ipsum perferendis aut ab. Voluptatum, ut sapiente. Fuga dolor corporis quis temporibus quos qui.

                        Visit My Blog

Body:
Using propriety position:relative|absolute to reslove your problem.
Add this in your code :

//Your button "Visit My Blog"
a{
    position: absolute;
    bottom: 0;
    right: 0;
}

//Your content
div.card-info{
    position: relative;
}


问:
Io language 'apply arguments'
In the Io programming language, is there an equivalent to lisp's apply function.

So for example I have a method to wrap writeln :

```<code>mymeth := method(
              //do some extra stuff

             writeln(call message arguments))
)
</code>```

At the moment this just prints the list, and doesn't evaluate it's contents as if they were it's own args.

答:
is there an equivalent to lisp's apply function?

Have a look at perform & performWithArgList methods.

To step back a bit you can replicate Lisp's FUNCALL in a few different ways in Io:

1 - Passing a function ie. block():

```<code>plotf := method (fn, min, max, step,
    for (i, min, max, step,
        fn call(i) roundDown repeat(write("*"))
        writeln
    )
)

plotf( block(n, n exp), 0, 4, 1/2 )
</code>```

2 - Passing a message:

```<code>plotm := method (msg, min, max, step,
    for (i, min, max, step,
        i doMessage(msg) roundDown repeat(write("*"))
        writeln
    )
)

plotm( message(exp), 0, 4, 1/2 )
</code>```

3 - passing the function name as a string:

```<code>plots := method (str, min, max, step,
    for (i, min, max, step,
        i perform(str) roundDown repeat(write("*"))
        writeln
    )
)

plots( "exp", 0, 4, 1/2 )
</code>```

So from all this you could create a Lisp APPLY like so:

```<code>apply := method (
    args := call message argsEvaluatedIn(call sender)
    fn   := args removeFirst
    performWithArgList( fn, args )
)

apply( "plotf", block(n, n exp), 0, 4, 1/2 )

apply( "plotm", message(exp), 0, 4, 1/2 )

apply( "plots", "exp", 0, 4, 1/2 )
</code>```

ContentLicense: CC BY-SA 2.5

Title: Io language 'apply arguments'

Body:
In the Io programming language, is there an equivalent to lisp's apply function.

So for example I have a method to wrap writeln :

mymeth := method(
              //do some extra stuff

             writeln(call message arguments))
)

At the moment this just prints the list, and doesn't evaluate it's contents as if they were it's own args.

Body:
is there an equivalent to lisp's apply function?

Have a look at perform & performWithArgList methods.

To step back a bit you can replicate Lisp's FUNCALL in a few different ways in Io:

1 - Passing a function ie. block():

plotf := method (fn, min, max, step,
    for (i, min, max, step,
        fn call(i) roundDown repeat(write("*"))
        writeln
    )
)

plotf( block(n, n exp), 0, 4, 1/2 )

2 - Passing a message:

plotm := method (msg, min, max, step,
    for (i, min, max, step,
        i doMessage(msg) roundDown repeat(write("*"))
        writeln
    )
)

plotm( message(exp), 0, 4, 1/2 )

3 - passing the function name as a string:

plots := method (str, min, max, step,
    for (i, min, max, step,
        i perform(str) roundDown repeat(write("*"))
        writeln
    )
)

plots( "exp", 0, 4, 1/2 )

So from all this you could create a Lisp APPLY like so:

apply := method (
    args := call message argsEvaluatedIn(call sender)
    fn   := args removeFirst
    performWithArgList( fn, args )
)

apply( "plotf", block(n, n exp), 0, 4, 1/2 )

apply( "plotm", message(exp), 0, 4, 1/2 )

apply( "plots", "exp", 0, 4, 1/2 )


问:
How to access c# model data in javascript
New to ASP.NET MVC 3. Started with a tutorial and am mirroring the code for my own model. I Can access the model data in my Index.cshtml file in the script but not in my javascript functions.

My Model

```<code>using System.ComponentModel.DataAnnotations;

namespace DotNetCoreSqlDb.Models

{
    public class Glassblower
    {
        public int ID { get; set; }
        public string TeacherID { get; set; }
        public string Lat { get; set; }
        public string Lng { get; set; }
        public string Name { get; set; }
        public string Bio { get; set; }
        public string Url { get; set; }
        public string Coe { get; set; }
        public string SubscriptionLevel { get; set; }
        public DateTime StartDate { get; set; }

    }
}
</code>```

My controller Index method:

```<code>// GET: Glassblowers
        public async Task<IActionResult> Index()
        {
            return View(await _context.Glassblower.ToListAsync());
        }
</code>```

My Index.cshtml

```<code>@model IEnumerable<DotNetCoreSqlDb.Models.Glassblower>

@{
    ViewData["Title"] = "Index";
}

<script id="gmapsrc" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBSJAns0GMR5gK60kw2c3IAnouZpyu_QHw"
></script>

<div class="row map-and-readout-container">
     <div id="timescale-map" class="timescale-map"></div>
    <div id="readout" class="readout">

       @foreach (var item in Model) {
               <div>
                @Html.DisplayFor(modelItem => item.Name)
               </div>
        }
    </div>

</div>
<script>
 var model = @Html.Raw(Json.Encode(@Model));
</script>

</code>```

Currently I am able to render the item names on the page. My goal is to loop through the model in a javascript function in my  tag.

I've tried accessing it with

```<code>var model = @Html.Raw(Json.Encode(@Model))
</code>```

but when I click run in Visual Studio Mac I get this build error

```<code>'IJsonHelper' does not contain a definition for 'Encode' and no accessible extension method 'Encode' accepting a first argument of type 'IJsonHelper' could be found (are you missing a using directive or an assembly reference?) (CS1061) (DotNetCoreSqlDb)
</code>```

Any Tips would be greatly appreciated. Thanks

答:
It's beacause your models is not json, you can try to put it in a array or list like this.

```<code><script>
    var availableTags = [];
    @foreach(var model in Model.Model)
    {
        @:availableTags.push(decodeHtml("@model"));
    }
</script>
</code>```

Body:
New to ASP.NET MVC 3. Started with a tutorial and am mirroring the code for my own model. I Can access the model data in my Index.cshtml file in the script but not in my javascript functions.

My Model

using System.ComponentModel.DataAnnotations;

namespace DotNetCoreSqlDb.Models

{
    public class Glassblower
    {
        public int ID { get; set; }
        public string TeacherID { get; set; }
        public string Lat { get; set; }
        public string Lng { get; set; }
        public string Name { get; set; }
        public string Bio { get; set; }
        public string Url { get; set; }
        public string Coe { get; set; }
        public string SubscriptionLevel { get; set; }
        public DateTime StartDate { get; set; }

    }
}

My controller Index method:

// GET: Glassblowers
        public async Task<IActionResult> Index()
        {
            return View(await _context.Glassblower.ToListAsync());
        }

My Index.cshtml

@model IEnumerable<DotNetCoreSqlDb.Models.Glassblower>

@{
    ViewData["Title"] = "Index";
}

       @foreach (var item in Model) {

                @Html.DisplayFor(modelItem => item.Name)

        }

Currently I am able to render the item names on the page. My goal is to loop through the model in a javascript function in my  tag.

I've tried accessing it with

var model = @Html.Raw(Json.Encode(@Model))

but when I click run in Visual Studio Mac I get this build error

'IJsonHelper' does not contain a definition for 'Encode' and no accessible extension method 'Encode' accepting a first argument of type 'IJsonHelper' could be found (are you missing a using directive or an assembly reference?) (CS1061) (DotNetCoreSqlDb)

Any Tips would be greatly appreciated. Thanks

Body:
It's beacause your models is not json, you can try to put it in a array or list like this.

<script>
    var availableTags = [];
    @foreach(var model in Model.Model)
    {
        @:availableTags.push(decodeHtml("@model"));
    }
</script>


问:
pysftp SFTP file transfert is being suspended after 30MB
I'am trying to transfer files from SFTP to Local and for some reasons, the transfer of files with more then 30MB is suspended automatically when acheiving the 27-28 MB without getting any error message.

This is my code :

```<code>    for entry in sftp.listdir_attr(remoteFilePath):
        filepath = remoteFilePath + '/' + entry.filename
        sftp.get(filepath, os.path.join(localFilePath, entry.filename))
        sftp.remove(filepath)
</code>```

答:
Well this is the solution :</p>

```<code>with sftp.open(filepath, "rb") as fr, \
     open(os.path.join(localFilePath, entry.filename), "wb") as fl:
    while True:
        data = fr.read(1024)
        fl.write(data)
        if len(data) == 0:
            break
</code>```

Body:
I'am trying to transfer files from SFTP to Local and for some reasons, the transfer of files with more then 30MB is suspended automatically when acheiving the 27-28 MB without getting any error message.

This is my code :

    for entry in sftp.listdir_attr(remoteFilePath):
        filepath = remoteFilePath + '/' + entry.filename
        sftp.get(filepath, os.path.join(localFilePath, entry.filename))
        sftp.remove(filepath)

Body:
Well this is the solution :

with sftp.open(filepath, "rb") as fr, \
     open(os.path.join(localFilePath, entry.filename), "wb") as fl:
    while True:
        data = fr.read(1024)
        fl.write(data)
        if len(data) == 0:
            break


问:
Is there is a way can hide the column in a Oracle View pivot when the whole column are 0 or null?
So in Oracle DB I run this query:

```<code>  SELECT * FROM (
SELECT
    WHSE,
    OLNTYPE,
    zone,
    LOCNID,
    COUNT(LOCN_BRCD) AS TOTLOCNS
    FROM IC_MST_NUTSANDBOLTS
    GROUP BY WHSE,
             OLNTYPE,
             ZONE,
             LOCNID
    ORDER BY OLNTYPE
                ) c1
PIVOT(
    COUNT(LOCNID)
    FOR (ZONE) IN
(null,
'G2',
'H2',
'P2',
'F2',
'DA',
'P3',
'A1',
'H5',
'C1',
'F1',
'P1',
'FR',
'D1',
'F3',
'G3',
'MP',
'R1',
'H1',
'H6',
'G5',
'G1',
'M1',
'B1'));
</code>```

and here is the query result:

I want to create a view on this, but as a result some column are entirly 0 values.

So is there is a way can hide a column from this, or not getting show up if the whole column are 0?

答:
The same question was answered here Hide column if any value is null or zero via proc

  sql or view

You can't hide a column dynamically unless you use dynamic SQL.
This quickly gets complicated: what if the zeros are in different columns on different rows? What should the output be

If the zeros/nulls are in the same column, then you can "hide" a column by not selecting it.

Body:
So in Oracle DB I run this query:

  SELECT * FROM (
SELECT
    WHSE,
    OLNTYPE,
    zone,
    LOCNID,
    COUNT(LOCN_BRCD) AS TOTLOCNS
    FROM IC_MST_NUTSANDBOLTS
    GROUP BY WHSE,
             OLNTYPE,
             ZONE,
             LOCNID
    ORDER BY OLNTYPE
                ) c1
PIVOT(
    COUNT(LOCNID)
    FOR (ZONE) IN
(null,
'G2',
'H2',
'P2',
'F2',
'DA',
'P3',
'A1',
'H5',
'C1',
'F1',
'P1',
'FR',
'D1',
'F3',
'G3',
'MP',
'R1',
'H1',
'H6',
'G5',
'G1',
'M1',
'B1'));

and here is the query result:

I want to create a view on this, but as a result some column are entirly 0 values.

So is there is a way can hide a column from this, or not getting show up if the whole column are 0?