问:
Mouse scroll wheel with selenium webdriver, on element without scrollbar?
I'm trying to drive part of a web map akin to Google Maps, where zoom in/out is done by scrolling while moused over. Ideally, I'd like to be able to do something like this:

```<code>someElement.scroll(-50)
</code>```

The closest methods I saw in the documentation were click and send_keys, but neither of those do scrolling. I've also tried sending scrolls to the page via Javascript, e.g. driver.execute_script("scroll(0,-50)") This doesn't seem to do anything though.

How can I do this?

答: You can try it with PyRobot class,first focus on the points on which you want to perform zoom in/out and then use PyRobot class to perform zoom in/out operation via keyboard keys.    </p>

Body:
I'm trying to drive part of a web map akin to Google Maps, where zoom in/out is done by scrolling while moused over. Ideally, I'd like to be able to do something like this:

someElement.scroll(-50)

The closest methods I saw in the documentation were click and send_keys, but neither of those do scrolling. I've also tried sending scrolls to the page via Javascript, e.g. driver.execute_script("scroll(0,-50)") This doesn't seem to do anything though.

How can I do this?


来源: stackexchange

问:
larger images cutting of in reveal.js
I'm using reveal js slideshow but it it larger images are cutting of as shown in this screenshot: https://prnt.sc/haa7wr

I want it show complete image but it's design is added via js and it's inline styling so my style is not overriding it or may be I wasn't doing it correctly.

```<code>.reveal section img { background-size: contain !important; }
</code>```

答:
you've got to override this style:</p>

```<code>.reveal .slide-background {
      background-size: contain !important;
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: larger images cutting of in reveal.js

Body:
I'm using reveal js slideshow but it it larger images are cutting of as shown in this screenshot: https://prnt.sc/haa7wr

I want it show complete image but it's design is added via js and it's inline styling so my style is not overriding it or may be I wasn't doing it correctly.

.reveal section img { background-size: contain !important; }

Body:
you've got to override this style:

.reveal .slide-background {
      background-size: contain !important;
}


问:
c++ Input a number which determines the other numbers and then compare them
I got this question: I want to write a program to find the minimum of some numbers . The first input number determines how many other numbers will be input. i know how to put the numbers but i don't know how to compare them.</p>

答:
You can do it by following</p>

```<code>int N; // total number of input
cin >> N;
int min_val = INT_MAX; //assign maximum integer value to min_val

for (int i = 0; i < N; i++) //looping through 0 to N-1 to take input and find min
{
   int N1;
   cin >> N1;
   min_val = std::min(min_val, N1); //returns min between min_val and N1 and assigns it to min_val
}

cout << min_val << endl; //print the min_val
</code>```

Body:
You can do it by following

int N; // total number of input
cin >> N;
int min_val = INT_MAX; //assign maximum integer value to min_val

for (int i = 0; i < N; i++) //looping through 0 to N-1 to take input and find min
{
   int N1;
   cin >> N1;
   min_val = std::min(min_val, N1); //returns min between min_val and N1 and assigns it to min_val
}

cout << min_val << endl; //print the min_val


问:
Azure Functions - ICollector binding not in resulting function.json
I have the following C# function code:

```<code>[FunctionName("UpdateCohortsByTenantFunction")]
[return: Queue("my-queue", Connection = "MyStorage")]
//note - I have tried both method decoration and parameter decoration
public static async Task Run([TimerTrigger("* * * * * *")]TimerInfo myTimer, IAsyncCollector<AudienceMessage> output)
{
    //some logic
    foreach (var audience in audiences)
    {
        await output.AddAsync(new AudienceMessage
        {
            AudienceId = audience.Id,
            TenantId = tenant.Id
        });
    }
}
</code>```

Which produces the following function.json:

```<code>{
   "generatedBy": "Microsoft.NET.Sdk.Functions.Generator-1.0.6",
   "configurationSource": "attributes",
   "bindings": [
   {
       "type": "timerTrigger",
       "schedule": "* * * * * *",
       "useMonitor": true,
       "runOnStartup": false,
       "name": "myTimer"
   }
  ],
  "disabled": false,
  "scriptFile": "../bin/MyApp.App.Tasks.Functions.dll",
  "entryPoint": "MyApp.App.Tasks.Functions.UpdateCohortsByTenantFunction.Run"
}
</code>```

According to the documentation here the json output should contain an binding to my queue with an "out" direction. Ie:

```<code>{
  "type": "queue",
  "direction": "out",
  "name": "$return",
  "queueName": "outqueue",
  "connection": "MyStorageConnectionAppSetting",
}
</code>```

When I try to run the queue via the npm tools (config described here), I get the following error:

Run: Microsoft.Azure.WebJobs.Host: Error indexing method 'UpdateCohortsByTenantFunction.Run'. Microsoft.Azure.WebJobs.Host: Cannot bind parameter 'output' to type IAsyncCollector`1. Make sure the parameter Type is supported by the binding. If you're using binding extensions (e.g. ServiceBus, Timers, etc.) make sure you've called the registration method for the extension(s) in your startup code (e.g. config.UseServiceBus(), config.UseTimers(), etc.).

The documentation contains no references to binding via startup code. My understanding is that this is done via the attributes described in the Microsoft documentation linked above, and in my example code, but the error message suggests otherwise.

答:
You should decorate your parameter with attribute, not return value:

public static async Task Run(
    [TimerTrigger("* * * * * *")]TimerInfo myTimer,
    [Queue("my-queue", Connection = "MyStg")] IAsyncCollector<AudienceMessage> output)
```

No output binding in function.json is to be expected. Attribute-defined bindings are not transferred to generated function.json. They will still work, don't worry.

Body:
I have the following C# function code:

[FunctionName("UpdateCohortsByTenantFunction")]
[return: Queue("my-queue", Connection = "MyStorage")]
//note - I have tried both method decoration and parameter decoration
public static async Task Run([TimerTrigger("* * * * * *")]TimerInfo myTimer, IAsyncCollector<AudienceMessage> output)
{
    //some logic
    foreach (var audience in audiences)
    {
        await output.AddAsync(new AudienceMessage
        {
            AudienceId = audience.Id,
            TenantId = tenant.Id
        });
    }
}

Which produces the following function.json:

{
   "generatedBy": "Microsoft.NET.Sdk.Functions.Generator-1.0.6",
   "configurationSource": "attributes",
   "bindings": [
   {
       "type": "timerTrigger",
       "schedule": "* * * * * *",
       "useMonitor": true,
       "runOnStartup": false,
       "name": "myTimer"
   }
  ],
  "disabled": false,
  "scriptFile": "../bin/MyApp.App.Tasks.Functions.dll",
  "entryPoint": "MyApp.App.Tasks.Functions.UpdateCohortsByTenantFunction.Run"
}

According to the documentation here the json output should contain an binding to my queue with an "out" direction. Ie:

{
  "type": "queue",
  "direction": "out",
  "name": "$return",
  "queueName": "outqueue",
  "connection": "MyStorageConnectionAppSetting",
}

When I try to run the queue via the npm tools (config described here), I get the following error:

Run: Microsoft.Azure.WebJobs.Host: Error indexing method 'UpdateCohortsByTenantFunction.Run'. Microsoft.Azure.WebJobs.Host: Cannot bind parameter 'output' to type IAsyncCollector`1. Make sure the parameter Type is supported by the binding. If you're using binding extensions (e.g. ServiceBus, Timers, etc.) make sure you've called the registration method for the extension(s) in your startup code (e.g. config.UseServiceBus(), config.UseTimers(), etc.).

The documentation contains no references to binding via startup code. My understanding is that this is done via the attributes described in the Microsoft documentation linked above, and in my example code, but the error message suggests otherwise.

Body:
You should decorate your parameter with attribute, not return value:

public static async Task Run(
    [TimerTrigger("* * * * * *")]TimerInfo myTimer,
    [Queue("my-queue", Connection = "MyStg")] IAsyncCollector<AudienceMessage> output)

No output binding in function.json is to be expected. Attribute-defined bindings are not transferred to generated function.json. They will still work, don't worry.


问:
publish more .net mvc applications with one click in visual studio 2012
I have a solution in Visual Studio 2012 with more MVC Web Projects. These are standalone modules of a complex system.

I want to have the ability to publish these projects separately, but in the most cases I don't have to publish only one of them. In this cases i want to publish e.g. Project A + Project B + Project C or Project A + Project D etc.

I created already a publish profile for all these projects. With these profiles I can easily publish one project at the time.

Can I somehow configure Visual Studio to run all the selected (configured) publish operations at the same time? Can I publish more than one projects with one click?

答:
Not in Visual Studio, however you can archive it using MSBuild command line.
I will update answer with example later on. short on time.</p>


问:
Slim Framework always return 404 Error
These days i'm using Slim Framework as my simplest tool to develop the php web api.
Using these two articles:

Coenraets

CodingThis

I follow some of the steps from there. Downloading the Slim Framework, putting the correct directory & files. Adjusting the initation statements such as;

```<code>//1. Require Slim
require('Slim/Slim.php');

//2. Instantiate Slim
$app = new Slim();

//3. Define routes
$app->get('/books', function ($id) {
    //Show book with id = $id
});
</code>```

And then, I modify the rest accordingly.

Such as my checklist that already done:

LoadModule rewrite_module modules/mod_rewrite.so -> enabled

Slim .htaccess:

RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteRule
  ^(.*)$ bootstrap.php [QSA,L]

httpd.conf: (Shared Link).

But, after Once I run this statement;

```<code>$app->run();
</code>```

And I run it on my browser.... then, I got 404 Error while testing it on my Localhost. What's the solution for fixing that?

FYI, here is my simplest PHP file that i'm currently using it. (shared Link)

答:
For me the problem was that I'd forgotten to provide a .htaccess file in my document root.

.htaccess

```<code>RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule . index.php [L]
</code>```

Title: Slim Framework always return 404 Error

Body:
These days i'm using Slim Framework as my simplest tool to develop the php web api.
Using these two articles:

Coenraets

CodingThis

I follow some of the steps from there. Downloading the Slim Framework, putting the correct directory & files. Adjusting the initation statements such as;

//1. Require Slim
require('Slim/Slim.php');

//2. Instantiate Slim
$app = new Slim();

//3. Define routes
$app->get('/books', function ($id) {
    //Show book with id = $id
});

And then, I modify the rest accordingly.

Such as my checklist that already done:

LoadModule rewrite_module modules/mod_rewrite.so -> enabled

Slim .htaccess:

RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteRule
  ^(.*)$ bootstrap.php [QSA,L]

httpd.conf: (Shared Link).

But, after Once I run this statement;

$app->run();

And I run it on my browser.... then, I got 404 Error while testing it on my Localhost. What's the solution for fixing that?

FYI, here is my simplest PHP file that i'm currently using it. (shared Link)

Body:
For me the problem was that I'd forgotten to provide a .htaccess file in my document root.

.htaccess

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule . index.php [L]


问:
How to generate unique int id using counting technique?
I have the following class that creates some comment and save it to dynamo db that must contain unique comment id. How to "implement" counting - a simple counter that will create the unique id for a comment. I don't want to repeat rsu_id value.

