问:
Parsing CSV into Struct Array
I am trying to parse CSV into Array of structures. Delimiter is ';'. If you look into the code it seems that I filled only first element of the array out of nine that is 9 lines are in my CSV right now. Remaining elements of the array are just 0. Anyone got some advice? Thanks

```<code>fileTO.open("imput.csv", ios_base :: app);
fileFROM.open("imput.csv", ios_base :: app);

//IntoCsvThruConsole();

// array of structures from csv

string line;

string sID, stype, scategory, samount, sdate;

int lines = CountExistingLines();

Properties * structure = new Properties[lines];
int counter = 0;
int position = 0;

while (getline(fileFROM, line))
    {
        sID = "";
        samount = "";

     for (int i = 0; i < line.size(); i++)
     {
      if (line[i] == ';')
      {
          position++;
          continue;
      }
      switch (position)
      {
          case 0 : sID = sID + line[i];
          break;

          case 1 : structure[counter].type = structure[counter].type + line[i];
          break;

          case 2 : structure[counter].category = structure[counter].category + line[i];
          break;

          case 3 : samount = samount + line[i];
          break;

          case 4 : structure[counter].date = structure[counter].date + line[i];
          break;
      }
     }
     structure[counter].ID = atoi(sID.c_str());
     structure[counter].amount = atoi(samount.c_str());

    cout << "ID zaznamu: " << structure[counter].ID << endl;
    cout << "Typ: " << structure[counter].type << endl;
    cout << "Kategorie: " << structure[counter].category << endl;
    cout << "Castka: " << structure[counter].amount << endl;
    cout << "Datum: " << structure[counter].date << endl;

    counter++;
    }

delete[] structure;
</code>```

I have globally initialized struct correctly and also fstreams. Hope it is enough. Thanks

enter image description here

答:
I recommend using Boost.Spirit for such parsing tasks.

```<code>#include <iostream>
#include <sstream>
#include <string>
#include <vector>

#include <boost/fusion/adapted.hpp>
#include <boost/spirit/home/x3.hpp>

struct Date
{
    int day;
    int month;
    int year;
};

std::ostream& operator<<(std::ostream& os, Date const &d)
{
    os << d.day << '/' << d.month << '/' << d.year;
    return os;
}

BOOST_FUSION_ADAPT_STRUCT(
    Date,
    day, month, year)

struct Properties
{
    int ID;
    std::string type;
    std::string category;
    int amount;
    Date date;
};

BOOST_FUSION_ADAPT_STRUCT(
    Properties,
    ID, type, category, amount, date)

std::vector<Properties> parse(std::string const &input)
{
    auto iter = input.begin();

    using namespace boost::spirit::x3;

    auto name = rule<class name, std::string>{}
        = lexeme[alpha >> *alpha];

    auto date = rule<class date, Date>{}
        = int_ > '/' > int_ > '/' > int_;

    std::vector<Properties> result;

    bool r = phrase_parse(iter, input.end(),
                          (int_ > ';' > name > ';' > name > ';' > int_ > ';' > date) % eol,
                          space - eol, result);

    if (!r)
    {
        std::string rest(iter, input.end());
        throw std::invalid_argument("Parsing failed at " + rest);
    }

    return result;
}

int main()
{
    // This could be a file instead with std::ifstream
    std::istringstream input;
    input.str(
        "1;TypeA;CategoryA;10;05/12/2017\n"
        "2;TypeB;CategoryA;21;04/12/2017\n"
        "3;TypeB;CategoryB;19;01/12/2017\n"
        "4;TypeA;CategoryA; 6;20/11/2017\n");

    std::vector<Properties> entry = parse(input.str());

    for (auto e :  entry)
    {
        std::cout << "Found the following entries:\n"
                  << "  ID: " << e.ID << "\n"
                  << "  Type: " << e.type << "\n"
                  << "  Category: " << e.category << "\n"
                  << "  Amount: " << e.amount << "\n"
                  << "  Date: " << e.date << "\n";
    }
}
</code>```

Live example

Title: Parsing CSV into Struct Array

Body:
I am trying to parse CSV into Array of structures. Delimiter is ';'. If you look into the code it seems that I filled only first element of the array out of nine that is 9 lines are in my CSV right now. Remaining elements of the array are just 0. Anyone got some advice? Thanks

fileTO.open("imput.csv", ios_base :: app);
fileFROM.open("imput.csv", ios_base :: app);

//IntoCsvThruConsole();

// array of structures from csv

string line;

string sID, stype, scategory, samount, sdate;

int lines = CountExistingLines();

Properties * structure = new Properties[lines];
int counter = 0;
int position = 0;

while (getline(fileFROM, line))
    {
        sID = "";
        samount = "";

     for (int i = 0; i < line.size(); i++)
     {
      if (line[i] == ';')
      {
          position++;
          continue;
      }
      switch (position)
      {
          case 0 : sID = sID + line[i];
          break;

          case 1 : structure[counter].type = structure[counter].type + line[i];
          break;

          case 2 : structure[counter].category = structure[counter].category + line[i];
          break;

          case 3 : samount = samount + line[i];
          break;

          case 4 : structure[counter].date = structure[counter].date + line[i];
          break;
      }
     }
     structure[counter].ID = atoi(sID.c_str());
     structure[counter].amount = atoi(samount.c_str());

    cout << "ID zaznamu: " << structure[counter].ID << endl;
    cout << "Typ: " << structure[counter].type << endl;
    cout << "Kategorie: " << structure[counter].category << endl;
    cout << "Castka: " << structure[counter].amount << endl;
    cout << "Datum: " << structure[counter].date << endl;

    counter++;
    }

delete[] structure;

I have globally initialized struct correctly and also fstreams. Hope it is enough. Thanks

enter image description here

Body:
I recommend using Boost.Spirit for such parsing tasks.

#include <iostream>
#include <sstream>
#include <string>
#include <vector>

#include <boost/fusion/adapted.hpp>
#include <boost/spirit/home/x3.hpp>

struct Date
{
    int day;
    int month;
    int year;
};

std::ostream& operator<<(std::ostream& os, Date const &d)
{
    os << d.day << '/' << d.month << '/' << d.year;
    return os;
}

BOOST_FUSION_ADAPT_STRUCT(
    Date,
    day, month, year)

struct Properties
{
    int ID;
    std::string type;
    std::string category;
    int amount;
    Date date;
};

BOOST_FUSION_ADAPT_STRUCT(
    Properties,
    ID, type, category, amount, date)

std::vector<Properties> parse(std::string const &input)
{
    auto iter = input.begin();

    using namespace boost::spirit::x3;

    auto name = rule<class name, std::string>{}
        = lexeme[alpha >> *alpha];

    auto date = rule<class date, Date>{}
        = int_ > '/' > int_ > '/' > int_;

    std::vector<Properties> result;

    bool r = phrase_parse(iter, input.end(),
                          (int_ > ';' > name > ';' > name > ';' > int_ > ';' > date) % eol,
                          space - eol, result);

    if (!r)
    {
        std::string rest(iter, input.end());
        throw std::invalid_argument("Parsing failed at " + rest);
    }

    return result;
}

int main()
{
    // This could be a file instead with std::ifstream
    std::istringstream input;
    input.str(
        "1;TypeA;CategoryA;10;05/12/2017\n"
        "2;TypeB;CategoryA;21;04/12/2017\n"
        "3;TypeB;CategoryB;19;01/12/2017\n"
        "4;TypeA;CategoryA; 6;20/11/2017\n");

    std::vector<Properties> entry = parse(input.str());

    for (auto e :  entry)
    {
        std::cout << "Found the following entries:\n"
                  << "  ID: " << e.ID << "\n"
                  << "  Type: " << e.type << "\n"
                  << "  Category: " << e.category << "\n"
                  << "  Amount: " << e.amount << "\n"
                  << "  Date: " << e.date << "\n";
    }
}

Live example


来源: stackexchange

问:
Laravel Mix common chunk and vendor chunk

I'm building a multipage app with Laravel v5.5 and using Laravel Mix v1.6.2 to compile my assets. I am defining an entry point for each page. I'm extracting vendor modules to a seperate vendor output chunk:

```<code>mix.js('resources/assets/js/page1.js', 'public/js')
.js('resources/assets/js/page2.js', 'public/js')
.extract('vue');
</code>```

What I also want to accomplish is having modules I've written, which are shared between multiple (2 or more) pages/entry-points, automatically extracted to a separate chunk (e.g. commons.js). I can do that with this:

```<code>mix.webpackConfig({
    plugins: [
        new webpack.optimize.CommonsChunkPlugin({
          name: "commons",
          filename: "js/commons.js",
          minChunks: 2
        })
    ]
});
</code>```

But this doesn't work together with mix.extract(). I've seen the examples here. But unsure of how to accomplish this in Laravel Mix.

Ideally the output would be something like:

```<code>js/
 |- page1.js
 |- page2.js
 |- commons.js
 |- vendor.js
</code>```

答:
After having a look though the Laravel Mix source, I realised that the array provided to mix.js().extract() is just being used to create entry points and so rather than use extract() I just used custom config to specify entry points for my node_modules that are being used everywhere, with entry point name matching the chunk name.

```<code>let mix = require('laravel-mix');
let webpack = require('webpack');

mix.js('resources/assets/js/page1.js', 'public/js')
    .js('resources/assets/js/page2.js', 'public/js');

mix.sass('resources/assets/sass/app.scss', 'public/css');

mix.webpackConfig({
    entry: {
        vendor: [
            'vue',
            'axios',
            'lodash',
            'promise-polyfill',
            'setasap'
        ]
    },
    plugins: [
        new webpack.optimize.CommonsChunkPlugin({
            names: ["commons", "vendor"],
            filename: 'js/[name].js',
            minChunks: 2
        })
    ]
});
</code>```

This results in 4 output files:

```<code>js/
 |- page1.js
 |- page2.js
 |- commons.js
 |- vendor.js
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm building a multipage app with Laravel v5.5 and using Laravel Mix v1.6.2 to compile my assets. I am defining an entry point for each page. I'm extracting vendor modules to a seperate vendor output chunk:

mix.js('resources/assets/js/page1.js', 'public/js')
.js('resources/assets/js/page2.js', 'public/js')
.extract('vue');

What I also want to accomplish is having modules I've written, which are shared between multiple (2 or more) pages/entry-points, automatically extracted to a separate chunk (e.g. commons.js). I can do that with this:

mix.webpackConfig({
    plugins: [
        new webpack.optimize.CommonsChunkPlugin({
          name: "commons",
          filename: "js/commons.js",
          minChunks: 2
        })
    ]
});

But this doesn't work together with mix.extract(). I've seen the examples here. But unsure of how to accomplish this in Laravel Mix.

Ideally the output would be something like:

js/
 |- page1.js
 |- page2.js
 |- commons.js
 |- vendor.js

Body:
After having a look though the Laravel Mix source, I realised that the array provided to mix.js().extract() is just being used to create entry points and so rather than use extract() I just used custom config to specify entry points for my node_modules that are being used everywhere, with entry point name matching the chunk name.

let mix = require('laravel-mix');
let webpack = require('webpack');

mix.js('resources/assets/js/page1.js', 'public/js')
    .js('resources/assets/js/page2.js', 'public/js');

mix.sass('resources/assets/sass/app.scss', 'public/css');

mix.webpackConfig({
    entry: {
        vendor: [
            'vue',
            'axios',
            'lodash',
            'promise-polyfill',
            'setasap'
        ]
    },
    plugins: [
        new webpack.optimize.CommonsChunkPlugin({
            names: ["commons", "vendor"],
            filename: 'js/[name].js',
            minChunks: 2
        })
    ]
});

This results in 4 output files:

js/
 |- page1.js
 |- page2.js
 |- commons.js
 |- vendor.js


问:
Proper way to get a specific item by it's property from Doctrine's collections
I'm working with doctrine for the first time in my own project. I'm facing a problem with finding the right object from a collection returned from a doctrine one-to-many relation.

Let's say I have an entity Page which has a lot of Section sub-entities.

```<code>/**
 * @ORM\Entity
 * @ORM\Table(name="Pages")
 */
