问:
Ajax Post request not working on mobile devices
I am having an issue in which I am sending an Ajax post request to the server after a .on('click') event in jQuery, but the Ajax request is not working on mobile devices. On desktop devices it works perfectly fine. That led me to doing some research. The first issue that I found was that the click event may not register on touch screen devices, but that wasn't the issue. The touch event triggered after I issued some alert messages when the button was touched on mobile devices. On both iOS and Android devices the touch event triggered, but not the Ajax request. I also added touchstart to make sure the event would trigger on touch devices. Another potential issue that I researched was that there might be some issues on iOS and Android devices if you do not specify an expected datatype returned from the server after a post request (plain-text, json ect…). I specified the dataType and there were still issues with the request. Lastly, I saw that there might be some caching issues, so I set the cache argument to false and in the headers specified no-cache. This didn't solve the issue either. With each "fix" that I attempted, the Ajax request still executed perfectly on desktop devices, but not on mobile devices. As I mentioned, the click event in it of itself was registered on mobile devices because when I issued alerts before the Ajax request they were shown on mobile devices. However, the Ajax request itself would not execute. Here is my code below:

```<code>$('.crop_image').on('click touchstart', function(event){
    alert("Triggered"); //Event triggered on mobile devices
    $image_crop.croppie('result', {
        size: 'viewport',
        format: 'png',
        type: 'blob'
   }).then(function (blob){
        $form = $('#uploadForm');
        var fd = new FormData($form);
        fd.append('upload_image', blob);
        $.ajax({
            url: "handle-image.html",
            type: "POST",
            data: fd,
            processData: false, //processData false
            contentType: false, //contentType false
            dataType: "text",  //response will be text
            cache: false,  //cache false
            headers: {
                "cache-control": "no-cache" //set headers
            },
            success: function (data){
                alert("Upload Successful"); //Only succeeds and executes on desktop
                $('#uploadImageModal').modal('hide');
                $('#uploaded_image').html(data);
            }
        });
    })
});
</code>```

I'm stumped as to why this is failing on mobile devices. I figured that one issue could be that I am sending a blob via Ajax, and maybe mobile devices cannot handle the blob format, but after further review, I saw no evidence to support that. That's why I am wondering what I could be missing here. As a side note, my form is not in the same place as the Button because my Button is in a modal. Since I am using form data I assumed that not having a submit Button within the actual form would not cause an issue, and again, this is not an issue on Desktop and Laptop devices.

答:
This is multipart/form-data, so I needed to change the enctype.

This was why I was having issues on some devices, and since this post the issue have been solved.

In the ajax request I simply needed to add:

```<code>enctype: 'multipart/form-data',
</code>```

and this resolved the issue.

Body:
I am having an issue in which I am sending an Ajax post request to the server after a .on('click') event in jQuery, but the Ajax request is not working on mobile devices. On desktop devices it works perfectly fine. That led me to doing some research. The first issue that I found was that the click event may not register on touch screen devices, but that wasn't the issue. The touch event triggered after I issued some alert messages when the button was touched on mobile devices. On both iOS and Android devices the touch event triggered, but not the Ajax request. I also added touchstart to make sure the event would trigger on touch devices. Another potential issue that I researched was that there might be some issues on iOS and Android devices if you do not specify an expected datatype returned from the server after a post request (plain-text, json ect…). I specified the dataType and there were still issues with the request. Lastly, I saw that there might be some caching issues, so I set the cache argument to false and in the headers specified no-cache. This didn't solve the issue either. With each "fix" that I attempted, the Ajax request still executed perfectly on desktop devices, but not on mobile devices. As I mentioned, the click event in it of itself was registered on mobile devices because when I issued alerts before the Ajax request they were shown on mobile devices. However, the Ajax request itself would not execute. Here is my code below:

$('.crop_image').on('click touchstart', function(event){
    alert("Triggered"); //Event triggered on mobile devices
    $image_crop.croppie('result', {
        size: 'viewport',
        format: 'png',
        type: 'blob'
   }).then(function (blob){
        $form = $('#uploadForm');
        var fd = new FormData($form);
        fd.append('upload_image', blob);
        $.ajax({
            url: "handle-image.html",
            type: "POST",
            data: fd,
            processData: false, //processData false
            contentType: false, //contentType false
            dataType: "text",  //response will be text
            cache: false,  //cache false
            headers: {
                "cache-control": "no-cache" //set headers
            },
            success: function (data){
                alert("Upload Successful"); //Only succeeds and executes on desktop
                $('#uploadImageModal').modal('hide');
                $('#uploaded_image').html(data);
            }
        });
    })
});

I'm stumped as to why this is failing on mobile devices. I figured that one issue could be that I am sending a blob via Ajax, and maybe mobile devices cannot handle the blob format, but after further review, I saw no evidence to support that. That's why I am wondering what I could be missing here. As a side note, my form is not in the same place as the Button because my Button is in a modal. Since I am using form data I assumed that not having a submit Button within the actual form would not cause an issue, and again, this is not an issue on Desktop and Laptop devices.

Body:
This is multipart/form-data, so I needed to change the enctype.

This was why I was having issues on some devices, and since this post the issue have been solved.

In the ajax request I simply needed to add:

enctype: 'multipart/form-data',

and this resolved the issue.


来源: stackexchange

问:
Google Maps V3 - How to calculate the zoom level for a given bounds
I'm looking for a way to calculate the zoom level for a given bounds using the Google Maps V3 API, similar to getBoundsZoomLevel() in the V2 API.

Here is what I want to do:

// These are exact bounds previously captured from the map object
var sw = new google.maps.LatLng(42.763479, -84.338918);
var ne = new google.maps.LatLng(42.679488, -84.524313);
var bounds = new google.maps.LatLngBounds(sw, ne);
var zoom = // do some magic to calculate the zoom level

// Set the map to these exact bounds
map.setCenter(bounds.getCenter());
map.setZoom(zoom);

// NOTE: fitBounds() will not work
```

<p>Unfortunately, I can't use the <code>fitBounds()</code> method for my particular use case. It works well for fitting markers on the map, but it does not work well for setting exact bounds. Here is an example of why I can't use the <code>fitBounds()</code> method.</p>

<pre class="lang-js prettyprint-override"><code>map.fitBounds(map.getBounds()); // not what you expect
</code>```

答:
Here a Kotlin version of the function:</p>
```<code>fun getBoundsZoomLevel(bounds: LatLngBounds, mapDim: Size): Double {
        val WORLD_DIM = Size(256, 256)
        val ZOOM_MAX = 21.toDouble();

        fun latRad(lat: Double): Double {
            val sin = Math.sin(lat * Math.PI / 180);
            val radX2 = Math.log((1 + sin) / (1 - sin)) / 2;
            return max(min(radX2, Math.PI), -Math.PI) /2
        }

        fun zoom(mapPx: Int, worldPx: Int, fraction: Double): Double {
            return floor(Math.log(mapPx / worldPx / fraction) / Math.log(2.0))
        }

        val ne = bounds.northeast;
        val sw = bounds.southwest;

        val latFraction = (latRad(ne.latitude) - latRad(sw.latitude)) / Math.PI;

        val lngDiff = ne.longitude - sw.longitude;
        val lngFraction = if (lngDiff < 0) { (lngDiff + 360) / 360 } else { (lngDiff / 360) }

        val latZoom = zoom(mapDim.height, WORLD_DIM.height, latFraction);
        val lngZoom = zoom(mapDim.width, WORLD_DIM.width, lngFraction);

        return minOf(latZoom, lngZoom, ZOOM_MAX)
    }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm looking for a way to calculate the zoom level for a given bounds using the Google Maps V3 API, similar to getBoundsZoomLevel() in the V2 API.

Here is what I want to do:

// These are exact bounds previously captured from the map object
var sw = new google.maps.LatLng(42.763479, -84.338918);
var ne = new google.maps.LatLng(42.679488, -84.524313);
var bounds = new google.maps.LatLngBounds(sw, ne);
var zoom = // do some magic to calculate the zoom level

// Set the map to these exact bounds
map.setCenter(bounds.getCenter());
map.setZoom(zoom);

// NOTE: fitBounds() will not work

Unfortunately, I can't use the fitBounds() method for my particular use case. It works well for fitting markers on the map, but it does not work well for setting exact bounds. Here is an example of why I can't use the fitBounds() method.

map.fitBounds(map.getBounds()); // not what you expect

Body:
Here a Kotlin version of the function:

fun getBoundsZoomLevel(bounds: LatLngBounds, mapDim: Size): Double {
        val WORLD_DIM = Size(256, 256)
        val ZOOM_MAX = 21.toDouble();

        fun latRad(lat: Double): Double {
            val sin = Math.sin(lat * Math.PI / 180);
            val radX2 = Math.log((1 + sin) / (1 - sin)) / 2;
            return max(min(radX2, Math.PI), -Math.PI) /2
        }

        fun zoom(mapPx: Int, worldPx: Int, fraction: Double): Double {
            return floor(Math.log(mapPx / worldPx / fraction) / Math.log(2.0))
        }

        val ne = bounds.northeast;
        val sw = bounds.southwest;

        val latFraction = (latRad(ne.latitude) - latRad(sw.latitude)) / Math.PI;

        val lngDiff = ne.longitude - sw.longitude;
        val lngFraction = if (lngDiff < 0) { (lngDiff + 360) / 360 } else { (lngDiff / 360) }

        val latZoom = zoom(mapDim.height, WORLD_DIM.height, latFraction);
        val lngZoom = zoom(mapDim.width, WORLD_DIM.width, lngFraction);

        return minOf(latZoom, lngZoom, ZOOM_MAX)
    }


问:
Creating another column in R
This is my current data set

I want to take the numbers after "narrow" (e.g. 20) and make another vector. Any idea how I can do that?

答:
Maybe you can try the code below, using regmatches

```<code>df$new <- with(df, as.numeric(unlist(regmatches(stimulus,gregexpr("\\d+",stimulus)))))
</code>```

Title: Creating another column in R

Body:
Maybe you can try the code below, using regmatches

df$new <- with(df, as.numeric(unlist(regmatches(stimulus,gregexpr("\\d+",stimulus)))))


问:
how do i Delay a component html from loading till all images are gotten?
i have a home page where i want to display the first 3 images as a slider which are called from an API.
this is my controller

```<code>export class ClientComponent implements OnInit {   public event;   public imgePAth: any;   public singleImg: any;   public secondImg: any;   public isAv: boolean = false;   filtersLoaded: Promise<boolean>;

  constructor(private servive: TycketService, private http: HttpClient,private route: Router) { }

  ngOnInit() {
    this.servive.allEvent().subscribe(data => {
      this.event = data;
      console.log(this.event);

      this.imgePAth = this.servive.imagebaseUrl(this.event[0]['image']);
      this.singleImg = this.servive.imagebaseUrl(this.event[1]['image']);
      this.secondImg = this.servive.imagebaseUrl(this.event[2]['image']);
      this.isAv = true;
      this.filtersLoaded = Promise.resolve(true);
      console.log(this.imgePAth);
    });   } }
