text:
Q: Align set of points to a calibration chessboard in Python I am trying to align a set of points forming a box to an opencv 9*6 calibration chessboard with an Intel RealSense D435 3D camera. I'm trying to modify one of the exemples of the Python SDK to do so, which has a Kabsch algorithm transformation function already inside. The example is the one to add bounding boxes to objects.
My problem is that whenever I try to align my points (which are calculated using an existing corner of the chessboard as a starting point and adding the length, width and height of the box) using this function, there is always a difference to where it should be.
My code to transform the coordinates of my points is basically
point_b = transformation_devices[device].inverse().apply_transformation(np.asarray([[(x + width)],[y], [z]]))
#used to calculate the position of the point and directly transform it, the apply_transformation() function is the built-in transformation function of the example

b_x, b_y = rs.rs2_project_point_to_pixel(intrinsics, b)
#to return to 2D coordinates and display the box using opencv

Do you see any blatantly obvious error that I missed in my method ? Is there a better way to try to align 3D points to a chessboard ?
Edit : What I'm trying to achieve is to align the purple box in the image to the chessboard, a bit like the green one
Image


text:
Q: CloudWatch custom EC2 memory metric and alarm with AutoScaling policy My goal is to test AutoScaling based on memory used on my EC2 instances.
To monitor my EC2 instance memory, I installed CloudWatch agent on my EC2 Instance and created and configured my CloudWatch agent configuration file, as explained here:
https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/Install-CloudWatch-Agent.html
https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/create-cloudwatch-agent-configuration-file.html
{
        "metrics": {
                "append_dimensions": {
                        "AutoScalingGroupName": "${aws:AutoScalingGroupName}",
                        "ImageId": "${aws:ImageId}",
                        "InstanceId": "${aws:InstanceId}",
                        "InstanceType": "${aws:InstanceType}"
                },
                "metrics_collected": {
                        "cpu": {
                                "measurement": [
                                        "cpu_usage_idle",
                                        "cpu_usage_iowait",
                                        "cpu_usage_user",
                                        "cpu_usage_system"
                                ],
                                "metrics_collection_interval": 60,
                                "totalcpu": false
                        },
                        "disk": {
                                "measurement": [
                                        "used_percent",
                                        "inodes_free"
                                ],
                                "metrics_collection_interval": 60,
                                "resources": [
                                        "*"
                                ]
                        },
                        "diskio": {
                                "measurement": [
                                        "io_time"
                                ],
                                "metrics_collection_interval": 60,
                                "resources": [
                                        "*"
                                ]
                        },
                        "mem": {
                                "measurement": [
                                        "mem_used_percent"
                                ],
                                "metrics_collection_interval": 60
                        },
                        "swap": {
                                "measurement": [
                                        "swap_used_percent"
                                ],
                                "metrics_collection_interval": 60
                        }
                }
        }
}

Once I start the CloudWatch agent on the EC2 Instance, the custom metrics work ok and I can see them on CloudWatch.
sudo /opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-ctl -a fetch-config -m ec2 -c ssm:configuration-parameter-store-name -s

I created an AMI with this EC2 Instance and created an AutoScaling group with this AMI.
I then set up an alarm based on the custom metric "mem_used_percent" (when >=50) and used it as an AutoScaling Group Policy (add 1 Instance). Image attached.

I connect to the EC2 instance and increase the memory used using "Stress". The alarm is raised, the AutoScaling policy is triggered and a new EC2 instance is created.
The problem I see is that I am creating an alarm on an specific EC2 Instance, instead of the whole AutoScaling Group, and once the initial EC2 Instance is terminated, the alarm does not make sense any more.
How could I configured the same idea but for the AutoScaling Group?
Thanks.

A: From AWS documentation,
For CloudWatch agent, You can aggregate custom metric using aggregation_dimensions
"metrics": {
  "cpu":{...}
  "disk":{...}
  "aggregation_dimensions" : [["AutoScalingGroupName"], ["InstanceId", "InstanceType"]]
}

https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch-Agent-common-scenarios.html
For those who are still using the old perl script, check the options :
--aggregated
--auto-scaling

https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/mon-scripts.html

A: I have taken the same approach but with no success.
{
"metrics": {
    "metrics_collected": {
        "LogicalDisk": {
            "measurement": [
                "% Free Space"
            ],
            "metrics_collection_interval": 60,
            "resources": [
                "*"
            ]
        },
        "Memory": {
            "measurement": [
                "% Committed Bytes In Use"
            ],
            "metrics_collection_interval": 60
        },
        "Paging File": {
            "measurement": [
                "% Usage"
            ],
            "metrics_collection_interval": 60,
            "resources": [
                "*"
            ]
        },
        "PhysicalDisk": {
            "measurement": [
                "% Disk Time"
            ],
            "metrics_collection_interval": 60,
            "resources": [
                "*"
            ]
        },
        "Processor": {
            "measurement": [
                "% User Time",
                "% Idle Time",
                "% Interrupt Time"
            ],
            "metrics_collection_interval": 60,
            "resources": [
                "_Total"
            ]
        }
    },
    "append_dimensions": {
        "ImageId": "${aws:ImageId}",
        "InstanceId": "${aws:InstanceId}",
        "InstanceType": "${aws:InstanceType}",
        "AutoScalingGroupName": "${aws:AutoScalingGroupName}"
    },
    "aggregation_dimensions" : [["AutoScalingGroupName"]]
}

}
When i review the output in the cloudwatch management console, i do not see the aggregation by the AutoScalingGroupName under All>CWAgent

redpajama_set_name: RedPajamaStackExchange


text:
Q: Automate Jenkins Pipeline to run multiple times I am using a Jenkins pipeline to process files for a UAT.
Stages are like:

*

*Get the files

*Put them in the right directory

*Run bash script

*Run another bash script

*Run another bash script

*Send results

I would like to be able to run 1 or more times this pipeline based on the number of EODs I want to run.
So if EODs are:
20180720, 20180721, 20180722

I want the pipeline to run 3 times.
So;
for eod in '20180720, 20180721, 20180722'
run pipeline $eod
done

I know you can launch it with the url and parameters like John mentions below, and I am looking for a more simple solution, if there is any.
How can I do this?


text:
Q: Window docking advice for Mac I'm from a Windows programming background when writing tools, but have been programming using Carbon and Cocoa for the past year.  I have introduced myself to Mac by, I admit it, hiding from UI programming.  I've been basically wapping my OpenGL code in a view, then staying in my comfort zone using my platform agnostic OpenGL C++ code as usual.
However, now I want to start porting one of my more sophisticated applications to Mac OS.
Typically I use the standard Visual Studio dockable MDI approach, which is excellent, but very Windows-like.  From using a Mac primarily now for a while, I don't tend to see this sort of method used for Mac UIs.  Even Xcode doesn't support the idea of drag and drop/dockable views, unfortunately.  I see docked views with splitter panels, but that's about it.
The closest thing I've seen to the Visual Studio approach is Photoshop CS4, which is pretty nice.
So what is the general consensus on this?  Is there are more Mac-like way of achieving the same thing that I haven't seen?  If not, I'm happy to write a window manager in Cocoa myself, so that I can finally delve in an learn what looks like an excellent API.
Note, I don't want to use QT or any other cross-platform libraries.  The whole point is that I want to make a Mac app look like a Mac app, leave the Windows app looking like a Windows app.  I always find the cross-platform libraries tend to lose this effect, and when I see a native Mac UI, with fancy Cocoa transitions and animations, I always smile.  It's also a good excuse for me to learn Cocoa.
That being said, if there is an Open Source Cocoa library to do this, I'd love to know about it!  I'd love to see how someone else achieves this, and would help smooth the Cocoa learning curve.
Cheers,
Shane
UPDATE: I forgot to mention a critical point.  I support plugins, which can have their own UI to display various plugin specific information.  I don't know which plugins will be loaded and I don't know where their UI will live, if I don't support docking.  I'd love to hear people's thoughts on this, specifically: How do I support a plugin view architecture, if the UI can't change?  Where do I put the plugin views?

A: +1 to Ken's answer.
From a user perspective unless its integral to the app like it is in Adobe CS or Eclipse i want everything as concise as possible and all the different options and displays out of my way so i can focus on the document.
I think you will find with mac users that those who have the "user skill" to make use of rearranging panels will in most cases opt for hot key bindings instead, and those who dont have that level of "skill" youre just going to confuse.
I would recommend keeping it as simple as possible.

