text:
Q: Casting comma separated string to integer to be used in "IN" SQL I pass a comma separated numbers as string to a stored procedure, the parameters are used in IN keyword, however when I execute the SP (with parameters like "1,2") it gives me an error:

Conversion failed when converting the varchar value '1,2' to data type
  int.

The stored procedure is:
ALTER PROCEDURE [Reports].[LocationSummary]
    @dtFrom VARCHAR(MAX),
    @dtTo VARCHAR(MAX),
    @passTypeId VARCHAR(MAX),
    @passCategoryId VARCHAR(MAX),
    @passTransId VARCHAR(MAX),
    @printOption VARCHAR(MAX),
    @printLocationId VARCHAR(MAX)
AS
BEGIN
    SELECT Admins.PLocations.ArabicName AS PLocationA,
           Admins.PLocations.EnglishName AS PLocationE,
           SUM(CASE WHEN Port.Info.Printed = 1 THEN 1 ELSE 0 END) AS Printed,
           SUM(CASE WHEN Port.Info.Printed = 0 THEN 0 ELSE 1 END) AS NotPrinted,
           SUM(CASE WHEN Port.PortPrintLog.PortId IS NOT NULL THEN 1 ELSE 0 END) AS Reprinted

    FROM Port.Info INNER JOIN
           Port.PortRequests ON
           Port.Info.PassRequestId = Port.PortRequests.ID LEFT JOIN
           Port.PortDefinitions ON
           Port.PortRequests.PassDefinitionID = Port.PortDefinitions.ID INNER JOIN
           Admins.PortCategories ON
           Port.PortDefinitions.PassCategoryId = Admins.PortCategories.ID INNER JOIN
           Admins.PortTypes ON
           Port.PortDefinitions.PassTypeId = Admins.PortTypes.ID  INNER JOIN
           Admins.PortTransactionTypes ON
           Port.PortDefinitions.PassTransactionTypeId = Admins.PortTransactionTypes.ID INNER JOIN
           Admins.PLocations ON
           Port.Info.PrintLocationID = Admins.PLocations.ID LEFT JOIN
           Port.PortPrintLog ON Port.PortPrintLog.PortId = Port.Info.ID

    WHERE
         (@dtFrom IS NOT NULL AND Port.PortRequests.IssuanceDate IS NOT NULL AND Port.PortRequests.IssuanceDate >= @dtFrom)
         AND (@dtTo IS NOT NULL AND Port.PortRequests.ExpiryDate IS NOT NULL AND Port.PortRequests.ExpiryDate <= @dtTo)
         AND ((Admins.PortTypes.ID IN (CAST(@passTypeId AS INT)))
         AND (Admins.PortCategories.ID IN (CAST(@passCategoryId)))
         AND (Admins.PortTransactionTypes.ID IN (CAST(@passTransId)))
         AND (Port.Info.PrintLocationID IN (CAST(@PrintLocationId AS INT))))

    GROUP BY Admins.PrintLocations.ArabicName, Admins.PrintLocations.EnglishName

How can I avoid that error? should I use a function to Split the string? Can I see some example for that function?

A: @jyparask has given dynamic query , you can use that otherwise try to implement following logic. you have more then one column otherwise i have done the changes.
Declare @var1 as varchar(2000)
Declare @var2 as varchar(2000)
Set @var1 = '31,39,41,45'
Set @var2 = ',' + @var1 + ','
select * from Table1 Where Charindex(','+cast(Col1 as varchar)+',', @var2) > 0

A: You may have a dynamic sql:
ALTER PROCEDURE [Reports].[LocationSummary]
    @dtFrom VARCHAR(MAX),
    @dtTo VARCHAR(MAX),
    @passTypeId VARCHAR(MAX),
    @passCategoryId VARCHAR(MAX),
    @passTransId VARCHAR(MAX),
    @printOption VARCHAR(MAX),
    @printLocationId VARCHAR(MAX)
AS
    DECLARE @SQL AS VARCHAR(MAX)
    SET @SQL =
    'SELECT Admins.PLocations.ArabicName AS PLocationA,
           Admins.PLocations.EnglishName AS PLocationE,
           SUM(CASE WHEN Port.Info.Printed = 1 THEN 1 ELSE 0 END) AS Printed,
           SUM(CASE WHEN Port.Info.Printed = 0 THEN 0 ELSE 1 END) AS NotPrinted,
           SUM(CASE WHEN Port.PortPrintLog.PortId IS NOT NULL THEN 1 ELSE 0 END) AS Reprinted

    FROM Port.Info INNER JOIN
           Port.PortRequests ON
           Port.Info.PassRequestId = Port.PortRequests.ID LEFT JOIN
           Port.PortDefinitions ON
           Port.PortRequests.PassDefinitionID = Port.PortDefinitions.ID INNER JOIN
           Admins.PortCategories ON
           Port.PortDefinitions.PassCategoryId = Admins.PortCategories.ID INNER JOIN
           Admins.PortTypes ON
           Port.PortDefinitions.PassTypeId = Admins.PortTypes.ID  INNER JOIN
           Admins.PortTransactionTypes ON
           Port.PortDefinitions.PassTransactionTypeId = Admins.PortTransactionTypes.ID INNER JOIN
           Admins.PLocations ON
           Port.Info.PrintLocationID = Admins.PLocations.ID LEFT JOIN
           Port.PortPrintLog ON Port.PortPrintLog.PortId = Port.Info.ID

    WHERE
         (@dtFrom IS NOT NULL AND Port.PortRequests.IssuanceDate IS NOT NULL AND Port.PortRequests.IssuanceDate >= @dtFrom)
         AND (@dtTo IS NOT NULL AND Port.PortRequests.ExpiryDate IS NOT NULL AND Port.PortRequests.ExpiryDate <= @dtTo)
         AND ((Admins.PortTypes.ID IN (' + @passTypeId + '))
         AND (Admins.PortCategories.ID IN (' + @passCategoryId + '))
         AND (Admins.PortTransactionTypes.ID IN (' + @passTransId + '))
         AND (Port.Info.PrintLocationID IN (' + @PrintLocationId + ')))

    GROUP BY Admins.PrintLocations.ArabicName, Admins.PrintLocations.EnglishName'

    EXEC (@SQL)

A: ALTER PROCEDURE [Reports].[LocationSummary]
    @dtFrom VARCHAR(MAX),
    @dtTo VARCHAR(MAX),
    @passTypeId VARCHAR(MAX),
    @passCategoryId VARCHAR(MAX),
    @passTransId VARCHAR(MAX),
    @printOption VARCHAR(MAX),
    @printLocationId VARCHAR(MAX)
AS
BEGIN
    SELECT Admins.PLocations.ArabicName AS PLocationA,
           Admins.PLocations.EnglishName AS PLocationE,
           SUM(CASE WHEN Port.Info.Printed = 1 THEN 1 ELSE 0 END) AS Printed,
           SUM(CASE WHEN Port.Info.Printed = 0 THEN 0 ELSE 1 END) AS NotPrinted,
           SUM(CASE WHEN Port.PortPrintLog.PortId IS NOT NULL THEN 1 ELSE 0 END) AS Reprinted

    FROM Port.Info INNER JOIN
           Port.PortRequests ON
           Port.Info.PassRequestId = Port.PortRequests.ID LEFT JOIN
           Port.PortDefinitions ON
           Port.PortRequests.PassDefinitionID = Port.PortDefinitions.ID INNER JOIN
           Admins.PortCategories ON
           Port.PortDefinitions.PassCategoryId = Admins.PortCategories.ID INNER JOIN
           Admins.PortTypes ON
           Port.PortDefinitions.PassTypeId = Admins.PortTypes.ID  INNER JOIN
           Admins.PortTransactionTypes ON
           Port.PortDefinitions.PassTransactionTypeId = Admins.PortTransactionTypes.ID INNER JOIN
           Admins.PLocations ON
           Port.Info.PrintLocationID = Admins.PLocations.ID LEFT JOIN
           Port.PortPrintLog ON Port.PortPrintLog.PortId = Port.Info.ID

    WHERE
         (@dtFrom IS NOT NULL AND Port.PortRequests.IssuanceDate IS NOT NULL AND Port.PortRequests.IssuanceDate >= @dtFrom)
         AND (@dtTo IS NOT NULL AND Port.PortRequests.ExpiryDate IS NOT NULL AND Port.PortRequests.ExpiryDate <= @dtTo)
         AND Admins.PortTypes.ID IN (@passTypeId)
         AND Admins.PortCategories.ID IN (@passCategoryId)
         AND Admins.PortTransactionTypes.ID IN (@passTransId)
         AND Port.Info.PrintLocationID IN (@PrintLocationId)

    GROUP BY Admins.PrintLocations.ArabicName, Admins.PrintLocations.EnglishName

casting to int will cause an error while passing 1,2 in parameter. do not cast it.

A: Make sure there are spaces in your comma separated list:
(1,2)

is not the same as
(1, 2)


text:
Q: Dynamic "Favorite" button - ASP.NET MVC I have created a table which dynamically generates records using the "Infinite Loading" process, I have a button in my HTML Code which i need to use to allow users to add the item in their favourite - so this is my HTML code
@model List<PagesAuth.Models.Links.MLink>

@foreach (var I in Model)
{

                @I._title
                @I._tp_created.ToString("dd MMM yyyy") /small>

                    @if (I._tp_favourite == 0)
                    {

<button class="btn-link glyphicon glyphicon-heart-empty" onclick="location.href='@Url.RequestContext .Action("_Fav", "Home", "@I._id")'"></button>

                    }
                    else
                    {

<button class="btn-link glyphicon glyphicon-heart-empty" onclick="location.href='@Url.RequestContext .Action("_UnFav", "Home", "@I._id")'"></button>

                    }

}

I am trying to use "Favourite" button to allow user to add that website to their favourite list (I am ok with the DB updates etc)

                    @if (I._tp_favourite == 0)
                    {

<button class="btn-link glyphicon glyphicon-heart-empty" onclick="location.href='@Url.RequestContext .Action("_Fav", "Home", "@I._id")'"></button>

                    }
                    else
                    {

<button class="btn-link glyphicon glyphicon-heart-empty" onclick="location.href='@Url.RequestContext .Action("_UnFav", "Home", "@I._id")'"></button>

                    }

*

*What I want to know is how to achieve this on user front-end - Like I thought I should just create a PartialView and make it child action only in my controller, send it ID and do DB Processing
[ChildActionOnly]

public ActionResult _Fav(int ID)

{//Do DB Processing

    return PartialView(ID);

}

First of all the following does not work
onclick="location.href='@Url.RequestContext .Action("_UnFav", "Home", "@I._id")'"

Second, if I end up making this work, it will still refresh the page and I don't want that.
Is there a better way to achieve this
Cheers

A: I don't know why you want to use partial views but you can do it this way.

*

*Use ajax to send request to controller action.

*Handle action result using JavaScript.

View:
@model List<PagesAuth.Models.Links.MLink>

@foreach (var I in Model)
{

                @I._title
                @I._tp_created.ToString("dd MMM yyyy") /small>

                    @if (I._tp_favourite == 0)
                    {

<button class="btn-link glyphicon glyphicon-heart-empty" onclick="Fav(@I._id)"></button>

                    }
                    else
                    {

<button class="btn-link glyphicon glyphicon-heart-empty" onclick="UnFav(@I._id)"></button>

                    }

}

JS:
Here I am just alerting that the favorite action succeeded, else you have an array of string errors to work with. You could redirect or do some stuff, whichever you prefer.

Controller:
[HttpPost]
public ActionResult _Fav(int ID)
{
    List<string> errors = new List<string>(); // You might want to return an error if something wrong happened

    //Do DB Processing

    return Json(errors, JsonRequestBehavior.AllowGet);
}