</code>```

my api service

```<code>  imagebaseUrl(data){
    return (this.imageUrl + data);
  }
</code>```

my html ignore the event index, i am setting the background image w the [ngStyle], when i inspect i get an undefined path of the variable, but when i console.log the path in my ngOnInit i get the right path

```<code><div class="cover_slider owl-carousel owl-theme" *ngIf="filtersLoaded | async">
        <div class="overlay">
            <div class="cover_item" [ngStyle]="{'background-image':'url('+imgePAth+')'}">
                <div class="slider_content">
                    <div class="slider-content-inner">
                        <div class="container">
                            <div class="slider-content-center" *ngIf="event && event[0]">
                                <h2 class="cover-title">
                                    Prepare yourself for
                                </h2>
                                <strong class="cover-xl-text">{{event[0]['name']}}</strong>
                                <p class="cover-date">
                                    {{event[0]['date']}}  - {{event[0]['venue']}} {{event[0]['location']}}.
                                </p>
                                <button class=" btn btn-primary btn-rounded" (click)="onClickBuy(event[0])">Buy Tickets Now</button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
</div>
</code>```

what is the solution for this?
enter image description here

答:
I suggest you use a tap pipe on your Observable

```<code>import { tap } from 'rxjs/operators';

 this.servive.allEvent().pipe(tap(_ => {
    // image loading code that you want to execute
   })).subscribe((val) => {
   console.log(val);
   });
</code>```

EDIT

```<code>*ngIf="event && event[0]"
</code>```

should be

```<code>*ngIf="event"
</code>```

Do you only want to display this block of code if event array has something inside? Just having event will give you a truthy value if something is there. If there is nothing in your array, then event[0] could be undefined and throw an error.

Body:
i have a home page where i want to display the first 3 images as a slider which are called from an API.
this is my controller

export class ClientComponent implements OnInit {   public event;   public imgePAth: any;   public singleImg: any;   public secondImg: any;   public isAv: boolean = false;   filtersLoaded: Promise<boolean>;

  constructor(private servive: TycketService, private http: HttpClient,private route: Router) { }

  ngOnInit() {
    this.servive.allEvent().subscribe(data => {
      this.event = data;
      console.log(this.event);

      this.imgePAth = this.servive.imagebaseUrl(this.event[0]['image']);
      this.singleImg = this.servive.imagebaseUrl(this.event[1]['image']);
      this.secondImg = this.servive.imagebaseUrl(this.event[2]['image']);
      this.isAv = true;
      this.filtersLoaded = Promise.resolve(true);
      console.log(this.imgePAth);
    });   } }

my api service

  imagebaseUrl(data){
    return (this.imageUrl + data);
  }

my html ignore the event index, i am setting the background image w the [ngStyle], when i inspect i get an undefined path of the variable, but when i console.log the path in my ngOnInit i get the right path

                                    Prepare yourself for

                                {{event[0]['name']}}

                                    {{event[0]['date']}}  - {{event[0]['venue']}} {{event[0]['location']}}.

                                <button class=" btn btn-primary btn-rounded" (click)="onClickBuy(event[0])">Buy Tickets Now</button>

what is the solution for this?
enter image description here

Body:
I suggest you use a tap pipe on your Observable

import { tap } from 'rxjs/operators';

 this.servive.allEvent().pipe(tap(_ => {
    // image loading code that you want to execute
   })).subscribe((val) => {
   console.log(val);
   });

EDIT

*ngIf="event && event[0]"

should be

*ngIf="event"

Do you only want to display this block of code if event array has something inside? Just having event will give you a truthy value if something is there. If there is nothing in your array, then event[0] could be undefined and throw an error.


问:
Error: Reverse for 'get_detail' not found. 'get_detail' is not a valid view function or pattern name
I am new to Django and facing the following issue.

My Template file index.html:

```<code><a href = "{% url 'polls:get_detail' question.id %}" class="btn btn-success btn-sm">Vote</a>
</code>```

I am passing question.id to the url and my urls.py:

```<code>app_name = 'polls'
urlpatterns = [
    path('',views.index, name='index'),
    path('<int:question_id>',views.get_detail, name='get_datail')
    ]
</code>```

and part of my views.py:

```<code> def get_detail(request,question_id):
    try:
        question = Question.objects.get(pk=question_id)
    except Question.DoesNotExist:
        raise Http404("Question not exist")
    return render(request,'polls/result.html',{ 'question':question })
</code>```

After running this I am getting below error:

Reverse for 'get_detail' not found. 'get_detail' is not a valid view function or pattern name.

I am using Django version : 3.0.3.
Thank you.

答:
Looks like you have a type error.

In your template you have 'polls:get_detail', and in your urls.py you named your url name='get_datail'

Body:
I am new to Django and facing the following issue.

My Template file index.html:

Vote

I am passing question.id to the url and my urls.py:

app_name = 'polls'
urlpatterns = [
    path('',views.index, name='index'),
    path('<int:question_id>',views.get_detail, name='get_datail')
    ]

and part of my views.py:

 def get_detail(request,question_id):
    try:
        question = Question.objects.get(pk=question_id)
    except Question.DoesNotExist:
        raise Http404("Question not exist")
    return render(request,'polls/result.html',{ 'question':question })

After running this I am getting below error:

Reverse for 'get_detail' not found. 'get_detail' is not a valid view function or pattern name.

I am using Django version : 3.0.3.
Thank you.


问:
How can I use SSL encryption in WCF
I have simple application from this tutorial: WCF 4 Getting Started Tutorial

How can I implement some encryption? Something like HTTPS (SSL?).

Example code from tutorial.

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

        // Step 1 of the address configuration procedure: Create a URI to serve as the base address.
        Uri baseAddress = new Uri("http://localhost:8000/ServiceModelSamples/Service");

        // Step 2 of the hosting procedure: Create ServiceHost
        ServiceHost selfHost = new ServiceHost(typeof(CalculatorService), baseAddress);

        try
        {

            // Step 3 of the hosting procedure: Add a service endpoint.
            selfHost.AddServiceEndpoint(
                typeof(ICalculator),
                new WSHttpBinding(),
                "CalculatorService");

            // Step 4 of the hosting procedure: Enable metadata exchange.
            ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
            smb.HttpGetEnabled = true;
            selfHost.Description.Behaviors.Add(smb);

            // Step 5 of the hosting procedure: Start (and then stop) the service.
            selfHost.Open();
            Console.WriteLine("The service is ready.");
            Console.WriteLine("Press <ENTER> to terminate service.");
            Console.WriteLine();
            Console.ReadLine();

            // Close the ServiceHostBase to shutdown the service.
            selfHost.Close();
        }
        catch (CommunicationException ce)
        {
            Console.WriteLine("An exception occurred: {0}", ce.Message);
            selfHost.Abort();
        }

    }
</code>```

答:
If you want to have https in you IIS7 web site, you can try this:

Change enabled protocol value "https" to your advance settings of the web site.

Add bindings https port number eg: localhost:81

Add SSL Settings to your web site.

Then access your site using http://fullyqnameofyourcomputer:81
If you want to access the WCF Service with basic binding with the secure site, just make sure you add securicty mode (Not None) in you client config.

ContentLicense: CC BY-SA 3.0

Title: How can I use SSL encryption in WCF

Body:
I have simple application from this tutorial: WCF 4 Getting Started Tutorial

How can I implement some encryption? Something like HTTPS (SSL?).

Example code from tutorial.

static void Main(string[] args)
    {

        // Step 1 of the address configuration procedure: Create a URI to serve as the base address.
        Uri baseAddress = new Uri("http://localhost:8000/ServiceModelSamples/Service");

        // Step 2 of the hosting procedure: Create ServiceHost
        ServiceHost selfHost = new ServiceHost(typeof(CalculatorService), baseAddress);

        try
        {

            // Step 3 of the hosting procedure: Add a service endpoint.
            selfHost.AddServiceEndpoint(
                typeof(ICalculator),
                new WSHttpBinding(),
                "CalculatorService");

            // Step 4 of the hosting procedure: Enable metadata exchange.
            ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
            smb.HttpGetEnabled = true;
            selfHost.Description.Behaviors.Add(smb);

            // Step 5 of the hosting procedure: Start (and then stop) the service.
            selfHost.Open();
            Console.WriteLine("The service is ready.");
            Console.WriteLine("Press <ENTER> to terminate service.");
            Console.WriteLine();
            Console.ReadLine();

            // Close the ServiceHostBase to shutdown the service.
            selfHost.Close();
        }
        catch (CommunicationException ce)
        {
            Console.WriteLine("An exception occurred: {0}", ce.Message);
            selfHost.Abort();
        }

    }


问:
How to print out a list of tuple?
This is my code:

```<code>def points_per_game(master_list):
container1= []
for line in master_list:
    container1.append((float(line[18]),line[0],line[2]))
container1.sort(reverse=True)
container1 = container1[:10]
return container1
</code>```

And the output of my code is a list of tuples:

```<code>[(1.92, 'Wayne Gretzky', 'C'), (1.88, 'Mario Lemieux', 'C'), (1.5, 'Mike Bossy', 'R'), (1.4, 'Joe Malone', 'C'), (1.39, 'Bobby Orr', 'D'), (1.33, 'Connor McDavid', 'C'), (1.31, 'Marcel Dionne', 'C'), (1.28, 'Sidney Crosby', 'C'), (1.27, 'Peter Stastny', 'C'), (1.25, 'Peter Forsberg', 'C')]
</code>```

How to turn the list into the picture below, changing the order of the floating point number, the name, and the letter, with format "{:<20s}{:>8s}{:>16s}" in main()?

答:
You can pass the format in a function and print using map (no loop alternative)

```<code>formatter = lambda tup: "{:<20s}{:>8s}{:>16s}".format(*map(str, tup))
print('\n'.join(map(formatter, your_tuple_list)))
</code>```

Title: How to print out a list of tuple?

Body:
This is my code:

def points_per_game(master_list):
container1= []
for line in master_list:
    container1.append((float(line[18]),line[0],line[2]))
container1.sort(reverse=True)
container1 = container1[:10]
return container1

And the output of my code is a list of tuples:

