问:
Angucomplete Alt : Getting "No Results Found" before the server response is obtained
I am trying to initiate a request after 3 characters but once 3 characters are typed I am getting the No records found error and after that I can find the service call get completed but nothing is shown in auto complete(only the error message under the autocomplete dropdown).What am I missing here?

HTML code:

```<code>       <angucomplete-alt id="angu_{{$index}}"
                                      placeholder="Search people"
                                      remote-api-handler="search"
                                      remote-url-data-field="results"
                                      title-field="fullName"
                                      minlength="3"
                                      input-class="form-control form-control-small"
                                      selected-object="selected"
                                      selected-object-data="$index"
                                      clear-selected="true"/>
</code>```

Api remote handler

```<code>  $scope.search = function(str, timeoutPromise) {
   return $timeout(function () {
    $scope.input = {};
     $scope.input.userId = "";
     $scope.input.name = str;
     $scope.input.system = "";
     $scope.input.officeNumber = "";
     $scope.input.department= "";
     //  server call and get the response to $scope.organisationNames
        var promise = genericAPIService.doApiCall(url, appConstant.POST,
    JSON.stringify($scope.input));
            promise.then(
              function(payload) {
                  console.log(payload);
                 $scope.organisationNames = payload.data.result.data.List;
                 $scope.results = [];
                 $scope.organisationNames.forEach(function(organisation) {
                        if ((organisation.fullName.toLowerCase().indexOf(str.toString().toLowerCase()) >= 0)) {
                            $scope.results.push(organisation);
                        }
                    });
                 return scope.results;
              },
              function(errorPayload) {
                  $log.error('failure loading role json', errorPayload);
              }).finally(function(){
                    $scope.loading = false;
                });
}
},5000);
};
</code>```

Tried another version of the same:

```<code> <angucomplete-alt id="angu_{{$index}}"
                   placeholder="Search people"
                   selected-object="selectedBusiness"
                   selected-object-data="$index"
                   clear-selected="true"
                   input-class="form-control
                   form-control-small"
                   remote-api-handler="searchAPI"
                   remote-url-data-field="responseData.data"
                   title-field="fullName" minlength="3" />

   $scope.searchAPI = function (userInputString, timeoutPromise) {
   $scope.approversAndEndorsersInput = {};
   return $timeout(function () {
         $scope.approversAndEndorsersInput.userId = "";
         $scope.approversAndEndorsersInput.name = userInputString;
         $scope.approversAndEndorsersInput.system = "";
         $scope.approversAndEndorsersInput.officeNumber = "";
         $scope.approversAndEndorsersInput.department= "";
         return $http.post(appConstant.selfDomainName+appConstant.getApproversAndEndorsersList, JSON.stringify($scope.approversAndEndorsersInput), {timeout: timeoutPromise});

   }, 1000);
</code>```

}

答:
I was able to solve the issue.PFB the link which helped in solving it.

Angucomplete-alt: Remote-API-handler not working as expected

Body:
I am trying to initiate a request after 3 characters but once 3 characters are typed I am getting the No records found error and after that I can find the service call get completed but nothing is shown in auto complete(only the error message under the autocomplete dropdown).What am I missing here?

HTML code:

       <angucomplete-alt id="angu_{{$index}}"
                                      placeholder="Search people"
                                      remote-api-handler="search"
                                      remote-url-data-field="results"
                                      title-field="fullName"
                                      minlength="3"
                                      input-class="form-control form-control-small"
                                      selected-object="selected"
                                      selected-object-data="$index"
                                      clear-selected="true"/>

Api remote handler

  $scope.search = function(str, timeoutPromise) {
   return $timeout(function () {
    $scope.input = {};
     $scope.input.userId = "";
     $scope.input.name = str;
     $scope.input.system = "";
     $scope.input.officeNumber = "";
     $scope.input.department= "";
     //  server call and get the response to $scope.organisationNames
        var promise = genericAPIService.doApiCall(url, appConstant.POST,
    JSON.stringify($scope.input));
            promise.then(
              function(payload) {
                  console.log(payload);
                 $scope.organisationNames = payload.data.result.data.List;
                 $scope.results = [];
                 $scope.organisationNames.forEach(function(organisation) {
                        if ((organisation.fullName.toLowerCase().indexOf(str.toString().toLowerCase()) >= 0)) {
                            $scope.results.push(organisation);
                        }
                    });
                 return scope.results;
              },
              function(errorPayload) {
                  $log.error('failure loading role json', errorPayload);
              }).finally(function(){
                    $scope.loading = false;
                });
}
},5000);
};

Tried another version of the same:

 <angucomplete-alt id="angu_{{$index}}"
                   placeholder="Search people"
                   selected-object="selectedBusiness"
                   selected-object-data="$index"
                   clear-selected="true"
                   input-class="form-control
                   form-control-small"
                   remote-api-handler="searchAPI"
                   remote-url-data-field="responseData.data"
                   title-field="fullName" minlength="3" />

   $scope.searchAPI = function (userInputString, timeoutPromise) {
   $scope.approversAndEndorsersInput = {};
   return $timeout(function () {
         $scope.approversAndEndorsersInput.userId = "";
         $scope.approversAndEndorsersInput.name = userInputString;
         $scope.approversAndEndorsersInput.system = "";
         $scope.approversAndEndorsersInput.officeNumber = "";
         $scope.approversAndEndorsersInput.department= "";
         return $http.post(appConstant.selfDomainName+appConstant.getApproversAndEndorsersList, JSON.stringify($scope.approversAndEndorsersInput), {timeout: timeoutPromise});

   }, 1000);

}


来源: stackexchange

问:
SSRS Custom Assemblies could not be loaded under Visual Studio 2017
I have just installed VS 2017 and moved my SSRS project from VS 2015 to 2017. I have a custom assembly which is working fine under VS 2015, but not 2017. It says

Error while loading code module: 'CustomLib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'. Details: Could not load file or assembly 'CustomLib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified.

I had exact same problem under VS 2015 and the solution was moving my custom dll under

C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\PrivateAssemblies

So, I have moved my custom dll under

C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\Common7\IDE\PrivateAssemblies

which I believe is the correct path for VS 2017 and check file/folder permissions and set them identical, but no way, it still throws same error.

What am I missing?

答:
TLDR - C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\Common7\IDE\CommonExtensions\Microsoft\SSDTRS

I was having the same problem - try using the Fusion Assembly Binding Log Viewer to peer into what the problem is as per http://www.hanselman.com/blog/BackToBasicsUsingFusionLogViewerToDebugObscureLoaderErrors.aspx

With "Log bind failures to disk" enabled (and restarting VS) the devenv.exe process folder in your log location should then produce log files when you recreate the problem. Part of what it will tell you is the various folder locations VS is checking for assemblies. My issue was that I hadn't copied a required assembly. You might also be having a problem with it not liking a specific version of a dll it is trying to load (for instance .Net 4 v 2), the logs will highlight that as well.

The viewer tool is pretty poor in terms of being able to sort columns. I found it much easier to just open C:\FusionLogs\Default\devenv.exe (where I had set C:\FusionLogs as the custom log path), sort by date modified and watch as new files were created when trying to add the data source.

In terms of which folder to use - I initially dropped them into PrivateAssemblies which worked for creating the data source / reports. However when it came to build the preview the report I then got another could not load assemblies message. Again using the log viewer, but this time in the PreviewProcessingService.exe folder the error suggests the only directory that checks for the assemblies is: C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\Common7\IDE\CommonExtensions\Microsoft\SSDTRS - this location works for both creating and previewing reports.

ContentLicense: CC BY-SA 3.0


问:
How to parse array of JSON in Swift 3
I am getting some data from Socket which I would like to access but I am getting error saying can't convert NSArray to NSDictionary each time.

```<code>struct SocketEventHandler {
    let event: String
    let id: UUID
    let callback: NormalCallback

    func executeCallback(with items: [Any], withAck ack: Int, withSocket socket: SocketIOClient) {
        callback(items, SocketAckEmitter(socket: socket, ackNum: ack))
    }
}

let onFriendRequestStatus: NormalCallback = {dataArray,socketAck in
        AppLog.debug(tag: TAG, msg: "Response: \(dataArray)")
        AppLog.debug(tag: TAG, msg: "Response: \(dataArray[0])")
        let response  = dataArray[0] as! Dictionary<String, Any> **// APP CRASHES ON THIS LINE**
}
</code>```

Response :-

```<code>[
    {
        "status": "A",
        "acceptorId": 126,
        "id": 94,
        "createdAt": "2017-06-05T09:50:42.000Z",
        "updatedAt": "2017-06-05T09:52:26.000Z",
        "userId": 126,
        "friendId": 401
    }
]
</code>```

Error - Could not cast value of type '__NSArrayM' (0x102f0de00) to 'NSDictionary' (0x102f0e2d8).

答:
May be you are having 2d array means the elements of dataArray are also Array not Dictionary.

```<code>if let response = dataArray[0] as? [[String: Any]], let dictionary = response.first {

    print(dictionary["status"])
}
</code>```

Title: How to parse array of JSON in Swift 3

Body:
I am getting some data from Socket which I would like to access but I am getting error saying can't convert NSArray to NSDictionary each time.

struct SocketEventHandler {
    let event: String
    let id: UUID
    let callback: NormalCallback

    func executeCallback(with items: [Any], withAck ack: Int, withSocket socket: SocketIOClient) {
        callback(items, SocketAckEmitter(socket: socket, ackNum: ack))
    }
}

let onFriendRequestStatus: NormalCallback = {dataArray,socketAck in
        AppLog.debug(tag: TAG, msg: "Response: \(dataArray)")
        AppLog.debug(tag: TAG, msg: "Response: \(dataArray[0])")
        let response  = dataArray[0] as! Dictionary<String, Any> **// APP CRASHES ON THIS LINE**
}

Response :-

[
    {
        "status": "A",
        "acceptorId": 126,
        "id": 94,
        "createdAt": "2017-06-05T09:50:42.000Z",
        "updatedAt": "2017-06-05T09:52:26.000Z",
        "userId": 126,
        "friendId": 401
    }
]

Error - Could not cast value of type '__NSArrayM' (0x102f0de00) to 'NSDictionary' (0x102f0e2d8).

