问:
iterator in python that should print 10 valid id numbers
Below is my code so far,The code should implement an iterator that prints 10 valid  IDs as at the condition at check_id function .

https://www.codepile.net/pile/b1PVdbBq

The output should be:
123456782
123456790
123456808
123456816
123456824
123456832
123456840
123456857
123456865
123456873
but  somehow the my output is  wrong...help...

```<code>import string
letters = string.ascii_letters
digits = string.digits

class NumNotNineLong(Exception):

    def __init__(self):
        pass
    def __str__(self):
        return "The number you provided is not nine digits long."

class NotNumber(Exception):

    def __init__(self):
        pass

    def __str__(self):
        return "The input you provided is not an integer"

class IDIterator():

    increment = 1

    def __init__(self,_id):
        self._id = _id

    def __iter__(self):
       return self

    def __next__(self):

        while check_id_valid(str(self._id)[-9::]) == False:
            self._id *= 2
            self._id += IDIterator.increment
            IDIterator.increment += 1
        if check_id_valid(str(self._id)[-9::]):
            result = str(self._id)[-9::]
            self._id *= 2
            self._id += 1
            IDIterator.increment = 2
            return result

def check_id_valid(id_number): #A function that checks whether ID number are valid or not
    for letter in str(id_number):
        if letter not in string.digits:
            raise NotNumber
    numbers = [int(i) for i in str(id_number)]
    if len(numbers) != 9:
        raise NumNotNineLong
    set_numbers = []
    for i in range(len(numbers)):
        if i % 2 == 0:
            set_numbers.append(numbers[i])
        else:
            set_numbers.append(numbers[i] * 2)
    true_numbers = []
    for num in set_numbers:
        if num > 9:
            temp = [int(i) for i in str(num)]
            true_numbers.append(sum(temp))
        else:
            true_numbers.append(num)
    if sum(true_numbers) % 10 == 0:
        return True
    else:
        return False

def main():
    result = IDIterator(123456780)
    for _ in range(10):
        print(result.__next__())

if __name__ == "__main__":
    main()
</code>```

The exercise goes like this: a boolean function called check_id_valid that is defined as:
def check_id_valid (id_number):
The function obtains as an ID number (integer) parameter and returns a true boolean value (True), otherwise returns a false value (False).
It works great when the check_id function is self-contained

Then a class should be implemented to represent an iterator named IDIterator.

This class has an attribute named id_ that represents an ID number in the range of 0 to 999999999 (this attribute is initialized when creating an iterator instance).

The iter method that returns the iterator instance must be used in the above class.

The next method that returns the next valid ID number in the range between id_ (inclusive) and 999999999 must be used in the above class.

To check that the code you have written is working, write a master program with an iterator from the class you created.

The iterator with the next ID value must be initialized 123456780, generate 10 new IDs and print them to the screen. Here is the output you should receive:

答:
I didn't understand what you wanted to do here:

def __next__(self):

    while check_id_valid(str(self._id)[-9::]) == False:
        self._id *= 2
        self._id += IDIterator.increment
        IDIterator.increment += 1
    if check_id_valid(str(self._id)[-9::]):
        result = str(self._id)[-9::]
        self._id *= 2
        self._id += 1
        IDIterator.increment = 2
        return result
```

<p>Here is code in the way you tried to do it (but I do not recommend using it, because that's not what they asked for!):</p>

<pre class="lang-py prettyprint-override"><code>class IDIterator:

    def __init__(self, _id):
        self._id = _id
        self.ok = ""

    def __iter__(self):
        return self

    def __next__(self):
        x = self.ok
        while not check_id_valid(str(self._id)[-9:]):
            self._id += 1
        else:
            self.ok = self._id
            self._id += 1
            return x
</code>```

I recommend you to use the code below:

class IDIterator:

    def __init__(self, _id=0, range=999999999):
        self._id = _id
        self.range = range
        self.count = 0

    def __iter__(self):
        return self

    def __next__(self):
        while self.count < self.range:
            x = self._id
            if not check_id_valid(x):
                self._id += 1
            else:
                self._id += 1
                self.count += 1
                return x
        else:
            raise StopIteration