[(1.92, 'Wayne Gretzky', 'C'), (1.88, 'Mario Lemieux', 'C'), (1.5, 'Mike Bossy', 'R'), (1.4, 'Joe Malone', 'C'), (1.39, 'Bobby Orr', 'D'), (1.33, 'Connor McDavid', 'C'), (1.31, 'Marcel Dionne', 'C'), (1.28, 'Sidney Crosby', 'C'), (1.27, 'Peter Stastny', 'C'), (1.25, 'Peter Forsberg', 'C')]

How to turn the list into the picture below, changing the order of the floating point number, the name, and the letter, with format "{:<20s}{:>8s}{:>16s}" in main()?

Body:
You can pass the format in a function and print using map (no loop alternative)

formatter = lambda tup: "{:<20s}{:>8s}{:>16s}".format(*map(str, tup))
print('\n'.join(map(formatter, your_tuple_list)))


问:
Class variable that is an instance of itself
Is something like this possible?

```<code>class Foo:
    BAR = Foo("bar")
    def __init__(self, name):
        self.name = name
</code>```

Currently this yields NameError: name 'Foo' is not defined.

答:
No. annotations only applies to variable and function annotations. Until the class statement as been completely executed, there is no class Foo to instantiate. You must wait until after Foo is defined to create an instance of it.

```<code>class Foo:
    def __init__(self, name):
        self.name = name

Foo.BAR = Foo("bar")
</code>```

You can always initialize BAR = None, then change the value of the attribute after the class is defined.

```<code>class Foo:
    BAR = None  # To be a Foo instance once Foo is defined
    ...

Foo.BAR = Foo("bar")  # Fulfilling our earlier promise
</code>```

That might be desirable for documentation purposes, to make it clearer in the definition that Foo.BAR will exist, though with a different value. I can't think of a situation where that would be necessary, though.

Body:
Is something like this possible?

class Foo:
    BAR = Foo("bar")
    def __init__(self, name):
        self.name = name

Currently this yields NameError: name 'Foo' is not defined.

Body:
No. annotations only applies to variable and function annotations. Until the class statement as been completely executed, there is no class Foo to instantiate. You must wait until after Foo is defined to create an instance of it.

class Foo:
    def __init__(self, name):
        self.name = name

Foo.BAR = Foo("bar")

You can always initialize BAR = None, then change the value of the attribute after the class is defined.

class Foo:
    BAR = None  # To be a Foo instance once Foo is defined
    ...

Foo.BAR = Foo("bar")  # Fulfilling our earlier promise

That might be desirable for documentation purposes, to make it clearer in the definition that Foo.BAR will exist, though with a different value. I can't think of a situation where that would be necessary, though.


问:
Call CreateProcess() and get return value of a string
I have a C++ application that calls an EXE written in C# which grabs some information, and I want to pass it back as a string to the calling C++ application.

So my question is, "is it possible to get a return value of string data from an EXE called with CreateProcess()?

I hope I didn't violate any "question" etiquette here.

答:
No worries Jeff yes there is a way to get the data from one to the other though the EXE.

What you will want to do is write your output in the C# application to standard output.

```<code>Console.WriteLine("Your message here.");
</code>```

Basically if you run the C# console application and it prints data to the screen all that data can be read in your C++ application.

In your C++ program you will want to read from standard input.

It may look something similar to this:

```<code>#include <iostream>
#include <string>

int main() {
    // Your code to run the application in a background process

    for (std::string line; std::getline(std::cin, line);) {
        std::cout << line << std::endl;
    }

    return 0;
}
</code>```

The only rule you broke was not providing enough detail or code to get more specific about the solution. But if you need more help just provide more details. Happy coding!

Here is a link to more information about the c# code if you need it: https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.process.standardoutput

Body:
No worries Jeff yes there is a way to get the data from one to the other though the EXE.

What you will want to do is write your output in the C# application to standard output.

Console.WriteLine("Your message here.");

Basically if you run the C# console application and it prints data to the screen all that data can be read in your C++ application.

In your C++ program you will want to read from standard input.

It may look something similar to this:

#include <iostream>
#include <string>

int main() {
    // Your code to run the application in a background process

    for (std::string line; std::getline(std::cin, line);) {
        std::cout << line << std::endl;
    }

    return 0;
}

The only rule you broke was not providing enough detail or code to get more specific about the solution. But if you need more help just provide more details. Happy coding!

Here is a link to more information about the c# code if you need it: https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.process.standardoutput


问:
lambda and TypeError: 'module' object is not callable
I'm trying to use the lambda function.

```<code>import random
from string import ascii_letters

choice = lambda x: x[int(random()* len(x))]

print(choice("azerty"))
</code>```

But I get an error :

```<code>TypeError: 'module' object is not callable
</code>```

I'm confused. Can you help me ? Thanks.

答:
Use this. random is a module which contains a function called random. You can use it by doing random.random().

```<code>choice = lambda x: x[int(random.random()* len(x))]
</code>```

If you want you random() directly then use this.

```<code>from random import random
choice = lambda x: x[int(random()* len(x))]
</code>```

Body:
I'm trying to use the lambda function.

import random
from string import ascii_letters

choice = lambda x: x[int(random()* len(x))]

print(choice("azerty"))

But I get an error :

TypeError: 'module' object is not callable

I'm confused. Can you help me ? Thanks.

Body:
Use this. random is a module which contains a function called random. You can use it by doing random.random().

choice = lambda x: x[int(random.random()* len(x))]

If you want you random() directly then use this.

from random import random
choice = lambda x: x[int(random()* len(x))]


问:
How to render recursive component in React?
I'm trying to render a component recursively. On each recursive call I subtract 10 px from the dimensions. I expect a series of nested divs, each one 10px smaller. When the height and width reach 10px, the component should return null, so that is my base case.

Instead of expected result, I've got nothing. No errors in the terminal, no errors in the dev tools, just a page that is frozen.

Any thoughts?

RecurentDiv.js:

```<code>const RecurentDiv = ({ width, height }) => {
  const style = {
    width: `${width - 10}px`,
    height: `${height - 10}px`,
    border: "1px solid black",
    display: "inline-block"
  };

  if (width < 10) return null; //base case

  return (
      <div style={style}>
        <RecurentDiv width={style.width} height={style.height} />
      </div>
  );
};

export default RecurentDiv;
</code>```

App.js:

```<code><RecurentDiv width={100} height={100} />
</code>```

答:
The issue is here:

```<code><RecurentDiv width={style.width} height={style.height} />
                  //^^^^^^               ^^^^^^
</code>```

style.width is a string, not a number: ${width - 10}px. The code is doing "100px" - 10 which evaluates to NaN, which is then passed into the next RecurentDiv's props. The base case is never reached.

Instead, pass width and height numbers directly into the recursive component, subtracting the reduction amount to approach the base case.

Here's a minimal, complete example:

const RecurrentDiv = ({width, height}) => {
  const style = {
    width: `${width}px`,
    height: `${height}px`,
    border: "1px solid black",
    display: "inline-block"
  };

  return width < 10 ? null : (

      <RecurrentDiv width={width - 10} height={height - 10} />

  );
};

ReactDOM.createRoot(document.querySelector("#app"))
  .render(<RecurrentDiv width={100} height={100} />);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script crossorigin src="https://unpkg.com/react@18/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
<div id="app"></div></code>```

Body:
I'm trying to render a component recursively. On each recursive call I subtract 10 px from the dimensions. I expect a series of nested divs, each one 10px smaller. When the height and width reach 10px, the component should return null, so that is my base case.

Instead of expected result, I've got nothing. No errors in the terminal, no errors in the dev tools, just a page that is frozen.

Any thoughts?

RecurentDiv.js:

const RecurentDiv = ({ width, height }) => {
  const style = {
    width: `${width - 10}px`,
    height: `${height - 10}px`,
    border: "1px solid black",
    display: "inline-block"
  };

  if (width < 10) return null; //base case

  return (

        <RecurentDiv width={style.width} height={style.height} />

  );
};

export default RecurentDiv;

App.js:

<RecurentDiv width={100} height={100} />

Body:
The issue is here:

<RecurentDiv width={style.width} height={style.height} />
                  //^^^^^^               ^^^^^^

style.width is a string, not a number: ${width - 10}px. The code is doing "100px" - 10 which evaluates to NaN, which is then passed into the next RecurentDiv's props. The base case is never reached.

Instead, pass width and height numbers directly into the recursive component, subtracting the reduction amount to approach the base case.

Here's a minimal, complete example:

const RecurrentDiv = ({width, height}) => {
  const style = {
    width: `${width}px`,
    height: `${height}px`,
    border: "1px solid black",
    display: "inline-block"
  };

  return width < 10 ? null : (
    <div style={style}>
      <RecurrentDiv width={width - 10} height={height - 10} />
    </div>
  );
};

ReactDOM.createRoot(document.querySelector("#app"))
  .render(<RecurrentDiv width={100} height={100} />);

<script crossorigin src="https://unpkg.com/react@18/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
<div id="app"></div>


问:
Load inserted text in dialog
I am using summernote 0.8 and jquery 3.5.

I have created a dialog that inputs synonyms for example, when inputing test1, test2, test3 in the dialog a special tag is filled into the editor like the following:

```<code><span data-function="addSynonym" data-options="[test2, test3]"><span style="background-color: yellow;">test1</span></span>
</code>```

I would like to load the dialog with these values, edit them and add the updated values to the editor's text field.

Find below my minimum viable example:

$(document).ready(function() {
  $('.summernote').summernote({
    height: 300,
    tabsize: 2,
    toolbar: [
      ['insert', ['synonym', 'codeview']]
    ],
  });
});

(function(factory) {
  /* global define */
  if (typeof define === 'function' && define.amd) {
    // AMD. Register as an anonymous module.
    define(['jquery'], factory);
  } else if (typeof module === 'object' && module.exports) {
    // Node/CommonJS
    module.exports = factory(require('jquery'));
  } else {
    // Browser globals
    factory(window.jQuery);
  }
}(function($) {
  $.extend($.summernote.plugins, {

    'synonym': function(context) {
      var self = this;
      var ui = $.summernote.ui;

      var $editor = context.layoutInfo.editor;
      var options = context.options;

      context.memo('button.synonym', function() {
        return ui.button({
          contents: '',
          tooltip: 'Create Synonym',
          click: context.createInvokeHandler('synonym.showDialog')
        }).render();
      });

      self.initialize = function() {
        var $container = options.dialogsInBody ? $(document.body) : $editor;

        var body = '
' +
          'Add Synonyms (comma - , - seperated' +
          '<input id="input-synonym" class="form-control" type="text" placeholder="Insert your synonym" />'
        '
'
        var footer = '<button href="#" class="btn btn-primary ext-synonym-btn">OK</button>';

        self.$dialog = ui.dialog({
          title: 'Create Synonym',
          fade: options.dialogsFade,
          body: body,
          footer: footer
        }).render().appendTo($container);
      };

      // You should remove elements on `initialize`.
      self.destroy = function() {
        self.$dialog.remove();
        self.$dialog = null;
      };

      self.showDialog = function() {
        self
          .openDialog()
          .then(function(data) {
            ui.hideDialog(self.$dialog);
            context.invoke('editor.restoreRange');
            self.insertToEditor(data);

            console.log("dialog returned: ", data)
          })
          .fail(function() {
            context.invoke('editor.restoreRange');
          });
      };

      self.openDialog = function() {
        return $.Deferred(function(deferred) {
          var $dialogBtn = self.$dialog.find('.ext-synonym-btn');
          var $synonymInput = self.$dialog.find('#input-synonym')[0];

          ui.onDialogShown(self.$dialog, function() {
            context.triggerEvent('dialog.shown');

            $dialogBtn
              .click(function(event) {
                event.preventDefault();

                deferred.resolve({
                  synonym: $synonymInput.value
                });
              });
          });

          ui.onDialogHidden(self.$dialog, function() {
            $dialogBtn.off('click');

            if (deferred.state() === 'pending') {
              deferred.reject();
            }
          });

          ui.showDialog(self.$dialog);
        });
      };

      this.insertToEditor = function(data) {
        console.log("synonym: " + data.synonym)

        var dataArr = data.synonym.split(',');
        var restArr = dataArr.slice(1);

        var $elem = $('', {
          'data-function': "addSynonym",
          'data-options': '[' + restArr.join(',').trim() + ']',
          'html': $('', {
            'text': dataArr[0],
            'css': {
              backgroundColor: 'yellow'
            }
          })
        });

        context.invoke('editor.insertNode', $elem[0]);
      };
    }
  });
}));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><head>
  <meta charset="UTF-8">
  <title>Summernote with Bootstrap 4</title>
  <script src="https://code.jquery.com/jquery-3.4.1.min.js" crossorigin="anonymous"></script>
  <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>

  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
  <link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">

  <link href="https://cdn.jsdelivr.net/npm/summernote@0.8.15/dist/summernote-bs4.min.css" rel="stylesheet">
  <script src="https://cdn.jsdelivr.net/npm/summernote@0.8.15/dist/summernote-bs4.min.js"></script>
</head>

<body style="
    padding-top: 50px;
    border-left-width: 50px;
    padding-left: 50px;
    border-right-width: 50px;
    padding-right: 150px;
">
  <div class="container">
    <div class="summernote">
      <p>Hello World!</p>
      This text should be replaced by the dialog. </div>
  </div>
</body></code>```

