问:
Consuming a Razor Class Library with Partial Views in .Net Framework Project
I have recently come across Razor Class Libraries and am not 100% sure of what can / can't be achieved with them, but am very much liking the concept of being able to create views (and partial views) which can be shared within multiple web projects.

However, whilst I know a bit of C# and am quite familiar with the conversion tools, I am 1000 times more proficient with VB.Net and consequently most of my work is coded that way. .NET Core, as far as I can deduce does not support VB.NET.

I followed the tutorial and downloaded the sample code from here https://learn.microsoft.com/en-us/aspnet/core/razor-pages/ui-class?view=aspnetcore-3.1&tabs=visual-studio

With this I was able to build a solution containing a RCL and a .NetCore website which uses views and partial views from the RCL.

I was able to build multiple .NETCore Websites and all I had to do was to add a reference to the RCL Project and they would all use the shared partial views in the RCL... everything worked well.

EXCEPT, I don't want a .NETCore website project because I want to stick with VB.NET, so I read up and am told that the RCL I have created using .netstandard2.0 should be compatible with the .Net Framework.

Note; Essentially, for the immediate requirements, I intend to use an RCL predominently for creating partial views to be shared across multiple projects. I am happy to create them using C# for the project logic, and a lot of my code logic already exists in VB class libraries which I can import, but don't want to have to rewrite or relearn everything I have already done in the main bulk of my projects.

Upgrading all my work to .NetCore would be a nightmare in one go anyway...

So....

I created a VB Web Application targeting .Net Framework 4.7.2.

I add a reference to my RCL

I ran a Build to check there were no version conflicts or reference incompatibilities

I ran the website to check no build errors that weren't caught by Visual Studio

All the above worked fine, the reference added OK, no problems at all.

BUT... I cannot work out how to get the partial views in the RCL to be accessible to the website.

I am constantly getting the error

```<code>The partial view '****' was not found or no view engine supports the searched locations.
</code>```

Can anyone tell me

How to hook up a Razor Class Library in order for Partial Views to be consumed in a .Net Framework Project?

Am I (quite likely knowing me) trying to do something that is simply not meant to work like that?!

EDIT...

Quite reasonably asked by Ben in the comments below, to clarify exactly what I'm doing

Firstly. I am literally just experimenting with a new Solution, so each time I am adding Projects I am literally just going to "Add New project  > select". I am not editing the projects beyond the templates created by Visual Studio (2019 Community Edition if it makes any difference) except to add the reference to my RCl.

The RCL has a single partial view which I am trying to display, it's contents are:

```<code>@using RazorUIClassLib
<h1>This is nothing but a test</h1>
</code>```

Where obviously RazorUIClassLib is the name of the RCL... there is nothing else in it at all at this stage.

File structure is

```<code>> Pages > Shared > Test.cshtml
</code>```

I have a C# .NETCore Project called WebApp1 which is the exact Project from the example downloaded from the link above has a relevant file structure

```<code>> Pages > Index.cshtml
</code>```

In Index.cshtml I have added this line:

```<code><partial name="Test"/>
</code>```

(Note; Visual Studio seems a little iffy about finding the Test file as intellisense (ReSharper) is saying cannot resolve partial view'Test', but it runs fine)

I have a second C# .netcore project which I added to make sure there wasn't something "special" about the one I downloaded from the example code, that is structured exactly as the Visual Studio Template, and has a slightly different file structure:

Views > Home > Index.cshtml

The same single line of code is added to this file as above and works just the same (all I did after adding this brand new project was to add this line and the reference to my RCL Project)

The problem Project is a VB Project, which obviously is targeting .Net Framework NOT CORE. It is literally just the default file structure created by Visual Studio when adding a new MVC Project to the Solution, so we have

Views > Home > Index.vbhtml

Again, I have done nothing to it except to add the reference to my RCL Project and this line:

```<code>@Html.Partial("Test")
</code>```

I have also tried

```<code>@Html.Partial("/Pages/Shared/Test")
@Html.Partial("~/Pages/Shared/Test")
@Html.Partial("/RazorUIClassLib/Pages/Shared/Test")
@Html.Partial("~/RazorUIClassLib/Pages/Shared/Test")
</code>```

And also all the above with the .cshtml file extension.

In all cases I get varying forms of this error:

```<code>The partial view 'Test' was not found or no view engine supports the searched locations. The following locations were searched:
~/Views/Home/Test.aspx
~/Views/Home/Test.ascx
~/Views/Shared/Test.aspx
~/Views/Shared/Test.ascx
~/Views/Home/Test.cshtml
~/Views/Home/Test.vbhtml
~/Views/Shared/Test.cshtml
~/Views/Shared/Test.vbhtml
</code>```

Clearly from the error it is expecting to find the Partial in the Views Directory, but as I mention, if I add the full path I still get the same error but with different "I tried looking here" type notes.

I keep saying that I haven't changed anything to clarify that I have not made any routing alterations... am wondering if I should, but if so, not sure what!

答: So it looks like my assumptions were wrong. Even though they can target .NET Standard, RCL's are an ASP.NET Core feature only. You can see on their documentation page that the only versions supported are ASP.NET Core products. However you would be able to share view models and business logic in the RCL but that's the extent of it.

Body:
I have recently come across Razor Class Libraries and am not 100% sure of what can / can't be achieved with them, but am very much liking the concept of being able to create views (and partial views) which can be shared within multiple web projects.

However, whilst I know a bit of C# and am quite familiar with the conversion tools, I am 1000 times more proficient with VB.Net and consequently most of my work is coded that way. .NET Core, as far as I can deduce does not support VB.NET.

I followed the tutorial and downloaded the sample code from here https://learn.microsoft.com/en-us/aspnet/core/razor-pages/ui-class?view=aspnetcore-3.1&tabs=visual-studio

With this I was able to build a solution containing a RCL and a .NetCore website which uses views and partial views from the RCL.

I was able to build multiple .NETCore Websites and all I had to do was to add a reference to the RCL Project and they would all use the shared partial views in the RCL... everything worked well.

EXCEPT, I don't want a .NETCore website project because I want to stick with VB.NET, so I read up and am told that the RCL I have created using .netstandard2.0 should be compatible with the .Net Framework.

Note; Essentially, for the immediate requirements, I intend to use an RCL predominently for creating partial views to be shared across multiple projects. I am happy to create them using C# for the project logic, and a lot of my code logic already exists in VB class libraries which I can import, but don't want to have to rewrite or relearn everything I have already done in the main bulk of my projects.

Upgrading all my work to .NetCore would be a nightmare in one go anyway...

So....

I created a VB Web Application targeting .Net Framework 4.7.2.

I add a reference to my RCL

I ran a Build to check there were no version conflicts or reference incompatibilities

I ran the website to check no build errors that weren't caught by Visual Studio

All the above worked fine, the reference added OK, no problems at all.

BUT... I cannot work out how to get the partial views in the RCL to be accessible to the website.

I am constantly getting the error

The partial view '****' was not found or no view engine supports the searched locations.

Can anyone tell me

How to hook up a Razor Class Library in order for Partial Views to be consumed in a .Net Framework Project?

Am I (quite likely knowing me) trying to do something that is simply not meant to work like that?!

EDIT...

Quite reasonably asked by Ben in the comments below, to clarify exactly what I'm doing

Firstly. I am literally just experimenting with a new Solution, so each time I am adding Projects I am literally just going to "Add New project  > select". I am not editing the projects beyond the templates created by Visual Studio (2019 Community Edition if it makes any difference) except to add the reference to my RCl.

The RCL has a single partial view which I am trying to display, it's contents are:

@using RazorUIClassLib

This is nothing but a test

Where obviously RazorUIClassLib is the name of the RCL... there is nothing else in it at all at this stage.

File structure is

> Pages > Shared > Test.cshtml

I have a C# .NETCore Project called WebApp1 which is the exact Project from the example downloaded from the link above has a relevant file structure

> Pages > Index.cshtml

In Index.cshtml I have added this line:

<partial name="Test"/>

(Note; Visual Studio seems a little iffy about finding the Test file as intellisense (ReSharper) is saying cannot resolve partial view'Test', but it runs fine)

I have a second C# .netcore project which I added to make sure there wasn't something "special" about the one I downloaded from the example code, that is structured exactly as the Visual Studio Template, and has a slightly different file structure:

Views > Home > Index.cshtml

The same single line of code is added to this file as above and works just the same (all I did after adding this brand new project was to add this line and the reference to my RCL Project)

The problem Project is a VB Project, which obviously is targeting .Net Framework NOT CORE. It is literally just the default file structure created by Visual Studio when adding a new MVC Project to the Solution, so we have

Views > Home > Index.vbhtml

Again, I have done nothing to it except to add the reference to my RCL Project and this line:

@Html.Partial("Test")

I have also tried

@Html.Partial("/Pages/Shared/Test")
@Html.Partial("~/Pages/Shared/Test")
@Html.Partial("/RazorUIClassLib/Pages/Shared/Test")
@Html.Partial("~/RazorUIClassLib/Pages/Shared/Test")

And also all the above with the .cshtml file extension.

In all cases I get varying forms of this error:

The partial view 'Test' was not found or no view engine supports the searched locations. The following locations were searched:
~/Views/Home/Test.aspx
~/Views/Home/Test.ascx
~/Views/Shared/Test.aspx
~/Views/Shared/Test.ascx
~/Views/Home/Test.cshtml
~/Views/Home/Test.vbhtml
~/Views/Shared/Test.cshtml
~/Views/Shared/Test.vbhtml

Clearly from the error it is expecting to find the Partial in the Views Directory, but as I mention, if I add the full path I still get the same error but with different "I tried looking here" type notes.

I keep saying that I haven't changed anything to clarify that I have not made any routing alterations... am wondering if I should, but if so, not sure what!


来源: stackexchange

问:
.NET Entity Framework and stored procedures
I'm new to EF and I got a bit of a philosophical question: all the books, videos, online courses etc - go on and on about working directly with table databases - i.e. with classes that correspond directly to them. How the class I create will abstract away the tables and all that. and then the entire books or courses show all the things I can do to a class that will in turn happen at the database table - the CRUD operations and such.

And I'm thinking - we never work directly with tables, and there are reasons for it. Its such a bad idea - be for us to do it manually or for a framework to handle it for us. We always work with stored procedures, which is the way it should be done (they return SELECTs which JOINs from a bunch of tables typically, and this way we exploit the relational model and encapsulate it. we give permissions to execute stored procedures, not directly, full access to tables, etc etc...)

But all the EF material is 99% on OR mapping which is code-to-physical table, and then a quick mention that its possible to do it with stored procedures.

So... is that the thinking behind the EF philosophy? did I get it right and... what were MS people thinking??

Thank you

答:
Please first of all note that you can also have classes representing Views, and also you can execute stored procedures using EF.

And also when you do joins or use navigational properties like category.Products, note that the same joins are being created by EF and executed.

So EF is just a way to make it easier to work with database, but it is not replacing the functionalities we had. I you want something to work with stored procedures do it. This is an example from my real code that uses stored procedure:

