问:
Get type definition for props.dispatch() for using TypeScript with React-Redux
I have this functional/stateless component:

```<code>import React from 'react';
import {useFormik} from 'formik';
import {connect} from "react-redux";

function mapStateToProps(){
  return {
     foo: "bar"
  }
}

interface OwnProps {
  propFromParent: number
}

type StateProps = ReturnType<typeof mapStateToProps>
type Props = StateProps & OwnProps

const SignupForm = (props: Props) => {

  const formik = useFormik({
    initialValues: {
      email: '',
      name: '',
      password: ''
    },
    onSubmit(values) {
      props.dispatch()   // props.dispatch is not defined!
    }
  });

  return (
    <form onSubmit={formik.handleSubmit}>
      <label htmlFor="name">Full Name</label>
      <input
        id="name"
        name="name"
        type="name"
        onChange={formik.handleChange}
        value={formik.values.name}
      />
      <button type="submit">Submit</button>
    </form>
  );
};

export default connect<StateProps, null, Props>(mapStateToProps)(SignupForm);
</code>```

so I am getting this compile error:

So how can I include the type definition so that props.dispatch is defined?
Just looking for help with the proper TS definitions.

答:
You need to add a new function and pass it to connect() as second argument</p>

```<code>...
function mapDispatchToProps(dispatch): IDispatchProps {
 return {
  dispatch
 };
}

connect(mapStateToProps, mapDispatchToProps)
</code>```

Body:
I have this functional/stateless component:

import React from 'react';
import {useFormik} from 'formik';
import {connect} from "react-redux";

function mapStateToProps(){
  return {
     foo: "bar"
  }
}

interface OwnProps {
  propFromParent: number
}

type StateProps = ReturnType<typeof mapStateToProps>
type Props = StateProps & OwnProps

const SignupForm = (props: Props) => {

  const formik = useFormik({
    initialValues: {
      email: '',
      name: '',
      password: ''
    },
    onSubmit(values) {
      props.dispatch()   // props.dispatch is not defined!
    }
  });

  return (
    <form onSubmit={formik.handleSubmit}>
      Full Name
      <input
        id="name"
        name="name"
        type="name"
        onChange={formik.handleChange}
        value={formik.values.name}
      />
      <button type="submit">Submit</button>
    </form>
  );
};

export default connect<StateProps, null, Props>(mapStateToProps)(SignupForm);

so I am getting this compile error:

So how can I include the type definition so that props.dispatch is defined?
Just looking for help with the proper TS definitions.

Body:
You need to add a new function and pass it to connect() as second argument

...
function mapDispatchToProps(dispatch): IDispatchProps {
 return {
  dispatch
 };
}

connect(mapStateToProps, mapDispatchToProps)


来源: stackexchange

问:
Error when saving a document using a web application in c#
I have a web application in c#,that creates and save a document in local machine folder.
The works fine when running from my machine - however as soon as I deploy the app to my web server I get this error.

This is not a valid file name. Try one or more of the following: *
  Check the path to make sure it was typed correctly. * Select a file
  from the list of files and folders.

Below is my source code

```<code>            //Create an instance for word app
            Microsoft.Office.Interop.Word.Application winword = new Microsoft.Office.Interop.Word.Application();

            //Set animation status for word application
            winword.ShowAnimation = false;

            //Set status for word application is to be visible or not.
            winword.Visible = false;

            //Create a missing variable for missing value
            object missing = System.Reflection.Missing.Value;

            //Create a new document
            Microsoft.Office.Interop.Word.Document document = winword.Documents.Add(ref missing, ref missing, ref missing, ref missing);

            //Add header into the document
            //foreach (Microsoft.Office.Interop.Word.Section section in document.Sections)
            //{
            //    //Get the header range and add the header details.
            //    Microsoft.Office.Interop.Word.Range headerRange = section.Headers[Microsoft.Office.Interop.Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;
            //    headerRange.Fields.Add(headerRange, Microsoft.Office.Interop.Word.WdFieldType.wdFieldPage);
            //    headerRange.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
            //    headerRange.Font.ColorIndex = Microsoft.Office.Interop.Word.WdColorIndex.wdBlue;
            //    headerRange.Font.Size = 10;
            //    headerRange.Text = "Header text goes here";
            //}

            //Add the footers into the document
            //foreach (Microsoft.Office.Interop.Word.Section wordSection in document.Sections)
            //{
            //    //Get the footer range and add the footer details.
            //    Microsoft.Office.Interop.Word.Range footerRange = wordSection.Footers[Microsoft.Office.Interop.Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;
            //    footerRange.Font.ColorIndex = Microsoft.Office.Interop.Word.WdColorIndex.wdDarkRed;
            //    footerRange.Font.Size = 10;
            //    footerRange.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
            //    footerRange.Text = "Footer text goes here";
            //}

            //adding text to document
            document.Content.SetRange(0, 0);
            document.Content.Text = "This is test document " + Environment.NewLine;

            //Add paragraph with Heading 1 style
            Microsoft.Office.Interop.Word.Paragraph para1 = document.Content.Paragraphs.Add(ref missing);
            object styleHeading1 = "Heading 1";
            para1.Range.set_Style(ref styleHeading1);
            para1.Range.Text = "Para 1 text";
            para1.Range.InsertParagraphAfter();

            //Add paragraph with Heading 2 style
            Microsoft.Office.Interop.Word.Paragraph para2 = document.Content.Paragraphs.Add(ref missing);
            object styleHeading2 = "Heading 2";
            para2.Range.set_Style(ref styleHeading2);
            para2.Range.Text = "Para 2 text";
            para2.Range.InsertParagraphAfter();

            //Create a 5X5 table and insert some dummy record
            Microsoft.Office.Interop.Word.Table firstTable = document.Tables.Add(para1.Range, 5, 5, ref missing, ref missing);

            firstTable.Borders.Enable = 1;
            foreach (Row row in firstTable.Rows)
            {
                foreach (Cell cell in row.Cells)
                {
                    //Header row
                    if (cell.RowIndex == 1)
                    {
                        cell.Range.Text = "Column " + cell.ColumnIndex.ToString();
                        cell.Range.Font.Bold = 1;
                        //other format properties goes here
                        cell.Range.Font.Name = "verdana";
                        cell.Range.Font.Size = 10;
                        //cell.Range.Font.ColorIndex = WdColorIndex.wdGray25;
                        cell.Shading.BackgroundPatternColor = WdColor.wdColorGray25;
                        //Center alignment for the Header cells
                        cell.VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter;
                        cell.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;

                    }
                    //Data row
                    else
                    {
                        cell.Range.Text = (cell.RowIndex - 2 + cell.ColumnIndex).ToString();
                    }
                }
            }

            //Save the document
            object filename = @"c:\Data\TestSignature.doc";

            document.SaveAs(ref filename);
            document.Close(ref missing, ref missing, ref missing);
            document = null;
            winword.Quit(ref missing, ref missing, ref missing);
            winword = null;
            Label7.Text = "Document created successfully !";
</code>```

答:
Apologies for not being clear enough on my question.
The document that is being created by the must,must be saved on the user/client computer.
The assumption is that all users will have C drive and a folder called Data.the folder will have necessary permissions to save the file.</p>

ContentLicense: CC BY-SA 4.0

Body:
I have a web application in c#,that creates and save a document in local machine folder.
The works fine when running from my machine - however as soon as I deploy the app to my web server I get this error.

This is not a valid file name. Try one or more of the following: *
  Check the path to make sure it was typed correctly. * Select a file
  from the list of files and folders.

Below is my source code

            //Create an instance for word app
            Microsoft.Office.Interop.Word.Application winword = new Microsoft.Office.Interop.Word.Application();

            //Set animation status for word application
            winword.ShowAnimation = false;

            //Set status for word application is to be visible or not.
            winword.Visible = false;

            //Create a missing variable for missing value
            object missing = System.Reflection.Missing.Value;

            //Create a new document
            Microsoft.Office.Interop.Word.Document document = winword.Documents.Add(ref missing, ref missing, ref missing, ref missing);

            //Add header into the document
            //foreach (Microsoft.Office.Interop.Word.Section section in document.Sections)
            //{
            //    //Get the header range and add the header details.
            //    Microsoft.Office.Interop.Word.Range headerRange = section.Headers[Microsoft.Office.Interop.Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;
            //    headerRange.Fields.Add(headerRange, Microsoft.Office.Interop.Word.WdFieldType.wdFieldPage);
            //    headerRange.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
            //    headerRange.Font.ColorIndex = Microsoft.Office.Interop.Word.WdColorIndex.wdBlue;
            //    headerRange.Font.Size = 10;
            //    headerRange.Text = "Header text goes here";
            //}

            //Add the footers into the document
            //foreach (Microsoft.Office.Interop.Word.Section wordSection in document.Sections)
            //{
            //    //Get the footer range and add the footer details.
            //    Microsoft.Office.Interop.Word.Range footerRange = wordSection.Footers[Microsoft.Office.Interop.Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;
            //    footerRange.Font.ColorIndex = Microsoft.Office.Interop.Word.WdColorIndex.wdDarkRed;
            //    footerRange.Font.Size = 10;
            //    footerRange.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
            //    footerRange.Text = "Footer text goes here";
            //}

            //adding text to document
            document.Content.SetRange(0, 0);
            document.Content.Text = "This is test document " + Environment.NewLine;

            //Add paragraph with Heading 1 style
            Microsoft.Office.Interop.Word.Paragraph para1 = document.Content.Paragraphs.Add(ref missing);
            object styleHeading1 = "Heading 1";
            para1.Range.set_Style(ref styleHeading1);
            para1.Range.Text = "Para 1 text";
            para1.Range.InsertParagraphAfter();

            //Add paragraph with Heading 2 style
            Microsoft.Office.Interop.Word.Paragraph para2 = document.Content.Paragraphs.Add(ref missing);
            object styleHeading2 = "Heading 2";
            para2.Range.set_Style(ref styleHeading2);
            para2.Range.Text = "Para 2 text";
            para2.Range.InsertParagraphAfter();

            //Create a 5X5 table and insert some dummy record
            Microsoft.Office.Interop.Word.Table firstTable = document.Tables.Add(para1.Range, 5, 5, ref missing, ref missing);

            firstTable.Borders.Enable = 1;
            foreach (Row row in firstTable.Rows)
            {
                foreach (Cell cell in row.Cells)
                {
                    //Header row
                    if (cell.RowIndex == 1)
                    {
                        cell.Range.Text = "Column " + cell.ColumnIndex.ToString();
                        cell.Range.Font.Bold = 1;
                        //other format properties goes here
                        cell.Range.Font.Name = "verdana";
                        cell.Range.Font.Size = 10;
                        //cell.Range.Font.ColorIndex = WdColorIndex.wdGray25;
                        cell.Shading.BackgroundPatternColor = WdColor.wdColorGray25;
                        //Center alignment for the Header cells
                        cell.VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter;
                        cell.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;

                    }
                    //Data row
                    else
                    {
                        cell.Range.Text = (cell.RowIndex - 2 + cell.ColumnIndex).ToString();
                    }
                }
            }

            //Save the document
            object filename = @"c:\Data\TestSignature.doc";

            document.SaveAs(ref filename);
            document.Close(ref missing, ref missing, ref missing);
            document = null;
            winword.Quit(ref missing, ref missing, ref missing);
            winword = null;
            Label7.Text = "Document created successfully !";


