问:
Multiple routes to the same razor page
Background

I've got a razor page in my Asp.Net Core 3.1 website called SignupAndApply. It's effectively a copy and paste of the register identity page but:

With some additional fields

Allows an optional applyid to be passed as part of the route

If I pass an applyId as part of the route, I make a couple of label changes to the page and redirect the user somewhere else

I want to create two routes for this page:

/identity/account/signupandapply/{applyId?} 'when the user is applying and signing up
/identity/account/signup 'when the user is just signing up
```

<p>I've added the following to the top of the page:</p>

```@page "{applyId?}"
```

<p>And set the applyId as an optional parameter on the OnGetAsync method:</p>

<pre class="lang-cs prettyprint-override"><code>public async Task OnGetAsync(string returnUrl = null, Guid? applyId = null)
</code>```

Issue

The route with the applyId is working but the /identity/account/signup route isn't.

I've tried adding this to my startup:

services.AddMvc()
        .AddRazorPagesOptions(options => options.Conventions
                             .AddPageRoute("/identity/account/signupandapply", "/identity/account/signup")
                             );
```

<p>It works if I go to one of these</p>

```/identity/account/signupandapply/<fooapplyid>
/identity/account/signupandapply
```

<p>But not this</p>

```/identity/account/signup
```

Any ideas what I'm doing wrong for what should be adding a simple alternative route?

答:
The page(/identity/account/signupandapply) is in area Identity ,so you need to use AddAreaPageRoute instead of AddAreaPage :

```<code>services.AddRazorPages().AddRazorPagesOptions(options =>
{

    options.Conventions.AddAreaPageRoute("Identity",
           "/account/signupandapply", "identity/account/signup");

    }); ;
</code>```

Title: Multiple routes to the same razor page

Body:
Background

I've got a razor page in my Asp.Net Core 3.1 website called SignupAndApply. It's effectively a copy and paste of the register identity page but:

With some additional fields

Allows an optional applyid to be passed as part of the route

If I pass an applyId as part of the route, I make a couple of label changes to the page and redirect the user somewhere else

I want to create two routes for this page:

/identity/account/signupandapply/{applyId?} 'when the user is applying and signing up
/identity/account/signup 'when the user is just signing up

I've added the following to the top of the page:

@page "{applyId?}"

And set the applyId as an optional parameter on the OnGetAsync method:

public async Task OnGetAsync(string returnUrl = null, Guid? applyId = null)

Issue

The route with the applyId is working but the /identity/account/signup route isn't.

I've tried adding this to my startup:

services.AddMvc()
        .AddRazorPagesOptions(options => options.Conventions
                             .AddPageRoute("/identity/account/signupandapply", "/identity/account/signup")
                             );

It works if I go to one of these

/identity/account/signupandapply/<fooapplyid>
/identity/account/signupandapply

But not this

/identity/account/signup

Any ideas what I'm doing wrong for what should be adding a simple alternative route?

Body:
The page(/identity/account/signupandapply) is in area Identity ,so you need to use AddAreaPageRoute instead of AddAreaPage :

services.AddRazorPages().AddRazorPagesOptions(options =>
{

    options.Conventions.AddAreaPageRoute("Identity",
           "/account/signupandapply", "identity/account/signup");

    }); ;


来源: stackexchange

问:
Google map api,how to handle marker hover event for all the markers at the same position(Overlapping markers)?
I am using google map API with angular. In a simple application, on the left side there is a MAP with lots of markers and on the right side, there is a list of the table which contains information about the markers, one row for each marker. And on marker hover I am highlighting row for the hovered marker on right side with below code.

```<code>google.maps.event.addListener(marker, 'mouseover', function () {
            var temp_marker_name = this.marker_name;
            $scope.$apply(function () {
                $scope.active_row_name = temp_marker_name;
            });
        });
        google.maps.event.addListener(marker, 'mouseout', function () {
            $scope.$apply(function () {
                $scope.active_row_name = '';
            });
        });
</code>```

So here, I set name on marker hover and based on the name, I highlight the row on right side.

Now, there is one case where more than one markers are plotted at the same position, and when I hover over that marker it highlights only one row on right side.

But I want to highlight all rows for the markers at that position.So, I want something that the hover event will fire for all the markers at the same position and I can make an array of names and then I can put a condition on that to highlight rows.

答:
You can make the bottom marker visible by seeing its zIndex above the other marker's zIndex.

```<code>function createMarker(point, html, i, map) {
  var marker = new google.maps.Marker({
    map: map,
    position: point,
    zIndex: 0,
    draggable: true

  });
  var activeIcon, idleIcon;

  idleIcon = 'http://labs.google.com/ridefinder/images/mm_20_blue.png';

  marker.setIcon(idleIcon);

  var elem = document.getElementById('a' + i);
  if (!!elem) {
    elem.onmouseover = function() {
      marker.setIcon('http://labs.google.com/ridefinder/images/mm_20_red.png');
      marker.setZIndex(100);
    }
    elem.onmouseleave = function() {
      marker.setIcon(idleIcon);
      marker.setZIndex(0);
    }
  }
  google.maps.event.addListener(marker, 'click', function() {
    infoWindow.setContent(html);
    infoWindow.open(map, marker);

  });

  return marker;
}
</code>```

proof of concept fiddle

```<code>var geocoder;
var infoWindow = new google.maps.InfoWindow();

function initialize() {
  var map = new google.maps.Map(
    document.getElementById("map_canvas"), {
      center: new google.maps.LatLng(37.4419, -122.1419),
      zoom: 13,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });
  var name = "Event1";
  var address = "address 1";
  var point = new google.maps.LatLng(42, -72);
  var html = "<b>" + name + "</b> <br/>" + address;
  var image1 = 'http://labs.google.com/ridefinder/images/mm_20_blue.png';
  var image2 = 'http://labs.google.com/ridefinder/images/mm_20_red.png';

  var i = 0;
  createMarker(point, html, i, map);

  point = new google.maps.LatLng(42.02, -72.02);
  name = "Event2";
  address = "address 2";
  html = "<b>" + name + "</b> <br/>" + address;
  i++;
  var marker = createMarker(point, html, i, map);

  point = new google.maps.LatLng(42.01, -72.01);
  name = "Event3";
  address = "address 3";
  html = "<b>" + name + "</b> <br/>" + address;
  i++;
  var marker = createMarker(point, html, i, map);
  map.setCenter(marker.getPosition());

  point = new google.maps.LatLng(42.01, -72.01);
  name = "Event4";
  address = "address 3";
  html = "<b>" + name + "</b> <br/>" + address;
  i++;
  var marker = createMarker(point, html, i, map);
  map.setCenter(marker.getPosition());

}

function createMarker(point, html, i, map) {
  var marker = new google.maps.Marker({
    map: map,
    position: point,
    zIndex: 0,
    draggable: true

  });
  var activeIcon, idleIcon;

  idleIcon = 'http://labs.google.com/ridefinder/images/mm_20_blue.png';

  marker.setIcon(idleIcon);

  var elem = document.getElementById('a' + i);
  if (!!elem) {
    elem.onmouseover = function() {
      marker.setIcon('http://labs.google.com/ridefinder/images/mm_20_red.png');
      marker.setZIndex(100);
    }
    elem.onmouseleave = function() {
      marker.setIcon(idleIcon);
      marker.setZIndex(0);
    }
  }
  google.maps.event.addListener(marker, 'click', function() {
    infoWindow.setContent(html);
    infoWindow.open(map, marker);

  });

  return marker;
}

function hover(marker, i) {
  document.getElementById('a' + i).onmouseover = function() {
    marker.setIcon('http://labs.google.com/ridefinder/images/mm_20_red.png');
  }
  document.getElementById('a' + i).onmouseleave = function() {
    marker.setIcon('http://labs.google.com/ridefinder/images/mm_20_blue.png');
  }
}

function bindInfoWindow(marker, map, infoWindow, html) {
  google.maps.event.addListener(marker, 'click', function() {
    infoWindow.setContent(html);
    infoWindow.open(map, marker);

  });
}
google.maps.event.addDomListener(window, "load", initialize);

html,
body,
#map_canvas {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}

<script src="https://maps.googleapis.com/maps/api/js?" type="text/javascript"></script>

<div id="a0">Event 1 address 1</div>
<div id="a1">Event 2 address 2</div>
<div id="a2">Event 3 address 3</div>
<div id="a3">Event 4 address 3</div>

<div id="map_canvas"></div>
</code>```

more info [Marker hovering on a Google Map

ContentLicense: CC BY-SA 4.0

Body:
I am using google map API with angular. In a simple application, on the left side there is a MAP with lots of markers and on the right side, there is a list of the table which contains information about the markers, one row for each marker. And on marker hover I am highlighting row for the hovered marker on right side with below code.

google.maps.event.addListener(marker, 'mouseover', function () {
            var temp_marker_name = this.marker_name;
            $scope.$apply(function () {
                $scope.active_row_name = temp_marker_name;
            });
        });
        google.maps.event.addListener(marker, 'mouseout', function () {
            $scope.$apply(function () {
                $scope.active_row_name = '';
            });
        });

So here, I set name on marker hover and based on the name, I highlight the row on right side.

Now, there is one case where more than one markers are plotted at the same position, and when I hover over that marker it highlights only one row on right side.

But I want to highlight all rows for the markers at that position.So, I want something that the hover event will fire for all the markers at the same position and I can make an array of names and then I can put a condition on that to highlight rows.

Body:
You can make the bottom marker visible by seeing its zIndex above the other marker's zIndex.

function createMarker(point, html, i, map) {
  var marker = new google.maps.Marker({
    map: map,
    position: point,
    zIndex: 0,
    draggable: true

  });
  var activeIcon, idleIcon;

  idleIcon = 'http://labs.google.com/ridefinder/images/mm_20_blue.png';

  marker.setIcon(idleIcon);

  var elem = document.getElementById('a' + i);
  if (!!elem) {
    elem.onmouseover = function() {
      marker.setIcon('http://labs.google.com/ridefinder/images/mm_20_red.png');
      marker.setZIndex(100);
    }
    elem.onmouseleave = function() {
      marker.setIcon(idleIcon);
      marker.setZIndex(0);
    }
  }
  google.maps.event.addListener(marker, 'click', function() {
    infoWindow.setContent(html);
    infoWindow.open(map, marker);

  });

  return marker;
}

proof of concept fiddle

var geocoder;
var infoWindow = new google.maps.InfoWindow();

function initialize() {
  var map = new google.maps.Map(
    document.getElementById("map_canvas"), {
      center: new google.maps.LatLng(37.4419, -122.1419),
      zoom: 13,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });
  var name = "Event1";
  var address = "address 1";
  var point = new google.maps.LatLng(42, -72);
  var html = "<b>" + name + "</b> <br/>" + address;
  var image1 = 'http://labs.google.com/ridefinder/images/mm_20_blue.png';
  var image2 = 'http://labs.google.com/ridefinder/images/mm_20_red.png';

  var i = 0;
  createMarker(point, html, i, map);

  point = new google.maps.LatLng(42.02, -72.02);
  name = "Event2";
  address = "address 2";
  html = "<b>" + name + "</b> <br/>" + address;
  i++;
  var marker = createMarker(point, html, i, map);

  point = new google.maps.LatLng(42.01, -72.01);
  name = "Event3";
  address = "address 3";
  html = "<b>" + name + "</b> <br/>" + address;
  i++;
  var marker = createMarker(point, html, i, map);
  map.setCenter(marker.getPosition());

  point = new google.maps.LatLng(42.01, -72.01);
  name = "Event4";
  address = "address 3";
  html = "<b>" + name + "</b> <br/>" + address;
  i++;
  var marker = createMarker(point, html, i, map);
  map.setCenter(marker.getPosition());

}

function createMarker(point, html, i, map) {
  var marker = new google.maps.Marker({
    map: map,
    position: point,
    zIndex: 0,
    draggable: true

  });
  var activeIcon, idleIcon;

  idleIcon = 'http://labs.google.com/ridefinder/images/mm_20_blue.png';

  marker.setIcon(idleIcon);

  var elem = document.getElementById('a' + i);
  if (!!elem) {
    elem.onmouseover = function() {
      marker.setIcon('http://labs.google.com/ridefinder/images/mm_20_red.png');
      marker.setZIndex(100);
    }
    elem.onmouseleave = function() {
      marker.setIcon(idleIcon);
      marker.setZIndex(0);
    }
  }
  google.maps.event.addListener(marker, 'click', function() {
    infoWindow.setContent(html);
    infoWindow.open(map, marker);

  });

  return marker;
}

function hover(marker, i) {
  document.getElementById('a' + i).onmouseover = function() {
    marker.setIcon('http://labs.google.com/ridefinder/images/mm_20_red.png');
  }
  document.getElementById('a' + i).onmouseleave = function() {
    marker.setIcon('http://labs.google.com/ridefinder/images/mm_20_blue.png');
  }
}

function bindInfoWindow(marker, map, infoWindow, html) {
  google.maps.event.addListener(marker, 'click', function() {
    infoWindow.setContent(html);
    infoWindow.open(map, marker);

  });
}
google.maps.event.addDomListener(window, "load", initialize);

html,
body,
#map_canvas {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}

<script src="https://maps.googleapis.com/maps/api/js?" type="text/javascript"></script>

<div id="a0">Event 1 address 1</div>
<div id="a1">Event 2 address 2</div>
<div id="a2">Event 3 address 3</div>
<div id="a3">Event 4 address 3</div>

<div id="map_canvas"></div>

more info [Marker hovering on a Google Map


问:
jQuery: Checking if next element exists
Is there a way to check if a next element exists? Check my code:

```<code>if($("#people .making-of .mask ul li.current").next("li") != null) {
    alert("Exists");
}
else {
    alert("Dont exists");
}
</code>```

What am I doing wrong? Thanks a lot!

答:
I think this is good to use like.</p>

```
   if ($(this).nextAll().length > 0) {

     alert("Exists");

   }else{

     alert("Don't exists");

   }
