问:
Dragging a UILabel within a UIView and maintaining it's new coordinates
So I have a UILabel on a UIView nib file and I am trying to give the user the ability to drag the label around and when they stop dragging the label stays there and if they try to drag it again they can.

I am able to drag the Label just fine using the UIPanGestureRecognizer and when I stop dragging it the label stays where it is. The problem I am having is that when I attempt to drag it again the Label jumps back to the original starting position at the center of the UIView.

I understand that using the UIPanGestureRecognizer.translation(in: UIVIew) gives the original coordinates as (x: 0.0, y: 0.0) when the actual coordinates that the Label starts at are (x: 150.0, y: 90.0).

```<code>@IBOutlet var cardView: UIView!
@IBOutlet weak var testLBL: UILabel!

override func awakeFromNib() {
    super.awakeFromNib()

    // trying to move the label
    let gesture = UIPanGestureRecognizer(target: self, action: #selector(self.wasDragged(gestureRecognizer:)))

    testLBL.isUserInteractionEnabled = true
    cardView.clipsToBounds = true

    testLBL.addGestureRecognizer(gesture)
}
</code>```

Below is the function that is used to handle the action, I have several other things I have tried commented out. I am also printing the current coordinates of the Label within the cardView

```<code>// function that helps drag the label around
func wasDragged(gestureRecognizer: UIPanGestureRecognizer) {
    let translation = gestureRecognizer.translation(in: cardView)

    //print(translation)

    // currently taking it from the original point each time you try to drag it

    testLBL.center = CGPoint(x: self.bounds.width / 2 + translation.x, y: self.bounds.height / 2 + translation.y)

    //how you will know what position the label was moved to
    print(["x",self.testLBL.frame.origin.x,"y", self.testLBL.frame.origin.y])

    //let newTranslation = gestureRecognizer.translation(in: cardView)

    //var coordinates = CGPoint(x: self.testLBL.frame.origin.x, y: self.testLBL.frame.origin.y)
}
</code>```

The testLBL.center = CGPoint(x: self.bounds.width / 2 + translation.x, y: self.bounds.height / 2 + translation.y) operation is what allows the label to move and works find I just want it to not jump back to the middle of the UIView when I try to drag it again.

Any help is greatly appreciated because I am still pretty new at coding, Thank You!

答:
this might help

```<code>CGPoint translation = [recognizer translationInView:self.superview];
testLBL.center = CGPointMake(self.center.x + translation.x, self.center.y + translation.y);
[recognizer setTranslation:CGPointZero inView:self];
</code>```

apply it on swift you won't find that hard

Body:
So I have a UILabel on a UIView nib file and I am trying to give the user the ability to drag the label around and when they stop dragging the label stays there and if they try to drag it again they can.

I am able to drag the Label just fine using the UIPanGestureRecognizer and when I stop dragging it the label stays where it is. The problem I am having is that when I attempt to drag it again the Label jumps back to the original starting position at the center of the UIView.

I understand that using the UIPanGestureRecognizer.translation(in: UIVIew) gives the original coordinates as (x: 0.0, y: 0.0) when the actual coordinates that the Label starts at are (x: 150.0, y: 90.0).

@IBOutlet var cardView: UIView!
@IBOutlet weak var testLBL: UILabel!

override func awakeFromNib() {
    super.awakeFromNib()

    // trying to move the label
    let gesture = UIPanGestureRecognizer(target: self, action: #selector(self.wasDragged(gestureRecognizer:)))

    testLBL.isUserInteractionEnabled = true
    cardView.clipsToBounds = true

    testLBL.addGestureRecognizer(gesture)
}

Below is the function that is used to handle the action, I have several other things I have tried commented out. I am also printing the current coordinates of the Label within the cardView

// function that helps drag the label around
func wasDragged(gestureRecognizer: UIPanGestureRecognizer) {
    let translation = gestureRecognizer.translation(in: cardView)

    //print(translation)

    // currently taking it from the original point each time you try to drag it

    testLBL.center = CGPoint(x: self.bounds.width / 2 + translation.x, y: self.bounds.height / 2 + translation.y)

    //how you will know what position the label was moved to
    print(["x",self.testLBL.frame.origin.x,"y", self.testLBL.frame.origin.y])

    //let newTranslation = gestureRecognizer.translation(in: cardView)

    //var coordinates = CGPoint(x: self.testLBL.frame.origin.x, y: self.testLBL.frame.origin.y)
}

The testLBL.center = CGPoint(x: self.bounds.width / 2 + translation.x, y: self.bounds.height / 2 + translation.y) operation is what allows the label to move and works find I just want it to not jump back to the middle of the UIView when I try to drag it again.

Any help is greatly appreciated because I am still pretty new at coding, Thank You!

Body:
this might help

CGPoint translation = [recognizer translationInView:self.superview];
testLBL.center = CGPointMake(self.center.x + translation.x, self.center.y + translation.y);
[recognizer setTranslation:CGPointZero inView:self];

apply it on swift you won't find that hard


来源: stackexchange

问:
How to make a Type-constructor part of the Functor typeclass if it has more than one Type-parameter?
I am trying to understand the way the Functor-Typeclass works in Haskell. If you have a function f :: a -> b -> c and you want to partially apply it to the argB to get a function that takes one argument, you can simply do:

```<code>f' :: a -> c
f' x = f x argB
</code>```

and use that. Is it possible to get such behavior when making something part of the Functor-Typeclass with something like this:

```<code>instance Functor (MyTypeconstructor _ argB) where
   fmap <implementation of fmap>
</code>```

I know you can partially apply a Type-constructor to its first type-parameter (standart currying):

```<code>instance Functor (MyTypeconstructor argA) where
   fmap <implementation of fmap>
</code>```

but how can you partially apply it to its second / third / all except one type-parameter, if this is possible?

thank you.

答:
More generally, you can write

```<code>newtype FlippedF a b = FlippedF { unFlip :: F b a }
</code>```

and then

```<code>instance Functor (FlippedF argB)
</code>```

Or even more generally,

```<code>newtype Flip f a b = Flip { unFlip :: f b a }

instance Functor (Flip F argB)
</code>```

Flip and many more type-level combinators are defined in e.g. http://hackage.haskell.org/package/TypeCompose-0.9.12/docs/Control-Compose.html#g:9 (and also http://hackage.haskell.org/package/bifunctors-5.4.1/docs/Data-Bifunctor-Flip.html#t:Flip)

ContentLicense: CC BY-SA 3.0

Body:
I am trying to understand the way the Functor-Typeclass works in Haskell. If you have a function f :: a -> b -> c and you want to partially apply it to the argB to get a function that takes one argument, you can simply do:

f' :: a -> c
f' x = f x argB

and use that. Is it possible to get such behavior when making something part of the Functor-Typeclass with something like this:

instance Functor (MyTypeconstructor _ argB) where
   fmap <implementation of fmap>

I know you can partially apply a Type-constructor to its first type-parameter (standart currying):

instance Functor (MyTypeconstructor argA) where
   fmap <implementation of fmap>

but how can you partially apply it to its second / third / all except one type-parameter, if this is possible?

thank you.

Body:
More generally, you can write

newtype FlippedF a b = FlippedF { unFlip :: F b a }

and then

instance Functor (FlippedF argB)

Or even more generally,

newtype Flip f a b = Flip { unFlip :: f b a }

instance Functor (Flip F argB)

Flip and many more type-level combinators are defined in e.g. http://hackage.haskell.org/package/TypeCompose-0.9.12/docs/Control-Compose.html#g:9 (and also http://hackage.haskell.org/package/bifunctors-5.4.1/docs/Data-Bifunctor-Flip.html#t:Flip)


问:
Check which form is used
I created to do list, through a database,

But the sign in and sign up need to go through 1 manager... yet I dont know how to check which form is used. Hope someone can help me put the 2 pieces of PHP toghter in one manager! Thanks for all help in advance!

EDIT THIS IS HOW IT WORKS!

THE MANAGER FILE

```<code><?php
    if ($_GET['action'] == 'login')  {
    $email = $_POST['email'];
    $wachtwoord = $_POST['pass'];
    $code       = sha1($wachtwoord);
    $pass       = crypt($code, 'ex');

    $sql = "SELECT * FROM tbl_users WHERE password = '$pass' AND email = '$email'";
    $result = $db_conn->query($sql)->rowCount();

    if ($result == 1)
    {
        session_start();
        $_SESSION['LoggedIn'] = true;
        header("Location: ../public/todo.php");
    }
    else{
        $ErrorMessage = "<strong>U heeft foutieve gegevens gebruikt, probeer het nog eens!</strong>";
        header("Location: ../public/index.php?message=$ErrorMessage");
    }
} else if($_GET['action'] == 'register')  {

    $ErrorMessage = "<strong>U moet een naam invullen!</strong>";
    if (empty($_POST['name'])){header("Location: ../public/signup.php?message=$ErrorMessage");die;}
    $ErrorMessage = "<strong>U moet een wachtwoord invullen!</strong>";
    if (empty($_POST['pass'])){header("Location: ../public/signup.php?message=$ErrorMessage");die;}
    $ErrorMessage = "<strong>U moet een geldige email invullen!</strong>";
    if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)){header("Location: ../public/signup.php?message=$ErrorMessage");die;}

    $email  = $_POST['email'];

    $qry="SELECT `email` FROM `tbl_users` ORDER BY `email`";
    $qryObj = $db_conn->prepare($qry);
    $qryObj->execute();

    $resultArr = $qryObj->fetchAll(PDO::FETCH_ASSOC);

    foreach($resultArr as $row)
    {
        if ($email === $row['email']) {
            $ErrorMessage = "<strong>Deze mail bestaat al!</strong>";
            header("Location: ../public/signup.php?message=$ErrorMessage");die;
        }
    }

    $name   = htmlspecialchars($_POST['name']);
    $wachtwoord = $_POST['pass'];
    $code = sha1($wachtwoord);
    $pass = crypt($code,'ex');

    $verificatie='name='.$name.'&email='.$email.'&pass='.$pass;

    $subject = 'Verifeer uw email adres';
    $from = 'De TODO Servicedesk';
    $bericht = '/verificatie.php?'.$verificatie;

    ini_set('sendmail_from', $from);

    $headers   = array();
    $headers[] = "MIME-Version: 1.0";
    $headers[] = "Content-type: text/plain; charset=iso-8859-1";
    $headers[] = "From: TODO Servicedesk <{$from}>";
    $headers[] = "Reply-To: TODO Servicedesk <{$from}>";
    //$headers[] = "Subject: {$subject}";

    mail($email, $subject, $bericht, implode("\r\n", $headers) );
    $ErrorMessage = "<strong>Er is een activatiemail verstuurd!</strong>";
    header("Location: ../public/signup.php?message=$ErrorMessage");
}
</code>```

?>

This are the FORMS

login form:

```<code><section>
<form action="../app/account_manager.php?action=login" method="POST">
    <div class="form-group">
        <label for="email">Email:</label>
        <input type="email" class="form-control" name="email">
    </div>
    <div class="form-group">
        <label for="password">Password:</label>
        <input type="password" class="form-control" name="pass">
    </div>
    <div class="form-group">
        <input type="submit" value="Login!" class="btn btn-primary" name="login">
    </div>
</form>
<?php
if (isset($_GET['message'])!= null )
{
    echo $_GET['message'];
}
?>
</code>```

Register Form:

```<code><section>
<form action="../app/account_manager.php?action=register" method="POST">
    <div class="form-group">
        <label for="name">Name:</label>
        <input type="text" class="form-control" name="name">
    </div>
    <div class="form-group">
        <label for="email">Email:</label>
        <input type="email" class="form-control" name="email">
    </div>
    <div class="form-group">
        <label for="pass">Password:</label>
        <input type="password" class="form-control" name="pass">
    </div>
    <div class="form-group">
        <input type="submit" value="Registreer!" class="btn btn-primary" name="submit">
    </div>
</form>
<?php
if (isset($_GET['message'])!= null )
{
    echo $_GET['message'];
}
?>
</code>```

答:
After you point your sign up form's action to the account manager script you could key off of the submit button "name" to do different action(s).

By the way, your sign in form's submit button doesn't currently carry a name attribute.

In  your manager script:

```<code>if(isset($_POST['signup'])){
    ... relevant registration code gets moved here ...
}else{
//or }elseif(isset($_POST['signin'])){  // if/when you give the button a name
    ...relevant sign in code goes here ...
}
</code>```

Title: Check which form is used

Body:
I created to do list, through a database,

But the sign in and sign up need to go through 1 manager... yet I dont know how to check which form is used. Hope someone can help me put the 2 pieces of PHP toghter in one manager! Thanks for all help in advance!

EDIT THIS IS HOW IT WORKS!

THE MANAGER FILE

<?php
    if ($_GET['action'] == 'login')  {
    $email = $_POST['email'];
    $wachtwoord = $_POST['pass'];
    $code       = sha1($wachtwoord);
    $pass       = crypt($code, 'ex');

    $sql = "SELECT * FROM tbl_users WHERE password = '$pass' AND email = '$email'";
    $result = $db_conn->query($sql)->rowCount();

    if ($result == 1)
    {
        session_start();
        $_SESSION['LoggedIn'] = true;
        header("Location: ../public/todo.php");
    }
    else{
        $ErrorMessage = "U heeft foutieve gegevens gebruikt, probeer het nog eens!";
        header("Location: ../public/index.php?message=$ErrorMessage");
    }
} else if($_GET['action'] == 'register')  {

    $ErrorMessage = "U moet een naam invullen!";
    if (empty($_POST['name'])){header("Location: ../public/signup.php?message=$ErrorMessage");die;}
    $ErrorMessage = "U moet een wachtwoord invullen!";
    if (empty($_POST['pass'])){header("Location: ../public/signup.php?message=$ErrorMessage");die;}
    $ErrorMessage = "U moet een geldige email invullen!";
    if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)){header("Location: ../public/signup.php?message=$ErrorMessage");die;}

    $email  = $_POST['email'];

    $qry="SELECT `email` FROM `tbl_users` ORDER BY `email`";
    $qryObj = $db_conn->prepare($qry);
    $qryObj->execute();

    $resultArr = $qryObj->fetchAll(PDO::FETCH_ASSOC);

    foreach($resultArr as $row)
    {
        if ($email === $row['email']) {
            $ErrorMessage = "Deze mail bestaat al!";
            header("Location: ../public/signup.php?message=$ErrorMessage");die;
        }
    }

    $name   = htmlspecialchars($_POST['name']);
    $wachtwoord = $_POST['pass'];
    $code = sha1($wachtwoord);
    $pass = crypt($code,'ex');

    $verificatie='name='.$name.'&email='.$email.'&pass='.$pass;

    $subject = 'Verifeer uw email adres';
    $from = 'De TODO Servicedesk';
    $bericht = '/verificatie.php?'.$verificatie;

    ini_set('sendmail_from', $from);

    $headers   = array();
    $headers[] = "MIME-Version: 1.0";
    $headers[] = "Content-type: text/plain; charset=iso-8859-1";
    $headers[] = "From: TODO Servicedesk <{$from}>";
    $headers[] = "Reply-To: TODO Servicedesk <{$from}>";
    //$headers[] = "Subject: {$subject}";

    mail($email, $subject, $bericht, implode("\r\n", $headers) );
    $ErrorMessage = "Er is een activatiemail verstuurd!";
    header("Location: ../public/signup.php?message=$ErrorMessage");
}