A: One thing that's common among many Mac apps is the ability to hide all the chrome and focus on your content.  That's the point behind the "tic tac" toolbar control in the top right corner of many windows.  A serious weakness of many docking UIs is that they expect you to have the window take up most of the screen, because the docked panels can obscure content.  Even if docked panels are collapsable, the space left by them is often just wasted and filled with white space.  So, if you build a docking panel into your interface, you should expect it to be visible most of the time.  For example, iTunes' source list is clearly designed to be visible all the time, but you can double-click a playlist to open it in a new window.
To get used to the range of Mac controls, I'd suggest you try doing some serious work with some apps that don't have a cross-platform UI; for example, the iWork apps, Interface Builder or Preview.  Take note of where controls appear and why—in toolbars, in bottom bars, in inspectors, in source lists/sidebars, in panels such as IB's Library or the Font and Color panels, in contextual HUDs.  Don't forget the menu bar either.  Get an idea of the feel of controls—their responsiveness, modality, sizing, grouping and consistency.  Try to develop some taste—not everything is perfect; just try iCal if you want to have something to make fun of.
Note that there's no "one size fits all" for controls, which can be an issue with docking UIs.  It's important to think about workflow: how commonly used the control would be, whether you can replace it with direct manipulation, whether a visible indication of its state is necessary, whether it's operable from the keyboard and mouse where appropriate, and so forth. Figure out how the control's placement and behavior lets the user work more efficiently.
As a simple example of example of a good versus bad control placement and behavior in otherwise-decent applications, compare image masking in OmniGraffle and Keynote.  In OmniGraffle, this uses the Image inspector where you have to first click on an unlabeled button ("Natural size") in order to enable the appropriate controls, then adjust size and position away in a low-fidelity fashion with an image thumbnail or by typing percentages into fields.  Trying to resize the frame directly behaves in a bizarre and counterintuitive fashion.
In Keynote, masking starts with a sensibly named menu item or toolbar item, uses a HUD which pops up the instant you click on a masked image and allows for direct manipulation including a sensible display of the extent of the image you're masking.  While you're dragging a masked image around, it even follows the guides. Advanced users can ignore the HUD entirely, just double-clicking the image to toggle mask editing and using the handles for sizing.  It should be easy to see, with a few caveats (e.g. the state of "Edit Mask" mode should be visible in the HUD rather than just from the image; the outer border of the image you're masking should be more effectively used) Keynote is substantially better at this, in part because it doesn't use an inspector.
That said, if you do have a huge number of options and the standard tabbed inspector layout doesn't work for you, check out the Omni Group's OmniInspector framework.  Try to use it for good, and hopefully you'll figure out how to obsess over UI as much as you do over graphics now :-)

A: Coming from a Windows background, you feel the need to have docking windows, but is it really essential to the app?  Apple's philosophy (in my opinion) is that the designer knows better than the user how things should look and work. For example, iTunes is a pretty sophisticated app, but it doesn't let you change the UI around, change the skin, etc., because Apple wants to keep it consistent. They offer the full view, the mini player, and a handful of different viewing options, but they don't let you pull the source list off into a separate window, or dock it in other positions.  They think it should be on the left, so there it stays...
You said you "want to make a Mac app look like a Mac app", and as you pointed out, Mac apps don't tend to have docking windows. Therefore, implementing your own docking windows is probably a step in the wrong direction ;)

A: (running in slow motion, reaching out in panic) Nnnnnoooooooo!!!!!
:-) Seriously, as I mentioned in reply to Ken's excellent answer, trying to force a "Windowsism" on an OS X UI is definitely a bad idea. In my opinion, the biggest problem with Windows UI is third-party developers inventing new and inconsistent ways of presenting UI, rather than being consistent and following established conventions. To a Mac user, that's the sign of a terrible application. It's that way for a reason.
I encourage you to rethink your UI app's implementation from the ground up with the Mac OS in mind. If you've done your job well, the architecture and model (sans platform-specific implementation) should clearly translate to any platform.
In terms of UI, you've been using a Mac for a year, so you should have a pretty good idea of "the norm". If you have doubts, it's best to post a question specifically detailing what you need to present and your thoughts on how you might do it (or asking how if you have no idea).
Just don't whack your app with the ugly stick by forcing it to behave as if it were running in Windows when it's clearly not. That's the kiss of death for an app to Mac users.


text:
Q: Convert Gatsby Website to WebFlow of WordPress? The marketing manager of esper.io (built in gatsby) said that it's hard for them to do updates on the site (they need to contact the developer every time) so they're thinking about rebuilding the whole site in WebFlow or WordPress. The blog on site is headless WordPress.
I work mostly with WordPress and WebFlow and have zero experience with Gatsby or React.
I was wondering is there any simple way how to do updates on a Gatsby website so the marketing team can do it themselves? (they're non coders)
They love the headless WodPress blog because they're all familiar with WordPress and can write blog posts  without coding.
I'll appreciate any tips or pointing in  a direction.
Thank you, Josef

A: I assume you still have a kind of deployment-process... means if you change something at the source-code and upload to your git-repository, the page will be rebuild and deployed automatically.
So if you search for an nice & easy way to edit the content of your page, I recommend to have a look at TinaCMS
It's also optimized for gatsby and - if ones integrated in gatsby - it's very easy to edit the content of the Page.


text:
Q: JavaScript changing default file name? How would I go about changing the name of a clip that is going to be downloaded by the client on a website? Each video clip currently downloaded is a default name how do I go about customising it?

A: Yes, you can change file name as per your own logic. and will be download in client browser as per following logic :
var blob = b64toBlob(b64Data, contentType, false);
var blobUrl = URL.createObjectURL(blob);
var a = document.createElement("a");
document.body.appendChild(a);
a.style.display = 'none'
a.href = blobUrl;
a.download = fileName;
a.click();
window.URL.revokeObjectURL(blobUrl);

FileName can be set as per your own logic and append file extension
b64Data = your file's binary data, contentType = content type of your file.
for example for image it will be "data:image/png;base64,"


text:
Q: XML not getting parsed into tableview I am trying to Parse a XML data into table view but the data is not getting reflected .I am implementing a refresh button which loads the data from XML once clicked. Can somebody please tell me what i am doing wrong ? Below is my code
//
//  Tab1.m
//  Sample
//
//  Created by Vishal Thakur on 10/3/13.
//  Copyright (c) 2013 __MyCompanyName__. All rights reserved.
//

#import "Tab1.h"
#import "TAB2.h"
#import "Fruit.h"

@interface Tab1() {
 TAB2 *t2;
 Fruit *aFruit;
 NSString *mark;
}
@property (retain, nonatomic) NSArray *fruits;
@end

@implementation Tab1
@synthesize table;
@synthesize fruits;
@synthesize fruitsDictionary;
- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
        self.fruits = [NSArray arrayWithObjects:@"Apple", @"PineApple", @"Orange", @"Banana", @"Pear", @"Kiwi", @"Strawberry", nil];
         NSString *filePath = [[NSBundle mainBundle] pathForResource:@"Names" ofType:@"xml"];

         NSXMLParser *parser = [[NSXMLParser alloc] initWithData:[NSData dataWithContentsOfFile:filePath]];

         [parser setDelegate:self];
         [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];

    UIView* customView = [[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, 300.0, 44.0)];
    UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [button setFrame:CGRectMake(50, 10, 80, 40)];
   [button setTitle:@"Refresh" forState:UIControlStateNormal];
    [button addTarget:self action:@selector(RefreshTable:) forControlEvents:UIControlEventTouchUpInside];    [customView addSubview:button];

    self.table.tableHeaderView = customView;

    }
    return self;
}

-(void)RefreshTable:(id)sender {

    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
      NSString *filePath = [[NSBundle mainBundle] pathForResource:@"Names" ofType:@"xml"];

     NSXMLParser *parser = [[NSXMLParser alloc] initWithData:[NSData dataWithContentsOfFile:filePath]];

   [parser setDelegate:self];

    if ([parser parse]) {
            NSLog(@"successful");
      NSLog(@"::::%@",fruitsDictionary);
      ///////DetailScreen *ds=[[DetailScreen alloc]init];

       [self.table reloadData];
    }
   else {
       NSLog(@"Failure!");
   }

   [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section;
{
    NSInteger count= [self.fruits count];
    return count;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView;
{
    return 1;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    NSArray *keys = [fruitsDictionary allKeys];
   NSDictionary *local = [NSDictionary dictionaryWithObject:[fruitsDictionary valueForKey:[keys objectAtIndex:indexPath.row]]forKey:[keys objectAtIndex:indexPath.row]];

    NSLog(@"%@",keys);
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Fruit" message:(NSString *)[keys objectAtIndex:indexPath.row] delegate:self cancelButtonTitle:@"cancel" otherButtonTitles:@"other", nil];
    [alert show];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"Cell Identifier";
 UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (!cell)
    {
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    NSArray *keys = [fruitsDictionary allKeys];
    NSString *fruit = [keys objectAtIndex:[indexPath row]];
    [cell.textLabel setText:fruit];

    return cell;
}

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{
    if ([elementName isEqualToString:@"Fruit"]) {
        aFruit = [[Fruit alloc] init];
        if (!fruitsDictionary) {
            fruitsDictionary = [[NSMutableDictionary alloc] init];
        }
    }
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
    currentElement = nil;
    currentElement = [[NSMutableString alloc] initWithString:string];
}

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
    if ([elementName isEqualToString:@"Name"]) {
        aFruit.name = currentElement;
    }
    else if ([elementName isEqualToString:@"Description"]) {
        aFruit.description = currentElement;
    }
    else if ([elementName isEqualToString:@"Fruit"]) {
        [fruitsDictionary setObject:aFruit forKey:aFruit.name];
    }
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];

    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;

    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}

- (void)viewDidUnload
{
    [self setTable:nil];
    [self setFruits:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - Table view data source

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

#pragma mark - Table view delegate

@end

A: You can use the parserDidStartDocument: method for doing this.
According to NSXMLParserDelegate:

parserDidEndDocument:
Sent by the parser object to the delegate when it has successfully
  completed parsing.
- (void)parserDidEndDocument:(NSXMLParser *)parser
Parameters
parser
A parser object.

Availability
Available in iOS 2.0 and later.
Available as part of an informal protocol prior to iOS 4.0.

See Also
– parserDidStartDocument:

Declared In NSXMLParser.h

You can implement it like:
- (void)parserDidStartDocument:(NSXMLParser *)parser
{
   [self.table reloadData];
}


text:
Q: MySQL and lock a table, read, and then truncate I am using mysqldb in python.
I need to do the following for a table.
1) Lock
2) Read
3) Truncate the table
4) Unlock

When I run the below code, I get the below error.  So, I am rather unsure on how to lock a table for reading it, then truncating the table.  I need to be sure that no other connection reads the data.
asin_list = []
    conn = MySQLdb.connect(host=parms['database']['operations']['host'],user=parms['database']['operations']['username'],passwd=parms['database']['operations']['password'],db=parms['database']['operations']['database'])
    cursor = conn.cursor()

    query = "LOCK TABLES asin_one_time_only READ"
    cursor.execute(query)
    print 'fu1'

    query = """select asin FROM asin_one_time_only"""
    cursor.execute(query)
    rows = cursor.fetchall()
    for row in rows:
        asin_list.append(row[0])

    print asin_list
    print 'fu2'
    query = "UNLOCK TABLES;"
    cursor.execute(query)
    conn.commit()

    print 'fu3'
    query = "LOCK TABLES asin_one_time_only WRITE"
    cursor.execute(query)

    query = """truncate table amz_one_time_only"""
    cursor.execute(query)
    conn.commit()

    print 'fu3'
    query = "UNLOCK TABLES;"
    cursor.execute(query)
    conn.commit()

    cursor.close()
    conn.close()

Traceback (most recent call last):
  File "/home/ubuntu/workspace/Amazon-Products-Crawler-1/threaded_crawl.py", line 1086, in <module>
    onetime = getOneTimeOnlyAsins(parms)
  File "/home/ubuntu/workspace/Amazon-Products-Crawler-1/threaded_crawl.py", line 109, in getOneTimeOnlyAsins
    cursor.execute(query)
  File "/usr/lib/pymodules/python2.7/MySQLdb/cursors.py", line 166, in execute
    self.errorhandler(self, exc, value)
  File "/usr/lib/pymodules/python2.7/MySQLdb/connections.py", line 35, in defaulterrorhandler
    raise errorclass, errorvalue
