问:
Reorder array of objects that contain parent/child relationships with lodash or vanilla js
I have an array of objects like:

```<code>[
    {
        id: 8,
        name: 'Shirts',
        slug: 'shirts',
        parent_id: null
    },
    {
        id: 9,
        name: 'Pants',
        slug: 'pants',
        parent_id: null
    },
    {
        id: 10,
        name: 'Vintage Prints',
        slug: 'vintage-prints',
        parent_id: 8
    },
    {
        id: 11,
        name: 'Cotton Tee',
        slug: 'cotton-tee',
        parent_id: 8
    },
    {
        id: 12,
        name: 'Business Khakis',
        slug: 'business-khakis',
        parent_id: 9
    }
]
</code>```

What I need is:

```<code>[
    {
        id: 9,
        name: 'Pants',
        slug: 'pants',
        parent_id: null
    },
    {
        id: 12,
        name: 'Business Khakis',
        slug: 'business-khakis',
        parent_id: 9
    },
    {
        id: 8,
        name: 'Shirts',
        slug: 'shirts',
        parent_id: null
    },
    {
        id: 11,
        name: 'Cotton Tee',
        slug: 'cotton-tee',
        parent_id: 8
    },
    {
        id: 10,
        name: 'Vintage Prints',
        slug: 'vintage-prints',
        parent_id: 8
    }
]
</code>```

WHAT I'VE TRIED:
This looks like it should work:

```<code>_.orderBy(categories, ['parent_id', 'name'], ['asc', 'asc']);
</code>```

But I wonder if the nulls in parent_id are messing with it.

EDIT:
Inner and outer results should also be sorted alphabetically. So Pants before shirts in the outer level and Cotton Tee before Vintage Prints in the child tier. Keep in mind that this can be infinite layers deep where Cotton Tee could be the parent and so on.

It would also be great if each sorted object could receive an index or level so that you knew how many levels it was nested.

答:
A single sort does not work, because of the parent children relation, which is not considered while sorting the data.

This solution works in three parts:

Sorts data by alphabet, because the following tree is build in insertion order.

Builds a tree with the given relationship.

Traverses the tree and gets the sorted flat data back.

var data = [{ id: 8, name: 'Shirts', slug: 'shirts', parent_id: null }, { id: 9, name: 'Pants', slug: 'pants', parent_id: null }, { id: 10, name: 'Vintage Prints', slug: 'vintage-prints', parent_id: 8 }, { id: 11, name: 'Cotton Tee', slug: 'cotton-tee', parent_id: 8 }, { id: 12, name: 'Business Khakis', slug: 'business-khakis', parent_id: 9 }]
    .sort(function (a, b) {
        return a.name.localeCompare(b.name);
    }),
    tree = function (data, root) {
        var r = [], o = {};
        data.forEach(function (a) {
            o[a.id] = { data: a, children: o[a.id] && o[a.id].children };
            if (a.parent_id === root) {
                r.push(o[a.id]);
            } else {
                o[a.parent_id] = o[a.parent_id] || {};
                o[a.parent_id].children = o[a.parent_id].children || [];
                o[a.parent_id].children.push(o[a.id]);
            }
        });
        return r;
    }(data, null),
    sorted = tree.reduce(function traverse(r, a) {
        return r.concat(a.data, (a.children || []).reduce(traverse, []));
    }, [])

console.log(sorted);
console.log(tree);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Extended version with level:

var data = [{ id: 8, name: 'Shirts', slug: 'shirts', parent_id: null }, { id: 9, name: 'Pants', slug: 'pants', parent_id: null }, { id: 10, name: 'Vintage Prints', slug: 'vintage-prints', parent_id: 8 }, { id: 11, name: 'Cotton Tee', slug: 'cotton-tee', parent_id: 8 }, { id: 12, name: 'Business Khakis', slug: 'business-khakis', parent_id: 9 }]
    .sort(function (a, b) {
        return a.name.localeCompare(b.name);
    }),
    tree = function (data, root) {
        var r = [], o = {};
        data.forEach(function (a) {
            o[a.id] = { data: a, children: o[a.id] && o[a.id].children };
            if (a.parent_id === root) {
                r.push(o[a.id]);
            } else {
                o[a.parent_id] = o[a.parent_id] || {};
                o[a.parent_id].children = o[a.parent_id].children || [];
                o[a.parent_id].children.push(o[a.id]);
            }
        });
        return r;
    }(data, null),
    sorted = tree.reduce(function traverse(level) {
        return function (r, a) {
            a.data.level = level
            return r.concat(a.data, (a.children || []).reduce(traverse(level + 1), []));
        };
    }(0), []);

console.log(sorted);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Body:
I have an array of objects like:

[
    {
        id: 8,
        name: 'Shirts',
        slug: 'shirts',
        parent_id: null
    },
    {
        id: 9,
        name: 'Pants',
        slug: 'pants',
        parent_id: null
    },
    {
        id: 10,
        name: 'Vintage Prints',
        slug: 'vintage-prints',
        parent_id: 8
    },
    {
        id: 11,
        name: 'Cotton Tee',
        slug: 'cotton-tee',
        parent_id: 8
    },
    {
        id: 12,
        name: 'Business Khakis',
        slug: 'business-khakis',
        parent_id: 9
    }
]

What I need is:

[
    {
        id: 9,
        name: 'Pants',
        slug: 'pants',
        parent_id: null
    },
    {
        id: 12,
        name: 'Business Khakis',
        slug: 'business-khakis',
        parent_id: 9
    },
    {
        id: 8,
        name: 'Shirts',
        slug: 'shirts',
        parent_id: null
    },
    {
        id: 11,
        name: 'Cotton Tee',
        slug: 'cotton-tee',
        parent_id: 8
    },
    {
        id: 10,
        name: 'Vintage Prints',
        slug: 'vintage-prints',
        parent_id: 8
    }
]

WHAT I'VE TRIED:
This looks like it should work:

_.orderBy(categories, ['parent_id', 'name'], ['asc', 'asc']);

But I wonder if the nulls in parent_id are messing with it.

EDIT:
Inner and outer results should also be sorted alphabetically. So Pants before shirts in the outer level and Cotton Tee before Vintage Prints in the child tier. Keep in mind that this can be infinite layers deep where Cotton Tee could be the parent and so on.

It would also be great if each sorted object could receive an index or level so that you knew how many levels it was nested.

Body:
A single sort does not work, because of the parent children relation, which is not considered while sorting the data.

This solution works in three parts:

Sorts data by alphabet, because the following tree is build in insertion order.

Builds a tree with the given relationship.

Traverses the tree and gets the sorted flat data back.

var data = [{ id: 8, name: 'Shirts', slug: 'shirts', parent_id: null }, { id: 9, name: 'Pants', slug: 'pants', parent_id: null }, { id: 10, name: 'Vintage Prints', slug: 'vintage-prints', parent_id: 8 }, { id: 11, name: 'Cotton Tee', slug: 'cotton-tee', parent_id: 8 }, { id: 12, name: 'Business Khakis', slug: 'business-khakis', parent_id: 9 }]
    .sort(function (a, b) {
        return a.name.localeCompare(b.name);
    }),
    tree = function (data, root) {
        var r = [], o = {};
        data.forEach(function (a) {
            o[a.id] = { data: a, children: o[a.id] && o[a.id].children };
            if (a.parent_id === root) {
                r.push(o[a.id]);
            } else {
                o[a.parent_id] = o[a.parent_id] || {};
                o[a.parent_id].children = o[a.parent_id].children || [];
                o[a.parent_id].children.push(o[a.id]);
            }
        });
        return r;
    }(data, null),
    sorted = tree.reduce(function traverse(r, a) {
        return r.concat(a.data, (a.children || []).reduce(traverse, []));
    }, [])

console.log(sorted);
console.log(tree);

.as-console-wrapper { max-height: 100% !important; top: 0; }

Extended version with level:

var data = [{ id: 8, name: 'Shirts', slug: 'shirts', parent_id: null }, { id: 9, name: 'Pants', slug: 'pants', parent_id: null }, { id: 10, name: 'Vintage Prints', slug: 'vintage-prints', parent_id: 8 }, { id: 11, name: 'Cotton Tee', slug: 'cotton-tee', parent_id: 8 }, { id: 12, name: 'Business Khakis', slug: 'business-khakis', parent_id: 9 }]
    .sort(function (a, b) {
        return a.name.localeCompare(b.name);
    }),
    tree = function (data, root) {
        var r = [], o = {};
        data.forEach(function (a) {
            o[a.id] = { data: a, children: o[a.id] && o[a.id].children };
            if (a.parent_id === root) {
                r.push(o[a.id]);
            } else {
                o[a.parent_id] = o[a.parent_id] || {};
                o[a.parent_id].children = o[a.parent_id].children || [];
                o[a.parent_id].children.push(o[a.id]);
            }
        });
        return r;
    }(data, null),
    sorted = tree.reduce(function traverse(level) {
        return function (r, a) {
            a.data.level = level
            return r.concat(a.data, (a.children || []).reduce(traverse(level + 1), []));
        };
    }(0), []);

console.log(sorted);

.as-console-wrapper { max-height: 100% !important; top: 0; }


来源: stackexchange

问:
Why doesn't the background colour of my Storyboard in Xcode change? It's always the same grey color?
So i've changed the background property of my default view in my storyboard file to as many as the colours in the rainbow. The colour shows up along with my buttons nicely in Xcode, but when I actually RUN the app, the background is always the same, ugly, default grey colour that you start with a new Xcode project ("Hello World!").

I've searched up for the answer all over Google and to no avail. Am I doing something wrong or is it just a glitch? It might be also important to mention than i'm using Spritekit, and that this "view" is the only view in my Storyboard file, the default one. Should I change self.view to skView? Would that work?

Oh and also, when I manually try to change the background colour under viewDidLoad in my .m class by doing:

```<code>self.view.backgroundColor = [UIColor backgroundColor];
</code>```

the background STILL doesn't change and is always the same default colour. Please help me... i'm desperate right now... there's no answers anywhere to be found. Thanks.

答:
If you have the same problem as me! That you see the ugly gray background right after the SplashScreen, I have found a solution! Just after creating the skView, create an empty scene with a white background and present it directly!</p>