```

Title: jQuery: Checking if next element exists

Body:
Is there a way to check if a next element exists? Check my code:

if($("#people .making-of .mask ul li.current").next("li") != null) {
    alert("Exists");
}
else {
    alert("Dont exists");
}

What am I doing wrong? Thanks a lot!

Body:
I think this is good to use like.

   if ($(this).nextAll().length > 0) {

     alert("Exists");

   }else{

     alert("Don't exists");

   }


问:
Python - Comparing two text file and output differences using loops
The first file:
This is text./n abc/n 123

The second file:
This is text./n xyz/n 123

I'm doing an assignment that is asking me to print("No") while also printing the part of the line that is different in both the first and second file if the file is different. They are asking me to use loops to compare and find the difference than to print the differences and break the loop if the differences are found. I can't seem to get to the second line of text to make my condition true.

```<code>secondFile = input("Enter the second file name: ")
first = open(firstFile, 'r')
second = open(secondFile, 'r')
if first.read() == second.read():
    print("Yes")
else:
    print("No")
    while True:
        firstLine = first.readline()
        secondLine = second.readline()
        if firstLine == secondLine:
            print(first.readline())
            print(second.readline())
            break```
```

答:
second.read() consimes all the data from the file, so once you reach first.readline() you get only empty strings. Read the file line by line and print "Yes" only if all the lines where already compare using for else. You should also close the files once done, you can do it by using with

```<code>with open(firstFile, 'r') as file1, open(secondFile, 'r') as file2:
    for line1, line2 in zip(file1, file2):
        if line1 != line2:
            print('No', line1, line2, sep='\n')
            break
    else:
        print('Yes')
</code>```

Body:
The first file:
This is text./n abc/n 123

The second file:
This is text./n xyz/n 123

I'm doing an assignment that is asking me to print("No") while also printing the part of the line that is different in both the first and second file if the file is different. They are asking me to use loops to compare and find the difference than to print the differences and break the loop if the differences are found. I can't seem to get to the second line of text to make my condition true.

secondFile = input("Enter the second file name: ")
first = open(firstFile, 'r')
second = open(secondFile, 'r')
if first.read() == second.read():
    print("Yes")
else:
    print("No")
    while True:
        firstLine = first.readline()
        secondLine = second.readline()
        if firstLine == secondLine:
            print(first.readline())
            print(second.readline())
            break```

Body:
second.read() consimes all the data from the file, so once you reach first.readline() you get only empty strings. Read the file line by line and print "Yes" only if all the lines where already compare using for else. You should also close the files once done, you can do it by using with

with open(firstFile, 'r') as file1, open(secondFile, 'r') as file2:
    for line1, line2 in zip(file1, file2):
        if line1 != line2:
            print('No', line1, line2, sep='\n')
            break
    else:
        print('Yes')


问:
error magic zoom with javascript and html,css
My code contains five images, four of which are thumbnails,Are displayed by clicking  in the main img tag
The problem is, besides changing the photo I want to zoom in  but Whenever the photo changes,show zoom for the same photo
my code show result zoom just for fist img and i think it is related to js code this line  buti am not sure and i cannot solve it

result.style.backgroundImage = "url('" + img.src + "')";

img in state of1

result zoom div not changing

```
<pre class="snippet-code-css lang-css prettyprint-override"><code><style>
    * {
      box-sizing: border-box;
    }

    body {
      margin: 0;
      font-family: Arial;
    }

    /* The grid: Four equal columns that floats next to each other */
    .column {
      float: left;
      width: 25%;
      padding: 10px;
    }

    /* Style the images inside the grid */
    .column img {
      opacity: 0.8;
      cursor: pointer;
    }

    .column img:hover {
      opacity: 1;
    }

    /* Clear floats after the columns */
    .row:after {
      content: "";
      display: table;
      clear: both;
    }

    /* The expanding image container */
    .container {
      position: relative;
      display: none;
    }

    /* Expanding image text */
    #imgtext {
      position: absolute;
      bottom: 15px;
      left: 15px;
      color: white;
      font-size: 20px;
    }

    /* Closable button inside the expanded image */
    .closebtn {
      position: absolute;
      top: 10px;
      right: 15px;
      color: white;
      font-size: 35px;
      cursor: pointer;
    }
    </style>
<style>
* {box-sizing: border-box;}

.img-zoom-container {
  position: relative;
}

.img-zoom-lens {
  position: absolute;
  border: 1px solid #d4d4d4;
  /*set the size of the lens:*/
  width: 40px;
  height: 40px;
}

.img-zoom-result {
  border: 1px solid #d4d4d4;
  /*set the size of the result div:*/
  width: 300px;
  height: 300px;
}
</style>
<script></code>```

```

答:
i solve it after 5 min insert my question :))))
i should use this code

function myFunction(imgs) {
  var expandImg = document.getElementById("expandedImg");

  expandImg.src = imgs.src;

  expandImg.parentElement.style.display = "block";
imageZoom("expandedImg", "myresult");
}```


问:
Provide multiple paths in the azure function path bindings for storage
I am using azure function to be called when there is a file copied in my ADLS gen2 storage account. There are roughly 10 containers in the ADLS gen2 storage and I would like to call this function app only when a file is copied to either 2 of the containers, later I will be increase it to more. My container names are like abc, def.... and inside them files are copied.

In my azure function I have input bindings like

```<code>{
      "name": "myblob",
      "type": "blobTrigger",
      "direction": "in",
      "path": "abc/{name}.{csv}",
      "connection": "storage account"
}
</code>```

How can I add def to the input path, Is multiple path supported here. I would like to call the same function when a file is copied

答:
Instead of using the blob trigger (which polls the storage account), you can use the Event Grid Trigger which is a recommended alternative in the blob storage trigger doc itself.

With this, you will have a single Event Grid triggered function which reacts to events coming from Event Grid. Also, you can filter events based on your requirement.

Another approach would be to change the path to something like this {path}/{name}.{csv}. With this, your function will get invoked for each file and in your code, check the path.

Also, note that using .{csv} will create a binding for the extension to a variable named csv. If the intention is to just trigger on .csv files, then just use it without the braces.

Body:
I am using azure function to be called when there is a file copied in my ADLS gen2 storage account. There are roughly 10 containers in the ADLS gen2 storage and I would like to call this function app only when a file is copied to either 2 of the containers, later I will be increase it to more. My container names are like abc, def.... and inside them files are copied.

In my azure function I have input bindings like

{
      "name": "myblob",
      "type": "blobTrigger",
      "direction": "in",
      "path": "abc/{name}.{csv}",
      "connection": "storage account"
}

How can I add def to the input path, Is multiple path supported here. I would like to call the same function when a file is copied


问:
What's the best practice for these kinds of routes?
I have a Job model that belongs_to three users (customer, employee, and qa). The customer is set to current_user when the job is created, but the employee and qa users pick their jobs from the pool of unclaimed jobs.

The way I have this implemented currently is as follows: match 'jobs/:id/assign/:type/:user_id' => 'jobs#assign' with an assign method with a case statement on params[:type]. So, for example, jobs/1/assign/qa/1 assigns user 1 as the qa for job 1.

This works, but it seems sloppy and I'd like to replace it with something cleaner. Is there a common convention for situations like this?

Edit: Users can have both employee and qa roles simultaneously. That's what's making me feel forcing into such a complex route.

```<code>class User < ActiveRecord::Base
  has_many :submitted_jobs,  :class_name => 'Job', :foreign_key => 'customer_id'
  has_many :assigned_jobs,   :class_name => 'Job', :foreign_key => 'employee_id'
  has_many :reviewed_jobs,   :class_name => 'Job', :foreign_key => 'qa_id'

class Job < ActiveRecord::Base
  belongs_to :customer, :class_name => 'User', :foreign_key => 'customer_id'
  belongs_to :employee, :class_name => 'User', :foreign_key => 'employee_id'
  belongs_to :qa,       :class_name => 'User', :foreign_key => 'qa_id'
</code>```

答:
I think a great way about solving this is design your routes first which is what you're doing.

Your current routing is great if the "Job" and the assignee are well known in advance. In my opinion if you stuff the the job AND the assignee type information in the route you're doing too much.

Do the employees/qa also login and pick their own jobs? If they do, then their own information will be available on the server side in "current_user".

In that case, the route should ideally be "/job/:id/pick" going to "JobsController#pick" action with a POST request for example. In your controller action you would get the eemployee/qa user info in the current_user.

```<code>config/routes.rb

resource :jobs do
  member do
    post :pick
  end
end

in app/controller/jobs_controller.rb

def pick
  job = Job.find(params[:id])
  current_user.jobs << job # User has_many :jobs
  # or
  job.user = current_user
  ...
