问:
$parse:ueoe Error in angular js when parsing ng-pattern bound in directive
I have a directive that binds a string to apply as an ng-pattern in the directive itself, yet when rendered it gives a UEOE error.

the directive is defined as:

```<code>myApp.directive('myDirective', Directive);

function Directive() {
    var directiveDefinition = {
        restrict: 'E',
        require: 'ngModel',
        replace: true,
        transclude: false,
        link: function (scope, element, attrs, ngModelCtrl) {

        },
        scope: {
            myPattern:'@',
           },

        templateUrl: 'template.htm'
    };
    return directiveDefinition;
}
</code>```

with template

```<code><div>
   <form  name=myForm>
        <input type='text' ng-model='ngModel'
               ng-model-options="{ updateOn:'blur', allowInvalid: true }"
               ng-pattern="{{myPattern}}" />
    </form>
</div>
</code>```

and it is used in a view as:

```<code><my-directive ng-model="someValue" my-pattern="[a-z]+"></my-directive>
</code>```

giving the error

angular.min.js:2 Error: [$parse:ueoe] http://errors.angularjs.org/1.6.4/$parse/ueoe?p0=%5Ba-z%5D%2B

if I change the regex to have no 'special' characters its fine, but for anything with a complex regex it doesnt work, for example I get a lexerr for the regex [A-Za-z0-9.]+

http://errors.angularjs.org/1.6.4/$parse/lexerr?p0=Unexpected%20next%20character%20&p1=s%2010-10%20%5B%5C%5D&p2=%5BA-Za-z0-9%5C.%5D%2B

is there a way I can pass such a regex to a directive so that it can be parsed successfully?

Incidentally the ng-pattern works correctly, but other unexpected behavior is seen which I suspect is a knock on effect.

答:
From the docs, it seems that ng-patterns expect angular expression and not interpolation in most cased ex ng-pattern="myPattern". Without testing it my self, if using interpolation than the end result has to be regex literal form ex. /abc/

From the api docs:

the value is an AngularJS expression:
     If the expression evaluates to a RegExp object, then this is used directly.

If the expression evaluates to a string, then it will be converted to a RegExp after wrapping it in ^ and $ characters. For
  instance, "abc" will be converted to new RegExp('^abc$').

If the value is a RegExp literal, e.g. ngPattern="/^\d+$/", it is used directly.

ngPattern

AngularJS expression that must evaluate to a RegExp or a String
  parsable into a RegExp, or a RegExp literal. See above for more
  details.

Body:
I have a directive that binds a string to apply as an ng-pattern in the directive itself, yet when rendered it gives a UEOE error.

the directive is defined as:

myApp.directive('myDirective', Directive);

function Directive() {
    var directiveDefinition = {
        restrict: 'E',
        require: 'ngModel',
        replace: true,
        transclude: false,
        link: function (scope, element, attrs, ngModelCtrl) {

        },
        scope: {
            myPattern:'@',
           },

        templateUrl: 'template.htm'
    };
    return directiveDefinition;
}

with template

   <form  name=myForm>
        <input type='text' ng-model='ngModel'
               ng-model-options="{ updateOn:'blur', allowInvalid: true }"
               ng-pattern="{{myPattern}}" />
    </form>

and it is used in a view as:

<my-directive ng-model="someValue" my-pattern="[a-z]+"></my-directive>

giving the error

angular.min.js:2 Error: [$parse:ueoe] http://errors.angularjs.org/1.6.4/$parse/ueoe?p0=%5Ba-z%5D%2B

if I change the regex to have no 'special' characters its fine, but for anything with a complex regex it doesnt work, for example I get a lexerr for the regex [A-Za-z0-9.]+

http://errors.angularjs.org/1.6.4/$parse/lexerr?p0=Unexpected%20next%20character%20&p1=s%2010-10%20%5B%5C%5D&p2=%5BA-Za-z0-9%5C.%5D%2B

is there a way I can pass such a regex to a directive so that it can be parsed successfully?

Incidentally the ng-pattern works correctly, but other unexpected behavior is seen which I suspect is a knock on effect.


来源: stackexchange

问:
Embedding javascript into html in Vue
So I've linked Firebase to my Vue project and now I want to display a portion of the content of a blog. I know that to display the entire blog content I can simple write the following within an html tag.

```<code>{{blogs[0].content}}
</code>```

My question is, how do you display just a portion of it, for example the first 100 characters of the content? I've tried,

```<code>{{blogs[0].content[:100]}}
</code>```

However that gives a compile error.

Also I have a second question, I have using bootstrap with Vue. More specifically the card cascade. Below shows a section of the bootstrap card cascade.

```<code><b-card
        title= blogs[0].title
        img-src="https://placekitten.com/g/400/450"
        img-alt="Image"
        img-top
      >
        <b-card-text>
          {{blogs[0].content[:10]}}
        </b-card-text>
</b-card>
</code>```

I want the title to be the title of blogs[0] but the way I have done it above just prints out "blogs[0].title"

答:
          {{blogs[0].content[:10]}}

```

This should work. Use v-bind to use JS in HTML tags.

See more in the docs: https://v2.vuejs.org/v2/guide/class-and-style.html

ContentLicense: CC BY-SA 4.0

Title: Embedding javascript into html in Vue

Body:
So I've linked Firebase to my Vue project and now I want to display a portion of the content of a blog. I know that to display the entire blog content I can simple write the following within an html tag.

{{blogs[0].content}}

My question is, how do you display just a portion of it, for example the first 100 characters of the content? I've tried,

{{blogs[0].content[:100]}}

However that gives a compile error.

Also I have a second question, I have using bootstrap with Vue. More specifically the card cascade. Below shows a section of the bootstrap card cascade.

          {{blogs[0].content[:10]}}

I want the title to be the title of blogs[0] but the way I have done it above just prints out "blogs[0].title"

Body:
<b-card
        :title=blogs[0].title
        img-src="https://placekitten.com/g/400/450"
        img-alt="Image"
        img-top
      >
        <b-card-text>
          {{blogs[0].content[:10]}}
        </b-card-text>
</b-card>

This should work. Use v-bind to use JS in HTML tags.

See more in the docs: https://v2.vuejs.org/v2/guide/class-and-style.html


问:
Connect JS secure websocket to C# websocket server (Fleck)
I have an API in C# (asp.net) in which i'm running this websocket server using fleck:

```<code>SocketService.start();

            SocketService.server.Start(socket =>
            {
                socket.OnOpen = () =>
                {
                    SocketService.Connessione(socket);
                };
                socket.OnClose = () =>
                {
                    SocketService.Disconnesione(socket);
                };
                socket.OnMessage = message =>
                {
                    SocketService.Messaggio(message, socket);
                };
            });
</code>```

This is SocketService.Start():

```<code>public static void start()
    {
        server = new WebSocketServer($"wss://{GetLocalIPAddress()}:{"4450"}/BNS/");
    }
</code>```

I have tried with a simple HTML/JS page using unsecure ws and it worked fine.

Then I have tried in my main program which i need it to be run on HTTPS so when using unsecure ws chrome told me to use wss instead.

So i change my ws server to wss but then it does nothing, it gives me timeout error.

This is the JS code:

```<code>var start = function () {
        var wsImpl = window.WebSocket || window.MozWebSocket;
        var form = document.getElementById('sendForm');
        var input = document.getElementById('sendText');

        alert("Connessione...");

        // create a new websocket and connect
        window.ws = new wsImpl('@Percorsi.IndirizzoSocket');

        alert("conn");

        // when the connection is established, this method is called
            ws.onopen = function () {
                alert("Connessione aperta");
                 var openJson = {
                    "Id": "@Model.accountCorrente.Id",
                    "type": "Identificazione"
                 };

                alert("send");
                ws.send(stringify(openJson));
            };
            // when the connection is closed, this method is called
            ws.onclose = function () {
                alert("Connessione chiusa");
            }
            // when data is comming from the server, this metod is called
            ws.onmessage = function (val) {
                if (confirm("Hai ricevuto un nuovo messaggio!\nPremi ok per visualizzarlo.")) {
                    window.location("/Annunci/Chat/" + val);
                } else { }
            };

    }
</code>```

I can't figured out how to make it works.

Thanks in advance for your help!

答:
It seems like you are not setting the server certificate to be used under WS over TLS (not to be confused with HTTPS which is HTTP over TLS).
If you see the example in fleck's webpage, you will realize that you have to set the Certificate:</p>

```<code>server.Certificate = new X509Certificate2("MyCert.pfx");
</code>```

Body:
I have an API in C# (asp.net) in which i'm running this websocket server using fleck:

SocketService.start();

            SocketService.server.Start(socket =>
            {
                socket.OnOpen = () =>
                {
                    SocketService.Connessione(socket);
                };
                socket.OnClose = () =>
                {
                    SocketService.Disconnesione(socket);
                };
                socket.OnMessage = message =>
                {
                    SocketService.Messaggio(message, socket);
                };
            });

This is SocketService.Start():

public static void start()
    {
        server = new WebSocketServer($"wss://{GetLocalIPAddress()}:{"4450"}/BNS/");
    }

I have tried with a simple HTML/JS page using unsecure ws and it worked fine.

Then I have tried in my main program which i need it to be run on HTTPS so when using unsecure ws chrome told me to use wss instead.

So i change my ws server to wss but then it does nothing, it gives me timeout error.

This is the JS code:

var start = function () {
        var wsImpl = window.WebSocket || window.MozWebSocket;
        var form = document.getElementById('sendForm');
        var input = document.getElementById('sendText');

        alert("Connessione...");

        // create a new websocket and connect
        window.ws = new wsImpl('@Percorsi.IndirizzoSocket');

        alert("conn");

        // when the connection is established, this method is called
            ws.onopen = function () {
                alert("Connessione aperta");
                 var openJson = {
                    "Id": "@Model.accountCorrente.Id",
                    "type": "Identificazione"
                 };

                alert("send");
                ws.send(stringify(openJson));
            };
            // when the connection is closed, this method is called
            ws.onclose = function () {
                alert("Connessione chiusa");
            }
            // when data is comming from the server, this metod is called
            ws.onmessage = function (val) {
                if (confirm("Hai ricevuto un nuovo messaggio!\nPremi ok per visualizzarlo.")) {
                    window.location("/Annunci/Chat/" + val);
                } else { }
            };

    }

I can't figured out how to make it works.

Thanks in advance for your help!

Body:
It seems like you are not setting the server certificate to be used under WS over TLS (not to be confused with HTTPS which is HTTP over TLS).
If you see the example in fleck's webpage, you will realize that you have to set the Certificate:

server.Certificate = new X509Certificate2("MyCert.pfx");


问:
Displaying only the title in the specific date of the calendar
I use fullcalendar in angularjs as follows to display some event values in the calendar

It displays the values correctly.

```<code><html>
   <head>
   <link rel="stylesheet" href="../fullcalendar-
   4.1.0/packages/core/main.css"></script>
   <link rel="stylesheet" href="../fullcalendar-
   4.1.0/packages/daygrid/main.css"></script>
   <link rel="stylesheet" href="../fullcalendar-
   4.1.0/packages/list/main.css"></script>
   <link rel="stylesheet" href="../fullcalendar-
  4.1.0/packages/timegrid/main.css"></script>
  <script type="text/javascript" src="../fullcalendar-
    4.1.0/packages/core/main.js"></script>
    <script type="text/javascript" src="../fullcalendar-
    4.1.0/packages/daygrid/main.js"></script>
    <script type="text/javascript" src="../fullcalendar-
    4.1.0/packages/timegrid/main.js"></script>
    <script type="text/javascript" src="../fullcalendar-
   4.1.0/packages/list/main.js"></script>
   </head>
   <script>
    $scope.event = {events: [{
            title:'test1',
            start: '2019-05-05 08:00',
            end: '2019-05-10 08:00'
          },
          {
            title:'test2',
            start: '2019-05-05 12:00'
        }]};
    var calendarEl = document.getElementById('calendar');

        var calendar = new FullCalendar.Calendar(calendarEl, {
            events: $scope.event.events,
            plugins: [ 'dayGrid','timeGrid','list' ],
            header: {
                      left: 'prev,next today',
                      center: 'title',
                      right: 'dayGridMonth,dayGridWeek,timeGridDay'
                    }
        });
        calendar.render();
    });
   </script>
   <body ng-app="myApp" ng-controller="myController">
   <div id="calendar" ng-model="eventSources"></div>
   </body>
   </html>