问:
two tabs vertical & horizontal - Not working Mat tabs
I was able to create vertical material tab with my below code but I want is inside vertical tab i need an horizontal tab

When I tried using below code both showing in vertical tabs Here is my code and here is my Stackblitz url.

```<code><div class="container">
      <div id="content">
        <div id="main-content">
          <mat-tab-group>
            <mat-tab label="Tab One">
              Tab One Content
            </mat-tab>
            <mat-tab label="Tab Two">
            <mat-tab-group>
            <mat-tab label="First"> Content 1 </mat-tab>
            <mat-tab label="Second"> Content 2 </mat-tab>
            <mat-tab label="Third"> Content 3 </mat-tab>
          </mat-tab-group>
            </mat-tab>
          </mat-tab-group>
        </div>
      </div>
    </div>
</code>```

Here is the stackblitz  link

答:
You may achieve that by nesting mat-tab-group's, specifying classes for vertical and horizontal depending on the orientation and adjusting css accordingly:

HTML

```<code><mat-tab-group class="vertical">
  <mat-tab label="Tab One">
    <mat-tab-group class="horizontal">
      <mat-tab label="Sub Tab One">
        Sub Tab One Content
      </mat-tab>
      <mat-tab label="Sub Tab Two">
        Sub Tab Two Content
      </mat-tab>
    </mat-tab-group>
  </mat-tab>
  <mat-tab label="Tab Two">
    Tab Two Content
  </mat-tab>
</mat-tab-group>
</code>```

CSS

```<code>  :host {
    /deep/ {
        .mat-tab-group.vertical {
            flex-direction: row;
        }
        .mat-tab-group.horizontal {
            flex-direction: column;
        }
        .vertical .mat-tab-labels {
            flex-direction: column;
        }
        .horizontal .mat-tab-labels {
            flex-direction: row;
        }
    }
}
</code>```

Working stackblitz here

Body:
I was able to create vertical material tab with my below code but I want is inside vertical tab i need an horizontal tab

When I tried using below code both showing in vertical tabs Here is my code and here is my Stackblitz url.

          <mat-tab-group>
            <mat-tab label="Tab One">
              Tab One Content
            </mat-tab>
            <mat-tab label="Tab Two">
            <mat-tab-group>
            <mat-tab label="First"> Content 1 </mat-tab>
            <mat-tab label="Second"> Content 2 </mat-tab>
            <mat-tab label="Third"> Content 3 </mat-tab>
          </mat-tab-group>
            </mat-tab>
          </mat-tab-group>

Here is the stackblitz  link

Body:
You may achieve that by nesting mat-tab-group's, specifying classes for vertical and horizontal depending on the orientation and adjusting css accordingly:

HTML

<mat-tab-group class="vertical">
  <mat-tab label="Tab One">
    <mat-tab-group class="horizontal">
      <mat-tab label="Sub Tab One">
        Sub Tab One Content
      </mat-tab>
      <mat-tab label="Sub Tab Two">
        Sub Tab Two Content
      </mat-tab>
    </mat-tab-group>
  </mat-tab>
  <mat-tab label="Tab Two">
    Tab Two Content
  </mat-tab>
</mat-tab-group>

CSS

  :host {
    /deep/ {
        .mat-tab-group.vertical {
            flex-direction: row;
        }
        .mat-tab-group.horizontal {
            flex-direction: column;
        }
        .vertical .mat-tab-labels {
            flex-direction: column;
        }
        .horizontal .mat-tab-labels {
            flex-direction: row;
        }
    }
}

Working stackblitz here


问:
select table from other schema
I have a table from schema "test":

```<code>class AttributeConversion(Base):
    __tablename__ = 'test.attribute_conversion'
</code>```

How to select records from this table?

SQLAlchemy generates SQL:

```<code>select * from "test.attribute_conversion"
</code>```

But it doesn't work. The correct query must be:

```<code>select * from test.attribute_conversion  (without quotes)
</code>```

答:
You can explicity specify a schema name for a table:

```<code>class AttributeConversion(Base)
    __tablename__ = 'attribute_conversion'
    __table_args__ = {'schema' : 'test'}
</code>```

See documentation on specifying the schema name.

Title: select table from other schema

Body:
I have a table from schema "test":

class AttributeConversion(Base):
    __tablename__ = 'test.attribute_conversion'

How to select records from this table?

SQLAlchemy generates SQL:

select * from "test.attribute_conversion"

But it doesn't work. The correct query must be:

select * from test.attribute_conversion  (without quotes)

Body:
You can explicity specify a schema name for a table:

class AttributeConversion(Base)
    __tablename__ = 'attribute_conversion'
    __table_args__ = {'schema' : 'test'}

See documentation on specifying the schema name.


问:
r dplyr ends_with multiple string matches
Can I use dplyr::select(ends_with) to select column names that fit any of multiple conditions. Considering my column names, I want to use ends with instead of contains or matches, because the strings I want to select are relevant at the end of the column name, but may also appear in the middle in others. For instance,

```<code>df <- data.frame(a10 = 1:4,
             a11 = 5:8,
             a20 = 1:4,
             a12 = 5:8)
</code>```

I want to select columns that end with 1 or 2, to have only columns a11 and a12. Is select(ends_with) the best way to do this?

Thanks!

答:
From version 1.0.0, you can combine multiple selections using Boolean logic such as ! (negate), & (and) and | (or).

### Install development version on GitHub first until CRAN version is available
# install.packages("devtools")
# devtools::install_github("tidyverse/dplyr")
library(dplyr, warn.conflicts = FALSE)

df <- data.frame(a10 = 1:4,
                 a11 = 5:8,
                 a20 = 1:4,
                 a12 = 5:8)

df %>%
  select(ends_with("1") | ends_with("2"))
#>   a11 a12
#> 1   5   5
#> 2   6   6
#> 3   7   7
#> 4   8   8
```

<p>or use <code>num_range()</code> to select the desired columns</p>

<pre class="lang-r prettyprint-override"><code>df %>%
  select(num_range(prefix = "a", range = 11:12))
#>   a11 a12
#> 1   5   5
#> 2   6   6
#> 3   7   7
#> 4   8   8
</code>```

Created on 2020-02-17 by the reprex package (v0.3.0)

ContentLicense: CC BY-SA 3.0

Body:
Can I use dplyr::select(ends_with) to select column names that fit any of multiple conditions. Considering my column names, I want to use ends with instead of contains or matches, because the strings I want to select are relevant at the end of the column name, but may also appear in the middle in others. For instance,

df <- data.frame(a10 = 1:4,
             a11 = 5:8,
             a20 = 1:4,
             a12 = 5:8)

I want to select columns that end with 1 or 2, to have only columns a11 and a12. Is select(ends_with) the best way to do this?

Thanks!

Body:
From version 1.0.0, you can combine multiple selections using Boolean logic such as ! (negate), & (and) and | (or).

### Install development version on GitHub first until CRAN version is available
# install.packages("devtools")
# devtools::install_github("tidyverse/dplyr")
library(dplyr, warn.conflicts = FALSE)

df <- data.frame(a10 = 1:4,
                 a11 = 5:8,
                 a20 = 1:4,
                 a12 = 5:8)

df %>%
  select(ends_with("1") | ends_with("2"))
#>   a11 a12
#> 1   5   5
#> 2   6   6
#> 3   7   7
#> 4   8   8

or use num_range() to select the desired columns

df %>%
  select(num_range(prefix = "a", range = 11:12))
#>   a11 a12
#> 1   5   5
#> 2   6   6
#> 3   7   7
#> 4   8   8

Created on 2020-02-17 by the reprex package (v0.3.0)


问:
findByIdAndUpdate not updating
When I test my update route in postman the server gives me a status code of 200 but nothing updated in my database, why is it not updating?

```<code>exports.updateTodos = async (req, res, next)=>{
    try{
        const update = await Todos.findByIdAndUpdate({_id: req.params.id});
        res.send({
            success: true,
            todosData: update,
            Msg: "successfully updated!"
        }).status(200);
    }catch(error){
        res.send({
            success: false,
            Msg: "There was A problem updating to todos",
            err: error
        });
    }
}

//This is my schema data
const schema = mongoose.Schema({
    task: {
        type: String,
        maxlength: 300,
        require: true
    },
    taskname: {
        type: String,
        require: true,
        maxlength: 14
    },
    createAt: {
        type: Date,
        default: Date.now
    }
});
</code>```

this is how I call updateTodos in my router

```<code>router.put('/:id', updateTodos);
</code>```

答:
You're basically not setting anything to be updated. See how it is done below

exports.updateTodos = async (req, res, next)=>{
    try{
        const update = await Todos.findByIdAndUpdate({_id: req.params.id}, {$set: req.body});
        res.send({
            success: true,
            todosData: update,
            Msg: "successfully updated!"
        }).status(200);
    }catch(error){
        res.send({
            success: false,
            Msg: "There was A problem updating to todos",
            err: error
        });
    }
}

```
<p>You can also explicitly choose what to update like so:</p>
<pre class="lang-js prettyprint-override"><code>
exports.updateTodos = async (req, res, next)=>{
    try{
        const update = await Todos.findByIdAndUpdate({_id: req.params.id},
                            {$set: {taskname: req.body.taskname}});
        res.send({
            success: true,
            todosData: update,
            Msg: "successfully updated!"
        }).status(200);
    }catch(error){
        res.send({
            success: false,
            Msg: "There was A problem updating to todos",
            err: error
        });
    }
}

</code>```

Title: findByIdAndUpdate not updating

Body:
When I test my update route in postman the server gives me a status code of 200 but nothing updated in my database, why is it not updating?

exports.updateTodos = async (req, res, next)=>{
    try{
        const update = await Todos.findByIdAndUpdate({_id: req.params.id});
        res.send({
            success: true,
            todosData: update,
            Msg: "successfully updated!"
        }).status(200);
    }catch(error){
        res.send({
            success: false,
            Msg: "There was A problem updating to todos",
            err: error
        });
    }
}

//This is my schema data
const schema = mongoose.Schema({
    task: {
        type: String,
        maxlength: 300,
        require: true
    },
    taskname: {
        type: String,
        require: true,
        maxlength: 14
    },
    createAt: {
        type: Date,
        default: Date.now
    }
});

this is how I call updateTodos in my router

router.put('/:id', updateTodos);

Body:
You're basically not setting anything to be updated. See how it is done below

