问:
How can I force Visual Studio to use dependency library names I want it to?
I've created a static c++ library in Visual Studio (2013) called "mylib.lib".  It is multi-threaded (/MT) and I specify the "output file" under Librarian/General to be "$(OutDir)$(TargetName)$(TargetExt)" so I can name it without the "mt" Visual Studio wants to force onto the end of the file name just because I used '/MT'.

This project also links in several other dependencies so they're all in one giant "mylib.lib" file for consumption by using applications.  These other librarys are "A.lib", "B.lib", and "C.lib". They are also built specifying the output name so as not to have "mt" on the end of their file names.

Now I want to consume "mylib.lib" in a C++ application that also uses '/MT' to build.  The application links with that library and calls a single function within it.  The application fails to link because it "cannot open file 'Amt.lib' LNK1104".

The application doesn't have a direct dependency on "A.lib" and that dependency is already contained in "mylib.lib" which it DOESN'T try to link as "mylibmt.lib".  The seemingly arbitrary decision to apply the "mt" suffix in one case and not another is confusing.

What is going on inside Visual Studio's mind here?  And is there a way I can tell it to NOT append "mt" onto certain libraries?

答:
One way to accomplish this is to set "No default libraries" in the consuming application and then manually add every "additional" dependency in the Linker section. This requires tracing all the way down the dependency tree, but it does work.

The easier way to do it is add the desired libraries to the "Ignore specific default libraries" field under Linker|Input. For example, I added "Amt.lib", "Bmt.lib", and "Cmt.lib" to that field -- then added "A.lib", "B.lib", and "C.lib" to the "Additional Dependencies" field (also under Linker|Input).


来源: stackexchange

问:
delay function in kafka streams
was trying something with the kafka streams code and wanted to add delay or something like threads.sleep() for 1ms after splitting data....I m confused how to do that..can someone help me out in doing that?

```<code>KStreamBuilder builder = new KStreamBuilder();
KStream<String, String> textlines = builder.stream("INTOPIC");
KStream<String, String> mstream = textlines
    .mapValues(value -> value.replace("[",""));
    .mapValues(value -> value.replace("]",""));
    .mapValues(value -> value.replaceAll("\\},\\{" ,"\\}\\},\\{\\{"))
    .flatMapValues(value -> Arrays.asList(value.split("\\},\\{")));
mstream.to("OUTTOPIC");
KafkaStreams streams = new KafkaStreams(builder, config);
streams.start();
</code>```

So after .flatmapvalues statement I need to add a thread.sleep() for 1ms so what can be my statement there..?

答: Not sure what you want to achieve, but it seems you want to slow down processing? Than you can just put a sleep into your use code. For this, your lambda expression must call "sleep" before it returns the actual result. As an alternative, you can also add an additional .foreach() or peek() call and sleep there.

ContentLicense: CC BY-SA 3.0

Title: delay function in kafka streams

Body:
was trying something with the kafka streams code and wanted to add delay or something like threads.sleep() for 1ms after splitting data....I m confused how to do that..can someone help me out in doing that?

KStreamBuilder builder = new KStreamBuilder();
KStream<String, String> textlines = builder.stream("INTOPIC");
KStream<String, String> mstream = textlines
    .mapValues(value -> value.replace("[",""));
    .mapValues(value -> value.replace("]",""));
    .mapValues(value -> value.replaceAll("\\},\\{" ,"\\}\\},\\{\\{"))
    .flatMapValues(value -> Arrays.asList(value.split("\\},\\{")));
mstream.to("OUTTOPIC");
KafkaStreams streams = new KafkaStreams(builder, config);
streams.start();

So after .flatmapvalues statement I need to add a thread.sleep() for 1ms so what can be my statement there..?

ContentLicense: CC BY-SA 4.0


问:
Use c++ libraries at C#
I'm working myself on a project, because performance is important i want to write some part of the code on c++ and want to call c++ codes from C#. I will write c++ library and want to write a C# wrapper, how can i do it? Have you any suggestion where i should begin to study? [any website, any link, any book]

Thanks !

答:
Example:

Windows:

```<code>[DllImport("User32.dll")]
public static extern void SetWindowText(int h, String s);
</code>```

Linux:

```<code>[System.Runtime.InteropServices.DllImport("/root/Desktop/q3noclient/libnoclient.so")]
static extern int DisconnectClient (string strServerIP, int iServerPort, string strClientIP, int iClientPort);
</code>```

C#:

```<code>[DllImport("Comdlg32.dll", CharSet=CharSet.Auto, SetLastError=true)]
private static extern bool GetSaveFileName(ref OPENFILENAME lpofn);
</code>```

VB.NET:

```<code><DllImport("Comdlg32.dll", CharSet:=CharSet.Auto, SetLastError:=True)> _
Private Shared Function GetSaveFileName(ByRef lpofn As OPENFILENAME) As Boolean
End Function
</code>```

ContentLicense: CC BY-SA 2.5

Title: Use c++ libraries at C#

Body:
Example:

Windows:

[DllImport("User32.dll")]
public static extern void SetWindowText(int h, String s);

Linux:

[System.Runtime.InteropServices.DllImport("/root/Desktop/q3noclient/libnoclient.so")]
static extern int DisconnectClient (string strServerIP, int iServerPort, string strClientIP, int iClientPort);

C#:

[DllImport("Comdlg32.dll", CharSet=CharSet.Auto, SetLastError=true)]
private static extern bool GetSaveFileName(ref OPENFILENAME lpofn);

VB.NET:

<DllImport("Comdlg32.dll", CharSet:=CharSet.Auto, SetLastError:=True)> _
Private Shared Function GetSaveFileName(ByRef lpofn As OPENFILENAME) As Boolean
End Function


问:
Producing multiple joins with sqlalchemy statement and expression api
Consider you have the following sql to represent:

SELECT user.id, user.name FROM user
JOIN address ON user.id = address.user_id

Now having the orm models as below:

```<code>from sqlalchemy import Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
metadata = Base.metadata

class User(Base):
    __tablename__ = 'user'
    id = Column(Integer, primary_key=True)
    name = Column(String

class Address(Base):
    __tablename__ = 'address'
    id = Column(Integer, primary_key=True)
    address_name = Column(String(64))
    user_id = Column(Integer)

class PostalCode(Base):
    __tablename__ = 'postal_code'
    id = Column(Integer, primary_key=True)
    code = Column(Integer)
</code>```

When doing simple join like:

```<code>from sqlalchemy import select, join
u = User
add = Address
po = PostalCode

query = select([u.id, u.name]).select_from(join(u,add, u.id = add.user_id))
print(query)
</code>```

Will yield eqvivalent expression to above original sql.

However if I want to do something like:

SELECT user.id, user.name FROM user
JOIN address ON user.id = address.user_id
JOIN postal_code ON postal_code.id = address.id

By writing:

```<code>query = select([u.id, u.name]).select_from(join(u,add, u.id = add.user_id).join(po, po.id = add.id))
print(query)
</code>```

This yield an error saying something like:

```<code>Attributeerror: type object ____ has no attribute '_from_objects`
</code>```

Any idea what is wrong with my syntax for using of two joins?

The explanation of how using one join is here.

答:
By subquerying a join you can achieve a multiple join :</p>

```<code>query = select([u.id, u.name]).select_from(join(join(u,add, u.id = add.user_id),po, po.id = add.id))
print(query)
</code>```

Body:
Consider you have the following sql to represent:

SELECT user.id, user.name FROM user
JOIN address ON user.id = address.user_id

Now having the orm models as below:

from sqlalchemy import Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
metadata = Base.metadata

class User(Base):
    __tablename__ = 'user'
    id = Column(Integer, primary_key=True)
    name = Column(String

class Address(Base):
    __tablename__ = 'address'
    id = Column(Integer, primary_key=True)
    address_name = Column(String(64))
    user_id = Column(Integer)

class PostalCode(Base):
    __tablename__ = 'postal_code'
    id = Column(Integer, primary_key=True)
    code = Column(Integer)

When doing simple join like:

from sqlalchemy import select, join
u = User
add = Address
po = PostalCode

query = select([u.id, u.name]).select_from(join(u,add, u.id = add.user_id))
print(query)

Will yield eqvivalent expression to above original sql.

However if I want to do something like:

SELECT user.id, user.name FROM user
JOIN address ON user.id = address.user_id
JOIN postal_code ON postal_code.id = address.id

By writing:

query = select([u.id, u.name]).select_from(join(u,add, u.id = add.user_id).join(po, po.id = add.id))
print(query)

This yield an error saying something like:

Attributeerror: type object ____ has no attribute '_from_objects`

Any idea what is wrong with my syntax for using of two joins?

The explanation of how using one join is here.

Body:
By subquerying a join you can achieve a multiple join :

query = select([u.id, u.name]).select_from(join(join(u,add, u.id = add.user_id),po, po.id = add.id))
print(query)


问:
Accessing Nested NSDictionary values in Swift 3.0
I have the following data I received from Firebase. I have made my snapshotValue a NSDictionary.

```<code>self.ref.child("users").child(facebookID_Firebase as! String).observeSingleEvent(of: .value, with: { (snapshot) in
            let snapshotValue = snapshot.value as? NSDictionary
            print(snapshotValue, "snapshotValue")
            //this line of code doesn't work
            //self.pictureURL = snapshot["picture"]["data"]["url"]
        }) { (error) in
            print(error.localizedDescription)
        }
</code>```

I tried How do I manipulate nested dictionaries in Swift, e.g. JSON data? , How to access deeply nested dictionaries in Swift , and other solutions yet no luck.

How do I access the url value inside the data key AND the picture key?

I can make another reference in Firebase and get the value, but I'm trying to save another request.

答:
Inline dictionary unwrapping:</p>

```<code>let url = ((snapshot.value as? NSDictionary)?["picture"] as? NSDictionary)?["url"] as? String
</code>```

Body:
I have the following data I received from Firebase. I have made my snapshotValue a NSDictionary.

self.ref.child("users").child(facebookID_Firebase as! String).observeSingleEvent(of: .value, with: { (snapshot) in
            let snapshotValue = snapshot.value as? NSDictionary
            print(snapshotValue, "snapshotValue")
            //this line of code doesn't work
            //self.pictureURL = snapshot["picture"]["data"]["url"]
        }) { (error) in
            print(error.localizedDescription)
        }

I tried How do I manipulate nested dictionaries in Swift, e.g. JSON data? , How to access deeply nested dictionaries in Swift , and other solutions yet no luck.

How do I access the url value inside the data key AND the picture key?

I can make another reference in Firebase and get the value, but I'm trying to save another request.

Body:
Inline dictionary unwrapping:

let url = ((snapshot.value as? NSDictionary)?["picture"] as? NSDictionary)?["url"] as? String


问:
Where did this invalid object name come from?
I have a simple SQL UPDATE query which is complaining about an "invalid object name" AuditCrudFields which doesn't exist in my ASP.NET project at all. (I have already tried grepping for AuditCrudFields in my project but couldn't find matches.)

