Title: Powershell convertto-json without labels

Body:
Silly me - I only needed to select and expand the property. like so.

$chartvalues = $processgroup | select -expandproperty count | convertto-json

$chartvalues
[
    1,
    1,
    1,
    1,
    1,
    1,
    30,
    1,
    1,
    1,
    5,
    2,
    1,
    1,
    1,
    1,
    2,
    1,
    1,
    2,
    1,
    1,
    1,
    1,
    4,
    1,
    1,
    1,
    30,
    1,
    1,
    1,
    1,
    1,
    1,
    1,
    1,
    1,
    1,
    2,
    1,
    1,
    2,
    2,
    1,
    1,
    1,
    1,
    1,
    2,
    1,
    1,
    1,
    2,
    1,
    1,
    1,
    1,
    1,
    1,
    1,
    1,
    1,
    1,
    1,
    1,
    2,
    1,
    2,
    1,
    1,
    1,
    1,
    75,
    1,
    1,
    1,
    2,
    1,
    1,
    1,
    1,
    1,
    1,
    1,
    1,
    1,
    1,
    2,
    1,
    1
]


来源: stackexchange

问:
Remove materialisecss cards dynamically
I am using materialisedcss and angularjs for designing my website.I have series a json data(from Rest) which will be displayed in the form of cards as shown below.

There will be two options which will be either to accept or reject the leave as shown in the picture.When the user selects any option ,the card will be revealed using materialised card-reveal class with two more options as shown below

Now my requirement is when the user clicks on the yes option,a function should be called that should remove the card from the view .How to do this using materialised and angularjs ?.Following are my code

Code for card display

      {{elem.signum}}

Leave applied from {{elem.startDate |date}} to {{elem.endDate |date}} pending for approval

Approve

Decline

     Sure?close

Are You Sure To approve the leave Request

YES

Cancel

```

答:
You should use ng-class to define class of your element based on variable.

For a if / else test on ng-class; please see this explanation : https://stackoverflow.com/a/21970785/3687474

ContentLicense: CC BY-SA 3.0

Title: Remove materialisecss cards dynamically


问:
calling a synonym of a procedure where input parameter is user-defined table type
On DatabaseA I have User-Defined Data Type which is used as input parameter in a stored procedure. On another database (DatabaseB) I am creating synonym to this procedure and I am creating same data type there.

When I call the sysnonym I am reciving an error "Operand type clash: Ids is incompatible with Ids"

Any suggestion how to resolve this problem?

```<code>use DatabaseA
go

CREATE TYPE [dbo].[Ids] AS TABLE(
    [Id] [sql_variant] NULL
)
GO

create procedure dbo.proc1 @Ids [Ids] readonly
as
begin
    select *
    from @Ids;
end

declare @Ids  dbo.Ids;
insert into @Ids values (1),(2)
exec dbo.proc1
    @Ids = @Ids

use DatabaseB

CREATE TYPE [dbo].[Ids] AS TABLE(
    [Id] [sql_variant] NULL
)
go

CREATE SYNONYM [Admiral_CentralSystem01].[dbo_proc1] FOR [Admiral_CentralSystem01].[dbo].[proc1]
GO

declare @Ids  dbo.Ids;
insert into @Ids values (1),(2)
exec [Admiral_CentralSystem01].[dbo_proc1]
    @Ids = @Ids
</code>```

答:
Basically tables variant are database scoped

In order to use a user-defined type (UDT) in Microsoft SQL Server, you
  must register it. Registering a UDT involves registering the assembly
  and creating the type in the database in which you wish to use it.
  UDTs are scoped to a single database, and cannot be used in multiple
  databases unless the identical assembly and UDT are registered with
  each database. Once the UDT assembly is registered and the type
  created, you can use the UDT in Transact-SQL and in client code. For
  more information, see CLR User-Defined Types.

https://learn.microsoft.com/en-us/sql/relational-databases/clr-integration-database-objects-user-defined-types/registering-user-defined-types-in-sql-server

Body:
On DatabaseA I have User-Defined Data Type which is used as input parameter in a stored procedure. On another database (DatabaseB) I am creating synonym to this procedure and I am creating same data type there.

When I call the sysnonym I am reciving an error "Operand type clash: Ids is incompatible with Ids"

Any suggestion how to resolve this problem?

use DatabaseA
go

CREATE TYPE [dbo].[Ids] AS TABLE(
    [Id] [sql_variant] NULL
)
GO

create procedure dbo.proc1 @Ids [Ids] readonly
as
begin
    select *
    from @Ids;
end

declare @Ids  dbo.Ids;
insert into @Ids values (1),(2)
exec dbo.proc1
    @Ids = @Ids

use DatabaseB

CREATE TYPE [dbo].[Ids] AS TABLE(
    [Id] [sql_variant] NULL
)
go

CREATE SYNONYM [Admiral_CentralSystem01].[dbo_proc1] FOR [Admiral_CentralSystem01].[dbo].[proc1]
GO

declare @Ids  dbo.Ids;
insert into @Ids values (1),(2)
exec [Admiral_CentralSystem01].[dbo_proc1]
    @Ids = @Ids


问:
Is it valid to predefine object of class even if we are using it or not?
I am just creating one class related to image upload and i was thinking to start it's object on end of the line of class that user can simply include it into file and execute it directly</p>

答:
I think it's better to create your upload image class with static function. So you never need to create object and you could include it in other class, whenever you want.

You could access your function as:

UploadImage::upload($destPath)


问:
Visual Studio warning: "Some of the properties associated with the solution could not be read"
When I open my solution, I get a dialog with this warning.  The solution (one web app, one class project) builds without errors.

How can I determine what properties are causing the problem, and resolve the error?

答:
The best solution is to force the VS to regenerate the configs. To do this:

Open the sln file with a text editor.

Scroll down till you reach the last "EndProject" element.

Delete everything after that.

Save, Close and rebuild the solution and everything will be regenerated.

ContentLicense: CC BY-SA 4.0


问:
C# Mono+Winforms MessageBox problem
I have a file called hellowf.cs

```<code>class MyFirstApp {
static void Main() {
     System.Windows.Forms.MessageBox.Show("Hello, Mono+WinForms!");
   }
}
</code>```

On Ubuntu 8.10, I do the following

```<code>gmcs hellowf.cs -r:System.Drawing.dll -r:System.Windows.Forms.dll
mono hellowf.exe
</code>```

... and it looks like this:

alt text http://img136.imageshack.us/img136/4674/helloproblemuk5.png

The second part of the message is missing. Why is this happening? The same binary - hellowf.exe - works fine on Windows.

Update:
This is really annoying. Here are the mono versions I have had and tried to make this work on so far:

```<code>    1.9.1 (from official ubuntu repo)
    2.0.1 (from some some 3rd party repo)
    2.2   (wiped every mono pkg and compiled myself)
</code>```

My Current mono version:

```<code>mono --version
Mono JIT compiler version 2.2 (tarball Wed Jan 14 22:58:21 CET 2009)
Copyright (C) 2002-2008 Novell, Inc and Contributors. www.mono-project.com
    TLS:           __thread
    GC:            Included Boehm (with typed GC)
    SIGSEGV:       altstack
    Notifications: epoll
    Architecture:  x86
    Disabled:      none
gmcs --version
Mono C# compiler version 2.2.0.0
</code>```

... any clues?

答:
Works OK on opensuse 11.0, mono 2.0.1.

Please, edit your question and put the mono version you are using.

ContentLicense: CC BY-SA 2.5

Title: C# Mono+Winforms MessageBox problem

Body:
I have a file called hellowf.cs

class MyFirstApp {
static void Main() {
     System.Windows.Forms.MessageBox.Show("Hello, Mono+WinForms!");
   }
}

On Ubuntu 8.10, I do the following

gmcs hellowf.cs -r:System.Drawing.dll -r:System.Windows.Forms.dll
mono hellowf.exe

... and it looks like this:

alt text http://img136.imageshack.us/img136/4674/helloproblemuk5.png

The second part of the message is missing. Why is this happening? The same binary - hellowf.exe - works fine on Windows.

Update:
This is really annoying. Here are the mono versions I have had and tried to make this work on so far:

    1.9.1 (from official ubuntu repo)
    2.0.1 (from some some 3rd party repo)
    2.2   (wiped every mono pkg and compiled myself)

My Current mono version:

mono --version
Mono JIT compiler version 2.2 (tarball Wed Jan 14 22:58:21 CET 2009)
Copyright (C) 2002-2008 Novell, Inc and Contributors. www.mono-project.com
    TLS:           __thread
    GC:            Included Boehm (with typed GC)
    SIGSEGV:       altstack
    Notifications: epoll
    Architecture:  x86
    Disabled:      none
gmcs --version
Mono C# compiler version 2.2.0.0

... any clues?

OwnerDisplayName: Sunny


问:
Silverlight + WCF Data Services getting InvalidOperationException :The context is already tracking a different entity with the same resource Uri
I'm trying to replace an object with a new one and am getting the mentioned exception. I've tried several combination and can't get around it.

I have a Playlist that has Items (the Items has another nested object, but I'm leaving it out to help make my question clearer. The user can change which items are in the playlist.

```<code> if (playlistChanged)
{
    // remove selectedForRemoval
    IEnumerable<PlaylistItemViewModel> nonSelectedItems = selectedDisplayTemplates.Where(pivm => pivm.IsSelectedForRemoval);
    foreach (temViewModel ivm in nonSelectedItems)
    {
        context.DeleteObject(ivm.Model);
    }

    // clear out and remove old items
    foreach (Item item in playlist.PlaylistItems)
    {
        context.DeleteObject(item);
    }

    playlist.PlaylistItems.Clear();

    // add the selectedItem(s) to the playlist
    // these items can be from the Media, or other tables
    // so are newly created in code on the client
    foreach (ItemViewModel ivm in selectedItems)
    {
        playlist.Items.Add(ivm.PlaylistItemModel);
        context.AddToItems(ivm.PlaylistItemModel);
    }
    context.BeginSaveChanges(SaveChangesOptions.Batch, new AsyncCallback((iar) =>
    {
        try
        {
            // Callback method for the async request, retrieves the status of the requested action
            DataServiceResponse response = context.EndSaveChanges(iar);
        }
        catch (DataServiceRequestException)
        {
            throw;
        }
    }), context);
}
</code>```

Any help is appreciated.

EDIT: I was overriding the Equals and ToString in Playlist partial class. After I removed those, it started working.

答: If you fetched the data using a different context from the one you are trying to add/delete with, you will get the exception you posted. Either dispose of the original context you fetched the data with or explicitly call Detach on the item you are calling AddItem/DeleteObject on.</p>

Body:
I'm trying to replace an object with a new one and am getting the mentioned exception. I've tried several combination and can't get around it.

I have a Playlist that has Items (the Items has another nested object, but I'm leaving it out to help make my question clearer. The user can change which items are in the playlist.

 if (playlistChanged)
{
    // remove selectedForRemoval
    IEnumerable<PlaylistItemViewModel> nonSelectedItems = selectedDisplayTemplates.Where(pivm => pivm.IsSelectedForRemoval);
    foreach (temViewModel ivm in nonSelectedItems)
    {
        context.DeleteObject(ivm.Model);
    }

    // clear out and remove old items
    foreach (Item item in playlist.PlaylistItems)
    {
        context.DeleteObject(item);
    }

    playlist.PlaylistItems.Clear();

    // add the selectedItem(s) to the playlist
    // these items can be from the Media, or other tables
    // so are newly created in code on the client
    foreach (ItemViewModel ivm in selectedItems)
    {
        playlist.Items.Add(ivm.PlaylistItemModel);
        context.AddToItems(ivm.PlaylistItemModel);
    }
    context.BeginSaveChanges(SaveChangesOptions.Batch, new AsyncCallback((iar) =>
    {
        try
        {
            // Callback method for the async request, retrieves the status of the requested action
            DataServiceResponse response = context.EndSaveChanges(iar);
        }
        catch (DataServiceRequestException)
        {
            throw;
        }
    }), context);
}

Any help is appreciated.

EDIT: I was overriding the Equals and ToString in Playlist partial class. After I removed those, it started working.


问:
Unexpected result in Java (floating to integer)
I have a problem with this

```<code>System.out.print((9/5) * 3);
</code>```

I expects the result 5.4 but it returns 3. Why is this happening?

答:
9/5 is evaluated in integer arithmetic, so it's equal to 1.

Writing 9.0 / 5 * 3 is a common fix. (Promoting one of the coefficients in the term to a double forces the evaluation to take place in double precision floating point.)

Body:
I have a problem with this

System.out.print((9/5) * 3);

I expects the result 5.4 but it returns 3. Why is this happening?


问:
Ionic notifications information
I'm trying to obtain information about a sent notification. But i don't know exactly how to proceed. This is my javascript code:

```<code>    function obtenerInformacion(uuid){
        var xhr = new XMLHttpRequest();
        xhr.withCredentials = true;

        xhr.addEventListener("readystatechange", function () {
          if (this.readyState === 4) {
            console.log(this.responseText);

      }
    });

    xhr.open("POST", "https://api.ionic.io/push/notifications/"+uuid);
    xhr.setRequestHeader("Access-Control-Allow-Origin","*");
    xhr.setRequestHeader("Access-Control-Allow-Methods","GET,PUT,POST,DELETE,OPTIONS");
    xhr.setRequestHeader("Access-Control-Allow-Headers","Content-Type");
    xhr.setRequestHeader("content-type", "application/json");
    xhr.setRequestHeader("authorization", "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiIxN2FlYWZlMC02ZTg4LTQ3NDItOWMxMC04ZTczY2IwNWU4NGMifQ.n25i9yTWdqFauTd6xnfW0Uats_x7EvnB42KhoFu8E04");
    xhr.send();
}
</code>```

I'm getting this error:error

Sorry for my english.

EDIT: Fixed. Apparently the request had to be made by GET

```<code>xhr.open("GET", "https://api.ionic.io/push/notifications/"+uuid);

