问:
ASP.NET VB change db connection on web forms framework
I have created an instance of ASP.NET Web Forms in my Microsoft Visual Studio. By default the program generates user login page and registration which are linked to the .mdb file.

I want to reconfigure the standard connection and link it to my instance of MSSQL 2012 SQLExpress server.

How can I do it?

答:
Ok so I will give some direction and link you to a page.
First let me ask you this the connection you are using presently is it in a web.config file. If so this is where you will change the server/instance and database/catalog name.

Web.Config modification for SQL Server Instance

or this link

Web Config modification for SQL Express 2

So if you in the web.config file you should see something similar to this.

```<code><ConnectionStrings>
<add name="" connectionString="Server=(localhost)\SqlExpress;Max Pool    Size=300;Initial Catalog=database;User ID=username;Password=password;" providerName="System.Data.SqlClient"/>
 </Connectionstrings>
</code>```

or

```<code><connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=  (LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\database.mdf;Initial    Catalog=database;Integrated Security=True" providerName="System.Data.SqlClient" />
</code>```

you need to change the follow:
Server or Data Source
and
Initial Catalog or AttachDbFilename

Now your credentials you may use any username and password that has access to the sql server express instance.

I hope this helps.

Body:
Ok so I will give some direction and link you to a page.
First let me ask you this the connection you are using presently is it in a web.config file. If so this is where you will change the server/instance and database/catalog name.

Web.Config modification for SQL Server Instance

or this link

Web Config modification for SQL Express 2

So if you in the web.config file you should see something similar to this.

<ConnectionStrings>
<add name="" connectionString="Server=(localhost)\SqlExpress;Max Pool    Size=300;Initial Catalog=database;User ID=username;Password=password;" providerName="System.Data.SqlClient"/>
 </Connectionstrings>

or

