问:
how can i deploy the jar file in remote server
In my local machine, i just running the java application in eclipse and working perfectly.

But in my staging machine,  i  have a spring boot application and running in the centos server, which i am accessing by putty

when i tried running the command

```<code>> mvn clean package -DskipTests
</code>```

after the above step, what the next step, i need to do

Actually i did was,

nohup java -jar target/cs.jar &

so that, jar was created in the target folder. Then when i tried to hit the endpoint from the postman its not working

答:
As you said there might be some internet issue on the Staging Server. Maven may try to get dependencies from internet, but since it is not able to get to internet it is hanging.

Can you try to use following command on your linux server

```<code>$wget http://www.google.com
</code>```

if it works correctly then you know that internet is there on that machine. Your maven should work then .

If not then, I would suggest build the whole thing on your local and transfer the build files to the server.  In the server you can just execute

```<code>$ java -jar target/myproject-0.0.1-SNAPSHOT.jar
</code>```

I am assuming that you can package the whole application in a jar file.
To move the jar file from windows machine to server machine you can use winscp tool.

Body:
In my local machine, i just running the java application in eclipse and working perfectly.

But in my staging machine,  i  have a spring boot application and running in the centos server, which i am accessing by putty

when i tried running the command

> mvn clean package -DskipTests

after the above step, what the next step, i need to do

Actually i did was,

nohup java -jar target/cs.jar &

so that, jar was created in the target folder. Then when i tried to hit the endpoint from the postman its not working

Body:
As you said there might be some internet issue on the Staging Server. Maven may try to get dependencies from internet, but since it is not able to get to internet it is hanging.

Can you try to use following command on your linux server

$wget http://www.google.com

if it works correctly then you know that internet is there on that machine. Your maven should work then .

If not then, I would suggest build the whole thing on your local and transfer the build files to the server.  In the server you can just execute

$ java -jar target/myproject-0.0.1-SNAPSHOT.jar

I am assuming that you can package the whole application in a jar file.
To move the jar file from windows machine to server machine you can use winscp tool.


来源: stackexchange

问:
How Run Wordpress Theme with Netbeans?
Please I need some guides or tuto showing how " run and import " a Theme Based on wordpress in Netbeans.

Thanks a lot.

答:
You can edit a installed WordPress theme in Netbeans using the new project options.

(New Project-->PHP-->PHP Application from Remote Server)

