问:
smooth scroll to name and ID
I have this code to scroll smoothly to a div id, but not to a name:

```<code>$('.scroll').on('click', function(e) {
    e.preventDefault();
    $('html, body').animate({
        scrollTop: $($(this).attr('href')).offset().top - 70
    }, 800, function(){
        window.location.hash = "#";
        return false;
    });
});
</code>```

and this one does the opposite:

```<code>$('.scroll').on('click', function(e) {
    e.preventDefault();
    $('html, body').animate({
        scrollTop: $('[name="' + $.attr(this, 'href').substr(1) + '"]').offset().top - 70
    }, 800, function(){
        window.location.hash = "#";
        return false;
    });
});
</code>```

How can I mix both codes to scroll to ID's and names in one code?

答:
I'm not sure if I understand your question 100% but I think you could just search for the element by name using querySelector and then apply the scroll to your element that way.

I was looking for an easy scroll solution earlier and came across scrollIntoView. Worked like a charm and required a lot less code than any of the other solutions I found.

var foo = document.querySelector('[name="foo"]');
var bar = document.querySelector('#bar');

foo.addEventListener('click',
  function(){
  bar.scrollIntoView({behavior: 'smooth', block: 'start'});
 });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.top {
  width: 100%;
  height: 150vh;
  background-color: blue;
  text-align: center
}

button {
  margin-top: 2rem;
  padding: 5px 15px;
  font-size 18px;
 }

.second {
  display: flex;
  justify-content: center;
  width: 100%;
  height: 100vh;
  background-color: green;
}

h1 {
  color: white;
 }</code>```

  <button name="foo">Click Here</button>

It's Working!

```

Title: smooth scroll to name and ID

Body:
I have this code to scroll smoothly to a div id, but not to a name:

$('.scroll').on('click', function(e) {
    e.preventDefault();
    $('html, body').animate({
        scrollTop: $($(this).attr('href')).offset().top - 70
    }, 800, function(){
        window.location.hash = "#";
        return false;
    });
});

and this one does the opposite:

$('.scroll').on('click', function(e) {
    e.preventDefault();
    $('html, body').animate({
        scrollTop: $('[name="' + $.attr(this, 'href').substr(1) + '"]').offset().top - 70
    }, 800, function(){
        window.location.hash = "#";
        return false;
    });
});

How can I mix both codes to scroll to ID's and names in one code?

Body:
I'm not sure if I understand your question 100% but I think you could just search for the element by name using querySelector and then apply the scroll to your element that way.

I was looking for an easy scroll solution earlier and came across scrollIntoView. Worked like a charm and required a lot less code than any of the other solutions I found.

var foo = document.querySelector('[name="foo"]');
var bar = document.querySelector('#bar');

foo.addEventListener('click',
  function(){
  bar.scrollIntoView({behavior: 'smooth', block: 'start'});
 });

.top {
  width: 100%;
  height: 150vh;
  background-color: blue;
  text-align: center
}

button {
  margin-top: 2rem;
  padding: 5px 15px;
  font-size 18px;
 }

.second {
  display: flex;
  justify-content: center;
  width: 100%;
  height: 100vh;
  background-color: green;
}

h1 {
  color: white;
 }

<div class="top">
  <button name="foo">Click Here</button>
</div>
<div class="second" id="bar">
  <h1>It's Working!</h1>
</div>


来源: stackexchange

问:
Display more than one search result on Multidimensional Array
I have a problem when I want to search in multidimensional arrays.
I have a string inside the textarea

```<code><textarea id='alltemplatememe'>
    ['2','makan lagi','kwik-templatememe-20171208215155.jpg'],['1','apapun','kwik-templatememe-20171208215124.jpg']
</textarea>
</code>```

and i will change the data in textarea into array, such as the function below

```<code>function meme_template_search(){
    var keyword=$("#keyword_template").val();
    var template=$("#alltemplatememe").val();
    var resultsame="";
    template=eval("[" + template + "]");
    for(var i=0; i<template.length; i++){
        result=template[i][1].search(new RegExp(keyword, "i"));
        if(result=="1"){
            resultsame+=template[i][1]+", ";
        }
        result="";
    }
    alert(resultsame);
}
</code>```

I've tried the above code, but the problem is the code above just show one result

when I do a search with the keyword "a", it should be two, but the function that I make only displays one result

答:
You are limiting your result to only one with this line

```<code>if(result=="1"){
</code>```

Result the position of where your keyword appears in the string.

I.e:

```<code>Search 'a' in 'Apple' -> 0        | Search 'to' in 'Potato' -> 4
</code>```

When your keyword doesn't appear in the string, result will be -1

So change your line to:

```<code>if (result !== -1) {
</code>```

Which will be true when a string matched.

See here for more details:
JavaScript RegExp Object

ContentLicense: CC BY-SA 3.0

Body:
I have a problem when I want to search in multidimensional arrays.
I have a string inside the textarea

<textarea id='alltemplatememe'>
    ['2','makan lagi','kwik-templatememe-20171208215155.jpg'],['1','apapun','kwik-templatememe-20171208215124.jpg']
</textarea>

and i will change the data in textarea into array, such as the function below

function meme_template_search(){
    var keyword=$("#keyword_template").val();
    var template=$("#alltemplatememe").val();
    var resultsame="";
    template=eval("[" + template + "]");
    for(var i=0; i<template.length; i++){
        result=template[i][1].search(new RegExp(keyword, "i"));
        if(result=="1"){
            resultsame+=template[i][1]+", ";
        }
        result="";
    }
    alert(resultsame);
}

I've tried the above code, but the problem is the code above just show one result

when I do a search with the keyword "a", it should be two, but the function that I make only displays one result

Body:
You are limiting your result to only one with this line

