问:
next(err) not stopping execution
I am create an authentication route for my backend API:

```<code>const express = require("express");
const jwt = require("jsonwebtoken");

const User = require("../models/User");

let router = express.Router();

router.post("/", (req, res, next) => {
  const { username, phone, password } = req.body;
  if (!(username || phone) || !password) {
    let err = new Error("invalid parameters");
    err.status = 400;
    next(err);
  }
  // XXX: Perhaps a better way to do this
  let params = {};
  if (username) {
    params.username = username;
  }
  if (phone) {
    params.phone = phone;
  }
  User.findOne(params)
    .then(user => {
      if (!user) {
        let err = new Error("invalid credentials");
        err.status = 401;
        next(err);
      }
      user.checkPassword(password, (err, isMatch) => {
        if (err) {
          next(err);
        }

        if (!isMatch) {
          console.log("we get here");
          let err = new Error("invalid credentials");
          err.status = 401;
          next(err);
        }
        console.log("we also get here");
        res.send({
          token: jwt.sign(
            {
              _id: user._id,
              username: user.username,
              phone: user.phone
            },
            req.app.get("jwtSecret")
          )
        });
      });
    })
    .catch(err => {
      next(err);
    });
});

module.exports = router;
</code>```

When passing in a valid username but invalid password I get the output:

```<code>we got here
we also got here
Error: Can't set headers after they are sent.
    at ...
</code>```

The error I presume is because next(err) is not stopping the execution flow and therefore a response is getting sent twice.

Why is next(err) not stopping the execution flow?

答:
You need to return inside your function after you call next(err).

next(err) stops future routing, but it doesn't stop execution within your own function.  So, you need to either be using if/else or return when you're done to stop other parts of your own function from executing.

Personally, I would uses promises for all my asnyc operations and not use a mix and match of promises and callbacks.  Then, you can just reject and funnel everything to just your one .catch() at the end.

But, if you're going to stick with your mixture of promises and callbacks, you can add return statements like this:

```<code>router.post("/", (req, res, next) => {
    const { username, phone, password } = req.body;
    if (!(username || phone) || !password) {
        let err = new Error("invalid parameters");
        err.status = 400;
        next(err);
        return;
    }
    // XXX: Perhaps a better way to do this
    let params = {};
    if (username) {
        params.username = username;
    }
    if (phone) {
        params.phone = phone;
    }
    User.findOne(params).then(user => {
        if (!user) {
            let err = new Error("invalid credentials");
            err.status = 401;
            throw err;
        }
        user.checkPassword(password, (err, isMatch) => {
            if (err) {
                next(err);
                return;
            }

            if (!isMatch) {
                console.log("we get here");
                let err = new Error("invalid credentials");
                err.status = 401;
                next(err);
                return;
            }
            console.log("we also get here");
            let token = jwt.sign({_id: user._id, username: user.username, phone: user.phone}, req.app.get("jwtSecret"))
            res.send({token});
        });
    }).catch(err => {
        next(err);
    });
});
</code>```

If you change your implementation of user.checkPassword() to return a promise instead of using a callback, then you can do it this way without mixing callbacks and promises:

```<code>router.post("/", (req, res, next) => {
    function throwErr(msg, status) {
        let err = new Error(msg);
        err.status = status;
        throw err;
    }

    Promise.resolve().then(() => {
        const { username, phone, password } = req.body;
        if (!(username || phone) || !password) {
            throwErr("invalid parameters", 400);
        }
        let params = {};
        if (username) {
            params.username = username;
        }
        if (phone) {
            params.phone = phone;
        }
        return User.findOne(params).then(user => {
            if (!user) {
                throwErr("invalid credentials", 401);
            }
            return user.checkPassword(password).then(isMatch) => {
                if (!isMatch) {
                    throwErr("invalid credentials", 401);
                }
                let token = jwt.sign({_id: user._id, username: user.username, phone: user.phone}, req.app.get("jwtSecret"))
                res.send({token});
            });
        });
    }).catch(err => {
        next(err);
    });
});
</code>```

The throwErr() calls will all end up in the .catch().

Title: next(err) not stopping execution

Body:
I am create an authentication route for my backend API:

const express = require("express");
const jwt = require("jsonwebtoken");

const User = require("../models/User");

let router = express.Router();

router.post("/", (req, res, next) => {
  const { username, phone, password } = req.body;
  if (!(username || phone) || !password) {
    let err = new Error("invalid parameters");
    err.status = 400;
    next(err);
  }
  // XXX: Perhaps a better way to do this
  let params = {};
  if (username) {
    params.username = username;
  }
  if (phone) {
    params.phone = phone;
  }
  User.findOne(params)
    .then(user => {
      if (!user) {
        let err = new Error("invalid credentials");
        err.status = 401;
        next(err);
      }
      user.checkPassword(password, (err, isMatch) => {
        if (err) {
          next(err);
        }

        if (!isMatch) {
          console.log("we get here");
          let err = new Error("invalid credentials");
          err.status = 401;
          next(err);
        }
        console.log("we also get here");
        res.send({
          token: jwt.sign(
            {
              _id: user._id,
              username: user.username,
              phone: user.phone
            },
            req.app.get("jwtSecret")
          )
        });
      });
    })
    .catch(err => {
      next(err);
    });
});

module.exports = router;

When passing in a valid username but invalid password I get the output:

we got here
we also got here
Error: Can't set headers after they are sent.
    at ...

The error I presume is because next(err) is not stopping the execution flow and therefore a response is getting sent twice.

Why is next(err) not stopping the execution flow?

Body:
You need to return inside your function after you call next(err).

next(err) stops future routing, but it doesn't stop execution within your own function.  So, you need to either be using if/else or return when you're done to stop other parts of your own function from executing.

Personally, I would uses promises for all my asnyc operations and not use a mix and match of promises and callbacks.  Then, you can just reject and funnel everything to just your one .catch() at the end.

But, if you're going to stick with your mixture of promises and callbacks, you can add return statements like this:

router.post("/", (req, res, next) => {
    const { username, phone, password } = req.body;
    if (!(username || phone) || !password) {
        let err = new Error("invalid parameters");
        err.status = 400;
        next(err);
        return;
    }
    // XXX: Perhaps a better way to do this
    let params = {};
    if (username) {
        params.username = username;
    }
    if (phone) {
        params.phone = phone;
    }
    User.findOne(params).then(user => {
        if (!user) {
            let err = new Error("invalid credentials");
            err.status = 401;
            throw err;
        }
        user.checkPassword(password, (err, isMatch) => {
            if (err) {
                next(err);
                return;
            }

            if (!isMatch) {
                console.log("we get here");
                let err = new Error("invalid credentials");
                err.status = 401;
                next(err);
                return;
            }
            console.log("we also get here");
            let token = jwt.sign({_id: user._id, username: user.username, phone: user.phone}, req.app.get("jwtSecret"))
            res.send({token});
        });
    }).catch(err => {
        next(err);
    });
});

If you change your implementation of user.checkPassword() to return a promise instead of using a callback, then you can do it this way without mixing callbacks and promises:

router.post("/", (req, res, next) => {
    function throwErr(msg, status) {
        let err = new Error(msg);
        err.status = status;
        throw err;
    }

    Promise.resolve().then(() => {
        const { username, phone, password } = req.body;
        if (!(username || phone) || !password) {
            throwErr("invalid parameters", 400);
        }
        let params = {};
        if (username) {
            params.username = username;
        }
        if (phone) {
            params.phone = phone;
        }
        return User.findOne(params).then(user => {
            if (!user) {
                throwErr("invalid credentials", 401);
            }
            return user.checkPassword(password).then(isMatch) => {
                if (!isMatch) {
                    throwErr("invalid credentials", 401);
                }
                let token = jwt.sign({_id: user._id, username: user.username, phone: user.phone}, req.app.get("jwtSecret"))
                res.send({token});
            });
        });
    }).catch(err => {
        next(err);
    });
});

The throwErr() calls will all end up in the .catch().


来源: stackexchange

问:
ASP.NET Core Test xUnit Controller
this test always return null, and test always fail...but when i run the projet all works fine and return data normally, this project using RavenDB

Controller

```<code>[Route("api/[controller]")]
public class CategoryController : Controller
{
    private readonly AppDbContext _context = new AppDbContext();

    // GET: api/category
    [HttpGet("{id}")]
    public async Task<JsonResult> Get(string id)
    {
        using (IAsyncDocumentSession session = _context.SessionAsync){
            var result = await session.LoadAsync<Category>(id);
            return Json(result);
        }
    }
}
</code>```

and using xUnit to testing

```<code> [Fact]
public async Task GetShouldReturnCategory()
{
    // Arrange
    var _categoryController = Substitute.For<CategoryController>();
    var category = CreateCategory();

    // Act
    var result = await _categoryController.Get(category.Result.Id);

    //Asserts here
}
</code>```

答:
Base on your question, system under test (SUT) is CategoryController. So, it doesn't make sense to mock CategoryController; instead, you want to mock AppDbContext.

If you want to unit test a controller, you should use ASP.NET Core's Dependency Inject, and inject its dependencies via constructor injection. In other words, you should not use new.

Normally, we inject interface instead of concrete class, so that we can easily mock it.

Your code is missing too many pieces, so I could only give you a directly. You want more detail you can look at this sample project at GitHub which uses NSubstitute and XUnit.

ContentLicense: CC BY-SA 3.0

Title: ASP.NET Core Test xUnit Controller

Body:
this test always return null, and test always fail...but when i run the projet all works fine and return data normally, this project using RavenDB

Controller

[Route("api/[controller]")]
public class CategoryController : Controller
{
    private readonly AppDbContext _context = new AppDbContext();

    // GET: api/category
    [HttpGet("{id}")]
    public async Task<JsonResult> Get(string id)
    {
        using (IAsyncDocumentSession session = _context.SessionAsync){
            var result = await session.LoadAsync<Category>(id);
            return Json(result);
        }
    }
}

and using xUnit to testing

 [Fact]
public async Task GetShouldReturnCategory()
{
    // Arrange
    var _categoryController = Substitute.For<CategoryController>();
    var category = CreateCategory();

    // Act
    var result = await _categoryController.Get(category.Result.Id);

    //Asserts here
}


问:
When making a list from a file, if the file contains more than one value it does not recognise any of the values
I made a program that is supposed to take a list of usernames and passwords from a file. It works perfectly if the files only have one username and password but as soon as I include more than one of them, it does not recognise them at all. Here is the code below.