_mysql_exceptions.OperationalError: (1192, "Can't execute the given command because you have active locked tables or an active transaction")

A: You can't truncate a table that is locked for writing. This is because "truncate" means "destroy the table, and recreate a new one with the same schema."
You can however, empty the table. Instead of TRUNCATE TABLE asin_one_time_only use DELETE FROM asin_one_time_only. Note that this will not reset the autoincrement numbering. If you want to reset it as well, use ALTER TABLE asin_one_time_only auto_increment=1
I suggest doing this:
LOCK TABLES asin_one_time_only READ;
SELECT asin FROM asin_one_time_only;
-- minimize the possibility of someone writing to the table in-between
-- an "UNLOCK TABLES" and a "LOCK TABLES" by just issuing a new LOCK TABLES
-- I am not 100% sure that MySQL will do this atomically, so there is a
-- possibility that you may delete a row that was not read.
-- If this is unacceptable, then use a "LOCK TABLES asin_one_time_only WRITE"
-- from the very beginning.
LOCK TABLES asin_one_time_only WRITE;
DELETE FROM asin_one_time_only;
ALTER TABLE asin_one_time_only auto_increment=1;
UNLOCK TABLES;

A: You can't truncate a table that's locked for writing.
There's a whole debate on the issue here: http://bugs.mysql.com/bug.php?id=20667
What you can do, however is drop the table and re-create it.


text:
Q: S3 CORS is not allowing origin for two domains I have an S3 bucket where I would like to allow 2 domains to access the resources:

*

*http://asubdomain.mysite.com

*http://localhost:3000
Here is the CORS rule:
<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
    <CORSRule>
        <AllowedOrigin>http://asubdomain.mysite.com</AllowedOrigin>
        <AllowedMethod>GET</AllowedMethod>
        <MaxAgeSeconds>3000</MaxAgeSeconds>
        <AllowedHeader>*</AllowedHeader>
    </CORSRule>
    <CORSRule>
        <AllowedOrigin>http://localhost:3000</AllowedOrigin>
        <AllowedMethod>GET</AllowedMethod>
        <MaxAgeSeconds>3000</MaxAgeSeconds>
        <AllowedHeader>*</AllowedHeader>
    </CORSRule>
</CORSConfiguration>

Yet when I try to access the resources on a page, I get this error... occasionally. Any ideas?
XMLHttpRequest cannot load https://s3.amazonaws.com/my_awesome_bucket/myfile.txt.
The 'Access-Control-Allow-Origin' header has a value 'http://localhost:3000' that is not equal to the supplied origin.
Origin 'http://asubdomain.mysite.com' is therefore not allowed access.


text:
Q: Delete/update table entries by joining 2 tables on Google BigQuery without import/export We have a usecase where we have hundreds of millions of entries in a table and have a problem splitting it up further. 99% of operations are append-only. However, we have occasional updates and deletes which Google itself says is only possible by deleting a table and creating a new one with the latest data.
Because it's a lot of data and we would wish to update the tables within 30 seconds or so, we thought about the possibility of joining an Original table with a Refresher Table in a way that we only have entries that appear in Original Table but not in Refresher Table (case of delete) or write items with data from Refresher Table if found (case of update). Output/target should be New Table, which we would then copy back to Original Table with WRITE_TRUNCATE (overwrite). If update seems to be too complex, we could live with a delete-only logic and re-insert the updated items ourselves.
Is this possible? What type of join seem to be a best fit? We'd stream insert our updates into the Refresher Table and periodically clean up the Original table. We would not have to pay for re-inserting the whole Original table (whether its time or money) but only for querying' once and those few streaming inserts to update-table.
EDIT: We can live with querying stale data until the periodic merge took place. We can also halt queries for short amount of time during maintenance.
Any thoughts welcome.

A: So to add more on my comment:

Why don't you just accept the updates as a new row in your table, and
  have queries that read only the last row from the table? That's much
  easier.

Create a view like this:
select * from (
SELECT
rank() over (partition by user_id order by timestamp desc) as _rank,
*
FROM [db.userupdate_last]
) where _rank=1

and update your queries to query the view table and your basic table and you are done.
Some context how we use this. We have an events table that hold user profile data. On every update we append the complete profile data row again in BQ. That means that we end up having a versioned content with as many rows for that user_id as how many updates they have done. This is all in the same table, and by looking at the time we know the order of the updates. Let's say the table us: [userupdate]. If we do a
select * from userupdate where user_id=10

it will return all updates made by this user to their profile in random order.
But we created a view, which we created only once, and the syntax is above. And now when we:
select * from userupdate_last where user_id=10 #notice the table name changed to view name

it will return only 1 row, the last row of the user. And we have queries where we just swap the table name to view name, if we want to query from a table holding a bunch of append only rows only the last one.

A: There is relatively simple option we found efficient in similar scenarios with BigQuery.
It allows to handle queries based on any time based snapshot – as well as query current snapshot
In short, idea is in having one master table and daily history tables
During the day - current daily table is used for insertions (new, update, delete) and then daily process does merge of last completed daily table with master table writing it out back to same master table. Of course, first, backup is taken via copy of latest master table (free operation).
Daily master table update process allows to keep master table clean and fresh as of last day.
Now at any given moment you can have most recent data by querying only (junk-less) master table and today's table only.
At the same time, as you have all daily tables, you can query any historical data
Of course, classic option of adding all data (new, update, delete) into the master table with respective qualifiers still looks good both price and performance wise because your main (99%) data are new entries!
In your case, me personally, I would vote for classic approach with periodic cleaning of historical entries
Finally, in my mind, it is less about joining, but rather about union with use of table wildcard and window functions


text:
Q: Images not found because @@pluginfile@@ getting bad url I have the next problem with @@pluginfile@@ urls.
When I upload a Image to moodle repository file management and I use plugin file to load any image, it gives me this url:
From:

    src="@@pluginfile@@/ConoceADashAndDotWEB.png"

Transform into:

    src="pluginfile.php/132/mod_forum/post/7/ConoceADashAndDotWEB.png"

But it should transform url into:
src="pluginfile.php/72/mod_forum/post/7/ConoceADashAndDotWEB.png"

As consequence, I can't see images because they are not found. I really don't understand how @@pluginfile@@ works.

A: When Moodle displays the text which includes @@pluginfile@@ somewhere inside, it should call the function file_rewrite_pluginfile_urls(), passing in the details of the contextid, component, file area and itemid that should be used to generate the full URL.
I would be surprised if the forum module was passing in the wrong details for this (as it has been working in a lot of sites for several years now).
Where are you seeing this output (in the forum, or in your own plugin)?
Why do you believe that the contextid should be 72 instead of 132?
Do you have any idea where the (incorrect) 132 is coming from?


text:
Q: "Secret text" Git credentials not showing up in Jenkins project Source Code Management section I am unable to see any Secret text credentials in the drop down in my Jenkins' project SCM section. I know that creating a Secret text credential from the drop down in SCM section is broken, but even if I create the credential by navigating to Jenkins -> Credentials, that credential does not appear in the drop down.
I've created every type of credential and the only type I see in the dropdown is Username with password. It seems like the dropdown in SCM filters out every credential that is not of this type.
The reason I need Secret text credentials in the SCM section is because I want to use a Github access token (and not my Github account username and password).
The following screenshot shows my global credentials where my Secret text credential is clearly present.

The following screenshot shows my project's SCM section's Git dropdown where only the Username and password credential is present.
Jenkins version: 2.102
Jenkins Credentials plugin version: 2.1.16
Jenkins Git plugin version: 3.7.0

A: You can't use the Secret Text credential for the SCM step because the Github Personal Access Token is only supposed to replace your password. Not your user and password. Meaning your user is still required. In the Github documentation here you'll see it reads:

You can create a personal access token and use it in place of a password

And then below in section "Using a token on the command line" here it reads:

Once you have a token, you can enter it instead of your password when performing Git operations over HTTPS.

And it follows up with this example:
$ git clone https://github.com/username/repo.git
Username: your_username
Password: your_token

If you extrapolate this to Jenkins, the sensible choice of credential type is still the User with password one.
So, simply create a credential of type User with password as you normally would and use your personal access token for the Password field.

A: After installing the Credentials Bindings plugin, the Build Environment section of your build job Configuration page will include a new option to "Use secret text(s) or file(s)". Enabling this option allows you add credential bindings where the Variable value will be used as the name of the environment variable that your build can use to access the value of the credential.
For example you create a secret: (the ***** = 12345)

You can use it in the following way in your build:

Output of echo $VAR in my case is *****. But you can use it as 12345 in your job. This is how you use secret text. The name says it all. The text remains secret but you can use it as unprinted variable in your job. This is for text, not for credentials.
If you want to reuse your credentials in your build it's recommended to use the "username and password conjoined". Here you can set a variable for your credentials. More info can be found here on how you can split username and password.


text:
Q: HTML elements won't align properly on mobile The html elements on this simple to do list app i'm making won't properly align themselves when ran on mobile. Essentially when on mobile, the h1 tag should be in the center of the screen as well as the input box and add button under it and the tasks being added to the page, instead on mobile everything is off alignment. Any fixes?

let task;
let text;
let addTask;
let list;
let taskNo = 0;
let remove;
let input = document.getElementById('message');
let btn = document.getElementById('btn');

input.addEventListener("keypress", function() {
    if (event.keyCode == 13) {
        if (input.value === "") {
            alert("Please enter a task!");
        } else {
            createTask();
        }
    }
});

btn.onclick = function() {
    if (input.value === "") {
        alert("Please enter a task!");
    } else {
        createTask();
    }
};

function createTask() {

    task = input.value;

    addTask = document.createElement('li');

    text = document.createTextNode(task);

    addTask.appendChild(text);

    addTask.classList.add("task");

    taskNo++;

    addTask.id = taskNo;

    document.getElementById("taskList").appendChild(addTask);

    input.value = "";

    let list = document.getElementsByClassName("task");

    [...list].forEach(b => {
        b.addEventListener("click", () => {
            remove = document.getElementById(b.id);
            remove.parentNode.removeChild(remove);
        });
    });
}
html, body{
    margin: 0;
    padding: 0;
}

body {
    font-family: Arial, Helvetica, sans-serif;
 font-size: 16px;
    background-color: #29313d;
    color: white;
}

#container {
    width: 100%;
}

h1{
    text-align: center;
    font-size: 44px;
}

#input{
    margin: auto;
    text-align: center;
}

