问:
Hooks in FeathersJS or Sequelize
Given the scenario I want to insert a default value in a database column (date_introduced). I'm considering two alternatives:

use a hook in sequelize (hook: beforeCreate)

use a hook in feathersJS (hook: create)

What would be the specific benefits for each alternative? But of course there are other scenario's like checking on an input, etc... each with their own concerns.

答:
Write a simple migration for your Sequelize DB.

'use strict';

module.exports = {
  up: function (queryInterface, Sequelize) {
    return queryInterface.changeColumn('tableName', 'columnName', {
      type: Sequelize.STRING,
      defaultValue: <defaultValue>
    });
  },

  down: function (queryInterface, Sequelize) {
    return queryInterface.changeColumn('tableName', 'columnName', {
      type: Sequelize.STRING,
      defaultValue: null
    });
  }
};```

You can find more info in official documentation of feathers.

Title: Hooks in FeathersJS or Sequelize

Body:
Write a simple migration for your Sequelize DB.

'use strict';

module.exports = {
  up: function (queryInterface, Sequelize) {
    return queryInterface.changeColumn('tableName', 'columnName', {
      type: Sequelize.STRING,
      defaultValue: <defaultValue>
    });
  },

  down: function (queryInterface, Sequelize) {
    return queryInterface.changeColumn('tableName', 'columnName', {
      type: Sequelize.STRING,
      defaultValue: null
    });
  }
};

You can find more info in official documentation of feathers.


来源: stackexchange

问:
how to make bouncing ball application
I have been following http://www.bit-101.com/blog/?p=1798 tutorial to make bouncing ball app.
But what i want to do is make 20-30 balls which can be dragged anywhere in the iphone screen on user touch and also can be dropped anywhere in the screen.So please can anyone suggest me on this -- how to do this in i phone not using cocos2d please help me out or give me some links or useful information any help will be appreciated.....</p>

答:
you can use timer {

pos = CGPointMake(7.0, 14.0);
    timer=[NSTimer scheduledTimerWithTimeInterval:0.05 target:self selector:@selector(onTimer) userInfo:nil repeats:YES];
}

and call the method using selector

-(void)onTimer{
    image.center = CGPointMake(image.center.x+pos.x ,image.center.y+pos.y );
    if (image.center.x>320 || image.center.x<0)
        pos.x=-pos.x;

```<code>    if (image.center.y>460 || image.center <0 )
    pos.y=-pos.y;
</code>```

}

by this u can move image in iphone screen and use touch move to hold that image

ContentLicense: CC BY-SA 3.0

Title: how to make bouncing ball application

Body:
you can use timer {

pos = CGPointMake(7.0, 14.0);
    timer=[NSTimer scheduledTimerWithTimeInterval:0.05 target:self selector:@selector(onTimer) userInfo:nil repeats:YES];
}

and call the method using selector

-(void)onTimer{
    image.center = CGPointMake(image.center.x+pos.x ,image.center.y+pos.y );
    if (image.center.x>320 || image.center.x<0)
        pos.x=-pos.x;

    if (image.center.y>460 || image.center <0 )
    pos.y=-pos.y;

}

by this u can move image in iphone screen and use touch move to hold that image


问:
Laravel 5.8 Won’t Connect to Non-Local Database
I am having an issue where a new Laravel Project (5.8) will not connect to a non-local database. I continue getting an “Access Denied for User...” error. I know that the configuration is correct because I have another project running in 5.6 connecting to the same database with the same configuration and it works. It appears that once I use a hostname other than “localhost”, it breaks. It was working locally until I attempted to connect to another non-local database.

I believe Laravel is not accepting the hostname correctly. I have recached everything as well, with no luck. The access denied error always shows the same local hostname of the machine the project is on, never the remote hostname in the env, so I assume it is trying to connect to that. Any ideas on how to fix this issue? I am stumped with no idea where to go.

Thanks in advance!

EDIT:
I know for sure there is not a configuration error, IP access error, or caching error as I have already troubleshooted all of these possible issues (it sounds like one of these issues). My env and the error are below (anything starting with "my" is the correct information that I have changed for security):

DB_CONNECTION=mysql
DB_HOST=mysql.myURL.com
DB_PORT=3306
DB_DATABASE=myDbName
DB_USERNAME=myDbUsername
DB_PASSWORD=myDbPassword
```

<pre class="lang-sql prettyprint-override"><code>SQLSTATE[HY000] [1045] Access denied for user 'myDbUsername'@'NOTmysql.myURL.com' (using password: YES) (SQL: select count(*) as aggregate from `myTable`)
</code>```

NOTmysql.myURL.com in the error actually happens to be the local hostname of the server that the website is running on, but myDbUsername is the username I set in the configuration.

答:
1. Go to the .env file and check the database configuration

```<code>DB_HOST=localhost
DB_DATABASE=laravelDb
DB_USERNAME=root
DB_PASSWORD=null
</code>```

2. Then restart the apache server and refresh the page

3. Exit/close and re-run the command

```<code>php artisan serve
</code>```

4. Clear the old configuration cache and config file

```<code>php artisan config:clear
php artisan cache:clear
</code>```

Now your error should be gone.

ContentLicense: CC BY-SA 4.0

Body:
I am having an issue where a new Laravel Project (5.8) will not connect to a non-local database. I continue getting an “Access Denied for User...” error. I know that the configuration is correct because I have another project running in 5.6 connecting to the same database with the same configuration and it works. It appears that once I use a hostname other than “localhost”, it breaks. It was working locally until I attempted to connect to another non-local database.

I believe Laravel is not accepting the hostname correctly. I have recached everything as well, with no luck. The access denied error always shows the same local hostname of the machine the project is on, never the remote hostname in the env, so I assume it is trying to connect to that. Any ideas on how to fix this issue? I am stumped with no idea where to go.

Thanks in advance!

EDIT:
I know for sure there is not a configuration error, IP access error, or caching error as I have already troubleshooted all of these possible issues (it sounds like one of these issues). My env and the error are below (anything starting with "my" is the correct information that I have changed for security):

DB_CONNECTION=mysql
DB_HOST=mysql.myURL.com
DB_PORT=3306
DB_DATABASE=myDbName
DB_USERNAME=myDbUsername
DB_PASSWORD=myDbPassword

SQLSTATE[HY000] [1045] Access denied for user 'myDbUsername'@'NOTmysql.myURL.com' (using password: YES) (SQL: select count(*) as aggregate from `myTable`)

NOTmysql.myURL.com in the error actually happens to be the local hostname of the server that the website is running on, but myDbUsername is the username I set in the configuration.

Body:
1. Go to the .env file and check the database configuration

DB_HOST=localhost
DB_DATABASE=laravelDb
DB_USERNAME=root
DB_PASSWORD=null

2. Then restart the apache server and refresh the page

3. Exit/close and re-run the command

php artisan serve

4. Clear the old configuration cache and config file

php artisan config:clear
php artisan cache:clear

Now your error should be gone.


问:
Not able to connect with Neo4j Desktop Online
I have newly started Neo4j, for this I have downloaded Neo4j Desktop version- 1.1.22, but it always says No Internet connection.

On developer tools, I have found the below issue.

Does anyone has resolved this issue?

答:
There is some issue with new versions of Neo4j Desktop.
I was facing the same issue for these versions 1.1.17, 1.1.18, 1.1.20 and 1.1.21 on Windows.

I have reverted back to version 1.1.15 It's working as expected.

You can download 1.1.15 here.


问:
Simply search a string in entire netbeans solution
Is there a way to find the entire solution for a string in netbeans.
I believe that there is a find [      ] tab to find a word in the .java file but looking to find the word in the entire solution.

p.s. Not to find and replace.

Thanks alot in advance.

答:
ctrl + shift + F is the shortest way.

You can define the wildcard there.


答:
Try using this simple approach:

```<code>import functools
import operator

temp_data = functools.reduce(operator.concat, org_time_list) #flatten the list of lists
df_3 = pd.DataFrame(temp_data, columns=['Date', 'DateValue'])
</code>```

If you can show how your original data looks like I think the first loop can be avoided too.

Title: How to keep adding data frames to an existing dataframe?

Body:
My input is a list of lists. I am trying to convert each sublist into a data frame with two columns and then convert all the data frames together.

I have about more than 80 sublists in that list, the following is just an example:

[[('04-24-2019 18:51:54:629', 'a'),
  ('04-24-2019 18:51:54:790', 'p'),
  ('04-24-2019 18:51:54:934', 'p'),
  ('04-24-2019 18:51:55:65', 'l'),
  ('04-24-2019 18:51:55:157', 'e'),
  ('04-24-2019 18:51:57:710', 'b'),
  ('04-24-2019 18:51:57:862', 'o'),
  ('04-24-2019 18:51:58:501', 'backspace'),
  ('04-24-2019 18:51:59:368', 'e'),
  ('04-24-2019 18:51:59:507', 'e'),
  ('04-24-2019 18:51:59:800', 's'),
  ('04-24-2019 18:52:05:502', 'backspace')],
 [('04-24-2019 18:51:54:629', 'a'),
  ('04-24-2019 18:51:54:790', 'p'),
  ('04-24-2019 18:51:54:934', 'p'),
  ('04-24-2019 18:51:55:65', 'l'),
  ('04-24-2019 18:51:55:157', 'e'),
  ('04-24-2019 18:51:57:710', 'b'),
  ('04-24-2019 18:51:57:862', 'o'),
  ('04-24-2019 18:51:58:501', 'backspace'),
  ('04-24-2019 18:51:59:368', 'e'),
  ('04-24-2019 18:51:59:507', 'e'),
  ('04-24-2019 18:51:59:800', 's'),
  ('04-24-2019 18:52:05:502', 'backspace')],
 [('04-24-2019 18:51:54:629', 'a'),
  ('04-24-2019 18:51:54:790', 'p'),
  ('04-24-2019 18:51:54:934', 'p'),
  ('04-24-2019 18:51:55:65', 'l'),
  ('04-24-2019 18:51:55:157', 'e'),
  ('04-24-2019 18:51:57:710', 'b'),
  ('04-24-2019 18:51:57:862', 'o'),
  ('04-24-2019 18:51:58:501', 'backspace'),
  ('04-24-2019 18:51:59:368', 'e'),
  ('04-24-2019 18:51:59:507', 'e'),
  ('04-24-2019 18:51:59:800', 's'),
  ('04-24-2019 18:52:05:502', 'backspace')]]

This is converting original data into a list of lists -

org_time_list = []
for x in range(len(data)):
    dd = (data[x]["input_clicks"])
    org_time_list.append(list(dd.items()))
org_time_list

This is trying to convert each sublist to a data frame and append those data frames together -

df_3 = pd.DataFrame()
for x in org_time_list:
    for y in x:
        df_3.append(pd.DataFrame((y), columns=['Date', 'DateValue']))
df_3

I am expecting to have a dataframe that contains all of the data from the list of lists with two columns only. The following is an example of a sublist.

Date    DateValue
0   04-24-2019 18:51:54:629 a
1   04-24-2019 18:51:54:790 p
2   04-24-2019 18:51:54:934 p
3   04-24-2019 18:51:55:65  l
4   04-24-2019 18:51:55:157 e
5   04-24-2019 18:51:57:710 b
6   04-24-2019 18:51:57:862 o
7   04-24-2019 18:51:58:501 backspace
8   04-24-2019 18:51:59:368 e
9   04-24-2019 18:51:59:507 e
10  04-24-2019 18:51:59:800 s
11  04-24-2019 18:52:05:502 backspace

Body:
Try using this simple approach:

import functools
import operator

temp_data = functools.reduce(operator.concat, org_time_list) #flatten the list of lists
df_3 = pd.DataFrame(temp_data, columns=['Date', 'DateValue'])

If you can show how your original data looks like I think the first loop can be avoided too.


问:
Is there any way to implement Initializer lists (kind of) in older version of c++ (Before c++11)?
i have tried to implement (kind of :) Initializer lists in older version of c++. like below..

```<code>#include <vector>
#include <cstdarg>
#include <iostream>

