问:
Gradle sync failed Android studio 2.3.2
Gradle sync failed: A problem occurred configuring project ':app'. Consult IDE log for more details.

Hence I'm very new to the Android Studio just tried to setup for the first time.  Even I tried all the methods which mentioned for the gradle sync failed unfortunately nothing works. Please help to find the issue.

Classpath:

buildscript {
     repositories {
         jcenter()
     }
     dependencies {
         classpath 'com.android.tools.build:gradle:2.3.2'

```<code>   // NOTE: Do not place your application dependencies here; they >belong
   // in the individual module build.gradle files
</code>```

}
  }

Wrapper Properties :

Wed May 24 08:00:32 IST 2017

distributionBase=GRADLE_USER_HOME
  distributionPath=wrapper/dists
  zipStoreBase=GRADLE_USER_HOME
  zipStorePath=wrapper/dists
  distributionUrl=https://services.gradle.org/distributions/gradle-3.3-all.zip

Error while Re-Building :

```<code> Error:A problem occurred configuring project ':app'.
 > java.lang.NullPointerException (no error message)
</code>```

Thanks in advance

Update : Added Logs

Logs

答:
Follow these three steps:

Check if your project level build.gradle file has this line:

classpath 'com.android.tools.build:gradle:2.3.2'

Make sure your gradle-wrapper.properties file in gradle folder looks exactly like this:

Delete .gradle folder from your project directory
`

distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https://services.gradle.org/distributions/gradle-3.3-all.zip

`
 4. Build -> Clean Project
 5. File -> Invalidate Caches/Restart
 6. Build -> Rebuild Project

Title: Gradle sync failed Android studio 2.3.2

Body:
Gradle sync failed: A problem occurred configuring project ':app'. Consult IDE log for more details.

Hence I'm very new to the Android Studio just tried to setup for the first time.  Even I tried all the methods which mentioned for the gradle sync failed unfortunately nothing works. Please help to find the issue.

Classpath:

buildscript {
     repositories {
         jcenter()
     }
     dependencies {
         classpath 'com.android.tools.build:gradle:2.3.2'

   // NOTE: Do not place your application dependencies here; they >belong
   // in the individual module build.gradle files

}
  }

Wrapper Properties :

Wed May 24 08:00:32 IST 2017

distributionBase=GRADLE_USER_HOME
  distributionPath=wrapper/dists
  zipStoreBase=GRADLE_USER_HOME
  zipStorePath=wrapper/dists
  distributionUrl=https://services.gradle.org/distributions/gradle-3.3-all.zip

Error while Re-Building :

 Error:A problem occurred configuring project ':app'.
 > java.lang.NullPointerException (no error message)

Thanks in advance

Update : Added Logs

Logs


来源: stackexchange

问:
How to make Google Contact API work with AngularJS?
I have been trying to get the data from response and add it to controller, but no luck.

Here is my previous question.

How is it done in AngularJS?

答:
The code that I used for this is like this:

```<code>invitePeersController.getGmailContacts = function(){
    console.log("I come in gmail contacts");
    var clientId = "contact key";
    var apiKey = "apiKey";
    var scopes = "https://www.googleapis.com/auth/contacts.readonly";
    authorize();
    function authorize() {
        gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: false}, handleAuthorization);
    }
    function handleAuthorization(authorizationResult){
        invitePeersController.gmailContacts = [];
        var gmailData = [];
        if (authorizationResult && !authorizationResult.error){
            var urlContact = "https://www.google.com/m8/feeds/contacts/default/thin?alt=json&access_token=" + authorizationResult.access_token + "&max-results=50000&v=3.0";
            var promiseGoogleData = HttpService.httpGetExternalLink(urlContact);
            promiseGoogleData.then(function (response) {
                var jsonChildData = response.data.feed.entry;
                for(var i=0; i<jsonChildData.length ;i++){
                    var item = {};
                    try{
                        var name = jsonChildData[i].title.$t;
                        var email = jsonChildData[i].gd$email[0].address;

                        if(name.substring(1, name.length-1) && email.substring(1, email.length-1)){
                            item ["name"] = name.substring(1, name.length-1);
                            item ["email"] = email.substring(1, email.length-1);
                            item ["id"] =  email.substring(1, email.length-1).replace(/[^a-zA-Z ]/g, "");
                        invitePeersController.gmailContacts.push(item);
                        gmailData.push(item);
                       }

                    }catch(error){
                        console.log("Error is thrown while trying to read gmail resposne");
                }

            }
            $state.go("app.inviteContacts");
            InvitePeersService.setGmailContactsData( invitePeersController.gmailContacts);

                        return response;
                    })
                    .catch(function (error) {
                        console.log("Something went terribly wrong while trying to get Gmail Data.");
                    });
                }

            }

        }
</code>```

Also don't forget to add the domain names in the credentials:

ContentLicense: CC BY-SA 3.0

Body:
The code that I used for this is like this:

invitePeersController.getGmailContacts = function(){
    console.log("I come in gmail contacts");
    var clientId = "contact key";
    var apiKey = "apiKey";
    var scopes = "https://www.googleapis.com/auth/contacts.readonly";
    authorize();
    function authorize() {
        gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: false}, handleAuthorization);
    }
    function handleAuthorization(authorizationResult){
        invitePeersController.gmailContacts = [];
        var gmailData = [];
        if (authorizationResult && !authorizationResult.error){
            var urlContact = "https://www.google.com/m8/feeds/contacts/default/thin?alt=json&access_token=" + authorizationResult.access_token + "&max-results=50000&v=3.0";
            var promiseGoogleData = HttpService.httpGetExternalLink(urlContact);
            promiseGoogleData.then(function (response) {
                var jsonChildData = response.data.feed.entry;
                for(var i=0; i<jsonChildData.length ;i++){
                    var item = {};
                    try{
                        var name = jsonChildData[i].title.$t;
                        var email = jsonChildData[i].gd$email[0].address;

                        if(name.substring(1, name.length-1) && email.substring(1, email.length-1)){
                            item ["name"] = name.substring(1, name.length-1);
                            item ["email"] = email.substring(1, email.length-1);
                            item ["id"] =  email.substring(1, email.length-1).replace(/[^a-zA-Z ]/g, "");
                        invitePeersController.gmailContacts.push(item);
                        gmailData.push(item);
                       }

                    }catch(error){
                        console.log("Error is thrown while trying to read gmail resposne");
                }

            }
            $state.go("app.inviteContacts");
            InvitePeersService.setGmailContactsData( invitePeersController.gmailContacts);

                        return response;
                    })
                    .catch(function (error) {
                        console.log("Something went terribly wrong while trying to get Gmail Data.");
                    });
                }

            }

        }

Also don't forget to add the domain names in the credentials:


问:
How to create an array from calculations of another array excel vba
I am new to coding and trying to learn through VBA. What I am trying to do is calculate outliers in a data set following a procedure. My trouble is trying to identify the elements in the Data Set that are furthest from the mean (the outlier) and looping that k times. Most of the code is very messy as I have been trying to find out what is wrong so ignore the MsgBox's and ugly formatting. In the last part of my code I tried taking the elements from DataSet and subtracting them from the mean and storing those values in a new array. After that I would take absolute value of the elements in the Diff array and store them in a new array (Diff2). I know I could bypass Diff2 by just taking the absolute value of the calculation of Diff. When I run the code I get the type mismatch error and after some investigation i realized that Diff (and Diff2) are not arrays. If anyone knows of how I can make Diff an array or of a better workaround for this that would be much appreciated!</p>

```<code>Sub CalculateOutliers()
    Dim n As Integer
    Dim mean As Double
    Dim SD As Double
    Dim X As Integer
    Dim k As Integer
    Dim DataSet As Variant
    Dim ESDPrin As Double

    DataSet = Selection.Value
    'Copies highlighted data into DataSet variable
    'Cell A1 is (1,1) Because it starts at 0 which is out of range

    n = Selection.CountLarge
    'Counts number of entries
    'If n < 20 Then
        'MsgBox "Data set too small"
        'Exit Sub
    'End If
    'Ends Subroutine if data set is too small for this analysis

    If n < 50 Then
        k = Int(n / 10)
    Else
        k = 5
    End If
    'determines k = number of possible outliers

    mean = Application.WorksheetFunction.Average(DataSet)
    'Calculates mean of Data Set
    MsgBox mean & "Average"

    SD = Application.WorksheetFunction.StDev(DataSet)
    'Calculates Standard Deviation of Data Set

    Dim element As Variant
    Dim Diff As Variant

    For Each element In DataSet
        Diff = element - mean
        MsgBox Diff & " Difference"
    Next element

    Dim P As Integer
    Dim Outlier As Integer
    Dim Diff2 As Variant

    Diff2 = Abs(Diff)

    For P = 1 To k
        Outlier = UBound(Diff, 1)
        MsgBox Outlier
   Next P
End Sub
</code>```

答:
I think code would be like this</p>

```<code>Sub CalculateOutliers()
    Dim n As Integer
    Dim mean As Double
    Dim SD As Double
    Dim X As Integer
    Dim k As Integer
    Dim DataSet As Variant
    Dim ESDPrin As Double

    DataSet = Selection.Value
    'Copies highlighted data into DataSet variable
    'Cell A1 is (1,1) Because it starts at 0 which is out of range

    n = Selection.CountLarge
    'Counts number of entries
    'If n < 20 Then
        'MsgBox "Data set too small"
        'Exit Sub
    'End If
    'Ends Subroutine if data set is too small for this analysis

    If n < 50 Then
        k = Int(n / 10)
    Else
        k = 5
    End If
    'determines k = number of possible outliers

    mean = Application.WorksheetFunction.Average(DataSet)
    'Calculates mean of Data Set
    MsgBox mean & "Average"

    SD = Application.WorksheetFunction.StDev(DataSet)
    'Calculates Standard Deviation of Data Set

    Dim element As Variant
    Dim Diff() As Variant, Diff2() As Variant, j As Integer

    For Each element In DataSet
        j = j + 1
        ReDim Preserve Diff(1 To j): ReDim Preserve Diff2(1 To j)
        Diff(j) = element - mean
        Diff2(j) = Abs(Diff(j))
        MsgBox Diff(j) & " Difference"
        MsgBox Diff2(j) & " Difference abs "
    Next element
    MsgBox UBound(Diff)
    'Dim P As Integer
    'Dim Outlier As Integer
    'Dim Diff2 As Variant

End Sub
</code>```