</code>```

Although I have declared a title in the above it always appends the time with a or p accordingly on the specific date. How can I only display the title in the calendar ?

答:
If we want to prevent appending the time to the title we need to define the start and end time without declaring the time as below.

```<code>$scope.event = {events: [{
            title:'test1',
            start: '2019-05-05',
            end: '2019-05-10'
          },
          {
            title:'test2',
            start: '2019-05-05'
        }]};
</code>```

Please note that I haven't uploaded the whole code but have updated the changed code only. Rest of the code remains the same.

Body:
I use fullcalendar in angularjs as follows to display some event values in the calendar

It displays the values correctly.

   <link rel="stylesheet" href="../fullcalendar-
   4.1.0/packages/core/main.css"></script>
   <link rel="stylesheet" href="../fullcalendar-
   4.1.0/packages/daygrid/main.css"></script>
   <link rel="stylesheet" href="../fullcalendar-
   4.1.0/packages/list/main.css"></script>
   <link rel="stylesheet" href="../fullcalendar-
  4.1.0/packages/timegrid/main.css"></script>

Although I have declared a title in the above it always appends the time with a or p accordingly on the specific date. How can I only display the title in the calendar ?

Body:
If we want to prevent appending the time to the title we need to define the start and end time without declaring the time as below.

$scope.event = {events: [{
            title:'test1',
            start: '2019-05-05',
            end: '2019-05-10'
          },
          {
            title:'test2',
            start: '2019-05-05'
        }]};

Please note that I haven't uploaded the whole code but have updated the changed code only. Rest of the code remains the same.


问:
How to start a python operator boto3 AWS-glue task in airflow based on another AWS-glue task successful completion in Airflow?
My Ariflow script has several tasks using python operator to start a glue job using boto3. Even though the flow depends on each task in Ariflow. The consecutive tasks don't wait until the previous task's successful completion.

Next glue job task is called as soon as the previous glue job task is invoked. At the end even though the Airflow looks like successfully completed the glue jobs are still running for several minutes.

```<code>    from airflow import DAG
    from airflow.operators.python_operator import PythonOperator
    from datetime import datetime, timedelta
    from airflow.operators.sensors import TimeDeltaSensor
    import boto3
    import json

    default_args = {
    'owner': 'SAM',
    'start_date': datetime(2019, 5, 27)
     }

    glue_client = boto3.client('glue', region_name='us-east-1')

    def run_customer_job():
        glue_client.start_job_run(JobName='customer')

    def run_product_job():
        glue_client.start_job_run(JobName='product')

    with DAG('dataload', default_args=default_args, schedule_interval="0 15 * * *") as dag:
        task1 = PythonOperator(task_id='task1',
                               python_callable=run_customer_job)
        task2 = PythonOperator(task_id='task2',
                               python_callable=run_product_job)

    task1 >> task2
</code>```

答: Create a new GlueOperator, based on https://github.com/apache/airflow/blob/main/airflow/providers/amazon/aws/operators/glue.py</p>

Body:
My Ariflow script has several tasks using python operator to start a glue job using boto3. Even though the flow depends on each task in Ariflow. The consecutive tasks don't wait until the previous task's successful completion.

Next glue job task is called as soon as the previous glue job task is invoked. At the end even though the Airflow looks like successfully completed the glue jobs are still running for several minutes.

    from airflow import DAG
    from airflow.operators.python_operator import PythonOperator
    from datetime import datetime, timedelta
    from airflow.operators.sensors import TimeDeltaSensor
    import boto3
    import json

    default_args = {
    'owner': 'SAM',
    'start_date': datetime(2019, 5, 27)
     }

    glue_client = boto3.client('glue', region_name='us-east-1')

    def run_customer_job():
        glue_client.start_job_run(JobName='customer')

    def run_product_job():
        glue_client.start_job_run(JobName='product')

    with DAG('dataload', default_args=default_args, schedule_interval="0 15 * * *") as dag:
        task1 = PythonOperator(task_id='task1',
                               python_callable=run_customer_job)
        task2 = PythonOperator(task_id='task2',
                               python_callable=run_product_job)

    task1 >> task2


问:
What is clientId, authTokenEndpoint, clientKey for accessing Azure Data Lake?
I am writing a test application to read file from AzureData Lake. I have created the account and the resource, as well as uploading the file. I am trying to create a client using the following code (as described in the documentation https://learn.microsoft.com/en-us/azure/data-lake-store/data-lake-store-get-started-java-sdk). Where do I get those values from exactly?
Thanks</p>

```<code>String clientId = "FILL-IN-HERE";
String authTokenEndpoint = "FILL-IN-HERE";
String clientKey = "FILL-IN-HERE";

AccessTokenProvider provider = new ClientCredsTokenProvider(authTokenEndpoint, clientId, clientKey);
// full account FQDN, not just the account name
String accountFQDN = "FILL-IN-HERE";
ADLStoreClient client = ADLStoreClient.createClient(accountFQDN, provider);
</code>```

答:
It seems that you are using Azure Active Directory authentication with Azure Data Lake.

Login Azure portal->click Azure Active Directory->click App registrations->find your application(or create a new one)

ClientId

clientKey(Click Certificates&secrets->click new client secret->click add) The client secret is the clientKey.

authTokenEndpoint Click Endpoints

Refer to this document for more details.

Body:
I am writing a test application to read file from AzureData Lake. I have created the account and the resource, as well as uploading the file. I am trying to create a client using the following code (as described in the documentation https://learn.microsoft.com/en-us/azure/data-lake-store/data-lake-store-get-started-java-sdk). Where do I get those values from exactly?
Thanks

String clientId = "FILL-IN-HERE";
String authTokenEndpoint = "FILL-IN-HERE";
String clientKey = "FILL-IN-HERE";

AccessTokenProvider provider = new ClientCredsTokenProvider(authTokenEndpoint, clientId, clientKey);
// full account FQDN, not just the account name
String accountFQDN = "FILL-IN-HERE";
ADLStoreClient client = ADLStoreClient.createClient(accountFQDN, provider);


问:
How to use Context.Request.Body and retain it?
I am trying to write a middleware where I will be doing a json schema validation against the request body. After the validation, I need to use the request body again. But I am not able to figure out how this can be done. I referred this post
and found a way to access the body. But once the request body is used, I need that available to my next function.

Here is the sample code:

```<code>package main
import (
        "fmt"
        "io/ioutil"
        "net/http"
        "github.com/gin-gonic/gin"
        //"github.com/xeipuuv/gojsonschema"
)

func middleware() gin.HandlerFunc {
 return func(c *gin.Context) {
    //Will be doing json schema validation here

    body := c.Request.Body
    x, _ := ioutil.ReadAll(body)

    fmt.Printf("%s \n", string(x))

    fmt.Println("I am a middleware for json schema validation")

    c.Next()
    return
 }
}

type E struct {
 Email    string
 Password string
}

func test(c *gin.Context) {
 //data := &E{}
 //c.Bind(data)
 //fmt.Println(data)   //prints empty as json body is already used

 body := c.Request.Body
 x, _ := ioutil.ReadAll(body)

 fmt.Printf("body is: %s \n", string(x))
 c.JSON(http.StatusOK, c)
}

func main() {
 router := gin.Default()

 router.Use(middleware())

 router.POST("/test", test)

 //Listen and serve
 router.Run("127.0.0.1:8080")
}
</code>```

Current output:

```<code>{
    "email": "test@test.com",
    "password": "123"
}

