问:
Website incompatible with IE11, fine in Chrome
The following snippet works fine in Chrome but does not display correctly in IE11 or Edge. The navbar is fixed to the top instead of being aligned to the side and the hover effects do not work.

I have ensured that I am declaring; <!DOCTYPE html>, I have also added the following the my  to try to force it into edge compatibility:

```<code><meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
</code>```

Even after doing this the display is still messed up. I go into Developer Tools in IE and cannot find any issues there either.

My code:

HTML

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Dashboard</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css" />
    <link rel="stylesheet" href="css/bootstrap.min.css" />
    <link rel="stylesheet" href="css/layout.css"/>
    @RenderSection("CustomStyles", false)
    @RenderSection("CustomScripts", false)
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
    <div class="container-fluid">
        <div class="col-lg-2 col-md-3 col-sm-8 col-xs-6">
            <nav class="navbar navbar-inverse navbar-fixed-top" id="sidebar-wrapper" role="navigation">
                <ul class="nav sidebar-nav">
                    <li class="sidebar-brand">
                        <a href="/">Dashboard</a>
                    </li>
                    <li class="dropdown">
                        <a href="#" class="dropdown-toggle" data-toggle="dropdown"><i class="fa fa-fw fa-home"></i> Directories <span class="caret"></span></a>
                        <ul class="dropdown-menu" role="menu">
                            <li><a href="#">Item 1</a></li>
                            <li><a href="#">Item 2</a></li>
                            <li><a href="#">Item 3</a></li>
                            <li><a href="#">Item 4</a></li>
                            <li><a href="#">Item 5</a></li>
                            <li><a href="#">Item 6</a></li>
                            <li><a href="#">Item 7</a></li>
                            <li><a href="#">Item 8</a></li>
                            <li><a href="#">Item 9</a></li>
                            <li><a href="#">Item 10</a></li>
                        </ul>
                    </li>
                    <li class="dropdown">
                        <a href="#" class="dropdown-toggle" data-toggle="dropdown"><i class="fa fa-fw fa-gbp"></i> Contracts <span class="caret"></span></a>
                        <ul class="dropdown-menu" role="menu">
                            <li><a href="#">Item 1</a></li>
                            <li><a href="#">Item 2</a></li>
                            <li><a href="#">Item 3</a></li>
                            <li><a href="#">Item 4</a></li>
                            <li><a href="#">Item 5</a></li>
                            <li><a href="#">Item 6</a></li>
                            <li><a href="#">Item 7</a></li>
                            <li><a href="#">Item 8</a></li>
                            <li><a href="#">Item 9</a></li>
                            <li><a href="#">Item 10</a></li>
                        </ul>
                    </li>
                    <li>
                        <a href="#"><i class="fa fa-fw fa-tasks"></i> Processes</a>
                    </li>
                    <li>
                        <a href="#"><i class="fa fa-fw fa-file"></i> Filing </a>
                    </li>
                    <li>
                        <a asp-controller="MyProfile" asp-action="Index">
                            <i class="fa fa-fw fa-user"></i> My Profile
                        </a>
                    </li>
                </ul>
            </nav>
        </div>
        <div class="col-lg-10 col-md-9 col-sm-4 col-xs-6">
            @RenderBody()
        </div>
    </div>
    <script>
        $(document).ready(function () {
            $(".dropdown-toggle").click(function () {
                $(".caret").removeClass('rotate-180');
                $(this).find(".caret").addClass('rotate-180');
            });
            $(document).mouseup(function (e) {
                $(".caret").removeClass('rotate-180');
            });
        });
    </script>
    @RenderSection("Scripts", required: false)
</body>
</html>
</code>```

CSS

```<code>body {
    position: relative;
    overflow-x: hidden;
    margin: 0;
    padding: 0;
}

body, html {
    height: var(--full-height);
    background-color: var(--bg-color)
}

/********************************************
/*                                          *
/*                                          *
/*               Variables                  *
/*                                          *
/*                                          *
********************************************/

:root {
    /* BACKGROUND COLOUR */
    --bg-color: #FFF;

    /* HIGHLIGHT COLOUR */
    --highlight-color: #ff5c16;

    /* WIDTH */
    --width1: 16.67%;
    --full-width: 100%;

    /* HEIGHT */
    --full-height: 100%;

    /* Sidebar Font Size*/
    --sidebar-fontsize: 16px;
}

/********************************************
/*                                          *
/*                                          *
/*                Wrappers                  *
/*                                          *
/*                                          *
********************************************/

.container-fluid {
    padding: 0;
    margin: 0;
    height: 100%;
}

/********************************************
/*                  Header                  *
********************************************/

.headerWrapper {
    height: 7%;
    width: 100%;
    padding: 0;
    margin: 0;
}

.headerWrapper > h1 {
    padding: 0;
    margin: 0;
    font-size: 18px;
}

/********************************************
/*                  Content                 *
********************************************/

.contentWrapper {
    height: 93%;
    width: 100%;
    padding: 0;
    margin: 0;
}

/********************************************
/*                  Sidebar                 *
********************************************/

#sidebar-wrapper {
    width: var(--width1);
}

#sidebar-wrapper {
    -moz-transition: all 0.5s ease;
    -o-transition: all 0.5s ease;
    -webkit-transition: all 0.5s ease;
    transition: all 0.5s ease;
    background-color: #1A1A1A;
    height: var(--full-height);
    overflow-x: hidden;
    overflow-y: auto;
    transition: all 0.5s ease;
}

#sidebar-wrapper::-webkit-scrollbar {
    display: none;
}

/********************************************
/*                                          *
/*                                          *
/*             Sidebar Styling              *
/*                                          *
/*                                          *
********************************************/

/*.sidebar-nav {
    list-style: none;
    margin: 0;
    padding: 0;
    position: absolute;
    top: 0;
}*/

.sidebar-nav .sidebar-brand:before {
    background-color: #222222;
    color: #FFF;
}

.sidebar-nav .sidebar-brand > a {
    color: #FFF;
    font-size: 24px;
    line-height: 60px;
}

.sidebar-nav .sidebar-brand a:hover {
    background-color: #222222;
}

.sidebar-nav > li > a {
    line-height: 20px;
    color: #DDD;
    padding: 10px 15px 10px 30px;
    font-size: var(--sidebar-fontsize);
}

.sidebar-nav > li:before {
    width: 3px;
    height: var(--full-height);
    position: absolute;
    top: 0;
    left: 0;
    background-color: var(--highlight-color);
    transition: width .2s ease-in;
    content: '';
}

.sidebar-nav > li:hover:before {
    transition: width .2s ease-in;
    width: var(--full-width);
}

.sidebar-nav > li.open:hover before {
    transition: width .2s ease-in;
    width: var(--full-width);
}

.sidebar-nav .dropdown-menu {
    background-color: #222222;
    border-radius: 0;
    border: none;
    margin: 0;
    padding: 0;
    position: relative;
    width: var(--full-width);
}

.sidebar-nav .dropdown-toggle > .caret {
    float: right;
    margin: 6px 0;
}

.sidebar-nav li a:hover, .sidebar-nav li a:active, .sidebar-nav li a:focus,
.sidebar-nav li.open a:active, .sidebar-nav li.open a:active, .sidebar-nav li.open a:active,
.sidebar-nav .open > a:hover, .sidebar-nav .open > a:focus {
    background-color: transparent;
    color: #FFF;
    text-decoration: none;
}

.nav .open > a {
    background-color: transparent;
}

.nav .open > a:hover, .nav .open > a:focus {
    background-color: transparent;
}

.caret {
    -moz-transition: transform 0.5s;
    -webkit-transition: transform 0.5s;
    transition: transform 0.5s;
}

.rotate-180 {
    transform: rotate(-180deg);
}
</code>```

Image working in Chrome:

But completely different and no hover effect in IE11:

I am using Bootstrap but I was under the impression that forcing it into Edge compatibility should fix any issues I may have.

答:
CSS custom properties (which you are using to define your variables) are not supported by any version of Internet Explorer, and as far as I know, there is no way to polyfill this functionality.

You will have to refactor your CSS to not use them if you want to support IE. Perhaps consider using a compile-to-CSS language that supports variables, like Sass or Less.

Body:
The following snippet works fine in Chrome but does not display correctly in IE11 or Edge. The navbar is fixed to the top instead of being aligned to the side and the hover effects do not work.

I have ensured that I am declaring; <!DOCTYPE html>, I have also added the following the my  to try to force it into edge compatibility:

<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">

Even after doing this the display is still messed up. I go into Developer Tools in IE and cannot find any issues there either.

My code:

HTML

<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Dashboard</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css" />
    <link rel="stylesheet" href="css/bootstrap.min.css" />
    <link rel="stylesheet" href="css/layout.css"/>
    @RenderSection("CustomStyles", false)
    @RenderSection("CustomScripts", false)

                        Dashboard

                         Directories

Item 1

Item 2

Item 3

Item 4

Item 5

Item 6

Item 7

Item 8

Item 9

Item 10

                         Contracts

Item 1

Item 2

Item 3

Item 4

Item 5

Item 6

Item 7

Item 8

Item 9

Item 10

                         Processes

                         Filing

                             My Profile

            @RenderBody()

    @RenderSection("Scripts", required: false)

CSS

body {
    position: relative;
    overflow-x: hidden;
    margin: 0;
    padding: 0;
}

body, html {
    height: var(--full-height);
    background-color: var(--bg-color)
}

/********************************************
/*                                          *
/*                                          *
/*               Variables                  *
/*                                          *
/*                                          *
********************************************/

:root {
    /* BACKGROUND COLOUR */
    --bg-color: #FFF;

    /* HIGHLIGHT COLOUR */
    --highlight-color: #ff5c16;

    /* WIDTH */
    --width1: 16.67%;
    --full-width: 100%;

    /* HEIGHT */
    --full-height: 100%;

    /* Sidebar Font Size*/
    --sidebar-fontsize: 16px;
}

/********************************************
/*                                          *
/*                                          *
/*                Wrappers                  *
/*                                          *
/*                                          *
********************************************/

.container-fluid {
    padding: 0;
    margin: 0;
    height: 100%;
}

/********************************************
/*                  Header                  *
********************************************/

.headerWrapper {
    height: 7%;
    width: 100%;
    padding: 0;
    margin: 0;
}

.headerWrapper > h1 {
    padding: 0;
    margin: 0;
    font-size: 18px;
}

/********************************************
/*                  Content                 *
********************************************/

.contentWrapper {
    height: 93%;
    width: 100%;
    padding: 0;
    margin: 0;
}

/********************************************
/*                  Sidebar                 *
********************************************/

#sidebar-wrapper {
    width: var(--width1);
}

#sidebar-wrapper {
    -moz-transition: all 0.5s ease;
    -o-transition: all 0.5s ease;
    -webkit-transition: all 0.5s ease;
    transition: all 0.5s ease;
    background-color: #1A1A1A;
    height: var(--full-height);
    overflow-x: hidden;
    overflow-y: auto;
    transition: all 0.5s ease;
}

#sidebar-wrapper::-webkit-scrollbar {
    display: none;
}

/********************************************
/*                                          *
/*                                          *
/*             Sidebar Styling              *
/*                                          *
/*                                          *
********************************************/

/*.sidebar-nav {
    list-style: none;
    margin: 0;
    padding: 0;
    position: absolute;
    top: 0;
}*/

.sidebar-nav .sidebar-brand:before {
    background-color: #222222;
    color: #FFF;
}

.sidebar-nav .sidebar-brand > a {
    color: #FFF;
    font-size: 24px;
    line-height: 60px;
}

.sidebar-nav .sidebar-brand a:hover {
    background-color: #222222;
}

.sidebar-nav > li > a {
    line-height: 20px;
    color: #DDD;
    padding: 10px 15px 10px 30px;
    font-size: var(--sidebar-fontsize);
}

.sidebar-nav > li:before {
    width: 3px;
    height: var(--full-height);
    position: absolute;
    top: 0;
    left: 0;
    background-color: var(--highlight-color);
    transition: width .2s ease-in;
    content: '';
}

.sidebar-nav > li:hover:before {
    transition: width .2s ease-in;
    width: var(--full-width);
}

.sidebar-nav > li.open:hover before {
    transition: width .2s ease-in;
    width: var(--full-width);
}

.sidebar-nav .dropdown-menu {
    background-color: #222222;
    border-radius: 0;
    border: none;
    margin: 0;
    padding: 0;
    position: relative;
    width: var(--full-width);
}

.sidebar-nav .dropdown-toggle > .caret {
    float: right;
    margin: 6px 0;
}

.sidebar-nav li a:hover, .sidebar-nav li a:active, .sidebar-nav li a:focus,
.sidebar-nav li.open a:active, .sidebar-nav li.open a:active, .sidebar-nav li.open a:active,
.sidebar-nav .open > a:hover, .sidebar-nav .open > a:focus {
    background-color: transparent;
    color: #FFF;
    text-decoration: none;
}

.nav .open > a {
    background-color: transparent;
}

.nav .open > a:hover, .nav .open > a:focus {
    background-color: transparent;
}

.caret {
    -moz-transition: transform 0.5s;
    -webkit-transition: transform 0.5s;
    transition: transform 0.5s;
}

.rotate-180 {
    transform: rotate(-180deg);
}

Image working in Chrome:

But completely different and no hover effect in IE11:

I am using Bootstrap but I was under the impression that forcing it into Edge compatibility should fix any issues I may have.


来源: stackexchange

问:
run js function in python which calls another js function
I know I can call JavaScript function in python with js2py like below :

```<code>import execjs
import  js2py
un ='''
function sample(x)
{
    return x
}
'''
print(js2py.eval_js(un)("Hi"))
</code>```

but my function in JavaScript calls another function, how can handle it in Python?

```<code>import execjs
import  js2py

