text:
Q: message sent to deallocated instance (probably UITableViewCell) I know that a lot of folks have had this problem before and I've read a lot of suggested solutions, none of which has worked out for me. I'm working on a part of a larger project, involving three different views: the first view contains a UITableView with custom made cells called WeekdaySelectionWithPopoverCellController. This cell contains a label designating the weekday (Monday through Friday), a UISwitch and the following elements that are displayed or hidden respectively based on the state of the switch. If the switch is on, the cell looks like this:
 ----------------------------------------------------------------------
|  Monday    [ON/off]    between        ( N/A )     and       ( N/A )  |
 ----------------------------------------------------------------------

If it's off it looks like this:
 ----------------------------------------------------------------------
|  Monday    [on/OFF]                                                  |
 ----------------------------------------------------------------------

The (N/A) elements are UIButtons. If the user hits one of those buttons a UIPopover with a date picker opens. The idea is that the user selects a time from the picker that should be displayed on the UIButtons instead of the (N/A):
 ----------------------------------------------------------------------
|  Monday    [ON/off]    between      ( 12:30 )     and     ( 16:00 )  |
 ----------------------------------------------------------------------

The hiding of the elements on hitting the UISwitch works as does the display of the popover. However, if the user hits the "Done" button in the popover and the popover is dismissed the app crashes with the following error:
-[UITableViewCell isKindOfClass:]: message sent to deallocated instance 0xf42a100

Strangely enough the only place containing code that calls isKindOfClass is ModalTableViewController (the parent view of the popover and the custom cells) and the address of the instance displayed does not belong to it. Neither is it the address of the popover which only leaves the class of the custom cells (WeekdaySelectionWithPopoverCellController).
Let me give you the relevant parts of the ModalTableViewController.m:
@implementation ModalTableViewController

@synthesize mtvcNavigationBar;
@synthesize mtvcTableView;

@synthesize cell;
@synthesize lable;

@synthesize button;

// WeekdaySelectionWithPopoverCell
@synthesize wswpMainLabel;
@synthesize wswpFromLabel;
@synthesize wswpToLabel;
@synthesize wswpOClockFromLabel;
@synthesize wswpOClockToLabel;
@synthesize wswpSwitch;
@synthesize wswpFromValueButton;
@synthesize wswpToValueButton;

@synthesize popoverController;

// more code...

- (ModalTableViewController *)initWithParam:(NSString *)title andData:(NSArray *)myData andSelection:(NSArray *)selection  {

    [self initSwipeLeftNavigation];

    mtvcNavigationBar.topItem.title = title;

    mtvcSectionSize = [myData count];
    mtvcSectionname = @"";

    mtvcLabels = myData;
    mtvcData   = selection;

    [mtvcLabels retain];
    [mtvcData retain];
    [otherValues retain];

    mtvSingleton = [ModalTableViewSingleton sharedInstance];

    return self;
}

// more code...

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

    UITableViewCell *cellRet;

    NSString *MyIdentifier = @"WeekdaySelectionWithPopoverCellController";

    cellRet = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];

    if (cellRet == nil) {
        [[NSBundle mainBundle] loadNibNamed:MyIdentifier owner:self options:nil];
        cellRet = self.cell;
    }

    NSDictionary *tempValues;
    tempValues = [mtvcData objectAtIndex:indexPath.row];

    wswpSwitch = (UISwitch *)[cellRet viewWithTag:2];
    wswpSwitch.on = [[tempValues valueForKey:@"company_id"] isKindOfClass:[NSNull class]] ? false: true;

    BOOL negatedState = !wswpSwitch.on;

    NSLog(@"tempValues: %@", tempValues);

    lable      = (UILabel *)[cellRet viewWithTag:1];
    lable.text = [NSString stringWithFormat:@"%@", [tempValues valueForKey:@"short"]];
    lable.font = [UIFont boldSystemFontOfSize:16];

    lable        = (UILabel *)[cellRet viewWithTag:3];
    lable.font   = [UIFont boldSystemFontOfSize:16];
    lable.text   = [NSString stringWithFormat:@"%@", @"von"];
    lable.hidden = negatedState;

    lable        = (UILabel *)[cellRet viewWithTag:5];
    lable.text   = [NSString stringWithFormat:@"%@", @"bis"];
    lable.font   = [UIFont boldSystemFontOfSize:16];
    lable.hidden = negatedState;

    lable        = (UILabel *)[cellRet viewWithTag:7];
    lable.text   = @"Uhr";
    lable.font   = [UIFont boldSystemFontOfSize:16];
    lable.hidden = negatedState;

    lable        = (UILabel *)[cellRet viewWithTag:8];
    lable.text   = @"Uhr";
    lable.font   = [UIFont boldSystemFontOfSize:16];
    lable.hidden = negatedState;

    button = (UIButton *)[cellRet viewWithTag:4];
    [self setButtonLabel:button forKey:@"beginning" fromDict:tempValues];
    button.hidden = negatedState;
    /*
    if (![[tempValues valueForKey:@"beginning"] isKindOfClass:[NSNull class]]) {

        button.titleLabel.text = [NSString stringWithFormat:@"%@", [tempValues valueForKey:@"beginning"]];
    } else {
        button.titleLabel.text = @"k.A.";
    }
     */

    button = (UIButton *)[cellRet viewWithTag:6];
    [self setButtonLabel:button forKey:@"until" fromDict:tempValues];
    button.hidden = negatedState;
    /*
    if (![[tempValues valueForKey:@"until"] isKindOfClass:[NSNull class]]) {

        button.titleLabel.text = [NSString stringWithFormat:@"%@", [tempValues valueForKey:@"until"]];
    } else {
        button.titleLabel.text = @"k.A.";
    }
     */

    self.cell = nil;

    return cellRet;
}

- (void)setButtonLabel:(UIButton *)btn forKey:(NSString *)key fromDict:(NSDictionary *)dict {
    [btn setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];

    NSString *text = [dict objectForKey:key];
    if ([mtvSingleton.sharedData objectForKey:key]) {
        [btn setTitle:[mtvSingleton.sharedData objectForKey:key] forState:UIControlStateNormal];
    } else {
        if ([text isKindOfClass:[NSNull class]] ||
            [text isEqualToString:@""])
        {
            [btn setTitle:@"k.A." forState:UIControlStateNormal];
        } else {
            [btn setTitle:text forState:UIControlStateNormal];
        }
    }
}

// more code...

- (IBAction)switchButtonValueChanged:(id)sender
{
    //[self changeDisplayState:wsdSwitch.on forObj:sender];
    // UISwitch *tmp = (UISwitch *)sender;
    UIView *v = (UIView *)sender;
    do {
        v = v.superview;
    } while (![v isKindOfClass:[UITableViewCell class]]);
    // WeekdaySelectionWithPopoverCellController *cell1 = (WeekdaySelectionWithPopoverCellController *)v;
    cell = (UITableViewCell *)v;

    wswpSwitch = (UISwitch *)[cell viewWithTag:2];
    BOOL negatedState = !wswpSwitch.on;

    lable = (UILabel *)[cell viewWithTag:3];
    lable.hidden = negatedState;

    lable = (UILabel *)[cell viewWithTag:5];
    lable.hidden = negatedState;

    lable = (UILabel *)[cell viewWithTag:7];
    lable.hidden = negatedState;

    lable = (UILabel *)[cell viewWithTag:8];
    lable.hidden = negatedState;

    button = (UIButton *)[cell viewWithTag:4];
    button.hidden = negatedState;

    button = (UIButton *)[cell viewWithTag:6];
    button.hidden = negatedState;

    /*
    wswpSwitch = (UISwitch *)[cell1 viewWithTag:2];
    BOOL negatedState = !wswpSwitch.on;

    lable = (UILabel *)[cell1 viewWithTag:3];
    lable.hidden = negatedState;

    lable = (UILabel *)[cell1 viewWithTag:5];
    lable.hidden = negatedState;

    lable = (UILabel *)[cell1 viewWithTag:7];
    lable.hidden = negatedState;

    lable = (UILabel *)[cell1 viewWithTag:8];
    lable.hidden = negatedState;

    button = (UIButton *)[cell1 viewWithTag:4];
    button.hidden = negatedState;

    button = (UIButton *)[cell1 viewWithTag:6];
    button.hidden = negatedState;
     */

}

#pragma mark - handlers

- (IBAction)toButtonHandler:(id)sender {
    dppvc = [[DatePickerPopoverViewController alloc] initWithCaller:self andKey:@"beginning"];
    UIPopoverController *popover = [[UIPopoverController alloc] initWithContentViewController:dppvc];

    popover.delegate = self;
    self.popoverController = popover;
    [popover release];

    [self.popoverController presentPopoverFromRect:[(UIButton *)sender frame]
                                            inView:self.view
                          permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
}

- (IBAction)fromButtonHandler:(id)sender {
    dppvc = [[DatePickerPopoverViewController alloc] initWithCaller:self andKey:@"until"];
    UIPopoverController *popover = [[UIPopoverController alloc] initWithContentViewController:dppvc];

    popover.delegate = self;
    self.popoverController = popover;
    [popover release];

    CGRect senderFrameRect = [(UIButton *)sender frame];

    [self.popoverController presentPopoverFromRect:senderFrameRect
                                            inView:self.view
                          permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
}

#pragma mark - UIPopoverControllerDelegate

//---called when the user clicks outside the popover view---
- (BOOL)popoverControllerShouldDismissPopover:(UIPopoverController *)popoverController {

    // NSLog(@"popover about to be dismissed");
    return YES;
}

//---called when the popover view is dismissed---
- (void)popoverControllerDidDismissPopover:(UIPopoverController *)popoverController {

    // NSLog(@"popover dismissed");
}

- (void)dismissPopover {
    if (popoverController != nil) {
        [popoverController dismissPopoverAnimated:YES];

        NSMutableArray *indexPaths = [[NSMutableArray alloc] init];
        int i;
        for (i = 0; i < [mtvcLabels count]; i++) {
            [indexPaths addObject:[NSIndexPath indexPathForRow:i inSection:0]];
        }

        [mtvcTableView reloadRowsAtIndexPaths:indexPaths withRowAnimation:YES];
    }
}

- (void)dealloc {
    [mtvcSectionname release];
    [mtvcLabels      release];
    [mtvcData        release];

    [cell      release];

    [super dealloc];
}

The crash occurs in main.m:
int main(int argc, char *argv[])
{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    // crashes:
    int retVal = UIApplicationMain(argc, argv, nil, nil);        // <--

    [pool release];
    return retVal;
}

I have enabled NSZombieEnabled, MallocStackLoggingNoComp and NSAutoreleaseFreedObjectCheckEnabled but the compiler doesn't give me any more information than what I posted.
I've spent the entire day trying to resolve this but to no avail. Any hint in the right direction is appreciated!

A: I've been able to take care of this particular error. The problem was that cellRet in cellForRowAtIndexPath had not been retained. The following snippet resolves the error mentioned above:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    UITableViewCell *cellRet;

    NSString *MyIdentifier = @"WeekdaySelectionWithPopoverCellController";

    cellRet = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];

    if (cellRet == nil) {
        [[NSBundle mainBundle] loadNibNamed:MyIdentifier owner:self options:nil];
        cellRet = self.cell;
        [cellRet retain];
    }

    // ...
}

Now however, I'm stuck with a new, similar error. This time it says:
*** -[CALayer release]: message sent to deallocated instance 0xc656d30

The following topic has some more information on the problem: "[CALayer release]: message sent to deallocated instance" when dismissing modal view controller
I have tried to change the property of the popover view controller to assign instead of retain but that gave me the message sent to deallocated instance error again, this time for the popover view controller.
Somebody with an idea? TIA!