Body:
I am new to coding and trying to learn through VBA. What I am trying to do is calculate outliers in a data set following a procedure. My trouble is trying to identify the elements in the Data Set that are furthest from the mean (the outlier) and looping that k times. Most of the code is very messy as I have been trying to find out what is wrong so ignore the MsgBox's and ugly formatting. In the last part of my code I tried taking the elements from DataSet and subtracting them from the mean and storing those values in a new array. After that I would take absolute value of the elements in the Diff array and store them in a new array (Diff2). I know I could bypass Diff2 by just taking the absolute value of the calculation of Diff. When I run the code I get the type mismatch error and after some investigation i realized that Diff (and Diff2) are not arrays. If anyone knows of how I can make Diff an array or of a better workaround for this that would be much appreciated!

Sub CalculateOutliers()
    Dim n As Integer
    Dim mean As Double
    Dim SD As Double
    Dim X As Integer
    Dim k As Integer
    Dim DataSet As Variant
    Dim ESDPrin As Double

    DataSet = Selection.Value
    'Copies highlighted data into DataSet variable
    'Cell A1 is (1,1) Because it starts at 0 which is out of range

    n = Selection.CountLarge
    'Counts number of entries
    'If n < 20 Then
        'MsgBox "Data set too small"
        'Exit Sub
    'End If
    'Ends Subroutine if data set is too small for this analysis

    If n < 50 Then
        k = Int(n / 10)
    Else
        k = 5
    End If
    'determines k = number of possible outliers

    mean = Application.WorksheetFunction.Average(DataSet)
    'Calculates mean of Data Set
    MsgBox mean & "Average"

    SD = Application.WorksheetFunction.StDev(DataSet)
    'Calculates Standard Deviation of Data Set

    Dim element As Variant
    Dim Diff As Variant

    For Each element In DataSet
        Diff = element - mean
        MsgBox Diff & " Difference"
    Next element

    Dim P As Integer
    Dim Outlier As Integer
    Dim Diff2 As Variant

    Diff2 = Abs(Diff)

    For P = 1 To k
        Outlier = UBound(Diff, 1)
        MsgBox Outlier
   Next P
End Sub

Body:
I think code would be like this

Sub CalculateOutliers()
    Dim n As Integer
    Dim mean As Double
    Dim SD As Double
    Dim X As Integer
    Dim k As Integer
    Dim DataSet As Variant
    Dim ESDPrin As Double

    DataSet = Selection.Value
    'Copies highlighted data into DataSet variable
    'Cell A1 is (1,1) Because it starts at 0 which is out of range

    n = Selection.CountLarge
    'Counts number of entries
    'If n < 20 Then
        'MsgBox "Data set too small"
        'Exit Sub
    'End If
    'Ends Subroutine if data set is too small for this analysis

    If n < 50 Then
        k = Int(n / 10)
    Else
        k = 5
    End If
    'determines k = number of possible outliers

    mean = Application.WorksheetFunction.Average(DataSet)
    'Calculates mean of Data Set
    MsgBox mean & "Average"

    SD = Application.WorksheetFunction.StDev(DataSet)
    'Calculates Standard Deviation of Data Set

    Dim element As Variant
    Dim Diff() As Variant, Diff2() As Variant, j As Integer

    For Each element In DataSet
        j = j + 1
        ReDim Preserve Diff(1 To j): ReDim Preserve Diff2(1 To j)
        Diff(j) = element - mean
        Diff2(j) = Abs(Diff(j))
        MsgBox Diff(j) & " Difference"
        MsgBox Diff2(j) & " Difference abs "
    Next element
    MsgBox UBound(Diff)
    'Dim P As Integer
    'Dim Outlier As Integer
    'Dim Diff2 As Variant

End Sub


问:
Undoing Git rebase --abort
I had local changes in my repository. before push , i fetch from remote and did rebasing it shows some conflicts and i fixed it.

and then i tried to push my changes , before commit it shows still need merge so i did rebase --abort without commiting my changes.
after that my local changes was gone.
i tried git reflog i dont find mine since i didnt commit.

I need my local changes how do i get it back? how rebase --abort delete my changes?

I did rebase --continue  once i fix conflict. since it says need update. then only i gave rebase --abort

答:
From your question along with what you commented above, it looks like you started a rebase, made some progress along the way, but did not complete it.  Instead, you typed git rebase --abort.  This effectively rolls back the entire rebase to the point where you were before you started the rebase.  There is no harm in aborting a rebase, save any work you already did resolving merge conflicts.

In any case, you should be able to just start the rebase origin/<branch> again.  This time around, just resolve the conflicts as each commit is applied by adding each conflicted file to the stage, and using git rebase --continue.  When all commits have been replayed, your rebased branch should be ready, with an empty working directory.

Title: Undoing Git rebase --abort


问:
using class to represent a task in c++
I'm writing a function to do a specific task. This function need some temporary data to process the task. The problem is if I do everything in this function then the size of this function will be big. Then I think about breaking this function into many small functions. But if I do that, I need to pass some temporary data to those small functions. It make the code look not very well. So I consider to create a class that have private data including input, output and temporary data and those small function become the method of class. Below is pseudo code to represent my idea.

```<code>/* big function */
output big_function(input)
{
    temporary_data data1;
    temporary_data data2;
    temporary_data data3;
    temporary_data data4;
    /* do task here*/
    ...
    return output;
}

/* many small function*/
output function1(input)
{
    temporary_data data1;
    temporary_data data2;
    temporary_data data3;
    temporary_data data4;
    /*do some thing */
    function2(input,data1,data2, data3, data4);
    output = function3(input,data1,data2, data3, data4);
    return output;
}

/* use class*/
class Task
{
public:
    Task(input);
    function1();
    output get_output();
private:
    function2();
    function3();
private:
    input;
    output;
    data1;
    data2;
    data3;
    data4;
}
</code>```

And my question is: using class to represent a task is a right way or not?

答:
Public interface, as well as internal structure, of your class depends on many factors:

how the class will be used (many instances or single, multithreaded or not, etc)

what is the temporary_data (structures, classes, collections/arrays, or just simple types)

volume of temporary data and place to store the data (what memory will be used - static, automatic (stack) or dynamic (heap))

other related matters (such as errors handling, input and output checking, etc.)

For the simplest implementation (one function call for solution that call other functions) my suggestion is to consider:

creation of class with one static method output solve_task(input) instead of three - Task(input) (constructor), function1() (running the solution) and output get_output() (getting the result)

private fields and methods have to be also static to be called from solve_task

solve_task can be as simple as possible, like

     output solve_task(input)
     {
        if(!check_input(input))
        {
            // reaction on wrong input
            throw(badInput);
        }
        // data preparation
        function1(input); // init private fields
        function2(input); // find/fill the temporary data
        // solution
        function3(); // works with internal temporary data
        ...
        functionN(); // works with internal temporary data
        // providing result
        return prepare_output()
     }
```

Title: using class to represent a task in c++

Body:
I'm writing a function to do a specific task. This function need some temporary data to process the task. The problem is if I do everything in this function then the size of this function will be big. Then I think about breaking this function into many small functions. But if I do that, I need to pass some temporary data to those small functions. It make the code look not very well. So I consider to create a class that have private data including input, output and temporary data and those small function become the method of class. Below is pseudo code to represent my idea.

/* big function */
output big_function(input)
{
    temporary_data data1;
    temporary_data data2;
    temporary_data data3;
    temporary_data data4;
    /* do task here*/
    ...
    return output;
}

/* many small function*/
output function1(input)
{
    temporary_data data1;
    temporary_data data2;
    temporary_data data3;
    temporary_data data4;
    /*do some thing */
    function2(input,data1,data2, data3, data4);
    output = function3(input,data1,data2, data3, data4);
    return output;
}

/* use class*/
class Task
{
public:
    Task(input);
    function1();
    output get_output();
private:
    function2();
    function3();
private:
    input;
    output;
    data1;
    data2;
    data3;
    data4;
}

And my question is: using class to represent a task is a right way or not?


问:
kwargs does not pass key-value parameters inside function, but does outside function
I want to create an empty pandas.DataFrame and add some columns to it using **kwargs.  The DataFrame remains empty when I try to populate it inside the function make_new_data_frame (I tried adding columns one by one, and all at once using kwargs).  However, if I return kwargs and err_df2 from the function, the operation works (in a jupyter notebook).  How can I get this to work inside the function, and why doesn't it?  MWE below

```<code>from pandas import DataFrame
def make_data_frame():
    df = DataFrame({'foo':[1,2,3], 'bar':[1.1,2.2,3.3]})
    return df
def make_new_data_frame():
    df = make_data_frame()
    err_df = DataFrame()
    kwargs = {}
    for c in df.columns:
        if c == 'foo':
            continue
        err_df.assign(**{c: df['foo'] - df[c]})
        kwargs[c] = df['foo'] - df[c]
    err_df2 = DataFrame()
    err_df2.assign(**kwargs)
    return err_df, err_df2, kwargs
err_df, err_df2, kwargs = make_new_data_frame()
print(err_df,'\n')
print(err_df2,'\n')
print(raw_data,'\n')
err_df2.assign(**kwargs)
</code>```

output:

```<code>Empty DataFrame
Columns: []
Index: []

Empty DataFrame
Columns: []
Index: []

{'bar': 0   -0.1
1   -0.2
2   -0.3
dtype: float64}