```<code>import easygui as e
import os
upper = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]
lower = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]
numbers = ["1","2","3","4","5","6","7","8","9","0"]
loginsystem = True
while loginsystem == True:
    users = []
    file = open("users.secure","r")
    reading = True
    while reading == True:
         tempuser = file.readline()
         if tempuser == "":
            reading = False
        else:
            users.append(tempuser)
    file.close()
    passwords = []
    file = open("passwords.secure","r")
    reading = True
    while reading == True:
        temppassword = file.readline()
        if temppassword == "":
            reading = False
        else:
            passwords.append(temppassword)
    file.close()
    loginmsg = "Enter your username and password"
    logintitle = "Login"
    loginfieldnames = ["Username","Password"]
    loginfieldvalues = []
    login = True
    while login == True:
        loginfieldvalues =
e.multpasswordbox(loginmsg,logintitle,loginfieldnames)
        while 1:
            if loginfieldvalues == None: break
            loginerrmsg = ""
            for i in range(len(loginfieldnames)):
              if loginfieldvalues[i].strip() == "":
                loginerrmsg = loginerrmsg + ('"%s" is a required field.\n\n' %     loginfieldnames[i])
            if loginerrmsg == "": break
            loginfieldvalues = e.multpasswordbox(loginerrmsg, logintitle, loginfieldnames, loginfieldvalues)
        inputuser = loginfieldvalues[0]
        inputpassword = loginfieldvalues[1]
        if inputuser not in users:
            e.msgbox("Unknown username.",title="Login",ok_button="Try Again")
        else:
            placement = users.index(inputuser)
            if inputpassword != passwords[placement]:
                 e.msgbox("Invalid password.",title="Login",ok_button="Try Again")
             else: login = False
    e.msgbox("Welcome, " + inputuser,title="Login System",ok_button="Continue")
    basicoptions = ["Logout","Quit"]
    running = True
    while running == True:
        choice = e.buttonbox("What would you like to do?",title="Login System",choices=basicoptions)
        if choice == "Quit":
            os._exit(0)
        else:
            running = False
</code>```

The files just contain the word "admin" and when I add another value, I add it onto the next line using "\nadmin2" when writing to the file.

答:
io.readline() will return the newline. That means if you have only one entry, you're likely getting admin, but with more lines, you're getting admin\n.

Instead you can do:

```<code>tempuser = file.readline().strip()
</code>```

Unrelated to the question, but you can cleanup the code a lot. For example for reading files:

```<code>def read_file(path):
    with open(path, 'r') as f:
        return [line.strip() for line in f]

users = read_file('users.secure')
passwords = read_file('passwords.secure')
</code>```

Body:
I made a program that is supposed to take a list of usernames and passwords from a file. It works perfectly if the files only have one username and password but as soon as I include more than one of them, it does not recognise them at all. Here is the code below.

import easygui as e
import os
upper = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]
lower = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]
numbers = ["1","2","3","4","5","6","7","8","9","0"]
loginsystem = True
while loginsystem == True:
    users = []
    file = open("users.secure","r")
    reading = True
    while reading == True:
         tempuser = file.readline()
         if tempuser == "":
            reading = False
        else:
            users.append(tempuser)
    file.close()
    passwords = []
    file = open("passwords.secure","r")
    reading = True
    while reading == True:
        temppassword = file.readline()
        if temppassword == "":
            reading = False
        else:
            passwords.append(temppassword)
    file.close()
    loginmsg = "Enter your username and password"
    logintitle = "Login"
    loginfieldnames = ["Username","Password"]
    loginfieldvalues = []
    login = True
    while login == True:
        loginfieldvalues =
e.multpasswordbox(loginmsg,logintitle,loginfieldnames)
        while 1:
            if loginfieldvalues == None: break
            loginerrmsg = ""
            for i in range(len(loginfieldnames)):
              if loginfieldvalues[i].strip() == "":
                loginerrmsg = loginerrmsg + ('"%s" is a required field.\n\n' %     loginfieldnames[i])
            if loginerrmsg == "": break
            loginfieldvalues = e.multpasswordbox(loginerrmsg, logintitle, loginfieldnames, loginfieldvalues)
        inputuser = loginfieldvalues[0]
        inputpassword = loginfieldvalues[1]
        if inputuser not in users:
            e.msgbox("Unknown username.",title="Login",ok_button="Try Again")
        else:
            placement = users.index(inputuser)
            if inputpassword != passwords[placement]:
                 e.msgbox("Invalid password.",title="Login",ok_button="Try Again")
             else: login = False
    e.msgbox("Welcome, " + inputuser,title="Login System",ok_button="Continue")
    basicoptions = ["Logout","Quit"]
    running = True
    while running == True:
        choice = e.buttonbox("What would you like to do?",title="Login System",choices=basicoptions)
        if choice == "Quit":
            os._exit(0)
        else:
            running = False

The files just contain the word "admin" and when I add another value, I add it onto the next line using "\nadmin2" when writing to the file.

Body:
io.readline() will return the newline. That means if you have only one entry, you're likely getting admin, but with more lines, you're getting admin\n.

Instead you can do:

tempuser = file.readline().strip()

Unrelated to the question, but you can cleanup the code a lot. For example for reading files:

def read_file(path):
    with open(path, 'r') as f:
        return [line.strip() for line in f]

users = read_file('users.secure')
passwords = read_file('passwords.secure')


问:
How to identify a character within a word and substitute that letter into another string - Python
For my hangman project, in the situation that the person does guess a letter correctly, I want to be able to substitute that letter in for a '_' space.

```<code>word = input('Please enter a word for your opponent:')

letter = input('Enter a letter to try and guess the word:')

print('_ '*len(word))

if 'a' in word and letter:
    print('_ '*len(word) with 'a' in word)
</code>```

For example if the word entered was 'matt,' the output would be '_a__'

答:
Here's another non-regex solution. Creates a set of indicies where the given character was found. That is then used to index characters that can be replaced in the list of underscores that's passed in (one approach to update the passed sequence reference in your main game loop).

```<code>def subsitute_character(character, target_word, sequence):
    indicies = {index for index, element in enumerate(target_word) if element == character}
    return ''.join(target_word[index] if index in indicies else element
        for index, element in enumerate(sequence))
</code>```

Sample Output:

```<code>>>> s = "matt"
>>> l = ["_" for _ in range(len(s))]
>>> print subsitute_character("t", s, l)
__tt
</code>```

Body:
For my hangman project, in the situation that the person does guess a letter correctly, I want to be able to substitute that letter in for a '_' space.

word = input('Please enter a word for your opponent:')

letter = input('Enter a letter to try and guess the word:')

print('_ '*len(word))

if 'a' in word and letter:
    print('_ '*len(word) with 'a' in word)

For example if the word entered was 'matt,' the output would be '_a__'

Body:
Here's another non-regex solution. Creates a set of indicies where the given character was found. That is then used to index characters that can be replaced in the list of underscores that's passed in (one approach to update the passed sequence reference in your main game loop).

def subsitute_character(character, target_word, sequence):
    indicies = {index for index, element in enumerate(target_word) if element == character}
    return ''.join(target_word[index] if index in indicies else element
        for index, element in enumerate(sequence))

Sample Output:

>>> s = "matt"
>>> l = ["_" for _ in range(len(s))]
>>> print subsitute_character("t", s, l)
__tt


问:
ReactJS: Uncaught ReferenceError: [function] not defined, July 2017
Attempting to turn a JSON file into an array, then randomly selecting 5 items from it.

I think the issue is my render/return statement at the bottom of ImageContainer.js, but I'm a ReactJS n00b, so it could be anything.

Any help or advice is greatly appreciated.

Console Error

```<code>compiled.js:31562 Uncaught ReferenceError: selectImages is not defined
  at ImageContainer.render (compiled.js:31562)
  at compiled.js:20195
  at measureLifeCyclePerf (compiled.js:19475)
  at ReactCompositeComponentWrapper._renderValidatedComponentWithoutOwnerOrContext (compiled.js:20194)
  at ReactCompositeComponentWrapper._renderValidatedComponent (compiled.js:20221)
  at ReactCompositeComponentWrapper.performInitialMount (compiled.js:19761)
  at ReactCompositeComponentWrapper.mountComponent (compiled.js:19657)
  at Object.mountComponent (compiled.js:4009)
  at ReactDOMComponent.mountChildren (compiled.js:24150)
  at ReactDOMComponent._createInitialChildren (compiled.js:21126)
</code>```

ImageContainer.js - pulls img info from a .JSON file, randomly selects 5 to render

```<code>import React from 'react';
import ReactDOM from 'react-dom';
import { Image } from './Image';

export class ImageContainer extends React.Component {
  constructor(props) {
    super(props);

    this.numImages = 5;

    this.state = {
      data: []
    };
  }

  componentDidMount() {
    $.ajax({
      url: '../app/data/namegame-data.json',
      dataType: 'json',
      success: function(data) {
        this.setState({data: data});
      }.bind(this),
      error: function(xhr, status, err) {
        console.error('#GET Error', status, err.toString());
      }.bind(this)
    });
  }

  shuffleArray(array) {
    let i = array.length - 1;
    for (; i > 0; i--) {
      const j = Math.floor(Math.random() * (i + 1));
      const temp = array[i];
      array[i] = array[j];
      array[j] = temp;
    }
    return array;
  }

  selectImages({ data }) {
    const shuffledImages = shuffleArray(images);
    return (
      shuffledImages.map((data, idx) => {
        for (let i = 0; i < this.numImages; i++) {
            if (this.state.data.length > 0) {
                return <Image key={idx} name={data.name} src={data.src} />;
            }
        }
      })
    );
  }

  render() {
    return {selectImages};
  }
}
</code>```

Image.js - just the image HTML

```<code>import React from 'react';

export class Image extends React.Component {
    render() {
        const key = this.props.id;
        const name = this.props.name;
        const src = this.props.src;
        return (
            <picture>
                <img id="pic-template" className="pic" src="{src}" name="{name}" key="id" />
            </picture>
        );
    }
}
</code>```

[Main].js - most of the HTML is here, just including the import bits

```<code>import React from 'react';
import ReactDOM from 'react-dom';
import { ImageContainer } from './ImageContainer';

export default class NameGame extends React.Component {
  render () {
    return (
      ...
      <div id="images-wrap">
          <ImageContainer />
      </div>
      ...
    );
  }
}
</code>```

Dependencies

```<code>{
  ...
  "dependencies": {
    "json-loader": "^0.5.4",
    "react": "^15.6.1",
    "react-dom": "^15.6.1"
  },
  "devDependencies": {
    "css-loader": "^0.28.4",
    "extract-text-webpack-plugin": "^2.1.2",
    "node-sass": "^4.5.3",
    "sass-loader": "^6.0.6",
    "style-loader": "^0.18.2",
    "webpack": "^2.2.0",
    "webpack-dev-server": "^2.5.0"
  }
}
</code>```

答:
i quickly changed ur code at 00:45 :D, but try something like this, explenation in my other answer. gl!</p>

```<code>import React from 'react';
import ReactDOM from 'react-dom';
import { Image } from './Image';

export class ImageContainer extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
          data: [],
          numImages: 5
        };
    }

    componentWillMount() {
      $.ajax({
          url: './app/data/namegame-data.json',
          dataType: 'json',
          type: 'get',
          success: function(data) {
            this.setState({data: JSON.parse(data) });
          }.bind(this),
          error: function(xhr, status, err) {
            console.error('#GET Error', status, err.toString());
          }.bind(this)
        });
    }

    randomPickFromArray() {
      // * as asked: " Attempting to turn a JSON file into an array, then randomly selecting 5 items from it. "

      // lets not shuffle, and just random pick 5 items from array,
      const { data, numImages } = this.state;
      const arr = [];
      for (let i = 0; i < numImages; i++) {
        arr.push(data[Math.floor(Math.random() * data.length)]);
      }
      return arr;
    }

    selectImages() {
      const shuffledImages = this.randomPickFromArray();
      return shuffledImages.map((item, idx) => <Image key={idx} name={item.name} src={item.src} />);
    }

    render() {
        return (
            <div>
                {this.selectImages()};
            </div>
        )
    }
}
</code>```