if(result=="1"){

Result the position of where your keyword appears in the string.

I.e:

Search 'a' in 'Apple' -> 0        | Search 'to' in 'Potato' -> 4

When your keyword doesn't appear in the string, result will be -1

So change your line to:

if (result !== -1) {

Which will be true when a string matched.

See here for more details:
JavaScript RegExp Object


问:
How to draw NSImage to CGContext
I have an object NSImage, which I want to draw to CGContext.
I found that there is no corresponding method for CGContext, but there seems to be a CGImage method, clip

```<code>func clip(to: CGRect, mask: CGImage)
</code>```

How do I need to do it, please?

答:
The easiest way is to create an NSGraphicsContext wrapping your CGContext, and draw into that:

```<code>let gc: CGContext = ...
let nsImage: NSImage = ...
let rect: CGRect = ...

let priorNsgc = NSGraphicsContext.current
defer { NSGraphicsContext.current = priorNsgc }
NSGraphicsContext.current = NSGraphicsContext(cgContext: gc, flipped: false)
nsImage.draw(in: rect)
</code>```

Title: How to draw NSImage to CGContext

Body:
I have an object NSImage, which I want to draw to CGContext.
I found that there is no corresponding method for CGContext, but there seems to be a CGImage method, clip

func clip(to: CGRect, mask: CGImage)

How do I need to do it, please?

Body:
The easiest way is to create an NSGraphicsContext wrapping your CGContext, and draw into that:

let gc: CGContext = ...
let nsImage: NSImage = ...
let rect: CGRect = ...

let priorNsgc = NSGraphicsContext.current
defer { NSGraphicsContext.current = priorNsgc }
NSGraphicsContext.current = NSGraphicsContext(cgContext: gc, flipped: false)
nsImage.draw(in: rect)


问:
How can I include records based on when they first appear, and exclude other records based on a certain date?
I need to select criteria based on inclusions and exclusions of the same attributes and on different dates and I am having a hard time wrapping my head around how to do this.  Here is a list of my criteria.

The record was first added to the database with a transaction of 222 or 223 and an activity code of ‘A’.

The record does not have a status code of 7

Any records where the latest activity code (A, V, W, J) for the following transactions (109, 154, 982, 745) after 10/01/2009 should not be included in the results,

There are 2 tables involved with a join on the employee ID.

Table 1:

```<code>|id  |  statcode
|  1     |  1
|  2     |  3
|  3     |  7
|  4     |  2
</code>```

Table 2:

```<code>|id       |  date      | act_code   |  trans
|   1     |  1/1/17    |   Z        |    109
|   1     |  3/4/12    |   A        |    222
|   1     |  2/14/09   |   A        |    154
|   2     |  1/1/17    |   A        |    223
|   2     |  6/6/13    |   V        |    109
|   3     |  11/23/14  |   A        |    222
|   4     |  12/13/16  |   X        |    154
|   4     |  11/23/14  |   W        |    223
</code>```

What I’d like to return is:

```<code>|    id  | statcode|  date      | act_code   |  trans
|   1    |   1     |  3/4/12    |   A        |    222
</code>```

ID 2 would not be selected because the first trans is not one of the correct values. ID 3 would not be included due to a incorrect status code. ID 4 would not be selected because the latest act_code is not one of the correct values. Anyone have an idea as to how to go about this? Thanks in advance.

edit: Here is the query as attempted. It seems to return everything.

```<code>SELECT *
FROM firsttable a
join secondtable b on a.id=b.id
where exists (select id, min(date) from
secondtable
where c.TRANS in ('222','223') and (TRANS NOT IN ('109', '154', '982',
'745')
AND ACT_CODE NOT IN  ('A', 'V', 'W', 'J') and date>= to_date('10/01/2009',
'MM/DD/YYYY'))
group by id)
and a.statcode <> '07'
;
</code>```

答:
Try This :</p>

```<code>select Emp_id,statcode,date,act_code,trans
from table1 A join table2 b on (a.id=b.id)
WHERE b.trans in(222,223)
AND b.act_code='A'
AND a.stat_code<>7
AND (SELECT NVL(max(date),TO_DATE('01-JAN-1990','DD-MON-YYYY'))
       FROM table2 c
       WHERE c.id=b.id
         AND c.act_code in ('A', 'V', 'W', 'J')
         AND c.trans IN (109, 154, 982, 745)) <  TO_DATE('01-OCT-1990','DD-MON-YYYY');
</code>```

Body:
I need to select criteria based on inclusions and exclusions of the same attributes and on different dates and I am having a hard time wrapping my head around how to do this.  Here is a list of my criteria.

The record was first added to the database with a transaction of 222 or 223 and an activity code of ‘A’.

The record does not have a status code of 7

Any records where the latest activity code (A, V, W, J) for the following transactions (109, 154, 982, 745) after 10/01/2009 should not be included in the results,

There are 2 tables involved with a join on the employee ID.

Table 1:

|id  |  statcode
|  1     |  1
|  2     |  3
|  3     |  7
|  4     |  2

Table 2:

|id       |  date      | act_code   |  trans
|   1     |  1/1/17    |   Z        |    109
|   1     |  3/4/12    |   A        |    222
|   1     |  2/14/09   |   A        |    154
|   2     |  1/1/17    |   A        |    223
|   2     |  6/6/13    |   V        |    109
|   3     |  11/23/14  |   A        |    222
|   4     |  12/13/16  |   X        |    154
|   4     |  11/23/14  |   W        |    223

What I’d like to return is:

|    id  | statcode|  date      | act_code   |  trans
|   1    |   1     |  3/4/12    |   A        |    222

ID 2 would not be selected because the first trans is not one of the correct values. ID 3 would not be included due to a incorrect status code. ID 4 would not be selected because the latest act_code is not one of the correct values. Anyone have an idea as to how to go about this? Thanks in advance.

edit: Here is the query as attempted. It seems to return everything.

SELECT *
FROM firsttable a
join secondtable b on a.id=b.id
where exists (select id, min(date) from
secondtable
where c.TRANS in ('222','223') and (TRANS NOT IN ('109', '154', '982',
'745')
AND ACT_CODE NOT IN  ('A', 'V', 'W', 'J') and date>= to_date('10/01/2009',
'MM/DD/YYYY'))
group by id)
and a.statcode <> '07'
;

Body:
Try This :

select Emp_id,statcode,date,act_code,trans
from table1 A join table2 b on (a.id=b.id)
WHERE b.trans in(222,223)
AND b.act_code='A'
AND a.stat_code<>7
AND (SELECT NVL(max(date),TO_DATE('01-JAN-1990','DD-MON-YYYY'))
       FROM table2 c
       WHERE c.id=b.id
         AND c.act_code in ('A', 'V', 'W', 'J')
         AND c.trans IN (109, 154, 982, 745)) <  TO_DATE('01-OCT-1990','DD-MON-YYYY');


问:
HTML Dropdown Menu very slow to load
I am working on a project for a client to make their roster viewing and entry paper-free. Some things rely on user input, but others are varied constants and are pulled from a database. One of the dropdowns pulling its information from said database is loading very slowly in my testing environment - I click it, and it takes two to three seconds for the items to actually show up.

I assume this is because the dropdown contains easily close to 400 items. What I'd like to know is if there is any way I can optimize this to make the loading faster. Cutting off at halfway or even a fourth of the way and making more dropdowns is outside of specification for the project, so a suggestion like that would have to go through the client for the go ahead. If that's the only solution, though, I'll do that.

Thanks in advance for suggestions.

EDIT:

This is the kind of oversight that makes me laugh, but I was wrong about my conservative estimate of 400 items - the list contains 12,700 items.

For all who assume the SQL query may be slow - I am doing a simple SELECT DISTINCT from one table, with only one WHERE condition.

答:
Before this question can be answered well, you'll need to do more testing and debugging to figure out what exactly is slowing things down.

Is this just a problem with your machine running something slowly?
Test things out on a real webserver and see how things go.

Is the select from the database slow? If so, that's a problem,
selects from mysql should be really fast.

Is the php slow? If so, you can use an IDE like PhpStorm to see
exactly what functions take how long to run.

Is the rendering in the client browser slow? If so, we can look at
optimizing the javascript/html.

As noted in a comment above, we also need to know when you are getting data from the database (before the page loads, or ajax). So before you can really look at how to speed this up, you need to know what is taking so long. Start there. Also make sure to check your javascript and html for any errors. Copy/paste the entire page's html into here, and fix all errors and warnings: http://validator.w3.org/#validate_by_input  For javascript, check the debugger console.

Title: HTML Dropdown Menu very slow to load


问:
How to use lxml to find element text in XHTML document
I've been bashing my head at this for ages, I must be doing something stupid.

I am trying to retrieve all of the possible Wikipedia supported languages and output them to a text file by traversing the tables on List_of_Wikipedias.

Here is my python code so far, which is simply trying to retrieve one of the tables:

```<code>import httplib
from lxml import etree

def main():
    conn = httplib.HTTPConnection("meta.wikimedia.org")
    conn.request("GET","/wiki/List_of_Wikipedias")
    res = conn.getresponse()
    root = etree.fromstring(res.read())
    table = root.xpath('//table')
    print table

main()
</code>```

On my machine this only prints an empty list.  To increase speed I cached the page locally and used:

```<code>wikipage = open("wikipage.html")
root = lxml.parse(wikipage)
</code>```

but this makes no impact whatsoever (other than the obvious speedup).  I have also tried

```<code>lxml.find('table')
</code>```

and:

```<code>for element in root.iter():
    print("%s - %s" % (element.tag, element.text))
</code>```

which successfully prints out all of the elements, so I know the tree is being created.

What am I doing wrong?

Any help would be appreciated.
Thanks.

答:
XPath requires namespaces. The page you have downloaded starts:

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" dir="ltr">
</code>```

So you actually want

```<code>xpath('//html:table')
</code>```

where html is the prefix bound to "http://www.w3.org/1999/xhtml"

You will have to find out how to bind namespaces in lxml - I am not a python expert.

If this is your problem I sympathize - it has caught me and many others out!

ContentLicense: CC BY-SA 2.5

Body:
I've been bashing my head at this for ages, I must be doing something stupid.

I am trying to retrieve all of the possible Wikipedia supported languages and output them to a text file by traversing the tables on List_of_Wikipedias.

Here is my python code so far, which is simply trying to retrieve one of the tables:

import httplib
from lxml import etree

def main():
    conn = httplib.HTTPConnection("meta.wikimedia.org")
    conn.request("GET","/wiki/List_of_Wikipedias")
    res = conn.getresponse()
    root = etree.fromstring(res.read())
    table = root.xpath('//table')
    print table

main()

On my machine this only prints an empty list.  To increase speed I cached the page locally and used:

wikipage = open("wikipage.html")
root = lxml.parse(wikipage)

but this makes no impact whatsoever (other than the obvious speedup).  I have also tried

lxml.find('table')

and:

for element in root.iter():
    print("%s - %s" % (element.tag, element.text))

which successfully prints out all of the elements, so I know the tree is being created.

What am I doing wrong?

Any help would be appreciated.
Thanks.

Body:
XPath requires namespaces. The page you have downloaded starts:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" dir="ltr">

So you actually want

xpath('//html:table')

where html is the prefix bound to "http://www.w3.org/1999/xhtml"

You will have to find out how to bind namespaces in lxml - I am not a python expert.

If this is your problem I sympathize - it has caught me and many others out!


问:
how to execute multiple conditions with try/catch in selenium webdriver
I am trying to execute a code that should give the output after verifying if any of the 6 conditions I define.
Is there any other way I can achieve that with try/catch method. Any other method is also appreciated.
This is the code I came up with so far:-

```<code> try {
         if(drv.findElement(By.id("errorExplanation"))!= null){

          System.out.println("Email already present");
                }
         }

         catch (Exception e) {
          if(drv.findElement(By.xpath("//*[@id='new_spree_user']/div[2]/div[4]/span"))!= null){

                  System.out.println("Issue in Email");
              }
         }

         try {
             if(drv.findElement(By.xpath("//*[@id='password-credentials']/span"))!=null){
                 System.out.println("Issue in Password");
             }
         }

         catch (Exception e) {
            if(drv.findElement(By.xpath("//*[@id='errorExplanation']/ul/li[2]"))!= null){
                System.out.println("Empty Password");
            }
            }
</code>```

Any help is greatly appreciated.

答:
driver.findElement() will not return null if no element is found so your condition that checks that is not necessary. If no element is found, an exception is thrown which you are catching. You can avoid all the try/catches by using .findElements() (note the plural). If the element is not found, an empty list will be returned. You can then check for an empty list and avoid all the exceptions.

For example, here are the first couple... I'll let you do the rest.

```<code>if (!driver.findElements(By.id("errorExplanation")).isEmpty())
{
    System.out.println("Email already present");
}
if (!driver.findElements(By.xpath("//*[@id='new_spree_user']/div[2]/div[4]/span")).isEmpty())
{
    System.out.println("Issue in Email");
}
</code>```

Body:
I am trying to execute a code that should give the output after verifying if any of the 6 conditions I define.
Is there any other way I can achieve that with try/catch method. Any other method is also appreciated.
This is the code I came up with so far:-

 try {
         if(drv.findElement(By.id("errorExplanation"))!= null){

          System.out.println("Email already present");
                }
         }

         catch (Exception e) {
          if(drv.findElement(By.xpath("//*[@id='new_spree_user']/div[2]/div[4]/span"))!= null){

                  System.out.println("Issue in Email");
              }
         }

         try {
             if(drv.findElement(By.xpath("//*[@id='password-credentials']/span"))!=null){
                 System.out.println("Issue in Password");
             }
         }

         catch (Exception e) {
            if(drv.findElement(By.xpath("//*[@id='errorExplanation']/ul/li[2]"))!= null){
                System.out.println("Empty Password");
            }
            }

Any help is greatly appreciated.

Body:
driver.findElement() will not return null if no element is found so your condition that checks that is not necessary. If no element is found, an exception is thrown which you are catching. You can avoid all the try/catches by using .findElements() (note the plural). If the element is not found, an empty list will be returned. You can then check for an empty list and avoid all the exceptions.

For example, here are the first couple... I'll let you do the rest.

if (!driver.findElements(By.id("errorExplanation")).isEmpty())
{
    System.out.println("Email already present");
}
if (!driver.findElements(By.xpath("//*[@id='new_spree_user']/div[2]/div[4]/span")).isEmpty())
{
    System.out.println("Issue in Email");
}


问:
Iframe Resizer - works on some pages but not others
I've tried all the troubleshooting suggestions, and I've got iFrameResizer working on other sites without any issues, but it's snagging on this one and I can't fathom out why. Weirdly, it works on the details page, but not on the listing page. Logging returns the

"hasn't responded in 5 seconds" message.

I've also tried all the various triggers ('max' etc.) none of them make a difference.

Example page where it doesn't work:
http://www.homesinfocus.co.uk/properties-to-let/

But on the details page, it does work:
http://www.homesinfocus.co.uk/property-details-let/?ID=790&LB=Let

I've made sure all the iFrames have unique IDs, and the listing page works okay for other sites, just can't see where the issue is with this one.

Any pointers would be much appreciated.

答:
The most common reason for that, is that the iframe hasn't loaded it's js file.

Also check that your using the very latest version, as the error message gives a bit more detail.


问:
Access to path denied on IIS
I'm trying to get my MVC app to write a simple text file to another server using System.IO.File.WriteAllText.  (A separate process is looking in that folder for text files to grab.)  It works fine when debugging on my local machine, but when deployed to IIS on a test server, I always get this error when trying to write the file:

Access to the path '\\server\C$\folder\subfolder\file.txt' is denied.

The answer to at least half a dozen similar questions here on SO was to give the application pool identity account access to that folder.  However, the app pool on IIS was already running under a service account that had full permissions to the desired folder but was still getting the error.  I even tried changing the app pool to my own account (the one used successfully in debugging) and still get the error.

Anonymous access is turned off, and Windows Authentication is turned on (part of the file.txt is info from the user's AD account).  I have tried accessing the app with several AD accounts, both with and without access to \\server\C$\folder\subfolder\ but they all give the same error.

I don't see how the app can be running under an authorized account, and the user can be logged in to the app with an authorized account, but still get the access denied error.  Is there any way to get more info about specifically what access is denied or which account is actually being denied? Anything else I'm missing here??

答:
You need to check whether other processes already have the file open, e.g, "A separate process is looking in that folder for text files to grab" - perhaps this separate process already has the file open and is therefore locking out your IIS process? Use Process Monitor (https://learn.microsoft.com/en-us/sysinternals/downloads/procmon) to monitor activity on the file.

Also you give the file location as '\server\C$\folder\subfolder\file.txt'. UNC paths normally begin with a '\\', e.g., '\\server\C$\folder\subfolder\file.txt'. That may just be an artefact of StackOverflow escaping the double slash to a single slash.

As a simple test, can you use notepad with your own account to open the file in the error message and write to the file? What if you use the application pool identity account?

Edit: You run Process Monitor on the server that has the file location. Add a Path filter like this:

```<code>Path   excludes    file.txt   then  Exclude
</code>```

Where file.txt is the file name (without the directory) of the file you are monitoring. This filter will only capture events for that file and will exclude everything else. Once an event occurs, right click it, and go to Properties, Process to see the User initiating the event.

Title: Access to path denied on IIS

Body:
You need to check whether other processes already have the file open, e.g, "A separate process is looking in that folder for text files to grab" - perhaps this separate process already has the file open and is therefore locking out your IIS process? Use Process Monitor (https://learn.microsoft.com/en-us/sysinternals/downloads/procmon) to monitor activity on the file.

Also you give the file location as '\server\C$\folder\subfolder\file.txt'. UNC paths normally begin with a '\\', e.g., '\\server\C$\folder\subfolder\file.txt'. That may just be an artefact of StackOverflow escaping the double slash to a single slash.

As a simple test, can you use notepad with your own account to open the file in the error message and write to the file? What if you use the application pool identity account?

Edit: You run Process Monitor on the server that has the file location. Add a Path filter like this:

Path   excludes    file.txt   then  Exclude

Where file.txt is the file name (without the directory) of the file you are monitoring. This filter will only capture events for that file and will exclude everything else. Once an event occurs, right click it, and go to Properties, Process to see the User initiating the event.


问:
Mockito - Verify all arguments exactly
How can I verify multiple calls to a method with different parameters, and also verify that no other parameters were given?

I know I can test for multiple arguments like this:

```<code>@Spy
SomeClass someClass

@Test
public void test() {
  someClass.triggerSomething();

  verify(someClass, times(1)).someMethod(1, 1);
  verify(someClass, times(1)).someMethod(2, 2);
  verify(someClass, times(1)).someMethod(3, 3);
  verify(someClass, times(1)).someMethod(4, 4);
  verify(someClass, times(1)).someMethod(5, 5);
}
</code>```

How do I verify that I haven't called it with any other combination of parameters?

答:
Use verifyNoMoreInteractions(someClass).

Checks if any of given mocks has any unverified interaction.

You can use this method after you verified your mocks - to make sure that nothing else was invoked on your mocks.

Title: Mockito - Verify all arguments exactly

Body:
How can I verify multiple calls to a method with different parameters, and also verify that no other parameters were given?

I know I can test for multiple arguments like this:

@Spy
SomeClass someClass

@Test
public void test() {
  someClass.triggerSomething();

  verify(someClass, times(1)).someMethod(1, 1);
  verify(someClass, times(1)).someMethod(2, 2);
  verify(someClass, times(1)).someMethod(3, 3);
  verify(someClass, times(1)).someMethod(4, 4);
  verify(someClass, times(1)).someMethod(5, 5);
}

How do I verify that I haven't called it with any other combination of parameters?


问:
Using only the sprite to draw
New to game development with SFML and really like it.

So far I'm trying to render a circle on a sprite, but somehow I only get a quarter of the circle meaning that the window is taken as surface when drawing instead of sprite. If I make the sprie size as the window, I'll see the full circle..

Here's my code:

```<code>#include <SFML/Window.hpp>
#include <SFML/Graphics.hpp>

const char *glsl = R"(
    #version 330 core
    uniform vec2 u_resolution;

    void main() {
        vec2 pos = gl_FragCoord.xy / u_resolution;

        float radius = 0.4;
        float d = smoothstep(radius + 0.01, radius, distance(pos, vec2(0.5)));

        gl_FragColor = vec4(d*0.0, d*0.5, d*1.0, 1.0);
    }
)";

int main() {
    sf::RenderWindow window(sf::VideoMode(800, 600), "GLSL", sf::Style::Default);

    sf::Texture tex;
    tex.create(800 / 2, 600 /2); // or tex.create(800, 600); for full window surface
    sf::Sprite spr(tex);

    sf::Shader shader;
    shader.loadFromMemory(glsl, sf::Shader::Fragment);
    shader.setUniform("u_resolution", sf::Vector2f(800, 600));

    while (window.isOpen()) {
        sf::Event event;
        while (window.pollEvent(event)) if(event.type == sf::Event::Closed) window.close();

        window.clear(sf::Color(244,244,244));

        window.draw(spr, &shader);
        window.display();
    }
}
</code>```

Any help would be appreciate. What I'm looking to achieve is to render the full circle in the sprite range. Thanks!

答: You take a quarter of the screen because you do tex.create(800 / 2, 600 /2); and your window size is sf::RenderWindow window(sf::VideoMode(800, 600) ...);. So it devide by the width and the height. Create a texture with the same size that your window and I think you'll be good (tex.create(800, 600);).

Title: Using only the sprite to draw

Body:
New to game development with SFML and really like it.

So far I'm trying to render a circle on a sprite, but somehow I only get a quarter of the circle meaning that the window is taken as surface when drawing instead of sprite. If I make the sprie size as the window, I'll see the full circle..

Here's my code:

#include <SFML/Window.hpp>
#include <SFML/Graphics.hpp>

const char *glsl = R"(
    #version 330 core
    uniform vec2 u_resolution;

    void main() {
        vec2 pos = gl_FragCoord.xy / u_resolution;

        float radius = 0.4;
        float d = smoothstep(radius + 0.01, radius, distance(pos, vec2(0.5)));

        gl_FragColor = vec4(d*0.0, d*0.5, d*1.0, 1.0);
    }
)";

int main() {
    sf::RenderWindow window(sf::VideoMode(800, 600), "GLSL", sf::Style::Default);

    sf::Texture tex;
    tex.create(800 / 2, 600 /2); // or tex.create(800, 600); for full window surface
    sf::Sprite spr(tex);

    sf::Shader shader;
    shader.loadFromMemory(glsl, sf::Shader::Fragment);
    shader.setUniform("u_resolution", sf::Vector2f(800, 600));

    while (window.isOpen()) {
        sf::Event event;
        while (window.pollEvent(event)) if(event.type == sf::Event::Closed) window.close();

        window.clear(sf::Color(244,244,244));

        window.draw(spr, &shader);
        window.display();
    }
}

Any help would be appreciate. What I'm looking to achieve is to render the full circle in the sprite range. Thanks!


问:
What is the default path in .desktop files and how to change?
I am installing a package manually on my own system because I need to make some changes to it that aren't available in the basic version in my package manager. I also am trying to keep packages installed locally if possible, so I'm installing it with prefix=$HOME/.local instead of the more common prefix=/usr/local.

When I do this, I have no problem executing the program from my terminal, because I added ~/.local/bin to my PATH and the package was installed with relative paths to its shared libraries (i.e. ~/.local/lib/<package>). Executing from the command line is no problem, but I want to be able to access it from the favorites menu in gnome, and for that I need to make use of the <package>.desktop file.

I could hard-code the path to the executable in the .desktop file itself, but when I pull a later version down and re-install it, I'll have to redo those steps. I was wondering if there's a way to avoid that.

I've tried symlinking the executable to a directory where .desktop files do have included in their path, and the application is correctly treated as a GUI option, but launching the executable results in an error trying to find a shared library. I think this has to do with how cmake handles rpaths, which to my understanding is a way of relatively linking executables with their required libraries.

I think what I want to do is have PATH inside a .desktop file include ~/.local/bin, without changing the .desktop file itself. Can I alter the 'default' path used in accessing a .desktop file?

答:
The answer to my question was found in the Archwiki:

Specifically, I needed to add ~/.local/bin to my path in ~/.xinitrc. Now my graphical programs work as expected.


问:
Opening URL from link into iframe

I have iframe created and it has no src at the beginning. When I click on a link, for example, the result from Google search, that link should try to open in that iframe. Not in the tab that I am currently browsing.

```<code>$(document).ready(function () {

    $('<div />', {
        id: 'firster',
        style: 'position: fixed; top: 0; bottom: 0; right: 0; max-width: 500px; z-index: 120;'
    }).appendTo('body');

    $('<iframe />', {
            name: 'frame1',
            id: 'frame1',
            src: ''
        })
        .css({
            'height': '100%',
            'width': '450px'
    }).appendTo('#firster');

    $("a").click(function(e) {
        $("#frame1").attr("src", window.location.protocol + '//' + window.location.host +  $(this).attr("href"));
        return false;
    })

});
</code>```

What I expect is to open that url ( I concated the protocol host and url ), it just does not open.

Element status before clicking on link:

And element status after clicking on link:

How to fix this? Any way around it?

Edit part:

This is what im getting periodically in console:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading
  the remote resource at
  https://accounts.google.com/ServiceLogin?passive=1209600&osid=1&continue=https://notifications.google.com/u/0//idv2&followup=https://notifications.google.com/u/0//idv2&authuser=0.
  (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).

答:
you can simply achieve it in html

here try this

```<code><iframe height="300px" width="100%" src="" name="iframe_a"></iframe>

<p><a href="https://www.stackoverflow.com" target="iframe_a">stackoverflow.com</a></p>
</code>```

you cant get to target because. it writes src as "yourwebsie.com+src"

in jquery:

```<code>  $(document).ready(function(){
    $("a").click(function(){
    var k=$(this).attr("src"))
        $("iframe").attr("src",k);
    });
});
</code>```

javascript method:

```<code><script>
 function loadIframe(iframeName, url) {
    if ( window.frames[iframeName] ) {
        window.frames[iframeName].location = url;
        return false;
    }
    return true;
}</script>