end
</code>```

Please do let me know if employees/qa do NOT login and i'll update solution accordingly with another solution.

ContentLicense: CC BY-SA 3.0

Body:
I have a Job model that belongs_to three users (customer, employee, and qa). The customer is set to current_user when the job is created, but the employee and qa users pick their jobs from the pool of unclaimed jobs.

The way I have this implemented currently is as follows: match 'jobs/:id/assign/:type/:user_id' => 'jobs#assign' with an assign method with a case statement on params[:type]. So, for example, jobs/1/assign/qa/1 assigns user 1 as the qa for job 1.

This works, but it seems sloppy and I'd like to replace it with something cleaner. Is there a common convention for situations like this?

Edit: Users can have both employee and qa roles simultaneously. That's what's making me feel forcing into such a complex route.

class User < ActiveRecord::Base
  has_many :submitted_jobs,  :class_name => 'Job', :foreign_key => 'customer_id'
  has_many :assigned_jobs,   :class_name => 'Job', :foreign_key => 'employee_id'
  has_many :reviewed_jobs,   :class_name => 'Job', :foreign_key => 'qa_id'

class Job < ActiveRecord::Base
  belongs_to :customer, :class_name => 'User', :foreign_key => 'customer_id'
  belongs_to :employee, :class_name => 'User', :foreign_key => 'employee_id'
  belongs_to :qa,       :class_name => 'User', :foreign_key => 'qa_id'

Body:
I think a great way about solving this is design your routes first which is what you're doing.

Your current routing is great if the "Job" and the assignee are well known in advance. In my opinion if you stuff the the job AND the assignee type information in the route you're doing too much.

Do the employees/qa also login and pick their own jobs? If they do, then their own information will be available on the server side in "current_user".

In that case, the route should ideally be "/job/:id/pick" going to "JobsController#pick" action with a POST request for example. In your controller action you would get the eemployee/qa user info in the current_user.

config/routes.rb

resource :jobs do
  member do
    post :pick
  end
end

in app/controller/jobs_controller.rb

def pick
  job = Job.find(params[:id])
  current_user.jobs << job # User has_many :jobs
  # or
  job.user = current_user
  ...
end

Please do let me know if employees/qa do NOT login and i'll update solution accordingly with another solution.


问:
Private node cannot join cluster
I've been trying to create a EKS cluster in terraform, the scripts below works fine if I create my worker nodes in hte public subnet. However if i try to put them in the private subnet, it fails for unable to join cluster.

I think it's something to do with the gateway, but I've tried a lot of things now and i just can't to see what the issue is, would someone be able to help me please.

https://gitlab.com/roboops/case_study/-/tree/master/terraform

答:
As per EKS documentation you would need outbound access for internet for worker nodes.

Check the notes section here https://docs.aws.amazon.com/eks/latest/userguide/network_reqs.html

Title: Private node cannot join cluster


问:
When use POST and PUT Method In Laravel?
I don't know exact difference between POST and PUT method.Some of the people said on internet that when you update record at time you have to use PUT method instead of POST, i don't know is it true??

form Internet if your website URL in POST method
1. www.example.com/user/{id}/update  :- PUT use
2. www.example.com/user/update       :- POST use
this is right or not ??

答:
If you're inserting a new data you'll most likely use POST method

```<code>Route::post('new/data', 'NewDataController@store');
</code>```

If you want to edit or add a new data that is not existing, you must use PUT method

```<code>Route::put('/data', 'NewDataController@update');
</code>```

Body:
If you're inserting a new data you'll most likely use POST method

Route::post('new/data', 'NewDataController@store');

If you want to edit or add a new data that is not existing, you must use PUT method

Route::put('/data', 'NewDataController@update');


问:
"Resource not accessible by integration" when trying to create trigger
This is a very simple question, but after trying to find an answer for 3 hours I am asking, so I apologize if it is a duplicate.

I am trying to add a "Continuous deployment trigger" to my Azure DevOps Pipeline:

But after configuring the Branch Filters and trying to save, I get the following error message:

"GitHub Could not create service hooks subscription Unable to
  configure a service on the selected GitHub repository. GitHub returned
  the error 'Resource not accessible by integration'. "

My repository is hosted on GitHub and it is private, and so is my project on Azure DevOps

I would expect this to "just work", so I really don't see which other information would be relevant on this question, so apologies in advance in case I forgot to mention something

答:
Through testing, I can reproduce this issue:

The cause of this error could be the selected service connection, when the service connection is to a GitHub-InstallationToken, I got the same error, as shown below:

When I choose the service connection as shown below, everything is normal:

You can check the service connections in the project settings.


问:
How do I disallow download file through direct url access?
I am currently working on a project that allows user to update and patch their application when updates are available. I am using Apache as web server and put my patch files in the webroot. The application download the patch files through https (I am using a patching system bought from unity assets stores. It supports http, https and ftp. It is done in c#). I have disable directory listing for better security, however I still able to download specific files through browser if I specify the path. For example:
https://example.com/patch/test.txt

Is there any way I can restrict user from downloading the files directly through url? Is there any better approach that I can improve the security?

Thank you.

答:
You can allow only specific ips:

```<code><Location />
        Order Deny,Allow
        Deny from all
        Allow from 192.168.
</Location>
</code>```

If the application is installed on the same pc as the browser,  then you are out of luck. You might be able to do some magic with user agents,  but that is hackable by pretty much anyone with postman.

This is why we prefer to store these in databases, file servers or blob storage, so that we can also secure them.

Body:
You can allow only specific ips:

<Location />
        Order Deny,Allow
        Deny from all
        Allow from 192.168.
</Location>

If the application is installed on the same pc as the browser,  then you are out of luck. You might be able to do some magic with user agents,  but that is hackable by pretty much anyone with postman.

This is why we prefer to store these in databases, file servers or blob storage, so that we can also secure them.


问:
How to pop-up message on the exact card where it's clicked?
I'm trying to show some elements in a list of cards and when I click on a card, I need to show a pop-up message on that exact card. Right now it's showing up the top card. But I need to it to show up on the card I click.

Here's my html code for showing card elements and pop-up:

```<code>
<a class="external" ng-repeat="card in cardData" ng-click="popUpFunction()">
  <div class="card">
      <img class="card-image" src="{{card.thumbNail_image}}" alt="">
      <div class="popup">
          <span class="popuptext" id="myPopup">A Simple Popup!</span>
      </div>
      <div class="card-infos">
          <h2 class="card-title">{{card.contentDescription}}</h2>
      </div>
   </div>
</a>

</code>```

Here's the css code:

```<code>.popup {
  position: relative;
  display: inline-block;
  cursor: pointer;
  height:0px;
  width:0px;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}

/* The actual popup */
.popup .popuptext {
  visibility: hidden;
  width: 160px;
  background-color: #555;
  color: #fff;
  text-align: center;
  border-radius: 6px;
  padding: 8px 0;
  position: absolute;
  z-index: 1;

  margin-left: 80px;
}

/* Popup arrow */
.popup .popuptext::after {
  content: "";
  position: absolute;
  top: 100%;
  left: 50%;
  margin-left: -5px;
  border-width: 5px;
  border-style: solid;
  border-color: #555 transparent transparent transparent;
}

/* Toggle this class - hide and show the popup */
.popup .show {
  visibility: visible;
  -webkit-animation: fadeIn 1s;
  animation: fadeIn 1s;
}

/* Add animation (fade in the popup) */
@-webkit-keyframes fadeIn {
  from {opacity: 0;}
  to {opacity: 1;}
}

@keyframes fadeIn {
  from {opacity: 0;}
  to {opacity:1 ;}
}
</code>```

And here's the js code:

```<code>$scope.popUpFunction = function () {
   var popup = document.getElementById("myPopup");
   popup.classList.toggle("show");
}
</code>```

答:
You can get the element clicked passing the event to the function. In the event object, you can extract the target property which is the element clicked. Here it is a quick demo to illustrate.

Also, it seems that you have your on click on a loop, I don't know angularJS but I think it would be something like this:

```<code><div class="card" ng-click="popUpFunction($event)">       // notice the $event
</code>```

instead of

```<code><a class="external" ng-repeat="card in cardData" ng-click="popUpFunction()">
</code>```

function onClickShowMessage(event) {
  const card = event.target;
  const message = createMessageElement();
  card.appendChild(message);
}

function createMessageElement() {
  const message = document.createElement('p');
  message.innerHTML = 'This is some message';
  message.classList.add('message');
  return message;
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.card {
  width: 200px;
  min-height: 150px;
  background-color: yellow;
  cursor: pointer;
  margin-bottom: 5px;
  display: block;
}

.message {
  background-color: firebrick;
  color: white;
  padding: 1rem;
}</code>```

```

Body:
I'm trying to show some elements in a list of cards and when I click on a card, I need to show a pop-up message on that exact card. Right now it's showing up the top card. But I need to it to show up on the card I click.

Here's my html code for showing card elements and pop-up:

          A Simple Popup!

{{card.contentDescription}}

Here's the css code:

.popup {
  position: relative;
  display: inline-block;
  cursor: pointer;
  height:0px;
  width:0px;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}

/* The actual popup */
.popup .popuptext {
  visibility: hidden;
  width: 160px;
  background-color: #555;
  color: #fff;
  text-align: center;
  border-radius: 6px;
  padding: 8px 0;
  position: absolute;
  z-index: 1;

  margin-left: 80px;
}

/* Popup arrow */
.popup .popuptext::after {
  content: "";
  position: absolute;
  top: 100%;
  left: 50%;
  margin-left: -5px;
  border-width: 5px;
  border-style: solid;
  border-color: #555 transparent transparent transparent;
}

/* Toggle this class - hide and show the popup */
.popup .show {
  visibility: visible;
  -webkit-animation: fadeIn 1s;
  animation: fadeIn 1s;
}

/* Add animation (fade in the popup) */
@-webkit-keyframes fadeIn {
  from {opacity: 0;}
  to {opacity: 1;}
}

@keyframes fadeIn {
  from {opacity: 0;}
  to {opacity:1 ;}
}

And here's the js code:

$scope.popUpFunction = function () {
   var popup = document.getElementById("myPopup");
   popup.classList.toggle("show");
}

Body:
You can get the element clicked passing the event to the function. In the event object, you can extract the target property which is the element clicked. Here it is a quick demo to illustrate.

Also, it seems that you have your on click on a loop, I don't know angularJS but I think it would be something like this:

<div class="card" ng-click="popUpFunction($event)">       // notice the $event

instead of

<a class="external" ng-repeat="card in cardData" ng-click="popUpFunction()">

function onClickShowMessage(event) {
  const card = event.target;
  const message = createMessageElement();
  card.appendChild(message);
}

function createMessageElement() {
  const message = document.createElement('p');
  message.innerHTML = 'This is some message';
  message.classList.add('message');
  return message;
}

.card {
  width: 200px;
  min-height: 150px;
  background-color: yellow;
  cursor: pointer;
  margin-bottom: 5px;
  display: block;
}

.message {
  background-color: firebrick;
  color: white;
  padding: 1rem;
}

<a class="card" onclick="onClickShowMessage(event)"></a>
<a class="card" onclick="onClickShowMessage(event)"></a>
<a class="card" onclick="onClickShowMessage(event)"></a>


问:
dynamically add array of buttons and reference those buttons by id in android
i found this helpful post for adding buttons dynamically to a layout, however i am can't understand how to reference those buttons by id (or some other way) to use them in the program.  can anyone help me?</p>

答:
I had the same situation.Just use Tag, and assign them an id that you can use in a loop. See example below for some images and assignment of tags and touch listener, but you can you it for buttons or anything you want.  Now you can use loops to change things about each button:

```<code>for (int i = 0; i < 8; i++)
        {
        String bid = "WLButton"+i;
        int resID = getResources().getIdentifier(bid, "id", "com.head");
        wlbutt[i] = (ImageView) findViewById(resID);
        wlbutt[i].setTag(i);
        wlbutt[i].setOnTouchListener((OnTouchListener) WLListener);
        }
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I had the same situation.Just use Tag, and assign them an id that you can use in a loop. See example below for some images and assignment of tags and touch listener, but you can you it for buttons or anything you want.  Now you can use loops to change things about each button:

for (int i = 0; i < 8; i++)
        {
        String bid = "WLButton"+i;
        int resID = getResources().getIdentifier(bid, "id", "com.head");
        wlbutt[i] = (ImageView) findViewById(resID);
        wlbutt[i].setTag(i);
        wlbutt[i].setOnTouchListener((OnTouchListener) WLListener);
        }