I am a middleware for json schema validation
body is:
</code>```

Expected output:

```<code>{
    "email": "test@test.com",
    "password": "123"
}
I am a middleware for json schema validation
body is: {
    "email": "test@test.com",
    "password": "123"
}
</code>```

答:
If you want to use the body content multiple times and you're also using gin-gonic, I think the ShouldBindBodyWith function is what you're looking for.

ShouldBindBodyWith is similar with ShouldBindWith, but it stores the request body into the context, and reuse when it is called again.

NOTE: This method reads the body before binding. So you should use ShouldBindWith for better performance if you need to call only once.

References:

https://github.com/gin-gonic/gin/issues/1078

https://godoc.org/github.com/gin-gonic/gin#Context.ShouldBindBodyWith

Body:
I am trying to write a middleware where I will be doing a json schema validation against the request body. After the validation, I need to use the request body again. But I am not able to figure out how this can be done. I referred this post
and found a way to access the body. But once the request body is used, I need that available to my next function.

Here is the sample code:

package main
import (
        "fmt"
        "io/ioutil"
        "net/http"
        "github.com/gin-gonic/gin"
        //"github.com/xeipuuv/gojsonschema"
)

func middleware() gin.HandlerFunc {
 return func(c *gin.Context) {
    //Will be doing json schema validation here

    body := c.Request.Body
    x, _ := ioutil.ReadAll(body)

    fmt.Printf("%s \n", string(x))

    fmt.Println("I am a middleware for json schema validation")

    c.Next()
    return
 }
}

type E struct {
 Email    string
 Password string
}

func test(c *gin.Context) {
 //data := &E{}
 //c.Bind(data)
 //fmt.Println(data)   //prints empty as json body is already used

 body := c.Request.Body
 x, _ := ioutil.ReadAll(body)

 fmt.Printf("body is: %s \n", string(x))
 c.JSON(http.StatusOK, c)
}

func main() {
 router := gin.Default()

 router.Use(middleware())

 router.POST("/test", test)

 //Listen and serve
 router.Run("127.0.0.1:8080")
}

Current output:

{
    "email": "test@test.com",
    "password": "123"
}

I am a middleware for json schema validation
body is:

Expected output:

{
    "email": "test@test.com",
    "password": "123"
}
I am a middleware for json schema validation
body is: {
    "email": "test@test.com",
    "password": "123"
}


问:
Are there any big spring-boot open source projects?
I'm currently developing a spring boot application and would like to see some kind of real-world examples of how big spring boot projects can be architectured. I've tried searching the web myself, but had no success so far.

I would be especially interested in bigger examples using spring-data-rest.

答:
I know couple of Projects which are open source

Mifos

Broadleaf-Commerce


问:
How to make a setup for c# app that uses a vbscript copying a file from LAN?
So i Have this c# application that contains a button allowing a file copy from a network share folder.i use a vbscript to copy the file, this script takes the source and destination path.now i want to create a setup to install my application on any PC connected to the LAN. the thing is the path will eventually change so i'm not sure if it will work.

I never made a setup before and i'm wondering if there is a way to customise the setup to allow the installer to make the changes.otherwise any solution will be very helpfull. thank you

答:
I don't normally like giving answers that are mostly links, but it is too much to post here. Here is a quick summary:

There are quite a few things that can do what you are asking.
The one I like is called Squirrel. I recently had to learn how to use it while deploying an application for my company.

The steps in a nutshell(see what I did there? :)

Build your application (optionally add the update checker code
first - see links for details)

Package your application into a .nuget file using Nuget Package Explorer(details in links below)

Run the squirrel --releasify on your nuget

It will output the setup files that you are looking for in the Releases directory.

More information (that you will likely need):

Github - Squirrel.Windows

Youtube - Video tutorial that I found helpful

Github - Squirrel Getting started guide

As for your vbscript, I would do the file copy inside C#. You are very likely to run into permissions issues when using vbs. In any case, why add the complexity of 2 different languages when C# can do a file copy easily.

Something like this during your application's startup.

```<code>if (File.Exists(localFileName) == false)         // check to see if the file is needed
{
    File.Copy(sourceFileOnLan, destinationFile); // get the file
}
</code>```

If you are really set on using a vbs file, you can launch it using Process.Start() and let Windows execute it.

Also, you can store the paths in your app.config file, and update them if/when they change.

Body:
I don't normally like giving answers that are mostly links, but it is too much to post here. Here is a quick summary:

There are quite a few things that can do what you are asking.
The one I like is called Squirrel. I recently had to learn how to use it while deploying an application for my company.

The steps in a nutshell(see what I did there? :)

Build your application (optionally add the update checker code
first - see links for details)

Package your application into a .nuget file using Nuget Package Explorer(details in links below)

Run the squirrel --releasify on your nuget

It will output the setup files that you are looking for in the Releases directory.

More information (that you will likely need):

Github - Squirrel.Windows

Youtube - Video tutorial that I found helpful

Github - Squirrel Getting started guide

As for your vbscript, I would do the file copy inside C#. You are very likely to run into permissions issues when using vbs. In any case, why add the complexity of 2 different languages when C# can do a file copy easily.

Something like this during your application's startup.

if (File.Exists(localFileName) == false)         // check to see if the file is needed
{
    File.Copy(sourceFileOnLan, destinationFile); // get the file
}

If you are really set on using a vbs file, you can launch it using Process.Start() and let Windows execute it.

Also, you can store the paths in your app.config file, and update them if/when they change.


问:
How can I see the console output from an assertion in Bixby story testing?
Is it possible to log console output and see what is going on when putting in assertions? I am seeing the desired behavior (the correct prompt shows up) of my capsule, however the assertion that checks for a prompt is failing and I can't really find any way to debug these assertions.

Also, I'm kind of new to StackOverflow so I could make this question more specific to my issue if that is better. I figured it would be best to start with a general question like this that would be useful to a wider audience!

答:
The Story Assertions feature is still in preview. Currently there is no great way to debug assertions. Rest assured we are working to stabilize the feature and provide full debug tooling.

P.S. I work on the Bixby Developer Studio team


问:
Keras: Missing clear_session, set_session, and get_session?
I'm using Keras 2.2.0 and am trying to do something like the following:

```<code>import keras.backend as K
K.clear_session()
sess = tf.Session()
K.set_session(sess)
...
with K.get_session() as sess:
</code>```

However, I get errors saying AttributeError: 'module' object has no attribute 'clear_session'.  So it seems this functionality is no longer in keras.backend?

For instance, if I do dir(keras.backend), I get:

```<code>['Function', 'NAME_SCOPE_STACK', 'Print', 'RandomStreams', 'T', 'T_softsign', '_BACKEND', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__', '_backend', '_config', '_config_path', '_epsilon', '_floatx', '_image_data_format', '_keras_base_dir', '_keras_dir', 'abs', 'absolute_import', 'all', 'any', 'arange', 'argmax', 'argmin', 'backend', 'batch_dot', 'batch_flatten', 'batch_get_value', 'batch_normalization', 'batch_set_value', 'bias_add', 'binary_crossentropy', 'cast', 'cast_to_floatx', 'categorical_crossentropy', 'clip', 'common', 'concatenate', 'constant', 'contextmanager', 'conv1d', 'conv2d', 'conv2d_transpose', 'conv3d', 'conv3d_transpose', 'cos', 'count_params', 'ctc_batch_cost', 'ctc_cost', 'ctc_create_skip_idxs', 'ctc_interleave_blanks', 'ctc_path_probs', 'ctc_update_log_p', 'cumprod', 'cumsum', 'defaultdict', 'depthwise_conv2d', 'division', 'dot', 'dropout', 'dtype', 'elu', 'epsilon', 'equal', 'eval', 'exp', 'expand_dims', 'eye', 'f', 'flatten', 'floatx', 'foldl', 'foldr', 'function', 'gather', 'get_uid', 'get_value', 'get_variable_shape', 'gradients', 'greater', 'greater_equal', 'hard_sigmoid', 'has_arg', 'identity', 'ifelse', 'image_data_format', 'image_dim_ordering', 'importlib', 'in_test_phase', 'in_top_k', 'in_train_phase', 'int_shape', 'is_keras_tensor', 'is_placeholder', 'is_sparse', 'is_tensor', 'json', 'l2_normalize', 'learning_phase', 'less', 'less_equal', 'local_conv1d', 'local_conv2d', 'log', 'logsumexp', 'map_fn', 'max', 'maximum', 'mean', 'min', 'minimum', 'moving_average_update', 'name_scope', 'ndim', 'normalize_batch_in_training', 'not_equal', 'np', 'one_hot', 'ones', 'ones_like', 'os', 'pattern_broadcast', 'permute_dimensions', 'placeholder', 'pool', 'pool2d', 'pool3d', 'pow', 'print_function', 'print_tensor', 'prod', 'py_all', 'py_any', 'py_slice', 'py_sum', 'random_binomial', 'random_normal', 'random_normal_variable', 'random_uniform', 'random_uniform_variable', 'relu', 'repeat', 'repeat_elements', 'reset_uids', 'reshape', 'resize_images', 'resize_volumes', 'reverse', 'rnn', 'round', 'separable_conv1d', 'separable_conv2d', 'set_epsilon', 'set_floatx', 'set_image_data_format', 'set_image_dim_ordering', 'set_learning_phase', 'set_value', 'shape', 'sigmoid', 'sign', 'sin', 'slice', 'softmax', 'softplus', 'softsign', 'sparse_categorical_crossentropy', 'spatial_2d_padding', 'spatial_3d_padding', 'sqrt', 'square', 'squeeze', 'stack', 'std', 'stop_gradient', 'sum', 'switch', 'sys', 'tanh', 'temporal_padding', 'th_sparse_module', 'theano', 'theano_backend', 'tile', 'to_dense', 'transpose', 'truncated_normal', 'update', 'update_add', 'update_sub', 'var', 'variable', 'zeros', 'zeros_like']
</code>```

and don't see any of those 3 in there.

How should I be writing this code in modern Keras?

Thanks!

答:
EDIT: https://github.com/keras-team/keras/issues/11015
Seems like it is not available any may have to downgrade

It might be that your backend is set to using Theano (I believe clear_session is only available through the Tensorflow backend with Keras). You can change these settings in your keras.json to TF and clear_session should be available to you.

Body:
I'm using Keras 2.2.0 and am trying to do something like the following:

import keras.backend as K
K.clear_session()
sess = tf.Session()
K.set_session(sess)
...
with K.get_session() as sess:

However, I get errors saying AttributeError: 'module' object has no attribute 'clear_session'.  So it seems this functionality is no longer in keras.backend?

For instance, if I do dir(keras.backend), I get:

['Function', 'NAME_SCOPE_STACK', 'Print', 'RandomStreams', 'T', 'T_softsign', '_BACKEND', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__', '_backend', '_config', '_config_path', '_epsilon', '_floatx', '_image_data_format', '_keras_base_dir', '_keras_dir', 'abs', 'absolute_import', 'all', 'any', 'arange', 'argmax', 'argmin', 'backend', 'batch_dot', 'batch_flatten', 'batch_get_value', 'batch_normalization', 'batch_set_value', 'bias_add', 'binary_crossentropy', 'cast', 'cast_to_floatx', 'categorical_crossentropy', 'clip', 'common', 'concatenate', 'constant', 'contextmanager', 'conv1d', 'conv2d', 'conv2d_transpose', 'conv3d', 'conv3d_transpose', 'cos', 'count_params', 'ctc_batch_cost', 'ctc_cost', 'ctc_create_skip_idxs', 'ctc_interleave_blanks', 'ctc_path_probs', 'ctc_update_log_p', 'cumprod', 'cumsum', 'defaultdict', 'depthwise_conv2d', 'division', 'dot', 'dropout', 'dtype', 'elu', 'epsilon', 'equal', 'eval', 'exp', 'expand_dims', 'eye', 'f', 'flatten', 'floatx', 'foldl', 'foldr', 'function', 'gather', 'get_uid', 'get_value', 'get_variable_shape', 'gradients', 'greater', 'greater_equal', 'hard_sigmoid', 'has_arg', 'identity', 'ifelse', 'image_data_format', 'image_dim_ordering', 'importlib', 'in_test_phase', 'in_top_k', 'in_train_phase', 'int_shape', 'is_keras_tensor', 'is_placeholder', 'is_sparse', 'is_tensor', 'json', 'l2_normalize', 'learning_phase', 'less', 'less_equal', 'local_conv1d', 'local_conv2d', 'log', 'logsumexp', 'map_fn', 'max', 'maximum', 'mean', 'min', 'minimum', 'moving_average_update', 'name_scope', 'ndim', 'normalize_batch_in_training', 'not_equal', 'np', 'one_hot', 'ones', 'ones_like', 'os', 'pattern_broadcast', 'permute_dimensions', 'placeholder', 'pool', 'pool2d', 'pool3d', 'pow', 'print_function', 'print_tensor', 'prod', 'py_all', 'py_any', 'py_slice', 'py_sum', 'random_binomial', 'random_normal', 'random_normal_variable', 'random_uniform', 'random_uniform_variable', 'relu', 'repeat', 'repeat_elements', 'reset_uids', 'reshape', 'resize_images', 'resize_volumes', 'reverse', 'rnn', 'round', 'separable_conv1d', 'separable_conv2d', 'set_epsilon', 'set_floatx', 'set_image_data_format', 'set_image_dim_ordering', 'set_learning_phase', 'set_value', 'shape', 'sigmoid', 'sign', 'sin', 'slice', 'softmax', 'softplus', 'softsign', 'sparse_categorical_crossentropy', 'spatial_2d_padding', 'spatial_3d_padding', 'sqrt', 'square', 'squeeze', 'stack', 'std', 'stop_gradient', 'sum', 'switch', 'sys', 'tanh', 'temporal_padding', 'th_sparse_module', 'theano', 'theano_backend', 'tile', 'to_dense', 'transpose', 'truncated_normal', 'update', 'update_add', 'update_sub', 'var', 'variable', 'zeros', 'zeros_like']

and don't see any of those 3 in there.

How should I be writing this code in modern Keras?

Thanks!


问:
Pivot Table Grand Total at the top
We have an Excel spreadsheet with the Grand Totals at the top using a Forumla, but this isn't on the actual Pivot Table it's just in the spreadsheet.

We have a client that wants the Grand Totals at the top of the Pivot Table and doesn't want us to use Formula. Does anyone know if this is possible (even using VBA or something, just so long as we don't look for a specific column or row name and compare with it (so no GETPIVOTDATA("Grand Total...)))?

答:
This slightly hacky solution might help:

http://www.contextures.com/xlPivot13.html

OwnerDisplayName: PintSizedCat

ContentLicense: CC BY-SA 2.5

Title: Pivot Table Grand Total at the top

OwnerDisplayName: barrowc


问:
Delete snapshots except those with specific description
I'm trying to delete old AWS snapshots but I need to exclude any with a description value that starts with "Created by CreateImage".

I've tried variations of boto3.resource and boto3.client.

```<code>from datetime import datetime, timedelta, timezone

import boto3
client = boto3.client('ec2')
snapshots = client.snapshots.filter(Description!='Created by CreateImage')

def lambda_handler(event, context):
    for snapshot in snapshots:
        start_time = snapshot.start_time
        delete_time = datetime.now(tz=timezone.utc) - timedelta(days=790)
        if delete_time > start_time:
            snapshot.delete()
            print('Snapshot with Id = {} is deleted '.format(snapshot.snapshot_id))
</code>```

Right now I have about 10 snapshots older than 790 days, 5 with a description that starts with "Created by CreateImage" and 5 that don't. In testing this out I want to delete those snapshots without that description.

the error I get is:

module initialization error: 'EC2' object has no attribute 'snapshots'

答:
You need to use describe_snapshots and properly pass in filters.

Also, the results are going to be a dictionary, not references to the Snapshot class so you need to update the way you pull out the attributes and delete the snapshot.

Something like:

from datetime import datetime, timedelta, timezone

import boto3
client = boto3.client('ec2')
snapshots = client.describe_snapshots(Filters=[
        {
            'Name': 'description',
            'Values': [
                'Created by CreateImage',
            ]
        },
    ])['Snapshots']

def lambda_handler(event, context):
    for snapshot in snapshots:
        start_time = snapshot['StartTime']
        delete_time = datetime.now(tz=timezone.utc) - timedelta(days=790)
        if delete_time > start_time:
            client.delete_snapshot(SnapshotId=snapshot['SnapshotId'])
            print('Snapshot with Id = {} is deleted '.format(snapshot['SnapshotId']))

```

Reference:
https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/ec2.html#EC2.Client.describe_snapshots

Body:
I'm trying to delete old AWS snapshots but I need to exclude any with a description value that starts with "Created by CreateImage".

I've tried variations of boto3.resource and boto3.client.

from datetime import datetime, timedelta, timezone

import boto3
client = boto3.client('ec2')
snapshots = client.snapshots.filter(Description!='Created by CreateImage')

def lambda_handler(event, context):
    for snapshot in snapshots:
        start_time = snapshot.start_time
        delete_time = datetime.now(tz=timezone.utc) - timedelta(days=790)
        if delete_time > start_time:
            snapshot.delete()
            print('Snapshot with Id = {} is deleted '.format(snapshot.snapshot_id))

Right now I have about 10 snapshots older than 790 days, 5 with a description that starts with "Created by CreateImage" and 5 that don't. In testing this out I want to delete those snapshots without that description.

the error I get is:

module initialization error: 'EC2' object has no attribute 'snapshots'

Body:
You need to use describe_snapshots and properly pass in filters.

Also, the results are going to be a dictionary, not references to the Snapshot class so you need to update the way you pull out the attributes and delete the snapshot.

Something like:

from datetime import datetime, timedelta, timezone

import boto3
client = boto3.client('ec2')
snapshots = client.describe_snapshots(Filters=[
        {
            'Name': 'description',
            'Values': [
                'Created by CreateImage',
            ]
        },
    ])['Snapshots']

def lambda_handler(event, context):
    for snapshot in snapshots:
        start_time = snapshot['StartTime']
        delete_time = datetime.now(tz=timezone.utc) - timedelta(days=790)
        if delete_time > start_time:
            client.delete_snapshot(SnapshotId=snapshot['SnapshotId'])
            print('Snapshot with Id = {} is deleted '.format(snapshot['SnapshotId']))

Reference:
https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/ec2.html#EC2.Client.describe_snapshots


问:
Change the color of a TextInput placeholder with Styled Components in React Native
How do you set the color of TextInput its placeholder with Styled Components in React Native?

I tried the following without any luck:

1.

```<code>const Input = styled.TextInput`
   border: 1px solid green;
   display: block;
   margin: 0 0 1em;

   ::placeholder {
       color: green;
   }
`
</code>```

2.

```<code>const Input = styled.TextInput`
   border: 1px solid green;
   display: block;
   margin: 0 0 1em;

   &::placeholder {
       color: green;
   }
`
</code>```

答:
The best way to make this:</p>

```<code>export const Input = styled.TextInput.attrs({
  placeholderTextColor: "red"
})`
  background-color: "#000";
`;
</code>```

Body:
How do you set the color of TextInput its placeholder with Styled Components in React Native?

I tried the following without any luck:

1.

const Input = styled.TextInput`
   border: 1px solid green;
   display: block;
   margin: 0 0 1em;

   ::placeholder {
       color: green;
   }
`

2.

const Input = styled.TextInput`
   border: 1px solid green;
   display: block;
   margin: 0 0 1em;

   &::placeholder {
       color: green;
   }
`

Body:
The best way to make this:

export const Input = styled.TextInput.attrs({
  placeholderTextColor: "red"
})`
  background-color: "#000";
`;


问:
compute all permutations of a list in a dataframe column
I am trying to compute all permutations of a list or column in a df while keeping an id column.</p>

```<code>input df
    id    list
    1     foo bar
    2     dog cat

desired df output
    id    list
    1     foo bar
    1     bar foo
    2     dog cat
    2     cat dog
</code>```

答:
IIUC just using permutations from itertools, then it is unnest

```<code>df['list']=df['list'].str.split(' ')
import itertools
df['list']=[list(itertools.permutations(x)) for x in df['list']]
pd.DataFrame({'id':df.id.repeat(df['list'].str.len()),'list':np.concatenate(df['list'].values).tolist()})
Out[522]:
   id        list
0   1  [foo, bar]
0   1  [bar, foo]
1   2  [dog, cat]
1   2  [cat, dog]
</code>```

Body:
I am trying to compute all permutations of a list or column in a df while keeping an id column.

input df
    id    list
    1     foo bar
    2     dog cat

desired df output
    id    list
    1     foo bar
    1     bar foo
    2     dog cat
    2     cat dog

Body:
IIUC just using permutations from itertools, then it is unnest

df['list']=df['list'].str.split(' ')
import itertools
df['list']=[list(itertools.permutations(x)) for x in df['list']]
pd.DataFrame({'id':df.id.repeat(df['list'].str.len()),'list':np.concatenate(df['list'].values).tolist()})
Out[522]:
   id        list
0   1  [foo, bar]
0   1  [bar, foo]
1   2  [dog, cat]
1   2  [cat, dog]


问:
Infinite loop when I try to update the state
Im using firebase.auth().onAuthStateChanged in order to change my state, if the user is not null, I want to update my state and set the user info in it, however when I try to do so, I get an infinite loop, however when I delete the this.setState({userInfo: user}) the code works without problems, below my code:</p>

```<code>class Test extends React.Component {

  state = {
    toDashboard: true,
    userInfo: null
  }

  render() {

    firebase.auth().onAuthStateChanged(user =>{
      if(!user){
        this.setState({toDashboard: false});
      }else{ //HERE is where I get the inifinite loop, if I delete the ELSE, it does not go into an infinite loop
        this.setState({userInfo: user});
      }
    })

    if (this.state.toDashboard === false) {
      return <Redirect to='/auth/login' />
    }

    return (
      <>
        <Sidebar
          {...this.props}
          routes={routes}
          logo={{
            innerLink: "/admin/index",
            imgSrc: require("assets/img/brand/LogoMorado.png"),
            imgAlt: "Logo"
          }}
        />
        <div className="main-content" ref="mainContent">
          <AdminNavbar
            {...this.props}
            brandText={this.getBrandText(this.props.location.pathname)}
          />
          <Switch>{this.getRoutes(routes)}</Switch>
          <Container fluid>
            <AdminFooter />
          </Container>
        </div>
      </>
    );
  }
}

export default Test;
</code>```

答:
Don't use setState({}) in render().

It causes the infinite loop.

basically, componentDidMount() do that instead of render().

and you should learn about React Life Cycle.

https://reactjs.org/docs/react-component.html

```<code>
componentDidMount(){
    firebase.auth().onAuthStateChanged(user =>{
      if(!user){
        this.setState({toDashboard: false});
      }else{ //HERE is where I get the inifinite loop, if I delete the ELSE, it does not go into an infinite loop
        this.setState({userInfo: user});
      }
    })

}
render() {

    return (
      <>
        {  (this.state.toDashboard === false)? <Redirect to='/auth/login' /> : null }
        <Sidebar
          {...this.props}
          routes={routes}
          logo={{
            innerLink: "/admin/index",
            imgSrc: require("assets/img/brand/LogoMorado.png"),
            imgAlt: "Logo"
          }}
        />
        <div className="main-content" ref="mainContent">
          <AdminNavbar
            {...this.props}
            brandText={this.getBrandText(this.props.location.pathname)}
          />
          <Switch>{this.getRoutes(routes)}</Switch>
          <Container fluid>
            <AdminFooter />
          </Container>
        </div>
      </>
    );
  }

</code>```

Body:
Im using firebase.auth().onAuthStateChanged in order to change my state, if the user is not null, I want to update my state and set the user info in it, however when I try to do so, I get an infinite loop, however when I delete the this.setState({userInfo: user}) the code works without problems, below my code:

class Test extends React.Component {

  state = {
    toDashboard: true,
    userInfo: null
  }

  render() {

    firebase.auth().onAuthStateChanged(user =>{
      if(!user){
        this.setState({toDashboard: false});
      }else{ //HERE is where I get the inifinite loop, if I delete the ELSE, it does not go into an infinite loop
        this.setState({userInfo: user});
      }
    })

    if (this.state.toDashboard === false) {
      return <Redirect to='/auth/login' />
    }

    return (
      <>
        <Sidebar
          {...this.props}
          routes={routes}
          logo={{
            innerLink: "/admin/index",
            imgSrc: require("assets/img/brand/LogoMorado.png"),
            imgAlt: "Logo"
          }}
        />

          <AdminNavbar
            {...this.props}
            brandText={this.getBrandText(this.props.location.pathname)}
          />
          <Switch>{this.getRoutes(routes)}</Switch>
          <Container fluid>
            <AdminFooter />
          </Container>

      </>
    );
  }
}

export default Test;

Body:
Don't use setState({}) in render().

It causes the infinite loop.

basically, componentDidMount() do that instead of render().

and you should learn about React Life Cycle.

https://reactjs.org/docs/react-component.html

componentDidMount(){
    firebase.auth().onAuthStateChanged(user =>{
      if(!user){
        this.setState({toDashboard: false});
      }else{ //HERE is where I get the inifinite loop, if I delete the ELSE, it does not go into an infinite loop
        this.setState({userInfo: user});
      }
    })

}
render() {

    return (
      <>
        {  (this.state.toDashboard === false)? <Redirect to='/auth/login' /> : null }
        <Sidebar
          {...this.props}
          routes={routes}
          logo={{
            innerLink: "/admin/index",
            imgSrc: require("assets/img/brand/LogoMorado.png"),
            imgAlt: "Logo"
          }}
        />
        <div className="main-content" ref="mainContent">
          <AdminNavbar
            {...this.props}
            brandText={this.getBrandText(this.props.location.pathname)}
          />
          <Switch>{this.getRoutes(routes)}</Switch>
          <Container fluid>
            <AdminFooter />
          </Container>
        </div>
      </>
    );
  }


问:
how to avoid memory wastage when storing UTF-8 characters (8 bit) in Java character (16 bit). two in one?
I'm afraid I have a question on a detail of a rather oversaturated topic, I searched aroudn a lot, but couldn't find a clear answer to that specific obvious -imho- important, problem:

When converting byte[] to String using UTF-8, each byte (8bit) becomes a 8 bit character encoded by UTF-8, but each UTF-8 character is saved as a 16 bit character in java. Is that correct?
If yes, this means, that each stupid java character only uses the first 8 bits, and consumes double the memory? Is that correct too? I wonder how this wasteful behaviour is acceptable..

Isn't there some trick to have a pseudo String that is 8 bit?  Would that actually result in less memory consumption?
Or maybe, is there a way to store >two< 8bit characters in one java 16bit character to avoid this memory waste?

thanks for any deconfusing answers...

EDIT:
hi, thanks everybody for answering. I was aware of the variable-length property of UTF-8. However, since my source is byte which is 8 bit, I understood (apparently wrongly) that it needs only 8-bit UTF-8 words. Is UTF-8 conversion actually saving the strange symbols that you see when on the CLI you do "cat somebinary" ? I thought UTF-8 was just somehow used to map each of the possible 8bit words of byte to one particular 8 bit word of UTF-8. Wrong? I thought about using Base64 but it's bad because it uses only 7 bit..

questions reformulated: is there a smarter way to convert byte to something String?
May favorite was to just cast byte[] to char[], but then I still have 16bit words.

additional use case info:

I'm adapting Jedis (java client for the NoSQL Redis) as the  "primitive storage layer" for hypergraphDB. So, jedis is a database for another "database".
My problem is that I have to feed jedis with byte[] data all the time, but internally, >Redis< (the actual server)  is dealing only with "binary safe" Strings. Since Redis is written in C, a char is 8 bit long, AFAIK not ASCIII which is 7 bit. In Jedis however, java world, every character is 16 bit long internally. I don't understand this code (yet), but I suppose jedis then converts this java 16 bit strings to a Redis conforming 8 bit string (([here][3]). It says it extends FilterOutputStream. My hope is to bypass the byte[] <-> string conversion altogether and use that Filteroutputstream...?  )

now I wonder: if I had to interconvert byte[] and String all the time, with datasizes ranging from very small to potentially very big, isn't there a huge waste of memory to have each 8 bit character passed around as 16bit within java?

答:
When converting byte[] to String using UTF-8, each byte (8bit) becomes a 8 bit character encoded by UTF-8

No. When converting byte[] to String using UTF-8, each UTF-8 sequence of 1-6 bytes is converted into a UTF-16 sequence of 1-2 16-bit characters.

In almost all cases, worldwide, this UTF-16 sequence contains a single character.

In Western Europe and North America, for most text, only 8 bits of this 16-bit character are used. However, if you have a Euro sign, you'll need more than 8 bits.

For more information, see Unicode. Or Joel Spolsky's article.

ContentLicense: CC BY-SA 3.0


问:
How do you acces IdentityUser to change its role?
I want to change the role of a user in my application.

I used Dependency Injection to access  UserManager _usermanager in my controller. To change the role I'm supposed to call _usermanager.AddToRoleAsync(IdentityUser user, string role), but I can't seem to locate the a IdentityUser enity.

```<code>    [HttpPost]
    public async Task<IActionResult> BewerkGebruiker(int id , ... )
    {
        Gebruiker g;
        using (var context =  new UTILcontext())
        {
            _userManager.AddToRoleAsync(<<what do i put here?>>),Rol);
            _manager.UpdateGebruiker(g);
            return RedirectToAction("Gebruikers");
        };
</code>```

答:
I didn't know about the _userManager.Users Property. This way I can find the right IdentityUser to fill the AddToRoleAsync with.

Problem solved!

Body:
I want to change the role of a user in my application.

I used Dependency Injection to access  UserManager _usermanager in my controller. To change the role I'm supposed to call _usermanager.AddToRoleAsync(IdentityUser user, string role), but I can't seem to locate the a IdentityUser enity.

    [HttpPost]
    public async Task<IActionResult> BewerkGebruiker(int id , ... )
    {
        Gebruiker g;
        using (var context =  new UTILcontext())
        {
            _userManager.AddToRoleAsync(<<what do i put here?>>),Rol);
            _manager.UpdateGebruiker(g);
            return RedirectToAction("Gebruikers");
        };


问:
Python function return value vs print
I am exceedingly new to programming, so go easy on me. I use Visual Studio Code as my editor in which I am working on a few python files. When I run the code, say for instance a pandas.dataframe.head() function, it doesn't return anything in the terminal. But when I print the same return value, I am seeing the data from a csv file as expected.

Can anyone explain what is going on?

Is it the case that when a function is run, that the data is stored but not necessarily displayed?

If so, is print the only means of displaying the value of a function when debugging?

Tried googling answers, but don't have clarity yet.

import pandas as pd

df = pd.read_csv('sample.csv')
df.head()
# print(df.head())
```

Expect some data to be displayed in the terminal

答:
Are the first 5 rows of your 'sample.csv' file blank per chance? If not selected, the df.head() returns (https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.head.html) the first 5 rows. So:

```<code>import pandas as pd
df = pd.DataFrame({'animal':['alligator', 'bee', 'falcon', 'lion', 'monkey', 'parrot', 'shark', 'whale', 'zebra']})

print(df.head())
</code>```

```<code>      animal
0  alligator
1        bee
2     falcon
3       lion
4     monkey
</code>```

Title: Python function return value vs print

Body:
I am exceedingly new to programming, so go easy on me. I use Visual Studio Code as my editor in which I am working on a few python files. When I run the code, say for instance a pandas.dataframe.head() function, it doesn't return anything in the terminal. But when I print the same return value, I am seeing the data from a csv file as expected.

Can anyone explain what is going on?

Is it the case that when a function is run, that the data is stored but not necessarily displayed?

If so, is print the only means of displaying the value of a function when debugging?

Tried googling answers, but don't have clarity yet.

import pandas as pd

df = pd.read_csv('sample.csv')
df.head()
# print(df.head())

Expect some data to be displayed in the terminal

Body:
Are the first 5 rows of your 'sample.csv' file blank per chance? If not selected, the df.head() returns (https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.head.html) the first 5 rows. So:

import pandas as pd
df = pd.DataFrame({'animal':['alligator', 'bee', 'falcon', 'lion', 'monkey', 'parrot', 'shark', 'whale', 'zebra']})

print(df.head())

      animal
0  alligator
1        bee
2     falcon
3       lion
4     monkey


问:
Recursion going infinite in clojure and not returning the values
I am new to clojure. Here you can see the function fp_fun. I am using this function and it goes to infinite. I think it is not returning the values. Please let me know the answer. Thanks in advance

(defn fp_fun
([x y row col vec]

(if (or (< x 0) (< y 0) (>= x row) (>= y col))
  0)
(if (= vec[x y] "@")
1)
(if (= vec[x y] "#")
0)

(def x1 (+ x 1))

(def y2 (- y 1))
(if (= ( (fp_fun x y2 row col vec)) 1  )
1)
(if (= ( (fp_fun x1 y row col vec)) 1  )
1)

1)
(println "!" x y)
0
) )
```

答:
To start with I'll apply the emacs auto formatter, then let's work through what each expression here means

```<code>(defn fp_fun
  ([x y row col vec]
   (if (or (< x 0)
           (< y 0)
           (>= x row)
           (>= y col))
     0)
   (if (= vec[x y] "@")
     1)
   (if (= vec[x y] "#")
     0)
   (def x1 (+ x 1))
   (def y2 (- y 1))
   (if (= ( (fp_fun x y2 row col vec)) 1  )
     1)
   (if (= ( (fp_fun x1 y row col vec)) 1  )
     1)
   1)
  (println "!" x y)
  0) )
</code>```

Initially this will not compile because there are two extra expressions after the main function body.

There are two main forms of the expression in clojure that defines functions they look basically like

```<code>((defn [args here]
   expression-that-returns-the-result-of-this-function-here)
</code>```

the second form if for when there are more than one way to call this function with different nubmers of arguments

```<code>(defn
  ([one-arg]
   result-expression-here)
  ([fist-arg second-arg]
   other-result-expression-here))
</code>```

what you have is a bit of both so let's remove the last two expressions:

```<code> (println "!" x y)
</code>```

and

```<code>0
</code>```

that leaves us with

```<code>(defn fp_fun
  ;; this function always takes 5 args, so prefer the basic form
  ([x y row col vec]

   ;; this first expression does absolutly nothing and it totally ignored
   (if (or (< x 0)
           (< y 0)
           (>= x row)
           (>= y col))
     0)

   ;; this next expression is also ignored, only the last value in a function determines it's result
   (if (= vec[x y] "@")
     1)

   ;; so this one does nothing as well
   (if (= vec[x y] "#")
     0)

   ;; these two define some global variables
   ;; using def inside a function is almost always better done with a let expression
   (def x1 (+ x 1))
   (def y2 (- y 1))

   ;; this will always run because none of the above statements cause the function to
   ;; stop and return it's value early.
   (if (= ( (fp_fun x y2 row col vec)) 1  )
     1)

   ;; and  then the stack will overflow before we get here
   (if (= ( (fp_fun x1 y row col vec)) 1  )
     1)
   1))
</code>```

Next we can nest the expressions so that the earlier ones get to control the result of the function:

```<code> (defn fp_fun [x y row col vec]
   (if (or (< x 0)
           (< y 0)
           (>= x row)
           (>= y col))
     0
     (if (= (vec x y) "@")
       1
       (if (= (vec x y) "#")
         0
         (let [x1 (+ x 1)
               y2 (- y 1)]
           (if (= (fp_fun x y2 row col vec) 1)
             1
             (if (= (fp_fun x1 y row col vec) 1)
               1)))))))
</code>```

I hope that gives you a structure to build your function from, the important part is that each function returns exactly one result, that result is whatever is returned by the last expression in the function. So usually that expression has other expressions nested in it.

As we add more if expressions it is starting to look a bit deeply nested and there is a common pattern of if followed by = fortunatly clojure has the cond, for conditional, macro for cleanly expressing patterns like this

```<code> (cond
   (or (< x 0) (< y 0) (>= x row) (>= y col)) 0
   (= (str(get-in board [x y])) "@")          1
   (= (str (get-in board [x y])) "#")         0
   (= (find_path x (- y 1) row col board) 1)  1
   (= (find_path (+ x 1) y row col board) 1)  1
   (and (>= x 0) (< y col))  (if (= (find_path x (+ y 1) row col board) 1)
                               1
                               0)
   :defautl nil) ;; i'm not sure you intended to default to nil
</code>```

Body:
To start with I'll apply the emacs auto formatter, then let's work through what each expression here means

(defn fp_fun
  ([x y row col vec]
   (if (or (< x 0)
           (< y 0)
           (>= x row)
           (>= y col))
     0)
   (if (= vec[x y] "@")
     1)
   (if (= vec[x y] "#")
     0)
   (def x1 (+ x 1))
   (def y2 (- y 1))
   (if (= ( (fp_fun x y2 row col vec)) 1  )
     1)
   (if (= ( (fp_fun x1 y row col vec)) 1  )
     1)
   1)
  (println "!" x y)
  0) )

