问:
React fixed data table make responsive
I have a table in a div as following:

```<code><div className="second-row-container">

    <Table
        rowsCount={this.state.myTableData.length}
        rowHeight={50}
        headerHeight={50}
        width={9*150}
        height={(this.state.myTableData.length+1)*50}>
        <Column
            header={<Cell>Delivery</Cell>}
            cell={props => (
                <Cell {...props}>
                    {this.state.myTableData[props.rowIndex].delivery}
                </Cell>
            )}
            width={150}
        />
        <Column
            header={<Cell>Category</Cell>}
            cell={props => (
                <Cell {...props}>
                    {this.state.myTableData[props.rowIndex].age}
                </Cell>
            )}
            width={150}
        />
        <Column
            header={<Cell>Language</Cell>}
            cell={props => (
                <Cell {...props}>
                    {this.state.myTableData[props.rowIndex].language}
                </Cell>
            )}
            width={150}
        />
        <Column
            header={<Cell>Target market</Cell>}
            cell={props => (
                <Cell {...props}>
                    {this.state.myTableData[props.rowIndex].market}
                </Cell>
            )}
            width={150}
        />
        <Column
            header={<Cell>Valid from</Cell>}
            cell={props => (
                <Cell {...props}>
                    {this.state.myTableData[props.rowIndex].valid_from}
                </Cell>
            )}
            width={150}
        />
        <Column
            header={<Cell>Valid till</Cell>}
            cell={props => (
                <Cell {...props}>
                    {this.state.myTableData[props.rowIndex].valid_till}
                </Cell>
            )}
            width={150}
        />
        <Column
            header={<Cell>Visibility</Cell>}
            cell={props => (
                <Cell {...props}>
                    {this.state.myTableData[props.rowIndex].visibility}
                </Cell>
            )}
            width={150}
        />
        <Column
            header={<Cell></Cell>}
            cell={props => (
                <Cell {...props}>

                </Cell>
            )}
            width={150}
        />
        <Column
            header={<Cell></Cell>}
            cell={props => (
                <Cell {...props}>

                </Cell>
            )}
            width={150}
        />
    </Table>

</div>
</code>```

And in css I have:

```<code>.second-row-container{
  height: 50vh;
  background-color: lightgray;
  padding: 0.5%;
  width: 100%;
}
</code>```

I thought by making parent width 100% the table will always be shrinking when I shrink the screen, but it doesn't.

How can I make the table fit in the parent div and on small screens I would like columns 3,4,5 and 6 to hide. How can I achieve this?

答:
You can achieve by attaching resize event to window, see code below

```<code>var React = require('react');
var ReactDOM = require('react-dom');
var {Table} = require('fixed-data-table');
var _ = require('lodash');

var FittedTable = React.createClass({
    getInitialState() {
        return {
            tableWidth  : 400,
            tableHeight : 400
        };
    },

    componentDidMount() {
        var win = window;
        if (win.addEventListener) {
            win.addEventListener('resize', _.throttle(this._update, 250), false);
        } else if (win.attachEvent) {
            win.attachEvent('onresize', _.throttle(this._update, 250));
        } else {
            win.onresize = this._update;
        }
        this._update();
    },

    componentWillReceiveProps(props) {
        this._update();
    },

    componentWillUnmount() {
        var win = window;
        if(win.removeEventListener) {
            win.removeEventListener('resize', _.throttle(this._update, 250), false);
        } else if(win.removeEvent) {
            win.removeEvent('onresize', _.throttle(this._update, 250), false);
        } else {
            win.onresize = null;
        }
    },

    _update() {
        if (this.isMounted()) {
            var node = ReactDOM.findDOMNode(this);

            this.setState({
                tableWidth  : node.clientWidth,
                tableHeight : node.clientHeight
            });
        }
    },

    render() {
        return (
            <div className="fitted-wrapper">
                <Table {...this.props} width={this.state.tableWidth} height={this.state.tableHeight}>
                    {this.props.children}
                </Table>
            </div>
        );
    },
});

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

Title: React fixed data table make responsive

Body:
I have a table in a div as following:

        <Column
            header={<Cell>Delivery</Cell>}
            cell={props => (
                <Cell {...props}>
                    {this.state.myTableData[props.rowIndex].delivery}
                </Cell>
            )}
            width={150}
        />
        <Column
            header={<Cell>Category</Cell>}
            cell={props => (
                <Cell {...props}>
                    {this.state.myTableData[props.rowIndex].age}
                </Cell>
            )}
            width={150}
        />
        <Column
            header={<Cell>Language</Cell>}
            cell={props => (
                <Cell {...props}>
                    {this.state.myTableData[props.rowIndex].language}
                </Cell>
            )}
            width={150}
        />
        <Column
            header={<Cell>Target market</Cell>}
            cell={props => (
                <Cell {...props}>
                    {this.state.myTableData[props.rowIndex].market}
                </Cell>
            )}
            width={150}
        />
        <Column
            header={<Cell>Valid from</Cell>}
            cell={props => (
                <Cell {...props}>
                    {this.state.myTableData[props.rowIndex].valid_from}
                </Cell>
            )}
            width={150}
        />
        <Column
            header={<Cell>Valid till</Cell>}
            cell={props => (
                <Cell {...props}>
                    {this.state.myTableData[props.rowIndex].valid_till}
                </Cell>
            )}
            width={150}
        />
        <Column
            header={<Cell>Visibility</Cell>}
            cell={props => (
                <Cell {...props}>
                    {this.state.myTableData[props.rowIndex].visibility}
                </Cell>
            )}
            width={150}
        />
        <Column
            header={<Cell></Cell>}
            cell={props => (
                <Cell {...props}>

                </Cell>
            )}
            width={150}
        />
        <Column
            header={<Cell></Cell>}
            cell={props => (
                <Cell {...props}>

                </Cell>
            )}
            width={150}
        />

And in css I have:

.second-row-container{
  height: 50vh;
  background-color: lightgray;
  padding: 0.5%;
  width: 100%;
}

I thought by making parent width 100% the table will always be shrinking when I shrink the screen, but it doesn't.

How can I make the table fit in the parent div and on small screens I would like columns 3,4,5 and 6 to hide. How can I achieve this?

Body:
You can achieve by attaching resize event to window, see code below

var React = require('react');
var ReactDOM = require('react-dom');
var {Table} = require('fixed-data-table');
var _ = require('lodash');

var FittedTable = React.createClass({
    getInitialState() {
        return {
            tableWidth  : 400,
            tableHeight : 400
        };
    },

    componentDidMount() {
        var win = window;
        if (win.addEventListener) {
            win.addEventListener('resize', _.throttle(this._update, 250), false);
        } else if (win.attachEvent) {
            win.attachEvent('onresize', _.throttle(this._update, 250));
        } else {
            win.onresize = this._update;
        }
        this._update();
    },

    componentWillReceiveProps(props) {
        this._update();
    },

    componentWillUnmount() {
        var win = window;
        if(win.removeEventListener) {
            win.removeEventListener('resize', _.throttle(this._update, 250), false);
        } else if(win.removeEvent) {
            win.removeEvent('onresize', _.throttle(this._update, 250), false);
        } else {
            win.onresize = null;
        }
    },

    _update() {
        if (this.isMounted()) {
            var node = ReactDOM.findDOMNode(this);

            this.setState({
                tableWidth  : node.clientWidth,
                tableHeight : node.clientHeight
            });
        }
    },

    render() {
        return (
            <div className="fitted-wrapper">
                <Table {...this.props} width={this.state.tableWidth} height={this.state.tableHeight}>
                    {this.props.children}
                </Table>
            </div>
        );
    },
});

module.exports = FittedTable;


来源: stackexchange

问:
Deploying Node.js, express, knex app on Heroku - Unhandled rejection Error: Pool is destroyed
Super big noob here only started coding 4 weeks ago so I apologize if this question is incredibly ignorant.

I am deploying this small node.js express and knex web app on Heroku.  Everything runs well locally. I have created the app successfully from the command line, and all the pages render. I have created the PostgreSQL database on Heroku, and I have successfully performed the migrations so that my tables are all set up. However, when I try to submit a form, which is suppose to insert data into the database, I keep getting the following error in the logs:

2017-06-25T06:01:57.360120+00:00 app[web.1]: Unhandled rejection Error: Pool is destroyed 2017-06-25T06:01:57.360123+00:00 app[web.1]: at Pool.acquire (/app/node_modules/pool2/lib/pool.js:162:12) 2017-06-25T06:01:57.360124+00:00 app[web.1]: at /app/node_modules/knex/lib/client.js:268:29 2017-06-25T06:01:57.360125+00:00 app[web.1]: at Promise._execute (/app/node_modules/bluebird/js/release/debuggability.js:300:9) 2017-06-25T06:01:57.360125+00:00 app[web.1]: at Promise._resolveFromExecutor (/app/node_modules/bluebird/js/release/promise.js:483:18) 2017-06-25T06:01:57.360126+00:00 app[web.1]: at new Promise (/app/node_modules/bluebird/js/release/promise.js:79:10) 2017-06-25T06:01:57.360127+00:00 app[web.1]: at Client.acquireConnection (/app/node_modules/knex/lib/client.js:264:21) 2017-06-25T06:01:57.360131+00:00 app[web.1]: at /app/node_modules/knex/lib/runner.js:188:47 2017-06-25T06:01:57.360132+00:00 app[web.1]: at Promise._execute (/app/node_modules/bluebird/js/release/debuggability.js:300:9) 2017-06-25T06:01:57.360134+00:00 app[web.1]: at /app/node_modules/knex/lib/runner.js:187:35 2017-06-25T06:01:57.360133+00:00 app[web.1]: at new Promise (/app/node_modules/bluebird/js/release/promise.js:79:10) 2017-06-25T06:01:57.360135+00:00 app[web.1]: at Function.Promise.attempt.Promise.try (/app/node_modules/bluebird/js/release/method.js:39:29) 2017-06-25T06:01:57.360132+00:00 app[web.1]: at Promise._resolveFromExecutor (/app/node_modules/bluebird/js/release/promise.js:483:18) 2017-06-25T06:01:57.360134+00:00 app[web.1]: at tryCatcher (/app/node_modules/bluebird/js/release/util.js:16:23) 2017-06-25T06:01:57.360136+00:00 app[web.1]: at Runner.run (/app/node_modules/knex/lib/runner.js:41:44) 2017-06-25T06:01:57.360136+00:00 app[web.1]: at Runner.ensureConnection (/app/node_modules/knex/lib/runner.js:186:39) 2017-06-25T06:01:57.360137+00:00 app[web.1]: at QueryBuilder.Target.then (/app/node_modules/knex/lib/interface.js:32:43)

I've gone through the tutorial on Heroku, and read through their node documentation.  I don't have a Procfile set up because as I understand from my reading it's not necessary.

Here is my Knex config:

```<code>  production: {
    client: 'pg',
    connection: process.env.DATABASE_URL + '?ssl=true',
    debug: true,
    pool: {
      min: 2,
      max: 10
    },
    migrations: {
      directory: './db/migrations',
      tableName: 'migrations'
    }
  }