Body:
Attempting to turn a JSON file into an array, then randomly selecting 5 items from it.

I think the issue is my render/return statement at the bottom of ImageContainer.js, but I'm a ReactJS n00b, so it could be anything.

Any help or advice is greatly appreciated.

Console Error

compiled.js:31562 Uncaught ReferenceError: selectImages is not defined
  at ImageContainer.render (compiled.js:31562)
  at compiled.js:20195
  at measureLifeCyclePerf (compiled.js:19475)
  at ReactCompositeComponentWrapper._renderValidatedComponentWithoutOwnerOrContext (compiled.js:20194)
  at ReactCompositeComponentWrapper._renderValidatedComponent (compiled.js:20221)
  at ReactCompositeComponentWrapper.performInitialMount (compiled.js:19761)
  at ReactCompositeComponentWrapper.mountComponent (compiled.js:19657)
  at Object.mountComponent (compiled.js:4009)
  at ReactDOMComponent.mountChildren (compiled.js:24150)
  at ReactDOMComponent._createInitialChildren (compiled.js:21126)

ImageContainer.js - pulls img info from a .JSON file, randomly selects 5 to render

import React from 'react';
import ReactDOM from 'react-dom';
import { Image } from './Image';

export class ImageContainer extends React.Component {
  constructor(props) {
    super(props);

    this.numImages = 5;

    this.state = {
      data: []
    };
  }

  componentDidMount() {
    $.ajax({
      url: '../app/data/namegame-data.json',
      dataType: 'json',
      success: function(data) {
        this.setState({data: data});
      }.bind(this),
      error: function(xhr, status, err) {
        console.error('#GET Error', status, err.toString());
      }.bind(this)
    });
  }

  shuffleArray(array) {
    let i = array.length - 1;
    for (; i > 0; i--) {
      const j = Math.floor(Math.random() * (i + 1));
      const temp = array[i];
      array[i] = array[j];
      array[j] = temp;
    }
    return array;
  }

  selectImages({ data }) {
    const shuffledImages = shuffleArray(images);
    return (
      shuffledImages.map((data, idx) => {
        for (let i = 0; i < this.numImages; i++) {
            if (this.state.data.length > 0) {
                return <Image key={idx} name={data.name} src={data.src} />;
            }
        }
      })
    );
  }

  render() {
    return {selectImages};
  }
}

Image.js - just the image HTML

import React from 'react';

export class Image extends React.Component {
    render() {
        const key = this.props.id;
        const name = this.props.name;
        const src = this.props.src;
        return (
            <picture>

            </picture>
        );
    }
}

[Main].js - most of the HTML is here, just including the import bits

import React from 'react';
import ReactDOM from 'react-dom';
import { ImageContainer } from './ImageContainer';

export default class NameGame extends React.Component {
  render () {
    return (
      ...

          <ImageContainer />

      ...
    );
  }
}

Dependencies

{
  ...
  "dependencies": {
    "json-loader": "^0.5.4",
    "react": "^15.6.1",
    "react-dom": "^15.6.1"
  },
  "devDependencies": {
    "css-loader": "^0.28.4",
    "extract-text-webpack-plugin": "^2.1.2",
    "node-sass": "^4.5.3",
    "sass-loader": "^6.0.6",
    "style-loader": "^0.18.2",
    "webpack": "^2.2.0",
    "webpack-dev-server": "^2.5.0"
  }
}

Body:
i quickly changed ur code at 00:45 :D, but try something like this, explenation in my other answer. gl!

import React from 'react';
import ReactDOM from 'react-dom';
import { Image } from './Image';

export class ImageContainer extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
          data: [],
          numImages: 5
        };
    }

    componentWillMount() {
      $.ajax({
          url: './app/data/namegame-data.json',
          dataType: 'json',
          type: 'get',
          success: function(data) {
            this.setState({data: JSON.parse(data) });
          }.bind(this),
          error: function(xhr, status, err) {
            console.error('#GET Error', status, err.toString());
          }.bind(this)
        });
    }

    randomPickFromArray() {
      // * as asked: " Attempting to turn a JSON file into an array, then randomly selecting 5 items from it. "

      // lets not shuffle, and just random pick 5 items from array,
      const { data, numImages } = this.state;
      const arr = [];
      for (let i = 0; i < numImages; i++) {
        arr.push(data[Math.floor(Math.random() * data.length)]);
      }
      return arr;
    }

    selectImages() {
      const shuffledImages = this.randomPickFromArray();
      return shuffledImages.map((item, idx) => <Image key={idx} name={item.name} src={item.src} />);
    }

    render() {
        return (
            <div>
                {this.selectImages()};
            </div>
        )
    }
}


问:
How to show pagination counter for array for pagination in views
```<code>used_cars = UsedCar.paginate(:page => params[:page], :per_page => 5)
used_cars_hash = used_cars.as_json
</code>```

I show all used_cars_hash in my view. But when I add <% will_paginate @user_cars_hash %>
it gives an error

How to show pagination counter on array?

Because when we add <% will_paginate @user_cars_hash %>

it gives an error

undefined method total_pages' for #<Array:0x007f1edef43c48>

答:
will_paginate does not work with the plain Ruby array you get by calling used_cars.as_json. Try passing used_cars to it:

```<code># no need to turn it into a plain array
@used_cars = UsedCar.paginate(:page => params[:page], :per_page => 5)

# in the view:
<%= will_paginate @used_cars %>
</code>```

If you absolutely have to use the array for pagination, you can do this:

```<code>require 'will_paginate/array'

# you can call `paginate` on plain arrays
used_cars = UsedCar.all
@used_cars_array = used_cars.as_json.paginate(:page => params[:page], :per_page => 5)

# in the view:
<%= will_paginate @used_cars_array %>
</code>```

Body:
used_cars = UsedCar.paginate(:page => params[:page], :per_page => 5)
used_cars_hash = used_cars.as_json

I show all used_cars_hash in my view. But when I add <% will_paginate @user_cars_hash %>
it gives an error

How to show pagination counter on array?

Because when we add <% will_paginate @user_cars_hash %>

it gives an error

undefined method total_pages' for #<Array:0x007f1edef43c48>

Body:
will_paginate does not work with the plain Ruby array you get by calling used_cars.as_json. Try passing used_cars to it:

# no need to turn it into a plain array
@used_cars = UsedCar.paginate(:page => params[:page], :per_page => 5)

# in the view:
<%= will_paginate @used_cars %>

If you absolutely have to use the array for pagination, you can do this:

require 'will_paginate/array'

# you can call `paginate` on plain arrays
used_cars = UsedCar.all
@used_cars_array = used_cars.as_json.paginate(:page => params[:page], :per_page => 5)

# in the view:
<%= will_paginate @used_cars_array %>


问:
Execute a method of a different namspace by dynamic code in C# winforms
I am implementing a dynamic code execution in C# which allows users to write their own c# for that particular application.

I am using C# code compiler for executing the dynamic codes. The C# compiler reads the code file and construct the code in new namespace (a complete new code), compiles and runs it. In other view the base application host all these.

I have few methods that are present in host application that I want to be executed by the dynamic code. Is there any way by which the method of other namespace or application can be executed?

答:
Could you force the author of your script to implement an interface, or you could even wrap their code with your own implementation..

Something like

```<code>public interface IMyApplication
{
      void DoSomethingInMyMainApp();
}
public interface IScriptKiddie
{
      void Init(IMyApplication app);
}
</code>```

Then your l33t scripters can write

```<code>public class MyScript : IScriptKiddie //< you could emit this yourself
{

     public void Init(IMyApplication app) //<could emit this yourself if scripter knows app keyword
     {
          app.DoSomethingInMyMainApp();
     }
}
</code>```

and in your app you can provide a concrete implementation of IMyApplication to pass into the class when you have compiled, constructed the class then pass into Init method.

ContentLicense: CC BY-SA 2.5

Body:
Could you force the author of your script to implement an interface, or you could even wrap their code with your own implementation..

Something like

public interface IMyApplication
{
      void DoSomethingInMyMainApp();
}
public interface IScriptKiddie
{
      void Init(IMyApplication app);
}

Then your l33t scripters can write

public class MyScript : IScriptKiddie //< you could emit this yourself
{

     public void Init(IMyApplication app) //<could emit this yourself if scripter knows app keyword
     {
          app.DoSomethingInMyMainApp();
     }
}

and in your app you can provide a concrete implementation of IMyApplication to pass into the class when you have compiled, constructed the class then pass into Init method.


问:
Do the amphtml and canonical urls need to match?
First off I apologize if this has already been asked, I attempted to search and haven't seen anything directly asking and/or answering this question.

Does the amphtml and the canonical url of content "have" to match?

Ex:

```<code><link rel="amphtml" href="http://self.com/self.html" />

<link rel="canonical" href="http://someotherwebsite.com" />
</code>```

From reading and researching, the only thing that appears to matter is that the content needs to match.

Per the docs and researching errors;

The content of the AMP page and its canonical web page should be essentially the same. The text need not be identical, but the topic should be the same, and users should be able to accomplish the same tasks on both the AMP and the canonical page.

If the urls do not need to match, does having different urls affect google rankings and/or any ad operations?

答: The canonical and the AMP are permitted to be on different domains or subdomains. You can always prove that the same entity owns both pages because the canonical points to the AMP and the AMP points to the canonical.</p>

Body:
First off I apologize if this has already been asked, I attempted to search and haven't seen anything directly asking and/or answering this question.

Does the amphtml and the canonical url of content "have" to match?

Ex:

<link rel="amphtml" href="http://self.com/self.html" />

<link rel="canonical" href="http://someotherwebsite.com" />

From reading and researching, the only thing that appears to matter is that the content needs to match.

Per the docs and researching errors;

The content of the AMP page and its canonical web page should be essentially the same. The text need not be identical, but the topic should be the same, and users should be able to accomplish the same tasks on both the AMP and the canonical page.

If the urls do not need to match, does having different urls affect google rankings and/or any ad operations?


问:
make an array out of JSON code nested inside two keys
I want to a javascript make an array out of this JSON code

```<code>{

 Technical Analysis: RSI:{

 2017-07-07 16:00: {RSI: "50.2925"},

 2017-07-07 15:45: {RSI: "54.1255"},

 2017-07-07 15:30: {RSI: "55.0698"},

 2017-07-07 15:15: {RSI: "52.0587"},

 2017-07-07 15:00: {RSI: "55.4002"},

 2017-07-07 14:45: {RSI: "57.9093"}

}
}
</code>```

I know how to do it generally, I mean it’s not rocket science, you just have to parse it and use a for in loop. But the thing is that the content I want to be inside the array, not only sits inside a key, it sits inside two keys! Therefore I don’t know how to access it. I would think that it has to be something like this:

```<code>parsedDoc[“Technical Analysis”]
</code>```

or:

```<code>parsedDoc[“Technical Analysis: RSI”]
</code>```

or:

```<code>parsedDoc[“Technical Analysis”][“RSI”]
</code>```

But none of these seems to work, can anyone help me out here.

答:
You have invalid JSON there, correct it to be valid JSON and your last approach will work.

A smaller version of your example that is valid JSON:

```<code>var parsedDoc = {
  "Technical Analysis": {
    "RSI":{
      "2017-07-07 16:00": {
        "RSI": "50.2925"
      }
    }
  }
}
</code>```

now

parsedDoc["Technical Analysis"]["RSI"] returns:

```<code>"2017-07-07 16:00": {
  "RSI": 50.2925
}
</code>```

Body:
I want to a javascript make an array out of this JSON code

{

 Technical Analysis: RSI:{

 2017-07-07 16:00: {RSI: "50.2925"},

 2017-07-07 15:45: {RSI: "54.1255"},

 2017-07-07 15:30: {RSI: "55.0698"},

 2017-07-07 15:15: {RSI: "52.0587"},

 2017-07-07 15:00: {RSI: "55.4002"},

 2017-07-07 14:45: {RSI: "57.9093"}

}
}

I know how to do it generally, I mean it’s not rocket science, you just have to parse it and use a for in loop. But the thing is that the content I want to be inside the array, not only sits inside a key, it sits inside two keys! Therefore I don’t know how to access it. I would think that it has to be something like this:

parsedDoc[“Technical Analysis”]

or:

parsedDoc[“Technical Analysis: RSI”]

or:

parsedDoc[“Technical Analysis”][“RSI”]

But none of these seems to work, can anyone help me out here.

Body:
You have invalid JSON there, correct it to be valid JSON and your last approach will work.

A smaller version of your example that is valid JSON:

var parsedDoc = {
  "Technical Analysis": {
    "RSI":{
      "2017-07-07 16:00": {
        "RSI": "50.2925"
      }
    }
  }
}

now

parsedDoc["Technical Analysis"]["RSI"] returns:

"2017-07-07 16:00": {
  "RSI": 50.2925
}


问:
What is the difference between reactjs vs nextjs
I have just started learning Reactjs and I am a little bit confused between Reactjs and next.js. what is the difference between them? Both are component oriented processes.

答:
Nextjs lets you render React apps on the server (SSR). If you check the source code of a react app, it's quite empty, which is not ideal for SEO matters. There are other benefits with SSR

With Nextjs, it is rendered on both the server and the client.

They can't be compared. They work together. Nextjs "wraps" react.


问:
Overlapping multi-column indices
Consider a table like so (contrived example; I am trying to make it vaguely relatable):

CREATE TABLE `roles` (
  `host` varchar(50) NOT NULL,
  `port` smallint(6) NOT NULL,
  `user_id` varchar(50) NOT NULL,
  `role` varchar(50) NOT NULL
) ENGINE=InnoDB
```

<p>Typical data:</p>

<pre class="lang-sql prettyprint-override"><code>INSERT INTO TABLE `roles`
(host, port, user_id, role)
VALUES
('localhost', 8080, 'root', 'admin'),
('localhost', 8080, 'guest', 'readonly');
</code>```

I know that the data is unique and non-null on:

(host, port, user_id)

I intend to use that multi-column index as my primary key.

But I would also like the covering index optimization for my SELECTs, which select all columns. To that end, I am considering adding also a wider multi-column index on:

(host, port, user_id, role)

So here's the question… if I create two indices, (a,b,c) and (a,b,c,d): is MySQL/InnoDB smart enough to implement that as a single index under-the-hood?

Or will it create & maintain both indices, wasting space and time — and fail to notice that (a,b,c,d) is a superset of (a,b,c)?

I am tempted to avoid the problem and just make the primary key (a,b,c,d), so that there's only one index. But that seems like a sub-optimal primary key (it considers more columns than necessary to guarantee uniqueness).

答:
(a,b,c) may be used in preference (by the Optimizer) over (a,b,c,d) because the index is smaller.

Having both is a waste of disk space and leads to wasting room in cache when parts of both indexes are cached.  And this can lead to slower queries.

Instead of having both, keep the longer one.  It will handle both situations.

If d is a "big" column, then the index with it will be "big".  In this case, (a,b,c) may be the preferred one to keep.

On the other hand, (a,b,c) and (b,c,a) handle different queries, so you may need both.

Cookbook on building indexes

Title: Overlapping multi-column indices

Body:
Consider a table like so (contrived example; I am trying to make it vaguely relatable):

CREATE TABLE `roles` (
  `host` varchar(50) NOT NULL,
  `port` smallint(6) NOT NULL,
  `user_id` varchar(50) NOT NULL,
  `role` varchar(50) NOT NULL
) ENGINE=InnoDB

Typical data:

INSERT INTO TABLE `roles`
(host, port, user_id, role)
VALUES
('localhost', 8080, 'root', 'admin'),
('localhost', 8080, 'guest', 'readonly');

I know that the data is unique and non-null on:

(host, port, user_id)

I intend to use that multi-column index as my primary key.

But I would also like the covering index optimization for my SELECTs, which select all columns. To that end, I am considering adding also a wider multi-column index on:

(host, port, user_id, role)

So here's the question… if I create two indices, (a,b,c) and (a,b,c,d): is MySQL/InnoDB smart enough to implement that as a single index under-the-hood?

Or will it create & maintain both indices, wasting space and time — and fail to notice that (a,b,c,d) is a superset of (a,b,c)?

I am tempted to avoid the problem and just make the primary key (a,b,c,d), so that there's only one index. But that seems like a sub-optimal primary key (it considers more columns than necessary to guarantee uniqueness).


问:
A short way to capture/back-reference every digit of a number individually
So basically I want to reformat a 10 digit number like so:

```<code>1234567890 --> (123) 456-7890
</code>```

A long way to do this would be to have each number be its own capture group and then back-reference each one individually:

```<code>'([0-9])([0-9])...([0-9])' --> (\1\2\3) \4\5\6-\7\8\9\10
</code>```

This seems unnecessary and verbose, but when I try the following

```<code>'([0-9]){10}'
</code>```

There appears to be only one back-reference and its of the last digit in the number.

Is there is a more elegant way to reference each character as its own capture group?

Thanks!

答:
Although the other answer with its example regex patterns hopefully shed light on the correct application of capture groups, it does not directly answer the question.  If you fail to understand how regular expressions work (capture groups in particular), you may find yourself wanting to do the same thing with a different pattern in the future.

Is there is a more elegant way to reference each character as its own
  capture group?

The initial answer is "No", there is no way to reference an individual capture of a single capture group using traditional replacement syntax - regardless of whether it is a single digit or any other capture group.  Consider that you indicate a precise number of matches with {10} and it seems perfectly reasonable to be able to access each capture.  But what if you had indicated a variable number of matches with + or {,3}?  There would be no well-defined way of knowing how many possible captures occurred.  If the same regex pattern had had more capture groups following the "repeated" capture group, there would be no way of correctly referencing the later groups.  Example:  Given the pattern ([a-z])+(\d){3}, the first capture group could match 4 letters one time, then the next time match 11 letters.  If you wanted to refer to the captured digits, how would you do that?  You could not, since \1, \2, \3, ... would all be reserved for possible capture instances of the first group.