Body:
May be you are having 2d array means the elements of dataArray are also Array not Dictionary.

if let response = dataArray[0] as? [[String: Any]], let dictionary = response.first {

    print(dictionary["status"])
}


问:
How to set the Tab bar item 1 to be selected by default in iphone?
I am new to iPhone development. I am creating a view based application. I have added a tab bar in my view (and not a tab bar controller). By setting the tag vale of the tab bar item to 1, 2, I have loaded the view for each tab bar on tabbar item click event.

I want the tab bar 1 to be selected by default. What should I do for that?

Here is my code:

```<code>- (void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item {
    NSLog(@"didSelectItem: %d", item.tag);
    [self activateTab:item.tag];
}

- (void)activateTab:(int)index {
    switch (index) {
        case 1:

                self.tab1ViewController =[[tab1 alloc] initWithNibName:@"tab1" bundle:nil];

            [self.view insertSubview:tab1ViewController.view belowSubview:tabbar1];
            if (currentViewController != nil)
                [currentViewController.view removeFromSuperview];
            currentViewController = tab1ViewController;
            break;
        case 2:

                self.tab2ViewController =[[tab2 alloc] initWithNibName:@"tab2" bundle:nil];
           [self.view insertSubview:tab2ViewController.view belowSubview:tabbar1];
           if (currentViewController != nil)
                [currentViewController.view removeFromSuperview];
            currentViewController = tab2ViewController;
            break;
        default:
            break;
    }
}
</code>```

I added the the tab bar in interface builder.Can i do any thing in interface builder?

答:
Swift 3:</p>

```<code>@IBOutlet weak var uiTabBarOutlet: UITabBar!

uiTabBarOutlet.selectedItem = uiTabBarOutlet.items?[0]
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am new to iPhone development. I am creating a view based application. I have added a tab bar in my view (and not a tab bar controller). By setting the tag vale of the tab bar item to 1, 2, I have loaded the view for each tab bar on tabbar item click event.

I want the tab bar 1 to be selected by default. What should I do for that?

Here is my code:

- (void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item {
    NSLog(@"didSelectItem: %d", item.tag);
    [self activateTab:item.tag];
}

- (void)activateTab:(int)index {
    switch (index) {
        case 1:

                self.tab1ViewController =[[tab1 alloc] initWithNibName:@"tab1" bundle:nil];

            [self.view insertSubview:tab1ViewController.view belowSubview:tabbar1];
            if (currentViewController != nil)
                [currentViewController.view removeFromSuperview];
            currentViewController = tab1ViewController;
            break;
        case 2:

                self.tab2ViewController =[[tab2 alloc] initWithNibName:@"tab2" bundle:nil];
           [self.view insertSubview:tab2ViewController.view belowSubview:tabbar1];
           if (currentViewController != nil)
                [currentViewController.view removeFromSuperview];
            currentViewController = tab2ViewController;
            break;
        default:
            break;
    }
}

I added the the tab bar in interface builder.Can i do any thing in interface builder?

Body:
Swift 3:

@IBOutlet weak var uiTabBarOutlet: UITabBar!

uiTabBarOutlet.selectedItem = uiTabBarOutlet.items?[0]


问:
Create new array from existing one only with elements that contain specific value
I create a new array from an existing one (big array with 100.000 objects). In the new array I want only elements where the value of "city" is for example New York City.

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

    for (var i = 0; i < data.length; i++) {

        if(data[i].city === "New York City") {

            newData[i] = {"city": data[i].city, "longitude":
            data[i].longitude, "latitude": data[i].latitude, "state":
            data[i].state};

        }
     }
</code>```

I must be doing something wrong since a lot of elements in the new array are null …

The new array then looks something like this:

```<code>[null,null,null,null,null, {"city":"New York", "logitude":
-73.935242, "latitude": 40.730610, "state": "NY"},
null,null,null,null,null,null,"city":"New York", "logitude":
-73.935242, "latitude": 40.730610, "state": "NY"}]
</code>```

What am I doing wrong? How could I achieve my goal?

Thanks in advance guys!

答:
You can use Array.prototype.filter method:

```<code>newData.filter(function (el) {
  return el.city === "New York City";
});
</code>```

or if you need other filter parameter:

```<code>newData.filter(function (el) {
  return el.city === "New York City" && el.state === "NY" ;
});
</code>```

This method is part of the new ECMAScript 5th Edition standard.

From documentation:

filter() calls a provided callback function once for each element in
  an array, and constructs a new array of all the values for which
  callback returns a value that coerces to true. callback is invoked
  only for indexes of the array which have assigned values; it is not
  invoked for indexes which have been deleted or which have never been
  assigned values. Array elements which do not pass the callback test
  are simply skipped, and are not included in the new array.

Body:
I create a new array from an existing one (big array with 100.000 objects). In the new array I want only elements where the value of "city" is for example New York City.

    var newData = [];

    for (var i = 0; i < data.length; i++) {

        if(data[i].city === "New York City") {

            newData[i] = {"city": data[i].city, "longitude":
            data[i].longitude, "latitude": data[i].latitude, "state":
            data[i].state};

        }
     }

I must be doing something wrong since a lot of elements in the new array are null …

The new array then looks something like this:

[null,null,null,null,null, {"city":"New York", "logitude":
-73.935242, "latitude": 40.730610, "state": "NY"},
null,null,null,null,null,null,"city":"New York", "logitude":
-73.935242, "latitude": 40.730610, "state": "NY"}]

What am I doing wrong? How could I achieve my goal?

Thanks in advance guys!

Body:
You can use Array.prototype.filter method:

newData.filter(function (el) {
  return el.city === "New York City";
});

or if you need other filter parameter:

newData.filter(function (el) {
  return el.city === "New York City" && el.state === "NY" ;
});

This method is part of the new ECMAScript 5th Edition standard.

From documentation:

filter() calls a provided callback function once for each element in
  an array, and constructs a new array of all the values for which
  callback returns a value that coerces to true. callback is invoked
  only for indexes of the array which have assigned values; it is not
  invoked for indexes which have been deleted or which have never been
  assigned values. Array elements which do not pass the callback test
  are simply skipped, and are not included in the new array.


问:
how to use scrolling in iframe in fancybox 3?
I'm trying to use iframe with in fancyapp 3 and I need to set the parameters preload and scrolling to false and auto, but with my current code I'm not able to do so.

Can you please check what it is wrong in it?

Follows the code:

```<code><script>
$("[data-fancybox]").fancybox({
    iframe : {
    scrolling: 'auto',
            css : {
            width : '600px'
        }
        }
});
</script>

<a data-fancybox data "http://www.test.com">show</a>
</code>```

答:
You can do like this:</p>

```<code>$("[data-fancybox]").fancybox({
    speed: 230,
    infobar: false,
    buttons: false,
    fullScreen: false,
    thumbs: false,
    closeBtn: false,
    iframe: {
        scrolling: 'yes' //'no'//'auto'
    }
});
</code>```

Body:
I'm trying to use iframe with in fancyapp 3 and I need to set the parameters preload and scrolling to false and auto, but with my current code I'm not able to do so.

Can you please check what it is wrong in it?

Follows the code:

show

Body:
You can do like this:

$("[data-fancybox]").fancybox({
    speed: 230,
    infobar: false,
    buttons: false,
    fullScreen: false,
    thumbs: false,
    closeBtn: false,
    iframe: {
        scrolling: 'yes' //'no'//'auto'
    }
});


问:
How to treat `Promise.reject` as a first-class function?
Why can I do this:

```<code>> Promise.reject(3);
< Promise {[[PromiseStatus]]: "rejected", [[PromiseValue]]: 3}
</code>```

But not this:

```<code>> var f = Promise.reject;
< undefined

> f(3)
< VM2366:1 Uncaught TypeError: PromiseReject called on non-object
    at reject (<anonymous>)
    at <anonymous>:1:1
</code>```

答:
The spec defines Promise.reject as follows (emphasis mine):

25.4.4.4 Promise.reject( r )

The reject function returns a new promise rejected with the passed
  argument.

Let C be the this value.

If Type(C) is not Object, throw a TypeError exception.

Let promiseCapability be ? NewPromiseCapability(C).

Perform ? Call(promiseCapability.[[Reject]], undefined, « r »).

Return promiseCapability.[[Promise]].

NOTE: The reject function expects its
  this value to be a constructor function that supports the parameter
  conventions of the Promise constructor.

As you can tell from this, Promise.reject expects to be called on a Promise constructor (either native promises or other compatible implementation). When treating Promise.reject as a first-class function like that, you're calling it on the global object, which is not a Promise constructor and therefore fails.1

If you need to use Promise.reject in this way, I'd recommend to bind it first:

```<code>var f = Promise.reject.bind(Promise);
f(3); // Promise {[[PromiseStatus]]: "rejected", [[PromiseValue]]: 3}
</code>```

1 I'm not exactly sure why the global object is not considered an object, though, since Promise.reject.call({ }) gives Uncaught TypeError: object is not a constructor.

Body:
Why can I do this:

> Promise.reject(3);
< Promise {[[PromiseStatus]]: "rejected", [[PromiseValue]]: 3}

But not this:

> var f = Promise.reject;
< undefined

> f(3)
< VM2366:1 Uncaught TypeError: PromiseReject called on non-object
    at reject (<anonymous>)
    at <anonymous>:1:1

Body:
The spec defines Promise.reject as follows (emphasis mine):

25.4.4.4 Promise.reject( r )

The reject function returns a new promise rejected with the passed
  argument.

Let C be the this value.

If Type(C) is not Object, throw a TypeError exception.

Let promiseCapability be ? NewPromiseCapability(C).

Perform ? Call(promiseCapability.[[Reject]], undefined, « r »).

Return promiseCapability.[[Promise]].

NOTE: The reject function expects its
  this value to be a constructor function that supports the parameter
  conventions of the Promise constructor.

As you can tell from this, Promise.reject expects to be called on a Promise constructor (either native promises or other compatible implementation). When treating Promise.reject as a first-class function like that, you're calling it on the global object, which is not a Promise constructor and therefore fails.1

If you need to use Promise.reject in this way, I'd recommend to bind it first:

var f = Promise.reject.bind(Promise);
f(3); // Promise {[[PromiseStatus]]: "rejected", [[PromiseValue]]: 3}

1 I'm not exactly sure why the global object is not considered an object, though, since Promise.reject.call({ }) gives Uncaught TypeError: object is not a constructor.


问:
Allowing Windows Server 2012 R2 access to directory on AIX 7.1
we have two AIX servers, Live and Test. On our live server, I am able to add an entry into smb.conf to allow a directory to be shared across a Windows network as shown in the extract below, displaying the ImportExport shared folder in Explorer:

```<code>[ImportExport]
        comment = Import Export directory
        path = /path/folder
        browseable = Yes
        hosts allow = <IP>
        guest ok = Yes
        force user = <user>
        forcegroup = pro4
        read only = No
        create mask = 0777
        directory mask = 0777
        dead time = 10
</code>```

However, adding a very similar configuration on our Test server, I cannot even get to the server from a Windows box, I get the "\ is not accessible..." message as if the server does not exist, or there are no shares.

Is there anything else I need to do to the local AIX folder to get this visible to Windows, or can you give me some ideas of what the pre-reqs are for this?

Sorry, I am not an AIX specialist, primarily a Windows house.

Thanks

答: Got this working now - Samba 3.2.0 was restricted to 14 chars or less for the share name. Reduced, restarted SAMBA and now OK. Thanks all</p>

Body:
we have two AIX servers, Live and Test. On our live server, I am able to add an entry into smb.conf to allow a directory to be shared across a Windows network as shown in the extract below, displaying the ImportExport shared folder in Explorer:

[ImportExport]
        comment = Import Export directory
        path = /path/folder
        browseable = Yes
        hosts allow = <IP>
        guest ok = Yes
        force user = <user>
        forcegroup = pro4
        read only = No
        create mask = 0777
        directory mask = 0777
        dead time = 10

However, adding a very similar configuration on our Test server, I cannot even get to the server from a Windows box, I get the "\ is not accessible..." message as if the server does not exist, or there are no shares.

Is there anything else I need to do to the local AIX folder to get this visible to Windows, or can you give me some ideas of what the pre-reqs are for this?

Sorry, I am not an AIX specialist, primarily a Windows house.

Thanks


问:
.NET Scheduling many operations: single timer vs one timer for operation
I am developing a Windows Service application, in .NET, which executes many functions (it is a WCF service host), and one of the targets is running scheduled tasks.

I chose to create a System.Threading.Timer for every operation, with a dueTime set to the next execution and no period to avoid reentrancy.

Every time the operation ends, it changes the dueTime to match the next scheduled execution.

Most of the operations are scheduled to run every minute, not all toghether but delayed by some seconds each other.

Now, after adding a number of operations, about 30, it seems that the timers start to be inaccurate, starting the operations many seconds late, or even minutes late.

I am running the operation logic directly in the callback method of the timer, so the running thread should be the same as the timer.

Should I create a Task to run the operation instead of running it in the callback method to improve accuracy?

Or should I use a single timer with a fixed (1 second) dueTime to check which operations need to be started?

I don't like this last option because it would be more difficult to handle reentrancy..