</code>```

Here is my server.js:

```<code>"use strict";

if (process.env.NODE_ENV !== 'production') require('dotenv').config();

const PORT        = process.env.PORT || 8080;
const ENV         = process.env.ENV || "development";
const express     = require("express");
const bodyParser  = require("body-parser");
const sass        = require("node-sass-middleware");
const app         = express();
var pg = require('pg');

const knexConfig  = require("./knexfile");
const knex        = require("knex")(knexConfig[ENV]);
const morgan      = require('morgan');
const knexLogger  = require('knex-logger');

// Seperated Routes for each Resource
const pollRoutes  = require("./routes/poll");
const voteRoutes  = require("./routes/vote");
const administrativeRoutes = require("./routes/administrative");
const dbHelper    = require("./lib/dbHelper")(knex);

app.use(morgan('dev'));

app.use(knexLogger(knex));

app.set("view engine", "ejs");
app.use(bodyParser.urlencoded({ extended: true }));
app.use("/styles", sass({
  src: __dirname + "/styles",
  dest: __dirname + "/public/styles",
  debug: true,
  outputStyle: 'expanded'
}));
app.use(express.static("public"));

app.get("/", (req, res) => {
  res.redirect("/create");
});
app.get("/error", (req, res) => {
  res.render('error');
});

// Mount all resource routes
app.use("/create", pollRoutes(dbHelper, process.env));
app.use("/vote", voteRoutes(dbHelper, process.env));
app.use("/administrative", administrativeRoutes(dbHelper));

// Home page

app.listen(PORT, () => {
  console.log("Example app listening on port " + PORT);
});
</code>```

Again, any help is much appreciated. I used to work as an illustrator before I began learning this stuff, I'm happy to draw a portrait for whoever helps me solves this problem <3

答:
Your const ENV = process.env.ENV || "development"; is continually resolving to  "development," which is going to be undefined when you push to production.  This is because of your conditional statement that you placed on top of your server.js.

Change this to:

```<code>const ENV = process.env.NODE_ENV || 'development'
</code>```

You can console.log your knex and ENV constants to debug them.

ContentLicense: CC BY-SA 3.0

Body:
Super big noob here only started coding 4 weeks ago so I apologize if this question is incredibly ignorant.

I am deploying this small node.js express and knex web app on Heroku.  Everything runs well locally. I have created the app successfully from the command line, and all the pages render. I have created the PostgreSQL database on Heroku, and I have successfully performed the migrations so that my tables are all set up. However, when I try to submit a form, which is suppose to insert data into the database, I keep getting the following error in the logs:

2017-06-25T06:01:57.360120+00:00 app[web.1]: Unhandled rejection Error: Pool is destroyed 2017-06-25T06:01:57.360123+00:00 app[web.1]: at Pool.acquire (/app/node_modules/pool2/lib/pool.js:162:12) 2017-06-25T06:01:57.360124+00:00 app[web.1]: at /app/node_modules/knex/lib/client.js:268:29 2017-06-25T06:01:57.360125+00:00 app[web.1]: at Promise._execute (/app/node_modules/bluebird/js/release/debuggability.js:300:9) 2017-06-25T06:01:57.360125+00:00 app[web.1]: at Promise._resolveFromExecutor (/app/node_modules/bluebird/js/release/promise.js:483:18) 2017-06-25T06:01:57.360126+00:00 app[web.1]: at new Promise (/app/node_modules/bluebird/js/release/promise.js:79:10) 2017-06-25T06:01:57.360127+00:00 app[web.1]: at Client.acquireConnection (/app/node_modules/knex/lib/client.js:264:21) 2017-06-25T06:01:57.360131+00:00 app[web.1]: at /app/node_modules/knex/lib/runner.js:188:47 2017-06-25T06:01:57.360132+00:00 app[web.1]: at Promise._execute (/app/node_modules/bluebird/js/release/debuggability.js:300:9) 2017-06-25T06:01:57.360134+00:00 app[web.1]: at /app/node_modules/knex/lib/runner.js:187:35 2017-06-25T06:01:57.360133+00:00 app[web.1]: at new Promise (/app/node_modules/bluebird/js/release/promise.js:79:10) 2017-06-25T06:01:57.360135+00:00 app[web.1]: at Function.Promise.attempt.Promise.try (/app/node_modules/bluebird/js/release/method.js:39:29) 2017-06-25T06:01:57.360132+00:00 app[web.1]: at Promise._resolveFromExecutor (/app/node_modules/bluebird/js/release/promise.js:483:18) 2017-06-25T06:01:57.360134+00:00 app[web.1]: at tryCatcher (/app/node_modules/bluebird/js/release/util.js:16:23) 2017-06-25T06:01:57.360136+00:00 app[web.1]: at Runner.run (/app/node_modules/knex/lib/runner.js:41:44) 2017-06-25T06:01:57.360136+00:00 app[web.1]: at Runner.ensureConnection (/app/node_modules/knex/lib/runner.js:186:39) 2017-06-25T06:01:57.360137+00:00 app[web.1]: at QueryBuilder.Target.then (/app/node_modules/knex/lib/interface.js:32:43)

I've gone through the tutorial on Heroku, and read through their node documentation.  I don't have a Procfile set up because as I understand from my reading it's not necessary.

Here is my Knex config:

  production: {
    client: 'pg',
    connection: process.env.DATABASE_URL + '?ssl=true',
    debug: true,
    pool: {
      min: 2,
      max: 10
    },
    migrations: {
      directory: './db/migrations',
      tableName: 'migrations'
    }
  }

Here is my server.js:

"use strict";

if (process.env.NODE_ENV !== 'production') require('dotenv').config();

const PORT        = process.env.PORT || 8080;
const ENV         = process.env.ENV || "development";
const express     = require("express");
const bodyParser  = require("body-parser");
const sass        = require("node-sass-middleware");
const app         = express();
var pg = require('pg');

const knexConfig  = require("./knexfile");
const knex        = require("knex")(knexConfig[ENV]);
const morgan      = require('morgan');
const knexLogger  = require('knex-logger');

// Seperated Routes for each Resource
const pollRoutes  = require("./routes/poll");
const voteRoutes  = require("./routes/vote");
const administrativeRoutes = require("./routes/administrative");
const dbHelper    = require("./lib/dbHelper")(knex);

app.use(morgan('dev'));

app.use(knexLogger(knex));

app.set("view engine", "ejs");
app.use(bodyParser.urlencoded({ extended: true }));
app.use("/styles", sass({
  src: __dirname + "/styles",
  dest: __dirname + "/public/styles",
  debug: true,
  outputStyle: 'expanded'
}));
app.use(express.static("public"));

app.get("/", (req, res) => {
  res.redirect("/create");
});
app.get("/error", (req, res) => {
  res.render('error');
});

// Mount all resource routes
app.use("/create", pollRoutes(dbHelper, process.env));
app.use("/vote", voteRoutes(dbHelper, process.env));
app.use("/administrative", administrativeRoutes(dbHelper));

// Home page

app.listen(PORT, () => {
  console.log("Example app listening on port " + PORT);
});

Again, any help is much appreciated. I used to work as an illustrator before I began learning this stuff, I'm happy to draw a portrait for whoever helps me solves this problem <3

Body:
Your const ENV = process.env.ENV || "development"; is continually resolving to  "development," which is going to be undefined when you push to production.  This is because of your conditional statement that you placed on top of your server.js.

Change this to:

const ENV = process.env.NODE_ENV || 'development'

You can console.log your knex and ENV constants to debug them.


问:
Android Studio not recognising changes made in imported project library module
I have downloaded ZXing core source files, and created a new project with these source files. I then imported this project as a new module into my main project.

This has worked fine, and it all compiles and runs smoothly.

However when I try and change some of the code in the imported project, such as create a new method, the IDE doesn't detect any errors on compiling, but when I run the application, it says no such method exists.

Here is a screenshot of the error I get when I tried adding and calling a method called please() within the imported project

Here is a screenshot of the actual method I added to the imported project

I called this in my main application as follows:

```<code>Log.i(TAG, "" + Decoder.please());
</code>```

Any ideas?

答:
Have you tried cleaning and rebuilding your project? Also closing the Android Studio and re-opening?

Just answering so OP can choose the best answer and close the question

Body:
I have downloaded ZXing core source files, and created a new project with these source files. I then imported this project as a new module into my main project.

This has worked fine, and it all compiles and runs smoothly.

However when I try and change some of the code in the imported project, such as create a new method, the IDE doesn't detect any errors on compiling, but when I run the application, it says no such method exists.

Here is a screenshot of the error I get when I tried adding and calling a method called please() within the imported project

Here is a screenshot of the actual method I added to the imported project

I called this in my main application as follows:

Log.i(TAG, "" + Decoder.please());

Any ideas?


问:
listen to message queue
I am trying to create a console application that listens to a Message queue on my local computer. this is my code so far..

```<code>static void Main(string[] args)
    {
        var _queue = new MessageQueue(@".\private$\testing");
        _queue.Formatter = new XmlMessageFormatter(new Type[] {
       typeof(string) });

        _queue.ReceiveCompleted += new
       ReceiveCompletedEventHandler(queue_ReceiveCompleted);
        _queue.BeginReceive();

    }
  private static void queue_ReceiveCompleted(object source,
         ReceiveCompletedEventArgs e)
    {
        MessageQueue mq = (MessageQueue)source;
        Message msg = mq.EndReceive(e.AsyncResult);
        Console.WriteLine(msg.Body.ToString());
        mq.BeginReceive();
    }
</code>```

my problem is like this.. First of all the program exits right after

```<code>        Console.WriteLine(msg.Body.ToString());
</code>```

and I don't get the other messages in the queue.

So I tried without Console.WriteLine to see if all messages are read from the queue

```<code>private static void queue_ReceiveCompleted(object source,
         ReceiveCompletedEventArgs e)
    {
        MessageQueue mq = (MessageQueue)source;
        Message msg = mq.EndReceive(e.AsyncResult);
        mq.BeginReceive();
    }
