text:
Q: Azure API Management: Discriminate operations by both path and query parameters I have a backend API (that implements ApiController) which I'd like to put behind an APIM API. ApiController allows us to discriminate between two different GET operations based on the query parameters that are passed in. When I attempt to define these endpoints in APIM, I get the following error:

The message suggests an endpoint is defined solely by the path and operation. But that seems to contradict documentation I found here which suggests there's a way to differentiate between operations based on query parameters:

Required parameters across both path and query must have unique names.
  (In OpenAPI a parameter name only needs to be unique within a
  location, for example path, query, header. However, in API Management
  we allow operations to be discriminated by both path and query
  parameters (which OpenAPI doesn't support). That's why we require
  parameter names to be unique within the entire URL template.)

I have an ApiController that defines two different Get operations, differing only by the query parameters. How do I represent that in my APIM API?

A: The problem comes from multiple operation objects with the same OperationId. This is invalid swagger. In the Swagger file did not match the name of the selected API, so change the title attribute of the doc tag to match the destination API it worked..
Here is a similar SO thread you could refer to.

A: I got my answer from Azure support, sharing the info here:
APIM endpoints are defined by the path, method, and the name you assign to the operation. To differentiate between two GET endpoints to the same controller, differing only by query parameters, you need to hardcode required query parameters into the path. See the following two images:

In the latter image, the hardcoded query parameter is classified by the UI as a template parameter, but it still behaves like a regular query parameter. Query arguments defined in this way:

*

*Are required

*Can appear in anywhere in a request's list of query arguments

*Are not case-sensitive

*Are listed as a "Request Parameter" along side all other path parameters and query arguments in the Development Portal

Edit:
There's a typo in the screenshots. The URLs are case sensitive, and the casing of "blah" were different in each case. Here's what the the Open API Specification looks like when the casing is consistent. The overloaded path (with the query parameter hardcoded into the path template) appears in a section called x-ms-paths:
{
    "swagger": "2.0",
    "info": {
        "title": "Echo API",
        "version": "1.0"
    },
    "host": "<hostUrl>",
    "basePath": "/echo",
    "schemes": ["https"],
    "securityDefinitions": {
        "apiKeyHeader": {
            "type": "apiKey",
            "name": "Ocp-Apim-Subscription-Key",
            "in": "header"
        },
        "apiKeyQuery": {
            "type": "apiKey",
            "name": "subscription-key",
            "in": "query"
        }
    },
    "security": [{
        "apiKeyHeader": []
    }, {
        "apiKeyQuery": []
    }],
    "paths": {
        "/Blah": {
            "get": {
                "operationId": "blah",
                "summary": "Blah",
                "responses": {}
            }
        }
    },
    "tags": [],
    "x-ms-paths": {
        "/Blah?alpha={alpha}": {
            "get": {
                "operationId": "blah2",
                "summary": "Blah2",
                "parameters": [{
                    "name": "alpha",
                    "in": "query",
                    "required": true,
                    "type": "string"
                }],
                "responses": {}
            }
        }
    }
}


text:
Q: How can I get Google search results with Python 3? I am trying to write a Python 3 function that works like the following:
links = google_search('"done" "store"')
for l in links: print(l)

The output should be a very long list, something like:
www.cnn.com/articles/done_with_sotres.html
www.something.org/whatever?p=bla
.
.
.

I found this suggestion, Google Search from a Python App, but I seem to get only 4 urls in "hits", and I am unsure how to get the rest.
any suggestion will be highly appreciated!
EDIT: stupid me! I didn't put the implementation. anyway, it's the one described in the link:
def search(search_string):
  query = urllib.parse.urlencode({'q': search_string})
  url = 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&%s' % query
  search_response = urllib.request.urlopen(url)
  search_results = search_response.read().decode("utf8")
  results = json.loads(search_results)
  data = results['responseData']
  print('Total results: %s' % data['cursor']['estimatedResultCount'])
  hits = data['results']
  print('Top %d hits:' % len(hits))
  for h in hits: print(' ', h['url'])
  print('For more results, see %s' % data['cursor']['moreResultsUrl'])
  return hits

A: The maximum number of results that can be obtained from this api is 8 results for each query.
You get it by adding a "&rsz=large" to the url:
url = 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&%s&rsz=large' % query

There is another useful argument "start=" which let you move in the result set.
So basically you may loop on you can ask 1st block of 8 results, second block and so on(start=1, start=8 and so on).
url = 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&rsz=large&%s&start=%d' % (query, i)

In any case please note that this api is deprecated (https://developers.google.com/web-search/docs/)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Connection closed error on server sent events I created a server-sent event on ASP.NET Web API using the following codes :
namespace SpaServerSide.Controllers
{
    public class SSEController : ApiController
    {

        static readonly ConcurrentQueue<StreamWriter> ConnectedClients = new ConcurrentQueue<StreamWriter>();
        static System.Threading.Timer _dd = new System.Threading.Timer(OnTimerEvent, null, 0, 1000);

        [Route("api/sse")]
        public HttpResponseMessage Get()
        {
            var Response = Request.CreateResponse();
            Response.Content = new PushStreamContent((Action< Stream, HttpContent, TransportContext>)OnStreamAvailabe, "text/event-stream");
            return Response;
        }

        private static void OnStreamAvailabe(Stream stream, HttpContent headers, TransportContext context)
        {
            var clientStream = new StreamWriter(stream);
            ConnectedClients.Enqueue(clientStream);
        }

        static void OnTimerEvent(object state)
        {
            _dd.Change(Timeout.Infinite, Timeout.Infinite);
            try
            {
                var jsSerializer = new JavaScriptSerializer();
                var message = jsSerializer.Serialize(new { msg = "Server send this response on " + DateTime.Now.ToString() });
                foreach (var clientStream in ConnectedClients)
                {
                    clientStream.WriteLine("data:" + message + Environment.NewLine + Environment.NewLine);
                    clientStream.Flush();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                _dd.Change(1000, 1000);
            }
        }

    }
}

Then, I connect to this server with javascript using the following snippets :
var evtSource = new EventSource("http://localhost:5587/api/sse");

        evtSource.onopen = function(e){
            alert("Opened");
        }

        evtSource.onmessage = function(e){
            console.log(e);
            alert("Response Received.");
        }

        evtSource.onerror = function (e) {
            alert('error');
        };

However, an exception occurs. The message is :The remote host closed the connection. How did this happen? And for further studies, when does the server-sent event trigger? Can it be controlled manually?


text:
Q: numberOfSections being called? iOS Skip all this info and skip to the update at the bottom...
I have dealt with unrecognized selectors before, but I cannot figure out what is going on this time. The call stack is opaque and I can't find out where the problem is originating from. I have tried using symbolic and exception breakpoints. This code was working perfectly before..I come back to work on this program some more and am now running into this
[UITableViewSectionElement numberOfSections]: unrecognized selector sent to instance 0xa285d50

I have two UITableViews in this view controller. One of them is hooked up in IB(datasource and delegate). The second one is instantiated in code and its datasource/delegate are also pointing to the view controller. I put a tag of 2 on the second tableview to distinguish them from each other. UITableViewTwo is add to a UIView which is returned as the first tableview's footer if I have valid data to show. Again, this code was working perfectly without any crashes a while back, and I can't seem to figure out why it is crashing now. I am using ARC.
Here is some code:
When I check what the address of the object the selector being sent to is: it is indeed a UITableViewSectionElement. Why the H is this receiving the call numberOfSections? Isn't it supposed to be numberOfSectionsInTableView?
UITableView Delegate/DataSource methods

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView.tag == 0) {
        if (indexPath.row == 0) {
            PCFCustomNumberReviewsCell *cell = [self.tableViewOne dequeueReusableCellWithIdentifier:@"PCFNumberOfRatings"];
            [cell.numberOfReviews setText:[NSString stringWithFormat:@"%d", numReviews.integerValue]];
            [cell.numberOfReviews setFont:[PCFFontFactory droidSansFontWithSize:17]];
            [cell.numberOfReviews setTextColor:[UIColor lightGrayColor]];
            UIImageView *imgView = [[UIImageView alloc] initWithFrame:cell.frame];
            [imgView setImage:[UIImage imageNamed:@"1slot2.png"]];
            [cell setBackgroundView:imgView];
            return cell;
        }else if(indexPath.row == 1) {
            PCFCustomReviewCell *cell = [self.tableViewOne dequeueReusableCellWithIdentifier:@"RateEasiness"];
            [cell.stars setBackgroundImage:[self getImageForStars:[NSString stringWithFormat:@"%d", totalEasiness.integerValue]] forState:UIControlStateNormal];
            UIImageView *imgView = [[UIImageView alloc] initWithFrame:cell.frame];
            [imgView setImage:[UIImage imageNamed:@"1slot2.png"]];
            [cell setBackgroundView:imgView];
            return cell;
        }else if(indexPath.row == 2) {
            PCFCustomReviewCell *cell = [self.tableViewOne dequeueReusableCellWithIdentifier:@"RateUsefulness"];
            [cell.stars setBackgroundImage:[self getImageForStars:[NSString stringWithFormat:@"%d", totalUsefulness.integerValue]] forState:UIControlStateNormal];
            UIImageView *imgView = [[UIImageView alloc] initWithFrame:cell.frame];
            [imgView setImage:[UIImage imageNamed:@"1slot2.png"]];
            [cell setBackgroundView:imgView];
            return cell;
        }else if(indexPath.row == 3) {
            PCFCustomReviewCell *cell = [self.tableViewOne dequeueReusableCellWithIdentifier:@"RateFunness"];
            [cell.stars setBackgroundImage:[self getImageForStars:[NSString stringWithFormat:@"%d", totalFunness.integerValue]] forState:UIControlStateNormal];
            UIImageView *imgView = [[UIImageView alloc] initWithFrame:cell.frame];
            [imgView setImage:[UIImage imageNamed:@"1slot2.png"]];
            [cell setBackgroundView:imgView];
            return cell;
        }else if(indexPath.row == 4) {
            PCFCustomReviewCell *cell = [self.tableViewOne dequeueReusableCellWithIdentifier:@"RateInterestLevel"];
            [cell.stars setBackgroundImage:[self getImageForStars:[NSString stringWithFormat:@"%d", totalInterestLevel.integerValue]] forState:UIControlStateNormal];
            UIImageView *imgView = [[UIImageView alloc] initWithFrame:cell.frame];
            [imgView setImage:[UIImage imageNamed:@"1slot2.png"]];
            [cell setBackgroundView:imgView];
            return cell;
        }else if(indexPath.row == 5) {
            PCFCustomReviewCell *cell = [self.tableViewOne dequeueReusableCellWithIdentifier:@"RateTexbookUse"];
            [cell.stars setBackgroundImage:[self getImageForStars:[NSString stringWithFormat:@"%d", totalTextbookUse.integerValue]] forState:UIControlStateNormal];
            UIImageView *imgView = [[UIImageView alloc] initWithFrame:cell.frame];
            [imgView setImage:[UIImage imageNamed:@"1slot2.png"]];
            [cell setBackgroundView:imgView];
            return cell;
        }else if(indexPath.row == 6) {
            PCFCustomReviewCell *cell = [self.tableViewOne dequeueReusableCellWithIdentifier:@"RateOverall"];
            [cell.stars setBackgroundImage:[self getImageForStars:[NSString stringWithFormat:@"%d", totalOverall.integerValue]] forState:UIControlStateNormal];
            UIImageView *imgView = [[UIImageView alloc] initWithFrame:cell.frame];
            [imgView setImage:[UIImage imageNamed:@"1slot2.png"]];
            [cell setBackgroundView:imgView];
            return cell;
        }

    }else {
        PCFCustomCourseCommentCell *cell = (PCFCustomCourseCommentCell *) [self.tableViewTwo dequeueReusableCellWithIdentifier:@"PCFCourseCommentCell"];
        if (cell == nil) {
            NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"PCFCustomCourseReviewCell" owner:self options:nil];
            cell = [topLevelObjects objectAtIndex:0];
        }
        UIImageView *imgView = [[UIImageView alloc] initWithFrame:cell.frame];
        [imgView setImage:[UIImage imageNamed:@"1slot2.png"]];
        [cell setBackgroundView:imgView];

        PCFRateModel *rateObject = [courseReviews objectAtIndex:indexPath.section];
        [cell.userName setText:rateObject.username];
        [cell.date setText:rateObject.date];
        [cell.professor setText:rateObject.course];
        [cell.comment setText:rateObject.message];
        [cell.term setText:rateObject.term];
        for (UIView *view in cell.contentView.subviews) {
            if ([view isMemberOfClass:[UILabel class]]) {
                UILabel *tempLabel = (UILabel *)view;
                if ([tempLabel tag] != 0) {
                    [tempLabel setFont:[PCFFontFactory droidSansFontWithSize:tempLabel.tag]];
                }
            }
        }
        CGSize size = [rateObject.message sizeWithFont:[PCFFontFactory droidSansFontWithSize:11] constrainedToSize:CGSizeMake(290, 100000)];
        [cell.comment setFrame:CGRectMake(cell.comment.frame.origin.x, cell.comment.frame.origin.y, size.width, size.height)];
        [cell.comment setBaselineAdjustment:UIBaselineAdjustmentAlignBaselines];
        [cell.comment setPreferredMaxLayoutWidth:290];
        [cell.comment setLineBreakMode:NSLineBreakByWordWrapping];
        [cell.starFunness setBackgroundImage:[self getImageForStars:rateObject.totalClarity] forState:UIControlStateNormal];
        [cell.starEasiness setBackgroundImage:[self getImageForStars:rateObject.totalEasiness] forState:UIControlStateNormal];
        [cell.starUsefulness setBackgroundImage:[self getImageForStars:rateObject.totalHelpfulness] forState:UIControlStateNormal];
        [cell.starInterestLevel setBackgroundImage:[self getImageForStars:rateObject.totalInterestLevel] forState:UIControlStateNormal];
        [cell.starOverall setBackgroundImage:[self getImageForStars:rateObject.totalOverall] forState:UIControlStateNormal];
        [cell.starTextbookUse setBackgroundImage:[self getImageForStars:rateObject.totalTextbookUse] forState:UIControlStateNormal];
        return cell;
    }
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView.tag == 0) {
        if (isLoading == YES) {
            return 0;
        }else {
            return 7;
        }
    }else {
        if (isLoadingComments == NO && courseReviews) {
            return 1;
        }else {
            return 0;
        }

    }
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (isLoading == YES) return 0;
    if (tableView.tag != 0) return courseReviews.count;
    return  1;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    if (section == 0 && tableView.tag == 0) {
        if (isLoading == YES) {
            return  activityIndicator;
        }else if (isLoading == NO) {
            if (isLoadingComments == NO && courseReviews.count > 0) {
                UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, tableViewTwo.frame.size.height)];
                [view addSubview:tableViewTwo];
                return view;
            }else if (isLoadingComments == YES){
                UIView *subView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 50)];
                UIActivityIndicatorView *view = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(145, 10, 36, 36)];
                [view setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleWhiteLarge];
                [view setColor:[UIColor whiteColor]];
                [view startAnimating];
                [subView addSubview:view];
                return subView;
            }else if (!courseReviews) {
                UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 40)];
                UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 10, 320, 30)];
                [label setTextColor:[UIColor whiteColor]];
                [label setTextAlignment:NSTextAlignmentCenter];
                [label setFont:[PCFFontFactory droidSansFontWithSize:22]];
                [label setText:@"No Reviews"];
                [label setBackgroundColor:[UIColor clearColor]];
                [view addSubview:label];
                return view;
            }

        }
    }
    return nil;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    if (tableView.tag == 0) {
        if (isLoadingComments == NO && courseReviews.count > 0) return tableViewTwo.frame.size.height + 50;
    }
    return 5;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView.tag == 2) {
        PCFRateModel *model = [courseReviews objectAtIndex:indexPath.section];
        CGSize size = [model.message sizeWithFont:[PCFFontFactory droidSansFontWithSize:11] constrainedToSize:CGSizeMake(290, 100000)];
        return (93 + size.height + 10);
    }else {
        return tableView.rowHeight;
    }
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section == 0 && tableView.tag == 0) {
        if ([PCFInAppPurchases boughtRemoveAds] == NO) {
            if (adView && adView.hidden == NO) {
                UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 80)];
                CGRect frame = adView.frame;
                frame.origin.y = 0;
                adView.frame = frame;
                UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, 60, 320, 30)];
                [label setNumberOfLines:0];
                [label setText:classTitle];
                [label setFont:[PCFFontFactory droidSansFontWithSize:14]];
                [label setTextColor:[UIColor whiteColor]];
                [label setBackgroundColor:[UIColor clearColor]];
                [view addSubview:adView];
                [view addSubview:label];
                return view;
            }
        }else {
            UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, 320, 30)];
            [label setNumberOfLines:0];
            [label setText:classTitle];
            [label setFont:[PCFFontFactory droidSansFontWithSize:14]];
            [label setTextColor:[UIColor whiteColor]];
            [label setBackgroundColor:[UIColor clearColor]];
            return label;

        }
    }
    return nil;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0 & tableView.tag == 0) {
        if ([PCFInAppPurchases boughtRemoveAds] == NO) {
            if (adView && adView.hidden == NO)  {
                return 90;
            }return 10;
        }else {
            return 30;
        }

    }
    return 5;
}