<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=  (LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\database.mdf;Initial    Catalog=database;Integrated Security=True" providerName="System.Data.SqlClient" />

you need to change the follow:
Server or Data Source
and
Initial Catalog or AttachDbFilename

Now your credentials you may use any username and password that has access to the sql server express instance.

I hope this helps.


来源: stackexchange

问:
TypeError: Cannot read property 'then' of undefined at m.$scope.profile
I am trying to call a child service function in Main Controller.

But I am getting error on than in profile function.
This is my profile function inside main controller.

```<code>App.controller("globalCtrl", function($scope,$rootScope, $window, $location, $rootScope, $cookieStore, toastr, ClientService,) {
  var theClient = $cookieStore.get('UserData') || {};

  $scope.profile = function(theClient) {

              var getCurrentClient = theClient;
              var getOrganizationId = $rootScope.globalSession.OrganizationId;
            if($rootScope.globalSession.UserRole == "Admin")
             {
               if (getOrganizationId) {

               ClientService.getClient(getOrganizationId).then(function(aGetClientResponse) {

                if(getClientResponse[0] == $scope.RESPONSE_CODE.CM_SUCCESS) {

                        $scope.myprofile = getClientResponse[1];
                        $location.path("/profile");
                }
                else {
                    toastr.warning($scope.USER_MESSAGE.SERVICE_NOT_AVAILABLE, '');
                 }
              });
            }
          }
      };
)};
</code>```

This is Service of another controller whom function "getClient" I am calling in profile function.

```<code>App.factory('ClientService', function($http, $cookieStore, uuid2, API_URL, REQUEST_HEADER, RESPONSE_CODE) {
    var theClient = $cookieStore.get('UserData') || {};

    return {

        getClient: function() {

            if(theClient.OrganizationId) {
                //API Call
                var promise = $http.get(API_URL.GET_CLIENT+theClient.OrganizationId+"&CorrelationId="+uuid2.newuuid()+"&ContextOrganizationId=009", REQUEST_HEADER).then(
                function(aGetClientResponse) { //Success Callback

                    return [aGetClientResponse.data.GetClientResponse.Result.ResponseCode, aGetClientResponse.data.GetClientResponse];
                },
                function(aGetClientResponse) { //Error Callback
                    return [aGetClientResponse.status,''];
                });
            }
            return promise;
        },
        setClient: function(aClient) {
            theClient = aClient;
            $cookieStore.put('UserData', theClient);
        }
    }
});
</code>```

Need Help. cant figure out the Problem. Thanks in advance!

答:
I'm not sure it this works, but instead of returning a object with the functions inside, have you tried to declare them as part of the factory object? I have some declared like this and they are working, so have a try:

```<code>App.factory('ClientService', function($http, $cookieStore, uuid2, API_URL, REQUEST_HEADER, RESPONSE_CODE) {
    var theClient = $cookieStore.get('UserData') || {};

    var function = {
        getClient: function() {

            if(theClient.OrganizationId) {
                //API Call
                var promise = $http.get(API_URL.GET_CLIENT+theClient.OrganizationId+"&CorrelationId="+uuid2.newuuid()+"&ContextOrganizationId=009", REQUEST_HEADER).then(
                function(aGetClientResponse) { //Success Callback

                    return [aGetClientResponse.data.GetClientResponse.Result.ResponseCode, aGetClientResponse.data.GetClientResponse];
                },
                function(aGetClientResponse) { //Error Callback
                    return [aGetClientResponse.status,''];
                });
            }
            return promise;
        },
        setClient: function(aClient) {
            theClient = aClient;
            $cookieStore.put('UserData', theClient);
        }
    }
    return function;
});
</code>```

You can have a try with this too:

Define the services in the controller declaration (and remove one rootScope, its duplicated):

```<code>App.controller("globalCtrl", ['$scope','$rootScope','$window','$location','$cookieStore','toastr','ClientService', function($scope,$rootScope, $window, $location, $cookieStore, toastr, ClientService){
   [...]
}]);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to call a child service function in Main Controller.

But I am getting error on than in profile function.
This is my profile function inside main controller.

App.controller("globalCtrl", function($scope,$rootScope, $window, $location, $rootScope, $cookieStore, toastr, ClientService,) {
  var theClient = $cookieStore.get('UserData') || {};

  $scope.profile = function(theClient) {

              var getCurrentClient = theClient;
              var getOrganizationId = $rootScope.globalSession.OrganizationId;
            if($rootScope.globalSession.UserRole == "Admin")
             {
               if (getOrganizationId) {

               ClientService.getClient(getOrganizationId).then(function(aGetClientResponse) {

                if(getClientResponse[0] == $scope.RESPONSE_CODE.CM_SUCCESS) {

                        $scope.myprofile = getClientResponse[1];
                        $location.path("/profile");
                }
                else {
                    toastr.warning($scope.USER_MESSAGE.SERVICE_NOT_AVAILABLE, '');
                 }
              });
            }
          }
      };
)};

This is Service of another controller whom function "getClient" I am calling in profile function.

App.factory('ClientService', function($http, $cookieStore, uuid2, API_URL, REQUEST_HEADER, RESPONSE_CODE) {
    var theClient = $cookieStore.get('UserData') || {};

    return {

        getClient: function() {

            if(theClient.OrganizationId) {
                //API Call
                var promise = $http.get(API_URL.GET_CLIENT+theClient.OrganizationId+"&CorrelationId="+uuid2.newuuid()+"&ContextOrganizationId=009", REQUEST_HEADER).then(
                function(aGetClientResponse) { //Success Callback

                    return [aGetClientResponse.data.GetClientResponse.Result.ResponseCode, aGetClientResponse.data.GetClientResponse];
                },
                function(aGetClientResponse) { //Error Callback
                    return [aGetClientResponse.status,''];
                });
            }
            return promise;
        },
        setClient: function(aClient) {
            theClient = aClient;
            $cookieStore.put('UserData', theClient);
        }
    }
});

Need Help. cant figure out the Problem. Thanks in advance!

Body:
I'm not sure it this works, but instead of returning a object with the functions inside, have you tried to declare them as part of the factory object? I have some declared like this and they are working, so have a try:

App.factory('ClientService', function($http, $cookieStore, uuid2, API_URL, REQUEST_HEADER, RESPONSE_CODE) {
    var theClient = $cookieStore.get('UserData') || {};

    var function = {
        getClient: function() {

            if(theClient.OrganizationId) {
                //API Call
                var promise = $http.get(API_URL.GET_CLIENT+theClient.OrganizationId+"&CorrelationId="+uuid2.newuuid()+"&ContextOrganizationId=009", REQUEST_HEADER).then(
                function(aGetClientResponse) { //Success Callback

                    return [aGetClientResponse.data.GetClientResponse.Result.ResponseCode, aGetClientResponse.data.GetClientResponse];
                },
                function(aGetClientResponse) { //Error Callback
                    return [aGetClientResponse.status,''];
                });
            }
            return promise;
        },
        setClient: function(aClient) {
            theClient = aClient;
            $cookieStore.put('UserData', theClient);
        }
    }
    return function;
});

You can have a try with this too:

Define the services in the controller declaration (and remove one rootScope, its duplicated):

App.controller("globalCtrl", ['$scope','$rootScope','$window','$location','$cookieStore','toastr','ClientService', function($scope,$rootScope, $window, $location, $cookieStore, toastr, ClientService){
   [...]
}]);


问:
Bootstrap 3 - Vertically Algn Row Content
I have a row in Bootstrap. Within this row, I have three columns. The first column has an input field. The second column has some text. The third column has another input field. You can see this layout in this Bootply, which includes this code:

```<code><div class="container">
  <div class="row">
    <div class="col-xs-6">
<div class="row">
  <div class="col-xs-5">
    <div class="form-group">
      <label for="Minimum">Minimum</label>
      <div class="input-group">
        <input class="form-control" data-val="true" id="Minimum" name="Minimum" type="text" value="0">
      </div>
    </div>
  </div>

  <div class="col-xs-2 text-center"><p>Up To</p></div>

  <div class="col-xs-5">
    <div class="form-group">
      <label for="Maximum">Maximum</label>
      <div class="input-group">
        <input class="form-control" data-val="true" id="Maximum" name="Maximum" type="text" value="100">
      </div>
    </div>
  </div>
</div>
    </div>
  </div>
</div>
</code>```

I'm am trying to figure out how to vertically align the "Up To" text in the middle column. I want to vertically align the text against the bottom of the row. How can I do that?

答:
You can add a class on your row and set display: table;

Then you add another class on your 3 divs and set display: table-cell;and float: inherit; and a last class on your element you want to align vertically and set vertical-align: middle;

Updated Bootply

Body:
I have a row in Bootstrap. Within this row, I have three columns. The first column has an input field. The second column has some text. The third column has another input field. You can see this layout in this Bootply, which includes this code:

      Minimum

        <input class="form-control" data-val="true" id="Minimum" name="Minimum" type="text" value="0">

Up To

      Maximum

        <input class="form-control" data-val="true" id="Maximum" name="Maximum" type="text" value="100">

I'm am trying to figure out how to vertically align the "Up To" text in the middle column. I want to vertically align the text against the bottom of the row. How can I do that?


问:
Enforce type safety in C++ without using extra classes
I am somewhat familiar with type safety, and have used it successfully before in methods which receive several parameters of the same type (bool) to avoid confusion. For example:

```<code>// Old version of the method
void sendPackage(bool sendImmediately, bool dividePacket);

// Type safe version
enum SendImmediatelyPreference
{
    SEND_IMMEDIATELY,
    DO_NOT_SEND_IMMEDIATELY
};

enum PacketDivisionPreference
{
    DIVIDE_PACKET,
    DO_NOT_DIVIDE_PACKET
};

void sendPackage(
    SendImmediateltPreference immediatePref,
    PacketDivisionPreference divisionPref);
</code>```

So the cryptic sendPackage(true, false) becomes sendPackage(SEND_IMMEDIATELY, DO_NOT_DIVIDE_PACKET).

The problem is that this is only an option for bool. I have a method that accepts several std::vector<std::string> and I'd like to minimise the posibility of the user inputting the arguments in the wrong order.

I can think of creating different classes which contains an std::vector<std::string> and either override tons of the std::vector methods or expose the internal vector.

Is there an easier way, some sort of typedef which enforces type safety? Using boost would be okay.

答:
How about an alternative approach using named parameters? There are several ways of going about this in C++ described here. The tag approach using a tuple looks reasonable.  There is also boost parameter.

This doesn't offer strong type safety, but you could argue that the user is just as likely to call the wrong constructor to make their type safe object as they are to use the wrong tag when calling your function.  This situation is less likely to occur if the types are used throughout your application vs defined only for one particular function.

See also the discussion of boost strong typedef vs parameter for a similar purpose here.

Body:
I am somewhat familiar with type safety, and have used it successfully before in methods which receive several parameters of the same type (bool) to avoid confusion. For example:

// Old version of the method
void sendPackage(bool sendImmediately, bool dividePacket);

// Type safe version
enum SendImmediatelyPreference
{
    SEND_IMMEDIATELY,
    DO_NOT_SEND_IMMEDIATELY
};

enum PacketDivisionPreference
{
    DIVIDE_PACKET,
    DO_NOT_DIVIDE_PACKET
};

void sendPackage(
    SendImmediateltPreference immediatePref,
    PacketDivisionPreference divisionPref);

So the cryptic sendPackage(true, false) becomes sendPackage(SEND_IMMEDIATELY, DO_NOT_DIVIDE_PACKET).

The problem is that this is only an option for bool. I have a method that accepts several std::vector<std::string> and I'd like to minimise the posibility of the user inputting the arguments in the wrong order.

I can think of creating different classes which contains an std::vector<std::string> and either override tons of the std::vector methods or expose the internal vector.

Is there an easier way, some sort of typedef which enforces type safety? Using boost would be okay.


问:
Console two line output
I have this code which output some value from array, plus - in new line under value a[i]

```<code>Console.Write(a[i] + "\n-");
</code>```

So it looks like this

```<code>a
-
</code>```

Now i have more of Console.Write(a[i+1] + "\n-"); codes and it outputs like this

```<code>a
-b
-c
-d
-
</code>```

I know why this is the case but how can I return one line up after every new line \n? So I can get this

```<code>abcd
----
</code>```

答:
What you are looking for is Console.SetCursorPosition

```<code>var baseLine = Console.CursorTop;
char[] a = {'a', 'b', 'c', 'd'};
char[] b = {'A', 'B', 'C', 'D'};
string[] conditions = {"a", "a", "both", "b"}; // Which arrays to show
for (int i = 0; i < a.Length; i++)
{
    Console.SetCursorPosition(i, baseLine);
    Console.Write(conditions[i] != "b" ? a[i] : '-');
    Console.SetCursorPosition(i, baseLine + 1);
    Console.Write(conditions[i] != "a" ? b[i] : '-');
}
</code>```

baseLine is needed because you don't know in which line you are going to start.

Output:

```<code>abc-
--CD
</code>```

Title: Console two line output

Body:
I have this code which output some value from array, plus - in new line under value a[i]

Console.Write(a[i] + "\n-");

So it looks like this

a
-

Now i have more of Console.Write(a[i+1] + "\n-"); codes and it outputs like this

a
-b
-c
-d
-

I know why this is the case but how can I return one line up after every new line \n? So I can get this

abcd
----

Body:
What you are looking for is Console.SetCursorPosition

var baseLine = Console.CursorTop;
char[] a = {'a', 'b', 'c', 'd'};
char[] b = {'A', 'B', 'C', 'D'};
string[] conditions = {"a", "a", "both", "b"}; // Which arrays to show
for (int i = 0; i < a.Length; i++)
{
    Console.SetCursorPosition(i, baseLine);
    Console.Write(conditions[i] != "b" ? a[i] : '-');
    Console.SetCursorPosition(i, baseLine + 1);
    Console.Write(conditions[i] != "a" ? b[i] : '-');
}

baseLine is needed because you don't know in which line you are going to start.

Output:

abc-
--CD


问:
Node.js: how to limit the HTTP request size and upload file size?
I'm using Node.js and express.

I would like to limit the HTTP request size. Let's say, if someone sends me a HTTP request more than 2 MB then I stop the request right away. I looked at the code and I think if I change the core, I can do it. However, is there a way to set a max_request_size or soemthing like that?

It is kind of related to my second question. I'm using express to get an uploaded file from req.files. Is there a way to stop writing the file to the /tmp folder (which is the default upload behavior) as soon as the file size exceeds a certain file size?

答:
Source code of node github :

```<code>/* Maximium header size allowed. If the macro is not defined
 * before including this header then the default is used. To
 * change the maximum header size, define the macro in the build
 * environment (e.g. -DHTTP_MAX_HEADER_SIZE=<value>). To remove
 * the effective limit on the size of the header, define the macro
 * to a very large number (e.g. -DHTTP_MAX_HEADER_SIZE=0x7fffffff)
 */
#ifndef HTTP_MAX_HEADER_SIZE
# define HTTP_MAX_HEADER_SIZE (80*1024)
#endif
</code>```

So, you need to rebuild node from source to surpass the limit of 80*1024

You can use this with Express 4 to limit request body size/Upload file size, instead of express.json() and express.urlencoded(), you must require the body-parser module and use its json() and urlencoded() methods, if the extended option is not explicitly defined for bodyParser.urlencoded(), it will throw a warning (body-parser deprecated undefined extended: provide extended option).

```<code>var bodyParser = require('body-parser');
app.use(bodyParser.json({limit: '50mb'}));
app.use(bodyParser.urlencoded({limit: '50mb', extended: true}));
</code>```

Body:
Source code of node github :

/* Maximium header size allowed. If the macro is not defined
 * before including this header then the default is used. To
 * change the maximum header size, define the macro in the build
 * environment (e.g. -DHTTP_MAX_HEADER_SIZE=<value>). To remove
 * the effective limit on the size of the header, define the macro
 * to a very large number (e.g. -DHTTP_MAX_HEADER_SIZE=0x7fffffff)
 */
#ifndef HTTP_MAX_HEADER_SIZE
# define HTTP_MAX_HEADER_SIZE (80*1024)
#endif

So, you need to rebuild node from source to surpass the limit of 80*1024

You can use this with Express 4 to limit request body size/Upload file size, instead of express.json() and express.urlencoded(), you must require the body-parser module and use its json() and urlencoded() methods, if the extended option is not explicitly defined for bodyParser.urlencoded(), it will throw a warning (body-parser deprecated undefined extended: provide extended option).

var bodyParser = require('body-parser');
app.use(bodyParser.json({limit: '50mb'}));
app.use(bodyParser.urlencoded({limit: '50mb', extended: true}));


问:
Integration of WCF Webservice in classic asp
I have to call a soap web Service to send data from from my classic asp page to the database for which the web service is written at another end and i have to consume it so for it i had written the code but its giving error of HTML so i am putting my code and error in this query

```<code><%
     cboYear = FixString(Request.Form("cboYear"))

    'For j=1 to 12
        execute("EndDay = Request.Form(""Days" & 1 & """)")
        execute("EndMonth = Request.Form(""Months" & 1 & """)")
        execute("EndYear = Request.Form(""Years" & 1 & """)")
        execute("EndTime = Request.Form(""Times" & 0 & """)")

        SendDate = trim(EndDay) & "/" & EndMonth & "/" &  EndYear
    'Response.Write "<br>START<hr>"

    Set oXmlHTTP = CreateObject("Microsoft.XMLHTTP")
    oXmlHTTP.Open "POST", "https://bmwservicesuating.bmwcrinhm.in:7446/DMSI/PragmasysService.svc?wsdl",true

    oXmlHTTP.setRequestHeader "Content-Type", "text/xml; charset=utf-8"

      oXmlHTTP.setRequestHeader "SOAPAction", "http://tempuri.org/Pragmasyshh/UpdateCancellationDate"

    SOAPRequest = _
      "<?xml version=""1.0"" encoding=""utf-8""?>" &_

      "<soapenv:Envelope xmlns:soapenv=""http://schemas.xmlsoap.org/soap/envelope/"" xmlns:tem=""http://tempuri.org/"">" &_

    "<soapenv:Header/>" &_

    "<soapenv:Body>" &_

       "<tem:UpdateCancellationDate>" &_

          "<tem:IP>" &_

             "<Year>" & valueyear &"</Year>" &_

           "  <Month>" & value & "</Month>" &_

         "                                           <CancellationDate>" & my value & "</CancellationDate>" &_

       "   </tem:IP>" &_

     "  </tem:UpdateCancellationDate>" &_

   " </soapenv:Body>" &_

 "</soapenv:Envelope> "&_
    "</xml>"

    oXmlHTTP.send SOAPRequest
    Response.Write oXmlHTTP.responseText

    'Response.Write "<br>END<hr>"

        'Next
%>
</code>```

Please guide me whats wrong in it why i am getting error of
XML Parsing Error: not well-formed
Location: URL of application
Line Number 248, Column 26:
-------------------------^

答:
You have assumed that the declaration

<?xml version="1.0" encoding="utf-8"?>
```

<p>needs an accompanying end tag which is not the case in fact placing</p>

<pre class="lang-xml prettyprint-override"><code></xml>
</code>```

at the end will cause a Parsing Error because it won't be able to find the starting tag

<xml>
```

Remove it to fix the Parse Error.

Body:
I have to call a soap web Service to send data from from my classic asp page to the database for which the web service is written at another end and i have to consume it so for it i had written the code but its giving error of HTML so i am putting my code and error in this query

<%
     cboYear = FixString(Request.Form("cboYear"))

    'For j=1 to 12
        execute("EndDay = Request.Form(""Days" & 1 & """)")
        execute("EndMonth = Request.Form(""Months" & 1 & """)")
        execute("EndYear = Request.Form(""Years" & 1 & """)")
        execute("EndTime = Request.Form(""Times" & 0 & """)")

        SendDate = trim(EndDay) & "/" & EndMonth & "/" &  EndYear
    'Response.Write "
START
"

    Set oXmlHTTP = CreateObject("Microsoft.XMLHTTP")
    oXmlHTTP.Open "POST", "https://bmwservicesuating.bmwcrinhm.in:7446/DMSI/PragmasysService.svc?wsdl",true

    oXmlHTTP.setRequestHeader "Content-Type", "text/xml; charset=utf-8"

      oXmlHTTP.setRequestHeader "SOAPAction", "http://tempuri.org/Pragmasyshh/UpdateCancellationDate"

    SOAPRequest = _
      "<?xml version=""1.0"" encoding=""utf-8""?>" &_

      "<soapenv:Envelope xmlns:soapenv=""http://schemas.xmlsoap.org/soap/envelope/"" xmlns:tem=""http://tempuri.org/"">" &_

    "<soapenv:Header/>" &_

    "<soapenv:Body>" &_

       "<tem:UpdateCancellationDate>" &_

          "<tem:IP>" &_

             "<Year>" & valueyear &"</Year>" &_

           "  <Month>" & value & "</Month>" &_

         "                                           <CancellationDate>" & my value & "</CancellationDate>" &_

       "   </tem:IP>" &_

     "  </tem:UpdateCancellationDate>" &_

   " </soapenv:Body>" &_

 "</soapenv:Envelope> "&_
    "</xml>"

    oXmlHTTP.send SOAPRequest
    Response.Write oXmlHTTP.responseText

    'Response.Write "
END
"

        'Next
%>

Please guide me whats wrong in it why i am getting error of
XML Parsing Error: not well-formed
Location: URL of application
Line Number 248, Column 26:
-------------------------^

Body:
You have assumed that the declaration

<?xml version="1.0" encoding="utf-8"?>

needs an accompanying end tag which is not the case in fact placing

</xml>

at the end will cause a Parsing Error because it won't be able to find the starting tag

<xml>

Remove it to fix the Parse Error.


问:
Schema.org WebPage markup on 'body' element with 'id' attribute
I would like to insert WebPage markup in my code. So it's written that this - itemscope="" itemtype="http://schema.org/WebPage" - should be put into body tag. But in body tag I have id="top-page".

When I copy the Microdata line to the body and test it with Google’s tool, it shows me http://xxxx.yy/top-page as @id.

How to avoid it?

答:
This is most likely a bug in Google’s tool. You don’t have to worry about it. But if you do, there are two workarounds:

Specify itemid on body in addition. This is the correct attribute responsible for providing an ID in Microdata, not id. You should provide the canonical URL of the web page as value.

Specify itemscope itemtype="http://schema.org/WebPage" on a different element (one that doesn’t have an id attribute). While it’s often useful to specify WebPage on the body, this is not required.

The first solution is preferable, as it’s generally a good practice to provide IDs for your structured data items.


问:
JUnit Testing for attribute values within in Stream
This question is related to my previous question at JUnit assertions within in Java 8 stream.

If I have 3 objects, how do I verify the values of the objects' attributes within a stream? My previous question answered how to test for the presence of them, but I now need to test for each individual attribute's value. Can someone give me a code snippet?

答:
You can filter the properties by the expected values and count the resulting entries. This number must be equal to the original size.

```<code>List<Integer> expected = Arrays.asList(1, 2, 3);
long count = objects.stream()
    .map(MyObject::getId)
    .filter(id -> expected.contains(id.intValue()))
    .count();
Assert.assertEquals(objects.size(), (int) count);
</code>```

If you want to check all properties in one stream, do it like this:

```<code>long count = objects.stream()
    .filter(o-> expectedIds.contains(o.getId().intValue()))
    .filter(o-> expectedNames.contains(o.getName()))
    // and so on
    .count();
</code>```

Body:
You can filter the properties by the expected values and count the resulting entries. This number must be equal to the original size.

List<Integer> expected = Arrays.asList(1, 2, 3);
long count = objects.stream()
    .map(MyObject::getId)
    .filter(id -> expected.contains(id.intValue()))
    .count();
Assert.assertEquals(objects.size(), (int) count);

If you want to check all properties in one stream, do it like this:

long count = objects.stream()
    .filter(o-> expectedIds.contains(o.getId().intValue()))
    .filter(o-> expectedNames.contains(o.getName()))
    // and so on
    .count();


问:
How to get all month record count in laravel
I have applied group by with with created_at column using DB query but like to do it by laravel eloquent

Output should be like this:-

```<code>Array
(
  [1] => 2
  [2] => 3
  [3] => 7
  [4] => 4
  [5] => 5
  [6] => 7
  [7] => 2
  [8] => 9
  [9] => 0
  [10] => 4
  [11] => 0
  [12] => 0
)
</code>```

Please provide any help me to do this.

答:
If your created_at column is DATETIME, you can group it like this

```<code>Entity::orderBy(...)->groupBy(DB::raw('MONTH(created_at)'))
</code>```

You can also select the month in advance

```<code>Entity::select(DB::raw('MONTH(created_at) as month')->groupBy('month')->get()->keyBy('month');
</code>```

Body:
I have applied group by with with created_at column using DB query but like to do it by laravel eloquent

Output should be like this:-

Array
(
  [1] => 2
  [2] => 3
  [3] => 7
  [4] => 4
  [5] => 5
  [6] => 7
  [7] => 2
  [8] => 9
  [9] => 0
  [10] => 4
  [11] => 0
  [12] => 0
)

Please provide any help me to do this.

Body:
If your created_at column is DATETIME, you can group it like this

Entity::orderBy(...)->groupBy(DB::raw('MONTH(created_at)'))

You can also select the month in advance

Entity::select(DB::raw('MONTH(created_at) as month')->groupBy('month')->get()->keyBy('month');


问:
Try catch not working in Laravel 5.4
Started working in Laravel 5.4 recently. I tried to catch an error and return an json response from controller in following code but it seems throwing error usual

```<code>try {
    $credentials = $request->only('Username', 'Password');
    $driverdata = Driver::where('username', $credentials['Username'])
            ->where('password', Hasher::hash($credentials['Password']))
            ->where('deleted', 0)
            ->where('blocked', 0)
            ->where('status', 1)
            ->first();
    // if(!count($driverdata)){
    //  return response()->json("Login Failed",401);
    // }
    return response()->json($driverdata->toArray());
} catch (Exception $e) {
    return response()->json($e->getMessage(), 500);
}
</code>```

I also tried

```<code>use Exception;
</code>```

on top
also using as

```<code>catch (\Exception $e) {
    return response()->json($e->getMessage(), 500);
}
</code>```

Following is the error i get

FatalErrorException in LoginController.php line 26:
      Call to a member function toArray() on null

Any suggestions? But the same thing used to work in Laravel 5.2

答:
To fix your problem Call to a member function toArray() on null change:

```<code> // if(!count($driverdata)){
 //  return response()->json("Login Failed",401);
 // }
</code>```

to

```<code> if(!count($driverdata)){
    //return response()->json("Login Failed",401);
    throw new Exception('Login Failed');
 }
</code>```

This fixes also the current FatalErrorException

For the rest google: laravel 5.4 fatalerrorexception php 5.6

Title: Try catch not working in Laravel 5.4

Body:
Started working in Laravel 5.4 recently. I tried to catch an error and return an json response from controller in following code but it seems throwing error usual

try {
    $credentials = $request->only('Username', 'Password');
    $driverdata = Driver::where('username', $credentials['Username'])
            ->where('password', Hasher::hash($credentials['Password']))
            ->where('deleted', 0)
            ->where('blocked', 0)
            ->where('status', 1)
            ->first();
    // if(!count($driverdata)){
    //  return response()->json("Login Failed",401);
    // }
    return response()->json($driverdata->toArray());
} catch (Exception $e) {
    return response()->json($e->getMessage(), 500);
}

I also tried

use Exception;

on top
also using as

catch (\Exception $e) {
    return response()->json($e->getMessage(), 500);
}

Following is the error i get

FatalErrorException in LoginController.php line 26:
      Call to a member function toArray() on null

Any suggestions? But the same thing used to work in Laravel 5.2

Body:
To fix your problem Call to a member function toArray() on null change:

 // if(!count($driverdata)){
 //  return response()->json("Login Failed",401);
 // }

to

 if(!count($driverdata)){
    //return response()->json("Login Failed",401);
    throw new Exception('Login Failed');
 }

This fixes also the current FatalErrorException

For the rest google: laravel 5.4 fatalerrorexception php 5.6


问:
Programmatically Inserting Profiling Marks
I'm using the Profiler of Visual Studio 2008 Development Edition.  To perform "targeted profiling," I can manually set profiler filters through "marks" anytime I am attached to my currently-running test code.  But I would like to insert the marks programmatically instead.  I would like to add a call, instruction, or directive to my test code that, when executed, tells the profiler "this is a 'mark' called 'BeginWork'" and "this is a 'mark' called 'EndWork'".

Is there a way to do that?  If not, does Visual Studio 2010 have that ability?

答:
You can use the Profiler API to insert marks programmatically. See the DataCollection.CommentMarkProfile method documentation on MSDN.

You just need to add a reference to Microsoft.VisualStudio.Profiler.dll from 'Program Files[ x86]\Microsoft Visual Studio 9.0\Team Tools\Performance Tools' to use the managed API.

Your test code could look something like:

```<code>MarkOperationResult result;
result = DataCollection.CommentMarkProfile(markID1, "BeginWork");
// Validate result...

SomeOperation();

result = DataCollection.CommentMarkProfile(markID2, "EndWork");
// Validate result...
</code>```

ContentLicense: CC BY-SA 2.5

Body:
You can use the Profiler API to insert marks programmatically. See the DataCollection.CommentMarkProfile method documentation on MSDN.

You just need to add a reference to Microsoft.VisualStudio.Profiler.dll from 'Program Files[ x86]\Microsoft Visual Studio 9.0\Team Tools\Performance Tools' to use the managed API.

Your test code could look something like:

MarkOperationResult result;
result = DataCollection.CommentMarkProfile(markID1, "BeginWork");
// Validate result...

SomeOperation();

result = DataCollection.CommentMarkProfile(markID2, "EndWork");
// Validate result...


问:
In Symfony 3.2.6 with BeSimpleI18nRoutingBundle, can't generate i18n routes in production mode
My project is in Symfony 3.2.6 and I try to generate the i18n routes in production mode with BeSimpleI18nRoutingBundle.

In dev mode, it's ok.

But in production mode, routes generated are always in same locale (the current).

(I already clear the cache)

I use these links to switch :

```<code><a href="{{ path(app.request.attributes.get('_route'), {'locale': 'fr'}) }}">fr</a>
<a href="{{ path(app.request.attributes.get('_route'), {'locale': 'en'}) }}">en</a>
</code>```

Do you have any idea ?

Thank you in advance.

答:
I found the solution.

For work in the dev mode, I had to update the "_main" route in "routing_dev.yml" with "type: be_simple_i18n" like this :

```<code>_main:
    resource: routing.yml
    type: be_simple_i18n
</code>```

And the solution for the production mode is to add the same line in the "config.yml" where the "routing.yml" is imported like this :

```<code>framework:
    ...
    router:
        resource: "%kernel.root_dir%/config/routing.yml"
        type: be_simple_i18n
</code>```

Body:
My project is in Symfony 3.2.6 and I try to generate the i18n routes in production mode with BeSimpleI18nRoutingBundle.

In dev mode, it's ok.

But in production mode, routes generated are always in same locale (the current).

(I already clear the cache)

I use these links to switch :

fr
en

Do you have any idea ?

Thank you in advance.

Body:
I found the solution.

For work in the dev mode, I had to update the "_main" route in "routing_dev.yml" with "type: be_simple_i18n" like this :

_main:
    resource: routing.yml
    type: be_simple_i18n

And the solution for the production mode is to add the same line in the "config.yml" where the "routing.yml" is imported like this :

framework:
    ...
    router:
        resource: "%kernel.root_dir%/config/routing.yml"
        type: be_simple_i18n


问:
Create a class that support json serialization for use with Celery
I'm using Celery to run some background tasks. One of the tasks returns a python class I created. I want to use json to serialize and deserialize this class, given the warnings about using pickle.

Is there a simple built in way to achieve this?

The class is very simple, it contains 3 attributes all of which are lists of named tuples. It contains a couple of methods that performs some calculations on the attributes.

My idea is to serialize/deserialize the 3 attributes, since that defines the class.

This is my idea for the encoder, but I'm not sure how to decode the data again?

```<code>import json

class JSONSerializable(object):
    def __repr__(self):
        return json.dumps(self.__dict__)

class MySimpleClass(JSONSerializable):
    def __init__(self, p1, p2, p3): # I only care about p1, p2, p3
        self.p1 = p1
        self.p2 = p2
        self.p3 = p2
        self.abc = p1 + p2 + p2

    def some_calc(self):
        ...
</code>```

答:
First but not least important: the warnings against pickle are mainly if you could have 3rd partis injecting pickled data on your worker stream. If you are certain your own system is creating all pickled data to be consumed, there is no security problem at all. And as for compatibility, it is relatively easy to handle, and automatic if you are on the same Python version for produers and consumers of your Pickle files.

That said, for JSON, you have to create a subclass of Python's json.JSONEncoder and json.JSONDecoder - each of which will need to be passed as the cls argument to all your json.dump(s) and json.load(s) calls.

A suggestion is that the default method on the encoder encodes the class __module__, its __name__ and a identifier key, say __custom__ to ensure it should be custom decoded, as keys to a dictionary, and the object's data as  a "data" key.

And on the encoder, you check for the  __custom__ key, and them instantiate a class using the __new__ method, and populate its dict. Like for pickle, side-effects that are triggered on the class __init__ won't run.

You can later on enhance your decoder and encoder so that, for example, they search the class for a __json_encode__ method that could handle only the desired attributes.

Sample implementation:

```<code>import json

class GenericJSONEncoder(json.JSONEncoder):
    def default(self, obj):
        try:
            return super().default(obj)
        except TypeError:
            pass
        cls = type(obj)
        result = {
            '__custom__': True,
            '__module__': cls.__module__,
            '__name__': cls.__name__,
            'data': obj.__dict__ if not hasattr(cls, '__json_encode__') else obj.__json_encode__
        }
        return result

class GenericJSONDecoder(json.JSONDecoder):
    def decode(self, str):
        result = super().decode(str)
        if not isinstance(result, dict) or not result.get('__custom__', False):
            return result
        import sys
        module = result['__module__']
        if not module in sys.modules:
            __import__(module)
        cls = getattr(sys.modules[module], result['__name__'])
        if hasattr(cls, '__json_decode__'):
            return cls.__json_decode__(result['data'])
        instance = cls.__new__(cls)
        instance.__dict__.update(result['data'])
        return instance
</code>```

Interactive test on the console:

```<code>In [36]: class A:
    ...:     def __init__(self, a):
    ...:         self.a = a
    ...:

In [37]: a = A('test')

In [38]: b = json.loads(json.dumps(a, cls=GenericJSONEncoder),  cls=GenericJSONDecoder)

In [39]: b.a
Out[39]: 'test'
</code>```

Body:
I'm using Celery to run some background tasks. One of the tasks returns a python class I created. I want to use json to serialize and deserialize this class, given the warnings about using pickle.

Is there a simple built in way to achieve this?

The class is very simple, it contains 3 attributes all of which are lists of named tuples. It contains a couple of methods that performs some calculations on the attributes.

My idea is to serialize/deserialize the 3 attributes, since that defines the class.

This is my idea for the encoder, but I'm not sure how to decode the data again?

import json

class JSONSerializable(object):
    def __repr__(self):
        return json.dumps(self.__dict__)

class MySimpleClass(JSONSerializable):
    def __init__(self, p1, p2, p3): # I only care about p1, p2, p3
        self.p1 = p1
        self.p2 = p2
        self.p3 = p2
        self.abc = p1 + p2 + p2

    def some_calc(self):
        ...

Body:
First but not least important: the warnings against pickle are mainly if you could have 3rd partis injecting pickled data on your worker stream. If you are certain your own system is creating all pickled data to be consumed, there is no security problem at all. And as for compatibility, it is relatively easy to handle, and automatic if you are on the same Python version for produers and consumers of your Pickle files.

That said, for JSON, you have to create a subclass of Python's json.JSONEncoder and json.JSONDecoder - each of which will need to be passed as the cls argument to all your json.dump(s) and json.load(s) calls.

A suggestion is that the default method on the encoder encodes the class __module__, its __name__ and a identifier key, say __custom__ to ensure it should be custom decoded, as keys to a dictionary, and the object's data as  a "data" key.

And on the encoder, you check for the  __custom__ key, and them instantiate a class using the __new__ method, and populate its dict. Like for pickle, side-effects that are triggered on the class __init__ won't run.

You can later on enhance your decoder and encoder so that, for example, they search the class for a __json_encode__ method that could handle only the desired attributes.

Sample implementation:

import json

class GenericJSONEncoder(json.JSONEncoder):
    def default(self, obj):
        try:
            return super().default(obj)
        except TypeError:
            pass
        cls = type(obj)
        result = {
            '__custom__': True,
            '__module__': cls.__module__,
            '__name__': cls.__name__,
            'data': obj.__dict__ if not hasattr(cls, '__json_encode__') else obj.__json_encode__
        }
        return result

class GenericJSONDecoder(json.JSONDecoder):
    def decode(self, str):
        result = super().decode(str)
        if not isinstance(result, dict) or not result.get('__custom__', False):
            return result
        import sys
        module = result['__module__']
        if not module in sys.modules:
            __import__(module)
        cls = getattr(sys.modules[module], result['__name__'])
        if hasattr(cls, '__json_decode__'):
            return cls.__json_decode__(result['data'])
        instance = cls.__new__(cls)
        instance.__dict__.update(result['data'])
        return instance

Interactive test on the console:

In [36]: class A:
    ...:     def __init__(self, a):
    ...:         self.a = a
    ...:

In [37]: a = A('test')

In [38]: b = json.loads(json.dumps(a, cls=GenericJSONEncoder),  cls=GenericJSONDecoder)

In [39]: b.a
Out[39]: 'test'


问:
2D iterator access in C++
I'm working on a 2D table with std::map() to count how many times one number transitions to another number.  I've run into two problems.  First, my first transition doesn't show (1->2).  Second, all my transitions are showing only one time (2->3 and 3->1 both happen twice).

I can see why the transitions are only happening once.  The iterator doesn't see currentVal and goes to else, where it adds the values then exits.  I'm not sure how to fix this though.  Any help is appreciated!

```<code>#include <iostream>
#include <map>
#include <algorithm>
#include <vector>

using namespace std;

//import midi notes
vector <int> midiFile = {1, 2, 3, 1, 20, 5, 2, 3, 1};

//create a 2d hashmap for matrix
map <string, map <string, int> > mCounts;

//strings for the previous value and current value
string prevVal = "";
string currentVal = "";

void addNumbers(vector <int> midiFile) {

    for (int i = 0; i < midiFile.size(); i++) {
        currentVal = to_string(midiFile[i]);

        if(prevVal == "") {
            prevVal = currentVal;   //first value
        } else {
            //playCounts is temporary map to store counts of current val in relation to previous val
            map <string, int> playCounts;

            map <string, int> ::iterator iterator;
            iterator = playCounts.find(currentVal);

            //if mCounts doesn't contain the value yet, create a new hashmap
            if(iterator != playCounts.end()){

                int counter = iterator -> second;
                mCounts[prevVal] [currentVal] = counter + 1;

            } else {
                playCounts.insert(pair <string, int>(currentVal, 1));
                mCounts [prevVal] = playCounts;

            }

            prevVal = currentVal;

        }

        //find values already in map
        map <string, map <string, int> > ::iterator it;
        it = mCounts.find(prevVal);

        if (it != mCounts.end()) {
            //if value is found, do nothing
        } else {
            mCounts.insert(pair <string, map <string, int>>(prevVal, map <string, int>()));
        }
    }
}
</code>```

答:
Here is solution that doesn't use nested maps and doesn't convert notes to strings (but assumes that notes are nonnegative):

```<code>// This snippet uses c++11 syntax
#include <map>

// Code in this example assumes that valid notes are nonnegative
struct transition {
    int from;
    int to;
};

// Comparison operator required to make transition usable as a
// key in std::map
bool operator< (const transition& l, const transition& r) {
    return l.from < r.from || (l.from == r.from && l.to < r.to);
}

// Range of all transitions with respective counter
// starting from a particular note
std::pair<std::map<transition, int>::const_iterator,
    std::map<transition, int>::const_iterator>
transitions_from(int from_note,
        const std::map<transition, int>& transition_counters) {
    return std::make_pair(transition_counters.lower_bound(transition{from_note, -1}),
            transition_counters.upper_bound(transition{from_note + 1, -1}));
}

int counter_for(transition t, const std::map<transition, int>& transition_counters) {
    const auto it = transition_counters.find(t);
    if (it != transition_counters.end()) {
        return it->second;
    } else {
        return 0;
    }
}
</code>```

Usage example:

```<code>#include <iostream>
#include <vector>

int main() {
    std::vector<int> notes = {1, 2, 3, 1, 20, 5, 2, 3, 1};
    std::map<transition, int> transition_counters;
    int previous_note = -1;
    for (int note: notes) {
        if (previous_note != -1) {
            transition t{previous_note, note};
            transition_counters[t] += 1;
        }
        previous_note = note;
    }

    std::cout << "all encountered transitions:\n";
    for (const auto& entry: transition_counters) {
        std::cout << '(' << entry.first.from << " -> " << entry.first.to << "): " << entry.second << '\n';
    }

    std::cout << "transitions from 1:\n";
    const auto transitions_from_1 = transitions_from(1, transition_counters);
    for (auto it = transitions_from_1.first; it != transitions_from_1.second; ++it) {
        std::cout << '(' << it->first.from << " -> " << it->first.to << "): " << it->second << '\n';
    }

    std::cout << "counters for individual transitions:\n";
    std::cout << "(1 -> 2): " << counter_for(transition{1, 2}, transition_counters) << '\n';
    std::cout << "(2 -> 1): " << counter_for(transition{2, 1}, transition_counters) << '\n';
}
</code>```

Title: 2D iterator access in C++

Body:
I'm working on a 2D table with std::map() to count how many times one number transitions to another number.  I've run into two problems.  First, my first transition doesn't show (1->2).  Second, all my transitions are showing only one time (2->3 and 3->1 both happen twice).

I can see why the transitions are only happening once.  The iterator doesn't see currentVal and goes to else, where it adds the values then exits.  I'm not sure how to fix this though.  Any help is appreciated!

#include <iostream>
#include <map>
#include <algorithm>
#include <vector>

using namespace std;

//import midi notes
vector <int> midiFile = {1, 2, 3, 1, 20, 5, 2, 3, 1};

//create a 2d hashmap for matrix
map <string, map <string, int> > mCounts;

//strings for the previous value and current value
string prevVal = "";
string currentVal = "";

void addNumbers(vector <int> midiFile) {

    for (int i = 0; i < midiFile.size(); i++) {
        currentVal = to_string(midiFile[i]);

        if(prevVal == "") {
            prevVal = currentVal;   //first value
        } else {
            //playCounts is temporary map to store counts of current val in relation to previous val
            map <string, int> playCounts;

            map <string, int> ::iterator iterator;
            iterator = playCounts.find(currentVal);

            //if mCounts doesn't contain the value yet, create a new hashmap
            if(iterator != playCounts.end()){

                int counter = iterator -> second;
                mCounts[prevVal] [currentVal] = counter + 1;

            } else {
                playCounts.insert(pair <string, int>(currentVal, 1));
                mCounts [prevVal] = playCounts;

            }

            prevVal = currentVal;

        }

        //find values already in map
        map <string, map <string, int> > ::iterator it;
        it = mCounts.find(prevVal);

        if (it != mCounts.end()) {
            //if value is found, do nothing
        } else {
            mCounts.insert(pair <string, map <string, int>>(prevVal, map <string, int>()));
        }
    }
}

Body:
Here is solution that doesn't use nested maps and doesn't convert notes to strings (but assumes that notes are nonnegative):

// This snippet uses c++11 syntax
#include <map>

// Code in this example assumes that valid notes are nonnegative
struct transition {
    int from;
    int to;
};

// Comparison operator required to make transition usable as a
// key in std::map
bool operator< (const transition& l, const transition& r) {
    return l.from < r.from || (l.from == r.from && l.to < r.to);
}

// Range of all transitions with respective counter
// starting from a particular note
std::pair<std::map<transition, int>::const_iterator,
    std::map<transition, int>::const_iterator>
transitions_from(int from_note,
        const std::map<transition, int>& transition_counters) {
    return std::make_pair(transition_counters.lower_bound(transition{from_note, -1}),
            transition_counters.upper_bound(transition{from_note + 1, -1}));
}

int counter_for(transition t, const std::map<transition, int>& transition_counters) {
    const auto it = transition_counters.find(t);
    if (it != transition_counters.end()) {
        return it->second;
    } else {
        return 0;
    }
}

Usage example:

#include <iostream>
#include <vector>

int main() {
    std::vector<int> notes = {1, 2, 3, 1, 20, 5, 2, 3, 1};
    std::map<transition, int> transition_counters;
    int previous_note = -1;
    for (int note: notes) {
        if (previous_note != -1) {
            transition t{previous_note, note};
            transition_counters[t] += 1;
        }
        previous_note = note;
    }

    std::cout << "all encountered transitions:\n";
    for (const auto& entry: transition_counters) {
        std::cout << '(' << entry.first.from << " -> " << entry.first.to << "): " << entry.second << '\n';
    }

    std::cout << "transitions from 1:\n";
    const auto transitions_from_1 = transitions_from(1, transition_counters);
    for (auto it = transitions_from_1.first; it != transitions_from_1.second; ++it) {
        std::cout << '(' << it->first.from << " -> " << it->first.to << "): " << it->second << '\n';
    }

    std::cout << "counters for individual transitions:\n";
    std::cout << "(1 -> 2): " << counter_for(transition{1, 2}, transition_counters) << '\n';
    std::cout << "(2 -> 1): " << counter_for(transition{2, 1}, transition_counters) << '\n';
}


问:
First available date previous day/month/year from a datetime range
I have a datetime instance with dates (dfDates):

```<code>2017-03-01 00:00
2017-03-02 00:00
2017-03-04 00:00
...
</code>```

For the last day (here: 2017-03-04) I calculate the previous day/month/year/etc. as follows:

```<code>def previous_day(dtToday):
    return dtToday - pd.DateOffset(days=1)
</code>```

This returns 2017-03-03. However, this business day is not available in my range of dates (dfDates).

I am therefore looking for a robust way to find the date that is the closest to the previous day/month/year/etc.. In this case for the previous day it should return 2017-03-02.

Note, I understand that you can do something like index -1 to get the previous day. It becomes however complicated when taking the previous month (there are not always 30 days in a month) and even the previous year (there are not always 252 working days in a year). Is there therefore a robust method to get the closest available date?

Update

I understand also that you can use timedelta as follows:

```<code>from datetime import datetime, timedelta

d = datetime.today() - timedelta(days=days_to_subtract)
</code>```

However, how does that relate to dtToday and how can I link it with dfDates? dtToday in my case is not always datetime.today(). Sometimes its a random date.

答:
If I understand correctly, you don't want to actually subtract 1 day, you want to get the previous available day from the list of available dates. If that's the case, then consider this :

```<code>available_dates = [
  2017-03-01 00:00,
  2017-03-02 00:00,
  2017-03-04 00:00,
  ...
]

def previous_day(dtToday):
    today_index = available_dates.index(dtToday)
    return available_dates[today_index-1]
</code>```

This assumes, of course, that your available_dates is sorted

EDIT:

If you want to be able to subtract month and years, then something a little bit more complex is needed :

```<code># Sorted
available_dates = [
  2017-03-01 00:00,
  2017-03-02 00:00,
  2017-03-04 00:00,
  ...
]

subtract_from_date(date, day=None, month=None, year=None):
  # check if it's day/month/yeah
  ...
  # do the actual subtraction and store it in substracted_date
  ...
  # get the closest date
  for index, date in enumerate(available_dates):
     if date > substracted_date:
       return available_dates[index-1]
</code>```

Body:
I have a datetime instance with dates (dfDates):

2017-03-01 00:00
2017-03-02 00:00
2017-03-04 00:00
...

For the last day (here: 2017-03-04) I calculate the previous day/month/year/etc. as follows:

def previous_day(dtToday):
    return dtToday - pd.DateOffset(days=1)

This returns 2017-03-03. However, this business day is not available in my range of dates (dfDates).

I am therefore looking for a robust way to find the date that is the closest to the previous day/month/year/etc.. In this case for the previous day it should return 2017-03-02.

Note, I understand that you can do something like index -1 to get the previous day. It becomes however complicated when taking the previous month (there are not always 30 days in a month) and even the previous year (there are not always 252 working days in a year). Is there therefore a robust method to get the closest available date?

Update

I understand also that you can use timedelta as follows:

from datetime import datetime, timedelta

d = datetime.today() - timedelta(days=days_to_subtract)

However, how does that relate to dtToday and how can I link it with dfDates? dtToday in my case is not always datetime.today(). Sometimes its a random date.

Body:
If I understand correctly, you don't want to actually subtract 1 day, you want to get the previous available day from the list of available dates. If that's the case, then consider this :

available_dates = [
  2017-03-01 00:00,
  2017-03-02 00:00,
  2017-03-04 00:00,
  ...
]

def previous_day(dtToday):
    today_index = available_dates.index(dtToday)
    return available_dates[today_index-1]

This assumes, of course, that your available_dates is sorted

EDIT:

If you want to be able to subtract month and years, then something a little bit more complex is needed :

# Sorted
available_dates = [
  2017-03-01 00:00,
  2017-03-02 00:00,
  2017-03-04 00:00,
  ...
]

subtract_from_date(date, day=None, month=None, year=None):
  # check if it's day/month/yeah
  ...
  # do the actual subtraction and store it in substracted_date
  ...
  # get the closest date
  for index, date in enumerate(available_dates):
     if date > substracted_date:
       return available_dates[index-1]


问:
Corrupt jar file
I have created a jar file in windows 7 using eclipse. When I am trying to open the jar file it says invalid or corrupt jar file. Can anyone suggest me why the jar file is invalid?</p>

答: Try use the command jar -xvf fileName.jar and then do export the content of the decompressed file into a new Java project into Eclipse. </p>

Title: Corrupt jar file


答:
In getClient() the code looks like this:

```<code>        if(theClient.OrganizationId) {
            //API Call
            var promise = ... some stuff ...;
        }
        return promise;
</code>```

So if the condition is false you return undefined which doesn't have a .then property.

You should make sure that a function which returns a promise always returns a promise. If you want to signal that a missing id is an error then just return $q.reject(something) for an already rejected promise.

Title: TypeError: Cannot read property 'then' of undefined at m.$scope.profile

Body:
I am trying to call a child service function in Main Controller.

But I am getting error on than in profile function.
This is my profile function inside main controller.

App.controller("globalCtrl", function($scope,$rootScope, $window, $location, $rootScope, $cookieStore, toastr, ClientService,) {
  var theClient = $cookieStore.get('UserData') || {};

  $scope.profile = function(theClient) {

              var getCurrentClient = theClient;
              var getOrganizationId = $rootScope.globalSession.OrganizationId;
            if($rootScope.globalSession.UserRole == "Admin")
             {
               if (getOrganizationId) {

               ClientService.getClient(getOrganizationId).then(function(aGetClientResponse) {

                if(getClientResponse[0] == $scope.RESPONSE_CODE.CM_SUCCESS) {

                        $scope.myprofile = getClientResponse[1];
                        $location.path("/profile");
                }
                else {
                    toastr.warning($scope.USER_MESSAGE.SERVICE_NOT_AVAILABLE, '');
                 }
              });
            }
          }
      };
)};

This is Service of another controller whom function "getClient" I am calling in profile function.

App.factory('ClientService', function($http, $cookieStore, uuid2, API_URL, REQUEST_HEADER, RESPONSE_CODE) {
    var theClient = $cookieStore.get('UserData') || {};

    return {

        getClient: function() {

            if(theClient.OrganizationId) {
                //API Call
                var promise = $http.get(API_URL.GET_CLIENT+theClient.OrganizationId+"&CorrelationId="+uuid2.newuuid()+"&ContextOrganizationId=009", REQUEST_HEADER).then(
                function(aGetClientResponse) { //Success Callback

                    return [aGetClientResponse.data.GetClientResponse.Result.ResponseCode, aGetClientResponse.data.GetClientResponse];
                },
                function(aGetClientResponse) { //Error Callback
                    return [aGetClientResponse.status,''];
                });
            }
            return promise;
        },
        setClient: function(aClient) {
            theClient = aClient;
            $cookieStore.put('UserData', theClient);
        }
    }
});

Need Help. cant figure out the Problem. Thanks in advance!

Body:
In getClient() the code looks like this:

        if(theClient.OrganizationId) {
            //API Call
            var promise = ... some stuff ...;
        }
        return promise;

So if the condition is false you return undefined which doesn't have a .then property.

You should make sure that a function which returns a promise always returns a promise. If you want to signal that a missing id is an error then just return $q.reject(something) for an already rejected promise.


问:
How to initialize the logger for integration tests?
I have a crate with production code in the src directory and integration tests in the tests directory. The production code uses log macros.

I would like to init a global logger when running the integration tests (e.g. env_logger::init().unwrap();)
There are several tests and the test order is not defined, so I don't know in which test I should put the initialize command.

Is there any way I can do this nicely? Perhaps by overriding the tests main function?

答:
You can use something like this:

```<code>use std::sync::Once;

static INIT: Once = Once::new();

/// Setup function that is only run once, even if called multiple times.
fn setup() {
    INIT.call_once(|| {
        env_logger::init().unwrap();
    });
}
</code>```

Then simply call setup() in the beginning of each test.

Originally based on this blogpost.

Body:
You can use something like this:

use std::sync::Once;

static INIT: Once = Once::new();

/// Setup function that is only run once, even if called multiple times.
fn setup() {
    INIT.call_once(|| {
        env_logger::init().unwrap();
    });
}

Then simply call setup() in the beginning of each test.

Originally based on this blogpost.

ContentLicense: CC BY-SA 4.0


问:
SonarQube. Create custom rule for Java
anyone can help me with this case.

I have the next test file:

```<code>AWSCredentialsProvider provider = new EnvironmentVariableCredentialsProvider();
AmazonWebServiceClient client = new AmazonS3Client(provider); // Noncompliant
</code>```

Are there way to extract the particular implementation of interface from the variable provider when I explore the arguments of constructor AmazonS3Client? Now I can extract AWSCredentialsProvider for this variable only.

答:
As it's not that explicit, I'm guessing that you are trying to retrieve implementation type used to initialize th providervariable, which would be EnvironmentVariableCredientialsProvider.

There is currently no easy and straightforward way to achieve this. The best way would be to proceed as follow:

From the provider IdentifierTree, use the semantic API to get to the corresponding symbol.

From the provider symbol, jump to the declaration tree (which will be null if the identifier is declared in another file).

From the declaration, and if the tree is a VariableTree, look for the initializer expression.

From the ExpressionTree, get the type of the symbol Type, which will give you the implementation type.

That's a first step which should help you to get further. Of course you will next probably need to handle cases where the variable is declared without initializer, and then assigned somewhere else. To retrieve these expressions, look at the symbol usages, instead of declaration, and walk the trees.

Title: SonarQube. Create custom rule for Java

Body:
anyone can help me with this case.

I have the next test file:

AWSCredentialsProvider provider = new EnvironmentVariableCredentialsProvider();
AmazonWebServiceClient client = new AmazonS3Client(provider); // Noncompliant

Are there way to extract the particular implementation of interface from the variable provider when I explore the arguments of constructor AmazonS3Client? Now I can extract AWSCredentialsProvider for this variable only.


问:
Some methods missing in Calendar class
I want to make use of some methods of java.util.Calendar class like getActualMaximum() and roll() but they are missing in CodenameOne.

Am trying to get maximum day(last day) in a month for some date related calculation.

Please any workaround to this?

答:
A workaround would be:

```<code>java.util.Calendar cal = java.util.Calendar.getInstance();

int startDate = 28;
int maxDayOfMonth = startDate;
int currentMonth = cal.get(Calendar.MONTH);
cal.set(Calendar.DAY_OF_MONTH, startDate + 1);

while (currentMonth == cal.get(Calendar.MONTH)) {
    maxDayOfMonth++;
    cal.set(Calendar.DAY_OF_MONTH, maxDayOfMonth + 1);
}
System.out.println(maxDayOfMonth);
</code>```

Test:

```<code>SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
String date1 = "2017-02-27";
String date2 = "2017-02-28";
String date3 = "2017-03-01";
String date4 = "2017-04-20";

java.util.Calendar cal = java.util.Calendar.getInstance();
cal.setTime(dateFormat.parse(date1)); //Change as neccessary to test others
</code>```

Title: Some methods missing in Calendar class

Body:
A workaround would be:

java.util.Calendar cal = java.util.Calendar.getInstance();

int startDate = 28;
int maxDayOfMonth = startDate;
int currentMonth = cal.get(Calendar.MONTH);
cal.set(Calendar.DAY_OF_MONTH, startDate + 1);

while (currentMonth == cal.get(Calendar.MONTH)) {
    maxDayOfMonth++;
    cal.set(Calendar.DAY_OF_MONTH, maxDayOfMonth + 1);
}
System.out.println(maxDayOfMonth);

Test:

SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
String date1 = "2017-02-27";
String date2 = "2017-02-28";
String date3 = "2017-03-01";
String date4 = "2017-04-20";

java.util.Calendar cal = java.util.Calendar.getInstance();
cal.setTime(dateFormat.parse(date1)); //Change as neccessary to test others


问:
iOS XCode getting IDEPseudoTerminalDomain error 1
I am trying build a app for iOS using XCode.
The app works fine on iPhone simulator but before running it throws error "IDEPseudoTerminalDomain error 1". Don't know why it is causing this.

If I try to run all on iPad simulator then it doesn't open simulator at all.

```<code>The operation couldn’t be completed. (IDEPseudoTerminalDomain error 1.)
</code>```

Please can you tell me why this error is coming and how to avoid it.

Thanks in advance.

答:
Try increasing the max number of pseudo terminals by doing this:

```<code>sudo sysctl -w kern.tty.ptmx_max=999
</code>```

To make the change permanent beyond the current terminal session, do this:

```<code>sudo touch /etc/sysctl.conf
sudo chown root:wheel /etc/sysctl.conf
sudo chmod 644 /etc/sysctl.conf
echo "kern.tty.ptmx_max=999" | sudo tee -a /etc/sysctl.conf
</code>```

Credits go to bartoszj at https://www.pgs-soft.com/ios-ui-testing-and-why-it-does-not-always-work-a-k-a-pushing-the-limits-of-the-xctest-framework/

Body:
I am trying build a app for iOS using XCode.
The app works fine on iPhone simulator but before running it throws error "IDEPseudoTerminalDomain error 1". Don't know why it is causing this.

If I try to run all on iPad simulator then it doesn't open simulator at all.

The operation couldn’t be completed. (IDEPseudoTerminalDomain error 1.)

Please can you tell me why this error is coming and how to avoid it.

Thanks in advance.

Body:
Try increasing the max number of pseudo terminals by doing this:

sudo sysctl -w kern.tty.ptmx_max=999

To make the change permanent beyond the current terminal session, do this:

sudo touch /etc/sysctl.conf
sudo chown root:wheel /etc/sysctl.conf
sudo chmod 644 /etc/sysctl.conf
echo "kern.tty.ptmx_max=999" | sudo tee -a /etc/sysctl.conf

Credits go to bartoszj at https://www.pgs-soft.com/ios-ui-testing-and-why-it-does-not-always-work-a-k-a-pushing-the-limits-of-the-xctest-framework/


问:
How do I grab just the parsed Infobox of a wikipedia article?
I'm still stuck on my problem of trying to parse articles from wikipedia. Actually I wish to parse the infobox section of articles from wikipedia i.e. my application has references to countries and on each country page I would like to be able to show the infobox which is on corresponding wikipedia article of that country. I'm using php here - I would greatly appreciate it if anyone has any code snippets or advice on what should I be doing here.

Thanks again.

EDIT

Well I have a db table with names of countries. And I have a script that takes a country and shows its details. I would like to grab the infobox - the blue box with all country details images etc as it is from wikipedia and show it on my page. I would like to know a really simple and easy way to do that - or have a script that just downloads the information of the infobox to a local remote system which I could access myself later on. I mean I'm open to ideas here - except that the end result I want is to see the infobox on my page - of course with a little Content by Wikipedia link at the bottom :)

EDIT

I think I found what I was looking for on http://infochimps.org - they got loads of datasets in I think the YAML language. I can use this information straight up as it is but I would need a way to constantly update this information from wikipedia now and then although I believe infoboxes rarely change especially o countries unless some nation decides to change their capital city or so.

答:
I'd use the wikipedia (wikimedia) API.  You can get data  back in JSON, XML, php native format, and others.  You'll then still need to parse the returned information to extract and format the info you want, but the info box start, stop, and information types are clear.

Run your query for just rvsection=0, as this first section gets you the material before the first section break, including the infobox.  Then you'll need to parse the infobox content, which shouldn't be too hard.  See en.wikipedia.org/w/api.php for the formal wikipedia api documentation, and www.mediawiki.org/wiki/API for the manual.

Run, for example, the query: http://en.wikipedia.org/w/api.php?action=query&prop=revisions&rvprop=content&format=xmlfm&titles=fortran&rvsection=0


问:
Issue with MultipleUIPickerView in single UIViewcontroller
    in IOS Application I want to develope UIPickerview like this.code is below.

```<code>#import "CalcViewController.h"

@interface CalcViewController ()

@end

@implementation EZCalcViewController

+(CalcViewController *)viewcontroller{
    CalcViewController *rz=[[CalcViewController alloc]initWithNibName:@"CalcViewController" bundle:nil];
    return  rz;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    picker1 = [[UIPickerView alloc] init];
    [self.view addSubview:picker1];
    picker2 = [[UIPickerView alloc] init];
    [self.view addSubview:picker2];
    picker3 = [[UIPickerView alloc] init];
    [self.view addSubview:picker3];
    picker1.delegate=self;
    picker1.delegate=self;
    _customPickerArrayshap = [[NSMutableArray alloc] init];
    _customPickerArraycolor = [[NSMutableArray alloc] init];
    _customPickerArrayclarity = [[NSMutableArray alloc] init];

   /// [_customPickerArrayshap.count = 0];
    [self dropdownshape];
    [self dropdowncolor];
    [self dropdownclarity];

}
-(void)dropdownshape
{

    NSLog(@"dropdown method is call");

    NSString *envalope=[NSString stringWithFormat:@"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
                        "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n"
                        "<soap:Body>\n"
                        "<value1 xmlns=\"http://tempuri.org/\">\n"
                        “</value1>\n"
                        "</soap:Body>\n"
                        "</soap:Envelope>"];

    envalope=[NSString stringWithFormat:envalope];
    NSData *envelope = [envalope dataUsingEncoding:NSUTF8StringEncoding];
    NSString *url=@“ABC.asmx";

    NSMutableURLRequest *request2 = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30.0];

    [request2 addValue:@"http://tempuri.org/Value1" forHTTPHeaderField:@"SOAPAction"];
    [request2 setHTTPMethod:@"POST"];
    [request2 setHTTPBody:envelope];
    [request2 setValue:@"text/xml; charset=utf-8"
    forHTTPHeaderField:@"Content-Type"];
    [request2 setValue:[NSString stringWithFormat:@"%d", [envelope length]]forHTTPHeaderField:@"Content-Length"];

    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request2 delegate:self];
    if (connection){
        resshap = [NSMutableData data];
        NSLog(@"connection Establish.");
    }
    else{
        NSLog(@"NSURLConnection initWithRequest: Failed to return a connection.");
    }

}
-(void)dropdowncolor
{

    NSLog(@"dropdown method is call");

    NSString *envalope=[NSString stringWithFormat:@"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
                        "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n"
                        "<soap:Body>\n"
                        "<value2 xmlns=\"http://tempuri.org/\">\n"
                        “</value2>\n"
                        "</soap:Body>\n"
                        "</soap:Envelope>"];

    envalope=[NSString stringWithFormat:envalope];
    NSData *envelope = [envalope dataUsingEncoding:NSUTF8StringEncoding];
    NSString *url=@"http://ABC.asmx";

    NSMutableURLRequest *request1 = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30.0];

    [request1 addValue:@"http://tempuri.org/value2" forHTTPHeaderField:@"SOAPAction"];
    [request1 setHTTPMethod:@"POST"];
    [request1 setHTTPBody:envelope];
    [request1 setValue:@"text/xml; charset=utf-8"
    forHTTPHeaderField:@"Content-Type"];
    [request1 setValue:[NSString stringWithFormat:@"%d", [envelope length]]forHTTPHeaderField:@"Content-Length"];

    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request1 delegate:self];
    if (connection){
        rescolor = [NSMutableData data];
        NSLog(@"connection Establish.");
    }
    else{
        NSLog(@"NSURLConnection initWithRequest: Failed to return a connection.");
    }

}

-(void)dropdownclarity
{

    NSLog(@"dropdown method is call");

    NSString *envalope=[NSString stringWithFormat:@"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
                        "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n"
                        "<soap:Body>\n"
                        "<value3 xmlns=\"http://tempuri.org/\">\n"
                        “</value3>\n"
                        "</soap:Body>\n"
                        "</soap:Envelope>"];

    envalope=[NSString stringWithFormat:envalope];
    NSData *envelope = [envalope dataUsingEncoding:NSUTF8StringEncoding];
  NSString *url=@"http://ABC.asmx";

    NSMutableURLRequest *request1 = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30.0];

    [request1 addValue:@"http://tempuri.org/value3" forHTTPHeaderField:@"SOAPAction"];
    [request1 setHTTPMethod:@"POST"];
    [request1 setHTTPBody:envelope];
    [request1 setValue:@"text/xml; charset=utf-8"
    forHTTPHeaderField:@"Content-Type"];
    [request1 setValue:[NSString stringWithFormat:@"%d", [envelope length]]forHTTPHeaderField:@"Content-Length"];

    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request1 delegate:self];
    if (connection){
       resclarity = [NSMutableData data];
        NSLog(@"connection Establish.");
    }
    else{
        NSLog(@"NSURLConnection initWithRequest: Failed to return a connection.");
    }

}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{

    [resshap setLength:0];
    [rescolor setLength:0];
     [resclarity setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {

   [resshap appendData:data];
    [rescolor appendData:data];
    [resclarity appendData:data];

}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    NSLog(@"connection didFailWithError: %@ %@", error.localizedDescription,
          [error.userInfo objectForKey:NSURLErrorFailingURLStringErrorKey]);
    NSString *err=error.localizedDescription;
    UIAlertView *alr=[[UIAlertView alloc]initWithTitle:@"App" message:err delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil];

}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    // [[ActivityIndicator currentIndicator]displayCompleted];
    NSLog(@"DONE. Received Bytes:%d",[resshap length]);
     NSLog(@"DONE. Received Bytes:%d",[rescolor length]);
     NSLog(@"DONE. Received Bytes:%d",[resclarity length]);

    NSString *theXml1 = [[NSString alloc] initWithBytes:[resshap mutableBytes] length:[resshap length] encoding:NSUTF8StringEncoding];
    NSLog(@"The final result 1--- :%@",theXml1);

    NSString *string1=[NSString stringWithFormat:@"r%@d",theXml1];
    NSLog(@"Object having value 1%@",string1);

      NSString *thexml2 = [[NSString alloc] initWithBytes:[rescolor mutableBytes] length:[rescolor length] encoding:NSUTF8StringEncoding];
    NSLog(@"The final result 2--- :%@",theXml1);

    NSString *string2=[NSString stringWithFormat:@"r%@d",thexml2];
    NSLog(@"Object having value  2%@",string2);

      NSString *thexml3 = [[NSString alloc] initWithBytes:[resclarity mutableBytes] length:[resclarity length] encoding:NSUTF8StringEncoding];
    NSLog(@"The final result 3--- :%@",theXml1);

    NSString *string3=[NSString stringWithFormat:@"r%@d",thexml3];
    NSLog(@"Object having value 3%@",string3);

    if(xmlParser1)
    {

    }
    xmlParser1 = [[NSXMLParser alloc] initWithData: resshap];
    [xmlParser1 setDelegate:self];
    [xmlParser1 setShouldResolveExternalEntities:YES];
    [xmlParser1 parse];
    //[theXml release];

    if(xmlParser2)
    {

    }
    xmlParser2 = [[NSXMLParser alloc] initWithData: rescolor];
    [xmlParser2 setDelegate:self];
    [xmlParser2 setShouldResolveExternalEntities:YES];
    [xmlParser2 parse];
    //[theXml release];

    if(xmlParser3)
    {

    }
    xmlParser3 = [[NSXMLParser alloc] initWithData: resclarity];
    [xmlParser3 setDelegate:self];
    [xmlParser3 setShouldResolveExternalEntities:YES];
    [xmlParser3 parse];
    //[theXml release];

}

//}
-(void) parser:(NSXMLParser *) parser didStartElement:(NSString *) elementName namespaceURI:(NSString *) namespaceURI qualifiedName:(NSString *) qName attributes:(NSDictionary *)attributeDict {
    if( [elementName isEqualToString:@“Value1Result"])
    {
        if (!soapResults1)
        {
            soapResults1 = [[NSMutableString alloc] init];
        }
        elementFound1 = YES;
    }
    else if([elementName isEqualToString:@“Value2Result"]){
        if (!soapResults2)
        {
            soapResults2 = [[NSMutableString alloc] init];
        }
        elementFound2 = YES;
    }else if( [elementName isEqualToString:@“value3Result"])
    {
        if (!soapResults3)
        {
            soapResults3 = [[NSMutableString alloc] init];
        }
        elementFound3 = YES;
    }

}
-(void)parser:(NSXMLParser *) parser foundCharacters:(NSString *)string
{
    if (elementFound1)
    {
        [soapResults1 appendString: string];

        NSArray * jsonarr1 =[NSJSONSerialization JSONObjectWithData:[string dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
        NSLog(@"print array :%@",jsonarr1);
        for (NSDictionary * d in jsonarr1)
        {
            if ([d objectForKey:@"SHP"]!=[NSNull null])
            {
                [picker1 reloadAllComponents];
                self.shapestring=[NSString stringWithFormat:@"%@",[d objectForKey:@“V1”]];
                 NSLog(@"pVALUE FOR CLR :%@",self.shapestring);
                [_customPickerArrayshap addObject:self.shapestring];
               NSLog(@"pVALUE AFTER ARRAY FILL:%d",_customPickerArrayshap.count);
                [picker1 reloadAllComponents];
            }
            else
            {self.shapestring=@"";
                            }
        }
    }
        if(elementFound2){
            [soapResults2 appendString: string];

            NSArray * jsonarr2 =[NSJSONSerialization JSONObjectWithData:[string dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
            NSLog(@"print array :%@",jsonarr2);
            for (NSDictionary * d in jsonarr2)
            {

            if ([d objectForKey:@"RAPCOL"]!=[NSNull null])
            {
                [picker2 reloadAllComponents];
                self.colorstring=[NSString stringWithFormat:@"%@",[d objectForKey:@“v2”]];
                NSLog(@"pVALUE FOR CLR :%@",self.colorstring);
                [_customPickerArraycolor addObject:self.colorstring];
                // NSLog(@"pVALUE AFTER ARRAY FILL:%d",_customPickerArray1.);
                [picker3 reloadAllComponents];
            }
            else
            {
                self.colorstring=@"";

            }

        }
        }
        if(elementFound3){
            [soapResults3 appendString: string];

            NSArray * jsonarr3 =[NSJSONSerialization JSONObjectWithData:[string dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
            NSLog(@"print array :%@",jsonarr3);

            for (NSDictionary * d in jsonarr3)
            {

            if ([d objectForKey:@"CLR"]!=[NSNull null])
            {
                [picker3 reloadAllComponents];
                self.claritystring=[NSString stringWithFormat:@"%@",[d objectForKey:@“V3”]];
                NSLog(@"pVALUE FOR CLR :%@",self.claritystring);
                [_customPickerArrayclarity addObject:self.claritystring];
                // NSLog(@"pVALUE AFTER ARRAY FILL:%d",_customPickerArray1.);
                [picker3 reloadAllComponents];
            }
            else
            {
                 self.claritystring=@"";
            }

        }
        }
    }

-(void)parser:(NSXMLParser *)parser
didEndElement:(NSString *)elementName
 namespaceURI:(NSString *)namespaceURI
qualifiedName:(NSString *)qName
{
    if ([elementName isEqualToString:@“value1Result"])
    {

        [self.customPickerArrayshap addObject:@“v1”];

        NSLog(@"%@",soapResults1);

        [soapResults1 setString:@""];
        elementFound1 = FALSE;

    }
   else if ([elementName isEqualToString:@“Value2Result"])
    {

        [self.customPickerArraycolor addObject:@“v2”];
             [soapResults2 setString:@""];
        elementFound2 = FALSE;

    }else if ([elementName isEqualToString:@“Value3Result"]){
        [self.customPickerArrayclarity addObject:@“V3”];
             [soapResults3 setString:@""];
        elementFound3 = FALSE;
    }

}
- (int)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 1;
}
- (int)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{

    if([pickerView tag]==1)
    {
        return _customPickerArrayshap.count;
    }
    else if([pickerView tag]==2)
    {

        return _customPickerArraycolor.count;
    }else if([pickerView tag]==3){

        return _customPickerArrayclarity.count;
    }

}
- (NSString*)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    if([pickerView tag]==1)
    {

        return _customPickerArrayshap[row];
    }
    else if([pickerView tag]==2)
    {
        return _customPickerArraycolor[row];
    }else if([pickerView tag]==3){
        return _customPickerArrayclarity[row];
    }

}
</code>```

using above code i want to Develope like thissee referance image,I have 3 PickerView and data is set from soap WebService,for data assign i have add Indivisual soap response in  in differant array,and based on PickerView's tag value data is assign,but problem is that only first soap response  is assign in pickerview remaining 2 are null,please suggest me if i'm go wrong.

答:
```<code>Try

picker1.delegate=self;
picker1.tag = 1;

picker2.delegate=self;
picker2.tag = 2;

picker3.delegate=self;
picker3.tag = 3;
</code>```

Body:
    in IOS Application I want to develope UIPickerview like this.code is below.

#import "CalcViewController.h"

@interface CalcViewController ()

@end

@implementation EZCalcViewController

+(CalcViewController *)viewcontroller{
    CalcViewController *rz=[[CalcViewController alloc]initWithNibName:@"CalcViewController" bundle:nil];
    return  rz;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    picker1 = [[UIPickerView alloc] init];
    [self.view addSubview:picker1];
    picker2 = [[UIPickerView alloc] init];
    [self.view addSubview:picker2];
    picker3 = [[UIPickerView alloc] init];
    [self.view addSubview:picker3];
    picker1.delegate=self;
    picker1.delegate=self;
    _customPickerArrayshap = [[NSMutableArray alloc] init];
    _customPickerArraycolor = [[NSMutableArray alloc] init];
    _customPickerArrayclarity = [[NSMutableArray alloc] init];

   /// [_customPickerArrayshap.count = 0];
    [self dropdownshape];
    [self dropdowncolor];
    [self dropdownclarity];

}
-(void)dropdownshape
{

    NSLog(@"dropdown method is call");

    NSString *envalope=[NSString stringWithFormat:@"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
                        "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n"
                        "<soap:Body>\n"
                        "<value1 xmlns=\"http://tempuri.org/\">\n"
                        “</value1>\n"
                        "</soap:Body>\n"
                        "</soap:Envelope>"];

    envalope=[NSString stringWithFormat:envalope];
    NSData *envelope = [envalope dataUsingEncoding:NSUTF8StringEncoding];
    NSString *url=@“ABC.asmx";

    NSMutableURLRequest *request2 = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30.0];

    [request2 addValue:@"http://tempuri.org/Value1" forHTTPHeaderField:@"SOAPAction"];
    [request2 setHTTPMethod:@"POST"];
    [request2 setHTTPBody:envelope];
    [request2 setValue:@"text/xml; charset=utf-8"
    forHTTPHeaderField:@"Content-Type"];
    [request2 setValue:[NSString stringWithFormat:@"%d", [envelope length]]forHTTPHeaderField:@"Content-Length"];

    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request2 delegate:self];
    if (connection){
        resshap = [NSMutableData data];
        NSLog(@"connection Establish.");
    }
    else{
        NSLog(@"NSURLConnection initWithRequest: Failed to return a connection.");
    }

}
-(void)dropdowncolor
{

    NSLog(@"dropdown method is call");

    NSString *envalope=[NSString stringWithFormat:@"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
                        "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n"
                        "<soap:Body>\n"
                        "<value2 xmlns=\"http://tempuri.org/\">\n"
                        “</value2>\n"
                        "</soap:Body>\n"
                        "</soap:Envelope>"];

    envalope=[NSString stringWithFormat:envalope];
    NSData *envelope = [envalope dataUsingEncoding:NSUTF8StringEncoding];
    NSString *url=@"http://ABC.asmx";

    NSMutableURLRequest *request1 = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30.0];

    [request1 addValue:@"http://tempuri.org/value2" forHTTPHeaderField:@"SOAPAction"];
    [request1 setHTTPMethod:@"POST"];
    [request1 setHTTPBody:envelope];
    [request1 setValue:@"text/xml; charset=utf-8"
    forHTTPHeaderField:@"Content-Type"];
    [request1 setValue:[NSString stringWithFormat:@"%d", [envelope length]]forHTTPHeaderField:@"Content-Length"];

    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request1 delegate:self];
    if (connection){
        rescolor = [NSMutableData data];
        NSLog(@"connection Establish.");
    }
    else{
        NSLog(@"NSURLConnection initWithRequest: Failed to return a connection.");
    }

}