First, the theme must be installed on a webserver that supports mysql, php, and HTTPS. (https://wordpress.org/about/requirements/)

ContentLicense: CC BY-SA 3.0

Title: How Run Wordpress Theme with Netbeans?


问:
Making unambiguous concatenate when retrieving info for email
The aim is to check individual worksheets for a list of dates in a range, and then send an email listing these dates to an email address located in the sheet.

The current code concatenates the dates in the current sheet as well as the dates on the previous sheet, instead of just the dates found on this sheet.

I'm struggling to make it uni-vocal,  tried putting "ws." before each aCell instruction but get compile error.

Sub Mail_Outlook()

    Dim ws As Worksheet
    Dim wsName As Variant

    Dim OutApp As Object
    Dim OutMail As Object
    Dim cell As Range
    Dim strbody As String
    Dim string1 As String
    Dim aCell As Range
    Dim i As Integer
    i = 0

    For Each wsName In Array("sheet1", "sheet2", "sheet3")

        Set ws = Worksheets(wsName)

        'retrieve all missing dates
        For Each aCell In ws.Range("Aa1:Aa1000")

            If aCell.Value <> "" Then
                i = i + 1
                If i <> 1 Then
                    string1 = string1 & ",   " & aCell.Value

                Else
                    string1 = aCell.Value
                End If

            End If

        Next

        'send email
        Set OutApp = CreateObject("Outlook.Application")
        Set OutMail = OutApp.CreateItem(0)

        strbody = "Good day " & ws.Range("E3").Cells & vbNewLine & vbNewLine & _
          "" & vbNewLine & vbNewLine & _
          "" & vbNewLine & vbNewLine & _
          string1 & vbNewLine & vbNewLine & vbNewLine & vbNewLine & _
          "(This is an automated message)" & vbNewLine & vbNewLine & _
          "Best regards" & vbNewLine & vbNewLine & _

        On Error Resume Next

        With OutMail
            .To = ws.Range("E5").Text
            .CC = ""
            .BCC = ""
            .Subject = ""
            .Body = strbody
            'You can add a file like this
            '.Attachments.Add ("C:\test.txt")
            .Display   'or use .Send
        End With

        On Error GoTo 0

        Set OutMail = Nothing
        Set OutApp = Nothing

    Next

End Sub
```

From the OP's comments:

code as is produces no errors, but e.g. the second email contains the string for the first sheet and second sheet, rather than just the second sheet.

答:
Zero the string before going into the second iteration of the loop.</p>

```<code>For Each wsName In Array("sheet1", "sheet2", "sheet3")

    Set ws = Worksheets(wsName)
    string1  = vbNullString    'reset string1 to a zero-length string for each ws

     'retrieve all missing dates
     For Each aCell In ws.Range("Aa1:Aa1000")
       'all the rest of the concatenation code
     next aCell

    'all the rest of the email code
Next wsName
</code>```

ContentLicense: CC BY-SA 4.0

Body:
The aim is to check individual worksheets for a list of dates in a range, and then send an email listing these dates to an email address located in the sheet.

The current code concatenates the dates in the current sheet as well as the dates on the previous sheet, instead of just the dates found on this sheet.

I'm struggling to make it uni-vocal,  tried putting "ws." before each aCell instruction but get compile error.

Sub Mail_Outlook()

    Dim ws As Worksheet
    Dim wsName As Variant

    Dim OutApp As Object
    Dim OutMail As Object
    Dim cell As Range
    Dim strbody As String
    Dim string1 As String
    Dim aCell As Range
    Dim i As Integer
    i = 0

    For Each wsName In Array("sheet1", "sheet2", "sheet3")

        Set ws = Worksheets(wsName)

        'retrieve all missing dates
        For Each aCell In ws.Range("Aa1:Aa1000")

            If aCell.Value <> "" Then
                i = i + 1
                If i <> 1 Then
                    string1 = string1 & ",   " & aCell.Value

                Else
                    string1 = aCell.Value
                End If

            End If

        Next

        'send email
        Set OutApp = CreateObject("Outlook.Application")
        Set OutMail = OutApp.CreateItem(0)

        strbody = "Good day " & ws.Range("E3").Cells & vbNewLine & vbNewLine & _
          "" & vbNewLine & vbNewLine & _
          "" & vbNewLine & vbNewLine & _
          string1 & vbNewLine & vbNewLine & vbNewLine & vbNewLine & _
          "(This is an automated message)" & vbNewLine & vbNewLine & _
          "Best regards" & vbNewLine & vbNewLine & _

        On Error Resume Next

        With OutMail
            .To = ws.Range("E5").Text
            .CC = ""
            .BCC = ""
            .Subject = ""
            .Body = strbody
            'You can add a file like this
            '.Attachments.Add ("C:\test.txt")
            .Display   'or use .Send
        End With

        On Error GoTo 0

        Set OutMail = Nothing
        Set OutApp = Nothing

    Next

End Sub

From the OP's comments:

code as is produces no errors, but e.g. the second email contains the string for the first sheet and second sheet, rather than just the second sheet.

Body:
Zero the string before going into the second iteration of the loop.

For Each wsName In Array("sheet1", "sheet2", "sheet3")

    Set ws = Worksheets(wsName)
    string1  = vbNullString    'reset string1 to a zero-length string for each ws

     'retrieve all missing dates
     For Each aCell In ws.Range("Aa1:Aa1000")
       'all the rest of the concatenation code
     next aCell

    'all the rest of the email code
Next wsName


问:
Create linux shell script files in C# (which does not need dos2unix )
I use C# to create shell scripts to automate my tasks in Linux.
In order to do this, I use below structure:

```<code>List<string> batchFileLines = new List<string>();
batchFileLines.Add("shell command 1");
batchFileLines.Add("shell command 2");
System.IO.File.WriteAllLines(shellBatchFileName, batchFileLines.ToArray());
</code>```

However when I move my file to linux due to EOL difference in windows and linux (which a fixed suggested here for linux), EOLs in shell file need to be corrected with dos2unix command.
I want to know how can I manipulate my file in C# so it is not required to execute dos2unix.

What would be the way to replace new lines with linux format with minimum effort?

答:
Using this answer, I should change

```<code>System.IO.File.WriteAllLines(shellBatchFileName, batchFileLines.ToArray());
</code>```

to

```<code>System.IO.File.WriteAllText(shellBatchFileName, string.Join("\n", batchFileLines.ToArray()));
</code>```

The output file will not require dos2unix anymore.

Body:
I use C# to create shell scripts to automate my tasks in Linux.
In order to do this, I use below structure:

List<string> batchFileLines = new List<string>();
batchFileLines.Add("shell command 1");
batchFileLines.Add("shell command 2");
System.IO.File.WriteAllLines(shellBatchFileName, batchFileLines.ToArray());

However when I move my file to linux due to EOL difference in windows and linux (which a fixed suggested here for linux), EOLs in shell file need to be corrected with dos2unix command.
I want to know how can I manipulate my file in C# so it is not required to execute dos2unix.

What would be the way to replace new lines with linux format with minimum effort?

Body:
Using this answer, I should change

System.IO.File.WriteAllLines(shellBatchFileName, batchFileLines.ToArray());

to

System.IO.File.WriteAllText(shellBatchFileName, string.Join("\n", batchFileLines.ToArray()));

The output file will not require dos2unix anymore.


问:
Collectd not collecting data when changed to "High Counter" or HC OIDs in snmp plugin config
I am playing with collectd. Evertying works fine until I decided to use "ifHCInOctets" instead of "ifInOctets". Here is my SNMP plugin config.

```<code><Plugin snmp>
    <Data "std_traffic_hc">
            Type "if_octets"
            Table true
#           Instance "IF-MIB::ifDescr"
            Instance "IF-MIB::ifName"
#           Values "IF-MIB::ifInOctets" "IF-MIB::ifOutOctets"
            Values "IF-MIB::ifHCInOctets" "IF-MIB::ifHCOutOctets"
    </Data>
    <Host "ABCDESW01-01">
            Address "10.0.3.131"
            Version 1
            Community "xxx"
            Collect "std_traffic_hc"
            Interval 60
    </Host>
</Plugin>
</code>```

I have also tried ifDescr and ifName in the "Instance" directive and that did not make a difference. Either one works for the regular OID but not the HC OID.

I used tcpdump but I don't see collectd ever tried to send snmp traffic to the HC OID. I do see the snmp traffic for the Instance OID.

I have also used snmpwalk to confirm that my switch (HP) supports the OID:

```<code># snmpwalk -v2c -cxxx 10.0.3.131 IF-MIB::ifHCInOctets
IF-MIB::ifHCInOctets.1 = Counter64: 0
IF-MIB::ifHCInOctets.2 = Counter64: 356053022
</code>```

Where did I do wrong?

Thank you!

答:
Well High Counter OID aren't usable within SNMP v1 so i would guess that that's the problem here.

You are correctly manually requesting the OID in Version 2c on the CLI, but the collectd configuration is set to "Version 1"

Body:
I am playing with collectd. Evertying works fine until I decided to use "ifHCInOctets" instead of "ifInOctets". Here is my SNMP plugin config.

<Plugin snmp>
    <Data "std_traffic_hc">
            Type "if_octets"
            Table true
#           Instance "IF-MIB::ifDescr"
            Instance "IF-MIB::ifName"
#           Values "IF-MIB::ifInOctets" "IF-MIB::ifOutOctets"
            Values "IF-MIB::ifHCInOctets" "IF-MIB::ifHCOutOctets"
    </Data>
    <Host "ABCDESW01-01">
            Address "10.0.3.131"
            Version 1
            Community "xxx"
            Collect "std_traffic_hc"
            Interval 60
    </Host>
</Plugin>

I have also tried ifDescr and ifName in the "Instance" directive and that did not make a difference. Either one works for the regular OID but not the HC OID.

I used tcpdump but I don't see collectd ever tried to send snmp traffic to the HC OID. I do see the snmp traffic for the Instance OID.

I have also used snmpwalk to confirm that my switch (HP) supports the OID:

# snmpwalk -v2c -cxxx 10.0.3.131 IF-MIB::ifHCInOctets
IF-MIB::ifHCInOctets.1 = Counter64: 0
IF-MIB::ifHCInOctets.2 = Counter64: 356053022

Where did I do wrong?

Thank you!


问:
Insert values from ArrayList into a JTable
```<code>public void populateJTable() {
    DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
    Object[] rowData = new Object[4];
    TrackService ts = new TrackService();
    ArrayList<Track> tracks = ts.jsonToTracks();

    for (int i = 0; i < tracks.size(); i++) {
        rowData[0] = tracks.get(i).getTrackName();
        rowData[1] = tracks.get(i).getArtist();
        model.addRow(rowData);
    }
    jTable1 = new JTable(model);
}
</code>```

In my json file I have stored metadata of an mp3 file which stores 5 values. My 'jsonToTracks' method stores them in an ArrayList.
I'm trying to get 2 of the values (trackName and artist) from inside my ArrayList and display them in my JTable.
My JTable has 4 columns - Name, Artist, Key, Mood. I'm trying to store the trackName and Artist in their corresponding columns. The Key and Mood column should be blank and the Name and Artist fields should be populated.
I can't see what I'm doing wrong, can anyone help?

答:
```<code>jTable1 = new JTable(model);
</code>```

I suspect the problem is that you are creating a new JTable but you never add the table to the frame.

Instead you should use:

```<code>jTable1.setModel( model );
</code>```

This will replace the data in the existing JTable was I assume you have already added to a JScrollpane that has been added to the frame.

Body:
public void populateJTable() {
    DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
    Object[] rowData = new Object[4];
    TrackService ts = new TrackService();
    ArrayList<Track> tracks = ts.jsonToTracks();

    for (int i = 0; i < tracks.size(); i++) {
        rowData[0] = tracks.get(i).getTrackName();
        rowData[1] = tracks.get(i).getArtist();
        model.addRow(rowData);
    }
    jTable1 = new JTable(model);
}

In my json file I have stored metadata of an mp3 file which stores 5 values. My 'jsonToTracks' method stores them in an ArrayList.
I'm trying to get 2 of the values (trackName and artist) from inside my ArrayList and display them in my JTable.
My JTable has 4 columns - Name, Artist, Key, Mood. I'm trying to store the trackName and Artist in their corresponding columns. The Key and Mood column should be blank and the Name and Artist fields should be populated.
I can't see what I'm doing wrong, can anyone help?

Body:
jTable1 = new JTable(model);

I suspect the problem is that you are creating a new JTable but you never add the table to the frame.

Instead you should use:

jTable1.setModel( model );

This will replace the data in the existing JTable was I assume you have already added to a JScrollpane that has been added to the frame.


问:
jq extract value of keypair and assign to bash variable
jq does my head in sometimes. Assume you have a json file called emails.json that looks like this;

```<code>[
  {
    "ParameterKey": "foo1",
    "ParameterValue": "bar1"
  },
  {
    "ParameterKey": "foo2",
    "ParameterValue": "bar2"
  }
]
</code>```

If I run my bash script (let's call it script.sh) using the argument foo1, I want to have bar1 assigned to a variable called emailAdd. Likewise, if I use the argument foo2, I want bar2 assigned.

I thought my script would look like the following, but I'm getting an empty variable.

```<code>#!/usr/bin/env bash

EMAIL=$1

emailAdd=$(jq --arg email "$EMAIL" '.[] | select(.ParameterKey=="$email") | .ParameterValue' < emails.json)

echo "address is " $emailAdd
</code>```

So, running sh script.sh foo1 I would expect address is bar1, etc

答:
You pretty much have it correct. You don't need the quotes around $email, because unlike shell, jq actually treats that as a variable containing a value, rather than something to expand to arbitrary text. You probably also want to use the -r option so that the output is bar1, rather than "bar1".

```<code>#!/usr/bin/env bash

EMAIL=$1

emailAdd=$(jq -r --arg email "$EMAIL" '.[] | select(.ParameterKey==$email) | .ParameterValue' < emails.json)

echo "address is $emailAdd"
</code>```

Body:
jq does my head in sometimes. Assume you have a json file called emails.json that looks like this;

[
  {
    "ParameterKey": "foo1",
    "ParameterValue": "bar1"
  },
  {
    "ParameterKey": "foo2",
    "ParameterValue": "bar2"
  }
]

If I run my bash script (let's call it script.sh) using the argument foo1, I want to have bar1 assigned to a variable called emailAdd. Likewise, if I use the argument foo2, I want bar2 assigned.

I thought my script would look like the following, but I'm getting an empty variable.

#!/usr/bin/env bash

EMAIL=$1

emailAdd=$(jq --arg email "$EMAIL" '.[] | select(.ParameterKey=="$email") | .ParameterValue' < emails.json)

echo "address is " $emailAdd

So, running sh script.sh foo1 I would expect address is bar1, etc

Body:
You pretty much have it correct. You don't need the quotes around $email, because unlike shell, jq actually treats that as a variable containing a value, rather than something to expand to arbitrary text. You probably also want to use the -r option so that the output is bar1, rather than "bar1".

#!/usr/bin/env bash

EMAIL=$1

emailAdd=$(jq -r --arg email "$EMAIL" '.[] | select(.ParameterKey==$email) | .ParameterValue' < emails.json)

echo "address is $emailAdd"


问:
Moodle questionary
I'm using moodle 3.2 and I wonder if someone can help me with questionary activity.

I want to create like a rolplay in moodle using a quiz, in which the question or page a respondent sees next based on how they answer the current question.

Lets say if I have :
For question 1)
if user response

a) then move to question X
b) then move to question Y
c) then move to question X
d) then move to question H

Not sure how to achieve this.

Best Regards,
Thanks

Sebastian.

答: Take a look at the lesson module in Moodle - https://docs.moodle.org/en/Lesson_module - that sounds like exactly what it does.</p>

Title: Moodle questionary


问:
Kotlin: Array of Generics
I'm writing a B-tree, which may have many keys in one node, and I have encountered a problem. When I create an array of Ints everything works fine:

```<code>class Node<K: Comparable<K>> (val t: Int) {
    val keys: Array<Int?> = Array<Int?> (t*2-1, {null})
}
</code>```

But I want to create an array of Generics Ks:

```<code>class Node<K: Comparable<K>> (val t: Int) {
    val keys : Array<K?> = Array<K?> (t*2-1, {null})
}
</code>```

In this case compiler throws this error message:

```<code>'Kotlin: Cannot use 'K' as reified type parameter. Use a class instead.'
</code>```

The question is How to create an array of Generics?

UPD: Thx for all the replies! It seems that MutableList is nice solution for my objective.

答:
You can just use List<K> instead, it doesn't require you to have reified types.

To use generic parameters with Array<K>, you need the generic parameter to be reified (so that you can get it's class)

You can't use reified with classes, only with functions, and the functions must be inline

So I'd suggest that you use a class as late as possible, with concrete or non-reified generic types.

Meanwhile, you can use functions like these

```<code>inline fun <reified K : Comparable<K>> computeKeys(t: Int): Array<K?> =
    Array(t * 2 - 1) { null }
</code>```

Title: Kotlin: Array of Generics

Body:
I'm writing a B-tree, which may have many keys in one node, and I have encountered a problem. When I create an array of Ints everything works fine:

class Node<K: Comparable<K>> (val t: Int) {
    val keys: Array<Int?> = Array<Int?> (t*2-1, {null})
}

But I want to create an array of Generics Ks:

class Node<K: Comparable<K>> (val t: Int) {
    val keys : Array<K?> = Array<K?> (t*2-1, {null})
}

In this case compiler throws this error message:

'Kotlin: Cannot use 'K' as reified type parameter. Use a class instead.'

The question is How to create an array of Generics?

UPD: Thx for all the replies! It seems that MutableList is nice solution for my objective.

Body:
You can just use List<K> instead, it doesn't require you to have reified types.

To use generic parameters with Array<K>, you need the generic parameter to be reified (so that you can get it's class)

You can't use reified with classes, only with functions, and the functions must be inline

So I'd suggest that you use a class as late as possible, with concrete or non-reified generic types.

Meanwhile, you can use functions like these

inline fun <reified K : Comparable<K>> computeKeys(t: Int): Array<K?> =
    Array(t * 2 - 1) { null }


问:
what is spec_path for fastlane action appium?
I'm trying to use appium using fastlane. What exactly is spec_path?

From documentation: https://docs.fastlane.tools/actions/#appium

Path to Appium spec directory

```<code>appium(
  app_path:  "appium/apps/TargetApp.app",
  spec_path: "appium/spec",
  platform:  "iOS",
  caps: {
    versionNumber: "9.1",
    deviceName:    "iPhone 6"
  }
)
</code>```

答:
According to the description in fastlane, the Appium action allows you to, "Run UI test by Appium with RSpec". spec_path refers to a file path (usually ending in a directory called spec) in which RSpec will find the tests to run.

The article, Automated iOS and Android Acceptance Testing with RSpec and Appium may be a good introduction to the pieces of the puzzle.

Body:
I'm trying to use appium using fastlane. What exactly is spec_path?

From documentation: https://docs.fastlane.tools/actions/#appium

Path to Appium spec directory

appium(
  app_path:  "appium/apps/TargetApp.app",
  spec_path: "appium/spec",
  platform:  "iOS",
  caps: {
    versionNumber: "9.1",
    deviceName:    "iPhone 6"
  }
)


问:
Is there a way to clear IBM MobileFirst Platform server Cache?
I'm working on an IBM MobileFirst Platform 7.1 project where there are many name value pairs in the worklight.properties file.

Say for example,

```<code>HOST_NAME = www.google.com
</code>```

I access these variables form the MobileFirst adapter.

```<code>var hostName = WL.Server.configuration["HOST_NAME"]
</code>```

There will be cases where I'll have to change the HOST_NAME in the worklight.properties to a different value. But sometimes, even after the value is changed in the worklight.properties file, they are not getting updated in the adapter.

Every time when I change the values I do the following,

Clean the project

Restart the server

Deploy the adapter again

Nothing seemed to change the value.

I suspect, the MobileFirst server caches the values and reuses the old values without updating the new ones. I say this because, I tried deleting the values in the worklight.properties file, and even tried deleting the file itself. Still the adapter was using the old value.

I tried deleting the MobileFirstServerConfig Folder in my workspace. Even that didn't work.

It would be great if someone could help me clear the cache or find a work around to this issue. Thanks in advance.

答: The worklight.properties file is embedded into the project runtime WAR file.  So, if you change anything in worklight.properties, you must rebuild the WAR file and redeploy it.  Based on your description, it sounds like you're only building the adapter (and not the app).  At minimum, I would suggest to remove the runtime WAR file from the project "bin" directory (just to ensure that it gets rebuilt) and build all app environments.  That should build / redeploy the WAR file and restart the server, and then what you're doing should work.</p>

Body:
I'm working on an IBM MobileFirst Platform 7.1 project where there are many name value pairs in the worklight.properties file.

Say for example,

HOST_NAME = www.google.com

I access these variables form the MobileFirst adapter.

var hostName = WL.Server.configuration["HOST_NAME"]

There will be cases where I'll have to change the HOST_NAME in the worklight.properties to a different value. But sometimes, even after the value is changed in the worklight.properties file, they are not getting updated in the adapter.

Every time when I change the values I do the following,

Clean the project

Restart the server

Deploy the adapter again

Nothing seemed to change the value.

I suspect, the MobileFirst server caches the values and reuses the old values without updating the new ones. I say this because, I tried deleting the values in the worklight.properties file, and even tried deleting the file itself. Still the adapter was using the old value.

I tried deleting the MobileFirstServerConfig Folder in my workspace. Even that didn't work.

It would be great if someone could help me clear the cache or find a work around to this issue. Thanks in advance.


问:
Import css/scss file into a class
I have a problem. I'm using vaadin inside liferay. I've successfully written a fully responsive (yeah, tables too) theme for vaadin, based on bootstrap. Now I'm importing it to liferay. Everything went fine 'till I needed to upgrade Liferay, where their new responsive theme is using same classes name as bootstrap, but with different behaviour (sad, very sad face).

The solution I've thought so far is to apply a class to the vaadin compiled css, like:

```<code>.daVaadinTheme {
    @import bootstrap.css;
}
</code>```

so the content will be compiled like:

```<code>.daVaadinTheme h1.insideTheFile{

}
.daVaadinTheme h2.insideTheFile{

}
</code>```

But, as you may figured out, is not obviously working.

Do you have any solution?

Read carefully! This is NOT a duplicate of the answer you've posted. I'm trying to import a CSS file inside a CSS/SCSS class of another file, like the example I've written above. My problem is not to simply import a CSS file inside another one...

SOLUTION: (kudos to Mathias Jørgensen)

using @import from another scss file:

in test.scss:

```<code>.daVaadinTheme{
    @import "bootstrap.scss";
}
</code>```

答:
Name your inner file with an underscore, and ending in scss. .Yes, even if it's plain css, i.e. foo.css → _foo.scss

Have an outer File like so:

```<code>#main .content {  // if that's, where you want them to rule only
    @import 'foo';
}
</code>```

Reasons:

import only works with scss

underscore-files are glady skipped by sass (also as in gulp.src(<some wildcards).sass())

if you have no influence in your repo about the css filename whatsoever. or it's a major pain on upgrades, consider using a symbolic link under an .scss extension...

Title: Import css/scss file into a class

Body:
I have a problem. I'm using vaadin inside liferay. I've successfully written a fully responsive (yeah, tables too) theme for vaadin, based on bootstrap. Now I'm importing it to liferay. Everything went fine 'till I needed to upgrade Liferay, where their new responsive theme is using same classes name as bootstrap, but with different behaviour (sad, very sad face).

The solution I've thought so far is to apply a class to the vaadin compiled css, like:

.daVaadinTheme {
    @import bootstrap.css;
}

so the content will be compiled like:

.daVaadinTheme h1.insideTheFile{

}
.daVaadinTheme h2.insideTheFile{

}

But, as you may figured out, is not obviously working.

Do you have any solution?

Read carefully! This is NOT a duplicate of the answer you've posted. I'm trying to import a CSS file inside a CSS/SCSS class of another file, like the example I've written above. My problem is not to simply import a CSS file inside another one...

SOLUTION: (kudos to Mathias Jørgensen)

using @import from another scss file:

in test.scss:

.daVaadinTheme{
    @import "bootstrap.scss";
}

Body:
Name your inner file with an underscore, and ending in scss. .Yes, even if it's plain css, i.e. foo.css → _foo.scss

Have an outer File like so:

#main .content {  // if that's, where you want them to rule only
    @import 'foo';
}

Reasons:

import only works with scss

underscore-files are glady skipped by sass (also as in gulp.src(<some wildcards).sass())

if you have no influence in your repo about the css filename whatsoever. or it's a major pain on upgrades, consider using a symbolic link under an .scss extension...


问:
Remove extra space before first col in bootstrap
Before the first col, there is big space left, like I have used pull-1. Before the first row I have my navbar with margin-bottom:0;

Here is my code

```<code> <div class="container-fluid">

            <div class="row" gpon-pic-area>
                                        <div class="col-md-2" style="background-color: red">
                                            Inspection
                                                            <br>
                                                            <div class="rail-select gpon-pic-area">
                                                        <div class="select-side">
                                                            <i class="fa fa-angle-down"></i>
                                                        </div>
                                                        <select class="form-control gpon-pic-area" >
                                                                                <option value="portStatus">Port Status</option>
                                                                    <option value="portAlarm">Port Alarm</option>
                                                                    <option value="portUsage">Port Usage</option>
                                                                    <option value="portBandwidth">Port Bandwidth</option>
                                                                                </select>
                                                                    </div>
                                        </div>