Any suggestions how to do add this update functionality to my yellow text?

I appreciate your replies!

答:
Using the oninit callback, we can easily use jquery methods to select that embedded text and trigger a click on that button you added in your plugin.

It's the first time I use Summernote. So to bring a clear code and a similar syntax in the [UPDATE], I added jquery-ui dialogBox that would be used to update the clicked span.

And for this I used updateSpan() function that receives the (targeted) current span object and it's new value as arguments.

var i=0;

function updateSpan(object,value){
    object.text(value.split(',', 1));
    object.attr('data-options',value.split(',', 1));
    object.attr('data-all','['+value+']');
    object.css('backgroundColor','yellow');
    object.parent().append(" ");
}

$(document).ready(function() {

  $('.summernote').summernote({
    height: 300,
    tabsize: 2,
    toolbar: [
      ['insert', ['synonym', 'codeview']]
    ],
    callbacks: {
        onInit: function() {

            $(".note-editable").on('click','span[data-function="addSynonym"]', function (e) {
            var spanvalue=($(this).attr('data-all')).replace(/[\[\]']+/g,'');
            var targetSpan=$(this);
            //console.log(spanvalue);

                $('#upDialog').dialog({
                    open : function (event, ui) {
                      $('#upDialog #input-synonym').empty().val(spanvalue);
                      //console.log(spanvalue);
                    },
                    modal: true,
                    title: 'Dialog',
                    show: {
                        effect: "scale",
                        duration: 200
                    },
                    resizable: false,
                    buttons: [{
                        text: "ok",
                        click: function () {
                            updateSpan(targetSpan,$('#upDialog #input-synonym').val());
                            $(this).dialog("close");
                            targetSpan.focus();
                        }
                    }]
                });
            });
        }
    }
  });
});

(function(factory) {
  /* global define */
  if (typeof define === 'function' && define.amd) {
    // AMD. Register as an anonymous module.
    define(['jquery'], factory);
  } else if (typeof module === 'object' && module.exports) {
    // Node/CommonJS
    module.exports = factory(require('jquery'));
  } else {
    // Browser globals
    factory(window.jQuery);
  }
}(function($) {
  $.extend($.summernote.plugins, {

    'synonym': function(context) {

      var self = this;
      var ui = $.summernote.ui;

      var $editor = context.layoutInfo.editor;
      var options = context.options;

      context.memo('button.synonym', function() {
        return ui.button({
          contents: '',
          tooltip: 'Create Synonym',
          click: context.createInvokeHandler('synonym.showDialog')
        }).render();
      });

      self.initialize = function() {
        var $container = options.dialogsInBody ? $(document.body) : $editor;

        var body = '
' +
          'Add Synonyms (comma - , - seperated' +
          '<input id="input-synonym" class="form-control" type="text" placeholder="Insert your synonym" />'
        '
'
        var footer = '<button href="#" class="btn btn-primary ext-synonym-btn">OK</button>';

        self.$dialog = ui.dialog({
          title: 'Create Synonym',
          fade: options.dialogsFade,
          body: body,
          footer: footer
        }).render().appendTo($container);
      };

      // You should remove elements on `initialize`.
      self.destroy = function() {
        self.$dialog.remove();
        self.$dialog = null;
      };

      self.showDialog = function() {
        self

          .openDialog()
          .then(function(data) {
            ui.hideDialog(self.$dialog);
            context.invoke('editor.restoreRange');
            self.insertToEditor(data);

            //console.log("dialog returned: ", data)
          })
          .fail(function() {
            context.invoke('editor.restoreRange');
          });
      };

      self.openDialog = function() {

        return $.Deferred(function(deferred) {
          var $dialogBtn = self.$dialog.find('.ext-synonym-btn');
          var $synonymInput = self.$dialog.find('#input-synonym')[0];

          ui.onDialogShown(self.$dialog, function() {
            context.triggerEvent('dialog.shown');

            $dialogBtn
              .click(function(event) {
                event.preventDefault();

                deferred.resolve({
                  synonym: $synonymInput.value
                });
              });
          });

          ui.onDialogHidden(self.$dialog, function() {
            $dialogBtn.off('click');

            if (deferred.state() === 'pending') {
              deferred.reject();
            }
          });

          ui.showDialog(self.$dialog);
        });
      };

      this.insertToEditor = function(data) {
        i++;
        //console.log("synonym: " + data.synonym)

        var dataArr = data.synonym.split(',');
        var restArr = dataArr.slice(1);

        var $elem = $('', {
          'data-function': "addSynonym",
          'data-id': i,
          'data-options': '[' + restArr.join(',').trim() + ']',
          'data-all': '[' + dataArr.join(',').trim() + ']',
          'html': $('', {
            'text': dataArr[0],
            'css': {
              backgroundColor: 'yellow'
            }
          })
        });

        context.invoke('editor.insertNode', $elem[0]);
        context.invoke('editor.insertText', ' ');
        //context.invoke('editor.restoreRange');
        //Still a bug : https://github.com/summernote/summernote/issues/3249
        $('.summernote').summernote('editor.insertText', ' ');
        context.invoke('editor.focus');
      }

    }
  });
}));```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#upDialog{
display:none;
}</code>```

  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">

  <link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">

  <link href="https://cdn.jsdelivr.net/npm/summernote@0.8.15/dist/summernote-bs4.min.css" rel="stylesheet">

  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css" integrity="sha256-rByPlHULObEjJ6XQxW/flG2r+22R5dKiAoef+aXWfik=" crossorigin="anonymous" />

Hello World!

      This text should be replaced by the dialog.

<input id="input-synonym" class="form-control" type="text" placeholder="Insert your synonym" />

  ```

You can replace this dialog by a modal to look identical or adapt the Dialog design to the old one.

Title: Load inserted text in dialog

Body:
I am using summernote 0.8 and jquery 3.5.

I have created a dialog that inputs synonyms for example, when inputing test1, test2, test3 in the dialog a special tag is filled into the editor like the following:

test1

I would like to load the dialog with these values, edit them and add the updated values to the editor's text field.

Find below my minimum viable example:

$(document).ready(function() {
  $('.summernote').summernote({
    height: 300,
    tabsize: 2,
    toolbar: [
      ['insert', ['synonym', 'codeview']]
    ],
  });
});

(function(factory) {
  /* global define */
  if (typeof define === 'function' && define.amd) {
    // AMD. Register as an anonymous module.
    define(['jquery'], factory);
  } else if (typeof module === 'object' && module.exports) {
    // Node/CommonJS
    module.exports = factory(require('jquery'));
  } else {
    // Browser globals
    factory(window.jQuery);
  }
}(function($) {
  $.extend($.summernote.plugins, {

    'synonym': function(context) {
      var self = this;
      var ui = $.summernote.ui;

      var $editor = context.layoutInfo.editor;
      var options = context.options;

      context.memo('button.synonym', function() {
        return ui.button({
          contents: '',
          tooltip: 'Create Synonym',
          click: context.createInvokeHandler('synonym.showDialog')
        }).render();
      });

      self.initialize = function() {
        var $container = options.dialogsInBody ? $(document.body) : $editor;

        var body = '
' +
          'Add Synonyms (comma - , - seperated' +
          '<input id="input-synonym" class="form-control" type="text" placeholder="Insert your synonym" />'
        '
'
        var footer = '<button href="#" class="btn btn-primary ext-synonym-btn">OK</button>';

        self.$dialog = ui.dialog({
          title: 'Create Synonym',
          fade: options.dialogsFade,
          body: body,
          footer: footer
        }).render().appendTo($container);
      };

      // You should remove elements on `initialize`.
      self.destroy = function() {
        self.$dialog.remove();
        self.$dialog = null;
      };

      self.showDialog = function() {
        self
          .openDialog()
          .then(function(data) {
            ui.hideDialog(self.$dialog);
            context.invoke('editor.restoreRange');
            self.insertToEditor(data);

            console.log("dialog returned: ", data)
          })
          .fail(function() {
            context.invoke('editor.restoreRange');
          });
      };

      self.openDialog = function() {
        return $.Deferred(function(deferred) {
          var $dialogBtn = self.$dialog.find('.ext-synonym-btn');
          var $synonymInput = self.$dialog.find('#input-synonym')[0];

          ui.onDialogShown(self.$dialog, function() {
            context.triggerEvent('dialog.shown');

            $dialogBtn
              .click(function(event) {
                event.preventDefault();

                deferred.resolve({
                  synonym: $synonymInput.value
                });
              });
          });

          ui.onDialogHidden(self.$dialog, function() {
            $dialogBtn.off('click');

            if (deferred.state() === 'pending') {
              deferred.reject();
            }
          });

          ui.showDialog(self.$dialog);
        });
      };

      this.insertToEditor = function(data) {
        console.log("synonym: " + data.synonym)

        var dataArr = data.synonym.split(',');
        var restArr = dataArr.slice(1);

        var $elem = $('', {
          'data-function': "addSynonym",
          'data-options': '[' + restArr.join(',').trim() + ']',
          'html': $('', {
            'text': dataArr[0],
            'css': {
              backgroundColor: 'yellow'
            }
          })
        });

        context.invoke('editor.insertNode', $elem[0]);
      };
    }
  });
}));

  <meta charset="UTF-8">
  <title>Summernote with Bootstrap 4</title>

  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">

  <link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">

  <link href="https://cdn.jsdelivr.net/npm/summernote@0.8.15/dist/summernote-bs4.min.css" rel="stylesheet">

Hello World!

      This text should be replaced by the dialog.

Any suggestions how to do add this update functionality to my yellow text?

I appreciate your replies!

Body:
Using the oninit callback, we can easily use jquery methods to select that embedded text and trigger a click on that button you added in your plugin.

It's the first time I use Summernote. So to bring a clear code and a similar syntax in the [UPDATE], I added jquery-ui dialogBox that would be used to update the clicked span.

And for this I used updateSpan() function that receives the (targeted) current span object and it's new value as arguments.

var i=0;

function updateSpan(object,value){
    object.text(value.split(',', 1));
    object.attr('data-options',value.split(',', 1));
    object.attr('data-all','['+value+']');
    object.css('backgroundColor','yellow');
    object.parent().append("&nbsp;");
}

$(document).ready(function() {

  $('.summernote').summernote({
    height: 300,
    tabsize: 2,
    toolbar: [
      ['insert', ['synonym', 'codeview']]
    ],
    callbacks: {
        onInit: function() {

            $(".note-editable").on('click','span[data-function="addSynonym"]', function (e) {
            var spanvalue=($(this).attr('data-all')).replace(/[\[\]']+/g,'');
            var targetSpan=$(this);
            //console.log(spanvalue);

                $('#upDialog').dialog({
                    open : function (event, ui) {
                      $('#upDialog #input-synonym').empty().val(spanvalue);
                      //console.log(spanvalue);
                    },
                    modal: true,
                    title: 'Dialog',
                    show: {
                        effect: "scale",
                        duration: 200
                    },
                    resizable: false,
                    buttons: [{
                        text: "ok",
                        click: function () {
                            updateSpan(targetSpan,$('#upDialog #input-synonym').val());
                            $(this).dialog("close");
                            targetSpan.focus();
                        }
                    }]
                });
            });
        }
    }
  });
});

(function(factory) {
  /* global define */
  if (typeof define === 'function' && define.amd) {
    // AMD. Register as an anonymous module.
    define(['jquery'], factory);
  } else if (typeof module === 'object' && module.exports) {
    // Node/CommonJS
    module.exports = factory(require('jquery'));
  } else {
    // Browser globals
    factory(window.jQuery);
  }
}(function($) {
  $.extend($.summernote.plugins, {

    'synonym': function(context) {

      var self = this;
      var ui = $.summernote.ui;

      var $editor = context.layoutInfo.editor;
      var options = context.options;

      context.memo('button.synonym', function() {
        return ui.button({
          contents: '<i class="fa fa-snowflake-o">',
          tooltip: 'Create Synonym',
          click: context.createInvokeHandler('synonym.showDialog')
        }).render();
      });

      self.initialize = function() {
        var $container = options.dialogsInBody ? $(document.body) : $editor;

        var body = '<div class="form-group">' +
          '<label>Add Synonyms (comma - , - seperated</label>' +
          '<input id="input-synonym" class="form-control" type="text" placeholder="Insert your synonym" />'
        '</div>'
        var footer = '<button href="#" class="btn btn-primary ext-synonym-btn">OK</button>';

        self.$dialog = ui.dialog({
          title: 'Create Synonym',
          fade: options.dialogsFade,
          body: body,
          footer: footer
        }).render().appendTo($container);
      };

      // You should remove elements on `initialize`.
      self.destroy = function() {
        self.$dialog.remove();
        self.$dialog = null;
      };

      self.showDialog = function() {
        self

          .openDialog()
          .then(function(data) {
            ui.hideDialog(self.$dialog);
            context.invoke('editor.restoreRange');
            self.insertToEditor(data);

            //console.log("dialog returned: ", data)
          })
          .fail(function() {
            context.invoke('editor.restoreRange');
          });
      };

      self.openDialog = function() {

        return $.Deferred(function(deferred) {
          var $dialogBtn = self.$dialog.find('.ext-synonym-btn');
          var $synonymInput = self.$dialog.find('#input-synonym')[0];

          ui.onDialogShown(self.$dialog, function() {
            context.triggerEvent('dialog.shown');

            $dialogBtn
              .click(function(event) {
                event.preventDefault();

                deferred.resolve({
                  synonym: $synonymInput.value
                });
              });
          });

          ui.onDialogHidden(self.$dialog, function() {
            $dialogBtn.off('click');

            if (deferred.state() === 'pending') {
              deferred.reject();
            }
          });

          ui.showDialog(self.$dialog);
        });
      };

      this.insertToEditor = function(data) {
        i++;
        //console.log("synonym: " + data.synonym)

        var dataArr = data.synonym.split(',');
        var restArr = dataArr.slice(1);

        var $elem = $('<span>', {
          'data-function': "addSynonym",
          'data-id': i,
          'data-options': '[' + restArr.join(',').trim() + ']',
          'data-all': '[' + dataArr.join(',').trim() + ']',
          'html': $('<span>', {
            'text': dataArr[0],
            'css': {
              backgroundColor: 'yellow'
            }
          })
        });

        context.invoke('editor.insertNode', $elem[0]);
        context.invoke('editor.insertText', ' ');
        //context.invoke('editor.restoreRange');
        //Still a bug : https://github.com/summernote/summernote/issues/3249
        $('.summernote').summernote('editor.insertText', ' ');
        context.invoke('editor.focus');
      }

    }
  });
}));

#upDialog{
display:none;
}

<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js" integrity="sha256-KM512VNnjElC30ehFwehXjx1YCHPiQkOPmqnrWtpccM=" crossorigin="anonymous"></script>

  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
  <link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">

  <link href="https://cdn.jsdelivr.net/npm/summernote@0.8.15/dist/summernote-bs4.min.css" rel="stylesheet">
  <script src="https://cdn.jsdelivr.net/npm/summernote@0.8.15/dist/summernote-bs4.min.js"></script>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css" integrity="sha256-rByPlHULObEjJ6XQxW/flG2r+22R5dKiAoef+aXWfik=" crossorigin="anonymous" />
<body style="
    padding-top: 50px;
    border-left-width: 50px;
    padding-left: 50px;
    border-right-width: 50px;
    padding-right: 150px;
">
  <div class="container">
    <div class="summernote">
      <p>Hello World!</p>
      This text should be replaced by the dialog.
      </div>
      <div id="upDialog" title="Update Value"><input id="input-synonym" class="form-control" type="text" placeholder="Insert your synonym" /></div>

  </div>
  </body>

You can replace this dialog by a modal to look identical or adapt the Dialog design to the old one.


问:
See if a customer had a purchase across every quarter and then graph
I have a dataframe that looks like this:

```<code> customer_id|date      |sales_amount
 479485     |20190120  | 500
 479485     |20180320  | 200
 472848     |20191020  | 100
</code>```

This data has transaction information from 2016-2019. For each business quarter (grouped by 3 months) I want to see if a unique customer had a transaction. Basically I want the y-axis for the table to be each unique customer_id and then the x-axis of the table to be the 12 quarters in the time period of the data with a Boolean of whether or not a customer had a transaction in that quarter.

Ultimately I want to visualize this data to see the distribution of the transactions for each quarter across all the unique customers.

Expect output:

```<code> customer_id|2017- Q1  |2017- Q2|.. |2019- Q4
 479485     |20190120  |   0    |.. |   1
 469488     |20180320  |   0    |.. |   0
 452848     |20191020  |   1    |.. |   1
</code>```

I have changed the date column to datetime but am unsure how to group and proceed to the next step.

答:
Solution:

```<code>df.groupby([df['customer_id'], df['date'].apply(lambda _: pd.Period(_, 'Q'))])['sales_amount'].count().unstack().fillna(0)
</code>```

Output:

```<code>       date 2017Q1  2018Q1  2019Q1  2019Q4
customer_id
469471      1.0     0.0     0.0     0.0
469488      0.0     1.0     1.0     1.0
472848      0.0     0.0     0.0     1.0
479485      1.0     1.0     1.0     0.0
</code>```

Notes

Assumptions: (1) all of the year-quarters appear in you data set, and (2) there's only a single transaction per quarter.

To get around (1), set the index as date, and reindex with missing dates, filling nans with zero values. The above output is based on a sample of dummy data, hence only four quarters are shown.

To get around (2), run np.sign(_) over your output.

Body:
I have a dataframe that looks like this:

 customer_id|date      |sales_amount
 479485     |20190120  | 500
 479485     |20180320  | 200
 472848     |20191020  | 100

This data has transaction information from 2016-2019. For each business quarter (grouped by 3 months) I want to see if a unique customer had a transaction. Basically I want the y-axis for the table to be each unique customer_id and then the x-axis of the table to be the 12 quarters in the time period of the data with a Boolean of whether or not a customer had a transaction in that quarter.

Ultimately I want to visualize this data to see the distribution of the transactions for each quarter across all the unique customers.

Expect output:

 customer_id|2017- Q1  |2017- Q2|.. |2019- Q4
 479485     |20190120  |   0    |.. |   1
 469488     |20180320  |   0    |.. |   0
 452848     |20191020  |   1    |.. |   1

I have changed the date column to datetime but am unsure how to group and proceed to the next step.

Body:
Solution:

df.groupby([df['customer_id'], df['date'].apply(lambda _: pd.Period(_, 'Q'))])['sales_amount'].count().unstack().fillna(0)

Output:

       date 2017Q1  2018Q1  2019Q1  2019Q4
customer_id
469471      1.0     0.0     0.0     0.0
469488      0.0     1.0     1.0     1.0
472848      0.0     0.0     0.0     1.0
479485      1.0     1.0     1.0     0.0

Notes

Assumptions: (1) all of the year-quarters appear in you data set, and (2) there's only a single transaction per quarter.

To get around (1), set the index as date, and reindex with missing dates, filling nans with zero values. The above output is based on a sample of dummy data, hence only four quarters are shown.

To get around (2), run np.sign(_) over your output.


问:
Can't access object value, says undefined
I am trying to access the value of an object but it appears to me that its value is undefined

If I use req.body it shows me the object correctly { '{"numeros":"584242549745","mensaje":"qweqwe","files":': [ '' ] }, but when trying to access its value req.body.numeros I get an indefinite value. I don't know what I can be doing wrong here.

答: You have to parse the request body with JSON.parse or a special middleware. If you use express.js the there is, for example, body-parser.


问:
LLDB How to use a file-defined macro in OC
Ive tried multiple variations of this, but none of them seem to work. Any ideas?

in ViewController.m

UIView *view1 = [[UIView alloc] initWithFrame:CGRectMake(100, 200, 300, 300)];
view1.backgroundColor = [UIColor redColor];
[self.view addSubview:view1];
```

<p>Another file <code>UIView+Frame.h</code>
I defined a color macro</p>

<pre class="lang-swift prettyprint-override"><code>#define RGBACOLOR(r,g,b,a) [UIColor colorWithRGB:r Green:g Blue:b Alpha:a]
</code>```

Actual operation
When the program executes [self.view addSubview: view1];I am going to use LLDB to use the defined macros to modify the color, but it prompts an error and I do n’t know how to modify it.
The wrong result is as follows

(lldb) e view1.backgroundColor = (UIColor *)RGBACOLOR(0,0,0,1)
error: use of undeclared identifier 'RGBACOLOR'
(lldb)
```

答:
Macros are not traditionally well supported by debug info.  The DWARF standard (which is the most common one on macOS & other Unixen) has a way to store the information, but it is so verbose very few toolchains support it.  So there's no natural way for the debugger to know about defines.

If you have a small number of fairly independent macros you want to use in debug expressions, you can put them in a .h file, and set that file as lldb's "expression prefix".  This will get included into the source of every expression you run subsequently.  Do this by:

```<code>(lldb) settings set target.expr-prefix ~/my-common-defines.h
</code>```

You can't get too ambitious here (e.g. #include <unistd.h> won't work).  The problem is that most system header files are conditioned by a set of other #defines.  lldb doesn't know what their values are, so at some point preprocessing the expr-prefix will fail.

Alternatively, clang also has a concept called "modules" which is an attempt to make the collection of headers from some package more shareable for repeated compilation.  It actually captures some of the info that would cause the expr-prefix parsing to fail.  So if the macro you want to access is in a set of headers that are built into a Clang module, then you can import the module into lldb's expression context, and that will make the defines from the modules available as well.  So for instance:

(lldb) expr -l objc -- @import Foundation

will make all the Foundation macro definitions available.

Similarly, if your headers are modular (this page goes into depth on what this means:

https://clang.llvm.org/docs/Modules.html

) then you can import the module you've created, and its defines will be available to the expression parser.

Body:
Ive tried multiple variations of this, but none of them seem to work. Any ideas?

in ViewController.m

UIView *view1 = [[UIView alloc] initWithFrame:CGRectMake(100, 200, 300, 300)];
view1.backgroundColor = [UIColor redColor];
[self.view addSubview:view1];

Another file UIView+Frame.h
I defined a color macro

#define RGBACOLOR(r,g,b,a) [UIColor colorWithRGB:r Green:g Blue:b Alpha:a]

Actual operation
When the program executes [self.view addSubview: view1];I am going to use LLDB to use the defined macros to modify the color, but it prompts an error and I do n’t know how to modify it.
The wrong result is as follows

(lldb) e view1.backgroundColor = (UIColor *)RGBACOLOR(0,0,0,1)
error: use of undeclared identifier 'RGBACOLOR'
(lldb)

Body:
Macros are not traditionally well supported by debug info.  The DWARF standard (which is the most common one on macOS & other Unixen) has a way to store the information, but it is so verbose very few toolchains support it.  So there's no natural way for the debugger to know about defines.

If you have a small number of fairly independent macros you want to use in debug expressions, you can put them in a .h file, and set that file as lldb's "expression prefix".  This will get included into the source of every expression you run subsequently.  Do this by:

(lldb) settings set target.expr-prefix ~/my-common-defines.h

You can't get too ambitious here (e.g. #include <unistd.h> won't work).  The problem is that most system header files are conditioned by a set of other #defines.  lldb doesn't know what their values are, so at some point preprocessing the expr-prefix will fail.

