text:
Q: Memory Leaks in for loop (Objective-C iPhone) I'm getting quite a few memory leaks with the loop in my - (void)connectionDidFinishLoading:(NSURLConnection *)connection method. Just wondering whether anyone can lead me in the right direction as to how to decrease the amount of memory leaks occurring? Perhaps it isn't the best code... any help with other areas would be greatly appreciated.
//  SearchViewController.h

#import <UIKit/UIKit.h>
#import "VenueDetailViewController.h"
#import "OverlayViewController.h"
#import "TBXML.h"
#import "CoreLocationController.h"

@interface SearchViewController : UIViewController <UITableViewDelegate, UISearchBarDelegate, CoreLocationControllerDelegate> {
    VenueDetailViewController *venueDetailView;
    IBOutlet UITableView *tv;
    NSString *navBarTitle;
    NSMutableArray *venues;
    NSMutableArray *primaryCategories;
    NSString *categoryId;

    //Search properties.
    OverlayViewController *overlayView;
    IBOutlet UISearchBar *searchBar;
    BOOL letUserSelectRow;

    //Core location properties.
    CoreLocationController *CLController;

    BOOL searching;

    NSMutableData *responseData;
}

@property (nonatomic, retain) NSString *navBarTitle;
@property (nonatomic, retain) CoreLocationController *CLController;
@property (nonatomic, retain) VenueDetailViewController *venueDetailView;
@property (nonatomic, retain) OverlayViewController *overlayView;
@property (nonatomic, retain) IBOutlet UITableView *tv;
@property (nonatomic, retain) NSMutableArray *venues;
@property (nonatomic, retain) NSMutableArray *primaryCategories;
@property (nonatomic, retain) NSString *categoryId;

- (void)doneSearching_Clicked:(id)sender;
- (void)findLocations:(id)sender;
- (void)loadPlacesWithLat:(NSString *)lat andLong:(NSString *)lng;
- (void)findPostcode:(NSString *)postcode;
- (void)showReloadButton;

@end

//  SearchViewController.m

#import "SearchViewController.h"
#import "GenericCell.h"
#import "FSVenue.h"
#import "AsyncImageView.h"
#import "Helper.h"
#import "JSON.h"

@implementation SearchViewController

@synthesize tv;
@synthesize venueDetailView, overlayView;
@synthesize CLController;
@synthesize navBarTitle;
@synthesize venues, primaryCategories;
@synthesize categoryId;

- (void)viewDidLoad {
    //Set the title.
    navBarTitle = @"Nearby Places";
    self.title = navBarTitle;

    //Set background and border to clear (to allow for background image to be visible).
    tv.backgroundColor = [UIColor clearColor];
    [tv setSeparatorColor:[UIColor clearColor]];

    //Add the search bar.
    tv.tableHeaderView = searchBar;
    searchBar.autocorrectionType = UITextAutocorrectionTypeNo;

    letUserSelectRow = YES;

    venues = [[NSMutableArray alloc] init];
    primaryCategories = [[NSMutableArray alloc] init];

    //Core location init.
    CLController = [[CoreLocationController alloc] init];
    CLController.delegate = self;

    //Add a refresh icon to the top right navigation bar.
    [self showReloadButton];

    if (self.categoryId != nil) {
        [self findLocations:nil];
    }

    searching = NO;

    [super viewDidLoad];
}

- (void)showReloadButton {
    UIBarButtonItem *refreshItem = [[UIBarButtonItem alloc]
                                    initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh
                                    target:self
                                    action:@selector(findLocations:)];

    self.navigationItem.rightBarButtonItem = refreshItem;
    [refreshItem release];
}

#pragma mark -
#pragma mark Nearby Places / Core Location

- (void)findLocations:(id)sender {
    // Display loading overlay view.
    if (!searching) {
        [Helper beginLoading:self.view withTitle:navBarTitle];

        [self doneSearching_Clicked:nil];

        //Calls locationUpdate delegate method.
        [CLController.locMgr startUpdatingLocation];

        searching = YES;
    }
}

- (void)locationUpdate:(CLLocation *)location {
    NSString *lat;
    NSString *lng;
#if !(TARGET_IPHONE_SIMULATOR)
    lat = [NSString stringWithFormat:@"%f", location.coordinate.latitude];
    lng = [NSString stringWithFormat:@"%f", location.coordinate.longitude];
#else
    lat = @"-37.816016";
    lng = @"144.969717";
#endif

    [self loadPlacesWithLat:lat andLong:lng];
}

- (void)locationError:(NSError *)error {
    NSLog(@"locationError: %@", [error description]);
}

- (void)loadPlacesWithLat:(NSString *)lat andLong:(NSString *)lng {
    [CLController.locMgr stopUpdatingLocation];

    responseData = [[NSMutableData data] retain];
    NSString *url = [NSString stringWithFormat:@"https://api.foursquare.com/v1/venues.json?geolat=%@&geolong=%@", lat, lng];
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
    [[NSURLConnection alloc] initWithRequest:request delegate:self];
}

- (void)findPostcode:(NSString *)pcode {
    //Webservice URL: http://ws.geonames.org/findNearbyPostalCodes?postalcode=2000&country=AU&style=SHORT&maxRows=1

    NSString *suburb;
    NSString *postcode;
    NSString *lat1;
    NSString *lng1;

    // load and parse an xml string.
    TBXML* tbxml = [[TBXML alloc] initWithURL:[NSURL URLWithString:
                                        [NSString stringWithFormat:@"http://ws.geonames.org/findNearbyPostalCodes?postalcode=%@&country=AU&style=SHORT&maxRows=1",
                                         pcode]]];

    // obtain root element.
    TBXMLElement *root = tbxml.rootXMLElement;

    // if root element is valid.
    if (root) {
        // search for the first geonames element within the root elements children.
        TBXMLElement *code = [TBXML childElementNamed:@"code" parentElement:root];

        if (code != nil) {
            // find the lat child element of the code element.
            TBXMLElement *lat = [TBXML childElementNamed:@"lat" parentElement:code];

            if (lat != nil) {
                lat1 = [TBXML textForElement:lat];
            }

            // find the long child element of the code element.
            TBXMLElement *lng = [TBXML childElementNamed:@"lng" parentElement:code];

            if (lng != nil) {
                lng1 = [TBXML textForElement:lng];
            }

            // find the postalcode child element of the code element.
            TBXMLElement *postalcode = [TBXML childElementNamed:@"postalcode" parentElement:code];

            if (postalcode != nil) {
                postcode = [TBXML textForElement:postalcode];
            }

            // find the postalcode child element of the code element.
            TBXMLElement *name = [TBXML childElementNamed:@"name" parentElement:code];

            if (name != nil) {
                suburb = [TBXML textForElement:name];
            }

            NSLog(@"Searching Postcode %@ (%@) ...", postcode, suburb);
            NSLog(@" Lat - %@", lat1);
            NSLog(@" Long - %@", lng1);

            [self loadPlacesWithLat:lat1 andLong:lng1];
        }
    }

    // release resources
    [tbxml release];
}

#pragma mark -
#pragma mark JSON Over HTTP

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    [responseData setLength:0];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [responseData appendData:data];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    NSLog(@"connectin didFailWithError: %@", [error description]);
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    [connection release];

    NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
    //[responseData release];

    NSDictionary *dictionary = [responseString JSONValue];
    [responseString release];

    NSArray *venueArray = [[[dictionary valueForKeyPath:@"groups"] objectAtIndex:0] valueForKeyPath:@"venues"];

    if ([dictionary valueForKeyPath:@"error"] != nil) {
        [Helper displayAlertMessage:[dictionary valueForKeyPath:@"error"] withTitle:@"Foursquare"];
    }

    for (id result in venueArray) {
        FSVenue *venue = [[FSVenue alloc] init];
        venue.name = [result valueForKeyPath:@"name"];
        venue.venueId = [result valueForKeyPath:@"id"];
        venue.geoLat = [result valueForKeyPath:@"geolat"];
        venue.geoLong = [result valueForKeyPath:@"geolong"];

        NSDictionary *primaryCategoryDict = [result valueForKeyPath:@"primarycategory"];

        FSPrimaryCategory *primaryCategory = [[FSPrimaryCategory alloc] init];
        primaryCategory.iconUrl = [primaryCategoryDict valueForKeyPath:@"iconurl"];
        primaryCategory.iconUrl = [primaryCategory.iconUrl stringByReplacingOccurrencesOfString:@".png" withString:@"_64.png"];
        primaryCategory.nodeName = [primaryCategoryDict valueForKeyPath:@"nodename"];
        primaryCategory.primaryCategoryId = [NSString stringWithFormat:@"%@", [primaryCategoryDict valueForKeyPath:@"id"]];

        //Check if categories match the category selected from the FSCategory controllers.
        if (self.categoryId != nil) {
            if ([self.categoryId isEqualToString:primaryCategory.primaryCategoryId]) {
                [venues addObject:venue];
                [venue release];
                [primaryCategories addObject:primaryCategory];
                [primaryCategory release];
            } else {
                [venue release];
                [primaryCategory release];
            }
        } else {
            [venues addObject:venue];
            [venue release];
            [primaryCategories addObject:primaryCategory];
            [primaryCategory release];
        }
    }

    [tv reloadData];

    //Hide loading overlay view.
    [Helper finishLoading:navBarTitle];

    searching = NO;
}

#pragma mark -
#pragma mark Table View

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

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [venues count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"GenericCell";

    GenericCell *cell = (GenericCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (cell == nil) {
        NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:CellIdentifier owner:nil options:nil];

        for (id currentObject in topLevelObjects) {
            if ([currentObject isKindOfClass:[UITableViewCell class]]) {
                cell = (GenericCell *)currentObject;
                break;
            }
        }
    } else {
        AsyncImageView *oldImage = (AsyncImageView *)
        [cell.contentView viewWithTag:999];
        [oldImage removeFromSuperview];
    }

    FSPrimaryCategory *primaryCategory = (FSPrimaryCategory *)[primaryCategories objectAtIndex:indexPath.row];
    FSVenue *venue = (FSVenue *)[venues objectAtIndex:indexPath.row];

    AsyncImageView *asyncImage = [[[AsyncImageView alloc] initWithFrame:CGRectMake(3, 3, 48, 48)] autorelease];
    asyncImage.tag = 999;

    NSURL *url = [NSURL URLWithString:primaryCategory.iconUrl];
    [asyncImage loadImageFromURL:url];
    [cell.contentView addSubview:asyncImage];

    //The two images are 1x140 vertical gradients that UIKit automatically stretches horizontally to fit the width of the cell.
    cell.backgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"Cell_1x140.png"]];
    cell.selectedBackgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"CellSelected_1x140.png"]];

    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    cell.titleLabel.text = venue.name;

    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (venueDetailView == nil) {

        venueDetailView = [[VenueDetailViewController alloc] initWithNibName:@"VenueDetailViewController" bundle:[NSBundle mainBundle]];

        FSVenue *venue = (FSVenue *)[venues objectAtIndex:indexPath.row];

        venueDetailView.vid = venue.venueId;

        [self.navigationController pushViewController:venueDetailView animated:YES];
    }

    venueDetailView = nil;
    [venueDetailView release];
}