<a href="link" onclick="return loadIframe('ifrm', this.href)">whasjjjf</a>
    <iframe name="ifrm" id="ifrm" src="tabs.html" frameborder="0">
    Your browser doesn't support iframes.</iframe>
</code>```

Title: Opening URL from link into iframe

Body:
I have iframe created and it has no src at the beginning. When I click on a link, for example, the result from Google search, that link should try to open in that iframe. Not in the tab that I am currently browsing.

$(document).ready(function () {

    $('
', {
        id: 'firster',
        style: 'position: fixed; top: 0; bottom: 0; right: 0; max-width: 500px; z-index: 120;'
    }).appendTo('body');

    $('', {
            name: 'frame1',
            id: 'frame1',
            src: ''
        })
        .css({
            'height': '100%',
            'width': '450px'
    }).appendTo('#firster');

    $("a").click(function(e) {
        $("#frame1").attr("src", window.location.protocol + '//' + window.location.host +  $(this).attr("href"));
        return false;
    })

});

What I expect is to open that url ( I concated the protocol host and url ), it just does not open.

Element status before clicking on link:

And element status after clicking on link:

How to fix this? Any way around it?

Edit part:

This is what im getting periodically in console:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading
  the remote resource at
  https://accounts.google.com/ServiceLogin?passive=1209600&osid=1&continue=https://notifications.google.com/u/0//idv2&followup=https://notifications.google.com/u/0//idv2&authuser=0.
  (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).

Body:
you can simply achieve it in html

here try this

<iframe height="300px" width="100%" src="" name="iframe_a"></iframe>

<p><a href="https://www.stackoverflow.com" target="iframe_a">stackoverflow.com</a></p>

you cant get to target because. it writes src as "yourwebsie.com+src"

in jquery:

  $(document).ready(function(){
    $("a").click(function(){
    var k=$(this).attr("src"))
        $("iframe").attr("src",k);
    });
});

javascript method:

<script>
 function loadIframe(iframeName, url) {
    if ( window.frames[iframeName] ) {
        window.frames[iframeName].location = url;
        return false;
    }
    return true;
}</script>

<a href="link" onclick="return loadIframe('ifrm', this.href)">whasjjjf</a>
    <iframe name="ifrm" id="ifrm" src="tabs.html" frameborder="0">
    Your browser doesn't support iframes.</iframe>


问:
How to build a model in MXNet using matrices and matrix operations explicitly?
I can create a model using the pre-build high-level functions like FullyConnected. For example:

```<code>X = mx.sym.Variable('data')
P  = mx.sym.FullyConnected(data = X, name = 'fc1', num_hidden = 2)
</code>```

In this way I get a symbolic variable P that is dependent on the symbolic variable X. In other words, I have computational graph that can be used to define a model and execute such operations as fit and predict.

Now, I would like to express P through X in a different way. In more detail, instead of using the high-level functionality (like FullyConnected), I would like to specify relations between P and X "explicitly", using low-level tensor operations (like matrix multiplication) and symbolic variables representing model parameters (lake weight matrix).

For example to achieve the same as above, I have tried the followig:

```<code>W = mx.sym.Variable('W')
B = mx.sym.Variable('B')
P = mx.sym.broadcast_plus(mx.sym.dot(X, W), B)
</code>```

However, P obtained this way is not equivalent to P obtained earlier. I cannot use it the same way. In particular, as far as I understand, MXNet is complaining that W and B do not have values (which makes sense).

I have also tried to declare W and B in another way (so that they do have values):

```<code>w = np.array([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]])
b = np.array([7.0, 8.0])