</div>
</div>
</code>```

答:
I think you are talking about the space created by the container-fluid.

With container-fluid

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

      Inspection

        <select class="form-control gpon-pic-area">
                                                                                <option value="portStatus">Port Status</option>
                                                                    <option value="portAlarm">Port Alarm</option>
                                                                    <option value="portUsage">Port Usage</option>
                                                                    <option value="portBandwidth">Port Bandwidth</option>
                                                                                </select>

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

<p><strong>Without container-fluid</strong></p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

  <div class="row" gpon-pic-area>
    <div class="col-md-2" style="background-color: red">
      Inspection
      <br>
      <div class="rail-select gpon-pic-area">
        <div class="select-side">
          <i class="fa fa-angle-down"></i>
        </div>
        <select class="form-control gpon-pic-area">
                                                                                <option value="portStatus">Port Status</option>
                                                                    <option value="portAlarm">Port Alarm</option>
                                                                    <option value="portUsage">Port Usage</option>
                                                                    <option value="portBandwidth">Port Bandwidth</option>
                                                                                </select>
      </div>
    </div>
  </div>
</div></code>```

Hope this helps!

Body:
Before the first col, there is big space left, like I have used pull-1. Before the first row I have my navbar with margin-bottom:0;

Here is my code

                                            Inspection

                                                        <select class="form-control gpon-pic-area" >
                                                                                <option value="portStatus">Port Status</option>
                                                                    <option value="portAlarm">Port Alarm</option>
                                                                    <option value="portUsage">Port Usage</option>
                                                                    <option value="portBandwidth">Port Bandwidth</option>
                                                                                </select>

Body:
I think you are talking about the space created by the container-fluid.

With container-fluid

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<div class="container-fluid">

  <div class="row" gpon-pic-area>
    <div class="col-md-2" style="background-color: red">
      Inspection
      <br>
      <div class="rail-select gpon-pic-area">
        <div class="select-side">
          <i class="fa fa-angle-down"></i>
        </div>
        <select class="form-control gpon-pic-area">
                                                                                <option value="portStatus">Port Status</option>
                                                                    <option value="portAlarm">Port Alarm</option>
                                                                    <option value="portUsage">Port Usage</option>
                                                                    <option value="portBandwidth">Port Bandwidth</option>
                                                                                </select>
      </div>
    </div>
  </div>
</div>

Without container-fluid

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

  <div class="row" gpon-pic-area>
    <div class="col-md-2" style="background-color: red">
      Inspection
      <br>
      <div class="rail-select gpon-pic-area">
        <div class="select-side">
          <i class="fa fa-angle-down"></i>
        </div>
        <select class="form-control gpon-pic-area">
                                                                                <option value="portStatus">Port Status</option>
                                                                    <option value="portAlarm">Port Alarm</option>
                                                                    <option value="portUsage">Port Usage</option>
                                                                    <option value="portBandwidth">Port Bandwidth</option>
                                                                                </select>
      </div>
    </div>
  </div>
</div>

Hope this helps!


问:
Is there a more agile way to re-factor the following string formating code
I need to format a string as bellow :

```<code>print "%8s%-32s%-32s%-32s" % (' ', 'CAT A', 'CAT B', 'CAT C')
</code>```

Since the number of cat is a variable, here is what I code.

```<code>values = [' ', ]
format = "%8s"
# width is a variable
width = house.get_width()

for cat in range(house.get_cat_count()):
    format = format + '%-' + str(width) + 's'
    values.append('CAT ' + chr(ord('A') + operator))

# format is "%8s%-32s%-32s%-32s"
# values is [' ', 'CAT A', 'CAT B', 'CAT C']
${format % tuple(values)}
</code>```

The code doesn't seem short and agile. Is there any other way to code it in python style?

答:
How about:

```<code>result = ' ' * 8
width = house.get_width() - 4 # subtract 4 to allow for 'CAT '
for i in range(house.get_cat_count()): # or xrange
    result += 'CAT %-*c' % (width, ord('A') + i)
</code>```

Note the use of * to indicate a variable width specifier, and the %c format specifier for a single character to avoid using chr().

ContentLicense: CC BY-SA 2.5

Body:
I need to format a string as bellow :

print "%8s%-32s%-32s%-32s" % (' ', 'CAT A', 'CAT B', 'CAT C')

Since the number of cat is a variable, here is what I code.

values = [' ', ]
format = "%8s"
# width is a variable
width = house.get_width()

