Gray out specific radio-set after specific answer in other radio-set

I have a form with two question:

1. What day you want to come

2. What time you want to come

When you answer in question 1 "I can't attend" question 2 should be grayed out. I found a lot of possible solutions, but not the one which could help me :( . Most were with a checkbox, and based on the checked option a radio button was disabled or not. However, this is what I have so far:

<fieldset>
                    <div>
                        ~(IF(CHARINDEX('VISIT_DAY',DATA_ERROR)>=0,'<label style="color:#CC0000; font-weight:bold; width:100% !important; padding:0px !important; margin:0px !important; text-align:left !important;">','<label style="color:black; font-weight:bold; width:100% !important; padding:0px !important; margin:0px !important; text-align:left !important;">'))~ Ja, ik ben graag bij dit evenement aanwezig. Mijn voorkeursdag is:<span style="color:#CC0000;display:inline !important;">*</span> ~(IF(CHARINDEX('VISIT_DAY',DATA_ERROR)>=0,'</label>','</label>'))~

                        <div style="clear:both;">
                        </div>

                        <div style="float:left !important; clear:none !important;color:black;">
                            <input type="radio" value="A" style="width: auto !important;" ~(IF(@VISIT_DAY='A','checked',''))~ name="VISIT_DAY" /> 21 maart 2017<br />
                            <input type="radio" value="B" style="width: auto !important;" ~(IF(@VISIT_DAY='B','checked',''))~ name="VISIT_DAY" /> 22 maart 2017<br />
                            <input type="radio" value="C" style="width: auto !important;" ~(IF(@VISIT_DAY='C','checked',''))~ name="VISIT_DAY" /> Ik kan niet aanwezig zijn<br />
                        </div>
                    </div>

                    <div>
                        ~(IF(CHARINDEX('VISIT_TIME',DATA_ERROR)>=0,'<label style="color:#CC0000; font-weight:bold; width:100% !important; padding:0px !important; margin:0px !important; text-align:left !important;">','<label style="color:black; font-weight:bold; width:100% !important; padding:0px !important; margin:0px !important; text-align:left !important;">'))~ Ik zal komen binnen het volgende tijdsbestek:<span style="color:#CC0000;display:inline !important;">*</span> ~(IF(CHARINDEX('VISIT_TIME',DATA_ERROR)>=0,'</label>','</label>'))~

                        <div style="clear:both;">
                        </div>

                        <div style="float:left !important; clear:none !important;color:black;">
                            <input type="radio" value="A" style="width: auto !important;" ~(IF(@VISIT_TIME='A','checked',''))~ name="VISIT_TIME" /> 09.30 - 13.00<br />
                            <input type="radio" value="B" style="width: auto !important;" ~(IF(@VISIT_TIME='B','checked',''))~ name="VISIT_TIME" /> 13.00 - 16.30<br />
                            <input type="radio" value="C" style="width: auto !important;" ~(IF(@VISIT_TIME='C','checked',''))~ name="VISIT_TIME" /> 16.30 - 20.00
                        </div>
                    </div>
                    </fieldset>

So, when option C is selected in question 1, question two should be grayed out/disabled. Thank you very much! so far.

Eelco


pass Var from one javascript class to another

I have a controller and a view class.In my controller class I have this code. I am trying to get the AccNo which is passed in the url. I know this code works fine for retrieving the account number, but I now need to pass the Var in to the view class.

    getURLParameter : function(name) {
        return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search)||[,""])[1].replace(/\+/g, '%20'))||null
    },

    // Parse URL parameters
    parseAndSetURLParameters : function(){

        var accNo    = this.getURLParameter('accNo');

    },


Return comma separated list of names from comma separate list of IDs

To begin with, please don't hold the crappy database structure against me.  We all have things we have to deal with that we can't change, and I inherited these tables that are deeply ingrained within the application.

Consider these two tables:

Personnel
+-----+-------+--------------+
| ID  | Name  | TECHNIQUE_ID |
+-----+-------+--------------+
| 134 | Bob   | 1,2,4        |
+-----+-------+--------------+
| 135 | Mary  | 1,3,4        |
+-----+-------+--------------+
| 136 | Frank | 2            |
+-----+-------+--------------+

Techniques
+-----+----------+
| ID  | Name     |
+-----+----------+
| 1   | Fishing  |
+-----+----------+
| 2   | Archery  |
+-----+----------+
| 3   | Bowling  |
+-----+----------+
| 4   | Hiking   |
+-----+----------+

What I need is a listing of each person with a comma-separated list of the techniques they perform.  Essentially turning "1,3,4" into "Fishing,Bowling,Hiking".

I can do this in the CF code by having a nested query, but the report has thousands of rows... which means it could be running tens of thousands of queries just for one report.  I'd prefer to do it all in one query.


Center page in IE

I am trying to center page on IE. If I force quirk-mode by adding <!-- some comment --> before DOCTYPE declaration margin: auto; doesn't work properly and page is adjusted to the left. If I remove the comment page is centered, but some other elements are in mess. Could you give me some hints how to solve this?


How to build a number from a list of numbers in Prolog?

I'm pretty new in Prolog, and I was trying (without any success) to get a number from it's representation as a list of numbers.
Eg:
L=[1,2,3] => N=123
I managed to build this recursive algorithm but it sais "Arithmetic Conv is not a function". Can someone help me correcting it?

    conv([],0).
    conv([H|T],R):-
         R is H*10+conv(T,R).
    conv([E],R):-
         R is E.


Tube geometry not working with array of vertices [ THREE.js ]

I am having a little problem creating a tube spline from a array random points. I don´t have no clue why this doesn't work.

I get this error:

Uncaught TypeError: Cannot read property 'x' of undefined

    for (var i = 0; i < 5; i++) {

                    //particle = new THREE.Sprite( material );
                    particle.position.x = (Math.random() - 0.5)* 20;
                    particle.position.y = (Math.random() - 0.5)* 20;
                    particle.position.z = (Math.random() - 0.5)* 20;

                    particle.scale.x = particle.scale.y = 1;
                    scene.add( particle );

                    geometry.vertices.push( particle.position );

                    //var line = new THREE.Line( geometry, new THREE.LineBasicMaterial( { color: 0xffffff, opacity: 0.5 } ) );

                    //scene.add( line );

//HERE IS WHERE THE PROBLEM START

        var tubeVertices = new THREE.Vector3(geometry.vertices);
        var Spline = new THREE.CatmullRomCurve3(
                  tubeVertices
                 );

        var material = new THREE.MeshLambertMaterial( { color: 0xff00ff } );
        var tubeGeometry = new THREE.TubeGeometry( Spline, 5, 1, 5);
        var tube = new THREE.Mesh(tubeGeometry,material);
        scene.add( tube );

       }

I had tried this way but it doesn't work also. I add a picture of the error.

    ....
    var tubeVertices = new THREE.Vector3(geometry.vertices[1]);
    console.log(tubeVertices);

     var sampleClosedSpline = new THREE.CatmullRomCurve3(
                new THREE.Vector3(geometry.vertices[0]),
                new THREE.Vector3(geometry.vertices[1]),
                new THREE.Vector3(geometry.vertices[2]),
                new THREE.Vector3(geometry.vertices[3]),
                new THREE.Vector3(geometry.vertices[4])
             );
   ...

here is what i am trying to make
ERROR_IMG

Thank you in advance


Newton method for computing an inverse

This is following the question I asked in this thread : Link error missing vtable

I defined a class 'function' and two others classes 'polynomial' and 'affine' that inherit from 'function'.

class function {

        public:
            function(){};
            virtual function* clone()const=0;
            virtual float operator()(float x)const=0; //gives the image of a number by the function
            virtual function* derivative()const=0;
            virtual float inverse(float y)const=0;
            virtual ~function(){}

        };

        class polynomial : public function {
        protected:
            int degree;
        private:
            float *coefficient;
        public:

            polynomial(int d);
            virtual~polynomial();
            virtual function* clone()const;
            int get_degree()const;
            float operator[](int i)const; //reads coefficient number i
            float& operator[](int i); //updates coefficient number i
            virtual float operator()(float x)const;
            virtual function* derivative()const;
            virtual float inverse(float y)const;

        };

        class affine : public polynomial {
            int a;
            int b;
            //ax+b
    public:
            affine(int d,float a_, float b_);
            function* clone()const;
            float operator()(float x)const;
            function* derivative()const;
            float inverse(float y)const;
            ~affine(){}
        };