```<code>List<Flower> flowers =  = context.Flowers.FromSqlRaw("GetFlowers {0}, {1}, {2}", domain, country, currency).ToList();
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Please first of all note that you can also have classes representing Views, and also you can execute stored procedures using EF.

And also when you do joins or use navigational properties like category.Products, note that the same joins are being created by EF and executed.

So EF is just a way to make it easier to work with database, but it is not replacing the functionalities we had. I you want something to work with stored procedures do it. This is an example from my real code that uses stored procedure:

List<Flower> flowers =  = context.Flowers.FromSqlRaw("GetFlowers {0}, {1}, {2}", domain, country, currency).ToList();


问:
How to use router.replace inside the client side of your app?
I'm trying to use Next.js router to redirect unauthorized users from accessing certain pages that are wrapped inside the AdminLayout component, but I got this error.

Error: No router instance found. You should only use "next/router"
  inside the client side of your app.

```<code>// Other imports
import Router from "next/router";

class AdminLayout extends React.Component {
  render() {
    const { currentUser } = this.props;

    if (currentUser === undefined) {
      console.log(currentUser);
      return null;
    }

    if (currentUser == null) {
      console.log(currentUser);
      //this is how I tried to redirect
      Router.replace("/admin/login");
    }
    return (
      // Other irrelevant code
    );
  }
}

const mapStateToProps = (state) => ({
  currentUser: state.user.currentUser,
});

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

Any way to fix this?

答:
render method is executed in the server as well, therefore you get the exception.

Usually it is a bad practice to put side effect (such as redirects) in the render method.

You should put it inside componentDidMount which runs only on the client side.

// Other imports
import Router from "next/router";

class AdminLayout extends React.Component {
  componentDidMount() {
    const {currentUser} = this.props;

    if (currentUser === undefined) {
      console.log(currentUser);
      return null;
    }

    if (currentUser == null) {
      console.log(currentUser);
      //this is how I tried to redirect
      Router.replace('/admin/login');
    }
  }
  render() {
    const {currentUser} = this.props;

    if (currentUser === undefined) {
      console.log(currentUser);
      return null;
    }
    return (
      // Other irrelevant code
    );
  }
}

const mapStateToProps = (state) => ({
  currentUser: state.user.currentUser,
});

export default connect(mapStateToProps)(AdminLayout);
```

<p>If you want to redirect on in the server side you will need to use <code>getInitialProps</code> / <code>getServerProps</code> which runs on <strong>the server</strong>, these methods on the server side it gets the server <code>request</code> & <code>response</code> which enables you to redirect from the server.</p>

```class AdminLayout extends React.Component {
   static getInitialProps ({ res }) {
      if(someCondition) {
        res.redirect('/your-path');
      }
   }
   ...
}
```

Body:
I'm trying to use Next.js router to redirect unauthorized users from accessing certain pages that are wrapped inside the AdminLayout component, but I got this error.

Error: No router instance found. You should only use "next/router"
  inside the client side of your app.

// Other imports
import Router from "next/router";

class AdminLayout extends React.Component {
  render() {
    const { currentUser } = this.props;

    if (currentUser === undefined) {
      console.log(currentUser);
      return null;
    }

    if (currentUser == null) {
      console.log(currentUser);
      //this is how I tried to redirect
      Router.replace("/admin/login");
    }
    return (
      // Other irrelevant code
    );
  }
}

const mapStateToProps = (state) => ({
  currentUser: state.user.currentUser,
});

export default connect(mapStateToProps)(AdminLayout);

Any way to fix this?

Body:
render method is executed in the server as well, therefore you get the exception.

Usually it is a bad practice to put side effect (such as redirects) in the render method.

You should put it inside componentDidMount which runs only on the client side.

// Other imports
import Router from "next/router";

class AdminLayout extends React.Component {
  componentDidMount() {
    const {currentUser} = this.props;

    if (currentUser === undefined) {
      console.log(currentUser);
      return null;
    }

    if (currentUser == null) {
      console.log(currentUser);
      //this is how I tried to redirect
      Router.replace('/admin/login');
    }
  }
  render() {
    const {currentUser} = this.props;

    if (currentUser === undefined) {
      console.log(currentUser);
      return null;
    }
    return (
      // Other irrelevant code
    );
  }
}

const mapStateToProps = (state) => ({
  currentUser: state.user.currentUser,
});

export default connect(mapStateToProps)(AdminLayout);

If you want to redirect on in the server side you will need to use getInitialProps / getServerProps which runs on the server, these methods on the server side it gets the server request & response which enables you to redirect from the server.

class AdminLayout extends React.Component {
   static getInitialProps ({ res }) {
      if(someCondition) {
        res.redirect('/your-path');
      }
   }
   ...
}


问:
In my code I am having a dilemma with the 'Colorama' module specifically changing my line color using the input() command
Here is the code: IM USING VISUAL STUDIO CODE BTW

```<code>import requests
from colorama import Fore, Style, init
from time import sleep

init()

print(f'{Fore.RED}WELCOME TO JYSKO\'S WEBSITE CHECKER!')
print(f'{Fore.YELLOW}Add my discord: ')
print(f'{Fore.YELLOW}Jy$ko#0420')

def main():
    try:
        site = input(f'{Fore.RED}Please Enter The Website Here: ')
        response = requests.get(site)
        requests.get(site)
        while True:
            if response.status_code == 200:
                print(f'{Fore.GREEN}Online!')
                sleep(1)
            else:
                print(f'{Fore.RED}Offline!')
                sleep(1)
    except:
        print(f'{Fore.RED}Unknown Error Occured.')
main()
</code>```

The problem is located in the function named 'Main()'.  As you can see in the previous lines of code, the last color used is '{Fore.YELLOW}' and in the input() command in this function I request the color RED but when executed still comes out as yellow.  I have tried most solutions available on this platform and am seeking help.
When the code is executed this is what spits out:

```<code>(RED TEXT->)WELCOME TO JYSKO'S WEBSITE CHECKER!
(YELLOW TEXT->)Add my discord:
(YELLOW TEXT->)Jysko#0420
(SUPPOSE TO BE RED BUT RETURNS YELLOW->){Fore.RED}Please Enter The Website Here:
</code>```

答:
I think you missed the f-string for the input.

```<code>input(f'{Fore.YELLOW}...')
</code>```

Without the 'f' at the beginning of the string, {Fore.YELLOW} is just treated as part of the string. However, with the f-string, then the contents inside the curly braces are more or less treated the same as having:

```<code>input(Fore.YELLOW + 'your string contents')
</code>```

EDIT: Worked with OP and found a strange error with Windows. The above works on Mac and Linux, but not Windows -- There seems to be a quirk on Windows python3.8 that prevents colorama from setting the text color in input(). However there is a workaround by adding a print statement first:

```<code>print(Fore.RED, end='') # Changes color, but doesn't add new line
input('original text')
</code>```

Body:
Here is the code: IM USING VISUAL STUDIO CODE BTW

import requests
from colorama import Fore, Style, init
from time import sleep

init()

print(f'{Fore.RED}WELCOME TO JYSKO\'S WEBSITE CHECKER!')
print(f'{Fore.YELLOW}Add my discord: ')
print(f'{Fore.YELLOW}Jy$ko#0420')

def main():
    try:
        site = input(f'{Fore.RED}Please Enter The Website Here: ')
        response = requests.get(site)
        requests.get(site)
        while True:
            if response.status_code == 200:
                print(f'{Fore.GREEN}Online!')
                sleep(1)
            else:
                print(f'{Fore.RED}Offline!')
                sleep(1)
    except:
        print(f'{Fore.RED}Unknown Error Occured.')
main()

The problem is located in the function named 'Main()'.  As you can see in the previous lines of code, the last color used is '{Fore.YELLOW}' and in the input() command in this function I request the color RED but when executed still comes out as yellow.  I have tried most solutions available on this platform and am seeking help.
When the code is executed this is what spits out:

(RED TEXT->)WELCOME TO JYSKO'S WEBSITE CHECKER!
(YELLOW TEXT->)Add my discord:
(YELLOW TEXT->)Jysko#0420
(SUPPOSE TO BE RED BUT RETURNS YELLOW->){Fore.RED}Please Enter The Website Here:

Body:
I think you missed the f-string for the input.

input(f'{Fore.YELLOW}...')

Without the 'f' at the beginning of the string, {Fore.YELLOW} is just treated as part of the string. However, with the f-string, then the contents inside the curly braces are more or less treated the same as having:

input(Fore.YELLOW + 'your string contents')

EDIT: Worked with OP and found a strange error with Windows. The above works on Mac and Linux, but not Windows -- There seems to be a quirk on Windows python3.8 that prevents colorama from setting the text color in input(). However there is a workaround by adding a print statement first:

print(Fore.RED, end='') # Changes color, but doesn't add new line
input('original text')


问:
Firestore get data once then update. looping of data Snapshot
The data keeps on looping. how can i make it read only once?</p>

```<code> onAddToCart() {
        const { id, product, authUser, cart, shippingType } = this.state;

  this.props.firebase.cartItems().doc(authUser.uid).collection('total').doc('total').onSnapshot(snapshot => {
            this.props.firebase.cartItems().doc(authUser.uid).collection("total").doc("total").update({'total': snapshot.data().total + (product.salePrice > 0 ? product.salePrice : product.price * 1)
        }).then(() => {

        cogoToast.success("Added to store list");

    });

                console.log("doc info",snapshot.data().total)

        })

    }