class Page
{
    // bunch of properties

    /**
     * @ORM\OneToMany(targetEntity="Section", mappedBy="page")
     * @var Collection
     */
    protected $sections;

    public function __construct()
    {
        $this->sections = new ArrayCollection();
    }

    /**
     * @return Collection
     */
    public function getSections(): Collection
    {
        return $this->sections;
    }

}
</code>```

Now what I want to achieve is to be able to get the Section by it's name (I should probably mention that the name is a property of the Section entity).

So at the end I want to be able to achieve something similar to:

```<code>class SomeController
{

    public function HomePageAction()
    {
        $page = $this->getEntityManager()
                     ->getRepository('App:Entity:Page')
                     ->findOneBy(array('name' => 'homepage'));

        $section = $page->findSectionByName('header');

        // rendering etc.
    }

}
</code>```

I can, of course, loop through all of the sections and return one that matches the name I'm looking for (throw the exception if none) or I'm wondering if there isn't some easier way to do that? Also, is it something I should do in some sort of custom repository class, or is it ok to leave the method findSectionByName inside the Entity class? Thank you in advance.

So, what I tried so far...

```<code>// class App\Entity\Page
public function getSectionByName(string $name)
{
    foreach ($this->getSections() as $section) {
        if ($section->getName() === $name)
            return $section;
    }
    return null;
}
</code>```

答:
You can also generate custom repository in your Page entity

```<code> /**
 * @ORM\Entity(repositoryClass="App\Repository\PageRepository")
 */
class Page
{
    ....
}
</code>```

after that in your App\Repository\PageRepository define function that will be get sections by page and section name

```<code>    // App\Repository\PageRepository
    public function getSectionByPageAndName($pageName, $sectionName)
    {
        return $this->getEntityManager()
            ->createQueryBuilder()
            ->select('s')
            ->from(Page::class, 'p')
            ->join(Section::class, 's')
            ->where('p.name = :pageName')
            ->andWhere('s.name = :sectionName')
            ->setParameter('pageName', $pageName)
            ->setParameter('sectionName', $sectionName)
            ->getQuery()
            ->getResult();
    }
</code>```

After that you can you this function easy
over and over again, just in your controllers call function on repository

```<code>class SomeController
{

    public function HomePageAction()
    {
        $sections = $this->getEntityManager()
            ->getRepository('App:Entity:Page')
            ->getSectionByPageAndName($pageName, $sectionName);

        //etc
    }

}
</code>```

cause you relationship is @OneToMany and if sectionName is not unique $sections will be empty array or array of Section objects, If you want to limit to only one result or something else please check docs

Body:
I'm working with doctrine for the first time in my own project. I'm facing a problem with finding the right object from a collection returned from a doctrine one-to-many relation.

Let's say I have an entity Page which has a lot of Section sub-entities.

/**
 * @ORM\Entity
 * @ORM\Table(name="Pages")
 */
class Page
{
    // bunch of properties

    /**
     * @ORM\OneToMany(targetEntity="Section", mappedBy="page")
     * @var Collection
     */
    protected $sections;

    public function __construct()
    {
        $this->sections = new ArrayCollection();
    }

    /**
     * @return Collection
     */
    public function getSections(): Collection
    {
        return $this->sections;
    }

}

Now what I want to achieve is to be able to get the Section by it's name (I should probably mention that the name is a property of the Section entity).

So at the end I want to be able to achieve something similar to:

class SomeController
{

    public function HomePageAction()
    {
        $page = $this->getEntityManager()
                     ->getRepository('App:Entity:Page')
                     ->findOneBy(array('name' => 'homepage'));

        $section = $page->findSectionByName('header');

        // rendering etc.
    }

}

I can, of course, loop through all of the sections and return one that matches the name I'm looking for (throw the exception if none) or I'm wondering if there isn't some easier way to do that? Also, is it something I should do in some sort of custom repository class, or is it ok to leave the method findSectionByName inside the Entity class? Thank you in advance.

So, what I tried so far...

// class App\Entity\Page
public function getSectionByName(string $name)
{
    foreach ($this->getSections() as $section) {
        if ($section->getName() === $name)
            return $section;
    }
    return null;
}

Body:
You can also generate custom repository in your Page entity

 /**
 * @ORM\Entity(repositoryClass="App\Repository\PageRepository")
 */
class Page
{
    ....
}

after that in your App\Repository\PageRepository define function that will be get sections by page and section name

    // App\Repository\PageRepository
    public function getSectionByPageAndName($pageName, $sectionName)
    {
        return $this->getEntityManager()
            ->createQueryBuilder()
            ->select('s')
            ->from(Page::class, 'p')
            ->join(Section::class, 's')
            ->where('p.name = :pageName')
            ->andWhere('s.name = :sectionName')
            ->setParameter('pageName', $pageName)
            ->setParameter('sectionName', $sectionName)
            ->getQuery()
            ->getResult();
    }

After that you can you this function easy
over and over again, just in your controllers call function on repository

class SomeController
{

    public function HomePageAction()
    {
        $sections = $this->getEntityManager()
            ->getRepository('App:Entity:Page')
            ->getSectionByPageAndName($pageName, $sectionName);

        //etc
    }

}

cause you relationship is @OneToMany and if sectionName is not unique $sections will be empty array or array of Section objects, If you want to limit to only one result or something else please check docs


问:
JavaScript Array.splice() method first argument(starting index)
I was reading about .splice() method in MDN. When I got to the first parameter(starting index) I understood all cases but the last one.

What does "and will be set to 0 if absolute value is greater than the length of the array" exactly means?

Parameters

start

  Index at which to start changing the array (with origin 0). If
  greater than the length of the array, actual starting index will be
  set to the length of the array. If negative, will begin that many
  elements from the end of the array (with origin -1) and will be set to
  0 if absolute value is greater than the length of the array.

Link to the documentation

答:
If the absolute value is greater than the array length it will do the same thing as if you passed 0.

var arr = [0, 1, 2, 3, 4, 5, 6];
arr.splice(-8, 1);
// Absolute value is 8, array length is 7
// Because 8 > 7, the first parameter is set to 0
// So this is the same as arr.splice(0, 1);

console.log(arr);```


问:
react native nested fetches
I have to render a list of cards with data. At first step I have to fetch a configured list of IDs. This fetch is relatively fast. And then in the second step I'm fetching the detailed information's for each ID. This second fetch is relatively slow, therefore each card with detailed information has an own spiner.

The IDs and detailed infos are coming from different, asynchronous data sources.

What is the best approach to do that?

I tried to fetch the ID list using redux from container's ComponentDidMount. And then in ComponentDidMount of each Card I'm initiate fetch of detailed informations for each ID. This works.

In the state-object I have then an object which holds all infos like this

```<code>```
{
   "accounts": {
        "id1": { "detailedInfo": "Datailed Info 1", fetching : false },
        "id2": { "detailedInfo": "Datailed Info 2", fetching : false },
        "id3": { "detailedInfo": "", fetching : true },
        ...
   },
   fetching : false,
   error : false
}
```
</code>```

The problem is, if I change one of entries in accounts-map, the whole list is re-rendered.

Is it possible to "bind" each card to it's own entry in props.accounts? So the card is re-rendered only if the particular detailed infos are changed?

This is container for the list

```<code>```
class BalancesContent extends React.Component {

    static propTypes = {
        dispatch: PropTypes.func,
        fetching: PropTypes.bool,
        getAccounts: PropTypes.func,
    };

    constructor(props) {
        super(props);
    }

    componentDidMount() {
        if (this.props.accounts.accounts.length == 0) {
            this.props.getAccounts();
        }
    }

    onRefresh() {
        this.props.getAccounts();
    }

    setState(newState) {
        console.log("bc new state", newState);
        super.setState(newState);
    }

    render() {
        const userCards = this.props.accounts.accounts?Object.keys(this.props.accounts.accounts).map((acc) =>
            <UserBalancesCard
                key={acc}
                account={acc}
                refreshing={false}
                balances={null} />
        ):null;

        return (
            <Content padder
                refreshControl={
                    <RefreshControl
                        refreshing={this.props.accounts.fetching}
                        onRefresh={this.onRefresh.bind(this)}
                        title="Loading..."
                    />
                }>
                <BalancesSummary />
                {userCards}
            </Content>

        )
    }
}

const mapStateToProps = state => {
    return {
        accounts: state.accounts
    };
};

const mapDispatchToProps = dispatch => {
    return {
        getAccounts: () => dispatch(AccountsActions.accountsRequest()),
    };
};
```
</code>```

This is the Component with detailed informations

```<code>```
class UserBalancesCard extends Component {

    static propTypes = {
        dispatch: PropTypes.func,
        fetching: PropTypes.bool,
        updateAccount: PropTypes.func,
    };

    getAccount() {
        return this.props.accounts.accounts[this.props.account];
    }

    componentDidMount() {
        console.log("ubc did mount");
        const acc = this.getAccount();
        if (!(acc.balances.timestamp && acc.balances.timestamp > 0)) {
            this.props.updateAccount(this.props.account);
        }
    }

    render() {
        const acc = this.getAccount();
        console.log("render UBC", this.props.account);
        return (
            <Card style={styles.container}>
                <CardItem header>

{this.props.account}

                </CardItem>
                <BalancesCardItem balances={acc.balances} />
                <CardItem footer>
                    <Right>{acc.fetching && <ActivityIndicator animating={true} size="small" />}</Right>
                </CardItem>
            </Card>
        )
    }
}

const mapStateToProps = state => {
    return {
        accounts: state.accounts
    };
};

const mapDispatchToProps = dispatch => {
    return {
        updateAccount: (account) => dispatch(AccountsActions.balanceRequest(account),),
    };
};

export default connect(mapStateToProps, mapDispatchToProps)(UserBalancesCard);

```
</code>```

答:
When you map a new list to your single components, you change the sate of those components and react starts rendering again. For example if you have a compoennt with this.state.counter = 1 and you call this.setState({counter: 1}) the component will rerender. To check, if the components values changed, you can implement the shouldComponentUpdate() method:

https://reactjs.org/docs/react-component.html#shouldcomponentupdate

Maybe try this in your UserBalanceCard component.

for example something like:

```<code>shouldComponentUpdate(nextProps, nextState) {
    if (nextProps.counter != this.props.counter) return true;
}
</code>```

Title: react native nested fetches

Body:
I have to render a list of cards with data. At first step I have to fetch a configured list of IDs. This fetch is relatively fast. And then in the second step I'm fetching the detailed information's for each ID. This second fetch is relatively slow, therefore each card with detailed information has an own spiner.

The IDs and detailed infos are coming from different, asynchronous data sources.

What is the best approach to do that?

I tried to fetch the ID list using redux from container's ComponentDidMount. And then in ComponentDidMount of each Card I'm initiate fetch of detailed informations for each ID. This works.

In the state-object I have then an object which holds all infos like this

```
{
   "accounts": {
        "id1": { "detailedInfo": "Datailed Info 1", fetching : false },
        "id2": { "detailedInfo": "Datailed Info 2", fetching : false },
        "id3": { "detailedInfo": "", fetching : true },
        ...
   },
   fetching : false,
   error : false
}
```

The problem is, if I change one of entries in accounts-map, the whole list is re-rendered.

Is it possible to "bind" each card to it's own entry in props.accounts? So the card is re-rendered only if the particular detailed infos are changed?

This is container for the list

```
class BalancesContent extends React.Component {

    static propTypes = {
        dispatch: PropTypes.func,
        fetching: PropTypes.bool,
        getAccounts: PropTypes.func,
    };

    constructor(props) {
        super(props);
    }

    componentDidMount() {
        if (this.props.accounts.accounts.length == 0) {
            this.props.getAccounts();
        }
    }

    onRefresh() {
        this.props.getAccounts();
    }

    setState(newState) {
        console.log("bc new state", newState);
        super.setState(newState);
    }

    render() {
        const userCards = this.props.accounts.accounts?Object.keys(this.props.accounts.accounts).map((acc) =>
            <UserBalancesCard
                key={acc}
                account={acc}
                refreshing={false}
                balances={null} />
        ):null;

        return (
            <Content padder
                refreshControl={
                    <RefreshControl
                        refreshing={this.props.accounts.fetching}
                        onRefresh={this.onRefresh.bind(this)}
                        title="Loading..."
                    />
                }>
                <BalancesSummary />
                {userCards}
            </Content>

        )
    }
}

const mapStateToProps = state => {
    return {
        accounts: state.accounts
    };
};

const mapDispatchToProps = dispatch => {
    return {
        getAccounts: () => dispatch(AccountsActions.accountsRequest()),
    };
};
```