for cat in range(house.get_cat_count()):
    format = format + '%-' + str(width) + 's'
    values.append('CAT ' + chr(ord('A') + operator))

# format is "%8s%-32s%-32s%-32s"
# values is [' ', 'CAT A', 'CAT B', 'CAT C']
${format % tuple(values)}

The code doesn't seem short and agile. Is there any other way to code it in python style?

Body:
How about:

result = ' ' * 8
width = house.get_width() - 4 # subtract 4 to allow for 'CAT '
for i in range(house.get_cat_count()): # or xrange
    result += 'CAT %-*c' % (width, ord('A') + i)

Note the use of * to indicate a variable width specifier, and the %c format specifier for a single character to avoid using chr().


问:
Create a variable to hold objects of different types C++
I have 3 different objects A, B and C. Depending on the the parameter given, I would like to choose among these different objects. In programming,

```<code>class A {
  public:
    void printHello() { cout << "HELLO A" << endl; }
};

class B {
  public:
    void printHello() { cout << "HELLO B" << endl; }
};

class C {
   public:
     void printHello() { cout << "HELLO C" << endl; }
};

int main () {
    string key = "c";
    A a;
    B b;
    C c;
    Object obj; // I don't know how to declare Object.

    if (key == "a") obj = a;
    else if (key == "b") obj = b;
    else obj = c;
    obj.printHello(); // print Hello C.
    return 0;
}
</code>```

I have thought about templates and struct objects. But none of them work so far.

```<code>template<typename T1, T2, T3>
T1 getType(string key, T1 t1, T2 t2, T3 t3) { // this is problem coz return types are different.
    if (key == "a") return t1;
    else if (key == "b") return t2;
    else return t3;
}
</code>```

It is easy to create Object o; in JAVA because every object in Java is subclass of Object class. But how do I achieve this in C++?

Edit.
I can't change class A, B and C. I was given these classes to work with and my goal is to implement main method. So, inheritance was out of the question for me. Sorry for any confusion.

Any help is appreciated.

答:
It seems to me that you should use a virtual common base class/struct and a pointer to this base class/struct.

The following is a full working example

```<code>#include <iostream>

struct Base
 { virtual void printHello () = 0; };

class A : public Base {
  public:
    void printHello() { std::cout << "HELLO A" << std::endl; }
};

class B  : public Base{
  public:
    void printHello() { std::cout << "HELLO B" << std::endl; }
};

class C  : public Base{
   public:
     void printHello() { std::cout << "HELLO C" << std::endl; }
};

int main () {
    std::string key = "c";
    A a;
    B b;
    C c;
    Base * obj;

    if (key == "a") obj = &a;
    else if (key == "b") obj = &b;
    else obj = &c;
    obj->printHello(); // print Hello C.
    return 0;
}
</code>```

Body:
I have 3 different objects A, B and C. Depending on the the parameter given, I would like to choose among these different objects. In programming,

class A {
  public:
    void printHello() { cout << "HELLO A" << endl; }
};

class B {
  public:
    void printHello() { cout << "HELLO B" << endl; }
};

class C {
   public:
     void printHello() { cout << "HELLO C" << endl; }
};

int main () {
    string key = "c";
    A a;
    B b;
    C c;
    Object obj; // I don't know how to declare Object.

    if (key == "a") obj = a;
    else if (key == "b") obj = b;
    else obj = c;
    obj.printHello(); // print Hello C.
    return 0;
}

I have thought about templates and struct objects. But none of them work so far.

template<typename T1, T2, T3>
T1 getType(string key, T1 t1, T2 t2, T3 t3) { // this is problem coz return types are different.
    if (key == "a") return t1;
    else if (key == "b") return t2;
    else return t3;
}

It is easy to create Object o; in JAVA because every object in Java is subclass of Object class. But how do I achieve this in C++?

Edit.
I can't change class A, B and C. I was given these classes to work with and my goal is to implement main method. So, inheritance was out of the question for me. Sorry for any confusion.

Any help is appreciated.

Body:
It seems to me that you should use a virtual common base class/struct and a pointer to this base class/struct.

The following is a full working example

#include <iostream>

struct Base
 { virtual void printHello () = 0; };

class A : public Base {
  public:
    void printHello() { std::cout << "HELLO A" << std::endl; }
};

class B  : public Base{
  public:
    void printHello() { std::cout << "HELLO B" << std::endl; }
};

class C  : public Base{
   public:
     void printHello() { std::cout << "HELLO C" << std::endl; }
};

int main () {
    std::string key = "c";
    A a;
    B b;
    C c;
    Base * obj;

    if (key == "a") obj = &a;
    else if (key == "b") obj = &b;
    else obj = &c;
    obj->printHello(); // print Hello C.
    return 0;
}


问:
Facebook Share Dialog does not display thumbnails one first load
I'm using the Facebook share dialog to share a specific url. The shared link contains an image which should be part of the sharing later on. The strange thing about this is that it works totally fine on mobile browsers. But desktop browser do not load the image at the first attempt. A simple reload of the sharing window fixes the missing image. Once this image shows up for at least one time it continues working in other browsers without additional reloads..

So my question is: Does anybody knows why the first call of this url does not show images?

Details

Link for opening the sharing dialog

Here is the output of the Facebook Debugger, which is free of errors and shows the image as well.

Facebook debugger output

Update

Seems to work with the Feed Dialog without any issues. But this is another way of sharing which I would like to prevent since it requires an App ID.

答:
You also can check og:image:width and og:image:height properties.

This works for me.


问:
Angular Primeng Datatable Paginator Bottom Anchoring
I have a Datatable with a paginator in bottom position.
Say it has to show 22 record per page, 26 records total.
In the second page the paginator is positioned right under the last 4 records, and not at the very bottom of the area assigned to the grid (under the 22th potential record). I don't think this is the good way to handle it, because the user sees the pages selector "disappear" under his mouse arrow, and he has to move up if he wants to get back to the previous page.
Is there a way to anchor the paginator always at the very bottom of the grid? I didn't find anything in the documentation.
Thanks, Giovanni</p>

答:
I can't be sure because I'm new to PrimeNG, but you can try adding simple CSS for this class:

.ui-datatable-tablewrapper{
    max-height: 300px;
    overflow: auto;
}```


问:
Spring Boot - inject map from properties file
property file looks like this:

```<code>url1=path_to_binary1
url2=path_to_binary2
</code>```

According this I tried following approach:

```<code>@Component
@EnableConfigurationProperties
public class ApplicationProperties {
    private Map<String, String> pathMapper;

    //get and set
}
</code>```

and in another component I autowired ApplicationProperties:

```<code>@Autowired
private ApplicationProperties properties;
      //inside some method:
      properties.getPathMapper().get(appName);