?>

This are the FORMS

login form:

<form action="../app/account_manager.php?action=login" method="POST">

        Email:
        <input type="email" class="form-control" name="email">

        Password:
        <input type="password" class="form-control" name="pass">

        <input type="submit" value="Login!" class="btn btn-primary" name="login">

</form>
<?php
if (isset($_GET['message'])!= null )
{
    echo $_GET['message'];
}
?>

Register Form:

<form action="../app/account_manager.php?action=register" method="POST">

        Name:
        <input type="text" class="form-control" name="name">

        Email:
        <input type="email" class="form-control" name="email">

        Password:
        <input type="password" class="form-control" name="pass">

        <input type="submit" value="Registreer!" class="btn btn-primary" name="submit">

</form>
<?php
if (isset($_GET['message'])!= null )
{
    echo $_GET['message'];
}
?>

Body:
After you point your sign up form's action to the account manager script you could key off of the submit button "name" to do different action(s).

By the way, your sign in form's submit button doesn't currently carry a name attribute.

In  your manager script:

if(isset($_POST['signup'])){
    ... relevant registration code gets moved here ...
}else{
//or }elseif(isset($_POST['signin'])){  // if/when you give the button a name
    ...relevant sign in code goes here ...
}


问:
Deploy MEAN stack project on IIS of local server
I am trying to deploy my MEAN framework application on IIS using iisnode on local machine.

My api call is working after hosting on IIS, but web application page is not loading because it can not load required css and js files related to web app.

My server.js contains following code:-

```<code>var express = require('express');
var app = express();
var http = require('http').Server(app);
var path = require('path');
var mongoOps = require('./MongoOperations.js');
var googleAuthOps = require('./passport_google.js');
var bodyparser = require('body-parser');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;

var cookieParser = require('cookie-parser');
var session = require('express-session');

exports.io = require('socket.io')(http);
var port = process.env.port || 1337;

app.use(bodyparser.json()); // for parsing application/json
app.use(bodyparser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
app.use(session({ secret: 'this is the secret' }));//, resave: true, saveUninitialized: true }));
app.use(cookieParser());
app.use(passport.initialize());
app.use(passport.session());

console.log("In Express top");

app.use(express.static(__dirname + '/views/src'));

console.log("In Express 11");

passport.serializeUser(function (user, done) {
    done(null, user);
});

passport.deserializeUser(function (user, done) {
    done(null, user);
});

app.post("/login", passport.authenticate('local'), function (req, res) {
    console.log('user' + req.user);
    var user = req.user;
    console.log(user);
    res.json(user);
});

app.get('/loggedin', function (req, res) {
    res.send(req.isAuthenticated() ? req.user : '0');
});

app.post('/logout', function (req, res) {
    req.logout();
    res.redirect('/login');
    //res.send(200);
});

app.get('/auth/google', passport.authenticate('google',
    {
        hd: 'gslab.com',
        scope: ['https://www.googleapis.com/auth/userinfo.profile',
            'https://www.googleapis.com/auth/userinfo.email']
    }),
    function (req, res) { } // this never gets called
);

app.get('/auth/google/callback', passport.authenticate('google',
    { successRedirect: '/#/dashboard', failureRedirect: '/#/login' }//this may change when website published to logout from all google services https://accounts.google.com/logout
));

app.use(function (req, res, next) {
    if (!req.user)
        res.header('Cache-Control', 'private, no-cache, no-store, must-revalidate');
    next();
});

var auth = function (req, res, next) {
    if (!req.isAuthenticated())
        res.send(401);
    else
        next();
};

app.get('/', function (request, response) {
    response.sendfile("views/src/index.html");
});

app.get('/idp1/api/idcnt', mongoOps.fetchIdeaCount);

app.get('/idp1/api/reclimit/:p_num', mongoOps.fetch);
app.post('/idp1/api/results', mongoOps.add);
//app.put('/idp1/api/results/:resultId', mongoOps.modify); //for later use

app.put('/idp1/api/results/:resultId', mongoOps.modify2);

app.get('/idp1/api/myreclimit/:uid/:pNum', mongoOps.fetchMyIdeas);
app.get('/idp1/api/myidcnt/:uid', mongoOps.fetchMyIdeaCount);
app.put('/idp1/api/updateidea/:iid', mongoOps.modifyIdea);

//Question master related routes
app.post('/idp1/api/question', mongoOps.upsertQuestion);
app.get('/idp1/api/question', mongoOps.getAllQuestion);
app.get('/idp1/api/question/:questionId', mongoOps.getQuestion);
app.delete('/idp1/api/question/:questionId', mongoOps.deleteQuestion);

//Role master related routes
app.post('/idp1/api/role', mongoOps.upsertRole);
app.get('/idp1/api/role', mongoOps.getAllRole);
app.get('/idp1/api/role/:roleId', mongoOps.getRole);
app.delete('/idp1/api/role/:roleId', mongoOps.deleteRole);

//Access rights related routes
app.get('/idp1/api/accessright', mongoOps.getAllAccessRight);

//Technology stuff
app.get('/idp1/api/techResults', mongoOps.fetchTechnology);
app.post('/idp1/api/techResults', mongoOps.addTechnology);
app.delete('/idp1/api/techResults/:id', mongoOps.delTechnology);
app.put('/idp1/api/techResults/:id', mongoOps.editTechnology);
app.get('/idp1/api/techResults/:id', mongoOps.getData);
app.post('/idp1/api/techResults', mongoOps.editTechnology);

app.get('/idp1/api/catresults', mongoOps.fetchCat);

app.get('/idp1/api/commentspnid/:iid/:pn', mongoOps.fetchCom2); //to fetch comments after pagination

app.get('/idp1/api/comments/count/:ideaId', mongoOps.fetchComCount); //to fetch comments count

if (app.post('/idp1/api/practice', mongoOps.addPractice)) { console.log("in practice post if"); }

app.put('/idp1/api/comments', mongoOps.modifyCom);

app.put('/idp1/api/updatecommentsNotify/:ideaId', mongoOps.resetCommentNotificationCount)

app.get('/idp1/api/getUserId/:userEmail', mongoOps.fetchUserData);
app.get('/idp1/api/userdetails/:userEmail', mongoOps.fetchUserData);
app.put('/idp1/api/userdetailstoupdate/:userId', mongoOps.updateUserData);
app.post('/idp1/api/userdetails', mongoOps.addUser);

app.post('/idp1/api/upsert_category', mongoOps.upsertCategory);
app.get('/idp1/api/fetch_categories', mongoOps.fetchCat);
app.get('/idp1/api/fetch_category/:categoryId', mongoOps.getSingleCat);
app.put('/idp1/api/delete_category/:categoryId/:userId', mongoOps.deleteCategory);

app.use('/idp11', express.static(path.join(__dirname, 'views/src/components')));
app.use('/idp2', express.static(path.join(__dirname, 'views/dist/js')));
app.use('/idp3', express.static(path.join(__dirname, 'views/src/img')));
app.use('/idp4', express.static(path.join(__dirname, 'views/src/templates')));
app.use('/idp5', express.static(path.join(__dirname, 'views/src/js')));
app.use('/idp6', express.static(path.join(__dirname, 'views/src')));

http.listen(port);
</code>```

And the web.config file is as follows:-

