Q:

Wicket: Avoid Assigning ListChoice's Model to a Form's Model

Been playing around with this for a couple of hours and can't seem to get my head around it.
In Wicket, a List Choice takes a list of models that will represent the choices that make up the list. When the Form that the List Choice is added to is submitted, Wicket binds the selected choice's model to the Form's model.
But what if I don't want the entire model bound and instead a specific property?
For example:
public class FormModel {
        private int locationId;

        public void setLocationId(int id) {
            this.locationId = id;
        }
    }

    public class LocationModel {
        private int id;

        public int getId() {
            return this.id;
        }
    }

    <select wicket:id="LocationId" id="LocationId" name="LocationId" size="1">
        <option value="#">#</option>
    </select>

When the form is submitted, Wicket will attempt to bind an entire LocationModel to the FormModel, where clearly I just want to bind it's locationId property.
I am already using a ChoiceRenderer but that seems to only work when the form is rendered not when it is submitted.
The result is an ultimate class cast exception since Wicket won't be able to convert a LocationModel to an integer.
I would hate to create another model specifically for the form to accept a LocationModel.
Any thoughts?

A:

The Model object of a DropDownChoice (chosen value) is always one of the objects in the choices List. So, it's not possible to provide a List of choices in which elements are of one type, and store the selection in the DropDownChoice's Model in an object of a different type (*).
Just provide a List<Integer>. In case you're ok with that locationId as <option>'s text, an IChoiceRenderer wouldn't be necessary. Otherwise, your IChoiceRenderer should come up with the description with the locationId, for instance with a call to a helper function getDescriptionForLocationId(Integer locationId).
If the implementation of that getDescriptionForLocationId function would be expensive, there's another approach you can use:

Implement a custom IModel that receives a Map<Integer, String> (or builds it up during getObject() ), and in its getObject(), return the keys from the Map. That will provide a List as the DropDownChoice's choices.
Implement a getDescription() method in your custom IModel class that will query the Map for the description of an Integer.
In the IChoiceRenderer, get the DropDownChoice's Model and call its getDescription() to get the proper description.

Here's a little sample: http://pastebin.com/DhKbsdQz
Please notice the drawbacks of this approach: The Map will get serialized along with the Model (it could also be extending LoadableDetachableModel for efficiency)
(*) Thinking about it, Wicket uses equals() behind the scenes in order to establish the correspondence between the ddc's ModelObject and the elements in the List of choices, so it has its logic things are this way.


Q:

How can I change my Mii's voice?

He sounds like, as one guy on forum put it, "a dying Yoshi" and I hate it. Is it possible to change it? Some say it's based on the height, some say weight, some say color. Some said it's impossible. Testing all of those would take forever...has anyone here already figured it out?

A:

Favorite color determines the pitch of the voice. You'll just have to play around with it to find which voice you like best.


Q:

Remove cell from Apple DateCell template

Here is my latest Screenshot from the app:

Now I want to remove the cell 'Title' and the two cells '(other item 1)' and '(other item 2)'. How can I do that correctly? I'm keep getting Errors.
Here's MyTableViewController.m (edited by me and downloaded before from here)
#import "MyTableViewController.h"

#define kPickerAnimationDuration    0.40   // duration for the animation to slide the date picker into view
#define kDatePickerTag              99     // view tag identifiying the date picker view

#define kTitleKey       @"title"   // key for obtaining the data source item's title
#define kDateKey        @"date"    // key for obtaining the data source item's date value

// keep track of which rows have date cells
#define kDateStartRow   1
#define kDateEndRow     2

static NSString *kDateCellID = @"dateCell";     // the cells with the start or end date
static NSString *kDatePickerID = @"datePicker"; // the cell containing the date picker
static NSString *kOtherCell = @"otherCell";     // the remaining cells at the end

#pragma mark -

@interface MyTableViewController ()

@property (nonatomic, strong) NSArray *dataArray;
@property (nonatomic, strong) NSDateFormatter *dateFormatter;

// keep track which indexPath points to the cell with UIDatePicker
@property (nonatomic, strong) NSIndexPath *datePickerIndexPath;

@property (assign) NSInteger pickerCellRowHeight;

@property (nonatomic, strong) IBOutlet UIDatePicker *pickerView;

// this button appears only when the date picker is shown (iOS 6.1.x or earlier)
@property (nonatomic, strong) IBOutlet UIBarButtonItem *doneButton;

@end

#pragma mark -

@implementation MyTableViewController

/*! Primary view has been loaded for this view controller
 */
- (void)viewDidLoad
{
    [super viewDidLoad];

    // setup our data source
    NSMutableDictionary *itemOne = [@{ kTitleKey : @"Title" } mutableCopy];
    NSMutableDictionary *itemTwo = [@{ kTitleKey : @"Startdatum",
                                       kDateKey : [NSDate date] } mutableCopy];
    NSMutableDictionary *itemThree = [@{ kTitleKey : @"Enddatum",
                                        kDateKey : [NSDate date] } mutableCopy];
    NSMutableDictionary *itemFour = [@{ kTitleKey : @"(other item1)" } mutableCopy];
    NSMutableDictionary *itemFive = [@{ kTitleKey : @"(other item2)" } mutableCopy];
    self.dataArray = @[itemOne, itemTwo, itemThree, itemFour, itemFive];

    self.dateFormatter = [[NSDateFormatter alloc] init];
    [self.dateFormatter setDateStyle:NSDateFormatterShortStyle];    // show short-style date format
    [self.dateFormatter setTimeStyle:NSDateFormatterShortStyle];

    // obtain the picker view cell's height, works because the cell was pre-defined in our storyboard
    UITableViewCell *pickerViewCellToCheck = [self.tableView dequeueReusableCellWithIdentifier:kDatePickerID];
    self.pickerCellRowHeight = pickerViewCellToCheck.frame.size.height;

    // if the local changes while in the background, we need to be notified so we can update the date
    // format in the table view cells
    //
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(localeChanged:)
                                                 name:NSCurrentLocaleDidChangeNotification
                                               object:nil];
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:NSCurrentLocaleDidChangeNotification
                                                  object:nil];
}

#pragma mark - Locale

/*! Responds to region format or locale changes.
 */
- (void)localeChanged:(NSNotification *)notif
{
    // the user changed the locale (region format) in Settings, so we are notified here to
    // update the date format in the table view cells
    //
    [self.tableView reloadData];
}

#pragma mark - Utilities

/*! Returns the major version of iOS, (i.e. for iOS 6.1.3 it returns 6)
 */
NSUInteger DeviceSystemMajorVersion()
{
    static NSUInteger _deviceSystemMajorVersion = -1;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{

        _deviceSystemMajorVersion = [[[[[UIDevice currentDevice] systemVersion] componentsSeparatedByString:@"."] objectAtIndex:0] intValue];
    });

    return _deviceSystemMajorVersion;
}

#define EMBEDDED_DATE_PICKER (DeviceSystemMajorVersion() >= 7)

/*! Determines if the given indexPath has a cell below it with a UIDatePicker.

 @param indexPath The indexPath to check if its cell has a UIDatePicker below it.
 */
- (BOOL)hasPickerForIndexPath:(NSIndexPath *)indexPath
{
    BOOL hasDatePicker = NO;

    NSInteger targetedRow = indexPath.row;
    targetedRow++;

    UITableViewCell *checkDatePickerCell =
        [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:targetedRow inSection:2]];
    UIDatePicker *checkDatePicker = (UIDatePicker *)[checkDatePickerCell viewWithTag:kDatePickerTag];

    hasDatePicker = (checkDatePicker != nil);
    return hasDatePicker;
}

/*! Updates the UIDatePicker's value to match with the date of the cell above it.
 */
- (void)updateDatePicker
{
    if (self.datePickerIndexPath != nil)
    {
        UITableViewCell *associatedDatePickerCell = [self.tableView cellForRowAtIndexPath:self.datePickerIndexPath];

        UIDatePicker *targetedDatePicker = (UIDatePicker *)[associatedDatePickerCell viewWithTag:kDatePickerTag];
        if (targetedDatePicker != nil)
        {
            // we found a UIDatePicker in this cell, so update it's date value
            //
            NSDictionary *itemData = self.dataArray[self.datePickerIndexPath.row - 1];
            [targetedDatePicker setDate:[itemData valueForKey:kDateKey] animated:NO];
        }
    }
}

/*! Determines if the UITableViewController has a UIDatePicker in any of its cells.
 */
- (BOOL)hasInlineDatePicker
{
    return (self.datePickerIndexPath != nil);
}

/*! Determines if the given indexPath points to a cell that contains the UIDatePicker.

 @param indexPath The indexPath to check if it represents a cell with the UIDatePicker.
 */
- (BOOL)indexPathHasPicker:(NSIndexPath *)indexPath
{
    return ([self hasInlineDatePicker] && self.datePickerIndexPath.row == indexPath.row);
}

/*! Determines if the given indexPath points to a cell that contains the start/end dates.

    @param indexPath The indexPath to check if it represents start/end date cell.
*/
- (BOOL)indexPathHasDate:(NSIndexPath *)indexPath
{
    BOOL hasDate = NO;

    if ((indexPath.row == kDateStartRow) ||
        (indexPath.row == kDateEndRow || ([self hasInlineDatePicker] && (indexPath.row == kDateEndRow + 1))))
    {
        hasDate = YES;
    }

    return hasDate;
}

#pragma mark - UITableViewDataSource

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 3;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return ([self indexPathHasPicker:indexPath] ? self.pickerCellRowHeight : self.tableView.rowHeight);
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 2) {
    if ([self hasInlineDatePicker])
    {
        // we have a date picker, so allow for it in the number of rows in this section
        NSInteger numRows = self.dataArray.count;
        return ++numRows;
    }

    return self.dataArray.count;
    } else {
        if (section == 0) {
            return 2;
        } else {
            return 1;
        }

    }
}

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

    UITableViewCell *cell = nil;
    if (indexPath.section <= 1) {
        static NSString *CellIdentifier = @"Cell";

        // Configure the cell...
        //UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (!cell) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        }

        if (indexPath.section == 0) {
            switch (indexPath.row) {
                case 0:
                    cell.textLabel.text = @"Hausaufgaben";
                    cell.accessoryType = UITableViewCellAccessoryCheckmark;
                    break;
                case 1:
                    cell.textLabel.text = @"Prüfung";
                    break;

                default:
                    break;
            }

        } else {
            UITextField *lblMainLabel = [[UITextField alloc]initWithFrame:CGRectMake(50, 9, 150, 25)];
            lblMainLabel.tag = 42;
            lblMainLabel.font = [UIFont fontWithName:@"Helvetica-Neue" size:15];
            lblMainLabel.textColor = [UIColor blackColor];
            lblMainLabel.placeholder = @"Beschreibung";
            [cell.contentView addSubview:lblMainLabel];
                cell.textLabel.text = @"Mat";
            cell.selectionStyle = UITableViewCellSelectionStyleNone;

        }
    } else {
    NSString *cellID = kOtherCell;

    if ([self indexPathHasPicker:indexPath])
    {
        // the indexPath is the one containing the inline date picker
        cellID = kDatePickerID;     // the current/opened date picker cell
    }
    else if ([self indexPathHasDate:indexPath])
    {
        // the indexPath is one that contains the date information
        cellID = kDateCellID;       // the start/end date cells
    }

    cell = [tableView dequeueReusableCellWithIdentifier:cellID];

    if (indexPath.row == 0)
    {
        // we decide here that first cell in the table is not selectable (it's just an indicator)
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }

    // if we have a date picker open whose cell is above the cell we want to update,
    // then we have one more cell than the model allows
    //
    NSInteger modelRow = indexPath.row;
    if (self.datePickerIndexPath != nil && self.datePickerIndexPath.row < indexPath.row)
    {
        modelRow--;
    }

    NSDictionary *itemData = self.dataArray[modelRow];

    // proceed to configure our cell
    if ([cellID isEqualToString:kDateCellID])
    {
        // we have either start or end date cells, populate their date field
        //
        cell.textLabel.text = [itemData valueForKey:kTitleKey];
        cell.detailTextLabel.text = [self.dateFormatter stringFromDate:[itemData valueForKey:kDateKey]];
    }
   else if ([cellID isEqualToString:kOtherCell])
    {
        // this cell is a non-date cell, just assign it's text label
        //
        cell.textLabel.text = [itemData valueForKey:kTitleKey];
    }
    }

    return cell;
}