</code>```

produces NullPointerException.

How to correct it?

update

I have correct according user7757360 advice:

```<code>@Component
@EnableConfigurationProperties
@ConfigurationProperties(prefix="app")
public class ApplicationProperties {
</code>```

and properties file:

```<code>app.url1=path_to_binary1
app.url2=path_to_binary2
</code>```

Still doesn't work

Update 2

```<code>@Component
@EnableConfigurationProperties
@ConfigurationProperties(prefix="app")
public class ApplicationProperties {
    private Map<String, String> app;
</code>```

and inside application.properties:

```<code>app.url1=path_to_binary1
app.url2=path_to_binary2
</code>```

Still doesn't work

答:
NullPointerException is probably from empty ApplicationProperties.

All custom properties should be annotated @ConfigurationProperties(prefix="custom").
After that, on your main class (class with main method) you must add @EnableConfigurationProperties(CustomProperties.class).
For autocomplete you can use:

```<code><dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-configuration-processor</artifactId>
    <optional>true</optional>
</dependency>
</code>```

If you use @ConfigurationProperties without prefix you use only field name. Field name in you properites. In your case path-mapper, next you specific key and value. Example:

```<code>path-mapper.key=value
</code>```

Remeber after changes in your own properites you need to reload application. Example:

https://github.com/kchrusciel/SpringPropertiesExample

Body:
property file looks like this:

url1=path_to_binary1
url2=path_to_binary2

According this I tried following approach:

@Component
@EnableConfigurationProperties
public class ApplicationProperties {
    private Map<String, String> pathMapper;

    //get and set
}

and in another component I autowired ApplicationProperties:

@Autowired
private ApplicationProperties properties;
      //inside some method:
      properties.getPathMapper().get(appName);

produces NullPointerException.

How to correct it?

update

I have correct according user7757360 advice:

@Component
@EnableConfigurationProperties
@ConfigurationProperties(prefix="app")
public class ApplicationProperties {

and properties file:

app.url1=path_to_binary1
app.url2=path_to_binary2

Still doesn't work

Update 2

@Component
@EnableConfigurationProperties
@ConfigurationProperties(prefix="app")
public class ApplicationProperties {
    private Map<String, String> app;

and inside application.properties:

app.url1=path_to_binary1
app.url2=path_to_binary2

Still doesn't work

Body:
NullPointerException is probably from empty ApplicationProperties.

All custom properties should be annotated @ConfigurationProperties(prefix="custom").
After that, on your main class (class with main method) you must add @EnableConfigurationProperties(CustomProperties.class).
For autocomplete you can use:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-configuration-processor</artifactId>
    <optional>true</optional>
</dependency>

If you use @ConfigurationProperties without prefix you use only field name. Field name in you properites. In your case path-mapper, next you specific key and value. Example:

path-mapper.key=value

Remeber after changes in your own properites you need to reload application. Example:

https://github.com/kchrusciel/SpringPropertiesExample


问:
Pandas column selection with coordinates
I've got a pandas dataframe:

A.loc[:,:,location]

with location = (x, y)
with x and y numbers. When i try to select the columns:
locations = (1, 2) in:

B = A.loc[:,:,location]

It says: '[(1, 2)] is not in the columns.'
When i print the dataframe it clearly says that (1, 2) is in the minor axis.
Any idea how I can select these coördinate-like columns?

答:
It is not really clear what you want, at least to me, but maybe these could help:</p>

```<code># Select the first 3 columns
df.iloc[:,:3]

# Select the first cell down in the column named location
df.ix[0, 'location']

# Select all the location rows has the value of "(1,2)"
df[(df['location'] == '(1,2)')]
</code>```

Body:
It is not really clear what you want, at least to me, but maybe these could help:

# Select the first 3 columns
df.iloc[:,:3]

# Select the first cell down in the column named location
df.ix[0, 'location']

# Select all the location rows has the value of "(1,2)"
df[(df['location'] == '(1,2)')]


问:
Why is the gets function so dangerous that it should not be used?
When I try to compile C code that uses the gets() function with GCC, I get this warning:

(.text+0x34): warning: the `gets' function is dangerous and should not be used.

I remember this has something to do with stack protection and security, but I'm not sure exactly why.

How can I remove this warning and why is there such a warning about using gets()?

If gets() is so dangerous then why can't we remove it?

答:
Why is gets() dangerous

The first internet worm (the Morris Internet Worm) escaped about 30 years ago (1988-11-02), and it used gets() and a buffer overflow as one of its methods of propagating from system to system. The basic problem is that the function doesn't know how big the buffer is, so it continues reading until it finds a newline or encounters EOF, and may overflow the bounds of the buffer it was given.

You should forget you ever heard that gets() existed.

The C11 standard ISO/IEC 9899:2011 eliminated gets() as a standard function, which is A Good Thing™ (it was formally marked as 'obsolescent' and 'deprecated' in ISO/IEC 9899:1999/Cor.3:2007 — Technical Corrigendum 3 for C99, and then removed in C11). Sadly, it will remain in libraries for many years (meaning 'decades') for reasons of backwards compatibility. If it were up to me, the implementation of gets() would become:

```<code>char *gets(char *buffer)
{
    assert(buffer != 0);
    abort();
    return 0;
}
</code>```

Given that your code will crash anyway, sooner or later, it is better to head the trouble off sooner rather than later. I'd be prepared to add an error message:

```<code>fputs("obsolete and dangerous function gets() called\n", stderr);
</code>```

Modern versions of the Linux compilation system generates warnings if you link gets() — and also for some other functions that also have security problems (mktemp(), …).

Alternatives to gets()

fgets()

As everyone else said, the canonical alternative to gets() is fgets() specifying stdin as the file stream.

```<code>char buffer[BUFSIZ];

while (fgets(buffer, sizeof(buffer), stdin) != 0)
{
    ...process line of data...
}
</code>```

What no-one else yet mentioned is that gets() does not include the newline but fgets() does. So, you might need to use a wrapper around fgets() that deletes the newline:

```<code>char *fgets_wrapper(char *buffer, size_t buflen, FILE *fp)
{
    if (fgets(buffer, buflen, fp) != 0)
    {
        size_t len = strlen(buffer);
        if (len > 0 && buffer[len-1] == '\n')
            buffer[len-1] = '\0';
        return buffer;
    }
    return 0;
}
</code>```

Or, better:

```<code>char *fgets_wrapper(char *buffer, size_t buflen, FILE *fp)
{
    if (fgets(buffer, buflen, fp) != 0)
    {
        buffer[strcspn(buffer, "\n")] = '\0';
        return buffer;
    }
    return 0;
}
</code>```

Also, as caf points out in a comment and paxdiablo shows in their answer, with fgets() you might have data left over on a line. My wrapper code leaves that data to be read next time; you can readily modify it to gobble the rest of the line of data if you prefer:

```<code>        if (len > 0 && buffer[len-1] == '\n')
            buffer[len-1] = '\0';
        else
        {
             int ch;
             while ((ch = getc(fp)) != EOF && ch != '\n')
                 ;
        }
</code>```

The residual problem is how to report the three different result states — EOF or error, line read and not truncated, and partial line read but data was truncated.

This problem doesn't arise with gets() because it doesn't know where your buffer ends and merrily tramples beyond the end, wreaking havoc on your beautifully tended memory layout, often messing up the return stack (a Stack Overflow) if the buffer is allocated on the stack, or trampling over the control information if the buffer is dynamically allocated, or copying data over other precious global (or module) variables if the buffer is statically allocated. None of these is a good idea — they epitomize the phrase 'undefined behaviour`.

There is also the TR 24731-1 (Technical Report from the C Standard Committee) which provides safer alternatives to a variety of functions, including gets():

§6.5.4.1 The gets_s function

###Synopsis

```<code>#define __STDC_WANT_LIB_EXT1__ 1
#include <stdio.h>
char *gets_s(char *s, rsize_t n);
</code>```

Runtime-constraints

s shall not be a null pointer. n shall neither be equal to zero nor be greater than RSIZE_MAX. A new-line character, end-of-file, or read error shall occur within reading n-1 characters from stdin.25)

3 If there is a runtime-constraint violation, s[0] is set to the null character, and characters are read and discarded from stdin until a new-line character is read, or end-of-file or a read error occurs.

Description

4 The gets_s function reads at most one less than the number of characters specified by n from the stream pointed to by stdin, into the array pointed to by s. No additional characters are read after a new-line character (which is discarded) or after end-of-file. The discarded new-line character does not count towards number of characters read. A null character is written immediately after the last character read into the array.

5 If end-of-file is encountered and no characters have been read into the array, or if a read error occurs during the operation, then s[0] is set to the null character, and the other elements of s take unspecified values.

Recommended practice

6 The fgets function allows properly-written programs to safely process input lines too long to store in the result array. In general this requires that callers of fgets pay attention to the presence or absence of a new-line character in the result array. Consider using fgets (along with any needed processing based on new-line characters) instead of gets_s.

25) The gets_s function, unlike gets, makes it a runtime-constraint violation for a line of input to overflow the buffer to store it. Unlike fgets, gets_s maintains a one-to-one relationship between input lines and successful calls to gets_s. Programs that use gets expect such a relationship.

The Microsoft Visual Studio compilers implement an approximation to the TR 24731-1 standard, but there are differences between the signatures implemented by Microsoft and those in the TR.

The C11 standard, ISO/IEC 9899-2011, includes TR24731 in Annex K as an optional part of the library. Unfortunately, it is seldom implemented on Unix-like systems.

getline() — POSIX

POSIX 2008 also provides a safe alternative to gets() called getline(). It allocates space for the line dynamically, so you end up needing to free it. It removes the limitation on line length, therefore. It also returns the length of the data that was read, or -1 (and not EOF!), which means that null bytes in the input can be handled reliably. There is also a 'choose your own single-character delimiter' variation called getdelim(); this can be useful if you are dealing with the output from find -print0 where the ends of the file names are marked with an ASCII NUL '\0' character, for example.

Body:
Why is gets() dangerous

The first internet worm (the Morris Internet Worm) escaped about 30 years ago (1988-11-02), and it used gets() and a buffer overflow as one of its methods of propagating from system to system. The basic problem is that the function doesn't know how big the buffer is, so it continues reading until it finds a newline or encounters EOF, and may overflow the bounds of the buffer it was given.

You should forget you ever heard that gets() existed.

The C11 standard ISO/IEC 9899:2011 eliminated gets() as a standard function, which is A Good Thing™ (it was formally marked as 'obsolescent' and 'deprecated' in ISO/IEC 9899:1999/Cor.3:2007 — Technical Corrigendum 3 for C99, and then removed in C11). Sadly, it will remain in libraries for many years (meaning 'decades') for reasons of backwards compatibility. If it were up to me, the implementation of gets() would become:

char *gets(char *buffer)
{
    assert(buffer != 0);
    abort();
    return 0;
}

Given that your code will crash anyway, sooner or later, it is better to head the trouble off sooner rather than later. I'd be prepared to add an error message:

fputs("obsolete and dangerous function gets() called\n", stderr);

Modern versions of the Linux compilation system generates warnings if you link gets() — and also for some other functions that also have security problems (mktemp(), …).

Alternatives to gets()

fgets()

As everyone else said, the canonical alternative to gets() is fgets() specifying stdin as the file stream.

char buffer[BUFSIZ];

while (fgets(buffer, sizeof(buffer), stdin) != 0)
{
    ...process line of data...
}

What no-one else yet mentioned is that gets() does not include the newline but fgets() does. So, you might need to use a wrapper around fgets() that deletes the newline:

char *fgets_wrapper(char *buffer, size_t buflen, FILE *fp)
{
    if (fgets(buffer, buflen, fp) != 0)
    {
        size_t len = strlen(buffer);
        if (len > 0 && buffer[len-1] == '\n')
            buffer[len-1] = '\0';
        return buffer;
    }
    return 0;
}

Or, better:

char *fgets_wrapper(char *buffer, size_t buflen, FILE *fp)
{
    if (fgets(buffer, buflen, fp) != 0)
    {
        buffer[strcspn(buffer, "\n")] = '\0';
        return buffer;
    }
    return 0;
}

Also, as caf points out in a comment and paxdiablo shows in their answer, with fgets() you might have data left over on a line. My wrapper code leaves that data to be read next time; you can readily modify it to gobble the rest of the line of data if you prefer:

        if (len > 0 && buffer[len-1] == '\n')
            buffer[len-1] = '\0';
        else
        {
             int ch;
             while ((ch = getc(fp)) != EOF && ch != '\n')
                 ;
        }

The residual problem is how to report the three different result states — EOF or error, line read and not truncated, and partial line read but data was truncated.

This problem doesn't arise with gets() because it doesn't know where your buffer ends and merrily tramples beyond the end, wreaking havoc on your beautifully tended memory layout, often messing up the return stack (a Stack Overflow) if the buffer is allocated on the stack, or trampling over the control information if the buffer is dynamically allocated, or copying data over other precious global (or module) variables if the buffer is statically allocated. None of these is a good idea — they epitomize the phrase 'undefined behaviour`.

There is also the TR 24731-1 (Technical Report from the C Standard Committee) which provides safer alternatives to a variety of functions, including gets():

§6.5.4.1 The gets_s function

###Synopsis

#define __STDC_WANT_LIB_EXT1__ 1
#include <stdio.h>
char *gets_s(char *s, rsize_t n);

Runtime-constraints

s shall not be a null pointer. n shall neither be equal to zero nor be greater than RSIZE_MAX. A new-line character, end-of-file, or read error shall occur within reading n-1 characters from stdin.25)

3 If there is a runtime-constraint violation, s[0] is set to the null character, and characters are read and discarded from stdin until a new-line character is read, or end-of-file or a read error occurs.

Description

4 The gets_s function reads at most one less than the number of characters specified by n from the stream pointed to by stdin, into the array pointed to by s. No additional characters are read after a new-line character (which is discarded) or after end-of-file. The discarded new-line character does not count towards number of characters read. A null character is written immediately after the last character read into the array.

5 If end-of-file is encountered and no characters have been read into the array, or if a read error occurs during the operation, then s[0] is set to the null character, and the other elements of s take unspecified values.

Recommended practice

6 The fgets function allows properly-written programs to safely process input lines too long to store in the result array. In general this requires that callers of fgets pay attention to the presence or absence of a new-line character in the result array. Consider using fgets (along with any needed processing based on new-line characters) instead of gets_s.

25) The gets_s function, unlike gets, makes it a runtime-constraint violation for a line of input to overflow the buffer to store it. Unlike fgets, gets_s maintains a one-to-one relationship between input lines and successful calls to gets_s. Programs that use gets expect such a relationship.

The Microsoft Visual Studio compilers implement an approximation to the TR 24731-1 standard, but there are differences between the signatures implemented by Microsoft and those in the TR.

The C11 standard, ISO/IEC 9899-2011, includes TR24731 in Annex K as an optional part of the library. Unfortunately, it is seldom implemented on Unix-like systems.

getline() — POSIX

