问:
In a csv file get all values of rows and columns between 2 specific words say start and stop
I have a csv file with time,event and acceleration values(x,y,z) as columns and I want to fetch only the values between the event values start and stop(where in event column there are various words like start stop motion location). I have done using data frame in pandas but I get values of start and stop instead of all the values in between them.

Csv file:

```<code> time   event   earthAcceleration.x earthAcceleration.y earthAcceleration.z

2017-11-22T09:20:13.944 motion  -0.006380   -0.001029   -0.010781

2017-11-22T09:20:13.954 start

2017-11-22T09:20:13.964 motion  0.008521    -0.008223   0.022574

2017-11-22T09:20:13.974 stop

2017-11-22T09:20:13.984 motion  0.016283    0.003181    0.006969
</code>```

Code:

```<code>import pandas as pd
df = pd.read_csv('nehi.csv')
df = df[df['event'].between('start', 'stop', inclusive=True)]
df
</code>```

My output is: values where the words = start and stop

```<code>time    event   earthAccelerationx earthAccelerationy earthAccelerationz

2017-11-22T09:20:13.954 start   NaN NaN NaN

2017-11-22T09:20:13.974 stop    NaN NaN NaN
</code>```

Also tried

```<code>start= event[(event['event']=='start') & (event['event']=='stop')]
start.head()
</code>```

But gives empty values

Desired output is: Values of time and acceleration between the words start and stop.

```<code>time       event    earthAccelerationx  earthAccelerationy earthAccelerationz

2017-11-22T09:20:13.964 motion  0.008521    -0.008223   0.022574
</code>```

Goal: To extract all column and row values between 2 keywords in column named events.

答:
You could process the file first to extract the data you want.  This checks for the keywords and uses a flag to toggle keeping or disregarding the data.

csv file:

```<code>import io

s = ''' time   event   earthAcceleration.x earthAcceleration.y earthAcceleration.z
2017-11-22T09:20:13.944 motion  -0.006380   -0.001029   -0.010781
2017-11-22T09:20:13.954 start
2017-11-22T09:20:13.964 motion  0.008521    -0.008223   0.022574
2017-11-22T09:20:13.974 stop
2017-11-22T09:20:13.984 motion  0.016283    0.003181    0.006969
'''
#Python 2.7
f = io.BytesIO(s)
#Python 3.6
#f = io.StringIO(s)
</code>```

Preprocess:

```<code>flag = False
data = []
header = f.next()
#or
#header = f.readline()
header = header.split()
for line in f:
   line = line.split()
   #print(line)
   if line[1] == 'start':
      flag = True
      continue
   elif line[1] == 'stop':
      flag = False
      continue
   if flag:
      data.append(line)
      #print(line)
</code>```

Working with an actual file, use a context manager while processing.

```<code>flag = False
data = []
with open('nehi.txt') as f:
   header = next(f)
   header = header.split()
   for line in f:
      line = line.split()
      #print(line)
      if line[1] == 'start':
         flag = True
         continue
      elif line[1] == 'stop':
         flag = False
         continue
      if flag:
         data.append(line)
         #print(line)
</code>```

Then you could feed data and header to pandas if you need a DataFrame.

```<code>df = pandas.DataFrame(data=data, columns = header)
</code>```

Body:
I have a csv file with time,event and acceleration values(x,y,z) as columns and I want to fetch only the values between the event values start and stop(where in event column there are various words like start stop motion location). I have done using data frame in pandas but I get values of start and stop instead of all the values in between them.

Csv file:

 time   event   earthAcceleration.x earthAcceleration.y earthAcceleration.z

2017-11-22T09:20:13.944 motion  -0.006380   -0.001029   -0.010781

2017-11-22T09:20:13.954 start

2017-11-22T09:20:13.964 motion  0.008521    -0.008223   0.022574

2017-11-22T09:20:13.974 stop

2017-11-22T09:20:13.984 motion  0.016283    0.003181    0.006969

Code:

import pandas as pd
df = pd.read_csv('nehi.csv')
df = df[df['event'].between('start', 'stop', inclusive=True)]
df

My output is: values where the words = start and stop

time    event   earthAccelerationx earthAccelerationy earthAccelerationz

2017-11-22T09:20:13.954 start   NaN NaN NaN

2017-11-22T09:20:13.974 stop    NaN NaN NaN

Also tried

start= event[(event['event']=='start') & (event['event']=='stop')]
start.head()

But gives empty values

Desired output is: Values of time and acceleration between the words start and stop.

time       event    earthAccelerationx  earthAccelerationy earthAccelerationz

2017-11-22T09:20:13.964 motion  0.008521    -0.008223   0.022574

Goal: To extract all column and row values between 2 keywords in column named events.

Body:
You could process the file first to extract the data you want.  This checks for the keywords and uses a flag to toggle keeping or disregarding the data.

csv file:

import io

s = ''' time   event   earthAcceleration.x earthAcceleration.y earthAcceleration.z
2017-11-22T09:20:13.944 motion  -0.006380   -0.001029   -0.010781
2017-11-22T09:20:13.954 start
2017-11-22T09:20:13.964 motion  0.008521    -0.008223   0.022574
2017-11-22T09:20:13.974 stop
2017-11-22T09:20:13.984 motion  0.016283    0.003181    0.006969
'''
#Python 2.7
f = io.BytesIO(s)
#Python 3.6
#f = io.StringIO(s)

Preprocess:

flag = False
data = []
header = f.next()
#or
#header = f.readline()
header = header.split()
for line in f:
   line = line.split()
   #print(line)
   if line[1] == 'start':
      flag = True
      continue
   elif line[1] == 'stop':
      flag = False
      continue
   if flag:
      data.append(line)
      #print(line)

Working with an actual file, use a context manager while processing.

flag = False
data = []
with open('nehi.txt') as f:
   header = next(f)
   header = header.split()
   for line in f:
      line = line.split()
      #print(line)
      if line[1] == 'start':
         flag = True
         continue
      elif line[1] == 'stop':
         flag = False
         continue
      if flag:
         data.append(line)
         #print(line)

Then you could feed data and header to pandas if you need a DataFrame.

df = pandas.DataFrame(data=data, columns = header)


来源: stackexchange

问:
Microsoft Access 2010 Duplicates Error Occurs Too Late
I have a table in Microsoft Access with a field that is set to Indexed = Yes (No Duplicates). The reason was to prevent the same number from being entered more than once for this field. I have an entry form for this table, and the flag works, but not as expected. It doesn't flag the user until they try to close or navigate away from the form. I think it would be much more helpful if the user got an error as soon as they try to leave the field they have entered an invalid value for. Is this possible? I think it will be frustrating for users if errors start popping up once they've finished entering data and I'm not sure if there's a better way to do this.</p>

答:
you can use the field's onExit event to:

Either check if the value is already in present using Dlookup()?

OR try to commit your changes by if me.dirty then me.dirty = false

Eitherway, this is a design issue. You should concider re-designing your table structure. If you provide code, you might get better answer.

ContentLicense: CC BY-SA 3.0


问:
Multiple File Exists Checking? A Better way?
I have a script. It recieves a variable called $node, which is a string; for now, lets assume the variable value is "NODEVALUE". When the script is called, it takes the variable $node, and tries to find an image called NODEVALUE.png. If it cant find that image, it then checks for NODEVALUE.jpg, if it can't find that it looks for NODEVALUE.gif... and after all that, it still cant find, it returns RANDOM.png.

Right now I am doing this script as follows:

```<code>if (file_exists($img = $node.".png")) {  }
else if (file_exists($img = $node.".jpg")) {  }
else if (file_exists($img = $node.".gif")) {  }
else
{
    $img = 'RANDOM.png';
}
</code>```

There has to be a better way than this... anyone have any ideas?

答:
```<code>$n_folder="images/nodes/";
$u_folder="images/users/";
     $extensions=array(".png",".jpg",".gif");

foreach ($extensions as $ext)
{
    if (file_exists($n_folder.$node.$ext))
    {
     $img=$n_folder.$node.$ext;
     break;
    }
    elseif (file_exists($u_folder.$node.$ext))
    {
      $img=$u_folder.$node.$ext;
     break;
    }
}

if (!$img)
{
    random image generator script...
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have a script. It recieves a variable called $node, which is a string; for now, lets assume the variable value is "NODEVALUE". When the script is called, it takes the variable $node, and tries to find an image called NODEVALUE.png. If it cant find that image, it then checks for NODEVALUE.jpg, if it can't find that it looks for NODEVALUE.gif... and after all that, it still cant find, it returns RANDOM.png.

Right now I am doing this script as follows:

if (file_exists($img = $node.".png")) {  }
else if (file_exists($img = $node.".jpg")) {  }
else if (file_exists($img = $node.".gif")) {  }
else
{
    $img = 'RANDOM.png';
}

There has to be a better way than this... anyone have any ideas?


问:
Numpy value error - the truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
Edit: Question updated - I should have asked:

Why is this:

```<code>new_x = x[(0<x<10) & (20<x<40)]
</code>```

giving me "ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()"?

The original question I posted did not reflect the problem I was having (apologies - my actual conditions are more complicated and I had oversimplified it). Original question below:

I have a numpy array x and I want to create a new array of x elements
  satisfying x>0 and x<10. I have tried all the following:

```<code>new_x = x[(x>0) and (x<10)]

new_x = x[(x>0) & (x<10)]

new_x = x[np.logical_and(x>0, x<10)]

new_x = x[np.where(x>0, x<10)]

new_x = x[np.all(x>0, x<10)]

new_x = x[np.all((x>0) and (x<10))]

new_x = x[np.all(x>0) and np.all(x<10)]