exports.updateTodos = async (req, res, next)=>{
    try{
        const update = await Todos.findByIdAndUpdate({_id: req.params.id}, {$set: req.body});
        res.send({
            success: true,
            todosData: update,
            Msg: "successfully updated!"
        }).status(200);
    }catch(error){
        res.send({
            success: false,
            Msg: "There was A problem updating to todos",
            err: error
        });
    }
}

You can also explicitly choose what to update like so:

exports.updateTodos = async (req, res, next)=>{
    try{
        const update = await Todos.findByIdAndUpdate({_id: req.params.id},
                            {$set: {taskname: req.body.taskname}});
        res.send({
            success: true,
            todosData: update,
            Msg: "successfully updated!"
        }).status(200);
    }catch(error){
        res.send({
            success: false,
            Msg: "There was A problem updating to todos",
            err: error
        });
    }
}


问:
Pandas: SettingWithCopyWarning when calling apply on a slice
I have a Pandas DataFrame with a few columns, but I want to manipulate all of values in a single column (conditionally), like this:

df[my_column] = df[my_column].apply(lambda x: -float(x))

This works, but Pandas gives me a SettingWithCopyWarning.

SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame.
  Try using .loc[row_indexer,col_indexer] = value instead

Is there a problem with the way I'm going about manipulating this column?

答:
The problem occurs earlier in your code.  df is probably a slice of another dataframe and pandas is warning you not to make a modification of df because it is a copy of that other dataframe.

The easiest solution when you want to subset a dataframe and manipulate further is to use the .copy() method.

df = df_original.copy()

now you can apply code like:

df[my_column] = xxx

without a SettingWithCopyWarning.


问:
Converting to C++ from C#
I have done pretty much all my programming using C# and very much a newbie to C++. However now I have to convert to C++ and is finding it a bit difficult. For example, I wrote a pretty simple program using C# to acquire a RegistryKey, then using a recursive function I iterate through my registry key to find a specific key and then get the values I want. No problem, I can write that program in 10 minutes using C#. Here is the code.

My primary function. It gets Bluetooth Registry Key and then call the recursive function.

```<code>private static void CheckOpenComPorts()
{
            RegistryKey blueToothPorts = Registry.LocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\Enum\Bluetooth");

            List<string> foundPorts = new List<string>();
            AddFoundPortsToList(blueToothPorts, ref foundPorts);

            //Rest of the program; not relevant here.
}
</code>```

Recursive Function. Iterates the passed Key to find out necessary values.

```<code>private static void AddFoundPortsToList(RegistryKey regKey, ref List<string> ports)
        {
            try
            {
                string[] subKeys = regKey.GetSubKeyNames();

                if (subKeys != null)
                {
                    foreach (string subKey in subKeys)
                    {
                        AddFoundPortsToList(regKey.OpenSubKey(subKey), ref ports);
                    }
                }

                if (regKey.Name.EndsWith("Device Parameters"))
                {
                    string str = System.Convert.ToString(regKey.GetValue("PortName"));
                    if (String.IsNullOrEmpty(str) == false)
                    {
                        ports.Add(str);
                    }
                }
            }
            catch (System.Security.SecurityException ex)
            {
                ;
            }
        }
</code>```

The above code works fine, but when I tried to convert it to C++, I'm pretty lost.
Note : I'm using a Win32 Console C++ Program.

I figured out that I can do something like the following to get the Bluetooth Registry Key.

```<code>RegOpenKeyEx(HKEY_LOCAL_MACHINE, L"SYSTEM\\CurrentControlSet\\Enum\\Bluetooth", 0, KEY_READ, &hKey)
</code>```

But after that, I'm pretty lost about the recursive function. Specially, how do I get the available subkeys of the passed registry key when I do NOT know the subkey names?. Or in short, what is the equivalent behavior of RegistryKey.GetSubKeyNames() in C++?

As I am only beginning this thing a code sample with some explanations would be great.

答:
Enumerate the subkeys of a key - RegEnumKeyEx

Enumerate the values of a key - RegEnumValue

You get all subkeys by calling RegEnumKeyEx in a loop until it returns ERROR_NO_MORE_ITEMS.

In the exact same way, you get all values by calling RegEnumValue in a loop until it returns ERROR_NO_MORE_ITEMS.

Title: Converting to C++ from C#

Body:
I have done pretty much all my programming using C# and very much a newbie to C++. However now I have to convert to C++ and is finding it a bit difficult. For example, I wrote a pretty simple program using C# to acquire a RegistryKey, then using a recursive function I iterate through my registry key to find a specific key and then get the values I want. No problem, I can write that program in 10 minutes using C#. Here is the code.

My primary function. It gets Bluetooth Registry Key and then call the recursive function.

private static void CheckOpenComPorts()
{
            RegistryKey blueToothPorts = Registry.LocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\Enum\Bluetooth");

            List<string> foundPorts = new List<string>();
            AddFoundPortsToList(blueToothPorts, ref foundPorts);

            //Rest of the program; not relevant here.
}

Recursive Function. Iterates the passed Key to find out necessary values.

private static void AddFoundPortsToList(RegistryKey regKey, ref List<string> ports)
        {
            try
            {
                string[] subKeys = regKey.GetSubKeyNames();

                if (subKeys != null)
                {
                    foreach (string subKey in subKeys)
                    {
                        AddFoundPortsToList(regKey.OpenSubKey(subKey), ref ports);
                    }
                }

                if (regKey.Name.EndsWith("Device Parameters"))
                {
                    string str = System.Convert.ToString(regKey.GetValue("PortName"));
                    if (String.IsNullOrEmpty(str) == false)
                    {
                        ports.Add(str);
                    }
                }
            }
            catch (System.Security.SecurityException ex)
            {
                ;
            }
        }

The above code works fine, but when I tried to convert it to C++, I'm pretty lost.
Note : I'm using a Win32 Console C++ Program.

I figured out that I can do something like the following to get the Bluetooth Registry Key.

RegOpenKeyEx(HKEY_LOCAL_MACHINE, L"SYSTEM\\CurrentControlSet\\Enum\\Bluetooth", 0, KEY_READ, &hKey)

But after that, I'm pretty lost about the recursive function. Specially, how do I get the available subkeys of the passed registry key when I do NOT know the subkey names?. Or in short, what is the equivalent behavior of RegistryKey.GetSubKeyNames() in C++?

As I am only beginning this thing a code sample with some explanations would be great.


问:
combining two numpy arrays of different dtype to a structured array
I have a numpy float array and an int array of the same length. I would like to concatenate them such that the output has the composite dtype (float, int). column_stacking them together just yields a float64 array:

import numpy

a = numpy.random.rand(5)
b = numpy.random.randint(0, 100, 5)

ab = numpy.column_stack([a, b])
print(ab.dtype)
```

```float64
```

Any hints?

Body:
I have a numpy float array and an int array of the same length. I would like to concatenate them such that the output has the composite dtype (float, int). column_stacking them together just yields a float64 array:

import numpy

a = numpy.random.rand(5)
b = numpy.random.randint(0, 100, 5)

ab = numpy.column_stack([a, b])
print(ab.dtype)

float64

Any hints?

Body:
Create a 'blank' array:

In [391]: dt = np.dtype('f,i')
In [392]: arr = np.zeros(5, dtype=dt)
In [393]: arr
Out[393]:
array([(0., 0), (0., 0), (0., 0), (0., 0), (0., 0)],
      dtype=[('f0', '<f4'), ('f1', '<i4')])

fill it:

In [394]: arr['f0']=np.random.rand(5)
In [396]: arr['f1']=np.random.randint(0,100,5)
In [397]: arr
Out[397]:
array([(0.40140057, 75), (0.93731374, 99), (0.6226782 , 48),
       (0.01068745, 68), (0.19197434, 53)],
      dtype=[('f0', '<f4'), ('f1', '<i4')])

There are recfunctions that can be used as well, but it's good to know (and understand) this basic approach.


问:
MySQL: How to copy row from one table to another with skipping empty rows in source table?
Can anyone help me turn this PHP/MySQLesque pseudo-code into a working MySQL-query? Tables A and B have identical columns / column order.

```<code>UPDATE B SET
B.col_1 = A.col_1 IF(A.col_1 != '' AND A.col_1 != 0 AND A.col_1 != NULL),
B.col_2 = A.col_2 IF(A.col_2 != '' AND A.col_2 != 0 AND A.col_2 != NULL),
…
B.col_n = A.col_n IF(A.col_n != '' AND A.col_n != 0 AND A.col_n != NULL)
WHERE A.$uniqueField = B.$uniqueField
</code>```

Any of the n columns (email, firstName, lastName, phone, …) can be $uniqueField (handled by PHP), so I can't use insert-on-duplicate-key.

I found many examples to do it the other way round (i.e. copy rows and skip empty fields in target table), including a promising way via COALESCE, but I could not get this to work.

Any help would be highly appreciated ... thanks in advance!

答:
```<code>UPDATE  B,A

SET B.Col1 = SELECT COALESCE(A.Col1,B.Col1),
    B.Col2  =SELECT COALESCE(A.Col2,B.Col2),
    ...
    B.Coln = SELECT COALESCE(A.Coln.B.Coln)
WHERE A.uniquefield = B.uniquefield  AND Condition
</code>```

Body:
Can anyone help me turn this PHP/MySQLesque pseudo-code into a working MySQL-query? Tables A and B have identical columns / column order.

UPDATE B SET
B.col_1 = A.col_1 IF(A.col_1 != '' AND A.col_1 != 0 AND A.col_1 != NULL),
B.col_2 = A.col_2 IF(A.col_2 != '' AND A.col_2 != 0 AND A.col_2 != NULL),
…
B.col_n = A.col_n IF(A.col_n != '' AND A.col_n != 0 AND A.col_n != NULL)
WHERE A.$uniqueField = B.$uniqueField

Any of the n columns (email, firstName, lastName, phone, …) can be $uniqueField (handled by PHP), so I can't use insert-on-duplicate-key.

I found many examples to do it the other way round (i.e. copy rows and skip empty fields in target table), including a promising way via COALESCE, but I could not get this to work.

Any help would be highly appreciated ... thanks in advance!


问:
"For dataset in total": Not applying to both train and test datasets
My for "dataset in total" is only applying to my test set, and is not altering the datapoints on my train set. Can someone help explain this?</p>

```<code>total=[train,test]
for dataset in total:
    dataset.loc[dataset['Fare'] <= 18, 'Fare'] = 9
    dataset.loc[(dataset['Fare'] > 18) & (dataset['Fare'] <= 37.0042), 'Fare'] = 11
    dataset.loc[(dataset['Fare'] > 37.0042) & (dataset['Fare'] <= 63.3583), 'Fare'] = 22
    dataset.loc[(dataset['Fare'] > 63.3583) & (dataset['Fare'] <= 93.5), 'Fare'] = 33
    dataset.loc[(dataset['Fare'] > 93.5) & (dataset['Fare'] <= 120), 'Fare'] = 44
    dataset.loc[(dataset['Fare'] > 120) & (dataset['Fare'] <= 164.8667), 'Fare'] = 55
    dataset.loc[(dataset['Fare'] > 164.8667) & (dataset['Fare'] <= 263), 'Fare'] = 66
    dataset.loc[dataset['Fare'] > 263, 'Fare'] =77