POSIX 2008 also provides a safe alternative to gets() called getline(). It allocates space for the line dynamically, so you end up needing to free it. It removes the limitation on line length, therefore. It also returns the length of the data that was read, or -1 (and not EOF!), which means that null bytes in the input can be handled reliably. There is also a 'choose your own single-character delimiter' variation called getdelim(); this can be useful if you are dealing with the output from find -print0 where the ends of the file names are marked with an ASCII NUL '\0' character, for example.


问:
Swift 3 - Http post to Https wcf web service
In my xcode console application (10.12), i m using http post requests for sending data to wcf web service. If that web service works with http there is no any problem. But if i change to secure (https) connection then i can not communicate with web service. I m getting 404 error code.

```<code>class request :NSObject,URLSessionDelegate{

func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
    completionHandler(.useCredential, URLCredential(trust: challenge.protectionSpace.serverTrust!))
}

func urlSession(_ session: URLSession, didBecomeInvalidWithError error: Error?) {
    if let err = error {
        print("Error: \(err.localizedDescription)")
    } else {
        print("Error. Giving up")
    }
}

func makeHTTPPostRequest(path: String, params: Dictionary<String,AnyObject>) {
    let request = NSMutableURLRequest(url: NSURL(string: path)! as URL)
    request.httpMethod = "POST"

    do  {
        request.httpBody = try JSONSerialization.data(withJSONObject: params, options: JSONSerialization.WritingOptions.prettyPrinted)
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        request.addValue("application/json", forHTTPHeaderField: "Accept")

        let configuration = URLSessionConfiguration.default
        configuration.timeoutIntervalForRequest = 10
        configuration.timeoutIntervalForResource = 10

        let session = URLSession(configuration: configuration,delegate: self, delegateQueue: nil)

        let task = session.dataTask(with: request as URLRequest, completionHandler: {data, response, error -> Void in

            print(response)

        })
        task.resume()

    }
    catch{

    }

}
</code>```

And web service code someting like that :

```<code>     [WebInvoke(UriTemplate = "/Test", Method = "POST", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest)]
    [OperationContract]
    string Test(string name);
</code>```

I m calling method :

```<code>var params = Dictionary<String,AnyObject>()
</code>```

params["name"] = "Hi" as AnyObject?

var r = request()
r.makeHTTPPostRequest(path:"https://192.168.1.104/sample/Service1.svc/Test",params:params)

This is response from server :

```<code>{ status code: 404, headers {
"Cache-Control" = private;
"Content-Length" = 0;
Date = "Sat, 25 Mar 2017 14:59:29 GMT";
Server = "Microsoft-IIS/7.5";
"Set-Cookie" = "ASP.NET_SessionId=l2omo5wflafesmcw2j23sw4t; path=/; HttpOnly";
"X-AspNet-Version" = "4.0.30319";
"X-Powered-By" = "ASP.NET";}
</code>```

So what i m doing wrong ? Do you have any idea?

Thanks in advance !

答:
I found my mistake, wrong web.config configuration.
The code above works fine.

Best

Body:
In my xcode console application (10.12), i m using http post requests for sending data to wcf web service. If that web service works with http there is no any problem. But if i change to secure (https) connection then i can not communicate with web service. I m getting 404 error code.

class request :NSObject,URLSessionDelegate{

func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
    completionHandler(.useCredential, URLCredential(trust: challenge.protectionSpace.serverTrust!))
}

func urlSession(_ session: URLSession, didBecomeInvalidWithError error: Error?) {
    if let err = error {
        print("Error: \(err.localizedDescription)")
    } else {
        print("Error. Giving up")
    }
}

func makeHTTPPostRequest(path: String, params: Dictionary<String,AnyObject>) {
    let request = NSMutableURLRequest(url: NSURL(string: path)! as URL)
    request.httpMethod = "POST"

    do  {
        request.httpBody = try JSONSerialization.data(withJSONObject: params, options: JSONSerialization.WritingOptions.prettyPrinted)
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        request.addValue("application/json", forHTTPHeaderField: "Accept")

        let configuration = URLSessionConfiguration.default
        configuration.timeoutIntervalForRequest = 10
        configuration.timeoutIntervalForResource = 10

        let session = URLSession(configuration: configuration,delegate: self, delegateQueue: nil)

        let task = session.dataTask(with: request as URLRequest, completionHandler: {data, response, error -> Void in

            print(response)

        })
        task.resume()

    }
    catch{

    }

}

And web service code someting like that :

     [WebInvoke(UriTemplate = "/Test", Method = "POST", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest)]
    [OperationContract]
    string Test(string name);

I m calling method :

var params = Dictionary<String,AnyObject>()

params["name"] = "Hi" as AnyObject?

var r = request()
r.makeHTTPPostRequest(path:"https://192.168.1.104/sample/Service1.svc/Test",params:params)

This is response from server :