Method inverse in polyomial does not seem to work fine. It is based on the Newton method applied to the function x->f(x)-y for fixed y (the element for which we're computing the inverse) and the current polynomial f.

float polynomial::inverse(float y)const
{
    int i=0;
    float x0=1;
    function* deriv=derivative();
    float x1=x0+(y-operator()(x0))/(deriv->operator()(x0));
    while(i<=100 && abs(x1-x0)>1e-5)
    {
        x0=x1;
        x1=x0+(y-operator()(x0))/(deriv->operator()(x0));
        i++;
    }

    if(abs(x1-x0)<=1e-5)
    {
        //delete deriv; //I get memory problems when I uncomment this line
        return x1;
    }

    else
    {
        cout<<"Maximum iteration reached in polynomial method 'inverse'"<<endl;
        //delete deriv; //same here
        return -1;
    }
}

double polynomial::operator()(double x)const
{
    double value=0;
    for(int i=0;i<=degree;i++) value+=coefficient[i]*pow(x,i);
    return value;
}
polynomial* polynomial::derivative()const
{
    if(degree==0)
    {
        return new affine(0,0,0);
    }
    polynomial* deriv=new polynomial(degree-1);
    for(int i=0;i<degree;i++)
        deriv[i]=(i+1)*coefficient[i+1];
    return deriv;
}

I test this method with p:x->x^3 :

#include "function.h"

int main(int argc, const char * argv[])
{

        polynomial p(3);
        for(int i=0;i<=2;i++) p[i]=0;
        p[3]=1;
        cout<<"27^(1/3)="<<p.inverse(27);

        return 0;
}

This script outputs 27^(1/3)=Maximum iteration reached in polynomial method 'inverse'
-1 even if I put 10,000 instead of 100. I've read some articles on the internet and it seems that it's a common way to compute the inverse.


Joomla 3.2 security breach

I have the following problem on a joomla 3.2 site.

I developed the site on localhost environment using xampp with no problems.

When I moved the site on a live server it got hacked. The hacker used the the core function from joomla (add image) to insert a script that hacked the entire server.

The hacker renamed the script into a .jpg or .png extension and was able to upload it on the server. My confusion is that on localhost I am unnable to upload a script renamed into a .jpg or .png extension because it says "invalid image type", however on the live site I can upload anything as long as I rename the file with an image extension.

My question is:

How come is this possible on the live server to do this and on my localhost not?

Are there any issues with the server configuration?

PS: I checked the "add image" code on the localhost environment and on the live server and everything is the same.

The server is Apache with PHP 5.3.28.

Also I want to add that before the site was hacked the file permissions where screwed up. Now the folders are 755 and files are 644.

Thanks


Mysql find_in_set with Join not working in postgres

My mysql query is working proper in SQL database server but when i run same query in Postgres database than find set is not working.
below is my query :

SELECT omh.id as idd, omh.modified as modified, omh.modified as modified1,
DATE_FORMAT(omh.modified, '%m/%d/%Y') as only_date, DATE_FORMAT(omh.modified, '%h:%i %p') as only_time

FROM order_memo_history as omh

LEFT JOIN users as usr ON (FIND_IN_SET(usr.user_id, omh.users_id) != 0)

INNER JOIN service_order as so ON omh.order_id = so.o_id
LEFT JOIN users as u ON omh.user_id = u.user_id
WHERE (omh.modified BETWEEN "2017-09-01 06:00:00" AND "2017-10-27 05:59:00")
AND IF((so.merge_company_id='0'),(omh.company_id = 2819), ((omh.order_id = so.o_id AND omh.company_id = so.merge_company_id) OR (so.merge_company_id = 2819
        AND (omh.group_id = 2819 OR omh.group_id = '0'))))
GROUP BY idd ORDER BY modified ASC

I am getting error

ERROR:  function find_in_set(integer, text) does not exist
LINE 6: LEFT JOIN users as usr ON (FIND_IN_SET(usr.user_id, omh.user...

I have try with string_to_array but not worked


Using For loop through string +

First, I want to say that this is my first attempt at building vba code. I am trying to extract data from the web using a web query .Add(Connection,Destination,sql). What I want my code to do is to loop through the string 'str' containing stock tickers to be inserted into my url using a for loop and pasting the table data in the active sheet.

In addition, it would be an extra if I could create a new sheet for every url queried with the corresponding NYSE name.

Currently my code does not run because it is not extracting the data. I think the error is in how I am specifying the url using the loop index NYSE(i).

Thanks for any responses, advice, and suggestions.

Sub URL_Get_Query()

Dim NYSE(1 To 22) As String
NYSE(1) = "APC"
NYSE(2) = "APA"
NYSE(3) = "COG"
NYSE(4) = "CHK"
NYSE(5) = "XEC"
NYSE(6) = "CRK"
NYSE(7) = "CLR"
NYSE(8) = "DNR"
NYSE(9) = "DVN"
NYSE(10) = "ECA"
NYSE(11) = "EOG"
NYSE(12) = "XCO"
NYSE(13) = "MHR"
NYSE(14) = "NFX"
NYSE(15) = "NBL"
NYSE(16) = "PXD"
NYSE(17) = "RRC"
NYSE(18) = "ROSE"
NYSE(19) = "SD"
NYSE(20) = "SWN"
NYSE(21) = "SFY"
NYSE(22) = "WLL"
For i = 1 To 22
  Debug.Print NYSE(i)
   With ActiveSheet.QueryTables.Add(Connection:= _
      "URL;http://finance.yahoo.com/q/ks?s=NYSE(i)+Key+Statistics", _
         Destination:=Range("a1"))

      .BackgroundQuery = True
      .TablesOnlyFromHTML = True
      .Refresh BackgroundQuery:=False
      .SaveData = True
   End With
Next i
End Sub


How to make a custom markdown syntax for my markdown using remark?

I want a custom syntax for my markdown so that I can use it with my React Component. I am using using remark and remark-react to render my markdown into React components. How do a I define a custom syntax for markdown so that I can use it to render my React Component?


Sed to wrap lines in text file?

I am a newbie with Sed. I have a bunch of ASCII files containing data that's laid out like so:

Test_Version:2.6.3
Model-Manufacturer:
HR21-100
Test_Version:2.6.3
Model-Manufacturer:
D12-100

All I want to do is fold the lines for "Model-Manufacturer:" like this:

Test_Version:2.6.3
Model-Manufacturer:HR21-100
Test_Version:2.6.3
Model-Manufacturer:D12-100

I tried to use sed since I discovered there are 2 hex values (0xA for \n) after "Model-Manufacturer:"

cat myfile| sed -n "/[[:xdigit:]]\{2\}/p"

The output looked like this for my match code:

Model-Manufacturer:
HR21-100
Model-Manufacturer:
D12-100

This tells me I am on the right track, right? What I cannot figure out is the proper match/replace code to  fold the lines for "Model-Manufacturer:". A attempt with

cat myfile| sed "s/[[:xdigit:]]\{3\}//g"

completed messed up my file. Any idea how to do this?


MVVM model design

In MVVM pattern I don't want to think about the view while creating the model. So I use public properties with data stored in ILists and so on.
But then my viewmodel isn't informed of changes done to these lists on model side.
Should I use ObservableCollections in my model instead? But this seems strange to me.


post/redirect/get - how to unset session variables

Bellow is part of the code from register.php

if($_SERVER['REQUEST_METHOD'] == "POST") {

  /* running  some checks of an input*/

 if(sizeof($errorArray)==0) {
    // redirecting to avoid form resubmission
    $_SESSION['registered'] = true;
    header('location: success.php',true,303);
    }

else{
    $_SESSION['post']['email'] = $_POST['email'];
    $_SESSION['post']['name'] = $_POST['name'];
    $_SESSION['errorArray'] = $errorArray;
    header('location: register.php',true,303);
    }
}

Logic is simple -- if an errorArray is empty redirect to a success page, else redirect to register.php itself. To avoid form resubmission i tried to put post variables into session variable, so the user doesn't have to fill form again in case of error.

<?php
            if (isset($_SESSION['errorArray'])) {
                if (sizeof($_SESSION['errorArray']) != 0) {
                    echo '<div class="alert alert-danger" role="alert">
                    <h4>There were errors in Your input:</h4>';
                    foreach ($_SESSION['errorArray'] as $item) {
                        echo $item . '<br>';
                    }
                }
                $_SESSION['post'] = null;
                $_SESSION['errorArray'] = null;
            }
 ?>

This part of a code is executed later in register.php but it doesen't gives me the result I want. Somehow the variables are sett to null before the loop above is executed (??!).  I have found a solution  with get method that includes microtime in url passed to header , but it seams to me that there is more elegant solution that does not every time adds new values to a session variable.

Is there some way around this?

edit :

    <?php
session_start();
if ($_SERVER['REQUEST_METHOD'] == "POST") {

    // array to hold all the errors of input
    $errorArray = [];
    $emailRegex = '/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/';
    $nameRegex = '/^[a-z0-9][a-z0-9_]*[a-z0-9]$/';
    $passwordRegex = '/^[a-z0-9][-a-z0-9_!@#$?]*[a-z0-9]$/';

    $email = $_POST['email'];
    if (empty($email)) {
        array_push($errorArray, "E-mail field required");
    } else {
        if (!preg_match($emailRegex, $email)) array_push($errorArray, 'Invalid email');
    }
    $name = $_POST['name'];
    if (empty($name)) {
        array_push($errorArray, "Name field required");
    } else {
        if (!preg_match($nameRegex, $name)) array_push($errorArray, 'Invalid name');
    }

    $password = $_POST['password'];
    $passwordR = $_POST['passwordR'];

    if (empty($passwordR) || empty($password)) {
        array_push($errorArray, 'Password fields required');
    } else if (!preg_match($passwordRegex, $password)) {
        array_push($errorArray, 'Invalid password');
    } else {
        if ($password !== $passwordR) {
            array_push($errorArray, 'Password inputs are not the same');
        }
    }

    if (sizeof($errorArray) == 0) {
        // redirecting to avoid form resubmission
        $_SESSION['registered'] = true;
        header('location: success.php', true, 303);
    } else {
        $_SESSION['post']['email'] = $_POST['email'];
        $_SESSION['post']['name'] = $_POST['name'];
        $_SESSION['errorArray'] = $errorArray;
        header('location: register.php', true, 303);
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Log</title>
    <link rel="stylesheet" href="css/bootstrap.min.css" type="text/css">
    <link rel="stylesheet" href="css/maincss.css" type="text/css">
    <meta name="viewport" content="width = device-width, initial-scale = 1, user - scalable = no">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script src="js/bootstrap.min.js"></script>
</head>
<body>

<nav class="navbar navbar-default navbar-fixed">
    <div class="container">
        <a href="index.php" class="navbar-brand col-xs-5">Home</a>
        <ul class="navbar-brand col-xs-5"><?= (isset($username)) ? 'Welcome ' . $username : ''; ?></ul>
        <a href="login.php" class="navbar-brand col-xs-1">Login</a>
        <a href="register.php" class="navbar-brand col-xs-1">Register</a>
    </div>
</nav>

<div class="container">

    <form class="form-signin" action="register.php" method="post">
        <h2 class="form-signin-heading text-center text-capitalize">Registration form</h2>
        <!-- I have purposely excluded required attribute from inputs and set type="text"
        for an email so all the checks could be done on server side -->
        <div class="row center-block">
            <div class="col-xs-4"></div>
            <div class="col-xs-4">
                <label for="email" class="sr-only">Email address</label>
                <input type="text" id="email" name="email" class="form-control" placeholder="Email address"
                       value="<?= (isset($_SESSION['post']['email'])) ? $_SESSION['post']['email'] : ''; ?>" autofocus>
            </div>
            <div class="col-xs-4"></div>
        </div>
        <br>
        <div class="row center-block">
            <div class="col-xs-4"></div>
            <div class="col-xs-4">
                <label for="name" class="sr-only">Name</label>
                <input type="text" id="name" name="name" class="form-control" placeholder="Name"
                       value="<?= (isset($_SESSION['post']['name'])) ? $_SESSION['post']['name'] : ''; ?>" autofocus>
            </div>
            <div class="col-xs-4"></div>
        </div>
        <br>
        <div class="row center-block">
            <div class="col-xs-4"></div>
            <div class="col-xs-4">
                <label for="password" class="sr-only">Password</label>
                <input type="password" id="password" name="password" class="form-control" placeholder="Password">
            </div>
            <div class="col-xs-4"></div>
        </div>
        <br>
        <div class="row center-block">
            <div class="col-xs-4"></div>
            <div class="col-xs-4">
                <label for="passwordR" class="sr-only">Repeat Password</label>
                <input type="password" id="passwordR" name="passwordR" class="form-control"
                       placeholder="Repeat Password">
            </div>
            <div class="col-xs-4"></div>
        </div>
        <br>
        <div class="row">
            <div class="col-xs-4"></div>
            <div class="col-xs-4 center-block">
                <button class="btn btn-lg btn-primary btn-block" type="submit">Submit</button>
            </div>
            <div class="col-xs-4"></div>
        </div>
        <br>
        <div>
            <?php
            if (isset($_SESSION['errorArray'])) {
                if (sizeof($_SESSION['errorArray']) != 0) {
                    echo '<div class="alert alert-danger" role="alert">
                    <h4>There were errors in Your input:</h4>';
                    foreach ($_SESSION['errorArray'] as $item) {
                        echo $item . '<br>';
                    }
                }
                // $_SESSION['post'] = null;
                // $_SESSION['errorArray'] = null;
            }
            ?>
        </div>

    </form>
</body>
</html>


Annoying mysql update query problem

I'm trying to update using mysql_query in php and it gives me this error:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'read='1' WHERE id='14'' at line 1

I've been looking at my query for about 10 minutes now and I cant find whats wrong with it. Here it is:

    if ($row['read'] == 0) {
        mysql_query("UPDATE mail SET read='1' WHERE id='$mailid'") or die(mysql_error());
    }

Do anyone see where the error is?


Interrupt based Soft_Uart with MikroC libraries

Is there any way to use MikroC Pro for PIC libraries to make an interrupt on change based soft_uart?

bytes read by the below routine are rubbish. I am using a 20MHz crystal, and will try a 32MHz one when I get one.

char error, data_;

void interrupt(){
  if (IOCAF.IOCAF2){
    do{
      data_ = Soft_Uart_Read(&error);
    }while(error);
    Soft_Uart_Write(data_);
    IOCAF.IOCAF2 = 0;
  }
}

void main() {
  //set RA2, pin 11, as input
  TRISA = 0b001100;
  TRISC = 0;
  ANSELA = 0;
  ANSELC = 0;
  //enable interrupts
  INTCON.GIE = 1;
  //enable interrupt on change
  INTCON.IOCIE = 1;
  //Clear all IOC flags in PORTA
  IOCAF = 0;
  //enable rising edge detection on RA2, pin 11
  IOCAP.IOCAP2 = 1;
  //Initialise software uart Pin11 = Rx, Pin12 = Tx
  error = Soft_Uart_Init(&PORTA, 2,1,9600,0);
}


Dynamic nested json string to java object using jackson

i have trouble in parsing json

I have a nested json string, i need to convert to java object , the string look like this, i want to ask how to handle this nested dynamic json using jackson, how to decode dynamic nested json string

{

"resultCode": "0",
"dataObject": [
    {
        "lastSyncDate": "20140101000000",
        "count": 2,
        "refType": "ADO",
        "update": [
            {
                "artist": "C",
                "albumTitle": "道",
                "productTitle": "道",
                "thumbnail": "http://w.com/mposter/album/m/VACL00020880A_m.jpg",
                "lastSyncDate": "20140425120159",
                "refId": "VACL00214522"
            },
            {
                "artist": "楊",
                "albumTitle": "學",
                "productTitle": "美",
                "thumbnail": "http://m.jpg",
                "lastSyncDate": "20140324161831",
                "refId": "VACP00168673"
            }
        ],
        "delete": [ ]
    },
    {
        "lastSyncDate": "20140101000000",
        "count": 8,
        "refType": "PAT",
        "update": [
            {
                "artist": "方",
                "thumbnail": "http://t.com/moov/images/profile/PAT/8/70/00021870_tn_1_s.jpg",
                "lastSyncDate": "20140201010203",
                "refId": "00021870"
            },
            {
                "artist": "楊",
                "lastSyncDate": "20140328120831",
                "refId": "00000125"
            },
            {
                "artist": "陳",
                "thumbnail": "http://s.jpg",
                "lastSyncDate": "20140328185030",
                "refId": "00017704"
            }
        ],
        "delete": [ ]
    },
    {
        "lastSyncDate": "20140101000000",
        "count": 4,
        "refType": "PAB",
        "update": [
            {
                "artist": "陳",
                "albumTitle": "The Key",
                "thumbnail": "http:/m.jpg",
                "lastSyncDate": "20140603143528",
                "refId": "VAUN00031629A"
            },
            {
                "artist": "何",
                "albumTitle": "梁",
                "thumbnail": "http://m.jpg",
                "lastSyncDate": "20140603143528",
                "refId": "VAEA00003170A"
            },
            {
                "artist": "何",
                "albumTitle": "艷",
                "thumbnail": "http://m.jpg",
                "lastSyncDate": "20110603151452",
                "refId": "VAEA00003179A"
            }
        ],
        "delete": [ ]
    },
    {
        "lastSyncDate": "20140101000000",
        "count": 4,
        "refType": "PP",
        "update": [
            {
                "chiName": "其",
                "engName": "Other",
                "lastSyncDate": "20140130010203",
                "chiAuthor": "",
                "engAuthor": "",
                "refId": "PP1000000003"
            },
            {
                "chiName": "演",
                "engName": "E演",
                "thumbnail": "http://s.jpg",
                "lastSyncDate": "20140126010758",
                "chiAuthor": "專",
                "engAuthor": "Recommended",
                "refId": "PP1000000040"
            },
            {
                "chiName": "日本派台歌",
                "engName": "Japan New Releases",
                "lastSyncDate": "20140126010758",
                "chiAuthor": "",
                "engAuthor": "",
                "refId": "PP1000000057"
            },
            {
                "chiName": "9",
                "engName": "9",
                "thumbnail": "http://s.jpg",
                "lastSyncDate": "20140126010203",
                "chiAuthor": "專",
                "engAuthor": "Recommended",
                "refId": "PP1000000048"
            }
        ],
        "delete": [ ]
    }
]

}


How do I mark conflicts as resolved in the git GUI tool?

I'm trying to merge changes from a feature branch into the development branch of my project. I use both the GitHub GUI app for Mac OS X as well as the command line to manage my git projects. For a long time, I've been able to manage merge conflicts with the command line, but I have no idea if and how to do the same thing in the GUI client. Even if I resolve the conflicts in BBEdit and then click the "Commit" button, it still says:

•error: 'commit' is not possible because you have unmerged files.
hint: Fix them up in the work tree,
hint: and then use 'git add/rm <file>' as
hint: appropriate to mark resolution and make a commit,
hint: or use 'git commit -a'.
fatal: Exiting because of an unresolved conflict.
 (128)

How can I resolve this without resorting to the command line?


Python - validate a url as having a domain name or ip address

I need to validate a url in Python and ensure that the host/netloc component is a domain name or ip v4/v6 address.

Most StackOverflow Q&As on this general topic say to "just use urlparse".  That is not applicable to this situation.

I have already used urlparse to validate that I do indeed have a url.

The problem is that I need to further validate the .netloc from urlparse to ensure that I am getting a Domain Name OR IP Address, and not just a hostname.

Let me illustrate:

>>> from urlparse import urlparse

This works as expected / desired :

>>> ## domain name
>>> print urlparse("http://example.com").netloc
example.com

>>> ## ipv4
>>> print urlparse("http://255.255.255.255").netloc
255.255.255.255

>>> ## acceptable hostname
>>> print urlparse("http://localhost").netloc
localhost

But I often run into typos that will let a malformed URL slip through.  Someone might accidentally miss a '.' in a domain name:

>>> ## valid hostname, but unacceptable
>>> print urlparse("http://examplecom").netloc
examplecom

examplecom is indeed a valid hostname, and could exist on a network, but it is not a valid domain name.

There also doesn't seem to be any rules enforced for IP Addresses  :

>>> print urlparse("http://266.266.266.266").netloc
266.266.266.266

>>> print urlparse("http://999.999.999.999.999").netloc
999.999.999.999.999


XSL syntax to only copy with more than one word

I have large XML files that must be trimmed to exclude specific nodes, and use xsl:template match statements to identify some for exclusion.

But what syntax can I use to exclude or include based on number of words?

Example: this is used to exclude string nodes where the content of instring is identical to the content of outstring

<xsl:template match="string[instring=outstring]"/>

I need to change that to only match if it is also the case that there is more than one word in instring and outstring.

Pseudo syntax now is: exclude string nodes where instring = outstring
Pseudo syntax needed is: exclude string nodes where instring = outstring AND instring/outstring is more than one word   (i.e. keep those identical strings, if they are just one word)


Magento: Rewriting Mage_Eav_Model_Entity_Type

I'm trying to override Magento order number creation by rewriting class Mage_Eav_Model_Entity_Type.

app/code/local/Custom/MyModule/Model/Entity/Type.php:

<?php
class Custom_MyModule_Model_Entity_Type extends Mage_Eav_Model_Entity_Type {
    public function fetchNewIncrementId($storeId = null) {
        $incrementId = parent::fetchNewIncrementId($storeId);
        $incrementId = 'test' . $incrementId;
        return $incrementId;
    }
}

But what should I write to app/code/local/Custom/MyModule/etc/config.xml? See TODO1 and TODO2 below.

<?xml version="1.0"?>
<config>
  <modules>
    <Custom_MyModule>
      <version>1.0.0</version>
    </Custom_MyModule>
  </modules>
  <global>
    <models>
      <TODO1>
        <rewrite>
          <TODO2>Custom_MyModule_Model_Entity_Type</TODO2>
        </rewrite>
      </TODO1>
    </models>
  </global>
</config>


Linked List sorting error

This code is supposed to sort through a list of 6 elements, ignoring the first. For some reason, I always get an error stating "TypeError: 'NoneType' object is not subscriptable". If anyone could offer me a solution or explain a fix to me that would be much appreciated.

def bubbleSortLinkedList(aLinkedList):
    pointer = aLinkedList
    swapped = True
    while swapped:
        pointer = aLinkedList['next']
        swapped = False
        for i in range(4):
            if pointer['data'] > pointer['next']['data']:
                pointer['data'], pointer['next']['data'] = pointer['next']['data'], pointer['data']
                swapped = True
            pointer = pointer['next']
        aLinkedList = pointer
    return aLinkedList


Checkbox - check add text, uncheck remove original text in text area

<script language="javascript" type="text/javascript">

function moveNumbers(num) {
   var txt=document.getElementById("result").value;
   txt=txt + num;
   document.getElementById("result").value=txt;
}
</script>

<textarea id="result" name="image_id" rows="8" cols="11" readonly>

</textarea>
<tr>

    <?php
        $path = "photos/";
        $dir_handle = @opendir($path) or die("Unable to open folder");
        echo "<table height='500px'width='800px'align='center'border='1'>";
        echo "<tr>";
        while (false !== ($file = readdir($dir_handle))) {

          if($file == "index.php")
          continue;
          if($file == ".")
          continue;
          if($file == "..")
          continue;

          echo ($x % 6 == 0) ? "</tr><tr>" : "";
          echo "<td><input type='checkbox' name='add' value='$file'
          onclick='moveNumbers(this.value)'>
          <img src='photos/$file'alt='$file' style='height:auto;width:50%;'alt='$file'>
          <br>
          $file
          </td>";
          $x++;
       }
       echo "</tr>";
       echo "</table>";
       closedir($dir_handle);
   ?>

Hi all, having some trouble with the check boxes. Click on the check box, text appears in text area no problem. I have been trying to figure out how to when you uncheck the check box the text is removed. E.G. Checked -> Text 123 inputted, Uncheck -> Test 123 removed.
Cheers.


C# Display 2 decimal places

I cant figure out how to display 2 decimal within this code. Below is a code show when i chose the option from combobox1 and combobox2 then i key any value to textbox2, so it will store the new value. And also if i chose back the same option from combobox1 and combobox2 it will auto take 1/textBox2.Text. But i want to display only 2 decimal places. Can anyone help out with this code?

Thanks

            int index1 = comboBox1.SelectedIndex;
            int index2 = comboBox2.SelectedIndex;
            arr[index1, index2] = double.Parse(textBox2.Text);
            arr[index2, index1] = (1 / double.Parse(textBox2.Text));
            MessageBox.Show("Your Current Rate Have Been Updated");


Switch from Synchronous request to Asynchronous request with image upload?

I need some help, i have been searching around and cant find the correct answer im looking for.

I am uploading images and videos to my server via php, When im uploading the video or image, i want to be able to show a progress view, i have been told that the only way to do this is to use asynchronous instead of synchronous. I have been looking at ways to set up this, but cant really seem to find a good tutorial that will help me with what im trying to accomplish.

Here is some code:

- (void)post:(NSData *)fileData
{

NSMutableArray *array = [[NSMutableArray alloc]initWithContentsOfFile:[self saveUserLogin]];

int test;
NSString *string = [array objectAtIndex:3];
test = [string intValue];
test++;
NSData *videoData = fileData;
NSString *urlString = [[NSString alloc]initWithFormat:@"http://www.site.com/members/uploadMovie.php?&username=%@", [array objectAtIndex:0]];

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:@"POST"];

NSString *boundary = [NSString stringWithString:@"---------------------------14737809831466499882746641449"];
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary];
[request addValue:contentType forHTTPHeaderField:@"Content-Type"];

NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
NSString *postName = [[NSString alloc]initWithFormat:@"Content-Disposition: form-data; name=\"userfile\"; filename=\"vid%i.mov\"\r\n", test];
[body appendData:[[NSString stringWithString:postName] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:videoData]];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];

NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];

NSLog(@"%@", returnString);

NSArray *values = [[NSArray alloc] initWithObjects: [array objectAtIndex:0],[array objectAtIndex:1], [array objectAtIndex:2], [NSString stringWithFormat:@"%i", test], nil];
[values writeToFile:[self saveUserLogin] atomically:YES];
[self.delegate didFinishController:self];
}

this is some code that im using to send a video. filedata is a paramater being passed in with the video data. I want to animate a UIProgressview for the upload progress. I have also heard that apple likes people to use asynchronous anyways. If someone could please help me set up asynchronous instead of what i have, i would be really grateful. Please be specific if you reply, like to what i need to import what delegates, methods. etc.

Thank you very much :)