This is the Component with detailed informations

```
class UserBalancesCard extends Component {

    static propTypes = {
        dispatch: PropTypes.func,
        fetching: PropTypes.bool,
        updateAccount: PropTypes.func,
    };

    getAccount() {
        return this.props.accounts.accounts[this.props.account];
    }

    componentDidMount() {
        console.log("ubc did mount");
        const acc = this.getAccount();
        if (!(acc.balances.timestamp && acc.balances.timestamp > 0)) {
            this.props.updateAccount(this.props.account);
        }
    }

    render() {
        const acc = this.getAccount();
        console.log("render UBC", this.props.account);
        return (
            <Card style={styles.container}>
                <CardItem header>
                    <H1>{this.props.account}</H1>
                </CardItem>
                <BalancesCardItem balances={acc.balances} />
                <CardItem footer>
                    <Right>{acc.fetching && <ActivityIndicator animating={true} size="small" />}</Right>
                </CardItem>
            </Card>
        )
    }
}

const mapStateToProps = state => {
    return {
        accounts: state.accounts
    };
};

const mapDispatchToProps = dispatch => {
    return {
        updateAccount: (account) => dispatch(AccountsActions.balanceRequest(account),),
    };
};

export default connect(mapStateToProps, mapDispatchToProps)(UserBalancesCard);

```

Body:
When you map a new list to your single components, you change the sate of those components and react starts rendering again. For example if you have a compoennt with this.state.counter = 1 and you call this.setState({counter: 1}) the component will rerender. To check, if the components values changed, you can implement the shouldComponentUpdate() method:

https://reactjs.org/docs/react-component.html#shouldcomponentupdate

Maybe try this in your UserBalanceCard component.

for example something like:

shouldComponentUpdate(nextProps, nextState) {
    if (nextProps.counter != this.props.counter) return true;
}


问:
Get camera field of view in iOS 11 ARKit
I'm using a ARSCNView from ARKit to display live a video feed from the camera on the iPad. I have the ARSCNView object setup exactly as Xcode's Augmented Reality App template. I was wondering if there is a way to get the field of view of the camera?</p>

```<code>@IBOutlet var sceneView: ARSCNView!

func start() {
    sceneView.delegate = self
    sceneView.session.run(ARWorldTrackingConfiguration())
    // Retrieve camera FOV here
}
</code>```

答:
There are a couple of ways to go here, and a possible false start to beware of.

⚠ ARKit + SceneKit (incorrect)

If you're already working with ARKit via SceneKit (ARSCNView), you might assume that ARKit is automatically updating the SceneKit camera (the view's pointOfView's camera) to match the projection transform used by ARKit. This is correct.

However, ARKit directly sets the SCNCamera's projectionTransform. When you work with geometric properties of SCNCamera like zNear and zFar and fieldOfView, SceneKit derives a projection matrix for use in rendering. But if you set projectionTransform directly, there's no math that can recover the near/far and xFov/yFov values, so the corresponding SCNCamera properties are invalid. That is, sceneView.pointOfView.camera.fieldOfView and similar APIs always return bogus results for an ARKit app.

So, what can you do instead? Read on...

Projection Matrix

An AR session continually vends ARFrame objects through its delegate, or you can request the currentFrame from it. Each frame has an ARCamera attached that describes the imaging parameters, one of which is a projectionMatrix that's dependent on field of view. (There's also the aforementioned SceneKit projectionTransform, which is the same matrix.)

A standard 3D projection matrix includes scaling terms that are based on the vertical field of view and aspect ratio. Specifically, the matrix looks like this:

```<code>[ xScale    0     0    0  ]   xScale = yScale * aspectRatio (width/height)
[   0    yScale   0    0  ]   yScale = 1 / tan(yFov/2)
[   0       0    nf1  nf2 ]   nf1 and nf2 relate to near and far clip planes,
[   0       0     -1   0  ]     so aren't relevant to field of view
</code>```

So you should be able to get yFov by solving the yScale equation:

```<code>let projection = session.currentFrame!.camera.projectionMatrix
let yScale = projection[1,1]
let yFov = 2 * atan(1/yScale) // in radians
let yFovDegrees = yFov * 180/Float.pi
</code>```

And for horizontal field of view, you can multiply by the aspect ratio (specifically, the width/height ratio):

```<code>let imageResolution = session.currentFrame!.camera.imageResolution
let xFov = yFov * Float(imageResolution.width / imageResolution.height)
</code>```

Note: Here, "horizontal" and "vertical" are with respect to the camera image, which is natively in landscape orientation regardless of how your device or AR view UI are oriented.

If you look closely, though, you might notice that the aspect ratio between xFov/yFov here (and the aspect ratio of imageResolution) don't necessarily match that of your device screen (especially on iPhone X) or the view you're drawing AR content in. That's because you've measured the FOV angles of the camera image, not those of your app's AR view. Don't worry, there's an API for that, too...

Projection Matrix with Viewport

ARCamera offers two APIs for getting a projection matrix. Besides the one we just went over, there's also projectionMatrix(for:viewportSize:zNear:zFar:), which takes presentation into account. If you want to match not the FOV of the camera, but the FOV of how ARSCNView or ARSKView (or Unity or Unreal, probably?) render your AR scene, use this, passing the device orientation and see of your view. Then do all the same math as above:

```<code>let imageResolution = session.currentFrame!.camera.imageResolution
let viewSize = sceneView.bounds.size
let projection = session.currentFrame!.camera.projectionMatrix(for: .portrait,
    viewportSize: viewSize, zNear: zNear, zFar: zFar)
let yScale = projection[1,1] // = 1/tan(fovy/2)
let yFovDegrees = 2 * atan(1/yScale) * 180/Float.pi
let xFovDegrees = yFovDegrees * Float(viewSize.height / viewSize.width)
</code>```

What you pass for zNear and zFar doesn't matter, since we're not using the parts of the matrix that depend on that. (You might still need to ensure zNear < zFar and zNear != zFar != 0.)

Note: Now the height/width are based on your view (or rather, the attributes of your view that you pass to projectionMatrix(for:...)). In this example, yFov is vertical with respect to the UI because the orientation is portrait, so you multiply by the height/width aspect ratio to get xFov. If you're in landscape, you multiply by width/height instead.

Camera Intrinsics

Keen observers may have noticed that the above calculations ignore parts of the projection matrix. That's because the definition of FOV angle is an optical property of the camera, not anything to do with 3D projection, so a whole projection matrix is an intermediate result you might not really need.

ARCamera also exposes an intrinsics matrix that describes optical properties of the camera. The first and second values along the diagonal in this matrix are the horizontal and vertical focal length of a single pixel in the camera image. If you have focal length and image width/height, you can compute FOV per the definition of FOV angle:

```<code>let imageResolution = session.currentFrame!.camera.imageResolution
let intrinsics = session.currentFrame!.camera.intrinsics
let xFovDegrees = 2 * atan(Float(imageResolution.width)/(2 * intrinsics[0,0])) * 180/Float.pi
let yFovDegrees = 2 * atan(Float(imageResolution.height)/(2 * intrinsics[1,1])) * 180/Float.pi
</code>```

Note: Like the version that uses projectionMatrix, this is based on the size and always-landscape orientation of the camera image, not the device screen or the view you're displaying AR content in. If you need something based on the viewport instead, scroll back up to "Projection Matrix with Viewport".

Body:
I'm using a ARSCNView from ARKit to display live a video feed from the camera on the iPad. I have the ARSCNView object setup exactly as Xcode's Augmented Reality App template. I was wondering if there is a way to get the field of view of the camera?

@IBOutlet var sceneView: ARSCNView!

func start() {
    sceneView.delegate = self
    sceneView.session.run(ARWorldTrackingConfiguration())
    // Retrieve camera FOV here
}

Body:
There are a couple of ways to go here, and a possible false start to beware of.

⚠ ARKit + SceneKit (incorrect)

If you're already working with ARKit via SceneKit (ARSCNView), you might assume that ARKit is automatically updating the SceneKit camera (the view's pointOfView's camera) to match the projection transform used by ARKit. This is correct.

However, ARKit directly sets the SCNCamera's projectionTransform. When you work with geometric properties of SCNCamera like zNear and zFar and fieldOfView, SceneKit derives a projection matrix for use in rendering. But if you set projectionTransform directly, there's no math that can recover the near/far and xFov/yFov values, so the corresponding SCNCamera properties are invalid. That is, sceneView.pointOfView.camera.fieldOfView and similar APIs always return bogus results for an ARKit app.

So, what can you do instead? Read on...

Projection Matrix

An AR session continually vends ARFrame objects through its delegate, or you can request the currentFrame from it. Each frame has an ARCamera attached that describes the imaging parameters, one of which is a projectionMatrix that's dependent on field of view. (There's also the aforementioned SceneKit projectionTransform, which is the same matrix.)

A standard 3D projection matrix includes scaling terms that are based on the vertical field of view and aspect ratio. Specifically, the matrix looks like this:

[ xScale    0     0    0  ]   xScale = yScale * aspectRatio (width/height)
[   0    yScale   0    0  ]   yScale = 1 / tan(yFov/2)
[   0       0    nf1  nf2 ]   nf1 and nf2 relate to near and far clip planes,
[   0       0     -1   0  ]     so aren't relevant to field of view

So you should be able to get yFov by solving the yScale equation:

let projection = session.currentFrame!.camera.projectionMatrix
let yScale = projection[1,1]
let yFov = 2 * atan(1/yScale) // in radians
let yFovDegrees = yFov * 180/Float.pi

And for horizontal field of view, you can multiply by the aspect ratio (specifically, the width/height ratio):

let imageResolution = session.currentFrame!.camera.imageResolution
let xFov = yFov * Float(imageResolution.width / imageResolution.height)

Note: Here, "horizontal" and "vertical" are with respect to the camera image, which is natively in landscape orientation regardless of how your device or AR view UI are oriented.

If you look closely, though, you might notice that the aspect ratio between xFov/yFov here (and the aspect ratio of imageResolution) don't necessarily match that of your device screen (especially on iPhone X) or the view you're drawing AR content in. That's because you've measured the FOV angles of the camera image, not those of your app's AR view. Don't worry, there's an API for that, too...

Projection Matrix with Viewport

ARCamera offers two APIs for getting a projection matrix. Besides the one we just went over, there's also projectionMatrix(for:viewportSize:zNear:zFar:), which takes presentation into account. If you want to match not the FOV of the camera, but the FOV of how ARSCNView or ARSKView (or Unity or Unreal, probably?) render your AR scene, use this, passing the device orientation and see of your view. Then do all the same math as above:

let imageResolution = session.currentFrame!.camera.imageResolution
let viewSize = sceneView.bounds.size
let projection = session.currentFrame!.camera.projectionMatrix(for: .portrait,
    viewportSize: viewSize, zNear: zNear, zFar: zFar)
let yScale = projection[1,1] // = 1/tan(fovy/2)
let yFovDegrees = 2 * atan(1/yScale) * 180/Float.pi
let xFovDegrees = yFovDegrees * Float(viewSize.height / viewSize.width)

What you pass for zNear and zFar doesn't matter, since we're not using the parts of the matrix that depend on that. (You might still need to ensure zNear < zFar and zNear != zFar != 0.)

Note: Now the height/width are based on your view (or rather, the attributes of your view that you pass to projectionMatrix(for:...)). In this example, yFov is vertical with respect to the UI because the orientation is portrait, so you multiply by the height/width aspect ratio to get xFov. If you're in landscape, you multiply by width/height instead.