问:
Valid Tree Traversal Base Cases and Pointers
I am currently transferring my C++ skills into python. Regarding tree traversals, I was wondering what typical base cases are used to detect the end of a branch, since python does not use pointers. Normally in C++, you would pass the next node in by reference and check if it is NULL. The code sample attached below works; however, are there any potential areas for these if-statements that may cause errors for other samples? I read on another answer that you can check if self.data = None, but I am not quite sure why this works (it did not work for my example). Thank you!</p>

```<code> def inOrder(self, list3):
        if self.left:
          self.left.inOrder(list3)
        list3.append(self.data)
        if self.right:
          self.right.inOrder(list3)
</code>```

答:
This is how you would define a Node in a tree.

```<code>class Node:
    def __init__(self,val):
        self.data = val
        self.left = None
        self.right = None
</code>```

Now let's declare a node temp with value 10.

```<code>temp = Node(10)
</code>```

Suppose you want to check whether temp is a leaf node or not, you would do something like,

```<code>if temp.left == None and temp.right == None:
    print('leaf node')
    return
</code>```

Now if you have traversed past the leaf node and you are checking whether a node actually exists or not, you would do :

```<code>temp2 = temp.left
if temp2 == None:
    #abc
</code>```

or

```<code>if not temp2:
    #abc
</code>```

Not sure why self.data = None would work in which case you are declaring a node but not assigning any data to it.

That would probably fail while checking the leaf node since we are checking whether there is a left or right node present. It's good to create a Node with a value.

Body:
I am currently transferring my C++ skills into python. Regarding tree traversals, I was wondering what typical base cases are used to detect the end of a branch, since python does not use pointers. Normally in C++, you would pass the next node in by reference and check if it is NULL. The code sample attached below works; however, are there any potential areas for these if-statements that may cause errors for other samples? I read on another answer that you can check if self.data = None, but I am not quite sure why this works (it did not work for my example). Thank you!

 def inOrder(self, list3):
        if self.left:
          self.left.inOrder(list3)
        list3.append(self.data)
        if self.right:
          self.right.inOrder(list3)

Body:
This is how you would define a Node in a tree.

class Node:
    def __init__(self,val):
        self.data = val
        self.left = None
        self.right = None

Now let's declare a node temp with value 10.

temp = Node(10)

Suppose you want to check whether temp is a leaf node or not, you would do something like,

if temp.left == None and temp.right == None:
    print('leaf node')
    return

Now if you have traversed past the leaf node and you are checking whether a node actually exists or not, you would do :

temp2 = temp.left
if temp2 == None:
    #abc

or

if not temp2:
    #abc

Not sure why self.data = None would work in which case you are declaring a node but not assigning any data to it.

That would probably fail while checking the leaf node since we are checking whether there is a left or right node present. It's good to create a Node with a value.


答:
The difference in implementation is just the phrase used, if you wanted to go according to the docs though, you should be using PUT for the first one and POST for the latter.
[https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.6][1]

PUT: www.example.com/user would create a new entity

PUT: www.example.com/user/{id} would update an existing entity

POST: www.example.com/user a data-accepting endpoint (such as batch updating where id's are defined in body and not in URI)

I hope this helps :)

Title: When use POST and PUT Method In Laravel?

Body:
I don't know exact difference between POST and PUT method.Some of the people said on internet that when you update record at time you have to use PUT method instead of POST, i don't know is it true??

form Internet if your website URL in POST method
1. www.example.com/user/{id}/update  :- PUT use
2. www.example.com/user/update       :- POST use
this is right or not ??


问:
JS for buttons, Jquery selector
I was browsing for examples for my page and ran across a weird JQuery selector. Can any of you explain how does it work, and can I use it to select ID's in HTML which have unique indexing.</p>

```<code>//The selector which I don't know how it works
//what is "^" exactly for?
"div[id^='myModal']"

//How Jquery for me dyanimcally creates HTML with Array elements and indexes ID's
 id=\"Modals_" +index+ "\"
</code>```

答: "div[id^='myModal']" it means that all the div's with starting of ID element with "myModal" for exmple myModal1, myModal2 etc/...............</p>

Title: JS for buttons, Jquery selector

Body:
I was browsing for examples for my page and ran across a weird JQuery selector. Can any of you explain how does it work, and can I use it to select ID's in HTML which have unique indexing.

//The selector which I don't know how it works
//what is "^" exactly for?
"div[id^='myModal']"

//How Jquery for me dyanimcally creates HTML with Array elements and indexes ID's
 id=\"Modals_" +index+ "\"


问:
JSON.parse() string that contains new line in a value
For reasons that can not be changed I have a string with a shitty piece of JSON with new lines like this:

```<code>{
    "description" : "- some text;
              - some more text;"
}
</code>```

I want to JSON.parse() it so it becomes usable. Of course, it fails when hitting the new line:

Unexpected token in JSON at position 156

How can I make this work?

答:
This is not the semi-colon, but the line-wrap is illegal. Escaped with \n this would be valid JSON:

```<code>{"description": "- some text;\n          - some more text;"}
</code>```

Body:
For reasons that can not be changed I have a string with a shitty piece of JSON with new lines like this:

{
    "description" : "- some text;
              - some more text;"
}

I want to JSON.parse() it so it becomes usable. Of course, it fails when hitting the new line:

Unexpected token in JSON at position 156

How can I make this work?

Body:
This is not the semi-colon, but the line-wrap is illegal. Escaped with \n this would be valid JSON:

{"description": "- some text;\n          - some more text;"}


问:
Azure DevOps, showing tasks instead of stories on my board
I would like to make a board for my team in Azure DevOps that shows only tasks and bugs and allows me to move the cards representing each task or bug between columns for new, active, or closed.

There are two boards that almost do what I want:

The sprint taskboard. But this groups tasks and bugs horizontally by their parent user story. I do not want that grouping

The 'board'. But the cards represent bugs and user stories, not tasks.

Other teams in my organisation get around this by using User Stories as tasks. None of their User Stories read 'as an X I want Y so that I can Z' they instead say things like 'optimize runtime of forest layer' which is a task, not a user story. Making that change (eschewing tasks and using user stories to represent tasks instead) enables them to use the board exactly as I would like to, but I am reluctant to get rid of real User Stories as they serve (I think) a useful purpose in reminding us why we are doing the child tasks related to each user story.

How can I configure a board in ADO DevOps that behaves like the current board but at the task instead of the user story level?

答:
How can I configure a board in ADO DevOps that behaves like the current board but at the task instead of the user story level?

The Boards and Backlogs are for Requirement backlog level work items which is the User Story in Agile process, and the Task work item type is actually the Iteration backlog level.

While the Bug is Iteration backlog like Task by default and can be configured as Requirement backlog which you can refer to Show bugs on backlogs and boards.

In summary, it's not possible to show Task work items directly in the Boards like the User Story work items since the Task is in a lower level.

However, you can show the Bug type work items directly in the Boards just like the User Story by editing the Working with bugs which you can find in the Boards - Settings, choose the first option:

In this case, you can see the Bugs as well as the User Story:


问:
How to implement a conditional fomula in Crystal Report
I have a table named tblRecovery with 4 column. ID, LStatus, Amount and RecoveredBy I created a formula to sum Amount Column where LStatus Column value is "WCL". I use following code.

It sum all value of Amount column without condition. I want to sum amount column if Lstatus Column value is "WCL". How can I do that?

```<code>if {tblRecovery.LStatus}='WCL' then sum({tblRecovery.Amount})
</code>```

答:
Crystal Reports formulas work on a per-record basis.

Your current formula shows the sum of tblRecovery.Amount on every single row where LStatus='WCL'.

To get the desired result, create a formula-field with following formula and the create a sum of it:

```<code>if {tblRecovery.LStatus}='WCL' then
    {tblRecovery.Amount}
else
    0
</code>```

Body:
I have a table named tblRecovery with 4 column. ID, LStatus, Amount and RecoveredBy I created a formula to sum Amount Column where LStatus Column value is "WCL". I use following code.

It sum all value of Amount column without condition. I want to sum amount column if Lstatus Column value is "WCL". How can I do that?

if {tblRecovery.LStatus}='WCL' then sum({tblRecovery.Amount})

Body:
Crystal Reports formulas work on a per-record basis.

Your current formula shows the sum of tblRecovery.Amount on every single row where LStatus='WCL'.

To get the desired result, create a formula-field with following formula and the create a sum of it:

if {tblRecovery.LStatus}='WCL' then
    {tblRecovery.Amount}
else
    0


问:
calculate checksum for a folder on windows and verify on linux
I have the following requirement:

Calculate one checksum (SHA1 preferred) from an entire folder. This has to be done on Windows.

Move this folder from a Windows to a Linux box.

Verify the entire folder against the hash value on the Linux box.

Any ideas are welcome!

答:
md5deep
http://linhost.info/2010/02/checksum-a-directory-with-md5deep/

It's done using MD5, but allows you to calculate hashes for sub-directories and is supposedly cross-platform.  It would not surprise me if there was a SHA version out there.

Alternate solution would be to do the transfer with rsync over SSH (install Cygwin on the Windows box).  Which will make sure that the destination matches the source.


问:
extract part of a filename python and insert into the MySQL DB
Want to extract the filename from a directory and insert it into MySQL DB.

with glob.glob could easily extract the full path and filename from the particular directory. I only need the 1st part of the filename. The part I want to omit is fixed, but the part I want to keep may change as it depends on the time stamp.

part of the code is like this:

```<code>for name in glob.glob(r'/home/PROJ/result/*fileinfo.csv'):
    print (name)
    filename = os.path.basename(name)
    print(filename)

    filetail = str("_fileinfo.csv")
    print(filetail)
</code>```

Print out shows as

```<code>/home/PROJ/result/Line01-200213_1625_fileinfo.csv
Line01-200213_1625_fileinfo.csv
_fileinfo.csv
/home/PROJ/result/Line01-200215_1619_fileinfo.csv
Line01-200215_1619_fileinfo.csv
_fileinfo.csv
</code>```

I just want the 'lineNo-YYMMDD_hhmm' part as a filename. Omit the '_fileinfo.csv' part from the filename and store it in a file. Then insert in DB.

答:
For extracting the part you want, you can strip out the filenames:</p>

```<code>for name in glob.glob(r'/home/PROJ/result/*fileinfo.csv'):
    file_prefix = os.path.basename(name)[:-(len('fileinfo.csv')+1)]
    print(file_prefix)
</code>```

Body:
Want to extract the filename from a directory and insert it into MySQL DB.

with glob.glob could easily extract the full path and filename from the particular directory. I only need the 1st part of the filename. The part I want to omit is fixed, but the part I want to keep may change as it depends on the time stamp.

part of the code is like this:

for name in glob.glob(r'/home/PROJ/result/*fileinfo.csv'):
    print (name)
    filename = os.path.basename(name)
    print(filename)

    filetail = str("_fileinfo.csv")
    print(filetail)

Print out shows as

/home/PROJ/result/Line01-200213_1625_fileinfo.csv
Line01-200213_1625_fileinfo.csv
_fileinfo.csv
/home/PROJ/result/Line01-200215_1619_fileinfo.csv
Line01-200215_1619_fileinfo.csv
_fileinfo.csv

I just want the 'lineNo-YYMMDD_hhmm' part as a filename. Omit the '_fileinfo.csv' part from the filename and store it in a file. Then insert in DB.

Body:
For extracting the part you want, you can strip out the filenames:

for name in glob.glob(r'/home/PROJ/result/*fileinfo.csv'):
    file_prefix = os.path.basename(name)[:-(len('fileinfo.csv')+1)]
    print(file_prefix)


问:
Creating a simple Python contact form
new to Python.

I am trying to make a contact form for my portfolio site using Python. The form has 4 input fields - first_name, last_name, email, and message. My website is hosted by hostgator.com.

I want the form when submitted to simply send me the info supplied in the 4 fields to my specified email.

After lots of searching I see a lot of Django tuts but I just want a simple form using Python.