Alternatively, clang also has a concept called "modules" which is an attempt to make the collection of headers from some package more shareable for repeated compilation.  It actually captures some of the info that would cause the expr-prefix parsing to fail.  So if the macro you want to access is in a set of headers that are built into a Clang module, then you can import the module into lldb's expression context, and that will make the defines from the modules available as well.  So for instance:

(lldb) expr -l objc -- @import Foundation

will make all the Foundation macro definitions available.

Similarly, if your headers are modular (this page goes into depth on what this means:

https://clang.llvm.org/docs/Modules.html

) then you can import the module you've created, and its defines will be available to the expression parser.


问:
Flutter DataStream not closing and re-building properly. [Bad state: Stream has already been listened to.]
Okay, so I'm aware that a stream can be manufactured to listen to a stream more than once, using a broadcast system, but that's specifically NOT what I'm trying to do here.

I'm also editing this as the one answer I have received isn't currently able to resolve my issue, so any assistance would be greatly appreciated.

Effectively for some reason the code I have is not deleting the stream in it's entirety, and if re-used, it is trying to re-listen to the same stream that has already been listened-to and closed, none of which works (Obviously).  Instead of trying to listen to that same stream again, I'm trying to create a NEW stream to listen to.  (Deleting and cleaning away all information from the original first stream).

