问:
how do i remove array of elements in mongodb
I'm trying to remove array of elements but it's not working at all..

in schema

```<code>var connectedUsers = Schema({
  fruits: { type: Array },
  vegetables: { type: Array }
})
var connectedusers = mongoose.model("connectedusers", connectedUsers)
</code>```

Node js routing file

```<code>router.post('/connectedusers', function(req,res) {
connection.connectedusers.update(
        { $pull: { fruits: { $in: [ "apples", "oranges" ] }, vegetables: "carrots" } },
        { multi: true }
    )
    connection.connectedusers.find({}, function (err, docs) {
        if (err) throw err;
        res.json({
            docs: docs
        })
    })
});
</code>```

In mongodb collection

```<code>{
    "_id": {
        "$oid": "5cef68f690a42ba057760e98"
    },
    "__v": 0,
    "connectArray": [
        "vinay",
        "vinay1"
    ],
    "fruits": [
        "apples",
        "pears",
        "oranges",
        "grapes",
        "bananas"
    ],
    "vegetables": [
        "carrots",
        "celery",
        "squash",
        "carrots"
    ]
}
</code>```

Array of elements are not removing.. its showing all collection details.
how do i remove elements from mongodb using $Pull or any other.

答:
You forgot the match query also the db functions are asynchronous so you will need to await for the update operation to complete before querying to check if the db has changed, this can be done with async functions</p>

```<code>// change callback to an async arrow function
router.post('/connectedusers', async (req, res) => {
    try {
        // wait for this operation to complete before continuing
        await connection.connectedusers.update(
            {},
            { $pull: { fruits: { $in: [ "apples", "oranges" ] }, vegetables: "carrots" } },
            { multi: true }
        );
        // update complete now wait for the find query
        const docs = await connection.connectedusers.find({});
        // no errors, send docs.
        // if the variable name is the same as your field
        // that you want to send in the object you can just
        // pass that variable directly
        res.json({ docs });
    // catches errors from both update and find operations
    } catch (err) {
        // set the status code and send the error
        res.status(/* error status */).json(err);
    }
});
</code>```

Body:
I'm trying to remove array of elements but it's not working at all..

in schema

var connectedUsers = Schema({
  fruits: { type: Array },
  vegetables: { type: Array }
})
var connectedusers = mongoose.model("connectedusers", connectedUsers)

Node js routing file

router.post('/connectedusers', function(req,res) {
connection.connectedusers.update(
        { $pull: { fruits: { $in: [ "apples", "oranges" ] }, vegetables: "carrots" } },
        { multi: true }
    )
    connection.connectedusers.find({}, function (err, docs) {
        if (err) throw err;
        res.json({
            docs: docs
        })
    })
});

In mongodb collection

{
    "_id": {
        "$oid": "5cef68f690a42ba057760e98"
    },
    "__v": 0,
    "connectArray": [
        "vinay",
        "vinay1"
    ],
    "fruits": [
        "apples",
        "pears",
        "oranges",
        "grapes",
        "bananas"
    ],
    "vegetables": [
        "carrots",
        "celery",
        "squash",
        "carrots"
    ]
}

Array of elements are not removing.. its showing all collection details.
how do i remove elements from mongodb using $Pull or any other.

Body:
You forgot the match query also the db functions are asynchronous so you will need to await for the update operation to complete before querying to check if the db has changed, this can be done with async functions

// change callback to an async arrow function
router.post('/connectedusers', async (req, res) => {
    try {
        // wait for this operation to complete before continuing
        await connection.connectedusers.update(
            {},
            { $pull: { fruits: { $in: [ "apples", "oranges" ] }, vegetables: "carrots" } },
            { multi: true }
        );
        // update complete now wait for the find query
        const docs = await connection.connectedusers.find({});
        // no errors, send docs.
        // if the variable name is the same as your field
        // that you want to send in the object you can just
        // pass that variable directly
        res.json({ docs });
    // catches errors from both update and find operations
    } catch (err) {
        // set the status code and send the error
        res.status(/* error status */).json(err);
    }
});


来源: stackexchange

问:
Difference between valueMap() and mapsValue()?
i am a beginner in using graph database. As per my knowledge,valueMap() returns the array of properties of a particular vertex.But in tinkerpop documentation, i have found another method like mapsValue(). may i know the difference please.thanks in advance.</p>

答:
mapValues() has been deprecated.

You need to use select() instead of mapValues() which is used for creating alias for traversals.

ContentLicense: CC BY-SA 4.0


问:
Git create release on commit reading a variable in file
I have a PHP project,
with a file called release.php, that's just containing some info about the version of the project and a variable $create_release:

```<code><?php
$release = '1.0.4';
$release_date = '2019/05/30';
$create_release = TRUE;
</code>```

I would on git push to GitHub, create a release if the variable inside PHP file is set TRUE.

How can I trigger GitHub release creation automatically on git push?

Is it possible?

答:
AFAIK GitHub doesn't support standard git hooks. It exposes Webhooks thou. I'd integrate it with some endpoint on your side.

In other words, you're pushing to GitHub. Webhook is fired and calls your endpoint. Your endpoint inspects the change and fires release process if all requirements are met.

Body:
I have a PHP project,
with a file called release.php, that's just containing some info about the version of the project and a variable $create_release:

<?php
$release = '1.0.4';
$release_date = '2019/05/30';
$create_release = TRUE;

I would on git push to GitHub, create a release if the variable inside PHP file is set TRUE.

How can I trigger GitHub release creation automatically on git push?

Is it possible?


问:
How to migrate collections from TFS 2017 to Azure DevOps Server 2019 (Different DB servers)
I have been handling an aging Windows Server 2008 machine with TFS upgraded in place to 2017.2. Now, with Azure DevOps Server 2019, support for Windows Server 2008 is no longer available. Also, the existing SQL Server is 2012 and is no longer supported as well. I cannot upgrade the database to SQL Server 2014+ as there is the OS restriction. and in our company, upgrading OS in-place is not allowed.

Existing setup is as follows:

Windows Server 2008 (One VM)

TFS 2017.2

SQL Server 2012 Ent (On same VM)

Non-HTTPS machine name URL Team Portal access over Intranet

I prepared a brand new Windows Server 2016 for the Azure DevOps 2019.0.1. I also was able to get hold of a SQL AlwaysON Cluster based off SQL Server 2017 Ent just for Azure DevOps.

If I proceed with DevOps setup, I'll target the new DB Cluster and it will set up the new DB accordingly.

How do I move my existing collections to the new cluster (easy: restore DBs on the new cluster)?

Will Azure DevOps just accept the new collections?

All migration topics I've read are always assuming DB server and TFS server are the same and do not change.

答:
Ideal path:

Install the SQL Server matching your original environment.

Attach the databases

Install a version of TFS that supports your SQL server version that is the same or newer than the original server.

Walk through the configuration wizard.

uninstall TFS server

Detach databases and uninstall SQL Server

Install the desired SQL Server version  with the same instance name.

Attach databases

Install latest version of Azure DevOps Server

Walk through the Upgrade wizard.

Full details here:

https://devblogs.microsoft.com/premier-developer/move-or-clone-tfs-from-one-hardware-to-another-in-tfs-2017-2018/


问:
Update values for all rows based on unique ID - Oracle
I have a table:

table1

```<code>unique_id       col_id      col_nm      col_val     sequ    s_date      e_date
1               1           test 1      100         1       null        null
1               2           test 2      abc         1       null        null
1               3           test 3      103         1       null        null
1               4           test 4      105         2       null        null
1               5           test 5      10          1       null        null
1               6           my date     20180912    1       null        null
1               7           my date 1   20180913    2       null        null
1               8           test 6      100         1       null        null

2               1           test 1      100         1       null        null
2               2           test 2      abc         1       null        null
2               3           test 3      103         1       null        null
2               4           test 4      105         2       null        null
2               5           test 5      10          1       null        null
2               6           my date     20180911    1       null        null
2               7           my date 1   20180910    2       null        null
2               8           test 6      100         1       null        null
</code>```

For each unique_id, I need to get col_val and set s_date and e_date:

s_date = col_val of col_id = 6 and col_nm = 'my date' and sequence = 1

e_date = col_val of col_id = 7 and col_nm = 'my date 1' and sequence = 2

and then set it for all rows of the appropriate unique_id.

The output table looks like:

```<code>unique_id       col_id      col_nm      col_val     sequ    s_date      e_date
1               1           test 1      100         1       20180912    20180913
1               2           test 2      abc         1       20180912    20180913
1               3           test 3      103         1       20180912    20180913
1               4           test 4      105         2       20180912    20180913
1               5           test 5      10          1       20180912    20180913
1               6           my date     20180912    1       20180912    20180913
1               7           my date 1   20180913    2       20180912    20180913
1               8           test 6      100         1       20180912    20180913

2               1           test 1      100         1       20180911    20180910
2               2           test 2      abc         1       20180911    20180910
2               3           test 3      103         1       20180911    20180910
2               4           test 4      105         2       20180911    20180910
2               5           test 5      10          1       20180911    20180910
2               6           my date     20180911    1       20180911    20180910
2               7           my date 1   20180910    2       20180911    20180910
2               8           test 6      100         1       20180911    20180910
</code>```

My table has over 50 million records, so need the query to take that into consideration.

Is there a way in SQL to achieve this?

Body:
I have a table:

table1

unique_id       col_id      col_nm      col_val     sequ    s_date      e_date
1               1           test 1      100         1       null        null
1               2           test 2      abc         1       null        null
1               3           test 3      103         1       null        null
1               4           test 4      105         2       null        null
1               5           test 5      10          1       null        null
1               6           my date     20180912    1       null        null
1               7           my date 1   20180913    2       null        null
1               8           test 6      100         1       null        null

2               1           test 1      100         1       null        null
2               2           test 2      abc         1       null        null
2               3           test 3      103         1       null        null
2               4           test 4      105         2       null        null
2               5           test 5      10          1       null        null
2               6           my date     20180911    1       null        null
2               7           my date 1   20180910    2       null        null
2               8           test 6      100         1       null        null

For each unique_id, I need to get col_val and set s_date and e_date:

s_date = col_val of col_id = 6 and col_nm = 'my date' and sequence = 1

e_date = col_val of col_id = 7 and col_nm = 'my date 1' and sequence = 2

and then set it for all rows of the appropriate unique_id.

The output table looks like:

unique_id       col_id      col_nm      col_val     sequ    s_date      e_date
1               1           test 1      100         1       20180912    20180913
1               2           test 2      abc         1       20180912    20180913
1               3           test 3      103         1       20180912    20180913
1               4           test 4      105         2       20180912    20180913
1               5           test 5      10          1       20180912    20180913
1               6           my date     20180912    1       20180912    20180913
1               7           my date 1   20180913    2       20180912    20180913
1               8           test 6      100         1       20180912    20180913