-(void)dropdownclarity
{

    NSLog(@"dropdown method is call");

    NSString *envalope=[NSString stringWithFormat:@"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
                        "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n"
                        "<soap:Body>\n"
                        "<value3 xmlns=\"http://tempuri.org/\">\n"
                        “</value3>\n"
                        "</soap:Body>\n"
                        "</soap:Envelope>"];

    envalope=[NSString stringWithFormat:envalope];
    NSData *envelope = [envalope dataUsingEncoding:NSUTF8StringEncoding];
  NSString *url=@"http://ABC.asmx";

    NSMutableURLRequest *request1 = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30.0];

    [request1 addValue:@"http://tempuri.org/value3" forHTTPHeaderField:@"SOAPAction"];
    [request1 setHTTPMethod:@"POST"];
    [request1 setHTTPBody:envelope];
    [request1 setValue:@"text/xml; charset=utf-8"
    forHTTPHeaderField:@"Content-Type"];
    [request1 setValue:[NSString stringWithFormat:@"%d", [envelope length]]forHTTPHeaderField:@"Content-Length"];

    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request1 delegate:self];
    if (connection){
       resclarity = [NSMutableData data];
        NSLog(@"connection Establish.");
    }
    else{
        NSLog(@"NSURLConnection initWithRequest: Failed to return a connection.");
    }

}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{

    [resshap setLength:0];
    [rescolor setLength:0];
     [resclarity setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {

   [resshap appendData:data];
    [rescolor appendData:data];
    [resclarity appendData:data];

}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    NSLog(@"connection didFailWithError: %@ %@", error.localizedDescription,
          [error.userInfo objectForKey:NSURLErrorFailingURLStringErrorKey]);
    NSString *err=error.localizedDescription;
    UIAlertView *alr=[[UIAlertView alloc]initWithTitle:@"App" message:err delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil];

}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    // [[ActivityIndicator currentIndicator]displayCompleted];
    NSLog(@"DONE. Received Bytes:%d",[resshap length]);
     NSLog(@"DONE. Received Bytes:%d",[rescolor length]);
     NSLog(@"DONE. Received Bytes:%d",[resclarity length]);

    NSString *theXml1 = [[NSString alloc] initWithBytes:[resshap mutableBytes] length:[resshap length] encoding:NSUTF8StringEncoding];
    NSLog(@"The final result 1--- :%@",theXml1);

    NSString *string1=[NSString stringWithFormat:@"r%@d",theXml1];
    NSLog(@"Object having value 1%@",string1);

      NSString *thexml2 = [[NSString alloc] initWithBytes:[rescolor mutableBytes] length:[rescolor length] encoding:NSUTF8StringEncoding];
    NSLog(@"The final result 2--- :%@",theXml1);

    NSString *string2=[NSString stringWithFormat:@"r%@d",thexml2];
    NSLog(@"Object having value  2%@",string2);

      NSString *thexml3 = [[NSString alloc] initWithBytes:[resclarity mutableBytes] length:[resclarity length] encoding:NSUTF8StringEncoding];
    NSLog(@"The final result 3--- :%@",theXml1);

    NSString *string3=[NSString stringWithFormat:@"r%@d",thexml3];
    NSLog(@"Object having value 3%@",string3);

    if(xmlParser1)
    {

    }
    xmlParser1 = [[NSXMLParser alloc] initWithData: resshap];
    [xmlParser1 setDelegate:self];
    [xmlParser1 setShouldResolveExternalEntities:YES];
    [xmlParser1 parse];
    //[theXml release];

    if(xmlParser2)
    {

    }
    xmlParser2 = [[NSXMLParser alloc] initWithData: rescolor];
    [xmlParser2 setDelegate:self];
    [xmlParser2 setShouldResolveExternalEntities:YES];
    [xmlParser2 parse];
    //[theXml release];

    if(xmlParser3)
    {

    }
    xmlParser3 = [[NSXMLParser alloc] initWithData: resclarity];
    [xmlParser3 setDelegate:self];
    [xmlParser3 setShouldResolveExternalEntities:YES];
    [xmlParser3 parse];
    //[theXml release];

}