#message, #btn{
    display: inline-block;
    height: 100%;
    margin-top: 10px;
    padding: 0;
    float: left;
    -webkit-box-sizing: border-box;
}

#message{
    background-color: #333;
    color: white;
    border: 4px solid coral;
    padding-left: 10px;
    width: 75%;
    height: 50px;
    border-radius: 10px;
}

#btn{
    font-size: 20px;
    background-color: coral;
    border: 4px solid coral;
    color: black;
    margin-left: 5%;
    width: 20%;
    height: 50px;
    border-radius: 10px;
}

#btn:focus{
    outline: none;
}

#message:focus{
    outline: none;
}

#input{
    height: 50px;
    width: 400px;
}

#taskList{
    list-style-type: none;
    padding: 0;
    margin-top: 50px;
}

.task {
    margin: auto;
    width: 85%;
    margin-top: 5px;
    padding: 10px;
    border: 4px solid coral;
    background-color: #333;
    color: white;
    border-radius: 10px;
}

@media(max-width: 600px) {

    #container {
        width: 80%;
    }

    h1{
        margin: auto;
    }

    #message{
        width: 100%;
    }

    #btn{
        display: none;
    }

    .task{
        width: 100%;
        margin-left: 0;
        margin-right: 0;
    }
}
<!DOCTYPE html>

        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=10">
        <link href="resources/style.css" rel="stylesheet" type="text/css">
        <link href="resources/logo.png" rel="shortcut icon" type="image/png">
        <title>Jennis App</title>

To Do List

                    <input type="text" id="message" placeholder="Please enter a new task">

                    <input type="button" id="btn" value="Add">

A: you need to make some css changes in media.

*

*Center the container for small device using margin

*Remove display: none for #btn in media query

*Use flex to align add button for small device

*clearfix the .input-group using before and after

let task;
let text;
let addTask;
let list;
let taskNo = 0;
let remove;
let input = document.getElementById('message');
let btn = document.getElementById('btn');

input.addEventListener("keypress", function() {
    if (event.keyCode == 13) {
        if (input.value === "") {
            alert("Please enter a task!");
        } else {
            createTask();
        }
    }
});

btn.onclick = function() {
    if (input.value === "") {
        alert("Please enter a task!");
    } else {
        createTask();
    }
};

function createTask() {

    task = input.value;

    addTask = document.createElement('li');

    text = document.createTextNode(task);

    addTask.appendChild(text);

    addTask.classList.add("task");

    taskNo++;

    addTask.id = taskNo;

    document.getElementById("taskList").appendChild(addTask);

    input.value = "";

    let list = document.getElementsByClassName("task");

    [...list].forEach(b => {
        b.addEventListener("click", () => {
            remove = document.getElementById(b.id);
            remove.parentNode.removeChild(remove);
        });
    });
}
html, body{
    margin: 0;
    padding: 0;
}

body {
    font-family: Arial, Helvetica, sans-serif;
 font-size: 16px;
    background-color: #29313d;
    color: white;
}

#container {
    width: 100%;
}

h1{
    text-align: center;
    font-size: 44px;
}

#input{
    margin: auto;
    text-align: center;
}

#message, #btn{
    display: inline-block;
    height: 100%;
    margin-top: 10px;
    padding: 0;
    float: left;
    -webkit-box-sizing: border-box;
}

#message{
    background-color: #333;
    color: white;
    border: 4px solid coral;
    padding-left: 10px;
    width: 75%;
    height: 50px;
    border-radius: 10px;
}

#btn{
    font-size: 20px;
    background-color: coral;
    border: 4px solid coral;
    color: black;
    margin-left: 5%;
    width: 20%;
    height: 50px;
    border-radius: 10px;
}

#btn:focus{
    outline: none;
}

#message:focus{
    outline: none;
}

#input{
    height: 50px;
    width: 400px;
}

#taskList{
    list-style-type: none;
    padding: 0;
    margin-top: 50px;
}

.task {
    margin: auto;
    width: 85%;
    margin-top: 5px;
    padding: 10px;
    border: 4px solid coral;
    background-color: #333;
    color: white;
    border-radius: 10px;
}

@media(max-width: 600px) {

    #container {
        width: 80%;
        margin: 0 auto; /* to align center */
    }

    h1{
        margin: auto;
    }

    #message{
        width: 100%;
    }

    #btn{
        /* display: none; */
    }

    .task{
        width: 100%;
        margin-left: 0;
        margin-right: 0;
    }

    /***  Additional css ***/
    .input-group.flex {
        display: flex;
        justify-content: center;
    }
    .input-group:before, .input-group:after {
        content: "";
        display: table;
        clear: both;
    }
}
<!DOCTYPE html>

        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=10">
        <link href="resources/style.css" rel="stylesheet" type="text/css">
        <link href="resources/logo.png" rel="shortcut icon" type="image/png">
        <title>Jennis App</title>

To Do List

                    <input type="text" id="message" placeholder="Please enter a new task">

                    <input type="button" id="btn" value="Add">

working fiddle here


text:
Q: What is the abutment filtration of the second spectral sequence of hypercohomology? I have been recently learning about spectral sequences, following mainly Illusie's notes and EGA, and I am about to write some expository notes, but there are still some points that I was not able to justify. One of them is the following: let $\mathcal{A},\mathcal{B}$ be two abelian categories and let $T:\mathcal{A} \to \mathcal{B}$ be an additive functor. Assume that $\mathcal{A}$ has enough injectives and that $\mathbf{D}^+(\mathcal{B})$ exists. Therefore $T$ has a right derived functor $\mathbf{R}T : \mathbf{D}^+(\mathcal{A}) \to \mathbf{D}^+(\mathcal{B})$ and we will denote by $\mathbf{R}^i T$ the composition of $\mathbf{R}T$ and the cohomology functor $H^i : \mathbf{D}^+(\mathcal{B}) \to \mathcal{B}$.
Given $K \in \mathbf{D}^+(\mathcal{A})$, it is possible to construct two biregular spectral sequences abutting to the hypercohomology $\mathbf{R}^*T(K)$. The first one has $E_1$ term $R^qT(K^p)$ and its abutment filtration is given by
$$ 'F^p(\mathbf{R}^nT(K)) = \text{Im}(\mathbf{R}^nT(\sigma_{\geq p}K) \to \mathbf{R}^nT(K)), $$
where $\sigma_{\geq p}K$ denotes the naive truncation of $K$.
The second one has $E_2$ term $R^pT(H^qK)$ and Illusie claims (p.189 of the above-mentioned notes) that the abutment filtration in this case is given by
$$ ''F^p(\mathbf{R}^nT(K)) = \text{Im}(\mathbf{R}^nT(\tau_{\leq n-p}K) \to \mathbf{R}^nT(K)), $$
where $\tau_{\leq n-p}K$ denotes the canonical truncation of $K$. I have tried to justify this without success. Illusie says that we need to use the method of décalage by Deligne. After some search I believe that he is referring to Deligne's Théorie de Hodge II, §1. It seems that we need to shift some indices, but I did not follow the argument given there and would appreciate if someone elaborated on this a bit.
Just to make things clear, I am following the standard construction of the spectral sequences of hypercohomology, namely, given $K$ we take an injective Cartan-Eilenberg resolution $L$ for it and consider the spectral sequences of the bicomplex $T(L)$. I would appreciate even more if your answers follow this approach.


text:
Q: How to test GHC plugins? Recent versions of GHC have a new "plugins" feature, where you can write ordinary Haskell code, compile it as usual, and then insert it into the compiler so it can fiddle with GHC's internal state.
Which is very cool. However, there's a small snag: In order to do this, the plugin has to be already compiled (seems obvious) and registered as a package in the package DB!
That's fine once the plugin is finished; package it up and put it on Hackage for all to enjoy. But how do you get around this while trying to develop the package? How does your edit-compile-execute cycle work when at every edit, you have to manually deregister the old package, build the new one, and register it?
Basically, is there some way I can side-step this requirement while trying to develop a plugin?

A: If you're using Cabal, it should manage everything for you:
my-plugin.cabal
cabal-version: 2.4
name: my-plugin
version: 1.0.0.0

library
  build-depends: base ^>= 4.12.0.0
               , ghc ^>= 8.6.1
  hs-source-dirs: src
  exposed-modules: MyPlugin

-- could also be an internal library, executable, etc
test-suite test-plugin
  type: exitcode-stdio-1.0
  -- the dependency on my-plugin is everything, placing it
  -- in the package DB of the GHC compiling this test
  build-depends: base, my-plugin
  hs-source-dirs: test
  ghc-options: -fplugin=MyPlugin
  main-is: Main.hs

src/MyPlugin.hs
module MyPlugin(plugin) where
import GhcPlugins
-- this is an example plugin from the manual
-- it prints the names of the non-recursive bindings in each module

plugin :: Plugin
plugin = defaultPlugin {
  installCoreToDos = install
  }

install :: [CommandLineOption] -> [CoreToDo] -> CoreM [CoreToDo]
install _ todo = do
  return (CoreDoPluginPass "Say name" pass : todo)

pass :: ModGuts -> CoreM ModGuts
pass guts = do dflags <- getDynFlags
               bindsOnlyPass (mapM (printBind dflags)) guts
  where printBind :: DynFlags -> CoreBind -> CoreM CoreBind
        printBind dflags bndr@(NonRec b _) = do
          putMsgS $ "Non-recursive binding named " ++ showSDoc dflags (ppr b)
          return bndr
        printBind _ bndr = return bndr

test/Main.hs
module Main where
import Numeric.Natural
import Prelude hiding (even, odd)

-- printed
x :: Int
x = 5

-- not printed
fixObvious :: (a -> a) -> a
fixObvious f = f (fixObvious f)

-- printed
fixSubtle :: (a -> a) -> a
fixSubtle f = let x = f x in x

-- neither printed
even, odd :: Natural -> Bool
even 0 = True
even n = odd (n - 1)
odd 0 = False
odd n = even (n - 1)

-- printed
main :: IO ()
main = return ()
-- if the plugin were more interesting, you may want to test that any
-- modified definitions act like you expect them to


text:
Q: Devise redirect to facebook isn't working Update:
Narrowed down the issue to routing table.
devise_for :users, skip: :all

  devise_scope :user do
    get '/auth/:provider/callback' => 'registrations#omniauth'
    get '/auth/facebook/callback' => 'registrations#omniauth'
    get 'vendors/sign_up' => 'registrations#vendor_sign_up'
    post 'vendors/sign_up' => 'registrations#create_vendor_sign_up'
    get 'vendors/thank_you' => 'registrations#vendor_thank_you'
  end