un ='''
function sample(x)
{
    return func2(x)
}
'''
print(js2py.eval_js(un)("Hi"))
</code>```

thre maybe more than 2 Functions

答:
One can define multiple functions in the string. Note that js2py runs the last function first.

```<code>import  js2py
un ='''
function func2(q) {
    return q + " World";
}
function sample(x) {
    return func2(x) + "!";
}
'''
print(js2py.eval_js(un)("Hello"))
</code>```

This prints the always heartwarming Hello World!

ContentLicense: CC BY-SA 3.0

Body:
I know I can call JavaScript function in python with js2py like below :

import execjs
import  js2py
un ='''
function sample(x)
{
    return x
}
'''
print(js2py.eval_js(un)("Hi"))

but my function in JavaScript calls another function, how can handle it in Python?

import execjs
import  js2py

un ='''
function sample(x)
{
    return func2(x)
}
'''
print(js2py.eval_js(un)("Hi"))

thre maybe more than 2 Functions

Body:
One can define multiple functions in the string. Note that js2py runs the last function first.

import  js2py
un ='''
function func2(q) {
    return q + " World";
}
function sample(x) {
    return func2(x) + "!";
}
'''
print(js2py.eval_js(un)("Hello"))

This prints the always heartwarming Hello World!

ContentLicense: CC BY-SA 4.0


问:
POST versus Ajax call
Now that most modern browsers support AJAX and client-side requests without performing a POST, what is the role of POST (form post)?

Are there situations or general rules when a POST will always be preferred to a XmlHttpRequest?

All that POST is doing is placing variable key value pairs inside the server head. The advantages of POST I can think of are large amounts of data and mobile browsers. Are there many others I'm missing?

N.B. I know you can perform POSTs with AJAX calls, I'm talking primarily about with a <form> tag

答:
Er .. posting forms?

Post is really good for big forms as the values are hidden in the html headers and not tacked onto the url string?

OwnerDisplayName: Chris

ContentLicense: CC BY-SA 2.5

Title: POST versus Ajax call

OwnerDisplayName: James Anderson


问:
AttributeError: module 'tensorflow' has no attribute 'python'
```<code>>import tensorflow

>import tensorflow.contrib

>tensorflow.contrib

module 'tensorflow.contrib' from 'D:\\ProgramData\\Anaconda3\\lib\\site-packages\\tensorflow\\contrib\\__init__.py'

>import tensorflow.python

>tensorflow.python

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: module 'tensorflow' has no attribute 'python'
</code>```

As you can see, I run this code in a cmd(win 10). Both "import tensorflow.contrib" and "import tensorflow.python" are OK, but commands "tensorflow.contrib" and "tensorflow.python" are different. One returns a directory and the other returns AttributeError.

Does anyone have a clue why?

答:
tensorflow.__init__() explicitly deletes its reference to the tensorflow.python module after importing everything from it.

The reason for that is to provide access to the submodules contained in the python package in the top-level tensorflow namespace. A few things from the tensorflow.core package are also imported and made available in the tensorflow namespace.

I think that the idea is not to import tensorflow.python directly. Those classes, objects, and submodules of python that are intended to be used by applications are made available simply by import tensorflow.

Body:
>import tensorflow

>import tensorflow.contrib

>tensorflow.contrib

module 'tensorflow.contrib' from 'D:\\ProgramData\\Anaconda3\\lib\\site-packages\\tensorflow\\contrib\\__init__.py'

>import tensorflow.python

>tensorflow.python

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: module 'tensorflow' has no attribute 'python'

As you can see, I run this code in a cmd(win 10). Both "import tensorflow.contrib" and "import tensorflow.python" are OK, but commands "tensorflow.contrib" and "tensorflow.python" are different. One returns a directory and the other returns AttributeError.

Does anyone have a clue why?


问:
Oracle SQL Count Grouping by without repeating records in previous days
I need to count the distinct WO grouping by day, but not counting the WO that were already in previous days. And sum the LABOR column grouping by day also.

SAMPLE:

```<code>DAY   WO     LABOR
6   379157    3
9   379157    5
10  379404    8
10  379362    8
19  386118    10
24  386547    2
25  388711    8
25  386547    5
30  386547    1
</code>```

RESULTS

```<code>DAY   WO    LABOR
6      1    3
9      0    5
10     2    16
19     1    10
24     1    2
25     1    13
30     0    1
</code>```

Thanks a lot for your help

答:
Here's a solution using row_number (since we only want to count the first instance of each wo across all days, per day):</p>

```<code>WITH your_table AS (SELECT 6 DAY, 379157 wo, 3 labor FROM dual UNION ALL
                    SELECT 9 DAY, 379157 wo, 5 labor FROM dual UNION ALL
                    SELECT 10 DAY, 379404 wo, 8 labor FROM dual UNION ALL
                    SELECT 10 DAY, 379362 wo, 8 labor FROM dual UNION ALL
                    SELECT 19 DAY, 386118 wo, 10 labor FROM dual UNION ALL
                    SELECT 24 DAY, 386547 wo, 2 labor FROM dual UNION ALL
                    SELECT 25 DAY, 388711 wo, 8 labor FROM dual UNION ALL
                    SELECT 25 DAY, 386547 wo, 5 labor FROM dual UNION ALL
                    SELECT 30 DAY, 386547 wo, 1 labor FROM dual)
-- end of mimicking data in "your_table" - see the main SQL below:
SELECT DAY,
       SUM(CASE WHEN rn = 1 THEN 1 ELSE 0 END) wo,
       SUM(labor) labor
FROM   (SELECT DAY,
               wo,
               labor,
               row_number() OVER (PARTITION BY wo ORDER BY DAY) rn
        FROM   your_table)
GROUP BY DAY
ORDER BY DAY;

       DAY         WO      LABOR
---------- ---------- ----------
         6          1          3
         9          0          5
        10          2         16
        19          1         10
        24          1          2
        25          1         13
        30          0          1
</code>```

Body:
I need to count the distinct WO grouping by day, but not counting the WO that were already in previous days. And sum the LABOR column grouping by day also.

SAMPLE:

DAY   WO     LABOR
6   379157    3
9   379157    5
10  379404    8
10  379362    8
19  386118    10
24  386547    2
25  388711    8
25  386547    5
30  386547    1

RESULTS

DAY   WO    LABOR
6      1    3
9      0    5
10     2    16
19     1    10
24     1    2
25     1    13
30     0    1

Thanks a lot for your help

Body:
Here's a solution using row_number (since we only want to count the first instance of each wo across all days, per day):

WITH your_table AS (SELECT 6 DAY, 379157 wo, 3 labor FROM dual UNION ALL
                    SELECT 9 DAY, 379157 wo, 5 labor FROM dual UNION ALL
                    SELECT 10 DAY, 379404 wo, 8 labor FROM dual UNION ALL
                    SELECT 10 DAY, 379362 wo, 8 labor FROM dual UNION ALL
                    SELECT 19 DAY, 386118 wo, 10 labor FROM dual UNION ALL
                    SELECT 24 DAY, 386547 wo, 2 labor FROM dual UNION ALL
                    SELECT 25 DAY, 388711 wo, 8 labor FROM dual UNION ALL
                    SELECT 25 DAY, 386547 wo, 5 labor FROM dual UNION ALL
                    SELECT 30 DAY, 386547 wo, 1 labor FROM dual)
-- end of mimicking data in "your_table" - see the main SQL below:
SELECT DAY,
       SUM(CASE WHEN rn = 1 THEN 1 ELSE 0 END) wo,
       SUM(labor) labor
FROM   (SELECT DAY,
               wo,
               labor,
               row_number() OVER (PARTITION BY wo ORDER BY DAY) rn
        FROM   your_table)
GROUP BY DAY
ORDER BY DAY;

       DAY         WO      LABOR
---------- ---------- ----------
         6          1          3
         9          0          5
        10          2         16
        19          1         10
        24          1          2
        25          1         13
        30          0          1


问:
angular-cli router lazy loading
I am attempting to run a sample web app to learn how lazy loading with Angular modules works.  I generated the app via angular-cli 1.0.0-beta.24 which uses angular 2.4.1.  I generated the core app and then 3 components.  I then added routing at the app level and directly reference the first two components by importing the components into the app module.  For the third component I simply added the routing using the loadChildren method specified in the Angular routing docs. My routing configuration for the main app is as follows:

```<code>const appRoutes: Routes  = [
    { path: 'comp1', component: Comp1Component},
    { path: 'comp2', component: Comp2Component},
    { path: 'comp3', loadChildren: 'app/comp3/comp3.module'}
];

export default RouterModule.forRoot(appRoutes);
</code>```

I turned the code for the third component into a module and removed all imports from the app to the third component.  The routing config for the the module is as follows:

```<code>const routes: Routes = [
    {path: '', component:Comp3Component}
];

