问:
css position:fixed

```

I can add anything inside that div tag and it will rise above the top and stay fixed to the bottom left, but the javascript file will just stay where I've placed it within the webpage as if it can't be bothered to adhere to the .css rule.

I was wondering how I could get around this. Thank you for all your help.

答:
The script element allows authors to include dynamic script and data
  blocks in their documents. The element does not represent content for
  the user.

The quotes above was extracted from this link here

The script is not a content layout html container but serves to the purpose of dynamic execution of blocks of codes that can produce a layout/expected output .Hence you will find certain css rules applied on a script tag  void.

Title: css position:fixed <script> tag within does not stay fixed

Body:
I'm having an issue trying to get a .js validation script to stay in a fixed location within a webpage.

My code for the css is:

div.fixed {
position: fixed;
bottom: 0;
left: 0;
}

HTML

I can add anything inside that div tag and it will rise above the top and stay fixed to the bottom left, but the javascript file will just stay where I've placed it within the webpage as if it can't be bothered to adhere to the .css rule.

I was wondering how I could get around this. Thank you for all your help.


来源: stackexchange

问:
Best way add a new column with sequential numbering in an existing data table
I have a non empty datatable . What is the best way to add another column to it that has sequential numbering starting from 1.

I tried the following code. But did not work.

```<code>DataColumn dc = new DataColumn("Col1");
dc.AutoIncrement = true;
dc.AutoIncrementSeed = 1;
dc.AutoIncrementStep = 1;
dc.DataType = typeof(Int32);
dt.Columns.Add(dc);
</code>```

Will setting any expression help in this scenario ?

Thanks in Advance

答:
below code worked for me

Code is Edited

```<code>        // Added temp rows so that this solution can mimic actual requirement

        DataTable dt = new DataTable();
        DataColumn dc1 = new DataColumn("Col");
        dt.Columns.Add(dc1);

        for(int i=0;i<10;i++)
        {
            DataRow dr = dt.NewRow();
             dr["Col"] = i.ToString();
             dt.Rows.Add(dr);
        }

        // Added new column with Autoincrement,

        DataColumn dc = new DataColumn("Col1");
        dc.AutoIncrement = true;
        dc.AutoIncrementSeed = 1;
        dc.DataType = typeof(Int32);

        // Handeled CollectionChanged event

        dt.Columns.CollectionChanged += new CollectionChangeEventHandler(Columns_CollectionChanged);
        dt.Columns.Add(dc);

        // After column added demostratation

        DataRow dr1 = dt.NewRow();
            dt.Rows.Add(dr1);

    void Columns_CollectionChanged(object sender, CollectionChangeEventArgs e)
    {
        DataColumn dc = (e.Element as DataColumn);
        if (dc != null && dc.AutoIncrement)
        {
            long i = dc.AutoIncrementSeed;
            foreach (DataRow drow in dc.Table.Rows)
            {
                drow[dc] = i;
                i++;
            }
        }
    }
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have a non empty datatable . What is the best way to add another column to it that has sequential numbering starting from 1.

I tried the following code. But did not work.

DataColumn dc = new DataColumn("Col1");
dc.AutoIncrement = true;
dc.AutoIncrementSeed = 1;
dc.AutoIncrementStep = 1;
dc.DataType = typeof(Int32);
dt.Columns.Add(dc);

Will setting any expression help in this scenario ?

Thanks in Advance

Body:
below code worked for me

Code is Edited

        // Added temp rows so that this solution can mimic actual requirement

        DataTable dt = new DataTable();
        DataColumn dc1 = new DataColumn("Col");
        dt.Columns.Add(dc1);

        for(int i=0;i<10;i++)
        {
            DataRow dr = dt.NewRow();
             dr["Col"] = i.ToString();
             dt.Rows.Add(dr);
        }

        // Added new column with Autoincrement,

        DataColumn dc = new DataColumn("Col1");
        dc.AutoIncrement = true;
        dc.AutoIncrementSeed = 1;
        dc.DataType = typeof(Int32);

        // Handeled CollectionChanged event

        dt.Columns.CollectionChanged += new CollectionChangeEventHandler(Columns_CollectionChanged);
        dt.Columns.Add(dc);

        // After column added demostratation

        DataRow dr1 = dt.NewRow();
            dt.Rows.Add(dr1);

    void Columns_CollectionChanged(object sender, CollectionChangeEventArgs e)
    {
        DataColumn dc = (e.Element as DataColumn);
        if (dc != null && dc.AutoIncrement)
        {
            long i = dc.AutoIncrementSeed;
            foreach (DataRow drow in dc.Table.Rows)
            {
                drow[dc] = i;
                i++;
            }
        }
    }


问:
Why does this array-reshaping routine work outside of a function but not inside of a function?
I am trying to convert a list into a numpy array with a specified number of columns. I can get the code to work outside the function as follows:

```<code>import numpy as np

ls = np.linspace(1,100,100) # Data Sample
ls = np.array(ls) # list --> array

# resize | outside function
ls.resize(ls.shape[0]//2,2)
print(ls)

>> [[   1.    2.]
    [   3.    4.]
           .
           .
           .
    [  97.   98.]
    [  99.  100.]]
</code>```

I do not understand my error when trying to throw the routine in a function. My attempt is as follows:

```<code># resize | inside function
def shapeshift(mylist, num_col):
    num_col = int(num_col)
    return mylist.resize(mylist.shape[0]//num_col,num_col)

ls = shapeshift(ls,2)
print(ls)

>> None
</code>```

I want to define the original function in this way because I want another function, consisting of the same inputs and a third input to loop over rows when extracting values, to call this original function for each loop over rows.

答:
The .resize method works in-place and returns None. It also refuses to work at all if there are other names referencing the same array. You can use the function form, which creates a new array and is not as capricious:

```<code>def shapeshift(mylist, num_col):
    num_col = int(num_col)
    return np.resize(mylist, (mylist.size//num_col,num_col))
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to convert a list into a numpy array with a specified number of columns. I can get the code to work outside the function as follows:

import numpy as np

ls = np.linspace(1,100,100) # Data Sample
ls = np.array(ls) # list --> array

# resize | outside function
ls.resize(ls.shape[0]//2,2)
print(ls)

>> [[   1.    2.]
    [   3.    4.]
           .
           .
           .
    [  97.   98.]
    [  99.  100.]]

I do not understand my error when trying to throw the routine in a function. My attempt is as follows:

# resize | inside function
def shapeshift(mylist, num_col):
    num_col = int(num_col)
    return mylist.resize(mylist.shape[0]//num_col,num_col)

ls = shapeshift(ls,2)
print(ls)

>> None

I want to define the original function in this way because I want another function, consisting of the same inputs and a third input to loop over rows when extracting values, to call this original function for each loop over rows.

Body:
The .resize method works in-place and returns None. It also refuses to work at all if there are other names referencing the same array. You can use the function form, which creates a new array and is not as capricious:

def shapeshift(mylist, num_col):
    num_col = int(num_col)
    return np.resize(mylist, (mylist.size//num_col,num_col))


问:
Loudev multiselect with ng-options
I am trying to implement loudev multiselect with angular ng-options. Problem is that, it returns no error but the select list is empty. </p>

```<code> <select ng-options="item.label for item in list"
         lp-multi-select multiple="multiple"
         class="multi-select" ng-model="$scope.selected"></select>
</code>```

答:
You can not write "$scope" in the ng-model because it is not defined there.So the rule is "$scope.selected" in angular controller js is same as "selected" in ng-model like--

ng-model="selected"

if you do so then it will return your multiple selected option as array of object.you can see example below(select two option then click the check button to see result)--

<!DOCTYPE html>

  <select ng-options="item.label for item in list" multiple="multiple" class="multi-select" ng-model="selected">
  </select>
  <button ng-click="checkM()">Check</button>

```

Title: Loudev multiselect with ng-options

Body:
I am trying to implement loudev multiselect with angular ng-options. Problem is that, it returns no error but the select list is empty.

 <select ng-options="item.label for item in list"
         lp-multi-select multiple="multiple"
         class="multi-select" ng-model="$scope.selected"></select>

Body:
You can not write "$scope" in the ng-model because it is not defined there.So the rule is "$scope.selected" in angular controller js is same as "selected" in ng-model like--

ng-model="selected"

if you do so then it will return your multiple selected option as array of object.you can see example below(select two option then click the check button to see result)--

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>

<body>

    <div ng-app="myApp" ng-controller="datCtrl">
  <select ng-options="item.label for item in list" multiple="multiple" class="multi-select" ng-model="selected">
  </select>
  <button ng-click="checkM()">Check</button>

    </div>

    <script>
        var app = angular.module('myApp', []);
        app.controller('datCtrl', function ($scope) {
            $scope.list=[{id:1,label:"banana"},{id:2,label:"mango"},{id:3,label:"apple"},{id:4,label:"water melon"}];
   $scope.checkM=function (){
    console.log($scope.selected);
   };
        });

    </script>

</body>

</html>


问:
SSL_connect error when using delayed_job processes
I have a traditional rails stack(mysql,ubuntu) that uses delayed_job for processing background tasks.

today started seeing ssl_connect errors, but only from our background processes.