- (NSIndexPath *)tableView :(UITableView *)theTableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (letUserSelectRow)
        return indexPath;
    else
        return nil;
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row % 2) {
        [cell setBackgroundColor:[UIColor colorWithRed:((float)173 / 255.0f) green:((float)173 / 255.0f) blue:((float)176 / 255.0f) alpha:.60]];
    } else {
        [cell setBackgroundColor:[UIColor colorWithRed:((float)152 / 255.0f) green:((float)152 / 255.0f) blue:((float)156 / 255.0f) alpha:.60]];
    }

    cell.selectionStyle = UITableViewCellSelectionStyleGray;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    NSString *titleHeader;

    if ([venues count] == 0) {
        titleHeader = @"No venues were found.";
    } else {
        titleHeader = @"";
    }

    return titleHeader;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 55;
}

#pragma mark -
#pragma mark Search Bar

- (void)searchBarTextDidBeginEditing:(UISearchBar *)theSearchbar {
    //Add the overlay view.
    if (overlayView == nil)
        overlayView = [[OverlayViewController alloc] initWithNibName:@"OverlayViewController" bundle:[NSBundle mainBundle]];

    CGFloat yaxis = self.navigationController.navigationBar.frame.size.height;
    CGFloat width = self.view.frame.size.width;
    CGFloat height = self.view.frame.size.height;

    //Parameters x = origin on x-axis, y = origin on y-axis.
    CGRect frame = CGRectMake(0, yaxis, width, height);
    overlayView.view.frame = frame;
    overlayView.view.backgroundColor = [UIColor grayColor];
    overlayView.view.alpha = 0.5;

    overlayView.searchView = self;

    [tv insertSubview:overlayView.view aboveSubview:self.parentViewController.view];

    letUserSelectRow = NO;
    tv.scrollEnabled = NO;
}

- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)theSearchBar {
    searchBar.showsScopeBar = YES;
    [searchBar sizeToFit];

    [searchBar setShowsCancelButton:YES animated:YES];

    return YES;
}

- (BOOL)searchBarShouldEndEditing:(UISearchBar *)theSearchBar {
    searchBar.showsScopeBar = NO;
    [searchBar sizeToFit];

    [searchBar setShowsCancelButton:NO animated:YES];

    [self doneSearching_Clicked:nil];

    return YES;
}

- (void) doneSearching_Clicked:(id)sender {
    [searchBar resignFirstResponder];

    letUserSelectRow = YES;
    tv.scrollEnabled = YES;

    [overlayView.view removeFromSuperview];
    [overlayView release];
    overlayView = nil;

    //Reverse geocode postcode entered.
    if (![searchBar.text isEqualToString:@""]) {
        [self findPostcode:searchBar.text];
        searchBar.text = @"";
        [tv reloadData];
    }
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)theSearchBar {
    [self doneSearching_Clicked:nil];
}

- (void) searchBarSearchButtonClicked:(UISearchBar *)theSearchBar {
    [searchBar resignFirstResponder];
}

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

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)viewDidUnload {
    [super viewDidUnload];
}

- (void)dealloc {
    [navBarTitle release];
    [venueDetailView release];
    [CLController release];
    [tv release];
    [venues release];
    [primaryCategories release];
    [categoryId release];
    [responseData release];
    [super dealloc];
}

@end

A: If self.categoryId != nil and ![self.categoryId isEqualToString:primaryCategory.primaryCategoryId], then primaryCategory and venue are leaked. I'd just factor [primaryCategory release] (and the same for venue) out of the branches, and put it at the end of the loop.
For future help, you might like XCode's "Build and Analyse" mode, which should statically detect this kind of code flow leak and tell you exactly what allocation is leaked where.

A: You are leaking the venue and primaryCategory whenever self.categoryId is set but does not match primaryCategory.primaryCategoryId.
Your code could certainly be cleaned up:

*

*Add an -[FSVenue initWithResult:] method.

*Add an -[FSPrimaryCategory initWithDictionary:] method.

*Decide whether to use a high-resolution icon based on the device.

*The if statements at the end of the loop contain duplicated code. Consider doing this instead:

for (...) {
    ...

    //Check if categories match the category selected from the FSCategory controllers.
    if (self.categoryId
        && ![self.categoryId isEqualToString:primaryCategory.primaryCategoryId]) {
        [venue release];
        [primaryCategory release];
        continue;
    }

    [venues addObject:venue];
    [venue release];

    [primaryCategories addObject:primaryCategory];
    [primaryCategory release];
}

*

*Consider using autorelease whenever you create an object. Then you would not have leaked anything in the first place!

A: venues = [[NSMutableArray alloc] init];
primaryCategories = [[NSMutableArray alloc] init];

for (id result in venueArray) {
    FSVenue *venue = [[FSVenue alloc] init];
    venue.name = [result valueForKeyPath:@"name"];
    venue.venueId = [result valueForKeyPath:@"id"];
    venue.geoLat = [result valueForKeyPath:@"geolat"];
    venue.geoLong = [result valueForKeyPath:@"geolong"];

    NSDictionary *primaryCategoryDict = [result valueForKeyPath:@"primarycategory"];

    FSPrimaryCategory *primaryCategory = [[FSPrimaryCategory alloc] init];
    primaryCategory.iconUrl = [primaryCategoryDict valueForKeyPath:@"iconurl"];
    primaryCategory.iconUrl = [primaryCategory.iconUrl stringByReplacingOccurrencesOfString:@".png" withString:@"_64.png"];
    primaryCategory.nodeName = [primaryCategoryDict valueForKeyPath:@"nodename"];
    primaryCategory.primaryCategoryId = [NSString stringWithFormat:@"%@", [primaryCategoryDict valueForKeyPath:@"id"]];

    //Check if categories match the category selected from the FSCategory controllers.
    if (self.categoryId != nil) {
        if ([self.categoryId isEqualToString:primaryCategory.primaryCategoryId]) {
            [venues addObject:venue];

            [primaryCategories addObject:primaryCategory];
        }
    } else {
        [venues addObject:venue];

        [primaryCategories addObject:primaryCategory];
    }
    [primaryCategory release];
    [venue release];
}