/*! Adds or removes a UIDatePicker cell below the given indexPath.

 @param indexPath The indexPath to reveal the UIDatePicker.
 */
- (void)toggleDatePickerForSelectedIndexPath:(NSIndexPath *)indexPath
{
    [self.tableView beginUpdates];

    NSArray *indexPaths = @[[NSIndexPath indexPathForRow:indexPath.row + 1 inSection:2]];

    // check if 'indexPath' has an attached date picker below it
    if ([self hasPickerForIndexPath:indexPath])
    {
        // found a picker below it, so remove it
        [self.tableView deleteRowsAtIndexPaths:indexPaths
                              withRowAnimation:UITableViewRowAnimationFade];
    }
    else
    {
        // didn't find a picker below it, so we should insert it
        [self.tableView insertRowsAtIndexPaths:indexPaths
                              withRowAnimation:UITableViewRowAnimationFade];
    }

    [self.tableView endUpdates];
}

/*! Reveals the date picker inline for the given indexPath, called by "didSelectRowAtIndexPath".

 @param indexPath The indexPath to reveal the UIDatePicker.
 */
- (void)displayInlineDatePickerForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // display the date picker inline with the table content
    [self.tableView beginUpdates];

    BOOL before = NO;   // indicates if the date picker is below "indexPath", help us determine which row to reveal
    if ([self hasInlineDatePicker])
    {
        before = self.datePickerIndexPath.row < indexPath.row;
    }

    BOOL sameCellClicked = (self.datePickerIndexPath.row - 1 == indexPath.row);

    // remove any date picker cell if it exists
    if ([self hasInlineDatePicker])
    {
        [self.tableView deleteRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:self.datePickerIndexPath.row inSection:2]]
                              withRowAnimation:UITableViewRowAnimationFade];
        self.datePickerIndexPath = nil;
    }

    if (!sameCellClicked)
    {
        // hide the old date picker and display the new one
        NSInteger rowToReveal = (before ? indexPath.row - 1 : indexPath.row);
        NSIndexPath *indexPathToReveal = [NSIndexPath indexPathForRow:rowToReveal inSection:2];

        [self toggleDatePickerForSelectedIndexPath:indexPathToReveal];
        self.datePickerIndexPath = [NSIndexPath indexPathForRow:indexPathToReveal.row + 1 inSection:2];
    }

    // always deselect the row containing the start or end date
    [self.tableView deselectRowAtIndexPath:indexPath animated:YES];

    [self.tableView endUpdates];

    // inform our date picker of the current date to match the current cell
    [self updateDatePicker];
}

/*! Reveals the UIDatePicker as an external slide-in view, iOS 6.1.x and earlier, called by "didSelectRowAtIndexPath".

 @param indexPath The indexPath used to display the UIDatePicker.
 */
- (void)displayExternalDatePickerForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // first update the date picker's date value according to our model
    NSDictionary *itemData = self.dataArray[indexPath.row];
    [self.pickerView setDate:[itemData valueForKey:kDateKey] animated:YES];

    // the date picker might already be showing, so don't add it to our view
    if (self.pickerView.superview == nil)
    {
        CGRect startFrame = self.pickerView.frame;
        CGRect endFrame = self.pickerView.frame;

        // the start position is below the bottom of the visible frame
        startFrame.origin.y = self.view.frame.size.height;

        // the end position is slid up by the height of the view
        endFrame.origin.y = startFrame.origin.y - endFrame.size.height;

        self.pickerView.frame = startFrame;

        [self.view addSubview:self.pickerView];

        // animate the date picker into view
        [UIView animateWithDuration:kPickerAnimationDuration animations: ^{ self.pickerView.frame = endFrame; }
                         completion:^(BOOL finished) {
                             // add the "Done" button to the nav bar
                             self.navigationItem.rightBarButtonItem = self.doneButton;
                         }];
    }
}

#pragma mark - UITableViewDelegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
            cell.accessoryType = UITableViewCellAccessoryCheckmark;
            UITableViewCell *cell2 = [[self tableView] cellForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:0]];
            cell2.accessoryType = UITableViewCellAccessoryNone;
             [self.tableView deselectRowAtIndexPath:indexPath animated:YES];

        }else {
            UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
            cell.accessoryType = UITableViewCellAccessoryCheckmark;
            UITableViewCell *cell2 = [[self tableView] cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
            cell2.accessoryType = UITableViewCellAccessoryNone;
             [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
        }
            }else {
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    if (cell.reuseIdentifier == kDateCellID)
    {
        if (EMBEDDED_DATE_PICKER)
            [self displayInlineDatePickerForRowAtIndexPath:indexPath];
        else
            [self displayExternalDatePickerForRowAtIndexPath:indexPath];
    }
    else
    {
        [tableView deselectRowAtIndexPath:indexPath animated:YES];
    }
    }
}

#pragma mark - Actions

/*! User chose to change the date by changing the values inside the UIDatePicker.

 @param sender The sender for this action: UIDatePicker.
 */
- (IBAction)dateAction:(id)sender
{
    NSIndexPath *targetedCellIndexPath = nil;

    if ([self hasInlineDatePicker])
    {
        // inline date picker: update the cell's date "above" the date picker cell
        //
        targetedCellIndexPath = [NSIndexPath indexPathForRow:self.datePickerIndexPath.row - 1 inSection:2];
    }
    else
    {
        // external date picker: update the current "selected" cell's date
        targetedCellIndexPath = [self.tableView indexPathForSelectedRow];
    }

    UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:targetedCellIndexPath];
    UIDatePicker *targetedDatePicker = sender;

    // update our data model
    NSMutableDictionary *itemData = self.dataArray[targetedCellIndexPath.row];
    [itemData setValue:targetedDatePicker.date forKey:kDateKey];

    // update the cell's date string
    cell.detailTextLabel.text = [self.dateFormatter stringFromDate:targetedDatePicker.date];
}

/*! User chose to finish using the UIDatePicker by pressing the "Done" button, (used only for non-inline date picker), iOS 6.1.x or earlier

 @param sender The sender for this action: The "Done" UIBarButtonItem
 */
- (IBAction)doneAction:(id)sender
{
    CGRect pickerFrame = self.pickerView.frame;
    pickerFrame.origin.y = self.view.frame.size.height;

    // animate the date picker out of view
    [UIView animateWithDuration:kPickerAnimationDuration animations: ^{ self.pickerView.frame = pickerFrame; }
                     completion:^(BOOL finished) {
                         [self.pickerView removeFromSuperview];
                     }];

    // remove the "Done" button in the navigation bar
    self.navigationItem.rightBarButtonItem = nil;

    // deselect the current table cell
    NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
    [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
}

@end

A:

I modified this sample code for my own app.  One thing I did, I modified the MutableDictionary in ViewDidLoad to change the "other cell" text to @"".  This made it basically blank, then I made the "Other Cells" background clear in the storyboard.  That may or may not work for you.  Apple really abstracts this code out a lot.  You can move the date info in the dictionary up to position 0 and the title down to position 2. Then change the values of the last 3 keys to @"".
This is the approach I took to modify this sample code.  If you start out like this, you might be able to get where you are wanting to go.
Here's is a screenshot from my app:

I don't know if it will let me post the image, I'm new to posting here.  But below is the code that I ended up using to make a tableview from the same sample code you are using. I left out a couple of imports and probably should have left out a lot more code that is not pertinent, but I just posted the whole tableViewController.  I figured a lot of this out by looking at an older version of the DateCell sample code.  It is FAR simpler.  But anyway, hope this helps.
#define kPickerAnimationDuration    0.40   // duration for the animation to slide the date picker into view
#define kDatePickerTag              99     // view tag identifiying the date picker view

#define kTitleKey       @"title"   // key for obtaining the data source item's title
#define kDateKey        @"date"    // key for obtaining the data source item's date value

// keep track of which rows have date cells
#define kDateStartRow   2
#define kDateEndRow     3

static NSString *kDateCellID = @"dateCell";     // the cells with the start or end date
static NSString *kDatePickerID = @"datePicker"; // the cell containing the date picker
static NSString *kOtherCell = @"otherCell";     // the remaining cells at the end

#pragma mark -

@interface EditShiftDetailViewController ()

@property (nonatomic, strong) NSArray *dataArray;
@property (nonatomic, strong) NSDateFormatter *dateFormatter;

// keep track which indexPath points to the cell with UIDatePicker
@property (nonatomic, strong) NSIndexPath *datePickerIndexPath;

@property (assign) NSInteger pickerCellRowHeight;

@property (nonatomic, strong) IBOutlet UIDatePicker *pickerView;

// this button appears only when the date picker is shown (iOS 6.1.x or earlier)
@property (nonatomic, strong) IBOutlet UIBarButtonItem *doneButton;

@end

#pragma mark -

@implementation EditShiftDetailViewController

/*! Primary view has been loaded for this view controller
 */
- (void)viewDidLoad
{
    [super viewDidLoad];
    UITapGestureRecognizer *gestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideKeyboard)];
    gestureRecognizer.cancelsTouchesInView = NO;
    [self.tableView addGestureRecognizer:gestureRecognizer];

    // setup our data source
    NSMutableDictionary *itemOne = [@{ kTitleKey : @"Tap a cell to change its value:" } mutableCopy];
    NSMutableDictionary *itemTwo = [@{ kTitleKey : @"Shift Name:" } mutableCopy];
    NSMutableDictionary *itemThree = [@{ kTitleKey : @"Start Time",
                                         kDateKey : self.currentShift.startTime } mutableCopy];
    NSMutableDictionary *itemFour = [@{ kTitleKey : @"End Time",
                                        kDateKey : self.currentShift.endTime } mutableCopy];
   NSMutableDictionary *itemFive = [@{ kTitleKey : @"" } mutableCopy] ;
    self.dataArray = @[itemOne, itemTwo, itemThree, itemFour, itemFive];

    self.dateFormatter = [[NSDateFormatter alloc] init];
    [self.dateFormatter setDateStyle:NSDateFormatterNoStyle];    // Don't show date
    [self.dateFormatter setTimeStyle:NSDateFormatterShortStyle]; // show short-style time format

    // obtain the picker view cell's height, works because the cell was pre-defined in our storyboard
    UITableViewCell *pickerViewCellToCheck = [self.tableView dequeueReusableCellWithIdentifier:kDatePickerID];
    self.pickerCellRowHeight = pickerViewCellToCheck.frame.size.height;

    //self.shiftNameField.text = self.currentShift.shiftName;

    self.title = [NSString stringWithFormat:@"%@, %@", self.currentDay.name, self.currentShift.shiftName];

    // if the local changes while in the background, we need to be notified so we can update the date
    // format in the table view cells
    //
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(localeChanged:)
                                                 name:NSCurrentLocaleDidChangeNotification
                                               object:nil];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    self.currentShift.startTime = [self.dataArray[2] valueForKey:kDateKey];
    self.currentShift.endTime = [self.dataArray[3] valueForKey:kDateKey];
    [[MyManager sharedManager] saveChanges];
}