View Did Load(The relevant information):
 tableViewTwo = [[UITableView alloc] initWithFrame:CGRectMake(0, 50, 320, self.view.bounds.size.height) style:UITableViewStyleGrouped];
    [tableViewTwo setSectionFooterHeight:0.0f];
    [tableViewTwo setDataSource:self];
    [tableViewTwo setDelegate:self];
    [tableViewTwo setTag:2];
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 10, 320, 30)];
    [label setTextColor:[UIColor whiteColor]];
    [label setTextAlignment:NSTextAlignmentCenter];
    [label setFont:[PCFFontFactory droidSansFontWithSize:22]];
    [label setText:@"User Reviews"];
    [label setBackgroundColor:[UIColor clearColor]];
    [tableViewTwo setTableHeaderView:label];
    [tableViewTwo setRowHeight:136];
    [tableViewTwo setSectionFooterHeight:.01f];
    [tableViewTwo setSectionHeaderHeight:.01f];

I am attaching some screenshots of the app:
Whenever I click on or try to scroll tableviewTwo I get this crash.

Update:

This is what it shows when I scroll the second UITableView(with all exceptions enabled):

I have a build of this working perfectly on my phone(a month ago)..I don't know why I am getting this error now. Could a change if Interface Builder have caused this? I have checked all the outlets and included them. Thanks..
Update:
Oddly enough, when I clone the repo on another laptop it is working without problems. I think somehow the project I was using was corrupted? I will go home and investigate further.
Any ideas as to why this is not crashing on my work laptop(similiar specs) and is crashing on my laptop. I have cloned the git directory in both laptops and I am getting a crash here, but not there. I am running XCode version 4.6.3 on my laptop.
Update 2:
It is no longer working on my work laptop..WTF is going on? Is there a bug in Xcode 4.6.3? Is there anything I can do to troubleshoot this further? Why is numberOfSections being called? I can't find documentation on that online ANYWHERE.
Update 3:
Okay, it turns out that this line of code in the viewForFooterInSection selector is the culprit:
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, tableViewTwo.frame.size.height)];
                [view addSubview:tableViewTwo];
                return view;

It works fine on the device but crashes on the simulator. When I simply change it to the following..it works.
return tableViewTwo;

Does anyone know why the returning the tableview in a view is giving an error?

A: numberOfSections is a method on UITableView - it's not a delegate method. It looks like the system calls this method internally, and for some reason your table is being released automatically (hence the crash).
I would try the following in your viewForFooterInSection method:
static UIView *view = nil;

if (!view) {
    view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, tableViewTwo.frame.size.height)];
    [view addSubview:tableViewTwo];
}

return view;

A: You just mentioned you are using ARC, so did you make your second TableView A strong property? is it an ivar?
The issue is that if you didn't make it a strong property, it will eventually get released thanks to ARC and you won't be able to get to know the problem, can you post code from .h file?


text:
Q: changing the value of object in attrs inside controller of a directive I have a directive as follows

<my-dir data=prd.data ng-click=stateChanged()></my-dir>