答:
We usually setup multiple timers to handle different actions within a single service. We set the intervals and start, stop the timer on the Service Start/Stop/Shutdown events (and have a variable indicating the status for each one, i.e. bool Stopped)
When the timer ticks over, we stop the timer, run the processing (which may take a while depending on the process, i.e. may take longer than the interval if its short.. (this code needs to be in a try--catch so it keeps going on errors)
After the code has processed, we check the Stopped variable and if its not stopped we start the timer again (this handles the reentrancy that you've mentioned and allows the code to stick to the interval as much as possible)
Timers are generally more accurate after about 100ms as far as I know, but should be close enough for what you want to do.

We have run this concept for years, and it hasn't let us down.

If you running these tasks as a sub-system of an ASP.NET app, you should also look at HangFire, which can handle background processing, eliminating the need for the windows service.

How accurate do the timers need to be? you could always use a single timer and run multiple processing threads at the same time? or queue the calls to some operations if less critical.


问:
d3.csv.parse only parses first line of csv string
I'd like to allow a user to populate a textbox with a csv string (sample shown below) and then parse with d3.csv.parse.

```<code>x,y,series,size
2,-0.083014839,Group 0,0.883928284
-9,0.355697349,Group 0,0.149154477
5,-0.256459661,Group 0,0.066308001
3,-0.243723214,Group 0,0.388138931
-7,0.776456119,Group 4,0.481110901
</code>```

When I grab the val() within the textbox it's only able to save the first row of the csv string to a variable in javascript and then errors out. How do I save the whole csv string to a variable so I can send to d3.csv.parse?

答:
This was happening with me. The problem was using the d3.csv.parse() in the same way I was using d3.csv(). For example:

d3.csv("data.csv", function(error, data) {
  //Do something with the data
}
```

<p>So, I tried to use <strong>d3.csv.parse</strong> like this:</p>

<pre class="lang-js prettyprint-override"><code>d3.csv.parse(variable_with_csv, function(data) {
  //Do something with the data
}
</code>```

But this is WRONG. The second parameter is an accessor not the call back with the data. The correct way to do what you want is simply get the data directly:

data = d3.csv.parse(variable_with_csv)
```

Body:
I'd like to allow a user to populate a textbox with a csv string (sample shown below) and then parse with d3.csv.parse.

x,y,series,size
2,-0.083014839,Group 0,0.883928284
-9,0.355697349,Group 0,0.149154477
5,-0.256459661,Group 0,0.066308001
3,-0.243723214,Group 0,0.388138931
-7,0.776456119,Group 4,0.481110901

When I grab the val() within the textbox it's only able to save the first row of the csv string to a variable in javascript and then errors out. How do I save the whole csv string to a variable so I can send to d3.csv.parse?

Body:
This was happening with me. The problem was using the d3.csv.parse() in the same way I was using d3.csv(). For example:

d3.csv("data.csv", function(error, data) {
  //Do something with the data
}

So, I tried to use d3.csv.parse like this:

d3.csv.parse(variable_with_csv, function(data) {
  //Do something with the data
}

But this is WRONG. The second parameter is an accessor not the call back with the data. The correct way to do what you want is simply get the data directly:

data = d3.csv.parse(variable_with_csv)


问:
Should DialogFragment be called through AsyncTask class?
I read many guides but I'm still confused.

Somewhere I read that the "activity flow" should not be interrupted by a DialogFragment, so you should call DialogFragment inside a AsyncTask Class inside the Activity Class.

In other guides I saw DialogFragment being called from the Activity Class without using AsyncTask.

So my question is: should DialogFragment be called only through AsyncTask class?

This is the way I did so far; the Activity class code:

```<code>public class LunchActivity extends AppCompatActivity  {
....
  public void callDialog(){
     class ShowInfoToUser extends AsyncTask<Bundle, Void, Bundle> {
        ...
        @Override
        protected Bundle doInBackground(Bundle... args) {
           ...
        }

        @Override
        protected void onPostExecute(Bundle resultBundle) {
            DialogFragment permissionDialogManager= permissionDialogManager.newInstance(messageBundle);
            permissionDialogManager.show(activity.getSupportFragmentManager(), "Permission Dialog");
        }
    }
}
</code>```

This is the class that extends DialogFragment:

```<code>public class PermissionDialogManager extends DialogFragment {

    public static PermissionDialogManager newInstance(Bundle bundle) {
        PermissionDialogManager frag = new PermissionDialogManager();
        frag.setArguments(bundle);
        return frag;
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        ...
    }
}
</code>```

Thank you

答: As the Dialog will interrupt the user, I see no reason to put it in an AsyncTask. The dialog is not supposed to take a huge amount of time to generate itself.</p>

Body:
I read many guides but I'm still confused.

Somewhere I read that the "activity flow" should not be interrupted by a DialogFragment, so you should call DialogFragment inside a AsyncTask Class inside the Activity Class.

In other guides I saw DialogFragment being called from the Activity Class without using AsyncTask.

So my question is: should DialogFragment be called only through AsyncTask class?

This is the way I did so far; the Activity class code:

public class LunchActivity extends AppCompatActivity  {
....
  public void callDialog(){
     class ShowInfoToUser extends AsyncTask<Bundle, Void, Bundle> {
        ...
        @Override
        protected Bundle doInBackground(Bundle... args) {
           ...
        }

        @Override
        protected void onPostExecute(Bundle resultBundle) {
            DialogFragment permissionDialogManager= permissionDialogManager.newInstance(messageBundle);
            permissionDialogManager.show(activity.getSupportFragmentManager(), "Permission Dialog");
        }
    }
}

This is the class that extends DialogFragment:

public class PermissionDialogManager extends DialogFragment {

    public static PermissionDialogManager newInstance(Bundle bundle) {
        PermissionDialogManager frag = new PermissionDialogManager();
        frag.setArguments(bundle);
        return frag;
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        ...
    }
}

Thank you


问:
Modifying SharePoint Alert Confirmation Email
I am adding search alert pro grammatically and when alert is added then system send notification email which tells user to your search alert added successfully , now i want to change the content of this notification email  or disabled to send this email.

Email Content:

'System Account' has subscribed you for alert 'My News Alert' on '' .

You will receive alerts in e-mail. The timing and criteria for the alerts depend on the settings entered when the alert was added.

I have tried looking at alerttemplates.xml but that ONLY modify the email alerts, NOT the alert confirmation email.

Btw, I am using SharePoint 2007.

How can I do this?

Thanks

答:
you can use newAlert.Update(false); for more details refer link below

SharePoint Alert customization

ContentLicense: CC BY-SA 2.5


问:
How to read from a .properties file using batch script
I have a requirement where i'd like to read values from a .properties file

my properties file test.properties content

```<code>file=jaguar8
extension=txt
path=c:\Program Files\AC
</code>```

From the above file I need to fetch jaguar or anything after =

Please help me. Thanks

答:
I know this is ancient post but I would like to expand on toschug's great answer.

If the path in the .properties file would be defined as %~dp0 or any other variable that needs to be expanded first before using it, I recommend doing it the following way:

In the .properties file:

```<code>path=%~dp0
</code>```

In the batch file you can then use it the following way (the code is to be used between the two for(s) defining one <=> cleanup one):

```<code>if "!test.path!" NEQ "" (
   echo Not expanded path: !test.path!
   call :expand !test.path! test.path
)

echo test.path expanded: !test.path!
pause

:expand
SET "%~2=%~1"
GOTO :EOF
</code>```

Don't forget to use (at the start of the batch file):

```<code>SETLOCAL ENABLEDELAYEDEXPANSION
</code>```

Body:
I have a requirement where i'd like to read values from a .properties file

my properties file test.properties content

file=jaguar8
extension=txt
path=c:\Program Files\AC

From the above file I need to fetch jaguar or anything after =

Please help me. Thanks

Body:
I know this is ancient post but I would like to expand on toschug's great answer.

If the path in the .properties file would be defined as %~dp0 or any other variable that needs to be expanded first before using it, I recommend doing it the following way:

In the .properties file:

path=%~dp0

In the batch file you can then use it the following way (the code is to be used between the two for(s) defining one <=> cleanup one):

if "!test.path!" NEQ "" (
   echo Not expanded path: !test.path!
   call :expand !test.path! test.path
)

echo test.path expanded: !test.path!
pause

:expand
SET "%~2=%~1"
GOTO :EOF

Don't forget to use (at the start of the batch file):

SETLOCAL ENABLEDELAYEDEXPANSION


问:
How to read message form activemq in camel route
Im trying to read message from a queue using camel route and send it to a bean of message listener, but it ends with exception. am i doing some thing wrong.
I have serialized object in activemq

```<code> <bean class="com.herman.cxf.incident.ReportIncidentRequestConsumer"
            id="requestConsumer" />
        <camelContext id="camelContext-32616f27-d786-4ed8-9f75-2d208cd14b40"
            trace="false" xmlns="http://camel.apache.org/schema/blueprint">
            <route id="report_amq">
                <from uri="activemq:queue:INCIDENT_REQUEST" />
                <to uri="bean:requestConsumer" />
            </route>
        </camelContext>
</code>```

Message Listner Class:

```<code>public class ReportIncidentRequestConsumer implements MessageListener {

        Logger _log = Logger.getLogger(ReportIncidentRequestConsumer.class);

        @Override
        public void onMessage(Message arg0) {
            _log.info("================== IM HERE IN REQUEST CONSUMER ===============");
        }

    }
</code>```

Excpetion:
Caused by: javax.jms.JMSException: Failed to build body from content. Serializable class not available to broker. Reason: java.lang.ClassNotFoundException: Forbidden class org.apache.cxf.message.MessageContentsList! This class is not trusted to be serialized as ObjectMessage payload.

答:
When using camel, you don't need a MessageListener to process a message.

You can use Processor  to do something to the message.

Firstly write a class which implements processor like this...

```<code>public class MyProcessor implements Processor {
  public void process(Exchange exchange) throws Exception {
    // do something...
  }
}
</code>```

Then you can then easily use this inside a route by declaring the bean in Spring, say via the XML (or registering it in JNDI if that is your Registry)

```<code><bean id="myProcessor" class="com.acme.MyProcessor"/>
</code>```

And then in Camel you can do

```<code>from("activemq:myQueue").to("myProcessor");
</code>```

Body:
Im trying to read message from a queue using camel route and send it to a bean of message listener, but it ends with exception. am i doing some thing wrong.
I have serialized object in activemq

 <bean class="com.herman.cxf.incident.ReportIncidentRequestConsumer"
            id="requestConsumer" />
        <camelContext id="camelContext-32616f27-d786-4ed8-9f75-2d208cd14b40"
            trace="false" xmlns="http://camel.apache.org/schema/blueprint">
            <route id="report_amq">
                <from uri="activemq:queue:INCIDENT_REQUEST" />
                <to uri="bean:requestConsumer" />
            </route>
        </camelContext>

Message Listner Class:

public class ReportIncidentRequestConsumer implements MessageListener {

        Logger _log = Logger.getLogger(ReportIncidentRequestConsumer.class);

        @Override
        public void onMessage(Message arg0) {
            _log.info("================== IM HERE IN REQUEST CONSUMER ===============");
        }

    }

Excpetion:
Caused by: javax.jms.JMSException: Failed to build body from content. Serializable class not available to broker. Reason: java.lang.ClassNotFoundException: Forbidden class org.apache.cxf.message.MessageContentsList! This class is not trusted to be serialized as ObjectMessage payload.

Body:
When using camel, you don't need a MessageListener to process a message.

You can use Processor  to do something to the message.

Firstly write a class which implements processor like this...

public class MyProcessor implements Processor {
  public void process(Exchange exchange) throws Exception {
    // do something...
  }
}

Then you can then easily use this inside a route by declaring the bean in Spring, say via the XML (or registering it in JNDI if that is your Registry)

<bean id="myProcessor" class="com.acme.MyProcessor"/>

And then in Camel you can do

from("activemq:myQueue").to("myProcessor");


问:
AngularJS compare dates wrong
I just wrote this code.
It should mark the rows that their dates column has in the past.

This is the code:

```<code>        <tr ng-repeat="row in records | orderBy: sortType : sortReverse" ng-class="{past_date:(date | date:'y M d') > (row.oddate | date:'y M d')}">
            <td>{{ $index +1 }}</td>
            <td>{{row.pname + " " + row.sname}}</td>
            <td>{{row.areaname}}</td>
            <td>{{row.oddate}}</td>
            <td>{{row.odtime}}</td>
            <td>{{row.cnt}}</td>
        </tr>
</code>```

my app has:

```<code>$scope.date = $filter('date')(Date.now(), 'yyyy-MM-dd');//new Date();
</code>```

every thing works just fine (the past rows was marked) but some other rows marked too! (before 05/06/2017 marked - Good, 06/06/2017 - 08/06/2017 not marked - Good, 11/06/2017-29/06/2017 marked - Problem!, 02/07/2017 and above not marked - Good).

I check and the all of the dates are fine.

FIDDLE

What can be the problem??

Thanks!

答:
Issue happens because of string compare "5" > "11"

You are casting dates to y M d, so "2017 5 1" will be evaluated to be greater than "2017 11 1"

Solution: use zero padding format yMMdd

Title: AngularJS compare dates wrong

Body:
I just wrote this code.
It should mark the rows that their dates column has in the past.

This is the code:

 (row.oddate | date:'y M d')}">
            {{ $index +1 }}
            {{row.pname + " " + row.sname}}
            {{row.areaname}}
            {{row.oddate}}
            {{row.odtime}}
            {{row.cnt}}

my app has:

$scope.date = $filter('date')(Date.now(), 'yyyy-MM-dd');//new Date();

every thing works just fine (the past rows was marked) but some other rows marked too! (before 05/06/2017 marked - Good, 06/06/2017 - 08/06/2017 not marked - Good, 11/06/2017-29/06/2017 marked - Problem!, 02/07/2017 and above not marked - Good).

I check and the all of the dates are fine.

FIDDLE

What can be the problem??

Thanks!


问:
Could not open modal window dynamically using Angular.js/Jquery
I have an issue. I am trying to open one pop-up window dynamically using Angular.js and Jquery but its not opening. I am explaining my code below.

```<code><input type='button' class='btn btn-xs btn-green' value='View' data-toggle="modal" data-target="#" ng-click="viewSearchDetails(133);">
<div class="modal fade" id="viewdetailssec" tabindex="-1" role="dialog" aria-labelledby="viewexamplelabel" aria-hidden="true" ng-repeat="ind in indUserDetails" ng-if="indUserDetails.length >0">
 <div class="modal-dialog fyndspacemodalsec" role="document">
<div class="modal-content">
 <div class="modal-header">
<h5 class="modal-title pull-left" id="viewexamplelabel">View Details</h5>
</div>
</div>
</div>
</div>
</code>```

My controller side code is given below.

```<code>$scope.viewSearchDetails=function(userid){
    $scope.indUserDetails=[];
    angular.forEach($scope.allUserInfo,function(obj){
      if(obj.user_id==userid){
        $scope.indUserDetails=obj;
        $("#viewdetailssec").modal();
      }
    })
  }
</code>```

Here I need to open the pop up window while if statement will execute but its not opening at all. Please help me to resolve this issue.

答:
Few things to see here:

you need to push the selected object in the array as
$scope.indUserDetails.push(obj)

Make sure you have all the dependencies set for bootstrap js and css

Also, you can set the data-target="#viewdetailssec" in the HTML itself for the modal reference.

function MyCtrl($scope) {

  $scope.allUserInfo = [{
    user_id: 131,
    name: "xyz"
  }, {
    user_id: 132,
    name: "xyz"
  }, {
    user_id: 133,
    name: "xyz"
  }, {
    user_id: 134,
    name: "xyz"
  }]

  $scope.viewSearchDetails = function(userid) {
    $scope.indUserDetails = [];
    angular.forEach($scope.allUserInfo, function(obj) {
      if (obj.user_id == userid) {
        $scope.indUserDetails.push(obj);
      }
    })
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

<body ng-app ng-controller="MyCtrl">
  <input type='button' class='btn btn-xs btn-green' value='View' data-toggle="modal" data-target="#viewdetailssec" ng-click="viewSearchDetails(133);">

  <div class="modal fade" id="viewdetailssec" role="dialog" ng-if="indUserDetails.length >0">
    <div class="modal-dialog">
      <!-- Modal content-->
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal">×</button>
          <h4 class="modal-title"></h4>
        </div>
        <div class="modal-body" ng-repeat="ind in indUserDetails">
          <p>{{ind}}</p>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        </div>
      </div>

    </div>
  </div>
</body></code>```

Body:
I have an issue. I am trying to open one pop-up window dynamically using Angular.js and Jquery but its not opening. I am explaining my code below.

<input type='button' class='btn btn-xs btn-green' value='View' data-toggle="modal" data-target="#" ng-click="viewSearchDetails(133);">

0">

View Details

My controller side code is given below.

$scope.viewSearchDetails=function(userid){
    $scope.indUserDetails=[];
    angular.forEach($scope.allUserInfo,function(obj){
      if(obj.user_id==userid){
        $scope.indUserDetails=obj;
        $("#viewdetailssec").modal();
      }
    })
  }

Here I need to open the pop up window while if statement will execute but its not opening at all. Please help me to resolve this issue.

Body:
Few things to see here:

you need to push the selected object in the array as
$scope.indUserDetails.push(obj)

Make sure you have all the dependencies set for bootstrap js and css

Also, you can set the data-target="#viewdetailssec" in the HTML itself for the modal reference.

function MyCtrl($scope) {

  $scope.allUserInfo = [{
    user_id: 131,
    name: "xyz"
  }, {
    user_id: 132,
    name: "xyz"
  }, {
    user_id: 133,
    name: "xyz"
  }, {
    user_id: 134,
    name: "xyz"
  }]

  $scope.viewSearchDetails = function(userid) {
    $scope.indUserDetails = [];
    angular.forEach($scope.allUserInfo, function(obj) {
      if (obj.user_id == userid) {
        $scope.indUserDetails.push(obj);
      }
    })
  }
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

<body ng-app ng-controller="MyCtrl">
  <input type='button' class='btn btn-xs btn-green' value='View' data-toggle="modal" data-target="#viewdetailssec" ng-click="viewSearchDetails(133);">

  <div class="modal fade" id="viewdetailssec" role="dialog" ng-if="indUserDetails.length >0">
    <div class="modal-dialog">
      <!-- Modal content-->
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal">&times;</button>
          <h4 class="modal-title"></h4>
        </div>
        <div class="modal-body" ng-repeat="ind in indUserDetails">
          <p>{{ind}}</p>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        </div>
      </div>

    </div>
  </div>
</body>


问:
iphone - stuff inside alertview
I have a part on my app that I show the users, the files they have created and have stored inside the app's directory. I want to allow the users to rename the files.

I am wondering of doing this:

The user selects a file

The user taps on the RENAME button.

An alertview pops showing the old name and having a textview where the user can type the new name.

My question is: is this blessed by Apple? This sounds like a hack to the alertview.

Will the app be approved?

I googled around and I saw mixed opinions about that.

thanks

答: You could either subclass UIAletView and add your own initWithTitle:message:...etc. method, as outlined in this tutorial, or use the undocumented [alert addTextFieldWithValue:@"" label:nil]; method, which is easier but may cause Apple to reject your app.

Title: iphone - stuff inside alertview


答:
I believe that this is because reject is defined as a static function on the Promise object.

As such, you cannot call it as you have above, as it is called directly on the class and not on an instance of the class.

More detail about static functions and when they can and cannot be called here:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/static

You could wrap it in a function:

```<code>function promiseReject(x) {
   return Promise.reject(x);
}

var f = promiseReject;

var out = f(3);
</code>```

Title: How to treat `Promise.reject` as a first-class function?

Body:
I believe that this is because reject is defined as a static function on the Promise object.

As such, you cannot call it as you have above, as it is called directly on the class and not on an instance of the class.

More detail about static functions and when they can and cannot be called here:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/static

You could wrap it in a function:

function promiseReject(x) {
   return Promise.reject(x);
}

var f = promiseReject;

var out = f(3);


问:
Priority of primary key in multiple column index?
I'm new to sql and now working with MySQL.
I'm going through the concept of indexes and I'm not sure what would happen in the following case:

```<code>CREATE TABLE test (
id         INT NOT NULL,
last_name  CHAR(30) NOT NULL,
first_name CHAR(30) NOT NULL,
PRIMARY KEY (id),
INDEX name (last_name,first_name)
);
</code>```

I have read that here, last_name or (last_name,first_name) can be used for lookup where as first_name cannot be used for lookup directly (not a leftmost index).

I have also read that PRIMARY KEY and UNIQUE KEY are indexed automatically. So, in my case where the id index comes? Don't it come as a leftmost prefix.

```<code>select * from test
where id=xxx and last_name==xxxx
</code>```

will this call for a look up or searches the entire database?

答:
First, your query is redundant.  The id comparison is sufficient.

The optimizer is going to recognize that two indexes can be used for the query.  I'm pretty sure that MySQL will choose the primary key index, because it is unique and clustered.  Hence, it is obviously the correct one.

If neither index is unique or a primary key, then MySQL will resort to statistics about the indexes (or arbitrarily choosing one of them).  You can read about index statistics in the documentation.

Body:
I'm new to sql and now working with MySQL.
I'm going through the concept of indexes and I'm not sure what would happen in the following case:

CREATE TABLE test (
id         INT NOT NULL,
last_name  CHAR(30) NOT NULL,
first_name CHAR(30) NOT NULL,
PRIMARY KEY (id),
INDEX name (last_name,first_name)
);

I have read that here, last_name or (last_name,first_name) can be used for lookup where as first_name cannot be used for lookup directly (not a leftmost index).

I have also read that PRIMARY KEY and UNIQUE KEY are indexed automatically. So, in my case where the id index comes? Don't it come as a leftmost prefix.

select * from test
where id=xxx and last_name==xxxx

will this call for a look up or searches the entire database?


问:
How to add click listener in List View, If ListView have already button in xml?
How to add click listener in List View, If ListView have already button in xml? I want to click on button for open New Activity.

Here is my code.
WashDetail.xml

```<code>      <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:gravity="center"
            android:orientation="horizontal">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textColor="#000"
                android:text="Malaber Hill" />

            <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="10dp"
                android:layout_marginLeft="16dp"
                android:layout_marginEnd="20dp"
                android:text="Get Details"
                android:id="@+id/gardetails"
                android:textColor="#FFFFFF"
                android:textSize="20dp"
                android:textStyle="normal"

                />
 </LinearLayout>
</code>```

activity_wash_detail

```<code>    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">
       <ListView
         android:layout_width="fill_parent"
         android:id="@+id/ls"
         android:layout_below="@+id/headerlay"
         android:focusable="true"
         android:clickable="true"
         android:duplicateParentState="true"
         android:focusableInTouchMode="true"
         android:layout_height="fill_parent">
        </ListView>
 </LinearLayout>
</code>```

WashDetailActivity.java

```<code>protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_wash_detail);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    listView = (ListView) findViewById(ls);
    GetDetails=(Button)findViewById(R.id.gardetails);
    Models = new ArrayList<>();
    Models.add(new WashDetailing(R.drawable.spl, "PP AUTOMATIVES", R.drawable.mahindra, "Authorized"));
    adapter = new WashDetailingAdapter(Models, getApplicationContext());

    listView.setAdapter(adapter);

    listView.setClickable(false);

     gardetails.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v)
         {
            Intent intent= new         Intent(getApplicationContext(),GarageDetailActivity.class);
            startActivity(intent);

        }
    });
}
</code>```

答:
set this click listener in getView method of your adapter class

```<code> public View getView(final int position, View convertView, ViewGroup parent) {

       ViewHolder holder = null;

        // Inflater for custom layout
        LayoutInflater inflater = (LayoutInflater)dContext
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        if (convertView == null) {
            convertView = inflater.inflate(R.layout.customer_list_layout, parent, false);

           holder.gardetails = convertView.findViewById(R.id.gardetails);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        holder.gardetails.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
 Intent intent= new                   Intent(getApplicationContext(),GarageDetailActivity.class);
            dContext.startActivity(intent)
            }
        });
        return convertView;
    }
</code>```

and here is your ViewHolder class

private class ViewHolder {

```<code>Button gardetails;
</code>```

}

Body:
How to add click listener in List View, If ListView have already button in xml? I want to click on button for open New Activity.

Here is my code.
WashDetail.xml

      <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:gravity="center"
            android:orientation="horizontal">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textColor="#000"
                android:text="Malaber Hill" />

            <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="10dp"
                android:layout_marginLeft="16dp"
                android:layout_marginEnd="20dp"
                android:text="Get Details"
                android:id="@+id/gardetails"
                android:textColor="#FFFFFF"
                android:textSize="20dp"
                android:textStyle="normal"

                />
 </LinearLayout>

activity_wash_detail

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">
       <ListView
         android:layout_width="fill_parent"
         android:id="@+id/ls"
         android:layout_below="@+id/headerlay"
         android:focusable="true"
         android:clickable="true"
         android:duplicateParentState="true"
         android:focusableInTouchMode="true"
         android:layout_height="fill_parent">
        </ListView>
 </LinearLayout>

WashDetailActivity.java

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_wash_detail);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    listView = (ListView) findViewById(ls);
    GetDetails=(Button)findViewById(R.id.gardetails);
    Models = new ArrayList<>();
    Models.add(new WashDetailing(R.drawable.spl, "PP AUTOMATIVES", R.drawable.mahindra, "Authorized"));
    adapter = new WashDetailingAdapter(Models, getApplicationContext());

    listView.setAdapter(adapter);

    listView.setClickable(false);

     gardetails.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v)
         {
            Intent intent= new         Intent(getApplicationContext(),GarageDetailActivity.class);
            startActivity(intent);

        }
    });
}