How do I add a get/post route which will map to devise's facebook redirect?
I have followed all the articles on first pages of google search and still unable to get my login with Facebook working. I am getting No route matches [GET] "/auth/facebook" when I click on Login with Facebook button. It is not redirecting me to Facebook at all.
I am using Rails 6, Devise 4.8, Omniauth 2.0.4 and omniauth-facebook 8
My gems:
gem 'omniauth'
gem 'omniauth-facebook'
gem 'devise', github: 'heartcombo/devise'

My omniauth.rb initializer
Rails.application.config.middleware.use OmniAuth::Builder do
  provider :facebook, 'XXXXX', 'XXXXX',scope: 'email', display: 'popup'
end

My routing table has been split into multiple files. But here are the routes for user/signup related methods:
Rails.application.routes.draw do
  devise_for :users, skip: :all

  devise_scope :user do
    get '/auth/facebook/callback', to: 'callback_handler#facebook'

    get 'vendors/sign_up' => 'registrations#vendor_sign_up'
    post 'vendors/sign_up' => 'registrations#create_vendor_sign_up'
    get 'vendors/thank_you' => 'registrations#vendor_thank_you'
    get 'users/thank_you' => 'registrations#user_thank_you'
  end
end

my link for login is
<%= link_to '/auth/facebook', class:"oatuth-button fb oatuth-btn" do %>
   <i class="fa fa-facebook fa-fw"></i> <%= t(:login_with) %> Facebookk
<% end %>

and here is my CallbackHandler
class CallbackHandlerController < Devise::OmniauthCallbacksController

  skip_before_action :authenticate_user!, raise: false
  def all
    p request.env["omniauth.auth"]
    user = User.from_omniauth(request.env["omniauth.auth"], current_user)
    if user.save
      session[:user_id] = user.id
      sign_in(user)
      redirect_to home_path
    else
      render :new
    end
 end

def failure
    #handle you logic here..
    #and delegate to super.
    super
  end

  alias_method :facebook, :all
  # alias_method :twitter, :all
  # alias_method :linkedin, :all
  # alias_method :github, :all
  # alias_method :passthru, :all
  alias_method :google_oauth2, :all
end

when I click on this button, i am getting No Route matches GET /auth/facebook
Any ideas what am I missing here?
Thanks


text:
Q: Integrate FxCop in VS 2010 modifying csproj file using Addin I have many projects in TFS, using VS2010. I have a Addin VS2010 that add some new business features for my company.
Now, it is required integrate FxCop and Visual Studio 2010 for older and new projects.
I(we) don't want to add FxCopCmd.exe to my Post-build events  to run FxCop with every compilation.
I(we) don't want to modify Microsoft.CSharp.targets or Microsoft.Common.targets.
I want the programmer don't do anything, not modify properties project, not modify xml csproj file.
I want to be able to run FxCop when the programmer do Build on the project in Solution Explorer, and too when do Build programatically in Addin:
solution.DTE.ExecuteCommand("Build.RebuildSolution", "");
project.DTE.ExecuteCommand("Build.RebuildSelection", "");

I think the better option is using Solution Events in Addin VS2010 for modify csproj file
solutionEvents.ProjectAdded
solutionEvents.Opened

Any suggestions about all this ? any sample source code ?


text:
Q: Prevent thread interruptions in Spring Boot scheduler shutdown I have a spring boot application which runs tasks on a schedule using the @Scheduled annotation.
On shutdown if the scheduled task is running, I want to allow it finish.
I first added a shutdown hook to the java runtime (Runtime.getRuntime().addShutdownHook( ... )) to simply wait -- but my tasks were still getting interrupted -- pretty much immediately.
So then I started looking into if this had to do with the scheduled task and tried this:
    @Bean
    public TaskScheduler taskScheduler() {
        ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
        scheduler.setWaitForTasksToCompleteOnShutdown(true);
        scheduler.setAwaitTerminationSeconds(60);
        scheduler.initialize();
        return scheduler;
    }

The problem is that this doesn't actually seem to be protecting the code that is running from thread interruption either and I am still getting  Unexpected error occurred in scheduled task errors where the cause is java.lang.InterruptedException and com.amazonaws.http.timers.client.SdkInterruptedException


text:
Q: Upload file with Vuejs i'm working in Laravel. i need to upload file with Vuejs. but it's not working. I add this code:
Blade (File upload):
<input class="form-control" type="file" >