```<code><?xml version="1.0" encoding="utf-8"?>
<!--
     This configuration file is required if iisnode is used to run node processes behind
     IIS or IIS Express.  For more information, visit:

     https://github.com/tjanczuk/iisnode/blob/master/src/samples/configuration/web.config
-->

<configuration>
  <system.webServer>
    <!-- Visit http://blogs.msdn.com/b/windowsazure/archive/2013/11/14/introduction-to-websockets-on-windows-azure-web-sites.aspx for more information on WebSocket support -->
    <webSocket enabled="false" />
    <handlers>
      <!-- Indicates that the server.js file is a node.js site to be handled by the iisnode module -->
      <add name="iisnode" path="server.js" verb="*" modules="iisnode"/>
    </handlers>
    <rewrite>
      <rules>
        <!-- Do not interfere with requests for node-inspector debugging -->
        <rule name="NodeInspector" patternSyntax="ECMAScript" stopProcessing="true">
          <match url="^server.js\/debug[\/]?" />
        </rule>

        <!-- First we consider whether the incoming URL matches a physical file in the /public folder -->
        <rule name="StaticContent">
          <action type="Rewrite" url="public{REQUEST_URI}"/>
        </rule>

        <!-- All other URLs are mapped to the node.js site entry point -->
        <rule name="DynamicContent">
          <conditions>
            <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="True"/>
          </conditions>
          <action type="Rewrite" url="server.js"/>
        </rule>
      </rules>
    </rewrite>

    <!-- 'bin' directory has no special meaning in node.js and apps can be placed in it -->
    <security>
      <requestFiltering>
        <hiddenSegments>
          <remove segment="bin"/>
        </hiddenSegments>
      </requestFiltering>
    </security>

    <!-- Make sure error responses are left untouched -->
    <httpErrors existingResponse="PassThrough" />

    <!--
      You can control how Node is hosted within IIS using the following options:
        * watchedFiles: semi-colon separated list of files that will be watched for changes to restart the server
        * node_env: will be propagated to node as NODE_ENV environment variable
        * debuggingEnabled - controls whether the built-in debugger is enabled

      See https://github.com/tjanczuk/iisnode/blob/master/src/samples/configuration/web.config for a full list of options
    -->
    <!--<iisnode watchedFiles="web.config;*.js"/>-->
  </system.webServer>
</configuration>
</code>```

We hosted the project on azure and it is working fine. Also our azure web app resource is using iisnode. But on local machine when we deploy on IIS with help of iisnode we get following error :

.

答:
The error that you got tells you that your configuration is invalid.

Make sure that you configure the IIS correctly. See the examples at:

https://github.com/tjanczuk/iisnode

There are a lot of good resources and config examples there.

Body:
I am trying to deploy my MEAN framework application on IIS using iisnode on local machine.

My api call is working after hosting on IIS, but web application page is not loading because it can not load required css and js files related to web app.

My server.js contains following code:-

var express = require('express');
var app = express();
var http = require('http').Server(app);
var path = require('path');
var mongoOps = require('./MongoOperations.js');
var googleAuthOps = require('./passport_google.js');
var bodyparser = require('body-parser');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;

var cookieParser = require('cookie-parser');
var session = require('express-session');

exports.io = require('socket.io')(http);
var port = process.env.port || 1337;

app.use(bodyparser.json()); // for parsing application/json
app.use(bodyparser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
app.use(session({ secret: 'this is the secret' }));//, resave: true, saveUninitialized: true }));
app.use(cookieParser());
app.use(passport.initialize());
app.use(passport.session());

console.log("In Express top");

app.use(express.static(__dirname + '/views/src'));

console.log("In Express 11");

passport.serializeUser(function (user, done) {
    done(null, user);
});

passport.deserializeUser(function (user, done) {
    done(null, user);
});

app.post("/login", passport.authenticate('local'), function (req, res) {
    console.log('user' + req.user);
    var user = req.user;
    console.log(user);
    res.json(user);
});

app.get('/loggedin', function (req, res) {
    res.send(req.isAuthenticated() ? req.user : '0');
});

app.post('/logout', function (req, res) {
    req.logout();
    res.redirect('/login');
    //res.send(200);
});

app.get('/auth/google', passport.authenticate('google',
    {
        hd: 'gslab.com',
        scope: ['https://www.googleapis.com/auth/userinfo.profile',
            'https://www.googleapis.com/auth/userinfo.email']
    }),
    function (req, res) { } // this never gets called
);

app.get('/auth/google/callback', passport.authenticate('google',
    { successRedirect: '/#/dashboard', failureRedirect: '/#/login' }//this may change when website published to logout from all google services https://accounts.google.com/logout
));

app.use(function (req, res, next) {
    if (!req.user)
        res.header('Cache-Control', 'private, no-cache, no-store, must-revalidate');
    next();
});

var auth = function (req, res, next) {
    if (!req.isAuthenticated())
        res.send(401);
    else
        next();
};

app.get('/', function (request, response) {
    response.sendfile("views/src/index.html");
});

app.get('/idp1/api/idcnt', mongoOps.fetchIdeaCount);

app.get('/idp1/api/reclimit/:p_num', mongoOps.fetch);
app.post('/idp1/api/results', mongoOps.add);
//app.put('/idp1/api/results/:resultId', mongoOps.modify); //for later use

app.put('/idp1/api/results/:resultId', mongoOps.modify2);

app.get('/idp1/api/myreclimit/:uid/:pNum', mongoOps.fetchMyIdeas);
app.get('/idp1/api/myidcnt/:uid', mongoOps.fetchMyIdeaCount);
app.put('/idp1/api/updateidea/:iid', mongoOps.modifyIdea);

//Question master related routes
app.post('/idp1/api/question', mongoOps.upsertQuestion);
app.get('/idp1/api/question', mongoOps.getAllQuestion);
app.get('/idp1/api/question/:questionId', mongoOps.getQuestion);
app.delete('/idp1/api/question/:questionId', mongoOps.deleteQuestion);

//Role master related routes
app.post('/idp1/api/role', mongoOps.upsertRole);
app.get('/idp1/api/role', mongoOps.getAllRole);
app.get('/idp1/api/role/:roleId', mongoOps.getRole);
app.delete('/idp1/api/role/:roleId', mongoOps.deleteRole);

//Access rights related routes
app.get('/idp1/api/accessright', mongoOps.getAllAccessRight);

//Technology stuff
app.get('/idp1/api/techResults', mongoOps.fetchTechnology);
app.post('/idp1/api/techResults', mongoOps.addTechnology);
app.delete('/idp1/api/techResults/:id', mongoOps.delTechnology);
app.put('/idp1/api/techResults/:id', mongoOps.editTechnology);
app.get('/idp1/api/techResults/:id', mongoOps.getData);
app.post('/idp1/api/techResults', mongoOps.editTechnology);

app.get('/idp1/api/catresults', mongoOps.fetchCat);

app.get('/idp1/api/commentspnid/:iid/:pn', mongoOps.fetchCom2); //to fetch comments after pagination

app.get('/idp1/api/comments/count/:ideaId', mongoOps.fetchComCount); //to fetch comments count

if (app.post('/idp1/api/practice', mongoOps.addPractice)) { console.log("in practice post if"); }

app.put('/idp1/api/comments', mongoOps.modifyCom);

app.put('/idp1/api/updatecommentsNotify/:ideaId', mongoOps.resetCommentNotificationCount)

app.get('/idp1/api/getUserId/:userEmail', mongoOps.fetchUserData);
app.get('/idp1/api/userdetails/:userEmail', mongoOps.fetchUserData);
app.put('/idp1/api/userdetailstoupdate/:userId', mongoOps.updateUserData);
app.post('/idp1/api/userdetails', mongoOps.addUser);

app.post('/idp1/api/upsert_category', mongoOps.upsertCategory);
app.get('/idp1/api/fetch_categories', mongoOps.fetchCat);
app.get('/idp1/api/fetch_category/:categoryId', mongoOps.getSingleCat);
app.put('/idp1/api/delete_category/:categoryId/:userId', mongoOps.deleteCategory);

app.use('/idp11', express.static(path.join(__dirname, 'views/src/components')));
app.use('/idp2', express.static(path.join(__dirname, 'views/dist/js')));
app.use('/idp3', express.static(path.join(__dirname, 'views/src/img')));
app.use('/idp4', express.static(path.join(__dirname, 'views/src/templates')));
app.use('/idp5', express.static(path.join(__dirname, 'views/src/js')));
app.use('/idp6', express.static(path.join(__dirname, 'views/src')));

http.listen(port);

And the web.config file is as follows:-

<?xml version="1.0" encoding="utf-8"?>

<configuration>
  <system.webServer>

    <webSocket enabled="false" />
    <handlers>

      <add name="iisnode" path="server.js" verb="*" modules="iisnode"/>
    </handlers>
    <rewrite>
      <rules>

        <rule name="NodeInspector" patternSyntax="ECMAScript" stopProcessing="true">
          <match url="^server.js\/debug[\/]?" />
        </rule>

        <rule name="StaticContent">
          <action type="Rewrite" url="public{REQUEST_URI}"/>
        </rule>

        <rule name="DynamicContent">
          <conditions>
            <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="True"/>
          </conditions>
          <action type="Rewrite" url="server.js"/>
        </rule>
      </rules>
    </rewrite>

    <security>
      <requestFiltering>
        <hiddenSegments>
          <remove segment="bin"/>
        </hiddenSegments>
      </requestFiltering>
    </security>

    <httpErrors existingResponse="PassThrough" />

  </system.webServer>
</configuration>

We hosted the project on azure and it is working fine. Also our azure web app resource is using iisnode. But on local machine when we deploy on IIS with help of iisnode we get following error :

.


问:
What is version support of Module created in DotnetNuke 7?
I have created a Module(Portal). I am going to publish it. I just don't know which version it can support. The previous versions and future versions. I am just curious above this all specially in case of .DLLs.

Please suggest me.

Development system

1- Visual Studio 2015

2- DotnetNuke 7

DLLs

答:
It will all depend on what version of the DotNetNuke.DLLs you compile your module against.

Typically if you compile against a version, say 07.00.01, the module will run on that version AND any NEWER version of DNN.

There are some cases where there are breaking changes for modules on upgrade of the DNN version, but they are pretty few and far between.


问:
Oracle db query - multiple questions regarding join and returning only latest date
I have 2 tables, Inventory and Transactions
In Inventory i have columns Part_id, Location_Id and Zone_id (all VARCHAR)
In Transactions i have columns Part_id, Code and Date (Part_ID and Code are VARCHAR and Date is TIMESTAMP with local timezone)

I would like to see all Part_id, Location_id and Zone_Id from Inventory table and a column which would return latest date for Code 'Pick' for that Part_Id from transactions table if exists and if not, return a blank for that Part_ID.
Problem is that Tranasactions can match the Part_Id in Inventory with other Codes. So just going for inventory.part_id = transactions.part_id will not work.
And when there is no record for a Part_id with code Pick, how to get that returned...

```<code>Inventory:                       Transactions:

│Part_ID│Location_ID│Zone_ID│    │Part_ID│Code   │Date
│a001   │A          │Z      │    │a001   │Pick   │01/01/2017│
│b002   │B          │X      │    │b002   │Check  │01/02/2017│
│c003   │C          │Y      │    │c003   │Receive│05/02/2017│
│d004   │D          │Q      │    │d004   │Pick   │09/02/2017│
                                 │a001   │Pick   │11/02/2017│

Wanted result:

│Part_ID│Location_ID│Zone_ID│LatestDateofPick│
│a001   │A          │Z      │11/02/2017      │
│b002   │B          │X      │                │
│c003   │C          │Y      │                │
│d004   │D          │Q      │09/02/2017      │
</code>```

I'm just a beginner with SQL so i'm kinda in square one with this, please be merciful. :)
Thanks for helping me out on this one!

答:
I see this using an outer join and a max for the date</p>

```<code>  -- Start test data
  with inventory (part_id, location_id, zone_id) as
       (select 'a001','A','Z' from dual union all
        select 'b002','B','X' from dual union all
        select 'c003','C','Y' from dual union all
        select 'd004','D','Q' from dual),
       transaction (part_id, code, txn_date) as
       (select 'a001','Pick',to_date( '01-jan-17','DD-MON-RR') from dual union all
        select 'b002','Check',to_date( '02-JAN-17','DD-MON-RR') from dual union all
        select 'c003','Receive',to_date( '02-may-17','DD-MON-RR') from dual union all
        select 'd004','Pick',to_date( '02-sep-17','DD-MON-RR') from dual union all
        select 'a001','Pick',to_date( '02-nov-17','DD-MON-RR') from dual)
  -- end test data
select inv.part_id,
       inv.location_id,
       inv.zone_id,
       MAX(txn.txn_date)
from inventory inv
     left outer join transaction txn on (inv.part_id = txn.part_id AND txn.code = 'Pick')
group by inv.part_id, inv.location_id, inv.zone_id;

"PART_ID"             "LOCATION_ID"         "ZONE_ID"     MAX(TXN.TXN_DATE)"
"d004"                "D"                   "Q"           "09/02/2017 00:00:00"
"c003"                "C"                   "Y"           ""
"a001"                "A"                   "Z"           "11/02/2017 00:00:00"
"b002"                "B"                   "X"           ""
</code>```