Initially this will not compile because there are two extra expressions after the main function body.

There are two main forms of the expression in clojure that defines functions they look basically like

((defn [args here]
   expression-that-returns-the-result-of-this-function-here)

the second form if for when there are more than one way to call this function with different nubmers of arguments

(defn
  ([one-arg]
   result-expression-here)
  ([fist-arg second-arg]
   other-result-expression-here))

what you have is a bit of both so let's remove the last two expressions:

 (println "!" x y)

and

0

that leaves us with

(defn fp_fun
  ;; this function always takes 5 args, so prefer the basic form
  ([x y row col vec]

   ;; this first expression does absolutly nothing and it totally ignored
   (if (or (< x 0)
           (< y 0)
           (>= x row)
           (>= y col))
     0)

   ;; this next expression is also ignored, only the last value in a function determines it's result
   (if (= vec[x y] "@")
     1)

   ;; so this one does nothing as well
   (if (= vec[x y] "#")
     0)

   ;; these two define some global variables
   ;; using def inside a function is almost always better done with a let expression
   (def x1 (+ x 1))
   (def y2 (- y 1))

   ;; this will always run because none of the above statements cause the function to
   ;; stop and return it's value early.
   (if (= ( (fp_fun x y2 row col vec)) 1  )
     1)

   ;; and  then the stack will overflow before we get here
   (if (= ( (fp_fun x1 y row col vec)) 1  )
     1)
   1))

Next we can nest the expressions so that the earlier ones get to control the result of the function:

 (defn fp_fun [x y row col vec]
   (if (or (< x 0)
           (< y 0)
           (>= x row)
           (>= y col))
     0
     (if (= (vec x y) "@")
       1
       (if (= (vec x y) "#")
         0
         (let [x1 (+ x 1)
               y2 (- y 1)]
           (if (= (fp_fun x y2 row col vec) 1)
             1
             (if (= (fp_fun x1 y row col vec) 1)
               1)))))))

I hope that gives you a structure to build your function from, the important part is that each function returns exactly one result, that result is whatever is returned by the last expression in the function. So usually that expression has other expressions nested in it.

As we add more if expressions it is starting to look a bit deeply nested and there is a common pattern of if followed by = fortunatly clojure has the cond, for conditional, macro for cleanly expressing patterns like this

 (cond
   (or (< x 0) (< y 0) (>= x row) (>= y col)) 0
   (= (str(get-in board [x y])) "@")          1
   (= (str (get-in board [x y])) "#")         0
   (= (find_path x (- y 1) row col board) 1)  1
   (= (find_path (+ x 1) y row col board) 1)  1
   (and (>= x 0) (< y col))  (if (= (find_path x (+ y 1) row col board) 1)
                               1
                               0)
   :defautl nil) ;; i'm not sure you intended to default to nil


问:
how to send mail from .net?
i wrote the method as below i got the error as The specified string is not in the form required for an e-mail address. pls help me</p>

```<code>SendMail("xyz@gmail.com","hi","heloo");

public bool SendMail(string toMailAddress, string mailSubject, string mailMessage)
    {

         string smtphost ="smtp.gmail.com";
            int smtpport = 100;
            string smtpuser ="xyz";
            string smtppwd = "xyz";
            SmtpClient client = null;

            string MessageBody = string.Empty;
            try
            {

                message = new MailMessage();
                message.From = new MailAddress(smtpuser);
                message.To.Add(toMailAddress);
                message.BodyEncoding = System.Text.Encoding.UTF8;
                message.Subject = mailSubject;
                message.Body = mailMessage.ToString();

                message.IsBodyHtml = true;

                client = new SmtpClient();
                client.Host = smtphost;

                client.Port = smtpport;
                client.Credentials = new System.Net.NetworkCredential(smtpuser, smtppwd);
                client.Send(message);
            }
            catch (Exception ex)
            {
                string x = ex.Message;
            }
            return true;
        }
</code>```

答:
This code will work. What i have done are

proper smtphost

proper smtpport - 587

Enable SSL

set UseDefaultCredentials to false before setting the credentials

set DeliveryMethod

   ``` public static bool SendMail(string toMailAddress, string mailSubject, string   mailMessage)
    {
        string smtphost = "smtp.gmail.com";
        int smtpport = 587;
        string smtpuser = "youremail@gmail.com";
        string smtppwd = "password";

        SmtpClient client = null;

        string MessageBody = string.Empty;
        try
        {

            var message = new MailMessage();
            message.From = new MailAddress(smtpuser);
            message.To.Add(toMailAddress);
            message.BodyEncoding = System.Text.Encoding.UTF8;
            message.Subject = mailSubject;
            message.Body = mailMessage.ToString();
            message.IsBodyHtml = true;

            client = new SmtpClient();
            client.Host = smtphost;
            client.EnableSsl = true;
            client.Port = smtpport;
            client.UseDefaultCredentials = false;
            client.DeliveryMethod = SmtpDeliveryMethod.Network;
            client.Credentials = new System.Net.NetworkCredential(smtpuser, smtppwd);

            client.Send(message);
        }
        catch (Exception ex)
        {
            string x = ex.InnerException.Message;
            Console.WriteLine(x);
        }
        return true;

    }```

Title: how to send mail from .net?

Body:
i wrote the method as below i got the error as The specified string is not in the form required for an e-mail address. pls help me

SendMail("xyz@gmail.com","hi","heloo");

public bool SendMail(string toMailAddress, string mailSubject, string mailMessage)
    {

         string smtphost ="smtp.gmail.com";
            int smtpport = 100;
            string smtpuser ="xyz";
            string smtppwd = "xyz";
            SmtpClient client = null;

            string MessageBody = string.Empty;
            try
            {

                message = new MailMessage();
                message.From = new MailAddress(smtpuser);
                message.To.Add(toMailAddress);
                message.BodyEncoding = System.Text.Encoding.UTF8;
                message.Subject = mailSubject;
                message.Body = mailMessage.ToString();

                message.IsBodyHtml = true;

                client = new SmtpClient();
                client.Host = smtphost;

                client.Port = smtpport;
                client.Credentials = new System.Net.NetworkCredential(smtpuser, smtppwd);
                client.Send(message);
            }
            catch (Exception ex)
            {
                string x = ex.Message;
            }
            return true;
        }

Body:
This code will work. What i have done are

proper smtphost

proper smtpport - 587

Enable SSL

set UseDefaultCredentials to false before setting the credentials

set DeliveryMethod

 public static bool SendMail(string toMailAddress, string mailSubject, string   mailMessage)
    {
        string smtphost = "smtp.gmail.com";
        int smtpport = 587;
        string smtpuser = "youremail@gmail.com";
        string smtppwd = "password";

        SmtpClient client = null;

        string MessageBody = string.Empty;
        try
        {

            var message = new MailMessage();
            message.From = new MailAddress(smtpuser);
            message.To.Add(toMailAddress);
            message.BodyEncoding = System.Text.Encoding.UTF8;
            message.Subject = mailSubject;
            message.Body = mailMessage.ToString();
            message.IsBodyHtml = true;

            client = new SmtpClient();
            client.Host = smtphost;
            client.EnableSsl = true;
            client.Port = smtpport;
            client.UseDefaultCredentials = false;
            client.DeliveryMethod = SmtpDeliveryMethod.Network;
            client.Credentials = new System.Net.NetworkCredential(smtpuser, smtppwd);

            client.Send(message);
        }
        catch (Exception ex)
        {
            string x = ex.InnerException.Message;
            Console.WriteLine(x);
        }
        return true;

    }


答:
It's possible to do that less elegantly but without regex - just a series of splits and clean ups:

```<code>import json

code = [your script above]

code2 = html.replace('½','').split('":"Taglia","options":[{')[1].split('}]}},"template"')[0].split('},{')

for i in range(len(code2)):
    data = json.loads('{'+code2[i]+'}')
    print(data['id'],data['label'])
</code>```

Output:

```<code>730 36
731 37
732 38
733 38
</code>```

etc.

Title: find all label and product in json python

Body:
I'm trying to find all label and product in text/javascript, but I don't have any idea to how do it. I'm trying to parse label, id  and products.

    var spConfigDisabledProducts = [-1
    , '290058', '290060', '290061', '290062', '290063', '290065', '290071', '290073', '290075', '290076', '290077', '290078'        ];
    var spConfig = new Product.Config({"attributes":{"959":{"id":"959","code":"aw_taglia","label":"Taglia","options":[{"id":"730","label":"36 ½","price":"0","oldPrice":"0","products":["290058"]},{"id":"731","label":"37 ½","price":"0","oldPrice":"0","products":["290060"]},{"id":"732","label":"38","price":"0","oldPrice":"0","products":["290061"]},{"id":"733","label":"38 ½","price":"0","oldPrice":"0","products":["290062"]},{"id":"734","label":"39","price":"0","oldPrice":"0","products":["290063"]},{"id":"735","label":"40","price":"0","oldPrice":"0","products":["290064"]},{"id":"736","label":"40 ½","price":"0","oldPrice":"0","products":["290065"]},{"id":"737","label":"41","price":"0","oldPrice":"0","products":["290066"]},{"id":"738","label":"42","price":"0","oldPrice":"0","products":["290067"]},{"id":"739","label":"42 ½","price":"0","oldPrice":"0","products":["290068"]},{"id":"740","label":"43","price":"0","oldPrice":"0","products":["290069"]},{"id":"741","label":"44","price":"0","oldPrice":"0","products":["290070"]},{"id":"742","label":"44 ½","price":"0","oldPrice":"0","products":["290071"]},{"id":"743","label":"45","price":"0","oldPrice":"0","products":["290072"]},{"id":"744","label":"45 ½","price":"0","oldPrice":"0","products":["290073"]},{"id":"745","label":"46","price":"0","oldPrice":"0","products":["290074"]},{"id":"746","label":"47","price":"0","oldPrice":"0","products":["290075"]},{"id":"747","label":"47 ½","price":"0","oldPrice":"0","products":["290076"]},{"id":"748","label":"13.5","price":"0","oldPrice":"0","products":["290077"]},{"id":"749","label":"48 ½","price":"0","oldPrice":"0","products":["290078"]}]}},"template":"#{price}\u00a0\u20ac","basePrice":"130","oldPrice":"130","productId":"290059","chooseText":"Seleziona","taxConfig":{"includeTax":true,"showIncludeTax":true,"showBothPrices":false,"defaultTax":0,"currentTax":0,"inclTaxTitle":"Incl. Tasse"}});
    jQuery("#attribute959 option").each(function () {
        var option = jQuery(this);
        var id = option.attr('value');
        jQuery.each(spConfig.config.attributes, function () {
            jQuery.each(this.options, function () {
                if (this.id == id) {
                    if (spConfigDisabledProducts.indexOf(this.products[0]) >= 0) {
                        option.data('disabled', true);
                    }
                }
            });
        });
    });

Body:
It's possible to do that less elegantly but without regex - just a series of splits and clean ups:

import json

code = [your script above]

code2 = html.replace('&frac12;','').split('":"Taglia","options":[{')[1].split('}]}},"template"')[0].split('},{')

for i in range(len(code2)):
    data = json.loads('{'+code2[i]+'}')
    print(data['id'],data['label'])

Output:

730 36
731 37
732 38
733 38

etc.


问:
Load RAW image to Canvas in WPF (C#)
I'm trying to load .RAW image from file and display it into canvas background (in WPF). File only contains HEX data (without header, but resolution and color is known) - photo viewer cannot display it (because there is no info in header), however in IrfranView after resolution and color is specified, it can be displayed.

Sorry if any duplicates exist, I tried to find some solutions carefully but unfortunately I couldn't find any solution, that worked int WPF. Mostly they were designed for Forms app, not WPF.

To specify my question:
How to load .raw data from file, convert it to bitmap and display it in canvas background? Width and height, color (32bit RGBA) are known and pixel HEX raw data are stored in .raw file.

答:
Welcome to SO.

Be aware that this question may get flagged for deletion because you haven't posted any code and you haven't asked a specific question. "Please write code for me" questions generally aren't well received in these parts, you might want to read up on the site rules.

To answer your question though, you don't load images onto a Canvas, you load them into an Image element (which can itself be placed inside a Canvas if you want). There are samples on the Microsoft site showing showing how to create one of these from a raw array of integers.

Title: Load RAW image to Canvas in WPF (C#)


问:
send email with vuejs
I want to send emails with laravel and vuejs. I wrote laravel controller function like below

```<code>Mail::send(['text' => 'mail'],['name', 'David'], function($message){
    $message->to('test123@gmail.com')->subject('Test Email');
    $message->from('testmail@gmail.com', 'David');
});
return response()->json(['success'=>true]);
</code>```

and I wrote a vuejs send email function for the @click method

```<code>this.axios.get('https://techwizlanka/send', {
    body: JSON.stringify(this.user),
    headers: {
        'content-type': 'application/json',
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
})
.then(res => res.json())
.then(data => {
    console.log("email sent");
})
.catch(err => console.error(err.toString()));
</code>```

I call this URL like this

```<code>Route::get('/send', 'MailController@sendMail');
</code>```

But it shows this error message when clicking the send button.

app.js:44786 Uncaught TypeError: Cannot read property 'get' of undefined
      at VueComponent.sendMail (app.js:44786)
      at invoker (app.js:34769)
      at HTMLButtonElement.fn._withTask.fn._withTask (app.js:34568)

Can anyone help me to fix this issue? Basically, I want to send an email when submitting a form with laravel and vuejs.

答:
try to use this method

```<code>axios.post(url, data)
      .then(response => {

})
</code>```

and make your route post in your route/web.php

in using get method function not expecting a request but in your situation you pass a request.

Title: send email with vuejs

Body:
I want to send emails with laravel and vuejs. I wrote laravel controller function like below

Mail::send(['text' => 'mail'],['name', 'David'], function($message){
    $message->to('test123@gmail.com')->subject('Test Email');
    $message->from('testmail@gmail.com', 'David');
});
return response()->json(['success'=>true]);

and I wrote a vuejs send email function for the @click method

this.axios.get('https://techwizlanka/send', {
    body: JSON.stringify(this.user),
    headers: {
        'content-type': 'application/json',
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
})
.then(res => res.json())
.then(data => {
    console.log("email sent");
})
.catch(err => console.error(err.toString()));

I call this URL like this

Route::get('/send', 'MailController@sendMail');

But it shows this error message when clicking the send button.

app.js:44786 Uncaught TypeError: Cannot read property 'get' of undefined
      at VueComponent.sendMail (app.js:44786)
      at invoker (app.js:34769)
      at HTMLButtonElement.fn._withTask.fn._withTask (app.js:34568)

Can anyone help me to fix this issue? Basically, I want to send an email when submitting a form with laravel and vuejs.

Body:
try to use this method

axios.post(url, data)
      .then(response => {

})

and make your route post in your route/web.php

in using get method function not expecting a request but in your situation you pass a request.


问:
Creating a open street maps view
I am trying to port this code: https://gist.github.com/ataffanel/13aac4b79bc0080b881f to the most recent versions of pyqt5, thus, using qtwebengine. The goal is just to have a map widget in the end.

This is the code I already have, running with random html and javascript it worked, but I cant get a map view how the original code is intended to.

Main.py:

```<code>
class MainWindow(QtWidgets.QWidget):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.setupUi()
        self.show()
        self.raise_()

    def setupUi(self):
        #self.setFixedSize(800, 500)
        vbox = QtWidgets.QVBoxLayout()
        self.setLayout(vbox)

        label = self.label = QtWidgets.QLabel()
        sp = QtWidgets.QSizePolicy()
        sp.setVerticalStretch(0)
        label.setSizePolicy(sp)
        vbox.addWidget(label)
        view = self.view = QtWebEngineWidgets.QWebEngineView()
        channel = self.channel = QWebChannel()

        channel.registerObject('MainWindow', self)
        view.page().setWebChannel(channel)
      # view.page().mainFrame().addToJavaScriptWindowObject("MainWindow", self)

      # view.page().setLinkDelegationPolicy(QQWebPage.DelegateAllLinks)
        html = open('src/main/assets/map.html','r').read()
        self.view.setHtml(html)
        view.loadFinished.connect(self.onLoadFinished)
        #view.linkClicked.connect(QtWidgets.QDesktopServices.openUrl)

        vbox.addWidget(view)

        button = QtWidgets.QPushButton('Go to Paris')
        panToParis = functools.partial(self.panMap, 2.3272, 48.8620)
        button.clicked.connect(panToParis)
        vbox.addWidget(button)

    def onLoadFinished(self, ok):
       if ok:
            page=self.view.page()
            with open('src/main/assets/map.js', 'r') as f:
                src=f.read()
                page.runJavaScript(src)

    @QtCore.pyqtSlot(float, float)
    def onMapMove(self, lat, lng):
        self.label.setText('Lng: {:.5f}, Lat: {:.5f}'.format(lng, lat))

    def panMap(self, lng, lat):
        page=self.view.page()
        page.runJavaScript('map.panTo(L.latLng({}, {}));'.format(lat, lng))

if __name__ == '__main__':
    app = QtWidgets.QApplication([])
    w = MainWindow()

app.exec_()
</code>```

map.html:

```<code><!DOCTYPE html>
<html>
<head>
    <script src="qrc:///qtwebchannel/qwebchannel.js"></script>
    <link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.css" />
    <script src="http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.js"></script>
    <style>
        body { padding: 0; margin: 0; }
        html, body, #map { height: 100%; }
    </style>
</head>
<body>
    <div id="map"></div>

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

map.js:

```<code>var map = L.map('map').setView([55.61121, 12.99351], 16);
L.tileLayer('http://otile{s}.mqcdn.com/tiles/1.0.0/map/{z}/{x}/{y}.png', {
    maxZoom: 18,
    attribution: 'Map data © <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, ' +
        'tiles Courtesy of <a href="http://www.mapquest.com/" target="_blank">MapQuest</a>',
    subdomains: '1234',
}).addTo(map);

var marker = L.marker(map.getCenter()).addTo(map);
marker.bindPopup("Hello World!").openPopup();

new QWebChannel(qt.webChannelTransport, function (channel) {
    window.MainWindow = channel.objects.MainWindow;

    if(typeof MainWindow != 'undefined') {
        var onMapMove = function() { MainWindow.onMapMove(map.getCenter().lat, map.getCenter().lng) };
        map.on('move', onMapMove);
        onMapMove();
    }
});
</code>```

There's no error message, just a blank screen where it was supposed to be a map.... I don't get why this happens since both the necessary javascript and html render if i change them to something else...

If there's a better way to create this widget would be enough too!

Thanks in advance!

答:
The main problem that your code has is that you are using URL template deprecated and old versions of leaflet.

On the other hand it is not necessary to load the html and js as text, QtWebEngine can show the file directly.

Considering the above, the solution is:

structure:

```<code>├── main.py
└── src
    └── main
        └── assets
            ├── map.html
            └── map.js
</code>```

map.js

```<code>var map;

function initialize(){
    map = L.map('map').setView([55.61121, 12.99351], 16);

    L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
        attribution: 'Map data © <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery © <a href="http://cloudmade.com">CloudMade</a>',
        maxZoom: 18
    }).addTo(map);

    var marker = L.marker(map.getCenter()).addTo(map);
    marker.bindPopup("Hello World!").openPopup();
    new QWebChannel(qt.webChannelTransport, function (channel) {
        window.MainWindow = channel.objects.MainWindow;
        if(typeof MainWindow != 'undefined') {
            var onMapMove = function() { MainWindow.onMapMove(map.getCenter().lat, map.getCenter().lng) };
            map.on('move', onMapMove);
            onMapMove();
        }
    });
}
</code>```

map.html

```<code><!DOCTYPE html>
<html>
<head>
    <script src="qrc:///qtwebchannel/qwebchannel.js"></script>
    <script src="https://unpkg.com/leaflet@1.0.2/dist/leaflet.js"></script>
    <link rel="stylesheet" href="https://unpkg.com/leaflet@1.0.2/dist/leaflet.css" />
    <script type="text/javascript" src="map.js"></script>
    <style>
        body { padding: 0; margin: 0; }
        html, body, #map { height: 100%; }
    </style>
</head>
<body onload="initialize()">
    <div id="map"></div>
</body>
</html>
</code>```

main.py

import os
import functools
from PyQt5 import QtCore, QtGui, QtWidgets, QtWebEngineWidgets, QtWebChannel

class MainWindow(QtWidgets.QWidget):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.setupUi()

    def setupUi(self):
        # self.setFixedSize(800, 500)
        vbox = QtWidgets.QVBoxLayout()
        self.setLayout(vbox)

        label = self.label = QtWidgets.QLabel()
        sp = QtWidgets.QSizePolicy()
        sp.setVerticalStretch(0)
        label.setSizePolicy(sp)
        vbox.addWidget(label)
        view = self.view = QtWebEngineWidgets.QWebEngineView()
        channel = self.channel = QtWebChannel.QWebChannel()

        channel.registerObject("MainWindow", self)
        view.page().setWebChannel(channel)

        file = os.path.join(
            os.path.dirname(os.path.realpath(__file__)),
            "src/main/assets/map.html",
        )
        self.view.setUrl(QtCore.QUrl.fromLocalFile(file))

        vbox.addWidget(view)

        button = QtWidgets.QPushButton("Go to Paris")
        panToParis = functools.partial(self.panMap, 2.3272, 48.8620)
        button.clicked.connect(panToParis)
        vbox.addWidget(button)

    @QtCore.pyqtSlot(float, float)
    def onMapMove(self, lat, lng):
        self.label.setText("Lng: {:.5f}, Lat: {:.5f}".format(lng, lat))

    def panMap(self, lng, lat):
        page = self.view.page()
        page.runJavaScript("map.panTo(L.latLng({}, {}));".format(lat, lng))

if __name__ == "__main__":
    import sys

    app = QtWidgets.QApplication(sys.argv)
    w = MainWindow()
    w.show()
    sys.exit(app.exec_())
```

Output:

Title: Creating a open street maps view

Body:
I am trying to port this code: https://gist.github.com/ataffanel/13aac4b79bc0080b881f to the most recent versions of pyqt5, thus, using qtwebengine. The goal is just to have a map widget in the end.

This is the code I already have, running with random html and javascript it worked, but I cant get a map view how the original code is intended to.

Main.py:

class MainWindow(QtWidgets.QWidget):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.setupUi()
        self.show()
        self.raise_()

    def setupUi(self):
        #self.setFixedSize(800, 500)
        vbox = QtWidgets.QVBoxLayout()
        self.setLayout(vbox)

        label = self.label = QtWidgets.QLabel()
        sp = QtWidgets.QSizePolicy()
        sp.setVerticalStretch(0)
        label.setSizePolicy(sp)
        vbox.addWidget(label)
        view = self.view = QtWebEngineWidgets.QWebEngineView()
        channel = self.channel = QWebChannel()

        channel.registerObject('MainWindow', self)
        view.page().setWebChannel(channel)
      # view.page().mainFrame().addToJavaScriptWindowObject("MainWindow", self)

      # view.page().setLinkDelegationPolicy(QQWebPage.DelegateAllLinks)
        html = open('src/main/assets/map.html','r').read()
        self.view.setHtml(html)
        view.loadFinished.connect(self.onLoadFinished)
        #view.linkClicked.connect(QtWidgets.QDesktopServices.openUrl)

        vbox.addWidget(view)

        button = QtWidgets.QPushButton('Go to Paris')
        panToParis = functools.partial(self.panMap, 2.3272, 48.8620)
        button.clicked.connect(panToParis)
        vbox.addWidget(button)

    def onLoadFinished(self, ok):
       if ok:
            page=self.view.page()
            with open('src/main/assets/map.js', 'r') as f:
                src=f.read()
                page.runJavaScript(src)

    @QtCore.pyqtSlot(float, float)
    def onMapMove(self, lat, lng):
        self.label.setText('Lng: {:.5f}, Lat: {:.5f}'.format(lng, lat))

    def panMap(self, lng, lat):
        page=self.view.page()
        page.runJavaScript('map.panTo(L.latLng({}, {}));'.format(lat, lng))

if __name__ == '__main__':
    app = QtWidgets.QApplication([])
    w = MainWindow()

app.exec_()

map.html:

<!DOCTYPE html>

    <link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.css" />

map.js:

var map = L.map('map').setView([55.61121, 12.99351], 16);
L.tileLayer('http://otile{s}.mqcdn.com/tiles/1.0.0/map/{z}/{x}/{y}.png', {
    maxZoom: 18,
    attribution: 'Map data © OpenStreetMap contributors, ' +
        'tiles Courtesy of MapQuest',
    subdomains: '1234',
}).addTo(map);

var marker = L.marker(map.getCenter()).addTo(map);
marker.bindPopup("Hello World!").openPopup();

new QWebChannel(qt.webChannelTransport, function (channel) {
    window.MainWindow = channel.objects.MainWindow;

    if(typeof MainWindow != 'undefined') {
        var onMapMove = function() { MainWindow.onMapMove(map.getCenter().lat, map.getCenter().lng) };
        map.on('move', onMapMove);
        onMapMove();
    }
});

There's no error message, just a blank screen where it was supposed to be a map.... I don't get why this happens since both the necessary javascript and html render if i change them to something else...

If there's a better way to create this widget would be enough too!

Thanks in advance!

Body:
The main problem that your code has is that you are using URL template deprecated and old versions of leaflet.

On the other hand it is not necessary to load the html and js as text, QtWebEngine can show the file directly.

Considering the above, the solution is:

structure:

├── main.py
└── src
    └── main
        └── assets
            ├── map.html
            └── map.js

map.js

var map;

function initialize(){
    map = L.map('map').setView([55.61121, 12.99351], 16);

    L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
        attribution: 'Map data &copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery © <a href="http://cloudmade.com">CloudMade</a>',
        maxZoom: 18
    }).addTo(map);

    var marker = L.marker(map.getCenter()).addTo(map);
    marker.bindPopup("Hello World!").openPopup();
    new QWebChannel(qt.webChannelTransport, function (channel) {
        window.MainWindow = channel.objects.MainWindow;
        if(typeof MainWindow != 'undefined') {
            var onMapMove = function() { MainWindow.onMapMove(map.getCenter().lat, map.getCenter().lng) };
            map.on('move', onMapMove);
            onMapMove();
        }
    });
}

