问:
Object oriented Login functionality
User Login functionality is very common to many applications. I would like to see how people implement this functionality in Object oriented way.

I have a User and I need to validate the userId and password against a system(this could be ldap, database, etc.). So what kind of classes and operations you would create to achieve this functionality?

Or is OO a bad choice to develop this functionality?

I am about to start a new project so want to gather good options.

I know there are frameworks which provide this solution already. I have used them in earlier projects. What I was trying to see is how people implement this in OO way.

I read the answers and everybody suggested a separate Credentials and Authentication Service. If instead of Credentials I use class name as User then shouldn't User class should have a method called login? Just like a Person object will have a method drink instead of DrinkService or I am wrong in understanding this correctly?

答:
Authentication also involves retrieving credentials and you will want to include how the credentials are accessed in your authentication framework. This can be even more important than the Authenticator class already highlighted.

```<code>class CredentialsAccessor {
  public bool hasCredentials(){};
  public Credentials getCredentials();
}
class FormAccessor : CredentialsAccessor {
    // get credentials from a webapp or form
}
class CookieAccessor : CredentialsAccessor {
    // get credentials based on cookie
}
class SessionAccessor : CredentialsAccessor {
    // get credentials from user session
}
class CredentialAccessManager
{
   list<CredentialsAccessor> m_Credentials;

   Credentials getCredentials()
   {
     foreach( CredentialsAccessor l_accessor in m_Credentials )
     {
         if( l_accessor.hasCredentials() ) return l_accessor.credentials();
     }
   }
}
</code>```

You plug all the accessor objects into the list in the right order and your user will magically be logged in every time.

OwnerDisplayName: Bhushan

Title: Object oriented Login functionality

LastEditorDisplayName: Bhushan

Body:
Authentication also involves retrieving credentials and you will want to include how the credentials are accessed in your authentication framework. This can be even more important than the Authenticator class already highlighted.

class CredentialsAccessor {
  public bool hasCredentials(){};
  public Credentials getCredentials();
}
class FormAccessor : CredentialsAccessor {
    // get credentials from a webapp or form
}
class CookieAccessor : CredentialsAccessor {
    // get credentials based on cookie
}
class SessionAccessor : CredentialsAccessor {
    // get credentials from user session
}
class CredentialAccessManager
{
   list<CredentialsAccessor> m_Credentials;

   Credentials getCredentials()
   {
     foreach( CredentialsAccessor l_accessor in m_Credentials )
     {
         if( l_accessor.hasCredentials() ) return l_accessor.credentials();
     }
   }
}

You plug all the accessor objects into the list in the right order and your user will magically be logged in every time.

OwnerDisplayName: SmokingRope

LastEditorDisplayName: SmokingRope


来源: stackexchange

问:
How to bypass the user confirmation when installing packages on linux
I'm writing a basic script in bash to automatically install a few packages on new machines (basically, the first script to run on a new machine before doing anything else). I'm downloading openssh-server and python for example.

My goal is just to launch the script in sudo mode, wait a few minutes and get started. The only problem I'm facing is the machine requires the user to input "y" when needed and I can't find a way to bypass this.

This is just a sample of my script :

```<code>#!/bin/bash

sudo apt update
sudo apt install openssh-server
sudo apt-get install python3
</code>```

what I expect is just run this command and let it roll without the user to have and put "y" when needed

```<code>sudo bash start-script.sh
</code>```

答:
Use the -y option of apt-get. From the apt-get man page:</p>

```<code>   -y, --yes, --assume-yes
       Automatic yes to prompts; assume "yes" as answer to all prompts and
       run non-interactively. If an undesirable situation, such as
       changing a held package, trying to install a unauthenticated
       package or removing an essential package occurs then apt-get will
       abort. Configuration Item: APT::Get::Assume-Yes.
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm writing a basic script in bash to automatically install a few packages on new machines (basically, the first script to run on a new machine before doing anything else). I'm downloading openssh-server and python for example.

My goal is just to launch the script in sudo mode, wait a few minutes and get started. The only problem I'm facing is the machine requires the user to input "y" when needed and I can't find a way to bypass this.

This is just a sample of my script :

#!/bin/bash

sudo apt update
sudo apt install openssh-server
sudo apt-get install python3

what I expect is just run this command and let it roll without the user to have and put "y" when needed

sudo bash start-script.sh

Body:
Use the -y option of apt-get. From the apt-get man page:

   -y, --yes, --assume-yes
       Automatic yes to prompts; assume "yes" as answer to all prompts and
       run non-interactively. If an undesirable situation, such as
       changing a held package, trying to install a unauthenticated
       package or removing an essential package occurs then apt-get will
       abort. Configuration Item: APT::Get::Assume-Yes.


问:
Python - Average of three values in a while true loop
I'm developing a python script on a raspberry pi with a distance sensor.
My code is working and i can reach the distance but I want to avoid some false positive/negative so I would like to get the average of the last three data.

Here is my code:

while True:
        distance= misura() # GETTING THE REAL DISTANCE IN CM
        print "Distanza : %.2f" % distanza

        avg_distance = <something> # <- HERE I NEED SOMETHING ELEGANT

        if (avg_distance > 30):
            print "NOT PRESENT"
        else:
            print "PRESENT"

        time.sleep(1.5)
```

I would like some function (maybe based on a list?) that returns the average of the last three (or n) distances

IMPORTANT:
I don't want to store ALL the values because this script will run for days and days

答:
try to restrict the length of the list</p>

```<code>_distance = []
if _distance.size == 3:
       _distance = _distance[-2:]
       _distance.append(distance)
else:
   _distance.append(distance)

 avg_distance = sum(distance[-3:]) / len(distance[-3:])
</code>```

Body:
I'm developing a python script on a raspberry pi with a distance sensor.
My code is working and i can reach the distance but I want to avoid some false positive/negative so I would like to get the average of the last three data.

Here is my code:

while True:
        distance= misura() # GETTING THE REAL DISTANCE IN CM
        print "Distanza : %.2f" % distanza

        avg_distance = <something> # <- HERE I NEED SOMETHING ELEGANT

        if (avg_distance > 30):
            print "NOT PRESENT"
        else:
            print "PRESENT"

        time.sleep(1.5)

I would like some function (maybe based on a list?) that returns the average of the last three (or n) distances

IMPORTANT:
I don't want to store ALL the values because this script will run for days and days

Body:
try to restrict the length of the list

_distance = []
if _distance.size == 3:
       _distance = _distance[-2:]
       _distance.append(distance)
else:
   _distance.append(distance)

 avg_distance = sum(distance[-3:]) / len(distance[-3:])


问:
Ranges in Kotlin
How do I write code to return a range of 10 numbers from a given number.

i.e if I am given 5, code should return 0..9

358 should return 350..359

33 should return 30..39  etc

答:
If the given number is integer type, you can simply write</p>

```<code>val x = 358
(x / 10 * 10)..(x / 10 * 10 + 9)
</code>```

Title: Ranges in Kotlin

Body:
If the given number is integer type, you can simply write

val x = 358
(x / 10 * 10)..(x / 10 * 10 + 9)


问:
Problems with $.post
I am doing some checks on my website to assure that the web browser can run it. If the browser pass the requirements, I want to reload the webpage and send a post argument with jQuery like this.

I have tried the $.post function on jQuery like this:

```<code>$.post("index.php", {
  correcto_obligatorio: true
});

window.location.reload("index.php")
</code>```

However, when the browser reloads the web, there is no correcto_obligatorio parameter on $_POST. I used the var_dump php function to print it and all I get is NULL

答:
your code does not wait for the post to finish. You basically send the request and redirect the browser to index.php without waiting for the server to answer you. Consider using a callback function:

```<code>$.post( "index.php",  {
  correcto_obligatorio: true
}, function( result) {
    if (result.passed) {
        window.location.reload("index.php")
    }
});
</code>```

That is assuming that the server responds with a valid json object that contains the parameter passed (content type should be set to application/json )

Title: Problems with $.post

Body:
I am doing some checks on my website to assure that the web browser can run it. If the browser pass the requirements, I want to reload the webpage and send a post argument with jQuery like this.

I have tried the $.post function on jQuery like this:

$.post("index.php", {
  correcto_obligatorio: true
});

window.location.reload("index.php")

However, when the browser reloads the web, there is no correcto_obligatorio parameter on $_POST. I used the var_dump php function to print it and all I get is NULL

Body:
your code does not wait for the post to finish. You basically send the request and redirect the browser to index.php without waiting for the server to answer you. Consider using a callback function:

$.post( "index.php",  {
  correcto_obligatorio: true
}, function( result) {
    if (result.passed) {
        window.location.reload("index.php")
    }
});

That is assuming that the server responds with a valid json object that contains the parameter passed (content type should be set to application/json )


问:
how to change index directory of my laravel website
I want to create a website using Laravel Framework in my localhost laragon server

I uploaded the website files in a Web Hosting. and when I enter the url http://www.mywebsite.com. then I just get the files like

But when I enter the url http://www.mywebsite.com/public then it is working perfectly.

Can anyone suggest me that what's I'm doing wrong.

答: You need to point your domain to public folder of laravel not root since laravel has index.php inside project folder/public/index.php so you need to point project folder/public/


问:
Autofocus first form element inside active div in a form
I have a form with several divs (10+) and I display only 1 at a time whereas the rest are set to display: hidden.When I click on the Next button, the current div gets hidden and the next one gets visible. There is a Previous button too.

Is there a way to focus the first form element of the currently visible div using JavaScript?

HTML Structure is as follows:

```<code><form id = "myForm">
<div id="div1">
<!-------Div can hav 2 cols---->
    <div class = "row">
        <div class= "col">
            <input autofocus>
        </div>
        <div class = "col">
            <select></select>
        </div>
    </div>
</div>
<div id="div2" style = "display: none;">
<!-------Or Div can have 1 col---->
    <div class = "row">
        <div class = "col">
             <!-------First element can be input---->
            <input>
        </div>
    </div>
</div>
<div id="div3" style = "display: none;">
    <div class = "row">
        <div class = "col">
             <!-------Or First element can be select---->
             <select> </select>
             <input>
        </div>
    </div>
</div>
<!-------More Divs---->
</form>
</code>```

The autofocus works on the first element but then I need to focus on the first elements of the rest of the divs inside the form using JavaScript.

答:
If you share your next and prev button click function then easy to understand your structure and able to give solution very simple way.

I have also prepare below thing for solution.

```<code> $("#myForm > div:visible .col").first().find('input').focus();
</code>```

you need to check every time when click on next and prev button.
So you need to add this code in next and prev function.

Edit : Please give one common class in form control(input, select, etc) and then use it in find element (replace class instead of input ).

Body:
I have a form with several divs (10+) and I display only 1 at a time whereas the rest are set to display: hidden.When I click on the Next button, the current div gets hidden and the next one gets visible. There is a Previous button too.

Is there a way to focus the first form element of the currently visible div using JavaScript?

HTML Structure is as follows:

<form id = "myForm">

            <input autofocus>

            <select></select>

            <input>

             <select> </select>
             <input>

</form>

The autofocus works on the first element but then I need to focus on the first elements of the rest of the divs inside the form using JavaScript.

Body:
If you share your next and prev button click function then easy to understand your structure and able to give solution very simple way.

I have also prepare below thing for solution.

 $("#myForm > div:visible .col").first().find('input').focus();

you need to check every time when click on next and prev button.
So you need to add this code in next and prev function.

Edit : Please give one common class in form control(input, select, etc) and then use it in find element (replace class instead of input ).


问:
403 Access Denied on Tomcat 8 Manager App without prompting for user/password
I have set up tomcat 8 according to this, and I have the following tomcat-users.xml file:

```<code><?xml version="1.0" encoding="UTF-8"?>
<tomcat-users xmlns="http://tomcat.apache.org/xml"
              xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
              xsi:schemaLocation="http://tomcat.apache.org/xml tomcat-users.xsd"
              version="1.0">
  <role rolename="manager-gui"/>
  <role rolename="manager-script"/>

  <user username="notadmin" password="not_real_pass" roles="manager-gui"/>
  <user username="cargo" password="not_real_pass" roles="manager-script"/>
<tomcat-users/>
</code>```