W = mx.nd.array(w)
B = mx.nd.array(b)
</code>```

It does not work as well. I guess that MXNet complains because it expects a symbolic variable but it gets nd-arrays instead.

So, my question is how to build a model using low-level tensor operations (like matrix multiplication) and explicit objects representing model parameters (like weight matrices).

答:
You might want to take a look at Gluon API. For example here is a guide for building MLP from scratch, including allocating the parameters:

```<code>#######################
#  Allocate parameters for the first hidden layer
#######################
W1 = nd.random_normal(shape=(num_inputs, num_hidden), scale=weight_scale, ctx=model_ctx)
b1 = nd.random_normal(shape=num_hidden, scale=weight_scale, ctx=model_ctx)

params = [W1, b1, ...]
</code>```

Attaching them to the automatic gradient

```<code>for param in params:
    param.attach_grad()
</code>```

Define the model:

```<code>def net(X):
    #######################
    #  Compute the first hidden layer
    #######################
    h1_linear = nd.dot(X, W1) + b1
    ...
</code>```

and execute it

```<code>epochs = 10
learning_rate = .001
smoothing_constant = .01

for e in range(epochs):
    ...
    for i, (data, label) in enumerate(train_data):
        data = data.as_in_context(model_ctx).reshape((-1, 784))
        label = label.as_in_context(model_ctx)
        ...
        with autograd.record():
            output = net(data)
            loss = softmax_cross_entropy(output, label_one_hot)
        loss.backward()
        SGD(params, learning_rate)
</code>```

You can see the full example in the straight dope:

http://gluon.mxnet.io/chapter03_deep-neural-networks/mlp-scratch.html

Body:
I can create a model using the pre-build high-level functions like FullyConnected. For example:

X = mx.sym.Variable('data')
P  = mx.sym.FullyConnected(data = X, name = 'fc1', num_hidden = 2)

In this way I get a symbolic variable P that is dependent on the symbolic variable X. In other words, I have computational graph that can be used to define a model and execute such operations as fit and predict.

Now, I would like to express P through X in a different way. In more detail, instead of using the high-level functionality (like FullyConnected), I would like to specify relations between P and X "explicitly", using low-level tensor operations (like matrix multiplication) and symbolic variables representing model parameters (lake weight matrix).

For example to achieve the same as above, I have tried the followig:

W = mx.sym.Variable('W')
B = mx.sym.Variable('B')
P = mx.sym.broadcast_plus(mx.sym.dot(X, W), B)

However, P obtained this way is not equivalent to P obtained earlier. I cannot use it the same way. In particular, as far as I understand, MXNet is complaining that W and B do not have values (which makes sense).

I have also tried to declare W and B in another way (so that they do have values):

w = np.array([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]])
b = np.array([7.0, 8.0])

W = mx.nd.array(w)
B = mx.nd.array(b)

It does not work as well. I guess that MXNet complains because it expects a symbolic variable but it gets nd-arrays instead.

So, my question is how to build a model using low-level tensor operations (like matrix multiplication) and explicit objects representing model parameters (like weight matrices).

Body:
You might want to take a look at Gluon API. For example here is a guide for building MLP from scratch, including allocating the parameters:

#######################
#  Allocate parameters for the first hidden layer
#######################
W1 = nd.random_normal(shape=(num_inputs, num_hidden), scale=weight_scale, ctx=model_ctx)
b1 = nd.random_normal(shape=num_hidden, scale=weight_scale, ctx=model_ctx)

params = [W1, b1, ...]

Attaching them to the automatic gradient

for param in params:
    param.attach_grad()

Define the model:

def net(X):
    #######################
    #  Compute the first hidden layer
    #######################
    h1_linear = nd.dot(X, W1) + b1
    ...

and execute it

epochs = 10
learning_rate = .001
smoothing_constant = .01

for e in range(epochs):
    ...
    for i, (data, label) in enumerate(train_data):
        data = data.as_in_context(model_ctx).reshape((-1, 784))
        label = label.as_in_context(model_ctx)
        ...
        with autograd.record():
            output = net(data)
            loss = softmax_cross_entropy(output, label_one_hot)
        loss.backward()
        SGD(params, learning_rate)

You can see the full example in the straight dope:

http://gluon.mxnet.io/chapter03_deep-neural-networks/mlp-scratch.html


问:
Getting JSON and cross to another class in AsyckTask
I'm trying to receive JSON from sever and continue to another class, but can't, not working, this how to look my code

class when I click button:

```<code>public void onHistoryCheckIn(View view) {
  String nCar = numberCar; // to send number car for receive all data json
  String type = "historyChckIn";
  PreHistoryCheckIn preHistoryCheckIn = new PreHistoryCheckIn(this);
  preHistoryCheckIn.execute(type,nCar); // send the data to recieve json
}
</code>```

Know I go to doInBackground, and I use the onPostExecute

```<code>protected void onPostExecute(String s) {
  // jsonResult ==> I NEED THE DATA!!!
  Intent intent = new Intent(context, HistoryCheckIn.class); // have Damage
  context.startActivity(intent);
  // alertDialog.setMessage(jsonResult);
  // alertDialog.show();
}
</code>```

I come to class HistoryCheckIn but without JSON, what I can do?

I want to bring jsonResult and I want to come to HistoryCheckIn.class

答:
You have to set the result as an extra to the Intent e.g.

```<code>protected void onPostExecute(String s) {
    Intent intent = new Intent(context, HistoryCheckIn.class);
    intent.putExtra("result", s);
    context.startActivity(intent);
}
</code>```

and retrieve it by calling in HistoryCheckIn

```<code>String jsonResult = getIntent().getStringExtra("result");
</code>```

Body:
I'm trying to receive JSON from sever and continue to another class, but can't, not working, this how to look my code

class when I click button:

public void onHistoryCheckIn(View view) {
  String nCar = numberCar; // to send number car for receive all data json
  String type = "historyChckIn";
  PreHistoryCheckIn preHistoryCheckIn = new PreHistoryCheckIn(this);
  preHistoryCheckIn.execute(type,nCar); // send the data to recieve json
}

Know I go to doInBackground, and I use the onPostExecute

protected void onPostExecute(String s) {
  // jsonResult ==> I NEED THE DATA!!!
  Intent intent = new Intent(context, HistoryCheckIn.class); // have Damage
  context.startActivity(intent);
  // alertDialog.setMessage(jsonResult);
  // alertDialog.show();
}

I come to class HistoryCheckIn but without JSON, what I can do?

I want to bring jsonResult and I want to come to HistoryCheckIn.class

Body:
You have to set the result as an extra to the Intent e.g.

protected void onPostExecute(String s) {
    Intent intent = new Intent(context, HistoryCheckIn.class);
    intent.putExtra("result", s);
    context.startActivity(intent);
}

and retrieve it by calling in HistoryCheckIn

String jsonResult = getIntent().getStringExtra("result");


问:
Ajax Call json_encode don't work
I hava a problem with my ajax call and the json response. The console tell me that my php file don't return a json format but i don't understand why. Here is my ajax function :

        function showEspece(espece, categorie, object)
  {
    $.ajax({
      type : 'POST',
      url: 'getespece.php',
      data: {espece: espece, categorie: categorie },
      dataType: 'json',
      success: function(data)
      {
        alert(data);
        var tableau = data;
        $('#output').html(tableau);
      },
      error: function(xhr, status, error) {
        console.log(xhr.responseText);
        console.log(error);
      }
    });
  }```
</div>
</div>
</p>

<p>And here is the php page call by the ajax function : </p>

```<?php
header('Content-type: application/json');
include("includes/connexionBD.php");

$requete = oci_parse($connect, "SELECT nomA, sexe, datenaissance FROM Animal WHERE categorie = '".$_POST['categorie']."' AND espece = '".$_POST['espece']."' ");

oci_execute($requete);

$test = oci_fetch_all($requete, $res);
$test1 = array();
$test1 = var_dump($res);

    echo json_encode($test1);
```

<p>?></p>

<p>My problem is that the ajax function always go to error and here is what i can read in the console : </p>

```    array(3) {
  ["NOMA"]=>
  array(3) {
    [0]=>
    string(6) "Chachi"
    [1]=>
    string(6) "Rafiki"
    [2]=>
    string(6) "Chakra"
  }
  ["SEXE"]=>
  array(3) {
    [0]=>
    string(1) "F"
    [1]=>
    string(1) "M"
    [2]=>
    string(1) "F"
  }
  ["DATENAISSANCE"]=>
  array(3) {
    [0]=>
    string(9) "05-MAY-15"
    [1]=>
    string(9) "07-JAN-15"
    [2]=>
    string(9) "17-SEP-17"
  }
}
null

SyntaxError: Unexpected token a in JSON at position 0
at parse (<anonymous>)
at Qb (jQuery.js:4)
at A (jQuery.js:4)
at XMLHttpRequest.<anonymous> (jQuery.js:4)
```

I have pass the day on it and i don't understand why it don't work. Can anyone help me ?

答:
You are using var_dump() wich does not return anything, but sends a string representation of the variable to the stdout. This is exactly what you are getting.

You can just encode the result of your oci_fetch_all query and send that as a json. The test variables in your code are not needed.

```<code><?php

    header('Content-type: application/json');
    include("includes/connexionBD.php");

    $requete = oci_parse($connect, "SELECT nomA, sexe, datenaissance FROM Animal WHERE categorie = '".$_POST['categorie']."' AND espece = '".$_POST['espece']."' ");

    oci_execute($requete);

    oci_fetch_all($requete, $res);
    echo json_encode($res);
</code>```

Title: Ajax Call json_encode don't work

Body:
I hava a problem with my ajax call and the json response. The console tell me that my php file don't return a json format but i don't understand why. Here is my ajax function :

        function showEspece(espece, categorie, object)
  {
    $.ajax({
      type : 'POST',
      url: 'getespece.php',
      data: {espece: espece, categorie: categorie },
      dataType: 'json',
      success: function(data)
      {
        alert(data);
        var tableau = data;
        $('#output').html(tableau);
      },
      error: function(xhr, status, error) {
        console.log(xhr.responseText);
        console.log(error);
      }
    });
  }

And here is the php page call by the ajax function :

<?php
header('Content-type: application/json');
include("includes/connexionBD.php");

$requete = oci_parse($connect, "SELECT nomA, sexe, datenaissance FROM Animal WHERE categorie = '".$_POST['categorie']."' AND espece = '".$_POST['espece']."' ");

oci_execute($requete);