using namespace std;

template <class T>
vector <T> VEC_VA(size_t argCount,T arg1, ... )
{
    va_list arguments;
    vector <T> sList;

    va_start ( arguments, argCount);
    for ( int x = 0; x < (int)argCount; x++ )
        sList.push_back(va_arg ( arguments, T));
    va_end ( arguments );

    return sList;
}

struct Test
{
    Test(int _x,std::string _s):x(_x),s(_s){}
    int x;
    std::string s;
};

void methodWithArgs(vector<Test> testObjs)
{
    cout<<"Size:"<<testObjs.size()<<endl;
    for (std::vector<Test>::const_iterator it = testObjs.begin();it != testObjs.end();++it)
        std::cout << it->x <<":"<< it->s.c_str()<< std::endl;
}

int main()
{
    methodWithArgs(VEC_VA(2,Test(1,"one"),Test(2,"two")));
    return 0;
}
</code>```

But this kind of implementation works in Visual studio 2012 (v11.0). But not in Linux g++ compiler. And ended with an Error: "cannot pass objects of non-trivially-copyable type ‘struct Test’ through ‘...’"

So is there any better idea?

答:
Same as like this above answer by daniel But some improvements

```<code>template <class T>
class VECS
{
    vector <T> vec;
    public:
        VECS(){}
        VECS(T t){vec.push_back(t);}
        VECS& operator()(const T& t){vec.push_back(t);return *this;}
        typedef VECS<T> myVECS;
        myVECS& operator<< (const T& t){vec.push_back(t);return *this;}
        operator vector<T>() const {return vec;}
};
</code>```

Usage

```<code>    methodWithArgs(VECS<Test>(Test(1,"one"))(Test(2,"two")));
    methodWithArgs(VECS<Test>()<<Test(1,"one")<<Test(2,"two"));
    methodWithArgs(VECS<Test>(Test(0,"zero")) <<Test(1,"one")<<Test(2,"two"));

    std::vector<int> v1 = VECS<int>() << 1 << 2 << 3;
    std::vector<int> v2 = VECS<int>(1)(2)(3);
</code>```

Body:
i have tried to implement (kind of :) Initializer lists in older version of c++. like below..

#include <vector>
#include <cstdarg>
#include <iostream>

using namespace std;

template <class T>
vector <T> VEC_VA(size_t argCount,T arg1, ... )
{
    va_list arguments;
    vector <T> sList;

    va_start ( arguments, argCount);
    for ( int x = 0; x < (int)argCount; x++ )
        sList.push_back(va_arg ( arguments, T));
    va_end ( arguments );

    return sList;
}

struct Test
{
    Test(int _x,std::string _s):x(_x),s(_s){}
    int x;
    std::string s;
};

void methodWithArgs(vector<Test> testObjs)
{
    cout<<"Size:"<<testObjs.size()<<endl;
    for (std::vector<Test>::const_iterator it = testObjs.begin();it != testObjs.end();++it)
        std::cout << it->x <<":"<< it->s.c_str()<< std::endl;
}

int main()
{
    methodWithArgs(VEC_VA(2,Test(1,"one"),Test(2,"two")));
    return 0;
}

But this kind of implementation works in Visual studio 2012 (v11.0). But not in Linux g++ compiler. And ended with an Error: "cannot pass objects of non-trivially-copyable type ‘struct Test’ through ‘...’"

So is there any better idea?

Body:
Same as like this above answer by daniel But some improvements

template <class T>
class VECS
{
    vector <T> vec;
    public:
        VECS(){}
        VECS(T t){vec.push_back(t);}
        VECS& operator()(const T& t){vec.push_back(t);return *this;}
        typedef VECS<T> myVECS;
        myVECS& operator<< (const T& t){vec.push_back(t);return *this;}
        operator vector<T>() const {return vec;}
};

Usage

    methodWithArgs(VECS<Test>(Test(1,"one"))(Test(2,"two")));
    methodWithArgs(VECS<Test>()<<Test(1,"one")<<Test(2,"two"));
    methodWithArgs(VECS<Test>(Test(0,"zero")) <<Test(1,"one")<<Test(2,"two"));

    std::vector<int> v1 = VECS<int>() << 1 << 2 << 3;
    std::vector<int> v2 = VECS<int>(1)(2)(3);


问:
Nginx ingress controller rate limiting not working
```<code>  annotations:
    kubernetes.io/ingress.class: "nginx"
    nginx.ingress.kubernetes.io/limit-connection: "1"
    nginx.ingress.kubernetes.io/limit-rpm: "20"
</code>```

and the container image version, iam using,
image: quay.io/kubernetes-ingress-controller/nginx-ingress-controller:0.22.0

trying to send 200 requests in ten mins of range (and per min it is like a 20 requests from a single ipaddress) and after that it has to refuse the requests.

答: Which nginx ingress version are you using ?  please use quay.io/aledbf/nginx-ingress-controller:0.415 and then check, Also Please look at this link - https://github.com/kubernetes/ingress-nginx/issues/1839</p>

Body:
  annotations:
    kubernetes.io/ingress.class: "nginx"
    nginx.ingress.kubernetes.io/limit-connection: "1"
    nginx.ingress.kubernetes.io/limit-rpm: "20"

and the container image version, iam using,
image: quay.io/kubernetes-ingress-controller/nginx-ingress-controller:0.22.0

trying to send 200 requests in ten mins of range (and per min it is like a 20 requests from a single ipaddress) and after that it has to refuse the requests.


问:
Problem running ng serve command on Windows 10. This question is different and it is not duplicate
I am unable to run ng serve command on Windows 10

I have successfully installed npm and node

I am trying to install angular on Windows 10.

1- My node version is

```<code>node -v
v10.16.0
</code>```

and npm version is

```<code>npm -v
6.9.0
</code>```

After running command of angular cli which is

```<code>npm install -g @angular/cli
</code>```

I am not able to run ng serve command. It show this error

```<code>'ng' is not recognized as an internal or external command,
operable program or batch file.
</code>```

I have looked some online solutions which says to set 'PATH` but my path npm folder is empty

```<code>
C:\Users\shaha\AppData\Roaming\npm
</code>```

I have tried many times uninstallation and installation of nodejs but I am unable to run ng serve command. Please help me to solve this issue.

答:
Its because of environment path setup

For now you can use npm run ng serve command

Body:
I am unable to run ng serve command on Windows 10

I have successfully installed npm and node

I am trying to install angular on Windows 10.

1- My node version is

node -v
v10.16.0

and npm version is

npm -v
6.9.0

After running command of angular cli which is

npm install -g @angular/cli

I am not able to run ng serve command. It show this error

'ng' is not recognized as an internal or external command,
operable program or batch file.

I have looked some online solutions which says to set 'PATH` but my path npm folder is empty

C:\Users\shaha\AppData\Roaming\npm

I have tried many times uninstallation and installation of nodejs but I am unable to run ng serve command. Please help me to solve this issue.


问:
How to select the maximum quarter from the result set?
I have a list of period for each quarter for many years, I need to select the maximum period from the result.

Say for example, the actual data would be like this;

```<code>**period description**
2014 Q2
2014 Q1
2018 Q3
2016 Q1
2017 Q4
2018 Q4
</code>```

Here I need to fetch only the latest quarter in the given data..i.e. we need to get 2018 Q4.

I tried :

```<code>select substring  (perioddescription, 1, 4)
</code>```

but I've a string in between them so any help would be much appreciated.thanks in advacne

答:
A simple MAX function can give you the desired output-

```<code>SELECT MAX(period_description)
FROM
(
    SELECT '2014 Q2' period_description UNION ALL
    SELECT '2014 Q1' UNION ALL
    SELECT '2018 Q3' UNION ALL
    SELECT '2016 Q1' UNION ALL
    SELECT '2017 Q4' UNION ALL
    SELECT '2018 Q4'
)A
</code>```

Output is-

```<code>2018 Q4
</code>```

Body:
I have a list of period for each quarter for many years, I need to select the maximum period from the result.

Say for example, the actual data would be like this;

**period description**
2014 Q2
2014 Q1
2018 Q3
2016 Q1
2017 Q4
2018 Q4

Here I need to fetch only the latest quarter in the given data..i.e. we need to get 2018 Q4.

I tried :

select substring  (perioddescription, 1, 4)

but I've a string in between them so any help would be much appreciated.thanks in advacne

Body:
A simple MAX function can give you the desired output-

SELECT MAX(period_description)
FROM
(
    SELECT '2014 Q2' period_description UNION ALL
    SELECT '2014 Q1' UNION ALL
    SELECT '2018 Q3' UNION ALL
    SELECT '2016 Q1' UNION ALL
    SELECT '2017 Q4' UNION ALL
    SELECT '2018 Q4'
)A

Output is-

2018 Q4


问:
In Hudson, how do I get the current build's git commit sha?
We are using Hudson with git. We have a build/test server which compiles our project and then a QA server to which we need to deploy.

We want to get the current built git commit sha and use it to pull the appropriate commit for deployment on our QA server.

Unfortunately it seems that the hudon git plugin does not set the git commit sha in the environment variables (as the svn plugin does in  SVN_REVISION for example). How do we get around this?

Pointer/ examples will be helpful as I am a hudson noob.

Thanks

答: This is apparently not possible with the current version of the git plugin. We are instead writing current head to a file and saving it as an artifact. We can later curl it and get the commit id corresponding to a given build.</p>

ContentLicense: CC BY-SA 2.5


问:
Why late init var cannot be used with Nullable?
Why can't we use lateinit with nullable variables?