The UPDATE statement is:

```<code>UPDATE [dbo].[PartModel]
SET partOfficial = 39, updateTS = CONVERT(DATETIME, ‘2017-12-08’, 111)
WHERE partId = 298
</code>```

the error returned:

What's puzzling is that these are all the properties that exist inside PartModel. So I wonder where did AuditCrudFields come from?

```<code>public class PartModel : EntityInformation
{
    [Key]
    public Int64 partId { get; set; }

    public int partTypeId { get; set; }
    [ForeignKey("partTypeId")]
    public virtual PartTypeModel PartType { get; set; }

    public int locationId { get; set; }
    [ForeignKey("locationId")]
    public virtual LocationModel Location { get; set; }

    public int partOfficial { get; set; }
    public int partUnofficial { get; set; }
    public int partThreshold { get; set; }

    public string partImg { get; set; }
    public int partStatus { get; set; }
}
</code>```

答:
What you have is a deleted or renamed object called AuditCrudFields  (I will call it a dead object)

This is probably inside a Trigger definition (or perhaps buried inside a Stored Procedure, Function or Index definition...)

The most effective way of finding a dead object is by scripting your entire database into text (into one big SQL Script), then search for the text...

Where you find the text, will point to where it is used (a Trigger perhaps), and then you can repair or remove the trigger and hopefully its fixed.

There is alot of help with scripting a SQL SERVER database on the internet or SO, but here is another link

Body:
I have a simple SQL UPDATE query which is complaining about an "invalid object name" AuditCrudFields which doesn't exist in my ASP.NET project at all. (I have already tried grepping for AuditCrudFields in my project but couldn't find matches.)

The UPDATE statement is:

UPDATE [dbo].[PartModel]
SET partOfficial = 39, updateTS = CONVERT(DATETIME, ‘2017-12-08’, 111)
WHERE partId = 298

the error returned:

What's puzzling is that these are all the properties that exist inside PartModel. So I wonder where did AuditCrudFields come from?

public class PartModel : EntityInformation
{
    [Key]
    public Int64 partId { get; set; }

    public int partTypeId { get; set; }
    [ForeignKey("partTypeId")]
    public virtual PartTypeModel PartType { get; set; }

    public int locationId { get; set; }
    [ForeignKey("locationId")]
    public virtual LocationModel Location { get; set; }

    public int partOfficial { get; set; }
    public int partUnofficial { get; set; }
    public int partThreshold { get; set; }

    public string partImg { get; set; }
    public int partStatus { get; set; }
}


问:
C# clearing sensitive data after communicating it to payment gateways.
I'm trying to find a solution for clearing sensitive credit card data from memory after communicating it to a payment gateway. Most payment gateways seem to expect the plain text card number as a string in the API. If I use a string in C# I cannot clear the memory as I do not have any control over when the memory is garbage collected. The below dto snippet from an SDK for Cybersource illustrates my problem.
Note I'm trying to fulfill PA-DSS version 3.2 requirement 5.1.6.1 Coding techniques include documentation of how PAN and/or SAD are handled in memory. Our auditor is indicating that plain text account numbers cannot be stored in a C# string variable.

We have integrations with other gateways that also have this PAN in string variable issue. How are others dealing with this problem?

```<code>namespace CyberSource.Clients.SoapServiceReference
{
    //
    [DebuggerStepThrough]
    [DesignerCategory("code")]
    [GeneratedCode("System.Xml", "4.0.30319.34234")]
    [XmlType(Namespace = "urn:schemas-cybersource-com:transaction-data-1.109")]
    public class Card : INotifyPropertyChanged
    {
        public Card();

        [XmlElement(Order = 6)]
        public string cardType { get; set; }
        //
        [XmlElement(Order = 5)]
        public string cvNumber { get; set; }
        //
        [XmlElement(Order = 4)]
        public string cvIndicator { get; set; }
        //
        [XmlElement(DataType = "integer", Order = 3)]
        public string expirationYear { get; set; }
        //
        [XmlElement(DataType = "integer", Order = 2)]
        public string expirationMonth { get; set; }
        //
        [XmlElement(Order = 1)]
        public string accountNumber { get; set; }
        //
        [XmlElement(Order = 0)]
        public string fullName { get; set; }
</code>```

答:
The solution is to use SecureString:
https://learn.microsoft.com/en-us/dotnet/api/system.security.securestring?view=netframework-4.7.1

Lots of examples on how to use it:

When would I need a SecureString in .NET?

Memory Heap Security: String garbage collection

C# SecureString Question

Body:
I'm trying to find a solution for clearing sensitive credit card data from memory after communicating it to a payment gateway. Most payment gateways seem to expect the plain text card number as a string in the API. If I use a string in C# I cannot clear the memory as I do not have any control over when the memory is garbage collected. The below dto snippet from an SDK for Cybersource illustrates my problem.
Note I'm trying to fulfill PA-DSS version 3.2 requirement 5.1.6.1 Coding techniques include documentation of how PAN and/or SAD are handled in memory. Our auditor is indicating that plain text account numbers cannot be stored in a C# string variable.

We have integrations with other gateways that also have this PAN in string variable issue. How are others dealing with this problem?

namespace CyberSource.Clients.SoapServiceReference
{
    //
    [DebuggerStepThrough]
    [DesignerCategory("code")]
    [GeneratedCode("System.Xml", "4.0.30319.34234")]
    [XmlType(Namespace = "urn:schemas-cybersource-com:transaction-data-1.109")]
    public class Card : INotifyPropertyChanged
    {
        public Card();