</code>```

答:
I just found an answer to this. so instead of onsnapchat I changed it into get(). here is the new code.</p>

```<code>this.props.firebase.cartItems().doc(authUser.uid).collection('total').get().then(snap => {
    snap.forEach(doc => {
        console.log(doc.data());
        this.props.firebase.cartItems().doc(authUser.uid).collection("total").doc("total").update({'total': doc.data().total + (product.salePrice > 0 ? product.salePrice : product.price * 1)})

    });
});
</code>```

Body:
The data keeps on looping. how can i make it read only once?

 onAddToCart() {
        const { id, product, authUser, cart, shippingType } = this.state;

  this.props.firebase.cartItems().doc(authUser.uid).collection('total').doc('total').onSnapshot(snapshot => {
            this.props.firebase.cartItems().doc(authUser.uid).collection("total").doc("total").update({'total': snapshot.data().total + (product.salePrice > 0 ? product.salePrice : product.price * 1)
        }).then(() => {

        cogoToast.success("Added to store list");

    });

                console.log("doc info",snapshot.data().total)

        })

    }

Body:
I just found an answer to this. so instead of onsnapchat I changed it into get(). here is the new code.

this.props.firebase.cartItems().doc(authUser.uid).collection('total').get().then(snap => {
    snap.forEach(doc => {
        console.log(doc.data());
        this.props.firebase.cartItems().doc(authUser.uid).collection("total").doc("total").update({'total': doc.data().total + (product.salePrice > 0 ? product.salePrice : product.price * 1)})

    });
});


问:
How to convert HierarchyId to Child/Parent (Tree) structure in C# dotnet?
For some reason such as performance, I have to use HiarachyId in my database. I have to convert the HierarchyId data type to JSON to show up in FancyTree.

I Use the solution here but won't work. My code was

```<code>static void Main(string[] args)
    {

        {

        var dd = new List<Field>();
        dd.Add(new Field(1, "Earth", HierarchyId.Parse("/")));
        dd.Add(new Field(2, "Europe", HierarchyId.Parse("/1/")));
        dd.Add(new Field(3, "South America", HierarchyId.Parse("/2/")));
        dd.Add(new Field(4, "Antarctica", HierarchyId.Parse("/3/")));
        dd.Add(new Field(5, "Brazil", HierarchyId.Parse("/2/1/")));
        dd.Add(new Field(6, "France", HierarchyId.Parse("/1/1/")));
        dd.Add(new Field(7, "Germany", HierarchyId.Parse("/1/4/")));
        dd.Add(new Field(8, "test", HierarchyId.Parse("/1/5/")));
        dd.Add(new Field(9, "McMurdo Station", HierarchyId.Parse("/3/1/")));
        dd.Add(new Field(10, "Italy", HierarchyId.Parse("/1/3/")));
        dd.Add(new Field(11, "Spain", HierarchyId.Parse("/1/2/")));
        dd.Add(new Field(12, "Morano", HierarchyId.Parse("/1/3/1/")));
        dd.Add(new Field(13, "Rio de Janeiro", HierarchyId.Parse("/2/1/3/")));
        dd.Add(new Field(14, "Paris", HierarchyId.Parse("/1/1/1/")));
        dd.Add(new Field(15, "Madrid", HierarchyId.Parse("/1/2/1/")));
        dd.Add(new Field(16, "Brasilia", HierarchyId.Parse("/2/1/1/")));
        dd.Add(new Field(17, "Bahia", HierarchyId.Parse("/2/1/2/")));
        dd.Add(new Field(18, "Salvador", HierarchyId.Parse("/2/1/2/1/")));
        dd.Add(new Field(19, "tets1", HierarchyId.Parse("/2/1/3/1/")));
        dd.Add(new Field(20, "test2", HierarchyId.Parse("/2/1/3/1/1/")));
        dd.Add(new Field(21, "test3", HierarchyId.Parse("/2/1/3/1/1/1/")));
        dd.Add(new Field(22, "test24", HierarchyId.Parse("/2/1/3/1/1/2/")));

            MyClass clss = new MyClass();
            var x=  clss.NewMthodTest(dd);

        }

    }
</code>```

Method to get child:

```<code>     public class MyClass
{
    public List<HierarchicalNode> NewMthodTest(List<Field> query)
    {

        var root = new HierarchicalNode("Root", 0);
        foreach (var rec in query)
        {
            var current = root;
            foreach (string part in rec.Node.ToString().Split(new[] { '/' },
                                           StringSplitOptions.RemoveEmptyEntries))
            {
                int parsedPart = int.Parse(part);
                current = current.Children[parsedPart - 1];
            }
            current.Children.Add(new HierarchicalNode(rec.FieldName, rec.Id));
        }
        return null; // in this method i don't know what do we suppose to return
    }
}
</code>```

and my input parameter class is :

```<code>    public class Field
    {
        public Field(long id, string fieldName, HierarchyId node)
        {
            Id = id;
            FieldName = fieldName;
            Node = node;
        }
        public long Id { get; set; }
        public string FieldName { get; set; }
        public HierarchyId Node { get; set; }
    }
</code>```

and output class is

```<code>    class HierarchicalNode
{
    private readonly List<HierarchicalNode> children =
        new List<HierarchicalNode>();
    public List<HierarchicalNode> Children { get { return children; } }

    private readonly string name;
    public string Name { get { return name; } }

    private readonly long id;
    public long Id { get { return id; } }

    public HierarchicalNode(string name, long id)
    {
        this.name = name;
        this.id = id;
    }
}
</code>```

it seems something wrong and it returns this:

答:
After a lot of search On the net with no result, I solve this by myself with a recursive method in c#.

I put my total code here to help people who search in the future for this question. If someone has any nice advice to make it better please leave a note and make me happy.

This is my code:

This is My Main method which calls GetTreeMethod

```<code>  public List<TreeView> GetTree()
    {
       //get all nodes from DB to make a collection in RAM
        var nodesColect = _getFieldsList.GetFieldsByNode("/");

        var x = GetTreeMethod("/", nodesColect);

        return x;
    }
</code>```

This is my main recursive method

```<code>private List<TreeView> GetTreeMethod(string nodeStr,List<FieldListDto> lstCollection)
    {
        List<TreeView> lst = new List<TreeView>();
        HierarchyId node = HierarchyId.Parse(nodeStr);
        var lastItemInCurrentLevel = GetChilds(node, lstCollection);

        foreach (var item in lastItemInCurrentLevel)
        {
            TreeView tr = new TreeView
            {
                title = item.title,
                id = item.id,
                node = item.node,
                fin = item.fin,
            };
            tr.children = GetTreeMethod(item.node.ToString(), lstCollection);
            lst.Add(tr);
        }

        return lst;
    }
</code>```

this just gives children of a specific node

```<code>   private List<TreeView> GetChilds(HierarchyId node, List<FieldListDto> lstCollection)
    {
        List<TreeView> child = lstCollection.Where(x => x.Node.ToString() != "/" && x.Node.GetAncestor(1).ToString() == node.ToString()).Select(q => new TreeView { id = q.Id, node = q.Node, title = q.FieldName }).ToList();
        return child;

    }
</code>```

Models

```<code>public class FieldListDto
{
    public long id { get; set; }
    public string FieldName { get; set; }
    public HierarchyId Node { get; set; }
}
 public class TreeView
{
    public long id { get; set; }
    public string title { get; set; }
    public HierarchyId node { get; set; }
    public List<TreeView> children { get; set; }
}
</code>```

here my SQL data

and here my final result

Body:
For some reason such as performance, I have to use HiarachyId in my database. I have to convert the HierarchyId data type to JSON to show up in FancyTree.

I Use the solution here but won't work. My code was

static void Main(string[] args)
    {

        {

        var dd = new List<Field>();
        dd.Add(new Field(1, "Earth", HierarchyId.Parse("/")));
        dd.Add(new Field(2, "Europe", HierarchyId.Parse("/1/")));
        dd.Add(new Field(3, "South America", HierarchyId.Parse("/2/")));
        dd.Add(new Field(4, "Antarctica", HierarchyId.Parse("/3/")));
        dd.Add(new Field(5, "Brazil", HierarchyId.Parse("/2/1/")));
        dd.Add(new Field(6, "France", HierarchyId.Parse("/1/1/")));
        dd.Add(new Field(7, "Germany", HierarchyId.Parse("/1/4/")));
        dd.Add(new Field(8, "test", HierarchyId.Parse("/1/5/")));
        dd.Add(new Field(9, "McMurdo Station", HierarchyId.Parse("/3/1/")));
        dd.Add(new Field(10, "Italy", HierarchyId.Parse("/1/3/")));
        dd.Add(new Field(11, "Spain", HierarchyId.Parse("/1/2/")));
        dd.Add(new Field(12, "Morano", HierarchyId.Parse("/1/3/1/")));
        dd.Add(new Field(13, "Rio de Janeiro", HierarchyId.Parse("/2/1/3/")));
        dd.Add(new Field(14, "Paris", HierarchyId.Parse("/1/1/1/")));
        dd.Add(new Field(15, "Madrid", HierarchyId.Parse("/1/2/1/")));
        dd.Add(new Field(16, "Brasilia", HierarchyId.Parse("/2/1/1/")));
        dd.Add(new Field(17, "Bahia", HierarchyId.Parse("/2/1/2/")));
        dd.Add(new Field(18, "Salvador", HierarchyId.Parse("/2/1/2/1/")));
        dd.Add(new Field(19, "tets1", HierarchyId.Parse("/2/1/3/1/")));
        dd.Add(new Field(20, "test2", HierarchyId.Parse("/2/1/3/1/1/")));
        dd.Add(new Field(21, "test3", HierarchyId.Parse("/2/1/3/1/1/1/")));
        dd.Add(new Field(22, "test24", HierarchyId.Parse("/2/1/3/1/1/2/")));

            MyClass clss = new MyClass();
            var x=  clss.NewMthodTest(dd);

        }

    }

Method to get child:

     public class MyClass
{
    public List<HierarchicalNode> NewMthodTest(List<Field> query)
    {

        var root = new HierarchicalNode("Root", 0);
        foreach (var rec in query)
        {
            var current = root;
            foreach (string part in rec.Node.ToString().Split(new[] { '/' },
                                           StringSplitOptions.RemoveEmptyEntries))
            {
                int parsedPart = int.Parse(part);
                current = current.Children[parsedPart - 1];
            }
            current.Children.Add(new HierarchicalNode(rec.FieldName, rec.Id));
        }
        return null; // in this method i don't know what do we suppose to return
    }
}

and my input parameter class is :

    public class Field
    {
        public Field(long id, string fieldName, HierarchyId node)
        {
            Id = id;
            FieldName = fieldName;
            Node = node;
        }
        public long Id { get; set; }
        public string FieldName { get; set; }
        public HierarchyId Node { get; set; }
    }

and output class is

    class HierarchicalNode
{
    private readonly List<HierarchicalNode> children =
        new List<HierarchicalNode>();
    public List<HierarchicalNode> Children { get { return children; } }

    private readonly string name;
    public string Name { get { return name; } }

    private readonly long id;
    public long Id { get { return id; } }

    public HierarchicalNode(string name, long id)
    {
        this.name = name;
        this.id = id;
    }
}

it seems something wrong and it returns this:

Body:
After a lot of search On the net with no result, I solve this by myself with a recursive method in c#.

I put my total code here to help people who search in the future for this question. If someone has any nice advice to make it better please leave a note and make me happy.

This is my code:

This is My Main method which calls GetTreeMethod

  public List<TreeView> GetTree()
    {
       //get all nodes from DB to make a collection in RAM
        var nodesColect = _getFieldsList.GetFieldsByNode("/");

        var x = GetTreeMethod("/", nodesColect);

        return x;
    }

This is my main recursive method

private List<TreeView> GetTreeMethod(string nodeStr,List<FieldListDto> lstCollection)
    {
        List<TreeView> lst = new List<TreeView>();
        HierarchyId node = HierarchyId.Parse(nodeStr);
        var lastItemInCurrentLevel = GetChilds(node, lstCollection);

        foreach (var item in lastItemInCurrentLevel)
        {
            TreeView tr = new TreeView
            {
                title = item.title,
                id = item.id,
                node = item.node,
                fin = item.fin,
            };
            tr.children = GetTreeMethod(item.node.ToString(), lstCollection);
            lst.Add(tr);
        }

        return lst;
    }

this just gives children of a specific node

   private List<TreeView> GetChilds(HierarchyId node, List<FieldListDto> lstCollection)
    {
        List<TreeView> child = lstCollection.Where(x => x.Node.ToString() != "/" && x.Node.GetAncestor(1).ToString() == node.ToString()).Select(q => new TreeView { id = q.Id, node = q.Node, title = q.FieldName }).ToList();
        return child;

    }

Models

public class FieldListDto
{
    public long id { get; set; }
    public string FieldName { get; set; }
    public HierarchyId Node { get; set; }
}
 public class TreeView
{
    public long id { get; set; }
    public string title { get; set; }
    public HierarchyId node { get; set; }
    public List<TreeView> children { get; set; }
}

here my SQL data

and here my final result


问:
Receiving Integrity Error from CustomUserModel form
I would like to create a form with my CustomUserModel as shown below, which has a extending model called customer.

```<code>class UserManager(BaseUserManager):
    def create_user(self, email, password=None,is_active=True, is_staff=False, is_admin=False):
        if not email:
            raise ValueError("Users must have email address")
        user_obj = self.model(email = self.normalize_email(email))
        if not password:
            raise ValueError("Users must have a password")

        user_obj.set_password(password)
        user_obj.staff = is_staff
        user_obj.admin = is_admin
        user_obj.active = is_active
        user_obj.save(using=self._db)

        return user_obj

    def create_staffuser(self,email,password=None):
        user = self.create_user(email, password=password,is_staff=True)

        return user

    def create_superuser(self, email, password=None):
        user = self.create_user(email, password=password, is_staff=True, is_admin=True)

        return user