</code>```

but then the results were inconsistent some times it would read 1 message some times 4 and sometimes all.

so whats going on, am I doing anything wrong?

答:
The BeginReceive method is asynchronous, so it will not prevent the main() to exit.

What you can do is just add a Console.ReadKey(); at the end of the main() to prevent this, until user interact.

Title: listen to message queue

Body:
I am trying to create a console application that listens to a Message queue on my local computer. this is my code so far..

static void Main(string[] args)
    {
        var _queue = new MessageQueue(@".\private$\testing");
        _queue.Formatter = new XmlMessageFormatter(new Type[] {
       typeof(string) });

        _queue.ReceiveCompleted += new
       ReceiveCompletedEventHandler(queue_ReceiveCompleted);
        _queue.BeginReceive();

    }
  private static void queue_ReceiveCompleted(object source,
         ReceiveCompletedEventArgs e)
    {
        MessageQueue mq = (MessageQueue)source;
        Message msg = mq.EndReceive(e.AsyncResult);
        Console.WriteLine(msg.Body.ToString());
        mq.BeginReceive();
    }

my problem is like this.. First of all the program exits right after

        Console.WriteLine(msg.Body.ToString());

and I don't get the other messages in the queue.

So I tried without Console.WriteLine to see if all messages are read from the queue

private static void queue_ReceiveCompleted(object source,
         ReceiveCompletedEventArgs e)
    {
        MessageQueue mq = (MessageQueue)source;
        Message msg = mq.EndReceive(e.AsyncResult);
        mq.BeginReceive();
    }

but then the results were inconsistent some times it would read 1 message some times 4 and sometimes all.

so whats going on, am I doing anything wrong?


问:
Convert pandas date object to integer of form YYYYMMDD
I have a date column in my pandas dataframe in the form of YYYY-MM-DD, I need to convert this to a integer in the form YYYYMMDD. I have been at it for a long time now and can't find a simple solution.</p>

答:
you can try:

```<code>df['column_to_change']=df['column_to_change'].str.replace('-','').apply(int)
</code>```

it will change all strings (or datetime) in your column column_to_change of you DataFrame df into format YYYYMMDD with the type integer as you can check with:

```<code>df.dtypes
</code>```

Body:
you can try:

df['column_to_change']=df['column_to_change'].str.replace('-','').apply(int)

it will change all strings (or datetime) in your column column_to_change of you DataFrame df into format YYYYMMDD with the type integer as you can check with:

df.dtypes


问:
Normal JSON to GraphSON format
I have two questions:

Where I can actually find the basic format for a GraphSON file, that is guaranteed to be successfully loaded by the gremlin console? I'm trying to convert a JSON (with about 10-20 fields) to another file that can be queried by gremlin but I can't actually find any relevant information about the fields reserved by the graphson format or how I should handle the IDs etc. I exported the modern graph they provide and it's not even a valid JSON (Multiple JSON root elements), but a list of JSONs [1] I also saw fields like outE, inE...are these fields something I manually have to create?

If I am able to create the JSON, where do I tell the server to load it as the base graph when I start it? In the config file or in the script?

Thanks!
Adrian

[1] https://pastebin.com/drwXhg5k

```<code>{"id":1,"label":"person","outE":{"created":[{"id":9,"inV":3,"properties":{"weight":0.4}}],"knows":[{"id":7,"inV":2,"properties":{"weight":0.5}},{"id":8,"inV":4,"properties":{"weight":1.0}}]},"properties":{"name":[{"id":0,"value":"marko"}],"age":[{"id":1,"value":29}]}}
{"id":2,"label":"person","inE":{"knows":[{"id":7,"outV":1,"properties":{"weight":0.5}}]},"properties":{"name":[{"id":2,"value":"vadas"}],"age":[{"id":3,"value":27}]}}
{"id":3,"label":"software","inE":{"created":[{"id":9,"outV":1,"properties":{"weight":0.4}},{"id":11,"outV":4,"properties":{"weight":0.4}},{"id":12,"outV":6,"properties":{"weight":0.2}}]},"properties":{"name":[{"id":4,"value":"lop"}],"lang":[{"id":5,"value":"java"}]}}
{"id":4,"label":"person","inE":{"knows":[{"id":8,"outV":1,"properties":{"weight":1.0}}]},"outE":{"created":[{"id":10,"inV":5,"properties":{"weight":1.0}},{"id":11,"inV":3,"properties":{"weight":0.4}}]},"properties":{"name":[{"id":6,"value":"josh"}],"age":[{"id":7,"value":32}]}}
{"id":5,"label":"software","inE":{"created":[{"id":10,"outV":4,"properties":{"weight":1.0}}]},"properties":{"name":[{"id":8,"value":"ripple"}],"lang":[{"id":9,"value":"java"}]}}
{"id":6,"label":"person","outE":{"created":[{"id":12,"inV":3,"properties":{"weight":0.2}}]},"properties":{"name":[{"id":10,"value":"peter"}],"age":[{"id":11,"value":35}]}}
</code>```

答:
Where I can actually find the basic format for a GraphSON file, that is guaranteed to be successfully loaded by the gremlin console?

There are multiple versions of GraphSON at this point. You can get a reference in the Apache TinkerPop IO Documentation. When you write, "successfully loaded by the gremlin console" I assume that you mean with the GraphSONReader methods described here. Of so, then the format you show above is one form you can use. It is not valid JSON as you can see, though you can build the reader/writer with the wrapAdjacencyList option set to true and it will produce valid JSON. Here is an example:

```<code>gremlin> graph = TinkerFactory.createModern();
==>tinkergraph[vertices:6 edges:6]
gremlin> writer =  graph.io(IoCore.graphson()).writer().wrapAdjacencyList(true).create()
==>org.apache.tinkerpop.gremlin.structure.io.graphson.GraphSONWriter@24a298a6
gremlin> os = new FileOutputStream('wrapped-adjacency-list.json')
==>java.io.FileOutputStream@6d3c232f
gremlin> writer.writeGraph(os, graph)
gremlin> os.close()
gremlin> newGraph = TinkerGraph.open()
==>tinkergraph[vertices:0 edges:0]
gremlin> ins = new FileInputStream('wrapped-adjacency-list.json')
==>java.io.FileInputStream@7435a578
gremlin> reader = graph.io(IoCore.graphson()).reader().unwrapAdjacencyList(true).create()
==>org.apache.tinkerpop.gremlin.structure.io.graphson.GraphSONReader@63da207f
gremlin> reader.readGraph(ins, newGraph)
gremlin> newGraph
==>tinkergraph[vertices:6 edges:6]
</code>```

The reason you do not get valid JSON by default is because the standard format for a GraphSON file needs to be splittable for Hadoop and other distributed processing engines. Therefore it produces one line per vertex - a StarGraph format.

If I am able to create the JSON, where do I tell the server to load it as the base graph when I start it? In the config file or in the script?

A script would work. as would the gremlin.tinkergraph.graphLocation and gremlin.tinkergraph.graphFormat configuration options on TinkerGraph.

Ultimately though, if you have existing JSON and you aren't loading tens of millions of graph elements, it is probably easiest to just parse it and use standard g.addV() and g.addE() methods to build the graph:

```<code>gremlin> import groovy.json.*
==>org.apache.tinkerpop.gremlin.structure.*,...
gremlin> graph = TinkerGraph.open()
==>tinkergraph[vertices:0 edges:0]
gremlin> g = graph.traversal()
==>graphtraversalsource[tinkergraph[vertices:0 edges:0], standard]
gremlin> jsonSlurper = new JsonSlurper()
==>groovy.json.JsonSlurper@53e3a87a
gremlin> object = jsonSlurper.parseText('[{ "name": "John Doe" }, { "name" : "Jane Doe" }]')
==>[name:John Doe]
==>[name:Jane Doe]
gremlin> object.each {g.addV('name',it.name).iterate() }
==>[name:John Doe]
==>[name:Jane Doe]
gremlin> g.V().valueMap()
==>[name:[John Doe]]
==>[name:[Jane Doe]]
</code>```

Trying to convert that to GraphSON is overly complicated compared to the approach above.

Title: Normal JSON to GraphSON format

Body:
I have two questions:

Where I can actually find the basic format for a GraphSON file, that is guaranteed to be successfully loaded by the gremlin console? I'm trying to convert a JSON (with about 10-20 fields) to another file that can be queried by gremlin but I can't actually find any relevant information about the fields reserved by the graphson format or how I should handle the IDs etc. I exported the modern graph they provide and it's not even a valid JSON (Multiple JSON root elements), but a list of JSONs [1] I also saw fields like outE, inE...are these fields something I manually have to create?

If I am able to create the JSON, where do I tell the server to load it as the base graph when I start it? In the config file or in the script?

Thanks!
Adrian

[1] https://pastebin.com/drwXhg5k

{"id":1,"label":"person","outE":{"created":[{"id":9,"inV":3,"properties":{"weight":0.4}}],"knows":[{"id":7,"inV":2,"properties":{"weight":0.5}},{"id":8,"inV":4,"properties":{"weight":1.0}}]},"properties":{"name":[{"id":0,"value":"marko"}],"age":[{"id":1,"value":29}]}}
{"id":2,"label":"person","inE":{"knows":[{"id":7,"outV":1,"properties":{"weight":0.5}}]},"properties":{"name":[{"id":2,"value":"vadas"}],"age":[{"id":3,"value":27}]}}
{"id":3,"label":"software","inE":{"created":[{"id":9,"outV":1,"properties":{"weight":0.4}},{"id":11,"outV":4,"properties":{"weight":0.4}},{"id":12,"outV":6,"properties":{"weight":0.2}}]},"properties":{"name":[{"id":4,"value":"lop"}],"lang":[{"id":5,"value":"java"}]}}
{"id":4,"label":"person","inE":{"knows":[{"id":8,"outV":1,"properties":{"weight":1.0}}]},"outE":{"created":[{"id":10,"inV":5,"properties":{"weight":1.0}},{"id":11,"inV":3,"properties":{"weight":0.4}}]},"properties":{"name":[{"id":6,"value":"josh"}],"age":[{"id":7,"value":32}]}}
{"id":5,"label":"software","inE":{"created":[{"id":10,"outV":4,"properties":{"weight":1.0}}]},"properties":{"name":[{"id":8,"value":"ripple"}],"lang":[{"id":9,"value":"java"}]}}
{"id":6,"label":"person","outE":{"created":[{"id":12,"inV":3,"properties":{"weight":0.2}}]},"properties":{"name":[{"id":10,"value":"peter"}],"age":[{"id":11,"value":35}]}}

Body:
Where I can actually find the basic format for a GraphSON file, that is guaranteed to be successfully loaded by the gremlin console?

There are multiple versions of GraphSON at this point. You can get a reference in the Apache TinkerPop IO Documentation. When you write, "successfully loaded by the gremlin console" I assume that you mean with the GraphSONReader methods described here. Of so, then the format you show above is one form you can use. It is not valid JSON as you can see, though you can build the reader/writer with the wrapAdjacencyList option set to true and it will produce valid JSON. Here is an example:

gremlin> graph = TinkerFactory.createModern();
==>tinkergraph[vertices:6 edges:6]
gremlin> writer =  graph.io(IoCore.graphson()).writer().wrapAdjacencyList(true).create()
==>org.apache.tinkerpop.gremlin.structure.io.graphson.GraphSONWriter@24a298a6
gremlin> os = new FileOutputStream('wrapped-adjacency-list.json')
==>java.io.FileOutputStream@6d3c232f
gremlin> writer.writeGraph(os, graph)
gremlin> os.close()
gremlin> newGraph = TinkerGraph.open()
==>tinkergraph[vertices:0 edges:0]
gremlin> ins = new FileInputStream('wrapped-adjacency-list.json')
==>java.io.FileInputStream@7435a578
gremlin> reader = graph.io(IoCore.graphson()).reader().unwrapAdjacencyList(true).create()
==>org.apache.tinkerpop.gremlin.structure.io.graphson.GraphSONReader@63da207f
gremlin> reader.readGraph(ins, newGraph)
gremlin> newGraph
==>tinkergraph[vertices:6 edges:6]

The reason you do not get valid JSON by default is because the standard format for a GraphSON file needs to be splittable for Hadoop and other distributed processing engines. Therefore it produces one line per vertex - a StarGraph format.

If I am able to create the JSON, where do I tell the server to load it as the base graph when I start it? In the config file or in the script?

A script would work. as would the gremlin.tinkergraph.graphLocation and gremlin.tinkergraph.graphFormat configuration options on TinkerGraph.

Ultimately though, if you have existing JSON and you aren't loading tens of millions of graph elements, it is probably easiest to just parse it and use standard g.addV() and g.addE() methods to build the graph:

gremlin> import groovy.json.*
==>org.apache.tinkerpop.gremlin.structure.*,...
gremlin> graph = TinkerGraph.open()
==>tinkergraph[vertices:0 edges:0]
gremlin> g = graph.traversal()
==>graphtraversalsource[tinkergraph[vertices:0 edges:0], standard]
gremlin> jsonSlurper = new JsonSlurper()
==>groovy.json.JsonSlurper@53e3a87a
gremlin> object = jsonSlurper.parseText('[{ "name": "John Doe" }, { "name" : "Jane Doe" }]')
==>[name:John Doe]
==>[name:Jane Doe]
gremlin> object.each {g.addV('name',it.name).iterate() }
==>[name:John Doe]
==>[name:Jane Doe]
gremlin> g.V().valueMap()
==>[name:[John Doe]]
==>[name:[Jane Doe]]

Trying to convert that to GraphSON is overly complicated compared to the approach above.


问:
Parsing chess notation string in R to find last move number
Have a list of strings ChessNotation like this:

"26. Qb7 Qc6 0-1"

"31. g3 Rh2 32. a4 Rxh3 33. Kg2 Rh5 34. a5 Rg5 35. Ra8 Rg4 1/2-1/2"

"36. Bd4 Bxb3 37. Rxc7+ Bxc7 38. axb3 a6 39. h3 Ke6 40. g4 1-0"

"34. b4 Ra8 35. Ng5 Rxa3 36. Nf3 Rb3 37. Kg3 Rxb4 38. h4 Kf6 39. Ng1 Kf5 0-1"
"25. Rad1 Qc6 26. Qb8 1-0"

I want to parse out the last move number from each.
So results from above would be: 26, 35, 40, 39, 26

Original plan was to str_split with space and then figure out if I need the 3rd last or the 4th last entry in the resulting list.

Problem is: I can't figure out how to get the length from a vector of string of string. If I do:

length(str_split(ChessNotation,' '))

I get 5, the number of entries in the ChessNotation list. I need to get back a vector with the number of entries in each str_split list.

I'd appreciate any help with getting the length of each list or with how to parse out the move number I need in general.

I should note I have no idea how to do regular expressions, but if anyone can point out how to do them for this instance that would be perfect too.

Thanks!

答:
Here's a simplish method: </p>

```<code>data = data.frame(x = c("26. Qb7 Qc6 0-1",
                        "31. g3 Rh2 32. a4 Rxh3 33. Kg2 Rh5 34. a5 Rg5 35. Ra8 Rg4 1/2-1/2",
                        "36. Bd4 Bxb3 37. Rxc7+ Bxc7 38. axb3 a6 39. h3 Ke6 40. g4 1-0"))