[HttpPost]
public ActionResult _UnFav(int ID)
{
    List<string> errors = new List<string>(); // You might want to return an error if something wrong happened

    //Do DB Processing

    return Json(errors, JsonRequestBehavior.AllowGet);
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Best Practises for syncing remote server and local machines in Laravel 4.2 I have been doing Laravel for a couple of years now. Currently, I am managing a system with Laravel 4.2
There are two parts for this project:

*

*Local Offline Systems with Apache running locally. This project is for rural Nepal. Thus, internet is not readily available all the time.

*A Central server that receives & stores data whenever local systems are connected to the internet.

Data that need to be transferred include MYSQL Table Data and images.
I have completed coding and testing the system in local machines. However, I am looking for the best ways to sync data to the server on click of a button i.e. whenever a SYNC button is pressed, all data should be securely synced to the central server. I am dealing with sensitive data and would like to prevent any sort of loss of data.
Thanks in advance!


text:
Q: jquery .add() is weird Why all elements turn red? I only intend to turn
 red.

list item 1

list item 2

list item 3

a paragraph

A: $('li') is selection all the li
$('li').add('p') is adding p tag into selected all the li
$('li').add('p').css('background-color', 'red') is changing all the li and p backgroundColor to red.
from jQuery.add API

Given a jQuery object that represents
  a set of DOM elements, the .add()
  method constructs a new jQuery object
  from the union of those elements and
  the ones passed into the method. The
  argument to .add() can be pretty much
  anything that $() accepts, including a
  jQuery selector expression, references
  to DOM elements, or an HTML snippet.

A: jQuery chains events, what you have said here is For each li add a p and make it red.
$('li').add('p');
$('li p').css(''background-color', 'red');

Should work =0)

A: this actually says give me all the li's, add all the p's, and then make them red in the background. if you just want the p tag to be red, do this:
('p').css('background-color', 'red');


text:
Q: Getting any AudioPlayer to stream or play music Bit at a loss here. I am on Xcode 7 and Swift 2 and I am trying to find and example of streaming audio that actually works.
Essentially I want to be able to stream, but I also tried this: Swift Radio Streaming AVPlayer
Which uses AVAudioPlayer. The github code works, but copying the code into my project with the same audio file crashes the app : Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[SwiftBasicMVC_Git.AudioStreamProxy copyWithZone:]: unrecognized selector sent to instance 0x14fdea100'
I also tried some ACPlayer examples and AVQueuePlayer, without success of playing any music.

A: I use singleton for my basic radio application because need to reach and handle it on every page. It's so simple to create, let's start with declare singleton and variables. I will explain everything step by step;
import AVKit
import AVFoundation

private var radioContext: UInt8 = 1

final class RadioModel: NSObject {

    dynamic var radioItem:AVPlayerItem? = nil
    dynamic var radioPlayer:AVPlayer? = nil
    static let sharedModel = RadioModel()
    private final let dataModel = BasicRadioApp.DataManager

    private override init() {
        super.init()

        do {
            _ = try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
            _ = try AVAudioSession.sharedInstance().setActive(true)
            UIApplication.sharedApplication().beginReceivingRemoteControlEvents()
        } catch {
            print("Error")
        }
    }

If you want to use AirPlay mode for podcast or radio, you have to control your sound object with KVO (Key Value Observer) and it's not supporting for Swift. So, our AVPlayerItem and AVPlayer objects are defined by dynamic which means that according to documentation;

Apply this modifier to any member of a class that can be represented by Objective-C. When you mark a member declaration with the dynamic modifier, access to that member is always dynamically dispatched using the Objective-C runtime. Access to that member is never inlined or devirtualized by the compiler.
Because declarations marked with the dynamic modifier are dispatched using the Objective-C runtime, they're implicitly marked with the objc attribute.

I'm getting data from server in my other Singleton object BasicRadioApp.
I need to control my audio session interacts with others (etc. Apple Watch) so need to set your AVAudioSessionCategory. Also i want to remote my audio on lockscreen and Glance in Apple Watch music app.
In AVAudioSession class, this function declared like that;
/* set session category */
    public func setCategory(category: String) throws

As you see, they throw exception so you need to set them in error handling like do/try concept for >Swift 2.0.
Let's try to play sound;
final func playRadio() {

         do {
                try removeObserverFromRadioItem()
            } catch {
                print("Can not remove observer from AVPlayerItem object!")
            }

            radioItem = AVPlayerItem(URL: NSURL(string: dataModel.radioStreamUrl)!)
            radioPlayer = AVPlayer(playerItem: radioItem!)
            radioItem!.addObserver(self, forKeyPath: "status", options: [.New, .Initial, .Old], context: &radioContext)

        if MPNowPlayingInfoCenter.defaultCenter().nowPlayingInfo == nil {

            let albumArt = MPMediaItemArtwork(image: UIImage(named: "AlbumArt")!)
            let songInfo: Dictionary = [MPMediaItemPropertyTitle: "Now listening Hard Rock Bla Bla FM",
                MPMediaItemPropertyArtist: "My Radyo",
                MPMediaItemPropertyAlbumTitle: "105.5 FM",
                MPMediaItemPropertyArtwork: albumArt]

            MPNowPlayingInfoCenter.defaultCenter().nowPlayingInfo = songInfo
        }
    }

Before declaring my AVPlayerItem, i need to remove KVO on it if it exist. You'll see what removeObserverFromRadioItem() is doing next. I need to register my AVPlayerItem to KVO object and it'll handle to play or not. As i said, i need to remote my audio on lockscreen so i'm using MPNowPlayingInfoCenter for that.
final func stopRadio() {
        MPNowPlayingInfoCenter.defaultCenter().nowPlayingInfo = nil
        radioPlayer?.pause()
    }

final func removeObserverFromRadioItem() throws {
        radioItem?.removeObserver(self, forKeyPath: "status", context: &radioContext)
    }

The most important part is here;
override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        if object as? AVPlayerItem == radioPlayer?.currentItem && keyPath! == "status" {
            if self.radioPlayer?.currentItem!.status == .Failed {
                print("STREAM FAILED")
            } else if self.radioPlayer?.currentItem!.status == .ReadyToPlay {
                self.radioPlayer!.play()
                radioDelegate?.RadioDidStartPlay()
            }
            return
        }
        super.observeValueForKeyPath(keyPath, ofObject: object, change: change, context: context)
    }

How do you start your radio from any class?
class RadioController: UIViewController {

    let sharedRadioPlayer = RadioModel.sharedModel
    ..

override func viewDidLoad() {
        super.viewDidLoad()

        // check if radio is NOT playing
        if sharedRadioPlayer.radioPlayer?.rate < 1 {
            sharedRadioPlayer.playRadio()
        }
    }

Last step is remote my app from lockscreen. Stop, play etc.
For remote that, i'm calling my method in RadioModel from AppDelegate. In AppDelegate;
override func remoteControlReceivedWithEvent(event: UIEvent?) {
        RadioModel.sharedModel.handleRemoteControlEvent(event!)
    }

and in RadioModel;
func handleRemoteControlEvent(responseEvent: UIEvent) {
        if responseEvent.type == UIEventType.RemoteControl {
            switch(responseEvent.subtype) {
            case UIEventSubtype.RemoteControlPlay:
                playRadio()
                break
            case UIEventSubtype.RemoteControlPause:
                stopRadio()
                break
            case UIEventSubtype.RemoteControlTogglePlayPause:
                if self.radioPlayer!.rate > 0 {
                    stopRadio()
                } else {
                    playRadio()
                }
                break
            default:
                print("Remote Error")
            }
        }
    }

Don't forget that in your app TARGETS > Capabilities > switch Background Modes on and select Audio, AirPlay and Picture in Picture. Then check your info.plist and search "Requires background modes". If it's not exist, create new one as Array and set item that "App plays audio or streams audio/video using AirPlay". That's it now you can play airPlay radio/stream.

A: DONT forget to add : App Transport Security Settings
As of XCode 7.x AND iOS 9.x
Needed in the pList settings : Add Arbitrary as YES


text:
Q: Vim auto indent large array litterals I'm faced with the problem of ugly-looking lists on several lines for which the lines do not have the same length.
Here take this example:
    voxels = [[90, 90,    90],
              [110, 110, 110],
              [40, 40,    40],
              [100, 100, 100],
              [50, 50,    50],
              [25, 25,    25],
              [10, 10,    10]]
    cords = [[-5.141, -114.9, 181.8],
             [-27.71, -99.95, 169.4],
             [51.29, -152.3, 213],
             [-16.43, -107.4, 175.6],
             [40, -144.8, 206.8],
             [68.21, -163.5, 222.3],
             [85.14, -174.7, 231.7]]

voxels list is corretly formatted but cords is not.
Couldn't find any vim tool that does this, any ideas on how to get this done?

A: You can try the Tabular plugin; once installed, go to the line starting with cords =, then run the following command (the end of the command may be different giving your own taste, see the plugin's help):
:.,.+6Tabularize /,/l0l1

This should give the following result:
cords = [[-5.141, -114.9, 181.8] ,
         [-27.71, -99.95, 169.4] ,
         [51.29 , -152.3, 213]   ,
         [-16.43, -107.4, 175.6] ,
         [40    , -144.8, 206.8] ,
         [68.21 , -163.5, 222.3] ,
         [85.14 , -174.7, 231.7]]


text:
Q: Динамический массив рандомными числами на СИ Не получается заполнить рандомно динамический массив.
//include library
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <cmath>
#include <ctime>

void createMatrix(int** array, int row, int col)
{
    int i;
    array = (int **) malloc(row * sizeof(int*));
    for (i = 0; i < row; i++)
        array[i] = (int*) malloc(col * sizeof(int));
}
void randomizeMatrix(int** array, int row, int col){
    int i, j;
    for (i=0; i< row; ++i)
        for (j=0; j<col; ++j)
            array[i][j]=rand()%100;
}
void printMatrix(int** array, int row, int col){
    int i, j;
    for (i=0; i< row; ++i)
    {
        for (j=0; j<col; ++j)
            printf("%i ",&array[i][j]);
        printf("\n");
    }
}
int main(){
    srand(time(NULL));
    int row, col;
    printf ("Enter count row: ");
    scanf("%i",&row);
    printf ("Enter count col: ");
    scanf("%i",&col);

    int** M1;

    createMatrix(M1, row, col);
    randomizeMatrix(M1, row, col);
    printMatrix(M1, row, col);

    return 0;
}```

A: Правильно написал @Harry . Из функции createMatrix(int** array, ) значение указателя после выделения памяти не возвращается в main, т.к. Вы передали указатель по значению. В итоге в следующую функцию передается указатель, который указывает в никуда.
Предавайте или по ссылке, или по указателю, или возвращайте значение:
// передача по ссылке
void createMatrix(int** &array, int row, int col) {}

// передача по указателю
void createMatrix(int*** array, int row, int col) {}

// возврат значения
int** createMatrix(int row, int col) {}
main()
{
  int** A = createMatrix( 3, 3);
}


text:
Q: Sound doesnt work in newest kernel, but works in 2.6.33 kernel? When I install the 10.04 LTS Lucid Lynx kernel on my Ubuntu 12.04 LTS system, sound works fine.
But if I use newest kernel of 12.04, it shows my audio hardware but plays no sound.
I don't want use the old kernel, because I think I cannot use some software, including GNOME 3, with it. Or at least they didn't work when I tested the old kernel, and the screen resolution was low.
I also tried newer kernels but only 2.6.33 worked without any sound problems.
My sound card is a Realtek HD ATI ALC1200 integrated card. My front jack is broken and it detects that something is always plugged in--does this affect my situation?
Do I have to buy a new sound card? That would suck.

A: The original poster was able to solve the problem as follows (moved from being an edit to the question, to here):

I fixed this problem by going to alsamixer. There was this thing
  called "automute-mode" and it was enabled. By disabling it, my sound
  started working again. I think this had something to do with my broken
  front jack.


text:
Q: easiest way to automate all software installations for new users/computers? Basically, for every new user we have about 30 different installers that all need to be run manually after an install of windows which is tedious/time consuming.
We can't simply ghost/image the computers as they come because of the wide variety of hardware being used (all laptops). What would you suggest to run through all the installers automatically without requiring me to sit and click 'next'.. 'next'.. 'continue'.. 'no dont install msn toolbar please'?

A: I use a program called InstallPad. It's really easy to use and you can add them as silent installs and just start it and the program does the rest... only requirement is a place where all the programs are located. Can be network share usb drive or similar.

A: There are a number of ways to do this. Sysprep is a common choice for Windows machines. I prefer to use images (Ghost, Drive Image, etc.).
Either way, what you do is set up one machine the way you want, then either image or sysprep it and use that as your source for other machines.

A: You need to look at the command line install options for all those programs and write a batch file/script to run them in turn passing the appropriate option flags to each installer to get the results you want.

A: If you're interested in publicly available package like Firefox, Chrome, Trucrypt, Notepad++, etc. Look into Ninite. You can select what you want and it will run without any user action required.
They are technically free, with a paid corporate option. I use it for every new machine that we receive.

A: nlite to make your master gold install dvd - http://www.nliteos.com/
sysprep that image whenever possible to move it to different hardware.
since you are requesting a sysprep guide, I used this when I first started using sysprep and it worked like a champ - https://web.archive.org/web/1/http://articles.techrepublic%2ecom%2ecom/5100-22_11-5838633.html
clonezilla to move your syspreped image to new hardware - http://clonezilla.org/

A: You'll be surprised, but the variety of laptops doesn't matter much. This is because most of them, like 85%-90% have all the same INTEL/RTL network card, INTEL/VIA chipset, e.t.c. Extracting the drivers from machines is an easy task, again, variety of tools to extract drivers available on the net:
http://www.google.com/search?q=extract+drivers+from+windows&rls=com.microsoft:en-us&ie=UTF-8&oe=UTF-8&startIndex=&startPage=1
Some of them freeware. As previously advised, using SYSPREP with NLITE will be your best approach.


text:
Q: PLSQL: Change Data Capture to get modified records of a table We have a requirement wherein we have to migrate modified/delta data on a table from Oracle to MongoDb. To do this I have suggested to create Trigger on intended table and insert the Updated/Inserted/Deleted records into logging table and using Java code we will be able to read these modified/delta records and then update the respective collections in MongoDB.
But I have been asked to check the feasibility of Oracle's CDC (Change Data Capture) feature.
I have checked Oracle doc to learn CDC but it takes quite a time. Could you please help me with some steps or any quick tutorial to implement CDC to capture modified data on a table as I have to create a demo.
Also please suggest which will be better from performance point of view to log modified/delta records using trigger or CDC.

A: Don't waste your time on Change Data Capture.  It's an interesting idea but unfortunately CDC is desupported in 12c.  And not desupported like the way IMP and EXP are not supported but will still work forever.  It's been completely removed from the database.  Oracle corporation wants you to pay for Oracle GoldenGate instead.


text:
Q: how can i display a value which is retrieved from the back end in all the pages of my application I'm using JSF 2.0 and jsp as views instead of facelets.
I have a registration form, which on success returns a registration number, which i want to display it as a popup. and also i want to display this num in each of my page when and where required.
How can I achieve this?

A: Keep the registration number in session for further use.popup can displayed using JavaScript in your jsp page.


text:
Q: Need help passing defined C constants to asm instruction I have the following code in a C program for a ATmega microcontroller:
define sbi(port,bit) asm("SBI " #port "," #bit)
[...]
sbi(PORTB,1);

The problem is that the compiler does not recognize PORTB when it's processing the assembly code, despite being defined in an included header file. Is there a way to tell the precompiler to put the defined value of PORTB (0x1b) in the ASM instruction rather than the literal text PORTB? The assembly instruction works fine when I manually do this like so:
sbi(0x1b,1);

But for obvious reasons I'd like to be able to use PORTB and other defined names in my C code.
Please note, I'm only using this ASM macro for defined constants, not variables, so I don't need anything too fancy to bridge between my ASM macro and my C code. I just need the preprocessor to replace PORTB with 0x1b in the ASM string.

A: You generally should not use stringification (the macro # operator) to construct strings for the asm construct. Instead, use the extended asm syntax.
To put operands into assembly instructions, use that syntax with constraints that tell the compiler how it may give the operands to the instructions. For immediate operands, use i:
asm("SBI %[port], %[bit]"
    : // Output operands would be here.
    : // Input operands are here.
        [port] "i" (PORT),
        [bit]  "i" (1)
);

The %[port] in the instruction string is replaced by the operand named port. The [port] in the operand list later on says the name of that operand is port. Of course this matches PORT except for the case, but you can use other names.
The "i" says to use an immediate operand, which must have a compile-time constant value.
The PORT in (PORT) is an expression that gives the value to use for the operand. For example, you could also use (PORT+1).
The 1 operand could be hard-coded, but the above shows how to keep it flexible.
For a default immediate operand with i, GCC and Clang include the punctuation that marks an immediate operand in assebmly code, such as $ in some assemblers. If this is a problem for some reason, you can use %c[port] instead of %[port] to get the bare operand, and insert the # manually, as with:
asm("SBI #%c[port], #%c[bit]"
    : // Output operands would be here.
    : // Input operands are here.
        [port] "i" (PORT),
        [bit]  "i" (1)
);


text:
Q: how to display message like "Record Already Exist" or "Error Happen" in Alertbox I am using kendo ui grid view and also use inline editing in NopCommerce.
now i want to check exist(for only one field) or not and if exist then not insert record in table this thing working fine.
but no any message display like "Record Already Exist" or "Error Happen".
and i see code of language resource string gird view and its working fine but i am not understand how to fire alert and display message as well.
please help me

A: There was a bug in nopCommerce 3.30 which did not properly display this error (fixed in the upcoming version 3.40).
You can return an error text the following way for grids:
return Json(new DataSourceResult() { Errors = "Your error text here" });


text:
Q: AWS Amplify migrate GraphQLTransformer to V2 I recently added the @index annotation to my GraphQL schema in my Amplify backend and am now getting the following error:
SchemaValidationError: Your GraphQL Schema is using "@index" directive from the newer version of the GraphQL Transformer
I've followed the migration guide referenced in the error: https://docs.amplify.aws/cli/migration/transformer-migration/ but it doesn't actually indicate how to perform the migration itself

A: The GraphQL Transformer version is managed in amplify/cli.json
You simply need to edit the file and set the following two properties:
  "features": {
    "graphqltransformer": {
      ...
      "useexperimentalpipelinedtransformer": true,
      "transformerversion": 2,
      ...
    },

From there you can do an amplify push or a amplify codegen models and assuming all changes referenced in the guide (https://docs.amplify.aws/cli/migration/transformer-migration/) have been catered for all will work.


text:
Q: Django: getting error NoReverseMatch for reverse Getting error:

NoReverseMatch: Reverse for 'single_view' with arguments '('article', 2013, 12, 12, 'triumphmotorcycleslaunched10newbikesinindia', 16)' and keyword arguments '{}' not found. 1 pattern(s) tried: [u'(P[article|review|blog|news|video])/(P\d{4})/(P\d{2})/(P\d{2})/(P\w+)/(P\d+)$']

Here is my URLConf, models and views
/urls.py
...
url(r'^(P<post_type>[article|review|blog|news|video])/', include('post.urls', namespace='post_views')),
...

/post/urls.py
urlpatterns = patterns('',
  url(r'^$', PostView.as_view(), name="index"),
  url(r'^(P<year>\d{4})/(P<month>\d{2})/(P<day>\d{2})/(P<slug>\w+)/(P<post_id>\d+)$', PostView.single, name="single_view")
)

and get_absolute_url in models.Post class
/post/models.py
def get_absolute_url(self):
    from django.core.urlresolvers import reverse
    return reverse('post_views:single_view', args=['article', 2013, 12, 12, str(self.slug).replace('-', ''), self.id])

and view
/post/views.py
def single(self, request, post_type, year, month, day, slug, post_id, *args, **kwargs):
    post_single = Post.objects.get(pk=1)

    context = {
        "post_single": post_single,
    }
    return self.render_to_response(context);

Resolver Error: Tried after @Yeo suggestion
from django.core.urlresolvers import reverse, resolve
from post.models import Post
p = Post.objects.get(pk=16)
reverse('post_views:single_view', args=['article', 2013, 12, 12, p.slug, p.id])
resolve('/article/2013/12/12/triumphlaunched10newbikesinindia/16/')

Resolver404: {u'path': u'article/2013/12/12/triumphlaunched10newbikesinindia/16/', u'tried': [[], [ (None:vehicle) ^vehicle/>], [ (None:post_views) ^(P[article|review|blog|news|video])/>], [ (None:gallery) ^gallery/>], [ (None:author) ^author/>], [.*)$>], [ (None:None) ^admin/doc/>], [ (admin:admin) ^admin/>], [ (None:None) ^admin_tools/>]]}

A: Your regular expressions are malformed, try replace
r'(P<post_type>[article|review|blog|news|video])'

with
r'(?P<post_type>article|review|blog|news|video)'

Note queston signs and absence of square brackets.
Similary, replace
r'^(P<year>\d{4})/(P<month>\d{2})/(P<day>\d{2})/(P<slug>\w+)/(P<post_id>\d+)$

with
r'^(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d{2})/(?P<slug>\w+)/(?P<post_id>\d+)$


text:
Q: How and when to rewrite jQuery callbacks into promises? I consider rewriting existing callback-based code into code using promises. However I'm unsure if this makes sense and how to start. The following code-snippet is a mostly self-contained example from that code:

function addTooltip($element, serverEndpoint, data) {
'use strict';

const DELAY = 300;
const TOOLTIP_PARENT_CLASS = 'hasTooltip';
let timeOutReference;
$element.hover(function hoverStart() {
    if ($element.hasClass(TOOLTIP_PARENT_CLASS)) {
        return;
    }
    timeOutReference = setTimeout(function getToolTip() {
        const $span = jQuery('');
        $span.html(jQuery(''));
        $element.append($span);
        $element.addClass(TOOLTIP_PARENT_CLASS);
        jQuery.get(serverEndpoint, data).done(function injectTooltip(response) {
            $span.html(response.data);
        }).fail(handleFailedAjax);
    }, DELAY);
}, function hoverEnd() {
    clearTimeout(timeOutReference);
});
};

Intended functionality: When the user hovers over $element for 300ms the tooltip-content is requested from the server and appended to $element.
Does it make sense to rewrite that code with promises and how would I do it?
(jQuery is provided by the framework (dokuwiki), so we might as well use it.)
Prior research:

*

*https://pouchdb.com/2015/05/18/we-have-a-problem-with-promises.html

*other SO questions about this topic which left me unsure about whether this is a sensible idea and how to do it

A: First, you'd need to wrap setTimeout into a promise. Simply create a function that accepts a timeout and returns a promise that resolves after that timeout.
Next, since jQuery.get already returns a promise, you just need to put it inside the promise resolve handler and return its promise. That way the next chained then listens to that promise instead of the timer's.
It would look something like:
function timer(n){
  return Promise(function(resolve){
    setTimeout(resolve, n);
  });
}

timer(DELAY).then(function(){
  return jQuery.get(...)
}).then(function(response){
  // jQuery.get promise resolved
}).catch(function(error){
  // something failed somewhere
});

As for your question

Does it make sense to rewrite that code with promises and how would I do it?

That depends on you. I find promise-based code more readable but takes time to write properly especially if if you intend to write pure callbacks and deal with multiple async operations. I usually write my code callbacks-first if the API is simpler to write that way and refactor later for readability.

A: To elaborate on my comment above. Below is an example of how promises can make dependent-callback code (arguably) more readable (Basically, it destroys the nesting of callbacks-in-callbacks):
Again, in the case of the code snippet you posted, I hardly see how it's worth it (unless your doing it as an exercise).
With Callbacks
function someAsyncMethod(callback) {
   $.get({...})
   .then(callback);
}

function anotherAsyncMethod(callback) {
   $.get({...})
   .then(callback);
}

someAsyncMethod(function() {
   anotherAsyncMethod(function yourFunction() {
      //do something
   });
});

With Promises:
function someAsyncMethod() {
  return $.get({...});
}

function anotherAsycnMethod() {
  return $.get({...});
}

someAsyncMethod()
 .then(anotherAsyncMethod)
 .then(function yourFunction() {
    //do something
  })


text:
Q: Only Allow jquery to load certain pages Sorry if this has been asked already, I've did a google search and couldn't find the answer.
I am new to jquery and I am wondering how to protect my backend pages from being loaded by external users?
For example, if my jquery .post or .get calls "delete-post.php" I only want the jquery to be able to load that page.  I don't want some John Doe user realizing he can post data from his own form to delete-post.php and delete whatever he wants, or calling delete-post.php?id=whatever_id_he_wants.
I hope this makes sense?  Like I said I am new to jQuery and am wondering about security.

A: About the only thing you can do, and something that you should be doing anyway, is checking that a user is logged in and is authorized to delete a post. You do this on the delete-post.php script by checking session variables.
The problem here isn't with jQuery or AJAX, if this were a normal static form, the user would still be able to figure out how to post to this delete-post.php page anyway.
Hope this helps.
Edit: And welcome to SO. :)

A: You have to validate your input on the server-side. Javascript is not capable of protecting you here. In your delete-post.php file, you should do multiple checks to make sure an authorized user on your site is calling the script and you could use some sort of unique validation key to authorize the action.

A: You can check if the incoming request is of the xhttp/ajax sort, but this will only tell you how the post was made.  You will need to set up at least the basics of an authenticated session in order to determine if a user has the authorization to delete a post.  That authority will carry over into the ajax requests.
If you are looking for something really quick and dirty, consider simple http basic access authentication, or if it is for you alone to moderate, a hard coded IP wouldn't be the worst situation you could be in.
In any event, you can't really do any sort of user verification on the client side like you want because it is too easily spoofed.

A: You should look into using security tokens (also called a 'nonce' which is an interesting choice of terminology if you happen to be a Brit).
A nonce is designed to ensure that any request originated from where you expected it to originate from.
Have a read through this guide (all of it! But the bit that's particularly relevant to this question is the bit about CSRF exploits) to see a simple implementation of this concept: http://php.robm.me.uk/
As an aside, never ever EVER do anything destructive using a GET request. Ever. Cardinal rule. Always use POST. In fact some also consider it good practice to never actually delete anything from the application, only direct from the database - just set a check for 'deleted' to perform a soft deletion instead. But that's not directly relevant to this question, of course. :-)


text:
Q: How do I maintain session state with a Google Earth client? I'm playing with dynamic updates to Google Earth KML files.
The updates are of the form
<kml...>
  <NetworkLinkControl>
    <Update>
      <targetHref="...">
      <Change>
        <Placemark targetId="...">
        ...stuff to update...
        </Placemark>
      </Change>
    </Update>
  </NetworkLinkControl>
</kml>

And it all works greatm from my Java Servlet - except that GE doesn't seem to support HTTP Sessions, and I need to provide only the updates that have occurred since the last request from a given client.
Am I doing something wrong? Does GE support sessions and I'm too stupid to work out how? If I need to provide client-specific updates without sessions, how can I do that? (I know I could use the source IP address as a coarse measure but that feels kinda nasty...)
Thanks!

A: It seems that I can use the kml/NetworkLinkControl/cookie element to give the client a parameter to send back to me. Trying to use this to get the client to tell me when it last requested an update and use this instead of sessions...

A: Old question, but you need to encode the session ID as part of the URLs.  GE does not maintain cookies.


text:
Q: Why does int(maxint) give a long, but int(int(maxint)) give an int? Is this a NumPy bug? Pretty self-explanatory (I'm on Windows):
>>> import sys, numpy
>>> a = numpy.int_(sys.maxint)
>>> int(a).__class__
<type 'long'>
>>> int(int(a)).__class__
<type 'int'>

Why does calling int once give me a long, whereas calling it twice gives me an int?
Is this a bug or a feature?

A: As proposed in the (now-deleted) other answer, this does seem to be a bug due to an incorrect use of < instead of <=, but it's not coming from the code cited in the other answer. That code is part of the printing logic, which isn't involved here.
I believe the code that handles int calls on NumPy scalars is generated from a template in numpy/core/src/umath/scalarmath.c.src, the relevant part for signed integer dtypes being
    if(LONG_MIN < x && x < LONG_MAX)
        return PyInt_FromLong(x);
#endif
    return @func@(x);

For integers strictly between LONG_MIN and LONG_MAX, this code produces an int. For an integer with value LONG_MAX, it falls back on the return @func@(x); case, where @func@ is substituted by an appropriate function from the PyLongFrom* family by the template engine.
Thus, calling int on a NumPy int with value LONG_MAX produces a long, but since the result is representable as an int, calling int on the result again produces an int.

A: This question is specific to Numpy and Python 2. In Python 3 there are no separate int and long types.
The behaviour happens due to an off-by-one error in numpy. int(x) with one argument converts x to number by calling PyNumber_Int(x). PyNumber_Int then specifically takes the path for int subclasses, as int64 returned by numpy.int_ is a subclass of int:
m = o->ob_type->tp_as_number;
if (m && m->nb_int) { /* This should include subclasses of int */
    /* Classic classes always take this branch. */
    PyObject *res = m->nb_int(o);
    if (res && (!PyInt_Check(res) && !PyLong_Check(res))) {
        PyErr_Format(PyExc_TypeError,
                     "__int__ returned non-int (type %.200s)",
                     res->ob_type->tp_name);
        Py_DECREF(res);
        return NULL;
    }
    return res;
}

Now, for this code calls a->ob_type->tp_as_number->nb_int, which is implemented in numpy/core/src/umath/scalarmath.c.src. This is the location for code that is parametrized for different types; this one for <typename>_int method that is used to fill the nb_int method slot. It has the following off-by one if there:
if(LONG_MIN < x && x < LONG_MAX)
    return PyInt_FromLong(x);

both operators should be <= instead. With < there, neither LONG_MIN nor LONG_MAX pass the condition and they're instead are converted into a PyLong at line 1432:
return @func@(x);

with @func@ being replaced by PyLong_FromLongLong in the case of int_. Thus, long(sys.maxint) is returned.
Now, as the sys.maxint is still representable by int, int(long(sys.maxint)) returns an int; likewise int(sys.maxint + 1) returns a long.


text:
Q: Angular-UI pagination missing last page I have a table I need to do pagination and the old pager is not acceptable. So I need to use the Pagination directive. I have implemented it according to the docs and various tutorials, but it is not working for me.
I have 20 items in the array, page size is set to 7 items per page, so I should have 3 pages right? But the directive only have page 1 and 2 and 3 is missing. Please help!!
Here is the html:

              <input type="checkbox" ng-model="vm.isSelectedAll" ng-click="vm.checkAll()" />

Customer Name

Customer PO#

Part Number

Delivery Date

<input type="checkbox" ng-model="qd.Selected" style="vertical-align:middle"/>

{{qd.customerName}}

{{qd.customerPoNumber}}

{{qd.partNumber}}

{{qd.deliveryDate | date : 'dd-MMM-yyyy'}}

                  Details | Quick Remark

Qty:

{{qd.quantity}}

                  {{qd.status}}

          <uib-pagination total-items="vm.qdPos.length"
                          item-per-page="vm.pageSize"
                          ng-model="vm.currentPage"
                          boundary-link="true"
                          previous-text="‹" next-text="›"
                          first-text="«" last-text="&raquo"
                          class="pagination-sm"></uib-pagination>

Here is the controller:
(function() {
  var app = angular.module('app');
  var controllerId = 'app.views.purchaseOrder.qdPo';

  app.filter('startFrom', function () {
    return function (input, start) {
      return input.slice(start);
    }
  });

  app.controller(controllerId, [
    '$scope', '$state', 'appSession',
    function($scope, $state, appSession ) {
      var vm = this;
      vm.qdPos = [{
        "id": 1,
        "customerName": "Jabberbean",
        "customerPoNumber": "0591-5319",
        "partNumber": "501114818-1",
        "quantity": 782564,
        "deliveryDate": "2015-09-28T09:36:06Z",
        "status": "Revised"
      }, {
        "id": 2,
        "customerName": "Meembee",
        "customerPoNumber": "75997-028",
        "partNumber": "963652003-8",
        "quantity": 411521,
        "deliveryDate": "2015-08-13T20:51:47Z",
        "status": "New"
      }, {
        "id": 3,
        "customerName": "Photospace",
        "customerPoNumber": "49349-927",
        "partNumber": "295842333-6",
        "quantity": 61715,
        "deliveryDate": "2015-10-18T01:48:22Z",
        "status": "Revised"
      }, {
        "id": 4,
        "customerName": "Topicstorm",
        "customerPoNumber": "16590-269",
        "partNumber": "830424508-6",
        "quantity": 831698,
        "deliveryDate": "2015-09-01T12:40:10Z",
        "status": "Revised"
      }, {
        "id": 5,
        "customerName": "Jabberbean",
        "customerPoNumber": "42291-225",
        "partNumber": "550455386-5",
        "quantity": 771454,
        "deliveryDate": "2015-05-05T12:27:42Z",
        "status": "New"
      }, {
        "id": 6,
        "customerName": "Photospace",
        "customerPoNumber": "0115-5212",
        "partNumber": "682923475-1",
        "quantity": 874958,
        "deliveryDate": "2015-07-20T03:32:33Z",
        "status": "Revised"
      }, {
        "id": 7,
        "customerName": "Eimbee",
        "customerPoNumber": "49738-182",
        "partNumber": "522413525-7",
        "quantity": 668127,
        "deliveryDate": "2015-06-13T18:24:09Z",
        "status": "No Change"
      }, {
        "id": 8,
        "customerName": "Meembee",
        "customerPoNumber": "41250-101",
        "partNumber": "945781744-3",
        "quantity": 224937,
        "deliveryDate": "2016-02-22T07:32:15Z",
        "status": "Revised"
      }, {
        "id": 9,
        "customerName": "Aivee",
        "customerPoNumber": "0591-3196",
        "partNumber": "230748890-1",
        "quantity": 648987,
        "deliveryDate": "2015-04-10T21:54:55Z",
        "status": "No Change"
      }, {
        "id": 10,
        "customerName": "Jabberbean",
        "customerPoNumber": "25113-333",
        "partNumber": "082625425-X",
        "quantity": 916253,
        "deliveryDate": "2015-12-28T06:18:52Z",
        "status": "No Change"
      }, {
        "id": 11,
        "customerName": "Topicstorm",
        "customerPoNumber": "59995-006",
        "partNumber": "945728924-2",
        "quantity": 810544,
        "deliveryDate": "2015-09-29T14:33:33Z",
        "status": "No Change"
      }, {
        "id": 12,
        "customerName": "InnoZ",
        "customerPoNumber": "76332-002",
        "partNumber": "121586408-6",
        "quantity": 536693,
        "deliveryDate": "2015-09-11T21:10:33Z",
        "status": "No Change"
      }, {
        "id": 13,
        "customerName": "InnoZ",
        "customerPoNumber": "51393-7223",
        "partNumber": "310043028-X",
        "quantity": 739695,
        "deliveryDate": "2016-02-07T10:31:12Z",
        "status": "No Change"
      }, {
        "id": 14,
        "customerName": "Blogtag",
        "customerPoNumber": "43742-0341",
        "partNumber": "637443495-1",
        "quantity": 305689,
        "deliveryDate": "2015-06-22T22:35:18Z",
        "status": "Revised"
      }, {
        "id": 15,
        "customerName": "Topicstorm",
        "customerPoNumber": "53808-0680",
        "partNumber": "481012830-X",
        "quantity": 533356,
        "deliveryDate": "2015-09-27T15:40:22Z",
        "status": "New"
      }, {
        "id": 16,
        "customerName": "Meembee",
        "customerPoNumber": "54868-4811",
        "partNumber": "428331365-3",
        "quantity": 177280,
        "deliveryDate": "2015-08-08T04:52:10Z",
        "status": "New"
      }, {
        "id": 17,
        "customerName": "Meembee",
        "customerPoNumber": "62037-599",
        "partNumber": "065890821-9",
        "quantity": 17787,
        "deliveryDate": "2015-05-12T12:57:11Z",
        "status": "New"
      }, {
        "id": 18,
        "customerName": "InnoZ",
        "customerPoNumber": "45802-201",
        "partNumber": "478496364-2",
        "quantity": 689218,
        "deliveryDate": "2015-03-31T22:57:24Z",
        "status": "Revised"
      }, {
        "id": 19,
        "customerName": "Photospace",
        "customerPoNumber": "65044-6586",
        "partNumber": "689861103-8",
        "quantity": 731566,
        "deliveryDate": "2015-03-16T19:25:19Z",
        "status": "Revised"
      }, {
        "id": 20,
        "customerName": "Eimbee",
        "customerPoNumber": "63187-061",
        "partNumber": "161036148-2",
        "quantity": 598961,
        "deliveryDate": "2016-02-21T07:49:44Z",
        "status": "New"
      }];

      vm.currentPage = 1;
      vm.pageSize = 7;
    }
  ]);
})();


text:
Q: how to restore np.arry from np.array string in pandas? how to restore np.arry from  np.array string in pandas?
np.arry is stored in a dataframe df,
>>> import pandas as pd
>>> df=pd.DataFrame({'X':['[2 5 6]','[5 6 9]']})
>>> df
         X
0  [2 5 6]
1  [5 6 9]

how can I restore the np.array and get the following
   [[2 5 6],
     [5 6 9]]

A: Try this:
np.array([line for line in df['X'].map(lambda x: x.replace(']','').replace('[','').split(' '))]).astype(int)

A: Try this.
from ast import literal_eval
df.X.str.replace(r'\s', r', ', regex=True).apply(literal_eval).tolist()
# [[2, 5, 6],
#  [5, 6, 9]]

Dummy Data
import pandas as pd
df=pd.DataFrame({'X':['[2 5 6]','[5 6 9]']})


text:
Q: PHP/Krumo: accessing arrays within arrays? I'm using krumo to output data from a page, all the data is accessible through the $page variable. I have a field called customer with the following structure:
customer (Array, 1 element)
    0 (Array, 1 element)
        id (String, 2 characters ) 85

How do i actually access id? I've tried $page->customer->id but it doesn't work. On the same level as customer, there's a string field called foo which I can access using $page->foo - so why doesn't my approach work?

A: If I'm not misunderstanding your question your solution would be:
$id=$page->customer[0]['id'];

A print_r() version would help too, maybe


text:
Q: What does these text nodes signify in DOM tree? For html code,

  Cascading
  Style
  Sheets

below is the DOM tree, using DOM inspector tool,

--
What does these text nodes(highlighted in red) signify?
Note: Beginner


text:
Q: Inheritance in class object not work and showing type error class BankAccount:
  def __init__(self):
    self.balance=0

  def withdraw(self,amount):
    self.balance-=amount
    return self.balance

  def deposit(self,amount):
    self.balance=amount+self.balance
    return self.balance

class MinimumBalanceAccount(BankAccount):
    def __init__(self, minimum_balance):
      BankAccount.__init__(self)
      self.minimum_balance = minimum_balance

    def withdraw(self, amount):
      if (self.balance - amount) < (self.minimum_balance):
        print('Sorry, minimum balance must be maintained.')
      else:
        BankAccount.withdraw(self, amount)

a=BankAccount()
a.balance
a.deposit(10)

aa=MinimumBalanceAccount(a)
aa.withdraw(1)

I'm getting the following error:
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-179-6160646c7f5f> in <module>()
      1 aa=MinimumBalanceAccount(a)
----> 2 aa.withdraw(1)

<ipython-input-168-6b59b3de5e45> in withdraw(self, amount)
      5
      6     def withdraw(self, amount):
----> 7       if (self.balance - amount) < (self.minimum_balance):
      8         print('Sorry, minimum balance must be maintained.')
      9       else:

TypeError: '<' not supported between instances of 'int' and 'BankAccount'

I'm revising the basics of OOP with this piece of code.Anyone can help me clear the error. I'm lost what I'm doing wrong.Why is there a type error?

A:
You have your base class BankAccount which looks fine. You could also let the initializer take a balance and set the default value to 0.
class BankAccount:
  def __init__(self, balance=0):
    self.balance = balance

  def withdraw(self, amount):
    self.balance -= amount
    return self.balance

  def deposit(self, amount):
    self.balance += amount
    return self.balance

There are some issues in your subclass. First, you attempt to initialize it with the class blueprint itself instead of its instance. You can do this by calling the __init__() method of the superclass, which will give you access to all its attributes and methods.
class MinimumBalanceAccount(BankAccount):
    def __init__(self, minimum_balance):
      super().__init__()
      self.minimum_balance = minimum_balance

You decide to override the inherited withdraw() method but try to retain some of its original functionality. Unfortunately, you can't have it both ways, so you will need to re-add that functionality to your overriden method. Note that you can now access balance from the superclass using self.balance.
def withdraw(self, amount):
      difference = self.balance - amount
      if difference < self.minimum_balance:
        print('Sorry, minimum balance must be maintained.')
      else:
        self.balance = difference
      return self.balance

With the implementation of the class outlined as above, the output of your test will then result in the following:
a = MinimumBalanceAccount(0)
a.balance  # -> 0 (by default)
a.deposit(10)  # -> 10
a.withdraw(5)  # -> 5

Edit:
Here is an implementation of the subclass which allows you to also adjust the balance in the superclass. This way, you never actually have to manually instantiate BankAccount anywhere else in your code:
class MinimumBalanceAccount(BankAccount):
    def __init__(self, balance, minimum_balance):
      super().__init__(balance)
      self.minimum_balance = minimum_balance

    def withdraw(self, amount):
      difference = self.balance - amount
      if difference < self.minimum_balance:
        print('Sorry, minimum balance must be maintained.')
      else:
        self.balance = difference
      return self.balance

The output then as follows:
a = MinimumBalanceAccount(balance=100, minimum_balance=0)
a.balance  # -> 100
a.deposit(10)  # -> 110
a.withdraw(5)  # -> 105


text:
Q: Isn't inertia experience by person in moving bus is Torque When a bus moves suddenly, the person standing in it tilts backwards. This concept is explained using inertia (tendency of body to resist change in its state of motion) but when the bus moves suddenly, can't we also say that the torque applied due to friction force on our feet causes our upper body to move backwards?

A: It should also be noted that the person tilting backward on the bus is not experiencing a real force but a pseudo force on the upper body, that is, a force that appears to be acting on the person because the persons motion is described in a non-inertial reference frame.

can't we also say that the torque applied due to friction force on our
  feet causes our upper body to move backwards?

The static friction force prevents the bottom part of the body from moving backwards as opposed to causing the upper part of the body to move backwards.
Hope this helps.


text:
Q: making a link unclickable in yii how to make a link in yii unclickable?
I have some id problems i.e. In the second form which is "Primary complain chain", there is a value which is used from the userinput data value in first form which is "Name and reference". So, if some one breaks the pipeline and moves directly to Primary complain chain, then, non-object error occurs which I want to avoid.
So, I was thinking if there is any trick such that, the links could be not click-able.
Please, I am stuck on this for like a long hour. Help needed immediately.
<?php
$this->menu = array(
    array('icon'=>'plus-sign-alt','label'=>'Home', 'url'=>array('/cname/index')),
    array('icon'=>'plus-sign-alt','label'=>'Name & Reference', 'url'=>array('/cname/create'),'active'=>true,),
    array('icon'=>'icon-signal','label'=>'Primary complain chain', 'url'=>array('/cprimary/create')),
);
?>

<?php
echo $this->renderPartial('_form', array('model'=>$model, 'model1'=>$model1));
?>

A: You could remove the menu item using something like this:
array('icon'=>'icon-signal',
      'label'=>'Primary complain chain',
      'url'=>array('/cprimary/create'),
      'visible'=>isset($model->name) && isset($model->reference),
),


text:
Q: Java Swing - Translucent Components causing Artifacts I'm currently working on a group project for a college course, and I've hit a bit of a stumbling block. The program we have decided to implement is a Peer-to-Peer chat client with a central server for storing and sharing usernames, etc. I've been assigned to do the GUI.
A friend jokingly suggested that I include "a flaming background!" So I decided to do just that, but to have a user-chosen background image. As is, only bits and pieces of the background image would be visible with all the components over top of it, so I decided to try to implement translucency.
This is where my problem lies:
When sending information from the input box to the chat window, or when navigating the friends list, or scrolling the chat window, strange artifacts are left behind. These artifacts are sometimes translucent "ghosts" of the Send button, sometimes part of the menu, or old text. It looks to me like the whole frame is not getting redrawn properly, but I'm not sure of how that works.
For components that implement JTextComponent, I'm setting their selection color to be a translucent color. For other components, I'm setting the background to be translucent. I have a function, setTranslucency(Component com) that looks at a component, sets its translucency depending on what it is, then sees if it is a container of some sort and sets the translucency of each item recursively.
Now, the way that I've found to fix this problem is to drag the window out of sight (such as minimizing or dragging the window off-screen and back).
So,
1) Is there a way to force the entire window to update like it does when I drag it off of the screen or minimize it?
or,
2) Am I doing it wrong in the first place? If so, how would I fix it?
Here's a picture for reference:
http://i.stack.imgur.com/4J9GJ.png

A: You need to tell Swing that the components are translucent, so it does also paint the background when repainting the changed components. For this, your components have to return false from the isOpaque() method (this can be achieved by setOpaque(false) when no subclass overwrites isOpaque to do something else).
With this, it should work without any manual repainting of everything, as the other answers proposed. (I already did this once.)
Edit: The reason for this is that Swing uses an optimized repainting-algorithm, repainting only these components which really need repainting (for example, a JTextField after some input) or components in front of such ones, as long as they are opaque. When a component needing repainting is not opaque (= filling its whole space with non-translucent color), also repainting of the components behind them is necessary.

A: myComponent.revalidate();
myComponent.repaint();
Not sure if it "force" the redraw, but it ask it to do it when possible.

A: Try JFrame.repaint(). That should work. If you want custom designing of your JFrame then you will have to override paint() method of JFrame. Additionally, if you want each component to be custom designed you will have to override the paint() method of each of your GUI component. Couple of things to note:

*

*You do not have to call paint() for any GUI component. You only need to call repaint().

*In case you do the overriding of the other GUI components [JButton, JTextField...], you do not have to call their repaint() method. The parent Container's [JFrame, JPanel...] repaint() will do the job.


text:
Q: Replace all numeric values with NaN Pandas I have a dataframe that looks like this:
data = {'Region': ['Africa','Africa','Africa','Africa','Africa','Africa','Africa','Africa','Asia','Asia','Asia','Asia'],
         'Country': ['South Africa','South Africa','South Africa','South Africa','South Africa','South Africa','South Africa','South Africa','Japan','Japan','Japan','Japan'],
         'Product': ['ABC','ABC','ABC','ABC','XYZ','XYZ','XYZ','XYZ','DEF','DEF','DEF','DEF'],
         'Year': [2016, 2017, 2018, 2019,2016, 2017, 2018, 2019,2016, 2017, 2018, 2019],
         'Price': [500, 400, 0,450,750,0,0,890,0,0,415,0],
         'Quantity': [1200,1700,0,330,500,0,0,120,300,0,50,0],
         'Value': [600000,680000,0,148500,350000,0,0,106800,0,0,20750,0]}

df = pd.dataframe(data)

I want to replace all the numeric values (i.e. those in columns Year, Price, Quantity, Value) with NaN but I can't figure out a good way to do it.

A: Select numeric columns by DataFrame.select_dtypes and set missing values:
df[df.select_dtypes(np.number).columns] = np.nan

Or if possible some rows has numeric or numeric saved like strings use to_numeric for test them with DataFrame.where for set NaNs:
df = df.where(df.apply(pd.to_numeric, errors='coerce').isna())
print (df)
    Region       Country Product  Year  Price  Quantity  Value
0   Africa  South Africa     ABC   NaN    NaN       NaN    NaN
1   Africa  South Africa     ABC   NaN    NaN       NaN    NaN
2   Africa  South Africa     ABC   NaN    NaN       NaN    NaN
3   Africa  South Africa     ABC   NaN    NaN       NaN    NaN
4   Africa  South Africa     XYZ   NaN    NaN       NaN    NaN
5   Africa  South Africa     XYZ   NaN    NaN       NaN    NaN
6   Africa  South Africa     XYZ   NaN    NaN       NaN    NaN
7   Africa  South Africa     XYZ   NaN    NaN       NaN    NaN
8     Asia         Japan     DEF   NaN    NaN       NaN    NaN
9     Asia         Japan     DEF   NaN    NaN       NaN    NaN
10    Asia         Japan     DEF   NaN    NaN       NaN    NaN
11    Asia         Japan     DEF   NaN    NaN       NaN    NaN


text:
Q: What to use instead of window.getLocation() in a textarea in React? I have a simple textarea where I want the user to be able to select/highlight text to make it bold, italicized, etc., much like the one I'm writing in now.
I actually get it working using a onKeyDown method and then using window.getSelection(), but I feel it's the wrong approach to use window in React. Correct? If so, what do I use instead?
handleKeyDown(event) {
    const highlightedText = window.getSelection().toString()
    console.log(highlightedText)
},

render() {
    return (
        <textarea onKeyDown={this.handleKeyDown} />
    )
}

A: The time when things can go wrong is when you modify the DOM outside of React. But this is not the case.
I don't mind calling window.getSelection in my react code. I've been using document methods/attrs like document.activeElement and window methods/attr like window.innerHeight and setTimeout. I have come across no problem and I did not find any other better way to get what I want.
This does need some attention in test though. You need to set up the window object and make it available to your test code.

A: It's ok to use window.getSelection in React. The only issue I see here in terms of breaking the component model and getting unexpected results, is the case where you call the method inside your component, but the selection is actually on a different element on the page.
In your case since you are calling getSelection inside the onKeyDown handler, you know the selection must have come from this component instance, since it needs to be focused to receive the event.
But if you would like to be able to get the selection at any time inside a component in a safe way, you could create a member function on the component to check if it's focused using refs:
getSelection() {
    return (this.refs.container === document.activeElement) ?
        window.getSelection() : null;
}

render() {
    return (
        <textarea onKeyDown={this.handleKeyDown} ref="container" />
    )
}

Here getSelection() will return the selection if it's within this component instance, otherwise null.


text:
Q: Android OpenGL weirdness with the setLookAtM method As a beginner to android and openGL 2.0 es, I'm testing simple things and see how it goes.
I downloaded the sample at http://developer.android.com/training/graphics/opengl/touch.html .
I changed the code to check if I could animate a rotation of the camera around the (0,0,0) point, the center of the square.
So i did this:
public void onDrawFrame(GL10 unused) {
    // Draw background color
    GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT);

    // Set the camera position (View matrix)
    long time = SystemClock.uptimeMillis() % 4000L;
    float angle = ((float) (2*Math.PI)/ (float) 4000) * ((int) time);
    Matrix.setLookAtM(mVMatrix, 0, (float) (3*Math.sin(angle)), 0, (float) (3.0f*Math.cos(angle)),     0 ,0, 0,     0f, 1.0f, 0.0f);

    // Calculate the projection and view transformation
    Matrix.multiplyMM(mMVPMatrix, 0, mProjMatrix, 0, mVMatrix, 0);

    // Draw square
    mSquare.draw(mMVPMatrix);
}

I expected the camera to look always to the center of the square (the (0,0,0) point) but that's not what happens. The camera is indeed rotating around the square but the square does not stay in the center of the screen.. instead it is moving along the X axis...:

I also expected that if we gave the eyeX and eyeY the same values as centerX and centerY,like this:
Matrix.setLookAtM(mVMatrix, 0, 1, 1, -3,     1 ,1, 0,     0f, 1.0f, 0.0f);

the square would keep it's shape (I mean, your field of vision would be dragged but along a plane which would be paralel to the square), but that's also not what happens:

This is my projection matrix:
float ratio = (float) width / height;

// this projection matrix is applied to object coordinates
// in the onDrawFrame() method
Matrix.frustumM(mProjMatrix, 0, -ratio, ratio, -1, 1, 2, 7);

What is going on here?

A: Looking at the source code to the example you downloaded, I can see why you're having that problem, it has to do with the order of the matrix multiplication.
Typically in OpenGL source you see matrices set up such that
transformed vertex = projMatrix * viewMatrix * modelMatrix * input vertex
However in the source example program that you downloaded, their shader is setup like this:
"  gl_Position = vPosition * uMVPMatrix;"
With the position on the other side of the matrix. You can work with OpenGL in this way, but it requires that you reverse the lhs/rhs of your matrix multiplications.
Long story short, in your case, you should change your shader to read:
"  gl_Position = uMVPMatrix * vPosition;"
and then I believe you will get the expected behavior.


text:
Q: Hidden button action won't change issue I'm trying to disable the navigation bar button when I start the app and after I finish the process(fetching data), I enable it back but unfortunately it won't enable.
Please where would be my issue? While I'm putting enable to YES and when I debug it I can see that it enabling it to YES.
- (void)viewDidLoad {

    UIImage *searchBtn = [UIImage imageNamed:@"search_icon.png"];
    barButtonSearch = [[UIBarButtonItem alloc] initWithImage:[searchBtn imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(searchButton)];

    UIImage *menuBtn = [UIImage imageNamed:@"menu_icon.png"];
    barButtonMenu = [[UIBarButtonItem alloc] initWithImage:[menuBtn imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(menuButton)];

    self.navigationItem.rightBarButtonItem = barButtonMenu;
    self.navigationItem.leftBarButtonItem = barButtonSearch;

    barButtonMenu.enabled = NO;
    barButtonSearch.enabled = NO;
}

- (void)unhide{

    if (!(barButtonSearch.enabled && barButtonMenu.enabled)) {

        barButtonMenu.enabled = YES;
        barButtonSearch.enabled = YES;
    }
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    ViewController *theInstance = [[ViewController alloc] init];

    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    operation.responseSerializer = [AFJSONResponseSerializer serializer];

    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {

        _dic  = (NSDictionary *)responseObject;

    [theInstance unhide];

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

        NSLog(@"Err");
    }];

    [operation start];

    return YES;
   }
}

A: Well there it is!
You are initializing your ViewController but that doesn't call your viewDidLoad: method. The viewDidLoad: method gets called when your ViewController is either Pushed or Presented! That is the time when the view gets loaded into the memory.
Therefore, the barButtons are never created and you are unable to see them.
So either make your network call inside the viewDidLoad: method of your ViewController
OR
Push the instance of your ViewController and then call the method unhide.
Edit
Since you are using Storyboards and not pushing any ViewController from AppDelegate, you need to use reference of your ViewController.
replace this in your - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions method
ViewController *theInstance = (ViewController *)[(UINavigationController*)self.window.rootViewController topViewController];

A: You are calling [theInstance unhide] from the completion block of the AFHTTPOperation - this will almost certainly be executed on a background queue.
All UI operations must be performed on the main queue.
You should use -
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {

        _dic  = (NSDictionary *)responseObject;
        dispatch_async(dispatch_get_main_queue(),^{
            [theInstance unhide];
        });

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

        NSLog(@"Err");
    }];

Update
Your main problem is that theInstance points to an instance of your view controller that isn't on the screen - It is just an instance you have allocated but not actually presented.
Assuming this view controller is the initial view controller loaded by your application you can get a reference to the correct instance using [UIApplication sharedApplication].keyWindow.rootViewController

A: Remove this method from the completion block of app delegate.
 [theInstance unhide];

And add some delegate function which will be activated after the asynchronous call completes its task. And add that unhide method there (In your view controller may be).


text:
Q: Eclipse Indigo OS X arrow and backspace keys no longer work I'm doing some Android dev and after a number of projects I recently found my arrow and backspace keys no longer work in the editor view (Java and XML).
It works in all other apps. I've tried restarting Eclipse and restarting my macbook, but it still occurs.
Can anyone help? :(

A: Ok, I've uninstalled an app called Air Display I had installed. Apparently it has issues with my late 2008 macbook pro on Lion (I lost the drag and drop ability).
after a reboot, all is working again.

A: Windows -> Preferences -> General -> Keys

Check if you've made a strange hotkey using space or the arrows

A: Try doing a middle click in the editor and try again.


text:
Q: Deleting a class with IDE - can't connect to SF? Can anyone shed some light on this error?  I cannot connect to either Production OR my Sandbox with the IDE.  :-(   Thanks.

This happens after entering user/pass/token in and selecting to get "all".  I've tried searching keywords from the error but am coming up with no help.
Windows 7 64-bit with 64-bit IDE standalone package.

A: This error is presented (not just during deployments) when Java7 (1.7) is installed.
Removing Java7 from the machine so that Eclipse cannot reference it, should revert you back to having just the 1.6 JDK available and you'll be back in business.
Worst case, remove all installed versions of Java and then download & install JDK 1.6 again. If you're running a 32-bit version of Eclipse be sure to install the 32-bit JDK.
this happenns when JRE is updated from 1.6 to a higher version. The way i handle is by going to Window -> preferences in ForceIDE top menu.
another alternative is,
You will get a dialog window, Click on Java ->Installed JRE and uncheck jre7. Restart ForceIDE it should work.

A: This looks to me an error because you have the latest version of jdk installed and force IDE is not compatible with it.
The way i handle is by going to Window -> preferences in ForceIDE top menu.
You will get a dialog window, Click on Java ->Installed JRE and uncheck jre7. Restart ForceIDE it should work.
You can look at  answer from Mark ponds and my answer with screenshot to a similar question.
In Force.con IDE - Error while deploying to Server

A: This is an overwealming Pain...
You can try this: http://www.myeclipseide.com/PNphpBB2-viewtopic-t-10280.html
basically adding -clean and then running eclipse
Something else you can try if that fails:

*

*create a new project

*Delete Eclipse and reinstall

A: Just loaded Classes and Triggers, after trying reinstallation, the -clean switch, deleting/recreating the projects, etc.

A: An answer was obtained on HOW TO DELETE TRIGGERS/CLASSES from Production in another thread:  Deleting a Class with IDE - cannot delete from Production?
The specific answer to this one is unclear as another JRE was installed (but I stuck with JRE7), AND other things were tried.  It is suspected that the JRE solved it, but I am unsure.  :-/
Thanks to all who helped!


text:
Q: Error with the structure of array passed as argument for joint diagonalisation I am trying to use ffdiag (pybss) from the following function :
def ffdiag(X, max_lag = 10, eps = 1.0e-10, max_iter = 100):
    '''
    Blind source separation using FFDIAG.  This version does not require that
    the estimated mixing matrix be orthogonal.

    INPUT:
    ------
    X : array, required
        N_sig x t matrix of signal mixtures

    max_lag : int, optional
        maximum lag (in samples) for covariance matrix calculation

    eps : double, optional
        convergence criterion for matrix updates

    max_iter : int, optional
        maximum number of iterations/updates
    '''
    R_tau = linalg.lagged_covariance(X,max_lag)
    dim = len(R_tau[0])
    n_lags = len(R_tau.keys())
    W = zeros((dim,dim))
    V = eye(dim)
    C = R_tau
    niter = 0
    theta = 0.9
    iter_eps = 1.0

with lagged_covariance defined by :
def lagged_covariance(X, max_lag):
    '''
    Generates a dictionary of lagged covariance matrices of matrix X, for
    lags 0,1,2,...,max_lag.

    INPUT:
    ------
    X : array, required
        N x t data matrix

    max_lag : integer, required
        covariance matrices will be computed for lags 0,1,...,max_lag

    OUTPUT:
    ------
    R_tau : dictionary, keyed on the lag, with values equal to the lagged
        covariance of X with the lagged version of itself.
    '''
    R_tau = {}
    t = X.shape[1]
    dim = X.shape[0]
    R_tau[0] = cov(X,X)[0:dim,dim::]
    for tau in range(1,max_lag+1):
        for i in range(tau,t):
            # create X(t) and X(t-tau)
            X_t = X[:,0:t-tau]

I get the following error :
/Users/henry/pybss/linalg.py", line 92, in lagged_covariance
    R_tau[0] = cov(X,X)[0:dim,dim::]
  File "<__array_function__ internals>", line 6, in cov
  File "/opt/intel/intelpython3/lib/python3.7/site-packages/numpy/lib/function_base.py", line 2371, in cov
    raise ValueError("m has more than 2 dimensions")
ValueError: m has more than 2 dimensions

In my script, I am calling ffdiag like this :
# dimension
m=7
# number of matrices
n=2

# Load spectro and WL+GCph+XC
FISH_GCsp = np.loadtxt('Fisher_GCsp_flat.txt')
FISH_XC = np.loadtxt('Fisher_XC_GCph_WL_flat.txt')

# Marginalizing over uncommon parameters between the two matrices
COV_GCsp_first = np.linalg.inv(FISH_GCsp)
COV_XC_first = np.linalg.inv(FISH_XC)
COV_GCsp = COV_GCsp_first[0:m,0:m]
COV_XC = COV_XC_first[0:m,0:m]
# Invert to get Fisher matrix
FISH_sp = np.linalg.inv(COV_GCsp)
FISH_xc = np.linalg.inv(COV_XC)
# Drawing a random set of commuting matrices
C=np.zeros((n,m,m));
B=np.zeros((n,m,m));
C[0,:,:] = np.array(FISH_sp)
C[1,:,:] = np.array(FISH_xc)

[invV, B, ut] = ffdiag(C, 10, 1.0e-10, 100)

but I don't know if the array C is well defined : in any cases, I have got to pass 2 matrices of size 7x7 but in which order :
# dimension
m=7
# number of matrices
n=2

C=np.zeros((n,m,m));
B=np.zeros((n,m,m));

or
C=np.zeros((m,m,n));
B=np.zeros((m,m,n));

or something else since the both above don't seem to work.
As you can see in the definition of ffdiag, it is noticed :
INPUT:
        ------
        X : array, required
            N_sig x t matrix of signal mixtures

But I can't guess which is the structure of X array.


text:
Q: DateTime processing methodology I'm facing an issue which I can't find a proper and elegant solution. I have a List of Videos, which is a class that contains informations about a video. Among those informations there is a startDate,endDate and an cameraId property.
My current database has the following values:
         startDate      endDate

I want to iterate through those  values and when a video is within 5 minutes difference from the last one and has the same cameraId it should be counted as one. But I can't find a proper nor elegant way to accomplish this task.
The output for the videos list shown above should be

*

*1st: 2013:03:01 18:25:26 -> 2013-03-01 18:34:29

*2nd: 2013:03:01 18:40:26 -> 2013:03:01 18:59:29

This is the code I have so far:
private void ProcessVideos(List<Video> videos)
        {
            bool isSameVideo = false;
            Video lastVideo = null;

            //debugar e ver esquema do ultimo valor do database
            DateTime startDate = DateTime.MinValue;
            DateTime endDate = DateTime.MinValue;
            for (int i = 1; i < videos.Count; i++)
            {
                TimeSpan timeSpan = new TimeSpan(videos[i].DataInicio.Ticks - videos[i - 1].DataFim.Ticks);
                if (timeSpan.Minutes > 0 && timeSpan.Minutes < 5 && videos[i].IdCamera == videos[i - 1].IdCamera)
                {
                    if (!isSameVideo)
                    {
                        isSameVideo = true;
                        startDate = videos[i - 1].DataInicio;
                        endDate = videos[i].DataFim;
                    }
                    else
                    {
                        endDate = videos[i].DataFim;
                    }
                }
                else
                {
                    if (isSameVideo)
                    {
                        i++;
                        isSameVideo = false;
                        Debug.WriteLine("inicio: {0} fim: {1}", startDate, endDate);
                        startDate = DateTime.MinValue;
                        endDate = DateTime.MinValue;
                    }
                    Debug.WriteLine("inicio: {0} fim: {1}", videos[i - 1].DataInicio, videos[i - 1].DataFim);
                }
            }
            if (startDate != DateTime.MinValue)
            {
                Debug.WriteLine("inicio: {0} fim: {1}", startDate, endDate);
            }
        }

The main question is: What is a good logic to iterate through those values and output a combinations of values according to the timespan specification?

A: I created a small example to show you:
My container object:
internal class Container
{
    public int Id { get; set; }
    public DateTime Start { get; set; }
    public DateTime Stop { get; set; }

    public override string ToString()
    {
        return "ID " + Id + ": " + Start + " -> " + Stop;
    }
}

My method:
    private static IEnumerable<Container> DoMerge(List<Container> elements, TimeSpan maxDiff)
    {
        var closedContainers = new List<Container>();
        var lastContainers = new Dictionary<int, Container>();

        foreach (Container container in elements.OrderBy(e => e.Start))
        {
            //First case, no previous container
            if (!lastContainers.ContainsKey(container.Id))
            {
                lastContainers[container.Id] = container;
            }
            else if (container.Start - lastContainers[container.Id].Stop > maxDiff)
                //We have a container, but not in our windows of 5 minutes
            {
                closedContainers.Add(lastContainers[container.Id]);
                lastContainers[container.Id] = container;
            }
            else
            {
                //We have to merge our two containers
                lastContainers[container.Id].Stop = container.Stop;
            }
        }

        //We have now to put all "lastContainer" in our final list
        foreach (KeyValuePair<int, Container> lastContainer in lastContainers)
        {
            closedContainers.Add(lastContainer.Value);
        }
        return closedContainers;
    }

And we just have to give our max timespan and list of elements:
    private static void Main(string[] args)
    {
        var elements = new List<Container>
            {
                new Container {Id = 1, Start = new DateTime(2013, 3, 1, 18, 25, 26), Stop = new DateTime(2013, 3, 1, 18, 27, 29)},
                new Container {Id = 1, Start = new DateTime(2013, 3, 1, 18, 30, 26), Stop = new DateTime(2013, 3, 1, 18, 34, 29)},
                new Container {Id = 1, Start = new DateTime(2013, 3, 1, 18, 40, 26), Stop = new DateTime(2013, 3, 1, 18, 52, 29)},
                new Container {Id = 1, Start = new DateTime(2013, 3, 1, 18, 55, 26), Stop = new DateTime(2013, 3, 1, 18, 59, 29)},
            };
        foreach (Container container in DoMerge(elements, TimeSpan.FromMinutes(5)))
        {
            Console.WriteLine(container);
        }
        Console.ReadLine();
    }

This give me your expected results we two objects lefts.
Result with the mentionned data:

A: Here's a solution. The crux of the method is shown in the ExtractVidTimes method. The rest is just for creating the sample data
    [TestFixture]
public class TestyMcTest
{
    public class Vid
    {
        public int CamId;
        public DateTime Start;
        public DateTime End;
    }

    [Test]
    public void Test()
    {
        var list = new List<Vid>
            {
                //=====Combination1=======
                new Vid
                    {
                        CamId = 1,
                        Start = new DateTime(2000, 1, 1, 0, 0, 0),
                        End = new DateTime(2000, 1, 1, 0, 3, 0)
                    },
                new Vid
                    {
                        CamId = 1,
                        Start = new DateTime(2000, 1, 1, 0, 5, 0),
                        End = new DateTime(2000, 1, 1, 0, 7, 0)
                    },
                //=====Combination2=======
                new Vid
                    {
                        CamId = 1,
                        Start = new DateTime(2000, 1, 1, 0, 15, 0),
                        End = new DateTime(2000, 1, 1, 0, 18, 0)
                    },
                //=====Combination3=======
                new Vid
                    {
                        CamId = 2,
                        Start = new DateTime(2000, 1, 1, 0, 0, 0),
                        End = new DateTime(2000, 1, 1, 0, 3, 0)
                    },
                //=====Combination4=======
                new Vid
                    {
                        CamId = 2,
                        Start = new DateTime(2000, 1, 1, 0, 10, 0),
                        End = new DateTime(2000, 1, 1, 0, 13, 0)
                    }
            };

        //here is your list of vids grouped by the cam id
        var result = ExtractVidTimes(list);
    }

    //THE METHOD
    private static List<List<Vid>> ExtractVidTimes(List<Vid> list)
    {
        //Group by cam ID
        var vidGroups = list.GroupBy(vid => vid.CamId).ToList();

        //extract vids with aggregate times
        var result = vidGroups.Select(vids =>
            {
                var vidTimes = new List<Vid>();
                var finalVid = vids.OrderBy(vid=> vid.Start).Aggregate((a, b) =>
                    {
                        if (a.End.AddMinutes(5) > b.Start)
                        {
                            a.End = b.End;
                            return a;
                        }

                        vidTimes.Add(a);
                        return b;
                    });

                vidTimes.Add(finalVid);

                return vidTimes;
            }).ToList();

                    //return result.SelectMany(x=>x);  //if you want a List<vid> return ed instead of a nested list

        return result;
    }
}


text:
Q: Refresh a ListView adding new elements on runtime in NativeScript and Angular I'm building a ListView based component, similar to the groceries example in the {N} page. I have a "+" button, that needs to add new items to the list, I have this code:
import { Component, OnInit } from '@angular/core';

@Component({
    moduleId: module.id,
    selector: 'my-list',
    templateUrl: 'my-list.component.html'
})
export class ListComponent implements OnInit {
    private myList: CustomObject;
    constructor() { }

    ngOnInit() { }

    addItem(){
        this.myList.push(new CustomObject());
    }

}

And here is the template:
<StackLayout>
    <Button text="+" (tap)="addItem()" ></Button>
    <ListView [items]="myList">
        <template let-item="item" let-i="i">

        </template>
    </ListView>
</StackLayout>

My problem is, when I click on the "+" button, I get an undescifrable exception. When I fill the list with code, no problem, but I need the user can add new elements to the view. How is the correct way to implement a dynamic ListView like I described?
EDIT:

An uncaught Exception ocurred on "main" thread.
  com.tns.NativeScriptException: Calling js method getView failded
Error No suitable views found in list template! Nesting level:0 File:
  "/data/data/org.nativescript.MyApp/files/app/tns_moudules/nativescript-angular/directives/list-view-comp.js,
  line:135 column:8
StackTrace: Frame: function:'getSingleViewRecursive', file:....

A: In NativeScript + Angular-2 application you can use AsyncPipe
Example on how to provide data via async pipe in NativeScript + NG2 app can be found here
What is noticeable is the usage of RxObservable
page.component.ts
import { Component, ChangeDetectionStrategy } from "@angular/core";
import { Observable as RxObservable } from "rxjs/Observable";

export class DataItem {
    constructor(public id: number, public name: string) { }
}

@Component({
    templateUrl: "ui-category/listview/using-async-pipe/using-async-pipe.component.html",
    changeDetection: ChangeDetectionStrategy.OnPush,
})
export class UsingAsyncPipeComponent {
    public myItems: RxObservable<Array<DataItem>>;

    constructor() {
        let items = [];
        for (let i = 0; i < 3; i++) {
            items.push(new DataItem(i, "data item " + i));
        }

        let subscr;
        this.myItems = RxObservable.create(subscriber => {
            subscr = subscriber;
            subscriber.next(items);
            return function () {
                console.log("Unsubscribe called!");
            };
        });

        let counter = 2;
        let intervalId = setInterval(() => {
            counter++;
            items.push(new DataItem(counter + 1, "data item " + (counter + 1)));
            subscr.next(items);
        }, 1000);

        setTimeout(() => {
            clearInterval(intervalId);
        }, 15000);
    }
}

page.component.html
<ListView [items]="myItems | async" class="list-group">
    <template let-item="item" let-i="index" let-odd="odd" let-even="even">
        <GridLayout class="list-group-item" [class.odd]="odd" [class.even]="even">

        </GridLayout>
    </template>
</ListView>

In this basic example the async is simulated with setInterval but based on the same logic you can achieve your desired UX with a button.


text:
Q: Changing a button's font color when touched in iOS I'm brand new to iOS with only Action Script 3.0 as a programming background.  Objective C is looking unbelievably foreign to me thus far.  I'm working with the latest version of Xcode and am trying to learn by taking baby steps, and too many tutorials start at far too high a level for a new guy like me.
I'm trying to have a label or button change font color when it is touched, and return to its original color when it is touched again.  I know it's probably stupidly simple, but I need to start somewhere.  Thanks much.

A: It is very easy to change a UIButton color property when it is touched.
-(IBAction)changeColor:(id)sender
{
UIButton *btn = (UIButton *)sender;

if(btn.enabled)
{
    btn.enabled=NO;
    btn.backgroundColor=[UIColor blueColor];

}
else
{
    btn.enabled=YES;
    btn.backgroundColor=[UIColor greenColor];
}

}

A:  @interface ViewController ()
{
BOOL muteIsSelected;
}

@end
- (IBAction)yourButton:(id)sender {
if(muteIsSelected == false)
{
   yourButton.backgroundColor = [UIColor redColor];
    muteIsSelected = true;
}
else if (muteIsSelected == true)
{
     yourButton.backgroundColor = [UIColor blackColor];
    muteIsSelected = false;
}
}


text:
Q: RLock#lock(long leaseTime, TimeUnit unit) leasetime lower than execution time Code:
public void lock() {
    RLock lock = redissonClient.getLock("lock");
    lock.lock(1, TimeUnit.SECONDS); // or use lock.lock()
    doSomething();
    lock.unlock(); // if necessary
}

If doSomething() spending time over 1s(reason like network), then another thread can get the lock, but this will cause some problems (such as oversold). If use lock.lock(), while this client offline, it will never unlock the lock and others client can not get the lock. How to solve or balance this problem?

A:
If use lock.lock(), while this client offline, it will never unlock the lock and others client can not get the lock.

When you use lock#lock(), an expiration time will be set on the corresponding key (the default is 30 seconds, see org.redisson.config.Config#lockWatchdogTimeout), and there will be a watchdog(watchdog is actually a timer task) that is always responsible for the automatic extension(extend the expiration time of the corresponding key).
So if your client is suddenly disconnected, then the lock will be released after a certain period of time (that is, the corresponding key has expired because watchdog also hangs up with your client
). So you don't have to worry about the problem that the lock will never be released if you use lock#lock().


text:
Q: how to make sql query with and in yii active record? I am new in Yii. Now i have encountered problem with active record in yii.
So , I have normal sql here :
 $sqlText = "SELECT *
        FROM tbl_webservicetokens
        WHERE clienttoken = '{$appToken}'
            AND
              systimestamp < expiredate";

I want to use active record. But i endeavored
$post=TBLWEBSERVICETOKENS::model()->find(
        'CLIENTTOKEN=:appToken AND EXPIREDATE>:systimestamp',
        array(
            ':appToken'=>$appToken,
            ':systimestamp'=>'systimestamp'));

But i had error!
any idea?

A: Try this query. I think this will work for you.
 $post= TBLWEBSERVICETOKENS::model()->find(array(
       'select'=>'*',
       'condition'=>'CLIENTTOKEN=:appToken AND EXPIREDATE>:systimestamp',
       'params'=>array(':appToken'=>$appToken,':systimestamp'=>'systimestamp'))
       );

A: You are passing wrong data type (string) for the date time field have you noted that
$post=TBLWEBSERVICETOKENS::model()->find(
        'CLIENTTOKEN=:appToken AND EXPIREDATE>:systimestamp',
        array(
            ':appToken'=>$appToken,
            ':systimestamp'=>$systimestamp)); //$systimestamp where your time data type value resides

If you still have the error
Read Me!!!

A: Well, It seems to me i find answer:
$criteria = new CDbCriteria;

$criteria->condition = "ID = 1212 AND CLIENTTOKEN = 'ws546b041c85ad38a2c1f4224e1e39fe09cf76a3c8703c5'";
$models = TBLWEBSERVICETOKENS::model()->findAll($criteria);


text:
Q: determine the number of intersecting records I have a set of objects that have a variety of attributes:

id
title
owner_id

25
The Name of the object
5000

31
Another name of a different object
5000

71
Yet another
5000

19
example title
6000

21
another example
6000

23
more example
6000

and a list of attributes for each object (this list isn't completely normalized, but could be if necessary)

object_id
attribute

25
Blue

25
Green

25
Black

31
Blue

31
Purple

71
White

19
Grey

19
Blue

21
Yellow

23
Pink

23
Grey

The goal is to calculate how many objects each owner has that overlap any attribtues with the other owners. So in the example, owner 5000 has 3 objects ( 25, 31, 71 ), and owner 6000 has 3 ( 19, 21, 23 ).
5000

*

*object 25 is (blue | green | black ) and overlaps with 19 because it also has a blue attribute.

*object 31 is (blue | purple | white ) and overlaps with 19 because it also has a blue attribute

*object 71 is (white) and doesn't overlap with any of owner 6000's objects, so it is unique.
6000

*object 19 is (grey | blue) and overlaps 25

*object 21 is (yellow) and is unique

*object 23 is (pink & grey) is unique because none of 5000s objects are pink or grey

so since it doesn't really matter if 1 or all of the other owners objects match, i can create a summary table for each owner that lists out all of that companies unique attributes, which would look like:
5000: ( blue | green | black | purple | white )
6000: ( grey | blue | yellow | pink )
so the goal would be some output like:

owner_a
owner_b
count_a
count_b
similarity_a_to_b
similarity_b_to_a
unique_a
unique_b

5000
6000
3
3
2
1
1
2

the challenge is that I'm dealing with several thousand owner_ids, with several million objects, which have 10s of millions of attributes, so I'm trying to figure out how to summarize the data so I could generate these types of metrics.

A: Well the SQL can be done via:
WITH objects (id, title, owner_id) AS (
    SELECT * FROM VALUES
      (25, 'The Name of the object', 5000),
      (31, 'Another name of a different object', 5000),
      (71, 'Yet another', 5000),
      (19, 'example title', 6000),
      (21, 'another example', 6000),
      (23, 'more example', 6000)
), attributes (object_id, attribute) AS (
    SELECT * FROM VALUES
      (25, 'Blue'),
      (25, 'Green'),
      (25, 'Black'),
      (31, 'Blue'),
      (31, 'Purple'),
      (71, 'White'),
      (19, 'Grey'),
      (19, 'Blue'),
      (21, 'Yellow'),
      (23, 'Pink'),
      (23, 'Grey')
), obj_att AS (
    SELECT o.*, a.*
    FROM objects AS o
    JOIN attributes AS a
        ON o.id = a.object_id
), owner_att AS (
    SELECT DISTINCT OWNER_ID, ATTRIBUTE
    FROM obj_att
), dist_owners AS (
    SELECT DISTINCT OWNER_ID
    FROM objects
), owner_pairs AS (
    SELECT a.owner_id as a_id, b.owner_id as b_id
    FROM dist_owners AS a
    JOIN dist_owners AS b
        ON a.owner_id <> b.owner_id
), object_mixed_attributes AS (
    SELECT op.*, oba.*, owa.attribute as b_att
    FROM owner_pairs AS op
    JOIN obj_att AS oba ON oba.owner_id = op.a_id
    LEFT JOIN owner_att AS owa ON owa.owner_id = op.b_id and oba.attribute = owa.attribute
)
SELECT op.a_id as owner_a
    ,op.b_id as owner_b
    ,count(distinct(om_a.id)) as count_a
    ,count(distinct(om_b.id)) as count_b
    ,count(distinct(iff(om_a.b_att is not null,om_a.id,null))) as similarity_a_to_b
    ,count(distinct(iff(om_b.b_att is not null,om_b.id,null))) as similarity_b_to_a
    ,count_a-similarity_a_to_b as unique_a
    ,count_b-similarity_b_to_a as unique_b
FROM owner_pairs AS op
JOIN object_mixed_attributes AS om_a ON om_a.a_id = op.a_id
JOIN object_mixed_attributes AS om_b ON om_b.a_id = op.b_id
WHERE op.a_id < op.b_id
GROUP BY 1,2;

which gives:
OWNER_A OWNER_B COUNT_A COUNT_B SIMILARITY_A_TO_B   SIMILARITY_B_TO_A   UNIQUE_A    UNIQUE_B
5000    6000    3       3       2                   1                   1             2

Given it's all equijoin's you will get the best performance out merge joins. looking at the profiles for this tiny example there are a couple WithReference blocks which over large tables, can sometime be slow than just reading from the table twice, this comes form the CTE being reused. So playing there can help.
Also I have ben lazy and not fully expanded the selects, thus using x.* at time, and maybe those values are not needed lower down. The complier will solve that for us, and if your tables are that large, then it will be lost in the wash.