        [XmlElement(Order = 6)]
        public string cardType { get; set; }
        //
        [XmlElement(Order = 5)]
        public string cvNumber { get; set; }
        //
        [XmlElement(Order = 4)]
        public string cvIndicator { get; set; }
        //
        [XmlElement(DataType = "integer", Order = 3)]
        public string expirationYear { get; set; }
        //
        [XmlElement(DataType = "integer", Order = 2)]
        public string expirationMonth { get; set; }
        //
        [XmlElement(Order = 1)]
        public string accountNumber { get; set; }
        //
        [XmlElement(Order = 0)]
        public string fullName { get; set; }


问:
How to pass any pdf link and open it
What i am trying to do is pass any pdf link and just open it.
This is what i came up so far but it returns a blank page.

```<code><input type="link" id="link" />
<input type="button" id="btn" value="Open"
onClick="javascript: window.open( document.getElementById('link').value);" />
</code>```

I am trying to pass the link below

https://gradcollege.okstate.edu/sites/default/files/PDF_linking.pdf

答:
you havet to do like this

```<code><input type="link" id="link" value ="https://gradcollege.okstate.edu/sites/default/files/PDF_linking.pdf"/>
<input type="button" id="btn" value="Open"
onClick="javascript: window.open( document.getElementById('link').value);" />
</code>```

if working have look to jsfiddle : https://jsfiddle.net/pranayamr/g5je1n3a/

you can try like this ,havent tested in chrom as i dont have it on my machine but might work in chrome too

function openInNewTab(url) {
  var win = window.open(url, '_blank');
  win.focus();
}

Title: How to pass any pdf link and open it

Body:
What i am trying to do is pass any pdf link and just open it.
This is what i came up so far but it returns a blank page.

<input type="link" id="link" />
<input type="button" id="btn" value="Open"
onClick="javascript: window.open( document.getElementById('link').value);" />

I am trying to pass the link below

https://gradcollege.okstate.edu/sites/default/files/PDF_linking.pdf

Body:
you havet to do like this

<input type="link" id="link" value ="https://gradcollege.okstate.edu/sites/default/files/PDF_linking.pdf"/>
<input type="button" id="btn" value="Open"
onClick="javascript: window.open( document.getElementById('link').value);" />

if working have look to jsfiddle : https://jsfiddle.net/pranayamr/g5je1n3a/

you can try like this ,havent tested in chrom as i dont have it on my machine but might work in chrome too

function openInNewTab(url) {
  var win = window.open(url, '_blank');
  win.focus();
}


问:
How to get a reference to the list in an ngfor with a pipe applied to it
I am applying a filter to a list inside an ngfor like so *ngFor="data | pipe" I want access to the object that gets outputted from the filter in my ts component class. I tried using this: *ngFor="data | pipe as filtereddata", but I think that only works relative to the tag and doesn't seem to get applied to the object on the component. Is there a way to get access to this filtered data?

For reference the pipe does a sort and a filter and I want to be able to select the first item in the list and I don't want to have to resort the data in the ts if it's already being done.

答:
I would suggest to put your sorting logic in a property with getter in your ts. Something like:

```<code>get sortedData(): any[] {
    return ...your sorting logic...
}
</code>```

Than do the ngFor through this sortedData property.

Note: return type from the getter could be you specific type ( e.g. YourType[] )

I hope this will help you

Body:
I would suggest to put your sorting logic in a property with getter in your ts. Something like:

get sortedData(): any[] {
    return ...your sorting logic...
}

Than do the ngFor through this sortedData property.

Note: return type from the getter could be you specific type ( e.g. YourType[] )

I hope this will help you


问:
Select random element in a list of R?
```<code>a<-c(1,2,0,7,5)
</code>```

Some languages have a picker -function -- choose one random number from a -- how in R?

答:
This method doesn't produce an error when your vector is length one, and it's simple.</p>
```<code>a[sample(1:length(a), 1)]
</code>```

Title: Select random element in a list of R?

Body:
a<-c(1,2,0,7,5)

Some languages have a picker -function -- choose one random number from a -- how in R?

Body:
This method doesn't produce an error when your vector is length one, and it's simple.

a[sample(1:length(a), 1)]


问:
AJAX returns blank page and prints the code
AJAX function should return HTML inside the div checkout-wrap in the same page. Instead, it redirects to a blank page and prints the array

Code in Controller:

```<code>return ['success'=>1, 'msg'=> trans('app.payment_received_msg'), 'response' => $this->payment_success_html()];
</code>```

What is printed:

```<code>{"success":1,"msg":"Success","response":" <div class=\"payment-received\">\n    <h1> <i class=\"fa fa-check-circle-o\"><\/i> Thank You<\/h1>\n    \n    <a href=\"http:\/\/localhost\" class=\"btn btn-filled\">Home<\/a>\n   <\/div>"}
</code>```

I'm using Laravel.

Ajax Function

```<code>$.ajax({
    url : '{{route('pg_submit')}}',
    type: "POST",
    data: form,
success : function (data) {
    if (data.success == 1){
       $('.checkout-wrap').html(data.response);
       toastr.success(data.msg, '@lang('app.success')', toastr_options);
    }
},
error   : function ( jqXhr, json, errorThrown ) {
    var errors = jqXhr.responseJSON;
    var errorsHtml= '';
    $.each( errors, function( key, value ) {
        errorsHtml += '<li>' + value[0] + '</li>';
    });
    toastr.error( errorsHtml , "Error " + jqXhr.status +': '+ errorThrown);
}
});
</code>```

Route pg_submit

```<code>Route::post('checkout/pg', ['as' => 'pg_submit','uses' => 'CampaignsController@pgRedirect']);
</code>```

答:
Maybe you have action & method attribute on your form like

<form action="/checkout/pg" method="post">

You can remove the attributes and give the id or class to your from like this

<form id="pg_submit">

Than you can add or modify your script like this

```<code>$('#pg_submit').submit(function (e) {
    e.preventDefault();
    $.ajax({
        url : '{{route('pg_submit')}}',
        type: "POST",
        data: form,
        success : function (data) {
            if (data.success == 1){
               $('.checkout-wrap').html(data.response);
               toastr.success(data.msg, '@lang('app.success')', toastr_options);
            }
        },
        error   : function ( jqXhr, json, errorThrown ) {
            var errors = jqXhr.responseJSON;
            var errorsHtml= '';
            $.each( errors, function( key, value ) {
                errorsHtml += '<li>' + value[0] + '</li>';
            });
            toastr.error( errorsHtml , "Error " + jqXhr.status +': '+ errorThrown);
        }
    });
});
</code>```

Body:
AJAX function should return HTML inside the div checkout-wrap in the same page. Instead, it redirects to a blank page and prints the array

Code in Controller:

return ['success'=>1, 'msg'=> trans('app.payment_received_msg'), 'response' => $this->payment_success_html()];

What is printed:

{"success":1,"msg":"Success","response":"
\n
 <\/i> Thank You<\/h1>\n    \n    Home<\/a>\n   <\/div>"}

I'm using Laravel.

Ajax Function

$.ajax({
    url : '{{route('pg_submit')}}',
    type: "POST",
    data: form,
success : function (data) {
    if (data.success == 1){
       $('.checkout-wrap').html(data.response);
       toastr.success(data.msg, '@lang('app.success')', toastr_options);
    }
},
error   : function ( jqXhr, json, errorThrown ) {
    var errors = jqXhr.responseJSON;
    var errorsHtml= '';
    $.each( errors, function( key, value ) {
        errorsHtml += '
' + value[0] + '
';
    });
    toastr.error( errorsHtml , "Error " + jqXhr.status +': '+ errorThrown);
}
});

Route pg_submit

Route::post('checkout/pg', ['as' => 'pg_submit','uses' => 'CampaignsController@pgRedirect']);

Body:
Maybe you have action & method attribute on your form like

<form action="/checkout/pg" method="post">

You can remove the attributes and give the id or class to your from like this

<form id="pg_submit">

Than you can add or modify your script like this

$('#pg_submit').submit(function (e) {
    e.preventDefault();
    $.ajax({
        url : '{{route('pg_submit')}}',
        type: "POST",
        data: form,
        success : function (data) {
            if (data.success == 1){
               $('.checkout-wrap').html(data.response);
               toastr.success(data.msg, '@lang('app.success')', toastr_options);
            }
        },
        error   : function ( jqXhr, json, errorThrown ) {
            var errors = jqXhr.responseJSON;
            var errorsHtml= '';
            $.each( errors, function( key, value ) {
                errorsHtml += '<li>' + value[0] + '</li>';
            });
            toastr.error( errorsHtml , "Error " + jqXhr.status +': '+ errorThrown);
        }
    });
});


问:
Convert a List of Object to Map<String,String> using jdk 8 lambdas
I want to convert a List<Properies> to a Map<String,String> using jdk 8 lambdas without doing a for loop. The map should contain the key as SubProperty.name and value as Properties.value.

```<code>public class Properties
{
    private SubProperty subProperty;

    private String value;

    public SubProperty getSubProperty()
    {
        return subProperty;
    }

    public void setSubProperty(SubProperty subProperty)
    {
        this.subProperty = subProperty;
    }

    public String getValue()
    {
        return value;
    }

    public void setValue(String value)
    {
        this.value = value;
    }
}

public class SubProperty
{
    private String category;
    private String name;

    public String getCategory()
    {
        return category;
    }

    public void setCategory(String category)
    {
        this.category = category;
    }

    public String getName()
    {
        return name;
    }

    public void setName(String name)
    {
        this.name = name;
    }
}
</code>```

答:
When you construct a Map from a Stream using Collectors.toMap(), you must consider whether your Stream may contain duplicate keys. In your case duplicate keys mean multiple Properties instances having SubProperty with the same name.

To resolve duplicates, you can use the 3 argument variant of Collectors.toMap. For example, the following will choose one of the getValue() values when encountering duplicate keys:

```<code>Map<String,String> map =
    list.stream()
        .collect(Collectors.toMap(p -> p.getSubProperty().getName(),
                                  Properties::getValue,
                                  (v1,v2) -> v1));
</code>```

Another option is to use Collectors.groupingBy, which would group the values that share the same key into a List:

```<code>Map<String,List<String>> map =
    list.stream()
        .collect(Collectors.groupingBy(p -> p.getSubProperty().getName(),
                                       Collectors.mapping(Properties::getValue,
                                                          Collectors.toList())));
</code>```

Body:
I want to convert a List<Properies> to a Map<String,String> using jdk 8 lambdas without doing a for loop. The map should contain the key as SubProperty.name and value as Properties.value.

public class Properties
{
    private SubProperty subProperty;

    private String value;

    public SubProperty getSubProperty()
    {
        return subProperty;
    }

    public void setSubProperty(SubProperty subProperty)
    {
        this.subProperty = subProperty;
    }

    public String getValue()
    {
        return value;
    }

    public void setValue(String value)
    {
        this.value = value;
    }
}

public class SubProperty
{
    private String category;
    private String name;

    public String getCategory()
    {
        return category;
    }

    public void setCategory(String category)
    {
        this.category = category;
    }

    public String getName()
    {
        return name;
    }

    public void setName(String name)
    {
        this.name = name;
    }
}

Body:
When you construct a Map from a Stream using Collectors.toMap(), you must consider whether your Stream may contain duplicate keys. In your case duplicate keys mean multiple Properties instances having SubProperty with the same name.

To resolve duplicates, you can use the 3 argument variant of Collectors.toMap. For example, the following will choose one of the getValue() values when encountering duplicate keys:

Map<String,String> map =
    list.stream()
        .collect(Collectors.toMap(p -> p.getSubProperty().getName(),
                                  Properties::getValue,
                                  (v1,v2) -> v1));

Another option is to use Collectors.groupingBy, which would group the values that share the same key into a List:

Map<String,List<String>> map =
    list.stream()
        .collect(Collectors.groupingBy(p -> p.getSubProperty().getName(),
                                       Collectors.mapping(Properties::getValue,
                                                          Collectors.toList())));


问:
Asp radio buttons using bootstrap 3 to make them appear as toggle buttons
I have 4 asp radio buttons that I want to appear like toggle buttons, but still function as asp radio buttons. Mainly, I need the CheckedChanged event to fire when the button is clicked. Currently, this is what I have for the HTML:

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

                ACH/E-Check
                <asp:RadioButton ID="rdo_ach" runat="server" Font-Bold="True" GroupName="rdo_pay_type"
                        AutoPostBack="True" Text="ACH/E-Check" CssClass="radioButton"></asp:RadioButton>

                Debit/Credit Card
                <asp:RadioButton ID="rdo_cc" runat="server" Font-Bold="True" GroupName="rdo_pay_type"
                    AutoPostBack="True" Text="Debit/Credit Card" CssClass="radioButton"></asp:RadioButton>

                Check
                <asp:RadioButton ID="rdo_ck" runat="server" Font-Bold="True" GroupName="rdo_pay_type"
                        AutoPostBack="True" Text="Check"></asp:RadioButton>

                EFT
                <asp:RadioButton ID="rdo_et" Font-Bold="True" GroupName="rdo_pay_type" AutoPostBack="True"
                    Text="EFT Deposit" runat="server"></asp:RadioButton>

```
</div>
</div>
</p>

<p>The radioButton CSS class:</p>

```
```

The issue I am currently having is when I do not have the radioButton css class on the asp:RadioButtons, the radio button shows through the button group and you have to click specifically within the radio to get the CheckedChanged event to fire. When I do have the class on the radio buttons, the radio button does not display through the button group, but when I click the button, the CheckedChanged event won't fire at all.

I also attempted using asp:Button instead of asp:RadioButton and then setting the necessary checked property so that the code behind runs properly, but due to the update panel on the master page, I can't get a full postback to run.

Is there any way to get a button group to display, but have a full postback run when one of the buttons is clicked?

答:
I figured it out. The issue is the javascript that handles the toggle buttons doesn't allow the postback to fire. Since I didn't want to change the functionality of all toggle buttons, I changed data-toggle="buttons" to data-toggle="buttons-postback" and modified the Button.prototype.toggle function in bootstrap.js to this:

```<code>Button.prototype.toggle = function () {
    var changed = true
    var $parent = this.$element.closest('[data-toggle="buttons"]')

    if ($parent.length) {
        var $input = this.$element.find('input')
        if ($input.prop('type') == 'radio') {
            if ($input.prop('checked')) changed = false
            $parent.find('.active').removeClass('active')
            this.$element.addClass('active')
        } else if ($input.prop('type') == 'checkbox') {
            if (($input.prop('checked')) !== this.$element.hasClass('active')) changed = false
            this.$element.toggleClass('active')
        }
        $input.prop('checked', this.$element.hasClass('active'))
        if (changed) $input.trigger('change')
    } else {
        var $parent = this.$element.closest('[data-toggle="buttons-postback"]')
        if ($parent.length) {
            var $input = this.$element.find('input')
            if ($input.prop('type') == 'radio') {
                if ($input.prop('checked')) changed = false
                $parent.find('.active').removeClass('active')
                this.$element.addClass('active')
            } else if ($input.prop('type') == 'checkbox') {
                if (($input.prop('checked')) !== this.$element.hasClass('active')) changed = false
                this.$element.toggleClass('active')
            }
            $input.prop('checked', this.$element.hasClass('active'))
            if (changed) $input.trigger('change')
            __doPostBack($input.id, '')
        } else {

            this.$element.attr('aria-pressed', !this.$element.hasClass('active'))
            this.$element.toggleClass('active')
        }
    }
}
</code>```

The part that I added is almost an exact copy of the function, but adds __doPostBack($input.id, '') at the end of the processing when it finds a parent with data-toggle="buttons-postback"

Since the postback resets the HTML to its original state, I also added this to the event handlers in my code behind:

```<code>ach_lbl.Attributes.Add("Class", "btn btn-primary active")
If tbl_rdo_cc.Visible Then
    cc_lbl.Attributes.Add("Class", "btn btn-primary")
End If
If tbl_rdo_ck.Visible Then
    ck_lbl.Attributes.Add("Class", "btn btn-primary")
End If
If tbl_rdo_et.Visible Then
    et_lbl.Attributes.Add("Class", "btn btn-primary")
End If
</code>```

I know this probably isn't the most elegant solution (due to the fact I barely understand the JavaScript I modified), so any suggestions on what I can remove from what I added to the Button.prototype.toggle function would be greatly appreciated.

Body:
I have 4 asp radio buttons that I want to appear like toggle buttons, but still function as asp radio buttons. Mainly, I need the CheckedChanged event to fire when the button is clicked. Currently, this is what I have for the HTML:

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

                ACH/E-Check
                <asp:RadioButton ID="rdo_ach" runat="server" Font-Bold="True" GroupName="rdo_pay_type"
                        AutoPostBack="True" Text="ACH/E-Check" CssClass="radioButton"></asp:RadioButton>

                Debit/Credit Card
                <asp:RadioButton ID="rdo_cc" runat="server" Font-Bold="True" GroupName="rdo_pay_type"
                    AutoPostBack="True" Text="Debit/Credit Card" CssClass="radioButton"></asp:RadioButton>

                Check
                <asp:RadioButton ID="rdo_ck" runat="server" Font-Bold="True" GroupName="rdo_pay_type"
                        AutoPostBack="True" Text="Check"></asp:RadioButton>

                EFT
                <asp:RadioButton ID="rdo_et" Font-Bold="True" GroupName="rdo_pay_type" AutoPostBack="True"
                    Text="EFT Deposit" runat="server"></asp:RadioButton>

The radioButton CSS class:

The issue I am currently having is when I do not have the radioButton css class on the asp:RadioButtons, the radio button shows through the button group and you have to click specifically within the radio to get the CheckedChanged event to fire. When I do have the class on the radio buttons, the radio button does not display through the button group, but when I click the button, the CheckedChanged event won't fire at all.

I also attempted using asp:Button instead of asp:RadioButton and then setting the necessary checked property so that the code behind runs properly, but due to the update panel on the master page, I can't get a full postback to run.

Is there any way to get a button group to display, but have a full postback run when one of the buttons is clicked?

Body:
I figured it out. The issue is the javascript that handles the toggle buttons doesn't allow the postback to fire. Since I didn't want to change the functionality of all toggle buttons, I changed data-toggle="buttons" to data-toggle="buttons-postback" and modified the Button.prototype.toggle function in bootstrap.js to this:

Button.prototype.toggle = function () {
    var changed = true
    var $parent = this.$element.closest('[data-toggle="buttons"]')

    if ($parent.length) {
        var $input = this.$element.find('input')
        if ($input.prop('type') == 'radio') {
            if ($input.prop('checked')) changed = false
            $parent.find('.active').removeClass('active')
            this.$element.addClass('active')
        } else if ($input.prop('type') == 'checkbox') {
            if (($input.prop('checked')) !== this.$element.hasClass('active')) changed = false
            this.$element.toggleClass('active')
        }
        $input.prop('checked', this.$element.hasClass('active'))
        if (changed) $input.trigger('change')
    } else {
        var $parent = this.$element.closest('[data-toggle="buttons-postback"]')
        if ($parent.length) {
            var $input = this.$element.find('input')
            if ($input.prop('type') == 'radio') {
                if ($input.prop('checked')) changed = false
                $parent.find('.active').removeClass('active')
                this.$element.addClass('active')
            } else if ($input.prop('type') == 'checkbox') {
                if (($input.prop('checked')) !== this.$element.hasClass('active')) changed = false
                this.$element.toggleClass('active')
            }
            $input.prop('checked', this.$element.hasClass('active'))
            if (changed) $input.trigger('change')
            __doPostBack($input.id, '')
        } else {

            this.$element.attr('aria-pressed', !this.$element.hasClass('active'))
            this.$element.toggleClass('active')
        }
    }
}

The part that I added is almost an exact copy of the function, but adds __doPostBack($input.id, '') at the end of the processing when it finds a parent with data-toggle="buttons-postback"

Since the postback resets the HTML to its original state, I also added this to the event handlers in my code behind:

ach_lbl.Attributes.Add("Class", "btn btn-primary active")
If tbl_rdo_cc.Visible Then
    cc_lbl.Attributes.Add("Class", "btn btn-primary")
End If
If tbl_rdo_ck.Visible Then
    ck_lbl.Attributes.Add("Class", "btn btn-primary")
End If
If tbl_rdo_et.Visible Then
    et_lbl.Attributes.Add("Class", "btn btn-primary")
End If

I know this probably isn't the most elegant solution (due to the fact I barely understand the JavaScript I modified), so any suggestions on what I can remove from what I added to the Button.prototype.toggle function would be greatly appreciated.


问:
Azure Application Insights - Parse string in format dd/MM/yyyy to datetime
The question is pretty direct: how can i parse a string like "23/12/2017" (dd/MM/yyyy) to a datetime?

答:
Assuming you're asking about Application Insights Analytics this should do a trick:

todatetime("2015-12-24") == datetime(2015-12-24)

https://docs.loganalytics.io/docs/Language-Reference/Scalar-functions/todatetime()


问:
Call to a different macro at a certain line
Is it possible to use the call feature to call a macro at a specific line? I ask as the macro i am coding does this - First it runs half of the code, then based upon user choices it opens up a custom UserForm, and runs the UserForm command buttons. After this I need a command button to go back to the code the line after the UserForm was used. The UserForm works as intended and many different stats calculations can be run. It has a button that returns the user back to the rest of the code, but I can't get that to work. </p>

<p>I have tried using  both GoTo statements and the Call feature (The most promising solution) but have had no success so far. </p>

答:
You can use VBA for this, but I would recommend using the Windows Task Scheduler.  I think that will be a lot better, all things considered.

https://www.digitalcitizen.life/how-create-task-basic-task-wizard

Body:
Is it possible to use the call feature to call a macro at a specific line? I ask as the macro i am coding does this - First it runs half of the code, then based upon user choices it opens up a custom UserForm, and runs the UserForm command buttons. After this I need a command button to go back to the code the line after the UserForm was used. The UserForm works as intended and many different stats calculations can be run. It has a button that returns the user back to the rest of the code, but I can't get that to work.

I have tried using  both GoTo statements and the Call feature (The most promising solution) but have had no success so far.


问:
aesEncrypt produces different results
I'm trying to encrypt a string in Swift 3, and my encryption is giving different output every time. Why is that? (I have tried similar encryption in python, and the encrypted output is always the same).

Here is my Swift 3 aesEncrypt function:

```<code>func aesEncrypt(key:String, iv:Array<Any>, options:Int = kCCOptionPKCS7Padding) -> String? {
    if let keyData = sha256(string:key),
        let data = self.data(using: String.Encoding.utf8),
        let cryptData    = NSMutableData(length: Int((data.count)) + kCCBlockSizeAES128) {

        let keyLength              = size_t(kCCKeySizeAES128)
        let operation: CCOperation = UInt32(kCCEncrypt)
        let algorithm:  CCAlgorithm = UInt32(kCCAlgorithmAES128)
        let options:   CCOptions   = UInt32(options)

        var numBytesEncrypted :size_t = 0

        let cryptStatus = CCCrypt(operation,
                                  algorithm,
                                  options,
                                  (keyData as NSData).bytes, keyLength,
                                  iv,
                                  (data as NSData).bytes, data.count,
                                  cryptData.mutableBytes, cryptData.length,
                                  &numBytesEncrypted)
        // ADDED PRINT STATEMENTS
        print("keyData")
        print(keyData)
        print("\(keyData as NSData)")
        print("iv")
        print(iv)
        var hex_iv = toHexString(arr: iv as! [UInt8])
        print(hex_iv)
        print("data")
        print(data)
        print("\(data as NSData)")

        print("encryption: cryptdata")
        print(cryptData)

        print("encryption: num bytes encrypted")
        print(numBytesEncrypted)

        if UInt32(cryptStatus) == UInt32(kCCSuccess) {
            cryptData.length = Int(numBytesEncrypted)
            let base64cryptString = cryptData.base64EncodedString(options: .lineLength64Characters)
            return base64cryptString
        }
        else {
            return nil
        }
    }
    return nil
}
</code>```

When I try to run the following code with initial_string = "hello", I get different encrypted output strings every time.

```<code>let iv [UInt8](repeating: 0, count: 16)
let key = "sample_key"
let initial_string = "hello"

let encryptedString = initial_string.aesEncrypt(key: key, iv: iv)
print("Encrypted string")
print(encryptedString)
</code>```

sample output from running code with "hello" string first time:

```<code>keyData
32 bytes
<d5a78c66 e9b3ed40 b3a92480 c732527f 1a919fdc f68957d2 b7e9218f 6221085d>
iv
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00
data
5 bytes
<68656c6c 6f>
encryption: cryptdata
<b17d67fc 26e3f316 6a2bdfbf 9d387c2d 00000000 00>
encryption: num bytes encrypted
16
Encrypted string
Optional("sX1n/Cbj8xZqK9+/nTh8LQ==")
</code>```

sample output from running code with "hello" string second time:

```<code>keyData
32 bytes
<d5a78c66 e9b3ed40 b3a92480 c732527f 1a919fdc f68957d2 b7e9218f 6221085d>
iv
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00
data
5 bytes
<68656c6c 6f>
encryption: cryptdata
<01b9f69b 45deb31d eda46c2d dc9ad9e8 00000000 00>
encryption: num bytes encrypted
16
Encrypted string
Optional("Abn2m0Xesx3tpGwt3JrZ6A==")
</code>```

Can you tell me why the output is different every time for the same key, iv, and string? Thanks!

答: you see that IV? that is initialization vector, that functions as a counter to make you encryption different each time, making it more secure and hard to break. so basically your code is working fine, but to decrypt it correctly, the receiver can not act only by having Key , but needs IV also</p>

Title: aesEncrypt produces different results

Body:
I'm trying to encrypt a string in Swift 3, and my encryption is giving different output every time. Why is that? (I have tried similar encryption in python, and the encrypted output is always the same).

Here is my Swift 3 aesEncrypt function:

func aesEncrypt(key:String, iv:Array<Any>, options:Int = kCCOptionPKCS7Padding) -> String? {
    if let keyData = sha256(string:key),
        let data = self.data(using: String.Encoding.utf8),
        let cryptData    = NSMutableData(length: Int((data.count)) + kCCBlockSizeAES128) {

        let keyLength              = size_t(kCCKeySizeAES128)
        let operation: CCOperation = UInt32(kCCEncrypt)
        let algorithm:  CCAlgorithm = UInt32(kCCAlgorithmAES128)
        let options:   CCOptions   = UInt32(options)

        var numBytesEncrypted :size_t = 0

        let cryptStatus = CCCrypt(operation,
                                  algorithm,
                                  options,
                                  (keyData as NSData).bytes, keyLength,
                                  iv,
                                  (data as NSData).bytes, data.count,
                                  cryptData.mutableBytes, cryptData.length,
                                  &numBytesEncrypted)
        // ADDED PRINT STATEMENTS
        print("keyData")
        print(keyData)
        print("\(keyData as NSData)")
        print("iv")
        print(iv)
        var hex_iv = toHexString(arr: iv as! [UInt8])
        print(hex_iv)
        print("data")
        print(data)
        print("\(data as NSData)")

        print("encryption: cryptdata")
        print(cryptData)

        print("encryption: num bytes encrypted")
        print(numBytesEncrypted)

        if UInt32(cryptStatus) == UInt32(kCCSuccess) {
            cryptData.length = Int(numBytesEncrypted)
            let base64cryptString = cryptData.base64EncodedString(options: .lineLength64Characters)
            return base64cryptString
        }
        else {
            return nil
        }
    }
    return nil
}

When I try to run the following code with initial_string = "hello", I get different encrypted output strings every time.

let iv [UInt8](repeating: 0, count: 16)
let key = "sample_key"
let initial_string = "hello"

let encryptedString = initial_string.aesEncrypt(key: key, iv: iv)
print("Encrypted string")
print(encryptedString)

sample output from running code with "hello" string first time:

keyData
32 bytes
<d5a78c66 e9b3ed40 b3a92480 c732527f 1a919fdc f68957d2 b7e9218f 6221085d>
iv
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00
data
5 bytes
<68656c6c 6f>
encryption: cryptdata
<b17d67fc 26e3f316 6a2bdfbf 9d387c2d 00000000 00>
encryption: num bytes encrypted
16
Encrypted string
Optional("sX1n/Cbj8xZqK9+/nTh8LQ==")

sample output from running code with "hello" string second time:

keyData
32 bytes
<d5a78c66 e9b3ed40 b3a92480 c732527f 1a919fdc f68957d2 b7e9218f 6221085d>
iv
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00
data
5 bytes
<68656c6c 6f>
encryption: cryptdata
<01b9f69b 45deb31d eda46c2d dc9ad9e8 00000000 00>
encryption: num bytes encrypted
16
Encrypted string
Optional("Abn2m0Xesx3tpGwt3JrZ6A==")

Can you tell me why the output is different every time for the same key, iv, and string? Thanks!


问:
How to iterate through a global array and return user input
I am trying to build a news site using the guardian api and search this api using user input to return the webTitle attribute for each matching element. I know simply appending user input into the ajax call would be a simpler method of completing this task but I'm looking for a bit of a challenge so I decided I could assign the ajax response to a global array and iterate through that to find the user input but I am having trouble iterating through the array.

The code for the global array and ajax call is here;

```<code>var searchQuery=[];

                $.ajax({
                    url: 'https://content.guardianapis.com/search?&api-key=xxxx',
                    async: true,
                    dataType: "json",
                    success: function(data){
                        searchQuery.push(data);
                    }
                });
</code>```

And this works as when outputted to the console it shows the array populated with all of the elements within the ajax call.

I am just wondering how I can then take this array, and using JQuery, iterate through it and check if any elements contain the user input from an input text box located in my application preferably when the search button is clicked, the code for which is here;

```<code><div id="search">
                            <div class="input-group col-md-12">
                                <input type="text" class="search-query form-control" placeholder="Search" id= 'userSearch' <a href="#" data-toggle="popover" title="How To Search" data-content="Enter a Key Word and Receive News Stories Associated With It"></a>
                                <span class="input-group-btn">
                                    <button class="btn btn-primary mb1 bg-blue" type="button" id="submitSearch">
                                        <span class=" glyphicon glyphicon-search"></span>
                                    </button>
                                </span>
                            </div>
</div>
</code>```

Any help with this would be greatly appreciated and I'm sure it is just my inexperience with web development giving me the issues so please don't judge me too much haha.

答:
How about this:</p>

```<code>$("#submitSearch").on("click", function(){
    var keyword = $("#userSearch").val();
    searchQuery.map(function(item){
        if(item.indexOf(keyword) != -1){
            //found, do something about it
            console.log(item);
        }
    });
});
</code>```

Body:
I am trying to build a news site using the guardian api and search this api using user input to return the webTitle attribute for each matching element. I know simply appending user input into the ajax call would be a simpler method of completing this task but I'm looking for a bit of a challenge so I decided I could assign the ajax response to a global array and iterate through that to find the user input but I am having trouble iterating through the array.

The code for the global array and ajax call is here;

var searchQuery=[];

                $.ajax({
                    url: 'https://content.guardianapis.com/search?&api-key=xxxx',
                    async: true,
                    dataType: "json",
                    success: function(data){
                        searchQuery.push(data);
                    }
                });

And this works as when outputted to the console it shows the array populated with all of the elements within the ajax call.

I am just wondering how I can then take this array, and using JQuery, iterate through it and check if any elements contain the user input from an input text box located in my application preferably when the search button is clicked, the code for which is here;

                                <input type="text" class="search-query form-control" placeholder="Search" id= 'userSearch'

                                    <button class="btn btn-primary mb1 bg-blue" type="button" id="submitSearch">

                                    </button>

Any help with this would be greatly appreciated and I'm sure it is just my inexperience with web development giving me the issues so please don't judge me too much haha.

Body:
How about this:

$("#submitSearch").on("click", function(){
    var keyword = $("#userSearch").val();
    searchQuery.map(function(item){
        if(item.indexOf(keyword) != -1){
            //found, do something about it
            console.log(item);
        }
    });
});


问:
Simplify overlapping And condition statements
I'm trying to figure out the best way to simplify conditional statements that are of the form:

```<code>if( ( A() && B() ) || ( B() && C() ) || ( C() && D() ) || .... )
{
    code
}
</code>```

The A/B/C/D/etc functions are relatively expensive, so it's not ideal that they could each be called twice.

Two alternatives I've thought of:

```<code>bool a = A();
bool b = B();
bool c = C();
bool d = D();
if( ( a && b ) || ( b && c ) || ( c && d ) || .... )
{
    code
}
</code>```

This version is not ideal because C(), D(), and any additional conditions are evaluated every time even if A() and B() were both true.  In the original version, they wouldn't have been called at all in that case.

```<code>bool b = B();
if( ( A() && b ) )
{
    code
}
else
{
    bool c = C();
    if( ( b && c ) )
    {
        code
    }
    else
    {
        bool d = D();
        if( ( c && D ) )
        {
            code
        }
        else
        {
            ...
        }
    }
}
</code>```

This version avoids any duplicate and unnecessary conditions from being evaluated, but is incredibly verbose and painful to write.

So I'm hopeful that there's some simpler but equally effective way to write it that I'm not thinking of...?

答:
```<code>bool a = A(), b, c, d;
if (((b = B()) && a) || ((c = C()) && b) || (d = D() && c) || ...) {
    // code;
}
</code>```

Here if a is false, B() is evaluated for next condition check. In the second condition, if b is false, C() is evaluated for its next condition. In this way, we can make sure every function is evaluated when needed. But for the last condition, we should use function evaluation as the second operand.

Body:
I'm trying to figure out the best way to simplify conditional statements that are of the form:

if( ( A() && B() ) || ( B() && C() ) || ( C() && D() ) || .... )
{
    code
}

The A/B/C/D/etc functions are relatively expensive, so it's not ideal that they could each be called twice.

Two alternatives I've thought of:

bool a = A();
bool b = B();
bool c = C();
bool d = D();
if( ( a && b ) || ( b && c ) || ( c && d ) || .... )
{
    code
}

This version is not ideal because C(), D(), and any additional conditions are evaluated every time even if A() and B() were both true.  In the original version, they wouldn't have been called at all in that case.

bool b = B();
if( ( A() && b ) )
{
    code
}
else
{
    bool c = C();
    if( ( b && c ) )
    {
        code
    }
    else
    {
        bool d = D();
        if( ( c && D ) )
        {
            code
        }
        else
        {
            ...
        }
    }
}

This version avoids any duplicate and unnecessary conditions from being evaluated, but is incredibly verbose and painful to write.

So I'm hopeful that there's some simpler but equally effective way to write it that I'm not thinking of...?

Body:
bool a = A(), b, c, d;
if (((b = B()) && a) || ((c = C()) && b) || (d = D() && c) || ...) {
    // code;
}

Here if a is false, B() is evaluated for next condition check. In the second condition, if b is false, C() is evaluated for its next condition. In this way, we can make sure every function is evaluated when needed. But for the last condition, we should use function evaluation as the second operand.


问:
Detect if php is called from a src?
So here's a question. Can a php script detect how it is being called? For example if it is called through  it will return an image, or if it is being called through <video> it will return video, or if it is called through <audio> it will return audio, or if it is called directly by typing in http://www.example.com/callme.php it will return some text.

The content from this callme.php would be provided through the following method:

```<code>header("Content-Disposition: attachment; "
.sprintf('filename="%s"; ', rawurlencode($_REQUEST['F']))
.sprintf("filename*=utf-8''%s", rawurlencode($_REQUEST['F'])));
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header("Content-Description: File Transfer");
flush(); // this doesn't really matter.

$fp = fopen($file, "r") or die("DEAD");
while (!feof($fp))
{
    echo fread($fp, 65536);
    flush(); // this is essential for large downloads
}
fclose($fp);
</code>```

答:
No this is not possible, at least not without some additional parameters in the URL.

Consider the following HTML

```<code><img src="/callme.php?target=img" />
</code>```

With the following PHP:

```<code>if ($_GET('target') == 'img') { ... }
</code>```

Title: Detect if php is called from a src?

Body:
So here's a question. Can a php script detect how it is being called? For example if it is called through  it will return an image, or if it is being called through <video> it will return video, or if it is called through <audio> it will return audio, or if it is called directly by typing in http://www.example.com/callme.php it will return some text.

The content from this callme.php would be provided through the following method:

header("Content-Disposition: attachment; "
.sprintf('filename="%s"; ', rawurlencode($_REQUEST['F']))
.sprintf("filename*=utf-8''%s", rawurlencode($_REQUEST['F'])));
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header("Content-Description: File Transfer");
flush(); // this doesn't really matter.

$fp = fopen($file, "r") or die("DEAD");
while (!feof($fp))
{
    echo fread($fp, 65536);
    flush(); // this is essential for large downloads
}
fclose($fp);

Body:
No this is not possible, at least not without some additional parameters in the URL.

Consider the following HTML

<img src="/callme.php?target=img" />

With the following PHP:

if ($_GET('target') == 'img') { ... }


问:
Why is generic required when all types are already defined?
The exercise was to write my own map() function over Collection (without using any functional primitives, such as reduce()). It should handle a case such as this:

```<code>func square(_ input: Int) -> Int {
            return input * input
        }
let result = input.accumulate(square) // [1,2,3] =>  [1,4,9]
</code>```

My first attempt was:

```<code>extension Collection {
    func accumulate(_ transform: (Element) -> Element) -> [Element] {

        var array: [Element] = []
        for element in self {
            array.append(transform(element))
        }
        return array
    }
}
</code>```

This works fine in a playground, but fails to build against the tests, giving an error:

```<code>Value of type '[Int]' has no member 'accumulate'
</code>```

The solution is to genericize the accumulate method:

```<code>extension Collection {
    func accumulate<T>(_ transform: (Element) -> T) -> [T] {

        var array: [T] = []
        for element in self {
            array.append(transform(element))
        }
        return array
    }
}
</code>```

I recognize that the generic version is less restrictive (doesn't require the transform to return same type), but given that the tests don't require this generality, why does the compiler?

Out of curiousity I tried:

```<code>extension Collection {
    func accumulate<Element>(_ transform: (Element) -> Element) -> [Element] {

        var array: [Element] = []
        for element in self {
            array.append(transform(element))
        }
        return array
    }
}
</code>```

which throws the fascinating build error: '(Self.Element) -> Element' is not convertible to '(Element) -> Element' at the append() statement.

So the compiler (of course) knows that the first Element is Self.Element, but doesn't treat the other Element type as the same. Why?

UPDATE:

Based on the answers, it appears that the rejection of the first version was a compiler bug, fixed in XCode 9.2 (I'm on 9.1).

But still I wondered whether in

```<code>func accumulate(_ transform: (Element) -> Element) -> [Element]
</code>```

it would see two types (Self.Element and Element) or recognize that they're the same.

So I did this test:

```<code>let arr = [1,2,3]
arr.accumulate {
    return String(describing: $0)
}
</code>```

Sure enough, got the expected error: error: cannot convert value of type 'String' to closure result type 'Int'

So the correct answer is: the compiler will treat references to Element as the same, as long as there isn't a generic type that overloads the name.

Oddly, though, this succeeds:

```<code>[1,2,3].accumulate {
    return String(describing: $0)
}
</code>```

PS. Thanks to everyone for your input! The bounty was auto-awarded.

答:
I'll focus on your second question.

```<code>func accumulate<Element>(_ transform: (Element) -> Element) -> [Element]
</code>```

The trouble with writing this signature is you've got two different types with the same name.

The first type is Element which is your generic type (the bit between the angle brackets).

The second type is Self.Element, that is, the type of the elements in your collection, declared by the protocol itself. Usually you don't have to explicitly write the Self. part, but because your generic type has the same name as this one, Swift can't tell them apart otherwise.

The difference is more obvious if you change the name of the generic type:

```<code>func accumulate<E>(_ transform: (E) -> E) -> [E]
</code>```

This is equivalent to the accumulate<Element> version — changing the name simply highlights what's actually happening.

In a more general sense, Swift will let you name your types whatever you wish. But if a types' name conflicts with another type from a different scope, then you either have to disambiguate it. If you don't disambiguate, Swift will choose the most-local match. In your function, the generic type is "most-local".

Imagine you were to define your own String type:

```<code>struct String {
  // ...
}
</code>```

This is totally valid, but if you want to then use the String type provided by the Swift standard lib, you have to disambiguate like this:

```<code>let my_string: String = String()
let swift_string: Swift.String = ""
</code>```

And this is the reason why Andrea changed the signature of the function. You need to tell the compiler which "Element" type you're referring to.

```<code>func accumulate<Element>(_ transform: (Self.Element) -> Element) -> [Element]
</code>```

In general I would advise against having a generic type match the name of another type you're using. It's just confusing for everyone.

Body:
The exercise was to write my own map() function over Collection (without using any functional primitives, such as reduce()). It should handle a case such as this:

func square(_ input: Int) -> Int {
            return input * input
        }
let result = input.accumulate(square) // [1,2,3] =>  [1,4,9]

My first attempt was:

extension Collection {
    func accumulate(_ transform: (Element) -> Element) -> [Element] {

        var array: [Element] = []
        for element in self {
            array.append(transform(element))
        }
        return array
    }
}

This works fine in a playground, but fails to build against the tests, giving an error:

Value of type '[Int]' has no member 'accumulate'

The solution is to genericize the accumulate method:

extension Collection {
    func accumulate<T>(_ transform: (Element) -> T) -> [T] {

        var array: [T] = []
        for element in self {
            array.append(transform(element))
        }
        return array
    }
}

I recognize that the generic version is less restrictive (doesn't require the transform to return same type), but given that the tests don't require this generality, why does the compiler?

Out of curiousity I tried:

extension Collection {
    func accumulate<Element>(_ transform: (Element) -> Element) -> [Element] {

        var array: [Element] = []
        for element in self {
            array.append(transform(element))
        }
        return array
    }
}

which throws the fascinating build error: '(Self.Element) -> Element' is not convertible to '(Element) -> Element' at the append() statement.

So the compiler (of course) knows that the first Element is Self.Element, but doesn't treat the other Element type as the same. Why?

UPDATE:

Based on the answers, it appears that the rejection of the first version was a compiler bug, fixed in XCode 9.2 (I'm on 9.1).

But still I wondered whether in

func accumulate(_ transform: (Element) -> Element) -> [Element]

it would see two types (Self.Element and Element) or recognize that they're the same.

So I did this test:

let arr = [1,2,3]
arr.accumulate {
    return String(describing: $0)
}

Sure enough, got the expected error: error: cannot convert value of type 'String' to closure result type 'Int'

So the correct answer is: the compiler will treat references to Element as the same, as long as there isn't a generic type that overloads the name.

Oddly, though, this succeeds:

[1,2,3].accumulate {
    return String(describing: $0)
}

PS. Thanks to everyone for your input! The bounty was auto-awarded.

Body:
I'll focus on your second question.

func accumulate<Element>(_ transform: (Element) -> Element) -> [Element]

The trouble with writing this signature is you've got two different types with the same name.

The first type is Element which is your generic type (the bit between the angle brackets).

The second type is Self.Element, that is, the type of the elements in your collection, declared by the protocol itself. Usually you don't have to explicitly write the Self. part, but because your generic type has the same name as this one, Swift can't tell them apart otherwise.

The difference is more obvious if you change the name of the generic type:

func accumulate<E>(_ transform: (E) -> E) -> [E]

This is equivalent to the accumulate<Element> version — changing the name simply highlights what's actually happening.

In a more general sense, Swift will let you name your types whatever you wish. But if a types' name conflicts with another type from a different scope, then you either have to disambiguate it. If you don't disambiguate, Swift will choose the most-local match. In your function, the generic type is "most-local".

Imagine you were to define your own String type:

struct String {
  // ...
}

This is totally valid, but if you want to then use the String type provided by the Swift standard lib, you have to disambiguate like this:

let my_string: String = String()
let swift_string: Swift.String = ""

And this is the reason why Andrea changed the signature of the function. You need to tell the compiler which "Element" type you're referring to.

func accumulate<Element>(_ transform: (Self.Element) -> Element) -> [Element]

In general I would advise against having a generic type match the name of another type you're using. It's just confusing for everyone.


问:
Creating and installing Conda packages into Virtual Envs
I'm working on packaging up a suite of tools that can be installed in different environments, and I've run into many problems with dependencies, which are an issue since this package will be installed in air-gapped environments.

The package will be installed via Anaconda, and I have provided the installation script. In order to create the package, I ran the following command:

```<code>conda metapackage toolkit_bundle 0.0.1 --dependencies r-essentials tensorflow gensim spacy r-ggplot2 r-plotly r-dplyr r-rjson r-tm r-reshape2 r-shiny r-sparklyr r-slam r-nlp r-cluster r-ggvis r-plyr r-tidyr r-zoo r-magrittr r-xtable r-htmlwidgets r-formattable r-highcharter --summary "Toolkit Bundle"
</code>```

This produced a tar.bzip2 file that I held on to and tried to install via the conda command

```<code>conda install toolkit_bundle.tar.bz2
</code>```

The command seemed to run successfully, but I was unsuccessful in importing the modules in Python. I also tried creating a virtual conda environment and importing the package.

```<code>conda create -n myenv toolkit_bundle-0.0.1.tar.bz2
</code>```

There was no error, but none of the modules were able to be imported either.

Am I missing a step in this process, or is my thought process flawed?

Update:
It looks like my thinking was pretty flawed. A quick skim of the conda metapackage command documentation revealed the following:

```<code>Tool for building conda metapackages.  A metapackage is a package  with no  files,  only  metadata.  They are typically used to collect several packages together into a single package via dependencies.
</code>```

So my initial understanding was incorrect, and the package only contains metadata. Are there any other ideas for creating packages with dependencies resolved that can be installed in an air gapped environment?

答:
I think you want to look at the command conda build for making packages, which just requires writing an appropriate meta.yaml file containing the dependencies, along with some other build parameters.  There is good documentation for doing so on the conda website: https://conda.io/docs/user-guide/tasks/build-packages  and there is a repo of examples.

If you have a working PIP package, you can also auto-generate a conda package recipe using conda skeleton.

Once you have built a set of packages locally, you can use the --use-local option to conda install to install from your local repo, with no need for an internet connection (as long as the packages for all the dependencies are in your local repo).

Body:
I'm working on packaging up a suite of tools that can be installed in different environments, and I've run into many problems with dependencies, which are an issue since this package will be installed in air-gapped environments.

The package will be installed via Anaconda, and I have provided the installation script. In order to create the package, I ran the following command:

conda metapackage toolkit_bundle 0.0.1 --dependencies r-essentials tensorflow gensim spacy r-ggplot2 r-plotly r-dplyr r-rjson r-tm r-reshape2 r-shiny r-sparklyr r-slam r-nlp r-cluster r-ggvis r-plyr r-tidyr r-zoo r-magrittr r-xtable r-htmlwidgets r-formattable r-highcharter --summary "Toolkit Bundle"

This produced a tar.bzip2 file that I held on to and tried to install via the conda command

conda install toolkit_bundle.tar.bz2

The command seemed to run successfully, but I was unsuccessful in importing the modules in Python. I also tried creating a virtual conda environment and importing the package.

conda create -n myenv toolkit_bundle-0.0.1.tar.bz2

There was no error, but none of the modules were able to be imported either.

Am I missing a step in this process, or is my thought process flawed?

Update:
It looks like my thinking was pretty flawed. A quick skim of the conda metapackage command documentation revealed the following:

Tool for building conda metapackages.  A metapackage is a package  with no  files,  only  metadata.  They are typically used to collect several packages together into a single package via dependencies.

So my initial understanding was incorrect, and the package only contains metadata. Are there any other ideas for creating packages with dependencies resolved that can be installed in an air gapped environment?


问:
AngularJS + Grunt ngAnnotate and single quote
I'm trying to minify my app but can't go over Grunt ngAnnotate as it throws an error

error: couldn't process source due to parse error
    Error parsing regular expression: Invalid regular expression: /[A-Za-z0-9!#_\?:&.- ']/: Range out of order in character class (3:22)

on a directive which looks like

```<code>myApp.directive('allowedChars', function() {

  var EMAIL_REGEXP = /[A-Za-z0-9!#_\?:&\.- ']/;

  return {
    require: 'ngModel',
    restrict: '',
    link: function(scope, elm, attrs, ctrl) {
      // only apply the validator if ngModel is present and Angular has added the allowed characters validator
      if (ctrl && ctrl.$validators.chars) {

        // this will overwrite the default Angular email validator
        ctrl.$validators.email = function(modelValue) {
          return ctrl.$isEmpty(modelValue) || EMAIL_REGEXP.test(modelValue);
        };
      }
    }
  };
});
</code>```

Gruntfile.js looks like

```<code>module.exports = function(grunt) {
    //grunt wrapper function
    grunt.initConfig({
        pkg: grunt.file.readJSON('package.json'),
        ngAnnotate: {
            options: {
                singleQuotes: true
            },
            app: {
          files: [
            {
              expand: true,     // Enable dynamic expansion.
              cwd: './app/js/controllers/',      // Src matches are relative to this path.
              src: ['**/*.js'], // Actual pattern(s) to match.
              dest: './app/js/build/controllers',   // Destination path prefix.
              ext: '.min.js',   // Dest filepaths will have this extension.
              extDot: 'first'   // Extensions in filenames begin after the first dot
            },
            {
              expand: true,     // Enable dynamic expansion.
              cwd: './app/js/services/',      // Src matches are relative to this path.
              src: ['**/*.js'], // Actual pattern(s) to match.
              dest: './app/js/build/services',   // Destination path prefix.
              ext: '.min.js',   // Dest filepaths will have this extension.
              extDot: 'first'   // Extensions in filenames begin after the first dot
            },
            {
              expand: true,     // Enable dynamic expansion.
              cwd: './app/js/directives/',      // Src matches are relative to this path.
              src: ['**/*.js'], // Actual pattern(s) to match.
              dest: './app/js/build/directives',   // Destination path prefix.
              ext: '.min.js',   // Dest filepaths will have this extension.
              extDot: 'first'   // Extensions in filenames begin after the first dot
            },
          ],
            }
        },
    });

    //load grunt tasks
    grunt.loadNpmTasks('grunt-contrib-concat');
    grunt.loadNpmTasks('grunt-contrib-uglify');
    grunt.loadNpmTasks('grunt-ng-annotate');

    //register grunt default task
    grunt.registerTask('default', ['ngAnnotate', 'concat', 'uglify']);
}
</code>```

答:
As the error suggests, your regular expression is invalid. Try escaping some of the special characters. Like this:

```<code>var EMAIL_REGEXP = /[A-Za-z0-9\!\#\_\?\:\&\.\- \']/;
</code>```

That should allow ngAnnotate to compile.

Body:
I'm trying to minify my app but can't go over Grunt ngAnnotate as it throws an error

error: couldn't process source due to parse error
    Error parsing regular expression: Invalid regular expression: /[A-Za-z0-9!#_\?:&.- ']/: Range out of order in character class (3:22)

on a directive which looks like

myApp.directive('allowedChars', function() {

  var EMAIL_REGEXP = /[A-Za-z0-9!#_\?:&\.- ']/;

  return {
    require: 'ngModel',
    restrict: '',
    link: function(scope, elm, attrs, ctrl) {
      // only apply the validator if ngModel is present and Angular has added the allowed characters validator
      if (ctrl && ctrl.$validators.chars) {

        // this will overwrite the default Angular email validator
        ctrl.$validators.email = function(modelValue) {
          return ctrl.$isEmpty(modelValue) || EMAIL_REGEXP.test(modelValue);
        };
      }
    }
  };
});

Gruntfile.js looks like

module.exports = function(grunt) {
    //grunt wrapper function
    grunt.initConfig({
        pkg: grunt.file.readJSON('package.json'),
        ngAnnotate: {
            options: {
                singleQuotes: true
            },
            app: {
          files: [
            {
              expand: true,     // Enable dynamic expansion.
              cwd: './app/js/controllers/',      // Src matches are relative to this path.
              src: ['**/*.js'], // Actual pattern(s) to match.
              dest: './app/js/build/controllers',   // Destination path prefix.
              ext: '.min.js',   // Dest filepaths will have this extension.
              extDot: 'first'   // Extensions in filenames begin after the first dot
            },
            {
              expand: true,     // Enable dynamic expansion.
              cwd: './app/js/services/',      // Src matches are relative to this path.
              src: ['**/*.js'], // Actual pattern(s) to match.
              dest: './app/js/build/services',   // Destination path prefix.
              ext: '.min.js',   // Dest filepaths will have this extension.
              extDot: 'first'   // Extensions in filenames begin after the first dot
            },
            {
              expand: true,     // Enable dynamic expansion.
              cwd: './app/js/directives/',      // Src matches are relative to this path.
              src: ['**/*.js'], // Actual pattern(s) to match.
              dest: './app/js/build/directives',   // Destination path prefix.
              ext: '.min.js',   // Dest filepaths will have this extension.
              extDot: 'first'   // Extensions in filenames begin after the first dot
            },
          ],
            }
        },
    });

    //load grunt tasks
    grunt.loadNpmTasks('grunt-contrib-concat');
    grunt.loadNpmTasks('grunt-contrib-uglify');
    grunt.loadNpmTasks('grunt-ng-annotate');

    //register grunt default task
    grunt.registerTask('default', ['ngAnnotate', 'concat', 'uglify']);
}

Body:
As the error suggests, your regular expression is invalid. Try escaping some of the special characters. Like this:

var EMAIL_REGEXP = /[A-Za-z0-9\!\#\_\?\:\&\.\- \']/;

That should allow ngAnnotate to compile.


问:
First, Second and Third largest number from user provided integer array
In this program, size of array and array elements are taken from user.

This code passes all the cases I have tried but not able to pass, where size of array is 4 and elements are {5,5,5,2}

Here output should be 5 5 5

But I am getting 2 2 5

I am able to figure out the problem is in this part.

```<code>else if((max1 == max2 && max2 == max3 && max1 == max3) && x[i] < max2)
                {
                    max2 = x[i];
                    if(max2 < max3)
                    {
                        max3 = max2;
                    }
                }
</code>```

How can I solve this problem using array only. Don't need solution in collections.

```<code>import java.util.*;
    class ThirdLargest
    {
        public static void main(String[] args)
        {
            Scanner sc = new Scanner(System.in);
            System.out.println("Enter size for array: ");
            int size = sc.nextInt();
            int[] x = new int[size];
            for(int i = 0; i < x.length; i++)
            {
                System.out.println("Enter elements for array: ");
                x[i] = sc.nextInt();
            }
            System.out.println("Array is: ");
            for(int i = 0; i < x.length; i++)
            {
                System.out.print(x[i] +"    ");
            }
            System.out.println();
            if (x.length >= 3)
            {
                int max1 = x[0], max2 = x[0], max3 = x[0];
            for (int i = 1; i < x.length; i++)
            {
                    if(x[i] > max1)
                    {
                        max3 = max2;
                        max2 = max1;
                        max1 = x[i];
                    }
                    else if(x[i] > max2)
                    {
                        max3 = max2;
                        max2 = x[i];
                    }
                    else if (x[i] > max3)
                    {
                        max3 = x[i];
                    }
                    else if((max1 == max2 && max2 == max3 && max1 == max3) && x[i] < max2)
                    {
                        max2 = x[i];
                        if(max2 < max3)
                        {
                            max3 = max2;
                        }
                    }
                    else if(max2 == max3 && x[i] < max3)
                        {
                            max3 = x[i];
                        }
                }
            System.out.println("3rd, 2nd and 1st maximum: " + max3 +"   "+max2+"    "+max1);
            }
            else
            {
                System.out.println("Array size is short");
            }
        }
    }
</code>```

答:
This code is not human readable, you will stuck in this for hours trying to debug.
First, you need to split this code to methods, don't try to do all thing in one method. You need to decouple logic of receiving int array from user from logic that doing max values calculation. Example: </p>

```<code>public int[] threeMaximumValuesFrom(int[] array) {
    int[] sorted = sortArray(array);
    int[] result = {
        sorted[array.length - 1];
        sorted[array.length - 2];
        sorted[array.length - 3];
    }
    return result;
}

private int[] sortArray(int[] array) {
    //when you don't want to use jdk sort implement your own
    //in any way other parts of code should knows nothing about it
    Arrays.sort(array);
    return array;
}
</code>```

Body:
In this program, size of array and array elements are taken from user.

This code passes all the cases I have tried but not able to pass, where size of array is 4 and elements are {5,5,5,2}

Here output should be 5 5 5

But I am getting 2 2 5

I am able to figure out the problem is in this part.

else if((max1 == max2 && max2 == max3 && max1 == max3) && x[i] < max2)
                {
                    max2 = x[i];
                    if(max2 < max3)
                    {
                        max3 = max2;
                    }
                }

How can I solve this problem using array only. Don't need solution in collections.

import java.util.*;
    class ThirdLargest
    {
        public static void main(String[] args)
        {
            Scanner sc = new Scanner(System.in);
            System.out.println("Enter size for array: ");
            int size = sc.nextInt();
            int[] x = new int[size];
            for(int i = 0; i < x.length; i++)
            {
                System.out.println("Enter elements for array: ");
                x[i] = sc.nextInt();
            }
            System.out.println("Array is: ");
            for(int i = 0; i < x.length; i++)
            {
                System.out.print(x[i] +"    ");
            }
            System.out.println();
            if (x.length >= 3)
            {
                int max1 = x[0], max2 = x[0], max3 = x[0];
            for (int i = 1; i < x.length; i++)
            {
                    if(x[i] > max1)
                    {
                        max3 = max2;
                        max2 = max1;
                        max1 = x[i];
                    }
                    else if(x[i] > max2)
                    {
                        max3 = max2;
                        max2 = x[i];
                    }
                    else if (x[i] > max3)
                    {
                        max3 = x[i];
                    }
                    else if((max1 == max2 && max2 == max3 && max1 == max3) && x[i] < max2)
                    {
                        max2 = x[i];
                        if(max2 < max3)
                        {
                            max3 = max2;
                        }
                    }
                    else if(max2 == max3 && x[i] < max3)
                        {
                            max3 = x[i];
                        }
                }
            System.out.println("3rd, 2nd and 1st maximum: " + max3 +"   "+max2+"    "+max1);
            }
            else
            {
                System.out.println("Array size is short");
            }
        }
    }

Body:
This code is not human readable, you will stuck in this for hours trying to debug.
First, you need to split this code to methods, don't try to do all thing in one method. You need to decouple logic of receiving int array from user from logic that doing max values calculation. Example:

public int[] threeMaximumValuesFrom(int[] array) {
    int[] sorted = sortArray(array);
    int[] result = {
        sorted[array.length - 1];
        sorted[array.length - 2];
        sorted[array.length - 3];
    }
    return result;
}

private int[] sortArray(int[] array) {
    //when you don't want to use jdk sort implement your own
    //in any way other parts of code should knows nothing about it
    Arrays.sort(array);
    return array;
}


问:
Jest - Unexpected token import
I'm trying to learn how to do unit testing with React and jest. I've run into the following error:

Unexpected token import

Here are my babel presets:

```<code>{
  "presets": ["es2015", "stage-0", "react"],
  "env": {
    "test": {
        "plugins": ["transform-es2015-modules-commonjs"]
    }
}
}
</code>```

Here is the file i'm trying to test:

```<code>import jest from 'jest';
import React from 'react';
import { shallow } from 'enzyme';
import Step from '../src/components/step.js';

const wrapper = shallow(<Step />);
wrapper.find('a').simulate('click', { preventDefault() {} });
</code>```

and here is my package.json:

```<code>{
  "name": "react-simple-boilerplate",
  "version": "1.0.0",
  "description": "Simple and lightweight Boilerplate for ReactJS projects",
  "scripts": {
    "lint": "eslint src",
    "start": "node server.js",
    "test": "jest"
  },
  "devDependencies": {
    "babel-core": "^6.24.1",
    "babel-loader": "^7.0.0",
    "babel-plugin-transform-es2015-modules-commonjs": "^6.26.0",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-react": "^6.24.1",
    "babel-preset-stage-0": "^6.24.1",
    "css-loader": "^0.28.0",
    "enzyme": "^3.2.0",
    "enzyme-adapter-react-16": "^1.1.0",
    "eslint": "^3.19.0",
    "eslint-plugin-react": "^6.10.3",
    "jest": "^21.2.1",
    "node-sass": "^4.5.2",
    "react-addons-test-utils": "^15.6.2",
    "sass-loader": "^6.0.3",
    "style-loader": "^0.16.1",
    "webpack": "^2.4.1",
    "webpack-dev-server": "^2.4.4"
  },
  "dependencies": {
    "babel-loader": "^7.0.0",
    "react": "^15.5.4",
    "react-dom": "^15.5.4"
  },
  "main": "server.js"
}
</code>```

Have no idea why its giving me this message?

答:
I'm pretty sure you need to add your babel presets to test as well, jest sets the env variable to test.

So...

```<code>"test": {
    "plugins": ["transform-es2015-modules-commonjs"],
    "presets": ["es2015", "react", "stage-0"]
}
</code>```

Title: Jest - Unexpected token import

Body:
I'm trying to learn how to do unit testing with React and jest. I've run into the following error:

Unexpected token import

Here are my babel presets:

{
  "presets": ["es2015", "stage-0", "react"],
  "env": {
    "test": {
        "plugins": ["transform-es2015-modules-commonjs"]
    }
}
}

Here is the file i'm trying to test:

import jest from 'jest';
import React from 'react';
import { shallow } from 'enzyme';
import Step from '../src/components/step.js';

const wrapper = shallow(<Step />);
wrapper.find('a').simulate('click', { preventDefault() {} });

and here is my package.json:

{
  "name": "react-simple-boilerplate",
  "version": "1.0.0",
  "description": "Simple and lightweight Boilerplate for ReactJS projects",
  "scripts": {
    "lint": "eslint src",
    "start": "node server.js",
    "test": "jest"
  },
  "devDependencies": {
    "babel-core": "^6.24.1",
    "babel-loader": "^7.0.0",
    "babel-plugin-transform-es2015-modules-commonjs": "^6.26.0",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-react": "^6.24.1",
    "babel-preset-stage-0": "^6.24.1",
    "css-loader": "^0.28.0",
    "enzyme": "^3.2.0",
    "enzyme-adapter-react-16": "^1.1.0",
    "eslint": "^3.19.0",
    "eslint-plugin-react": "^6.10.3",
    "jest": "^21.2.1",
    "node-sass": "^4.5.2",
    "react-addons-test-utils": "^15.6.2",
    "sass-loader": "^6.0.3",
    "style-loader": "^0.16.1",
    "webpack": "^2.4.1",
    "webpack-dev-server": "^2.4.4"
  },
  "dependencies": {
    "babel-loader": "^7.0.0",
    "react": "^15.5.4",
    "react-dom": "^15.5.4"
  },
  "main": "server.js"
}

Have no idea why its giving me this message?

Body:
I'm pretty sure you need to add your babel presets to test as well, jest sets the env variable to test.

So...

"test": {
    "plugins": ["transform-es2015-modules-commonjs"],
    "presets": ["es2015", "react", "stage-0"]
}


问:
Kotlin Extension Any?.toString()
I have been trying to use extension functions in Kotlin.

```<code>class ExtensionExample() {

   var name: String? = null

   fun Any?.toString() : String {

       if (this == null) {
           return "Value is null"
       }

       return "Value is not null"
   }
}
</code>```

When I print the name variable like below

```<code>println(ExtensionExample().name.toString())
</code>```

It should print like

```<code>Value is null
</code>```

But it doesn't print like I expected. It only prints null.

Can someone explain please?

答:
Defining an extension function inside a class:

If you want to leave the definition of toString() within ExtensionExample, you can only use it from there:

```<code>class ExtensionExample() {
    var name: String? = null

    // uses the toString() extension function defined in ExtensionExample
    fun useToString() = name.toString()

    fun Any?.toString(): String {

        if (this == null) {
            return "inside: Value is null"
        }
        return "inside: Value is not null"
    }
}
</code>```

This

```<code>// uses the version of toString() defined in the Kotlin Standard library
println(ExtensionExample().name.toString())

// uses the inside version of toString()
println(ExtensionExample().useToString())
</code>```

will print

null

  inside: Value is null

Defining an extension function outside a class:

But if you want to use it outside, you have to move it outside:

```<code>class ExtensionExample() {
    var name: String? = null

    // uses the toString() extension function defined in ExtensionExample
    fun useToString() = name.toString()

    fun Any?.toString(): String {

        if (this == null) {
            return "inside: Value is null"
        }
        return "inside: Value is not null"
    }
}

fun Any?.toString(): String {

    if (this == null) {
        return "outside: Value is null"
    }
    return "outside: Value is not null"
}
</code>```

This

```<code>// uses the outside version of toString() which overrides the one from the Kotlin Standard library
println(ExtensionExample().name.toString())

// uses the inside version of toString()
println(ExtensionExample().useToString())
</code>```

will print:

outside: Value is null

  inside: Value is null

Title: Kotlin Extension Any?.toString()

Body:
I have been trying to use extension functions in Kotlin.

class ExtensionExample() {

   var name: String? = null

   fun Any?.toString() : String {

       if (this == null) {
           return "Value is null"
       }

       return "Value is not null"
   }
}

When I print the name variable like below

println(ExtensionExample().name.toString())

It should print like

Value is null

But it doesn't print like I expected. It only prints null.

Can someone explain please?

Body:
Defining an extension function inside a class:

If you want to leave the definition of toString() within ExtensionExample, you can only use it from there:

class ExtensionExample() {
    var name: String? = null

    // uses the toString() extension function defined in ExtensionExample
    fun useToString() = name.toString()

    fun Any?.toString(): String {

        if (this == null) {
            return "inside: Value is null"
        }
        return "inside: Value is not null"
    }
}

This

// uses the version of toString() defined in the Kotlin Standard library
println(ExtensionExample().name.toString())

// uses the inside version of toString()
println(ExtensionExample().useToString())

will print

null

  inside: Value is null

Defining an extension function outside a class:

But if you want to use it outside, you have to move it outside:

class ExtensionExample() {
    var name: String? = null

    // uses the toString() extension function defined in ExtensionExample
    fun useToString() = name.toString()

    fun Any?.toString(): String {

        if (this == null) {
            return "inside: Value is null"
        }
        return "inside: Value is not null"
    }
}

fun Any?.toString(): String {

    if (this == null) {
        return "outside: Value is null"
    }
    return "outside: Value is not null"
}

This

// uses the outside version of toString() which overrides the one from the Kotlin Standard library
println(ExtensionExample().name.toString())

// uses the inside version of toString()
println(ExtensionExample().useToString())

will print:

outside: Value is null

  inside: Value is null


问:
How to insert a row in an HTML table body in JavaScript
I have an HTML table with a header and a footer:

```<code><table id="myTable">
    <thead>
        <tr>
            <th>My Header</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>aaaaa</td>
        </tr>
    </tbody>
    <tfoot>
        <tr>
            <td>My footer</td>
        </tr>
    <tfoot>
</table>
</code>```

I am trying to add a row in tbody with the following:

```<code>myTable.insertRow(myTable.rows.length - 1);
</code>```

but the row is added in the tfoot section.

How do I insert tbody?

答:
Basic approach:

This should add HTML-formatted content and show the newly added row.

```<code>var myHtmlContent = "<h3>hello</h3>"
var tableRef = document.getElementById('myTable').getElementsByTagName('tbody')[0];

var newRow = tableRef.insertRow(tableRef.rows.length);
newRow.innerHTML = myHtmlContent;
</code>```

Body:
I have an HTML table with a header and a footer:

            My Header

            aaaaa

            My footer

I am trying to add a row in tbody with the following:

myTable.insertRow(myTable.rows.length - 1);

but the row is added in the tfoot section.

How do I insert tbody?

Body:
Basic approach:

This should add HTML-formatted content and show the newly added row.

var myHtmlContent = "<h3>hello</h3>"
var tableRef = document.getElementById('myTable').getElementsByTagName('tbody')[0];

var newRow = tableRef.insertRow(tableRef.rows.length);
newRow.innerHTML = myHtmlContent;


问:
Is using regex for a request handler in PHP bad?
I am working on a request handler to route every page call through my index page and have SEO friendly urls.

domain.com/account/settings

this would be easy to map to the correct page but some are more complex when there becomes an ID number or a page number in the uri.

So I see some people will use things like preg_match and cycle through an array of patterns ->  uri to get a match which is nice for when paging and id's come into play but from my experience, it seems like running preg_match on an array of say 20 items on every page load is not good for performace.

Please tell me your thought on this?

答:
On my site I just have a few different rewrite rules, which I think works well:</p>

```<code>RewriteRule ^(main|home|daily_photo_mockup|games|sporktris(?:_web)?|nangooni|contact|source|admin|edit_photos?|edit_galleries|edit_gallery)(?:_(fr|sv))?$ index.pl?page=$1&lang=$2
RewriteRule ^(snow_flakes|photography)(\d+)?(?:_p(\d+))?(?:_(fr|sv))?$ index.pl?page=$1&subpage=$2&img=$3&lang=$4
</code>```

Body:
On my site I just have a few different rewrite rules, which I think works well:

RewriteRule ^(main|home|daily_photo_mockup|games|sporktris(?:_web)?|nangooni|contact|source|admin|edit_photos?|edit_galleries|edit_gallery)(?:_(fr|sv))?$ index.pl?page=$1&lang=$2
RewriteRule ^(snow_flakes|photography)(\d+)?(?:_p(\d+))?(?:_(fr|sv))?$ index.pl?page=$1&subpage=$2&img=$3&lang=$4