Out[26]:
bar
0   -0.1
1   -0.2
2   -0.3
</code>```

答:
To clarify an assumption built into your question, the dataframe is actually empty in both of your cases, inside and outside. It's not doing what you're expecting outside the function, either.

assign does not change the dataframe in place. The REPL environment is adding to the confusion that assign could be doing that, but it's not.

When you execute err_df2.assign(**kwargs) in your last line, the supposedly "correct" output that you see is just the new copy that results from the assign, printed in the interactive session. err_df2 itself is not changed.

So when you print the actual err_df2 dataframe—whether created "inside" or "outside"—you are seeing the empty DataFrame() you initialized, without any changes from assign.

Body:
I want to create an empty pandas.DataFrame and add some columns to it using **kwargs.  The DataFrame remains empty when I try to populate it inside the function make_new_data_frame (I tried adding columns one by one, and all at once using kwargs).  However, if I return kwargs and err_df2 from the function, the operation works (in a jupyter notebook).  How can I get this to work inside the function, and why doesn't it?  MWE below

from pandas import DataFrame
def make_data_frame():
    df = DataFrame({'foo':[1,2,3], 'bar':[1.1,2.2,3.3]})
    return df
def make_new_data_frame():
    df = make_data_frame()
    err_df = DataFrame()
    kwargs = {}
    for c in df.columns:
        if c == 'foo':
            continue
        err_df.assign(**{c: df['foo'] - df[c]})
        kwargs[c] = df['foo'] - df[c]
    err_df2 = DataFrame()
    err_df2.assign(**kwargs)
    return err_df, err_df2, kwargs
err_df, err_df2, kwargs = make_new_data_frame()
print(err_df,'\n')
print(err_df2,'\n')
print(raw_data,'\n')
err_df2.assign(**kwargs)

output:

Empty DataFrame
Columns: []
Index: []

Empty DataFrame
Columns: []
Index: []

{'bar': 0   -0.1
1   -0.2
2   -0.3
dtype: float64}

Out[26]:
bar
0   -0.1
1   -0.2
2   -0.3


问:
What's wrong with my function() in Shell Script! Syntax Token errors near {?
```<code>#!/bin/bash

# I get the newest file in Directory

latest_file=$(ls -t | head -n 1)
getAlldoublicate()

# getting Token syntax error here getAlldoublicate() '{

{
 Alldoublicate=$(tr -s ',' ' ' <latest_file  | awk  '{print $2" "$3" "$4}' | uniq -d)

# here I try to find dublicate rows in csv

 }
if [[ -s latest_file]] ; then

# here I check if file is emty

getAlldoublicate
else
cat "$latest_file"  | mailx -s "$latest_file is empty" bla..`@bla
fi
</code>```

答:
I guess this is your code.

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

# I get the newest file in Directory
latest_file=$(ls -t | head -n 1)

# getting Token syntax error here
getAlldoublicate()
{
    # here I try to find dublicate rows in csv
    Alldoublicate=$(tr -s ',' ' ' < $1 | awk '{print $2" "$3" "$4}' | uniq -d)
}

if [[ -s $latest_file ]]; then

# here I check if file is emty
    getAlldoublicate $latest_file
else
    cat $latest_file | mailx -s "$latest_file is empty" bla.. @bla
fi
</code>```

Three points you need to pay attention:

function must be defined first before being use.

You can pass the latest_file as an argument when calling getAlldoublicate. Then you could use it by $1 in the function. ($0 stands for the function being called itself).

It would be better if you read the How to Format Tutorials before asking questions.

Body:
I guess this is your code.

#!/bin/bash

# I get the newest file in Directory
latest_file=$(ls -t | head -n 1)

# getting Token syntax error here
getAlldoublicate()
{
    # here I try to find dublicate rows in csv
    Alldoublicate=$(tr -s ',' ' ' < $1 | awk '{print $2" "$3" "$4}' | uniq -d)
}

if [[ -s $latest_file ]]; then

# here I check if file is emty
    getAlldoublicate $latest_file
else
    cat $latest_file | mailx -s "$latest_file is empty" bla.. @bla
fi

Three points you need to pay attention:

function must be defined first before being use.

You can pass the latest_file as an argument when calling getAlldoublicate. Then you could use it by $1 in the function. ($0 stands for the function being called itself).

It would be better if you read the How to Format Tutorials before asking questions.


问:
C++: Failing to make a hash function for a Vertex object
So I'm trying to make a Graph class as part of another project. The vertices are stored in an adjacency list, which is defined by an unordered_map. I am trying to create a hash function to allow my Vertex class to be stored in this map, but I don't know what I am doing wrong. I get this error:

```<code>no matching function for call to ‘std::hash<Vertex<int> >::hash(int)’
</code>```

Here is my graph.h file

```<code>#ifndef GRAPH_GRAPH_H_
#define GRAPH_GRAPH_H_

#include <vector>
#include <unordered_map>

template <typename T>
class Vertex {
    private:
        T value;
    public:
        Vertex(T value);
        T getValue() const;
        void setValue(T value);

        //Equality check. This also requires an equality check to exist for T. If it does not (e.g. custom class), make sure you impemented one
        bool operator==(const Vertex<T>& v) const{
            return (this->value == v.value);
        }
};

template <typename T>
Vertex<T>::Vertex(T value) {
    this->value = value;
}

template <typename T>
T Vertex<T>::getValue() const{
    return this->value;
}

template <typename T>
void Vertex<T>::setValue(T value) {
    this->value = value;
}

//If you want to hash a vertex, T needs a way of being hashed
namespace std {
    template<typename T> struct hash<Vertex<T>> {
        size_t operator()(Vertex<T> const& v) const {
            return hash(v.getValue());
        }
    };
}

template <typename T>
class Graph {
private:
    //Now I know what you're thinking. Graph theory taught me that a graph needs a set of nodes, and an adjacency list.
    //All you've given us is an adjacency list.
    //Well, since we need to use our nodes as keys, the set of keys is equivalent to the set of nodes. So there.

    unordered_map<Vertex<T>, std::vector<Vertex<T>>> adjacencyList;

public:
    Graph(); //Needs a hash function. For example, if your vertices are storing std::pairs, we need a hash to convert the pair into a key
             //Since I don't know what you will be storing, you should provide a hash function
    ~Graph();
    //Since we are initialising a new object, v must be whatever we are using to initialise our vertices
    void addVertex(T value, std::vector<T> adjacent);
    void removeVertex(T value);
    void printGraph();
};

template <typename T>
Graph<T>::Graph() {
}

template <typename T>
Graph<T>::~Graph() {
}

template <typename T>
void Graph<T>::addVertex(T value, std::vector<T> adjacent) {
    //Check that the value does not already exist
    if (this->adjacencyList.find(Vertex<T>(value)) == this->adjacencyList.end()) {
        Vertex<T> v = Vertex<T>(value);
        std::vector<Vertex<T>> adj;
        for (unsigned int i = 0; i < adjacent.size(); i++) {
            Vertex<T> vAdj = Vertex<T>(adjacent[i]);
            adj.push_back(vAdj);
        }
        this->adjacencyList.insert(make_pair(v, adj));
    }
        //If the values does not exist, place it and the adjacency in there
        //Otherwise, do nothing

}

template <typename T>
void Graph<T>::removeVertex(T value) {
    //Check that the value does not already exist
    //if (this->adjacencyList.find(Vertex<T>(value)) != this->adjacencyList.end()) {
        this->adjacencyList.erase(Vertex<T>(value));
    //}
}

template <typename T>
void Graph<T>::printGraph() {

}
#endif /* GRAPH_GRAPH_H_ */
</code>```

答:
Vertex::getValue() can not be called inside hash<Vertex<T>> since it is not marked as const.

You would need to change its definition within the class to

```<code>template <typename T>
class Vertex {
    ...
    T getValue() const;
    ...
};
</code>```

While at it, you should probably apply the same change to operator== as well.

Body:
So I'm trying to make a Graph class as part of another project. The vertices are stored in an adjacency list, which is defined by an unordered_map. I am trying to create a hash function to allow my Vertex class to be stored in this map, but I don't know what I am doing wrong. I get this error:

no matching function for call to ‘std::hash<Vertex<int> >::hash(int)’

Here is my graph.h file

#ifndef GRAPH_GRAPH_H_
#define GRAPH_GRAPH_H_

#include <vector>
#include <unordered_map>

template <typename T>
class Vertex {
    private:
        T value;
    public:
        Vertex(T value);
        T getValue() const;
        void setValue(T value);

        //Equality check. This also requires an equality check to exist for T. If it does not (e.g. custom class), make sure you impemented one
        bool operator==(const Vertex<T>& v) const{
            return (this->value == v.value);
        }
};

template <typename T>
Vertex<T>::Vertex(T value) {
    this->value = value;
}

template <typename T>
T Vertex<T>::getValue() const{
    return this->value;
}

template <typename T>
void Vertex<T>::setValue(T value) {
    this->value = value;
}

//If you want to hash a vertex, T needs a way of being hashed
namespace std {
    template<typename T> struct hash<Vertex<T>> {
        size_t operator()(Vertex<T> const& v) const {
            return hash(v.getValue());
        }
    };
}

template <typename T>
class Graph {
private:
    //Now I know what you're thinking. Graph theory taught me that a graph needs a set of nodes, and an adjacency list.
    //All you've given us is an adjacency list.
    //Well, since we need to use our nodes as keys, the set of keys is equivalent to the set of nodes. So there.

    unordered_map<Vertex<T>, std::vector<Vertex<T>>> adjacencyList;

public:
    Graph(); //Needs a hash function. For example, if your vertices are storing std::pairs, we need a hash to convert the pair into a key
             //Since I don't know what you will be storing, you should provide a hash function
    ~Graph();
    //Since we are initialising a new object, v must be whatever we are using to initialise our vertices
    void addVertex(T value, std::vector<T> adjacent);
    void removeVertex(T value);
    void printGraph();
};

template <typename T>
Graph<T>::Graph() {
}

template <typename T>
Graph<T>::~Graph() {
}

template <typename T>
void Graph<T>::addVertex(T value, std::vector<T> adjacent) {
    //Check that the value does not already exist
    if (this->adjacencyList.find(Vertex<T>(value)) == this->adjacencyList.end()) {
        Vertex<T> v = Vertex<T>(value);
        std::vector<Vertex<T>> adj;
        for (unsigned int i = 0; i < adjacent.size(); i++) {
            Vertex<T> vAdj = Vertex<T>(adjacent[i]);
            adj.push_back(vAdj);
        }
        this->adjacencyList.insert(make_pair(v, adj));
    }
        //If the values does not exist, place it and the adjacency in there
        //Otherwise, do nothing

}

template <typename T>
void Graph<T>::removeVertex(T value) {
    //Check that the value does not already exist
    //if (this->adjacencyList.find(Vertex<T>(value)) != this->adjacencyList.end()) {
        this->adjacencyList.erase(Vertex<T>(value));
    //}
}

template <typename T>
void Graph<T>::printGraph() {

}
#endif /* GRAPH_GRAPH_H_ */

Body:
Vertex::getValue() can not be called inside hash<Vertex<T>> since it is not marked as const.

You would need to change its definition within the class to

template <typename T>
class Vertex {
    ...
    T getValue() const;
    ...
};

While at it, you should probably apply the same change to operator== as well.


问:
heap overflow affecting other programs
I was trying to create the condition for malloc to return a NULL pointer. In the below program, though I can see malloc returning NULL, once the program is forcebly terminated, I see that all other programs are becoming slow and finally I had to reboot the system. So my question is whether the memory for heap is shared with other programs? If not, other programs should not have affected. Is OS is not allocating certain amount of memory at the time of execution? I am using windows 10, Mingw.</p>

```<code>#include <stdio.h>
#include <malloc.h>