A: The way I usually handle this is to create a subclass of UITableViewCell for my custom cells. and use the nib. I create a custom init that loads the cell from the nib. as follows.
- (id)init
    {
    self = [[[[NSBundle mainBundle] loadNibNamed:@"NibName" owner:self options:nil] objectAtIndex:0] retain];
    if (self)
        {
        // any further initialization
        }
    return self;
    }

in the nib set the cell's class to your new class.
then to use your cell do the following.
  - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"CustomCell";
CustomCell *cell = (CustomCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
  if (!cell)
      {
      cell = [[[CustomCell alloc] init] autorelease];
      }
  // setup your cell
return cell;
}

You should definitely be using assign on your delegate properties.


text:
Q: CSS - relative element hides another I have few
 elements. I'm styling them with only one css property position: relative; to show some extra info which you can see on my screen. However if two table elements are styled, one of them is getting hidden by another and I don't know why. I could use  z-index: 1; for one on left side, but I believe it's not the best way to solve it. I've tried overflow and visibility properties, but none of them is working.
link

A: Please note that we need you to share your code, so we can identify where the problem is. But I'll try to help you out.
I'll assume from your image that you are using a position: relative container, for the blue stripe that is position: absolute, right?
In this case, remove the z-index from the relative elements, and set it only on the position: absolute ones, as you can see on the example bellow. Hope it helps:

.relative {
  position: relative;
  width: 100px;
  height: 100px;
  border: 1px solid black;
  background: white;
}