2               1           test 1      100         1       20180911    20180910
2               2           test 2      abc         1       20180911    20180910
2               3           test 3      103         1       20180911    20180910
2               4           test 4      105         2       20180911    20180910
2               5           test 5      10          1       20180911    20180910
2               6           my date     20180911    1       20180911    20180910
2               7           my date 1   20180910    2       20180911    20180910
2               8           test 6      100         1       20180911    20180910

My table has over 50 million records, so need the query to take that into consideration.

Is there a way in SQL to achieve this?

Body:
You can try to use MERGE with condition aggravated function

MERGE
INTO T trg
USING   (
         SELECT unique_id,
           MAX(CASE WHEN col_id = 6 AND col_nm = 'my date' and sequ = 1 THEN col_val END) mindt,
           MIN(CASE WHEN col_id = 7 AND col_nm = 'my date 1' and sequ = 2 THEN col_val END) maxdt
         FROM T
         GROUP BY unique_id
        ) src
ON  (trg.unique_id = src.unique_id)
WHEN MATCHED THEN UPDATE
    SET trg.e_date = maxdt , trg.s_date = mindt

Results:

| UNIQUE_ID | COL_ID |    COL_NM |  COL_VAL | SEQU |   S_DATE |   E_DATE |
|-----------|--------|-----------|----------|------|----------|----------|
|         1 |      1 |   test 1  |      100 |    1 | 20180912 | 20180913 |
|         1 |      2 |   test 2  |      abc |    1 | 20180912 | 20180913 |
|         1 |      3 |   test 3  |      103 |    1 | 20180912 | 20180913 |
|         1 |      4 |   test 4  |      105 |    2 | 20180912 | 20180913 |
|         1 |      5 |   test 5  |       10 |    1 | 20180912 | 20180913 |
|         1 |      6 |   my date | 20180912 |    1 | 20180912 | 20180913 |
|         1 |      7 | my date 1 | 20180913 |    2 | 20180912 | 20180913 |
|         1 |      8 |   test 6  |      100 |    1 | 20180912 | 20180913 |
|         2 |      1 |   test 1  |      100 |    1 | 20180911 | 20180910 |
|         2 |      2 |   test 2  |      abc |    1 | 20180911 | 20180910 |
|         2 |      3 |   test 3  |      103 |    1 | 20180911 | 20180910 |
|         2 |      4 |   test 4  |      105 |    2 | 20180911 | 20180910 |
|         2 |      5 |   test 5  |       10 |    1 | 20180911 | 20180910 |
|         2 |      6 |   my date | 20180911 |    1 | 20180911 | 20180910 |
|         2 |      7 | my date 1 | 20180910 |    2 | 20180911 | 20180910 |
|         2 |      8 |   test 6  |      100 |    1 | 20180911 | 20180910 |


问:
How do I make my boolean return the value true? Because it keeps returning false
I'm using the three layers architecture. In servlet, before I get to the methods, I have to check whether my boolean is true or false in my DAO layer. If false, it will go to the first method, if true, it will go to the second method.

I don't know what went wrong but it keeps returning the false one. So I'm stuck with one method even though I want another method. Below is my DAO layer:

```<code>public static RPHS getRph(RPHS rph)  {
        rph_id = rph.getRph_id();

        String searchQuery = "select * from rphs where rph_id='" + rph_id + "'";

        try {
            currentCon = ConnectionManager.getConnection();
            stmt = currentCon.createStatement();
            rs = stmt.executeQuery(searchQuery);
            boolean more = rs.next();

            // if rph exists set the isValid variable to true
            if (more) {
                int rph_id = rs.getInt("rph_id");
                rph.setRph_id(rph_id);
                rph.setValid(true);
            }

            else if (!more) {
                rph.setValid(false);
            }

        }
}
</code>```

How do I make it return the value true? Is something wrong with my query?

答:
You should use PreparedStatement instead of Statement, also use dynamic query, like..

```<code>String searchQuery = "select * from rphs where rph_id=?";
</code>```

and pass value to ? mark.

```<code>Ex. stmt.setInt(1,101);
</code>```

after taking result in ResultSet use-

```<code>if (rs.next())
{
   int rph_id = rs.getInt("rph_id");
   rph.setRph_id(rph_id);
   rph.setValid(true);
}else {
        rph.setValid(false);
}
</code>```

Body:
I'm using the three layers architecture. In servlet, before I get to the methods, I have to check whether my boolean is true or false in my DAO layer. If false, it will go to the first method, if true, it will go to the second method.

I don't know what went wrong but it keeps returning the false one. So I'm stuck with one method even though I want another method. Below is my DAO layer:

public static RPHS getRph(RPHS rph)  {
        rph_id = rph.getRph_id();

        String searchQuery = "select * from rphs where rph_id='" + rph_id + "'";

        try {
            currentCon = ConnectionManager.getConnection();
            stmt = currentCon.createStatement();
            rs = stmt.executeQuery(searchQuery);
            boolean more = rs.next();

            // if rph exists set the isValid variable to true
            if (more) {
                int rph_id = rs.getInt("rph_id");
                rph.setRph_id(rph_id);
                rph.setValid(true);
            }

            else if (!more) {
                rph.setValid(false);
            }

        }
}

How do I make it return the value true? Is something wrong with my query?

Body:
You should use PreparedStatement instead of Statement, also use dynamic query, like..

String searchQuery = "select * from rphs where rph_id=?";

and pass value to ? mark.

Ex. stmt.setInt(1,101);

after taking result in ResultSet use-

if (rs.next())
{
   int rph_id = rs.getInt("rph_id");
   rph.setRph_id(rph_id);
   rph.setValid(true);
}else {
        rph.setValid(false);
}


问:
Auth::id() can't find user id and return null, laravel
I am setting like and unlike options on articles. but in LikeController there is problem. when I push the like button it says ->

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'user_id'
  cannot be null (SQL: insert into likes (user_id, article_id,
  updated_at, created_at) values (?, 5, 2019-05-30 07:58:34,
  2019-05-30 07:58:34))

Updated JWT and Routes

Like model:

```<code>class Like extends Model
{
    public $timestamps = true;
    public $with = ["user"];

    protected $fillable = ["user_id", "article_id"];

    public function article()
    {
        return $this->belongsTo("App\Article");
    }

    public function user()
    {
        return $this->belongsTo("App\User");
    }
}
</code>```

and LikeController:

```<code>use Auth;
use App\Article;
use App\Like;

public function like($id)
{
    $article = Article::find($id);

    $like =  Like::create([
        "user_id" => Auth::id(),
        "article_id" => $article->id
    ]);

    return Like::find($like->id);
}

public function unlike($id)
{
    $article = Article::find($id);

    Like::where("user_id", Auth::id())
        ->where("article_id", $article->id)
        ->first()
        ->delete();

    return 1;
}
</code>```

I am not very sure why Auth::id() can't find the user id and return null?

Using JWT with vue.js

Routes:

```<code>Route::group(['prefix' => 'auth'], function ($router) {

  Route::post('register', 'AuthController@register');
  Route::post('login', 'AuthController@login');
  Route::post('logout', 'AuthController@logout');
  Route::post('refresh', 'AuthController@refresh');
  Route::post('me', 'AuthController@me');

});

Route::get("/like/{id}", [
        "uses" => "LikeController@like"
    ]);
Route::get("/unlike/{id}", [
        "uses" => "LikeController@unlike"
    ]);
</code>```

AuthController and User

to set controller and user model I followed the docs: https://jwt-auth.readthedocs.io/en/develop/quick-start/

答:
You seem to have not protected your LikeController routes with auth.

Unless you have something like this in your LikeController for constructor:

```<code>    public function __construct()
    {
        $this->middleware('auth:api');
    }
</code>```

then you should have your LikeController routes protected like this:

```<code>Route::group([
    'middleware' => 'api',
], function ($router) {

    Route::get("/like/{id}", [
        "uses" => "LikeController@like"
    ]);
    Route::get("/unlike/{id}", [
        "uses" => "LikeController@unlike"
    ]);

});
</code>```

Then the correct way of getting the logged in used is

```<code>auth('api')->user()
</code>```

or

```<code>Auth::guard('api')->user()
</code>```

Body:
I am setting like and unlike options on articles. but in LikeController there is problem. when I push the like button it says ->

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'user_id'
  cannot be null (SQL: insert into likes (user_id, article_id,
  updated_at, created_at) values (?, 5, 2019-05-30 07:58:34,
  2019-05-30 07:58:34))

Updated JWT and Routes

Like model:

class Like extends Model
{
    public $timestamps = true;
    public $with = ["user"];

    protected $fillable = ["user_id", "article_id"];

    public function article()
    {
        return $this->belongsTo("App\Article");
    }

    public function user()
    {
        return $this->belongsTo("App\User");
    }
}

and LikeController:

use Auth;
use App\Article;
use App\Like;

public function like($id)
{
    $article = Article::find($id);

    $like =  Like::create([
        "user_id" => Auth::id(),
        "article_id" => $article->id
    ]);

    return Like::find($like->id);
}

public function unlike($id)
{
    $article = Article::find($id);

    Like::where("user_id", Auth::id())
        ->where("article_id", $article->id)
        ->first()
        ->delete();

    return 1;
}

I am not very sure why Auth::id() can't find the user id and return null?

Using JWT with vue.js

Routes:

Route::group(['prefix' => 'auth'], function ($router) {

  Route::post('register', 'AuthController@register');
  Route::post('login', 'AuthController@login');
  Route::post('logout', 'AuthController@logout');
  Route::post('refresh', 'AuthController@refresh');
  Route::post('me', 'AuthController@me');

});

Route::get("/like/{id}", [
        "uses" => "LikeController@like"
    ]);
Route::get("/unlike/{id}", [
        "uses" => "LikeController@unlike"
    ]);

AuthController and User

to set controller and user model I followed the docs: https://jwt-auth.readthedocs.io/en/develop/quick-start/

Body:
You seem to have not protected your LikeController routes with auth.

Unless you have something like this in your LikeController for constructor:

    public function __construct()
    {
        $this->middleware('auth:api');
    }

then you should have your LikeController routes protected like this:

Route::group([
    'middleware' => 'api',
], function ($router) {

    Route::get("/like/{id}", [
        "uses" => "LikeController@like"
    ]);
    Route::get("/unlike/{id}", [
        "uses" => "LikeController@unlike"
    ]);

});

Then the correct way of getting the logged in used is

auth('api')->user()

or

Auth::guard('api')->user()