map.html

<!DOCTYPE html>
<html>
<head>
    <script src="qrc:///qtwebchannel/qwebchannel.js"></script>
    <script src="https://unpkg.com/leaflet@1.0.2/dist/leaflet.js"></script>
    <link rel="stylesheet" href="https://unpkg.com/leaflet@1.0.2/dist/leaflet.css" />
    <script type="text/javascript" src="map.js"></script>
    <style>
        body { padding: 0; margin: 0; }
        html, body, #map { height: 100%; }
    </style>
</head>
<body onload="initialize()">
    <div id="map"></div>
</body>
</html>

main.py

import os
import functools
from PyQt5 import QtCore, QtGui, QtWidgets, QtWebEngineWidgets, QtWebChannel

class MainWindow(QtWidgets.QWidget):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.setupUi()

    def setupUi(self):
        # self.setFixedSize(800, 500)
        vbox = QtWidgets.QVBoxLayout()
        self.setLayout(vbox)

        label = self.label = QtWidgets.QLabel()
        sp = QtWidgets.QSizePolicy()
        sp.setVerticalStretch(0)
        label.setSizePolicy(sp)
        vbox.addWidget(label)
        view = self.view = QtWebEngineWidgets.QWebEngineView()
        channel = self.channel = QtWebChannel.QWebChannel()

        channel.registerObject("MainWindow", self)
        view.page().setWebChannel(channel)

        file = os.path.join(
            os.path.dirname(os.path.realpath(__file__)),
            "src/main/assets/map.html",
        )
        self.view.setUrl(QtCore.QUrl.fromLocalFile(file))

        vbox.addWidget(view)

        button = QtWidgets.QPushButton("Go to Paris")
        panToParis = functools.partial(self.panMap, 2.3272, 48.8620)
        button.clicked.connect(panToParis)
        vbox.addWidget(button)

    @QtCore.pyqtSlot(float, float)
    def onMapMove(self, lat, lng):
        self.label.setText("Lng: {:.5f}, Lat: {:.5f}".format(lng, lat))

    def panMap(self, lng, lat):
        page = self.view.page()
        page.runJavaScript("map.panTo(L.latLng({}, {}));".format(lat, lng))