class User(AbstractBaseUser):

    email = models.EmailField(max_length=255,unique=True)
    active = models.BooleanField(default=True)
    staff = models.BooleanField(default=False)
    admin = models.BooleanField(default=False)

    USERNAME_FIELD = 'email'
    # email and password are required by default
    REQUIRED_FIELDS = []

    objects = UserManager()

    def __str__(self):
        return self.email

    def get_full_name(self):
        return self.email

    def get_short_name(self):
        return self.email

    def has_perm(self, perm, obj=None):
        return True

    def has_module_perms(self, app_label):
        return True

    @property
    def is_staff(self):
        return self.staff

    @property
    def is_admin(self):
        return self.admin

    @property
    def is_active(self):
        return self.active

class Customer(models.Model):

    GENDER = (
            ('Male', 'Male'),
            ('Female', 'Female'),
            )

    TITLE = (
            ('Mr', 'Mr'),
            ('Mrs', 'Mrs'),
            ('Miss', 'Miss'),
            ('Ms', 'Ms'),
            ('Dr', 'Dr'),
            ('Sir', 'Sir'),
            ('Madam', 'Madam'),
            )

    user = models.OneToOneField(User,on_delete=models.CASCADE)
    title = models.CharField(max_length=200, null=True, choices=TITLE)
    first_name = models.CharField(max_length=200, null=True)
    middle_name = models.CharField(max_length=200, blank=True,default='')
    last_name = models.CharField(max_length=200, null=True)
    phone = models.CharField(max_length=200, null=True)
    country = CountryField()
    birth_year = models.CharField(max_length=4, null=True)
    gender = models.CharField(max_length=200, null=True, choices=GENDER)
    date_created = models.DateTimeField(auto_now=True, null=True)
    profile_pic = models.ImageField(null=True, blank=True)
    last_purchase = models.DateTimeField(blank=True, null=True)

    def __str__(self):
        return self.user.email

</code>```

Below shows my views.py to create a new customer/user form, that I would like to create at the same time.

```<code>
@login_required(login_url='login')
def NewCustomerProfile(request):
    user_form = RegisterForm()
    customer_form = CustomerProfileForm()
    if request.method == 'POST':
        user_form = RegisterForm(request.POST)
        customer_form = CustomerProfileForm(request.POST)

        if user_form.is_valid() and customer_form.is_valid():
            user_form.save()
            customer_form.save()
            return redirect('/')
    return render(request, 'accounts/new_customer_profile.html', {'user_form': user_form,'customer_form':customer_form})

</code>```

And see below showing my forms for both of the models

```<code>
class CustomerProfileForm(ModelForm):
    class Meta:
        model = Customer
        fields = ['title','first_name','middle_name','last_name','phone','country','birth_year','gender']

class RegisterForm(forms.ModelForm):
    """
    A form for creating new users. Includes all the required
    fields, plus a repeated password.
    """
    password1 = forms.CharField(label='Password', widget=forms.PasswordInput)
    password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput)

    class Meta:
        model = User
        fields = ('email','admin', 'active')

</code>```

I have been getting an error as shown below

```<code>IntegrityError at /new_customer_profile/
NOT NULL constraint failed: accounts_customer.user_id
</code>```

Problem is new customer can be created once a user has been established and created. I would like to create a new user and customer at the same time with no errors accordingly to the models, forms and views shown above.

How does one come to the solution?

答:
A ModelForm when saved returns the instance. In addition it has parameter that allows you not to save the model to the database. Combine these two and there's your solution:

        if user_form.is_valid() and customer_form.is_valid():
            user = user_form.save()
            customer = customer_form.save(commit=False)
            customer.user = user
            customer.save()
            return redirect('/')

```

Body:
I would like to create a form with my CustomUserModel as shown below, which has a extending model called customer.

class UserManager(BaseUserManager):
    def create_user(self, email, password=None,is_active=True, is_staff=False, is_admin=False):
        if not email:
            raise ValueError("Users must have email address")
        user_obj = self.model(email = self.normalize_email(email))
        if not password:
            raise ValueError("Users must have a password")

        user_obj.set_password(password)
        user_obj.staff = is_staff
        user_obj.admin = is_admin
        user_obj.active = is_active
        user_obj.save(using=self._db)

        return user_obj

    def create_staffuser(self,email,password=None):
        user = self.create_user(email, password=password,is_staff=True)

        return user

    def create_superuser(self, email, password=None):
        user = self.create_user(email, password=password, is_staff=True, is_admin=True)

        return user

class User(AbstractBaseUser):

    email = models.EmailField(max_length=255,unique=True)
    active = models.BooleanField(default=True)
    staff = models.BooleanField(default=False)
    admin = models.BooleanField(default=False)

    USERNAME_FIELD = 'email'
    # email and password are required by default
    REQUIRED_FIELDS = []

    objects = UserManager()

    def __str__(self):
        return self.email

    def get_full_name(self):
        return self.email

    def get_short_name(self):
        return self.email

    def has_perm(self, perm, obj=None):
        return True

    def has_module_perms(self, app_label):
        return True

    @property
    def is_staff(self):
        return self.staff

    @property
    def is_admin(self):
        return self.admin

    @property
    def is_active(self):
        return self.active

class Customer(models.Model):

    GENDER = (
            ('Male', 'Male'),
            ('Female', 'Female'),
            )

    TITLE = (
            ('Mr', 'Mr'),
            ('Mrs', 'Mrs'),
            ('Miss', 'Miss'),
            ('Ms', 'Ms'),
            ('Dr', 'Dr'),
            ('Sir', 'Sir'),
            ('Madam', 'Madam'),
            )

    user = models.OneToOneField(User,on_delete=models.CASCADE)
    title = models.CharField(max_length=200, null=True, choices=TITLE)
    first_name = models.CharField(max_length=200, null=True)
    middle_name = models.CharField(max_length=200, blank=True,default='')
    last_name = models.CharField(max_length=200, null=True)
    phone = models.CharField(max_length=200, null=True)
    country = CountryField()
    birth_year = models.CharField(max_length=4, null=True)
    gender = models.CharField(max_length=200, null=True, choices=GENDER)
    date_created = models.DateTimeField(auto_now=True, null=True)
    profile_pic = models.ImageField(null=True, blank=True)
    last_purchase = models.DateTimeField(blank=True, null=True)

    def __str__(self):
        return self.user.email

Below shows my views.py to create a new customer/user form, that I would like to create at the same time.

@login_required(login_url='login')
def NewCustomerProfile(request):
    user_form = RegisterForm()
    customer_form = CustomerProfileForm()
    if request.method == 'POST':
        user_form = RegisterForm(request.POST)
        customer_form = CustomerProfileForm(request.POST)

        if user_form.is_valid() and customer_form.is_valid():
            user_form.save()
            customer_form.save()
            return redirect('/')
    return render(request, 'accounts/new_customer_profile.html', {'user_form': user_form,'customer_form':customer_form})

And see below showing my forms for both of the models

class CustomerProfileForm(ModelForm):
    class Meta:
        model = Customer
        fields = ['title','first_name','middle_name','last_name','phone','country','birth_year','gender']

class RegisterForm(forms.ModelForm):
    """
    A form for creating new users. Includes all the required
    fields, plus a repeated password.
    """
    password1 = forms.CharField(label='Password', widget=forms.PasswordInput)
    password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput)

    class Meta:
        model = User
        fields = ('email','admin', 'active')

I have been getting an error as shown below

IntegrityError at /new_customer_profile/
NOT NULL constraint failed: accounts_customer.user_id

Problem is new customer can be created once a user has been established and created. I would like to create a new user and customer at the same time with no errors accordingly to the models, forms and views shown above.

How does one come to the solution?


问:
No errors but Go app still doesn't work properly
I'm working on a web chat application and I experienced an issue that shouldn't be happening.
In the main.go I have this function:

```<code>http.Handle("/chat", MustAuth(&templateHandler{filename: "chat.html"}))
</code>```

and I've just built an authentication file (auth.go, still in progress) with a cookie, here it is:

```<code>package main

import "net/http"

type authHandler struct {
    next http.Handler
}

func (h *authHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    _, err := r.Cookie("auth")
    if err == http.ErrNoCookie {
        //not authenticated
        w.Header().Set("Location", "/login")
        w.WriteHeader(http.StatusTemporaryRedirect)
        return
    }
    if err != nil {
        //some other error
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }
    //success - call the next handler
    h.next.ServeHTTP(w, r)
}
func MustAuth(handler http.Handler) http.Handler {
    return &authHandler{next: handler}
}
</code>```

The problem is that when I run it and open the localhost page, the cookie doesn't work how it should and doesn't redirect me to the login page as it should.

答:
I have made a fully compiling example out of the code you provided - however it does work for me: lolcalhost:8080/chat redirects me to localhost:8080/login
I suspect your browser may have a cookie "auth" already set.

You can press STRG+SHIFT+I and go to the networking tab to see what is transmitted.
Check there really is no cookie set for you.

Code I tried:

```<code>package main

import "net/http"

type authHandler struct {
    next http.Handler
}

func ServeHTTP(w http.ResponseWriter, r *http.Request) {
    _, err := r.Cookie("auth")
    if err == http.ErrNoCookie {
        //not authenticated
        w.Header().Set("Location", "/login")
        w.WriteHeader(http.StatusTemporaryRedirect)
        return
    }
    if err != nil {
        //some other error
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }
    //success - call the next handler
    //h.next.ServeHTTP(w, r)
    w.Write([]byte("Hi"))
}

func main() {
    http.HandleFunc("/chat", ServeHTTP)
    http.ListenAndServe(":8080", nil)
}
</code>```

Body:
I'm working on a web chat application and I experienced an issue that shouldn't be happening.
In the main.go I have this function:

http.Handle("/chat", MustAuth(&templateHandler{filename: "chat.html"}))