But the inability of basic regular expressions syntax to do what you want does not remove the validity of your question, nor does it necessarily place the solution outside the realm of many regular expression implementations.  Various regex implementations (i.e. language syntax and regex libraries) resolve this limitation by facilitating regex matching with various objects for accessing repeated captures.  (c# and .Net regex library is one example, like match.Groups[1].Captures[3])  So even though you can't use basic replacement patterns to get want you want, the answer is often "Yes", depending on the specific implementation.

Body:
So basically I want to reformat a 10 digit number like so:

1234567890 --> (123) 456-7890

A long way to do this would be to have each number be its own capture group and then back-reference each one individually:

'([0-9])([0-9])...([0-9])' --> (\1\2\3) \4\5\6-\7\8\9\10

This seems unnecessary and verbose, but when I try the following

'([0-9]){10}'

There appears to be only one back-reference and its of the last digit in the number.

Is there is a more elegant way to reference each character as its own capture group?

Thanks!


问:
Finding 'first occurrence' using Match Function in R
I am new to 'R' and 'Stackoverflow' so forgive me for the incredibly basic question. I'm trying to find the 'index' of the first female in my dataset.

Code Snapshot

My overall dataset is called 'bike', so first I thought it would be a good idea to assign a new vector of just the genders...

```<code>bike$genders
</code>```

Then I tried using the function:

```<code>match(1, genders)
match(F, genders)
</code>```

Neither of which worked! I know this is and should be relatively simple but I'm just starting out so I really appreciate your help.

答:
If you want to know the rows#, this should give you the rows, with their numbers printed to the screen, and you will see the index for rows with it.

bike[bike$gender=="F",]

and if you only want the row numbers to set to a vector

rnam<-row.names(bike[bike$gender=="F",])

Body:
I am new to 'R' and 'Stackoverflow' so forgive me for the incredibly basic question. I'm trying to find the 'index' of the first female in my dataset.

Code Snapshot

My overall dataset is called 'bike', so first I thought it would be a good idea to assign a new vector of just the genders...

bike$genders

Then I tried using the function:

match(1, genders)
match(F, genders)

Neither of which worked! I know this is and should be relatively simple but I'm just starting out so I really appreciate your help.


问:
Plot one histogram(separate) for each variable in the column
I want to plot one histogram(separate) for each variable in the column. The data is import using a CSV file(sample.csv) and looks like

```<code>ip_addr_player_id,  event_name, level, points_earned, stars_earned, moves
118.93.180.241, Puzzle Complete, Botany Lab Puzzle 1, 1000, 2,   2
118.93.180.241, Puzzle Complete, Botany Lab Puzzle 2, 1000, 2,   2
118.93.180.241, Puzzle Complete, Botany Lab Puzzle 3, 1000, 2,   2
203.166.252.219, Puzzle Complete, Botany Lab Puzzle 1, 1000, 2,  2
54.166.252.324, Puzzle Complete, Botany Lab Puzzle 5, 1000, 2,  2
</code>```

Given each ip_addr_player_id is unique, I want to plot histograms (for each ip_addr_payer_id) for points_earned, starts_earned and moves.

I tried this based on an example I could find online;

```<code> library(readr)
 dataIn <- read.csv("sample.csv")
 #View(dataIn)
 library(ggplot2)
 plot <- ggplot(dataIn, aes(level, points_earned, fill=points_earned))+
              geom_histogram() + facet_wrap(~ip_addr_player_id)
 plot
</code>```

But this code gives me no output.

答:
```<code>    dataIn = read.table(text="
    ip_addr_player_id,  event_name, level, points_earned, stars_earned, moves
    118.93.180.241, Puzzle Complete, Botany Lab Puzzle 1, 1000, 2,   2
    118.93.180.241, Puzzle Complete, Botany Lab Puzzle 2, 800, 2,   2
    118.93.180.241, Puzzle Complete, Botany Lab Puzzle 1, 1000, 2,   2
    203.166.252.219, Puzzle Complete, Botany Lab Puzzle 1, 1000, 2,  2
    54.166.252.324, Puzzle Complete, Botany Lab Puzzle 5, 1000, 2,  2
    ",header=T, sep=",")
    dataIn

    # get uniqe players
    players=unique(dataIn$ip_addr_player_id)
    players
    library(data.table)
    #loop over players
    for (i in players) {
      #print (i)

      #select rows for uniq ip_addr_player_id
      index=which(dataIn$ip_addr_player_id ==i)
      #print(index)

      #get dataframe of the coresponding index
      p1=dataIn[index,]

      # get data table
      DT <- data.table(p1)
     #  print(DT)
     # group by level
     dt1= DT[, sum(points_earned), by = level]
      #save the each plot to a file
       png(filename=sprintf("%s.png",i ))
     # set ip as a title for the graph
     barplot(dt1$V1, names.arg=dt1$level, main = i)
     # do the same for other variables for barplot
      dev.off()
    }
</code>```

Review a partial result online

Body:
I want to plot one histogram(separate) for each variable in the column. The data is import using a CSV file(sample.csv) and looks like

ip_addr_player_id,  event_name, level, points_earned, stars_earned, moves
118.93.180.241, Puzzle Complete, Botany Lab Puzzle 1, 1000, 2,   2
118.93.180.241, Puzzle Complete, Botany Lab Puzzle 2, 1000, 2,   2
118.93.180.241, Puzzle Complete, Botany Lab Puzzle 3, 1000, 2,   2
203.166.252.219, Puzzle Complete, Botany Lab Puzzle 1, 1000, 2,  2
54.166.252.324, Puzzle Complete, Botany Lab Puzzle 5, 1000, 2,  2

Given each ip_addr_player_id is unique, I want to plot histograms (for each ip_addr_payer_id) for points_earned, starts_earned and moves.

I tried this based on an example I could find online;

 library(readr)
 dataIn <- read.csv("sample.csv")
 #View(dataIn)
 library(ggplot2)
 plot <- ggplot(dataIn, aes(level, points_earned, fill=points_earned))+
              geom_histogram() + facet_wrap(~ip_addr_player_id)
 plot

But this code gives me no output.

Body:
    dataIn = read.table(text="
    ip_addr_player_id,  event_name, level, points_earned, stars_earned, moves
    118.93.180.241, Puzzle Complete, Botany Lab Puzzle 1, 1000, 2,   2
    118.93.180.241, Puzzle Complete, Botany Lab Puzzle 2, 800, 2,   2
    118.93.180.241, Puzzle Complete, Botany Lab Puzzle 1, 1000, 2,   2
    203.166.252.219, Puzzle Complete, Botany Lab Puzzle 1, 1000, 2,  2
    54.166.252.324, Puzzle Complete, Botany Lab Puzzle 5, 1000, 2,  2
    ",header=T, sep=",")
    dataIn

    # get uniqe players
    players=unique(dataIn$ip_addr_player_id)
    players
    library(data.table)
    #loop over players
    for (i in players) {
      #print (i)

      #select rows for uniq ip_addr_player_id
      index=which(dataIn$ip_addr_player_id ==i)
      #print(index)

      #get dataframe of the coresponding index
      p1=dataIn[index,]

      # get data table
      DT <- data.table(p1)
     #  print(DT)
     # group by level
     dt1= DT[, sum(points_earned), by = level]
      #save the each plot to a file
       png(filename=sprintf("%s.png",i ))
     # set ip as a title for the graph
     barplot(dt1$V1, names.arg=dt1$level, main = i)
     # do the same for other variables for barplot
      dev.off()
    }

Review a partial result online


问:
can't find plaint text in android
While learning how to build a simple user interface on The instructs. From the Palette window on the left, click Text in the left panel, and then drag Plain Text into the design editor and drop it near the top of the layout.  Where exactly can I find "plain-text", or is it something I type then drag into the design editor?

The link's down below:

https://developer.android.com/training/basics/firstapp/building-ui.html#textbox

答:
You can find it here.
Start typing after pressing the magnifying button it would show up as the top result.

Title: can't find plaint text in android


问:
random image and its url
i want to create a random image and its url, i mean not the link of the image, but in addition to image's link, i want the specified URL, so that random image was displayed and when u click on it, u go to the specified URL

here is my javascript:

```<code>    function random_imglink(){
      var myimages=new Array()
      //specify random images below. You can have as many as you wish
      myimages[1]="/documents/templates/projedepo/banner/canon.jpg"
      myimages[2]="/documents/templates/projedepo/banner/indigovision.jpg"

      var ry=Math.floor(Math.random()*myimages.length)

      if (ry==0)
         ry=1

    var randomImage = '<img src="'+myimages[ry]+'" height="420" width="964" />';
    document.getElementById("image2").innerHTML = randomImage;
    }
    random_imglink()
</code>```

Here is my HTML:

```<code><div id="slider_container">
<div id="image2">
</div>
<div id="thumb2">
<a href="#" rel="/documents/templates/projedepo/banner/canon.jpg" class="image2" ><img title="Canon" class="slider_thumb" src="/documents/templates/bilgiteknolojileri/images/t_flash/t1.png" border="0"/></a>
<a href="#" rel="/documents/templates/projedepo/banner/indigovision.jpg" class="image2"><img title="IndogoVision" class="slider_thumb" src="/documents/templates/bilgiteknolojileri/images/t_flash/t2.png" border="0"/></a>
</div></div>
</code>```

答:
I'm not entirely sure what you want to do, but I think you want to create a single image which links to an url, chosen at random from a list of images and corresponding urls. You could do it like this:

```<code>function random_imglink() {
    var myimages = [
        {image: "/documents/templates/projedepo/banner/canon.jpg", url: "http://www.url1.com"},
        {image: "/documents/templates/projedepo/banner/indigovision.jpg", url: "http://www.url2.com"}
    ];

    var ry=Math.floor(Math.random()*myimages.length);

    var randomImage = myimages[ry];

    var randomImageLink = '<a href="' + randomImage.url + '"><img src="'+randomImage.image+'" height="420" width="964" /></a>';
    document.getElementById("image2").innerHTML = randomImageLink;
}
</code>```

I'm using [] here to create an array, which starts at index 0 (see: http://www.hunlock.com/blogs/Mastering_Javascript_Arrays). Because of this, you don't need the if (ry == 0) ry = 1; part. The things in {} are javascript objects, which you can use as associative (key-value) arrays. See also http://www.quirksmode.org/js/associative.html.

Maybe you already know all of this, in which case please disregard everything I said :)

EDIT:

By the way, if you want to do this a little bit nicer and there will always be an image and a link in your image2 div, you could put all the non-dynamic stuff in the html:

```<code><div id="image2">
    <a id="image2-link" href="#"><img id="image2-image" src="" height="420" width="964" /></a>
</div>
</code>```

and then

```<code>(...)

    var randomImage = myimages[ry];

    document.getElementById("image2-link").href = randomImage.url;
    document.getElementById("image2-image").src = randomImage.image;
</code>```

Title: random image and its url

Body:
i want to create a random image and its url, i mean not the link of the image, but in addition to image's link, i want the specified URL, so that random image was displayed and when u click on it, u go to the specified URL

here is my javascript:

    function random_imglink(){
      var myimages=new Array()
      //specify random images below. You can have as many as you wish
      myimages[1]="/documents/templates/projedepo/banner/canon.jpg"
      myimages[2]="/documents/templates/projedepo/banner/indigovision.jpg"

      var ry=Math.floor(Math.random()*myimages.length)

      if (ry==0)
         ry=1

    var randomImage = '';
    document.getElementById("image2").innerHTML = randomImage;
    }
    random_imglink()

Here is my HTML:

Body:
I'm not entirely sure what you want to do, but I think you want to create a single image which links to an url, chosen at random from a list of images and corresponding urls. You could do it like this:

function random_imglink() {
    var myimages = [
        {image: "/documents/templates/projedepo/banner/canon.jpg", url: "http://www.url1.com"},
        {image: "/documents/templates/projedepo/banner/indigovision.jpg", url: "http://www.url2.com"}
    ];

    var ry=Math.floor(Math.random()*myimages.length);

    var randomImage = myimages[ry];

    var randomImageLink = '<a href="' + randomImage.url + '"><img src="'+randomImage.image+'" height="420" width="964" /></a>';
    document.getElementById("image2").innerHTML = randomImageLink;
}

I'm using [] here to create an array, which starts at index 0 (see: http://www.hunlock.com/blogs/Mastering_Javascript_Arrays). Because of this, you don't need the if (ry == 0) ry = 1; part. The things in {} are javascript objects, which you can use as associative (key-value) arrays. See also http://www.quirksmode.org/js/associative.html.

Maybe you already know all of this, in which case please disregard everything I said :)

EDIT:

By the way, if you want to do this a little bit nicer and there will always be an image and a link in your image2 div, you could put all the non-dynamic stuff in the html:

<div id="image2">
    <a id="image2-link" href="#"><img id="image2-image" src="" height="420" width="964" /></a>
</div>

and then

(...)

    var randomImage = myimages[ry];

    document.getElementById("image2-link").href = randomImage.url;
    document.getElementById("image2-image").src = randomImage.image;


问:
Xamarin Forms LocalNotification not showing when button clicked
I am a novice in Xamarin Forms, I am trying to show a local notification whenever a button is clicked.

I have installed this plugin:
-https://github.com/B1naryStudio/Xamarin.LocalNotifications
-https://www.nuget.org/packages/Xam.Plugin.LocalNotifications/

The thing is, the plugin does not work. I have followed every step but I cannot see why I still have nothing.

Here my XAML:

```<code><?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="LeafWords.Classes.SettingsLeaf.WordSettings">
    <ContentPage.Content>

        <StackLayout>
            <Button Clicked="WordNotif" Text="Local Notification"></Button>
        </StackLayout>

    </ContentPage.Content>
</ContentPage>
</code>```

Here is my method:

```<code>  void WordNotif() {

        // Handle when your app starts
        var notification = new LocalNotification
        {
            Text = "Hello Plugin",
            Title = "Nbation Plugin",
            Id = 2,
            NotifyTime = DateTime.Now.AddSeconds(10)
        };

        var notifier = CrossLocalNotifications.CreateLocalNotifier();
        notifier.Notify(notification);

    }
</code>```

答:
I found this link , and it is working :
https://github.com/edsnider/LocalNotificationsPlugin</p>

Body:
I am a novice in Xamarin Forms, I am trying to show a local notification whenever a button is clicked.

I have installed this plugin:
-https://github.com/B1naryStudio/Xamarin.LocalNotifications
-https://www.nuget.org/packages/Xam.Plugin.LocalNotifications/

The thing is, the plugin does not work. I have followed every step but I cannot see why I still have nothing.

Here my XAML:

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="LeafWords.Classes.SettingsLeaf.WordSettings">
    <ContentPage.Content>

        <StackLayout>
            <Button Clicked="WordNotif" Text="Local Notification"></Button>
        </StackLayout>

    </ContentPage.Content>