```<code>let backgroundColoredScene = SKScene()
backgroundColoredScene.backgroundColor = SKColor.white()
skView.presentScene(backgroundColoredScene)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
So i've changed the background property of my default view in my storyboard file to as many as the colours in the rainbow. The colour shows up along with my buttons nicely in Xcode, but when I actually RUN the app, the background is always the same, ugly, default grey colour that you start with a new Xcode project ("Hello World!").

I've searched up for the answer all over Google and to no avail. Am I doing something wrong or is it just a glitch? It might be also important to mention than i'm using Spritekit, and that this "view" is the only view in my Storyboard file, the default one. Should I change self.view to skView? Would that work?

Oh and also, when I manually try to change the background colour under viewDidLoad in my .m class by doing:

self.view.backgroundColor = [UIColor backgroundColor];

the background STILL doesn't change and is always the same default colour. Please help me... i'm desperate right now... there's no answers anywhere to be found. Thanks.

Body:
If you have the same problem as me! That you see the ugly gray background right after the SplashScreen, I have found a solution! Just after creating the skView, create an empty scene with a white background and present it directly!

let backgroundColoredScene = SKScene()
backgroundColoredScene.backgroundColor = SKColor.white()
skView.presentScene(backgroundColoredScene)


问:
Help with (somewhat simple) MySQL JOIN
Consider I have three tables:

Movies (movie 1, movie 2, etc)

Categories (action, suspense, etc)

Movies_Categories (movie 1 -> action, movie 1 -> suspense, movie 2 -> suspense, etc)

How could I select only the movies that belong or don't belong to a specific category using only 1 query?

Thanks!

答:
Belongs:

```<code>    SELECT m.*
      FROM movies m
INNER JOIN movies_categories mc
        ON m.id = mc.movie_id
INNER JOIN categories c
        ON c.id = mc.category_id
       AND c.name = 'action';
</code>```

Doesn't belong:

```<code>         SELECT m.*
           FROM movies m
LEFT OUTER JOIN (SELECT mc.movie_id
                   FROM movies_categories mc
             INNER JOIN categories c
                     ON c.id = mc.category_id
                    AND c.name = 'action') mcx
             ON m.id = mcx.movie_id
          WHERE mcx.movie_id IS NULL
</code>```

ContentLicense: CC BY-SA 2.5

Title: Help with (somewhat simple) MySQL JOIN

Body:
Belongs:

    SELECT m.*
      FROM movies m
INNER JOIN movies_categories mc
        ON m.id = mc.movie_id
INNER JOIN categories c
        ON c.id = mc.category_id
       AND c.name = 'action';

Doesn't belong:

         SELECT m.*
           FROM movies m
LEFT OUTER JOIN (SELECT mc.movie_id
                   FROM movies_categories mc
             INNER JOIN categories c
                     ON c.id = mc.category_id
                    AND c.name = 'action') mcx
             ON m.id = mcx.movie_id
          WHERE mcx.movie_id IS NULL


问:
Cannot GET /products/5a22c1bdc2f7e634fc7c7c97
Please I created a nodejs app used mlab for my db and postman as my means of posting apis but now if i want to view my products i get this error:

Cannot GET /products/5a22c1bdc2f7e634fc7c7c97
  below are my codes.

Server.js File:

```<code>const express = require('express');
const morgan = require('morgan');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const ejs = require('ejs');
const ejsmate = require('ejs-mate');
const session = require('express-session');
const cookieParser = require('cookie-parser');
const flash = require('express-flash');
const LocalStrategy = require('passport-local').Strategy;
const MongoStore = require('connect-mongo')(session);
const passport = require('passport');
var secret = require('./config/secret');
var User = require('./models/user');
var Category = require('./models/category');
var Universities = require('./models/universities');

var app = express();

mongoose.Promise = global.Promise;
var promise = mongoose.connect(secret.database,{useMongoClient: true}, (err) =>{
 if(err){
console.log(err)
}else{
console.log('connected to new database');
}
})

// MiddleWare

app.use(bodyParser.urlencoded({extended:true}));
app.use(cookieParser());
app.use(session({
resave: true,
saveUninitialized: true,
secret: secret.secretKey,
store: new MongoStore({url: secret.database, autoReconnect: true})
}));
app.use(flash());
app.use(passport.initialize());
app.use(passport.session());
app.use((req, res, next)=>{
 res.locals.user = req.user;
next();
})

app.use((req, res, next)=>{
Category.find({}, (err, categories)=>{
 if(err) return next(err)
 res.locals.categories = categories;
next();
})
})

app.set("view engine", "ejs");

app.engine('ejs', ejsmate);
app.use(express.static(__dirname + "/views"));
app.use(express.static(__dirname + "/public"));

var mainRoutes = require('./routes/main');
var userRoutes = require('./routes/user');
var adminRoutes = require('./routes/admin');
var apiRoutes = require('./api/api');

app.use(mainRoutes, function(req, res, next){
next();
})
app.use(userRoutes, function(req, res, next){
next();
})
app.use(adminRoutes, function(req, res, next){
next();

});
app.use('/api', apiRoutes, function(req, res, next){
next();

});

app.listen(secret.port, function(){
console.log(`app is runing on port. ${secret.port}`);
})

Main.js file
const express = require('express');
const router = express.Router();
var Product = require("../models/product");

router.get('/', function(req, res){
 res.render("main/home");
})

router.get('/about', function(req, res){
 res.render("main/about");
})

router.get('products/:id', function(req, res, next){
 Product
.find({ category: req.params.id })
.populate('category')
.exec(function(err, products){
 if(err) return next(err)
 res.render("main/category", {products: products})
})
});

router.get("/product/:id", (req, res, next)=>{
Product.findById({_id: req.params.id}, (err, product)=>{
 if(err) return next(err);
 res.render("main/product", {
product: product
})
})
})

module.exports = router;
category.ejs

<% layout('layout') -%>

<div class = "container">
<div class ="row">
<% for (var i = 0; i < products.length; i ++){%>
<div class="col-md-4">
<a href="/product/<%=products[i]._id %>">
<div class="thumbnail">
<img src="<%=products[i].image %>">
<h3><%= products[i].name%></h3>
<p><%=products[i].category.name%></p>
<p><%=products[i].intro%></p>
<p><%=products[i].website%></p>
</div>
</a>
</div>
<%}%>
</div>
</div>
</code>```

So please how do i view the products of a category though for now  have only populated one product(universities) of  the category

答:
ok I have been able to fix it forgot to add "/" before products in the router.get products url.

thank you.

Body:
Please I created a nodejs app used mlab for my db and postman as my means of posting apis but now if i want to view my products i get this error:

Cannot GET /products/5a22c1bdc2f7e634fc7c7c97
  below are my codes.

Server.js File:

const express = require('express');
const morgan = require('morgan');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const ejs = require('ejs');
const ejsmate = require('ejs-mate');
const session = require('express-session');
const cookieParser = require('cookie-parser');
const flash = require('express-flash');
const LocalStrategy = require('passport-local').Strategy;
const MongoStore = require('connect-mongo')(session);
const passport = require('passport');
var secret = require('./config/secret');
var User = require('./models/user');
var Category = require('./models/category');
var Universities = require('./models/universities');

var app = express();

mongoose.Promise = global.Promise;
var promise = mongoose.connect(secret.database,{useMongoClient: true}, (err) =>{
 if(err){
console.log(err)
}else{
console.log('connected to new database');
}
})

// MiddleWare

app.use(bodyParser.urlencoded({extended:true}));
app.use(cookieParser());
app.use(session({
resave: true,
saveUninitialized: true,
secret: secret.secretKey,
store: new MongoStore({url: secret.database, autoReconnect: true})
}));
app.use(flash());
app.use(passport.initialize());
app.use(passport.session());
app.use((req, res, next)=>{
 res.locals.user = req.user;
next();
})

app.use((req, res, next)=>{
Category.find({}, (err, categories)=>{
 if(err) return next(err)
 res.locals.categories = categories;
next();
})
})

app.set("view engine", "ejs");

app.engine('ejs', ejsmate);
app.use(express.static(__dirname + "/views"));
app.use(express.static(__dirname + "/public"));

var mainRoutes = require('./routes/main');
var userRoutes = require('./routes/user');
var adminRoutes = require('./routes/admin');
var apiRoutes = require('./api/api');

app.use(mainRoutes, function(req, res, next){
next();
})
app.use(userRoutes, function(req, res, next){
next();
})
app.use(adminRoutes, function(req, res, next){
next();

});
app.use('/api', apiRoutes, function(req, res, next){
next();

});

app.listen(secret.port, function(){
console.log(`app is runing on port. ${secret.port}`);
})

Main.js file
const express = require('express');
const router = express.Router();
var Product = require("../models/product");

router.get('/', function(req, res){
 res.render("main/home");
})

router.get('/about', function(req, res){
 res.render("main/about");
})

router.get('products/:id', function(req, res, next){
 Product
.find({ category: req.params.id })
.populate('category')
.exec(function(err, products){
 if(err) return next(err)
 res.render("main/category", {products: products})
})
});

router.get("/product/:id", (req, res, next)=>{
Product.findById({_id: req.params.id}, (err, product)=>{
 if(err) return next(err);
 res.render("main/product", {
product: product
})
})
})

module.exports = router;
category.ejs

<% layout('layout') -%>

<% for (var i = 0; i < products.length; i ++){%>

<a href="/product/<%=products[i]._id %>">

<img src="<%=products[i].image %>">

<%= products[i].name%>

<%=products[i].category.name%>

<%=products[i].intro%>

<%=products[i].website%>

<%}%>

So please how do i view the products of a category though for now  have only populated one product(universities) of  the category


问:
Which is a better practice - global import or local import
I am developing an app in django and I had a doubt if importing a library at the global level has any impact over the memory or performance than importing at the local ( per-function) level. If it is imported per function or view, the modules that are needed alone are imported saving space right? Or are there any negatives in doing so?</p>

答:
Import Statement Overhead

From Python Performance Tips:

It's often useful to place them inside functions to restrict their visibility and/or reduce initial startup time. Although Python's interpreter is optimized to not import the same module multiple times, repeatedly executing an import statement can seriously affect performance in some circumstances.


问:
Total number of documents in pysolr
How can I get the total number of documents matching the given query. I have use the query below:

```<code>result = solr.search('ad_id : 20')
print(len(result))
</code>```

Since the default returning value is '10', the output is only 10, but the count is 4000. How can I get the total number of counts?

答:
The count is stored in numFound variable. Use the code below:</p>

```<code>result = solr.search('ad_id : 20')
print(result.raw_response['response']['numFound'])
</code>```

Title: Total number of documents in pysolr

Body:
How can I get the total number of documents matching the given query. I have use the query below:

result = solr.search('ad_id : 20')
print(len(result))

Since the default returning value is '10', the output is only 10, but the count is 4000. How can I get the total number of counts?

Body:
The count is stored in numFound variable. Use the code below:

result = solr.search('ad_id : 20')
print(result.raw_response['response']['numFound'])


问:
"Connection for controluser as defined in your configuration failed" with phpMyAdmin in XAMPP
I have just installed XAMPP on my Windows XP machine, and I get an error saying:

Connection for controluser as defined in your configuration failed.

Before I installed XAMPP, I had a MySQL database installed and it had a password. I changed and put the password in config.inc.php for MySQL, and I got this error:

```<code><?php
if (!empty($_SERVER['HTTPS']) && ('on' == $_SERVER['HTTPS'])) {
    $uri = 'https://';
} else {
    $uri = 'http://';
}
$uri .= $_SERVER['HTTP_HOST'];
header('Location: '.$uri.'/xampp/');
exit;
?>
</code>```

When I try to access index.php, it seems like something is wrong with the XAMPP installation.  What can I do to fix this problem?

答: I just simply make changes on config.inc.php  file.  There is password in error in this link $cfg['Servers'][$i]['password'] = 'your password '; and now its perfectly worked .</p>

Body:
I have just installed XAMPP on my Windows XP machine, and I get an error saying:

Connection for controluser as defined in your configuration failed.

Before I installed XAMPP, I had a MySQL database installed and it had a password. I changed and put the password in config.inc.php for MySQL, and I got this error:

<?php
if (!empty($_SERVER['HTTPS']) && ('on' == $_SERVER['HTTPS'])) {
    $uri = 'https://';
} else {
    $uri = 'http://';
}
$uri .= $_SERVER['HTTP_HOST'];
header('Location: '.$uri.'/xampp/');
exit;
?>

When I try to access index.php, it seems like something is wrong with the XAMPP installation.  What can I do to fix this problem?


问:
How to return boolean in if else statement and the return value will link to anothe if else statement in Matlab?
I have the following if else statement that created by myself in order to link to the if else statement given in second part:

```<code>m=4
if m==3
   disp(true)