splits = str_split(data$x, pattern = " ")
last_move = function(x){
  x[max(grep(pattern = "^[0-9]+\\.$", x = x))]
}
data$last_moves = mapply(FUN = last_move, x = splits)
</code>```

Body:
Here's a simplish method:

data = data.frame(x = c("26. Qb7 Qc6 0-1",
                        "31. g3 Rh2 32. a4 Rxh3 33. Kg2 Rh5 34. a5 Rg5 35. Ra8 Rg4 1/2-1/2",
                        "36. Bd4 Bxb3 37. Rxc7+ Bxc7 38. axb3 a6 39. h3 Ke6 40. g4 1-0"))
splits = str_split(data$x, pattern = " ")
last_move = function(x){
  x[max(grep(pattern = "^[0-9]+\\.$", x = x))]
}
data$last_moves = mapply(FUN = last_move, x = splits)


问:
Incorrect lookat matrix
I've started working on shadow maps for directional lights and for that I need a lookAt matrix, but when I tried constructing from example of an online tutorial it looked something like this:

It currently looks like this:
https://media.giphy.com/media/QrMnqBBJZuATu/giphy.gif

I've tried multiple ways of constructing it but with no success, I checked if the normalization, cross and translation functions weren't correct but that wasn't the case. I've also tried changing from column-major matrices to row-major matrices but with no luck. Would someone be able to point out what I did wrong?

Lookat matrix constructing:

Center vector = (0, 0, 0),
Up vector = (0, 1, 0)

```<code>Matrix4f Matrix4f::lookAt(const Vector3f& position, const Vector3f& center, const Vector3f& up) {
        Matrix4f out(1.0f);

        Vector3f z = position.substract(center).normalize();

        Vector3f y = up;

        Vector3f x = y.cross(z).normalize();

        y = z.cross(x);

        out.mElements[0 * 4 + 0] = x.x;
        out.mElements[0 * 4 + 1] = x.y;
        out.mElements[0 * 4 + 2] = x.z;

        out.mElements[1 * 4 + 0] = y.x;
        out.mElements[1 * 4 + 1] = y.y;
        out.mElements[1 * 4 + 2] = y.z;

        out.mElements[2 * 4 + 0] = z.x;
        out.mElements[2 * 4 + 1] = z.y;
        out.mElements[2 * 4 + 2] = z.z;

        return (out * Matrix4f::translation(Vector3f(-position.x, -position.y, -position.z)));
    }
}
</code>```

Credit for code: https://stackoverflow.com/users/5577765/rabbid76

This is how I pass a matrix to the shader:

```<code>void Shader::setMat4(const char* name, const math::Matrix4f& matrix){
    glUniformMatrix4fv(getUniformLocation(name), 1, GL_TRUE, matrix.mElements);
}
</code>```

After I've calculated the lookAt matrix I directly pass it to the vertex shader to the uniform: view and calculate a point like this:

```<code>gl_Position = projection * view * model * vec4(vertexPosition, 1.0);
</code>```

And this is how my matrix multiplication works:

```<code>Matrix4f Matrix4f::multiply(const Matrix4f& other) const {
    Matrix4f out;
    for (int y = 0; y < 4; y++) {
        for (int x = 0; x < 4; x++) {
            fl32 o = 0;
            for (int c = 0; c < 4; c++) {
                o += this->mElements[c + y * 4] * other.mElements[x + c * 4];                   }
            out.mElements[x + y * 4] = o;
        }
    }
    return out;
}
</code>```

Edit: updated picture
Edit: Added a more detailed description

答: You need to normalize s before u is calculated. I'm not sure if it is the only problem</p>

Title: Incorrect lookat matrix

Body:
I've started working on shadow maps for directional lights and for that I need a lookAt matrix, but when I tried constructing from example of an online tutorial it looked something like this:

It currently looks like this:
https://media.giphy.com/media/QrMnqBBJZuATu/giphy.gif

I've tried multiple ways of constructing it but with no success, I checked if the normalization, cross and translation functions weren't correct but that wasn't the case. I've also tried changing from column-major matrices to row-major matrices but with no luck. Would someone be able to point out what I did wrong?

Lookat matrix constructing:

Center vector = (0, 0, 0),
Up vector = (0, 1, 0)

Matrix4f Matrix4f::lookAt(const Vector3f& position, const Vector3f& center, const Vector3f& up) {
        Matrix4f out(1.0f);

        Vector3f z = position.substract(center).normalize();

        Vector3f y = up;

        Vector3f x = y.cross(z).normalize();

        y = z.cross(x);

        out.mElements[0 * 4 + 0] = x.x;
        out.mElements[0 * 4 + 1] = x.y;
        out.mElements[0 * 4 + 2] = x.z;

        out.mElements[1 * 4 + 0] = y.x;
        out.mElements[1 * 4 + 1] = y.y;
        out.mElements[1 * 4 + 2] = y.z;

        out.mElements[2 * 4 + 0] = z.x;
        out.mElements[2 * 4 + 1] = z.y;
        out.mElements[2 * 4 + 2] = z.z;

        return (out * Matrix4f::translation(Vector3f(-position.x, -position.y, -position.z)));
    }
}

Credit for code: https://stackoverflow.com/users/5577765/rabbid76

This is how I pass a matrix to the shader:

void Shader::setMat4(const char* name, const math::Matrix4f& matrix){
    glUniformMatrix4fv(getUniformLocation(name), 1, GL_TRUE, matrix.mElements);
}

After I've calculated the lookAt matrix I directly pass it to the vertex shader to the uniform: view and calculate a point like this:

gl_Position = projection * view * model * vec4(vertexPosition, 1.0);

And this is how my matrix multiplication works:

Matrix4f Matrix4f::multiply(const Matrix4f& other) const {
    Matrix4f out;
    for (int y = 0; y < 4; y++) {
        for (int x = 0; x < 4; x++) {
            fl32 o = 0;
            for (int c = 0; c < 4; c++) {
                o += this->mElements[c + y * 4] * other.mElements[x + c * 4];                   }
            out.mElements[x + y * 4] = o;
        }
    }
    return out;
}

Edit: updated picture
Edit: Added a more detailed description


问:
toDataURL() very slow
I have a report with charts and tables.

I am using the html2canvas with jsPDF to export this report to PDF file.

But the process is taking a long time, more than 11000ms.

I've tried to change the format, the quality, but nothing worked.

See below the code I used:

```<code>html2canvas($('#first-page'), {
    onrendered: function(canvas) {
        firstPage = canvas.toDataURL('image/jpeg', 0.5);
    },
    background: '#ffffff'
});
</code>```

I'm doing something wrong or really is a problem?

How I can improve the performance?

答:
You don't need to use toDataUrl.http://jsfiddle.net/davidmather/sxp0meer/3/</p>

```<code>html2canvas($('#first-page'), {
onrendered: function(canvas) {
    var doc = new jsPDF('p', 'mm');
    doc.addImage(canvas, 'PNG', 10, 10);
    doc.save('sample-file.pdf');
}
});
</code>```

Title: toDataURL() very slow

Body:
I have a report with charts and tables.

I am using the html2canvas with jsPDF to export this report to PDF file.

But the process is taking a long time, more than 11000ms.

I've tried to change the format, the quality, but nothing worked.

See below the code I used:

html2canvas($('#first-page'), {
    onrendered: function(canvas) {
        firstPage = canvas.toDataURL('image/jpeg', 0.5);
    },
    background: '#ffffff'
});

I'm doing something wrong or really is a problem?

How I can improve the performance?

Body:
You don't need to use toDataUrl.http://jsfiddle.net/davidmather/sxp0meer/3/

html2canvas($('#first-page'), {
onrendered: function(canvas) {
    var doc = new jsPDF('p', 'mm');
    doc.addImage(canvas, 'PNG', 10, 10);
    doc.save('sample-file.pdf');
}
});


问:
Unique word count on selected word in file python
With Python 2.7 I open an external file which contains:

```<code>Text another word1
Lorem ipsem word1 something
hello first word2 post
</code>```

I want to perform an unique count on the word word only, not on the 3rd row.

Desired output:

```<code>$ script.py
2x word1
1x word2
</code>```

What I got so far but fails..:

```<code>import os
import sys
from collections import Counter