export default RouterModule.forChild(routes);
</code>```

When I run the app, the routes for Comp1 and Comp2 work fine, when I click the link for Comp3 (the module route), I get the following error logged to the console:

```<code>EXCEPTION: Uncaught (in promise): Error: Cannot find module ./comp3/comp3.module'.
Error: Cannot find module './comp3/comp3.module'.
    at webpackEmptyContext (http://localhost:4200/main.bundle.js:77:8) [angular]
</code>```

It seems that webpack is not handling the lazy loading.  I've tried all kinds of path variants of the "loadChildren" call including:

```<code>loadChildren: 'app/comp3/comp3.module#Comp3Module'
</code>```

with no change in behavior (still get the error above).  New to angular2 so may be something in my code, but I see others getting the same error.  My google/stackoverflow foo has not lead me to a solution.
I added my sample app to my Github account here.

I saw this issue logged by another developer with the Angular team but they kicked it as a support issue to StackOverflow because the sample worked on plunkr.  I'm sure there is a clue somewhere in there, but I don't really know enough about webpack and what it is doing to find the differences in the plunkr vs. ng serve run of the app.

Adding additional info.  The app's html template looks like this (also available on github repo):

```<code> <h1>
    {{title}}
 </h1>
 <ul>
    <li><a class="nav-link" routerLink="/comp1" routerLinkActive="active">Component 1</a></li>
    <li><a class="nav-link" routerLink="/comp2" routerLinkActive="active">Component 2</a></li>
    <li><a class="nav-link" routerLink="/comp3" routerLinkActive="active">Component 3</a></li>
  </ul>
  <p></p>
  <router-outlet></router-outlet>
</code>```

I copied my source tree for this app (from src/app on down) to the angular2 seed project, and with some minor expected tweeks, it runs fine there and continues to fail in the environment set up by angular-cli. The only change I made to my TS source is to use the relative pathing:

```<code>{ path: 'comp3', loadChildren: './comp3/comp3.module#Comp3Module'}
</code>```

for the loadChildren call.  I changed my Github example code to reflect this update, but it still fails under the angular-cli environment.

答:
Another way of using loadChildren routing as below:

In your app.route.ts use

```<code>// have to be export modules to handle the lazy loading routing
export function loadExampleModuleOne() {  return ExampleModuleOne }
export function loadExampleModuleTwo() { return ExampleModuleTwo }
</code>```

then after in your routing you need to use like :

```<code>const APP_ROUTE: Routes = [
  {
    path: '',
    redirectTo: 'example-one',
    pathMatch: 'full'
  },
  {
    path: 'example-one',
    loadChildren: loadExampleModuleOne
  },
  {
    path: 'example-two',
    loadChildren: loadExampleModuleTwo
  }
];

export const AppRouting = RouterModule.forRoot(APP_ROUTE);
</code>```

and then use the AppRouting constant in your app.module.ts like :

```<code>import {AppRouting} from './app.routing';

@NgModule({
   import: [
     AppRouting
   ]
})
export class AppModule() {
}
</code>```

Title: angular-cli router lazy loading

Body:
I am attempting to run a sample web app to learn how lazy loading with Angular modules works.  I generated the app via angular-cli 1.0.0-beta.24 which uses angular 2.4.1.  I generated the core app and then 3 components.  I then added routing at the app level and directly reference the first two components by importing the components into the app module.  For the third component I simply added the routing using the loadChildren method specified in the Angular routing docs. My routing configuration for the main app is as follows:

const appRoutes: Routes  = [
    { path: 'comp1', component: Comp1Component},
    { path: 'comp2', component: Comp2Component},
    { path: 'comp3', loadChildren: 'app/comp3/comp3.module'}
];

export default RouterModule.forRoot(appRoutes);

I turned the code for the third component into a module and removed all imports from the app to the third component.  The routing config for the the module is as follows:

const routes: Routes = [
    {path: '', component:Comp3Component}
];

export default RouterModule.forChild(routes);

When I run the app, the routes for Comp1 and Comp2 work fine, when I click the link for Comp3 (the module route), I get the following error logged to the console:

EXCEPTION: Uncaught (in promise): Error: Cannot find module ./comp3/comp3.module'.
Error: Cannot find module './comp3/comp3.module'.
    at webpackEmptyContext (http://localhost:4200/main.bundle.js:77:8) [angular]

It seems that webpack is not handling the lazy loading.  I've tried all kinds of path variants of the "loadChildren" call including:

loadChildren: 'app/comp3/comp3.module#Comp3Module'

with no change in behavior (still get the error above).  New to angular2 so may be something in my code, but I see others getting the same error.  My google/stackoverflow foo has not lead me to a solution.
I added my sample app to my Github account here.

I saw this issue logged by another developer with the Angular team but they kicked it as a support issue to StackOverflow because the sample worked on plunkr.  I'm sure there is a clue somewhere in there, but I don't really know enough about webpack and what it is doing to find the differences in the plunkr vs. ng serve run of the app.

Adding additional info.  The app's html template looks like this (also available on github repo):

    {{title}}

Component 1

Component 2

Component 3

  <router-outlet></router-outlet>

I copied my source tree for this app (from src/app on down) to the angular2 seed project, and with some minor expected tweeks, it runs fine there and continues to fail in the environment set up by angular-cli. The only change I made to my TS source is to use the relative pathing:

{ path: 'comp3', loadChildren: './comp3/comp3.module#Comp3Module'}

for the loadChildren call.  I changed my Github example code to reflect this update, but it still fails under the angular-cli environment.

Body:
Another way of using loadChildren routing as below:

In your app.route.ts use

// have to be export modules to handle the lazy loading routing
export function loadExampleModuleOne() {  return ExampleModuleOne }
export function loadExampleModuleTwo() { return ExampleModuleTwo }

then after in your routing you need to use like :

const APP_ROUTE: Routes = [
  {
    path: '',
    redirectTo: 'example-one',
    pathMatch: 'full'
  },
  {
    path: 'example-one',
    loadChildren: loadExampleModuleOne
  },
  {
    path: 'example-two',
    loadChildren: loadExampleModuleTwo
  }
];

export const AppRouting = RouterModule.forRoot(APP_ROUTE);

and then use the AppRouting constant in your app.module.ts like :

import {AppRouting} from './app.routing';

@NgModule({
   import: [
     AppRouting
   ]
})
export class AppModule() {
}


问:
How remove contents of layout
My script allovs drawing lines by mouse. I want to delete last line by butoon Clear.(And sometimes delete gradually all lines) On stack overflow i found construction "self.ids.layout.remove_widget(self.ids.test)" How I create "self.ids.test" dynamically?. How must I modify this constuction for my script?  Thank You.</p>

```<code>from random import random
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.uix.button import Button
from kivy.graphics import Color, Ellipse, Line

class MyPaintWidget(Widget):

    def on_touch_down(self, touch):
        color = (random(), 1, 1)
        with self.canvas:
            Color(*color, mode='hsv')
            touch.ud['line'] = Line(points=(touch.x, touch.y))

    def on_touch_move(self, touch):
        touch.ud['line'].points += [touch.x, touch.y]

class MyPaintApp(App):

    def build(self):
        parent = Widget()
        self.painter = MyPaintWidget()
        clearbtn = Button(text='Clear', pos=(50,50))
        clearbtn.bind(on_release=self.clear_canvas)

        parent.add_widget(self.painter)
        parent.add_widget(clearbtn)
        return parent

    def clear_canvas(self, obj):
        pass

if __name__ == '__main__':
    MyPaintApp().run()
</code>```

答:
When an instruction such as Line is added to canvas this is returned, then a possible solution is to store those instructions in a list, and then remove it through the remove() method of canvas:

```<code>class MyPaintWidget(Widget):
    def __init__(self, *args, **kwargs):
        Widget.__init__(self, *args, **kwargs)
        self.lines = []

    def on_touch_down(self, touch):
        color = (random(), 1, 1)
        with self.canvas:
            Color(*color, mode='hsv')
            l = Line(points=(touch.x, touch.y))
            touch.ud['line'] = l
            self.lines.append(l)

    def on_touch_move(self, touch):
        touch.ud['line'].points += [touch.x, touch.y]

class MyPaintApp(App):

    def build(self):
        parent = Widget()
        self.painter = MyPaintWidget()
        clearbtn = Button(text='Clear', pos=(50,50))
        clearbtn.bind(on_release=self.clear_canvas)
        parent.add_widget(self.painter)
        parent.add_widget(clearbtn)
        return parent

    def clear_canvas(self, obj):
        if len(self.painter.lines) != 0:
            self.painter.canvas.remove(self.painter.lines[-1])
            self.painter.lines = self.painter.lines[:-1]

if __name__ == '__main__':
    MyPaintApp().run()
</code>```

if you want to clean all the instructions you must use self.painter.canvas.clear()

Title: How remove contents of layout

Body:
My script allovs drawing lines by mouse. I want to delete last line by butoon Clear.(And sometimes delete gradually all lines) On stack overflow i found construction "self.ids.layout.remove_widget(self.ids.test)" How I create "self.ids.test" dynamically?. How must I modify this constuction for my script?  Thank You.

from random import random
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.uix.button import Button
from kivy.graphics import Color, Ellipse, Line

class MyPaintWidget(Widget):

    def on_touch_down(self, touch):
        color = (random(), 1, 1)
        with self.canvas:
            Color(*color, mode='hsv')
            touch.ud['line'] = Line(points=(touch.x, touch.y))

    def on_touch_move(self, touch):
        touch.ud['line'].points += [touch.x, touch.y]

class MyPaintApp(App):

    def build(self):
        parent = Widget()
        self.painter = MyPaintWidget()
        clearbtn = Button(text='Clear', pos=(50,50))
        clearbtn.bind(on_release=self.clear_canvas)

        parent.add_widget(self.painter)
        parent.add_widget(clearbtn)
        return parent

    def clear_canvas(self, obj):
        pass

if __name__ == '__main__':
    MyPaintApp().run()

Body:
When an instruction such as Line is added to canvas this is returned, then a possible solution is to store those instructions in a list, and then remove it through the remove() method of canvas:

class MyPaintWidget(Widget):
    def __init__(self, *args, **kwargs):
        Widget.__init__(self, *args, **kwargs)
        self.lines = []

    def on_touch_down(self, touch):
        color = (random(), 1, 1)
        with self.canvas:
            Color(*color, mode='hsv')
            l = Line(points=(touch.x, touch.y))
            touch.ud['line'] = l
            self.lines.append(l)

    def on_touch_move(self, touch):
        touch.ud['line'].points += [touch.x, touch.y]

class MyPaintApp(App):

    def build(self):
        parent = Widget()
        self.painter = MyPaintWidget()
        clearbtn = Button(text='Clear', pos=(50,50))
        clearbtn.bind(on_release=self.clear_canvas)
        parent.add_widget(self.painter)
        parent.add_widget(clearbtn)
        return parent

    def clear_canvas(self, obj):
        if len(self.painter.lines) != 0:
            self.painter.canvas.remove(self.painter.lines[-1])
            self.painter.lines = self.painter.lines[:-1]

if __name__ == '__main__':
    MyPaintApp().run()

if you want to clean all the instructions you must use self.painter.canvas.clear()


问:
How do I create a black and white theme with Angular Material Design?
I am looking to create a simple black and white theme for Angular Material Design. The documentation is sparse in this area.

My goal is to do this:

Unaccented background color is white

Unaccented text color is black

Accents, error, warning colors to be decided later

I was hoping to do something like this in a config block:

```<code>$mdThemingProvider.theme('default')
  .primaryPalette('black')
  .backgroundPalette('white');
</code>```

But, the white and black palettes do not exist.

Is there a simple way to do this?

答:
This code may help for using white and black colors in md-colors</p>

```<code><!DOCTYPE html>
    <html lang="en">
        <head>
            <meta name="viewport" content="width=device-width, initial-scale=1">
            <!-- Angular Material style sheet -->
            <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/angular_material/1.1.0/angular-material.min.css">
        </head>
        <body ng-app="BlankApp" ng-cloak md-colors="::{'background': 'grey-400'}">
            <!--Your HTML content here-->
            <div flex layout="row">
                <div flex layout="row" layout-padding md-colors="{'color':'white-50', 'background': 'black-500'}"
                layout-align="center center">White text and Black background</div>
                <div flex layout="row" layout-padding md-colors="{'color':'black-50', 'background': 'white-500'}"
                layout-align="center center">Black text and White background</div>
            </div>
            <!--Your HTML content here-->
            <!-- Angular Material requires Angular.js Libraries -->
            <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.min.js"></script>
            <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular-animate.min.js"></script>
            <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular-aria.min.js"></script>
            <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular-messages.min.js"></script>
            <!-- Angular Material Library -->
            <script src="https://ajax.googleapis.com/ajax/libs/angular_material/1.1.0/angular-material.min.js"></script>
            <!-- Your application bootstrap  -->
            <script>
                /**
                 * You must include the dependency on 'ngMaterial'
                 */
                var app = angular.module('BlankApp', ['ngMaterial']);
                app.config(function($mdThemingProvider) {
                    $mdThemingProvider.definePalette('black', {
                    '50': '000000',
                    '100': '000000',
                    '200': '000000',
                    '300': '000000',
                    '400': '000000',
                    '500': '000000',
                    '600': '000000',
                    '700': '000000',
                    '800': '000000',
                    '900': '000000',
                    'A100': '000000',
                    'A200': '000000',
                    'A400': '000000',
                    'A700': '000000',
                    'contrastDefaultColor': 'light'
                    });
                    $mdThemingProvider.definePalette('white', {
                    '50': 'ffffff',
                    '100': 'ffffff',
                    '200': 'ffffff',
                    '300': 'ffffff',
                    '400': 'ffffff',
                    '500': 'ffffff',
                    '600': 'ffffff',
                    '700': 'ffffff',
                    '800': 'ffffff',
                    '900': 'ffffff',
                    'A100': 'ffffff',
                    'A200': 'ffffff',
                    'A400': 'ffffff',
                    'A700': 'ffffff',
                    'contrastDefaultColor': 'dark'
                    });

                    $mdThemingProvider.theme('default')
                    .primaryPalette('black')
                    .backgroundPalette('white');
                });
            </script>
        </body>
    </html>
</code>```

Body:
I am looking to create a simple black and white theme for Angular Material Design. The documentation is sparse in this area.

My goal is to do this:

Unaccented background color is white

Unaccented text color is black

Accents, error, warning colors to be decided later

I was hoping to do something like this in a config block:

$mdThemingProvider.theme('default')
  .primaryPalette('black')
  .backgroundPalette('white');

But, the white and black palettes do not exist.

Is there a simple way to do this?

Body:
This code may help for using white and black colors in md-colors

<!DOCTYPE html>
    <html lang="en">
        <head>
            <meta name="viewport" content="width=device-width, initial-scale=1">
            <!-- Angular Material style sheet -->
            <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/angular_material/1.1.0/angular-material.min.css">
        </head>
        <body ng-app="BlankApp" ng-cloak md-colors="::{'background': 'grey-400'}">
            <!--Your HTML content here-->
            <div flex layout="row">
                <div flex layout="row" layout-padding md-colors="{'color':'white-50', 'background': 'black-500'}"
                layout-align="center center">White text and Black background</div>
                <div flex layout="row" layout-padding md-colors="{'color':'black-50', 'background': 'white-500'}"
                layout-align="center center">Black text and White background</div>
            </div>
            <!--Your HTML content here-->
            <!-- Angular Material requires Angular.js Libraries -->
            <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.min.js"></script>
            <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular-animate.min.js"></script>
            <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular-aria.min.js"></script>
            <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular-messages.min.js"></script>
            <!-- Angular Material Library -->
            <script src="https://ajax.googleapis.com/ajax/libs/angular_material/1.1.0/angular-material.min.js"></script>
            <!-- Your application bootstrap  -->
            <script>
                /**
                 * You must include the dependency on 'ngMaterial'
                 */
                var app = angular.module('BlankApp', ['ngMaterial']);
                app.config(function($mdThemingProvider) {
                    $mdThemingProvider.definePalette('black', {
                    '50': '000000',
                    '100': '000000',
                    '200': '000000',
                    '300': '000000',
                    '400': '000000',
                    '500': '000000',
                    '600': '000000',
                    '700': '000000',
                    '800': '000000',
                    '900': '000000',
                    'A100': '000000',
                    'A200': '000000',
                    'A400': '000000',
                    'A700': '000000',
                    'contrastDefaultColor': 'light'
                    });
                    $mdThemingProvider.definePalette('white', {
                    '50': 'ffffff',
                    '100': 'ffffff',
                    '200': 'ffffff',
                    '300': 'ffffff',
                    '400': 'ffffff',
                    '500': 'ffffff',
                    '600': 'ffffff',
                    '700': 'ffffff',
                    '800': 'ffffff',
                    '900': 'ffffff',
                    'A100': 'ffffff',
                    'A200': 'ffffff',
                    'A400': 'ffffff',
                    'A700': 'ffffff',
                    'contrastDefaultColor': 'dark'
                    });

                    $mdThemingProvider.theme('default')
                    .primaryPalette('black')
                    .backgroundPalette('white');
                });
            </script>
        </body>
    </html>


问:
Authorize over WebSocket connection to remote kubernetes api-server
See the connected question - Kubernetes pod exec API exception: Response must not include 'Sec-WebSocket-Protocol' header if not present in request.

I have been able to successfully make a WebSocket connection using Pod exec API. But I am using kubectl proxy on localhost to handle the authorization on behalf of the terminal client.

The next step is to be able to authorize the request directly to the kubernetes API server, so that there's no need to route the traffic via kubectl proxy. Here's a discussion in the python community where they have been able to send Authorization token to the api-server. But I haven't had any success with this in nodejs. I must admit that I am not familiar with python as well to understand the discussion enough.

Can someone from the kubernetes team point me in the right direction?

Thanks

答:
For future wanderers....

Although the exec API supports Authorization header, the browser WebSocket API doesn't support it yet. So the solution for us was to reverse-proxy it from our server APIs.

It went like this...

client browser -wss-> GKE LB (SSL Termination) -ws-> site API (nodejs) -WSS & Authorization-> kube api-server exec API

So to answer my own question, per my tests, the GKE kubernetes supports Authorization only in headers, so you need to reverse proxy if you want to connect to it via browser. Per this code, some Kubernetes setups allow tokens in the query string, but I didn't have any success with GKE. If you are using a different cluster host, YMMY. I welcome comments from kubernetes team on my observations.

If you came here only for an authorization issue, you may stop reading further.

There are still more challenges to overcome though, and there's good news and bad news... the good news first:

GKE Loadbalancer automatically handles SSL termination even for WebSockets, so you can proxy to either WS or WSS without any issues.

And then the bad news:

GKE Loadbalancer force terminates ALL connections within 30 seconds, even if they are in use! There are workarounds, but they either don't stay put, require you to deploy your own controller, or you need to use Ingress. What this means for a Terminal sessions is that Chrome will close the client with a 1006 code, even if a command is running at that time.

For some WS scenarios, it may be acceptable to simply reconnect on a 1006 close, but for a terminal session, this is a deal-breaker as you cannot reconnect to the previous terminal instance and must begin with a new one.

For now we have resorted to increasing the timeout of the GKE Loadbalancer. But eventually we are planning to deploy our own Loadbalancer which can handle this better. Ingress has some issues which we don't want to live with at the moment.


问:
Taking Screenshot using Selenium 3.6 - Java - Webdriver
I'm not able to take a screenshot in my project.  I'm using Selenium 3.6 version with Java. Here is my code:

```<code>File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile, new File("c:\\tmp\\screenshot.png"));
</code>```

Unfortunately the "copyFile" gives the following error:

```<code>The method copyFile(File, File) is undefined for the type FileUtils
</code>```

I have also imported all the required packages.

Can anyone help me to take screenshot?

答:
Import Use import org.apache.commons.io.FileUtils. This imports the FileUtils class you need.

Guess you import wrong package

check these package should be there

```<code>import org.apache.commons.io.FileUtils;