and I've just built an authentication file (auth.go, still in progress) with a cookie, here it is:

package main

import "net/http"

type authHandler struct {
    next http.Handler
}

func (h *authHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    _, err := r.Cookie("auth")
    if err == http.ErrNoCookie {
        //not authenticated
        w.Header().Set("Location", "/login")
        w.WriteHeader(http.StatusTemporaryRedirect)
        return
    }
    if err != nil {
        //some other error
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }
    //success - call the next handler
    h.next.ServeHTTP(w, r)
}
func MustAuth(handler http.Handler) http.Handler {
    return &authHandler{next: handler}
}

The problem is that when I run it and open the localhost page, the cookie doesn't work how it should and doesn't redirect me to the login page as it should.

Body:
I have made a fully compiling example out of the code you provided - however it does work for me: lolcalhost:8080/chat redirects me to localhost:8080/login
I suspect your browser may have a cookie "auth" already set.

You can press STRG+SHIFT+I and go to the networking tab to see what is transmitted.
Check there really is no cookie set for you.

Code I tried:

package main

import "net/http"

type authHandler struct {
    next http.Handler
}

func ServeHTTP(w http.ResponseWriter, r *http.Request) {
    _, err := r.Cookie("auth")
    if err == http.ErrNoCookie {
        //not authenticated
        w.Header().Set("Location", "/login")
        w.WriteHeader(http.StatusTemporaryRedirect)
        return
    }
    if err != nil {
        //some other error
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }
    //success - call the next handler
    //h.next.ServeHTTP(w, r)
    w.Write([]byte("Hi"))
}

func main() {
    http.HandleFunc("/chat", ServeHTTP)
    http.ListenAndServe(":8080", nil)
}


问:
Function to delete selective row in dataframe
I have a question.

I want to delete row in a dataframe but my function is deleting the wrong row. Sorry it is not the best code as I just start and the constant print are for my fault search.

```<code>#Reduce by a factor
    firstrow = int(in_csv.loc[in_csv.index[0]].name)
    lastrow = int(in_csv.loc[in_csv.index[-1]].name)

    for i in range (firstrow, lastrow+1):
        division = (i/reduce_factor)
        print (str(i) + " is " + str(division))
        print ("Division" + str(math.modf(division)))
        if ((math.modf(division)[0]) != 0):
            print (i)
            print (in_csv.iloc[i])
            i_drop = in_csv.loc[in_csv.index[i]].name
            print ("drop: " + str(i_drop))
            in_csv.drop([i], inplace=True)
</code>```

The results is the following

```<code>5 is 2.5
Division(0.5, 2.0)
5
Time             5/11/20 12:01:32 AM
number                     1

Name: 7, dtype: object
drop: 7
</code>```

For the calulation for row 5 it is dropping row 7, for row 7 it is 10, for row 3 it is row 4, for row 1 it is correct. So for every dropped row the fault is increasing by one row.

What is my fault?

答:
I suppose that you should gather indices of rows to drop and perform the drop
after the loop.

But to be sure I have to know the content of your DataFrame, at least some
initial part of it, including the rows in question.

Body:
I have a question.

I want to delete row in a dataframe but my function is deleting the wrong row. Sorry it is not the best code as I just start and the constant print are for my fault search.

#Reduce by a factor
    firstrow = int(in_csv.loc[in_csv.index[0]].name)
    lastrow = int(in_csv.loc[in_csv.index[-1]].name)

    for i in range (firstrow, lastrow+1):
        division = (i/reduce_factor)
        print (str(i) + " is " + str(division))
        print ("Division" + str(math.modf(division)))
        if ((math.modf(division)[0]) != 0):
            print (i)
            print (in_csv.iloc[i])
            i_drop = in_csv.loc[in_csv.index[i]].name
            print ("drop: " + str(i_drop))
            in_csv.drop([i], inplace=True)

The results is the following

5 is 2.5
Division(0.5, 2.0)
5
Time             5/11/20 12:01:32 AM
number                     1

Name: 7, dtype: object
drop: 7

For the calulation for row 5 it is dropping row 7, for row 7 it is 10, for row 3 it is row 4, for row 1 it is correct. So for every dropped row the fault is increasing by one row.

What is my fault?


问:
Iterate through firebase values
I would like to access the comments array and do some calculations to render the average of ratings (avgstars) and show the numbers of comments on a particular item in my firebase array.

Any idea?

ngOnInit() {
  this.route.params
    .pipe(switchMap((params: Params) => this.dishservice.getDish(params['id'])))
    .subscribe(dish => {
      this.dish = dish
      this.favorite = this.favoriteService.isFavorite(this.dish.id);

      //compute the average of the comments and the render the length of the array
      this.numcomments = /* This is the locus --->*/ this.dish.comments.length;
      let total =0;
      this.dish.comments.forEach(comment =>total += comment.rating);
      this.avgstars = (total/this.numcomments).toFixed(2);
         },
        errmess => this.errMess = <any>errmess);
      }
```

Here is the data sample

答:
```<code>You don't have change your firebase data model as long as you create a new Array by iterating your "key" (-M8V...) values from the "comments" object.

I would do something like this:

let p = this.dish[0].comments;
for (let [key, value] of Object.entries(p)) {
  console.log(key, value);
}
</code>```

Title: Iterate through firebase values

Body:
I would like to access the comments array and do some calculations to render the average of ratings (avgstars) and show the numbers of comments on a particular item in my firebase array.

Any idea?

ngOnInit() {
  this.route.params
    .pipe(switchMap((params: Params) => this.dishservice.getDish(params['id'])))
    .subscribe(dish => {
      this.dish = dish
      this.favorite = this.favoriteService.isFavorite(this.dish.id);

      //compute the average of the comments and the render the length of the array
      this.numcomments = /* This is the locus --->*/ this.dish.comments.length;
      let total =0;
      this.dish.comments.forEach(comment =>total += comment.rating);
      this.avgstars = (total/this.numcomments).toFixed(2);
         },
        errmess => this.errMess = <any>errmess);
      }

Here is the data sample


问:
while making ssh connection in node js why is a latter code executing before the ssh connection is made
I have written following code:

```<code>var Client = require('ssh2').Client;

var info={
    errors:'',
    stdout:'',
    stderr:''
};

conn=new Client();

conn.on('ready',()=>{
    console.log('entering...');
    conn.exec('ls',(err,stream)=>{
        if(err) info.errors=err;
        stream.on('close',(code,signal)=>{
            console.log('leaving: code:'+code+' signal:'+signal);
        });
        stream.on('data',(data)=>{
            info.stdout=data;
        }).stderr.on('data',(data)=>{
            info.stderr=data;
        });
    });

}).connect({
    host: ip,
    port: 22,
    username: u,
    password: p
});

//this gets printed earlier
console.log(info);

</code>```

so in the above code connects to a server and executes a command and updates the object info with the output of the executed command so after i run this code it enters and also executes the code and what is expect is it'll console.log info with the updated values but what i get is first the un-updated info and then the above code exectes.
Can anyone help me out in understanding why this is happening and how to fix this?

答:
Though console.log(info); is at the bottom of the program, it will get executed before the other async methods are executed and hence will have the info object not updated.

conn.on('ready',()=>{...
stream.on('data',(data)=>{...

are all async functions which will be queued up in the Event Queue to be handled after they are resolved and the queue is free.

You could choose  to use console.log(info) inside each of the async method's call back instead.

```<code>conn.on('ready',()=>{
    console.log('entering...');
    conn.exec('ls',(err,stream)=>{
        if(err) {
         info.errors=err;

         console.log(info);

        }
        stream.on('close',(code,signal)=>{
            console.log('leaving: code:'+code+' signal:'+signal);
        });
        stream.on('data',(data)=>{
            info.stdout=data;

            console.log(info);

        }).stderr.on('data',(data)=>{
            info.stderr=data;

            console.log(info);

        });
    });

}).connect({
    host: ip,
    port: 22,
    username: u,
    password: p
});
</code>```

This way, whenever you're receiving data or an error occurs, your info object will be receiving the right message and then you can log them to console.

Body:
I have written following code:

var Client = require('ssh2').Client;

var info={
    errors:'',
    stdout:'',
    stderr:''
};

conn=new Client();

conn.on('ready',()=>{
    console.log('entering...');
    conn.exec('ls',(err,stream)=>{
        if(err) info.errors=err;
        stream.on('close',(code,signal)=>{
            console.log('leaving: code:'+code+' signal:'+signal);
        });
        stream.on('data',(data)=>{
            info.stdout=data;
        }).stderr.on('data',(data)=>{
            info.stderr=data;
        });
    });

}).connect({
    host: ip,
    port: 22,
    username: u,
    password: p
});

//this gets printed earlier
console.log(info);

so in the above code connects to a server and executes a command and updates the object info with the output of the executed command so after i run this code it enters and also executes the code and what is expect is it'll console.log info with the updated values but what i get is first the un-updated info and then the above code exectes.
Can anyone help me out in understanding why this is happening and how to fix this?

Body:
Though console.log(info); is at the bottom of the program, it will get executed before the other async methods are executed and hence will have the info object not updated.

conn.on('ready',()=>{...
stream.on('data',(data)=>{...

are all async functions which will be queued up in the Event Queue to be handled after they are resolved and the queue is free.

You could choose  to use console.log(info) inside each of the async method's call back instead.

conn.on('ready',()=>{
    console.log('entering...');
    conn.exec('ls',(err,stream)=>{
        if(err) {
         info.errors=err;

         console.log(info);

        }
        stream.on('close',(code,signal)=>{
            console.log('leaving: code:'+code+' signal:'+signal);
        });
        stream.on('data',(data)=>{
            info.stdout=data;

            console.log(info);

        }).stderr.on('data',(data)=>{
            info.stderr=data;

            console.log(info);

        });
    });

}).connect({
    host: ip,
    port: 22,
    username: u,
    password: p
});

This way, whenever you're receiving data or an error occurs, your info object will be receiving the right message and then you can log them to console.


问:
Visual Studio Code - coding beginner
everyone. I am a graphic designer, and thought I would start to learn coding to write scripts for Adobe Illustrator in ExtendScript/JavaScript. I started some beginner tutorials and have been making progress. A response to a question I had posted on a JavaScript forum suggested I use Visual Studio Code as a writing environment, so I downloaded it. It seems to be very advanced, and I can't figure out how to use it. I watched some of the introductory videos and they seem to start with an assumption of some experience.

My question is does anyone know of any resources for someone just starting out with Visual Studio Code? I did some searching and couldn't find anything suitable.

Thanks for your time.
Joe

答:
It is not easy for beginners but you try next steps (if any of steps will look complex, start again):

1) Open Visual studio code

2) Go to menu File -> new File

3) Rename file to somename.js

4) Write code in it

(if you reached this text it means you succeded)

Title: Visual Studio Code - coding beginner


问:
Extract a specific block of text and place it in a new document
I am using EmEditor and I see there is a "find and extract to new document" function that supports Regex statements.
I am trying to extract some specific text from a Thunderbird mailbox text file. In the mailbox there are copies of customer service chats. Unfortunately, because we use a free version of this chat program it does not allow to export the data. In the body of the email is a lot of text including the chats and decoded attachments. But on the bottom of each chat is the name, email, company name, etc.

It looks like this:

```<code>Name: Tan
Email: someone@domcin.com
Operator: OperatorName
Start Time: 07/01/2014 14:43:47
End Time: 07/01/2014 15:35:22
Product/Service: Delivery
Phone: 123 1234567
Company: MyCompany Inc.
</code>```

I try to extract the name, email, operator, product, phone and company. To make matters worse, not all have company since there are private people too. Also the telephone sometimes has a +60 or (60) or spaces, since the chat user could enter what we wants. I can do this manually but its 6k entries.

The question is if there would be a regex statement to find them. I could then use EmEditor to find this block and place the result in a new document and with a bit of tweaking I should be able to make a excel file to import into a CRM.

If this does not work with regex than does anyone know of a smart way to do this so I do not have to copy and paste all this?

答:
If I understand your question correctly, you want to broadly manipulate your source file in order to get it into a csv of some sort in order to load in excel, etc.

Using EmEditor you could try the following steps (assuming the sample fields mentioned):

1) delete blank lines [optional]

2) Find:^(.*)\r?\n(?!Name) Replace:\1\t

3) Find:((Name|Email|Operator|Start Time|End Time|Product/Service|Phone|Company): ?) Replace:[nothing leave blank
]

4) Add a header line

I've rolled this into a macro you can try on a copy of your source file, and hopefully providing a tab separated output file:

```<code>editor.ExecuteCommandByID(3882);        //Heading = 0
editor.ExecuteCommandByID(4323);        //Remove existing bookmarks