total=[train,test]
</code>```

答:
Pandas dataframes are mutable.
Read the following from here:

Mutability and copying of data All pandas data structures are
  value-mutable (the values they contain can be altered) but not always
  size-mutable. The length of a Series cannot be changed, but, for
  example, columns can be inserted into a DataFrame. However, the vast
  majority of methods produce new objects and leave the input data
  untouched. In general we like to favor immutability where sensible.

You could change your code as follows:

```<code>total=[train,test]
for i in range(2):
    total[i].loc[dataset['Fare'] <= 18, 'Fare'] = 9
    total[i].loc[(dataset['Fare'] > 18) & (dataset['Fare'] <= 37.0042), 'Fare'] = 11
    total[i].loc[(dataset['Fare'] > 37.0042) & (dataset['Fare'] <= 63.3583), 'Fare'] = 22
    total[i].loc[(dataset['Fare'] > 63.3583) & (dataset['Fare'] <= 93.5), 'Fare'] = 33
    total[i].loc[(dataset['Fare'] > 93.5) & (dataset['Fare'] <= 120), 'Fare'] = 44
    total[i].loc[(dataset['Fare'] > 120) & (dataset['Fare'] <= 164.8667), 'Fare'] = 55
    total[i].loc[(dataset['Fare'] > 164.8667) & (dataset['Fare'] <= 263), 'Fare'] = 66
    total[i].loc[dataset['Fare'] > 263, 'Fare'] =77
# no need for this statement! total=[train,test]
</code>```

Body:
My for "dataset in total" is only applying to my test set, and is not altering the datapoints on my train set. Can someone help explain this?

total=[train,test]
for dataset in total:
    dataset.loc[dataset['Fare'] <= 18, 'Fare'] = 9
    dataset.loc[(dataset['Fare'] > 18) & (dataset['Fare'] <= 37.0042), 'Fare'] = 11
    dataset.loc[(dataset['Fare'] > 37.0042) & (dataset['Fare'] <= 63.3583), 'Fare'] = 22
    dataset.loc[(dataset['Fare'] > 63.3583) & (dataset['Fare'] <= 93.5), 'Fare'] = 33
    dataset.loc[(dataset['Fare'] > 93.5) & (dataset['Fare'] <= 120), 'Fare'] = 44
    dataset.loc[(dataset['Fare'] > 120) & (dataset['Fare'] <= 164.8667), 'Fare'] = 55
    dataset.loc[(dataset['Fare'] > 164.8667) & (dataset['Fare'] <= 263), 'Fare'] = 66
    dataset.loc[dataset['Fare'] > 263, 'Fare'] =77
total=[train,test]

Body:
Pandas dataframes are mutable.
Read the following from here:

Mutability and copying of data All pandas data structures are
  value-mutable (the values they contain can be altered) but not always
  size-mutable. The length of a Series cannot be changed, but, for
  example, columns can be inserted into a DataFrame. However, the vast
  majority of methods produce new objects and leave the input data
  untouched. In general we like to favor immutability where sensible.

You could change your code as follows:

total=[train,test]
for i in range(2):
    total[i].loc[dataset['Fare'] <= 18, 'Fare'] = 9
    total[i].loc[(dataset['Fare'] > 18) & (dataset['Fare'] <= 37.0042), 'Fare'] = 11
    total[i].loc[(dataset['Fare'] > 37.0042) & (dataset['Fare'] <= 63.3583), 'Fare'] = 22
    total[i].loc[(dataset['Fare'] > 63.3583) & (dataset['Fare'] <= 93.5), 'Fare'] = 33
    total[i].loc[(dataset['Fare'] > 93.5) & (dataset['Fare'] <= 120), 'Fare'] = 44
    total[i].loc[(dataset['Fare'] > 120) & (dataset['Fare'] <= 164.8667), 'Fare'] = 55
    total[i].loc[(dataset['Fare'] > 164.8667) & (dataset['Fare'] <= 263), 'Fare'] = 66
    total[i].loc[dataset['Fare'] > 263, 'Fare'] =77
# no need for this statement! total=[train,test]


问:
How to configure IP/listeners in Apache Kafka so that external clients can connect to it
I need to use the ip of kafka for my other microservices. but when am deploying by this method theres no external IP moreover when am trying with localhost everything is working fine. so can anyone help me in understanding how to set up the ext IP of lb for the Kafka here to use it in</p>

答:
Kafka can be installed as LoadBalancer External Service Type on kubernetes using helm. Steps are here. Following is needed in helm's values.yaml to do it:

```<code> external:
  enabled: true
  type: LoadBalancer
   ...
  "advertised.listeners": |-
    EXTERNAL://${LOAD_BALANCER_IP}:31090
  "listener.security.protocol.map": |-
    PLAINTEXT:PLAINTEXT,EXTERNAL:PLAINTEXT
</code>```

Kafka installed as LoadBalancer External Service Type:

```<code>$ kubectl -n kafka get svc
NAME                       TYPE           CLUSTER-IP      EXTERNAL-IP      PORT(S)                      AGE
kafka                      ClusterIP      10.39.241.217   <none>           9092/TCP                     2m39s
kafka-0-external           LoadBalancer   10.39.242.45    35.200.238.174   31090:30108/TCP              2m39s
kafka-1-external           LoadBalancer   10.39.241.90    35.244.44.162    31090:30582/TCP              2m39s
kafka-2-external           LoadBalancer   10.39.243.160   35.200.149.80    31090:30539/TCP
</code>```

Now, to connect external clients to kafka, deploy kubernetes ingress in front of this kafka service using following links:

k8s ingress

k8s nginx ingress controller

kafka-manager helm chart

Body:
Kafka can be installed as LoadBalancer External Service Type on kubernetes using helm. Steps are here. Following is needed in helm's values.yaml to do it:

 external:
  enabled: true
  type: LoadBalancer
   ...
  "advertised.listeners": |-
    EXTERNAL://${LOAD_BALANCER_IP}:31090
  "listener.security.protocol.map": |-
    PLAINTEXT:PLAINTEXT,EXTERNAL:PLAINTEXT

Kafka installed as LoadBalancer External Service Type:

$ kubectl -n kafka get svc
NAME                       TYPE           CLUSTER-IP      EXTERNAL-IP      PORT(S)                      AGE
kafka                      ClusterIP      10.39.241.217   <none>           9092/TCP                     2m39s
kafka-0-external           LoadBalancer   10.39.242.45    35.200.238.174   31090:30108/TCP              2m39s
kafka-1-external           LoadBalancer   10.39.241.90    35.244.44.162    31090:30582/TCP              2m39s
kafka-2-external           LoadBalancer   10.39.243.160   35.200.149.80    31090:30539/TCP

Now, to connect external clients to kafka, deploy kubernetes ingress in front of this kafka service using following links:

k8s ingress

k8s nginx ingress controller

kafka-manager helm chart


问:
Adding element to list in pandas column
I can't figure out how to add element to pandas column for single row.

```<code>index = ['a','b','c','d']
df = pd.DataFrame(index = index)
df['Col'] = [[]] * len(index)

df.loc['d','Col'].append('AA')
</code>```

returns:

```<code>    Col
a   [AA]
b   [AA]
c   [AA]
d   [AA]
</code>```

I look for value 'AA' to be in the last row only.

答:
We should create the list of empty list by , avoid same object assignment. Also you can use <code>.loc</code> for assign the value in pandas </p>

```<code>df['Col'] = [[] for x in df.index]
df.loc['d','Col']='AA'
df
  Col
a  []
b  []
c  []
d  AA

df.loc['d','Col'].append('AA')
df
    Col
a    []
b    []
c    []
d  [AA]
</code>```

Title: Adding element to list in pandas column

Body:
I can't figure out how to add element to pandas column for single row.

index = ['a','b','c','d']
df = pd.DataFrame(index = index)
df['Col'] = [[]] * len(index)

df.loc['d','Col'].append('AA')

returns:

    Col
a   [AA]
b   [AA]
c   [AA]
d   [AA]

I look for value 'AA' to be in the last row only.

Body:
We should create the list of empty list by , avoid same object assignment. Also you can use .loc for assign the value in pandas

df['Col'] = [[] for x in df.index]
df.loc['d','Col']='AA'
df
  Col
a  []
b  []
c  []
d  AA

df.loc['d','Col'].append('AA')
df
    Col
a    []
b    []
c    []
d  [AA]


问:
How to solve: Detected locally installed Ionic CLI, but it’s too old -- using global CLI?
ionic -v results in this warning:

[WARN] Detected locally installed Ionic CLI, but it’s too old -- using global CLI.

How to uninstall local Ionic CLI?

答:
I had this issue on my app as well.
I no longer had '@ionic/cli' or 'ionic' as a dependency, but every time I re-ran "npm i" it would return as a locally installed item.  Looking through my package-lock.json I saw that it was also being installed as a dependency of @types/ionic which I then removed and solved this issue as well.  </p>


问:
Express validator returning value : undefined msg: 'Invalid value'
Routes

```<code>const express = require('express');
const { check } = require('express-validator');

const logControllers = require('../controllers/log-controllers');

const router = express.Router();

router.post('/',
    [
      check('title')
         .not()
         .isEmpty()
    ],
    logControllers.createLogEntry
);
</code>```

logControllers

```<code>const uuid = require('uuid/v4');
const { validationResult } = require('express-validator');
const HttpError = require('../models/http-error');

let DUMMY_LOGENTRIES = [
    {
        id: "j1",
        title: "king"}]