xhr.setRequestHeader("content-type", "application/json");
xhr.setRequestHeader("authorization", "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiIxN2FlYWZlMC02ZTg4LTQ3NDItOWMxMC04ZTczY2IwNWU4NGMifQ.n25i9yTWdqFauTd6xnfW0Uats_x7EvnB42KhoFu8E04");
xhr.send();
</code>```

Thank you very much to all

答:
The Access-Control-Allow-Headers configuration needs to be set by the server when it sends to message to you (the client).

See this reply for more info.

Title: Ionic notifications information

Body:
I'm trying to obtain information about a sent notification. But i don't know exactly how to proceed. This is my javascript code:

    function obtenerInformacion(uuid){
        var xhr = new XMLHttpRequest();
        xhr.withCredentials = true;

        xhr.addEventListener("readystatechange", function () {
          if (this.readyState === 4) {
            console.log(this.responseText);

      }
    });

    xhr.open("POST", "https://api.ionic.io/push/notifications/"+uuid);
    xhr.setRequestHeader("Access-Control-Allow-Origin","*");
    xhr.setRequestHeader("Access-Control-Allow-Methods","GET,PUT,POST,DELETE,OPTIONS");
    xhr.setRequestHeader("Access-Control-Allow-Headers","Content-Type");
    xhr.setRequestHeader("content-type", "application/json");
    xhr.setRequestHeader("authorization", "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiIxN2FlYWZlMC02ZTg4LTQ3NDItOWMxMC04ZTczY2IwNWU4NGMifQ.n25i9yTWdqFauTd6xnfW0Uats_x7EvnB42KhoFu8E04");
    xhr.send();
}

I'm getting this error:error

Sorry for my english.

EDIT: Fixed. Apparently the request had to be made by GET

xhr.open("GET", "https://api.ionic.io/push/notifications/"+uuid);

xhr.setRequestHeader("content-type", "application/json");
xhr.setRequestHeader("authorization", "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiIxN2FlYWZlMC02ZTg4LTQ3NDItOWMxMC04ZTczY2IwNWU4NGMifQ.n25i9yTWdqFauTd6xnfW0Uats_x7EvnB42KhoFu8E04");
xhr.send();

Thank you very much to all


问:
Is importing a file good in Python
I have around 80 lines of a function in a file. I need the same functionality in another file so I am currently importing the other file for the function.

My question is that in terms of running time on a machine which technique would be better :- importing the complete file and running the function or copying the function as it is and run it from same package.

I know it won't matter in a large sense but I want to learn it in the sense that if we are making a large project is it better to import a complete file in Python or just add the function in the current namespace.....

答: Importing is how you're supposed to do it. That's why it's possible. Performance is a complicated question, but in general it really doesn't matter. People who really, really need performance, and can't be satisfied by just fixing the basic algorithm, are not using Python in the first place. :) (At least not for the tiny part of the project where the performance really matters. ;) )</p>

Title: Is importing a file good in Python


Title: Unexpected result in Java (floating to integer)

Body: System.out.print((9.0/5) * 3);


问:
Qt C++ - Delete row in QTableWidget
I'm new to Qt and I want to do this

```<code>void MainWindow::test()
{
    for (int i = 0 ; i < 5 ; ++i)
    {
        ui->tableWidget->setRowCount(ui->tableWidget->rowCount() + 1);
        ui->tableWidget->setItem(i,0, new QTableWidgetItem(QString("1")));
        ui->tableWidget->setItem(i,1, new QTableWidgetItem(QString("1")));
    }

    QPushButton *listB = new QPushButton[5];
    QHBoxLayout *listLayout = new QHBoxLayout[5];
    QWidget* listWidget = new QWidget[5];

    for (int i = 0 ; i <  5 ; ++i)
    {
        ui->tableWidget->setRowCount(ui->tableWidget->rowCount() + 1);
        listB[i].setText("OK");
        listLayout[i].addWidget(listB + i);
        listWidget[i].setLayout(listLayout + i);
        ui->tableWidget->setCellWidget(i,0,listWidget + i);
        connect(listB + i , &QPushButton::clicked, [=]{ui->tableWidget->removeRow(i);});
    }

}
</code>```

I want to add a QPushButton in each row of QTableWidget and when i click to this Button, the corresponding row will disappear. However whenever i click to Button it cause "Segmentation Error".

Please point out what wrong with my code and what is the solution for my program.
Thanks.

答:
The problem is caused by the arrays it has generated, it seems that deleting an element from the array causes problems with the index.</p>

```<code>void MainWindow::test()
{
    ui->tableWidget->setColumnCount(2);

    for (int i = 0 ; i < 5 ; ++i)
    {
        ui->tableWidget->setRowCount(ui->tableWidget->rowCount() + 1);
        ui->tableWidget->setItem(i,0, new QTableWidgetItem(QString("1")));
        ui->tableWidget->setItem(i,1, new QTableWidgetItem(QString("1")));
    }

    for (int i = 0 ; i <  5 ; ++i)
    {
        QPushButton *listB = new QPushButton;
        QHBoxLayout *listLayout = new QHBoxLayout;
        QWidget* listWidget = new QWidget;
        ui->tableWidget->setRowCount(ui->tableWidget->rowCount() + 1);
        listB->setText("OK");
        listLayout->addWidget(listB);
        listWidget->setLayout(listLayout);
        ui->tableWidget->setCellWidget(i,0,listWidget);
        connect(listB, &QPushButton::clicked, [=]{ui->tableWidget->removeRow(i);});
    }

}
</code>```

Title: Qt C++ - Delete row in QTableWidget

Body:
I'm new to Qt and I want to do this

void MainWindow::test()
{
    for (int i = 0 ; i < 5 ; ++i)
    {
        ui->tableWidget->setRowCount(ui->tableWidget->rowCount() + 1);
        ui->tableWidget->setItem(i,0, new QTableWidgetItem(QString("1")));
        ui->tableWidget->setItem(i,1, new QTableWidgetItem(QString("1")));
    }

    QPushButton *listB = new QPushButton[5];
    QHBoxLayout *listLayout = new QHBoxLayout[5];
    QWidget* listWidget = new QWidget[5];

    for (int i = 0 ; i <  5 ; ++i)
    {
        ui->tableWidget->setRowCount(ui->tableWidget->rowCount() + 1);
        listB[i].setText("OK");
        listLayout[i].addWidget(listB + i);
        listWidget[i].setLayout(listLayout + i);
        ui->tableWidget->setCellWidget(i,0,listWidget + i);
        connect(listB + i , &QPushButton::clicked, [=]{ui->tableWidget->removeRow(i);});
    }

}

I want to add a QPushButton in each row of QTableWidget and when i click to this Button, the corresponding row will disappear. However whenever i click to Button it cause "Segmentation Error".

Please point out what wrong with my code and what is the solution for my program.
Thanks.

Body:
The problem is caused by the arrays it has generated, it seems that deleting an element from the array causes problems with the index.

void MainWindow::test()
{
    ui->tableWidget->setColumnCount(2);

    for (int i = 0 ; i < 5 ; ++i)
    {
        ui->tableWidget->setRowCount(ui->tableWidget->rowCount() + 1);
        ui->tableWidget->setItem(i,0, new QTableWidgetItem(QString("1")));
        ui->tableWidget->setItem(i,1, new QTableWidgetItem(QString("1")));
    }

    for (int i = 0 ; i <  5 ; ++i)
    {
        QPushButton *listB = new QPushButton;
        QHBoxLayout *listLayout = new QHBoxLayout;
        QWidget* listWidget = new QWidget;
        ui->tableWidget->setRowCount(ui->tableWidget->rowCount() + 1);
        listB->setText("OK");
        listLayout->addWidget(listB);
        listWidget->setLayout(listLayout);
        ui->tableWidget->setCellWidget(i,0,listWidget);
        connect(listB, &QPushButton::clicked, [=]{ui->tableWidget->removeRow(i);});
    }

}


问:
laravel 5.0 delete and edit in database
How can I delete or edit things from my database in Laravel 5.0 with the public function destroy and edit?

This is my library, here I want to delete or update something from my database

```<code>@foreach ($allJobs as $job)
    <tr>
        <td><img src="{{$job->selected_icon}}" width="50" /> </td>
        <td>{{$job->jobtitle_de}}</td>
        <td>{{$job->location}}</td>
        <td><img src="{{$job->selected_image}}" width="100" /></td>
        <td>{{$job->workinghours}}</td>
        <td>{{$job->grey_header_de}}</td>
        <td>{{$job->date}}</td>
        <td>
            <a href=""><button>Edit</button></a> <a href="/delete">
            <button>Delete</button></a></td>
            <!--<td> <button type="delete" name="button"></button>-->
        <td>
        </td>
    </tr>
@endforeach
</code>```

答:
In your controller (I will assume that you have created), implements this two functions.

```
public function edit($id) {
    // Create a var called `$job` and uses the function `find()` passing into the $id that you clicked before

    $job = Job::find($id);

    // Return a view with the object that you found into a edit view
    return view('jobs.edit', [
        'job' => $job
    ]);
}

public function destroy($id) {
    // Use the function `find()` passing into the $id that you clicked before and that use the delete method to delete the job
    Job::find($id)->delete();

    // Returning into a route that contains the jobs, probably
    return redirect()->route('jobs');
}