Script Vuejs :
    var app = new Vue({
    el: '#app',
data: {
person: {
        id: 0,
        user_name:'',
        position_id:'',
        image:'',
        },
        },

    methods: {
      addPerson: function () {
        axios.post('/addperson', this.person)
            .then(response => {
                console.log(response.data);
                if (response.data.etat) {
                    this.person = {
                         id: 0,
                          user_name: response.data.etat.user_name,
                          position_name: response.data.etat.position_id,
                          image: response.data.etat.image
                    };
                }

            })
            .catch(error => {
                console.log('errors: ', error)
            })
    },

Controller:
public function addPerson(Request $request){
$person = new Person;

$person->user_name=$request->user_name;
$person->position_id=$request->position_id;
 if($request->hasFile('photo')){
     $person->image= $request->image->store('image');
    }
$person->save();

return back()->with('success', 'New Position added successfully.');

My Axios post function is working without the image upload line code. I just don't know how to add the upload code.
Thank you if someone can help.

A: In your blade file
<input type="file" @change="onFileChange" name="id_image" id="id_image" class="inputFile">

In your vue.js file, under methods:
    onFileChange(e) {
                let files = e.target.files || e.dataTransfer.files;
                if (!files.length)
                    return;
                this.createImage(files[0]);
            },

createImage(file) {
            let reader = new FileReader();
            reader.onload = (e) => {
                this.person.image = e.target.result;
            };
            reader.readAsDataURL(file);
        },

That should allow your axios code to upload the image. Note, that it uploads in base64, so if you need validators you will have to create a custom Validator for base64 images.

A: I struggled to find out how to do this, but I've now found a way. Hopefully this makes someones life easier(I have the uploadUserImage method in a mixin):
HTML:
<input type="file" @change="uploadImage($event)">
JS:
uploadImage (e) {
      this.file = e.currentTarget.files[0]
      let formData = new FormData()
      formData.append('img', this.file)
      this.uploadUserImage(formData)
}

    uploadUserImage: function (formData) {
      axios.post('http://snowdon-backend.local:8000/api/users/img', formData,
        {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        })
        .then(function (response) {
          console.log(response)
        })
    }

Make sure file is set in the data method as well:
data () {
    return {
      file: ''
    }
  }


text:
Q: Tensorflow model memory usage keeps increasing I have a python program that runs several processes, each of which loads a tensorflow model and then runs in a loop performing some operations.
Each iteration of the loop is independent, but the model stays loaded.
I see that the memory usage keeps increasing with each iteration, even though I'm calling tf.keras.backend.clear_session at the end of each iteration.
Each process is communicating with the main process via a pipe, and in each iteration of the loop it receives a message, does some operations using the model, and sends the result back.
The code that each process runs looks something like this:
model = tf.saved_model.load(saved_model_location)
utils.model = model

while True:
    message = connection.recv()[0] # wait for message from main process
    result = do_something(message) # perform operations on the message
    tf.keras.backend.clear_session()
    connection.send([result])  # Send result of execution to main process

The utils object stores the model, which is later accessed by the do_something function.
The do_something function calls the following tensorflow functions during its execution:
tf.keras.preprocessing.sequence.pad_sequences,
tf.data.Dataset.from_tensor_slices,
tf_ad.text.viterbi_decode
When I implemented my code with a single process, the tf.keras.backend.clear_session function did clear the global state and I had no memory issues, but when I switched to multiprocessing it seems like it stopped clearing the memory, and I keep running into issues where I'm out of memory.
Can anyone shed some light on to why this is happening? Is there something I'm missing regarding tensorflow and its global state when working with multiprocessing?
Thanks


text:
Q: Проблема с установкой Ramus У меня Windows 10. Я установил Ramus, но ярлыка нет ни на рабочем столе, ни в панели "Пуск", причём если ввести в поиск в том же "Пуске" найти тоже ничего не получается. Переход в папку приложения также проблемы не решает, так как при попадании туда я обнаруживают только кучу jre файлов.

A: Как казалось, нужна была Java Runtime Environment: http://java-runtime.ru/download


text:
Q: "[WinError 6] The handle is invalid" with Urllib import urllib.request

def Download(url, file_name):
    urllib.request.urlretrieve(url, file_name)

f = open("links.txt", "r")
lines = f.readlines()

for line in lines:
    for x in range (1, 5):
        filenaame = x

        cut_string = line.split('?$')
        new_string = cut_string[0]
        numerator = new_string.split('/1/')
        separator = ''

        link = (separator.join(numerator[0] + "/{}/".format(x) + numerator[1]))

        file_name = link.split('/{}/'.format(x))
        file_name = file_name[1]
        file_name = file_name.split('.')
        file_name = (separator.join(file_name[0] + "{}".format(filenaame)))
        filenaame =+ 1

        print("Downloading: {}".format(file_name))
        Download(link, filenaame)

Error:
Traceback (most recent call last):
  File "C:\python\downloader\rr.py", line 29, in <module>
    Download(link, filenaame)
  File "C:\python\downloader\rr.py", line 5, in Download
    urllib.request.urlretrieve(url, file_name)
  File "C:\python\lib\urllib\request.py", line 258, in urlretrieve
    tfp = open(filename, 'wb')
OSError: [WinError 6] The handle is invalid

I have googled a lot about this and in every result I found the person was using the subprocess module, which I'm not, which makes it even more difficult.
The code is for downloading images. It does download the first one successfully, then it crashes. Anyone know what's causing the error? I'm still a beginner.

A: you're passing your counter as a second parameter. In the end the function uses that as a filename to copy the downloaded data to.
By passing an integer you enable the "pass a lowlevel file descriptor" to open:

file is either a string or bytes object giving the pathname (absolute or relative to the current working directory) of the file to be opened or an integer file descriptor of the file to be wrapped.

But the file descriptor doesn't exist (fortunately!)
Let's reproduce the issue here:
>>> open(4,"rb")
Traceback (most recent call last):
  File "<string>", line 301, in runcode
  File "<interactive input>", line 1, in <module>
OSError: [Errno 9] Bad file descriptor

the fix is obviously:
Download(link, file_name)

(I'd suggest that you rename your filenaame counter for something more meaningful, it avoids mistakes like that)

A: At this line,
urllib.request.urlretrieve(url, file_name)

here file_name should be a string so before calling Download(link, filenaame) make integer filenaame to string try.
Download(link, str(filenaame))

Sample working for downloading an image
def download_img(url):
    name = random.randrange(100,1000)
    full_name = str(name)+ ".jpg"
    urllib.request.urlretrieve(url, full_name)

download_img("http://images.freeimages.com/images/small-previews/25d/eagle-1523807.jpg")


text:
Q: google-apps-script restric menu use/creation to users I have a sheet with a google apps script that does various things. One of those things is building a menu on open.
I would like this menu to be built only when a certain specific user is acessing the sheet. How can I achieve this?

A: You cannot have restrictions inside onOpen since the user's email address is not available in any context that allows a script to run without that user's authorization. You can however include checks in the function that runs on clicking menu items.
 function onOpen(e) {
    SpreadsheetApp.getUi()
      .createMenu('Menu')
      .addItem('First item', 'doSomething')
      .addToUi();
}

 function doSomething() {
    if (Session.getActiveUser().getEmail() !== "abc@example.com") return;
    // else do something here
}


text:
Q: Schedule overwriting itself If the below 'delayingTest' is called N times, I expect it to eventually call doIt N times as well. However this is not the case, it seems as if the schedule overwrites any previous schedule, supposedly having the same selector. Anyway around this?
-(void)delayingTest {
    if (_delay) {
        [self schedule:@selector(delayingTest) interval:1.0f repeat:0 delay:1.0f];
    }
    else {
        [self doIt];
    }
}

A: one way would be :
dont use _delay as int but bind it with timestamp storing it in NSDate and comparing the timestamps when next time your method gets called.

A: Try This:
-(void)delayingTest
{
    if (_delay)
    {
        [self unschedule:@selector(delayingTest)];
        [self schedule:@selector(delayingTest) interval:1.0f];
    }
    else
    {
        [self doIt];
    }
}


text:
Q: Array turns to string after passing as an EJS variable So I have a file with an array which I am passing to the ejs template. I must use that array in a for loop to render each item of the array. But all I'm getting right now are the letters in the console. Seems like I somehow turned it into a string.
Can someone help me render each item in the array by using a for loop and also by using proper EJS syntax?
Here's the code:
Example.js
router.get('/example', (req, res) => {
    const array         = ['superman', 'batman', 'wonderwoman'];
    res.render("../views/example", { data: array });
});

EJS template
<script>

    <% if(data) { %>
        const dataArr = '<%- data %>';

        for ( let i = 0; i < dataArr.length; i++ ) {
            console.log(dataArr[i]);
        }

    <% }else{ %>
        console.log('no data')
    <% } %>

</script>

A: Had a similar problem recently using ejs, what fixed it for me was using the following assignment within the script:
const dataArr =  <%-JSON.stringify(data)%>;


text:
Q: List is returning one after clearing all the items by deleting My List is returning an item after clearing all the items by deleting ,On app fresh install its returing null which is good but after adding item and then by deleting all, this happens when go back from that activity and come again, list.size() is returning 1 and an item is remaing ,i don't know if it is loading from cache object instance here is my code of adapter class
[please look to the image attached ,list is empty but still counter 1 counter = cartModelList.size()]i have a list of cart itemsprivate List<CartModel> cartModelList;
It's returning null on app fresh install which is good but when i add item to the cart and then remove all the items then its returning 1.
I mean cartmodelList.size() is returning as far I know it's returning some items from cached objects or some thing like that.

The question is how to remove that List object cached or any alternative?

I tried on delete button but still cached coming

    public static  double p = 0;
    private List<CartModel> cartModelList;
    Database db;
    Context context;

    public CartAdapter(Context context, List<CartModel> cartModelList) {
        this.cartModelList = cartModelList;
        this.context = context;
        db = new Database(context);
    }

    @NonNull
    @Override
    public Viewholder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.cart_layout_item, parent, false);
        return new Viewholder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull final Viewholder holder, final int position) {

        String namee = cartModelList.get(position).getName();
        String manufacturere = cartModelList.get(position).getManufacturer();
        String availabilitye = cartModelList.get(position).getAvailability();
        String e_parte = cartModelList.get(position).getE_part();
        String m_parte = cartModelList.get(position).getM_part();
        String floatprice = cartModelList.get(position).getUnit_();
        String int_quantity = cartModelList.get(position).getQuantity();
        String float_line_total = cartModelList.get(position).getLine_total();

        holder.setItemDetails(namee, manufacturere, availabilitye, e_parte, m_parte, floatprice, int_quantity, float_line_total);

        int  checker = SharedPrefManager.getInstance(context).cartcount().getCounter();

        if (checker <= 0){

            cartModelList.clear();

        }

        holder.btn_delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (db.deleteProduct(cartModelList.get(position).getID())) {

                        cartModelList.remove(position);
                        notifyDataSetChanged();

                    Toast.makeText(context, "Product  deleted from cart", Toast.LENGTH_LONG).show();

                } else {

                    Toast.makeText(context, "Product not deleted from cart", Toast.LENGTH_LONG).show();

                }

                CartList user111 = new CartList(--COUNTER_BADGE);

                //  Toast.makeText(context, "else", Toast.LENGTH_SHORT).show();
                SharedPrefManager.getInstance(context).cartList(user111);
                ((Activity)context).invalidateOptionsMenu();
                ((Activity)context).finish();
                Intent intent = new Intent(context, CartActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
                context.startActivity(intent);

            }

        });

 @Override
    public int getItemCount() {
        return cartModelList.size();
    }

    class Viewholder extends RecyclerView.ViewHolder {

        private TextView name;
        private TextView manufacturer;
        private TextView availability;
        private TextView e_part;
        private TextView m_part;
        private TextView price;
        private EditText quantity;
        private TextView linetotal;
        private Button btn_delete;
        private Button btn_update;
        private  Button adapter_livestock;
        public  SpinKitView progressbar;

        public Viewholder(@NonNull View itemView) {
            super(itemView);

            name = itemView.findViewById(R.id.name);
            manufacturer = itemView.findViewById(R.id.manufacturer);
            availability = itemView.findViewById(R.id.availability);
            e_part = itemView.findViewById(R.id.e_part);
            m_part = itemView.findViewById(R.id.m_part);
            price = itemView.findViewById(R.id.price);
            quantity = itemView.findViewById(R.id.quantity);
            linetotal = itemView.findViewById(R.id.linetotal);
            btn_delete = itemView.findViewById(R.id.btn_delete);
            btn_update = itemView.findViewById(R.id.btn_update);
            adapter_livestock = itemView.findViewById(R.id.adapter_livestock);
            progressbar = itemView.findViewById(R.id.adapterrprogresslivestockprogress);

        }

        private void setItemDetails(String namee, String manufacturere, String availabilitye, String e_parte, String m_parte, String floatprice, String int_quantity, String float_line_total) {

            name.setText(namee);
            manufacturer.setText(manufacturere);
            availability.setText(availabilitye);
            e_part.setText(e_parte);
            m_part.setText(m_parte);
            price.setText("£"+floatprice);
            quantity.setText(int_quantity);
            linetotal.setText("£"+float_line_total);

        }

    }

[https://i.stack.imgur.com/PxDTZ.jpg]

A: Okay... The first.
if (db.deleteProduct(cartModelList.get(position).getID()))

will not delete your item from cartModelList, you need to do it manually. Like this:
if (db.deleteProduct(cartModelList.get(position).getID())) {
    cartModelList.remove(position)

And the second. You have to call notifyDataSetChanged() or itemChanged or itemRemoved etc. only in the end of your deletion method. Please, tell me, if it worked.
P.S. Your items do not cached. The problem is in your code order.
Edit 1. Also, you need to check your db.deleteProduct method. Is it worked? Is your if statement worked?
Edit 2. Try this.
holder.btn_delete.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (db.deleteProduct(cartModelList.get(position).getID())) {
                    cartModelList.remove(position);
                    notifyItemRemoved(position);

                Toast.makeText(context, "Product  deleted from cart", Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(context, "Product not deleted from cart", Toast.LENGTH_LONG).show();
            }

            CartList user111 = new CartList(cartModelList.size());

            //  Toast.makeText(context, "else", Toast.LENGTH_SHORT).show();
            SharedPrefManager.getInstance(context).cartList(user111);
            ((Activity)context).invalidateOptionsMenu();
            ((Activity)context).finish();
            Intent intent = new Intent(context, CartActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
            context.startActivity(intent);
        }
    });

A: my problem is solved by putting cartModelList.clear on delete button when cartModelList.size() == 1 , so after deleting the last item it will clear the list.


text:
Q: Net Core 5.0 Web Api 'Some services are not able to be constructed' when trying to set up Google Authentication I have a combined windows service/MVC Web API have built in dotNET Core 5.0 which I am trying to add Google Oauth.  Not authenticating directly with a database, not my intension at this point.  Just want to capture the Google claims to do my own authentications on.  However after adding the Google OAuth to the Start function, i get the following error:

System.AggregateException: 'Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: Microsoft.AspNetCore.Identity.ISecurityStampValidator Lifetime: Scoped ImplementationType: Microsoft.AspNetCore.Identity.SecurityStampValidator1[Microsoft.AspNetCore.Identity.IdentityUser]': Unable to resolve service for type 'Microsoft.AspNetCore.Identity.IUserStore1[Microsoft.AspNetCore.Identity.IdentityUser]' while attempting to activate 'Microsoft.AspNetCore.Identity.UserManager1[Microsoft.AspNetCore.Identity.IdentityUser]'.) (Error while validating the service descriptor 'ServiceType: Microsoft.AspNetCore.Identity.ITwoFactorSecurityStampValidator Lifetime: Scoped ImplementationType: Microsoft.AspNetCore.Identity.TwoFactorSecurityStampValidator1[Microsoft.AspNetCore.Identity.IdentityUser]': Unable to resolve service for type 'Microsoft.AspNetCore.Identity.IUserStore1[Microsoft.AspNetCore.Identity.IdentityUser]' while attempting to activate 'Microsoft.AspNetCore.Identity.UserManager1[Microsoft.AspNetCore.Identity.IdentityUser]'.) (Error while validating the service descriptor 'ServiceType: Microsoft.AspNetCore.Identity.IUserClaimsPrincipalFactory1[Microsoft.AspNetCore.Identity.IdentityUser] Lifetime: Scoped ImplementationType: Microsoft.AspNetCore.Identity.UserClaimsPrincipalFactory2[Microsoft.AspNetCore.Identity.IdentityUser,Microsoft.AspNetCore.Identity.IdentityRole]': Unable to resolve service for type 'Microsoft.AspNetCore.Identity.IUserStore1[Microsoft.AspNetCore.Identity.IdentityUser]' while attempting to activate 'Microsoft.AspNetCore.Identity.UserManager1[Microsoft.AspNetCore.Identity.IdentityUser]'.) (Error while validating the service descriptor 'ServiceType: Microsoft.AspNetCore.Identity.UserManager1[Microsoft.AspNetCore.Identity.IdentityUser] Lifetime: Scoped ImplementationType: Microsoft.AspNetCore.Identity.UserManager1[Microsoft.AspNetCore.Identity.IdentityUser]': Unable to resolve service for type 'Microsoft.AspNetCore.Identity.IUserStore1[Microsoft.AspNetCore.Identity.IdentityUser]' while attempting to activate 'Microsoft.AspNetCore.Identity.UserManager1[Microsoft.AspNetCore.Identity.IdentityUser]'.) (Error while validating the service descriptor 'ServiceType: Microsoft.AspNetCore.Identity.SignInManager1[Microsoft.AspNetCore.Identity.IdentityUser] Lifetime: Scoped ImplementationType: Microsoft.AspNetCore.Identity.SignInManager1[Microsoft.AspNetCore.Identity.IdentityUser]': Unable to resolve service for type 'Microsoft.AspNetCore.Identity.IUserStore1[Microsoft.AspNetCore.Identity.IdentityUser]' while attempting to activate 'Microsoft.AspNetCore.Identity.UserManager1[Microsoft.AspNetCore.Identity.IdentityUser]'.) (Error while validating the service descriptor 'ServiceType: Microsoft.AspNetCore.Identity.RoleManager1[Microsoft.AspNetCore.Identity.IdentityRole] Lifetime: Scoped ImplementationType: Microsoft.AspNetCore.Identity.RoleManager1[Microsoft.AspNetCore.Identity.IdentityRole]': Unable to resolve service for type 'Microsoft.AspNetCore.Identity.IRoleStore1[Microsoft.AspNetCore.Identity.IdentityRole]' while attempting to activate 'Microsoft.AspNetCore.Identity.RoleManager1[Microsoft.AspNetCore.Identity.IdentityRole]'.)'

Here is my Program.cs
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging.EventLog;

public class Program
{
    public static void Main(string[] args)
    {
        CreateHostBuilder(args).Build().Run();
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureServices(services =>
            {
                services.AddHostedService<BudgetWorker>().Configure<EventLogSettings>(config =>
                {
                    config.LogName = " Budget";
                    config.SourceName = " Budget";
                });
            })
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
            });
}

and this is my Startup (which is essentially what comes out of the box as standard in VS2019 when you create a ASP.NET WEB API project:
using Microsoft.AspNetCore.Authentication.Google;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddIdentity<IdentityUser, IdentityRole>();
        services.AddAuthentication(options =>
        {
            options.DefaultAuthenticateScheme = GoogleDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = GoogleDefaults.AuthenticationScheme;
        }).AddGoogle(options =>
        {
            var clientSecret = new ConfigurationBuilder().AddJsonFile("Resources\\client_secret.json", optional: false, reloadOnChange: false).Build();
            options.ClientId = clientSecret.GetSection("installed").GetSection("client_id").Value;
            options.ClientSecret = clientSecret.GetSection("installed").GetSection("client_secret").Value;
        });
        services.AddControllers();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Error");
            // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
            app.UseHsts();
        }
        app.UseHttpsRedirection();
        app.UseStaticFiles();

        app.UseRouting();

        app.UseAuthentication();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
    }
}