Any help would be greatly appreciated! - Mike Rossi

```<code>#!/usr/bin/python

# Import modules from CGI handling
import cgi, cgitb, smtplib

cgitb.enable()

# Create instance of FieldStorage
form = cgi.FieldStorage()
print("")

# Get data from fields
first_name = form.getvalue("first_name")
last_name = form.getvalue("last_name")
email = form.getvalue("email")
message = form.getvalue("message")

to = "mike.jacob.rossi@gmail.com"
subject = "Comment from MikeTheDev.com"
mfrom msg['To']
to msg['Subject']
form['subject'].value

print("Thanks for contacting me! Get back to you soon,%s. ") % cgi.escape(first_name)
</code>```

答:
Due to the OP posting this 3 years ago, I came across this question in my attempt to set up a contact page on my portfolio website.
After coming across this question I found this link: https://code.tutsplus.com/tutorials/intro-to-flask-adding-a-contact-page--net-28982.
This should answer your question.</p>

Title: Creating a simple Python contact form

Body:
new to Python.

I am trying to make a contact form for my portfolio site using Python. The form has 4 input fields - first_name, last_name, email, and message. My website is hosted by hostgator.com.

I want the form when submitted to simply send me the info supplied in the 4 fields to my specified email.

After lots of searching I see a lot of Django tuts but I just want a simple form using Python.

Any help would be greatly appreciated! - Mike Rossi

#!/usr/bin/python

# Import modules from CGI handling
import cgi, cgitb, smtplib

cgitb.enable()

# Create instance of FieldStorage
form = cgi.FieldStorage()
print("")

# Get data from fields
first_name = form.getvalue("first_name")
last_name = form.getvalue("last_name")
email = form.getvalue("email")
message = form.getvalue("message")

to = "mike.jacob.rossi@gmail.com"
subject = "Comment from MikeTheDev.com"
mfrom msg['To']
to msg['Subject']
form['subject'].value

print("Thanks for contacting me! Get back to you soon,%s. ") % cgi.escape(first_name)


问:
Why Jython behaves inconsistently when tested with PyStone?
I've been playing recently with Jython and decided to do some quick and dirty benchmarking with pystone. In order to have a reference, I first tested cPython 2.6, with an increasing numbers of loops (I thought this may be relevant as Jython should start to profit from the JIT only after some time).

```<code>(richard garibaldi):/usr/local/src/pybench% python ~/tmp/pystone.py
Pystone(1.1) time for 50000 passes = 1.04
This machine benchmarks at 48076.9 pystones/second

(richard garibaldi):/usr/local/src/pybench% python ~/tmp/pystone.py 500000
Pystone(1.1) time for 500000 passes = 10.33
This machine benchmarks at 48402.7 pystones/second

(richard garibaldi):/usr/local/src/pybench% python ~/tmp/pystone.py 1000000
Pystone(1.1) time for 1000000 passes = 19.6
This machine benchmarks at 51020.4 pystones/second
</code>```

As you can see, cPython behaves consistently: the time it takes to complete the test increases linearly to the number of loops. Knowing this, I started testing Jython.

```<code>(richard garibaldi):/usr/local/src/pybench% jython ~/tmp/pystone.py
Pystone(1.1) time for 50000 passes = 2.29807
This machine benchmarks at 21757.4 pystones/second

(richard garibaldi):/usr/local/src/pybench% jython ~/tmp/pystone.py 500000
Pystone(1.1) time for 500000 passes = 10.931
This machine benchmarks at 45741.4 pystones/second

(richard garibaldi):/usr/local/src/pybench% jython ~/tmp/pystone.py 1000000
Pystone(1.1) time for 1000000 passes = 107.183
This machine benchmarks at 9329.86 pystones/second
</code>```

During the first run Jython runs rather lousily in comparison to its C brother. When increased the number of loops it started feeling better, coming close to cPython, like my initial hypothesis predicted. Note that the number of loops increased 10 times, but it took Jython only about 5 times longer to complete them. So, as you imagine, I was expecting that Jython would really rock in the final test. To my great disappointment, however, it did really bad: more than twice slower than in the initial run.

What are your hypotheses: why does Jython behave such an inconsistent manner? Could it be that GC is kicking in at some moment, and taking a lot of time? I've looked at PyStone's code and garbage collection doesn't seem to be turned off, but I would expect Java's GC to be at least as good as Python's... Do you think this slowing down is permanent, or it will go away at some point after increasing the number of loops? How shall Jython behave in a really long running processes?

EDIT: unfortunately, I get java.lang.OutOfMemoryError if I increase the number of loops to 2 million...

(Of course, Jython is still beta, so it should get better in the final release.)

I am using Jython 2.5b1 (trunk:5903:5905, Jan 9 2009, 16:01:29), Java(TM) SE Runtime Environment (build 1.6.0_07-b06-153) and Java HotSpot(TM) 64-Bit Server VM (build 1.6.0_07-b06-57, mixed mode) on MacOS X 10.5.

Thanks for your answers.

答:
my bench on a XP_Win32_PC :

```<code>C:\jython\jython2.5b1>bench "50000"

C:\jython\jython2.5b1>jython Lib\test\pystone.py "50000"
Pystone(1.1) time for 50000 passes = 1.73489
This machine benchmarks at 28820.2 pystones/second

C:\jython\jython2.5b1>bench "100000"

C:\jython\jython2.5b1>jython Lib\test\pystone.py "100000"
Pystone(1.1) time for 100000 passes = 3.36223
This machine benchmarks at 29742.2 pystones/second

C:\jython\jython2.5b1>bench "500000"

C:\jython\jython2.5b1>jython Lib\test\pystone.py "500000"
Pystone(1.1) time for 500000 passes = 15.8116
This machine benchmarks at 31622.3 pystones/second

C:\jython\jython2.5b1>bench "1000000"

C:\jython\jython2.5b1>jython Lib\test\pystone.py "1000000"
Pystone(1.1) time for 1000000 passes = 30.9763
This machine benchmarks at 32282.8 pystones/second

C:\jython\jython2.5b1>jython
Jython 2.5b1 (trunk:5903:5905, Jan 9 2009, 16:01:29)
[Java HotSpot(TM) Client VM (Sun Microsystems Inc.)] on java1.5.0_17
</code>```

It is not so fast, but ...

no "special effects"

Is it a java-vm 'problem' ?

Add a comment if you want further infos to my benchmarking on this old Win32-PC

OwnerDisplayName: Ryszard Szopa

Body:
I've been playing recently with Jython and decided to do some quick and dirty benchmarking with pystone. In order to have a reference, I first tested cPython 2.6, with an increasing numbers of loops (I thought this may be relevant as Jython should start to profit from the JIT only after some time).

(richard garibaldi):/usr/local/src/pybench% python ~/tmp/pystone.py
Pystone(1.1) time for 50000 passes = 1.04
This machine benchmarks at 48076.9 pystones/second

(richard garibaldi):/usr/local/src/pybench% python ~/tmp/pystone.py 500000
Pystone(1.1) time for 500000 passes = 10.33
This machine benchmarks at 48402.7 pystones/second

(richard garibaldi):/usr/local/src/pybench% python ~/tmp/pystone.py 1000000
Pystone(1.1) time for 1000000 passes = 19.6
This machine benchmarks at 51020.4 pystones/second

As you can see, cPython behaves consistently: the time it takes to complete the test increases linearly to the number of loops. Knowing this, I started testing Jython.

(richard garibaldi):/usr/local/src/pybench% jython ~/tmp/pystone.py
Pystone(1.1) time for 50000 passes = 2.29807
This machine benchmarks at 21757.4 pystones/second

(richard garibaldi):/usr/local/src/pybench% jython ~/tmp/pystone.py 500000
Pystone(1.1) time for 500000 passes = 10.931
This machine benchmarks at 45741.4 pystones/second

(richard garibaldi):/usr/local/src/pybench% jython ~/tmp/pystone.py 1000000
Pystone(1.1) time for 1000000 passes = 107.183
This machine benchmarks at 9329.86 pystones/second

During the first run Jython runs rather lousily in comparison to its C brother. When increased the number of loops it started feeling better, coming close to cPython, like my initial hypothesis predicted. Note that the number of loops increased 10 times, but it took Jython only about 5 times longer to complete them. So, as you imagine, I was expecting that Jython would really rock in the final test. To my great disappointment, however, it did really bad: more than twice slower than in the initial run.

What are your hypotheses: why does Jython behave such an inconsistent manner? Could it be that GC is kicking in at some moment, and taking a lot of time? I've looked at PyStone's code and garbage collection doesn't seem to be turned off, but I would expect Java's GC to be at least as good as Python's... Do you think this slowing down is permanent, or it will go away at some point after increasing the number of loops? How shall Jython behave in a really long running processes?

EDIT: unfortunately, I get java.lang.OutOfMemoryError if I increase the number of loops to 2 million...

(Of course, Jython is still beta, so it should get better in the final release.)

I am using Jython 2.5b1 (trunk:5903:5905, Jan 9 2009, 16:01:29), Java(TM) SE Runtime Environment (build 1.6.0_07-b06-153) and Java HotSpot(TM) 64-Bit Server VM (build 1.6.0_07-b06-57, mixed mode) on MacOS X 10.5.

Thanks for your answers.

Body:
my bench on a XP_Win32_PC :

C:\jython\jython2.5b1>bench "50000"

C:\jython\jython2.5b1>jython Lib\test\pystone.py "50000"
Pystone(1.1) time for 50000 passes = 1.73489
This machine benchmarks at 28820.2 pystones/second

C:\jython\jython2.5b1>bench "100000"

C:\jython\jython2.5b1>jython Lib\test\pystone.py "100000"
Pystone(1.1) time for 100000 passes = 3.36223
This machine benchmarks at 29742.2 pystones/second

C:\jython\jython2.5b1>bench "500000"

C:\jython\jython2.5b1>jython Lib\test\pystone.py "500000"
Pystone(1.1) time for 500000 passes = 15.8116
This machine benchmarks at 31622.3 pystones/second

C:\jython\jython2.5b1>bench "1000000"

C:\jython\jython2.5b1>jython Lib\test\pystone.py "1000000"
Pystone(1.1) time for 1000000 passes = 30.9763
This machine benchmarks at 32282.8 pystones/second

C:\jython\jython2.5b1>jython
Jython 2.5b1 (trunk:5903:5905, Jan 9 2009, 16:01:29)
[Java HotSpot(TM) Client VM (Sun Microsystems Inc.)] on java1.5.0_17

It is not so fast, but ...

no "special effects"

Is it a java-vm 'problem' ?

Add a comment if you want further infos to my benchmarking on this old Win32-PC

OwnerDisplayName: Blauohr


问:
How to integrate WhatsApp with rails application
How to integrate WhatsApp with rails application? or how to send a message using rails application.

Is there any gem or plugin available?

答:
You can use twilio for sending whatsapp messages -

https://www.twilio.com/whatsapp

They only problem is that they don't provide service for sending whatsapp messages in India as of today.

But you can send whatsapp messages in India using textlocal(third party service provider).
You can find documentation here -
https://api.textlocal.in/docs/send-whatsapp

You can use this gem as well -
https://github.com/getninjas/whatsapp

To use this gem, you would require to follow the documentation provided by facebook.
https://developers.facebook.com/docs/whatsapp/getting-started


问:
How to set up machine specifc sql scripts using Flyway and spring boot?
I need to set up Flyway such that certain sql scripts are run in UAT instances and certain sql scripts are run in production instances. How do I go about implementing this? Should I have two different sets of configuration files specific to each machine? Or should I use flyway.locations property to achieve this?