document.selection.Find("^[ \\t]*$\x0a",eeFindNext | eeFindReplaceCase | eeFindReplaceRegExp | eeFindCount | eeFindBookmark,0); //Bookmark blank lines
editor.ExecuteCommandByID(4589);        //Delete Bookmarked lines

document.selection.Replace("^(.*)\\r?\\n(?!Name)","\\1\\t",eeFindReplaceCase | eeReplaceAll | eeFindReplaceRegExp,0);       //Find:^(.*)\r?\n(?!Name)       R:^(.*)\r?\n(?!Name)
document.selection.Replace("((Name|Email|Operator|Start Time|End Time|Product\\/Service|Phone|Company): ?)","",eeFindReplaceCase | eeReplaceAll | eeFindReplaceRegExp,0);   //Find:((Name|Email|Operator|Start Time|End Time|Product\/Service|Phone|Company): ?)    R:[blank]

document.selection.StartOfDocument(false);          //Ctrl-Home, insert blank line, and header line
document.selection.NewLine(1);
document.selection.StartOfDocument(false);          //Ctrl-Home
document.write("Name\tEmail\tOperator\tStart Time\tEnd Time\tProduct\/Service\tPhone\tCompany");    editor.ExecuteCommandByID(3901);        // Adjust separator visible lines only

editor.ExecuteCommandByID(3894); //Heading=1
</code>```

Body:
I am using EmEditor and I see there is a "find and extract to new document" function that supports Regex statements.
I am trying to extract some specific text from a Thunderbird mailbox text file. In the mailbox there are copies of customer service chats. Unfortunately, because we use a free version of this chat program it does not allow to export the data. In the body of the email is a lot of text including the chats and decoded attachments. But on the bottom of each chat is the name, email, company name, etc.

It looks like this:

Name: Tan
Email: someone@domcin.com
Operator: OperatorName
Start Time: 07/01/2014 14:43:47
End Time: 07/01/2014 15:35:22
Product/Service: Delivery
Phone: 123 1234567
Company: MyCompany Inc.

I try to extract the name, email, operator, product, phone and company. To make matters worse, not all have company since there are private people too. Also the telephone sometimes has a +60 or (60) or spaces, since the chat user could enter what we wants. I can do this manually but its 6k entries.

The question is if there would be a regex statement to find them. I could then use EmEditor to find this block and place the result in a new document and with a bit of tweaking I should be able to make a excel file to import into a CRM.

If this does not work with regex than does anyone know of a smart way to do this so I do not have to copy and paste all this?

Body:
If I understand your question correctly, you want to broadly manipulate your source file in order to get it into a csv of some sort in order to load in excel, etc.

Using EmEditor you could try the following steps (assuming the sample fields mentioned):

1) delete blank lines [optional]

2) Find:^(.*)\r?\n(?!Name) Replace:\1\t

3) Find:((Name|Email|Operator|Start Time|End Time|Product/Service|Phone|Company): ?) Replace:[nothing leave blank
]

4) Add a header line

I've rolled this into a macro you can try on a copy of your source file, and hopefully providing a tab separated output file:

editor.ExecuteCommandByID(3882);        //Heading = 0
editor.ExecuteCommandByID(4323);        //Remove existing bookmarks

document.selection.Find("^[ \\t]*$\x0a",eeFindNext | eeFindReplaceCase | eeFindReplaceRegExp | eeFindCount | eeFindBookmark,0); //Bookmark blank lines
editor.ExecuteCommandByID(4589);        //Delete Bookmarked lines

document.selection.Replace("^(.*)\\r?\\n(?!Name)","\\1\\t",eeFindReplaceCase | eeReplaceAll | eeFindReplaceRegExp,0);       //Find:^(.*)\r?\n(?!Name)       R:^(.*)\r?\n(?!Name)
document.selection.Replace("((Name|Email|Operator|Start Time|End Time|Product\\/Service|Phone|Company): ?)","",eeFindReplaceCase | eeReplaceAll | eeFindReplaceRegExp,0);   //Find:((Name|Email|Operator|Start Time|End Time|Product\/Service|Phone|Company): ?)    R:[blank]

document.selection.StartOfDocument(false);          //Ctrl-Home, insert blank line, and header line
document.selection.NewLine(1);
document.selection.StartOfDocument(false);          //Ctrl-Home
document.write("Name\tEmail\tOperator\tStart Time\tEnd Time\tProduct\/Service\tPhone\tCompany");    editor.ExecuteCommandByID(3901);        // Adjust separator visible lines only

editor.ExecuteCommandByID(3894); //Heading=1


问:
Plot2d cut in 3D function
I have 3D Gaussians and their derivatives (Laplace operator)

```<code>f1(x,y,z):=exp(-w1*((x-x1)^2+y^2+z^2));
f2(x,y,z):=exp(-w2*(x^2+y^2+z^2));
dx2_f2(x,y,z):=diff(f2(x,y,z),x,2);
Lf2(x,y,z):=diff(f2(x,y,z),x,2) + diff(f2(x,y,z),y,2) + diff(f2(x,y,z),z,2);
</code>```

Now I want to plot a profile along x cutting the function for fixed y,z for some values of parameters

```<code>w1:1.2;w2:0.5;x1:1.5;
plot2d( Lf2(x,0,0) ,[x,-5,5]);
</code>```

I get following error

```<code>diff: second argument must be a variable; found 0
#0: Lf2(x=x,y=0,z=0)
 -- an error. To debug this try: debugmode(true);
</code>```

While plot2d( [f1(x,0,0),f2(x,0,0),dx2_f2(x,0,0)] ,[x,-5,5]); works just fine.

The same error is if I try to partially substite the variables manually
Lf2x(x):=Lf2(x,0,0);

My guess, the problem is Maxima/lisp does some lazy evaluation, therefore the derivatives along y,z are not yet calculated when I substitute them by y=0,z=0. Therefore it refuse do derivative along constant (?).

But I don't know how to solve it (i.e. substitute the constant only after the derivatives are calculated)

答:
Here is a solution which makes use of quote-quote as you suggested. The main idea is to say foo(x) := ''(diff(something, x)) instead of foo(x) := diff(something, x).

```<code>(%i2) f1(x, y, z) := exp(-w1*((x - x1)^2 + y^2 + z^2));
                                           2    2    2
(%o2)   f1(x, y, z) := exp((- w1) ((x - x1)  + y  + z ))
(%i3) f2(x, y, z) := exp(-w2*(x^2 + y^2 + z^2));
                                        2    2    2
(%o3)       f2(x, y, z) := exp((- w2) (x  + y  + z ))
(%i4) dx2_f2(x, y, z) := ''(diff(f2(x, y, z), x, 2));
                                           2    2    2
                             2  2   - w2 (z  + y  + x )
(%o4) dx2_f2(x, y, z) := 4 w2  x  %e
                                                     2    2    2
                                              - w2 (z  + y  + x )
                                     - 2 w2 %e
(%i5) Lf2(x, y, z) := ''(diff(f2(x, y, z), x, 2) + diff(f2(x, y, z), y, 2) + diff(f2(x, y, z), z, 2));
                                        2    2    2
                          2  2   - w2 (z  + y  + x )
(%o5) Lf2(x, y, z) := 4 w2  z  %e
                     2    2    2
       2  2   - w2 (z  + y  + x )
 + 4 w2  y  %e
                     2    2    2                  2    2    2
       2  2   - w2 (z  + y  + x )          - w2 (z  + y  + x )
 + 4 w2  x  %e                    - 6 w2 %e