EDIT:

This is what it looks like now:

- (void)post:(NSData *)fileData
{

NSMutableArray *array = [[NSMutableArray alloc]initWithContentsOfFile:[self saveUserLogin]];

int test;
NSString *string = [array objectAtIndex:3];
test = [string intValue];
test++;
NSData *videoData = fileData;
NSString *urlString = [[NSString alloc]initWithFormat:@"http://www.site.com/members/uploadMovie.php?&username=%@", [array objectAtIndex:0]];

NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:urlString] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30];

NSString *boundary = [NSString stringWithString:@"---------------------------14737809831466499882746641449"];
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary];
[request addValue:contentType forHTTPHeaderField:@"Content-Type"];

NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
NSString *postName = [[NSString alloc]initWithFormat:@"Content-Disposition: form-data; name=\"userfile\"; filename=\"vid%i.mov\"\r\n", test];
[body appendData:[[NSString stringWithString:postName] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:videoData]];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];

//NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
//NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
if (connection) {
    NSLog(@"connected");
    responceData = [NSMutableData data];

}
else{
    NSLog(@"error");
}
//  NSLog(@"%@", returnString);

NSArray *values = [[NSArray alloc] initWithObjects: [array objectAtIndex:0],[array objectAtIndex:1], [array objectAtIndex:2], [NSString stringWithFormat:@"%i", test], nil];
[values writeToFile:[self saveUserLogin] atomically:YES];
   // [self.delegate didFinishController:self];
}

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

- (void) connectionDidFinishLoading:(NSURLConnection *)connection {

NSString* responseString = [[NSString alloc] initWithData:responceData     encoding:NSUTF8StringEncoding];
NSLog(@"result: %@", responseString);

}