问:
pathlib library error in pathlib.Path.home() : type object 'Path' has no attribute 'home'
So I've just updated matplotlib to version 3.0.2 . I can import matplotlib just fine, but when I try to import matplotlib.pyplot, I get :

```<code>---------------------------------------------------------------------------
AttributeError
Traceback (most recent call last) <ipython-input-3-864e826dab68> in <module>()
----> 1 import matplotlib.pyplot

/usr/local/lib/python3.6/dist-packages/matplotlib/pyplot.py in <module>()
     30 from cycler import cycler
     31 import matplotlib
---> 32 import matplotlib.colorbar
     33 import matplotlib.image
     34 from matplotlib import rcsetup, style

/usr/local/lib/python3.6/dist-packages/matplotlib/colorbar.py in <module>()
     30 import matplotlib.collections as collections
     31 import matplotlib.colors as colors
---> 32 import matplotlib.contour as contour
     33 import matplotlib.cm as cm
     34 import matplotlib.gridspec as gridspec

/usr/local/lib/python3.6/dist-packages/matplotlib/contour.py in <module>()
     16 import matplotlib.colors as mcolors
     17 import matplotlib.collections as mcoll
---> 18 import matplotlib.font_manager as font_manager
     19 import matplotlib.text as text
     20 import matplotlib.cbook as cbook

/usr/local/lib/python3.6/dist-packages/matplotlib/font_manager.py in <module>()
    133
    134 if not USE_FONTCONFIG and sys.platform != 'win32':
--> 135     OSXFontDirectories.append(str(Path.home() / "Library/Fonts"))
    136     X11FontDirectories.append(str(Path.home() / ".fonts"))
    137

AttributeError: type object 'Path' has no attribute 'home'
</code>```

I'm on Ubuntu 18.04 LTS, on Jupyter Lab 0.35.4 with python3.6.7.

Side information/question : Before installing jupyter lab this morning, I was using jupyter notebook with python3.6.0. Now the kernels says it is using python3.6.7, although I cannot seem to find it anywhere on my system.

That being told, when I import anything else that doesn't rely on matplotlib.pyplot, everything works perfectly. If I try seaborn, for example, it returns me to the same attribute error.

EDIT In fact, the error happens with the pathlib library. It also happens whether or not I'm in jupyter. To replicate it :

```<code>from pathlib import Path
Path.home()
</code>```

and the error is the same as before :

```<code>AttributeError: type object 'Path' has no attribute 'home'
</code>```

答:
I hit this recently where matplotlib was trying to import and use pathlib and failing because my virtualenv was 3.6 but it was somehow getting a 3.4 pathlib and hitting either the exception you hit or another exception where the mkdir() it was calling was missing the exists_ok optional parameter.

It turned out that one of the modules I was using, openapi-spec-validator version 0.2.6, downloads a copy of pathlib (of the 3.4 type) and sticks it in the base site-packages folder where it can easily end up being used by matplotlib instead of the standard library version. In my case upgrading to 0.2.7 fixed it as that version doesn't download and place the file there.

However, if you're not using openapi-spec-validator and you hit this problem check to see if there are extra copies of pathlib.py floating around your environment.

Body:
So I've just updated matplotlib to version 3.0.2 . I can import matplotlib just fine, but when I try to import matplotlib.pyplot, I get :

---------------------------------------------------------------------------
AttributeError
Traceback (most recent call last) <ipython-input-3-864e826dab68> in <module>()
----> 1 import matplotlib.pyplot

/usr/local/lib/python3.6/dist-packages/matplotlib/pyplot.py in <module>()
     30 from cycler import cycler
     31 import matplotlib
---> 32 import matplotlib.colorbar
     33 import matplotlib.image
     34 from matplotlib import rcsetup, style

/usr/local/lib/python3.6/dist-packages/matplotlib/colorbar.py in <module>()
     30 import matplotlib.collections as collections
     31 import matplotlib.colors as colors
---> 32 import matplotlib.contour as contour
     33 import matplotlib.cm as cm
     34 import matplotlib.gridspec as gridspec

/usr/local/lib/python3.6/dist-packages/matplotlib/contour.py in <module>()
     16 import matplotlib.colors as mcolors
     17 import matplotlib.collections as mcoll
---> 18 import matplotlib.font_manager as font_manager
     19 import matplotlib.text as text
     20 import matplotlib.cbook as cbook

/usr/local/lib/python3.6/dist-packages/matplotlib/font_manager.py in <module>()
    133
    134 if not USE_FONTCONFIG and sys.platform != 'win32':
--> 135     OSXFontDirectories.append(str(Path.home() / "Library/Fonts"))
    136     X11FontDirectories.append(str(Path.home() / ".fonts"))
    137

AttributeError: type object 'Path' has no attribute 'home'

I'm on Ubuntu 18.04 LTS, on Jupyter Lab 0.35.4 with python3.6.7.

Side information/question : Before installing jupyter lab this morning, I was using jupyter notebook with python3.6.0. Now the kernels says it is using python3.6.7, although I cannot seem to find it anywhere on my system.

That being told, when I import anything else that doesn't rely on matplotlib.pyplot, everything works perfectly. If I try seaborn, for example, it returns me to the same attribute error.

EDIT In fact, the error happens with the pathlib library. It also happens whether or not I'm in jupyter. To replicate it :

from pathlib import Path
Path.home()

and the error is the same as before :

AttributeError: type object 'Path' has no attribute 'home'


问:
How to link OpenSSL in CLion
I'm currently working on a web server in C and I wanted to include  for hashing passwords. My problem right now is that I get the error undefined reference to 'SHA1' when trying to compile. It appears to be an error with the Linker because the building seemed to work fine.

This is how I call SHA1():

```<code>SHA1(src, srcLength, hashStr);
</code>```

I've simply installed OpenSSL by using apt-get install openssl

Do I somehow have to add OpenSSL to the target_link_libraries in the CMake-File?

EDIT: Sorry, I miss-typed, I installed openssl-dev, not just openssl

答: You need to install the development package sudo apt-get install libssl-dev which includes the necessary header files.

Title: How to link OpenSSL in CLion

Body:
I'm currently working on a web server in C and I wanted to include  for hashing passwords. My problem right now is that I get the error undefined reference to 'SHA1' when trying to compile. It appears to be an error with the Linker because the building seemed to work fine.

This is how I call SHA1():

SHA1(src, srcLength, hashStr);

I've simply installed OpenSSL by using apt-get install openssl

Do I somehow have to add OpenSSL to the target_link_libraries in the CMake-File?

EDIT: Sorry, I miss-typed, I installed openssl-dev, not just openssl


问:
Angular 2 - large scale application forms' handling
At the company I’m working for, we’re developing a large scale application with multiple forms, that the user needs to fill in in order to register for our program. When all questions have been answered, then the user reaches a section that sums up all their answers, highlights invalid answers and gives the user the chance to revisit any of the preceding form steps and revise their answers. This logic will be repeated across a range of top-level sections, each having multiple steps/pages and a summary page.

To accomplish this, we have created a component for each separate form step (they are categories like “Personal Details” or “Qualifications” etc.) along with their respective routes and a component for the Summary Page.

In order to keep it as DRY as possible, we started creating a “master” service which holds the information for all the different form steps (values, validity etc.).

import { Injectable } from '@angular/core';
import { Validators } from '@angular/forms';
import { ValidationService } from '../components/validation/index';

@Injectable()
export class FormControlsService {
  static getFormControls() {
    return [
      {
        name: 'personalDetailsForm$',
        groups: {
          name$: [
            {
              name: 'firstname$',
              validations: [
                Validators.required,
                Validators.minLength(2)
              ]
            },
            {
              name: 'lastname$',
              validations: [
                Validators.required,
                Validators.minLength(2)
              ]
            }
          ],
          gender$: [
            {
              name: 'gender$',
              validations: [
                Validators.required
              ]
            }
          ],
          address$: [
            {
              name: 'streetaddress$',
              validations: [
                Validators.required
              ]
            },
            {
              name: 'city$',
              validations: [
                Validators.required
              ]
            },
            {
              name: 'state$',
              validations: [
                Validators.required
              ]
            },
            {
              name: 'zip$',
              validations: [
                Validators.required
              ]
            },
            {
              name: 'country$',
              validations: [
                Validators.required
              ]
            }
          ],
          phone$: [
            {
              name: 'phone$',
              validations: [
                Validators.required
              ]
            },
            {
              name: 'countrycode$',
              validations: [
                Validators.required
              ]
            }
          ],
        }
      },
      {
        name: 'parentForm$',
        groups: {
          all: [
            {
              name: 'parentName$',
              validations: [
                Validators.required
              ]
            },
            {
              name: 'parentEmail$',
              validations: [
                ValidationService.emailValidator
              ]
            },
            {
              name: 'parentOccupation$'
            },
            {
              name: 'parentTelephone$'
            }
          ]
        }
      },
      {
        name: 'responsibilitiesForm$',
        groups: {
          all: [
            {
              name: 'hasDrivingLicense$',
              validations: [
                Validators.required,
              ]
            },
            {
              name: 'drivingMonth$',
              validations: [
                ValidationService.monthValidator
              ]
            },
            {
              name: 'drivingYear$',
              validations: [
                ValidationService.yearValidator
              ]
            },
            {
              name: 'driveTimesPerWeek$',
              validations: [
                Validators.required
              ]
            },
          ]
        }
      }
    ];
  }
}
```

<p>That service is being used by all the components in order to set up the HTML form bindings for each, by accessing the corresponding object key and creating nested form groups, as well as by the Summary page, whose presentation layer is only 1way bound (Model -> View).</p>

<pre class="lang-ts prettyprint-override"><code>export class FormManagerService {
    mainForm: FormGroup;

    constructor(private fb: FormBuilder) {
    }

    setupFormControls() {
        let allForms = {};
        this.forms = FormControlsService.getFormControls();

        for (let form of this.forms) {

            let resultingForm = {};

            Object.keys(form['groups']).forEach(group => {

                let formGroup = {};
                for (let field of form['groups'][group]) {
                    formGroup[field.name] = ['', this.getFieldValidators(field)];
                }

                resultingForm[group] = this.fb.group(formGroup);
            });

            allForms[form.name] = this.fb.group(resultingForm);
        }

        this.mainForm = this.fb.group(allForms);
    }

    getFieldValidators(field): Validators[] {
        let result = [];

        for (let validation of field.validations) {
            result.push(validation);
        }

        return (result.length > 0) ? [Validators.compose(result)] : [];
    }
}
</code>```

After, we started using the following syntax in the components in order to reach the form controls specified in the master form service:

personalDetailsForm$: AbstractControl;
streetaddress$: AbstractControl;