Best I can tell it's getting hung up on the services.AddIdentity() call, and not sure what needs to change?
I have read all the other "related" posts I can find, but nothing sticks out to me as yet.
I suspect it may be something to do with a mix of Singleton/Scoped/Transient services, but this is all new to me, so not sure where to start.
Any information would be greatly appreciated!


text:
Q: Testing a Java Applet with JUnit I'm completely new to Java and I'm trying to set up a test for it. But how do I call a method from the test class?
Right now I'm trying with a public method, and making a new instance of the class Hangman, but the call to the method doesn't work.
Hangman.java:
public class Hangman extends Applet implements ActionListener{
       public String[] getWordArray(){
        /* Enter the wordslist, separated by a | here: */
        String str = "computer|"
                + "radio|"
                + "calculator|"
                + "teacher|"
                + "bureau|"
                + "police|"
                + "geometry|"
                + "president";
        String[] temp;

        /* delimiter */
        String delimiter = "\\|";

        /* given string will be split by the argument delimiter provided. */
        temp = str.split(delimiter);

        return temp;
    }
}

HangmanTest.java:
public class HangmanTest {
    Hangman hangman = new Hangman();

    @Before
    public void setUp() throws Exception {
    }

    @After
    public void tearDown() throws Exception {
    }

    @Test
    public void testGetWordArray() {
        int expected = 8;
        int actual = hangman.getWordArray().length();
        Assert.assertEquals(expected, actual);
    }
}

A: You have a syntax error. It is int actual = hangman.getWordArray().length;, not int actual = hangman.getWordArray().length();. The length of array is an attribute, not a method. All other datastructures (like ArrayList) have a method for this.


text:
Q: css that starts with selector ^= dont work after changing class with javascript When loading page into browser everything looks fine and the background-image is correct. But when I click on the icon and the javascript changes the class of the icon to .icon-myapp-cow the css from [class^="icon-myapp"] is ignored. Only the css from icon-myapp-cow is applied. Tested in chrome and IE9
My css
[class^="icon-myapp"] {
    background-image: url("../img/myapp-icons.png");
}

.icon-myapp-horse {
    background-position: -1px -1px;
    height: 15px;
    width: 15px;
}

.icon-myapp-cow {
    background-position: -51px -1px;
    height: 15px;
    width: 15px;
}

My html
<i class="icon-myapp-horse icon-clickable"></i>

My javascript
$(".icon-clickable").click(function() {
    $(this).removeClass("icon-myapp-horse");
    $(this).addClass("icon-myapp-cow");

});

A: You need to change [class^="icon-myapp"] to:
[class*="icon-myapp"]
See here for some more information, and here for a fiddle

[attr^=value]
  Represents an element with an attribute name of attr and whose value is the (sic) prefixed by "value".
[attr*=value] Represents an element with an attribute name of attr and
  whose value contains at least one occurrence of string "value" as
  substring.

A: Change the ^ to *
When you remove the class icon-myapp-horse and then add icon-myapp-cow this newly added class is appended to the class names so the new set of classes look like icon-clickable icon-myapp-cow hence it does not start with icon-myapp
http://jsfiddle.net/Pj3d5/1/