.absolute {
  position: absolute;
  top: 5px;
  left: 20px;
  width: 100px;
  height: 20px;
  background: red;
  z-index: 100;
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: R - finding pattern in a column and replacing it (more efficient solution) I have a large data set of passengers per route similar to the following:
routes <- c("MEX-GDL", "ACA-MEX", "CUN-MTY", "MTY-CUN", "GDL-MEX", "MEX-ACA")
pax <- sample(100:500, size = 6, replace = T)
traffic <- data.frame(routes = routes, pax = pax)

   routes pax
   1 MEX-GDL 282
   2 ACA-MEX 428
   3 CUN-MTY 350
   4 MTY-CUN 412
   5 GDL-MEX 474
   6 MEX-ACA 263

I want to group flights if the origin and destination match as to get the total number of passengers in the route - so for example renaming the route MEX-GDL as GDL-MEX or viceversa so I can then use group_by() on the data set.
Kind of like this:
traffic %>% group_by(routes) %>% summarise(sum(pax))

I have done the following and it works, but I believe there can be a more efficient way to solve the problem (as it takes quite some time to run):
library(tidyverse)

traffic$routes <- as.character(traffic$routes)

for(route in traffic$routes){
  a <- substring(route, first = 1, last = 3)
  b <- substring(route, first = 5, last = 7)
  aux <- which(sapply(traffic$routes, str_detect, pattern = paste0(b,"-",a)))
  traffic$routes[aux] <- paste0(a,"-",b)
}

Any suggestions?
Thanks for the help!
Note: it's my first question here, so I hope I complied with all the guidelines.

A: We can separate into two columns, grouped by the pmax or pmin, get the sum
library(tidyverse)
traffic %>%
   separate(routes, into = c("Col1", "Col2")) %>%
   group_by(ColN = pmin(Col1, Col2), ColN2 = pmax(Col1, Col2)) %>%
   summarise(Sum = sum(pax))

A: data.table version
data: (?I READ THIS)
traffic <- data.frame(routes = I(routes), pax = pax)

library(data.table)
setDT(traffic)[,routes := sapply(strsplit(routes, split="-"), function(x) paste0(sort(x),collapse = "-"))][,.(Sum = sum(pax)), by = routes]

result: (values differ because of sample function)
#    routes Sum
#1: GDL-MEX 621
#2: ACA-MEX 595
#3: CUN-MTY 266

*

*If you use data with ?sample use ?set.seed along with it.


text:
Q: JSreact render issue I am a beginner coder diving into ReactJS with webpack. Taking a course on my own liberty on Udemy, but I cannot figure out why my code isn't working because the code appears exactly the same as the videos ive followed.
The question simply is, why isn't the video detail file rendering properly?
Though I have 5 component files, I will only include the parent index.js and the child video_detail.js as the problem I have is with those 2 files only.
index.js file

import React, {Component } from 'react';
import ReactDOM from 'react-dom';
import YTSearch from 'youtube-api-search';
import SearchBar from './components/searchbar';
import VideoList from './components/video_list';
import VideoDetail from './components/video_detail';
const API_KEY = 'AIzaSyAi1CzVpifuFUDVQf3dzrTu3mwJDP2n8r8';

class App extends Component {
 constructor(props){
  super(props);
  //Do i expect this component to play any type of state? aka pass props
  this.state= { videos: []};
      //  ^proper name can be anything
  YTSearch({key: API_KEY, term: 'surfboards'}, (videos) => {
// console.log(data);
  this.setState({ videos });
});  // this.setState({videos : vidoos});
 }
 render (){
 return (

  <SearchBar />
  <VideoDetail video={this.state.video[0]} />
  <VideoList videos={this.state.videos} />

  );
 }
}

ReactDOM.render(<App />, document.querySelector('.container'));

video_detail.js file

import React from 'react';

const VideoDetail = ({video}) => {
 if (!video) {

  return
Loading...
;
 }

 const videoId = video.id.videoId;
 const url = `https://www.youtube.com/embed/${videoId}`;

 return(

{video.snippet.title}

{video.snippet.description}

 );
};
export default VideoDetail;

Additional info : google stephen grider github and the repository will pop up, I am using ReduxSimpleStarter. This will help with answering the above question I hope!

A: this should be videos[0] instead of video[0] ?
Change <VideoDetail video={this.state.video[0]} /> to
<VideoDetail video={this.state.videos[0]} />


text:
Q: How to write wild card in less I want a way to represent the following in less.
row-fluid [class*="span"]
This means it should select all elements which have class row fluid and then select all elements which will have class which has word span in it.
Any help would be appreciated.


text:
Q: Problems with react router using regexp as a path I need to let user type in a date in this form: 15-03-2018 in an adress bar. So naturally I thought to go with regexp since I read in React Router docs that this is supported. I tried adding a long date regexp and couldn't make it work. So i thought ill try with a simple regex like (abc*), and that works, but this doesn't:
    <Route path="/(^([0-2][0-9]|(3)[0-1])(\-)(((0)[0-9])|((1)[0-2]))(\-)\d{4}$)" component={Dashboard} />

I tried excluding ^ and $ from the regex since that is only needed in a multiline input, that i don't need at the moment.
Couldn't find any resource to solve this, i'll be grateful if anyone can help me with this, thanks in advance!
p.s. This is my first question on stack overflow so if I made any formating errors, excuse me.

A: Seem that the parser of the React Router works like this:
-Regex should be in placed in braces like this(), but any more complex regex that contains more braces in it self should be typed in separate braces like this:
example: (abc*)(abc*),
and not like this ((abc*)(abc*))
Lost my nerves with this, finnaly got it right, maybe it will help someone.


text:
Q: How To Deploy Word 2010 Macros To Others? I have a macro that I developed in Word 2010.
How do I send this to others to use?

A: Save the document as .dotm (macro enabled template). Save it to
%Appdata%/Microsoft/word/startup

Close word. Now, it will be accessible to all other word documents.
If not by default, then go to templates and tick the file saved above
to deploy, create a simple script that copies the file to the appropriate folder. You can probably deploy via email

A: From the sublime to the ridiculous, here are four different options:

*

*Create an add-in. Distribute and tell others to install it. Instructions

*Create a COM add-in. Distribute and tell others to set a reference to it. Instructions

*Export the code module containing your macro to a *.bas file. (Right-click module, Export File...) Distribute and tell others to import it.

*Copy-paste macro code into an e-mail. Distribute and tell others to paste it into a module.

A: *

*Go to the VBA Editor.

*Open the Project Explorer if it is not visible (View>ProjectExplorer or Ctrl+R).

*If a new module is needed in the project for your file (Project ( _your file_ )),

*

*right click on the project and select Insert>Module

*OR select the project, then on the menu, select Insert>Module.

*In the Project Explorer, open Project ( your file )>Modules>ModuleX.

*Copy your code into this module.

*Save the file as a Word Macro-Enabled Document (*.docm) (File>Save or Ctrl+S).

*Distribute the file. The code will now go with it.

A: I used an old solution - Nullsoft Scriptable Install System to copy the .dotm file to the %Appdata%/Microsoft/word/startup directory. To do this, I set InstallDir in the NSIS script to this:
InstallDir "$APPDATA\Microsoft\Word\Startup"

NSIS creates a small installer in the form of an EXE file that is easy to distribute and easy for users to install.


text:
Q: To know hex number from a bash shell key or escape code letter How to know hex number from a bash shell key or escape code letter when sed -n l not work on this ie. not give anything back, for backspace key?
e.g. as sed -n l work on alt-L
\033l$

for backspace key in .inputrc its escape letter is \b
Please help get the get hex number for it

A: $ echo -e "murugesan \bopenssl"
murugesanopenssl
$ echo -ne "\b" | od -bx
0000000 010
           0008
0000001
$ echo -e "murugesan \010openssl"
murugesanopenssl

Hence \010 referring backspace.
cat "73550541.sh"
#!/bin/bash
echo Provide one character l
read -n 1 REPLY
echo -ne "$REPLY" | od -bx
echo Provide Two characters Alt l
read -n 1 REPLY
echo -ne "$REPLY" | od -bx
read -n 1 REPLY
echo -ne "$REPLY" | od -bx
$ ./73550541.sh
Provide one character l
l0000000 154
           006c
0000001
Provide Two characters Alt l
0000000 033
           001b
0000001
0000000 154
           006c
0000001
Hence we can set the same using
$ export PS1='\033[32m$LOGNAME@$HOSTNAME \033[33m$PWD \033[0m[ $? ]\n$ '
Here \033 => referring Ctrl V Ctrl [
32m referring the string 32m
33m referring the string 33m


text:
Q: DAX Formula - Calculate Rolling 5 Day average, always getting 5 days for average, but excluding weekends I've tried a few ways of doing this, but can't seem to grok exactly how to get this done.
I have a large fact table full of charges with posting dates, and a calendar table associated via the posting date.
I want to get a rolling 5 day average of each day's total charges, but excluding the weekends, since those are exceedingly small.
So this, obviously, works for a rolling 5 day average including all days of the week.
'Date' is the Calendar Table
CombinedData is the fact table
[ChargesTotal] just calculates SUM(CombinedData[charges]).
AVERAGEX(DATESINPERIOD('Date'[Date], LASTDATE(CombinedData[postdate]), -5, DAY), [ChargesTotal])
I'm just not sure how to filter to always get 5 days, but not include weekends.
Any guidance is appreciated, and I am glad to clarify anything I presented poorly.

A: Try this (maybe you have to replace semicolon with comma),
in my Calendar-Table I have a Column DayOfWeek =WEEKDAY('Calendar'[Date];2)
Here are some measures, you are interessted in the last one:
Total Charges:=SUM(CombinedData[Charge])

Charges_Last_5_WeekDays:=CALCULATE([Total Charges]; DATESBETWEEN('Calendar'[Date]; LASTDATE('Calendar'[Date])-7;LASTDATE('Calendar'[Date])-1);'Calendar'[DayOfWeek]<=5)

AVG Charges:=AVERAGE(CombinedData[Charge])

AVG Charges_Last_5_WeekDays:=CALCULATE(AVERAGE('CombinedData'[Charge]); DATESBETWEEN('Calendar'[Date]; LASTDATE('Calendar'[Date])-7;LASTDATE('Calendar'[Date])-1))


text:
Q: ipod 4th gen wont load app Ive tested my app on the iphone 3GS+, and all the ipads and it just gives me a black screen after the loading screen is done. Its an openGL ES app, and after buying one here is the stack trace. Anyone know what is the problem?
0 Husky Bus Free 0x001950da + 0
1 Husky Bus Free 0x00195d04 + 0
2 libsystem_c.dylib 0x32a0b7ec _sigtramp + 48
3 libGPUSupportMercury.dylib 0x37c360b4 gpus_KillClient + 24
4 libGPUSupportMercury.dylib 0x37c365c0 gpusSubmitDMABuffers + 136
5 IMGSGX543GLDriver 0x3396e536 SubmitPacketsIfAny + 158
6 IMGSGX543GLDriver 0x3396e65a glrFlushContextToken + 38
7 GLEngine 0x34b4ec50 gliPresentViewES + 216
8 OpenGLES 0x358506ba -[EAGLContext presentRenderbuffer:] + 66
9 Husky Bus Free 0x000e72aa + 0
10 Foundation 0x3512360c __NSFireTimer + 144
11 CoreFoundation 0x355d3a32 __CFRUNLOOP_IS_CALLING_OUT_TO_A_TIMER_CALLBACK_FUNCTION__ + 14
12 CoreFoundation 0x355d3698 __CFRunLoopDoTimer + 364
13 CoreFoundation 0x355d226e __CFRunLoopRun + 1206
14 CoreFoundation 0x355554a4 CFRunLoopRunSpecific + 300
15 CoreFoundation 0x3555536c CFRunLoopRunInMode + 104
16 GraphicsServices 0x371f1438 GSEventRunModal + 136
17 UIKit 0x33061cd4 UIApplicationMain + 1080
18 Husky Bus Free 0x000e666c + 0
19 Husky Bus Free 0x000e1393 + 0


text:
Q: Commit to a repository in GitLab not updating issue states in YouTrack I've got UpSource, YouTrack and Hub setup. I have a project called "Overhaul" which has two services UpSource and YouTrack. Both are connected via VCS. UpSource recieves everything that happens within the repository yet when I want to update an issue in YouTrack via a commit message it doesn't update in YouTrack issue tracker, the issue state remains the same.
My commit message would be: #HAUL-1 Fixed
YouTrack integration with UpSource is enabled and everything should be working the way I want it to, I've searched everywhere and tried recreating the project over and over and have checked everything time and time again but I cannot figure out what am I doing wrong.

A: From the YouTrack installation: Menu > UpSource Integration
Click on your UpSource integration then click enable. This will allow UpSource to push commands to YouTrack.
From: https://www.jetbrains.com/help/youtrack/standalone/7.0/Integration-with-Upsource.html#d67048e120

A: Try with [fixed #abc] where abc is the issue number
from the gitlab documentation

Awesome commit message
Fix #20, Fixes #21 and Closes group/otherproject#22. This commit is
  also related to #17 and fixes #18, #19 and
  https://gitlab.example.com/group/otherproject/issues/23. will
  close #18, #19, #20, and #21 in the project this commit is pushed to, as well as #22 and #23 in group/otherproject. #17 won't be closed as it
  does not match the pattern. It works with multi-line commit messages
  as well as one-liners when used with git commit -m.


text:
Q: QR decompositon for singular matrices I read in textbook that every $m$ by $n$ matrix with independent columns can be factored into $A=QR$. The columns of $Q$ are orthonormal, and $R$ is upper triangular and invertible.
I don't fully understand why $R$ is invertible when $A$ has independent columns. My thought is:
$A=QR\rightarrow Q^TA=R$ (multiply both sides by $Q^T$, and $Q^TQ=I$)
If $A$ is not square but has right inverse $A^{-1}$, then
$Q^TAA^{-1}Q=I=RA^{-1}Q$
So $A^{-1}Q$ is the inverse of $R$. But having right inverse requires independent rows, and I don't see how independent columns are related to it.
To clear my doubt, I looked at some other materials, and saw the following statement:
Every invertible matrix has a $QR$ decomposition, where $R$ is invertible.
As  a  side  note,  it  bears  mentioning  that  this  result  holds  even  if  the  matrix  is  not invertible: Every matrix has a $QR$ decomposition, though $R$ may not always be invertible.
It confused me even more. If a matrix $A$ does not have independent columns, how will its $QR$ decomposition be like? As far as I know, $Q$ has pairwise orthogonal columns, all of unit length, and its shape is the same as $A$. But if $A$ doesn't have independent columns in the first place, how do we find the corresponding $Q$?
I am stuck and hope someone can help me make it clear. Any help is appreciated! Thanks in advance.

A: Regarding your original question:
We want to show that if $A$ has linearly independent columns and $A = QR$ with $R$ square and upper triangular (in fact I'll ignore the properties of $Q$), then $R$ must be invertible.
Note that $A$ has linearly independent columns if and only if $Ax = 0$ implies that $x = 0$ for $x \in \Bbb R^n$.
Now, suppose for the purpose of contradiction that $R$ fails to be invertible.  It follows that the columns of $R$ fail to be linearly independent, which is to say that $Rx = 0$ has a non-zero solution.  This contradicts our statement about $A$, however, since the same non-zero $x$ satisfies
$$
Ax = (QR)x = Q(Rx) = Q(0) = 0.
$$

Regarding the different kinds of $QR$-decompositions:
The confusion here stems from the fact that there are different versions of the $QR$ decomposition.  Your "other materials" state the following:

Every invertible matrix has a $QR$ decomposition, where $R$ is invertible...  Every matrix has a $QR$ decomposition, though $R$ may not always be invertible.

In this context, a "$QR$ decomposition" requires an orthogonal matrix $Q$ (so $Q$ is always square) and an upper-triangular matrix $R$ of the same size as $A$.
With this definition, $R$ will have the same rank as $A$ since we have $R = Q^TA$, and $Q^T$ is an invertible matrix.
On the other hand, your original source states the following:

Every $m$ by $n$ matrix with independent columns can be factored into $A=QR$. The columns of $Q$ are orthonormal, and $R$ is upper triangular and invertible.

In this context, $Q$ is not necessarily square, but $R$ is.  Since both $Q$ and $R$ are smaller matrices, this is sometimes called a "thin" or "reduced" factorization.  Since you are looking at a statement about matrices $A$ with linearly independent columns, let's focus on this case.
First, note that since the columns are linearly independent, we necessarily have $m \geq n$.  In the case where $m > n$, we can break write the product as follows:
$$
A = QR = \pmatrix{Q_1 & Q_2} \pmatrix{\tilde R\\0}
$$
The sizes here are as follows. $Q_1: m\times n$, $Q_2: m \times (m-n)$, $R: n \times n$, $0: (m-n) \times n$.
In fact, this partition is confromable for a block-matrix product.  With block-matrix multiplication, we find that
$$
QR = \pmatrix{Q_1 & Q_2} \pmatrix{\tilde R\\0} = Q_1\tilde R + Q_20 = Q_1 \tilde R.
$$
So, $A = Q_1 \tilde R$ is a "thin" $QR$-decomposition where the columns of $Q_1$ are orthonormal (but $Q_1$ is not necessarily square) and if $A$ has linearly independent columns, then $\tilde R$ is invertible.


text:
Q: C# assigning elements of a list to a list of variables In Perl one can do the following
($a, $b, $c) = split(',', "aaa,bbb,ccc");

does anyone know if there is an equivalent in C# other than doing the following?
var elements = "aaa,bbb,ccc".Split(',');
var a = elements[0];
var b = elements[1];
var c = elements[2];

Or is there an alternative for doing the above more concisely?

A: No. There's no way of assigning more than one variable in a single assignment expression in C#. Do you definitely need separate variables instead of an array?
Perhaps if you gave us the wider context, we may be able to suggest a better approach to the overall problem - often if you try to approach a task in the way that you would in a different language, you end up with messy code, and that may be the case here.

A: No there is no other way to do this in C#.
But there is hope in .net - namely F# :D
With this you could do
let [| a; b; c |] = "aaa,bbb,ccc".Split(',')

A: Still not a perfect solution but with C# 7 we can use tuple deconstruction:
var elements = "aaa,bbb,ccc".Split(',');
var (a, b, c) = (elements[0], elements[1], elements[2]);


text:
Q: Moment.js to format dateString Need to use Moment.js to format the below Date string.
Wed Sept 01 2017 04:33:01 GMT+0400 (+04)
I tried to use below but it didn't work
moment(e.dateVale, 'D MMMM D YYYY, hh:mm:ss a')

I  referred http://momentjs.com/ but couldn't make it work.
Any help would be highly appreciated

A: You need to use new Date for creating a Date object from the String you're passing and then will enable you to use moment for formatting that Date object.
See this:
console.log(moment(new Date('Wed Sept 03 2017 06:33:01 GMT+0400 (+04)')).format( 'D MMMM D YYYY, hh:mm:ss a'));

A: Try This:
console.log(moment('Wed Sep 06 2017 04:33:01 GMT+0400 (+04)', 'ddd MMM DD YYYY HH:mm:ss [GMT]Z').utc())

Day and date combination in the string provided by you is not correct and will give following error.
moment.invalid(/* Wed Sept 01 2017 04:33:01 GMT+0400 (+04) */)


text:
Q: Simple noir server won't start I've just started to learn Clojure, and thought a good way to dive into it would be to write a simple Noir website.
I've installed leiningen, did lein self-install and installed the lein noir plugin. When I create a dummy project ...
>> lein noir new test-noir
Creating noir project:  test-noir
Creating new dirs at:  /Users/pdeuchler/Documents/workspace/test-noir
Adding files...
Project created!
>> cd test-noir/

And then try to run it ...
>> lein run

I get an error which I googled, but resulted in no relevant results.
Exception in thread "main" java.io.FileNotFoundException: Could not locate clojure/core/incubator__init.class or clojure/core/incubator.clj on classpath: , compiling:(response.clj:1)
at clojure.lang.Compiler$InvokeExpr.eval(Compiler.java:3342)
at clojure.lang.Compiler.compile1(Compiler.java:6985)
at clojure.lang.Compiler.compile1(Compiler.java:6975)
at clojure.lang.Compiler.compile(Compiler.java:7046)
at clojure.lang.RT.compile(RT.java:385)
at clojure.lang.RT.load(RT.java:425)
at clojure.lang.RT.load(RT.java:398)
at clojure.core$load$fn__4610.invoke(core.clj:5386)
at clojure.core$load.doInvoke(core.clj:5385)
at clojure.lang.RestFn.invoke(RestFn.java:408)
at clojure.core$load_one.invoke(core.clj:5200)
at clojure.core$load_lib.doInvoke(core.clj:5237)
at clojure.lang.RestFn.applyTo(RestFn.java:142)
at clojure.core$apply.invoke(core.clj:602)
at clojure.core$load_libs.doInvoke(core.clj:5271)
at clojure.lang.RestFn.applyTo(RestFn.java:137)
at clojure.core$apply.invoke(core.clj:604)
at clojure.core$use.doInvoke(core.clj:5363)
at clojure.lang.RestFn.invoke(RestFn.java:457)
at compojure.core$loading__4505__auto__.invoke(core.clj:1)
at clojure.lang.AFn.applyToHelper(AFn.java:159)
at clojure.lang.AFn.applyTo(AFn.java:151)
at clojure.lang.Compiler$InvokeExpr.eval(Compiler.java:3337)
at clojure.lang.Compiler.compile1(Compiler.java:6985)
at clojure.lang.Compiler.compile1(Compiler.java:6975)
at clojure.lang.Compiler.compile(Compiler.java:7046)
at clojure.lang.RT.compile(RT.java:385)
....

Can anyone help me out?


text:
Q: Please Fill Out This Field tooltip vs This Field is Required message in HTML Forms Are there certain conditions in which one of them appears and in other cases the other? I know that both appear when 'required' is used with a field in HTML form.
In validation Jquery, if I use $("#register_form").validate({ directly, then I get the This Field is Required message in red color, for the empty fields, on submit.
But if for instance I have a check for recaptcha like this (and the validate part now goes into Else)-
jQuery('#register_form').on('submit', function(event) {
        var recaptcha = document.forms["donor_form"]["g-recaptcha-response"].value;
        console.log('recap val- '+recaptcha);
        if (grecaptcha.getResponse() == "") {
            console.log(grecaptcha.getResponse());
            jQuery("#captcha-reqd").html('reCAPTCHA is required');
            event.preventDefault();
            return false;
        }
        else{
            $("#register_form").validate({

Then in this case I get the Please Fill Out This Field tooltip for empty fields.


text:
Q: Maximum URL nesting reduction Tell me, please, is it possible to reduce the nesting of the page url to a minimum?
For example:
From the original site.com/product_categories/main_category/sub_category/ make site.com/sub_category/
If possible, what is the best way to do this using WP? Maybe there are plugins for this task?
Thank you!


text:
Q: RecyclerView in Fragment with slide Tabs I have an application where I use slide tabs with fragment and in each fragment I have recyclerview with custom adapter, I have 5 tabs now the apps works ok while I slide, the correct data is shown, the first 4 tabs share same layout for the recyclerview adapter the 5th doesn't, now if I click the 4th tab the app crashes it says that it can't get the textview after debugging awhile I've found out that the layout passed to the adapter and the ids of the textviews don't match, so in this case, the layout for the 4th tab is passed to the adapter, but the ids of the textviews are from the 5th tab in which the layout is different, why this happens? this is how the adapter in a fragment looks:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View v = inflater.inflate(R.layout.fragment_two, container, false);

    Display display = getActivity().getWindowManager().getDefaultDisplay();
    Point size = new Point();
    display.getSize(size);
    int width = size.x;
    int height = size.y;

    DisplayMetrics metrics = getResources().getDisplayMetrics();

    List<Info> mDataset = new ArrayList<Info>();

    mDataset.add(new Info("Display", Build.DISPLAY,""));
    mDataset.add(new Info("Width", width+" px",""));
    mDataset.add(new Info("Height", height+" px",""));
    mDataset.add(new Info("Density", ""+metrics.density,""));

    if ( v != null ) {

        mRecyclerView = (RecyclerView) v.findViewById(R.id.my_recycler_view2);
        final LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
        mRecyclerView.setLayoutManager(linearLayoutManager);
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());

        mAdapter = new MyAdapter(mDataset, getContext(), "Display");
        mRecyclerView.setAdapter(mAdapter);

    }

    return v;
}

And this is the adapter, I use same adapter in each fragment:
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private List<Info> mDataset;
private int mLayout;
private Context mContext;
private static int mTextInfoA;
private static int mTextInfoB;
private static int mTextInfoC;
private static String mFragment;

// Provide a suitable constructor (depends on the kind of dataset)
public MyAdapter(List<Info> mDataset, Context mContext, String mFragment) {
    this.mDataset = mDataset;
    this.mContext = mContext;
    this.mFragment = mFragment;

    if( mFragment.equals("Device") || mFragment.equals("Battery") || mFragment.equals("Display") || mFragment.equals("Ram") ) {
        this.mLayout = R.layout.cardview_layout;
        this.mTextInfoA = R.id.info_name;
        this.mTextInfoB = R.id.info_value;
    } else if( mFragment.equals("Storage") ){
        this.mLayout = R.layout.cardview_storage_layout;
        this.mTextInfoA = R.id.storage_total_value;
        this.mTextInfoB = R.id.storage_free_value;
        this.mTextInfoC = R.id.storage_textview;
    }
}

// Create new views (invoked by the layout manager)
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent,
                                               int viewType) {
    // create a new view
    View v = LayoutInflater.from(parent.getContext())
            .inflate(mLayout, parent, false);

    ViewHolder vHolder = new ViewHolder(v);

    return vHolder;
}

@Override
public void onBindViewHolder(ViewHolder viewHolder, int i) {
    Info info = mDataset.get(i);
    viewHolder.mTextInfoa.setText(info.a);
    viewHolder.mTextInfob.setText(info.b);

    if (!info.c.isEmpty()) {
    if (info.c.equals("Internal Storage")) {
        viewHolder.mTextInfoc.setBackgroundColor(Color.parseColor("#2196F3"));
    } else if (info.c.equals("External Storage")) {
        viewHolder.mTextInfoc.setBackgroundColor(Color.parseColor("#F44336"));
    }
        viewHolder.mTextInfoc.setText(info.c);
}
}

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

public static class ViewHolder extends RecyclerView.ViewHolder {
    public TextView mTextInfoa;
    public TextView mTextInfob;
    public TextView mTextInfoc;

    public ViewHolder(View itemView) {
        super(itemView);

        mTextInfoa = (TextView) itemView.findViewById(mTextInfoA);
        mTextInfob = (TextView) itemView.findViewById(mTextInfoB);
        mTextInfoc = (TextView) itemView.findViewById(mTextInfoC);
    }

}

Clicking on the first three tabs its ok but if I'm on the 1th tab and I click directly on the 4th or 5th it crashes with that error.
My Activity OnCreate Method:
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
    setupViewPager(viewPager);

    TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
    tabLayout.setupWithViewPager(viewPager);

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });
}

My main layout:
<?xml version="1.0" encoding="utf-8"?>

<android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/AppTheme.AppBarOverlay">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:layout_scrollFlags="scroll|enterAlways"
        app:popupTheme="@style/AppTheme.PopupOverlay" />

    <android.support.design.widget.TabLayout
        android:id="@+id/tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:tabGravity="fill"
        app:tabMode="scrollable" />

</android.support.design.widget.AppBarLayout>

<android.support.v4.view.ViewPager
    android:id="@+id/viewpager"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:layout_behavior="@string/appbar_scrolling_view_behavior" />

<android.support.design.widget.FloatingActionButton
    android:id="@+id/fab"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom|end"
    android:layout_margin="@dimen/fab_margin"
    android:src="@android:drawable/ic_dialog_email" />

A: I've fixed it myself, the problem was that the variables in the adapter were static.


text:
Q: Error while connecting to SQL server through Django In settings file, I have given SQL SERVER Database connection values like this.
DATABASES = {

'default': {

        'NAME': 'AdventureWorks2014',

        'ENGINE': 'sqlserver_ado',

        'HOST': '127.0.0.1',

        'USER': '',

        'PASSWORD': '',
    }
}

Versions:
Django v:1.11
Python v:2.7
django-mssql v:1.8
pip v:9.0
Development Platform:
Visual Studio
After the database connection values changes, I have used the command
python manage.py makemigrations

Here I got the error:

Executing manage.py makemigrations
  Traceback (most recent call last):
    File "E:\Django Projects\DjangoMSSQLDatabaseConn\DjangoMSSQLDatabaseConn\manage.py", line 17, in
      execute_from_command_line(sys.argv)
    File "E:\Django Projects\DjangoMSSQLDatabaseConn\DjangoMSSQLDatabaseConn\VirtualEnv\lib\site-packages\django\core\management__init__.py", line 364, in execute_from_command_line
      utility.execute()
    File "E:\Django Projects\DjangoMSSQLDatabaseConn\DjangoMSSQLDatabaseConn\VirtualEnv\lib\site-packages\django\core\management__init__.py", line 338, in execute
      django.setup()
    File "E:\Django Projects\DjangoMSSQLDatabaseConn\DjangoMSSQLDatabaseConn\VirtualEnv\lib\site-packages\django__init__.py", line 27, in setup
      apps.populate(settings.INSTALLED_APPS)
    File "E:\Django Projects\DjangoMSSQLDatabaseConn\DjangoMSSQLDatabaseConn\VirtualEnv\lib\site-packages\django\apps\registry.py", line 108, in populate
      app_config.import_models()
    File "E:\Django Projects\DjangoMSSQLDatabaseConn\DjangoMSSQLDatabaseConn\VirtualEnv\lib\site-packages\django\apps\config.py", line 202, in import_models
      self.models_module = import_module(models_module_name)
    File "C:\Python27\Lib\importlib__init__.py", line 37, in import_module
      import(name)
    File "E:\Django Projects\DjangoMSSQLDatabaseConn\DjangoMSSQLDatabaseConn\VirtualEnv\lib\site-packages\django\contrib\auth\models.py", line 4, in
      from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager
    File "E:\Django Projects\DjangoMSSQLDatabaseConn\DjangoMSSQLDatabaseConn\VirtualEnv\lib\site-packages\django\contrib\auth\base_user.py", line 52, in
      class AbstractBaseUser(models.Model):
    File "E:\Django Projects\DjangoMSSQLDatabaseConn\DjangoMSSQLDatabaseConn\VirtualEnv\lib\site-packages\django\db\models\base.py", line 124, in new
      new_class.add_to_class('_meta', Options(meta, app_label))
    File "E:\Django Projects\DjangoMSSQLDatabaseConn\DjangoMSSQLDatabaseConn\VirtualEnv\lib\site-packages\django\db\models\base.py", line 325, in add_to_class
      value.contribute_to_class(cls, name)
    File "E:\Django Projects\DjangoMSSQLDatabaseConn\DjangoMSSQLDatabaseConn\VirtualEnv\lib\site-packages\django\db\models\options.py", line 214, in contribute_to_class
      self.db_table = truncate_name(self.db_table, connection.ops.max_name_length())
    File "E:\Django Projects\DjangoMSSQLDatabaseConn\DjangoMSSQLDatabaseConn\VirtualEnv\lib\site-packages\django\db__init__.py", line 33, in getattr
      return getattr(connections[DEFAULT_DB_ALIAS], item)
    File "E:\Django Projects\DjangoMSSQLDatabaseConn\DjangoMSSQLDatabaseConn\VirtualEnv\lib\site-packages\django\db\utils.py", line 212, in getitem
      conn = backend.DatabaseWrapper(db, alias)
    File "E:\Django Projects\DjangoMSSQLDatabaseConn\DjangoMSSQLDatabaseConn\VirtualEnv\lib\site-packages\sqlserver_ado\base.py", line 184, in init
      super(DatabaseWrapper, self).init(*args, **kwargs)
    File "E:\Django Projects\DjangoMSSQLDatabaseConn\DjangoMSSQLDatabaseConn\VirtualEnv\lib\site-packages\django\db\backends\base\base.py", line 96, in init
      self.client = self.client_class(self)
  TypeError: Error when calling the metaclass bases
      'NoneType' object is not callable
  The interactive Python process has exited.

Can anyone help me solve this?


text:
Q: use grunt to update package dependancy version numbers I have two projects EasyUI and EasyUI-Layout. EasyUI-Layout depends on EasyUI. I have grunt files set up to build them and push them to github. Here are the abridged grunt files:
// easyui
module.exports = function(grunt) {
  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    browserify:...,
    bumpup: {
      file: 'package.json'
    },
    shell: {
      git: ...
    },
    watch: ...
  });

  grunt.registerTask('g', ['bumpup', 'browserify', 'shell:git']);
};

// easyui-layout
module.exports = function(grunt) {
  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    browserify:...,
    bumpup: {
      file: 'package.json'
    },
    shell: {
      git: ...,
      npm: ...
    },
    watch: ..
  });

  grunt.registerTask('g', ['shell:npm', 'bumpup', 'browserify', 'shell:git']);
};

What I would like is that when I build and commit the EasyUI-Layout project, its package json is updated with the latest version number from EasyUI. At the moment, for example, the version number for EasyUI dependency in the package.json stays stuck on 0.0.0. Here is the abridged package.json file:
{
  "name": "easyui-layout",
  "version": "0.0.3",
  "dependencies": {
    "easyui": "0.0.0"
  }
}

Say the EasyUI version number is 0.0.7, then the next time I build EasyUI-Layout with grunt I would like the package.json to be:
{
  "name": "easyui-layout",
  "version": "0.0.4",
  "dependencies": {
    "easyui": "0.0.7"
  }
}

I assume this is possible with bump or bumpup? But a little experimentation has gotten me nowhere.

A: No, these types of things should be manually specified. You can use semver ranges though to have the package automatically install

A: Let me answer my own question. Since I'm publishing EasyUI to npmjs.org let's assume the latest version is up there. Here's the abridged grunt file for the EasyUI-Layout package:
grunt.initConfig({
  pkg: grunt.file.readJSON('package.json'),
  shell: {
    npm: {
      command: [
        'npm install easyui@latest --save'
      ].join('&&')
    }
  }
});

This just forces npm to install the latest version of EasyUI and updates the package.json file.
Simple as that. No need for other grunt tasks, custom or otherwise, and nothing to do with semver.


text:
Q: Angular2 Routing from Navbar (AppComponent) I'm having an issue with Routing in Angular2 where routing creates a new object and keeps the old object.
My navbar and [Home] button resides in the AppComponent.
.. app.html
Home
<router-outlet></router-outlet>
..

The router defaults to AuthComponent at the start.
.. app.component.ts
@RouteConfig([
  { path: '/', as: 'Auth', component: AuthComponent, useAsDefault: true }
])
..

I'll demonstrate the scenario by logging a message in AuthComponent's constructor.
.. auth.component.ts
constructor(private _router: Router) {
    console.log("Constructing AuthComponent");
    this.router = _router;
}
..

The response to clicking the Home button will produce Constructing AuthComponent everytime it is clicked thus creating a new object. (I can confirm that the old objects do still exist)
I want to be able to route to somewhere and then route back into AuthComponent while still having access to my data I set previously.
See this plunker.
I'm currently using 2.0.0-beta.7 Updated to 2.0.0.beta.9

A: You could use the CanReuse interface on your component and its routerCanReuse method. This way, if this method returns true, the same instance of the component will be used within routing:
@Component({
  (...)
})
class SomeComponent implements CanReuse {
  constructor(params: RouteParams) {

  }

  routerCanReuse(next: ComponentInstruction, prev: ComponentInstruction) {
    return true;
  }
}

See this link for more details:

*

*https://angular.io/docs/ts/latest/api/router/CanReuse-interface.html


text:
Q: threejs texture causes "GL ERROR :GL_INVALID_OPERATION : glDrawElements" I'm trying to apply a texture to a geometry created at runtime, reading a binary asset from a remote server.
I create the geometry assigning UVs (geometry.faceVertexUvs = uvs;), normals (face.vertexNormals.push(...)) and tangents (face.vertexTangents.push(...)).
If I try to create a mesh with a basic material, there are no problems, but when I create the mesh with that geometry and I try to apply my texture, webgl doesn't display any geometry and I get this warning:
[.WebGLRenderingContext]GL ERROR :GL_INVALID_OPERATION : glDrawElements: attempt to access out of range vertices in attribute 1
Does anybody know what is going on? I think that my geometry has something wrong, because if I use a THREE.Sphere, I can actually apply the texture.
But everyone told me that in order to apply texture I need UVs, and I have'em.
I think that my faceVertexUvs is wrong.
The real question is: geometry.faceVertexUvs.length should be equal to geometry.vertices.length, or it should be equal to geometry.faces.length ?
Thank you very much.
PS: I've already read the following posts
WebGL drawElements out of range?
Three JS Map Material causes WebGL Warning
THREEjs can't use the material on the JSON Model when initializing. Gives me WebGL errors
Loading a texture for a custom geometry causes "GL_INVALID_OPERATION" error

A: problem solved!!
@GuyGood: you're right when you say that every vertex need a UV-Vector2, but it's wrong to say that geometry.faceVertexUvs.length should be equal to geometry.vertices.length...
it seems that facevertexUvs is a matrix, and not an array..well, it is an array of arrays..not properly a matrix..in fact I think it can be used to handle multi-mesh objects..if facevertexUvs.length == 3, we have 3 submeshes, so 3 arrays..each one of them has a length equal to the number of faces of a particular submesh..and every face knows the UV mapping about the 3 vertices defining that face..
hope this is clear and helpful!!


text:
Q: SMTPSenderRefused at /contacts I am using Django. I want to send email via html contact form. And I am facing this error:
SMTPSenderRefused at /contacts
(530, b'5.7.0 Must issue a STARTTLS command first. p6-20020a1c5446000000b003b47e75b401sm7708347wmi.37 - gsmtp', 'webmaster@localhost')
Request Method: POST
Request URL:    http://127.0.0.1:8000/contacts
Django Version: 4.1.2
Exception Type: SMTPSenderRefused
Exception Value:
(530, b'5.7.0 Must issue a STARTTLS command first. p6-20020a1c5446000000b003b47e75b401sm7708347wmi.37 - gsmtp', 'webmaster@localhost')

Here is my settings.py
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_USE_TSL = True
EMAIL_HOST_USER = 'email@gmail.com'
EMAIL_PASSWORD = 'Key'
EMAIL_PORT = 587
EMAIL_USE_SSL = False

Here is my view.py
def contacts(request):
    selected = "contact"

    if request.method == 'POST':
        name = request.POST.get('name')
        email = request.POST.get('email')
        subject = request.POST.get('subject')
        message = request.POST.get('comments')

        data = {
            'name':name,
            'email': email,
            'subject': subject,
            'message': message
        }

        message = '''
        New Message : {}

        From : {}
        '''.format(data['message'], data['email'])

        send_mail(data['subject'], message,'' ,['qweaverinfo@gmail.com'])
        return render(request, 'layouts/auth-signup-success.html', locals())

    return render(request, 'layouts/contact.html', locals())

I don't understand how to fix the STARTTLS. Is anyone here to help me?
I tried to use the SSL, I met the same problem.
I want to the Django documentation, I did not find anything about the STARTTLS command.
I was expecting to send email via a html template using Django.


text:
Q: Entity Framework 6, Repository pattern and Unit of Work I am learning Entity Framework and some design patterns such repository pattern and unit of work. I wrote a program that uses these patterns. In this class I have one DbContext object and I always use this static DbContext. Throughout my application's lifetime, there is only one DbContext object. Am I doing right using this way, think if there are lots of users. Will be any problem about database connections.
UI code:
UnitOfWork uow = GetUnitOfWork(); //There is only one uow object
uow.EmployeeRepository.Insert(new Employee
{
    Name = name,
    Surname = surname
});

GetUnitOfWork code:
private static UnitOfWork _uow;
public static UnitOfWork GetUnitOfWork()
{
    return _uow ?? (_uow = new UnitOfWork());
}

UnitOfWork code:
public class UnitOfWork : IDisposable
{
    private static FollowerEntities _context;
    private DbContextTransaction _transaction;

    //repositories
    private EmployeeRepository _employeeRepository;

    public UnitOfWork()
    {
        _context = new FollowerEntities();
    }

    public EmployeeRepository EmployeeRepository
    {
        get { return _employeeRepository ?? (_employeeRepository = new EmployeeRepository(_context)); }
    }

    public void Save()
    {
        try
        {
            _transaction = _context.Database.BeginTransaction();
            _context.SaveChanges();
            _transaction.Commit();
        }
        catch
        {
            _transaction.Rollback();
            throw;
        }
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    private void Dispose(bool disposing)
    {
        if (disposing)
        {
            if (_context != null)
            {
                _context.Dispose();
                _context = null;
            }
        }
    }
}

Employee Repository
public class EmployeeRepository : GenericRepository<Employee>
{
    public EmployeeRepository(FollowerEntities entities)
        : base(entities)
    {

    }
}

Generic Repository
public class GenericRepository<T> where T : class
{
    private FollowerEntities _entities;

    private DbSet<T> table = null;

    public GenericRepository()
    {

    }

    public GenericRepository(FollowerEntities entities)
    {
        this._entities = entities;
        table = _entities.Set<T>();
    }

    public IEnumerable<T> SelectAll()
    {
        return table.ToList();
    }

    public T SelvectById(object id)
    {
        return table.Find(id);
    }

    public void Insert(T obj)
    {
        table.Add(obj);
    }

    public void Update(T obj)
    {
        table.Attach(obj);
        _entities.Entry(obj).State = EntityState.Modified;
    }

    public void Delete(object id)
    {
        T existing = table.Find(id);
        table.Remove(existing);
    }
}

A: private static UnitOfWork _uow;
public static UnitOfWork GetUnitOfWork()
{
    return _uow ?? (_uow = new UnitOfWork());
}

Although technically correct, this won't be as useful as you think. You limit the API to a single instance of the UoW. Considering shared scenarios like ASP.NET, this method won't probably be used as often as you think. I suggest removing it.
public UnitOfWork()
{
    _context = new FollowerEntities();
}

This unnecessarily couples the context lifetime to UoW lifetime. Instead, separate them:
public UnitOfWork( FollowerEntities context )
{
    _context = context;
}

This way, other means of lifetime management (IoC container possibly) could be used.
_transaction = _context.Database.BeginTransaction();
_context.SaveChanges();
_transaction.Commit();

Are you sure saves should always be wrapped in a transaction? What if another transaction exists on the same connection and you want to reuse it?
And the biggest issue - neither the UoW nor repositories are abstracted (with interfaces). This means that the client is still coupled to the sole implementation. You have just created a wrapped over Entity Framework but you can't benefit from it, for example, you can't switch to another implementation without rewriting it. I don't see any solid point in it, beside just excercising.


text:
Q: Android add fragment and tab after load? I have a FragmentActivity with two Fragments in it and a sliding tab layout:
String titles[] = new String[] {"Tab One", "Tab Two"};
int numTabs = titles.length;

EventAdapter adapter = new EventAdapter(getSupportFragmentManager(), titles, numTabs);
ViewPager pager = (ViewPager) findViewById(R.id.pager);
pager.setAdapter(adapter);

SlidingTabLayout sliding_tabs = (SlidingTabLayout) findViewById(R.id.sliding_tabs);
sliding_tabs.setDistributeEvenly(true);
sliding_tabs.setViewPager(pager);

With the FragmentPagerAdapter:
private class EventAdapter extends FragmentPagerAdapter {
    private List<String> titles;
    private int numTabs;

    public void addTab (String title) {
        this.titles.add(title);
        this.numTabs++;
        this.notifyDataSetChanged();
    }

    public EventAdapter(FragmentManager fm, List<String> mTitles, int mNumTabs) {
        super(fm);

        this.titles = mTitles;
        this.numTabs = mNumTabs;
    }

    @Override
    public Fragment getItem(int position) {
        switch (position) {
            case 2:
                return new FragThree();
            case 1:
                return new FragTwo();
            default:
                return new FragOne();
        }
    }

    @Override
    public String getPageTitle(int position) {
        return titles.get(position);
    }

    @Override
    public int getCount() {
        return numTabs;
    }
}

Some time down the line, I would like to dynamically add the third tab to this layout. Is there a way to do this in code? As you can see, I already have the PagerAdapter set up to catch the third tab. I just need to load it in...

A: You need to add this method to your adapter EventAdapter :
public void addTab (String title) {
    this.titles.add(title);
    // this is the variable returned from getCount method
    this.numbTabs++;
    this.notifyDataSetChanged();
}

Main purpose is to add the tab and call notifydatasetchanged.
Now call addTab on this adapter's object and tab will be added.
after addTab do sliding_tab.setViewPager(this.pager);
 Please accept if this solves the purpose.


text:
Q: How to get both edge and vertex properties in gremlin titan graph database and valueMap() in java ts1=graph.addVertex(label,"test","test_id",872)
ts2=graph.addVertex(label,"test","test_id",873)
rj1=graph.addVertex(label,"req","id1",113,"status","S")
rj2=graph.addVertex(label,"req","id1",114,"status","S")
e1=rj1.addEdge("edgeA",ts1,"seq",1)
e2=rj2.addEdge("edgeA",ts2,"seq",2)

I am able to get the following in seperate query:
g.V().hasLabel("req").has("status","S").outE("edgeA").valueMap()
==>[seq:1]
==>[seq:2]
g.V().hasLabel("job").has("status","S").outE("job_edge").inV().valueMap()
==>[test_id,872]
==>[test_id,873]

How to get both sequence and corresponding test_id in single query
updated question:
public void readTestbedJob(String tbName){
    GraphTraversalSource traversalSource = getTitanTraversalSource();
    GraphTraversal<Vertex, Map<String, Object>> query1 = traversalSource.V()
                .has("req","id1",113).valueMap();
    GraphTraversal<Vertex, Map<String, Object>> query2 = traversalSource.V().has("status","S").as("a").
            outE("edgeA").as("e").
            inV().as("v").
            select("a","e","v").by(valueMap());
}

From gremlin console: both query1 and query2 are returning results properly.
but, I am not able to use valueMap() or values() in query2 directly in java,
GraphTraversal<Vertex, Map<String, Object>> query2 = traversalSource.V().has("status","S").as("a").
            outE("edgeA").as("e").
            inV().as("v").
            select("a","e","v").by(valueMap());

1)when I use by(valueMap()) or by(values()) directly in the above query, I am getting following compilation error: undefined function valueMap()
2)Instead of by(valueMap()), by() returning only vertex id and edge id.
a=v[16576],b=e[2pjpce-6eo-90r9-9ig][edgeA], c=v[8304]}
Could you please help me to resolve this problem. I am not able identify how to use by(valueMap()) in Java.