(%i6) w1: 1.2;
(%o6)                          1.2
(%i7) w2: 0.5;
(%o7)                          0.5
(%i8) x1: 1.5;
(%o8)                          1.5
(%i9) plot2d( Lf2(x, 0, 0) ,[x, -5, 5]);
(%i10) plot2d( [f1(x, 0, 0), f2(x, 0, 0), dx2_f2(x, 0, 0)], [x, -5, 5]);
</code>```

With these definitions, I find the plots at the end make nice looking plots without errors. Note that the function definitions %o4 and %o5 have the actual derivatives on the right-hand side, not a diff expression. You could get the same effect by using define as I suggested at first.

Title: Plot2d cut in 3D function

Body:
I have 3D Gaussians and their derivatives (Laplace operator)

f1(x,y,z):=exp(-w1*((x-x1)^2+y^2+z^2));
f2(x,y,z):=exp(-w2*(x^2+y^2+z^2));
dx2_f2(x,y,z):=diff(f2(x,y,z),x,2);
Lf2(x,y,z):=diff(f2(x,y,z),x,2) + diff(f2(x,y,z),y,2) + diff(f2(x,y,z),z,2);

Now I want to plot a profile along x cutting the function for fixed y,z for some values of parameters

w1:1.2;w2:0.5;x1:1.5;
plot2d( Lf2(x,0,0) ,[x,-5,5]);

I get following error

diff: second argument must be a variable; found 0
#0: Lf2(x=x,y=0,z=0)
 -- an error. To debug this try: debugmode(true);

While plot2d( [f1(x,0,0),f2(x,0,0),dx2_f2(x,0,0)] ,[x,-5,5]); works just fine.

The same error is if I try to partially substite the variables manually
Lf2x(x):=Lf2(x,0,0);

My guess, the problem is Maxima/lisp does some lazy evaluation, therefore the derivatives along y,z are not yet calculated when I substitute them by y=0,z=0. Therefore it refuse do derivative along constant (?).

But I don't know how to solve it (i.e. substitute the constant only after the derivatives are calculated)

Body:
Here is a solution which makes use of quote-quote as you suggested. The main idea is to say foo(x) := ''(diff(something, x)) instead of foo(x) := diff(something, x).

(%i2) f1(x, y, z) := exp(-w1*((x - x1)^2 + y^2 + z^2));
                                           2    2    2
(%o2)   f1(x, y, z) := exp((- w1) ((x - x1)  + y  + z ))
(%i3) f2(x, y, z) := exp(-w2*(x^2 + y^2 + z^2));
                                        2    2    2
(%o3)       f2(x, y, z) := exp((- w2) (x  + y  + z ))
(%i4) dx2_f2(x, y, z) := ''(diff(f2(x, y, z), x, 2));
                                           2    2    2
                             2  2   - w2 (z  + y  + x )
(%o4) dx2_f2(x, y, z) := 4 w2  x  %e
                                                     2    2    2
                                              - w2 (z  + y  + x )
                                     - 2 w2 %e
(%i5) Lf2(x, y, z) := ''(diff(f2(x, y, z), x, 2) + diff(f2(x, y, z), y, 2) + diff(f2(x, y, z), z, 2));
                                        2    2    2
                          2  2   - w2 (z  + y  + x )
(%o5) Lf2(x, y, z) := 4 w2  z  %e
                     2    2    2
       2  2   - w2 (z  + y  + x )
 + 4 w2  y  %e
                     2    2    2                  2    2    2
       2  2   - w2 (z  + y  + x )          - w2 (z  + y  + x )
 + 4 w2  x  %e                    - 6 w2 %e
(%i6) w1: 1.2;
(%o6)                          1.2
(%i7) w2: 0.5;
(%o7)                          0.5
(%i8) x1: 1.5;
(%o8)                          1.5
(%i9) plot2d( Lf2(x, 0, 0) ,[x, -5, 5]);
(%i10) plot2d( [f1(x, 0, 0), f2(x, 0, 0), dx2_f2(x, 0, 0)], [x, -5, 5]);

With these definitions, I find the plots at the end make nice looking plots without errors. Note that the function definitions %o4 and %o5 have the actual derivatives on the right-hand side, not a diff expression. You could get the same effect by using define as I suggested at first.


问:
making an action to fire when navigating through the app
I made a navigation using createMaterialBottomTabNavigator
and I have a component thats being rendered when I switch to the screen using this navigation,
I want to make the navigation to fire a function everytime I enter the screen using this navigation,
something of a useEffect,
I tried doing useEffect with an empty array [], but it doesn't work, is there a way to achieve this?

答:
You have to use the useFocusEffect hook which is similar to useEffect but it runs every time you navigate to a screen. But use effect will run only the first time.
You can see the sample code in the docs

https://reactnavigation.org/docs/use-focus-effect/


问:
Meteor | Helper function. How to print attribute values of returned element on HTML
I am using Meteor JS for UI development of a project. There is a helper method which takes a input parameter and return an object.

Helper Function:

```<code>"getPhoneName": function (param) {
        let myObj = PhoneRegister.findOne({"_id": param});
        //This myObj contains  name, _id, modelNumber
        return myObj;
    }
</code>```

How i am using it on HTML

```<code><span>{{getPhoneName 'id_1234'}}</span> //This line is obviously prints the [[Object]]

    Here i am not getting solution how to print modelNumber. I have tried following :
1.{{getPhoneName 'id_1234'.modelNumber}}
2.{{getPhoneName 'id_1234'}}.modelNumber
</code>```

Can someone help? If you need more information please let me know.

答:
You have mentioned you have this helper function:

```<code>getPhoneName (_id) {
  const myObj = PhoneRegister.findOne({_id});
  //This myObj contains  name, _id, modelNumber
  return myObj;
}
</code>```

There are 2 ways to go based on your needs

First, if you want to get just the "name" as the helper implies getPhoneName, you can instead return myObj.name; (error handling to ensure myObj exists should also be considered).

You can then just use it:

The name of the phone is {{getPhoneName phoneId}}

```

<hr>

<p>But, if you instead what to list a variety of information about the phone in your template, you can leave the helper alone and adjust your template in one of two different ways:</p>

<p>1) Use <code>#let</code> to name your object within your template.</p>