with open('./file.txt', 'r') as file:
        for item in file:
            if '.sh' in item:
                    all = item.split()[2]
                    print Counter(all.split())
</code>```

答:
Hey If you want to print all the words starting with word here is the code

```<code>import os
import sys

occurenceDict = {}
with open('./file.txt', 'r') as file:
    for line in file:  # reading each line of the file
        for word in line.split():  # splitting the line into words
           if word.find('word') != -1: # find the occurrence of word
                if word in occurenceDict: # check if word in dict
                    occurenceDict[word] += 1
                else:
                    occurenceDict[word] = 1

for word in occurenceDict:
    print str(occurenceDict[word])+'x'+" "+word
</code>```

Output:

```<code>2x word1
1x word2
</code>```

Body:
With Python 2.7 I open an external file which contains:

Text another word1
Lorem ipsem word1 something
hello first word2 post

I want to perform an unique count on the word word only, not on the 3rd row.

Desired output:

$ script.py
2x word1
1x word2

What I got so far but fails..:

import os
import sys
from collections import Counter

with open('./file.txt', 'r') as file:
        for item in file:
            if '.sh' in item:
                    all = item.split()[2]
                    print Counter(all.split())

Body:
Hey If you want to print all the words starting with word here is the code

import os
import sys

occurenceDict = {}
with open('./file.txt', 'r') as file:
    for line in file:  # reading each line of the file
        for word in line.split():  # splitting the line into words
           if word.find('word') != -1: # find the occurrence of word
                if word in occurenceDict: # check if word in dict
                    occurenceDict[word] += 1
                else:
                    occurenceDict[word] = 1

for word in occurenceDict:
    print str(occurenceDict[word])+'x'+" "+word

Output:

2x word1
1x word2


问:
Sort items by name in template instead of controller
Here is my runable Plunker

I want to sort items by name. This is the bug, for the top one, "Please select a student name", it displays as an empty field.

```<code><select ng-options="student as student.name for student in students | orderBy: sortNameExcludeTopOne"
        ng-model = "student">
</select>

$scope.sortNameExcludeTopOne = function(student) {
        if (student.id === 0) {
          return -1;
        }
        return student.name;
      }
</code>```

What I want:

Now I sort items by its name by using a custom function in the controller, can we do sort items by its name in the template? instead of in controller?

What UI I want for select is:
"Please select a student name" -> "Bar" -> "Foo"

Update: I want the "Please select a student name" at the top of select

答:
You don't need push the item to array, you can put then direct in the view:</p>

```<code><select ng-options="student as student.name for student in students | orderBy: 'name'" ng-model = "student">
  <option value="">Please select a student name</option>