```<code>lateinit var v: String?
</code>```

lateinit modifier is not allowed on properties of nullable types

答:
One of the main feature in kotlin is Null Safe.

By default it won't allow u to create a null value. You have explicitly defined

 var a: String? = null

            , If u don't want to initialise any value to the variable there come "lateinit". While using lateinit variable You do pre-check whether it is initialised or not

Body:
Why can't we use lateinit with nullable variables?

lateinit var v: String?

lateinit modifier is not allowed on properties of nullable types


问:
RobotParser throws SSL Certificate Verify Failed exception
I'm writing a simple webcrawler in Python 2.7 and am getting an SSL Certificate Verify Failed exception when attempting to retrieve the robots.txt file from an HTTPS website.

Here's the relevant code:

```<code>def getHTMLpage(pagelink, currenttime):
    "Downloads HTML page from server"
    #init
    #parse URL and get domain name
    o = urlparse.urlparse(pagelink,"http")
    if o.netloc == "":
        netloc = re.search(r"[^/]+\.[^/]+\.[^/]+", o.path)
        if netloc:
            domainname="http://"+netloc.group(0)+"/"
    else:
        domainname=o.scheme+"://"+o.netloc+"/"
    if o.netloc != "" and o.netloc != None and o.scheme != "mailto": #if netloc isn't empty and it's not a mailto link
        link=domainname+o.path[1:]+o.params+"?"+o.query+"#"+o.fragment
        if not (robotfiledictionary.get(domainname)): #if robot file for domainname was not downloaded
            robotfiledictionary[domainname] = robotparser.RobotFileParser() #initialize robots.txt parser
            robotfiledictionary[domainname].set_url(domainname+"robots.txt") #set url for robots.txt
            print "  Robots.txt for %s initial download" % str(domainname)
            robotfiledictionary[domainname].read() #download/read robots.txt
        elif (robotfiledictionary.get(domainname)): #if robot file for domainname was already downloaded
            if (currenttime - robotfiledictionary[domainname].mtime()) > 3600: #if robot file is older than 1 hour
                robotfiledictionary[domainname].read() #download/read robots.txt
                print "  Robots.txt for %s downloaded" % str(domainname)
                robotfiledictionary[domainname].modified() #update time
        if robotfiledictionary[domainname].can_fetch("WebCrawlerUserAgent", link): #if access is allowed...
            #fetch page
            print link
            page = requests.get(link, verify=False)
            return page.text()
        else: #otherwise, report
            print "  URL disallowed due to robots.txt from %s" % str(domainname)
            return "URL disallowed due to robots.txt"
    else: #if netloc was empty, URL wasn't parsed. report
        print "URL not parsed: %s" % str(pagelink)
        return "URL not parsed"
</code>```

And here's the exception I'm getting:

```<code>  Robots.txt for https://ehi-siegel.de/ initial download
Traceback (most recent call last):
  File "C:\webcrawler.py", line 561, in <module>
    HTMLpage = getHTMLpage(link, loopstarttime)
  File "C:\webcrawler.py", line 122, in getHTMLpage
    robotfiledictionary[domainname].read() #download/read robots.txt
  File "C:\Python27\lib\robotparser.py", line 58, in read
    f = opener.open(self.url)
  File "C:\Python27\lib\urllib.py", line 213, in open
    return getattr(self, name)(url)
  File "C:\Python27\lib\urllib.py", line 443, in open_https
    h.endheaders(data)
  File "C:\Python27\lib\httplib.py", line 1053, in endheaders
    self._send_output(message_body)
  File "C:\Python27\lib\httplib.py", line 897, in _send_output
    self.send(msg)
  File "C:\Python27\lib\httplib.py", line 859, in send
    self.connect()
  File "C:\Python27\lib\httplib.py", line 1278, in connect
    server_hostname=server_hostname)
  File "C:\Python27\lib\ssl.py", line 353, in wrap_socket
    _context=self)
  File "C:\Python27\lib\ssl.py", line 601, in __init__
    self.do_handshake()
  File "C:\Python27\lib\ssl.py", line 830, in do_handshake
    self._sslobj.do_handshake()
IOError: [Errno socket error] [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:590)
</code>```

As you can see, I've already changed the code at the end to retrieve the page ignoring the SSL certificate (which I know is frowned upon in production, but I wanted to test it), but it seems now the robotparser.read() function fails the SSL verification. I've seen I can download the certificates manually and point the program in that direction to verify the SSL certificate, but ideally I'd like to have my program work "off-the-box" since I personally am not going to be the one using it. Does anyone have any idea what to do?

Edit: I went into robotparser.py. I added

```<code>import requests
</code>```

and changed line 58 to

```<code>f = requests.get(self.url, verify=False)
</code>```

and this seems to have fixed it. This still isn't ideal, so I'm still open to suggestions on what to do.

答:
I recently had the same problem.
A quick fix was to add these lines to my code:

```<code>import ssl
ssl._create_default_https_context = ssl._create_unverified_context
</code>```

python 2.7.16

Body:
I'm writing a simple webcrawler in Python 2.7 and am getting an SSL Certificate Verify Failed exception when attempting to retrieve the robots.txt file from an HTTPS website.

Here's the relevant code:

def getHTMLpage(pagelink, currenttime):
    "Downloads HTML page from server"
    #init
    #parse URL and get domain name
    o = urlparse.urlparse(pagelink,"http")
    if o.netloc == "":
        netloc = re.search(r"[^/]+\.[^/]+\.[^/]+", o.path)
        if netloc:
            domainname="http://"+netloc.group(0)+"/"
    else:
        domainname=o.scheme+"://"+o.netloc+"/"
    if o.netloc != "" and o.netloc != None and o.scheme != "mailto": #if netloc isn't empty and it's not a mailto link
        link=domainname+o.path[1:]+o.params+"?"+o.query+"#"+o.fragment
        if not (robotfiledictionary.get(domainname)): #if robot file for domainname was not downloaded
            robotfiledictionary[domainname] = robotparser.RobotFileParser() #initialize robots.txt parser
            robotfiledictionary[domainname].set_url(domainname+"robots.txt") #set url for robots.txt
            print "  Robots.txt for %s initial download" % str(domainname)
            robotfiledictionary[domainname].read() #download/read robots.txt
        elif (robotfiledictionary.get(domainname)): #if robot file for domainname was already downloaded
            if (currenttime - robotfiledictionary[domainname].mtime()) > 3600: #if robot file is older than 1 hour
                robotfiledictionary[domainname].read() #download/read robots.txt
                print "  Robots.txt for %s downloaded" % str(domainname)
                robotfiledictionary[domainname].modified() #update time
        if robotfiledictionary[domainname].can_fetch("WebCrawlerUserAgent", link): #if access is allowed...
            #fetch page
            print link
            page = requests.get(link, verify=False)
            return page.text()
        else: #otherwise, report
            print "  URL disallowed due to robots.txt from %s" % str(domainname)
            return "URL disallowed due to robots.txt"
    else: #if netloc was empty, URL wasn't parsed. report
        print "URL not parsed: %s" % str(pagelink)
        return "URL not parsed"

And here's the exception I'm getting:

  Robots.txt for https://ehi-siegel.de/ initial download
Traceback (most recent call last):
  File "C:\webcrawler.py", line 561, in <module>
    HTMLpage = getHTMLpage(link, loopstarttime)
  File "C:\webcrawler.py", line 122, in getHTMLpage
    robotfiledictionary[domainname].read() #download/read robots.txt
  File "C:\Python27\lib\robotparser.py", line 58, in read
    f = opener.open(self.url)
  File "C:\Python27\lib\urllib.py", line 213, in open
    return getattr(self, name)(url)
  File "C:\Python27\lib\urllib.py", line 443, in open_https
    h.endheaders(data)
  File "C:\Python27\lib\httplib.py", line 1053, in endheaders
    self._send_output(message_body)
  File "C:\Python27\lib\httplib.py", line 897, in _send_output
    self.send(msg)
  File "C:\Python27\lib\httplib.py", line 859, in send
    self.connect()
  File "C:\Python27\lib\httplib.py", line 1278, in connect
    server_hostname=server_hostname)
  File "C:\Python27\lib\ssl.py", line 353, in wrap_socket
    _context=self)
  File "C:\Python27\lib\ssl.py", line 601, in __init__
    self.do_handshake()
  File "C:\Python27\lib\ssl.py", line 830, in do_handshake
    self._sslobj.do_handshake()
IOError: [Errno socket error] [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:590)

As you can see, I've already changed the code at the end to retrieve the page ignoring the SSL certificate (which I know is frowned upon in production, but I wanted to test it), but it seems now the robotparser.read() function fails the SSL verification. I've seen I can download the certificates manually and point the program in that direction to verify the SSL certificate, but ideally I'd like to have my program work "off-the-box" since I personally am not going to be the one using it. Does anyone have any idea what to do?

Edit: I went into robotparser.py. I added

import requests

and changed line 58 to

f = requests.get(self.url, verify=False)

and this seems to have fixed it. This still isn't ideal, so I'm still open to suggestions on what to do.

Body:
I recently had the same problem.
A quick fix was to add these lines to my code:

import ssl
ssl._create_default_https_context = ssl._create_unverified_context

python 2.7.16


问:
Webex guest issuer integration with widgets -- Create team web api issue
I am trying to create a Webex team using the following process. But not working. I had created JWT token and exchanged it for  access token which I had passed in to the Authorization header in the API call. But I keep getting the error message that I mentioned below. And another fact is I can execute the same API with GET method which returns the number of teams I had.I had followed steps in the webex developer site. But I can't create the team.

```<code>Request URL:
https://api.ciscospark.com/v1/teams
Request Method:
POST
</code>```

The following is the header that I passed to the API

Accept:
application/json

Content-Type:
application/json