//}
-(void) parser:(NSXMLParser *) parser didStartElement:(NSString *) elementName namespaceURI:(NSString *) namespaceURI qualifiedName:(NSString *) qName attributes:(NSDictionary *)attributeDict {
    if( [elementName isEqualToString:@“Value1Result"])
    {
        if (!soapResults1)
        {
            soapResults1 = [[NSMutableString alloc] init];
        }
        elementFound1 = YES;
    }
    else if([elementName isEqualToString:@“Value2Result"]){
        if (!soapResults2)
        {
            soapResults2 = [[NSMutableString alloc] init];
        }
        elementFound2 = YES;
    }else if( [elementName isEqualToString:@“value3Result"])
    {
        if (!soapResults3)
        {
            soapResults3 = [[NSMutableString alloc] init];
        }
        elementFound3 = YES;
    }

}
-(void)parser:(NSXMLParser *) parser foundCharacters:(NSString *)string
{
    if (elementFound1)
    {
        [soapResults1 appendString: string];

        NSArray * jsonarr1 =[NSJSONSerialization JSONObjectWithData:[string dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
        NSLog(@"print array :%@",jsonarr1);
        for (NSDictionary * d in jsonarr1)
        {
            if ([d objectForKey:@"SHP"]!=[NSNull null])
            {
                [picker1 reloadAllComponents];
                self.shapestring=[NSString stringWithFormat:@"%@",[d objectForKey:@“V1”]];
                 NSLog(@"pVALUE FOR CLR :%@",self.shapestring);
                [_customPickerArrayshap addObject:self.shapestring];
               NSLog(@"pVALUE AFTER ARRAY FILL:%d",_customPickerArrayshap.count);
                [picker1 reloadAllComponents];
            }
            else
            {self.shapestring=@"";
                            }
        }
    }
        if(elementFound2){
            [soapResults2 appendString: string];

            NSArray * jsonarr2 =[NSJSONSerialization JSONObjectWithData:[string dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
            NSLog(@"print array :%@",jsonarr2);
            for (NSDictionary * d in jsonarr2)
            {

            if ([d objectForKey:@"RAPCOL"]!=[NSNull null])
            {
                [picker2 reloadAllComponents];
                self.colorstring=[NSString stringWithFormat:@"%@",[d objectForKey:@“v2”]];
                NSLog(@"pVALUE FOR CLR :%@",self.colorstring);
                [_customPickerArraycolor addObject:self.colorstring];
                // NSLog(@"pVALUE AFTER ARRAY FILL:%d",_customPickerArray1.);
                [picker3 reloadAllComponents];
            }
            else
            {
                self.colorstring=@"";

            }

        }
        }
        if(elementFound3){
            [soapResults3 appendString: string];

            NSArray * jsonarr3 =[NSJSONSerialization JSONObjectWithData:[string dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
            NSLog(@"print array :%@",jsonarr3);

            for (NSDictionary * d in jsonarr3)
            {

            if ([d objectForKey:@"CLR"]!=[NSNull null])
            {
                [picker3 reloadAllComponents];
                self.claritystring=[NSString stringWithFormat:@"%@",[d objectForKey:@“V3”]];
                NSLog(@"pVALUE FOR CLR :%@",self.claritystring);
                [_customPickerArrayclarity addObject:self.claritystring];
                // NSLog(@"pVALUE AFTER ARRAY FILL:%d",_customPickerArray1.);
                [picker3 reloadAllComponents];
            }
            else
            {
                 self.claritystring=@"";
            }

        }
        }
    }

-(void)parser:(NSXMLParser *)parser
didEndElement:(NSString *)elementName
 namespaceURI:(NSString *)namespaceURI
qualifiedName:(NSString *)qName
{
    if ([elementName isEqualToString:@“value1Result"])
    {

        [self.customPickerArrayshap addObject:@“v1”];

        NSLog(@"%@",soapResults1);

        [soapResults1 setString:@""];
        elementFound1 = FALSE;

    }
   else if ([elementName isEqualToString:@“Value2Result"])
    {

        [self.customPickerArraycolor addObject:@“v2”];
             [soapResults2 setString:@""];
        elementFound2 = FALSE;

    }else if ([elementName isEqualToString:@“Value3Result"]){
        [self.customPickerArrayclarity addObject:@“V3”];
             [soapResults3 setString:@""];
        elementFound3 = FALSE;
    }

}
- (int)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 1;
}
- (int)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{

    if([pickerView tag]==1)
    {
        return _customPickerArrayshap.count;
    }
    else if([pickerView tag]==2)
    {

        return _customPickerArraycolor.count;
    }else if([pickerView tag]==3){

        return _customPickerArrayclarity.count;
    }

}
- (NSString*)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    if([pickerView tag]==1)
    {

        return _customPickerArrayshap[row];
    }
    else if([pickerView tag]==2)
    {
        return _customPickerArraycolor[row];
    }else if([pickerView tag]==3){
        return _customPickerArrayclarity[row];
    }

}

using above code i want to Develope like thissee referance image,I have 3 PickerView and data is set from soap WebService,for data assign i have add Indivisual soap response in  in differant array,and based on PickerView's tag value data is assign,but problem is that only first soap response  is assign in pickerview remaining 2 are null,please suggest me if i'm go wrong.