Original post continues below:

I'm using a DataStream template for streaming data to and/or from various parts of my program, and I'm not entirely certain how to rectify this.  I'm certain it's a silly newb error, but I haven't used DataStreams enough to understand why this is happening.

Now don't get me wrong, going through a single cycle of my program works perfectly fine, no issues at all.  However, once I've completed a single cycle through the program, if I try to go through a second time, I get the error:

Bad state: Stream has already been listened to.

So from this I know my program is not creating a new stream, and instead trying to re-use the original stream, and I'm not 100% certain how to stop this functionality, (Or even if I should).  (Honestly the number of times I would expect multiple cycles to be completed are slim to null, but I want to resolve these kinds of errors before they become problems.)

Edit:  Minimal Reproducible Example to Follow

File 1 (main.dart)

```<code>import 'package:flutter/cupertino.dart';
import 'dart:async';
import './page2.dart';
import './stream.dart';

void main() => runApp(MyApp());

DataStream stream = DataStream();

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return CupertinoApp(
      title: 'Splash Test',
      theme: CupertinoThemeData(
        primaryColor: Color.fromARGB(255, 0, 0, 255),
      ),
      home: MyHomePage(title: 'Splash Test Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  bool textBool = false;
  int counter = 0;

  void changeTest(context) async {
    int counter = 0;
    Timer.periodic(Duration (seconds: 2), (Timer t) {
      counter++;
      stream.dataSink.add(true);
      if (counter >= 3) {
        t.cancel();
        stream.dispose();
        Navigator.pop(context);
      }
    },);
    Navigator.push(context, CupertinoPageRoute(builder: (context) => Page2(stream: stream)));
  }

  @override
  Widget build(BuildContext context) {

    return CupertinoPageScaffold(
      child: Center(
        child: CupertinoButton(
          child: Text('To Splash'),
          onPressed: () => changeTest(context),
        ),
      ),
    );
  }
}
</code>```

File 2 (stream.dart)

```<code>import 'dart:async';

class DataStream {
  StreamController _streamController;

    StreamSink<bool> get dataSink =>
      _streamController.sink;

  Stream<bool> get dataStream =>
      _streamController.stream;

  DataStream() {
    _streamController = StreamController<bool>();
  }

  dispose() {
    _streamController?.close();
  }

}
</code>```

File 3 (page2.dart)

```<code>import 'package:flutter/material.dart';
import 'package:flutter/semantics.dart';

import './main.dart';
import './stream.dart';

class Page2 extends StatefulWidget {

  DataStream stream;
  Page2({this.stream});

  @override
  State<StatefulWidget> createState() => new PageState();
}

class PageState extends State<Page2> {

bool textChanger = false;
bool firstText = true;

Text myText() {
  if (textChanger) {
    Text text1 = new Text('Text One',
      style: TextStyle(color: Color.fromARGB(255, 0, 0, 0)));
    return text1;
  } else {
    Text text1 = new Text('Text Two',
      style: TextStyle(color: Color.fromARGB(255, 0, 0, 0)));
    return text1;
  }
}

void changeText() {
  if (!firstText) {
    if (textChanger) {
      print('Change One');
      setState(() {
        textChanger = false;
      });
    } else {
      print('Change Two');
      setState(() {
        textChanger = true;
      });
    }
  } else {
    firstText = false;
  }
}

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      body: new Container(
        child: Center(
          child: myText()
        )
      ),);
  }

@override
  void initState() {
    super.initState();
    widget.stream.dataStream.listen((onData) {
      changeText();
    });
  }

}
</code>```

Effectively, in this example, you can click on the text, and goto the second page, which will correctly change text when told, and return to the original page once completed.  That would be a single "Cycle" of my program.

And you can see that this program then immediately disposes of the stream.

The issue is that if I click the text a second time, it is still trying to listen to the original stream, rather than creating a brand new stream and starting fresh.

Why?  And how do I fix this?

答: Without being able to grasp your problem in its entirety, I'd just like to state that I've been having headaches pretty much every time I've used "normal" streams myself and RxDart has been like Aspirin in the world of streams for me :) Not sure if this is the answer you're looking for, but I thought I'd post it anyway - you never know!</p>

Body:
Okay, so I'm aware that a stream can be manufactured to listen to a stream more than once, using a broadcast system, but that's specifically NOT what I'm trying to do here.

I'm also editing this as the one answer I have received isn't currently able to resolve my issue, so any assistance would be greatly appreciated.

Effectively for some reason the code I have is not deleting the stream in it's entirety, and if re-used, it is trying to re-listen to the same stream that has already been listened-to and closed, none of which works (Obviously).  Instead of trying to listen to that same stream again, I'm trying to create a NEW stream to listen to.  (Deleting and cleaning away all information from the original first stream).

Original post continues below:

I'm using a DataStream template for streaming data to and/or from various parts of my program, and I'm not entirely certain how to rectify this.  I'm certain it's a silly newb error, but I haven't used DataStreams enough to understand why this is happening.