- (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog(@"error - read error object for details");
}


Referencing a Workbook variable in IF formula

I have a macro which is comparing numbers between two workbooks and outputting if it's correct or incorrect.
One of the workbooks is stored as a variable as it references last month in it's name.

Dim wb As Workbook
Set wb = Workbooks("Monthly Life Management Report " & Format(DateAdd("m", -1, Date), "mmmm yyyy") & ".xlsm")

I am getting a application or object defined error when running the final part of the macro.

 Range("E8").Select
ActiveCell.FormulaR1C1 = _
"=IF([wb]'2 Claims'!R8C5 =[Template.xlsx]Claims!R8C5,""Correct"",""Incorrect"")"

Entire Script

Sub Monthly_Life_Management()

Dim thisWb As Workbook
Set thisWb = ActiveWorkbook
Workbooks.Add
ActiveWorkbook.SaveAs Filename:=thisWb.Path & "\Validation_File_" & Format(Date, "dd mm yy") & ".xls"

Dim wb As Workbook
Set wb = Workbooks("Monthly Life Management Report " & Format(DateAdd("m", -1, Date), "mmmm yyyy") & ".xlsm")

'Claims Tab
 wb.Activate
 Sheets("2 Claims").Select

 Range("C2:C13").Select
 Application.CutCopyMode = False
 Selection.Copy
 Windows("Validation_File_" & Format(Date, "dd mm yy") & ".xls").Activate
 Range("C2").Select
 ActiveSheet.Paste

 wb.Activate
 Sheets("2 Claims").Select
 Range("D2:D13").Select
 Application.CutCopyMode = False
 Selection.Copy
 Windows("Validation_File_" & Format(Date, "dd mm yy") & ".xls").Activate
 Range("D2").Select
 ActiveSheet.Paste

 wb.Activate
 Sheets("2 Claims").Select
 Range("E7:G7").Select
 Application.CutCopyMode = False
 Selection.Copy
 Windows("Validation_File_" & Format(Date, "dd mm yy") & ".xls").Activate
 Range("E7").Select
 ActiveSheet.Paste

'Counts
 Range("E8").Select
 ActiveCell.FormulaR1C1 = _
"=IF('[wb]2 Claims'!R8C5 ='[Template.xlsx]Claims'!R8C5,""Correct"",""Incorrect"")"

 Cells.Select
 Selection.Copy
 Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False

End Sub


How to Append/Queue Media File to the Current Media Player program in C#.net?

I used:

System.Diagnostics.Process.Start(@"D:\Song1.mp3");

It played the MP3 file with my default Media Play (e.g Window Media Player);

I have another MP3 File (e.g D:\Song2.mp3) that i want to append/queue to the current Media Player. Anyone please tell me how to do this?


Maven: Build dependencies with dynamic params on persistence.xml file when main project is been compiled

I am a new maven user.

I am developing differents projects that depends on a maven project that needs to connect to db using JPA. So, for each parent project I need to set the db URL, user name and password on persistence.xml on dependent project.

I want to know if there is a way to recompile the dependency setting this values dynamically on persistence.xml while one of parent projects.

Thanks in advance


Hide VSTS/TFS extension's Summary section when extension not added to build task

We have developed VSTS/TFS extension which consists summary page with details generated from our extension task, at the end of build.

we have added contribution similar to below in manifest file  to add this summary section

{
            "id": "build-status-section",
            "type": "ms.vss-build-web.build-results-section",
            "description": "A section contributing to our own new tab and also to existing build 'summary' tab",
            "targets": [
                ".build-info-tab",
                "ms.vss-build-web.build-results-summary-tab"
            ],
            "properties": {
                 "name": "Custom Section",
                 "uri": "statusSection.html",
                 "order": 20,
                 "height": 500
            }
        }

However currently we are facing issue as even when user not add our extension task in to his build our summary page will appear in summary tab (if our extension is installed and enabled).

Is there any way to avoid displaying summary section when our task is not added to their build. Please be kind enough to help on this.


Is it possible to create a variable data type in Assembly?

I'm studying (slowly) x86 assembly and one thing I'd like to know is:

Is it possible for me to create a variable data type like a 16 byte integer?

Or do I only have access to db (8 bits), dw (2 bytes) and dd (4 bytes)?


pandas filling date gaps and overwrite with function

I have a big data frame with 2 groups: score and day.
Is there a simple possibility with pandas tools to fill the gaps and the missing scores with the average (alternative ewma etc..) of the values before.

First of all I group overwrite the scores by grouping and later stack the
modified grouped df's together.

 dfg = df.groupby(['g1','g2'])
 for name , group in dfg:
    print group
    break

 ix               g1           g2   score      day
 4                19           24    4.150513  2014-02-12
 5                19           24    6.986235  2014-02-13
 6                19           24    9.634231  2014-02-14
 7                19           24    1.818548  2014-02-15
 8                19           24    1.699897  2014-03-02
 9                19           24    2.128781  2014-03-25
 10               19           24    1.720297  2014-03-26
 14               19           24    2.079877  2014-03-30


I want to copy a folder from Google drive and paste it somewhere else on my hard drive. When I do this, the folder icon looks like the folder is still associated with Google drive. How can I copy a Google drive folder and remove Google drive association?


how to change actionbar's menu item text color in material design

I'm trying to update my notepad app to use Material Design, even on older devices.

What i did so far:

add library appcompat_v7 to my project, to support Material Design on older devices

modify theme in AndroidManifest, adding android:theme="@style/Theme.NoteItTheme" to <application ... ></application> attributes

creating the theme in /res/values/themes.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources xmlns:android="http://schemas.android.com/apk/res/android">
   <style name="Theme.NoteItTheme" parent="Theme.AppCompat.Light">
    <!-- Here we setting appcompat’s actionBarStyle -->
    <!-- <item name="actionBarStyle">@style/MyActionBarStyle</item> -->

    <!-- ...and here we setting appcompat’s color theming attrs -->
    <item name="colorPrimary">@color/primary</item>
    <item name="colorPrimaryDark">@color/primary_dark</item>
    <item name="android:textColorPrimary">@color/text</item>
    <item name="colorAccent">@color/ui</item>

    <!-- The rest of your attributes -->
</style>

The problem:

As you can better see here:

when i expand the actionbar's menu, text color and background color are very similar.
I hadn't this problem before, how do i change just the items text color?


Android Custom Content View

I've made a custom layoutView instead of a built in xml that comes with each Android activity. So onCreate in my MainActivity I've set:

    setContentView(mainActivity_layoutView);

mainActivity_layoutView is my custom layout java class. I made that layout so I could do my own custom animations. Now here is the question:
Since mainActivity_layoutView is a java class, how do I add a button to my custom layout? Typically if you are referencing the xml file, you would just add this line "button.findViewById(R.id.mybutton);", but I am not using the xml file, I'm using my custom java class, so how would I go about adding a button to it? Thanks...


Streaming or custom Jar in Hadoop

I'm running a streaming job in Hadoop (on Amazon's EMR) with the mapper and reducer written in Python. I want to know about the speed gains I would experience if I implement the same mapper and reducer in Java (or use Pig).

In particular, I'm looking for people's experiences on migrating from streaming to custom jar deployments and/or Pig and also documents containing benchmark comparisons of these options. I found this question, but the answers are not specific enough for me. I'm not looking for comparisons between Java and Python, but comparisons between custom jar deployment in Hadoop and Python-based streaming.

My job is reading NGram counts from the Google Books NGgram dataset and computing aggregate measures. It seems like CPU utilization on the compute nodes are close to 100%. (I would like to hear your opinions about the differences of having CPU-bound or an IO-bound job, as well).

Thanks!

Amaç


How to send an object to the Telerik MVC Grid Ajax Select() Controller Method

I am using the Telerik MVC Grid with Ajax binding, and am having a problem passing an object to the controller to be used to filter data.  I am able to pass simple data (string, int), but not a more complex object.

For instance, I can to this no problem:

.DataBinding(dataBinding => dataBinding.Ajax().Select("_CasesAjaxBinding", "Home", new {orderId = "12345"} ))

And then in my controller, handle the orderId like this:

public ActionResult _CasesAjaxBinding(string orderId)

The problem I am having is when I try to pass a more complex object (in this case the @Model) to the controller, like this (The @Model is type CaseFilterModel):

.DataBinding(dataBinding => dataBinding.Ajax().Select("_CasesAjaxBinding", "Home", new {filterSpec = @Model} ))

And then trying to handle the object, like this:

public ActionResult _CasesAjaxBinding(CaseFilterModel filterSpec)

The filterSpec parameter is always null.

Thanks in advance for any ideas!


decimal issue when adding a flat fee

I have a small issue I believe the code is doing exactly what its suppose to be doing I have a function whereby I pass in an amount and I add a flat fee of 40 cents to it for the surcharge.

Below is how my current code is constructed

Double surcharge;
surcharge = 0.4 * moneyIn / 100;

If I pass 999.00m in as moneyIn it returns 0.3996 when in fact it should return 0.4 I'm unsure what I need to do to make it be 0.4 I'm learning percentages within c# so please bare with me.


How to add delete button in my php rows

I am new to php coding.

I am adding each row delete button but it should not working please help me.

This is my html code:

<!DOCTYPE html>
<html>
<head>
</head>
<body>
<?php
    $connection = mysql_connect('localhost', 'root','');
if (!$connection)
{
    die("Database Connection Failed" . mysql_error());
}
$select_db = mysql_select_db( "emp",$connection);
if (!$select_db)
{
    die("Database Selection Failed" . mysql_error());
}
    $sql = "SELECT * FROM venu ";
    $result = mysql_query($sql) or die(mysql_error());
    ?>
    <table border="2" style= " margin: 0 auto;" id="myTable">
      <thead>
        <tr>
          <th>name</th>
          <th>id</th>
          <th>rollnumber</th>
          <th>address</th>
          <th>phonenumber</th>
        </tr>
      </thead>
      <tbody>
      <?php
            while($row = mysql_fetch_array($result))
            {
              echo "<tr>";
                echo "<td>" . $row['name'] . "</td>";
                echo "<td>" . $row['id'] . "</td>";
                echo "<td>" . $row['rollnumber'] . "</td>";
                echo "<td>" . $row['address'] . "</td>";
                echo "<td>" . $row['phonenumber'] . "</td>";
               echo "<td><form action='delete.php' method='POST'><input type='hidden'  value='".$row["address"]."'/><input type='submit' name='submit-btn' value='delete' /></form></td></tr>";
                echo "</tr>";

            }
            ?>
            </tbody>
            </table>
    </body>
    </html>

This is my delete php code:

<?php
$connection = mysql_connect('localhost', 'root','');
if (!$connection)
{
    die("Database Connection Failed" . mysql_error());
}
$select_db = mysql_select_db( "emp",$connection);
if (!$select_db)
{
    die("Database Selection Failed" . mysql_error());
}
    error_reporting(0);
    session_start();
    $name = $_POST['name'];
    $id = $_POST['id'];
    $rollnumber = $_POST['rollnumber'];
    $address = $_POST['address'];
    $phonenumber = $_POST['phonenumber'];
    if($name!='' and $id!='')
    {
        $sql = mysql_query("DELETE FROM 'venu' WHERE name='balaji'AND id='93'AND rollnumber='93'AND address='bangalore'AND phonenumber='1234567890'");
    echo "<br/><br/><span>deleted successfully...!!</span>";
}
else{
echo "<p>ERROR</p>";
}
mysql_close($connection);
?>

I am trying to delete each row using button but should not working please help me.


Android Studio - Error Building - Android tasks have already been created

Getting the following error when building the project:

Error:(2, 0) Android tasks have already been created.
This happens when calling android.applicationVariants,
android.libraryVariants or android.testVariants.
Once these methods are called, it is not possible to
continue configuring the model.

Root build.gradle:

buildscript {
      repositories {
        jcenter()
      }
      dependencies {
        classpath 'com.android.tools.build:gradle:1.1.0'
      }
}
apply plugin: 'android'

android {
    compileSdkVersion 'Google Inc.:Google APIs:19'
    buildToolsVersion '19.1.0'
    defaultConfig {
       versionCode 5
       versionName '5'
       targetSdkVersion 19
       minSdkVersion 10
       applicationId 'tsp.movil'
    }
}
dependencies {
     compile 'com.google.android.gms:play-services:7.0.0'
     compile 'com.android.support:support-v4:22.1.1'
}