```

Read the docs https://laravel.com/docs/5.4/controllers

Title: laravel 5.0 delete and edit in database

Body:
How can I delete or edit things from my database in Laravel 5.0 with the public function destroy and edit?

This is my library, here I want to delete or update something from my database

@foreach ($allJobs as $job)

        selected_icon}}" width="50" />
        {{$job->jobtitle_de}}
        {{$job->location}}
        selected_image}}" width="100" />
        {{$job->workinghours}}
        {{$job->grey_header_de}}
        {{$job->date}}

            <button>Edit</button>
            <button>Delete</button>

@endforeach

Body:
In your controller (I will assume that you have created), implements this two functions.

public function edit($id) {
    // Create a var called `$job` and uses the function `find()` passing into the $id that you clicked before

    $job = Job::find($id);

    // Return a view with the object that you found into a edit view
    return view('jobs.edit', [
        'job' => $job
    ]);
}

public function destroy($id) {
    // Use the function `find()` passing into the $id that you clicked before and that use the delete method to delete the job
    Job::find($id)->delete();

    // Returning into a route that contains the jobs, probably
    return redirect()->route('jobs');
}

Read the docs https://laravel.com/docs/5.4/controllers


问:
JavaScript at bottom/top of web page?
I was just using the plugin "Yslow" for Mozilla Firefox, and it told me that I should put JavaScript at the bottom.  I have heard this before but haven't really thought about it too much.  Is there really an advantage in putting JavaScript at the bottom of a web page compared to the top?</p>

答: Placing scripts at the bottom of the  element improves the display speed, because script compilation slows down the display.</p>

Title: JavaScript at bottom/top of web page?


问:
React js: Invariant Violation: processUpdates() when rendering a table with a different number of child rows
I am getting the following error when my react component is re-rendered after a click event:

```<code>Uncaught Error: Invariant Violation: processUpdates(): Unable to find child 2 of element. This probably means the DOM was unexpectedly mutated ...
</code>```

This only happens when my table has a different number of rows than the previously rendered version. For example:

```<code>/** @jsx React.DOM */

React = require('react');

var _ = require("underscore");

var testComp = React.createClass({

  getInitialState: function () {
    return {
      collapsed: false
    };
  },

  handleCollapseClick: function(){
    this.setState({collapsed: !this.state.collapsed});
  },

  render: function() {

    var rows = [
      <tr onClick={this.handleCollapseClick}><th>Header 1</th><th>Header 2</th><th>Header 3</th></tr>
    ];

    if(!this.state.collapsed){
      rows.push(<tr><th>Row1 1</th><th>Row1 2</th><th>Row1 3</th></tr>);
    }

    rows.push(<tr><th>Footer 1</th><th>Footer 2</th><th>Footer 3</th></tr>);

    return  <div>
                <table>
                    {rows}
                </table>
            </div>
  }

});

module.exports = testComp
</code>```

If I render different content, but with the same number of rows, I don't get the error, so if I update the if statement to:

```<code>if(!this.state.collapsed){
  rows.push(<tr><th>Row1 1</th><th>Row1 2</th><th>Row1 3</th></tr>);
}else{
  rows.push(<tr><th>Row2 1</th><th>Row2 2</th><th>Row2 3</th></tr>);
}
</code>```

... everything works.

Do I need to force react to re-render the entire component in this case, instead of just the 'changed' elements?

答:
In My case the fix is to remove spaces in Table render from

```<code><tbody> {rows} </tbody>
</code>```

to

```<code><tbody>{rows}</tbody>
</code>```

Body:
I am getting the following error when my react component is re-rendered after a click event:

Uncaught Error: Invariant Violation: processUpdates(): Unable to find child 2 of element. This probably means the DOM was unexpectedly mutated ...

This only happens when my table has a different number of rows than the previously rendered version. For example:

/** @jsx React.DOM */

React = require('react');

var _ = require("underscore");

var testComp = React.createClass({

  getInitialState: function () {
    return {
      collapsed: false
    };
  },

  handleCollapseClick: function(){
    this.setState({collapsed: !this.state.collapsed});
  },

  render: function() {

    var rows = [

Header 1	Header 2	Header 3

    ];

    if(!this.state.collapsed){
      rows.push(
Row1 1	Row1 2	Row1 3
);
    }

    rows.push(
Footer 1	Footer 2	Footer 3
);

    return

                    {rows}

  }

});

module.exports = testComp

If I render different content, but with the same number of rows, I don't get the error, so if I update the if statement to:

if(!this.state.collapsed){
  rows.push(
Row1 1	Row1 2	Row1 3
);
}else{
  rows.push(
Row2 1	Row2 2	Row2 3
);
}

... everything works.

Do I need to force react to re-render the entire component in this case, instead of just the 'changed' elements?

Body:
In My case the fix is to remove spaces in Table render from

<tbody> {rows} </tbody>

to

<tbody>{rows}</tbody>


问:
Android Studio Lower Sound than Original Soundtrack
I simply want to play an audio with mediaPlayer of Android Studio, but the sound which I hear is too lower than original sound track (Genymotion's emulator sound is at max volume)

Any idea?

```<code>ImageButton img_scream1 = (ImageButton) findViewById(R.id.imageButton_scare_1);
    img_scream1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            mediaControl = MediaPlayer.create(java_sounds_scary.this,R.raw.scream1_sound);
            mediaControl.start();
        }
    });
</code>```

答:
```<code>    final MediaPlayer mp = MediaPlayer.create(this, R.raw.sound);

    Button play_button = (Button)this.findViewById(R.id.button);
    play_button.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            Log.v(TAG, "Playing sound...");
            mp.start();
        }
    });
</code>```

Place your sound in res/raw folder.

Run your app in a mobile and check it. sometimes geny motion doesn't not work properly.

Body:
I simply want to play an audio with mediaPlayer of Android Studio, but the sound which I hear is too lower than original sound track (Genymotion's emulator sound is at max volume)

Any idea?

ImageButton img_scream1 = (ImageButton) findViewById(R.id.imageButton_scare_1);
    img_scream1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            mediaControl = MediaPlayer.create(java_sounds_scary.this,R.raw.scream1_sound);
            mediaControl.start();
        }
    });

Body:
    final MediaPlayer mp = MediaPlayer.create(this, R.raw.sound);

    Button play_button = (Button)this.findViewById(R.id.button);
    play_button.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            Log.v(TAG, "Playing sound...");
            mp.start();
        }
    });

Place your sound in res/raw folder.

Run your app in a mobile and check it. sometimes geny motion doesn't not work properly.


问:
Git pull error: unable to create temporary sha1 filename
I've got a small git repo setup with the only real purpose to be able to develop locally on several machines (work, home, laptop). Thus I have one branch and I commit/push once I leave a computer, pull once I sit down at the next. Has worked fine, up to now that is. Now when I pull on my 'live test' machine, I get the following:

```<code>remote: Counting objects: 38, done.
remote: Compressiremote: ng objects: 100% (20/20), done.
remote: Total 20 (delta 17), reused 0 (delta 0)
error: unable to create temporary sha1 filename .git/objects/ed: File exists

fatal: failed to write object
fatal: unpack-objects failed
</code>```

Searching around the net the only real answer I could find was the following: http://marc.info/?l=git&m=122720741928774&w=2 which basically states that this is a bogus error that's on top of the pile and thus says nothing about what really is wrong.

Where do I go from here to find out what is wrong?

Edit: Removed the local copy and re-cloned

答:
I had a similar error, and it was not a permissions problem (I'm the only user of the repository), and none of the gc/repack techniques worked.  Ultimately I just moved aside the old remote repository and pushed a new one.  Fortunately it was quite small.

Liam

Body:
I've got a small git repo setup with the only real purpose to be able to develop locally on several machines (work, home, laptop). Thus I have one branch and I commit/push once I leave a computer, pull once I sit down at the next. Has worked fine, up to now that is. Now when I pull on my 'live test' machine, I get the following:

remote: Counting objects: 38, done.
remote: Compressiremote: ng objects: 100% (20/20), done.
remote: Total 20 (delta 17), reused 0 (delta 0)
error: unable to create temporary sha1 filename .git/objects/ed: File exists

fatal: failed to write object
fatal: unpack-objects failed

Searching around the net the only real answer I could find was the following: http://marc.info/?l=git&m=122720741928774&w=2 which basically states that this is a bogus error that's on top of the pile and thus says nothing about what really is wrong.

Where do I go from here to find out what is wrong?

Edit: Removed the local copy and re-cloned


问:
Why min({1},{0}) returns {1}
min() function should return the smallest of the numbers given. Then why

```<code>min({0},{1})
</code>```

returns {0}, while

```<code>min({1},{0})
</code>```

returns {1}?

答:
In python sets are compared based on whether or not one is a subset of the other.

None is a subset of the other, so < gives False in all cases, so the first one is returned.

So {1}<{0} gives False just like {2}<{1} gives False and {2}<{3,4,5} gives False.
However {1,2}<{1,3,2} gives True.
This means there is no total order defined on sets.

Title: Why min({1},{0}) returns {1}

Body:
min() function should return the smallest of the numbers given. Then why

min({0},{1})

returns {0}, while

min({1},{0})

returns {1}?


问:
Swift 3, iOS 10+, xCode 8.3+, Quickblox - Toggle full screen remote stream while keeping aspect ratio/video res
I am working with a webRTC remote video stream and attaching the remote session to this:

```<code>@IBOutlet weak var remoteVideoElement: QBRTCRemoteVideoView!
</code>```

What I want to have happen is when a user taps the outlet above, the remote stream fill the entire window. When the user taps it again, it will return to its place as it was in the layout normally. For the most part it works fine except I cannot maintain the correct aspect ratio or screen resolution of the remote video stream. Can someone help me figure out the right way to get the desired effect?

Here is my code:

```<code>var isExpanded = Bool()
var videoPlayerViewCenter = CGPoint()