答:
You can use Spring-Profiles (see https://www.baeldung.com/spring-profiles) and define on each profile a other location.

Otherwise you can define an environment-variable (spring.flyway.location=${ENV_VAR:defaultPath}).

And the last option: Implement Flyway the "manual way". See https://flywaydb.org/documentation/api/hooks


问:
Bean is not formed for datasource in Spring MVC Project
I am facing error "Property datasource is required".

Below is the configuration in dao-beans xml.

```<code><bean id="Template" class="org.springframework.jndi.JndiObjectFactoryBean">
        <property name="jndiName" value="java:/comp/env/jdbc/TEMPLATES" />
    </bean>

<bean id="languageDao" class="com.test.daoImpl.LanguageDAOImpl"
        init-method="init">
        <property name="cspLanguageGet" value="csp_LANGUAGE_Get" />
    </bean>
</code>```

Class has the following configurations:

```<code>private DataSource Template;

    private SimpleJdbcCall languageGet;

    private String cspLanguageGet;

    @Autowired
    @Qualifier("Template")
    public void setTemplate(DataSource Template) {
        this.Template = Template;
    }

    @Required
    public void setCspLanguageGet(String cspLanguageGet) {
        this.cspLanguageGet = cspLanguageGet;
    }

    public void init() {
        this.languageGet = new SimpleJdbcCall(Template).withProcedureName(cspLanguageGet);
        this.languageGet.compile();
    }
</code>```

I tried with the many solutions which I found over but no luck.I can't use  since my java version is 1.8

Below is the error stack trace.

```<code>java.lang.IllegalArgumentException: Property 'dataSource' is required
        at org.springframework.jdbc.support.JdbcAccessor.afterPropertiesSet(JdbcAccessor.java:134)
        at org.springframework.jdbc.core.JdbcTemplate.<init>(JdbcTemplate.java:165)
        at org.springframework.jdbc.core.simple.AbstractJdbcCall.<init>(AbstractJdbcCall.java:87)
        at org.springframework.jdbc.core.simple.SimpleJdbcCall.<init>(SimpleJdbcCall.java:69)
        at com.aexp.travel.docdelivery.tcapp.daoImpl.LanguageDAOImpl.init(LanguageDAOImpl.java:56)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
</code>```

Context.xml deployed in tomcat has the following configuration:

```<code><Resource
    name="jdbc/TEMPLATES"
    auth="Container"
    type="javax.sql.DataSource"
    maxActive="100"
    maxIdle="30"
    maxWait="10000"
    driverClassName="net.sourceforge.jtds.jdbc.Driver"
    factory="org.apache.tomcat.jdbc.pool.DataSourceFactory"
    url="jdbc:jtds:sqlserver://gtwtdwdbsqlv001.gbt.gbtad.com:1433;databaseName=Template"
    username="Test"
    password="*******"
    />
</code>```

I am stuck in this from past 3 days.Not able to resolve this.Can anyone pls help me to understand where it is going wrong

答:
It depends which version of Spring you are using but You may include DataSoure bean as shown below

```<code><bean name="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
    <property name="driverClassName" value="org.h2.Driver" />
    <property name="url" value="jdbc:h2:file:C:/temp/test" />
    <property name="username" value="sa" />
    <property name="password" value="" />
    <property name="initialSize" value="2" />
    <property name="maxActive" value="5" />
</bean>
</code>```

OR

```<code>@Bean
public DataSource getDataSource() {
  DataSourceBuilder dataSourceBuilder = DataSourceBuilder.create();
  dataSourceBuilder.driverClassName("org.h2.Driver");
  dataSourceBuilder.url("jdbc:h2:file:C:/temp/test");
  dataSourceBuilder.username("sa");
  dataSourceBuilder.password("");
  return dataSourceBuilder.build();
}
</code>```

Body:
I am facing error "Property datasource is required".

Below is the configuration in dao-beans xml.

<bean id="Template" class="org.springframework.jndi.JndiObjectFactoryBean">
        <property name="jndiName" value="java:/comp/env/jdbc/TEMPLATES" />
    </bean>

<bean id="languageDao" class="com.test.daoImpl.LanguageDAOImpl"
        init-method="init">
        <property name="cspLanguageGet" value="csp_LANGUAGE_Get" />
    </bean>

Class has the following configurations:

private DataSource Template;

    private SimpleJdbcCall languageGet;

    private String cspLanguageGet;

    @Autowired
    @Qualifier("Template")
    public void setTemplate(DataSource Template) {
        this.Template = Template;
    }

    @Required
    public void setCspLanguageGet(String cspLanguageGet) {
        this.cspLanguageGet = cspLanguageGet;
    }

    public void init() {
        this.languageGet = new SimpleJdbcCall(Template).withProcedureName(cspLanguageGet);
        this.languageGet.compile();
    }

I tried with the many solutions which I found over but no luck.I can't use  since my java version is 1.8

Below is the error stack trace.

java.lang.IllegalArgumentException: Property 'dataSource' is required
        at org.springframework.jdbc.support.JdbcAccessor.afterPropertiesSet(JdbcAccessor.java:134)
        at org.springframework.jdbc.core.JdbcTemplate.<init>(JdbcTemplate.java:165)
        at org.springframework.jdbc.core.simple.AbstractJdbcCall.<init>(AbstractJdbcCall.java:87)
        at org.springframework.jdbc.core.simple.SimpleJdbcCall.<init>(SimpleJdbcCall.java:69)
        at com.aexp.travel.docdelivery.tcapp.daoImpl.LanguageDAOImpl.init(LanguageDAOImpl.java:56)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)

Context.xml deployed in tomcat has the following configuration:

<Resource
    name="jdbc/TEMPLATES"
    auth="Container"
    type="javax.sql.DataSource"
    maxActive="100"
    maxIdle="30"
    maxWait="10000"
    driverClassName="net.sourceforge.jtds.jdbc.Driver"
    factory="org.apache.tomcat.jdbc.pool.DataSourceFactory"
    url="jdbc:jtds:sqlserver://gtwtdwdbsqlv001.gbt.gbtad.com:1433;databaseName=Template"
    username="Test"
    password="*******"
    />

I am stuck in this from past 3 days.Not able to resolve this.Can anyone pls help me to understand where it is going wrong

Body:
It depends which version of Spring you are using but You may include DataSoure bean as shown below

<bean name="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
    <property name="driverClassName" value="org.h2.Driver" />
    <property name="url" value="jdbc:h2:file:C:/temp/test" />
    <property name="username" value="sa" />
    <property name="password" value="" />
    <property name="initialSize" value="2" />
    <property name="maxActive" value="5" />
</bean>

OR

@Bean
public DataSource getDataSource() {
  DataSourceBuilder dataSourceBuilder = DataSourceBuilder.create();
  dataSourceBuilder.driverClassName("org.h2.Driver");
  dataSourceBuilder.url("jdbc:h2:file:C:/temp/test");
  dataSourceBuilder.username("sa");
  dataSourceBuilder.password("");
  return dataSourceBuilder.build();
}


问:
What is the function of add_custom_target in CMake?
From the CMake Cookbook, I see that we can use the command add_custom_command and add_custom_target to run a custom command at build time. There is a toy example that I want to extract compressed files in subdirectory and link it to the final executable files. We have two CMakeLists.txt files and the following one is in the subdirectory.

```<code>find_package(BLAS REQUIRED)
find_package(LAPACK REQUIRED)

set(MATH_SRCS
  ${CMAKE_CURRENT_BINARY_DIR}/wrap_BLAS_LAPACK/CxxBLAS.cpp
  ${CMAKE_CURRENT_BINARY_DIR}/wrap_BLAS_LAPACK/CxxLAPACK.cpp
  ${CMAKE_CURRENT_BINARY_DIR}/wrap_BLAS_LAPACK/CxxBLAS.hpp
  ${CMAKE_CURRENT_BINARY_DIR}/wrap_BLAS_LAPACK/CxxLAPACK.hpp
  )

add_custom_target(BLAS_LAPACK_wrappers
  WORKING_DIRECTORY
    ${CMAKE_CURRENT_BINARY_DIR}
  DEPENDS
    ${MATH_SRCS}
  COMMENT
    "Intermediate BLAS_LAPACK_wrappers target"
  VERBATIM
  )

add_custom_command(
  OUTPUT
    ${MATH_SRCS}
  COMMAND
    ${CMAKE_COMMAND} -E tar xzf ${CMAKE_CURRENT_SOURCE_DIR}/wrap_BLAS_LAPACK.tar.gz
  WORKING_DIRECTORY
    ${CMAKE_CURRENT_BINARY_DIR}
  DEPENDS
    ${CMAKE_CURRENT_SOURCE_DIR}/wrap_BLAS_LAPACK.tar.gz
  COMMENT
    "Unpacking C++ wrappers for BLAS/LAPACK"
  )

add_library(math "")

target_sources(math
  PRIVATE
    ${MATH_SRCS}
  )

target_include_directories(math
  INTERFACE
    ${CMAKE_CURRENT_BINARY_DIR}/wrap_BLAS_LAPACK
  )

# BLAS_LIBRARIES are included in LAPACK_LIBRARIES
target_link_libraries(math
  PUBLIC
    ${LAPACK_LIBRARIES}
  )
</code>```

The following CMakeLists.txt is in the main directory.

```<code>cmake_minimum_required(VERSION 3.5 FATAL_ERROR)

# Fortran needed to discover LAPACK with some compilers
project(recipe-04 LANGUAGES CXX Fortran)

set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_EXTENSIONS OFF)
set(CMAKE_CXX_STANDARD_REQUIRED ON)

add_subdirectory(deps)

add_executable(linear-algebra linear-algebra.cpp)

target_link_libraries(linear-algebra
  PRIVATE
    math
  )
</code>```

I do not know why we need the add_custom_target in this example.

答:
The command add_custom_command cannot be executed without generating any target. That is why we need the custom target to run this command. What's more, it can only execute at the configure time. If we want to run the command after we configure the CMakeLists.txt file, we can create a custom target to achieve that as the following.

```<code>add_custom_target(BLAS_LAPACK_wrappers
  WORKING_DIRECTORY
    ${CMAKE_CURRENT_BINARY_DIR}
  DEPENDS
    ${MATH_SRCS}
  COMMENT
    "Intermediate BLAS_LAPACK_wrappers target"
  VERBATIM
  )

add_custom_command(
  OUTPUT
    ${MATH_SRCS}
  COMMAND
    ${CMAKE_COMMAND} -E tar xzf ${CMAKE_CURRENT_SOURCE_DIR}/wrap_BLAS_LAPACK.tar.gz
  WORKING_DIRECTORY
    ${CMAKE_CURRENT_BINARY_DIR}
  DEPENDS
    ${CMAKE_CURRENT_SOURCE_DIR}/wrap_BLAS_LAPACK.tar.gz
  COMMENT
    "Unpacking C++ wrappers for BLAS/LAPACK"
  )
</code>```

After we configure the CMakeLists.txt file, we use the Cmake --build . --target=BLAS_LAPACK_wrappers the execute it at the build time.

Body:
From the CMake Cookbook, I see that we can use the command add_custom_command and add_custom_target to run a custom command at build time. There is a toy example that I want to extract compressed files in subdirectory and link it to the final executable files. We have two CMakeLists.txt files and the following one is in the subdirectory.

find_package(BLAS REQUIRED)
find_package(LAPACK REQUIRED)

set(MATH_SRCS
  ${CMAKE_CURRENT_BINARY_DIR}/wrap_BLAS_LAPACK/CxxBLAS.cpp
  ${CMAKE_CURRENT_BINARY_DIR}/wrap_BLAS_LAPACK/CxxLAPACK.cpp
  ${CMAKE_CURRENT_BINARY_DIR}/wrap_BLAS_LAPACK/CxxBLAS.hpp
  ${CMAKE_CURRENT_BINARY_DIR}/wrap_BLAS_LAPACK/CxxLAPACK.hpp
  )

