问:
Pdf Writer for Rails 3
Does anyone know of a PDF writer that is easy and works well with Rails 3? If so can someone point me to it and instructs on how to configure it to work with Rails 3?</p>

答:
There are mainly two ways to do a pdf in Rails.

Either you build it from scratch, or use something to generate pdf from html. second one is easier but might not be sufficient if what you're trying to put inside a pdf is more complex.

If you want total control over your pdf, you have to build it from scratch. For that, use a combination between prawn and prawnto.

For the second option, which is easier, you can use PDFKit, which uses wkhtmltopdf to generate pdf straight from a html page. I recommend starting with this one and see if it suits your purposes; then, if you think you need more control and this isn't enough, use prawn.

Title: Pdf Writer for Rails 3


来源: stackexchange

问:
SQL Server Left Join Counting
I got this sample code

```<code>create table #Reservation
(id int identity(1,1),
 name varchar(50)
);

create table #Reservation_details
(id int identity(1,1),
 reservation_id int,
 reservation_date date,
 seated tinyint
);

create table #Payment
(id int identity(1,1),
 reservation_id int,
 payment decimal(18,2)
);

insert into #Reservation(name)
values ('Spiderman'),('Superman'),('Batman'),('Hulk');

insert into #Reservation_details(reservation_id,reservation_date,seated)
values (1,'2017-12-07',0),(2,'2017-12-08',0),(3,'2017-12-08',1),(4,'2017-12-08',0);

insert into #Payment(reservation_id,payment)
values(1,220),(2,1000)

select
 A.id,
 A.name,
 B.reservation_date,
 B.seated,
 C.payment
from #Reservation A
inner join #Reservation_details B
on B.reservation_id = A.id
left join #Payment C
on C.reservation_id = B.reservation_id
where reservation_date = '2017-12-08'

drop table #Reservation
drop table #Reservation_details
drop table #Payment
</code>```

I wanted to get the count of all reservations where date is '2017-12-08' and seated = 1 or payment is not null

I've tried putting where date is '2017-12-08' and seated = 1 or payment is not
null

but instead it showed me the past date also how do use where as count?

答:
Try it

```<code>select COUNT(*)
from #Reservation A
inner join #Reservation_details B on B.reservation_id = A.id
left join #Payment C on C.reservation_id = B.reservation_id
where reservation_date = '2017-12-08'
  and (B.seated=1 or C.payment is not null)
</code>```

I think you forgot to use brackets (condition1 OR condition2) for OR operation.

See operator precedence - https://learn.microsoft.com/en-us/sql/t-sql/language-elements/operator-precedence-transact-sql

In your case if you don't use brackets then

```<code>reservation_date = '2017-12-08' and B.seated=1 or C.payment is not null
</code>```

equals the following

```<code>(reservation_date = '2017-12-08' and B.seated=1) or C.payment is not null
</code>```

ContentLicense: CC BY-SA 3.0

Title: SQL Server Left Join Counting

Body:
I got this sample code

create table #Reservation
(id int identity(1,1),
 name varchar(50)
);

create table #Reservation_details
(id int identity(1,1),
 reservation_id int,
 reservation_date date,
 seated tinyint
);

create table #Payment
(id int identity(1,1),
 reservation_id int,
 payment decimal(18,2)
);

insert into #Reservation(name)
values ('Spiderman'),('Superman'),('Batman'),('Hulk');

insert into #Reservation_details(reservation_id,reservation_date,seated)
values (1,'2017-12-07',0),(2,'2017-12-08',0),(3,'2017-12-08',1),(4,'2017-12-08',0);

insert into #Payment(reservation_id,payment)
values(1,220),(2,1000)

select
 A.id,
 A.name,
 B.reservation_date,
 B.seated,
 C.payment
from #Reservation A
inner join #Reservation_details B
on B.reservation_id = A.id
left join #Payment C
on C.reservation_id = B.reservation_id
where reservation_date = '2017-12-08'

drop table #Reservation
drop table #Reservation_details
drop table #Payment

I wanted to get the count of all reservations where date is '2017-12-08' and seated = 1 or payment is not null

I've tried putting where date is '2017-12-08' and seated = 1 or payment is not
null

but instead it showed me the past date also how do use where as count?

Body:
Try it

select COUNT(*)
from #Reservation A
inner join #Reservation_details B on B.reservation_id = A.id
left join #Payment C on C.reservation_id = B.reservation_id
where reservation_date = '2017-12-08'
  and (B.seated=1 or C.payment is not null)

I think you forgot to use brackets (condition1 OR condition2) for OR operation.

See operator precedence - https://learn.microsoft.com/en-us/sql/t-sql/language-elements/operator-precedence-transact-sql

In your case if you don't use brackets then

reservation_date = '2017-12-08' and B.seated=1 or C.payment is not null

equals the following

(reservation_date = '2017-12-08' and B.seated=1) or C.payment is not null


问:
Empty content on the downloaded PDF using itextsharp in WebAPI 2 response
```<code>public IHttpActionResult DownloadPDF()
{
    var stream = CreatePdf();

    return ResponseMessage(new HttpResponseMessage
    {
        Content = new StreamContent(stream)
        {
            Headers =
            {
                ContentType = new MediaTypeHeaderValue("application/pdf"),
                ContentDisposition = new ContentDispositionHeaderValue("attachment")
                {
                    FileName = "myfile.pdf"
                }
            }
        },
        StatusCode = HttpStatusCode.OK
    });
}
Here is the CreatePdf method:

private Stream CreatePdf()
{
    using (var document = new Document(PageSize.A4, 50, 50, 25, 25))
    {
        var output = new MemoryStream();

        var writer = PdfWriter.GetInstance(document, output);
        writer.CloseStream = false;

        document.Open();
        document.Add(new Paragraph("Hello World"));
        document.Close();

        output.Seek(0, SeekOrigin.Begin);

        return output;
    }
}
</code>```

<p>I can able to download the PDF but the context is empty. Here I am using memory stream and I also tried with file stream its downloading in the respective folder but if I tried to open the downloaded file then also the content is empty. Can anyone help me what I'm missing here? </p>

答:
Here is an approach that usually works for me when using Web API

```<code>private byte[] CreatePdf() {
    var buffer = new byte[0];
    //stream to hold output data
    var output = new MemoryStream();
    //creation of a document-object
    using (var document = new Document(PageSize.A4, 50, 50, 25, 25)) {
        //create a writer that listens to the document
        // and directs a PDF-stream to output stream
        var writer = PdfWriter.GetInstance(document, output);

        //open the document
        document.Open();

        // Create a page in the document
        document.NewPage();

        // Get the top layer to write some text
        var pdfContentBytes = writer.DirectContent;
        pdfContentBytes.BeginText();

        //add content to page
        document.Add(new Paragraph("Hello World"));

        //done writing text
        pdfContentBytes.EndText();

        // make sure any data in the buffer is written to the output stream
        writer.Flush();

        document.Close();
    }
    buffer = output.GetBuffer();
    return buffer;
}
</code>```

And then in the action

```<code>public IHttpActionResult DownloadPDF() {
    var buffer = CreatePdf();

    return ResponseMessage(new HttpResponseMessage {
        Content = new StreamContent(new MemoryStream(buffer)) {
            Headers = {
                ContentType = new MediaTypeHeaderValue("application/pdf"),
                ContentDisposition = new ContentDispositionHeaderValue("attachment") {
                    FileName = "myfile.pdf"
                }
            }
        },
        StatusCode = HttpStatusCode.OK
    });
}
</code>```

Body:
public IHttpActionResult DownloadPDF()
{
    var stream = CreatePdf();

    return ResponseMessage(new HttpResponseMessage
    {
        Content = new StreamContent(stream)
        {
            Headers =
            {
                ContentType = new MediaTypeHeaderValue("application/pdf"),
                ContentDisposition = new ContentDispositionHeaderValue("attachment")
                {
                    FileName = "myfile.pdf"
                }
            }
        },
        StatusCode = HttpStatusCode.OK
    });
}
Here is the CreatePdf method:

private Stream CreatePdf()
{
    using (var document = new Document(PageSize.A4, 50, 50, 25, 25))
    {
        var output = new MemoryStream();

        var writer = PdfWriter.GetInstance(document, output);
        writer.CloseStream = false;

        document.Open();
        document.Add(new Paragraph("Hello World"));
        document.Close();

        output.Seek(0, SeekOrigin.Begin);

        return output;
    }
}

I can able to download the PDF but the context is empty. Here I am using memory stream and I also tried with file stream its downloading in the respective folder but if I tried to open the downloaded file then also the content is empty. Can anyone help me what I'm missing here?

Body:
Here is an approach that usually works for me when using Web API

private byte[] CreatePdf() {
    var buffer = new byte[0];
    //stream to hold output data
    var output = new MemoryStream();
    //creation of a document-object
    using (var document = new Document(PageSize.A4, 50, 50, 25, 25)) {
        //create a writer that listens to the document
        // and directs a PDF-stream to output stream
        var writer = PdfWriter.GetInstance(document, output);

        //open the document
        document.Open();

        // Create a page in the document
        document.NewPage();

        // Get the top layer to write some text
        var pdfContentBytes = writer.DirectContent;
        pdfContentBytes.BeginText();

        //add content to page
        document.Add(new Paragraph("Hello World"));

        //done writing text
        pdfContentBytes.EndText();

        // make sure any data in the buffer is written to the output stream
        writer.Flush();

        document.Close();
    }
    buffer = output.GetBuffer();
    return buffer;
}

And then in the action

public IHttpActionResult DownloadPDF() {
    var buffer = CreatePdf();

    return ResponseMessage(new HttpResponseMessage {
        Content = new StreamContent(new MemoryStream(buffer)) {
            Headers = {
                ContentType = new MediaTypeHeaderValue("application/pdf"),
                ContentDisposition = new ContentDispositionHeaderValue("attachment") {
                    FileName = "myfile.pdf"
                }
            }
        },
        StatusCode = HttpStatusCode.OK
    });
}


问:
Add a diagonal of zeros to a matrix in MATLAB
Suppose I have a matrix A of dimension Nx(N-1) in MATLAB, e.g.

```<code>N=5;
A=[1  2  3  4;
   5  6  7  8;
   9  10 11 12;
   13 14 15 16;
   17 18 19 20 ];
</code>```

I want to transform A into an NxN matrix B, just by adding a zero diagonal, i.e.,

```<code>B=[ 0  1   2   3   4;
    5  0   6   7   8;
    9  10  0   11  12;
    13 14  15  0   16;
    17 18  19  20  0];
</code>```

This code does what I want:

```<code>B_temp = zeros(N,N);
B_temp(1,:) = [0 A(1,:)];
B_temp(N,:) = [A(N,:) 0];
for j=2:N-1
    B_temp(j,:)= [A(j,1:j-1) 0 A(j,j:end)];
end
B = B_temp;
</code>```

Could you suggest an efficient way to vectorise it?

答:
Generate a matrix with zeros at diagonal and ones at non-diagonal indices. Replace the non-diagonal elements with the transpose of A (since MATLAB is column major). Transpose again to get the correct order.