import org.openqa.selenium.OutputType;

import org.openqa.selenium.TakesScreenshot;
</code>```

Sample code:

```<code>public class Takenscreensshot {
    public static void main(String[] args) throws IOException {
        WebDriver driver=new FirefoxDriver();
        driver.get("https://www.google.co.in");
        File src=((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
        FileUtils.copyFile(src, new File("d:/ss.png"));
        driver.close();
    }
}
</code>```

Body:
I'm not able to take a screenshot in my project.  I'm using Selenium 3.6 version with Java. Here is my code:

File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile, new File("c:\\tmp\\screenshot.png"));

Unfortunately the "copyFile" gives the following error:

The method copyFile(File, File) is undefined for the type FileUtils

I have also imported all the required packages.

Can anyone help me to take screenshot?

Body:
Import Use import org.apache.commons.io.FileUtils. This imports the FileUtils class you need.

Guess you import wrong package

check these package should be there

import org.apache.commons.io.FileUtils;

import org.openqa.selenium.OutputType;

import org.openqa.selenium.TakesScreenshot;

Sample code:

public class Takenscreensshot {
    public static void main(String[] args) throws IOException {
        WebDriver driver=new FirefoxDriver();
        driver.get("https://www.google.co.in");
        File src=((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
        FileUtils.copyFile(src, new File("d:/ss.png"));
        driver.close();
    }
}


问:
Jquery loop table from n to n row
I have a table as below:

    Group 1

     Group 1 item 1

     Group 1 item 2

     Group 1 item 3

     group 2

     group 2 item 1

     group 3

     group 4

     group 5

     group 5 item 1

     group 5 item 2

```

Whenever I click on any row  I add a class to each row (e.g. selection). If I click on any row which has a class called group then I want to add/remove a class to all other rows (if any) in that group

e.g. If I click on first row which has class called group then I should add another class to row 2,3 and 4 and they belong to row 1 (group 1).

so loop in the rows from current row until group class is found again (e.g. row 5)

can I loop through table from n to n row?

答:
You could  use nextUntil() method to select the next elements until you reach the next tr.group

see here > nextUntil()

You also need to get the groupIndex so you can add class accordingly to the selected tr

And of course add/remove the selection and group1,2,3,4,5 classes when clicking on other elements. I added some colors ( you can see them in css ) for example purposes

$("tr").click(function() {
  var groupIndex = $(this).closest('table').find('.group').index(this) + 1
  $(".selection").removeClass("selection")

  $(this).addClass("selection") //for example
  if ($(this).hasClass("group")) {
    $(this).siblings().not(".group").removeClass()
    $(this).nextUntil(".group").addClass("group" + groupIndex + "")
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.group1 {
  color: red;
}

.group2 {
  color: blue;
}

.group5 {
  color: yellow;
}

.selection {
  color: green
}</code>```

    Group 1

     Group 1 item 1

     Group 1 item 2

     Group 1 item 3

     group 2

     group 2 item 1

     group 3

     group 4

     group 5

     group 5 item 1

     group 5 item 2

```

Title: Jquery loop table from n to n row

Body:
I have a table as below:

    Group 1

     Group 1 item 1

     Group 1 item 2

     Group 1 item 3

     group 2

     group 2 item 1

     group 3

     group 4

     group 5

     group 5 item 1

     group 5 item 2

Whenever I click on any row  I add a class to each row (e.g. selection). If I click on any row which has a class called group then I want to add/remove a class to all other rows (if any) in that group

e.g. If I click on first row which has class called group then I should add another class to row 2,3 and 4 and they belong to row 1 (group 1).

so loop in the rows from current row until group class is found again (e.g. row 5)

can I loop through table from n to n row?

Body:
You could  use nextUntil() method to select the next elements until you reach the next tr.group

see here > nextUntil()

You also need to get the groupIndex so you can add class accordingly to the selected tr

And of course add/remove the selection and group1,2,3,4,5 classes when clicking on other elements. I added some colors ( you can see them in css ) for example purposes

$("tr").click(function() {
  var groupIndex = $(this).closest('table').find('.group').index(this) + 1
  $(".selection").removeClass("selection")

  $(this).addClass("selection") //for example
  if ($(this).hasClass("group")) {
    $(this).siblings().not(".group").removeClass()
    $(this).nextUntil(".group").addClass("group" + groupIndex + "")
  }
});

.group1 {
  color: red;
}

.group2 {
  color: blue;
}

.group5 {
  color: yellow;
}

.selection {
  color: green
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr class='group'>
    <td>Group 1 </td>
  </tr>
  <tr>
    <td> Group 1 item 1</td>
  </tr>
  <tr>
    <td> Group 1 item 2</td>
  </tr>
  <tr>
    <td> Group 1 item 3</td>
  </tr>
  <tr class='group'>
    <td> group 2</td>
  </tr>
  <tr>
    <td> group 2 item 1</td>
  </tr>
  <tr class='group'>
    <td> group 3</td>
  </tr>
  <tr class='group'>
    <td> group 4</td>
  </tr>
  <tr class='group'>
    <td> group 5</td>
  </tr>
  <tr>
    <td> group 5 item 1</td>
  </tr>
  <tr>
    <td> group 5 item 2</td>
  </tr>
</table>


问:
how to iterate a List that contains Map and get the key and value of that map
I have a list that contains a map on class type. I want to iterate that list and get the key and values of the inner map.

Here is the List :

```<code>quotationList =  quotationService.searchByIdList(accountId, Account.class);
</code>```

It contains one index i.e at 0 index it contains a map. i need to get the key and values of that map.

My attempt:

```<code>for (int i = 0; i < quotationList.size(); i++) {
            Map myMap = (Map) quotationList.get(i);
            System.out.println("Data For Map" + i);
            for (Entry<String, Object> entrySet : ((Map<String, Object>) myMap).entrySet()) {
                System.out.println("Key = " + entrySet.getKey() + " , Value = " + entrySet.getValue());
            }
        }
</code>```

答:
To get the first item in the list:

```<code>Map<MyKey, MyValue> myMap = quotationList.get(0);
</code>```

To get the values of the map:

```<code>myMap.entrySet();
</code>```

Next step would be to loop that entrySet:

```<code>    for (Entry<MyKey, MyValue> entry : myMap.entrySet()) {
        MyKey key = entry.getKey();
        MyValue value = entry.getValue();
    }
</code>```

Body:
I have a list that contains a map on class type. I want to iterate that list and get the key and values of the inner map.

Here is the List :

quotationList =  quotationService.searchByIdList(accountId, Account.class);

It contains one index i.e at 0 index it contains a map. i need to get the key and values of that map.

My attempt:

for (int i = 0; i < quotationList.size(); i++) {
            Map myMap = (Map) quotationList.get(i);
            System.out.println("Data For Map" + i);
            for (Entry<String, Object> entrySet : ((Map<String, Object>) myMap).entrySet()) {
                System.out.println("Key = " + entrySet.getKey() + " , Value = " + entrySet.getValue());
            }
        }

Body:
To get the first item in the list:

Map<MyKey, MyValue> myMap = quotationList.get(0);

To get the values of the map:

myMap.entrySet();

Next step would be to loop that entrySet:

    for (Entry<MyKey, MyValue> entry : myMap.entrySet()) {
        MyKey key = entry.getKey();
        MyValue value = entry.getValue();
    }


问:
Keras model taking forerver to train with dask dataframe
I m working with large dataset having low memory and I got introduced to Dask dataframe. What I understood from the docs that Dask does not load whole dataset into memory . instead it created multiple threads which will fetch the records from disk on demand basis. So I suppose keras model with having batch size = 500, it should only have 500 records in the memory at the training time. but when I start training. it takes forever.May be I am doing something wrong.please suggest.

shape of training data: 1000000 * 1290

```<code>import glob
import dask.dataframe
paths_train = glob.glob(r'x_train_d_final*.csv')

X_train_d = dd.read_csv('.../x_train_d_final0.csv')
Y_train1 = keras.utils.to_categorical(Y_train.iloc[,1], num_classes)
batch_size = 500
num_classes = 2
epochs = 5

model = Sequential()
model.add(Dense(645, activation='sigmoid', input_shape=(1290,),kernel_initializer='glorot_normal'))
#model.add(Dense(20, activation='sigmoid',kernel_initializer='glorot_normal'))
model.add(Dense(num_classes, activation='sigmoid'))

model.compile(loss='binary_crossentropy',
          optimizer=Adam(decay=0),
          metrics=['accuracy'])

history = model.fit(X_train_d.to_records(), Y_train,
                batch_size=batch_size,
                epochs=epochs,
                verbose=1,
                class_weight = {0:1,1:6.5},
                shuffle=False)
</code>```

答:
You should use fit_generator() from Sequential model with generator or with a Sequence instance. Both provide a proper way to load only a portion of data.

Keras docs provide an excellent example:

```<code>def generate_arrays_from_file(path):
    while 1:
        f = open(path)
        for line in f:
            # create Numpy arrays of input data
            # and labels, from each line in the file
            x, y = process_line(line)
            yield (x, y)
        f.close()

model.fit_generator(generate_arrays_from_file('/my_file.txt'),
                    steps_per_epoch=1000, epochs=10)
</code>```

Body:
I m working with large dataset having low memory and I got introduced to Dask dataframe. What I understood from the docs that Dask does not load whole dataset into memory . instead it created multiple threads which will fetch the records from disk on demand basis. So I suppose keras model with having batch size = 500, it should only have 500 records in the memory at the training time. but when I start training. it takes forever.May be I am doing something wrong.please suggest.

shape of training data: 1000000 * 1290

import glob
import dask.dataframe
paths_train = glob.glob(r'x_train_d_final*.csv')

X_train_d = dd.read_csv('.../x_train_d_final0.csv')
Y_train1 = keras.utils.to_categorical(Y_train.iloc[,1], num_classes)
batch_size = 500
num_classes = 2
epochs = 5

model = Sequential()
model.add(Dense(645, activation='sigmoid', input_shape=(1290,),kernel_initializer='glorot_normal'))
#model.add(Dense(20, activation='sigmoid',kernel_initializer='glorot_normal'))
model.add(Dense(num_classes, activation='sigmoid'))

model.compile(loss='binary_crossentropy',
          optimizer=Adam(decay=0),
          metrics=['accuracy'])

history = model.fit(X_train_d.to_records(), Y_train,
                batch_size=batch_size,
                epochs=epochs,
                verbose=1,
                class_weight = {0:1,1:6.5},
                shuffle=False)

Body:
You should use fit_generator() from Sequential model with generator or with a Sequence instance. Both provide a proper way to load only a portion of data.

Keras docs provide an excellent example:

def generate_arrays_from_file(path):
    while 1:
        f = open(path)
        for line in f:
            # create Numpy arrays of input data
            # and labels, from each line in the file
            x, y = process_line(line)
            yield (x, y)
        f.close()

model.fit_generator(generate_arrays_from_file('/my_file.txt'),
                    steps_per_epoch=1000, epochs=10)


问:
Find element with rel attribute and change text
I have a pagination for browsing older posts. I need to change it's text using jquery or js. (pagination generated in laravel package so can't edit text directly)

So I tried with finding rel and replace text. But no luck. This is my code.

$(".older-posts").find("li[rel='next']").html("Older posts");```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="older-posts">
  <ul class="pagination">
    <li>
      « Previous
    </li>
    <li class="disabled"><span>Next »</span></li>
  </ul>
</div></code>```

Any idea?

Body:
I have a pagination for browsing older posts. I need to change it's text using jquery or js. (pagination generated in laravel package so can't edit text directly)

So I tried with finding rel and replace text. But no luck. This is my code.

$(".older-posts").find("li[rel='next']").html("Older posts");

      « Previous

Next »

Any idea?

Body: $('[rel="prev"]').text('your text here')


问:
Core Data - Memory Management?
```<code>[myArray addObject:myObject];
[object release];
</code>```

In obvjective c every time you add an object with retain count of 1 to an array, you must release it right after to prevent a leak.

Does this apply to NSManagedObjects ?
Because in the code above if myObject is an instance of NSManagedObject I get "EXC_BAD_ACCESS"

答:
Please read the Memory Management Programming Guide. It will answer this question and any memory management questions you have in the future.

To directly answer this question: You must release or autorelease objects that you own. You must not release or autorelease objects you do not own. You own an object when you call retain on it or obtain the object using alloc/new/copy.

There is certainly no blanket rule about releasing an object when you add it to an array.

Title: Core Data - Memory Management?

Body:
[myArray addObject:myObject];
[object release];

In obvjective c every time you add an object with retain count of 1 to an array, you must release it right after to prevent a leak.

Does this apply to NSManagedObjects ?
Because in the code above if myObject is an instance of NSManagedObject I get "EXC_BAD_ACCESS"


问:
DotNetBrowser override window.navigator
I got the following code

```<code>using DotNetBrowser;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Browsium
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private Browser browser;
        private DotNetBrowser.WinForms.WinFormsBrowserView bview;
        private void Form1_Load(object sender, EventArgs e)
        {
            browser = BrowserFactory.Create(BrowserContext.DefaultContext,BrowserType.HEAVYWEIGHT);
            browser.ScriptContextCreated += Browser_ScriptContextCreated;
            bview = new DotNetBrowser.WinForms.WinFormsBrowserView(browser);
            this.Controls.Add(bview);
            browser.LoadURL("https://whoer.net/#extended");
        }

        private void Browser_ScriptContextCreated(object sender, DotNetBrowser.Events.ScriptContextEventArgs e)
        {
            // demo
            browser.ExecuteJavaScriptAndReturnValue(e.Context.FrameId, System.IO.File.ReadAllText("test.js"));
        }
    }
}
</code>```

test.js file contains

```<code>window = new function() {
    this.innerWidth = 240,
    this.innerHeight = 182
};

window.screen = new function() {
    this.availHeight = 320,
    this.availLeft = 0,
    this.availTop = 0,
    this.availWidth = 240,
    this.clientHeight = 320,
    this.clientWidth = 240,
    this.colorDepth = 24,
    this.height = 320,
    this.left = 0,
    this.offsetHeight = 320,
    this.offsetWidth = 240,
    this.pixelDepth = 24,
    this.top = 0,
    this.width = 240,
    this.orientation = "landscape-primary",
    this.mozEnabled = true
};

window.navigator = new function() {
    this.userAgent = "Mozilla/5.0 (Windows NT 10.0) AppleWebKit/537.70 (KHTML, like Gecko) Chrome/46.0.2490.80 Safari/537.70",
    this.appCodeName = "Mozilla",
    this.appName = "Netscape",
    this.appVersion = "5.0 (Windows NT 10.0) AppleWebKit/537.70 (KHTML, like Gecko) Chrome/46.0.2490.80 Safari/537.70",
    this.language = "en",
    this.languages = "en",
    this.platform = "x86",
    this.oscpu = "x86",
    this.hardwareConcurrency = "8",
    this.vendor = "Test Inc.",
    this.vendorSub = "",
    this.buildID = "",
    this.product = "Chrome",
    this.productSub = "20030107"
};
</code>```

The window and the window.screen are working , but I can't manage to override window.navigator.
I have found window.navigator object on mozilla dev. but for some strange reason , my solution does not work.
What I try to do , is to modify window.navigator properties and to add plugins.
Any ideas on how to do that ?

答:
The 'window.navigator' property is read-only, so you cannot update its value. However, if you need to change the user-agent string in DotNetBrowser, you can do this using the following approach:

Browser browser = BrowserFactory.Create();
 browser.UserAgent = "Modified User Agent String";

You can find information related to the user-agent string in the following article: https://dotnetbrowser.support.teamdev.com/support/solutions/articles/9000110164-user-agent

Title: DotNetBrowser override window.navigator

Body:
I got the following code

using DotNetBrowser;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Browsium
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private Browser browser;
        private DotNetBrowser.WinForms.WinFormsBrowserView bview;
        private void Form1_Load(object sender, EventArgs e)
        {
            browser = BrowserFactory.Create(BrowserContext.DefaultContext,BrowserType.HEAVYWEIGHT);
            browser.ScriptContextCreated += Browser_ScriptContextCreated;
            bview = new DotNetBrowser.WinForms.WinFormsBrowserView(browser);
            this.Controls.Add(bview);
            browser.LoadURL("https://whoer.net/#extended");
        }

        private void Browser_ScriptContextCreated(object sender, DotNetBrowser.Events.ScriptContextEventArgs e)
        {
            // demo
            browser.ExecuteJavaScriptAndReturnValue(e.Context.FrameId, System.IO.File.ReadAllText("test.js"));
        }
    }
}

test.js file contains

window = new function() {
    this.innerWidth = 240,
    this.innerHeight = 182
};

window.screen = new function() {
    this.availHeight = 320,
    this.availLeft = 0,
    this.availTop = 0,
    this.availWidth = 240,
    this.clientHeight = 320,
    this.clientWidth = 240,
    this.colorDepth = 24,
    this.height = 320,
    this.left = 0,
    this.offsetHeight = 320,
    this.offsetWidth = 240,
    this.pixelDepth = 24,
    this.top = 0,
    this.width = 240,
    this.orientation = "landscape-primary",
    this.mozEnabled = true
};

window.navigator = new function() {
    this.userAgent = "Mozilla/5.0 (Windows NT 10.0) AppleWebKit/537.70 (KHTML, like Gecko) Chrome/46.0.2490.80 Safari/537.70",
    this.appCodeName = "Mozilla",
    this.appName = "Netscape",
    this.appVersion = "5.0 (Windows NT 10.0) AppleWebKit/537.70 (KHTML, like Gecko) Chrome/46.0.2490.80 Safari/537.70",
    this.language = "en",
    this.languages = "en",
    this.platform = "x86",
    this.oscpu = "x86",
    this.hardwareConcurrency = "8",
    this.vendor = "Test Inc.",
    this.vendorSub = "",
    this.buildID = "",
    this.product = "Chrome",
    this.productSub = "20030107"
};

The window and the window.screen are working , but I can't manage to override window.navigator.
I have found window.navigator object on mozilla dev. but for some strange reason , my solution does not work.
What I try to do , is to modify window.navigator properties and to add plugins.
Any ideas on how to do that ?


问:
Change text color from canvas with Select option
I have a canvas and I can introduce text into it. I'm trying to change the color of that text from canvas using Select object but I failed. Can someone help me with this one? This is the code and thank you for your time.

Here is JS for text introduction into the canvas:

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

   var canvas=document.getElementById("canvas");
   var ctx=canvas.getContext("2d");

   ctx.font= "bold 90px Arial";
   ctx.textAlign="center";

   var $text1=document.getElementById("sourceText1");

   $text1.onkeyup=function(e){ redrawTexts(); }

   function redrawTexts(){
       ctx.clearRect(0,0,canvas.width,canvas.height);
       wrapText(ctx,$text1.value,66.5, 82,"Arial");

   }

   function wrapText(context, text, x, y, maxWidth, fontSize, fontFace){
      var words = text.split(' ');
      var line = '';
      var lineHeight=fontSize;

      context.font=fontSize+" "+fontFace;

      for(var n = 0; n < words.length; n++) {
          var testLine = line + words[n] + ' ';
          var metrics = context.measureText(testLine);
          var testWidth = metrics.width;
          if(testWidth > maxWidth) {
             context.fillText(line, x, y);
             line = words[n] + ' ';
             y += lineHeight;
          }
          else {
             line = testLine;
          }
      }
      context.fillText(line, x, y);
      return(y);
   }

 }); // end $(function(){});