add_custom_target(BLAS_LAPACK_wrappers
  WORKING_DIRECTORY
    ${CMAKE_CURRENT_BINARY_DIR}
  DEPENDS
    ${MATH_SRCS}
  COMMENT
    "Intermediate BLAS_LAPACK_wrappers target"
  VERBATIM
  )

add_custom_command(
  OUTPUT
    ${MATH_SRCS}
  COMMAND
    ${CMAKE_COMMAND} -E tar xzf ${CMAKE_CURRENT_SOURCE_DIR}/wrap_BLAS_LAPACK.tar.gz
  WORKING_DIRECTORY
    ${CMAKE_CURRENT_BINARY_DIR}
  DEPENDS
    ${CMAKE_CURRENT_SOURCE_DIR}/wrap_BLAS_LAPACK.tar.gz
  COMMENT
    "Unpacking C++ wrappers for BLAS/LAPACK"
  )

add_library(math "")

target_sources(math
  PRIVATE
    ${MATH_SRCS}
  )

target_include_directories(math
  INTERFACE
    ${CMAKE_CURRENT_BINARY_DIR}/wrap_BLAS_LAPACK
  )

# BLAS_LIBRARIES are included in LAPACK_LIBRARIES
target_link_libraries(math
  PUBLIC
    ${LAPACK_LIBRARIES}
  )

The following CMakeLists.txt is in the main directory.

cmake_minimum_required(VERSION 3.5 FATAL_ERROR)

# Fortran needed to discover LAPACK with some compilers
project(recipe-04 LANGUAGES CXX Fortran)

set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_EXTENSIONS OFF)
set(CMAKE_CXX_STANDARD_REQUIRED ON)

add_subdirectory(deps)

add_executable(linear-algebra linear-algebra.cpp)

target_link_libraries(linear-algebra
  PRIVATE
    math
  )

I do not know why we need the add_custom_target in this example.

Body:
The command add_custom_command cannot be executed without generating any target. That is why we need the custom target to run this command. What's more, it can only execute at the configure time. If we want to run the command after we configure the CMakeLists.txt file, we can create a custom target to achieve that as the following.

add_custom_target(BLAS_LAPACK_wrappers
  WORKING_DIRECTORY
    ${CMAKE_CURRENT_BINARY_DIR}
  DEPENDS
    ${MATH_SRCS}
  COMMENT
    "Intermediate BLAS_LAPACK_wrappers target"
  VERBATIM
  )

add_custom_command(
  OUTPUT
    ${MATH_SRCS}
  COMMAND
    ${CMAKE_COMMAND} -E tar xzf ${CMAKE_CURRENT_SOURCE_DIR}/wrap_BLAS_LAPACK.tar.gz
  WORKING_DIRECTORY
    ${CMAKE_CURRENT_BINARY_DIR}
  DEPENDS
    ${CMAKE_CURRENT_SOURCE_DIR}/wrap_BLAS_LAPACK.tar.gz
  COMMENT
    "Unpacking C++ wrappers for BLAS/LAPACK"
  )

After we configure the CMakeLists.txt file, we use the Cmake --build . --target=BLAS_LAPACK_wrappers the execute it at the build time.


问:
How to find and replace multiple words from paragraph with identified next word in python?
I want to replace and tag multiple words from a paragraph with their next word.

```<code>paragraph = "Python is the most powerful language [YES] yes. my sex is [NO] male [YES] female"
</code>```

I want to replace the keys [YES] and [NO] with their next word like below.

```<code>paragraph = "Python is the most powerful language [YES]yes[/YES]. my sex is [NO]male[/NO] [YES]female[/YES]"
</code>```

答:
You can use Regular expressions to achieve the result:

Here is the code:

```<code>import re

paragraph = "Python is the most powerful language [YES] yes. my sex is [NO] male [YES] female"

paragraph = re.sub(r"\[(.*?)\]\s\b(\w+)\b", r"[\1]\2[/\1]", paragraph)
</code>```

Output is:

```<code>"Python is the most powerful language [YES]yes[/YES]. my sex is [NO]male[/NO] [YES]female[/YES]"
</code>```

Hope it helps you!

Body:
I want to replace and tag multiple words from a paragraph with their next word.

paragraph = "Python is the most powerful language [YES] yes. my sex is [NO] male [YES] female"

I want to replace the keys [YES] and [NO] with their next word like below.

paragraph = "Python is the most powerful language [YES]yes[/YES]. my sex is [NO]male[/NO] [YES]female[/YES]"

Body:
You can use Regular expressions to achieve the result:

Here is the code:

import re

paragraph = "Python is the most powerful language [YES] yes. my sex is [NO] male [YES] female"

paragraph = re.sub(r"\[(.*?)\]\s\b(\w+)\b", r"[\1]\2[/\1]", paragraph)

Output is:

"Python is the most powerful language [YES]yes[/YES]. my sex is [NO]male[/NO] [YES]female[/YES]"

Hope it helps you!


问:
Newbie Question About Running a Process On a New Thread
So far my apps have been pretty simple, but now I'm finding I need to run a process on a separate thread, so this is an xCode 101 question asking how I do that.

I want to run a process that runs when the app launches, so I want to execute it in AppDelegate.applicationDidFinishLaunching.

From what I've read, I think this is all I need to do, but please correct me if I'm wrong.

```<code>// *** AppDelegate.m ****

- (void)applicationDidFinishLaunching:(UIApplication *)application {

    [NSThread detachNewThreadSelector:@selector([XMLParser parseXML:])
        toTarget:self
        withObject:requestStr];

}

// *** XMLParser.m ***

-(void)parseXML {

    // Dunno why NSAutoreleasePool is needed but apparently it is

    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    // . . . my code

    [pool release];

}

}
</code>```

答: I have not used the method you describe, but have used NSOpertaions. It supports but concurrent and non-concurrent operations and is easy to use.</p>

Body:
So far my apps have been pretty simple, but now I'm finding I need to run a process on a separate thread, so this is an xCode 101 question asking how I do that.

I want to run a process that runs when the app launches, so I want to execute it in AppDelegate.applicationDidFinishLaunching.

From what I've read, I think this is all I need to do, but please correct me if I'm wrong.

// *** AppDelegate.m ****

- (void)applicationDidFinishLaunching:(UIApplication *)application {

    [NSThread detachNewThreadSelector:@selector([XMLParser parseXML:])
        toTarget:self
        withObject:requestStr];

}

// *** XMLParser.m ***

-(void)parseXML {

    // Dunno why NSAutoreleasePool is needed but apparently it is

    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    // . . . my code

    [pool release];

}

}


问:
Redirecting http to https in Apache2 and my domain build is in var/www/html
I have uploaded build in var/www/html and ssl is configure and trying to redirect http to https but it is not redirecting. I have checked for .htaccess file but it is not working.</p>

答:
Include this in htaccess to redirect http to https

```<code>RewriteCond %{HTTPS} !on
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}
</code>```

Include this in htaccess to redirect www to non-www

```<code>RewriteCond %{HTTP_HOST} www.yourdomain.com
RewriteRule (.*) https://yourdomain.com/$1 [R=301,L]
</code>```

Body:
Include this in htaccess to redirect http to https

RewriteCond %{HTTPS} !on
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}

Include this in htaccess to redirect www to non-www

RewriteCond %{HTTP_HOST} www.yourdomain.com
RewriteRule (.*) https://yourdomain.com/$1 [R=301,L]


问:
How to Create a Table from JSON objects?
I am trying to make a table from json objects, actually i have  JSON objects in large quantity. But first i am trying to create tabe for few JSON objects, if this will go right , i willl implement this method later on.

This is what i tried so Far.

```<code>   var  attributes =

     [

      {

        "name": "Asset #",

        "display_name": "Asset #",

        "key": "header2",

        "values": {

          "MSSBL": "4-194169767930##1-2H77NZSQ",

          "SNOW": "4-194169767930##1-2H77NZSQ"},

        "type": "header",

        "data_type": "Text",

        "editable": "N"

      },

      {

        "name": "Serial Number",

        "display_name": "Serial Number",

        "key": "header3",

        "values": {

          "MSSBL": "21256112##1-2H77NZSQ",

          "SNOW": "NA##1-2H77NZSQ"},

        "type": "header",

        "data_type": "Text",

        "editable": "N"

      },

      {

        "name": "ACCOUNT NUMBER",

        "display_name": "ACCOUNT NUMBER",

        "key": "header6",

        "values": { "MSSBL": "532649##1-2H77NZSQ",
          "SNOW": "NA##1-2H77NZSQ"},

        "type": "header",

        "data_type": "Text",

        "editable": "N"

      }
    ]
           var key = [];

           document.write("<table border==\"1\"><tr>");
           for (key in attributes[0]) {
           document.write('<td>' + '<b>' + key + '</b>' + '</td>');
            }

            document.write("</tr>");
            for (var i = 0; i < attributes.length; i++) {
            document.write('<tr>');
            for (key in attributes[i]) {
             document.write('<td>' + attributes[i][key] + '</td>');
             }
            document.write('</tr>');
              }
            document.write("</table>");
</code>```

Actually i am facing a issue when, i am trying  to add Values inside the table if I remove values then the table is visible in output otherwise no output
'

```<code>           "values": {
        "MSSBL": "4-194169767930##1-2H77NZSQ",
          "SNOW": "4-194169767930##1-2H77NZSQ"},
</code>```

答:
Your trouble came from this loop:

```<code>for (var j = 0; j < col.length; j++) {
    // ...
}
</code>```

You can check when col[j] is values to get MSSBL or SNOW value:

```<code>for (var j = 0; j < col.length; j++) {
    var tabCell = tr.insertCell(-1);

    if (col[j] === 'values') {
        var item = attributes[i][col[j]];

        console.log('MSSBL:', item.MSSBL);
        console.log('SNOW:', item.SNOW);

        // try to append MSSBL value:
        tabCell.innerHTML = item.MSSBL;
    } else {
        // other properties
        tabCell.innerHTML = attributes[i][col[j]];
    }
}
</code>```

Update: In your updated code, you can edit it inside the loop:

```<code>for (key in attributes[i]) {
    if (key === 'values') {
        document.write('<td>' + attributes[i][key]['MSSBL'] + '</td>');
    } else {
        document.write('<td>' + attributes[i][key] + '</td>');
    }
}
</code>```