You're leaking venue and primaryCategory unless they meet the conditions to be inserted in the arrays. The correct structure of this loop is above.
I take it that the arrays 'venues' and 'primaryCategories' are ivars and you release them in the dealloc method of your class. (or else you're leaking those arrays too.)

A: After the discussion we add in Jeremy's answer, here's a suggestion of code.
In your object's .h file
@interface MyObject : UIViewController <UITableViewDelegate,UITableViewDataSource> {
    NSMutableArray *venues;
    NSMutableArray *primaryCategories;
}

@property (nonatomic,retain) NSMutableArray *venues;
@property (nonatomic,retain) NSMutableArray *primaryCategories;

In your object's .m file
@implementation MyObject

@synthesize venues;
@synthesize primaryCategories;

- (void)viewDidLoad {
    [super viewDidLoad];
    self.venues = [[NSMutableArray alloc] init];
    self.primaryCategories = [[NSMutableArray alloc] init];
}

- (void)whatEverMethodYouLike {
    // The for loop here (with proper deallocs)
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    FSPrimaryCategory *primaryCategory = (FSPrimaryCategory *)[primaryCategories objectAtIndex:indexPath.row];
    // Et caetera
}

- (void)dealloc {
    [self.venues release];
    [self.primaryCategories release];
    [super dealloc];
}

A: you have one leak primaryCategory , because inside the if statement u have another if statement .. so there might have possibilities of memory leak


text:
Q: Where is Ilyn Payne and why is he not dead? Arya's killing list included Ilyn Payne, the king's torturer and executor. All of the rest of the names she had in the list

 have found their deaths in one way or another, but he dissapeared.

Was it mentioned anywhere if he died or not?

A: The last we hear of Ilyn Payne is Tywin Lannister on the toilet trying to reason with Tyrion. And the last we saw of him was actually in Season 2 Episode 9, "Blackwater", when he accompanied Cersei and the Ladies to "free them" should Stannis take the city.

Tyrion: All my life, you've wanted me dead.
A silence between father and son. If Tyrion's expecting an apology, he's not going to get one.
Tywin: But you refuse to die. I respect that. Admire it, even. You fight for what's yours.
Tyrion says nothing, crossbow still aimed right at Tywin.
Tywin: I'd never let them execute you. Is that what you fear? You think I'd let Ilyn Payne take your head? You're a Lannister! You're my son.
Game of Thrones, Season 4 Episode 10, "The Children" - Official Script

This was the last we hear of him and it's understandable as Wilko Johnson the actor who plays Ilyn was diagnosed with terminal cancer. He was then phased out of the show with his main plot going to Bronn to train with Jaime. Wilko has said in the past that he was up for a return if it was possible stating that he knows his character is still alive.

Payne is still alive in the show, and Johnson recovered from pancreatic cancer in 2014. Johnson told NME: "I'd certainly love to go back to Game Of Thrones. It was so much fun, and my character is still alive, so it's certainly possible."
Johnson added he received "lovely messages" from the show's producers when he was in hospital. "There was talk about me going back," he said.
NME, Wilko Johnson: 'I'd love to return to Game Of Thrones' (31/05/2916)

Since then Wilko has done a few tours so it's possible there were scheduling conflicts if they did ever want to bring him back and just couldn't.
I think as of Season 8 Episode 5, "The Bells", we can assume he died in the attack on King's Landing if he doesn't appear in the final episode which seems unlikely.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Wine not installing, no matter what Alright guys, here's the deal.
I'm on ubuntu 14.04 xfce version, running on an Acer C270 Chromebook with crouton. This is a clean install of Ubuntu, not upgraded from a previous version, nor did it ever have any other version of wine on it.
I'm trying to install Wine. These are the commands I've used and all the solutions I've tried already to always the exact same result.
(trusty)pineapplez13@localhost:~$ sudo add-apt-repository ppa:ubuntu-wine/ppa

To success of adding the wine ppa
(trusty)pineapplez13@localhost:~$ sudo apt-get update

Also successful
   (trusty)pineapplez13@localhost:~$ sudo apt-get install wine
Reading package lists... Done
Building dependency tree
Reading state information... Done
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:

The following packages have unmet dependencies:
 wine : Depends: wine1.6 but it is not going to be installed or
                 wine1.7 but it is not going to be installed
E: Unable to correct problems, you have held broken packages.

And this is the problem. It seems fairly common so I google and find several solutions.
Installing only Wine1.7:
(trusty)pineapplez13@localhost:~$ sudo apt-get install wine1.7
Reading package lists... Done
Building dependency tree
Reading state information... Done
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:

The following packages have unmet dependencies:
 wine1.7 : Depends: wine1.7-amd64 (= 1:1.7.26-0ubuntu1~ppa1) but it is not going to be installed
           Depends: wine1.7-i386 (= 1:1.7.26-0ubuntu1~ppa1)
           Recommends: cups-bsd
E: Unable to correct problems, you have held broken packages.

It would appear that I don't have i386 architecture right? So then I do this:
(trusty)pineapplez13@localhost:~$ sudo dpkg --add-architecture i386
(trusty)pineapplez13@localhost:~$

That is all it outputs, so it would appear to be a success. So I do apt-get update. However installing wine1.7 again returns the same result.
(trusty)pineapplez13@localhost:~$ sudo apt-get install wine1.7
Reading package lists... Done
Building dependency tree
Reading state information... Done
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:

The following packages have unmet dependencies:
 wine1.7 : Depends: wine1.7-amd64 (= 1:1.7.26-0ubuntu1~ppa1) but it is not going to be installed
           Depends: wine1.7-i386 (= 1:1.7.26-0ubuntu1~ppa1)
           Recommends: cups-bsd
E: Unable to correct problems, you have held broken packages.

So I try to install cups-bsd and it sends me on a dependency goose chase
(trusty)pineapplez13@localhost:~$ sudo apt-get install cups-bsd
Reading package lists... Done
Building dependency tree
Reading state information... Done
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:

The following packages have unmet dependencies:
 cups-bsd : Depends: cups-client (= 1.7.2-0ubuntu1)
E: Unable to correct problems, you have held broken packages.
(trusty)pineapplez13@localhost:~$ sudo apt-get install cups-client
Reading package lists... Done
Building dependency tree
Reading state information... Done
cups-client is already the newest version.
0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.
(trusty)pineapplez13@localhost:~$

I also have tried installing wine1.7 and wine-i386 at the same time
(trusty)pineapplez13@localhost:~$ sudo apt-get install wine1.7 wine1.7-i386
Reading package lists... Done
Building dependency tree
Reading state information... Done
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:

The following packages have unmet dependencies:
 wine1.7 : Depends: wine1.7-amd64 (= 1:1.7.26-0ubuntu1~ppa1) but it is not going to be installed
           Recommends: cups-bsd
 wine1.7-i386:i386 : Depends: libglib2.0-0:i386 (>= 2.12.0) but it is not going to be installed
                     Depends: libglu1-mesa:i386 but it is not going to be installed or
                              libglu1:i386
                     Depends: libgphoto2-6:i386 (>= 2.5.2) but it is not going to be installed
                     Depends: libgphoto2-port10:i386 (>= 2.5.2) but it is not going to be installed
                     Depends: libgstreamer-plugins-base0.10-0:i386 (>= 0.10.22) but it is not going to be installed
                     Depends: libgstreamer0.10-0:i386 (>= 0.10.26) but it is not going to be installed
                     Depends: libldap-2.4-2:i386 (>= 2.4.7) but it is not going to be installed
                     Depends: libpulse0:i386 (>= 1:0.99.1) but it is not going to be installed
                     Depends: libxml2:i386 (>= 2.9.0) but it is not going to be installed
                     Recommends: libasound2-plugins:i386 but it is not going to be installed
                     Recommends: libcups2:i386 but it is not going to be installed
                     Recommends: libdbus-1-3:i386 but it is not going to be installed
                     Recommends: libfontconfig1:i386 but it is not going to be installed or
                                 libfontconfig:i386
                     Recommends: libfreetype6:i386 but it is not going to be installed
                     Recommends: libgnutls26:i386 but it is not going to be installed
                     Recommends: libosmesa6:i386 but it is not going to be installed
                     Recommends: libsane:i386 but it is not going to be installed
                     Recommends: libtiff5:i386 but it is not going to be installed or
                                 libtiff4:i386 but it is not installable
                     Recommends: libxslt1.1:i386 but it is not going to be installed
                     Recommends: libxt6:i386 but it is not going to be installed
                     Recommends: p11-kit-modules:i386 but it is not going to be installed
E: Unable to correct problems, you have held broken packages.

And here it is pointing to a bunch of libraries that I apparently don't have, also pointing back to an error with the dpkg multiarching so I also tried this fix:
(trusty)pineapplez13@localhost:~$ gksu gedit /etc/dpkg/dpkg.cfg.d/multiarch

Creating a text file with foreign-architecture i386 printed in it to allow me to install wine1.7-i386. After successfully updating apt-get I try to install wine1.7-i386 and I get:
(trusty)pineapplez13@localhost:~$ sudo apt-get install wine1.7-i386
Reading package lists... Done
Building dependency tree
Reading state information... Done
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:

The following packages have unmet dependencies:
 wine1.7-i386:i386 : Depends: libglib2.0-0:i386 (>= 2.12.0) but it is not going to be installed
                     Depends: libglu1-mesa:i386 but it is not going to be installed or
                              libglu1:i386
                     Depends: libgphoto2-6:i386 (>= 2.5.2) but it is not going to be installed
                     Depends: libgphoto2-port10:i386 (>= 2.5.2) but it is not going to be installed
                     Depends: libgstreamer-plugins-base0.10-0:i386 (>= 0.10.22) but it is not going to be installed
                     Depends: libgstreamer0.10-0:i386 (>= 0.10.26) but it is not going to be installed
                     Depends: libldap-2.4-2:i386 (>= 2.4.7) but it is not going to be installed
                     Depends: libpulse0:i386 (>= 1:0.99.1) but it is not going to be installed
                     Depends: libxml2:i386 (>= 2.9.0) but it is not going to be installed
                     Recommends: libasound2-plugins:i386 but it is not going to be installed
                     Recommends: libcups2:i386 but it is not going to be installed
                     Recommends: libdbus-1-3:i386 but it is not going to be installed
                     Recommends: libfontconfig1:i386 but it is not going to be installed or
                                 libfontconfig:i386
                     Recommends: libfreetype6:i386 but it is not going to be installed
                     Recommends: libgnutls26:i386 but it is not going to be installed
                     Recommends: libosmesa6:i386 but it is not going to be installed
                     Recommends: libsane:i386 but it is not going to be installed
                     Recommends: libtiff5:i386 but it is not going to be installed or
                                 libtiff4:i386 but it is not installable
                     Recommends: libxslt1.1:i386 but it is not going to be installed
                     Recommends: libxt6:i386 but it is not going to be installed
                     Recommends: p11-kit-modules:i386 but it is not going to be installed
E: Unable to correct problems, you have held broken packages.

Once again.
Edit: I have confirmed that I do indeed have support for i386 architecture, because
sudo dpkg --print-foreign-architectures

Returns i386 so that appears not to be the problem, very strange.
Even using the -f command with apt-get doesn't change anything
(trusty)pineapplez13@localhost:~$ sudo apt-get install -f wine1.7
Reading package lists... Done
Building dependency tree
Reading state information... Done
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:

The following packages have unmet dependencies:
 wine1.7 : Depends: wine1.7-amd64 (= 1:1.7.26-0ubuntu1~ppa1) but it is not going to be installed
           Depends: wine1.7-i386 (= 1:1.7.26-0ubuntu1~ppa1)
           Recommends: cups-bsd
E: Unable to correct problems, you have held broken packages.

Also, using apt-get clean, apt-get autoclean, and apt-get -f install all return 0 packages modified in any way. Downloading through software center returns same result.
I've tried what feels like every fix that has been uploaded as a solution to this problem but to no avail. This really doesn't wake any sense, I can't find out what the problem is.
Edit: I've now given up on installing wine, so I'm just going to try to build it in a 32-bit linux container. I'll post here with the steps I used if I ever get it working.

A: First, clear your system with:
apt-get update
apt-get -f install

Then remove Wine:
apt-get remove wine wine1.6

Then install only one package, depending on your system: either amd64 or i386
sudo apt-get install wine1.7

let me see your output of doing so in case of error.


text:
Q: How can I combine string array resources? In my Android app I have multiple activities using different array resources and I want to create one that has all of them. Is there an easy way to do this so that when I add an item to the string array it is automatically added to the "All" activity?

A: You need to create a generalized array in a class called ConstantCodes.java and declare your all arrays in it as follows,
public class ConstantCodes
{
       public static String[][] arrayCollection = { { "A11","A22","A33" },
                                    { "B11","B22","B33" },
                                    { "C11","C22","C33" }
                                  };
}

Calling FirstActivity.java
private String[] firstActivityArray = ConstantCodes.arrayCollection[0]; // this will return first stored array on 0th position.

Calling SecondActivity.java
private String[] secondActivityArray = ConstantCodes.arrayCollection[1]; // this will return first stored array on 1st position.


text:
Q: Is there a standard #include convention for C++? This is a rather basic question, but it's one that's bugged me for awhile.
My project has a bunch of .cpp (Implementation) and .hpp (Definition) files.
I find that as I add additional classes and more class inter-dependencies, I have to #include other header files.  After a week or two, I end up with #include directives in lots of places.  Later, I'll try removing some of the #includes and discover that everything still works because some OTHER included class is also #including what I just removed.
Is there a simple, easy rule for putting in #includes that will stop this ugly mess from happening in the first place?  What is the best practice?
For example, I've worked on projects where the Implementation .cpp file ONLY includes the corresponding Definition .hpp file, and nothing else.  If there are any other .hpp files that need to be used by the Implementation .cpp, they are all referenced by the Definition .hpp file.

A: I always use the principle of least coupling. I only include a file if the current file actually needs it; if I can get away with a forward declaration instead of a full definition, I'll use that instead. My .cpp files always have a pile of #includes at the top.
Bar.h:
class Foo;

class Bar
{
    Foo * m_foo;
};

Bar.cpp:
#include "Foo.h"
#include "Bar.h"

A: Use only the minimum amount of includes needed. Useless including slows down compiling.
Also, you don't have to include a header if you just need to pointer to a class. In this case you can just use a forward declaration like:
class BogoFactory;

edit: Just to make it clear. When I said minimum amount, I didn't mean building include chains like:
a.h
#include "b.h"

b.h
#include "c.h"

If a.h needs c.h, it needs to be included in a.h of course to prevent maintenance problems.

A: There are several problems with the #include model used in C/C++, the main one being that it doesn't express the actual dependency graph. Instead it just concatenates a bunch of definitions in a certain order, often resulting in definitions coming in a different order in each source file.
In general, the include file hierarchy of your software is something you need to know in the same way as you know your datastructures; you have to know which files are included from where. Read your source code, know which files are high up in the hierarchy so you can avoid accidentally adding an include so that it will be included "from everywhere". Think hard when you add a new include: do I really need to include this here? What other files will be drawn in when I do this?
Two conventions (apart from those already mentioned) which can help out:

*

*One class == one source file + one header file, consistently named. Class A goes in A.cpp and A.h. Code templates and snippets are good here to reduce the amount of typing needed to declare each class in a separate file.

*Use the Impl-pattern to avoid exposing internal members in a header file. The impl pattern means putting all internal members in a struct defined in the .cpp file, and just have a private pointer with a forward declaration in the class. This means that the header file will only need to include those headerfiles needed for its public interface, and any definitions needed for its internal members will be kept out of the headerfile.

A: Some best practices:

*

*Every .cpp or .C file includes all headers it needs and does not rely on headers including other related headers

*Every .hpp or .h file includes all its dependencies and does not rely on the included headers including other related headers

*Every header is wrapped with:
#ifndef HEADER_XXX_INCLUDED
#define HEADER_XXX_INCLUDED
...
#endif /* HEADER_XXX_INCLUDED */

*Headers do not include each others in cycles

*Often: there is a single "project-wide header file" like "config.h" or ".h" which is always included first by any .cpp or .C file. Typically this has platform related configuration data, project-wide constants and macros etc.

These are not necessarily "best practice", but rules which I usually follow also:

*

*Project-specific headers are included as #include "..." and before the system-wide headers, which are included as #include <...>

*Project-specific headers are included in alphabetical order as a way to ensure that there is no accidental, hidden requirement on which order they are included. As every header should include its dependents and the headers should be protected against multiple inclusion, you should be able to include them in any order you wish.

A: Building on what antti.huima said:
Let's say you have classes A, B, and C.  A depends on (includes) B, and both A and B depend on C.  One day you discover you no longer need to include C in A, because B does it for you, and so you remove that #include statement.
Now what happens if at some point in the future you update B to no longer use C?  All of a sudden A is broken for no good reason.

A: Check out John Lakos's Large-Scale C++ Software Design.  Here's what I follow (written as an example):
Interface
// foo.h
// 1) standard include guards.  DO NOT prefix with underscores.
#ifndef PROJECT_FOO_H
#define PROJECT_FOO_H

// 2) include all dependencies necessary for compilation
#include <vector>

// 3) prefer forward declaration to #include
class Bar;
class Baz;
#include <iosfwd> // this STL way to forward-declare istream, ostream

class Foo { ... };
#endif

Implementation
// foo.cxx
// 1) precompiled header, if your build environment supports it
#include "stdafx.h"

// 2) always include your own header file first
#include "foo.h"

// 3) include other project-local dependencies
#include "bar.h"
#include "baz.h"

// 4) include third-party dependencies
#include <mysql.h>
#include <dlfcn.h>
#include <boost/lexical_cast.hpp>
#include <iostream>

Precompiled Header
// stdafx.h
// 1) make this easy to disable, for testing
#ifdef USE_PCH

// 2) include all third-party dendencies.  Do not reference any project-local headers.
#include <mysql.h>
#include <dlfcn.h>
#include <boost/lexical_cast.hpp>
#include <iosfwd>
#include <iostream>
#include <vector>
#endif

A: In A.cpp, always include A.h first, to ensure that A.h has no additional dependencies.
Include all local (same module) files before all project files before all system files, again to ensure that nothing depends on pre-included system files.
Use forward declarations as much as possible.
Use #indef/#define/#endif pattern
If a header is included in A.h, you don't need to include it in A.cpp. Any other headers A.cpp needs must be explicitly included, even if they happen to be provided by other .h files.

A: Organizing code files in C and C++:


text:
Q: Harddrive not visible after update Yesterday I upgraded from 13.04 to 14.
During the installation, I left - when I came back (a couple of hours later), it showed a black screen, nothing else. Nothing happened for about an hour, so I restarted.
Now, when I try to boot my computer, it gives an error: No bootable device
I can run Ubuntu from a LiveCD, but I can't reinstall Ubuntu. It doesn't find my original hard drive, just the usb drive.
Similarly, if I Try Ubuntu from the USB-stick and run gparted, it only recognizes the USB, but the hard drive is not visible.
Anyone have any ideas how to get Ubuntu to recognize my hard drive again?

A: There are three possibilities:

*

*Your Hard Drive is not plugged in all the way - Very likely

*Your Hard Drive is not enabled in BIOS - Likely

*Your Hard Drive has no partition table - Likely

*Your Hard Drive is broken - Likely

*Your Hard Drive connector and/or socket is broken - Not Likely

Fixing #1:

*

*Plug in your hard drive all the way

Fixing #2:

*

*Go muck around in BIOS until you enable your hard drive

Fixing #3:

*

*Boot to LiveCD

*Run command in console: ls /dev/ | grep sd

*If there's a result, continue. If no result, #4 or #5.

*Use gParted to make new partition sector

Fixing #4:

*

*Plug Hard Drive into other PC and see if it works.

*If yes, #5. If no, HDD is broken (or #3).

Fixing #5:

*

*Your hardware broke, bud. No way to fix this.


text:
Q: IsMouseOver nâo funciona Tenho um botao em WPF e mudei o estilo ao passar o mouse em cima (IsMouseOver), mas o problema é que nem sempre que passo o mouse em cima ele muda de estilo. Qdo passo o mouse muito rápido ele continua como se não estivesse com o mouse em cima, assim não mudando o estilo e tbm não aceita o clique.
Estilo do IsMouseOver:
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="true">
    <Setter Property="Background">
        <Setter.Value>
            <ImageBrush ImageSource="\Img\on.png" />
        </Setter.Value>
    </Setter>
</Trigger>

E no botao:
<Button Style="{StaticResource BotaoTeste}" Grid.Row="0" Grid.Column="0" Click="Clicado">Passe o Mouse</Button>

O que pode estar de errado?

A: Sei que esta pergunta já é velha mas segue um exemplo:
Parece complicado mas não é, clique com o botão direito do mouse sobre o botão é selecione o menu edit style > edit a copy, ele vai gerar esse codigo original do botão, então nele vc remova a linha que contem o mouse over padrão que esta comentada no código.
RenderMouseOver="{TemplateBinding IsMouseOver}
Agora adicione sua regra junto com as outras Triggers padrão como mostra o exemplo abaixo.
Tambem pode usar esta outra solução editando o ControlTemplate conforme o exemplo do link aqui!:
<Style x:Key="ButtonFocusVisual">
        <Setter Property="Control.Template">
            <Setter.Value>
                <ControlTemplate>
                    <Rectangle Margin="2"
                               SnapsToDevicePixels="true"
                               Stroke="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}"
                               StrokeThickness="1" StrokeDashArray="1 2"/>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
    <LinearGradientBrush x:Key="ButtonNormalBackground" EndPoint="0,1" StartPoint="0,0">
        <GradientStop Color="#F3F3F3" Offset="0"/>
        <GradientStop Color="#EBEBEB" Offset="0.5"/>
        <GradientStop Color="#DDDDDD" Offset="0.5"/>
        <GradientStop Color="#CDCDCD" Offset="1"/>
    </LinearGradientBrush>
    <SolidColorBrush x:Key="ButtonNormalBorder" Color="#FF707070"/>
    <Style x:Key="ButtonStyle1" TargetType="{x:Type Button}">
        <Setter Property="FocusVisualStyle" Value="{StaticResource ButtonFocusVisual}"/>
        <Setter Property="Background" Value="{StaticResource ButtonNormalBackground}"/>
        <Setter Property="BorderBrush" Value="{StaticResource ButtonNormalBorder}"/>
        <Setter Property="BorderThickness" Value="1"/>
        <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}"/>
        <Setter Property="HorizontalContentAlignment" Value="Center"/>
        <Setter Property="VerticalContentAlignment" Value="Center"/>
        <Setter Property="Padding" Value="1"/>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type Button}">
                    <Themes:ButtonChrome x:Name="Chrome" BorderBrush="{TemplateBinding BorderBrush}"
                                         Background="{TemplateBinding Background}"
                                         RenderPressed="{TemplateBinding IsPressed}"
                                         RenderDefaulted="{TemplateBinding IsDefaulted}"
                                         SnapsToDevicePixels="true">

                                        <!--RenderMouseOver="{TemplateBinding IsMouseOver}" -->

                        <ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
                                          Margin="{TemplateBinding Padding}" RecognizesAccessKey="True"
                                          SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"
                                          VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
                    </Themes:ButtonChrome>
                    <ControlTemplate.Triggers>
                        <Trigger Property="IsKeyboardFocused" Value="true">
                            <Setter Property="RenderDefaulted" TargetName="Chrome" Value="true"/>
                        </Trigger>
                        <Trigger Property="ToggleButton.IsChecked" Value="true">
                            <Setter Property="RenderPressed" TargetName="Chrome" Value="true"/>
                        </Trigger>
                        <Trigger Property="IsEnabled" Value="false">
                            <Setter Property="Foreground" Value="#ADADAD"/>
                        </Trigger>
                        <Trigger Property="IsMouseOver" Value="true">
                            <Setter Property="Background">
                                <Setter.Value>
                                    <ImageBrush ImageSource="\Img\on.png"/>
                                </Setter.Value>
                            </Setter>
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</Window.Resources>