Authorization:
Bearer eyJhbGciOiJSUzI1NiJ9.eyJtYWNoaW5lX3R5cGUiOiJhcHB1c2VyIiwiY2x1c3RlciI6IlBGODQiLCJwcml2YXRlIjoiZXlKamRIa2lPaUpLVjFRaUxDSmxibU1pT2lKQk1USTRRMEpETFVoVE1qVTJJaXdpWVd4bklqb2laR2x5SW4wLi4zRnp6Mkh4c2k0TnI4Z24yMk03cm1BLjhtUnRIYUhOWXBkQ2ZydUR1d0s0MnJNMlhZTEZvNHJKN0NTTkJSQ21kZFRnNTdzUzZ1cUVxcjZFakQ0Yk1JOUY5NFluOWx6VGFWcnRHVkpLOGo2djNzX1VBaTJ2Rnk5TDl3Z05SaUlOczB3NU5yTkxLLUx3TDNQdGhiMzJEYzF2TlhGZkRtakFmSjlOZG1QeEdMQVYxWU9EVnhnNE5MbnpHNDczY24zaTJlbWlfdVBzbk9LRTZHYjEwMVBkekdCSVVQaGRwMkY4bVZhd3hzN2pxbUdzVmEtdXJaYXhpN243emZyaXBjUE5HZjNhSURWb011LVkzaXN0ak03U2s1Qno4TXcwNFZueXpGYWt4LWw0WHlfdUVJalpDeXNsNU56TGNTWkVHc2hJRnJsVHZmdzZZU1J4elV0cXJ2Y3hrX09GT01ZeFRsSDVvSXVsSXdXRWpVQ2o5RTBWZVJMNHB2Z3BQYTRkOE1zNHR6Tmh3cmNpRV9Hd0Fob0tmOE9oMEVQZTM4MmdaOW5wNFJvOWRVSnBnRGszR3NhYWx4ZmJubFRmMmt6RWVjQlJCa0NnSEJXRjhUZXNpdWZWV2djWktZX0E1dXh0aTlMSTB0Umk5X3ZsNjJuTy1uMlh5dm1VZlQxUUxLNmthamJwU01renRUOHdLRkxxLVdTVk54TUJlMWRid094Ni1nN0c3bldLZ1J5ZEpEVEdrazMtRW9wbVRURnZhTEk2dkp6S3NGTzlGRUFJVld1ZFd2RWlWWjVXdVN3dS5yS3RJTzZ6aVpFVE1XV3ZhOEVZaElnIiwicmVmZXJlbmNlX2lkIjoiODlkNjdlZDUtOTU5My00YjBjLWI0MGEtMGFjOTE0OTZlZjZkIiwiaXNzIjoiaHR0cHM6XC9cL2lkYnJva2VyLndlYmV4LmNvbVwvaWRiIiwidG9rZW5fdHlwZSI6IkJlYXJlciIsImNsaWVudF9pZCI6IkMzMTE3NzIzYTBhNGM5ODVhOGJkNmRkYTc2Zjc3NjZjNTEzMjRiNmY0MWJmNGZlZjFjMmM4Mjc4NGExZjI5NzVjIiwidXNlcl90eXBlIjoibWFjaGluZSIsInRva2VuX2lkIjoiQWFaM3IwWkRabU1XWXhaVEF0T0dGbU15MDBOR05oTFdKa09EY3RZVFZrTmpjM056STBNamhoTkRkaU9XVXlNbU10TkdOaiIsInVzZXJfbW9kaWZ5X3RpbWVzdGFtcCI6IjIwMTkwNTI3MDQxNzQ4LjEwMloiLCJyZWFsbSI6IjM5ZWQ0NDRmLTU2NGUtNDFlNC05N2VkLWI4MWFmNzM0ZWVkMCIsImNpc191dWlkIjoiNjJkZWU2NjktNDE5OC00N2YzLWE2ODgtNzA4YWQxM2VjNDc3IiwiZXhwaXJ5X3RpbWUiOjE1NTg5NTIyNzA0NTB9.VNUms24YsiwNbU_KN0Y7v1osAilq1MMiIQn6DRnyNitJAgeTLuyrwiYM0JIaox-dQxQKBp897uAj9vksg0ik2-j2MddcRmx4gsVF787uw7VpCIiZNNME346__xddvmmttna7IErBTz84hqZsnvSlmKLpus4lQs_k9I8ZHTsuPJ9FRXPry6ZAmPjDk1uWGGWFXyOSgH-VkDj9hY9Fy_6r7MKIn0YV21dxIKaZVZ6DMo1NSJM68I-90Vv-QbQY3gBeH25ZXDNDDBJg6-woMF2QPk_N8zrL8G1WPRXxGAA_lqGr_qGq65CfOwuqGikpLsRtjhWU4sYDX3xrK918W08CFw

This is the parameter I passed to the API

name=hearingteam

This is the server response
{"message":"The request could not be understood by the server due to malformed syntax.","errors":[{"description":"The request could not be understood by the server due to malformed syntax."}],"trackingId":"ROUTER_5CEB64F0-FC8D-01BB-05C2-7AA62A6905C2"}

答:
The API requires parameters to be passed in JSON format.

Eg : JSON.stringyfy({"name":"hearingteam"});

Body:
I am trying to create a Webex team using the following process. But not working. I had created JWT token and exchanged it for  access token which I had passed in to the Authorization header in the API call. But I keep getting the error message that I mentioned below. And another fact is I can execute the same API with GET method which returns the number of teams I had.I had followed steps in the webex developer site. But I can't create the team.

Request URL:
https://api.ciscospark.com/v1/teams
Request Method:
POST

The following is the header that I passed to the API

Accept:
application/json

Content-Type:
application/json

Authorization:
Bearer eyJhbGciOiJSUzI1NiJ9.eyJtYWNoaW5lX3R5cGUiOiJhcHB1c2VyIiwiY2x1c3RlciI6IlBGODQiLCJwcml2YXRlIjoiZXlKamRIa2lPaUpLVjFRaUxDSmxibU1pT2lKQk1USTRRMEpETFVoVE1qVTJJaXdpWVd4bklqb2laR2x5SW4wLi4zRnp6Mkh4c2k0TnI4Z24yMk03cm1BLjhtUnRIYUhOWXBkQ2ZydUR1d0s0MnJNMlhZTEZvNHJKN0NTTkJSQ21kZFRnNTdzUzZ1cUVxcjZFakQ0Yk1JOUY5NFluOWx6VGFWcnRHVkpLOGo2djNzX1VBaTJ2Rnk5TDl3Z05SaUlOczB3NU5yTkxLLUx3TDNQdGhiMzJEYzF2TlhGZkRtakFmSjlOZG1QeEdMQVYxWU9EVnhnNE5MbnpHNDczY24zaTJlbWlfdVBzbk9LRTZHYjEwMVBkekdCSVVQaGRwMkY4bVZhd3hzN2pxbUdzVmEtdXJaYXhpN243emZyaXBjUE5HZjNhSURWb011LVkzaXN0ak03U2s1Qno4TXcwNFZueXpGYWt4LWw0WHlfdUVJalpDeXNsNU56TGNTWkVHc2hJRnJsVHZmdzZZU1J4elV0cXJ2Y3hrX09GT01ZeFRsSDVvSXVsSXdXRWpVQ2o5RTBWZVJMNHB2Z3BQYTRkOE1zNHR6Tmh3cmNpRV9Hd0Fob0tmOE9oMEVQZTM4MmdaOW5wNFJvOWRVSnBnRGszR3NhYWx4ZmJubFRmMmt6RWVjQlJCa0NnSEJXRjhUZXNpdWZWV2djWktZX0E1dXh0aTlMSTB0Umk5X3ZsNjJuTy1uMlh5dm1VZlQxUUxLNmthamJwU01renRUOHdLRkxxLVdTVk54TUJlMWRid094Ni1nN0c3bldLZ1J5ZEpEVEdrazMtRW9wbVRURnZhTEk2dkp6S3NGTzlGRUFJVld1ZFd2RWlWWjVXdVN3dS5yS3RJTzZ6aVpFVE1XV3ZhOEVZaElnIiwicmVmZXJlbmNlX2lkIjoiODlkNjdlZDUtOTU5My00YjBjLWI0MGEtMGFjOTE0OTZlZjZkIiwiaXNzIjoiaHR0cHM6XC9cL2lkYnJva2VyLndlYmV4LmNvbVwvaWRiIiwidG9rZW5fdHlwZSI6IkJlYXJlciIsImNsaWVudF9pZCI6IkMzMTE3NzIzYTBhNGM5ODVhOGJkNmRkYTc2Zjc3NjZjNTEzMjRiNmY0MWJmNGZlZjFjMmM4Mjc4NGExZjI5NzVjIiwidXNlcl90eXBlIjoibWFjaGluZSIsInRva2VuX2lkIjoiQWFaM3IwWkRabU1XWXhaVEF0T0dGbU15MDBOR05oTFdKa09EY3RZVFZrTmpjM056STBNamhoTkRkaU9XVXlNbU10TkdOaiIsInVzZXJfbW9kaWZ5X3RpbWVzdGFtcCI6IjIwMTkwNTI3MDQxNzQ4LjEwMloiLCJyZWFsbSI6IjM5ZWQ0NDRmLTU2NGUtNDFlNC05N2VkLWI4MWFmNzM0ZWVkMCIsImNpc191dWlkIjoiNjJkZWU2NjktNDE5OC00N2YzLWE2ODgtNzA4YWQxM2VjNDc3IiwiZXhwaXJ5X3RpbWUiOjE1NTg5NTIyNzA0NTB9.VNUms24YsiwNbU_KN0Y7v1osAilq1MMiIQn6DRnyNitJAgeTLuyrwiYM0JIaox-dQxQKBp897uAj9vksg0ik2-j2MddcRmx4gsVF787uw7VpCIiZNNME346__xddvmmttna7IErBTz84hqZsnvSlmKLpus4lQs_k9I8ZHTsuPJ9FRXPry6ZAmPjDk1uWGGWFXyOSgH-VkDj9hY9Fy_6r7MKIn0YV21dxIKaZVZ6DMo1NSJM68I-90Vv-QbQY3gBeH25ZXDNDDBJg6-woMF2QPk_N8zrL8G1WPRXxGAA_lqGr_qGq65CfOwuqGikpLsRtjhWU4sYDX3xrK918W08CFw

This is the parameter I passed to the API

name=hearingteam

This is the server response
{"message":"The request could not be understood by the server due to malformed syntax.","errors":[{"description":"The request could not be understood by the server due to malformed syntax."}],"trackingId":"ROUTER_5CEB64F0-FC8D-01BB-05C2-7AA62A6905C2"}


问:
Change scale and measurement according to a projection in openlayer5
I am building a image tiles based map using openlayer where I changed the projection to a custom one instead of default EPSG. I need the scale to show the correct scale according to my distance to pixel ratio and also need the measurements according to that scale.