override func viewDidLoad() {
        super.viewDidLoad()
        isExpanded = false

        let toggleFullScreen = UITapGestureRecognizer(target: self, action: #selector (self.toggleFullScreenRemoteVideo(sender:)))
        self.view.addGestureRecognizer(toggleFullScreen)
}

func toggleFullScreenRemoteVideo(sender: QBRTCRemoteVideoView) {
        if !isExpanded {
            // GO FULL SCREEN
            UIView.animate(withDuration: 0.8, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: .curveEaseOut, animations: {
                self.videoPlayerViewCenter = self.remoteVideoElement.center
                self.view.bringSubview(toFront: self.modalShadeBackground)
                self.view.bringSubview(toFront: self.remoteVideoElement)
                self.remoteVideoElement.frame = CGRect(x: 0, y: 0, width: self.view.frame.height, height: self.view.frame.width)
                self.remoteVideoElement.frame = AVMakeRect(aspectRatio: (self.remoteVideoElement.layer.preferredFrameSize()), insideRect: self.remoteVideoElement.frame)
                self.remoteVideoElement.contentMode = .scaleAspectFit
                self.remoteVideoElement.frame = UIScreen.main.bounds
                self.remoteVideoElement.center = self.view.center
                self.remoteVideoElement.transform = CGAffineTransform(rotationAngle: CGFloat(Double.pi / 2))
                self.remoteVideoElement.layoutSubviews()
            }, completion: nil)
        } else {
            // REVERT BACK TO ORIGINAL CONTRAINTS IN THE LAYOUT
            UIView.animate(withDuration: 0.8, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: .curveEaseOut, animations: {
                self.remoteVideoElement.transform = CGAffineTransform.identity
                self.remoteVideoElement.center = self.videoPlayerViewCenter
                self.view.sendSubview(toBack: self.remoteVideoElement)
                self.view.sendSubview(toBack: self.modalShadeBackground)
                self.remoteVideoElement.frame = AVMakeRect(aspectRatio: (self.remoteVideoElement.layer.preferredFrameSize()), insideRect: self.remoteVideoElement.frame)
                self.remoteVideoElement.layoutSubviews()
            }, completion: nil)
        }
        isExpanded = !isExpanded
    }
</code>```

答:
I am not sure about QBRTCRemoteVideoView but I solved similar issue with video streaming
by getting the ratio of my video image and convert it to the rect of my video view.
basically like this:

```<code>let xScale = maxImageDrawingArea.size.width / imageSize.width
let yScale = maxImageDrawingArea.size.height / imageSize.height
let scaleFactor = xScale < yScale ? xScale : yScale;
</code>```

then get your view size by

```<code>let height = maxImageDrawingArea.size.height * scaleFactor
let width = maxImageDrawingArea.size.width * scaleFactor
</code>```

then use this height and width to draw your video holder in your case remoteVideoElement

Update me how did it go;

Good luck,

Body:
I am working with a webRTC remote video stream and attaching the remote session to this:

@IBOutlet weak var remoteVideoElement: QBRTCRemoteVideoView!

What I want to have happen is when a user taps the outlet above, the remote stream fill the entire window. When the user taps it again, it will return to its place as it was in the layout normally. For the most part it works fine except I cannot maintain the correct aspect ratio or screen resolution of the remote video stream. Can someone help me figure out the right way to get the desired effect?

Here is my code:

var isExpanded = Bool()
var videoPlayerViewCenter = CGPoint()

override func viewDidLoad() {
        super.viewDidLoad()
        isExpanded = false

        let toggleFullScreen = UITapGestureRecognizer(target: self, action: #selector (self.toggleFullScreenRemoteVideo(sender:)))
        self.view.addGestureRecognizer(toggleFullScreen)
}

func toggleFullScreenRemoteVideo(sender: QBRTCRemoteVideoView) {
        if !isExpanded {
            // GO FULL SCREEN
            UIView.animate(withDuration: 0.8, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: .curveEaseOut, animations: {
                self.videoPlayerViewCenter = self.remoteVideoElement.center
                self.view.bringSubview(toFront: self.modalShadeBackground)
                self.view.bringSubview(toFront: self.remoteVideoElement)
                self.remoteVideoElement.frame = CGRect(x: 0, y: 0, width: self.view.frame.height, height: self.view.frame.width)
                self.remoteVideoElement.frame = AVMakeRect(aspectRatio: (self.remoteVideoElement.layer.preferredFrameSize()), insideRect: self.remoteVideoElement.frame)
                self.remoteVideoElement.contentMode = .scaleAspectFit
                self.remoteVideoElement.frame = UIScreen.main.bounds
                self.remoteVideoElement.center = self.view.center
                self.remoteVideoElement.transform = CGAffineTransform(rotationAngle: CGFloat(Double.pi / 2))
                self.remoteVideoElement.layoutSubviews()
            }, completion: nil)
        } else {
            // REVERT BACK TO ORIGINAL CONTRAINTS IN THE LAYOUT
            UIView.animate(withDuration: 0.8, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: .curveEaseOut, animations: {
                self.remoteVideoElement.transform = CGAffineTransform.identity
                self.remoteVideoElement.center = self.videoPlayerViewCenter
                self.view.sendSubview(toBack: self.remoteVideoElement)
                self.view.sendSubview(toBack: self.modalShadeBackground)
                self.remoteVideoElement.frame = AVMakeRect(aspectRatio: (self.remoteVideoElement.layer.preferredFrameSize()), insideRect: self.remoteVideoElement.frame)
                self.remoteVideoElement.layoutSubviews()
            }, completion: nil)
        }
        isExpanded = !isExpanded
    }

Body:
I am not sure about QBRTCRemoteVideoView but I solved similar issue with video streaming
by getting the ratio of my video image and convert it to the rect of my video view.
basically like this:

let xScale = maxImageDrawingArea.size.width / imageSize.width
let yScale = maxImageDrawingArea.size.height / imageSize.height
let scaleFactor = xScale < yScale ? xScale : yScale;

then get your view size by

let height = maxImageDrawingArea.size.height * scaleFactor
let width = maxImageDrawingArea.size.width * scaleFactor

then use this height and width to draw your video holder in your case remoteVideoElement

Update me how did it go;

Good luck,


问:
How to trigger keyboard enter event to add indentation on next line of textarea
I have a html text-area when user put colon(:) and press enter there should be indentation on next line of text-area

My code

<textarea id="yourcode" cols="40" rows="10" class="form-control"></textarea>
```

<p>What i have tried</p>

<pre class="lang-js prettyprint-override"><code>$('#yourcode').keypress(function(e) {
    if(e.keyCode == 58) {
        if(e.keyCode == 13 ) {
            $(this).val(
                $(this).val().substring(0, start)
                + "\t"
                + $(this).val().substring(end)
            );
        }
    }
});
</code>```

答:
$('#yourcode').keypress(function(e){
 if(e.keyCode == 13){
   val = $(this).val();
   if(val.substr(val.length - 1) == ":"){
        console.log(": after enter")
        // your code here
        $('textarea').val(val.replace(/:/g, ':\n') + "   ");
   }
 }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<textarea id="yourcode" cols="40" rows="10" class="form-control">
 </textarea></code>```

Body:
I have a html text-area when user put colon(:) and press enter there should be indentation on next line of text-area

My code

<textarea id="yourcode" cols="40" rows="10" class="form-control"></textarea>

What i have tried

$('#yourcode').keypress(function(e) {
    if(e.keyCode == 58) {
        if(e.keyCode == 13 ) {
            $(this).val(
                $(this).val().substring(0, start)
                + "\t"
                + $(this).val().substring(end)
            );
        }
    }
});

Body:
$('#yourcode').keypress(function(e){
 if(e.keyCode == 13){
   val = $(this).val();
   if(val.substr(val.length - 1) == ":"){
        console.log(": after enter")
        // your code here
        $('textarea').val(val.replace(/:/g, ':\n') + "   ");
   }
 }
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<textarea id="yourcode" cols="40" rows="10" class="form-control">
 </textarea>


问:
Freeradius ended itself and could not start
I installed Freeradius on Jessie Debian. First it was ok - working. But then, I don't know why it stopped and I can't start it. I tryed reinstall, but there is same problem. Here is status and starting attempt.

```<code> radius@debian:~$ /etc/init.d/freeradius status
    ● freeradius.service - LSB: Radius Daemon
       Loaded: loaded (/etc/init.d/freeradius)
       Active: failed (Result: exit-code) since Thu 2017-06-08 11:12:02 BST; 32min ago
</code>```

and after try to start

```<code>radius@debian:~$ /etc/init.d/freeradius start
[....] Starting freeradius (via systemctl): freeradius.serviceFailed to start freeradius.service: Access denied
 failed!
</code>```

What is more in Ubuntu 12.04 I have same problem.

I used:

```<code>radius@debian:~$ sudo freeradius -XC
freeradius: FreeRADIUS Version 2.2.5, for host x86_64-pc-linux-gnu, built on Oct 24 2014 at 02:05:28
Copyright (C) 1999-2013 The FreeRADIUS server project and contributors.
There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE.
You may redistribute copies of FreeRADIUS under the terms of the
GNU General Public License.
For more information about these matters, see the file named COPYRIGHT.
Starting - reading configuration files ...
including configuration file /etc/freeradius/radiusd.conf
Configuration file /etc/freeradius/radiusd.conf is globally writable.  Refusing to start due to insecure configuration.
Errors reading or parsing /etc/freeradius/radiusd.conf
</code>```

and:

```<code>radius@debian:~$ sudo freeradius -lstdout -xxx -fC
Fri Jun  9 06:22:07 2017 : Info: freeradius: FreeRADIUS Version 2.2.5, for host x86_64-pc-linux-gnu, built on Oct 24 2014 at 02:05:28
Fri Jun  9 06:22:07 2017 : Debug: Server was built with:
Fri Jun  9 06:22:07 2017 : Debug:   accounting
Fri Jun  9 06:22:07 2017 : Debug:   authentication
Fri Jun  9 06:22:07 2017 : Debug:  WITH_DHCP
Fri Jun  9 06:22:07 2017 : Debug:  WITH_VMPS
Fri Jun  9 06:22:07 2017 : Debug: Server core libs:
Fri Jun  9 06:22:07 2017 : Debug:   ssl: OpenSSL 1.0.1t  3 May 2016
Fri Jun  9 06:22:07 2017 : Info: Copyright (C) 1999-2013 The FreeRADIUS server project and contributors.
Fri Jun  9 06:22:07 2017 : Info: There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A
Fri Jun  9 06:22:07 2017 : Info: PARTICULAR PURPOSE.
Fri Jun  9 06:22:07 2017 : Info: You may redistribute copies of FreeRADIUS under the terms of the
Fri Jun  9 06:22:07 2017 : Info: GNU General Public License.
Fri Jun  9 06:22:07 2017 : Info: For more information about these matters, see the file named COPYRIGHT.
Fri Jun  9 06:22:07 2017 : Info: Starting - reading configuration files ...
Fri Jun  9 06:22:07 2017 : Debug: including configuration file /etc/freeradius/radiusd.conf
Fri Jun  9 06:22:07 2017 : Error: Configuration file /etc/freeradius/radiusd.conf is globally writable.  Refusing to start due to insecure configuration.
Fri Jun  9 06:22:07 2017 : Error: Errors reading or parsing /etc/freeradius/radiusd.conf
</code>```

答:
Run freeradius with sudo freeradius -XC, it'll print out the reason why it cannot start (and then exit).

if sudo freeradius -XC reports no errors, it's likely a permissions issue.

Run sudo freeradius -lstdout -xxx -fc, FreeRADIUS will then seuid()/segid() down to the use configured in radiusd.conf.

Body:
I installed Freeradius on Jessie Debian. First it was ok - working. But then, I don't know why it stopped and I can't start it. I tryed reinstall, but there is same problem. Here is status and starting attempt.

 radius@debian:~$ /etc/init.d/freeradius status
    ● freeradius.service - LSB: Radius Daemon
       Loaded: loaded (/etc/init.d/freeradius)
       Active: failed (Result: exit-code) since Thu 2017-06-08 11:12:02 BST; 32min ago

and after try to start

radius@debian:~$ /etc/init.d/freeradius start
[....] Starting freeradius (via systemctl): freeradius.serviceFailed to start freeradius.service: Access denied
 failed!

What is more in Ubuntu 12.04 I have same problem.

I used:

radius@debian:~$ sudo freeradius -XC
freeradius: FreeRADIUS Version 2.2.5, for host x86_64-pc-linux-gnu, built on Oct 24 2014 at 02:05:28
Copyright (C) 1999-2013 The FreeRADIUS server project and contributors.
There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE.
You may redistribute copies of FreeRADIUS under the terms of the
GNU General Public License.
For more information about these matters, see the file named COPYRIGHT.
Starting - reading configuration files ...
including configuration file /etc/freeradius/radiusd.conf
Configuration file /etc/freeradius/radiusd.conf is globally writable.  Refusing to start due to insecure configuration.
Errors reading or parsing /etc/freeradius/radiusd.conf

and:

radius@debian:~$ sudo freeradius -lstdout -xxx -fC
Fri Jun  9 06:22:07 2017 : Info: freeradius: FreeRADIUS Version 2.2.5, for host x86_64-pc-linux-gnu, built on Oct 24 2014 at 02:05:28
Fri Jun  9 06:22:07 2017 : Debug: Server was built with:
Fri Jun  9 06:22:07 2017 : Debug:   accounting
Fri Jun  9 06:22:07 2017 : Debug:   authentication
Fri Jun  9 06:22:07 2017 : Debug:  WITH_DHCP
Fri Jun  9 06:22:07 2017 : Debug:  WITH_VMPS
Fri Jun  9 06:22:07 2017 : Debug: Server core libs:
Fri Jun  9 06:22:07 2017 : Debug:   ssl: OpenSSL 1.0.1t  3 May 2016
Fri Jun  9 06:22:07 2017 : Info: Copyright (C) 1999-2013 The FreeRADIUS server project and contributors.
Fri Jun  9 06:22:07 2017 : Info: There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A
Fri Jun  9 06:22:07 2017 : Info: PARTICULAR PURPOSE.
Fri Jun  9 06:22:07 2017 : Info: You may redistribute copies of FreeRADIUS under the terms of the
Fri Jun  9 06:22:07 2017 : Info: GNU General Public License.
Fri Jun  9 06:22:07 2017 : Info: For more information about these matters, see the file named COPYRIGHT.
Fri Jun  9 06:22:07 2017 : Info: Starting - reading configuration files ...
Fri Jun  9 06:22:07 2017 : Debug: including configuration file /etc/freeradius/radiusd.conf
Fri Jun  9 06:22:07 2017 : Error: Configuration file /etc/freeradius/radiusd.conf is globally writable.  Refusing to start due to insecure configuration.
Fri Jun  9 06:22:07 2017 : Error: Errors reading or parsing /etc/freeradius/radiusd.conf


问:
Match conditions and latest date from array
```<code>db.chat.find().pretty().limit(3)
{
    "_id" : ObjectId("593921425ccc8150f35e7662"),
    "user1" : 1,
    "user2" : 2,
    "messages" : [
        {
            "sender" : 1,
            "datetime" : ISODate("2017-06-08T10:04:50Z"),
            "body" : "hiii 0"
        },
        {
            "sender" : 2,
            "datetime" : ISODate("2017-06-09T10:04:50Z"),
            "body" : "hiii 1"
        },
        {
            "sender" : 2,
            "datetime" : ISODate("2017-06-10T10:04:50Z"),
            "body" : "hiii 2"
        }
    ]
}
{
    "_id" : ObjectId("593921425ccc8150f35e7663"),
    "user1" : 1,
    "user2" : 3,
    "messages" : [
        {
            "sender" : 1,
            "datetime" : ISODate("2017-06-08T10:04:50Z"),
            "body" : "hiii 0"
        },
        {
            "sender" : 3,
            "datetime" : ISODate("2017-06-09T10:04:50Z"),
            "body" : "hiii 1"
        },
        {
            "sender" : 1,
            "datetime" : ISODate("2017-06-10T10:04:50Z"),
            "body" : "hiii 2"
        }
    ]
}
{
    "_id" : ObjectId("593921425ccc8150f35e7664"),
    "user1" : 1,
    "user2" : 4,
    "messages" : [
        {
            "sender" : 1,
            "datetime" : ISODate("2017-06-08T10:04:50Z"),
            "body" : "hiii 0"
        },
        {
            "sender" : 1,
            "datetime" : ISODate("2017-06-09T10:04:50Z"),
            "body" : "hiii 1"
        },
        {
            "sender" : 4,
            "datetime" : ISODate("2017-06-10T10:04:50Z"),
            "body" : "hiii 2"
        }
    ]
}
</code>```

Above mongodb collection store chats between user1 and user2.
I am looking for a query that will give me result of the latest messages where
message.sender = 1 of each row.

i.e looking for 3 rows as output

```<code>For user1=1 and user2, message hiii0 should only come
For user1=1 and user3, message hiii2 should only come
For user1=1 and user4, message hiii1 should only come
</code>```

ie. just three rows.

db.chat.find({"messages.sender":1}) is giving all the rows while i am looking for just the matched row with the latest datetime.
Please help

Example:

```<code>db.chat.aggregate([
  {$unwind:"$messages"},
  {$match:{"messages.sender":1}},
  {$sort:{"messages.datetime":-1}
])
</code>```

is giving output as

```<code>{ "_id" : ObjectId("593921425ccc8150f35e7663"), "user1" : 1, "user2" : 3, "messages" : { "sender" : 1, "datetime" : ISODate("2017-06-10T10:04:50Z"), "body" : "hiii 2" } }
{ "_id" : ObjectId("593921425ccc8150f35e7664"), "user1" : 1, "user2" : 4, "messages" : { "sender" : 1, "datetime" : ISODate("2017-06-09T10:04:50Z"), "body" : "hiii 1" } }
{ "_id" : ObjectId("593921425ccc8150f35e7662"), "user1" : 1, "user2" : 2, "messages" : { "sender" : 1, "datetime" : ISODate("2017-06-08T10:04:50Z"), "body" : "hiii 0" } }
{ "_id" : ObjectId("593921425ccc8150f35e7663"), "user1" : 1, "user2" : 3, "messages" : { "sender" : 1, "datetime" : ISODate("2017-06-08T10:04:50Z"), "body" : "hiii 0" } }
{ "_id" : ObjectId("593921425ccc8150f35e7664"), "user1" : 1, "user2" : 4, "messages" : { "sender" : 1, "datetime" : ISODate("2017-06-08T10:04:50Z"), "body" : "hiii 0" } }
</code>```

Last two rows are not desirable as its its not the latest record for user1-user2 record.

If i am adding ,{$limit:1} , its giving just one row.

答:
The basic concept here is you need the aggregation framework in order to apply conditions to "filter" the array elements to the conditions. Depending on the available version there are different techniques that can be applied.

In all cases this is the result:

{
    "_id" : ObjectId("593921425ccc8150f35e7664"),
    "user1" : 1,
    "user2" : 4,
    "messages" : {
            "sender" : 1,
            "datetime" : ISODate("2017-06-09T10:04:50Z"),
            "body" : "hiii 1"
    }
}
{
    "_id" : ObjectId("593921425ccc8150f35e7663"),
    "user1" : 1,
    "user2" : 3,
    "messages" : {
            "sender" : 1,
            "datetime" : ISODate("2017-06-10T10:04:50Z"),
            "body" : "hiii 2"
    }
}
{
    "_id" : ObjectId("593921425ccc8150f35e7662"),
    "user1" : 1,
    "user2" : 2,
    "messages" : {
            "sender" : 1,
            "datetime" : ISODate("2017-06-08T10:04:50Z"),
            "body" : "hiii 0"
    }
}
```

<h2>MongoDB 3.4 and above</h2>

<pre class="lang-js prettyprint-override"><code>db.chat.aggregate([
  { "$match": { "messages.sender": 1 } },
  { "$replaceRoot": {
    "newRoot": {
      "$let": {
        "vars": {
          "messages": {
            "$filter": {
              "input": "$messages",
              "as": "m",
              "cond": { "$eq": [ "$$m.sender", 1 ] }
            }
          },
          "maxDate": {
            "$max": {
              "$map": {
                "input": {
                  "$filter": {
                    "input": "$messages",
                    "as": "m",
                    "cond": { "$eq": [ "$$m.sender", 1 ] }
                  }
                },
                "as": "m",
                "in": "$$m.datetime"
              }
            }
          }
        },
        "in": {
          "_id": "$_id",
          "user1": "$user1",
          "user2": "$user2",
          "messages": {
            "$arrayElemAt": [
              { "$filter": {
                "input": "$$messages",
                "as": "m",
                "cond": { "$eq": [ "$$m.datetime", "$$maxDate" ] }
              }},
              0
            ]
          }
        }
      }
    }
  }}
])
</code>```

This is the most efficient way which takes advantage of $replaceRoot which allows us to declare variables to use in the "replaced" structure using $let. The main advantage here is that this requires only "two" pipeline stages.

In order to match the array content you use $filter where you apply the $eq logical operation to test the value of "sender". Where the condition matches, then only the matching array entries are returned.

Using the same $filter so that only the matching "sender" entries are considered, we then want to apply $max over the "filtered" list to the values in "datetime". The $max]5 value is the "latest" date by the conditions.

We want this value so we can later compare the returned results from the "filtered" array to this "maxDate". Which is what happens inside the "in" block of $let where the two "variables" declared earlier for the filtered content and the "maxDate" are again applied to $filter in order to return what should be the only value that met both conditions having the "latest date" as well.

Since you only want "one" result, we use $arrayElemAt to use the value rather than the array.

MongoDB 3.2

db.chat.aggregate([
  { "$match": { "messages.sender": 1 } },
  { "$project": {
    "user1": 1,
    "user2": 1,
    "messages": {
      "$filter": {
        "input": "$messages",
        "as": "m",
        "cond": { "$eq": [ "$$m.sender", 1 ] }
      }
    },
    "maxDate": {
      "$max": {
        "$map": {
          "input": {
            "$filter": {
              "input": "$messages",
              "as": "m",
              "cond": { "$eq": [ "$$m.sender", 1 ] }
            }
          },
          "as": "m",
          "in": "$$m.datetime"
        }
      }
    }
  }},
  { "$project": {
    "user1": 1,
    "user2": 1,
    "messages": {
      "$arrayElemAt":[
       { "$filter": {
         "input": "$messages",
          "as": "m",
          "cond": { "$eq": [ "$$m.datetime", "$maxDate" ] }
       }},
       0
      ]
    }
  }}
])
```

<p>This is basically the same process as described, but without the <code>$replaceRoot</code> pipeline stage, we need to apply in two <code>$project</code> stages. The reason for this is we need the "calculated value" from "maxDate" in order to do that final <code>$filter</code>, and it is not available to do in a compound statement, so instead we split the pipelines. This has a small impact on the overall cost of the operation.</p>

<p>In MongoDB 2.6 to 3.0 we can use most of the technique here except for <code>$arrayElemAt</code> and either accept the  "array" result with a single entry or put in an <code>$unwind</code> stage to deal with what should now be a single entry.</p>

<h2>MongoDB earlier versions</h2>

<pre class="lang-js prettyprint-override"><code>db.chat.aggregate([
  { "$match": { "messages.sender": 1 } },
  { "$unwind": "$messages" },
  { "$match": { "messages.sender": 1 } },
  { "$sort": { "_id": 1, "messages.datetime": -1 } },
  { "$group": {
    "_id": "$_id",
    "user1": { "$first": "$user1" },
    "user2": { "$first": "$user2" },
    "messages": { "$first": "$messages" }
  }}
])
</code>```

Whilst it looks brief, this is by far the most costly operation. Here you must use $unwind in order to apply the conditions to the array elements. This is a very costly process as it produces a copy of each document for each array entry, and is essentially replaced by the modern operators that avoid this in the case of "filtering".

The second $match stage here discards any elements ( now "documents" ) which did not match the "sender" condition. Then we apply a $sort in order to put the "latest" date on top for each document by the _id, hence the two "sort" keys.

Finally we apply $group in order to just refer to the original document, using $first as the accumulator to get the element that is "on top".

Body:
db.chat.find().pretty().limit(3)
{
    "_id" : ObjectId("593921425ccc8150f35e7662"),
    "user1" : 1,
    "user2" : 2,
    "messages" : [
        {
            "sender" : 1,
            "datetime" : ISODate("2017-06-08T10:04:50Z"),
            "body" : "hiii 0"
        },
        {
            "sender" : 2,
            "datetime" : ISODate("2017-06-09T10:04:50Z"),
            "body" : "hiii 1"
        },
        {
            "sender" : 2,
            "datetime" : ISODate("2017-06-10T10:04:50Z"),
            "body" : "hiii 2"
        }
    ]
}
{
    "_id" : ObjectId("593921425ccc8150f35e7663"),
    "user1" : 1,
    "user2" : 3,
    "messages" : [
        {
            "sender" : 1,
            "datetime" : ISODate("2017-06-08T10:04:50Z"),
            "body" : "hiii 0"
        },
        {
            "sender" : 3,
            "datetime" : ISODate("2017-06-09T10:04:50Z"),
            "body" : "hiii 1"
        },
        {
            "sender" : 1,
            "datetime" : ISODate("2017-06-10T10:04:50Z"),
            "body" : "hiii 2"
        }
    ]
}
{
    "_id" : ObjectId("593921425ccc8150f35e7664"),
    "user1" : 1,
    "user2" : 4,
    "messages" : [
        {
            "sender" : 1,
            "datetime" : ISODate("2017-06-08T10:04:50Z"),
            "body" : "hiii 0"
        },
        {
            "sender" : 1,
            "datetime" : ISODate("2017-06-09T10:04:50Z"),
            "body" : "hiii 1"
        },
        {
            "sender" : 4,
            "datetime" : ISODate("2017-06-10T10:04:50Z"),
            "body" : "hiii 2"
        }
    ]
}

Above mongodb collection store chats between user1 and user2.
I am looking for a query that will give me result of the latest messages where
message.sender = 1 of each row.

i.e looking for 3 rows as output

For user1=1 and user2, message hiii0 should only come
For user1=1 and user3, message hiii2 should only come
For user1=1 and user4, message hiii1 should only come

ie. just three rows.

db.chat.find({"messages.sender":1}) is giving all the rows while i am looking for just the matched row with the latest datetime.
Please help

Example:

db.chat.aggregate([
  {$unwind:"$messages"},
  {$match:{"messages.sender":1}},
  {$sort:{"messages.datetime":-1}
])

is giving output as

{ "_id" : ObjectId("593921425ccc8150f35e7663"), "user1" : 1, "user2" : 3, "messages" : { "sender" : 1, "datetime" : ISODate("2017-06-10T10:04:50Z"), "body" : "hiii 2" } }
{ "_id" : ObjectId("593921425ccc8150f35e7664"), "user1" : 1, "user2" : 4, "messages" : { "sender" : 1, "datetime" : ISODate("2017-06-09T10:04:50Z"), "body" : "hiii 1" } }
{ "_id" : ObjectId("593921425ccc8150f35e7662"), "user1" : 1, "user2" : 2, "messages" : { "sender" : 1, "datetime" : ISODate("2017-06-08T10:04:50Z"), "body" : "hiii 0" } }
{ "_id" : ObjectId("593921425ccc8150f35e7663"), "user1" : 1, "user2" : 3, "messages" : { "sender" : 1, "datetime" : ISODate("2017-06-08T10:04:50Z"), "body" : "hiii 0" } }
{ "_id" : ObjectId("593921425ccc8150f35e7664"), "user1" : 1, "user2" : 4, "messages" : { "sender" : 1, "datetime" : ISODate("2017-06-08T10:04:50Z"), "body" : "hiii 0" } }

Last two rows are not desirable as its its not the latest record for user1-user2 record.

If i am adding ,{$limit:1} , its giving just one row.

Body:
The basic concept here is you need the aggregation framework in order to apply conditions to "filter" the array elements to the conditions. Depending on the available version there are different techniques that can be applied.

In all cases this is the result:

{
    "_id" : ObjectId("593921425ccc8150f35e7664"),
    "user1" : 1,
    "user2" : 4,
    "messages" : {
            "sender" : 1,
            "datetime" : ISODate("2017-06-09T10:04:50Z"),
            "body" : "hiii 1"
    }
}
{
    "_id" : ObjectId("593921425ccc8150f35e7663"),
    "user1" : 1,
    "user2" : 3,
    "messages" : {
            "sender" : 1,
            "datetime" : ISODate("2017-06-10T10:04:50Z"),
            "body" : "hiii 2"
    }
}
{
    "_id" : ObjectId("593921425ccc8150f35e7662"),
    "user1" : 1,
    "user2" : 2,
    "messages" : {
            "sender" : 1,
            "datetime" : ISODate("2017-06-08T10:04:50Z"),
            "body" : "hiii 0"
    }
}

MongoDB 3.4 and above

db.chat.aggregate([
  { "$match": { "messages.sender": 1 } },
  { "$replaceRoot": {
    "newRoot": {
      "$let": {
        "vars": {
          "messages": {
            "$filter": {
              "input": "$messages",
              "as": "m",
              "cond": { "$eq": [ "$$m.sender", 1 ] }
            }
          },
          "maxDate": {
            "$max": {
              "$map": {
                "input": {
                  "$filter": {
                    "input": "$messages",
                    "as": "m",
                    "cond": { "$eq": [ "$$m.sender", 1 ] }
                  }
                },
                "as": "m",
                "in": "$$m.datetime"
              }
            }
          }
        },
        "in": {
          "_id": "$_id",
          "user1": "$user1",
          "user2": "$user2",
          "messages": {
            "$arrayElemAt": [
              { "$filter": {
                "input": "$$messages",
                "as": "m",
                "cond": { "$eq": [ "$$m.datetime", "$$maxDate" ] }
              }},
              0
            ]
          }
        }
      }
    }
  }}
])

This is the most efficient way which takes advantage of $replaceRoot which allows us to declare variables to use in the "replaced" structure using $let. The main advantage here is that this requires only "two" pipeline stages.

In order to match the array content you use $filter where you apply the $eq logical operation to test the value of "sender". Where the condition matches, then only the matching array entries are returned.

Using the same $filter so that only the matching "sender" entries are considered, we then want to apply $max over the "filtered" list to the values in "datetime". The $max]5 value is the "latest" date by the conditions.

We want this value so we can later compare the returned results from the "filtered" array to this "maxDate". Which is what happens inside the "in" block of $let where the two "variables" declared earlier for the filtered content and the "maxDate" are again applied to $filter in order to return what should be the only value that met both conditions having the "latest date" as well.

Since you only want "one" result, we use $arrayElemAt to use the value rather than the array.

MongoDB 3.2

db.chat.aggregate([
  { "$match": { "messages.sender": 1 } },
  { "$project": {
    "user1": 1,
    "user2": 1,
    "messages": {
      "$filter": {
        "input": "$messages",
        "as": "m",
        "cond": { "$eq": [ "$$m.sender", 1 ] }
      }
    },
    "maxDate": {
      "$max": {
        "$map": {
          "input": {
            "$filter": {
              "input": "$messages",
              "as": "m",
              "cond": { "$eq": [ "$$m.sender", 1 ] }
            }
          },
          "as": "m",
          "in": "$$m.datetime"
        }
      }
    }
  }},
  { "$project": {
    "user1": 1,
    "user2": 1,
    "messages": {
      "$arrayElemAt":[
       { "$filter": {
         "input": "$messages",
          "as": "m",
          "cond": { "$eq": [ "$$m.datetime", "$maxDate" ] }
       }},
       0
      ]
    }
  }}
])

This is basically the same process as described, but without the $replaceRoot pipeline stage, we need to apply in two $project stages. The reason for this is we need the "calculated value" from "maxDate" in order to do that final $filter, and it is not available to do in a compound statement, so instead we split the pipelines. This has a small impact on the overall cost of the operation.

In MongoDB 2.6 to 3.0 we can use most of the technique here except for $arrayElemAt and either accept the  "array" result with a single entry or put in an $unwind stage to deal with what should now be a single entry.

MongoDB earlier versions

db.chat.aggregate([
  { "$match": { "messages.sender": 1 } },
  { "$unwind": "$messages" },
  { "$match": { "messages.sender": 1 } },
  { "$sort": { "_id": 1, "messages.datetime": -1 } },
  { "$group": {
    "_id": "$_id",
    "user1": { "$first": "$user1" },
    "user2": { "$first": "$user2" },
    "messages": { "$first": "$messages" }
  }}
])

Whilst it looks brief, this is by far the most costly operation. Here you must use $unwind in order to apply the conditions to the array elements. This is a very costly process as it produces a copy of each document for each array entry, and is essentially replaced by the modern operators that avoid this in the case of "filtering".

The second $match stage here discards any elements ( now "documents" ) which did not match the "sender" condition. Then we apply a $sort in order to put the "latest" date on top for each document by the _id, hence the two "sort" keys.

Finally we apply $group in order to just refer to the original document, using $first as the accumulator to get the element that is "on top".


答:
Importing is good cause it helps you manage stuff easily. What if you needed the same function again? Instead of making changes at multiple places, there is just one centralized location - your module.

In case the function is small and you won't need it anywhere else, put it in the file itself.

If it is complex and would require to be used again, separate it and put it inside a module.

Performance should not be your concern here. It should hardly matter. And even if it does, ask yourself - does it matter to you?

Title: Is importing a file good in Python

Body:
I have around 80 lines of a function in a file. I need the same functionality in another file so I am currently importing the other file for the function.

My question is that in terms of running time on a machine which technique would be better :- importing the complete file and running the function or copying the function as it is and run it from same package.

I know it won't matter in a large sense but I want to learn it in the sense that if we are making a large project is it better to import a complete file in Python or just add the function in the current namespace.....


答:
Because these are sets, not numbers.

Moreover, it should return {1}, not 1, as you can see here:

```<code>>>> min({0},{1})
set([0])
>>> min({1},{0})
set([1])
</code>```

That means that it will return the set, not the number.

Title: Why min({1},{0}) returns {1}

Body:
Because these are sets, not numbers.

Moreover, it should return {1}, not 1, as you can see here:

>>> min({0},{1})
set([0])
>>> min({1},{0})
set([1])

That means that it will return the set, not the number.


问:
Acceleo file tags
I'm new to Acceleo and I'm trying to figure out some things about the file tags I can use.
The format I see most commonly is something like that:

```<code>[file (someElement.anotherElement.concat('SomeText.java'), false, 'UTF-8')]
</code>```

1st Question: How can I write some text first and then the text from some element? e.g. Create a file named "SomeTextElement1.java". Where Element1 is a property(or something) from an .ecore file)

2nd Question: How can I take values from 2 different elements?
e.g. Create a file named "Element1-Element2.java". Where Element1 and Element2 taken from an .ecore file.

and 3rd Question: How can I put a file statement inside an [if] statement???
e.g.

```<code>[if (condition) /]
[file (Element1.concat('.java'),false, 'UTF-8')]
[else if (condition)]
[file (Element1.concat('.java'),false, 'UTF-8')]
[if/]
</code>```

I get an error saying file tag is not terminated. But i don't want to terminate it inside the if statement because then i would have to write the same code twice... all i want is to change the filename if a condition is true.. is that possible or not?

Thanks in advance.

答:
In order to generate two different file for a same type on a condition, you have multiple options:

You can do as proposed by @Kellindil in the [file ()] tag

You can also use your solution but by ending the [/file] tag in the [if..] like this:

```<code>[if (condition)]
[file ('name1', ...)]
...
[/file]
[elseif (condition)]
[file ('name2', ...)]
...
[/file]
[/if]
</code>```

Finally, you can also use a guard on the template that owns the code:

```<code>[template public generate_stuff(p : your_type) ? (condition1)]
[file ('name1' ....)]
...
[/file]
[/template]

[comment Yep, the template name is exactly the same, only the condition change/]
[template public generate_stuff(p: your_type) ? (condition2)]
[file ('name2' ....)]
...
[/file]
[/template]
</code>```

This later solution is probably the best as you can clearly 'cut' your code and write a dedicated implementation regarding the condition.

(you could also use a solution that mixes the if solutions with multiple templates)

EDIT>

The last solution can produce the same code, no issues about that

```<code>[template public generate_stuff(p : your_type) ? (condition1)]
[file ('name1' ....)]
[p.body_generation()/]
[/file]
[/template]

[comment Yep, the template name is exactly the same, only the condition change/]
[template public generate_stuff(p: your_type) ? (condition2)]
[file ('name2' ....)]
[p.body_generation()/]
[/file]
[/template]

[template public body_generation(p: your_type)]
...
[/template]
</code>```

Acceleo is a really verbose language, trying to put everything on a single statement is often not a great idea for readability.

Title: Acceleo file tags

Body:
I'm new to Acceleo and I'm trying to figure out some things about the file tags I can use.
The format I see most commonly is something like that:

[file (someElement.anotherElement.concat('SomeText.java'), false, 'UTF-8')]

1st Question: How can I write some text first and then the text from some element? e.g. Create a file named "SomeTextElement1.java". Where Element1 is a property(or something) from an .ecore file)