$test = oci_fetch_all($requete, $res);
$test1 = array();
$test1 = var_dump($res);

    echo json_encode($test1);

?>

My problem is that the ajax function always go to error and here is what i can read in the console :

    array(3) {
  ["NOMA"]=>
  array(3) {
    [0]=>
    string(6) "Chachi"
    [1]=>
    string(6) "Rafiki"
    [2]=>
    string(6) "Chakra"
  }
  ["SEXE"]=>
  array(3) {
    [0]=>
    string(1) "F"
    [1]=>
    string(1) "M"
    [2]=>
    string(1) "F"
  }
  ["DATENAISSANCE"]=>
  array(3) {
    [0]=>
    string(9) "05-MAY-15"
    [1]=>
    string(9) "07-JAN-15"
    [2]=>
    string(9) "17-SEP-17"
  }
}
null

SyntaxError: Unexpected token a in JSON at position 0
at parse (<anonymous>)
at Qb (jQuery.js:4)
at A (jQuery.js:4)
at XMLHttpRequest.<anonymous> (jQuery.js:4)

I have pass the day on it and i don't understand why it don't work. Can anyone help me ?

Body:
You are using var_dump() wich does not return anything, but sends a string representation of the variable to the stdout. This is exactly what you are getting.

You can just encode the result of your oci_fetch_all query and send that as a json. The test variables in your code are not needed.

<?php

    header('Content-type: application/json');
    include("includes/connexionBD.php");

    $requete = oci_parse($connect, "SELECT nomA, sexe, datenaissance FROM Animal WHERE categorie = '".$_POST['categorie']."' AND espece = '".$_POST['espece']."' ");

    oci_execute($requete);

    oci_fetch_all($requete, $res);
    echo json_encode($res);


问:
SQLite unrecognized token error while inserting protobuf: Which tokens to be handled & How?
I am using sqlite3_exec() function for executing the queries. I am aware that as per below post, it's better to use _prepare, _bind, _step, _finalize combination for various benefits.

sqllite query with encrypted std::string (unrecognized token)

However, in my case I already have a library in place, which is tightly coupled around sqlite3_exec() and it will be difficult to change. Even for education purpose, I would like to know, how can I enter special tokens inside an sqlite3 database. Currently I am programatically reading this statement from a file using C++ and inserting into the DB using sqlite3_exec()

Currently, following statement is giving error:

```<code>INSERT INTO Convey(username, data, id, type)
VALUES('12345', '^Z^Dfine* ^HºÉÙ<98>ö÷×^B2^@', 'abcd', 31);
</code>```

The error comes at this symbol ^@ as SQL error: unrecognized token:. When I dismantled the statement and checked ascii for each characters, it showed 0 in place of ^@. The type of data, be it TEXT or BLOB doesn't make a difference.

Note that, the "data", I am trying to enter here is a Google protobuf message in a serialised form.

What is the correct way to escape such "nul" like characters in sqlite, when one has to use sqlite3_exec()?

[Note: 1 way is to replace 0 with some pre-defined pattern, which less likely to be found in binary strings and then restore them while reading it. I am open to this solution as well.]

答:
The character with value zero is not a valid UTF-8 character, so it cannot be written directly in SQL.

Just for the record: you should use parameters.
But if you want to do this in SQL, you have to write a blob literal:

```<code>... VALUES('12345', x'1A0466696E652A2008BAC9D998F6F7D7023200', 'abcd', 31);
</code>```

Body:
I am using sqlite3_exec() function for executing the queries. I am aware that as per below post, it's better to use _prepare, _bind, _step, _finalize combination for various benefits.

sqllite query with encrypted std::string (unrecognized token)

However, in my case I already have a library in place, which is tightly coupled around sqlite3_exec() and it will be difficult to change. Even for education purpose, I would like to know, how can I enter special tokens inside an sqlite3 database. Currently I am programatically reading this statement from a file using C++ and inserting into the DB using sqlite3_exec()

Currently, following statement is giving error:

INSERT INTO Convey(username, data, id, type)
VALUES('12345', '^Z^Dfine* ^HºÉÙ<98>ö÷×^B2^@', 'abcd', 31);

The error comes at this symbol ^@ as SQL error: unrecognized token:. When I dismantled the statement and checked ascii for each characters, it showed 0 in place of ^@. The type of data, be it TEXT or BLOB doesn't make a difference.

Note that, the "data", I am trying to enter here is a Google protobuf message in a serialised form.

What is the correct way to escape such "nul" like characters in sqlite, when one has to use sqlite3_exec()?

[Note: 1 way is to replace 0 with some pre-defined pattern, which less likely to be found in binary strings and then restore them while reading it. I am open to this solution as well.]

Body:
The character with value zero is not a valid UTF-8 character, so it cannot be written directly in SQL.

Just for the record: you should use parameters.
But if you want to do this in SQL, you have to write a blob literal:

... VALUES('12345', x'1A0466696E652A2008BAC9D998F6F7D7023200', 'abcd', 31);


问:
How to sum n % of values in Postgres
How to sum let's say 50 % of all values ordered by value in my Postgres table?

In table I have values 1, 2, 3, 4, 5, 6 and I'd like to get the sum of half values ordered by value DESC. So the result would be 4 + 5 + 6 = 15

Also, I might want to get only 1/3 of values so I would get 6 + 5 = 11

Is it possible with SQL in Postgres? Something like

```<code>SELECT sum(value)
FROM (
       SELECT value
       FROM table
       ORDER BY value DESC
       LIMIT 50%
     ) subquery
</code>```

答:
My version I came up with:

```<code>SELECT sum(value)
FROM (
       SELECT
         value,
         ntile(10)
         OVER (
           ORDER BY value DESC ) AS tile
       FROM t
     ) subquery
WHERE tile >= 10*0.5;
</code>```

That doesn't work for count of values < ntile's N but in the end I plan to use it for thousands of values

Title: How to sum n % of values in Postgres

Body:
How to sum let's say 50 % of all values ordered by value in my Postgres table?

In table I have values 1, 2, 3, 4, 5, 6 and I'd like to get the sum of half values ordered by value DESC. So the result would be 4 + 5 + 6 = 15

Also, I might want to get only 1/3 of values so I would get 6 + 5 = 11

Is it possible with SQL in Postgres? Something like

SELECT sum(value)
FROM (
       SELECT value
       FROM table
       ORDER BY value DESC
       LIMIT 50%
     ) subquery

Body:
My version I came up with:

SELECT sum(value)
FROM (
       SELECT
         value,
         ntile(10)
         OVER (
           ORDER BY value DESC ) AS tile
       FROM t
     ) subquery
WHERE tile >= 10*0.5;

That doesn't work for count of values < ntile's N but in the end I plan to use it for thousands of values


问:
angularjs how can pass multipul parameter to api
How can I pass mutipul parameters from angularjs -to WebAPi My Api as its Required two parameters

```<code>public IHttpActionResult GetData(int pagesize,int Totalpages){---}
</code>```

angularctrls.js

```<code>function GetData() {
        var PageDetails={
            'currentpage': $scope.currentPage,
            'pagesize':$scope.pagesize
        }
        HomeFactory.GetDat(PageDetails).then(function () {
        })
    }
</code>```

Factory.js

```<code> EmployeeServiceFactory.GetDat = function (PageDetails) {
        return $http({
            url:WebAPi+'Home/GetData/',
            method: 'GET',
            data: PageDetails,
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
        })
}
</code>```

Getting Error as

```<code>Failed to load http://localhost:3084/Home/GetData/%7B%22currentpage%22:1,%22pagesize%22:5%7D: No 'Access-Control-Allow-Origin' header is present on the requested resource
</code>```

答:
try params instead of data like below:

```<code>  EmployeeServiceFactory.GetDat = function (PageDetails) {
            return $http({
                url:WebAPi+'Home/GetData/',
                method: 'GET',
                params: PageDetails,
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
            })
    }
</code>```

Body:
How can I pass mutipul parameters from angularjs -to WebAPi My Api as its Required two parameters

public IHttpActionResult GetData(int pagesize,int Totalpages){---}

angularctrls.js

function GetData() {
        var PageDetails={
            'currentpage': $scope.currentPage,
            'pagesize':$scope.pagesize
        }
        HomeFactory.GetDat(PageDetails).then(function () {
        })
    }

Factory.js

 EmployeeServiceFactory.GetDat = function (PageDetails) {
        return $http({
            url:WebAPi+'Home/GetData/',
            method: 'GET',
            data: PageDetails,
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
        })
}

Getting Error as

Failed to load http://localhost:3084/Home/GetData/%7B%22currentpage%22:1,%22pagesize%22:5%7D: No 'Access-Control-Allow-Origin' header is present on the requested resource

Body:
try params instead of data like below:

  EmployeeServiceFactory.GetDat = function (PageDetails) {
            return $http({
                url:WebAPi+'Home/GetData/',
                method: 'GET',
                params: PageDetails,
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
            })
    }


问:
Do ping-pong at regular interval using Tornado websocket
I am new to Tornado server in python and trying to a ping-pong at regular interval to the clients connected.
I saw something called websocket_ping_interval in tornado documentation but couldn't find any example as to how/when to use it.

I did the below using ioloop.PeriodicCallback but doesn't seem to be doing any ping.

```<code>import tornado.web
from tornado import ioloop
from terminado import TermSocket, SingleTermManager
from tornado import websocket

# BaseWebSocketHandler removed, because we need to track all opened
# sockets in the class. You could change this later.
class MeterInfo(websocket.WebSocketHandler):
    """Establish an websocket connection and send meter readings."""
    opened_sockets = []
    previous_meter_reading = 0

    def open(self):
        self.write_message('Connection Established.')
        MeterInfo.opened_sockets.append(self)

    def on_close(self):
        """Close the connection."""
        self.write_message('bye')
        MeterInfo.opened_sockets.remove(self)

    @classmethod
    def try_send_new_reading(cls):
        """Send new reading to all connected clients"""
        new_reading = "text"

        if new_reading == cls.previous_meter_reading:
            return

        cls.previous_meter_reading = new_reading

        for socket in cls.opened_sockets:
            socket.write_message({'A': new_reading})

if __name__ == '__main__':
    term_manager = SingleTermManager(shell_command=['bash'])
    handlers = [
        (r"/websocket", TermSocket, {'term_manager': term_manager}),
        (r"/()", tornado.web.StaticFileHandler, {'path': 'index.html'}),
        (r"/(.*)", tornado.web.StaticFileHandler, {'path': '.'}),
    ]
    app = tornado.web.Application(handlers)
    app.listen(8010)
    METER_CHECK_INTERVAL = 100  # ms
    ioloop.PeriodicCallback(MeterInfo.try_send_new_reading,METER_CHECK_INTERVAL).start()
    ioloop.IOLoop.instance().start()
</code>```

All I need to do is to keep pinging the clients connected with something.

答:
websocket_ping_interval is an application setting, so you pass it to the Application constructor:

```<code>app = tornado.web.Application(handlers, websocket_ping_interval=10)
</code>```

Body:
I am new to Tornado server in python and trying to a ping-pong at regular interval to the clients connected.
I saw something called websocket_ping_interval in tornado documentation but couldn't find any example as to how/when to use it.

I did the below using ioloop.PeriodicCallback but doesn't seem to be doing any ping.

import tornado.web
from tornado import ioloop
from terminado import TermSocket, SingleTermManager
from tornado import websocket