A: You could use select():
gremlin> g.V().has("job_status","S").
......1>   outE("edgeA").as('e').
......2>   inV().as('v').
......3>   select('e','v').by(valueMap())
==>[e:[sequence:1],v:[test_suite_id:[872]]]
==>[e:[sequence:2],v:[test_suite_id:[873]]]


text:
Q: Sorting and paginating Mongodb documents Update: I would really appreciate if anyone can point me in the right direction here. All of the links I've looked at and read through seem to be showing me how to sort  documents within the console, but I still haven't worked out how to do this on the actual user interface. The code below shows how my index page is generating the 'blog' documents through a forEach loop. All I want to do is:
a) limit the number of results displayed on the app to 5 per page and
b) sort these results by date
One user, as you can see, pointed me in the direction of another link regarding pagination,. I'm sure Im being stupid but I really am a beginner to all this and I cannot work out how this ties in with my code and how to implement this.

Original Post:
I'm creating a blog app using node.js and express with mongoDB as my database. All is up and running and working fine, however on the page which lists the blogs, I need to ensure that only a maximum of, say, 5 appear on each page and then I want to add pagination to scroll to older blogs. I've tried searching online how to do this but cannot find any explanation. Can anyone help?
Here the code which displays my blogs:

Welcome to the Blog

