问:
Generic EF Model Builder for Persistence DataLayer in .Net Core
I want pass my entities to my SQL Server database from API in .Net Core. I need an extension or module that can be added to Container builder and Helps me to use in ConfigureServices method in Startup.cs
I found a project according to my needs (https://github.com/devmentors/DNC-DShop), but this sample has been implemented with MongoDB. I want to implement the same thing with SQLSERVER DB and EF ORM.

This  code is inside startup file For Mongo Sample :

```<code>builder.AddMongo();
builder.AddMongoRepository<Cart>("Carts");
builder.AddMongoRepository<Customer>("Customers");
builder.AddMongoRepository<Product>("Products");
</code>```

This code in applicationsetting.json file:

```<code>  "mongo": {
    "connectionString": "mongodb://localhost:27017",
"database": "customers-service",
    "seed": false
},
</code>```

This Code is inside Extension.cs:

```<code>public static class Extensions
    {

        public static void AddMongoRepository<TEntity>(this ContainerBuilder builder, string collectionName)
            where TEntity : IIdentifiable
            => builder.Register(ctx => new EFRepository<TEntity>(ctx.Resolve<IMongoDatabase>(), collectionName))
                .As<IMongoRepository<TEntity>>()
                .InstancePerLifetimeScope();
    }
</code>```

答:
I'll describe a solution with a project I'm currently working on (Sppd.TeamTuner), which supports multiple database providers.

There is a *.DataAccess.EF.csproj project, registering the required services and configuring the DbContext. It is important to understand that this project does NOT register the used database instance, it merely specifies how the entities will be stored. The interesting classes for you are both partial TeamTunerContext.cs classes here. I've added this paragraph as in your example it seems your coupled with MongoDb, which shouldn't be necessary.

What you are looking for, telling what DB to use, is being done in one of the dedicated DB provider projects (MsSql, Sqlite, InMemory). As you want to use SQL, this line is relevant:

```<code>services.AddDbContext<TeamTunerContextMsSql>(options => options.UseSqlServer(databaseConfig.ConnectionString))
</code>```

For this the nuget package Microsoft.EntityFrameworkCore.SqlServer, containing the extension method UseSqlServer is being referenced. (If you references asp.net core in your project I think this is already included).

Body:
I want pass my entities to my SQL Server database from API in .Net Core. I need an extension or module that can be added to Container builder and Helps me to use in ConfigureServices method in Startup.cs
I found a project according to my needs (https://github.com/devmentors/DNC-DShop), but this sample has been implemented with MongoDB. I want to implement the same thing with SQLSERVER DB and EF ORM.

This  code is inside startup file For Mongo Sample :

builder.AddMongo();
builder.AddMongoRepository<Cart>("Carts");
builder.AddMongoRepository<Customer>("Customers");
builder.AddMongoRepository<Product>("Products");

This code in applicationsetting.json file:

  "mongo": {
    "connectionString": "mongodb://localhost:27017",
"database": "customers-service",
    "seed": false
},

This Code is inside Extension.cs:

public static class Extensions
    {

        public static void AddMongoRepository<TEntity>(this ContainerBuilder builder, string collectionName)
            where TEntity : IIdentifiable
            => builder.Register(ctx => new EFRepository<TEntity>(ctx.Resolve<IMongoDatabase>(), collectionName))
                .As<IMongoRepository<TEntity>>()
                .InstancePerLifetimeScope();
    }

Body:
I'll describe a solution with a project I'm currently working on (Sppd.TeamTuner), which supports multiple database providers.

There is a *.DataAccess.EF.csproj project, registering the required services and configuring the DbContext. It is important to understand that this project does NOT register the used database instance, it merely specifies how the entities will be stored. The interesting classes for you are both partial TeamTunerContext.cs classes here. I've added this paragraph as in your example it seems your coupled with MongoDb, which shouldn't be necessary.

What you are looking for, telling what DB to use, is being done in one of the dedicated DB provider projects (MsSql, Sqlite, InMemory). As you want to use SQL, this line is relevant:

services.AddDbContext<TeamTunerContextMsSql>(options => options.UseSqlServer(databaseConfig.ConnectionString))

For this the nuget package Microsoft.EntityFrameworkCore.SqlServer, containing the extension method UseSqlServer is being referenced. (If you references asp.net core in your project I think this is already included).


来源: stackexchange

问:
How to loop through a json string with PL/SQL?
My example only returns BMW 2010.
How do I get it to return AUDI 2000 and BMW 2010?

```<code>declare
    sample_json   varchar2 (32767)
        := '

            [{"NAME":"AUDI","YEAR":"2000"},{"NAME":"BMW","YEAR":"2010"}]
';
begin
    apex_json.parse (sample_json);
    dbms_output.put_line (apex_json.get_varchar2 ('NAME'));
    dbms_output.put_line (apex_json.get_varchar2 ('YEAR'));
end;
</code>```

答:
Since you're running Oracle 12c, you don't need Apex_json. You may use standard Oracle's JSON functions.</p>

```<code>set serveroutput on
declare
sample_json   varchar2 (32767)
        := '[{"NAME":"AUDI","YEAR":"2000"},{"NAME":"BMW","YEAR":"2010"}]';
BEGIN
for rec IN (
     select j.name,j.year
       from json_table(sample_json,'$[*]' COLUMNS
        name varchar2(20) PATH '$.NAME',
        year NUMBER       PATH '$.YEAR'
       ) j  )
     LOOP
       dbms_output.put_line (rec.name||','||rec.year);
     END LOOP;
END;
/

AUDI,2000
BMW,2010

PL/SQL procedure successfully completed.
</code>```

ContentLicense: CC BY-SA 4.0

Body:
My example only returns BMW 2010.
How do I get it to return AUDI 2000 and BMW 2010?

declare
    sample_json   varchar2 (32767)
        := '

            [{"NAME":"AUDI","YEAR":"2000"},{"NAME":"BMW","YEAR":"2010"}]
';
begin
    apex_json.parse (sample_json);
    dbms_output.put_line (apex_json.get_varchar2 ('NAME'));
    dbms_output.put_line (apex_json.get_varchar2 ('YEAR'));
end;

Body:
Since you're running Oracle 12c, you don't need Apex_json. You may use standard Oracle's JSON functions.

set serveroutput on
declare
sample_json   varchar2 (32767)
        := '[{"NAME":"AUDI","YEAR":"2000"},{"NAME":"BMW","YEAR":"2010"}]';
BEGIN
for rec IN (
     select j.name,j.year
       from json_table(sample_json,'$[*]' COLUMNS
        name varchar2(20) PATH '$.NAME',
        year NUMBER       PATH '$.YEAR'
       ) j  )
     LOOP
       dbms_output.put_line (rec.name||','||rec.year);
     END LOOP;
END;
/

AUDI,2000
BMW,2010

PL/SQL procedure successfully completed.


问:
How to fix CORS error For Response header
I am using Angular7 as frontend and yii2 as backend app
When i try to call api from angular it gives error "XMLHttpRequest at 'http://localhost/pwap/html/api/web/v2/users/login' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status."

I have applied different solution for CORS but not succeed

My htaccess code in Yii2 backend is like below

```<code>Header set Access-Control-Allow-Origin "*"
#Header always set Access-Control-Allow-Origin: "http://localhost:4200"
Header set Access-Control-Allow-Methods "POST, GET, PUT, OPTIONS, DELETE"
Header set Access-Control-Max-Age "86400"
Header set Access-Control-Allow-Headers "*"
Header set Access-Control-Request-Headers "*"
</code>```

Angular code like below

```<code>        const httpOptions = {
            headers: new HttpHeaders({
              'Content-Type':  'application/x-www-form-urlencoded; charset=UTF-8, application/json, text/html, text/plain , text/xml',
              'app_token': environment.app_token,
              'Accept': '*/*',
              'Access-Control-Allow-Origin': ['*'],
              //'Access-Control-Request-Headers': ['*'],
              'Access-Control-Allow-Headers': ['*']
            })
          };

        let data = {
            "username": username,
            "password": password
        }
        let params = new URLSearchParams();
        for(let key in data){
            params.set(key, data[key])
        }

        return this.http.post('http://localhost/pwap/html/api/web/v2/users/login', data, httpOptions)
            .pipe().subscribe(user => {
                // login successful if there's a jwt token in the response
                if (user) {
                    console.log(user);
                    // store user details and jwt token in local storage to keep user logged in between page refreshes
                    localStorage.setItem('currentUser', JSON.stringify(user));
                    //this.currentUserSubject.next(user);
                }

                return user;
            }
            );
    }
</code>```

also i have passed 'app_token' header which is not display in "Key:value" pair

Response Header

Whats wrong i am doing here? Need a help

答:
in api controller</p>

```<code>public function behaviors()
{
    return yii\helpers\ArrayHelper::merge(parent::behaviors(), [
                'corsFilter' => [
                    'class' => yii\filters\Cors::className(),
                    'cors' => [
                        'Origin' => ['*'], // or your app adddress specified
                        'Access-Control-Request-Method' => ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'],
                        'Access-Control-Request-Headers' => ['*'],
                        'Access-Control-Allow-Credentials' => true
                    ]
                ]
    ]);
}
</code>```

Body:
I am using Angular7 as frontend and yii2 as backend app
When i try to call api from angular it gives error "XMLHttpRequest at 'http://localhost/pwap/html/api/web/v2/users/login' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status."

I have applied different solution for CORS but not succeed

My htaccess code in Yii2 backend is like below

Header set Access-Control-Allow-Origin "*"
#Header always set Access-Control-Allow-Origin: "http://localhost:4200"
Header set Access-Control-Allow-Methods "POST, GET, PUT, OPTIONS, DELETE"
Header set Access-Control-Max-Age "86400"
Header set Access-Control-Allow-Headers "*"
Header set Access-Control-Request-Headers "*"

Angular code like below

        const httpOptions = {
            headers: new HttpHeaders({
              'Content-Type':  'application/x-www-form-urlencoded; charset=UTF-8, application/json, text/html, text/plain , text/xml',
              'app_token': environment.app_token,
              'Accept': '*/*',
              'Access-Control-Allow-Origin': ['*'],
              //'Access-Control-Request-Headers': ['*'],
              'Access-Control-Allow-Headers': ['*']
            })
          };

        let data = {
            "username": username,
            "password": password
        }
        let params = new URLSearchParams();
        for(let key in data){
            params.set(key, data[key])
        }

        return this.http.post('http://localhost/pwap/html/api/web/v2/users/login', data, httpOptions)
            .pipe().subscribe(user => {
                // login successful if there's a jwt token in the response
                if (user) {
                    console.log(user);
                    // store user details and jwt token in local storage to keep user logged in between page refreshes
                    localStorage.setItem('currentUser', JSON.stringify(user));
                    //this.currentUserSubject.next(user);
                }

                return user;
            }
            );
    }

also i have passed 'app_token' header which is not display in "Key:value" pair

Response Header

Whats wrong i am doing here? Need a help

Body:
in api controller

public function behaviors()
{
    return yii\helpers\ArrayHelper::merge(parent::behaviors(), [
                'corsFilter' => [
                    'class' => yii\filters\Cors::className(),
                    'cors' => [
                        'Origin' => ['*'], // or your app adddress specified
                        'Access-Control-Request-Method' => ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'],
                        'Access-Control-Request-Headers' => ['*'],
                        'Access-Control-Allow-Credentials' => true
                    ]
                ]
    ]);
}


问:
How to change register value from a predefined array in powershell after testing the registry path?
I'm trying to optimize IE11 for our application per user in case a GP is not allowed to be used. I want to optimize these settings with a single script so that it doesn't take me a lot of times each time i get the request.

I tried to create a powershell script that first tests the path of the registry key.
After that it should provide a message to either cancel or continue and then it should change the values.

So far the "test-path" part works, but realy changing the values is not.

```<code>$RegPaths =
'HKCU:\Software\Microsoft\Internet Explorer\BrowserEmulation',
'HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Internet Settings\ZoneMap',
'HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Internet Settings\Zones\1',
'HKCU:\Software\Microsoft\Internet Explorer\New Windows'

#Test-path $RegPaths

$RegEdit =
{Set-ItemProperty -Path 'HKCU:\Software\Microsoft\Internet Explorer\BrowserEmulation' -name IntranetCompatibilityMode -value 0},
{Set-ItemProperty -Path 'HKCU:\Software\Microsoft\Internet Explorer\BrowserEmulation' -name MSCompatibilityModegpupd -value 0},
{Set-ItemProperty -Path 'HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Internet Settings\ZoneMap' -name AutoDetect -value 1},
{Set-ItemProperty -Path 'HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Internet Settings\Zones\1' -name 1001 -value 0},
{Set-ItemProperty -Path 'HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Internet Settings\Zones\1' -name 1004 -value 0},
{Set-ItemProperty -Path 'HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Internet Settings\Zones\1' -name 1201 -value 0},
{Set-ItemProperty -path 'HKCU:\Software\Microsoft\Internet Explorer\New Windows' -name PopupMgr -value 0}

#If (Test-path $RegPaths = True)
#{write-host "Registry paths exist, continueing improving IE settings for ISCV client"}
#Foreach ($RegEdit) {if (Test-path $RegPaths -eq $True) {continue}}
#Else {write-host "Register path invalid or missing, canceling changes"}

If (( Test-Path $RegPaths) -eq $True)
    {
        {write-host "Registry paths exist, continueing improving IE settings for ISCV client"}
        #{ForEach-object -process $RegEdit}
    Foreach ($RegEdit in $RegEdit)
        {start-job $RegEdit}
    }
Else
        {Write-Host " Path missing or invalid, cancel script"}
</code>```

The -process, or the start-job is not changing the values from 0 to 1 for example, which is expected.

Thanks!

Update
Thanks for the advise so far. I was trying and noticed that only the "write-host" line and the first set-itemproperty line are actually working, after is nothing happening, any idea how or why?

```<code>{write-host "Registry paths exist, continueing improving IE settings for
client"}
    &{Set-ItemProperty -Path 'HKCU:\Software\Microsoft\Internet
Explorer\BrowserEmulation' -name IntranetCompatibilityMode -value 0}
    &{Set-ItemProperty -Path 'HKCU:\Software\Microsoft\Internet
Explorer\BrowserEmulation' -name MSCompatibilityModegpupd -value 0}
    &{Set-ItemProperty -Path
'HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Internet Settings\ZoneMap'
-name AutoDetect -value 1}
    &{Set-ItemProperty -Path
'HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Internet Settings\Zones\1'
-name 1001 -value 0}
    &{Set-ItemProperty -Path
'HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Internet Settings\Zones\1'
-name 1004 -value 0}
    &{Set-ItemProperty -Path
'HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Internet Settings\Zones\1'
-name 1201 -value 0}
    &{Set-ItemProperty -path 'HKCU:\Software\Microsoft\Internet Explorer\New
Windows' -name PopupMgr -value 0}
</code>```

Update  the above update is working, i didn't look good. Thanks!

答:
this code is working ok for me now:</p>

```<code>{write-host "Registry paths exist, continueing improving IE settings for
client"}
    &{Set-ItemProperty -Path 'HKCU:\Software\Microsoft\Internet
Explorer\BrowserEmulation' -name IntranetCompatibilityMode -value 0}
    &{Set-ItemProperty -Path 'HKCU:\Software\Microsoft\Internet
Explorer\BrowserEmulation' -name MSCompatibilityModegpupd -value 0}
    &{Set-ItemProperty -Path
'HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Internet Settings\ZoneMap'
-name AutoDetect -value 1}
    &{Set-ItemProperty -Path
'HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Internet Settings\Zones\1'
-name 1001 -value 0}
    &{Set-ItemProperty -Path
'HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Internet Settings\Zones\1'
-name 1004 -value 0}
    &{Set-ItemProperty -Path
'HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Internet Settings\Zones\1'
-name 1201 -value 0}
    &{Set-ItemProperty -path 'HKCU:\Software\Microsoft\Internet Explorer\New
Windows' -name PopupMgr -value 0}
</code>```

Body:
I'm trying to optimize IE11 for our application per user in case a GP is not allowed to be used. I want to optimize these settings with a single script so that it doesn't take me a lot of times each time i get the request.

I tried to create a powershell script that first tests the path of the registry key.
After that it should provide a message to either cancel or continue and then it should change the values.

So far the "test-path" part works, but realy changing the values is not.

$RegPaths =
'HKCU:\Software\Microsoft\Internet Explorer\BrowserEmulation',
'HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Internet Settings\ZoneMap',
'HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Internet Settings\Zones\1',
'HKCU:\Software\Microsoft\Internet Explorer\New Windows'

#Test-path $RegPaths

$RegEdit =
{Set-ItemProperty -Path 'HKCU:\Software\Microsoft\Internet Explorer\BrowserEmulation' -name IntranetCompatibilityMode -value 0},
{Set-ItemProperty -Path 'HKCU:\Software\Microsoft\Internet Explorer\BrowserEmulation' -name MSCompatibilityModegpupd -value 0},
{Set-ItemProperty -Path 'HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Internet Settings\ZoneMap' -name AutoDetect -value 1},
{Set-ItemProperty -Path 'HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Internet Settings\Zones\1' -name 1001 -value 0},
{Set-ItemProperty -Path 'HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Internet Settings\Zones\1' -name 1004 -value 0},
{Set-ItemProperty -Path 'HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Internet Settings\Zones\1' -name 1201 -value 0},
{Set-ItemProperty -path 'HKCU:\Software\Microsoft\Internet Explorer\New Windows' -name PopupMgr -value 0}

#If (Test-path $RegPaths = True)
#{write-host "Registry paths exist, continueing improving IE settings for ISCV client"}
#Foreach ($RegEdit) {if (Test-path $RegPaths -eq $True) {continue}}
#Else {write-host "Register path invalid or missing, canceling changes"}

If (( Test-Path $RegPaths) -eq $True)
    {
        {write-host "Registry paths exist, continueing improving IE settings for ISCV client"}
        #{ForEach-object -process $RegEdit}
    Foreach ($RegEdit in $RegEdit)
        {start-job $RegEdit}
    }
Else
        {Write-Host " Path missing or invalid, cancel script"}

The -process, or the start-job is not changing the values from 0 to 1 for example, which is expected.

Thanks!

Update
Thanks for the advise so far. I was trying and noticed that only the "write-host" line and the first set-itemproperty line are actually working, after is nothing happening, any idea how or why?

{write-host "Registry paths exist, continueing improving IE settings for
client"}
    &{Set-ItemProperty -Path 'HKCU:\Software\Microsoft\Internet
Explorer\BrowserEmulation' -name IntranetCompatibilityMode -value 0}
    &{Set-ItemProperty -Path 'HKCU:\Software\Microsoft\Internet
Explorer\BrowserEmulation' -name MSCompatibilityModegpupd -value 0}
    &{Set-ItemProperty -Path
'HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Internet Settings\ZoneMap'
-name AutoDetect -value 1}
    &{Set-ItemProperty -Path
'HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Internet Settings\Zones\1'
-name 1001 -value 0}
    &{Set-ItemProperty -Path
'HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Internet Settings\Zones\1'
-name 1004 -value 0}
    &{Set-ItemProperty -Path
'HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Internet Settings\Zones\1'
-name 1201 -value 0}
    &{Set-ItemProperty -path 'HKCU:\Software\Microsoft\Internet Explorer\New
Windows' -name PopupMgr -value 0}

Update  the above update is working, i didn't look good. Thanks!

Body:
this code is working ok for me now:

{write-host "Registry paths exist, continueing improving IE settings for
client"}
    &{Set-ItemProperty -Path 'HKCU:\Software\Microsoft\Internet
Explorer\BrowserEmulation' -name IntranetCompatibilityMode -value 0}
    &{Set-ItemProperty -Path 'HKCU:\Software\Microsoft\Internet
Explorer\BrowserEmulation' -name MSCompatibilityModegpupd -value 0}
    &{Set-ItemProperty -Path
'HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Internet Settings\ZoneMap'
-name AutoDetect -value 1}
    &{Set-ItemProperty -Path
'HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Internet Settings\Zones\1'
-name 1001 -value 0}
    &{Set-ItemProperty -Path
'HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Internet Settings\Zones\1'
-name 1004 -value 0}
    &{Set-ItemProperty -Path
'HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Internet Settings\Zones\1'
-name 1201 -value 0}
    &{Set-ItemProperty -path 'HKCU:\Software\Microsoft\Internet Explorer\New
Windows' -name PopupMgr -value 0}


问:
How to make a div content not overextend
I have a div of width for example 100px and when I put content in it, this content overextends beyond the 100px instead of dropping one line. ( I was checking with the inspect tool inside the browser. )
Note: this div is placed inside a
 with display: flex;

I've tried making the
 to float: left; and to display: inline; and to display: inline-block; but it didn't work...

CSS

```<code>.fixed-header #nav-list {
    flex-basis: 80%;
    align-self: flex-start;
}

.fixed-header #nav-list ul {
    list-style: none;

    display: flex;
    justify-content: space-around;
    flex-basis: 100%;
}

.fixed-header #nav-list ul li {
    display: flex;
    flex-direction: column;
}

.fixed-header #nav-list ul .drop-down-element {
    width: 15%;
}

.fixed-header #nav-list ul li div {
    float: left;
}
</code>```

Note: The #nav-list is a flex element of .fixed-header (see in the HTML Section).

HTML

```<code><div class="fixed-header">
    <div id="header"><h1>Physi_Cs</h1></div>

    <div id="nav-list">
        <ul>
            <li class="drop-down-element"><a href="#">Shop</a> <div>BLABLA</div> </li>
            <li class="drop-down-element"><a href="#">Learn Physics</a></li>
            <li class="drop-down-element"><a href="#">Articles</a></li>
            <li><a href="SignUpPage.html">Sign Up</a></li>
            <li><a href="LoginPage.html">Log In</a></li>
        </ul>
    </div>
</div>
</code>```

My question is:

How do I make the content of the
 inside of the
 not overextend beyond the
 width.

答:
Basically your only problem was

.fixed-header #nav-list ul .drop-down-element {
   width: 15%
}
```

It makes the elements' width relative to the available space ignoring any kind of overflow.
So to fix it just remove this rule.

Body:
I have a div of width for example 100px and when I put content in it, this content overextends beyond the 100px instead of dropping one line. ( I was checking with the inspect tool inside the browser. )
Note: this div is placed inside a
 with display: flex;

I've tried making the
 to float: left; and to display: inline; and to display: inline-block; but it didn't work...

CSS

.fixed-header #nav-list {
    flex-basis: 80%;
    align-self: flex-start;
}

.fixed-header #nav-list ul {
    list-style: none;

    display: flex;
    justify-content: space-around;
    flex-basis: 100%;
}

.fixed-header #nav-list ul li {
    display: flex;
    flex-direction: column;
}

.fixed-header #nav-list ul .drop-down-element {
    width: 15%;
}

.fixed-header #nav-list ul li div {
    float: left;
}

Note: The #nav-list is a flex element of .fixed-header (see in the HTML Section).

HTML

Physi_Cs

Shop
BLABLA

Learn Physics

Articles

Sign Up

Log In

My question is:

How do I make the content of the
 inside of the
 not overextend beyond the
 width.

Body:
Basically your only problem was

.fixed-header #nav-list ul .drop-down-element {
   width: 15%
}

It makes the elements' width relative to the available space ignoring any kind of overflow.
So to fix it just remove this rule.


问:
Why GCC refuses a const reference within a copy-assignment operation?
I want to overload a common copy-assignment operator normally.
At first I used a interface that only requires a const reference to the source,
and explicitly disabled the interface that accepts a modifiable reference,
but I can not pass the compilation.
The compiler reports "error: use of deleted function ‘ClassA& ClassA::operator=(ClassA&)"

Of course, I can get compiled if I don't expicitly delete the interface, but that is not my purpose.
I'd like to explicitly delete it, to avoid unexpected using it.

Why a copy-assignment operation needs a modifiable reference to the source, instead of a const reference?
The assignment operation just needs to access the source read-only!

There is a same question about the copy-constructor, I omit it for simplifying.

What's wrong with my code? or we can NOT delete it?

My sample code is following:

```<code>class ClassA {
public:
   ClassA() = default;
   ClassA( ClassA & ) = default;

   ClassA & operator=( ClassA & )
   = delete   // Must comment-out this, or we can't pass the compilation.
   // { cout << "ClassA & operator=( ClassA & ) executed." << endl; return *this; }
   ;

   ClassA & operator=( ClassA && ) {
      cout << "ClassA & operator=( ClassA && ) executed." << endl;
      return *this;
   };

   ClassA & operator=( const ClassA & ) {
      cout << "ClassA & operator=( const ClassA & ) executed." << endl;
      return *this;
   };
   ClassA & operator=( const ClassA && ) {
      cout << "ClassA & operator=( const ClassA && ) executed." << endl;
      return *this;
   };
};

int main() {
   ClassA oa, ob;
   ob = oa;

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

答:
or we can NOT delete it?

You just don't need to do that. If you provide a user-defined copy assignment operator, then no other ones will be implicitly-declared, i.e. only the user-defined one will exist.

If you do that, the copy assignment operator you explicitly marked as delete will participate in overload resolution; when it's selected the compilation fails. For ob = oa;, the operator=( ClassA & ) is a better match, if it doesn't exist, operator=( const ClassA & ) will be used and work fine.

So in this case you can just do

```<code>class ClassA {
public:

   ClassA & operator=( ClassA && ) {
      cout << "ClassA & operator=( ClassA && ) executed." << endl;
      return *this;
   }

   ClassA & operator=( const ClassA & ) {
      cout << "ClassA & operator=( const ClassA & ) executed." << endl;
      return *this;
   }
};
</code>```

Body:
I want to overload a common copy-assignment operator normally.
At first I used a interface that only requires a const reference to the source,
and explicitly disabled the interface that accepts a modifiable reference,
but I can not pass the compilation.
The compiler reports "error: use of deleted function ‘ClassA& ClassA::operator=(ClassA&)"

Of course, I can get compiled if I don't expicitly delete the interface, but that is not my purpose.
I'd like to explicitly delete it, to avoid unexpected using it.

Why a copy-assignment operation needs a modifiable reference to the source, instead of a const reference?
The assignment operation just needs to access the source read-only!

There is a same question about the copy-constructor, I omit it for simplifying.

What's wrong with my code? or we can NOT delete it?

My sample code is following:

class ClassA {
public:
   ClassA() = default;
   ClassA( ClassA & ) = default;

   ClassA & operator=( ClassA & )
   = delete   // Must comment-out this, or we can't pass the compilation.
   // { cout << "ClassA & operator=( ClassA & ) executed." << endl; return *this; }
   ;

   ClassA & operator=( ClassA && ) {
      cout << "ClassA & operator=( ClassA && ) executed." << endl;
      return *this;
   };

   ClassA & operator=( const ClassA & ) {
      cout << "ClassA & operator=( const ClassA & ) executed." << endl;
      return *this;
   };
   ClassA & operator=( const ClassA && ) {
      cout << "ClassA & operator=( const ClassA && ) executed." << endl;
      return *this;
   };
};

int main() {
   ClassA oa, ob;
   ob = oa;

   return EXIT_SUCCESS;
};

Body:
or we can NOT delete it?

You just don't need to do that. If you provide a user-defined copy assignment operator, then no other ones will be implicitly-declared, i.e. only the user-defined one will exist.

If you do that, the copy assignment operator you explicitly marked as delete will participate in overload resolution; when it's selected the compilation fails. For ob = oa;, the operator=( ClassA & ) is a better match, if it doesn't exist, operator=( const ClassA & ) will be used and work fine.

So in this case you can just do

class ClassA {
public:

   ClassA & operator=( ClassA && ) {
      cout << "ClassA & operator=( ClassA && ) executed." << endl;
      return *this;
   }

   ClassA & operator=( const ClassA & ) {
      cout << "ClassA & operator=( const ClassA & ) executed." << endl;
      return *this;
   }
};


问:
How to Print Values in console Without passing in any Function?
I just want to print something in console in my typescript file. But whenever I tried to do the same , it gives a error.

```<code>console.log(this.dataList);
</code>```

Error:

error TS2391: Function implementation is missing or not immediately following the declaration.

答:
A calss can contain only functions and declarations. Not definitions. try putting the log in any of the methods or constructor

Function implementation is missing or not immediately following the declaration, TypeScript class

Body:
I just want to print something in console in my typescript file. But whenever I tried to do the same , it gives a error.

console.log(this.dataList);

Error:

error TS2391: Function implementation is missing or not immediately following the declaration.


问:
How do I move an object in opengles using vertices?
I am wondering if there is a way to update and move a triangle in OpenGL ES using the vertices. These are the vertices of my triangle:

```<code>// in counterclockwise order :

static float triangleCoords[] = {
        0.0f,  0.622008459f, 0.0f,  // top
        -0.5f, -0.311004243f, 0.0f, // bottom left
        0.5f, -0.311004243f, 0.0f   // bottom right
};
</code>```

I wanted to know if it was possible to move the triangle without the matrices.

Thank you!

答:
Ok i will present you some of my idea (I use ECMA6). Change every number with methods with return. Then in class (model) define what ever you want.

First use class based coding avoid procedural.
webGL2 project - object oriented

      class Scale {

        constructor() {

            this.x = 1;
            this.y = 1;
            this.z = 1;

        }

        LinearScale(scale_) {

            this.x = scale_;
            this.y = scale_;
            this.z = scale_;

        }

    }

        class Point {

        constructor(x, y, z) {

            if (typeof z == 'undefined') {
                z = 0;
            }

            this.x = x;
            this.y = y;
            this.z = z;
            this.scale = new Scale();

        }

        get X() {
            return parseFloat(this.x * this.scale.x);
        }
        get Y() {
            return parseFloat(this.y * this.scale.y);
        }
        get Z() {
            return parseFloat(this.z * this.scale.z);
        }

    }

class TriangleVertex {

    constructor(root) {

        this.root = root;
        this.size = root.size;
        this.dynamicBuffer = App.dynamicBuffer;
        this.pointA = new Point(0.0, 1, 0.0);
        this.pointB = new Point(-1, -1, 0);
        this.pointC = new Point(1, -1, 0);

    }

    // GETTER
    get vertices() {

        return new Float32Array([
                this.pointA.X, this.pointA.Y * this.root.size, this.pointA.Z,

                this.pointB.X * this.root.size, this.pointB.Y * this.root.size, this.pointB.Z,

                this.pointC.X * this.root.size, this.pointC.Y * this.root.size, this.pointC.Z
            ]);

    }

    setScale(scale) {

        this.size = scale;

        if (this.dynamicBuffer == true)
            return;

        App.operation.triangle_buffer_procedure(this.root)

        return 'dynamicBuffer is false but i will update vertex array prototypical.';

    }

}

class Position {

    constructor(x, y, z) {
        //super()

        if (typeof x == 'undefined') {
            x = 0;
        }
        if (typeof y == 'undefined') {
            y = 0;
        }
        if (typeof z == 'undefined') {
            z = 0;
        }

        this.x = x;
        this.y = y;
        this.z = z;

        return this;

    }

    get worldLocation() {

        return [this.x, this.y, this.z];

    }

    SetX(newx) {

        this.x = newx;

    }

    SetY(newy) {

        this.y = newy;

    }

    SetZ(newz) {

        this.z = newz;

    }

    setPosition(newx, newy, newz) {

        this.x = newx;
        this.y = newy;
        this.z = newz;

    }

}```

Body:
I am wondering if there is a way to update and move a triangle in OpenGL ES using the vertices. These are the vertices of my triangle:

// in counterclockwise order :

static float triangleCoords[] = {
        0.0f,  0.622008459f, 0.0f,  // top
        -0.5f, -0.311004243f, 0.0f, // bottom left
        0.5f, -0.311004243f, 0.0f   // bottom right
};

I wanted to know if it was possible to move the triangle without the matrices.

Thank you!


问:
How to use generic type in a value tuple?
Let's presume i have two enums:

```<code>    public enum eFruits : int
    {
        Apple = 1,
        Pear = 2,
        Banana = 3
    }
</code>```

```<code>    public enum eAnimals : int
    {
        Dog = 1,
        Cat = 2,
        Rabbit = 3
    }
</code>```

I would like to use these in dropdownlists/checklists etc; basically as listitems. The current code i have as a tryout is this;

```<code>    public static class EnumHelper
    {
        public static IEnumerable<(int eCode, eFruits eType)> GetFruitTypesAsListItems()
        {
            var enums = new List<(int eCode, eFruits eType)>();
            foreach (var item in (eFruits[])Enum.GetValues(typeof(eFruits)))
            {
                enums.Add(((int)item, item));
            }
            return enums;
        }
    }
</code>```

Two issues with this;

1) I would like to have this in a generic way

2) It doesn't look nice inside a list/dropdown etc. so I'd like to use a ToString override.

Therefore I thought of something like this:

```<code>    public class EnumListItem : Tuple<int, T>
    {
        public EnumListItem(int eCode, T eType)
            : base(eCode, eType)
        { }

        public override string ToString() => $"{base.Item2.ToString()} ({base.Item1})";
    }
</code>```

So in effect;

1) I would like to use a Generic with a Tuple

2) Would like to use a Generic to be able to generate list items based on that Tuple

Is this possible? I'm not sure how the declaration of this would look like. At this point I can't get it to work. Can someone point me in the right direction?

答:
It is quite simple to make it a generic function. And you could use yield to return a generator enumerable instead of a buffered List to get rid of unnecessary use of memory.

```<code>public static IEnumerable<(int, TEnum)> GetValues<TEnum>()
where TEnum : struct, Enum
{
    foreach (var item in Enum.GetValues(typeof(TEnum)))
    {
        yield return ((int)item, (TEnum)item);
    }
}
</code>```

Body:
Let's presume i have two enums:

    public enum eFruits : int
    {
        Apple = 1,
        Pear = 2,
        Banana = 3
    }

    public enum eAnimals : int
    {
        Dog = 1,
        Cat = 2,
        Rabbit = 3
    }

I would like to use these in dropdownlists/checklists etc; basically as listitems. The current code i have as a tryout is this;

    public static class EnumHelper
    {
        public static IEnumerable<(int eCode, eFruits eType)> GetFruitTypesAsListItems()
        {
            var enums = new List<(int eCode, eFruits eType)>();
            foreach (var item in (eFruits[])Enum.GetValues(typeof(eFruits)))
            {
                enums.Add(((int)item, item));
            }
            return enums;
        }
    }

Two issues with this;

1) I would like to have this in a generic way

2) It doesn't look nice inside a list/dropdown etc. so I'd like to use a ToString override.

Therefore I thought of something like this:

    public class EnumListItem : Tuple<int, T>
    {
        public EnumListItem(int eCode, T eType)
            : base(eCode, eType)
        { }

        public override string ToString() => $"{base.Item2.ToString()} ({base.Item1})";
    }

So in effect;

1) I would like to use a Generic with a Tuple

2) Would like to use a Generic to be able to generate list items based on that Tuple

Is this possible? I'm not sure how the declaration of this would look like. At this point I can't get it to work. Can someone point me in the right direction?

Body:
It is quite simple to make it a generic function. And you could use yield to return a generator enumerable instead of a buffered List to get rid of unnecessary use of memory.

public static IEnumerable<(int, TEnum)> GetValues<TEnum>()
where TEnum : struct, Enum
{
    foreach (var item in Enum.GetValues(typeof(TEnum)))
    {
        yield return ((int)item, (TEnum)item);
    }
}


答:
Of course, I can get compiled if I don't expicitly delete the interface, but that is not my purpose. I'd like to expicitly delete it, to avoid unexpected using it.

You cannot unexpectedly use something which does not exist. If your class defines ClassA & operator=( const ClassA & ), then ClassA & operator=( ClassA & ) will not exist at all (the compiler will not generate that). There's no reason to provide & delete it.

Title: Why GCC refuses a const reference within a copy-assignment operation?


问:
Ubuntu, how to install OpenCV for python3?
I want to install OpenCV for python3 in ubuntu 16.04.  Fist I tried running sudo apt-get install python3-opencv which is how I pretty much install all of my python software.  This could not find a repository.  The install does work however if I do sudo apt-get install python-opencv this issue with this is that by not adding the three to python it installs for python 2 which I do not use.  I would really perfer not to have to build and install from source so is there a way I can get a repository?  I also tried installing it with pip3 and it could not find it either.

答:
Assuming that you installed Python3.x, I resolved it using the following:

1: Install side packages required for OpenCV with Ubuntu (only validated for: Ubuntu 16.04):

```<code>apt-get update
apt-get install -y libglib2.0.0 libsm6
apt-get install libxext6
apt-get install -y libxrender-dev
</code>```

2: Install OpenCV on python3.x:

```<code>pip3 install opencv-contrib-python
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Assuming that you installed Python3.x, I resolved it using the following:

1: Install side packages required for OpenCV with Ubuntu (only validated for: Ubuntu 16.04):

apt-get update
apt-get install -y libglib2.0.0 libsm6
apt-get install libxext6
apt-get install -y libxrender-dev

2: Install OpenCV on python3.x:

pip3 install opencv-contrib-python


问:
Lag() with condition in sql server
i have a table like this:

```<code>Number   Price    Type       Date         Time
------   -----    ----    ----------    ---------
23456    0,665     SV     2014/02/02     08:00:02
23457    1,3       EC     2014/02/02     07:50:45
23460    0,668     SV     2014/02/02     07:36:34
</code>```

For each EC I need previous/next SV price. In this case, the query is simple.

```<code>Select Lag(price, 1, price) over (order by date desc, time desc),
Lead(price, 1, price) over (order by date desc, time desc)
from ITEMS
</code>```

But, there are some special cases where two or more rows are EC type:

```<code>Number   Price    Type       Date         Time
------   -----    ----    ----------    ---------
23456    0,665     SV     2014/02/02     08:00:02
23457    1,3       EC     2014/02/02     07:50:45
23658    2,4       EC     2014/02/02     07:50:45
23660    2,4       EC     2014/02/02     07:50:48
23465    0,668     SV     2014/02/02     07:36:34
</code>```

can I use Lead/Lag in this cases? If not, did I have to use a subquery?

答:
Here is yet another way of achieving the same result, but using conditional max/min functions windowed over an ordinal. The ordinal can be be set up based on whatever columns fits the purpose, but in this case I believe the OP intends them to be Date and Time.

```<code>DROP TABLE IF EXISTS #t;
CREATE TABLE #t (
    Number INT,
    Price MONEY,
    Type CHAR(2),
    Date DATE,
    Time TIME(0)
);
INSERT INTO #t VALUES
(23456, 0.666, 'SV', '2014/02/02', '10:00:02'),
(23457, 1.4  , 'EC', '2014/02/02', '09:50:45'),
(23658, 2.5  , 'EC', '2014/02/02', '09:50:45'),
(23660, 2.5  , 'EC', '2014/02/02', '09:50:48'),
(23465, 0.669, 'SV', '2014/02/02', '09:36:34'),
(23456, 0.665, 'SV', '2014/02/02', '08:00:02'),
(23457, 1.3  , 'EC', '2014/02/02', '07:50:45'),
(23658, 2.4  , 'EC', '2014/02/02', '07:50:45'),
(23660, 2.4  , 'EC', '2014/02/02', '07:50:48'),
(23465, 0.668, 'SV', '2014/02/02', '07:36:34'), -- which one of these?
(23465, 0.670, 'SV', '2014/02/02', '07:36:34'); --

WITH time_ordered AS (
    SELECT *, DENSE_RANK() OVER (ORDER BY Date, Time) AS ordinal FROM #t
)
SELECT
    *,
    CASE WHEN Type = 'EC'
    THEN MAX(CASE WHEN ordinal = preceding_non_EC_ordinal THEN Price END)
    OVER (PARTITION BY preceding_non_EC_ordinal ORDER BY ordinal ASC) END AS preceding_price,
    CASE WHEN Type = 'EC'
    THEN MIN(CASE WHEN ordinal = following_non_EC_ordinal THEN Price END)
    OVER (PARTITION BY following_non_EC_ordinal ORDER BY ordinal DESC) END AS following_price
FROM (
    SELECT
        *,
        MAX(CASE WHEN Type <> 'EC' THEN ordinal END)
        OVER (ORDER BY ordinal ASC) AS preceding_non_EC_ordinal,
        MIN(CASE WHEN Type <> 'EC' THEN ordinal END)
        OVER (ORDER BY ordinal DESC) AS following_non_EC_ordinal
    FROM time_ordered
) t
ORDER BY Date, Time
</code>```

Note that the example given by the OP has been extended to show that interspersed sequences of EC yeild the intended result. The ambiguity introduced by the earliest two consecutive rows with type SV will in this case lead to the maximum value being picked. Setting up the ordinal to include the Price is a possible way to change this behavior.

An SQLFiddle can be found here: http://sqlfiddle.com/#!18/85117/1

Title: Lag() with condition in sql server

Body:
i have a table like this:

Number   Price    Type       Date         Time
------   -----    ----    ----------    ---------
23456    0,665     SV     2014/02/02     08:00:02
23457    1,3       EC     2014/02/02     07:50:45
23460    0,668     SV     2014/02/02     07:36:34

For each EC I need previous/next SV price. In this case, the query is simple.

Select Lag(price, 1, price) over (order by date desc, time desc),
Lead(price, 1, price) over (order by date desc, time desc)
from ITEMS

But, there are some special cases where two or more rows are EC type:

Number   Price    Type       Date         Time
------   -----    ----    ----------    ---------
23456    0,665     SV     2014/02/02     08:00:02
23457    1,3       EC     2014/02/02     07:50:45
23658    2,4       EC     2014/02/02     07:50:45
23660    2,4       EC     2014/02/02     07:50:48
23465    0,668     SV     2014/02/02     07:36:34

can I use Lead/Lag in this cases? If not, did I have to use a subquery?

Body:
Here is yet another way of achieving the same result, but using conditional max/min functions windowed over an ordinal. The ordinal can be be set up based on whatever columns fits the purpose, but in this case I believe the OP intends them to be Date and Time.

DROP TABLE IF EXISTS #t;
CREATE TABLE #t (
    Number INT,
    Price MONEY,
    Type CHAR(2),
    Date DATE,
    Time TIME(0)
);
INSERT INTO #t VALUES
(23456, 0.666, 'SV', '2014/02/02', '10:00:02'),
(23457, 1.4  , 'EC', '2014/02/02', '09:50:45'),
(23658, 2.5  , 'EC', '2014/02/02', '09:50:45'),
(23660, 2.5  , 'EC', '2014/02/02', '09:50:48'),
(23465, 0.669, 'SV', '2014/02/02', '09:36:34'),
(23456, 0.665, 'SV', '2014/02/02', '08:00:02'),
(23457, 1.3  , 'EC', '2014/02/02', '07:50:45'),
(23658, 2.4  , 'EC', '2014/02/02', '07:50:45'),
(23660, 2.4  , 'EC', '2014/02/02', '07:50:48'),
(23465, 0.668, 'SV', '2014/02/02', '07:36:34'), -- which one of these?
(23465, 0.670, 'SV', '2014/02/02', '07:36:34'); --

WITH time_ordered AS (
    SELECT *, DENSE_RANK() OVER (ORDER BY Date, Time) AS ordinal FROM #t
)
SELECT
    *,
    CASE WHEN Type = 'EC'
    THEN MAX(CASE WHEN ordinal = preceding_non_EC_ordinal THEN Price END)
    OVER (PARTITION BY preceding_non_EC_ordinal ORDER BY ordinal ASC) END AS preceding_price,
    CASE WHEN Type = 'EC'
    THEN MIN(CASE WHEN ordinal = following_non_EC_ordinal THEN Price END)
    OVER (PARTITION BY following_non_EC_ordinal ORDER BY ordinal DESC) END AS following_price
FROM (
    SELECT
        *,
        MAX(CASE WHEN Type <> 'EC' THEN ordinal END)
        OVER (ORDER BY ordinal ASC) AS preceding_non_EC_ordinal,
        MIN(CASE WHEN Type <> 'EC' THEN ordinal END)
        OVER (ORDER BY ordinal DESC) AS following_non_EC_ordinal
    FROM time_ordered
) t
ORDER BY Date, Time

Note that the example given by the OP has been extended to show that interspersed sequences of EC yeild the intended result. The ambiguity introduced by the earliest two consecutive rows with type SV will in this case lead to the maximum value being picked. Setting up the ordinal to include the Price is a possible way to change this behavior.

An SQLFiddle can be found here: http://sqlfiddle.com/#!18/85117/1


问:
How to fix import ssl error in Apache server(Windows)
I'm trying to design a RESTful API with a Flask app using mod_wsgi on an Apache server, and I'm getting an error with importing the ssl module in the Apache server.
I have installed Apache 2.4 from https://www.apachelounge.com/download/, and mod_wsgi using pip, configured it in the Apache server.

I created a simple Flask app:

```<code>    from flask import Flask   '
app = Flask(__name__)
    @app.route("/")
    def hello():
        return "Hello World"
    if __name__ == "__main__":
        app.run()
</code>```

I created a web.wsgi file:

```<code>    import sys
sys.path.insert(0, 'C:/Users/chant/myapp')
from final_app import app as application
</code>```

and used it to configure a virtual host for the Flask App, by pasting the following code in http-vhosts.conf:

```<code><VirtualHost *:5000>
    ServerName  localhost
    WSGIScriptAlias / "C:/Users/chant/myapp/web.wsgi"
    DocumentRoot "C:/Users/chant/myapp"
ErrorLog "C:/Users/chant/myapp/logs/error.log"
    CustomLog "C:/Users/chant/myapp/logs/access.log" common
</code>```

My error log shows:

```<code>    File "c:\\programdata\\anaconda3\\Lib\\ssl.py", line 98, in <module>\r
    import _ssl             # if we can't import it, let the error propagate\r
ImportError: DLL load failed: The specified module could not be found.\r
</code>```

Though I tried testing the import module and it ran in python, though it is not importing in the Apache server.

If anyone has any suggestions, it would be most appreciated.

答:
I noticed later that an important part of the deployment of the Flask app is that Python should be installed for all users, else Apache server is not able to import the ssl module.

Hope this helps!

Body:
I'm trying to design a RESTful API with a Flask app using mod_wsgi on an Apache server, and I'm getting an error with importing the ssl module in the Apache server.
I have installed Apache 2.4 from https://www.apachelounge.com/download/, and mod_wsgi using pip, configured it in the Apache server.

I created a simple Flask app:

    from flask import Flask   '
app = Flask(__name__)
    @app.route("/")
    def hello():
        return "Hello World"
    if __name__ == "__main__":
        app.run()

I created a web.wsgi file:

    import sys
sys.path.insert(0, 'C:/Users/chant/myapp')
from final_app import app as application

and used it to configure a virtual host for the Flask App, by pasting the following code in http-vhosts.conf:

<VirtualHost *:5000>
    ServerName  localhost
    WSGIScriptAlias / "C:/Users/chant/myapp/web.wsgi"
    DocumentRoot "C:/Users/chant/myapp"
ErrorLog "C:/Users/chant/myapp/logs/error.log"
    CustomLog "C:/Users/chant/myapp/logs/access.log" common

My error log shows:

    File "c:\\programdata\\anaconda3\\Lib\\ssl.py", line 98, in <module>\r
    import _ssl             # if we can't import it, let the error propagate\r
ImportError: DLL load failed: The specified module could not be found.\r

Though I tried testing the import module and it ran in python, though it is not importing in the Apache server.

If anyone has any suggestions, it would be most appreciated.


问:
changing a property value in an array
when i try to assign a new value to an array property i get the error :
Cannot assign to property: 'color' is a 'let' constant

```<code>struct car {
    let model: String
    let color: String
}

var myCars :[car] = [
    car(name:"model X", color: "black"),
    car(name:"model Y", color: "blue"),
    car(name:"roadster", color: "red"),
    car(name:"model S", color: "black"),
    car(name:"model 3", color: "black")
]

let colorFilter = dataSource.items.index(where: {$0.color == "black"})
myCars[colorFilter].color = "grey"

</code>```

replace all the items with color property set to "black" with "grey"

答:
Since color is a constant (let) property, i.e. once initialised you cannot change its value. In case you want to modify the value of color, make it var instead of let

```<code>struct car {
    let model: String
    var color: String
}
</code>```

To update the color of all cars from black to grey, use map(_:) on myCars array.

```<code>myCars = myCars.map {
    var newCar = $0
    if newCar.color == "black" {
        newCar.color = "grey"
    }
    return newCar
}
</code>```

Output:

```<code>print(myCars)

// [car(model: "model X", color: "grey"), car(model: "model Y", color: "blue"), car(model: "roadster", color: "red"), car(model: "model S", color: "grey"), car(model: "model 3", color: "grey")]
</code>```

Title: changing a property value in an array

Body:
when i try to assign a new value to an array property i get the error :
Cannot assign to property: 'color' is a 'let' constant

struct car {
    let model: String
    let color: String
}

var myCars :[car] = [
    car(name:"model X", color: "black"),
    car(name:"model Y", color: "blue"),
    car(name:"roadster", color: "red"),
    car(name:"model S", color: "black"),
    car(name:"model 3", color: "black")
]

let colorFilter = dataSource.items.index(where: {$0.color == "black"})
myCars[colorFilter].color = "grey"

replace all the items with color property set to "black" with "grey"

Body:
Since color is a constant (let) property, i.e. once initialised you cannot change its value. In case you want to modify the value of color, make it var instead of let

struct car {
    let model: String
    var color: String
}

To update the color of all cars from black to grey, use map(_:) on myCars array.

myCars = myCars.map {
    var newCar = $0
    if newCar.color == "black" {
        newCar.color = "grey"
    }
    return newCar
}

Output:

print(myCars)

// [car(model: "model X", color: "grey"), car(model: "model Y", color: "blue"), car(model: "roadster", color: "red"), car(model: "model S", color: "grey"), car(model: "model 3", color: "grey")]


问:
How to plot ordered horizontal bars
I have a list of values that I want to plot ordered in a horizontal bar plot with indices in y-axis and values in x-axis. This is the code I have, it outputs unordered bars.</p>

```<code>        plt.barh(indices,values)
        plt.xlabel('Value', fontsize=12)
        plt.ylabel('Value Label', fontsize=12)
        plt.yticks(indices, listOflabels, rotation='horizontal')
        plt.tight_layout()
        plt.title('horizontal ranked bar plot')
        plt.show()
</code>```

答:
Try to do an np.argsort on values:

```<code>idx = np.argsort(values)
plt.barh(indices,values[idx])
plt.xlabel('Value', fontsize=12)
plt.ylabel('Value Label', fontsize=12)
plt.yticks(indices, listOflabels[idx], rotation='horizontal')
plt.tight_layout()
plt.title('horizontal ranked bar plot')
plt.show()
</code>```

Title: How to plot ordered horizontal bars

Body:
I have a list of values that I want to plot ordered in a horizontal bar plot with indices in y-axis and values in x-axis. This is the code I have, it outputs unordered bars.

        plt.barh(indices,values)
        plt.xlabel('Value', fontsize=12)
        plt.ylabel('Value Label', fontsize=12)
        plt.yticks(indices, listOflabels, rotation='horizontal')
        plt.tight_layout()
        plt.title('horizontal ranked bar plot')
        plt.show()

Body:
Try to do an np.argsort on values:

idx = np.argsort(values)
plt.barh(indices,values[idx])
plt.xlabel('Value', fontsize=12)
plt.ylabel('Value Label', fontsize=12)
plt.yticks(indices, listOflabels[idx], rotation='horizontal')
plt.tight_layout()
plt.title('horizontal ranked bar plot')
plt.show()


问:
Uncaught (in promise): Error: Can't resolve all parameters for LocalStorageService
I try to upgrade to latest Angular, and I got the error on my component and going to URL /login

it something like this :
ERROR Error: "Uncaught (in promise): Error: Can't resolve all parameters for LocalStorageService: (?).

my pages/login/login.component something like this :

```<code>import { Component, OnInit } from "@angular/core";
import { LocalStorageService } from "ngx-webstorage";
import { Router } from "@angular/router";
import { NgForm } from "@angular/forms";
import {
  SnotifyService,
  SnotifyPosition,
  SnotifyToastConfig
} from "ng-snotify";

import { AuthenticationService }
  constructor(
    private authenticationService: AuthenticationService,
    private router: Router,
    private localStorageService: LocalStorageService,
    private snotifyService: SnotifyService
  ) {}
</code>```

and on pages/login/login.module

```<code>import { NgModule } from "@angular/core";
import { RouterModule, Routes } from "@angular/router";
import { CommonModule } from "@angular/common";
import { LoginComponent } from "./login.component";
import { AuthService } from "../../../services/base-services/auth.service";
import { AuthenticationService } from "../../../services/authentication.service";
import { SnotifyModule, SnotifyService, ToastDefaults } from "ng-snotify";
import { FormsModule } from "@angular/forms";
import { LocalStorageService } from "ngx-webstorage";

export const LoginRoutes: Routes = [
  {
    path: "",
    data: {
      breadcrumb: "Login"
    },
    children: [
      {
        path: "",
        component: LoginComponent,
        data: {
          breadcrumb: "Login"
        }
      }
    ]
  }
];

@NgModule({
  declarations: [LoginComponent],
  imports: [
    CommonModule,
    RouterModule.forChild(LoginRoutes),
    SnotifyModule,
    FormsModule
  ],
  providers: [
    LocalStorageService,
    AuthenticationService,
    AuthService,
    SnotifyService,
    { provide: "SnotifyToastConfig", useValue: ToastDefaults }
  ]
})
export class LoginModule {}
</code>```

and on my app.module is something like this

```<code>import { BrowserModule } from "@angular/platform-browser";
import { NgModule } from "@angular/core";
import { AuthComponent } from "./layout/auth/auth.component";
import { HttpClientModule } from "@angular/common/http";
import { AuthGuardService } from "./services/base-services/auth-guard.service";
import { AuthenticationService } from "./services/authentication.service";
import { BreadcrumbsComponent } from "./layout/admin/breadcrumbs/breadcrumbs.component";
import { FormsModule } from "@angular/forms";

import { AppRoutingModule } from "./app-routing.module";
import { AppComponent } from "./app.component";

@NgModule({
  declarations: [AppComponent, AuthComponent, BreadcrumbsComponent],
  imports: [BrowserModule, AppRoutingModule, FormsModule, HttpClientModule],
  providers: [AuthGuardService, AuthenticationService],
  bootstrap: [AppComponent]
})
export class AppModule {}
</code>```

is there something wrong for import and put services on my files ?? or any missing syntax on my component ??

my package.json

```<code>{
  "name": "kontrak-hukum-front-end",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@agm/core": "^1.0.0-beta.5",
    "@angular/animations": "^8.0.0-rc.4",
    "@angular/common": "^8.0.0-rc.4",
    "@angular/compiler": "^8.0.0-rc.4",
    "@angular/core": "^8.0.0-rc.4",
    "@angular/forms": "^8.0.0-rc.4",
    "@angular/platform-browser": "^8.0.0-rc.4",
    "@angular/platform-browser-dynamic": "^8.0.0-rc.4",
    "@angular/platform-server": "^8.0.0-rc.4",
    "@angular/router": "^8.0.0-rc.4",
    "@fortawesome/angular-fontawesome": "^0.3.0",
    "@ng-bootstrap/ng-bootstrap": "^4.1.3",
    "@ng-select/ng-select": "^2.20.0",
    "@nicky-lenaers/ngx-scroll-to": "^2.0.0",
    "@swimlane/ngx-datatable": "^14.0.0",
    "@types/googlemaps": "^3.36.0",
    "angular-2-local-storage": "^3.0.2",
    "angular-froala-wysiwyg": "^3.0.0-beta.1",
    "angular-io-slimscroll": "^2.3.3",
    "angular2-chartjs": "^0.5.1",
    "angular2-datatable": "^0.6.0",
    "angular2-material-datepicker": "^0.5.0",
    "angular2-notifications": "^2.0.0",
    "angular2-wizard": "^0.4.0",
    "bootstrap": "^4.3.1",
    "c3": "^0.7.0",
    "core-js": "^3.1.2",
    "css-animator": "^2.3.1",
    "d3": "^5.9.2",
    "echarts": "^4.2.1",
    "famfamfam-flags": "^1.0.0",
    "font-awesome": "^4.7.0",
    "jquery": "^3.4.1",
    "jquery-sparkline": "^2.4.0",
    "ng-auto-complete": "^4.1.7",
    "ng-click-outside": "^4.0.0",
    "ng-snotify": "^4.3.1",
    "ng2-auto-complete": "^0.12.0",
    "ng2-ckeditor": "^1.2.2",
    "ng2-currency-mask": "^5.3.1",
    "ng2-file-upload": "^1.3.0",
    "ng2-google-charts": "^4.0.0",
    "ng2-nvd3": "^2.0.0",
    "ng2-order-pipe": "^0.1.5",
    "ng2-search-filter": "^0.5.1",
    "ng2-toasty": "^4.0.3",
    "ng2-ui-switch": "^1.0.2",
    "ng2-validation": "^4.2.0",
    "ngx-bootstrap": "^4.3.0",
    "ngx-chips": "^2.0.0-beta.0",
    "ngx-color-picker": "^7.5.0",
    "ngx-echarts": "^4.1.1",
    "ngx-order-pipe": "^2.0.2",
    "ngx-pagination": "^3.2.1",
    "ngx-quill": "^5.1.0",
    "ngx-quill-editor": "^2.2.2",
    "ngx-webstorage": "^3.0.2",
    "npm": "^6.9.0",
    "peity": "^3.3.0",
    "rxjs": "^6.5.2",
    "screenfull": "^4.2.0",
    "squeezebox": "^1.4.1",
    "sweetalert2": "^8.11.4",
    "ti-icons": "^0.1.2",
    "tslib": "^1.9.0",
    "wijmo": "^5.20191.606",
    "zone.js": "~0.9.1"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "~0.800.0-rc.4",
    "@angular/cli": "^8.0.0-rc.4",
    "@angular/compiler-cli": "^8.0.0-rc.4",
    "@angular/language-service": "^8.0.0-rc.4",
    "@types/jasmine": "~3.3.12",
    "@types/jasminewd2": "~2.0.3",
    "@types/node": "~12.0.2",
    "codelyzer": "^5.0.1",
    "jasmine-core": "~3.4.0",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "~4.1.0",
    "karma-chrome-launcher": "~2.2.0",
    "karma-coverage-istanbul-reporter": "~2.0.1",
    "karma-jasmine": "~2.0.1",
    "karma-jasmine-html-reporter": "^1.4.2",
    "protractor": "~5.4.0",
    "ts-node": "~8.1.0",
    "tslint": "~5.11.0",
    "typescript": "3.4.5"
  }
}
</code>```

答: It seems that ngx-webstorage does not yet support Angular 8.x.x. There is already a pull request on github to change that. I can't think of anything else, as long as you run the application in a browser.

Body:
I try to upgrade to latest Angular, and I got the error on my component and going to URL /login

it something like this :
ERROR Error: "Uncaught (in promise): Error: Can't resolve all parameters for LocalStorageService: (?).

my pages/login/login.component something like this :

import { Component, OnInit } from "@angular/core";
import { LocalStorageService } from "ngx-webstorage";
import { Router } from "@angular/router";
import { NgForm } from "@angular/forms";
import {
  SnotifyService,
  SnotifyPosition,
  SnotifyToastConfig
} from "ng-snotify";

import { AuthenticationService }
  constructor(
    private authenticationService: AuthenticationService,
    private router: Router,
    private localStorageService: LocalStorageService,
    private snotifyService: SnotifyService
  ) {}

and on pages/login/login.module

import { NgModule } from "@angular/core";
import { RouterModule, Routes } from "@angular/router";
import { CommonModule } from "@angular/common";
import { LoginComponent } from "./login.component";
import { AuthService } from "../../../services/base-services/auth.service";
import { AuthenticationService } from "../../../services/authentication.service";
import { SnotifyModule, SnotifyService, ToastDefaults } from "ng-snotify";
import { FormsModule } from "@angular/forms";
import { LocalStorageService } from "ngx-webstorage";

export const LoginRoutes: Routes = [
  {
    path: "",
    data: {
      breadcrumb: "Login"
    },
    children: [
      {
        path: "",
        component: LoginComponent,
        data: {
          breadcrumb: "Login"
        }
      }
    ]
  }
];

@NgModule({
  declarations: [LoginComponent],
  imports: [
    CommonModule,
    RouterModule.forChild(LoginRoutes),
    SnotifyModule,
    FormsModule
  ],
  providers: [
    LocalStorageService,
    AuthenticationService,
    AuthService,
    SnotifyService,
    { provide: "SnotifyToastConfig", useValue: ToastDefaults }
  ]
})
export class LoginModule {}

and on my app.module is something like this

import { BrowserModule } from "@angular/platform-browser";
import { NgModule } from "@angular/core";
import { AuthComponent } from "./layout/auth/auth.component";
import { HttpClientModule } from "@angular/common/http";
import { AuthGuardService } from "./services/base-services/auth-guard.service";
import { AuthenticationService } from "./services/authentication.service";
import { BreadcrumbsComponent } from "./layout/admin/breadcrumbs/breadcrumbs.component";
import { FormsModule } from "@angular/forms";

import { AppRoutingModule } from "./app-routing.module";
import { AppComponent } from "./app.component";

@NgModule({
  declarations: [AppComponent, AuthComponent, BreadcrumbsComponent],
  imports: [BrowserModule, AppRoutingModule, FormsModule, HttpClientModule],
  providers: [AuthGuardService, AuthenticationService],
  bootstrap: [AppComponent]
})
export class AppModule {}

is there something wrong for import and put services on my files ?? or any missing syntax on my component ??

my package.json

{
  "name": "kontrak-hukum-front-end",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@agm/core": "^1.0.0-beta.5",
    "@angular/animations": "^8.0.0-rc.4",
    "@angular/common": "^8.0.0-rc.4",
    "@angular/compiler": "^8.0.0-rc.4",
    "@angular/core": "^8.0.0-rc.4",
    "@angular/forms": "^8.0.0-rc.4",
    "@angular/platform-browser": "^8.0.0-rc.4",
    "@angular/platform-browser-dynamic": "^8.0.0-rc.4",
    "@angular/platform-server": "^8.0.0-rc.4",
    "@angular/router": "^8.0.0-rc.4",
    "@fortawesome/angular-fontawesome": "^0.3.0",
    "@ng-bootstrap/ng-bootstrap": "^4.1.3",
    "@ng-select/ng-select": "^2.20.0",
    "@nicky-lenaers/ngx-scroll-to": "^2.0.0",
    "@swimlane/ngx-datatable": "^14.0.0",
    "@types/googlemaps": "^3.36.0",
    "angular-2-local-storage": "^3.0.2",
    "angular-froala-wysiwyg": "^3.0.0-beta.1",
    "angular-io-slimscroll": "^2.3.3",
    "angular2-chartjs": "^0.5.1",
    "angular2-datatable": "^0.6.0",
    "angular2-material-datepicker": "^0.5.0",
    "angular2-notifications": "^2.0.0",
    "angular2-wizard": "^0.4.0",
    "bootstrap": "^4.3.1",
    "c3": "^0.7.0",
    "core-js": "^3.1.2",
    "css-animator": "^2.3.1",
    "d3": "^5.9.2",
    "echarts": "^4.2.1",
    "famfamfam-flags": "^1.0.0",
    "font-awesome": "^4.7.0",
    "jquery": "^3.4.1",
    "jquery-sparkline": "^2.4.0",
    "ng-auto-complete": "^4.1.7",
    "ng-click-outside": "^4.0.0",
    "ng-snotify": "^4.3.1",
    "ng2-auto-complete": "^0.12.0",
    "ng2-ckeditor": "^1.2.2",
    "ng2-currency-mask": "^5.3.1",
    "ng2-file-upload": "^1.3.0",
    "ng2-google-charts": "^4.0.0",
    "ng2-nvd3": "^2.0.0",
    "ng2-order-pipe": "^0.1.5",
    "ng2-search-filter": "^0.5.1",
    "ng2-toasty": "^4.0.3",
    "ng2-ui-switch": "^1.0.2",
    "ng2-validation": "^4.2.0",
    "ngx-bootstrap": "^4.3.0",
    "ngx-chips": "^2.0.0-beta.0",
    "ngx-color-picker": "^7.5.0",
    "ngx-echarts": "^4.1.1",
    "ngx-order-pipe": "^2.0.2",
    "ngx-pagination": "^3.2.1",
    "ngx-quill": "^5.1.0",
    "ngx-quill-editor": "^2.2.2",
    "ngx-webstorage": "^3.0.2",
    "npm": "^6.9.0",
    "peity": "^3.3.0",
    "rxjs": "^6.5.2",
    "screenfull": "^4.2.0",
    "squeezebox": "^1.4.1",
    "sweetalert2": "^8.11.4",
    "ti-icons": "^0.1.2",
    "tslib": "^1.9.0",
    "wijmo": "^5.20191.606",
    "zone.js": "~0.9.1"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "~0.800.0-rc.4",
    "@angular/cli": "^8.0.0-rc.4",
    "@angular/compiler-cli": "^8.0.0-rc.4",
    "@angular/language-service": "^8.0.0-rc.4",
    "@types/jasmine": "~3.3.12",
    "@types/jasminewd2": "~2.0.3",
    "@types/node": "~12.0.2",
    "codelyzer": "^5.0.1",
    "jasmine-core": "~3.4.0",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "~4.1.0",
    "karma-chrome-launcher": "~2.2.0",
    "karma-coverage-istanbul-reporter": "~2.0.1",
    "karma-jasmine": "~2.0.1",
    "karma-jasmine-html-reporter": "^1.4.2",
    "protractor": "~5.4.0",
    "ts-node": "~8.1.0",
    "tslint": "~5.11.0",
    "typescript": "3.4.5"
  }
}


问:
Highcharts. Dynamic labels inside donut chart on mouseOver
so this is what I'm trying to acomplish:
Example

What I need is:

Label inside donut chart changing on mouse over

Color depending on data

Styling label to look like the picture

I actually managed to do the mouse over but I can't change the color according to data and place it in the middle

Here is a fiddle: https://jsfiddle.net/9cjxb97a/1/

Here is the code I wrote so far:

```<code>    Highcharts.chart('container', {
  chart: {
    plotBackgroundColor: null,
    plotBorderWidth: null,
    plotShadow: false,
    type: 'pie'
  },
  title: {
    text: ''
  },
  exporting: {
    enabled: false
  },
  tooltip: {
    enabled: false
  },
  colors: ['red', 'blue', 'green'],
  plotOptions: {
    pie: {
      allowPointSelect: true,
      cursor: 'pointer',
      dataLabels: {
        enabled: false,
        format: '<b>{point.name}</b>: {point.percentage:.1f} %',
        style: {
          color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black'
        }
      }
    },
    series: {
      point: {
        events: {
          mouseOver: function() {
            var chart = this.series.chart;
            if (!chart.lbl) {
              chart.lbl = chart.renderer.label('')
                .attr({
                  padding: 10,
                })
                .css({
                  color: 'red',
                })
                .add();
            }
            chart.lbl
              .show()
              .attr({
                text: this.y + '%'
              });
          }
        }
      },

    },
  },
  series: [{
    name: 'Brands',
    colorByPoint: true,
    data: [{
      name: 'Microsoft Internet Explorer',
      y: 56.33
    }, {
      name: 'Chrome',
      y: 24.03,

    }, {
      name: 'Firefox',
      y: 10.38
    }, {
      name: 'Safari',
      y: 4.77
    }, {
      name: 'Opera',
      y: 0.91
    }, {
      name: 'Proprietary or Undetectable',
      y: 0.2
    }],
    innerSize: '80%'
  }],

});
</code>```

Thanks

答:
Here's your code to display value in between circle.</p>

```<code> Highcharts.chart('container', {
chart: {
    plotBackgroundColor: null,
    plotBorderWidth: null,
    plotShadow: false,
    type: 'pie'
},
title: {
    text: ''
},
exporting:{
enabled:false
},
tooltip: {
    enabled:false
},
   colors:['red', 'blue', 'green'],
plotOptions: {
    pie: {
        allowPointSelect: true,
        cursor: 'pointer',
        dataLabels: {
            enabled: false,
            format: '<b>{point.name}</b>: {point.percentage:.1f} %',
            style: {
                color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black'
            }
        }
    },
     series: {
    point: {
        events: {
            mouseOver: function () {
                var chart = this.series.chart;
                if (!chart.lbl) {
                    chart.lbl = chart.renderer.label('')
                        .attr({
                            padding: 10,
                        })
                        .css({
                            color: 'red',
                        })
                        .add();
                }
                chart.lbl
                    .show()
                    .attr({
                        text: this.y + '%'
                    });
            }
        }
    },

},
},
 tooltip: {
          borderWidth: 0,
          backgroundColor: 'none',
          headerFormat: '',
          shadow: false,
          style: {
              fontSize: '16px'
          },
          pointFormat: '<span style="font-size:40px;color:black; font-weight: bold">{point.y}%</span><br><span>50 Kg</span>{point.custom.customParam}',
          positioner: function (labelWidth) {
              return {
                  x: (this.chart.chartWidth - labelWidth) / 2,
                  y: this.chart.plotHeight/2
              };
          }
      },
series: [{
    name: 'Brands',
    colorByPoint: true,
    data: [{
        name: 'Microsoft Internet Explorer',
        y: 56.33
    }, {
        name: 'Chrome',
        y: 24.03,

    }, {
        name: 'Firefox',
        y: 10.38
    }, {
        name: 'Safari',
        y: 4.77
    }, {
        name: 'Opera',
        y: 0.91
    }, {
        name: 'Proprietary or Undetectable',
        y: 0.2
    }],
    innerSize:'80%'
}],

});
</code>```

Body:
so this is what I'm trying to acomplish:
Example

What I need is:

Label inside donut chart changing on mouse over

Color depending on data

Styling label to look like the picture

I actually managed to do the mouse over but I can't change the color according to data and place it in the middle

Here is a fiddle: https://jsfiddle.net/9cjxb97a/1/

Here is the code I wrote so far:

    Highcharts.chart('container', {
  chart: {
    plotBackgroundColor: null,
    plotBorderWidth: null,
    plotShadow: false,
    type: 'pie'
  },
  title: {
    text: ''
  },
  exporting: {
    enabled: false
  },
  tooltip: {
    enabled: false
  },
  colors: ['red', 'blue', 'green'],
  plotOptions: {
    pie: {
      allowPointSelect: true,
      cursor: 'pointer',
      dataLabels: {
        enabled: false,
        format: '{point.name}: {point.percentage:.1f} %',
        style: {
          color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black'
        }
      }
    },
    series: {
      point: {
        events: {
          mouseOver: function() {
            var chart = this.series.chart;
            if (!chart.lbl) {
              chart.lbl = chart.renderer.label('')
                .attr({
                  padding: 10,
                })
                .css({
                  color: 'red',
                })
                .add();
            }
            chart.lbl
              .show()
              .attr({
                text: this.y + '%'
              });
          }
        }
      },

    },
  },
  series: [{
    name: 'Brands',
    colorByPoint: true,
    data: [{
      name: 'Microsoft Internet Explorer',
      y: 56.33
    }, {
      name: 'Chrome',
      y: 24.03,

    }, {
      name: 'Firefox',
      y: 10.38
    }, {
      name: 'Safari',
      y: 4.77
    }, {
      name: 'Opera',
      y: 0.91
    }, {
      name: 'Proprietary or Undetectable',
      y: 0.2
    }],
    innerSize: '80%'
  }],

});

Thanks

Body:
Here's your code to display value in between circle.

 Highcharts.chart('container', {
chart: {
    plotBackgroundColor: null,
    plotBorderWidth: null,
    plotShadow: false,
    type: 'pie'
},
title: {
    text: ''
},
exporting:{
enabled:false
},
tooltip: {
    enabled:false
},
   colors:['red', 'blue', 'green'],
plotOptions: {
    pie: {
        allowPointSelect: true,
        cursor: 'pointer',
        dataLabels: {
            enabled: false,
            format: '<b>{point.name}</b>: {point.percentage:.1f} %',
            style: {
                color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black'
            }
        }
    },
     series: {
    point: {
        events: {
            mouseOver: function () {
                var chart = this.series.chart;
                if (!chart.lbl) {
                    chart.lbl = chart.renderer.label('')
                        .attr({
                            padding: 10,
                        })
                        .css({
                            color: 'red',
                        })
                        .add();
                }
                chart.lbl
                    .show()
                    .attr({
                        text: this.y + '%'
                    });
            }
        }
    },

},
},
 tooltip: {
          borderWidth: 0,
          backgroundColor: 'none',
          headerFormat: '',
          shadow: false,
          style: {
              fontSize: '16px'
          },
          pointFormat: '<span style="font-size:40px;color:black; font-weight: bold">{point.y}%</span><br><span>50 Kg</span>{point.custom.customParam}',
          positioner: function (labelWidth) {
              return {
                  x: (this.chart.chartWidth - labelWidth) / 2,
                  y: this.chart.plotHeight/2
              };
          }
      },
series: [{
    name: 'Brands',
    colorByPoint: true,
    data: [{
        name: 'Microsoft Internet Explorer',
        y: 56.33
    }, {
        name: 'Chrome',
        y: 24.03,

    }, {
        name: 'Firefox',
        y: 10.38
    }, {
        name: 'Safari',
        y: 4.77
    }, {
        name: 'Opera',
        y: 0.91
    }, {
        name: 'Proprietary or Undetectable',
        y: 0.2
    }],
    innerSize:'80%'
}],

});


问:
Convert 4 level nested JSON file to 1 level nested with Python
I have the 4 level nested JSON file below, that I would like to normalize to a one level nesting:

Input file is like this:

```<code>{
    "@index": "40",
    "row": [
      {
        "column": [
          {
            "text": {
              "@fontName": "Times New Roman",
              "@fontSize": "12.0",
              "@x": "85.10",
              "@y": "663.12",
              "@width": "250.01",
              "@height": "12.00",
              "#text": "text 1"
            }
          }
        ]
      },
      {
        "column": [
          {
            "text": {
              "@fontName": "Times New Roman",
              "@fontSize": "8.0",
              "@x": "121.10",
              "@y": "675.36",
              "@width": "348.98",
              "@height": "8.04",
              "#text": "text 2"
            }
          },
          {
            "text": {
              "@fontName": "Times New Roman",
              "@fontSize": "12.0",
              "@x": "473.30",
              "@y": "676.92",
              "@width": "42.47",
              "@height": "12.00",
              "#text": "text 3"
            }
          }
        ]
      },
      {
        "column": [
          {
            "text": {
              "@fontName": "Times New Roman",
              "@fontSize": "12.0",
              "@x": "85.10",
              "@y": "690.72",
              "@width": "433.61",
              "@height": "12.00",
              "#text": "text 4"
            }
          }
        ]
      }
    ]
  }
</code>```

Desired output is like this:

```<code>{
    "@index": "40",
    "row": [
          {
              "@fontName": "Times New Roman",
              "@fontSize": "12.0",
              "@x": "85.10",
              "@y": "663.12",
              "@width": "250.01",
              "@height": "12.00",
              "#text": "Text 1"
          },
          {
              "@fontName": "Times New Roman",
              "@fontSize": "8.0",
              "@x": "121.10",
              "@y": "675.36",
              "@width": "348.98",
              "@height": "8.04",
              "#text": "Text 2"
          },
          {
              "@fontName": "Times New Roman",
              "@fontSize": "12.0",
              "@x": "473.30",
              "@y": "676.92",
              "@width": "42.47",
              "@height": "12.00",
              "#text": "Text 3"
          },
          {
              "@fontName": "Times New Roman",
              "@fontSize": "12.0",
              "@x": "85.10",
              "@y": "690.72",
              "@width": "433.61",
              "@height": "12.00",
              "#text": "Text 4"
          }
    ]
  }
</code>```

The code I have so far is this using pandas is below, but I don´t know how to continue to normalize to one level.

```<code>import json
import pandas as pd
from pandas.io.json import json_normalize #package for flattening json in pandas df

#load json object
with open('D:\Files\JSON\4Level.json') as f:
    d = json.load(f)

nycphil = json_normalize(d['row'])
print (nycphil.head(4))
</code>```

This is the current output tabulated, where shows that column is a nested element:

```<code>                                            column
0  [{'text': {'@fontName': 'Times New Roman', '@f...
1  [{'text': {'@fontName': 'Times New Roman', '@f...
2  [{'text': {'@fontName': 'Times New Roman', '@f...
</code>```

The print with one level nesting would be:

```<code>text.#text   text.@fontName text.@fontSize   ...   text.@width text.@x text.@y
0     Text 1  Times New Roman           12.0   ...        250.01   85.10  663.12
1     Text 2  Times New Roman            8.0   ...        348.98  121.10  675.36
2     Text 3  Times New Roman           12.0   ...         42.47  473.30  676.92
3     Text 4  Times New Roman           12.0   ...        433.61   85.10  690.72
</code>```

The Input/Output comparison is like this:

Maybe someone could help me with this. Thanks for any help.

UPDATE

In order to make a small sample in first sample input I showed, I removed some elements that seems to be are needed in your scripts to work. So now I show exactly the same structure as real file but with this input your scripts don't work. I think they need a little tweak but I've been trying and I don't know how to change them to get the same output with this new input. Maybe you can help me and sorry for not show the correct input from beginning.

```<code>{
   "document":{
      "page":[
         {
            "@index":"0",
            "image":{
               "@data":"ABC",
               "@format":"png",
               "@height":"620.00",
               "@type":"base64encoded",
               "@width":"450.00",
               "@x":"85.00",
               "@y":"85.00"
            }
         },
         {
            "@index":"1",
            "row":[
               {
                  "column":[
                     {
                        "text":""
                     },
                     {
                        "text":{
                           "#text":"Text1",
                           "@fontName":"Arial",
                           "@fontSize":"12.0",
                           "@height":"12.00",
                           "@width":"71.04",
                           "@x":"121.10",
                           "@y":"83.42"
                        }
                     }
                  ]
               },
               {
                  "column":[
                     {
                        "text":""
                     },
                     {
                        "text":{
                           "#text":"Text2",
                           "@fontName":"Arial",
                           "@fontSize":"12.0",
                           "@height":"12.00",
                           "@width":"101.07",
                           "@x":"121.10",
                           "@y":"124.82"
                        }
                     }
                  ]
               }
            ]
         },
         {
            "@index":"2",
            "row":[
               {
                  "column":{
                     "text":{
                        "#text":"Text3",
                        "@fontName":"Arial",
                        "@fontSize":"12.0",
                        "@height":"12.00",
                        "@width":"363.44",
                        "@x":"85.10",
                        "@y":"69.62"
                     }
                  }
               },
               {
                  "column":{
                     "text":{
                        "#text":"Text4",
                        "@fontName":"Arial",
                        "@fontSize":"12.0",
                        "@height":"12.00",
                        "@width":"382.36",
                        "@x":"85.10",
                        "@y":"83.42"
                     }
                  }
               },
               {
                  "column":{
                     "text":{
                        "#text":"Text5",
                        "@fontName":"Arial",
                        "@fontSize":"12.0",
                        "@height":"12.00",
                        "@width":"435.05",
                        "@x":"85.10",
                        "@y":"97.22"
                     }
                  }
               }
            ]
         },
         {
            "@index":"3"
         }
      ]
   }
}
</code>```

答:
This does the job:

```<code>data = json.load(json_file)
flat = [ column['text'] for entry in data['row'] for column in entry['column'] ]
</code>```

Complete working example:

```<code>import json
import sys
import os.path

def main(argv):

    #Load JSON
    current_folder = os.path.dirname(os.path.realpath(__file__))
    with open(current_folder + '\\input.json') as json_file:
        data = json.load(json_file)

    #Flatten (using for loops)
    flat=[]
    for entry in data['row']:
        for column in entry['column']:
            flat.append(column['text'])

    # OR, Flatten the pythonic way (using list comprehension)
    # looks strange at first but notice
    #   1. we start with the item we want to keep in the list
    #   2. the loops order is the same, we just write them inline
    flat2 = [ column['text'] for entry in data['row'] for column in entry['column'] ]

    #Format data for saving to JSON
    output = {}
    output['@index']=data['@index']
    output['row'] = flat #or flat2

    #Save to JSON
    with open('flat.txt', 'w') as outfile:
        json.dump(output, outfile, indent=4)

if __name__ == "__main__":
   main(sys.argv[1:])
</code>```

Body:
I have the 4 level nested JSON file below, that I would like to normalize to a one level nesting:

Input file is like this:

{
    "@index": "40",
    "row": [
      {
        "column": [
          {
            "text": {
              "@fontName": "Times New Roman",
              "@fontSize": "12.0",
              "@x": "85.10",
              "@y": "663.12",
              "@width": "250.01",
              "@height": "12.00",
              "#text": "text 1"
            }
          }
        ]
      },
      {
        "column": [
          {
            "text": {
              "@fontName": "Times New Roman",
              "@fontSize": "8.0",
              "@x": "121.10",
              "@y": "675.36",
              "@width": "348.98",
              "@height": "8.04",
              "#text": "text 2"
            }
          },
          {
            "text": {
              "@fontName": "Times New Roman",
              "@fontSize": "12.0",
              "@x": "473.30",
              "@y": "676.92",
              "@width": "42.47",
              "@height": "12.00",
              "#text": "text 3"
            }
          }
        ]
      },
      {
        "column": [
          {
            "text": {
              "@fontName": "Times New Roman",
              "@fontSize": "12.0",
              "@x": "85.10",
              "@y": "690.72",
              "@width": "433.61",
              "@height": "12.00",
              "#text": "text 4"
            }
          }
        ]
      }
    ]
  }

Desired output is like this:

{
    "@index": "40",
    "row": [
          {
              "@fontName": "Times New Roman",
              "@fontSize": "12.0",
              "@x": "85.10",
              "@y": "663.12",
              "@width": "250.01",
              "@height": "12.00",
              "#text": "Text 1"
          },
          {
              "@fontName": "Times New Roman",
              "@fontSize": "8.0",
              "@x": "121.10",
              "@y": "675.36",
              "@width": "348.98",
              "@height": "8.04",
              "#text": "Text 2"
          },
          {
              "@fontName": "Times New Roman",
              "@fontSize": "12.0",
              "@x": "473.30",
              "@y": "676.92",
              "@width": "42.47",
              "@height": "12.00",
              "#text": "Text 3"
          },
          {
              "@fontName": "Times New Roman",
              "@fontSize": "12.0",
              "@x": "85.10",
              "@y": "690.72",
              "@width": "433.61",
              "@height": "12.00",
              "#text": "Text 4"
          }
    ]
  }

The code I have so far is this using pandas is below, but I don´t know how to continue to normalize to one level.

import json
import pandas as pd
from pandas.io.json import json_normalize #package for flattening json in pandas df

#load json object
with open('D:\Files\JSON\4Level.json') as f:
    d = json.load(f)

nycphil = json_normalize(d['row'])
print (nycphil.head(4))

This is the current output tabulated, where shows that column is a nested element:

                                            column
0  [{'text': {'@fontName': 'Times New Roman', '@f...
1  [{'text': {'@fontName': 'Times New Roman', '@f...
2  [{'text': {'@fontName': 'Times New Roman', '@f...

The print with one level nesting would be:

text.#text   text.@fontName text.@fontSize   ...   text.@width text.@x text.@y
0     Text 1  Times New Roman           12.0   ...        250.01   85.10  663.12
1     Text 2  Times New Roman            8.0   ...        348.98  121.10  675.36
2     Text 3  Times New Roman           12.0   ...         42.47  473.30  676.92
3     Text 4  Times New Roman           12.0   ...        433.61   85.10  690.72

The Input/Output comparison is like this:

Maybe someone could help me with this. Thanks for any help.

UPDATE

In order to make a small sample in first sample input I showed, I removed some elements that seems to be are needed in your scripts to work. So now I show exactly the same structure as real file but with this input your scripts don't work. I think they need a little tweak but I've been trying and I don't know how to change them to get the same output with this new input. Maybe you can help me and sorry for not show the correct input from beginning.

{
   "document":{
      "page":[
         {
            "@index":"0",
            "image":{
               "@data":"ABC",
               "@format":"png",
               "@height":"620.00",
               "@type":"base64encoded",
               "@width":"450.00",
               "@x":"85.00",
               "@y":"85.00"
            }
         },
         {
            "@index":"1",
            "row":[
               {
                  "column":[
                     {
                        "text":""
                     },
                     {
                        "text":{
                           "#text":"Text1",
                           "@fontName":"Arial",
                           "@fontSize":"12.0",
                           "@height":"12.00",
                           "@width":"71.04",
                           "@x":"121.10",
                           "@y":"83.42"
                        }
                     }
                  ]
               },
               {
                  "column":[
                     {
                        "text":""
                     },
                     {
                        "text":{
                           "#text":"Text2",
                           "@fontName":"Arial",
                           "@fontSize":"12.0",
                           "@height":"12.00",
                           "@width":"101.07",
                           "@x":"121.10",
                           "@y":"124.82"
                        }
                     }
                  ]
               }
            ]
         },
         {
            "@index":"2",
            "row":[
               {
                  "column":{
                     "text":{
                        "#text":"Text3",
                        "@fontName":"Arial",
                        "@fontSize":"12.0",
                        "@height":"12.00",
                        "@width":"363.44",
                        "@x":"85.10",
                        "@y":"69.62"
                     }
                  }
               },
               {
                  "column":{
                     "text":{
                        "#text":"Text4",
                        "@fontName":"Arial",
                        "@fontSize":"12.0",
                        "@height":"12.00",
                        "@width":"382.36",
                        "@x":"85.10",
                        "@y":"83.42"
                     }
                  }
               },
               {
                  "column":{
                     "text":{
                        "#text":"Text5",
                        "@fontName":"Arial",
                        "@fontSize":"12.0",
                        "@height":"12.00",
                        "@width":"435.05",
                        "@x":"85.10",
                        "@y":"97.22"
                     }
                  }
               }
            ]
         },
         {
            "@index":"3"
         }
      ]
   }
}

Body:
This does the job:

data = json.load(json_file)
flat = [ column['text'] for entry in data['row'] for column in entry['column'] ]

Complete working example:

import json
import sys
import os.path

def main(argv):

    #Load JSON
    current_folder = os.path.dirname(os.path.realpath(__file__))
    with open(current_folder + '\\input.json') as json_file:
        data = json.load(json_file)

    #Flatten (using for loops)
    flat=[]
    for entry in data['row']:
        for column in entry['column']:
            flat.append(column['text'])

    # OR, Flatten the pythonic way (using list comprehension)
    # looks strange at first but notice
    #   1. we start with the item we want to keep in the list
    #   2. the loops order is the same, we just write them inline
    flat2 = [ column['text'] for entry in data['row'] for column in entry['column'] ]

    #Format data for saving to JSON
    output = {}
    output['@index']=data['@index']
    output['row'] = flat #or flat2

    #Save to JSON
    with open('flat.txt', 'w') as outfile:
        json.dump(output, outfile, indent=4)

if __name__ == "__main__":
   main(sys.argv[1:])


问:
How to set DNS when the device is connected via Ethernet?
My android target is connect via Ethernet using static IP.
I am able to connect it by using ADB, but I am not able to ping any server.
Please tell me how can I configure my DNS setting so that I can ping any server.</p>

Body:
Android 8.0

////////////////////////////////////////////////////////////

ifconfig usb0 192.168.225.3 netmask 255.255.255.0

ndc network create 9792

ndc network interface add 9792 usb0

ndc network route add 9792 usb0 0.0.0.0/0 192.168.225.1

ndc resolver setnetdns 9792 8.8.8.8 8.8.4.4

ndc network default set 9792

///////////////////////////////////////////////////////////


问:
How to find right "div" to web scrape with python
I cant seem to "inspect" the right function for beautiful soup to function. I am trying to follow these guides but I cant seem to get past this point.

https://www.youtube.com/watch?v=XQgXKtPSzUI&t=119s
Web scraping with Python

I am trying to webscrape a website to compare four vehicles by Safety features, Maintenance cost, and Price point. I am using spyder (python 3.6)

```<code>import bs4
from urllib import urlopen as uReq
from bs4 import BeautifulSoup as soup

my_url = 'https://www.edmunds.com/car-comparisons/?
veh1=401768437&veh2=401753723&veh3=401780798&veh4=401768504'

# opening up connection, grabbing the page
uClient = uReq(my_url)
page_html = uClient.read()
uClient.close()

# html parsing
page_soup = soup(page_html, "html.parser")

#grabs each product
containers = page_soup.findAll("div", {"class":"feature-field-value"})

filename = "car_comparison.csv"
f = open(filename, "W")

Headers = "Title, product_name, shipping\n"
f.write(headers)

for container in containers:
brand = container.div.div.a.img["title"]

title_container = container.findAll("a", {"class":"vehicle-title f16-nm f14
lh22-nm lh18 pv2 sserif-2 tr-text minh90"})
product_name = title_container[0].text

shipping_container = container.findAll("li",{"class":"price-ship"})
shipping_container[0].text.strip()

print("Title: " + title)
print("product_name: " + product_name)
print("shipping: " + shipping)

f.write( brand + "," +product_name.replace(",", "|") + "," + shipping +
"\n")

f.close()

#Criteria 1
#safety = Warranty, Basic?
#Maintence Cost = Maintence
#Price = Base MSRP
</code>```

I know I have to change quite a bit but right now I just want it to run without getting errors

runfile('C:/Users/st.s.mahathirath.ctr/.spyder-py3/temp.py', wdir='C:/Users/st.s.mahathirath.ctr/.spyder-py3')
Traceback (most recent call last):

File "", line 1, in
    runfile('C:/Users/st.s.mahathirath.ctr/.spyder-py3/temp.py', wdir='C:/Users/st.s.mahathirath.ctr/.spyder-py3')

File "C:\ProgramData\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 705, in runfile
    execfile(filename, namespace)

File "C:\ProgramData\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 102, in execfile
    exec(compile(f.read(), filename, 'exec'), namespace)

File "C:/Users/st.s.mahathirath.ctr/.spyder-py3/temp.py", line 2, in
    from urllib import urlopen as uReq

ImportError: cannot import name 'urlopen'

答:
```<code>from urllib.request urlopen as uReq
</code>```

This looks like a typo to me? Maybe you meant:

from urllib.request import urlopen as uReq

Body:
I cant seem to "inspect" the right function for beautiful soup to function. I am trying to follow these guides but I cant seem to get past this point.

https://www.youtube.com/watch?v=XQgXKtPSzUI&t=119s
Web scraping with Python

I am trying to webscrape a website to compare four vehicles by Safety features, Maintenance cost, and Price point. I am using spyder (python 3.6)

import bs4
from urllib import urlopen as uReq
from bs4 import BeautifulSoup as soup

my_url = 'https://www.edmunds.com/car-comparisons/?
veh1=401768437&veh2=401753723&veh3=401780798&veh4=401768504'

# opening up connection, grabbing the page
uClient = uReq(my_url)
page_html = uClient.read()
uClient.close()

# html parsing
page_soup = soup(page_html, "html.parser")

#grabs each product
containers = page_soup.findAll("div", {"class":"feature-field-value"})

filename = "car_comparison.csv"
f = open(filename, "W")

Headers = "Title, product_name, shipping\n"
f.write(headers)

for container in containers:
brand = container.div.div.a.img["title"]

title_container = container.findAll("a", {"class":"vehicle-title f16-nm f14
lh22-nm lh18 pv2 sserif-2 tr-text minh90"})
product_name = title_container[0].text

shipping_container = container.findAll("li",{"class":"price-ship"})
shipping_container[0].text.strip()

print("Title: " + title)
print("product_name: " + product_name)
print("shipping: " + shipping)

f.write( brand + "," +product_name.replace(",", "|") + "," + shipping +
"\n")

f.close()

#Criteria 1
#safety = Warranty, Basic?
#Maintence Cost = Maintence
#Price = Base MSRP

I know I have to change quite a bit but right now I just want it to run without getting errors

runfile('C:/Users/st.s.mahathirath.ctr/.spyder-py3/temp.py', wdir='C:/Users/st.s.mahathirath.ctr/.spyder-py3')
Traceback (most recent call last):

File "", line 1, in
    runfile('C:/Users/st.s.mahathirath.ctr/.spyder-py3/temp.py', wdir='C:/Users/st.s.mahathirath.ctr/.spyder-py3')

File "C:\ProgramData\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 705, in runfile
    execfile(filename, namespace)

File "C:\ProgramData\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 102, in execfile
    exec(compile(f.read(), filename, 'exec'), namespace)

File "C:/Users/st.s.mahathirath.ctr/.spyder-py3/temp.py", line 2, in
    from urllib import urlopen as uReq

ImportError: cannot import name 'urlopen'

Body:
from urllib.request urlopen as uReq

This looks like a typo to me? Maybe you meant:

from urllib.request import urlopen as uReq