Body:
I have 2 tables, Inventory and Transactions
In Inventory i have columns Part_id, Location_Id and Zone_id (all VARCHAR)
In Transactions i have columns Part_id, Code and Date (Part_ID and Code are VARCHAR and Date is TIMESTAMP with local timezone)

I would like to see all Part_id, Location_id and Zone_Id from Inventory table and a column which would return latest date for Code 'Pick' for that Part_Id from transactions table if exists and if not, return a blank for that Part_ID.
Problem is that Tranasactions can match the Part_Id in Inventory with other Codes. So just going for inventory.part_id = transactions.part_id will not work.
And when there is no record for a Part_id with code Pick, how to get that returned...

Inventory:                       Transactions:

│Part_ID│Location_ID│Zone_ID│    │Part_ID│Code   │Date
│a001   │A          │Z      │    │a001   │Pick   │01/01/2017│
│b002   │B          │X      │    │b002   │Check  │01/02/2017│
│c003   │C          │Y      │    │c003   │Receive│05/02/2017│
│d004   │D          │Q      │    │d004   │Pick   │09/02/2017│
                                 │a001   │Pick   │11/02/2017│

Wanted result:

│Part_ID│Location_ID│Zone_ID│LatestDateofPick│
│a001   │A          │Z      │11/02/2017      │
│b002   │B          │X      │                │
│c003   │C          │Y      │                │
│d004   │D          │Q      │09/02/2017      │

I'm just a beginner with SQL so i'm kinda in square one with this, please be merciful. :)
Thanks for helping me out on this one!

Body:
I see this using an outer join and a max for the date

  -- Start test data
  with inventory (part_id, location_id, zone_id) as
       (select 'a001','A','Z' from dual union all
        select 'b002','B','X' from dual union all
        select 'c003','C','Y' from dual union all
        select 'd004','D','Q' from dual),
       transaction (part_id, code, txn_date) as
       (select 'a001','Pick',to_date( '01-jan-17','DD-MON-RR') from dual union all
        select 'b002','Check',to_date( '02-JAN-17','DD-MON-RR') from dual union all
        select 'c003','Receive',to_date( '02-may-17','DD-MON-RR') from dual union all
        select 'd004','Pick',to_date( '02-sep-17','DD-MON-RR') from dual union all
        select 'a001','Pick',to_date( '02-nov-17','DD-MON-RR') from dual)
  -- end test data
select inv.part_id,
       inv.location_id,
       inv.zone_id,
       MAX(txn.txn_date)
from inventory inv
     left outer join transaction txn on (inv.part_id = txn.part_id AND txn.code = 'Pick')
group by inv.part_id, inv.location_id, inv.zone_id;

"PART_ID"             "LOCATION_ID"         "ZONE_ID"     MAX(TXN.TXN_DATE)"
"d004"                "D"                   "Q"           "09/02/2017 00:00:00"
"c003"                "C"                   "Y"           ""
"a001"                "A"                   "Z"           "11/02/2017 00:00:00"
"b002"                "B"                   "X"           ""


问:
Including file inside a class php
I am doing something using classes in php for very first time.
I am trying to fetch an return object array items in class.

This is my class

```<code>class User {

    $dbconn = include("config.php");
    private $dbHost     = $dbconn->host;
    private $dbUsername = $dbconn->username;
    private $dbPassword = $dbconn->pass;
    private $dbName     = $dbconn->database;
    private $userTbl    = 'users';

    function __construct(){
        if(!isset($this->db)){
            // Connect to the database
            $conn = new mysqli($this->dbHost, $this->dbUsername, $this->dbPassword, $this->dbName);
            if($conn->connect_error){
                die("Failed to connect with MySQL: " . $conn->connect_error);
            }else{
                $this->db = $conn;
            }
        }
    }
}
</code>```

This is my config.php file

```<code>return (object) array(
    'host' => 'localhost',
    'username' => 'my_user',
    'pass' => 'my_pass',
    'database' => 'my_db'
);
</code>```

How do i do it?

```<code>PHP Parse error:  syntax error, unexpected '$dbconn' (T_VARIABLE)
</code>```

答:
Try this way of using it.

```<code><?php
class User
{

    private $dbconn = null;
    private $dbHost;
    private $dbUsername;
    private $dbPassword;
    private $dbName;
    private $userTbl = 'users';

    function __construct()
    {
        include 'config.php'; //included file in constructor
        if (!isset($this->db))
        {
            $this->dbHost= $this->dbconn->host;
            $this->dbUsername= $this->dbconn->username;
            $this->dbPassword= $this->dbconn->pass;
            $this->dbName= $this->dbconn->database;
            // Connect to the database
            $conn = new mysqli($this->dbHost, $this->dbUsername, $this->dbPassword, $this->dbName);
            if ($conn->connect_error)
            {
                die("Failed to connect with MySQL: " . $conn->connect_error);
            } else
            {
                $this->db = $conn;
            }
        }
    }

}
</code>```

Config.php

```<code><?php
$this->dbconn= (object) array(
    'host' => 'localhost',
    'username' => 'my_user',
    'pass' => 'my_pass',
    'database' => 'my_db'
);
</code>```

Title: Including file inside a class php

Body:
I am doing something using classes in php for very first time.
I am trying to fetch an return object array items in class.

This is my class

class User {

    $dbconn = include("config.php");
    private $dbHost     = $dbconn->host;
    private $dbUsername = $dbconn->username;
    private $dbPassword = $dbconn->pass;
    private $dbName     = $dbconn->database;
    private $userTbl    = 'users';

    function __construct(){
        if(!isset($this->db)){
            // Connect to the database
            $conn = new mysqli($this->dbHost, $this->dbUsername, $this->dbPassword, $this->dbName);
            if($conn->connect_error){
                die("Failed to connect with MySQL: " . $conn->connect_error);
            }else{
                $this->db = $conn;
            }
        }
    }
}

This is my config.php file

return (object) array(
    'host' => 'localhost',
    'username' => 'my_user',
    'pass' => 'my_pass',
    'database' => 'my_db'
);

How do i do it?

PHP Parse error:  syntax error, unexpected '$dbconn' (T_VARIABLE)

Body:
Try this way of using it.

<?php
class User
{

    private $dbconn = null;
    private $dbHost;
    private $dbUsername;
    private $dbPassword;
    private $dbName;
    private $userTbl = 'users';

    function __construct()
    {
        include 'config.php'; //included file in constructor
        if (!isset($this->db))
        {
            $this->dbHost= $this->dbconn->host;
            $this->dbUsername= $this->dbconn->username;
            $this->dbPassword= $this->dbconn->pass;
            $this->dbName= $this->dbconn->database;
            // Connect to the database
            $conn = new mysqli($this->dbHost, $this->dbUsername, $this->dbPassword, $this->dbName);
            if ($conn->connect_error)
            {
                die("Failed to connect with MySQL: " . $conn->connect_error);
            } else
            {
                $this->db = $conn;
            }
        }
    }

}

Config.php

<?php
$this->dbconn= (object) array(
    'host' => 'localhost',
    'username' => 'my_user',
    'pass' => 'my_pass',
    'database' => 'my_db'
);


问:
jQuery UI ui-autocomplete-loading spinner not stopping/disappear when found results
I am using JQuery UI autocomplete-loading spinner in my project by adding .ui-autocomplete-loading class. When I start typing in the editor box, the spinner shows up as expect. If there is no match results, the loading spinner disappear which indicates the search complete. But if there is a match found, the spinner is still showing, even after a selection is made. (see below pic)

My goal is to get this results: (when search complete or results found, spinner should be removed/stopped)
https://jqueryui.com/autocomplete/#multiple-remote

Here is my example code:

View:

```<code>@model AutoCompleteInMVCJson.Models.City

@{
    ViewBag.Title = "www.myexample.com";
}
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<style>
    .ui-autocomplete-loading {
        background: white url("../images/ui-anim_basic_16x16.gif") right center no-repeat;
    }
</style>
<script type="text/javascript">
    $(document).ready(function () {
        $("#Name").autocomplete({
            source: function (request, response) {
                $.ajax({
                    url: "/Home/Index",
                    type: "POST",
                    dataType: "json",
                    data: { Prefix: request.term },
                    success: function (data) {
                        response($.map(data, function (item) {
                            return { label: item.Name, value: item.Name };
                        }))

                    }
                })
            },
            messages: {
                noResults: "", results: ""
            }
        });
    })
</script>
</code>```

Model

```<code>public class City
{
    public int Id { get; set; }
    public string Name { get; set; }

}
</code>```

Controller:

```<code>[HttpPost]
        public JsonResult Index(string Prefix)
        {
            //Note : you can bind same list from database
            List<City> ObjList = new List<City>()
            {

                new City {Id=1,Name="Latur" },
                new City {Id=2,Name="Mumbai" },
                new City {Id=3,Name="Pune" },
                new City {Id=4,Name="Delhi" },
                new City {Id=5,Name="Dehradun" },
                new City {Id=6,Name="Noida" },
                new City {Id=7,Name="New Delhi" }

        };
            //Searching records from list using LINQ query
            var CityName = (from N in ObjList
                            where N.Name.StartsWith(Prefix)
                          select new { N.Name });
            return Json(CityName, JsonRequestBehavior.AllowGet);
        }
    }
</code>```

How can I fix this issue? Thanks in advance.

答:
Thanks for Curiousdev's input and after my further debugging I found a solution.

Add

```<code>$("#Name").removeClass("ui-autocomplete-loading");
</code>```

in both success and complete method will resolve this issue.

Body:
I am using JQuery UI autocomplete-loading spinner in my project by adding .ui-autocomplete-loading class. When I start typing in the editor box, the spinner shows up as expect. If there is no match results, the loading spinner disappear which indicates the search complete. But if there is a match found, the spinner is still showing, even after a selection is made. (see below pic)

My goal is to get this results: (when search complete or results found, spinner should be removed/stopped)
https://jqueryui.com/autocomplete/#multiple-remote

Here is my example code:

View:

@model AutoCompleteInMVCJson.Models.City

@{
    ViewBag.Title = "www.myexample.com";
}
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">

Model

public class City
{
    public int Id { get; set; }
    public string Name { get; set; }

}

Controller:

[HttpPost]
        public JsonResult Index(string Prefix)
        {
            //Note : you can bind same list from database
            List<City> ObjList = new List<City>()
            {

                new City {Id=1,Name="Latur" },
                new City {Id=2,Name="Mumbai" },
                new City {Id=3,Name="Pune" },
                new City {Id=4,Name="Delhi" },
                new City {Id=5,Name="Dehradun" },
                new City {Id=6,Name="Noida" },
                new City {Id=7,Name="New Delhi" }

        };
            //Searching records from list using LINQ query
            var CityName = (from N in ObjList
                            where N.Name.StartsWith(Prefix)
                          select new { N.Name });
            return Json(CityName, JsonRequestBehavior.AllowGet);
        }
    }

How can I fix this issue? Thanks in advance.

Body:
Thanks for Curiousdev's input and after my further debugging I found a solution.

Add

$("#Name").removeClass("ui-autocomplete-loading");

in both success and complete method will resolve this issue.


问:
Hide Item in WPF ListView
I have a WPF XAML ListView which contains a GridView with two GridViewColumns.
The ListView has its ItemsSource bound to my class like so:

```<code><ListView Name="MyListView" ItemsSource="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type mynameSpace:MyClass}}, Path=ItemsSource}" >

<ListView.ItemContainerStyle>
    <Style TargetType="{x:Type ListViewItem}" BasedOn="{StaticResource ListViewItemStyle}">
        <Setter Property="HorizontalContentAlignment" Value="Stretch"/>
        <Setter Property="VerticalContentAlignment" Value="Stretch"/>
        <!--<Setter Property="Visibility" Value="{Binding RelativeSource={RelativeSource Self}, Path=IsEnabled, Converter={StaticResource BoolToVisibility}}"></Setter>-->
        <Setter Property="Visibility" Value="{Binding Path=IsEnabled, Converter={StaticResource BoolToVisibility}}"/>
    </Style>
</ListView.ItemContainerStyle>
<ListView.View>
   <GridView>
        // blah blah
   </GridView>
</ListView>
</code>```

I am attempting to hide a ListView item based on a property IsEnabled so I have tried the two methods above but neither work as the item still appears in the ListView:

```<code><Setter Property="Visibility" Value="{Binding RelativeSource={RelativeSource Self}, Path=IsEnabled, Converter={StaticResource BoolToVisibility}}"></Setter>
<Setter Property="Visibility" Value="{Binding Path=IsEnabled, Converter={StaticResource BoolToVisibility}}"/>
</code>```

How can I hide an item in a list view like this?

答:
Where is the IsEnabled property defined, how is your "ListViewItemStyle" defined and what converter are you using?

You haven't provided a reproducible sample of your issue but you could refer to the following sample code which does hide the second of three items in the ListView as expected:

```<code>public class DataItem
{
    public bool IsEnabled { get; set; }
}

...

public MainWindow()
{
    InitializeComponent();

    MyListView123.ItemsSource = new List<DataItem>
    {
        new DataItem() { IsEnabled = true }, new DataItem() { IsEnabled = false }, new DataItem() { IsEnabled = true }
    };
}
</code>```

```<code><ListView Name="MyListView123">
    <ListView.Resources>
        <BooleanToVisibilityConverter x:Key="BoolToVisibility" />
    </ListView.Resources>
    <ListView.ItemContainerStyle>
        <Style TargetType="{x:Type ListViewItem}">
            <Setter Property="Visibility" Value="{Binding Path=IsEnabled, Converter={StaticResource BoolToVisibility}}"/>
        </Style>
    </ListView.ItemContainerStyle>
    <ListView.View>
        <GridView>
            <GridViewColumn DisplayMemberBinding="{Binding IsEnabled}" />
        </GridView>
    </ListView.View>
</ListView>
</code>```

Title: Hide Item in WPF ListView

Body:
I have a WPF XAML ListView which contains a GridView with two GridViewColumns.
The ListView has its ItemsSource bound to my class like so:

<ListView Name="MyListView" ItemsSource="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type mynameSpace:MyClass}}, Path=ItemsSource}" >

<ListView.ItemContainerStyle>

</ListView.ItemContainerStyle>
<ListView.View>
   <GridView>
        // blah blah
   </GridView>
</ListView>

I am attempting to hide a ListView item based on a property IsEnabled so I have tried the two methods above but neither work as the item still appears in the ListView:

<Setter Property="Visibility" Value="{Binding RelativeSource={RelativeSource Self}, Path=IsEnabled, Converter={StaticResource BoolToVisibility}}"></Setter>
<Setter Property="Visibility" Value="{Binding Path=IsEnabled, Converter={StaticResource BoolToVisibility}}"/>

How can I hide an item in a list view like this?

Body:
Where is the IsEnabled property defined, how is your "ListViewItemStyle" defined and what converter are you using?

You haven't provided a reproducible sample of your issue but you could refer to the following sample code which does hide the second of three items in the ListView as expected:

public class DataItem
{
    public bool IsEnabled { get; set; }
}

...

public MainWindow()
{
    InitializeComponent();

    MyListView123.ItemsSource = new List<DataItem>
    {
        new DataItem() { IsEnabled = true }, new DataItem() { IsEnabled = false }, new DataItem() { IsEnabled = true }
    };
}

<ListView Name="MyListView123">
    <ListView.Resources>
        <BooleanToVisibilityConverter x:Key="BoolToVisibility" />
    </ListView.Resources>
    <ListView.ItemContainerStyle>
        <Style TargetType="{x:Type ListViewItem}">
            <Setter Property="Visibility" Value="{Binding Path=IsEnabled, Converter={StaticResource BoolToVisibility}}"/>
        </Style>
    </ListView.ItemContainerStyle>
    <ListView.View>
        <GridView>
            <GridViewColumn DisplayMemberBinding="{Binding IsEnabled}" />
        </GridView>
    </ListView.View>
</ListView>


问:
Display titles which are missing association values partially or completely
I am having problem writing SQL query for the following scenario. I need someone's help to write the query.

I have the following tables 7 tables:

1) Titles

```<code>ID    Title                                                        Author
-------------------------------------------------------------------------
1     The Hidden Language of Computer Hardware and Software   Charles Petzold
2     Paths, Dangers, Strategies                              Nick Bostrom
3     The Smart Girl's Guide to Privacy                       Violet Blue
4     Introduction to Algorithms                              Thomas H. Cormen
5     Machine Learning in Action                              Peter Harrington
...
</code>```

2) Themes

```<code>ID         Name
------------------------------------------
1          Science Fiction
2          Biography
3          Painting
...
</code>```

3)   Subjects

```<code>ID           Name
-----------------------------------
1            Science
2            Technology
3            Music
4            Geography
...
</code>```

4)  Grades

```<code>ID            Name
------------------------------------
1             Grade 1
2             Grade 2
3             Grade 3
4             Grade 4
5             Grade 5
...
</code>```

5) TitleThemeAssociation

```<code>TitleID         ThemeID
------------------------------------------
1               1
1               3
4               2
4               3
...
</code>```

6) TitleSubjectAssociaton

```<code>TitleID          SubjectID
---------------------------------
1                1
1                3
2                1
2                3
4                1
4                2
...
</code>```

7) TitleGradeAssociaton

```<code>TitleID              GradeID
1                    1
1                    2
1                    3
2                    1
2                    2
...
</code>```

I need to write a query to display only titles which are missing any of three values (Themes, Subjects and Grades) or not assigned values completely. I should not display the title if all three values (Themes, Subjects, Grades) are assigned. In the above data set since TitleID 1 has all three values it should not be present in the list. TitleID 2 has only Subjects and Grades assigned but not Themes so it should be displayed in the output. While listing the titles if a title has multiple values then they should be contacted with comma (,) separator.

So the final output of the above data set should be as below:

Output:

```<code>Title ID      Title                      Theme        Subject           Grade
-------------------------------------------------------------------------------------------
2      Paths, Dangers, Strategies          -          Science, Music    Grade 1, Grade 2
3      The Smart Girl's Guide to Privacy   -           -                   -
4      Introduction to Algorithms         Biography, Painting    Science, Technology    -
5      Machine Learning in Action          -              -              -
</code>```

答:
Hope this Helps.</p>

```<code>;WITH cte_Titles (ID,Title,Author)   AS
(
SELECT 1,'The Hidden Language of Computer Hardware and Software','Charles Petzold' UNION ALL
SELECT 2,'Paths, Dangers, Strategies','Nick Bostrom' UNION ALL
SELECT 3,'The Smart Girls Guide to Privacy','Violet Blue' UNION ALL
SELECT 4,'Introduction to Algorithms','Thomas H. Cormen' UNION ALL
SELECT 5,'Machine Learning in Action','Peter Harrington'
),cte_Themes(ID,Name) AS
(
SELECT 1,'Science Fiction' UNION ALL
SELECT 2,'Biography' UNION ALL
SELECT 3,'Painting'
),cte_Subjects(ID,Name) AS
(
SELECT 1,'Science' UNION ALL
SELECT 2,'Technology' UNION ALL
SELECT 3,'Music' UNION ALL
SELECT 4,'Geography'
),cte_Grades(ID,Name) AS
(
SELECT 1,'Grade 1' UNION ALL
SELECT 2,'Grade 2' UNION ALL
SELECT 3,'Grade 3' UNION ALL
SELECT 4,'Grade 4' UNION ALL
SELECT 5,'Grade 5'
),cte_TitleThemeAssociation(TitleID,ThemeID) AS
(
SELECT 1,1 UNION ALL
SELECT 1,3 UNION ALL
SELECT 4,2 UNION ALL
SELECT 4,3
),cte_TitleSubjectAssociaton(TitleID,SubjectID) AS
(
SELECT 1, 1 UNION ALL
SELECT 1, 3 UNION ALL
SELECT 2, 1 UNION ALL
SELECT 2, 3 UNION ALL
SELECT 4, 1 UNION ALL
SELECT 4, 2
),cte_TitleGradeAssociaton(TitleID,GradeID) AS
(
SELECT 1, 1 UNION ALL
SELECT 1, 2 UNION ALL
SELECT 1, 3 UNION ALL
SELECT 2, 1 UNION ALL
SELECT 2, 2
)
,cte_ResultSet AS
(
SELECT DISTINCT t.ID AS TitleID,
    t.Title,
    th.NAME AS Theme,
    s.NAME AS Subject,
    g.NAME AS Grade
FROM cte_Titles t
LEFT JOIN cte_TitleThemeAssociation tta
    ON t.ID = tta.TitleID
LEFT JOIN cte_Themes th
    ON tta.ThemeID = th.ID
LEFT JOIN cte_TitleSubjectAssociaton tsa
    ON tsa.TitleID = t.ID
LEFT JOIN cte_Subjects s
    ON tsa.SubjectID = s.ID
LEFT JOIN cte_TitleGradeAssociaton tga
    ON tga.TitleID = t.ID
LEFT JOIN cte_Grades g
    ON g.ID = tga.GradeID
)
SELECT DISTINCT Title
                , STUFF((SELECT DISTINCT ',' + SUB.Theme AS [text()]
                        FROM cte_ResultSet SUB
                        WHERE SUB.TitleID = CAT.TitleID
                        FOR XML PATH('')
                        ), 1, 1, '' ) AS Theme
                , STUFF((SELECT DISTINCT ',' + SUB.Subject AS [text()]
                        FROM cte_ResultSet SUB
                        WHERE SUB.TitleID = CAT.TitleID
                        FOR XML PATH('')
                        ), 1, 1, '' ) AS Subject
                , STUFF((SELECT DISTINCT ',' + SUB.Grade AS [text()]
                        FROM cte_ResultSet SUB
                        WHERE SUB.TitleID = CAT.TitleID
                        FOR XML PATH('')
                        ), 1, 1, '' ) AS Grade
FROM cte_ResultSet CAT
</code>```

Body:
I am having problem writing SQL query for the following scenario. I need someone's help to write the query.

I have the following tables 7 tables:

1) Titles

ID    Title                                                        Author
-------------------------------------------------------------------------
1     The Hidden Language of Computer Hardware and Software   Charles Petzold
2     Paths, Dangers, Strategies                              Nick Bostrom
3     The Smart Girl's Guide to Privacy                       Violet Blue
4     Introduction to Algorithms                              Thomas H. Cormen
5     Machine Learning in Action                              Peter Harrington
...

2) Themes

ID         Name
------------------------------------------
1          Science Fiction
2          Biography
3          Painting
...

3)   Subjects

ID           Name
-----------------------------------
1            Science
2            Technology
3            Music
4            Geography
...

4)  Grades

ID            Name
------------------------------------
1             Grade 1
2             Grade 2
3             Grade 3
4             Grade 4
5             Grade 5
...

5) TitleThemeAssociation

TitleID         ThemeID
------------------------------------------
1               1
1               3
4               2
4               3
...

6) TitleSubjectAssociaton

TitleID          SubjectID
---------------------------------
1                1
1                3
2                1
2                3
4                1
4                2
...