const createLogEntry = (req, res, next) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
        console.log(errors);
        throw new HttpError('Invalid inputs passed, please check your data.', 422);
    }
    const { title } = req.body;
    const createdLogEntry =
    //new logEntry(
    {
        id: uuid(), title
    };
    DUMMY_LOGENTRIES.push(createdLogEntry);
    res.status(201).json({ logEntry: createdLogEntry });
};
</code>```

When I remove validators, POST request works, but with the validator Nodemon returns:

```<code>  formatter: [Function: formatter],
  errors: [
    {
      value: undefined,
      msg: 'Invalid value',
      param: 'title',
      location: 'body'
    },
</code>```

Bonus question: Without the validator the returned response is only the uuid... not the title and I can't figure out why since I ask for the full createdLogEntry which should return title and uuid. Thoughts?

答: Didn't find what was missing in terms of the validator, but I did find that I was returning text instead of JSON in Postman.  Just rewrote everything and it worked.  Guessing it was syntax.</p>

Body:
Routes

const express = require('express');
const { check } = require('express-validator');

const logControllers = require('../controllers/log-controllers');

const router = express.Router();

router.post('/',
    [
      check('title')
         .not()
         .isEmpty()
    ],
    logControllers.createLogEntry
);

logControllers

const uuid = require('uuid/v4');
const { validationResult } = require('express-validator');
const HttpError = require('../models/http-error');

let DUMMY_LOGENTRIES = [
    {
        id: "j1",
        title: "king"}]

const createLogEntry = (req, res, next) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
        console.log(errors);
        throw new HttpError('Invalid inputs passed, please check your data.', 422);
    }
    const { title } = req.body;
    const createdLogEntry =
    //new logEntry(
    {
        id: uuid(), title
    };
    DUMMY_LOGENTRIES.push(createdLogEntry);
    res.status(201).json({ logEntry: createdLogEntry });
};

When I remove validators, POST request works, but with the validator Nodemon returns:

  formatter: [Function: formatter],
  errors: [
    {
      value: undefined,
      msg: 'Invalid value',
      param: 'title',
      location: 'body'
    },

Bonus question: Without the validator the returned response is only the uuid... not the title and I can't figure out why since I ask for the full createdLogEntry which should return title and uuid. Thoughts?


问:
http.client.InvalidURL: nonnumeric port: '//water-lined.net' Error?
I've been trying to make a script to check if a random website exists and then opens it if it does exist, but I keep getting a bunch of different errors. Here is my code:

```<code>import webbrowser
import time
import random
import http.client
from random_word import RandomWords
r=RandomWords()
while True:
    possible_things = random.choice([".com",".net"])
    WEB = "http://"+r.get_random_word()+possible_things
    c = http.client.HTTPConnection(WEB)
    if c.getresponse().status == 200:
        seconds = random.randint(5,20)
        print("Web site exists; Website: "+WEB+" ; Seconds: "+seconds)
        time.sleep(seconds)
        webbrowser.open(WEB)
        print("Finished countdown, re-looping...")
    else:
        print('Web site DOES NOT exists; Website: '+WEB+'; re-looping...')
</code>```

And here is the error:

```<code>Traceback (most recent call last):
  File "C:\Users\[REDACTED]\AppData\Local\Programs\Python\Python37-32\lib\http\client.py", line 877, in _get_hostport
    port = int(host[i+1:])
ValueError: invalid literal for int() with base 10: '//water-lined.net'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "Troll.py", line 10, in <module>
    c = http.client.HTTPConnection(WEB)
  File "C:\Users\[REDACTED]\AppData\Local\Programs\Python\Python37-32\lib\http\client.py", line 841, in __init__
    (self.host, self.port) = self._get_hostport(host, port)
  File "C:\Users\[REDACTED]\AppData\Local\Programs\Python\Python37-32\lib\http\client.py", line 882, in _get_hostport
    raise InvalidURL("nonnumeric port: '%s'" % host[i+1:])
http.client.InvalidURL: nonnumeric port: '//water-lined.net'
</code>```

答: I just set a long delay and added a lot of tries, but thanks a lot @Błotosmętek!</p>

Body:
I've been trying to make a script to check if a random website exists and then opens it if it does exist, but I keep getting a bunch of different errors. Here is my code:

import webbrowser
import time
import random
import http.client
from random_word import RandomWords
r=RandomWords()
while True:
    possible_things = random.choice([".com",".net"])
    WEB = "http://"+r.get_random_word()+possible_things
    c = http.client.HTTPConnection(WEB)
    if c.getresponse().status == 200:
        seconds = random.randint(5,20)
        print("Web site exists; Website: "+WEB+" ; Seconds: "+seconds)
        time.sleep(seconds)
        webbrowser.open(WEB)
        print("Finished countdown, re-looping...")
    else:
        print('Web site DOES NOT exists; Website: '+WEB+'; re-looping...')

And here is the error:

Traceback (most recent call last):
  File "C:\Users\[REDACTED]\AppData\Local\Programs\Python\Python37-32\lib\http\client.py", line 877, in _get_hostport
    port = int(host[i+1:])
ValueError: invalid literal for int() with base 10: '//water-lined.net'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "Troll.py", line 10, in <module>
    c = http.client.HTTPConnection(WEB)
  File "C:\Users\[REDACTED]\AppData\Local\Programs\Python\Python37-32\lib\http\client.py", line 841, in __init__
    (self.host, self.port) = self._get_hostport(host, port)
  File "C:\Users\[REDACTED]\AppData\Local\Programs\Python\Python37-32\lib\http\client.py", line 882, in _get_hostport
    raise InvalidURL("nonnumeric port: '%s'" % host[i+1:])
http.client.InvalidURL: nonnumeric port: '//water-lined.net'


问:
How to set the ng-template value from the component
I have this in my HTML file:

```<code><div>
  <ng-template  #valueTemplate>

  </ng-template>
</div>
</code>```

How can I set the innerHtml of the ng-template using my local reference #valueTemplate from the component?

I tried this but it doesn't work:

```<code>import { Component, OnInit, ViewChild } from '@angular/core';

@Component({
  selector: 'app-some',
  templateUrl: './some.component.html',
  styleUrls: ['./some.component.css'],
})
export class SomeComponent implements OnInit {
  @ViewChild('valueTemplate', { static: false }) valueTemplate;

  ngOnInit() {
    this.postContentEditContent.innerHTML(data.content); // Doesn't work
    this.postContentEditContent.value(data.content); // Doesn't work
    this.postContentEditContent.setValue(data.content); // Doesn't work
    this.postContentEditContent.textContent(data.content); // Doesn't work
  }
}
</code>```

How can I set its value from the component?

答:
<ng-template> won't be created in the DOM as it is just a template.

You should bind to an element that will get created in the DOM, such as a
.

As a bonus, you can bind using the innerHTML property.

```<code><div [innerHTML]="content"></div>
</code>```

To do this you will need to mark it as safe HTML in the component:

```<code>constructor(private sanitizer:DomSanitizer){}

content: string;

ngOnInit(): void {
  this.content = this.sanitizer.bypassSecurityTrustHtml('<p>Hello, world!</p>');
}
</code>```

Body:
I have this in my HTML file:

  <ng-template  #valueTemplate>

  </ng-template>

How can I set the innerHtml of the ng-template using my local reference #valueTemplate from the component?

I tried this but it doesn't work:

import { Component, OnInit, ViewChild } from '@angular/core';

@Component({
  selector: 'app-some',
  templateUrl: './some.component.html',
  styleUrls: ['./some.component.css'],
})
export class SomeComponent implements OnInit {
  @ViewChild('valueTemplate', { static: false }) valueTemplate;

  ngOnInit() {
    this.postContentEditContent.innerHTML(data.content); // Doesn't work
    this.postContentEditContent.value(data.content); // Doesn't work
    this.postContentEditContent.setValue(data.content); // Doesn't work
    this.postContentEditContent.textContent(data.content); // Doesn't work
  }
}

How can I set its value from the component?

Body:
<ng-template> won't be created in the DOM as it is just a template.

You should bind to an element that will get created in the DOM, such as a <div>.

As a bonus, you can bind using the innerHTML property.

<div [innerHTML]="content"></div>

To do this you will need to mark it as safe HTML in the component:

constructor(private sanitizer:DomSanitizer){}

content: string;

ngOnInit(): void {
  this.content = this.sanitizer.bypassSecurityTrustHtml('<p>Hello, world!</p>');
}


问:
Ionic 4 error showing on using component in 2 pages
I have created a loader component and i am trying to use in my pages. Problem is its working fine in one page but when i am using in other page its showing error of

component is part of the declarations of 2 modules: AppModule in

This is my first page category.module.ts

```<code>import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { LoaderComponent } from '../loader/loader.component';    //this is component i am using
import { IonicModule } from '@ionic/angular';

import { CategoryPageRoutingModule } from './category-routing.module';

import { CategoryPage } from './category.page';

@NgModule({
  imports: [
    CommonModule,
    FormsModule,
    IonicModule,
    CategoryPageRoutingModule
  ],
  declarations: [CategoryPage, LoaderComponent]
})
export class CategoryPageModule {}
</code>```

My other mage login.module.ts

```<code>import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { IonicModule } from '@ionic/angular';
import { LoaderComponent } from '../loader/loader.component'; //this is component

import { LoginPageRoutingModule } from './login-routing.module';

import { LoginPage } from './login.page';

@NgModule({
  imports: [
    CommonModule,
    FormsModule,
    IonicModule,
    LoginPageRoutingModule,
  ],
  declarations: [LoginPage, LoaderComponent]
})
export class LoginPageModule {}
</code>```

Now if i am removing my component from second page its working fine. And in app.module.ts i have added my component in declaration array.

答:
I agree with the suggestion provided by @bjdose. Below is an example of how you could implement the shared component.

You will want to have a loader.module.ts file for this example to work. In that file you can declare and export the Loader component like this...

```<code>import { NgModule } from "@angular/core";
import { CommonModule } from "@angular/common";
import { IonicModule } from '@ionic/angular';

import { LoaderComponent } from './loader.component';

@NgModule({
    imports: [CommonModule, IonicModule],
    declarations: [LoaderComponent],
    exports: [LoaderComponent]
})
export class LoaderModule { }
</code>```

Now that it is exported, it is available throughout the app. In order use it all you need to do is import the component module into the module that declares the page you want to use it in. Something like this...

```<code>import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { IonicModule } from '@ionic/angular';
import { FormsModule } from '@angular/forms';
import { RouterModule } from '@angular/router';

import { LoaderModule } from '../loader/loader.module';

import { HomePage } from './home.page';

@NgModule({
  imports: [
    CommonModule,
    FormsModule,
    IonicModule,
    RouterModule.forChild([
      {
        path: '',
        component: HomePage
      }
    ]),
    LoaderModule
  ],
  declarations: [HomePage]
})
export class HomePageModule { }
</code>```

Hope his helps.

Body:
I have created a loader component and i am trying to use in my pages. Problem is its working fine in one page but when i am using in other page its showing error of

component is part of the declarations of 2 modules: AppModule in

This is my first page category.module.ts

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { LoaderComponent } from '../loader/loader.component';    //this is component i am using
import { IonicModule } from '@ionic/angular';

import { CategoryPageRoutingModule } from './category-routing.module';

import { CategoryPage } from './category.page';

@NgModule({
  imports: [
    CommonModule,
    FormsModule,
    IonicModule,
    CategoryPageRoutingModule
  ],
  declarations: [CategoryPage, LoaderComponent]
})
export class CategoryPageModule {}

My other mage login.module.ts

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { IonicModule } from '@ionic/angular';
import { LoaderComponent } from '../loader/loader.component'; //this is component

import { LoginPageRoutingModule } from './login-routing.module';

import { LoginPage } from './login.page';

@NgModule({
  imports: [
    CommonModule,
    FormsModule,
    IonicModule,
    LoginPageRoutingModule,
  ],
  declarations: [LoginPage, LoaderComponent]
})
export class LoginPageModule {}

Now if i am removing my component from second page its working fine. And in app.module.ts i have added my component in declaration array.

Body:
I agree with the suggestion provided by @bjdose. Below is an example of how you could implement the shared component.

You will want to have a loader.module.ts file for this example to work. In that file you can declare and export the Loader component like this...

import { NgModule } from "@angular/core";
import { CommonModule } from "@angular/common";
import { IonicModule } from '@ionic/angular';

import { LoaderComponent } from './loader.component';

@NgModule({
    imports: [CommonModule, IonicModule],
    declarations: [LoaderComponent],
    exports: [LoaderComponent]
})
export class LoaderModule { }

Now that it is exported, it is available throughout the app. In order use it all you need to do is import the component module into the module that declares the page you want to use it in. Something like this...

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { IonicModule } from '@ionic/angular';
import { FormsModule } from '@angular/forms';
import { RouterModule } from '@angular/router';

import { LoaderModule } from '../loader/loader.module';

import { HomePage } from './home.page';

@NgModule({
  imports: [
    CommonModule,
    FormsModule,
    IonicModule,
    RouterModule.forChild([
      {
        path: '',
        component: HomePage
      }
    ]),
    LoaderModule
  ],
  declarations: [HomePage]
})
export class HomePageModule { }

Hope his helps.


问:
How to use Camel to get message from remote WMQ and place message in ActiveMQ?
I have been looking at these for days and still haven't have mush success.

I have install and run activeMQ on a server. Created a queue called "testUpdate". I also have another queue on another server, let call this "forward" and this is on the IBM MQ (WMQ).

So we have testUpdate on ActiveMQ and forward on WMQ. I want the message on forward queue to be placed into testUpdate queue. Trying to use Camel for this process.

So the setup in ActiveMQ has an XML(activemq.xml) that I can place spring beans and configure to do the routing. In this xml, I added http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd to the xmlns and then added

import resource="camel.xml"

In this new xml, I have the following:

```<code>    <beans
   xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="
     http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd
     http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

        <camelContext id="camel" xmlns="http://camel.apache.org/schema/spring">
            <route>
                <description>Example Camel Route</description>
                <from uri="mqseries:forward"/>
                <to uri="activemq:testUpdate"/>
            </route>
        </camelContext>

        <bean id="mqseries" class="com.ibm.mq.jms.MQQueueConnectionFactory">
                <property name="transportType" value="1"/>
                <property name="hostName" value="172.00.12.21/>
                <property name="port" value="xyza"/>
                <property name="queueManager" value="manager"/>
                <property name="channel" value="srvcChannel"/>
        </bean>

        <!--
           Lets configure some Camel endpoints

           http://camel.apache.org/components.html
        -->

        <!-- configure the camel activemq component to use the current broker -->
        <bean id="activemq" class="org.apache.activemq.camel.component.ActiveMQComponent" >
            <property name="connectionFactory">
              <bean class="org.apache.activemq.ActiveMQConnectionFactory">
                <property name="brokerURL" value="vm://amq-broker?create=false"/>
                <property name="userName" value="${activemq.username}"/>
                <property name="password" value="${activemq.password}"/>
              </bean>
            </property>
        </bean>

    </beans>
</code>```

I added the jar file com.ibm.mq.allclient.jar into the lib folder of ActiveMQ. When running the program, I am getting this exception:
java.lang.ClassNotFoundException: javax.jms.JMSRuntimeException

It sounds like I am missing the websphere jar file? Is this correct?

答: You can use users camel extra component https://github.com/camel-extra/camel-extra/blob/master/components/camel-wmq/README.md to get messages from wmq without using the JMS wrapping and then send messages to ActiveMQ with custom camel component https://camel.apache.org/components/latest/activemq-component.html. See also a similar topic Apache Camel with IBM MQ. </p>

Body:
I have been looking at these for days and still haven't have mush success.

I have install and run activeMQ on a server. Created a queue called "testUpdate". I also have another queue on another server, let call this "forward" and this is on the IBM MQ (WMQ).

So we have testUpdate on ActiveMQ and forward on WMQ. I want the message on forward queue to be placed into testUpdate queue. Trying to use Camel for this process.

So the setup in ActiveMQ has an XML(activemq.xml) that I can place spring beans and configure to do the routing. In this xml, I added http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd to the xmlns and then added

import resource="camel.xml"

In this new xml, I have the following:

    <beans
   xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="
     http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd
     http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

        <camelContext id="camel" xmlns="http://camel.apache.org/schema/spring">
            <route>
                <description>Example Camel Route</description>
                <from uri="mqseries:forward"/>
                <to uri="activemq:testUpdate"/>
            </route>
        </camelContext>

        <bean id="mqseries" class="com.ibm.mq.jms.MQQueueConnectionFactory">
                <property name="transportType" value="1"/>
                <property name="hostName" value="172.00.12.21/>
                <property name="port" value="xyza"/>
                <property name="queueManager" value="manager"/>
                <property name="channel" value="srvcChannel"/>
        </bean>

        <bean id="activemq" class="org.apache.activemq.camel.component.ActiveMQComponent" >
            <property name="connectionFactory">
              <bean class="org.apache.activemq.ActiveMQConnectionFactory">
                <property name="brokerURL" value="vm://amq-broker?create=false"/>
                <property name="userName" value="${activemq.username}"/>
                <property name="password" value="${activemq.password}"/>
              </bean>
            </property>
        </bean>

    </beans>

I added the jar file com.ibm.mq.allclient.jar into the lib folder of ActiveMQ. When running the program, I am getting this exception:
java.lang.ClassNotFoundException: javax.jms.JMSRuntimeException

It sounds like I am missing the websphere jar file? Is this correct?


问:
How to comment in jspx page
How to comment the code in jspx page? I have tried several methods,

```<code><!--  -->
<%-- -->
</code>```

but it doesn't not work!

So I have to:

```<code><c:if test="${false}">code</c:if>,
</code>```

it is really urgly, Is there any other ways?
Any help is appreciated!

答:
Just use  for comments. JSPX file uses XML syntax so that's the reason XML style comment work here.

Also read article Creating a JSP Document for understanding the difference between JSP standard syntax and XML syntax

ContentLicense: CC BY-SA 2.5

Title: How to comment in jspx page

Body:
How to comment the code in jspx page? I have tried several methods,

<%-- -->

but it doesn't not work!

So I have to:

<c:if test="${false}">code</c:if>,

it is really urgly, Is there any other ways?
Any help is appreciated!

Body:
Just use <!-- comment --> for comments. JSPX file uses XML syntax so that's the reason XML style comment work here.

Also read article Creating a JSP Document for understanding the difference between JSP standard syntax and XML syntax


问:
http://localhost:50070 shows unable to connect but http://localhost:50030 is working
I'm using Vmware with centos version 6(Fedora). I'm using hadoop version 1.0.4. My http://localhost:50070 address shows "unable to connect", but the http://localhost:50030 address is working.

My jps command is showing this:

```<code>5296 SecondaryNameNode
5697 Jps
5171 DataNode
5382 JobTracker
5514 TaskTracker.
</code>```

答: Port 50070 is related to the HDFS service and it corresponds to the described behaviour because the NameNode is not running (according to the jps command). Most probably you have a configuration issue in the hdfs xml configuration files. To find why the NameNode was not able to start, please go to the hadoop NameNode logs ($HADOOP_HOME/logs) and trace the error, commonly specified in the clause Caused By.

Body:
I'm using Vmware with centos version 6(Fedora). I'm using hadoop version 1.0.4. My http://localhost:50070 address shows "unable to connect", but the http://localhost:50030 address is working.

My jps command is showing this:

5296 SecondaryNameNode
5697 Jps
5171 DataNode
5382 JobTracker
5514 TaskTracker.


问:
Flutter cached image is it possible to reload image instead of getting the cached image?
I'm using the package flutter_cached_network_image to load images from firebase. When a user updates his profile picture (filename is still the same) the image that is loaded is still the same as the one before the update because it is loaded from cache (because it still has the same url as before).
Is it possible to clear the picture from the cache so the new image is loaded?</p>

答:
Like @EderBaum said, you can force puting an additional query string input, the value depends of the effect that you want, for example:

1 - Never cache
http:urlofresource.com/yourimage.jpg?version={NewRandonNumberGenerated}

You can use Random class to achieve this.

2- Reload cache based on app version

Same that before, but now, you use an version information that you can put into your global state or somewhere else to retrieve information after an update

3 - Use normal cache

Just leave the widget do the job.


问:
Optional nested validation in vuelidate
what is the correct way to add an optional validation object in vuelidate?

Given a validation shape of:

```<code>validations: {
    vehicles: {
        $each: {
            type: {
                required
            },
            engine: {
                required: requiredIf((vehicle) => vehicle.type == 'car'),

                size: {
                    required
                },

                power: {
                    required
                }
            }
        }
    }
}
</code>```

My expectation was that for a vehicle of type bike I would not need to provide a size and power as their parent engine is not required. However the validation is returning invalid.

答:
What you could do instead of asking for each subfield of engine to be required is to ask every engine to have both size and power, so that for everytime there is an engine it must have those keys. Add this together with the requiredIf and you have the following: Every vehicle must have a type, if it is a car then an engine is required and every engine must have a power and size.

The following snippet shows it working.

Vue.use(vuelidate.default);
let { required, requiredIf, helpers } = validators;
const contains = (param) =>
  (value) => !helpers.req(value) ||
    param.reduce((accum, curr) => accum && curr in value, true);
var app = new Vue({
  el: '#app',
  data: () => ({
    vehicles: [
      {
        type: 'car',
        engine: {
          size: 5,
          power: 2.5,
        }
      },
      {
        type: 'bike',
      }
    ]
  }),
  validations: {
    vehicles: {
      $each: {
        type: { required },
        engine: {
          required: requiredIf((value) => value.type === 'car'),
          contains: contains(['size', 'power']),
        }
      }
    }
  },
  created() {
    console.log(this.$v.$invalid);
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vuelidate@0.7.5/dist/vuelidate.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vuelidate@0.7.5/dist/validators.min.js"></script>
<div id="app"></div></code>```

Title: Optional nested validation in vuelidate

Body:
what is the correct way to add an optional validation object in vuelidate?

Given a validation shape of:

validations: {
    vehicles: {
        $each: {
            type: {
                required
            },
            engine: {
                required: requiredIf((vehicle) => vehicle.type == 'car'),

                size: {
                    required
                },

                power: {
                    required
                }
            }
        }
    }
}

My expectation was that for a vehicle of type bike I would not need to provide a size and power as their parent engine is not required. However the validation is returning invalid.

Body:
What you could do instead of asking for each subfield of engine to be required is to ask every engine to have both size and power, so that for everytime there is an engine it must have those keys. Add this together with the requiredIf and you have the following: Every vehicle must have a type, if it is a car then an engine is required and every engine must have a power and size.

The following snippet shows it working.

Vue.use(vuelidate.default);
let { required, requiredIf, helpers } = validators;
const contains = (param) =>
  (value) => !helpers.req(value) ||
    param.reduce((accum, curr) => accum && curr in value, true);
var app = new Vue({
  el: '#app',
  data: () => ({
    vehicles: [
      {
        type: 'car',
        engine: {
          size: 5,
          power: 2.5,
        }
      },
      {
        type: 'bike',
      }
    ]
  }),
  validations: {
    vehicles: {
      $each: {
        type: { required },
        engine: {
          required: requiredIf((value) => value.type === 'car'),
          contains: contains(['size', 'power']),
        }
      }
    }
  },
  created() {
    console.log(this.$v.$invalid);
  }
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vuelidate@0.7.5/dist/vuelidate.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vuelidate@0.7.5/dist/validators.min.js"></script>
<div id="app"></div>


问:
How to make sure the public key's authenticity
I'm new to asymmetric cryptography (public-private keys) and has a fundamental confusion:
  I understand that once a person has broadcast his public key to the network, the following communications become safe using the public-private key paradigm.
  However, how do you make sure the public key received is valid at the first place? For example, if Bob wants to establish a secure communication with Alice, with Eve eavesdropping in the middle, how do you make sure that Bob receives the real public key from Alice, instead of the fake public key forged by Eve?
  Thanks!

Cheers,
M.

答:
Public Key Infrastructure (PKI).

You have a third-party trusted authority that issues certificates to different people/companies. You don't only trust the people, but also the Certification Authority (CA).

The Certification Authority must ensure and validate that the people/company that is buying a certificate is in fact who it claims to be.

The verification is done by signing a the certificate using a private key (from this CA), then both peers in the connection will check that the certificate was signed by a trusted CA and validate the connection.

In you example, Bob will sign the certificate in a CA that Alice trusts.

If Eve tries to sign a certificate in this CA, claiming to be Bob, this will be rejected, because the CA will validate its authenticity. Try to buy a client certificate here to see: https://www.verisign.com/

Another example is your browser, it only shows that a trusted connection is done with StackOverflow, because it trust on Let´s Encrypt, which issued the StackOverflow.com certificate.

Every browser has some default CAs that are already trusted.


问:
jQuery - 2 different functions for 2 different submit buttons in one form
I have had a search around at other suggestions for what i want to do, but none seems to have what i need.

Basically i have a form with 2 submit buttons, i want one to save the data to the database, which i have done and works perfect ... the second submit button ( preview ) i need to open in a new window, take all the form data and display it on a form while leaving the previous page as it is ... if that makes sense.

I figure i cant do this with PHP as to get the post data it needs to basically reload a page ... i thought there might be a way with jQuery.

Any help?

答:
I wouldn't use jQuery for this unless you're already using it elsewhere in the application.

HTML Markup:

```<code><form method="post" action="foo.php" id="myform">
    <button type="submit" name="save_data">Save Data</button>
    <button type="submit" name="preview_data" onclick="document.getElementById('myform').target = '_blank'; return true;">Preview Data</button>
</form>
</code>```

PHP:

```<code><?php
if (isset($_POST['preview_data'])) {
    // Clicked Preview
} else if (isset($_POST['save_data'])) {
    // Clicked Save
} else {
    // How'd you get here? Probably not POST
}
?>
</code>```

Body:
I wouldn't use jQuery for this unless you're already using it elsewhere in the application.

HTML Markup:

<form method="post" action="foo.php" id="myform">
    <button type="submit" name="save_data">Save Data</button>
    <button type="submit" name="preview_data" onclick="document.getElementById('myform').target = '_blank'; return true;">Preview Data</button>
</form>

PHP:

<?php
if (isset($_POST['preview_data'])) {
    // Clicked Preview
} else if (isset($_POST['save_data'])) {
    // Clicked Save
} else {
    // How'd you get here? Probably not POST
}
?>


问:
How to convert multiple array to single array
Sorry for asking this silly question here. I am very new to PHP language.
I am trying to know how can i convert the array.

I want to convert this array to single array like.

Convert this :-

```<code>Array ( [0] => user )
Array ( [0] => user1 )
Array ( [0] => user2 )
Array ( [0] => user3 )
Array ( [0] => user8 )
Array ( [0] => user7 )
Array ( [0] => user6 )
</code>```

Convert To :-

```<code>Array("user", "user1", "user2", "user3", "user4", "user5", "user6");
</code>```

答:
Something like this should do:</p>

```<code>while($row = $result->fetch_array(MYSQLI_NUM)) {
    $users[] = $row[0];
}
</code>```

Body:
Sorry for asking this silly question here. I am very new to PHP language.
I am trying to know how can i convert the array.

I want to convert this array to single array like.

Convert this :-

Array ( [0] => user )
Array ( [0] => user1 )
Array ( [0] => user2 )
Array ( [0] => user3 )
Array ( [0] => user8 )
Array ( [0] => user7 )
Array ( [0] => user6 )

Convert To :-

Array("user", "user1", "user2", "user3", "user4", "user5", "user6");

Body:
Something like this should do:

while($row = $result->fetch_array(MYSQLI_NUM)) {
    $users[] = $row[0];
}


问:
sparse sparse product A^T*A optim in Eigen lib
In the case of multiple of same matrix matA, like

```<code>matA.transpose()*matA,
</code>```

You don't have to compute all result product, because the result matrix is symmetric(so only if the m>n), in my specific case is always symmetric! square.

So its enough the compute only for. ex. lower triangular part and rest only copy..... because the results of the multiple 2nd and 3rd row, resp.col, is the same like 3rd and 2nd.....And etc....

So my question is , exist way how to tell Eigen, to compute only lower part. and  optionally save to only lower trinaguler part the product?

```<code>    DATA = SparseMatrix<double>((SparseMatrix<double>(matA.transpose()) * matA).pruned()).toDense();
</code>```

答:
https://eigen.tuxfamily.org/dox/classEigen_1_1SparseSelfAdjointView.html

The symmetric rank update is defined as:

```<code>B = B + alpha * A * A^T
</code>```

where alpha is a scalar. In your case, you are doing A^T * A, so you should pass the transposed matrix instead. The resulting matrix will only store the upper or lower portion of the matrix, whichever you prefer. For example:

```<code>SparseMatrix<double> B;
B.selfadjointView<Lower>().rankUpdate(A.transpose());
</code>```

Body:
In the case of multiple of same matrix matA, like

matA.transpose()*matA,

You don't have to compute all result product, because the result matrix is symmetric(so only if the m>n), in my specific case is always symmetric! square.

So its enough the compute only for. ex. lower triangular part and rest only copy..... because the results of the multiple 2nd and 3rd row, resp.col, is the same like 3rd and 2nd.....And etc....

So my question is , exist way how to tell Eigen, to compute only lower part. and  optionally save to only lower trinaguler part the product?

    DATA = SparseMatrix<double>((SparseMatrix<double>(matA.transpose()) * matA).pruned()).toDense();

Body:
https://eigen.tuxfamily.org/dox/classEigen_1_1SparseSelfAdjointView.html

The symmetric rank update is defined as:

B = B + alpha * A * A^T

where alpha is a scalar. In your case, you are doing A^T * A, so you should pass the transposed matrix instead. The resulting matrix will only store the upper or lower portion of the matrix, whichever you prefer. For example:

SparseMatrix<double> B;
B.selfadjointView<Lower>().rankUpdate(A.transpose());


问:
How to use \b word boundary in pandas str.contains?
Is there an equivalent when using str.contains?

the following code is mistakenly listing "Said Business School" in the category because of 'Sa.' If I could create a wordboundary it would solve the problem. Putting a space after messes this up. I am using pandas, which are the dfs. I know I can use regex, but just curious if i can use strings to make it faster

```<code>gprivate_n = ('Co|Inc|Llc|Group|Ltd|Corp|Plc|Sa |Insurance|Ag|As|Media|&|Corporation')
df.loc[df[df.Name.str.contains('{0}'.format(gprivate_n))].index, "Private"] = 1
</code>```

答:
This is just the same old Python issue in regexes where '\b' should be passed either as raw-string r'\b...'. Or less desirably, double-escaping ('\\b').

So your regex should be:

```<code>gprivate_n = (r'\b(Co|Inc|Llc|Group|Ltd|Corp|Plc|Sa |Insurance|Ag|As|Media|&|Corporation)')
</code>```

Body:
Is there an equivalent when using str.contains?

the following code is mistakenly listing "Said Business School" in the category because of 'Sa.' If I could create a wordboundary it would solve the problem. Putting a space after messes this up. I am using pandas, which are the dfs. I know I can use regex, but just curious if i can use strings to make it faster

gprivate_n = ('Co|Inc|Llc|Group|Ltd|Corp|Plc|Sa |Insurance|Ag|As|Media|&|Corporation')
df.loc[df[df.Name.str.contains('{0}'.format(gprivate_n))].index, "Private"] = 1

Body:
This is just the same old Python issue in regexes where '\b' should be passed either as raw-string r'\b...'. Or less desirably, double-escaping ('\\b').

So your regex should be:

gprivate_n = (r'\b(Co|Inc|Llc|Group|Ltd|Corp|Plc|Sa |Insurance|Ag|As|Media|&|Corporation)')


问:
Multiple hits in on page in MTurk
In Mturk, we want to show a set of tweets, e.g., 20 tweets, in boxes in one page. Then, Workers click JUST on the tweets (boxes) that are relevant to a specific concept like "entrepreneurship". For example for 3 tweets:

Tweet 1: Money and supporting customers are essential for a business

Tweet 2: I like tennis

Tweet 3: I spend my invest for buying my home.

Tweets should be shown in boxes and Workers should just click on Tweet 1 (instead of clicking on Yes or No buttons) and MTurk returns the results in a file (like csv format) in this way:

Yes (or 1)

No (or 0)

No (or 0)

We want to show multiple tweets (multiple hits) in one page.

How can we create a code so that for a batch of tweets, MTurk reads 20 tweets from the batch and puts them in their place for the Workers?
Is there such design? If yes, would you please guide me how I can do it? With many thanks. Jafar

答: All 20 tweets would be required to be part of the same HIT. There's no way to create one HIT per tweet, then have Mechanical Turk display 20 of them as one task for a worker to complete. </p>

Title: Multiple hits in on page in MTurk


问:
Page count of Pdf with Java
at the moment I am using itext to read the page count of a pdf. This takes quite long because the lib seems to scan the whole file.

Is the page information somewhere in the header of the pdf, or is a full filescan needed?

答:
Lars Vogel uses the following code:

```<code>PdfReader reader = new PdfReader(INPUTFILE);
int n = reader.getNumberOfPages();
</code>```

I'd be surprised if the implementation of getNumberOfPages is slower than any other solution.

Section F.3.3 says there is a header-field called N described as follows:

```<code>N     integer (Required)      The number of pages in the document.
</code>```

Title: Page count of Pdf with Java

Body:
Lars Vogel uses the following code:

PdfReader reader = new PdfReader(INPUTFILE);
int n = reader.getNumberOfPages();

I'd be surprised if the implementation of getNumberOfPages is slower than any other solution.

Section F.3.3 says there is a header-field called N described as follows:

N     integer (Required)      The number of pages in the document.


问:
Remove-WebBindings removing binding from all IIS sites
I am creating a Powershell script using the WebAdministration module to create a couple of sites and automatically add bindings

```<code>Import-Module WebAdministration

$config = @{
    Sites = @(
        @{
            Name = "Site1";
            Path = "Path1";
            Bindings = @(
                @{ Protocol = "http"; Port = 80;},
                @{ Protocol = "https"; Port = 443;}
            );
        },
        @{
            Name = "Site2";
            Path = "Path2";
            Bindings = @(
                @{ Protocol = "http"; Port = 3009;}
            );
        }
    )
}

foreach($site in $config.Sites){
    $physicalPath = Get-Item "$($site.Path)"
    # Create the current site
    New-WebSite -Name "$($site.Name)" -PhysicalPath $physicalPath.FullName

    ## Trying to remove default port 80 binding for the current site
    Remove-WebBinding -Name $site.Name -Port 80 -Protocol "http"

    ## Add the desired bindings
    foreach ($binding in $site.Bindings){
        New-WebBinding -Name "$($site.Name)" -Protocol $binding.Protocol -Port $binding.Port
    }
}
</code>```

When I do this though, I'm left without a binding on port 80 Site1. It looks like Remove-WebBinding -Name $site.Name -Port 80 -Protocol "http" is removing bindings for both sites.

```<code>PS > Get-ChildItem IIS:\Sites

Name             ID   State      Physical Path                  Bindings
----             --   -----      -------------                  --------
Site1            1    Started    Path1                          https *:443: sslFlags=0
Site2            2    Stopped    Path2                          http *:3009:
</code>```

If I do this without attempting to modify any bindings

```<code>foreach($site in $config.Sites){
    $physicalPath = Get-Item "$($site.Path)"
    # Create the current site
    New-WebSite -Name "$($site.Name)" -PhysicalPath $physicalPath.FullName
}
</code>```

I end up with both sites bound to port 80

```<code>PS > Get-ChildItem IIS:\Sites

Name             ID   State      Physical Path                  Bindings
----             --   -----      -------------                  --------
Site1            1    Started    Path1                          http *:80:
Site2            2    Stopped    Path2                          http *:80:
</code>```

What am I doing wrong? Is there a better way? Is this a bug?

答:
I have seen similar behavior.  Rather than attempting to explicitly find and remove a binding entry, I have found more success using the pipeline to reference an already identified object.

For example:

```<code>Get-Website -Name "$($site.Name)" | Get-WebBinding -Protocol "http" -Port 80 | Remove-WebBinding
</code>```

Body:
I am creating a Powershell script using the WebAdministration module to create a couple of sites and automatically add bindings

Import-Module WebAdministration

$config = @{
    Sites = @(
        @{
            Name = "Site1";
            Path = "Path1";
            Bindings = @(
                @{ Protocol = "http"; Port = 80;},
                @{ Protocol = "https"; Port = 443;}
            );
        },
        @{
            Name = "Site2";
            Path = "Path2";
            Bindings = @(
                @{ Protocol = "http"; Port = 3009;}
            );
        }
    )
}

foreach($site in $config.Sites){
    $physicalPath = Get-Item "$($site.Path)"
    # Create the current site
    New-WebSite -Name "$($site.Name)" -PhysicalPath $physicalPath.FullName

    ## Trying to remove default port 80 binding for the current site
    Remove-WebBinding -Name $site.Name -Port 80 -Protocol "http"

    ## Add the desired bindings
    foreach ($binding in $site.Bindings){
        New-WebBinding -Name "$($site.Name)" -Protocol $binding.Protocol -Port $binding.Port
    }
}

When I do this though, I'm left without a binding on port 80 Site1. It looks like Remove-WebBinding -Name $site.Name -Port 80 -Protocol "http" is removing bindings for both sites.

PS > Get-ChildItem IIS:\Sites

Name             ID   State      Physical Path                  Bindings
----             --   -----      -------------                  --------
Site1            1    Started    Path1                          https *:443: sslFlags=0
Site2            2    Stopped    Path2                          http *:3009:

If I do this without attempting to modify any bindings

foreach($site in $config.Sites){
    $physicalPath = Get-Item "$($site.Path)"
    # Create the current site
    New-WebSite -Name "$($site.Name)" -PhysicalPath $physicalPath.FullName
}

I end up with both sites bound to port 80

PS > Get-ChildItem IIS:\Sites

Name             ID   State      Physical Path                  Bindings
----             --   -----      -------------                  --------
Site1            1    Started    Path1                          http *:80:
Site2            2    Stopped    Path2                          http *:80:

What am I doing wrong? Is there a better way? Is this a bug?

Body:
I have seen similar behavior.  Rather than attempting to explicitly find and remove a binding entry, I have found more success using the pipeline to reference an already identified object.

For example:

Get-Website -Name "$($site.Name)" | Get-WebBinding -Protocol "http" -Port 80 | Remove-WebBinding


问:
Combing Dataframes in a list by two columns "i" and "j" to do staistical analysis
I have a List of 366 Dataframes, each DG contains 3 Columns, i.e; "i", "j" and "Value". I want to merge these data frames in a single data frame to do statistical analysis, like mean, mode, median. each list contains almost the same no. observations? </p>

答:
Assuming the data sets are in your working directory & have some unique identifier in filename (e.g. "dataset": "dataset1.csv", "dataset2.csv", "dataset3.csv", etc...), and you don't mind using tidyverse, the following should work:

```<code>library(tidyverse)

file_names <- list.files() %>%
   str_extract(., "dataset")

my_df <- map(file_names, ~ read_csv(.x)) %>% bind_rows()

</code>```

Body:
Assuming the data sets are in your working directory & have some unique identifier in filename (e.g. "dataset": "dataset1.csv", "dataset2.csv", "dataset3.csv", etc...), and you don't mind using tidyverse, the following should work:

library(tidyverse)

file_names <- list.files() %>%
   str_extract(., "dataset")

my_df <- map(file_names, ~ read_csv(.x)) %>% bind_rows()


答:
Base R options:

set.seed(42)
listdat <- replicate(3, data.frame(i=sample(100, size=2), j=sample(100, size=2), Value=sample(100, size=2)), simplify = FALSE)
str(listdat)
# List of 3
#  $ :'data.frame': 2 obs. of  3 variables:
#   ..$ i    : int [1:2] 92 93
#   ..$ j    : int [1:2] 29 83
#   ..$ Value: int [1:2] 65 52
#  $ :'data.frame': 2 obs. of  3 variables:
#   ..$ i    : int [1:2] 74 14
#   ..$ j    : int [1:2] 66 70
#   ..$ Value: int [1:2] 46 72
#  $ :'data.frame': 2 obs. of  3 variables:
#   ..$ i    : int [1:2] 94 26
#   ..$ j    : int [1:2] 47 94
#   ..$ Value: int [1:2] 98 12
```

<p>Starting with that, the first thing we can do is just combine them row-wise, all in one go:</p>

<pre class="lang-r prettyprint-override"><code>do.call(rbind, listdat)
#    i  j Value
# 1 92 29    65
# 2 93 83    52
# 3 74 66    46
# 4 14 70    72
# 5 94 47    98
# 6 26 94    12
</code>```

It might be nice to include which index they came from. If they are not named, then you can just include the index number:

do.call(rbind, Map(cbind, listdat, num=seq_along(listdat)))
#    i  j Value num
# 1 92 29    65   1
# 2 93 83    52   1
# 3 74 66    46   2
# 4 14 70    72   2
# 5 94 47    98   3
# 6 26 94    12   3
```

<p>If they have names, however, we can use the same technique:</p>

<pre class="lang-r prettyprint-override"><code>names(listdat) <- c("A","B","C")
do.call(rbind, Map(cbind, listdat, name=names(listdat)))
#      i  j Value name
# A.1 92 29    65    A
# A.2 93 83    52    A
# B.1 74 66    46    B
# B.2 14 70    72    B
# C.1 94 47    98    C
# C.2 26 94    12    C
</code>```

Per @akrun's commented suggestion, here are two external-package suggestions that are a bit shorter.

# 'dplyr'
dplyr::bind_rows(listdat)                      # if no names present
dplyr::bind_rows(listdat, .id = 'name')        # with names
# 'data.table'
data.table::rbindlist(listdat)                 # if no names present
data.table::rbindlist(listdat, idcol = 'name') # with names
```

Title: Combing Dataframes in a list by two columns "i" and "j" to do staistical analysis

Body: I have a List of 366 Dataframes, each DG contains 3 Columns, i.e; "i", "j" and "Value". I want to merge these data frames in a single data frame to do statistical analysis, like mean, mode, median. each list contains almost the same no. observations?

Body:
Base R options:

set.seed(42)
listdat <- replicate(3, data.frame(i=sample(100, size=2), j=sample(100, size=2), Value=sample(100, size=2)), simplify = FALSE)
str(listdat)
# List of 3
#  $ :'data.frame': 2 obs. of  3 variables:
#   ..$ i    : int [1:2] 92 93
#   ..$ j    : int [1:2] 29 83
#   ..$ Value: int [1:2] 65 52
#  $ :'data.frame': 2 obs. of  3 variables:
#   ..$ i    : int [1:2] 74 14
#   ..$ j    : int [1:2] 66 70
#   ..$ Value: int [1:2] 46 72
#  $ :'data.frame': 2 obs. of  3 variables:
#   ..$ i    : int [1:2] 94 26
#   ..$ j    : int [1:2] 47 94
#   ..$ Value: int [1:2] 98 12

Starting with that, the first thing we can do is just combine them row-wise, all in one go:

do.call(rbind, listdat)
#    i  j Value
# 1 92 29    65
# 2 93 83    52
# 3 74 66    46
# 4 14 70    72
# 5 94 47    98
# 6 26 94    12

It might be nice to include which index they came from. If they are not named, then you can just include the index number:

do.call(rbind, Map(cbind, listdat, num=seq_along(listdat)))
#    i  j Value num
# 1 92 29    65   1
# 2 93 83    52   1
# 3 74 66    46   2
# 4 14 70    72   2
# 5 94 47    98   3
# 6 26 94    12   3

If they have names, however, we can use the same technique:

names(listdat) <- c("A","B","C")
do.call(rbind, Map(cbind, listdat, name=names(listdat)))
#      i  j Value name
# A.1 92 29    65    A
# A.2 93 83    52    A
# B.1 74 66    46    B
# B.2 14 70    72    B
# C.1 94 47    98    C
# C.2 26 94    12    C

Per @akrun's commented suggestion, here are two external-package suggestions that are a bit shorter.

# 'dplyr'
dplyr::bind_rows(listdat)                      # if no names present
dplyr::bind_rows(listdat, .id = 'name')        # with names
# 'data.table'
data.table::rbindlist(listdat)                 # if no names present
data.table::rbindlist(listdat, idcol = 'name') # with names