where prd.data is an object. In my directive I did the following
app.directive('myDir',function(){
    return {
        scope:{
            data:'=data'
        },
        templateUrl: './templates/testtemplate.html',
        controllerAs:'bd',
        controller:function($scope,$attrs){
            this.stateChanged = function (value) {
                $attrs.data = { 'fd','sdfs'};
            }
       }
     });

I am unable to modify the data value within the controller how do I proceed thanks in advance.

A: I think the problem could be in the way you trying to get data object in your controller.
You should try to get it by $scope.data. All directive inputs getting attached to your internal scope.
$attrs - is a hash object with key-value pairs of normalized attribute names and their corresponding attribute values. According to AngularJS docs.

A: Try this

var app = angular.module("myApp", []);
app.controller("prdController", function($scope) {
  $scope.data = "krupesh";
  $scope.stateChanged = function() {
    $scope.data = "kotecha";
  }
});
app.directive('myDir', function() {
  return {
    restrict: 'E',
    template: "
{{data}}
"
  };
});

  <my-dir data="prd.data" ng-click=stateChanged()></my-dir>


text:
Q: UIButton titleLabel number of lines working fine on iOS5 but not on iOS4.3 I am setting numberOfLines for titleLabel of UIButton :
btnMailAddress.titleLabel.numberOfLines = 3;

In iOS5 device the text is being displayed in 3 lines but in iOS4.3 device the text is fitting in 1 line only.

A: try with setting it zero.
btnMailAddress.titleLabel.numberOfLines = 0;

From UILabel documentation for the property numberOfLines.

For using as many lines as needed, set the value of this property to 0.

A: Try setting the lineBreakMode property of UIButton's titleLabel to UILineBreakModeWordWrap.
btnMailAddress.titleLabel.lineBreakMode = UILineBreakModeWordWrap;

Hope this helps you.


text:
Q: Secure insert queries with go-sql-driver and mysql I have reviewed the go-sql-driver examples with db.Prepare but I couldn't get it to work properly so I modified it to work directly with db.Query. My understanding is that by using ?? the value is escaped anyway so I was wondering if the following is correct and secure against SQL injection (note that I am using MySQL)
stmtIns, err := db.Query("INSERT INTO users (name, address) VALUES(?,?)", name, address) // ? = placeholder
        if err != nil {
            panic(err.Error()) // proper error handling instead of panic in your app
        }
        defer stmtIns.Close() // Close the statement when we leave main() / the program terminates

Also, what is the best way to detect if the row has been inserted?
clarification: for secure I meant from SQL Injection. I think it is but then I wonder why all example I could find use db.Prepare and not db.Query as I do.

A: Yes, this safe from SQL injection attacks.
Note that the client code does not "escape" parameters in a query of this kind. It does something much simpler and more secure:
The client does not combine INSERT INTO users (name) VALUES(?) and the parameter ;DROP TABLE USERS; into INSERT INTO users (name) VALUES(;DROP TABLE USERS;.
Nor does the client do the above with escape characters to make it "safe". The client does not construct something like INSERT INTO users (name) VALUES("\;DROP TABLE USERS\;")
What it does is send a query to MySQL that contains, separately:

*

*the query string INSERT INTO users (name) VALUES(?) -- MySQL knows this is a query string and knows that the ? is where parameters are plugged in.

*the parameter ;DROP TABLE USERS; -- MySQL knows this is a parameter to the query

Hence the server knows that the parameter is not SQL code, and that neatly avoids the whole nasty problem of escaping characters.
By choosing not to use Prepare you are skipping some potential for optimisation in the server. The server compiles each statement into an internal representation, and this takes time. By making this explicit and re-using the prepared statement, you explicitly save repeating that compilation step.
However, MySQL does cache compiled statements, to avoid repeatedly compiling exactly the same string -- so you probably won't see big performance issues.


text:
Q: Oracle db - get rid of doubled rows I have an Oracle database with a table like this:
yr      op    v1   v2   v3
2014    op1   10   15   20
2014    op1   10   15   20
2014    op1   10   15   20
2015    op2   33   44   55
2015    op2   33   44   55
2015    op3   100  200  300
2015    op3   100  200  300
2015    op3   100  200  300

how can I get rid of values that are more than one time on each year/op? my table should look like this:
yr      op    v1   v2   v3
2014    op1   10   15   20
2014    op1   0    0    0
2014    op1   0    0    0
2015    op2   33   44   55
2015    op2   0    0    0
2015    op3   100  200  300
2015    op3   0    0    0
2015    op3   0    0    0

Thanks!

A: I would guess that you want something like
SELECT yr,
       op,
       (case when rnk = 1
             then val1
             else 0
         end) val1,
       (case when rnk = 1
             then val2
             else 0
          end) val2,
       (case when rnk = 1
             then val3
             else 0
         end)
  FROM( SELECT a.*,
               row_number() over (partition by yr, op) rnk
          FROM your_view a )


text:
Q: GitLab operations without providing password and user token I am able to upload, download, list projects and repositories using a private token.
Is it possible to do the same without a private token? Means user will provide username or email address alone...
Regard

A: It is not possible to push to a repository without authentication first.
And it is not possible to pull from a private repository, again without authentication.
If you are not using a token or password, the only other alternative (for authentication) would be using a private/public pair of SSH keys, with the public one registered to your GitLab account.

The OP adds:

Means when user x upload file using common login, want to display user x has committed the file and so on...is that possible

Commit authorship has nothing to do with push/pull remote access authentication.
For a user to be visible on a commit, all they need to do is set their git config user.name and git config user.email, and then do some commits.


text:
Q: An existing connection was forcibly closed by remote host Part of my C# windows Form is peer to peer (only two users) chat.
I use .Net Socket.
What I want to do is that whenever both users are available, they can chat. However, many issues comes up when one of them closes the program then opens it again. Or when only one is online I get this exception.
"An existing connection was forcibly closed by the remote host".
I tried to use Socket.Close and Socket.ShutDown. I also tried to re-initiate the socket variable by defining it again. All seems not working. I am opened for any suggestion even using different libraries or methods.
The code is below:
namespace TextChatApp
{
    public partial class Form1 : Form

    {
        //attributes:
        Socket sck;
        EndPoint epLocal, epRemote;

        public Form1()
        {
            InitializeComponent();
            sck = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            sck.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);

            textBox1.Text=GetLocalIP();
            textBox3.Text = GetLocalIP();
            textBox2.Text = "8001";
            textBox4.Text = "8000";
            send.Enabled = false;
            connectEndPoint();
            InitTimer();
        }

        private void MessageCallBack(IAsyncResult aResult)
        {
            try
            {
                int size = sck.EndReceiveFrom(aResult, ref epRemote);
                if(size>0)
                {
                    byte[] receivedData = new byte[1500];
                    receivedData = (byte[])aResult.AsyncState;
                    ASCIIEncoding eEncoding = new ASCIIEncoding();
                    string receivedMessage = eEncoding.GetString(receivedData);
                    listBox1.Items.Add("From a friend: "+receivedMessage);
                }
                byte[] buffer = new byte[1500];
                sck.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref epRemote, new AsyncCallback(MessageCallBack), buffer);

            }
            catch(Exception exp)
            {
                MessageBox.Show("Exception Small Chat: " + exp.ToString());
            }
        }

        private void start_Click(object sender, EventArgs e)
        {

        }

        public void connectEndPoint()
        {
            try
            {
                epLocal = new IPEndPoint(IPAddress.Parse(textBox1.Text), Convert.ToInt32(textBox2.Text));
                sck.Bind(epLocal);

                epRemote = new IPEndPoint(IPAddress.Parse(textBox3.Text), Convert.ToInt32(textBox4.Text));
                sck.Connect(epRemote);

                byte[] buffer = new byte[1500];
                sck.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref epRemote, new AsyncCallback(MessageCallBack), buffer);
                start.Enabled = false;
                start.Text = "Connected";
                send.Enabled = true;
                textBox5.Focus();

            }
            catch (Exception exp)
            {

            }
        }

        private void send_Click(object sender, EventArgs e)
        {
            try
            {
                System.Text.Encoding encoding = System.Text.Encoding.UTF8;
                byte[] msg = new byte[1500];
                msg = encoding.GetBytes(textBox5.Text);//

                sck.Send(msg);
                listBox1.Items.Add("You: " + textBox5.Text);
                textBox5.Clear();
            }
            catch(Exception exp)
            {
                MessageBox.Show("Exception Small Chat: " + exp.ToString());
            }
        }

A: I think I solved my own issue.
Since I have the exception triggered when sending data and the endpoint is off or not connected, I should check if it is connected or not before sending the data.
However, there is no straight forward way to find if the endpoint is connected.
Since when I send data and the endpoint is off it triggers exception, the exception became my indicator that the endpoint is off and connection is lost. So what I do is that I create the Socket again within the "Catch" statement and try again every period of time until the Socket is connected again.
The reason I create the Socket again every time exception triggered is because the Socket will be unstable and will lead to many connection issues. So better to create it again instead of having instability.
Here is the code I included
               private void MessageCallBack(IAsyncResult aResult)
                {
                 try
                {
                    int size = sck.EndReceiveFrom(aResult, ref epRemote);
                    if(size>0)
                    {
                        byte[] receivedData = new byte[1500];
                        receivedData = (byte[])aResult.AsyncState;
                        ASCIIEncoding eEncoding = new ASCIIEncoding();
                        string receivedMessage = eEncoding.GetString(receivedData);
                        listBox1.Invoke(new MethodInvoker(delegate {
                    listBox1.Items.Add("From a friend: " + receivedMessage); }));
                    }
                    byte[] buffer = new byte[1500];
                    sck.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None,
                ref epRemote, new AsyncCallback(MessageCallBack), buffer);

                }
                catch(Exception exp)
                { /* here is the solution, when the Catch is triggered, close the
                  socket and recreate it to avoid the issues that I been having of
                  not sending messages and instability. I also added some functions
                  that would keep sending the status and //being checked on the other
                  side in order to keep online/offline status.*/

                    sck.Close();
                    sck = new Socket(AddressFamily.InterNetwork, SocketType.Dgram,
                     ProtocolType.Udp);
                    sck.SetSocketOption(SocketOptionLevel.Socket,
                     SocketOptionName.ReuseAddress, true);
                    connectEndPoint();
                    //MessageBox.Show("Exception Small Chat: " + exp.ToString());
                }
    }


text:
Q: What is best design pattern to simplfy class with a lot of options to create it? I have a base class [for example]:
class base
{
private:
    std::string name;

public:
    virtual void set_name(const std::string& name) = 0;
    virtual std::string get_name() const = 0;
};

*

*And 20 class inherited from it.

*And I have a UI (build with Qt) which user can select type of class to create it.

for handle this i use enumeration type [for example]:
enum class types
{
    TYPE_1,
    TYPE_2,
    TYPE_3,
    ...
    TYPE_20,
};

and i end up with a long switch-case for type creation [for example]:
switch(user_selected_mode)
{
case types::TYPE_1:
    return std::make_shared<type_1>();
    ...
case types::TYPE_2:
    return std::make_shared<type_2>();
}

i think you can imagine the ugly code in other section of code which depend of type of objects.
How could i make it cleaner ?

A: For creating the objects, you could make a factory object, but in the end that's still going to have the same switch statement you currently have, just in a different object. Swings and roundabouts.
However, that's not going to fix this:

i think you can imagine the ugly code in other section of code which depend of type of objects.

I can imagine what happens if everywhere you use one of these objects you've got to have a switch statement or similar based on the type of the object. What that says to me is that you've got a bigger problem with your design in that you're passing around what is (effectively) an empty object and then subverting the type system to work out what object type it actually is. I don't think we can fix that for you without more details as to why you think you need to do this rather than just passing round more specific types.