I changed metersPerUnit to match my need for scale but it seems to depend on the extents.
1. How exactly is extent used to in scale?
2. I can see the scale value change when moved vertically on my map which should not be the case since its a flat projection. (I have the global set as true which I assumed should have fixed that. Am I understanding something wrong about global?

Measurements are still very different even after changing metersPerUnit which I guess is because I need to change the getPointResolution function also? But I added which does not seem to be working correctly. Measurements are still different.

```<code>getPointResolution = (projection, resolution, point, opt_units) => {
        var pointResolution = resolution;
        pointResolution /= projection.getMetersPerUnit();
        return pointResolution;
    };

proj = new Projection({
      code: 'ZOOMIFY',
      units: 'pixels',
      extent: [0, 0, imgWidth, imgHeight],
      metersPerUnit: (constant_micronsperpixel * 0.000001 / imgWidth),
      global: true,
      getPointResolution: getPointProjection
    });
</code>```

Another thing was, I needed to use imgWidth in metersPerUnit to correct the scale which seems to be a hack or I do not quite understand how extent is used for scale calculation. And whats really the difference between extent and globalExtent

Update: 27 May

I managed to figure some things.Extents are not needed for scale. Fixing the resolutions and implementing the correct getPointResolution for view ensure the measurements are correct along with scale. This also fixed my changing scale on moving vertically.
However, the View does not query for images now. Any idea why?

Updated Code

```<code>this.getPointResolution = (resolution, point) => {
        var pointResolution = resolution;
        return pointResolution;
    }

    this.proj = new Projection({
      code: 'MORPHLE',
      units: 'm',
      metersPerUnit: 0.000001,
      global: true,
      getPointResolution: this.getPointResolution,

    });

    this.resolutions = [this.props.slide_data.uperpixel * 128,this.props.slide_data.uperpixel * 64,this.props.slide_data.uperpixel * 32, this.props.slide_data.uperpixel * 16, this.props.slide_data.uperpixel * 8, this.props.slide_data.uperpixel * 4, this.props.slide_data.uperpixel*2, this.props.slide_data.uperpixel];

    this.viewer = new Map({
      controls: [],
      target: null,
      overlays: [this.popup],
      layers: [
        new TileLayer({
          source: new XYZ({
            url: this.props.url,
            maxZoom: this.props.max_zoom - 1,
            minZoom: 0,
            wrapX: false,
            tileSize: [500, 500],
            projection: this.proj
          }),
          minResolution: (this.props.slide_data.uperpixel),
          maxResolution: (this.props.slide_data.uperpixel * 128)

        })
      ],
      view: new View({
        projection: this.proj,
        center: this.state.center,
        resolutions: this.resolutions,
        minZoom: 0,
        zoom: this.state.zoom,
        rotation: this.slideAngle
      })
    });
</code>```

Images are not being queried though now as I see in Network Tab of browser.

答:
After a lot of playing around, I solved my problem. Here are some insights that I learnt and are missing/hard to understand in documentation:

Extent imgHeight and imgWidth needs to be the size of full resolution image i.e. in the most zoomed level X-images * Tile-X-Width and Y-Images * Tile-Y-Width.

Resolutions added in TileGrid define the image url query where as resolutions in View only define the view resolutions. If they match(at some zooms), then images will be queries else the zoom will only be digital in nature.

So, if someone wants to use a deep zoom using OpenLayer with custom projection and resolutions along with correct projection and measurements- The following would be the code:

```<code>this.imgWidth = this.stitched_tile_width * this.x_max;
this.imgHeight = this.tile_height * this.y_max;

this.resolutions = [];
let z_levels = this.props.slide_data.z_levels.split(",");
(z_levels).forEach((level, index) => {
      this.resolutions.push(this.distperpixel * Math.pow(2, parseInt(level)));
});

this.resolutions = this.resolutions.reverse();

this.getPointResolution = (resolution, point) => {
      var pointResolution = resolution;
      return pointResolution;
}

    this.proj = new Projection({
      code: 'CUSTOM',
      units: 'pixels',
      extent: [0, 0, this.imgWidth, this.imgHeight],
      metersPerUnit: 0.000001,
      global: true,
      getPointResolution: this.getPointResolution,
    });

    this.layer = new TileLayer({
      extent: this.proj.getExtent(),
      source: new TileImage({
        tileGrid: new TileGrid({
          extent: this.proj.getExtent(),
          origin: [0, this.imgHeight],
          resolutions: this.resolutions,
          tileSize: [this.tile_width, this.tile_height],
        }),
        projection: this.proj,
        url: this.props.url,
        wrapX: false
      }),
    });

    this.viewer = new Map({
      layers: [
        this.layer
      ],
      view: new View({
        projection: this.proj,
        extent: this.proj.getExtent(),
        center: this.state.center,
        zoom: starting_zoom,
        maxResolution: this.resolutions[0],
        maxZoom: (this.resolutions.length - 1),
        rotation: this.slideAngle
      })
    });
</code>```

Body:
I am building a image tiles based map using openlayer where I changed the projection to a custom one instead of default EPSG. I need the scale to show the correct scale according to my distance to pixel ratio and also need the measurements according to that scale.

I changed metersPerUnit to match my need for scale but it seems to depend on the extents.
1. How exactly is extent used to in scale?
2. I can see the scale value change when moved vertically on my map which should not be the case since its a flat projection. (I have the global set as true which I assumed should have fixed that. Am I understanding something wrong about global?

Measurements are still very different even after changing metersPerUnit which I guess is because I need to change the getPointResolution function also? But I added which does not seem to be working correctly. Measurements are still different.

getPointResolution = (projection, resolution, point, opt_units) => {
        var pointResolution = resolution;
        pointResolution /= projection.getMetersPerUnit();
        return pointResolution;
    };

proj = new Projection({
      code: 'ZOOMIFY',
      units: 'pixels',
      extent: [0, 0, imgWidth, imgHeight],
      metersPerUnit: (constant_micronsperpixel * 0.000001 / imgWidth),
      global: true,
      getPointResolution: getPointProjection
    });

Another thing was, I needed to use imgWidth in metersPerUnit to correct the scale which seems to be a hack or I do not quite understand how extent is used for scale calculation. And whats really the difference between extent and globalExtent

Update: 27 May

I managed to figure some things.Extents are not needed for scale. Fixing the resolutions and implementing the correct getPointResolution for view ensure the measurements are correct along with scale. This also fixed my changing scale on moving vertically.
However, the View does not query for images now. Any idea why?

Updated Code

this.getPointResolution = (resolution, point) => {
        var pointResolution = resolution;
        return pointResolution;
    }

    this.proj = new Projection({
      code: 'MORPHLE',
      units: 'm',
      metersPerUnit: 0.000001,
      global: true,
      getPointResolution: this.getPointResolution,

    });

    this.resolutions = [this.props.slide_data.uperpixel * 128,this.props.slide_data.uperpixel * 64,this.props.slide_data.uperpixel * 32, this.props.slide_data.uperpixel * 16, this.props.slide_data.uperpixel * 8, this.props.slide_data.uperpixel * 4, this.props.slide_data.uperpixel*2, this.props.slide_data.uperpixel];

    this.viewer = new Map({
      controls: [],
      target: null,
      overlays: [this.popup],
      layers: [
        new TileLayer({
          source: new XYZ({
            url: this.props.url,
            maxZoom: this.props.max_zoom - 1,
            minZoom: 0,
            wrapX: false,
            tileSize: [500, 500],
            projection: this.proj
          }),
          minResolution: (this.props.slide_data.uperpixel),
          maxResolution: (this.props.slide_data.uperpixel * 128)

        })
      ],
      view: new View({
        projection: this.proj,
        center: this.state.center,
        resolutions: this.resolutions,
        minZoom: 0,
        zoom: this.state.zoom,
        rotation: this.slideAngle
      })
    });

Images are not being queried though now as I see in Network Tab of browser.

Body:
After a lot of playing around, I solved my problem. Here are some insights that I learnt and are missing/hard to understand in documentation:

Extent imgHeight and imgWidth needs to be the size of full resolution image i.e. in the most zoomed level X-images * Tile-X-Width and Y-Images * Tile-Y-Width.

Resolutions added in TileGrid define the image url query where as resolutions in View only define the view resolutions. If they match(at some zooms), then images will be queries else the zoom will only be digital in nature.

So, if someone wants to use a deep zoom using OpenLayer with custom projection and resolutions along with correct projection and measurements- The following would be the code:

this.imgWidth = this.stitched_tile_width * this.x_max;
this.imgHeight = this.tile_height * this.y_max;

this.resolutions = [];
let z_levels = this.props.slide_data.z_levels.split(",");
(z_levels).forEach((level, index) => {
      this.resolutions.push(this.distperpixel * Math.pow(2, parseInt(level)));
});

this.resolutions = this.resolutions.reverse();

this.getPointResolution = (resolution, point) => {
      var pointResolution = resolution;
      return pointResolution;
}

    this.proj = new Projection({
      code: 'CUSTOM',
      units: 'pixels',
      extent: [0, 0, this.imgWidth, this.imgHeight],
      metersPerUnit: 0.000001,
      global: true,
      getPointResolution: this.getPointResolution,
    });

    this.layer = new TileLayer({
      extent: this.proj.getExtent(),
      source: new TileImage({
        tileGrid: new TileGrid({
          extent: this.proj.getExtent(),
          origin: [0, this.imgHeight],
          resolutions: this.resolutions,
          tileSize: [this.tile_width, this.tile_height],
        }),
        projection: this.proj,
        url: this.props.url,
        wrapX: false
      }),
    });

    this.viewer = new Map({
      layers: [
        this.layer
      ],
      view: new View({
        projection: this.proj,
        extent: this.proj.getExtent(),
        center: this.state.center,
        zoom: starting_zoom,
        maxResolution: this.resolutions[0],
        maxZoom: (this.resolutions.length - 1),
        rotation: this.slideAngle
      })
    });


问:
Spring MVC Annotated Controller
I have a controller which has a few actions, which are triggered by hitting various buttons on the page.  I would like to have a default action, but am unsure how to annotate the method.  Here is an example:

```<code>@Controller
@RequestMapping("/view.jsp")
public class ExampleController {

    @RequestMapping(method = RequestMethod.GET)
    public ModelAndView displayResults() {
        ModelAndView mav = new ModelAndView("view");
        mav.addObject("queryResults", methodToQueryDBForListing());
        return mav;
    }

    @RequestMapping(method = RequestMethod.POST, params="submit=Action 1")
    public ModelAndView action1(@RequestParam("selectedItemKey") String key) {
        ModelAndView mav = new ModelAndView("action1");
        //Business logic
        return mav;
    }

    @RequestMapping(method = RequestMethod.POST, params="submit=Action 2")
    public ModelAndView action2(@RequestParam("selectedItemKey") String key) {
        ModelAndView mav = new ModelAndView("action2");
        //Business logic
        return mav;
    }

    //A few more methods which basically do what action1 and action2 do
}
</code>```

How can I annotate a method which will act on a POST with any submit button pressed with no key selected?

I have tried:

```<code>@RequestMethod(method = RequestMethod.POST, params="!selectedItemKey")
@RequestMethod(method = RequestMethod.POST)
</code>```

I'd really hate it if I had to set required = false on each of the methods which take RequestParams and then conditionally check to see if one comes in or not...  Is there a way to annotate this to work properly?

答:
The proper annotation is:

```<code>@RequestMapping(
  method = RequestMethod.POST,
  params = { "!selectedItemKey", "submit" }
)
</code>```

It seems odd though, that it was not hitting this method until adding that second parameter.

Title: Spring MVC Annotated Controller

Body:
I have a controller which has a few actions, which are triggered by hitting various buttons on the page.  I would like to have a default action, but am unsure how to annotate the method.  Here is an example:

@Controller
@RequestMapping("/view.jsp")
public class ExampleController {

    @RequestMapping(method = RequestMethod.GET)
    public ModelAndView displayResults() {
        ModelAndView mav = new ModelAndView("view");
        mav.addObject("queryResults", methodToQueryDBForListing());
        return mav;
    }

    @RequestMapping(method = RequestMethod.POST, params="submit=Action 1")
    public ModelAndView action1(@RequestParam("selectedItemKey") String key) {
        ModelAndView mav = new ModelAndView("action1");
        //Business logic
        return mav;
    }

    @RequestMapping(method = RequestMethod.POST, params="submit=Action 2")
    public ModelAndView action2(@RequestParam("selectedItemKey") String key) {
        ModelAndView mav = new ModelAndView("action2");
        //Business logic
        return mav;
    }

    //A few more methods which basically do what action1 and action2 do
}

How can I annotate a method which will act on a POST with any submit button pressed with no key selected?

I have tried:

@RequestMethod(method = RequestMethod.POST, params="!selectedItemKey")
@RequestMethod(method = RequestMethod.POST)

I'd really hate it if I had to set required = false on each of the methods which take RequestParams and then conditionally check to see if one comes in or not...  Is there a way to annotate this to work properly?

Body:
The proper annotation is:

@RequestMapping(
  method = RequestMethod.POST,
  params = { "!selectedItemKey", "submit" }
)

It seems odd though, that it was not hitting this method until adding that second parameter.


问:
DomPDF does not download file for AJAX request on Laravel
I'm working on 'DomPDF' using Ajax Post request on Laravel project. Below is ajax code.

```<code>       $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });
        $.ajax({
            url:"{{ route('screen.pdfticket') }}",
            method:"POST",
            data:{
                id:$('#screenid').val()
            },
            success:function(data){
                console.log(data);
            }
        });
</code>```

And below is code in controller.

```<code>    $customPaper = array(0,0,216,158);
    $pdf->loadView("screen.ticket" , [
        'clinic' => 'clinic name' ,
        'queno' => $screen->que
    ])->setPaper($customPaper, 'landscape');
    return $pdf->download($screen->que .'.pdf');
</code>```

I can get correct response but it's not readable format. I would like to save in pdf format after ajax called success instead. Any advise or guidance would be greatly appreciated, Thanks.

答: Use stream() to stream created PDF to browser and use output() to get a correct return format. See https://github.com/dompdf/dompdf/wiki/Usage for more information. </p>

Body:
I'm working on 'DomPDF' using Ajax Post request on Laravel project. Below is ajax code.

       $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });
        $.ajax({
            url:"{{ route('screen.pdfticket') }}",
            method:"POST",
            data:{
                id:$('#screenid').val()
            },
            success:function(data){
                console.log(data);
            }
        });