When I try to access the Manager App, I get rejected with 403 without any prompt for username and password.

What did I miss in the config?

Edit1: Added full xml file.

答:
Go and Check if a user is created or not
if no please create a user by opening a file in /apache-tomcat-9.0.20/tomcat-users.xml
add a line into it

<user username="tomcat" password="tomcat" roles="admin-gui,manager-gui,manager-script" />

Goto /apache-tomcat-9.0.20/webapps/manager/META-INF/
open context.xml
comment everything in context tag
example:

```<code><Context antiResourceLocking="false" privileged="true" >
     <!--Valve className="org.apache.catalina.valves.RemoteAddrValve"
            allow="127\.\d+\.\d+\.\d+|::1|0:0:0:0:0:0:0:1" /-->
   </Context>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have set up tomcat 8 according to this, and I have the following tomcat-users.xml file:

<?xml version="1.0" encoding="UTF-8"?>
<tomcat-users xmlns="http://tomcat.apache.org/xml"
              xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
              xsi:schemaLocation="http://tomcat.apache.org/xml tomcat-users.xsd"
              version="1.0">
  <role rolename="manager-gui"/>
  <role rolename="manager-script"/>

  <user username="notadmin" password="not_real_pass" roles="manager-gui"/>
  <user username="cargo" password="not_real_pass" roles="manager-script"/>
<tomcat-users/>

When I try to access the Manager App, I get rejected with 403 without any prompt for username and password.

What did I miss in the config?

Edit1: Added full xml file.

Body:
Go and Check if a user is created or not
if no please create a user by opening a file in /apache-tomcat-9.0.20/tomcat-users.xml
add a line into it

<user username="tomcat" password="tomcat" roles="admin-gui,manager-gui,manager-script" />

Goto /apache-tomcat-9.0.20/webapps/manager/META-INF/
open context.xml
comment everything in context tag
example:

<Context antiResourceLocking="false" privileged="true" >
     <!--Valve className="org.apache.catalina.valves.RemoteAddrValve"
            allow="127\.\d+\.\d+\.\d+|::1|0:0:0:0:0:0:0:1" /-->
   </Context>


问:
Angular Unit tests with Chrome headless and Karma hangs on
I'm using Chrome-Headless to run my Angular 7  unit tests project with Karma

It seems to not be stable as when running dozens of specs , it breaks randomly at any test without completing all tests.

I don't know if it's a probleme of memory , of chrome itself of karma..

My karma.conf :

```<code>// Karma configuration file, see link for more information
// https://karma-runner.github.io/1.0/config/configuration-file.html
var process = require('process');

module.exports = function (config) {

  config.set({
    basePath: '',
    frameworks: ['jasmine', '@angular-devkit/build-angular'],
    plugins: [
      require('karma-jasmine'),
      require('karma-chrome-launcher'),
      require('karma-jasmine-html-reporter'),
      require('karma-coverage-istanbul-reporter'),
      require('@angular-devkit/build-angular/plugins/karma')
    ],
    client:{
      clearContext: false // leave Jasmine Spec Runner output visible in browser
    },
    mime: {
      'text/x-typescript': ['ts','tsx']
    },
    coverageIstanbulReporter: {
      dir: require('path').join(__dirname, 'coverage'),
      reports: [ 'html', 'lcovonly' ],
      fixWebpackSourcePaths: true
    },

    reporters: config.angularCli && config.angularCli.codeCoverage
      ? ['progress', 'coverage-istanbul']
      : ['progress', 'kjhtml'],
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: true,
    browsers: ['Chrome'],
    browserDisconnectTimeout: 60000,
    browserDisconnectTolerance: 3,
    browserNoActivityTimeout: 60000,
    flags: [
      '--disable-web-security',
      '--disable-gpu',
      '--no-sandbox'
    ],
    singleRun: true,
    concurrency: Infinity
  });
};
</code>```

And i'm using thos testing packages :

```<code>"jasmine-core": "^3.3.0",
"jasmine-spec-reporter": "^4.2.1",
"karma": "^4.0.0",
"karma-chrome-launcher": "^2.2.0",
"karma-cli": "^2.0.0",
"karma-coverage-istanbul-reporter": "2.0.4",
"karma-jasmine": "^2.0.1",
"karma-jasmine-html-reporter": "^1.4.0",
</code>```

Suggestions ??

答:
add a customer luncher for it, it should fix the problem

```<code>browsers: ['ChromeHeadlessNoSandbox'],
customLaunchers: {
  ChromeHeadlessNoSandbox: {
    base: 'ChromeHeadless',
    flags: ['--no-sandbox']
  }
},
</code>```

here is an example of a working config using ChromiumHeadless

```<code>module.exports = function (config) {
  config.set({
    basePath: '',
    frameworks: ['jasmine', '@angular-devkit/build-angular'],
    plugins: [
      require('karma-jasmine'),
      require('karma-junit-reporter'),
      require('karma-chrome-launcher'),
      require('karma-jasmine-html-reporter'),
      require('karma-coverage-istanbul-reporter'),
      require('@angular-devkit/build-angular/plugins/karma')
    ],
    client: {
      clearContext: false // leave Jasmine Spec Runner output visible in browser
    },
    coverageIstanbulReporter: {
      dir: require('path').join(__dirname, '../coverage'),
      reports: ['html', 'lcovonly', 'text-summary'],
      fixWebpackSourcePaths: true
    },
    reporters: ['junit','progress', 'kjhtml'],
    junitReporter: {
      outputDir: require('path').join(__dirname, '../coverage'), // results will be saved as $outputDir/$browserName.xml
      outputFile: 'junit.xml', // if included, results will be saved as $outputDir/$browserName/$outputFile
      suite: '', // suite will become the package name attribute in xml testsuite element
      useBrowserName: false, // add browser name to report and classes names
      nameFormatter: undefined, // function (browser, result) to customize the name attribute in xml testcase element
      classNameFormatter: undefined, // function (browser, result) to customize the classname attribute in xml testcase element
      properties: {}, // key value pair of properties to add to the <properties> section of the report
      xmlVersion: null // use '1' if reporting to be per SonarQube 6.2 XML format
    },
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: true,
    singleRun: false,
    browsers: ['Chrome_no_sandbox'],
    customLaunchers: {
      Chrome_no_sandbox: {
        base: 'ChromiumHeadless',
        flags: ['--no-sandbox']
      }
    }
  });
};
</code>```

Body:
I'm using Chrome-Headless to run my Angular 7  unit tests project with Karma

It seems to not be stable as when running dozens of specs , it breaks randomly at any test without completing all tests.

I don't know if it's a probleme of memory , of chrome itself of karma..

My karma.conf :

// Karma configuration file, see link for more information
// https://karma-runner.github.io/1.0/config/configuration-file.html
var process = require('process');

module.exports = function (config) {

  config.set({
    basePath: '',
    frameworks: ['jasmine', '@angular-devkit/build-angular'],
    plugins: [
      require('karma-jasmine'),
      require('karma-chrome-launcher'),
      require('karma-jasmine-html-reporter'),
      require('karma-coverage-istanbul-reporter'),
      require('@angular-devkit/build-angular/plugins/karma')
    ],
    client:{
      clearContext: false // leave Jasmine Spec Runner output visible in browser
    },
    mime: {
      'text/x-typescript': ['ts','tsx']
    },
    coverageIstanbulReporter: {
      dir: require('path').join(__dirname, 'coverage'),
      reports: [ 'html', 'lcovonly' ],
      fixWebpackSourcePaths: true
    },

    reporters: config.angularCli && config.angularCli.codeCoverage
      ? ['progress', 'coverage-istanbul']
      : ['progress', 'kjhtml'],
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: true,
    browsers: ['Chrome'],
    browserDisconnectTimeout: 60000,
    browserDisconnectTolerance: 3,
    browserNoActivityTimeout: 60000,
    flags: [
      '--disable-web-security',
      '--disable-gpu',
      '--no-sandbox'
    ],
    singleRun: true,
    concurrency: Infinity
  });
};

And i'm using thos testing packages :

"jasmine-core": "^3.3.0",
"jasmine-spec-reporter": "^4.2.1",
"karma": "^4.0.0",
"karma-chrome-launcher": "^2.2.0",
"karma-cli": "^2.0.0",
"karma-coverage-istanbul-reporter": "2.0.4",
"karma-jasmine": "^2.0.1",
"karma-jasmine-html-reporter": "^1.4.0",

Suggestions ??

Body:
add a customer luncher for it, it should fix the problem

browsers: ['ChromeHeadlessNoSandbox'],
customLaunchers: {
  ChromeHeadlessNoSandbox: {
    base: 'ChromeHeadless',
    flags: ['--no-sandbox']
  }
},

here is an example of a working config using ChromiumHeadless

module.exports = function (config) {
  config.set({
    basePath: '',
    frameworks: ['jasmine', '@angular-devkit/build-angular'],
    plugins: [
      require('karma-jasmine'),
      require('karma-junit-reporter'),
      require('karma-chrome-launcher'),
      require('karma-jasmine-html-reporter'),
      require('karma-coverage-istanbul-reporter'),
      require('@angular-devkit/build-angular/plugins/karma')
    ],
    client: {
      clearContext: false // leave Jasmine Spec Runner output visible in browser
    },
    coverageIstanbulReporter: {
      dir: require('path').join(__dirname, '../coverage'),
      reports: ['html', 'lcovonly', 'text-summary'],
      fixWebpackSourcePaths: true
    },
    reporters: ['junit','progress', 'kjhtml'],
    junitReporter: {
      outputDir: require('path').join(__dirname, '../coverage'), // results will be saved as $outputDir/$browserName.xml
      outputFile: 'junit.xml', // if included, results will be saved as $outputDir/$browserName/$outputFile
      suite: '', // suite will become the package name attribute in xml testsuite element
      useBrowserName: false, // add browser name to report and classes names
      nameFormatter: undefined, // function (browser, result) to customize the name attribute in xml testcase element
      classNameFormatter: undefined, // function (browser, result) to customize the classname attribute in xml testcase element
      properties: {}, // key value pair of properties to add to the <properties> section of the report
      xmlVersion: null // use '1' if reporting to be per SonarQube 6.2 XML format
    },
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: true,
    singleRun: false,
    browsers: ['Chrome_no_sandbox'],
    customLaunchers: {
      Chrome_no_sandbox: {
        base: 'ChromiumHeadless',
        flags: ['--no-sandbox']
      }
    }
  });
};


问:
How to add up unique values from table in SQL
I have a table in SQL that looks like this

```<code>Person  brand   brand_spend category    category_spend
0   p1  b1       20           c1           100
1   p1  b2       50           c1           100
2   p2  b1       25           c2           40
3   p1  b3       30           c1           100
4   p1  b2       15           c2           70
</code>```

I need to tag every customer based on percentage spend he has made  at a brand based on total category spend where that brand is present.
So essentially I would want to tag Person p1 for brand b1' as percentage spend at 'b1 which should be calculated as  45/ 140

How this can be achieved. If I roll up on brand level to find total category spend then I think duplicates rows would add up.

I just want to find customer's Spend at a brand based on total spend at Brand for all categories where that brand is present.

答:
You need grouping on two levels, as shown here:

```<code>select person, brand, sum(brand_spend) personspend, spendbrandallcats,
       round(sum(brand_spend)/spendbrandallcats,3) pbratio from tbl t