new_x = x[np.any(x>0, x<10)]
</code>```

and they all give the following error:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

I have ran out of ideas. I realise this may be a duplicate question
  but I have consulted
  this
  and
  this
  and many others which did not help as I keep getting the same value
  error.

Edit: Fixed typo (x<0 and x>10) --> (x>0 and x<10)

答: Replacing and with & in the first one will do the trick.

Body:
Edit: Question updated - I should have asked:

Why is this:

new_x = x[(0<x<10) & (20<x<40)]

giving me "ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()"?

The original question I posted did not reflect the problem I was having (apologies - my actual conditions are more complicated and I had oversimplified it). Original question below:

I have a numpy array x and I want to create a new array of x elements
  satisfying x>0 and x<10. I have tried all the following:

new_x = x[(x>0) and (x<10)]

new_x = x[(x>0) & (x<10)]

new_x = x[np.logical_and(x>0, x<10)]

new_x = x[np.where(x>0, x<10)]

new_x = x[np.all(x>0, x<10)]

new_x = x[np.all((x>0) and (x<10))]

new_x = x[np.all(x>0) and np.all(x<10)]

new_x = x[np.any(x>0, x<10)]

and they all give the following error:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

I have ran out of ideas. I realise this may be a duplicate question
  but I have consulted
  this
  and
  this
  and many others which did not help as I keep getting the same value
  error.

Edit: Fixed typo (x<0 and x>10) --> (x>0 and x<10)


问:
TimeStamp / Rowversion column with EF Core
I am trying to figure out how I should add a Timestamp/rowversion column to data tables in SQL Server via Entity Framework code first.

This is using EF Core V2.0.

I have tried two approaches to achieve this, the first:

```<code>public class Contact
{
    public int ContactId { get; set; }
    public string ContactName { get; set; }
    public string CompanyName { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    [Timestamp]
    public byte[] RowVersion { get; set; }
}
</code>```

The second via the fluent API:

```<code>protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    foreach (var entityType in modelBuilder.Model.GetEntityTypes())
    {
        modelBuilder.Entity(entityType.Name).Property<DateTime>("Inserted");
        modelBuilder.Entity(entityType.Name).Property<DateTime>("LastModified");
        modelBuilder.Entity(entityType.Name).Property<byte[]>  ("RowVersion");
    }
}
</code>```

In both cases after I run Add-Migration, I get the following:

```<code>protected override void Up(MigrationBuilder migrationBuilder)
{
    migrationBuilder.CreateTable(
        name: "Contacts",
        columns: table => new
        {
            ContactId    = table.Column<int>(type: "int", nullable: false)
                .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
            CompanyName  = table.Column<string>  (type: "nvarchar(max)", nullable: true),
            ContactName  = table.Column<string>  (type: "nvarchar(max)", nullable: true),
            FirstName    = table.Column<string>  (type: "nvarchar(max)", nullable: true),
            Inserted     = table.Column<DateTime>(type: "datetime2", nullable: false),
            LastModified = table.Column<DateTime>(type: "datetime2", nullable: false),
            LastName     = table.Column<string>  (type: "nvarchar(max)", nullable: true),
            RowVersion   = table.Column<byte[]>  (type: "varbinary(max)", nullable: true)
        },
        constraints: table =>
        {
            table.PrimaryKey("PK_Contacts", x => x.ContactId);
        }
    );
}
</code>```

I would have expected the RowVersion column to be of type timestamp and for its nullable property to be false.  Is this a limitation of EF Core or am I trying to do this incorrectly?

答:
```<code>protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);

    modelBuilder.Entity<MyEntity>()
      .Property(b => b.MyVersionProperty)
      .IsRowVersion();
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to figure out how I should add a Timestamp/rowversion column to data tables in SQL Server via Entity Framework code first.

This is using EF Core V2.0.

I have tried two approaches to achieve this, the first:

public class Contact
{
    public int ContactId { get; set; }
    public string ContactName { get; set; }
    public string CompanyName { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    [Timestamp]
    public byte[] RowVersion { get; set; }
}

The second via the fluent API:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    foreach (var entityType in modelBuilder.Model.GetEntityTypes())
    {
        modelBuilder.Entity(entityType.Name).Property<DateTime>("Inserted");
        modelBuilder.Entity(entityType.Name).Property<DateTime>("LastModified");
        modelBuilder.Entity(entityType.Name).Property<byte[]>  ("RowVersion");
    }
}

In both cases after I run Add-Migration, I get the following:

protected override void Up(MigrationBuilder migrationBuilder)
{
    migrationBuilder.CreateTable(
        name: "Contacts",
        columns: table => new
        {
            ContactId    = table.Column<int>(type: "int", nullable: false)
                .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
            CompanyName  = table.Column<string>  (type: "nvarchar(max)", nullable: true),
            ContactName  = table.Column<string>  (type: "nvarchar(max)", nullable: true),
            FirstName    = table.Column<string>  (type: "nvarchar(max)", nullable: true),
            Inserted     = table.Column<DateTime>(type: "datetime2", nullable: false),
            LastModified = table.Column<DateTime>(type: "datetime2", nullable: false),
            LastName     = table.Column<string>  (type: "nvarchar(max)", nullable: true),
            RowVersion   = table.Column<byte[]>  (type: "varbinary(max)", nullable: true)
        },
        constraints: table =>
        {
            table.PrimaryKey("PK_Contacts", x => x.ContactId);
        }
    );
}

I would have expected the RowVersion column to be of type timestamp and for its nullable property to be false.  Is this a limitation of EF Core or am I trying to do this incorrectly?


问:
CSS: Make it possible that element only have differnent :hover background after clicking (:active) on it
Hi there I try to make it possible that you first need to click on the element and after that it should chang the background everytime you hover over it. Important is that No JavaScript or JQuery should be used. It's not a link so :visited and href is not an option

```<code>*Pseudocode*

 *if* .lst-c:active *than* .lst-c:hover   {
       background: blue;
       border-radius: 20px 20px 0px 0px !important;
       }
</code>```

答:
You can try the Checkbox Hack

http://timpietrusky.com/advanced-checkbox-hack

input[type=checkbox] {
  position: absolute;
  top: -9999px;
  left: -9999px;
}

div {
  background: green;
}