# BaseWebSocketHandler removed, because we need to track all opened
# sockets in the class. You could change this later.
class MeterInfo(websocket.WebSocketHandler):
    """Establish an websocket connection and send meter readings."""
    opened_sockets = []
    previous_meter_reading = 0

    def open(self):
        self.write_message('Connection Established.')
        MeterInfo.opened_sockets.append(self)

    def on_close(self):
        """Close the connection."""
        self.write_message('bye')
        MeterInfo.opened_sockets.remove(self)

    @classmethod
    def try_send_new_reading(cls):
        """Send new reading to all connected clients"""
        new_reading = "text"

        if new_reading == cls.previous_meter_reading:
            return

        cls.previous_meter_reading = new_reading

        for socket in cls.opened_sockets:
            socket.write_message({'A': new_reading})

if __name__ == '__main__':
    term_manager = SingleTermManager(shell_command=['bash'])
    handlers = [
        (r"/websocket", TermSocket, {'term_manager': term_manager}),
        (r"/()", tornado.web.StaticFileHandler, {'path': 'index.html'}),
        (r"/(.*)", tornado.web.StaticFileHandler, {'path': '.'}),
    ]
    app = tornado.web.Application(handlers)
    app.listen(8010)
    METER_CHECK_INTERVAL = 100  # ms
    ioloop.PeriodicCallback(MeterInfo.try_send_new_reading,METER_CHECK_INTERVAL).start()
    ioloop.IOLoop.instance().start()

All I need to do is to keep pinging the clients connected with something.

Body:
websocket_ping_interval is an application setting, so you pass it to the Application constructor:

app = tornado.web.Application(handlers, websocket_ping_interval=10)


问:
How to create a class which restricts methods based on the input file? Creating a database API
This question is more about how one uses OOP to read in databases. SQLite and sqlite3 are simply examples to work with, and are not the main thrust of the question. (Arguably Python is only used here to explain my point):

I am creating a software package which allows users to query SQLite index files which have already been generated. It's basically syntactic to make it super user-friendly to query SQLite files indexed in a certain way, for a very particular case This should be quite straightforward, but I am somewhat confused how to "automatically" read in the SQLite

Here's an example (with pseudo-code):

```<code>import sqlite3

Class EasySQL:
    def __init__(self, filepath):
        self.filepath = filepath

    def connect(self, filepath):  ## perhaps this should be above in init?
        return sqlite3.connect(self.filepath)

    def query_indexA(self):
        ## query index A on SQLite3 connection

    def query_indexB(self):
        ## query index B on SQLite3 connection

    def query_indexC(self):
        ## query index C on SQLite3 connection

    def query_indexD(self):
        ## query index D on SQLite3 connection
</code>```

Here's my problem: users would have access to only two types of indexed SQLite files. The "Type 1" files are only indexed on A and B---indices C and D do not exist in this SQLite files, and should throw an error if users try to call these functions. The "Type 2" files are only indexed on C and D---indices A and B do not exist in this SQLite files, and should throw an error if users try to call these functions.

How do I "restrict" these methods such that if a user calls (for example) query_indexC on a "Type 1" SQLite file, there's an error?

I would strongly prefer not to force users to use two separate classes, as that is far too complicated, e.g. EasySQL_Type1() or EasySQL_Type2() A flag for which type would be ok though.

答:
If you can properly discern the type of file you can easily store that as internal reference and throw errors when trying to access 'invalid' indexes. You can also establish the connection to your SQLite file in the __init__() as, short of network drives, you won't need reconnection handling.

There are, of course, edge cases, but this should get you started:

```<code>import sqlite3

class EasySQL(object):

    def __init__(self, filepath, index_type=1):  # type 1 by default
        self.connection = sqlite3.connect(filepath)
        self.index_type = index_type

    def query_indexA(self):
        if self.index_type != 1:
            raise ValueError("indexA can only be queried by index type 1")
        # do your indexA processing... your DB is available in self.connection

    def query_indexB(self):
        if self.index_type != 1:
            raise ValueError("indexB can only be queried by index type 1")
        # do your indexB processing... your DB is available in self.connection

    def query_indexC(self):
        if self.index_type != 2:
            raise ValueError("indexC can only be queried by index type 2")
        # do your indexC processing... your DB is available in self.connection

    def query_indexD(self):
        if self.index_type != 2:
            raise ValueError("indexD can only be queried by index type 2")
        # do your indexD processing... your DB is available in self.connection
</code>```

Now your users can initiate it with:

```<code>type1_db = EasySQL("path/to/their/file.sqlite", 1)  # for type 1, or
type2_db = EasySQL("path/to/their/file.sqlite", 2)  # for type 2
</code>```

And if they attempt to use methods not associated with their types it will raise a ValueError. If you don't want to leave to the users to provide the type of their database file, you'll have to devise a way to determine it from the file itself (name, schema, whatever).

Body:
This question is more about how one uses OOP to read in databases. SQLite and sqlite3 are simply examples to work with, and are not the main thrust of the question. (Arguably Python is only used here to explain my point):

I am creating a software package which allows users to query SQLite index files which have already been generated. It's basically syntactic to make it super user-friendly to query SQLite files indexed in a certain way, for a very particular case This should be quite straightforward, but I am somewhat confused how to "automatically" read in the SQLite

Here's an example (with pseudo-code):

import sqlite3

Class EasySQL:
    def __init__(self, filepath):
        self.filepath = filepath

    def connect(self, filepath):  ## perhaps this should be above in init?
        return sqlite3.connect(self.filepath)

    def query_indexA(self):
        ## query index A on SQLite3 connection

    def query_indexB(self):
        ## query index B on SQLite3 connection

    def query_indexC(self):
        ## query index C on SQLite3 connection

    def query_indexD(self):
        ## query index D on SQLite3 connection

Here's my problem: users would have access to only two types of indexed SQLite files. The "Type 1" files are only indexed on A and B---indices C and D do not exist in this SQLite files, and should throw an error if users try to call these functions. The "Type 2" files are only indexed on C and D---indices A and B do not exist in this SQLite files, and should throw an error if users try to call these functions.

How do I "restrict" these methods such that if a user calls (for example) query_indexC on a "Type 1" SQLite file, there's an error?

I would strongly prefer not to force users to use two separate classes, as that is far too complicated, e.g. EasySQL_Type1() or EasySQL_Type2() A flag for which type would be ok though.

Body:
If you can properly discern the type of file you can easily store that as internal reference and throw errors when trying to access 'invalid' indexes. You can also establish the connection to your SQLite file in the __init__() as, short of network drives, you won't need reconnection handling.

There are, of course, edge cases, but this should get you started:

import sqlite3

class EasySQL(object):

    def __init__(self, filepath, index_type=1):  # type 1 by default
        self.connection = sqlite3.connect(filepath)
        self.index_type = index_type

    def query_indexA(self):
        if self.index_type != 1:
            raise ValueError("indexA can only be queried by index type 1")
        # do your indexA processing... your DB is available in self.connection

    def query_indexB(self):
        if self.index_type != 1:
            raise ValueError("indexB can only be queried by index type 1")
        # do your indexB processing... your DB is available in self.connection

    def query_indexC(self):
        if self.index_type != 2:
            raise ValueError("indexC can only be queried by index type 2")
        # do your indexC processing... your DB is available in self.connection

    def query_indexD(self):
        if self.index_type != 2:
            raise ValueError("indexD can only be queried by index type 2")
        # do your indexD processing... your DB is available in self.connection

Now your users can initiate it with:

type1_db = EasySQL("path/to/their/file.sqlite", 1)  # for type 1, or
type2_db = EasySQL("path/to/their/file.sqlite", 2)  # for type 2

And if they attempt to use methods not associated with their types it will raise a ValueError. If you don't want to leave to the users to provide the type of their database file, you'll have to devise a way to determine it from the file itself (name, schema, whatever).


问:
Finding time taken by the code
I am trying to find the time taken by memmove function in c using time.h library. However, When i execute the code, I get the value as zero. Any possible solution to find the time taken by the memmove function?</p>

```<code>void main(){
uint64_t start,end;
uint8_t a,b;
char source[5000];
char dest[5000];
uint64_t j=0;

for(j=0;j<5000;j++){
source[j]=j;
}

start=clock();
memmove(dest,source,5000);
end=clock();
printf("%f",((double)end-start));
}
</code>```

答:
As I write in my comment, memmoving 5000 bytes is far too fast to be mesurable with clock. If you do your memmove 100000 times, then it will get mesurable.

This code below gives an output of 12 on my computer. But this is platform dependent, the number you get on your computer might be quite different.

```<code>#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <time.h>

int main(void) {
  uint64_t start, end;
  char source[5000];
  char dest[5000];
  uint64_t j = 0;

  for (j = 0; j < 5000; j++) {
    source[j] = j;
  }

  start = clock();

  for (int i = 0; i < 100000; i++)
  {
    memmove(dest, source, 5000);
  }

  end = clock();
  printf("%lld", (end - start));  // no need to convert to double, (end - start)
                                  // is an uint64_t.
 }
</code>```

Title: Finding time taken by the code

Body:
I am trying to find the time taken by memmove function in c using time.h library. However, When i execute the code, I get the value as zero. Any possible solution to find the time taken by the memmove function?

void main(){
uint64_t start,end;
uint8_t a,b;
char source[5000];
char dest[5000];
uint64_t j=0;

for(j=0;j<5000;j++){
source[j]=j;
}

start=clock();
memmove(dest,source,5000);
end=clock();
printf("%f",((double)end-start));
}

Body:
As I write in my comment, memmoving 5000 bytes is far too fast to be mesurable with clock. If you do your memmove 100000 times, then it will get mesurable.

This code below gives an output of 12 on my computer. But this is platform dependent, the number you get on your computer might be quite different.

#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <time.h>

int main(void) {
  uint64_t start, end;
  char source[5000];
  char dest[5000];
  uint64_t j = 0;

  for (j = 0; j < 5000; j++) {
    source[j] = j;
  }

  start = clock();

  for (int i = 0; i < 100000; i++)
  {
    memmove(dest, source, 5000);
  }

  end = clock();
  printf("%lld", (end - start));  // no need to convert to double, (end - start)
                                  // is an uint64_t.
 }


问:
Copy one database in SQL Server 2016 to another in SQL Server 2012 using asp.net C#
I need to copy data from one database from SQL Server 2016 to another database in SQL Server 2012 using asp.net C#. How can I do it? Is it possible to copy data between two versions of SQL Server?</p>

答:
@jdweng is right. BulkCopy works well.

you can use a very good example in this link.


问:
Plot Integral trace in R
I would like to automate an analysis I have been doing with Graphpad Prism with R, but apparently it is harder than I thought.

I have Voltage~Time data that I would like to integrate and plot. In Graphpad Prism, this is performed by Analysis -> Integrate -> Create the Integral.

Here blow I plot the data in Prism and I plot the trace that I got from the Plot Integral command.

How can I do that with R?

The data I used are similar to these:

```<code>Time <- seq(1,100,1)
Voltage <- sample(1:1000,100, replace = F)
</code>```

I tried integrate(), but that requires a function to integrate, which I do not have, and gives me just a number.
I tried approxfun() and I could create a function of my data but again, as soon as I apply 'integrate()' I only got a single value.

Do you have any ideas on what the Graphpad Prism function does and how I can translate that to R?

Thank you for the help!

答:
With discrete values you can use cumsum:

```<code>set.seed(1)

Time <- seq(1,100,1)
Voltage <- sample(1:1000,100, replace = F)

df = data.frame(Time, Voltage)

library(ggplot2)
p1 <- ggplot(data = df)+
  geom_line(aes(x = Time, y = Voltage))

p2 <- ggplot(data = df)+
  geom_line(aes(x = Time, y = cumsum(Voltage)))

library(gridExtra)
grid.arrange(p1, p2)][1]][1]
</code>```