constructor(private fm: FormManagerService) {
    this.personalDetailsForm$ = this.fm.mainForm.controls['personalDetailsForm$'];
    this.streetaddress$ = this.personalDetailsForm$['controls']['address$']['controls']['streetaddress$'];
}
```

which seems like a code smell in our inexperienced eyes. We have strong concerns how an application like this will scale, given the amount of sections we'll have in the end.

We’ve been discussing different solutions but we can’t come up with one that leverages Angular’s form engine, allows us to keep our validation hierarchy intact and is also simple.

Is there a better way to achieve what we’re trying to do?

答:
Your approach and Ovangle's one seem to be pretty good but even though this SO question is solved, I want to share my solution because it's a really different approach that I think you might like or might be useful to someone else.

what solutions there are for an app wide form where Components take care of different sub parts to the global form.

We've faced that exact same issue and after months of struggling with huge, nested and sometimes polymorphic forms, we've come up with a solution that pleases us, which is simple to use and which gives us "super powers" (like type safety within both TS and HTML), access to nested errors and others.

We've decided to extract that into a separated library and open source it.

Source code is available here: https://github.com/cloudnc/ngx-sub-form

And the npm package can be installed like that npm i ngx-sub-form

Behind the scenes, our library uses ControlValueAccessor and that allows us to use it on template forms AND reactive forms (you'll get the best out of it by using reactive forms though).

So what is it all about?

Before I start explaining, if you prefer to follow along with a proper editor I've made a Stackblitz example: https://stackblitz.com/edit/so-question-angular-2-large-scale-application-forms-handling

Well an example is worth a 1000 words I guess so let's redo one part of your form (the hardest one with nested data): personalDetailsForm$

First thing to do is make sure everything is going to be type safe. Let's create the interfaces for that:

```<code>export enum Gender {
  MALE = 'Male',
  FEMALE = 'Female',
  Other = 'Other',
}

export interface Name {
  firstname: string;
  lastname: string;
}

export interface Address {
  streetaddress: string;
  city: string;
  state: string;
  zip: string;
  country: string;
}

export interface Phone {
  phone: string;
  countrycode: string;
}

export interface PersonalDetails {
  name: Name;
  gender: Gender;
  address: Address;
  phone: Phone;
}

export interface MainForm {
  // this is one example out of what you posted
  personalDetails: PersonalDetails;

  // you'll probably want to add `parent` and `responsibilities` here too
  // which I'm not going to do because `personalDetails` covers it all :)
}
</code>```

Then, we can create a component that extends NgxSubFormComponent.

Let's call it personal-details-form.component.

```<code>@Component({
  selector: 'app-personal-details-form',
  templateUrl: './personal-details-form.component.html',
  styleUrls: ['./personal-details-form.component.css'],
  providers: subformComponentProviders(PersonalDetailsFormComponent)
})
export class PersonalDetailsFormComponent extends NgxSubFormComponent<PersonalDetails> {
  protected getFormControls(): Controls<PersonalDetails> {
    return {
      name: new FormControl(null, { validators: [Validators.required] }),
      gender: new FormControl(null, { validators: [Validators.required] }),
      address: new FormControl(null, { validators: [Validators.required] }),
      phone: new FormControl(null, { validators: [Validators.required] }),
    };
  }
}
</code>```

Few things to notice here:

NgxSubFormComponent<PersonalDetails> is going to give us type safety

We have to implements the getFormControls methods which expects a dictionary of the top level keys matching an abstract control (here name, gender, address, phone)

We keep full control over the options to create the formControl (validators, async validators etc)

providers: subformComponentProviders(PersonalDetailsFormComponent) is a small utility function to create the providers necessary to use a ControlValueAccessor (cf Angular doc), you just need to pass as argument the current component

Now, for every entry of name, gender, address, phone that is an object, we create a sub form for it (so in this case everything but gender).

Here's an example with phone:

```<code>@Component({
  selector: 'app-phone-form',
  templateUrl: './phone-form.component.html',
  styleUrls: ['./phone-form.component.css'],
  providers: subformComponentProviders(PhoneFormComponent)
})
export class PhoneFormComponent extends NgxSubFormComponent<Phone> {
  protected getFormControls(): Controls<Phone> {
    return {
      phone: new FormControl(null, { validators: [Validators.required] }),
      countrycode: new FormControl(null, { validators: [Validators.required] }),
    };
  }
}
</code>```

Now, let's write the template for it:

```<code><div [formGroup]="formGroup">
  <input type="text" placeholder="Phone" [formControlName]="formControlNames.phone">
  <input type="text" placeholder="Country code" [formControlName]="formControlNames.countrycode">
</div>
</code>```

Notice that:

We define
, the formGroup here is provided by NgxSubFormComponent you don't have to create it yourself

[formControlName]="formControlNames.phone" we use property binding to have a dynamic formControlName and then use formControlNames. This type safety mechanism is offered by NgxSubFormComponent too and if your interface changes at some point (we all know about refactors...), not only your TS will error for missing properties in the form but also the HTML (when you compile with AOT)!

Next step: Let's build the PersonalDetailsFormComponent template but first just add that line into the TS: public Gender: typeof Gender = Gender; so we can safely access the enum from the view

```<code><div [formGroup]="formGroup">
    <app-name-form [formControlName]="formControlNames.name"></app-name-form>

    <select [formControlName]="formControlNames.gender">
    <option *ngFor="let gender of Gender | keyvalue" [value]="gender.value">{{ gender.value }}</option>
  </select>

  <app-address-form [formControlName]="formControlNames.address"></app-address-form>

  <app-phone-form [formControlName]="formControlNames.phone"></app-phone-form>
</div>
</code>```

Notice how we delegate the responsibility to a sub component? <app-name-form [formControlName]="formControlNames.name"></app-name-form> that's the key point here!

Final step: built the top form component

Good news, we can also use NgxSubFormComponent to enjoy type safety!

```<code>@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent extends NgxSubFormComponent<MainForm> {
  protected getFormControls(): Controls<MainForm> {
    return {
      personalDetails: new FormControl(null, { validators: [Validators.required] }),
    };
  }
}
</code>```

And the template:

```<code><form [formGroup]="formGroup">
  <app-personal-details-form [formControlName]="formControlNames.personalDetails"></app-personal-details-form>
</form>

<!-- let see how the form values looks like! -->
<h1>Values:</h1>
```{{ formGroupValues | json }}```