2nd Question: How can I take values from 2 different elements?
e.g. Create a file named "Element1-Element2.java". Where Element1 and Element2 taken from an .ecore file.

and 3rd Question: How can I put a file statement inside an [if] statement???
e.g.

[if (condition) /]
[file (Element1.concat('.java'),false, 'UTF-8')]
[else if (condition)]
[file (Element1.concat('.java'),false, 'UTF-8')]
[if/]

I get an error saying file tag is not terminated. But i don't want to terminate it inside the if statement because then i would have to write the same code twice... all i want is to change the filename if a condition is true.. is that possible or not?

Thanks in advance.

Body:
In order to generate two different file for a same type on a condition, you have multiple options:

You can do as proposed by @Kellindil in the [file ()] tag

You can also use your solution but by ending the [/file] tag in the [if..] like this:

[if (condition)]
[file ('name1', ...)]
...
[/file]
[elseif (condition)]
[file ('name2', ...)]
...
[/file]
[/if]

Finally, you can also use a guard on the template that owns the code:

[template public generate_stuff(p : your_type) ? (condition1)]
[file ('name1' ....)]
...
[/file]
[/template]

[comment Yep, the template name is exactly the same, only the condition change/]
[template public generate_stuff(p: your_type) ? (condition2)]
[file ('name2' ....)]
...
[/file]
[/template]