</code>```

And here is JS for changing the color:

```<code>  var main8 = document.getElementById("canvas");
  var render8 = main8.getContext("2d");

  function color(v8) {
    switch(v8) {
     // top: 103px; left: 210px
        case "green":
            main8.fillStyle = 'green';
            break;

        case "red":
            main8.fillStyle = "#ff3300";
            break;
            }
  }
</code>```

Here is HTML:

```<code> <input id="sourceText1" type="text" style="height: 32px;width: 223px;">

 <select name="colours" onchange="color(this.value)">
        <option value="blue">Blue</option>
        <option value="black">Black</option>
        <option value="red">Red</option>
        <option value="yellow">Yellow</option>
        <option value="green">Green</option>
 </select>
</code>```

Here is the CSS:

```<code>  #canvas{border:2px dotted transparent;
  border-radius: 5px;
   }
</code>```

答:
You are setting fillStyle on main8, which is the canvas element.

The property should be set on the canvas context, i.e. main8.getContext("2d").

Moreover you should also redraw the text via your redrawTexts function.

```<code>function color(v8) {
  switch(v8) {
   // top: 103px; left: 210px
      case "green":
          main8.getContext("2d").fillStyle = 'green';
          break;

      case "red":
          main8.getContext("2d").fillStyle = "#ff3300";
          break;
  }
  redrawTexts();
}
</code>```

Try it out:

  var canvas=document.getElementById("canvas");
  var ctx=canvas.getContext("2d");

  ctx.font= "bold 90px Arial";
  ctx.textAlign="center";

  var $text1=document.getElementById("sourceText1");

  $text1.onkeyup=function(e){ redrawTexts(); }

  function redrawTexts(){
      ctx.clearRect(0,0,canvas.width,canvas.height);
      wrapText(ctx,$text1.value,66.5, 82,"Arial");

  }

  function wrapText(context, text, x, y, maxWidth, fontSize, fontFace){
     var words = text.split(' ');
     var line = '';
     var lineHeight=fontSize;

     context.font=fontSize+" "+fontFace;

     for(var n = 0; n < words.length; n++) {
         var testLine = line + words[n] + ' ';
         var metrics = context.measureText(testLine);
         var testWidth = metrics.width;
         if(testWidth > maxWidth) {
            context.fillText(line, x, y);
            line = words[n] + ' ';
            y += lineHeight;
         }
         else {
            line = testLine;
         }
     }
     context.fillText(line, x, y);
     return(y);
  }

  var main8 = document.getElementById("canvas");
  var render8 = main8.getContext("2d");

  function color(v8) {
    switch(v8) {
     // top: 103px; left: 210px
        case "green":
            main8.getContext("2d").fillStyle = 'green';
            break;

        case "red":
            main8.getContext("2d").fillStyle = "#ff3300";
            break;
    }
    redrawTexts();
  }```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#canvas{border:2px dotted transparent;
  border-radius: 5px;
  display: block;
 }</code>```

<input id="sourceText1" type="text" style="height: 32px;width: 223px;">

 <select name="colours" onchange="color(this.value)">
        <option value="blue">Blue</option>
        <option value="black">Black</option>
        <option value="red">Red</option>
        <option value="yellow">Yellow</option>
        <option value="green">Green</option>
 </select>

<canvas id="canvas" width="300" height="300"></canvas>```