Now don't get me wrong, going through a single cycle of my program works perfectly fine, no issues at all.  However, once I've completed a single cycle through the program, if I try to go through a second time, I get the error:

Bad state: Stream has already been listened to.

So from this I know my program is not creating a new stream, and instead trying to re-use the original stream, and I'm not 100% certain how to stop this functionality, (Or even if I should).  (Honestly the number of times I would expect multiple cycles to be completed are slim to null, but I want to resolve these kinds of errors before they become problems.)

Edit:  Minimal Reproducible Example to Follow

File 1 (main.dart)

import 'package:flutter/cupertino.dart';
import 'dart:async';
import './page2.dart';
import './stream.dart';

void main() => runApp(MyApp());

DataStream stream = DataStream();

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return CupertinoApp(
      title: 'Splash Test',
      theme: CupertinoThemeData(
        primaryColor: Color.fromARGB(255, 0, 0, 255),
      ),
      home: MyHomePage(title: 'Splash Test Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  bool textBool = false;
  int counter = 0;

  void changeTest(context) async {
    int counter = 0;
    Timer.periodic(Duration (seconds: 2), (Timer t) {
      counter++;
      stream.dataSink.add(true);
      if (counter >= 3) {
        t.cancel();
        stream.dispose();
        Navigator.pop(context);
      }
    },);
    Navigator.push(context, CupertinoPageRoute(builder: (context) => Page2(stream: stream)));
  }

  @override
  Widget build(BuildContext context) {

    return CupertinoPageScaffold(
      child: Center(
        child: CupertinoButton(
          child: Text('To Splash'),
          onPressed: () => changeTest(context),
        ),
      ),
    );
  }
}

File 2 (stream.dart)

import 'dart:async';

class DataStream {
  StreamController _streamController;

    StreamSink<bool> get dataSink =>
      _streamController.sink;

  Stream<bool> get dataStream =>
      _streamController.stream;

  DataStream() {
    _streamController = StreamController<bool>();
  }

  dispose() {
    _streamController?.close();
  }

}

File 3 (page2.dart)

import 'package:flutter/material.dart';
import 'package:flutter/semantics.dart';

import './main.dart';
import './stream.dart';

class Page2 extends StatefulWidget {

  DataStream stream;
  Page2({this.stream});

  @override
  State<StatefulWidget> createState() => new PageState();
}

class PageState extends State<Page2> {

bool textChanger = false;
bool firstText = true;

Text myText() {
  if (textChanger) {
    Text text1 = new Text('Text One',
      style: TextStyle(color: Color.fromARGB(255, 0, 0, 0)));
    return text1;
  } else {
    Text text1 = new Text('Text Two',
      style: TextStyle(color: Color.fromARGB(255, 0, 0, 0)));
    return text1;
  }
}

void changeText() {
  if (!firstText) {
    if (textChanger) {
      print('Change One');
      setState(() {
        textChanger = false;
      });
    } else {
      print('Change Two');
      setState(() {
        textChanger = true;
      });
    }
  } else {
    firstText = false;
  }
}

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      body: new Container(
        child: Center(
          child: myText()
        )
      ),);
  }

@override
  void initState() {
    super.initState();
    widget.stream.dataStream.listen((onData) {
      changeText();
    });
  }

}

Effectively, in this example, you can click on the text, and goto the second page, which will correctly change text when told, and return to the original page once completed.  That would be a single "Cycle" of my program.

And you can see that this program then immediately disposes of the stream.

The issue is that if I click the text a second time, it is still trying to listen to the original stream, rather than creating a brand new stream and starting fresh.

Why?  And how do I fix this?


问:
getaddrinfo() returns 0 (success) but sets errno to EINVAL (22)
I'm having problems with the following piece of code:

```<code>#include <errno.h>
#include <stdlib.h>

#include <netdb.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>

[...]
    struct protoent *tcp;
    struct addrinfo hint = {0};
    struct addrinfo *addrs;
    int             status;

    tcp = getprotobyname("tcp");
    if (!tcp)
        return  -EINVAL;
    hint.ai_family      = AF_UNSPEC;
    hint.ai_socktype    = SOCK_STREAM;
    hint.ai_protocol    = tcp->p_proto;
// errno is 0
    status  = getaddrinfo("localhost", "30002", &hint, &addrs);
// errno is 22
    if (status)
        return  -labs(status);
[...]
</code>```