text:
Q: IntelliJ can't find any LibGDX packages? I have just switched to Ubuntu and I've installed IntelliJ IDEA 14 Community Edition. When I imported my existing project, I found that IntelliJ can't seem to find any of the LibGDX dependencies. I installed Gradle beforehand. I've tried using the Gradle wrapper included with the IntelliJ project to and saying ./gradlew --refresh-dependencies, but this doesn't seem to do much of anything. My external TweenEngine packages were loaded just fine. It seems to only be with the LibGDX packages that IntelliJ is having a problem with. I do not wish to have IntelliJ see my project as a Gradle Project, as then it will have to sync. I prefer to do things myself in that regard.
My guess is that Gradle isn't installing the LibGDX dependencies, but I'm not entirely sure why that would be happening. Shouldn't ./gradlew --refresh-dependencies install them? The errors I get are all the same as this one, just with different package names and different line numbers:
Error:(7, 24) java: package com.badlogic.gdx does not exist

The line numbers correlate to my LibGDX class imports, so this is what leads me to believe that Gradle is not installing the dependencies.
When I imported the project, I selected the build.gradle file. I have the local.properties file pointing to a valid Android SDK.
If you want a specific look at the project and would like more detail than I have provided, feel free to check out the source code: http://bitbucket.org/Sonic2kk/mr.-ballguy/
What could be causing these errors and how can I correct them?

A: Try installing the android sdk. If that doesn't work, try reinstalling IntelliJ.
Also, try linking your IntelliJ project to IntelliJ's Gradle plugin.


text:
Q: What is the seaborn equivalent for matplotlilb histrogram of a column values? I have code snippet in matplotlilb like below:
df['coln1'].plot(kind='hist') # This works!

I tried to use the seaborn API to plot the same and my Jupyter Notebook hangs inefinitely. I tried the code below that fails:
sns.barplot(x=df.index, y=df['coln1']) # What is the right way in seaborn?

UPDATE: My objective is to see visually the distribution of values for a given column, using seaborn API.
Your help is much appreciated.

A: The equivalent solution to matplotlilb borrowed from the seaborn official documentation is shown below:
import seaborn as sns
sns.set(style="whitegrid")
tips = sns.load_dataset("tips")

tips.head(5)
   total_bill   tip     sex smoker  day    time  size
0       16.99  1.01  Female     No  Sun  Dinner     2
1       10.34  1.66    Male     No  Sun  Dinner     3
2       21.01  3.50    Male     No  Sun  Dinner     3
3       23.68  3.31    Male     No  Sun  Dinner     2
4       24.59  3.61  Female     No  Sun  Dinner     4

You can simply do this:
ax = sns.distplot(tips["total_bill"])

Which gives you the distribution of values in the "total_bill" column.

A: import seaborn as sns

sns.distplot(df[column], bins=bins)


text:
Q: Will int32 be the same size on all platforms? I'm developing a multi platform app (iOS, Android, etc), using C++.
Are there base types in the C++ standard which are guaranteed to be a fixed width, and portable across multiple platforms?
I'm looking for fixed-width types such as Int32, UInt32, Int16, UInt16, Float32, etc.

A: int32 is a custom typedef, only int exists by default. If you need a specified width take a look at stdint.h
#include <cstdint>

int32_t integer32bits;

I don't think any floating point counterpart exists in the standard, correct me if I'm wrong.

A: Floats are almost always 32 bit except on some obscure platforms that do not comply with IEEE 754. You don't need to bother with those, in all likelihood. Integer types may vary, but if your target platform has a C++11-compliant compiler, then you can use the cstdint header to access types of a specific size in a standard way.  If you can't use C++11,  then you will need separate code for each platform, most likely.

A: The definitions in <stdint.h>, or <cstdint> can be used for portability:

*

*int32_t is guaranteed to be a typedef for a signed 32 bit type, or not exist at all. Since this is C++, you can use enable_if to decide on a course of action.

*int_least32_t is a typedef for the smallest type that has at least 32 bits

*int_fast32_t is a typedef for a type that has at least 32 bit and can be operated on efficiently (e.g. if the memory bus is 64 bit wide and allows no partial stores, it is faster to use a 64 bit type and waste memory rather than perform read-modify-write accesses)

See also The difference of int8_t, int_least8_t and int_fast8_t.
Note that different systems can also have different endianness, so it is never safe to transmit these over the network.


text:
Q: how to get Network mapped drive VolumeLabel in C#? So for example, if i have drive Z:NetworkDrive, which mapped to shared folder on another server, and i want to return volumelabel "NetworkDrive". Next code seems to work:
 foreach (DriveInfo drive in drives)
            {
                if (drive.DriveType == DriveType.Network)
                    mappedDrivesNames.Add(drive.VolumeLabel);
            }

But it return the name of the first shared folder from the list on server. Any ideas, why this happened?

A: If I just code
var drive = new DriveInfo("Z");
Console.WriteLine(drive.VolumeLabel);

It is showing me the Label of the Volume the network share is on. I have my drive Z: connected to a share on a Windows XP computer and the share is on a NTFS formatted drive. If I remove the label for that volume, the program will output an empty line.
I don't know what the expected result should be if the share is on a Linux machine. I don't know if Linux has something like a Label, but I don't think so.


text:
Q: how can I save output as a float in python How can I save output as a float datatype.
def div_by_one(input):
    var = 1/input
    print var
    return var

This prints var as 0 instead of 0.125 for input=8.

A: Use 1.0 to let Python infer that you want a float.
def div_by_one(input):
    var = 1.0/input
    print var
    return var

A: just convert input number to float just like below
def div_by_one(num):
    var = 1.0 / float(num)
    print var
    return var

A: def div_by_one(input):
    var = 1.0/float(input)
    print format(var, '.2f')
    return format(var, '.2f')

A: If you are using Python 2.7 then you can do this
def div_by_one(input):
    var = 1//input
    return var

ans = div_by_one(8)
print(ans)                    #Prints 0.125


text:
Q: Finding related entities from three list I have three lists that contain the following data:
Entities:  ['Ashraf', 'Afghanistan', 'Afghanistan', 'Kabul']
Relations:  ['Born', 'President', 'employee', 'Capital', 'Located', 'Lecturer', 'University']
sentence_list: ['Ashraf','Born', 'in', 'Kabul', '.' 'Ashraf', 'is', 'the', 'president', 'of', 'Afghanistan', '.', ...]

As the sentence_list is a list of sentences. In each sentence, I want to check if any word of Entities and Relations, the combination of specific words should be added in another list. such as, (Ashraf, born, Kabul) in the first sentence.
What I did:
First incomplete Solution:
# read file
with open('../data/parse.txt', 'r') as myfile:
    json_data = json.load(myfile)

for i in range(len(json_data)): # the dataset was in json format
     if json_data[i]['word'] in relation(json_data)[0]: # I extract the relations
         print(json_data[i]['word'])
     if json_data[i]['word'] in entities(json_data)[0]:
         print(json[i]['word'])

The output: (Ashraf, Born, Ashraf), where I want (Ashraf, Born, Kabul)
The next incomplete solution: I stored json_data to a list and then I did this:
json_data2 = []
for i in range(len(json_data)):
    json2_data.append(json_data[i]['word'])
print(json_data2)

'''
Now I tried if I can find any element of `Entities` list and `Relations` list
in each sentence of `sentence_list`. And then it should store matched
entities and relations based on sentence to a list. '''

for line in json_data2:
    for rel in relation(obj):
        for ent in entities(obj):
            match = re.findall(rel,  line['word'])
            if match:
                print('word matched relations: %s ==> word: %s' % (rel,  line['address']))
            match2 = re.findall(ent, line['word'])
            if match2:
                print('word matched entities: %s ==> word: %s' % (ent,  line['address']))

Unfortunately, does not work?

A: You could use the following list comprehension:
to_match = set(Entities+Relations)
l = [{j for j in to_match if j in i}
        for i in ' '.join(sentence_list).split('.')[:-1]]

 Output
[{'Ashraf', 'Born', 'Kabul'}, {'Afghanistan', 'Ashraf'}]

Note that I'm, returning a list of sets to avoid duplicate values, given that for instance in Entities Afghanistan appears twice.
Useful reads:

*

*List comprehensions

*sets — Unordered collections of unique elements

*string methods


text:
Q: Setting up auto replies in Lotus Notes bassed on a specific subject How do I set up an auto-reply in Lotus Notes based on the text in the subject field?  Would it be possible to set up the auto-responder to reply to the email address in the cc: field and not just the sender?

A: You'd have to use an agent to do this. You can find tons of resources by googling "auto-reply agent lotus notes" but it's highly likely that the administrators at your company will disable it or have already prevented your ability to create agents. Auto responding agents are especially problematic since they tend to be the root cause of email loops.
If you have a legit business need for auto responding, you may want to work with your admins, they may already have a group inbox style mailfile design setup for auto replying.


text:
Q: designing nested template classes I'm defining a class which has as private members pointers to templated classes. I'm having a question concerning the design of such a class. More precisely, whether the outer class should be templated or not.
Since, I'm initializing the private members in the constructor of the outer class, I guess, it's correct to do so. Are there any other alternatives?
An example of the class declaration is given below and all suggestions are welcomed:
 #include <foo.h>
 #include <bar.h>

 template < class FOO_TYPE, class BAR_TYPE >
 class OuterClass{
     public:

        OuterClass(){
           this->m_pFoo   = new CFoo<FOO_TYPE>();
           this->m_pBar   = new CBar<BAR_TYPE>();
           this->m_nMyInt = 0;
        }

        template < class FOO_TYPE >
        CFoo<FOO_TYPE> * processFoo();

        template < class BAR_TYPE >
        CBar<BAR_TYPE> * processBar();

        ~OuterClass(){
           delete this->m_pFoo;
           delete this->m_pBar;
        }

     private:
        int m_nMyInt;
        CFoo<FOO_TYPE> * m_pFoo;
        CBar<BAR_TYPE> * m_pBar;
 };

A: That depends on the intended usage of the outer class. Your code suggests that OuterClass can be used with different template types, so it makes sense to have it as a template, too. Actually, this kind of template argument forwarding is very common.
However, if you rather want OuterClass to use only specific template specializations of CFoo and CBar, then you can just specify the desired FOO_TYPE and BAR_TYPE in the declaration of the corresponding members.

A: Within your class processFoo() and processBar() are incorrectly defined.
They are not templated functions within your class, they are specifically typed to your 1st and 2nd template parameter.
CFoo and CBar appear to be external templates.
Your class is also failing the "rule of 3" with regards to copy-construction and assignment and is not exception safe if the constructor of CBar throws (in which case your constructor will throw, your destructor will never get called and m_pFoo will never get deleted).