```

Body:
Below is my code so far,The code should implement an iterator that prints 10 valid  IDs as at the condition at check_id function .

https://www.codepile.net/pile/b1PVdbBq

The output should be:
123456782
123456790
123456808
123456816
123456824
123456832
123456840
123456857
123456865
123456873
but  somehow the my output is  wrong...help...

import string
letters = string.ascii_letters
digits = string.digits

class NumNotNineLong(Exception):

    def __init__(self):
        pass
    def __str__(self):
        return "The number you provided is not nine digits long."

class NotNumber(Exception):

    def __init__(self):
        pass

    def __str__(self):
        return "The input you provided is not an integer"

class IDIterator():

    increment = 1

    def __init__(self,_id):
        self._id = _id

    def __iter__(self):
       return self

    def __next__(self):

        while check_id_valid(str(self._id)[-9::]) == False:
            self._id *= 2
            self._id += IDIterator.increment
            IDIterator.increment += 1
        if check_id_valid(str(self._id)[-9::]):
            result = str(self._id)[-9::]
            self._id *= 2
            self._id += 1
            IDIterator.increment = 2
            return result

def check_id_valid(id_number): #A function that checks whether ID number are valid or not
    for letter in str(id_number):
        if letter not in string.digits:
            raise NotNumber
    numbers = [int(i) for i in str(id_number)]
    if len(numbers) != 9:
        raise NumNotNineLong
    set_numbers = []
    for i in range(len(numbers)):
        if i % 2 == 0:
            set_numbers.append(numbers[i])
        else:
            set_numbers.append(numbers[i] * 2)
    true_numbers = []
    for num in set_numbers:
        if num > 9:
            temp = [int(i) for i in str(num)]
            true_numbers.append(sum(temp))
        else:
            true_numbers.append(num)
    if sum(true_numbers) % 10 == 0:
        return True
    else:
        return False

def main():
    result = IDIterator(123456780)
    for _ in range(10):
        print(result.__next__())

if __name__ == "__main__":
    main()

The exercise goes like this: a boolean function called check_id_valid that is defined as:
def check_id_valid (id_number):
The function obtains as an ID number (integer) parameter and returns a true boolean value (True), otherwise returns a false value (False).
It works great when the check_id function is self-contained

Then a class should be implemented to represent an iterator named IDIterator.

This class has an attribute named id_ that represents an ID number in the range of 0 to 999999999 (this attribute is initialized when creating an iterator instance).

The iter method that returns the iterator instance must be used in the above class.

The next method that returns the next valid ID number in the range between id_ (inclusive) and 999999999 must be used in the above class.

To check that the code you have written is working, write a master program with an iterator from the class you created.

The iterator with the next ID value must be initialized 123456780, generate 10 new IDs and print them to the screen. Here is the output you should receive:

Body:
I didn't understand what you wanted to do here:

def __next__(self):

    while check_id_valid(str(self._id)[-9::]) == False:
        self._id *= 2
        self._id += IDIterator.increment
        IDIterator.increment += 1
    if check_id_valid(str(self._id)[-9::]):
        result = str(self._id)[-9::]
        self._id *= 2
        self._id += 1
        IDIterator.increment = 2
        return result

Here is code in the way you tried to do it (but I do not recommend using it, because that's not what they asked for!):

class IDIterator:

    def __init__(self, _id):
        self._id = _id
        self.ok = ""

    def __iter__(self):
        return self

    def __next__(self):
        x = self.ok
        while not check_id_valid(str(self._id)[-9:]):
            self._id += 1
        else:
            self.ok = self._id
            self._id += 1
            return x

I recommend you to use the code below:

class IDIterator:

    def __init__(self, _id=0, range=999999999):
        self._id = _id
        self.range = range
        self.count = 0

    def __iter__(self):
        return self

    def __next__(self):
        while self.count < self.range:
            x = self._id
            if not check_id_valid(x):
                self._id += 1
            else:
                self._id += 1
                self.count += 1
                return x
        else:
            raise StopIteration


来源: stackexchange

问:
Spring Session not working with Sitemesh
I'm working on implementing Spring Session in a legacy application. I followed the Spring documentation to get the session library implemented and everything seems to be working well, except....

There is a UI element that is decorated on every page through sitemesh. This UI element checks an object in the session to see if it should be displayed or not. When the object is retrieved from the session through the sitemesh decorator, the object is null. When I access the same object through the controller or main content JSP, the object is populated and everything works fine.

In other words:

Web request -> tomcat -> controller -> jsp -> jstl -> session object = ok

then it continues rendering sitemesh decorator adds main.jsp -> jstl -> same session object is null

I think this must be a configuration issue. I can confirm that when I comment out the springSessionRepositoryFilter the page renders correctly, but then I am not using spring session and hitting my redis server. If anyone has any thoughts, I would really appreciate it. Thanks! My web.xml looks like this.

```<code><web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    version="3.0" id="WebApp_1398187215147">
    <display-name>MyApplication Web Application</display-name>
    <listener>
        <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
    </listener>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <listener>
        <listener-class>org.springframework.security.web.session.HttpSessionEventPublisher</listener-class>
    </listener>

    <filter>
        <filter-name>springSessionRepositoryFilter</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>springSessionRepositoryFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <filter>
        <description>spring-security-filter</description>
        <filter-name>springSecurityFilterChain</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>springSecurityFilterChain</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <filter>
        <description>sitemesh-filter</description>
        <filter-name>MyApplicationSitemeshFilter</filter-name>
        <filter-class>com.opensymphony.module.sitemesh.filter.PageFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>MyApplicationSitemeshFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <servlet>
        <description>MyApplication-spring-servlet</description>
        <servlet-name>MyApplicationSpringServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:MyApplication-web-context.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>MyApplicationSpringServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>MyApplicationSpringServlet</servlet-name>
        <url-pattern>/dwr/*</url-pattern>
    </servlet-mapping>

    <servlet>
        <description>MyApplication-webflow-servlet</description>
        <servlet-name>MyApplicationWebFlowServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>WEB-INF/config/MyApplication-webflow-config.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>MyApplicationWebFlowServlet</servlet-name>
        <url-pattern>/manageRegistration</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>MyApplicationWebFlowServlet</servlet-name>
        <url-pattern>/forgotUserCredentials</url-pattern>
    </servlet-mapping>

    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
    <error-page>
        <error-code>404</error-code>
        <location>/WEB-INF/pages/error/error_redirect.jsp</location>
    </error-page>

    <error-page>
        <exception-type>java.lang.Exception</exception-type>
        <location>/WEB-INF/pages/error/error_redirect.jsp</location>
    </error-page>
    <error-page>
        <error-code>500</error-code>
        <location>/WEB-INF/pages/error/error_redirect.jsp</location>
    </error-page>
    <error-page>
        <exception-type>java.io.IOException</exception-type>
        <location>/WEB-INF/pages/error/error_redirect.jsp</location>
    </error-page>

</web-app>
</code>```

答:
Maybe this can help, where you are using this:

```<code><filter>
    <description>sitemesh-filter</description>
    <filter-name>MyApplicationSitemeshFilter</filter-name>
    <filter-class>com.opensymphony.module.sitemesh.filter.PageFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>MyApplicationSitemeshFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>
</code>```

Try replacing it with this:

```<code>   <filter>
        <filter-name>sitemesh</filter-name>
        <filter-class>com.opensymphony.sitemesh.webapp.SiteMeshFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>sitemesh</filter-name>
        <url-pattern>/*</url-pattern>
        <dispatcher>REQUEST</dispatcher>
        <dispatcher>FORWARD</dispatcher>
        <dispatcher>ERROR</dispatcher>
    </filter-mapping>
</code>```

I consult this information in these two posts:

Link 1

Link 2

ContentLicense: CC BY-SA 3.0

Body:
I'm working on implementing Spring Session in a legacy application. I followed the Spring documentation to get the session library implemented and everything seems to be working well, except....

There is a UI element that is decorated on every page through sitemesh. This UI element checks an object in the session to see if it should be displayed or not. When the object is retrieved from the session through the sitemesh decorator, the object is null. When I access the same object through the controller or main content JSP, the object is populated and everything works fine.

In other words:

Web request -> tomcat -> controller -> jsp -> jstl -> session object = ok

then it continues rendering sitemesh decorator adds main.jsp -> jstl -> same session object is null

I think this must be a configuration issue. I can confirm that when I comment out the springSessionRepositoryFilter the page renders correctly, but then I am not using spring session and hitting my redis server. If anyone has any thoughts, I would really appreciate it. Thanks! My web.xml looks like this.

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    version="3.0" id="WebApp_1398187215147">
    <display-name>MyApplication Web Application</display-name>
    <listener>
        <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
    </listener>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <listener>
        <listener-class>org.springframework.security.web.session.HttpSessionEventPublisher</listener-class>
    </listener>

    <filter>
        <filter-name>springSessionRepositoryFilter</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>springSessionRepositoryFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <filter>
        <description>spring-security-filter</description>
        <filter-name>springSecurityFilterChain</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>springSecurityFilterChain</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <filter>
        <description>sitemesh-filter</description>
        <filter-name>MyApplicationSitemeshFilter</filter-name>
        <filter-class>com.opensymphony.module.sitemesh.filter.PageFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>MyApplicationSitemeshFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <servlet>
        <description>MyApplication-spring-servlet</description>
        <servlet-name>MyApplicationSpringServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:MyApplication-web-context.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>MyApplicationSpringServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>MyApplicationSpringServlet</servlet-name>
        <url-pattern>/dwr/*</url-pattern>
    </servlet-mapping>

    <servlet>
        <description>MyApplication-webflow-servlet</description>
        <servlet-name>MyApplicationWebFlowServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>WEB-INF/config/MyApplication-webflow-config.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>MyApplicationWebFlowServlet</servlet-name>
        <url-pattern>/manageRegistration</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>MyApplicationWebFlowServlet</servlet-name>
        <url-pattern>/forgotUserCredentials</url-pattern>
    </servlet-mapping>

    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
    <error-page>
        <error-code>404</error-code>
        <location>/WEB-INF/pages/error/error_redirect.jsp</location>
    </error-page>

    <error-page>
        <exception-type>java.lang.Exception</exception-type>
        <location>/WEB-INF/pages/error/error_redirect.jsp</location>
    </error-page>
    <error-page>
        <error-code>500</error-code>
        <location>/WEB-INF/pages/error/error_redirect.jsp</location>
    </error-page>
    <error-page>
        <exception-type>java.io.IOException</exception-type>
        <location>/WEB-INF/pages/error/error_redirect.jsp</location>
    </error-page>

</web-app>

Body:
Maybe this can help, where you are using this:

<filter>
    <description>sitemesh-filter</description>
    <filter-name>MyApplicationSitemeshFilter</filter-name>
    <filter-class>com.opensymphony.module.sitemesh.filter.PageFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>MyApplicationSitemeshFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

Try replacing it with this:

   <filter>
        <filter-name>sitemesh</filter-name>
        <filter-class>com.opensymphony.sitemesh.webapp.SiteMeshFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>sitemesh</filter-name>
        <url-pattern>/*</url-pattern>
        <dispatcher>REQUEST</dispatcher>
        <dispatcher>FORWARD</dispatcher>
        <dispatcher>ERROR</dispatcher>
    </filter-mapping>

I consult this information in these two posts:

Link 1

Link 2

ContentLicense: CC BY-SA 4.0


问:
SQL Select where values in List<string>
Is there a way that I can create query against a data source (could be sql, oracle or access) that has a where clause that points to an ArrayList or List?

example:

```<code>Select * from Table where RecordID in (RecordIDList)
</code>```

I've seen some ways to do it with Linq, but I'd rather not resort to it if it's avoidable.

答:
Using Linq to SQL and I assume the Entity Framework you can do the following:

```<code>dataContext.Table.Where(t => RecordIDList.Contains(t.RecordID));
</code>```

Will work with both List<> and ArrayList as they both implement IEnumerable.

Linq and Lambdas require that you reverse the Contains method but it does work and generates a SQL "IN ()" clause.

OwnerDisplayName: JoelHess

ContentLicense: CC BY-SA 2.5

Title: SQL Select where values in List<string>

Body:
Is there a way that I can create query against a data source (could be sql, oracle or access) that has a where clause that points to an ArrayList or List?

example:

Select * from Table where RecordID in (RecordIDList)

I've seen some ways to do it with Linq, but I'd rather not resort to it if it's avoidable.

LastEditorDisplayName: Andrew Hare

Body:
Using Linq to SQL and I assume the Entity Framework you can do the following:

dataContext.Table.Where(t => RecordIDList.Contains(t.RecordID));

Will work with both List<> and ArrayList as they both implement IEnumerable.

Linq and Lambdas require that you reverse the Contains method but it does work and generates a SQL "IN ()" clause.

OwnerDisplayName: Andrew Robinson


问:
How To Assign A Number To A Line From An Array Using PHP
Here is the script as I am using it now:

```<code><?php
echo '<html><body>';

// Data from a flat file
$dataArray = file('text.dat');

// Get the current page
if (isset($_REQUEST['page'])) {
    $currentPage = $_REQUEST['page'];
} else {
    $currentPage = 'some default value';
}

// Pagination settings
$perPage = 3;
$numPages = ceil(count($dataArray) / $perPage);
if(!$currentPage || $currentPage > $numPages)
    $currentPage = 0;
$start = $currentPage * $perPage;
$end = ($currentPage * $perPage) + $perPage;

// Extract ones we need
foreach($dataArray AS $key => $val)
{
    if($key >= $start && $key < $end)
        $pagedData[] = $dataArray[$key];
}

foreach($pagedData AS $item) {
    $item = explode('||', $item);
    echo '<a href="/'. $item[1] .'/index.php">'. $item[0] .'</a><br>';
}

if($currentPage > 0 && $currentPage < $numPages)
    echo '<a href="?page=' . ($currentPage - 1) . '">« Previous page</a><br>';
if($numPages > $currentPage && ($currentPage + 1) < $numPages)
    echo '<a href="?page=' . ($currentPage + 1) . '" class="right">Next page »</a><br>';

echo '</body></html>';
?>
</code>```

And here is the contents of text.dat

```<code>Fun||http://site.com/page11.html
Games||http://site.com/page12.html
Toys||http://site.com/page13.html
Sports||http://site.com/page16.html
Fishing||http://site.com/page18.html
Pools||http://site.com/page41.html
Boats||http://site.com/page91.html
</code>```

Here is my question. There are Seven lines in this array. How can I display the line number (I think it is $key) next to my displayed link? I should end up a list of links, each with it own number like:

```<code>LINE NUMBER - <a href="/'. $item[1] .'/index.php">'. $item[0] .'</a><br />
</code>```

Thanks for any assistance.....

答:
You will need a counter variable, like $i, that is incremented in the loop.

```<code>$i = $start;
foreach ($pagedData as $item) {
    $item = explode('||', $item);
    echo $i. ' - <a href ...';
    $i++;
}
</code>```

Edit: Started $i at $start so it matches the numbering of $key.

Body:
Here is the script as I am using it now:

<?php
echo '';

// Data from a flat file
$dataArray = file('text.dat');

// Get the current page
if (isset($_REQUEST['page'])) {
    $currentPage = $_REQUEST['page'];
} else {
    $currentPage = 'some default value';
}

// Pagination settings
$perPage = 3;
$numPages = ceil(count($dataArray) / $perPage);
if(!$currentPage || $currentPage > $numPages)
    $currentPage = 0;
$start = $currentPage * $perPage;
$end = ($currentPage * $perPage) + $perPage;

// Extract ones we need
foreach($dataArray AS $key => $val)
{
    if($key >= $start && $key < $end)
        $pagedData[] = $dataArray[$key];
}

foreach($pagedData AS $item) {
    $item = explode('||', $item);
    echo ''. $item[0] .'
';
}

if($currentPage > 0 && $currentPage < $numPages)
    echo '« Previous page
';
if($numPages > $currentPage && ($currentPage + 1) < $numPages)
    echo 'Next page »
';

echo '';
?>

And here is the contents of text.dat

Fun||http://site.com/page11.html
Games||http://site.com/page12.html
Toys||http://site.com/page13.html
Sports||http://site.com/page16.html
Fishing||http://site.com/page18.html
Pools||http://site.com/page41.html
Boats||http://site.com/page91.html

Here is my question. There are Seven lines in this array. How can I display the line number (I think it is $key) next to my displayed link? I should end up a list of links, each with it own number like:

LINE NUMBER - '. $item[0] .'

Thanks for any assistance.....

Body:
You will need a counter variable, like $i, that is incremented in the loop.

$i = $start;
foreach ($pagedData as $item) {
    $item = explode('||', $item);
    echo $i. ' - <a href ...';
    $i++;
}

Edit: Started $i at $start so it matches the numbering of $key.


问:
java.lang.NoClassDefFoundError: io/jsonwebtoken/SignatureAlgorithm
i have the following code that tries to create a jwt token. there will always be an error as shown below whenever it tries to execute SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;

I have manually deleted the jwt jar file and update maven again to reinstall the jar but the issue still persist.

Any help will be greatly appreciated!

```<code>//Sample method to construct a JWT
public static String createJWT(String id, String issuer, String subject,
        String payload, String role, String name, long ttlMillis) {
    String jwt = "";

    try {
        //The JWT signature algorithm we will be using to sign the token
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;

        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);

        //We will sign our JWT with our ApiKey secret
        byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(apiKey.getSecret());
        Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());

        //Let's set the JWT Claims
        JwtBuilder builder = Jwts.builder()
                                    .setIssuedAt(now)
                                    .setSubject("test")
                                    .claim("role", role)
                                    .claim("name", name)
                                    .setIssuer("tester")
                                    .signWith(io.jsonwebtoken.SignatureAlgorithm.HS256, signingKey);
                                    //.signWith(signatureAlgorithm, apiKey.getSecret().getBytes("UTF-8"));
                                    //

        //if it has been specified, let's add the expiration
        if (ttlMillis >= 0) {
        long expMillis = nowMillis + ttlMillis;
            Date exp = new Date(expMillis);
            builder.setExpiration(exp);
        }

        //Builds the JWT and serializes it to a compact, URL-safe string
        jwt = builder.compact();

    } catch (Exception ex) {

    }
    return jwt;
}
</code>```

Error Log

java.lang.NoClassDefFoundError: io/jsonwebtoken/SignatureAlgorithm
    at com.test.service.JWTToken.createJWT(JWTToken.java:21)
    at com.test.controller.AccountController.authenticateUser(AccountController.java:82)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.glassfish.jersey.server.internal.routing.SubResourceLocatorRouter$1.run(SubResourceLocatorRouter.java:158)
    at org.glassfish.jersey.server.internal.routing.SubResourceLocatorRouter.getResource(SubResourceLocatorRouter.java:178)
    at org.glassfish.jersey.server.internal.routing.SubResourceLocatorRouter.apply(SubResourceLocatorRouter.java:109)
    at org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:109)
    at org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:112)
    at org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:112)
    at org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:112)
    at org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:112)
    at org.glassfish.jersey.server.internal.routing.RoutingStage.apply(RoutingStage.java:92)
    at org.glassfish.jersey.server.internal.routing.RoutingStage.apply(RoutingStage.java:61)
    at org.glassfish.jersey.process.internal.Stages.process(Stages.java:197)
    at org.glassfish.jersey.server.ServerRuntime$2.run(ServerRuntime.java:301)
    at org.glassfish.jersey.internal.Errors$1.call(Errors.java:271)
    at org.glassfish.jersey.internal.Errors$1.call(Errors.java:267)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:267)
    at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:317)
    at org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:292)
    at org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:1139)
    at org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:460)
    at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:386)
    at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:334)
    at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:221)
    at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:318)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
    at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
    at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
    at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
    at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:416)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:283)
    at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:459)
    at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:167)
    at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:206)
    at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:180)
    at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:235)
    at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:283)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:200)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:132)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:111)
    at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
    at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:536)
    at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:56)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:591)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:571)
    at java.lang.Thread.run(Thread.java:745)

POM Dependencies

```<code><dependencies>

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.8.8</version>
        </dependency>

        <dependency>
            <groupId>org.glassfish.jersey.core</groupId>
            <artifactId>jersey-client</artifactId>
            <version>2.25.1</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jersey.core</groupId>
            <artifactId>jersey-server</artifactId>
            <version>2.25</version>
        </dependency>

        <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
            <version>20160810</version>
        </dependency>
        <dependency>
            <groupId>commons-beanutils</groupId>
            <artifactId>commons-beanutils</artifactId>
            <version>1.9.3</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.jaxrs</groupId>
            <artifactId>jackson-jaxrs-json-provider</artifactId>
            <version>2.8.6</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>2.8.9</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jersey.media</groupId>
            <artifactId>jersey-media-json-jackson</artifactId>
            <version>2.25.1</version>
        </dependency>
        <dependency>
            <groupId>org.eclipse.persistence</groupId>
            <artifactId>org.eclipse.persistence.moxy</artifactId>
            <version>2.6.4</version>
        </dependency>

        <dependency>
             <groupId>org.glassfish.jersey.containers</groupId>
             <artifactId>jersey-container-servlet</artifactId>
             <version>2.22.1</version>
        </dependency>

        <dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt</artifactId>
            <version>0.7.0</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.42</version>
        </dependency>

    </dependencies>
</code>```

答:
I have solved that issue on gradle by using</p>

```<code>implementation "io.jsonwebtoken:jjwt-api:0.11.0"
implementation "io.jsonwebtoken:jjwt-jackson:0.11.0", {exclude group:'io.jsonwebtoken', module:'jjwt-api'}
implementation "io.jsonwebtoken:jjwt-impl:0.11.0", {exclude group:'io.jsonwebtoken', module:'jjwt-api'}
</code>```

Body:
i have the following code that tries to create a jwt token. there will always be an error as shown below whenever it tries to execute SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;

I have manually deleted the jwt jar file and update maven again to reinstall the jar but the issue still persist.

Any help will be greatly appreciated!

//Sample method to construct a JWT
public static String createJWT(String id, String issuer, String subject,
        String payload, String role, String name, long ttlMillis) {
    String jwt = "";

    try {
        //The JWT signature algorithm we will be using to sign the token
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;

        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);

        //We will sign our JWT with our ApiKey secret
        byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(apiKey.getSecret());
        Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());

        //Let's set the JWT Claims
        JwtBuilder builder = Jwts.builder()
                                    .setIssuedAt(now)
                                    .setSubject("test")
                                    .claim("role", role)
                                    .claim("name", name)
                                    .setIssuer("tester")
                                    .signWith(io.jsonwebtoken.SignatureAlgorithm.HS256, signingKey);
                                    //.signWith(signatureAlgorithm, apiKey.getSecret().getBytes("UTF-8"));
                                    //

        //if it has been specified, let's add the expiration
        if (ttlMillis >= 0) {
        long expMillis = nowMillis + ttlMillis;
            Date exp = new Date(expMillis);
            builder.setExpiration(exp);
        }

        //Builds the JWT and serializes it to a compact, URL-safe string
        jwt = builder.compact();

    } catch (Exception ex) {

    }
    return jwt;
}

Error Log

java.lang.NoClassDefFoundError: io/jsonwebtoken/SignatureAlgorithm
    at com.test.service.JWTToken.createJWT(JWTToken.java:21)
    at com.test.controller.AccountController.authenticateUser(AccountController.java:82)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.glassfish.jersey.server.internal.routing.SubResourceLocatorRouter$1.run(SubResourceLocatorRouter.java:158)
    at org.glassfish.jersey.server.internal.routing.SubResourceLocatorRouter.getResource(SubResourceLocatorRouter.java:178)
    at org.glassfish.jersey.server.internal.routing.SubResourceLocatorRouter.apply(SubResourceLocatorRouter.java:109)
    at org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:109)
    at org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:112)
    at org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:112)
    at org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:112)
    at org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:112)
    at org.glassfish.jersey.server.internal.routing.RoutingStage.apply(RoutingStage.java:92)
    at org.glassfish.jersey.server.internal.routing.RoutingStage.apply(RoutingStage.java:61)
    at org.glassfish.jersey.process.internal.Stages.process(Stages.java:197)
    at org.glassfish.jersey.server.ServerRuntime$2.run(ServerRuntime.java:301)
    at org.glassfish.jersey.internal.Errors$1.call(Errors.java:271)
    at org.glassfish.jersey.internal.Errors$1.call(Errors.java:267)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:267)
    at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:317)
    at org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:292)
    at org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:1139)
    at org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:460)
    at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:386)
    at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:334)
    at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:221)
    at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:318)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
    at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
    at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
    at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
    at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:416)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:283)
    at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:459)
    at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:167)
    at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:206)
    at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:180)
    at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:235)
    at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:283)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:200)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:132)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:111)
    at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
    at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:536)
    at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:56)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:591)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:571)
    at java.lang.Thread.run(Thread.java:745)

POM Dependencies

<dependencies>

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.8.8</version>
        </dependency>

        <dependency>
            <groupId>org.glassfish.jersey.core</groupId>
            <artifactId>jersey-client</artifactId>
            <version>2.25.1</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jersey.core</groupId>
            <artifactId>jersey-server</artifactId>
            <version>2.25</version>
        </dependency>

        <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
            <version>20160810</version>
        </dependency>
        <dependency>
            <groupId>commons-beanutils</groupId>
            <artifactId>commons-beanutils</artifactId>
            <version>1.9.3</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.jaxrs</groupId>
            <artifactId>jackson-jaxrs-json-provider</artifactId>
            <version>2.8.6</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>2.8.9</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jersey.media</groupId>
            <artifactId>jersey-media-json-jackson</artifactId>
            <version>2.25.1</version>
        </dependency>
        <dependency>
            <groupId>org.eclipse.persistence</groupId>
            <artifactId>org.eclipse.persistence.moxy</artifactId>
            <version>2.6.4</version>
        </dependency>

        <dependency>
             <groupId>org.glassfish.jersey.containers</groupId>
             <artifactId>jersey-container-servlet</artifactId>
             <version>2.22.1</version>
        </dependency>

        <dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt</artifactId>
            <version>0.7.0</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.42</version>
        </dependency>

    </dependencies>

Body:
I have solved that issue on gradle by using

implementation "io.jsonwebtoken:jjwt-api:0.11.0"
implementation "io.jsonwebtoken:jjwt-jackson:0.11.0", {exclude group:'io.jsonwebtoken', module:'jjwt-api'}
implementation "io.jsonwebtoken:jjwt-impl:0.11.0", {exclude group:'io.jsonwebtoken', module:'jjwt-api'}


问:
FilesSystemWatcher For each item in List, look at that file
Goal:

The main goal is to get all path names from MySQL, and use File System Watch to watch them paths for rename, deleted and created.

I have this full code here:

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using MySql.Data.MySqlClient;

namespace ConsoleApp1

{
    class Program
    {

        static void Main(string[] args)
        {

            Run();
        }

        public static void Run()
        {

            MySqlConnection mcon = new MySqlConnection("credentials");
            MySqlDataReader myreader = null;
            MySqlCommand cmd = new MySqlCommand("select * from files", mcon);
            mcon.Open();

            myreader = cmd.ExecuteReader();

            List<String> list = new List<String>();
            while (myreader.Read())
            {
                list.Add(myreader[1].ToString());

                foreach (string i in list)
                {
                    Console.WriteLine(i);
                    FileSystemWatcher watcher = new FileSystemWatcher();
                    watcher.Path = Path.GetDirectoryName($@"{i}");
                    watcher.Filter = Path.GetFileName($@"{i}");
                    watcher.EnableRaisingEvents = true;
                    watcher.IncludeSubdirectories = true;

                    watcher.Created += directoryChange;
                    watcher.Deleted += directoryChange;
                    watcher.Renamed += onRename;

                    Console.Read();
                }
            }
            mcon.Close();

        }

        private static void directoryChange(object source, System.IO.FileSystemEventArgs e)
        {
            Console.WriteLine($"{e.ChangeType} - {e.FullPath} - {System.Environment.NewLine}");
        }

        private static void onRename(object source, RenamedEventArgs e)
        {
            Console.WriteLine($"{e.OldFullPath} renamed to {e.FullPath}");
        }

    }
}
</code>```

And this is a table in MySQL:

```<code>ID                   Path
1   G:/Folder/EdGzi/Test purposes Python/file.txt
2   G:/Folder/EdGzi/Test purposes Python/test2.txt
</code>```

Problem:

When I run this application. It watches only 1 file(only the top record only from MySQL data). Whereas, it should have been watching all the files returned from MySQL table.

That's why I have created the foreach code.

Question:

How can I do this?

答:
You can given FileSystemWatcher objects only one directory and file extension.
You must create multiple FileSystemWatcher objects to monitor multiple different files. If you do this, you must c# lock statement each event.

This example follows the *.jpg extensions, including subdirectories in the target directory.

    static void Main(string[] args)
    {
        // target main folder
        string directoryName = @"E:\Apps\2019\SADtest\Decupe\SADtest\Veriler\sources\";

        // such as only watch JPG files
        string fileExtension = "*.jpg";

        using (FileSystemWatcher watcher = new FileSystemWatcher())
        {
            // NotifyFilter is Flag attribute.
            // triggers when file names created, changed or updated.
            watcher.NotifyFilter = NotifyFilters.FileName | NotifyFilters.CreationTime | NotifyFilters.LastWrite;
            watcher.Path = directoryName;

            // the Filter propertie must contain wildcards or empty.
            // you cannot write multiple extensions.
            // all files  : *.*
            // only text  : *.txt
            // ends withs : *test2.txt
            watcher.Filter = fileExtension;

            // track the same extensions in all subdirectories.
            watcher.IncludeSubdirectories = true;

            // register events
            watcher.Created += Watcher_Created;
            watcher.Deleted += Watcher_Deleted;
            watcher.Renamed += Watcher_Renamed;

            // begin watching...
            watcher.EnableRaisingEvents = true;

            // sample message
            Console.WriteLine("Press 'ENTER' to quit watching.");
            Console.WriteLine($"I am watching the files with the '{fileExtension}' extension in the '{directoryName}' directory.");

            // wait for the user to quit the program.
            Console.WriteLine();

            Console.Read();
        }
    }

    private static void Watcher_Renamed(object sender, RenamedEventArgs e)
    {
        Console.WriteLine($"Renamed:File: {e.OldFullPath} renamed to {e.FullPath}");
    }

    private static void Watcher_Deleted(object sender, FileSystemEventArgs e)
    {
        Console.WriteLine($"Deleted:File: {e.FullPath} {e.ChangeType}");
    }

    private static void Watcher_Created(object sender, FileSystemEventArgs e)
    {
        Console.WriteLine($"Created:File: {e.FullPath} {e.ChangeType}");
    }
```

Here is the console results :

Press 'ENTER' to quit watching.
I am watching the files with the '*.jpg' extension in the 'E:\Apps\2019\SADtest\Decupe\SADtest\Veriler\sources' directory.

Renamed:File: E:\Apps\2019\SADtest\Decupe\SADtest\Veriler\sources\meee.jpg renamed to E:\Apps\2019\SADtest\Decupe\SADtest\Veriler\sources\sener.jpg
Created:File: E:\Apps\2019\SADtest\Decupe\SADtest\Veriler\sources\logo2.jpg Created
Deleted:File: E:\Apps\2019\SADtest\Decupe\SADtest\Veriler\sources\logo2.jpg Deleted

Body:
Goal:

The main goal is to get all path names from MySQL, and use File System Watch to watch them paths for rename, deleted and created.

I have this full code here:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using MySql.Data.MySqlClient;

namespace ConsoleApp1

{
    class Program
    {

        static void Main(string[] args)
        {

            Run();
        }

        public static void Run()
        {

            MySqlConnection mcon = new MySqlConnection("credentials");
            MySqlDataReader myreader = null;
            MySqlCommand cmd = new MySqlCommand("select * from files", mcon);
            mcon.Open();

            myreader = cmd.ExecuteReader();

            List<String> list = new List<String>();
            while (myreader.Read())
            {
                list.Add(myreader[1].ToString());

                foreach (string i in list)
                {
                    Console.WriteLine(i);
                    FileSystemWatcher watcher = new FileSystemWatcher();
                    watcher.Path = Path.GetDirectoryName($@"{i}");
                    watcher.Filter = Path.GetFileName($@"{i}");
                    watcher.EnableRaisingEvents = true;
                    watcher.IncludeSubdirectories = true;

                    watcher.Created += directoryChange;
                    watcher.Deleted += directoryChange;
                    watcher.Renamed += onRename;

                    Console.Read();
                }
            }
            mcon.Close();

        }

        private static void directoryChange(object source, System.IO.FileSystemEventArgs e)
        {
            Console.WriteLine($"{e.ChangeType} - {e.FullPath} - {System.Environment.NewLine}");
        }

        private static void onRename(object source, RenamedEventArgs e)
        {
            Console.WriteLine($"{e.OldFullPath} renamed to {e.FullPath}");
        }

    }
}

And this is a table in MySQL:

ID                   Path
1   G:/Folder/EdGzi/Test purposes Python/file.txt
2   G:/Folder/EdGzi/Test purposes Python/test2.txt

Problem:

When I run this application. It watches only 1 file(only the top record only from MySQL data). Whereas, it should have been watching all the files returned from MySQL table.

That's why I have created the foreach code.

Question:

How can I do this?

Body:
You can given FileSystemWatcher objects only one directory and file extension.
You must create multiple FileSystemWatcher objects to monitor multiple different files. If you do this, you must c# lock statement each event.

This example follows the *.jpg extensions, including subdirectories in the target directory.

    static void Main(string[] args)
    {
        // target main folder
        string directoryName = @"E:\Apps\2019\SADtest\Decupe\SADtest\Veriler\sources\";

        // such as only watch JPG files
        string fileExtension = "*.jpg";

        using (FileSystemWatcher watcher = new FileSystemWatcher())
        {
            // NotifyFilter is Flag attribute.
            // triggers when file names created, changed or updated.
            watcher.NotifyFilter = NotifyFilters.FileName | NotifyFilters.CreationTime | NotifyFilters.LastWrite;
            watcher.Path = directoryName;

            // the Filter propertie must contain wildcards or empty.
            // you cannot write multiple extensions.
            // all files  : *.*
            // only text  : *.txt
            // ends withs : *test2.txt
            watcher.Filter = fileExtension;

            // track the same extensions in all subdirectories.
            watcher.IncludeSubdirectories = true;

            // register events
            watcher.Created += Watcher_Created;
            watcher.Deleted += Watcher_Deleted;
            watcher.Renamed += Watcher_Renamed;

            // begin watching...
            watcher.EnableRaisingEvents = true;

            // sample message
            Console.WriteLine("Press 'ENTER' to quit watching.");
            Console.WriteLine($"I am watching the files with the '{fileExtension}' extension in the '{directoryName}' directory.");

            // wait for the user to quit the program.
            Console.WriteLine();

            Console.Read();
        }
    }

    private static void Watcher_Renamed(object sender, RenamedEventArgs e)
    {
        Console.WriteLine($"Renamed:File: {e.OldFullPath} renamed to {e.FullPath}");
    }

    private static void Watcher_Deleted(object sender, FileSystemEventArgs e)
    {
        Console.WriteLine($"Deleted:File: {e.FullPath} {e.ChangeType}");
    }

    private static void Watcher_Created(object sender, FileSystemEventArgs e)
    {
        Console.WriteLine($"Created:File: {e.FullPath} {e.ChangeType}");
    }

Here is the console results :

Press 'ENTER' to quit watching.
I am watching the files with the '*.jpg' extension in the 'E:\Apps\2019\SADtest\Decupe\SADtest\Veriler\sources' directory.

Renamed:File: E:\Apps\2019\SADtest\Decupe\SADtest\Veriler\sources\meee.jpg renamed to E:\Apps\2019\SADtest\Decupe\SADtest\Veriler\sources\sener.jpg
Created:File: E:\Apps\2019\SADtest\Decupe\SADtest\Veriler\sources\logo2.jpg Created
Deleted:File: E:\Apps\2019\SADtest\Decupe\SADtest\Veriler\sources\logo2.jpg Deleted


问:
Java and MySql connection problem
I am using Java+MySql. I am trying to add bulk data (around 40 million records). My application works fine for couple of hundred thousands records but after that it starts giving me following exception:

```<code>Exception in thread "main" com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure

The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
    at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:1116)
    at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:344)
    at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2333)
    at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2370)
    at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2154)
    at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:792)
    at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:47)
    at sun.reflect.GeneratedConstructorAccessor5.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
    at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:381)
    at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:305)
    at java.sql.DriverManager.getConnection(Unknown Source)
    at java.sql.DriverManager.getConnection(Unknown Source)
    at net.jboss.Database.DatabaseConnection.getConnection(DatabaseConnection.java:48)
    at net.jboss.emp.idm.adta(mde.java:96)
    at net.jboss.emp.idm.main(mde.java:69)
Caused by: java.net.SocketException: No buffer space available (maximum connections reached?): connect
    at java.net.PlainSocketImpl.socketConnect(Native Method)
    at java.net.PlainSocketImpl.doConnect(Unknown Source)
    at java.net.PlainSocketImpl.connectToAddress(Unknown Source)
    at java.net.PlainSocketImpl.connect(Unknown Source)
    at java.net.SocksSocketImpl.connect(Unknown Source)
    at java.net.Socket.connect(Unknown Source)
    at java.net.Socket.connect(Unknown Source)
    at java.net.Socket.<init>(Unknown Source)
    at java.net.Socket.<init>(Unknown Source)
    at com.mysql.jdbc.StandardSocketFactory.connect(StandardSocketFactory.java:257)
    at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:294)
    ... 16 more
</code>```

I googled this problem and tried almost every option (updating windows registry, changing my.cnf file, changing mysql global parameters etc.) but its not working.

答:
this can resolve your issue now :)
CommunicationsException</p>

Title: Java and MySql connection problem

Body:
I am using Java+MySql. I am trying to add bulk data (around 40 million records). My application works fine for couple of hundred thousands records but after that it starts giving me following exception:

Exception in thread "main" com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure

The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
    at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:1116)
    at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:344)
    at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2333)
    at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2370)
    at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2154)
    at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:792)
    at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:47)
    at sun.reflect.GeneratedConstructorAccessor5.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
    at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:381)
    at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:305)
    at java.sql.DriverManager.getConnection(Unknown Source)
    at java.sql.DriverManager.getConnection(Unknown Source)
    at net.jboss.Database.DatabaseConnection.getConnection(DatabaseConnection.java:48)
    at net.jboss.emp.idm.adta(mde.java:96)
    at net.jboss.emp.idm.main(mde.java:69)
Caused by: java.net.SocketException: No buffer space available (maximum connections reached?): connect
    at java.net.PlainSocketImpl.socketConnect(Native Method)
    at java.net.PlainSocketImpl.doConnect(Unknown Source)
    at java.net.PlainSocketImpl.connectToAddress(Unknown Source)
    at java.net.PlainSocketImpl.connect(Unknown Source)
    at java.net.SocksSocketImpl.connect(Unknown Source)
    at java.net.Socket.connect(Unknown Source)
    at java.net.Socket.connect(Unknown Source)
    at java.net.Socket.<init>(Unknown Source)
    at java.net.Socket.<init>(Unknown Source)
    at com.mysql.jdbc.StandardSocketFactory.connect(StandardSocketFactory.java:257)
    at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:294)
    ... 16 more

I googled this problem and tried almost every option (updating windows registry, changing my.cnf file, changing mysql global parameters etc.) but its not working.


问:
No compile check for generics in Typescript?
Given the following code:

```<code>interface Contract<T> {
}

class Deal<D> implements Contract<D> {
}

class Agreement<A> implements Contract<A> {
}
</code>```

I would have expected this not to compile:

```<code>let deal:Contract<number> = new Deal<number>()
let agreement:Contract<string> = new Agreement<string>()

// expects this to not compile
agreement = deal;
</code>```

or this

```<code>let deal:Deal<number> = new Deal<number>()
let agreement:Agreement<string> = new Agreement<string>()

// expects this to not compile
agreement = deal;
</code>```

But they both compile!

Here is a playground link

I would have expected that a GenericOf is not the same as Genericof and the compiler should not allow assigning one to the other. What am I missing here?

答:
In TypeScript, type parameters only affect the resulting type when consumed as part of the type of a member. See the relevant documentation for more details.

If you actually use the generic, you do get exactly the error you are expecting:

interface Contract<T> {
    log: (value: T) => void
}

class Deal<D> implements Contract<D> {
    log(value: D) {
        console.log(value)
    }
}

class Agreement implements Contract {
    log(value: A) {
        console.log(value)
    }
}

let deal: Contract<number> = new Deal<number>()
let agreement: Contract<string> = new Agreement<string>()

agreement = deal;
// Error: Type 'Contract<number>' is not assignable to type 'Contract<string>'. Type 'string' is not assignable to type 'number'.
```

Body:
Given the following code:

interface Contract<T> {
}

class Deal<D> implements Contract<D> {
}

class Agreement implements Contract {
}

I would have expected this not to compile:

let deal:Contract<number> = new Deal<number>()
let agreement:Contract<string> = new Agreement<string>()

// expects this to not compile
agreement = deal;

or this

let deal:Deal<number> = new Deal<number>()
let agreement:Agreement<string> = new Agreement<string>()

// expects this to not compile
agreement = deal;

But they both compile!

Here is a playground link

I would have expected that a GenericOf is not the same as Genericof and the compiler should not allow assigning one to the other. What am I missing here?

Body:
In TypeScript, type parameters only affect the resulting type when consumed as part of the type of a member. See the relevant documentation for more details.

If you actually use the generic, you do get exactly the error you are expecting:

interface Contract<T> {
    log: (value: T) => void
}

class Deal<D> implements Contract<D> {
    log(value: D) {
        console.log(value)
    }
}

class Agreement<A> implements Contract<A> {
    log(value: A) {
        console.log(value)
    }
}

let deal: Contract<number> = new Deal<number>()
let agreement: Contract<string> = new Agreement<string>()

agreement = deal;
// Error: Type 'Contract<number>' is not assignable to type 'Contract<string>'. Type 'string' is not assignable to type 'number'.


问:
use Google Cloud Functions with a registry other than registry.npmjs.org
I'm currently trying to deploy a node.js cloud function using a (private) package from the GitHub package registry (npm.pkg.github.com).

According to the official docs here, using private modules is supported by adding a .npmrc file with an access token, however there is no mention of using custom registries.

The .npmrc which I upload to Cloud Functions alongside the package.json and the rest of the code looks like this:

```<code>registry=https://npm.pkg.github.com/<myorg>
//npm.pkg.github.com/:_authToken=<mytoken>
</code>```

However, the deployment fails due to:

```<code>Build failed: {"error": {"canonicalCode": "INVALID_ARGUMENT", "errorMessage": "`npm_install` had stderr output:
npm ERR! code E404
npm ERR! 404 Not Found - GET https://registry.npmjs.org/<mypackage> - Not found
npm ERR! 404
npm ERR! 404 '<mypackage>' is not in the npm registry.
npm ERR! 404 You should bug the author to publish it (or use the name yourself!)
</code>```

So as you can see, the registry definition from the .npmrc seems to be ignored, as it tries to pull the package from npmjs.org, where it does indeed not exist.

Do Google Cloud Functions not support custom registries?

Edit: added verbose log output

```<code>Deploying function (may take a while - up to 2 minutes)...failed.
DEBUG: (gcloud.functions.deploy) OperationError: code=3, message=Build failed: {"error": {"canonicalCode": "INVALID_ARGUMENT", "errorMessage": "`npm_install` had stderr output:\nnpm ERR! code E404\nnpm ERR! 404 Not Found - GET https://registry.npmjs.org/<redacted> - Not found\nnpm ERR! 404 \nnpm ERR! 404  '<redacted>' is not in the npm registry.\nnpm ERR! 404 You should bug the author to publish it (or use the name yourself!)\nnpm ERR! 404 It was specified as a dependency of 'functions'\nnpm ERR! 404 \nnpm ERR! 404 Note that you can also install from a\nnpm ERR! 404 tarball, folder, http url, or git url.\n\nnpm ERR! A complete log of this run can be found in:\nnpm ERR!     /builder/home/.npm/_logs/2020-02-12T14_14_22_565Z-debug.log\nnpm ERR! code ELIFECYCLE\nnpm ERR! errno 1\nnpm ERR! @ preinstall: `./install-function-dependencies`\nnpm ERR! Exit status 1\nnpm ERR! \nnpm ERR! Failed at the @ preinstall script.\nnpm ERR! This is probably not a problem with npm. There is likely additional logging output above.\n\nnpm ERR! A complete log of this run can be found in:\nnpm ERR!     /builder/home/.npm/_logs/2020-02-12T14_14_22_586Z-debug.log\n\nerror: `npm_install` returned code: 1", "errorType": "InternalError", "errorId": "BDE5340F"}}
Traceback (most recent call last):
  File "/usr/local/Caskroom/google-cloud-sdk/latest/google-cloud-sdk/lib/googlecloudsdk/calliope/cli.py", line 981, in Execute
    resources = calliope_command.Run(cli=self, args=args)
  File "/usr/local/Caskroom/google-cloud-sdk/latest/google-cloud-sdk/lib/googlecloudsdk/calliope/backend.py", line 807, in Run
    resources = command_instance.Run(args)
  File "/usr/local/Caskroom/google-cloud-sdk/latest/google-cloud-sdk/lib/surface/functions/deploy.py", line 307, in Run
    return _Run(args, track=self.ReleaseTrack())
  File "/usr/local/Caskroom/google-cloud-sdk/latest/google-cloud-sdk/lib/surface/functions/deploy.py", line 263, in _Run
    op, do_every_poll=TryToSetInvokerPermission)
  File "/usr/local/Caskroom/google-cloud-sdk/latest/google-cloud-sdk/lib/googlecloudsdk/api_lib/functions/util.py", line 306, in CatchHTTPErrorRaiseHTTPExceptionFn
    return func(*args, **kwargs)
  File "/usr/local/Caskroom/google-cloud-sdk/latest/google-cloud-sdk/lib/googlecloudsdk/api_lib/functions/util.py", line 353, in WaitForFunctionUpdateOperation
    do_every_poll=do_every_poll)
  File "/usr/local/Caskroom/google-cloud-sdk/latest/google-cloud-sdk/lib/googlecloudsdk/api_lib/functions/operations.py", line 137, in Wait
    _WaitForOperation(client, request, notice, do_every_poll)
  File "/usr/local/Caskroom/google-cloud-sdk/latest/google-cloud-sdk/lib/googlecloudsdk/api_lib/functions/operations.py", line 111, in _WaitForOperation
    sleep_ms=SLEEP_MS)
  File "/usr/local/Caskroom/google-cloud-sdk/latest/google-cloud-sdk/lib/googlecloudsdk/core/util/retry.py", line 219, in RetryOnResult
    result = func(*args, **kwargs)
  File "/usr/local/Caskroom/google-cloud-sdk/latest/google-cloud-sdk/lib/googlecloudsdk/api_lib/functions/operations.py", line 70, in _GetOperationStatus
    raise exceptions.FunctionsError(OperationErrorToString(op.error))
FunctionsError: OperationError: code=3, message=Build failed: {"error": {"canonicalCode": "INVALID_ARGUMENT", "errorMessage": "`npm_install` had stderr output:\nnpm ERR! code E404\nnpm ERR! 404 Not Found - GET https://registry.npmjs.org/<redacted> - Not found\nnpm ERR! 404 \nnpm ERR! 404  '<redacted>' is not in the npm registry.\nnpm ERR! 404 You should bug the author to publish it (or use the name yourself!)\nnpm ERR! 404 It was specified as a dependency of 'functions'\nnpm ERR! 404 \nnpm ERR! 404 Note that you can also install from a\nnpm ERR! 404 tarball, folder, http url, or git url.\n\nnpm ERR! A complete log of this run can be found in:\nnpm ERR!     /builder/home/.npm/_logs/2020-02-12T14_14_22_565Z-debug.log\nnpm ERR! code ELIFECYCLE\nnpm ERR! errno 1\nnpm ERR! @ preinstall: `./install-function-dependencies`\nnpm ERR! Exit status 1\nnpm ERR! \nnpm ERR! Failed at the @ preinstall script.\nnpm ERR! This is probably not a problem with npm. There is likely additional logging output above.\n\nnpm ERR! A complete log of this run can be found in:\nnpm ERR!     /builder/home/.npm/_logs/2020-02-12T14_14_22_586Z-debug.log\n\nerror: `npm_install` returned code: 1", "errorType": "InternalError", "errorId": "BDE5340F"}}
</code>```

答:
Do Google Cloud Functions not support custom registries?

Google Cloud Functions should support custom registries.
What version of Nodejs are you using? There were reported some other similar issues: Runtime doesn't support private npm packages with Nodejs 10.

On the thread it is mentionded that:

I would like to inform you that the Cloud Functions engineering team
    has rolled out a change to resolve this issue. You may feel free to
    try your migration efforts from Node.js 8 to Node.js 10 again. The
    roll out addresses the 404 NOT_FOUND issue when trying to install private
    packages.

Also I would suggest to test deploying your cloud function using env variables.

```<code>gcloud functions deploy functionName
 --region europe-west1
 --runtime nodejs10
 --source=SOURCE
 --set-env-vars= NPM_REGISTRY=<your private registry URL>, NPM_SCOPE=<@private-registry-scope>, NPM_CONFIG_EXTRA=auth_token
</code>```

EDIT

It seems that the issue resurfaced again for Nodejs10 link

Body:
I'm currently trying to deploy a node.js cloud function using a (private) package from the GitHub package registry (npm.pkg.github.com).

According to the official docs here, using private modules is supported by adding a .npmrc file with an access token, however there is no mention of using custom registries.

The .npmrc which I upload to Cloud Functions alongside the package.json and the rest of the code looks like this:

registry=https://npm.pkg.github.com/<myorg>
//npm.pkg.github.com/:_authToken=<mytoken>

However, the deployment fails due to:

Build failed: {"error": {"canonicalCode": "INVALID_ARGUMENT", "errorMessage": "`npm_install` had stderr output:
npm ERR! code E404
npm ERR! 404 Not Found - GET https://registry.npmjs.org/<mypackage> - Not found
npm ERR! 404
npm ERR! 404 '<mypackage>' is not in the npm registry.
npm ERR! 404 You should bug the author to publish it (or use the name yourself!)

So as you can see, the registry definition from the .npmrc seems to be ignored, as it tries to pull the package from npmjs.org, where it does indeed not exist.

Do Google Cloud Functions not support custom registries?

Edit: added verbose log output

Deploying function (may take a while - up to 2 minutes)...failed.
DEBUG: (gcloud.functions.deploy) OperationError: code=3, message=Build failed: {"error": {"canonicalCode": "INVALID_ARGUMENT", "errorMessage": "`npm_install` had stderr output:\nnpm ERR! code E404\nnpm ERR! 404 Not Found - GET https://registry.npmjs.org/<redacted> - Not found\nnpm ERR! 404 \nnpm ERR! 404  '<redacted>' is not in the npm registry.\nnpm ERR! 404 You should bug the author to publish it (or use the name yourself!)\nnpm ERR! 404 It was specified as a dependency of 'functions'\nnpm ERR! 404 \nnpm ERR! 404 Note that you can also install from a\nnpm ERR! 404 tarball, folder, http url, or git url.\n\nnpm ERR! A complete log of this run can be found in:\nnpm ERR!     /builder/home/.npm/_logs/2020-02-12T14_14_22_565Z-debug.log\nnpm ERR! code ELIFECYCLE\nnpm ERR! errno 1\nnpm ERR! @ preinstall: `./install-function-dependencies`\nnpm ERR! Exit status 1\nnpm ERR! \nnpm ERR! Failed at the @ preinstall script.\nnpm ERR! This is probably not a problem with npm. There is likely additional logging output above.\n\nnpm ERR! A complete log of this run can be found in:\nnpm ERR!     /builder/home/.npm/_logs/2020-02-12T14_14_22_586Z-debug.log\n\nerror: `npm_install` returned code: 1", "errorType": "InternalError", "errorId": "BDE5340F"}}
Traceback (most recent call last):
  File "/usr/local/Caskroom/google-cloud-sdk/latest/google-cloud-sdk/lib/googlecloudsdk/calliope/cli.py", line 981, in Execute
    resources = calliope_command.Run(cli=self, args=args)
  File "/usr/local/Caskroom/google-cloud-sdk/latest/google-cloud-sdk/lib/googlecloudsdk/calliope/backend.py", line 807, in Run
    resources = command_instance.Run(args)
  File "/usr/local/Caskroom/google-cloud-sdk/latest/google-cloud-sdk/lib/surface/functions/deploy.py", line 307, in Run
    return _Run(args, track=self.ReleaseTrack())
  File "/usr/local/Caskroom/google-cloud-sdk/latest/google-cloud-sdk/lib/surface/functions/deploy.py", line 263, in _Run
    op, do_every_poll=TryToSetInvokerPermission)
  File "/usr/local/Caskroom/google-cloud-sdk/latest/google-cloud-sdk/lib/googlecloudsdk/api_lib/functions/util.py", line 306, in CatchHTTPErrorRaiseHTTPExceptionFn
    return func(*args, **kwargs)
  File "/usr/local/Caskroom/google-cloud-sdk/latest/google-cloud-sdk/lib/googlecloudsdk/api_lib/functions/util.py", line 353, in WaitForFunctionUpdateOperation
    do_every_poll=do_every_poll)
  File "/usr/local/Caskroom/google-cloud-sdk/latest/google-cloud-sdk/lib/googlecloudsdk/api_lib/functions/operations.py", line 137, in Wait
    _WaitForOperation(client, request, notice, do_every_poll)
  File "/usr/local/Caskroom/google-cloud-sdk/latest/google-cloud-sdk/lib/googlecloudsdk/api_lib/functions/operations.py", line 111, in _WaitForOperation
    sleep_ms=SLEEP_MS)
  File "/usr/local/Caskroom/google-cloud-sdk/latest/google-cloud-sdk/lib/googlecloudsdk/core/util/retry.py", line 219, in RetryOnResult
    result = func(*args, **kwargs)
  File "/usr/local/Caskroom/google-cloud-sdk/latest/google-cloud-sdk/lib/googlecloudsdk/api_lib/functions/operations.py", line 70, in _GetOperationStatus
    raise exceptions.FunctionsError(OperationErrorToString(op.error))
FunctionsError: OperationError: code=3, message=Build failed: {"error": {"canonicalCode": "INVALID_ARGUMENT", "errorMessage": "`npm_install` had stderr output:\nnpm ERR! code E404\nnpm ERR! 404 Not Found - GET https://registry.npmjs.org/<redacted> - Not found\nnpm ERR! 404 \nnpm ERR! 404  '<redacted>' is not in the npm registry.\nnpm ERR! 404 You should bug the author to publish it (or use the name yourself!)\nnpm ERR! 404 It was specified as a dependency of 'functions'\nnpm ERR! 404 \nnpm ERR! 404 Note that you can also install from a\nnpm ERR! 404 tarball, folder, http url, or git url.\n\nnpm ERR! A complete log of this run can be found in:\nnpm ERR!     /builder/home/.npm/_logs/2020-02-12T14_14_22_565Z-debug.log\nnpm ERR! code ELIFECYCLE\nnpm ERR! errno 1\nnpm ERR! @ preinstall: `./install-function-dependencies`\nnpm ERR! Exit status 1\nnpm ERR! \nnpm ERR! Failed at the @ preinstall script.\nnpm ERR! This is probably not a problem with npm. There is likely additional logging output above.\n\nnpm ERR! A complete log of this run can be found in:\nnpm ERR!     /builder/home/.npm/_logs/2020-02-12T14_14_22_586Z-debug.log\n\nerror: `npm_install` returned code: 1", "errorType": "InternalError", "errorId": "BDE5340F"}}

Body:
Do Google Cloud Functions not support custom registries?

Google Cloud Functions should support custom registries.
What version of Nodejs are you using? There were reported some other similar issues: Runtime doesn't support private npm packages with Nodejs 10.

On the thread it is mentionded that:

I would like to inform you that the Cloud Functions engineering team
    has rolled out a change to resolve this issue. You may feel free to
    try your migration efforts from Node.js 8 to Node.js 10 again. The
    roll out addresses the 404 NOT_FOUND issue when trying to install private
    packages.

Also I would suggest to test deploying your cloud function using env variables.

gcloud functions deploy functionName
 --region europe-west1
 --runtime nodejs10
 --source=SOURCE
 --set-env-vars= NPM_REGISTRY=<your private registry URL>, NPM_SCOPE=<@private-registry-scope>, NPM_CONFIG_EXTRA=auth_token

EDIT

It seems that the issue resurfaced again for Nodejs10 link


问:
How to setup SVG's viewbox, width and height which is scalable and responsive
I am new to SVG design.
Struggling to scale, zoom in/out with container and make it responsive to all the devices.

Is it even possible to design SVG in a way that fits in all the devices and handles browsing zoom in/out functionality?

I have tried to play with viewport and viewbox for each breakpoint.

e.g. for Desktop, I have SVG to fit in a container. should scale and zoom in and out with the container(svgClass).

```<code>.svgClass {
 background-image: url('assets/svg/desktop-svg.svg');
 width: "100%";
 height: 800px;
 position: absolute;
}

<div class="svgClass"></div>
</code>```

Sample SVG

---desktop-svg.svg---

```<code><svg width="1400" height="800" viewbox="0 0 1121 641">
-----
</svg>
</code>```

It fits well with 100% browser zoom, but if in case of zoom in and zoom out SVG gets displaced.

To handle zoom in, I have increased viewport height="1400" and width="800" compared to viewbox (0 0 1121 641). which worked fine but zoom out still fails.

Had tried out: Removed width and height from viewport, also tried with setting auto and 100% with width and height. No success.

How to design SVG which can scale with the container and stay responsive, second do we need to setup viewport and viewbox for each device?

答:
I want to explain with an example in which svg is in the parent container.
The parent container in the application will look like a gray square
Svg will not have the width and height in the header of the svg file but the viewBox must be mandatory to ensure adaptability

I used input to show how with changing the width of the parent container the dimensions of the SVG are proportionally changed

.container {
width: var(--w1,60px);
background:#EAEAEA;

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
    <input type="range"
           min="60"
           max="600"
           oninput="document.querySelector('.container').style.setProperty('--w1', this.value + 'px');"
           value="0">
    <span>width Container</span><br>
</div>
<div class="container" >
    <svg  viewBox="0 0 120 120">
        <defs>
            <mask id="msk1">
                <circle class="maskCircle" cx="60" cy="60" r="40" fill="none"
                        stroke="white" stroke-width="8"
                        stroke-dashoffset="0" stroke-dasharray="251.2">
                    <animate attributeName="stroke-dashoffset" dur="3s"
                             values="251.2;0" fill="freeze"
                             repeatCount="indefinite" />
                </circle>
            </mask>
        </defs>
        <circle class="background" cx="60" cy="60" r="40" fill="none"
                stroke="#E4E4E4" stroke-width="8" />
        <circle class="default" cx="60" cy="60" r="40" fill="none"
                stroke="black"
                stroke-width="8"
  stroke-dasharray="3.14"
                stroke-dashoffset="40"
                mask="url(#msk1)">

        </circle>
    </svg>
</div> </code>```

UPDATE

```<code><div>
<input type="range" min="60" max="600" oninput="document.querySelector('.container').style.setProperty('--w1', this.value + 'px');" value="0"><span>width Container</span><br>
</div>
</code>```

These lines need to be removed from the application since the input in this example serves only to demonstrate the adaptability of SVG when resizing the parent container

Practical advice:

When developing an adaptive SVG application, assign for example viewBox ="0 0 200 200"with dimensions equal to the smallest size of the gadget's screen and when drawing in a vector editor, do not go beyond the boundaries of the document - 200x200px

When you do not assign the width and height of the svg application becomes adaptive that is, it will occupy the entire screen of the gadget

```<code><svg xmlns="http://www.w3.org/2000/svg"
    xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 200 200" >
</code>```

At screen resolution, let's say 1400px svg will increase by 7 times

If, for example, you want the SVG to occupy only one quarter of the parent container, you must specify 25% percent width and height

```<code><div class="container" style="width:25%; height:25%;">
   <svg xmlns="http://www.w3.org/2000/svg"
    xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 200 200" >
    ....
    </svg>
</div>
</code>```

Body:
I am new to SVG design.
Struggling to scale, zoom in/out with container and make it responsive to all the devices.

Is it even possible to design SVG in a way that fits in all the devices and handles browsing zoom in/out functionality?

I have tried to play with viewport and viewbox for each breakpoint.

e.g. for Desktop, I have SVG to fit in a container. should scale and zoom in and out with the container(svgClass).

.svgClass {
 background-image: url('assets/svg/desktop-svg.svg');
 width: "100%";
 height: 800px;
 position: absolute;
}

Sample SVG

---desktop-svg.svg---

<svg width="1400" height="800" viewbox="0 0 1121 641">
-----
</svg>

It fits well with 100% browser zoom, but if in case of zoom in and zoom out SVG gets displaced.

To handle zoom in, I have increased viewport height="1400" and width="800" compared to viewbox (0 0 1121 641). which worked fine but zoom out still fails.

Had tried out: Removed width and height from viewport, also tried with setting auto and 100% with width and height. No success.

How to design SVG which can scale with the container and stay responsive, second do we need to setup viewport and viewbox for each device?

Body:
I want to explain with an example in which svg is in the parent container.
The parent container in the application will look like a gray square
Svg will not have the width and height in the header of the svg file but the viewBox must be mandatory to ensure adaptability

I used input to show how with changing the width of the parent container the dimensions of the SVG are proportionally changed

.container {
width: var(--w1,60px);
background:#EAEAEA;

}

<div>
    <input type="range"
           min="60"
           max="600"
           oninput="document.querySelector('.container').style.setProperty('--w1', this.value + 'px');"
           value="0">
    <span>width Container</span><br>
</div>
<div class="container" >
    <svg  viewBox="0 0 120 120">
        <defs>
            <mask id="msk1">
                <circle class="maskCircle" cx="60" cy="60" r="40" fill="none"
                        stroke="white" stroke-width="8"
                        stroke-dashoffset="0" stroke-dasharray="251.2">
                    <animate attributeName="stroke-dashoffset" dur="3s"
                             values="251.2;0" fill="freeze"
                             repeatCount="indefinite" />
                </circle>
            </mask>
        </defs>
        <circle class="background" cx="60" cy="60" r="40" fill="none"
                stroke="#E4E4E4" stroke-width="8" />
        <circle class="default" cx="60" cy="60" r="40" fill="none"
                stroke="black"
                stroke-width="8"
  stroke-dasharray="3.14"
                stroke-dashoffset="40"
                mask="url(#msk1)">

        </circle>
    </svg>
</div>

UPDATE

<div>
<input type="range" min="60" max="600" oninput="document.querySelector('.container').style.setProperty('--w1', this.value + 'px');" value="0"><span>width Container</span><br>
</div>

These lines need to be removed from the application since the input in this example serves only to demonstrate the adaptability of SVG when resizing the parent container

Practical advice:

When developing an adaptive SVG application, assign for example viewBox ="0 0 200 200"with dimensions equal to the smallest size of the gadget's screen and when drawing in a vector editor, do not go beyond the boundaries of the document - 200x200px

When you do not assign the width and height of the svg application becomes adaptive that is, it will occupy the entire screen of the gadget

<svg xmlns="http://www.w3.org/2000/svg"
    xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 200 200" >

At screen resolution, let's say 1400px svg will increase by 7 times

If, for example, you want the SVG to occupy only one quarter of the parent container, you must specify 25% percent width and height

<div class="container" style="width:25%; height:25%;">
   <svg xmlns="http://www.w3.org/2000/svg"
    xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 200 200" >
    ....
    </svg>
</div>


问:
Laravel - logging "route not found"
I do not see any log output when a route is not found.  I am running laravel in development mode and I can see this error when hitting a route that does not exist.

```<code>"message": "",
"exception":
"Symfony\\Component\\HttpKernel\\Exception\\NotFoundHttpException",
"file":
"/var/www/html/Customer_Interface/vendor/laravel/framework/src/Illuminate/Routing/RouteCollection.php",
"line": 179,
</code>```

However, it does not show any activity storage/logs.  Is there anyway to catch this exception and log it there?

答: Within Handler.php (in directory Exceptions) there is an $dontReport array that holds the exception classes that shall not be reported. As far as I know the said NotFoundHttpException is listed there as default. If you remove it from the array the related exceptions should be represented in the logs.

Title: Laravel - logging "route not found"

Body:
I do not see any log output when a route is not found.  I am running laravel in development mode and I can see this error when hitting a route that does not exist.

"message": "",
"exception":
"Symfony\\Component\\HttpKernel\\Exception\\NotFoundHttpException",
"file":
"/var/www/html/Customer_Interface/vendor/laravel/framework/src/Illuminate/Routing/RouteCollection.php",
"line": 179,

However, it does not show any activity storage/logs.  Is there anyway to catch this exception and log it there?


问:
SSH Tunnel within docker container
I have a client running in a docker container that subscribes to a MQTT broker and then writes the data into a database.
To connect to the MQTT Broker i will have to set up port forwarding.

While developing the client on my local machine the following worked fine:

```<code>SSH -L <mqtt-port:1883>:localhost:<9000> <user>@<ip-of-server-running-broker>
</code>```

The client is then configured to subscribe to the MQTT broker via localhost:9000.
This all works fine on my local machine.

Within the container it wont, unless I run the container with --net=host but I'd rather not do that due to security concerns.

I tried the following:

Create docker network "testNetwork"

Run a ssh_tunnel container within "testNetwork" and implement port forwarding inside this container.

Run the database_client container within "testNetwork" and subscribe to the mqtt broker via the bridge network like ("ssh_tunnel.testNetwork:")

(I want 2 seperate containers for this because the ip address will have to be altered quite often and I don't want to re-build the client container all the time)

But all of my attempts have failed so far. The forwarding seems to work (I can access the shell on the server in the ssh container) but I haven't found a way to actually subscribe to the mqtt broker from within the client container.

Maybe this is actually quite simple and I just don't see how it works, but I've been stuck on this problem for hours by now...
Any help or hints are appreciated!

答:
The solution was actually quite simple and works without using -net=host.
I needed to bind to 0.0.0.0 and use the Gateway Forwarding Option  to allow remote hosts (the database client) to connect to the forwarded ports.

ssh -L -g *:<hostport>:localhost:<mqtt-port/remote port> <user>@<remote-ip>

Other containers within the same Docker bridge network can then simply use the connection string <name-of-ssh-container>:<hostport>.

Title: SSH Tunnel within docker container

Body:
I have a client running in a docker container that subscribes to a MQTT broker and then writes the data into a database.
To connect to the MQTT Broker i will have to set up port forwarding.

While developing the client on my local machine the following worked fine:

SSH -L <mqtt-port:1883>:localhost:<9000> <user>@<ip-of-server-running-broker>

The client is then configured to subscribe to the MQTT broker via localhost:9000.
This all works fine on my local machine.

Within the container it wont, unless I run the container with --net=host but I'd rather not do that due to security concerns.

I tried the following:

Create docker network "testNetwork"

Run a ssh_tunnel container within "testNetwork" and implement port forwarding inside this container.

Run the database_client container within "testNetwork" and subscribe to the mqtt broker via the bridge network like ("ssh_tunnel.testNetwork:")

(I want 2 seperate containers for this because the ip address will have to be altered quite often and I don't want to re-build the client container all the time)

But all of my attempts have failed so far. The forwarding seems to work (I can access the shell on the server in the ssh container) but I haven't found a way to actually subscribe to the mqtt broker from within the client container.

Maybe this is actually quite simple and I just don't see how it works, but I've been stuck on this problem for hours by now...
Any help or hints are appreciated!


问:
How can I hash Clang AST Nodes for use as key in a C++ unordered map?
I need to associate external information with Clang AST nodes. I'd like to do this, at least for now, by using such nodes as keys in unordered maps (C++). However, the Clang AST node types don't appear to support the hash functions that would be required to use them as keys in maps. Declaring an unordered map with key type, clang::VarDecl, for example, causes the following compiler error (g++).

```<code>/usr/include/c++/7/bits/hashtable_policy.h:87:34: error: no match for call to '(const std::hash<clang::VarDecl>) (const clang::VarDecl&)'
</code>```

The narrow question is, Is there a way to use Clang AST nodes as keys in unordered maps in C++?

The broader question is, What is the best way to establish a machine-readable associative store linking AST nodes to associated information?

答: You can get a hash of the cursor while iterating over the AST using clang_hashCursor. It is stable across multiple runs on the same file. But I am not sure if it is guaranteed to be unique within a translation unit for multiple cursors, but then again, once you have a value to start with, you can do any operation to keep it unique within the TU.</p>

Body:
I need to associate external information with Clang AST nodes. I'd like to do this, at least for now, by using such nodes as keys in unordered maps (C++). However, the Clang AST node types don't appear to support the hash functions that would be required to use them as keys in maps. Declaring an unordered map with key type, clang::VarDecl, for example, causes the following compiler error (g++).

/usr/include/c++/7/bits/hashtable_policy.h:87:34: error: no match for call to '(const std::hash<clang::VarDecl>) (const clang::VarDecl&)'

The narrow question is, Is there a way to use Clang AST nodes as keys in unordered maps in C++?

The broader question is, What is the best way to establish a machine-readable associative store linking AST nodes to associated information?