The problem is that although it works (I'm using this for a TCP communication which indeed is working), it's inconsistent:

man getaddrinfo says nothing about errno; instead it returns an error code.  Why may it be setting errno to EINVAL (22, Invalid argument) internally?

答:
It doesn't matter why it happens.  errno only has meaning to you when a function call fails in your own code, and that function is designed to use errno to report errors to you.  But that is not the case with getaddrinfo() in most situations.

getaddrinfo() may be (and likely is) using other functions internally to do its work, and if those functions fail then getaddrinfo() will silently handle them internally as needed.  If those errors are fatal to getaddrinfo()'s work then it will exit with its own error code returned to you as needed.

So, as long as getaddrinfo() itself is not reporting an error code to you than you simply can't rely on errno having any kind of meaningful value.  errno changing value is simply a side effect of getaddrinfo()'s internal implementation on your system.

The ONLY time you should be looking at errno after getaddrinfo() exits is when getaddrinfo() returns EAI_SYSTEM, ONLY THEN will errno have a meaningful value to you.

Body:
I'm having problems with the following piece of code:

#include <errno.h>
#include <stdlib.h>

#include <netdb.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>

[...]
    struct protoent *tcp;
    struct addrinfo hint = {0};
    struct addrinfo *addrs;
    int             status;

    tcp = getprotobyname("tcp");
    if (!tcp)
        return  -EINVAL;
    hint.ai_family      = AF_UNSPEC;
    hint.ai_socktype    = SOCK_STREAM;
    hint.ai_protocol    = tcp->p_proto;
// errno is 0
    status  = getaddrinfo("localhost", "30002", &hint, &addrs);
// errno is 22
    if (status)
        return  -labs(status);
[...]

The problem is that although it works (I'm using this for a TCP communication which indeed is working), it's inconsistent:

man getaddrinfo says nothing about errno; instead it returns an error code.  Why may it be setting errno to EINVAL (22, Invalid argument) internally?


问:
Freemarker loop doesn't seems to print sequentially
I am trying to make model code with getter and setter from a comma-separated string. But somewhere I am making a mistake or so, I am not getting it right.

```<code>package ${packageName};

    public class modelName{

    <#assign x = ''>
    <#list parameters?split(',') as x>
    private ${x};
    <#assign mappedArray = []>
    <#assign y = ''>
    <#list x?split(r'\s+', 'r') as y>
    <#assign mappedArray = mappedArray + [y]>
    </#list>

    public ${mappedArray[0]} get${mappedArray[1]}(){
    return ${mappedArray[1]};
    }

    public void set${mappedArray[1]}( ${mappedArray[0]} ${mappedArray[1]}){
    this.${mappedArray[1]} = ${mappedArray[1]};
    }

    </#list>
    }
</code>```

I am giving int id, String name as parameters. I am expecting it to be split and we get x. From x I am trying to assign it to mappedAray and trying to print get and set function. But I am not getting the right output.

```<code>    package com.vindys.myapplication;

public class modelName {

    private int id;
    private String name;

    public getString() {
        return String;
    }

    public int getid() {
        return id;
    }

    public void setid(int id) {
        this.id = id;
    }

    public void setString(String) {
        this.String = String;
    }

}
</code>```

It writes for the first parameter, and later setter and getter is messed up.

答:
The output you are showing can't be the output of the template you are showing. So check if the template you are looking at is what's actually used. Because otherwise the template should work, though it's needlessly over-complicated. Like you split something to a sequence, and then build another totally identical sequence from it. Consider this, which does the same:</p>

```<code><#list parameters?split(',') as param>
<#assign paramWords = param?word_list>
<#assign type = paramWords[0]>
<#assign name = paramWords[1]>
private ${type} ${name};

public ${type} get${name?cap_first}(){
    return ${name};
}

public void set${name?cap_first}(${type} ${name}){
    this.${name} = ${name};
}
</#list>
</code>```

Body:
I am trying to make model code with getter and setter from a comma-separated string. But somewhere I am making a mistake or so, I am not getting it right.

package ${packageName};

    public class modelName{

    <#assign x = ''>
    <#list parameters?split(',') as x>
    private ${x};
    <#assign mappedArray = []>
    <#assign y = ''>
    <#list x?split(r'\s+', 'r') as y>
    <#assign mappedArray = mappedArray + [y]>
    </#list>

    public ${mappedArray[0]} get${mappedArray[1]}(){
    return ${mappedArray[1]};
    }

    public void set${mappedArray[1]}( ${mappedArray[0]} ${mappedArray[1]}){
    this.${mappedArray[1]} = ${mappedArray[1]};
    }

    </#list>
    }

I am giving int id, String name as parameters. I am expecting it to be split and we get x. From x I am trying to assign it to mappedAray and trying to print get and set function. But I am not getting the right output.

    package com.vindys.myapplication;

public class modelName {

    private int id;
    private String name;

    public getString() {
        return String;
    }

    public int getid() {
        return id;
    }

    public void setid(int id) {
        this.id = id;
    }

    public void setString(String) {
        this.String = String;
    }

}

It writes for the first parameter, and later setter and getter is messed up.

Body:
The output you are showing can't be the output of the template you are showing. So check if the template you are looking at is what's actually used. Because otherwise the template should work, though it's needlessly over-complicated. Like you split something to a sequence, and then build another totally identical sequence from it. Consider this, which does the same:

<#list parameters?split(',') as param>
<#assign paramWords = param?word_list>
<#assign type = paramWords[0]>
<#assign name = paramWords[1]>
private ${type} ${name};

public ${type} get${name?cap_first}(){
    return ${name};
}

public void set${name?cap_first}(${type} ${name}){
    this.${name} = ${name};
}
</#list>


问:
Powerpoint Chart Data Update From Excel Instance - Data disappears when Edit Data
I am editing a PPT template with data from Excel using the following code:

```<code>    Set shapeObject = oPPT.ActivePresentation.Slides(slideIndex).Shapes("Chart 9")
    With shapeObject.Chart.ChartData
     .Workbook.Worksheets(1).Range("B2").Value = Sheets(slideSheetName).Range("D3").Text
     .Workbook.Worksheets(1).Range("B3").Value = Sheets(slideSheetName).Range("D4").Text
     .Workbook.Worksheets(1).Range("B4").Value = Sheets(slideSheetName).Range("D5").Text
     .Workbook.Close
    End With
</code>```

When I click to Edit Data on the chart in PPT I see the data as it was copied over from the above code.  But some users see no data in the Edit Data sheet but the chart itself still has data in it.

Has anyone ever seen that before?  What is the fix?

答:
```<code>.Workbook.Worksheets(1).
</code>```

This reference doesn't seem sound.

I'd try something like this:

```<code>Workbooks('NameofWB').Sheets('Sheet1')
</code>```

So the code is explicit as to what workbook is referenced.

Body:
I am editing a PPT template with data from Excel using the following code:

    Set shapeObject = oPPT.ActivePresentation.Slides(slideIndex).Shapes("Chart 9")
    With shapeObject.Chart.ChartData
     .Workbook.Worksheets(1).Range("B2").Value = Sheets(slideSheetName).Range("D3").Text
     .Workbook.Worksheets(1).Range("B3").Value = Sheets(slideSheetName).Range("D4").Text
     .Workbook.Worksheets(1).Range("B4").Value = Sheets(slideSheetName).Range("D5").Text
     .Workbook.Close
    End With

When I click to Edit Data on the chart in PPT I see the data as it was copied over from the above code.  But some users see no data in the Edit Data sheet but the chart itself still has data in it.

Has anyone ever seen that before?  What is the fix?

Body:
.Workbook.Worksheets(1).

This reference doesn't seem sound.

I'd try something like this:

Workbooks('NameofWB').Sheets('Sheet1')

So the code is explicit as to what workbook is referenced.


问:
What is the ASP.NET Core way of setting TemplateInfo on a ViewDataDictionary
In attempting to convert a project to Core I am running into an issue.

Pre-Core System.Web.MVC.ViewDataDictionary exposed a TemplateInfo property with both a getter and a setter property.  This allows us to set an HtmlFieldPrefix field that was the magic behind getting form fields in nested arrays to bind during a form POST.

We use it like this...

```<code>for (var c = 0; c < Model.Items.Count(); c++)
{
    for (var p = 0; p < Model.Items[c].ParticipantViewModels.Count; p += 1)
    {
        @Html.Partial("~/Views/Shared/_CheckoutPrices.cshtml", Model.Items[c].ParticipantViewModels[p],
            new ViewDataDictionary(Html.ViewData)
            {
                TemplateInfo = new TemplateInfo
                {
                    HtmlFieldPrefix = $"Items[{c}].ParticipantViewModels[{p}]"
                }
            })
    }
}
for (var c = 0; c < Model.UnscheduledItems.Count(); c++)
{
    for (var p = 0; p < Model.UnscheduledItems[c].ParticipantViewModels.Count; p += 1)
    {
        @Html.Partial("~/Views/Shared/_CheckoutPrices.cshtml", Model.UnscheduledItems[c].ParticipantViewModels[p],
            new ViewDataDictionary(Html.ViewData)
            {
                TemplateInfo = new TemplateInfo
                {
                    HtmlFieldPrefix = $"UnscheduledItems[{c}].ParticipantViewModels[{p}]"
                }
            })
    }
}
</code>```

The same partial view is used for 'Items' and 'UnscheduledItems' but the HtmlFieldPrefix value is what gives the partial view context. The partial view can then use regular HtmlHelpers to produce the html with the proper name attribute set.  In this example we use IdFor because this is a radio button but for other input types we use the helpers.

```<code>@Html.RadioButtonFor(m => Model.SelectedPriceId, Model.Prices[p].Id, new { Id = Html.IdFor(m => Model.Prices[p]) })
</code>```

Which produces HTML like this..

```<code><input id="Items_0__ParticipantViewModels_0__Prices_0_" checked="checked" name="Items[0].ParticipantViewModels[0].SelectedPriceId" type="radio" value="VFdwSk5VMUVUVEZXU0VvMVpFYzBQUT09">
</code>```

The problem that I am facing is that the TemplateInfo property on the .Net Core ViewDataDictionary does not expose a setter. Source: https://github.com/dotnet/aspnetcore/blob/master/src/Mvc/Mvc.ViewFeatures/src/ViewDataDictionary.cs

Looking for a clean solution to this problem and so far can't seem to find one.

Couple questions:

How is one supposed to set TemplateInfo in .Net Core?

Is there a different way that we should be handling this?

Thanks in advance!

答:
Found great solution: MVC 6 VNext how to set HtmlFieldPrefix?

Solution recap:  Add an extension method like:

```<code>public static class HtmlHelpers
{
    public static Task<IHtmlContent> PartialAsync(this IHtmlHelper htmlHelper, string partialViewName, object model, string prefix)
    {
        var viewData = new ViewDataDictionary(htmlHelper.ViewData);
        var htmlPrefix = viewData.TemplateInfo.HtmlFieldPrefix;
        viewData.TemplateInfo.HtmlFieldPrefix += !Equals(htmlPrefix, string.Empty) ? $".{prefix}" : prefix;
        return htmlHelper.PartialAsync(partialViewName, model, viewData);
    }
}
</code>```

And consume it like:

```<code>@await Html.PartialAsync("~/Views/Shared/_CheckoutPricesV3.cshtml", Model.Items[c].ParticipantViewModels[p], $"Items[{c}].ParticipantViewModels[{p}]")
</code>```

Body:
In attempting to convert a project to Core I am running into an issue.

Pre-Core System.Web.MVC.ViewDataDictionary exposed a TemplateInfo property with both a getter and a setter property.  This allows us to set an HtmlFieldPrefix field that was the magic behind getting form fields in nested arrays to bind during a form POST.

We use it like this...

for (var c = 0; c < Model.Items.Count(); c++)
{
    for (var p = 0; p < Model.Items[c].ParticipantViewModels.Count; p += 1)
    {
        @Html.Partial("~/Views/Shared/_CheckoutPrices.cshtml", Model.Items[c].ParticipantViewModels[p],
            new ViewDataDictionary(Html.ViewData)
            {
                TemplateInfo = new TemplateInfo
                {
                    HtmlFieldPrefix = $"Items[{c}].ParticipantViewModels[{p}]"
                }
            })
    }
}
for (var c = 0; c < Model.UnscheduledItems.Count(); c++)
{
    for (var p = 0; p < Model.UnscheduledItems[c].ParticipantViewModels.Count; p += 1)
    {
        @Html.Partial("~/Views/Shared/_CheckoutPrices.cshtml", Model.UnscheduledItems[c].ParticipantViewModels[p],
            new ViewDataDictionary(Html.ViewData)
            {
                TemplateInfo = new TemplateInfo
                {
                    HtmlFieldPrefix = $"UnscheduledItems[{c}].ParticipantViewModels[{p}]"
                }
            })
    }
}

The same partial view is used for 'Items' and 'UnscheduledItems' but the HtmlFieldPrefix value is what gives the partial view context. The partial view can then use regular HtmlHelpers to produce the html with the proper name attribute set.  In this example we use IdFor because this is a radio button but for other input types we use the helpers.

@Html.RadioButtonFor(m => Model.SelectedPriceId, Model.Prices[p].Id, new { Id = Html.IdFor(m => Model.Prices[p]) })

Which produces HTML like this..

<input id="Items_0__ParticipantViewModels_0__Prices_0_" checked="checked" name="Items[0].ParticipantViewModels[0].SelectedPriceId" type="radio" value="VFdwSk5VMUVUVEZXU0VvMVpFYzBQUT09">

The problem that I am facing is that the TemplateInfo property on the .Net Core ViewDataDictionary does not expose a setter. Source: https://github.com/dotnet/aspnetcore/blob/master/src/Mvc/Mvc.ViewFeatures/src/ViewDataDictionary.cs

Looking for a clean solution to this problem and so far can't seem to find one.

Couple questions:

How is one supposed to set TemplateInfo in .Net Core?

Is there a different way that we should be handling this?

Thanks in advance!

Body:
Found great solution: MVC 6 VNext how to set HtmlFieldPrefix?

Solution recap:  Add an extension method like:

public static class HtmlHelpers
{
    public static Task<IHtmlContent> PartialAsync(this IHtmlHelper htmlHelper, string partialViewName, object model, string prefix)
    {
        var viewData = new ViewDataDictionary(htmlHelper.ViewData);
        var htmlPrefix = viewData.TemplateInfo.HtmlFieldPrefix;
        viewData.TemplateInfo.HtmlFieldPrefix += !Equals(htmlPrefix, string.Empty) ? $".{prefix}" : prefix;
        return htmlHelper.PartialAsync(partialViewName, model, viewData);
    }
}

And consume it like:

@await Html.PartialAsync("~/Views/Shared/_CheckoutPricesV3.cshtml", Model.Items[c].ParticipantViewModels[p], $"Items[{c}].ParticipantViewModels[{p}]")


问:
LatLngToLayerPoint transformation to pixel coordinates
I am writing a test for leaf-let Map component using jest and React-testing-library.

My Map component uses some map method for example LatLngToLayerPoint.

Where as to I also mock 'react-leaflet' library that does not include the LatLngToLayerPoint method. I think I have to write a custom method for this transformation as a mock function.  Can anyone help? or identify a possible solution?

For mocking leafleat I use this link
https://github.com/PaulLeCam/react-leaflet/blob/master/mocks/leaflet.js

答:
The React-Leaflet library creates an instance of a leaflet map which does indeed contain all the same tools as any other leaflet map.  For something like this you're best off accessing this method from within the componentDidMount method, using a reference to the map.

import { Map as LeafletMap, TileLayer } from "react-leaflet";

class Map extends React.Component {

  componentDidMount(){

    // leafletElement is the leaflet object created by any react-leaflet component
    const map = this.mapReference.leafletElement
    const layerPoint = map.latLngToLayerPoint(map.getCenter())

  }

  render() {

    return (
      <LeafletMap
        ref={mapReference => this.mapReference = mapReference}
        zoom={4}
        center={[33.852169, -100.5322]} >

        <TileLayer ... />

      </LeafletMap>
    );

  }

}
```

Here is a working codesandbox.

Body:
The React-Leaflet library creates an instance of a leaflet map which does indeed contain all the same tools as any other leaflet map.  For something like this you're best off accessing this method from within the componentDidMount method, using a reference to the map.

import { Map as LeafletMap, TileLayer } from "react-leaflet";

class Map extends React.Component {

  componentDidMount(){

    // leafletElement is the leaflet object created by any react-leaflet component
    const map = this.mapReference.leafletElement
    const layerPoint = map.latLngToLayerPoint(map.getCenter())

  }

  render() {

    return (
      <LeafletMap
        ref={mapReference => this.mapReference = mapReference}
        zoom={4}
        center={[33.852169, -100.5322]} >

        <TileLayer ... />

      </LeafletMap>
    );

  }

}

Here is a working codesandbox.