<!-- let see if there's any error (works with nested ones!) -->
<h1>Errors:</h1>
```{{ formGroupErrors | json }}```
</code>```

Takeaway from all of that:
 - Type safe forms
 - Reusable! Needs to reuse the address one for the parents? Sure, no worries
 - Nice utilities to build nested forms, access form control names, form values, form errors (+nested!)
 - Have you noticed any complex logic at all? No observables, no service to inject... Just defining interfaces, extending a class, pass an object with the form controls and create the view. That's it

By the way, here's a live demo of everything I've been talking about:

https://stackblitz.com/edit/so-question-angular-2-large-scale-application-forms-handling

Also, it was not necessary in that case but for forms a little bit more complex, for example when you need to handle a polymorphic object like type Animal = Cat | Dog we've got another class for that which is NgxSubFormRemapComponent but you can read the README if you need more info.

Hope it helps you scale your forms!

Edit:

If you want to go further, I've just published a blog post to explain a lot of things about forms and ngx-sub-form here https://dev.to/maxime1992/building-scalable-robust-and-type-safe-forms-with-angular-3nf9

ContentLicense: CC BY-SA 3.0

Body:
At the company I’m working for, we’re developing a large scale application with multiple forms, that the user needs to fill in in order to register for our program. When all questions have been answered, then the user reaches a section that sums up all their answers, highlights invalid answers and gives the user the chance to revisit any of the preceding form steps and revise their answers. This logic will be repeated across a range of top-level sections, each having multiple steps/pages and a summary page.

To accomplish this, we have created a component for each separate form step (they are categories like “Personal Details” or “Qualifications” etc.) along with their respective routes and a component for the Summary Page.

In order to keep it as DRY as possible, we started creating a “master” service which holds the information for all the different form steps (values, validity etc.).

import { Injectable } from '@angular/core';
import { Validators } from '@angular/forms';
import { ValidationService } from '../components/validation/index';

@Injectable()
export class FormControlsService {
  static getFormControls() {
    return [
      {
        name: 'personalDetailsForm$',
        groups: {
          name$: [
            {
              name: 'firstname$',
              validations: [
                Validators.required,
                Validators.minLength(2)
              ]
            },
            {
              name: 'lastname$',
              validations: [
                Validators.required,
                Validators.minLength(2)
              ]
            }
          ],
          gender$: [
            {
              name: 'gender$',
              validations: [
                Validators.required
              ]
            }
          ],
          address$: [
            {
              name: 'streetaddress$',
              validations: [
                Validators.required
              ]
            },
            {
              name: 'city$',
              validations: [
                Validators.required
              ]
            },
            {
              name: 'state$',
              validations: [
                Validators.required
              ]
            },
            {
              name: 'zip$',
              validations: [
                Validators.required
              ]
            },
            {
              name: 'country$',
              validations: [
                Validators.required
              ]
            }
          ],
          phone$: [
            {
              name: 'phone$',
              validations: [
                Validators.required
              ]
            },
            {
              name: 'countrycode$',
              validations: [
                Validators.required
              ]
            }
          ],
        }
      },
      {
        name: 'parentForm$',
        groups: {
          all: [
            {
              name: 'parentName$',
              validations: [
                Validators.required
              ]
            },
            {
              name: 'parentEmail$',
              validations: [
                ValidationService.emailValidator
              ]
            },
            {
              name: 'parentOccupation$'
            },
            {
              name: 'parentTelephone$'
            }
          ]
        }
      },
      {
        name: 'responsibilitiesForm$',
        groups: {
          all: [
            {
              name: 'hasDrivingLicense$',
              validations: [
                Validators.required,
              ]
            },
            {
              name: 'drivingMonth$',
              validations: [
                ValidationService.monthValidator
              ]
            },
            {
              name: 'drivingYear$',
              validations: [
                ValidationService.yearValidator
              ]
            },
            {
              name: 'driveTimesPerWeek$',
              validations: [
                Validators.required
              ]
            },
          ]
        }
      }
    ];
  }
}

That service is being used by all the components in order to set up the HTML form bindings for each, by accessing the corresponding object key and creating nested form groups, as well as by the Summary page, whose presentation layer is only 1way bound (Model -> View).

export class FormManagerService {
    mainForm: FormGroup;

    constructor(private fb: FormBuilder) {
    }

    setupFormControls() {
        let allForms = {};
        this.forms = FormControlsService.getFormControls();

        for (let form of this.forms) {

            let resultingForm = {};

            Object.keys(form['groups']).forEach(group => {

                let formGroup = {};
                for (let field of form['groups'][group]) {
                    formGroup[field.name] = ['', this.getFieldValidators(field)];
                }

                resultingForm[group] = this.fb.group(formGroup);
            });

            allForms[form.name] = this.fb.group(resultingForm);
        }

        this.mainForm = this.fb.group(allForms);
    }

    getFieldValidators(field): Validators[] {
        let result = [];

        for (let validation of field.validations) {
            result.push(validation);
        }

        return (result.length > 0) ? [Validators.compose(result)] : [];
    }
}

After, we started using the following syntax in the components in order to reach the form controls specified in the master form service:

personalDetailsForm$: AbstractControl;
streetaddress$: AbstractControl;

constructor(private fm: FormManagerService) {
    this.personalDetailsForm$ = this.fm.mainForm.controls['personalDetailsForm$'];
    this.streetaddress$ = this.personalDetailsForm$['controls']['address$']['controls']['streetaddress$'];
}

which seems like a code smell in our inexperienced eyes. We have strong concerns how an application like this will scale, given the amount of sections we'll have in the end.

We’ve been discussing different solutions but we can’t come up with one that leverages Angular’s form engine, allows us to keep our validation hierarchy intact and is also simple.

Is there a better way to achieve what we’re trying to do?

Body:
Your approach and Ovangle's one seem to be pretty good but even though this SO question is solved, I want to share my solution because it's a really different approach that I think you might like or might be useful to someone else.

what solutions there are for an app wide form where Components take care of different sub parts to the global form.

We've faced that exact same issue and after months of struggling with huge, nested and sometimes polymorphic forms, we've come up with a solution that pleases us, which is simple to use and which gives us "super powers" (like type safety within both TS and HTML), access to nested errors and others.

We've decided to extract that into a separated library and open source it.

Source code is available here: https://github.com/cloudnc/ngx-sub-form

And the npm package can be installed like that npm i ngx-sub-form

Behind the scenes, our library uses ControlValueAccessor and that allows us to use it on template forms AND reactive forms (you'll get the best out of it by using reactive forms though).

So what is it all about?

Before I start explaining, if you prefer to follow along with a proper editor I've made a Stackblitz example: https://stackblitz.com/edit/so-question-angular-2-large-scale-application-forms-handling

Well an example is worth a 1000 words I guess so let's redo one part of your form (the hardest one with nested data): personalDetailsForm$

First thing to do is make sure everything is going to be type safe. Let's create the interfaces for that:

export enum Gender {
  MALE = 'Male',
  FEMALE = 'Female',
  Other = 'Other',
}

export interface Name {
  firstname: string;
  lastname: string;
}

export interface Address {
  streetaddress: string;
  city: string;
  state: string;
  zip: string;
  country: string;
}

export interface Phone {
  phone: string;
  countrycode: string;
}

export interface PersonalDetails {
  name: Name;
  gender: Gender;
  address: Address;
  phone: Phone;
}

export interface MainForm {
  // this is one example out of what you posted
  personalDetails: PersonalDetails;

  // you'll probably want to add `parent` and `responsibilities` here too
  // which I'm not going to do because `personalDetails` covers it all :)
}

Then, we can create a component that extends NgxSubFormComponent.

Let's call it personal-details-form.component.

@Component({
  selector: 'app-personal-details-form',
  templateUrl: './personal-details-form.component.html',
  styleUrls: ['./personal-details-form.component.css'],
  providers: subformComponentProviders(PersonalDetailsFormComponent)
})
export class PersonalDetailsFormComponent extends NgxSubFormComponent<PersonalDetails> {
  protected getFormControls(): Controls<PersonalDetails> {
    return {
      name: new FormControl(null, { validators: [Validators.required] }),
      gender: new FormControl(null, { validators: [Validators.required] }),
      address: new FormControl(null, { validators: [Validators.required] }),
      phone: new FormControl(null, { validators: [Validators.required] }),
    };
  }
}

Few things to notice here:

NgxSubFormComponent<PersonalDetails> is going to give us type safety

We have to implements the getFormControls methods which expects a dictionary of the top level keys matching an abstract control (here name, gender, address, phone)

We keep full control over the options to create the formControl (validators, async validators etc)

providers: subformComponentProviders(PersonalDetailsFormComponent) is a small utility function to create the providers necessary to use a ControlValueAccessor (cf Angular doc), you just need to pass as argument the current component

Now, for every entry of name, gender, address, phone that is an object, we create a sub form for it (so in this case everything but gender).

Here's an example with phone:

@Component({
  selector: 'app-phone-form',
  templateUrl: './phone-form.component.html',
  styleUrls: ['./phone-form.component.css'],
  providers: subformComponentProviders(PhoneFormComponent)
})
export class PhoneFormComponent extends NgxSubFormComponent<Phone> {
  protected getFormControls(): Controls<Phone> {
    return {
      phone: new FormControl(null, { validators: [Validators.required] }),
      countrycode: new FormControl(null, { validators: [Validators.required] }),
    };
  }
}

Now, let's write the template for it:

<div [formGroup]="formGroup">
  <input type="text" placeholder="Phone" [formControlName]="formControlNames.phone">
  <input type="text" placeholder="Country code" [formControlName]="formControlNames.countrycode">
</div>

Notice that:

We define <div [formGroup]="formGroup">, the formGroup here is provided by NgxSubFormComponent you don't have to create it yourself

[formControlName]="formControlNames.phone" we use property binding to have a dynamic formControlName and then use formControlNames. This type safety mechanism is offered by NgxSubFormComponent too and if your interface changes at some point (we all know about refactors...), not only your TS will error for missing properties in the form but also the HTML (when you compile with AOT)!

Next step: Let's build the PersonalDetailsFormComponent template but first just add that line into the TS: public Gender: typeof Gender = Gender; so we can safely access the enum from the view

<div [formGroup]="formGroup">
    <app-name-form [formControlName]="formControlNames.name"></app-name-form>

    <select [formControlName]="formControlNames.gender">
    <option *ngFor="let gender of Gender | keyvalue" [value]="gender.value">{{ gender.value }}</option>
  </select>

  <app-address-form [formControlName]="formControlNames.address"></app-address-form>

  <app-phone-form [formControlName]="formControlNames.phone"></app-phone-form>
</div>

Notice how we delegate the responsibility to a sub component? <app-name-form [formControlName]="formControlNames.name"></app-name-form> that's the key point here!

Final step: built the top form component

Good news, we can also use NgxSubFormComponent to enjoy type safety!

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent extends NgxSubFormComponent<MainForm> {
  protected getFormControls(): Controls<MainForm> {
    return {
      personalDetails: new FormControl(null, { validators: [Validators.required] }),
    };
  }
}

And the template:

<form [formGroup]="formGroup">
  <app-personal-details-form [formControlName]="formControlNames.personalDetails"></app-personal-details-form>
</form>

<!-- let see how the form values looks like! -->
<h1>Values:</h1>
<pre>{{ formGroupValues | json }}</pre>

<!-- let see if there's any error (works with nested ones!) -->
<h1>Errors:</h1>
<pre>{{ formGroupErrors | json }}</pre>

Takeaway from all of that:
 - Type safe forms
 - Reusable! Needs to reuse the address one for the parents? Sure, no worries
 - Nice utilities to build nested forms, access form control names, form values, form errors (+nested!)
 - Have you noticed any complex logic at all? No observables, no service to inject... Just defining interfaces, extending a class, pass an object with the form controls and create the view. That's it

By the way, here's a live demo of everything I've been talking about:

https://stackblitz.com/edit/so-question-angular-2-large-scale-application-forms-handling

Also, it was not necessary in that case but for forms a little bit more complex, for example when you need to handle a polymorphic object like type Animal = Cat | Dog we've got another class for that which is NgxSubFormRemapComponent but you can read the README if you need more info.

Hope it helps you scale your forms!

Edit:

If you want to go further, I've just published a blog post to explain a lot of things about forms and ngx-sub-form here https://dev.to/maxime1992/building-scalable-robust-and-type-safe-forms-with-angular-3nf9


问:
insert in std::map is throwing error. The key is a std::pair and the value is a short
```<code>#include <iostream>
#include <map>
#include <utility>
int main()
    {
        std::pair<std::string, std::string> p;
        std::map< std::pair<std::string, std::string>, short> m;
       // p = std::make_pair("A", "a1");
        m.insert(std::make_pair("A", "a1"), 10);
        return 0;
    }
</code>```

This code is throwing the following error

```<code>maptest.cpp: In function ‘int main()’:
maptest.cpp:9: error: no matching function for call to
‘std::map<std::pair<std::basic_string<char, std::char_traits<char>,
std::allocator<char> >, std::basic_string<char, std::char_traits<char>,
std::allocator<char> > >, short int,
std::less<std::pair<std::basic_string<char, std::char_traits<char>,
std::allocator<char> >, std::basic_string<char, std::char_traits<char>,
std::allocator<char> > > >, std::allocator<std::pair<const
std::pair<std::basic_string<char, std::char_traits<char>,
std::allocator<char> >, std::basic_string<char, std::char_traits<char>,
std::allocator<char> > >, short int> > >::insert(std::pair<const char*,
const char*>, int)’
</code>```

I am trying to do a std map insertion. The kwy is a std pair and value is a short. But I am getting the above mentioned error.
What am I doing wrong here? Pleas help.

答:
There is simply no insert method with key and value arguments i.e map<...>::insert(K key, V value). Instead it accepts key-value pair, so this code should work:

```<code>#include <iostream>
#include <map>
#include <utility>
int main()
{
        std::pair<std::string, std::string> p;
        std::map< std::pair<std::string, std::string>, short> m;

        auto&& key = std::make_pair("A", "a1");
        short value = 10;
        auto&& key_value_pair = std::make_pair(key, value);
        //Structured bindings are c++17
        auto&&[IT, wasInserted] = m.insert(key_value_pair);

        return 0;
}
</code>```

I would recommend using C++17 method try_emplace which has key and value arguments:

```<code>auto&&[IT, wasInserted] = m.try_emplace(key, value);
</code>```

Body:
#include <iostream>
#include <map>
#include <utility>
int main()
    {
        std::pair<std::string, std::string> p;
        std::map< std::pair<std::string, std::string>, short> m;
       // p = std::make_pair("A", "a1");
        m.insert(std::make_pair("A", "a1"), 10);
        return 0;
    }

This code is throwing the following error

maptest.cpp: In function ‘int main()’:
maptest.cpp:9: error: no matching function for call to
‘std::map<std::pair<std::basic_string<char, std::char_traits<char>,
std::allocator<char> >, std::basic_string<char, std::char_traits<char>,
std::allocator<char> > >, short int,
std::less<std::pair<std::basic_string<char, std::char_traits<char>,
std::allocator<char> >, std::basic_string<char, std::char_traits<char>,
std::allocator<char> > > >, std::allocator<std::pair<const
std::pair<std::basic_string<char, std::char_traits<char>,
std::allocator<char> >, std::basic_string<char, std::char_traits<char>,
std::allocator<char> > >, short int> > >::insert(std::pair<const char*,
const char*>, int)’

I am trying to do a std map insertion. The kwy is a std pair and value is a short. But I am getting the above mentioned error.
What am I doing wrong here? Pleas help.

Body:
There is simply no insert method with key and value arguments i.e map<...>::insert(K key, V value). Instead it accepts key-value pair, so this code should work:

#include <iostream>
#include <map>
#include <utility>
int main()
{
        std::pair<std::string, std::string> p;
        std::map< std::pair<std::string, std::string>, short> m;

        auto&& key = std::make_pair("A", "a1");
        short value = 10;
        auto&& key_value_pair = std::make_pair(key, value);
        //Structured bindings are c++17
        auto&&[IT, wasInserted] = m.insert(key_value_pair);

        return 0;
}

I would recommend using C++17 method try_emplace which has key and value arguments:

auto&&[IT, wasInserted] = m.try_emplace(key, value);


问:
How to include libraried that are included on the server to pom?
I have a Libery server local instalation, that have some .jar files included. I would like to include this files as dependacies or in some other way to my pom.xml.

server.xml :

```<code>...
<library id="DB2Type4">
   <fileset dir="path" includes="db22first.jar db2second.jar"/>