7) TitleGradeAssociaton

TitleID              GradeID
1                    1
1                    2
1                    3
2                    1
2                    2
...

I need to write a query to display only titles which are missing any of three values (Themes, Subjects and Grades) or not assigned values completely. I should not display the title if all three values (Themes, Subjects, Grades) are assigned. In the above data set since TitleID 1 has all three values it should not be present in the list. TitleID 2 has only Subjects and Grades assigned but not Themes so it should be displayed in the output. While listing the titles if a title has multiple values then they should be contacted with comma (,) separator.

So the final output of the above data set should be as below:

Output:

Title ID      Title                      Theme        Subject           Grade
-------------------------------------------------------------------------------------------
2      Paths, Dangers, Strategies          -          Science, Music    Grade 1, Grade 2
3      The Smart Girl's Guide to Privacy   -           -                   -
4      Introduction to Algorithms         Biography, Painting    Science, Technology    -
5      Machine Learning in Action          -              -              -

Body:
Hope this Helps.

;WITH cte_Titles (ID,Title,Author)   AS
(
SELECT 1,'The Hidden Language of Computer Hardware and Software','Charles Petzold' UNION ALL
SELECT 2,'Paths, Dangers, Strategies','Nick Bostrom' UNION ALL
SELECT 3,'The Smart Girls Guide to Privacy','Violet Blue' UNION ALL
SELECT 4,'Introduction to Algorithms','Thomas H. Cormen' UNION ALL
SELECT 5,'Machine Learning in Action','Peter Harrington'
),cte_Themes(ID,Name) AS
(
SELECT 1,'Science Fiction' UNION ALL
SELECT 2,'Biography' UNION ALL
SELECT 3,'Painting'
),cte_Subjects(ID,Name) AS
(
SELECT 1,'Science' UNION ALL
SELECT 2,'Technology' UNION ALL
SELECT 3,'Music' UNION ALL
SELECT 4,'Geography'
),cte_Grades(ID,Name) AS
(
SELECT 1,'Grade 1' UNION ALL
SELECT 2,'Grade 2' UNION ALL
SELECT 3,'Grade 3' UNION ALL
SELECT 4,'Grade 4' UNION ALL
SELECT 5,'Grade 5'
),cte_TitleThemeAssociation(TitleID,ThemeID) AS
(
SELECT 1,1 UNION ALL
SELECT 1,3 UNION ALL
SELECT 4,2 UNION ALL
SELECT 4,3
),cte_TitleSubjectAssociaton(TitleID,SubjectID) AS
(
SELECT 1, 1 UNION ALL
SELECT 1, 3 UNION ALL
SELECT 2, 1 UNION ALL
SELECT 2, 3 UNION ALL
SELECT 4, 1 UNION ALL
SELECT 4, 2
),cte_TitleGradeAssociaton(TitleID,GradeID) AS
(
SELECT 1, 1 UNION ALL
SELECT 1, 2 UNION ALL
SELECT 1, 3 UNION ALL
SELECT 2, 1 UNION ALL
SELECT 2, 2
)
,cte_ResultSet AS
(
SELECT DISTINCT t.ID AS TitleID,
    t.Title,
    th.NAME AS Theme,
    s.NAME AS Subject,
    g.NAME AS Grade
FROM cte_Titles t
LEFT JOIN cte_TitleThemeAssociation tta
    ON t.ID = tta.TitleID
LEFT JOIN cte_Themes th
    ON tta.ThemeID = th.ID
LEFT JOIN cte_TitleSubjectAssociaton tsa
    ON tsa.TitleID = t.ID
LEFT JOIN cte_Subjects s
    ON tsa.SubjectID = s.ID
LEFT JOIN cte_TitleGradeAssociaton tga
    ON tga.TitleID = t.ID
LEFT JOIN cte_Grades g
    ON g.ID = tga.GradeID
)
SELECT DISTINCT Title
                , STUFF((SELECT DISTINCT ',' + SUB.Theme AS [text()]
                        FROM cte_ResultSet SUB
                        WHERE SUB.TitleID = CAT.TitleID
                        FOR XML PATH('')
                        ), 1, 1, '' ) AS Theme
                , STUFF((SELECT DISTINCT ',' + SUB.Subject AS [text()]
                        FROM cte_ResultSet SUB
                        WHERE SUB.TitleID = CAT.TitleID
                        FOR XML PATH('')
                        ), 1, 1, '' ) AS Subject
                , STUFF((SELECT DISTINCT ',' + SUB.Grade AS [text()]
                        FROM cte_ResultSet SUB
                        WHERE SUB.TitleID = CAT.TitleID
                        FOR XML PATH('')
                        ), 1, 1, '' ) AS Grade
FROM cte_ResultSet CAT


问:
matching the regular expression with the whole string
im kinda strumped in a situation where i need to match a whole string with a regular expression rather than finding if the pattern exists in the string.

suppose if i have a regular expression

```<code>/\\^^\\w+\\$^/
</code>```

what i want is that the code will run through various strings , compare the strings with the regular expression and perform some task if the strings start and end with a ^.

Examples

^hello world^ is a match

my ^hello world^ should not be a match

the php function preg_match matches both of the results

any clues ???

答:
Here is a way to do the job:

```<code>$strs = array('^hello world^', 'my ^hello world^');
foreach($strs as $str) {
    echo $str, preg_match('/^\^.*\^$/', $str) ? "\tmatch\n" : "\tdoesn't match\n";
}
</code>```

Output:

```<code>^hello world^   match
my ^hello world^        doesn't match
</code>```

ContentLicense: CC BY-SA 2.5

Body:
im kinda strumped in a situation where i need to match a whole string with a regular expression rather than finding if the pattern exists in the string.

suppose if i have a regular expression

/\\^^\\w+\\$^/

what i want is that the code will run through various strings , compare the strings with the regular expression and perform some task if the strings start and end with a ^.

Examples

^hello world^ is a match

my ^hello world^ should not be a match

the php function preg_match matches both of the results

any clues ???

Body:
Here is a way to do the job:

$strs = array('^hello world^', 'my ^hello world^');
foreach($strs as $str) {
    echo $str, preg_match('/^\^.*\^$/', $str) ? "\tmatch\n" : "\tdoesn't match\n";
}

Output:

^hello world^   match
my ^hello world^        doesn't match


问:
Compress and Minify multiples javascript files into one, with Webpack?
I'm trying to concatenate, minify multiples javascript files into one, with webpack.

So my question can this be done with webpack? and How?

I tried a lot of ways, but couldn't get it to work as what I wanted.

Best I show examples.

3 javascript files.

app.js

```<code>var fnA = function () {
    console.log('fnA')
}
</code>```

global.js

```<code>fnA();
</code>```

main.js

```<code>require('./app.js');
require('./global.js');
</code>```

webpack.config.js

```<code>const path = require('path');
const webpack = require('webpack');

module.exports = {
    entry : [
        './app/main.js'
    ],
    output : {
        path : path.resolve(__dirname, 'dist'),
        filename : 'bundle.js'
    },
    plugins : [
        new webpack.optimize.UglifyJsPlugin(
        {
            minimize: true,
            compress: false,
            mangle: {
                 keep_fnames: true
            },
            bare_returns : true
        }),
    ]
};
</code>```

I'm expecting that global.js is able to call to any function in app.js.
Probably this can be done with grunt, but I thought webpack can do this too.

Worry that I'm heading to a total wrong direction. Google around, but can't seem to find any solution, tried with other plugin suc as chunk, which doesn't helps.

Any advices are welcome.
Thanks in advance.

答:
I put together something simple but you need babel.

https://github.com/vpanjganj/simple-webpack-sample

This is your webpack config:

```<code>var path = require('path');
var webpack = require('webpack');

module.exports = {
    entry: [ "./app/main.js" ],
    output: {
        path: path.join(__dirname, "./dist"),
        filename: "bundle.js"
    },

  module: {
    rules: [
      { test: /\.js$/, use: [ { loader: 'babel-loader' } ], exclude: /node_modules/ }
    ]
  },

  plugins: [
    new webpack.LoaderOptionsPlugin({
      minimize: true,
      debug: false
    }),
    new webpack.LoaderOptionsPlugin({
      minimize: true
    })
  ]
};
</code>```

here your 2 modules:

First module, moduleOne.js:

```<code>export default function sayHello() {
   console.log('hello')
}
</code>```

moduleTwo.js file:

```<code>export default function sayBye() {
   console.log('bye')
}
</code>```

and your main.js file:

```<code>import sayHello from './moduleOne'
import sayBye from './moduleTwo'

const myApp = ()=>{
   sayHello();
   sayBye()
};

myApp();
</code>```

The command to build:

```<code>$ ./node_modules/.bin/webpack  --color --display-error-details --config ./webpack.js"
</code>```

Body:
I'm trying to concatenate, minify multiples javascript files into one, with webpack.

So my question can this be done with webpack? and How?

I tried a lot of ways, but couldn't get it to work as what I wanted.

Best I show examples.

3 javascript files.

app.js

var fnA = function () {
    console.log('fnA')
}

global.js

fnA();

main.js

require('./app.js');
require('./global.js');

webpack.config.js

const path = require('path');
const webpack = require('webpack');

module.exports = {
    entry : [
        './app/main.js'
    ],
    output : {
        path : path.resolve(__dirname, 'dist'),
        filename : 'bundle.js'
    },
    plugins : [
        new webpack.optimize.UglifyJsPlugin(
        {
            minimize: true,
            compress: false,
            mangle: {
                 keep_fnames: true
            },
            bare_returns : true
        }),
    ]
};

I'm expecting that global.js is able to call to any function in app.js.
Probably this can be done with grunt, but I thought webpack can do this too.

Worry that I'm heading to a total wrong direction. Google around, but can't seem to find any solution, tried with other plugin suc as chunk, which doesn't helps.

Any advices are welcome.
Thanks in advance.

Body:
I put together something simple but you need babel.

https://github.com/vpanjganj/simple-webpack-sample

This is your webpack config:

var path = require('path');
var webpack = require('webpack');

module.exports = {
    entry: [ "./app/main.js" ],
    output: {
        path: path.join(__dirname, "./dist"),
        filename: "bundle.js"
    },

  module: {
    rules: [
      { test: /\.js$/, use: [ { loader: 'babel-loader' } ], exclude: /node_modules/ }
    ]
  },

  plugins: [
    new webpack.LoaderOptionsPlugin({
      minimize: true,
      debug: false
    }),
    new webpack.LoaderOptionsPlugin({
      minimize: true
    })
  ]
};

here your 2 modules:

First module, moduleOne.js:

export default function sayHello() {
   console.log('hello')
}

moduleTwo.js file:

export default function sayBye() {
   console.log('bye')
}

and your main.js file:

import sayHello from './moduleOne'
import sayBye from './moduleTwo'

const myApp = ()=>{
   sayHello();
   sayBye()
};

myApp();

The command to build:

$ ./node_modules/.bin/webpack  --color --display-error-details --config ./webpack.js"


问:
Checking username and password in Android using SQLite database
I want to get query from SQLite Database in my APP that consist of name, surname, username and also password.

when I click login button, it made crash. here is my code ##

```<code>public String Login(String Username, String Password) {

    String Q = "SELECT * FROM " + DBHelper.TBLname + " WHERE "
            + DBHelper.ColumnUser + " = " + Username
            + " AND " + DBHelper.ColumnPass + " = " + Password;

    Cursor LoginQuery = MyDB.rawQuery(Q, null);

    if (LoginQuery == null) {
        LoginQuery.close();
        String LoginResult = "Wrong User Name and Password";
        return LoginResult;
    }
        LoginQuery.moveToFirst();
        String LoginResult = LoginQuery.getString(3);
        LoginQuery.close();
    return LoginResult;
}
</code>```