text:
Q: Node - What are the other application frameworks like Express that run on Node ? I have been looking into node and trying to understand the various components . I have tried node express . Are there other application frameworks like express ? Is there any one framework recommended ?

A: There are many frameworks and libraries that you could include and use.  It depends on what you want to do.  npm has many libraries that you can download and use with node.  I would recommend at least downloading and using underscore or lodash for declarative programming.  They are good to have.
There are many other cool libraries/fameworks you can try like sails.js, mean.io, and yeoman.
Express is great though.  It really helps with structure and handling routes and middleware.  (For example, I was able to add gzip to my respsonses with one line of middleware code).  You could do it all without express, but it makes working with node.js so much easier.
If you want to use Web Sockets, use Socket.io.  Web Sockets are great for real-time information.  The example given is always chat, but you could use it like stack overflow when a new message, or new rep comes in.  Basically something happened from another user and you want to display it without a page refresh or polling.
To handle larger volume on an "Enterprise" level, look at the Node Cluster functionality.  You can create a node process per CPU processor core.
Again, it would be good for you to describe more about what you are trying to do, but you could build a web app with just node.js and express.


text:
Q: youtube-dl: Optimum settings for speech quality - podcasts or audiobooks There is a huge YouTube playlist containing speeches. I wish to convert them all into the best audio format OPUS with minimum file size. For speech audio tracks they recommend a Bitrate of 24 (mono) or 32 (stereo) kbps.
youtube-dl offers the option --audio-quality [1-9], where 9 should produce the smallest audio file. But with this setting it produced a OPUS file with variable bitrate around 100 kbps, instead of those mentioned above.
This is how I tried it:
youtube-dl -f bestaudio --max-downloads 99 --extract-audio \
   --audio-format opus --audio-quality 8 -o "%(title)s.%(ext)s" PLAYLIST-URL

What have I done wrong?

A: Look at the man pages explanation for --audio-quality:
--audio-quality QUALITY
          Specify ffmpeg/avconv audio quality, insert a value between 0
          (better) and 9 (worse) for VBR or a specific bitrate like 128K (default 5)

You have to include a unit on the number if you want it to be fixed, otherwise it defaults to VBR.
So try this instead:
$ youtube-dl -f bestaudio --max-downloads 99 --extract-audio \
   --audio-format opus --audio-quality 100K -o "%(title)s.%(ext)s" PLAYLIST-URL

References

*

*Can't use YouTube-dl to download specified bitrate [closed]


text:
Q: ADO.NET POCO with SQLite database - alter table instead of drop table relating to this msdn sample I've build a application which generates the database from a model. Now I think about the fact that I have a filled database and don't want to drop all tables because of the losing of my data. Is there a possibility to generate a "alter table" version of thequery instead of a "drop table" version?
regards Chris

A: If you've made changes to models and want those changes to be reflected in your database without losing data you should look at using Entity Framework Code First Migrations.
The tutorial in the link provides a good walk-through.