</library>
...
</code>```

答: You could use local repository ulr, or private maven repository server like Artifactory.</p>

Body:
I have a Libery server local instalation, that have some .jar files included. I would like to include this files as dependacies or in some other way to my pom.xml.

server.xml :

...
<library id="DB2Type4">
   <fileset dir="path" includes="db22first.jar db2second.jar"/>
</library>
...


问:
Is there a way to not pass anything to a child prop method?
Error: TypeError: _this.props.handleChange is not a function

I have a React component that has a prop method that is used in another view component.

The problem is that my other view components need to use my Child component but it causes an error because it is required to use the prop method.

class NeedsPropMethod extends Component {
 handleChange = value => {
  // receives the value
 }

 return (
  <Child toy="car" color="blue" handleChange={this.handleChange}>
 )
}

class DoesntNeedPropMethod extends Component {
 return (
  <Child toy="car" color="blue"}>
 )
}

class Child extends Component {
 return (
  this.props.toy; // "car"
  this.props.color; // "blue"
  this.props.handleChange(value) // I do not need this but it gives me the error above
 );
}
```

答:
You can add propTypes to your code like this to make it become optional

```<code>Child.propTypes = {
  handleChange: PropTypes.func
};
</code>```

so your handleChange will be optional

Body:
You can add propTypes to your code like this to make it become optional

Child.propTypes = {
  handleChange: PropTypes.func
};

so your handleChange will be optional


问:
How to handle an array in a stored procedure on DB2?
I'm developing an app which store data in DB2, and I should be able to 'delete' data in bulk in a table of a DB. Actually the way to 'delete' the data is by changing its 'deleted' value to 'Y'.

The form of the table is:

id |  name   | deleted |

1  | name1 | N  |

2  | name2 | N  |

...

x  | namex | N  |

What I want to do is to make a SQL stored procedure which take as a parameter one array with the IDs of the items I need to change from 'N' to 'Y'.

The way I do it (individually) is:

```<code>UPDATE MyTable DELETED = 'Y' where id = '1';
</code>```

So with an stored procedure I should only send the array with this form:

```<code>[1, 20, 5, ... , x]
</code>```

and the rows with those Id should be changed to Y.

The structure for the stored procedure I was thinking about is:

```<code>PROCEDURE deleteSeveral (arrayWithIds)

LANGUAGE SQL

BEGIN

    -- loop for ids array
            UPDATE MyTable DELETED = 'Y' where id = arrayWithIds[i];
    -- Ciclo para recorrer el arreglo

END
</code>```

Could anybody help me with this? Thanks!

答:
Try to pass the list of IDs as an "xml-like" string:</p>

```<code>UPDATE MyTable t
SET DELETED = 'Y'
where exists (
  select 1
  from xmltable (
    '$D/d/i' passing xmlparse(document '<d><i>1</i><i>20</i><i>5</i></d>') as "D"
    columns
      i int path '.'
  ) p
  where p.i=t.id
)
</code>```

Body:
I'm developing an app which store data in DB2, and I should be able to 'delete' data in bulk in a table of a DB. Actually the way to 'delete' the data is by changing its 'deleted' value to 'Y'.

The form of the table is:

id |  name   | deleted |

1  | name1 | N  |

2  | name2 | N  |

...

x  | namex | N  |

What I want to do is to make a SQL stored procedure which take as a parameter one array with the IDs of the items I need to change from 'N' to 'Y'.

The way I do it (individually) is:

UPDATE MyTable DELETED = 'Y' where id = '1';

So with an stored procedure I should only send the array with this form:

[1, 20, 5, ... , x]

and the rows with those Id should be changed to Y.

The structure for the stored procedure I was thinking about is:

PROCEDURE deleteSeveral (arrayWithIds)

LANGUAGE SQL

BEGIN

    -- loop for ids array
            UPDATE MyTable DELETED = 'Y' where id = arrayWithIds[i];
    -- Ciclo para recorrer el arreglo

END

Could anybody help me with this? Thanks!

Body:
Try to pass the list of IDs as an "xml-like" string:

UPDATE MyTable t
SET DELETED = 'Y'
where exists (
  select 1
  from xmltable (
    '$D/d/i' passing xmlparse(document '<d><i>1</i><i>20</i><i>5</i></d>') as "D"
    columns
      i int path '.'
  ) p
  where p.i=t.id
)


问:
stl decomposition in r for daily data shows error only univariate series are allowed
I am trying to decompose a daily time series, however this gives an

Error 'only univariate series are allowed'

When I have clearly converted the daily data in to time series using the ts function.  How can I fix this?

I have tried solutions from other posts but none has worked for me. My data comprise of 669 observations, where the data spans from Jan 2017 to March 2019.

```<code>SCTB.LV.TS = ts(SCTB_TS[,-1], start = c(2017,6,01), frequency = 365)
SCTB.LV.TS

decomp <- stl(log(SCTB.LV.TS), s.window = 'Periodic')
</code>```

Before converting the data frame to time series the data looks like below

```<code>Date    Count
6/1/2017    329
6/2/2017    284
6/3/2017    429
6/4/2017    454
6/5/2017    362
6/6/2017    334
6/7/2017    369
6/8/2017    319
6/9/2017    349
6/10/2017   373
6/11/2017   456
6/12/2017   344
</code>```

答:
I get no complaints of 'only univariate series are allowed', only about too few periods, which is understandable.

```<code>SCTB_TS <- read.table(text="
    Date      Count
    6/1/2017    329
    6/2/2017    284
    6/3/2017    429
    6/4/2017    454
    6/5/2017    362
    6/6/2017    334
    6/7/2017    369
    6/8/2017    319
    6/9/2017    349
    6/10/2017   373
    6/11/2017   456
    6/12/2017   344", header=TRUE)

# your argument to start didn't make sense, so I changed it
SCTB.LV.TS <- ts(SCTB_TS[,-1], start=c(2017, 1), frequency=365)
SCTB.LV.TS

decomp <- stl(log(SCTB.LV.TS), s.window="periodic")
</code>```

Error in stl(log(SCTB.LV.TS), s.window = "periodic") :    series is
  not periodic or has less than two periods

Which again is understandable. How can you do seasonal decomposition when you only have 12/365 period to work with?

Body:
I am trying to decompose a daily time series, however this gives an

Error 'only univariate series are allowed'

When I have clearly converted the daily data in to time series using the ts function.  How can I fix this?

I have tried solutions from other posts but none has worked for me. My data comprise of 669 observations, where the data spans from Jan 2017 to March 2019.

SCTB.LV.TS = ts(SCTB_TS[,-1], start = c(2017,6,01), frequency = 365)
SCTB.LV.TS

decomp <- stl(log(SCTB.LV.TS), s.window = 'Periodic')

Before converting the data frame to time series the data looks like below

Date    Count
6/1/2017    329
6/2/2017    284
6/3/2017    429
6/4/2017    454
6/5/2017    362
6/6/2017    334
6/7/2017    369
6/8/2017    319
6/9/2017    349
6/10/2017   373
6/11/2017   456
6/12/2017   344

Body:
I get no complaints of 'only univariate series are allowed', only about too few periods, which is understandable.