- (void) hideKeyboard
{
    [self.view endEditing:YES];
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:NSCurrentLocaleDidChangeNotification
                                                  object:nil];
}

#pragma mark - Locale

/*! Responds to region format or locale changes.
 */
- (void)localeChanged:(NSNotification *)notif
{
    // the user changed the locale (region format) in Settings, so we are notified here to
    // update the date format in the table view cells
    //
    [self.tableView reloadData];
}

#pragma mark - Utilities

/*! Returns the major version of iOS, (i.e. for iOS 6.1.3 it returns 6)
 */
NSUInteger DeviceSystemMajorVersion()
{
    static NSUInteger _deviceSystemMajorVersion = -1;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{

        _deviceSystemMajorVersion = [[[[[UIDevice currentDevice] systemVersion] componentsSeparatedByString:@"."] objectAtIndex:0] intValue];
    });

    return _deviceSystemMajorVersion;
}

#define EMBEDDED_DATE_PICKER (DeviceSystemMajorVersion() >= 7)

/*! Determines if the given indexPath has a cell below it with a UIDatePicker.

 @param indexPath The indexPath to check if its cell has a UIDatePicker below it.
 */
- (BOOL)hasPickerForIndexPath:(NSIndexPath *)indexPath
{
    BOOL hasDatePicker = NO;

    NSInteger targetedRow = indexPath.row;
    targetedRow++;

    UITableViewCell *checkDatePickerCell =
    [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:targetedRow inSection:0]];
    UIDatePicker *checkDatePicker = (UIDatePicker *)[checkDatePickerCell viewWithTag:kDatePickerTag];

    hasDatePicker = (checkDatePicker != nil);
    return hasDatePicker;
}

/*! Updates the UIDatePicker's value to match with the date of the cell above it.
 */
- (void)updateDatePicker
{
    if (self.datePickerIndexPath != nil)
    {
        UITableViewCell *associatedDatePickerCell = [self.tableView cellForRowAtIndexPath:self.datePickerIndexPath];

        UIDatePicker *targetedDatePicker = (UIDatePicker *)[associatedDatePickerCell viewWithTag:kDatePickerTag];
        if (targetedDatePicker != nil)
        {
            // we found a UIDatePicker in this cell, so update it's date value
            //
            NSDictionary *itemData = self.dataArray[self.datePickerIndexPath.row - 1];
            [targetedDatePicker setDate:[itemData valueForKey:kDateKey] animated:NO];

        }
    }
}

/*! Determines if the UITableViewController has a UIDatePicker in any of its cells.
 */
- (BOOL)hasInlineDatePicker
{
    return (self.datePickerIndexPath != nil);
}

/*! Determines if the given indexPath points to a cell that contains the UIDatePicker.

 @param indexPath The indexPath to check if it represents a cell with the UIDatePicker.
 */
- (BOOL)indexPathHasPicker:(NSIndexPath *)indexPath
{
    return ([self hasInlineDatePicker] && self.datePickerIndexPath.row == indexPath.row);
}

/*! Determines if the given indexPath points to a cell that contains the start/end dates.

 @param indexPath The indexPath to check if it represents start/end date cell.
 */

- (BOOL)indexPathHasShiftName:(NSIndexPath *)indexPath
{
    return (indexPath.row == 1);
}

- (BOOL)indexPathHasDate:(NSIndexPath *)indexPath
{
    BOOL hasDate = NO;

    if ((indexPath.row == kDateStartRow) ||
        (indexPath.row == kDateEndRow || ([self hasInlineDatePicker] && (indexPath.row == kDateEndRow + 1))))
    {
        hasDate = YES;
    }

    return hasDate;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    self.currentShift.shiftName = textField.text;
    self.title = [NSString stringWithFormat:@"%@, %@", self.currentDay.name, self.currentShift.shiftName];
    [self.tableView reloadData];

    return YES;
}

#pragma mark - UITableViewDataSource

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return ([self indexPathHasPicker:indexPath] ? self.pickerCellRowHeight : self.tableView.rowHeight);
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if ([self hasInlineDatePicker])
    {
        // we have a date picker, so allow for it in the number of rows in this section
        NSInteger numRows = self.dataArray.count;
        return ++numRows;
    }

    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = nil;

    NSString *cellID = kOtherCell;

    if ([self indexPathHasPicker:indexPath])
    {
        // the indexPath is the one containing the inline date picker
        cellID = kDatePickerID;     // the current/opened date picker cell
    }
    else if ([self indexPathHasDate:indexPath])
    {
        // the indexPath is one that contains the date information
        cellID = kDateCellID;       // the start/end date cells
    }
    else if ([self indexPathHasShiftName:indexPath])
    {
        cellID = @"shiftNameCell";
    }

    cell = [tableView dequeueReusableCellWithIdentifier:cellID];

    if (indexPath.row == 0)
    {
        // we decide here that first cell in the table is not selectable (it's just an indicator)
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }

    // if we have a date picker open whose cell is above the cell we want to update,
    // then we have one more cell than the model allows
    //
    NSInteger modelRow = indexPath.row;
    if (self.datePickerIndexPath != nil && self.datePickerIndexPath.row < indexPath.row)
    {
        modelRow--;
    }

    NSDictionary *itemData = self.dataArray[modelRow];

    // proceed to configure our cell
    if ([cellID isEqualToString:kDateCellID])
    {
        // we have either start or end date cells, populate their date field
        //
        cell.textLabel.text = [itemData valueForKey:kTitleKey];
        cell.detailTextLabel.text = [self.dateFormatter stringFromDate:[itemData valueForKey:kDateKey]];
    }
    else if ([cellID isEqualToString:@"shiftNameCell"])
    {
        UITextField *txtField = (UITextField *)[cell viewWithTag:8];
        txtField.delegate = self;
        txtField.enablesReturnKeyAutomatically = YES;
        txtField.returnKeyType = UIReturnKeyDone;
        txtField.text = self.currentShift.shiftName;
    }
    else if ([cellID isEqualToString:kOtherCell])
    {
        // this cell is a non-date cell, just assign it's text label
        //
        /*if (indexPath.row == 4) {
            NSTimeInterval timeInterval = [self.currentShift.endTime timeIntervalSinceDate:self.currentShift.startTime];

            NSString *cellText = [self stringFromTimeInterval:timeInterval];

            cell.textLabel.text = [NSString stringWithFormat:@"Shift Length %@ hours", cellText];
        } else { */
        cell.textLabel.text = [itemData valueForKey:kTitleKey];
       // }
    }

    return cell;
}

- (NSString *)stringFromTimeInterval:(NSTimeInterval)interval {
    NSInteger ti = (NSInteger)interval;
    NSInteger minutes = (ti / 60) % 60;
    NSInteger hour = (ti / 3600);
    return [NSString stringWithFormat:@"%i:%02i", hour, minutes];
}

/*! Adds or removes a UIDatePicker cell below the given indexPath.

 @param indexPath The indexPath to reveal the UIDatePicker.
 */
- (void)toggleDatePickerForSelectedIndexPath:(NSIndexPath *)indexPath
{
    [self.tableView beginUpdates];

    NSArray *indexPaths = @[[NSIndexPath indexPathForRow:indexPath.row + 1 inSection:0]];

    // check if 'indexPath' has an attached date picker below it
    if ([self hasPickerForIndexPath:indexPath])
    {
        // found a picker below it, so remove it
        [self.tableView deleteRowsAtIndexPaths:indexPaths
                              withRowAnimation:UITableViewRowAnimationFade];
    }
    else
    {
        // didn't find a picker below it, so we should insert it
        [self.tableView insertRowsAtIndexPaths:indexPaths
                              withRowAnimation:UITableViewRowAnimationFade];
    }

    [self.tableView endUpdates];
}

/*! Reveals the date picker inline for the given indexPath, called by "didSelectRowAtIndexPath".

 @param indexPath The indexPath to reveal the UIDatePicker.
 */
- (void)displayInlineDatePickerForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // display the date picker inline with the table content
    [self.tableView beginUpdates];

    BOOL before = NO;   // indicates if the date picker is below "indexPath", help us determine which row to reveal
    if ([self hasInlineDatePicker])
    {
        before = self.datePickerIndexPath.row < indexPath.row;
    }

    BOOL sameCellClicked = (self.datePickerIndexPath.row - 1 == indexPath.row);

    // remove any date picker cell if it exists
    if ([self hasInlineDatePicker])
    {
        [self.tableView deleteRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:self.datePickerIndexPath.row inSection:0]]
                              withRowAnimation:UITableViewRowAnimationFade];
        self.datePickerIndexPath = nil;
    }

    if (!sameCellClicked)
    {
        // hide the old date picker and display the new one
        NSInteger rowToReveal = (before ? indexPath.row - 1 : indexPath.row);
        NSIndexPath *indexPathToReveal = [NSIndexPath indexPathForRow:rowToReveal inSection:0];

        [self toggleDatePickerForSelectedIndexPath:indexPathToReveal];
        self.datePickerIndexPath = [NSIndexPath indexPathForRow:indexPathToReveal.row + 1 inSection:0];
    }

    // always deselect the row containing the start or end date
    [self.tableView deselectRowAtIndexPath:indexPath animated:YES];

    [self.tableView endUpdates];

    // inform our date picker of the current date to match the current cell
    [self updateDatePicker];

}

/*! Reveals the UIDatePicker as an external slide-in view, iOS 6.1.x and earlier, called by "didSelectRowAtIndexPath".

 @param indexPath The indexPath used to display the UIDatePicker.
 */