Camera Intrinsics

Keen observers may have noticed that the above calculations ignore parts of the projection matrix. That's because the definition of FOV angle is an optical property of the camera, not anything to do with 3D projection, so a whole projection matrix is an intermediate result you might not really need.

ARCamera also exposes an intrinsics matrix that describes optical properties of the camera. The first and second values along the diagonal in this matrix are the horizontal and vertical focal length of a single pixel in the camera image. If you have focal length and image width/height, you can compute FOV per the definition of FOV angle:

let imageResolution = session.currentFrame!.camera.imageResolution
let intrinsics = session.currentFrame!.camera.intrinsics
let xFovDegrees = 2 * atan(Float(imageResolution.width)/(2 * intrinsics[0,0])) * 180/Float.pi
let yFovDegrees = 2 * atan(Float(imageResolution.height)/(2 * intrinsics[1,1])) * 180/Float.pi

Note: Like the version that uses projectionMatrix, this is based on the size and always-landscape orientation of the camera image, not the device screen or the view you're displaying AR content in. If you need something based on the viewport instead, scroll back up to "Projection Matrix with Viewport".

ContentLicense: CC BY-SA 4.0


问:
.ondragstart not equivalent to .addEventListener("dragstart"
I want to make an img element unselectable and undraggable because I'm using it as a window resizing control (clicking and dragging on the surrounding div resizes a window).

It works perfectly fine as the following:

```<code>noSelect[x].ondragstart = function() {return false};
</code>```

But since this will be used in a firefox(3.6.*) extension which uses an XPCNativeWrapper around every HTMLElement, I cannot use ".onsdragstart" and have to use ".addEventListener"

The problem is the equivalent to the above code isn't working. Clicking and dragging the img triggers firefox's default image dragging, instead of resizing my window in the following:

```<code>noSelect[x].addEventListener("dragstart", function () {return false}, false)
</code>```

Are the two lines of code quoted above not equivalent?

Full context for unselectable objects:

```<code>var noSelect = document.getElementsByClassName("noSelect")
    for (x in noSelect) {
        if (x == "length")
            break
        noSelect[x].unselectable = "on";
        noSelect[x].onselectstart = function(){return false};
        noSelect[x].ondragstart = function() {return false};
        noSelect[x].style.userSelect = "none"; // w3c standard
        noSelect[x].style.MozUserSelect = "none"; // Firefox
    }
</code>```

答: I don't know why function() { return false; } doesn't work, but I do know that function(event) { event.preventDefault(); } will work in Firefox.

Body:
I want to make an img element unselectable and undraggable because I'm using it as a window resizing control (clicking and dragging on the surrounding div resizes a window).

It works perfectly fine as the following:

noSelect[x].ondragstart = function() {return false};

But since this will be used in a firefox(3.6.*) extension which uses an XPCNativeWrapper around every HTMLElement, I cannot use ".onsdragstart" and have to use ".addEventListener"

The problem is the equivalent to the above code isn't working. Clicking and dragging the img triggers firefox's default image dragging, instead of resizing my window in the following:

noSelect[x].addEventListener("dragstart", function () {return false}, false)

Are the two lines of code quoted above not equivalent?

Full context for unselectable objects:

var noSelect = document.getElementsByClassName("noSelect")
    for (x in noSelect) {
        if (x == "length")
            break
        noSelect[x].unselectable = "on";
        noSelect[x].onselectstart = function(){return false};
        noSelect[x].ondragstart = function() {return false};
        noSelect[x].style.userSelect = "none"; // w3c standard
        noSelect[x].style.MozUserSelect = "none"; // Firefox
    }

ContentLicense: CC BY-SA 2.5


问:
How to get my photos in the center
How do I make these photos all go in the center of the webpage? this is my html code</p>

```<code><html>
<body>
    <div id="travel_photos">
      <img style="display: inline; margin: 0 10px; title="branson" src="branson.jpg" alt="" width="150" height="50"/>
      <img style="display: inline; margin: 0 10px; title="cancun" src="cancun.jpg" alt="" width="150" height="50"/>
      <img style="display: inline; margin: 0 10px; title="denver" src="denver.png" alt="" width="150" height="50"/>
      <img style="display: inline; margin: 0 10px; title="destin" src="destin.png" alt="" width="150" height="50"/>
      <img style="display: inline; margin: 0 10px; title="PV" src="PV.png" alt="" width="150" height="50"/>

</body>
</html>
</code>```

答:
If you're trying to center the images horizontally, try this: https://jsfiddle.net/a5u3q1w5/2/

HTML:

```<code><div id="travel_photos">
    <img title="branson" src="http://www.catster.com/wp-content/uploads/2017/08/A-fluffy-cat-looking-funny-surprised-or-concerned.jpg"/>
    <img title="branson" src="http://www.petmd.com/sites/default/files/petmd-cat-happy-13.jpg"/>
    <img title="branson" src="https://static.pexels.com/photos/126407/pexels-photo-126407.jpeg"/>
</div>
</code>```

CSS:

```<code>#travel_photos > img {
  width: 300px;
  height: 100px;
  margin: 0 auto;
  display: block;
}
</code>```

Title: How to get my photos in the center

Body:
If you're trying to center the images horizontally, try this: https://jsfiddle.net/a5u3q1w5/2/

HTML:

<div id="travel_photos">
    <img title="branson" src="http://www.catster.com/wp-content/uploads/2017/08/A-fluffy-cat-looking-funny-surprised-or-concerned.jpg"/>
    <img title="branson" src="http://www.petmd.com/sites/default/files/petmd-cat-happy-13.jpg"/>
    <img title="branson" src="https://static.pexels.com/photos/126407/pexels-photo-126407.jpeg"/>
</div>

CSS:

#travel_photos > img {
  width: 300px;
  height: 100px;
  margin: 0 auto;
  display: block;
}


问:
django form textarea allow vertical resize only
in my django project I made a form using

```<code>message = forms.CharField(widget=forms.Textarea)
</code>```

It works out ok and I get this. The text area is resizeable both horizontally and vertically:

I would like to make it un-resizeable horizontally, what should I do? I tried adding "attrs=" to the textarea but can't figure out what to call... Please help... Thanks.

答:
I believe you can achieve this with a css rule:

```<code>resize: vertical;
</code>```

So, one way is to give it a class

```<code>message = forms.CharField(widget=forms.TextArea(attrs={"class": "message"}))
</code>```

Then define a css rule

```<code>.message{
    resize: vertical;
}
</code>```

Body:
in my django project I made a form using

message = forms.CharField(widget=forms.Textarea)

It works out ok and I get this. The text area is resizeable both horizontally and vertically:

I would like to make it un-resizeable horizontally, what should I do? I tried adding "attrs=" to the textarea but can't figure out what to call... Please help... Thanks.

Body:
I believe you can achieve this with a css rule:

resize: vertical;

So, one way is to give it a class

message = forms.CharField(widget=forms.TextArea(attrs={"class": "message"}))

Then define a css rule

.message{
    resize: vertical;
}


问:
How to set some dropout when training a neural network using MxNet?
When training a Deep Convolutional Neural Network using MxNet, what is the simplest way to turn on some amount of dropout in order to reduce overfitting? Is there a way to add a dropout rate without manually implementing dropout in the network architecture?</p>

答:
Yes you can set the dropout rate.
The dropout layer API is here: https://mxnet.incubator.apache.org/api/python/symbol/symbol.html?highlight=dropout#mxnet.symbol.Dropout

Where p is the dropout rate.


问:
I noticed the prefix 'sd:' in front some of the properties in log4j2.xml -- what do they stand for?
I need to configure Log4j 2.x logging with encryption key (AES). I have this part in the log4j2.xml:

```<code><Encryption keyId="${sd:encryptionKeyId}" key="${sd:encryptionKey}">
    ....
</Encryption>
</code>```

For testing purposes, I used an online generation tool to generate an AES key and I put it directly there instead of ${sd:encryptionKey}. It worked, ie. I didn't get any exceptions.

Then I wanted to move the key up to the properties, like so:

```<code><Property name="sd:encryptionKey">---my key here---</Property>
</code>```

It didn't work. I removed the sd: prefix and it worked again.

My question is: What does this prefix stand for and is setting the key directly in this file as a property the right way to do it?