inner join (  -- brand statistics: sum of all spends per brand in all categories
 select brand br, sum(casp) spendbrandallcats from tbl
 inner join ( -- category statistics: total category sums
   select category ca, sum(brand_spend) casp from tbl group by category
 ) catspend ON ca=category
 group by brand
) brandstats on br=brand
group by person,brand
</code>```

These are the results:

```<code>person brand personspend spendbrandallcats pbratio
p1     b1    20          140               0.143
p1     b2    65          140               0.464
p1     b3    30          100               0.3
p2     b1    25          140               0.179
</code>```

See the little demo here: https://rextester.com/SVNH27609

Body:
I have a table in SQL that looks like this

Person  brand   brand_spend category    category_spend
0   p1  b1       20           c1           100
1   p1  b2       50           c1           100
2   p2  b1       25           c2           40
3   p1  b3       30           c1           100
4   p1  b2       15           c2           70

I need to tag every customer based on percentage spend he has made  at a brand based on total category spend where that brand is present.
So essentially I would want to tag Person p1 for brand b1' as percentage spend at 'b1 which should be calculated as  45/ 140

How this can be achieved. If I roll up on brand level to find total category spend then I think duplicates rows would add up.

I just want to find customer's Spend at a brand based on total spend at Brand for all categories where that brand is present.

Body:
You need grouping on two levels, as shown here:

select person, brand, sum(brand_spend) personspend, spendbrandallcats,
       round(sum(brand_spend)/spendbrandallcats,3) pbratio from tbl t
inner join (  -- brand statistics: sum of all spends per brand in all categories
 select brand br, sum(casp) spendbrandallcats from tbl
 inner join ( -- category statistics: total category sums
   select category ca, sum(brand_spend) casp from tbl group by category
 ) catspend ON ca=category
 group by brand
) brandstats on br=brand
group by person,brand

These are the results:

person brand personspend spendbrandallcats pbratio
p1     b1    20          140               0.143
p1     b2    65          140               0.464
p1     b3    30          100               0.3
p2     b1    25          140               0.179

See the little demo here: https://rextester.com/SVNH27609


问:
git commit metrics
I want to determine git commit metrics  using  bash script.

But I never use bash script.

The idea is to have the number of commit wich are not referenced in their status during a specific time

(i.e.: not closed or no #nnnn reference where n is a number, because we use Redmine to show the reference of open commit)

the algorithm is:

```<code>fonction (initial date, final date)
  read initial date
  read final date
  int n=0
  while (initial date<date<final date) do
    if (status!=closed or status!= #nnnn) //where #nnnn is a reference and n a number
      n=+1
    end if
  end while
  echo "the number of none referenced commit is"
  echo n
  return 0
</code>```

If there is a specific git command or other idea, please leave a response, it will help me a lot. thank you

答:
Such a script would use and exploit the git low-level commands (plumbing, suitable for scripting) command git rev-list:

The commit limiting options allow you to define a range of date, and to select the right log message:

```<code>--skip=<number>
    Skip number commits before starting to show the commit output.
--since=<date>
--after=<date>
    Show commits more recent than a specific date.
--until=<date>
--before=<date>
    Show commits older than a specific date.
--max-age=<timestamp>
--min-age=<timestamp>
    Limit the commits output to specified time range.

--grep=<pattern>
</code>```

Limit the commits output to ones with log message that matches the specified pattern (regular expression).

The commit formatting options allow you to display only what you need, mainly the comment of the commit, for you to parse (I suppose it is in the comment of a commit that you have stored the status of said commit, although you could also have used git notes):

```<code>--pretty[=<format>]
--format=<format>
</code>```

Pretty-print the contents of the commit logs in a given format, where  can be one of oneline, short, medium, full, fuller, email, raw and format:. See the "PRETTY FORMATS" section for some additional details for each format. When omitted, the format defaults to medium.

Title: git commit metrics

Body:
I want to determine git commit metrics  using  bash script.

But I never use bash script.

The idea is to have the number of commit wich are not referenced in their status during a specific time

(i.e.: not closed or no #nnnn reference where n is a number, because we use Redmine to show the reference of open commit)

the algorithm is:

fonction (initial date, final date)
  read initial date
  read final date
  int n=0
  while (initial date<date<final date) do
    if (status!=closed or status!= #nnnn) //where #nnnn is a reference and n a number
      n=+1
    end if
  end while
  echo "the number of none referenced commit is"
  echo n
  return 0

If there is a specific git command or other idea, please leave a response, it will help me a lot. thank you

Body:
Such a script would use and exploit the git low-level commands (plumbing, suitable for scripting) command git rev-list:

The commit limiting options allow you to define a range of date, and to select the right log message:

--skip=<number>
    Skip number commits before starting to show the commit output.
--since=<date>
--after=<date>
    Show commits more recent than a specific date.
--until=<date>
--before=<date>
    Show commits older than a specific date.
--max-age=<timestamp>
--min-age=<timestamp>
    Limit the commits output to specified time range.

--grep=<pattern>

Limit the commits output to ones with log message that matches the specified pattern (regular expression).

The commit formatting options allow you to display only what you need, mainly the comment of the commit, for you to parse (I suppose it is in the comment of a commit that you have stored the status of said commit, although you could also have used git notes):

--pretty[=<format>]
--format=<format>

Pretty-print the contents of the commit logs in a given format, where  can be one of oneline, short, medium, full, fuller, email, raw and format:. See the "PRETTY FORMATS" section for some additional details for each format. When omitted, the format defaults to medium.


问:
General question regarding allocating memory for an integer in C
I am currently learning about dynamic memory allocation in C and am having difficulty with a particular concept. For using malloc for a particular integer, I need to put a previously declared integer within that space.

The following below is what I am putting in as my code.

```<code>void example(int ab)
{
int* intPtr=(int*)malloc(sizeof(int));
*intPtr = &ab;
}
</code>```

I am not trying to run a program or anything. I just want to see if I have the right idea about some basic memory allocation.

答:
There are few issues, firstly its not necessary to typecast the result of malloc() as it's done implicitly by compiler. Read Do I cast the result of malloc?. This

```<code>int* intPtr = malloc(sizeof(int)); /* or even malloc(sizeof(*intPtr)); is better */
</code>```

is fine.

Secondly, this

```<code>*intPtr = &ab; /* *intPtr means value at allocated dynamic address, you should assign the value not address of ab*/
</code>```

is wrong as *intPtr is the value at dynamic address, compiler should have warned you like

main.c:7:9: warning: incompatible pointer to integer
        conversion assigning to 'int' from 'int *'; remove &
        [-Wint-conversion]

If you had compiled with below flags like

```<code>gcc -Wall -Wextra -Werror -Wpedantic test.c
</code>```

It should be

```<code>*intPtr = ab;
</code>```

Also you are not freeing the dynamically allocated memory, its leads to memory leakage. Free the dynamically allocated memory  by calling free() once usage is done.

Side note, if your intention is to do like this

```<code>intPtr = &ab; /* Before this statement intPtr was pointing dynamic memory(heap), but now that gets overwritten with stack allocated space */
</code>```

then you are overwriting dynamic memory with stack created memory i.e address of local variable, in that case you are loosing dynamic memory as nothing is pointing to previously allocated dynamic address.

Body:
I am currently learning about dynamic memory allocation in C and am having difficulty with a particular concept. For using malloc for a particular integer, I need to put a previously declared integer within that space.

The following below is what I am putting in as my code.

void example(int ab)
{
int* intPtr=(int*)malloc(sizeof(int));
*intPtr = &ab;
}

I am not trying to run a program or anything. I just want to see if I have the right idea about some basic memory allocation.

Body:
There are few issues, firstly its not necessary to typecast the result of malloc() as it's done implicitly by compiler. Read Do I cast the result of malloc?. This

int* intPtr = malloc(sizeof(int)); /* or even malloc(sizeof(*intPtr)); is better */

is fine.

Secondly, this

*intPtr = &ab; /* *intPtr means value at allocated dynamic address, you should assign the value not address of ab*/

is wrong as *intPtr is the value at dynamic address, compiler should have warned you like

main.c:7:9: warning: incompatible pointer to integer
        conversion assigning to 'int' from 'int *'; remove &
        [-Wint-conversion]

If you had compiled with below flags like

gcc -Wall -Wextra -Werror -Wpedantic test.c

It should be

*intPtr = ab;

Also you are not freeing the dynamically allocated memory, its leads to memory leakage. Free the dynamically allocated memory  by calling free() once usage is done.

Side note, if your intention is to do like this

intPtr = &ab; /* Before this statement intPtr was pointing dynamic memory(heap), but now that gets overwritten with stack allocated space */

then you are overwriting dynamic memory with stack created memory i.e address of local variable, in that case you are loosing dynamic memory as nothing is pointing to previously allocated dynamic address.


问:
Error while loading Module Controllers from Test Fragment in Jmeter4.0 & 5.0
I've been trying to use a Main-Fragment Framework with JMeter but encountered an error while using Module controller within the fragment.jmx (see attached image), have you encountered this error? (tried on Jmeter 4.0 and 5.0)

Do you have any suggestions how to reuse pieces of code, because I have the same calls in five different places and every time I modify it I miss at least one place and it's very frustrating

Thanks!

答:
Please check if you have selected any - Module to Run under Modules -> Google Request

This error might appear in case no module is selected under Modules -> Google Request

You can refer How to use test fragments with Module and include controller


问:
Do-While won't repeat itself
I need the user to enter their age, then the program has to calculate how much money they are going to have when their age hit pension. The person is saving 500 or 1000 depending on the situation.

My code won't repeat the if and else statement even though I wrote a Do-While loop. Am I supposed to use a bool-statement? How or where? Or there something else I need to look at?

I've tried using only 'while' but I think I need to use a do-while.

```<code>static void Main(string[] args)
{
    Console.Write("Enter age");
    string str = Console.ReadLine();
    int MyAge = Convert.ToInt32(str);
    int money = 15000;
    {
        do
        {
            {
                if (money > 20000 || MyAge < 60)
                {
                    Console.Write("You are saving little");
                    money = money + 500;
                }
                else
                {
                    Console.Write("You are saving a lot");
                    money = money + 1000;
                }
                MyAge++;
            }
        }
        while (money > 20000 && MyAge > 65);
    }

    Console.Write("You are retired by the age of " + MyAge + " and you saved " + money + " dollars.");
}
</code>```

I expected the program to hit at least 65 but it ends by the age of 26 of I type down that I'm 25 years old. So it doesn't loop.

答:
The solution was to type || instead of && in the while code! Thanks everybody for your help! Couldn't have done this without you. :)</p>

```<code>                while ((MyAge < 65) || (money < 20000));
</code>```

Title: Do-While won't repeat itself

Body:
I need the user to enter their age, then the program has to calculate how much money they are going to have when their age hit pension. The person is saving 500 or 1000 depending on the situation.

My code won't repeat the if and else statement even though I wrote a Do-While loop. Am I supposed to use a bool-statement? How or where? Or there something else I need to look at?

I've tried using only 'while' but I think I need to use a do-while.

static void Main(string[] args)
{
    Console.Write("Enter age");
    string str = Console.ReadLine();
    int MyAge = Convert.ToInt32(str);
    int money = 15000;
    {
        do
        {
            {
                if (money > 20000 || MyAge < 60)
                {
                    Console.Write("You are saving little");
                    money = money + 500;
                }
                else
                {
                    Console.Write("You are saving a lot");
                    money = money + 1000;
                }
                MyAge++;
            }
        }
        while (money > 20000 && MyAge > 65);
    }

    Console.Write("You are retired by the age of " + MyAge + " and you saved " + money + " dollars.");
}

I expected the program to hit at least 65 but it ends by the age of 26 of I type down that I'm 25 years old. So it doesn't loop.

Body:
The solution was to type || instead of && in the while code! Thanks everybody for your help! Couldn't have done this without you. :)

                while ((MyAge < 65) || (money < 20000));


问:
Can't bind to 'ng-forOf' since it isn't a known native property

I am trying to follow the basic Angular 2 tutorial here:

https://angular.io/docs/js/latest/guide/displaying-data.html

I can get the angular app to load and display my name with this code:

import { Component, View, bootstrap } from 'angular2/angular2';

@Component({
    selector: "my-app"
})

class AppComponent {
    myName: string;
    names: Array<string>;
    constructor() {
        this.myName = "Neil";

    }

}
bootstrap(AppComponent);
```

<p>However when I try to add an array of strings and try to display them with an ng-for, it is throwing the following error:</p>

<pre class="lang-ts prettyprint-override"><code>Can't bind to 'ng-forOf' since it isn't a known native property ("
    <p>Friends:</p>
    <ul>
        <li [ERROR ->]*ng-for="#name of names">
        {{ name }}
        </li>
"): AppComponent@4:16
Property binding ng-forOf not used by any directive on an embedded template ("
    <p>Friends:</p>
    <ul>
        [ERROR ->]<li *ng-for="#name of names">
        {{ name }}
        </li>
"): AppComponent@4:12
</code>```

Here is the code:

import { Component, View, bootstrap } from 'angular2/angular2';

@Component({
    selector: "my-app"
})

@View({
    template: `

My name: {{ myName }}

Friends:

                {{ name }}

    `,
    directives: [ NgFor ]
})

class AppComponent {
    myName: string;
    names: Array<string>;
    constructor() {
        this.myName = "Neil";
        this.names = ["Tom", "Dick", "Harry"];
    }

}
bootstrap(AppComponent);
```

What am I missing?

答:
My problem was caused by a missing export of the component containing the *ngFor. This component (MyComponentWithNgFor) was already imported and declared inside my SharedModule. The SharedModule also imported Angular's CommonModule, so everything looked fine.

However, I was using my component with the *ngFor in another module - let's call it ModuleB - which was importing SharedModule, so that I could use MyComponentWithNgFor.

My solution was simply to add my component containing the *ngFor to my SharedModule's exports array, like so:

```<code>@NgModule({
  imports: [ CommonModule ],
  declarations: [ MyComponentWithNgFor ],
  exports: [ MyComponentWithNgFor ]
})
export class SharedModule { }
</code>```

This made it possible for my ModuleB (which imports SharedModule) to use MyComponentWithNgFor.

Body:
I am trying to follow the basic Angular 2 tutorial here:

https://angular.io/docs/js/latest/guide/displaying-data.html

I can get the angular app to load and display my name with this code:

import { Component, View, bootstrap } from 'angular2/angular2';

@Component({
    selector: "my-app"
})

class AppComponent {
    myName: string;
    names: Array<string>;
    constructor() {
        this.myName = "Neil";

    }

}
bootstrap(AppComponent);

However when I try to add an array of strings and try to display them with an ng-for, it is throwing the following error:

Can't bind to 'ng-forOf' since it isn't a known native property ("

Friends:

]*ng-for="#name of names">
        {{ name }}

"): AppComponent@4:16
Property binding ng-forOf not used by any directive on an embedded template ("

Friends:

        [ERROR ->]

        {{ name }}

"): AppComponent@4:12

Here is the code:

import { Component, View, bootstrap } from 'angular2/angular2';

@Component({
    selector: "my-app"
})

@View({
    template: `

My name: {{ myName }}

Friends:

                {{ name }}

    `,
    directives: [ NgFor ]
})

class AppComponent {
    myName: string;
    names: Array<string>;
    constructor() {
        this.myName = "Neil";
        this.names = ["Tom", "Dick", "Harry"];
    }

}
bootstrap(AppComponent);

What am I missing?

Body:
My problem was caused by a missing export of the component containing the *ngFor. This component (MyComponentWithNgFor) was already imported and declared inside my SharedModule. The SharedModule also imported Angular's CommonModule, so everything looked fine.

However, I was using my component with the *ngFor in another module - let's call it ModuleB - which was importing SharedModule, so that I could use MyComponentWithNgFor.

My solution was simply to add my component containing the *ngFor to my SharedModule's exports array, like so:

@NgModule({
  imports: [ CommonModule ],
  declarations: [ MyComponentWithNgFor ],
  exports: [ MyComponentWithNgFor ]
})
export class SharedModule { }

This made it possible for my ModuleB (which imports SharedModule) to use MyComponentWithNgFor.


问:
$vuetify.goTo('#foo') not working on another router page
I try to smooth scroll using the function: goTo("#how") provided by Vuetify. It worked fine but when I go to a different router page it gives an error.

[Vue warn]: Error in v-on handler: "Error: Target element "#how" not found."

In my knowledge, it means that the target element does not exist.

I tried changing goTo("/#how"), goTo("/how") but it seems to be of no hope.

```<code>//App.vue where the header, footer of my app exist and the button that calls the function: goTo()
<v-btn @click="() => this.$vuetify.goTo('#how')">How it Works</v-btn>
</code>```

```<code>//The section where the page should scroll when the button is clicked
<section id="how">
</section>
</code>```

```<code>//the goTo scroll function provided by Vuetify
scrollBehavior: (to, from, savedPosition) => {
  let scrollTo = 0

  if (to.hash) {
      scrollTo = to.hash
  } else if (savedPosition) {
      scrollTo = savedPosition.y
  }

  return goTo(scrollTo)
}
</code>```

I expect it when on another route page and the button is clicked, it should scroll smoothly to the section.

答:
So, I have found a solution to my problem. It may not be the cleanest way but it works.

My solution is to put a conditional statement for the buttons.

```<code>//First check if the current route is on landing page (or wherever your #foo is) then set the click function for it.
<v-btn v-if='this.$route.path == "/"' color="white" @click="() => this.$vuetify.goTo('#foo')" flat>How it Works</v-btn>

//If route.path is not at "/" then we call the router push to redirect first to Landing and then scroll.
<v-btn v-else color="white" @click="() => this.$router.push('/#foo')" flat>How it Works</v-btn>
</code>```

Body:
I try to smooth scroll using the function: goTo("#how") provided by Vuetify. It worked fine but when I go to a different router page it gives an error.

[Vue warn]: Error in v-on handler: "Error: Target element "#how" not found."

In my knowledge, it means that the target element does not exist.

I tried changing goTo("/#how"), goTo("/how") but it seems to be of no hope.

//App.vue where the header, footer of my app exist and the button that calls the function: goTo()
<v-btn @click="() => this.$vuetify.goTo('#how')">How it Works</v-btn>

//The section where the page should scroll when the button is clicked

//the goTo scroll function provided by Vuetify
scrollBehavior: (to, from, savedPosition) => {
  let scrollTo = 0

  if (to.hash) {
      scrollTo = to.hash
  } else if (savedPosition) {
      scrollTo = savedPosition.y
  }

  return goTo(scrollTo)
}

I expect it when on another route page and the button is clicked, it should scroll smoothly to the section.

Body:
So, I have found a solution to my problem. It may not be the cleanest way but it works.

My solution is to put a conditional statement for the buttons.

//First check if the current route is on landing page (or wherever your #foo is) then set the click function for it.
<v-btn v-if='this.$route.path == "/"' color="white" @click="() => this.$vuetify.goTo('#foo')" flat>How it Works</v-btn>

//If route.path is not at "/" then we call the router push to redirect first to Landing and then scroll.
<v-btn v-else color="white" @click="() => this.$router.push('/#foo')" flat>How it Works</v-btn>


答:
Well maybe you need just create a list like
list = [misura(),misura(),misura()] to get three values respectively and pass it to a function like

```<code>def mean(list) :
    Total = 0
    For item in list :
        Total += item
    Return total /len(list)
</code>```

Title: Python - Average of three values in a while true loop

Body:
I'm developing a python script on a raspberry pi with a distance sensor.
My code is working and i can reach the distance but I want to avoid some false positive/negative so I would like to get the average of the last three data.

Here is my code:

while True:
        distance= misura() # GETTING THE REAL DISTANCE IN CM
        print "Distanza : %.2f" % distanza

        avg_distance = <something> # <- HERE I NEED SOMETHING ELEGANT

        if (avg_distance > 30):
            print "NOT PRESENT"
        else:
            print "PRESENT"

        time.sleep(1.5)

I would like some function (maybe based on a list?) that returns the average of the last three (or n) distances

IMPORTANT:
I don't want to store ALL the values because this script will run for days and days

Body:
Well maybe you need just create a list like
list = [misura(),misura(),misura()] to get three values respectively and pass it to a function like

def mean(list) :
    Total = 0
    For item in list :
        Total += item
    Return total /len(list)


问:
Error using R flextable package - cannot load temporary image file
I am trying to save a data frame as an image file using flextable, with the ultimate goal to plot it next to a ggplot object. Here is example of the code:

```<code>library(flextable)
ft <- flextable( head( mtcars ) )
ft <- autofit(ft)
tf <- tempfile(fileext = ".png")
save_as_image(ft, tf)
</code>```

which returns the following error:

```<code>Could not load  file:///D:/Antonis/Documents/file:/C:/Users/Antonis/AppData/Local/Temp/RtmpmgSSYv/file2510dc77c47.html
Error in webshot::webshot(url = sprintf("file://%s", tf), file = path,  :
  webshot.js returned failure value: 1
In addition: Warning message:
In normalizePath(path.expand(path), winslash, mustWork) :
  path[1]="file://C:\Users\Antonis\AppData\Local\Temp\RtmpmgSSYv\file2510dc77c47.html": The filename, directory name, or volume label syntax is incorrect
</code>```

It seems like the file path is incorrect. I tried to change the working directory with setwd:

```<code>setwd("C:/Users/Antonis/AppData/Local/Temp/RtmpmgSSYv")
</code>```

but the error persists:

```<code>Could not load  file:///C:/Users/Antonis/AppData/Local/Temp/RtmpmgSSYv/file:/C:/Users/Antonis/AppData/Local/Temp/RtmpmgSSYv/file25105e4f2c8b.html
Error in webshot::webshot(url = sprintf("file://%s", tf), file = path,  :
  webshot.js returned failure value: 1
In addition: Warning message:
In normalizePath(path.expand(path), winslash, mustWork) :
  path[1]="file://C:\Users\Antonis\AppData\Local\Temp\RtmpmgSSYv\file25105e4f2c8b.html": The filename, directory name, or volume label syntax is incorrect
</code>```

The same happens when I try to set the path through the tempfile command:

```<code>tf <- tempfile(tmpdir = "C:/Users/Antonis/AppData/Local/Temp/RtmpmgSSYv", fileext = ".png")
</code>```

The save_as_image help file also did not offer some insight.

The above code is quite generic and in fact it is drawn from a blog post, so my problem seems to be local.
Any suggestions?

答:
Not sure about flextable, but you can use tableHTML for this as an alternative. You can specify a file to save locally or it will be saved on a temp file automatically.

```<code>library(tableHTML)
mtcars %>%
 head() %>%
 tableHTML() %>%
 add_theme('scientific') %>%
 tableHTML_to_image()
</code>```

Output:

Body:
I am trying to save a data frame as an image file using flextable, with the ultimate goal to plot it next to a ggplot object. Here is example of the code:

library(flextable)
ft <- flextable( head( mtcars ) )
ft <- autofit(ft)
tf <- tempfile(fileext = ".png")
save_as_image(ft, tf)

which returns the following error:

Could not load  file:///D:/Antonis/Documents/file:/C:/Users/Antonis/AppData/Local/Temp/RtmpmgSSYv/file2510dc77c47.html
Error in webshot::webshot(url = sprintf("file://%s", tf), file = path,  :
  webshot.js returned failure value: 1
In addition: Warning message:
In normalizePath(path.expand(path), winslash, mustWork) :
  path[1]="file://C:\Users\Antonis\AppData\Local\Temp\RtmpmgSSYv\file2510dc77c47.html": The filename, directory name, or volume label syntax is incorrect

It seems like the file path is incorrect. I tried to change the working directory with setwd:

setwd("C:/Users/Antonis/AppData/Local/Temp/RtmpmgSSYv")

but the error persists:

Could not load  file:///C:/Users/Antonis/AppData/Local/Temp/RtmpmgSSYv/file:/C:/Users/Antonis/AppData/Local/Temp/RtmpmgSSYv/file25105e4f2c8b.html
Error in webshot::webshot(url = sprintf("file://%s", tf), file = path,  :
  webshot.js returned failure value: 1
In addition: Warning message:
In normalizePath(path.expand(path), winslash, mustWork) :
  path[1]="file://C:\Users\Antonis\AppData\Local\Temp\RtmpmgSSYv\file25105e4f2c8b.html": The filename, directory name, or volume label syntax is incorrect

The same happens when I try to set the path through the tempfile command:

tf <- tempfile(tmpdir = "C:/Users/Antonis/AppData/Local/Temp/RtmpmgSSYv", fileext = ".png")

The save_as_image help file also did not offer some insight.

The above code is quite generic and in fact it is drawn from a blog post, so my problem seems to be local.
Any suggestions?

Body:
Not sure about flextable, but you can use tableHTML for this as an alternative. You can specify a file to save locally or it will be saved on a temp file automatically.

library(tableHTML)
mtcars %>%
 head() %>%
 tableHTML() %>%
 add_theme('scientific') %>%
 tableHTML_to_image()

Output:


问:
Extjs combobox autocomplete doesn't work
I have an editor grid and a combobox is one of its fields.
The combobox uses a json store.
Here is the combobox code:

```<code>var patternCmb = new Ext.form.ComboBox({ //combobox for workers
    store:  dsPatterns,
    valueField: 'pid',
    displayField: 'pname',
    typeAhead:true,
    lazyRender:true,
    forceSelection:true,
    minChars: 2,
    valueNotFoundText:"not found",
    editable: true,
    triggerAction: 'all'
});
</code>```

After typing the third character the FIRST (not correct) value of the store is selected. What can be the problem?

答:
Try the following:

Set  mode: 'local' in your combobox.

Ensure that you have autoLoad: true in your dsPatterns (store).

Body:
I have an editor grid and a combobox is one of its fields.
The combobox uses a json store.
Here is the combobox code:

var patternCmb = new Ext.form.ComboBox({ //combobox for workers
    store:  dsPatterns,
    valueField: 'pid',
    displayField: 'pname',
    typeAhead:true,
    lazyRender:true,
    forceSelection:true,
    minChars: 2,
    valueNotFoundText:"not found",
    editable: true,
    triggerAction: 'all'
});

After typing the third character the FIRST (not correct) value of the store is selected. What can be the problem?


问:
Bot responding too slow after first message
We have a bot built using Microsoft Boatbuilder and node.js, hosted on Azure. The bot works fine and responds almost instantly when a single user says "Hi". But we have observed that when multiple users are trying to chat, the bot takes anywhere between 30 sec to 1 minute to respond to the first message.

We checked the application logs but there is nothing in there that can explain the cause of this delay.

答: My first guess would be to enable the Always On feature in the bot's appservice.  </p>


问:
How can I identify only base tables when iterating through all tables in SQL smo?
This is my code:

```<code>Server server = new Server(new ServerConnection(con));
server.ConnectionContext.Connect();

foreach (Table table in server.Databases[sqlDatabase].Tables)
{
    if (table <is a base table>)
</code>```

Basically this pulls back views as well I think. The SQL I use to identify the wanted tables is:

SELECT TABLE_NAME FROM MyDatabase.INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE'

However there doesn't seem to be a TABLE_TYPE property on the results which are Microsoft.SqlServer.Management.Smo.TableCollection. According to SQL, the TABLE_TYPE is either BASE TABLE or VIEW so only two possibilities.

How can I identify only tables (and not views)?

答:
It's okay what you did. You can find views this way -> WHERE TABLE_TYPE = 'VIEW', so your select do what you want. I recommend you to open management studio or any other program that allows you to query data and run this:

```<code>SELECT * FROM MyDatabase.INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE'
SELECT * FROM MyDatabase.INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'VIEW'
</code>```

Body:
This is my code:

Server server = new Server(new ServerConnection(con));
server.ConnectionContext.Connect();

foreach (Table table in server.Databases[sqlDatabase].Tables)
{
    if (table <is a base table>)

Basically this pulls back views as well I think. The SQL I use to identify the wanted tables is:

SELECT TABLE_NAME FROM MyDatabase.INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE'

However there doesn't seem to be a TABLE_TYPE property on the results which are Microsoft.SqlServer.Management.Smo.TableCollection. According to SQL, the TABLE_TYPE is either BASE TABLE or VIEW so only two possibilities.

How can I identify only tables (and not views)?

Body:
It's okay what you did. You can find views this way -> WHERE TABLE_TYPE = 'VIEW', so your select do what you want. I recommend you to open management studio or any other program that allows you to query data and run this:

SELECT * FROM MyDatabase.INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE'
SELECT * FROM MyDatabase.INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'VIEW'


问:
Loopback Email Connector not sending emails
I have a Loopback Application with a REST API.

I want to make a REST API Enpoint /Email/sendEmail which sends an email. I did this tutorial: https://loopback.io/doc/en/lb3/Email-connector.html, but it's not working for me somehow.

When I open https://localhost:3000/explorer , I can see the API Endpoint and I can press the button "Try it out". But then it just loads forever and after a while I get a Timeout error in the console.

File: datasource.json

```<code>{
  "db": {
    "host": "localhost",
    "port": 27017,
    "url": "",
    "database": "siemens",
    "password": "",
    "name": "db",
    "user": "",
    "useNewUrlParser": true,
    "connector": "mongodb"
  },
  "email": {
    "name": "email",
    "connector": "mail",
    "transports": [{
      "type": "SMTP",
      "host": "smtp.gmail.com",
      "secure": true,
      "port": 465,
      "auth": {
        "user": "xbit.dany@gmail.com",
        "pass": "XXX"
      }
    }]
  }
}
</code>```

File: model-config.json

```<code>"Email": {
    "dataSource": "email",
    "public": true
  }
</code>```

File: email.js

```<code>module.exports = function(Email) {

  // send an email
  Email.sendEmail = function(cb) {
    console.log("Sending Email");
    Email.app.models.Email.send({
      to: 'siemens.dany@gmail.com',
      from: 'xbit.dany@gmail.com',
      subject: 'my subject',
      text: 'my text',
      html: 'my <em>html</em>'
    }, function(err, mail) {
      console.log('email sent!');
      cb(err);
    });
  }

  Email.remoteMethod(
    'sendEmail', {
      http: {
        path: '/sendEmail',
        verb: 'get'
      },
      returns: {

      }
    }
  );

};
</code>```

File: models/email.json

```<code>{
    "name": "Email",
    "base": "Model",
    "properties": {
      "to": {"type": "String", "required": true},
      "from": {"type": "String", "required": true},
      "subject": {"type": "String", "required": true},
      "text": {"type": "String"},
      "html": {"type": "String"}
    }
}
</code>```

答:
The mail is now working. This is the code of email.js</p>

```<code>module.exports = function(emailDS) {

  // send an email
  emailDS.sendEmail = function(cb) {
    console.log("Sending Email");

    emailDS.app.models.Email.send({
      to: 'siemens.dany@gmail.com',
      from: 'xbit.dany@gmail.com',
      subject: 'my subject',
      html: 'my <em>html</em>'
    }, function(err, mail) {
      console.log("Mail: " + mail);
      console.log("Error: " + err);
      cb(null, mail);
    });
  }

  emailDS.remoteMethod(
    'sendEmail', {
      http: {
        path: '/sendEmail',
        verb: 'get'
      },
      returns: {
        arg: 'Status', type:'string'
      }
    }
  );

};
</code>```

Body:
I have a Loopback Application with a REST API.

I want to make a REST API Enpoint /Email/sendEmail which sends an email. I did this tutorial: https://loopback.io/doc/en/lb3/Email-connector.html, but it's not working for me somehow.

When I open https://localhost:3000/explorer , I can see the API Endpoint and I can press the button "Try it out". But then it just loads forever and after a while I get a Timeout error in the console.

File: datasource.json

{
  "db": {
    "host": "localhost",
    "port": 27017,
    "url": "",
    "database": "siemens",
    "password": "",
    "name": "db",
    "user": "",
    "useNewUrlParser": true,
    "connector": "mongodb"
  },
  "email": {
    "name": "email",
    "connector": "mail",
    "transports": [{
      "type": "SMTP",
      "host": "smtp.gmail.com",
      "secure": true,
      "port": 465,
      "auth": {
        "user": "xbit.dany@gmail.com",
        "pass": "XXX"
      }
    }]
  }
}

File: model-config.json

"Email": {
    "dataSource": "email",
    "public": true
  }

File: email.js

module.exports = function(Email) {

  // send an email
  Email.sendEmail = function(cb) {
    console.log("Sending Email");
    Email.app.models.Email.send({
      to: 'siemens.dany@gmail.com',
      from: 'xbit.dany@gmail.com',
      subject: 'my subject',
      text: 'my text',
      html: 'my html'
    }, function(err, mail) {
      console.log('email sent!');
      cb(err);
    });
  }

  Email.remoteMethod(
    'sendEmail', {
      http: {
        path: '/sendEmail',
        verb: 'get'
      },
      returns: {

      }
    }
  );

};

File: models/email.json

{
    "name": "Email",
    "base": "Model",
    "properties": {
      "to": {"type": "String", "required": true},
      "from": {"type": "String", "required": true},
      "subject": {"type": "String", "required": true},
      "text": {"type": "String"},
      "html": {"type": "String"}
    }
}

Body:
The mail is now working. This is the code of email.js

module.exports = function(emailDS) {

  // send an email
  emailDS.sendEmail = function(cb) {
    console.log("Sending Email");

    emailDS.app.models.Email.send({
      to: 'siemens.dany@gmail.com',
      from: 'xbit.dany@gmail.com',
      subject: 'my subject',
      html: 'my <em>html</em>'
    }, function(err, mail) {
      console.log("Mail: " + mail);
      console.log("Error: " + err);
      cb(null, mail);
    });
  }

  emailDS.remoteMethod(
    'sendEmail', {
      http: {
        path: '/sendEmail',
        verb: 'get'
      },
      returns: {
        arg: 'Status', type:'string'
      }
    }
  );

};


问:
Using Apache Ant APIs in Java program to programmatically build source files
I am looking for good and practical resources that will help me use the Ant APIs effectively. The project website just gives the documentation of the API which is not useful at all. Very few websites seem to give very brief tutorials on the subject.

Is there some resource I am missing out on? How can I use the Ant APIs for simple tasks, without spending hours browsing through them and looking at source code?

Thanks.

(Answers to previously asked questions not helpful - How can i use Apache ANT Programmatically )

答:
As it turns out, the lack of good resources on using the Ant API, is known and intended.
The bottom paragraph of this article from the Ant says -

The question you are probably asking yourself at this point is: How would I know which classes and methods have to be called in order to set up a dummy Project and Target? The answer is: you don't. Ultimately, you have to be willing to get your feet wet and read the source code. The above example is merely designed to whet your appetite and get you started. Go for it!

So this seems to be the only way to make best use of the API.


问:
Sub-components in Vue functional components
As I was playing around with functional components in Vue, I realized that the components property isn't supported to declare sub-components for functional components. Trying do so will result in an Unknown custom element exception.

Except for using global components, is there any way to use sub-components in functional components?

答:
It is a bit of a workaround, but this Github comment suggest using inject instead to inject the component.

```<code><template functional>
  <div>
    <component :is="injections.components.SomeChildren"></component>
  </div>
</template>

<script>
import SomeChildren from "./SomeChildren.vue";
export default {
  inject: {
    components: {
      default: {
        SomeChildren
      }
    }
  }
};
</script>
</code>```

Not as simple as for regular components, but it does the job.

Body:
It is a bit of a workaround, but this Github comment suggest using inject instead to inject the component.

<template functional>
  <div>
    <component :is="injections.components.SomeChildren"></component>
  </div>
</template>

<script>
import SomeChildren from "./SomeChildren.vue";
export default {
  inject: {
    components: {
      default: {
        SomeChildren
      }
    }
  }
};
</script>

Not as simple as for regular components, but it does the job.


问:
How to save and load cookies using Ruby + Selenium WebDriver
How can I save all cookies in Ruby's Selenium WebDriver to a txt-file, then load them later? I don't find any answer which does export and import at the same time

In python looks like a very easy way to do that, how to do it in RUBY?

How to save and load cookies using Python + Selenium WebDriver:

import pickle
import selenium.webdriver

driver = selenium.webdriver.Firefox()
driver.get("http://www.google.com")
pickle.dump( driver.get_cookies() , open("cookies.pkl","wb"))
```

Edits:
I am only using Selenium WebDriver (no capybara etc)

答:
In tests you can use gem show_me_the_cookies (a wrapper/adapter)

cookies = show_me_the_cookies # => [{:name, :domain, :value, :expires, :path, :secure}]
# here you can write them as you like
# and then load and
cookies.each{|c|
  create_cookie(c[:name], c[:value], path: c[:path], domain: c[:domain]) # etc.
}
```

<p>Without gems you can call directly to selenium driver:</p>

<pre class="lang-rb prettyprint-override"><code>driver = Capybara.current_session.driver # or get your selenium driver other way if not using capybara
cookies = driver.browser.manage.all_cookies
# be sure that you've visited a page in your app, selenium cannot create cookies at `about:blank`
driver.browser.manage.add_cookie(name: ..., value:...)
</code>```

Body:
How can I save all cookies in Ruby's Selenium WebDriver to a txt-file, then load them later? I don't find any answer which does export and import at the same time

In python looks like a very easy way to do that, how to do it in RUBY?

How to save and load cookies using Python + Selenium WebDriver:

import pickle
import selenium.webdriver

driver = selenium.webdriver.Firefox()
driver.get("http://www.google.com")
pickle.dump( driver.get_cookies() , open("cookies.pkl","wb"))

Edits:
I am only using Selenium WebDriver (no capybara etc)

Body:
In tests you can use gem show_me_the_cookies (a wrapper/adapter)

cookies = show_me_the_cookies # => [{:name, :domain, :value, :expires, :path, :secure}]
# here you can write them as you like
# and then load and
cookies.each{|c|
  create_cookie(c[:name], c[:value], path: c[:path], domain: c[:domain]) # etc.
}

Without gems you can call directly to selenium driver:

driver = Capybara.current_session.driver # or get your selenium driver other way if not using capybara
cookies = driver.browser.manage.all_cookies
# be sure that you've visited a page in your app, selenium cannot create cookies at `about:blank`
driver.browser.manage.add_cookie(name: ..., value:...)


问:
Load Average/Perfomance problem with php-fpm
When site loaded by users (about 3000 online) I have big perfomance error. I have nginx+php-fpm. When I have some online(~3k) php make big amount of processes. And then Load Average goes to 200+. Have 128gb RAM and 32 cores. After that mane users have 502 error. It helps reboot php-fpm, but not for long, the processes multiply again and the load increases.

Tried different php max child values.

```<code>php.ini :
engine = On
short_open_tag = On
asp_tags = Off
precision = 14
output_buffering = Off
zlib.output_compression = Off
implicit_flush = Off
serialize_precision = 17
expose_php = Off
max_execution_time = 1000
max_input_time = 0
max_input_vars = 10000
error_reporting = E_ERROR
error_reporting =
display_errors = Off
display_startup_errors = On
log_errors = On
log_errors_max_len = 1024
ignore_repeated_errors = On
ignore_repeated_source = Off
report_memleaks = On
track_errors = On
html_errors = On
error_log = /var/log/php-fpm/php-errors.log
variables_order = "GPCS"
request_order = "GP"
register_argc_argv = Off
auto_globals_jit = On
post_max_size = 100M
default_mimetype = "text/html"
default_charset = "UTF-8"
enable_dl = Off
file_uploads = On
upload_tmp_dir =/tmp/php/uploads
upload_max_filesize = 200M
max_file_uploads = 50
allow_url_fopen = On
allow_url_include = Off
default_socket_timeout = 60000
extension=memcache.so
extension=memcached.so
zend_extension=ioncube_loader_lin_7.1.so
cli_server.color = On
date.timezone = "Europe/Kiev"
SMTP = localhost
smtp_port = 25
sendmail_path="/usr/sbin/sendmail -t -i"
mail.add_x_header = On
mail.log =/var/log/php-fpm/php-mail.log
sql.safe_mode = Off
mysql.allow_local_infile = On
mysql.allow_persistent = On
mysql.cache_size = 2000
mysql.max_persistent = -1
mysql.max_links = -1
mysql.default_port =
mysql.default_socket =
mysql.default_host =
mysql.default_user =
mysql.default_password =
mysql.connect_timeout = 3
mysql.trace_mode = Off
mysqli.max_persistent = -1
mysqli.allow_persistent = On
mysqli.max_links = -1
mysqli.cache_size = 2000
mysqli.default_port = 3306
mysqli.default_socket =
mysqli.default_host =
mysqli.default_user =
mysqli.default_pw =
mysqli.reconnect = Off
mysqlnd.collect_statistics = On
mysqlnd.collect_memory_statistics = On
pgsql.allow_persistent = On
pgsql.auto_reset_persistent = Off
pgsql.max_persistent = -1
pgsql.max_links = -1
pgsql.ignore_notice = 0
pgsql.log_notice = 0
session.save_handler = files
session.save_path = "/tmp/php/sessions"
session.use_cookies = 1
;session.cookie_secure =
session.use_only_cookies = 1
session.name = PHPSESSID
session.auto_start = 0
session.cookie_lifetime = 0
session.cookie_path = /
session.cookie_domain =
session.cookie_httponly =
session.serialize_handler = php
session.gc_probability = 1
session.gc_divisor = 1000
session.gc_maxlifetime = 1440
session.bug_compat_42 = On
session.bug_compat_warn = On
session.referer_check =
session.cache_limiter = nocache
session.cache_expire = 180
session.use_trans_sid = 0
session.hash_function = 0
session.hash_bits_per_character = 5
tidy.clean_output = Off
soap.wsdl_cache_enabled=1
soap.wsdl_cache_dir="/tmp"
soap.wsdl_cache_ttl=86400
soap.wsdl_cache_limit = 5
ldap.max_links = -1

ngix.conf:
worker_processes 32;
worker_rlimit_nofile 200000;
load_module "modules/ngx_http_geoip_module.so";

events {
    worker_connections  8000;
    use epoll;
    multi_accept on;
}

http {
    ssl_session_cache   shared:SSL:100m;
    ssl_session_timeout 1h;
    include       mime.types;
    default_type  application/octet-stream;
    include /etc/nginx/conf.d/*.conf;
    include /etc/nginx/sites/*;
    server_tokens off;
    sendfile            on;
    keepalive_timeout   65;
    keepalive_requests 1000;  ###
    reset_timedout_connection on;  ###
    open_file_cache max=200000 inactive=20s;  #####
    open_file_cache_valid 30s; ####
    open_file_cache_min_uses 2; ###
    open_file_cache_errors on; ###
    client_body_timeout 10;  ###
    send_timeout 2;  ###
    chunked_transfer_encoding off;
    server_names_hash_max_size 1024;
    server_names_hash_bucket_size 256;
    client_max_body_size 128m;
    proxy_send_timeout 6000;
    proxy_read_timeout 600;
    large_client_header_buffers 16 32k;
    tcp_nodelay on;
    tcp_nopush on;   ####
    include cloudflare;

    #Compression.
    gzip                on;
    gzip_disable "msie6";
    gzip_vary on;
    gzip_proxied any;
    gzip_comp_level 8;
    gzip_buffers 16 8k;
    gzip_http_version 1.1;
    gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript;

}

fpm.conf:
listen = 127.0.0.1:9001
user = website
group = website
request_slowlog_timeout = 3s
listen.allowed_clients = 127.0.0.1
pm = ondemand
pm.max_children = 4000
pm.start_servers = 5
pm.min_spare_servers = 5
pm.process_idle_timeout = 1s
pm.max_requests = 0
listen.backlog = 8193
pm.status_path = /php-status.html
request_terminate_timeout = 90s
rlimit_files = 131072
rlimit_core = unlimited
catch_workers_output = yes
env[HOSTNAME] = $HOSTNAME
env[TMP] = /tmp
env[TMPDIR] = /tmp
env[TEMP] = /tmp
catch_workers_output = yes
php_flag[display_errors] = on
php_admin_value[error_log] = /var/log/fpm-php.www.log
php_admin_flag[log_errors] = on
</code>```

Can someone help with conf files? Maby something is wrong. He was made for a long time ago and not by me.

答:
Your problem is not about PHP config at this point, IMHO, your problem is about scalability.

You didn't mentionned if your server is statefull or stateless, I suppose, due to your problem that it's statefull.
Plus, you didn't explained if you have a cluster of servers with load balancing, but I assume you've not.

What does that mean ?

It means that your server, for each user, write a file to store its session in the server filesystem.
This process is memory consumer, and its expensive.

A simple math calcul will show your problem,

you said that you have 128G of RAM, and about 3000 users, means they consume all the ram available if your PHP memory limit is about 32M per user. Wich is basically extremely low to be honest in 2019.

Solutions ?

For 3000 user at the same time on a single server, you should consider load balancing.
Load balancing allow your app to be balanced between multiple servers, depends on the trafic. It involves a lot of setup and configurations to start with, but it's doable.

Another solution is to migrate your application to a stateless one. Means that the server does not know about users session, and authentication is done by a token (JWT to the rescue). This solution is not easy to settle, if your app is big, and require some work also.

A link to know more (look for the Performance and Scalability with PHP Sessions section)

Body:
When site loaded by users (about 3000 online) I have big perfomance error. I have nginx+php-fpm. When I have some online(~3k) php make big amount of processes. And then Load Average goes to 200+. Have 128gb RAM and 32 cores. After that mane users have 502 error. It helps reboot php-fpm, but not for long, the processes multiply again and the load increases.

Tried different php max child values.

php.ini :
engine = On
short_open_tag = On
asp_tags = Off
precision = 14
output_buffering = Off
zlib.output_compression = Off
implicit_flush = Off
serialize_precision = 17
expose_php = Off
max_execution_time = 1000
max_input_time = 0
max_input_vars = 10000
error_reporting = E_ERROR
error_reporting =
display_errors = Off
display_startup_errors = On
log_errors = On
log_errors_max_len = 1024
ignore_repeated_errors = On
ignore_repeated_source = Off
report_memleaks = On
track_errors = On
html_errors = On
error_log = /var/log/php-fpm/php-errors.log
variables_order = "GPCS"
request_order = "GP"
register_argc_argv = Off
auto_globals_jit = On
post_max_size = 100M
default_mimetype = "text/html"
default_charset = "UTF-8"
enable_dl = Off
file_uploads = On
upload_tmp_dir =/tmp/php/uploads
upload_max_filesize = 200M
max_file_uploads = 50
allow_url_fopen = On
allow_url_include = Off
default_socket_timeout = 60000
extension=memcache.so
extension=memcached.so
zend_extension=ioncube_loader_lin_7.1.so
cli_server.color = On
date.timezone = "Europe/Kiev"
SMTP = localhost
smtp_port = 25
sendmail_path="/usr/sbin/sendmail -t -i"
mail.add_x_header = On
mail.log =/var/log/php-fpm/php-mail.log
sql.safe_mode = Off
mysql.allow_local_infile = On
mysql.allow_persistent = On
mysql.cache_size = 2000
mysql.max_persistent = -1
mysql.max_links = -1
mysql.default_port =
mysql.default_socket =
mysql.default_host =
mysql.default_user =
mysql.default_password =
mysql.connect_timeout = 3
mysql.trace_mode = Off
mysqli.max_persistent = -1
mysqli.allow_persistent = On
mysqli.max_links = -1
mysqli.cache_size = 2000
mysqli.default_port = 3306
mysqli.default_socket =
mysqli.default_host =
mysqli.default_user =
mysqli.default_pw =
mysqli.reconnect = Off
mysqlnd.collect_statistics = On
mysqlnd.collect_memory_statistics = On
pgsql.allow_persistent = On
pgsql.auto_reset_persistent = Off
pgsql.max_persistent = -1
pgsql.max_links = -1
pgsql.ignore_notice = 0
pgsql.log_notice = 0
session.save_handler = files
session.save_path = "/tmp/php/sessions"
session.use_cookies = 1
;session.cookie_secure =
session.use_only_cookies = 1
session.name = PHPSESSID
session.auto_start = 0
session.cookie_lifetime = 0
session.cookie_path = /
session.cookie_domain =
session.cookie_httponly =
session.serialize_handler = php
session.gc_probability = 1
session.gc_divisor = 1000
session.gc_maxlifetime = 1440
session.bug_compat_42 = On
session.bug_compat_warn = On
session.referer_check =
session.cache_limiter = nocache
session.cache_expire = 180
session.use_trans_sid = 0
session.hash_function = 0
session.hash_bits_per_character = 5
tidy.clean_output = Off
soap.wsdl_cache_enabled=1
soap.wsdl_cache_dir="/tmp"
soap.wsdl_cache_ttl=86400
soap.wsdl_cache_limit = 5
ldap.max_links = -1

ngix.conf:
worker_processes 32;
worker_rlimit_nofile 200000;
load_module "modules/ngx_http_geoip_module.so";

events {
    worker_connections  8000;
    use epoll;
    multi_accept on;
}

http {
    ssl_session_cache   shared:SSL:100m;
    ssl_session_timeout 1h;
    include       mime.types;
    default_type  application/octet-stream;
    include /etc/nginx/conf.d/*.conf;
    include /etc/nginx/sites/*;
    server_tokens off;
    sendfile            on;
    keepalive_timeout   65;
    keepalive_requests 1000;  ###
    reset_timedout_connection on;  ###
    open_file_cache max=200000 inactive=20s;  #####
    open_file_cache_valid 30s; ####
    open_file_cache_min_uses 2; ###
    open_file_cache_errors on; ###
    client_body_timeout 10;  ###
    send_timeout 2;  ###
    chunked_transfer_encoding off;
    server_names_hash_max_size 1024;
    server_names_hash_bucket_size 256;
    client_max_body_size 128m;
    proxy_send_timeout 6000;
    proxy_read_timeout 600;
    large_client_header_buffers 16 32k;
    tcp_nodelay on;
    tcp_nopush on;   ####
    include cloudflare;

    #Compression.
    gzip                on;
    gzip_disable "msie6";
    gzip_vary on;
    gzip_proxied any;
    gzip_comp_level 8;
    gzip_buffers 16 8k;
    gzip_http_version 1.1;
    gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript;

}

fpm.conf:
listen = 127.0.0.1:9001
user = website
group = website
request_slowlog_timeout = 3s
listen.allowed_clients = 127.0.0.1
pm = ondemand
pm.max_children = 4000
pm.start_servers = 5
pm.min_spare_servers = 5
pm.process_idle_timeout = 1s
pm.max_requests = 0
listen.backlog = 8193
pm.status_path = /php-status.html
request_terminate_timeout = 90s
rlimit_files = 131072
rlimit_core = unlimited
catch_workers_output = yes
env[HOSTNAME] = $HOSTNAME
env[TMP] = /tmp
env[TMPDIR] = /tmp
env[TEMP] = /tmp
catch_workers_output = yes
php_flag[display_errors] = on
php_admin_value[error_log] = /var/log/fpm-php.www.log
php_admin_flag[log_errors] = on

Can someone help with conf files? Maby something is wrong. He was made for a long time ago and not by me.


问:
Copying a column in excel and doubling every entry/cell. How to?
Let's say we have a row of elements, 1 per cell: 1,2,3,4.
I want to copy this row(or column) and double every entry: 1,1,2,2,3,3,4,4.

Is there any formula, function, etc that does this? Thanks a lot.

I have about 20k entries so doing it manually is not an option.

答:
You could use:

```<code>Option Explicit

Sub test()

    Dim LastRow As Long, i As Long, j As Long, LastColumn1 As Long, LastColumn2 As Long, Add1 As Long, Add2 As Long
    Dim str As String

    With ThisWorkbook.Worksheets("Sheet1")

        LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row

        For i = 1 To LastRow

            LastColumn1 = .Cells(i, .Columns.Count).End(xlToLeft).Column

            For j = 1 To LastColumn1

                LastColumn2 = .Cells(i, .Columns.Count).End(xlToLeft).Column

                If LastColumn2 = LastColumn1 Then
                    Add1 = 2
                    Add2 = 3
                Else
                    Add1 = 1
                    Add2 = 2
                End If

                .Range(.Cells(i, LastColumn2 + Add1), .Cells(i, LastColumn2 + Add2)).Value = .Cells(i, j).Value

            Next j

        Next i

    End With

End Sub
</code>```

Results:

Body:
You could use:

Option Explicit

Sub test()

    Dim LastRow As Long, i As Long, j As Long, LastColumn1 As Long, LastColumn2 As Long, Add1 As Long, Add2 As Long
    Dim str As String

    With ThisWorkbook.Worksheets("Sheet1")

        LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row

        For i = 1 To LastRow

            LastColumn1 = .Cells(i, .Columns.Count).End(xlToLeft).Column

            For j = 1 To LastColumn1

                LastColumn2 = .Cells(i, .Columns.Count).End(xlToLeft).Column

                If LastColumn2 = LastColumn1 Then
                    Add1 = 2
                    Add2 = 3
                Else
                    Add1 = 1
                    Add2 = 2
                End If

                .Range(.Cells(i, LastColumn2 + Add1), .Cells(i, LastColumn2 + Add2)).Value = .Cells(i, j).Value

            Next j

        Next i

    End With

End Sub

Results:


问:
iText 7 SVGConverter does not render as expected
I'd like to add an SVG coming from the client on a pdf page. When looking at the SVG on the client as well as the SVG image it looks as expected. However, when the SVG is added to the pdf things like fonts, axis, gridlines, etc. are not drawn as expected.

I have tried playing with the CSS definition for font-familiy and axis definitions but none of them had any effect on the output in the PDF. I'm using some non-standard fonts but even when I tried Arial that did not appear on the PDF.

I‘m using iText 7.1.6

Expected Chart:

Resulting SVG in PDF:

Code

```<code>string fPath = System.IO.Path.Combine(fFolder, fName);

DateTime dateTime = DateTime.Now;

PdfWriter writer = new PdfWriter(fPath);
PdfDocument pdf = new PdfDocument(writer);
Document doc = new Document(pdf, PageSize.A4);

string svg = System.IO.File.ReadAllText(@"C:\Users\Public\Desktop\cData.txt");

byte[] byteArray = Encoding.UTF8.GetBytes(svg);

using (MemoryStream ms = new MemoryStream(byteArray))
{

    Image image = SvgConverter.ConvertToImage(ms, pdf);
    image.SetFixedPosition(0, 400);
    image.ScaleToFit(500, 360);
    doc.Add(image);
}

doc.Close();
</code>```

SVG Code (copy in txt-Files

 <svg xmlns="http://www.w3.org/2000/svg" id="reportChartNAVSvg" width="1000" height="720"><defs></defs><g transform="translate(52 52)"><g class="print" style="font-family: Arial; font-size: 26px;"><rect style="fill: #c6b493;" x="114.667" y="617.95" width="52" height="5.2" /><text x="179.6667" y="630.95">Index Performance (CHF)</text></g><g class="grid" font-family="sans-serif" font-size="10" fill="none" text-anchor="end"><path class="domain" style="opacity: 0;" stroke="currentColor" d="M 948 525.5 H 0.5 V 0.5 H 948" /><g class="tick" opacity="1" transform="translate(0 525.5)"><line style="opacity: 0.7; stroke: #d9d9d9;" stroke="currentColor" x2="948" /><text fill="currentColor" x="-3" dy="0.32em" /></g><g class="tick" opacity="1" transform="translate(0 420.5)"><line style="opacity: 0.7; stroke: #d9d9d9;" stroke="currentColor" x2="948" /><text fill="currentColor" x="-3" dy="0.32em" /></g><g class="tick" opacity="1" transform="translate(0 315.5)"><line style="opacity: 0.7; stroke: #d9d9d9;" stroke="currentColor" x2="948" /><text fill="currentColor" x="-3" dy="0.32em" /></g><g class="tick" opacity="1" transform="translate(0 210.5)"><line style="opacity: 0.7; stroke: #d9d9d9;" stroke="currentColor" x2="948" /><text fill="currentColor" x="-3" dy="0.32em" /></g><g class="tick" opacity="1" transform="translate(0 105.5)"><line style="opacity: 0.7; stroke: #d9d9d9;" stroke="currentColor" x2="948" /><text fill="currentColor" x="-3" dy="0.32em" /></g><g class="tick" opacity="1" transform="translate(0 0.5)"><line style="opacity: 0.7; stroke: #d9d9d9;" stroke="currentColor" x2="948" /><text fill="currentColor" x="-3" dy="0.32em" /></g><g class="tick" opacity="1" transform="translate(0 -104.5)"><line style="opacity: 0.7; stroke: #d9d9d9;" stroke="currentColor" x2="948" /><text fill="currentColor" x="-3" dy="0.32em" /></g></g><g class="axis axis-x" font-family="sans-serif" font-size="10" style="font-family: Arial; font-size: 26px;" fill="none" text-anchor="middle" transform="translate(0 525)"><path class="domain" stroke="currentColor" d="M 0.5 0.5 H 948.5" /><g class="tick" opacity="1" transform="translate(69.4825 0.1)"><line stroke="currentColor" y2="0" /><text fill="currentColor" y="3" dy="39">Okt 16</text></g><g class="tick" opacity="1" transform="translate(171.89 0.1)"><line stroke="currentColor" y2="0" /><text fill="currentColor" y="3" dy="39">Jan 17</text></g><g class="tick" opacity="1" transform="translate(271.98 0.1)"><line stroke="currentColor" y2="0" /><text fill="currentColor" y="3" dy="39">Apr 17</text></g><g class="tick" opacity="1" transform="translate(373.228 0.1)"><line stroke="currentColor" y2="0" /><text fill="currentColor" y="3" dy="39">Jul 17</text></g><g class="tick" opacity="1" transform="translate(475.589 0.1)"><line stroke="currentColor" y2="0" /><text fill="currentColor" y="3" dy="39">Okt 17</text></g><g class="tick" opacity="1" transform="translate(577.997 0.1)"><line stroke="currentColor" y2="0" /><text fill="currentColor" y="3" dy="39">Jan 18</text></g><g class="tick" opacity="1" transform="translate(678.087 0.1)"><line stroke="currentColor" y2="0" /><text fill="currentColor" y="3" dy="39">Apr 18</text></g><g class="tick" opacity="1" transform="translate(779.335 0.1)"><line stroke="currentColor" y2="0" /><text fill="currentColor" y="3" dy="39">Jul 18</text></g><g class="tick" opacity="1" transform="translate(881.696 0.1)"><line stroke="currentColor" y2="0" /><text fill="currentColor" y="3" dy="39">Okt 18</text></g></g><g class="axis axis-y-left" font-family="sans-serif" font-size="10" style="font-family: Arial; font-size: 26px;" fill="none" text-anchor="end"><path class="domain" stroke="currentColor" d="M 0.5 525.5 V 0.5" /><g class="tick" opacity="1" transform="translate(0 525.5)"><line stroke="currentColor" x2="0" /><text style="opacity: 1; text-anchor: end;" fill="currentColor" x="-3" dx="-6.5" dy="0.32em">97</text></g><g class="tick" opacity="1" transform="translate(0 420.5)"><line stroke="currentColor" x2="0" /><text style="opacity: 1; text-anchor: end;" fill="currentColor" x="-3" dx="-6.5" dy="0.32em">98</text></g><g class="tick" opacity="1" transform="translate(0 315.5)"><line stroke="currentColor" x2="0" /><text style="opacity: 1; text-anchor: end;" fill="currentColor" x="-3" dx="-6.5" dy="0.32em">99</text></g><g class="tick" opacity="1" transform="translate(0 210.5)"><line stroke="currentColor" x2="0" /><text style="opacity: 1; text-anchor: end;" fill="currentColor" x="-3" dx="-6.5" dy="0.32em">101</text></g><g class="tick" opacity="1" transform="translate(0 105.5)"><line stroke="currentColor" x2="0" /><text style="opacity: 1; text-anchor: end;" fill="currentColor" x="-3" dx="-6.5" dy="0.32em">102</text></g><g class="tick" opacity="1" transform="translate(0 0.5)"><line stroke="currentColor" x2="0" /><text style="opacity: 1; text-anchor: end;" fill="currentColor" x="-3" dx="-6.5" dy="0.32em">103</text></g><g class="tick" opacity="1" transform="translate(0 -104.5)"><line stroke="currentColor" x2="0" /><text style="opacity: 1; text-anchor: end;" fill="currentColor" x="-3" dx="-6.5" dy="0.32em">104</text></g></g><g><path style="fill: none; stroke: #c6b493; stroke-width: 8;" d="M 0 262.5 L 3.33786 262.5 L 34.4913 290.938 L 67.8699 290.938 L 102.408 371.438 L 135.786 409.5 L 165.827 365.313 L 170.277 368.813 L 204.769 346.5 L 235.922 237.563 L 270.367 225.75 L 300.408 197.313 L 303.746 183.267 L 338.237 154.738 L 371.616 228.914 L 406.107 178.439 L 440.598 163.516 L 473.977 152.104 L 508.514 122.697 L 541.893 148.154 L 571.934 111.724 L 576.384 122.258 L 610.876 96.8008 L 642.029 199.068 L 674.249 217.064 L 676.474 217.064 L 706.515 217.064 L 709.853 157.823 L 744.344 202.917 L 777.723 236.516 L 812.214 224.579 L 846.705 285.588 L 880.084 320.513 L 914.621 425.732 L 948 461.099" /></g></g></svg>```

答:
I was able to draw the SVG proper on the PDF. With the following code I could resolve the issue regarding the font. Using the propoer Encoding is important if you need to show the chars in the right language.

```<code>FontProvider provider = new FontProvider();
        provider.AddFont(FontProgramFactory.CreateFont(@"C:\Windows\Fonts\lte50144.ttf"));

        SvgConverterProperties props = new SvgConverterProperties();
        props.SetCharset("Windows-1252");
        props.SetFontProvider(provider);

        byte[] byteArray = Encoding.GetEncoding(1252).GetBytes(svg);

        using (MemoryStream ms = new MemoryStream(byteArray))
        {

            Image image = SvgConverter.ConvertToImage(ms, pdf, props);
            image.SetFixedPosition(llx, lly);
            image.ScaleToFit(width, height);
            doc.Add(image);
        }
</code>```

The SVG itself is being produced in d3.js. The moved x-axis comes from some transform elements on a parent level that is ignored on the child. With a loop over those elemente, removing the transformon the parent and set the absolute position on the child resolved this issue.

Body:
I'd like to add an SVG coming from the client on a pdf page. When looking at the SVG on the client as well as the SVG image it looks as expected. However, when the SVG is added to the pdf things like fonts, axis, gridlines, etc. are not drawn as expected.

I have tried playing with the CSS definition for font-familiy and axis definitions but none of them had any effect on the output in the PDF. I'm using some non-standard fonts but even when I tried Arial that did not appear on the PDF.

I‘m using iText 7.1.6

Expected Chart:

Resulting SVG in PDF:

Code

string fPath = System.IO.Path.Combine(fFolder, fName);

DateTime dateTime = DateTime.Now;

PdfWriter writer = new PdfWriter(fPath);
PdfDocument pdf = new PdfDocument(writer);
Document doc = new Document(pdf, PageSize.A4);

string svg = System.IO.File.ReadAllText(@"C:\Users\Public\Desktop\cData.txt");

byte[] byteArray = Encoding.UTF8.GetBytes(svg);

using (MemoryStream ms = new MemoryStream(byteArray))
{

    Image image = SvgConverter.ConvertToImage(ms, pdf);
    image.SetFixedPosition(0, 400);
    image.ScaleToFit(500, 360);
    doc.Add(image);
}

doc.Close();

SVG Code (copy in txt-Files

 <svg xmlns="http://www.w3.org/2000/svg" id="reportChartNAVSvg" width="1000" height="720"><defs></defs><g transform="translate(52 52)"><g class="print" style="font-family: Arial; font-size: 26px;"><rect style="fill: #c6b493;" x="114.667" y="617.95" width="52" height="5.2" /><text x="179.6667" y="630.95">Index Performance (CHF)</text></g><g class="grid" font-family="sans-serif" font-size="10" fill="none" text-anchor="end"><path class="domain" style="opacity: 0;" stroke="currentColor" d="M 948 525.5 H 0.5 V 0.5 H 948" /><g class="tick" opacity="1" transform="translate(0 525.5)"><line style="opacity: 0.7; stroke: #d9d9d9;" stroke="currentColor" x2="948" /><text fill="currentColor" x="-3" dy="0.32em" /></g><g class="tick" opacity="1" transform="translate(0 420.5)"><line style="opacity: 0.7; stroke: #d9d9d9;" stroke="currentColor" x2="948" /><text fill="currentColor" x="-3" dy="0.32em" /></g><g class="tick" opacity="1" transform="translate(0 315.5)"><line style="opacity: 0.7; stroke: #d9d9d9;" stroke="currentColor" x2="948" /><text fill="currentColor" x="-3" dy="0.32em" /></g><g class="tick" opacity="1" transform="translate(0 210.5)"><line style="opacity: 0.7; stroke: #d9d9d9;" stroke="currentColor" x2="948" /><text fill="currentColor" x="-3" dy="0.32em" /></g><g class="tick" opacity="1" transform="translate(0 105.5)"><line style="opacity: 0.7; stroke: #d9d9d9;" stroke="currentColor" x2="948" /><text fill="currentColor" x="-3" dy="0.32em" /></g><g class="tick" opacity="1" transform="translate(0 0.5)"><line style="opacity: 0.7; stroke: #d9d9d9;" stroke="currentColor" x2="948" /><text fill="currentColor" x="-3" dy="0.32em" /></g><g class="tick" opacity="1" transform="translate(0 -104.5)"><line style="opacity: 0.7; stroke: #d9d9d9;" stroke="currentColor" x2="948" /><text fill="currentColor" x="-3" dy="0.32em" /></g></g><g class="axis axis-x" font-family="sans-serif" font-size="10" style="font-family: Arial; font-size: 26px;" fill="none" text-anchor="middle" transform="translate(0 525)"><path class="domain" stroke="currentColor" d="M 0.5 0.5 H 948.5" /><g class="tick" opacity="1" transform="translate(69.4825 0.1)"><line stroke="currentColor" y2="0" /><text fill="currentColor" y="3" dy="39">Okt 16</text></g><g class="tick" opacity="1" transform="translate(171.89 0.1)"><line stroke="currentColor" y2="0" /><text fill="currentColor" y="3" dy="39">Jan 17</text></g><g class="tick" opacity="1" transform="translate(271.98 0.1)"><line stroke="currentColor" y2="0" /><text fill="currentColor" y="3" dy="39">Apr 17</text></g><g class="tick" opacity="1" transform="translate(373.228 0.1)"><line stroke="currentColor" y2="0" /><text fill="currentColor" y="3" dy="39">Jul 17</text></g><g class="tick" opacity="1" transform="translate(475.589 0.1)"><line stroke="currentColor" y2="0" /><text fill="currentColor" y="3" dy="39">Okt 17</text></g><g class="tick" opacity="1" transform="translate(577.997 0.1)"><line stroke="currentColor" y2="0" /><text fill="currentColor" y="3" dy="39">Jan 18</text></g><g class="tick" opacity="1" transform="translate(678.087 0.1)"><line stroke="currentColor" y2="0" /><text fill="currentColor" y="3" dy="39">Apr 18</text></g><g class="tick" opacity="1" transform="translate(779.335 0.1)"><line stroke="currentColor" y2="0" /><text fill="currentColor" y="3" dy="39">Jul 18</text></g><g class="tick" opacity="1" transform="translate(881.696 0.1)"><line stroke="currentColor" y2="0" /><text fill="currentColor" y="3" dy="39">Okt 18</text></g></g><g class="axis axis-y-left" font-family="sans-serif" font-size="10" style="font-family: Arial; font-size: 26px;" fill="none" text-anchor="end"><path class="domain" stroke="currentColor" d="M 0.5 525.5 V 0.5" /><g class="tick" opacity="1" transform="translate(0 525.5)"><line stroke="currentColor" x2="0" /><text style="opacity: 1; text-anchor: end;" fill="currentColor" x="-3" dx="-6.5" dy="0.32em">97</text></g><g class="tick" opacity="1" transform="translate(0 420.5)"><line stroke="currentColor" x2="0" /><text style="opacity: 1; text-anchor: end;" fill="currentColor" x="-3" dx="-6.5" dy="0.32em">98</text></g><g class="tick" opacity="1" transform="translate(0 315.5)"><line stroke="currentColor" x2="0" /><text style="opacity: 1; text-anchor: end;" fill="currentColor" x="-3" dx="-6.5" dy="0.32em">99</text></g><g class="tick" opacity="1" transform="translate(0 210.5)"><line stroke="currentColor" x2="0" /><text style="opacity: 1; text-anchor: end;" fill="currentColor" x="-3" dx="-6.5" dy="0.32em">101</text></g><g class="tick" opacity="1" transform="translate(0 105.5)"><line stroke="currentColor" x2="0" /><text style="opacity: 1; text-anchor: end;" fill="currentColor" x="-3" dx="-6.5" dy="0.32em">102</text></g><g class="tick" opacity="1" transform="translate(0 0.5)"><line stroke="currentColor" x2="0" /><text style="opacity: 1; text-anchor: end;" fill="currentColor" x="-3" dx="-6.5" dy="0.32em">103</text></g><g class="tick" opacity="1" transform="translate(0 -104.5)"><line stroke="currentColor" x2="0" /><text style="opacity: 1; text-anchor: end;" fill="currentColor" x="-3" dx="-6.5" dy="0.32em">104</text></g></g><g><path style="fill: none; stroke: #c6b493; stroke-width: 8;" d="M 0 262.5 L 3.33786 262.5 L 34.4913 290.938 L 67.8699 290.938 L 102.408 371.438 L 135.786 409.5 L 165.827 365.313 L 170.277 368.813 L 204.769 346.5 L 235.922 237.563 L 270.367 225.75 L 300.408 197.313 L 303.746 183.267 L 338.237 154.738 L 371.616 228.914 L 406.107 178.439 L 440.598 163.516 L 473.977 152.104 L 508.514 122.697 L 541.893 148.154 L 571.934 111.724 L 576.384 122.258 L 610.876 96.8008 L 642.029 199.068 L 674.249 217.064 L 676.474 217.064 L 706.515 217.064 L 709.853 157.823 L 744.344 202.917 L 777.723 236.516 L 812.214 224.579 L 846.705 285.588 L 880.084 320.513 L 914.621 425.732 L 948 461.099" /></g></g></svg>

Body:
I was able to draw the SVG proper on the PDF. With the following code I could resolve the issue regarding the font. Using the propoer Encoding is important if you need to show the chars in the right language.

FontProvider provider = new FontProvider();
        provider.AddFont(FontProgramFactory.CreateFont(@"C:\Windows\Fonts\lte50144.ttf"));

        SvgConverterProperties props = new SvgConverterProperties();
        props.SetCharset("Windows-1252");
        props.SetFontProvider(provider);

        byte[] byteArray = Encoding.GetEncoding(1252).GetBytes(svg);

        using (MemoryStream ms = new MemoryStream(byteArray))
        {

            Image image = SvgConverter.ConvertToImage(ms, pdf, props);
            image.SetFixedPosition(llx, lly);
            image.ScaleToFit(width, height);
            doc.Add(image);
        }

The SVG itself is being produced in d3.js. The moved x-axis comes from some transform elements on a parent level that is ignored on the child. With a loop over those elemente, removing the transformon the parent and set the absolute position on the child resolved this issue.