Body:
I have a canvas and I can introduce text into it. I'm trying to change the color of that text from canvas using Select object but I failed. Can someone help me with this one? This is the code and thank you for your time.

Here is JS for text introduction into the canvas:

$(function(){

   var canvas=document.getElementById("canvas");
   var ctx=canvas.getContext("2d");

   ctx.font= "bold 90px Arial";
   ctx.textAlign="center";

   var $text1=document.getElementById("sourceText1");

   $text1.onkeyup=function(e){ redrawTexts(); }

   function redrawTexts(){
       ctx.clearRect(0,0,canvas.width,canvas.height);
       wrapText(ctx,$text1.value,66.5, 82,"Arial");

   }

   function wrapText(context, text, x, y, maxWidth, fontSize, fontFace){
      var words = text.split(' ');
      var line = '';
      var lineHeight=fontSize;

      context.font=fontSize+" "+fontFace;

      for(var n = 0; n < words.length; n++) {
          var testLine = line + words[n] + ' ';
          var metrics = context.measureText(testLine);
          var testWidth = metrics.width;
          if(testWidth > maxWidth) {
             context.fillText(line, x, y);
             line = words[n] + ' ';
             y += lineHeight;
          }
          else {
             line = testLine;
          }
      }
      context.fillText(line, x, y);
      return(y);
   }

 }); // end $(function(){});

And here is JS for changing the color:

  var main8 = document.getElementById("canvas");
  var render8 = main8.getContext("2d");

  function color(v8) {
    switch(v8) {
     // top: 103px; left: 210px
        case "green":
            main8.fillStyle = 'green';
            break;

        case "red":
            main8.fillStyle = "#ff3300";
            break;
            }
  }

Here is HTML:

 <input id="sourceText1" type="text" style="height: 32px;width: 223px;">

 <select name="colours" onchange="color(this.value)">
        <option value="blue">Blue</option>
        <option value="black">Black</option>
        <option value="red">Red</option>
        <option value="yellow">Yellow</option>
        <option value="green">Green</option>
 </select>

Here is the CSS:

  #canvas{border:2px dotted transparent;
  border-radius: 5px;
   }

Body:
You are setting fillStyle on main8, which is the canvas element.

The property should be set on the canvas context, i.e. main8.getContext("2d").

Moreover you should also redraw the text via your redrawTexts function.

function color(v8) {
  switch(v8) {
   // top: 103px; left: 210px
      case "green":
          main8.getContext("2d").fillStyle = 'green';
          break;

      case "red":
          main8.getContext("2d").fillStyle = "#ff3300";
          break;
  }
  redrawTexts();
}

Try it out:

  var canvas=document.getElementById("canvas");
  var ctx=canvas.getContext("2d");

  ctx.font= "bold 90px Arial";
  ctx.textAlign="center";

  var $text1=document.getElementById("sourceText1");

  $text1.onkeyup=function(e){ redrawTexts(); }

  function redrawTexts(){
      ctx.clearRect(0,0,canvas.width,canvas.height);
      wrapText(ctx,$text1.value,66.5, 82,"Arial");

  }

  function wrapText(context, text, x, y, maxWidth, fontSize, fontFace){
     var words = text.split(' ');
     var line = '';
     var lineHeight=fontSize;

     context.font=fontSize+" "+fontFace;

     for(var n = 0; n < words.length; n++) {
         var testLine = line + words[n] + ' ';
         var metrics = context.measureText(testLine);
         var testWidth = metrics.width;
         if(testWidth > maxWidth) {
            context.fillText(line, x, y);
            line = words[n] + ' ';
            y += lineHeight;
         }
         else {
            line = testLine;
         }
     }
     context.fillText(line, x, y);
     return(y);
  }

  var main8 = document.getElementById("canvas");
  var render8 = main8.getContext("2d");

  function color(v8) {
    switch(v8) {
     // top: 103px; left: 210px
        case "green":
            main8.getContext("2d").fillStyle = 'green';
            break;

        case "red":
            main8.getContext("2d").fillStyle = "#ff3300";
            break;
    }
    redrawTexts();
  }