答:
Try this without dbhelper:</p>
```<code>SELECT * FROM YOUR_TABLE WHERE Username=YOUR_USERNAME AND Password=YOUR_PASSWORD
</code>```

Body:
I want to get query from SQLite Database in my APP that consist of name, surname, username and also password.

when I click login button, it made crash. here is my code ##

public String Login(String Username, String Password) {

    String Q = "SELECT * FROM " + DBHelper.TBLname + " WHERE "
            + DBHelper.ColumnUser + " = " + Username
            + " AND " + DBHelper.ColumnPass + " = " + Password;

    Cursor LoginQuery = MyDB.rawQuery(Q, null);

    if (LoginQuery == null) {
        LoginQuery.close();
        String LoginResult = "Wrong User Name and Password";
        return LoginResult;
    }
        LoginQuery.moveToFirst();
        String LoginResult = LoginQuery.getString(3);
        LoginQuery.close();
    return LoginResult;
}

Body:
Try this without dbhelper:

SELECT * FROM YOUR_TABLE WHERE Username=YOUR_USERNAME AND Password=YOUR_PASSWORD

ContentLicense: CC BY-SA 4.0


问:
how to get data of list inside list using thymeleaf ?
i have two entities particiapants and XrayFieldRadiology. they have onetoone relationship. so whenever i select participants the related XrayFieldRadiology is also selected. now i need to show all those database on my table and form.

my html file looks like this.

Xraystatusform.html

```<code>    <div class="box-body" >
                        <span class="successMessage" th:text="${dataSuccess}" style="color: green; align-self:flex-end"></span>
                        <table id="example1" class="table table-bordered table-striped">
                            <thead>
                            <tr>
                                <th>Person Id</th>
                                <th>First Name</th>
                                <th>Last Name</th>
                                <th>Age</th>
                                <th>Sex</th>
                                <th>District</th>
                                <th>VDC/MUNICIPAL</th>
                                <th>Ward No.</th>
                                <th>Xray Status</th>
                                <th>Remarks</th>
                                <th>Actions</th>
                            </tr>
                            </thead>
                            <tbody  th:each="persons : ${part}">
                                <form  method="post" th:action="@{/xraystatus(id=${persons.id})}" enctype="multipart/form-data" id="form1">
                                    <td th:text="${persons.id}" id="xrayid"></td>
                                    <td th:text="${persons.name}"></td>
                                    <td th:text="${persons.lastName}"></td >
                                    <td th:text="${persons.age}"></td>
                                    <td th:text="${persons.sex}"> </td>
                                    <td th:text="${persons.district}"></td>
                                    <td th:text="${persons.district}"></td>
                                    <td th:text="${persons.wardNo}"></td>

                                    <td>
                                        <div class="checkbox"  >
                                            <select name="xraystatus" onchange="yesnoCheck(this);" style="width:61px"  >
                                                <!--<option th:each="xraydata:${xraydata}" th:text="${xraydata.xrayStatus}"></option>-->
                                                <option value="">Select</option>
                                                <option value="1">Yes</option>
                                                <option value="0">No</option>
                                                <option value="2">Possible</option>
                                                <option value="3">Exempted</option>
                                            </select>
                                        </div>
                                    </td>

                                    <td >
                                        <!--<div id="ifYes6" style="display:none; height:30px" >-->
                                            <input type="text" name="remarks"  >
                                        <!--</div>-->
                                    </td>
                                    <td><button type="submit" class="btn btn-success" >Submit</button> </td>
                                </form>

                            </tbody>
                        </table>
                    </div>
</code>```

my controller returns data like this.

data picture

on my input field remarks i need to load data of remarks e.g here blindman. and on xraystatus e.g 0,1(according to database).

my table so far looks like this.

table

so by using thymeleaf how can i access the list inside the list?

答:
If I'm reading your data right, it should be as simple as:</p>

```<code><input type="text" name="remarks" th:value="${persons.xrayFieldRadiology != null ? persons.xrayFieldRadiology.remarks : ''}" />
</code>```

Body:
i have two entities particiapants and XrayFieldRadiology. they have onetoone relationship. so whenever i select participants the related XrayFieldRadiology is also selected. now i need to show all those database on my table and form.

my html file looks like this.

Xraystatusform.html

                                Person Id
                                First Name
                                Last Name
                                Age
                                Sex
                                District
                                VDC/MUNICIPAL
                                Ward No.
                                Xray Status
                                Remarks
                                Actions

                                <form  method="post" th:action="@{/xraystatus(id=${persons.id})}" enctype="multipart/form-data" id="form1">

                                            <select name="xraystatus" onchange="yesnoCheck(this);" style="width:61px"  >

                                                <option value="">Select</option>
                                                <option value="1">Yes</option>
                                                <option value="0">No</option>
                                                <option value="2">Possible</option>
                                                <option value="3">Exempted</option>
                                            </select>

                                            <input type="text" name="remarks"  >

                                    <button type="submit" class="btn btn-success" >Submit</button>
                                </form>

my controller returns data like this.

data picture

on my input field remarks i need to load data of remarks e.g here blindman. and on xraystatus e.g 0,1(according to database).

my table so far looks like this.

table

so by using thymeleaf how can i access the list inside the list?

Body:
If I'm reading your data right, it should be as simple as:

<input type="text" name="remarks" th:value="${persons.xrayFieldRadiology != null ? persons.xrayFieldRadiology.remarks : ''}" />


问:
Find all customers who have an account at all branches located in Brooklyn
I have some tables:

"branch" table(branch_name, branch_city, assets)

"customer" table(customer_name, customer_street, customer_city)

"account" table (account_number, branch_name, balance)

"loan"table (loan_number, branch_name, amount)

"depositor"table (customer_name, account_number)

"borrower" table (customer_name, loan_number)

Now I want to find all customers who have an account at all branches located in Brooklyn. Here is my SQL for this problem. BUT I want to know how to use TABLE JOIN, and WITHOUT USING EXCEPT to solve this problem. CAN SOMEONE HELP ME ?????THANKS.

```<code>SELECT distinct S.customer_name FROM depositor as S
WHERE not exists (
     (SELECT branch_name
      FROM branch
      WHERE branch_city = 'Brooklyn')
      EXCEPT
      (SELECT R.branch_name
       FROM depositor as T, account as R
       WHERE T.account_number = R.account_number and
             S.customer_name = T.customer_name ))
</code>```

答:
Assuming you want an answer to: "find all customers who have an account at any branch located in Brooklyn"

```<code>select c.*
from customer c
inner join depositor d
   on c.customer_name = d.customer_name
inner join account a
   on d.account_numver = a.account_number
inner join branch b
   on a.branch_name = b.branch_name
where b.branch_city = 'Brooklyn'
</code>```

If a customer can have more than one account or an account can have more than one branch, you will need to adjust the joins.

Body:
I have some tables:

"branch" table(branch_name, branch_city, assets)

"customer" table(customer_name, customer_street, customer_city)

"account" table (account_number, branch_name, balance)

"loan"table (loan_number, branch_name, amount)

"depositor"table (customer_name, account_number)

"borrower" table (customer_name, loan_number)

Now I want to find all customers who have an account at all branches located in Brooklyn. Here is my SQL for this problem. BUT I want to know how to use TABLE JOIN, and WITHOUT USING EXCEPT to solve this problem. CAN SOMEONE HELP ME ?????THANKS.

SELECT distinct S.customer_name FROM depositor as S
WHERE not exists (
     (SELECT branch_name
      FROM branch
      WHERE branch_city = 'Brooklyn')
      EXCEPT
      (SELECT R.branch_name
       FROM depositor as T, account as R
       WHERE T.account_number = R.account_number and
             S.customer_name = T.customer_name ))

Body:
Assuming you want an answer to: "find all customers who have an account at any branch located in Brooklyn"

select c.*
from customer c
inner join depositor d
   on c.customer_name = d.customer_name
inner join account a
   on d.account_numver = a.account_number
inner join branch b
   on a.branch_name = b.branch_name
where b.branch_city = 'Brooklyn'

If a customer can have more than one account or an account can have more than one branch, you will need to adjust the joins.


问:
How to replace an entire Pandas DataFrame row if all values equal np.NaN
Example Code & Output:

```<code>data_country1 = {'Country': [np.NaN, 'India', 'Brazil'],
                 'Capital': [np.NaN, 'New Delhi', 'Brasília'],
                 'Population': [np.NaN, 1303171035, 207847528]}

df_country1 = pd.DataFrame(data_country1, columns=['Country', 'Capital', 'Population'])

data_country2= {'Country': ['Belgium', 'India', 'Brazil'],
                'Capital': ['Brussels', 'New Delhi', 'Brasília'],
                'Population': [102283932, 1303171035, 207847528]}

df_country2 = pd.DataFrame(data_country2, columns=['Country', 'Capital', 'Population'])

print(df_country1)
print(df_country2)

  Country    Capital    Population
0     NaN        NaN           NaN
1   India  New Delhi  1.303171e+09
2  Brazil   Brasília  2.078475e+08

   Country    Capital  Population
0  Belgium   Brussels   102283932
1    India  New Delhi  1303171035
2   Brazil   Brasília   207847528
</code>```

In the first DataFrame, for every row that is comprised of ALL NaN, I want to replace the entire row with a row from another dataframe.  In this example, row 0 from the second dataframe, so that the first df ends up with the same information as the second dataframe.

答:
You can combine them using append, drop any duplicates (rows that were in both data frames), and then remove all the indices where the values are NaN:

```<code>#combine into one data frame with unique values
df_country = df_country1.append(df_country2,ignore_index=True).drop_duplicates()

#filter out NaN rows
df_country = df_country.drop(df_country.index[df_country.isnull().all(axis=1)])
</code>```

The ignore_index flag in append gives each line unique indexes so that when you search for the indexes with NaN rows and it returns 0 you don't end up deleting the 0 index row from df_country2.

Body:
Example Code & Output:

data_country1 = {'Country': [np.NaN, 'India', 'Brazil'],
                 'Capital': [np.NaN, 'New Delhi', 'Brasília'],
                 'Population': [np.NaN, 1303171035, 207847528]}

df_country1 = pd.DataFrame(data_country1, columns=['Country', 'Capital', 'Population'])

data_country2= {'Country': ['Belgium', 'India', 'Brazil'],
                'Capital': ['Brussels', 'New Delhi', 'Brasília'],
                'Population': [102283932, 1303171035, 207847528]}

df_country2 = pd.DataFrame(data_country2, columns=['Country', 'Capital', 'Population'])

print(df_country1)
print(df_country2)

  Country    Capital    Population
0     NaN        NaN           NaN
1   India  New Delhi  1.303171e+09
2  Brazil   Brasília  2.078475e+08

   Country    Capital  Population
0  Belgium   Brussels   102283932
1    India  New Delhi  1303171035
2   Brazil   Brasília   207847528

In the first DataFrame, for every row that is comprised of ALL NaN, I want to replace the entire row with a row from another dataframe.  In this example, row 0 from the second dataframe, so that the first df ends up with the same information as the second dataframe.

Body:
You can combine them using append, drop any duplicates (rows that were in both data frames), and then remove all the indices where the values are NaN:

#combine into one data frame with unique values
df_country = df_country1.append(df_country2,ignore_index=True).drop_duplicates()

#filter out NaN rows
df_country = df_country.drop(df_country.index[df_country.isnull().all(axis=1)])

The ignore_index flag in append gives each line unique indexes so that when you search for the indexes with NaN rows and it returns 0 you don't end up deleting the 0 index row from df_country2.


问:
Angular 2 polyfills initializing takes too long
I am pretty new to Front-end development and having some issue with angular2 app.

As you can see the timeline capture below, polyfills taks too long time ( almost 6 seconds ! )

It seems not a normal. but,, I have no idea what can I do to decrease this polyfills time.

Some lines of the conf.