For unevenly spaced time values, you would want to calculate:

```<code>cumsum(df$Voltage[1:(nrow(df)-1)]) * diff(df$Time)
</code>```

Title: Plot Integral trace in R

Body:
I would like to automate an analysis I have been doing with Graphpad Prism with R, but apparently it is harder than I thought.

I have Voltage~Time data that I would like to integrate and plot. In Graphpad Prism, this is performed by Analysis -> Integrate -> Create the Integral.

Here blow I plot the data in Prism and I plot the trace that I got from the Plot Integral command.

How can I do that with R?

The data I used are similar to these:

Time <- seq(1,100,1)
Voltage <- sample(1:1000,100, replace = F)

I tried integrate(), but that requires a function to integrate, which I do not have, and gives me just a number.
I tried approxfun() and I could create a function of my data but again, as soon as I apply 'integrate()' I only got a single value.

Do you have any ideas on what the Graphpad Prism function does and how I can translate that to R?

Thank you for the help!

Body:
With discrete values you can use cumsum:

set.seed(1)

Time <- seq(1,100,1)
Voltage <- sample(1:1000,100, replace = F)

df = data.frame(Time, Voltage)

library(ggplot2)
p1 <- ggplot(data = df)+
  geom_line(aes(x = Time, y = Voltage))

p2 <- ggplot(data = df)+
  geom_line(aes(x = Time, y = cumsum(Voltage)))

library(gridExtra)
grid.arrange(p1, p2)][1]][1]

For unevenly spaced time values, you would want to calculate:

cumsum(df$Voltage[1:(nrow(df)-1)]) * diff(df$Time)


问:
MySql query returning all the data
I'm trying to use checkbox to look into my DB but i don't know why, the answer is made of all the data of the table and not the specific entry I want!

Code

```<code>$req_lieux = $sqlQuery->query("select lieux.nom from lieux, type_lieu WHERE lieux.id_type_lieu = type_lieu.ID");
</code>```

PHP code:

```<code><fieldset>
            <legend class="title-color-bloc">Couleur</legend>
            <?php
            require_once 'search.php';
            /* la requête est dans search.php */
            while ($couleurs = $query_check_color->fetch())
            {?>
            <input class="color-choice" type="checkbox" id="color-choice<?php echo $couleurs['ID']; ?>" name="color-choice[]" value="<?php echo $couleurs['ID']; ?>">
            <label for="color-choice<?php echo $couleurs['ID']; ?>"><?php echo $couleurs['couleur']; ?></label>
            <?php
            }
            $query_check_color->closeCursor();
            ?>
        </fieldset>
        <fieldset>
            <legend class="title-color-bloc">Lieux</legend>
            <?php
            /* la requête est dans search.php */
            while ($types = $query_check_types->fetch())
            {?>
                <input class="type-choice" type="checkbox" id="type-choice<?php echo $types['ID']; ?>" name="type-choice[]" value="<?php echo $types['ID']; ?>">
                <label for="type-choice<?php echo $types['ID']; ?>"><?php echo $types['libelle']; ?></label>
                <?php
            }
            $query_check_types->closeCursor();
            ?>
        </fieldset>
        <input type="submit" value="Afficher" class="submit-btn" name="submit-btn">
    </form>
    <?php
    if(isset($_POST))
    {
        if(!empty($_POST['type-choice']))
        {
            $type = implode("," , $_POST['type-choice']);
            while ($type = $req_lieux->fetch())
            { ?>
                <h1><?php echo $type['nom'] ?></h1>
            <?php }
        }
    }
    ?>
</code>```

Thanks for your help!

答:
You're not restricting the results of your query to any specific type.

```<code>select lieux.nom from lieux, type_lieu WHERE lieux.id_type_lieu = type_lieu.ID
</code>```

This query will select every record from lieux where a record exists in type_lieu.

So if you have a specific type_lieu you're trying to use then you do something like the following:

```<code>SELECT l.nom from lieux AS l INNER JOIN type_lieu AS tl ON l.id_type_lieu = tl.ID WHERE tl.type = xxxx
</code>```

Title: MySql query returning all the data

Body:
I'm trying to use checkbox to look into my DB but i don't know why, the answer is made of all the data of the table and not the specific entry I want!

Code

$req_lieux = $sqlQuery->query("select lieux.nom from lieux, type_lieu WHERE lieux.id_type_lieu = type_lieu.ID");

PHP code:

<fieldset>
            <legend class="title-color-bloc">Couleur</legend>
            <?php
            require_once 'search.php';
            /* la requête est dans search.php */
            while ($couleurs = $query_check_color->fetch())
            {?>
            <input class="color-choice" type="checkbox" id="color-choice<?php echo $couleurs['ID']; ?>" name="color-choice[]" value="<?php echo $couleurs['ID']; ?>">
            <label for="color-choice<?php echo $couleurs['ID']; ?>"><?php echo $couleurs['couleur']; ?>
            <?php
            }
            $query_check_color->closeCursor();
            ?>
        </fieldset>
        <fieldset>
            <legend class="title-color-bloc">Lieux</legend>
            <?php
            /* la requête est dans search.php */
            while ($types = $query_check_types->fetch())
            {?>
                <input class="type-choice" type="checkbox" id="type-choice<?php echo $types['ID']; ?>" name="type-choice[]" value="<?php echo $types['ID']; ?>">
                <label for="type-choice<?php echo $types['ID']; ?>"><?php echo $types['libelle']; ?>
                <?php
            }
            $query_check_types->closeCursor();
            ?>
        </fieldset>
        <input type="submit" value="Afficher" class="submit-btn" name="submit-btn">
    </form>
    <?php
    if(isset($_POST))
    {
        if(!empty($_POST['type-choice']))
        {
            $type = implode("," , $_POST['type-choice']);
            while ($type = $req_lieux->fetch())
            { ?>

<?php echo $type['nom'] ?>

            <?php }
        }
    }
    ?>

Thanks for your help!

Body:
You're not restricting the results of your query to any specific type.

select lieux.nom from lieux, type_lieu WHERE lieux.id_type_lieu = type_lieu.ID

This query will select every record from lieux where a record exists in type_lieu.

So if you have a specific type_lieu you're trying to use then you do something like the following:

SELECT l.nom from lieux AS l INNER JOIN type_lieu AS tl ON l.id_type_lieu = tl.ID WHERE tl.type = xxxx


问:
How to find which checkstyle version gradle is using?

In my gradle file I have:

```<code>apply plugin: 'checkstyle'
</code>```

I'm trying to create my own checkstyle rules. For this reason I have added a dependency to my gradle file.

```<code>dependencies {
     checkstyle 'com.puppycrawl.tools:checkstyle:8.2'
}
</code>```

I am trying to extend "Check" class of checkstyle. But there are a lot of version of checkstyle and I dont know which one is used by gradle.

How can I find the exact version number of checkstyle which gradle is using?

答:
with out-of-box apply plugin: 'checkstyle', the checkstyle would use v6.19.

Downloaded dependencies:

```<code>Download https://repo1.maven.org/maven2/com/puppycrawl/tools/checkstyle/6.19/checkstyle-6.19.pom
Download https://repo1.maven.org/maven2/org/antlr/antlr4-runtime/4.5.3/antlr4-runtime-4.5.3.pom
Download https://repo1.maven.org/maven2/org/antlr/antlr4-master/4.5.3/antlr4-master-4.5.3.pom
Download https://repo1.maven.org/maven2/commons-beanutils/commons-beanutils/1.9.3/commons-beanutils-1.9.3.pom
Download https://repo1.maven.org/maven2/commons-cli/commons-cli/1.3.1/commons-cli-1.3.1.pom
Download https://repo1.maven.org/maven2/org/apache/commons/commons-parent/41/commons-parent-41.pom
Download https://repo1.maven.org/maven2/commons-cli/commons-cli/1.3.1/commons-cli-1.3.1.jar
Download https://repo1.maven.org/maven2/com/puppycrawl/tools/checkstyle/6.19/checkstyle-6.19.jar
Download https://repo1.maven.org/maven2/commons-beanutils/commons-beanutils/1.9.3/commons-beanutils-1.9.3.jar
Download https://repo1.maven.org/maven2/org/antlr/antlr4-runtime/4.5.3/antlr4-runtime-4.5.3.jar
</code>```

after dependencies { checkstyle 'com.puppycrawl.tools:checkstyle:8.2' }, the downloaded dependency list:

```<code>Download https://repo1.maven.org/maven2/com/puppycrawl/tools/checkstyle/8.2/checkstyle-8.2.pom
Download https://repo1.maven.org/maven2/org/antlr/antlr4-runtime/4.7/antlr4-runtime-4.7.pom
Download https://repo1.maven.org/maven2/org/antlr/antlr4-master/4.7/antlr4-master-4.7.pom
Download https://repo1.maven.org/maven2/commons-cli/commons-cli/1.4/commons-cli-1.4.pom
Download https://repo1.maven.org/maven2/net/sf/saxon/Saxon-HE/9.8.0-4/Saxon-HE-9.8.0-4.pom
Download https://repo1.maven.org/maven2/org/antlr/antlr4-runtime/4.7/antlr4-runtime-4.7.jar
Download https://repo1.maven.org/maven2/net/sf/saxon/Saxon-HE/9.8.0-4/Saxon-HE-9.8.0-4.jar
Download https://repo1.maven.org/maven2/commons-cli/commons-cli/1.4/commons-cli-1.4.jar
Download https://repo1.maven.org/maven2/com/puppycrawl/tools/checkstyle/8.2/checkstyle-8.2.jar
</code>```

Body:
In my gradle file I have:

apply plugin: 'checkstyle'

I'm trying to create my own checkstyle rules. For this reason I have added a dependency to my gradle file.

dependencies {
     checkstyle 'com.puppycrawl.tools:checkstyle:8.2'
}

I am trying to extend "Check" class of checkstyle. But there are a lot of version of checkstyle and I dont know which one is used by gradle.

How can I find the exact version number of checkstyle which gradle is using?

Body:
with out-of-box apply plugin: 'checkstyle', the checkstyle would use v6.19.

Downloaded dependencies:

Download https://repo1.maven.org/maven2/com/puppycrawl/tools/checkstyle/6.19/checkstyle-6.19.pom
Download https://repo1.maven.org/maven2/org/antlr/antlr4-runtime/4.5.3/antlr4-runtime-4.5.3.pom
Download https://repo1.maven.org/maven2/org/antlr/antlr4-master/4.5.3/antlr4-master-4.5.3.pom
Download https://repo1.maven.org/maven2/commons-beanutils/commons-beanutils/1.9.3/commons-beanutils-1.9.3.pom
Download https://repo1.maven.org/maven2/commons-cli/commons-cli/1.3.1/commons-cli-1.3.1.pom
Download https://repo1.maven.org/maven2/org/apache/commons/commons-parent/41/commons-parent-41.pom
Download https://repo1.maven.org/maven2/commons-cli/commons-cli/1.3.1/commons-cli-1.3.1.jar
Download https://repo1.maven.org/maven2/com/puppycrawl/tools/checkstyle/6.19/checkstyle-6.19.jar
Download https://repo1.maven.org/maven2/commons-beanutils/commons-beanutils/1.9.3/commons-beanutils-1.9.3.jar
Download https://repo1.maven.org/maven2/org/antlr/antlr4-runtime/4.5.3/antlr4-runtime-4.5.3.jar