else
   disp(false)
</code>```

Second part ( this code is fix cannot be change):

```<code>if (true)
   A=Hello World
else
   A=Bye
</code>```

If using the first part code, my output will be

```<code>A=Hello World
</code>```

but my desire output is

```<code>A=Bye
</code>```

Anyone one have idea to edit the first part, because now my return value in first part not able to link to my second part.

答:
If you can't change the second part's code, I'm afraid your desire cannot be fulfilled. Or rather, I'm afraid your code won't run at all, because your perenthesis, quotes, end-statement (and arguably semicolons) are not in place.

```<code>if true
    A = 'Hello World';
else
    A = 'Bye';
end
</code>```

This code will return A = 'Hello World', no matter what, since true is always true. If-else conditions work like this:

```<code>if (*what's in here evealuates to true*)
%do stuff
else (*if what's up there does not evaluate to true*)
%do other stuff
</code>```

Clearly, true will always evaluate to true. So the above if-else condition will always return A = 'Hello World'.

Body:
I have the following if else statement that created by myself in order to link to the if else statement given in second part:

m=4
if m==3
   disp(true)
else
   disp(false)

Second part ( this code is fix cannot be change):

if (true)
   A=Hello World
else
   A=Bye

If using the first part code, my output will be

A=Hello World

but my desire output is

A=Bye

Anyone one have idea to edit the first part, because now my return value in first part not able to link to my second part.

Body:
If you can't change the second part's code, I'm afraid your desire cannot be fulfilled. Or rather, I'm afraid your code won't run at all, because your perenthesis, quotes, end-statement (and arguably semicolons) are not in place.

if true
    A = 'Hello World';
else
    A = 'Bye';
end

This code will return A = 'Hello World', no matter what, since true is always true. If-else conditions work like this:

if (*what's in here evealuates to true*)
%do stuff
else (*if what's up there does not evaluate to true*)
%do other stuff

Clearly, true will always evaluate to true. So the above if-else condition will always return A = 'Hello World'.


问:
remove part of name query MySql
this is my record in database
Dynamic Keyword In C# 4.0 - Part 3

now i want edit this name with query to
Dynamic Keyword In C# 4.0 - Part 3

as u seen I want to remove ftp/ after domain address

答:
You can use the REPLACE(str, find_string, replace_with) build in FUNCTION

```<code>SELECT REPLACE(`link_field`, '/ftp/', '/') AS `link` FROM `table`;
</code>```

see more info and examples in

https://dev.mysql.com/doc/refman/5.7/en/string-functions.html#function_replace

https://www.w3resource.com/mysql/string-functions/mysql-replace-function.php

Title: remove part of name query MySql

Body:
You can use the REPLACE(str, find_string, replace_with) build in FUNCTION

SELECT REPLACE(`link_field`, '/ftp/', '/') AS `link` FROM `table`;

see more info and examples in

https://dev.mysql.com/doc/refman/5.7/en/string-functions.html#function_replace

https://www.w3resource.com/mysql/string-functions/mysql-replace-function.php


问:
Install TensorFlow's tf-nightly and tf-nightly-gpu on macOS
I have run into a known issue with TensorFlow 1.4 and Python 3.6, which manifests itself by this RuntimeWarning:

```<code>compiletime version 3.5 of module 'tensorflow.python.framework.fast_tensor_util'
does not match runtime version 3.6
</code>```

I would like to overcome by installing the latest tf-nightly and tf-nightly-gpu, as currently recommended. So far, I have so far followed normal instructions for installing TensorFlow (on macOS) like so:

```<code>virtualenv --system-site-packages ~/tensorflow
source ~/tensorflow/bin/activate
(tensorflow)$ easy_install -U pip
(tensorflow)$ pip install --upgrade tensorflow
</code>```

What (minimal) changes to these steps so that they perform installation from tf-nightly and tf-nightly-gpu?

答: using --upgrade will try to get tensorflow for the python version it was originally installed for, which the error says is 3.5, while you're currently apparently running 3.6 as the default

Body:
I have run into a known issue with TensorFlow 1.4 and Python 3.6, which manifests itself by this RuntimeWarning:

compiletime version 3.5 of module 'tensorflow.python.framework.fast_tensor_util'
does not match runtime version 3.6

I would like to overcome by installing the latest tf-nightly and tf-nightly-gpu, as currently recommended. So far, I have so far followed normal instructions for installing TensorFlow (on macOS) like so:

virtualenv --system-site-packages ~/tensorflow
source ~/tensorflow/bin/activate
(tensorflow)$ easy_install -U pip
(tensorflow)$ pip install --upgrade tensorflow

What (minimal) changes to these steps so that they perform installation from tf-nightly and tf-nightly-gpu?


问:
Can multiple versions of the same iphone or android app use shared code or libraries?
Let's say I write an app that displays restaurant menus and lets a user order items from them. I'll call it RestaurantMenuApp. I'd like to have this main application be branded under my company name. It would allow users to view multiple different restaurants and place orders on any of them. Purchases are done through API calls to my web service using my company's merchant account.

Now let's say I also want to sell customized versions of this app to individual restaurants. The customized version would be themed just for that restaurant, only show their menus, locations, their promos, and so forth. It would make the restaurant look like they built their own custom app. Purchases are still done through API calls to my web service, but each branded version can use their own merchant account.

I'm wondering if each application (the main RestaurantMenuApp and each individually customized restaurant app) has to contain an entire copy of the entire application. Is it possible to have each app install a shared library that all of the apps use? If any of the apps has already installed this shared library, the others apps don't need to install it as well?

I'm new to mobile app development and searched for answers, but could only find solutions for how to build lite vs. full versions of the same app. It was not clear if these apps could SHARE code to make each install smaller.

答: For iPhone/iOS App store apps, an OS enforced security sandbox prohibits apps from sharing any code.</p>


问:
Automatic pull from remote
I have a remote repository (on bitbucket) that houses all of our production and staging repositories. When I am on my local development machine and make a commit + push, how can I set my development server (its remotely hosted, sharing the same remote repository) up to automatically know that I pushed, so it does a pull request to pull in the changes that I pushed up to the remote repository?

Is there any easy way to do this? Right now, I am manually SSHing into the development server and pulling, but this is time consuming, and there are times that I forget to do it, and the content team working on the content doesn't get the latest changes.

Are there git hooks available for this, or do I need to write some custom functionality to check the current remote HEAD and pull if it's changed (on a cron job most likely)

答:
git pull is kind of idempotent, so simply launch it in a cron job, no need to check if it's necessary or not.

If you want a smarter solution, use webhooks:

Create a webapp that will perform the pull when an URL is called

Configure a webhook in bitbucket to call this URL and is triggered by a push event on the repo

Title: Automatic pull from remote


问:
Website Components Don't Resize when Viewing Horizontally on Mobile
I've created a website that works perfectly when viewed on desktop. When I view it vertically on a mobile phone, everything fits on screen, just like on a desktop. However, when I tilt the phone and view the website horizontally, everything scales wrong, even after refreshing.

For the size of containers, images, etc. I've used vw and vh.

When I view the website horizontally, the width and height effectively switch values... except the components are still the same size as they were in portrait mode.

Can anyone tell me how I can bind the sizes of components to the width/height or the screen?

答:
The problem you have could appear out of the aspect ratio that changes when you tilt your phone.

If you use vw and vh units - keep in mind, that a container in vertical hold has ~ twice the total height if its in horizontal position.

I.E.: A samsung galaxy s5 has 360px on short and 640px on its long side.

You have several options to solve your problem, just two of them but in my opinion the most powerful are the following.

Take a look on the flexbox system - it's really simple and easy to use, especially for responsive designs!
https://www.w3schools.com/css/css3_flexbox.asp

With media querys you can set different attributes and values for different display/window sizes.
https://www.w3schools.com/css/css_rwd_mediaqueries.asp


问:
How can I add condition based on the parameters of the array data on the rules Laravel?
I use Laravel 5.3

My rules Laravel like this :

```<code><?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class AddCartRequest extends FormRequest
{
    public function rules()
    {
        return [
            'product_id'=>'required|numeric',
            'delivery_address'=>'required',
            'request_delivery_at' => 'required|date_format:d-m-Y H:i:s|after:120 minutes'
        ];
    }
}
</code>```

The result of echo '```';print_r($this->request->get('delivery_address'));echo '```'; like this :

```<code>Array
(
    [sender_name] => chelsea
    [postal] => 12345
    [country] => japan
    [city] => tokyo
    [send_date] => 09-12-2017
    [send_time] =>
    [information] => test
)
</code>```

I want to make it like this :

If send_time is empty, the rules of request_delivery_at like this :

```<code>'request_delivery_at' => 'required|date_format:d-m-Y H:i:s'
</code>```

So, it without |after:120 minutes

If send_time is have value (for example send_time = 12:30:00), the rules of request_delivery_at like this :

```<code>'request_delivery_at' => 'required|date_format:d-m-Y H:i:s|after:120 minutes'
</code>```

How can I do it?

Update :

I try like this :

```<code>public function rules()
{
    $send_time = $this->request->get('delivery_address')['send_time'];

    if($send_time)
        $validation_time = '|after:120 minutes';
    else
        $validation_time = '';

    return [
        'product_id'=>'required|numeric',
        'delivery_address'=>'required',
        'request_delivery_at' => 'required|date_format:d-m-Y H:i:s'.$validation_time
    ];
}
</code>```

Seems it works

答:
Your question is not very clear for me, so far to what i understand is, you want to have conditional validation rule, based on the send time in delivery address array's presence,

you can achieve this by creating your own validation rule or by adding validations checking conditionally in the controller it self,

controller method ex:

```<code>if(!$request->has('delivery_address.send_time')){
    $rules = [

    ];

    $messages = [

    ];

    $validator = Validator::make($request->all(),$rules,$messages);
    if($validator->fails()){
        $this->throwValidationException($request,$validator);
    }
}else{
  $rules = [

    ];

    $messages = [

    ];

    $validator = Validator::make($request->all(),$rules,$messages);
    if($validator->fails()){
        $this->throwValidationException($request,$validator);
    }

}
</code>```

or you can refer the following my SO answer on how to make custom validation rule.
Date Compare in validation Laravel 5.2

Body:
I use Laravel 5.3

My rules Laravel like this :

<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class AddCartRequest extends FormRequest
{
    public function rules()
    {
        return [
            'product_id'=>'required|numeric',
            'delivery_address'=>'required',
            'request_delivery_at' => 'required|date_format:d-m-Y H:i:s|after:120 minutes'
        ];
    }
}

The result of echo '
';print_r($this->request->get('delivery_address'));echo '
'; like this :

Array
(
    [sender_name] => chelsea
    [postal] => 12345
    [country] => japan
    [city] => tokyo
    [send_date] => 09-12-2017
    [send_time] =>
    [information] => test
)

I want to make it like this :

If send_time is empty, the rules of request_delivery_at like this :

'request_delivery_at' => 'required|date_format:d-m-Y H:i:s'

So, it without |after:120 minutes

If send_time is have value (for example send_time = 12:30:00), the rules of request_delivery_at like this :

'request_delivery_at' => 'required|date_format:d-m-Y H:i:s|after:120 minutes'

How can I do it?

Update :

I try like this :

public function rules()
{
    $send_time = $this->request->get('delivery_address')['send_time'];

    if($send_time)
        $validation_time = '|after:120 minutes';
    else
        $validation_time = '';

    return [
        'product_id'=>'required|numeric',
        'delivery_address'=>'required',
        'request_delivery_at' => 'required|date_format:d-m-Y H:i:s'.$validation_time
    ];
}

Seems it works

Body:
Your question is not very clear for me, so far to what i understand is, you want to have conditional validation rule, based on the send time in delivery address array's presence,

you can achieve this by creating your own validation rule or by adding validations checking conditionally in the controller it self,

controller method ex:

if(!$request->has('delivery_address.send_time')){
    $rules = [

    ];

    $messages = [

    ];

    $validator = Validator::make($request->all(),$rules,$messages);
    if($validator->fails()){
        $this->throwValidationException($request,$validator);
    }
}else{
  $rules = [

    ];

    $messages = [

    ];

    $validator = Validator::make($request->all(),$rules,$messages);
    if($validator->fails()){
        $this->throwValidationException($request,$validator);
    }

}

or you can refer the following my SO answer on how to make custom validation rule.
Date Compare in validation Laravel 5.2


问:
Xamarin.Forms center title and transparent navigation bar - Android
I am using Xamarin.Forms and I have a problem getting 2 things to work on Android:

I want to set ActionBar to be transparent, setting BarBackgroundColor works with every color but not with transparent.

I want the page title to be centered, just like it is on iOS.

```<code>MainPage = new NavigationPage(
       new LoginPage(){Title = "Center"}) {BarBackgroundColor = Color.Transparent});
</code>```

Can anyone help me with this?

答:
I have recently encounter the same problem, I was using MasterDetailPage in Xamarin.Forms and in android it does not set the title to center.

So, obvious route was to create a custom renderer and override its OnLayout method, and find Toolbar's TextView and set its Gravity to Center, easy right?

But hey when i try to do this myTextView.Gravity = Android.Views.GravityFlags.Center it just doesn't work. I tried setting ForegroundGravity but no effect.

So finally i've calculated center X position and set TextView X position and VOILLA! it is now in center. Here is my solution.

```<code>[assembly: ExportRenderer(typeof(CustomMasterDetailPage), typeof(CustomMasterDetailPageRenderer))]
namespace myApp.Droid
{
    public class CustomMasterDetailPageRenderer : MasterDetailPageRenderer
    {
        protected override void OnLayout(bool changed, int l, int t, int r, int b)
        {
            base.OnLayout(changed, l, t, r, b);

            var toolbar = FindViewById<Android.Support.V7.Widget.Toolbar>(Resource.Id.toolbar);

            for (int index = 0; index < toolbar.ChildCount; index++)
            {
                if (toolbar.GetChildAt(index) is TextView)
                {
                    var title = toolbar.GetChildAt(index) as TextView;
                    float toolbarCenter = toolbar.MeasuredWidth / 2;
                    float titleCenter = title.MeasuredWidth / 2;
                    title.SetX(toolbarCenter - titleCenter);
                }
            }
        }
    }
}
</code>```

Body:
I am using Xamarin.Forms and I have a problem getting 2 things to work on Android:

I want to set ActionBar to be transparent, setting BarBackgroundColor works with every color but not with transparent.

I want the page title to be centered, just like it is on iOS.

MainPage = new NavigationPage(
       new LoginPage(){Title = "Center"}) {BarBackgroundColor = Color.Transparent});

Can anyone help me with this?

Body:
I have recently encounter the same problem, I was using MasterDetailPage in Xamarin.Forms and in android it does not set the title to center.

So, obvious route was to create a custom renderer and override its OnLayout method, and find Toolbar's TextView and set its Gravity to Center, easy right?

But hey when i try to do this myTextView.Gravity = Android.Views.GravityFlags.Center it just doesn't work. I tried setting ForegroundGravity but no effect.

So finally i've calculated center X position and set TextView X position and VOILLA! it is now in center. Here is my solution.

[assembly: ExportRenderer(typeof(CustomMasterDetailPage), typeof(CustomMasterDetailPageRenderer))]
namespace myApp.Droid
{
    public class CustomMasterDetailPageRenderer : MasterDetailPageRenderer
    {
        protected override void OnLayout(bool changed, int l, int t, int r, int b)
        {
            base.OnLayout(changed, l, t, r, b);

            var toolbar = FindViewById<Android.Support.V7.Widget.Toolbar>(Resource.Id.toolbar);

            for (int index = 0; index < toolbar.ChildCount; index++)
            {
                if (toolbar.GetChildAt(index) is TextView)
                {
                    var title = toolbar.GetChildAt(index) as TextView;
                    float toolbarCenter = toolbar.MeasuredWidth / 2;
                    float titleCenter = title.MeasuredWidth / 2;
                    title.SetX(toolbarCenter - titleCenter);
                }
            }
        }
    }
}


问:
Locate an element in selenium having only href
I am trying to click a Href element

```<code><a type="button" class="btn btn-primary sub_count" href="http://10.144.97.192:8090/JEP/HQCreation">
<span class="fa fa-plus"></span>
</a>
</code>```

in selenium.
I have tried

```<code>driver.findElement(By.xpath("//a[@href='http://10.144.97.192:8090/JEP/HQCreation']")).click();
</code>```

And getting following error:

org.openqa.selenium.InvalidSelectorException: invalid selector: An
  invalid or illegal selector was specified

Kindly help

答:
you can use cssselector instead of xpath. You please try with the below code

```<code>WebElement element= driver.findElement(By.cssSelector("a[href='http://10.144.97.192:8090/JEP/HQCreation']"));

JavascriptExecutor executor = (JavascriptExecutor) driver;
executor.executeScript("arguments[0].click();", element);
</code>```

or

```<code>driver.findElement(By.cssSelector("a[href='http://10.144.97.192:8090/JEP/HQCreation']")).click();
</code>```

as you have asked a very basic question you can follow  https://www.testingexcellence.com/click-link-href-value-webdriver/

Body:
I am trying to click a Href element

in selenium.
I have tried

driver.findElement(By.xpath("//a[@href='http://10.144.97.192:8090/JEP/HQCreation']")).click();

And getting following error:

org.openqa.selenium.InvalidSelectorException: invalid selector: An
  invalid or illegal selector was specified

Kindly help

Body:
you can use cssselector instead of xpath. You please try with the below code

WebElement element= driver.findElement(By.cssSelector("a[href='http://10.144.97.192:8090/JEP/HQCreation']"));

JavascriptExecutor executor = (JavascriptExecutor) driver;
executor.executeScript("arguments[0].click();", element);

or

driver.findElement(By.cssSelector("a[href='http://10.144.97.192:8090/JEP/HQCreation']")).click();

as you have asked a very basic question you can follow  https://www.testingexcellence.com/click-link-href-value-webdriver/


问:
How to create a button with function parameter?
I want to create a button by using function below, example createGetInfo(120,Test,1) I want the result become a 'Test' button with 120 width but the function below fail, How can I put the parameter inside the button tag?</p>

```<code>function createGetInfo(size,wording,filter) {
    var GetInfo = $("<button class='eqGroupBtn' type='button' class='btn' style='width:size'>wording</button>");
    secondLevelMenuDiv.append(GetInfo);
    GetInfo.click(function(){
        Do something...
    });
};
</code>```

答:
```<code>function createGetInfo(size,wording,filter) {
    var GetInfo = $("<button class='eqGroupBtn' type='button' class='btn' style='width:'+size + 'px'>wording</button>");
    secondLevelMenuDiv.append(GetInfo);
    GetInfo.click(function(){
        Do something...
    });
};

'width:'+size + 'px'
</code>```

Define it like the above

Body:
I want to create a button by using function below, example createGetInfo(120,Test,1) I want the result become a 'Test' button with 120 width but the function below fail, How can I put the parameter inside the button tag?

function createGetInfo(size,wording,filter) {
    var GetInfo = $("<button class='eqGroupBtn' type='button' class='btn' style='width:size'>wording</button>");
    secondLevelMenuDiv.append(GetInfo);
    GetInfo.click(function(){
        Do something...
    });
};

Body:
function createGetInfo(size,wording,filter) {
    var GetInfo = $("<button class='eqGroupBtn' type='button' class='btn' style='width:'+size + 'px'>wording</button>");
    secondLevelMenuDiv.append(GetInfo);
    GetInfo.click(function(){
        Do something...
    });
};

'width:'+size + 'px'

Define it like the above


问:
ggplot2 facet - Highlight matching columns
Sample data set

```<code>brand=c('MS', 'Google', 'Apple', 'MS', 'FB', 'Apple', 'Oracle')
product=c('OS', 'Search', 'Iphone', 'Search', 'Network', 'OS', 'DB')
df= data.frame(brand, product)
</code>```

it looks like this

```<code>   brand product
1     MS      OS
2 Google  Search
3  Apple  Iphone
4     MS  Search
5     FB Network
6  Apple      OS
7 Oracle      DB
</code>```

Problem statement

I am plotting this graph using ggplot, here the code

```<code>library(dplyr)
library(ggplot2)
df %>%
    group_by(brand) %>%
    count(product, sort = TRUE) %>%
    ggplot(aes(product, n)) +
        geom_col()  +
        facet_wrap(~brand, ncol = 5, scales = "free_x") +
        coord_flip()
</code>```

it will give graph like this

Now we can see 'search' is common in both 'Google' and 'MS' and 'OS' is common in 'MS' and 'Appple', I want to highlight both the bars but don't know how can I do it, Please suggest also let me know if its possible with other graphical interface other than ggplot.

答:
My approach to this problem: use geom_point() instead of facets and specify color if there are multiple occurrences of the same product (also added some minor visual tweaks).

```<code>library(ggplot2)

# Define color
df$myColor <- NA
foo <- df$product %in% names(which(table(df$product) > 1))
df$myColor[foo] <- df$product[foo]

ggplot(df, aes(brand, product, color = myColor)) +
    geom_point(shape = 15, size = 20) +
    scale_color_brewer(guide = FALSE, palette = "Dark2", na.value = "grey") +
    labs(x = NULL,
         y = NULL) +
    theme_classic() +
    theme(axis.ticks = element_blank(),
          axis.text = element_text(size = 15, color = "black"))
</code>```

Body:
Sample data set

brand=c('MS', 'Google', 'Apple', 'MS', 'FB', 'Apple', 'Oracle')
product=c('OS', 'Search', 'Iphone', 'Search', 'Network', 'OS', 'DB')
df= data.frame(brand, product)

it looks like this

   brand product
1     MS      OS
2 Google  Search
3  Apple  Iphone
4     MS  Search
5     FB Network
6  Apple      OS
7 Oracle      DB

Problem statement

I am plotting this graph using ggplot, here the code

library(dplyr)
library(ggplot2)
df %>%
    group_by(brand) %>%
    count(product, sort = TRUE) %>%
    ggplot(aes(product, n)) +
        geom_col()  +
        facet_wrap(~brand, ncol = 5, scales = "free_x") +
        coord_flip()

it will give graph like this

Now we can see 'search' is common in both 'Google' and 'MS' and 'OS' is common in 'MS' and 'Appple', I want to highlight both the bars but don't know how can I do it, Please suggest also let me know if its possible with other graphical interface other than ggplot.

Body:
My approach to this problem: use geom_point() instead of facets and specify color if there are multiple occurrences of the same product (also added some minor visual tweaks).

library(ggplot2)

# Define color
df$myColor <- NA
foo <- df$product %in% names(which(table(df$product) > 1))
df$myColor[foo] <- df$product[foo]

ggplot(df, aes(brand, product, color = myColor)) +
    geom_point(shape = 15, size = 20) +
    scale_color_brewer(guide = FALSE, palette = "Dark2", na.value = "grey") +
    labs(x = NULL,
         y = NULL) +
    theme_classic() +
    theme(axis.ticks = element_blank(),
          axis.text = element_text(size = 15, color = "black"))


问:
Multiple images not inserted into mysql database
I am unable to insert multiple images into  database. When I am inserting the images, only one image is inserted. not all inserted. I have shown here the form with php insert code.I have not found where the problem is. Plz help.

```<code>$(document).ready(function() {
  if (window.File && window.FileList && window.FileReader) {
    $("#files").on("change", function(e) {
      var files = e.target.files,
        filesLength = files.length;
      for (var i = 0; i < filesLength; i++) {
        var f = files[i]
        var fileReader = new FileReader();
        fileReader.onload = (function(e) {
          var file = e.target;
          $("<span class=\"pip\">" +
            "<img class=\"imageThumb\" src=\"" + e.target.result + "\" title=\"" + file.name + "\"/>" +
            "<br/><span class=\"remove\">Remove image</span>" +
            "</span>").insertAfter("#files");
          $(".remove").click(function(){
            $(this).parent(".pip").remove();
          });
        });
        fileReader.readAsDataURL(f);
      }
    });
  } else {
    alert("Your browser doesn't support to File API")
  }
});

input[type="file"] {display: block;}
.imageThumb {max-height: 75px; border: 2px solid; padding: 1px; cursor: pointer;}
.pip {display: inline-block; margin: 10px 10px 0 0;}
.remove { display: block;background: #444;border: 1px solid black;color: white;text-align: center;cursor: pointer;}
.remove:hover {background: white;color: black;}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <h3>Upload your images</h3>
  <input type="file" id="files" name="files[]" multiple /><br>
  <input type="submit" name="submit" value="Submit">
</div>
</code>```

This is php code:

```<code><?php
   if(isset($_POST['submit']))
      {
      if(isset($_FILES['files']))
         {

        $n_arrays = $_FILES['files']['name'];
        $tmp_name_arrays = $_FILES['files']['tmp_name'];
        $type_arrays = $_FILES['files']['type'];
        $size_arrays = $_FILES['files']['size'];

        foreach ($tmp_name_arrays as $index => $val)
        {
            $n_array = $n_arrays[$index];
            $tmp_name_array = $tmp_name_arrays[$index];
            $type_array = $type_arrays[$index];
            $size_array = $size_arrays[$index];

            if(move_uploaded_file($tmp_name_array, "ad/data/img/".$n_array))
            {
                $sql = 'INSERT INTO `image`
                        SET `img_name` = ?, `img_type` = ?, `img_size` = ?';

                // Prepare the SQL statement for execution.
                $statement = $connection->prepare($sql);
                $bound = $statement->bind_param('sss', $n_array, $type_array, $size_array);

                // Execute the prepared statement.
                $executed2 = $statement->execute();

                if(!$executed2){
                    echo "error". mysqli_error($connection);
                } else {
                    $_SESSION['s']="Images successfully saved";
                    header('location:posting_ad_image.php');
                }
            }
        }
    }
 }
?>
</code>```

I am able to upload only the last image that is uploaded last. All images are not inserted into phpmyadmin database.

答:
The problem is you are redirecting to page after upload fist image. You need to change your if-else statmente.</p>

```<code><?php
   if(isset($_POST['submit']))
      {
      if(isset($_FILES['files']))
         {

        $n_arrays = $_FILES['files']['name'];
        $tmp_name_arrays = $_FILES['files']['tmp_name'];
        $type_arrays = $_FILES['files']['type'];
        $size_arrays = $_FILES['files']['size'];

        foreach ($tmp_name_arrays as $index => $val)
        {
            $n_array = $n_arrays[$index];
            $tmp_name_array = $tmp_name_arrays[$index];
            $type_array = $type_arrays[$index];
            $size_array = $size_arrays[$index];

            if(move_uploaded_file($tmp_name_array, "ad/data/img/".$n_array))
            {
                $sql = 'INSERT INTO `image`
                        SET `img_name` = ?, `img_type` = ?, `img_size` = ?';

                // Prepare the SQL statement for execution.
                $statement = $connection->prepare($sql);

                $bound = $statement->bind_param('sss', $n_array, $type_array, $size_array);

                // Execute the prepared statement.
                $executed2 = $statement->execute();

                if(!$executed2){
                                                echo "error". mysqli_error($connection);
                                                }else{
                                                    $_SESSION['s']="Images successfully saved";

                                                }
            }
        }
        header('location:posting_ad_image.php');// add it here after for loop
    }

 }
?>
</code>```

Body:
I am unable to insert multiple images into  database. When I am inserting the images, only one image is inserted. not all inserted. I have shown here the form with php insert code.I have not found where the problem is. Plz help.

$(document).ready(function() {
  if (window.File && window.FileList && window.FileReader) {
    $("#files").on("change", function(e) {
      var files = e.target.files,
        filesLength = files.length;
      for (var i = 0; i < filesLength; i++) {
        var f = files[i]
        var fileReader = new FileReader();
        fileReader.onload = (function(e) {
          var file = e.target;
          $("" +
            "" +
            "
Remove image" +
            "").insertAfter("#files");
          $(".remove").click(function(){
            $(this).parent(".pip").remove();
          });
        });
        fileReader.readAsDataURL(f);
      }
    });
  } else {
    alert("Your browser doesn't support to File API")
  }
});

input[type="file"] {display: block;}
.imageThumb {max-height: 75px; border: 2px solid; padding: 1px; cursor: pointer;}
.pip {display: inline-block; margin: 10px 10px 0 0;}
.remove { display: block;background: #444;border: 1px solid black;color: white;text-align: center;cursor: pointer;}
.remove:hover {background: white;color: black;}

Upload your images

  <input type="file" id="files" name="files[]" multiple />

  <input type="submit" name="submit" value="Submit">

This is php code:

<?php
   if(isset($_POST['submit']))
      {
      if(isset($_FILES['files']))
         {

        $n_arrays = $_FILES['files']['name'];
        $tmp_name_arrays = $_FILES['files']['tmp_name'];
        $type_arrays = $_FILES['files']['type'];
        $size_arrays = $_FILES['files']['size'];

        foreach ($tmp_name_arrays as $index => $val)
        {
            $n_array = $n_arrays[$index];
            $tmp_name_array = $tmp_name_arrays[$index];
            $type_array = $type_arrays[$index];
            $size_array = $size_arrays[$index];

            if(move_uploaded_file($tmp_name_array, "ad/data/img/".$n_array))
            {
                $sql = 'INSERT INTO `image`
                        SET `img_name` = ?, `img_type` = ?, `img_size` = ?';

                // Prepare the SQL statement for execution.
                $statement = $connection->prepare($sql);
                $bound = $statement->bind_param('sss', $n_array, $type_array, $size_array);

                // Execute the prepared statement.
                $executed2 = $statement->execute();

                if(!$executed2){
                    echo "error". mysqli_error($connection);
                } else {
                    $_SESSION['s']="Images successfully saved";
                    header('location:posting_ad_image.php');
                }
            }
        }
    }
 }
?>

I am able to upload only the last image that is uploaded last. All images are not inserted into phpmyadmin database.

Body:
The problem is you are redirecting to page after upload fist image. You need to change your if-else statmente.

<?php
   if(isset($_POST['submit']))
      {
      if(isset($_FILES['files']))
         {

        $n_arrays = $_FILES['files']['name'];
        $tmp_name_arrays = $_FILES['files']['tmp_name'];
        $type_arrays = $_FILES['files']['type'];
        $size_arrays = $_FILES['files']['size'];

        foreach ($tmp_name_arrays as $index => $val)
        {
            $n_array = $n_arrays[$index];
            $tmp_name_array = $tmp_name_arrays[$index];
            $type_array = $type_arrays[$index];
            $size_array = $size_arrays[$index];

            if(move_uploaded_file($tmp_name_array, "ad/data/img/".$n_array))
            {
                $sql = 'INSERT INTO `image`
                        SET `img_name` = ?, `img_type` = ?, `img_size` = ?';

                // Prepare the SQL statement for execution.
                $statement = $connection->prepare($sql);

                $bound = $statement->bind_param('sss', $n_array, $type_array, $size_array);

                // Execute the prepared statement.
                $executed2 = $statement->execute();

                if(!$executed2){
                                                echo "error". mysqli_error($connection);
                                                }else{
                                                    $_SESSION['s']="Images successfully saved";

                                                }
            }
        }
        header('location:posting_ad_image.php');// add it here after for loop
    }

 }
?>


问:
Mysql select recursive get all child with multiple level
i have a table

```<code> CREATE TABLE IF NOT EXISTS `Folder` (
    `idFolder` INT(11) NOT NULL AUTO_INCREMENT,
    `FolderName` VARCHAR(150) NOT NULL,
    `idFolderParent` INT(11) NULL,
    PRIMARY KEY (`idFolder`),
    CONSTRAINT `fk_1`
    FOREIGN KEY (`idFolderParent`)
    REFERENCES `Folder` (`idFolder`)
)
</code>```

i fill this table by

```<code>idFolder , FolderName , idFolderParent
   1           ADoc           Null
   2           ADoc1           1
   3           ADoc2           2
   4           ADoc3           3
   5           ADoc4           4
   6           ADoc5           5
   7           ADoc6           4
</code>```

when select a folder with idFolder=1, it should be return all child for this folder and subchild folder(2, 3, 4, 5 ,6 ,7)

When i select a folder id = 4 ==> (5,7, 6)

When i select a folder id = 3 ==> (4, 5,6, 7)

How to do that with one query?

Thx

答:
to get all level child of a particular parent you can use this below query:</p>

```<code> select idFolder from (select * from Folder order by idFolderParent, idFolder) Folder, (select @pv := '1') initialisation where find_in_set(idFolderParent, @pv) > 0 and @pv := concat(@pv, ',', idFolder )
</code>```

Body:
i have a table

 CREATE TABLE IF NOT EXISTS `Folder` (
    `idFolder` INT(11) NOT NULL AUTO_INCREMENT,
    `FolderName` VARCHAR(150) NOT NULL,
    `idFolderParent` INT(11) NULL,
    PRIMARY KEY (`idFolder`),
    CONSTRAINT `fk_1`
    FOREIGN KEY (`idFolderParent`)
    REFERENCES `Folder` (`idFolder`)
)

i fill this table by

idFolder , FolderName , idFolderParent
   1           ADoc           Null
   2           ADoc1           1
   3           ADoc2           2
   4           ADoc3           3
   5           ADoc4           4
   6           ADoc5           5
   7           ADoc6           4

when select a folder with idFolder=1, it should be return all child for this folder and subchild folder(2, 3, 4, 5 ,6 ,7)

When i select a folder id = 4 ==> (5,7, 6)

When i select a folder id = 3 ==> (4, 5,6, 7)

How to do that with one query?

Thx

Body:
to get all level child of a particular parent you can use this below query:

 select idFolder from (select * from Folder order by idFolderParent, idFolder) Folder, (select @pv := '1') initialisation where find_in_set(idFolderParent, @pv) > 0 and @pv := concat(@pv, ',', idFolder )


问:
How do I create a custom event class in Javascript?
How do I create a custom event class similar to ActionScript? What I mean by that is a class that I can use to fire off my own events, send the necessary data.

I don't want to use third-party libraries like YUI or jQuery to do it. My goal is to be able to send a event that looks like this:

```<code>document.addEventListener("customEvent", eventHandler, false);

function eventHandler(e){
    alert(e.para1);
}

document.dispatchEvent(new CustomEvent("customEvent", para1, para2));
</code>```

Please no third-party library solutions.

答:
This by John Resig:

```<code>function addEvent( obj, type, fn ) {
  if ( obj.attachEvent ) {
    obj['e'+type+fn] = fn;
    obj[type+fn] = function(){obj['e'+type+fn]( window.event );}
    obj.attachEvent( 'on'+type, obj[type+fn] );
  } else
    obj.addEventListener( type, fn, false );
}
function removeEvent( obj, type, fn ) {
  if ( obj.detachEvent ) {
    obj.detachEvent( 'on'+type, obj[type+fn] );
    obj[type+fn] = null;
  } else
    obj.removeEventListener( type, fn, false );
}
</code>```

More at his blog post at http://ejohn.org/projects/flexible-javascript-events/.

ContentLicense: CC BY-SA 4.0

Body:
How do I create a custom event class similar to ActionScript? What I mean by that is a class that I can use to fire off my own events, send the necessary data.

I don't want to use third-party libraries like YUI or jQuery to do it. My goal is to be able to send a event that looks like this:

document.addEventListener("customEvent", eventHandler, false);

function eventHandler(e){
    alert(e.para1);
}

document.dispatchEvent(new CustomEvent("customEvent", para1, para2));

Please no third-party library solutions.

Body:
This by John Resig:

function addEvent( obj, type, fn ) {
  if ( obj.attachEvent ) {
    obj['e'+type+fn] = fn;
    obj[type+fn] = function(){obj['e'+type+fn]( window.event );}
    obj.attachEvent( 'on'+type, obj[type+fn] );
  } else
    obj.addEventListener( type, fn, false );
}
function removeEvent( obj, type, fn ) {
  if ( obj.detachEvent ) {
    obj.detachEvent( 'on'+type, obj[type+fn] );
    obj[type+fn] = null;
  } else
    obj.removeEventListener( type, fn, false );
}

More at his blog post at http://ejohn.org/projects/flexible-javascript-events/.


问:
how to prevent infinite while loop in python 3
I am creating a program that plays the game pig dice. It should do the following:
1. Select whether the user or the computer plays the first turn.
2. If computer starts first, computer plays one turn
3. Repeat as long as computer score is less than 100:
a. User plays one turn.
b. If user’s score reaches 100, exit loop
c. Computer plays one turn.
4. Print results.
My problem is that when I run the program, there is an infinite loop, and I am not sure where it is running into this problem. Could anyone point out where the problem is occurring and possibly make suggestions as to how to prevent this? Pointing out any other errors is also appreciated as I am new to python.

```<code>from random import randint

def print_scores(uscore, cscore):
    uscore = 0
    cscore = 0

    print(uscore, cscore)

def roll_two_dice():
    roll1 = randint(1, 6)
    roll2 = randint(1, 6)

    if roll1 or roll2 == 1:
        return 0

    elif roll1 and roll2 == 1:
        return 25
    else:
        return roll1 + roll2

def computerTurn(score):

    turn_score = 0
    while score + turn_score < 100 and turn_score < 20:
        roll = roll_two_dice()
        if roll == 0:
            return 0
        score = roll + turn_score
    return turn_score

def userTurn(score):
    turn_score = 0
    while score + turn_score < 100 or user == hold:
        roll = roll_two_dice()
        if roll == 0:
            return 0
        score = roll + turn_score
    return turn_score

def final_result(uscore, cscore):
    uscore = 0
    cscore = 0
    print('Final results:{}'.format(uscore, cscore))
    if uscore >= 100:
        print('You win')
    else:
        print('Computer wins')

def main():
    c_score = 0
    u_score = 0
    if randint(0, 1) == 0:
        print('Computer starts')
        c_turn = computerTurn(c_score) + c_score
    while c_score < 100:
        print('Current scores')
        print_scores(u_score, c_score)
        u_turn = userTurn(u_score) + u_score
        if u_score >= 100:
            exit
        c_turn = computerTurn(c_score)
        print(c_turn)
        c_score = c_score + c_turn
    final_result(u_score, c_score)

main()
</code>```

codepart1

codepart2

答:
There are a few problems in your code as I have gone through your code extensively.

In the following code segment

def roll_two_dice():
    roll1 = randint(1, 6)
    roll2 = randint(1, 6)

```<code>if roll1 or roll2 == 1:
    return 0

elif roll1 and roll2 == 1:
    return 25
else:
    return roll1 + roll2
</code>```

both the cases should contain ,

roll1 == 1

As the condition that you have written will not check that either roll1 =1 or roll2 =1.Actually it checks roll2 = 1 and roll1 anything other than 1. That could might result in making an infinite loop.

Secondly in the following 2 functions :-

computerTurn(score)

and

userTurn(Score)

You are not updating the value of the turn_score and returning that value that results to make the matter worse and the values c_score always renders to 0 and code will fall in infinite loop.

Also in function

def final_result(uscore, cscore):

You should not make the values of uscore and cscore = 0 as the condition for uscore >= 100 will never come

Body:
I am creating a program that plays the game pig dice. It should do the following:
1. Select whether the user or the computer plays the first turn.
2. If computer starts first, computer plays one turn
3. Repeat as long as computer score is less than 100:
a. User plays one turn.
b. If user’s score reaches 100, exit loop
c. Computer plays one turn.
4. Print results.
My problem is that when I run the program, there is an infinite loop, and I am not sure where it is running into this problem. Could anyone point out where the problem is occurring and possibly make suggestions as to how to prevent this? Pointing out any other errors is also appreciated as I am new to python.

from random import randint

def print_scores(uscore, cscore):
    uscore = 0
    cscore = 0

    print(uscore, cscore)

def roll_two_dice():
    roll1 = randint(1, 6)
    roll2 = randint(1, 6)

    if roll1 or roll2 == 1:
        return 0

    elif roll1 and roll2 == 1:
        return 25
    else:
        return roll1 + roll2

def computerTurn(score):

    turn_score = 0
    while score + turn_score < 100 and turn_score < 20:
        roll = roll_two_dice()
        if roll == 0:
            return 0
        score = roll + turn_score
    return turn_score

def userTurn(score):
    turn_score = 0
    while score + turn_score < 100 or user == hold:
        roll = roll_two_dice()
        if roll == 0:
            return 0
        score = roll + turn_score
    return turn_score

def final_result(uscore, cscore):
    uscore = 0
    cscore = 0
    print('Final results:{}'.format(uscore, cscore))
    if uscore >= 100:
        print('You win')
    else:
        print('Computer wins')

def main():
    c_score = 0
    u_score = 0
    if randint(0, 1) == 0:
        print('Computer starts')
        c_turn = computerTurn(c_score) + c_score
    while c_score < 100:
        print('Current scores')
        print_scores(u_score, c_score)
        u_turn = userTurn(u_score) + u_score
        if u_score >= 100:
            exit
        c_turn = computerTurn(c_score)
        print(c_turn)
        c_score = c_score + c_turn
    final_result(u_score, c_score)

main()

codepart1

codepart2

Body:
There are a few problems in your code as I have gone through your code extensively.

In the following code segment

def roll_two_dice():
    roll1 = randint(1, 6)
    roll2 = randint(1, 6)

if roll1 or roll2 == 1:
    return 0

elif roll1 and roll2 == 1:
    return 25
else:
    return roll1 + roll2

both the cases should contain ,

roll1 == 1

As the condition that you have written will not check that either roll1 =1 or roll2 =1.Actually it checks roll2 = 1 and roll1 anything other than 1. That could might result in making an infinite loop.

Secondly in the following 2 functions :-

computerTurn(score)

and

userTurn(Score)

You are not updating the value of the turn_score and returning that value that results to make the matter worse and the values c_score always renders to 0 and code will fall in infinite loop.

Also in function

def final_result(uscore, cscore):

You should not make the values of uscore and cscore = 0 as the condition for uscore >= 100 will never come


问:
Wordpress "admin-ajax.php" 404 Error
I created a website for a small bed and breakfast, but I found a problem, which I don’t understand if it is depended on WordPress or the server.

This website uses a pop-up animation to show the room description. The problem is that this popup has stopped working in the last week. From browser console, I noticed that the whole thing depends on a 404 error (admin-ajax.php not found). Here it is the detail:

```<code>jquery.js?ver=1.12.4:4 POST http://lettoacastello.net/wp-admin/admin-ajax.php 404 (Not Found)
send @ jquery.js?ver=1.12.4:4
ajax @ jquery.js?ver=1.12.4:4
(anonymous) @ script.js?ver=4.9.1:207
dispatch @ jquery.js?ver=1.12.4:3
r.handle @ jquery.js?ver=1.12.4:3
</code>```

To be able to solve the problem temporarily, I simply reinstall WordPress from dashboard. The problem doesn’t occur again for a whole day, all works fine! But the next day all starts over and the problem presents again (this cycle continues like this every day). For this reason I do not understand if it is a server problem or not.

A last very important thing. The popup has no problems if I am logged into WordPress admin panel (the browser recognizes “admin-ajax.php” file).

The code was not written by me (the developer says that the problem does not depend on him).

However, I believe this is the portion of code that controls room popup:

```<code>jQuery(document).ready(function($){

$('.special-room button.btn, .rooms-sec button.btn').live('click', function(e){

    e.preventDefault();

    $('#room.modal').html('');

    var thislink = this;

    var page_id = $(this).data('id');

    $.ajax({

        url: ajaxurl,

        method: 'POST',

        data: 'action=_sh_ajax_callback&subaction=sh_room_detail&post_id='+page_id,

        success: function(res){

            $('#room.modal').html(res);

        }

    });

});
</code>```

Please, can I ask you for help? Unfortunately I’m not very technical.

Thank you

答:
If everything works when you are logged in, this is not a direct problem of your code, but a security issue: of course you are not allowed to call any stuff in /wp-admin/ (which is the folder for backend actions) if not logged in, but your code does not handle that very well.

If you need to run this without a login, some more work has to be done in PHP code. But helping out is difficult if we cannot see that code

Title: Wordpress "admin-ajax.php" 404 Error

Body:
I created a website for a small bed and breakfast, but I found a problem, which I don’t understand if it is depended on WordPress or the server.

This website uses a pop-up animation to show the room description. The problem is that this popup has stopped working in the last week. From browser console, I noticed that the whole thing depends on a 404 error (admin-ajax.php not found). Here it is the detail:

jquery.js?ver=1.12.4:4 POST http://lettoacastello.net/wp-admin/admin-ajax.php 404 (Not Found)
send @ jquery.js?ver=1.12.4:4
ajax @ jquery.js?ver=1.12.4:4
(anonymous) @ script.js?ver=4.9.1:207
dispatch @ jquery.js?ver=1.12.4:3
r.handle @ jquery.js?ver=1.12.4:3

To be able to solve the problem temporarily, I simply reinstall WordPress from dashboard. The problem doesn’t occur again for a whole day, all works fine! But the next day all starts over and the problem presents again (this cycle continues like this every day). For this reason I do not understand if it is a server problem or not.

A last very important thing. The popup has no problems if I am logged into WordPress admin panel (the browser recognizes “admin-ajax.php” file).

The code was not written by me (the developer says that the problem does not depend on him).

However, I believe this is the portion of code that controls room popup:

jQuery(document).ready(function($){

$('.special-room button.btn, .rooms-sec button.btn').live('click', function(e){

    e.preventDefault();

    $('#room.modal').html('');

    var thislink = this;

    var page_id = $(this).data('id');

    $.ajax({

        url: ajaxurl,

        method: 'POST',

        data: 'action=_sh_ajax_callback&subaction=sh_room_detail&post_id='+page_id,

        success: function(res){

            $('#room.modal').html(res);

        }

    });

});

Please, can I ask you for help? Unfortunately I’m not very technical.

Thank you


问:
How to get database after mongoose connect?
I'm new to node and I've a remote database hosted on mlab and I want to connect to my database using mongoose.connect. I want to access that database to a specified route.

My code looks like :

```<code>var db = null;

db = mongoose.connect('mongodb://username:password@ds135186.mlab.com:12345/collection', function (err, database) {
  db = database
});
</code>```

and I've defined route as :

```<code>app.get('/fetchtest', function (req, res) {
  db.collection('okhitweets').find({}).limit(10).toArray(function (err, doc) {
    res.send(JSON.stringify(doc))
  })
});
</code>```

I'm getting can't find collection of undefined because db is not getting initialised. I tried finding online about how to access database but couldn't get much help. How can I access this database. My application is gonna be fairly small so I don't need to define routes in different file etc. and the database exists on mlab cloud.

答:
You can add following to server.js (i.e. main file) right after your database assignment (not in the scope where you assign, but after in a global one).

```<code>app.use( (req, res) => {
    req.db = db
})
</code>```

And then in your routes (or in main file) say

```<code>app.get("/chocolate", (req, res) => {
    const db = req.db
    db.collection("chocolates").find({})
         .toArray()
         .then(results => {
              res.status(200).send(results)
          })
})
</code>```

And you can also check the EventEmitter out, so that you start server only if you connect to the DB.

Let me know if this helps.

EDIT 1: If you are still "alive" (just joking), the snippet below may be more applicable than the one I share

```<code>app.all('*', (req, res, next) => {
    req.db = db;
    next();
});
</code>```

This also makes the db connection available throughout all routes.

Body:
I'm new to node and I've a remote database hosted on mlab and I want to connect to my database using mongoose.connect. I want to access that database to a specified route.

My code looks like :

var db = null;

db = mongoose.connect('mongodb://username:password@ds135186.mlab.com:12345/collection', function (err, database) {
  db = database
});

and I've defined route as :

app.get('/fetchtest', function (req, res) {
  db.collection('okhitweets').find({}).limit(10).toArray(function (err, doc) {
    res.send(JSON.stringify(doc))
  })
});

I'm getting can't find collection of undefined because db is not getting initialised. I tried finding online about how to access database but couldn't get much help. How can I access this database. My application is gonna be fairly small so I don't need to define routes in different file etc. and the database exists on mlab cloud.

Body:
You can add following to server.js (i.e. main file) right after your database assignment (not in the scope where you assign, but after in a global one).

app.use( (req, res) => {
    req.db = db
})

And then in your routes (or in main file) say

app.get("/chocolate", (req, res) => {
    const db = req.db
    db.collection("chocolates").find({})
         .toArray()
         .then(results => {
              res.status(200).send(results)
          })
})

And you can also check the EventEmitter out, so that you start server only if you connect to the DB.

Let me know if this helps.

EDIT 1: If you are still "alive" (just joking), the snippet below may be more applicable than the one I share

app.all('*', (req, res, next) => {
    req.db = db;
    next();
});

This also makes the db connection available throughout all routes.


问:
How to test a method with a parameter using RSpec?
I have the following RSpec:

```<code>describe Job do
  let(:job) { Job.new }

  describe 'run_job' do
    context 'success' do
        my_param = [{"job1" => "run"}, {"job2" => "run again"}]

        it 'should pass' do
            test_result = job.run_job(my_param)
            expect(test_result[0]["job1"]).to eq("run")
        end
     end
  end
end
</code>```

The method:

```<code>Class Job
  def run_job(my_param)
    # puts "#{my_param}"
    my_param.each do|f|
      # do something
    end
  end
end
</code>```

when I run the test I receive the following error

```<code> NoMethodError:
   undefined method `each' for nil:NilClass
</code>```

I print out my_param in the console and see same object that was passed to the test, [{"job1" => "run"}, {"job2" => "run again"}]. I have no idea why my_param is nil when calling .each. What did I do wrong? Any insight is appreciated.

答:
Better Specs recommends using let to assign variables:

```<code>describe Job do
  let(:job) { Job.new }

  describe 'run_job' do
    context 'success' do
      let(:my_param) { [{"job1" => "run"}, {"job2" => "run again"}] }

      it 'should pass' do
        test_result = job.run_job(my_param)
        expect(test_result[0]["job1"]).to eq("run")
      end
    end
  end
end
</code>```

Body:
I have the following RSpec:

describe Job do
  let(:job) { Job.new }

  describe 'run_job' do
    context 'success' do
        my_param = [{"job1" => "run"}, {"job2" => "run again"}]

        it 'should pass' do
            test_result = job.run_job(my_param)
            expect(test_result[0]["job1"]).to eq("run")
        end
     end
  end
end

The method:

Class Job
  def run_job(my_param)
    # puts "#{my_param}"
    my_param.each do|f|
      # do something
    end
  end
end

when I run the test I receive the following error

 NoMethodError:
   undefined method `each' for nil:NilClass

I print out my_param in the console and see same object that was passed to the test, [{"job1" => "run"}, {"job2" => "run again"}]. I have no idea why my_param is nil when calling .each. What did I do wrong? Any insight is appreciated.

Body:
Better Specs recommends using let to assign variables:

describe Job do
  let(:job) { Job.new }

  describe 'run_job' do
    context 'success' do
      let(:my_param) { [{"job1" => "run"}, {"job2" => "run again"}] }

      it 'should pass' do
        test_result = job.run_job(my_param)
        expect(test_result[0]["job1"]).to eq("run")
      end
    end
  end
end


问:
Is there a way that I can show comment parameters for a method in the Visual Studio IDE?
I have method:

```<code>    /// <summary>
    /// Updates Phrase SELECTED and either CATEGORY or CardChoice
    /// </summary>
    /// <param name="selected">True or False</param>
    public void UpdateSelected(bool selected)
    {
</code>```

The Summary information appears but not the comment I have about the parameter.

Is there some way I can also show the parameter and it's comment "True or False"?

答:
I use the VS extension called GhostDoc, it has more detailed xml comments than doing a triple slash. It fills out the description based on your method name, the param types and names, and the return type of your method.

Place your cursor anywhere on your method signature and hit Ctrl-Shift-D to include all the information you would need. You may need to change the description slightly but other than that, it is quite accurate.

You could also used the cref attribute in your <param> tags to reference the parameter type.

Body:
I have method:

    ///
    /// Updates Phrase SELECTED and either CATEGORY or CardChoice
    ///
    /// <param name="selected">True or False</param>
    public void UpdateSelected(bool selected)
    {

The Summary information appears but not the comment I have about the parameter.

Is there some way I can also show the parameter and it's comment "True or False"?


问:
SyntaxError: Invalid regular expression: nothing to repeat

When I use javascript write regex.

```<code>var regex = new RegExp("^[ ]{"+p1.length+"}\* ([^\n]*)", "gm")
</code>```

btw, i have alert(p1.length)

it's value 0.

i got error:

SyntaxError: Invalid regular expression: nothing to repeat

why?

this is same error

```<code>        var regex = new RegExp("^ {"+p1.length+"}\* ([^\n]*)", "gm")
</code>```

but this is right:

```<code>var r="^ {"+p1.length+"}[0-9]+\. ([^\n]*)"
            var regex = new RegExp(r, "gm")

</code>```

my question is why???

```<code>   var regex = new RegExp("^ {"+p1.length+"}[*] ([^\n]*)", "gm")        //this is ok
   var regex = new RegExp("^ {"+p1.length+"}\\* ([^\n]*)", "gm")        //and this is ok too.
</code>```

so when we use string build a regex, we need double\\ it is so trick.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions

{n}   Matches exactly n occurrences of the preceding expression. N must be a positive integer.
For example, /a{2}/ doesn't match the 'a' in "candy," but it does match all of the a's in "caandy," and the first two a's in "caaandy."

so my use {0} is right, no problem.
the problem is we need \\ in string to build regex, just like @Andreas  say, thanks.

答:
First things first, you didn't escape your regexes. You should probably do that...

Your 2 erroneous regexes have 2 separate errors.

Your first one is trying to quantify [ ]{0} with "0 or more times".

[ ]{0} repeated 100 or 1000 or however many times is still an empty string. This means that the regex will never stop matching if this were valid, because it would not have proceeded to match any more characters after [ ]{0}*.

Your second regex is trying to repeat ^ 0 times.

^ is not a character, it is just a zero-width position - the start of the string. The same goes with other "positions" like \b. There can't be 2 "starts" of a string next to each other.

I will now explain why the two regexes in your edit works.

[*] is a character class. In a character class, * loses its meaning of "zero or more times" and becomes literal. So you are just matching the character * after no spaces.

\\* unescaped is just \*. Here the * loses its meaning again since it is after a backslash.

Body:
When I use javascript write regex.

var regex = new RegExp("^[ ]{"+p1.length+"}\* ([^\n]*)", "gm")

btw, i have alert(p1.length)

it's value 0.

i got error:

SyntaxError: Invalid regular expression: nothing to repeat

why?

this is same error

        var regex = new RegExp("^ {"+p1.length+"}\* ([^\n]*)", "gm")

but this is right:

var r="^ {"+p1.length+"}[0-9]+\. ([^\n]*)"
            var regex = new RegExp(r, "gm")

my question is why???

   var regex = new RegExp("^ {"+p1.length+"}[*] ([^\n]*)", "gm")        //this is ok
   var regex = new RegExp("^ {"+p1.length+"}\\* ([^\n]*)", "gm")        //and this is ok too.

so when we use string build a regex, we need double\\ it is so trick.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions

{n}   Matches exactly n occurrences of the preceding expression. N must be a positive integer.
For example, /a{2}/ doesn't match the 'a' in "candy," but it does match all of the a's in "caandy," and the first two a's in "caaandy."

so my use {0} is right, no problem.
the problem is we need \\ in string to build regex, just like @Andreas  say, thanks.


问:
IE8 Height 100% Bug
Has anyone heard of a bug that occurs with IE8 when applying height as a percentage to the html and body using CSS? I'm seeing a white background when a tile pattern should be applied.</p>

```<code>html, body {
    margin: 0;
    padding: 0;
    height: 100%;
}

body {
    background-color: #666;
    background-image: url('../images/body/bg_pattern.gif');
}
</code>```

答:
To prevent the generated height:0 when you're floating the child elements, set

```<code>overflow:hidden;
position: relative;
</code>```

on the parent.

Title: IE8 Height 100% Bug

Body:
Has anyone heard of a bug that occurs with IE8 when applying height as a percentage to the html and body using CSS? I'm seeing a white background when a tile pattern should be applied.

html, body {
    margin: 0;
    padding: 0;
    height: 100%;
}

body {
    background-color: #666;
    background-image: url('../images/body/bg_pattern.gif');
}

Body:
To prevent the generated height:0 when you're floating the child elements, set

overflow:hidden;
position: relative;

on the parent.


问:
Get the word from stem (stemming)
I am using porter stemmer as follows to get the stem of my words.

```<code>from nltk.stem.porter import PorterStemmer
stemmer = PorterStemmer()
def stem_tokens(tokens, stemmer):
    stemmed = []
    for item in tokens:
        stemmed.append(stemmer.stem(item))
    return stemmed
</code>```

Now, I want to know the possibility of some word from the stem to make it readable. For example environ to environment or educ to education etc. Is it possible to do?

答:
What, so you want to take a stem and map it to a list of possible words in a dictionary that stem back to it?

This is difficult because the stemming process is lossy and because it's not a 1:1 transformation.

That said, in some cases like environ -> {environment, environments, environmental} and educ -> {educate, educational, education, educated, educating} you can get by with a trie structure where you do a prefix lookup. Things get more interesting for stems like happi which has to map back to happy

In the general case, you would have to start with a dictionary and then produce an inverted index by stemming each word and mapping the stem back to the source word in the index. Using the inverted index you can then look up matches given a stem.

Hope this helps..

Title: Get the word from stem (stemming)

Body:
I am using porter stemmer as follows to get the stem of my words.

from nltk.stem.porter import PorterStemmer
stemmer = PorterStemmer()
def stem_tokens(tokens, stemmer):
    stemmed = []
    for item in tokens:
        stemmed.append(stemmer.stem(item))
    return stemmed

Now, I want to know the possibility of some word from the stem to make it readable. For example environ to environment or educ to education etc. Is it possible to do?


问:
What are the differences between unit tests, integration tests, smoke tests, and regression tests?
What are unit tests, integration tests, smoke tests, and regression tests?  What are the differences between them and which tools can I use for each of them?

For example, I use JUnit and NUnit for unit testing and integration testing. Are there any tools for the last two, smoke testing or regression testing?

答:
Smoke tests have been explained here already and is simple. Regression tests come under integration tests.

Automated tests can be divided into just two.

Unit tests and integration tests (this is all that matters)

I would call use the phrase "long test" (LT) for all tests like integration tests, functional tests, regression tests, UI tests, etc. And unit tests as "short test".

An LT example could be, automatically loading a web page, logging in to the account and buying a book. If the test passes it is more likely to run on live site the same way(hence the 'better sleep' reference). Long = distance between web page (start) and database (end).

And this is a great article discussing the benefits of integration testing (long test) over unit testing.


问:
how to properly install GIT to WIN7 command prompt
I made this because Git's official instruction is incomplete.

go to https://git-scm.com/download/win

https://git-scm.com/book/en/v2/Getting-Started-Installing-Git to ge the install package and install it.

Now you should have github UI ready for you but if are trying to run "git" in CMD, then follow the rest:

Search where git is installed but some people have it in their C:\Users\xxxxxx\AppData\Local\GitHubDesktop\app-1.0.10\resources\app\git\mingw64\bin
therefore they can't find it since AppData folder is hidden. To un-hide:

Select the Start button, then select Control Panel > Appearance and Personalization.

Select Folder Options, then select the View tab.

Under Advanced settings, select Show hidden files, folders, and drives, and then select OK.

Once copy the full path and add it to the "PATH" environmental variable. Here are the steps:

Select Start, select Control Panel. double click System, and select the Advanced tab.

Click Environment Variables. ...

Under the System Variable (or New System Variable) window, append the full path to the end of the variable "Path".

Now you should be able to run "git --version".  or post your answers below.

答:
With the latest Git for Windows release, all you need to do is to uncompress the archive PortableGit-2.15.1.2-64-bit.7z.exe anywhere you want and add it to your PATH (as I do here), then launch GitHub Desktop.

```<code>set PATH=C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\
set GH=C:\path\to\git
set PATH=%GH%\bin;%GH%\usr\bin;%GH%\mingw64\bin;%PATH%
</code>```

Then you can run any Git command you want directly from a CMD shell session, or even type 'bash' and use a bash shell session.

Body:
With the latest Git for Windows release, all you need to do is to uncompress the archive PortableGit-2.15.1.2-64-bit.7z.exe anywhere you want and add it to your PATH (as I do here), then launch GitHub Desktop.

set PATH=C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\
set GH=C:\path\to\git
set PATH=%GH%\bin;%GH%\usr\bin;%GH%\mingw64\bin;%PATH%

Then you can run any Git command you want directly from a CMD shell session, or even type 'bash' and use a bash shell session.