This later solution is probably the best as you can clearly 'cut' your code and write a dedicated implementation regarding the condition.

(you could also use a solution that mixes the if solutions with multiple templates)

EDIT>

The last solution can produce the same code, no issues about that

[template public generate_stuff(p : your_type) ? (condition1)]
[file ('name1' ....)]
[p.body_generation()/]
[/file]
[/template]

[comment Yep, the template name is exactly the same, only the condition change/]
[template public generate_stuff(p: your_type) ? (condition2)]
[file ('name2' ....)]
[p.body_generation()/]
[/file]
[/template]

[template public body_generation(p: your_type)]
...
[/template]

Acceleo is a really verbose language, trying to put everything on a single statement is often not a great idea for readability.


问:
Can XPath match on parts of an element's name?
I want to do this:

//*fu

which returns all nodes whose name ends in fu, such as <tarfu /> and <snafu />, but not <fubar />

答:
I struggled with Dimitre Novatchev's answer, it wouldn't return matches. I knew your XPath must have a section telling that "fu" has length 2.

It's advised to have a string-length('fu') to determine what to substring.

For those who aren't able to get results with his answer and they require solution with xpath 1.0:

//*[substring(name(), string-length(name()) - string-length('fu') +1) = 'fu']

Finds matches of elements ending with "fu"