if __name__ == "__main__":
    import sys

    app = QtWidgets.QApplication(sys.argv)
    w = MainWindow()
    w.show()
    sys.exit(app.exec_())

Output:


问:
Trying to sort a list using bootstrap and js
Here is a image of the table i get

Im trying to order a list with names of patients i get from the fhir example datebase. i have been working on this for at least 10 hours now am im really frustrated. i found a w3c example code for sorting the table data, it works when i use their examples, but not when i include mine.

i basically tried everything.
javascript DOES work in my project

<!DOCTYPE html>

    <title>Welcome to the Template-Engine</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <#include "header.ftl">

Welcome to 0000 FHIR

Searching for Patients

Using FHIR ${p_repo} - corresponding information at ${p_info}

Overall Number of patients: ${p_total}

            <fieldset>

                <legend>Patient suchen</legend>
                    <form action="/patient2/addPatient" method="POST">

                            Vorname: <input type="text" name="vorname" placeholder="Vorname" class="form-control" />

                            Nachname: <input type="text" name="nachname" placeholder="Nachname" class="form-control" />

                            Geburtsdatum: <input type="date" name="date" placeholder="..." class="form-control" />

                            <input type="submit" value="Suchen" class="btn btn-secondary btn-lg"/>

                    </form>
            </fliedset>

                     ID
                    Name
                    Gender
                    Birthdate

                <#list patientList as p>

                        ${(p.id)!"NA"}
                        ${(p.name)!"NA"}
                        ${(p.gender)!"NA"}
                        ${(p.birthdate)!"NA"}

                </#list>

