问:
Can you subscribe to events on an embedded view in Angular?
I am trying to pass data/events up through a chain of nested components using EventEmitters.  However I think the way I solved one problem may be preventing this from happening.

I am creating an embedded view on one of the components so it doesn't mess up the table structure.  So for that component,  here is some relevant code:

```<code>@ContentChild(DataTableAddRecordComponent) adder: DataTableAddRecordComponent;
@ViewChild('dtAdder', { read: ViewContainerRef }) adderContainer: ViewContainerRef;

ngAfterContentInit(): void {
    if (this.adder && this.adderContainer) {
      this.adderContainer.createEmbeddedView(this.adder.templateRef);
    }

  }
</code>```

and here is some HTML for the same component.  Notice how the thing I'm trying to subscribe to an event on is ng-container instead of the actual component.  Again this is so I don't get <data-table-adder> tags screwing up my table.  But how can I catch events from that component when it's not in my template (or is there something else I'm missing)?

```<code><table>
<tbody>
<tr><td>Some Junk</td></tr>
<ng-container #dtAdder (added)="onAdd($event)"></ng-container>
</tbody>
</table>
</code>```

答:
This turned out to be easy...  you have the reference to the component and you can subscribe to the emitted event programmatically.</p>

```<code>if (this.adder && this.adderContainer) {
  this.adderContainer.createEmbeddedView(this.adder.templateRef);
  this.adder.added.subscribe(data =>
    this.add.emit(data));
}
</code>```

Body:
I am trying to pass data/events up through a chain of nested components using EventEmitters.  However I think the way I solved one problem may be preventing this from happening.

I am creating an embedded view on one of the components so it doesn't mess up the table structure.  So for that component,  here is some relevant code:

@ContentChild(DataTableAddRecordComponent) adder: DataTableAddRecordComponent;
@ViewChild('dtAdder', { read: ViewContainerRef }) adderContainer: ViewContainerRef;

ngAfterContentInit(): void {
    if (this.adder && this.adderContainer) {
      this.adderContainer.createEmbeddedView(this.adder.templateRef);
    }

  }

and here is some HTML for the same component.  Notice how the thing I'm trying to subscribe to an event on is ng-container instead of the actual component.  Again this is so I don't get <data-table-adder> tags screwing up my table.  But how can I catch events from that component when it's not in my template (or is there something else I'm missing)?

Some Junk

<ng-container #dtAdder (added)="onAdd($event)"></ng-container>

Body:
This turned out to be easy...  you have the reference to the component and you can subscribe to the emitted event programmatically.

if (this.adder && this.adderContainer) {
  this.adderContainer.createEmbeddedView(this.adder.templateRef);
  this.adder.added.subscribe(data =>
    this.add.emit(data));
}


来源: stackexchange

问:
Access SQL calculating date difference from dup
I have a table that records the status by date
t1

```<code>ID  Date    Status
101 1   N
101 2   N
101 3   P
101 4   P
101 5   R
101 6   R
101 7   R
102 1   N
102 2   N
102 3   P
102 4   N
102 5   N
102 6   N
102 7   P
103 5   N
103 6   N
103 7   P
</code>```

but I've been trying to get a result where I can count the period for each status and only show the date where the status changes.

```<code>ID  Date    Status  Period
101 1   N   2
101 3   P   2
101 5   R   2
102 1   N   2
102 3   P   1
102 4   N   3
102 7   P   1
103 5   N   2
103 7   P   1
</code>```

Please help...
Thank you in advance!

答:
I think this gets you what you're looking for:</p>

```<code>SELECT Table.*, tA.Period
FROM Table INNER JOIN (SELECT ID, Status, MIN(Date) AS DateOfChange, COUNT(*) as Period
                       FROM Table
                       GROUP BY ID, Status) AS tA ON Table.ID = tA.ID
                                               AND Table.Date = tA.DateOfChange
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a table that records the status by date
t1

ID  Date    Status
101 1   N
101 2   N
101 3   P
101 4   P
101 5   R
101 6   R
101 7   R
102 1   N
102 2   N
102 3   P
102 4   N
102 5   N
102 6   N
102 7   P
103 5   N
103 6   N
103 7   P

but I've been trying to get a result where I can count the period for each status and only show the date where the status changes.

ID  Date    Status  Period
101 1   N   2
101 3   P   2
101 5   R   2
102 1   N   2
102 3   P   1
102 4   N   3
102 7   P   1
103 5   N   2
103 7   P   1

Please help...
Thank you in advance!

Body:
I think this gets you what you're looking for:

SELECT Table.*, tA.Period
FROM Table INNER JOIN (SELECT ID, Status, MIN(Date) AS DateOfChange, COUNT(*) as Period
                       FROM Table
                       GROUP BY ID, Status) AS tA ON Table.ID = tA.ID
                                               AND Table.Date = tA.DateOfChange


问:
When sending a file via AJAX, does it get read into memory first?
I'm writing an uploader that has to be able to transmit files of any size (up to 30gigs) to the server.

My original intention was to write a java applet that would break the file up into pieces, send those to the server, and then reassemble them there.

However, someone has suggested that AJAX's XMLHttpRequest can do the job in conjunction with nsIFileInputStream
(example here: https://developer.mozilla.org/en/using_xmlhttprequest#Sending_files_using_a_FormData_object )
and by using PUT instead of POST.

I'm worried about 2 things and can't seem to find the answer.

1) Will AJAX attempt to read the file into memory before sending it (that obviously would break the whole thing)

[EDIT]
This http://www.codeproject.com/KB/ajax/AJAXFileUpload.aspx?msg=2329446 example explicitly states that they're using ActiveXObject because that DOESN'T load the file into memory... which suggests to me that XMLHttpRequest would load it into memory.  I'm surprised I'm having such a hard time finding this info, to be honest.

2) How reliable is this approach. I realize that if the connection just dies the upload would have to resume from scratch, but realistically, how likely is it that using a standard cable connection with an upload throttle of about .5MB/s that a 30 gig file would arrive at the server?

答:
I'm trying something similar using File Api and blob.slice, but it turned out to clock up memory on large files.. However, you could use Google Gears, which plays much better with large sliced files. It also doesnt cause errors with the slice order, which FileReader combined with XHR does frequently and randomly.

I do however find (generally) that uploading files via JavaScript is very unstable..

ContentLicense: CC BY-SA 2.5


问:
Does mutation observers support iframe documents when added to the main html document?
I have not been able to get the mutation observers to work with documents with in an iframe. My main document contains multiple iframes with the same origin as the main document. I have added the mutation observer on the main document but the mutation observer does not fire when there is a dom change in the document with in the iframe. It fires when I add mutation observer to each and every document explicitly for every iframe in the main document.

Hence I want to know can the mutation observer monitor the changes made to the dom of the document with an iframe when the mutation observer is added to the main html document which hosts the iframe? Please help

答:
MutationObserver is linked only to the parent document so any changes inside of the iframe would not be captured.

if you have iframe information add the event listeners to each of the iframes or just look for all the children in the main document and event listeners to them.

I'm using this from a browser extension so all I had to was add
"all_frames" : true
inside the content scripts and this take care of adding the complete script tag so the events listeners will be added here as well


问:
How to escape reserved word (keyword) in InterSystems Caché SQL?
I have a column named Date in SQL table, but unfortunately this query throws an error:

```<code>select Author, Date, Text from Tiny.Comment
</code>```

I've tried to escape the Date keyword with [Date] or 'Date' but this never worked for me.

答:
You can also use %STRING function like:</p>

```<code>SELECT ID, Super
FROM %Dictionary.CompiledClass
WHERE %STRING(Super) %STARTSWITH %STRING('Base.%')
</code>```

Body:
I have a column named Date in SQL table, but unfortunately this query throws an error:

select Author, Date, Text from Tiny.Comment

I've tried to escape the Date keyword with [Date] or 'Date' but this never worked for me.

Body:
You can also use %STRING function like:

SELECT ID, Super
FROM %Dictionary.CompiledClass
WHERE %STRING(Super) %STARTSWITH %STRING('Base.%')


问:
Makefile generic rule to build src files from multiple folders
I intend to keep my all *.o files build/obj and have source files src/src.c log/log.c

```<code>OBJECTS=build/log.o build/src.o

$(OBJ_DIR)/%.o : src/%.c log/%.c
       $(CC) $(CFLAGS) $(DEFINE) $(INCLUDE) -o$@ $<
</code>```

But it not mapping *.o to proper *.c what am I doing wrong ?

答:
You can use VPATH as follows:

```<code>~/tmp8> more Makefile

OBJECTS=build/log.o build/src.o
OBJ_DIR=build

all: $(OBJECTS)

VPATH=src:log

$(OBJ_DIR)/%.o: %.c
        @echo compiling "$< ==> $@"
</code>```

```<code>~/tmp8> find . -type f
./src/src.c
./Makefile
./log/log.c

~/tmp8> make
compiling log/log.c ==> build/log.o
compiling src/src.c ==> build/src.o