App build.gradle:

android {
     compileSdkVersion 'Google Inc.:Google APIs:19'
     buildToolsVersion '19.1.0'
     defaultConfig {
        applicationId "tsp.movil"
        minSdkVersion 10
        targetSdkVersion 19
        versionCode 5
        versionName '5'
     }
     buildTypes {
         release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'),      'proguard-rules.txt'
         }
     }
     productFlavors {
     }
}
dependencies {
    compile 'com.android.support:support-v4:19.1.0'
    compile 'com.google.android.gms:play-services:+'
    compile files('libs/zbar.jar')
}


ReactJS: What is the correct way to set a state value as array?

I have an array of object that get users data using fetch API. I have tried constructor, create a function, bind it. It didn't work. I tried ComponentDidMount and setState, it returns undefined.

class Admin extends Component {

    componentDidMount () {

        var that = this;
        fetch('http://localhost:4500/data/users', {
            method: 'GET',
            headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
            }
         }).then(function(response) {
             return response.json();
        }).then(function(json){
             console.log(json);
             that.state = {users: json};
        });

    }

    render() {

     return (

        <SpicyDatatable
          tableKey={key}
          columns={columns}
          rows={this.state.users}
          config={customOptions}
        />
       );
    }
}

What is the correct way to set a state value as array and render it? Thanks


How to debug startup exceptions with service hosted in IIS?

I have my service running in IIS. I have a non fatal exception occurring and being logged on startup.

How do I attach Visual Studio to IIS so that it also debugs the startup?

I know I can attached visual studio to the w3wp.exe to debug while its running.


passing arraylist of bitmap from activity to another

I have an android where i want to pass a arraylist of bitmap from one activity to andother .how can i do that.

ArrayList<String> questionArray;

 ArrayList<Bitmap>questionBitmap=new ArrayList<Bitmap>(); questionBitmap=loadBitmapFromAllArray(questionArray);public ArrayList<Bitmap> loadBitmapFromAllArray(ArrayList<String> questionArray)
    {
        URL questionUrl = null;
        ArrayList<Bitmap>questionBitmap=new ArrayList<Bitmap>();
         for(int b =0; b <questionArray.size(); b+=1)
            {
                String questionSource=questionArray.get(b);
                try
                {
                     questionUrl=new URL(questionSource);
                }
                catch (MalformedURLException e)
                {
                    e.printStackTrace();
                }
                questionBitmap.add(getRemoteImage(questionUrl));
            }
        return questionBitmap;
    }
     public Bitmap getRemoteImage(final URL aURL) {
         try {
                 final URLConnection conn = aURL.openConnection();
                 conn.connect();
                 final BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());
                 final Bitmap bm = BitmapFactory.decodeStream(bis);
                 bis.close();
                 return bm;
         }
         catch (IOException e)
         {
         }
         return null;
 }


why must a fragment accompany a different activity

ActivityA launches fragmentA. I need to launch fragmentB. There are 2 ways of doing it, but I dont know which is the best way First way, create a ActivityB which would launch FragmentB. Therefore, ActivityA--> ActivityB--> FragmentB.

The second way, is just replacing FragmentA with FragmentB

Fragment b = AddRecordFragment.init(Integer.valueOf(f.getId()));
getFragmentManager().beginTransaction().replace(R.id.container,b).addToBackStack(null).commit();

When I took the Udacity course, they perferred the first way, but I cant see the logic in creating an second activity (activityB) for the mere purpose of launching an Fragment. Can you tell me what is the advantages and disadvantages to each ?


How to print vector class type contents

I am having problem to print out the vector that hold my person info.

struct PersonInfo{

    string name;
    vector<string> phones;
};

int main(){

    string line, word;
    vector<PersonInfo> people;
    while(getline(cin, line)){
        PersonInfo info;
        istringstream record(line);
        record >> info.name;
        while(record >> word)
            info.phones.push_back(word);
        people.push_back(info);

    }
    for(auto i = people.begin(); i != people.end(); i++)
         cout << people << endl;
    return 0;
}


How to map a command to multiple edits

I'm using the plugin vim-surround, which maps ds( to "delete surrounding brackets", e.g. turns (Hello) into Hello. I want to map a command to delete a function appliction, e.g. turning foo(bar) into bar.

I tried