```

it sounds dumb but i have to get this done for uni and im really on the edge to cry.

答:
Sometimes even little typos cause big problems. Look at the 4th  col in your #myTable table table head. Should be scope="col"

Doesn't sound dumb, we've all been there!
Hope this helps. Good luck.

Body:
Here is a image of the table i get

Im trying to order a list with names of patients i get from the fhir example datebase. i have been working on this for at least 10 hours now am im really frustrated. i found a w3c example code for sorting the table data, it works when i use their examples, but not when i include mine.

i basically tried everything.
javascript DOES work in my project

<!DOCTYPE html>

    <title>Welcome to the Template-Engine</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <#include "header.ftl">

Welcome to 0000 FHIR

Searching for Patients

Using FHIR ${p_repo} - corresponding information at ${p_info}

Overall Number of patients: ${p_total}

            <fieldset>

                <legend>Patient suchen</legend>
                    <form action="/patient2/addPatient" method="POST">

                            Vorname: <input type="text" name="vorname" placeholder="Vorname" class="form-control" />

                            Nachname: <input type="text" name="nachname" placeholder="Nachname" class="form-control" />

                            Geburtsdatum: <input type="date" name="date" placeholder="..." class="form-control" />

                            <input type="submit" value="Suchen" class="btn btn-secondary btn-lg"/>

                    </form>
            </fliedset>

                     ID
                    Name
                    Gender
                    Birthdate

                <#list patientList as p>

                        ${(p.id)!"NA"}
                        ${(p.name)!"NA"}
                        ${(p.gender)!"NA"}
                        ${(p.birthdate)!"NA"}

                </#list>

it sounds dumb but i have to get this done for uni and im really on the edge to cry.


问:
Obtain create objects for VSI and Bare Metal by datacenter
I am investigating a method using REST API to obtain valid objects I can use on a create of a VSI or Bare Metal in a specific datacenters.
Information needed:
 1. Private network speed 10Gbs or 1Gbs
 2. Machine types supported, if a vGPU is supported is machine type a V100 or P100.

Can you help me with some guidance on methods to use and how to filter by datacenter? Thanks.

答:
If you wish to retrieve items from a specific datecenter, you can  to use SoftLayer_Product_Package::getItemPrices, for example, the rest API call below retrieves all   network speed items  greater than 1000 Mbps in ams01 for the VSI package Id (eg. 835 "PUBLIC_CLOUD_SERVER"):

Method: GET

```<code>https://username:apikey@api.softlayer.com/rest/v3.1/SoftLayer_Product_Package/835/getItemPrices?objectMask=mask[id,item,pricingLocationGroup[locations[name]]]&objectFilter={"itemPrices":{"pricingLocationGroup":{"locations":{"name":{"operation":"ams01"}}},"item":{"itemCategory":{"categoryCode":{"operation":"port_speed"}},"capacity":{"operation":">=1000"}}}}
</code>```

You can use a bare metal package Id (eg. 200 "BARE_METAL_SERVER"), in order to retrieve items for Bare Metal. Also, I suggest you use standard prices and use them with any datacenter.

Method: GET

```<code>https://username:apikey@api.softlayer.com/rest/v3.1/SoftLayer_Product_Package/200/getItemPrices?objectMask=mask[id,locationGroupId,item[itemCategory],pricingLocationGroup[locations[name]]]&objectFilter={"itemPrices":{"locationGroupId":{"operation":"is null"},"item":{"itemCategory":{"categoryCode":{"operation":"port_speed"}},"capacity":{"operation":">=1000"}}}}
</code>```

Keep in mind that the API call above, retrieves standard prices for bare metal, and if you wish to get standard prices for VSI you will have to use a package Id for VSI.

References:

https://sldn.softlayer.com/article/understanding-ordering/
https://sldn.softlayer.com/python/ordering_slcli/

Body:
If you wish to retrieve items from a specific datecenter, you can  to use SoftLayer_Product_Package::getItemPrices, for example, the rest API call below retrieves all   network speed items  greater than 1000 Mbps in ams01 for the VSI package Id (eg. 835 "PUBLIC_CLOUD_SERVER"):

Method: GET

https://username:apikey@api.softlayer.com/rest/v3.1/SoftLayer_Product_Package/835/getItemPrices?objectMask=mask[id,item,pricingLocationGroup[locations[name]]]&objectFilter={"itemPrices":{"pricingLocationGroup":{"locations":{"name":{"operation":"ams01"}}},"item":{"itemCategory":{"categoryCode":{"operation":"port_speed"}},"capacity":{"operation":">=1000"}}}}

You can use a bare metal package Id (eg. 200 "BARE_METAL_SERVER"), in order to retrieve items for Bare Metal. Also, I suggest you use standard prices and use them with any datacenter.

Method: GET

https://username:apikey@api.softlayer.com/rest/v3.1/SoftLayer_Product_Package/200/getItemPrices?objectMask=mask[id,locationGroupId,item[itemCategory],pricingLocationGroup[locations[name]]]&objectFilter={"itemPrices":{"locationGroupId":{"operation":"is null"},"item":{"itemCategory":{"categoryCode":{"operation":"port_speed"}},"capacity":{"operation":">=1000"}}}}

Keep in mind that the API call above, retrieves standard prices for bare metal, and if you wish to get standard prices for VSI you will have to use a package Id for VSI.

References:

https://sldn.softlayer.com/article/understanding-ordering/
https://sldn.softlayer.com/python/ordering_slcli/