```<code>  // Add build specific plugins
  if (ENV === 'build') {
    config.plugins.push(
      // Reference: http://webpack.github.io/docs/list-of-plugins.html#noerrorsplugin
      // Only emit files when there are no errors
      new webpack.NoErrorsPlugin(),

      // Reference: http://webpack.github.io/docs/list-of-plugins.html#dedupeplugin
      // Dedupe modules in the output
      new webpack.optimize.DedupePlugin(),

      // Reference: http://webpack.github.io/docs/list-of-plugins.html#uglifyjsplugin
      // Minify all javascript, switch loaders to minimizing mode
      new webpack.optimize.UglifyJsPlugin({
          compress: { warnings: false }
      })
    );
  }
</code>```

Whole webpack.config.js I use in my app.
https://gist.github.com/jeesim2/484186d630fedc9f42e264ca905ad123

My angular version

```<code>"@angular/common": "^2.0.1",
"@angular/compiler": "^2.0.1",
"@angular/core": "^2.0.1",
"@angular/forms": "^2.0.1",
"@angular/http": "^2.0.1",
"@angular/platform-browser": "^2.0.1",
"@angular/platform-browser-dynamic": "^2.0.1",
"@angular/router": "^3.0.1",
</code>```

webpack.optimize.UglifyJsPlugin decreased package size to 70% but Page loading speed wasn't get faster.

What cause this long page loading?

答:
Welcome to angular2 single page app :). A2 is still IMHO in development state. This behaviour is normal, depends of OS/browser/components number rendering is taking some seconds. Since bundled file with A2/vendors/polyfills is about 800kb+ (minimalized) it take some time to read all to browser memory.

You can check that rendering is done quite fast but scripts can be runned in background for few more seconds after initialized. Even on fast PC it takes some time.

It is done by https://github.com/angular/zone.js/

Body:
I am pretty new to Front-end development and having some issue with angular2 app.

As you can see the timeline capture below, polyfills taks too long time ( almost 6 seconds ! )

It seems not a normal. but,, I have no idea what can I do to decrease this polyfills time.

Some lines of the conf.

  // Add build specific plugins
  if (ENV === 'build') {
    config.plugins.push(
      // Reference: http://webpack.github.io/docs/list-of-plugins.html#noerrorsplugin
      // Only emit files when there are no errors
      new webpack.NoErrorsPlugin(),

      // Reference: http://webpack.github.io/docs/list-of-plugins.html#dedupeplugin
      // Dedupe modules in the output
      new webpack.optimize.DedupePlugin(),

      // Reference: http://webpack.github.io/docs/list-of-plugins.html#uglifyjsplugin
      // Minify all javascript, switch loaders to minimizing mode
      new webpack.optimize.UglifyJsPlugin({
          compress: { warnings: false }
      })
    );
  }

Whole webpack.config.js I use in my app.
https://gist.github.com/jeesim2/484186d630fedc9f42e264ca905ad123

My angular version

"@angular/common": "^2.0.1",
"@angular/compiler": "^2.0.1",
"@angular/core": "^2.0.1",
"@angular/forms": "^2.0.1",
"@angular/http": "^2.0.1",
"@angular/platform-browser": "^2.0.1",
"@angular/platform-browser-dynamic": "^2.0.1",
"@angular/router": "^3.0.1",

webpack.optimize.UglifyJsPlugin decreased package size to 70% but Page loading speed wasn't get faster.

What cause this long page loading?


问:
including external script doen't work in web.py (html template)
I include script in html (web template), it doen't work when I visited it by http://127.0.0.1:8080/main, but in local when I double click the html file, the script can work.

I find one question here, but the answer doen't work either:
including script doesn't work in web.py

```<code># web.py
import web

urls = ('/main', 'main')
render = web.template.render('templates/')

class main:
    def GET(self):
        return render.main()

app = web.application(urls, globals())

if __name__ == "__main__":
    app.run()
</code>```

Below is the HTML

```<code><!DOCTYPE html>

<html>
  <head>
    <title>title</title>
    <script src="echarts.min.js"></script>
  </head>
  <body>
    <p>Hello world!+++</p>
</code>```

答:
How is your directory structure defined? Do you have js files in static folder ?

For any static scripts such as css and js to work, web.py expects them in a static folder under main app folder.
Here is general structure I normally go with.

```<code>/app.py           #main app

/static           #static data
       /css       #css
       /js        #javascript
       /images    #images

/templates        #html templates
</code>```

These folders can be accessed using relative path in html file.

For e.g. Once you have defined above directory structure, in your html file simply put in,

```<code><script src="static/js/yourJavaScript.js" ></script>
</code>```

When you launch app.py, the app then would look into static/js folder for your javascript and it should work.

I've my setup working as above.

Body:
I include script in html (web template), it doen't work when I visited it by http://127.0.0.1:8080/main, but in local when I double click the html file, the script can work.

I find one question here, but the answer doen't work either:
including script doesn't work in web.py

# web.py
import web

urls = ('/main', 'main')
render = web.template.render('templates/')

class main:
    def GET(self):
        return render.main()

app = web.application(urls, globals())

if __name__ == "__main__":
    app.run()

Below is the HTML

<!DOCTYPE html>

    <title>title</title>

Hello world!+++

Body:
How is your directory structure defined? Do you have js files in static folder ?

For any static scripts such as css and js to work, web.py expects them in a static folder under main app folder.
Here is general structure I normally go with.

/app.py           #main app

/static           #static data
       /css       #css
       /js        #javascript
       /images    #images

/templates        #html templates

These folders can be accessed using relative path in html file.

For e.g. Once you have defined above directory structure, in your html file simply put in,

<script src="static/js/yourJavaScript.js" ></script>

When you launch app.py, the app then would look into static/js folder for your javascript and it should work.

I've my setup working as above.


问:
CSS Animation and Columns in Google Chrome
I've encountered some trouble with animating icons in Google Chrome. I tested this in Safari and Firefox, and my code works there, so I'm not sure if this is an error on my part or an issue with the browser. I'm coding icons in columns so that they stack evenly in a responsive layout, but when I put them in columns, all icons except the first one move down the page.

Any help either identifying what I'm doing wrong or helping to find a workaround would be appreciated. I cut out the media queries in my code for the sake of simplicity posting it here.

#pptoc {
  background-color: #3f72a5;
  text-align: center;
  color: #a1c0d0;
  margin: 0;
  width: 100%;
  padding: 35px 0px;
  -webkit-columns: 6;
  -moz-columns: 6;
  columns: 6;
}

#pptoc img {}

#pptoc a {
  text-decoration: none;
  color: #a1c0d0;
}

@-webkit-keyframes wiggle {
  0% {
    -webkit-transform: rotate(4deg);
  }
  50% {
    -webkit-transform: rotate(-4deg);
  }
  100% {
    -webkit-transform: rotate(4deg);
  }
}

.pptocitem:hover {
  -webkit-animation: wiggle 0.2s 1;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="pptoc">
  <div class="pptocsect"><img src="http://placehold.it/100x100?text=im1" class="pptocitem"><br>part 1</a>
  </div>
  <div class="pptocsect"><img src="http://placehold.it/100x100?text=im2" class="pptocitem"><span class="test1"><br>part 2</a></div>
<div class="pptocsect"><img src="http://placehold.it/100x100?text=im3" class="pptocitem"><br>part 3</a></div>
<div class="pptocsect"><img src="http://placehold.it/100x100?text=im4" class="pptocitem"><br>part 4</a></div>
<div class="pptocsect"><img src="http://placehold.it/100x100?text=im5" class="pptocitem"><br>part 5</a></div>
<div class="part 6"><img src="http://placehold.it/100x100?text=im6" class="pptocitem"><br>part 6</a></div></code>```

答:
You can use flex instead of CSS columns and those elements will stay put. Flexbox also gives you more positioning options.

BTW, you have a bunch of unclosed a tags and an unclosed span

#pptoc {
  background-color: #3f72a5;
  text-align: center;
  color: #a1c0d0;
  margin: 0;
  padding: 35px 0px;
  display: flex;
  justify-content: space-around;
}

#pptoc a {
  text-decoration: none;
  color: #a1c0d0;
}

@-webkit-keyframes wiggle {
  0% {
    -webkit-transform: rotate(4deg);
  }
  50% {
    -webkit-transform: rotate(-4deg);
  }
  100% {
    -webkit-transform: rotate(4deg);
  }
}

.pptocitem:hover {
  -webkit-animation: wiggle 0.2s 1;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="pptoc">
  <div class="pptocsect"><img src="http://placehold.it/100x100?text=im1" class="pptocitem"><br>part 1
  </div>
  <div class="pptocsect"><img src="http://placehold.it/100x100?text=im2" class="pptocitem"><span class="test1"><br>part 2</span></div>
<div class="pptocsect"><img src="http://placehold.it/100x100?text=im3" class="pptocitem"><br>part 3</div>
<div class="pptocsect"><img src="http://placehold.it/100x100?text=im4" class="pptocitem"><br>part 4</div>
<div class="pptocsect"><img src="http://placehold.it/100x100?text=im5" class="pptocitem"><br>part 5</div>
<div class="part 6"><img src="http://placehold.it/100x100?text=im6" class="pptocitem"><br>part 6</div></code>```

Body:
I've encountered some trouble with animating icons in Google Chrome. I tested this in Safari and Firefox, and my code works there, so I'm not sure if this is an error on my part or an issue with the browser. I'm coding icons in columns so that they stack evenly in a responsive layout, but when I put them in columns, all icons except the first one move down the page.

Any help either identifying what I'm doing wrong or helping to find a workaround would be appreciated. I cut out the media queries in my code for the sake of simplicity posting it here.

#pptoc {
  background-color: #3f72a5;
  text-align: center;
  color: #a1c0d0;
  margin: 0;
  width: 100%;
  padding: 35px 0px;
  -webkit-columns: 6;
  -moz-columns: 6;
  columns: 6;
}

#pptoc img {}

#pptoc a {
  text-decoration: none;
  color: #a1c0d0;
}

@-webkit-keyframes wiggle {
  0% {
    -webkit-transform: rotate(4deg);
  }
  50% {
    -webkit-transform: rotate(-4deg);
  }
  100% {
    -webkit-transform: rotate(4deg);
  }
}

.pptocitem:hover {
  -webkit-animation: wiggle 0.2s 1;
}

part 1

part 2

part 3

part 4

part 5

part 6

Body:
You can use flex instead of CSS columns and those elements will stay put. Flexbox also gives you more positioning options.

BTW, you have a bunch of unclosed a tags and an unclosed span

#pptoc {
  background-color: #3f72a5;
  text-align: center;
  color: #a1c0d0;
  margin: 0;
  padding: 35px 0px;
  display: flex;
  justify-content: space-around;
}

#pptoc a {
  text-decoration: none;
  color: #a1c0d0;
}

@-webkit-keyframes wiggle {
  0% {
    -webkit-transform: rotate(4deg);
  }
  50% {
    -webkit-transform: rotate(-4deg);
  }
  100% {
    -webkit-transform: rotate(4deg);
  }
}

.pptocitem:hover {
  -webkit-animation: wiggle 0.2s 1;
}

<div id="pptoc">
  <div class="pptocsect"><img src="http://placehold.it/100x100?text=im1" class="pptocitem"><br>part 1
  </div>
  <div class="pptocsect"><img src="http://placehold.it/100x100?text=im2" class="pptocitem"><span class="test1"><br>part 2</span></div>
<div class="pptocsect"><img src="http://placehold.it/100x100?text=im3" class="pptocitem"><br>part 3</div>
<div class="pptocsect"><img src="http://placehold.it/100x100?text=im4" class="pptocitem"><br>part 4</div>
<div class="pptocsect"><img src="http://placehold.it/100x100?text=im5" class="pptocitem"><br>part 5</div>
<div class="part 6"><img src="http://placehold.it/100x100?text=im6" class="pptocitem"><br>part 6</div>