or

//*[substring(name(), string-length(name()) - string-length('Position') +1) = 'Position']

Finds matches to elements ending with "Position"


问:
How do I extract table names from MS Access database using ADO
i tried using this code :

```<code>OleDbConnection c = new OleDbConnection(con);
string SQLS = "SELECT MSysObjects.Name FROM MSysObjects WHERE MSysObjects.Name Not Like 'MsyS*' AND MSysObjects.Type=1 ORDER BY MSysObjects.Name";
OleDbDataAdapter da = new OleDbDataAdapter(SQLS, c);
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
</code>```

But i got  this exception:

Record(s) cannot be read; no read permission on 'MSysObjects'.

Now, i need to transfer the entire ms-access database to mysql programmaticaly, thus i need the database names. How do I work my way around this error?

答:
You can access it like this:

```<code>OleDbConnection conn =
 new OleDbConnection(
    "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +
    "C:\\phycoaide\\phycoaide.mdb;Persist Security Info=False;");

// retrieving schema for a single table
OleDbCommand cmd = new OleDbCommand("taxa", conn);
cmd.CommandType = CommandType.TableDirect;
conn.Open();
OleDbDataReader reader =
 cmd.ExecuteReader(CommandBehavior.SchemaOnly);
DataTable schemaTable = reader.GetSchemaTable();
reader.Close();
conn.Close();
</code>```

See http://harborsparrow.blogspot.com/2009/05/c-code-to-get-schema-of-access-table.html for more details.

EDIT:

Ok, so then you can retrieve all the tables using a solution like this: How do I list all the queries in a MS Access file using OleDB in C#? and then loop through them.

Body:
i tried using this code :

OleDbConnection c = new OleDbConnection(con);
string SQLS = "SELECT MSysObjects.Name FROM MSysObjects WHERE MSysObjects.Name Not Like 'MsyS*' AND MSysObjects.Type=1 ORDER BY MSysObjects.Name";
OleDbDataAdapter da = new OleDbDataAdapter(SQLS, c);
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;

But i got  this exception:

Record(s) cannot be read; no read permission on 'MSysObjects'.

Now, i need to transfer the entire ms-access database to mysql programmaticaly, thus i need the database names. How do I work my way around this error?

Body:
You can access it like this:

OleDbConnection conn =
 new OleDbConnection(
    "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +
    "C:\\phycoaide\\phycoaide.mdb;Persist Security Info=False;");

// retrieving schema for a single table
OleDbCommand cmd = new OleDbCommand("taxa", conn);
cmd.CommandType = CommandType.TableDirect;
conn.Open();
OleDbDataReader reader =
 cmd.ExecuteReader(CommandBehavior.SchemaOnly);
DataTable schemaTable = reader.GetSchemaTable();
reader.Close();
conn.Close();

See http://harborsparrow.blogspot.com/2009/05/c-code-to-get-schema-of-access-table.html for more details.

EDIT:

Ok, so then you can retrieve all the tables using a solution like this: How do I list all the queries in a MS Access file using OleDB in C#? and then loop through them.


问:
IBM MobileFirst Adapters with external libraries
is there any restriction for using external libraries with java adapters in IBM MobileFirst 8.0?

When I added guava my code have no errors (mfpdev adapter build Success), but when deploying to my server it respond with error:

```<code>[ERROR] Failed to execute goal com.ibm.mfp:adapter-maven-plugin:8.0.2016082422:deploy (default-cli) on project X: The output of /mfpadmin/management-apis/2.0/runtimes/mfp/adapters is of type text/html, which is unsupported. Expected an output of type text/xml or application/xml or application/json. -> [Help 1]
</code>```

But when I delete guava in pom (mvn dependencies) I am able to deploy adapter. Problem as I can see happen to some other libraries also. Is there any option to use such libraries?

mfpdev -v: 8.0.0-2017012016

EDIT: I finally resolved problem by setting scope for guava in pom file:

```<code><scope>provided</scope>
</code>```

答:
I tried this in my MFP 8.0 environment and do not see an issue.

```<code>mfpdev -v
8.0.0-2017012016

0. Create  a sample Java adapter "mfpdev adapter create"
1. Added dependency with guava 21 in pom.xml
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>21.0</version>
</dependency>

2. added a simple guava package and used it.

import com.google.common.base.Optional;

@GET

        @Produces(MediaType.TEXT_PLAIN)
        public String getResourceData() {
                // log message to server log
                logger.info("Logging info message...");
                Integer invalidInput = new Integer(20);
      Optional<Integer> a =  Optional.of(Input);
      Optional<Integer> b =  Optional.of(new Integer(10));
      logger.info("Logging my message with guava");
      );
        return "Hello from guava resource "+sum(a,b) ;
       }

4. build, deploy went successful

5. Access above resource

Request URL

http://localhost:9080/mfp/api/adapters/testGuavaAdapter/resource

Response Body

Hello from guava resource 30

Response Code

200

Response Headers

{
  "x-powered-by": "Servlet/3.1",
  "content-type": "text/plain",
  "date": "Thu, 08 Jun 2017 11:48:32 GMT",
  "content-length": "28"
}
</code>```

Verify this working pom against your environment.

Body:
is there any restriction for using external libraries with java adapters in IBM MobileFirst 8.0?

When I added guava my code have no errors (mfpdev adapter build Success), but when deploying to my server it respond with error:

[ERROR] Failed to execute goal com.ibm.mfp:adapter-maven-plugin:8.0.2016082422:deploy (default-cli) on project X: The output of /mfpadmin/management-apis/2.0/runtimes/mfp/adapters is of type text/html, which is unsupported. Expected an output of type text/xml or application/xml or application/json. -> [Help 1]

But when I delete guava in pom (mvn dependencies) I am able to deploy adapter. Problem as I can see happen to some other libraries also. Is there any option to use such libraries?

mfpdev -v: 8.0.0-2017012016

EDIT: I finally resolved problem by setting scope for guava in pom file:

<scope>provided</scope>

Body:
I tried this in my MFP 8.0 environment and do not see an issue.

mfpdev -v
8.0.0-2017012016

0. Create  a sample Java adapter "mfpdev adapter create"
1. Added dependency with guava 21 in pom.xml
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>21.0</version>
</dependency>

2. added a simple guava package and used it.

import com.google.common.base.Optional;

@GET

        @Produces(MediaType.TEXT_PLAIN)
        public String getResourceData() {
                // log message to server log
                logger.info("Logging info message...");
                Integer invalidInput = new Integer(20);
      Optional<Integer> a =  Optional.of(Input);
      Optional<Integer> b =  Optional.of(new Integer(10));
      logger.info("Logging my message with guava");
      );
        return "Hello from guava resource "+sum(a,b) ;
       }

4. build, deploy went successful

5. Access above resource

Request URL

http://localhost:9080/mfp/api/adapters/testGuavaAdapter/resource

Response Body

Hello from guava resource 30

Response Code

200

Response Headers

{
  "x-powered-by": "Servlet/3.1",
  "content-type": "text/plain",
  "date": "Thu, 08 Jun 2017 11:48:32 GMT",
  "content-length": "28"
}

Verify this working pom against your environment.


问:
Can't Select Checkbox, Selenium WebDriver
I am unable to select a checkbox with Selenium WebDriver in Java.
I tried by Xpath but no result.
WebDriver can't click on element.
I tried with Selenium IDE - recorder, no results.

Here it is - html code for checkbox

I try:

1.

```<code>driver.findElement(By.xpath(".//form[@id='placeOrderForm1']/div[@class='terms right']/label")).click();
</code>```

2.

```<code>driver.findElement(By.id("Terms1")).click();
</code>```

3.

```<code>driver.findElement(By.cssSelector("label")).click();
</code>```

4.

```<code>driver.findElement(By.xpath("//div[3]/form/div/input")).click();
</code>```

Nothing works.
Please help.

答:
Here is the Answer of your Question:

As you mentioned unable to select a checkbox, actually we don't select the checkbox, we checkmark the checkbox. The checkbox you depicted have an id as Terms1 and name astermsCheck`. So you use either of the locators to checkmark the checkbox as follows:

```<code>driver.findElement(By.id("Terms1")).click();
</code>```

OR

```<code>element = driver.findElement(By.name("termsCheck")).click();
</code>```

Let me know if this Answers your Question.

Body:
I am unable to select a checkbox with Selenium WebDriver in Java.
I tried by Xpath but no result.
WebDriver can't click on element.
I tried with Selenium IDE - recorder, no results.

Here it is - html code for checkbox

I try:

1.

driver.findElement(By.xpath(".//form[@id='placeOrderForm1']/div[@class='terms right']/label")).click();

2.

driver.findElement(By.id("Terms1")).click();

3.

driver.findElement(By.cssSelector("label")).click();

4.

driver.findElement(By.xpath("//div[3]/form/div/input")).click();

Nothing works.
Please help.

Body:
Here is the Answer of your Question:

As you mentioned unable to select a checkbox, actually we don't select the checkbox, we checkmark the checkbox. The checkbox you depicted have an id as Terms1 and name astermsCheck`. So you use either of the locators to checkmark the checkbox as follows:

driver.findElement(By.id("Terms1")).click();

OR

element = driver.findElement(By.name("termsCheck")).click();

Let me know if this Answers your Question.


问:
In spark, does cache operation for dataframe cause serialized results too big exception?
I have a big table A, and two sets table B1, B2, ..., Bn and C1, C2, ..., Cn. My logic is: Bi join Ci join A. A is big and used many times, so I want to load A first and cache it. Then in each loop i, load Bi and Ci, and join three tables.
But here's the problem: every time loading A, the following exception happened