void mallocInFunction(void)
{
    int *ptr=malloc(500);
    if(ptr==NULL)
    {
        printf("Memory Could not be allocated\n");
    }
    else
    {
        printf("Allocated memory successfully\n");
    }
}

int main (void)
{
    while(1)
    {
        mallocInFunction();
    }

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

答:
... whether the memory for heap is shared with other programs?

Well, the C standard doesn't exactly require a heap, but in the context of a task-switching, multi-user and multi-threaded OS, of course memory is shared between processes! The C standard doesn't require any of this, but this is all pretty common stuff:

CPU cache memory tends to be preferred for code that's executed often, though this might get swapped around quite a bit; that may or may not be swapped to a heap.

Task switching causes registers to be swapped to other forms of memory; that may or may not be swapped to a heap.

Entire pages are swapped to and from disk, so that other programs can make use of them when your OS switches execution away from your program and to the other programs, and when it's your programs turn to execute again among other reasons. This may or may not involve manipulating the heap.

FWIW, you're referring to memory that has allocated storage duration. It's best to avoid using terms like heap and stack, as they're virtually meaningless. The memory you're referring to is on a silicon chip, regardless of whether it uses a heap or a stack.

... Is OS is not allocating certain amount of memory at the time of execution?

Speaking of silicon chips and execution, your OS likely only has control of one processor (a silicon chip which contains some logic circuits and memory, among other things I'm sure) with which to execute many programs! To summarise this post, yes, your program is most likely sharing those silicon chips with other programs!

On a tangential note, I don't think heap overflow means what you think it means.

Title: heap overflow affecting other programs

Body:
I was trying to create the condition for malloc to return a NULL pointer. In the below program, though I can see malloc returning NULL, once the program is forcebly terminated, I see that all other programs are becoming slow and finally I had to reboot the system. So my question is whether the memory for heap is shared with other programs? If not, other programs should not have affected. Is OS is not allocating certain amount of memory at the time of execution? I am using windows 10, Mingw.

#include <stdio.h>
#include <malloc.h>

void mallocInFunction(void)
{
    int *ptr=malloc(500);
    if(ptr==NULL)
    {
        printf("Memory Could not be allocated\n");
    }
    else
    {
        printf("Allocated memory successfully\n");
    }
}

int main (void)
{
    while(1)
    {
        mallocInFunction();
    }

    return(0);
}


问:
Java: Writing array to text file inconsistencies
For a class project, a group and I have been working on an application that reads in lines of text from a text file and can encrypt it, decrypt it (both using DES), and calculate an MD5 hash.  The program reads in text and encrypts it just fine, writing the array of now encrypted strings back into the text file in the order in which they were read, line by line with all requisite carriage returns.

However, when decrypting these strings, the program writes the plaintext to the file all on one line, with no spaces or carriage returns.  Both the encrypt and decrypt methods use the same fileWrite class, which uses a buffered writer.  I have added a System.out.println statement for debugging purposes to print out the contents of the arrays as they are being encrypted and decrypted to check for errors in storage, but I can't find any.

Even when I artificially insert carriage returns by way of the "\n" symbol, the text file is all one line after it's decrypted.  I cannot for the life of me figure out why the same class would behave in two different ways at different times. The code to write the array to the file is simple enough, and just proceeds element by element and probably doesn't really need to be included, but here it is anyway.

```<code>    for(int i=0;i<s.length;i++){
    bufferedWriter.write(s[i]);
    }
</code>```

From what I can gather, the issue potentially stems from how java and notepad handle new lines differently.  When it is reading the plaintext strings from the file, I'm assuming it receives the line breaks from the text file and prints out the encrypted text in this manner, but here java denotes a new line differently than it was originally in the file, leading to this spacing issue when these encrypted lines are then read and processed, but again, I'm not really sure, which is why I'm here. Any help would be appreciated.

答:
Try using a PrintWritter, if you can, using the method println().

I believe the write() method does not change lines, you can force that by using the newLine() method.

Also careful that when reading from the file most methods do not return the line feed.

ContentLicense: CC BY-SA 2.5

Body:
For a class project, a group and I have been working on an application that reads in lines of text from a text file and can encrypt it, decrypt it (both using DES), and calculate an MD5 hash.  The program reads in text and encrypts it just fine, writing the array of now encrypted strings back into the text file in the order in which they were read, line by line with all requisite carriage returns.

However, when decrypting these strings, the program writes the plaintext to the file all on one line, with no spaces or carriage returns.  Both the encrypt and decrypt methods use the same fileWrite class, which uses a buffered writer.  I have added a System.out.println statement for debugging purposes to print out the contents of the arrays as they are being encrypted and decrypted to check for errors in storage, but I can't find any.

Even when I artificially insert carriage returns by way of the "\n" symbol, the text file is all one line after it's decrypted.  I cannot for the life of me figure out why the same class would behave in two different ways at different times. The code to write the array to the file is simple enough, and just proceeds element by element and probably doesn't really need to be included, but here it is anyway.

    for(int i=0;i<s.length;i++){
    bufferedWriter.write(s[i]);
    }

From what I can gather, the issue potentially stems from how java and notepad handle new lines differently.  When it is reading the plaintext strings from the file, I'm assuming it receives the line breaks from the text file and prints out the encrypted text in this manner, but here java denotes a new line differently than it was originally in the file, leading to this spacing issue when these encrypted lines are then read and processed, but again, I'm not really sure, which is why I'm here. Any help would be appreciated.


问:
wondering if there is an efficient way to shorten this code
So my program is going to end up being fairly large and I don't want a whole lot of code that could just be shortened. Here is one instance I am looking for some tips on:

```<code>private void bookComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
    string books = null;
    // sets books to the clicked item
    books = bookComboBox.SelectedItem.ToString();
    selectedPictureBox.Visible = true;
    // Loads string to list box and image to selectedPictureBox when programming is selected
    if (books == "Programming")
    {
        bookListBox.Items.Clear();
        selectedPictureBox.Image = Image.FromFile("programming.png");
        bookListBox.Items.Add("Visual Basic");
        bookListBox.Items.Add("Java");
        bookListBox.Items.Add("C#");
    }
    // Loads string to list box and image to selectedPictureBox when Networking is selected
    else if (books == "Networking")
    {
        bookListBox.Items.Clear();
        selectedPictureBox.Image = Image.FromFile("networking.png");
        bookListBox.Items.Add("LAN Networks");
        bookListBox.Items.Add("Windows Networking");
        bookListBox.Items.Add("More About Networking");
    }
    // Loads string to list box and image to selectedPictureBox when Web is selected
    else if (books == "Web")
    {
        bookListBox.Items.Clear();
        selectedPictureBox.Image = Image.FromFile("html.png");
        bookListBox.Items.Add("Web Programming");
        bookListBox.Items.Add("JavaScript");
        bookListBox.Items.Add("ASP");
    }
}
</code>```

The code works fine but I was just hoping to get some tips on shortening this code if necessary, any input is appreciated.

答:
I do not have visual studio, so giving you the points/suggestions to improve on.

switch should be preferred over if-elseif.

bookListBox.Items.Clear(); and selectedPictureBox.Image out of if block. Use a variable to set the image file name.

Body:
So my program is going to end up being fairly large and I don't want a whole lot of code that could just be shortened. Here is one instance I am looking for some tips on:

private void bookComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
    string books = null;
    // sets books to the clicked item
    books = bookComboBox.SelectedItem.ToString();
    selectedPictureBox.Visible = true;
    // Loads string to list box and image to selectedPictureBox when programming is selected
    if (books == "Programming")
    {
        bookListBox.Items.Clear();
        selectedPictureBox.Image = Image.FromFile("programming.png");
        bookListBox.Items.Add("Visual Basic");
        bookListBox.Items.Add("Java");
        bookListBox.Items.Add("C#");
    }
    // Loads string to list box and image to selectedPictureBox when Networking is selected
    else if (books == "Networking")
    {
        bookListBox.Items.Clear();
        selectedPictureBox.Image = Image.FromFile("networking.png");
        bookListBox.Items.Add("LAN Networks");
        bookListBox.Items.Add("Windows Networking");
        bookListBox.Items.Add("More About Networking");
    }
    // Loads string to list box and image to selectedPictureBox when Web is selected
    else if (books == "Web")
    {
        bookListBox.Items.Clear();
        selectedPictureBox.Image = Image.FromFile("html.png");
        bookListBox.Items.Add("Web Programming");
        bookListBox.Items.Add("JavaScript");
        bookListBox.Items.Add("ASP");
    }
}

The code works fine but I was just hoping to get some tips on shortening this code if necessary, any input is appreciated.


问:
VBA regex and group
applying the below regex on below email body:

```<code>(pls[a-zA-Z0-9 .*-]*) \(([A-Z 0-9]*)\)
</code>```

email body:

```<code>pls18244a.lam64*fra-pth (PI000581)
pls18856a.10ge*fra-pth (PI0005AW)
pls25040a.10ge*fra-pth (IIE0004WK)
pls27477a.10ge*fra-pth (WL050814)
pls22099a.stm4*par-pth (PI0005TE)
</code>```

returns 5 match, with two groups. what is the VBA script to get groups in each match using using incremental variable to copy each match groups in excel row?

答:
Not making any changes to your regular expression pattern. Using the following way, you can iterate through the groups of each match:</p>

```<code>str="pls18244a.lam64*fra-pth (PI000581)pls18856a.10ge*fra-pth (PI0005AW)pls25040a.10ge*fra-pth (IIE0004WK)pls27477a.10ge*fra-pth (WL050814)pls22099a.stm4*par-pth (PI0005TE)"
Set objReg = New RegExp
objReg.IgnoreCase=False
objReg.Global=True
objReg.Pattern = "(pls[a-zA-Z0-9 .*-]*) \(([A-Z 0-9]*)\)"
Set objMatches = objReg.Execute(str)
For Each match In objMatches             'The variable match will contain the full match
    a= match.Submatches.Count            'total number of groups in the full match
    For i=0 To a-1
        MsgBox match.Submatches.Item(i)  'display each group
    Next
Next
Set objReg = Nothing
</code>```

Title: VBA regex and group

Body:
applying the below regex on below email body:

(pls[a-zA-Z0-9 .*-]*) \(([A-Z 0-9]*)\)

email body:

pls18244a.lam64*fra-pth (PI000581)
pls18856a.10ge*fra-pth (PI0005AW)
pls25040a.10ge*fra-pth (IIE0004WK)
pls27477a.10ge*fra-pth (WL050814)
pls22099a.stm4*par-pth (PI0005TE)

returns 5 match, with two groups. what is the VBA script to get groups in each match using using incremental variable to copy each match groups in excel row?

Body:
Not making any changes to your regular expression pattern. Using the following way, you can iterate through the groups of each match:

str="pls18244a.lam64*fra-pth (PI000581)pls18856a.10ge*fra-pth (PI0005AW)pls25040a.10ge*fra-pth (IIE0004WK)pls27477a.10ge*fra-pth (WL050814)pls22099a.stm4*par-pth (PI0005TE)"
Set objReg = New RegExp
objReg.IgnoreCase=False
objReg.Global=True
objReg.Pattern = "(pls[a-zA-Z0-9 .*-]*) \(([A-Z 0-9]*)\)"
Set objMatches = objReg.Execute(str)
For Each match In objMatches             'The variable match will contain the full match
    a= match.Submatches.Count            'total number of groups in the full match
    For i=0 To a-1
        MsgBox match.Submatches.Item(i)  'display each group
    Next
Next
Set objReg = Nothing


问:
Importing json2csv module in Angular 4
I am trying to use this library in my application to convert JSON data to CSV file format. I installed the lib into my project as it mentions  https://www.npmjs.com/package/json2csv

npm install json2csv --save.

I also see the module in my node_module folder. Then in my component class i am calling it like so

 import { json2csv } from 'json2csv';

But then I get this error

[ts] Module '"c:/dev/angularworkspace/tntzweb/node_modules/json2csv/index"' has no exported member 'json2csv'.

Can someone please help me!!

答:
Change the import to:

```<code>import * as json2csv  from 'json2csv';
</code>```

Then implement as:

```<code>  let fields = ['field1', 'field2', 'field3'];
  let result = json2csv({ data:[{ field1: 'a', field2: 'b', field3: 'c' }], fields: fields });
  console.log(result);
</code>```

Title: Importing json2csv module in Angular 4

Body:
Change the import to:

import * as json2csv  from 'json2csv';

Then implement as:

  let fields = ['field1', 'field2', 'field3'];
  let result = json2csv({ data:[{ field1: 'a', field2: 'b', field3: 'c' }], fields: fields });
  console.log(result);


问:
Data Annotation table columns
```<code>public partial class Employee
{
    public int Emp_Id { get; set; }
    public string Emp_Name { get; set; }
    public string Emp_City { get; set; }
    public Nullable<int> Emp_Age { get; set; }
}
</code>```

This is generated class for table Employee using EF. I want Emp_Name change to EmpName in application without changing table structure. But using below changes using data annotation dbEntity.Set<Employee>().ToList();  getting exception

"The entity type Employee is not part of the model for the current
  context."

System.InvalidOperationException.

How can solve this

```<code>public partial class Employee
{
    public int Emp_Id { get; set; }
    [Column("Emp_Name")]
    public string EmpName { get; set; }
    public string Emp_City { get; set; }
    public Nullable<int> Emp_Age { get; set; }
}
</code>```

答:
It seems you are using Database First approach. Do the following to change the property name without changing the column name:

Just double click your .edmx file and it will show the tables.

Find your table, right click the column name > Rename

Give it a new name of your choice

It will keep this name and if you update your EDMX, it will still keep it. However, if you delete the EDMX and regenerate it, then you would need to do the renaming again.

Title: Data Annotation table columns

Body:
public partial class Employee
{
    public int Emp_Id { get; set; }
    public string Emp_Name { get; set; }
    public string Emp_City { get; set; }
    public Nullable<int> Emp_Age { get; set; }
}

This is generated class for table Employee using EF. I want Emp_Name change to EmpName in application without changing table structure. But using below changes using data annotation dbEntity.Set<Employee>().ToList();  getting exception

"The entity type Employee is not part of the model for the current
  context."

System.InvalidOperationException.

How can solve this

public partial class Employee
{
    public int Emp_Id { get; set; }
    [Column("Emp_Name")]
    public string EmpName { get; set; }
    public string Emp_City { get; set; }
    public Nullable<int> Emp_Age { get; set; }
}


问:
How to fixed this error in Contact Form & multi step
I`m using Contact form Multi Step plugin in wordpress, i have 5 form and everytime I press the previous button it will not redirect to the previous form

Hi guys Everytime I press the previous button it has an error:

Error:

```<code>    {"code":"rest_no_route","message":"No route was found matching the URL and
    request method","data":{"status":404}}
</code>```

Additional:
And Everytime i submit the thank you message appear

答:
The answer below is an unofficial fix of a bug with Contact Form 7 Multi-Step Forms v2.1 on WordPress v4.7.5.

The plugin does not work properly anymore according to the author's update.

UPDATE:  This plugin still works as expected for most people, but it does not for some.

To fix this, you will have to edit some codes of the plugin.

Update this function in wp-content/plugins/contact-form-7-multi-step-module/form-tags/module-back.php.

```<code>/**
 * Handle the back form shortcode.
 */
function cf7msm_back_shortcode_handler( $tag ) {
    if (!class_exists('WPCF7_Shortcode') || !function_exists('wpcf7_form_controls_class'))
        return;
    $tag = new WPCF7_Shortcode( $tag );

    $class = wpcf7_form_controls_class( $tag->type );

    $atts = array();

    $atts['class'] = $tag->get_class_option( $class );
    $atts['id'] = $tag->get_id_option();
    $atts['tabindex'] = $tag->get_option( 'tabindex', 'int', true );

    $value = isset( $tag->values[0] ) ? $tag->values[0] : '';
    $previous_url = isset( $tag->values[1] ) ? $tag->values[1] : '.';
    if ( empty( $value ) ) {
        if ( $tag->type == 'previous') {
            $value = __( 'Previous', 'contact-form-7-multi-step-module' );
        }
        else {
            //using old version
            $value = __( 'Back', 'contact-form-7-multi-step-module' );
        }
    }

    $atts['type'] = 'button';
    $atts['value'] = $value;
    $atts['href'] = $previous_url;

    $atts = wpcf7_format_atts( $atts );

    $html = sprintf( '<input %1$s />', $atts );

    return $html;
}
</code>```

And update 1 line in wp-content/plugins/contact-form-7-multi-step-module/resources/cf7msm.js changing

```<code>window.location.href = val[step_field.val()];
</code>```

to

```<code>window.location.href = $(this).attr('href');
</code>```

Finally, you need to change how you insert [previous] tag in contact form. After making the changes above, the [previous] tag works like so.

```<code>[previous "Button Label" "URL of previous step"]
</code>```

Body:
I`m using Contact form Multi Step plugin in wordpress, i have 5 form and everytime I press the previous button it will not redirect to the previous form

Hi guys Everytime I press the previous button it has an error:

Error:

    {"code":"rest_no_route","message":"No route was found matching the URL and
    request method","data":{"status":404}}

Additional:
And Everytime i submit the thank you message appear

Body:
The answer below is an unofficial fix of a bug with Contact Form 7 Multi-Step Forms v2.1 on WordPress v4.7.5.

The plugin does not work properly anymore according to the author's update.

UPDATE:  This plugin still works as expected for most people, but it does not for some.

To fix this, you will have to edit some codes of the plugin.

Update this function in wp-content/plugins/contact-form-7-multi-step-module/form-tags/module-back.php.

/**
 * Handle the back form shortcode.
 */
function cf7msm_back_shortcode_handler( $tag ) {
    if (!class_exists('WPCF7_Shortcode') || !function_exists('wpcf7_form_controls_class'))
        return;
    $tag = new WPCF7_Shortcode( $tag );

    $class = wpcf7_form_controls_class( $tag->type );

    $atts = array();

    $atts['class'] = $tag->get_class_option( $class );
    $atts['id'] = $tag->get_id_option();
    $atts['tabindex'] = $tag->get_option( 'tabindex', 'int', true );

    $value = isset( $tag->values[0] ) ? $tag->values[0] : '';
    $previous_url = isset( $tag->values[1] ) ? $tag->values[1] : '.';
    if ( empty( $value ) ) {
        if ( $tag->type == 'previous') {
            $value = __( 'Previous', 'contact-form-7-multi-step-module' );
        }
        else {
            //using old version
            $value = __( 'Back', 'contact-form-7-multi-step-module' );
        }
    }

    $atts['type'] = 'button';
    $atts['value'] = $value;
    $atts['href'] = $previous_url;

    $atts = wpcf7_format_atts( $atts );

    $html = sprintf( '<input %1$s />', $atts );

    return $html;
}

And update 1 line in wp-content/plugins/contact-form-7-multi-step-module/resources/cf7msm.js changing

window.location.href = val[step_field.val()];

to

window.location.href = $(this).attr('href');

Finally, you need to change how you insert [previous] tag in contact form. After making the changes above, the [previous] tag works like so.

[previous "Button Label" "URL of previous step"]


问:
Deleting "Android\sdk" folder from the path "C:\User\AppData\Local\Android\Sdk"
Will it cause any problem if I delete the "Android\sdk" [Size: 2 GB] folder from an old directory path "C:\User\AppData\Local\Android\Sdk" ?
I actually do have another "Android\sdk" folder [Size: 23 GB] on a different location [Local Disk D] since previously I faced WHITESPACE NAMING ISSUES while using Android Studio. So I think the folder is lying idle on my Local Disk C. Should I delete the folder on the path "C:\User\AppData\Local\Android\Sdk" ? Or, will it harm the IDE in the future ?

答: No it will not harm your development and IDE, but make sure that before deleting this sdk folder, the Android Studio SDK path has been set to the other targeting SDK. You can completely delete the one which you are not using.</p>


问:
TypeError: Cannot read property 'Symbol(Symbol.toStringTag)' of undefined
I have encountered an unfortunate bug when attempting to run my bot written in Node.js.

Whenever attempting to run the init script which calls various other functions of the bot, I am given the following error of "TypeError: Cannot read property 'Symbol(Symbol.toStringTag)' of undefined" at various different points in my code. I understand that this is one of the standard functions from JavaScript, so I am unsure why it is giving me an error.

The odd part is these errors are new, and I have run the scripts before many times without running into this issue.

Below is the first error line in async.js which shows at line 175.

```<code>174 function isAsync(fn) {
175    return supportsSymbol && fn[Symbol.toStringTag] === 'AsyncFunction';
176 }
</code>```

And a second example is in my own bot_startup.js at line 43.

```<code>43 connectToServerCallback(null, "connected");
</code>```

It seems like it is erroring out whenever trying to convert data to strings, but I do not know how I would go about fixing this. Any help would be appreciated.

答:
For those wondering, I was able to fix this problem on my own. </p>

<p>The error itself arose from one of the functions being called in async.waterfall not being correctly defined (an error in committing to Git rolled back one of the files it was calling functions from, making the function call no longer valid). </p>

Body:
I have encountered an unfortunate bug when attempting to run my bot written in Node.js.

Whenever attempting to run the init script which calls various other functions of the bot, I am given the following error of "TypeError: Cannot read property 'Symbol(Symbol.toStringTag)' of undefined" at various different points in my code. I understand that this is one of the standard functions from JavaScript, so I am unsure why it is giving me an error.

The odd part is these errors are new, and I have run the scripts before many times without running into this issue.

Below is the first error line in async.js which shows at line 175.

174 function isAsync(fn) {
175    return supportsSymbol && fn[Symbol.toStringTag] === 'AsyncFunction';
176 }

And a second example is in my own bot_startup.js at line 43.

43 connectToServerCallback(null, "connected");

It seems like it is erroring out whenever trying to convert data to strings, but I do not know how I would go about fixing this. Any help would be appreciated.

Body:
For those wondering, I was able to fix this problem on my own.

The error itself arose from one of the functions being called in async.waterfall not being correctly defined (an error in committing to Git rolled back one of the files it was calling functions from, making the function call no longer valid).


问:
Can't see why I have "no implicit conversion from nil to integer" error
Hey guys I'm having an issue with this problem. I'm doing exercises from a book and this is one of them.

A collection of spelling blocks has two letters per block, as shown in this list:

```<code>B:O   X:K   D:Q   C:P   N:A
G:T   R:E   F:S   J:W   H:U
V:I   L:Y   Z:M
</code>```

This limits the words you can spell with the blocks to just those words that do not use both letters from any given block. Each block can only be used once.

Write a method that returns true if the word passed in as an argument can be spelled from this set of blocks, false otherwise.

Examples:

```<code>block_word?('BATCH') == true
block_word?('BUTCH') == false
block_word?('jest') == true
</code>```

This is my attempt at a solution. I'm reading in the collection from a text document.

```<code>  text = []
    File.open('example2.txt').each { |line| text << line }
    @pair1 = []
    @pair2 = []
    text.join('').split('   ').each {|x, i| @pair1 << x[0].to_s; @pair2 << x[2].to_s}

    def block_word?(word)
      word = word.upcase
      @pair1.map {|x, i| word.include?(x) && word.include?(@pair2[i]) }.include?(true)
    end

    block_word?('BATCH') == true
    block_word?('BUTCH') == false
    block_word?('jest') == true
</code>```

I'm getting this error. Not sure why.

```<code>rb2.rb:10:in `[]': no implicit conversion from nil to integer (TypeError)
        from rb2.rb:10:in `block in block_word?'
        from rb2.rb:10:in `map'
        from rb2.rb:10:in `block_word?'
        from rb2.rb:13:in `<main>'
</code>```

答:
This error raised, because you've trying to access array @pair2 with nil index. map method doesn't send index as second argument to provided block. To add them you can add each_with_index method before map. Also see this question.

```<code>@pair1.each_with_index
   .map{ |x, i| word.include?(x) && word.include?(@pair2[i]) }
   .include?(true)
</code>```

Try this code, it will help to understand what's happen:

```<code>pair2 = []
puts pair2[nil] # will raise the same exception
</code>```

Body:
Hey guys I'm having an issue with this problem. I'm doing exercises from a book and this is one of them.

A collection of spelling blocks has two letters per block, as shown in this list:

B:O   X:K   D:Q   C:P   N:A
G:T   R:E   F:S   J:W   H:U
V:I   L:Y   Z:M

This limits the words you can spell with the blocks to just those words that do not use both letters from any given block. Each block can only be used once.

Write a method that returns true if the word passed in as an argument can be spelled from this set of blocks, false otherwise.

Examples:

block_word?('BATCH') == true
block_word?('BUTCH') == false
block_word?('jest') == true

This is my attempt at a solution. I'm reading in the collection from a text document.

  text = []
    File.open('example2.txt').each { |line| text << line }
    @pair1 = []
    @pair2 = []
    text.join('').split('   ').each {|x, i| @pair1 << x[0].to_s; @pair2 << x[2].to_s}

    def block_word?(word)
      word = word.upcase
      @pair1.map {|x, i| word.include?(x) && word.include?(@pair2[i]) }.include?(true)
    end

    block_word?('BATCH') == true
    block_word?('BUTCH') == false
    block_word?('jest') == true

I'm getting this error. Not sure why.

rb2.rb:10:in `[]': no implicit conversion from nil to integer (TypeError)
        from rb2.rb:10:in `block in block_word?'
        from rb2.rb:10:in `map'
        from rb2.rb:10:in `block_word?'
        from rb2.rb:13:in `'

Body:
This error raised, because you've trying to access array @pair2 with nil index. map method doesn't send index as second argument to provided block. To add them you can add each_with_index method before map. Also see this question.

@pair1.each_with_index
   .map{ |x, i| word.include?(x) && word.include?(@pair2[i]) }
   .include?(true)

Try this code, it will help to understand what's happen:

pair2 = []
puts pair2[nil] # will raise the same exception


问:
Silverstripe: CMS Pages as JSON?
I am working on a Silverstripe project and I would like to have a simple way to present the content of a CMS generated Page (or subtype of Page) as JSON.

Ideally, I would like to append "/json" at the end of the route, or send a parameter via post (json=true) and obtain a response in JSON format.

I tried adding an action to my CustomPage_Controller class like this:

```<code>public static $allowed_actions = array('json');
public function json(SS_HTTPRequest $request) {
    // ...
}
</code>```

But I cannot figure out how to make that work:

What URL/Route should I use?

How do I get the content of the page?

答:
Shane's answer was helpful, however I needed to output all pages from a route, not just the current record.

Here is how I managed to do this :

```<code><?php

class Page_Controller extends ContentController {

    private static $allowed_actions = [
        'index',
    ];

    public function init() {
        parent::init();
        // You can include any CSS or JS required by your project here.
        // See: http://doc.silverstripe.org/framework/en/reference/requirements
    }

    public function index(SS_HTTPRequest $request) {
        $results = [];
        $f = new JSONDataFormatter();
        foreach (Article::get() as $pageObj) {
            $results[] = $f->convertDataObjectToJSONObject($pageObj);
        }

        $this->response->addHeader('Content-Type', 'application/json');
        return json_encode($results);
    }
}
</code>```

Title: Silverstripe: CMS Pages as JSON?

Body:
I am working on a Silverstripe project and I would like to have a simple way to present the content of a CMS generated Page (or subtype of Page) as JSON.

Ideally, I would like to append "/json" at the end of the route, or send a parameter via post (json=true) and obtain a response in JSON format.

I tried adding an action to my CustomPage_Controller class like this:

public static $allowed_actions = array('json');
public function json(SS_HTTPRequest $request) {
    // ...
}

But I cannot figure out how to make that work:

What URL/Route should I use?

How do I get the content of the page?

Body:
Shane's answer was helpful, however I needed to output all pages from a route, not just the current record.

Here is how I managed to do this :

<?php

class Page_Controller extends ContentController {

    private static $allowed_actions = [
        'index',
    ];

    public function init() {
        parent::init();
        // You can include any CSS or JS required by your project here.
        // See: http://doc.silverstripe.org/framework/en/reference/requirements
    }

    public function index(SS_HTTPRequest $request) {
        $results = [];
        $f = new JSONDataFormatter();
        foreach (Article::get() as $pageObj) {
            $results[] = $f->convertDataObjectToJSONObject($pageObj);
        }

        $this->response->addHeader('Content-Type', 'application/json');
        return json_encode($results);
    }
}


答:
Your index i is nil, as you are only doing map which iterates over the element only, to use map with index you need to use .map.with_index as shown in the docs which will give you both element x and index i

```<code>def block_word?(word)
  word = word.upcase
  @pair1.map.with_index { |x, i| word.include?(x) && word.include?(@pair2[i]) }.include?(true)
end
</code>```

Title: Can't see why I have "no implicit conversion from nil to integer" error

Body:
Your index i is nil, as you are only doing map which iterates over the element only, to use map with index you need to use .map.with_index as shown in the docs which will give you both element x and index i

def block_word?(word)
  word = word.upcase
  @pair1.map.with_index { |x, i| word.include?(x) && word.include?(@pair2[i]) }.include?(true)
end


问:
Angular 2 Routes to show confirmation screen without compoent?
I have the UX design in my project like suppose I have a Register page, so I have made a Register component with its html and css and given a state 'localhost:8080/register' i.e. '/register'as a route.
On successfull registeration I want to display a different HTML template for register with some route stats as "/register/done" but here I donot want to make any new component, So is it possible to create a route without component.
The second approach is I can replace the HTML template in the current component to show the successfull registration confirmation screen. So is it possible to change the HTML template dynamically or not. As I am using webpack, it is not possible I think.

If there is any other solution to show these two related routes with different HTML template and route then please share it here.

Thanks in advance!!

答:
Use a flag to dynamically change the html template.
Set flag true or false in your register.component.ts as per your requirement. And in html template use 'ngIf' to toggle between template views.

   Main Template

   Successfull registration template

```

`

Body:
Use a flag to dynamically change the html template.
Set flag true or false in your register.component.ts as per your requirement. And in html template use 'ngIf' to toggle between template views.

<div *ngIf="flag">
   Main Template
</div>

<div *ngIf="!flag">
   Successfull registration template
</div>

`


问:
How does composition work in C#?
I have a Car Class:

```<code>public class Car
{
    private String _Brand;
    private String _Model;
    private Engine _Engine;

    public Car(){

    }

     public String Brand
     {
        get { return _Brand; }
        set { _Brand = value; }
     }

     public String Model
     {
        get { return _Model; }
        set { _Model = value; }
     }

     public Engine Engine
     {
        get { return _Engine; }
        set { _Engine = value; }
     }
}
</code>```

And an Engine Class:

```<code>public class Engine
{
     private int _Code;
     private DateTime _Year;

     public Engine(){

     }

     public int Code
     {
        get { return _Code; }
        set { _Code = value; }
     }

     public DateTime Year
     {
        get { return _Year; }
        set { _Year = value; }
     }
}
</code>```

From code-behind of Registration.aspx.cs, I wanna create using a button, a Car and an Engine w/ theirs respective relationship (Composition).

However, I have a massive confusion about how a composition for these objects should be behave. I.E., I can't figure it out if I must declare: Engine = new Engine(); in Car's constructor or if in Registration Event (Button, Code-Behind) declare: Car car = new Car() and then car.Engine = new Engine();.

I don't how composition relationship work in a scenario like this. The existence of where to declare "new" is putting me in a mixing of concepts.

Regards

答:
It all depends on the way you design your classes. Car and Engine are very generic. For instance, if you were to create a Mercedes, then it makes sense to create a new type, MercedesCar that inherits from the Car. In this case, you could instantiate a MercedesEngine from within the constructor of the MercedesCar as follows:

```<code>public class Car
{
    public Engine Engine
    {
        get;
        private set;
    }

    public Car(Engine engine)
    {
        this.Engine = engine;
    }
}

public class MercedesCar : Car
{
    public MercedesCar() : base(new MercedesEngine())
    {
    }
}

public class Engine
{
}

public class MercedesEngine : Engine
{
}
</code>```

But if you were to stick with Car class alone, then there is nothing wrong in creating the engine from the outside!

Title: How does composition work in C#?

Body:
I have a Car Class:

public class Car
{
    private String _Brand;
    private String _Model;
    private Engine _Engine;

    public Car(){

    }

     public String Brand
     {
        get { return _Brand; }
        set { _Brand = value; }
     }

     public String Model
     {
        get { return _Model; }
        set { _Model = value; }
     }

     public Engine Engine
     {
        get { return _Engine; }
        set { _Engine = value; }
     }
}

And an Engine Class:

public class Engine
{
     private int _Code;
     private DateTime _Year;

     public Engine(){

     }

     public int Code
     {
        get { return _Code; }
        set { _Code = value; }
     }

     public DateTime Year
     {
        get { return _Year; }
        set { _Year = value; }
     }
}

From code-behind of Registration.aspx.cs, I wanna create using a button, a Car and an Engine w/ theirs respective relationship (Composition).

However, I have a massive confusion about how a composition for these objects should be behave. I.E., I can't figure it out if I must declare: Engine = new Engine(); in Car's constructor or if in Registration Event (Button, Code-Behind) declare: Car car = new Car() and then car.Engine = new Engine();.

I don't how composition relationship work in a scenario like this. The existence of where to declare "new" is putting me in a mixing of concepts.

Regards

Body:
It all depends on the way you design your classes. Car and Engine are very generic. For instance, if you were to create a Mercedes, then it makes sense to create a new type, MercedesCar that inherits from the Car. In this case, you could instantiate a MercedesEngine from within the constructor of the MercedesCar as follows:

public class Car
{
    public Engine Engine
    {
        get;
        private set;
    }

    public Car(Engine engine)
    {
        this.Engine = engine;
    }
}

public class MercedesCar : Car
{
    public MercedesCar() : base(new MercedesEngine())
    {
    }
}

public class Engine
{
}

public class MercedesEngine : Engine
{
}

But if you were to stick with Car class alone, then there is nothing wrong in creating the engine from the outside!


问:
How to wrap multi actionCreators into one props?
I'm getting the following error:

Uncaught TypeError: this.props.dispatch is not a function

Here's my component:

```<code>import React from 'react';
import PropTypes from 'prop-types';
import {Link} from 'react-router-dom';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';
import * as jobTitleSkillsActions from '../../actions/jobTitleSkillsActions';
import SkillList from './SkillList';
import * as userPositionActions from '../../actions/userPositionActions';

class SkillPage extends React.Component {

  componentDidMount() {
    this.props.dispatch(userPositionActions.loadUserPositions());
    var job_title_id = this.props.user_positions[0].job_title_id;    this.props.dispatch(jobTitleSkillsActions.loadJobTitleSkills(job_title_id));
  }

.....

const mapStateToProps = state => {
  return {
    job_title_skills: state.job_title_skills,
    user_positions: state.user_positions
  };
};

function mapDispatchToProps(dispatch) {
  return {
    actions: {
      userPositionActions: bindActionCreators(userPositionActions, dispatch),
      jobTitleSkillsActions: bindActionCreators(jobTitleSkillsActions, dispatch),
    }
  };
}

export default connect(mapStateToProps, mapDispatchToProps)(SkillPage);
</code>```

What am I doing wrong here?

答:
Since you have already used mapDispatchToProps, dispatch wont be available to the component as a prop. Since you have used mapDisptachToProps, the jobs actions will be available as props and you can use them like

```<code>componentDidMount() {
    this.props.actions.userPositionActions.loadUserPositions());
    var job_title_id = this.props.user_positions[0].job_title_id;
    this.props.actions.jobTitleSkillsActions.loadJobTitleSkills(job_title_id));
  }
</code>```

However you can simplify it further like

```<code>function mapDispatchToProps(dispatch) {
  return bindActionCreators({userPositionActions, jobTitleSkillsActions}, dispatch)
}

...

componentDidMount() {
    this.props.userPositionActions.loadUserPositions());
    var job_title_id = this.props.user_positions[0].job_title_id;
    this.props.jobTitleSkillsActions.loadJobTitleSkills(job_title_id));
  }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm getting the following error:

Uncaught TypeError: this.props.dispatch is not a function

Here's my component:

import React from 'react';
import PropTypes from 'prop-types';
import {Link} from 'react-router-dom';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';
import * as jobTitleSkillsActions from '../../actions/jobTitleSkillsActions';
import SkillList from './SkillList';
import * as userPositionActions from '../../actions/userPositionActions';

class SkillPage extends React.Component {

  componentDidMount() {
    this.props.dispatch(userPositionActions.loadUserPositions());
    var job_title_id = this.props.user_positions[0].job_title_id;    this.props.dispatch(jobTitleSkillsActions.loadJobTitleSkills(job_title_id));
  }

.....

const mapStateToProps = state => {
  return {
    job_title_skills: state.job_title_skills,
    user_positions: state.user_positions
  };
};

function mapDispatchToProps(dispatch) {
  return {
    actions: {
      userPositionActions: bindActionCreators(userPositionActions, dispatch),
      jobTitleSkillsActions: bindActionCreators(jobTitleSkillsActions, dispatch),
    }
  };
}

export default connect(mapStateToProps, mapDispatchToProps)(SkillPage);

What am I doing wrong here?

Body:
Since you have already used mapDispatchToProps, dispatch wont be available to the component as a prop. Since you have used mapDisptachToProps, the jobs actions will be available as props and you can use them like

componentDidMount() {
    this.props.actions.userPositionActions.loadUserPositions());
    var job_title_id = this.props.user_positions[0].job_title_id;
    this.props.actions.jobTitleSkillsActions.loadJobTitleSkills(job_title_id));
  }