And below is code in controller.

    $customPaper = array(0,0,216,158);
    $pdf->loadView("screen.ticket" , [
        'clinic' => 'clinic name' ,
        'queno' => $screen->que
    ])->setPaper($customPaper, 'landscape');
    return $pdf->download($screen->que .'.pdf');

I can get correct response but it's not readable format. I would like to save in pdf format after ajax called success instead. Any advise or guidance would be greatly appreciated, Thanks.


问:
Is there any npm library to push history in array?
I want to find the history of data change in Mongoose schema like when anybody updates or delete data, then I want to find the name of the user who deletes that field or if anybody updated that field then I want to find the last value and updated value and . then I want to push these in array named "history" in Mongoose schema.

Already used mongoose-diff-history, mongoose-history but these libraries create another collection.

答: Look into Mongoose middleware. It should not be that hard to utilize their hooks to write audit records to a collection of your choosing etc. You can hook into the model methods (init,  save, remove etc) and on their pre or post take actions. So before a record is deleted you can intercept that and write an audit etc.


问:
How to update Progressbar in android while downloading and inserting JSON data in SQLite?
The background or thread operation of downloading and inserting JSON data into database works fine but as I also want to update my ProgressBar when the data insertion operation keeps updating. My problem is, it starts with Zero percent and dismisses when the whole operation is completed without any update in percentage value.

Sync Fragment:

```<code>String value; //defined globally

private class JsonParse extends AsyncTask<String, String, String> {

    Context mcontext;
    private ProgressDialog progressDialog;

    public JsonParse(Context context) {
        this.mcontext = context;
    }

    @Override
    protected void onCancelled() {
        super.onCancelled();
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

        progressDialog = new ProgressDialog(mcontext);

        progressDialog.setTitle("Downloading"); // Setting Title
        progressDialog.setMessage("Please wait"); // Setting Message
        progressDialog.setIndeterminate(false);
        progressDialog.setMax(100);
        progressDialog.setCancelable(false);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.setButton(DialogInterface.BUTTON_NEGATIVE, mcontext.getString(R.string.cancel_btn), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });

        progressDialog.show();
    }

    @Override
    protected String doInBackground(String... params) {

        String choice = params[0];
        final String url = BASE_URL + "" + VERSION + "" + METHOD + "";

        StringRequest request = new StringRequest(Request.Method.POST, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {

                        Log.i("response", url + "response:" + response);

                        try {
                            JSONObject object = new JSONObject(response);
                            JSONArray jsonArray = object.getJSONArray(METHOD + "");

                            long counter = 0;
                            int size = jsonArray.length();

                            for (int i = 0; i <= size; i++) {

                                final JSONObject jsonObject = jsonArray.getJSONObject(i);

                                counter++;
                                int percent = (int) ((counter * 100) / size);
                                value = percent + "";

                                onProgressUpdate(value);

                                Log.i("view_", "size: " + size + " " + "counter: " + counter + " " + "percent: " + percent + "%");

                                switch (choice) {

                                    case "deaths":

                                        String id_d = jsonObject.getString("id");
                                        String family_id = jsonObject.getString("family_id");
                                        String death_one_year = jsonObject.getString("death_one_year");
                                        String no_of_deaths = jsonObject.getString("no_of_death");
                                        String cause = jsonObject.getString("cause");
                                        String cause_other = jsonObject.getString("cause_other");
                                        String ward_id_d = jsonObject.getString("ward_id");
                                        String has_error_d = jsonObject.getString("has_error");
                                        String updated_by_d = jsonObject.getString("updated_by");
                                        String updated_at_d = jsonObject.getString("updated_at");
                                        String created_at = jsonObject.getString("created_at");
                                        String uuid_d = jsonObject.getString("uuid");

                                        dbHelper.SyncDeath(Integer.parseInt(id_d), family_id, death_one_year, no_of_deaths, cause, cause_other,
                                                ward_id_d, has_error_d, updated_by_d, updated_at_d, created_at, uuid_d);

                                        death_txt.setTextColor(getResources().getColor(R.color.colorPrimary));
                                        death_txt.setText(R.string.synced);

                                        break;
                                }
                            }
                            return;

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        progressDialog.dismiss();
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
                Toast.makeText(getContext(), "Server Error, Please Try Again!!", Toast.LENGTH_SHORT).show();
            }
        });

        requestQueue.add(request);

        publishProgress(value);

        Log.i("view_percent_value", value); // Getting null value

        /*for (int i = 0; i <= 100; i++){
            try {
                Thread.sleep(300);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            publishProgress(String.valueOf(i));
        }*/

        return null;
    }

    @Override
    protected void onProgressUpdate(String... values) {

        progressDialog.setProgress(Integer.parseInt(values[0]));
        value = values[0]; // Tried to update this "value" i.e. set globally but can't update

        Log.i("view_values", values[0] + "");
        super.onProgressUpdate(values);
    }

    @Override
    protected void onPostExecute(String result) {

    }
}
</code>```

The above-commented code:

```<code> /*for (int i = 0; i <= 100; i++){
            try {
                Thread.sleep(300);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            publishProgress(String.valueOf(i));
        }*/
</code>```

helps me update ProgressBar but it is not updating in Realtime. In my case, the parameter passed in publishprogress(); i.e. "value" which is defined globally is not getting updated value from the loop. As I guess, it may be the case using for-loop inside try-catch but I can't find the way how to pass that value to publishprogress(); method.

The Log view:

```<code>Log.i("view_", "size: " + size + " " + "counter: " + counter + " " + "percent: " + percent + "%");
</code>```

is updating the percentage value in real-time. Like this:

Please help me to figure out this problem. I'm stuck with this problem from couple of weeks. Thank you in advance!!

答:
First, according to android documents never call onPreExecute(), onPostExecute(Result), doInBackground(Params...), onProgressUpdate(Progress...) manually.
(you are calling onProgressUpdate in doInBackground manually)

Second, move publishProgress(value);  to for loop inside try block.

Body:
The background or thread operation of downloading and inserting JSON data into database works fine but as I also want to update my ProgressBar when the data insertion operation keeps updating. My problem is, it starts with Zero percent and dismisses when the whole operation is completed without any update in percentage value.

Sync Fragment:

String value; //defined globally

private class JsonParse extends AsyncTask<String, String, String> {

    Context mcontext;
    private ProgressDialog progressDialog;

    public JsonParse(Context context) {
        this.mcontext = context;
    }

    @Override
    protected void onCancelled() {
        super.onCancelled();
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

        progressDialog = new ProgressDialog(mcontext);

        progressDialog.setTitle("Downloading"); // Setting Title
        progressDialog.setMessage("Please wait"); // Setting Message
        progressDialog.setIndeterminate(false);
        progressDialog.setMax(100);
        progressDialog.setCancelable(false);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.setButton(DialogInterface.BUTTON_NEGATIVE, mcontext.getString(R.string.cancel_btn), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });

        progressDialog.show();
    }

    @Override
    protected String doInBackground(String... params) {

        String choice = params[0];
        final String url = BASE_URL + "" + VERSION + "" + METHOD + "";

        StringRequest request = new StringRequest(Request.Method.POST, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {

                        Log.i("response", url + "response:" + response);

                        try {
                            JSONObject object = new JSONObject(response);
                            JSONArray jsonArray = object.getJSONArray(METHOD + "");

                            long counter = 0;
                            int size = jsonArray.length();

                            for (int i = 0; i <= size; i++) {

                                final JSONObject jsonObject = jsonArray.getJSONObject(i);

                                counter++;
                                int percent = (int) ((counter * 100) / size);
                                value = percent + "";

                                onProgressUpdate(value);

                                Log.i("view_", "size: " + size + " " + "counter: " + counter + " " + "percent: " + percent + "%");

                                switch (choice) {

                                    case "deaths":

                                        String id_d = jsonObject.getString("id");
                                        String family_id = jsonObject.getString("family_id");
                                        String death_one_year = jsonObject.getString("death_one_year");
                                        String no_of_deaths = jsonObject.getString("no_of_death");
                                        String cause = jsonObject.getString("cause");
                                        String cause_other = jsonObject.getString("cause_other");
                                        String ward_id_d = jsonObject.getString("ward_id");
                                        String has_error_d = jsonObject.getString("has_error");
                                        String updated_by_d = jsonObject.getString("updated_by");
                                        String updated_at_d = jsonObject.getString("updated_at");
                                        String created_at = jsonObject.getString("created_at");
                                        String uuid_d = jsonObject.getString("uuid");

                                        dbHelper.SyncDeath(Integer.parseInt(id_d), family_id, death_one_year, no_of_deaths, cause, cause_other,
                                                ward_id_d, has_error_d, updated_by_d, updated_at_d, created_at, uuid_d);

                                        death_txt.setTextColor(getResources().getColor(R.color.colorPrimary));
                                        death_txt.setText(R.string.synced);

                                        break;
                                }
                            }
                            return;

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        progressDialog.dismiss();
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
                Toast.makeText(getContext(), "Server Error, Please Try Again!!", Toast.LENGTH_SHORT).show();
            }
        });

        requestQueue.add(request);

        publishProgress(value);

        Log.i("view_percent_value", value); // Getting null value

        /*for (int i = 0; i <= 100; i++){
            try {
                Thread.sleep(300);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            publishProgress(String.valueOf(i));
        }*/

        return null;
    }

    @Override
    protected void onProgressUpdate(String... values) {

        progressDialog.setProgress(Integer.parseInt(values[0]));
        value = values[0]; // Tried to update this "value" i.e. set globally but can't update

        Log.i("view_values", values[0] + "");
        super.onProgressUpdate(values);
    }

    @Override
    protected void onPostExecute(String result) {

    }
}

The above-commented code:

 /*for (int i = 0; i <= 100; i++){
            try {
                Thread.sleep(300);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            publishProgress(String.valueOf(i));
        }*/

helps me update ProgressBar but it is not updating in Realtime. In my case, the parameter passed in publishprogress(); i.e. "value" which is defined globally is not getting updated value from the loop. As I guess, it may be the case using for-loop inside try-catch but I can't find the way how to pass that value to publishprogress(); method.

The Log view:

Log.i("view_", "size: " + size + " " + "counter: " + counter + " " + "percent: " + percent + "%");

is updating the percentage value in real-time. Like this:

Please help me to figure out this problem. I'm stuck with this problem from couple of weeks. Thank you in advance!!


问:
Image Corner Radius
Is there any way to round the corners of an ImageView through xml layout? And even if not, what are the ways we can achieve that?

PS: The image urls are being fetched from an API. Not from drawable folder

答:
You can achieve it using custom views like this

```<code>public class RoundImageView extends ImageView {

    private float mRadius = 18.0f;
    private Path mPath;
    private RectF mRect;

    public RoundImageView(Context context) {
        super(context);
        init();
    }

    public RoundImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public RoundImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init();
    }

    private void init() {
        mPath = new Path();

    }

    @Override
    protected void onDraw(Canvas canvas) {
        mRect = new RectF(0, 0, this.getWidth(), this.getHeight());

        mPath.addRoundRect(mRect, mRadius, mRadius, Path.Direction.CW);

        canvas.clipPath(mPath);

        super.onDraw(canvas);
    }
}
</code>```

and use it in your XML

```<code><your_pkag.RoundImageView
     android:id="@+id/imgView"
     android:layout_width="match_parent"
     android:layout_height="match_parent"
     android:src="@drawable/image" />
</code>```

Title: Image Corner Radius

Body:
You can achieve it using custom views like this

public class RoundImageView extends ImageView {

    private float mRadius = 18.0f;
    private Path mPath;
    private RectF mRect;

    public RoundImageView(Context context) {
        super(context);
        init();
    }

    public RoundImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public RoundImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init();
    }

    private void init() {
        mPath = new Path();

    }

    @Override
    protected void onDraw(Canvas canvas) {
        mRect = new RectF(0, 0, this.getWidth(), this.getHeight());

        mPath.addRoundRect(mRect, mRadius, mRadius, Path.Direction.CW);

        canvas.clipPath(mPath);

        super.onDraw(canvas);
    }
}

and use it in your XML

<your_pkag.RoundImageView
     android:id="@+id/imgView"
     android:layout_width="match_parent"
     android:layout_height="match_parent"
     android:src="@drawable/image" />


问:
Do I need to create multiple database connection in a loop?
I am using sqllite3 and want to insert data into the table. My code roughly looks like:

```<code>def fill_database(db):
     ...
    for record in records:
       add_to_db(db, record)
 ...

def add_to_db(db, record):
   ...
   connection = sqlite3.connect(db)
   cursor = connection.cursor()
   cursor.execute("...")
   connection.commit()
   connection.close()
</code>```

As it can be seen, the database is connected and closed for each insertion of the data record. Is there a way to only connect and close the db once for all the data to be processed?

答:
It better to open the database once in the beginning and close it at the end by Createing a global varible.

```<code>connection = sqlite3.connect(db)
cursor = connection.cursor()
def fill_database():
     ...
    for record in records:
       add_to_db(record)
 ...

def add_to_dbrecord):
   ..
   cursor.execute("...")
   connection.commit()

#end of script
connection.close()
</code>```

you can use Singleton Design Pattern if you are using classes

Hope it helps

Body:
I am using sqllite3 and want to insert data into the table. My code roughly looks like:

def fill_database(db):
     ...
    for record in records:
       add_to_db(db, record)
 ...

def add_to_db(db, record):
   ...
   connection = sqlite3.connect(db)
   cursor = connection.cursor()
   cursor.execute("...")
   connection.commit()
   connection.close()

As it can be seen, the database is connected and closed for each insertion of the data record. Is there a way to only connect and close the db once for all the data to be processed?

Body:
It better to open the database once in the beginning and close it at the end by Createing a global varible.

connection = sqlite3.connect(db)
cursor = connection.cursor()
def fill_database():
     ...
    for record in records:
       add_to_db(record)
 ...

def add_to_dbrecord):
   ..
   cursor.execute("...")
   connection.commit()

#end of script
connection.close()

you can use Singleton Design Pattern if you are using classes

Hope it helps


问:
Exceeding Max Char Limit in Excel
How do I use more than 255 characters in Excel's CONCATENATE function? I am actually also using the CONCATENATE function within the HYPERLINK function in EXCEL. An example looks like this:

```<code>=HYPERLINK(CONCATENATE("http://www.google/com/morethan255charsmorethan255charsmorethan255charsmorethan255charsmorethan255charsmorethan255charsmorethan255charsmorethan255charsmorethan255charsmorethan255chars","morethan255chars morethan255charsmorethan255charsmorethan255charsmorethan25"),"link");
</code>```

UPDATE: It's not issue with CONCATENATE function, but an issue with the first parameter of the HYPERLINK function. Using a string longer than 255 characters directly/indirectly (ex: =HYPERLINK(K204,"link") where K204 contains the 256-character length link) fails the HYPERLINK function

I realize that I can use a URL shortener, but I am doing this for ALOT of links which would require ALOT of manual use of the URL shortener.

答:
You can create a hyperlink in Microsoft Word, and then copy it over to Excel.
For some reason, those hyperlink elements are not limited by the 255 character limit, but you won't be able to use the HYPERLINK() function.

Source

Title: Exceeding Max Char Limit in Excel

Body:
How do I use more than 255 characters in Excel's CONCATENATE function? I am actually also using the CONCATENATE function within the HYPERLINK function in EXCEL. An example looks like this:

=HYPERLINK(CONCATENATE("http://www.google/com/morethan255charsmorethan255charsmorethan255charsmorethan255charsmorethan255charsmorethan255charsmorethan255charsmorethan255charsmorethan255charsmorethan255chars","morethan255chars morethan255charsmorethan255charsmorethan255charsmorethan25"),"link");

UPDATE: It's not issue with CONCATENATE function, but an issue with the first parameter of the HYPERLINK function. Using a string longer than 255 characters directly/indirectly (ex: =HYPERLINK(K204,"link") where K204 contains the 256-character length link) fails the HYPERLINK function

I realize that I can use a URL shortener, but I am doing this for ALOT of links which would require ALOT of manual use of the URL shortener.


问:
How to only change child components while parent component dont re render upon route change?
So, while changing the route using react-router-dom I have to again add i.e re-render my header and sidebar component in that route. Which effect my page load time.

Following is my code for better understanding

index.js

```<code> ...
<Route exact path="/" component={UI} />
<Route exact path="/rms" component={rms} />
 ...
</code>```

UI.js

```<code><div>
    <Header />
    <div className="mainbody">
      <Sidebar history={this.props.history}/>
      <div className="main">
        ...
      </div>
    </div>
  </div>
</code>```

rms.js

```<code><div>
    <Header />
    <div className="mainbody">
      <Sidebar history={this.props.history} />
      <div className="main">
        ... //new content
      </div>
    </div>
  </div>
</code>```

P.S I m still a newb to react, so do point out if I am doing it wrong or not?

答:
Premature optimization is the root of all evil

-Donald Knuth

You said that re-rendering your header and sidebar are affecting your page load time.  I find that suspect.  A single extra component, unless it's doing something crazy, should not meaningfully impact your load time.

I'd double check how you're metricing things, but before you even start metricing things you should make sure page load is actually a problem.  If it's not more than a few seconds, you likely are better off focusing your efforts elsewhere.

Body:
So, while changing the route using react-router-dom I have to again add i.e re-render my header and sidebar component in that route. Which effect my page load time.

Following is my code for better understanding

index.js

 ...
<Route exact path="/" component={UI} />
<Route exact path="/rms" component={rms} />
 ...

UI.js

      <Sidebar history={this.props.history}/>

        ...

rms.js

      <Sidebar history={this.props.history} />

        ... //new content

P.S I m still a newb to react, so do point out if I am doing it wrong or not?


问:
If a bash command accepts a filename as the last arg, can piping be used to provide file content?
Say a command takes a filename as its last argument:

```<code>count-words "$word" file.txt
</code>```

Is there a way to use pipe in order to provide file content rather than writing to a temp file?

答:
I'm not sure if I'm understanding your requirement correctly but you may
be in the situation that:

You have a program (say "generate-words") which prints a text
to the stdout.

You also have a program "count-words" which counts a given word
in the specified text file.

You can combine two programs by writing the output of "generate-words"
to a temporary file file.txt.

But you want to find a solution without writing to a temporary file.

If the assumptions above are correct, please try:

```<code>count-words "$word" <(generate-words)
</code>```

where <(command) is called process substitution and you can connect the
output (stdout) of the command to other program which requires filename
as an input.