```<code>org.apache.spark.SparkException: Job aborted due to stage failure: Total size of serialized results of 615 tasks (3.0 GB) is bigger than spark.driver.maxResultSize (3.0 GB)
    at org.apache.spark.scheduler.DAGScheduler.org$apache$spark$scheduler$DAGScheduler$$failJobAndIndependentStages(DAGScheduler.scala:1431)
    at org.apache.spark.scheduler.DAGScheduler$$anonfun$abortStage$1.apply(DAGScheduler.scala:1419)
    at org.apache.spark.scheduler.DAGScheduler$$anonfun$abortStage$1.apply(DAGScheduler.scala:1418)
    at scala.collection.mutable.ResizableArray$class.foreach(ResizableArray.scala:59)
    at scala.collection.mutable.ArrayBuffer.foreach(ArrayBuffer.scala:48)
    at org.apache.spark.scheduler.DAGScheduler.abortStage(DAGScheduler.scala:1418)
    at org.apache.spark.scheduler.DAGScheduler$$anonfun$handleTaskSetFailed$1.apply(DAGScheduler.scala:799)
    at org.apache.spark.scheduler.DAGScheduler$$anonfun$handleTaskSetFailed$1.apply(DAGScheduler.scala:799)
    at scala.Option.foreach(Option.scala:257)
    at org.apache.spark.scheduler.DAGScheduler.handleTaskSetFailed(DAGScheduler.scala:799)
    at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.doOnReceive(DAGScheduler.scala:1640)
    at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.onReceive(DAGScheduler.scala:1599)
    at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.onReceive(DAGScheduler.scala:1588)
    at org.apache.spark.util.EventLoop$$anon$1.run(EventLoop.scala:48)
    at org.apache.spark.scheduler.DAGScheduler.runJob(DAGScheduler.scala:620)
    at org.apache.spark.SparkContext.runJob(SparkContext.scala:1832)
    at org.apache.spark.SparkContext.runJob(SparkContext.scala:1845)
    at org.apache.spark.SparkContext.runJob(SparkContext.scala:1922)
    at org.apache.spark.sql.execution.datasources.InsertIntoHadoopFsRelation$$anonfun$run$1.apply$mcV$sp(InsertIntoHadoopFsRelation.scala:150)
    at org.apache.spark.sql.execution.datasources.InsertIntoHadoopFsRelation$$anonfun$run$1.apply(InsertIntoHadoopFsRelation.scala:108)
    at org.apache.spark.sql.execution.datasources.InsertIntoHadoopFsRelation$$anonfun$run$1.apply(InsertIntoHadoopFsRelation.scala:108)
    at org.apache.spark.sql.execution.SQLExecution$.withNewExecutionId(SQLExecution.scala:56)
    at org.apache.spark.sql.execution.datasources.InsertIntoHadoopFsRelation.run(InsertIntoHadoopFsRelation.scala:108)
    at org.apache.spark.sql.execution.ExecutedCommand.sideEffectResult$lzycompute(commands.scala:58)
    at org.apache.spark.sql.execution.ExecutedCommand.sideEffectResult(commands.scala:56)
    at org.apache.spark.sql.execution.ExecutedCommand.doExecute(commands.scala:70)
    at org.apache.spark.sql.execution.SparkPlan$$anonfun$execute$5.apply(SparkPlan.scala:132)
    at org.apache.spark.sql.execution.SparkPlan$$anonfun$execute$5.apply(SparkPlan.scala:130)
    at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:150)
    at org.apache.spark.sql.execution.SparkPlan.execute(SparkPlan.scala:130)
    at org.apache.spark.sql.execution.QueryExecution.toRdd$lzycompute(QueryExecution.scala:55)
    at org.apache.spark.sql.execution.QueryExecution.toRdd(QueryExecution.scala:55)
    at org.apache.spark.sql.execution.datasources.ResolvedDataSource$.apply(ResolvedDataSource.scala:256)
    at org.apache.spark.sql.DataFrameWriter.save(DataFrameWriter.scala:148)
    at org.apache.spark.sql.DataFrameWriter.save(DataFrameWriter.scala:139)
    at org.apache.spark.sql.DataFrameWriter.parquet(DataFrameWriter.scala:334)
</code>```

I don't know why, does cache operation send serialized data like some meta data to driver?

答:
I'm hitting something similar, came across this:

SPARK-128347

I haven't been able to try the same code on 2.2.0, where the issue is supposedly fixed. If you do get a chance to try it there, let us know.

Body:
I have a big table A, and two sets table B1, B2, ..., Bn and C1, C2, ..., Cn. My logic is: Bi join Ci join A. A is big and used many times, so I want to load A first and cache it. Then in each loop i, load Bi and Ci, and join three tables.
But here's the problem: every time loading A, the following exception happened

org.apache.spark.SparkException: Job aborted due to stage failure: Total size of serialized results of 615 tasks (3.0 GB) is bigger than spark.driver.maxResultSize (3.0 GB)
    at org.apache.spark.scheduler.DAGScheduler.org$apache$spark$scheduler$DAGScheduler$$failJobAndIndependentStages(DAGScheduler.scala:1431)
    at org.apache.spark.scheduler.DAGScheduler$$anonfun$abortStage$1.apply(DAGScheduler.scala:1419)
    at org.apache.spark.scheduler.DAGScheduler$$anonfun$abortStage$1.apply(DAGScheduler.scala:1418)
    at scala.collection.mutable.ResizableArray$class.foreach(ResizableArray.scala:59)
    at scala.collection.mutable.ArrayBuffer.foreach(ArrayBuffer.scala:48)
    at org.apache.spark.scheduler.DAGScheduler.abortStage(DAGScheduler.scala:1418)
    at org.apache.spark.scheduler.DAGScheduler$$anonfun$handleTaskSetFailed$1.apply(DAGScheduler.scala:799)
    at org.apache.spark.scheduler.DAGScheduler$$anonfun$handleTaskSetFailed$1.apply(DAGScheduler.scala:799)
    at scala.Option.foreach(Option.scala:257)
    at org.apache.spark.scheduler.DAGScheduler.handleTaskSetFailed(DAGScheduler.scala:799)
    at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.doOnReceive(DAGScheduler.scala:1640)
    at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.onReceive(DAGScheduler.scala:1599)
    at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.onReceive(DAGScheduler.scala:1588)
    at org.apache.spark.util.EventLoop$$anon$1.run(EventLoop.scala:48)
    at org.apache.spark.scheduler.DAGScheduler.runJob(DAGScheduler.scala:620)
    at org.apache.spark.SparkContext.runJob(SparkContext.scala:1832)
    at org.apache.spark.SparkContext.runJob(SparkContext.scala:1845)
    at org.apache.spark.SparkContext.runJob(SparkContext.scala:1922)
    at org.apache.spark.sql.execution.datasources.InsertIntoHadoopFsRelation$$anonfun$run$1.apply$mcV$sp(InsertIntoHadoopFsRelation.scala:150)
    at org.apache.spark.sql.execution.datasources.InsertIntoHadoopFsRelation$$anonfun$run$1.apply(InsertIntoHadoopFsRelation.scala:108)
    at org.apache.spark.sql.execution.datasources.InsertIntoHadoopFsRelation$$anonfun$run$1.apply(InsertIntoHadoopFsRelation.scala:108)
    at org.apache.spark.sql.execution.SQLExecution$.withNewExecutionId(SQLExecution.scala:56)
    at org.apache.spark.sql.execution.datasources.InsertIntoHadoopFsRelation.run(InsertIntoHadoopFsRelation.scala:108)
    at org.apache.spark.sql.execution.ExecutedCommand.sideEffectResult$lzycompute(commands.scala:58)
    at org.apache.spark.sql.execution.ExecutedCommand.sideEffectResult(commands.scala:56)
    at org.apache.spark.sql.execution.ExecutedCommand.doExecute(commands.scala:70)
    at org.apache.spark.sql.execution.SparkPlan$$anonfun$execute$5.apply(SparkPlan.scala:132)
    at org.apache.spark.sql.execution.SparkPlan$$anonfun$execute$5.apply(SparkPlan.scala:130)
    at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:150)
    at org.apache.spark.sql.execution.SparkPlan.execute(SparkPlan.scala:130)
    at org.apache.spark.sql.execution.QueryExecution.toRdd$lzycompute(QueryExecution.scala:55)
    at org.apache.spark.sql.execution.QueryExecution.toRdd(QueryExecution.scala:55)
    at org.apache.spark.sql.execution.datasources.ResolvedDataSource$.apply(ResolvedDataSource.scala:256)
    at org.apache.spark.sql.DataFrameWriter.save(DataFrameWriter.scala:148)
    at org.apache.spark.sql.DataFrameWriter.save(DataFrameWriter.scala:139)
    at org.apache.spark.sql.DataFrameWriter.parquet(DataFrameWriter.scala:334)

I don't know why, does cache operation send serialized data like some meta data to driver?


问:
v8 C++ Api: pass non-English strings from JavaScript to c++
In my c++ code I have:

```<code>Handle<ObjectTemplate> globalTemplate = ObjectTemplate::New();
globalTemplate->Set( String::New("print"), FunctionTemplate::New( printMessage ));
Handle<Context> context = Context::New( NULL, globalTemplate );
</code>```

The printMessage function is defined as:

```<code>Handle<Value> printMessage(const Arguments& args)
{
    Locker locker;
    HandleScope scope;

    if( args.Length() )
    {
        String::Utf8Value message( args[0]->ToString() );

        if( message.length() )
        {
            //Print the message to stdout
            printf( "%s", *message );

            bool newline = true;
            if(args.Length() == 2)
            {
                newline = args[1]->ToBoolean()->BooleanValue();
            }

            if(newline) printf("\n");

            return scope.Close( Boolean::New( true ) );
        }
    }

    return Undefined();
}
</code>```

when I call this function from JavaScript:

```<code>print("Привет");
</code>```

I see "пїЅпїЅпїЅпїЅпїЅпїЅ" instead of string.

What was wrong with this code?

答:
The code looks correct, so as @xaxxon suggested, I'd double-check that the terminal you use for output can deal with non-ASCII characters, and that the input file (if any) is encoded correctly.

Also, your V8 versions appears to be pretty old (e.g. the HandleScope constructor always takes an Isolate* parameter these days), so it's also possible that you're experiencing some old bug that has since been fixed.

For reference, the official sample shell does things almost the same way, and on my machine at least works fine with your test string:

```<code>void Print(const v8::FunctionCallbackInfo<v8::Value>& args) {
  bool first = true;
  for (int i = 0; i < args.Length(); i++) {
    v8::HandleScope handle_scope(args.GetIsolate());
    if (first) {
      first = false;
    } else {
      printf(" ");
    }
    v8::String::Utf8Value str(args[i]);
    const char* cstr = ToCString(str);
    printf("%s", cstr);
  }
  printf("\n");
  fflush(stdout);
}
</code>```

Body:
In my c++ code I have:

Handle<ObjectTemplate> globalTemplate = ObjectTemplate::New();
globalTemplate->Set( String::New("print"), FunctionTemplate::New( printMessage ));
Handle<Context> context = Context::New( NULL, globalTemplate );

The printMessage function is defined as:

Handle<Value> printMessage(const Arguments& args)
{
    Locker locker;
    HandleScope scope;

    if( args.Length() )
    {
        String::Utf8Value message( args[0]->ToString() );

        if( message.length() )
        {
            //Print the message to stdout
            printf( "%s", *message );

            bool newline = true;
            if(args.Length() == 2)
            {
                newline = args[1]->ToBoolean()->BooleanValue();
            }

            if(newline) printf("\n");

            return scope.Close( Boolean::New( true ) );
        }
    }

    return Undefined();
}

when I call this function from JavaScript:

print("Привет");

I see "пїЅпїЅпїЅпїЅпїЅпїЅ" instead of string.

What was wrong with this code?

Body:
The code looks correct, so as @xaxxon suggested, I'd double-check that the terminal you use for output can deal with non-ASCII characters, and that the input file (if any) is encoded correctly.

Also, your V8 versions appears to be pretty old (e.g. the HandleScope constructor always takes an Isolate* parameter these days), so it's also possible that you're experiencing some old bug that has since been fixed.

For reference, the official sample shell does things almost the same way, and on my machine at least works fine with your test string:

void Print(const v8::FunctionCallbackInfo<v8::Value>& args) {
  bool first = true;
  for (int i = 0; i < args.Length(); i++) {
    v8::HandleScope handle_scope(args.GetIsolate());
    if (first) {
      first = false;
    } else {
      printf(" ");
    }
    v8::String::Utf8Value str(args[i]);
    const char* cstr = ToCString(str);
    printf("%s", cstr);
  }
  printf("\n");
  fflush(stdout);
}


问:
authorize request with wildcard preceding url in spring web security
I have a rest endpoint of the form

{pathvariable}/foo/

and I want to permit access to this url:

```<code>httpSecurity
     .authorizeRequests()
        // Allow following urls to be called without authentification
        .antMatchers("**/foo").permitAll()
</code>```

What I tried above is not working. Can anybody help?

答:
found it myself: http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/util/AntPathMatcher.html

.antMatchers("/{pathvariable:[0-9A-Za-z]+}/comment")

Body:
I have a rest endpoint of the form

{pathvariable}/foo/

and I want to permit access to this url:

httpSecurity
     .authorizeRequests()
        // Allow following urls to be called without authentification
        .antMatchers("**/foo").permitAll()

What I tried above is not working. Can anybody help?