However you can simplify it further like

function mapDispatchToProps(dispatch) {
  return bindActionCreators({userPositionActions, jobTitleSkillsActions}, dispatch)
}

...

componentDidMount() {
    this.props.userPositionActions.loadUserPositions());
    var job_title_id = this.props.user_positions[0].job_title_id;
    this.props.jobTitleSkillsActions.loadJobTitleSkills(job_title_id));
  }


答:
I think you should create a class that represents book category. Then, you could simply iterate through all the category lists and extract the necessary information, like this:

```<code>string books = null;
books = bookComboBox.SelectedItem.ToString();
selectedPictureBox.Visible = true;

for (int i = 0; i < categories.Count; i++) {
    if (books == categories[i].Name) {
        bookListBox.Items.Clear();
        selectedPictureBox.Image = Image.FromFile(categories[i].ImagePath);
        for (int j = 0; j < categories[i].Items.Count; j++) {
             bookListBox.Items.Add(categories[i].Items[j]);
        }
    }
}
</code>```

Title: wondering if there is an efficient way to shorten this code

Body:
So my program is going to end up being fairly large and I don't want a whole lot of code that could just be shortened. Here is one instance I am looking for some tips on:

private void bookComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
    string books = null;
    // sets books to the clicked item
    books = bookComboBox.SelectedItem.ToString();
    selectedPictureBox.Visible = true;
    // Loads string to list box and image to selectedPictureBox when programming is selected
    if (books == "Programming")
    {
        bookListBox.Items.Clear();
        selectedPictureBox.Image = Image.FromFile("programming.png");
        bookListBox.Items.Add("Visual Basic");
        bookListBox.Items.Add("Java");
        bookListBox.Items.Add("C#");
    }
    // Loads string to list box and image to selectedPictureBox when Networking is selected
    else if (books == "Networking")
    {
        bookListBox.Items.Clear();
        selectedPictureBox.Image = Image.FromFile("networking.png");
        bookListBox.Items.Add("LAN Networks");
        bookListBox.Items.Add("Windows Networking");
        bookListBox.Items.Add("More About Networking");
    }
    // Loads string to list box and image to selectedPictureBox when Web is selected
    else if (books == "Web")
    {
        bookListBox.Items.Clear();
        selectedPictureBox.Image = Image.FromFile("html.png");
        bookListBox.Items.Add("Web Programming");
        bookListBox.Items.Add("JavaScript");
        bookListBox.Items.Add("ASP");
    }
}