SCTB_TS <- read.table(text="
    Date      Count
    6/1/2017    329
    6/2/2017    284
    6/3/2017    429
    6/4/2017    454
    6/5/2017    362
    6/6/2017    334
    6/7/2017    369
    6/8/2017    319
    6/9/2017    349
    6/10/2017   373
    6/11/2017   456
    6/12/2017   344", header=TRUE)

# your argument to start didn't make sense, so I changed it
SCTB.LV.TS <- ts(SCTB_TS[,-1], start=c(2017, 1), frequency=365)
SCTB.LV.TS

decomp <- stl(log(SCTB.LV.TS), s.window="periodic")

Error in stl(log(SCTB.LV.TS), s.window = "periodic") :    series is
  not periodic or has less than two periods

Which again is understandable. How can you do seasonal decomposition when you only have 12/365 period to work with?


问:
Blatant floating point error in C++ program
I am assigning a double literal to a double variable.
The variable's value gets truncated, otherwise I cannot understand why, for example the difference diff is 0.0.

Sorry for the code duplication at setprecision but I am really pissed off.

```<code>#include <iostream>
#include <iomanip>
#include <cmath>
#include <limits>

int main()
{
    long double d = 1300010000000000000144.5700788999;
    long double d1 = 1300010000000000000000.0;
    long double diff = d - d1; // shall be 144.5700788999!!!
    long double d2 = 0.5700788999;

    std::cout << "d = " << std::fixed << std::setprecision(std::numeric_limits<long double>::digits10 + 1) << d << '\n';
    std::cout << "d1 = " << std::fixed << std::setprecision(std::numeric_limits<long double>::digits10 + 1) << d1 << '\n';
    std::cout << "d - d1 = " << std::fixed << std::setprecision(std::numeric_limits<long double>::digits10 + 1) << diff << '\n';
    std::cout << "d2 = " << std::fixed << std::setprecision(std::numeric_limits<long double>::digits10 + 1) << d2 << '\n';
}
</code>```

This is the output:

```<code>d = 1300009999999999900000.0000000000000000
d1 = 1300009999999999900000.0000000000000000
d - d1 = 0.0000000000000000
d2 = 0.5700788999000001
</code>```

I am expecting diff to be 144.5700788999 but it is 0.0

So, how to deal with it? (Window 7 and higher, VS 2013)

...To use two doubles, one for high values and one for low values?
Like, instead using d to use d1 and d2?

答:
Well, you're faced Wild West of Floating Points! Do not trust anybody, do not expect much, keep your hand on your gun.

The thing is: floating point representation is a split. Given amount of bytes are spent to store two pieces, mantissa value and tenth power (simplified description for sure, however it would suffice our needs here). Once you have a value that is too much to fit into the mantissa, what should computer do? It has to carry the rest to another portion of bytes (like Big Math libraries do) or just round to the closest possible value. Let me show:

```<code>d2 =                      0.5700788999; // shows                      0.5700788999000001
d2 = 1300010000000000000000.5700788999; // shows 1300009999999999934464.0000000000000000000
</code>```

Hey, where is my fractional part in 2nd case? It's gone! Call the police! Oh, wait, it just doesn't fit into... This is why diff gives zero: mantisses are so huge that the tail part (where the actual difference is) can not be stored. And as soon as the rest of the digits are the same, we have zero diff.

After careful comparison, you can spot another thing: printed value is close to the assigned one, however it's a bit different. This is because a mantissa is just a sum of powers of 2. So, to represent the value, computer has to round assigned value to closest binary-compatible one. This is another sort of pain sometimes and you should not compare floating-point numbers by equality operator, just evaluate a difference and compare it with expected delta of intended precision.

Body:
I am assigning a double literal to a double variable.
The variable's value gets truncated, otherwise I cannot understand why, for example the difference diff is 0.0.

Sorry for the code duplication at setprecision but I am really pissed off.

#include <iostream>
#include <iomanip>
#include <cmath>
#include <limits>

int main()
{
    long double d = 1300010000000000000144.5700788999;
    long double d1 = 1300010000000000000000.0;
    long double diff = d - d1; // shall be 144.5700788999!!!
    long double d2 = 0.5700788999;

    std::cout << "d = " << std::fixed << std::setprecision(std::numeric_limits<long double>::digits10 + 1) << d << '\n';
    std::cout << "d1 = " << std::fixed << std::setprecision(std::numeric_limits<long double>::digits10 + 1) << d1 << '\n';
    std::cout << "d - d1 = " << std::fixed << std::setprecision(std::numeric_limits<long double>::digits10 + 1) << diff << '\n';
    std::cout << "d2 = " << std::fixed << std::setprecision(std::numeric_limits<long double>::digits10 + 1) << d2 << '\n';
}

This is the output:

d = 1300009999999999900000.0000000000000000
d1 = 1300009999999999900000.0000000000000000
d - d1 = 0.0000000000000000
d2 = 0.5700788999000001

I am expecting diff to be 144.5700788999 but it is 0.0

So, how to deal with it? (Window 7 and higher, VS 2013)

...To use two doubles, one for high values and one for low values?
Like, instead using d to use d1 and d2?

Body:
Well, you're faced Wild West of Floating Points! Do not trust anybody, do not expect much, keep your hand on your gun.

The thing is: floating point representation is a split. Given amount of bytes are spent to store two pieces, mantissa value and tenth power (simplified description for sure, however it would suffice our needs here). Once you have a value that is too much to fit into the mantissa, what should computer do? It has to carry the rest to another portion of bytes (like Big Math libraries do) or just round to the closest possible value. Let me show:

d2 =                      0.5700788999; // shows                      0.5700788999000001
d2 = 1300010000000000000000.5700788999; // shows 1300009999999999934464.0000000000000000000

Hey, where is my fractional part in 2nd case? It's gone! Call the police! Oh, wait, it just doesn't fit into... This is why diff gives zero: mantisses are so huge that the tail part (where the actual difference is) can not be stored. And as soon as the rest of the digits are the same, we have zero diff.

After careful comparison, you can spot another thing: printed value is close to the assigned one, however it's a bit different. This is because a mantissa is just a sum of powers of 2. So, to represent the value, computer has to round assigned value to closest binary-compatible one. This is another sort of pain sometimes and you should not compare floating-point numbers by equality operator, just evaluate a difference and compare it with expected delta of intended precision.


问:
jupyter notebook: show seaborn plot again
Trying to build seaborn FacetGrid plots in a Jupyter notebook. Upon creation, it displays just fine. But if I manipulate the chart and want to see it again, I cannot. I can only get the object listing.

How can I show the chart a second time?

答: g.fig doesn't work.Instead, g.figure works out.


问:
mysql stored procedure set value from table
I've got a following, simple table:

```<code>mysql> select * from version;
+----+---------+
| id | version |
+----+---------+
|  1 | 1       |
+----+---------+
1 row in set (0.00 sec)
</code>```

I need to create a stored procedure that will do something (or nothing) depending on the value of this table (precisely, the only row of this table).

```<code>DELIMITER $$
DROP PROCEDURE IF EXISTS upgrade_version $$
CREATE PROCEDURE upgrade_version(current_version INTEGER, script TEXT)
BEGIN
  DECLARE version INT(11);
  SET version = (SELECT `version` FROM `version` WHERE `id` = 1 LIMIT 1);
  SELECT version;
  IF version = current_version + 1 THEN
    PREPARE upgrade_stmt FROM script;
    EXECUTE upgrade_stmt;
    UPDATE `version` SET `version` = `version` + 1 WHERE `id` = 1;
  ENDIF;
END $$
DELIMITER ;
</code>```

To be called within:

```<code>CALL upgrade_version(1,'ALTER TABLE ...');
</code>```

It is syntactically incorrect, mysql returns:

```<code>1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'script;
    EXECUTE upgrade_stmt;
    UPDATE `version` SET `version` = `version`' at line 7
</code>```

What is wrong?

答:
Set Value To Declare variable

```<code>       DELIMITER $$
       create procedure Testing()
           begin
            declare Regione int;
            set Regione=(select  id from users
            where id=1) ;
            select Regione ;
           end $$
         DELIMITER;
</code>```

Body:
I've got a following, simple table:

mysql> select * from version;
+----+---------+
| id | version |
+----+---------+
|  1 | 1       |
+----+---------+
1 row in set (0.00 sec)

I need to create a stored procedure that will do something (or nothing) depending on the value of this table (precisely, the only row of this table).

DELIMITER $$
DROP PROCEDURE IF EXISTS upgrade_version $$
CREATE PROCEDURE upgrade_version(current_version INTEGER, script TEXT)
BEGIN
  DECLARE version INT(11);
  SET version = (SELECT `version` FROM `version` WHERE `id` = 1 LIMIT 1);
  SELECT version;
  IF version = current_version + 1 THEN
    PREPARE upgrade_stmt FROM script;
    EXECUTE upgrade_stmt;
    UPDATE `version` SET `version` = `version` + 1 WHERE `id` = 1;
  ENDIF;
END $$
DELIMITER ;

To be called within:

CALL upgrade_version(1,'ALTER TABLE ...');

It is syntactically incorrect, mysql returns:

1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'script;
    EXECUTE upgrade_stmt;
    UPDATE `version` SET `version` = `version`' at line 7

What is wrong?

Body:
Set Value To Declare variable

       DELIMITER $$
       create procedure Testing()
           begin
            declare Regione int;
            set Regione=(select  id from users
            where id=1) ;
            select Regione ;
           end $$
         DELIMITER;


问:
Keeping track of boolean data
I need to keep track of n samples. The information I am keeping track of is of boolean type, i.e. something is true or false. As soon as I am on sample n+1, i basically want to ignore the oldest sample and record information about the newest one.

So say I keep track of samples, I may have something like

OLDEST 0   0   1   1  0   NEWEST

If the next sample is 1, this will become

OLDEST 0   1   1   0  1   NEWEST

if the next one is 0, this will become...

OLDEST 1   1   0   1  0   NEWEST

So what is the best way to implement this in terms of simplicity and memory?

Some ideas I had:

Vector of bool (this would require shifting elements so seems expensive)
    Storing it as bits...and using bit shifting (memorywise --cheap? but is there a limit on the number of samples?)
    Linked lists? (might be an overkill for the task)

Thanks for the ideas and suggestions :)

答:
It really depends on how many samples you want to keep.
vector<bool> could be a valid option; I would expect an
erase() on the first element to be reasonably efficient.
Otherwise, there's deque<bool>.  If you know how many elements
you want to keep at compile time, bitset<N> is probably better
than either.

In any case, you'll have to wrap the standard container in some
additional logic; none have the actual logic you need (that of
a ring buffer).

Title: Keeping track of boolean data


问:
Tensorflow Hub and CGI
I have installed tensorflow_hub package in python 3.6. The package can be imported correctly when I test it in python console. However, when I use it in a cgi-script an error occurs:

```<code>no module named tensorflow_hub
</code>```

Source Code

```<code>#!/usr/bin/python3.6
import sys
import cgitb
import cgi
t = ''
try:
   import tensorflow_hub as tf
except Exception as e:
   t = str(e)
cgitb.enable()
sys.stdout.write("Content-Type: application/json")
sys.stdout.write("\n")
sys.stdout.write("\n")

result = dict()
result['data'] = t

sys.stdout.write(json.dumps(result,indent=1))
sys.stdout.write("\n")
</code>```

Could you explain me which is the problem? I tested other packages (e.g. tensorflow) but I hadn't any issue.

Edit

To install the package:

```<code>pip3 install tensorflow-hub

which pip3
     /usr/bin/pip3
</code>```

答:
To answer my question giving feedback to others with similar problem:

The tensorflow_hub was in the ~/.local/lib/python3.6/site-packages/ where the cgi hasn't got access.

To find the location:

```<code>pip3 show tensorflow_hub
</code>```

I observed that all the other packages where in /usr/local/lib/python3.6/dist-packages/

So, I moved the package from the first location to the second.

This helped me:
Why can't python find some modules when I'm running CGI scripts from the web?

Title: Tensorflow Hub and CGI

Body:
I have installed tensorflow_hub package in python 3.6. The package can be imported correctly when I test it in python console. However, when I use it in a cgi-script an error occurs:

no module named tensorflow_hub

Source Code

#!/usr/bin/python3.6
import sys
import cgitb
import cgi
t = ''
try:
   import tensorflow_hub as tf
except Exception as e:
   t = str(e)
cgitb.enable()
sys.stdout.write("Content-Type: application/json")
sys.stdout.write("\n")
sys.stdout.write("\n")

result = dict()
result['data'] = t