~/tmp8>
</code>```

Body:
I intend to keep my all *.o files build/obj and have source files src/src.c log/log.c

OBJECTS=build/log.o build/src.o

$(OBJ_DIR)/%.o : src/%.c log/%.c
       $(CC) $(CFLAGS) $(DEFINE) $(INCLUDE) -o$@ $<

But it not mapping *.o to proper *.c what am I doing wrong ?

Body:
You can use VPATH as follows:

~/tmp8> more Makefile

OBJECTS=build/log.o build/src.o
OBJ_DIR=build

all: $(OBJECTS)

VPATH=src:log

$(OBJ_DIR)/%.o: %.c
        @echo compiling "$< ==> $@"

~/tmp8> find . -type f
./src/src.c
./Makefile
./log/log.c

~/tmp8> make
compiling log/log.c ==> build/log.o
compiling src/src.c ==> build/src.o

~/tmp8>


问:
Showing app and sqlite in android/data folder
I have created an app with an associated SQlite database which I have installed to my phone. It works fine.

I would like the app to create a com.mypackage.app folder in the Android/data folder.

My phone isnt rooted, but I can see other applications in this folder such as com.dropbox.android and com.google.earth. I can even see the associated sqlite databases for some apps I have installed.

Can anyone tell me why I cant see my own app and database in this folder?

答:
I can see that the Android/data folder is actually on the SDcard.

I used this tutorial to create the folder:androprogrammer.com/2014/03/…

I have an option to backup my database using the details above provided by Saran to copy the database into the created folder


问:
Delete data row from DB in DataGridView winforms?
i want to delete the row of data from the database, currently i can delete the row of data by clicking on the delete button, but the database Table is not updated, how do i do so?</p>

```<code>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace project
{
    public partial class frmTestPrint : Form
    {
        public frmTestPrint()
        {
            InitializeComponent();
        }

        private void frmTestPrint_Load(object sender, EventArgs e)
        {
            // TODO: This line of code loads data into the 'usersDataSet1.Booking' table. You can move, or remove it, as needed.
            this.bookingTableAdapter.Fill(this.usersDataSet1.Booking);

        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            dataGridView1.Rows.RemoveAt(dataGridView1.CurrentRow.Index);
        }
    }
}
</code>```

答:
This is only to delete one at a time. I am still working on multiple deletes.</p>

```<code>        if (MessageBox.Show("Sure you wanna delete?", "Warning", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
        {
            //get the index from the dataGridView
            int rowIndex = table1DataGridView.CurrentCell.RowIndex;
            //Remove from both the actual database & datagridview
            table1BindingSource.RemoveAt(rowIndex);
            //update table 1
            this.table1TableAdapter.Update(this.maquinasDataSet.Table1);
            //load table 1
            this.table1TableAdapter.Fill(this.maquinasDataSet.Table1);
        }
</code>```

Body:
i want to delete the row of data from the database, currently i can delete the row of data by clicking on the delete button, but the database Table is not updated, how do i do so?

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace project
{
    public partial class frmTestPrint : Form
    {
        public frmTestPrint()
        {
            InitializeComponent();
        }

        private void frmTestPrint_Load(object sender, EventArgs e)
        {
            // TODO: This line of code loads data into the 'usersDataSet1.Booking' table. You can move, or remove it, as needed.
            this.bookingTableAdapter.Fill(this.usersDataSet1.Booking);

        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            dataGridView1.Rows.RemoveAt(dataGridView1.CurrentRow.Index);
        }
    }
}

Body:
This is only to delete one at a time. I am still working on multiple deletes.

        if (MessageBox.Show("Sure you wanna delete?", "Warning", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
        {
            //get the index from the dataGridView
            int rowIndex = table1DataGridView.CurrentCell.RowIndex;
            //Remove from both the actual database & datagridview
            table1BindingSource.RemoveAt(rowIndex);
            //update table 1
            this.table1TableAdapter.Update(this.maquinasDataSet.Table1);
            //load table 1
            this.table1TableAdapter.Fill(this.maquinasDataSet.Table1);
        }


问:
Using regular expression to cut/paste lines in sublime
What's the best way to move the "data-filter-tags" to one line above using sublime or other methods?

```<code><div class="col-4">
   <a class="app-list__item">
        <div class="display-4" data-filter-tags="angle-down">
            <i class="fal fa-angle-down"></i>
        </div>
    </a>
</div>
<div class="col-4">
   <a class="app-list__item">
        <div class="display-4" data-filter-tags="angle-left">
            <i class="fal fa-angle-left"></i>
        </div>
    </a>
</div>
</code>```

The result will look like this:

```<code><div class="col-4">
   <a class="app-list__item" data-filter-tags="angle-down">
        <div class="display-4">
            <i class="fal fa-angle-down"></i>
        </div>
    </a>
</div>
<div class="col-4">
   <a class="app-list__item" data-filter-tags="angle-left">
        <div class="display-4">
            <i class="fal fa-angle-left"></i>
        </div>
    </a>
</div>
</code>```

答:
Code

See regex in use here

```<code>(<[^>]*)(>\s*.*?)(\s*data-filter-tags="[^"]*")
</code>```

Replacement: $1$3$2

Results

Input

```<code><div class="col-4">
   <a class="app-list__item">
        <div class="display-4" data-filter-tags="angle-down">
            <i class="fal fa-angle-down"></i>
        </div>
    </a>
</div>
<div class="col-4">
   <a class="app-list__item">
        <div class="display-4" data-filter-tags="angle-left">
            <i class="fal fa-angle-left"></i>
        </div>
    </a>
</div>
</code>```

Output

```<code><div class="col-4">
   <a class="app-list__item" data-filter-tags="angle-down">
        <div class="display-4">
            <i class="fal fa-angle-down"></i>
        </div>
    </a>
</div>
<div class="col-4">
   <a class="app-list__item" data-filter-tags="angle-left">
        <div class="display-4">
            <i class="fal fa-angle-left"></i>
        </div>
    </a>
</div>
</code>```

Explanation

(<[^>]*) Capture the following into capture group 1

< Match this literally

[^>]* Match any character except > any number of times

(>\s*.*?) Capture the following into capture group 2

> Match this literally

\s* Match any number of whitespace characters

.*? Match any character any number of times, but as few as possible (excludes newline characters)

(\s*data-filter-tags="[^"]*") Capture the following into capture group 3

\s* Match any number of whitespace characters

data-filter-tags=" Match this literally

[^"]* Match any character except " any number of times

" Match this literally

The replacement of $1$3$2 simply reorders the captured text such that the third capture group is placed after the first, but before the second.

Body:
What's the best way to move the "data-filter-tags" to one line above using sublime or other methods?

The result will look like this:

Body:
Code

See regex in use here

(<[^>]*)(>\s*.*?)(\s*data-filter-tags="[^"]*")

Replacement: $1$3$2

Results

Input

<div class="col-4">
   <a class="app-list__item">
        <div class="display-4" data-filter-tags="angle-down">
            <i class="fal fa-angle-down"></i>
        </div>
    </a>
</div>
<div class="col-4">
   <a class="app-list__item">
        <div class="display-4" data-filter-tags="angle-left">
            <i class="fal fa-angle-left"></i>
        </div>
    </a>
</div>

Output

<div class="col-4">
   <a class="app-list__item" data-filter-tags="angle-down">
        <div class="display-4">
            <i class="fal fa-angle-down"></i>
        </div>
    </a>
</div>
<div class="col-4">
   <a class="app-list__item" data-filter-tags="angle-left">
        <div class="display-4">
            <i class="fal fa-angle-left"></i>
        </div>
    </a>
</div>

Explanation

(<[^>]*) Capture the following into capture group 1

< Match this literally

[^>]* Match any character except > any number of times

(>\s*.*?) Capture the following into capture group 2

> Match this literally

\s* Match any number of whitespace characters

.*? Match any character any number of times, but as few as possible (excludes newline characters)

(\s*data-filter-tags="[^"]*") Capture the following into capture group 3

\s* Match any number of whitespace characters

data-filter-tags=" Match this literally

[^"]* Match any character except " any number of times

" Match this literally

The replacement of $1$3$2 simply reorders the captured text such that the third capture group is placed after the first, but before the second.


问:
Python regex to find digit in first n characters
I was wondering if it is possible to use a regex to check the first n characters of a string and determine if any of them contain a digit?

I realize this can be done by first splitting the string and then using a \d on the substring, but I would like to see a solution where it could be done in one shot

答:
This will do it in 1 shot, but not the way you'd expect:

```<code>r'\D{n}'
</code>```

That is, it matches string of length n that does not contain any digits; thus, if the match fails, there must be a digit in the first n characters.

Body:
This will do it in 1 shot, but not the way you'd expect:

r'\D{n}'

That is, it matches string of length n that does not contain any digits; thus, if the match fails, there must be a digit in the first n characters.


问:
Redirect to dynamically generated html in Angular 5
I am building an SPA with Angular 5 and I'm calling an authentication and authorization service.
This service checks if I have a session active and if there's no session or if it has expired then returns 401 and an HTML with the company-wide login page.
I built a service for making this call, like this:

```<code>@Injectable()
export class AuthService {

    private authServicePath = '/<path-to-the-service>';
    private authToken: string;
    private serviceURL: string;
    private requestOptions: any;

    constructor(private http: HttpClient, private cookieService: CookieService) { }

    validateAuth() {
        this.serviceURL = environment.endpoint + this.authServicePath;
        this.authToken = this.cookieService.get('SESSION-TOKEN-COOKIE');
        this.requestOptions = {
            headers: new HttpHeaders(
                {
                    'SESSION-TOKEN-COOKIE': this.authToken
                }
            )
        };

        return this
                .http
                .get(this.serviceURL, this.requestOptions)
                .subscribe(
                    data => {
                        // Do nothing
                    },
                    (err: HttpErrorResponse) => {
                        /*window.document.write = err.error;
                        window.document.close();*/
                    }
                );
    }
}
</code>```

As you can see, I'm calling the service. If the token is valid then there's nothing to do, but if I don't have any active/valid session, then the service will return the 401 Unauthorized and in its payload (.error field) I will get something like this:

```<code><html>
      <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
      </head>
      <body>
        <form action="..." ...
</code>```

How do I tell my app to redirect me to this generated page?

As you can see, I tried writing a new HTML with window.document.write but it didn't work.
I understand that Angular Router can only redirect to components belonging to the app.

Thanks in advance.

答:
Sounds like what you should be doing is redirecting to an error/login page or displaying an error message with partial page content populated from your service (not the whole html page).

If you want to go that route, just set a property to contain your HTML and then bind it to the InnerHTML of a div element as follows:

typescript

public myHtmlCode: string = 'header
paragraph
';

template

Body:
I am building an SPA with Angular 5 and I'm calling an authentication and authorization service.
This service checks if I have a session active and if there's no session or if it has expired then returns 401 and an HTML with the company-wide login page.
I built a service for making this call, like this:

@Injectable()
export class AuthService {

    private authServicePath = '/<path-to-the-service>';
    private authToken: string;
    private serviceURL: string;
    private requestOptions: any;

    constructor(private http: HttpClient, private cookieService: CookieService) { }

    validateAuth() {
        this.serviceURL = environment.endpoint + this.authServicePath;
        this.authToken = this.cookieService.get('SESSION-TOKEN-COOKIE');
        this.requestOptions = {
            headers: new HttpHeaders(
                {
                    'SESSION-TOKEN-COOKIE': this.authToken
                }
            )
        };

        return this
                .http
                .get(this.serviceURL, this.requestOptions)
                .subscribe(
                    data => {
                        // Do nothing
                    },
                    (err: HttpErrorResponse) => {
                        /*window.document.write = err.error;
                        window.document.close();*/
                    }
                );
    }
}

As you can see, I'm calling the service. If the token is valid then there's nothing to do, but if I don't have any active/valid session, then the service will return the 401 Unauthorized and in its payload (.error field) I will get something like this:

        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>

        <form action="..." ...

How do I tell my app to redirect me to this generated page?

As you can see, I tried writing a new HTML with window.document.write but it didn't work.
I understand that Angular Router can only redirect to components belonging to the app.

Thanks in advance.

Body:
Sounds like what you should be doing is redirecting to an error/login page or displaying an error message with partial page content populated from your service (not the whole html page).

If you want to go that route, just set a property to contain your HTML and then bind it to the InnerHTML of a div element as follows:

typescript

public myHtmlCode: string = '<b>header</b><p>paragraph</p>';

template

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


问:
c# sql server backup percent read
sql command

```<code>BACKUP DATABASE [databasesample] TO  DISK = N'D:\kkk\test.bat' WITH  INIT ,  NOUNLOAD ,
NAME = N'name test',  NOSKIP ,
STATS = 5,  DESCRIPTION = N'test',  NOFORMAT
</code>```

result

```<code>5 percent processed.
10 percent processed.
15 percent processed.
20 percent processed.
25 percent processed.
30 percent processed.
35 percent processed.
40 percent processed.
45 percent processed.
50 percent processed.
55 percent processed.
60 percent processed.
65 percent processed.
70 percent processed.
75 percent processed.
80 percent processed.
85 percent processed.
90 percent processed.
95 percent processed.
Processed 30960 pages for database 'databasesample', file 'sample_Data' on file 1.
100 percent processed.
</code>```

I want to catch the percentage with C#. I think BeginExecuteNonQuery() function is done. but I do not know exactly how. Suggestions?

答: I would suggest using the SMO tools which contain a Backup class which sends a PercentCompleteNotification via a PercentComplete event.  I love the SMO tools - they're powerful and easy to use.

Title: c# sql server backup percent read

Body:
sql command

BACKUP DATABASE [databasesample] TO  DISK = N'D:\kkk\test.bat' WITH  INIT ,  NOUNLOAD ,
NAME = N'name test',  NOSKIP ,
STATS = 5,  DESCRIPTION = N'test',  NOFORMAT

result

5 percent processed.
10 percent processed.
15 percent processed.
20 percent processed.
25 percent processed.
30 percent processed.
35 percent processed.
40 percent processed.
45 percent processed.
50 percent processed.
55 percent processed.
60 percent processed.
65 percent processed.
70 percent processed.
75 percent processed.
80 percent processed.
85 percent processed.
90 percent processed.
95 percent processed.
Processed 30960 pages for database 'databasesample', file 'sample_Data' on file 1.
100 percent processed.

I want to catch the percentage with C#. I think BeginExecuteNonQuery() function is done. but I do not know exactly how. Suggestions?


问:
Updating the feature names into scikit TFIdfVectorizer
I am trying out this code

```<code>from sklearn.feature_extraction.text import TfidfVectorizer
import numpy as np

train_data = ["football is the sport","gravity is the movie", "education is imporatant"]
vectorizer = TfidfVectorizer(sublinear_tf=True, max_df=0.5,
                                                 stop_words='english')

print "Applying first train data"
X_train = vectorizer.fit_transform(train_data)
print vectorizer.get_feature_names()

print "\n\nApplying second train data"
train_data = ["cricket", "Transformers is a film","AIMS is a college"]
X_train = vectorizer.transform(train_data)
print vectorizer.get_feature_names()

print "\n\nApplying fit transform onto second train data"
X_train = vectorizer.fit_transform(train_data)
print vectorizer.get_feature_names()
</code>```

The output for this one is

```<code>Applying first train data
[u'education', u'football', u'gravity', u'imporatant', u'movie', u'sport']

Applying second train data
[u'education', u'football', u'gravity', u'imporatant', u'movie', u'sport']

 Applying fit transform onto second train data
[u'aims', u'college', u'cricket', u'film', u'transformers']
</code>```

I gave the first set of data using fit_transform to vectorizer so it gave me feature names like  [u'education', u'football', u'gravity', u'imporatant', u'movie', u'sport'] after that i applied another train set to the same vectorizer but it gave me the same feature names as I didnt use fit or fit_transform. But I want to know how to update the features of a vectorizer without overwriting the previous oncs. If I use fit_transform again the previous features will get overwritten. So I want to update the feature list of the vectorizer. So i want something like [u'education', u'football', u'gravity', u'imporatant', u'movie', u'sport',u'aims', u'college', u'cricket', u'film', u'transformers'] How can I get  that.

答:
I found this question while googling for the same issue that OP raised. Like mbatchkarov said Scikit-Learn's TfidfVectorizer doesn't natively support partial fitting.

HashingVectorizer is usually a great alternative, but it really depends on your use-case. Specifically, if you care very much about representing infrequent terms precisely, then collisions will hurt performance.

So I went ahead and wrote my own implementation of "partial_fit" for both TfidfVectorizer and CountVectorizer (see here). Hope it's useful for other people reaching this post. Note that this kind of partial fitting does change the dimension of the output vector given by the vectorizer since the whole point is to update the vocabulary (so take this into account when using in a pipeline).

Body:
I am trying out this code

from sklearn.feature_extraction.text import TfidfVectorizer
import numpy as np

train_data = ["football is the sport","gravity is the movie", "education is imporatant"]
vectorizer = TfidfVectorizer(sublinear_tf=True, max_df=0.5,
                                                 stop_words='english')

print "Applying first train data"
X_train = vectorizer.fit_transform(train_data)
print vectorizer.get_feature_names()

print "\n\nApplying second train data"
train_data = ["cricket", "Transformers is a film","AIMS is a college"]
X_train = vectorizer.transform(train_data)
print vectorizer.get_feature_names()

print "\n\nApplying fit transform onto second train data"
X_train = vectorizer.fit_transform(train_data)
print vectorizer.get_feature_names()

The output for this one is

Applying first train data
[u'education', u'football', u'gravity', u'imporatant', u'movie', u'sport']

Applying second train data
[u'education', u'football', u'gravity', u'imporatant', u'movie', u'sport']

 Applying fit transform onto second train data
[u'aims', u'college', u'cricket', u'film', u'transformers']

I gave the first set of data using fit_transform to vectorizer so it gave me feature names like  [u'education', u'football', u'gravity', u'imporatant', u'movie', u'sport'] after that i applied another train set to the same vectorizer but it gave me the same feature names as I didnt use fit or fit_transform. But I want to know how to update the features of a vectorizer without overwriting the previous oncs. If I use fit_transform again the previous features will get overwritten. So I want to update the feature list of the vectorizer. So i want something like [u'education', u'football', u'gravity', u'imporatant', u'movie', u'sport',u'aims', u'college', u'cricket', u'film', u'transformers'] How can I get  that.


问:
Passing parameters to raw SQL queries inside ruby on rails
I want to execute a raw SQL query using rails active record, but my query takes a parameter, I can't find a proper way to safely pass that parameter into the query string. The query is as follows </p>

```<code>def self.get_branches_by_workspace_name(workspace_name)
  branches = ActiveRecord::Base.connection.execute("
    select
      address,
      phone,
      email,
      services
    from branches as b, workspaces as w
    where b.workspace_id = w.id and w.name= :workspace_name", workspace_name).to_a
  return branches
end
</code>```

<p>I would like to pass a parameter named "workspace_name". Any help? </p>

答:
In your model add this method

```<code>  def self.execute_sql(*sql_array)
   connection.execute(send(:sanitize_sql_array, sql_array))
  end
</code>```

This will let you sanitize and execute arbitrary SQL in an AR model

Then simply do this

```<code>ModelName.execute_sql("select address,phone,email,services from branches as b, workspaces as w
    where b.workspace_id = w.id and w.name= ?", workspace_name)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I want to execute a raw SQL query using rails active record, but my query takes a parameter, I can't find a proper way to safely pass that parameter into the query string. The query is as follows

def self.get_branches_by_workspace_name(workspace_name)
  branches = ActiveRecord::Base.connection.execute("
    select
      address,
      phone,
      email,
      services
    from branches as b, workspaces as w
    where b.workspace_id = w.id and w.name= :workspace_name", workspace_name).to_a
  return branches
end

I would like to pass a parameter named "workspace_name". Any help?

Body:
In your model add this method

  def self.execute_sql(*sql_array)
   connection.execute(send(:sanitize_sql_array, sql_array))
  end

This will let you sanitize and execute arbitrary SQL in an AR model

Then simply do this

ModelName.execute_sql("select address,phone,email,services from branches as b, workspaces as w
    where b.workspace_id = w.id and w.name= ?", workspace_name)


问:
Turning a 2D array into a sparse array of arrays
I have an array of x=[[3,1],[2,2]] and I want to turn it into x[3][1]=1 and x[2][2]=1. The code should also work for longer arrays like x=[[3,1],[2,12],[3,3]].

答:
```<code>const x = [[3,1], [2,2]]

console.log('x =', x)

// Initialize 1st dimension array
const y = []
for (let i in x) {
  // Initialize the 2nd dimension array if not exist
  y[x[i][0]] = y[x[i][0]] || []
  // Assign the value to the sparse array
  y[x[i][0]][x[i][1]] = 1
}

console.log('y =', y)
</code>```

Output:

```<code>x = [ [ 3, 1 ], [ 2, 2 ] ]
y = [ , , [ , , 1 ], [ , 1 ] ]
</code>```

Body:
const x = [[3,1], [2,2]]

console.log('x =', x)

// Initialize 1st dimension array
const y = []
for (let i in x) {
  // Initialize the 2nd dimension array if not exist
  y[x[i][0]] = y[x[i][0]] || []
  // Assign the value to the sparse array
  y[x[i][0]][x[i][1]] = 1
}

console.log('y =', y)

Output:

x = [ [ 3, 1 ], [ 2, 2 ] ]
y = [ , , [ , , 1 ], [ , 1 ] ]


问:
How can I have this program add the user input into my linked list?
```<code>import java.util.*;

public class TestClass {
static String name;
static String gender;
static String hairColor;

TestClass(String name, String gender, String hairColor){
    this.name=name;
    this.gender=gender;
    this.hairColor=hairColor;

}
public static void main (String[]args) {
    TestClass info = new TestClass(name, gender, hairColor);
    LinkedList<TestClass> linky = new LinkedList<TestClass>();
    Scanner input = new Scanner(System.in);

    System.out.println("Enter name ");
    name=input.nextLine();

    System.out.println("Enter gender ");
    gender=input.nextLine();

    System.out.println("Enter hair color ");
    hairColor=input.nextLine();

    }

}
</code>```

I want to add user input into the linked list but I can't figure out how to. I have tried to use linky.add(name); but that gives an error. How can I add input into the linked list?

答:
You first need to store all the user inputs in the TestClass object and then add that object to your LinkedList

After taking inputs from user, pass all the variables that contain user input values in to TestClass constructor

```<code>TestClass test = new TestClass(name, gender, hairColor);
</code>```

then store test object in your LinkedList

```<code>linky.add(test);
</code>```

Important Note:

Data member variables of class TestClass should not be static if you want to store multiple instances of TestClass each having its own data.

Body:
import java.util.*;

public class TestClass {
static String name;
static String gender;
static String hairColor;

TestClass(String name, String gender, String hairColor){
    this.name=name;
    this.gender=gender;
    this.hairColor=hairColor;

}
public static void main (String[]args) {
    TestClass info = new TestClass(name, gender, hairColor);
    LinkedList<TestClass> linky = new LinkedList<TestClass>();
    Scanner input = new Scanner(System.in);

    System.out.println("Enter name ");
    name=input.nextLine();

    System.out.println("Enter gender ");
    gender=input.nextLine();

    System.out.println("Enter hair color ");
    hairColor=input.nextLine();

    }

}

I want to add user input into the linked list but I can't figure out how to. I have tried to use linky.add(name); but that gives an error. How can I add input into the linked list?

Body:
You first need to store all the user inputs in the TestClass object and then add that object to your LinkedList

After taking inputs from user, pass all the variables that contain user input values in to TestClass constructor

TestClass test = new TestClass(name, gender, hairColor);

then store test object in your LinkedList

linky.add(test);

Important Note:

Data member variables of class TestClass should not be static if you want to store multiple instances of TestClass each having its own data.


问:
Does using AWS Cloud9 costs?

I am starting to use AWS Cloud9, I created an environment and played a little bit with the editor but I haven't seen any notice that says if it costs. Is this service free?
</p>

答: The service itself is free, but in can be installed on an underlying ec2 instance, and you have to pay for that if you do.</p>

Title: Does using AWS Cloud9 costs?


答:
```<code>LinkedList<TestClass> linky = new LinkedList<TestClass>();
</code>```

You need to add your instance of TestClass

Title: How can I have this program add the user input into my linked list?

Body:
LinkedList<TestClass> linky = new LinkedList<TestClass>();

You need to add your instance of TestClass


问:
Directly setting values for an ArrayList in Java
Setting a list of values for a Java ArrayList works:

```<code>Integer[] a = {1,2,3,4,5,6,7,8,9};
ArrayList<Integer> possibleValues2 = new ArrayList<Integer>(Arrays.asList(a));
</code>```

However, the following doesn't work and has the error "Illegal start of type" as well as other. Why not? Since the first line in the first code block is simply assignment, shouldn't it not have an effect?

```<code>ArrayList<Integer> possibleValues2 = new ArrayList<Integer>(Arrays.asList({1,2,3,4,5,6,7,8,9}));
</code>```

答:
You should use either the vararg version of Arrays.asList, e.g.

```<code>ArrayList<Integer> possibleValues2 =
    new ArrayList<Integer>(Arrays.asList(1,2,3,4,5,6,7,8,9));
</code>```

or explicitly create an array parameter, e.g.

```<code>ArrayList<Integer> possibleValues2 =
    new ArrayList<Integer>(Arrays.asList(new Integer[]{1,2,3,4,5,6,7,8,9}));
</code>```

Body:
Setting a list of values for a Java ArrayList works:

Integer[] a = {1,2,3,4,5,6,7,8,9};
ArrayList<Integer> possibleValues2 = new ArrayList<Integer>(Arrays.asList(a));

However, the following doesn't work and has the error "Illegal start of type" as well as other. Why not? Since the first line in the first code block is simply assignment, shouldn't it not have an effect?

ArrayList<Integer> possibleValues2 = new ArrayList<Integer>(Arrays.asList({1,2,3,4,5,6,7,8,9}));

Body:
You should use either the vararg version of Arrays.asList, e.g.

ArrayList<Integer> possibleValues2 =
    new ArrayList<Integer>(Arrays.asList(1,2,3,4,5,6,7,8,9));

or explicitly create an array parameter, e.g.

ArrayList<Integer> possibleValues2 =
    new ArrayList<Integer>(Arrays.asList(new Integer[]{1,2,3,4,5,6,7,8,9}));


问:
How do I use CultureInfo to get the 12-hour or 24-hour time (without the date)

I would like to use C# to format a time of day in the proper cultural format.

For example, if the current culture is en-US I would like to show 1:00 PM, and if the current culture is fr-FR I would like to show 13:00. I just want the time of day, I do not want the date.

```<code>//timeOfDay is a DateTime object.

//This will return the 12 hour clock regardless of culture:
time = timeOfDay.ToString("h:mm tt", CultureInfo.CurrentCulture);
//This will return the 24 hour clock regardless of culture
time = timeOfDay.ToString("H:mm tt", CultureInfo.CurrentCulture);
//This will return the correct clock for the culture, but the date will also be present
time = timeOfDay.ToString(CultureInfo.CurrentCulture);
</code>```

Note that the "tt" is for AM/PM, and it is culturally sensitive (in France it is blank, as it should be).

How do I acquire the appropriate clock format for the current culture, without the date?

答:
This seems to work:

```<code>string time = timeOfDay.ToString(CultureInfo.CurrentCulture.DateTimeFormat.ShortTimePattern, CultureInfo.CurrentCulture);
</code>```

The second parameter is probably unnecessary as well.

Body:
I would like to use C# to format a time of day in the proper cultural format.

For example, if the current culture is en-US I would like to show 1:00 PM, and if the current culture is fr-FR I would like to show 13:00. I just want the time of day, I do not want the date.

//timeOfDay is a DateTime object.

//This will return the 12 hour clock regardless of culture:
time = timeOfDay.ToString("h:mm tt", CultureInfo.CurrentCulture);
//This will return the 24 hour clock regardless of culture
time = timeOfDay.ToString("H:mm tt", CultureInfo.CurrentCulture);
//This will return the correct clock for the culture, but the date will also be present
time = timeOfDay.ToString(CultureInfo.CurrentCulture);

Note that the "tt" is for AM/PM, and it is culturally sensitive (in France it is blank, as it should be).

How do I acquire the appropriate clock format for the current culture, without the date?

Body:
This seems to work:

string time = timeOfDay.ToString(CultureInfo.CurrentCulture.DateTimeFormat.ShortTimePattern, CultureInfo.CurrentCulture);

The second parameter is probably unnecessary as well.


问:
Python pandas CustomBusinessDay
I am attempting to filter some time series data without any luck in pandas.. Any tips for what I am doing wrong is greatly appreciated.. First I am attempting to filter just for the month of July 2013 and then filter the data again for taking hourly averages of the dataset samples.

Ultimately what I am wanting to do is filter the data as described above in addition for Weekdays, OR individual weekdays Mondays, Tuesdays, Wednesday, etc. with the CustomBusinessDay function.

I am getting tripped up where the code is commented out for the CustomBusinessDay

```<code>import pandas as pd
import numpy as np
from pandas.tseries.offsets import CustomBusinessDay

time = pd.date_range('6/28/2013', periods=2000, freq='45min')
data = pd.Series(np.random.randint(100, size=2000), index=time)

print(data)

##weekmask = 'Mon Tue Wed Thu Fri'

df = data.truncate(before='7/1/2013', after='7/31/2013')
df = df.groupby(df.index.hour).mean()
print(df)

##df = CustomBusinessDay(weekmask=weekmask)
##df = pd.bdate_range(start=None, end=None, periods=None, freq='B')
##
##print(df)
</code>```

答:
Ultimately what I am wanting to do is filter the data as described
  above in addition for Weekdays, OR individual weekdays Mondays,
  Tuesdays, Wednesday, etc. with the CustomBusinessDay function.

Have you considered using DatetimeIndex.dayofweek?

The day of the week with Monday=0, Sunday=6

```<code># Exclude Sundays
data.loc[data.index.dayofweek != 6]

# Weekends only
data.loc[data.index.dayofweek.isin([5, 6])]

# Weekdays only
data.loc[~data.index.dayofweek.isin([5, 6])]
</code>```

Also, I think an alternative to df = df.groupby(df.index.hour).mean() would be just:

```<code>df.resample('H').mean()
</code>```

Title: Python pandas CustomBusinessDay

Body:
I am attempting to filter some time series data without any luck in pandas.. Any tips for what I am doing wrong is greatly appreciated.. First I am attempting to filter just for the month of July 2013 and then filter the data again for taking hourly averages of the dataset samples.

Ultimately what I am wanting to do is filter the data as described above in addition for Weekdays, OR individual weekdays Mondays, Tuesdays, Wednesday, etc. with the CustomBusinessDay function.

I am getting tripped up where the code is commented out for the CustomBusinessDay

import pandas as pd
import numpy as np
from pandas.tseries.offsets import CustomBusinessDay

time = pd.date_range('6/28/2013', periods=2000, freq='45min')
data = pd.Series(np.random.randint(100, size=2000), index=time)

print(data)

##weekmask = 'Mon Tue Wed Thu Fri'

df = data.truncate(before='7/1/2013', after='7/31/2013')
df = df.groupby(df.index.hour).mean()
print(df)

##df = CustomBusinessDay(weekmask=weekmask)
##df = pd.bdate_range(start=None, end=None, periods=None, freq='B')
##
##print(df)

Body:
Ultimately what I am wanting to do is filter the data as described
  above in addition for Weekdays, OR individual weekdays Mondays,
  Tuesdays, Wednesday, etc. with the CustomBusinessDay function.

Have you considered using DatetimeIndex.dayofweek?

The day of the week with Monday=0, Sunday=6

# Exclude Sundays
data.loc[data.index.dayofweek != 6]

# Weekends only
data.loc[data.index.dayofweek.isin([5, 6])]

# Weekdays only
data.loc[~data.index.dayofweek.isin([5, 6])]

Also, I think an alternative to df = df.groupby(df.index.hour).mean() would be just:

df.resample('H').mean()


问:
Class mutable.HashTable in Scala
The on-line documentation doesn't say too much about it (http://www.scala-lang.org/api/2.12.0/scala/collection/mutable/HashTable.html), and it's impossible to find any example of its usage.
I'm wondering how to even put elements into a mutable.HashTable.

Are there any data structure with the same constant time complexity in research and delete operations that i could use?

答:
mutable.HashTable is a trait.

```<code>trait HashTable[A, Entry >: Null <: HashEntry[A, Entry]] extends HashTable.HashUtils[A]
</code>```

with default load factor as 75%

```<code>private[collection] final def defaultLoadFactor: Int = 750
</code>```

uses array for implementation,

```<code>protected var table: Array[HashEntry[A, Entry]] = new Array(initialCapacity)
</code>```

1) you have to use implementations of HashTable, which are mutable.HashMap or mutable.LinkedHashMap.

example,

```<code>scala> import scala.collection.mutable.HashMap
import scala.collection.mutable.HashMap

scala> new HashMap[String, String]
res9: scala.collection.mutable.HashMap[String,String] = Map()
</code>```

add element

```<code>scala> res9+= "order-id-1" -> "delivered"
res10: res9.type = Map(order-id-1 -> delivered)

scala> res9
res11: scala.collection.mutable.HashMap[String,String] = Map(order-id-1 -> delivered)
</code>```

access element

```<code>scala> res9("order-id-1")
res12: String = delivered
</code>```

Write complexity should be O(1) same as in hashmap datastructure. You find the hashcode and add to the array of Entry.

```<code>  def += (kv: (A, B)): this.type = {
    val e = findOrAddEntry(kv._1, kv._2)
    if (e ne null) e.value = kv._2
    this
  }

  protected def findOrAddEntry[B](key: A, value: B): Entry = {
    val h = index(elemHashCode(key))
    val e = findEntry0(key, h)
    if (e ne null) e else { addEntry0(createNewEntry(key, value), h); null }
  }

  private[this] def findEntry0(key: A, h: Int): Entry = {
    var e = table(h).asInstanceOf[Entry]
    while (e != null && !elemEquals(e.key, key)) e = e.next
    e
  }

  private[this] def addEntry0(e: Entry, h: Int) {
    e.next = table(h).asInstanceOf[Entry]
    table(h) = e
    tableSize = tableSize + 1
    nnSizeMapAdd(h)
    if (tableSize > threshold)
      resize(2 * table.length)
  }
</code>```

2. If you use LinkedHashMap it maintains the order of insertion with use of linked entries

```<code>  @transient protected var firstEntry: Entry = null
  @transient protected var lastEntry: Entry = null
</code>```

example,

```<code>scala> import scala.collection.mutable.LinkedHashMap
import scala.collection.mutable.LinkedHashMap

scala> LinkedHashMap[String, String]()
res0: scala.collection.mutable.LinkedHashMap[String,String] = Map()

scala> res0 += "line-item1" -> "Delivered" += "line-item2" -> "Processing"
res2: res0.type = Map(line-item1 -> Delivered, line-item2 -> Processing)

scala> res0
res3: scala.collection.mutable.LinkedHashMap[String,String] = Map(line-item1 -> Delivered, line-item2 -> Processing)
</code>```

Title: Class mutable.HashTable in Scala

Body:
mutable.HashTable is a trait.

trait HashTable[A, Entry >: Null <: HashEntry[A, Entry]] extends HashTable.HashUtils[A]

with default load factor as 75%

private[collection] final def defaultLoadFactor: Int = 750

uses array for implementation,

protected var table: Array[HashEntry[A, Entry]] = new Array(initialCapacity)

1) you have to use implementations of HashTable, which are mutable.HashMap or mutable.LinkedHashMap.

example,

scala> import scala.collection.mutable.HashMap
import scala.collection.mutable.HashMap

scala> new HashMap[String, String]
res9: scala.collection.mutable.HashMap[String,String] = Map()

add element

scala> res9+= "order-id-1" -> "delivered"
res10: res9.type = Map(order-id-1 -> delivered)

scala> res9
res11: scala.collection.mutable.HashMap[String,String] = Map(order-id-1 -> delivered)

access element

scala> res9("order-id-1")
res12: String = delivered

Write complexity should be O(1) same as in hashmap datastructure. You find the hashcode and add to the array of Entry.

  def += (kv: (A, B)): this.type = {
    val e = findOrAddEntry(kv._1, kv._2)
    if (e ne null) e.value = kv._2
    this
  }

  protected def findOrAddEntry[B](key: A, value: B): Entry = {
    val h = index(elemHashCode(key))
    val e = findEntry0(key, h)
    if (e ne null) e else { addEntry0(createNewEntry(key, value), h); null }
  }

  private[this] def findEntry0(key: A, h: Int): Entry = {
    var e = table(h).asInstanceOf[Entry]
    while (e != null && !elemEquals(e.key, key)) e = e.next
    e
  }

  private[this] def addEntry0(e: Entry, h: Int) {
    e.next = table(h).asInstanceOf[Entry]
    table(h) = e
    tableSize = tableSize + 1
    nnSizeMapAdd(h)
    if (tableSize > threshold)
      resize(2 * table.length)
  }

2. If you use LinkedHashMap it maintains the order of insertion with use of linked entries

  @transient protected var firstEntry: Entry = null
  @transient protected var lastEntry: Entry = null

example,

scala> import scala.collection.mutable.LinkedHashMap
import scala.collection.mutable.LinkedHashMap

scala> LinkedHashMap[String, String]()
res0: scala.collection.mutable.LinkedHashMap[String,String] = Map()

scala> res0 += "line-item1" -> "Delivered" += "line-item2" -> "Processing"
res2: res0.type = Map(line-item1 -> Delivered, line-item2 -> Processing)

scala> res0
res3: scala.collection.mutable.LinkedHashMap[String,String] = Map(line-item1 -> Delivered, line-item2 -> Processing)


问:
Using findbugs-slf4j plugin with maven
I am trying findbugs-slf4j plugin with maven. As mentioned in their documentation I have added the below in my `pom.xml

```<code><plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>findbugs-maven-plugin</artifactId>
        <version>3.0.1</version>
        <configuration>
          <plugins>
            <plugin>
              <groupId>jp.skypencil.findbugs.slf4j</groupId>
              <artifactId>bug-pattern</artifactId>
              <version>1.2.4</version>
            </plugin>
          </plugins>
        </configuration>
      </plugin>
</code>```

To test this I added a log like below in my code

```<code>logger.error("Could not send inventory data to collector. Exception: {}", e); // where e is an instance of Exception
</code>```

But on compiling the project and then executing mvn findbugs:findbugs and then mvn findbugs:gui I am not seeing any bugs related to SLF4J_PLACE_HOLDER_MISMATCH.

EDIT
As suggested in one of the answer I changes my plugin dependency to

```<code><reporting>
        <plugins>
            <plugin>
                <groupId>com.github.spotbugs</groupId>
                <artifactId>spotbugs-maven-plugin</artifactId>
                <version>3.1.0-RC7</version>
                <configuration>
                    <plugins>
                        <plugin>
                            <groupId>jp.skypencil.findbugs.slf4j</groupId>
                            <artifactId>bug-pattern</artifactId>
                            <version>1.2.4</version>
                        </plugin>
                    </plugins>
                </configuration>
            </plugin>
        </plugins>
    </reporting>
</code>```

But on running mvn spotbugs:spotbugs it is throwing me the below error

```<code>No plugin found for prefix 'spotbugs' in the current project and in the plugin groups [org.apache.maven.plugins, org.codehaus.mojo] available from the repositories [local (/Users/dmanna/.m2/repository), central (http://artifactory.srk.local:8080/plugins-release), snapshots (http://artifactory.srk.local:8080/plugins-snapshot)]
</code>```

Can someone let me know what I am doing wrong?

答:
Wrong plugin and task

It looks like the documentation on this page is outdated and differs from the README which apparently is the correct one.
You should include the plugin using the following artifact:

```<code><groupId>com.github.spotbugs</groupId>
<artifactId>spotbugs-maven-plugin</artifactId>
<version>3.1.0-RC7</version>
</code>```

The correct maven task to use with this one is spotbugs:spotbugs instead of findbugs:findbugs.

Old answer

Let's see what the SLF4J_PLACE_HOLDER_MISMATCH rule checks for...

This pattern checks how placeholder is used. Alert if count of placeholder does not match to count of parameter.

You have one placeholder and one parameter, hence there is no violation of SLF4J_PLACE_HOLDER_MISMATCH as per the documentation, that's why you don't see any bugs reported. Keep in mind that this is not true for Throwable instances as they do not need a placeholder.

Try to use the test cases from the documentation to see if the plugin works correctly in your setup.

Title: Using findbugs-slf4j plugin with maven

Body:
I am trying findbugs-slf4j plugin with maven. As mentioned in their documentation I have added the below in my `pom.xml

<plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>findbugs-maven-plugin</artifactId>
        <version>3.0.1</version>
        <configuration>
          <plugins>
            <plugin>
              <groupId>jp.skypencil.findbugs.slf4j</groupId>
              <artifactId>bug-pattern</artifactId>
              <version>1.2.4</version>
            </plugin>
          </plugins>
        </configuration>
      </plugin>

To test this I added a log like below in my code

logger.error("Could not send inventory data to collector. Exception: {}", e); // where e is an instance of Exception

But on compiling the project and then executing mvn findbugs:findbugs and then mvn findbugs:gui I am not seeing any bugs related to SLF4J_PLACE_HOLDER_MISMATCH.

EDIT
As suggested in one of the answer I changes my plugin dependency to

<reporting>
        <plugins>
            <plugin>
                <groupId>com.github.spotbugs</groupId>
                <artifactId>spotbugs-maven-plugin</artifactId>
                <version>3.1.0-RC7</version>
                <configuration>
                    <plugins>
                        <plugin>
                            <groupId>jp.skypencil.findbugs.slf4j</groupId>
                            <artifactId>bug-pattern</artifactId>
                            <version>1.2.4</version>
                        </plugin>
                    </plugins>
                </configuration>
            </plugin>
        </plugins>
    </reporting>

But on running mvn spotbugs:spotbugs it is throwing me the below error

No plugin found for prefix 'spotbugs' in the current project and in the plugin groups [org.apache.maven.plugins, org.codehaus.mojo] available from the repositories [local (/Users/dmanna/.m2/repository), central (http://artifactory.srk.local:8080/plugins-release), snapshots (http://artifactory.srk.local:8080/plugins-snapshot)]

Can someone let me know what I am doing wrong?

Body:
Wrong plugin and task

It looks like the documentation on this page is outdated and differs from the README which apparently is the correct one.
You should include the plugin using the following artifact:

<groupId>com.github.spotbugs</groupId>
<artifactId>spotbugs-maven-plugin</artifactId>
<version>3.1.0-RC7</version>

The correct maven task to use with this one is spotbugs:spotbugs instead of findbugs:findbugs.

Old answer

Let's see what the SLF4J_PLACE_HOLDER_MISMATCH rule checks for...

This pattern checks how placeholder is used. Alert if count of placeholder does not match to count of parameter.

You have one placeholder and one parameter, hence there is no violation of SLF4J_PLACE_HOLDER_MISMATCH as per the documentation, that's why you don't see any bugs reported. Keep in mind that this is not true for Throwable instances as they do not need a placeholder.

Try to use the test cases from the documentation to see if the plugin works correctly in your setup.


问:
Scrambling/Unscrambling a string in Classic ASP
I'm wanting to send a string that has some meaning through the URL.

I know that I could probably do other things to send a string, but this is the only way in this situation.

I'm wanting send it and an unreadable format and be able to get the original string back later. I'm trying to avoid the words encrypt/decrypt because I've done research and It seems a bit more envolved than what I'm wanting in classic ASP( unless I'm missing something ). So I'm not really wanting to IMPLEMENT a encrypt/decrypt algorithm. I'm hoping there is something built into ASP that will allow me to do this.

I'm looking for both the way to scramble the message and a way to get it back.

Any suggestions?

答:
Why not send the information in a POST instead of a GET?  That way it's not visible to the user.  You would need to include more detail though for us to know if that is a viable options.

-- OR --

How about this genius code....

```<code><%

 'Functions for Encrypting/Decrypting querystrings

  '******************************'******************************

Function Encrypt(Input)

Dim Temp

Temp = CDbl(Input)
Temp = Temp * 7
Temp = Temp + 37
Temp = Temp * 13
Temp = Temp + 91

Encrypt = Temp

End Function 'Encrypt

'******************************

Function Decrypt(Input)

Dim Temp

Temp = CDbl(Input)
Temp = Temp - 91
Temp = Temp / 13
Temp = Temp - 37
Temp = Temp / 7

Decrypt = Temp

End Function 'Decrypt

'******************************

%>
</code>```

Bonus... Now you get to write your Sql Queries like this to find a record when the query string is encrypted...

Select * from sometable where id = (((@id * 7) + 37) *13) + 91

Please don't use this...

Body:
Why not send the information in a POST instead of a GET?  That way it's not visible to the user.  You would need to include more detail though for us to know if that is a viable options.

-- OR --

How about this genius code....

<%

 'Functions for Encrypting/Decrypting querystrings

  '******************************'******************************

Function Encrypt(Input)

Dim Temp

Temp = CDbl(Input)
Temp = Temp * 7
Temp = Temp + 37
Temp = Temp * 13
Temp = Temp + 91

Encrypt = Temp

End Function 'Encrypt

'******************************

Function Decrypt(Input)

Dim Temp

Temp = CDbl(Input)
Temp = Temp - 91
Temp = Temp / 13
Temp = Temp - 37
Temp = Temp / 7

Decrypt = Temp

End Function 'Decrypt

'******************************

%>

Bonus... Now you get to write your Sql Queries like this to find a record when the query string is encrypted...

Select * from sometable where id = (((@id * 7) + 37) *13) + 91

Please don't use this...


问:
How to extract only parameter value from URL using ONLY Regular Expressions
Extract the value of the u2 parameter from this URL using a regular expression. http://www.example.com?u1=US&u2=HA853&u3=HPA

```<code><?php
$subject="http://www.example.com?u1=US&u2=HA853&u3=HPA"; //my url
$pattern='/u2=[0-9A-Za-z]*/'; //R.E that url value is only digit/Alphabet
preg_match($pattern,$subject,$match);
print_r($match[0]);
?>
</code>```

Output:-
u2=HA853

How can i retrieve only HA853?

答:
The 0 group is everything that the regex matched so either use \K to ignore the previous matches of the regex,

```<code>$subject="http://www.example.com?u1=US&u2=HA853&u3=HPA"; //my url
$pattern='/u2=\K[0-9A-Za-z]*/'; //R.E that url value is only digit/Alphabet
preg_match($pattern,$subject,$match);
print_r($match[0]);
</code>```

or use a second capture group:

```<code>...
$pattern='/u2=([0-9A-Za-z]*)/'; //R.E that url value is only digit/Alphabet
...
print_r($match[1]);
</code>```

Why you'd need to do that though is unclear to me, http://php.net/manual/en/function.parse-str.php, seems like a simpler approach.

```<code>$subject="http://www.example.com?u1=US&u2=HA853&u3=HPA";
parse_str($subject, $output);
echo $output['u2'];
</code>```

Demo: https://3v4l.org/gR4cb

Body:
Extract the value of the u2 parameter from this URL using a regular expression. http://www.example.com?u1=US&u2=HA853&u3=HPA

<?php
$subject="http://www.example.com?u1=US&u2=HA853&u3=HPA"; //my url
$pattern='/u2=[0-9A-Za-z]*/'; //R.E that url value is only digit/Alphabet
preg_match($pattern,$subject,$match);
print_r($match[0]);
?>

Output:-
u2=HA853

How can i retrieve only HA853?

Body:
The 0 group is everything that the regex matched so either use \K to ignore the previous matches of the regex,

$subject="http://www.example.com?u1=US&u2=HA853&u3=HPA"; //my url
$pattern='/u2=\K[0-9A-Za-z]*/'; //R.E that url value is only digit/Alphabet
preg_match($pattern,$subject,$match);
print_r($match[0]);

or use a second capture group:

...
$pattern='/u2=([0-9A-Za-z]*)/'; //R.E that url value is only digit/Alphabet
...
print_r($match[1]);

Why you'd need to do that though is unclear to me, http://php.net/manual/en/function.parse-str.php, seems like a simpler approach.

$subject="http://www.example.com?u1=US&u2=HA853&u3=HPA";
parse_str($subject, $output);
echo $output['u2'];

Demo: https://3v4l.org/gR4cb


问:
Can I delete a OneDrive file after processing it in an Azure Function?
I have an Azure Function that triggers on OneDrive files being saved to a certain folder in my OneDrive account using the "External File (Preview) trigger" from the Azure Portal.

Now I also want to delete the processed file from OneDrive in the same function. Is this possible, and if so how do I do it?

答:
This is not currently supported by the OneDrive binding. If this is a feature you desire, you can request it here.

Note that you can make the size of the file 0 bytes by making the direction of your binding out and by making the parameter it is bound to an out string. If you set this parameters value to an empty string, then the content of the file will be replaced by that string, and the file will no longer take up any space, but will still be present.

If you still want to use exclusively functions to delete the binding, you can still use the Token binding to get an AAD token for Microsoft Graph, and use that token for authorization for one of these SDKs (probably the .NET and JavaScript ones would be the easiest to use within a Function). These SDKs should provide you with most of the capabilities of the MS Graph API, including OneDrive file deletion.


问:
Do triggers work for attachments object on insert event?
I have the requirement to calculate the number of attachments for custom object.
So I have written the trigger on attachment where as it was not working on Insert event. I want to check is insert event work on Attachments or not?</p>

答:
Okay so you're working with Files and not Attachments. Files work with ContentVersions, ContentDocuments and ContentDocumentLinks.

You want a trigger on a ContentVersion.


问:
Pass a reference to a ng-include dinamically
Basically what I am trying to solve is a working example of this Plunker where switching between the tabs I will have the upcoming visits and the completed visits using the same view but different parameter passed to the ng-include.

Explanation of the app in the Plunker (TL;DR)

In my app (AngularJS v1) I am using a module that is managing the tabs with some directives built in it (this is the GitHub reference about it).

Using this plugin, I am trying to include dynamically the same view (using ng-include) in the body of each tab.

```<code><ng-tabs ng-class="">
    <ng-tab-head ng-repeat="itemTab in itemTabs" ng-class="{ 'tabHead': true, 'active': itemTab.active }">
        {{ itemTab.tabHeader }}
    </ng-tab-head>

    <ng-tab-body ng-repeat="itemTab in itemTabs" ng-class="{ 'tabBody': true, 'active': itemTab.active }">
        <div ng-include="'app/visits/user-visits.html'" onload="userVisits(itemTab.visitState)"></div>

        <div ng-include="'app/visits/empty-visits.html'"></div>
    </ng-tab-body>
</ng-tabs>
</code>```

The data passed is something like this (the following array can contain dynamically more than 2 objects, this is why I am performing the ng-repeat in the code above):

```<code>$scope.itemTabs = [
    {
        tabHeader: 'Upcoming Visits',
        visitState: 'allocated',
        active: true
    },
    {
        tabHeader: 'Completed Visits',
        visitState: 'completed',
        active: false
    }
];
</code>```

The first view included in the tab body (user-visits.html), is a simple view that is also repeated multiple times and that is showing some details about the visits returned from an API request, while the second one is shown if there are no visits (empty-visits.html) for that specific body, but this is stuff that is already managed by the controller. The URL for the API is something like this:

```<code>'apiHost/api/users/visits?include=client,address&visit_state=' + visitState
</code>```

Basically all the visits (Upcoming and Completed) are coming from the same API request, with only a different parameter visitState passed in the URL. This parameter is the one that I would like to pass to the included view to tell the controller that is managing the request which tab has been shown so which request has to be performed by it.

Now, I have already tried  onload attribute as suggested here and here but this is not working, neither what is suggested here is working.

I think this is because the content of the tabs should refresh when there is the tab switching, and for this reason the content is not loaded only once at onload time. Am I wrong about this idea?

What is happening at the moment, is that the tabs plugin is working correctly (because I can see the index changing when I click on the tabs and here there is a working example), but the content is not changing between the tabs, it is only showing the first option (Upcoming Visits).

I have also tried using this specific directive

```<code>angular.module('app').directive('includeTemplate', directive);

function directive() {
    return {
        templateUrl: function (elem, attrs) {
            return attrs.includeTemplate;
        },
        restrict: 'EA',
        scope: {
            'includeVariables': '&'
        },
        link: function (scope, elem, attrs) {
            var vars = scope.includeVariables();
            Object.keys(vars).forEach(function (key) {
                scope[key] = vars[key];
            });
        }
    };
}
</code>```

That was suggested here, but it is also not working I think because it is expecting a clear value passed in and not a dynamic one as a include-variables. So in the tabs body I have used it

```<code><div include-template="'app/visits/user-visits.html'" include-variables="{{ itemTab.visitState }}"></div>
</code>```

Am I wrong somewhere?

Have you ever faced the problem with these dynamic levels?

As said at the beginning, I have created this simplified Plunker that is showing the whole problem. You can play with it and help me solve this problem.

答:
I came out with the introduction of AngularJS UI-Router as a solution for this problem.

This solution has also implied a complete redesign of the config function and the discard of several directive that I had tried to implement in the description above

Body:
Basically what I am trying to solve is a working example of this Plunker where switching between the tabs I will have the upcoming visits and the completed visits using the same view but different parameter passed to the ng-include.

Explanation of the app in the Plunker (TL;DR)

In my app (AngularJS v1) I am using a module that is managing the tabs with some directives built in it (this is the GitHub reference about it).

Using this plugin, I am trying to include dynamically the same view (using ng-include) in the body of each tab.

<ng-tabs ng-class="">
    <ng-tab-head ng-repeat="itemTab in itemTabs" ng-class="{ 'tabHead': true, 'active': itemTab.active }">
        {{ itemTab.tabHeader }}
    </ng-tab-head>

    <ng-tab-body ng-repeat="itemTab in itemTabs" ng-class="{ 'tabBody': true, 'active': itemTab.active }">

    </ng-tab-body>
</ng-tabs>

The data passed is something like this (the following array can contain dynamically more than 2 objects, this is why I am performing the ng-repeat in the code above):

$scope.itemTabs = [
    {
        tabHeader: 'Upcoming Visits',
        visitState: 'allocated',
        active: true
    },
    {
        tabHeader: 'Completed Visits',
        visitState: 'completed',
        active: false
    }
];

The first view included in the tab body (user-visits.html), is a simple view that is also repeated multiple times and that is showing some details about the visits returned from an API request, while the second one is shown if there are no visits (empty-visits.html) for that specific body, but this is stuff that is already managed by the controller. The URL for the API is something like this:

'apiHost/api/users/visits?include=client,address&visit_state=' + visitState

Basically all the visits (Upcoming and Completed) are coming from the same API request, with only a different parameter visitState passed in the URL. This parameter is the one that I would like to pass to the included view to tell the controller that is managing the request which tab has been shown so which request has to be performed by it.

Now, I have already tried  onload attribute as suggested here and here but this is not working, neither what is suggested here is working.

I think this is because the content of the tabs should refresh when there is the tab switching, and for this reason the content is not loaded only once at onload time. Am I wrong about this idea?

What is happening at the moment, is that the tabs plugin is working correctly (because I can see the index changing when I click on the tabs and here there is a working example), but the content is not changing between the tabs, it is only showing the first option (Upcoming Visits).

I have also tried using this specific directive

angular.module('app').directive('includeTemplate', directive);

function directive() {
    return {
        templateUrl: function (elem, attrs) {
            return attrs.includeTemplate;
        },
        restrict: 'EA',
        scope: {
            'includeVariables': '&'
        },
        link: function (scope, elem, attrs) {
            var vars = scope.includeVariables();
            Object.keys(vars).forEach(function (key) {
                scope[key] = vars[key];
            });
        }
    };
}

That was suggested here, but it is also not working I think because it is expecting a clear value passed in and not a dynamic one as a include-variables. So in the tabs body I have used it

Am I wrong somewhere?

Have you ever faced the problem with these dynamic levels?

As said at the beginning, I have created this simplified Plunker that is showing the whole problem. You can play with it and help me solve this problem.


问:
Netezza rows to columns showing duplicates

I am trying to transpose rows to columns.
One row per supplier with their yearly gross margin in columns.

This is the table given:

```<code>SELECT
SupplierName,
CASE WHEN YearID = 2018 THEN Shipping_cost ELSE NULL END SC_2018,
CASE WHEN YearID = 2017 THEN Shipping_cost ELSE NULL END SC_2017,
CASE WHEN YearID = 2016 THEN Shipping_cost ELSE NULL END SC_2016,

CASE WHEN YearID = 2018 THEN Retail_Percent_2018 ELSE NULL END Retail_2018,
CASE WHEN YearID = 2017 THEN Retail_Percent_2017 ELSE NULL END Retail_2017,
CASE WHEN YearID = 2016 THEN Retail_Percent_2016 ELSE NULL END Retail_2016

  FROM
    (
      SELECT
      SUPL.SUP_NAM AS SupplierName,
      SUPL.SUPL_CST AS Shipping_cost,

        (SELECT SUM(Shipping_Cost) FROM MM_TRX_TABLE S
        WHERE YearID = '2018') AS GRANDTOTAL_2018,

        (SELECT SUM(Shipping_Cost) FROM MM_TRX_TABLE S
        WHERE YearID = '2017')  AS GRANDTOTAL_2017,

         (SELECT SUM(Shipping_Cost) FROM MM_TRX_TABLE S
        WHERE YearID = '2016')  AS GRANDTOTAL_2016,

      SUM(SUPL.Retail_Cost) AS Retail_Total,

      CASE WHEN YearID = 2018
      THEN (Retail_Total/GRANDTOTAL_2018) * 100
      ELSE NULL END AS Retail_Percent_2018,

      CASE WHEN YearID = 2017
      THEN (Retail_Total/GRANDTOTAL_2017) * 100
      ELSE NULL END AS Retail_Percent_2017,

      CASE WHEN YearID = 2016
      THEN (Retail_Total/GRANDTOTAL_2016) * 100
      ELSE NULL END AS Retail_Percent_2016,

     FROM MM_TRX_TABLE S
      WHERE YEARID IN ('2018', '2017', '2016')

      GROUP BY
        SupplierName,
        YEARID,
        )DTL
   ORDER BY GrossMargin DESC
</code>```

I'm expecting the table to look like:

 But I get suppliers repeated in multiple rows.enter image description here

答:
I’ll give it a shot.

First of all: you are joining way too much for my taste. Remember that fewer joins generally means less decisions by the optimizer, therefore more robust code. Furthermore it is generally better performing in the first place.

If you disregard the fact that you wish the retail to be expressed as percentages per year it is very simple to solve:

```<code>Select
SupplierName,
Sum(CASE WHEN YearID = 2018 THEN Supl_cst ELSE NULL END) SC_2018,
Sum(CASE WHEN YearID = 2017 THEN Supl_cst ELSE NULL END) SC_2017,
Sum(CASE WHEN YearID = 2016 THEN Supl_cst ELSE NULL END) SC_2016,

Sum(CASE WHEN YearID = 2018 THEN Retail_cst ELSE NULL END) Retail_2018,
Sum(CASE WHEN YearID = 2017 THEN Retail_cst ELSE NULL END) Retail_2017,
Sum(CASE WHEN YearID = 2016 THEN Retail_cst ELSE NULL END) Retail_2016
FROM MM_TRX_TABLE S
  WHERE YEARID IN (2018,2017,2016)
GROUP BY SupplierName
</code>```

If you want the percentages, just join the totals back onto the first result and do the division inside the sum:

```<code>Select
SupplierName,
Sum(CASE WHEN YearID = 2018 THEN Supl_cst ELSE NULL END) SC_2018,
Sum(CASE WHEN YearID = 2017 THEN Supl_cst ELSE NULL END) SC_2017,
Sum(CASE WHEN YearID = 2016 THEN Supl_cst ELSE NULL END) SC_2016,

Sum(CASE WHEN YearID = 2018 THEN Retail_cst / Retail_total ELSE NULL END) Retail_2018,
Sum(CASE WHEN YearID = 2017 THEN Retail_cst / Retail_total ELSE NULL END) Retail_2017,
Sum(CASE WHEN YearID = 2016 THEN Retail_cst / Retail_total ELSE NULL END) Retail_2016
FROM MM_TRX_TABLE S
Join (select
        YearID,
        sum(Retail_cst) Retail_total
      Group by YearID
     ) T
Using (YearID)
  WHERE S.YEARID IN (2018,2017,2016)
GROUP BY SupplierName
</code>```

Body:
I am trying to transpose rows to columns.
One row per supplier with their yearly gross margin in columns.

This is the table given:

SELECT
SupplierName,
CASE WHEN YearID = 2018 THEN Shipping_cost ELSE NULL END SC_2018,
CASE WHEN YearID = 2017 THEN Shipping_cost ELSE NULL END SC_2017,
CASE WHEN YearID = 2016 THEN Shipping_cost ELSE NULL END SC_2016,

CASE WHEN YearID = 2018 THEN Retail_Percent_2018 ELSE NULL END Retail_2018,
CASE WHEN YearID = 2017 THEN Retail_Percent_2017 ELSE NULL END Retail_2017,
CASE WHEN YearID = 2016 THEN Retail_Percent_2016 ELSE NULL END Retail_2016

  FROM
    (
      SELECT
      SUPL.SUP_NAM AS SupplierName,
      SUPL.SUPL_CST AS Shipping_cost,

        (SELECT SUM(Shipping_Cost) FROM MM_TRX_TABLE S
        WHERE YearID = '2018') AS GRANDTOTAL_2018,

        (SELECT SUM(Shipping_Cost) FROM MM_TRX_TABLE S
        WHERE YearID = '2017')  AS GRANDTOTAL_2017,

         (SELECT SUM(Shipping_Cost) FROM MM_TRX_TABLE S
        WHERE YearID = '2016')  AS GRANDTOTAL_2016,

      SUM(SUPL.Retail_Cost) AS Retail_Total,

      CASE WHEN YearID = 2018
      THEN (Retail_Total/GRANDTOTAL_2018) * 100
      ELSE NULL END AS Retail_Percent_2018,

      CASE WHEN YearID = 2017
      THEN (Retail_Total/GRANDTOTAL_2017) * 100
      ELSE NULL END AS Retail_Percent_2017,

      CASE WHEN YearID = 2016
      THEN (Retail_Total/GRANDTOTAL_2016) * 100
      ELSE NULL END AS Retail_Percent_2016,

     FROM MM_TRX_TABLE S
      WHERE YEARID IN ('2018', '2017', '2016')

      GROUP BY
        SupplierName,
        YEARID,
        )DTL
   ORDER BY GrossMargin DESC

I'm expecting the table to look like:

 But I get suppliers repeated in multiple rows.enter image description here

Body:
I’ll give it a shot.

First of all: you are joining way too much for my taste. Remember that fewer joins generally means less decisions by the optimizer, therefore more robust code. Furthermore it is generally better performing in the first place.

If you disregard the fact that you wish the retail to be expressed as percentages per year it is very simple to solve:

Select
SupplierName,
Sum(CASE WHEN YearID = 2018 THEN Supl_cst ELSE NULL END) SC_2018,
Sum(CASE WHEN YearID = 2017 THEN Supl_cst ELSE NULL END) SC_2017,
Sum(CASE WHEN YearID = 2016 THEN Supl_cst ELSE NULL END) SC_2016,

Sum(CASE WHEN YearID = 2018 THEN Retail_cst ELSE NULL END) Retail_2018,
Sum(CASE WHEN YearID = 2017 THEN Retail_cst ELSE NULL END) Retail_2017,
Sum(CASE WHEN YearID = 2016 THEN Retail_cst ELSE NULL END) Retail_2016
FROM MM_TRX_TABLE S
  WHERE YEARID IN (2018,2017,2016)
GROUP BY SupplierName

If you want the percentages, just join the totals back onto the first result and do the division inside the sum:

Select
SupplierName,
Sum(CASE WHEN YearID = 2018 THEN Supl_cst ELSE NULL END) SC_2018,
Sum(CASE WHEN YearID = 2017 THEN Supl_cst ELSE NULL END) SC_2017,
Sum(CASE WHEN YearID = 2016 THEN Supl_cst ELSE NULL END) SC_2016,

Sum(CASE WHEN YearID = 2018 THEN Retail_cst / Retail_total ELSE NULL END) Retail_2018,
Sum(CASE WHEN YearID = 2017 THEN Retail_cst / Retail_total ELSE NULL END) Retail_2017,
Sum(CASE WHEN YearID = 2016 THEN Retail_cst / Retail_total ELSE NULL END) Retail_2016
FROM MM_TRX_TABLE S
Join (select
        YearID,
        sum(Retail_cst) Retail_total
      Group by YearID
     ) T
Using (YearID)
  WHERE S.YEARID IN (2018,2017,2016)
GROUP BY SupplierName


问:
Modal dimmed and nothing clickable on it
I'm trying to make a Bootstrap Modal open when a button is clicked, it does open but the whole screen including the modal is dimmed and I can not click on any of the buttons on it. Any idea what I am doing wrong? I am using Bootstrap 4 beta 2

    <meta charset="utf-8" />
    <meta name="viewport"
     content="width=device-width, initial-scale=1, shrink-to-fit=no" />
    <meta name="description" content="" />
    <meta name="author" content="" />

    <title>My site</title>

    <link rel="stylesheet"
     href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css"
     integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb"
     crossorigin="anonymous" />

       Home
       <button class="navbar-toggler" type="button" data-toggle="collapse"
        data-target="#navbarResponsive" aria-controls="navbarResponsive"
        aria-expanded="false" aria-label="Toggle navigation">

       </button>
       <button type="button" class="btn btn-danger" data-toggle="modal"
        data-target="#myModal">Upload</button>

Home
           (current)

About

Contact

Modal title

          <button type="button" class="close" data-dismiss="modal"
           aria-label="Close">
           ×
          </button>

...

          <button type="button" class="btn btn-secondary"
           data-dismiss="modal">Close</button>
          <button type="button" class="btn btn-primary">Save
           changes</button>

Copyright © MySite
        2017

    ```

答:
Move your modal code outside of the nav tag as below. I'm honestly not 100% sure of the reason but I have had this issue before

Don't change any bootstrap css as it most likely will be problematic in the future. Just move the code a line down.

    <meta charset="utf-8" />
    <meta name="viewport"
     content="width=device-width, initial-scale=1, shrink-to-fit=no" />
    <meta name="description" content="" />
    <meta name="author" content="" />

    <title>My site</title>

    <link rel="stylesheet"
     href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css"
     integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb"
     crossorigin="anonymous" />

       Home
       <button class="navbar-toggler" type="button" data-toggle="collapse"
        data-target="#navbarResponsive" aria-controls="navbarResponsive"
        aria-expanded="false" aria-label="Toggle navigation">

       </button>
       <button type="button" class="btn btn-danger" data-toggle="modal"
        data-target="#myModal">Upload</button>

Home
           (current)

About

Contact

Modal title

          <button type="button" class="close" data-dismiss="modal"
           aria-label="Close">
           ×
          </button>

...

          <button type="button" class="btn btn-secondary"
           data-dismiss="modal">Close</button>
          <button type="button" class="btn btn-primary">Save
           changes</button>

Copyright © MySite
        2017

    ```

Body:
Move your modal code outside of the nav tag as below. I'm honestly not 100% sure of the reason but I have had this issue before

Don't change any bootstrap css as it most likely will be problematic in the future. Just move the code a line down.

    <html>
    <head th:fragment="head">
    <meta charset="utf-8" />
    <meta name="viewport"
     content="width=device-width, initial-scale=1, shrink-to-fit=no" />
    <meta name="description" content="" />
    <meta name="author" content="" />

    <title>My site</title>

    <!-- Bootstrap core CSS -->
    <link rel="stylesheet"
     href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css"
     integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb"
     crossorigin="anonymous" />

    <script>
     $('#myModal').on('shown.bs.modal', function() {
      $('#myInput').focus()
     })
    </script>
    </head>
    <body>

     <!-- Navigation -->
     <nav
      class="navbar navbar-expand-lg navbar-dark bg-dark fixed-top">

      <div class="container">
       <a class="navbar-brand" href="/">Home</a>
       <button class="navbar-toggler" type="button" data-toggle="collapse"
        data-target="#navbarResponsive" aria-controls="navbarResponsive"
        aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
       </button>
       <button type="button" class="btn btn-danger" data-toggle="modal"
        data-target="#myModal">Upload</button>
       <div class="collapse navbar-collapse" id="navbarResponsive">
        <ul class="navbar-nav ml-auto">
         <li class="nav-item active"><a class="nav-link" href="#">Home
           <span class="sr-only">(current)</span>
         </a></li>
         <li class="nav-item"><a class="nav-link" href="#">About</a></li>
         <li class="nav-item"><a class="nav-link" href="#">Contact</a>
         </li>
        </ul>
       </div>
      </div>

     </nav>

      <!-- Modal -->
      <div class="modal fade" id="myModal" tabindex="-1" role="dialog"
       aria-labelledby="exampleModalLabel" aria-hidden="true">
       <div class="modal-dialog" role="document">
        <div class="modal-content">
         <div class="modal-header">
          <h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
          <button type="button" class="close" data-dismiss="modal"
           aria-label="Close">
           <span aria-hidden="true">&times;</span>
          </button>
         </div>
         <div class="modal-body">...</div>
         <div class="modal-footer">
          <button type="button" class="btn btn-secondary"
           data-dismiss="modal">Close</button>
          <button type="button" class="btn btn-primary">Save
           changes</button>
         </div>
        </div>
       </div>
      </div>

     <!-- Footer -->
     <footer class="py-5 bg-dark">
      <div class="container">
       <p class="m-0 text-center text-white">Copyright &copy; MySite
        2017</p>
      </div>
      <!-- /.container -->

      <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"
       integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN"
       crossorigin="anonymous" async="async"></script>
      <script
       src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js"
       integrity="sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh"
       crossorigin="anonymous" async="async"></script>
      <script
       src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js"
       integrity="sha384-alpBpkh1PFOepccYVYDB4do5UnbKysX5WZXm3XxPqe5iKTfUKjNkCk9SaVuEZflJ"
       crossorigin="anonymous" async="async"></script>

      <!--modal-->
      <script>
       $(document).ready(function() {
        $("#myModal").modal();
       });
      </script>
     </footer>
    </body>
    </html>


问:
What is AABB? Explanation required
What is AABB? A king of preview-collision before the real collision detection (I mean, the accurate one)?

I displayed the debug shapes and set up b2DebugDraw.e_aabbBit flag in order to see it in action. I put a simple box falling, and when the box hit the ground, the AABB frame is completely different.

答:
I think the other respondent already addressed what an AABB is. This response adds to their answer by explaining why the AABB you've drawn could be bigger and of different shape.

The AABB that's being displayed here looks like an AABB calculated for a square that's been dropped onto the green surface. That would at least explain why the AABB is bigger and why the AABB isn't the same shape.

Here's why...

While an AABB can serve as a minimally enclosing axis-aligned bounding box for any shape, Box2D also uses AABBs that encompass some movement and some additional wiggle room for future movement.

Take void b2Fixture::CreateProxies(b2BroadPhase* broadPhase, const b2Transform& xf) for example. Here Box2D calculates AABBs using the shape's ComputeAABB method which basically just calculates the minimal enclosure. This method is called for every "child" shape when first creating a new fixture (where any shape may be composed of 1 or more sub-shapes that are called "child" shapes).

OTOH, take a look at void b2Fixture::Synchronize(b2BroadPhase* broadPhase, const b2Transform& transform1, const b2Transform& transform2). This method is invoked from calling the world step method which calls it for all bodies that may have moved. When it calculates AABBs, it:

computes an AABB for where every child shape has been,

computes an AABB for where every child shape has gone to (in that step),

combines the two AABBs for every child shape into the "proxy" AABB (see void b2AABB::Combine(const b2AABB& aabb1, const b2AABB& aabb2)), and finally

calls broadPhase->MoveProxy(proxy->proxyId, proxy->aabb, displacement) which adds some predictive room to each AABB.

So as to why specifically the AABB drawn could be bigger and of different shape: step 3 often results in an AABB enlarged to hold most of the entire sweep of the child shape, and step 4 results in an AABB that's further extended on all sides by b2_aabbExtension and additionally extended in the direction of travel (by b2_aabbMultiplier * displacement).

Hope this helps!

Title: What is AABB? Explanation required


问:
Java Matcher overreplacing groups
```<code>public class HexASCIITest {
public static void main(String[] args) throws DecoderException, UnsupportedEncodingException {

    String test = "src=\"test/__test/path/path2/AA_5F00_20140915_5F00_15_5F00_11_5F00_55_5F00_image_5F005F00_name.jpg\"";

    Pattern patternImages = Pattern.compile("src=\"[^\"]*?/__test/[^/]*?/[^/]*?/([^\"/]*?)\"");
    Matcher matcherImages = patternImages.matcher(test);

    while(matcherImages.find()) {
        String imageName = matcherImages.group(1);

        Pattern pattern = Pattern.compile("_((?:[01234567890ABCDEF]{4}){1,})_");
        Matcher matcher = pattern.matcher(imageName);

        while(matcher.find()) {
            byte[] bytes = Hex.decodeHex(matcher.group(1).toCharArray());
            String imagePath = new String(bytes, "latin1");
            imagePath = imagePath.replaceAll("\0", "");
            imageName = imageName.replaceFirst("_((?:[01234567890ABCDEF]{4}){1,})_", imagePath.trim());
        }
        System.out.println(imageName);
    }
}
}
</code>```

Hi guys, this is a program of mine, that should actually turn the HEX codes to ASCII, but it seems i am having logic problems, could anyone assist me ?

The initial image name is  : AA_5F00_20140915_5F00_15_5F00_11_5F00_55_5F00_image_5F005F00_name.jpg
After all of the replaces : AA_15_11_55__image_5F005F00_name.jpg

Which is not how it is supposed to work as the date 20140915 is gone and 5F005F00 is still there. Thank you for your help !

答:
Found it
Regex should be - Pattern pattern = Pattern.compile("(([0123456789ABCDEF]{4}){1,})");

Then - > byte[] bytes = Hex.decodeHex(matcher.group(2).toCharArray());

and finally the replace
imageName = imageName.replaceFirst(matcher.group(1), imagePath.trim());

Title: Java Matcher overreplacing groups

Body:
public class HexASCIITest {
public static void main(String[] args) throws DecoderException, UnsupportedEncodingException {

    String test = "src=\"test/__test/path/path2/AA_5F00_20140915_5F00_15_5F00_11_5F00_55_5F00_image_5F005F00_name.jpg\"";

    Pattern patternImages = Pattern.compile("src=\"[^\"]*?/__test/[^/]*?/[^/]*?/([^\"/]*?)\"");
    Matcher matcherImages = patternImages.matcher(test);

    while(matcherImages.find()) {
        String imageName = matcherImages.group(1);

        Pattern pattern = Pattern.compile("_((?:[01234567890ABCDEF]{4}){1,})_");
        Matcher matcher = pattern.matcher(imageName);

        while(matcher.find()) {
            byte[] bytes = Hex.decodeHex(matcher.group(1).toCharArray());
            String imagePath = new String(bytes, "latin1");
            imagePath = imagePath.replaceAll("\0", "");
            imageName = imageName.replaceFirst("_((?:[01234567890ABCDEF]{4}){1,})_", imagePath.trim());
        }
        System.out.println(imageName);
    }
}
}

Hi guys, this is a program of mine, that should actually turn the HEX codes to ASCII, but it seems i am having logic problems, could anyone assist me ?

The initial image name is  : AA_5F00_20140915_5F00_15_5F00_11_5F00_55_5F00_image_5F005F00_name.jpg
After all of the replaces : AA_15_11_55__image_5F005F00_name.jpg

Which is not how it is supposed to work as the date 20140915 is gone and 5F005F00 is still there. Thank you for your help !


问:
Lagom Cassandra Driver
According to some research about Lagom and Cassandra, I found that:

Lagom uses DataStax Java Driver for Cassandra, and

DataStax Java Driver only supports Cassandra 3.0.x (link)

So, if I want to use Cassandra 3.11 and Lagom, what should I do:

Should I configure Lagom with another Cassandra driver like  Achilles, PlayORM, ... (link). Is that possible?

is DataStax support Cassandra 3.11 in the enterprise edition?

Any help, please?

答:
DataStax Java Driver 3.2.0 that is used by Lagom should work with Cassandra 3.11 out of the box (just checked it myself using simple queries).

Even if it won't work out of the box, you can explicitly override driver version in Maven or other build system.

Title: Lagom Cassandra Driver


问:
Unable to issue identity in Hyperledger Composer

I am trying to issue an identity to a participant that already exists in the network.

```<code> return this.bizNetworkConnection.connect(this.cardname)
     .then((result) => {
         let email = 'user@gmail.com',
             username = email.split('@')[0];

         this.businessNetworkDefinition = result;

         return this.bizNetworkConnection.issueIdentity('org.test.Person#user@gmail.com', username);
     })
    .then((result) => {
        console.log(`userID = ${result.userID}`);
        console.log(`userSecret = ${result.userSecret}`);

     })
</code>```

I expect that I will see the userID and the userSecret logged on the console but I am getting errors as described below.

Following the developer tutorial on their documents:

If I use the card name for PeerAdmin@hlfv1 on the connect function above, I get the error. "Error trying to ping. Error: Error trying to query business network. Error: Missing \"chaincodeId\" parameter in the proposal request"

If I use the card name for admin@tutorial-network on the connect function above, I get the error "fabric-ca request register failed with errors [[{\"code\":400,\"message\":\"Authorization failure\"}]]"

For option 1, I know the network name is missing in the given card, whie option 2 means that the admin has no rights to issue an identity. However, I cannot seem to find any documentation directing me on how to use either to achieve my objective. Any help is highly welcome.

While I have listed the javascript code I am using to achieve the same, I would not mind if anyone can explain what I am missing using the composer cli.

答:
see https://hyperledger.github.io/composer/latest/managing/identity-issue.html

you would definitely use the admin@tutorial-network card, as PeerAdmin does not have authority to issue identities (admin does).

Did you already do: 1) a composer card import -f networkadmin.card (per the tutorial)  ? 2) a composer network ping -c admin@tutorial-network to use the card (now in the card store) and thereby populate the admin's credentials (certificate/private key).

Only at that point would admin be recognised as the identity to issue further identities. Is it possible you spun up a new dockerized CA server at some stage since you did the import etc ?

What happens if you issue a test identity through the command line (using admin@tutorial-network? Does it fail)

Body:
I am trying to issue an identity to a participant that already exists in the network.

 return this.bizNetworkConnection.connect(this.cardname)
     .then((result) => {
         let email = 'user@gmail.com',
             username = email.split('@')[0];

         this.businessNetworkDefinition = result;

         return this.bizNetworkConnection.issueIdentity('org.test.Person#user@gmail.com', username);
     })
    .then((result) => {
        console.log(`userID = ${result.userID}`);
        console.log(`userSecret = ${result.userSecret}`);

     })

I expect that I will see the userID and the userSecret logged on the console but I am getting errors as described below.

Following the developer tutorial on their documents:

If I use the card name for PeerAdmin@hlfv1 on the connect function above, I get the error. "Error trying to ping. Error: Error trying to query business network. Error: Missing \"chaincodeId\" parameter in the proposal request"

If I use the card name for admin@tutorial-network on the connect function above, I get the error "fabric-ca request register failed with errors [[{\"code\":400,\"message\":\"Authorization failure\"}]]"

For option 1, I know the network name is missing in the given card, whie option 2 means that the admin has no rights to issue an identity. However, I cannot seem to find any documentation directing me on how to use either to achieve my objective. Any help is highly welcome.

While I have listed the javascript code I am using to achieve the same, I would not mind if anyone can explain what I am missing using the composer cli.


问:
Bitbucket private repository limits for free plan
I'm a university professor teaching a programming class. There will be a group assignment for this class and I'd like to monitor each group's progress, therefore I thought of using GitHub or Bitbucket to host the assignments. Each group will be composed of at most 4 students, and of course I will need to be able to see the repository as well.

Thus there will be a repository containing myself and students A, B, C and D, a second repository containing myself and students E, F, G and H, a third repository containing myself and students I, J, K and L, and so on.

Due to the particulars of this assignment, the repositories must necessarily be private.

I understand GitHub doesn't offer free private repositories, so I've crossed out that option. As for Bitbucket, am I correct in assuming that this doesn't exceed the limits for the free plan? If it does, are there other Git hosting services where I could host these assignments for free?

答:
Have a look at GitHub education plan: https://education.github.com/

Also, GitLab is another alternative to GitHub and BitBucket. You can even host it on your network (for free)


问:
Linear and Unique types with mkPair
I've been reading through this article here http://edsko.net/2017/01/08/linearity-in-haskell/ and the author mentions that one can construct a non-unique array with unique elements but that you can't extract them.

I.e.

```<code>mkPair :: 1:a -> 1:b -> ω:(1:a, 1:b) -- correct but useless
mkPair x y = (x, y)
</code>```

but couldn't you read the elements once in the calling function? Maybe I'm missing something.

Also, although legal, this same function is illegal when looking at it from a linearity perspective. But I thought these were just 2 sides of the same coin, so the function would not change legality depending upon perspective.

答:
Actually, mkPair is ill-typed (as the blog itself states), since its return type allows one to duplicate the resulting pair. So, any caller having unique values of types a and b, could make a pair, duplicate it, and take the four components (two from each pair), and obtain two values of type a, and two values of type b.

This would circumvent the linearity of a and b, so there must be no function having a type as the one of mkPair you show above.

Title: Linear and Unique types with mkPair

Body:
I've been reading through this article here http://edsko.net/2017/01/08/linearity-in-haskell/ and the author mentions that one can construct a non-unique array with unique elements but that you can't extract them.

I.e.

mkPair :: 1:a -> 1:b -> ω:(1:a, 1:b) -- correct but useless
mkPair x y = (x, y)

but couldn't you read the elements once in the calling function? Maybe I'm missing something.

Also, although legal, this same function is illegal when looking at it from a linearity perspective. But I thought these were just 2 sides of the same coin, so the function would not change legality depending upon perspective.