The code works fine but I was just hoping to get some tips on shortening this code if necessary, any input is appreciated.

Body:
I think you should create a class that represents book category. Then, you could simply iterate through all the category lists and extract the necessary information, like this:

string books = null;
books = bookComboBox.SelectedItem.ToString();
selectedPictureBox.Visible = true;

for (int i = 0; i < categories.Count; i++) {
    if (books == categories[i].Name) {
        bookListBox.Items.Clear();
        selectedPictureBox.Image = Image.FromFile(categories[i].ImagePath);
        for (int j = 0; j < categories[i].Items.Count; j++) {
             bookListBox.Items.Add(categories[i].Items[j]);
        }
    }
}


问:
When using a private git url for an npm module, how can I configure the consuming application to only use files from the module's dist folder?
I am using angular-cli for my angular application, but because angular-cli currently does not support use for creating a library, I used the seemingly most widely used git project to create my library: https://github.com/jvandemo/generator-angular2-library

My issue is that I don't want to publish my npm module library to the public directory. Instead I want to use the git url directly in my dependencies. During development, this works fine. I can run the build locally and run an npm link inside the "dist" folder and everything is dandy. However when I push my npm module code to git, and then run an npm install in the consuming project, I'm not sure how to set it so that my consuming project just looks inside the dist folder of the module and treats it as if it was the root of the module.