text:
Q: Can't make Metricbeat use passed env variable I'm trying to run metricbeat service in docker, according to the official documentation (version 7.2.0). Here's my bash command for setup:
docker run -d --name=metricbeat docker.elastic.co/beats/metricbeat:7.2.0 setup\
 -e setup.kibana.host=http://XXX.XXX.XXX.XXX:5601\
 -e output.elasticsearch.host=["XXX.XXX.XXX.XXX:9200"]\
 -e output.elasticsearch.password=XXXXXXXX

As you see I'm passing the output.elasticsearch.host variable and it's definitely not equal to the default value. But here's the part of the metricbeat container logs:
2019-07-31T14:32:40.335Z        INFO    elasticsearch/client.go:166     Elasticsearch url: http://elasticsearch:9200

This means that metricbeat used the default Elastic host instead of the environment variable value. How can I fix it?

A: You have made a typo, there is a s missing in output.elasticsearch.hosts.
Use also double quotes around the whole environment variable definition and single quotes around the host value, such as:
-E "output.elasticsearch.hosts=['http://myhost:9200']"

The above example is directly taken from the official documentation about global flags.


text:
Q: Internet of Things : ESP module Wifi Ip address as you can read in title I'm making a super simple IOT (Not really)
and
using a esp8266 and want to make it connect to my home wifi network and make a communication between a android app and the module (android app connects to home wifi)
Note : Iam Using CODE VISION AVR
you may say :

Why not directly connect to ESP when its on Server Mode?
that's fine cause when ESP is server "he" can set ip for him self so
  ip will be always same BUT I want it to connect to home wifi

-

Why you wont connect with IP ?
you cant find the module ip easily because its given by Wifi

-

Find ESP ip using IP scanner
Its not possible cause it changes every time and user have to change
  IP every time in android app AND my app cant scann every time it want
  to connect to a single device its so dumb...

-

Do a Static Ip for ESP !
well that's not possible too because maybe that IP was taken by
  someone before ESP send static IP AT command ! + if IP wasent taken it may taken after Home Wifi Restarts !

Sorry for bad English :X

A: You can use software serial to configure esp8266 from arduino. You need to know the setup circuit perfectly. Keep it in mind that esp8266 operates on 3.3V where arduino gives 5V output. The most important thing is to send AT commands to esp8266. You can use the following command to connect with your wifi.
AT+CWJAP="Your_WiFi","password"

If you need to see the ip address of esp8266, you can use this command.
AT+CIFSR

If you want to set static ip to esp8266 , then you can try this one.
AT+CIPSTA="ip module","ip gateway","subnet mask"

A: Use mDNS responder:
https://github.com/esp8266/Arduino/blob/master/libraries/ESP8266mDNS/examples/mDNS_Web_Server/mDNS_Web_Server.ino
This way you would be able to connect to ESP8266 via hardcoded url like http://esp8266.local.


text:
Q: How do you mock a method with a block using RR (double ruby) on Rails 3 I am using the Koala gem to make facebook requests and i have the following code:
  @graph = Koala::Facebook::API.new(oauth_token)
  @graph.batch do |batch_api|
    #... do stuff here
  end

I want to mock out the batch call to simulate the stuff we are doing in there.
Here is what i have in RR.
oauth_token= "Sometoken"
batch_api_mock = nil
graph_mock = mock(Koala::Facebook::API).new(oauth_token).mock!
graph_mock.batch.returns do
  yield batch_api_mock if block_given?
end

The problem is that block_given? is return false even though there is a block being passed in my source.
How do i mock a method that takes a block using RR?

A: K so after looking through the open tickets i found that the answer was that the first argument to the block is a RR::ProcFromBlock which is exactly the block that would be passed to the function. Here is the modification to the code to make it work.
oauth_token= "Sometoken"
batch_api_mock = nil
graph_mock = mock(Koala::Facebook::API).new(oauth_token).mock!

#The block is passed in as a proc as the first argument to the returns block.
graph_mock.batch.returns do |proc_as_block|
  proc_as_block.call
end

Hope that helps someone save some time. They need to add this little gem to the documentation


text:
Q: Map array containing another array with objects and display them in a table in javascript I have the array
const data = [
    {
        "id": 1,
        "name": "Name 1",
        "code": "1",
        "asig": "[1,2,3]",
        "category": "B"
    },
    {
        "id": 2,
        "name": "Name 1",
        "code": "1",
        "asig": "[3,5,9]",
        "category": "A"
    },
    {
        "id": 3,
        "name": "Name 2",
        "code": "2",
        "asig": "[3,4,5]",
        "category": "A"
    }
]

And ordered it like this, grouping the asig and category
let newArray = [];
let last = 0;
data.forEach(elem => {
    if(last != elem.code) {
        newArray.push({
            id: elem.id,
            Name: elem.name,
            Code: elem.code,
            Group: []
        });
        last = elem.code;
    }
    let index = newArray.length - 1;
    newArray[index].Group.push({
        asig: elem.asig,
        category: elem.category,
    });
});

the new array
console.log(newArray)

[
  {
    id: 1,
    Name: 'Name 1',
    Code: '1',
    Group: [
      { asig: '[1,2,3]', category: 'B' },
      { asig: '[3,5,9]', category: 'A' }
    ]
  },
  {
    id: 3,
    Name: 'Name 2',
    Code: '2',
    Group: [ { asig: '[3,4,5]', category: 'A' } ]
  }
]

I need to show it as it looks in this table

id
Name
Group
Category

1
Name 1
A: 3,5,9 - B: 1,2,3
A, B

3
Name 2
A: 3,4,5
A

how can I do it? Thanks

A:

for (let index = 0; index < newArray.length; index++) {
    console.log(newArray[index]);
    console.log(newArray[index].id);
    for (let index = 0; index < newArray[index].Group.length; index++) {
        console.log(newArray[index].Group[index]);
    }
}

Now you can get all the data from this array. you can store 'newArray[index].id' this as a variable. Then use any where

A: You can do as:

const data = [
    {
        id: 1,
        name: "Name 1",
        code: "1",
        asig: "[1,2,3]",
        category: "B"
    }, {
        id: 2,
        name: "Name 1",
        code: "1",
        asig: "[3,5,9]",
        category: "A"
    }, {
        id: 3,
        name: "Name 2",
        code: "2",
        asig: "[3,4,5]",
        category: "A"
    }
];

const map = new Map();

data.forEach( ( o ) => {
    const { id, name, code, asig, category } = o;
    if ( !map.has( name ) ) {
        map.set( name, { id, name, code, Group: [{ asig, category }], category: [category] } );
    } else {
        const existingObj = map.get( name );
        existingObj.category.push( category );
        existingObj.Group.push( { asig, category } );
    }
} );

const dataSet = [...map.values()].reduce( ( acc, curr ) => {
    const { id, name, code, Group, category } = curr;
    acc.push( {
        id, name, code,
        Group: Group
            .sort( ( a, b ) => a.category.localeCompare( b.category ) )
            .map( ( { asig, category } ) => `${category}: ${asig.slice( 0, asig.length - 1 ).slice( "1" )}` ).join( " - " ),
        category: category.sort( ( a, b ) => a.localeCompare( b ) ).join( ", " )
    } )
    return acc;
}, [] );

const tbody = document.querySelector( "tbody" );
dataSet.forEach( ( o ) => {
    const { id, name, code, Group, category } = o;
    const tr = tbody.insertRow();
    [id, name, code, Group, category].forEach( ( prop ) => {
        const cell = tr.insertCell();
        cell.appendChild( document.createTextNode( prop ) )
    } )

} )
<link href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css" rel="stylesheet"/>

          id
          name
          code
          Group
          category


text:
Q: What would be more efficient in java? If-return-else or If-return? I was just wondering, what is actually more efficient for the compiler to use?
if (condition) {
    return something;
} else {
    dosomething();
}

OR
if (condition) {
    return something;
}
dosomething();

I know that these are extremely low differences and that the more readable version should be chosen, but lets just say we would execute this code a billion times, which one would be more efficient?
I also know that there are no gains at all in the "real world", but I am just curious.

A: No performance difference.  The bytecode contains the same instructions, in the same order, operating on the same data.
   L0
    LINENUMBER 11 L0
    ICONST_1
    ISTORE 0
   L1
    LINENUMBER 12 L1
    ILOAD 0
    IFEQ L2
   L3
    LINENUMBER 13 L3
    GETSTATIC p/A.something : Ljava/lang/Object;
    ARETURN
   L2
    LINENUMBER 15 L2
   FRAME APPEND [I]
    INVOKESTATIC p/A.dosomething()V
   L4
    LINENUMBER 17 L4
    ACONST_NULL
    ARETURN
   L5
    LOCALVARIABLE condition Z L1 L5 0
    MAXSTACK = 1
    MAXLOCALS = 1

vs.
   L0
    LINENUMBER 7 L0
    ICONST_1
    ISTORE 0
   L1
    LINENUMBER 8 L1
    ILOAD 0
    IFEQ L2
   L3
    LINENUMBER 9 L3
    GETSTATIC p/B.something : Ljava/lang/Object;
    ARETURN
   L2
    LINENUMBER 11 L2
   FRAME APPEND [I]
    INVOKESTATIC p/B.dosomething()V
   L4
    LINENUMBER 12 L4
    ACONST_NULL
    ARETURN
   L5
    LOCALVARIABLE condition Z L1 L5 0
    MAXSTACK = 1
    MAXLOCALS = 1

public class A {
    static Object something = new Object();
    public static void main(String[] args) {
        test();
    }
    private static Object test() {
        boolean condition = true;
        if (condition) {
            return something;
        } else {
            dosomething();
        }
        return null;
    }
    private static void dosomething() {}
}

vs.
public class B {
    static Object something = new Object();
    public static void main(String[] args) {
        test();
    }
    private static Object test() {
        boolean condition = true;
        if (condition) {
            return something;
        }
        dosomething();
        return null;
    }
    private static void dosomething() {}
}

A: There is no difference whatsoever in the two versions. Only differences that may be are purely from a readability point of view.
If you adopt a style where checks are done at the beginning of a function and return is executed as soon as possible, the second comes in hand.
void foo()
{
   if (condition1)
      return;
   if (goo())
      return;
   //...
}

Otherwise, the first version provides more visible branching.

A: It wouldn't make a significant difference at all. Realize that the else is not evaluating another expression, but simply saying if the original condition is false, do this. Condition is still evaluated once both ways.
As a matter of fact, depending on the optimization done by different compilers, it may result in the same bytecode. There are many plugins for IDE's to view Java bytecode.

A: Any gains would be negligible, and I wouldn't be surprised if the resulting instructions are identical.
You are almost always better off concentrating on 'low hanging fruit', rather than such small performance micro-optimisations.
Err on the side of readability. And always measure to ensure you really have a performance bottleneck.