</select>
</code>```

Body:
Here is my runable Plunker

I want to sort items by name. This is the bug, for the top one, "Please select a student name", it displays as an empty field.

<select ng-options="student as student.name for student in students | orderBy: sortNameExcludeTopOne"
        ng-model = "student">
</select>

$scope.sortNameExcludeTopOne = function(student) {
        if (student.id === 0) {
          return -1;
        }
        return student.name;
      }

What I want:

Now I sort items by its name by using a custom function in the controller, can we do sort items by its name in the template? instead of in controller?

What UI I want for select is:
"Please select a student name" -> "Bar" -> "Foo"

Update: I want the "Please select a student name" at the top of select

Body:
You don't need push the item to array, you can put then direct in the view:

<select ng-options="student as student.name for student in students | orderBy: 'name'" ng-model = "student">
  <option value="">Please select a student name</option>
</select>


问:
open desktop using QText Browser
Right now I am displaying something like /home/binary/ in QText browser. Now I want the open the folder by clicking on this text. How to do that ? Thanks in advance

Here is my sample code. I am display the result
s

```<code>bool MainWindow::displayResult(multimap<string,
</code>```

string> &resultMap, string &filePath)
      {
          multimap::iterator iter;
          bool fileStatus = false;
          int noOfLocFound = 0, forAppending = 0;
          QString no;

```<code>    noOfLocFound = resultMap.size();

    if ( noOfLocFound != 0 )
        ui->textBrowser->append( "<i>File found at <b>" + no.setNum (
</code>```

noOfLocFound ) + " locations");

```<code>    for ( forAppending = 0,iter = resultMap.begin(); iter !=
</code>```

resultMap.end(); iter++,
  forAppending++ )
          {
              string file = iter->first;
              string dir = iter->second;

```<code>        if ( forAppending == 0)
            filePath.append(dir);
        else
            filePath.append(","+dir);

        QString qdir = QString::fromStdString(dir);

        cout << "Display";

        ui->textBrowser->append( qdir );
        fileStatus = true;

    }

    if ( fileStatus == false )
    {
        ui->textBrowser->append("File not
</code>```

found");
              return false;
          }

```<code>    return true;
}
</code>```

答:
By "open the folder", do you mean, open a file dialog for the user to select something inside of the given directory?

If so, you would probably want to connect your QTextBrowser's clicked signal to a slot that looked something like:

```<code>// connect events, in MyWindow constructor, or whereever...
connect(textbrowser, SIGNAL(mousePressEvent(QMouseEvent*)), this, SLOT(openFileDialog(QMouseEvent*)));

void MyWindow::openFileDialog(QMouseEvent* event) {
    Q_UNUSED(event);

    QStringList files = QFileDialog::getOpenFileNames(this, "Select a file...",
        textbrowser.plainText());

    // do something with the files here...
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: open desktop using QText Browser

Body:
Right now I am displaying something like /home/binary/ in QText browser. Now I want the open the folder by clicking on this text. How to do that ? Thanks in advance

Here is my sample code. I am display the result
s

bool MainWindow::displayResult(multimap<string,

string> &resultMap, string &filePath)
      {
          multimap::iterator iter;
          bool fileStatus = false;
          int noOfLocFound = 0, forAppending = 0;
          QString no;

    noOfLocFound = resultMap.size();

    if ( noOfLocFound != 0 )
        ui->textBrowser->append( "File found at " + no.setNum (

noOfLocFound ) + " locations");

    for ( forAppending = 0,iter = resultMap.begin(); iter !=

resultMap.end(); iter++,
  forAppending++ )
          {
              string file = iter->first;
              string dir = iter->second;

        if ( forAppending == 0)
            filePath.append(dir);
        else
            filePath.append(","+dir);

        QString qdir = QString::fromStdString(dir);

        cout << "Display";

        ui->textBrowser->append( qdir );
        fileStatus = true;

    }

    if ( fileStatus == false )
    {
        ui->textBrowser->append("File not

found");
              return false;
          }

    return true;
}

Body:
By "open the folder", do you mean, open a file dialog for the user to select something inside of the given directory?

If so, you would probably want to connect your QTextBrowser's clicked signal to a slot that looked something like:

// connect events, in MyWindow constructor, or whereever...
connect(textbrowser, SIGNAL(mousePressEvent(QMouseEvent*)), this, SLOT(openFileDialog(QMouseEvent*)));

void MyWindow::openFileDialog(QMouseEvent* event) {
    Q_UNUSED(event);

    QStringList files = QFileDialog::getOpenFileNames(this, "Select a file...",
        textbrowser.plainText());

    // do something with the files here...
}


答:
If your pandas column is datetime dtype then use datetime access .dt and strftime, if you are talking about a datetimeindex then you don't need the .dt:

```<code>df['Date'].dt.strftime('%Y%m%d')
</code>```

Title: Convert pandas date object to integer of form YYYYMMDD

Body: I have a date column in my pandas dataframe in the form of YYYY-MM-DD, I need to convert this to a integer in the form YYYYMMDD. I have been at it for a long time now and can't find a simple solution.

Body:
If your pandas column is datetime dtype then use datetime access .dt and strftime, if you are talking about a datetimeindex then you don't need the .dt:

df['Date'].dt.strftime('%Y%m%d')


问:
Find hash in interval
I have an SHA-224 hash and I know it can be made with a number from 0.0000(29 0s)1 and 0.999(30 9s). How could I check if a given hash is made with a number in some interval, I.e. between 0.00(29 0s) and 0.666(30 6s), without having to calculate all the hashes.</p>

答: There is no way to do what you want to do with SHA-224 without calculating all of the hashes and building lookup tables.</p>

Title: Find hash in interval


问:
How to get Laravel 5.4 working with AWS SQS Queues
I am using Laravel 5.4 with an SQS Fifo Queue.

I can't seem to be able to get it working with my SQS Fifo Queue. To Queue my email job.

Can anyone with experience of this point me in the right direction for how to get laravel working with my SQS Fifo Queue.

This is my controller code to add the job to the queue:

```<code>(new ReferFriendEmail($referFriendObj))->onConnection('my_sqs_fifo');
</code>```

This is the code of my job:

```<code>class ReferFriendEmail implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $referFriendObj = false;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($referFriendObj)
    {
        $this->referFriendObj = $referFriendObj;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle(  )
    {
        $input = $this->referFriendObj->input;

        Mail::send( 'emails.refer-a-friend',
            [
                'user' => $this->referFriendObj->from_user_info,
                'first_name' => strtoupper( trim( $this->referFriendObj->from_user_info->first_name)),
                'unique_link' => $this->referFriendObj->unique_link,
            ],
            function ($m) use ( $input ) {
                    $m->from('ryan_hughes_smith@live.co.uk', 'Kuflink');
                    $m->to($input['to_email'], $input['to_email'] )->subject( "You've been referred to Kuflink by " . $input['first_name'] );
            }
        );

        Email_user_referrer::where('email' , $input['to_email'])
                            ->update(['flag_email_sent' => 1]);
    }
}
</code>```

It just seems nothing is going sqs. I am using it as the driver.

答:
Per the comments, you're creating the job, but you aren't actually sending it. The dispatch helper does this for you:

```<code>$job = (new ReferFriendEmail($referFriendObj))->onConnection('my_sqs_fifo');
dispatch($job);
</code>```

Body:
I am using Laravel 5.4 with an SQS Fifo Queue.

I can't seem to be able to get it working with my SQS Fifo Queue. To Queue my email job.

Can anyone with experience of this point me in the right direction for how to get laravel working with my SQS Fifo Queue.

This is my controller code to add the job to the queue:

(new ReferFriendEmail($referFriendObj))->onConnection('my_sqs_fifo');

This is the code of my job:

class ReferFriendEmail implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $referFriendObj = false;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($referFriendObj)
    {
        $this->referFriendObj = $referFriendObj;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle(  )
    {
        $input = $this->referFriendObj->input;

        Mail::send( 'emails.refer-a-friend',
            [
                'user' => $this->referFriendObj->from_user_info,
                'first_name' => strtoupper( trim( $this->referFriendObj->from_user_info->first_name)),
                'unique_link' => $this->referFriendObj->unique_link,
            ],
            function ($m) use ( $input ) {
                    $m->from('ryan_hughes_smith@live.co.uk', 'Kuflink');
                    $m->to($input['to_email'], $input['to_email'] )->subject( "You've been referred to Kuflink by " . $input['first_name'] );
            }
        );

        Email_user_referrer::where('email' , $input['to_email'])
                            ->update(['flag_email_sent' => 1]);
    }
}

It just seems nothing is going sqs. I am using it as the driver.

Body:
Per the comments, you're creating the job, but you aren't actually sending it. The dispatch helper does this for you:

$job = (new ReferFriendEmail($referFriendObj))->onConnection('my_sqs_fifo');
dispatch($job);


问:
EXCEL VBA - Copying columns that match a condition from one worksheet to a formatted worksheet
I'm very familiar with vlookup, pivot tables, but feel like this can be accomplished with VBA.

Here is what I'm trying to do:

Sheet 1: data sheet with headers.
Sheet 2: summary sheet that is formatted with a specific look and data can only be pasted into the sheet starting at row 10.

In sheet 2, B5, has a drop down list that allows you to select a name.

I want someone to be able to check if the value in Sheet 2 B5, matches up Sheet 1 Column A.

then the code will go back to the data sheet (sheet 1) and check in column A if it matches Sheet 2 B5.

If Sheet 2 B5, matches Sheet 1 Column A, then copy Sheet 1 columns B, C, D, E, H, I, J, K, L, M, N, R, S, T, U, V, W, X, Y, that match Sheet 2 B5 value, INTO sheet 2 starting at row 10.

other notes
- Formats from Sheet 1 cannot be copied into Sheet 2. I just need the contents.
- the button to run the code is on sheet 2. (thus sheet 2 is the active sheet at the time the macro runs).

My code so far...

```<code>Sub Report ()
Dim finalrow As Integer, i as Integer, name as String
Sheets("Sheet 2").Range("A10:N29").ClearContents
name = Sheets("Sheet 2").Range("B5").Value
For i = 2 To Sheets("Sheet 1").Range("B" & Rows.Count).End(xlUp).Row
If Cells(i, 1) = name Then
Range(Cells(i, 2), Cells(i, 25)).Select
Selection.Copy
Worksheets("Sheet 2").Select
erow = ActiveSheet.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row
ActiveSheet.Cells(erow, 1).Select
ActiveSheet.PasteSpecial xlPasteFormulasAndNumberFormats
End If
Next i
End Sub
</code>```

But I keep getting

runtime error 9.

答:
Run-time error mostly happens due to not properly addressing cells. If you use explicit coding you are less likely to get these errors and also your code would be easily legible. Also use comments.

```<code>Option Explicit

Sub Report ()

 'Declare variables
  Dim name as String
  Dim wsh1 As Worksheet, wsh2 As Worksheet
  Dim erow As Long, i as Long

 'Set the sheets
  Set wsh1 = ThisWorkbook.Worksheets("Sheet 1")
  Set wsh2 = ThisWorkbook.Worksheets("Sheet 2")

 'clean destination worksheet
  wsh2.Range("A10:N29").ClearContents

  name = wsh2.Range("B5").Value 'condition for copying

 'loop over reference sheet
  For i = 2 To wsh1.Range("B" & Rows.Count).End(xlUp).Row

    'Check if the row meets the condition
    If wsh1.Cells(i, 1) = name Then

      wsh1.Range(wsh1.Cells(i, 2), wsh1.Cells(i, 25)).Copy 'copy the row

      erow = wsh2.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row 'find last row in wsh2

      wsh2.Cells(erow, 1).PasteSpecial xlPasteFormulasAndNumberFormats 'paste only values

    End If

  Next i

End Sub
</code>```

Update:

As OP mentioned that it should be always at row 10, then this would be a better approach than using last row:

At the beginning of the code and outside the for loop define erow = 10. Then your if-block should be like this:

```<code>If wsh1.Cells(i, 1) = name Then 'Check if the row meets the condition

  wsh1.Range(wsh1.Cells(i, 2), wsh1.Cells(i, 25)).Copy 'copy the row

  wsh2.Cells(erow, 1).PasteSpecial xlPasteFormulasAndNumberFormats 'paste only values

  erow = erow + 1

End If
</code>```

Body:
I'm very familiar with vlookup, pivot tables, but feel like this can be accomplished with VBA.

Here is what I'm trying to do:

Sheet 1: data sheet with headers.
Sheet 2: summary sheet that is formatted with a specific look and data can only be pasted into the sheet starting at row 10.

In sheet 2, B5, has a drop down list that allows you to select a name.

I want someone to be able to check if the value in Sheet 2 B5, matches up Sheet 1 Column A.

then the code will go back to the data sheet (sheet 1) and check in column A if it matches Sheet 2 B5.

If Sheet 2 B5, matches Sheet 1 Column A, then copy Sheet 1 columns B, C, D, E, H, I, J, K, L, M, N, R, S, T, U, V, W, X, Y, that match Sheet 2 B5 value, INTO sheet 2 starting at row 10.

other notes
- Formats from Sheet 1 cannot be copied into Sheet 2. I just need the contents.
- the button to run the code is on sheet 2. (thus sheet 2 is the active sheet at the time the macro runs).

My code so far...

Sub Report ()
Dim finalrow As Integer, i as Integer, name as String
Sheets("Sheet 2").Range("A10:N29").ClearContents
name = Sheets("Sheet 2").Range("B5").Value
For i = 2 To Sheets("Sheet 1").Range("B" & Rows.Count).End(xlUp).Row
If Cells(i, 1) = name Then
Range(Cells(i, 2), Cells(i, 25)).Select
Selection.Copy
Worksheets("Sheet 2").Select
erow = ActiveSheet.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row
ActiveSheet.Cells(erow, 1).Select
ActiveSheet.PasteSpecial xlPasteFormulasAndNumberFormats
End If
Next i
End Sub

But I keep getting

runtime error 9.

Body:
Run-time error mostly happens due to not properly addressing cells. If you use explicit coding you are less likely to get these errors and also your code would be easily legible. Also use comments.

Option Explicit

Sub Report ()

 'Declare variables
  Dim name as String
  Dim wsh1 As Worksheet, wsh2 As Worksheet
  Dim erow As Long, i as Long

 'Set the sheets
  Set wsh1 = ThisWorkbook.Worksheets("Sheet 1")
  Set wsh2 = ThisWorkbook.Worksheets("Sheet 2")

 'clean destination worksheet
  wsh2.Range("A10:N29").ClearContents

  name = wsh2.Range("B5").Value 'condition for copying

 'loop over reference sheet
  For i = 2 To wsh1.Range("B" & Rows.Count).End(xlUp).Row

    'Check if the row meets the condition
    If wsh1.Cells(i, 1) = name Then

      wsh1.Range(wsh1.Cells(i, 2), wsh1.Cells(i, 25)).Copy 'copy the row

      erow = wsh2.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row 'find last row in wsh2

      wsh2.Cells(erow, 1).PasteSpecial xlPasteFormulasAndNumberFormats 'paste only values

    End If

  Next i

End Sub

Update:

As OP mentioned that it should be always at row 10, then this would be a better approach than using last row:

At the beginning of the code and outside the for loop define erow = 10. Then your if-block should be like this:

If wsh1.Cells(i, 1) = name Then 'Check if the row meets the condition

  wsh1.Range(wsh1.Cells(i, 2), wsh1.Cells(i, 25)).Copy 'copy the row

  wsh2.Cells(erow, 1).PasteSpecial xlPasteFormulasAndNumberFormats 'paste only values

  erow = erow + 1

End If


问:
How to share my trip with Google Maps programmatically?
With the introduction of trip sharing inside Google Maps, I wonder if there is a way to share my trip with others programmatically. I am building a mobile app and I think it might be possible to send a link to other users and maybe send my location to Google Maps via its API.</p>

答:
Currently you cannot do this via Google Maps APIs.

There is a feature request in the public issue tracker:

https://issuetracker.google.com/issues/62938530

Feel free to star the feature request to add your vote and subscribe to further notifications.


问:
java use StAX to get children elements in a generic fashion
I am trying to use StAX (I already dislike it....)

It seems that the only way to use it is by continuous if-else conditions.

But most important it seems there is no way to associate an element with its children unless one knows beforehand the
structure of the xml document being parsed.Is this correct?

I have tried the following:
I have this xml in a String

```<code><ns1:Root xmlns:ns1=\"http://rootNameSpace.com/\">
<ns1:A/>
<ns1:B>
        <Book xmlns=\"http://www.myNameSpace.com\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">
            <Data>
                <Author>John</Author>
                <Edition>1</Edition>
                <PubHouse>Small Publishing House</PubHouse>
                <Price>37.8</Price>
            </Data>
        </Book>
</ns1:B>
</ns1:Root>
</code>```

I would like to use StAX to get the Book element, but it seems I can only write code that has hardcoded all the structure.

I.e. Use XMLEventReader and once
you get Book, start looping for Data,Author etc.

Is there a generic solution on this?

I tried the following to get arround this: I tried to go from String to XMLEventReader and back to String but I can not get the exact String representation that I originally used (the namespaces are in brackets, extra colons etc).

```<code>StringBuilder xml = new StringBuilder();
XMLInputFactory inputFactory = XMLInputFactory.newInstance();
String msg = "<ns1:Root xmlns:ns1=\"http://rootNameSpace.com/\"><ns1:A/><ns1:B><Book xmlns=\"http://www.myNameSpace.com\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"><Data><Author>John</Author><Edition>1</Edition><PubHouse>Small Publishing House</PubHouse><Price>37.8</Price></Data></Book></ns1:B></ns1:Root>";
InputStream input = new ByteArrayInputStream(msg.getBytes("UTF-8"));
XMLEventReader xmlEventReader = inputFactory.createXMLEventReader(input);
while (xmlEventReader.hasNext())
{

    XMLEvent event = xmlEventReader.nextEvent();
    StringWriter sw = new StringWriter();
    event.writeAsEncodedUnicode(sw);
   xml.append(sw);

}
System.out.println(xml);
</code>```

I get the following:

```<code><?xml version="1.0" encoding='UTF-8' standalone='no'?><['http://rootNameSpace.com/']:ns1:Root xmlns:ns1='http://rootNameSpace.com/'><['http://rootNameSpace.com/']:ns1:A></ns1:A><['http://rootNameSpace.com/']:ns1:B><['http://www.myNameSpace.com']::Book xmlns:='http://www.myNameSpace.com' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'><['http://www.myNameSpace.com']::Data><['http://www.myNameSpace.com']::Author>John</Author><['http://www.myNameSpace.com']::Edition>1</Edition><['http://www.myNameSpace.com']::PubHouse>Small Publishing House</PubHouse><['http://www.myNameSpace.com']::Price>37.8</Price></Data></Book></ns1:B></ns1:Root>
</code>```

Can this case be addressed via StAX or DOM is the only solution?

答:
It sounds like you may have chosen the wrong tool here: Stax is a great API to use for efficient handling of large content. But if convenience is more important than efficiency, yes, you probably should consider a tree model (not DOM necessarily, XOM is better for example) or data binding (JAXB or XStream). Specifically, Stax like SAX are stream-based so you only see whatever is the current event or token. There are no accessors for children or parents because there is no guaranteed way to get to them, as that is not necessarily possible considering current stream position.

But if performance or memory usage are a concern, you can still either consider JAXB (which is typically more efficient than tree models like DOM), or StaxMate. StaxMate is high-performance, low memory usage extension over Stax, and is bit more convenient to use.
While you still need to iterate over elements in document order, its cursor approach maps more naturally with parent-then-children lookups. So it might work for your case.

Body:
I am trying to use StAX (I already dislike it....)

It seems that the only way to use it is by continuous if-else conditions.

But most important it seems there is no way to associate an element with its children unless one knows beforehand the
structure of the xml document being parsed.Is this correct?

I have tried the following:
I have this xml in a String

<ns1:Root xmlns:ns1=\"http://rootNameSpace.com/\">
<ns1:A/>
<ns1:B>
        <Book xmlns=\"http://www.myNameSpace.com\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">
            <Data>
                <Author>John</Author>
                <Edition>1</Edition>
                <PubHouse>Small Publishing House</PubHouse>
                <Price>37.8</Price>
            </Data>
        </Book>
</ns1:B>
</ns1:Root>

I would like to use StAX to get the Book element, but it seems I can only write code that has hardcoded all the structure.

I.e. Use XMLEventReader and once
you get Book, start looping for Data,Author etc.

Is there a generic solution on this?

I tried the following to get arround this: I tried to go from String to XMLEventReader and back to String but I can not get the exact String representation that I originally used (the namespaces are in brackets, extra colons etc).

StringBuilder xml = new StringBuilder();
XMLInputFactory inputFactory = XMLInputFactory.newInstance();
String msg = "<ns1:Root xmlns:ns1=\"http://rootNameSpace.com/\"><ns1:A/><ns1:B><Book xmlns=\"http://www.myNameSpace.com\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"><Data><Author>John</Author><Edition>1</Edition><PubHouse>Small Publishing House</PubHouse><Price>37.8</Price></Data></Book></ns1:B></ns1:Root>";
InputStream input = new ByteArrayInputStream(msg.getBytes("UTF-8"));
XMLEventReader xmlEventReader = inputFactory.createXMLEventReader(input);
while (xmlEventReader.hasNext())
{

    XMLEvent event = xmlEventReader.nextEvent();
    StringWriter sw = new StringWriter();
    event.writeAsEncodedUnicode(sw);
   xml.append(sw);

}
System.out.println(xml);

I get the following:

<?xml version="1.0" encoding='UTF-8' standalone='no'?><['http://rootNameSpace.com/']:ns1:Root xmlns:ns1='http://rootNameSpace.com/'><['http://rootNameSpace.com/']:ns1:A></ns1:A><['http://rootNameSpace.com/']:ns1:B><['http://www.myNameSpace.com']::Book xmlns:='http://www.myNameSpace.com' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'><['http://www.myNameSpace.com']::Data><['http://www.myNameSpace.com']::Author>John</Author><['http://www.myNameSpace.com']::Edition>1</Edition><['http://www.myNameSpace.com']::PubHouse>Small Publishing House</PubHouse><['http://www.myNameSpace.com']::Price>37.8</Price></Data></Book></ns1:B></ns1:Root>

Can this case be addressed via StAX or DOM is the only solution?


问:
ndepend - no dependency graph/metrics after analysis
I can't get any form of interactive graph in VisualNDepend. There is only a black screen.

I'm using Visual NDepend v1.9.

I created a project, selected my sln and clicked on Run Analysis and Report. I was presented with several graphs in html but they were low-res. Nex to the graphs were this note:

It is recommended to use the NDepend interactive dependency Graph and interactive Dependency Matrix for an in-depth exploration of the actual architecture of your code.

I opened VisualNDepend and checked the Dependency Graph and Dependency Matrix tabs which were empty. I went back to dashboard tab and clicked Run Analysis on Current Project but the tabs still displayed nothing. At the bottom right there is a red circle which when clicked, shows analysis complete x mins ago.

How do I display any form of graphs with ndepend? I tried on several slns.

Thanks

答:
My bad.

After going through every menu item, I found that I had to explicitly click on graph->view dependency graph and matrix->view dependency matrix to actually see the stuff.


问:
Laravel custom validation for confirm password
I have to do the back end validation for confirm password. I write my validator as

```<code>$validator = Validator::make($request->all(), [
    'first_name' => 'required',
    'last_name' => 'required',
    'email' => 'email|required',
    'password' => 'required',
    'confirm_password' => 'required',
    'tnc' => 'required'
]);
</code>```

now the confirm password must be same as the password field. Can we do it with laravel validator?

答:
```<code>'password'  =>  'required|min:6|confirmed',
'confirm_password'  =>  'required|min:6|confirmed',
</code>```

try this

Body:
I have to do the back end validation for confirm password. I write my validator as

$validator = Validator::make($request->all(), [
    'first_name' => 'required',
    'last_name' => 'required',
    'email' => 'email|required',
    'password' => 'required',
    'confirm_password' => 'required',
    'tnc' => 'required'
]);

now the confirm password must be same as the password field. Can we do it with laravel validator?

Body:
'password'  =>  'required|min:6|confirmed',
'confirm_password'  =>  'required|min:6|confirmed',

try this


问:
Upload Alexa Slot Types via API
Is there anyway of uploading Custom Slot Types values via an API, so that you do not need to type them in manually using the new Alexa Skill Builder interface (if you have many of them):

I haven't found anything.

答:
As other answers suggest, you can use the SMAPI.

Alternatively, you can select the "code editor" tab on the left and drag/drop or copy/paste your schema json code.

Title: Upload Alexa Slot Types via API

ContentLicense: CC BY-SA 4.0


问:
How to replace a particular string in js
I have a variable with the following data

Peaks in mesothelioma incidence were expected to take place between 2014 and 2021 in Australia, between 2011 and 2015 in the United Kingdom, between 2015 and 2024 in Italy, in 2010 in the United States, in 2015 in Denmark, in 2017 in the Netherlands, and in 2027 in Japan.

Here I want to replace

```<code><img src="test" />
</code>```

To

```<code><amp-img src="test"></amp-img>
</code>```

But here I am getting the data of 100 records as an example I put

```<code> <img src="test" />
</code>```

But I am not sure what my img tag contains.So I van replace img with

```<code>replace('<img',<amp-img>);
</code>```

But how can I replace the end tag i.e

```<code>  ('/>','></amp-img>').
</code>```

Can any one please suggest me help.Thanks.

答:
This will replace the very last closing tag with what you want:</p>

```<code>sampleString.replace(sampleString.slice(sampleString.lastIndexOf(' />')), '></amp-img>');
</code>```

Body:
I have a variable with the following data

Peaks in mesothelioma incidence were expected to take place between 2014 and 2021 in Australia, between 2011 and 2015 in the United Kingdom, between 2015 and 2024 in Italy, in 2010 in the United States, in 2015 in Denmark, in 2017 in the Netherlands, and in 2027 in Japan.

Here I want to replace

To

<amp-img src="test"></amp-img>

But here I am getting the data of 100 records as an example I put

But I am not sure what my img tag contains.So I van replace img with

replace('<img',<amp-img>);

But how can I replace the end tag i.e

  ('/>','></amp-img>').

Can any one please suggest me help.Thanks.

Body:
This will replace the very last closing tag with what you want:

sampleString.replace(sampleString.slice(sampleString.lastIndexOf(' />')), '></amp-img>');


问:
Performance increase for PowerShell dataset to Excel
I have a PowerShell script which pulls data from DB and pushes it to a excel sheet. I am facing slowness (45 mins approx) while copying the records in the dataset to the excel sheet as the number of records exceed 200K. And I am trying to loop them one by one using the below snippet, which takes more time. Is there a way in which I can transfer the data from dataset to excel more efficiently?</p>

```<code>   $cells=$Worksheet.Cells
   $row=1
   foreach ($rec in $dataset.Tables[0].Rows)
        {
            $row++
            $col=1
            $cells.item($Row,$col)=$USR.ID
            $col++
            $cells.item($Row,$col)=$USR.Name
            $col++
            $cells.item($Row,$col)=$USR.Age
            $col++
        }
</code>```

答:
You shoud try PSExcel module. There's no need to create COM object and even have Excel installed. Your example would look like this and be lightning fast: </p>

```<code>$dataset.Tables[0] |
Select-Object ID,Name,Age |
Export-XLSX -Path $FullName -AutoFit -WorksheetName 'MyData'
</code>```

Body:
I have a PowerShell script which pulls data from DB and pushes it to a excel sheet. I am facing slowness (45 mins approx) while copying the records in the dataset to the excel sheet as the number of records exceed 200K. And I am trying to loop them one by one using the below snippet, which takes more time. Is there a way in which I can transfer the data from dataset to excel more efficiently?

   $cells=$Worksheet.Cells
   $row=1
   foreach ($rec in $dataset.Tables[0].Rows)
        {
            $row++
            $col=1
            $cells.item($Row,$col)=$USR.ID
            $col++
            $cells.item($Row,$col)=$USR.Name
            $col++
            $cells.item($Row,$col)=$USR.Age
            $col++
        }

Body:
You shoud try PSExcel module. There's no need to create COM object and even have Excel installed. Your example would look like this and be lightning fast:

$dataset.Tables[0] |
Select-Object ID,Name,Age |
Export-XLSX -Path $FullName -AutoFit -WorksheetName 'MyData'


问:
Beanshell - using arraylist
I am using beanshell and i want to use arraylist

My code -

```<code>import java.util.*;

List test= new ArrayList();
test.add("Last Name");
</code>```

But I am getting following exception

```<code>Caused by: org.apache.bsf.BSFException: BeanShell script error:Typed variable declaration :
Attempt to resolve method: add() on undefined variable or class name: test: at Line: 206
</code>```

Any idea what is causing the problem?

Thanks

答:
Try ArrayList test = new ArrayList();
That worked fine for me.
Guess that the BeanShell doesn't work with polymorphism.

Title: Beanshell - using arraylist

Body:
I am using beanshell and i want to use arraylist

My code -

import java.util.*;

List test= new ArrayList();
test.add("Last Name");

But I am getting following exception

Caused by: org.apache.bsf.BSFException: BeanShell script error:Typed variable declaration :
Attempt to resolve method: add() on undefined variable or class name: test: at Line: 206

Any idea what is causing the problem?

Thanks


问:
Bind checkbox to Timer.Enabled
Is it possible to bind a checkbox to Enabled property of System.Timers.Timer?

I can wrap it in a boolean property which returns its state, like this:

```<code>public bool TimerEnabled
    {
        get { return _timer.Enabled; }
        set
        {
            _timer.Enabled = value;
            InvokePropertyChanged(new PropertyChangedEventArgs("TimerEnabled"));
        }
    }
</code>```

But I don't get notified when _timer.Autoreset = false and _timer.Enabled changes value.

I want to have a checkbox ("EnabledCheckbox") in which shows the current state of the timer, and the user can enable or disable it. Besides, I want another checkbox ("AutoResetCheckbox") which controls wether this timer has it's Autoreset property enabled. And finally, if Autoreset is disabled and timer triggers Elapsed event and therefore sets Enabled to false, I want the "EnabledCheckbox" to uncheck on its own.

How do I achieve this?

Edit: I could make my own implementation of autoreset, but is there a better way?

答:
Wrap _timer.Autoreset into a property like that:

```<code>public bool Autoreset
{
    get { return _timer.Autoreset; }
    set
    {
        _timer.Autoreset = value;
        InvokePropertyChanged(new PropertyChangedEventArgs(nameof(TimerEnabled));
        InvokePropertyChanged(new PropertyChangedEventArgs(nameof(Autoreset));
    }
}
</code>```

And then work with the property instead of _timer.Autoreset.

Title: Bind checkbox to Timer.Enabled

Body:
Is it possible to bind a checkbox to Enabled property of System.Timers.Timer?

I can wrap it in a boolean property which returns its state, like this:

public bool TimerEnabled
    {
        get { return _timer.Enabled; }
        set
        {
            _timer.Enabled = value;
            InvokePropertyChanged(new PropertyChangedEventArgs("TimerEnabled"));
        }
    }

But I don't get notified when _timer.Autoreset = false and _timer.Enabled changes value.

I want to have a checkbox ("EnabledCheckbox") in which shows the current state of the timer, and the user can enable or disable it. Besides, I want another checkbox ("AutoResetCheckbox") which controls wether this timer has it's Autoreset property enabled. And finally, if Autoreset is disabled and timer triggers Elapsed event and therefore sets Enabled to false, I want the "EnabledCheckbox" to uncheck on its own.

How do I achieve this?

Edit: I could make my own implementation of autoreset, but is there a better way?

Body:
Wrap _timer.Autoreset into a property like that:

public bool Autoreset
{
    get { return _timer.Autoreset; }
    set
    {
        _timer.Autoreset = value;
        InvokePropertyChanged(new PropertyChangedEventArgs(nameof(TimerEnabled));
        InvokePropertyChanged(new PropertyChangedEventArgs(nameof(Autoreset));
    }
}

And then work with the property instead of _timer.Autoreset.


问:
How to let asynchronous readFile method follow order in node.js
I have a code like this

```<code>var fs = require('fs');
console.log("1");
fs.readFile("./index.js", function(err, data) {
    if (err) {
         console.log("err");
    }
    console.log("2");
});
console.log("3");
</code>```

and the result will be

```<code>1
3
2
</code>```

But I want 1 2 3 I have look through filesystem's document and it says With the asynchronous methods there is no guaranteed ordering.  so the document says if I want my code result 1 2 3 it should be

```<code>var fs = require('fs');
console.log("1");
fs.readFile("./index.js", function(err, data) {
    if (err) {
         console.log("err");
    }
    console.log("2");
    console.log("3");
});
</code>```

But it's for short code if I'm building a system which has a lot of other function needs to be after this code we can't nested all in because the function need to be work after it will be use by other functions so is there a way to let the fs.readFile work in order but not incuding all the code need to work after it in fs code?

code I have issue

```<code>function servedatastart() {

    if (urlcontentbasic(urlslug) != "err") {
        responsearray["data"] = urlcontentbasic(urlslug);
    } else {
        // callback function
        console.log("urlex");
        urlex("none", urlslug); // this function I use fs.readFile(urlslug, function...
    }
    console.log("other function");
    //other function
    cuswriteheader();
    includescript();
    writefooter()
    res.end();
}
</code>```

答:
Use async.waterfall, it allows you to run asynchronous functions in order, each function depends on the previous one to complete. when the last function completes the main callback is called, each function can pass the result to the next one.
check https://caolan.github.io/async/docs.html</p>

```<code>var fs = require('fs');
var async = require('async');

async.waterfall([
    function (callback) {
        console.log("1");
        callback();
    },
    function (arg1, callback) {
        fs.readFile("./index.js", callback);
        console.log("2");
    },
    function (arg2, callback) {
        console.log("3");
        callback()
    }
], function(err, res){

});
</code>```

Body:
I have a code like this

var fs = require('fs');
console.log("1");
fs.readFile("./index.js", function(err, data) {
    if (err) {
         console.log("err");
    }
    console.log("2");
});
console.log("3");

and the result will be

1
3
2

But I want 1 2 3 I have look through filesystem's document and it says With the asynchronous methods there is no guaranteed ordering.  so the document says if I want my code result 1 2 3 it should be

var fs = require('fs');
console.log("1");
fs.readFile("./index.js", function(err, data) {
    if (err) {
         console.log("err");
    }
    console.log("2");
    console.log("3");
});

But it's for short code if I'm building a system which has a lot of other function needs to be after this code we can't nested all in because the function need to be work after it will be use by other functions so is there a way to let the fs.readFile work in order but not incuding all the code need to work after it in fs code?

code I have issue

function servedatastart() {

    if (urlcontentbasic(urlslug) != "err") {
        responsearray["data"] = urlcontentbasic(urlslug);
    } else {
        // callback function
        console.log("urlex");
        urlex("none", urlslug); // this function I use fs.readFile(urlslug, function...
    }
    console.log("other function");
    //other function
    cuswriteheader();
    includescript();
    writefooter()
    res.end();
}

Body:
Use async.waterfall, it allows you to run asynchronous functions in order, each function depends on the previous one to complete. when the last function completes the main callback is called, each function can pass the result to the next one.
check https://caolan.github.io/async/docs.html

var fs = require('fs');
var async = require('async');

async.waterfall([
    function (callback) {
        console.log("1");
        callback();
    },
    function (arg1, callback) {
        fs.readFile("./index.js", callback);
        console.log("2");
    },
    function (arg2, callback) {
        console.log("3");
        callback()
    }
], function(err, res){

});