</ContentPage>

Here is my method:

  void WordNotif() {

        // Handle when your app starts
        var notification = new LocalNotification
        {
            Text = "Hello Plugin",
            Title = "Nbation Plugin",
            Id = 2,
            NotifyTime = DateTime.Now.AddSeconds(10)
        };

        var notifier = CrossLocalNotifications.CreateLocalNotifier();
        notifier.Notify(notification);

    }


问:
Matplotlib : the colorbar keeps shrinking
I wrote a code where I have an array called array2 with numbers between 0. and 1. in it. When I click on the array displayed by imshow the cells in the array take the value 2. and become red.

Then I added a colorbar but it kept shrinking once I clicked on it and the cells didn't become red.

What am I doing wrong ?

Code without colorbar (works fine)

```<code>import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
from matplotlib import cm
from mpl_toolkits.axes_grid1 import make_axes_locatable
from random import random

def test(n):
    array1 = np.zeros((n,n))
    for i in range(n):
        for j in range(n):
            array1[i,j] = random()
    return array1

# Array
global array2
array2 = test(10)

# Colormap
greens = cm.Greens(np.linspace(0,1, num=50))
greensfill = cm.Greens(np.ones(25))
red = [(1,0,0,1)]*len(greens)
gray = [(.5,.5,.5,1)]*len(greens)
colors = np.vstack((greens, greensfill, red, gray))
mycmap = mcolors.LinearSegmentedColormap.from_list('my_colormap', colors)

# Matplotlib
fig, axes = plt.subplots(1)
fig.tight_layout()

plt.imshow(array2, animated=True, cmap = mycmap, interpolation="none", vmin=0, vmax=3.5, origin='lower')

def onclick(event):
    global x, y
    x, y = int(event.xdata), int(event.ydata)
    array2[y,x] = 2.

    plt.imshow(array2, animated=True, cmap = mycmap, interpolation="none", vmin=0, vmax=3.5, origin='lower')

fig.canvas.mpl_connect('button_press_event', onclick)
</code>```

Code with colorbar (doesn't work)

```<code>import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
from matplotlib import cm
from mpl_toolkits.axes_grid1 import make_axes_locatable
from random import random

def test(n):
    array1 = np.zeros((n,n))
    for i in range(n):
        for j in range(n):
            array1[i,j] = random()
    return array1

# Array
global array2
array2 = test(10)

# Colormap
greens = cm.Greens(np.linspace(0,1, num=50))
greensfill = cm.Greens(np.ones(25))
red = [(1,0,0,1)]*len(greens)
gray = [(.5,.5,.5,1)]*len(greens)
colors = np.vstack((greens, greensfill, red, gray))
mycmap = mcolors.LinearSegmentedColormap.from_list('my_colormap', colors)

# Matplotlib
fig, axes = plt.subplots(1)
fig.tight_layout()

im = plt.imshow(array2, animated=True, cmap = mycmap, interpolation="none", vmin=0, vmax=3.5, origin='lower')

divider = make_axes_locatable(axes)
cax = divider.append_axes("right", size="13%", pad=0.2)

cb = plt.colorbar(im, cax=cax, boundaries=np.linspace(0,1, num=100), ticks=[0,1])

cb.set_label("Title", fontsize=15, labelpad=-5, y=0.5)

def onclick(event):
    global x, y
    x, y = int(event.xdata), int(event.ydata)
    array2[y,x] = 2.

    im = plt.imshow(array2, animated=True, cmap = mycmap, interpolation="none", vmin=0, vmax=3.5, origin='lower')

    divider = make_axes_locatable(axes)
    cax = divider.append_axes("right", size="13%", pad=0.2)

    cb = plt.colorbar(im, cax=cax, boundaries=np.linspace(0,1, num=100), ticks=[0,1])

    cb.set_label("Title", fontsize=15, labelpad=-5, y=0.5)

fig.canvas.mpl_connect('button_press_event', onclick)
</code>```

答:
It would be better to just update the imshow, instead of drawing a new one every time a click is performed. This can be done using the .set_data() method. The advantage is that the colorbar can stay where it is and doesn't get touched.

In general it's best to work with the plotting objects directly instead of pyplot when doing interactive stuff. So using fig and ax instead of plt in most cases.

Note that to accurately catch the click on a pixel you need to round the coordinate first, int(np.round(event.xdata)).

```<code>import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
from matplotlib import cm
from mpl_toolkits.axes_grid1 import make_axes_locatable

global array2
array2 = np.random.rand(10,10)

# Colormap
greens = cm.Greens(np.linspace(0,1, num=50))
greensfill = cm.Greens(np.ones(25))
red = [(1,0,0,1)]*len(greens)
gray = [(.5,.5,.5,1)]*len(greens)
colors = np.vstack((greens, greensfill, red, gray))
mycmap = mcolors.LinearSegmentedColormap.from_list('my_colormap', colors)

# Matplotlib
fig, ax = plt.subplots()
fig.tight_layout()
im = ax.imshow(array2, animated=True, cmap = mycmap, interpolation="none",
               vmin=0, vmax=3.5, origin='lower')

divider = make_axes_locatable(ax)
cax = divider.append_axes("right", size="13%", pad=0.2)
cb = fig.colorbar(im, ax =ax, cax=cax, boundaries=np.linspace(0,1, num=100),
                  ticks=[0,1])
cb.set_label("Title", fontsize=15, labelpad=-5, y=0.5)

def onclick(event):
    x, y = int(np.round(event.xdata)), int(np.round(event.ydata))
    array2[y,x] = 2.
    im.set_data(array2)
    fig.canvas.draw_idle()

fig.canvas.mpl_connect('button_press_event', onclick)
plt.show()
</code>```

Body:
I wrote a code where I have an array called array2 with numbers between 0. and 1. in it. When I click on the array displayed by imshow the cells in the array take the value 2. and become red.

Then I added a colorbar but it kept shrinking once I clicked on it and the cells didn't become red.

What am I doing wrong ?

Code without colorbar (works fine)

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
from matplotlib import cm
from mpl_toolkits.axes_grid1 import make_axes_locatable
from random import random

def test(n):
    array1 = np.zeros((n,n))
    for i in range(n):
        for j in range(n):
            array1[i,j] = random()
    return array1

# Array
global array2
array2 = test(10)

# Colormap
greens = cm.Greens(np.linspace(0,1, num=50))
greensfill = cm.Greens(np.ones(25))
red = [(1,0,0,1)]*len(greens)
gray = [(.5,.5,.5,1)]*len(greens)
colors = np.vstack((greens, greensfill, red, gray))
mycmap = mcolors.LinearSegmentedColormap.from_list('my_colormap', colors)

# Matplotlib
fig, axes = plt.subplots(1)
fig.tight_layout()

plt.imshow(array2, animated=True, cmap = mycmap, interpolation="none", vmin=0, vmax=3.5, origin='lower')

def onclick(event):
    global x, y
    x, y = int(event.xdata), int(event.ydata)
    array2[y,x] = 2.

    plt.imshow(array2, animated=True, cmap = mycmap, interpolation="none", vmin=0, vmax=3.5, origin='lower')

fig.canvas.mpl_connect('button_press_event', onclick)

Code with colorbar (doesn't work)

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
from matplotlib import cm
from mpl_toolkits.axes_grid1 import make_axes_locatable
from random import random

def test(n):
    array1 = np.zeros((n,n))
    for i in range(n):
        for j in range(n):
            array1[i,j] = random()
    return array1

# Array
global array2
array2 = test(10)

# Colormap
greens = cm.Greens(np.linspace(0,1, num=50))
greensfill = cm.Greens(np.ones(25))
red = [(1,0,0,1)]*len(greens)
gray = [(.5,.5,.5,1)]*len(greens)
colors = np.vstack((greens, greensfill, red, gray))
mycmap = mcolors.LinearSegmentedColormap.from_list('my_colormap', colors)

# Matplotlib
fig, axes = plt.subplots(1)
fig.tight_layout()

im = plt.imshow(array2, animated=True, cmap = mycmap, interpolation="none", vmin=0, vmax=3.5, origin='lower')

divider = make_axes_locatable(axes)
cax = divider.append_axes("right", size="13%", pad=0.2)

cb = plt.colorbar(im, cax=cax, boundaries=np.linspace(0,1, num=100), ticks=[0,1])

cb.set_label("Title", fontsize=15, labelpad=-5, y=0.5)

def onclick(event):
    global x, y
    x, y = int(event.xdata), int(event.ydata)
    array2[y,x] = 2.

    im = plt.imshow(array2, animated=True, cmap = mycmap, interpolation="none", vmin=0, vmax=3.5, origin='lower')

    divider = make_axes_locatable(axes)
    cax = divider.append_axes("right", size="13%", pad=0.2)

    cb = plt.colorbar(im, cax=cax, boundaries=np.linspace(0,1, num=100), ticks=[0,1])

    cb.set_label("Title", fontsize=15, labelpad=-5, y=0.5)

fig.canvas.mpl_connect('button_press_event', onclick)

Body:
It would be better to just update the imshow, instead of drawing a new one every time a click is performed. This can be done using the .set_data() method. The advantage is that the colorbar can stay where it is and doesn't get touched.

In general it's best to work with the plotting objects directly instead of pyplot when doing interactive stuff. So using fig and ax instead of plt in most cases.

Note that to accurately catch the click on a pixel you need to round the coordinate first, int(np.round(event.xdata)).

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
from matplotlib import cm
from mpl_toolkits.axes_grid1 import make_axes_locatable

global array2
array2 = np.random.rand(10,10)

# Colormap
greens = cm.Greens(np.linspace(0,1, num=50))
greensfill = cm.Greens(np.ones(25))
red = [(1,0,0,1)]*len(greens)
gray = [(.5,.5,.5,1)]*len(greens)
colors = np.vstack((greens, greensfill, red, gray))
mycmap = mcolors.LinearSegmentedColormap.from_list('my_colormap', colors)

# Matplotlib
fig, ax = plt.subplots()
fig.tight_layout()
im = ax.imshow(array2, animated=True, cmap = mycmap, interpolation="none",
               vmin=0, vmax=3.5, origin='lower')

divider = make_axes_locatable(ax)
cax = divider.append_axes("right", size="13%", pad=0.2)
cb = fig.colorbar(im, ax =ax, cax=cax, boundaries=np.linspace(0,1, num=100),
                  ticks=[0,1])
cb.set_label("Title", fontsize=15, labelpad=-5, y=0.5)

def onclick(event):
    x, y = int(np.round(event.xdata)), int(np.round(event.ydata))
    array2[y,x] = 2.
    im.set_data(array2)
    fig.canvas.draw_idle()

fig.canvas.mpl_connect('button_press_event', onclick)
plt.show()


问:
Pattern with action for two statements
I'm am trying to match and delete two statements with rascals visit statement. Of course I would also need to check if they are used but in this case, I don't have to worry about that. In the example below, you can see two tmp variabels which are created but not used (this is semi-pseudo Rust code). They are only created as temporary variables and freed. (I have tried to create equivelant in Java but it lost some context in translation like for example the redeclaration of the tmp)

```<code>{
    let tmp : c_void = repository as c_void;
    repository = MArray();
    free(tmp);

    let tmp : c_void = where_ as c_void;
    where_ = MArray();
    free(tmp);
}
</code>```

This is an example of the simplified version of the pattern with action which I have been playing with. With this pattern, I would think that the first free statement would be matched but it apparently is the last one within the scope. I have tried to do this in all kind of ways like statement counters and various different patterns to no success.

```<code>visit(crate){
    case (Statements) `let tmp : c_void = <Identifier _> as c_void;
                      '<Statement* stmts>
                      'free(tmp);` =>
         (Statements) `<Statement* stmts>`
}
</code>```

The final product should look like following:

```<code>{
    repository = MArray();

    where_ = MArray();
}
</code>```

Edit: Progress

I have managed to do what I wanted with the following code (this is still just the semi-pseudo Rust):

```<code>crate = innermost visit(crate){
    case (Statements) `let tmp : c_void = <Identifier _> as c_void;
                      '<Statement* stmts>
                      'free(tmp);
                      '<Statement* post_stmts>` =>
         (Statements) `<Statement* stmts>
                      '<Statement* post_stmts>`

    case (Statements) `<Statement* pre_stmts>
                      'let tmp : c_void = <Identifier _> as c_void;
                      '<Statement* stmts>
                      'free(tmp);` =>
         (Statements) `<Statement* pre_stmts>
                      '<Statement* stmts>`
}
</code>```

This now works for a single scope matching of both tmp instances but it does not expand into other scopes. I'm not sure why it doesn't just continue to match in other scopes despite it using the innermost matching. An example of an if else would be fitting for this. It matches and changes the tmp instances in the if branch but it does not continue into the else branch to also match them there.

Edit: Final

This seems to be solved now. I was wondering if adding another case would help and yes it did. Apparentaly it was not the problem of not reaching the scope but a problem of not matching the contents of the scope. Here is the modified code which works (I had to change the statements names because Rascal complaining about redeclared Statement* names accros cases):

```<code>crate = innermost visit(crate){
    case (Statements) `let mut tmp : *mut ::std::os::raw::c_void = <Identifier _> as (*mut ::std::os::raw::c_void);
                      '<Statement* stmts1>
                      'free(tmp);
                      '<Statement* stmts2>` =>
         (Statements) `<Statement* stmts1>
                      '<Statement* stmts2>`

    case (Statements) `<Statement* stmts3>
                      'let mut tmp : *mut ::std::os::raw::c_void = <Identifier _> as (*mut ::std::os::raw::c_void);
                      '<Statement* stmts4>
                      'free(tmp);` =>
         (Statements) `<Statement* stmts3>
                      '<Statement* stmts4>`

    case (Statements) `<Statement* stmts5>
                      'let mut tmp : *mut ::std::os::raw::c_void = <Identifier _> as (*mut ::std::os::raw::c_void);
                      '<Statement* stmts6>
                      'free(tmp);
                      '<Statement* stmts7>` =>
         (Statements) `<Statement* stmts5>
                      '<Statement* stmts6>
                      '<Statement* stmts7>`
}
</code>```

^ (This example is the actual code an not a semi-pseudo code anymore.)

答:
There is no place holder after the last free(tmp); so the last free(tmp) has to match. May be use a pattern like this:

```<code>`let tmp : c_void = <Identifier _> as c_void;
'<Statement* stmts1>
'free(tmp);
'<Statement* stmts2>`
</code>```

I don't know the precise details of your example, but you could give this a try.

Title: Pattern with action for two statements

Body:
I'm am trying to match and delete two statements with rascals visit statement. Of course I would also need to check if they are used but in this case, I don't have to worry about that. In the example below, you can see two tmp variabels which are created but not used (this is semi-pseudo Rust code). They are only created as temporary variables and freed. (I have tried to create equivelant in Java but it lost some context in translation like for example the redeclaration of the tmp)

{
    let tmp : c_void = repository as c_void;
    repository = MArray();
    free(tmp);

    let tmp : c_void = where_ as c_void;
    where_ = MArray();
    free(tmp);
}

This is an example of the simplified version of the pattern with action which I have been playing with. With this pattern, I would think that the first free statement would be matched but it apparently is the last one within the scope. I have tried to do this in all kind of ways like statement counters and various different patterns to no success.

visit(crate){
    case (Statements) `let tmp : c_void = <Identifier _> as c_void;
                      '<Statement* stmts>
                      'free(tmp);` =>
         (Statements) `<Statement* stmts>`
}