#canvas{border:2px dotted transparent;
  border-radius: 5px;
  display: block;
 }

<input id="sourceText1" type="text" style="height: 32px;width: 223px;">

 <select name="colours" onchange="color(this.value)">
        <option value="blue">Blue</option>
        <option value="black">Black</option>
        <option value="red">Red</option>
        <option value="yellow">Yellow</option>
        <option value="green">Green</option>
 </select>

<canvas id="canvas" width="300" height="300"></canvas>


问:
Encrypting App.config / Web.config file
I am abusing the Web.config file as the config file of some windows service exe files, because the service mostly needs the same settings as the IIS:

```<code>Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory);

if (File.Exists("..\\Web.config"))
{
    var path = Path.GetFullPath("..\\Web.config");
    logger.Info("Web.config gefunden in {0}", path);
    AppConfig.Change(path);
}
</code>```

Someone else has tried to encrypt parts of the Web.config file:

```<code>aspnet_regiis -pe connectionStrings -app /ourapp
</code>```

Renaming an original App.config to Web.config and back seems to be Microsoft's recommended way of encrypting an App.config file:

https://weblogs.asp.net/jongalloway/encrypting-passwords-in-a-net-app-config-file

However, the windows services won't start:

Anwendung: MyService.exe

  Frameworkversion: v4.0.30319

  Beschreibung: Der Prozess wurde aufgrund einer unbehandelten Ausnahme beendet.

  Ausnahmeinformationen: System.Configuration.ConfigurationErrorsException

```<code>bei System.Configuration.RsaProtectedConfigurationProvider.ThrowBetterException(Boolean)
bei System.Configuration.RsaProtectedConfigurationProvider.GetCryptoServiceProvider(Boolean, Boolean)
bei System.Configuration.RsaProtectedConfigurationProvider.Decrypt(System.Xml.XmlNode)
bei System.Configuration.ProtectedConfigurationSection.DecryptSection(System.String, System.Configuration.ProtectedConfigurationProvider)
bei System.Configuration.Internal.InternalConfigHost.System.Configuration.Internal.IInternalConfigHost.DecryptSection(System.String, System.Configuration.ProtectedConfigurationProvider, System.Configuration.ProtectedConfigurationSection)
bei System.Configuration.Internal.DelegatingConfigHost.DecryptSection(System.String, System.Configuration.ProtectedConfigurationProvider, System.Configuration.ProtectedConfigurationSection)
bei System.Configuration.BaseConfigurationRecord.CallHostDecryptSection(System.String, System.Configuration.ProtectedConfigurationProvider, System.Configuration.ProtectedConfigurationSection)
bei System.Configuration.RuntimeConfigurationRecord.CallHostDecryptSection(System.String, System.Configuration.ProtectedConfigurationProvider, System.Configuration.ProtectedConfigurationSection)
bei System.Configuration.BaseConfigurationRecord.DecryptConfigSection(System.Configuration.ConfigXmlReader, System.Configuration.ProtectedConfigurationProvider)
</code>```

Ausnahmeinformationen: System.Configuration.ConfigurationErrorsException

```<code>bei System.Configuration.BaseConfigurationRecord.EvaluateOne(System.String[], System.Configuration.SectionInput, Boolean, System.Configuration.FactoryRecord, System.Configuration.SectionRecord, System.Object)
bei System.Configuration.BaseConfigurationRecord.Evaluate(System.Configuration.FactoryRecord, System.Configuration.SectionRecord, System.Object, Boolean, Boolean, System.Object ByRef, System.Object ByRef)
bei System.Configuration.BaseConfigurationRecord.GetSectionRecursive(System.String, Boolean, Boolean, Boolean, Boolean, System.Object ByRef, System.Object ByRef)
bei System.Configuration.BaseConfigurationRecord.GetSectionRecursive(System.String, Boolean, Boolean, Boolean, Boolean, System.Object ByRef, System.Object ByRef)
bei System.Configuration.BaseConfigurationRecord.GetSectionRecursive(System.String, Boolean, Boolean, Boolean, Boolean, System.Object ByRef, System.Object ByRef)
bei System.Configuration.BaseConfigurationRecord.GetSection(System.String)
bei System.Configuration.ClientConfigurationSystem.System.Configuration.Internal.IInternalConfigSystem.GetSection(System.String)
bei System.Configuration.ConfigurationManager.GetSection(System.String)
bei System.Configuration.ConfigurationManager.get_ConnectionStrings()
bei MyService.Program.Main(System.String[])
</code>```

Why is this and how can I fix it?

答:
You need to grant permissions to access RSA container with which your section has been encrypted to the account under which your service runs. By default (with aspnet_regiis command you used in your question), that container is named "NetFrameworkConfigurationKey", so you need to do this:

```<code>aspnet_regiis -pa "NetFrameworkConfigurationKey" "YourServiceAccountHere"
</code>```

Title: Encrypting App.config / Web.config file

Body:
I am abusing the Web.config file as the config file of some windows service exe files, because the service mostly needs the same settings as the IIS:

Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory);

if (File.Exists("..\\Web.config"))
{
    var path = Path.GetFullPath("..\\Web.config");
    logger.Info("Web.config gefunden in {0}", path);
    AppConfig.Change(path);
}

Someone else has tried to encrypt parts of the Web.config file:

aspnet_regiis -pe connectionStrings -app /ourapp

Renaming an original App.config to Web.config and back seems to be Microsoft's recommended way of encrypting an App.config file:

https://weblogs.asp.net/jongalloway/encrypting-passwords-in-a-net-app-config-file

However, the windows services won't start:

Anwendung: MyService.exe

  Frameworkversion: v4.0.30319

  Beschreibung: Der Prozess wurde aufgrund einer unbehandelten Ausnahme beendet.

  Ausnahmeinformationen: System.Configuration.ConfigurationErrorsException

bei System.Configuration.RsaProtectedConfigurationProvider.ThrowBetterException(Boolean)
bei System.Configuration.RsaProtectedConfigurationProvider.GetCryptoServiceProvider(Boolean, Boolean)
bei System.Configuration.RsaProtectedConfigurationProvider.Decrypt(System.Xml.XmlNode)
bei System.Configuration.ProtectedConfigurationSection.DecryptSection(System.String, System.Configuration.ProtectedConfigurationProvider)
bei System.Configuration.Internal.InternalConfigHost.System.Configuration.Internal.IInternalConfigHost.DecryptSection(System.String, System.Configuration.ProtectedConfigurationProvider, System.Configuration.ProtectedConfigurationSection)
bei System.Configuration.Internal.DelegatingConfigHost.DecryptSection(System.String, System.Configuration.ProtectedConfigurationProvider, System.Configuration.ProtectedConfigurationSection)
bei System.Configuration.BaseConfigurationRecord.CallHostDecryptSection(System.String, System.Configuration.ProtectedConfigurationProvider, System.Configuration.ProtectedConfigurationSection)
bei System.Configuration.RuntimeConfigurationRecord.CallHostDecryptSection(System.String, System.Configuration.ProtectedConfigurationProvider, System.Configuration.ProtectedConfigurationSection)
bei System.Configuration.BaseConfigurationRecord.DecryptConfigSection(System.Configuration.ConfigXmlReader, System.Configuration.ProtectedConfigurationProvider)

Ausnahmeinformationen: System.Configuration.ConfigurationErrorsException

bei System.Configuration.BaseConfigurationRecord.EvaluateOne(System.String[], System.Configuration.SectionInput, Boolean, System.Configuration.FactoryRecord, System.Configuration.SectionRecord, System.Object)
bei System.Configuration.BaseConfigurationRecord.Evaluate(System.Configuration.FactoryRecord, System.Configuration.SectionRecord, System.Object, Boolean, Boolean, System.Object ByRef, System.Object ByRef)
bei System.Configuration.BaseConfigurationRecord.GetSectionRecursive(System.String, Boolean, Boolean, Boolean, Boolean, System.Object ByRef, System.Object ByRef)
bei System.Configuration.BaseConfigurationRecord.GetSectionRecursive(System.String, Boolean, Boolean, Boolean, Boolean, System.Object ByRef, System.Object ByRef)
bei System.Configuration.BaseConfigurationRecord.GetSectionRecursive(System.String, Boolean, Boolean, Boolean, Boolean, System.Object ByRef, System.Object ByRef)
bei System.Configuration.BaseConfigurationRecord.GetSection(System.String)
bei System.Configuration.ClientConfigurationSystem.System.Configuration.Internal.IInternalConfigSystem.GetSection(System.String)
bei System.Configuration.ConfigurationManager.GetSection(System.String)
bei System.Configuration.ConfigurationManager.get_ConnectionStrings()
bei MyService.Program.Main(System.String[])

Why is this and how can I fix it?

Body:
You need to grant permissions to access RSA container with which your section has been encrypted to the account under which your service runs. By default (with aspnet_regiis command you used in your question), that container is named "NetFrameworkConfigurationKey", so you need to do this:

aspnet_regiis -pa "NetFrameworkConfigurationKey" "YourServiceAccountHere"


问:
Web scraping and python data types
Web Scraping script using BeautifulSoup4 and Python 3.0
I want to remove the $ sign (in result) from price value, make it of type float and perform some numeric operation on it. But it is in text. </p>

```<code>import requests
from bs4 import BeautifulSoup

def bitcoin_scheduler():
    url = "https://coinmarketcap.com/currencies/bitcoin/"
    r = requests.get(url)
    offline_data = r.content
    soup = BeautifulSoup(offline_data, 'html.parser')

    name_box = soup.find('small', attrs={'class': 'bold hidden-xs'})
    name = name_box.text.strip()

    price_box = soup.find('span', attrs={'class': 'text-large'})
    price = price_box.text.strip()

    print(time.ctime(), name, price)
    threading.Timer(5.0, bitcoin_scheduler).start()

bitcoin_scheduler()
</code>```

<p>Result: </p>

```<code>Wed Nov 15 16:37:20 2017 (BTC) $6962.29
Wed Nov 15 16:37:25 2017 (BTC) $6962.29
Wed Nov 15 16:37:31 2017 (BTC) $6962.29
Wed Nov 15 16:37:36 2017 (BTC) $6962.29
</code>```

答:
Use the replace() method, alternatively use the strip() method</p>

```<code>import requests
from bs4 import BeautifulSoup

def bitcoin_scheduler():
    url = "https://coinmarketcap.com/currencies/bitcoin/"
    r = requests.get(url)
    offline_data = r.content
    soup = BeautifulSoup(offline_data, 'html.parser')

    name_box = soup.find('small', attrs={'class': 'bold hidden-xs'})
    name = name_box.text.strip()

    price_box = soup.find('span', attrs={'class': 'text-large'})
    price = price_box.text.strip()

    print(time.ctime(), name, price.replace('$',''))
    threading.Timer(5.0, bitcoin_scheduler).start()

bitcoin_scheduler()
</code>```

Title: Web scraping and python data types