For example, in node_modules/my_private_module, my file structure looks like:

```<code>dist/
-- component1
-- compoennt2
-- my_module.metadata.json
-- my_module.d.ts
-- my_module.umd.js
-- index.d.ts
-- index.js
-- package.json
-- README.MD
package.json
README.md
</code>```

All the files that my application is using are in the /dist folder, but I DO NOT want to specify "dist" in all my imports like

```<code>import { myComponent1 } from 'my_private_module/dist';
</code>```

I want to be able to just specify

```<code>import { myComponent } from 'my_private_module";
</code>```

As I do in development when I run an npm link in the dist folder.

Is there a way I can achieve this?

Thanks

答:
In package.json for your module, in the root folder:

```<code>typings: 'dist/index.d.ts',
main: 'dist/index.js'
</code>```

Remove the package.json in your dist folder.

When the package is resolved from import {...} from 'my_private_module', the module loader will look for a folder called my_private_module under node_modules, and look either for index.js which defines the exports, or within package.json for the main property - which in your case also points to index.js from the dist folder.

It is good practice to put package.json where you want your module to be found, and have main and typings point to index.js and index.d.ts.

Body:
I am using angular-cli for my angular application, but because angular-cli currently does not support use for creating a library, I used the seemingly most widely used git project to create my library: https://github.com/jvandemo/generator-angular2-library

My issue is that I don't want to publish my npm module library to the public directory. Instead I want to use the git url directly in my dependencies. During development, this works fine. I can run the build locally and run an npm link inside the "dist" folder and everything is dandy. However when I push my npm module code to git, and then run an npm install in the consuming project, I'm not sure how to set it so that my consuming project just looks inside the dist folder of the module and treats it as if it was the root of the module.

For example, in node_modules/my_private_module, my file structure looks like:

dist/
-- component1
-- compoennt2
-- my_module.metadata.json
-- my_module.d.ts
-- my_module.umd.js
-- index.d.ts
-- index.js
-- package.json
-- README.MD
package.json
README.md

All the files that my application is using are in the /dist folder, but I DO NOT want to specify "dist" in all my imports like

import { myComponent1 } from 'my_private_module/dist';

I want to be able to just specify

import { myComponent } from 'my_private_module";

As I do in development when I run an npm link in the dist folder.

Is there a way I can achieve this?

Thanks

Body:
In package.json for your module, in the root folder:

typings: 'dist/index.d.ts',
main: 'dist/index.js'

Remove the package.json in your dist folder.

When the package is resolved from import {...} from 'my_private_module', the module loader will look for a folder called my_private_module under node_modules, and look either for index.js which defines the exports, or within package.json for the main property - which in your case also points to index.js from the dist folder.

It is good practice to put package.json where you want your module to be found, and have main and typings point to index.js and index.d.ts.


问:
How to copy all rows from one SQL Server table to a table on a different SQL Server
I have a database in SQL Server 2008 and the same database (backup) in SQL Server 2016. All the schema and tables are exactly the same.

I need to copy all rows from a table in SQL Server 2008 to the same table in SQL Server 2016. How to achieve this?

答:
create your table on the target server using your scripts from the Script Table As / Create Script step
on the target server, you can then issue a T-SQL statement:</p>

```<code>INSERT INTO dbo.YourTableNameHere
   SELECT *
   FROM [SourceServer].[SourceDatabase].dbo.YourTableNameHere
</code>```

Body:
create your table on the target server using your scripts from the Script Table As / Create Script step
on the target server, you can then issue a T-SQL statement:

INSERT INTO dbo.YourTableNameHere
   SELECT *
   FROM [SourceServer].[SourceDatabase].dbo.YourTableNameHere


问:
what's `set ovs_ctl ${1-start}` command in linux shell mean?
I'm reading ovs' script, in start/stop script, there is :

```<code>start () {
    set ovs_ctl ${1-start}
    set "$@" --system-id=random
    ...
</code>```

what's set ovs_ctl ${1-start} means?

Thank you!

答:
That looks like a bash parameter substitution with a default.

```<code>${parameter-default}, ${parameter:-default}
If parameter not set, use default.
</code>```

http://tldp.org/LDP/abs/html/parameter-substitution.html

So in your case it will set "ovs_ctl" to $1, the first command line argument if it is set, or else "start"

Body:
I'm reading ovs' script, in start/stop script, there is :

start () {
    set ovs_ctl ${1-start}
    set "$@" --system-id=random
    ...

what's set ovs_ctl ${1-start} means?

Thank you!

Body:
That looks like a bash parameter substitution with a default.

${parameter-default}, ${parameter:-default}
If parameter not set, use default.

http://tldp.org/LDP/abs/html/parameter-substitution.html

So in your case it will set "ovs_ctl" to $1, the first command line argument if it is set, or else "start"


问:
JSP Data table Limit number of rows on each div
I'm doing a page where i display some labels and input text field so the user can introduce some data and send it back to the server. But sometimes the server send back more than 50 rows of information. In this case the user need to scoll multiple times in order to see all the fields. I want to create 2/3 divs and each contains maybe ~20 fields so that all fields can be displayed without scrolling. Any idea?

Here is my code

```<code><div class="container">
    <div class="row">
        <f:view>
            <h:form>
                <h:dataTable value="#{Message.bits}" var="bit">
                    <h:column>
                        <div class="col-lg-4">
                            <h:outputText value="#{bit.id} #{bit.name}" />
                            <div class="input-group">
                                <h:inputText styleClass="form-control" size="100"
                                    maxlength="100" value="#{bit.value}" />
                            </div>
                            </p>
                        </div>
                    </h:column>
                </h:dataTable>
            </h:form>
        </f:view>
    </div>
</div>
</code>```

Class Message -> A container of bits. It is a bean manager

```<code>@ManagedBean
@ViewScoped
public class Message implements Serializable {

    /**
     *
     */
    private static final long serialVersionUID = 2712306195992874273L;

    private List<Bit> bits = null;

    public List<Bit> getBits() {
            return bits;
        }
    //Do more things
</code>```

Bit class

```<code>public class Bit implements Serializable {

    /**
     *
     */
    private static final long serialVersionUID = -6341896264030346040L;

    private String name = null;

    private String value = null;

    private int id = 0;

   //Business logic
</code>```

I can use html, css, any js framework, jsp,java.

Thanks for your time.

答:
If I got your question right, you want to display your data like this:

```<code>1   4   7
2   5   8
3   6   9
</code>```

Instead of this:

```<code>1
2
3
4
5
..
</code>```

I don't know if this is the best solution but it works for me.

You can try the code below.

```<code> <div class="row">

   <ui:repeat var="bit" value="#{message.bits}" varStatus="bitstatus">
       <h:outputText escape="false" value="<div class='col-lg-4'>" rendered="#{(bitstatus.index + 1) % 20 eq 1}" />

       <h:outputText value="#{bit.id} #{bit.name}" />

       <div class="input-group">
         <h:inputText styleClass="form-control" size="100" maxlength="100" value="#{bit.value}" />
       </div>

       <h:outputText escape="false" value="</div>" rendered="#{(productstatus.index + 1) % 5 eq 0}" />
   </ui:repeat>

 </div>
</code>```

Body:
I'm doing a page where i display some labels and input text field so the user can introduce some data and send it back to the server. But sometimes the server send back more than 50 rows of information. In this case the user need to scoll multiple times in order to see all the fields. I want to create 2/3 divs and each contains maybe ~20 fields so that all fields can be displayed without scrolling. Any idea?

Here is my code

        <f:view>
            <h:form>
                <h:dataTable value="#{Message.bits}" var="bit">
                    <h:column>

                            <h:outputText value="#{bit.id} #{bit.name}" />

                                <h:inputText styleClass="form-control" size="100"
                                    maxlength="100" value="#{bit.value}" />

                    </h:column>
                </h:dataTable>
            </h:form>
        </f:view>

Class Message -> A container of bits. It is a bean manager

@ManagedBean
@ViewScoped
public class Message implements Serializable {

    /**
     *
     */
    private static final long serialVersionUID = 2712306195992874273L;

    private List<Bit> bits = null;

    public List<Bit> getBits() {
            return bits;
        }
    //Do more things

Bit class

public class Bit implements Serializable {

    /**
     *
     */
    private static final long serialVersionUID = -6341896264030346040L;

    private String name = null;

    private String value = null;

    private int id = 0;

   //Business logic

I can use html, css, any js framework, jsp,java.

Thanks for your time.

Body:
If I got your question right, you want to display your data like this:

1   4   7
2   5   8
3   6   9

Instead of this:

1
2
3
4
5
..

I don't know if this is the best solution but it works for me.

You can try the code below.

 <div class="row">

   <ui:repeat var="bit" value="#{message.bits}" varStatus="bitstatus">
       <h:outputText escape="false" value="&lt;div class='col-lg-4'&gt;" rendered="#{(bitstatus.index + 1) % 20 eq 1}" />

       <h:outputText value="#{bit.id} #{bit.name}" />

       <div class="input-group">
         <h:inputText styleClass="form-control" size="100" maxlength="100" value="#{bit.value}" />
       </div>

       <h:outputText escape="false" value="&lt;/div&gt;" rendered="#{(productstatus.index + 1) % 5 eq 0}" />
   </ui:repeat>

 </div>