The final product should look like following:

{
    repository = MArray();

    where_ = MArray();
}

Edit: Progress

I have managed to do what I wanted with the following code (this is still just the semi-pseudo Rust):

crate = innermost visit(crate){
    case (Statements) `let tmp : c_void = <Identifier _> as c_void;
                      '<Statement* stmts>
                      'free(tmp);
                      '<Statement* post_stmts>` =>
         (Statements) `<Statement* stmts>
                      '<Statement* post_stmts>`

    case (Statements) `<Statement* pre_stmts>
                      'let tmp : c_void = <Identifier _> as c_void;
                      '<Statement* stmts>
                      'free(tmp);` =>
         (Statements) `<Statement* pre_stmts>
                      '<Statement* stmts>`
}

This now works for a single scope matching of both tmp instances but it does not expand into other scopes. I'm not sure why it doesn't just continue to match in other scopes despite it using the innermost matching. An example of an if else would be fitting for this. It matches and changes the tmp instances in the if branch but it does not continue into the else branch to also match them there.

Edit: Final

This seems to be solved now. I was wondering if adding another case would help and yes it did. Apparentaly it was not the problem of not reaching the scope but a problem of not matching the contents of the scope. Here is the modified code which works (I had to change the statements names because Rascal complaining about redeclared Statement* names accros cases):

crate = innermost visit(crate){
    case (Statements) `let mut tmp : *mut ::std::os::raw::c_void = <Identifier _> as (*mut ::std::os::raw::c_void);
                      '<Statement* stmts1>
                      'free(tmp);
                      '<Statement* stmts2>` =>
         (Statements) `<Statement* stmts1>
                      '<Statement* stmts2>`

    case (Statements) `<Statement* stmts3>
                      'let mut tmp : *mut ::std::os::raw::c_void = <Identifier _> as (*mut ::std::os::raw::c_void);
                      '<Statement* stmts4>
                      'free(tmp);` =>
         (Statements) `<Statement* stmts3>
                      '<Statement* stmts4>`

    case (Statements) `<Statement* stmts5>
                      'let mut tmp : *mut ::std::os::raw::c_void = <Identifier _> as (*mut ::std::os::raw::c_void);
                      '<Statement* stmts6>
                      'free(tmp);
                      '<Statement* stmts7>` =>
         (Statements) `<Statement* stmts5>
                      '<Statement* stmts6>
                      '<Statement* stmts7>`
}

^ (This example is the actual code an not a semi-pseudo code anymore.)

Body:
There is no place holder after the last free(tmp); so the last free(tmp) has to match. May be use a pattern like this:

`let tmp : c_void = <Identifier _> as c_void;
'<Statement* stmts1>
'free(tmp);
'<Statement* stmts2>`

I don't know the precise details of your example, but you could give this a try.


问:
Need to pick up the SUM OF Tax Amount for the highest Sequence number Per Year, Per SSN, Per employer
Consider Employee table:

```<code>Employerid ssn  year  Seqnumber     q1taxamt   q2taxamt     q3taxamt     q4taxamt
1004       101  2013    1             2000       0            0             0
1004       101  2013    2             2000       100          0             0
1004       101  2013    3             2000       100          200           0
1004       101  2013    4             2000       100          200           300
1004       102  2013    1             3000       0            0             0
1004       102  2013    2             3000       200          0             0
1004       102  2013    3             3000       200          300           0
1004       102  2013    4             3000       200          300           400
1004       102  2013    5             3000       200          300           400
</code>```

Here the  transformation rule is we need to pick the highest Seqnumber with respect to each ssn per year per

Employerid and the amounts.

i.e for 10004 for sum(q1taxamt) is 2000 +3000 = 5000

The Logic is ssn 101 has highest seq number of 4 and ssn 102 has highest seq number of 5 so we need to pick those values wrt to employerid

Example:
Want to check for q1taxamt: 2000 +3000 = 5000

Want to check for q4taxamt: 300 +400 = 700

output must be:

```<code>Employerid  YEAR     q1taxamt   q2taxamt     q3taxamt     q4taxamt
10004        2013     5000        300          500           700
</code>```

The below query is generating wrong result:

```<code>Select
    Sum(E1.q1taxamt) q1taxamt,
    Sum(E1.q2taxamt) q2taxamt,
    Sum(E1.q3taxamt) q3taxamt,
    Sum(E1.q4taxamt) q4taxamt,
    E1.Employerid,
    E1.YEAR
from Employee E1
join
(
    select
        E.Employerid,
        MAX(E.seqnumber) seqnumber,
        E.YEAR
    from Employee E
    group by E.Employerid,E.SSn,E.year
)E2
on E1.Employerid=E2.Employerid
AND E1.YEAR=E2.YEAR
and E1.seqnumber=E2.Taxseqnumber
</code>```

答:
Just use row_number():

```<code>select e.*
from (select e.*,
             row_number() over (partition by E.Employerid, E.SSn, E.year
                                order by e.seqnumber desc
                               ) as seqnum
      from Employee e
     ) e
where seqnum = 1;
</code>```

For best performance, you want an index on Employee(EmployerId, SSN, seqnumber desc).

Body:
Consider Employee table:

Employerid ssn  year  Seqnumber     q1taxamt   q2taxamt     q3taxamt     q4taxamt
1004       101  2013    1             2000       0            0             0
1004       101  2013    2             2000       100          0             0
1004       101  2013    3             2000       100          200           0
1004       101  2013    4             2000       100          200           300
1004       102  2013    1             3000       0            0             0
1004       102  2013    2             3000       200          0             0
1004       102  2013    3             3000       200          300           0
1004       102  2013    4             3000       200          300           400
1004       102  2013    5             3000       200          300           400

Here the  transformation rule is we need to pick the highest Seqnumber with respect to each ssn per year per

Employerid and the amounts.

i.e for 10004 for sum(q1taxamt) is 2000 +3000 = 5000

The Logic is ssn 101 has highest seq number of 4 and ssn 102 has highest seq number of 5 so we need to pick those values wrt to employerid

Example:
Want to check for q1taxamt: 2000 +3000 = 5000

Want to check for q4taxamt: 300 +400 = 700

output must be:

Employerid  YEAR     q1taxamt   q2taxamt     q3taxamt     q4taxamt
10004        2013     5000        300          500           700

The below query is generating wrong result:

Select
    Sum(E1.q1taxamt) q1taxamt,
    Sum(E1.q2taxamt) q2taxamt,
    Sum(E1.q3taxamt) q3taxamt,
    Sum(E1.q4taxamt) q4taxamt,
    E1.Employerid,
    E1.YEAR