<pre class="lang-html prettyprint-override"><code>{{#let currentPhone=(getPhoneName phoneId)}}
  <ul>
    <li>ID: {{currentPhone._id}}</li>
    <li>Name: {{currentPhone.name}}</li>
  </ul>
{{/let}}
</code>```

2) Use #with to use that object as your data context without assigning a name

{{#with getPhoneName phoneId}}

ID: {{_id}}

Name: {{name}}

{{/let}}
```

Body:
I am using Meteor JS for UI development of a project. There is a helper method which takes a input parameter and return an object.

Helper Function:

"getPhoneName": function (param) {
        let myObj = PhoneRegister.findOne({"_id": param});
        //This myObj contains  name, _id, modelNumber
        return myObj;
    }

How i am using it on HTML

{{getPhoneName 'id_1234'}} //This line is obviously prints the [[Object]]

    Here i am not getting solution how to print modelNumber. I have tried following :
1.{{getPhoneName 'id_1234'.modelNumber}}
2.{{getPhoneName 'id_1234'}}.modelNumber

Can someone help? If you need more information please let me know.

Body:
You have mentioned you have this helper function:

getPhoneName (_id) {
  const myObj = PhoneRegister.findOne({_id});
  //This myObj contains  name, _id, modelNumber
  return myObj;
}

There are 2 ways to go based on your needs

First, if you want to get just the "name" as the helper implies getPhoneName, you can instead return myObj.name; (error handling to ensure myObj exists should also be considered).

You can then just use it:

<p>The name of the phone is {{getPhoneName phoneId}}</p>

But, if you instead what to list a variety of information about the phone in your template, you can leave the helper alone and adjust your template in one of two different ways:

1) Use #let to name your object within your template.

{{#let currentPhone=(getPhoneName phoneId)}}
  <ul>
    <li>ID: {{currentPhone._id}}</li>
    <li>Name: {{currentPhone.name}}</li>
  </ul>
{{/let}}

2) Use #with to use that object as your data context without assigning a name

{{#with getPhoneName phoneId}}
  <ul>
    <li>ID: {{_id}}</li>
    <li>Name: {{name}}</li>
  </ul>
{{/let}}


问:
When I attempt to transition between views some data is not appearing such UIImageViews: Xcode
Currently, I have some simple firebase login and sign up code setup by which after the user logs in or signs up their home view will display their username and a default profile image.  When I log in from the log_in controller view it works fine in showing the username and default profile image in the home_view.  However, when I transition to my sign_up view and then attempt to transition to my home view with the new user data, it shows neither the username or profile image view. I am not using storyboards.

For my sign up controller I have nothing in the viewWillAppear but I have these functions which create the user and transition the user to the home page after the create account button is pressed:

The create account button:

```<code>@objc func createAccountButtonClicked(_ : UIButton){
   sign_up()
}
</code>```

The sign up function:

```<code>func sign_up(){
    guard usernameTxt.hasText,
    passwordTxt.hasText,
        emailTxt.hasText

        else {

            AlertController.showAlert(self, title: "Missing info", message: "Please fill out all fields")
            return

    }
    let username = usernameTxt.text!
    let password = passwordTxt.text!
    let email = emailTxt.text!

    Auth.auth().createUser(withEmail: email, password: password, completion: {(user, error) in

        guard error == nil else{
            AlertController.showAlert(self, title: "Error", message: error!.localizedDescription)
            return
        }
        guard let user = user else { return }
        print(user.user.email ?? "Missing Email")
        print(user.user.uid)

        self.createProfile(user.user)

        if Auth.auth().currentUser?.uid != nil{
            self.goToHomePage()
        }

    })

}
</code>```

This is a snippet from my create profile function as the rest is simply updating my firebase database:

```<code>func createProfile(_ user: User){

    let username = usernameTxt.text
    let changeRequest = user.createProfileChangeRequest()
    changeRequest.displayName = username
    changeRequest.commitChanges(completion: { (error) in

        guard error == nil else{

            AlertController.showAlert(self, title: "Error", message: error!.localizedDescription)
            return
        }

    })
</code>```

And finally, this is the function that takes care of the transitioning from the sign up to the home view:

```<code>func goToHomePage(){
    let homeView = HomeMenu()
    homeView.modalTransitionStyle = .flipHorizontal
    homeView.modalPresentationStyle = .fullScreen
    self.present(homeView, animated: true, completion: nil)

}
</code>```

This is some code form my view did load function in my home menu which might help as well:

```<code>    if let userID = Auth.auth().currentUser?.uid{

        databaseRef.child("profile").child(userID).observeSingleEvent(of: .value, with: { (snapshot) in
            let dictionary = snapshot.value as? NSDictionary

            guard let username = Auth.auth().currentUser?.displayName else { return }

            if let profileImageURL = dictionary?["photo"] as? String{

                let url = URL(string: profileImageURL)

                URLSession.shared.dataTask(with: url!, completionHandler: {
                    (data, response, error) in

                    if error !=  nil {
                        print(error!)
                        return
                    }
                    DispatchQueue.main.async {
                        self.profileImage.image = UIImage(data: data!)
                    }
                }).resume()
            }
            self.name.text = username

        }){(error) in
            print(error.localizedDescription)
            return
        }

    }
</code>```

Any help on what is going wrong with my code would help as when I run it I receive no errors even though I have my breakpoints set up. Thank you

答:
Now i understand the problem is with goToHomePage() function calling
Please update the following functions in your code and let me know</p>

```<code>func sign_up(){
    guard usernameTxt.hasText,
        passwordTxt.hasText,
        emailTxt.hasText

        else {

            AlertController.showAlert(self, title: "Missing info", message: "Please fill out all fields")
            return

    }
    let username = usernameTxt.text!
    let password = passwordTxt.text!
    let email = emailTxt.text!

    Auth.auth().createUser(withEmail: email, password: password, completion: {(user, error) in

        guard error == nil else{
            AlertController.showAlert(self, title: "Error", message: error!.localizedDescription)
            return
        }
        guard let user = user else { return }
        print(user.user.email ?? "Missing Email")
        print(user.user.uid)

        self.createProfile(user.user)
    })

}

func createProfile(_ user: User){

    let username = usernameTxt.text
    let changeRequest = user.createProfileChangeRequest()
    changeRequest.displayName = username
    changeRequest.commitChanges(completion: { (error) in

        guard error == nil else{

            AlertController.showAlert(self, title: "Error", message: error!.localizedDescription)
            return
        }
        self.goToHomePage()

    })
}

</code>```

Body:
Currently, I have some simple firebase login and sign up code setup by which after the user logs in or signs up their home view will display their username and a default profile image.  When I log in from the log_in controller view it works fine in showing the username and default profile image in the home_view.  However, when I transition to my sign_up view and then attempt to transition to my home view with the new user data, it shows neither the username or profile image view. I am not using storyboards.

For my sign up controller I have nothing in the viewWillAppear but I have these functions which create the user and transition the user to the home page after the create account button is pressed:

The create account button:

@objc func createAccountButtonClicked(_ : UIButton){
   sign_up()
}

The sign up function:

func sign_up(){
    guard usernameTxt.hasText,
    passwordTxt.hasText,
        emailTxt.hasText

        else {

            AlertController.showAlert(self, title: "Missing info", message: "Please fill out all fields")
            return

    }
    let username = usernameTxt.text!
    let password = passwordTxt.text!
    let email = emailTxt.text!

    Auth.auth().createUser(withEmail: email, password: password, completion: {(user, error) in

        guard error == nil else{
            AlertController.showAlert(self, title: "Error", message: error!.localizedDescription)
            return
        }
        guard let user = user else { return }
        print(user.user.email ?? "Missing Email")
        print(user.user.uid)

        self.createProfile(user.user)

        if Auth.auth().currentUser?.uid != nil{
            self.goToHomePage()
        }

    })

}

This is a snippet from my create profile function as the rest is simply updating my firebase database:

func createProfile(_ user: User){

    let username = usernameTxt.text
    let changeRequest = user.createProfileChangeRequest()
    changeRequest.displayName = username
    changeRequest.commitChanges(completion: { (error) in

        guard error == nil else{

            AlertController.showAlert(self, title: "Error", message: error!.localizedDescription)
            return
        }

    })

And finally, this is the function that takes care of the transitioning from the sign up to the home view:

func goToHomePage(){
    let homeView = HomeMenu()
    homeView.modalTransitionStyle = .flipHorizontal
    homeView.modalPresentationStyle = .fullScreen
    self.present(homeView, animated: true, completion: nil)

}

This is some code form my view did load function in my home menu which might help as well:

    if let userID = Auth.auth().currentUser?.uid{

        databaseRef.child("profile").child(userID).observeSingleEvent(of: .value, with: { (snapshot) in
            let dictionary = snapshot.value as? NSDictionary

            guard let username = Auth.auth().currentUser?.displayName else { return }

            if let profileImageURL = dictionary?["photo"] as? String{

                let url = URL(string: profileImageURL)

                URLSession.shared.dataTask(with: url!, completionHandler: {
                    (data, response, error) in

                    if error !=  nil {
                        print(error!)
                        return
                    }
                    DispatchQueue.main.async {
                        self.profileImage.image = UIImage(data: data!)
                    }
                }).resume()
            }
            self.name.text = username

        }){(error) in
            print(error.localizedDescription)
            return
        }

    }

Any help on what is going wrong with my code would help as when I run it I receive no errors even though I have my breakpoints set up. Thank you

Body:
Now i understand the problem is with goToHomePage() function calling
Please update the following functions in your code and let me know

func sign_up(){
    guard usernameTxt.hasText,
        passwordTxt.hasText,
        emailTxt.hasText

        else {

            AlertController.showAlert(self, title: "Missing info", message: "Please fill out all fields")
            return

    }
    let username = usernameTxt.text!
    let password = passwordTxt.text!
    let email = emailTxt.text!

    Auth.auth().createUser(withEmail: email, password: password, completion: {(user, error) in

        guard error == nil else{
            AlertController.showAlert(self, title: "Error", message: error!.localizedDescription)
            return
        }
        guard let user = user else { return }
        print(user.user.email ?? "Missing Email")
        print(user.user.uid)

        self.createProfile(user.user)
    })

}

func createProfile(_ user: User){

    let username = usernameTxt.text
    let changeRequest = user.createProfileChangeRequest()
    changeRequest.displayName = username
    changeRequest.commitChanges(completion: { (error) in

        guard error == nil else{

            AlertController.showAlert(self, title: "Error", message: error!.localizedDescription)
            return
        }
        self.goToHomePage()

    })
}


问:
Numpy parallel indexing using np.ix_
I have a Python script in which I heavily use numpy. I recently learned a bit more about numpys inherent parallelisation, and that one should avoid big for-loops with numpy and instead rely on implicit parallel indexing.

I have a very huge for-loop in my script (which actually contains another for-loop). That loop splits data in training and test sets, manipulates each set independently in some way, fits models and repeats. It is an n-repeated k-fold.

However, the script is very slow and seems to cause memory leakage if n and k are big. I think this is also due to the huge for loop. So I wanted to get rid of the for loop and use the splits in a parallel fashion. However, I don't succeed. Here is what is happening in my script:

This first bit is generic:

```<code>from sklearn.model_selection import RepeatedKFold
import ...
#Some data is imported, functions defined, variables pre-allocated.

number_conditions = 10 #Usually bigger.
output = np.array(number_conditions, number_conditions) #This contains real data, though.
outer_k = 5
outer_reps = 1 # usually much higher
outer_rkf = RepeatedKFold(n_splits=outer_k, n_repeats=outer_reps)

array_for_indices = list(range(number_conditions))
</code>```

This is the non-efficient for-loop version:

```<code>for train_indices, test_indices in outer_rkf.split(array_for_indices):

    ixgrid_train = np.ix_(train_indices, train_indices)
    output_train = output[ixgrid_train]

    ixgrid_test = np.ix_(test_indices, test_indices)
    output_test = output[ixgrid_test]

    ...
</code>```

This is followed by some heavy data manipulation and another nested for-loop, and is then repeated (outer_k*outer_reps) times.

I wanted to parallelise this and tried this:

```<code>outer_split_1, outer_split_2, outer_split_3, outer_split_4, outer_split_5 = outer_rkf.split(array_for_indices)

index = np.array([outer_split_1, outer_split_2, outer_split_3, outer_split_4, outer_split_5])

all_train_inds = index[:, 0]
all_test_inds = index[:, 1]

ixgrid_train = np.ix_(all_train_inds, all_train_inds)
output_train = output[ixgrid_train]
</code>```

But the last line gives me

IndexError: arrays used as indices must be of integer (or boolean) type

Which kind of makes sense to me: in the for-loop version, ixgrid_train is a tuple with two arrays of ints. In the latter version, it is a tuple with two arrays of objects, which in turn hold arrays.

I tried making index not an array but a tuple, or a list, and tried to index index on different ways (writing this shows me that index is probably a name to-be-improved). However, I never achieve what I want: that output_train contains not just the desired data for one split, but for all, and gets it assigned in one go.

At the base of my problem is that I don't know how to basically increase the dimensionality of what I am doing. I imagine that I need to transfer the dimension I am looping over in the loop-version into a dimension of the objects I am operating on, but I don't know how to do this which yields actual parallellism. Especially, since tuple confuse me.

How can I achieve what I want: create all indices for all folds at once, and then assign all selected data for each fold at once, so that I can carry on working with that in parallel later on?

I am grateful for any input! :)

Title: Numpy parallel indexing using np.ix_

Body:
I have a Python script in which I heavily use numpy. I recently learned a bit more about numpys inherent parallelisation, and that one should avoid big for-loops with numpy and instead rely on implicit parallel indexing.

I have a very huge for-loop in my script (which actually contains another for-loop). That loop splits data in training and test sets, manipulates each set independently in some way, fits models and repeats. It is an n-repeated k-fold.

However, the script is very slow and seems to cause memory leakage if n and k are big. I think this is also due to the huge for loop. So I wanted to get rid of the for loop and use the splits in a parallel fashion. However, I don't succeed. Here is what is happening in my script:

This first bit is generic:

from sklearn.model_selection import RepeatedKFold
import ...
#Some data is imported, functions defined, variables pre-allocated.

number_conditions = 10 #Usually bigger.
output = np.array(number_conditions, number_conditions) #This contains real data, though.
outer_k = 5
outer_reps = 1 # usually much higher
outer_rkf = RepeatedKFold(n_splits=outer_k, n_repeats=outer_reps)

array_for_indices = list(range(number_conditions))

This is the non-efficient for-loop version:

for train_indices, test_indices in outer_rkf.split(array_for_indices):

    ixgrid_train = np.ix_(train_indices, train_indices)
    output_train = output[ixgrid_train]

    ixgrid_test = np.ix_(test_indices, test_indices)
    output_test = output[ixgrid_test]

    ...

This is followed by some heavy data manipulation and another nested for-loop, and is then repeated (outer_k*outer_reps) times.

I wanted to parallelise this and tried this:

outer_split_1, outer_split_2, outer_split_3, outer_split_4, outer_split_5 = outer_rkf.split(array_for_indices)

index = np.array([outer_split_1, outer_split_2, outer_split_3, outer_split_4, outer_split_5])

all_train_inds = index[:, 0]
all_test_inds = index[:, 1]

ixgrid_train = np.ix_(all_train_inds, all_train_inds)
output_train = output[ixgrid_train]

But the last line gives me

IndexError: arrays used as indices must be of integer (or boolean) type

Which kind of makes sense to me: in the for-loop version, ixgrid_train is a tuple with two arrays of ints. In the latter version, it is a tuple with two arrays of objects, which in turn hold arrays.

I tried making index not an array but a tuple, or a list, and tried to index index on different ways (writing this shows me that index is probably a name to-be-improved). However, I never achieve what I want: that output_train contains not just the desired data for one split, but for all, and gets it assigned in one go.

At the base of my problem is that I don't know how to basically increase the dimensionality of what I am doing. I imagine that I need to transfer the dimension I am looping over in the loop-version into a dimension of the objects I am operating on, but I don't know how to do this which yields actual parallellism. Especially, since tuple confuse me.

How can I achieve what I want: create all indices for all folds at once, and then assign all selected data for each fold at once, so that I can carry on working with that in parallel later on?

I am grateful for any input! :)

Body:
Does this illustrate your problem:

In [186]: idx=np.array([np.array([1,2,3]), np.array([4,5])])
In [187]: idx
Out[187]: array([array([1, 2, 3]), array([4, 5])], dtype=object)
In [188]: np.ix_(idx,idx)
Out[188]:
(array([[array([1, 2, 3])],
        [array([4, 5])]], dtype=object),
 array([[array([1, 2, 3]), array([4, 5])]], dtype=object))
In [189]: np.ones((10,10),int)[_]
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-189-fa4d7e0befc5> in <module>
----> 1 np.ones((10,10),int)[_]

while the iterative case is

In [190]: [np.arange(100).reshape(10,10)[np.ix_(row,row)] for row in idx]
Out[190]:
[array([[11, 12, 13],
        [21, 22, 23],
        [31, 32, 33]]),
 array([[44, 45],
        [54, 55]])]

Indexing different size blocks (possibly overlapping) means this is impossible to cast as one n-d indexing operation.

IndexError: arrays used as indices must be of integer (or boolean) type

You don't want a union-block like

In [192]: np.arange(100).reshape(10,10)[np.ix_([1,2,3,4,5],[1,2,3,4,5])]
Out[192]:
array([[11, 12, 13, 14, 15],
       [21, 22, 23, 24, 25],
       [31, 32, 33, 34, 35],
       [41, 42, 43, 44, 45],
       [51, 52, 53, 54, 55]])

nor do you want the flattened elements:

In [193]: np.hstack([i.ravel() for i in _190])
Out[193]: array([11, 12, 13, 21, 22, 23, 31, 32, 33, 44, 45, 54, 55])