Body:
Web Scraping script using BeautifulSoup4 and Python 3.0
I want to remove the $ sign (in result) from price value, make it of type float and perform some numeric operation on it. But it is in text.

import requests
from bs4 import BeautifulSoup

def bitcoin_scheduler():
    url = "https://coinmarketcap.com/currencies/bitcoin/"
    r = requests.get(url)
    offline_data = r.content
    soup = BeautifulSoup(offline_data, 'html.parser')

    name_box = soup.find('small', attrs={'class': 'bold hidden-xs'})
    name = name_box.text.strip()

    price_box = soup.find('span', attrs={'class': 'text-large'})
    price = price_box.text.strip()

    print(time.ctime(), name, price)
    threading.Timer(5.0, bitcoin_scheduler).start()

bitcoin_scheduler()

Result:

Wed Nov 15 16:37:20 2017 (BTC) $6962.29
Wed Nov 15 16:37:25 2017 (BTC) $6962.29
Wed Nov 15 16:37:31 2017 (BTC) $6962.29
Wed Nov 15 16:37:36 2017 (BTC) $6962.29

Body:
Use the replace() method, alternatively use the strip() method

import requests
from bs4 import BeautifulSoup

def bitcoin_scheduler():
    url = "https://coinmarketcap.com/currencies/bitcoin/"
    r = requests.get(url)
    offline_data = r.content
    soup = BeautifulSoup(offline_data, 'html.parser')

    name_box = soup.find('small', attrs={'class': 'bold hidden-xs'})
    name = name_box.text.strip()

    price_box = soup.find('span', attrs={'class': 'text-large'})
    price = price_box.text.strip()

    print(time.ctime(), name, price.replace('$',''))
    threading.Timer(5.0, bitcoin_scheduler).start()

bitcoin_scheduler()


问:
Cronjobs run differently (correctly) when command typed at console
I have encountered a strange problem with crontab: I have correct entries in crontab, have set my path correctly, and yet still when the jobs are run through crontab, they run differently (e.g. log files are not produced, and data is not written to file). However, when I type the EXACT commands at the command line, the scripts work as intended.

This is not likely a permissions problem, as I am running the cronjobs as myself.

Here are the relevant details:

Crontab entries:

```<code>0,30 8-18 * * 1-5 python /home/rascal/work/skunkworks/scripts/python/downloaders/make_whoopy.py

0,30 7-18 * * 1-5 /home/rascal/work/skunkworks/scripts/python/scrapers/funny_quotes.sh

0,30 7-20 * * 1-5 /home/rascal/work/skunkworks/scripts/python/scrapers/even_funnier_quotes.sh
</code>```

/var/log/syslog entries (filtered for CRON)

```<code>Nov  1 09:00:01 BIGBERTHA CRON[8998]: (rascal) CMD (/home/rascal/work/skunkworks/scripts/python/scrapers/funny_quotes.sh)
Nov  1 09:00:01 BIGBERTHA CRON[8999]: (rascal) CMD (/home/rascal/work/skunkworks/scripts/python/scrapers/even_funnier_quotes.sh)
Nov  1 09:00:01 BIGBERTHA CRON[9004]: (rascal) CMD (python /home/rascal/work/skunkworks/scripts/python/downloaders/make_whoopy.py)
Nov  1 09:09:01 BIGBERTHA CRON[9306]: (root) CMD (  [ -x /usr/lib/php/sessionclean ] && /usr/lib/php/sessionclean)
Nov  1 09:09:01 BIGBERTHA CRON[9313]: (root) CMD (  [ -x /usr/lib/php5/maxlifetime ] && [ -x /usr/lib/php5/sessionclean ] && [ -d /var/lib/php5 ] && /usr/lib/php5/sessionclean /var/lib/php5 $(/usr/lib/php5/maxlifetime))
Nov  1 09:17:01 BIGBERTHA CRON[9495]: (root) CMD (   cd / && run-parts --report /etc/cron.hourly)
</code>```

Environment (on Server machine running cron jobs)

```<code>rascal@BIGBERTHA:~/work/skunkworks/scripts/python/scrapers$ which python
/usr/bin/python
rascal@BIGBERTHA:~/work/skunkworks/scripts/python/scrapers$ which bash
/bin/bash
rascal@BIGBERTHA:~$ which scrapy
/usr/local/bin/scrapy
</code>```

funny_quotes.sh

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

. /home/rascal/.profile

cd /home/rascal/work/skunkworks/scripts/python/scrapers

scrapy crawl funny_quotes
</code>```

Running in command prompt ...

```<code>rascal@BIGBERTHA:~$ /home/rascal/work/skunkworks/scripts/python/scrapers/funny_quotes.sh
2017-11-01 09:57:05 [scrapy.utils.log] INFO: Scrapy 1.4.0 started (bot: scrapers)
2017-11-01 09:57:05 [scrapy.utils.log] INFO: Overridden settings: {'NEWSPIDER_MODULE': 'scrapers.spiders', 'SPIDER_MODULES': ['scrapers.spiders'], 'BO
T_NAME': 'scrapers'}
2017-11-01 09:57:05 [scrapy.middleware] INFO: Enabled extensions:
['scrapy.extensions.memusage.MemoryUsage',
 'scrapy.extensions.logstats.LogStats',
 'scrapy.extensions.telnet.TelnetConsole',
 'scrapy.extensions.corestats.CoreStats']
...
</code>```

Why are jobs being run differently through cron?

答:
It turns out that this was related to an environment issue. Cron reported to syslog that it had run the job, yet no files/log files were created.

Eventually, the way I solved this was to add a MAILTO=username to my crontab. After I had done this, when the job run and failed, I saw the error message:

scrapy: command not found

I then resolved this by adding the following statment to my bash script:

PATH=$PATH:/usr/local/bin/

Body:
I have encountered a strange problem with crontab: I have correct entries in crontab, have set my path correctly, and yet still when the jobs are run through crontab, they run differently (e.g. log files are not produced, and data is not written to file). However, when I type the EXACT commands at the command line, the scripts work as intended.

This is not likely a permissions problem, as I am running the cronjobs as myself.

Here are the relevant details:

Crontab entries:

0,30 8-18 * * 1-5 python /home/rascal/work/skunkworks/scripts/python/downloaders/make_whoopy.py

0,30 7-18 * * 1-5 /home/rascal/work/skunkworks/scripts/python/scrapers/funny_quotes.sh

0,30 7-20 * * 1-5 /home/rascal/work/skunkworks/scripts/python/scrapers/even_funnier_quotes.sh

/var/log/syslog entries (filtered for CRON)

Nov  1 09:00:01 BIGBERTHA CRON[8998]: (rascal) CMD (/home/rascal/work/skunkworks/scripts/python/scrapers/funny_quotes.sh)
Nov  1 09:00:01 BIGBERTHA CRON[8999]: (rascal) CMD (/home/rascal/work/skunkworks/scripts/python/scrapers/even_funnier_quotes.sh)
Nov  1 09:00:01 BIGBERTHA CRON[9004]: (rascal) CMD (python /home/rascal/work/skunkworks/scripts/python/downloaders/make_whoopy.py)
Nov  1 09:09:01 BIGBERTHA CRON[9306]: (root) CMD (  [ -x /usr/lib/php/sessionclean ] && /usr/lib/php/sessionclean)
Nov  1 09:09:01 BIGBERTHA CRON[9313]: (root) CMD (  [ -x /usr/lib/php5/maxlifetime ] && [ -x /usr/lib/php5/sessionclean ] && [ -d /var/lib/php5 ] && /usr/lib/php5/sessionclean /var/lib/php5 $(/usr/lib/php5/maxlifetime))
Nov  1 09:17:01 BIGBERTHA CRON[9495]: (root) CMD (   cd / && run-parts --report /etc/cron.hourly)

Environment (on Server machine running cron jobs)

rascal@BIGBERTHA:~/work/skunkworks/scripts/python/scrapers$ which python
/usr/bin/python
rascal@BIGBERTHA:~/work/skunkworks/scripts/python/scrapers$ which bash
/bin/bash
rascal@BIGBERTHA:~$ which scrapy
/usr/local/bin/scrapy

funny_quotes.sh

#!/bin/bash

. /home/rascal/.profile

cd /home/rascal/work/skunkworks/scripts/python/scrapers

scrapy crawl funny_quotes

Running in command prompt ...

rascal@BIGBERTHA:~$ /home/rascal/work/skunkworks/scripts/python/scrapers/funny_quotes.sh
2017-11-01 09:57:05 [scrapy.utils.log] INFO: Scrapy 1.4.0 started (bot: scrapers)
2017-11-01 09:57:05 [scrapy.utils.log] INFO: Overridden settings: {'NEWSPIDER_MODULE': 'scrapers.spiders', 'SPIDER_MODULES': ['scrapers.spiders'], 'BO
T_NAME': 'scrapers'}
2017-11-01 09:57:05 [scrapy.middleware] INFO: Enabled extensions:
['scrapy.extensions.memusage.MemoryUsage',
 'scrapy.extensions.logstats.LogStats',
 'scrapy.extensions.telnet.TelnetConsole',
 'scrapy.extensions.corestats.CoreStats']
...

Why are jobs being run differently through cron?


问:
How to prevent edge lapping in graphviz with circo layout
I was trying to draw a circular graph using GraphViz, and decided it would be the best to use circo for this graph.

Having taken advice in a post from 7 years ago, How to prevent edges in graphviz to overlap each other, and using global overlap=false and splines=true, the edges still overlap with each other.

The whole graph can be seen here, and is defined as:

```<code>digraph question6 {

 layout="circo"
 overlap=false
 splines=true
 node [shape="circle"]

 G1 [label="1, G"]
 G2 [label="2, G"]
 D11 [label="1, D1"]
 D12 [label="2, D1"]
 D21 [label="1, D2"]
 D22 [label="2, D2"]

 G1 -> D12 [label="c"]
 G1 -> G2 [label="a"]
 G2 -> D12 [label="a"]
 D11 -> G1 [label="d"]
 D11 -> D21 [label="e"]
 D11 -> D12  [label="c"]
 D12 -> G2 [label="d"]
 D12 -> D22 [label="c"]
 D21 -> G1 [label="d"]
 D21 -> D22 [label="c"]

 D22 -> D21 [label="b"]
 D22 -> G2 [label="d"]
}
</code>```

答:
As for now, there is not a viable way for this.

One of the very difficult things that GraphViz is not yet able to
  resolve is to determine if the graph is planar.

Body:
I was trying to draw a circular graph using GraphViz, and decided it would be the best to use circo for this graph.

Having taken advice in a post from 7 years ago, How to prevent edges in graphviz to overlap each other, and using global overlap=false and splines=true, the edges still overlap with each other.

The whole graph can be seen here, and is defined as:

digraph question6 {

 layout="circo"
 overlap=false
 splines=true
 node [shape="circle"]

 G1 [label="1, G"]
 G2 [label="2, G"]
 D11 [label="1, D1"]
 D12 [label="2, D1"]
 D21 [label="1, D2"]
 D22 [label="2, D2"]

 G1 -> D12 [label="c"]
 G1 -> G2 [label="a"]
 G2 -> D12 [label="a"]
 D11 -> G1 [label="d"]
 D11 -> D21 [label="e"]
 D11 -> D12  [label="c"]
 D12 -> G2 [label="d"]
 D12 -> D22 [label="c"]
 D21 -> G1 [label="d"]
 D21 -> D22 [label="c"]

 D22 -> D21 [label="b"]
 D22 -> G2 [label="d"]
}