```<code>class RsuService(object):
    next_id = 0

    def __init__(self):
        self.rsu_id = RsuService.next_id
        RsuService.next_id += 1

    async def create(self, alert_id, text):
        message = {
            'event_id': alert_id,
            'text': text,
            'is_rsu': True,
            'comment_id': self.rsu_id
        }
        await save(message)
</code>```

Is it good implementation? How to improve it?

答:
I think this is not good a approach. You can generate UUID for each comment and use it as unique id</p>

```<code>import uuid

class RsuService(object):
    async def create(self, alert_id, text):
        message = {
            'event_id': alert_id,
            'text': text,
            'is_rsu': True,
            'comment_id': uuid.uuid4().hex
        }
        await save(message)
</code>```

Body:
I have the following class that creates some comment and save it to dynamo db that must contain unique comment id. How to "implement" counting - a simple counter that will create the unique id for a comment. I don't want to repeat rsu_id value.

class RsuService(object):
    next_id = 0

    def __init__(self):
        self.rsu_id = RsuService.next_id
        RsuService.next_id += 1

    async def create(self, alert_id, text):
        message = {
            'event_id': alert_id,
            'text': text,
            'is_rsu': True,
            'comment_id': self.rsu_id
        }
        await save(message)

Is it good implementation? How to improve it?

Body:
I think this is not good a approach. You can generate UUID for each comment and use it as unique id

import uuid

class RsuService(object):
    async def create(self, alert_id, text):
        message = {
            'event_id': alert_id,
            'text': text,
            'is_rsu': True,
            'comment_id': uuid.uuid4().hex
        }
        await save(message)


问:
Hiding play button initially
How would I hide the Playbutton when viewing the cover image, and show it after you click on the image?

I've been trying different ways, but can't seem to get it.

Full Code:

https://jsfiddle.net/0yxvpa09/12/

Click on the image to reveal a grid

Screenshot

```<code><div class="playButton ">

  <svg class="play" style="margin:5px 9px;" width="38" height="40" viewbox="0 0 85 100">
    <path d="M81 44.6c5 3 5 7.8 0 10.8L9 98.7c-5 3-9 .7-9-5V6.3c0-5.7 4-8 9-5l72 43.3z"></path>
  </svg>

  <svg class="pause" style="display: none;margin:5px 7px;" width="36" height="40" viewbox="0 0 60 100">
    <path d="M0 8c0-5 3-8 8-8s9 3 9 8v84c0 5-4 8-9 8s-8-3-8-8V8zm43 0c0-5 3-8 8-8s8 3 8 8v84c0 5-3 8-8 8s-8-3-8-8V8z"></path>
  </svg>

<script>
  (function iife() {
    "use strict";

    function hideClickedElement(evt) {
      var target = evt.target;
      target.classList.add("hide");
      document.querySelector(".test").classList.remove("hide");
    }
    var cover = document.querySelector(".cover");
    cover.addEventListener("click", hideClickedElement, false);
  }());

</script>
</code>```

答:
Just add the hide class to the play button and add document.querySelector(".playButton").classList.remove("hide"); to the hideClickedElement function.

JSFiddle: https://jsfiddle.net/0yxvpa09/19/

Title: Hiding play button initially

Body:
How would I hide the Playbutton when viewing the cover image, and show it after you click on the image?

I've been trying different ways, but can't seem to get it.

Full Code:

https://jsfiddle.net/0yxvpa09/12/

Click on the image to reveal a grid

Screenshot

  <svg class="play" style="margin:5px 9px;" width="38" height="40" viewbox="0 0 85 100">
    <path d="M81 44.6c5 3 5 7.8 0 10.8L9 98.7c-5 3-9 .7-9-5V6.3c0-5.7 4-8 9-5l72 43.3z"></path>
  </svg>

  <svg class="pause" style="display: none;margin:5px 7px;" width="36" height="40" viewbox="0 0 60 100">
    <path d="M0 8c0-5 3-8 8-8s9 3 9 8v84c0 5-4 8-9 8s-8-3-8-8V8zm43 0c0-5 3-8 8-8s8 3 8 8v84c0 5-3 8-8 8s-8-3-8-8V8z"></path>
  </svg>


问:
Php search in database to show data, not working
i'm trying to display some data from my database, and i dosen't work when i try to display some of the data, specified by a search bar. Here is the code. I hope someone can fix my problem.

Ive tried for a few hours, but nothing seems to work.

I removed most of the html code, to even be able to post.

<?php
 include_once 'includes/dbh.inc.php';
?>
<!DOCTYPE html>

    <form>
    <input type="text" name="search" placeholder="Search for graphicscard"/>
    <input type="submit" value="Search" />

<?php

?>

    </form>

Graphicscard
Coin
Hashrate
Bios-modded
Core-clock
Memory-clock
Power draw
Additional info

      <?
  if(isset($_POST['search'])) {
        $searchq = $_POST['search'];
        $searchq = preg_replace("#[^`0-9a-z]#i","", $searchq);

        $query = mysqli_query("SELECT * FROM 'cards' WHERE 'name' LIKE '$search%' OR coin LIKE '$search%'") or die ("No results");
        $count = mysqli_num_rows($queryQ);

            while ($row = mysqli_fetch_array($query)) {
                echo "
";
                echo "".$row['name']."	";
                echo "".$row['coin'] . "	";
                echo "".$row['hashrate'] . "	";
                echo "".$row['bios_mod'] . "	";
                echo "".$row['core_clock'] . "	";
                echo "".$row['memory_clock'] . "	";
                echo "".$row['power_draw'] . "	";
                echo "".$row['additional_info'] . "	";
                echo "
";
            }
        }

        ?>```

答:
The mysqli_query() used as a function needs the link id returned by mysqli_connect() o mysqli_init()

PHP mysqli_query() Function

So you need a $connection var:

```<code> $connection=mysqli_connect("localhost","my_user","my_password","my_db");
</code>```

and the use it on the query:

```<code> mysqli_query($connection, "SELECT * FROM 'cards' WHERE 'name' LIKE '$search%' OR coin LIKE '$search%'") or die ("No results");
</code>```

Body:
The mysqli_query() used as a function needs the link id returned by mysqli_connect() o mysqli_init()

PHP mysqli_query() Function

So you need a $connection var:

 $connection=mysqli_connect("localhost","my_user","my_password","my_db");

and the use it on the query:

 mysqli_query($connection, "SELECT * FROM 'cards' WHERE 'name' LIKE '$search%' OR coin LIKE '$search%'") or die ("No results");


问:
Whats a good use case for an EIMI?
EIMI being an explicit interface member implementation. So instead of:

```<code>public int SomeValue{get;}
</code>```

you have

```<code>int SomeInterface.SomeValue {get;}
</code>```

I'm currently considering using one as i'm using an internal interface (to decouple, yet restrict) and I don't want to make the methods on the implementing object to appear in its public API.

Is this a good use case?

答:
A very good example is in the .Net generic collections classes.

For example, List<T> implements 'IList' implicitly and IList (non generic interface) explicitly. That means when you use the class directly you'll only see the specialized methods and not the ones that work with Object.

Let's say you instantiate a List<Person>. If IList was implemented implicitly you'd have two add methods directly accessible on the class  Add(Person item) and Add(Object item), which will break type safety provided by generics. Calling list.Add("Foo") will compile just fine as the Add(Object) overload will get chosen automatically, and type safety provided by generics is gone.

OwnerDisplayName: Quarrelsome

ContentLicense: CC BY-SA 2.5

Title: Whats a good use case for an EIMI?

Body:
EIMI being an explicit interface member implementation. So instead of:

public int SomeValue{get;}

you have

int SomeInterface.SomeValue {get;}

I'm currently considering using one as i'm using an internal interface (to decouple, yet restrict) and I don't want to make the methods on the implementing object to appear in its public API.

Is this a good use case?

OwnerDisplayName: Pop Catalin


问:
Upload file to directory on server using Java and JSP - can't get path right
On my vps, I want to upload a file to the Logos directory.
The directory structure is as follows on my vps -

/home/webadmin/domain.com/html/Logos

When a file is uploaded through my jsp page, that file is renamed, and then I want to put it into the Logos directory.... but I can't seem to get the path right in my servlet code.

Snippet of servlet code -

```<code>String upload_directory="/Logos/"; // path to the upload folder

File savedFile = new File(upload_directory,BusinessName+"_Logo."+fileExtension);

//.....
//file saved to directory
//.....
</code>```

I've tried many variations, but still fail. What is the proper way to specify the path?

Edited

The problem with using getServletContext() is that it returns the path to the directory where Tomcat and my webapp is...whereas I want to reach the directory where my html and image files are - under the root directory of the vps. How do I specify that path?

```<code>    String server_path = getServletContext().getRealPath("/"); // get server path.

    //server_path = /opt/tomcat6/webapps/domain.com/

    String upload_directory = "Logos/"; // get path to the upload folder.

    String complete_path = server_path + upload_directory; // get the complete path to the upload folder.

    //complete_path = /opt/tomcat6/webapps/domain.com/Logos/

    File savedFile = new File(complete_path,"NewLogo.jpg");

    //savedFile = /opt/tomcat6/webapps/domain.com/Logos/NewLogo.jpg