Body:
set this click listener in getView method of your adapter class

 public View getView(final int position, View convertView, ViewGroup parent) {

       ViewHolder holder = null;

        // Inflater for custom layout
        LayoutInflater inflater = (LayoutInflater)dContext
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        if (convertView == null) {
            convertView = inflater.inflate(R.layout.customer_list_layout, parent, false);

           holder.gardetails = convertView.findViewById(R.id.gardetails);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        holder.gardetails.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
 Intent intent= new                   Intent(getApplicationContext(),GarageDetailActivity.class);
            dContext.startActivity(intent)
            }
        });
        return convertView;
    }

and here is your ViewHolder class

private class ViewHolder {

Button gardetails;

}


问:
npm copy and compile LESS files using cpx
I'm trying to copy and compile / transform LESS files and ES6 files to another directory using npm tools and packages.

This is my basic structure:

```<code>-src
  -components
    -component1
      component1.js // es6 code
      styles.less
    -component2
      component2.js // es6 code
      styles.less
    -component3
      component3.js  // es6 code
      styles.less
</code>```

And this is the desired new directory structure:

```<code>-lib
  -component1
    component1.js // es5 code
    styles.css
  -component2
    component2.js // es5 code
    styles.css
  -component3
    component3.js  // es5 code
    styles.css
</code>```

For the es6 transpile I'm using babel and it works great:

```<code>"build:js": "cross-env NODE_ENV=production babel ./src/components --out-dir ./lib --ignore spec.js"
</code>```

But i struggle with the LESS files. I know i can use cpx to copy files and keep the structure:

```<code>"build:less": "cpx \"./src/components/**/*.less\" ./lib"
</code>```

But i want to copy them while processing each of them and compile it from LESS to CSS.

There is a -t argument for a module transformation of each file passed through the pipeline but i can't find a proper module to pass them through.

I tried lessc and lessify but it doesn't seem like a good fit.

```<code>"build:less": "cpx \"./src/components/**/*.less\" ./lib -t [less_compiler_here?]"
</code>```

I don't mind using webpack or any other pattern to achieve this.

答:
Answering my own question here

I failed to find a fit solution to my situation. After testing a lot of npm packages i found out that each package provides a small part of the solution to my challenge, I decided to write my own solution.

 lessc-glob

Basically it takes a glob and copy the structure from source to target (using cpx) but it passes each file through a less transform stream. Of course it changes the file extension to .css in the end.
This is a very tailored solution to my exact challenge but maybe someone will find it useful.

Feel free to make it better if you want to.

Body:
I'm trying to copy and compile / transform LESS files and ES6 files to another directory using npm tools and packages.

This is my basic structure:

-src
  -components
    -component1
      component1.js // es6 code
      styles.less
    -component2
      component2.js // es6 code
      styles.less
    -component3
      component3.js  // es6 code
      styles.less

And this is the desired new directory structure:

-lib
  -component1
    component1.js // es5 code
    styles.css
  -component2
    component2.js // es5 code
    styles.css
  -component3
    component3.js  // es5 code
    styles.css

For the es6 transpile I'm using babel and it works great:

"build:js": "cross-env NODE_ENV=production babel ./src/components --out-dir ./lib --ignore spec.js"

But i struggle with the LESS files. I know i can use cpx to copy files and keep the structure:

"build:less": "cpx \"./src/components/**/*.less\" ./lib"

But i want to copy them while processing each of them and compile it from LESS to CSS.

There is a -t argument for a module transformation of each file passed through the pipeline but i can't find a proper module to pass them through.

I tried lessc and lessify but it doesn't seem like a good fit.

"build:less": "cpx \"./src/components/**/*.less\" ./lib -t [less_compiler_here?]"

I don't mind using webpack or any other pattern to achieve this.


问:
How to stress test a gwt app
Did someone have succeed stressing a GWT app?

Any recommended tool?

答: We are successfully using http://loadui.org to test our GWT app. To test the GUI we input directly JSON HTTP requests to our RPC servlet. It's also useful to test SOAP/REST web services.</p>

Title: How to stress test a gwt app


问:
How to count duplicate elements in ArrayList?
I need to separate and count how many values in arraylist are the same and print them according to the number of occurrences.

I've got an arraylist called digits :

```<code> [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765]
</code>```

I created a method which separates each value and saves it to a new array.

```<code>public static ArrayList<Integer> myNumbers(int z) {

    ArrayList<Integer> digits = new ArrayList<Integer>();
    String number = String.valueOf(z);
    for (int a = 0; a < number.length(); a++) {
        int j = Character.digit(number.charAt(a), 10);
        digits.add(j);
    }
    return digits;

}
</code>```

After this I've got a new array called numbers. I'm using sort on this array

```<code>Collections.sort(numbers);
</code>```

and my ArrayList looks like this:

```<code>[0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 6, 6, 6, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 9, 9, 9]
</code>```

It has:

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

I need to print out the string of numbers depend on how many are they
So it suppose to look like this :
1354678290

答: use Collections.frequency method to count the duplicates

Body:
I need to separate and count how many values in arraylist are the same and print them according to the number of occurrences.

I've got an arraylist called digits :

 [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765]

I created a method which separates each value and saves it to a new array.

public static ArrayList<Integer> myNumbers(int z) {

    ArrayList<Integer> digits = new ArrayList<Integer>();
    String number = String.valueOf(z);
    for (int a = 0; a < number.length(); a++) {
        int j = Character.digit(number.charAt(a), 10);
        digits.add(j);
    }
    return digits;

}

After this I've got a new array called numbers. I'm using sort on this array

Collections.sort(numbers);

and my ArrayList looks like this:

[0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 6, 6, 6, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 9, 9, 9]

It has:

2 times 0;
9 times 1;
4 times 2;
6 times 3;
5 times 4;
6 times 5;
5 times 6;
5 times 7;
5 times 8;
3 times 9;

I need to print out the string of numbers depend on how many are they
So it suppose to look like this :
1354678290


问:
Does TCP ensure packet is received by sequence that server send it
I'm working on an gameServer that communicate with game client, but wonder whether the packet server send to client remain sequence when client received it ?

like server sends packets A,B,C
but the client received B,A,C ?

I have read the great blog http://packetlife.net/blog/2010/jun/7/understanding-tcp-sequence-acknowledgment-numbers/
It seems that every packet send by the server has an ack corresponding by client, but it does not say why the packet received by client has the same sequence with server

答:
It's worth reading TCP's RFC, particularly section 1.5 (Operation), which explains the process. In part, it says:

The TCP must recover from data that is damaged, lost, duplicated, or delivered out of order by the internet communication system.  This is achieved by assigning a sequence number to each octet transmitted, and requiring a positive acknowledgment (ACK) from the receiving TCP.  If the ACK is not received within a timeout interval, the data is retransmitted.  At the receiver, the sequence numbers are used to correctly order segments that may be received out of order and to eliminate duplicates.  Damage is handled by adding a checksum to each segment transmitted, checking it at the receiver, and discarding damaged segments.

I don't see where it's ever made explicit, but since the acknowledgement (as described in section 2.6) describes the next expected packet, the receiving TCP implementation is only ever acknowledging consecutive sequences of packets from the beginning. That is, if you never receive the first packet, you never send an acknowledgement, even if you've received all other packets in the message; if you've received 1, 2, 3, 5, and 6, you only acknowledge 1-3.

For completeness, I'd also direct your attention to section 2.6, again, after it describes the above-quoted section in more detail:

An acknowledgment by TCP does not guarantee that the data has been delivered to the end user, but only that the receiving TCP has taken the responsibility to do so.

So, TCP ensures the order of packets, unless the application doesn't receive them. That exception probably wouldn't be common, except for cases where the application is unavailable, but it does mean that an application shouldn't assume that a successful send is equivalent to a successful reception. It probably is, for a variety of reasons, but it's explicitly outside of the protocol's scope.


问:
Apple Mach -O Linker command failed

After updating my POD install, Xcode sprouted a new issue:

答:
Following steps helped me to get rid of this problem:

Go to project path and remove Pods folder and Podfile.lock file.

Reinstall pods again using "pod install" command.

Open xcworkspace and clean it before running.

Hope it will save someone's time like it did for me.

Title: Apple Mach -O Linker command failed


问:
Array base address pointer
Given the following code what is the difference between ptr and ptr2? because size of v is 20 whereas size of &v[0] is 4. Why does this even work? Why not a third pointer like ptr* = &v. All of these have the same base address but what is the difference between first... I'm confused. And it gets even worse when using 2d arrays. Thank you for your help!</p>

```<code>#include <iostream>
using namespace std;

int main(void)
{
    int v[5] = { 1, 2, 3, 4, 5 };
    int *ptr = v;
    int *ptr2 = &v[0];

    cout << sizeof(v) << endl << sizeof(&v[0]) << endl;
    cout << v << endl << &v << endl << &v[0];
    system("pause");
    return 0;
}
</code>```

答: In the context of int *ptr = v;, the array v decays to &v[0].  In the context of sizeof(v), it's still an array.

Title: Array base address pointer

Body:
Given the following code what is the difference between ptr and ptr2? because size of v is 20 whereas size of &v[0] is 4. Why does this even work? Why not a third pointer like ptr* = &v. All of these have the same base address but what is the difference between first... I'm confused. And it gets even worse when using 2d arrays. Thank you for your help!

#include <iostream>
using namespace std;

int main(void)
{
    int v[5] = { 1, 2, 3, 4, 5 };
    int *ptr = v;
    int *ptr2 = &v[0];

    cout << sizeof(v) << endl << sizeof(&v[0]) << endl;
    cout << v << endl << &v << endl << &v[0];
    system("pause");
    return 0;
}


问:
Back navigation button not showing up
I cloned the code using

ionic start myProjectName tutorial

and changed the project according to ionic 3 , now , there is a file list.html , it has a button at header which opens side menu. i wanted to have a back button over there ,and removed the code for side menu opening. Expected that back button would automatically show up , but it did not happen, instead it shows header without any button with just title written.

in this project , you will find list.html , and i have altered it as follows:

```<code>  <ion-header>
  <ion-navbar>
    <ion-title>My First List</ion-title>
  </ion-navbar>
</ion-header>
<ion-content>
  <ion-list>
    <button ion-item *ngFor="let item of items" (click)="itemTapped($event, item)">
      <ion-icon name="{{item.icon}}" item-left></ion-icon>
      {{item.title}}
      <div class="item-note" item-right>
        {{item.note}}
      </div>
    </button>
  </ion-list>
</ion-content>
</code>```

It just have a title , no back navigation button which could take me to root page

答:
You can add below code in app.component.ts</p>

```<code>itemTapped(item) {
    // close the menu when clicking a link from the menu
    this.menu.close();
    // navigate to the new page if it is not the current page
    this.nav.push(page.component);
 }
</code>```

Title: Back navigation button not showing up

Body:
I cloned the code using

ionic start myProjectName tutorial

and changed the project according to ionic 3 , now , there is a file list.html , it has a button at header which opens side menu. i wanted to have a back button over there ,and removed the code for side menu opening. Expected that back button would automatically show up , but it did not happen, instead it shows header without any button with just title written.

in this project , you will find list.html , and i have altered it as follows:

  <ion-header>
  <ion-navbar>
    <ion-title>My First List</ion-title>
  </ion-navbar>
</ion-header>
<ion-content>
  <ion-list>
    <button ion-item *ngFor="let item of items" (click)="itemTapped($event, item)">
      <ion-icon name="{{item.icon}}" item-left></ion-icon>
      {{item.title}}

        {{item.note}}

    </button>
  </ion-list>