nmap <Leader>df bdt(ds(

to go to the beginning of the word, delete up to the first (, and then delete the surrounding parentheses. However, when I use it, it only deletes up to the bracket, and doesn't do the subsequent deletion of the brackets themselves. I've tried putting other editing commands after the initial part, and that works. So

nmap <Leader>df bdt(x

works as expected.

Similarly, I tried just doing

nmap <Leader>s ds(

and that also works!

Other things that don't work:

nmap <Leader>df bdt(<bar>ds(

Does anyone know how I can make this work?


C++ Protected / Public overloads

I have a class like this :

class Foo
{
public:
    Foo()
    {
        for(int i = 0; i < 10; ++i)
            v.push_back(i);
    };
    const vector<double>& V() const {return v;};
protected:
    vector<double>& V() {return v;};
private:
    vector<double> v;
};

And then a piece of code like this :

Foo foo;
for(int i = 0; i < (int) foo.V().size(); ++i)
    cout << foo.V().at(i) << endl;

However, the latter raises a compilation error saying the V() call is a protected method while i am just trying to read from it, not modify it.

I have tried the following (but without success).

Foo foo;
const vector<double>& test = foo.V();
for(int i = 0; i < (int) test.size(); ++i)
    cout << test.at(i) << endl;

Many thanks for your help.

=====

Thank you all for the explanations and solutions ! It's greatly appreciated !


How do I decompose a number into powers of 2?

I'm trying to create a function that receives a number as an argument and performs actions on that number to find out its closest powers of 2 that will then add up to that number. For example, if the user enters 4, the function will append 4 because it is already a power of 2. If the user enters a 14 the function should see that 14 is not a power of 2 and the closest powers of 2 that make up 14 are 2,4, and 8.

Key notes:
I am only going up to 2^9.

What i have so far:

def powers_finder(n):
    powers=[]
    i=0
    total=0
    while i<10:
         value=2**i
         total=total+value
         i=i+1
         #This if statement is for if the user enters a power of 2 as n
         #Then the number will be appended right away into my powers list.
         if value==n:
            powers.append(value)

The problem here being if the user enters in lets say 5 as (n) 5 is made up of the power 2^2=4 and 2^0=1 4+1=5. How can i extend my function to include this process?

thank you!


While selecting values in selectOneMenu, values are not getting selected

I use selectOneMenu component. Using Primefaces 5.2. I reduced the body size as zoom="95%". For first time selected an value and once again selecting other value-->value is not getting selected, still the older value is getting displayed.

Xhtml code:

<h:body style="zoom:95%;">
    <p:selectOneMenu id="id"  value="#{manageBean.summarySearch.status}"  style="width:180px;">
         <f:selectItem itemLabel="Pending" itemValue="Pending"/>
         <f:selectItem itemLabel="Approved" itemValue="Approved" />
         <f:selectItem itemLabel="Rejected" itemValue="Rejected" />
         <f:selectItem itemLabel="All" itemValue="All" />
    </p:selectOneMenu>

    <p:commandButton value="Search" actionListener="#{manageBean.search}"
                                        update=":listForm:empDT" />
</h:body>

Bean:

public void search(){

                summaryList=manageDao.findDetail(summarySearch,new Utill().getId());

                if(summaryList.size()==0)
                {
                    FacesContext.getCurrentInstance().addMessage("editMessage",new FacesMessage(FacesMessage.SEVERITY_ERROR,NO_RECORD_FOUND,""));
                }

            }


Unable to remove all classes in td with jQuery

I am trying to remove colspan class but it is removing only create class.

<td class="create colspan">
</td>

if ($(this).prev().hasClass('colspan') || $(this).next().hasClass('colspan')) {
    alert('yes');
    } else {
         $(this).removeClass();
         $(this).removeClass('.colspan')
 }


Mandos in Docker

I try to setup Mandos inside a Docker container and failed with dbus errors. It's possible to run the server without dbus, but mandos-ctl and mandos-monitor need dbus to run.

my Dockerfile

FROM ubuntu:16.04
RUN locale-gen de_DE.UTF-8
ENV TERM=xterm
RUN apt-get update \
    && apt-get install -y mandos \
        fping \
        dbus \
    && rm -rf /var/lib/apt/lists/*

Build it: docker build -t mandos-server .

If I host mount /var/run/dbus and start the container with:
docker run -v /dev/log:/dev/log -v /var/run/dbus:/var/run/dbus -it mandos-server bash and start mandos --debug I get the following errors:

2016-06-16 15:26:30,278 root [11]: DEBUG: Did setuid/setgid to 108:111
2016-06-16 15:26:30,280 root [11]: ERROR: Disabling D-Bus:
Traceback (most recent call last):
  File "/usr/sbin/mandos", line 3009, in main
    do_not_queue=True)
  File "/usr/lib/python2.7/dist-packages/dbus/service.py", line 131, in __new__
    retval = bus.request_name(name, name_flags)
  File "/usr/lib/python2.7/dist-packages/dbus/bus.py", line 303, in request_name
    'su', (name, flags))
  File "/usr/lib/python2.7/dist-packages/dbus/connection.py", line 651, in call_blocking
    message, timeout)
DBusException: org.freedesktop.DBus.Error.AccessDenied: Connection ":1.362" is not allowed to own the service "se.recompile.Mandos" due to security policies in the configuration file

Second trial:
Starting the container without mounting dbus docker run -v /dev/log:/dev/log -it mandos-server bash
and starting dbus by hand:
/etc/init.d/dbus start
 * Starting system message bus dbus                                          [ OK ]

mandos --debug leeds to the following error:

2016-06-16 15:36:38,338 root [40]: DEBUG: Did setuid/setgid to 108:111
2016-06-16 15:36:38,353 root [40]: WARNING: Could not load persistent state: No such file or directory
2016-06-16 15:36:38,359 root [40]: WARNING: No clients defined
2016-06-16 15:36:38,361 root [40]: INFO: Now listening on address '::', port 39145, flowinfo 0, scope_id 0
2016-06-16 15:36:38,363 dbus.proxies [40]: ERROR: Introspect error on org.freedesktop.Avahi:/: dbus.exceptions.DBusException: org.freedesktop.DBus.Error.Spawn.FileInvalid: Cannot do system-bus activation with no user

2016-06-16 15:36:38,363 dbus.proxies [40]: DEBUG: Executing introspect queue due to error
2016-06-16 15:36:38,363 root [40]: CRITICAL: D-Bus Exception
Traceback (most recent call last):
  File "/usr/sbin/mandos", line 3415, in main
    service.activate()
  File "/usr/sbin/mandos", line 470, in activate
    self.server_state_changed(self.server.GetState())
  File "/usr/lib/python2.7/dist-packages/dbus/proxies.py", line 70, in __call__
    return self._proxy_method(*args, **keywords)
  File "/usr/lib/python2.7/dist-packages/dbus/proxies.py", line 145, in __call__
    **keywords)
  File "/usr/lib/python2.7/dist-packages/dbus/connection.py", line 651, in call_blocking
    message, timeout)
DBusException: org.freedesktop.DBus.Error.Spawn.FileInvalid: Cannot do system-bus activation with no user

Any idea whats going wrong and maybe a solution?


Convert date into dd-mm-yy format and select last 12 dates from a picked value in SQL 2008

I have a table with a column 'Required date'. I need to convert the date format into dd-mm-yy format. I am able to do that using the following code -

Select Convert(VARCHAR(8),[RecordDate], 3) AS [DD/MM/YY]
From [resolveConfig].dbo.myTable

Now, when a date is picked, I would like to select the last 12 days data from the table from the 'picked date'.

How can I do that?
It is already converting the date to string format so i guess dateadd() would not work?

I am using sql 2008.

Please help.


Dynamically increase and decrease char arrays?

I have to send data with UDP. The buffer field is of type char. I also have to encrypt/decrypt what I send. Here's my code for encrypting/decrypting.

const unsigned BUFFER_SIZE = 128;
char data[BUFFER_SIZE];

cout << "Enter something." << endl;
cin.getline(data, BUFFER_SIZE);
cout << data;
char outchar[BUFFER_SIZE];

for(int i = 0; i < strlen(data); i++)
{
    //outchar[i] = data[i];
            outchar[i] = encr[(int)data[i]];
            cout << outchar[i];

}

cout << "Correct so far" << endl;

char transchar[BUFFER_SIZE];
for(int j = 0; j < strlen(outchar); j++)
{
transchar[j] = decr[(int)outchar[j]];
cout << transchar[j]; // prints out decrypted text and unused space!
}

The problem here is that using the fixed size of char means there is a lot of unused space in the buffer. In the code provided, it gets printed to screen.

Is there anyway to dynamically increase and decrease the buffer (char array) size so that I do not get the unused space?

EDIT: Something I don't think is clear: EVERY LETTER has to be encrypted and decrypted! The words are not encrypted, the letters that make them up are! The advice given up to now would translate words into an array. I need the characters.

EDIT2: deleted.

EDIT3: Russians, you got to love them. Big thanks to Vlad from Moscow!


What causes "unknown resolver null" in Spark Kafka Connector?

I am new to spark, I have start zookeeper, kafka(0.10.1.1) on my local, also spark standalone(2.2.0) with one cluster manager and 2 workers. my local scal version is 2.12.3

I was able to run wordcount on spark, and using kafka console producer and consumer to pub/sub message from kafka topic.

The problem I have is: whenever I add kafka package using the spark-submit --packages, I got

...
:: problems summary ::
:::: ERRORS
    unknown resolver null

:: USE VERBOSE OR DEBUG MESSAGE LEVEL FOR MORE DETAILS
:: retrieving :: org.apache.spark#spark-submit-parent
    confs: [default]
    0 artifacts copied, 13 already retrieved (0kB/9ms)
...

Even I am not using the kafka connector at all.
The detail logs are following:

command

$SPARK_HOME/bin/spark-submit --packages org.apache.spark:spark-streaming-kafka-0-10_2.11:2.2.0 --cluster_manager spark://TUSMA06RMLVT047:7077 build/libs/sparkdriver-1.0-SNAPSHOT.jar

log

Ivy Default Cache set to: /Users/v0001/.ivy2/cache
The jars for the packages stored in: /Users/v0001/.ivy2/jars
:: loading settings :: url = jar:file:/usr/local/Cellar/apache-spark/2.2.0/libexec/jars/ivy-2.4.0.jar!/org/apache/ivy/core/settings/ivysettings.xml
org.apache.spark#spark-streaming-kafka-0-10_2.11 added as a dependency
:: resolving dependencies :: org.apache.spark#spark-submit-parent;1.0
    confs: [default]
    found org.apache.spark#spark-streaming-kafka-0-10_2.11;2.2.0 in local-m2-cache
    found org.apache.kafka#kafka_2.11;0.10.0.1 in local-m2-cache
    found com.101tec#zkclient;0.8 in local-m2-cache
    found org.slf4j#slf4j-api;1.7.16 in spark-list
    found org.slf4j#slf4j-log4j12;1.7.16 in spark-list
    found log4j#log4j;1.2.17 in spark-list
    found com.yammer.metrics#metrics-core;2.2.0 in local-m2-cache
    found org.scala-lang.modules#scala-parser-combinators_2.11;1.0.4 in spark-list
    found org.apache.kafka#kafka-clients;0.10.0.1 in local-m2-cache
    found net.jpountz.lz4#lz4;1.3.0 in spark-list
    found org.xerial.snappy#snappy-java;1.1.2.6 in spark-list
    found org.apache.spark#spark-tags_2.11;2.2.0 in local-m2-cache
    found org.spark-project.spark#unused;1.0.0 in spark-list
:: resolution report :: resolve 1805ms :: artifacts dl 14ms
    :: modules in use:
    com.101tec#zkclient;0.8 from local-m2-cache in [default]
    com.yammer.metrics#metrics-core;2.2.0 from local-m2-cache in [default]
    log4j#log4j;1.2.17 from spark-list in [default]
    net.jpountz.lz4#lz4;1.3.0 from spark-list in [default]
    org.apache.kafka#kafka-clients;0.10.0.1 from local-m2-cache in [default]
    org.apache.kafka#kafka_2.11;0.10.0.1 from local-m2-cache in [default]
    org.apache.spark#spark-streaming-kafka-0-10_2.11;2.2.0 from local-m2-cache in [default]
    org.apache.spark#spark-tags_2.11;2.2.0 from local-m2-cache in [default]
    org.scala-lang.modules#scala-parser-combinators_2.11;1.0.4 from spark-list in [default]
    org.slf4j#slf4j-api;1.7.16 from spark-list in [default]
    org.slf4j#slf4j-log4j12;1.7.16 from spark-list in [default]
    org.spark-project.spark#unused;1.0.0 from spark-list in [default]
    org.xerial.snappy#snappy-java;1.1.2.6 from spark-list in [default]
    ---------------------------------------------------------------------
    |                  |            modules            ||   artifacts   |
    |       conf       | number| search|dwnlded|evicted|| number|dwnlded|
    ---------------------------------------------------------------------
    |      default     |   13  |   2   |   2   |   0   ||   13  |   0   |
    ---------------------------------------------------------------------

:: problems summary ::
:::: ERRORS
    unknown resolver null

:: USE VERBOSE OR DEBUG MESSAGE LEVEL FOR MORE DETAILS
:: retrieving :: org.apache.spark#spark-submit-parent
    confs: [default]
    0 artifacts copied, 13 already retrieved (0kB/9ms)
Using Spark's default log4j profile: org/apache/spark/log4j-defaults.properties
17/11/08 15:53:55 INFO SparkContext: Running Spark version 2.2.0
17/11/08 15:53:55 WARN NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
17/11/08 15:53:55 INFO SparkContext: Submitted application: WordCount
17/11/08 15:53:55 INFO SecurityManager: Changing view acls to: v0001
17/11/08 15:53:55 INFO SecurityManager: Changing modify acls to: v0001
17/11/08 15:53:55 INFO SecurityManager: Changing view acls groups to:
17/11/08 15:53:55 INFO SecurityManager: Changing modify acls groups to:
17/11/08 15:53:55 INFO SecurityManager: SecurityManager: authentication disabled; ui acls disabled; users  with view permissions: Set(v0001); groups with view permissions: Set(); users  with modify permissions: Set(v0001); groups with modify permissions: Set()
17/11/08 15:53:55 INFO Utils: Successfully started service 'sparkDriver' on port 63760.
17/11/08 15:53:55 INFO SparkEnv: Registering MapOutputTracker
17/11/08 15:53:55 INFO SparkEnv: Registering BlockManagerClusterManager
17/11/08 15:53:55 INFO BlockManagerClusterManagerEndpoint: Using org.apache.spark.storage.DefaultTopologyMapper for getting topology information
17/11/08 15:53:55 INFO BlockManagerClusterManagerEndpoint: BlockManagerClusterManagerEndpoint up
17/11/08 15:53:55 INFO DiskBlockManager: Created local directory at /private/var/folders/26/lfnkdm_d6mj48xfwdyl_sntm8tdtp9/T/blockmgr-b6a7af13-30eb-43ef-a235-e42105699289
17/11/08 15:53:55 INFO MemoryStore: MemoryStore started with capacity 366.3 MB
17/11/08 15:53:55 INFO SparkEnv: Registering OutputCommitCoordinator
17/11/08 15:53:55 INFO Utils: Successfully started service 'SparkUI' on port 4040.
17/11/08 15:53:55 INFO SparkUI: Bound SparkUI to 0.0.0.0, and started at http://10.0.1.2:4040
17/11/08 15:53:55 INFO SparkContext: Added JAR file:/Users/v0001/.ivy2/jars/org.apache.spark_spark-streaming-kafka-0-10_2.11-2.2.0.jar at spark://10.0.1.2:63760/jars/org.apache.spark_spark-streaming-kafka-0-10_2.11-2.2.0.jar with timestamp 1510174435998
17/11/08 15:53:55 INFO SparkContext: Added JAR file:/Users/v0001/.ivy2/jars/org.apache.kafka_kafka_2.11-0.10.0.1.jar at spark://10.0.1.2:63760/jars/org.apache.kafka_kafka_2.11-0.10.0.1.jar with timestamp 1510174435999
17/11/08 15:53:55 INFO SparkContext: Added JAR file:/Users/v0001/.ivy2/jars/org.apache.spark_spark-tags_2.11-2.2.0.jar at spark://10.0.1.2:63760/jars/org.apache.spark_spark-tags_2.11-2.2.0.jar with timestamp 1510174435999
17/11/08 15:53:55 INFO SparkContext: Added JAR file:/Users/v0001/.ivy2/jars/org.spark-project.spark_unused-1.0.0.jar at spark://10.0.1.2:63760/jars/org.spark-project.spark_unused-1.0.0.jar with timestamp 1510174435999
17/11/08 15:53:55 INFO SparkContext: Added JAR file:/Users/v0001/.ivy2/jars/com.101tec_zkclient-0.8.jar at spark://10.0.1.2:63760/jars/com.101tec_zkclient-0.8.jar with timestamp 1510174435999
17/11/08 15:53:55 INFO SparkContext: Added JAR file:/Users/v0001/.ivy2/jars/org.slf4j_slf4j-log4j12-1.7.16.jar at spark://10.0.1.2:63760/jars/org.slf4j_slf4j-log4j12-1.7.16.jar with timestamp 1510174435999
17/11/08 15:53:55 INFO SparkContext: Added JAR file:/Users/v0001/.ivy2/jars/com.yammer.metrics_metrics-core-2.2.0.jar at spark://10.0.1.2:63760/jars/com.yammer.metrics_metrics-core-2.2.0.jar with timestamp 1510174435999
17/11/08 15:53:56 INFO SparkContext: Added JAR file:/Users/v0001/.ivy2/jars/org.scala-lang.modules_scala-parser-combinators_2.11-1.0.4.jar at spark://10.0.1.2:63760/jars/org.scala-lang.modules_scala-parser-combinators_2.11-1.0.4.jar with timestamp 1510174436000
17/11/08 15:53:56 INFO SparkContext: Added JAR file:/Users/v0001/.ivy2/jars/org.apache.kafka_kafka-clients-0.10.0.1.jar at spark://10.0.1.2:63760/jars/org.apache.kafka_kafka-clients-0.10.0.1.jar with timestamp 1510174436000
17/11/08 15:53:56 INFO SparkContext: Added JAR file:/Users/v0001/.ivy2/jars/org.slf4j_slf4j-api-1.7.16.jar at spark://10.0.1.2:63760/jars/org.slf4j_slf4j-api-1.7.16.jar with timestamp 1510174436000
17/11/08 15:53:56 INFO SparkContext: Added JAR file:/Users/v0001/.ivy2/jars/log4j_log4j-1.2.17.jar at spark://10.0.1.2:63760/jars/log4j_log4j-1.2.17.jar with timestamp 1510174436000
17/11/08 15:53:56 INFO SparkContext: Added JAR file:/Users/v0001/.ivy2/jars/net.jpountz.lz4_lz4-1.3.0.jar at spark://10.0.1.2:63760/jars/net.jpountz.lz4_lz4-1.3.0.jar with timestamp 1510174436000
17/11/08 15:53:56 INFO SparkContext: Added JAR file:/Users/v0001/.ivy2/jars/org.xerial.snappy_snappy-java-1.1.2.6.jar at spark://10.0.1.2:63760/jars/org.xerial.snappy_snappy-java-1.1.2.6.jar with timestamp 1510174436000
17/11/08 15:53:56 INFO SparkContext: Added JAR file:/Users/v0001/iot/thingspace/go/src/stash.verizon.com/npdthing/metrics/sparkdriver/build/libs/sparkdriver-1.0-SNAPSHOT.jar at spark://10.0.1.2:63760/jars/sparkdriver-1.0-SNAPSHOT.jar with timestamp 1510174436000
17/11/08 15:53:56 INFO Executor: Starting executor ID driver on host localhost
17/11/08 15:53:56 INFO Utils: Successfully started service 'org.apache.spark.network.netty.NettyBlockTransferService' on port 63761.
17/11/08 15:53:56 INFO NettyBlockTransferService: Server created on 10.0.1.2:63761
17/11/08 15:53:56 INFO BlockManager: Using org.apache.spark.storage.RandomBlockReplicationPolicy for block replication policy
17/11/08 15:53:56 INFO BlockManagerClusterManager: Registering BlockManager BlockManagerId(driver, 10.0.1.2, 63761, None)
17/11/08 15:53:56 INFO BlockManagerClusterManagerEndpoint: Registering block manager 10.0.1.2:63761 with 366.3 MB RAM, BlockManagerId(driver, 10.0.1.2, 63761, None)
17/11/08 15:53:56 INFO BlockManagerClusterManager: Registered BlockManager BlockManagerId(driver, 10.0.1.2, 63761, None)
17/11/08 15:53:56 INFO BlockManager: Initialized BlockManager: BlockManagerId(driver, 10.0.1.2, 63761, None)
17/11/08 15:53:56 INFO MemoryStore: Block broadcast_0 stored as values in memory (estimated size 236.5 KB, free 366.1 MB)
17/11/08 15:53:56 INFO MemoryStore: Block broadcast_0_piece0 stored as bytes in memory (estimated size 22.9 KB, free 366.0 MB)
17/11/08 15:53:56 INFO BlockManagerInfo: Added broadcast_0_piece0 in memory on 10.0.1.2:63761 (size: 22.9 KB, free: 366.3 MB)
17/11/08 15:53:56 INFO SparkContext: Created broadcast 0 from textFile at WordCount.java:15
17/11/08 15:53:56 INFO FileInputFormat: Total input paths to process : 1
17/11/08 15:53:56 INFO FileOutputCommitter: File Output Committer Algorithm version is 1
17/11/08 15:53:56 INFO SparkContext: Starting job: saveAsTextFile at WordCount.java:21
17/11/08 15:53:56 INFO DAGScheduler: Registering RDD 2 (flatMapToPair at WordCount.java:18)
17/11/08 15:53:56 INFO DAGScheduler: Got job 0 (saveAsTextFile at WordCount.java:21) with 1 output partitions
17/11/08 15:53:56 INFO DAGScheduler: Final stage: ResultStage 1 (saveAsTextFile at WordCount.java:21)
17/11/08 15:53:56 INFO DAGScheduler: Parents of final stage: List(ShuffleMapStage 0)
17/11/08 15:53:56 INFO DAGScheduler: Missing parents: List(ShuffleMapStage 0)
17/11/08 15:53:56 INFO DAGScheduler: Submitting ShuffleMapStage 0 (MapPartitionsRDD[2] at flatMapToPair at WordCount.java:18), which has no missing parents
17/11/08 15:53:56 INFO MemoryStore: Block broadcast_1 stored as values in memory (estimated size 5.3 KB, free 366.0 MB)
17/11/08 15:53:56 INFO MemoryStore: Block broadcast_1_piece0 stored as bytes in memory (estimated size 3.1 KB, free 366.0 MB)
17/11/08 15:53:56 INFO BlockManagerInfo: Added broadcast_1_piece0 in memory on 10.0.1.2:63761 (size: 3.1 KB, free: 366.3 MB)
17/11/08 15:53:56 INFO SparkContext: Created broadcast 1 from broadcast at DAGScheduler.scala:1006
17/11/08 15:53:56 INFO DAGScheduler: Submitting 1 missing tasks from ShuffleMapStage 0 (MapPartitionsRDD[2] at flatMapToPair at WordCount.java:18) (first 15 tasks are for partitions Vector(0))
17/11/08 15:53:56 INFO TaskSchedulerImpl: Adding task set 0.0 with 1 tasks
17/11/08 15:53:56 INFO TaskSetManager: Starting task 0.0 in stage 0.0 (TID 0, localhost, executor driver, partition 0, PROCESS_LOCAL, 4937 bytes)
17/11/08 15:53:56 INFO Executor: Running task 0.0 in stage 0.0 (TID 0)
17/11/08 15:53:56 INFO Executor: Fetching spark://10.0.1.2:63760/jars/org.slf4j_slf4j-api-1.7.16.jar with timestamp 1510174436000
17/11/08 15:53:57 INFO TransportClientFactory: Successfully created connection to /10.0.1.2:63760 after 30 ms (0 ms spent in bootstraps)
17/11/08 15:53:57 INFO Utils: Fetching spark://10.0.1.2:63760/jars/org.slf4j_slf4j-api-1.7.16.jar to /private/var/folders/26/lfnkdm_d6mj48xfwdyl_sntm8tdtp9/T/spark-07e33210-a6be-447c-92a0-4dd504e80965/userFiles-9a4b5741-a318-420e-b112-1a4441ba030a/fetchFileTemp4839646631087629609.tmp
17/11/08 15:53:57 INFO Executor: Adding file:/private/var/folders/26/lfnkdm_d6mj48xfwdyl_sntm8tdtp9/T/spark-07e33210-a6be-447c-92a0-4dd504e80965/userFiles-9a4b5741-a318-420e-b112-1a4441ba030a/org.slf4j_slf4j-api-1.7.16.jar to class loader
17/11/08 15:53:57 INFO Executor: Fetching spark://10.0.1.2:63760/jars/org.apache.kafka_kafka_2.11-0.10.0.1.jar with timestamp 1510174435999
17/11/08 15:53:57 INFO Utils: Fetching spark://10.0.1.2:63760/jars/org.apache.kafka_kafka_2.11-0.10.0.1.jar to /private/var/folders/26/lfnkdm_d6mj48xfwdyl_sntm8tdtp9/T/spark-07e33210-a6be-447c-92a0-4dd504e80965/userFiles-9a4b5741-a318-420e-b112-1a4441ba030a/fetchFileTemp8667361266232337100.tmp
17/11/08 15:53:57 INFO Executor: Adding file:/private/var/folders/26/lfnkdm_d6mj48xfwdyl_sntm8tdtp9/T/spark-07e33210-a6be-447c-92a0-4dd504e80965/userFiles-9a4b5741-a318-420e-b112-1a4441ba030a/org.apache.kafka_kafka_2.11-0.10.0.1.jar to class loader
17/11/08 15:53:57 INFO Executor: Fetching spark://10.0.1.2:63760/jars/org.slf4j_slf4j-log4j12-1.7.16.jar with timestamp 1510174435999
17/11/08 15:53:57 INFO Utils: Fetching spark://10.0.1.2:63760/jars/org.slf4j_slf4j-log4j12-1.7.16.jar to /private/var/folders/26/lfnkdm_d6mj48xfwdyl_sntm8tdtp9/T/spark-07e33210-a6be-447c-92a0-4dd504e80965/userFiles-9a4b5741-a318-420e-b112-1a4441ba030a/fetchFileTemp5418243157152191799.tmp
17/11/08 15:53:57 INFO Executor: Adding file:/private/var/folders/26/lfnkdm_d6mj48xfwdyl_sntm8tdtp9/T/spark-07e33210-a6be-447c-92a0-4dd504e80965/userFiles-9a4b5741-a318-420e-b112-1a4441ba030a/org.slf4j_slf4j-log4j12-1.7.16.jar to class loader
17/11/08 15:53:57 INFO Executor: Fetching spark://10.0.1.2:63760/jars/org.scala-lang.modules_scala-parser-combinators_2.11-1.0.4.jar with timestamp 1510174436000
17/11/08 15:53:57 INFO Utils: Fetching spark://10.0.1.2:63760/jars/org.scala-lang.modules_scala-parser-combinators_2.11-1.0.4.jar to /private/var/folders/26/lfnkdm_d6mj48xfwdyl_sntm8tdtp9/T/spark-07e33210-a6be-447c-92a0-4dd504e80965/userFiles-9a4b5741-a318-420e-b112-1a4441ba030a/fetchFileTemp2366789843424249528.tmp
17/11/08 15:53:57 INFO Executor: Adding file:/private/var/folders/26/lfnkdm_d6mj48xfwdyl_sntm8tdtp9/T/spark-07e33210-a6be-447c-92a0-4dd504e80965/userFiles-9a4b5741-a318-420e-b112-1a4441ba030a/org.scala-lang.modules_scala-parser-combinators_2.11-1.0.4.jar to class loader
17/11/08 15:53:57 INFO Executor: Fetching spark://10.0.1.2:63760/jars/org.apache.spark_spark-tags_2.11-2.2.0.jar with timestamp 1510174435999
17/11/08 15:53:57 INFO Utils: Fetching spark://10.0.1.2:63760/jars/org.apache.spark_spark-tags_2.11-2.2.0.jar to /private/var/folders/26/lfnkdm_d6mj48xfwdyl_sntm8tdtp9/T/spark-07e33210-a6be-447c-92a0-4dd504e80965/userFiles-9a4b5741-a318-420e-b112-1a4441ba030a/fetchFileTemp2527586655699915856.tmp
17/11/08 15:53:57 INFO Executor: Adding file:/private/var/folders/26/lfnkdm_d6mj48xfwdyl_sntm8tdtp9/T/spark-07e33210-a6be-447c-92a0-4dd504e80965/userFiles-9a4b5741-a318-420e-b112-1a4441ba030a/org.apache.spark_spark-tags_2.11-2.2.0.jar to class loader
17/11/08 15:53:57 INFO Executor: Fetching spark://10.0.1.2:63760/jars/org.spark-project.spark_unused-1.0.0.jar with timestamp 1510174435999
17/11/08 15:53:57 INFO Utils: Fetching spark://10.0.1.2:63760/jars/org.spark-project.spark_unused-1.0.0.jar to /private/var/folders/26/lfnkdm_d6mj48xfwdyl_sntm8tdtp9/T/spark-07e33210-a6be-447c-92a0-4dd504e80965/userFiles-9a4b5741-a318-420e-b112-1a4441ba030a/fetchFileTemp4436635514367901872.tmp
17/11/08 15:53:57 INFO Executor: Adding file:/private/var/folders/26/lfnkdm_d6mj48xfwdyl_sntm8tdtp9/T/spark-07e33210-a6be-447c-92a0-4dd504e80965/userFiles-9a4b5741-a318-420e-b112-1a4441ba030a/org.spark-project.spark_unused-1.0.0.jar to class loader
17/11/08 15:53:57 INFO Executor: Fetching spark://10.0.1.2:63760/jars/com.101tec_zkclient-0.8.jar with timestamp 1510174435999
17/11/08 15:53:57 INFO Utils: Fetching spark://10.0.1.2:63760/jars/com.101tec_zkclient-0.8.jar to /private/var/folders/26/lfnkdm_d6mj48xfwdyl_sntm8tdtp9/T/spark-07e33210-a6be-447c-92a0-4dd504e80965/userFiles-9a4b5741-a318-420e-b112-1a4441ba030a/fetchFileTemp4322710809557945921.tmp
17/11/08 15:53:57 INFO Executor: Adding file:/private/var/folders/26/lfnkdm_d6mj48xfwdyl_sntm8tdtp9/T/spark-07e33210-a6be-447c-92a0-4dd504e80965/userFiles-9a4b5741-a318-420e-b112-1a4441ba030a/com.101tec_zkclient-0.8.jar to class loader
17/11/08 15:53:57 INFO Executor: Fetching spark://10.0.1.2:63760/jars/org.apache.spark_spark-streaming-kafka-0-10_2.11-2.2.0.jar with timestamp 1510174435998
17/11/08 15:53:57 INFO Utils: Fetching spark://10.0.1.2:63760/jars/org.apache.spark_spark-streaming-kafka-0-10_2.11-2.2.0.jar to /private/var/folders/26/lfnkdm_d6mj48xfwdyl_sntm8tdtp9/T/spark-07e33210-a6be-447c-92a0-4dd504e80965/userFiles-9a4b5741-a318-420e-b112-1a4441ba030a/fetchFileTemp6210645736090344233.tmp
17/11/08 15:53:57 INFO Executor: Adding file:/private/var/folders/26/lfnkdm_d6mj48xfwdyl_sntm8tdtp9/T/spark-07e33210-a6be-447c-92a0-4dd504e80965/userFiles-9a4b5741-a318-420e-b112-1a4441ba030a/org.apache.spark_spark-streaming-kafka-0-10_2.11-2.2.0.jar to class loader
17/11/08 15:53:57 INFO Executor: Fetching spark://10.0.1.2:63760/jars/log4j_log4j-1.2.17.jar with timestamp 1510174436000
17/11/08 15:53:57 INFO Utils: Fetching spark://10.0.1.2:63760/jars/log4j_log4j-1.2.17.jar to /private/var/folders/26/lfnkdm_d6mj48xfwdyl_sntm8tdtp9/T/spark-07e33210-a6be-447c-92a0-4dd504e80965/userFiles-9a4b5741-a318-420e-b112-1a4441ba030a/fetchFileTemp2587760876873828850.tmp
17/11/08 15:53:57 INFO Executor: Adding file:/private/var/folders/26/lfnkdm_d6mj48xfwdyl_sntm8tdtp9/T/spark-07e33210-a6be-447c-92a0-4dd504e80965/userFiles-9a4b5741-a318-420e-b112-1a4441ba030a/log4j_log4j-1.2.17.jar to class loader
17/11/08 15:53:57 INFO Executor: Fetching spark://10.0.1.2:63760/jars/com.yammer.metrics_metrics-core-2.2.0.jar with timestamp 1510174435999
17/11/08 15:53:57 INFO Utils: Fetching spark://10.0.1.2:63760/jars/com.yammer.metrics_metrics-core-2.2.0.jar to /private/var/folders/26/lfnkdm_d6mj48xfwdyl_sntm8tdtp9/T/spark-07e33210-a6be-447c-92a0-4dd504e80965/userFiles-9a4b5741-a318-420e-b112-1a4441ba030a/fetchFileTemp8763096223513955185.tmp
17/11/08 15:53:57 INFO Executor: Adding file:/private/var/folders/26/lfnkdm_d6mj48xfwdyl_sntm8tdtp9/T/spark-07e33210-a6be-447c-92a0-4dd504e80965/userFiles-9a4b5741-a318-420e-b112-1a4441ba030a/com.yammer.metrics_metrics-core-2.2.0.jar to class loader
17/11/08 15:53:57 INFO Executor: Fetching spark://10.0.1.2:63760/jars/org.apache.kafka_kafka-clients-0.10.0.1.jar with timestamp 1510174436000
17/11/08 15:53:57 INFO Utils: Fetching spark://10.0.1.2:63760/jars/org.apache.kafka_kafka-clients-0.10.0.1.jar to /private/var/folders/26/lfnkdm_d6mj48xfwdyl_sntm8tdtp9/T/spark-07e33210-a6be-447c-92a0-4dd504e80965/userFiles-9a4b5741-a318-420e-b112-1a4441ba030a/fetchFileTemp2368772990989848791.tmp
17/11/08 15:53:57 INFO Executor: Adding file:/private/var/folders/26/lfnkdm_d6mj48xfwdyl_sntm8tdtp9/T/spark-07e33210-a6be-447c-92a0-4dd504e80965/userFiles-9a4b5741-a318-420e-b112-1a4441ba030a/org.apache.kafka_kafka-clients-0.10.0.1.jar to class loader
17/11/08 15:53:57 INFO Utils: Fetching spark://10.0.1.2:63760/jars/org.xerial.snappy_snappy-java-1.1.2.6.jar to /private/var/folders/26/lfnkdm_d6mj48xfwdyl_sntm8tdtp9/T/spark-07e33210-a6be-447c-92a0-4dd504e80965/userFiles-9a4b5741-a318-420e-b112-1a4441ba030a/fetchFileTemp5933403694236070460.tmp
17/11/08 15:53:57 INFO Executor: Adding file:/private/var/folders/26/lfnkdm_d6mj48xfwdyl_sntm8tdtp9/T/spark-07e33210-a6be-447c-92a0-4dd504e80965/userFiles-9a4b5741-a318-420e-b112-1a4441ba030a/org.xerial.snappy_snappy-java-1.1.2.6.jar to class loader
17/11/08 15:53:57 INFO Executor: Fetching spark://10.0.1.2:63760/jars/sparkdriver-1.0-SNAPSHOT.jar with timestamp 1510174436000
17/11/08 15:53:57 INFO Utils: Fetching spark://10.0.1.2:63760/jars/sparkdriver-1.0-SNAPSHOT.jar to /private/var/folders/26/lfnkdm_d6mj48xfwdyl_sntm8tdtp9/T/spark-07e33210-a6be-447c-92a0-4dd504e80965/userFiles-9a4b5741-a318-420e-b112-1a4441ba030a/fetchFileTemp9172284954823303788.tmp
17/11/08 15:53:57 INFO Executor: Adding file:/private/var/folders/26/lfnkdm_d6mj48xfwdyl_sntm8tdtp9/T/spark-07e33210-a6be-447c-92a0-4dd504e80965/userFiles-9a4b5741-a318-420e-b112-1a4441ba030a/sparkdriver-1.0-SNAPSHOT.jar to class loader
17/11/08 15:53:57 INFO Executor: Fetching spark://10.0.1.2:63760/jars/net.jpountz.lz4_lz4-1.3.0.jar with timestamp 1510174436000
17/11/08 15:53:57 INFO Utils: Fetching spark://10.0.1.2:63760/jars/net.jpountz.lz4_lz4-1.3.0.jar to /private/var/folders/26/lfnkdm_d6mj48xfwdyl_sntm8tdtp9/T/spark-07e33210-a6be-447c-92a0-4dd504e80965/userFiles-9a4b5741-a318-420e-b112-1a4441ba030a/fetchFileTemp2018048990610379910.tmp
17/11/08 15:53:57 INFO Executor: Adding file:/private/var/folders/26/lfnkdm_d6mj48xfwdyl_sntm8tdtp9/T/spark-07e33210-a6be-447c-92a0-4dd504e80965/userFiles-9a4b5741-a318-420e-b112-1a4441ba030a/net.jpountz.lz4_lz4-1.3.0.jar to class loader
17/11/08 15:53:57 INFO HadoopRDD: Input split: file:/usr/local/Cellar/apache-spark/2.2.0/libexec/logs/spark-v0001-org.apache.spark.deploy.cluster_manager.cluster-manager-1-TUSMA06RMLVT047.out:0+3424
17/11/08 15:53:57 INFO Executor: Finished task 0.0 in stage 0.0 (TID 0). 1192 bytes result sent to driver
17/11/08 15:53:57 INFO TaskSetManager: Finished task 0.0 in stage 0.0 (TID 0) in 571 ms on localhost (executor driver) (1/1)
17/11/08 15:53:57 INFO TaskSchedulerImpl: Removed TaskSet 0.0, whose tasks have all completed, from pool
17/11/08 15:53:57 INFO DAGScheduler: ShuffleMapStage 0 (flatMapToPair at WordCount.java:18) finished in 0.590 s
17/11/08 15:53:57 INFO DAGScheduler: looking for newly runnable stages
17/11/08 15:53:57 INFO DAGScheduler: running: Set()
17/11/08 15:53:57 INFO DAGScheduler: waiting: Set(ResultStage 1)
17/11/08 15:53:57 INFO DAGScheduler: failed: Set()
17/11/08 15:53:57 INFO DAGScheduler: Submitting ResultStage 1 (MapPartitionsRDD[4] at saveAsTextFile at WordCount.java:21), which has no missing parents
17/11/08 15:53:57 INFO MemoryStore: Block broadcast_2 stored as values in memory (estimated size 72.6 KB, free 366.0 MB)
17/11/08 15:53:57 INFO MemoryStore: Block broadcast_2_piece0 stored as bytes in memory (estimated size 26.1 KB, free 365.9 MB)
17/11/08 15:53:57 INFO BlockManagerInfo: Added broadcast_2_piece0 in memory on 10.0.1.2:63761 (size: 26.1 KB, free: 366.2 MB)
17/11/08 15:53:57 INFO SparkContext: Created broadcast 2 from broadcast at DAGScheduler.scala:1006
17/11/08 15:53:57 INFO DAGScheduler: Submitting 1 missing tasks from ResultStage 1 (MapPartitionsRDD[4] at saveAsTextFile at WordCount.java:21) (first 15 tasks are for partitions Vector(0))
17/11/08 15:53:57 INFO TaskSchedulerImpl: Adding task set 1.0 with 1 tasks
17/11/08 15:53:57 INFO TaskSetManager: Starting task 0.0 in stage 1.0 (TID 1, localhost, executor driver, partition 0, ANY, 4621 bytes)
17/11/08 15:53:57 INFO Executor: Running task 0.0 in stage 1.0 (TID 1)
17/11/08 15:53:57 INFO ShuffleBlockFetcherIterator: Getting 1 non-empty blocks out of 1 blocks
17/11/08 15:53:57 INFO ShuffleBlockFetcherIterator: Started 0 remote fetches in 4 ms
17/11/08 15:53:57 INFO FileOutputCommitter: File Output Committer Algorithm version is 1
17/11/08 15:53:57 INFO FileOutputCommitter: Saved output of task 'attempt_20171108155356_0001_m_000000_1' to file:/Users/v0001/iot/thingspace/go/src/stash.verizon.com/npdthing/metrics/sparkdriver/wordcount.out/_temporary/0/task_20171108155356_0001_m_000000
17/11/08 15:53:57 INFO SparkHadoopMapRedUtil: attempt_20171108155356_0001_m_000000_1: Committed
17/11/08 15:53:57 INFO Executor: Finished task 0.0 in stage 1.0 (TID 1). 1224 bytes result sent to driver
17/11/08 15:53:57 INFO TaskSetManager: Finished task 0.0 in stage 1.0 (TID 1) in 123 ms on localhost (executor driver) (1/1)
17/11/08 15:53:57 INFO TaskSchedulerImpl: Removed TaskSet 1.0, whose tasks have all completed, from pool
17/11/08 15:53:57 INFO DAGScheduler: ResultStage 1 (saveAsTextFile at WordCount.java:21) finished in 0.123 s
17/11/08 15:53:57 INFO DAGScheduler: Job 0 finished: saveAsTextFile at WordCount.java:21, took 0.852166 s
17/11/08 15:53:57 INFO SparkContext: Invoking stop() from shutdown hook
17/11/08 15:53:57 INFO SparkUI: Stopped Spark web UI at http://10.0.1.2:4040
17/11/08 15:53:57 INFO MapOutputTrackerClusterManagerEndpoint: MapOutputTrackerClusterManagerEndpoint stopped!
17/11/08 15:53:57 INFO MemoryStore: MemoryStore cleared
17/11/08 15:53:57 INFO BlockManager: BlockManager stopped
17/11/08 15:53:57 INFO BlockManagerClusterManager: BlockManagerClusterManager stopped
17/11/08 15:53:57 INFO OutputCommitCoordinator$OutputCommitCoordinatorEndpoint: OutputCommitCoordinator stopped!
17/11/08 15:53:57 INFO SparkContext: Successfully stopped SparkContext
17/11/08 15:53:57 INFO ShutdownHookManager: Deleting directory /private/var/folders/26/lfnkdm_d6mj48xfwdyl_sntm8tdtp9/T/spark-07e33210-a6be-447c-92a0-4dd504e80965


InsertMany throw E11000 duplicate key error but insert successfully

I am using mongoose to insert bulk data to database.
The insertMany throw E11000 duplicate key error although the data is saved succeed in database.

Here is my codes:

  var data = [
      {_id: '598d7ae7c3148a6d853866e8'},
      {_id: '598d7afdc3148a6d853866f4'}
    ]
Movies.insertMany(data, function(error, docs) {});

This happen infrequently.

Appreciated any help.

Thanks


Binding empty values to numerical fields in Play Framework 2 (Java)

I have forms where I want to be able to leave some numerical fields empty, but I get "Invalid value" errors from Form.bindFromRequest(). This seems like a common requirement, but I can't find any documentation on this after hours of searching. I am still hoping I've missed something obvious, though!

I did some digging and found that Play uses Spring's DataBinder class to do the actual binding. That class is really sophisticated and would allow me to set custom binders for my fields, and if I was using Spring I could just add an @InitBinder method to my controller to set up the binder exactly the way I want using a CustomNumberEditor. However, it seems that Play Framework's Form object does not allow access to the DataBinder, apart from setting allowed fields. So, the binder tries to convert an empty string into a long, which gives a NumberFormatException:

Failed to convert property value of type 'java.lang.String' to required type 'long'
for property 'unitPriceExVAT';
nested exception is java.lang.NumberFormatException: For input string: ""

So, is there some other way of getting the binder to allow empty numerical fields?