text:
Q: Configuring RSS Viewer Should I be able to configure a RSS Viewer that reads from another list on my site/farm?
My attempts so far generate this error, first from a list in the same site, then from a list in a neighboring site collection:
"ProtocolError occured trying to complete the request. The server returned a status code of : InternalServerError and the status description is : "( The server denied the specified Uniform Resource Locator (URL)."

A: You can only use the RSS viewer to pull internal SharePoint content if you're using Kerberos authentication in the farm.  If you aren't running Kerberos, you'll need to use data view web parts most likely.

A: If you wish to view an rss feed from an internal site you must turn on intranet calls. The error in ULS for intranet calls looks similar to the one you stated: Cannot find site lookup info for request Uri & Preventing an intranet call.
Using powershell:
$farm=get-spfarm
$farm.properties.disableintranetcalls=$false
$farm.properties.disableintranetcallsfromapps=$false
$farm.Update()

A: The solution is not to use the RSS-wiever webpart. Insert the Content Query and you can import an RSS from your site collection. Microsoft should really do something to inform users about this.


text:
Q: Override WooCommerce Shop Site Breadcrumb with Yoast SEO Breadcrumb I tried to remove the WooCommerce Breadcrumbs with this code:
add_action( 'init', 'remove_wc_breadcrumbs' );
function remove_wc_breadcrumbs() {
remove_action( 'woocommerce_before_main_content', 'woocommerce_breadcrumb', 20, 0 );
}

...which works.
After that I activated the Yoast Seo Plugin Breadcrumbs an placed this code in my theme header.php
<?php if ( function_exists('yoast_breadcrumb') ) {
    yoast_breadcrumb('
','
');
    } ?>

...which also works.
The problem appears when I navigate to my "shop-site" which I defined in the WooCommerce settings. The full breadcrumb looks like this
Home > Product

Note: The Page name in WordPress for the "shop-site" is "Test" (not "Product").
I want to override the "Product" in something different. I tried to override it by defining a custom breadcrumb title in the advanced Yoast settings on the wordpress "shop-site" page but it didn't seems to work. Overriding works if the page isn't defined as the "shop-site" in the WooCommerce settings. So I guess some function overwrites the Yoast Breadcrumb override but I can't figure out which function does this.
The same problem appears when I navigate to a single product. Breadcrumb looks like this
Home > Product > Product Name

Again I want to rename the "Product" (only the second crumb here) into something different.
Can someone solve this mysticism?

A: I fixed it with this code:
add_filter( 'wpseo_breadcrumb_output', 'custom_wpseo_breadcrumb_output' );
function custom_wpseo_breadcrumb_output( $output ){
if( is_product() ){
    $from = 'rel="v:url" property="v:title">Product';
    $to = 'rel="v:url" property="v:title">New Title';
    $output = str_replace( $from, $to, $output );
}

elseif ( is_shop() ) {
    $from = 'Products';
    $to = 'New Title';
    $output = str_replace( $from, $to, $output );
}
return $output;
}

A: I wonder if there wouldn't be an easier way to change the first "product" into sth like "product category"...
Have you tried in wp-admin:

*

*Go to "Yoast"

*Then "SEO settings"

*Then "Breadcrumbs" and adapt taxonomies (eg: product > category).


text:
Q: JavaFX controller communication with dynamic content Here is a general structure of a JavaFX android mobile application I am creating.
Using (AppBar or AppBarSearch these interchange dynamically) as nested controllers within Primary Application FXML.
ParentController
 - AppBarController
 - AppBarSearchController
primary.fxml
 - appBar.fxml / appBarSearch.fxml
    <AnchorPane fx:id="appBarPane" prefHeight="56.0" prefWidth="350.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0">
        <children>
            <fx:include source="appbar.fxml" fx:id="appBar" />
    <!-- initially shows AppBar but appBarSearch can also be here after clicking search button -->
        </children>
    </AnchorPane>

A button in each of the child fxml is responsible for changing between the fxml content from appBar/AppBarSearch.
The issue arises when I am dynamically change the content of the appBar to appBarSearch and back. I want the appBar menu button to communicate to the NavigationMenu to slide in and out.
I have been looking into whether I should somehow have an instance of the parentController inside the AppBarController.
I did use the following:
@FXML
private AppBarController appBarController; // injected via <fx:include fx:id="child" ... />

<fx:include source="appbar.fxml" fx:id="appBar" /> <- dynamically changes

//to dynamically change content in Panes
public static void setView(View view, Pane pane) {
    try {
        pane.getChildren().clear();
        pane.getChildren().setAll((Node) FXMLLoader.load(Main.class.getResource(view.getTemplate()), resources));
    } catch (IOException e) {
        logger.error(e.getMessage());
    }
}

    @FXML
public void initialize() {
    appBarController.setParentController(this);
}

    @FXML
private void menuButtonClick (ActionEvent event) {
    this.parentController.triggerMenu();
}

Initially the above works but after switching between appBarSearch and appBar it gives me a nullPointer to the parentController instance.
It may be that after switching between controllers dynamically it would not recognise the child controller.
I want the menuBtn in AppBar to open a navigationMenu so it would require to call triggerMenu() from within PrimaryController to start animations of it sliding in and out after the button in AppBar is clicked.

A: Thanks very much to the comments I was able to fix the issue and improve my understanding of how to use Controllers and included fxml.
Below is the general code I used to connect the child controllers with my primary controller and change views dynamically.
@FXML
private AppBarController appBarController; // injected via <fx:include fx:id="child" ... />

@FXML
private NavMenuController navMenuController; // injected via <fx:include fx:id="child" ... />

@FXML
private MainContentController mainContentController; // injected via <fx:include fx:id="child" ... />

@FXML
public void initialize() {
    appBarController.setScreenParent(this);
    navMenuController.setScreenParent(this);
    mainContentController.setScreenParent(this);
}

/**
 * Set View on a Pane Javafx component
 */
public <T extends Pane> boolean setView(View view, T pane) {
    try {
        FXMLLoader myLoader = new FXMLLoader(getClass().getResource(view.getTemplate()), resources);
        pane.getChildren().clear();
        pane.getChildren().setAll((Node) myLoader.load());
        ControlledScreen childController = myLoader.getController();
        childController.setScreenParent(this);
        return true;
    } catch (IOException e) {
        logger.error(e.getMessage());
        return false;
    }
}

public void setMainContentView(View view) {
    setView(view, mainContentPane);
}

public void setAppBarView(View view) {
    setView(view, appBarPane);
}

public void setNavMenuView(View view) {
    setView(view, navMenuPane);
}

public void triggerNavMenu() {
    if (navMenuPane.getTranslateX() != 0) {
        openNav.play();
        appBarController.setMenuClosedImage();
    } else {
        closeNav.setToX(-(navMenuPane.getWidth()));
        closeNav.play();
        appBarController.setMenuClosedImage();
    }
}


text:
Q: How to put an arbitrary big tuple in pattern matching with case? I posted this day some questions at Stack Overflow, but the problem I am dealing with requires more complicated code than expected.
I have this code:
val nsc1= Stream.iterate((1,0,1,1))({case (a,b,c,d) => (b,c,d,b+c)}) map (c=> c._1)

Here the initial value of the stream is a Tuple4, but I need to manage an arbitrary size of it. The problem isn't actually the initial argument, but 'case' with a list of values in the tuple. How can I achieve it?
I will search on the web in 'pattern matching' also, and put the answer here if I find it.

A: Working with a List or some other type of collection would certainly be easier, but if you really are stuck with tuples of various lengths then I think you'll have to drop pattern matching.
Instead, you might have to pass the tuple t => and then use t.productArity, t.productElement(), and/or t.productIterator to inspect the tuple and build the return tuple of the same profile.

A: You can have an arbitrary length matching List. Not sure what you are trying to do but here is one way to do this:
Stream.iterate( List(1,0,1,1) ){
    case List(a,b,c,d) => List(b,c,d,b+c)
    case List(a,b,c) => List(a)
    case List(a,b) => List(a)
    case List(a) => List(a)
} map(_(0))


text:
Q: sympy laurent polynomial factor I think there must be a simple answer to this, but I searched long and couldn't find it.
Example: A simple Laurent Polynomial, so that
>> p = 2*y*x**2+4*y/x
A factorization gives
>> factor(p)
2*y*(x**3 + 2)/x
How do I extract the factor 2*y/x ? Is there a simple way to get the common factor in the expression when the expression isn't a polynomial? I have tried a lot, but haven't found anything remotely satisfying. The factorization must exist somewhere in the steps of factor(), right?

A: As @unutbu points out, from this question you can see that factor_list gives the factors of a polynomial in a easier to use fashon.
Unfortunately, SymPy doesn't actually deal with Laurent polynomials (see https://github.com/sympy/sympy/issues/5131). You might actually not get what you are expecting for higher order terms. What SymPy does is it sees that p is a rational function, so it factors the numerator and denominator separately.
If you also want to do this, you can use something like
n, d = fraction(cancel(p))
factor_list(n)
factor_list(d)

and manipulate the factors separately.
The cancel will ensure that there are no duplicates, which would otherwise happen automatically with factor(p), and it also puts the expression in rational form so that fraction will work. You could also use p.as_numer_denom() to skip this step (if it ends up being slow).
Alternately, you may want to consider x and 1/x as separate generators of the polynomial. Here's a (corrected) function from the above issue
def aspoly1t(p, t, z=Symbol('z')):
    """
    Rewrite p, a polynomial in t and 1/t, as a polynomial in t and z=1/t
    """
    pa, pd = cancel(p).as_numer_denom()
    pa, pd = Poly(pa, t), Poly(pd, t)
    assert pd.is_monomial
    d = pd.degree(t)
    one_t_part = pa.slice(0, d + 1)
    t_part = pa - one_t_part
    t_part = t_part.to_field().quo(pd)
    one_t_part = Poly.from_list(reversed(one_t_part.rep.rep), *one_t_part.gens, domain=one_t_part.domain)
    one_t_part = one_t_part.replace(t, z) # z will be 1/t
    ans = t_part.as_poly(t, z) + one_t_part.as_poly(t, z)
    return ans

(some day Poly will support this natively as Poly(p, x, 1/x)) You can then use factor_list on this:
>>> aspoly1t(p, x)
Poly(2*y*x**2 + 4*y*z, x, z, domain='ZZ[y]')
>>> factor_list(aspoly1t(p, x))
(2, [(Poly(y, x, y, z, domain='ZZ'), 1), (Poly(x**2 + 2*z, x, y, z, domain='ZZ'), 1)])

Note that the factors here are not the same, so it really does matter how you want to interpret and factor your Laurent polynomials.


text:
Q: Problem with OAuth in accessing Google Contacts I am trying to import the contacts of a person using google contacts API in the following PHP code . It uses OAuth 1.0 protocol :
<?php
    $consumer_key="www.spats.in";
    $secret="***********************";
    $mt = microtime();
    $rand = mt_rand();
    $nonce = md5($mt.$rand);

    $url="https://www.google.com/accounts/OAuthGetRequestToken";
    $params="oauth_callback=www.spats.in/nssc2/gmailContactsImport.php".
            "&oauth_consumer_key=$consumer_key".
            "&oauth_nonce=$nonce".
            "&oauth_signature_method=HMAC-SHA1".
            "&oauth_timestamp=".time().
            "&oauth_version=1.0".
            "&scope=https://www.google.com/m8/feeds/";

    $base_string = "GET&".urlencode($url).'?'.urlencode($params);
    $signature = base64_encode(hash_hmac('sha1', $base_string, $secret, true));
    $params.="&oauth_signature=".$signature;

    $result=file_get_contents($url."?".$params);
    echo $result;
?>

However, on executing the php code, the result is as follows :
signature_invalid base_string:GET&https%3A%2F%2Fwww.google.com%2Faccounts%2FOAuthGetRequestToken&oauth_callback%3Dwww.spats.in%252Fnssc2%252FgmailContactsImport.php%26oauth_consumer_key%3Dwww.spats.in%26oauth_nonce%3D36bc2ce5f00b79300d753bb94dc924df%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1308644840%26oauth_version%3D1.0%26scope%3Dhttps%253A%252F%252Fwww.google.com%252Fm8%252Ffeeds%252F

What is the problem with the signature? I can't seem to figure it out.

A: Okkay, the problem was with the key. I solved it myself.


text:
Q: "whether they are", "whether it is"
Whether they are useful skills, important values or good habits, parents teach us a lot that we need for life.
Whether it is useful skills, important values or good habits, parents teach us a lot that we need for life.

I don't know if these two sentences are good.
I'm worried that "whether it is" is followed by plural nouns.
I'm also worried that "whether" is followed by more than two items.

My current knowledge:
I learned the following sentences from the following websites, and I assume they are good sentences.
https://strategiesforparents.com/whether-it-be-grammatically-correct-use-of-this-phrase/ has these two sentences:

She likes drawing, whether it be portraits, landscapes, or still life sketches.
I enjoy indoor activities, whether it be reading, writing, or cooking.

https://www.inenglishwithlove.com/blog/difference-between-if-and-whether  says When introducing more than two options, use if. But with whether, we're limited to two choices. For example,

I don't know whether/if the meeting is on Tuesday or Thursday.
I don't know if the meeting is on Tuesday or Thursday, or if it's next week.

A: The words that follow "to be" ("useful skills, important values or good habits") are unimportant for determining the verb's number. More important is the subject: "they" or "it".
The plural pronoun "they" is incorrect because it has no plural referent. The singular pronoun "it" is better because the referent would be "a lot", which in this sentence would be considered singular.
The two sentences that you got from the "strategies for parents" website use the subjunctive mood (specifically, what some people call the "present subjunctive"). I won't address it here, because it's really a separate issue.
Your last statement ("When introducing more than two options, use if. But with whether, we're limited to two choices.") is incorrect. You can use either "if" or "whether" for any number of choices.