sys.stdout.write(json.dumps(result,indent=1))
sys.stdout.write("\n")

Could you explain me which is the problem? I tested other packages (e.g. tensorflow) but I hadn't any issue.

Edit

To install the package:

pip3 install tensorflow-hub

which pip3
     /usr/bin/pip3

Body:
To answer my question giving feedback to others with similar problem:

The tensorflow_hub was in the ~/.local/lib/python3.6/site-packages/ where the cgi hasn't got access.

To find the location:

pip3 show tensorflow_hub

I observed that all the other packages where in /usr/local/lib/python3.6/dist-packages/

So, I moved the package from the first location to the second.

This helped me:
Why can't python find some modules when I'm running CGI scripts from the web?


问:
Azure DevOps is it possible to group builds which are in queue
I have multiple check in happening in our dev branch and each checking triggers a build. this causes a log of queue in the builds.

It is possible to setup in such a way all the builds in the queue could be clubbed together and built?

答:
Yes! in the build trigger options when you check the "Enable continues integration" you have another check box:

[ ] Batch changes while a build is in progress.

Just check it :)

If you are using .yaml builds just add this to the trigger section:

```<code>batch: true
</code>```

Body:
Yes! in the build trigger options when you check the "Enable continues integration" you have another check box:

[ ] Batch changes while a build is in progress.

Just check it :)

If you are using .yaml builds just add this to the trigger section:

batch: true


问:
SQL server python service-"DECLARE @myscript NVARCHAR(MAX) = N' " gives syntax error, what could be the possible mistake?
I am using SQL Server 2017 with in-database Machine Learning with python scripts with a goal to run Machine Learning models.
While following a tutorial on PluralSight 'Getting started with Python on SQL Server' within a sql file, I Declare a variable with its data type and enter my Python script into it. But it throws a syntax error on the first line.
My code is as below :

I am writing the statement as per the tutorial.

```<code>DECLARE @myscript NVARCHAR(MAX) = N
</code>```

error is as:

```<code>DECLARE @myscript NVARCHAR(MAX) = N'
                             ^
SyntaxError: invalid syntax
</code>```

Expectedly the code must declare a variable @myscript which I then use it during definition of input code.

Here is the full code below

```<code>DECLARE @myscript NVARCHAR(MAX) = N'
import sys
sys.path += ["D:\\sql_queries"]
import ml_models as ms
mydf = ms.fill_na(mydf)
mydf = ms.backup_columns(mydf)
mydf = ms.shaping_df(mydf)
mydf = ms.normalising_numerical_mydf(mydf)
mydf = ms.date_to_datetime(mydf)
mydf = ms.split_years_months(mydf)
mydf = ms.replacing_strings_with_integers(mydf)
mydf = ms.type_casting(mydf)
mydf = ms.label_encoder(mydf)
mydf = ms.drop_unnecessary_features(mydf)
x_train, x_valid, x_test, y_train, y_valid = ms.seperate_train_test_validation(mydf)
y_pred_rf = ms.random_forest_model(x_train, y_train, x_valid, y_valid, x_test)
y_pred_ada = ms.adboost_model(x_train, y_train, x_valid, y_valid, x_test)
y_pred_xgb = ms.xgb_model(x_train, y_train, x_valid, y_valid, x_test)
y_pred_lgb = ms.light_gradient_boost_model(x_train, y_train, x_valid, y_valid, x_test)

predictions = y_pred_rf*0.3 + y_pred_ada*0.2 + y_pred_xgb*0.2 + y_pred_xgb*0.3
';

DECLARE @myquery NVARCHAR(MAX) = N'
select * from banktest.dbo.train
UNION ALL
select *, 6 as loan_default from banktest.dbo.test;'
;

DECLARE @predictions float;

EXEC sp_execute_external_script
    @language = N'Python'
    , @script = @myscript
    , @input_data_1 = @myquery
    , @input_data_1_name = N'mydf'
    , @output_data_1_name = N'predictions'
    , @parallel = 1
    , @params = N'@predictions float out'
    , @predictions = @predictions OUT
WITH RESULT SETS ((predicted_value nvarchar(MAX)));
</code>```

答: The error was due to directly running the code on python server using VS Code. For it to display the output we must execute the code by Ctrl+Shift+P

Body:
I am using SQL Server 2017 with in-database Machine Learning with python scripts with a goal to run Machine Learning models.
While following a tutorial on PluralSight 'Getting started with Python on SQL Server' within a sql file, I Declare a variable with its data type and enter my Python script into it. But it throws a syntax error on the first line.
My code is as below :

I am writing the statement as per the tutorial.

DECLARE @myscript NVARCHAR(MAX) = N

error is as:

DECLARE @myscript NVARCHAR(MAX) = N'
                             ^
SyntaxError: invalid syntax

Expectedly the code must declare a variable @myscript which I then use it during definition of input code.

Here is the full code below

DECLARE @myscript NVARCHAR(MAX) = N'
import sys
sys.path += ["D:\\sql_queries"]
import ml_models as ms
mydf = ms.fill_na(mydf)
mydf = ms.backup_columns(mydf)
mydf = ms.shaping_df(mydf)
mydf = ms.normalising_numerical_mydf(mydf)
mydf = ms.date_to_datetime(mydf)
mydf = ms.split_years_months(mydf)
mydf = ms.replacing_strings_with_integers(mydf)
mydf = ms.type_casting(mydf)
mydf = ms.label_encoder(mydf)
mydf = ms.drop_unnecessary_features(mydf)
x_train, x_valid, x_test, y_train, y_valid = ms.seperate_train_test_validation(mydf)
y_pred_rf = ms.random_forest_model(x_train, y_train, x_valid, y_valid, x_test)
y_pred_ada = ms.adboost_model(x_train, y_train, x_valid, y_valid, x_test)
y_pred_xgb = ms.xgb_model(x_train, y_train, x_valid, y_valid, x_test)
y_pred_lgb = ms.light_gradient_boost_model(x_train, y_train, x_valid, y_valid, x_test)

predictions = y_pred_rf*0.3 + y_pred_ada*0.2 + y_pred_xgb*0.2 + y_pred_xgb*0.3
';

DECLARE @myquery NVARCHAR(MAX) = N'
select * from banktest.dbo.train
UNION ALL
select *, 6 as loan_default from banktest.dbo.test;'
;

DECLARE @predictions float;

EXEC sp_execute_external_script
    @language = N'Python'
    , @script = @myscript
    , @input_data_1 = @myquery
    , @input_data_1_name = N'mydf'
    , @output_data_1_name = N'predictions'
    , @parallel = 1
    , @params = N'@predictions float out'
    , @predictions = @predictions OUT
WITH RESULT SETS ((predicted_value nvarchar(MAX)));


问:
Angular2 - How to reference an image in the template
I have this structure:

And I want to reference "logo.svg" in my component.
Like this:

```<code>@Component(
    selector: 'my-app',
    template: '<img src="logo.svg">')
class AppComponent {}
</code>```

What should I put in the src attribute to reference the logo correctly? Is there a specific scheme to use?

答:
For Angular 5.0.0 you can reference it like this:

@Component(
    selector: 'my-app',
    template: '')
class AppComponent {}
```

Replace angular_app with the name defined in your pubspec.yaml.

Body:
I have this structure:

And I want to reference "logo.svg" in my component.
Like this:

@Component(
    selector: 'my-app',
    template: '')
class AppComponent {}

What should I put in the src attribute to reference the logo correctly? Is there a specific scheme to use?

Body:
For Angular 5.0.0 you can reference it like this:

@Component(
    selector: 'my-app',
    template: '<img src="packages/angular_app/logo.svg">')
class AppComponent {}

Replace angular_app with the name defined in your pubspec.yaml.


问:
laravel route name parameter
Use a pageNation to request the value of the page to the controller. But why can't any parameters reach the controller?

```<code> Route::get('/index', 'Penpal\ViewController@index')->name('penpal.index');

 <form action="{!! route('penpal.index', ['menu' => 'p11-c3']) !!}" method="get">
            <select id="inputState" class="form-control" style="height:35px; width:80%" name="pagination" onchange="this.form.submit()">
                    <option value="3">@lang('penpal/component/indexMenu.twelve')</option>
                    <option value="4">@lang('penpal/component/indexMenu.twenty_four')</option>
                    <option value="5">@lang('penpal/component/indexMenu.thirty_six')</option>
                </select>
        </form>

 public function index (Request $request){
    return $request;\
 }
</code>```

A parameter named "menu" cannot be received from the controller.

答:
Your <form> is using method='get', instead of method='POST' (which is used to post data to the request via a form.

You will also need to use @csrf in your blade template or you will not be able to post data:

```<code><form action="{!! route('penpal.index', ['menu' => 'p11-c3']) !!}" method="POST">
   @csrf
   <select id="inputState" class="form-control" style="height:35px; width:80%" name="pagination" onchange="this.form.submit()">
      <option value="3">@lang('penpal/component/indexMenu.twelve')</option>
      <option value="4">@lang('penpal/component/indexMenu.twenty_four')</option>
      <option value="5">@lang('penpal/component/indexMenu.thirty_six')</option>
   </select>
</form>
</code>```

Finally, make sure that your route is a ::post() route.

Title: laravel route name parameter

Body:
Use a pageNation to request the value of the page to the controller. But why can't any parameters reach the controller?

 Route::get('/index', 'Penpal\ViewController@index')->name('penpal.index');

 <form action="{!! route('penpal.index', ['menu' => 'p11-c3']) !!}" method="get">
            <select id="inputState" class="form-control" style="height:35px; width:80%" name="pagination" onchange="this.form.submit()">
                    <option value="3">@lang('penpal/component/indexMenu.twelve')</option>
                    <option value="4">@lang('penpal/component/indexMenu.twenty_four')</option>
                    <option value="5">@lang('penpal/component/indexMenu.thirty_six')</option>
                </select>
        </form>

 public function index (Request $request){
    return $request;\
 }

A parameter named "menu" cannot be received from the controller.

Body:
Your <form> is using method='get', instead of method='POST' (which is used to post data to the request via a form.

You will also need to use @csrf in your blade template or you will not be able to post data:

<form action="{!! route('penpal.index', ['menu' => 'p11-c3']) !!}" method="POST">
   @csrf
   <select id="inputState" class="form-control" style="height:35px; width:80%" name="pagination" onchange="this.form.submit()">
      <option value="3">@lang('penpal/component/indexMenu.twelve')</option>
      <option value="4">@lang('penpal/component/indexMenu.twenty_four')</option>
      <option value="5">@lang('penpal/component/indexMenu.thirty_six')</option>
   </select>
</form>

Finally, make sure that your route is a ::post() route.