Migration using model first approach in entity framework


text:
Q: HOW TO CHECK IF DOM ELEMENTS ARE CORRECTLY NESTED i need help with this coding challenge.
Have the function HTMLElements(str) read the str parameter being passed which will be a string of HTML DOM elements and plain text. The elements that will be used are: b, i, em, div, p. For example: if str is "

hello world

" then this string of DOM elements is nested correctly so your program should return the string true.
If a string is not nested correctly, return the first element encountered where, if changed into a different element, would result in a properly formatted string. If the string is not formatted properly, then it will only be one element that needs to be changed. For example: if str is "
helloworld" then your program should return the string div because if the first  element were changed into a , the string would be properly formatted.
example:
Input: "

"
output:

Input: "
abc

test test test
"
output: i

Here is how far I've gotten:
function HTMLElements(str) {

 let openingTag = str.match(/<\w+>/g)
 let closingTag = str.match(/(<\/\w+>)/g)
 let strObj = {
  '
': '
',
  '
': '
',
  '': '',
  '
': '
',
  '': '',
  '': '',
  }

  let unclosedElem = []

  for(let i=0; i<openingTag.length; i++){
     console.log(closingTag)
    if(closingTag.indexOf(strObj[openingTag[i]]) ===-1){
      unclosedElem.push(closingTag.splice(closingTag.indexOf(strObj[openingTag[i]]),1))
    }
  }
  console.log(unclosedElem)
  if(unclosedElem.length === 0) return true;
  return unclosedElem[0]
}