A: I doubt there's much of a difference in performance but I tend to prefer the latter since the former can lead to indentation hell.
Even executing that code a billion times, the doSomething() is almost certainly going to swamp the if/else in terms of time taken.
I always optimise for readability first and only worry about performance when it becomes a problem.
Unreadable code is far more of an issue than slightly slow code :-)

A: I believe that it's just personal preference.
Some more informational answers can be found at this question


text:
Q: Unable to store a string in session using SharedPreferences in android i am trying to store city name at Splash Screen, after getting city name using Geocoder i am trying to store it in Session  and use it in anther activity. But app is getting crash after adding session object.
below is my session.java
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;

import java.security.PublicKey;
import java.util.HashMap;

public class Session {
    private SharedPreferences sp;
    private SharedPreferences.Editor spEditor;

 public Session(Context context) {
        sp = PreferenceManager.getDefaultSharedPreferences(context);

    }

 public void setLocation(String city){
        spEditor.putString("UserCity", city);
        spEditor.commit();
    }

and my SplashActivity.java
import android.animation.ObjectAnimator;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Typeface;
import android.location.Address;
import android.location.Geocoder;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import zesteve.com.myapplication.location.LocationTrack;

import static android.Manifest.permission.ACCESS_COARSE_LOCATION;
import static android.Manifest.permission.ACCESS_FINE_LOCATION;

public class SplashActivity extends AppCompatActivity {

    TextView welcomeText;
    ImageView mLogo;
    ImageView zbgimg;

    Typeface tf1;

    private Session session;

    private ArrayList<String> permissionsToRequest;
    private ArrayList<String> permissionsRejected = new ArrayList<>();
    private ArrayList<String> permissions = new ArrayList<>();

    private final static int ALL_PERMISSIONS_RESULT = 101;
    LocationTrack locationTrack;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash);

        session = new Session(SplashActivity.this);

        //GPS Tracker
        permissions.add(ACCESS_FINE_LOCATION);
        permissions.add(ACCESS_COARSE_LOCATION);

        permissionsToRequest = findUnAskedPermissions(permissions);
        //get the permissions we have asked for before but are not granted..
        //we will store this in a global list to access later.

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (permissionsToRequest.size() > 0)
                requestPermissions(permissionsToRequest.toArray(new String[permissionsToRequest.size()]), ALL_PERMISSIONS_RESULT);
        }

        locationTrack = new LocationTrack(SplashActivity.this);

        if (locationTrack.canGetLocation()) {
            double longitude = locationTrack.getLongitude();
            double latitude = locationTrack.getLatitude();

            Geocoder gcd = new Geocoder(SplashActivity.this, Locale.getDefault());
            List<Address> addresses = null;
            try {
                addresses = gcd.getFromLocation(latitude, longitude, 1);
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (addresses != null && addresses.size() > 0) {
                String locality = addresses.get(0).getLocality();
                String address = addresses.get(0).getAddressLine(0);
                String state = addresses.get(0).getAdminArea();
                String countryn = addresses.get(0).getCountryName();
                String postalCode = addresses.get(0).getPostalCode();
                String knownName = addresses.get(0).getFeatureName();

                session.setLocation(locality);

                //Toast.makeText(SplashActivity.this,locality +" "+ postalCode + " " + latitude+ " " + longitude,Toast.LENGTH_SHORT).show();
            }
        } else {
            locationTrack.showSettingsAlert();
        }

        welcomeText = (TextView) findViewById(R.id.welcome);
        tf1 = Typeface.createFromAsset(getAssets(), "fonts/Roboto-Light.ttf");
        welcomeText.setTypeface(tf1);
        mLogo = (ImageView) findViewById(R.id.applogo);
        zbgimg = (ImageView) findViewById(R.id.zbgimg);
        zbgimg.setImageResource(R.drawable.splash_screen_option_three);

        animation2();
        animation3();

        new Handler().postDelayed(new Runnable() {

            @SuppressLint("PrivateResource")
            @Override
            public void run() {
                if (session.FbLoggedIn()) {
                    Intent i = new Intent(SplashActivity.this,
                            MainActivity.class);
                    startActivity(i);
                    finish();
                    overridePendingTransition(R.anim.entry, R.anim.exit);
                } else {
                    Intent i = new Intent(SplashActivity.this,
                            LoginActivity.class);
                    startActivity(i);
                    finish();
                    overridePendingTransition(R.anim.entry, R.anim.exit);
                }

            }

        }, 3000);
    }

    private void animation2() {
        mLogo.setAlpha(1.0F);
        Animation anim = AnimationUtils.loadAnimation(SplashActivity.this, R.anim.translate_top_to_center);
        mLogo.startAnimation(anim);
    }

    private void animation3() {
        ObjectAnimator alphaAnimation = ObjectAnimator.ofFloat(welcomeText, "alpha", 0.0F, 1.0F);
        alphaAnimation.setStartDelay(1700);
        alphaAnimation.setDuration(500);
        alphaAnimation.start();
    }

    ///GPS Tracker
    private ArrayList<String> findUnAskedPermissions(ArrayList<String> wanted) {
        ArrayList<String> result = new ArrayList<String>();

        for (String perm : wanted) {
            if (!hasPermission(perm)) {
                result.add(perm);
            }
        }

        return result;
    }

    private boolean hasPermission(String permission) {
        if (canMakeSmores()) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                return (checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED);
            }
        }
        return true;
    }

    private boolean canMakeSmores() {
        return (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP_MR1);
    }

    @TargetApi(Build.VERSION_CODES.M)
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {

        switch (requestCode) {

            case ALL_PERMISSIONS_RESULT:
                for (String perms : permissionsToRequest) {
                    if (!hasPermission(perms)) {
                        permissionsRejected.add(perms);
                    }
                }

                if (permissionsRejected.size() > 0) {

                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                        if (shouldShowRequestPermissionRationale(permissionsRejected.get(0))) {
                            showMessageOKCancel("These permissions are mandatory for the application. Please allow access.",
                                    new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                                                requestPermissions(permissionsRejected.toArray(new String[permissionsRejected.size()]), ALL_PERMISSIONS_RESULT);
                                            }
                                        }
                                    });
                            return;
                        }
                    }

                }

                break;
        }

    }

    private void showMessageOKCancel(String message, DialogInterface.OnClickListener okListener) {
        new AlertDialog.Builder(SplashActivity.this)
                .setMessage(message)
                .setPositiveButton("OK", okListener)
                .setNegativeButton("Cancel", null)
                .create()
                .show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        locationTrack.stopListener();
    }

}

i could able to see the city name in
Toast.makeText(SplashActivity.this,locality +" "+ postalCode + " " + latitude+ " " + longitude,Toast.LENGTH_SHORT).show();

but unable to store it in session. my session.jave is working fine with other Activity. bellow is Logcat:
05-11 22:36:15.966 3836-3836/
zesteve.com.myapplication E/AndroidRuntime:
FATAL EXCEPTION: main
Process: zesteve.com.myapplication, PID: 3836
java.lang.RuntimeException:
Unable to start activity ComponentInfo
{zesteve.com.myapplication/zesteve.com.myapplication.SplashActivity}:
java.lang.NullPointerException: Attempt to invoke interface method
android.content.SharedPreferences$Editor
android.content.SharedPreferences
$Editor.putString(java.lang.String,
java.lang.String)
on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2439)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2499)                                                                                at android.app.ActivityThread.access$900(ActivityThread.java:166)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1360)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5468)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run
(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

Caused by: java.lang.NullPointerException:
Attempt to invoke interface method android.content.SharedPreferences$Editor
android.content.SharedPreferences$Editor.putString(java.lang.String, java.lang.String)
on a null object reference

at zesteve.com.myapplication.Session.setLocation(Session.java:71)
at zesteve.com.myapplication.SplashActivity.onCreate(SplashActivity.java:100)
at android.app.Activity.performCreate(Activity.java:6556)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1108)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2392)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2499)
at android.app.ActivityThread.access$900(ActivityThread.java:166)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1360)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5468)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

A: you are not initialized preference editor you have to make change below
public void setLocation(String city){
        spEditor=sp.edit();//// make sure sp also initialized
        spEditor.putString("UserCity", city);
        spEditor.commit();
    }

A: Your spEditor variable is null because you don't initialize it to anything.
Try this for your session.java constructor.
public Session(Context context) {
  sp = PreferenceManager.getDefaultSharedPreferences(context);
  spEditor = sp.edit();
}

A: Check that all the fields in variable SharedPreferences.Editor spEditor; are initialized. Check your setter method.


text:
Q: Securing Asp.net Web Form Application Can any one let me know what are the various methods of adding security to asp.net application. for example how we can protect the web.config file that contains the database connection information or how we can generally protect our web.config file.
Are their any methods or features like using cryptography or something else to protect our application or we can add any additional security to our application.

A: .config files are, by default, not served by IIS so in that regard you don't have to do anything.
As far as encrypting the connection string, ASP.NET provides that for you out of the box. Read this article: http://msdn.microsoft.com/en-us/library/89211k9b(v=vs.80).aspx


text:
Q: Removing default textbox border animation in xaml I have a global style for all my textboxes like so:
<Style TargetType="TextBox">
    <Style.Triggers>
        <Trigger Property="IsMouseOver" Value="True">
            <Setter Property="BorderBrush" Value="Red"/>
        </Trigger>
    </Style.Triggers>
    <Setter Property="BorderBrush" Value="#007acc"/>
    <Setter Property="Foreground" Value="GhostWhite"/>
    <Setter Property="Background" Value="#49494e"/>
    <Setter Property="HorizontalAlignment" Value="Left"/>
    <Setter Property="Width" Value="250"/>
    <Setter Property="Margin" Value="0,0,0,5"/>
</Style>

When I hover over a textbox with a mouse, its border color will correctly snap to a red color for couple of instants but then the default animation takes over and changes it into the default textbox bluish border color.
How can I disable, or overwrite this animation without having to redefine the entire textbox template? I just want the border color to stay red, while the mouse cursor is hovering over the textbox.

A: One solution to your problem would be to change Template of TextBox
<Style TargetType="{x:Type TextBox}">
   <Style.Triggers>
      <Trigger Property="IsMouseOver" Value="True">
         <Setter Property="BorderBrush" Value="Red"/>
      </Trigger>
   </Style.Triggers>
   <Setter Property="Template">
      <Setter.Value>
         <ControlTemplate TargetType="{x:Type TextBox}">
            <Border Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="1">
               <ScrollViewer x:Name="PART_ContentHost"/>
            </Border>
         </ControlTemplate>
      </Setter.Value>
   </Setter>
   <Setter Property="BorderBrush" Value="#007acc"/>
   <Setter Property="Foreground" Value="GhostWhite"/>
   <Setter Property="Background" Value="#49494e"/>
   <Setter Property="HorizontalAlignment" Value="Left"/>
   <Setter Property="Width" Value="250"/>
   <Setter Property="Margin" Value="0,0,0,5"/>