after dependencies { checkstyle 'com.puppycrawl.tools:checkstyle:8.2' }, the downloaded dependency list:

Download https://repo1.maven.org/maven2/com/puppycrawl/tools/checkstyle/8.2/checkstyle-8.2.pom
Download https://repo1.maven.org/maven2/org/antlr/antlr4-runtime/4.7/antlr4-runtime-4.7.pom
Download https://repo1.maven.org/maven2/org/antlr/antlr4-master/4.7/antlr4-master-4.7.pom
Download https://repo1.maven.org/maven2/commons-cli/commons-cli/1.4/commons-cli-1.4.pom
Download https://repo1.maven.org/maven2/net/sf/saxon/Saxon-HE/9.8.0-4/Saxon-HE-9.8.0-4.pom
Download https://repo1.maven.org/maven2/org/antlr/antlr4-runtime/4.7/antlr4-runtime-4.7.jar
Download https://repo1.maven.org/maven2/net/sf/saxon/Saxon-HE/9.8.0-4/Saxon-HE-9.8.0-4.jar
Download https://repo1.maven.org/maven2/commons-cli/commons-cli/1.4/commons-cli-1.4.jar
Download https://repo1.maven.org/maven2/com/puppycrawl/tools/checkstyle/8.2/checkstyle-8.2.jar


问:
VBA/SQL: Nested Query, Baffling Data Mismatch
The basic idea: I want a list of all of the processes that exist within a certain division. Processes are related to OperationalUnits, which are related to Divisions.

The query I want:

SELECT ID, ProcessName FROM Processes WHERE Unit IN (SELECT ID FROM OperationalUnits WHERE Division='1');

This always throws me a "type mismatch in expression" error.

I've tested by breaking the query down into the two component queries:

SELECT ID FROM OperationalUnits WHERE Division='1';

This returns a single ID, 2, which is what I expect from my test data.

SELECT ID, ProcessName FROM Processes WHERE Unit IN ('2');

This returns a single process, which is again exactly what I expect.

But if I combine them back together into the main query? Nope. It appears that the issue is that the inside query returns [2], while the outside query only works if it returns ['2'], but that doesn't seem like it can be right to me. Any help is appreciated!

答:
You could change the data type within the SQL, although it would be better to have matching data types to start with.

Access won't be able to represent the join in Design View, but it will execute it just fine:

```<code>SELECT  Processes.ID
        , ProcessName
FROM    Processes INNER JOIN OperationalUnits ON CLNG(Processes.Unit) = OperationalUnits.ID
</code>```

Body:
You could change the data type within the SQL, although it would be better to have matching data types to start with.

Access won't be able to represent the join in Design View, but it will execute it just fine:

SELECT  Processes.ID
        , ProcessName
FROM    Processes INNER JOIN OperationalUnits ON CLNG(Processes.Unit) = OperationalUnits.ID


问:
C++ Stack Implementation (not working right)
Here's the previous thread where I got help with this same lab. My stack is misbehaving, to say the least, when I add an item to stack, to print out later, it doesn't seem to add right. I always print out plus'(+), not matter if I enter another operand(*,/,+).

I am using a stack to convert a, user inputed, infix express to postfix. It seems to work fine except printing out the operands in the stack at the end.

```<code>#include <iostream>;
#include <vector>
using namespace std;

class DishWell{
public:
    char ReturnFront(){
        return Well.front();
    }
    void Push(char x){
        Well.push_back(x);
    }
    void Pop(){
        Well.pop_back();
    }
    bool IsEmpty(){
        return Well.empty();
    }
private:
    vector<char> Well;
};

bool Precidence(char Input, char Stack){
    int InputPrecidence,StackPrecidence;
    switch (Input){
        case '*':
            InputPrecidence = 4;
            break;
        case '/':
            InputPrecidence = 4;
            break;
        case '+':
            InputPrecidence = 3;
            break;
        case '-':
            InputPrecidence = 3;
            break;
        case '(':
            InputPrecidence = 2;
            break;
        default:
            InputPrecidence = 0;
    }
switch (Stack){
    case '*':
        StackPrecidence = 4;
        break;
    case '/':
        StackPrecidence = 4;
        break;
    case '+':
        StackPrecidence = 3;
        break;
    case '-':
        StackPrecidence = 3;
        break;
    case '(':
        StackPrecidence = 2;
        break;
    default:
        StackPrecidence = 0;
}
if(InputPrecidence>StackPrecidence) return true;
else return false;
}

int main(int argc, char** argv) {
    DishWell DishTray;
    char Input;
    bool InputFlag;
    InputFlag = true;
    cout<<"Enter Input, invalid input will terminate"<<endl;
    while(InputFlag){
        cout<<"Input: ";
        cin>>Input;
        cout<<endl;
        if((((Input>='a'&&Input<='z')||(Input>='A'&&Input<='Z'))||Input>='0'&&Input<='9')))//If Digit or Number
            cout<<Input;
        if((Input=='*'||Input=='/'||Input=='+'||Input=='-')){//if operand
            if(DishTray.IsEmpty())
                DishTray.Push(Input);
            else if(Precidence(Input,DishTray.ReturnFront()))
                DishTray.Push(Input);
            else if(!Precidence(Input,DishTray.ReturnFront()))
                cout<<"Output: "<<Input<<endl;
        }
        else if(!((((Input>='a'&&Input<='z')||(Input>='A'&&Input<='Z'))||(Input>='0'&&Input<='9')))||((Input=='*'||Input=='/'||Input=='+'||Input=='-')))//if not digit/numer or operand
            InputFlag = false;
    }
    int counter = 0;
    while(!DishTray.IsEmpty()){
        counter++;
        cout<<counter<<" Element "<<DishTray.ReturnFront()<<endl;
        DishTray.Pop();
    }
    return 0;
</code>```

Thank you, Macaire Bell

答: Wouldn't you want to see the value returned from pop_back() instead if discarding it as you're currently doing?</p>

Body:
Here's the previous thread where I got help with this same lab. My stack is misbehaving, to say the least, when I add an item to stack, to print out later, it doesn't seem to add right. I always print out plus'(+), not matter if I enter another operand(*,/,+).

I am using a stack to convert a, user inputed, infix express to postfix. It seems to work fine except printing out the operands in the stack at the end.

#include <iostream>;
#include <vector>
using namespace std;

class DishWell{
public:
    char ReturnFront(){
        return Well.front();
    }
    void Push(char x){
        Well.push_back(x);
    }
    void Pop(){
        Well.pop_back();
    }
    bool IsEmpty(){
        return Well.empty();
    }
private:
    vector<char> Well;
};

bool Precidence(char Input, char Stack){
    int InputPrecidence,StackPrecidence;
    switch (Input){
        case '*':
            InputPrecidence = 4;
            break;
        case '/':
            InputPrecidence = 4;
            break;
        case '+':
            InputPrecidence = 3;
            break;
        case '-':
            InputPrecidence = 3;
            break;
        case '(':
            InputPrecidence = 2;
            break;
        default:
            InputPrecidence = 0;
    }
switch (Stack){
    case '*':
        StackPrecidence = 4;
        break;
    case '/':
        StackPrecidence = 4;
        break;
    case '+':
        StackPrecidence = 3;
        break;
    case '-':
        StackPrecidence = 3;
        break;
    case '(':
        StackPrecidence = 2;
        break;
    default:
        StackPrecidence = 0;
}
if(InputPrecidence>StackPrecidence) return true;
else return false;
}

int main(int argc, char** argv) {
    DishWell DishTray;
    char Input;
    bool InputFlag;
    InputFlag = true;
    cout<<"Enter Input, invalid input will terminate"<<endl;
    while(InputFlag){
        cout<<"Input: ";
        cin>>Input;
        cout<<endl;
        if((((Input>='a'&&Input<='z')||(Input>='A'&&Input<='Z'))||Input>='0'&&Input<='9')))//If Digit or Number
            cout<<Input;
        if((Input=='*'||Input=='/'||Input=='+'||Input=='-')){//if operand
            if(DishTray.IsEmpty())
                DishTray.Push(Input);
            else if(Precidence(Input,DishTray.ReturnFront()))
                DishTray.Push(Input);
            else if(!Precidence(Input,DishTray.ReturnFront()))
                cout<<"Output: "<<Input<<endl;
        }
        else if(!((((Input>='a'&&Input<='z')||(Input>='A'&&Input<='Z'))||(Input>='0'&&Input<='9')))||((Input=='*'||Input=='/'||Input=='+'||Input=='-')))//if not digit/numer or operand
            InputFlag = false;
    }
    int counter = 0;
    while(!DishTray.IsEmpty()){
        counter++;
        cout<<counter<<" Element "<<DishTray.ReturnFront()<<endl;
        DishTray.Pop();
    }
    return 0;

Thank you, Macaire Bell


问:
PHP - Display Serial Numbers automatically using for loop
```<code><thead>
    <tr>
       <th> S.No </th>
       <th> Movie Name </th>
       <th> Language </th>
    </tr>
</thead>
   <?php

        $result = mysqli_query($connect,"SELECT * FROM movies ;")or die(mysqli_error());
        $rows = mysqli_fetch_array($result);
        ?>
        <tbody>

        <?php
        $counter=0;
        foreach($result as $rows)
        {
        $counter=$counter+1;
        ?>
        <?php     echo "<tr><td>" . $counter . "</td><td>" . $rows['language'] . "</td><td>" . $rows['movie_name'] . "</td></tr>"; ?>
    <?php  } ?>
         </tbody>
</code>```

I want to display serial numbers in the table automatically for the fetched results . Here the serial number displays correctly for the first five results like 1,2,3,4,5 rows
but on the 2nd page the number shows like 8,9,10,6,7

Where i am making mistake ? I even tried while loop and forloop increment counter. Im using Bootstrap data table to display the results from database.

答:
```<code><?php
    $result = mysqli_query($connect,"SELECT * FROM movies");

    $counter=0;
    while($rows = mysqli_fetch_array($result)){

    echo "<tr><td>" . $counter . "</td>
              <td>" . $result[$counter]['language'] . "</td>
              <td>" . $result[$counter]['movie_name'] . "</td>
          </tr>";
    $counter++;
    }
?>
</code>```

This should work for you. You need to fetch the results inside a loop in order to parse them.

Body:
        S.No
        Movie Name
        Language

   <?php

        $result = mysqli_query($connect,"SELECT * FROM movies ;")or die(mysqli_error());
        $rows = mysqli_fetch_array($result);
        ?>

        <?php
        $counter=0;
        foreach($result as $rows)
        {
        $counter=$counter+1;
        ?>
        <?php     echo "
" . $counter . "	" . $rows['language'] . "	" . $rows['movie_name'] . "
"; ?>
    <?php  } ?>

I want to display serial numbers in the table automatically for the fetched results . Here the serial number displays correctly for the first five results like 1,2,3,4,5 rows
but on the 2nd page the number shows like 8,9,10,6,7

Where i am making mistake ? I even tried while loop and forloop increment counter. Im using Bootstrap data table to display the results from database.

Body:
<?php
    $result = mysqli_query($connect,"SELECT * FROM movies");

    $counter=0;
    while($rows = mysqli_fetch_array($result)){

    echo "<tr><td>" . $counter . "</td>
              <td>" . $result[$counter]['language'] . "</td>
              <td>" . $result[$counter]['movie_name'] . "</td>
          </tr>";
    $counter++;
    }
?>

This should work for you. You need to fetch the results inside a loop in order to parse them.

ContentLicense: CC BY-SA 4.0