var  attributes =

     [

      {

        "name": "Asset #",

        "display_name": "Asset #",

        "key": "header2",

        "values": {

          "MSSBL": "4-194169767930##1-2H77NZSQ",

          "SNOW": "4-194169767930##1-2H77NZSQ"},

        "type": "header",

        "data_type": "Text",

        "editable": "N"

      },

      {

        "name": "Serial Number",

        "display_name": "Serial Number",

        "key": "header3",

        "values": {

          "MSSBL": "21256112##1-2H77NZSQ",

          "SNOW": "NA##1-2H77NZSQ"},

        "type": "header",

        "data_type": "Text",

        "editable": "N"

      },

      {

        "name": "ACCOUNT NUMBER",

        "display_name": "ACCOUNT NUMBER",

        "key": "header6",

        "values": { "MSSBL": "532649##1-2H77NZSQ",
          "SNOW": "NA##1-2H77NZSQ"},

        "type": "header",

        "data_type": "Text",

        "editable": "N"

      }
    ]
           var key = [];

           document.write("

");
           for (key in attributes[0]) {
           document.write('' + '' + key + '' + '	');
            }

            document.write("
");
            for (var i = 0; i < attributes.length; i++) {
            document.write('
');
            for (key in attributes[i]) {

              if (key === 'values') {
                 document.write('' + attributes[i][key]['MSSBL'] + '	');
              } else {
                 document.write('' + attributes[i][key] + '	');
              }

             }
            document.write('
');
              }
            document.write("
");```

Body:
I am trying to make a table from json objects, actually i have  JSON objects in large quantity. But first i am trying to create tabe for few JSON objects, if this will go right , i willl implement this method later on.

This is what i tried so Far.

   var  attributes =

     [

      {

        "name": "Asset #",

        "display_name": "Asset #",

        "key": "header2",

        "values": {

          "MSSBL": "4-194169767930##1-2H77NZSQ",

          "SNOW": "4-194169767930##1-2H77NZSQ"},

        "type": "header",

        "data_type": "Text",

        "editable": "N"

      },

      {

        "name": "Serial Number",

        "display_name": "Serial Number",

        "key": "header3",

        "values": {

          "MSSBL": "21256112##1-2H77NZSQ",

          "SNOW": "NA##1-2H77NZSQ"},

        "type": "header",

        "data_type": "Text",

        "editable": "N"

      },

      {

        "name": "ACCOUNT NUMBER",

        "display_name": "ACCOUNT NUMBER",

        "key": "header6",

        "values": { "MSSBL": "532649##1-2H77NZSQ",
          "SNOW": "NA##1-2H77NZSQ"},

        "type": "header",

        "data_type": "Text",

        "editable": "N"

      }
    ]
           var key = [];

           document.write("

");
           for (key in attributes[0]) {
           document.write('' + '' + key + '' + '	');
            }

            document.write("
");
            for (var i = 0; i < attributes.length; i++) {
            document.write('
');
            for (key in attributes[i]) {
             document.write('' + attributes[i][key] + '	');
             }
            document.write('
');
              }
            document.write("
");

Actually i am facing a issue when, i am trying  to add Values inside the table if I remove values then the table is visible in output otherwise no output
'

           "values": {
        "MSSBL": "4-194169767930##1-2H77NZSQ",
          "SNOW": "4-194169767930##1-2H77NZSQ"},

Body:
Your trouble came from this loop:

for (var j = 0; j < col.length; j++) {
    // ...
}

You can check when col[j] is values to get MSSBL or SNOW value:

for (var j = 0; j < col.length; j++) {
    var tabCell = tr.insertCell(-1);

    if (col[j] === 'values') {
        var item = attributes[i][col[j]];

        console.log('MSSBL:', item.MSSBL);
        console.log('SNOW:', item.SNOW);

        // try to append MSSBL value:
        tabCell.innerHTML = item.MSSBL;
    } else {
        // other properties
        tabCell.innerHTML = attributes[i][col[j]];
    }
}

Update: In your updated code, you can edit it inside the loop:

for (key in attributes[i]) {
    if (key === 'values') {
        document.write('<td>' + attributes[i][key]['MSSBL'] + '</td>');
    } else {
        document.write('<td>' + attributes[i][key] + '</td>');
    }
}

var  attributes =

     [

      {

        "name": "Asset #",

        "display_name": "Asset #",

        "key": "header2",

        "values": {

          "MSSBL": "4-194169767930##1-2H77NZSQ",

          "SNOW": "4-194169767930##1-2H77NZSQ"},

        "type": "header",

        "data_type": "Text",

        "editable": "N"

      },

      {

        "name": "Serial Number",

        "display_name": "Serial Number",

        "key": "header3",

        "values": {

          "MSSBL": "21256112##1-2H77NZSQ",

          "SNOW": "NA##1-2H77NZSQ"},

        "type": "header",

        "data_type": "Text",

        "editable": "N"

      },

      {

        "name": "ACCOUNT NUMBER",

        "display_name": "ACCOUNT NUMBER",

        "key": "header6",

        "values": { "MSSBL": "532649##1-2H77NZSQ",
          "SNOW": "NA##1-2H77NZSQ"},

        "type": "header",

        "data_type": "Text",

        "editable": "N"

      }
    ]
           var key = [];

           document.write("<table border==\"1\"><tr>");
           for (key in attributes[0]) {
           document.write('<td>' + '<b>' + key + '</b>' + '</td>');
            }

            document.write("</tr>");
            for (var i = 0; i < attributes.length; i++) {
            document.write('<tr>');
            for (key in attributes[i]) {

              if (key === 'values') {
                 document.write('<td>' + attributes[i][key]['MSSBL'] + '</td>');
              } else {
                 document.write('<td>' + attributes[i][key] + '</td>');
              }

             }
            document.write('</tr>');
              }
            document.write("</table>");


问:
Array of JavaScript arrow functions
I'm implementing the card game Hearts in JavaScript, and one of the core elements of the game is that you can pass your cards to other players. My game has strictly 4 players, no more, no less.

The passing order goes left, right, straight ahead, then no passing. Therefore, P1 would pass to P2, P4, P3, and then pass to nobody. The cycle loops until the game is over.

I am trying to implement this logic via arrow functions, however, it is not working. What I am trying to do is print out the player, and the player that they should pass to, based on a given index.

Here is my code, I hope it is clear what I am trying to do.

const players = [1, 2, 3, 4];
const passingOrder = 2;
const passCards = [
  i => (i + 1) % 4, //pass left
  i => (i - 1 + 4) % 4, //pass right
  i => (i + 2) % 4, //pass straight
  i => i //pass to ones self
];

players.forEach((player, index) => {
  console.log(player + "passes to " + passCards[passingOrder](index))
})```

答:
I would go a simple solution, each player should remember his passing order, if he can't, he should not join the game.

class Player {
  constructor(id, passOrder, name = 'Anounymous') {
    this.id = id
    this.name = name
    this.passOrder = passOrder
  }
}

let players = [
  new Player(1, [2, 4, 3], 'Alex'),
  new Player(2, [3, 1, 4], 'Billy'),
  new Player(3, [4, 2, 1]),
  new Player(4, [1, 3, 2], 'Tom')
]

players.forEach((p, i) => {
  console.log(`#${i+1} Player ${p.name} pass to `)
  p.passOrder.forEach(np => {
    console.log(`    #${np} player ${players[np-1].name},`)
  })
  console.log('-------------------')
})```

Title: Array of JavaScript arrow functions


问:
CodeIgniter admin
I am looking to create an admin side for my website, which is built in CodeIgniter. It will mainly manage content and upload portfolio pieces, etc... I have setup CodeExtinguisher as my admin right now. As of recently, this is a deprecated technology, no longer supported by JTaby(the author). I find it very useful and accomplishes a lot, most of what I want.

But it does have its limitations. It is table specific. Meaning that it generates data for a single table at a time. I am running into foreign key problems. I need to access data across tables but an not able to. Its how CodeExtinguisher builds it's queries.

This is more than question I am getting at. "How can I use CodeExtinguisher to query across multiple tables?" I need to access user_id from user table to insert id for foreign key constraint

Thanks for all the help guys.

Regards,
-David

答:
So, you can write code to get values form multiple tables like this

To get value of userid

```<code>    $this->db->select('userid');
    $this->db->insert('userTable', $data);

    $userid=$data[0][]
    $row = $query->row();
    $userid = $row->userid;
</code>```

To insert

```<code>    $data = array(
     'title' => 'My title' ,
     'name' => 'My Name' ,
     'userid' => $userid

    );

    $this->db->insert('mytable', $data);
</code>```

Also there is always option of writing your own query but I will not recommend it for simple cases.

Title: CodeIgniter admin

Body:
So, you can write code to get values form multiple tables like this

To get value of userid

    $this->db->select('userid');
    $this->db->insert('userTable', $data);

    $userid=$data[0][]
    $row = $query->row();
    $userid = $row->userid;

To insert

    $data = array(
     'title' => 'My title' ,
     'name' => 'My Name' ,
     'userid' => $userid

    );

    $this->db->insert('mytable', $data);

Also there is always option of writing your own query but I will not recommend it for simple cases.


问:
JS for buttons, Jquery selector
I was browsing for examples for my page and ran across a weird JQuery selector. Can any of you explain how does it work, and can I use it to select ID's in HTML which have unique indexing.</p>

```<code>//The selector which I don't know how it works
//what is "^" exactly for?
"div[id^='myModal']"

//How Jquery for me dyanimcally creates HTML with Array elements and indexes ID's
 id=\"Modals_" +index+ "\"
</code>```

答:
a[href^="https"]    this mean is Selects every  element whose href attribute value begins with "https"
 you can find meaning of selector in this link
https://www.w3schools.com/cssref/css_selectors.asp

about id=\"Modals_" +index+ "\"index is variable and you can use this for ID like this code

```<code>ID="Modals_"+index
$("p").attr("id",ID)
</code>```

Title: JS for buttons, Jquery selector

Body:
I was browsing for examples for my page and ran across a weird JQuery selector. Can any of you explain how does it work, and can I use it to select ID's in HTML which have unique indexing.

//The selector which I don't know how it works
//what is "^" exactly for?
"div[id^='myModal']"

//How Jquery for me dyanimcally creates HTML with Array elements and indexes ID's
 id=\"Modals_" +index+ "\"

Body:
a[href^="https"]    this mean is Selects every  element whose href attribute value begins with "https"
 you can find meaning of selector in this link
https://www.w3schools.com/cssref/css_selectors.asp

about id=\"Modals_" +index+ "\"index is variable and you can use this for ID like this code

ID="Modals_"+index
$("p").attr("id",ID)


问:
Using () (and other zero-sized types) in FFI
What's the equivalent of () (or any other zero-sized type) when doing FFI in Rust? Specifically, I'm curious what the most reasonable equivalent of () as a function argument when writing an extern "C" function.

My understanding is that zero-sized types are not valid in C, but Rust seems to allow them in extern "C" functions, for example:

#[no_mangle]
pub extern "C" fn test_ffi(input: ()) -> () {
}
```

In this case, returning () is the same as declaring a void function in C#. However, it's not clear to me how you would declare the input argument when generating the binding from C. I was under the impression that ZSTs aren't representable in C, and so shouldn't be FFI-safe. It seems like the nomicon confirms this, saying:

And to avoid warning around using () in FFI, we instead use an empty array ([u8; 0]), which works just as well as an empty type but is FFI-compatible.

Which seems to imply that () isn't FFI-compatible, but that [u8; 0] is (even though I'd expect it to also be zero-size)?

答:
There is no equivalent to () in C. Some could argue void is equivalent but that's actually not the case.  Of course they have similarities, in most cases they are interchangeable like you said: pub extern "C" fn test_ffi() -> () will correctly be interpreted as void test_ffi(void). (NB: here void inside the parameter list means the function takes no arguments so it is not an empty type).

You can think of void as nothing, but is () nothing? No, it's an empty tuple, while void is actually just nothing.

I was under the impression that ZSTs aren't representable in C, and so shouldn't be FFI-safe.

No, they are not representable in C: pub extern "C" fn test_ffi(input: (), foo: i32) -> () here is unclear what the Rust compiler should understand because void test_ffi(void, int32_t foo); is invalid in C.

Nomicon uses an empty array to make types opaque. I would not recommend that but it could be okay for this specific use case. Opaque types in C are evil anyway. Note that empty arrays are illegal in C so they should only be used on the Rust side.

I would advise to never use any zero sized type in any FFI.

Body:
What's the equivalent of () (or any other zero-sized type) when doing FFI in Rust? Specifically, I'm curious what the most reasonable equivalent of () as a function argument when writing an extern "C" function.

My understanding is that zero-sized types are not valid in C, but Rust seems to allow them in extern "C" functions, for example:

#[no_mangle]
pub extern "C" fn test_ffi(input: ()) -> () {
}

In this case, returning () is the same as declaring a void function in C#. However, it's not clear to me how you would declare the input argument when generating the binding from C. I was under the impression that ZSTs aren't representable in C, and so shouldn't be FFI-safe. It seems like the nomicon confirms this, saying:

And to avoid warning around using () in FFI, we instead use an empty array ([u8; 0]), which works just as well as an empty type but is FFI-compatible.

Which seems to imply that () isn't FFI-compatible, but that [u8; 0] is (even though I'd expect it to also be zero-size)?