</code>```

答:
It's a common practice to make the path for storage configurable - either via some application.properties file, or if you don't have such a properties file - as a context-param in web.xml. There you configure the path to be the absolute path, like:

```<code>configuredUploadDir=/home/webadmin/domain.com/html/Logos
</code>```

Obtain that value in your code (depending on how you stored it), and have:

```<code>File uploadDir = new File(configuredUploadDir);
</code>```

Note: make sure you have the permissions to read and write the target directory.

Body:
On my vps, I want to upload a file to the Logos directory.
The directory structure is as follows on my vps -

/home/webadmin/domain.com/html/Logos

When a file is uploaded through my jsp page, that file is renamed, and then I want to put it into the Logos directory.... but I can't seem to get the path right in my servlet code.

Snippet of servlet code -

String upload_directory="/Logos/"; // path to the upload folder

File savedFile = new File(upload_directory,BusinessName+"_Logo."+fileExtension);

//.....
//file saved to directory
//.....

I've tried many variations, but still fail. What is the proper way to specify the path?

Edited

The problem with using getServletContext() is that it returns the path to the directory where Tomcat and my webapp is...whereas I want to reach the directory where my html and image files are - under the root directory of the vps. How do I specify that path?

    String server_path = getServletContext().getRealPath("/"); // get server path.

    //server_path = /opt/tomcat6/webapps/domain.com/

    String upload_directory = "Logos/"; // get path to the upload folder.

    String complete_path = server_path + upload_directory; // get the complete path to the upload folder.

    //complete_path = /opt/tomcat6/webapps/domain.com/Logos/

    File savedFile = new File(complete_path,"NewLogo.jpg");

    //savedFile = /opt/tomcat6/webapps/domain.com/Logos/NewLogo.jpg

Body:
It's a common practice to make the path for storage configurable - either via some application.properties file, or if you don't have such a properties file - as a context-param in web.xml. There you configure the path to be the absolute path, like:

configuredUploadDir=/home/webadmin/domain.com/html/Logos

Obtain that value in your code (depending on how you stored it), and have:

File uploadDir = new File(configuredUploadDir);

Note: make sure you have the permissions to read and write the target directory.


问:
Convert MySQL query (with where condition) to Elasticsearch query
I need to "transform" mysql query to Elasticsearch query. What is blocking me is "where" statement. Basically what I need is to find all items that are within distance of 25 miles based on latitude and longitude and where pickup is enabled OR where items do have delivery enabled and provided zip code

```<code>where
(
    (
        `enabled_pickup` = '1'
        and(
            ST_Distance_Sphere(
                POINT(- 122.41941550000001 , 37.7749295) ,
                geolocation
            ) / 1000 * 0.62137119223733
        ) <= 25
    )
    or(
        `enabled_delivery` = '1'
        `zip_code` = '94116'
    )
)
</code>```

and this is Elasticsearch query that is not working as expected

```<code>{
"query": {
    "bool": {
      "must": [
        {
      "bool": {
        "should": [
          {
            "bool": {
              "must": [
                {
                  "match": {
                    "enabled_pickup": "1"
                  }
                },
                {
                  "geo_distance": {
                    "distance": "25 mi",
                    "geo_location": {
                      "lat": "37.7749295",
                      "lon": "-122.41941550000001"
                    }
                  }
                }
              ]
            }
          },
          {
            "bool": {
              "must": [
                {
                  "term": {
                    "dispensary.delivery": "1"
                  }
                },
                {
                  "term": {
                    "zip_code": "94116"
                  }
                }
              ]
            }
          }
        ]
      }
    }
  ]
}
</code>```

}
}

can somebody please point me in right direction?

答:
I was reading about the similar issue, you can give a try with below query. you can find a similar question being solved by this stackoverflow discussion

Hope this helps, Cheers!

```<code>{
"query": {
        "bool": {
            "should": [
                {
                    "bool": {
                      "must": [
                            {"match": { "enabled_pickup": "1"}}
                            ,{ "match": {
                                  "geo_distance": {
                                        "distance": "25 mi",
                                        "geo_location": {
                                            "lat": "37.7749295",
                                            "lon": "-122.41941550000001"
                                        }
                                    }
                                }
                            }
                        ]
                    }
                  ,
                    "bool": {
                      "must": [
                            { "match": {"dispensary.delivery": "1"} }
                            ,{"match": {"zip_code": "94116"} }
                        ]
                    }
                }
            ]
        }
    }
}
</code>```

Body:
I need to "transform" mysql query to Elasticsearch query. What is blocking me is "where" statement. Basically what I need is to find all items that are within distance of 25 miles based on latitude and longitude and where pickup is enabled OR where items do have delivery enabled and provided zip code

where
(
    (
        `enabled_pickup` = '1'
        and(
            ST_Distance_Sphere(
                POINT(- 122.41941550000001 , 37.7749295) ,
                geolocation
            ) / 1000 * 0.62137119223733
        ) <= 25
    )
    or(
        `enabled_delivery` = '1'
        `zip_code` = '94116'
    )
)

and this is Elasticsearch query that is not working as expected

{
"query": {
    "bool": {
      "must": [
        {
      "bool": {
        "should": [
          {
            "bool": {
              "must": [
                {
                  "match": {
                    "enabled_pickup": "1"
                  }
                },
                {
                  "geo_distance": {
                    "distance": "25 mi",
                    "geo_location": {
                      "lat": "37.7749295",
                      "lon": "-122.41941550000001"
                    }
                  }
                }
              ]
            }
          },
          {
            "bool": {
              "must": [
                {
                  "term": {
                    "dispensary.delivery": "1"
                  }
                },
                {
                  "term": {
                    "zip_code": "94116"
                  }
                }
              ]
            }
          }
        ]
      }
    }
  ]
}

}
}

can somebody please point me in right direction?

Body:
I was reading about the similar issue, you can give a try with below query. you can find a similar question being solved by this stackoverflow discussion

Hope this helps, Cheers!

{
"query": {
        "bool": {
            "should": [
                {
                    "bool": {
                      "must": [
                            {"match": { "enabled_pickup": "1"}}
                            ,{ "match": {
                                  "geo_distance": {
                                        "distance": "25 mi",
                                        "geo_location": {
                                            "lat": "37.7749295",
                                            "lon": "-122.41941550000001"
                                        }
                                    }
                                }
                            }
                        ]
                    }
                  ,
                    "bool": {
                      "must": [
                            { "match": {"dispensary.delivery": "1"} }
                            ,{"match": {"zip_code": "94116"} }
                        ]
                    }
                }
            ]
        }
    }
}


问:
Converting Json data to html?
```<code><script>
  $(document).ready(function() {

    $("#getMessage").on("click", function() {
      $.getJSON("/json/cats.json", function(json) {

        var html = "";
        // Only change code below this line.
        json.forEach(function(val){
                     var keys = Object.keys(val);
                     html+="<div class='cat'>";
                     keys.forEach(function(key){
                       html+="<strong>"+key+"</strong>;"+val[key]+"<br>";
                     });
        html+="</div><br>";
                     });

        // Only change code above this line.

        $(".message").html(html);

      });
    });
  });
</script>

<div class="container-fluid">
  <div class = "row text-center">
    <h2>Cat Photo Finder</h2>
  </div>
  <div class = "row text-center">
    <div class = "col-xs-12 well message">
      The message will go here
   </div>
  </div>
  <div class = "row text-center">
    <div class = "col-xs-12">
      <button id = "getMessage" class = "btn btn-primary">
        Get Message
      </button>
    </div>
  </div>
</div>
</code>```

<p>So I am an amateur front end developer I just finished some basic JS and started learning about json and jquery but this above bit of code is going over my head.
Could some one please explain the javascript part of it. </p>

答:
```<code>$(document).ready(function() { //function get executed when page finished all loading (i.e. html, JS/CSS files)
    $("#getMessage").on("click", function() { //clicking on an element (can be button) with ID "getMessage" triggers this function
          $.getJSON("/json/cats.json", function(json) { //Jquery method to fetch a file from given address and expected file should be a JSON file

        var html = "";
        // Only change code below this line.
            json.forEach(function(val){ // on successfully getting the file this function would be triggered
                 var keys = Object.keys(val); //storing keys to a variable "keys"
                 html+="<div class='cat'>"; //appending HTML object to a var
                 keys.forEach(function(key){ // loop through all the keys
                   html+="<strong>"+key+"</strong>;"+val[key]+"<br>"; // add all the keys as strong text and place values next to them
                 });
    html+="</div><br>"; // close the div and append line break
                 });

    // Only change code above this line.
   $(".message").html(html); //append the newly created HTML to a section (can be div) with ID "message" to show up on HTML page.
   });
 });
});
</code>```

Title: Converting Json data to html?

Body:
Cat Photo Finder

      The message will go here

      <button id = "getMessage" class = "btn btn-primary">
        Get Message
      </button>

So I am an amateur front end developer I just finished some basic JS and started learning about json and jquery but this above bit of code is going over my head.
Could some one please explain the javascript part of it.


问:
how to ignore attribute without quotes in xml
i want to count how many times tag1 occurs
givin this 123.xml file ( streaming from the internet)

```<code><startend>

 <tag1 name=myname>
<date>10-10-10</date>
</tag1 >

 <tag1 name=yourname>
   <date>11-10-10</date>
  </tag1 >

 </startend>
</code>```

using : xmlstarlet sel -t -v  "count(//tag1)" 123.xml

output :

AttValue: " or ' expected
attributes construct error

how to ignore that the attribute has no " "  ?

答:
XML always requires quotes around attribute values. If you want to keep using XML, you first must produce valid XML from your input. You could use an SGML processor such as OpenSP (in particular, the osx program) to format your input into wellformed XML. It's as simple as invoking osx <your Input file> on it.

If you're on Ubuntu/Debian Linux, you can install osx by invoking sudo apt-get install opensp on the command line (and similarly on other Unix systems).

Body:
i want to count how many times tag1 occurs
givin this 123.xml file ( streaming from the internet)

<startend>

 <tag1 name=myname>
<date>10-10-10</date>
</tag1 >

 <tag1 name=yourname>
   <date>11-10-10</date>
  </tag1 >

 </startend>

using : xmlstarlet sel -t -v  "count(//tag1)" 123.xml

output :

AttValue: " or ' expected
attributes construct error

how to ignore that the attribute has no " "  ?


问:
Matches dates in Laravel 5
I have $startdate and $finishdate, and in one table in Mysql, two columns "start_date" and "finish_date".

I want to know if the first range ($startdate,$finishdate) it matches in some date with the second range ("start_date,"finish_date").

I tried with Between, but with Eloquent is different, and not working for me.

答:
I think you mean that you want to check if the 2 ranges overlap (a solution here but not tested):</p>

```<code>if ($startdate<= "finish_date") and ("start_date" <= $finishdate)
</code>```

Title: Matches dates in Laravel 5

Body:
I think you mean that you want to check if the 2 ranges overlap (a solution here but not tested):

if ($startdate<= "finish_date") and ("start_date" <= $finishdate)


问:
How to optimize query which has to get last 5 rows with joined table
I have two tables events and user_device. events and user_device has a common field device_id.

user_device table has fields user_id and device_id. Basically, user_device table holding all devices belongs to users.

events table holding all events belongs to devices.

Now I want to get last 5 alerts for a specific user.

So I have made a query by joining both tables like below.

```<code>SELECT *
FROM events
LEFT JOIN user_device ON user_device.deviceid=events.deviceid
WHERE user_device.userid=101
ORDER BY events.id DESC
LIMIT 5
</code>```

events table has more than 4 million records. This query takes 30 seconds to return the results.

If I remove ORDER BY, the query takes only two seconds.

How can I optimize this?

答:
The fact that this takes longer than usual is most likely because of lack of indexes on the table. Add an indexes for deviceId and userId will help a lot with the speed of the query.

```<code>SELECT *
FROM events
LEFT JOIN user_device ON user_device.**deviceid**=events.**deviceid**
WHERE user_device.**userid**=101
ORDER BY events.id DESC
LIMIT 5
</code>```

Bold text requires indexes for quick 'hooks'. the Order by doesn't requre an index.

Body:
I have two tables events and user_device. events and user_device has a common field device_id.

user_device table has fields user_id and device_id. Basically, user_device table holding all devices belongs to users.

events table holding all events belongs to devices.

Now I want to get last 5 alerts for a specific user.

So I have made a query by joining both tables like below.

SELECT *
FROM events
LEFT JOIN user_device ON user_device.deviceid=events.deviceid
WHERE user_device.userid=101
ORDER BY events.id DESC
LIMIT 5

events table has more than 4 million records. This query takes 30 seconds to return the results.

If I remove ORDER BY, the query takes only two seconds.

How can I optimize this?

Body:
The fact that this takes longer than usual is most likely because of lack of indexes on the table. Add an indexes for deviceId and userId will help a lot with the speed of the query.

SELECT *
FROM events
LEFT JOIN user_device ON user_device.**deviceid**=events.**deviceid**
WHERE user_device.**userid**=101
ORDER BY events.id DESC
LIMIT 5

Bold text requires indexes for quick 'hooks'. the Order by doesn't requre an index.


问:
Where to put LESS, SCSS and JS files in ASP.NET MVC 6 Web Application
I am building a website with ASP.NET MVC 6 and i discover NPM, Bower & Gulp. I've understood the utility of each one.

I would like to know how to organize my "wwwroot" folder. I assuming that i need to have my final bundled and minified css & js files in the "wwwroot" folder.

But where do i put my LESS, SCSS and custom JS files ? in "wwwroot" folder too or in a folder in my solution ?

And if i want to use boostrap for example, but with LESS sources, where do i put them ?

答: I added same as per Cicero suggested above and formed the folders inside wwwroot as per requirement. For example- my custom files (js/css/less) files goes in separate folder under respective category. Later on, I wanted to add few files for bundling and minification, so added the reference of required files in bundleconfig.json</p>


问:
How to know data coming from JSON is a Float or an Integer in Swift 3?
I am getting data from Json and displaying it in table view how to check whether the number is float or double or integer in swift 3 if it is float how to get the no.of digits after decimal can anyone help me how to implement this in swift 3 ?</p>

```<code>                    if specialLoop.attributeCode == "special_price" {
                        let attributeString: NSMutableAttributedString = NSMutableAttributedString(string: "$ \((arr.price))")
                        attributeString.addAttribute(NSStrikethroughStyleAttributeName, value: 1, range: NSMakeRange(0, attributeString.length))
                        let specialPrice = specialLoop.value.replacingOccurrences(of: ".0000", with: "0")
                        print(specialPrice)
                        cell.productPrice.text = "$ \(specialPrice)"
                        cell.specialPriceLabel.isHidden = false
                        cell.specialPriceLabel.attributedText = attributeString
                        break
                     }
                     else {
                        cell.specialPriceLabel.isHidden = true
                        let price = arr.price
                        print(price)
                        cell.productPrice.text = "$ \( (price))0"
                    }
</code>```

答:
as describe below, you can find a type of any object (whether custom class or built-in class like - String, Int, etc.).

```<code>class demo {
    let a: String = ""
}

let demoObj = demo()

print(type(of: demoObj))
</code>```

--> Output: "demo.Type"

Body:
I am getting data from Json and displaying it in table view how to check whether the number is float or double or integer in swift 3 if it is float how to get the no.of digits after decimal can anyone help me how to implement this in swift 3 ?

                    if specialLoop.attributeCode == "special_price" {
                        let attributeString: NSMutableAttributedString = NSMutableAttributedString(string: "$ \((arr.price))")
                        attributeString.addAttribute(NSStrikethroughStyleAttributeName, value: 1, range: NSMakeRange(0, attributeString.length))
                        let specialPrice = specialLoop.value.replacingOccurrences(of: ".0000", with: "0")
                        print(specialPrice)
                        cell.productPrice.text = "$ \(specialPrice)"
                        cell.specialPriceLabel.isHidden = false
                        cell.specialPriceLabel.attributedText = attributeString
                        break
                     }
                     else {
                        cell.specialPriceLabel.isHidden = true
                        let price = arr.price
                        print(price)
                        cell.productPrice.text = "$ \( (price))0"
                    }

Body:
as describe below, you can find a type of any object (whether custom class or built-in class like - String, Int, etc.).

class demo {
    let a: String = ""
}

let demoObj = demo()

print(type(of: demoObj))

--> Output: "demo.Type"


问:
Java equivalent of visual basic tab function
I am attempting to convert some old VB6 code into java for my company. I have all of it done except for the formatting of the strings. In the old VB6 code they would use the Tab(N) function to dictate where the string would be positioned on a line as it was being written to a text file. I have been looking for some way to duplicate this in any way with Java. I am attempting right now to figure out the String.format method, but I'm slightly confused on how it functions. Is there any other function or any way I can set the absolute position of a string on a line in java? One example is the first string is 15 characters long and the next string in the line needs to be at line position 50, while another string is 4 characters long and each string after that is supposed to be at position 19, 34, 41, 51, 59, 66, 76, 83, and 90. Any help would be greatly appreciated!

Example:

```<code>(name)                                           PRODUCTION DATE    : (date)

SERVICE           PROC  MODS       BILLED       ALLOWED      PAID          ADJ    ADJ    LINE REMARK
DATE              CODE           UNI    AMT       AMT     UNI    AMT       AMT    CODES  CODE
</code>```

答:
I ran into a similar issue and ended up creating a builder for this.

```<code>public class TabLineBuilder {

    int length;
    private String line;
    StringBuilder sb;

    public TabLineBuilder(int length) {
        this.length = length;
        initialize(); // call non-overridable method
    }

    public TabLineBuilder insert(int pos, String text) {
        sb.replace(pos, pos + text.length(), text);
        line = sb.toString();
        return this;
    }

    public String toString() {
        return line;
    }

    private void initialize() {
        // new line of spaces
        line = String.format("%" + length + "s", ' ');
        sb = new StringBuilder(line);
    }

    public void clear() {
        // Overridable public method
        initialize();
    }
}
</code>```

Example:

```<code>TabLineBuilder tlb = new TabLineBuilder(120);
String line = tlb.insert(0, "(name)").insert(50, "PRODUCTION DATE").toString();
System.out.println(line);
tlb.clear();
line = tlb.insert(0, "DATE").insert(19, "CODE").insert(34, "UNI").toString();
System.out.println(line);
tlb.clear();
</code>```

Output:

```<code>(name)                                            PRODUCTION DATE
DATE               CODE           UNI
</code>```

Body:
I am attempting to convert some old VB6 code into java for my company. I have all of it done except for the formatting of the strings. In the old VB6 code they would use the Tab(N) function to dictate where the string would be positioned on a line as it was being written to a text file. I have been looking for some way to duplicate this in any way with Java. I am attempting right now to figure out the String.format method, but I'm slightly confused on how it functions. Is there any other function or any way I can set the absolute position of a string on a line in java? One example is the first string is 15 characters long and the next string in the line needs to be at line position 50, while another string is 4 characters long and each string after that is supposed to be at position 19, 34, 41, 51, 59, 66, 76, 83, and 90. Any help would be greatly appreciated!

Example:

(name)                                           PRODUCTION DATE    : (date)

SERVICE           PROC  MODS       BILLED       ALLOWED      PAID          ADJ    ADJ    LINE REMARK
DATE              CODE           UNI    AMT       AMT     UNI    AMT       AMT    CODES  CODE

Body:
I ran into a similar issue and ended up creating a builder for this.

public class TabLineBuilder {

    int length;
    private String line;
    StringBuilder sb;

    public TabLineBuilder(int length) {
        this.length = length;
        initialize(); // call non-overridable method
    }

    public TabLineBuilder insert(int pos, String text) {
        sb.replace(pos, pos + text.length(), text);
        line = sb.toString();
        return this;
    }

    public String toString() {
        return line;
    }

    private void initialize() {
        // new line of spaces
        line = String.format("%" + length + "s", ' ');
        sb = new StringBuilder(line);
    }

    public void clear() {
        // Overridable public method
        initialize();
    }
}

Example:

TabLineBuilder tlb = new TabLineBuilder(120);
String line = tlb.insert(0, "(name)").insert(50, "PRODUCTION DATE").toString();
System.out.println(line);
tlb.clear();
line = tlb.insert(0, "DATE").insert(19, "CODE").insert(34, "UNI").toString();
System.out.println(line);
tlb.clear();

Output:

(name)                                            PRODUCTION DATE
DATE               CODE           UNI


问:
ssh through port 443 on gitlab not working
I am trying to use port 443 to push and pull my gitlab repository since my port 22 has been blocked (reference: https://about.gitlab.com/2016/02/18/gitlab-dot-com-now-supports-an-alternate-git-plus-ssh-port/)

I have given below my config file that i created (i created a new ssh key that I updated in my gitlab profile - Note: I did not add the server key as a deploy key, rather, I just added it in my profile)

my config file:

```<code>Host gitlab.com
        Hostname altssh.gitlab.com
        User gitlabusername
        Port 443
        PreferredAuthentications publickey
        IdentityFile ~/.ssh/id_rsa.pub
</code>```

I keep getting the following error:

permission denied (publickey)
fatal: Could not read from remote repository

Could the error be because of something other than the ssh key?

Regards,
Galeej

答:
I just configured it and it's working well for me.

In your config file you need to use the private key id_rsa for authenticating not the public one id_rsa.pub

```<code>Host gitlab.com
  Hostname altssh.gitlab.com
  User git
  Port 443
  PreferredAuthentications publickey
  IdentityFile ~/.ssh/id_rsa
</code>```

You may test the connection using using this command ssh -T -p 443 git@altssh.gitlab.com.

Make sure that you already added the public key id_rsa.pub to your GitLab account as described here.

Body:
I am trying to use port 443 to push and pull my gitlab repository since my port 22 has been blocked (reference: https://about.gitlab.com/2016/02/18/gitlab-dot-com-now-supports-an-alternate-git-plus-ssh-port/)

I have given below my config file that i created (i created a new ssh key that I updated in my gitlab profile - Note: I did not add the server key as a deploy key, rather, I just added it in my profile)

my config file:

Host gitlab.com
        Hostname altssh.gitlab.com
        User gitlabusername
        Port 443
        PreferredAuthentications publickey
        IdentityFile ~/.ssh/id_rsa.pub

I keep getting the following error:

permission denied (publickey)
fatal: Could not read from remote repository

Could the error be because of something other than the ssh key?

Regards,
Galeej

Body:
I just configured it and it's working well for me.

In your config file you need to use the private key id_rsa for authenticating not the public one id_rsa.pub

Host gitlab.com
  Hostname altssh.gitlab.com
  User git
  Port 443
  PreferredAuthentications publickey
  IdentityFile ~/.ssh/id_rsa

You may test the connection using using this command ssh -T -p 443 git@altssh.gitlab.com.

Make sure that you already added the public key id_rsa.pub to your GitLab account as described here.


问:
Hotswap Agent, add New Classes
can I add new class on Hotswap Agent? I try changing name methods, body of methods, fields, and works fine, but when I add new class and call it on another the app crash, don do the content of that class and not show errors.</p>

```<code>package test;

public class TestNewClass
{
        public void test()
    {
        System.out.println("test new class");
    }
}

@Controller
public class MenuController extends MainController
{
    @RequestMapping(value = "/menu/getMenu", method = RequestMethod.GET, produces = APPLICATION_JSON_VALUE_UTF_8)
        @ResponseBody
        public String getMenu(HttpServletResponse httpRessponse)
        {
            System.out.println("test 3 "+test);
            UserVitrina user = getUserVitrina();
            MenuHandler menuHandler = new MenuHandler();
            try
            {
                genericBO.openSessionTransaction();
                Map menu = menuHandler.getMenu(user.getIdUsuario());
                genericBO.commitTransaction();
                return new Gson().toJson(menu);
            }
            catch (Exception ex)
            {
                new Log().printLogError("MENU. Error obtener menu.", ex, (user == null ? "usuario nulo" : user.getUsername()), null, Resources.LogName.DEBUG);
                httpRessponse.setStatus(HttpStatus.BAD_GATEWAY.value());
                genericBO.abortTransaction();
                return new Gson().toJson(new MessageServer().generateMessageError(ex));
            }
            finally
            {
                genericBO.closeSession();
            }
        }
}
</code>```

答:
If you do hotswap with your IDE, it swaps only existing classes. New classes are loaded by standard mechanism from the classpath. Is your new class on the classpath? If you have e.g. multimodule maven project, you may be able to swap classes from dependent module, but new classes are loaded only from built jar files.

To solve this add extraClaspath (http://hotswapagent.org/mydoc_configuration.html) to your hotswap-agent.properties file.

Title: Hotswap Agent, add New Classes

Body:
can I add new class on Hotswap Agent? I try changing name methods, body of methods, fields, and works fine, but when I add new class and call it on another the app crash, don do the content of that class and not show errors.

package test;

public class TestNewClass
{
        public void test()
    {
        System.out.println("test new class");
    }
}

@Controller
public class MenuController extends MainController
{
    @RequestMapping(value = "/menu/getMenu", method = RequestMethod.GET, produces = APPLICATION_JSON_VALUE_UTF_8)
        @ResponseBody
        public String getMenu(HttpServletResponse httpRessponse)
        {
            System.out.println("test 3 "+test);
            UserVitrina user = getUserVitrina();
            MenuHandler menuHandler = new MenuHandler();
            try
            {
                genericBO.openSessionTransaction();
                Map menu = menuHandler.getMenu(user.getIdUsuario());
                genericBO.commitTransaction();
                return new Gson().toJson(menu);
            }
            catch (Exception ex)
            {
                new Log().printLogError("MENU. Error obtener menu.", ex, (user == null ? "usuario nulo" : user.getUsername()), null, Resources.LogName.DEBUG);
                httpRessponse.setStatus(HttpStatus.BAD_GATEWAY.value());
                genericBO.abortTransaction();
                return new Gson().toJson(new MessageServer().generateMessageError(ex));
            }
            finally
            {
                genericBO.closeSession();
            }
        }
}


问:
Windows Mobile - Localization
I need to create Localized Windows Mobile Application. I seen some videos from MSDN. But, all requires either Satelite assemblies or separate forms resources for each language. This will increase the size of executable. I am storing localized text in SQLite database which I need to show on Buttons, MessageBoxes etc.

How Can I show localized text on UI Controls (Fetching from DB is not a problem)? When I try to show Hindi (India) language text on Button, it shows junk characters.

Is there anything like Culture, Character set that needs to be set to show Hindi (India) text on UI without creating any resource file (directly from database)? I need to support many languages and my main server will provide me localized resources to store in database.

答: If you load the localized string from the database but it's not displaying properly, then it's not a problem of the text, it's a problem of the font.  The Font you're using likely doesn't have the Hindi glyphs you're requesting.  Get a Font (legally) that you can distribute with the app that does support them.</p>

Title: Windows Mobile - Localization


答:
It will be fairly simple if you select the data based on Service containing server_hit_rate by forward filling Host and then merge the data i.e

```<code>temp = df2.ffill()[df2['Service']=='server_hit_rate']

#                 Host          Service             Time OK      ...
#1  server1.test.com:1717  server_hit_rate  99.000% (100.000%)   ...
#6  server2.test.com:1717  server_hit_rate  99.000% (100.000%)   ...

combined = pd.merge(df[['Host',' Time Up']],temp[['Host',' Time OK']], on='Host')
combined[' Time OK'] = combined[' Time OK'].apply(lambda x: x.split('(')[0])
combined[' Time Up'] = combined[' Time Up'].apply(lambda x: x.split('(')[0])
</code>```

Output of dataframe combined :

```
print(combined)

                  Host    Time Up   Time OK
0  server1.test.com:1717  100.000%   99.000%
1  server2.test.com:1717  100.000%   99.000%
```

Also instead of using spaces before the column name strip the spaces using

```<code>df.columns = df.columns.str.strip()
</code>```

Title: column operation in csv [python]

Body:
I have a scenario where I am extracting a row value from a csv file.

(CSV) test1:

    Host, Time Up, Time Down, Time Unreachable, Time Undetermined
server1.test.com:1717,100.000% (100.000%),0.000% (0.000%),0.000% (0.000%),0.000
server2.test.com:1717,100.000% (100.000%),0.000% (0.000%),0.000% (0.000%),0.000
Average,100.000% (100.000%),0.000% (0.000%),0.000% (0.000%),0.000

(CSV) test2:

Host,Service, Time OK, Time Warning, Time Unknown, Time Critical, Time Undetermined
server1.test.com:1717,application_availability_check,100.000% (100.000%),0.000% (0.000%),0.000% (0.000%),0.000% (0.000%),0.000
,server_hit_rate,99.000% (100.000%),0.000% (0.000%),0.000% (0.000%),0.000% (0.000%),0.000
,max_hit_rate,100.000% (100.000%),0.000% (0.000%),0.000% (0.000%),0.000% (0.000%),0.000
,application_log_check,100.000% (100.000%),0.000% (0.000%),0.000% (0.000%),0.000% (0.000%),0.000
,application_sessions_check,100.000% (100.000%),0.000% (0.000%),0.000% (0.000%),0.000% (0.000%),0.000
server2.test.com:1717,application_availability_check,100.000% (100.000%),0.000% (0.000%),0.000% (0.000%),0.000% (0.000%),0.000
,server_hit_rate,99.000% (100.000%),0.000% (0.000%),0.000% (0.000%),0.000% (0.000%),0.000
,max_hit_rate,100.000% (100.000%),0.000% (0.000%),0.000% (0.000%),0.000% (0.000%),0.000
,application_log_check,100.000% (100.000%),0.000% (0.000%),0.000% (0.000%),0.000% (0.000%),0.000
,application_sessions_check,100.000% (100.000%),0.000% (0.000%),0.000% (0.000%),0.000% (0.000%),0.000
Average,100.000% (100.000%),0.000% (0.000%),0.000% (0.000%),0.000% (0.000%),0.000

This is my code:

df = pd.read_csv('test1.csv',skipfooter=1)
df2 = pd.read_csv('test2.csv',skipfooter=1)
combined = pd.merge(df[['Host',' Time Up']],df2[['Host',' Time OK']], on='Host')
combined[' Time OK'] = combined[' Time OK'].apply(lambda x: x.split('(')[0])
combined[' Time Up'] = combined[' Time Up'].apply(lambda x: x.split('(')[0])

Here I am trying to get the value of "server_hit_rate" which is 99% & belongs to 3rd row data.
But with this above code I am able to get the data which is in first row only. i.e.

                    Host    Time Up    Time OK
0  server1.test.com:1717  100.000%   100.000%
1  server2.test.com:1717  100.000%   100.000%

The required output should be:

                    Host    Time Up    Time OK
0  server1.test.com:1717  100.000%    99.000%
1  server2.test.com:1717  100.000%    99.000%

Any advice to achieve the following will be helpful.

Edit1:

import pandas as pd
import pandas
import os, shutil, glob
import sys
import datetime
import time
def t1():
    import pandas as pd
    import pandas
    today=datetime.datetime.utcnow().strftime("%a %b %d %H:%M:%S %Z %Y")
    print "date :", today
    df = pd.read_csv('t1.csv',skipfooter=1, engine='python')
    df2 = pd.read_csv('t2.csv',skipfooter=1, engine='python')
    temp = df2.ffill()[df2['Service']=='server_hit_rate']
    combined = pd.merge(df[['Host',' Time Up']],temp[['Host',' Time OK']], on='Host')
    combined[' Time OK'] = combined[' Time OK'].apply(lambda x: x.split('(')[0])
    combined[' Time Up'] = combined[' Time Up'].apply(lambda x: x.split('(')[0])
    combined.to_csv('test.csv',index=False)
t1()

O/P:

Wed Nov 15 10:07:01  2017
Empty DataFrame
Columns: [Host, % Time Up, % Time OK]
Index: []

Body:
It will be fairly simple if you select the data based on Service containing server_hit_rate by forward filling Host and then merge the data i.e

temp = df2.ffill()[df2['Service']=='server_hit_rate']

#                 Host          Service             Time OK      ...
#1  server1.test.com:1717  server_hit_rate  99.000% (100.000%)   ...
#6  server2.test.com:1717  server_hit_rate  99.000% (100.000%)   ...

combined = pd.merge(df[['Host',' Time Up']],temp[['Host',' Time OK']], on='Host')
combined[' Time OK'] = combined[' Time OK'].apply(lambda x: x.split('(')[0])
combined[' Time Up'] = combined[' Time Up'].apply(lambda x: x.split('(')[0])

Output of dataframe combined :

print(combined)

                  Host    Time Up   Time OK
0  server1.test.com:1717  100.000%   99.000%
1  server2.test.com:1717  100.000%   99.000%

Also instead of using spaces before the column name strip the spaces using

df.columns = df.columns.str.strip()


问:
How do you get the systemctl Result for a failed service from Python?
If a systemd service unit is in a failed state, systemctl status shows that fact:

```<code>    # systemctl status myservice
    ● myservice.service - Important Crash Prone service (myservice)
       Loaded: loaded (/etc/systemd/system/myservice.service; enabled; vendor preset: disabled)
       Active: failed (Result: start-limit) since Tue 2017-08-22 20:04:13 UTC; 3s ago
      Process: 31108 ExecStart=/bin/myservice (code=dumped, signal=ABRT)
     Main PID: 31108 (code=dumped, signal=ABRT)
</code>```

I'd like to have a Python program get that "Result: start-limit" field without forking systemctl and attempting to parse the output. The other fields (e.g. Loaded, Active) are available from the Python dbus library.

For instance, the following code gets the ActiveState property which is displayed by systemctl after "Active:" (the word "failed" in the output above).

```<code>from dbus import Interface, SystemBus, SessionBus
bus = SystemBus()
systemd = bus.get_object('org.freedesktop.systemd1',
                         '/org/freedesktop/systemd1')

manager = Interface(systemd, dbus_interface='org.freedesktop.systemd1.Manager')

myservice_unit = manager.LoadUnit('myservice.service')

myservice_proxy = bus.get_object('org.freedesktop.systemd1', str(myservice_unit))

myservice = Interface(myservice_proxy,
dbus_interface='org.freedesktop.systemd1.Unit')

prop = 'ActiveState'
value = myservice_proxy.Get('org.freedesktop.systemd1.Unit',
                            prop,
                            dbus_interface='org.freedesktop.DBus.Properties')
print("{} is: {}".format(prop, value))
</code>```

It appears the "Result" value is not a property in the sense that much of the other output is.

答:
If you check the docs at https://www.freedesktop.org/wiki/Software/systemd/dbus/, it explains the Result being part of Service Unit Objects (org.freedesktop.systemd1.Service).

So, I added this to your code:

```<code>if value == 'failed':
    result_prop = 'Result'
    result = myservice_proxy.Get('org.freedesktop.systemd1.Service',
                                 result_prop,
                                 dbus_interface='org.freedesktop.DBus.Properties')
    print(result)
</code>```

Now it's working beautifully!

Body:
If a systemd service unit is in a failed state, systemctl status shows that fact:

    # systemctl status myservice
    ● myservice.service - Important Crash Prone service (myservice)
       Loaded: loaded (/etc/systemd/system/myservice.service; enabled; vendor preset: disabled)
       Active: failed (Result: start-limit) since Tue 2017-08-22 20:04:13 UTC; 3s ago
      Process: 31108 ExecStart=/bin/myservice (code=dumped, signal=ABRT)
     Main PID: 31108 (code=dumped, signal=ABRT)

I'd like to have a Python program get that "Result: start-limit" field without forking systemctl and attempting to parse the output. The other fields (e.g. Loaded, Active) are available from the Python dbus library.

For instance, the following code gets the ActiveState property which is displayed by systemctl after "Active:" (the word "failed" in the output above).

from dbus import Interface, SystemBus, SessionBus
bus = SystemBus()
systemd = bus.get_object('org.freedesktop.systemd1',
                         '/org/freedesktop/systemd1')

manager = Interface(systemd, dbus_interface='org.freedesktop.systemd1.Manager')

myservice_unit = manager.LoadUnit('myservice.service')

myservice_proxy = bus.get_object('org.freedesktop.systemd1', str(myservice_unit))

myservice = Interface(myservice_proxy,
dbus_interface='org.freedesktop.systemd1.Unit')

prop = 'ActiveState'
value = myservice_proxy.Get('org.freedesktop.systemd1.Unit',
                            prop,
                            dbus_interface='org.freedesktop.DBus.Properties')
print("{} is: {}".format(prop, value))

It appears the "Result" value is not a property in the sense that much of the other output is.

Body:
If you check the docs at https://www.freedesktop.org/wiki/Software/systemd/dbus/, it explains the Result being part of Service Unit Objects (org.freedesktop.systemd1.Service).

So, I added this to your code:

if value == 'failed':
    result_prop = 'Result'
    result = myservice_proxy.Get('org.freedesktop.systemd1.Service',
                                 result_prop,
                                 dbus_interface='org.freedesktop.DBus.Properties')
    print(result)

Now it's working beautifully!


问:
Regular Expression (regex) to Parse HTML Segment
I am currently trying to come up with a regular expression that will parse out something like the following:

ORIGINAL HTML:

```<code><td align="center"><p>line 1</p><p>line 2</p><p>line 3</p></td>
</code>```

INTENDED HTML:

```<code><td align="center">line 1<br />line 2<br />line 3</td>
</code>```

Note that there are other
...
 tags throughout the HTML document that must not be touched. I only want to replace
...
 within a  or  only.

I would also need a regexp to reverse the process. Please note that these regular expressions have to work in VB/VBScript/Classic ASP, so although I can use lookaheads (which I think is the key here), I cannot use lookbehinds. Some regex's I've tried unsuccessfully are:

```<code>1. <td[^>]*>(<p>.+<\/p>)<\/td>
2. <td[^>]*>(<p>.+<\/p>)+?<\/td>
3. <td[^>]*><p>(?:(.+?)<\/p><p>(.+))+<\/p><\/td>
4. <td[^>]*>(<p>(?:(?!<\/p>)).*<\/p>)+?<\/td>
5. <td[^>]*>(?:<p>(.+?)<\/p>)*(?:<p>(.+)<\/p>)<\/td>
6. <td[^>]*>(?:<p>(.+?)<\/p>)(?:<p>(.+)<\/p>)*(?:<p>(.+)<\/p>)<\/td>
</code>```

I can "cheat" and pull out the entire line and then parse it manually usually standard VB string manipulation functions, but that's definitely not the most elegant, nor the fastest way. There has to be some way to do this in one shot using RegEx's.

Eventually I'd like to take...

```<code><td align="center"><p><span style="color:#ff0000;"><strong>line 1</strong></span></p><p>line 2</p><p>line 3</p></td>
</code>```

...and turn it into

```<code><td align="center"><span style="color:#ff0000;"><strong>line 1</strong></span><br />line 2<br />line 3</td>
</code>```

Any ideas (besides not to do this with a regex, lol)?

Thank you!

答:
Regular expression are not suited for a irregular language like HTML. You should better use a proper HTML parser.

You could use PHP’s DOM library:

```<code>$doc = new DOMDocument();
$doc->loadHTML($code);
$xpath = new DOMXpath($doc);
forach ($xpath->query('//td/p') as $i => $elem) {  // find all P elements that are a child of a TD
    if ($i != 0) {                                  // add BR for any P except the first
        $elem->parentNode->insertBefore($doc->createElement('br'), $elem);
    }
    foreach ($elem->childNodes as $nodes) {        // move contents out of P
        $elem->parentNode->insertBefore($node, $elem);
    }
    $elem->parentNode->removeChild($elem);         // remove empty P
}
</code>```

Body:
I am currently trying to come up with a regular expression that will parse out something like the following:

ORIGINAL HTML:

line 1

line 2

line 3

INTENDED HTML:

line 1
line 2
line 3

Note that there are other
...
 tags throughout the HTML document that must not be touched. I only want to replace
...
 within a  or  only.

I would also need a regexp to reverse the process. Please note that these regular expressions have to work in VB/VBScript/Classic ASP, so although I can use lookaheads (which I think is the key here), I cannot use lookbehinds. Some regex's I've tried unsuccessfully are:

1. ]*>(
.+<\/p>)<\/td>
2. ]*>(
.+<\/p>)+?<\/td>
3. ]*>
(?:(.+?)<\/p>
(.+))+<\/p><\/td>
4. ]*>(
(?:(?!<\/p>)).*<\/p>)+?<\/td>
5. ]*>(?:
(.+?)<\/p>)*(?:
(.+)<\/p>)<\/td>
6. ]*>(?:
(.+?)<\/p>)(?:
(.+)<\/p>)*(?:
(.+)<\/p>)<\/td>

I can "cheat" and pull out the entire line and then parse it manually usually standard VB string manipulation functions, but that's definitely not the most elegant, nor the fastest way. There has to be some way to do this in one shot using RegEx's.

Eventually I'd like to take...

line 1

line 2

line 3

...and turn it into

line 1
line 2
line 3

Any ideas (besides not to do this with a regex, lol)?

Thank you!

Body:
Regular expression are not suited for a irregular language like HTML. You should better use a proper HTML parser.

You could use PHP’s DOM library:

$doc = new DOMDocument();
$doc->loadHTML($code);
$xpath = new DOMXpath($doc);
forach ($xpath->query('//td/p') as $i => $elem) {  // find all P elements that are a child of a TD
    if ($i != 0) {                                  // add BR for any P except the first
        $elem->parentNode->insertBefore($doc->createElement('br'), $elem);
    }
    foreach ($elem->childNodes as $nodes) {        // move contents out of P
        $elem->parentNode->insertBefore($node, $elem);
    }
    $elem->parentNode->removeChild($elem);         // remove empty P
}


问:
finding the largest binary number from a range of cells
I have a data of some binary numbers in few range of cells, from A2 to A8, B2 to B8, and so on, till G column.
Now, I want to check the largest binary number from the above Rows and paste it to the cell, two row below the last used range. (i.e., Largest binary number from Row A to be paste in A10, and so on).
I am not finding any function which can find the value of binary numbers, and the code which I ran finds out the max number considering those as natural numbers.
Your help will be appreciated.
Thank You!</p>

答:
You can use the excel function Bin2Dec to change them into decimal</p>

```<code>Function MaxBin(r as range)
Dim curmax as long
Dim s as range
For each s in r
   If Application.WorksheetFunction.Bin2Dec(s.Text) > curmax Then curmax = Application.WorksheetFunction.Bin2Dec(s.Text)
Next s
MaxBin = curmax
End Function
</code>```

Body:
You can use the excel function Bin2Dec to change them into decimal

Function MaxBin(r as range)
Dim curmax as long
Dim s as range
For each s in r
   If Application.WorksheetFunction.Bin2Dec(s.Text) > curmax Then curmax = Application.WorksheetFunction.Bin2Dec(s.Text)
Next s
MaxBin = curmax
End Function


问:
How to create compile-time class fields using templates?

Little background and rationale

I am designing a compile-time ECS. The design has its specifics - for instance, there will be a great variety of entities. This means that the overall number of components is likely to be fairly high whilst number of components per entity will be fairly low (having some obvious present-almost-everywhere-commons such as Sprite or BoundingBox)

My approach

I would implement the following interface:

```<code>/* Tell the compiler which fields we would use in this entity */
Entity<GraphicsComponent, PhysicsComponent> entity;

/* Populate the handles with the appropriate data (integer, pointer, doesn't matter) */
// via explicit creation
Entity.add<GraphicsComponent>(RenderSystem::create<GraphicsComponent>());
// or in some other way?
</code>```

The inception of the Entity class I wrote:

```<code>template <typename ...>
class Entity final {};
</code>```

I have, however, no idea how would I create the handle data fields for the respective Component types, and if it is even possible at all. Can anyone help me or explain why it wouldn't work (or possibly suggest a different solution)?

答:
Use std::variant for a mixture of flexibility and simplicity, at the cost of possibly sacrificing some memory.

```<code>template<typename... Components>
class Entity final {
    using variant = std::variant<Components...>;
    std::vector<variant> components;

public:
    template<typename T>
    void add(T&& t) {
        components.push_back(std::forward<T>(t));
    }
};
</code>```

The memory problem arises when your component have largely varying sizes. Say one is 1 byte while another is 200 bytes, all the entries in the std::vector will be at least 200 bytes large.

Another solution is std::any.

```<code>template<typename... Components>
class Entity final {
    std::vector<std::any> components;

public:
    template<typename T>
    void add(T&& t) {
        static_assert((std::is_same_v<Components, std::decay_t<T>> || ...));
        components.push_back(std::forward<T>(t));
    }
};
</code>```

std::any most certainly have everything on the heap except very small objects, but doesn't suffer from the aforementioned problem with std::variant.

In the case with std::any, we use the type system only to enable checks, not to govern the layout of data.

Body:
Little background and rationale

I am designing a compile-time ECS. The design has its specifics - for instance, there will be a great variety of entities. This means that the overall number of components is likely to be fairly high whilst number of components per entity will be fairly low (having some obvious present-almost-everywhere-commons such as Sprite or BoundingBox)

My approach

I would implement the following interface:

/* Tell the compiler which fields we would use in this entity */
Entity<GraphicsComponent, PhysicsComponent> entity;

/* Populate the handles with the appropriate data (integer, pointer, doesn't matter) */
// via explicit creation
Entity.add<GraphicsComponent>(RenderSystem::create<GraphicsComponent>());
// or in some other way?

The inception of the Entity class I wrote:

template <typename ...>
class Entity final {};

I have, however, no idea how would I create the handle data fields for the respective Component types, and if it is even possible at all. Can anyone help me or explain why it wouldn't work (or possibly suggest a different solution)?

Body:
Use std::variant for a mixture of flexibility and simplicity, at the cost of possibly sacrificing some memory.

template<typename... Components>
class Entity final {
    using variant = std::variant<Components...>;
    std::vector<variant> components;

public:
    template<typename T>
    void add(T&& t) {
        components.push_back(std::forward<T>(t));
    }
};

The memory problem arises when your component have largely varying sizes. Say one is 1 byte while another is 200 bytes, all the entries in the std::vector will be at least 200 bytes large.

Another solution is std::any.

template<typename... Components>
class Entity final {
    std::vector<std::any> components;

public:
    template<typename T>
    void add(T&& t) {
        static_assert((std::is_same_v<Components, std::decay_t<T>> || ...));
        components.push_back(std::forward<T>(t));
    }
};

std::any most certainly have everything on the heap except very small objects, but doesn't suffer from the aforementioned problem with std::variant.

In the case with std::any, we use the type system only to enable checks, not to govern the layout of data.


问:
How can I prevent a conflict between JSON encode and a unique id generator?
I want to insert a unique id into my database and output some text via json encode. Like this my code is working fine, my output is "hello":

```<code>   $json = array(
        'example' => 'hello',
    );

   echo json_encode($json);

   $uniqueID = "123";

   $pdo = $db->prepare('INSERT INTO example (unique_id) values(:unique_id) ');
    $pdo->execute(array(
        ':unique_id' => $uniqueID,
    ));
</code>```

But when I want to generate the unique id, then there is some error I cannot figure out:

```<code>   $json = array(
        'example' => 'hello',
    );

   echo json_encode($json);

   $random_id_length = 10;
   $uniqueID = crypt(uniqid(rand(),1));
   $uniqueID = strip_tags(stripslashes($uniqueID));
   $uniqueID = str_replace(".","",$uniqueID);
   $uniqueID = strrev(str_replace("/","",$uniqueID));
   $uniqueID = substr($uniqueID,0,$random_id_length);

   $pdo = $db->prepare('INSERT INTO example (unique_id) values(:unique_id) ');
    $pdo->execute(array(
        ':unique_id' => $uniqueID,
    ));
</code>```

Like this, everything is correctly inserted into the database. But I do not get any output.

答:
I think that the error that you're getting is this:

```<code>PHP: crypt(): No salt parameter was specified. You must use a randomly generated salt and a strong hash function to produce a secure hash.
</code>```

From the docs:

The salt parameter is optional. However, crypt() creates a weak hash without the salt. PHP 5.6 or later raise an E_NOTICE error without it. Make sure to specify a strong enough salt for better security.

The docs also recommend using password_hash instead:

password_hash() uses a strong hash, generates a strong salt, and applies proper rounds automatically. password_hash() is a simple crypt() wrapper and compatible with existing password hashes. Use of password_hash() is encouraged.

So try changing:

```<code>$uniqueID = crypt(uniqid(rand(),1));
</code>```

To:

```<code>$uniqueID = password_hash(uniqid(rand(),1), PASSWORD_DEFAULT);
</code>```

Body:
I want to insert a unique id into my database and output some text via json encode. Like this my code is working fine, my output is "hello":

   $json = array(
        'example' => 'hello',
    );

   echo json_encode($json);

   $uniqueID = "123";

   $pdo = $db->prepare('INSERT INTO example (unique_id) values(:unique_id) ');
    $pdo->execute(array(
        ':unique_id' => $uniqueID,
    ));

But when I want to generate the unique id, then there is some error I cannot figure out:

   $json = array(
        'example' => 'hello',
    );

   echo json_encode($json);

   $random_id_length = 10;
   $uniqueID = crypt(uniqid(rand(),1));
   $uniqueID = strip_tags(stripslashes($uniqueID));
   $uniqueID = str_replace(".","",$uniqueID);
   $uniqueID = strrev(str_replace("/","",$uniqueID));
   $uniqueID = substr($uniqueID,0,$random_id_length);

   $pdo = $db->prepare('INSERT INTO example (unique_id) values(:unique_id) ');
    $pdo->execute(array(
        ':unique_id' => $uniqueID,
    ));

Like this, everything is correctly inserted into the database. But I do not get any output.

Body:
I think that the error that you're getting is this:

PHP: crypt(): No salt parameter was specified. You must use a randomly generated salt and a strong hash function to produce a secure hash.

From the docs:

The salt parameter is optional. However, crypt() creates a weak hash without the salt. PHP 5.6 or later raise an E_NOTICE error without it. Make sure to specify a strong enough salt for better security.

The docs also recommend using password_hash instead:

password_hash() uses a strong hash, generates a strong salt, and applies proper rounds automatically. password_hash() is a simple crypt() wrapper and compatible with existing password hashes. Use of password_hash() is encouraged.

So try changing:

$uniqueID = crypt(uniqid(rand(),1));

To:

$uniqueID = password_hash(uniqid(rand(),1), PASSWORD_DEFAULT);


问:
sending multiple checkbox values through PHPmailer
Once i enter submit button. mail has been send. But instead of sending selected values it send every value in the list. i cant able to find what am i missing. Please suggest.

As far as i seen i didn't get any error in it. but i think issue lies in the communicating part.

Built using
1) html
2) javascript
3) jquery
4) PHP
5) PHPMailer

Please suggest any solution.

var address = document.getElementById('faddress');
var optiona = document.getElementById('optiona');
var optionb = document.getElementById('optionb');
var optionc = document.getElementById('optionc');
var optiond = document.getElementById('optiond');
var optione = document.getElementById('optione');
var optionf = document.getElementById('optionf');
var optiong = document.getElementById('optiong');
var optionh = document.getElementById('optionh');
var optioni = document.getElementById('optioni');
var optionj = document.getElementById('optionj');
var sectiona = document.getElementById('sectiona');

function checkErrors(){
  var error_count = 0;

  if(error_count == 0){

     document.getElementById('container').innerHTML = "

Thank You

We will get back to you shortly.

";
     var xhttp = new XMLHttpRequest();
      xhttp.onreadystatechange = function() {
      if (this.readyState == 4 && this.status == 200) {
        if(this.responseText == "OKAY"){

        }
      }
      };
      xhttp.open("GET", "comm.php? address="+address.value+"&optiona="+optiona.value+"&optionb="+optionb.value+"&optionc="+optionc.value+"&optiond="+optiond.value+"&optione="+optione.value+"&optionf="+optionf.value+"&optiong="+optiong.value+"&optionh="+optionh.value+"&optioni="+optioni.value+"&optionj="+optionj.value+"&sectiona="+sectiona.value);
      xhttp.send();
  }
}

document.getElementById("submit_button").addEventListener("click", function(){
  checkErrors();
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code>  <form method="POST" name="contactform" action="contact-form-handler.php">

                <input class="form-check-input " type="checkbox" name="optiona" id="optiona" value="ESOL - National 3: Ayr">

                <input class="form-check-input " type="checkbox" name="optionb" id="optionb" value="ESOL - National 4: Kilmarnock/Kilwinning">

                <input class="form-check-input " type="checkbox" name="optionc" id="optionc" value="ESOL - National 5: Ayr / Kilmarnock">

                <input class="form-check-input " type="checkbox" name="optiond" id="optiond" value="ESOL - Higher: Ayr/Kilmarnock">

                <input class="form-check-input " type="checkbox" name="optione" id="optione" value="PEZ: Ayr/Kilmarnock/Kilwinning">

                <input class="form-check-input " type="checkbox" name="optionf" id="optionf" value="PEZ Plus: Ayr/Kilmarnock/Kilwinning /Cumnock">

                <input class="form-check-input " type="checkbox" name="optiong" id="optiong" value="Step Into Employment: Kilwinning">

                <input class="form-check-input " type="checkbox" name="optionh" id="optionh" value="Step Into Youthwork: Ayr">

                <input class="form-check-input " type="checkbox" name="optioni" id="optioni" value="Twenty Four/Seven Plus: Ayr/Kilmarnock/Kilwinning">

                <input class="form-check-input " type="checkbox" name="optionj" id="optionj" value="Princes Trust (Feb 18 start): Ayr/Kilmarnock/Kilwinning">

                <input class="form-check-input " type="checkbox" name="sectiona" id="sectiona" value="Introduction to Business and Computing: Kilwinning">

      <input type="text" class="textbx form-control" name="faddress" id="faddress" placeholder="Enter your email">
      <button type="submit" name="submit" class="subsc" id="submit_button"></button>
  </form></code>```

Comm.php

<?php
date_default_timezone_set("America/New_York");
require 'PHPMailer/PHPMailerAutoload.php';

   class MyDB extends SQLite3 {
      function __construct() {
         $this->open('south_bay.sqlite');
      }
   }

$address = $_GET['address'];
$optiona = $_GET['optiona'];
$optionb = $_GET['optionb'];
$optionc = $_GET['optionc'];
$optiond = $_GET['optiond'];
$optione = $_GET['optione'];
$optionf = $_GET['optionf'];
$optiong = $_GET['optiong'];
$optionh = $_GET['optionh'];
$optioni = $_GET['optioni'];
$optionj = $_GET['optionj'];
$sectiona = $_GET['sectiona'];
$monthNum  = date("m");
$dateObj   = DateTime::createFromFormat('!m', $monthNum);
$monthName = $dateObj->format('F');
$date = $monthName.date("-d-Y").' '.date("h:i:s A");

$mail = new PHPMailer();
$body = "
Here are your customer details

 EMAIL ADDRESS: $address

 PARTNERSHIP AND EMPLOYABLITY COURSES - CAMPUS LOCATION

$optiona

$optionb

$optionc

$optiond

$optione

$optionf

$optiong

$optionh

$optioni

$optionj

 BUSSINESS AND COUMPUTING

$sectiona

";

$mail->SMTPDebug  = 0;                     // enables SMTP debug information (for testing)
$mail->SMTPAuth   = true;                  // enable SMTP authentication
$mail->SMTPSecure = "ssl";                 // sets the prefix to the servier
$mail->Host       = "smtp.gmail.com";      // sets GMAIL as the SMTP server
$mail->Port       = 465;   // set the SMTP port for the GMAIL server
$mail->SMTPKeepAlive = true;
$mail->Mailer = "smtp";
$mail->Username   = "testing@gmail.com";  // GMAIL username
$mail->Password   = "welcome$123";            // GMAIL password
$mail->AddAddress('testing@gmail.com');
$mail->AddAddress('testing@gmail.com');
$mail->SetFrom('testing@gmail.com');
$mail->Subject = 'Contact Form';
$mail->AltBody = 'To view the message, please use an HTML compatible email viewer!'; // optional - MsgHTML will create an alternate automatically
$mail->MsgHTML($body);
$mail->Send();

echo "OKAY";
?>```

Once i enter submit button. mail has been send. But instead of sending selected values it send every value in the list. i cant able to find what am i missing. Please suggest.

As far as i seen i didn't get any error in it. but i think issue lies in the communicating part.

Built using
1) html
2) javascript
3) jquery
4) PHP
5) PHPMailer

Please suggest any solution.

答:
You've gone through a very hard way.

You could use a checkbox array like this:

```<code>  <form method="POST" id="contactform" name="contactform" action="contact-form-handler.php">

                <input class="form-check-input " type="checkbox" name="option[]" id="optiona" value="ESOL - National 3: Ayr">

                <input class="form-check-input " type="checkbox" name="option[]" id="optionb" value="ESOL - National 4: Kilmarnock/Kilwinning">

                <input class="form-check-input " type="checkbox" name="option[]" id="optionc" value="ESOL - National 5: Ayr / Kilmarnock">

                <input class="form-check-input " type="checkbox" name="option[]" id="optiond" value="ESOL - Higher: Ayr/Kilmarnock">

                <input class="form-check-input " type="checkbox" name="option[]" id="optione" value="PEZ: Ayr/Kilmarnock/Kilwinning">

                <input class="form-check-input " type="checkbox" name="option[]" id="optionf" value="PEZ Plus: Ayr/Kilmarnock/Kilwinning /Cumnock">

                <input class="form-check-input " type="checkbox" name="option[]" id="optiong" value="Step Into Employment: Kilwinning">

                <input class="form-check-input " type="checkbox" name="option[]" id="optionh" value="Step Into Youthwork: Ayr">

                <input class="form-check-input " type="checkbox" name="option[]" id="optioni" value="Twenty Four/Seven Plus: Ayr/Kilmarnock/Kilwinning">

                <input class="form-check-input " type="checkbox" name="option[]" id="optionj" value="Princes Trust (Feb 18 start): Ayr/Kilmarnock/Kilwinning">

                <input class="form-check-input " type="checkbox" name="sectiona" id="sectiona" value="Introduction to Business and Computing: Kilwinning">

      <input type="text" class="textbx form-control" name="faddress" id="faddress" placeholder="Enter your email">
      <button type="submit" name="submit" class="subsc" id="submit_button"></button>
  </form>
</code>```

And using jQuery,

```<code>$(function(){

$('#contactform').submit(function(){

var data = $(this).serialize();

$.ajax({
  method: 'POST',
  url: 'path-to-your-php-file-here',
  data: data,
  success: function(result){
    console.log(result) //what to do on success
  },
  error: function(result){
    console.log(result) //what to do on error
  },
  complete: function(result){
    console.log(result) //what to do on complete (success or error)
  },

});

});

});
</code>```

And, in your PHP file, you could use $_POST in order to fetch the data.

```<code>$address = $_POST['address'];
$option_array = $_POST['option'];

$option_to_string = implode(", ", $option_array); //if you want it as a comma separated string
$sectiona = $_POST['sectiona'];
</code>```

Body:
Once i enter submit button. mail has been send. But instead of sending selected values it send every value in the list. i cant able to find what am i missing. Please suggest.

As far as i seen i didn't get any error in it. but i think issue lies in the communicating part.

Built using
1) html
2) javascript
3) jquery
4) PHP
5) PHPMailer

Please suggest any solution.

var address = document.getElementById('faddress');
var optiona = document.getElementById('optiona');
var optionb = document.getElementById('optionb');
var optionc = document.getElementById('optionc');
var optiond = document.getElementById('optiond');
var optione = document.getElementById('optione');
var optionf = document.getElementById('optionf');
var optiong = document.getElementById('optiong');
var optionh = document.getElementById('optionh');
var optioni = document.getElementById('optioni');
var optionj = document.getElementById('optionj');
var sectiona = document.getElementById('sectiona');

function checkErrors(){
  var error_count = 0;

  if(error_count == 0){

     document.getElementById('container').innerHTML = "

Thank You

We will get back to you shortly.

";
     var xhttp = new XMLHttpRequest();
      xhttp.onreadystatechange = function() {
      if (this.readyState == 4 && this.status == 200) {
        if(this.responseText == "OKAY"){

        }
      }
      };
      xhttp.open("GET", "comm.php? address="+address.value+"&optiona="+optiona.value+"&optionb="+optionb.value+"&optionc="+optionc.value+"&optiond="+optiond.value+"&optione="+optione.value+"&optionf="+optionf.value+"&optiong="+optiong.value+"&optionh="+optionh.value+"&optioni="+optioni.value+"&optionj="+optionj.value+"&sectiona="+sectiona.value);
      xhttp.send();
  }
}

document.getElementById("submit_button").addEventListener("click", function(){
  checkErrors();
});

  <form method="POST" name="contactform" action="contact-form-handler.php">

                <input class="form-check-input " type="checkbox" name="optiona" id="optiona" value="ESOL - National 3: Ayr">

                <input class="form-check-input " type="checkbox" name="optionb" id="optionb" value="ESOL - National 4: Kilmarnock/Kilwinning">

                <input class="form-check-input " type="checkbox" name="optionc" id="optionc" value="ESOL - National 5: Ayr / Kilmarnock">

                <input class="form-check-input " type="checkbox" name="optiond" id="optiond" value="ESOL - Higher: Ayr/Kilmarnock">

                <input class="form-check-input " type="checkbox" name="optione" id="optione" value="PEZ: Ayr/Kilmarnock/Kilwinning">

                <input class="form-check-input " type="checkbox" name="optionf" id="optionf" value="PEZ Plus: Ayr/Kilmarnock/Kilwinning /Cumnock">

                <input class="form-check-input " type="checkbox" name="optiong" id="optiong" value="Step Into Employment: Kilwinning">

                <input class="form-check-input " type="checkbox" name="optionh" id="optionh" value="Step Into Youthwork: Ayr">

                <input class="form-check-input " type="checkbox" name="optioni" id="optioni" value="Twenty Four/Seven Plus: Ayr/Kilmarnock/Kilwinning">

                <input class="form-check-input " type="checkbox" name="optionj" id="optionj" value="Princes Trust (Feb 18 start): Ayr/Kilmarnock/Kilwinning">

                <input class="form-check-input " type="checkbox" name="sectiona" id="sectiona" value="Introduction to Business and Computing: Kilwinning">

      <input type="text" class="textbx form-control" name="faddress" id="faddress" placeholder="Enter your email">
      <button type="submit" name="submit" class="subsc" id="submit_button"></button>
  </form>

Comm.php

<?php
date_default_timezone_set("America/New_York");
require 'PHPMailer/PHPMailerAutoload.php';

   class MyDB extends SQLite3 {
      function __construct() {
         $this->open('south_bay.sqlite');
      }
   }

$address = $_GET['address'];
$optiona = $_GET['optiona'];
$optionb = $_GET['optionb'];
$optionc = $_GET['optionc'];
$optiond = $_GET['optiond'];
$optione = $_GET['optione'];
$optionf = $_GET['optionf'];
$optiong = $_GET['optiong'];
$optionh = $_GET['optionh'];
$optioni = $_GET['optioni'];
$optionj = $_GET['optionj'];
$sectiona = $_GET['sectiona'];
$monthNum  = date("m");
$dateObj   = DateTime::createFromFormat('!m', $monthNum);
$monthName = $dateObj->format('F');
$date = $monthName.date("-d-Y").' '.date("h:i:s A");

$mail = new PHPMailer();
$body = "
Here are your customer details

 EMAIL ADDRESS: $address

 PARTNERSHIP AND EMPLOYABLITY COURSES - CAMPUS LOCATION

$optiona

$optionb

$optionc

$optiond

$optione

$optionf

$optiong

$optionh

$optioni

$optionj

 BUSSINESS AND COUMPUTING

$sectiona

";

$mail->SMTPDebug  = 0;                     // enables SMTP debug information (for testing)
$mail->SMTPAuth   = true;                  // enable SMTP authentication
$mail->SMTPSecure = "ssl";                 // sets the prefix to the servier
$mail->Host       = "smtp.gmail.com";      // sets GMAIL as the SMTP server
$mail->Port       = 465;   // set the SMTP port for the GMAIL server
$mail->SMTPKeepAlive = true;
$mail->Mailer = "smtp";
$mail->Username   = "testing@gmail.com";  // GMAIL username
$mail->Password   = "welcome$123";            // GMAIL password
$mail->AddAddress('testing@gmail.com');
$mail->AddAddress('testing@gmail.com');
$mail->SetFrom('testing@gmail.com');
$mail->Subject = 'Contact Form';
$mail->AltBody = 'To view the message, please use an HTML compatible email viewer!'; // optional - MsgHTML will create an alternate automatically
$mail->MsgHTML($body);
$mail->Send();

echo "OKAY";
?>

Once i enter submit button. mail has been send. But instead of sending selected values it send every value in the list. i cant able to find what am i missing. Please suggest.

As far as i seen i didn't get any error in it. but i think issue lies in the communicating part.

Built using
1) html
2) javascript
3) jquery
4) PHP
5) PHPMailer

Please suggest any solution.

Body:
You've gone through a very hard way.

You could use a checkbox array like this:

  <form method="POST" id="contactform" name="contactform" action="contact-form-handler.php">

                <input class="form-check-input " type="checkbox" name="option[]" id="optiona" value="ESOL - National 3: Ayr">

                <input class="form-check-input " type="checkbox" name="option[]" id="optionb" value="ESOL - National 4: Kilmarnock/Kilwinning">

                <input class="form-check-input " type="checkbox" name="option[]" id="optionc" value="ESOL - National 5: Ayr / Kilmarnock">

                <input class="form-check-input " type="checkbox" name="option[]" id="optiond" value="ESOL - Higher: Ayr/Kilmarnock">

                <input class="form-check-input " type="checkbox" name="option[]" id="optione" value="PEZ: Ayr/Kilmarnock/Kilwinning">

                <input class="form-check-input " type="checkbox" name="option[]" id="optionf" value="PEZ Plus: Ayr/Kilmarnock/Kilwinning /Cumnock">

                <input class="form-check-input " type="checkbox" name="option[]" id="optiong" value="Step Into Employment: Kilwinning">

                <input class="form-check-input " type="checkbox" name="option[]" id="optionh" value="Step Into Youthwork: Ayr">

                <input class="form-check-input " type="checkbox" name="option[]" id="optioni" value="Twenty Four/Seven Plus: Ayr/Kilmarnock/Kilwinning">

                <input class="form-check-input " type="checkbox" name="option[]" id="optionj" value="Princes Trust (Feb 18 start): Ayr/Kilmarnock/Kilwinning">

                <input class="form-check-input " type="checkbox" name="sectiona" id="sectiona" value="Introduction to Business and Computing: Kilwinning">

      <input type="text" class="textbx form-control" name="faddress" id="faddress" placeholder="Enter your email">
      <button type="submit" name="submit" class="subsc" id="submit_button"></button>
  </form>

And using jQuery,

$(function(){

$('#contactform').submit(function(){

var data = $(this).serialize();

$.ajax({
  method: 'POST',
  url: 'path-to-your-php-file-here',
  data: data,
  success: function(result){
    console.log(result) //what to do on success
  },
  error: function(result){
    console.log(result) //what to do on error
  },
  complete: function(result){
    console.log(result) //what to do on complete (success or error)
  },

});

});

});

And, in your PHP file, you could use $_POST in order to fetch the data.

$address = $_POST['address'];
$option_array = $_POST['option'];

$option_to_string = implode(", ", $option_array); //if you want it as a comma separated string
$sectiona = $_POST['sectiona'];