- (void)displayExternalDatePickerForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // first update the date picker's date value according to our model
    NSDictionary *itemData = self.dataArray[indexPath.row];
    [self.pickerView setDatePickerMode:UIDatePickerModeTime];
    [self.pickerView setMinuteInterval:5];
    [self.pickerView setDate:[itemData valueForKey:kDateKey] animated:YES];

    // the date picker might already be showing, so don't add it to our view
    if (self.pickerView.superview == nil)
    {
        CGRect startFrame = self.pickerView.frame;
        CGRect endFrame = self.pickerView.frame;

        // the start position is below the bottom of the visible frame
        startFrame.origin.y = self.view.frame.size.height;

        // the end position is slid up by the height of the view
        endFrame.origin.y = startFrame.origin.y - endFrame.size.height;

        self.pickerView.frame = startFrame;

        [self.view addSubview:self.pickerView];

        // animate the date picker into view
        [UIView animateWithDuration:kPickerAnimationDuration animations: ^{ self.pickerView.frame = endFrame; }
                         completion:^(BOOL finished) {
                             // add the "Done" button to the nav bar
                             self.navigationItem.rightBarButtonItem = self.doneButton;
                         }];
    }
}

#pragma mark - UITableViewDelegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    if (cell.reuseIdentifier == kDateCellID)
    {
        if (EMBEDDED_DATE_PICKER)
            [self displayInlineDatePickerForRowAtIndexPath:indexPath];
        else
            [self displayExternalDatePickerForRowAtIndexPath:indexPath];
    }
    else
    {
        [tableView deselectRowAtIndexPath:indexPath animated:YES];

    }
}

#pragma mark - Actions

/*! User chose to change the date by changing the values inside the UIDatePicker.

 @param sender The sender for this action: UIDatePicker.
 */
- (IBAction)dateAction:(id)sender
{
    NSIndexPath *targetedCellIndexPath = nil;

    if ([self hasInlineDatePicker])
    {
        // inline date picker: update the cell's date "above" the date picker cell
        //
        targetedCellIndexPath = [NSIndexPath indexPathForRow:self.datePickerIndexPath.row - 1 inSection:0];
    }
    else
    {
        // external date picker: update the current "selected" cell's date
        targetedCellIndexPath = [self.tableView indexPathForSelectedRow];
    }

    UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:targetedCellIndexPath];
    UIDatePicker *targetedDatePicker = sender;

    // update our data model
    NSMutableDictionary *itemData = self.dataArray[targetedCellIndexPath.row];
    [itemData setValue:targetedDatePicker.date forKey:kDateKey];

    // update the cell's date string
    cell.detailTextLabel.text = [self.dateFormatter stringFromDate:targetedDatePicker.date];
    [[MyManager sharedManager] saveChanges];
    [self.tableView reloadData];
}

/*! User chose to finish using the UIDatePicker by pressing the "Done" button, (used only for non-inline date picker), iOS 6.1.x or earlier

 @param sender The sender for this action: The "Done" UIBarButtonItem
 */
- (IBAction)doneAction:(id)sender
{
    CGRect pickerFrame = self.pickerView.frame;
    pickerFrame.origin.y = self.view.frame.size.height;

    // animate the date picker out of view
    [UIView animateWithDuration:kPickerAnimationDuration animations: ^{ self.pickerView.frame = pickerFrame; }
                     completion:^(BOOL finished) {
                         [self.pickerView removeFromSuperview];
                     }];

    // remove the "Done" button in the navigation bar
    self.navigationItem.rightBarButtonItem = nil;

    // deselect the current table cell
    NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
    [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
}

@end


Q:

How to load memory output from QGIS processing?

Many processing algorithms have an option to save output as memory. If ran from toolbox, this works fine, because you can tick the "Open output file after running algorithm" box.
Looking at the source code for QGIS, the code for loading the memory layer seems to be defined in the function Postprocessing.handleAlgorithmResults. The function uses access to an alg.outputs list, and does the following:
for out in alg.outputs:
    progress.setPercentage(100 * i / float(len(alg.outputs)))
    if out.hidden or not out.open:
        continue
    if isinstance(out, (OutputRaster, OutputVector, OutputTable)):
        try:
            if out.value.startswith('memory:'):
                layer = out.memoryLayer                                # NOTE!!
                QgsMapLayerRegistry.instance().addMapLayers([layer])   # NOTE!!
            else:
                # ...

When you run processing algorithms from the console, is there a way to load the layer without access to this object? I can run
processing.runalg("qgis:intersection", layer1, layer2, "memory:")

or even
processing.runalg("qgis:intersection", layer1, layer2, "memory:myLayerName")

I can however not find a way to grab the resulting output.

A:

Aaaand I found it. Use processing.runandload, which loads the output layer into the table of contents after running the algorithm.
processing.runandload("qgis:intersection", layer1, layer2, "memory:myLayerName")
layer = QgsMapLayerRegistry.instance().mapLayersByName("memory:myLayerName")[0]
# Should do error checking as well, but this works!!

A:

it is the correct way, it's explained in the documentation
http://docs.qgis.org/2.14/es/docs/user_manual/processing/console.html
the next code work with in memory all except the last that it is load
MDT=path/mdt.tif
drain=processing.runalg("grass:r.drain",MDT,"",(pun),False,False,False,"%f,%f,%f,%f"% (xmin, xmax, ymin, ymax),0,-1,0.00100,None)
vect=processing.runalg("grass:r.to.vect",drain['output'],0,False,"%f,%f,%f,%f"% (xmin, xmax, ymin, ymax),0,None)
bu=processing.runalg("qgis:fixeddistancebuffer",vect['output'],Metros_afecta,1,False,None)
buf=bu['OUTPUT']
bufe= QgsVectorLayer(buf,"area", "ogr")
#the last load the layer
QgsMapLayerRegistry.instance().addMapLayers([bufe])

the processing.runalg returns a dictionary in this case bu['OUTPUT']. OUTPUT IS THE KEY, and the value is a temp path. You can see the key with processeing.alghelp("name processing") as processing,alghelp("grass:r.drain")
return
processing.alghelp("grass:r.drain")
ALGORITHM: r.drain - Traces a flow through an elevation model on a raster map.
input <ParameterRaster>
coordinate <ParameterString>
vector_points <ParameterMultipleInput>
-c <ParameterBoolean>
-a <ParameterBoolean>
-n <ParameterBoolean>
GRASS_REGION_PARAMETER <ParameterExtent>
GRASS_REGION_CELLSIZE_PARAMETER <ParameterNumber>
GRASS_SNAP_TOLERANCE_PARAMETER <ParameterNumber>
GRASS_MIN_AREA_PARAMETER <ParameterNumber>
output <OutputRaster>

in this case the key is output , take care with capital letters you must write in capital or without capital, in this case not capital.


Q:

Mass change a portion of a file name?

I have a whole bunch of files named as following (example):
ADVANTE  18''8.0 PCD5'114.3 ET45 CB73.1.jpg
ADVANTE  18x8.0 PCD6139.7 ET20 CB110.2.jpg
ADVANTE 'A MI576B 20''8.5 PCD6'139.7 ET25 CB110.2 GBXZLDCP.jpg
ADVANTE 'A SH10 15''6.5 PCD8'100-114.3 ET40 CB73.1 3FPBU.jpg

How do I go to each file and change a portion of their filename to:
ADVANTI  18''8.0 PCD5'114.3 ET45 CB73.1.jpg
ADVANTI  18x8.0 PCD6139.7 ET20 CB110.2.jpg
ADVANTI 'A MI576B 20''8.5 PCD6'139.7 ET25 CB110.2 GBXZLDCP.jpg
ADVANTI 'A SH10 15''6.5 PCD8'100-114.3 ET40 CB73.1 3FPBU.jpg

using some sort of command or app? It would take too long to rename each and every one of them manually.

A:

If you use the ZSH shell, this can be done easily in Terminal with zmv (included with OS X by default). Why use fancy scripts if the work is already done?
Type zsh in a terminal window if for some crazy reason you do not have it set as your default shell.
autoload zmv
zmv 'ADVANTE(*)' 'ADVANTI$1'


Q:

Youtube API User History (Playlistitems) without Authorization

I'm trying to retrieve the watch history data of my own Youtube account using the Youtube Javascript API. I am using the auth.js listed here.
I have made everything work, but it requires authorization (website asks you to login with a Google account so other people cannot view what i'm displaying without logging into my Youtube account).
I'm looking for a way for a website to display my Youtube history data without authorization. Reading similar questions here and googling seems to suggest that it's not possible with just Google Client API. If anyone knows a way to do this or where I should look for, please let me know. I'm new to web stuff so any help will be appreciated!
Thanks

A:

Very simple answer: It can not do without Authorization
You can do that in different way
after Authorization you can sync your youtube history with another database and show that data from fetching from that database to others


Q:

How to add "Ubuntu Font Family" to my site using CSS?

How do I add the Ubuntu Font Family in CSS editor for my site? Here's what I have for my font and header already, but  don't want the current font I have, I want Ubuntu Font.
/* ##### Common Styles ##### */

body {
  color: black;
  background-color: white;
  font-family: "times new roman", times, roman, serif;
  font-size: 12pt;
  margin: 0;
  padding: 0;
}

acronym, .titleTip {
  font-style: italic;
  border-bottom: none;
}

or
/* ##### Header ##### */

#header {
  margin: 0;
  padding: 0;
  border-bottom: 1px solid black;
}

.headerTitle {
  font-size: 200%;
  margin: 0;
  padding: 0 0 0.5ex 0;
}

.headerTitle a {
  color: black;
  background-color: transparent;
  font-family: "trebuchet ms", verdana, helvetica, arial, sans-serif;
  font-weight: normal;
  text-decoration: none;
}

.subHeader {
  display: none;
}

/* ##### Side Bars ##### */

#side-bar {
  display: none;
}

/* ##### Main Copy ##### */

#main-copy {
  text-align: justify;
  margin: 0;
  padding: 0;
}

#main-copy h1 {
  font-family: "trebuchet ms", verdana, helvetica, arial, sans-serif;
  font-size: 120%;
  margin: 2ex 0 1ex 0;
  padding: 0;

Where do I add Ubuntu Font Family? And did I insert the wrong code to help you, help me?

A:

Importing the font
First, you have to make sure, your site has that font in case the average user who vistits your site doesn't have it.
Option 1 - Import from external provider
You can import the whole font file and and settings from an external font host like Google Fonts. Just place this code to your HTML to import it externally:
<link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Ubuntu:regular,bold&subset=Latin">