</Style>

A: This is actually a known issue with property precedence. Basically your local property setter for the border brush is clashing with your trigger. This Msdn article explains it more fully but essentially if you remove
    <Setter Property="BorderBrush" Value="#007acc"/>

your trigger should work correctly


text:
Q: How to Deselect same checkbox again? When i select a checkbox, i am not able to de-select same checkbox again.
I want to de-select same checkbox again when I firstly checked. Here below is the sample of code on which i am working.
checkBoxChanged = (AttibuteCollectionId) => {
        var value = AttibuteCollectionId
        console.log("^^^^^^^^^^^", value)
        this.setState({ checkedCheckBox: !this.state.checkedCheckBox })
        alert(this.state.checkedCheckBox)
    }

{this.state.checkboxAttCollection.map((item, i) => {
                                        return (<View key={item.AttibuteCollectionId} style={{ flexDirection: 'row'}}>

                                            <CheckBox
                                                center
                                                title="yes"
                                                checked={this.state.checkedCheckBox}
                                                //     value={this.state.checked}
                                                onValueChange={() => this.checkBoxChanged(item.AttibuteCollectionId)}
                                            />
                                            <View style={{ justifyContent: 'center' }}>
                                                <Text>{item.AttibuteCollectionName}</Text>
                                            </View>
                                        </View>)
                                    })}

Please provide me solution for this in order to get desired output.

A: Try this way
checkBoxChanged = (index) => {
       const newData = [...this.state.checkboxAttCollection];
       const newData[index].checked = !newData[index].checked;
       this.setState({checkboxAttCollection: newData});
}