News, views and commentary

    <% blogs.forEach(function(blog){ %>

                    <a class = "col-md-12" href = "/blogs/<%= blog._id %>">
<%= blog.title %>

<%= blog.created.toDateString() %>

                    <img class = "col-md-4 img-responsive" src="<%= blog.image %>">

<% if(blog.body) { %><%-blog.body.substring(0,300)%>... <% } %>

        <% }) %>


text:
Q: Como escribo una list comprenhension de los cubos del 1 al 10 si el value***3 me da invalid syntax cubes=[value***3 for value in range(1,10)]
print(cubes

A: si lo que quieres es ver todos los números del 1 al 10 al cubo se debe hacer de esta forma
for num in range(1,11):
    print(f"{num} al cubo es: {num**3}")

para elevar un numero a n se debe usar dos veces el operador de multiplicación **
para almacenarlos en una lista lo podes hacer de la siguiente manera
cubes=[value**3 for value in range(1,11)]
print(cubes)

A: En Python, el operador de potencia es el operador ** (dos asteriscos, ver The power operator), por lo tanto, el código que tienes debería ser  de la siguiente forma:
cubes=[value**3 for value in range(1,10)]
print(cubes)


text:
Q: reducer.state.props is undefined in nested actions react/redux Below are my action and reducer files - In my component state I am only seeing this.props.mainData - but others subdataOneData etc., are not being loaded in to the state - till reducer i see the right actions are being dispatched and I also see the data for sub - calls - but they are not reaching my component - I have mapStatetoprops - where I am doing
New issue: as per the updated code - when i print out payload in reducer - I see maindata with the api data but SubData [{}, {}, {}] ..?
Updated code:
    import { GET_DATA_AND_SUBDATA } from '../constants/types';
export function getMainData() {
  return async function getMainData(dispatch) {
    const { data } = await getMainDataAPI();
    const subData = data.map((item) => {
      const endpoint = 'build with item.name';
      return Request.get(endpoint);
    });
     console.log('subddd' + subData);  prints -> **[object Promise],[object Promise],[object Promise]**
    dispatch({
      type: GET_DATA_AND_SUBDATA,
      payload: { data, subData }
    });
  };
}

async function getMainDataAPI() {
  const endpoint = 'url';
  return Request.get(endpoint);
}

A: The problem lies on the way you dispatch the actions.
You are not providing data for mainData and subdataOneData at the same time.
export function getData() {
    return async function getData(dispatch) {
        const { data } = await getDataAPI();

        // This will cause first re-render
        dispatch({ type: GET_DATA, payload: data });

        Object.keys(data).map((keyName, keyIndex) => {
            const endpoint = 'ENDPOINT';
            Request.get(endpoint).then((response) => {
                // This will cause second re-render
                dispatch({
                    type: GET_subdata + keyIndex,
                    payload: response.data });
                });

            return keyIndex;
        });
    };
}

At first render your subdataOneData is not availble yet.
You are not even specifying a default value in the reducer, therefore it will be undefined.
You can change your action thunk like this
export function getData() {
    return async function getData(dispatch) {
        const { data } = await getDataAPI();

        const subDataResponse =  await Promise.all(
            Object.keys(data).map( () => {
                const endpoint = 'ENDPOINT';
                return Request.get(endpoint)
            })
        )

        const subData = subDataResponse.map( response => response.data )

        dispatch({
            type: GET_DATA_AND_SUBDATA
            payload: { data, subData }
        });

    };
}

And change your reducer accordingly in order to set all data at once.
export default function myReducer(state = {}, action) {
    switch (action.type) {
        case GET_DATA_AND_SUBDATA:
        return {
            ...state,
            mainData: action.payload.data,
            subdataOneData: action.payload.subData[0],
            subdataTwoData: action.payload.subData[1]
        };
        default:
            return state;
    }
}

Note: it's also a good practice to set your initial state in the reducer.
const initialState = {
    mainData: // SET YOUR INITIAL DATA
    subdataOneData: // SET YOUR INITIAL DATA
    subdataTwoData: // SET YOUR INITIAL DATA
}

export default function myReducer(initialState, action) {


text:
Q: Create tensorflow with tf.data.Dataset.from_tensor_slices and one property with dynamic size I have a pandas dataframe and of its columns is "bbox" with value i.e. [[94.0, 58.0, 469.0, 362.0]]. I want to convert this dataframe to a custom dataset with tf.data.Dataset.from_tensor_slices.
I want the bbox element to have a shape of (None,4) but it is created with shape (1,4) tf.Tensor([[ 94.  58. 469. 362.]], shape=(1, 4), dtype=float32) and I don't know what I am doing wrong.
My dataset is created with this code:
myimages = pd.DataFrame.from_dict(train_data).to_dict("list")
myimages = tf.data.Dataset.from_tensor_slices(myimages)

Thanks everyone in advance for your time

A: The shape of the tensor is (1, 4) since the bbox column in your dataframe contains elements that are a list of lists, not a single list.
To get a shape of (4, ) for each label, you can modify the elements in the bbox column in your dataframe by indexing each bbox element to obtain the first bbox, and inserting it into the dataframe like so:
myimages["bbox"] = [bbox_element[0] for bbox_element in myimages["bbox"].values]

A: You can just use tf.data.Dataset.map and tf.squeeze to get rid of the extra dimension:
import tensorflow as tf
import pandas as pd

train_data = {'names': ['some_image.jpg', 'other_image.jpg'],
              'bbox': [[[94.0, 58.0, 469.0, 362.0]], [[94.0, 58.0, 469.0, 362.0]]]}
df = pd.DataFrame(train_data)
myimages = tf.data.Dataset.from_tensor_slices((df['names'].to_numpy(), df['bbox'].to_list()))
myimages = myimages.map(lambda x, y: (x, tf.squeeze(y, axis=0)))

for x, y in myimages:
  print(x, y)

tf.Tensor(b'some_image.jpg', shape=(), dtype=string) tf.Tensor([ 94.  58. 469. 362.], shape=(4,), dtype=float32)
tf.Tensor(b'other_image.jpg', shape=(), dtype=string) tf.Tensor([ 94.  58. 469. 362.], shape=(4,), dtype=float32)


text:
Q: Quorum: "invalid opcode: SELFBALANCE" error unless 'petersburg' chosen manually We are running a GoQuorum 27.7 network.
In Remix with 'default' as the EVM version, when running the function SELFBALANCE it gives the error: invalid opcode: SELFBALANCE .
However, when manually choosing "petersburg" as the EVM version, it works fine.
// SPDX-License-Identifier: MIT

pragma solidity >=0.8.0;

contract TestCalls {

    uint256 public XYSTORED = 0;

    function setBalance() external returns(uint256) {
            XYSTORED = address(this).balance;
            return XYSTORED;
    }

    function withdawlCIC() external {
        payable(msg.sender).transfer(XYSTORED);
        XYSTORED = address(this).balance;
    }

    function emergencyWithdrawl() external {
        payable(msg.sender).transfer(XYSTORED);
    }

    function ViewXXBalance() external view returns(uint256 balance) {
        balance = address(this).balance;
    }

}

What is the approach to allow let it work without having to choose "petersburg" every time a contract with this function is deployed?
It is a QBFT network.
 "config": {
                "chainId": 1234,
                "homesteadBlock": 0,
                "eip150Block": 0,
                "eip150Hash": "0x0000000000000000000000000000000000000000000000>
                "eip155Block": 0,
                "eip158Block": 0,
                "byzantiumBlock": 0,
                "constantinopleBlock": 0,
..........

I tried adding the following transitions to Genesis. The issue persisted:
"transitions": [{
                                "block": 54074,
                                "istanbulBlock": true
                        },
                        {
                                "block": 547122,
                                "petersburgBlock": true
                        }]

To run a function in Remix to retrieve the self balance.


text:
Q: React Redux one-page app: handle an API 404 with full page render In a React one-page application using react-router to implement navigation, what's the best practice for rendering a full page error when encountering API errors requested when rendering a component in the page?
To be more specific, I understand react-router has a good method to implement a 404 error handler for URL routes that are simply not mapped, but when a route DOES match a mapped route with a dynamic portion of the URL (like an data-id) resulting in the rendering of a component that makes a request which responds in a 404 error, what is the best practice for replacing the entire react rendered view with an error view?
Example Scenario:

*

*Route = "/profile/person/:PersonId",

*Person ID 1234 does NOT exist in the backend.

*User visits "/profile/person/1234"

*The component for the profile/person/:PersonId route renders, and makes the request to get the profile data for person Id 1234, which returns with a 404, which really means the given URL is a 404, though not to react-router.

A: This is just a suggestion as I don't really believe there is a defined best practice as you are asking.
ApiService.fetch(url).then(
  onSuccess(result) => { /* dispatch page fetch success */ },
  onError(result) => { /* dispatch page fetch error */ }
);

Then structure your app something like:
<App>
  { error ? <ErrorHandler /> : <PageHandler /> }
</App>

This structure would shortcut your page rendering on valid routes that encounter a server error and render error content instead.


text:
Q: Dynamic segment not working in ember Possible Duplicate
My code is quite simple, my html:

My Ember code:
    WebApp.Router.map(function () {
    this.resource('sites', { path: '/' } , function() {
        this.route('index', { path: '/:site_id' })
    });
});

//returns all Sites to display
WebApp.SitesRoute = Ember.Route.extend({
    model: function () {
        return WebApp.Site.find();
    }
});

 WebApp.Site = DS.Model.extend({
      id: DS.attr('integer')
 });

WebApp.Site.FIXTURES = [
{
    id: 1,
    siteName: gff1.com
},
{
    id: 2,
    siteName: gff2.com
},
{
    id: 3,
    siteName: gff3.com
}
];

I want to make a list of sites with link to /sites/index/<ID>
When I run this code I get Assertion failed: Cannot call get with 'id' on an undefined object.
What am I doing wrong?

A: There are a few issues going on here.  A working version can be found at http://jsbin.com/ikozuv/1/edit
The cause of your problem is in your template, you don't have site defined when you are trying to linkTo it.  This should fix that issue
{{#each site in controller}}

    {{#linkTo 'sites.index' site}} {{site.siteName}} {{/linkTo}}

{{/each}}

Note: the above still wouldn't be the preferred way to do it, see below.
The other issues include not listing siteName as an attribute to your WebApp.Site, setting an ID in your model declaration, and the url you are expecting /sites/index/<ID> isn't quite what you would get with the router defined the way it is.  The recommended way would be to configure your router like:
WebApp.Router.map(function () {
    this.resource('sites', { path: '/' } , function() {
        this.resource('site', { path: ':site_id' });
    });
});


text:
Q: Internal Error on trying copy data to postgres table from python code using copy_from function of psycopg2 I did this in my python code, based on the documentation here and it's mention here
# anything can be used as a file if it has .read() and .readline() methods
data = StringIO.StringIO()
data.write('\n'.join(['Tom\tJenkins\t37',
                  'Madonna\t\N\t45',
                  'Federico\tDi Gregorio\t\N']))
data.seek(0)

curs.copy_from(data, 'distributors')

I got this error:
Traceback (most recent call last):
  File "", line 1, in
    cursor.copy_from(data, 'distributors')
InternalError: current transaction is aborted, commands ignored until end of transaction block

A: Found the answer here:
There was an attempted query run of an erroneous query using the same database connection. (For details: I had run a copy_from execution on this db connection with incorrect data. It had failed. And, then I modified my data to be in correct format)
When your previous query/command on the database using this connection had a problem/error, it needs to be rolled back using connection.rollback() call. Once, you execute that code, and re-run the fresh correct code, you would get data to be properly copied from Python code to Postgres database.


text:
Q: marklogic remove duplicate node/element I have several thousand documents that have duplicate element nodes.  How can I find and remove duplicate title elements in my XML files?
I use fn:distict-values() cause performance issues.
for example:
01.xml
<doc>
     <pdf>1</pdf>
     <title>Head First JavaScript</title>
     <title>Head First JavaScript</title>
</doc>

02.xml
<doc>
    <pdf>0</pdf>
    <title>Python: Programming Basics for Absolute Beginners </title>
    <title>Python: Programming Basics for Absolute Beginners </title>
</doc>

result:
01.xml
<doc>
     <pdf>1</pdf>
     <title>Head First JavaScript</title>

</doc>

02.xml
<doc>
    <pdf>0</pdf>
    <title>Python: Programming Basics for Absolute Beginners </title>

</doc>

A: Hi Please test attached code
    let $doc :=
<doc>
    <title>Head First JavaScript</title>
     <title>Head First JavaScript</title>
     <title>hellao</title>
     <title>hello</title>
     <title>hello</title>
     <title>Python: Programming Basics for Absolute Beginners </title>
     <title>ahello</title>
     <title>Python: Programming Basics for Absolute Beginners </title>
</doc>

for $data in $doc//title[not(. = preceding-sibling::node())]
return $data

A: I suggest you run a CORB job and have each doc get processed individually. Then the exact code you run for each document won't matter all that much so long as it does the work. It's the kind of thing you'll let run overnight if you have a massive dataset.

A: One of the easiest ways to remove duplicate title elements would be with an XSLT transformation.
xquery version "1.0-ml";
declare variable $XSLT :=
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">

    <!-- This identity template copies all content by default -->
    <xsl:template match="node()|@*">
        <xsl:copy>
            <xsl:apply-templates select="node()|@*"/>
        </xsl:copy>
    </xsl:template>

    <!--This template matches (and removes) the duplicate title elements
        You could match more generically on any element * or add other match criteria
       -->
    <xsl:template match="title[text() = preceding-sibling::title[1]/text()]"/>

</xsl:stylesheet>;

xdmp:xslt-eval($XSLT,
  <doc>
    <pdf>0</pdf>
    <title>Python: Programming Basics for Absolute Beginners </title>
    <title>Python: Programming Basics for Absolute Beginners </title>
  </doc>
)

If it's just several thousand documents, then you might be able to transform and save them all in one module execution.
Otherwise, applying the transform in a CoRB job as @hunterhacker suggests would ensure that you don't need to worry about timeouts by splitting up the work into individual executions.


text:
Q: Postgresql refusing connection to server I have been trying to connect to my postgresql 9.3 server but I keep getting this error.
Server doesn't listen
The server doesn't accept connections: the connection library reports
could not connect to server: Connection refused (0x0000274D/10061)
Is the server running on host "localhost" (::1) and accepting TCP/IP
connections on port 5433? could not connect to server: Connection
refused (0x0000274D/10061) Is the server running on host "localhost" (127.0.0.1)
and accepting TCP/IP connections on port 5432?

I have tried connecting through pgadmin3 and the command line.
psql.exe -h localhost -U postgres

This command also gives the same error.
I am on a windows machine. I have tried creating a separate server also with the same result.
I have no idea whats happening. Please help.
Thanks

A: Start the server with postgres -D ['data folder']
As in docs:
http://www.postgresql.org/docs/9.1/static/server-start.html
So in my Windows postgres installation from the bin folder:
postgres.exe -D ..\data
where data is in the postgresql installation folder

A: As the error clearly tells or asks actually, Is the server running on host "localhost"?
So the chances are, the Postgres server is not running on your machine.
You can start the service(the layman way) by going to services and starting the service.
Here is how you do it:

*

*Open Run Window by Winkey + R

*Type services.msc

*Search Postgres service based on the version installed.

*Click stop, start or restart the service option.

A: I had the same issue like Venkatesh had. But in my case I had installed pgadmin in version 9. But also installed version 12 at the same time.
When I now uninstalled version 9, the port was already set in the config of version 12 and not given free.
So my solution was to change the port of version 12 in the postgresql.conf file. Or even simplier, change the port in the server creation from 5432 to 5433. Now you are able to create a server again.

A: I got this same error. This happened when I uninstall and re-install postgress, for some reason after second-time installation, pgadmin tries to connect to the server on port 5433 whereas the server is running on 5432.
Rightclick server properties and change the port to 5432 and try to connect again. It should work now.

A: Your server running on port 5432 but in the properties, the port is set to 5433.
You must go to pgAdmin, click on database version, ex: PostgresSQL 10 and edit properties.
A new window appears and you need to change the port to 5432 [this is default port].
Hope this helps.


text:
Q: The concept about jquery and javascript I was a beginner in JavaScript and jQuery.
here is my question
var a = $("selector").height(); // or other methods

if I would like to change the height of this element to "b"
why should I write the $("selector").height("b"); instead of "a = b"??

A: That's the difference between setters and getters, as another programming language.
$(selector).height() returns the height of selector, so is a getter.
$(selector).height("90") sets a height of 90px, so is a setter.
When you make var a = $(selector).height() you are storing the height of the selector to the a variable.

A: When you write var a = $("selector").height();, you are assigning the value of the height method call to the variable a.
You are not in any way creating a link to the actual height via the variable a.  This is why you cannot say a=100 where 100 is the new height.
You must use the method call $("selector").height(a), where a is a variable containing the numerical value of the height you require.

A: The $.fn.height method without any arguments is a getter that will return a number. You can add or subtract that number to your hearts content but it wont get you anywhere.
When you pass an argument it becomes a setter that will actually change the selected element.

A: Because b has to be attached to a jQuery object ($) in order to manipulate it in the DOM. making a = b simply equates the values. It does nothing to the DOM itself. You also need to remove the quotes from the "b" variable - otherwise you are passing the string "b" instead of the variable itself.
var b = 100;
$("selector").height(b);


text:
Q: Sum of all integers No, I'm not talking about $-\frac{1}{12}$.
I was talking with someone the other day, and they said that the sum of all integers, positive and negative, is zero because they all cancel each other out. Basically,
$$\cdots+(-3)+(-2)+(-1)+0+1+2+3+\cdots=0$$
I'm skeptical, given how infinity tends to never work the way I want it to, but I have no math to back this.
What I'm asking is this:
Is the sum of all integers 0?

A: When you see written $\sum\limits_{i=1}^{\infty} x_i$ this term has a sense only if the series of $x_i$ is converging of diverging towards $\infty$ or $-\infty$. If you write $$ ... + (-3) + (-2) + (-1) + 0 + 1 + ... = 0$$
this sum is actually not defined. What would be the term of your sum? You could write $\sum\limits_{i=1}^{\infty} i$ + $\sum\limits_{i=1}^{\infty} -i$ which gives you $\infty - \infty$ but this is not defined.

A: We model the concept of "infinite sum" by taking limits of finite sums. This model has the "flaw" that the value of an infinite sum will depend on the order we sum the terms (compared to finite sums, where the order doesn't matter). If you think the sum of all integers as
$$\lim_{n\to \infty} \sum_{i=0}^n (i-i)$$
then certainly the sum is equal to $0$, however, if you think this sum as
$$\lim_{n\to \infty} \left(\sum_{i=0}^n (i-(i+1))\right)$$
(All the integers appear as a sumand) then the sum is not zero!, The limit doesn't exist.

A: EDIT: Shoot. I just realized that the op wasn't asking about the -1/12. I can't figure out how to withdraw the answer. Oh well, what I posted is still relevant to the sums of infinite series.
The sum is undefined, as other respondents have noted. If I recall correctly, this is an example of what's called "Ramanajan Summation." There's a wiki article on that subject. I'm new to supplying answers, so I don't know if linking in from wikipedia is kosher.
Anyhoo, the Ramanajan sum is supposed to be a way of giving a value to an infinite sum in order to study the properties of the partial sums, but isn't (I think) meant to be taken too seriously as the sum of the entire series.
Technically, you're supposed to put a little notation after the sum to indicate that you're not using a regular sum. E.g.:
1+2+3+4+... = 1/12 (R)
where the "R" denotes Ramanajan summation.
Hope that helps...

A: Not really. It's not even a particularly well-posed question, to be honest. The problem is that most the usual suspects behind assigning values to divergent sums (like the statement that $1+2+3+\ldots=\frac{-1}{12}$) work on sums of the form:
$$\sum_{i=1}^{\infty}s_i$$
for some sequence $s_i$. Why is this a problem? Well, they simply can't handle it if your series extends infinitely in both directions.
Okay, we could try to work around it by asking about
$$0+1-1+2-2+3-3+4-4+\ldots$$
though I'm not sure what techniques might handle such a sum. However, the trouble is that we could equally well ask about:
$$0+1+2-1+3+4-2+5+6-3+7+8-4+\ldots$$
where we include two positive terms for each negative one - and we'll probably get a different answer. So what order are we supposed to choose?
To illustrate the point, we can use the usual pseudo-algebraic techniques, or something more rigorous (like a Cesaro summation) to assign the value $\frac{1}2$ to the sum:
$$0+1+0-1+0+1+0-1+0+1+0-1+0+1+0-1+\ldots$$
but, if we shuffle the zeros around to get the expression:
$$1-1+0+0+1-1+0+0+1-1+0+0+1-1+\ldots$$
we end up assigning a different sum ($\frac{1}4$), despite the terms being the same. So we have some pathological behavior based on the ordering - which is troubling, because if we have no canonical order (i.e. we want to sum the set $\mathbb Z$, not some enumeration of it), we have no reason to think we can't order it so as to convince our method to spit out whatever number we want!
Sadly, the notion of summing a set is, almost exclusively, a measure theoretic concept applying to only absolutely convergent series - it doesn't even work on conditionally convergent series, let alone divergent ones. Worse, other techniques tend to want to examine a generating function, but they're not bidirectional unless we start talking about coefficients of $x^{-1}$ and so on (which we could do, but wouldn't be as useful as usual, since the main advantage of such a generating function is being able to work with the series near $0$, but we just plopped a singularity there...)

A: It is generally considered that the series
$$ 1 - 1 + 1 - 1 + 1 - 1 \pm \cdots$$
does not converge, since the partial sums alternate between $1$ and $0$
forever.
Even if you suppose that it's OK to rewrite a double-ended sum by taking
terms alternately in each direction,
you do not get a better result by summing
$$ 0 + 1 - 1 + 2 - 2 + 3 - 3 + 4 - 4 \pm \cdots.$$
You could put parentheses around pairs of terms and pretend
that both of these series are the same as
$ 0 + 0 + 0 + \cdots,$
but they are not.
You can try rearranging the positive and negative integers in
any sequence you like; none of it is going to stop the series from
eventually taking larger and larger steps up or down with each new
partial sum.

A: Certainly $\sum\limits_{n = -\infty}^\infty n$ is divergent because for each positive integer $N$,  $\sum\limits_{n = -2N}^{2N+1} n = 2N+1  \ge 2$.
It appears that the person you spoke with interpreted $\sum\limits_{n = -\infty}^\infty n$ as $\lim\limits_{n\to \infty} \sum\limits_{i = -n}^n i$, in which case the sum will be zero. However, this is incorrect. A bi-infinite series $\sum\limits_{n = -\infty}^\infty a_n$ converges if the double sequence
$$A_{m,n} := \sum\limits_{i = -m}^n a_i$$
converges. Note $m$ is independent of $n$. When $a_i = i$, we have $A_{2N,2N+1} \ge 2$ for all $N\in \Bbb N$, by the statement made above. This implies that the double sequence $A_{m,n}$ is unbounded, hence divergent. So $\sum\limits_{n = -\infty}^\infty n$ is divergent.
However, if you know a priori that a bi-infinite series $\sum\limits_{n = -\infty}^\infty a_n$ converges, then you can claim that the sum of the series is $\lim\limits_{n\to \infty}\sum\limits_{i = -n}^n a_i$.


text:
Q: How to write an idempotent file update in a Bash script? I am writing a bash script that will update a configuration file. Right now it simply moves the file into place:
if [ ! -e /path/to/file.conf ]; then
  mv file.conf /path/to/file.conf
fi

However, now I realize that I may want to make changes to that file in the future, so a simple move won't work if the file is already there. How do I write this so that the file is updated with the right contents in a way that allows me to execute the same script multiple times (idempotent)?

A: Consider:
if cmp -s file.conf /path/to/file.conf
then : OK - identical
else mv /path/to/file.conf /path/to/file.conf.$(date +%Y%m%d.%H%M%S)
     mv file.conf /path/to/file.conf
fi

That preserves a dated copy of the previous version of the configuration file, which makes it easier to rollback if something goes wrong.  There are other, arguably better, ways to handle that.  The trouble is that it dates the configuration file with when it was replaced, not when it was created.
So, an alternative is:
if cmp -s file.conf /path/to/file.conf
then : OK - identical
else now=$(date +%Y%m%d.%H%M%S)
     mv file.conf /path/to/file.conf.$now
     rm /path/to/file.conf
     ln -s /path/to/file.conf.$now /path/to/file.conf
fi

This leaves you with a symlink called /path/to/file.conf that points to a dated version of the configuration file — at the time it was created.  You can remove the symlink and put in a different version at any time, or change it to point to an older version without necessarily removing the newer version, etc.


text:
Q: refresh rate for gyroscop and accelerometer [ mpu6050 ] What is refresh rate ( update rate) for gyroscop and accelerometer ? If you write in the register the following values in mpu6050 :
SMPLRT_DIV --> 19
CONFIG --> 2 ( DLPF off )

A: I would suggest the first thing is to look at the register map of MPU6050 ( that is mostly named as register map MPU6000)
According to the formula given in the CONFIG register description
Sample Rate = Gyroscope output rate / (1+SMPLRT_DIV)
Over here you have chosen Gyroscope rate as 1KHz , hence your sample rate comes to 50 Hz   i.e 50 Samples per second.


text:
Q: Adding a condition to the showcase The task is as follows. I have a code that has a huge number of attributes. And to one of the attributes, let's say this is the card type card_type='universal', you need to add the following condition:
case when card>='129897' and card<='293965'then 'unnamed' and card>='093750' and card <='903750' then 'personal' end as parameter
The attribute itself is as follows :select case when card_sybtype in ('VISA','MS') then 'universal'
At the same time, I do not need to output this to the final script, but I need this feature to be present in the script. That is, I need it to be linked only to the card type.

A: I think you can use a nested case when.
And if you dont want to select parameter column, you can use a subquery to hide the columns. So, in case you want it, just add it to the outside select list.
SELECT col1, col2
FROM
(SELECT
col1, col2,
case when card_sybtype in ('VISA','MS')  THEN -- universal case
         case when card>='129897' and card <='293965' then 'unnamed'
              when card>='093750' and card <='903750' then 'personal' end
     else null
end as param_adhoc
FROM tab
) rs


text:
Q: Connect the same signal from several widgets to the same function in PyQt? Well, i have this app which has a lot o lineEdit widgets on it (more than 20 actually). And on the end of it, i have another lineEdit that is supposed to show the sum of the values on the other widgets. But, I would like to make it update that sum everytime some value is changed, using the "textEdited()" signal. I know i can to this connecting all those widgets' signals to the function that makes the sum, but I guess that there must be another way to get this done so that this amount of repeated code isn't necessary. Am I right?
Does anyone know how to do this?
Thanks in advice.

A: You already gave the answer yourself: You have to connect your sum function to every QLineEdit's textEdited() signal.  You can do this with very little code when you store all those widgets in a Python list:
# ...append all line edits to this list:
line_edits = []

for le in line_edits:
  le.textChanged.connect(self.mySumFunction)

This also has the advantage that you can re-use the list if you ever need to edit/enable/disable/clear/... all line edits at the same time.


text:
Q: Systemd custom service not start at boot Ubuntu 16.04
In the terminal this command is ok:
sudo systemctl start TestSM.service

the service works in manual start, but not start at boot.
Systemd service details:
[Unit]
Description=inotify

[Service]
ExecStart =/home/test/inotifySendMM

[Install]
WantedBy = multi-user.target

This is the error in boot log ( journalctl -b):
ubuntuVM systemd[1010]: TestSM.service: Failed at step EXEC spawning /home/test/inotifySendMM: No such file or directory


text:
Q: Is $l^2$ really a generalized Euclidean space? Sorry for kind of clickbait title, but I am very interested in $l^2$ space - space of all square-summable (and ths convergent) sequences.
First, since I have read that $l^2$ is (with a pinch of salt) something like generalized Euclidean space or "sum of real lines" (really large sum though) - how can we really relate $l^2$ spaces and Euclidean spaces, particularly $\mathbb{R}$ or $\mathbb{R^n}$? Can we really say statements like that?
Second, how does the "standard" topology on $l^2$ look like? Can we deliver it somehow from Euclidean standard topology?
Third, how are Hilbert spaces related to Euclidean generally? (Since $l^2(E)$ is isometric to any other Hilbert spaces, as I already asked about here).
I hope these questions are not too ambiguous - I am always interested in intuition more than the technical stuff). I can try to make them more precise.
Thank you for your insights.

A: The linear $\ell^2$ has infinite sequences as vectors, namely precisely those that are square summable so that $\sum_{i=0}^\infty x_i^2$ converges and this value being finite allows us to define a norm $\|x\|_2 = \sqrt{\sum_{i=0}^\infty x_i^2}$ which has the usual properties of a norm, like we know it from the Euclidean norm on $\Bbb R^n$. We can embed $\Bbb R^n$ into $\ell^2$ by $(x_1, \ldots, x_n) \to (x_1, \ldots x_n, 0,0,0,\ldots)$ and we have an isometry, so the finite Euclidean spaces sit nicely inside this $\ell^2$. It also has an inner product (so we can talk about orthogonal vectors and such geometric concepts; we can define angles between vectors as usual etc.). The topology is also induced by the metric from this norm as $d(x,y)= \|x-y\|_2$ etc. It's also separable and complete like $\Bbb R^n$ is and locally convex, path-connected and all such nice things.
But in infinite dimensional spaces things do behave differently: no compact set can have a non-empty interior (so no local compactness) and if $K$ is compact (or even $\sigma$-compact) it can be shown that $\ell^2 \simeq \ell^2\setminus K$, in stark contrast with $\Bbb R^n$ where even removing a point leaves us with a non-homeomorphic result... The book about infinite-dimensional topology by Bessaga and Pelczynski is a classic intro to such facts.


text:
Q: How to install a arbitrary version of iOS on iPhone? I have to develop an app for a specific version of iOS (I am just a freelancer, doing what I am told).
How I install iOS 8.2, or below (8.1, 7.x are fine too) on an iPhone 4S?

A: There's no official way of installing an older iOS on a device that Apple has stopped signing the SHSH keys for.
Your best bet is either to get a hold of a device that still has an older iOS or just using a simulator when developing the app.

A: Short answer, you don't.
Apple will only sign the current OS, or in the case of a device incapable of running the current OS, the latest it supports.
There are no models that support iOS 8 that don't also support up to 8.4.1 [& even the coming iOS 9]