{ status code: 404, headers {
"Cache-Control" = private;
"Content-Length" = 0;
Date = "Sat, 25 Mar 2017 14:59:29 GMT";
Server = "Microsoft-IIS/7.5";
"Set-Cookie" = "ASP.NET_SessionId=l2omo5wflafesmcw2j23sw4t; path=/; HttpOnly";
"X-AspNet-Version" = "4.0.30319";
"X-Powered-By" = "ASP.NET";}

So what i m doing wrong ? Do you have any idea?

Thanks in advance !


问:
switch line class in clojurescript with if boolean variable
how can I switch the li class in a list with clojurescript, when the @switchvar is true all odd lines should be active, in the other case the even lines should be active

I tried an if statement, nothing happens.

```<code>(defn listitems [items]
  [:ul
   (for [item items]
     ^{:key item} [:li {:class
        (if (@switchvar true)
            ((odd? item) "active")
            ((even? item) "active") )
      } "Item " item ])])
</code>```

答:
Your if statement does not seem right. You could do something like that:</p>

```<code>[:ul (map #(-> [:li {:class %2} "item" %1])
          items
          (cycle ["active" "non-active"]))]
</code>```

Body:
how can I switch the li class in a list with clojurescript, when the @switchvar is true all odd lines should be active, in the other case the even lines should be active

I tried an if statement, nothing happens.

(defn listitems [items]
  [:ul
   (for [item items]
     ^{:key item} [:li {:class
        (if (@switchvar true)
            ((odd? item) "active")
            ((even? item) "active") )
      } "Item " item ])])

Body:
Your if statement does not seem right. You could do something like that:

[:ul (map #(-> [:li {:class %2} "item" %1])
          items
          (cycle ["active" "non-active"]))]


问:
Import Excel Data into PostgreSQL 9.3
I've developed a huge table in excel and now facing problem in transferring it into the postgresql database. I've downloaded the odbc software and I'm able to open table created in postgresql with excel. However, I'm not able to do it in a reverse manner which is creating a table in excel and open it in the postgresql. So I would like to know it is can be done in this way or is there any alternative ways that can create a large table with pgAdmin III cause inserting the data raw by raw is quite tedious.</p>

答:
I have used Excel/PowerPivot to create the postgreSQL insert statement. Seems like overkill, except when you need to do it over and over again. Once the data is in the PowerPivot window, I add successive columns with concatenate statements to 'build' the insert statement.  I create a flattened pivot table with that last and final column.  Copy and paste the resulting insert statement into my EXISTING postgreSQL table with pgAdmin.

Example two column table  (my table has 30 columns from which I import successive contents over and over with the same Excel/PowerPivot.)

Column1 {a,b,...}   Column2 {1,2,...}

In PowerPivot I add calculated columns with the following commands:

Calculated Column 1 has "insert into table_name values ('"

Calculated Column 2 has CONCATENATE([Calculated Column 1],CONCATENATE([Column1],"','"))

...until you get to the last column and you need to terminate the insert statement:

Calculated Column 3 has CONCATENATE([Calculated Column 2],CONCATENATE([Column2],"');"

Then in PowerPivot I add a flattened pivot table and have all of the insert statement that I just copy and paste to pgAgent.

Resulting insert statements:

```<code>insert into table_name values ('a','1');

insert into table_name values ('b','2');

insert into table_name values ('c','3');
</code>```

NOTE:  If you are familiar with the power pivot CONCATENATE statement, you know that it can only handle 2 arguments (nuts).  Would be nice if it allowed more.

Title: Import Excel Data into PostgreSQL 9.3

Body:
I have used Excel/PowerPivot to create the postgreSQL insert statement. Seems like overkill, except when you need to do it over and over again. Once the data is in the PowerPivot window, I add successive columns with concatenate statements to 'build' the insert statement.  I create a flattened pivot table with that last and final column.  Copy and paste the resulting insert statement into my EXISTING postgreSQL table with pgAdmin.

Example two column table  (my table has 30 columns from which I import successive contents over and over with the same Excel/PowerPivot.)

Column1 {a,b,...}   Column2 {1,2,...}

In PowerPivot I add calculated columns with the following commands:

Calculated Column 1 has "insert into table_name values ('"

Calculated Column 2 has CONCATENATE([Calculated Column 1],CONCATENATE([Column1],"','"))

...until you get to the last column and you need to terminate the insert statement:

Calculated Column 3 has CONCATENATE([Calculated Column 2],CONCATENATE([Column2],"');"

Then in PowerPivot I add a flattened pivot table and have all of the insert statement that I just copy and paste to pgAgent.

Resulting insert statements:

insert into table_name values ('a','1');

insert into table_name values ('b','2');

insert into table_name values ('c','3');

NOTE:  If you are familiar with the power pivot CONCATENATE statement, you know that it can only handle 2 arguments (nuts).  Would be nice if it allowed more.


问:
Use a loop to make the first column the rownames in a set of tables
I am trying to write my first loop in R. I have a database loaded in the global environment in R-studio containing a set of tables. Here is an example of one table.

I would like to make the first column in each file the row name like this:

I have tried a couple of ideas but I am having no luck. First code:

```<code>tables = ls(envir=.GlobalEnv)[sapply(ls(envir=.GlobalEnv),

for (i in 1:length(tables)){
df=read.table(tables[[i]], sep="\t", header=T); rownames(df) = df[,1]}
}
</code>```

Second code:

```<code>tables = ls(envir=.GlobalEnv)[sapply(ls(envir=.GlobalEnv),

for(i in 1:length(tables)){
tables[[i]] <- tables[[i]][,-1]
rownames(tables[[i]]) <- tables[[i]][,1]}
}
</code>```

I'm sure it's an easy solution, I am still a novice at R though. Any thoughts on how to get this to work?

答:
Your second attempt is actually correct but you are dropping the column you want to use for the names before you make change the row names!

Importantly, you should use the drop = FALSE in the deselection of the first row, to keep the data frame type. See what may happen and why to use that statement.

One way of getting a list of all data frames in the global environment is to check which variables are data frames and using the get function to retrieve it by names.

```<code>  ## Logical vector of which variables from ls() are of type data.frame
temp <- sapply(ls(), function(i) is.data.frame(get(i)))
  ## Combine them all in a list
tables <- lapply(names(temp)[temp],get)

tables ## Example of have
## [[1]]
##   a b d
## 1 9 3 a
## 2 8 4 b
##
## [[2]]
##   b c
## 1 5 2
## 2 4 3
## 3 3 4
## 4 2 5
</code>```

To get the output we want is just a slight modification of your code as mentioned above.

```<code>for(i in 1:length(tables)){
    rownames(tables[[i]]) <- tables[[i]][,1]
    tables[[i]] <- tables[[i]][,-1,drop = FALSE]
}
tables ## Example of want
## [[1]]
##   b d
## 9 3 a
## 8 4 b
##
## [[2]]
##   c
## 5 2
## 4 3
## 3 4
## 2 5
</code>```

Body:
I am trying to write my first loop in R. I have a database loaded in the global environment in R-studio containing a set of tables. Here is an example of one table.

I would like to make the first column in each file the row name like this:

I have tried a couple of ideas but I am having no luck. First code:

tables = ls(envir=.GlobalEnv)[sapply(ls(envir=.GlobalEnv),

for (i in 1:length(tables)){
df=read.table(tables[[i]], sep="\t", header=T); rownames(df) = df[,1]}
}

Second code:

tables = ls(envir=.GlobalEnv)[sapply(ls(envir=.GlobalEnv),

for(i in 1:length(tables)){
tables[[i]] <- tables[[i]][,-1]
rownames(tables[[i]]) <- tables[[i]][,1]}
}

I'm sure it's an easy solution, I am still a novice at R though. Any thoughts on how to get this to work?

Body:
Your second attempt is actually correct but you are dropping the column you want to use for the names before you make change the row names!

Importantly, you should use the drop = FALSE in the deselection of the first row, to keep the data frame type. See what may happen and why to use that statement.

One way of getting a list of all data frames in the global environment is to check which variables are data frames and using the get function to retrieve it by names.

  ## Logical vector of which variables from ls() are of type data.frame
temp <- sapply(ls(), function(i) is.data.frame(get(i)))
  ## Combine them all in a list
tables <- lapply(names(temp)[temp],get)

tables ## Example of have
## [[1]]
##   a b d
## 1 9 3 a
## 2 8 4 b
##
## [[2]]
##   b c
## 1 5 2
## 2 4 3
## 3 3 4
## 4 2 5

To get the output we want is just a slight modification of your code as mentioned above.

for(i in 1:length(tables)){
    rownames(tables[[i]]) <- tables[[i]][,1]
    tables[[i]] <- tables[[i]][,-1,drop = FALSE]
}
tables ## Example of want
## [[1]]
##   b d
## 9 3 a
## 8 4 b
##
## [[2]]
##   c
## 5 2
## 4 3
## 3 4
## 2 5


问:
Spring MVC @Controller to intercept own requests
Imagine we have a controller like this:

```<code>@RestController
@RequestMapping("/{parameter}")
public class MyController {

    @ExceptionHandler(SomeException.class)
    public Object handleSomeException() { /* handle */ }

    @RequestMapping("/something")
    public Object handleSomething(@PathVariable("parameter") String parameter) {
        /* handle */
    }

    @RequestMapping("/somethingElse")
    public Object handleSomethingElse(@PathVariable("parameter") String parameter) {
        /* handle */
    }
}
</code>```

The question is, how to implement some common pre-\post-handling for this particular controller in similar way as @ExceptionHandler is working? E.g. I want to have a method in controller which receives request prior to handler methods, but only requests for this particular controller.

I'm aware of RequestBodyAdvice and ResponseBodyAdvice interfaces, but want something local to controller.

As a usage example - I want to do some validation for common parameter variable before each handler.

答:
Use HandlerInterceptorAdapter

Intercept the before and after controller execution, log the start and end of the execution time, save it into the existing intercepted controller’s modelAndView for later display.

```<code>public class ExecuteTimeInterceptor extends HandlerInterceptorAdapter{

private static final Logger logger = Logger.getLogger(ExecuteTimeInterceptor.class);

//before the actual handler will be executed
public boolean preHandle(HttpServletRequest request,
    HttpServletResponse response, Object handler)
    throws Exception {

    long startTime = System.currentTimeMillis();
    request.setAttribute("startTime", startTime);

    return true;
}

//after the handler is executed
public void postHandle(
    HttpServletRequest request, HttpServletResponse response,
    Object handler, ModelAndView modelAndView)
    throws Exception {

    long startTime = (Long)request.getAttribute("startTime");

    long endTime = System.currentTimeMillis();

    long executeTime = endTime - startTime;

    //modified the exisitng modelAndView
    modelAndView.addObject("executeTime",executeTime);

    //log it
    if(logger.isDebugEnabled()){
       logger.debug("[" + handler + "] executeTime : " + executeTime + "ms");
    }
}
</code>```

Some more examples - http://www.mkyong.com/spring-mvc/spring-mvc-handler-interceptors-example/

Body:
Imagine we have a controller like this:

@RestController
@RequestMapping("/{parameter}")
public class MyController {

    @ExceptionHandler(SomeException.class)
    public Object handleSomeException() { /* handle */ }

    @RequestMapping("/something")
    public Object handleSomething(@PathVariable("parameter") String parameter) {
        /* handle */
    }

    @RequestMapping("/somethingElse")
    public Object handleSomethingElse(@PathVariable("parameter") String parameter) {
        /* handle */
    }
}

The question is, how to implement some common pre-\post-handling for this particular controller in similar way as @ExceptionHandler is working? E.g. I want to have a method in controller which receives request prior to handler methods, but only requests for this particular controller.

I'm aware of RequestBodyAdvice and ResponseBodyAdvice interfaces, but want something local to controller.

As a usage example - I want to do some validation for common parameter variable before each handler.

Body:
Use HandlerInterceptorAdapter

Intercept the before and after controller execution, log the start and end of the execution time, save it into the existing intercepted controller’s modelAndView for later display.

public class ExecuteTimeInterceptor extends HandlerInterceptorAdapter{

private static final Logger logger = Logger.getLogger(ExecuteTimeInterceptor.class);

//before the actual handler will be executed
public boolean preHandle(HttpServletRequest request,
    HttpServletResponse response, Object handler)
    throws Exception {

    long startTime = System.currentTimeMillis();
    request.setAttribute("startTime", startTime);

    return true;
}

//after the handler is executed
public void postHandle(
    HttpServletRequest request, HttpServletResponse response,
    Object handler, ModelAndView modelAndView)
    throws Exception {

    long startTime = (Long)request.getAttribute("startTime");

    long endTime = System.currentTimeMillis();

    long executeTime = endTime - startTime;

    //modified the exisitng modelAndView
    modelAndView.addObject("executeTime",executeTime);

    //log it
    if(logger.isDebugEnabled()){
       logger.debug("[" + handler + "] executeTime : " + executeTime + "ms");
    }
}

Some more examples - http://www.mkyong.com/spring-mvc/spring-mvc-handler-interceptors-example/


问:
Ruby YAML delimiter
Is there any way to change the delimiter that is used when Ruby creates a YAML file?

What is given right now:

```<code>---
- de
- abbrv_apr: APR
</code>```

What is wanted:

```<code>\t de
\t abbrv_apr: APR
</code>```

The \t is a tab, so basically I want all of the dashes to be gone from the created yaml files

I was able to fix my problem by creating a nested sequence http://www.yaml.org/YAML_for_ruby.html#nested_sequences

答:
YAML is a format that does not allow for such customizations.

Of course, you can always do obj.to_yaml.gsub(/^-/, "\t") if you need to. (with /^\t/, '-' on read)

Title: Ruby YAML delimiter

Body:
Is there any way to change the delimiter that is used when Ruby creates a YAML file?

What is given right now:

---
- de
- abbrv_apr: APR

What is wanted:

\t de
\t abbrv_apr: APR

The \t is a tab, so basically I want all of the dashes to be gone from the created yaml files

I was able to fix my problem by creating a nested sequence http://www.yaml.org/YAML_for_ruby.html#nested_sequences


问:
In Boto3 how does one assign a public IP when creating an instance
I am working on an AWS VPC that has one subnet that does not auto-assign a public IP by default.  I would like to use boto3 to create the instance and automatically assign the public IP.  It's not clear how to do this from the boto3 documentation.

The closest I got was the following, but this still has errors:

self._ec2.create_instances(
    ImageId=self._cluster._image,
    KeyName="key_pair_1",
    InstanceType="t2.micro",
    MinCount=1,
    MaxCount=1,
    SecurityGroupIds=["sg-someid"],
    SubnetId="subnet-anotherid",
    BlockDeviceMappings=[{
        "DeviceName": "/dev/sda1",
        "Ebs": {
            "VolumeType": "gp2",
            "VolumeSize": disk_size,
            "DeleteOnTermination": True
        },
    }],
    NetworkInterfaces=[{
        "DeviceIndex": 0,
        "AssociatePublicIpAddress": True
    }]
)

答:
Might help someone:
You have to put the SecurityGroupIds, and the subnetID as a network interface parameter, and remove them from the instance parameters, then it will run fine.</p>

```<code>NetworkInterfaces=[
    {
        'DeviceIndex': 0,
        'SubnetId' : 'subnet-xxxxxx',
        'Groups': [
            'sg-xxxxxx','sg-xxxx','sg-xxxxxx'
        ],
        'AssociatePublicIpAddress': True
    },
</code>```

Body:
Might help someone:
You have to put the SecurityGroupIds, and the subnetID as a network interface parameter, and remove them from the instance parameters, then it will run fine.

NetworkInterfaces=[
    {
        'DeviceIndex': 0,
        'SubnetId' : 'subnet-xxxxxx',
        'Groups': [
            'sg-xxxxxx','sg-xxxx','sg-xxxxxx'
        ],
        'AssociatePublicIpAddress': True
    },


问:
Angular2 callback vs Promise/Observable
Context:

I have AWS cognito working on an Angular 2 app. The AWS demo uses callbacks to handle asynchronous requests.

```<code>public getSession(callback: CognitoCallback) {
let cognitoUser: CognitoUser = this.getCurrentUser();
let cognitoUtil = this;
cognitoUser.getSession(function (err, session) {
  if (err) {
    let error = new CognitoError(err.name, err.message);
    callback.cognitoCallback(error, null);
    return;
  }
  if (!session.isValid()) {
    let error = new CognitoError("SessionInvalid", "Session is not valid");
    callback.cognitoCallback(error, session);
    return;
  }
  callback.cognitoCallback(null, session);
  cognitoUtil.setCurrentUser(cognitoUser);
  return;
});
</code>```

}

Is it possible to implement the same functionality with Promise or Observable?

Thanks in advance.

答:
Absolutely. RXJS natively gives a function to convert a callback to an Observable and use it exactly as you are thinking.

https://github.com/Reactive-Extensions/RxJS/blob/master/doc/api/core/operators/fromcallback.md

Title: Angular2 callback vs Promise/Observable

Body:
Context:

I have AWS cognito working on an Angular 2 app. The AWS demo uses callbacks to handle asynchronous requests.

public getSession(callback: CognitoCallback) {
let cognitoUser: CognitoUser = this.getCurrentUser();
let cognitoUtil = this;
cognitoUser.getSession(function (err, session) {
  if (err) {
    let error = new CognitoError(err.name, err.message);
    callback.cognitoCallback(error, null);
    return;
  }
  if (!session.isValid()) {
    let error = new CognitoError("SessionInvalid", "Session is not valid");
    callback.cognitoCallback(error, session);
    return;
  }
  callback.cognitoCallback(null, session);
  cognitoUtil.setCurrentUser(cognitoUser);
  return;
});

}

Is it possible to implement the same functionality with Promise or Observable?

Thanks in advance.


问:
Changes in package.json for Angular 2 to 4 migration
Currently, the application is on Angular 2.0.0. What are the packages or dependencies that need to be changed for compatibility with Angular 4?
So far i have changed the following,

```<code>"dependencies": {
"@angular/common": "4.0.0",
"@angular/compiler": "4.0.0",
"@angular/core": "4.0.0",
"@angular/forms": "4.0.0",
"@angular/http": "4.0.0",
"@angular/platform-browser": "4.0.0",
"@angular/platform-browser-dynamic": "4.0.0",
"@angular/router": "4.0.0",
"@angular/router-deprecated": "2.0.0-rc.2",
"@angular/upgrade": "4.0.0",
"angular2-toaster": "2.0.0",
"rxjs": "^5.0.1",
"typescript": "^2.1.5",
"zone.js": "^0.8.4"
}
</code>```

Are there any other packages/dependencies that needs to be changed?

Should I make changes to the tsconfig.json?

```<code>{

 "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "lib": [
      "es5",
      "es2015",
      "es2017",
      "dom",
      "scripthost"
    ],
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "sourceMap": true,
    "noEmitHelpers": true,
    "allowNonTsExtensions" : true
  },
  "exclude": [
    "node_modules",
    "typings/main.d.ts",
    "typings/main"
  ],
  "filesGlob": [
    "./src/**/*.ts",
    "./test/**/*.ts",
    "!./node_modules/**/*.ts",
    "src/custom_typings.d.ts",
    "typings/browser.d.ts"
  ],
  "awesomeTypescriptLoaderOptions": {
    "resolveGlobs": true,
    "forkChecker": true
  },
  "compileOnSave": false,
  "buildOnSave": false,
  "atom": { "rewriteTsconfig": false }
}
</code>```

答:
My solution in these situations is to use angular-cli to create a new project at the angular version I want (almost always the newest version for me), and then add in the other dependencies I need, allowing the package manager to sort out what version I should have, or asserting my opinion about that through my package manager command options.

This allows me to quickly build a vendor library and quickly test that it will all load without error using the "app works!" project that cli provides.

Once this process is done, you should have a package.json file that you can just cut and paste the dependency sections into your project.

One more thing to look at if you haven't... Yarn. Yarn is a newer package manager from our friends at facebook. It is newer, and therefore less tested than npm, but it has some really nice features and, at least in my setup, runs about 20x faster than npm. Another commmenter mentioned shrinkwrap which is a great tool, so I thought I would just point out another solution in that area.

Body:
Currently, the application is on Angular 2.0.0. What are the packages or dependencies that need to be changed for compatibility with Angular 4?
So far i have changed the following,

"dependencies": {
"@angular/common": "4.0.0",
"@angular/compiler": "4.0.0",
"@angular/core": "4.0.0",
"@angular/forms": "4.0.0",
"@angular/http": "4.0.0",
"@angular/platform-browser": "4.0.0",
"@angular/platform-browser-dynamic": "4.0.0",
"@angular/router": "4.0.0",
"@angular/router-deprecated": "2.0.0-rc.2",
"@angular/upgrade": "4.0.0",
"angular2-toaster": "2.0.0",
"rxjs": "^5.0.1",
"typescript": "^2.1.5",
"zone.js": "^0.8.4"
}

Are there any other packages/dependencies that needs to be changed?

Should I make changes to the tsconfig.json?

{

 "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "lib": [
      "es5",
      "es2015",
      "es2017",
      "dom",
      "scripthost"
    ],
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "sourceMap": true,
    "noEmitHelpers": true,
    "allowNonTsExtensions" : true
  },
  "exclude": [
    "node_modules",
    "typings/main.d.ts",
    "typings/main"
  ],
  "filesGlob": [
    "./src/**/*.ts",
    "./test/**/*.ts",
    "!./node_modules/**/*.ts",
    "src/custom_typings.d.ts",
    "typings/browser.d.ts"
  ],
  "awesomeTypescriptLoaderOptions": {
    "resolveGlobs": true,
    "forkChecker": true
  },
  "compileOnSave": false,
  "buildOnSave": false,
  "atom": { "rewriteTsconfig": false }
}


问:
Good practices on finding circular dependencies between spring beans
I have this exception:

```<code>SEVERE: Context initialization failedorg.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'myService': Bean with name 'myService' has been injected into other beans [otherService] in its raw version as part of a circular reference, but has eventually been wrapped. This means that said other beans do not use the final version of the bean. This is often the result of over-eager type matching - consider using 'getBeanNamesOfType' with the 'allowEagerInit' flag turned off, for example.
</code>```

Can anyone suggest good strategies for finding where the circular dependency comes from ?

I am currently looking through the context definition, but as you might imagine in a project of some maturity this takes quite a while.

So I'm generally looking for ideas on quickly finding circular bean dependencies.

答:
I know that OP's case is different, but for future reference:

If you have this exception:

org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'a': Requested bean is currently in creation: Is there an unresolvable circular reference?

Then the message at the top of the stack trace should say what is the dependency cycle, e.g.:

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'a' defined in file [filename]: Unsatisfied dependency expressed through constructor argument with index 0 of type [com.gk.simple.B]: Error creating bean with name 'b' defined in file [filename]: Unsatisfied dependency expressed through constructor argument with index 0 of type [com.gk.simple.A]: Error creating bean with name 'a': Requested bean is currently in creation: Is there an unresolvable circular reference?

Here the cycle is a -> b -> a.

Body:
I have this exception:

SEVERE: Context initialization failedorg.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'myService': Bean with name 'myService' has been injected into other beans [otherService] in its raw version as part of a circular reference, but has eventually been wrapped. This means that said other beans do not use the final version of the bean. This is often the result of over-eager type matching - consider using 'getBeanNamesOfType' with the 'allowEagerInit' flag turned off, for example.

Can anyone suggest good strategies for finding where the circular dependency comes from ?

I am currently looking through the context definition, but as you might imagine in a project of some maturity this takes quite a while.

So I'm generally looking for ideas on quickly finding circular bean dependencies.


问:
Ignore or not API endpoint parameters based on access level
I am working on an API endpoint that returns a list of products:

```<code>"api/products"
</code>```

The endpoint accepts the following parameters:

```<code>page_size
page_number
</code>```

Each product has a boolean property named IsApproved.

In the web application used by common users I always want to return only the Approved products ... On the web ADMIN application used by administrators I want to return all products, Approved or Not ...

My idea would be to add a new parameter (enumeration) named:

```<code>ApprovedStatus
</code>```

And the values would be Approved, NotApproved and All.

On each API call I would check the user permissions ... If is admin I will consider the value on this parameter. If not then I will always return only approved products.

Another solution would be to have different endpoints ...

Any advice on which approach to take or is there other options?

答:
Going with the principle of least astonishment, I'd be in favour of adding a second endpoint for admin users. Such that you'll have:

```<code>GET /api/products       (for regular users)
GET /api/admin/products (for admins)
</code>```

This allows your code and API documentation to be nicely separated, and all of the admin-specific authentication details can live under the "admin" namespace.

The intention behind each API call is also clearer this way, which helps developers; and means that you can differentiate between admin vs regular usage in any usage stats that you track.

With ApprovedStatus, I think the specifics here don't matter much, but - considering what a developer using the API might reasonably expect / assume - it would be good to:

Ensure the ApprovalStatus parameter name matches the property name for "approval" that you return with each product object

Defaults to "approved" if it is not specified

Alert the user when an invalid value is specified, or one that they don't have access to

Bottom line: to answer your headline question - I think it's bad practice to ignore user input... sometimes. Design your API such that distinctions around when input can be passed in is very clear; and always alert the user if you receive input values that are technically acceptable, but not in the way that the user has requested, or for their access level. Ignoring values that are plain wrong (e.g. an argument that doesn't exist) is another story, and can be useful for future proofing or backwards compatibility.

Body:
I am working on an API endpoint that returns a list of products:

"api/products"

The endpoint accepts the following parameters:

page_size
page_number

Each product has a boolean property named IsApproved.

In the web application used by common users I always want to return only the Approved products ... On the web ADMIN application used by administrators I want to return all products, Approved or Not ...

My idea would be to add a new parameter (enumeration) named:

ApprovedStatus

And the values would be Approved, NotApproved and All.

On each API call I would check the user permissions ... If is admin I will consider the value on this parameter. If not then I will always return only approved products.

Another solution would be to have different endpoints ...

Any advice on which approach to take or is there other options?

Body:
Going with the principle of least astonishment, I'd be in favour of adding a second endpoint for admin users. Such that you'll have:

GET /api/products       (for regular users)
GET /api/admin/products (for admins)

This allows your code and API documentation to be nicely separated, and all of the admin-specific authentication details can live under the "admin" namespace.

The intention behind each API call is also clearer this way, which helps developers; and means that you can differentiate between admin vs regular usage in any usage stats that you track.

With ApprovedStatus, I think the specifics here don't matter much, but - considering what a developer using the API might reasonably expect / assume - it would be good to:

Ensure the ApprovalStatus parameter name matches the property name for "approval" that you return with each product object

Defaults to "approved" if it is not specified

Alert the user when an invalid value is specified, or one that they don't have access to

Bottom line: to answer your headline question - I think it's bad practice to ignore user input... sometimes. Design your API such that distinctions around when input can be passed in is very clear; and always alert the user if you receive input values that are technically acceptable, but not in the way that the user has requested, or for their access level. Ignoring values that are plain wrong (e.g. an argument that doesn't exist) is another story, and can be useful for future proofing or backwards compatibility.


问:
how to sync Packages and settings for multiple computer in Github Atom Editor
I have installed Github Atom Editor in my Personal PC and Office PC.
I want to sync the settings and packages to my dropbox account so when i log in the office PC it automatically download or update all the packages and settings to my Home PC</p>

答:
If you don't absolutely need Dropbox, atom-package-sync is a package that I created a couple weeks ago. It works a little bit like the synchronization of Google Chrome, you just login and it syncs your packages and settings automatically across all your Atom instances.

I plan to release the source code for the server side in the coming weeks and add an export feature for alternative backups.