input[type=checkbox]:checked ~ div:hover {
  background: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><label for="toggle-1">Do Something</label>
<input type="checkbox" id="toggle-1">
<div>Control me</div></code>```

Body:
Hi there I try to make it possible that you first need to click on the element and after that it should chang the background everytime you hover over it. Important is that No JavaScript or JQuery should be used. It's not a link so :visited and href is not an option

*Pseudocode*

 *if* .lst-c:active *than* .lst-c:hover   {
       background: blue;
       border-radius: 20px 20px 0px 0px !important;
       }

Body:
You can try the Checkbox Hack

http://timpietrusky.com/advanced-checkbox-hack

input[type=checkbox] {
  position: absolute;
  top: -9999px;
  left: -9999px;
}

div {
  background: green;
}

input[type=checkbox]:checked ~ div:hover {
  background: red;
}

<label for="toggle-1">Do Something</label>
<input type="checkbox" id="toggle-1">
<div>Control me</div>


问:
Select submit button after form submit in jQuery
I have the following form:

```<code><form id="save-form-datas">
    <input type="text" name="name">
    <input type="text" name="address">
    <button type="submit">Submit</button>
</form>
</code>```

How can I select my button to get the text Submit if I have the following JS code:

```<code>$('#save-form-datas').on('submit', function (e) {
    ...
}
</code>```

I do not want to add id or class in my HTML code.

Thanks.

答:
since its a button tag you should use .html() or .text() to get the text or html inside it rather than .value()

$('.save-form-datas').on('submit', function(e) {
  console.log($(this).find('button').text());
  e.preventDefault();
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="save-form-datas">
  <input type="text" name="name">
  <input type="text" name="address">
  <button type="submit">Submit</button>
</form>
<form class="save-form-datas">
  <input type="text" name="name">
  <input type="text" name="address">
  <button type="submit">Submit2</button>
</form>
<form class="save-form-datas">
  <input type="text" name="name">
  <input type="text" name="address">
  <button type="submit">Submit3</button>
</form>
<form class="save-form-datas">
  <input type="text" name="name">
  <input type="text" name="address">
  <button type="submit">Submit4</button>
</form></code>```

Body:
I have the following form:

<form id="save-form-datas">
    <input type="text" name="name">
    <input type="text" name="address">
    <button type="submit">Submit</button>
</form>

How can I select my button to get the text Submit if I have the following JS code:

$('#save-form-datas').on('submit', function (e) {
    ...
}

I do not want to add id or class in my HTML code.

Thanks.

Body:
since its a button tag you should use .html() or .text() to get the text or html inside it rather than .value()

$('.save-form-datas').on('submit', function(e) {
  console.log($(this).find('button').text());
  e.preventDefault();
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="save-form-datas">
  <input type="text" name="name">
  <input type="text" name="address">
  <button type="submit">Submit</button>
</form>
<form class="save-form-datas">
  <input type="text" name="name">
  <input type="text" name="address">
  <button type="submit">Submit2</button>
</form>
<form class="save-form-datas">
  <input type="text" name="name">
  <input type="text" name="address">
  <button type="submit">Submit3</button>
</form>
<form class="save-form-datas">
  <input type="text" name="name">
  <input type="text" name="address">
  <button type="submit">Submit4</button>
</form>


问:
PHP Search string in multiple files pdf and get name this files
I have write script to the search string in pdf files. I used script from this link:  link.
I have problem, because my script not search in all files pdf, only search in first file (sorted by name)

My script:

```<code>foreach (glob("storage/cvs/*.pdf") as $file) {
    // $files = 'storage/cvs/d08540965a_2017-12-06.pdf';
    $this->pdf2text->setFilename($file);
    $this->pdf2text->decodePDF();
    $convert2Txt = $this->pdf2text->output();

    if (stripos($convert2Txt, $query) !== false) {
        echo $resultQuery =  "tak ".$file."</br>";
    } else {
        echo $resultQuery =  "nie znaleziono ".$file."</br>";
    }

}
</code>```

And I don't know how I can get name files where found string.

答:
This is how I do it:

```<code>$dir = "/path/to/your/directory/"; // Set your directory path here
if (is_dir($dir)){                // Check its a directory
    if ($dh = opendir($dir)){     // Open the directory
        while (($file = readdir($dh)) !== false){  // Read the files
            if (substr($file, -3)=='pdf') {  // Check filename ends 'pdf'
              // Your code here
</code>```

$file will be set as the filename

Body:
I have write script to the search string in pdf files. I used script from this link:  link.
I have problem, because my script not search in all files pdf, only search in first file (sorted by name)

My script:

foreach (glob("storage/cvs/*.pdf") as $file) {
    // $files = 'storage/cvs/d08540965a_2017-12-06.pdf';
    $this->pdf2text->setFilename($file);
    $this->pdf2text->decodePDF();
    $convert2Txt = $this->pdf2text->output();

    if (stripos($convert2Txt, $query) !== false) {
        echo $resultQuery =  "tak ".$file."
";
    } else {
        echo $resultQuery =  "nie znaleziono ".$file."
";
    }

}

And I don't know how I can get name files where found string.

Body:
This is how I do it:

$dir = "/path/to/your/directory/"; // Set your directory path here
if (is_dir($dir)){                // Check its a directory
    if ($dh = opendir($dir)){     // Open the directory
        while (($file = readdir($dh)) !== false){  // Read the files
            if (substr($file, -3)=='pdf') {  // Check filename ends 'pdf'
              // Your code here

$file will be set as the filename


问:
SuperLearner Predict error
I am using SuperLearner R package.
I am trying to generate predicted y values for both train and test set.

After fitting a superlearner model without defining a "newX" to get predictions on the train set first so that I can compute MSE and plot predictions vs. actual Y values, I use "predict" command to predict Y values for the test set by running the following code:

```<code>sl.cv<-SuperLearner(Y = label, X = train,
                 SL.library=c("SL.randomForest", "SL.glmnet", "SL.svm"),
                 method = "method.NNLS", verbose=TRUE, cvControl=list(V=10))

pred.sl.cv <- predict(sl.cv, newdata=test, onlySL = T)
</code>```

Then, I get the following error after "predict":
"Error in object$whichScreen : $ operator is invalid for atomic vectors"

I browsed many online sources to learn how to use "predict" after fitting a SuperLearner model, and I am doing just as what others do: That is, to put the object name of the fitted SuperLearner model (in this case, "sl.cv") followed by the new test set. I didn't even type $ operator.

Why am I getting this error message? How do I solve this problem?

Another question is: Does adding cvControl=list(V=10) as an option make any change? I think the default setting for SuperLearner model is to conduct 10-fold cross-validation. So, removing "cvControl=list(V=10)" will not change anything, right?

I would appreciate your advice. Thank you!

答:
The problem is you are using matrices for your train and/or test data. You should use a data.frame. So change your code to the following:

```<code>sl.cv<-SuperLearner(Y = label, X = as.data.frame(train),
                 SL.library=c("SL.randomForest", "SL.glmnet", "SL.svm"),
                 method = "method.NNLS", verbose=TRUE, cvControl=list(V=10))

pred.sl.cv <- predict(sl.cv, newdata=as.data.frame(test), onlySL = T)
</code>```

Also, make sure your labels are a list.

Title: SuperLearner Predict error

Body:
I am using SuperLearner R package.
I am trying to generate predicted y values for both train and test set.

After fitting a superlearner model without defining a "newX" to get predictions on the train set first so that I can compute MSE and plot predictions vs. actual Y values, I use "predict" command to predict Y values for the test set by running the following code:

sl.cv<-SuperLearner(Y = label, X = train,
                 SL.library=c("SL.randomForest", "SL.glmnet", "SL.svm"),
                 method = "method.NNLS", verbose=TRUE, cvControl=list(V=10))

pred.sl.cv <- predict(sl.cv, newdata=test, onlySL = T)

Then, I get the following error after "predict":
"Error in object$whichScreen : $ operator is invalid for atomic vectors"

I browsed many online sources to learn how to use "predict" after fitting a SuperLearner model, and I am doing just as what others do: That is, to put the object name of the fitted SuperLearner model (in this case, "sl.cv") followed by the new test set. I didn't even type $ operator.

Why am I getting this error message? How do I solve this problem?

Another question is: Does adding cvControl=list(V=10) as an option make any change? I think the default setting for SuperLearner model is to conduct 10-fold cross-validation. So, removing "cvControl=list(V=10)" will not change anything, right?

I would appreciate your advice. Thank you!

Body:
The problem is you are using matrices for your train and/or test data. You should use a data.frame. So change your code to the following:

sl.cv<-SuperLearner(Y = label, X = as.data.frame(train),
                 SL.library=c("SL.randomForest", "SL.glmnet", "SL.svm"),
                 method = "method.NNLS", verbose=TRUE, cvControl=list(V=10))

pred.sl.cv <- predict(sl.cv, newdata=as.data.frame(test), onlySL = T)

Also, make sure your labels are a list.


问:
jQuery: hide element after it has been shown?
I have this strange scenario that I cannot understand.

Basically, I show an element using jquery show(); which works fine.

But I need to hide() the same element using the hide(); function but the element stays visible and the hide() doesn't work.

Can someone please advice on this?

Here is a working FIDDLE.

This is my code:

```<code>$(document).on('click','.buildExMain', function(e){
$(this).children('.buildExDrop').show();
});

$(document).on('click','.pSelection', function(e){

$('.buildExDrop').hide();
});
</code>```

答:
@billyonecan was spot on, adding e.stopPropagation(); after your $('.buildExDrop').hide(); fixes this.

This allows the hide click event for the sub-elements .pSelection to not bubble up to the show click event of the .buildExDrop element.

Body:
I have this strange scenario that I cannot understand.

Basically, I show an element using jquery show(); which works fine.

But I need to hide() the same element using the hide(); function but the element stays visible and the hide() doesn't work.

Can someone please advice on this?

Here is a working FIDDLE.

This is my code:

$(document).on('click','.buildExMain', function(e){
$(this).children('.buildExDrop').show();
});

$(document).on('click','.pSelection', function(e){

$('.buildExDrop').hide();
});


答:
Your click to hide also triggers the click to show. this works</p>

```<code>$(function(){
$(document).on('click','.buildExMain span', function(e){
$('.buildExDrop').show();
});

$(".buildExMain").on('click','.pSelection', function(){
$('.buildExDrop').hide();
});
});
</code>```

Title: jQuery: hide element after it has been shown?

Body:
Your click to hide also triggers the click to show. this works

$(function(){
$(document).on('click','.buildExMain span', function(e){
$('.buildExDrop').show();
});

$(".buildExMain").on('click','.pSelection', function(){
$('.buildExDrop').hide();
});
});


问:
Is it possible to check he bitrate of a twilio video stream?
I am developing a video chat application using twilio. I would like to check the bitrate of a video stream playing in the browser to study how the bitrate will be affected at different bandwidths. How can I do this?</p>

答:
Many videos actually will have variable bit rate, so you can either get an average by simply dividing the file size by the time, or alternatively use a tool like VLC player which will show you the bit rate changing over time (on a Mac it shows the numbers but I believe on Windows it shows a graph):

If you are more interested in the download bandwidth itself, you can use developer tools in Chrome to see the bit rate.

If you open developer tools and go to the network tab you should see a waterfall column.

Hover over the timeline here in a row that corresponds to your video download and you can see all the details about the request and response including the time it took. The time combined with the size which is also in the row will show you the actual achieved download bit rate.

Here is an example for a YouTube video:


问:
Service worker and Django
I create a project in Django and I want add a service worker that will be redirect to another page (normal html without django tags )  in the absence of a connection.
How can i do this?

Sorry for my english.

答:
Open the source code of your HTML web page. And copy it in a file inside your static folder.

Make sure you have STATIC_URL in your settings.py enabled and is available through the address.

Then in your service-worker.js add:

```<code>var filesToCache = ['desired_HTML_page.html']
</code>```

Afterwards make the corresponding install and fetch events.

Title: Service worker and Django

Body:
Open the source code of your HTML web page. And copy it in a file inside your static folder.

Make sure you have STATIC_URL in your settings.py enabled and is available through the address.

Then in your service-worker.js add:

var filesToCache = ['desired_HTML_page.html']

Afterwards make the corresponding install and fetch events.


问:
How to mutate() a list of columns using map2() in dplyr

I recently had to compile a data frame of student scores (one row per student, id column and several integer-valued columns, one per score component). I had to combine a "master" data frame and several "correction" data frames (containing mostly NA and some updates to the master), so that the result contains the maximum values from the master, and all corrections.

I succeeded by copy-pasting a sequence of mutate() calls, which works (see example below), but is not elegant in my opinion. What I would have wanted to do, was instead of copying and pasting, to use something along the lines of map2 and two lists of columns to compare the columns pair-wise. Something like (which obviously does not work as such):

```<code>list_of_cols1 <- list(col1.x, col2.x, col3.x)
list_of_cols2 <- list(col1.y, col2.y, col3.y
map2(list_of_cols1, list_of_cols2, ~ column = pmax(.x, .y, na.rm=T))
</code>```

I can't seem to be able to figure out to do it. My question is: how to specify such lists of columns and mutate them in one map2() call in dplyr pipe, or is it even possible – have I gotten it all wrong?

Minimum working example

```<code>library(tidyverse)

master <- tibble(
  id=c(1,2,3),
  col1=c(1,1,1),
  col2=c(2,2,2),
  col3=c(3,3,3)
)
correction1 <- tibble(
  id=seq(1,3),
  col1=c(NA, NA, 2 ),
  col2=c( 1, NA, 3 ),
  col3=c(NA, NA, NA)
)

result <- reduce(
  # Ultimately there would several correction data frames
  list(master, correction1),
  function(x,y) {
    x <- x %>%
      left_join(
        y,
        by = c("id")
      ) %>%
      # Wish I knew how to do this mutate call with map2
      mutate(
        col1 = pmax(col1.x, col1.y, na.rm=T),
        col2 = pmax(col2.x, col2.y, na.rm=T),
        col3 = pmax(col3.x, col3.y, na.rm=T)
      ) %>%
      select(id, col1:col3)
  }
)
</code>```

The result is

```<code>> result
# A tibble: 3 x 4
     id  col1  col2  col3
  <int> <dbl> <dbl> <dbl>
1     1     1     2     3
2     2     1     2     3
3     3     2     3     3
</code>```

答:
Rather than do a left_join, just bind the rows then summarize. For example

```<code>result <- reduce(
  list(master, master),
  function(x,y) {
    bind_rows(x, y) %>%
      group_by(id) %>%
      summarize_all(max, na.rm=T)
  }
)
result
#     id  col1  col2  col3
#   <dbl> <dbl> <dbl> <dbl>
# 1     1     1     2     3
# 2     2     1     2     3
# 3     3     2     3     3
</code>```

Actually, you don't even need reduce as bind_rows can take a list

Adding another table

```<code>correction2 <- tibble(id=2,col1=NA,col2=8,col3=NA)
bind_rows(master, correction1, correction2) %>%
  group_by(id) %>%
  summarize_all(max, na.rm=T)
</code>```

Body:
I recently had to compile a data frame of student scores (one row per student, id column and several integer-valued columns, one per score component). I had to combine a "master" data frame and several "correction" data frames (containing mostly NA and some updates to the master), so that the result contains the maximum values from the master, and all corrections.

I succeeded by copy-pasting a sequence of mutate() calls, which works (see example below), but is not elegant in my opinion. What I would have wanted to do, was instead of copying and pasting, to use something along the lines of map2 and two lists of columns to compare the columns pair-wise. Something like (which obviously does not work as such):

list_of_cols1 <- list(col1.x, col2.x, col3.x)
list_of_cols2 <- list(col1.y, col2.y, col3.y
map2(list_of_cols1, list_of_cols2, ~ column = pmax(.x, .y, na.rm=T))

I can't seem to be able to figure out to do it. My question is: how to specify such lists of columns and mutate them in one map2() call in dplyr pipe, or is it even possible – have I gotten it all wrong?

Minimum working example

library(tidyverse)

master <- tibble(
  id=c(1,2,3),
  col1=c(1,1,1),
  col2=c(2,2,2),
  col3=c(3,3,3)
)
correction1 <- tibble(
  id=seq(1,3),
  col1=c(NA, NA, 2 ),
  col2=c( 1, NA, 3 ),
  col3=c(NA, NA, NA)
)

result <- reduce(
  # Ultimately there would several correction data frames
  list(master, correction1),
  function(x,y) {
    x <- x %>%
      left_join(
        y,
        by = c("id")
      ) %>%
      # Wish I knew how to do this mutate call with map2
      mutate(
        col1 = pmax(col1.x, col1.y, na.rm=T),
        col2 = pmax(col2.x, col2.y, na.rm=T),
        col3 = pmax(col3.x, col3.y, na.rm=T)
      ) %>%
      select(id, col1:col3)
  }
)

The result is

> result
# A tibble: 3 x 4
     id  col1  col2  col3
  <int> <dbl> <dbl> <dbl>
1     1     1     2     3
2     2     1     2     3
3     3     2     3     3

Body:
Rather than do a left_join, just bind the rows then summarize. For example

result <- reduce(
  list(master, master),
  function(x,y) {
    bind_rows(x, y) %>%
      group_by(id) %>%
      summarize_all(max, na.rm=T)
  }
)
result
#     id  col1  col2  col3
#   <dbl> <dbl> <dbl> <dbl>
# 1     1     1     2     3
# 2     2     1     2     3
# 3     3     2     3     3

Actually, you don't even need reduce as bind_rows can take a list

Adding another table

correction2 <- tibble(id=2,col1=NA,col2=8,col3=NA)
bind_rows(master, correction1, correction2) %>%
  group_by(id) %>%
  summarize_all(max, na.rm=T)


问:
Get objects using reference in function desynchronization
I would like to get Comments from RealTime Database. i did accomplished the task but Objects will display only after comeback to page(not refresh).

default angularfire2 constuctor inside blog.service.ts

```<code>constructor(public afDb: AngularFireDatabase) {}
</code>```

My function to get comments out of DB. This is just one of many functions, I have no idea how to get reference or objects in one procedure, co i came up with function like this.

```<code>getComments(blogTitle: string) {
    const blogsRef = this.afDb.database.ref('blog-pl');
    let commentsRef = null;
    blogsRef.orderByChild('title').equalTo(blogTitle).on("child_added", function (snapshot) {
      if (snapshot.hasChild('comments')) {
        commentsRef = snapshot.child('comments').ref;
      }
    });
    return this.afDb.list<Comment>(commentsRef, ref =>
      ref.orderByChild('timestamp')
    ).valueChanges();
  }
</code>```

Of course i want get Observable Comment[], but instead i get null. Problem is that commentsRef cant get in

```<code>this.afDb.list<Comment>(commentsRef,...
</code>```

before it returns values. I've tried return it inside function where i assign reference to commentsRef. But it calls
Error:(56, 9) TS2347:Untyped function calls may not accept type arguments.
Which I am not able to resolve.

trying to get it in comments.component.ts

```<code>public currentComments: Observable<Comment[]>;

constructor(private blogService: BlogService, private authServicec: AuthService) {}

ngOnInit(): void {
    this.currentComments = this.blogService.getComments(this.blogTitle);
    this.currentComments.subscribe(val => {
      if (val.length != 0) {
        this.areAnyComms = true;
      }})
  }
</code>```

Displaying it in html using

```<code><ul *ngFor="let curUserReview of (currentUsersReviews | async)?.slice().reverse()">
</code>```

Waiting for your advices and thanks for your answers.

答:
You should put it inside your first get, because data comes asynchronous. Try</p>

```<code>getComments(blogTitle: string) {
const blogsRef = this.afDb.database.ref('blog-pl');
let commentsRef = null;
return blogsRef.orderByChild('title').equalTo(blogTitle).on("child_added", function (snapshot) {
  if (snapshot.hasChild('comments')) {
    commentsRef = snapshot.child('comments').ref;
    return this.afDb.list<Comment>(commentsRef, ref =>
      ref.orderByChild('timestamp')
    ).valueChanges();
  }
});
}
</code>```

Body:
I would like to get Comments from RealTime Database. i did accomplished the task but Objects will display only after comeback to page(not refresh).

default angularfire2 constuctor inside blog.service.ts

constructor(public afDb: AngularFireDatabase) {}

My function to get comments out of DB. This is just one of many functions, I have no idea how to get reference or objects in one procedure, co i came up with function like this.

getComments(blogTitle: string) {
    const blogsRef = this.afDb.database.ref('blog-pl');
    let commentsRef = null;
    blogsRef.orderByChild('title').equalTo(blogTitle).on("child_added", function (snapshot) {
      if (snapshot.hasChild('comments')) {
        commentsRef = snapshot.child('comments').ref;
      }
    });
    return this.afDb.list<Comment>(commentsRef, ref =>
      ref.orderByChild('timestamp')
    ).valueChanges();
  }

Of course i want get Observable Comment[], but instead i get null. Problem is that commentsRef cant get in

this.afDb.list<Comment>(commentsRef,...

before it returns values. I've tried return it inside function where i assign reference to commentsRef. But it calls
Error:(56, 9) TS2347:Untyped function calls may not accept type arguments.
Which I am not able to resolve.

trying to get it in comments.component.ts

public currentComments: Observable<Comment[]>;

constructor(private blogService: BlogService, private authServicec: AuthService) {}

ngOnInit(): void {
    this.currentComments = this.blogService.getComments(this.blogTitle);
    this.currentComments.subscribe(val => {
      if (val.length != 0) {
        this.areAnyComms = true;
      }})
  }

Displaying it in html using

Waiting for your advices and thanks for your answers.

Body:
You should put it inside your first get, because data comes asynchronous. Try

getComments(blogTitle: string) {
const blogsRef = this.afDb.database.ref('blog-pl');
let commentsRef = null;
return blogsRef.orderByChild('title').equalTo(blogTitle).on("child_added", function (snapshot) {
  if (snapshot.hasChild('comments')) {
    commentsRef = snapshot.child('comments').ref;
    return this.afDb.list<Comment>(commentsRef, ref =>
      ref.orderByChild('timestamp')
    ).valueChanges();
  }
});
}


问:
AngularDart - Way to aggregate statically defined child component with dynamic once

I would like to aggregate statically defined child components with dynamical once that might be sourced from the stream. I want a generic way to define carousel in this carousel where I can have a typed collection of components. The collection can be defined statically or dynamically. Below is an example:

```<code>import 'package:angular/angular.dart';
import 'package:angular/core.dart';
import 'package:angular_components/angular_components.dart';

/**
 *
 */
@Component(
    selector: 'md-text',
    styleUrls: const ['md_text.css'],
    template: '<li>{{name}}</li>',
    directives: const [
      materialDirectives,
    ]
)
class TextComponent implements OnInit{
  @Input()
  String name;

  TextComponent([this.name]);

  TextComponent.withName(String name)
      : this(name);

  @override
  ngOnInit() {
  }
}

@Component(
    selector: 'md-texts',
    styleUrls: const ['text_component.css'],
    template: '<ol><md-text *ngFor="let component of components" [name]="component.name"></md-text><ng-content></ng-content></ol>',
    directives: const [
      CORE_DIRECTIVES,
      materialDirectives,
      TextComponent
    ]
)
class TextsComponent<TextComponent> implements OnInit
{
  Set<T> _components;

  Set<T> get components => _components;

  addComponent(T component){
    this._components.add(component);
  }

  removeComponent(T component) {
    this._components.remove(component);
  }

  TextsComponent() {
    this._components = new LinkedHashSet<T>();
    TextComponent declarativeChannel = new TextComponent.withName("United States");
    this.addComponent(declarativeChannel);
  }

  @override
  ngOnInit(){
    print("I am here");
  }
}
</code>```

in my dashboard component, I have statically defined the usage as follows:

```<code><md-texts>
    <md-text [name]="'Liberty'"></md-text>
    <md-text [name]="'Life'"></md-text>
<md-texts>
</code>```

The display is as following
United States
Liberty
Life

What I want to do is have the "Liberty" and "Life" also be aggregated to my component collection, so I can control it with the next and previous button. I also only want to render them when their index is called for.  What is the best way to do this in AngularDart.

I found a similar question with old version but with older version How to reference child component from its parent in AngularDart in AD 1.0.0 and How to reference child component from its parent in AngularDart in AD 1.0.0

Regards,  Hopefully i have explained my problem and i will get clear direction on what is the correct way of addressing this design issue.

答:
You can use @ViewChildren and @ContentChildren to query for child components. @ViewChildren will query for components declared in your template, whereas @ContentChildren will query for components projected into an <ng-content> in your template.

It's worth mentioning that in your example, your dynamic TextComponent is being created twice. First, you create one in your constructor, then again when you declare a <md-text> in your template. This means the instance you're keeping a reference to, isn't actually the component rendered in your view. To avoid this, don't bother creating the instance imperatively. Just keep a model of the data needed to create them, then pass that through inputs in your template where you declare the components. You can then use @ViewChildren to query for those components you've created.

Here's an example

```<code>@Component(
  selector: 'md-texts',
  template: '''
    <ol>
      <md-text *ngFor="let text of texts" [text]="text"></md-text>
      <ng-content></ng-content>
    </ol>
  ''',
  directives: const [NgFor, TextComponent],
)
class TextsComponent {
  /// Text that was projected through `<ng-content>`.
  @ContentChildren(TextComponent)
  QueryList<TextComponent> contentTexts;

  /// Text that was created in our view from our model.
  @ViewChildren(TextComponent)
  QueryList<TextComponent> viewTexts;

  /// Data model for the text in our view.
  final List<String> texts = [
    ...
  ];
}
</code>```

Alternatively, you could render all of the <md-text> from a single source of data in your view, and rely on passing in a model for the static data rather than projecting the components.

Body:
I would like to aggregate statically defined child components with dynamical once that might be sourced from the stream. I want a generic way to define carousel in this carousel where I can have a typed collection of components. The collection can be defined statically or dynamically. Below is an example:

import 'package:angular/angular.dart';
import 'package:angular/core.dart';
import 'package:angular_components/angular_components.dart';

/**
 *
 */
@Component(
    selector: 'md-text',
    styleUrls: const ['md_text.css'],
    template: '
{{name}}
',
    directives: const [
      materialDirectives,
    ]
)
class TextComponent implements OnInit{
  @Input()
  String name;

  TextComponent([this.name]);

  TextComponent.withName(String name)
      : this(name);

  @override
  ngOnInit() {
  }
}

@Component(
    selector: 'md-texts',
    styleUrls: const ['text_component.css'],
    template: '
<md-text *ngFor="let component of components" [name]="component.name"></md-text><ng-content></ng-content>
',
    directives: const [
      CORE_DIRECTIVES,
      materialDirectives,
      TextComponent
    ]
)
class TextsComponent<TextComponent> implements OnInit
{
  Set<T> _components;

  Set<T> get components => _components;

  addComponent(T component){
    this._components.add(component);
  }

  removeComponent(T component) {
    this._components.remove(component);
  }

  TextsComponent() {
    this._components = new LinkedHashSet<T>();
    TextComponent declarativeChannel = new TextComponent.withName("United States");
    this.addComponent(declarativeChannel);
  }

  @override
  ngOnInit(){
    print("I am here");
  }
}

in my dashboard component, I have statically defined the usage as follows:

<md-texts>
    <md-text [name]="'Liberty'"></md-text>
    <md-text [name]="'Life'"></md-text>
<md-texts>

The display is as following
United States
Liberty
Life

What I want to do is have the "Liberty" and "Life" also be aggregated to my component collection, so I can control it with the next and previous button. I also only want to render them when their index is called for.  What is the best way to do this in AngularDart.

I found a similar question with old version but with older version How to reference child component from its parent in AngularDart in AD 1.0.0 and How to reference child component from its parent in AngularDart in AD 1.0.0

Regards,  Hopefully i have explained my problem and i will get clear direction on what is the correct way of addressing this design issue.

Body:
You can use @ViewChildren and @ContentChildren to query for child components. @ViewChildren will query for components declared in your template, whereas @ContentChildren will query for components projected into an <ng-content> in your template.

It's worth mentioning that in your example, your dynamic TextComponent is being created twice. First, you create one in your constructor, then again when you declare a <md-text> in your template. This means the instance you're keeping a reference to, isn't actually the component rendered in your view. To avoid this, don't bother creating the instance imperatively. Just keep a model of the data needed to create them, then pass that through inputs in your template where you declare the components. You can then use @ViewChildren to query for those components you've created.

Here's an example

@Component(
  selector: 'md-texts',
  template: '''
    <ol>
      <md-text *ngFor="let text of texts" [text]="text"></md-text>
      <ng-content></ng-content>
    </ol>
  ''',
  directives: const [NgFor, TextComponent],
)
class TextsComponent {
  /// Text that was projected through `<ng-content>`.
  @ContentChildren(TextComponent)
  QueryList<TextComponent> contentTexts;

  /// Text that was created in our view from our model.
  @ViewChildren(TextComponent)
  QueryList<TextComponent> viewTexts;

  /// Data model for the text in our view.
  final List<String> texts = [
    ...
  ];
}

Alternatively, you could render all of the <md-text> from a single source of data in your view, and rely on passing in a model for the static data rather than projecting the components.


问:
Peewee error on model.create() [ Proxy ]

Hello.
When i'm trying to create new record in model, i'm getting

AttributeError: 'dict' object has no attribute 'compiler'

Possible, that i'm getting this error because using Proxy class, but can't find mistake in my code.

init.py

```<code>from flask import Flask
from flask_peewee.db import Proxy
from flask_bootstrap import Bootstrap

from app.config import config_select

db = Proxy()
bootstrap = Bootstrap()

def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config_select[config_name])
    config_select[config_name].init_app(app)

    db.initialize(config_select[config_name].DATABASE)
    bootstrap.init_app(app)

    #register blueprints
    from app.blueprint.main import main_bp as main_blueprint

    app.register_blueprint(main_blueprint)

    return app
</code>```

models.py

```<code>from peewee import *

from app import db

class BaseModel(Model):
    class Meta:
        database = db

class User(BaseModel):
    id = PrimaryKeyField()
    username = CharField(default='test', max_length=20)

    class Meta:
        db_table = 'users'

MODELS_LIST = [User]
</code>```

Database was created by manager  'generate_db_tables' command

```<code>import os
from app import create_app

from flask_script import Manager, Shell

app = create_app(os.getenv('FLASK_CONFIG') or 'default')
manager = Manager(app)

def connect_db():
    from peewee import SqliteDatabase
    db_lite = SqliteDatabase(app.config['DATABASE']['name'])
    return db_lite

@manager.command
def generate_db_tables():
    from app.models.models import MODELS_LIST
    db_lite = connect_db()
    for model in MODELS_LIST:
        db_lite.create_table(model, safe=True)
    print("Db tables created")
</code>```

and the view function:

```<code>from flask import render_template, session, \
    redirect, url_for, current_app, flash, request, make_response

from . import main_bp
from .forms import NameForm
from app.models.models import User

@main_bp.route('/', methods=['GET', 'POST'])
def index():
    form = NameForm()
    if form.validate_on_submit():
        User.create(username=form.name.data) # <<<< Here is error
        return url_for('.index')
    return render_template('index.html', form=form)
</code>```

Before i started to use Proxy class everything worked like a charm.

答:
Seems, that i pass dict

```<code>DATABASE = {
    'name': 'test.db',
    'engine': 'peewee.SqliteDatabase'
}
</code>```

to db.initialize()

instead of string name of database

```<code>DATABASE_INFO = 'test.db'
DATABASE = peewee.SqliteDatabase(DATABASE_INFO)
db.initialize(DATABASE)
</code>```

Body:
Hello.
When i'm trying to create new record in model, i'm getting

AttributeError: 'dict' object has no attribute 'compiler'

Possible, that i'm getting this error because using Proxy class, but can't find mistake in my code.

init.py

from flask import Flask
from flask_peewee.db import Proxy
from flask_bootstrap import Bootstrap

from app.config import config_select

db = Proxy()
bootstrap = Bootstrap()

def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config_select[config_name])
    config_select[config_name].init_app(app)

    db.initialize(config_select[config_name].DATABASE)
    bootstrap.init_app(app)

    #register blueprints
    from app.blueprint.main import main_bp as main_blueprint

    app.register_blueprint(main_blueprint)

    return app

models.py

from peewee import *

from app import db

class BaseModel(Model):
    class Meta:
        database = db

class User(BaseModel):
    id = PrimaryKeyField()
    username = CharField(default='test', max_length=20)

    class Meta:
        db_table = 'users'

MODELS_LIST = [User]

Database was created by manager  'generate_db_tables' command

import os
from app import create_app

from flask_script import Manager, Shell

app = create_app(os.getenv('FLASK_CONFIG') or 'default')
manager = Manager(app)

def connect_db():
    from peewee import SqliteDatabase
    db_lite = SqliteDatabase(app.config['DATABASE']['name'])
    return db_lite

@manager.command
def generate_db_tables():
    from app.models.models import MODELS_LIST
    db_lite = connect_db()
    for model in MODELS_LIST:
        db_lite.create_table(model, safe=True)
    print("Db tables created")

and the view function:

from flask import render_template, session, \
    redirect, url_for, current_app, flash, request, make_response

from . import main_bp
from .forms import NameForm
from app.models.models import User

@main_bp.route('/', methods=['GET', 'POST'])
def index():
    form = NameForm()
    if form.validate_on_submit():
        User.create(username=form.name.data) # <<<< Here is error
        return url_for('.index')
    return render_template('index.html', form=form)

Before i started to use Proxy class everything worked like a charm.

Body:
Seems, that i pass dict

DATABASE = {
    'name': 'test.db',
    'engine': 'peewee.SqliteDatabase'
}

to db.initialize()

instead of string name of database

DATABASE_INFO = 'test.db'
DATABASE = peewee.SqliteDatabase(DATABASE_INFO)
db.initialize(DATABASE)


问:
How to count individual user selections in a while loop
I would like to know how to count the number of times a user selects a specific option within a while loop. The user is selecting location, and I need to keep track of how many times this location is selected. What's the best way to do this without using an array? For example, I want to keep track of each time the while loop processes, how many London, Rome, or Key West options are selected. </p>

```<code>locationSelection = mainMenu(console);
while (locationSelection != 'Q') {
    if(locationSelection == 'A') {
        locationSelectionString = "London, England.";
    }
    if (locationSelection == 'B') {
        locationSelectionString = "Rome, Italy.";
    }
    if (locationSelection == 'C') {
        locationSelectionString = "Key West, Florida.";
    }
    if (locationSelection == 'Q') {
        break;
    }
</code>```

答:
Simply declare a counter.

```<code>int counter = 0;
</code>```

then inside your if statements increase the counter.

```<code>int counterA = 0;
int counterB = 0;
int counterC = 0;
locationSelection = mainMenu(console);
while (locationSelection != 'Q') {
    if(locationSelection == 'A') {
        locationSelectionString = "London, England.";
        counterA++;
    }
    if (locationSelection == 'B') {
        locationSelectionString = "Rome, Italy.";
        counterB++;
    }
    if (locationSelection == 'C') {
        locationSelectionString = "Key West, Florida.";
        counterC++;
    }
    if (locationSelection == 'Q') {
        break;
    }
</code>```

Body:
I would like to know how to count the number of times a user selects a specific option within a while loop. The user is selecting location, and I need to keep track of how many times this location is selected. What's the best way to do this without using an array? For example, I want to keep track of each time the while loop processes, how many London, Rome, or Key West options are selected.

locationSelection = mainMenu(console);
while (locationSelection != 'Q') {
    if(locationSelection == 'A') {
        locationSelectionString = "London, England.";
    }
    if (locationSelection == 'B') {
        locationSelectionString = "Rome, Italy.";
    }
    if (locationSelection == 'C') {
        locationSelectionString = "Key West, Florida.";
    }
    if (locationSelection == 'Q') {
        break;
    }

Body:
Simply declare a counter.

int counter = 0;

then inside your if statements increase the counter.

int counterA = 0;
int counterB = 0;
int counterC = 0;
locationSelection = mainMenu(console);
while (locationSelection != 'Q') {
    if(locationSelection == 'A') {
        locationSelectionString = "London, England.";
        counterA++;
    }
    if (locationSelection == 'B') {
        locationSelectionString = "Rome, Italy.";
        counterB++;
    }
    if (locationSelection == 'C') {
        locationSelectionString = "Key West, Florida.";
        counterC++;
    }
    if (locationSelection == 'Q') {
        break;
    }


问:
How to properly delete pointers when using abstract classes
Suppose I have the following classes and objects:

```<code>#include <iostream>

class Animal
{
public:
    virtual void makeNoise() = 0;

    void eat()
    {
        std::cout << "Eating..." << "\n";
    }

    void sleep()
    {
        std::cout << "Sleeping..." << "\n";
    }
};

class Cat: public Animal
{
public:
    void makeNoise()
    {
        std::cout << "Miow..." << "\n";
    }
};

class Cow: public Animal
{
public:
    void makeNoise()
    {
        std::cout << "Mooo..." << "\n";
    }
};

int main()
{
    Animal *animal;
    Cat *cat = new Cat();
    Cow *cow = new Cow();

    animal = cat;
    animal->eat();
    animal->sleep();
    animal->makeNoise();

    animal = cow;
    animal->eat();
    animal->sleep();
    animal->makeNoise();

    return 0;
}
</code>```

Note that animal is an abstract class.

How can I properly delete the pointers animal, cat and cow?

When I try to delete animal; I get the following warning message:

warning: deleting object of abstract class type 'Animal' which has
  non-virtual destructor will cause undefined behaviour.

In the other hand, when I try to delete cat; I get the following message:

warning: deleting object of polymorphic class type 'Cat' which has
  non-virtual destructor might cause undefined behaviour.

答:
A basic C++ rule says that destructors work their way up from the derived class to the base class. When a Cat is destroyed, then the Cat part is destroyed first and the Animal part is destroyed after.

delete animal; is undefined behaviour because in order to properly follow C++ destruction rules, one must know, at runtime, which derived class part should be destroyed before the Animal base part. A virtual destructor does exactly that - it enables a dynamic dispatch mechanism that makes sure destruction works as designed.

You have no virtual destructor, however, so delete animal just doesn't make sense. There is no way to call the correct derived-class destructor, and destroying only the Animal part wouldn't exactly be meaningful behaviour, either.

Therefore, the C++ language makes no assumptions about what will happen in such a situation.

Your compiler is nice enough to warn you about this.

With delete cat, the situation is slightly different. The static type of the cat pointer is Cat*, not Animal*, so it is clear even without any dynamic dispatch mechanism which derived-class destructor to call first.

The compiler still warns you about this, but it does so with a different wording ("might cause" vs. "will cause"). I believe the reason is that Cat might itself be the base class for more derived classes, seeing as it is already part of a class hierarchy with virtual functions.

It apparently doesn't bother to execute a more complete code analysis to find out that delete cat is really harmless.

In order to fix this, make the Animal destructor virtual. While you're at it, replace your raw pointers with std::unique_ptr. You still have to follow the virtual destructor rule for classes like yours, but you no longer have to perform a manual delete.

Body:
Suppose I have the following classes and objects:

#include <iostream>

class Animal
{
public:
    virtual void makeNoise() = 0;

    void eat()
    {
        std::cout << "Eating..." << "\n";
    }

    void sleep()
    {
        std::cout << "Sleeping..." << "\n";
    }
};

class Cat: public Animal
{
public:
    void makeNoise()
    {
        std::cout << "Miow..." << "\n";
    }
};

class Cow: public Animal
{
public:
    void makeNoise()
    {
        std::cout << "Mooo..." << "\n";
    }
};

int main()
{
    Animal *animal;
    Cat *cat = new Cat();
    Cow *cow = new Cow();

    animal = cat;
    animal->eat();
    animal->sleep();
    animal->makeNoise();

    animal = cow;
    animal->eat();
    animal->sleep();
    animal->makeNoise();

    return 0;
}

Note that animal is an abstract class.

How can I properly delete the pointers animal, cat and cow?

When I try to delete animal; I get the following warning message:

warning: deleting object of abstract class type 'Animal' which has
  non-virtual destructor will cause undefined behaviour.

In the other hand, when I try to delete cat; I get the following message:

warning: deleting object of polymorphic class type 'Cat' which has
  non-virtual destructor might cause undefined behaviour.


问:
Avoid the “Expression has changed after it was checked” error by calling "ChangeDetectorRef::detectChanges()"
I am trying to implement two way data binding on a date input while applying a pipe on the model:

```<code><!-- The name variable is retrieved within the HTML from a loop expression -->
<input matInput [matDatepicker]="datePicker" placeholder="{{label}}" formControlName="{{name}}"
[ngModel]="data[name] | date"
(ngModelChange)="handleDateChange(data[name], $event)" >
</code>```

Where my component looks something like:

```<code>//...
private data: any;

constructor(private cdRef:ChangeDetectorRef) { }

handleDateChange(field: any, date: any) {
    field = date; // The code is simplified, there is more handling with the date field
    this.cdRef.detectChanges();
}
</code>```

Based on this post, the code above works well only thanks to this.cdRef.detectChanges(); If I remove it I get the following error:
Expression has changed after it was checked

My question is more general than related specifically to the above implementation. I would like to know what are the best practices to deal with the Expression has changed after it was checked error? Is calling cdRef.detectChanges() a good idea?

答:
try changing this

```<code>handleDateChange(field: any, date: any) {
    field = date;
    this.cdRef.detectChanges();
}
</code>```

to

```<code><input matInput [matDatepicker]="datePicker" placeholder="{{label}}" formControlName="{{name}}"
[ngModel]="data[name] | date"
(ngModelChange)="handleDateChange(name, $event)" >

  ...

  handleDateChange(field, date) {
    this.data[field] = date;
  }
</code>```

let me know if you need any explanation why the Expression has changed after it was checked happens and why this.cdRef.detectChanges(); helps

Body:
I am trying to implement two way data binding on a date input while applying a pipe on the model:

<input matInput [matDatepicker]="datePicker" placeholder="{{label}}" formControlName="{{name}}"
[ngModel]="data[name] | date"
(ngModelChange)="handleDateChange(data[name], $event)" >

Where my component looks something like:

//...
private data: any;

constructor(private cdRef:ChangeDetectorRef) { }

handleDateChange(field: any, date: any) {
    field = date; // The code is simplified, there is more handling with the date field
    this.cdRef.detectChanges();
}

Based on this post, the code above works well only thanks to this.cdRef.detectChanges(); If I remove it I get the following error:
Expression has changed after it was checked

My question is more general than related specifically to the above implementation. I would like to know what are the best practices to deal with the Expression has changed after it was checked error? Is calling cdRef.detectChanges() a good idea?

Body:
try changing this

handleDateChange(field: any, date: any) {
    field = date;
    this.cdRef.detectChanges();
}

to

<input matInput [matDatepicker]="datePicker" placeholder="{{label}}" formControlName="{{name}}"
[ngModel]="data[name] | date"
(ngModelChange)="handleDateChange(name, $event)" >

  ...

  handleDateChange(field, date) {
    this.data[field] = date;
  }

let me know if you need any explanation why the Expression has changed after it was checked happens and why this.cdRef.detectChanges(); helps


问:
Can I connect to NetSuite data via ODBC without having SuiteAnalytics?
Just starting a job with a company that uses NetSuite. I am new to NetSuite, and my background is in SQL and C# - I'd like the ability to access the data outside of the UI and wondering if there's a way to do that without asking management to purchase SuiteAnalytics. Their NetSuite consultants of course say I don't need that kind of access but I've already heard the consultants say some reports would be too hard to do - which I know I could easily accomplish with ODBC access and a little code. If I could do it at no extra cost I will truly be a hero.</p>

答: No, you cannot connect via ODBC without the module.</p>


问:
Angular 2 TypeError: Object doesn't support property or method 'json'
I am building a basic CRUD application that references a SSMS database, using an Angular 2 front end and a MVC back end. I am running into the error when i run my HTTPGet on any browser:

TypeError: Object doesn't support property or method 'json'

I have a debug point set for the service call but it doesn't get there, so I am assuming the issue is in the component somewhere..

I have googled for about a day and a half, and have found a lot of people that have other things in the place of the 'json', but I cannot find anyone else with this issue exactly. Below you will find the could for my Get. If there is any other snippets you need please let me know.

Here is my Get component:

```<code>import { Component, OnInit, ViewChild } from '@angular/core';
import { CorrectionCodeService } from '../Service/correctioncode.service';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { ModalComponent } from 'ng2-bs3-modal/ng2-bs3-modal';
import { ICorrectionCode } from '../Models/ICorrectionCode';
import { DBOperation } from '../Shared/enum';
import { Observable } from 'rxjs/Rx';
import { Global } from '../Shared/global';

@Component({

templateUrl: 'app/Components/correctioncode.component.html'

})

`enter code here`export class CorrectionCodeComponent implements OnInit {

@ViewChild('modal') modal: ModalComponent;
corrCodes: ICorrectionCode[];
corrCode: ICorrectionCode;
msg: string;
indLoading: boolean = false;
form: FormGroup;
dbops: DBOperation;
modalTitle: string;
modalBtnTitle: string;

constructor(private fb: FormBuilder,private _corrCodeService: CorrectionCodeService) { }

ngOnInit() {
    this.form = this.fb.group({
        id: [''],
        pgm_code_name: [''],
        rec_act_code: [''],
        rgln_Year: [''],
        rgln_type_name: [''],
        rgln_one_code: [''],
        rgln_two_code: [''],
        rgln_three_code: [''],
        rgln_title_text: [''],
        rgln_desc_text: [''],
        sevrty_code: [''],
        valdtn_value: [''],
        last_updt_dt: [''],
        last_updt_logn_id: [''],
        creat_dt: [''],
        creat_logn_id: [''],
        del_dt: [''],
        del_logn_id: [''],
        prev_rec_id: ['']
    });

    this.getCorrectionCodes();

}
 getCorrectionCodes(): void {
    this.indLoading = true;
    this._corrCodeService.get(Global.BASE_CORRECTION_CODE_ENDPOINT)
        .subscribe(corrCodes => {
            this.corrCodes = corrCodes; this.indLoading = false;
        }, error => this.msg = <any>error);
}
</code>```

And, here is my service:

```<code>import { Injectable } from '@angular/core';
import { Http, Response, Headers, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/catch';
@Injectable()
export class CorrectionCodeService {
    constructor(private _http: Http) { }

    get(url: string): Observable<any> {
        let headers = new Headers({ 'accept': 'applicationCache/json' });
        let options = new RequestOptions({ headers: headers });
        return this._http.get(url,options)
            .map((response: Response) => <any>response.json())
            // .do(data => console.log("All: " + JSON.stringify(data)));

    }
</code>```

here is my app.module.ts:

```<code>import { NgModule } from '@angular/core';
import { APP_BASE_HREF } from '@angular/common';
import { BrowserModule } from '@angular/platform-browser';
import { ReactiveFormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { HttpModule } from '@angular/http';
import { routing } from './app.routing';
import { HomeComponent } from './Components/home.component';
import { CorrectionCodeComponent } from './Components/correctioncode.component';
import { Ng2Bs3ModalModule } from 'ng2-bs3-modal/ng2-bs3-modal';
import { CorrectionCodeService } from './Service/correctioncode.service';
import { UploadFileComponent } from './Components/uploadFile.component';
import { UploadFileService } from './Service/uploadFile.service';

@NgModule({
    imports: [BrowserModule, ReactiveFormsModule, HttpModule, routing, Ng2Bs3ModalModule],
    declarations: [AppComponent, CorrectionCodeComponent, HomeComponent,  UploadFileComponent],
    providers: [{ provide: APP_BASE_HREF, useValue: '/' }, CorrectionCodeService, UploadFileService],
    bootstrap: [AppComponent]
})

export class AppModule { }
</code>```

Here is my controller:

```<code>using CorrectionCodeEditor.Models;
using CorrectionCodeEditor.Repository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;

namespace CorrectionCodeEditor.Controllers
{
    public class CorrectionCodeController : BaseAPIController
    {
        string ProgramAreaName = "FAS";
        private CorrectionCodeRepository context;
        public CorrectionCodeController()
        {

            context = new CorrectionCodeRepository();
        }

        [HttpGet]
        public HttpResponseMessage Get()
        {
            var corrCodes = context.GetAllCorrectionCodes(ProgramAreaName).AsEnumerable();
                return ToJson(corrCodes);
        }
</code>```

my ToJson method:

```<code>protected HttpResponseMessage ToJson(dynamic obj)
        {
            var response = Request.CreateResponse(HttpStatusCode.OK);
            response.Content = new StringContent(JsonConvert.SerializeObject(obj), Encoding.UTF8, "application/json");
            return response;
        }
</code>```

and my Contextual DB Repository:

```<code> public IEnumerable<CorrectionCode> GetAllCorrectionCodes(string pgm_area_name)
        {
            using (con)
            {
                 con.Open();
                var dP = new DynamicParameters();
                dP.Add("@ProgramAreaName", pgm_area_name);
                IEnumerable<CorrectionCode> corrCodeList = con.Query<CorrectionCode>("[mobile].[p_get_correction_codes_by_params]", dP, commandType: CommandType.StoredProcedure);
                return corrCodeList;
            }
        }
</code>```

EDIT#1 Compile Tile Error from Google Developer Tools while the screen displays "TypeError: error.json is not a function":

```<code>SyntaxError: Unexpected token < in JSON at position 0
    at JSON.parse (<anonymous>)
    at Response.Body.json (body.ts:36)
    at MapSubscriber.eval [as project] (correctioncode.service.ts:12)
    at MapSubscriber._next (map.ts:75)
    at MapSubscriber.Subscriber.next (Subscriber.ts:95)
    at XMLHttpRequest.onLoad (xhr_backend.ts:104)
    at ZoneDelegate.invokeTask (zone.js:265)
    at Object.onInvokeTask (ng_zone.ts:254)
    at ZoneDelegate.invokeTask (zone.js:264)
    at Zone.runTask (zone.js:154)
</code>```

here is a screenshot of the error readout in IE11 while the screen is saying "TypeError: Object doesn't support property or method 'json'":

答:
I strongly suggest you to use the Http Client instead Http, because the first is deprecated. to use it simple:

```<code>import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable()
export class AccountService {

  constructor(private http: HttpClient) {
   ...
  }
</code>```

Of Course you should declare HttpClient also in your app.module in the same form that Http.

Body:
I am building a basic CRUD application that references a SSMS database, using an Angular 2 front end and a MVC back end. I am running into the error when i run my HTTPGet on any browser:

TypeError: Object doesn't support property or method 'json'

I have a debug point set for the service call but it doesn't get there, so I am assuming the issue is in the component somewhere..

I have googled for about a day and a half, and have found a lot of people that have other things in the place of the 'json', but I cannot find anyone else with this issue exactly. Below you will find the could for my Get. If there is any other snippets you need please let me know.

Here is my Get component:

import { Component, OnInit, ViewChild } from '@angular/core';
import { CorrectionCodeService } from '../Service/correctioncode.service';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { ModalComponent } from 'ng2-bs3-modal/ng2-bs3-modal';
import { ICorrectionCode } from '../Models/ICorrectionCode';
import { DBOperation } from '../Shared/enum';
import { Observable } from 'rxjs/Rx';
import { Global } from '../Shared/global';

@Component({

templateUrl: 'app/Components/correctioncode.component.html'

})

`enter code here`export class CorrectionCodeComponent implements OnInit {

@ViewChild('modal') modal: ModalComponent;
corrCodes: ICorrectionCode[];
corrCode: ICorrectionCode;
msg: string;
indLoading: boolean = false;
form: FormGroup;
dbops: DBOperation;
modalTitle: string;
modalBtnTitle: string;

constructor(private fb: FormBuilder,private _corrCodeService: CorrectionCodeService) { }

ngOnInit() {
    this.form = this.fb.group({
        id: [''],
        pgm_code_name: [''],
        rec_act_code: [''],
        rgln_Year: [''],
        rgln_type_name: [''],
        rgln_one_code: [''],
        rgln_two_code: [''],
        rgln_three_code: [''],
        rgln_title_text: [''],
        rgln_desc_text: [''],
        sevrty_code: [''],
        valdtn_value: [''],
        last_updt_dt: [''],
        last_updt_logn_id: [''],
        creat_dt: [''],
        creat_logn_id: [''],
        del_dt: [''],
        del_logn_id: [''],
        prev_rec_id: ['']
    });

    this.getCorrectionCodes();

}
 getCorrectionCodes(): void {
    this.indLoading = true;
    this._corrCodeService.get(Global.BASE_CORRECTION_CODE_ENDPOINT)
        .subscribe(corrCodes => {
            this.corrCodes = corrCodes; this.indLoading = false;
        }, error => this.msg = <any>error);
}

And, here is my service:

import { Injectable } from '@angular/core';
import { Http, Response, Headers, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/catch';
@Injectable()
export class CorrectionCodeService {
    constructor(private _http: Http) { }

    get(url: string): Observable<any> {
        let headers = new Headers({ 'accept': 'applicationCache/json' });
        let options = new RequestOptions({ headers: headers });
        return this._http.get(url,options)
            .map((response: Response) => <any>response.json())
            // .do(data => console.log("All: " + JSON.stringify(data)));

    }

here is my app.module.ts:

import { NgModule } from '@angular/core';
import { APP_BASE_HREF } from '@angular/common';
import { BrowserModule } from '@angular/platform-browser';
import { ReactiveFormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { HttpModule } from '@angular/http';
import { routing } from './app.routing';
import { HomeComponent } from './Components/home.component';
import { CorrectionCodeComponent } from './Components/correctioncode.component';
import { Ng2Bs3ModalModule } from 'ng2-bs3-modal/ng2-bs3-modal';
import { CorrectionCodeService } from './Service/correctioncode.service';
import { UploadFileComponent } from './Components/uploadFile.component';
import { UploadFileService } from './Service/uploadFile.service';

@NgModule({
    imports: [BrowserModule, ReactiveFormsModule, HttpModule, routing, Ng2Bs3ModalModule],
    declarations: [AppComponent, CorrectionCodeComponent, HomeComponent,  UploadFileComponent],
    providers: [{ provide: APP_BASE_HREF, useValue: '/' }, CorrectionCodeService, UploadFileService],
    bootstrap: [AppComponent]
})

export class AppModule { }

Here is my controller:

using CorrectionCodeEditor.Models;
using CorrectionCodeEditor.Repository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;

namespace CorrectionCodeEditor.Controllers
{
    public class CorrectionCodeController : BaseAPIController
    {
        string ProgramAreaName = "FAS";
        private CorrectionCodeRepository context;
        public CorrectionCodeController()
        {

            context = new CorrectionCodeRepository();
        }

        [HttpGet]
        public HttpResponseMessage Get()
        {
            var corrCodes = context.GetAllCorrectionCodes(ProgramAreaName).AsEnumerable();
                return ToJson(corrCodes);
        }

my ToJson method:

protected HttpResponseMessage ToJson(dynamic obj)
        {
            var response = Request.CreateResponse(HttpStatusCode.OK);
            response.Content = new StringContent(JsonConvert.SerializeObject(obj), Encoding.UTF8, "application/json");
            return response;
        }

and my Contextual DB Repository:

 public IEnumerable<CorrectionCode> GetAllCorrectionCodes(string pgm_area_name)
        {
            using (con)
            {
                 con.Open();
                var dP = new DynamicParameters();
                dP.Add("@ProgramAreaName", pgm_area_name);
                IEnumerable<CorrectionCode> corrCodeList = con.Query<CorrectionCode>("[mobile].[p_get_correction_codes_by_params]", dP, commandType: CommandType.StoredProcedure);
                return corrCodeList;
            }
        }

EDIT#1 Compile Tile Error from Google Developer Tools while the screen displays "TypeError: error.json is not a function":

SyntaxError: Unexpected token < in JSON at position 0
    at JSON.parse (<anonymous>)
    at Response.Body.json (body.ts:36)
    at MapSubscriber.eval [as project] (correctioncode.service.ts:12)
    at MapSubscriber._next (map.ts:75)
    at MapSubscriber.Subscriber.next (Subscriber.ts:95)
    at XMLHttpRequest.onLoad (xhr_backend.ts:104)
    at ZoneDelegate.invokeTask (zone.js:265)
    at Object.onInvokeTask (ng_zone.ts:254)
    at ZoneDelegate.invokeTask (zone.js:264)
    at Zone.runTask (zone.js:154)

here is a screenshot of the error readout in IE11 while the screen is saying "TypeError: Object doesn't support property or method 'json'":

Body:
I strongly suggest you to use the Http Client instead Http, because the first is deprecated. to use it simple:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable()
export class AccountService {

  constructor(private http: HttpClient) {
   ...
  }

Of Course you should declare HttpClient also in your app.module in the same form that Http.


问:
Where is flock() for Perl on Windows?
I have a Perl script that I'd like to run on Windows, using either Strawberry Perl or ActivePerl; I don't care which. This script however, uses flock() calls, which does not seem to be included in either of those versions of Perl.

Can anyone help get this up and running?

答:
Is the Fcntl module installed?  Try this:

```<code>perl.exe -MFcntl -e 1
</code>```

If it complains, you don't have the Fcntl module installed.  If it doesn't complain, then you have access to Fcntl::flock, so put this in your script:

```<code>use Fcntl qw(:DEFAULT :flock);
</code>```

and off you go.

OwnerDisplayName: gbjbaanb

Title: Where is flock() for Perl on Windows?

LastEditorDisplayName: brian d foy

Body:
Is the Fcntl module installed?  Try this:

perl.exe -MFcntl -e 1

If it complains, you don't have the Fcntl module installed.  If it doesn't complain, then you have access to Fcntl::flock, so put this in your script:

use Fcntl qw(:DEFAULT :flock);

and off you go.


问:
Why must a monitor be acquired before calling Monitor.Wait()
If a thread calls Monitor.Wait(lockObj) on a lock object that it does not currently own then a SyncronizationLockException will be thrown.

I don't understand the point of this? If the thread does own the lock and thus can successfully call Monitor.Wait() then it's just going to immediately release the lock anyway. Why can't a thread just wait on a lock it does not currently own?

Update

I've decided to add a bit more explanation to my question.

From what I understand Wait simply puts the current thread on the monitors wait queue and releases the lock. Later a pulse or pulse all moves one or all threads on the wait queue to the ready queue. Whenever the monitor is released the next (if any) thread on the ready queue is given the lock.

So why can't a wait simply add the thread to the wait queue? Why does it need to acquire the lock to do this? Is there a physical reason for this or just that Microsoft designed the class to force you into using it the correct way?

Now that I think about it I guess putting something on the monitor's wait queue, or moving something to the ready queue is really manipulating the monitor. It would make sense that you would need to own the monitor to do this. Is that the right way of thinking about it?

Owe my brain multithreading is hard!

答:
Calling Monitor.Wait without a lock would in most cases introduce a non-deterministic bug. The same if you call Monitor.Wait just after acquiring a lock and without setting any shared variables in between of acquiring a lock and calling Monitor.Wait.

In particular - if you do not own a lock then you can never be sure that accompanying Monitor.Pulse has not been executed before you entered Monitor.Wait. Think about a situation when the operating system had suspended thread A just before Monitor.Wait call and resumed thread B that is executing Monitor.Pulse after doing some computation. All shared variables convince thread B that A is waiting, but this is simply not true yet. And thread A cannot stop executing Monitor.Wait at this point.

Also - you may be interested in the idea of Semaphores http://en.wikipedia.org/wiki/Semaphore_(programming) . You can wait and signal them without the idea of acquiring them. This is because they hold a state in them. So if you signal first then wait will not lock.


答:
Sorry this doesn't answer your question about map2, I find it's easier to aggregate over rows than it is over columns in tidy R:

library(dplyr)

master <- tibble(
  id=c(1,2,3),
  col1=c(1,1,1),
  col2=c(2,2,2),
  col3=c(3,3,3)
)
correction1 <- tibble(
  id=seq(1,3),
  col1=c(NA, NA, 2 ),
  col2=c( 1, NA, 3 ),
  col3=c(NA, NA, NA)
)

result <- list(master, correction1) %>%
  bind_rows() %>%
  group_by(id) %>%
  summarise_all(max, na.rm = TRUE)

result
#> # A tibble: 3 x 4
#>      id  col1  col2  col3
#>   <dbl> <dbl> <dbl> <dbl>
#> 1     1     1     2     3
#> 2     2     1     2     3
#> 3     3     2     3     3
```

Title: How to mutate() a list of columns using map2() in dplyr


问:
Serializing double to an int within POJO
I am having trouble figuring out how to serialize my a double to an int in my POJO. At the moment, I am sloppily making the conversion within the setter method. The double will always be between 0 and 1. Below are the getter and setter methods within my POJO:

```<code>@JsonProperty("costMargin")
public int getCostMargin() {
    return costMargin;
}

@JsonProperty("costMargin")
public void setCostMargin(double costMargin) {
        this.costMargin = (int)(Math.round(costMargin * 100));
}
</code>```

Can anyone help me figure out how to serialize this double to an int, without making the conversion within the setter method? I am trying to look into other ways of doing this, such as creating a serializer class, and including an annotation in my Pojo. for example: @JsonSerialize(using = CustomDoubleSerializer.class)

答:
I ended up using:

```<code>    @JsonSerialize(using = CustomDoubleSerializer.class)
    @JsonProperty("costMargin")
         public int getCostMargin() {
         return costMargin;
    }
</code>```

to call

```<code>public class CustomDoubleSerializer extends JsonSerializer<Double> {

@Override
public void serialize(Double value, JsonGenerator gen, SerializerProvider serializers)
        throws IOException, JsonProcessingException {
    gen.writeObject((int)(Math.round(value * 100)));
}
</code>```

}

public class CustomDoubleSerializer extends JsonSerializer {

Body:
I am having trouble figuring out how to serialize my a double to an int in my POJO. At the moment, I am sloppily making the conversion within the setter method. The double will always be between 0 and 1. Below are the getter and setter methods within my POJO:

@JsonProperty("costMargin")
public int getCostMargin() {
    return costMargin;
}

@JsonProperty("costMargin")
public void setCostMargin(double costMargin) {
        this.costMargin = (int)(Math.round(costMargin * 100));
}

Can anyone help me figure out how to serialize this double to an int, without making the conversion within the setter method? I am trying to look into other ways of doing this, such as creating a serializer class, and including an annotation in my Pojo. for example: @JsonSerialize(using = CustomDoubleSerializer.class)

Body:
I ended up using:

    @JsonSerialize(using = CustomDoubleSerializer.class)
    @JsonProperty("costMargin")
         public int getCostMargin() {
         return costMargin;
    }

to call

public class CustomDoubleSerializer extends JsonSerializer<Double> {

@Override
public void serialize(Double value, JsonGenerator gen, SerializerProvider serializers)
        throws IOException, JsonProcessingException {
    gen.writeObject((int)(Math.round(value * 100)));
}

}

public class CustomDoubleSerializer extends JsonSerializer {


问:
Hangman game wont print same letter
I have a question about my game. It seems like I can only get one letter to print instead how many there are in a word. For instance, "star wars" looks like "star wr".

//array of Star Wars Names
var words = ["star wars",
  "senator organa",
  "boba fett",
  "chewbacca",
  "luke skywalker",
  "darth vader",
  "lando calrissian",
  "anakin skywalker",
  "padme amidala"
];

//Declared variables
var rightLetter = [];
var wrongLetter = [];
var underScore = [];
var underScore = [];
var randomWords = Math.floor(Math.random() * words.length);
var chosenWords = words[randomWords];
var starWarsNames = document.getElementsByClassName("Star_Wars_words");
var correctGuess = document.getElementsByClassName("rightGuess");
var incorrectGuess = document.getElementsByClassName("wrongGuess");

//random word array

console.log(chosenWords);

function generateUnderscore() {
  for (i = 0; i < chosenWords.length; i++) {
    underScore.push("_");
  }
  return underScore;
}

//Game Loop
document.addEventListener("keypress", letterPressed);
//letter function
function letterPressed(event) {
  var letter = String.fromCharCode(event.keyCode);
  if (chosenWords.indexOf(letter) > -1) {
    rightLetter.push(letter);
    underScore[chosenWords.indexOf(letter)] = letter;
    starWarsNames[0].innerHTML = underScore.join(" ");
    correctGuess[0].innerHTML = rightLetter;
    if (underScore.join(" ") == chosenWords) {
      alert("The force is strong with you!");
    }
  } else {
    wrongLetter.push(letter);
    incorrectGuess[0].innerHTML = wrongLetter;
  }
}

console.log(rightLetter);
console.log(wrongLetter);
console.log(starWarsNames);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="Star_Wars_words">

</div>
<div class="rightGuess">

</div>
<div class="wrongGuess">

</div></code>```

答:
In your letterPressed function, you can reorganize it to check for multiple instances. For example:

```<code>var idx = 0;
idx = chosenWords.indexOf(letter, idx);
if (idx == -1) {
    wrongLetter.push(letter);
    incorrectGuess[0].innerHTML = wrongLetter;
    return;
}
while (idx > -1) {
    rightLetter.push(letter);
    underScore[idx] = letter;
    starWarsNames[0].innerHTML = underScore.join(" ");
    correctGuess[0].innerHTML = rightLetter;
    if(underScore.join(" ") == chosenWords) {
        alert("The force is strong with you!");
    }
    idx = chosenWords.indexOf(letter, ++idx);
}
</code>```

So the difference is that if a letter is found (idx > -1) then you will process it as you were before, but then you will update idx with the next index of the letter.

Title: Hangman game wont print same letter

Body:
In your letterPressed function, you can reorganize it to check for multiple instances. For example:

var idx = 0;
idx = chosenWords.indexOf(letter, idx);
if (idx == -1) {
    wrongLetter.push(letter);
    incorrectGuess[0].innerHTML = wrongLetter;
    return;
}
while (idx > -1) {
    rightLetter.push(letter);
    underScore[idx] = letter;
    starWarsNames[0].innerHTML = underScore.join(" ");
    correctGuess[0].innerHTML = rightLetter;
    if(underScore.join(" ") == chosenWords) {
        alert("The force is strong with you!");
    }
    idx = chosenWords.indexOf(letter, ++idx);
}

So the difference is that if a letter is found (idx > -1) then you will process it as you were before, but then you will update idx with the next index of the letter.


问:
ESXi remote access
i have a server with ESXi in my local network.
i can connect to it via vSphere from my local network
but can't connect from internet. Some people http://www.logicalsolutions.co.nz/connect-vsphere-client-externally/ achived by port forwarding so did i.

```<code>ESXi settings
ip 192.168.100.118
mask 255.255.255.0
gateway 192.168.100.1

Router settings
incoming port 443 forwarded to 443 of server 192.168.100.118 (my ESXi)
incoming port 902 forwarded to 902 of server 192.168.100.118 (my ESXi)
</code>```

vSphere "public ip":port

still no connection.

So i thought if the problem was with router and forwarded some port to my local sqlserver port. It works

Maybe there are some settings where can i enable public access to ESXi.

答:
for connect to esxi remotely you have two solution.

if you use Esxi 6.5 its has WebConsole client instead of vsphereClient that you can connect to it remotely on port 80.

you can connect via ssh on port 22 that dpcument in this link

Title: ESXi remote access

Body:
i have a server with ESXi in my local network.
i can connect to it via vSphere from my local network
but can't connect from internet. Some people http://www.logicalsolutions.co.nz/connect-vsphere-client-externally/ achived by port forwarding so did i.

ESXi settings
ip 192.168.100.118
mask 255.255.255.0
gateway 192.168.100.1

Router settings
incoming port 443 forwarded to 443 of server 192.168.100.118 (my ESXi)
incoming port 902 forwarded to 902 of server 192.168.100.118 (my ESXi)

vSphere "public ip":port

still no connection.

So i thought if the problem was with router and forwarded some port to my local sqlserver port. It works

Maybe there are some settings where can i enable public access to ESXi.


问:
Where can I find good reference/tutorial on writing Apache modules (in C)?
I've looked all over and can't really find much of anything. I need three basic things:

Good API reference

Some sort of a tutorial

Good architectural overview

I have the module source code and am going through it - but I really don't have much of any context for most of the things its doing.

Any suggestions?

答:
Here is the list of links about apache module development that I found useful:

Apache Tutor

Apache Modules Development and Debugging

libapr(apache portable runtime) programming tutorial

The Apache Modules Book: Application Development with Apache

Mailing list archives

Apache at WebÞing

Writing portable C code with APR

Apache Modeling Project

You can also download the apache source code and experiment with mod_example.


问:
Move some objects of array at the end in swift 3
I have a list of conversation which needs to be sorted on last updated time. I am able to do this but now i also need to add a check that if user is not included in conversation then it should appear at the end of list. </p>

```<code>func sortConversationList () {
self.conversationList = self.conversationList.sorted(by: { $0.lastupdatedTime! > $1.lastupdatedTime! })
    for (index, conversation) in self.conversationList.enumerated() {
        if (conversation.isIncluded == kNo) {
            self.conversationList.move(at: index, to: self.conversationList.endIndex-1)
        }
    }
    self.tableView.reloadData()
}
 mutating func move(at oldIndex: Int, to newIndex: Int) {
        self.insert(self.remove(at: oldIndex), at: newIndex)
    }
</code>```

<p>but this is not working properly. Any better way to do this in swift ? </p>

答:
Your approach is far too complicated. You have two sorting criteria:

isIncluded – true values should be sorted before false values,

lastupdatedTime – larger values should be sorted first.

That can be done with a single sort() call:

```<code>conversationList.sort(by: {
    if $0.isIncluded != $1.isIncluded {
        return $0.isIncluded
    } else {
        return $0.lastupdatedTime > $1.lastupdatedTime
    }
})
</code>```

This assumes isIncluded is a boolean variable (which would be sensible). If it is an integer (as you indicated in the comments)
then it is even simpler: (compare Swift - Sort array of objects with multiple criteria):

```<code>conversationList.sort(by: {
    ($0.isIncluded, $0.lastupdatedTime) > ($1.isIncluded, $1.lastupdatedTime)
})
</code>```

Body:
I have a list of conversation which needs to be sorted on last updated time. I am able to do this but now i also need to add a check that if user is not included in conversation then it should appear at the end of list.

func sortConversationList () {
self.conversationList = self.conversationList.sorted(by: { $0.lastupdatedTime! > $1.lastupdatedTime! })
    for (index, conversation) in self.conversationList.enumerated() {
        if (conversation.isIncluded == kNo) {
            self.conversationList.move(at: index, to: self.conversationList.endIndex-1)
        }
    }
    self.tableView.reloadData()
}
 mutating func move(at oldIndex: Int, to newIndex: Int) {
        self.insert(self.remove(at: oldIndex), at: newIndex)
    }

but this is not working properly. Any better way to do this in swift ?

Body:
Your approach is far too complicated. You have two sorting criteria:

isIncluded – true values should be sorted before false values,

lastupdatedTime – larger values should be sorted first.

That can be done with a single sort() call:

conversationList.sort(by: {
    if $0.isIncluded != $1.isIncluded {
        return $0.isIncluded
    } else {
        return $0.lastupdatedTime > $1.lastupdatedTime
    }
})

This assumes isIncluded is a boolean variable (which would be sensible). If it is an integer (as you indicated in the comments)
then it is even simpler: (compare Swift - Sort array of objects with multiple criteria):

conversationList.sort(by: {
    ($0.isIncluded, $0.lastupdatedTime) > ($1.isIncluded, $1.lastupdatedTime)
})