答:
The ${sd:... prefix is for Log4j2’s built in Structured Data lookup.

From the manual:

The StructuredDataLookup is very similar to the MapLookup in that it will retrieve values from StructuredDataMessages.

Log4j2 offers other lookups so you could get items from system properties, environment variables, the Log4j2 thread context map etc.

It’s also easy to build a custom lookup that gets data from your application.

Important: a lookup needs the dollar and curly braces to work.

For the purpose of what you’re trying to achieve I would define a simple property like you’re doing in your question but perhaps put the key in an environment variable to prevent other people from discovering the key by reading the log configuration.

Defining environment variables is OS-specific but in Linux you could do it in your ~/profile, in Windows you’d go to Control Panel > System > Advanced > Environment variables.

Then use the environment variable lookup to allow Log4j2 to get the value.

```<code><Property name="encryptionKey">${env:MY_AES_KEY}</Property>
</code>```

Body:
I need to configure Log4j 2.x logging with encryption key (AES). I have this part in the log4j2.xml:

<Encryption keyId="${sd:encryptionKeyId}" key="${sd:encryptionKey}">
    ....
</Encryption>

For testing purposes, I used an online generation tool to generate an AES key and I put it directly there instead of ${sd:encryptionKey}. It worked, ie. I didn't get any exceptions.

Then I wanted to move the key up to the properties, like so:

<Property name="sd:encryptionKey">---my key here---</Property>

It didn't work. I removed the sd: prefix and it worked again.

My question is: What does this prefix stand for and is setting the key directly in this file as a property the right way to do it?

Body:
The ${sd:... prefix is for Log4j2’s built in Structured Data lookup.

From the manual:

The StructuredDataLookup is very similar to the MapLookup in that it will retrieve values from StructuredDataMessages.

Log4j2 offers other lookups so you could get items from system properties, environment variables, the Log4j2 thread context map etc.

It’s also easy to build a custom lookup that gets data from your application.

Important: a lookup needs the dollar and curly braces to work.

For the purpose of what you’re trying to achieve I would define a simple property like you’re doing in your question but perhaps put the key in an environment variable to prevent other people from discovering the key by reading the log configuration.

Defining environment variables is OS-specific but in Linux you could do it in your ~/profile, in Windows you’d go to Control Panel > System > Advanced > Environment variables.

Then use the environment variable lookup to allow Log4j2 to get the value.

<Property name="encryptionKey">${env:MY_AES_KEY}</Property>


问:
How to transfer complex classes in web api 2 without using extensions?
I'm a tadbit unsure on how complex classes can be transfreed in web api 2.
Almost every example I find is about the old json post class (which no longer exists). For the new Version I don't find that much. Especially when it Comes to complex classes. Almost all of These examples use extensions like the NewtonSoft... .

So my question is: For the example below is there any way (aside from putting a converter into the class that transforms it into a string and back into a class from a string) to Transfer it in a post without having to rely on extensions?

Server example:

```<code>public async Task<IHttpActionResult> DeviceConnect([FromBody]MyDevice device)
{
     ...... // device is to be used and should be transferred from the client
}
</code>```

Client example:

```<code>var cont = new MyDevice();

HttpResponseMessage rb = await client.PostAsync(@"http://localhost:34326/Api/Updater", cont);
</code>```

What I tired already (and naturally failed as it would only convert the Name of the class):

```<code>var a1= new MyDevice("MyTestDevice", "a");
var cont = new StringContent(a1.ToString(), Encoding.UTF8, "application/json");
</code>```

MyDevice has the following layout:

```<code>public class MyDevice
{
    private EnumClient _Client;
    private string _Office;
    private string _DeviceNumber;
    private List<InstalledProgram> _InstalledPrograms;

    public List<InstalledProgram> InstalledPrograms{ get => _InstalledPrograms; set => _InstalledPrograms= value; }
    public string DeviceNumber { get => _DeviceNumber; set => _DeviceNumber = value; }
    public EnumClient Client { get => _Client; set => _Client = value; }
    public string Office { get => _Office; set => _Office = value; }

}
</code>```

InstalledPrograms has only a few properties (string Name, string Version).

答:
The issue is how you are serializing your class to send as StringContent. You need to serialize it as a json string instead of just using the ToString method. The code below uses the Newtonsoft.Json nuget package.

```<code>var cont = new StringContent(JsonConvert.SerializeObject(a1), Encoding.UTF8, "application/json");
</code>```

Body:
I'm a tadbit unsure on how complex classes can be transfreed in web api 2.
Almost every example I find is about the old json post class (which no longer exists). For the new Version I don't find that much. Especially when it Comes to complex classes. Almost all of These examples use extensions like the NewtonSoft... .

So my question is: For the example below is there any way (aside from putting a converter into the class that transforms it into a string and back into a class from a string) to Transfer it in a post without having to rely on extensions?

Server example:

public async Task<IHttpActionResult> DeviceConnect([FromBody]MyDevice device)
{
     ...... // device is to be used and should be transferred from the client
}

Client example:

var cont = new MyDevice();

HttpResponseMessage rb = await client.PostAsync(@"http://localhost:34326/Api/Updater", cont);

What I tired already (and naturally failed as it would only convert the Name of the class):

var a1= new MyDevice("MyTestDevice", "a");
var cont = new StringContent(a1.ToString(), Encoding.UTF8, "application/json");

MyDevice has the following layout:

public class MyDevice
{
    private EnumClient _Client;
    private string _Office;
    private string _DeviceNumber;
    private List<InstalledProgram> _InstalledPrograms;

    public List<InstalledProgram> InstalledPrograms{ get => _InstalledPrograms; set => _InstalledPrograms= value; }
    public string DeviceNumber { get => _DeviceNumber; set => _DeviceNumber = value; }
    public EnumClient Client { get => _Client; set => _Client = value; }
    public string Office { get => _Office; set => _Office = value; }

}

InstalledPrograms has only a few properties (string Name, string Version).

Body:
The issue is how you are serializing your class to send as StringContent. You need to serialize it as a json string instead of just using the ToString method. The code below uses the Newtonsoft.Json nuget package.

var cont = new StringContent(JsonConvert.SerializeObject(a1), Encoding.UTF8, "application/json");


问:
Scala: Main method not found in class
I am new to scala and java.
I am writing the below code for K-Means clustering but getting the below error :

```<code>Error: Main method not found in class kmeans, please define the main method as:
   public static void main(String[] args)
or a JavaFX application class must extend javafx.application.Application
</code>```

Kindly help me to overcome this issue.

My .scala code :

```<code>object kmeans {

  import scala.math.pow
  import org.apache.spark.SparkContext
  import org.apache.spark.SparkConf

  def distanceSquared(p1: (Double, Double), p2: (Double, Double)) = {
    pow(p1._1 - p2._1, 2) + pow(p1._2 - p2._2, 2)
  }

  def addPoints(p1: (Double, Double), p2: (Double, Double)) = {
    (p1._1 + p2._1, p1._2 + p2._2)
  }

  def closestPoint(p: (Double, Double), points: Array[(Double, Double)]): Int = {
    var index = 0
    var bestIndex = 0
    var closest = Double.PositiveInfinity

    for (i <- 0 until points.length) {
      val dist = distanceSquared(p, points(i))
      if (dist < closest) {
        closest = dist
        bestIndex = i
      }
    }
    bestIndex
  }

  def main(args: Array[String]) {

    val conf = new SparkConf().setAppName("First Scala app").setMaster("local[*]")
    val sc = new SparkContext(conf)

    val filename = "loudacre/*"

    val K = 5

    val convergeDist = .1

    val fileRdd = sc.textFile(filename)
    val pairLatLongRdd = fileRdd.map(line => line.split(',')).map(pair => (pair(3).toDouble, pair(4).toDouble)).filter(point => !((point._1 == 0) && (point._2 == 0))).
      persist()

    println(pairLatLongRdd.count())

    for ((a, b) <- pairLatLongRdd.take(2)) {

      println("Lat: " + a + " Long : " + b);

    }

    var kPoints = pairLatLongRdd.takeSample(false, K, 42)

    println("K Center points initialized :");

    for ((a, b) <- kPoints) {

      println("Lat: " + a + " Long : " + b);

    }
    var tempDist = Double.PositiveInfinity

    while (tempDist > convergeDist) {

      val closestToKpointRdd = pairLatLongRdd.map(point => (closestPoint(point, kPoints), (point, 1)))

      val pointCalculatedRdd = closestToKpointRdd.reduceByKey { case ((point1, n1), (point2, n2)) => (addPoints(point1, point2), n1 + n2) }

      val newPoints = pointCalculatedRdd.map { case (i, (point, n)) => (i, (point._1 / n, point._2 / n)) }.collectAsMap()

      tempDist = 0.0

      for (i <- 0 until K) {
        tempDist += distanceSquared(kPoints(i), newPoints(i))

      }

      println("Distance between iterations: " + tempDist);

      for (i <- 0 until K) {

        kPoints(i) = newPoints(i)

      }
    }

    println("Final center points :");

    for (point <- kPoints) {
      println(point);
    }

    val deviceRdd = fileRdd.map(line => line.split(',')).map(pair => (pair(1), (pair(3).toDouble, pair(4).toDouble))).filter(device => !((device._2._1 == 0) && (device._2._2 == 0))).
      persist()

    var points = deviceRdd.takeSample(false, 10, 42)

    for ((device, point) <- points) {

      val k = closestPoint(point, kPoints)
      println("device: " + device + " to K: " + k);

    }

    sc.stop()
  }

}
</code>```

答: You may be missing = after your main declaration.</p>

Title: Scala: Main method not found in class

Body:
I am new to scala and java.
I am writing the below code for K-Means clustering but getting the below error :

Error: Main method not found in class kmeans, please define the main method as:
   public static void main(String[] args)
or a JavaFX application class must extend javafx.application.Application

Kindly help me to overcome this issue.

My .scala code :

object kmeans {

  import scala.math.pow
  import org.apache.spark.SparkContext
  import org.apache.spark.SparkConf

  def distanceSquared(p1: (Double, Double), p2: (Double, Double)) = {
    pow(p1._1 - p2._1, 2) + pow(p1._2 - p2._2, 2)
  }

  def addPoints(p1: (Double, Double), p2: (Double, Double)) = {
    (p1._1 + p2._1, p1._2 + p2._2)
  }

  def closestPoint(p: (Double, Double), points: Array[(Double, Double)]): Int = {
    var index = 0
    var bestIndex = 0
    var closest = Double.PositiveInfinity

    for (i <- 0 until points.length) {
      val dist = distanceSquared(p, points(i))
      if (dist < closest) {
        closest = dist
        bestIndex = i
      }
    }
    bestIndex
  }

  def main(args: Array[String]) {

    val conf = new SparkConf().setAppName("First Scala app").setMaster("local[*]")
    val sc = new SparkContext(conf)

    val filename = "loudacre/*"

    val K = 5

    val convergeDist = .1

    val fileRdd = sc.textFile(filename)
    val pairLatLongRdd = fileRdd.map(line => line.split(',')).map(pair => (pair(3).toDouble, pair(4).toDouble)).filter(point => !((point._1 == 0) && (point._2 == 0))).
      persist()

    println(pairLatLongRdd.count())

    for ((a, b) <- pairLatLongRdd.take(2)) {

      println("Lat: " + a + " Long : " + b);

    }

    var kPoints = pairLatLongRdd.takeSample(false, K, 42)

    println("K Center points initialized :");

    for ((a, b) <- kPoints) {

      println("Lat: " + a + " Long : " + b);

    }
    var tempDist = Double.PositiveInfinity

    while (tempDist > convergeDist) {

      val closestToKpointRdd = pairLatLongRdd.map(point => (closestPoint(point, kPoints), (point, 1)))

      val pointCalculatedRdd = closestToKpointRdd.reduceByKey { case ((point1, n1), (point2, n2)) => (addPoints(point1, point2), n1 + n2) }

      val newPoints = pointCalculatedRdd.map { case (i, (point, n)) => (i, (point._1 / n, point._2 / n)) }.collectAsMap()

      tempDist = 0.0

      for (i <- 0 until K) {
        tempDist += distanceSquared(kPoints(i), newPoints(i))

      }

      println("Distance between iterations: " + tempDist);

      for (i <- 0 until K) {

        kPoints(i) = newPoints(i)

      }
    }

    println("Final center points :");

    for (point <- kPoints) {
      println(point);
    }

    val deviceRdd = fileRdd.map(line => line.split(',')).map(pair => (pair(1), (pair(3).toDouble, pair(4).toDouble))).filter(device => !((device._2._1 == 0) && (device._2._2 == 0))).
      persist()

    var points = deviceRdd.takeSample(false, 10, 42)

    for ((device, point) <- points) {

      val k = closestPoint(point, kPoints)
      println("device: " + device + " to K: " + k);

    }

    sc.stop()
  }

}


问:
GROUP BY and mysql 5.7
I've recently migrated to mysql 5.7. All queries with "GROUP BY" does not work anymore.

It will helpfull if someone could help me to write this one :

```<code>SELECT * FROM visitors WHERE visitor_country = :visitor_country GROUP BY visitor_ip ORDER BY visitor_date ASC
</code>```

Thanks,

Have a nice day,

答:
Pre-5.7, your query was selecting arbitrary values for date/country/region/etc from those for each visitor_id/visitor_ip, which is presumably not what you wanted.  Starting with 5.7, you need to be explicit about what values you want to return.  You can just be explicit:

```<code>SELECT visitor_id, MAX(visitor_date), MAX(visitor_country), MAX(visitor_region), MAX(visitor_city), MAX(visitor_postcode), MAX(visitor_latitude), MAX(visitor_ip)
FROM visitors
WHERE visitor_country =: visitor_country
GROUP BY visitor_id, visitor_ip
ORDER BY MAX(visitor_date) ASC
</code>```

Or you can revert to the pre-5.7 settings (even if you can't change the global server settings) by doing

```<code>SET SESSION sql_mode = 'NO_ENGINE_SUBSTITUTION';
</code>```

after connecting to the database.  Though if you are using auto-reconnect, you may want to do it before each problematic query.

Title: GROUP BY and mysql 5.7

Body:
I've recently migrated to mysql 5.7. All queries with "GROUP BY" does not work anymore.

It will helpfull if someone could help me to write this one :

SELECT * FROM visitors WHERE visitor_country = :visitor_country GROUP BY visitor_ip ORDER BY visitor_date ASC

Thanks,

Have a nice day,

Body:
Pre-5.7, your query was selecting arbitrary values for date/country/region/etc from those for each visitor_id/visitor_ip, which is presumably not what you wanted.  Starting with 5.7, you need to be explicit about what values you want to return.  You can just be explicit:

SELECT visitor_id, MAX(visitor_date), MAX(visitor_country), MAX(visitor_region), MAX(visitor_city), MAX(visitor_postcode), MAX(visitor_latitude), MAX(visitor_ip)
FROM visitors
WHERE visitor_country =: visitor_country
GROUP BY visitor_id, visitor_ip
ORDER BY MAX(visitor_date) ASC

Or you can revert to the pre-5.7 settings (even if you can't change the global server settings) by doing

SET SESSION sql_mode = 'NO_ENGINE_SUBSTITUTION';

after connecting to the database.  Though if you are using auto-reconnect, you may want to do it before each problematic query.


问:
wordpress -override number of posts in loop
See: http://jasondaydesign.com/portfolio

Also, for this custom loop, how would I override the number of posts as set by WP Settings > Reading > show 10 posts.

thanks!

```<code><?php
/*
Template Name: Portfolio
*/
?>

<?php get_header(); ?>

<ul id="portfolio-filter">
  <li><a href="#all">All</a></li>
  <li><a href="#web-design">Web</a></li>
  <li><a href="#logo-and-branding-design">Logo</a></li>
  <li><a href="#print-and-graphic-design">Print</a></li>
  <li><a href="#sculpture">Sculpture </a></li>
  <li><a href="#for-sale">For Sale </a></li>
 </ul>

        <ul id="portfolio-list">
        <?php query_posts('cat=5&showposts='); ?>
        <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>

<!-- ** store the category slugs for each post in a variable $catSlug ** -->
  <li class="<?php foreach((get_the_category()) as $category ) { echo $category->category_nicename . ' '; } ?>all">

 <!-- ** This is my own plugin to get the thumbnail from the post - you may use some custom field you have to get the image. ** -->
                    <a href='<?php the_permalink() ?>' title='<?php the_title(); ?>'><img src='<?php woo_image('width='.$woo_options['woo_thumb_w'].'&height='.$woo_options['woo_thumb_h'].'&class=thumbnail '.$woo_options['woo_thumb_align']); ?>' alt='<?php the_title(); ?>' /></a>

                    <p><?php the_title(); ?></p>
     <p><?php the_excerpt(); ?></p>

                </li>
            <? endwhile; ?>
        <? endif; ?>
  <?php wp_reset_query(); ?>
        </ul>

<?php get_footer(); ?>
</code>```

答:
Easiest way:   Custom Post Limits | coffee2code.com

Or work with the post limits in the loop: Function Reference/query posts « WordPress Codex, i.e. Example_3 on that page

Body:
See: http://jasondaydesign.com/portfolio

Also, for this custom loop, how would I override the number of posts as set by WP Settings > Reading > show 10 posts.

thanks!

<?php
/*
Template Name: Portfolio
*/
?>

<?php get_header(); ?>

All

Web

Logo

Print

Sculpture

For Sale

        <?php query_posts('cat=5&showposts='); ?>
        <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>

  <li class="<?php foreach((get_the_category()) as $category ) { echo $category->category_nicename . ' '; } ?>all">

                    <a href='<?php the_permalink() ?>' title='<?php the_title(); ?>'><img src='<?php woo_image('width='.$woo_options['woo_thumb_w'].'&height='.$woo_options['woo_thumb_h'].'&class=thumbnail '.$woo_options['woo_thumb_align']); ?>' alt='<?php the_title(); ?>' />

<?php the_title(); ?>

<?php the_excerpt(); ?>

            <? endwhile; ?>
        <? endif; ?>
  <?php wp_reset_query(); ?>

<?php get_footer(); ?>


问:
Is it possible to create an Express.js server in my Jest test suite?
I'm trying to test a function that gets data from an external API using axios. To keep my test function as close as possible to the real thing, I'm querying mock data I have in a file. Axios can't return data from local files, which is a security feature. So the solution I'm trying is spinning up a simple server in my test suite, serving the file there, and then running my tests.

My test suite looks like this right now:

```<code>import React from 'react';
import {shallow} from 'enzyme';
import express from 'express';
import { getFeedId, getFeedData, reverseStop } from '../mocks/apiMock';

const app = express();
const port = 4000;
app.use(express.static('../mocks/MockData.json'));
app.listen(port, tests());

function tests () {
    it('returns the expected feed id for a given subway line', () => {
        expect(getFeedId('L')).toBe(2);
    });

    it('returns json data', () => {
        expect.assertions(2);
        return getFeedData('L').then(data => {
            expect(data).toBeDefined();
            expect(data.header.gtfs_realtime_version).toBe('1.0');
        });
    });

    it('returns a stop_id for a given subway line and stop', () => {
        expect(reverseStop('L', 'Lorimer St')).toBe('L10N');
    });
}
</code>```

The functions I'm testing look like this (the one that uses Axios is getFeedData, so I don't think the others are causing a problem but I'm not positive).

```<code>const axios = require('axios');

export function getFeedId (sub) {
    switch (sub) {
        case '1': case '2': case '3': case '4': case '5': case '6': case 'S':
            return 1;
        case 'A': case 'C': case 'E':
            return 26;
        case 'N': case 'Q': case 'R': case 'W':
            return 16;
        case 'B': case 'D': case 'F': case 'M':
            return 21;
        case 'L':
            return 2;
        case 'G':
            return 31;
    }
}

export function getFeedData (sub) {
    if (getFeedId(sub) === 2) {
        return axios.get('http://localhost:4000').then((data) => JSON.parse(data));
    }
}

export function reverseStop (sub, stop) {
    const stops = require('../utils/stops');
    const stopObjs = stops.filter((item) => item.stop_name == stop && typeof item.stop_id === 'string' && item.stop_id.charAt(0) == sub);
    for (var i = 0; i < stopObjs.length; i++) {
        if (stopObjs[i].stop_id.charAt(stopObjs[i].stop_id.length - 1) == 'N') {
            return stopObjs[i].stop_id;
        }
    }
}
</code>```

Here's the error message Jest is giving me:

```<code>FAIL  src/tests/api.test.js (23.311s)
  ● returns json data

Network Error

  at createError (node_modules/axios/lib/core/createError.js:16:15)
  at XMLHttpRequest.handleError [as onerror] (node_modules/axios/lib/adapters/xhr.js:87:14)
  at XMLHttpRequest.callback.(anonymous function) (node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:289:32)
  at invokeEventListeners (node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:219:27)
  at invokeInlineListeners (node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:166:7)
  at EventTargetImpl._dispatch (node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:122:7)
  at EventTargetImpl.dispatchEvent (node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:87:17)
  at XMLHttpRequest.dispatchEvent (node_modules/jsdom/lib/jsdom/living/generated/EventTarget.js:61:35)
  at dispatchError (node_modules/jsdom/lib/jsdom/living/xmlhttprequest.js:994:9)
  at validCORSHeaders (node_modules/jsdom/lib/jsdom/living/xmlhttprequest.js:1009:7)
  at receiveResponse (node_modules/jsdom/lib/jsdom/living/xmlhttprequest.js:871:12)
  at Request.client.on.res (node_modules/jsdom/lib/jsdom/living/xmlhttprequest.js:691:38)
  at emitOne (events.js:96:13)
  at Request.emit (events.js:191:7)
  at Request.onRequestResponse (node_modules/request/request.js:1074:10)
  at emitOne (events.js:96:13)
  at ClientRequest.emit (events.js:191:7)
  at HTTPParser.parserOnIncomingClient (_http_client.js:522:21)
  at HTTPParser.parserOnHeadersComplete (_http_common.js:99:23)
  at Socket.socketOnData (_http_client.js:411:20)
  at emitOne (events.js:96:13)
  at Socket.emit (events.js:191:7)
  at readableAddChunk (_stream_readable.js:178:18)
  at Socket.Readable.push (_stream_readable.js:136:10)
  at TCP.onread (net.js:560:20)

  ● returns json data

expect.assertions(2)

Expected two assertions to be called but only received zero assertion calls.

  at addAssertionErrors (node_modules/jest-jasmine2/build/setup-jest-globals.js:68:21)
  at process._tickCallback (internal/process/next_tick.js:109:7)```
```

My best guess at the issue is that maybe Jest doesn't run in a node environment (is there any way I can figure that out)? So maybe the Express server isn't being run at all. However, I'm a little beyond my expertise so that is little more than a guess. Is anyone able to shed a little light on what's really going on? Was my idea to run the Express server a good one? Was it a good idea to put it in the test suite? If the answer to one or both of those questions is "no," what are best practices here?

答:
You should create your server beforeEach() (and stop it in afterEach()) so that it runs for each test.

docs.

You should also pick an unused port so that tests can run in parallel.

Body:
I'm trying to test a function that gets data from an external API using axios. To keep my test function as close as possible to the real thing, I'm querying mock data I have in a file. Axios can't return data from local files, which is a security feature. So the solution I'm trying is spinning up a simple server in my test suite, serving the file there, and then running my tests.

My test suite looks like this right now:

import React from 'react';
import {shallow} from 'enzyme';
import express from 'express';
import { getFeedId, getFeedData, reverseStop } from '../mocks/apiMock';

const app = express();
const port = 4000;
app.use(express.static('../mocks/MockData.json'));
app.listen(port, tests());

function tests () {
    it('returns the expected feed id for a given subway line', () => {
        expect(getFeedId('L')).toBe(2);
    });

    it('returns json data', () => {
        expect.assertions(2);
        return getFeedData('L').then(data => {
            expect(data).toBeDefined();
            expect(data.header.gtfs_realtime_version).toBe('1.0');
        });
    });

    it('returns a stop_id for a given subway line and stop', () => {
        expect(reverseStop('L', 'Lorimer St')).toBe('L10N');
    });
}

The functions I'm testing look like this (the one that uses Axios is getFeedData, so I don't think the others are causing a problem but I'm not positive).

const axios = require('axios');

export function getFeedId (sub) {
    switch (sub) {
        case '1': case '2': case '3': case '4': case '5': case '6': case 'S':
            return 1;
        case 'A': case 'C': case 'E':
            return 26;
        case 'N': case 'Q': case 'R': case 'W':
            return 16;
        case 'B': case 'D': case 'F': case 'M':
            return 21;
        case 'L':
            return 2;
        case 'G':
            return 31;
    }
}

export function getFeedData (sub) {
    if (getFeedId(sub) === 2) {
        return axios.get('http://localhost:4000').then((data) => JSON.parse(data));
    }
}

export function reverseStop (sub, stop) {
    const stops = require('../utils/stops');
    const stopObjs = stops.filter((item) => item.stop_name == stop && typeof item.stop_id === 'string' && item.stop_id.charAt(0) == sub);
    for (var i = 0; i < stopObjs.length; i++) {
        if (stopObjs[i].stop_id.charAt(stopObjs[i].stop_id.length - 1) == 'N') {
            return stopObjs[i].stop_id;
        }
    }
}

Here's the error message Jest is giving me:

FAIL  src/tests/api.test.js (23.311s)
  ● returns json data

Network Error

  at createError (node_modules/axios/lib/core/createError.js:16:15)
  at XMLHttpRequest.handleError [as onerror] (node_modules/axios/lib/adapters/xhr.js:87:14)
  at XMLHttpRequest.callback.(anonymous function) (node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:289:32)
  at invokeEventListeners (node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:219:27)
  at invokeInlineListeners (node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:166:7)
  at EventTargetImpl._dispatch (node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:122:7)
  at EventTargetImpl.dispatchEvent (node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:87:17)
  at XMLHttpRequest.dispatchEvent (node_modules/jsdom/lib/jsdom/living/generated/EventTarget.js:61:35)
  at dispatchError (node_modules/jsdom/lib/jsdom/living/xmlhttprequest.js:994:9)
  at validCORSHeaders (node_modules/jsdom/lib/jsdom/living/xmlhttprequest.js:1009:7)
  at receiveResponse (node_modules/jsdom/lib/jsdom/living/xmlhttprequest.js:871:12)
  at Request.client.on.res (node_modules/jsdom/lib/jsdom/living/xmlhttprequest.js:691:38)
  at emitOne (events.js:96:13)
  at Request.emit (events.js:191:7)
  at Request.onRequestResponse (node_modules/request/request.js:1074:10)
  at emitOne (events.js:96:13)
  at ClientRequest.emit (events.js:191:7)
  at HTTPParser.parserOnIncomingClient (_http_client.js:522:21)
  at HTTPParser.parserOnHeadersComplete (_http_common.js:99:23)
  at Socket.socketOnData (_http_client.js:411:20)
  at emitOne (events.js:96:13)
  at Socket.emit (events.js:191:7)
  at readableAddChunk (_stream_readable.js:178:18)
  at Socket.Readable.push (_stream_readable.js:136:10)
  at TCP.onread (net.js:560:20)

  ● returns json data

expect.assertions(2)

Expected two assertions to be called but only received zero assertion calls.

  at addAssertionErrors (node_modules/jest-jasmine2/build/setup-jest-globals.js:68:21)
  at process._tickCallback (internal/process/next_tick.js:109:7)```

My best guess at the issue is that maybe Jest doesn't run in a node environment (is there any way I can figure that out)? So maybe the Express server isn't being run at all. However, I'm a little beyond my expertise so that is little more than a guess. Is anyone able to shed a little light on what's really going on? Was my idea to run the Express server a good one? Was it a good idea to put it in the test suite? If the answer to one or both of those questions is "no," what are best practices here?


问:
How to set required claims for IdentityServer4 API Resources?
I am using IdentityServer4 1.0.0 with the configuration information for the clients and API resources stored in SQL Server using the IdentityServer4.EntityFramework 1.0.0 package.

Is there a way to set a list of claims that must be present to access my API in the tables that are managed with the IdentityServer4.EntityFramework 1.0.0 package?

答:
In your API startup

```<code>services.AddAuthorization(options =>
        {
            options.AddPolicy("SecurePolicyName", policyUser =>
            {
                policyUser.RequireClaim("role", "admin");
            });
        });
</code>```

Then in your controller use Auhtorize Attribute with your policy.

```<code>[Authorize(Policy = "SecurePolicyName")]
</code>```

Body:
In your API startup

services.AddAuthorization(options =>
        {
            options.AddPolicy("SecurePolicyName", policyUser =>
            {
                policyUser.RequireClaim("role", "admin");
            });
        });

Then in your controller use Auhtorize Attribute with your policy.

[Authorize(Policy = "SecurePolicyName")]


问:
Datatables render body and footer column as numeric
I'm trying to format numeric data from a single column on the body and footer section. The formatting is as follows:

Thousands grouping separator: "."

Decimal point indicator: ","

Number of decimal points to show: "0"

Prefix: "$"

This is my try:

    $('#idtablainforme_ventaporfamilia').DataTable({
        destroy: true,
        "searching": false, "paging": false, "ordering": false, "info": false, "autowidth": false,
        columns: [
           { data: "1", render: $.fn.dataTable.render.text() },
           { data: "2", render: $.fn.dataTable.render.number('.', ',', 0, '$') }
        ],
        dom: 'Bfrtip',
        buttons: [
            {
                extend: 'excel',
                footer: true,
                title: 'INFORME DE VENTAS POR FAMILIA',
                text: '',
                titleAttr: 'Exporta a EXCEL',
            }
        ]
    });
```

<p>This is the data:</p>

```CHEQUERA MUJER 5231760
CARTERA 3487630
BILLETERA MUJER 2155120
NECESER 21980
COSMETIQUERA 10990
SET DE VIAJE 10990
TOTAL 12925150
```

<p>But it renders the following table:</p>

<pre class="lang-html prettyprint-override"><code><table id="idtablainforme_ventaporfamilia" class="table table-striped table-striped table-bordered nowrap dataTable">
    <thead>
        <tr role="row">
            <th>
                FAMILIA
            </th>
            <th>
                VENTA
            </th>
        </tr>
    </thead>
    <tfoot>
        <tr>
            <th>
                TOTAL
            </th>
            <th style="text-align: right">
                12.925.150
            </th>
        </tr>
    </tfoot>
    <tbody>
        <tr>
            <td>CHEQUERA MUJER</td>
            <td>$5</td>
        </tr>
        <tr>
            <td>CARTERA</td>
            <td>$5</td>
        </tr>
        <tr>
            <td>BILLETERA MUJER</td>
            <td>$2</td>
        </tr>
        <tr>
            <td>NECESER</td>
            <td>$21</td>
        </tr>
        <tr>
            <td>COSMETIQUERA</td>
            <td>$10</td>
        </tr>
        <tr>
            <td>SET DE VIAJE</td>
            <td>$10</td>
        </tr>
    </tbody>
</table>
</code>```

The problem is that the formatting on the body section is wrong ($5 instead of $5.231.760) and it doesn't format the footer section.

答:
Look at the source around line 14489 (the exact line number will probably change in the future). The renderers is in fact an object literal on the form :

render = {
  number: function(..) {
    return {
      display: function(..) {
      }
    }
  }
  ...
}
```

<p>So you can call the renderer programmatically with </p>

<pre class="lang-js prettyprint-override"><code>$.fn.dataTable.render.number('.', ',', 0, '$').display(value)
</code>```

Now you can use footerCallback to render its value using render.number().display()

footerCallback: function(tfoot, data, start, end, display) {
  var $th = $(tfoot).find('th').eq(1);
  $th.text( $.fn.dataTable.render.number('.', ',', 0, '$').display( $th.text() ))
},
```

Notice that the value must be an unformatted number, i.e 12925150 not 12.925.150 - otherwise it will fail

http://jsfiddle.net/wotyo6nL/

Body:
I'm trying to format numeric data from a single column on the body and footer section. The formatting is as follows:

Thousands grouping separator: "."

Decimal point indicator: ","

Number of decimal points to show: "0"

Prefix: "$"

This is my try:

    $('#idtablainforme_ventaporfamilia').DataTable({
        destroy: true,
        "searching": false, "paging": false, "ordering": false, "info": false, "autowidth": false,
        columns: [
           { data: "1", render: $.fn.dataTable.render.text() },
           { data: "2", render: $.fn.dataTable.render.number('.', ',', 0, '$') }
        ],
        dom: 'Bfrtip',
        buttons: [
            {
                extend: 'excel',
                footer: true,
                title: 'INFORME DE VENTAS POR FAMILIA',
                text: '',
                titleAttr: 'Exporta a EXCEL',
            }
        ]
    });

This is the data:

CHEQUERA MUJER 5231760
CARTERA 3487630
BILLETERA MUJER 2155120
NECESER 21980
COSMETIQUERA 10990
SET DE VIAJE 10990
TOTAL 12925150

But it renders the following table:

                FAMILIA

                VENTA

                TOTAL

                12.925.150

            CHEQUERA MUJER
            $5

            CARTERA
            $5

            BILLETERA MUJER
            $2

            NECESER
            $21

            COSMETIQUERA
            $10

            SET DE VIAJE
            $10

The problem is that the formatting on the body section is wrong ($5 instead of $5.231.760) and it doesn't format the footer section.

Body:
Look at the source around line 14489 (the exact line number will probably change in the future). The renderers is in fact an object literal on the form :

render = {
  number: function(..) {
    return {
      display: function(..) {
      }
    }
  }
  ...
}

So you can call the renderer programmatically with

$.fn.dataTable.render.number('.', ',', 0, '$').display(value)

Now you can use footerCallback to render its value using render.number().display()

footerCallback: function(tfoot, data, start, end, display) {
  var $th = $(tfoot).find('th').eq(1);
  $th.text( $.fn.dataTable.render.number('.', ',', 0, '$').display( $th.text() ))
},

Notice that the value must be an unformatted number, i.e 12925150 not 12.925.150 - otherwise it will fail

http://jsfiddle.net/wotyo6nL/


问:
ORA-01422: exact fetch returns more than requested number of rows ORA-06512: at "LPR_PROD.MPKG_LPKREPORT", line 21
I am trying to execute the below query in oracle and i am getting the ORA-01422 error. Below is the query i am using to accomplish my results. This query is a part of Package.

```<code>Select DISTINCT TO_CHAR(RHR.d_end_of_month_s,'MM/dd/yyyy') "Disbursal Date",
RST.st_nam_s "State Name", MLO_COUNTY.loc_nam_s "County Name",RHR.d_pmtdu_s,
MLO_CITY.loc_nam_s "City Name", RHR.recip_s "Original GeoCode",
RHR.lse_s "Lease Number",RHR.unit_lse_s "Asset Number",
REQ.bk_acct_s "Contract Type", REQ.eqt_stat_s "Asset Status",
TO_CHAR(REQ.d_disp_s,'MM/dd/yyyy') "Asset Disposition Date",
RHR.p_st_rat_d "State Rate",(RHR.p_ct_rat_d-RHR.p_ct_trnst_rat_d) "County Rate",
RHR.p_ct_trnst_rat_d "County Transit Rate",
RHR.p_cy_rat_d -RHR.p_cy_trnst_rat_d) "City Rate",
RHR.p_cy_trnst_rat_d "City Transit rate",
RHR.p_st_rat_d +RHR.p_ct_rat_d+RHR.p_cy_rat_d) "Combined Rate",
RHR.nontax_gross_d+RHR.gross_d) "Gross Invoice Billed",
CASE WHEN trim(RHR.lse_s)='UPF STAX' THEN
mpkg_lpkreport.GROSSTAX(trim(RHR.UNIT_LSE_S),RHR.d_end_of_month_s,
trim(RHR.LSE_S),RHR.p_ct_rat_d) ELSE RHR.gross_d END "Taxable Invoice Billed",
mpkg_lpkreport.NCALACCUREDTAXVALUE(RHR.UNIT_LSE_S,0,TO_CHAR(RHR.d_end_of_month_s,'MM/dd/yyyy'),
RHR.LSE_S,TO_CHAR(RHR.d_pmtdu_s,'MM/dd/yyyy'),RHR.p_ct_rat_d) "Accrued State Tax",
mpkg_lpkreport.NCALACCUREDTAXVALUE(RHR.UNIT_LSE_S,1,TO_CHAR(RHR.d_end_of_month_s,'MM/dd/yyyy'),
RHR.LSE_S,TO_CHAR(RHR.d_pmtdu_s,'MM/dd/yyyy'),RHR.p_ct_rat_d ) "Accrued County Tax",
mpkg_lpkreport.NCALACCUREDTAXVALUE(RHR.UNIT_LSE_S,2,TO_CHAR(RHR.d_end_of_month_s,'MM/dd/yyyy'),
RHR.LSE_S,TO_CHAR(RHR.d_pmtdu_s,'MM/dd/yyyy'),RHR.p_ct_rat_d) "Accrued City Tax",
mpkg_lpkreport.NCALACCUREDDISTRICTTAX(RHR.UNIT_LSE_S,1,TO_CHAR(RHR.d_end_of_month_s,'MM/dd/yyyy'),
RHR.LSE_S,TO_CHAR(RHR.d_pmtdu_s,'MM/dd/yyyy')) "Accrued County District Tax",
mpkg_lpkreport.NCALACCUREDDISTRICTTAX(RHR.UNIT_LSE_S,2,TO_CHAR(RHR.d_end_of_month_s,'MM/dd/yyyy'),
RHR.LSE_S,TO_CHAR(RHR.d_pmtdu_s,'MM/dd/yyyy')) "Accrued City District Tax",
TO_CHAR(RLS.d_com_s,'MM/dd/yyyy') "Lease commencement date",
REQ.txp_s "Tax payment code",
replace((State_Geocodes.geo_st_l || substr(RHR.recip_s,3,length(recip_s))),'','')
"Translated GeoCode"
from   RHR
Inner join REQ on REQ.unit_s =RHR.unit_lse_s
and rhr.use_tax_c = case when REQ.txp_s in ('CNTY','CNCI' ) then '1'  when  REQ.txp_s = 'CITY' then
'2' else '0' end
Inner join RLS on RLS.lse_s = REQ.lse_s
Inner join RST on REQ.st_s =RST.st_s
Inner join MLO_COUNTY on MLO_COUNTY.ct_s =REQ.ct_s and MLO_COUNTY.st_s =REQ.st_s
Inner join MLO_CITY on MLO_CITY.cy_s =REQ.cy_s AND MLO_CITY.ct_s =REQ.ct_s
AND MLO_CITY.st_s =REQ.st_s
Inner join State_Geocodes on State_Geocodes.ST_S=substr(RHR.recip_s,1,2)
Where 1=1 and rhr.por_s =' 1' and rhr.d_end_of_month_s = '30-NOV-2017';
</code>```

Is there anything i missed in the query?

Below is the function that has been used in the query mpkg_lpkreport.GROSSTAX. It is showing the error in this function and i am not sure what issue is in this.

```<code>FUNCTION GROSSTAX(sunit_lse_s varchar2,
sd_end_of_month_s date, slse_s varchar2, rat_d FLOAT) return FLOAT
AS
n_grossd FLOAT;
BEGIN
BEGIN
select nvl(gross_d,0) into n_grossd      from RHR
where trim(RHR.lse_s)=slse_s and trim(RHR.unit_lse_s)=sunit_lse_s
and RHR.use_tax_c IN ('0') and RHR.d_end_of_month_s=sd_end_of_month_s
and  RHR.P_CT_RAT_D=rat_d;
EXCEPTION
WHEN NO_DATA_FOUND THEN
n_grossd := 0;
END;
IF n_grossd = 0 THEN
BEGIN
select nvl(gross_d,0) into n_grossd      from RHR
where trim(RHR.lse_s)=slse_s and trim(RHR.unit_lse_s)=sunit_lse_s
and RHR.use_tax_c IN ('1') and RHR.d_end_of_month_s=sd_end_of_month_s
and  RHR.P_CT_RAT_D=rat_d;
EXCEPTION
WHEN NO_DATA_FOUND THEN
n_grossd := 0;
END;
END IF;
IF n_grossd = 0 THEN
BEGIN
select nvl(gross_d,0) into n_grossd      from RHR
where trim(RHR.lse_s)=slse_s and trim(RHR.unit_lse_s)=sunit_lse_s
and RHR.use_tax_c IN ('2') and RHR.d_end_of_month_s=sd_end_of_month_s
and  RHR.P_CT_RAT_D=rat_d ;
EXCEPTION
WHEN NO_DATA_FOUND THEN
n_grossd := 0;
END;
END IF;
return n_grossd;
END GROSSTAX;
</code>```

答:
The problem is that one of the queries in your GROSSTAX function is returning more than one row, but because you're doing a SELECT...INTO these queries must return at most one row. One way to work around this is to rewrite GROSSTAX:

```<code>FUNCTION GROSSTAX(sunit_lse_s       IN varchar2,
                  sd_end_of_month_s IN date,
                  slse_s            IN varchar2,
                  rat_d             IN FLOAT)
  return FLOAT AS
BEGIN
  FOR aRow IN (select GROSS_D
                 from RHR
                 where trim(RHR.lse_s) = slse_s and
                       trim(RHR.unit_lse_s)=sunit_lse_s and
                       RHR.use_tax_c IN ('0', '1', '2') and
                       RHR.d_end_of_month_s = sd_end_of_month_s and
                       RHR.P_CT_RAT_D=rat_d
                 ORDER BY RHR.USE_TAX_C ASC)
  LOOP
    RETURN NVL(aRow.GROSS_D, 0);
  END LOOP;

  RETURN 0;
END GROSSTAX;
</code>```

Here I've compressed the three queries into one, as it appeared that they only differed by the value of RHR.USE_TAX_C they were checking for. The results of the query are ordered in ascending order by RHR.USE_TAX_C so that it will give back the GROSS_D value associated with the minimum value of USE_TAX_C which exists, all other comparisons being the same. Only the first row returned by the query is used; once the first row is returned by the cursor the function returns.

Best of luck.

Body:
I am trying to execute the below query in oracle and i am getting the ORA-01422 error. Below is the query i am using to accomplish my results. This query is a part of Package.

Select DISTINCT TO_CHAR(RHR.d_end_of_month_s,'MM/dd/yyyy') "Disbursal Date",
RST.st_nam_s "State Name", MLO_COUNTY.loc_nam_s "County Name",RHR.d_pmtdu_s,
MLO_CITY.loc_nam_s "City Name", RHR.recip_s "Original GeoCode",
RHR.lse_s "Lease Number",RHR.unit_lse_s "Asset Number",
REQ.bk_acct_s "Contract Type", REQ.eqt_stat_s "Asset Status",
TO_CHAR(REQ.d_disp_s,'MM/dd/yyyy') "Asset Disposition Date",
RHR.p_st_rat_d "State Rate",(RHR.p_ct_rat_d-RHR.p_ct_trnst_rat_d) "County Rate",
RHR.p_ct_trnst_rat_d "County Transit Rate",
RHR.p_cy_rat_d -RHR.p_cy_trnst_rat_d) "City Rate",
RHR.p_cy_trnst_rat_d "City Transit rate",
RHR.p_st_rat_d +RHR.p_ct_rat_d+RHR.p_cy_rat_d) "Combined Rate",
RHR.nontax_gross_d+RHR.gross_d) "Gross Invoice Billed",
CASE WHEN trim(RHR.lse_s)='UPF STAX' THEN
mpkg_lpkreport.GROSSTAX(trim(RHR.UNIT_LSE_S),RHR.d_end_of_month_s,
trim(RHR.LSE_S),RHR.p_ct_rat_d) ELSE RHR.gross_d END "Taxable Invoice Billed",
mpkg_lpkreport.NCALACCUREDTAXVALUE(RHR.UNIT_LSE_S,0,TO_CHAR(RHR.d_end_of_month_s,'MM/dd/yyyy'),
RHR.LSE_S,TO_CHAR(RHR.d_pmtdu_s,'MM/dd/yyyy'),RHR.p_ct_rat_d) "Accrued State Tax",
mpkg_lpkreport.NCALACCUREDTAXVALUE(RHR.UNIT_LSE_S,1,TO_CHAR(RHR.d_end_of_month_s,'MM/dd/yyyy'),
RHR.LSE_S,TO_CHAR(RHR.d_pmtdu_s,'MM/dd/yyyy'),RHR.p_ct_rat_d ) "Accrued County Tax",
mpkg_lpkreport.NCALACCUREDTAXVALUE(RHR.UNIT_LSE_S,2,TO_CHAR(RHR.d_end_of_month_s,'MM/dd/yyyy'),
RHR.LSE_S,TO_CHAR(RHR.d_pmtdu_s,'MM/dd/yyyy'),RHR.p_ct_rat_d) "Accrued City Tax",
mpkg_lpkreport.NCALACCUREDDISTRICTTAX(RHR.UNIT_LSE_S,1,TO_CHAR(RHR.d_end_of_month_s,'MM/dd/yyyy'),
RHR.LSE_S,TO_CHAR(RHR.d_pmtdu_s,'MM/dd/yyyy')) "Accrued County District Tax",
mpkg_lpkreport.NCALACCUREDDISTRICTTAX(RHR.UNIT_LSE_S,2,TO_CHAR(RHR.d_end_of_month_s,'MM/dd/yyyy'),
RHR.LSE_S,TO_CHAR(RHR.d_pmtdu_s,'MM/dd/yyyy')) "Accrued City District Tax",
TO_CHAR(RLS.d_com_s,'MM/dd/yyyy') "Lease commencement date",
REQ.txp_s "Tax payment code",
replace((State_Geocodes.geo_st_l || substr(RHR.recip_s,3,length(recip_s))),'','')
"Translated GeoCode"
from   RHR
Inner join REQ on REQ.unit_s =RHR.unit_lse_s
and rhr.use_tax_c = case when REQ.txp_s in ('CNTY','CNCI' ) then '1'  when  REQ.txp_s = 'CITY' then
'2' else '0' end
Inner join RLS on RLS.lse_s = REQ.lse_s
Inner join RST on REQ.st_s =RST.st_s
Inner join MLO_COUNTY on MLO_COUNTY.ct_s =REQ.ct_s and MLO_COUNTY.st_s =REQ.st_s
Inner join MLO_CITY on MLO_CITY.cy_s =REQ.cy_s AND MLO_CITY.ct_s =REQ.ct_s
AND MLO_CITY.st_s =REQ.st_s
Inner join State_Geocodes on State_Geocodes.ST_S=substr(RHR.recip_s,1,2)
Where 1=1 and rhr.por_s =' 1' and rhr.d_end_of_month_s = '30-NOV-2017';

Is there anything i missed in the query?

Below is the function that has been used in the query mpkg_lpkreport.GROSSTAX. It is showing the error in this function and i am not sure what issue is in this.

FUNCTION GROSSTAX(sunit_lse_s varchar2,
sd_end_of_month_s date, slse_s varchar2, rat_d FLOAT) return FLOAT
AS
n_grossd FLOAT;
BEGIN
BEGIN
select nvl(gross_d,0) into n_grossd      from RHR
where trim(RHR.lse_s)=slse_s and trim(RHR.unit_lse_s)=sunit_lse_s
and RHR.use_tax_c IN ('0') and RHR.d_end_of_month_s=sd_end_of_month_s
and  RHR.P_CT_RAT_D=rat_d;
EXCEPTION
WHEN NO_DATA_FOUND THEN
n_grossd := 0;
END;
IF n_grossd = 0 THEN
BEGIN
select nvl(gross_d,0) into n_grossd      from RHR
where trim(RHR.lse_s)=slse_s and trim(RHR.unit_lse_s)=sunit_lse_s
and RHR.use_tax_c IN ('1') and RHR.d_end_of_month_s=sd_end_of_month_s
and  RHR.P_CT_RAT_D=rat_d;
EXCEPTION
WHEN NO_DATA_FOUND THEN
n_grossd := 0;
END;
END IF;
IF n_grossd = 0 THEN
BEGIN
select nvl(gross_d,0) into n_grossd      from RHR
where trim(RHR.lse_s)=slse_s and trim(RHR.unit_lse_s)=sunit_lse_s
and RHR.use_tax_c IN ('2') and RHR.d_end_of_month_s=sd_end_of_month_s
and  RHR.P_CT_RAT_D=rat_d ;
EXCEPTION
WHEN NO_DATA_FOUND THEN
n_grossd := 0;
END;
END IF;
return n_grossd;
END GROSSTAX;

Body:
The problem is that one of the queries in your GROSSTAX function is returning more than one row, but because you're doing a SELECT...INTO these queries must return at most one row. One way to work around this is to rewrite GROSSTAX:

FUNCTION GROSSTAX(sunit_lse_s       IN varchar2,
                  sd_end_of_month_s IN date,
                  slse_s            IN varchar2,
                  rat_d             IN FLOAT)
  return FLOAT AS
BEGIN
  FOR aRow IN (select GROSS_D
                 from RHR
                 where trim(RHR.lse_s) = slse_s and
                       trim(RHR.unit_lse_s)=sunit_lse_s and
                       RHR.use_tax_c IN ('0', '1', '2') and
                       RHR.d_end_of_month_s = sd_end_of_month_s and
                       RHR.P_CT_RAT_D=rat_d
                 ORDER BY RHR.USE_TAX_C ASC)
  LOOP
    RETURN NVL(aRow.GROSS_D, 0);
  END LOOP;

  RETURN 0;
END GROSSTAX;

Here I've compressed the three queries into one, as it appeared that they only differed by the value of RHR.USE_TAX_C they were checking for. The results of the query are ordered in ascending order by RHR.USE_TAX_C so that it will give back the GROSS_D value associated with the minimum value of USE_TAX_C which exists, all other comparisons being the same. Only the first row returned by the query is used; once the first row is returned by the cursor the function returns.

Best of luck.


问:
Proof for optimal page replacement (OPT)
I need prove that the optimal page replacement algorithm is indeed optimal, and I'm not sure exactly how to start. I thought maybe proof by contradiction, but once I formulated an alternative claim, I wasn't sure how to show that it would have equal or less  page faults than OPT.</p>

答: Is this for CSE 330 final tomorrow?</p>

Body: Is this for CSE 330 final tomorrow?


问:
Correlate two floats using c#
I know im an idiot and I am sure this is simple math. But I cannot seem to wrap my head around it here is my situation

When X = 3, I need Y = 0, and when X = 0 I need y = 1;.
I am trying to fill a progress bar based upon how low X is.

The value to fill the progress bar (Y) must be between 0 and 1.

Math?

答:
```<code>// "Single" is just like "float"
Single y = (3.0f - x) / 3.0f;
</code>```

So that

```<code>x=3 -> y=0.00
x=2 -> y=0.33
x=1 -> y=0.66
x=0 -> y=1.00
</code>```

Alternatively:

```<code>// different points of view are better
Single y = -(x - 3.0f) / 3.0f;
</code>```

Title: Correlate two floats using c#

Body:
// "Single" is just like "float"
Single y = (3.0f - x) / 3.0f;

So that

x=3 -> y=0.00
x=2 -> y=0.33
x=1 -> y=0.66
x=0 -> y=1.00

Alternatively:

// different points of view are better
Single y = -(x - 3.0f) / 3.0f;