from Employee E1
join
(
    select
        E.Employerid,
        MAX(E.seqnumber) seqnumber,
        E.YEAR
    from Employee E
    group by E.Employerid,E.SSn,E.year
)E2
on E1.Employerid=E2.Employerid
AND E1.YEAR=E2.YEAR
and E1.seqnumber=E2.Taxseqnumber

Body:
Just use row_number():

select e.*
from (select e.*,
             row_number() over (partition by E.Employerid, E.SSn, E.year
                                order by e.seqnumber desc
                               ) as seqnum
      from Employee e
     ) e
where seqnum = 1;

For best performance, you want an index on Employee(EmployerId, SSN, seqnumber desc).


问:
How can I establish grouping in Django through models?
I created a model named MenuItems which will allow for me to enter all of the items that a restaurant has on their menu, later I will use these on the front end. I also created a model name MenuGrouping so that on the front end, I can have Bootstrap tabs show the group_title and under each, show the items in that group. What field should I add in the MenuItems model to associate it to a group? I attempted to use group = models.ForeignKey(MenuGrouping) but then I run into the issue of showing each item in the specific group.

Models.py:

```<code>class MenuItems(models.Model):

  menu_item_title = models.CharField(max_length=256)
  menu_item_description = models.TextField()
  menu_item_price = models.DecimalField(max_digits=4, decimal_places=2)

  customer_favorite = models.BooleanField(default=False)
  is_on_menu = models.BooleanField(default=True)

class Meta:
    ordering = ('menu_item_title', )

class MenuGrouping(models.Model):
    group_title = models.CharField(max_length=256)
</code>```

Is there a relationship that I can add in the MenuGrouping model that I can associate multiple MenuItems?

Thank you in advance!

答:
If I understand you correctly that you are trying to make groups like drink, food, desert and ... then here it is:

Each item can be only in one group (I mean soda is a drink and it can't be food too and etc). So what you need to do here is to add a field to MenuItems model.

your MenuItems should be like this:

```<code>class MenuItems(models.Model):

    menu_item_title = models.CharField(max_length=256)
    menu_item_description = models.TextField()
    menu_item_price = models.DecimalField(max_digits=4, decimal_places=2)

   customer_favorite = models.BooleanField(default=False)
   is_on_menu = models.BooleanField(default=True)
   group = models.ForeignKey(MenuGrouping)
</code>```

Now to use this in your template first get the groups in view and send them to template and then:

```<code>{% for group in groups %)

    # add your tabs or just print the group name. or how ever you want.

    Group {{ group.group_title }}:

    # and now you can list the items in this group here

    {% for item in group.menuitems_set.all %}
        Title is: {{ item.menu_item_title }}
        Price is: {{ item.menu_item_price }}
        ...
    {% endfor %}
{% endfor %}
</code>```

If you need all items to be listed somewhere else out of groups or any other way just send the items to the template too.

Here is the Many to One relationship  documentation :
Many-to-one relationships

Also you can add a m2m relation to MenuGrouping and add items to each group but then one item can be in multiple groups and for a restaurant menu I can't see how that might happen.

Body:
I created a model named MenuItems which will allow for me to enter all of the items that a restaurant has on their menu, later I will use these on the front end. I also created a model name MenuGrouping so that on the front end, I can have Bootstrap tabs show the group_title and under each, show the items in that group. What field should I add in the MenuItems model to associate it to a group? I attempted to use group = models.ForeignKey(MenuGrouping) but then I run into the issue of showing each item in the specific group.

Models.py:

class MenuItems(models.Model):

  menu_item_title = models.CharField(max_length=256)
  menu_item_description = models.TextField()
  menu_item_price = models.DecimalField(max_digits=4, decimal_places=2)

  customer_favorite = models.BooleanField(default=False)
  is_on_menu = models.BooleanField(default=True)

class Meta:
    ordering = ('menu_item_title', )

class MenuGrouping(models.Model):
    group_title = models.CharField(max_length=256)

Is there a relationship that I can add in the MenuGrouping model that I can associate multiple MenuItems?

Thank you in advance!

Body:
If I understand you correctly that you are trying to make groups like drink, food, desert and ... then here it is:

Each item can be only in one group (I mean soda is a drink and it can't be food too and etc). So what you need to do here is to add a field to MenuItems model.

your MenuItems should be like this:

class MenuItems(models.Model):

    menu_item_title = models.CharField(max_length=256)
    menu_item_description = models.TextField()
    menu_item_price = models.DecimalField(max_digits=4, decimal_places=2)

   customer_favorite = models.BooleanField(default=False)
   is_on_menu = models.BooleanField(default=True)
   group = models.ForeignKey(MenuGrouping)

Now to use this in your template first get the groups in view and send them to template and then:

{% for group in groups %)

    # add your tabs or just print the group name. or how ever you want.

    Group {{ group.group_title }}:

    # and now you can list the items in this group here

    {% for item in group.menuitems_set.all %}
        Title is: {{ item.menu_item_title }}
        Price is: {{ item.menu_item_price }}
        ...
    {% endfor %}
{% endfor %}

If you need all items to be listed somewhere else out of groups or any other way just send the items to the template too.

Here is the Many to One relationship  documentation :
Many-to-one relationships

Also you can add a m2m relation to MenuGrouping and add items to each group but then one item can be in multiple groups and for a restaurant menu I can't see how that might happen.


问:
When I delete an item from the database and updatethe datagrid, I still see this object
I have two windows wpf.
On the first window I see data from DataGrid, on the second window I delete object from database.

First window:

```<code>private void mnRemoveProduct_Click(object sender, RoutedEventArgs e)
{
   RemoveProduct window = new RemoveProduct();
   window.ShowDialog();
   ShowWatchTable();
} // mnRemoveProduct_Click
</code>```

Second window:

```<code>private void btnDelete_Click(object sender, RoutedEventArgs e)
{
    if (cmbNameOfWatch.SelectedIndex > 0)
    {
        var value =
            (from watch in obj.Watch.Where(w => w.mark == cmbNameOfWatch.SelectedValue.ToString())
             select new { watch.id }).ToArray().First();

        Watch watchObj = obj.Watch.Find(value.id);
        obj.Watch.Remove(watchObj);
        obj.SaveChanges();

        this.Close();
    }
} // btnDelete_Click
</code>```

and function ShowTable

```<code>public void ShowWatchTable()
{
    obj.Watch.ToList();
    dataGrid.ItemsSource =
        from watch in obj.Watch.Local
        select new
        {
            ID = watch.id,
            Brand = watch.mark,
            Typ = watch.TypeWatch.typeName,
            Price = watch.price + " $".ToString(),
            Quantity = watch.number,
            Fabricator = watch.Fabricator.fName,
            Country = watch.Fabricator.Country.countryName
        };
}
</code>```

When I delete value from database, I still see this value in DataGrid. Only when I close and open this form then I no longer see this object. When I add an element, the same logic is used. Datagrid is updated with the ShowTable function and I see the updated database. But when deleting it it does not work. Please help

答:
From what I can see, you are deleting from obj.Watch using

```<code>obj.Watch.Remove(watchObj);
obj.SaveChanges();
</code>```

but when refreshing your list, you are binding to obj.Watch.Local which I assume is a local cache of your datasource. I don't see where you are syncing this so you might want to sync that before binding or perform your operations on the local sync and ensure that it sends it's changes to the remote data source.

Body:
I have two windows wpf.
On the first window I see data from DataGrid, on the second window I delete object from database.

First window:

private void mnRemoveProduct_Click(object sender, RoutedEventArgs e)
{
   RemoveProduct window = new RemoveProduct();
   window.ShowDialog();
   ShowWatchTable();
} // mnRemoveProduct_Click

Second window:

private void btnDelete_Click(object sender, RoutedEventArgs e)
{
    if (cmbNameOfWatch.SelectedIndex > 0)
    {
        var value =
            (from watch in obj.Watch.Where(w => w.mark == cmbNameOfWatch.SelectedValue.ToString())
             select new { watch.id }).ToArray().First();

        Watch watchObj = obj.Watch.Find(value.id);
        obj.Watch.Remove(watchObj);
        obj.SaveChanges();

        this.Close();
    }
} // btnDelete_Click

and function ShowTable

public void ShowWatchTable()
{
    obj.Watch.ToList();
    dataGrid.ItemsSource =
        from watch in obj.Watch.Local
        select new
        {
            ID = watch.id,
            Brand = watch.mark,
            Typ = watch.TypeWatch.typeName,
            Price = watch.price + " $".ToString(),
            Quantity = watch.number,
            Fabricator = watch.Fabricator.fName,
            Country = watch.Fabricator.Country.countryName
        };
}

When I delete value from database, I still see this value in DataGrid. Only when I close and open this form then I no longer see this object. When I add an element, the same logic is used. Datagrid is updated with the ShowTable function and I see the updated database. But when deleting it it does not work. Please help

Body:
From what I can see, you are deleting from obj.Watch using

obj.Watch.Remove(watchObj);
obj.SaveChanges();

but when refreshing your list, you are binding to obj.Watch.Local which I assume is a local cache of your datasource. I don't see where you are syncing this so you might want to sync that before binding or perform your operations on the local sync and ensure that it sends it's changes to the remote data source.


问:
I have wrong header height when I'm logget Wordpress
I have my own wordpres template where I have a header consisting of two parts and how scrolling the header is scraping up and leaving only the menu..the problem is that when i'm crawled in WordPress the header height is different than when i'm not logged in and i do not know what is cause That's why somebody had a similar case? I need help and I will be grateful for any tips.

enter image description here

答:
Try putting the header in h1 tag and than:

h1 {
  font-size: 40;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h1>My Header<h1></code>```

Body:
Try putting the header in h1 tag and than:

h1 {
  font-size: 40;
}

<h1>My Header<h1>


问:
Linux server, locating files containing nothing but 4 specific lines
I'm dealing with a compromised website, in which hackers injected an htaccess instruction to redirect traffic. I can easily locate .htaccess files that contain the forwarding hack, BUT in cases where the directory already contained an htaccess file, they appended the dangerous instructions, so I cannot just deleted any htaccess file or could harm the site by letting formerly pw-protected directories wide open, or urlrewrite instructions (WordPress) be deleted, etc.
I could not find the way to locate files that only contain those 4 lines of redirect hack, could you shed some light ?
So far, using

find . -type f -exec grep -q targetpiratedomain {} \; -exec echo rm {} \;

Thanks !

答:
Use one of the .htaccess files as template. Then issue the following command:

```<code>find . -type f -name .htaccess -exec cmp -s <template> {} \; -exec rm {} \;
</code>```

cmp will compare the file to the template file and if this returns true, the rm is executed. You might want to test this first with echo or cat instead of rm.

Be sure to rename or move the template file before starting the command, else the template will be removed during the process.

Body:
Use one of the .htaccess files as template. Then issue the following command:

find . -type f -name .htaccess -exec cmp -s <template> {} \; -exec rm {} \;

cmp will compare the file to the template file and if this returns true, the rm is executed. You might want to test this first with echo or cat instead of rm.

Be sure to rename or move the template file before starting the command, else the template will be removed during the process.