</ion-content>

It just have a title , no back navigation button which could take me to root page

Body:
You can add below code in app.component.ts

itemTapped(item) {
    // close the menu when clicking a link from the menu
    this.menu.close();
    // navigate to the new page if it is not the current page
    this.nav.push(page.component);
 }


问:
How nodes work in ElasticSearch Cluster
I have a cluster of 4 nodes.

Node 1:
  node.master: true
  node.data: true
Node 2:
  node.master: true
  node.data: true
Node 3:
  node.master: true
  node.data: true
Node 4:
  node.master: false
  node.data: false

and
discovery.zen.minimum_master_nodes: 2.

Now, as per my understanding, there will be single master elected for the cluster and the master decides where and how to store the incoming data.

Say suppose, Node 2: goes down and never comes back. The cluster will still be up and running as reelection takes place when  Node 2: goes down.

But what happens to the data which was stored in Node 2:. Can any one please explain me the flow here.

答:
If node 2 goes down and never come back means you lost the data forever, unless you have replica configured.

If you have one replica for each shard, then you will have extra copy of each shard in different node.

So when node 2 goes down, the node 2 data will server from replica server from node 2 or node 1.

Hope it helps!

Title: How nodes work in ElasticSearch Cluster


问:
How to center GridView correctly?
I have been trying and trying and no such luck. I have lucked at all other answers on here as well related to centering GridView and also no luck. This is my GridView xml:

```<code><GridView
        android:id="@+id/calendar_grid"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:numColumns="7"
        android:columnWidth="40dp"
        android:verticalSpacing="1dp"
        android:horizontalSpacing="1dp"
        android:paddingTop="2dp"
        android:stretchMode="columnWidth"
        android:layout_gravity="right"
        android:gravity="right"
        android:background="#696969" ></GridView>
</code>```

I have tried every combination I can think of, but not much has worked. At least its not consistent between devices. This is an image of what it always does.

As you can see on the right side of the GridView, there is spacing. I try to constantly change that, and it almost never works. Using android:stretchMode does change it, but it messes up the spacing I have between the cells, so thats not working. Using Gravity also fails as you can see. I've tried all the other values for it and it still changes nothing. It's stuck to the left. I also find it weird that trying to change the size of android:columnWidth from anything under 40 it does nothing either. And when I increase 40 to 45, it also changes nothing. But changing it to 50 makes the space on the right go away. But when putting it on my phone, the spacing is there! I skipped this like 2 weeks ago to continue working on other stuff but it looks like I have yet to solve this issue or even understand why nothing I try works.

If it helps anyone help me out here I can also provide the xml for what makes the cells. But I am not sure if it matters. But here it is:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <TextView
        android:id="@+id/day_num"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:textSize="10dp"
        android:background="#000000"
        android:height="35dp"
        android:gravity="center_vertical|center_horizontal" />

</LinearLayout>
</code>```

If it helps, the GridView's parent is a LinearLayout with this:

```<code><LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:layout_weight="0"
    android:gravity="center" >
</code>```

There is also a sibling with a weight of 1, but I don't think that should be effecting is as the weight of 0 makes that part set its space first.

EDIT:

So I have kept playing with it, very annoyed, especially since not that many people seem to have this issue, but it looks like no matter how small I make the columnWidth, the GridView barely gets any smaller. In fact, that same gap you see is what it stays at until I go to 50dp. But when I go in portrait mode the gap reappears, so I raise it up to 90dp (I tried under that, didn't change anything), and it goes away. Weird thing is the GridView doesn't change besides the filling of the gap. So I could make it 200dp, and it would look perfect on my screen dimen, and any other smaller screen. Once I go to a tablet, I suspect I would need to increase that more, but the point is, this is weird behavior. Has anyone encountered this?

答:
```<code>There is more specific method to do this. You can define custom layout. And add TextView as the element. Then apply the properties what you want. To center make gravity = center like wise. Then apply that layout as the layout for your grid view.

Ex :
Sample layout name : myCellitemlayout.xml
<TextView>
      android:id="@+id/text_id"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:gravity="center"
</TextView>

Now add this to your gridView adapter.
Ex: GridView

ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                R.id.myCellitemlayout, numbers);

gridView.setAdapter(adapter);
</code>```

Title: How to center GridView correctly?

Body:
I have been trying and trying and no such luck. I have lucked at all other answers on here as well related to centering GridView and also no luck. This is my GridView xml:

<GridView
        android:id="@+id/calendar_grid"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:numColumns="7"
        android:columnWidth="40dp"
        android:verticalSpacing="1dp"
        android:horizontalSpacing="1dp"
        android:paddingTop="2dp"
        android:stretchMode="columnWidth"
        android:layout_gravity="right"
        android:gravity="right"
        android:background="#696969" ></GridView>

I have tried every combination I can think of, but not much has worked. At least its not consistent between devices. This is an image of what it always does.

As you can see on the right side of the GridView, there is spacing. I try to constantly change that, and it almost never works. Using android:stretchMode does change it, but it messes up the spacing I have between the cells, so thats not working. Using Gravity also fails as you can see. I've tried all the other values for it and it still changes nothing. It's stuck to the left. I also find it weird that trying to change the size of android:columnWidth from anything under 40 it does nothing either. And when I increase 40 to 45, it also changes nothing. But changing it to 50 makes the space on the right go away. But when putting it on my phone, the spacing is there! I skipped this like 2 weeks ago to continue working on other stuff but it looks like I have yet to solve this issue or even understand why nothing I try works.

If it helps anyone help me out here I can also provide the xml for what makes the cells. But I am not sure if it matters. But here it is:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <TextView
        android:id="@+id/day_num"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:textSize="10dp"
        android:background="#000000"
        android:height="35dp"
        android:gravity="center_vertical|center_horizontal" />

</LinearLayout>

If it helps, the GridView's parent is a LinearLayout with this:

<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:layout_weight="0"
    android:gravity="center" >

There is also a sibling with a weight of 1, but I don't think that should be effecting is as the weight of 0 makes that part set its space first.

EDIT:

So I have kept playing with it, very annoyed, especially since not that many people seem to have this issue, but it looks like no matter how small I make the columnWidth, the GridView barely gets any smaller. In fact, that same gap you see is what it stays at until I go to 50dp. But when I go in portrait mode the gap reappears, so I raise it up to 90dp (I tried under that, didn't change anything), and it goes away. Weird thing is the GridView doesn't change besides the filling of the gap. So I could make it 200dp, and it would look perfect on my screen dimen, and any other smaller screen. Once I go to a tablet, I suspect I would need to increase that more, but the point is, this is weird behavior. Has anyone encountered this?


问:
Android dotted underline is staying in middle of textview
I want to show a dotted underline below the textview, following are my codes

```<code><TextView
  android:id="@+id/contact_num"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:paddingTop="4dp"
  android:text="1234567890"
  android:background="@drawable/dashed_line"
  android:layerType="software"
  android:textSize="20dp" />
</code>```

dashed_line.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="line">

    <stroke
        android:color="@color/oceanBlue"
        android:dashWidth="2dp"
        android:dashGap="3dp"
        android:width="1dp"/>
</shape>
</code>```

and the textview looks as above

can anyone help me to get the dotted line below to the textview?

tried with drawableBottom also but no use

```<code>android:drawableBottom="@drawable/dashed_line"
</code>```

答:
use this file for dotted line :

```<code><layer-list xmlns:android="http://schemas.android.com/apk/res/android" >

    <item
        android:left="-5dp"
        android:right="-5dp"
        android:top="-5dp">
        <shape
            android:shape="rectangle">

            <stroke
              android:color="@color/oceanBlue"
              android:dashWidth="2dp"
              android:dashGap="3dp"
              android:width="1dp"/>
        </shape>
    </item>

</layer-list>
</code>```

then add

android:background="@drawable/dashed_line"

Body:
I want to show a dotted underline below the textview, following are my codes

<TextView
  android:id="@+id/contact_num"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:paddingTop="4dp"
  android:text="1234567890"
  android:background="@drawable/dashed_line"
  android:layerType="software"
  android:textSize="20dp" />

dashed_line.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="line">

    <stroke
        android:color="@color/oceanBlue"
        android:dashWidth="2dp"
        android:dashGap="3dp"
        android:width="1dp"/>
</shape>

and the textview looks as above

can anyone help me to get the dotted line below to the textview?

tried with drawableBottom also but no use

android:drawableBottom="@drawable/dashed_line"

Body:
use this file for dotted line :

<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >

    <item
        android:left="-5dp"
        android:right="-5dp"
        android:top="-5dp">
        <shape
            android:shape="rectangle">

            <stroke
              android:color="@color/oceanBlue"
              android:dashWidth="2dp"
              android:dashGap="3dp"
              android:width="1dp"/>
        </shape>
    </item>

</layer-list>

then add

android:background="@drawable/dashed_line"


问:
MVC Structure. Where should be placed language folder?
I'm doing app using JavaFX and want to add to it different language support. Current structure is:

app

app.controller

app.DA

app.DB

app.DB.backup

app.model (Objects)

app.view

app.view.styles

Where would be right to place a language folder?

答:
I am not a JavaFX expert but in general, language strings are a part of view model.
So may be you can do this in app.view.model/ app.view.strings or may be in the app.model itself.</p>


问:
W3C HTML validation for React JSX files
When working on front-end projects I always like to work with linting tools. They prevent from dumb mistakes to serious smelly code pieces. Linting tools also suggest improvements and optimisations.

Validating and linting HTML means using the W3C Validator. When working with vanilla JavaScript projects I use the grunt-html Grunt NPM module. And when working with Angular 1.x I use the grunt-html-angular-validate module, which is the same validator but adapted to Angular requirements (non standard attributes or incomplete HTML documents will not fire errors or warnings). However I have tried to find some similar tool for React JSX documents either for Grunt or Gulp but with not luck.

Does it exist W3C HTML validators for React JSX files? In case it does not, any reason for it?

NOTE: I am not interested on checking the JavaScript part of the JSX with tools like JSXHint but just the HTML part and its compliance with W3C specifications.

答:
There are no W3C HTML validators for JSX.
JSX is JS, not HTML. So you can use eslint plugins for linting jsx to avoid common problems:

https://github.com/yannickcr/eslint-plugin-react

https://github.com/evcohen/eslint-plugin-jsx-a11y

Title: W3C HTML validation for React JSX files


问:
ASP.NET Core route with constraint is not falling back to default route
I have a new ASP.NET Core web application with routing defined as follows:

```<code>app.UseMvc(routes =>
{
    routes.MapRoute(
        name: "sitemap",
        defaults: new { controller = "Sitemap", action = "Index" },
        template: "sitemap.xml");

    routes.MapRoute(
        name: "cms",
        template: "{*permalink}",
        defaults: new { controller = "Content", action = "Index" },
        constraints: new { permalink = new CmsRouteConstraint() });

    routes.MapRoute(
        name: "default",
        template: "{controller=Home}/{action=Index}/{id?}");
});
</code>```

When I request the URL / I see my home page served by HomeController. When I request the URL /sitemap.xml I see the XML served by SitemapController. When I request a URL for which my Match method in CmsRouteConstraint returns true I see the request being handled by ContentController.

However, all other URLs are returning a 404 response. By my understanding these URLs should still be handled by my default route and passed to HomeController but they're not. What I find strange is that regardless of whether I request URL / or /where/am/i I can see CmsRouteConstraint returning false both times, so why would the former end up being handled by HomeController and not the latter?

答:
You need to use what you have. For exaple if you want call /yolo/swag it will be handled by deafult route but you dont have yolo controller with swag action and will return 404

Also remember about * in cms route and his catch-all route function so i reccoment use "greedy matching" at the end of route table

Body:
I have a new ASP.NET Core web application with routing defined as follows:

app.UseMvc(routes =>
{
    routes.MapRoute(
        name: "sitemap",
        defaults: new { controller = "Sitemap", action = "Index" },
        template: "sitemap.xml");

    routes.MapRoute(
        name: "cms",
        template: "{*permalink}",
        defaults: new { controller = "Content", action = "Index" },
        constraints: new { permalink = new CmsRouteConstraint() });

    routes.MapRoute(
        name: "default",
        template: "{controller=Home}/{action=Index}/{id?}");
});

When I request the URL / I see my home page served by HomeController. When I request the URL /sitemap.xml I see the XML served by SitemapController. When I request a URL for which my Match method in CmsRouteConstraint returns true I see the request being handled by ContentController.

However, all other URLs are returning a 404 response. By my understanding these URLs should still be handled by my default route and passed to HomeController but they're not. What I find strange is that regardless of whether I request URL / or /where/am/i I can see CmsRouteConstraint returning false both times, so why would the former end up being handled by HomeController and not the latter?


问:
When are GAS ELF the directives .type, .thumb, .size and .section needed?
I'm working on an assembly program for an ARM Cortex-M3 based microcontroller (Thumb 2 instruction set), using GNU as.

In some example code I find directives like .size, .section and .type which I understand are ELF directives. As an example:

```<code>    .section    .text.Reset_Handler
    .weak       Reset_Handler
    .type       Reset_Handler, %function
Reset_Handler:
    bl      main
    b       Infinite_Loop
    .size   Reset_Handler, .-Reset_Handler
</code>```

The .type directive is said to set the type of a symbol - usually either to %object (meaning data?) or %function. I do not know what difference it makes. It is not always included, so I am unsure when it needs to be used.

Also related to this is the .thumb_func directive. From what I have read it seems like it might be equivalent to:

```<code>.thumb
.type Symbol_Name, %function
</code>```

Or is it something completely different?

.size supposedly sets the size associated with a symbol. When this is needed, I have no idea. Is this calculated by default, but overrideable with this directive? If so - when would you want to override?

.section is easier to find docs on, and I think I have a fair idea of what it does, but I am still a little bit unsure about the usage. The way I understand it, it switches between different ELF sections (text for code, data for writable data, bss for uninitialized data, rodata for constants, and others), and defines new ones when desired. I guess you would switch between these depending on whether you define code, data, uninitialized data, etc. But why would you create a subsection for a function, as in the example above?

Any help with this is appreciated. If you can find links to tutorials or docs that explain this in greater detail - preferably understandable for a novice - I would be very grateful.

So far, the Using as manual has been of some help - maybe you can get more out of it than me, with more knowledge.

答:
Sections of your program are tightly related to the ELF format in which most systems (Linux, BSD, ...) store their object and executable files. This article should give you a good insight about how ELF works, which will help you understand the why of sections.

Simply put, sections let you organize your program into different memory areas which have different properties, including address, permission to execute and write, etc. During the final link stage, the linker uses a particular linker script that usually groups all sections of the same name together (e.g. all code from all compilation units together, ...) and assigns them a final address in memory.

For embedded systems their use is particularly obvious: first, the boot code (usually contained in the .text section) must be loaded at a fixed address in order to be executed. Then, read-only data can be grouped into a dedicated read-only section that will be mapped into the ROM area of the device. Last example: operating systems have initialization functions that are only called once and then never used afterwards, wasting precious memory space. If all these initialization functions are grouped together into a dedication section called, say, .initcode, and if this section is set to be the last section of the program, then the operating system can easily reclaim this memory once initialization is finished by lowering the upper limit of its own memory. Linux for instance is known to use that trick, and GCC allows you to place a variable or method into a specific section by postfixing it with __attribute__ ((section ("MYSECTION")))

.type and .size are actually still quite unclear to me too. I see them as helpers for the linker and never saw them outside of assembler-generated code.

.thumb_func seems to only be needed for the old OABI interface in order to allow interworking with Arm code. Unless you are using an old toolchain, you probably don't have to worry about it.

Body:
I'm working on an assembly program for an ARM Cortex-M3 based microcontroller (Thumb 2 instruction set), using GNU as.

In some example code I find directives like .size, .section and .type which I understand are ELF directives. As an example:

    .section    .text.Reset_Handler
    .weak       Reset_Handler
    .type       Reset_Handler, %function
Reset_Handler:
    bl      main
    b       Infinite_Loop
    .size   Reset_Handler, .-Reset_Handler

The .type directive is said to set the type of a symbol - usually either to %object (meaning data?) or %function. I do not know what difference it makes. It is not always included, so I am unsure when it needs to be used.

Also related to this is the .thumb_func directive. From what I have read it seems like it might be equivalent to:

.thumb
.type Symbol_Name, %function

Or is it something completely different?

.size supposedly sets the size associated with a symbol. When this is needed, I have no idea. Is this calculated by default, but overrideable with this directive? If so - when would you want to override?

.section is easier to find docs on, and I think I have a fair idea of what it does, but I am still a little bit unsure about the usage. The way I understand it, it switches between different ELF sections (text for code, data for writable data, bss for uninitialized data, rodata for constants, and others), and defines new ones when desired. I guess you would switch between these depending on whether you define code, data, uninitialized data, etc. But why would you create a subsection for a function, as in the example above?

Any help with this is appreciated. If you can find links to tutorials or docs that explain this in greater detail - preferably understandable for a novice - I would be very grateful.

So far, the Using as manual has been of some help - maybe you can get more out of it than me, with more knowledge.


问:
Is there a function in R, which returns number of significant digits?
Somewhere I found this code

```<code>signdig = function(x)
{
  length(gregexpr("[[:digit:]]", as.character(x))[[1]])
}
</code>```

But this returns strange numbers, like

```<code>> L=matrix(c(15,5,9,3.111),nrow=2)
> kappa(L)
[1] 239.5819
> signdig(kappa(L))
[1] 15
</code>```

Can somebody suggest an algorithm or code to solve it?

答:
In the interest of simplicity, let's assume that all of the values in L are precise to the third decimal place and that kappa(L) is also precise to the third decimal place. Let's also assume a convention such that a value has a precision attribute (denoted pa) equal to its order of magnitude.  Thus, all of the values in L have a precision attribute of -3.

Then the count of significant figures in kappa(L) is

```<code>sigfig = ceiling(log10(abs(x))) - precision + (log10(abs(x)) %% 1 == 0)
</code>```

as a general function

```<code>count_sigfig <- function(x, precision){
  ceiling(log10(abs(x))) - precision + log10(abs(x)) %% 1 == 0)
}
</code>```

Body:
Somewhere I found this code

signdig = function(x)
{
  length(gregexpr("[[:digit:]]", as.character(x))[[1]])
}

But this returns strange numbers, like

> L=matrix(c(15,5,9,3.111),nrow=2)
> kappa(L)
[1] 239.5819
> signdig(kappa(L))
[1] 15

Can somebody suggest an algorithm or code to solve it?

Body:
In the interest of simplicity, let's assume that all of the values in L are precise to the third decimal place and that kappa(L) is also precise to the third decimal place. Let's also assume a convention such that a value has a precision attribute (denoted pa) equal to its order of magnitude.  Thus, all of the values in L have a precision attribute of -3.

Then the count of significant figures in kappa(L) is

sigfig = ceiling(log10(abs(x))) - precision + (log10(abs(x)) %% 1 == 0)

as a general function

count_sigfig <- function(x, precision){
  ceiling(log10(abs(x))) - precision + log10(abs(x)) %% 1 == 0)
}


问:
how to break a line java script
i am setting a text of a h4 through java script what i want to do is add new line here's the code

```<code>$("#description").text("for CCAET and has received significant international scientific recognition. <br /> \n Dr. Armogan has also been responsible for many surgical firsts in retina and cataract management.");
</code>```

now i tried it with multiple solutions but still not working here's another one

```<code>$("#description").text("or CCAET and has received significant international scientific recognition.Dr. Armogan has also been responsible for many surgical firsts in retina and cataract management."+
                        "abc"+
                         "def");
</code>```

any help?

答: Try $("#description").html(...) instead of $("#description").text(...).

Title: how to break a line java script

Body:
i am setting a text of a h4 through java script what i want to do is add new line here's the code

$("#description").text("for CCAET and has received significant international scientific recognition.
 \n Dr. Armogan has also been responsible for many surgical firsts in retina and cataract management.");

now i tried it with multiple solutions but still not working here's another one

$("#description").text("or CCAET and has received significant international scientific recognition.Dr. Armogan has also been responsible for many surgical firsts in retina and cataract management."+
                        "abc"+
                         "def");

any help?