Option 2 - Store it in your server
You could just download then upload the font files to your server then import them via @font-face in your CSS. In this example the place of your font file will be http://example.com/fonts/ubuntu.woff.
@font-face {
    font-family: 'Ubuntu';
    font-style: normal;
    font-weight: 400;
    src: local('Ubuntu'), url(http://example.com/fonts/ubuntu.woff) format('woff');
}

Using the font
Then you have to specify where do you want to use that font. Just add Ubuntu to your font-family list:
body {
    font-family: Ubuntu, "times new roman", times, roman, serif;
}

This example code will give the Ubuntu Font for every text in your HTML page if it is avilable.


Q:

How Gmail app gets info about new email?

How Gmail knows that some new emails are on server? Does it use GCM?
I wondering about it, because I also want to implement this king of functionality in my app. Can you give me some points to start with this?

A:

Yes, Gmail does use GCM to get push notifications of new emails. The Getting Started guide is a good place to start, although there are quite a few steps in setting up both the client (i.e., the Android side) and the server component.


Q:

git rebase ate my commits ! Translate 'git reflog' output for me?

I had done five commits and I wanted to make them all into one commit before pushing them. For some reason I decided to try doing this by a different means than I usually use.
FWIW: I was attempting to follow the instructions here http://gitready.com/advanced/2009/02/10/squashing-commits-with-rebase.html .
I'll put a lot of detail below but you might want to skip down to the bottom of the question where I put the output of git reflog because I suspect that's what's significant here.
So here's what I did - with all my changes committed I did :
git rebase -i HEAD~5

and I was presented with the text editor which showed the commits and I, wrongly I now realise, changed all the first column values of 'pick' to 'squash'.
I then saw an error message. To my shame I can't remember what the error message said but I think it said something like "You have no commit to use".
At that point I was back to the prompt and when I try to repeat the :
git rebase -i HEAD~5

I get the message :
It seems that there is already a rebase-merge directory, and
I wonder if you are in the middle of another rebase.  If that is the
case, please try
        git rebase (--continue | --abort | --skip)
If that is not the case, please
        rm -fr /home/foo/dev/bar/.git/rebase-merge
and run me again.  I am stopping in case you still have something
valuable there.

Then I read this answer https://stackoverflow.com/a/12163247/364088 which suggests doing :
git reset --soft HEAD^

I did that (I wish I had not). After I'd done it.
git status

showed a number of files with uncommitted changes although
git diff

showed no changes . Anyway I then did a
git commit

And now I have lost all my chnages in the last five commits !
git reflog

shows (this is just the top of it):
3f80e4b HEAD@{0}: commit: Decorator demo added
1888dd9 HEAD@{1}: reset: moving to HEAD^
7d6228e HEAD@{2}: checkout: moving from master to 7d6228eb9b03d0c45acf7c66e662220213cf4fb9
705736f HEAD@{3}: commit: Snapshot commit - squash later
75db0c3 HEAD@{4}: commit: Snapshot commit - squash later
b70b50f HEAD@{5}: commit: Snapshot commit - squash later
d970a62 HEAD@{6}: commit: Snapshot commit - squash later
0f24e88 HEAD@{7}: commit: Snapshot commit - squash later
7d6228e HEAD@{8}: commit: Move some standard code into its own module and tidy up .
1888dd9 HEAD@{9}: commit: Early version of the decorators demo

So the thing is the commits labelled "Snapshot commit - squash later" are the ones I wanted to merge into a single commit.
The commits HEAD@{2} and HEAD@{1} are stuff I've done in the process of trying to merge those "Snapshot commit - squash later". The commit HEAD@{0} is the commit I did after the rebase and the reset.
In case it matters the last commit pushed was HEAD@{8}.
So what I'd like is to get back to the '705736f' commit and then, ideally do the merging of commits again only this time make it work !
I'd be quite happy if I could recover the work in the "Snapshot commit - squash later" changes.
Would be grateful for advice.

A:

My preferred method is to stick a label on the thing you want to get back, like a branch:
git branch recover 705736f

At this point you can check it out (it's a new local branch) and make sure you've recovered what you wanted:
git checkout recover
git log    # or gitk, or whatever

This is a new branch label, pointing at the old (pre-rebase-attempt) commits.
Your new commit (Decorator demo added) will be on the other branch, which (in a graph log viewer, like gitk --branches or git log with --graph) forks off after the Early version of the decorators demo commit.

If you're willing to "lose" (except for in the reflog) the new commit, you can force-reset your current branch back to the old commit in the reflog:
git reset --hard 705736f

(instead of creating a new branch to point to 705736f).  Again, run git log to see if that's where you want (you can even git log 705736f first!).


Q:

Regex Optionally match a pattern multiple times

I have a string and I want to match a specific pattern optionally as many times as may occur.
My String
    0.91 0.45 0.69 58 47 45 23 83 90 $595 NO IDL
After 45 until $595 There could be upto 6 more number there. How can I optionally look for repeating number in that space?
Here's what I have so far:
/([\d.]+) ([\d.]+) ([\d.]+)? (\d+) (\d+) (\d+)  \$(\d+)/ig

Here are some samples with expected outputs:
0.91 0.45 0.69 58 47 45 23 83 90 $595 NO IDL
output: array([0] => 0.91,
              [1] => 0.45,
              [2] => 0.69,
              [3] => 58,
              [4] => 47,
              [5] => 45,
              [6] => 23,
              [7] => 83,
              [8] => 90,
              [9] => 595)

0.91 0.45 0.69 58 47 45 $595 NO IDL
output: array([0] => 0.91,
              [1] => 0.45,
              [2] => 0.69,
              [3] => 58,
              [4] => 47,
              [5] => 45,
              [5] => 595)

0.91 0.45 0.69 0.63 58 47 45 $595 NO IDL
output: Does not match the pattern because we only want 3 of the first items to contain decimals.

This seems to split the last number into multiple numbers. Can't figure out whats going on.
I am using php preg_match method for this so would like not empty elements in the resulting array if possible. Thanks.

A:

You may validate the string with a positive lookahead triggered at the start of the string, and then match all numbers from the start up to the currency value once the validation succeeds:
'~(?:\G(?!^)|^(?=\d+\.\d+ \d+\.\d+ \d+(?:\.\d+)?(?: \d+)* \$\d))\s*\$?\K\d+(?:\.\d+)?~'

See the regex demo
Details

(?:\G(?!^)|^(?=\d+\.\d+ \d+\.\d+ \d+(?:\.\d+)?(?: \d+)* \$\d)) - either the end of the previous match (\G(?!^)) or start of a string (^) that is followed with

\d+\.\d+
  - a space
\d+\.\d+
  - a space
\d+ - 1+ digits
(?:\.\d+)? - an optional fractional part
(?: \d+)* - 0+ sequences of a space followed with 1+ digits
  - space
\$\d - a $ and a digit.

\s* - 0+ whitespaces
\$? - an optional $ char
\K - match reset operator
\d+(?:\.\d+)? - an int/float number (1+ digits followed with an optional sequence of . and 1+ digits).

PHP demo:
$strs = ['0.91 0.45 0.69 58 47 45 23 83 90 $595 NO IDL','0.91 0.45 0.69 58 47 45 $595 NO IDL','0.91 0.45 0.69 0.63 58 47 45 $595 NO IDL'];
$rx = '~(?:\G(?!^)|^(?=\d+\.\d+ \d+\.\d+ \d+(?:\.\d+)?(?: \d+)* \$\d))\s*\$?\K\d+(?:\.\d+)?~';
foreach ($strs as $s) {
    echo "$s:\n";
    if (preg_match_all($rx, $s, $matches)) {
        print_r($matches[0]);
        echo "---------\n";
    } else {
        echo "NO MATCH!!!\n---------\n";
    }

}

Output:
0.91 0.45 0.69 58 47 45 23 83 90 $595 NO IDL:
Array
(
    [0] => 0.91
    [1] => 0.45
    [2] => 0.69
    [3] => 58
    [4] => 47
    [5] => 45
    [6] => 23
    [7] => 83
    [8] => 90
    [9] => 595
)
---------
0.91 0.45 0.69 58 47 45 $595 NO IDL:
Array
(
    [0] => 0.91
    [1] => 0.45
    [2] => 0.69
    [3] => 58
    [4] => 47
    [5] => 45
    [6] => 595
)
---------
0.91 0.45 0.69 0.63 58 47 45 $595 NO IDL:
NO MATCH!!!
---------


Q:

How to get all the image resources in a project’s sub folders?

I have a project like this; I want to get all the images in the “Images” folder.
If all the png files are stored in a folder on the disk, this would be easy.
But they are embedded in the project, then how can I access them?
Or even further, how do I get a tree data structure of the image resources?
Thanks

A:

You can access them using a package URI:
Image image = new Image();
image.Source = new BitmapImage(new Uri(“pack://application:,,,/Images/ImageCategory1/Burn Disc.png”));

If you want to get the folder structure:
I am afraid there is no folder structure other than that the structure in the project is added to the name of each resource.
Fortunately there is a way to enumerate all resources: searching and listing WPF resource dictionaries in a folder


Q:

ActiveMQ - Kaha persistence filling up disk

I am using ActiveMQ and kahadb 5.7.0.
My broker is configured like this :
<amq:broker id="broker" useJmx="true" persistent="true" useShutdownHook="false"  >
        <amq:transportConnectors>
            <amq:transportConnector uri="tcp://localhost:61616?jms.messagePrioritySupported=true" />
        </amq:transportConnectors>
  <amq:persistenceAdapter>
     <amq:kahaPersistenceAdapter directory="activemq-data" maxDataFileLength="10g"/>
   </amq:persistenceAdapter>

    <amq:destinationPolicy>
            <amq:policyMap>
                <amq:policyEntries>
                    <amq:policyEntry queue=">" producerFlowControl="false" prioritizedMessages="true" >  <amq:pendingQueuePolicy>
                        <amq:fileQueueCursor />
                    </amq:pendingQueuePolicy>
                    </amq:policyEntry>
        </amq:policyEntries>
            </amq:policyMap>
        </amq:destinationPolicy>
 <amq:systemUsage>
            <amq:systemUsage>
                <amq:memoryUsage>
                    <amq:memoryUsage limit="2 gb"/>
                </amq:memoryUsage>
                <amq:storeUsage>
                    <amq:storeUsage limit="20 gb"/>
                </amq:storeUsage>
                <amq:tempUsage>
                    <amq:tempUsage limit="5 gb"/>
                </amq:tempUsage>
            </amq:systemUsage>
        </amq:systemUsage>
    </amq:broker>

The problem i have is that i see files in the directory activemq-data growing in size, especially files with data-queue-data. Most of them reach the 10g limit
Why is not cleaning those files ?

A:

First thing would be to update to a recent release, 5.7.0 is years old now and many, many....many bugs have been fixed since then.
You need to investigate what is causing data to be retained in the store which all comes down to how you are using the broker and how your consumers are reading and acknowledging (or not which is likely the case) message that are placed onto the brokers queues.  One common issue is consumers using message selectors leaving old unconsumed messages lingering on the broker which will result in data being retained.
There is a very good bit of documentation on the ActiveMQ website that explains steps in debugging log file retention.


Q:

CURL for WAMP

I’m new to PHP and I’m trying to learn how to parse information, I’m trying to use CURL but I’m not able to install it on my desktop WAMP on Windows Vista. How do I install CURL?

A:

There seems to be a bug somewhere. If you are experiencing this on Windows 7 64 bit then try installing Apache addon version 2.2.9 and PHP addon version 5.3.1 and switching to those in WAMP and then activating the CURL extension. That worked for me.
You can download it from http://www.wampserver.com/en/.

A:

Check out cURL with PHP and Apache on Windows for instructions.


Q:

predefined argument value to map function. Javascript

var i = [1,2,3,4,6,7];
var k = i.map( (data, i) => { if(data==1) return 2; else return data; } );
console.log(k);

This program is going to output [2,2,3,4,6,7]
I am changing value of k based on a specific value. How can i change the value according to a specific array index using map function?
like how we do normally, array[index] = somevalue;

A:

You could check with the index of the array while iterating, with the wanted index and return a selected value or the original value.

var array = [1, 2, 3, 4, 6, 7],
    index = 3,
    result = array.map((a, i) => i === index ? 42 : a);

console.log(result);


Q:

How to set width of layer-list as a whole?

How can I specify the width of an XML drawable when using a layer-list? I want the width of the drawable (as a whole) to be set to 20dp but I don't where/how to set this + the preview pane doesn't help that much either.
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape>
            <solid android:color="@color/blue" />
        </shape>
    </item>
    <item android:left="8dp" android:right="8dp">
        <shape>
            <solid android:color="#fff" />
        </shape>
    </item>
</layer-list>

A:

You could try this:
    <shape>
        <solid android:color="#fff"/>
        <size android:height="10dp" android:width="20dp"/>
    </shape>


Q:

Why do Computers use Hex Number System at assembly language?

Why do computer use Hex Number System at assembly language? Why don't they use any other number system like binary, octal, decimal? What thing forced computer designer to use hex system at assembly? Why it looked so beneficial to them?

A:

Computers don't use the hexadecimal number system for assembly language. Assembly language, or rather machine code, uses base 256 (typically): instructions are encoded in units of bytes. When displaying machine code, it is customary to use octal or hexadecimal. The reason is that in many cases, the byte is further subdivided into bitstrings, and identifying these bitstrings is easier when using a base which is a power of 2. Hexdecimal is particularly compact since each byte can be encoded using exactly two hexadecimal digits.

A:

The simplest reason is that, the computer does not see this, it only sees the binary. This really just aids the programer. Binary is a mess to look at, octal does not usually work since an octal number is three bits and historically computers have been using 16,32,64 bit instruction sets, none of which are divisible by 3, leaving hex as the best choice.


Q:

C++ character array holding integer values

I'm trying to create a dynamic char array which will contain numbers then change these to either a X or 0,
I'm creating a tic tac toe game which creates a grid to a specific number you want, the array needs to contain all numbers for the squares and then change this number to either a X,0 depending on player,
I currently have;
const int grid_size = size * size; // determines the size of the grid height x width
char **number = new char*[grid_size]; // create the array to the size of the grid

for ( int i = 1; i <= grid_size+1; i++ ) {
    number[i] = i;
}

but with this I get a error:- error C2440: '=' : cannot convert from 'int' to 'char *' on line number[i] = i;
how would I create the array to contain the numbers - 1,grid_size, the change these numbers to either a X,0 ?

A:

You have two solutions: create an array of arrays to store your characters (that's what a matrix is fundamentally), or create a single array of char which would be the linearized version of the matrix, ie. an array containing all the rows of the matrix put together in one.
The first case is trivial:
const int grid_size = size * size; // determines the size of the grid height x width
char **number = new char*[size]; // create the array to the size of the grid

for ( int i = 0; i < size; i++ ) {
    number[i] = new char[grid_size];
    for( int j = 0; j < size; j++)
         number[i][j] = i * size + j;
}

// access any char with a double bracket notation
// beware that coordinates start at `0`
number[2][1] = 'X';

The second solution is trickier, and I recommend using a helper function to translate matrix coordinates into the array index:
const int grid_size = size * size;

int idx(int x, int y){
    return y * size + x;
}

char *number = new char[grid_size];

for (int i = 0; i < grid_size; i++)
    number[i] = i;

number[idx(2,1)] = 'O';

Characters are actually numbers in disguise, but with values way above 9, so for a regular tic-tac-toe game it should not be a problem, and you should be able to have it work with size up to 8*8. Starting from 65, the numbers start representing regular alphabet characters (ie. 65 is A, 66 is B and so on, look up the ASCII code table for more details). One way to overcome the issue, if you want to store the cell number in the cell and also keep track of the state of the game, is to use 254 and 255 as the values denoting the player moves, instead of O and X, but you will still be limited to a 7*7 grid size.
For larger size, you will probably need consider another data structure to track the game state.


Q:

Java Basics: create class object

In C++:
class Rectangle {
    int x, y;
  public:
    void set_values (int,int);
    int area () {return (x*y);}
};

int main () {
  Rectangle rect;
  rect.set_values (3,4);
}

In Java:
class Rectangle {
    int x, y;
    void set_values (int x,int y);
    int area () {return (x*y);}
}

public static void main(String[] args) {

Rectangle rect=new Rectangle(3,4);

}

In C++ compiler will create rect object & reserve memory 4 bytes. I want to know How Java is creating object?

A:

When you do: -
Rectangle rect;

in C++, it invokes, the 0-arg default constructor, provided by the compiler.
If you wanted to use a 2-arg constructor, you would have to do: -
Rectangle rect(3, 4);

wherein, you would have to provide a 2-arg constructor explicitly, else it won't compile.

Now, similar is the case in Java. If you do: -
new Rectangle();

then its ok, because, in that case, compiler will provide you with a default 0-arg constructor, as in C++, but when your create object like: -
new Rectangle(3, 4);

Then you would have to explicitly provide the class with a 2-arg constructor, else it won't compile, as in your 2nd example, that won't compile.
Also, once you provide a parameterized constructor, then in that case, Compiler won't provide the default constructor. You would have to provide a 0-arg constructor explicitly, if you want to use one. This suffice in both, Java and C++
Now, as per the memory allocation is concerned, since Java is platform independent, so the size of int type is 32 bits, in all platforms. This is in contrast to C++ where size of data types are platform dependent.
See JVM Specification - The Structure of JVM for detaled information about the allocation of various types.
P.S.: -
I suggest you to go through the below link, for basics of Java classes and objects: -

http://docs.oracle.com/javase/tutorial/java/javaOO/index.html


Q:

Specify a Directory for Save in Mathematica

Considering :
ALLdwafDif[#] & /@ symmetries

Save["ALLL.m", ALLL]

Is there a way to save the results in a particular directory ? It automatically save the results in my user directory now.

A:

The current working directory is given by Directory[]. You can set it by SetDirectory[]. Alternatively, you can append the directory name to ALLL.m and it works.
eg
f = 5;
Save["~/Desktop/temp.m", f]

does what you'd expect (~ is a shortcut for home directory on most Unices, and mma respects it, so this gets saved on my desktop)

A:

If you want to change the default working directory permanently you can add something like SetDirectory["new_dir"]; to one of the files $BaseDirectory/Kernel/init.m or $UserBaseDirectory/Kernel/init.m (which one depends on whether you want to change the default directory for all users or for the current user only). Next time you restart Mathematica, Directory[] will then automatically be set to new_dir.

A:

Save[SystemDialogInput["FileSave", "All.m"], ALLL]

brings up a standard system save-file dialog box and saves your file after you've chosen a location (and a new file name if you have chosen one).


Q:

Search engine - before string and after

A have something like this. It works fine, but I have been tried 2 hours to cut search result - 100 str before $word and 100 after.
How can I make this?
$word = $_POST["search"];

$sql_events = mysql_query("SELECT * FROM events WHERE event_title LIKE '%" . $word . "%' OR event_desc LIKE '%" . $word ."%'");

function highlightWords($content, $word){
    if(is_array($search)){
        foreach ( $search as $word ){
            $content = str_ireplace($word1, ''.$word1.'', $content);
        }
    } else {
        $content = str_ireplace($word, ''.$word.'', $content);
    }
    return $content;
}
while($row = mysql_fetch_array($sql_events)){

    $content = $row["event_desc"];

    $result = highlightWords($content, $word);
    echo '

'.$row['event_title'].'

'.$result .'...

';
}

A:

$wordpos1 = (mb_strpos($content, $word) - 100);
  if ($wordpos1 < 0){
    $wordpos1 = 0;
  } else {
    $wordpos1 = (mb_strpos($content, $word) - 100);
  }
  $wordpos2 = (mb_strpos($content, $word) + 400);

  $resText = mb_substr($content, $wordpos1, $wordpos2);

  $result = highlightWords($resText, $word);

And it's works to me :)


Q:

Which design pattern to follow to make code structured

I have created  a class called "DownloadManagerWrapper and it will call be called based on run time argument. can i follow any design pattern for the below code to make it clean and structured. which design pattern i can go for if its possible? need your advise and sample design pattern code and simple explanation if its possible because i'm new to design pattern.
public class DownloadManagerWrapper {

    public static void main(String[] args) {
    String downloadId = args[0];
    String bankId =args[1];
    String serviceId =args[2];
    readInterfaceConfig(serviceId,bankId,downloadId);
    }

    public static void readInterfaceConfig(String intfCode,String bankId,String downloadId) {

    Connection conn = CRMConnection.getConnection();

    String statusOfDownload;
    DownloadManager dwlManager = new DownloadManager();

    ResultSet rs=null;

    if(downloadId.equals("A"))
    {
    if(intfCode.equals("-1")) //all download
    {
        String query = "select INTF_CODE from CRMUSER.TABLE1 where bank_id ="+"'"+bankId+"'"+"order by INTF_CODE";
        System.out.println("query>"+query);
        try
        {
        Statement st = conn.createStatement();
        rs = st.executeQuery(query);
                while(rs.next())
             {
                    String intfCodeFromDB = rs.getString("INTF_CODE");
                    statusOfDownload = new DownloadManager().downloadDataFromCore(intfCodeFromDB,bankId,downloadId);
             }
        }
        catch(SQLException e)
        {
        e.printStackTrace();
        }
        finally
        {
        try {
            rs.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        }
    }
    else  //specific download
    {
          statusOfDownload = dwlManager.downloadDataFromCore(intfCode,bankId,downloadId);
    }
    }
    else if(downloadId.equals("I"))
    {
           if(intfCode.equals("-1")) //all download
        {
            String query = "select INTF_CODE from CRMUSER.TABLE1 where bank_id ="+"'"+bankId+"'"+"order by INTF_CODE";
            System.out.println("query>"+query);
            try
            {
            Statement st = conn.createStatement();
            rs = st.executeQuery(query);
                    while(rs.next())
                 {
                        String intfCodeFromDB = rs.getString("INTF_CODE");
                        statusOfDownload = new DownloadManager().downloadDataFromCore(intfCodeFromDB,bankId,downloadId);
                 }
            }
            catch(SQLException e)
            {
            e.printStackTrace();
            }
            finally
            {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            }
        }
        else  //specific download
        {
              statusOfDownload = dwlManager.downloadDataFromCore(intfCode,bankId,downloadId);
        }
    }
    }
}

A:

Some pointers :

Accessing DB should be through a Data Access Object (DAO)
Pattern
If you have a lot of if-statements you should take a look at the
Strategy Pattern.


Q:

Calling a function when a new row be added to a dataframe in R

I have a dataframe dd and I want to observe this dataframe, so everytime a new row is added to this dataframe, I want to call a function (to calculate new mean value of all the columns of this datafram for instance).
How could I do that in R?
Update:
Sample code:
df = data.frame(x1=as.integer(),x2=as.integer())

df = rbind (df, c(1,2)) # --> should run a function here

A:

You can do this using an S3 class:
df <- data.frame(x1 = 3, x2 = 4)
class(df) <- c("autoupdateDF", class(df))

rbind.autoupdateDF <- function(DF, newrow, colFUN = mean, ...) {
  DF <- rbind.data.frame(DF, newrow, ...)
  DF[] <- lapply(DF, colFUN)
  DF
}

df <- rbind(df, c(1, 2))
#  x1 x2
#1  2  3
#2  2  3


Q:

How to select upvote arrow for a comment in Stack Exchange using Windows 8 tablet?

I am unable to select the upvote arrow for a comment on Stack Exchange sites using my Windows 8 Surface tablet. It seems that there is no equivalent to mouseover via a tablet. Is this currently possible?

A:

Switch to the mobile view with the link at the bottom of the page.
On a phone (touchscreen):

The only thing it's really missing is the share link...


Q:

unit/integration testing web service proxy client

I'm rewriting a PHP client/proxy library that provides an interface to a SOAP-based .Net webservice, and in the process I want to add some unit and integration tests so future modifications are less risky.
The work the library I'm working on performs is to marshall the calls to the web service and do a little reorganizing of the responses to present a slightly more -object-oriented interface to the underlying service.
Since this library is little else than a thin layer on top of web service calls, my basic assumption is that I'll really be writing integration tests more than unit tests - for example, I don't see any reason to mock away the web service - the work that's performed by the code I'm working on is very light; it's almost passing the response from the service right back to its consumer.
Most of the calls are basic CRUD operations: CreateRole(), CreateUser(), DeleteUser(), FindUser(), &ct.
I'll be starting from a known database state - the system I'm using for these tests is isolated for testing purposes, so the results will be more or less predictable.
My question is this: is it natural to use web service calls to confirm the results of operations within the tests and to reset the state of the application within the scope of each test?  Here's an example:
One test might be createUserReturnsValidUserId() and might go like this:
public function createUserReturnsValidUserId() {
   // we're assuming a global connection to the service
   $newUserId = $client->CreateUser("user1");
   assertNotNull($newUserId);
   assertNotNull($client->FindUser($newUserId);
   $client->deleteUser($newUserId);
}

So I'm creating a user, making sure I get an ID back and that it represents a user in the system, and then cleaning up after myself (so that later tests don't rely on the success or failure of this test w/r/t the number of users in the system, for example). However this still seems pretty fragile - lots of dependencies and opportunities for tests to fail and effect the results of later tests, which I definitely want to avoid.
Am I missing some options of ways to decouple these tests from the system under test, or is this really the best I can do?
I think this is a fairly general unit/integration testing question, but if it matters I'm using PHPUnit for the testing framework.

A:

Unfortunately I am not familiar with PHP or PHPUnit; so I apologize if this answer may end up not so useful.
I have experience of trying to do testing in the style you are suggesting and I found it to quickly become a large problem. Integration tests which integrate with the DB must ensure that either after every test, or before ever test that the db is in a known good state. Without this you will get lots of false results. To do it can be an annoying problem. In either case it will take time and be slow.
If your layer is in fact a thin layer which takes a some data from the web and push it to the db layer after (possibly) some modification, validation, etc - I would strongly suggest decoupling it from both the web and from the DB. Mock both ends in your tests. Your tests will be small and fast. Test separately your db layer to ensure it does the right thing when your translation layer tells it to do something.
Since I am not familiar with PHP or PHPUnit I can't help you on how to decouple and mock these items, unfortunately.


Q:

A splash screen which doesnot just disappear but fades in/out

I have a splash screen which appears for a few seconds before the application home screen is loaded. And then the home screen is pushed in.
But I need to fade out the splash screen before the home screen appears.
Any idea how to do that??

A:

Yeah, you should do two things:

push application home screen, and after that push splash screen

inside splash screen before close start png "animation" with growing transparency (image should be size of screen)

See also
Blackberry - background image/animation RIM OS 4.5.0


Q:

Unable to upgrade a Reporting Services project to Visual Studio 2019

We recently upgraded our Visual Studio 2015 to VS 2019. When I open one of our VS 2015 solution files in Visual Studio 2019 I'm not prompted to migrate and I receive the following error:

Error Unsupported
This version of Visual Studio is unable to open the
  following projects. The project types may not be installed or this
  version of Visual Studio may not support them.  For more information
  on enabling these project types or otherwise migrating your assets,
  please see the details in the "Migration Report" displayed after
  clicking OK.

Financial Reporting, "Z:\Folders by Department\Finance\Reporting\Visual Studio 2019\Projects\Financial
  Reporting\Financial Reporting\Financial Reporting.rptproj"

How can I migrate this project?

A:

From my research it appears that as of Visual Studio 2017, .rptproj are not supported out of the box. You need to install the Microsoft Reporting Services Projects package in order to open this file type in Visual Studio 2017 or Visual Studio 2019:

The [package contains the] Microsoft RDL report designer, projects and
  wizards for creating professional reports. This package provides
  support for the .rptproj type and is designed for the most recent
  versions of Microsoft Reporting Services.

The RDLC Report Designer that came with previous versions of Visual Studio is also now a VSIX installation package - Microsoft RDLC Report Designer.


Q:

How to get the count of a specific word or character for each row?

I have a spreadsheet with a few hundred rows of testers. There are ten columns ("Passed Q1", "Passed Q2", "Passed Q3", etc.) where a value of "Yes" or "No" is assigned. Many online resources have only given me ways to find the count of a specific word in a given range, but I am trying to get count for each row.
Here is an image of the kind of output that I'm trying to get:

A:

You've got a table with many "Yes" and "No". To reproduce this problem, I have made a table like yours:

To get the total count of "Yes" in the K2 cell for the first row, type in this formula and hit 'enter':
=COUNTIF(A2:J2, "Yes")
where A2:J2 is the cell range for the first count.
Now drag from the edge of the cell of K2 all way down to get count of each individual row. There you will have something like this:

I hope this helps :)


Q:

How to initialize variable only if it is set up in controller?

How to initialize variable only if it is set up in controller???

A:

Add the default value for the profile while defining the method and check if it is not the default value.
def initialize(profile = nil)
  if profile
    @profile = profile
    @person = profile.person
  end
end


Q:

Good and Bad Omen - on something that can be calculated in advance

Inspired by Why make a bracha on an earthquake but not on an eclipse?
When something can be predicted in advance to an exact moment - for example an eclipse which Chazal say it is a bad Omen (Sukkah 29A), does that mean that Chazal were unable to calculate this? Or perhaps even though they were able to calculate an eclipse it is a bad Omen?

A:

It doesn't make sense to say that something predictable and cyclical is a bad omen. It's like saying the seasons, which occur every year, are a bad omen. The case of eclipses are just further apart.
The achronim assume Chazal knew what they were talking about when they said מאורות לוקין, and assume that they knew how to predict eclipses (I'm not sure if that's the historical consensus), so they want to give a different explanation of that gemarra.
One is the Aruch LeNer Sukkah 29a. He felt the term "בזמן", at the time of, was extra. They should have just said when חמה לקה. Rather it's referring to the time period when the eclipses occur. Yes the phenomenon is predictable, but Chazal knew this specific time was a time of דין, judgement.
The other is the Yearos Devash, Chelek Beis, Drush 12. It's referring to something that sounds like sun spots. Some blotch on the sun blocking its light (although I'm not sure how to this would be true for the moon).
You could also say it's referring to something that doesn't occur anymore, but I don't know if any source suggests that.


Q:

Filemaker php api: encode for each loop variables to json

I've been asked to provide filemaker data as json objects through the filemaker php api.
I've been able to use the following on a single record
 echo json_encode(array($namefamily, $namefirst, $dob, ));

Now I need to encode to json in my for each loop - not sure how to get it to work with concatenated variables in:
$records = $result->getRecords();
foreach($records as $record){
    echo' ' . $record->getField('NameFirst') . ' | ' . $record->getField('NameFamily') .' ';
}

A:

Similar to previous answer, but using working FileMaker API syntax...
$records = $result->getRecords();

foreach($records as $record){
    $data[] = array(
                    'NameFirst' => $record->getField("NameFirst"),
                    'NameFamily' => $record->getField("NameFamily")
                   );
}

echo json_encode($data);


Q:

How to popup a text field

I have a view in my app with many labels and a toolbar with some buttons. I would like to edit all the labels at the same time when pressing a button. I thought it might be a way to "popup" a text input and make a keyboard appear at the same time. Which is the cleanest way to do that?
Thank you

A:

http://discussions.apple.com/thread.jspa?messageID=8445879
Alternatively. Here's how I do it:
UIAlertView *prompt = [[UIAlertView alloc] initWithTitle:@"Please enter your name:"
                                                 message:@"\n\n"
                                                delegate:self
                                       cancelButtonTitle:@"Cancel"
                                       otherButtonTitles:@"Enter", nil];

textField = [[UITextField alloc] initWithFrame:CGRectMake(12, 50, 260, 25)];
[textField setBackgroundColor:[UIColor whiteColor]];
[textField setPlaceholder:@"Name for message"];
[prompt addSubview:textField];
[textField release];

// show the dialog box
[prompt show];
[prompt release];

// set cursor and show keyboard
[textField becomeFirstResponder];

Then in the UIAlertView delegate method you read the content from textField.text :-)

A:

I know its too late answer,But this answer for those who are using iOS 5.0 or later.
Now AlertView has new Property AlertViewStyle for various purpose.
UIAlertViewStyle
The presentation style of the alert.

typedef enum {
   UIAlertViewStyleDefault = 0,
   UIAlertViewStyleSecureTextInput,
   UIAlertViewStylePlainTextInput,
   UIAlertViewStyleLoginAndPasswordInput
} UIAlertViewStyle;

Example:
UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:@"Title"  message:@"Message" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Ok",nil];
         [alertView setAlertViewStyle:UIAlertViewStylePlainTextInput];
         [alertView show];
         [alertView release];

Delegate:
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    NSLog(@"%@",[[alertView textFieldAtIndex:0] text])
}

Reference : http://developer.apple.com/library/ios/#DOCUMENTATION/UIKit/Reference/UIAlertView_Class/UIAlertView/UIAlertView.html


Q:

Advice Needed with Mysql Query, sorting, grouping and performance

I have a 'message' table, where users send and receive messages, pretty straight forward. What I would like to do is: retrieve DISTINCT sender_ids WHERE receiver_id is X, and have it sorted in a way where users from who receiver X has unread mesages appear first and users from who receiver X has read messages appear after and everything is sorted by created_at DESC.
Any ideas how I can accomplish this? Note: Performance is an issue too.
This is the query I was using, but it appears that sorting isn't really done right, maybe DISTINCT screws things up? I am expecting result 6, 5, 4, 2, 3 - but am getting 6, 5, 4, 3, 2
SELECT DISTINCT sender_id
FROM message m
WHERE receiver_id = 1
ORDER BY read_at, created_at DESC

Here is the table with sample data:
CREATE TABLE `message` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `sender_id` bigint(20) NOT NULL,
  `receiver_id` bigint(20) NOT NULL,
  `message` text,
  `read_at` datetime DEFAULT NULL,
  `created_at` datetime DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `sender` (`sender_id`),
  KEY `receiver` (`receiver_id`),
  KEY `dates` (`receiver_id`,`read_at`,`created_at`)
) ENGINE=MyISAM AUTO_INCREMENT=13 DEFAULT CHARSET=latin1;

INSERT INTO `message` (id, sender_id, receiver_id, message, read_at, created_at)
VALUES
  (1,2,1,NULL,'2011-01-01 01:01:01','2011-01-01 01:01:01'),
  (2,1,2,NULL,'2011-01-01 01:01:01','2011-01-01 01:01:02'),
  (3,2,1,NULL,'2011-01-01 01:01:01','2011-01-01 01:01:03'),
  (4,3,1,NULL,'2011-01-01 01:01:01','2011-01-01 01:01:04'),
  (5,3,1,NULL,'2011-01-01 01:01:01','2011-01-01 01:01:05'),
  (6,1,4,NULL,'2011-01-01 01:01:01','2011-01-01 01:01:06'),
  (7,4,1,NULL,NULL,'2011-01-01 01:01:07'),
  (8,5,1,NULL,NULL,'2011-01-01 01:01:08'),
  (9,5,1,NULL,NULL,'2011-01-01 01:01:09'),
  (10,1,6,NULL,NULL,'2011-01-01 01:01:10'),
  (11,6,1,NULL,NULL,'2011-01-01 01:01:11');

A:

The following returns the desired result on the sample data:
SELECT sender_id
  FROM message AS m
  WHERE receiver_id=?
  GROUP BY sender_id
  ORDER BY COUNT(*)=COUNT(read_at), MAX(created_at) DESC;

If you want to use the oldest message when sorting by created_at, change MAX to MIN.
COUNT(read_at) ignores nulls, while COUNT(*) doesn't, so the two will be unequal if there are any unread messages. If there aren't too many messages to a giver receiver, it should perform fairly quickly (the index on receiver_id will help). Profile the query before deciding more optimization is needed.
With a bit of tweaking, The Scrum Meister's aggregate expression can be made to work. Try MIN(IF(read_at IS NULL, 0, 1)) as a replacement for COUNT(*)=COUNT(read_at). I don't think it will improve execution time, but there's at least a small chance it will (like much of optimization, it depends on MySQL internals).
Result of EXPLAIN on the test table:
+----+-------------+-------+------+----------------+----------+---------+-------+------+----------------------------------------------+
| id | select_type | table | type | possible_keys  | key      | key_len | ref   | rows | Extra                                        |
+----+-------------+-------+------+----------------+----------+---------+-------+------+----------------------------------------------+
|  1 | SIMPLE      | m     | ref  | receiver,dates | receiver | 8       | const |    7 | Using where; Using temporary; Using filesort |
+----+-------------+-------+------+----------------+----------+---------+-------+------+----------------------------------------------+

Getting rid of the aggregate functions applied to the message rows:
SELECT sender_id
  FROM ( (SELECT sender_id, 0 AS all_read, MAX(created_at) AS recent
          FROM message AS m
          WHERE receiver_id=:receiver AND read_at IS NULL
          GROUP BY sender_id)
       UNION
         (SELECT sender_id, 1 AS all_read, MAX(created_at) AS recent
          FROM message AS m
          WHERE receiver_id=:receiver AND read_at IS NOT NULL
          GROUP BY sender_id)
       ) AS t
  GROUP BY sender_id
  ORDER BY MIN(all_read), recent DESC;

look to lose ground. This query works by using constant values (the separate queries allows for this) for the column indicating whether or not any of the sender's messages are unread, rather than the aggregate expressions. Here's the output of EXPLAIN for this query:
+----+--------------+------------+-------+----------------+-------+---------+------+------+----------------------------------------------+
| id | select_type  | table      | type  | possible_keys  | key   | key_len | ref  | rows | Extra                                        |
+----+--------------+------------+-------+----------------+-------+---------+------+------+----------------------------------------------+
|  1 | PRIMARY      | <derived2> | ALL   | NULL           | NULL  | NULL    | NULL |    5 | Using temporary; Using filesort              |
|  2 | DERIVED      | m          | ref   | receiver,dates | dates | 17      |      |    4 | Using where; Using temporary; Using filesort |
|  3 | UNION        | m          | range | receiver,dates | dates | 17      | NULL |    3 | Using where; Using temporary; Using filesort |
|NULL| UNION RESULT | <union2,3> | ALL   | NULL           | NULL  | NULL    | NULL | NULL |                                              |
+----+--------------+------------+-------+----------------+-------+---------+------+------+----------------------------------------------+


Q:

SQL Server, find cross value in different columns

I need to help for a sql server query. I have to many rows like this and my table has 3 columns like a, b, c.
      a          b          c
     ---        ---        ---
    hello      world       10
     hey        you        80
    world      hello       20
     my         day        15
    merhaba    dunya       40
    bugun      nasilsin    75
    dunya      merhaba     20

So I want to find cross values in different columns with add c column values. So after the query I want to see that;
      a          b          c
     ---        ---        ---
    hello      world       30
     hey        you        80
      my        day        15
    merhaba    dunya       60
     bugun     nasilsin    75

Sorry for my bad English, thank you for answers...
Edit: answers don't work. I tried them all. Have you any idea for this solution guys?

A:

Here is a way of doing this
create table t(a varchar(10), b varchar(10), c varchar(10))

insert into t values('hello','world',10)
insert into t values('world','hello',20)

select  min(a) as a
       ,max(b) as b
       ,sum(cast(c as int)) as c
  from t as x
 group by case when a>b then a
            else b
       end


Q:

trying to encrypt with bouncycastle throw error

I am trying to encrypt using bouncycastle jar here my code:
private static byte[] encrypt(byte[] plain, byte[] key, byte[] iv) throws Exception
{
    PaddedBufferedBlockCipher aes = new PaddedBufferedBlockCipher(new CBCBlockCipher(
            new AESEngine()));
    CipherParameters ivAndKey = new ParametersWithIV(new KeyParameter(key), iv);
    aes.init(true, ivAndKey);
    return cipherData(aes, plain);
}

Here my main:
    String msg="hello";
    String key="123";

    SecureRandom secureRandom = new SecureRandom();
    byte[] keyB = new byte[16];
    secureRandom.nextBytes(keyB);
    SecretKey secretKey = new SecretKeySpec(keyB, "AES");

    byte[] enc=encrypt(msg.getBytes(),key.getBytes(),keyB);

    System.out.println(new String(enc));

but I/m getting
Exception in thread "main" java.lang.IllegalArgumentException: Key length not 128/192/256 bits.
    at org.bouncycastle.crypto.engines.AESEngine.generateWorkingKey(Unknown Source)
    at org.bouncycastle.crypto.engines.AESEngine.init(Unknown Source)
    at org.bouncycastle.crypto.modes.CBCBlockCipher.init(Unknown Source)
    at org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher.init(Unknown Source)
    at Aes.encrypt(Aes.java:122)
    at Aes.main(Aes.java:47)

A:

You're not passing what you think are into the encrypt() method:
String key="123";
…
byte[] enc=encrypt(msg.getBytes(),key.getBytes(),keyB);

You're passing the encoded string content, NOT the key array you create a few lines in.


Q:

selecting alternative first view controller from story board at application startup

I've just started on iOS programming and so far the tutorials and answers I found here have been a great help to move forward. However, this particular problem has been bumming me all night and I can't find an answer that "feels right".
I'm writing an application that connects to a remote service and the users need to sign in before they can use it. When they start using the application, their first view should be the sign in dialog; when they've authenticated before, they immediately see the overview page.
The project uses story boards - which I think is a great feature - so most of the code that selects and loads the root view controller is already taken care of. I thought the best place to add my logic is the application:didFinishLaunchingWithOptions: method of the AppDelegate:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:
      (NSDictionary *)launchOptions
{
    // select my root view controller here based on credentials present or not
    return YES;
}

But this brought up two questions:

Inside this particular delegate method, the root view controller has already been selected (and loaded?) based on the story board. Could I move to an earlier spot in the loading process to override the first view controller selection or would that needlessly complicate matters?
To override the first view controller I need a reference to the story board, but I couldn't find a better way than to use the storyboardWithName:bundle: constructor of UIStoryboard. That feels wrong, the application should already have a reference to the story board, but how can I access it?

Update
I worked out the second issue I was having, as I found my answer here:
UIStoryboard: What's the Correct Way to Get the Active Storyboard?
NSBundle *bundle = [NSBundle mainBundle];
NSString *sbFile = [bundle objectForInfoDictionaryKey:@"UIMainStoryboardFile"];
UIStoryboard *sb = [UIStoryboard storyboardWithName:sbFile bundle:bundle];

The above will create a new story board instance; to get the active instance, it's a whole lot simpler:
UIStoryboard *sb = [[self.window rootViewController] storyboard];

In the story board file itself you have to set an identifier for the view you wish to load, e.g. LoginDialog. Afterwards you instantiate the view like this:
LoginViewController *login = [sb instantiateViewControllerWithIdentifier:@"LoginDialog"];
[self.window setRootViewController:login];

Within another view controller, the following suffices:
UIStoryboard *sb = self.storyboard;
LoginViewController *login = [sb instantiateViewControllerWithIdentifier:@"LoginDialog"];
[self presentViewController:login animated:NO completion:nil];

A:

You can just reset the root view controller of the window
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:
      (NSDictionary *)launchOptions
{
   if(your_condition) {
       UIViewController *newRoot = [your implementation];
       self.window.rootViewController = newRoot;
   }
   return YES;
}

This is worked for me, Xcode5.0.1

A:

I have a similar scenario as yours. My application uses a UINavigationController as the root view controller. If the user is logged in, I want to present him/her with NotLoggedInViewController, while if it's logged in I want to show the LoggedInViewController.
In a storyboard a UINavigationController can only have one child, so you have to be able to programmatically assign another root view controller to it.
I start by creating a custom navigation controller class, let's name it MyNavigationController. In the storyboard I assign this custom class to the navigation controller object.
Still in the storyboard, I then model both view controllers, and connect one of them to the navigation controller object. Since I need to be able to access them from my code later on, I assign each of them an identifier using the XCode inspector on the right. These identifiers which can be arbitrary strings, but to things simple I just use the class names.
Finally I then implement the viewDidLoad method on MyNavigationController class:
BOOL isLoggedIn = ...;

- (void)viewDidLoad {
  id rootController;
  if (isLoggedIn) {
    rootController = [self.storyboard instantiateViewControllerWithIdentifier:@"LoggedInViewController"];
  } else {
    rootController = [self.storyboard instantiateViewControllerWithIdentifier:@"NotLoggedInViewController"];
  }
  self.viewControllers = [NSArray arrayWithObjects:rootController, nil];
}