Body:
Say a command takes a filename as its last argument:

count-words "$word" file.txt

Is there a way to use pipe in order to provide file content rather than writing to a temp file?

Body:
I'm not sure if I'm understanding your requirement correctly but you may
be in the situation that:

You have a program (say "generate-words") which prints a text
to the stdout.

You also have a program "count-words" which counts a given word
in the specified text file.

You can combine two programs by writing the output of "generate-words"
to a temporary file file.txt.

But you want to find a solution without writing to a temporary file.

If the assumptions above are correct, please try:

count-words "$word" <(generate-words)

where <(command) is called process substitution and you can connect the
output (stdout) of the command to other program which requires filename
as an input.


问:
Parsing input to get specific values
I have input like this:

"[0|0|{A=145,B=2,C=12,D=18}|!][0|0|{A=167,B=2,C=67,D=17}|.1iit][196|0|{A=244,B=6,C=67,D=12}|10:48AM][204|0|{A=9,B=201,C=61,D=11}|Calculator][66|0|{A=145,B=450,C=49,D=14}|phone]0|0|{A=145,B=2,C=12,D=18}|!0|0|{A=167,B=2,C=67,D=17}|.1iit196|0|{A=244,B=6,C=67,D=12}|10:48AM204|0|{A=9,B=201,C=61,D=11}|Calculator66|0|{A=145,B=450,C=49,D=14}|phone";

It appears as a continuous line, there are no line breaks.  I need the
largest value out of the values between [ and the first occurrence of
|.  In this case, for example, the largest value is 204.  Once
that is obtained, I want to print the contents of that element
between [].  In this case, it would be "204|0|{A=9,B=201,C=61,D=11}|Calculator".

I've tried something like this, but it is not going anywhere:

```<code>my @array1;

my $data =  "[0|0|{A=145,B=2,C=12,D=18}|!][0|0|{A=167,B=2,C=67,D=1
+7}|.1iit][196|0|{A=244,B=6,C=67,D=12}|10:48AM][204|0|{A=9,B=201,C=61,
+D=11}|Calculator][66|0|{A=145,B=450,C=49,D=14}|phone]0|0|{A=145,B=2,C
+=12,D=18}|!0|0|{A=167,B=2,C=67,D=17}|.1iit196|0|{A=244,B=6,C=67,D=12}
+|10:48AM204|0|{A=9,B=201,C=61,D=11}|Calculator66|0|{A=145,B=450,C=49,
+D=14}|phone";

my $high = 0;
my @values = split(/\[([^\]]+)\]/,$data) ;
print "Values is @values \n";

foreach (@values) {
    # I want the value that preceeds the first occurence of | in each array
    # element, i.e. 0,0,196,204, etc.
    my ($conf,$rest)= split(/\|/,$_);
    print "Conf is $conf \n";
    print "Rest is $rest \n";
    push(@array1, $conf);
    push (@array2, $rest);
    print "Array 1 is @array1 \n";
    print "Array 2 is @array2 \n";
}

$conf = highest(@array1);
my $i=0;

# I want the index value of the element that contains the highest conf value,
# in this case 204.

for (@myarray1) { last if $conf eq $_; $i++; };
print "$conf=$i\n";

# I want to print the rest of the string that was split in  the same index
# position.

$rest = @array2[$i];
print "Rest is $rest \n";

# To get the highest conf value

sub highest {
    my  @data = @_;
    my $high = 0;
    for(@data) {
        $high = $_ if $_ > $high;
    }
    $high;
}
</code>```

Maybe I should be using a different approach.  Could someone help me, please?

答:
One way of doing it:

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

use strict;

my $s = "[0|0|{A=145,B=2,C=12,D=18}|!][0|0|{A=167,B=2,C=67,D=17}|.1iit][196|0|{A=244,B=6,C=67,D=12}|10:48AM][204|0|{A=9,B=201,C=61,D=11}|Calculator][66|0|{A=145,B=450,C=49,D=14}|phone]";

my @parts = split(/\]/, $s);

my $max = 0;
my $data = "";
foreach my $part (@parts) {
    if ($part =~ /\[(\d+)/) {
        if ($1 > $max) {
            $max = $1;
            $data = substr($part, 1);
        }
    }
}
print $data."\n";
</code>```

A couple of notes:

you can split your original string by \], so you get parts like [0|0|{A=145,B=2,C=12,D=18}|!

then you parse each part to get the integer after the initial [

the rest it's easy: keep track of the biggest integer and of the corresponding part, and output it at the end.

Title: Parsing input to get specific values

Body:
I have input like this:

"[0|0|{A=145,B=2,C=12,D=18}|!][0|0|{A=167,B=2,C=67,D=17}|.1iit][196|0|{A=244,B=6,C=67,D=12}|10:48AM][204|0|{A=9,B=201,C=61,D=11}|Calculator][66|0|{A=145,B=450,C=49,D=14}|phone]0|0|{A=145,B=2,C=12,D=18}|!0|0|{A=167,B=2,C=67,D=17}|.1iit196|0|{A=244,B=6,C=67,D=12}|10:48AM204|0|{A=9,B=201,C=61,D=11}|Calculator66|0|{A=145,B=450,C=49,D=14}|phone";

It appears as a continuous line, there are no line breaks.  I need the
largest value out of the values between [ and the first occurrence of
|.  In this case, for example, the largest value is 204.  Once
that is obtained, I want to print the contents of that element
between [].  In this case, it would be "204|0|{A=9,B=201,C=61,D=11}|Calculator".

I've tried something like this, but it is not going anywhere:

my @array1;

my $data =  "[0|0|{A=145,B=2,C=12,D=18}|!][0|0|{A=167,B=2,C=67,D=1
+7}|.1iit][196|0|{A=244,B=6,C=67,D=12}|10:48AM][204|0|{A=9,B=201,C=61,
+D=11}|Calculator][66|0|{A=145,B=450,C=49,D=14}|phone]0|0|{A=145,B=2,C
+=12,D=18}|!0|0|{A=167,B=2,C=67,D=17}|.1iit196|0|{A=244,B=6,C=67,D=12}
+|10:48AM204|0|{A=9,B=201,C=61,D=11}|Calculator66|0|{A=145,B=450,C=49,
+D=14}|phone";

my $high = 0;
my @values = split(/\[([^\]]+)\]/,$data) ;
print "Values is @values \n";

foreach (@values) {
    # I want the value that preceeds the first occurence of | in each array
    # element, i.e. 0,0,196,204, etc.
    my ($conf,$rest)= split(/\|/,$_);
    print "Conf is $conf \n";
    print "Rest is $rest \n";
    push(@array1, $conf);
    push (@array2, $rest);
    print "Array 1 is @array1 \n";
    print "Array 2 is @array2 \n";
}

$conf = highest(@array1);
my $i=0;

# I want the index value of the element that contains the highest conf value,
# in this case 204.

for (@myarray1) { last if $conf eq $_; $i++; };
print "$conf=$i\n";

# I want to print the rest of the string that was split in  the same index
# position.

$rest = @array2[$i];
print "Rest is $rest \n";

# To get the highest conf value

sub highest {
    my  @data = @_;
    my $high = 0;
    for(@data) {
        $high = $_ if $_ > $high;
    }
    $high;
}

Maybe I should be using a different approach.  Could someone help me, please?

Body:
One way of doing it:

#!/usr/bin/perl

use strict;

my $s = "[0|0|{A=145,B=2,C=12,D=18}|!][0|0|{A=167,B=2,C=67,D=17}|.1iit][196|0|{A=244,B=6,C=67,D=12}|10:48AM][204|0|{A=9,B=201,C=61,D=11}|Calculator][66|0|{A=145,B=450,C=49,D=14}|phone]";

my @parts = split(/\]/, $s);

my $max = 0;
my $data = "";
foreach my $part (@parts) {
    if ($part =~ /\[(\d+)/) {
        if ($1 > $max) {
            $max = $1;
            $data = substr($part, 1);
        }
    }
}
print $data."\n";

A couple of notes:

you can split your original string by \], so you get parts like [0|0|{A=145,B=2,C=12,D=18}|!

then you parse each part to get the integer after the initial [

the rest it's easy: keep track of the biggest integer and of the corresponding part, and output it at the end.


问:
I need code to run a SQL Server query which is stored in my local drive via VBA and get data into an Excel sheet
I have multiple SQL queries saved on my local drive, and each time I have to run SQL and copy data from SQL Server to Excel.</p>

答:
You can do something similar to this.

txtSQLcmd = "SELECT * FROM xxxx_Log;"
dtDateValue = DateValue(FetchAValueFromTable(txtSQLcmd))
txtSQLcmd = "UPDATE TablevVariables SET [TablevVariables].KeyValue = #" & dtDateValue & "# WHERE [TablevVariables].KeyName='xxxx_Log';"
ExecuteSQLcmd (txtSQLcmd)

Function FetchAValueFromTable(ByVal strSQL As String) As String
Dim cnn1 As ADODB.Connection
Set cnn1 = CurrentProject.Connection
Dim myRecordSet As New ADODB.Recordset
myRecordSet.ActiveConnection = cnn1
myRecordSet.CursorType = adOpenDynamic
myRecordSet.LockType = adLockOptimistic
myRecordSet.Open strSQL
FetchAValueFromTable = myRecordSet.Fields(0).Value
myRecordSet.Close
Set myRecordSet = Nothing
Set cnn1 = Nothing
End Function
```


问:
How to convert a number to a three-character string using an Oracle sequence
I need to create an Oracle 12c sequence and convert it from a number to a three-character string that has the format of 001, 002, 003 etc.

Here is an example of a sequence:

```<code>CREATE SEQUENCE supplier_seq
  MINVALUE 1
  MAXVALUE 999
  START WITH 1
  INCREMENT BY 1
  CACHE 1;
</code>```

Taking the above sequence, I now need to convert it to a three character string as shown above.

答:
It is not possible using the only sequence.

But yes you can use the following function, wherever sequence is used, to convert the values of sequence to the required format.

```<code>SELECT LPAD(supplier_seq.nextval,3,0) FROM DUAL; -- 001, 002, 003
</code>```

Hope, This is what you are looking for.

Body:
I need to create an Oracle 12c sequence and convert it from a number to a three-character string that has the format of 001, 002, 003 etc.

Here is an example of a sequence:

CREATE SEQUENCE supplier_seq
  MINVALUE 1
  MAXVALUE 999
  START WITH 1
  INCREMENT BY 1
  CACHE 1;

Taking the above sequence, I now need to convert it to a three character string as shown above.

Body:
It is not possible using the only sequence.

But yes you can use the following function, wherever sequence is used, to convert the values of sequence to the required format.

SELECT LPAD(supplier_seq.nextval,3,0) FROM DUAL; -- 001, 002, 003

Hope, This is what you are looking for.