{this.state.checkboxAttCollection.map((item, i) => {
       return (

          <CheckBox
            ......
            checked={item.checked || false}
             onValueChange={() => this.checkBoxChanged(i)}
          />
})}


text:
Q: Datastage : Reading excel from window env. shared folder I have an Excel file at a shared location on windows environment. I have data stage server on Unix box. I want to read the excel file and load data to a Teradata table. I need help with reading the excel. One option for me is to transfer file to the server location and access it from there but can i read the excel from the shared folder in windows environment?
I tried to use ftp first in datastage. But getting the below error.
<FTP_Enterprise_18> Error occurred during initializeFromArgs().
<FTP_Enterprise_18> uri : ftp://server/path/file.xlsx is not valid remote file.
<main_program> Creation of a step finished with status = FAILED.

A: No - it is not possible to read it from a remote location so you will need to tranfer it first (if the shared location is not a SAMBA mount on the Unix maschine).
You can use the "Unstructured data" stage to read the Excel fle one it is on the Unix server.


text:
Q: Website doesn't scroll on Android mobile I have been reading a lot but I can't find a solution.
I'm working on a website that works perfectly in Desktop, iPhone and iPad, but it doesn't scroll in Android mobile.
I add to the mobile @media:
body {
    overflow: scroll;
    -webkit-overflow-scrolling: touch;
}

And the header and footer have position as relative (I read 'fixed' value does make troubles with Android) but it not solve the problem.
Does anybody know how to solve it?


text:
Q: Convert HTML Time into Java Time Object I am getting startTime and endTime value from html5 input type. I am getting it in Servlet in String.
I want to convert it into Java Date Object so I can use methods like before and after for comparing Time.
    String startTimeValue = request.getParameter("startTime");
    String endTimeValue = request.getParameter("endTime");
    SimpleDateFormat sdf = new SimpleDateFormat("hh:mm");
    Date startTime = sdf.parse(startTimeValue);
    Date endTime = sdf.parse(endTimeValue);
    sdf.format(startTime);
    sdf.format(endTime);
    System.out.println(endTime.before(startTime));

Any help would be appreciated.

A: I think you're able to do the parsing right this way :
String DateString = request.getParameter("date");
//SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss");
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
Date date = sdf.parse(myDateString);

Calendar calendar = GregorianCalendar.getInstance(); // creates a new calendar instance
calendar.setTime(date);   // assigns calendar to the given date
int hour = calendar.get(Calendar.HOUR);
int minute; /... similar methods for minutes and seconds

A: I am achieving it using the following Code Snippet
    String startTimeValue = request.getParameter("startTime");
    String endTimeValue = request.getParameter("endTime");

    String[] time1 = startTimeValue.split(":");
    Date date1 = new Date();
    date1.setHours(Integer.parseInt(time1[0]));
    date1.setMinutes(Integer.parseInt(time1[1]));
    date1.setSeconds(0);
    String[] time2 = endTimeValue.split(":");
    Date date2 = new Date();
    date2.setHours(Integer.parseInt(time2[0]));
    date2.setMinutes(Integer.parseInt(time2[1]));
    date2.setSeconds(0);

    System.out.println(date2.after(date1));


text:
Q: Problems with string pattern matching Asterisk complains that one extension does not exist:
[Mar 14 11:07:22] NOTICE[28139]: chan_sip.c:22622 handle_request_invite: Call from 'sippartner1' (99.23.69.31:5060) to extension 'iax2partner69#4000' rejected because extension not found in context 'carriers'.

But I have indeed that pattern defined in context carriers:
pbx1*CLI> dialplan show @carriers

  '_iax2.' =>       1. Set(exten=${EXTEN:5})                      [pbx_config]
                    2. Set(iax2partner=${CUT(exten,#,1)})         [pbx_config]
                    3. Set(iax2exten=${CUT(exten,#,2)})           [pbx_config]
                    4. Log(NOTICE,EXTEN=${EXTEN} exten=${exten} iax2partner=${iax2partner} iax2exten=${iax2exten}) [pbx_config]
                    5. Dial(IAX2/${iax2partner}/${iax2exten})     [pbx_config]

This is the carriers source:
[carriers]

...

exten => _iax2.,1,Set(exten=${EXTEN:5})
exten => _iax2.,n,Set(iax2partner=${CUT(exten,#,1)})
exten => _iax2.,n,Set(iax2exten=${CUT(exten,#,2)})
exten => _iax2.,n,Log(NOTICE,EXTEN=${EXTEN} exten=${exten} iax2partner=${iax2partner} iax2exten=${iax2exten})
exten => _iax2.,n,Dial(IAX2/${iax2partner}/${iax2exten})

Why is asterisk not matching against pattern _iax2.?

A: quick and dirty approach
exten => _[i][a][x][2].,1,Set(exten=${EXTEN:5})
same=>n,Set(iax2partner=${CUT(exten,#,1)})
same=>n,Set(iax2exten=${CUT(exten,#,2)})
same=>n,Log(NOTICE,EXTEN=${EXTEN} exten=${exten} iax2partner=${iax2partner} iax2exten=${iax2exten})
same=>n,Dial(IAX2/${iax2partner}/${iax2exten})


text:
Q: CollectionView generating SIGABRT on pushViewController Below function call generating Thread 1: EXC_BREAKPOINT (code=1, subcode=0x189d35a80).
func showChatView(message: ChatMessage) {
        DispatchQueue.main.async {
            if self.chatViewController == nil  {
                let mainStoryboard : UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
                self.chatViewController = mainStoryboard.instantiateViewController(withIdentifier: "VAChatViewController") as? VAChatViewController
                self.chatViewController?.delegate = self;
            }
            self.chatViewController?.messages += [message]

            self.navigationController?.pushViewController(self.chatViewController!, animated: true, completion: {
                let buttonMessage = self.chatViewController?.messages.last
                let hasButtons = buttonMessage?.hasButtons
                if hasButtons! {
                    let vaButtonModel = ChatMessage(buttons: buttonMessage?.buttons)
                    self.chatViewController?.addNewMessage(vaButtonModel)
                }
            })
        }
    }

One more thing- VAChatViewController implements collectionView to display incoming chat events, which is a response to a string message "xyz". In collectionView delegates I get the array[count] > 0 but it is not calling the collectionView: cellForItemAt after numberOfItems and crashes with SIGABRT followed by above crash. Any idea?

A: Silly mistake. I am calling showChatView: multiple times for the reason I made a single object of ChatViewController, but I forgot to put pushViewController under any check. And, thats the reason of crash. Thanks


text:
Q: How to integrate rubocop with Rake? rubocop is a code style checker for Ruby. A similar tool to rubocop, Cane, can be integrated with Rake. I prefer rubocop to Cane since rubocop makes checks based on the Ruby Style Guide and it seems to spot more problems. To automate the process of style checking I would like to integrate rubocop with Rake so that the build fails if code quality is lacking.
Gem already supports adding tests to packages via Rake. I would like to do the same with style checks so that style checks are run along with the tests. How can I do this?
If it helps to start with a Rakefile here is one:
# -*- coding: utf-8; mode: ruby -*-

require 'bundler/gem_tasks'
require 'rake/testtask'

Rake::TestTask.new do |t|
  t.libs << 'test'
  t.test_files = FileList['test/unit/test*.rb']
end

desc 'Run tests'
task default: :test

A: As of version 0.10.0 rubocop contain a custom rake task that you can use. Just put the following in your Rakefile
require 'rubocop/rake_task'

RuboCop::RakeTask.new

Make sure to use upper-case 'R' and 'C' or you will get a NameError.

A: I highly recommend,
require 'rubocop/rake_task'

RuboCop::RakeTask.new(:rubocop) do |t|
  t.options = ['--display-cop-names']
end

This uses the rubocop's own rake tasks and allows you to pass options if you like.

A: You will probably find https://github.com/yujinakayama/guard-rubocop useful if you use Guard for your RSpec tests. It enables Rubocop to give you instant feedback as soon as you save the file,  along with your test results.

A: I needed to do something similar myself, and ended up looking in the internal source code of the RuboCop::RakeTask here:
https://github.com/rubocop/rubocop/blob/a34a1c2c2dd1fa6d90ffd06c183421a495a0717c/lib/rubocop/rake_task.rb#L40-L43
      require 'rubocop'

      cli = CLI.new
      puts 'Running RuboCop...' if verbose
      result = cli.run(options)
      abort('RuboCop failed!') if result.nonzero? && fail_on_error

You can actually invoke similar code directly in your own codebase / rake task.
I ended up writing a little wrapper module I can call to, with some default flags that I always want to be applied:
module RubocopCli
  def self.run!(*args)
    require "rubocop"
    cli = RuboCop::CLI.new
    result = cli.run(["--display-cop-names", "--force-exclusion", "--fail-level", "autocorrect", *args])
    raise "RubocopCli.run! Linting failed." if result.nonzero?
  end
end

Then you can call it with additional args from any task, or app code, like:
files_to_lint = %w[lib/whatever.rb spec/lib/whatever_spec.rb]
RubocopCli.run!("--auto-correct", *files_to_lint)

A: You can shell out via Rake with the options you prefer:
  desc 'Run Rubocop with options'
  task rubocop: :environment do
    sh 'bundle exec rubocop -D --format offenses --format progress || true'
  end

I then recommend modifying the default task to include the output. The trick is to clear the task and then add back what you want. Note the need to end with || true so that an error from Rubocop will not prevent the next task from running. Here's what I do, which also uses parallel tests:
task(:default).clear.enhance ['parallel:parallel_prepare', 'parallel:spec',
                              'parallel:features', 'lint:rubocop',
                              'lint:rails_best_practices']

A: I would recommend shelling out to the rubocop program. It's the simplest solution. Just add this to your Rakefile:
task test: :rubocop

task :rubocop do
  sh 'rubocop'
end


text:
Q: Converting a curve to a diagonal line with Cairo (in Avant Window Navigator on Linux) I'm currently trying to modify Avant Window Navigator's "Lucido mode" code in order to replace the separator's/s' curves with diagonal lines.
The part of the (Cairo) code that governs the curviness is present from lines 330 to 334 in the following file on GitHub: link
{ /* Oblique */
  gfloat xm = ( *xs + xf ) / 2.0;
  cairo_curve_to (cr, xm, *ys, xm, yf, xf, yf);
}

In order to make the goal easier to understand, here is an image of what AWN Lucido looks like right now and what I want it to look like:

I would be very grateful if anyone could help me with getting the code right to make the separator a straight, diagonal line.
Thank you very much for your time :)

A: Info on drawing curves with Cairo can be found here.
A four point Bezier curve looks like this:

cairo_curve_to takes the current pen position for p0 and its arguments are the next 3 points.
So you could make cairo_curve_to draw a straight line by passing the same point for each argument. This is kinda wasteful but not a serious issue for you probably.
It looks like if you pass the end position for both arguments of _line_from_to it will degenerate to drawing a straight line, as you want. e.g. if the call to that function was _line_from_to(cr, &x, &y, x2, y2) change it to _line_from_to(cr, &x2, &y2, x2, y2).
Alternatively, change the code for _line_from_to to be
static void
_line_from_to ( cairo_t *cr,
                gfloat *xs,
                gfloat *ys,
                gfloat xf,
                gfloat yf)
{
  cairo_line_to (cr, xf, yf);
  *xs = xf;
  *ys = yf;
}

If you want more info on cairo_curve_to, see this example.


text:
Q: Magento Connect no longer works after migration I moved a site from a dev server to production and Magento Connect no longer works.  I've seen several posts on the /downloader/perlib fix but I'm using 1.9.1 and that file isn't there.

A: Download a fresh copy of Magento and put the downloader folder in the root of your installation. Is this or bad permissions.


text:
Q: C# project won't compile anymore due to missing reference to Microsoft.Office.Tools.Common.4.0.Utilities It used to compile just fine but as of today it won't anymore - I'm using Visual Studio 2019 and I tried installing the Visual Studio Tools for Office Runtime 2010 and closing/reopening the project but that didn't help...

A: Try to delete the .vs, the bin and the obj folders of your project. Open your project again and rebuilt it. This steps will most likely resolve your problem.

A: I installed the Office development workload from the Visual Studio installer and that resolved the reference for me. No idea how it was working before...


text: Q: Is the transpose of $T$ also the dual map of $T$? Suppose I have $T: V \to W$. Then $T$ defines a map $T': W' \to V'$ that some sources (e.g. Axler) call the dual map of $T$. And $T$ defines a map $T^t: W' \to V'$ that some sources (e.g. Hoffman and Kunze) call the transpose of $T$. My question is: are these synonyms?


text:
Q: If possible to run a Docker Compose comand before a job exe in GitLab CI I am new to GitLabCI, it seems GitLab CI is docker everywhere.
I was trying to run a Mariadb before run tests. In Github actions, it is very easy, just docker-compose up -d command before my mvn.
When came to GitLab CI.
I was trying to use the following job to archive the purpose.
test:
  stage: test
  image: maven:3.6.3-openjdk-16
  services:
    - name: docker
  cache:
    key: "${CI_JOB_NAME}"
    paths:
      - .sonar/cache
      - .m2/repository
  script: |
    docker-compose up -d
    sleep 10
    mvn clean verify sonar:sonar

But this does not work, docker-compose is not found.

A: You can make use of docker-dind docker-dind and run the docker commands inside another docker container.
But there is limitation to run docker-compose by default. It is recommended to build a custom image on top of DIND and push it to gitlab image registry. So that can be used across your jobs


text:
Q: Trouble installing sleuthkit package BUILD FAILED
/home/ABC/Downloads/sleuthkit-4.1.3/bindings/java/build.xml:119: The following error occurred while executing this line:
/home/ABC/Downloads/sleuthkit-4.1.3/bindings/java/build.xml:98: impossible to resolve dependencies:
    resolve failed - see output for details

Total time: 40 seconds
make[2]: *** [all-local] Error 1
make[2]: Leaving directory `/home/ABC/Downloads/sleuthkit-4.1.3/bindings/java'
make[1]: *** [all-recursive] Error 1
make[1]: Leaving directory `/home/ABC/Downloads/sleuthkit-4.1.3/bindings/java'
make: *** [all-recursive] Error 1
root@ubuntu:/home/ABC/Downloads/sleuthkit-4.1.3#

A: I think you are experiencing the same problem as described here which says there is some problem in the bindings/java/ivysettings.xml in locating the repositories for sqlite-jdbc-3.8.0-SNAPSHOT.jar.
Currently it looks in http://oss.sonatype.org/content/repositories/snapshots/org/xerial/sqlite-jdbc/3.8.0-SNAPSHOT/sqlite-jdbc-3.8.0-SNAPSHOT.jar
but the file Ivy wants is actually at
https://oss.sonatype.org/content/repositories/snapshots/org/xerial/sqlite-jdbc/3.8.0-SNAPSHOT/sqlite-jdbc-3.8.0-20130827.035027-1.jar


text:
Q: GetMessage(WM_CHAR) override? Making sure all other Window Hooks activate I'm looking for a way to intercept a GetMessage() call for WM_CHAR in an external process (only the active window, to be specific). I'm hesitant to use SetWindowsHookEx() - I want to make absolutely sure that the widest possible range of programs which may modify keyboard input have a chance to fire first. Does anyone have any suggestions?
Context: I'm building an application meant to generate a visual of the current keyboard layout. However, I'm looking to make it as compatible with third-party keyboard remapping software as possible (including user-made AutoHotkey scripts and the like). When triggered via hotkey, my program sends key-presses to the active window (scancodes + appropriate virtual keys), which should get processed by its window procedure... thus triggering both any remap software based on system-wide hooks and that which has been programmed to only remap keys within the active application... and then my program would intercept the resulting WM_CHAR / WM_UNICHAR / WM_DEADCHAR message, from which it reconstructs the keyboard layout. In effect, the character messages should never reach the active window for output. (I might replace them with no char messages of some kind for compatibility.)
P.S. Sorry, this is probably terrible etiquette - posting a question first thing after registering - but I've been researching this issue for many nights now, and I still haven't figured out an optimum solution! I'm working primarily from AutoHotkey, and I'm fully willing to share other methods I've considered for getting the true current keyboard layout, but they all have their limitations re: playing nice with remapping software.

A: Put '~' (without the quotes) before your hotkey.
This will run whatever code you have for you hotkey and allow the keystroke to fall through.
Example:
~^a::
MsgBox, You pressed Ctrl+a
return


text:
Q: how to get match id by jquery how to get match (id) by jquery
I want to get (id) in (href) Between (span)
If the code
here
HTML

   123
   hgi

   123
   hgi

   123
   hgi

jquery
$(".zero span").each(function(){
$(this).find("a").attr("href").match(/id=/);

});

but Error >_<
why ?
and
how ?
i want
id=222
id= 333
id= 111

A: Some of your  elements do not have an href property. attr() will return undefined in this case. When trying to call match() on undefined, JavaScript throws an error.
Fix it with:
$(".zero span").each(function(){
    href = $(this).find("a").attr("href");
    if (href !== undefined) {
        href.match(/id=/);
    }
});

Or change the selector to include a[href].
Outside:
$(".zero span a[href]").each(function(){
    $(this).attr("href").match(/id=/);
});

Inside:
$(".zero span").each(function(){
    $(this).find("a[href]").attr("href").match(/id=/);
});

A: You need this:
$(".zero span").each(function(){
   alert($(this).find("a").attr("href").match(/id=\d+/)[0]);
});

A: Have you tried
$(this).find("a").attr("href").match(/id=.*/);

That will match id and all characters after.


text:
Q: Apply computations basing on column name pattern How do I apply computations on data frame columns basing on name patterns. I'm looking for a more R-like solution / more readable code:
df <- data.frame(xA1 = sample(x = 1:4, size = 10, replace = TRUE),
                 yA1 = sample(x = 1:4, size = 10, replace = TRUE),
                 xA2 = sample(x = 1:4, size = 10, replace = TRUE),
                 yA2 = sample(x = 1:4, size = 10, replace = TRUE),
                 xB1 = sample(x = 1:4, size = 10, replace = TRUE),
                 yB1 = sample(x = 1:4, size = 10, replace = TRUE),
                 xB2 = sample(x = 1:4, size = 10, replace = TRUE),
                 yB2 = sample(x = 1:4, size = 10, replace = TRUE))

# df$A1 <- weighted.mean(x = c(df$xA1, df$yA1),
#                        w = c(0.25, 0.75))
# repeat for A2, B1, B2

for (middle in c('A', 'B')) {
 for (right in 1:2) {
  df[paste0(middle, right)] <- apply(X = subset(df, select = c(paste0('x', middle, right), paste0('y', middle, right))),
                                     MARGIN = 1,
                                     FUN = weighted.mean,
                                     w = c(0.25, 0.75))
 }
}

A: This is substantially longer, but arguably more readable if you don't mind a tidyverse approach:
bind_cols(df,

  # reshape long into multiple columns for xy, grp, and num
  df %>% mutate(row = row_number()) %>%
    pivot_longer(-row, names_to = c("xy","grp", "num"), names_pattern = "(.)(.)(.)") %>%

    # calculate weighted sum for each row/grp/num combination
    group_by(row, grp, num) %>%
    summarize(wtd_sum = sum(value * if_else(xy == "x", 0.25, 0.75))) %>%
    ungroup() %>%

    # reshape wide
    select(-row) %>%
    pivot_wider(names_from = c(grp, num), values_from = wtd_sum)
)