// keep this function call here
HTMLElements("

")

now i understand this is far from solving the challenge but i guess it's a start for me. I will eventually solve this but your inputs are appreciated

A: There are a couple of issues.
First, you are doing closingTag.indexOf(...) === -1. If it's equal to -1, it means that this closing tag was not found at all. But the requirement is to "detect a problem" even if the closing tag is here, but in the wrong order (not nested correctly).
So, a first fix you could do is:
closingTag.indexOf(...) !== closingTag.length - i

This would count backward from the end of the closing tags array. Because the first opening tag corresponds to the last closing tag.
But then, we have a problem. indexOf will return the first occurrence of a tag. But what if we have multiple div tags nested inside of each other? It would not know which one you're referring to.
My suggestion, instead of using indexOf, would be to go from left to right in the opening tags array, while going from right to left in the closing tags array. An easy way to do it is to .reverse() the second array so that you can go in the same direction with both:

function HTMLElements(str) {
  let openingTags = str.match(/<\w+>/g)
  let closingTags = str.match(/(<\/\w+>)/g).reverse();
  let strObj = {
    '
': '
',
    '
': '
',
    '': '',
    '
': '
',
    '': '',
    '': '',
  };

  // There might not be the same number of opening and closing tags
  const max = Math.max(openingTags.length, closingTags.length);

  for (let i = 0; i < max; i++) {
    if (strObj[openingTags[i]] !== closingTags[i]) {
      return (openingTags[i] || closingTags[i]).replace(/<|>/g, '');
    }
  }

  return true;
}

function demo(str) {
  const res = HTMLElements(str);
  console.log(str, '\t--> ', res);
}

demo("

"); // "div" (closing a `div` with a `p`)
demo("

");   // "b" (because `<b/>` is invalid)
demo("

");          // "p" (wrong order)
demo("

");             // "p" (not closed at all)
demo("

");      // "/b" (not opened)
demo("

");   // true

A: I have worked an alternative solution, based on the one posted by blex. As a note, this method does not take into account if the tag is malformed, so it might be necessary to watch out for that.

function HTMLElements(str) {
    let openingTags = str.match(/<\w+>/g)
    let closingTags = str.match(/(<\/\w+>)/g);
    let sin_par = []

    for (const ciclo_1 in openingTags) {
        tiene_par = false
        for (ciclo_2 in closingTags) {
            //console.log("##: " + openingTags[ciclo_1] + " : " + closingTags[ciclo_2])
            if (openingTags[ciclo_1] === closingTags[ciclo_2].replace("/", "")) {
                closingTags.splice(ciclo_2, 1)
                tiene_par = true
            }
        }

        if (tiene_par == false) {
            //console.log("etiqueta sin par: " + openingTags[ciclo_1].replace(/<|>/g, ''))
            sin_par.push(openingTags[ciclo_1].replace(/<|>/g, ''))
        }
    }
    longitud = sin_par.length
    //console.log("RESULTADO: " + sin_par)
    return longitud>0 ? sin_par[0] : true;

}

console.log(HTMLElements("

abc

hola

"));
console.log(HTMLElements("

"));
console.log(HTMLElements("

/
"));
console.log(HTMLElements("
abc

test test test
"));

A: Further work on blex's solution to account for case strings such as
abc

test test test
 where the div tag was opened and closed right away and not having any other tags nested in it.

function HTMLElements(str) {
  const openingTags = str.match(/<\w+>/g)
  const closingTags = str.match(/(<\/\w+>)/g);

  const strObj = {
    '
': '
',
    '
': '
',
    '': '',
    '
': '
',
    '': '',
    '': '',
  };

  // there might not be the same number of opening and closing tags
  const max = Math.max(openingTags.length, closingTags.length);

  for (let i = 0; i < max; i++) {
    if (strObj[openingTags[i]] !== closingTags[closingTags.length - 1] && strObj[openingTags[i]] !== closingTags[0]) {
      return (openingTags[i]).replace(/<|>/g, '');
    }
      closingTags.splice(closingTags.indexOf(strObj[openingTags[i]]),1);
  }

  return "true";
}

console.log(HTMLElements("

hello world

"));
console.log(HTMLElements("
helloworld"));
console.log(HTMLElements("

"));
console.log(HTMLElements("
abc

test test test
"));
console.log(HTMLElements("

"));

But when I think more deeply about the problem and take into account "If a string is not nested correctly, return the first element encountered where, if changed into a different element, would result in a properly formatted string. If the string is not formatted properly, then it will only be one element that needs to be changed", this condition sure helps, knowing that it can only be one element not nested correctly
That said, I think a better solution and approach would be:

function HTMLElements(str) {
  const openingTags = str.match(/<\w+>/g)
  const closingTags = str.match(/(<\/\w+>)/g);

  const strObj = {
    '
': '
',
    '
': '
',
    '': '',
    '
': '
',
    '': '',
    '': '',
  };

  for(let i = 0; i < openingTags.length; i++) {
    const openingTag = openingTags[i];
    const closingTag = strObj[openingTag];
    if (closingTag) {
      const closingTagIndex = closingTags.indexOf(closingTag);
      if (closingTagIndex > -1) {
        closingTags.splice(closingTagIndex, 1);
      }
      else return openingTags[i].replace(/<|>/g, '');
    }
  }
  return "true";
}

console.log(HTMLElements("

hello world

"));
console.log(HTMLElements("
helloworld"));
console.log(HTMLElements("

"));
console.log(HTMLElements("
abc

test test test
"));
console.log(HTMLElements("

"));

Another approach would be to make a frequency count of the tags using dictionaries and do a comparison for the ones that don't add up:

function HTMLElements(str) {
  const openingTags = str.match(/<\w+>/g)
  const closingTags = str.match(/(<\/\w+>)/g);

  const strObj = {
    '
': '
',
    '
': '
',
    '': '',
    '
': '
',
    '': '',
    '': '',
  };

  const expectedClosingTagsDict = {};
  openingTags.forEach(tag => {
    const validClosingTag = strObj[tag];
    if(validClosingTag) {
      expectedClosingTagsDict[validClosingTag] ? expectedClosingTagsDict[validClosingTag]++ : expectedClosingTagsDict[validClosingTag] = 1;
    }
  });

  const actualClosingTagsDict = {};
  closingTags.forEach(tag => {
    actualClosingTagsDict[tag] ? actualClosingTagsDict[tag]++ : actualClosingTagsDict[tag] = 1;
  });

  for (let tag in expectedClosingTagsDict){
    if (expectedClosingTagsDict[tag]  !== actualClosingTagsDict[tag]) return tag.replace(/<|\/|>/g, '');
  }
  return "true";
}

console.log(HTMLElements("

hello world

"));
console.log(HTMLElements("
helloworld"));
console.log(HTMLElements("

"));
console.log(HTMLElements("
abc

test test test
"));
console.log(HTMLElements("

"));

Not sure which is the fastest but I'd definitely pick my second or third solution over the first when thinking of performance, space & time complexity, and readability.
I think I'd finally pick the third solution over the second one as the third would run in O(n) whereas the second is not guaranteed to run in O(n) but looks more like O(n * m), more akin to quadratic time due to the nested splice in the for-loop. A whole lot more to discuss and factor in here but in the end, you can just do timed tests and pick one over the other really ♂

A: Here is the python solution for this problem:
import re

def string_check(str):
    opening_tags = ["
","","
",""]
    closing_tags = ["
","","
",""]

    stack = []

    tags_list = re.split('(<[^>]*>)', str)[1::2]

    for tag in tags_list:
        if tag in opening_tags:
            stack.append(tag)
        elif tag in closing_tags:
            pos = closing_tags.index(tag)
            if (len(stack) > 0) and (opening_tags[pos] == stack[len(stack)-1]):
                stack.pop()
            else:
                continue
    if stack:
        return stack[-1].replace('<','').replace('>','')
    return True

A: Using PHP
$div="

";

function sub_str($str, $start, $end)
{
    return substr($str, $start, $end - $start );
}
function find_open_tag($str) {

    $open_tags=array(
        "
"=>"div",
        "
"=>"p",
        ""=>"b",
        ""=>"i",
        ""=>"em",

    );
    $closed_tags=array(
        "
"=>"
",
        "
"=>"
",
        ""=> "",
        ""=>"",
        ""=>"",
    );

    for($i=0;$i<strlen($str);$i++){
        if($open=array_search(sub_str($str,$i,$i+5),$closed_tags)){
            $start=strpos($str,sub_str($str,$i,$i+5));
            $end=strpos($str,$open);
            if($end !== false){
                find_open_tag(sub_str($str,$start+5,$end));
            }else {
                return $open_tags[sub_str($str,$i,$i+5)];
            }

        }elseif($open=array_search(sub_str($str,$i,$i+4),$closed_tags) ){
            $start=strpos($str,sub_str($str,$i,$i+4));
            $end=strpos($str,$open);
            if($end !== false){
                find_open_tag(sub_str($str,$start+4,$end));
            }else {
                return $open_tags[sub_str($str,$i,$i+4)];
            }
        }elseif($open=array_search(sub_str($str,$i,$i+3),$closed_tags) ){

            $start=strpos($str,sub_str($str,$i,$i+3));
            $end=strpos($str,$open);
            if($end !== false){
                find_open_tag(sub_str($str,$start+3,$end));
            }else {

                return $open_tags[sub_str($str,$i,$i+3)];
            }
        }

    }
    return false;
}
function StringChallenge($str) {

    $closed_tags=array(
        "
"=>"
",
        "
"=>"
",
        ""=> "",
        ""=>"",
        ""=>"",
    );

    for($i=0;$i<strlen($str);$i++){

        if($open=array_search(sub_str($str,$i,$i+5),$closed_tags)){
            $start=strpos($str,sub_str($str,$i,$i+5));
            $end=strpos($str,$open);
            if($value=find_open_tag(sub_str($str,$start+5,$end))){
                return htmlspecialchars($value);
            }

            $i=$end;
        }elseif($open=array_search(sub_str($str,$i,$i+4),$closed_tags) ){
            $start=strpos($str,sub_str($str,$i,$i+4));
            $end=strpos($str,$open);
            if($value=find_open_tag(sub_str($str,$start+4,$end))){
                return htmlspecialchars($value);
            }
            $i=$end;
        }elseif($open=array_search(sub_str($str,$i,$i+3),$closed_tags) ){
            $start=strpos($str,sub_str($str,$i,$i+3));
            $end=strpos($str,$open);
            if($value=find_open_tag(sub_str($str,$start+3,$end))){
                return htmlspecialchars($value);
            }
            $i=$end;
        }

    }
    return "true";

  }
// keep this function call here
echo StringChallenge($div);

A: Here is an entirely alternate direction
if the nodes are properly nested, it removes them until all have been removed (so we know they were all properly nested), OR when it finds not properly nested nodes, it returns the first node that could be changed to rectify the issue.
function HTMLElements(str) {
  while (str != theThing(str)){
    str = theThing(str);
    if (!str.match("</"))
      return "true";
  }
  const badTag = str.match(/<(\w+?)>[^>]*?<\/\w+?>/);
  return badTag[1];
}
function theThing(str){
  const endTag = str.match(/<\/(\w+?)>/);
  var replace = "<"+endTag[1]+">[^<]*?<."+endTag[1]+">";
  var re = new RegExp(replace,"");
  str = str.replace(re,"");
  return str;
}
// keep this function call here
console.log(HTMLElements(readline()));

A: Here is another approach using Stack and not regex.

*

*We want to create a method converStringToList. This will need as a replacement for using regex.

*Then in the htmlElements method I want to instantiate a stack, an array of openTags and closeTags, a string called res and converStringToList.

*We iterate the converStringToList and check if current is an openTag. If it is, push into the stack.

*If current is a closeTag and index of stack peek in openTag is equal to the index of current in closeTag, pop it out of the stack because they match

*If current is a closeTag and index of stack peek in openTag is not equal to the index of current in closeTag, then we have met the condition and return stack peek.

htmlElement method
public static String htmlElements (String str) {
        List<String> list = convertStringToList(str);
        Stack<String> stack = new Stack<>();
        String[] openTags = {"
", "", "
", "", "
", "", ""};
        String[] closeTags = {"
", "", "
", "", "
", "", ""};
        String res = "";

        for (String s : list) {
            if (Arrays.asList(openTags).contains(s)) {
                stack.push(s);
            } else if (
                    Arrays.asList(closeTags).contains(s) &&
                    Arrays.asList(openTags).indexOf(stack.peek()) ==
                    Arrays.asList(closeTags).indexOf(s)
            ) {
                stack.pop();
            } else if (
                    Arrays.asList(closeTags).contains(s) &&
                    Arrays.asList(openTags).indexOf(stack.peek()) !=
                    Arrays.asList(closeTags).indexOf(s)
            ) {
                res = stack.peek();
                break;
            }

        }

        return res;
    }

converStringToList method
public static List<String> convertStringToList(String str) {
        List<String> list = new ArrayList<>();

        int left, right,  i = 0;
        int n = str.length();

        while (i < n) {

            if (str.charAt(i) == '<') {
                right = i;
                while (str.charAt(right) != '>') {
                    right++;
                }
                right++;
                list.add(str.substring(i, right));
            }

            if (i > 0 && str.charAt(i - 1) == '>' && str.charAt(i) != '<') {
                left = i;
                while (str.charAt(left) != '<') {
                    left++;
                }
                list.add(str.substring(i, left));
            }

            i++;
        }

        return list;
    }


text:
Q: Swashbuckle/Swagger + ASP.Net Core: "Failed to load API definition" I develop an ASP.NET Core 2 application and included Swagger. Everything worked fine until I introduced a method without explicitly defining the HTTP action:
public class ErrorController : Controller
{
    [Route("/error")]
    public IActionResult Index()
    {
        return StatusCode(500, new Error("Internal error."));
    }
}

When I started the app with this method, the following message showed up:

Failed to load API definition.
Errors
Fetch error Internal Server Error /swagger/v1/swagger.json

As soon as I explicitly set e.g. [HttpGet] the error disappears. The problem with this is, I need this method to fire for all possible HTTP operations.
Of course, I could specify all operations explicitly, but I have the feeling Swagger should be able to handle this correctly.
Why does Swagger behave this way?
Is there any configuration I can use?

A: Add Httpxxx([HttpGet], [HttpPost], ...) attribute for each Action method, or [ApiExplorerSettings(IgnoreApi = true)]

A: In addition to Helder Sepulvedas answer and from 'Monte-Christos' answer in this github issue - Actions require unique method/path combination for Swagger

I found the place to configure ResolveConflictingActions in ASP.NET
  Core apps. In your Setup class, add this to the ConfigureServices()
  method:

services.AddSwaggerGen(c =>
  {
    other configs...;
    c.ResolveConflictingActions(apiDescriptions => apiDescriptions.First());
  });

This done the trick for me!

A: Simply you can look into the log in the Output window. The actual error can be seen there. In my case, I missed adding HTTP action on top of a methods

A: Swagger also throws the same exception if there are public methods that are not actions in a controller. The fix is to make all of them protected or private or as mentioned add the attribute [ApiExplorerSettings(IgnoreApi = true)].

A: in my case i use this code as like as .net code
[ActionName("Login")]
[HttpPost]

now i change it for use on net core web api
[HttpPost("Login")]

And it works right

A: The option ResolveConflictingActions should be working on this case...
Here is the actual error:
System.NotSupportedException: Ambiguous HTTP method for action

That is coming from:
https://github.com/domaindrivendev/Swashbuckle.AspNetCore/blob/86cc761bc4f5dda796f80ad8dfd8bc205542a6f6/src/Swashbuckle.AspNetCore.SwaggerGen/Generator/SwaggerGenerator.cs#L90
I think this is a bug, if you are truly interested you should report it to the project

A: Instead of blindy guessing what could be the issue, navigate to
http:///swagger/v1/swagger.json

In my case this could have been resolved by using the
c.CustomSchemaIds(x => x.FullName);
which is a horrible workaround, but might be a quick fix for someone in need. My solution was to rename and clarify the path for those endpoints

A: I had the same issue. In my case, All of my controllers inherited from a BaseController. in this base class, I got a public action which returns UserId according to Claims. I set the [NonAction] attribute on the top of this action.
[ApiController]
[ApiResultFilter]
[Route("api/[controller]")]
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]

public class BaseController : ControllerBase
{

    [NonAction]
    public int GetCurrentUserId()
    {
        return int.Parse(this.User.Claims.First(p => p.Type == ClaimTypes.NameIdentifier).Value);
    }
}

A: Guess what... started getting this error page "Failed to load API definition":

By looking at the app's console or the output window in Visual Studio it told me the following:

I added a public method called Client to the Web API BaseController and Swagger was thinking it should be included in the API.
To solve the problem: mark that method as protected:

A: I was also getting this error because i created a controller which dosent have [Route("api/[controller]")]. After putting it, the error went away.
app.UseSwagger()
   .UseSwaggerUI(c =>
   {
       c.SwaggerEndpoint("/swagger/v1/swagger.json", "DOA.API V1");
   });

A: Double check , if you have used same url name in your same controller. It was happened to my code

A: What worked for me is adding [NonAction] attribute to the public methods that are not API calls in my controller wrapper.

A: The default api controller route configuration is the cause of this issue. When we add the API controller in the ASP.NET Core API application, by default it has controller-specific routes, which means it can support only a single method for each of the HTTP verbs Post, PUT, Delete, GET, and Patch.
There may be a requirement when we need to create more than one method having the Http verbs Post, PUT, Delete, GET, and Patch in a single controller, and if you create the method with the default route configuration, then you will get the following error while loading the Swagger UI.

The solution is that you have to change the default route configuration at the controller level when you have created more than one method with the HTTP verbs "post," "put," and "get." Delete or Put in the single API controller class.
Consider the following example: I have created the ASP.NET Core API application, which has by default one Get method, GetWeatherForecast, which returns the WeatherForecast. Then I have added one more Get method named WeatherForecastByCity in the default API Controller class without modifying the default route.
 [ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
    private static readonly string[] Summaries = new[]
    {
    "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};

    private readonly ILogger<WeatherForecastController> _logger;

    public WeatherForecastController(ILogger<WeatherForecastController> logger)
    {
        _logger = logger;
    }

    [HttpGet(Name = "GetWeatherForecast")]
    public IEnumerable<WeatherForecast> Get()
    {
        return Enumerable.Range(1, 5).Select(index => new WeatherForecast
        {
            Date = DateTime.Now.AddDays(index),
            TemperatureC = Random.Shared.Next(-20, 55),
            Summary = Summaries[Random.Shared.Next(Summaries.Length)]
        })
        .ToArray();
    }

    [HttpGet(Name = "WeatherForecastByCity")]
    public IEnumerable<WeatherForecast> Get(string city)
    {
        return Enumerable.Range(1, 5).Select(index => new WeatherForecast
        {
            Date = DateTime.Now.AddDays(index),
            TemperatureC = Random.Shared.Next(-20, 55),
            Summary = Summaries[Random.Shared.Next(Summaries.Length)]
        })
        .ToArray();
    }
}

When we have run the application, we will get the Swagger loading error,

Now change the default route at controller level which can support more than one method having the Http verbs Post, PUT, Delete, GET, and Patch in a single controller.
[Route("api/[controller]/[action]")]

Also, remove the name of the method from the HTTP verb, which is defined using the Name attribute; just define the HTTP verb and proper method name.
Change from
 [HttpGet(Name = "GetWeatherForecast")]
    public IEnumerable<WeatherForecast> Get()
    {
        return Enumerable.Range(1, 5).Select(index => new WeatherForecast
        {
            Date = DateTime.Now.AddDays(index),
            TemperatureC = Random.Shared.Next(-20, 55),
            Summary = Summaries[Random.Shared.Next(Summaries.Length)]
        })
        .ToArray();
    }

To
 [HttpGet]
    public IEnumerable<WeatherForecast> GetWeatherForecast()
    {
        return Enumerable.Range(1, 5).Select(index => new WeatherForecast
        {
            Date = DateTime.Now.AddDays(index),
            TemperatureC = Random.Shared.Next(-20, 55),
            Summary = Summaries[Random.Shared.Next(Summaries.Length)]
        })
        .ToArray();
    }

Full Code
 [ApiController]
[Route("api/[controller]/[action]")]
public class WeatherForecastController : ControllerBase
{
    private static readonly string[] Summaries = new[]
    {
    "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};

    private readonly ILogger<WeatherForecastController> _logger;

    public WeatherForecastController(ILogger<WeatherForecastController> logger)
    {
        _logger = logger;
    }

    [HttpGet]
    public IEnumerable<WeatherForecast> GetWeatherForecast()
    {
        return Enumerable.Range(1, 5).Select(index => new WeatherForecast
        {
            Date = DateTime.Now.AddDays(index),
            TemperatureC = Random.Shared.Next(-20, 55),
            Summary = Summaries[Random.Shared.Next(Summaries.Length)]
        })
        .ToArray();
    }

     [HttpGet]
    public IEnumerable<WeatherForecast> WeatherForecastByCity(string city)
    {
        return Enumerable.Range(1, 5).Select(index => new WeatherForecast
        {
            Date = DateTime.Now.AddDays(index),
            TemperatureC = Random.Shared.Next(-20, 55),
            Summary = Summaries[Random.Shared.Next(Summaries.Length)]
        })
        .ToArray();
    }
}

Now, run the application again after changing the default route, and you will see swagger loads without any issue.

A: This is answer 32 so there is a variety of reasons!
-> You need to troubleshoot efficiently
Solutions differ from some only working for NSwag/Swashbuckle to different versions of Swashbuckle to adding JsonIgnore of Newtonsoft vs built in or adding the BindNever attribute which all might or might not help but for sure it costs time!
Before you start: Check if there is maybe an exception or error message in debug console. This might speed you up the most. Sometimes there is none!
Speedy troubleshooting guide:

*

*All your Controllers should have a [ApiController] attribute (if not consider adding it) so search and replace [ApiController] with [ApiController][ApiExplorerSettings(IgnoreApi = true)] to make them invisible for SwaggerGen

OptionA - Working now without any api controllers:

*Open your favorite Git tool that has a user interface and dismiss half of the changes in git until swagger loads https://127.0.0.1:12345/swagger/index.html again and that way rule it down to a single controller that breaks swashbuckle

*Comment out all Get/Post/Put/Delete actions within this single controller and check if it is working.

*Comment back in half of that actions until it is no longer working and that way rule it down to a single action

*Comment out the whole content of the Action and just return Ok(); to see if response is the problem.

*Try with a replacement request class that just has a fraction of the props and narrow it down to a property causing the problem.

OptionB - Still not working even without any api controllers:

*

*Try to reproduce with a fresh minimal project using the same package version and make the new project more and more similar to your big one. Your problem is likely already the initialisation which might be broken e.g. due to breaking changes or incompatibility within packages.

When you have the root cause the solution is often obvious
In my case the root cause was that I had a property of type "Type" in the request POCO which was failing without leaving any hint about what the problem is. The solution was to change it to a function which even made more sense than how it was.
If you know how to improve this guide write it in the comments.

A: I don't know if this has been resolved or not but one way you can go about this is by decorating the method with:
[ApiExplorerSettings(IgnoreApi = true)]

This will ensure that the method in question is ignored by Swagger.

A: Another possible issue is that the endpoint needs to be complete from the domain root.
I had:
app.UseSwaggerUI(c =>
{
     c.SwaggerEndpoint("/swagger/v1/swagger.json", "V1 Docs");
});

I had to use:
 app.UseSwaggerUI(c=>
{
     c.SwaggerEndpoint("/myApi/swagger/v1/swagger.json", "V1 Docs");

});

A: In ASP.NET Core, if there is a controller endpoint like:
[Route("images")]
[HttpGet("{id}")]

This can also fail with fetch failed. The solution is to have something like
[HttpGet("images/{id}")]

Same thing goes for HttpPost.

A: My error reason was that same url name,
 [HttpGet("get/LeaveCommand/{id}")]

I use same url and swagger cannot get them
 [HttpGet("get/LeaveCommand/{id}")]

A: I also had this problem. I checked and applied all of the solutions for swagger config but the issue still remained.
Finally, I checked the output panel and the problem was because of [DefaultValue("SYSDATETIMEOFFSET()")].
The answer is here: Check the output panel and you will find the answer

A: I was getting below error in .net core web api:
Swashbuckle.AspNetCore.SwaggerGen.SwaggerGeneratorException: Failed to generate Operation for action - WebApplication9.Controllers.AnimalsController.Post (WebApplication9). See inner exception
Solution:
Make sure to use the different class/name per models, I was passing the same name with different properties. So swagger json schemas wasn't identifying the correct one.
Example:
UserController.cs
[HttpPost, Route("Create")]
public IActionResult Create(CreateRequest model) {}

PersonController.cs
[HttpPost, Route("Create")]
public IActionResult Create(CreateRequest model) {}

So, we need to use different models as parameter such as UserCreateRequest and  PersonCreateRequest.

A: When you use Swagger is necessary to add [ApiExplorerSettings(IgnoreApi = true)] in your code like this:
    [Route("/error")]
    [ApiExplorerSettings(IgnoreApi = true)]
    public IActionResult HandleError() =>
        Problem();

A: I've got the error mentioned in the question and didn't find in answers the simple reason like:
Endpoints should have unique routes i.e. distinct by name, VERB etc.

Swagger is struggled when 2 endpoints routs looks the same
Check recently added endpoint(s) if they are not duplicating from routing perspective (name, verbs etc.)
in my case i was experimenting and did a copy-paste like this:

once i've made them distinct routes, Swagger was ok

the solution is simply specify a unique route

A: I was getting a TypeLoadException on a class that I was deleting that was unused. The fix in my case was to delete the bin/obj/Debug folder contents. Clean solution + rebuild solution did not fix for me.

A: It happened because of Newtonsoft.Json in my case. But the thing is I was not using it. One of the packages may be depend on it but I did not have time to check.
So just check the output panenl solve the related issue.

A: If you have in your models (request or response) properties of type which inherits/implements types like System.ComponentModel (or other types) this will throw an error
"The JSON property 'item' is defined multiple times on type"...

Try to ignore this property using [JsonIgnore] attribute of Newtonsoft.Json
In my case i had a getter of type DataTable

A: In the Startup file you need to make sure that you add
services.AddSwaggerDocument();

before you add
app.UseOpenApi();
app.UseSwaggerUi3();

or it can result in this error

Fetch error undefined /swagger/{documentName}/swagger.json

A: for core 3 I had the same issue and was really confused that problem was in slash.
Configuration was:
services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo { Title = "my-API", Version = "v1" });
            });

This swagger endpoint threw the message of TS:
app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/v1/swagger.json", "my-API v1");
            });

And finally I got it worked with removing the first slash in the URL:
app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("v1/swagger.json", "my-API v1");
            });

A: For me the problem was having registering swagger after MapControllers middleware. Once I moved before it worked.

A: For me it was a very simple issue, i had 3 [HttpGet] methods which turned out i needed to change the "createOrder" method to a [HttpPost]
        [HttpGet]
        public async Task<ActionResult<List<Order>>> GetOrders()
        {
            return await _context.Orders.Include(o => o.OrderItems).Where(x => x.BuyerId == User.Identity.Name).ToListAsync();
        }

        [HttpGet("{id}", Name = "GetOrder")]
        public async Task<ActionResult<Order>> GetOrder(int id)
        {
            return await _context.Orders.Include(x => x.OrderItems).Where(x => x.BuyerId == User.Identity.Name && x.Id == id).FirstOrDefaultAsync();
        }

        [HttpPost]
        public async Task<ActionResult<int>> CreateOrder(CreateOrderDto orderDto)
        {
            var basket = await _context.Baskets.RetrieveBasketWithItems(User.Identity.Name).FirstOrDefaultAsync();
            var items = new List<OrderItem>();
}

A: For me it was solved by adding the HttpGet attribute and removing the index methods.

A: The issue for me was caused by lazy/frustrated refactoring and I was able to determine the issue by reading the debug console when running the API in debugger mode.
Due to the bad refactoring, I ended up with two models with the same name, and Swagger was getting confused.
I had something like:
PROJECT
├───Auth
│       AutheController.cs
│       UserDto.cs
│
└───Controllers
    │   MyContrller.cs
    │
    └───Models
            UserDto.cs

Having two UserDto models is what was confusing Swagger. Cleaning this up fixed the issues.

A:
And the logs.....
System.ArgumentOutOfRangeException: Count cannot be less than zero. (Parameter 'count')

And in my case, the Route definition was wrong.
Before  (returns error)
Note the lack of {curly braces} in the Route definition.
[HttpGet]
[Route("id:guid")]

After (all good - no error)
[HttpGet]
[Route("{id:guid}")]

A: Make sure you methods in controller are marked with [HttPost] and/or [HttpGet]

A: use the [HttpGet("Post")] or [HttpGet("Get")] in your Actions

A: I found out that using enums in your object class (get, put, or post) also causes this issue.
By removing the line below in my

AddJsonOptions

I had it resolved.
options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());


text:
Q: Absolute value in indefinite integral
I have to show that $$ \int \left(\frac{dx}{x^2 \sqrt{x^2+4}}\right) = \left(\frac{-\sqrt{x^2+4}}{4x}\right) + c$$

I used the substitution $ \frac{x}{2} = \tan u$, and I got:
$$\frac{1}{4}\int \left(\frac{ |\cos u|\; du}{ (\sin u)^2 }\right)$$
I saw in the solution of this task that $|\cos u| = \cos u$. Why do we ignore the absolute value?
Thanks in advance.

A: When defining $x=\tan u$ and from $$-\infty<x=\tan u<\infty$$we conclude that $$-{\pi \over 2}<u<{\pi \over 2}$$is sufficient. In this interval $0<\cos u\le1$ and $$|\cos u|=\cos u$$

A: Note that the domain of $\tan (u)$ is $u \in \big(-\frac{\pi}{2}, \frac{\pi}{2}\big)$.
Where is $\cos(u)$ positive? What can you conclude from that regarding $\vert \cos(u)\vert$ and $\cos(u)$?


text:
Q: Visual Studio 2008 debug does not stop on error I have a simple Windows App written in Visual Studio 2008 (.NET 3.0, C#).
Without making any change to the project, solution or Visual Studion (from what I can remember), something weird is happening: when I debug (or run) my application, when it hits an error, Visual Studio does not show me any messagebox with the error, and does not stop execution. It "looks" like nothing happened... the code after the error is not executed, but everything else continues to behave like nothing had happened.
What might be wrong?

A: Click Debug, Exceptions (Ctrl+D, E) and tell Visual Studio to break on all exceptions.
Note that this will break on all thrown exceptions, not just all unhandled exceptions; that may not be what you want.

A: Do you have a try catch block? See if your catch block has code to handle the exception (either a messagebox showing what the exception is or logging that exception).
HTH

A: From tools menu goto Options -> Projects and Solutions -> Build and Run
from On run when build or deployment errors occur, the combobox selects Prompt to launch.


text:
Q: Waiting for all elements to have been loaded to do something? I am dynamically creating
 elements to add to the page once the page has been loaded, where the positions for these are dependent on the positions of other elements on the page.
eg.
x = $('#div1').position().left + 100;
y = $('#div1').position().top;

$('
').appendTo('#container').css({
    'position': 'absolute',
    'top': y,
    'left': x
});

Which should put the new
 element 100px to the right of '#div1'.
The problem I am having is that in the $(document).ready event, the x and y values are 100 and 0 respectively, i.e. the $('#div1').position() is returning 0 values, which I have verified by checking it on the console. Alternatively, when i put the same checks for x and y values on a button click event instead, i.e. after everything has finished loaded fully, it returns the correct x and y values that I am expecting. Which means when I am calling the function in the document.ready event, all the elements have not yet loaded on the page.
I have tried using window.load as well as trying to put it in ('#div1').ready / .load as well and neither of them work.
Is there any other event that would allow me to call the function automatically when the page loads rather than having to wait for the user to click a button?

        Sunday
        Monday
        Tuesday
        Wednesday
        Thursday
        Friday
        Saturday

    @for(var i=6; i < 21; i++)
    {

            @i:00

    }


text:
Q: hover effect respective to the value of image I have 5 images. When I hover on the 5th image the first 5 images background-color must be changed. When I hover on the 4th image the first 4 images background color must be changed, similarly for 3rd image first 3, 2nd image first 2, 1st image the 1st one background-color must be changed. How to write the CSS?
$(document).ready(function(){
  $("#images img").click(function(){
    var va = $(this).attr("name");
    if(va=='5'){
        $('.two,.three,.four,.one,.five').addClass('active');
    }else if(va=='4'){
        $('.two,.three,.four,.one').addClass('active');
        $('.five').removeClass('active');
    }else if(va=='3'){
        $('.two,.three,.one').addClass('active');
        $('.four,.five').removeClass('active');
    }else if(va=='2'){
        $('.two,.one').addClass('active');
        $('.three,.four,.five').removeClass('active');
    }else if(va=='1'){
        $('.one').addClass('active');
        $('.two,.three,.four,.five').removeClass('active');
    }
    $("#result_value").text(va);
});
$("#images img").mouseover(function(){
    var va = $(this).attr("name");
    if(va=='5'){
        $('.two,.three,.four,.one,.five').addClass('active');
    }else if(va=='4'){
        $('.two,.three,.four,.one').addClass('active');
        $('.five').removeClass('active');
    }else if(va=='3'){
        $('.two,.three,.one').addClass('active');
        $('.four,.five').removeClass('active');
    }else if(va=='2'){
        $('.two,.one').addClass('active');
        $('.three,.four,.five').removeClass('active');
    }else if(va=='1'){
        $('.one').addClass('active');
        $('.two,.three,.four,.five').removeClass('active');
    }
    });
    $("#images img").mouseleave(function(){
        $('.one,.two,.three,.four,.five').removeClass('active');
     });
   });

     <form name="imagediv" id="imagediv" method="post">

     </form>

For click and mousehover I have written the save logic so for click the added class must not be removed, for mousehover the class must be removed after mouseout butthe class is not getting removed, for this I used mouseout but this mouseout for the image class and this mouseout is applying for click also, whereas for click the added class must not be removed on mouseout and the background color is removed for mousehover a

A: You can make use of nextAll() & prevAll() to make it look simple. You need to unbind the mouseout event on click event.
$(document).ready(function () {
    var index;
    $("#images img").click(function () {
        var va = $(this).attr("name");
        $(this).addClass("active").prevAll().addClass("active");
        $(this).nextAll("img").removeClass('active');
        index = $("#images img").index(this);
        $("#result_value").text(va);
    });
    $("#images img").mouseover(function () {
        var va = $(this).attr("name");
 $(this).addClass("active").prevAll("img").addClass('active');
        $(this).nextAll("img").removeClass('active');

    });
    $("#images img").mouseout(function () {
        $("#images img").removeClass('active');
        if(index) {
              $("#images img").eq(index).addClass("active").prevAll("img").addClass("active");
             $("#images img").eq(index+1).removeClass("active");

        }
    });
});

DEMO

A: This works:

$("#images img").click(function(){
    var va = $(this).attr("name");
    $(this).prevAll().addClass("active");
    $("#result_value").text(va);
});

$("#images img").mouseover(function(){
    var va = $(this).attr("name");
    $(this).addClass("active").prevAll("img").addClass('active');
    $(this).nextAll("img").removeClass('active');
});

$("#images img").mouseleave(function(){
    var va = 1 * $("#result_value").text();

    if(va > 0) {
        $('.s' + va).addClass('active').prevAll("img").addClass('active');
        $('.s' + va).nextAll().removeClass('active');
    }
    else {
        $("#images img").removeClass('active');
    }
});

Try and switch all your code to "s1, s2, ..." instead of "one, two...". It's far easier to build those class names programatically and, as you can see, you need to.
Also try not to use name any more on anything other than form inputs. It's non-standard HTML. Maybe switch to HTML5 and the data- attributes class.
Here's the fiddle.


text:
Q: Proving the inequality $ \frac {x+y}{x^2+y^2}\leq \frac 12 \left(\frac {1}{x}+\frac{1}{y}\right)$ Let $x$ and $y$ be two positive numbers:
Prove that $$ \left( \frac {x+y}{x^2+y^2}\right) \leq  \frac 12 \left(\frac {1}{x}+\frac{1}{y}\right).$$
I answered this one by squaring the two expressions. And therefore finding the difference after squaring the formulas. I don't even know if it's right but I wanted to find another way to answer this question?

A: Just notice that the following inequalities are equivalent to each other:
$$
\begin{align*}
\frac {x+y}{x^2+y^2} &\leq  \frac 12 \left(\frac {1}{x}+\frac{1}{y}\right)\\
\frac {x+y}{x^2+y^2} &\le \frac12 \cdot \frac{x+y}{xy}\\
\frac 1{x^2+y^2} &\le \frac12 \cdot \frac{1}{xy}\\
2xy &\le x^2+y^2
\end{align*}
$$
The last one is a well-known inequality:

*

*Simple algebra question - proving $a^2+b^2 \geqslant 2ab$

*Show that $2 xy < x^2 + y^2$ for $x$ is not equal to $y$

*Prove the inequality $|xy|\leq\frac{1}{2}(x^2+y^2)$

*Show that for all real numbers $a$ and $b$, $\,\, ab \le (1/2)(a^2+b^2)$

A: Since $x$ and $y$ are positive, so is $x+y$, and $0\leq(x-y)^2$ since squares are always non-negative. So, $0\leq (x+y)(x-y)^2$, which expands to $0\leq x^3+y^3-xy^2-x^2y$. We can rewrite this to $$(x+y)\cdot xy \leq \tfrac{1}{2}(x(x^2+y^2)+y(x^2+y^2))$$ and dividing by $xy\cdot (x^2+y^2)$ yields
$$\frac{(x+y)\cdot xy}{xy(x^2+y^2)}=\frac{x+y}{x^2+y^2} \leq \tfrac{1}{2}\left(\frac{1}{x}+\frac{1}{y}\right)=\tfrac{1}{2}\frac{x+y}{xy}=\tfrac{1}{2}\frac{x(x^2+y^2)+y(x^2+y^2)}{xy(x^2+y^2)}$$
$$\frac{x+y}{x^2+y^2}\leq\tfrac{1}{2}\left(\frac{1}{x}+\frac{1}{y}\right)$$ which is the wanted inequality.
Hope this helped!

A: Since the inequality is homogenious, you can suppose $x+y=1$. The resulting inequality is the $AM-GM$.

Edit: An inequality $f(x_1,x_2,...,x_n)\ge 0$ is homogenius if there is some $n$ such that for all $f(tx_1,tx_2,...,tx_n)=t^nf(x_1,x_2,...,x_n)$ for all $t>0$. If an inequality is homogenius, you can suppose some condition of normality. For example $x_1+x_2+...+x_n=1$ or $x_1\times x_2\times...\times x_n=1$.

AM-GM is: for $x_1,...,x_n>0$ we have $\frac{x_1+...+x_n}{n}\ge\sqrt[n]{x_1\times...\times x_n}$

A: An alternative approach:
$\left( \frac {x+y}{x^2+y^2}\right) \leq  \frac 12 \left(\frac {1}{x}+\frac{1}{y}\right) \Longleftrightarrow 4x^2y + 4xy^2 \leq (x^2 + y^2)(2y + 2x) \Longleftrightarrow x^2y + y^2x \leq  x^3 + y^3$
We assume WLOG $x \leq y \Longrightarrow \exists c\in \mathbb{R}_{≥0}$ such that $x+c = y$
Hence the rightmost inequality can be simplified to $0 \leq (x^3 + (x+c)^3) -(x^2(x+c) + x(x+c)^2) = c^2(c+2x)$ which is clear.


text:
Q: What is the proper way to log manual SQL statements with active record? I am doing a raw sql query with PG exec_params:
ActiveRecord::Base.connection.raw_connection.exec_params(...)

When this query is executed, there is no friendly SQL logging happening.  Is there a preferred way to get that to happen so I can actually see what is executed, similar to when I do a regular query via the active record api?

A: I tried this out with
  create_table :tasks do |t|
    t.boolean :a, default: false
    t.boolean :b, default: false
    t.boolean :c, default: false
    t.string :d
    t.string :e
  end

  class Task < ActiveRecord::Base
    def self.test_sql
      random_bool = [true, false]
      sql = "insert into tasks (a, b, c, d, e) values ('0', '0', '0', ''1', 'I just dont know')"
      row_count = ActiveRecord::Base.connection.raw_connection.exec_params(sql)
    end
  end

Task.test_sql  # => #<PG::Result:0x00007faeef4461c8 status=PGRES_COMMAND_OK ntuples=0 nfields=0 cmd_tuples=1>
Task.last      # => #<Task id: 1, a: false, b: false, c: false, d: "1", e: "I just dont know">

# here is the logs
# >> D, [2020-03-04T11:21:12.977892 #17467] DEBUG -- :   ActiveRecord::InternalMetadata Load (0.2ms)  SELECT  "ar_internal_metadata".* FROM "ar_internal_metadata" WHERE "ar_internal_metadata"."key" = $1 LIMIT $2  [["key", "environment"], ["LIMIT", 1]]
# >> D, [2020-03-04T11:21:12.981050 #17467] DEBUG -- :    (0.1ms)  BEGIN
# >> D, [2020-03-04T11:21:12.981931 #17467] DEBUG -- :   ActiveRecord::InternalMetadata Create (0.3ms)  INSERT INTO "ar_internal_metadata" ("key", "value", "created_at", "updated_at") VALUES ($1, $2, $3, $4) RETURNING "key"  [["key", "environment"], ["value", "default_env"], ["created_at", "2020-03-04 10:21:12.981267"], ["updated_at", "2020-03-04 10:21:12.981267"]]
# >> D, [2020-03-04T11:21:12.982333 #17467] DEBUG -- :    (0.3ms)  COMMIT
# >> W, [2020-03-04T11:21:12.985424 #17467]  WARN -- : Creating scope :system. Overwriting existing method TaskStatus.system.
# >> D, [2020-03-04T11:21:12.991951 #17467] DEBUG -- :   Task Load (0.1ms)  SELECT  "tasks".* FROM "tasks" ORDER BY "tasks"."id" DESC LIMIT $1  [["LIMIT", 1]]