```<code>B = double(~eye(N));  %Converting to double since we want to replace with double entries
B(find(B)) = A.';     %Replacing the entries
B = B.';              %Transposing again to get the matrix in the correct order
</code>```

Edit:

As suggested by Wolfie for the same algorithm, you can get rid of conversion to double and the use of find with:

```<code>B = 1-eye(N);
B(logical(B)) = A.';
B = B.';
</code>```

Body:
Suppose I have a matrix A of dimension Nx(N-1) in MATLAB, e.g.

N=5;
A=[1  2  3  4;
   5  6  7  8;
   9  10 11 12;
   13 14 15 16;
   17 18 19 20 ];

I want to transform A into an NxN matrix B, just by adding a zero diagonal, i.e.,

B=[ 0  1   2   3   4;
    5  0   6   7   8;
    9  10  0   11  12;
    13 14  15  0   16;
    17 18  19  20  0];

This code does what I want:

B_temp = zeros(N,N);
B_temp(1,:) = [0 A(1,:)];
B_temp(N,:) = [A(N,:) 0];
for j=2:N-1
    B_temp(j,:)= [A(j,1:j-1) 0 A(j,j:end)];
end
B = B_temp;

Could you suggest an efficient way to vectorise it?

Body:
Generate a matrix with zeros at diagonal and ones at non-diagonal indices. Replace the non-diagonal elements with the transpose of A (since MATLAB is column major). Transpose again to get the correct order.

B = double(~eye(N));  %Converting to double since we want to replace with double entries
B(find(B)) = A.';     %Replacing the entries
B = B.';              %Transposing again to get the matrix in the correct order

Edit:

As suggested by Wolfie for the same algorithm, you can get rid of conversion to double and the use of find with:

B = 1-eye(N);
B(logical(B)) = A.';
B = B.';


问:
Redux - update parents props via Redux?
I have a dynamic router that takes routes as props of <App>. By default all routes are blocked and user can only go to Payments.

A few levels deep I have <Payments>. Once you do your first payment you should be able to access the whole app, in short:

```<code><App> -> <OtherComponent> -> <OtherComponent> - <Payments>
</code>```

I want to dispatch an action in <Payments> (grandchild) that will change redux state in <App> reducer and change <App> props (grandparent), how do I handle this? As far as I'm concerned I'm only allowed to mapStateToProps in <Payments> but the router is in <App>.

I'm using basic react-router and would rather not change it for anything else (eg. react-redux-router).

答:
I think I got the Redux part just right, the problem I have is
  CombineReducers, with one big flat state it would be easy peasy for me
  to do what I want to achieve but I feel like my state is now not truly
  global but split between 3 different reducers and they don't have
  access to each other.

You can safely listen to the same actions in multiple reducers. That's also good practice to do so. Imagine an action that has an impact in multiple places of your store. Every nested structure will have it's own reducer and therefore you will have to listen to that action in multiple reducers. That is totally fine.

Title: Redux - update parents props via Redux?

Body:
I have a dynamic router that takes routes as props of <App>. By default all routes are blocked and user can only go to Payments.

A few levels deep I have <Payments>. Once you do your first payment you should be able to access the whole app, in short:

<App> -> <OtherComponent> -> <OtherComponent> - <Payments>

I want to dispatch an action in <Payments> (grandchild) that will change redux state in <App> reducer and change <App> props (grandparent), how do I handle this? As far as I'm concerned I'm only allowed to mapStateToProps in <Payments> but the router is in <App>.

I'm using basic react-router and would rather not change it for anything else (eg. react-redux-router).


问:
How to fix d3.js chart scaling
I would like to this.

But when I zoom it, the line is out of the area.

line definition:

```<code>var valueline_1 = d3.line()
  .x(function (d) { return x_1(parseDate(d.date)); })
  .y(function (d) { return y_1(d.count); });

var valueline2_1 = d3.line()
  .x(function (d) { return x2_1(parseDate(d.date)); })
  .y(function (d) { return y2_1(d.count); });
</code>```

and then this code:

```<code>focus_1.append("path")
  .data([data])
  .attr("class", "line")
  .attr("d", valueline_1(i));

context_1.append("path")
  .data([data])
  .attr("class", "line")
  .attr("d", valueline2_1);
</code>```

Can you help how to fix it?

thx.

EDIT:
This code for zoom:

```<code>var zoom_0 = d3.zoom()
    .scaleExtent([1, Infinity])
    .translateExtent([[0, 0], [width_0, height_0]])
    .extent([[0, 0], [width_0, height_0]])
    .on("zoom", zoomed_0);

function zoomed_0() {
    if (d3.event.sourceEvent && d3.event.sourceEvent.type === "brush"
    ) return; // ignore zoom-by-brush
    var t = d3.event.transform;
    x_0.domain(t.rescaleX(x2_0).domain());
    focus_0.select(".area").attr("d", area_0);
    focus_0.select(".line").attr("d", valueline_0);
    focus_0.select(".axis--x").call(xAxis_0);
    context_0.select(".brush").call(brush_0.move, x_0.range().map(t.invertX, t));
}
</code>```

I have multiple charts on page. From 1 to 5 - for this purpose I append  _{number}

答:
It looks like you did not apply clip-path style. If you switch off this style in blocks that you mentioned it will look like your screen, (see demo gif below):

Check that you append defs element and clipPath element as child for defs:

```<code>svg.append("defs").append("clipPath")
  .attr("id", "clip")
  .append("rect")
  .attr("width", width)
  .attr("height", height);
</code>```

Also, check that you have this style:

```<code>.line { // <== this class name should be on your line/area
  clip-path: url(#clip); // <== !!!
}
</code>```

Title: How to fix d3.js chart scaling

Body:
I would like to this.

But when I zoom it, the line is out of the area.

line definition:

var valueline_1 = d3.line()
  .x(function (d) { return x_1(parseDate(d.date)); })
  .y(function (d) { return y_1(d.count); });

var valueline2_1 = d3.line()
  .x(function (d) { return x2_1(parseDate(d.date)); })
  .y(function (d) { return y2_1(d.count); });

and then this code:

focus_1.append("path")
  .data([data])
  .attr("class", "line")
  .attr("d", valueline_1(i));

context_1.append("path")
  .data([data])
  .attr("class", "line")
  .attr("d", valueline2_1);

Can you help how to fix it?

thx.

EDIT:
This code for zoom:

var zoom_0 = d3.zoom()
    .scaleExtent([1, Infinity])
    .translateExtent([[0, 0], [width_0, height_0]])
    .extent([[0, 0], [width_0, height_0]])
    .on("zoom", zoomed_0);

function zoomed_0() {
    if (d3.event.sourceEvent && d3.event.sourceEvent.type === "brush"
    ) return; // ignore zoom-by-brush
    var t = d3.event.transform;
    x_0.domain(t.rescaleX(x2_0).domain());
    focus_0.select(".area").attr("d", area_0);
    focus_0.select(".line").attr("d", valueline_0);
    focus_0.select(".axis--x").call(xAxis_0);
    context_0.select(".brush").call(brush_0.move, x_0.range().map(t.invertX, t));
}

I have multiple charts on page. From 1 to 5 - for this purpose I append  _{number}

Body:
It looks like you did not apply clip-path style. If you switch off this style in blocks that you mentioned it will look like your screen, (see demo gif below):

Check that you append defs element and clipPath element as child for defs:

svg.append("defs").append("clipPath")
  .attr("id", "clip")
  .append("rect")
  .attr("width", width)
  .attr("height", height);

Also, check that you have this style:

.line { // <== this class name should be on your line/area
  clip-path: url(#clip); // <== !!!
}


问:
How to close an AsynchronousFileChannel
According to the API description of AsynchronousChannel which AsynchronousFileChannel implements.

Any outstanding asynchronous operations upon this channel will complete with the exception AsynchronousCloseException.

So from my understanding the right way to close it is that putting the invocation of close() in CompletionHandler which
passed to AsynchronousFileChannel.write, say if I'm going to write file through AsynchronousFileChannel. However how to
pass the channel to the handler really confuses me. Should I pass it as an attachment of the Handler? Can anyone offer me a sample code?

答:
Pass the channel object as an attachment</p>

```<code>    Path path = Paths.get("hello_world.txt");
    path.toFile().createNewFile();

    AsynchronousFileChannel channel = AsynchronousFileChannel.open(path, StandardOpenOption.WRITE);
    channel.write(ByteBuffer.wrap("hello".getBytes()), 0, channel, new CompletionHandler<Integer, Closeable>() {
        @Override
        public void completed(Integer result, Closeable closeMe) {
            System.out.println("Written: " + result);
            try {
                closeMe.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void failed(Throwable exc, Closeable closeMe) {
            System.err.println("Error occurred: " + exc);
            try {
                closeMe.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    });

    //wait for async task to complete
    Thread.sleep(5000L);
</code>```

Title: How to close an AsynchronousFileChannel

Body:
Pass the channel object as an attachment

    Path path = Paths.get("hello_world.txt");
    path.toFile().createNewFile();

    AsynchronousFileChannel channel = AsynchronousFileChannel.open(path, StandardOpenOption.WRITE);
    channel.write(ByteBuffer.wrap("hello".getBytes()), 0, channel, new CompletionHandler<Integer, Closeable>() {
        @Override
        public void completed(Integer result, Closeable closeMe) {
            System.out.println("Written: " + result);
            try {
                closeMe.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void failed(Throwable exc, Closeable closeMe) {
            System.err.println("Error occurred: " + exc);
            try {
                closeMe.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    });

    //wait for async task to complete
    Thread.sleep(5000L);


问:
Firebase console: How to specify click_action for notifications
I implemented Firebase and testing the Firebase notifications.
When the app is in the foreground I don't have problems, I implemented a service that extends FirebaseMessagingService and handle the message and data in onMessageReceived

I have problems when the app is in background, I would like to send a notification that opens a specific activity and does what I schedule to do, not just opening the App.

I did as described on the Firebase guide, but I'm not able to start the specific activity.

Here the manifest:

```<code><activity android:name=".BasicNotificationActivity">
            <intent-filter>
                <action android:name="OPEN_ACTIVITY_1" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>
</code>```

And here the Firebase Console. What do I have to write in those fields to open my "BasicNotificationActivity"?

答:
I have used handleIntent(Intent intent) method to handle intent and move to that particular screen.
Below is my code which is working perfectly even when the app is in background :

FCMMessagingService.java which extends FCMMessagingService

```<code>@Override
    public void handleIntent(Intent intent) {
        super.handleIntent(intent);

     Intent i = null;
     String value_action = "";

      if (intent.getExtras() != null) {
          if (key.equals("click_action")) {
                value_action = intent.getExtras().getString(key);
            }

          i = new Intent(FCMMessagingService.this, MainActivity.class);
          i.putExtra("notificationFlag", value_action);
          i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

      }
     PendingIntent pendingIntent = PendingIntent.getActivity(this, notifCount, i, PendingIntent.FLAG_ONE_SHOT);
        final int icon = R.mipmap.logo;
    Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this);

    Notification notification;
    notification = notificationBuilder.setSmallIcon(icon).setTicker(title)
            .setAutoCancel(true)
            .setContentTitle(title)
            .setContentText(body)
            .setSound(defaultSoundUri)
            .setContentIntent(pendingIntent)
            .setSmallIcon(R.mipmap.notification_icon)
            .setLargeIcon(BitmapFactory.decodeResource(getResources(), icon))
            .build();

    notificationBuilder.setContentTitle(title);
    notificationBuilder.setContentText(body);
    notificationBuilder.setAutoCancel(true);
    notificationBuilder.setSound(defaultSoundUri);
    notificationBuilder.setContentIntent(pendingIntent);
    notificationBuilder.setLargeIcon(BitmapFactory.decodeResource(getResources(), icon));
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        notificationBuilder.setSmallIcon(R.mipmap.logo);
    } else {
        notificationBuilder.setSmallIcon(R.mipmap.logo);
    }

    NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(notifCount, notification);

}
</code>```

Body:
I implemented Firebase and testing the Firebase notifications.
When the app is in the foreground I don't have problems, I implemented a service that extends FirebaseMessagingService and handle the message and data in onMessageReceived

I have problems when the app is in background, I would like to send a notification that opens a specific activity and does what I schedule to do, not just opening the App.

I did as described on the Firebase guide, but I'm not able to start the specific activity.

Here the manifest:

<activity android:name=".BasicNotificationActivity">
            <intent-filter>
                <action android:name="OPEN_ACTIVITY_1" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>

And here the Firebase Console. What do I have to write in those fields to open my "BasicNotificationActivity"?

Body:
I have used handleIntent(Intent intent) method to handle intent and move to that particular screen.
Below is my code which is working perfectly even when the app is in background :

FCMMessagingService.java which extends FCMMessagingService

@Override
    public void handleIntent(Intent intent) {
        super.handleIntent(intent);

     Intent i = null;
     String value_action = "";

      if (intent.getExtras() != null) {
          if (key.equals("click_action")) {
                value_action = intent.getExtras().getString(key);
            }

          i = new Intent(FCMMessagingService.this, MainActivity.class);
          i.putExtra("notificationFlag", value_action);
          i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

      }
     PendingIntent pendingIntent = PendingIntent.getActivity(this, notifCount, i, PendingIntent.FLAG_ONE_SHOT);
        final int icon = R.mipmap.logo;
    Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this);

    Notification notification;
    notification = notificationBuilder.setSmallIcon(icon).setTicker(title)
            .setAutoCancel(true)
            .setContentTitle(title)
            .setContentText(body)
            .setSound(defaultSoundUri)
            .setContentIntent(pendingIntent)
            .setSmallIcon(R.mipmap.notification_icon)
            .setLargeIcon(BitmapFactory.decodeResource(getResources(), icon))
            .build();

    notificationBuilder.setContentTitle(title);
    notificationBuilder.setContentText(body);
    notificationBuilder.setAutoCancel(true);
    notificationBuilder.setSound(defaultSoundUri);
    notificationBuilder.setContentIntent(pendingIntent);
    notificationBuilder.setLargeIcon(BitmapFactory.decodeResource(getResources(), icon));
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        notificationBuilder.setSmallIcon(R.mipmap.logo);
    } else {
        notificationBuilder.setSmallIcon(R.mipmap.logo);
    }

    NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(notifCount, notification);

}


问:
libtool library version numbering
currently I'm linking a successfully built library with the option

```<code>libtool --mode=link g++ -version-info 1:0
</code>```

which results in a library named

```<code>libxxx.so.1.0.0
</code>```

This is fine so far. My question: how can I influence the last digit in the version scheme, mean how can I have a different value than 0 at the end of the library name?

Thanks!

答:
how can I influence the last digit in the version scheme

You can influence it by specifying it:

```<code>-version-info 1:0:3
</code>```

Title: libtool library version numbering

Body:
currently I'm linking a successfully built library with the option

libtool --mode=link g++ -version-info 1:0

which results in a library named

libxxx.so.1.0.0

This is fine so far. My question: how can I influence the last digit in the version scheme, mean how can I have a different value than 0 at the end of the library name?

Thanks!

Body:
how can I influence the last digit in the version scheme

You can influence it by specifying it:

-version-info 1:0:3


问:
Angular Service and HttpClient Type does not exist
I am trying to get a service working in Angular 5. This is what I have:

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

@Injectable()
export class DataService {

  constructor() { }

  getData() {
    // don't use 'any', type your data instead!
    return this.httpClient.get<any>('./assets/data.json');
  }

}
</code>```

I'm getting the following error:

Property HttpClient does not exist on type DataService.

What am I missing?

答:
Http Calls have been modified and moved to '@angular/common/http' as HttpClient, since the idea was supported by many developers since its move to '@angular/common/http' from Angular 4.3 and further imports of Http Module from @angular/http is deprecated from Angular 5.Check out the changes here : https://jaxenter.com/road-to-angular-5-133253.html.

Now to your question, you should import HttpClient Module and create an instance of it.
So your code would be like:-

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

@Injectable()
export class DataService {

```<code>constructor(private _httpClient: HttpClient) { }

getData() {
    // don't use 'any', type your data instead!
    return this._httpClient.get<any>('./assets/data.json');
}
</code>```

}

Body:
I am trying to get a service working in Angular 5. This is what I have:

import { Injectable } from '@angular/core';

@Injectable()
export class DataService {

  constructor() { }

  getData() {
    // don't use 'any', type your data instead!
    return this.httpClient.get<any>('./assets/data.json');
  }

}

I'm getting the following error:

Property HttpClient does not exist on type DataService.

What am I missing?

Body:
Http Calls have been modified and moved to '@angular/common/http' as HttpClient, since the idea was supported by many developers since its move to '@angular/common/http' from Angular 4.3 and further imports of Http Module from @angular/http is deprecated from Angular 5.Check out the changes here : https://jaxenter.com/road-to-angular-5-133253.html.

Now to your question, you should import HttpClient Module and create an instance of it.
So your code would be like:-

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

@Injectable()
export class DataService {

constructor(private _httpClient: HttpClient) { }

getData() {
    // don't use 'any', type your data instead!
    return this._httpClient.get<any>('./assets/data.json');
}

}


问:
Visual Studio 2010 Express C# limitations
I am trying to develop the nerddinner mvc website, so I downloaded Visual Studio 2010 Express but I do not see an option for MVC or even asp.net website.  Can I download this for Visual Studio?</p>

答:
Visual Studio 2010 Express will let you work on WinForms, Libraries, Etc in C#, VB.NET, and even C++.

Visual Web Developer Express will let you work on ASP.NET web applications in both C# and VB.NET

However the Microsoft website calls them both "Visual Studio 2010 Express", they are differentiated by "Windows" and "Web"

Both are free

ContentLicense: CC BY-SA 2.5


问:
Unknown devices in Device Manager after migrating a VM to Azure
I recently migrated a Windows 2008 R2 VM that was running in Hyper-V on a Windows 2008 R2 host to Azure. Upon starting it up in the Azure virtual machine, Windows is showing three Unknown Devices in device manager.  The first has a value of ACPI\Hyper_V_Gen_Counter_V1 in the Hardware ID.  The other two simply show VMBUS(unique ID) in the Hardware ID value.

I'm wondering if these are the remnants of the Hyper-V Integration Services that were installed when the VM was running on Hyper-V locally?  And, if so, should they still be installed when the VM is running in Azure? Are there other integration components that should be installed for VM's running in Azure?

答:
The VMBUS device is explained by the following Microsoft article:

https://support.microsoft.com/en-gb/help/2925727/unknown-device-vmbus-in-device-manager-in-virtual-machine-for-avma


问:
fetch detail into the model view angularjs
```<code>$scope.orderDetails = [
        {
            "id":"115584",
            "user_id":"78937",
            "your_sys_global":null,
            "created_at":"2017-12-08 05:03:20"
        },
        {
            "id":"115585",
            "user_id":"78936",
            "your_sys_global":"MicSamse",
            "created_at":"2017-12-08 05:03:21"
        },
        {
            "id":"115586",
            "user_id":"78938",
            "your_sys_global":null,
            "created_at":"2017-12-08 05:03:52"
        }
    ];

<div ng-repeat="user in profiles track by $index">
    <input
    type="text"
    name="your_sys_global_{{user.user_id}}"
    ng-model="orderDetails[user.user_id].your_sys_global"
    ng-change="saveOrder(user, orderDetails[user.user_id])"
    >
</div>
</code>```

Details are not fetching into the textbox please guide why

答:
The problem is at orderDetails[user.user_id], your $scope.orderDetails is an array an you need index to update a value in that array.

And why are you using ng-change, ng-model will itself update your $scope.orderDetails if set properly.

Add following method in your $scope

```<code>$scope.getUserOrder = function(user) {
  return $scope.orderDetails.filter(function(order) {
    return order.user_id === user.user_id;
  })[0]
}
</code>```

and modify your markup to use this method

```<code><div ng-repeat="user in profiles track by $index">
    <input
    type="text"
    name="your_sys_global_{{user.user_id}}"
    ng-model="getUserOrder(user).your_sys_global"
    >
</div>
</code>```

There may be some typo mistakes, please don't mind.

Body:
$scope.orderDetails = [
        {
            "id":"115584",
            "user_id":"78937",
            "your_sys_global":null,
            "created_at":"2017-12-08 05:03:20"
        },
        {
            "id":"115585",
            "user_id":"78936",
            "your_sys_global":"MicSamse",
            "created_at":"2017-12-08 05:03:21"
        },
        {
            "id":"115586",
            "user_id":"78938",
            "your_sys_global":null,
            "created_at":"2017-12-08 05:03:52"
        }
    ];

    <input
    type="text"
    name="your_sys_global_{{user.user_id}}"
    ng-model="orderDetails[user.user_id].your_sys_global"
    ng-change="saveOrder(user, orderDetails[user.user_id])"
    >

Details are not fetching into the textbox please guide why

Body:
The problem is at orderDetails[user.user_id], your $scope.orderDetails is an array an you need index to update a value in that array.

And why are you using ng-change, ng-model will itself update your $scope.orderDetails if set properly.

Add following method in your $scope

$scope.getUserOrder = function(user) {
  return $scope.orderDetails.filter(function(order) {
    return order.user_id === user.user_id;
  })[0]
}

and modify your markup to use this method

<div ng-repeat="user in profiles track by $index">
    <input
    type="text"
    name="your_sys_global_{{user.user_id}}"
    ng-model="getUserOrder(user).your_sys_global"
    >
</div>

There may be some typo mistakes, please don't mind.


问:
How to validate 8 to 10 digit long phone number?
In my android application, phone number field used. 8 to 10 digit input value given by the user. How to validate  8 to 10 digit phone number using PHONE_REGEX?

I have already tried this method,

```<code>private static final String PHONE_REGEX = "\\d{8-10}";

  public static boolean isPhoneNumber(EditText editText, boolean required) {
    return isValid(editText, PHONE_REGEX, PHONE_MSG, required);
}
</code>```

答:
Use \\d{8,10} instead of \\d{8-10}

and trim() the text

```<code>private static final String PHONE_REGEX = "\\d{8,10}";

  public static boolean isPhoneNumber(EditText editText, boolean required) {
    return isValid(editText.getText().toString().trim(), PHONE_REGEX, PHONE_MSG, required);
}
</code>```

Body:
In my android application, phone number field used. 8 to 10 digit input value given by the user. How to validate  8 to 10 digit phone number using PHONE_REGEX?

I have already tried this method,

private static final String PHONE_REGEX = "\\d{8-10}";

  public static boolean isPhoneNumber(EditText editText, boolean required) {
    return isValid(editText, PHONE_REGEX, PHONE_MSG, required);
}

Body:
Use \\d{8,10} instead of \\d{8-10}

and trim() the text

private static final String PHONE_REGEX = "\\d{8,10}";

  public static boolean isPhoneNumber(EditText editText, boolean required) {
    return isValid(editText.getText().toString().trim(), PHONE_REGEX, PHONE_MSG, required);
}


问:
Webpack ts-loader : change tsconfig filename
I have 2 tsconfigs, one for my dev build and one for my prod build.

I choose the tsconfig with the -p flag :

tsc -p dev.tsconfig.json

Ts-loader is looking for a tsconfig.json file. How can I specify another filename with the ts-loader?

```<code>module.exports = {
    entry : __dirname + "/src/app/main.ts",
    output : {
        path : __dirname + "/dist",
        filename : "bundle.js"
    },
   resolve : {
     extensions : ["", ".webpack.js", ".web.js", ".js", ".ts"]
   },
   module: {
        loaders: [
            { test: /\.ts?$/, loader: "ts" }
        ]
    }
};
</code>```

答:
Here is how to specify configFile (formerly configFileName, as Frank notes), as of December 2017 (Webpack 3.10.0).

Webpack config

Note: Since version 2, Webpack has been using module.rules rather than module.loaders, and has deprecated use of query params in favour of an options object.

```<code>module.exports = {
    entry:  {
        "./build/bundle" : "./src/startup/Entry.ts"
    },
    output: {
        filename: '[name].js',
        libraryTarget: 'this'
    },
    devtool: 'source-map',
    resolve: {
        modules: [".", "node_modules"],
        extensions: [".js", ".webpack.js", ".web.js", ".d.ts", ".ts", ".tsx"]
    },
    module: {
        rules: [
            {
                test: /\.tsx?$/,
                exclude: [/node_modules/],
                loader: "ts-loader",
                options: {
                    configFile: "webpack_configs/tsconfig.webpack.json"
                }
            }
        ]
    },
    plugins: []
};
</code>```

Directory structure

The root of my directory structure looks like:

```<code>webpack.config.js
webpack_configs/tsconfig.webpack.json
tsconfig.json
package.json
src/*
test/*
node_modules/*
build/*
</code>```

... Where * indicates multiple files.

Typescript config

tsconfig.webpack.json itself just extends my generic tsconfig.json by excluding the test folder:

```<code>{
    "extends": "../tsconfig",
     "exclude": [
       "node_modules",
       "test"
     ]
}
</code>```

... But you needn't have two webpack configs to benefit from the configFile setting; you could simply use it to target your singular tsconfig.json from a custom location.

Body:
I have 2 tsconfigs, one for my dev build and one for my prod build.

I choose the tsconfig with the -p flag :

tsc -p dev.tsconfig.json

Ts-loader is looking for a tsconfig.json file. How can I specify another filename with the ts-loader?

module.exports = {
    entry : __dirname + "/src/app/main.ts",
    output : {
        path : __dirname + "/dist",
        filename : "bundle.js"
    },
   resolve : {
     extensions : ["", ".webpack.js", ".web.js", ".js", ".ts"]
   },
   module: {
        loaders: [
            { test: /\.ts?$/, loader: "ts" }
        ]
    }
};

Body:
Here is how to specify configFile (formerly configFileName, as Frank notes), as of December 2017 (Webpack 3.10.0).

Webpack config

Note: Since version 2, Webpack has been using module.rules rather than module.loaders, and has deprecated use of query params in favour of an options object.

module.exports = {
    entry:  {
        "./build/bundle" : "./src/startup/Entry.ts"
    },
    output: {
        filename: '[name].js',
        libraryTarget: 'this'
    },
    devtool: 'source-map',
    resolve: {
        modules: [".", "node_modules"],
        extensions: [".js", ".webpack.js", ".web.js", ".d.ts", ".ts", ".tsx"]
    },
    module: {
        rules: [
            {
                test: /\.tsx?$/,
                exclude: [/node_modules/],
                loader: "ts-loader",
                options: {
                    configFile: "webpack_configs/tsconfig.webpack.json"
                }
            }
        ]
    },
    plugins: []
};

Directory structure

The root of my directory structure looks like:

webpack.config.js
webpack_configs/tsconfig.webpack.json
tsconfig.json
package.json
src/*
test/*
node_modules/*
build/*

... Where * indicates multiple files.

Typescript config

tsconfig.webpack.json itself just extends my generic tsconfig.json by excluding the test folder:

{
    "extends": "../tsconfig",
     "exclude": [
       "node_modules",
       "test"
     ]
}

... But you needn't have two webpack configs to benefit from the configFile setting; you could simply use it to target your singular tsconfig.json from a custom location.


问:
How to change the size of a picture after inserting it into a word document
I'm adding a picture to a word document at a certain bookmark.  However, the picture is too big and is forcing text off the page, so I need to be able to change the size of the picture after it is in the word document.</p>

答:
Code, which I used to resize the picture successfully is:

```<code>var shape = headerRange.InlineShapes.AddPicture(tempLogoPathName, true, true).ConvertToShape();
shape.HeightRelative = 10f;
shape.WidthRelative = 40f;
</code>```

Seems that convering to Shape is the solution. Previous set the different height directly in InLineShapes, produced an error.
(I just edited a post and simplified the code, so it does not use 2nd dll library: Microsoft.Office.Core anymore)

Body:
Code, which I used to resize the picture successfully is:

var shape = headerRange.InlineShapes.AddPicture(tempLogoPathName, true, true).ConvertToShape();
shape.HeightRelative = 10f;
shape.WidthRelative = 40f;

Seems that convering to Shape is the solution. Previous set the different height directly in InLineShapes, produced an error.
(I just edited a post and simplified the code, so it does not use 2nd dll library: Microsoft.Office.Core anymore)


问:
Selecting First Tab - Laravel
i want to have my first tab selected when page loads or refreshes. In my code, the content of the first tab shows alright but the tab doesn't show it is selected although its content is showing.

Why is this happening please?

```<code><input type="hidden" name="currentTab" value="0"/>

<div class="row">
        <div class="col-md-9">

          <div  class="nav-tabs-custom"  id="tabs">

            <ul class="nav nav-tabs">
            @foreach($students as $student)

               <li ><a href="#tab_{{ $student->id }}" data-toggle="tab" >{!!$student->name!!}</a></li>
               @endforeach

            </ul>
            <div class="tab-content">
            @foreach($stduents as $key => $student)

            <div class="tab-pane" id="tab_{{ $student->id }}">
                 //content
             </div>
            @endforeach
              </div>

            </div>

          </div>

        </div>

<script>

$( document ).ready(function() {

    $("#tabs").tabs({active: document.tabTest.currentTab.value});

            $('#tabs a').click(function(e) {
                var curTab = $('.ui-tabs-active');
                curTabIndex = curTab.index();
                document.tabTest.currentTab.value = curTabIndex;
            });
})
</script>
</code>```

答:
Here is a jQuery solution for that:

```<code>$(document).ready(function(){
    $('.nav-tabs').find('li > a:first').click(); // **
})
</code>```

** This will activate the first tab when page loads or refreshes.

If you want to do a quick test, just select any other tab than 1st tab, and execute this line in your browser's console $('.nav-tabs').find('li > a:first').click();

Title: Selecting First Tab - Laravel

Body:
i want to have my first tab selected when page loads or refreshes. In my code, the content of the first tab shows alright but the tab doesn't show it is selected although its content is showing.

Why is this happening please?

<input type="hidden" name="currentTab" value="0"/>

            @foreach($students as $student)

id }}" data-toggle="tab" >{!!$student->name!!}

               @endforeach

            @foreach($stduents as $key => $student)

id }}">
                 //content

            @endforeach

Body:
Here is a jQuery solution for that:

$(document).ready(function(){
    $('.nav-tabs').find('li > a:first').click(); // **
})

** This will activate the first tab when page loads or refreshes.

If you want to do a quick test, just select any other tab than 1st tab, and execute this line in your browser's console $('.nav-tabs').find('li > a:first').click();


问:
setAnchorView not working with Recycler view
I am trying to build a music player.

I did everything what is required and the working is smooth but however i can't seem to see my MediaController Controls.

Declaration:private MusicController musicController;

```<code>public class MusicController extends MediaController {
    public MusicController(Context context) {
        super(context);
    }

    @Override
    public void hide() {

    }
}
</code>```

MainActivity.java

```<code>musicController.setMediaPlayer(this);
musicController.setAnchorView(findViewById(R.id.my_recycler_view));
musicController.setEnabled(true);
</code>```

mainactivity.xml

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:background="#FF330000"
    android:layout_height="match_parent"
    android:id="@+id/recycler_parent_view"
    >
    <android.support.v7.widget.RecyclerView
        android:id="@+id/my_recycler_view"
        android:scrollbars="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        />
</LinearLayout>
</code>```

I have added a screenshot.

What could be the problem here?

MainActivity.java

MusicService.java

MusicController.java

MyAdaptor.java

I have included every file that might be important. Please help me look out the problem. Thank You.

答:
I see musicController.show(0); being called only after some click events.
Should you call it also soon after having set the anchorView?

From documentation

void show (int timeout)

Show the controller on screen. It will go away automatically after 'timeout' milliseconds of inactivity.

Try just musicController.show();

EDIT

I saw you overrode the MusicController.hide() method so it shouldn't be removed after the timeout period, but still it seems to me you don't show it when you set the anchorView

UPDATE

```<code>musicController.setMediaPlayer(this);
musicController.setAnchorView(findViewById(R.id.my_recycler_view));
musicController.setEnabled(true);
new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            musicController.show();
        }
    }, 5000);
</code>```

I ran your code and I was able to show the controller after applying a delay. Maybe you should show it after your service is connected...not sure about this, but at least you could try this code and then improve it.

Body:
I am trying to build a music player.

I did everything what is required and the working is smooth but however i can't seem to see my MediaController Controls.

Declaration:private MusicController musicController;

public class MusicController extends MediaController {
    public MusicController(Context context) {
        super(context);
    }

    @Override
    public void hide() {

    }
}

MainActivity.java

musicController.setMediaPlayer(this);
musicController.setAnchorView(findViewById(R.id.my_recycler_view));
musicController.setEnabled(true);

mainactivity.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:background="#FF330000"
    android:layout_height="match_parent"
    android:id="@+id/recycler_parent_view"
    >
    <android.support.v7.widget.RecyclerView
        android:id="@+id/my_recycler_view"
        android:scrollbars="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        />
</LinearLayout>

I have added a screenshot.

What could be the problem here?

MainActivity.java

MusicService.java

MusicController.java

MyAdaptor.java

I have included every file that might be important. Please help me look out the problem. Thank You.

Body:
I see musicController.show(0); being called only after some click events.
Should you call it also soon after having set the anchorView?

From documentation

void show (int timeout)

Show the controller on screen. It will go away automatically after 'timeout' milliseconds of inactivity.

Try just musicController.show();

EDIT

I saw you overrode the MusicController.hide() method so it shouldn't be removed after the timeout period, but still it seems to me you don't show it when you set the anchorView

UPDATE

musicController.setMediaPlayer(this);
musicController.setAnchorView(findViewById(R.id.my_recycler_view));
musicController.setEnabled(true);
new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            musicController.show();
        }
    }, 5000);

I ran your code and I was able to show the controller after applying a delay. Maybe you should show it after your service is connected...not sure about this, but at least you could try this code and then improve it.


问:
Your CPU does not support VT-x
I have created AVD, but when I try to run android program, it is showing an
error

Your CPU does not support VT-x

I enabled virtualization technology in BIOS, but still this error comes up when I try to run my android program.

答:
According to Android Documentation, to run an emulator the development system's CPU should support one of the following virtualization extensions technologies:

Intel Virtualization Technology (VT, VT-x, vmx)

AMD Virtualization (AMD-V, SVM) -- only supported for Linux

Your CPU is Intel® Core™2 Duo Processor E7300, which according to the manufacturer does not support Intel Virtualization Technology (VT-x). That's the reason for this error.

The workaround is to use an alternative Android Emulator, e.g. Genymotion, as already suggested.

Title: Your CPU does not support VT-x


问:
vex confirm dialog, cancel-action as default
I'm trying to use https://github.com/HubSpot/vex modal script for a confirm-dialog. At the moment, if the confirm dialog box appeares, the "ok"-button is selected as default. Do anybody know how i can change this? I'd like the the cancel-button is for default so that anybody hit just enter, nothing happens.

thanks for your answer.

best regards
thomas

答:
To modify this as default behaviour, change the order of the buttons and class name in the vex JavaScript file. (vex.combined.js)

This will make the 'Cancel' button the default button.

```<code>dialog.buttons = {
        NO: {
          text: 'Cancel',
          type: 'button',
          className: 'vex-dialog-button-primary',
          click: function noClick () {
            this.value = false
            this.close()
          }
        },
        YES: {
          text: 'OK',
          type: 'submit',
          className: 'vex-dialog-button-secondary',
          click: function yesClick () {
            this.value = true
          }
        }
}

dialog.defaultOptions = {
    ..
    buttons: [
      dialog.buttons.NO,
      dialog.buttons.YES
    ],
    ..
  }
</code>```

Body:
To modify this as default behaviour, change the order of the buttons and class name in the vex JavaScript file. (vex.combined.js)

This will make the 'Cancel' button the default button.

dialog.buttons = {
        NO: {
          text: 'Cancel',
          type: 'button',
          className: 'vex-dialog-button-primary',
          click: function noClick () {
            this.value = false
            this.close()
          }
        },
        YES: {
          text: 'OK',
          type: 'submit',
          className: 'vex-dialog-button-secondary',
          click: function yesClick () {
            this.value = true
          }
        }
}

dialog.defaultOptions = {
    ..
    buttons: [
      dialog.buttons.NO,
      dialog.buttons.YES
    ],
    ..
  }


问:
dictionary<int, guid> how to take value field that is Guid?
I was struggling a lot to get a Guid Value from Dictionary. Somebody please help me out.It is showing System.FormatException.Thank you advance.

My code:

```<code>Dictionary<int, Guid> products = productRepository.QueryNoTracking()
    .Select(x => new { x.ID, x.ProductKey })
    .ToDictionary(x => x.ProductKey, x => x.ID);
</code>```

From this I need to take productID from Position group Entity:-

```<code>var positionGroup = new Entities.PositionGroup();

positionGroup.ProductID = (Guid?)products
   .Where(s => s.Key == productKey)
   .Select(s => s.Value).ToString();
</code>```

答:
Don't use a LINQ query to find the key/value in a dictionary:</p>

```<code>Guid productID;
bool knownProductKey = products.TryGetValue(productKey, out productID);
if(knownProductKey)
    positionGroup.ProductID = productID;
else
    positionGroup.ProductID = new Nullable<Guid>();
</code>```

Body:
I was struggling a lot to get a Guid Value from Dictionary. Somebody please help me out.It is showing System.FormatException.Thank you advance.

My code:

Dictionary<int, Guid> products = productRepository.QueryNoTracking()
    .Select(x => new { x.ID, x.ProductKey })
    .ToDictionary(x => x.ProductKey, x => x.ID);

From this I need to take productID from Position group Entity:-

var positionGroup = new Entities.PositionGroup();

positionGroup.ProductID = (Guid?)products
   .Where(s => s.Key == productKey)
   .Select(s => s.Value).ToString();

Body:
Don't use a LINQ query to find the key/value in a dictionary:

Guid productID;
bool knownProductKey = products.TryGetValue(productKey, out productID);
if(knownProductKey)
    positionGroup.ProductID = productID;
else
    positionGroup.ProductID = new Nullable<Guid>();


问:
Apache2 Configuration: Execute if mod is enabled?
Is there a possibility to execute a part of a configuration file in Apache 2.4 only if a specific mod (e.g. mod_wsgi) is enabled?</p>

答:
Apache provides IfModule for this, see the docs.

Use it like this:

```<code><IfModule ssl_module>
    Include conf/extra/httpd-ssl.conf
    SSLRandomSeed startup builtin
    SSLRandomSeed connect builtin
</IfModule>
</code>```

Body:
Apache provides IfModule for this, see the docs.

Use it like this:

<IfModule ssl_module>
    Include conf/extra/httpd-ssl.conf
    SSLRandomSeed startup builtin
    SSLRandomSeed connect builtin
</IfModule>


问:
Can not give 100% height to transformed image?
I am unable to apply the height of a transformed element to it's parent.
I have a bootstrap modal in which I am rendering an image that may be very large in size or may be small the size of the image is dynamic. So what I want is that whatever the size of image is the modal's size should also be same as the transformed Image.

I tried giving it a max-height: 100% but it does not works.
If I give it max-height in px then modal height will always cut if the height of my image is greater than my max-height so suggest me what to do.

Following is JSFiddle which is demonstrating my problem.

https://jsfiddle.net/harish_soni/6r9p07sg/

When you will open the modal the height of the modal is very large and the image inside it it much smaller after tranformation.

Any help would be appreciated.

HTML::

  Bootstrap Example

```<code><body>

<div class="container">
  <h2>Modal Example</h2>
  <!-- Trigger the modal with a button -->
  <button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal</button>

  <!-- Modal -->
  <div class="modal fade" id="myModal" role="dialog">
    <div class="modal-dialog">

      <!-- Modal content-->
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal">×</button>
          <h4 class="modal-title">Modal Header</h4>
        </div>
        <div class="modal-body">
          <img class="modal-image" src="http://canacopegdl.com/images/example/example-1.jpg" />
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        </div>
      </div>

    </div>
  </div>

</div>

</body>
</code>```

CSS:

```<code>.modal-image{
    transform: scale(0.3) translateX(-50%);
    transform-origin: left top;
    position: relative;
    left: 50%;
}
</code>```

答:
If I understand your requirements correctly, you can achieve this without any extra CSS, just using Bootstrap's helper classes: change the img class to class="modal-image img-responsive center-block".

Updated JSfiddle with a 100px image: https://jsfiddle.net/y2b96spb/1/

and a 3000px image: https://jsfiddle.net/e52uafd4/

Body:
I am unable to apply the height of a transformed element to it's parent.
I have a bootstrap modal in which I am rendering an image that may be very large in size or may be small the size of the image is dynamic. So what I want is that whatever the size of image is the modal's size should also be same as the transformed Image.

I tried giving it a max-height: 100% but it does not works.
If I give it max-height in px then modal height will always cut if the height of my image is greater than my max-height so suggest me what to do.

Following is JSFiddle which is demonstrating my problem.

https://jsfiddle.net/harish_soni/6r9p07sg/

When you will open the modal the height of the modal is very large and the image inside it it much smaller after tranformation.

Any help would be appreciated.

HTML::

  Bootstrap Example

Modal Example

  <button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal</button>

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

Modal Header

          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

CSS:

.modal-image{
    transform: scale(0.3) translateX(-50%);
    transform-origin: left top;
    position: relative;
    left: 50%;
}


问:
GTFS application (python)
I need to make a command line application which has two parameters:

the location of the input file, and
the location of the output file.
The input file is a GTFS (.txt) file.

The output file is a .shp file.

How should I do this?

答:
To get command line parameters:

```<code>% python3 your_script.py parameter1 parameter2
</code>```

Where parameter1 and parameter2 are you input file and output file names:

```<code>import sys
parameters = sys.argv
#parameters now contains 3 strings:
#"your_script.py" in parameters[0]
#"parameter1" in parameters [1]
#"parameter2" in parameters [2]
</code>```

So you can use the command line arguments as variables. To open the files:

```<code>in_file = open(parameters[1] + ".txt") #from your problem statement, it sounds
             #like your filenames don't include extensions. If they do, remove
             #the (+ ".txt") part

out_file = open(parameters[2] + ".shp", 'w')
</code>```

For more information about I/O operations in Python, see this link

Title: GTFS application (python)

Body:
To get command line parameters:

% python3 your_script.py parameter1 parameter2

Where parameter1 and parameter2 are you input file and output file names:

import sys
parameters = sys.argv
#parameters now contains 3 strings:
#"your_script.py" in parameters[0]
#"parameter1" in parameters [1]
#"parameter2" in parameters [2]

So you can use the command line arguments as variables. To open the files:

in_file = open(parameters[1] + ".txt") #from your problem statement, it sounds
             #like your filenames don't include extensions. If they do, remove
             #the (+ ".txt") part

out_file = open(parameters[2] + ".shp", 'w')

For more information about I/O operations in Python, see this link


问:
Groovy JsonBuilder, array inside an array
I need to build the following json using groovy's JsonBuilder().

```<code>[
  {
    "date": "2017-12-08",
    "dog": [
        {
            "name": "Joe",
            "age": "1"
        },
        {
            "name": "Bro",
            "age": "2"
        },
        {
            "name": "Doe",
            "age": "3"
        }
    ]
}
]
</code>```

I cant get the array in the array, because of the date, it wants to always to put date not in the same level as dog array, but put it in { }, like:

```<code>[{
    {
    "date": "2017-12-08",
    },
    "dog": [
        {
            "name": "Joe",
            "age": "1"
        },
        {
            "name": "Bro",
            "age": "2"
        },
        {
            "name": "Doe",
            "age": "3"
        }
    ]
}
]
</code>```

答:
Just stick the date alongside your list in the model:

```<code>import groovy.json.JsonBuilder
import groovy.transform.Canonical

@Canonical
class Dog {
    int age
    String name
}

@Canonical
class DogList {
    String date
    List<Dog> dog
}

def ark = [
    new DogList('2017-12-08', [
        new Dog(1, 'Joe'),
        new Dog(2, 'Bro'),
        new Dog(3, 'Doe')
    ])
]

def json = new JsonBuilder(ark).toPrettyString()
println json
</code>```

prints:

```<code>[
    {
        "date": "2017-12-08",
        "dog": [
            {
                "age": 1,
                "name": "Joe"
            },
            {
                "age": 2,
                "name": "Bro"
            },
            {
                "age": 3,
                "name": "Doe"
            }
        ]
    }
]
</code>```

Body:
I need to build the following json using groovy's JsonBuilder().

[
  {
    "date": "2017-12-08",
    "dog": [
        {
            "name": "Joe",
            "age": "1"
        },
        {
            "name": "Bro",
            "age": "2"
        },
        {
            "name": "Doe",
            "age": "3"
        }
    ]
}
]

I cant get the array in the array, because of the date, it wants to always to put date not in the same level as dog array, but put it in { }, like:

[{
    {
    "date": "2017-12-08",
    },
    "dog": [
        {
            "name": "Joe",
            "age": "1"
        },
        {
            "name": "Bro",
            "age": "2"
        },
        {
            "name": "Doe",
            "age": "3"
        }
    ]
}
]

Body:
Just stick the date alongside your list in the model:

import groovy.json.JsonBuilder
import groovy.transform.Canonical

@Canonical
class Dog {
    int age
    String name
}

@Canonical
class DogList {
    String date
    List<Dog> dog
}

def ark = [
    new DogList('2017-12-08', [
        new Dog(1, 'Joe'),
        new Dog(2, 'Bro'),
        new Dog(3, 'Doe')
    ])
]

def json = new JsonBuilder(ark).toPrettyString()
println json

prints:

[
    {
        "date": "2017-12-08",
        "dog": [
            {
                "age": 1,
                "name": "Joe"
            },
            {
                "age": 2,
                "name": "Bro"
            },
            {
                "age": 3,
                "name": "Doe"
            }
        ]
    }
]


问:
How to change devise views model in an existing app
So, I have actually generated the views for devise but recently i want to change it back to another name, how will i?

Initially it was rails g devise 'Writer'...
now, i want rails g devise 'User'

Thanks.

答:
Destroy and then generate the model.

First:

```<code> rails destroy devise Writer
</code>```

then:

```<code>rails generate devise User
</code>```

It would be more easier and recommended then changing.

Body:
Destroy and then generate the model.

First:

 rails destroy devise Writer

then:

rails generate devise User

It would be more easier and recommended then changing.


问:
iOS navigation bar item image size
I want to customize my NavigationBar button and using my own images.

The question is what the size should be?

I found that the button size should be 40*40, so the image should be 80*80 for retina?

答:
Apple updated their Human Interface Guidelines Docs. Now the recommended sizes for creating custom icons for Navigation Bar and Toolbar

@2x - 48px × 48px (24pt × 24pt @2x)

@3x - 72px × 72px (24pt × 24pt @3x)

ContentLicense: CC BY-SA 4.0

Title: iOS navigation bar item image size


问:
Python error: global variable in class undefined
I have a class with two variables set to some default value. I have defined a function where I declare these variables as global inside my function.  I get this error which says the variable is not defined. One variable is counter, which will increment on each function call and other variable has to append message on each call. After appending multiple messages and counter value reaches some threshold I want to insert all these messages into MySQL database.
But the variable is not appending the values. It shows the variable is undefined.</p>

```<code>class Message():
     insertStatement= ''
     insertCounter = 0

    def Save(self, msg)
        global insertCounter
        global insertStatement

        if  msg.topic.startswith("topic1/"):
            insertStatement += "INSERT INTO mydatabase.table VALUES (" + msg.payload.decode("utf-8") + "," + datetime + ");"
       elif msg.topic.startswith("topic2/"):
            insertStatement += "INSERT INTO mydatabase.table1 VALUES (" + msg.payload.decode("utf-8") + "," + datetime + ");"
       elif msg.topic.startswith("topic3/")
            insertStatement += "INSERT INTO mydatabase.table2 VALUES (" +msg.payload.decode("utf-8") + "," + datetime + ");"
       elif msg.topic.startswith("messages"):
            insertStatement += "INSERT INTO mydatabase.table3 VALUES ('" + msg.topic + "',"  + msg.payload.decode("utf-8") + "," + datetime + ");"
       else:
            return
       insertcounter +=1
       if(insertCounter > 1000):
         for result in cursor.execute(insertStatement, multi=True):
             print result.row_count  # i changed it to result
</code>```

答:
There are couple of typos in your code, please update that and check.

You have declared  a global variable insertCounter and incrementing variable insertcounter. Update it to self.insertCounter+1

Update your result variable, it suppose to be result, not reslut

Body:
I have a class with two variables set to some default value. I have defined a function where I declare these variables as global inside my function.  I get this error which says the variable is not defined. One variable is counter, which will increment on each function call and other variable has to append message on each call. After appending multiple messages and counter value reaches some threshold I want to insert all these messages into MySQL database.
But the variable is not appending the values. It shows the variable is undefined.

class Message():
     insertStatement= ''
     insertCounter = 0

    def Save(self, msg)
        global insertCounter
        global insertStatement

        if  msg.topic.startswith("topic1/"):
            insertStatement += "INSERT INTO mydatabase.table VALUES (" + msg.payload.decode("utf-8") + "," + datetime + ");"
       elif msg.topic.startswith("topic2/"):
            insertStatement += "INSERT INTO mydatabase.table1 VALUES (" + msg.payload.decode("utf-8") + "," + datetime + ");"
       elif msg.topic.startswith("topic3/")
            insertStatement += "INSERT INTO mydatabase.table2 VALUES (" +msg.payload.decode("utf-8") + "," + datetime + ");"
       elif msg.topic.startswith("messages"):
            insertStatement += "INSERT INTO mydatabase.table3 VALUES ('" + msg.topic + "',"  + msg.payload.decode("utf-8") + "," + datetime + ");"
       else:
            return
       insertcounter +=1
       if(insertCounter > 1000):
         for result in cursor.execute(insertStatement, multi=True):
             print result.row_count  # i changed it to result


问:
[Obj-C]How do i do an IBAlert after using NSTask?
i use NSTask, works 100% but after running it (when running it, i also use an MBProcessHUD) i want to do an IBAlert with somethings in it...

here is my code

```<code>-(void) runScript {
    task = [[NSTask alloc] init];
    [task setLaunchPath:@"/bin/bash"];
    NSString *script;
    script = [[[NSBundle mainBundle] bundlePath] stringByAppendingString:@"a2cy.sh"];
    NSArray *arguments = [NSArray arrayWithObjects:script, [sourcerepo text], nil];
    [task setArguments: arguments];
    [task launch];
    sleep(1);
    HUD.customView = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"checkmark.png"]] autorelease];
    HUD.mode = MBProgressHUDModeCustomView;
    HUD.labelText = @"Complete!";
    NSString *loggy;
    loggy = [NSString stringWithContentsOfFile:[[[NSBundle mainBundle] bundlePath] stringByAppendingString:@"/log.txt"]];
    UIAlertView *log = [[UIAlertView alloc] initWithTitle:@"Result" message:loggy delegate:self cancelButtonTitle:@"Ok!" otherButtonTitles:nil];
    [loggy show];
    [loggy release];
}
</code>```

but after running, it doesn't show up :/ any help? thanks

答: I didn't take too close a look at it, but you're sending show to the NSString loggy rather than the UIAlert log.

Body:
i use NSTask, works 100% but after running it (when running it, i also use an MBProcessHUD) i want to do an IBAlert with somethings in it...

here is my code

-(void) runScript {
    task = [[NSTask alloc] init];
    [task setLaunchPath:@"/bin/bash"];
    NSString *script;
    script = [[[NSBundle mainBundle] bundlePath] stringByAppendingString:@"a2cy.sh"];
    NSArray *arguments = [NSArray arrayWithObjects:script, [sourcerepo text], nil];
    [task setArguments: arguments];
    [task launch];
    sleep(1);
    HUD.customView = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"checkmark.png"]] autorelease];
    HUD.mode = MBProgressHUDModeCustomView;
    HUD.labelText = @"Complete!";
    NSString *loggy;
    loggy = [NSString stringWithContentsOfFile:[[[NSBundle mainBundle] bundlePath] stringByAppendingString:@"/log.txt"]];
    UIAlertView *log = [[UIAlertView alloc] initWithTitle:@"Result" message:loggy delegate:self cancelButtonTitle:@"Ok!" otherButtonTitles:nil];
    [loggy show];
    [loggy release];
}

but after running, it doesn't show up :/ any help? thanks


问:
For Stream.generate(foo).parallel(), does foo have to be thread safe?
I'm working with Java 8 Streams. I have a custom function, foo(), that yields an object, and I would like to parallel stream the objects it creates. I know foo() is not thread safe.

If I write Stream.generate(foo).parallel(), will foo() be called in an asynchronous manner? I.e. will objects be generated serially, and passed to parallel threads, or will multiple threads each generate objects as needed by calling foo()?

答:
While data races are not a guaranteed behavior, the following code

```<code>System.out.println(
    Stream.generate(new Supplier<Integer>() {
        int i; @Override public Integer get() { return i++; }
    }).parallel()
      .limit(10_000)
      .collect(BitSet::new, BitSet::set, BitSet::or)
      .cardinality()
);
</code>```

reproducibly prints numbers less than 10,000 in my environment, demonstrating that missing updates may indeed happen when the supplier is not thread safe.

Note that it is also possible that the supplier gets queried for more elements than needed for the result evaluation. E.g.

```<code>LongAdder adder = new LongAdder();
System.out.println(
    Stream.generate(new Supplier<Integer>() {
        int i; @Override public Integer get() { adder.increment(); return i++; }
    }).parallel()
      .limit(10_000)
      .collect(BitSet::new, BitSet::set, BitSet::or)
      .cardinality()
);
System.out.println("queried "+adder+" times");
</code>```

usually reports a number of queries greater than 10,000, while at the same time, the result reports less than 10,000 distinct elements due to the data race.

Making the supplier thread safe, changes the result to the correct number of 10,000 distinct elements, but the supplier may still got queried more than 10,000 times, hence, the result is not guaranteed to contain exactly the numbers from 0 to 9,999, as the stream created via generate is unordered, so any 10,000 distinct numbers from the supplier may be used.

Body:
While data races are not a guaranteed behavior, the following code

System.out.println(
    Stream.generate(new Supplier<Integer>() {
        int i; @Override public Integer get() { return i++; }
    }).parallel()
      .limit(10_000)
      .collect(BitSet::new, BitSet::set, BitSet::or)
      .cardinality()
);

reproducibly prints numbers less than 10,000 in my environment, demonstrating that missing updates may indeed happen when the supplier is not thread safe.

Note that it is also possible that the supplier gets queried for more elements than needed for the result evaluation. E.g.

LongAdder adder = new LongAdder();
System.out.println(
    Stream.generate(new Supplier<Integer>() {
        int i; @Override public Integer get() { adder.increment(); return i++; }
    }).parallel()
      .limit(10_000)
      .collect(BitSet::new, BitSet::set, BitSet::or)
      .cardinality()
);
System.out.println("queried "+adder+" times");

usually reports a number of queries greater than 10,000, while at the same time, the result reports less than 10,000 distinct elements due to the data race.

Making the supplier thread safe, changes the result to the correct number of 10,000 distinct elements, but the supplier may still got queried more than 10,000 times, hence, the result is not guaranteed to contain exactly the numbers from 0 to 9,999, as the stream created via generate is unordered, so any 10,000 distinct numbers from the supplier may be used.


问:
asp.net proper async locking per cache key
I am reading about great AsyncLock library, but I have some questions.

Example from link has following line of the code:

```<code>private readonly AsyncLock _mutex = new AsyncLock();
public async Task DoStuffAsync()
{
  using (await _mutex.LockAsync())
  {
    await Task.Delay(TimeSpan.FromSeconds(1));
  }
}
</code>```

I tried to reuse this code in my ASP.NET controller, but I have some doubts.

Scenario mentioned above covers bacic locking where cache key is always the same, but how about if I have dynamic cache, such as in example below, and I would not want ArticleId1 locks user loading ArticleId2.
Should each cache key has it's own AsyncLock _mutex?

Also, have I done right to convert mutex to static, due to fact that multiple users will share the lock?

```<code>private static readonly AsyncLock _mutexIndex = new AsyncLock();
public async Task<IActionResult> Index(int articleId)
{

    var key = CacheKeysFor.Article.ById(articleId);
    ArticleModel cacheEntry;
    cacheEntry = _cache.Get<ArticleModel>(key);

    if (cacheEntry == null)
    {
        using (await _mutexIndex.LockAsync())
        {
            if (cacheEntry == null)
            {
                cacheEntry = SomeDatabaseCall
                _cache.Set(key, cacheEntry, TimeSpan.FromSeconds(60));
            }

        }
    }

    return View(cacheEntry);
}
</code>```

答:
If you are going this route - yes, you need separate lock for each key. You can achieve that for example with ConcurrentDictionary:

```<code>static ConcurrentDictionary<string, Lazy<AsyncLock>> _keyLocks = new ConcurrentDictionary<string, Lazy<AsyncLock>>();

public async Task<IActionResult> Index(int articleId)
{
    var key = CacheKeysFor.Article.ById(articleId);
    ArticleModel cacheEntry;
    cacheEntry = _cache.Get<ArticleModel>(key);

    if (cacheEntry == null)
    {
        var keyLock = _keyLocks.GetOrAdd(key, _ => new Lazy<AsyncLock>(() => new AsyncLock())).Value;
        using (await keyLock.LockAsync())
        {
            if (cacheEntry == null)
            {
                cacheEntry = SomeDatabaseCall
                _cache.Set(key, cacheEntry, TimeSpan.FromSeconds(60));
            }

        }
    }

    return View(cacheEntry);
}
</code>```

Note that keys locks will accumulate over time. That is not a big problem unless you have many millions of them. If you do have millions of them - you can clear locks collection from time to time. Doing that is not safe and might allow multiple threads to enter protected block, but in this concrete case it seems to be not a problem either (because you use locks to just avoid expensive database call).

Body:
I am reading about great AsyncLock library, but I have some questions.

Example from link has following line of the code:

private readonly AsyncLock _mutex = new AsyncLock();
public async Task DoStuffAsync()
{
  using (await _mutex.LockAsync())
  {
    await Task.Delay(TimeSpan.FromSeconds(1));
  }
}

I tried to reuse this code in my ASP.NET controller, but I have some doubts.

Scenario mentioned above covers bacic locking where cache key is always the same, but how about if I have dynamic cache, such as in example below, and I would not want ArticleId1 locks user loading ArticleId2.
Should each cache key has it's own AsyncLock _mutex?

Also, have I done right to convert mutex to static, due to fact that multiple users will share the lock?

private static readonly AsyncLock _mutexIndex = new AsyncLock();
public async Task<IActionResult> Index(int articleId)
{

    var key = CacheKeysFor.Article.ById(articleId);
    ArticleModel cacheEntry;
    cacheEntry = _cache.Get<ArticleModel>(key);

    if (cacheEntry == null)
    {
        using (await _mutexIndex.LockAsync())
        {
            if (cacheEntry == null)
            {
                cacheEntry = SomeDatabaseCall
                _cache.Set(key, cacheEntry, TimeSpan.FromSeconds(60));
            }

        }
    }

    return View(cacheEntry);
}

Body:
If you are going this route - yes, you need separate lock for each key. You can achieve that for example with ConcurrentDictionary:

static ConcurrentDictionary<string, Lazy<AsyncLock>> _keyLocks = new ConcurrentDictionary<string, Lazy<AsyncLock>>();

public async Task<IActionResult> Index(int articleId)
{
    var key = CacheKeysFor.Article.ById(articleId);
    ArticleModel cacheEntry;
    cacheEntry = _cache.Get<ArticleModel>(key);

    if (cacheEntry == null)
    {
        var keyLock = _keyLocks.GetOrAdd(key, _ => new Lazy<AsyncLock>(() => new AsyncLock())).Value;
        using (await keyLock.LockAsync())
        {
            if (cacheEntry == null)
            {
                cacheEntry = SomeDatabaseCall
                _cache.Set(key, cacheEntry, TimeSpan.FromSeconds(60));
            }

        }
    }

    return View(cacheEntry);
}

Note that keys locks will accumulate over time. That is not a big problem unless you have many millions of them. If you do have millions of them - you can clear locks collection from time to time. Doing that is not safe and might allow multiple threads to enter protected block, but in this concrete case it seems to be not a problem either (because you use locks to just avoid expensive database call).


问:
What is optimal response size for chunked transfer in ASP.NET?
I am creating a reverse proxy and I am trying to find the optimal buffer for a response size for a chunked transfer-encoding.  Currently I have it set at 4 kb.  Is this number OK, or is there a better size that I should be using.  I would like this backed up with some tests if at all possible.

I would also accept a property setting somebody knows about in the .NET framework that has a default value.

答:
The optimal size is going to be rather application and network specific. There was a previous post that offered suggestions on measuring the best chunk size given the environment.

J2ME used to default to 2KB chunks (that's client-to-server). But I have no idea what .NET defaults to. Unfortunately the HTTP Spec on chunking offers no guidance either.

OwnerDisplayName: Nick Berardi

OwnerDisplayName: David Thomas Garcia


问:
Celery "Received unregistered task of type"
I have read quite a few posts that are similar to this but none seem to make sense to me.

I am trying to configure a Celery PeriodicTask to fire every 5 seconds but I'm getting hung up on a Celery configuration issue (I think)

comm/tasks.py

```<code>import datetime
from celery.decorators import periodic_task

@periodic_task
def send_queued_messages():
    # do something...
</code>```

myapp/settings.py

```<code>...
from comm.tasks import send_queued_messages
from datetime import timedelta
CELERYBEAT_SCHEDULE = {
    'send_queued_messages_every_5_seconds': {
        'task': 'comm.tasks.send_queued_messages',   # Is the issue here?  I've tried a dozen variations!!
        'schedule': timedelta(seconds=5),
        },
    }
</code>```

The relevant output from my error logs:

```<code>23:41:00 worker.1 | [2015-06-10 03:41:00,657: ERROR/MainProcess] Received unregistered task of type 'send_queued_messages'.
23:41:00 worker.1 | The message has been ignored and discarded.
23:41:00 worker.1 |
23:41:00 worker.1 | Did you remember to import the module containing this task?
23:41:00 worker.1 | Or maybe you are using relative imports?
23:41:00 worker.1 | Please see http://bit.ly/gLye1c for more information.
23:41:00 worker.1 |
23:41:00 worker.1 | The full contents of the message body was:
23:41:00 worker.1 | {'utc': True, 'chord': None, 'args': [], 'retries': 0, 'expires': None, 'task': 'send_queued_messages', 'callbacks': None, 'errbacks': None, 'timelimit': (None, None), 'taskset': None, 'kwargs': {}, 'eta': None, 'id': 'a8ca18...227a56'} (216b)
</code>```

答:
Celery-beat was throwing me the same issue and nothing what was wrote above didn't help me.

I tried to insert this snippet into my settings file:

CELERY_IMPORTS = ['myapp.tasks']

although I didn't need it. But it helped me because new error log was appeared. In my tasks file I had an import of non-existing apps.

This can be caused by very confusion reasons... A lot of time there is a syntax error or something like this.

Body:
I have read quite a few posts that are similar to this but none seem to make sense to me.

I am trying to configure a Celery PeriodicTask to fire every 5 seconds but I'm getting hung up on a Celery configuration issue (I think)

comm/tasks.py

import datetime
from celery.decorators import periodic_task

@periodic_task
def send_queued_messages():
    # do something...

myapp/settings.py

...
from comm.tasks import send_queued_messages
from datetime import timedelta
CELERYBEAT_SCHEDULE = {
    'send_queued_messages_every_5_seconds': {
        'task': 'comm.tasks.send_queued_messages',   # Is the issue here?  I've tried a dozen variations!!
        'schedule': timedelta(seconds=5),
        },
    }

The relevant output from my error logs:

23:41:00 worker.1 | [2015-06-10 03:41:00,657: ERROR/MainProcess] Received unregistered task of type 'send_queued_messages'.
23:41:00 worker.1 | The message has been ignored and discarded.
23:41:00 worker.1 |
23:41:00 worker.1 | Did you remember to import the module containing this task?
23:41:00 worker.1 | Or maybe you are using relative imports?
23:41:00 worker.1 | Please see http://bit.ly/gLye1c for more information.
23:41:00 worker.1 |
23:41:00 worker.1 | The full contents of the message body was:
23:41:00 worker.1 | {'utc': True, 'chord': None, 'args': [], 'retries': 0, 'expires': None, 'task': 'send_queued_messages', 'callbacks': None, 'errbacks': None, 'timelimit': (None, None), 'taskset': None, 'kwargs': {}, 'eta': None, 'id': 'a8ca18...227a56'} (216b)


问:
Data Analytics Approach
I have a dataset of fresh graduate employees with their GPA scores and whether they were hired or fired after Probation period. I was asked by the boss to analyse whether the university GPA has any significant effect on being hired or fired. Sometimes additional features can also be included like university ranking and etc. Boss is now a days interested in data science and machine learning. But I haven't had any prior experience in data analytics  So just give me a heads up into how i can approach this problem and what i should learn to do this? I have programming background (know python) so technical jargons are welcome.</p>

答:
You are trying to predict the employment status of fresh graduates given their GPA, University_ranking etc as features.

Your problem can be considered as a "Binary Classification problem" since your output should be fired/hired as (0 or 1)

Training_set: First of all you need to create a training set with features and their actual output.

Feature Analysis: Try to analyze how the data is affecting the output using something like this:

```<code>train = pd.read_csv('../input/train.csv')
print (train[["GPA", "Employment_status"]].groupby(['GPA'], as_index=False).mean())
</code>```

Algorithm to train: There are many machine learning algorithms that can be used to solve binary classification problems like SVM, Decision trees, KNN.
You can also go for anomaly detection where you can fit a distribution with one of the outputs.
Use sklearn libraries, because they are easy to use and also provide a large variety of algorithms.

Check this to learn more about sklearn.

Testing: Finally test your model with a test set and calculate the accuracy to see how the model has fit the data.

Check out the lectures by andrew ng as they are very easy to understand for anyone who is starting machine learning.Find it here

Data Visualization:

Kaggle is one of the best platforms to learn new approaches and algorithms Check this link as it provides information about how to use different data visualization tools on Iris dataset.

Check this MOOC to learn more about data visualizations.

Data Visualizations will thereby help you understand how your features are correlated.

Title: Data Analytics Approach

Body:
You are trying to predict the employment status of fresh graduates given their GPA, University_ranking etc as features.

Your problem can be considered as a "Binary Classification problem" since your output should be fired/hired as (0 or 1)

Training_set: First of all you need to create a training set with features and their actual output.

Feature Analysis: Try to analyze how the data is affecting the output using something like this:

train = pd.read_csv('../input/train.csv')
print (train[["GPA", "Employment_status"]].groupby(['GPA'], as_index=False).mean())

Algorithm to train: There are many machine learning algorithms that can be used to solve binary classification problems like SVM, Decision trees, KNN.
You can also go for anomaly detection where you can fit a distribution with one of the outputs.
Use sklearn libraries, because they are easy to use and also provide a large variety of algorithms.

Check this to learn more about sklearn.

Testing: Finally test your model with a test set and calculate the accuracy to see how the model has fit the data.

Check out the lectures by andrew ng as they are very easy to understand for anyone who is starting machine learning.Find it here

Data Visualization:

Kaggle is one of the best platforms to learn new approaches and algorithms Check this link as it provides information about how to use different data visualization tools on Iris dataset.

Check this MOOC to learn more about data visualizations.

Data Visualizations will thereby help you understand how your features are correlated.


问:
Is it possible to add html inside a title attribute?
Is there a way to put actual html code inside a title attribute on a table row element?  My goal is to pop-up not only text but some info-graphics along with it, so a mouseover event thats not a modal would be great.  Am I going in the wrong direction?

This table is already using jquery datatables but I don't believe it can do that sort of event.

```<code><tr title='This activity will be open to registration on April 31st' >
.....
</tr>
</code>```

答:
There is no direct way to render HTML code written inside a tooltip. However, if you are using jQueryUI (or, if you can) then the code below will show the HTML effect (render) and not the HTML code in the tooltip.

Requirements: jQuery, jQueryUI.js, jQueryUI.css

HTML Code:

```<code><tr data-title='This activity will be open to registration on <b>April 31st</b>'>.....</tr>
</code>```

JavaScript:

```<code>$(function() {
        $( document ).tooltip({
              items: '[title], [data-title]',
              track:true,
              content: function(){
                  var element = $( this );
                    if ( element.is( "[title]" ) ) {
                      return element.attr( "title" );
                    }
                    if ( element.is( "[data-title]" ) ) {
                      return element.attr( "data-title" );
                    }
              }
        });
});
</code>```

Body:
Is there a way to put actual html code inside a title attribute on a table row element?  My goal is to pop-up not only text but some info-graphics along with it, so a mouseover event thats not a modal would be great.  Am I going in the wrong direction?

This table is already using jquery datatables but I don't believe it can do that sort of event.

.....

Body:
There is no direct way to render HTML code written inside a tooltip. However, if you are using jQueryUI (or, if you can) then the code below will show the HTML effect (render) and not the HTML code in the tooltip.

Requirements: jQuery, jQueryUI.js, jQueryUI.css

HTML Code:

<tr data-title='This activity will be open to registration on <b>April 31st</b>'>.....</tr>

JavaScript:

$(function() {
        $( document ).tooltip({
              items: '[title], [data-title]',
              track:true,
              content: function(){
                  var element = $( this );
                    if ( element.is( "[title]" ) ) {
                      return element.attr( "title" );
                    }
                    if ( element.is( "[data-title]" ) ) {
                      return element.attr( "data-title" );
                    }
              }
        });
});


问:
Another Git process seems to be running in this repository
I'm trying to learn how to use Git and have created a small project with an HTML, CSS, and JavaScript file. I made a branch from my basically empty project and then made some changes to my code. I tried staging the changes, but I get the following error message:

```<code>Another git process seems to be running in this repository, e.g.
an editor opened by 'git commit'. Please make sure all processes
are terminated then try again. If it still fails, a git process
may have crashed in this repository earlier:
remove the file manually to continue.
</code>```

Granted, I did run into problems trying to commit my empty project earlier and just quit Git Bash since I didn't know how to get out of where I somehow had gotten.

Is there a way for me to fix this or should I just start a new repository?

答:
It is similar to methods in previous answers, but in my case I had several of those:

```<code>.git/refs/heads/<branch_name>.lock
</code>```

And I was able to remove all at once by this way:

```<code>find -name "*.lock" -exec xargs rm {} \;
</code>```

Body:
I'm trying to learn how to use Git and have created a small project with an HTML, CSS, and JavaScript file. I made a branch from my basically empty project and then made some changes to my code. I tried staging the changes, but I get the following error message:

Another git process seems to be running in this repository, e.g.
an editor opened by 'git commit'. Please make sure all processes
are terminated then try again. If it still fails, a git process
may have crashed in this repository earlier:
remove the file manually to continue.

Granted, I did run into problems trying to commit my empty project earlier and just quit Git Bash since I didn't know how to get out of where I somehow had gotten.

Is there a way for me to fix this or should I just start a new repository?

Body:
It is similar to methods in previous answers, but in my case I had several of those:

.git/refs/heads/<branch_name>.lock

And I was able to remove all at once by this way:

find -name "*.lock" -exec xargs rm {} \;


问:
How to unit test with ILogger in ASP.NET Core
This is my controller:

```<code>public class BlogController : Controller
{
    private IDAO<Blog> _blogDAO;
    private readonly ILogger<BlogController> _logger;

    public BlogController(ILogger<BlogController> logger, IDAO<Blog> blogDAO)
    {
        this._blogDAO = blogDAO;
        this._logger = logger;
    }
    public IActionResult Index()
    {
        var blogs = this._blogDAO.GetMany();
        this._logger.LogInformation("Index page say hello", new object[0]);
        return View(blogs);
    }
}
</code>```

As you can see I have 2 dependencies, a IDAO and a ILogger

And this is my test class, I use xUnit to test and Moq to create mock and stub, I can mock DAO easy, but with the ILogger I don't know what to do so I just pass null and comment out the call to log in controller when run test. Is there a way to test but still keep the logger somehow ?

```<code>public class BlogControllerTest
{
    [Fact]
    public void Index_ReturnAViewResult_WithAListOfBlog()
    {
        var mockRepo = new Mock<IDAO<Blog>>();
        mockRepo.Setup(repo => repo.GetMany(null)).Returns(GetListBlog());
        var controller = new BlogController(null,mockRepo.Object);

        var result = controller.Index();

        var viewResult = Assert.IsType<ViewResult>(result);
        var model = Assert.IsAssignableFrom<IEnumerable<Blog>>(viewResult.ViewData.Model);
        Assert.Equal(2, model.Count());
    }
}
</code>```

答:
Use a custom logger that uses ITestOutputHelper (from xunit) to capture output and logs. The following is a small sample that only writes the state to the output.

```<code>public class XunitLogger<T> : ILogger<T>, IDisposable
{
    private ITestOutputHelper _output;

    public XunitLogger(ITestOutputHelper output)
    {
        _output = output;
    }
    public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
    {
        _output.WriteLine(state.ToString());
    }

    public bool IsEnabled(LogLevel logLevel)
    {
        return true;
    }

    public IDisposable BeginScope<TState>(TState state)
    {
        return this;
    }

    public void Dispose()
    {
    }
}
</code>```

Use it in your unittests like

```<code>public class BlogControllerTest
{
  private XunitLogger<BlogController> _logger;

  public BlogControllerTest(ITestOutputHelper output){
    _logger = new XunitLogger<BlogController>(output);
  }

  [Fact]
  public void Index_ReturnAViewResult_WithAListOfBlog()
  {
    var mockRepo = new Mock<IDAO<Blog>>();
    mockRepo.Setup(repo => repo.GetMany(null)).Returns(GetListBlog());
    var controller = new BlogController(_logger,mockRepo.Object);
    // rest
  }
}
</code>```

Body:
This is my controller:

public class BlogController : Controller
{
    private IDAO<Blog> _blogDAO;
    private readonly ILogger<BlogController> _logger;

    public BlogController(ILogger<BlogController> logger, IDAO<Blog> blogDAO)
    {
        this._blogDAO = blogDAO;
        this._logger = logger;
    }
    public IActionResult Index()
    {
        var blogs = this._blogDAO.GetMany();
        this._logger.LogInformation("Index page say hello", new object[0]);
        return View(blogs);
    }
}

As you can see I have 2 dependencies, a IDAO and a ILogger

And this is my test class, I use xUnit to test and Moq to create mock and stub, I can mock DAO easy, but with the ILogger I don't know what to do so I just pass null and comment out the call to log in controller when run test. Is there a way to test but still keep the logger somehow ?

public class BlogControllerTest
{
    [Fact]
    public void Index_ReturnAViewResult_WithAListOfBlog()
    {
        var mockRepo = new Mock<IDAO<Blog>>();
        mockRepo.Setup(repo => repo.GetMany(null)).Returns(GetListBlog());
        var controller = new BlogController(null,mockRepo.Object);

        var result = controller.Index();

        var viewResult = Assert.IsType<ViewResult>(result);
        var model = Assert.IsAssignableFrom<IEnumerable<Blog>>(viewResult.ViewData.Model);
        Assert.Equal(2, model.Count());
    }
}

Body:
Use a custom logger that uses ITestOutputHelper (from xunit) to capture output and logs. The following is a small sample that only writes the state to the output.

public class XunitLogger<T> : ILogger<T>, IDisposable
{
    private ITestOutputHelper _output;

    public XunitLogger(ITestOutputHelper output)
    {
        _output = output;
    }
    public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
    {
        _output.WriteLine(state.ToString());
    }

    public bool IsEnabled(LogLevel logLevel)
    {
        return true;
    }

    public IDisposable BeginScope<TState>(TState state)
    {
        return this;
    }

    public void Dispose()
    {
    }
}

Use it in your unittests like

public class BlogControllerTest
{
  private XunitLogger<BlogController> _logger;

  public BlogControllerTest(ITestOutputHelper output){
    _logger = new XunitLogger<BlogController>(output);
  }

  [Fact]
  public void Index_ReturnAViewResult_WithAListOfBlog()
  {
    var mockRepo = new Mock<IDAO<Blog>>();
    mockRepo.Setup(repo => repo.GetMany(null)).Returns(GetListBlog());
    var controller = new BlogController(_logger,mockRepo.Object);
    // rest
  }
}