The error does not happen with our main application(re: https://github.com/lostisland/faraday/issues/371)

the error does not happen fetching from rubygems(re: http://guides.rubygems.org/ssl-certificate-update/)

The error does not happen when I start a rails console process and manually invoke a job(re: https://stackoverflow.com/a/4020485/1536309)

Have also tried using the ssl_tools/doctor from @mislav and have no errors.

For reference error is:

```<code>OpenSSL::SSL::SSLError: SSL_connect returned=1 errno=0 state=SSLv3 read server certificate B: certificate verify failed
- 17 non-project frames
File "/home/deploy/.rvm/rubies/ruby-2.1.7/lib/ruby/2.1.0/net/http.rb" line 923 in connect
File "/home/deploy/.rvm/rubies/ruby-2.1.7/lib/ruby/2.1.0/net/http.rb" line 923 in block in connect
File "/home/deploy/.rvm/rubies/ruby-2.1.7/lib/ruby/2.1.0/timeout.rb" line 90 in block in timeout
File "/home/deploy/.rvm/rubies/ruby-2.1.7/lib/ruby/2.1.0/timeout.rb" line 100 in call
File "/home/deploy/.rvm/rubies/ruby-2.1.7/lib/ruby/2.1.0/timeout.rb" line 100 in timeout
File "/home/deploy/.rvm/rubies/ruby-2.1.7/lib/ruby/2.1.0/net/http.rb" line 923 in connect
File "/home/deploy/.rvm/rubies/ruby-2.1.7/lib/ruby/2.1.0/net/http.rb" line 863 in do_start
File "/home/deploy/.rvm/rubies/ruby-2.1.7/lib/ruby/2.1.0/net/http.rb" line 852 in start
File "/home/deploy/.rvm/rubies/ruby-2.1.7/lib/ruby/2.1.0/net/http.rb" line 1375 in request
</code>```

答:
Wow.

PID stands for process ID, which is the strategy that computers use to keep track internal programs that are running. each process gets a PID. Delayed jobs allows you to configure the PID directory.

IF you are having trouble with delayed jobs, check the pids and make sure you don't have random DJ processes running on old code. That was my problem above. anytime a bug came up, someone would manually restart DJ without specifying PIDs and it would create NEW PIDs. YIKES.

Old DJ processes running old/outdated code.

Body:
I have a traditional rails stack(mysql,ubuntu) that uses delayed_job for processing background tasks.

today started seeing ssl_connect errors, but only from our background processes.

The error does not happen with our main application(re: https://github.com/lostisland/faraday/issues/371)

the error does not happen fetching from rubygems(re: http://guides.rubygems.org/ssl-certificate-update/)

The error does not happen when I start a rails console process and manually invoke a job(re: https://stackoverflow.com/a/4020485/1536309)

Have also tried using the ssl_tools/doctor from @mislav and have no errors.

For reference error is:

OpenSSL::SSL::SSLError: SSL_connect returned=1 errno=0 state=SSLv3 read server certificate B: certificate verify failed
- 17 non-project frames
File "/home/deploy/.rvm/rubies/ruby-2.1.7/lib/ruby/2.1.0/net/http.rb" line 923 in connect
File "/home/deploy/.rvm/rubies/ruby-2.1.7/lib/ruby/2.1.0/net/http.rb" line 923 in block in connect
File "/home/deploy/.rvm/rubies/ruby-2.1.7/lib/ruby/2.1.0/timeout.rb" line 90 in block in timeout
File "/home/deploy/.rvm/rubies/ruby-2.1.7/lib/ruby/2.1.0/timeout.rb" line 100 in call
File "/home/deploy/.rvm/rubies/ruby-2.1.7/lib/ruby/2.1.0/timeout.rb" line 100 in timeout
File "/home/deploy/.rvm/rubies/ruby-2.1.7/lib/ruby/2.1.0/net/http.rb" line 923 in connect
File "/home/deploy/.rvm/rubies/ruby-2.1.7/lib/ruby/2.1.0/net/http.rb" line 863 in do_start
File "/home/deploy/.rvm/rubies/ruby-2.1.7/lib/ruby/2.1.0/net/http.rb" line 852 in start
File "/home/deploy/.rvm/rubies/ruby-2.1.7/lib/ruby/2.1.0/net/http.rb" line 1375 in request


问:
Custom aggregate function inside a package
I'm trying to write a custom aggregate function in Oracle and group that function inside a package together with some other functions that I have. As an example (to simulate the problem I have) suppose my custom aggregation to do a summation of numbers looks like:

```<code>CREATE OR REPLACE TYPE SUM_AGGREGATOR_TYPE AS OBJECT (
    summation NUMBER,

    STATIC FUNCTION ODCIAggregateInitialize(agg_context IN OUT
       SUM_AGGREGATOR_TYPE) RETURN NUMBER,

    MEMBER FUNCTION ODCIAggregateIterate(self IN OUT SUM_AGGREGATOR_TYPE,
        next_number IN NUMBER) RETURN NUMBER,

    MEMBER FUNCTION ODCIAggregateMerge(self IN OUT SUM_AGGREGATOR_TYPE,
        para_context IN SUM_AGGREGATOR_TYPE) RETURN NUMBER,

    MEMBER FUNCTION ODCIAggregateTerminate(self IN SUM_AGGREGATOR_TYPE,
        return_value OUT NUMBER, flags IN NUMBER) RETURN NUMBER
);
</code>```

```<code>CREATE OR REPLACE TYPE BODY SUM_AGGREGATOR_TYPE IS

  STATIC FUNCTION ODCIAggregateInitialize(agg_context IN OUT
    SUM_AGGREGATOR_TYPE)
      RETURN NUMBER IS
  BEGIN
    agg_context := SUM_AGGREGATOR_TYPE(NULL);
    RETURN ODCIConst.Success;
  END;

  MEMBER FUNCTION ODCIAggregateIterate(self IN OUT SUM_AGGREGATOR_TYPE,
    next_number IN NUMBER)
      RETURN NUMBER IS
  BEGIN
    IF self.summation IS NULL THEN
        self.summation := next_number;
    ELSIF summation IS NOT NULL THEN
        self.summation := self.summation + next_number;
    END IF;
    RETURN ODCIConst.Success;
  END;

  MEMBER FUNCTION ODCIAggregateMerge(self IN OUT SUM_AGGREGATOR_TYPE,
    para_context IN SUM_AGGREGATOR_TYPE)
      RETURN NUMBER IS
  BEGIN
    self.summation := self.summation + para_context.summation;
    RETURN ODCIConst.Success;
  END;

  MEMBER FUNCTION ODCIAggregateTerminate(self IN SUM_AGGREGATOR_TYPE,
    return_value OUT NUMBER, flags IN NUMBER)
      RETURN NUMBER IS
  BEGIN
    return_value := self.summation;
    return ODCIConst.Success;
  END;

END;
</code>```

If I write the following function definition:

```<code>CREATE OR REPLACE FUNCTION MY_SUM(input NUMBER)
  RETURN NUMBER PARALLEL_ENABLE AGGREGATE USING SUM_AGGREGATOR_TYPE;
</code>```

and corresponding type declaration to test:

```<code>CREATE OR REPLACE TYPE VECTOR
IS
  TABLE OF NUMBER;
</code>```

this statement:

```<code>select my_sum(column_value) from table(vector(1, 2, 1, 45, 22, -1));
</code>```

gives the correct result of 70. However, creating a package with the function definition:

```<code>CREATE OR REPLACE PACKAGE MY_FUNCTIONS AS
  FUNCTION MY_SUM(input NUMBER)
    RETURN NUMBER PARALLEL_ENABLE AGGREGATE USING SUM_AGGREGATOR_TYPE;
END;
</code>```

and calling it via:

```<code>select MY_FUNCTIONS.my_sum(column_value) from table(vector(1, 2, 1, 45, 22, -1));
</code>```

explodes with

```<code>ORA-00600: internal error code, arguments: [17090], [], [], [], [], [], [], [], [], [], [], []
</code>```

Is it possible to have custom aggregate functions nested inside package declarations?

答:
Oracle uses ORA-00600 to signal unhandled exceptions i.e. bugs.  The first argument indicates the exception; ORA-17090 is a generic "operation not allowed".  Frequently they are restricted to specific permutations of database version and OS platform.  Other times it just means we're doing something really unusual.

Does including a custom aggregate function inside a package count as "really unusual"?  Not sure.  Certainly we are permitted to include data cartridge functions in PL/SQL functions.  But user-defined aggregates are a special case of ODCI.  While the documentation has no explicit rule against packages all the examples implement the aggregate using CREATE FUNCTION.

So, what to do?  Well, ORA-00600 messages require the intervention of Oracle Support, as it needs a patch.   If you have a Support account you can find out more about this particular issue here.  You will need to raise an iTAR to get further resolution.  Otherwise I'm afraid you're probably out of luck.

Body:
I'm trying to write a custom aggregate function in Oracle and group that function inside a package together with some other functions that I have. As an example (to simulate the problem I have) suppose my custom aggregation to do a summation of numbers looks like:

CREATE OR REPLACE TYPE SUM_AGGREGATOR_TYPE AS OBJECT (
    summation NUMBER,

    STATIC FUNCTION ODCIAggregateInitialize(agg_context IN OUT
       SUM_AGGREGATOR_TYPE) RETURN NUMBER,

    MEMBER FUNCTION ODCIAggregateIterate(self IN OUT SUM_AGGREGATOR_TYPE,
        next_number IN NUMBER) RETURN NUMBER,

    MEMBER FUNCTION ODCIAggregateMerge(self IN OUT SUM_AGGREGATOR_TYPE,
        para_context IN SUM_AGGREGATOR_TYPE) RETURN NUMBER,

    MEMBER FUNCTION ODCIAggregateTerminate(self IN SUM_AGGREGATOR_TYPE,
        return_value OUT NUMBER, flags IN NUMBER) RETURN NUMBER
);

CREATE OR REPLACE TYPE BODY SUM_AGGREGATOR_TYPE IS

  STATIC FUNCTION ODCIAggregateInitialize(agg_context IN OUT
    SUM_AGGREGATOR_TYPE)
      RETURN NUMBER IS
  BEGIN
    agg_context := SUM_AGGREGATOR_TYPE(NULL);
    RETURN ODCIConst.Success;
  END;

  MEMBER FUNCTION ODCIAggregateIterate(self IN OUT SUM_AGGREGATOR_TYPE,
    next_number IN NUMBER)
      RETURN NUMBER IS
  BEGIN
    IF self.summation IS NULL THEN
        self.summation := next_number;
    ELSIF summation IS NOT NULL THEN
        self.summation := self.summation + next_number;
    END IF;
    RETURN ODCIConst.Success;
  END;

  MEMBER FUNCTION ODCIAggregateMerge(self IN OUT SUM_AGGREGATOR_TYPE,
    para_context IN SUM_AGGREGATOR_TYPE)
      RETURN NUMBER IS
  BEGIN
    self.summation := self.summation + para_context.summation;
    RETURN ODCIConst.Success;
  END;

  MEMBER FUNCTION ODCIAggregateTerminate(self IN SUM_AGGREGATOR_TYPE,
    return_value OUT NUMBER, flags IN NUMBER)
      RETURN NUMBER IS
  BEGIN
    return_value := self.summation;
    return ODCIConst.Success;
  END;

END;

If I write the following function definition:

CREATE OR REPLACE FUNCTION MY_SUM(input NUMBER)
  RETURN NUMBER PARALLEL_ENABLE AGGREGATE USING SUM_AGGREGATOR_TYPE;

and corresponding type declaration to test:

CREATE OR REPLACE TYPE VECTOR
IS
  TABLE OF NUMBER;

this statement:

select my_sum(column_value) from table(vector(1, 2, 1, 45, 22, -1));

gives the correct result of 70. However, creating a package with the function definition:

CREATE OR REPLACE PACKAGE MY_FUNCTIONS AS
  FUNCTION MY_SUM(input NUMBER)
    RETURN NUMBER PARALLEL_ENABLE AGGREGATE USING SUM_AGGREGATOR_TYPE;
END;

and calling it via:

select MY_FUNCTIONS.my_sum(column_value) from table(vector(1, 2, 1, 45, 22, -1));

explodes with

ORA-00600: internal error code, arguments: [17090], [], [], [], [], [], [], [], [], [], [], []

Is it possible to have custom aggregate functions nested inside package declarations?


问:
Switch statement ends prematurely in for loop
So I am doing a HackerRank question and cant seem to pass all the tests for some reason. My code passed the first run but appears to fail all the other tests. Looking through debugging, it seems that the for loop terminates once all the switch cases have been used.

This exercise is a Java List problem. An input is given such as

```<code>5
12 0 1 78 12
2
Insert
5 23
Delete
0
</code>```

The first line contains an integer,N  (the initial number of elements in the list, which is 5 in this case ).
The second line contains N space-separated integers that make up the list.
The third line contains an integer,q  (the number of queries).
The  subsequent lines describe the queries, and each query is described over two lines:

If the first line of a query contains the String Insert, then the second line contains two space separated integer, and the value  must be inserted into  at index .
   If the first line of a query contains the String Delete, then the second line contains index , whose element must be deleted from .

```<code>import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class ListSolution {
public static void main(String[] args){
    List<Integer> list1 = new ArrayList<>();
    Scanner sc = new Scanner(System.in);
    int n = sc.nextInt();
    sc.nextLine();
    for(int i =0;i<n;i++){
        list1.add(sc.nextInt());
    }

    sc.nextLine();
    int q = sc.nextInt();
    sc.nextLine();
    for(int i=0;i<q;i++){
        switch(sc.nextLine()){
        case "Insert" :
            int x = sc.nextInt();
            int y = sc.nextInt();
            sc.nextLine();
            list1.add(x,y);
            continue;
        case "Delete" :
            int z = sc.nextInt();
            list1.remove(z);
            continue;
        default:
            continue;
        }
    }
    for(int i=0;i<list1.size(); i++){
        System.out.print(list1.get(i)+" ");;
    }
}
}
</code>```

I was able to finish the problem and pass this specific input. However, it failed all the other in which there were 3 queries in which Insert and Delete are the first two. It seemed that once the switch went through all the cases, it terminated the for loop even though there were more iterations to be done. An example of such input is this:

```<code>10
100 50 20 10 70 80 200 259 1 900
3
Insert
2 80
Delete
6
Insert
5 89
</code>```

答: In the switch case, use sc.next() instead of sc.nextLine(). Finally, delete sc.nextLine() from the insert case.</p>

Body:
So I am doing a HackerRank question and cant seem to pass all the tests for some reason. My code passed the first run but appears to fail all the other tests. Looking through debugging, it seems that the for loop terminates once all the switch cases have been used.

This exercise is a Java List problem. An input is given such as

5
12 0 1 78 12
2
Insert
5 23
Delete
0

The first line contains an integer,N  (the initial number of elements in the list, which is 5 in this case ).
The second line contains N space-separated integers that make up the list.
The third line contains an integer,q  (the number of queries).
The  subsequent lines describe the queries, and each query is described over two lines:

If the first line of a query contains the String Insert, then the second line contains two space separated integer, and the value  must be inserted into  at index .
   If the first line of a query contains the String Delete, then the second line contains index , whose element must be deleted from .

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class ListSolution {
public static void main(String[] args){
    List<Integer> list1 = new ArrayList<>();
    Scanner sc = new Scanner(System.in);
    int n = sc.nextInt();
    sc.nextLine();
    for(int i =0;i<n;i++){
        list1.add(sc.nextInt());
    }

    sc.nextLine();
    int q = sc.nextInt();
    sc.nextLine();
    for(int i=0;i<q;i++){
        switch(sc.nextLine()){
        case "Insert" :
            int x = sc.nextInt();
            int y = sc.nextInt();
            sc.nextLine();
            list1.add(x,y);
            continue;
        case "Delete" :
            int z = sc.nextInt();
            list1.remove(z);
            continue;
        default:
            continue;
        }
    }
    for(int i=0;i<list1.size(); i++){
        System.out.print(list1.get(i)+" ");;
    }
}
}

I was able to finish the problem and pass this specific input. However, it failed all the other in which there were 3 queries in which Insert and Delete are the first two. It seemed that once the switch went through all the cases, it terminated the for loop even though there were more iterations to be done. An example of such input is this:

10
100 50 20 10 70 80 200 259 1 900
3
Insert
2 80
Delete
6
Insert
5 89


问:
Firebase Cloud Messaging not sending aps payload in correct format for iOS Notification Content & Service Extensions
I'm trying to implement notifications using Firebase. The notification is received correctly when the app is in the background or foreground. So, the basic mechanics are working.

Now I've added Content Extensions and Service Extensions to the app. The Content Extension works when I use a local notification, but the Firebase message payload seems incorrect as far as the optional fields are considered. Here is a link to an image of my console:

And here is the Firebase remote notification payload that comes across (with some of the long Google numbers edited for anonymity:

```<code>{
    aps =
    {
        alert =
        {
        body = "Eureka! 11";
        title = "Patient is not doing well";
        };
    };
    category = provider-body-panel;
    gcm.message_id = 0:149073;
    gcm.n.e = 1;
    google.c.a.c_id = 2825604;
    google.c.a.e = 1;
    google.c.a.ts = 149073;
    google.c.a.udt = 0;
    mutable-content = 1;
}
</code>```

It appears that the "category" and "mutable-content" are not in the correct place. They should be in the aps payload.

How can I get those options to be in the payload so that my app can correctly parse it and connect it with the Content and Service Extensions?

答:
To start off, I'm going to mention that there are two types of message payloads for FCM. notification and data. See the documentation here

When sending notifications through the Firebase Notifications Console, it will be treated as a notification payload. However, if you add in Custom Data, it will add it in the payload as a custom key-value pair.

For example, in your post, the FCM payload should look something like this:

```<code>{
    "notification": {
        "body" : "Eureka!",
        "title": "Patient is not doing well"
    },

    "data": {
        "category": "provider-body-panel",
        "mutable-content" : true,
        "click_action" : "provider-body-panel"
    }
}
</code>```

What's wrong?

click_action should be inside notification.

mutable-content should be mutable_content (notice the underscore) and should be on the same level as notification.

(this one I might've misunderstood, but) There is no category parameter for FCM, click_action already corresponds to it.

See the docs for the parameters here.

It it is currently not possible to set the value for click_action and mutable_content when using the Firebase Notifications Console. You'll have to build the payload yourself, something like this:

```<code>{
    "to": "<REGISTRATION_TOKEN_HERE>",
    "mutable_content" : true,
    "notification": {
        "body" : "Eureka!",
        "title": "Patient is not doing well",
        "click_action" : "provider-body-panel"
    }
}
</code>```

Then send it from your own App Server. You could also do this by using Postman or cURL

Body:
I'm trying to implement notifications using Firebase. The notification is received correctly when the app is in the background or foreground. So, the basic mechanics are working.

Now I've added Content Extensions and Service Extensions to the app. The Content Extension works when I use a local notification, but the Firebase message payload seems incorrect as far as the optional fields are considered. Here is a link to an image of my console:

And here is the Firebase remote notification payload that comes across (with some of the long Google numbers edited for anonymity:

{
    aps =
    {
        alert =
        {
        body = "Eureka! 11";
        title = "Patient is not doing well";
        };
    };
    category = provider-body-panel;
    gcm.message_id = 0:149073;
    gcm.n.e = 1;
    google.c.a.c_id = 2825604;
    google.c.a.e = 1;
    google.c.a.ts = 149073;
    google.c.a.udt = 0;
    mutable-content = 1;
}

It appears that the "category" and "mutable-content" are not in the correct place. They should be in the aps payload.

How can I get those options to be in the payload so that my app can correctly parse it and connect it with the Content and Service Extensions?

Body:
To start off, I'm going to mention that there are two types of message payloads for FCM. notification and data. See the documentation here

When sending notifications through the Firebase Notifications Console, it will be treated as a notification payload. However, if you add in Custom Data, it will add it in the payload as a custom key-value pair.

For example, in your post, the FCM payload should look something like this:

{
    "notification": {
        "body" : "Eureka!",
        "title": "Patient is not doing well"
    },

    "data": {
        "category": "provider-body-panel",
        "mutable-content" : true,
        "click_action" : "provider-body-panel"
    }
}

What's wrong?

click_action should be inside notification.

mutable-content should be mutable_content (notice the underscore) and should be on the same level as notification.

(this one I might've misunderstood, but) There is no category parameter for FCM, click_action already corresponds to it.

See the docs for the parameters here.

It it is currently not possible to set the value for click_action and mutable_content when using the Firebase Notifications Console. You'll have to build the payload yourself, something like this:

{
    "to": "<REGISTRATION_TOKEN_HERE>",
    "mutable_content" : true,
    "notification": {
        "body" : "Eureka!",
        "title": "Patient is not doing well",
        "click_action" : "provider-body-panel"
    }
}

Then send it from your own App Server. You could also do this by using Postman or cURL

ContentLicense: CC BY-SA 4.0


问:
Interfacing Haskell and C++
I'd like to call some Haskell functions in a c++ program.

In order to do so, i have applied these
 instructions and adapted them to my code and system.

What I have for the moment is the following:

Main.cpp

Shared header and cpp files

makefile

cpp/

some cpp and header files

haskell/

hello.hs

The make file is the following:

```<code>CPP_SOURCES = main.cpp textures.cpp cpp/game.cpp \
cpp/piece.cpp cpp/factories.cpp cpp/utils.cpp
HASKELL_SOURCES = haskell/hello.hs

all: main; ./main

main: $(CPP_SOURCES) HaskellPart.o; g++ \
    -lsfml-graphics \
    -lsfml-window \
    -lsfml-system \
    -I/usr/lib/ghc/include \
    -liconv \
    -I/usr/lib/ghc/ghc-8.0.1/include \
    -L/usr/lib/ghc/ghc-8.0.1 \
    -L/usr/lib/ghc/rts \
    -lHSrts \
    -L/usr/lib/ghc/base-4.9.0.0 \
    -lHSbase-4.9.0.0 \
    -L/usr/lib/ghc/ghc-prim-0.5.0.0 \
    -lHSghc-prim-0.5.0.0 \
    -L/usr/lib/ghc/integer-gmp-1.0.0.1 \
    -lHSinteger-gmp-1.0.0.1 \
    -lHSghc-prim-0.5.0.0 \
    -fno-stack-protector \
    -Wall \
    -o main $(CPP_SOURCES) haskell/hello.o

HaskellPart.o: $(HASKELL_SOURCES); ghc -fforce-recomp -fPIC $(HASKELL_SOURCES)

clean: ; rm -rf main && rm -rf haskell/*.o && \
rm -rf haskell/*.hi && rm -rf haskell/*_stub.h
</code>```

What I have done is:

add -I/usr/lib/ghc/include to allow g++ to find HsFFI.h

update the librairies paths

add -fPIC to the ghc arguments to avoid symbol errors.

However, I end up with the following output:

```<code>    $ make
ghc -fforce-recomp -fPIC haskell/hello.hs
[1 of 1] Compiling Hello            ( haskell/hello.hs, haskell/hello.o )
g++ \
-lsfml-graphics \
-lsfml-window \
-lsfml-system \
-I/usr/lib/ghc/include \
 -liconv \
-L/usr/lib/ghc/rts \
-lHSrts \
-L/usr/lib/ghc/base-4.9.0.0 \
-lHSbase-4.9.0.0 \
-L/usr/lib/ghc/ghc-prim-0.5.0.0 \
-lHSghc-prim-0.5.0.0 \
-L/usr/lib/ghc/integer-gmp-1.0.0.1 \
-lHSinteger-gmp-1.0.0.1 \
-lHSghc-prim-0.5.0.0 \
 -fno-stack-protector \
 -Wall \
 -o main main.cpp textures.cpp cpp/game.cpp cpp/piece.cpp cpp/factories.cpp cpp/utils.cpp haskell/hello.o
/tmp/ccHPRuDY.o: In function `main':
main.cpp:(.text+0x358): undefined reference to `hs_init'
main.cpp:(.text+0x375): undefined reference to `hs_exit'
haskell/hello.o: In function `sRs_info':
/tmp/ghc9fcb_0/ghc_7.o:(.text+0x2e): undefined reference to `newCAF'
/tmp/ghc9fcb_0/ghc_7.o:(.text+0x3e): undefined reference to `stg_bh_upd_frame_info'
/tmp/ghc9fcb_0/ghc_7.o:(.text+0x54): undefined reference to `ghczmprim_GHCziCString_unpackCStringzh_closure'
/tmp/ghc9fcb_0/ghc_7.o:(.text+0x5d): undefined reference to `stg_ap_n_fast'
/tmp/ghc9fcb_0/ghc_7.o:(.text+0x96): undefined reference to `newCAF'
/tmp/ghc9fcb_0/ghc_7.o:(.text+0xa6): undefined reference to `stg_bh_upd_frame_info'
/tmp/ghc9fcb_0/ghc_7.o:(.text+0xbc): undefined reference to `base_SystemziIO_putStrLn_closure'
/tmp/ghc9fcb_0/ghc_7.o:(.text+0xc5): undefined reference to `stg_ap_p_fast'
haskell/hello.o: In function `helloFromHaskell':
(.text+0xd8): undefined reference to `rts_lock'
haskell/hello.o: In function `helloFromHaskell':
(.text+0xee): undefined reference to `base_GHCziTopHandler_runIO_closure'
haskell/hello.o: In function `helloFromHaskell':
(.text+0xf9): undefined reference to `rts_apply'
haskell/hello.o: In function `helloFromHaskell':
(.text+0x10f): undefined reference to `rts_evalIO'
haskell/hello.o: In function `helloFromHaskell':
(.text+0x122): undefined reference to `rts_checkSchedStatus'
haskell/hello.o: In function `helloFromHaskell':
(.text+0x12e): undefined reference to `rts_unlock'
haskell/hello.o: In function `stginit_export_Hello_zdfstableZZC0ZZCmainZZCHelloZZChelloFromHaskell':
ghc_3.c:(.text+0x144): undefined reference to `foreignExportStablePtr'
haskell/hello.o: In function `sRs_closure':
/tmp/ghc9fcb_0/ghc_7.o:(.data+0x40): undefined reference to `stg_IND_STATIC_info'
haskell/hello.o: In function `rHM_closure':
/tmp/ghc9fcb_0/ghc_7.o:(.data+0x60): undefined reference to `ghczmprim_GHCziTypes_TrNameS_static_info'
haskell/hello.o: In function `rI0_closure':
/tmp/ghc9fcb_0/ghc_7.o:(.data+0x70): undefined reference to `ghczmprim_GHCziTypes_TrNameS_static_info'
/tmp/ghc9fcb_0/ghc_7.o:(.data+0x80): undefined reference to `ghczmprim_GHCziTypes_Module_static_info'
haskell/hello.o: In function `SRD_srt':
/tmp/ghc9fcb_0/ghc_7.o:(.data.rel.ro+0x0): undefined reference to `ghczmprim_GHCziCString_unpackCStringzh_closure'
/tmp/ghc9fcb_0/ghc_7.o:(.data.rel.ro+0x8): undefined reference to `base_SystemziIO_putStrLn_closure'
collect2: error: ld returned 1 exit status
makefile:17: recipe for target 'main' failed
make: *** [main] Error 1
</code>```

Any idea of what I am doing wrong ?

Thank you!

EDIT :

According to n.m answer, I changed the order of g++ arguments. Here's the new makefile:

```<code>CPP_SOURCES = main.cpp textures.cpp cpp/game.cpp cpp/piece.cpp cpp/factories.cpp cpp/utils.cpp
HASKELL_SOURCES = haskell/hello.hs
CFLAGS = -Wall -g -fno-stack-protector

all: main; ./main

main: $(CPP_SOURCES) HaskellPart.o; g++ \
    $(CFLAGS) -o main $(CPP_SOURCES) haskell/hello.o \
    -lsfml-graphics \
    -lsfml-window \
    -lsfml-system \
    -I/usr/lib/ghc/include \
    -liconv \
    -I/usr/lib/ghc/ghc-8.0.1/include \
    -L/usr/lib/ghc/ghc-8.0.1 \
    -L/usr/lib/ghc/base-4.9.0.0 \
    -lHSbase-4.9.0.0 \
    -L/usr/lib/ghc/ghc-prim-0.5.0.0 \
    -lHSghc-prim-0.5.0.0 \
    -L/usr/lib/ghc/integer-gmp-1.0.0.1 \
    -lHSinteger-gmp-1.0.0.1 \
    -lHSghc-prim-0.5.0.0 \
    -L/usr/lib/ghc/rts \
    -lHSrts \

HaskellPart.o: $(HASKELL_SOURCES); ghc -fforce-recomp -fPIC $(HASKELL_SOURCES)

clean: ; rm -rf main && rm -rf haskell/*.o && rm -rf haskell/*.hi && rm -rf haskell/*_stub.h
</code>```

But it raised another error:

/usr/bin/ld: /usr/lib/ghc/rts/libHSrts.a(Itimer.o): undefined reference to symbol 'timer_settime@@GLIBC_2.3.3'

According to this thread, I added -lrt but got:

/usr/bin/ld: /usr/lib/ghc/rts/libHSrts.a(Linker.o): undefined reference to symbol 'dlsym@@GLIBC_2.2.5'

So according to this thread I added -ldl and now it's a big mess...

EDIT : BOUNTY

Guys I'm adding a bounty spending a large proportion of my low amount of reputation because I can't manage to make this work and really need this.

This is for a school related project but I have to precise that this is not cheating as subject only says: "write a large program in c++ and write the same program in haskell".

Making a common graphical interface for both programs is my decision and is out of the scope of the coursework.

Beside that, I think there a lack of documentation on this subject on internet, my teacher told me he never managed to do it so it would be helpful to have a constructed answer on the configuration of g++ with Haskell Foreign Export.

Thanks you for your help.

答:
Tried just linking to my answer on your other version of this question but it decided to automatically make it a comment... Not particularly helpful because people who find this thread in the future might just see it as unanswered so I'll paste the full answer instead.

Not sure whether that's actually in your file or whether it's just in the version you put in your question but "// hello.hs" won't compile. Comments are -- in Haskell not //.

Anyway on to the interesting part...

First you need to import the HsFFI.h header file into your C++ code.

```<code>#include <iostream>
#include "Hello_stub.h"
#include <HsFFI.h>
</code>```

Then use ghc to link the files after compiling them. Open a command prompt / terminal and navigate the directory containing your C++ and Haskell files. Then run the following commands:

```<code>ghc -c -XForeignFunctionInterface -O hello.hs
g++ -c -O main.cpp -I "C:\Program Files\Haskell Platform\7.10.3\lib\include"
ghc -no-hs-main hello.o main.o -lstdc++
</code>```

The filepath in the second command is to the directory containing the HsFFI.h file.

Running main then outputs:

```<code>Hello from C++
Hello from Haskell
</code>```

Title: Interfacing Haskell and C++

Body:
I'd like to call some Haskell functions in a c++ program.

In order to do so, i have applied these
 instructions and adapted them to my code and system.

What I have for the moment is the following:

Main.cpp

Shared header and cpp files

makefile

cpp/

some cpp and header files

haskell/

hello.hs

The make file is the following:

CPP_SOURCES = main.cpp textures.cpp cpp/game.cpp \
cpp/piece.cpp cpp/factories.cpp cpp/utils.cpp
HASKELL_SOURCES = haskell/hello.hs

all: main; ./main

main: $(CPP_SOURCES) HaskellPart.o; g++ \
    -lsfml-graphics \
    -lsfml-window \
    -lsfml-system \
    -I/usr/lib/ghc/include \
    -liconv \
    -I/usr/lib/ghc/ghc-8.0.1/include \
    -L/usr/lib/ghc/ghc-8.0.1 \
    -L/usr/lib/ghc/rts \
    -lHSrts \
    -L/usr/lib/ghc/base-4.9.0.0 \
    -lHSbase-4.9.0.0 \
    -L/usr/lib/ghc/ghc-prim-0.5.0.0 \
    -lHSghc-prim-0.5.0.0 \
    -L/usr/lib/ghc/integer-gmp-1.0.0.1 \
    -lHSinteger-gmp-1.0.0.1 \
    -lHSghc-prim-0.5.0.0 \
    -fno-stack-protector \
    -Wall \
    -o main $(CPP_SOURCES) haskell/hello.o

HaskellPart.o: $(HASKELL_SOURCES); ghc -fforce-recomp -fPIC $(HASKELL_SOURCES)

clean: ; rm -rf main && rm -rf haskell/*.o && \
rm -rf haskell/*.hi && rm -rf haskell/*_stub.h

What I have done is:

add -I/usr/lib/ghc/include to allow g++ to find HsFFI.h

update the librairies paths

add -fPIC to the ghc arguments to avoid symbol errors.

However, I end up with the following output:

    $ make
ghc -fforce-recomp -fPIC haskell/hello.hs
[1 of 1] Compiling Hello            ( haskell/hello.hs, haskell/hello.o )
g++ \
-lsfml-graphics \
-lsfml-window \
-lsfml-system \
-I/usr/lib/ghc/include \
 -liconv \
-L/usr/lib/ghc/rts \
-lHSrts \
-L/usr/lib/ghc/base-4.9.0.0 \
-lHSbase-4.9.0.0 \
-L/usr/lib/ghc/ghc-prim-0.5.0.0 \
-lHSghc-prim-0.5.0.0 \
-L/usr/lib/ghc/integer-gmp-1.0.0.1 \
-lHSinteger-gmp-1.0.0.1 \
-lHSghc-prim-0.5.0.0 \
 -fno-stack-protector \
 -Wall \
 -o main main.cpp textures.cpp cpp/game.cpp cpp/piece.cpp cpp/factories.cpp cpp/utils.cpp haskell/hello.o
/tmp/ccHPRuDY.o: In function `main':
main.cpp:(.text+0x358): undefined reference to `hs_init'
main.cpp:(.text+0x375): undefined reference to `hs_exit'
haskell/hello.o: In function `sRs_info':
/tmp/ghc9fcb_0/ghc_7.o:(.text+0x2e): undefined reference to `newCAF'
/tmp/ghc9fcb_0/ghc_7.o:(.text+0x3e): undefined reference to `stg_bh_upd_frame_info'
/tmp/ghc9fcb_0/ghc_7.o:(.text+0x54): undefined reference to `ghczmprim_GHCziCString_unpackCStringzh_closure'
/tmp/ghc9fcb_0/ghc_7.o:(.text+0x5d): undefined reference to `stg_ap_n_fast'
/tmp/ghc9fcb_0/ghc_7.o:(.text+0x96): undefined reference to `newCAF'
/tmp/ghc9fcb_0/ghc_7.o:(.text+0xa6): undefined reference to `stg_bh_upd_frame_info'
/tmp/ghc9fcb_0/ghc_7.o:(.text+0xbc): undefined reference to `base_SystemziIO_putStrLn_closure'
/tmp/ghc9fcb_0/ghc_7.o:(.text+0xc5): undefined reference to `stg_ap_p_fast'
haskell/hello.o: In function `helloFromHaskell':
(.text+0xd8): undefined reference to `rts_lock'
haskell/hello.o: In function `helloFromHaskell':
(.text+0xee): undefined reference to `base_GHCziTopHandler_runIO_closure'
haskell/hello.o: In function `helloFromHaskell':
(.text+0xf9): undefined reference to `rts_apply'
haskell/hello.o: In function `helloFromHaskell':
(.text+0x10f): undefined reference to `rts_evalIO'
haskell/hello.o: In function `helloFromHaskell':
(.text+0x122): undefined reference to `rts_checkSchedStatus'
haskell/hello.o: In function `helloFromHaskell':
(.text+0x12e): undefined reference to `rts_unlock'
haskell/hello.o: In function `stginit_export_Hello_zdfstableZZC0ZZCmainZZCHelloZZChelloFromHaskell':
ghc_3.c:(.text+0x144): undefined reference to `foreignExportStablePtr'
haskell/hello.o: In function `sRs_closure':
/tmp/ghc9fcb_0/ghc_7.o:(.data+0x40): undefined reference to `stg_IND_STATIC_info'
haskell/hello.o: In function `rHM_closure':
/tmp/ghc9fcb_0/ghc_7.o:(.data+0x60): undefined reference to `ghczmprim_GHCziTypes_TrNameS_static_info'
haskell/hello.o: In function `rI0_closure':
/tmp/ghc9fcb_0/ghc_7.o:(.data+0x70): undefined reference to `ghczmprim_GHCziTypes_TrNameS_static_info'
/tmp/ghc9fcb_0/ghc_7.o:(.data+0x80): undefined reference to `ghczmprim_GHCziTypes_Module_static_info'
haskell/hello.o: In function `SRD_srt':
/tmp/ghc9fcb_0/ghc_7.o:(.data.rel.ro+0x0): undefined reference to `ghczmprim_GHCziCString_unpackCStringzh_closure'
/tmp/ghc9fcb_0/ghc_7.o:(.data.rel.ro+0x8): undefined reference to `base_SystemziIO_putStrLn_closure'
collect2: error: ld returned 1 exit status
makefile:17: recipe for target 'main' failed
make: *** [main] Error 1

Any idea of what I am doing wrong ?

Thank you!

EDIT :

According to n.m answer, I changed the order of g++ arguments. Here's the new makefile:

CPP_SOURCES = main.cpp textures.cpp cpp/game.cpp cpp/piece.cpp cpp/factories.cpp cpp/utils.cpp
HASKELL_SOURCES = haskell/hello.hs
CFLAGS = -Wall -g -fno-stack-protector

all: main; ./main

main: $(CPP_SOURCES) HaskellPart.o; g++ \
    $(CFLAGS) -o main $(CPP_SOURCES) haskell/hello.o \
    -lsfml-graphics \
    -lsfml-window \
    -lsfml-system \
    -I/usr/lib/ghc/include \
    -liconv \
    -I/usr/lib/ghc/ghc-8.0.1/include \
    -L/usr/lib/ghc/ghc-8.0.1 \
    -L/usr/lib/ghc/base-4.9.0.0 \
    -lHSbase-4.9.0.0 \
    -L/usr/lib/ghc/ghc-prim-0.5.0.0 \
    -lHSghc-prim-0.5.0.0 \
    -L/usr/lib/ghc/integer-gmp-1.0.0.1 \
    -lHSinteger-gmp-1.0.0.1 \
    -lHSghc-prim-0.5.0.0 \
    -L/usr/lib/ghc/rts \
    -lHSrts \

HaskellPart.o: $(HASKELL_SOURCES); ghc -fforce-recomp -fPIC $(HASKELL_SOURCES)

clean: ; rm -rf main && rm -rf haskell/*.o && rm -rf haskell/*.hi && rm -rf haskell/*_stub.h

But it raised another error:

/usr/bin/ld: /usr/lib/ghc/rts/libHSrts.a(Itimer.o): undefined reference to symbol 'timer_settime@@GLIBC_2.3.3'

According to this thread, I added -lrt but got:

/usr/bin/ld: /usr/lib/ghc/rts/libHSrts.a(Linker.o): undefined reference to symbol 'dlsym@@GLIBC_2.2.5'

So according to this thread I added -ldl and now it's a big mess...

EDIT : BOUNTY

Guys I'm adding a bounty spending a large proportion of my low amount of reputation because I can't manage to make this work and really need this.

This is for a school related project but I have to precise that this is not cheating as subject only says: "write a large program in c++ and write the same program in haskell".

Making a common graphical interface for both programs is my decision and is out of the scope of the coursework.

Beside that, I think there a lack of documentation on this subject on internet, my teacher told me he never managed to do it so it would be helpful to have a constructed answer on the configuration of g++ with Haskell Foreign Export.

Thanks you for your help.

Body:
Tried just linking to my answer on your other version of this question but it decided to automatically make it a comment... Not particularly helpful because people who find this thread in the future might just see it as unanswered so I'll paste the full answer instead.

Not sure whether that's actually in your file or whether it's just in the version you put in your question but "// hello.hs" won't compile. Comments are -- in Haskell not //.

Anyway on to the interesting part...

First you need to import the HsFFI.h header file into your C++ code.

#include <iostream>
#include "Hello_stub.h"
#include <HsFFI.h>

Then use ghc to link the files after compiling them. Open a command prompt / terminal and navigate the directory containing your C++ and Haskell files. Then run the following commands:

ghc -c -XForeignFunctionInterface -O hello.hs
g++ -c -O main.cpp -I "C:\Program Files\Haskell Platform\7.10.3\lib\include"
ghc -no-hs-main hello.o main.o -lstdc++

The filepath in the second command is to the directory containing the HsFFI.h file.

Running main then outputs:

Hello from C++
Hello from Haskell


问:
c - dynamically allocate variable names
I am trying to take number of inputs from a user and take the inputs then and store them under dynamically created variable names. can anyone help?

I want to take the number of array user want to input then create the exact number of variables which maintains a common pattern so I can know which array is under which variable and I can call them for further processing.

My current code is as follows

```<code> int input, eqn, m, i,n,x;
    char inputarr[100], eqnarr[100];
    printf("Enter number of variables: ");
    scanf("%d",&n);
    m=n;
    printf("Enter your variables: \n");
    while(n!=-1){
    gets(inputarr[n]);
    n--;
    }
    while(m!=0){
    puts(inputarr[m]);
    printf("\n");
    m--;
    }
</code>```

my inputs are like

2 (here 2 is number of inputs user intended to give)

a = 3

b = 4

I need to save them  in 2 variables say var1 and var2 as I need to work with them later.

答:
As mentioned in the comments and answers of others, you cannot dynamically create variables in C.

However, you can follow this approach:

Dynamically read the characters for each line of n expressions (When the
length of input string is not fixed) For ex, Consider n =1 and the
input line is "a=10" Read each character 'a', '=' , '1' , '0'

Parse the string "a=10" to obtain the value 10. Dynamically allocate
memory to store this value 10.

Do this for all n input lines.

Here is the code to achieve this:

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// Dynamically read the input string character by character: Taken from a SO answer
char *inputString(FILE* fp, size_t size){
//The size is extended by the input with the value of the provisional
    char *str;
    int ch;
    size_t len = 0;
    str = realloc(NULL, sizeof(char)*size);//size is start size
    if(!str)return str;
    while(EOF!=(ch=fgetc(fp)) && ch != '\n'){
        str[len++]=ch;
        if(len==size){
            str = realloc(str, sizeof(char)*(size+=16));
            if(!str)return str;
        }
    }
    str[len++]='\0';

    return realloc(str, sizeof(char)*len);
}

int main(void) {
    int n,i,numindex;
    char *variableline,*vartemp;
    char keys[] = "1234567890";

    //Read in the number of variables
    printf("Enter n\n");
    scanf("%d\n",&n);

    printf("Enter %d lines\n",n);
    //Allocate memory for these variables
    int *variable_values = malloc(n*sizeof(int));
    for(i=0;i<n;i++){
        // Read the characters dynamically from the n input lines
        variableline = inputString(stdin, 10);

        //numindex - index where the number starts. For ex, in the string "a=12", numindex is the position of '1'
        numindex = strcspn (variableline,keys);

        //Read the number into vartemp
        vartemp = malloc(strlen(variableline));
        strncpy(vartemp, variableline+numindex, strlen(variableline) - numindex);

        //Convert the string to number
        *(variable_values+i) = atoi(vartemp);
    }

    printf("The variable values are:\n");
    // All the variable values are stored in the dynamically created memory variable_values
    for(i=0;i<n;i++)
    printf("%d\n",variable_values[i]);
    return 0;
}
</code>```

Title: c - dynamically allocate variable names

Body:
I am trying to take number of inputs from a user and take the inputs then and store them under dynamically created variable names. can anyone help?

I want to take the number of array user want to input then create the exact number of variables which maintains a common pattern so I can know which array is under which variable and I can call them for further processing.

My current code is as follows

 int input, eqn, m, i,n,x;
    char inputarr[100], eqnarr[100];
    printf("Enter number of variables: ");
    scanf("%d",&n);
    m=n;
    printf("Enter your variables: \n");
    while(n!=-1){
    gets(inputarr[n]);
    n--;
    }
    while(m!=0){
    puts(inputarr[m]);
    printf("\n");
    m--;
    }

my inputs are like

2 (here 2 is number of inputs user intended to give)

a = 3

b = 4

I need to save them  in 2 variables say var1 and var2 as I need to work with them later.

Body:
As mentioned in the comments and answers of others, you cannot dynamically create variables in C.

However, you can follow this approach:

Dynamically read the characters for each line of n expressions (When the
length of input string is not fixed) For ex, Consider n =1 and the
input line is "a=10" Read each character 'a', '=' , '1' , '0'

Parse the string "a=10" to obtain the value 10. Dynamically allocate
memory to store this value 10.

Do this for all n input lines.

Here is the code to achieve this:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// Dynamically read the input string character by character: Taken from a SO answer
char *inputString(FILE* fp, size_t size){
//The size is extended by the input with the value of the provisional
    char *str;
    int ch;
    size_t len = 0;
    str = realloc(NULL, sizeof(char)*size);//size is start size
    if(!str)return str;
    while(EOF!=(ch=fgetc(fp)) && ch != '\n'){
        str[len++]=ch;
        if(len==size){
            str = realloc(str, sizeof(char)*(size+=16));
            if(!str)return str;
        }
    }
    str[len++]='\0';

    return realloc(str, sizeof(char)*len);
}

int main(void) {
    int n,i,numindex;
    char *variableline,*vartemp;
    char keys[] = "1234567890";

    //Read in the number of variables
    printf("Enter n\n");
    scanf("%d\n",&n);

    printf("Enter %d lines\n",n);
    //Allocate memory for these variables
    int *variable_values = malloc(n*sizeof(int));
    for(i=0;i<n;i++){
        // Read the characters dynamically from the n input lines
        variableline = inputString(stdin, 10);

        //numindex - index where the number starts. For ex, in the string "a=12", numindex is the position of '1'
        numindex = strcspn (variableline,keys);

        //Read the number into vartemp
        vartemp = malloc(strlen(variableline));
        strncpy(vartemp, variableline+numindex, strlen(variableline) - numindex);

        //Convert the string to number
        *(variable_values+i) = atoi(vartemp);
    }

    printf("The variable values are:\n");
    // All the variable values are stored in the dynamically created memory variable_values
    for(i=0;i<n;i++)
    printf("%d\n",variable_values[i]);
    return 0;
}


问:
How can I close this search dropdown after a click?
When I try and add a onClick="{this.displayResults(false)}" to the  the dropdown li, it will not appear.
When I try and add the onClick="{this.displayResults(false)} to the Search Results div, it conflicts with the inputs onChange event.
Any suggestions on how I can close the dropdown when a user clicks a search result?</p>

```<code>import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Link } from 'react-router';
import * as actions from '../actions';

class Search extends Component {

handleSearchTerm(term) {
    if (!term == "") {
        this.props.getSearchResults({term});
        this.displayResults(true);
    } else {
        this.displayResults(false);
    }
}

displayResults(display) {
    if (display === false) {
        $( ".search-results" ).css( "display", "none" );
    } else {
        $( ".search-results" ).css( "display", "block" );
    }
}

buildResultsList() {
    if (!this.props.searchResults) {
        return null;
    } else {
        const searchResultsList = this.props.searchResults.map(function (result) {
            return ([
                <div className="dropdown-divider"></div>,
                <Link to={`/project-spotlight/${result.uri}`} className="dropdown-item" id="search-result"> <li key={result.urlName}>{result.urlName}</li></Link>
            ]);
        });
        return searchResultsList;
    }
}

render() {
    console.log(this.props.searchResults);

    return (
        <div className="search-component">
            <form className="form-inline nav-search">
                <input
                    className="form-control mr-sm-2"
                    onChange={(e) => this.handleSearchTerm(e.target.value)}
                    id="navBarSearchForm"
                    aria-expanded="false"
                    aria-haspopup="true"
                    type="text"
                    placeholder="What Pod you looking for?"
                    autoComplete="off">
                </input>
            </form>
            <ul className="dropdown-menu search-results" >
                <h5 className="dropdown-header">-Pods-</h5>
                {this.buildResultsList()}
            </ul>
        </div>
    );
}

}

function mapStateToProps(state) {
return { searchResults: state.search.searchResult};
}

export default connect(mapStateToProps, actions)(Search);
</code>```

答:
Add event.preventDefault(); to your handler method

If this method is called, the default action of the event will not be
  triggered.

```<code>import React, { Component } from 'react';

export default class MyComponent extends Component {
  handleClick(event) {
    event.preventDefault();
    //...
  }

  render() {
    return (<button onClick={this.handleClick.bind(this)}>Submit</button>)
  }
}
</code>```

Body:
When I try and add a onClick="{this.displayResults(false)}" to the  the dropdown li, it will not appear.
When I try and add the onClick="{this.displayResults(false)} to the Search Results div, it conflicts with the inputs onChange event.
Any suggestions on how I can close the dropdown when a user clicks a search result?

import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Link } from 'react-router';
import * as actions from '../actions';

class Search extends Component {

handleSearchTerm(term) {
    if (!term == "") {
        this.props.getSearchResults({term});
        this.displayResults(true);
    } else {
        this.displayResults(false);
    }
}

displayResults(display) {
    if (display === false) {
        $( ".search-results" ).css( "display", "none" );
    } else {
        $( ".search-results" ).css( "display", "block" );
    }
}

buildResultsList() {
    if (!this.props.searchResults) {
        return null;
    } else {
        const searchResultsList = this.props.searchResults.map(function (result) {
            return ([

,
                <Link to={`/project-spotlight/${result.uri}`} className="dropdown-item" id="search-result">
{result.urlName}
</Link>
            ]);
        });
        return searchResultsList;
    }
}

render() {
    console.log(this.props.searchResults);

    return (

            <form className="form-inline nav-search">
                <input
                    className="form-control mr-sm-2"
                    onChange={(e) => this.handleSearchTerm(e.target.value)}
                    id="navBarSearchForm"
                    aria-expanded="false"
                    aria-haspopup="true"
                    type="text"
                    placeholder="What Pod you looking for?"
                    autoComplete="off">
                </input>
            </form>

-Pods-

                {this.buildResultsList()}

    );
}

}

function mapStateToProps(state) {
return { searchResults: state.search.searchResult};
}

export default connect(mapStateToProps, actions)(Search);

Body:
Add event.preventDefault(); to your handler method

If this method is called, the default action of the event will not be
  triggered.

import React, { Component } from 'react';

export default class MyComponent extends Component {
  handleClick(event) {
    event.preventDefault();
    //...
  }

  render() {
    return (<button onClick={this.handleClick.bind(this)}>Submit</button>)
  }
}


问:
Python Pandas: Adding boolean columns to assist in filtering on one True value per record
How can pandas dataframe boolean columns be added together to create a column with the count of true values?

For example, the purpose is to create the 'count' column:

```<code>a       b       c       count
TRUE    FALSE   FALSE   1
TRUE    TRUE    FALSE   2
TRUE    TRUE    TRUE    3
</code>```

Following addition of booleans in python (e.g. True + True = 2), tried:

```<code>df.count = df.a + df.b + df.c
</code>```

Which didn't work and produced warning:

```<code>UserWarning: evaluating in Python space because the '+' operator is not supported by numexpr for the bool dtype, use '|' instead
  unsupported[op_str]))
</code>```

The purpose is to make it easier to filter on records that have only one True value.

答:
You can use sum function, .sum(1) will count the trues for each row:

```<code>df['count'] = df[list("abc")].sum(1)
df
</code>```

Body:
How can pandas dataframe boolean columns be added together to create a column with the count of true values?

For example, the purpose is to create the 'count' column:

a       b       c       count
TRUE    FALSE   FALSE   1
TRUE    TRUE    FALSE   2
TRUE    TRUE    TRUE    3

Following addition of booleans in python (e.g. True + True = 2), tried:

df.count = df.a + df.b + df.c

Which didn't work and produced warning:

UserWarning: evaluating in Python space because the '+' operator is not supported by numexpr for the bool dtype, use '|' instead
  unsupported[op_str]))

The purpose is to make it easier to filter on records that have only one True value.

Body:
You can use sum function, .sum(1) will count the trues for each row:

df['count'] = df[list("abc")].sum(1)
df


问:
UNIQUE Constraint, only when a field contains a specific value
I'm trying to create a UNIQUE INDEX constraint for two columns, but only when another column contains the value 1. For example, column_1 and column_2 should be UNIQUE only when active = 1. Any rows that contain active = 0 can share values for column_1 and column_2 with another row, regardless of what the other row's value for active is. But rows where active = 1 cannot share values of column_1 or column_2 with another row that has active = 1.

What I mean by "share" is two rows having the same value(s) in the same column(s). Example: row1.a = row2.a AND row1.b = row2.b. Values would be shared only if both columns in row1 matched the other two columns in row2.

I hope I made myself clear. :\

答:
I'm trying to create a UNIQUE INDEX constraint for two columns, but only when another column contains the value 1

You can set the value of "another column" to a unique value that does not equal to 1. for example the id of a record.

Then the unique index constraint could be applied to all three columns including the "another column". Let's call the "another column" columnX.
Set the value of columnX to 1 if you want to apply the unique constraint to a record. Set the value of columnX to a unique value if you don't want to apply the unique constraint.

Then no extra work/triggers needed. The unique index to all three columns could solve your problem.


问:
C++ std::ifstream std::ios::in versus std::ios::in | std::ios::binary, why do I get junk data?
I'm curious when I call read on an std::ifstream object, why I get junk data if I open the file as std::ios::in, whereas I don't get junk data with std::ios::in | std::ios::binary?

I included screenshots of some messy code I've been trying stuff out with. I'm just confused why I get junk data with the first picture, when the second picture produces the correct data with the std::ios::binary flag set.

Junk data, but correct file length:

No junk data, same file length:

答:
In text mode, certain characters may be transformed.

On cppreference, it says this about binary vs. text mode for files:

Data read in from a text stream is guaranteed to compare equal to the
  data that were earlier written out to that stream only if all of the
  following is true:

the data consist only of printing characters and the control
  characters \t and \n (in particular, on Windows OS, the
  character '\0x1A' terminates input)

no \n is immediately preceded by a space character (space
  characters that are written out immediately
  before a \n may disappear when read)

the last character is \n

At a guess I would say that some of the characters in your input file do not obey these rules.


问:
InfoPath 2013 development with error "Cannot start debugging. Pre-debugging negotiations with Host failed."
I am using Visual Studio 2012 (exclusively for InfoPath development, nothing else because of Microsoft) and Visual Studio 2013 for other development including SSRS, SSIS. I made a move to 2015 last week and that is where troubles came.

After installing VS2015 with SSTD update, I cannot debug or work on InfoPath form code any more. Everytime I try to debug or save the form with code, I get:

```<code>Cannot start debugging. Pre-debugging negotiations with Host failed.
</code>```

I know this error is popular with SSIS rather than VSTA, I couldn't find any post relate to this issue in VSTA in general and InfoPath in specific. I have tried a lot of suggestion for the SSIS one when possible but nothing works.

I still need to do work on InfoPath 2013 form code (legacy project) and also have to use 2015, or 2017 for other projects. Any suggestion is appreciated.

Update:

Uninstall VS2012 and reinstall it doesn't help. Same with VSTA uninstalled and reinstalled. VS2015 is a big effort to uninstall so I leave it alone.

Reinstalled Windows 10, InfoPath 2013, Visual Studio 2012 Update 5, VSTA 2012 then Visual Studio 2017 in exact order. Same issue.

答:
Apparently the only option is remove Visual Studio Tools for Application 2015 or later then reinstall/repair Visual Studio Tools for Application 2012. If you have to use VSTA 2015 for your SSIS or something else, you may need a separate machine.

I have reached MS but there is no response. I don't think this should be an answer for this issue but I would leave it here in case anyone needs help.

Body:
I am using Visual Studio 2012 (exclusively for InfoPath development, nothing else because of Microsoft) and Visual Studio 2013 for other development including SSRS, SSIS. I made a move to 2015 last week and that is where troubles came.

After installing VS2015 with SSTD update, I cannot debug or work on InfoPath form code any more. Everytime I try to debug or save the form with code, I get:

Cannot start debugging. Pre-debugging negotiations with Host failed.

I know this error is popular with SSIS rather than VSTA, I couldn't find any post relate to this issue in VSTA in general and InfoPath in specific. I have tried a lot of suggestion for the SSIS one when possible but nothing works.

I still need to do work on InfoPath 2013 form code (legacy project) and also have to use 2015, or 2017 for other projects. Any suggestion is appreciated.

Update:

Uninstall VS2012 and reinstall it doesn't help. Same with VSTA uninstalled and reinstalled. VS2015 is a big effort to uninstall so I leave it alone.

Reinstalled Windows 10, InfoPath 2013, Visual Studio 2012 Update 5, VSTA 2012 then Visual Studio 2017 in exact order. Same issue.


问:
Break error while creating a calendar

Have break error Thread 1: EXC_BAD_INSTRUCTION (code=EXC_1386_INVOP, subcode==0x0). No errors with build, just when run, have a break

```<code>func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if let calendars = self.calendars {
        return calendars.count
    }
    return 0

}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell")!
</code>```

//error happens here

```<code>    if self.calendars != nil {
    let calendarName = self.calendars?[(indexPath as NSIndexPath).row].title
        cell.textLabel?.text = calendarName
    } else {
        cell.textLabel?.text = "Unknown Calendar Name"
    }
    return cell
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    let destinationVC = segue.destination as! UINavigationController
    let addCalendarVC = destinationVC.viewControllers[0] as! AddCalendarViewController
    addCalendarVC.delegate = self
}
func calendarDidAdd() {
    self.loadCalendars()
    self.refreshTableView()
}
</code>```

}

答:
The immediate red flag I see is here:

```<code>let cell = tableView.dequeueReusableCell(withIdentifier: "Cell")!
</code>```

When dequeueing reusable cells, I like to wrap them in guard statements, so my app doesn't crash. It also tells me a bit more information when something does go wrong:

```<code>guard let cell = tableView.dequeueReusableCell(withIdentifier: "Cell") else {
    print("couldn't dequeue a reusable cell for identifier Cell in \(#function)")
    return UITableViewCell()
}
</code>```

This crash could be for a few reasons. You may have forgotten to register the reuse identifier, but if you're using storyboards this is handled for you. There may simply be a typo or you forgot to enter a reuse identifier for that cell.

Title: Break error while creating a calendar

Body:
Have break error Thread 1: EXC_BAD_INSTRUCTION (code=EXC_1386_INVOP, subcode==0x0). No errors with build, just when run, have a break

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if let calendars = self.calendars {
        return calendars.count
    }
    return 0

}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell")!

//error happens here

    if self.calendars != nil {
    let calendarName = self.calendars?[(indexPath as NSIndexPath).row].title
        cell.textLabel?.text = calendarName
    } else {
        cell.textLabel?.text = "Unknown Calendar Name"
    }
    return cell
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    let destinationVC = segue.destination as! UINavigationController
    let addCalendarVC = destinationVC.viewControllers[0] as! AddCalendarViewController
    addCalendarVC.delegate = self
}
func calendarDidAdd() {
    self.loadCalendars()
    self.refreshTableView()
}

}

Body:
The immediate red flag I see is here:

let cell = tableView.dequeueReusableCell(withIdentifier: "Cell")!

When dequeueing reusable cells, I like to wrap them in guard statements, so my app doesn't crash. It also tells me a bit more information when something does go wrong:

guard let cell = tableView.dequeueReusableCell(withIdentifier: "Cell") else {
    print("couldn't dequeue a reusable cell for identifier Cell in \(#function)")
    return UITableViewCell()
}

This crash could be for a few reasons. You may have forgotten to register the reuse identifier, but if you're using storyboards this is handled for you. There may simply be a typo or you forgot to enter a reuse identifier for that cell.


问:
Android - OkHttp 3.6.0 Adress.class Duplication
I've come across similar issues which indicates the same problem. However, in my case it seems to be happening in a different way which shouldn't produce this issue as described below:

Imagine I have two internal private libraries, published on private maven repository named as below:

```<code>com.x.y.analytics
com.x.y.player
</code>```

Both of these libraries use OkHttp 3.6.0 with the given code snippet below:

```<code>provided 'com.squareup.okhttp3:okhttp:3.6.0'
</code>```

So basically, I don't include the actual library when I'm releasing an aar to maven, I compile this and provide it to mentioned libraries from the parent project with the code snippet below:

```<code>compile 'com.squareup.okhttp3:okhttp:3.6.0'
</code>```

However, even though everything should be fine due that there is only 1 compiled version of this library, I have the error given below:

Error:Execution failed for task
  ':application:transformClassesWithJarMergingForDebug'.

com.android.build.api.transform.TransformException: java.util.zip.ZipException: duplicate entry: okhttp3/Address.class

I believe this issue would happen if I used compile to inject the library inside the private libraries but since I use provided could you elaborate the issue if there are any leads to a fix?

PS: There is also an issue for GitHub project of OkHttp which can be found here.

答:
I had the same issue. And I tried to add this line

```<code>android {
configurations {
all*.exclude group: 'com.squareup.okhttp3', module: 'okhttp'
}
}
</code>```

And It works fine for me. Please try to do it.

Body:
I've come across similar issues which indicates the same problem. However, in my case it seems to be happening in a different way which shouldn't produce this issue as described below:

Imagine I have two internal private libraries, published on private maven repository named as below:

com.x.y.analytics
com.x.y.player

Both of these libraries use OkHttp 3.6.0 with the given code snippet below:

provided 'com.squareup.okhttp3:okhttp:3.6.0'

So basically, I don't include the actual library when I'm releasing an aar to maven, I compile this and provide it to mentioned libraries from the parent project with the code snippet below:

compile 'com.squareup.okhttp3:okhttp:3.6.0'

However, even though everything should be fine due that there is only 1 compiled version of this library, I have the error given below:

Error:Execution failed for task
  ':application:transformClassesWithJarMergingForDebug'.

com.android.build.api.transform.TransformException: java.util.zip.ZipException: duplicate entry: okhttp3/Address.class

I believe this issue would happen if I used compile to inject the library inside the private libraries but since I use provided could you elaborate the issue if there are any leads to a fix?

PS: There is also an issue for GitHub project of OkHttp which can be found here.

Body:
I had the same issue. And I tried to add this line

android {
configurations {
all*.exclude group: 'com.squareup.okhttp3', module: 'okhttp'
}
}

And It works fine for me. Please try to do it.


问:
Convert IP's in Numeric to traditional IP display
I am trying to convert IP addresses from numeric (eg 4183726815 ) to the actual traditional IP display (eg 192.168.1.230) in MS SQL Server.

I have found other code (below), however I then get an error.

```<code>CREATE FUNCTION dbo.IntegerToIPAddress (@IP AS bigint)

RETURNS varchar(15)

AS

BEGIN

DECLARE @Octet1 tinyint

DECLARE @Octet2 tinyint

DECLARE @Octet3 tinyint

DECLARE @Octet4 tinyint

DECLARE @RestOfIP bigint

SET @Octet1 = @IP / 16777216

SET @RestOfIP = @IP - (@Octet1 * 16777216)

SET @Octet2 = @RestOfIP / 65536

SET @RestOfIP = @RestOfIP - (@Octet2 * 65536)

SET @Octet3 = @RestOfIP / 256

SET @Octet4 = @RestOfIP - (@Octet3 * 256)

RETURN(CONVERT(varchar, @Octet1) + '.' +

CONVERT(varchar, @Octet2) + '.' +

CONVERT(varchar, @Octet3) + '.' +

CONVERT(varchar, @Octet4))

END
</code>```

And when I run

```<code>SELECT dbo.IntegerToIPAddress(2130806436)
</code>```

It returns 127.1.134.164. Which is exactly what is required.

However, when I run my data ip's , I get the following error:
eg

```<code>SELECT dbo.IntegerToIPAddress2(3232235780)
</code>```

Arithmetic overflow error converting expression to data type int.

Any ideas? Or should I try another approach from the above code?

Thanks folks! :)

答:
MySQL has INET_NTOA and INET_ATON built in functions;
https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html#function_inet-aton
Google search revealed that MS SQL has those as well.
Hope this helps someone looking for an answer now.</p>

Body:
I am trying to convert IP addresses from numeric (eg 4183726815 ) to the actual traditional IP display (eg 192.168.1.230) in MS SQL Server.

I have found other code (below), however I then get an error.

CREATE FUNCTION dbo.IntegerToIPAddress (@IP AS bigint)

RETURNS varchar(15)

AS

BEGIN

DECLARE @Octet1 tinyint

DECLARE @Octet2 tinyint

DECLARE @Octet3 tinyint

DECLARE @Octet4 tinyint

DECLARE @RestOfIP bigint

SET @Octet1 = @IP / 16777216

SET @RestOfIP = @IP - (@Octet1 * 16777216)

SET @Octet2 = @RestOfIP / 65536

SET @RestOfIP = @RestOfIP - (@Octet2 * 65536)

SET @Octet3 = @RestOfIP / 256

SET @Octet4 = @RestOfIP - (@Octet3 * 256)

RETURN(CONVERT(varchar, @Octet1) + '.' +

CONVERT(varchar, @Octet2) + '.' +

CONVERT(varchar, @Octet3) + '.' +

CONVERT(varchar, @Octet4))

END

And when I run

SELECT dbo.IntegerToIPAddress(2130806436)

It returns 127.1.134.164. Which is exactly what is required.

However, when I run my data ip's , I get the following error:
eg

SELECT dbo.IntegerToIPAddress2(3232235780)

Arithmetic overflow error converting expression to data type int.

Any ideas? Or should I try another approach from the above code?

Thanks folks! :)


问:
Symfony 3 Datafixtures using parameter.yml values
I'm using LDAP in my User data fixtures and I don't want to hardcode the LDAP login options. Initially, I tried this:

```<code>$options = array(
            'host' => '%ldap_host%',
            'port' => '%ldap_port%',
            'useSsl' => true,
            'username' => '%ldap_username%',
            'password' => '%ldap_password%',
            'baseDn' => '%ldap_baseDn_users%'
        );
</code>```

But that didn't work. I did some research and realized I needed to include the container in my fixtures. However, it's at this point I'm unsure what my next step is.

As I understand it I need to use the container and it's get method to get the service containing the parameters, but I don't know what that is:

```<code>$this->container->get('parameters');
</code>```

Doesn't work, so I'm wondering what I should use.

My full datafixture is as follows:

```<code>class LoadFOSUsers extends AbstractFixture implements OrderedFixtureInterface, ContainerAwareInterface
{
    /**
     * @var ContainerInterface
     */
    private $container;

    public function setContainer(ContainerInterface $container = null)
    {
        $this->container = $container;
    }

    public function load(ObjectManager $manager)
    {
        $this->container->get('parameters');

        // Not sure how to access param values.
        $options = array(
            'host' => '%ldap_host%',
            'port' => '%ldap_port%',
            'useSsl' => true,
            'username' => '%ldap_username%',
            'password' => '%ldap_password%',
            'baseDn' => '%ldap_baseDn_users%'
        );

        $ldap = new Ldap($options);
        $ldap->bind();

        $baseDn = '%ldap_baseDn_users%';
        $filter = '(&(&(ObjectClass=user))(samaccountname=*))';
        $attributes=['samaccountname', 'dn', 'mail','memberof'];
        $result = $ldap->searchEntries($filter, $baseDn, Ldap::SEARCH_SCOPE_SUB, $attributes);

        foreach ($result as $item) {
            echo $item["dn"] . ': ' . $item['samaccountname'][0] . PHP_EOL;
        }
    }

    public function getOrder()
    {
        // the order in which fixtures will be loaded
        // the lower the number, the sooner that this fixture is loaded
        return 8;
    }
}
</code>```

答:
You just have to fetch them from container via getParameter('name') or get them all in a bag via getParameterBag().

So:

```<code>    $options = array(
        'host' => $this->container->getParameter('ldap_host'),
        'port' => $this->container->getParameter('ldap_port'),
        'useSsl' => true,
        'username' => $this->container->getParameter('ldap_username'),
        'password' => $this->container->getParameter('ldap_password'),
        'baseDn' => $this->container->getParameter('ldap_baseDn_users')
    );
</code>```

etc.

Body:
I'm using LDAP in my User data fixtures and I don't want to hardcode the LDAP login options. Initially, I tried this:

$options = array(
            'host' => '%ldap_host%',
            'port' => '%ldap_port%',
            'useSsl' => true,
            'username' => '%ldap_username%',
            'password' => '%ldap_password%',
            'baseDn' => '%ldap_baseDn_users%'
        );

But that didn't work. I did some research and realized I needed to include the container in my fixtures. However, it's at this point I'm unsure what my next step is.

As I understand it I need to use the container and it's get method to get the service containing the parameters, but I don't know what that is:

$this->container->get('parameters');

Doesn't work, so I'm wondering what I should use.

My full datafixture is as follows:

class LoadFOSUsers extends AbstractFixture implements OrderedFixtureInterface, ContainerAwareInterface
{
    /**
     * @var ContainerInterface
     */
    private $container;

    public function setContainer(ContainerInterface $container = null)
    {
        $this->container = $container;
    }

    public function load(ObjectManager $manager)
    {
        $this->container->get('parameters');

        // Not sure how to access param values.
        $options = array(
            'host' => '%ldap_host%',
            'port' => '%ldap_port%',
            'useSsl' => true,
            'username' => '%ldap_username%',
            'password' => '%ldap_password%',
            'baseDn' => '%ldap_baseDn_users%'
        );

        $ldap = new Ldap($options);
        $ldap->bind();

        $baseDn = '%ldap_baseDn_users%';
        $filter = '(&(&(ObjectClass=user))(samaccountname=*))';
        $attributes=['samaccountname', 'dn', 'mail','memberof'];
        $result = $ldap->searchEntries($filter, $baseDn, Ldap::SEARCH_SCOPE_SUB, $attributes);

        foreach ($result as $item) {
            echo $item["dn"] . ': ' . $item['samaccountname'][0] . PHP_EOL;
        }
    }

    public function getOrder()
    {
        // the order in which fixtures will be loaded
        // the lower the number, the sooner that this fixture is loaded
        return 8;
    }
}

Body:
You just have to fetch them from container via getParameter('name') or get them all in a bag via getParameterBag().

So:

    $options = array(
        'host' => $this->container->getParameter('ldap_host'),
        'port' => $this->container->getParameter('ldap_port'),
        'useSsl' => true,
        'username' => $this->container->getParameter('ldap_username'),
        'password' => $this->container->getParameter('ldap_password'),
        'baseDn' => $this->container->getParameter('ldap_baseDn_users')
    );

etc.


问:
How to link dates with merge and get relevant calculated field?
Lets say i have 4 customers ( ID - 1,2,3,4)
I have data in two tables :

```<code>Table 1 - lists down the dates of Purchase of A( only once a year)
ID     Date of Purchase
1       10-03-2014
2       15-05-2014
3       13-09-2014
4       15-10-2015

Table 2 - lists down dates of purchase of B( can be multiple times )
ID     Date of Purchase
1       10-01-2014
1       15-05-2014
1       15-10-2014
2       13-06-2014
2       15-10-2015
3       23-11-2014
4       22-09-2016
</code>```

What i need is a table giving :

Difference in dates(purchase of A from Purchase of B) for a customer with condition

The purchase date of B should be > then Purchase date of A

The difference in date should be with first purchase of B ( made after purchase of A )

Example for ID 1 -
1. Purchase of A was in 3rd month . And first purchase of B after 3rd month is in 5th month so difference is 2 months ( or equivalent days )

Example for ID 2 - Purchase of A was in 5th month , first purchase of B is in 6th month , so difference is 1 month ( or equivalent days )

```<code>Table3
ID   Difference days
1      60
2      30
</code>```

How do i get that in R ?

答:
You could use this approach:

```<code>tab1 <- data.frame(ID= c(1,2,3,4),  Date_of_Purchase = as.Date( c("10-03-2014","15-05-2014","13-09-2014","15-10-2015"), format = "%d-%m-%Y"))
tab2 <- data.frame(ID= c(1,1,1,2,2,3,4),  Date_of_Purchase = as.Date( c("10-01-2014","15-05-2014 ","15-10-2014","13-06-2014","15-05-2014 ","15-10-2014","13-06-2014"), format = "%d-%m-%Y"))
library("dplyr")
tab <- tab1 %>% left_join(tab2, c("ID" = "ID"))
tab$dif <- tab$Date_of_Purchase.y- tab$Date_of_Purchase.x
</code>```

then group by id and select the min

```<code>tab <- filter(tab, dif > 0)
tab3 <-   tab %>%
  dplyr::group_by(ID) %>%
  dplyr::summarise(min = min(dif))
</code>```

Results:

```<code>     ID      min
  <dbl>   <time>
1     1  66 days
2     2  29 days
3     3  71 days
4     4 343 days
</code>```

Body:
Lets say i have 4 customers ( ID - 1,2,3,4)
I have data in two tables :

Table 1 - lists down the dates of Purchase of A( only once a year)
ID     Date of Purchase
1       10-03-2014
2       15-05-2014
3       13-09-2014
4       15-10-2015

Table 2 - lists down dates of purchase of B( can be multiple times )
ID     Date of Purchase
1       10-01-2014
1       15-05-2014
1       15-10-2014
2       13-06-2014
2       15-10-2015
3       23-11-2014
4       22-09-2016

What i need is a table giving :

Difference in dates(purchase of A from Purchase of B) for a customer with condition

The purchase date of B should be > then Purchase date of A

The difference in date should be with first purchase of B ( made after purchase of A )

Example for ID 1 -
1. Purchase of A was in 3rd month . And first purchase of B after 3rd month is in 5th month so difference is 2 months ( or equivalent days )

Example for ID 2 - Purchase of A was in 5th month , first purchase of B is in 6th month , so difference is 1 month ( or equivalent days )

Table3
ID   Difference days
1      60
2      30

How do i get that in R ?

Body:
You could use this approach:

tab1 <- data.frame(ID= c(1,2,3,4),  Date_of_Purchase = as.Date( c("10-03-2014","15-05-2014","13-09-2014","15-10-2015"), format = "%d-%m-%Y"))
tab2 <- data.frame(ID= c(1,1,1,2,2,3,4),  Date_of_Purchase = as.Date( c("10-01-2014","15-05-2014 ","15-10-2014","13-06-2014","15-05-2014 ","15-10-2014","13-06-2014"), format = "%d-%m-%Y"))
library("dplyr")
tab <- tab1 %>% left_join(tab2, c("ID" = "ID"))
tab$dif <- tab$Date_of_Purchase.y- tab$Date_of_Purchase.x

then group by id and select the min

tab <- filter(tab, dif > 0)
tab3 <-   tab %>%
  dplyr::group_by(ID) %>%
  dplyr::summarise(min = min(dif))

Results:

     ID      min
  <dbl>   <time>
1     1  66 days
2     2  29 days
3     3  71 days
4     4 343 days


问:
How do I turn off the gutter icons in the IntelliJ IDEA editor?
I want the implementing and override gutter icons turned off in the gutter (next to the line numbers). Their rendering is causing my editor window to jump every time they redraw (with each keystroke I type), and it is driving me nuts. I'm using version 8.1.4.</p>

答:
IntelliJ IDEA 2017

Approach 1

File > Settings... > Editor > General > Gutter Icons > uncheck Show gutter icons

 Settings > Editor > General > Gutter Icons">

Approach 2

Help > Find Action... (Ctrl + Shift + A) > type "Show Gutter" and switch the toggle using Enter or mouse left click.

Body:
IntelliJ IDEA 2017

Approach 1

File > Settings... > Editor > General > Gutter Icons > uncheck Show gutter icons

Approach 2

Help > Find Action... (Ctrl + Shift + A) > type "Show Gutter" and switch the toggle using Enter or mouse left click.


问:
lambda with more than one effect
I have three different classes of some common interface Bag. Those are simple containers with some properties. I can add a bunch of stuff in them, e.g ints. For purposes of unit testing, I wanted to add a number of values to each and every one of those Bags. So I used the following IntConsumer:

```<code>IntStream.rangeClosed(1, 300).forEach(new IntConsumer() {
    @Override
    public void accept(int value) {
        staticBag.add(value);
        shuffledBag.add(value);
        randomAccessBag.add(value);
        }
    });
</code>```

My question is how that might be changeable to a lambda expression. Intellij is usually doing a pretty good job at changing those things automatically, but at this point it hasn't been showing me any tips.

答:
add a utility method accept(IntConsumer) you can chain the functions with IntConsumer.andThen.

```<code>IntStream.rangeClosed(1, 300).forEach(accept(staticBag::add)
                                     .andThen(shuffledBag::add)
                                     .andThen(randomAccessBag::add));

private IntConsumer accept(IntConsumer consumer) {
    return consumer;
}
</code>```

OR add a utility method accept(IntConsumer...) to composing all consumers using Stream.reduce(BinaryOperator).

```<code>IntStream.rangeClosed(1, 300).forEach(accept(staticBag::add
                                     /**/, shuffledBag::add
                                     /**/, randomAccessBag::add));

private IntConsumer accept(IntConsumer... consumers) {
    IntConsumer nothing = (value) -> { };
    return Arrays.stream(consumers).reduce(IntConsumer::andThen).orElse(nothing);
}
</code>```

Title: lambda with more than one effect

Body:
I have three different classes of some common interface Bag. Those are simple containers with some properties. I can add a bunch of stuff in them, e.g ints. For purposes of unit testing, I wanted to add a number of values to each and every one of those Bags. So I used the following IntConsumer:

IntStream.rangeClosed(1, 300).forEach(new IntConsumer() {
    @Override
    public void accept(int value) {
        staticBag.add(value);
        shuffledBag.add(value);
        randomAccessBag.add(value);
        }
    });

My question is how that might be changeable to a lambda expression. Intellij is usually doing a pretty good job at changing those things automatically, but at this point it hasn't been showing me any tips.

Body:
add a utility method accept(IntConsumer) you can chain the functions with IntConsumer.andThen.

IntStream.rangeClosed(1, 300).forEach(accept(staticBag::add)
                                     .andThen(shuffledBag::add)
                                     .andThen(randomAccessBag::add));

private IntConsumer accept(IntConsumer consumer) {
    return consumer;
}

OR add a utility method accept(IntConsumer...) to composing all consumers using Stream.reduce(BinaryOperator).

IntStream.rangeClosed(1, 300).forEach(accept(staticBag::add
                                     /**/, shuffledBag::add
                                     /**/, randomAccessBag::add));

private IntConsumer accept(IntConsumer... consumers) {
    IntConsumer nothing = (value) -> { };
    return Arrays.stream(consumers).reduce(IntConsumer::andThen).orElse(nothing);
}


问:
Which commit to use when git commit?
For example, in the beginning, master is in commit01, which is OK, then I merged branch001 which contains 2 commits into master, then became:

```<code>commit04 Merge branch001 into master
commit03 commit from branch001
commit02 commit from branch001
commit01 master commit
</code>```

Then I found that there is a big bug in branch001, so I want to go back to commit01, if I use git revert, which commit should I use?

答:
if you git revert commit04, it will revert all of the changes to the master branch performed by the merge.

If you haven't pushed this to a remote yet you can run git reset --hard commit01 to restore your working tree to its state at commit01 and erase commits02-4.

Title: Which commit to use when git commit?

Body:
For example, in the beginning, master is in commit01, which is OK, then I merged branch001 which contains 2 commits into master, then became:

commit04 Merge branch001 into master
commit03 commit from branch001
commit02 commit from branch001
commit01 master commit

Then I found that there is a big bug in branch001, so I want to go back to commit01, if I use git revert, which commit should I use?


问:
jQuery: Loop print only one value
I have below code

```<code><script src="https://code.jquery.com/jquery-3.2.0.min.js"></script>
<table id="main_table">
    <tr>
        <td><input name="" value="3" id="id_3" checked="checked" type="checkbox"></td>
        <td><input name="qty[]" value="5.0000" type="text"></td>
    </tr>
    <tr>
        <td><input name="" value="4" id="id_4" checked="checked" type="checkbox"></td>
        <td><input name="qty[]" value="2.0000" type="text"></td>
    </tr>
    <tr>
        <td><input name="" value="5" id="id_5" checked="checked" type="checkbox"></td>
        <td><input name="qty[]" value="3.0000" type="text"></td>
    </tr>
</table>
<script>
jQuery('table#main_table').each( function(){
    if(jQuery(this).find("input:checkbox").is(':checked')){
         var txt = jQuery(this).find("input[name='qty[]']").val();
         alert(txt);
    }
});
</code>```

I need to check within table if checkbox is checked then print it's qty value.  But below code only prints 1 value. Instead of all

What I'm missing?

答:
You're using each on
 which will iterate only once as there is only one table with that ID. Iterate over the
 elements in the table.

```<code>$('#main_table tr').each(function() {
    ...
</code>```

jQuery('table#main_table tr').each(function() {
  if (jQuery(this).find("input:checkbox").is(':checked')) {
    var txt = jQuery(this).find("input[name='qty[]']").val();
    console.log(txt);
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="main_table">
  <tr>
    <td><input name="" value="3" id="id_3" checked="checked" type="checkbox"></td>
    <td><input name="qty[]" value="5.0000" type="text"></td>
  </tr>
  <tr>
    <td><input name="" value="4" id="id_4" checked="checked" type="checkbox"></td>
    <td><input name="qty[]" value="2.0000" type="text"></td>
  </tr>
  <tr>
    <td><input name="" value="5" id="id_5" checked="checked" type="checkbox"></td>
    <td><input name="qty[]" value="3.0000" type="text"></td>
  </tr>
</table></code>```

There's better way to do this. Instead of iterating over tr and finding checked checkboxes, you can iterate over checked checkboxes and get the value of the associated textbox.

```<code>$(this)                       // Will refer to the checkbox
    .closest('td')            // Get parent <td>
    .next()                   // Get next element i.e. next <td>
    .find('[name="qty[]"]')   // Find element with name attribute value as "qty[]"
    .val()                    // Get it's value
</code>```

$('#main_table tr :checkbox:checked').each(function() {
  console.log($(this).closest('td').next().find('[name="qty[]"]').val());
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="main_table">
  <tr>
    <td><input name="" value="3" id="id_3" checked="checked" type="checkbox"></td>
    <td><input name="qty[]" value="5.0000" type="text"></td>
  </tr>
  <tr>
    <td><input name="" value="4" id="id_4" checked="checked" type="checkbox"></td>
    <td><input name="qty[]" value="2.0000" type="text"></td>
  </tr>
  <tr>
    <td><input name="" value="5" id="id_5" checked="checked" type="checkbox"></td>
    <td><input name="qty[]" value="3.0000" type="text"></td>
  </tr>
</table></code>```

Title: jQuery: Loop print only one value

Body:
I have below code

        <input name="" value="3" id="id_3" checked="checked" type="checkbox">
        <input name="qty[]" value="5.0000" type="text">

        <input name="" value="4" id="id_4" checked="checked" type="checkbox">
        <input name="qty[]" value="2.0000" type="text">

        <input name="" value="5" id="id_5" checked="checked" type="checkbox">
        <input name="qty[]" value="3.0000" type="text">

Body:
You're using each on <table> which will iterate only once as there is only one table with that ID. Iterate over the <tr> elements in the table.

$('#main_table tr').each(function() {
    ...

jQuery('table#main_table tr').each(function() {
  if (jQuery(this).find("input:checkbox").is(':checked')) {
    var txt = jQuery(this).find("input[name='qty[]']").val();
    console.log(txt);
  }
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="main_table">
  <tr>
    <td><input name="" value="3" id="id_3" checked="checked" type="checkbox"></td>
    <td><input name="qty[]" value="5.0000" type="text"></td>
  </tr>
  <tr>
    <td><input name="" value="4" id="id_4" checked="checked" type="checkbox"></td>
    <td><input name="qty[]" value="2.0000" type="text"></td>
  </tr>
  <tr>
    <td><input name="" value="5" id="id_5" checked="checked" type="checkbox"></td>
    <td><input name="qty[]" value="3.0000" type="text"></td>
  </tr>
</table>

There's better way to do this. Instead of iterating over tr and finding checked checkboxes, you can iterate over checked checkboxes and get the value of the associated textbox.

$(this)                       // Will refer to the checkbox
    .closest('td')            // Get parent <td>
    .next()                   // Get next element i.e. next <td>
    .find('[name="qty[]"]')   // Find element with name attribute value as "qty[]"
    .val()                    // Get it's value

$('#main_table tr :checkbox:checked').each(function() {
  console.log($(this).closest('td').next().find('[name="qty[]"]').val());
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="main_table">
  <tr>
    <td><input name="" value="3" id="id_3" checked="checked" type="checkbox"></td>
    <td><input name="qty[]" value="5.0000" type="text"></td>
  </tr>
  <tr>
    <td><input name="" value="4" id="id_4" checked="checked" type="checkbox"></td>
    <td><input name="qty[]" value="2.0000" type="text"></td>
  </tr>
  <tr>
    <td><input name="" value="5" id="id_5" checked="checked" type="checkbox"></td>
    <td><input name="qty[]" value="3.0000" type="text"></td>
  </tr>
</table>


问:
Unwind Segue not working in iOS 8
I have an app, that works fine under iOS 7, but when built for iOS 8 the unwind segues are not working.

I created a new project and added a modal (navigationcontroller with tableviewcontroller)and tried to use an unwind modal. Unfortunately it doesn't work either. The methods that are being unwind to, are in the desination view controller. The unwind segue is created through the storyboard (a Navigationbar button in the tableviewcontroller) When I tap the button, nothing happens. There is no log output and the modal does not disappear. It also only seems to affect modal segues. push/popover are unwound normally.

Has anyone had a similar problem and has an Idea how I could solve it?

答:
Steps to be followed:

Link the unwind segue to the button in Storyboard.

Create IBAction for the button and add the below code in it:

```<code>[self dismissViewControllerAnimated:NO completion:nil];
</code>```

This should work for all versions.

Title: Unwind Segue not working in iOS 8

Body:
Steps to be followed:

Link the unwind segue to the button in Storyboard.

Create IBAction for the button and add the below code in it:

[self dismissViewControllerAnimated:NO completion:nil];

This should work for all versions.