问:
insert into php isn't working
I'm not that good with PHP but i need to do a user registration form and this is what I haven done so far

```<code><!doctype html>
<html>
<head>
<title>Register</title>
</head>
<body>

<p><a href="register.php">Register</a> | <a href="login.php">Login</a></p>
<h3>Formulario de registro</h3>
<form action="" method="POST">
Usuario: <input type="text" name="login"><br />
Contrasena: <input type="password" name="password"><br />
Email: <input type="text" name="email"><br />
Sexo: <input type="text" name="sex"><br />
Edad: <input type="text" name="age"><br />
Telefono: <input type="text" name="phone"><br />
Pais: <input type="text" name="country"><br />
Ciudad: <input type="text" name="city"><br />
Direccion: <input type="text" name="address"><br />
<input type="submit" value="Register" name="submit" />
</form>
<?php
if(isset($_POST["submit"])){

if(!empty($_POST['login']) && !empty($_POST['password'])) {
    $login=$_POST['login'];
    $password=$_POST['password'];
    $email=$_POST['email'];
    $sex=$_POST['sex'];
    $age=$_POST['age'];
    $phone=$_POST['phone'];
    $country=$_POST['country'];
    $city=$_POST['city'];
    $address=$_POST['address'];

    $con=mysqli_connect('localhost','root','','registro_usuarios') or die(mysql_error());

    $sql="SELECT * FROM usuario ";
    $result = mysqli_query($con,$sql);
    if(mysqli_num_rows($result)>=0)
    {
    echo "I'm in";
    $sql="INSERT INTO usuario (login,password,email,sex,age,phone,country,city,address)
    VALUES('$login','$password','$password','$email','$sex','$age','$country','$city','$address')";

    $result=mysqli_query($con,$sql);

    if($result){
    echo "Account Successfully Created";
    } else {
    echo "Failure!";
    }

    } else {
    echo "That username already exists! Please try again with another.";
    }

} else {
    echo "All fields are required!";
}
}
?>

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

I can see the message "I'm in" in my screen but I'm also get the "Failure" message because it's not inserting anything into the the database. I have been struggling trying to find the error but nothing so far. The error should be around here

```<code>$sql="INSERT INTO usuario (login,password,email,sex,age,phone,country,city,address)
    VALUES('$login','$password','$password','$email','$sex','$age','$country','$city','$address')";

    $result=mysqli_query($con,$sql);
</code>```

I have checked all the values from my database in case of a typo just in case you guys wonder and there is no typo.

Thanks

答:
You wrong in sql insert.

your sql :

```<code>$sql="INSERT INTO usuario (login,password,email,sex,age,phone,country,city,address) VALUES('$login','$password','$password','$email','$sex','$age','$country','$city','$address')";
$result=mysqli_query($con,$sql);
</code>```

look at the value row doesn't match with the insert fields. You insert twice $password, and no $phone.

If still error, you can add this to know what wrong with your query:

```<code>if(mysqli_query($con,$sql))
{
   echo 'Success'.'</br>';
}
else
{
   echo 'Fail';
   echo "Error Description : ".mysqli_error($con);
}
</code>```

Title: insert into php isn't working

Body:
I'm not that good with PHP but i need to do a user registration form and this is what I haven done so far

<!doctype html>

<title>Register</title>

Register | Login

Formulario de registro

<form action="" method="POST">
Usuario: <input type="text" name="login">

Contrasena: <input type="password" name="password">

Email: <input type="text" name="email">

Sexo: <input type="text" name="sex">

Edad: <input type="text" name="age">

Telefono: <input type="text" name="phone">

Pais: <input type="text" name="country">

Ciudad: <input type="text" name="city">

Direccion: <input type="text" name="address">

<input type="submit" value="Register" name="submit" />
</form>
<?php
if(isset($_POST["submit"])){

if(!empty($_POST['login']) && !empty($_POST['password'])) {
    $login=$_POST['login'];
    $password=$_POST['password'];
    $email=$_POST['email'];
    $sex=$_POST['sex'];
    $age=$_POST['age'];
    $phone=$_POST['phone'];
    $country=$_POST['country'];
    $city=$_POST['city'];
    $address=$_POST['address'];

    $con=mysqli_connect('localhost','root','','registro_usuarios') or die(mysql_error());

    $sql="SELECT * FROM usuario ";
    $result = mysqli_query($con,$sql);
    if(mysqli_num_rows($result)>=0)
    {
    echo "I'm in";
    $sql="INSERT INTO usuario (login,password,email,sex,age,phone,country,city,address)
    VALUES('$login','$password','$password','$email','$sex','$age','$country','$city','$address')";

    $result=mysqli_query($con,$sql);

    if($result){
    echo "Account Successfully Created";
    } else {
    echo "Failure!";
    }

    } else {
    echo "That username already exists! Please try again with another.";
    }

} else {
    echo "All fields are required!";
}
}
?>

I can see the message "I'm in" in my screen but I'm also get the "Failure" message because it's not inserting anything into the the database. I have been struggling trying to find the error but nothing so far. The error should be around here

$sql="INSERT INTO usuario (login,password,email,sex,age,phone,country,city,address)
    VALUES('$login','$password','$password','$email','$sex','$age','$country','$city','$address')";

    $result=mysqli_query($con,$sql);

I have checked all the values from my database in case of a typo just in case you guys wonder and there is no typo.

Thanks

Body:
You wrong in sql insert.

your sql :

$sql="INSERT INTO usuario (login,password,email,sex,age,phone,country,city,address) VALUES('$login','$password','$password','$email','$sex','$age','$country','$city','$address')";
$result=mysqli_query($con,$sql);

look at the value row doesn't match with the insert fields. You insert twice $password, and no $phone.

If still error, you can add this to know what wrong with your query:

if(mysqli_query($con,$sql))
{
   echo 'Success'.'</br>';
}
else
{
   echo 'Fail';
   echo "Error Description : ".mysqli_error($con);
}


来源: stackexchange

问:
(python) Telegram bot- how to send messages periodically?
I have a dilemma regarding my telegram bot. Let's say I have to create a function that will ask, every user connected to the bot, one time per week/month, a question:

```<code>def check_the_week(bot, update):
reply_keyboard = [['YES', 'NO']]
bot.send_message(
    chat_id=update.message.chat_id,
    text=report,

    reply_markup=ReplyKeyboardMarkup(reply_keyboard, one_time_keyboard=True))  # sends the total nr of hours
update.reply_text("Did you report all you working hour on freshdesk for this week?",
                  ReplyKeyboardMarkup(reply_keyboard, one_time_keyboard=True))

if update.message.text == "YES":
    update.message.reply_text(text="Are you sure?",
                              reply_markup=ReplyKeyboardMarkup(reply_keyboard, one_time_keyboard=True))

    # Asks confirmation
    if update.message.text == "YES":
        update.message.reply_text(text="Thank you for reporting your working hours in time!")

    elif update.message.text == "NO":
        update.message.reply_text(text="Please, check you time reports and add missing")

elif update.message.text == "NO":
    update.message.reply_text(text="Please, check you time reports and add missing")
</code>```

I want this function to be triggered every week. I was thinking about using JobQueue. The problem is that in this case the function should have two parameters- bot AND job_queue, but no update:

```<code>def callback_30(bot, job):
    bot.send_message(chat_id='@examplechannel',
    text='A single message with 30s delay')

j.run_once(callback_30, 30)
</code>```

How can I create a Job Scheduler (or any other solution) in telegram bot to be trigger my function once a week?
p.s. No "while True"+time.sleep() solutions please. The loop just stuck forever, I tried it.

答:
You need to use the context parameter when defining the job in your function. Look at this example:

```<code>   from telegram.ext import Updater, CommandHandler, MessageHandler,    Filters, InlineQueryHandler

def sayhi(bot, job):
    job.context.message.reply_text("hi")

def time(bot, update,job_queue):
    job = job_queue.run_repeating(sayhi, 5, context=update)

def main():
    updater = Updater("BOT TOKEN")
    dp = updater.dispatcher
    dp.add_handler(MessageHandler(Filters.text , time,pass_job_queue=True))

    updater.start_polling()
    updater.idle()

if __name__ == '__main__':
    main()
</code>```

Now in your call back function wherever you need update. type job.context instead.

ContentLicense: CC BY-SA 3.0

Body:
I have a dilemma regarding my telegram bot. Let's say I have to create a function that will ask, every user connected to the bot, one time per week/month, a question:

def check_the_week(bot, update):
reply_keyboard = [['YES', 'NO']]
bot.send_message(
    chat_id=update.message.chat_id,
    text=report,

    reply_markup=ReplyKeyboardMarkup(reply_keyboard, one_time_keyboard=True))  # sends the total nr of hours
update.reply_text("Did you report all you working hour on freshdesk for this week?",
                  ReplyKeyboardMarkup(reply_keyboard, one_time_keyboard=True))

if update.message.text == "YES":
    update.message.reply_text(text="Are you sure?",
                              reply_markup=ReplyKeyboardMarkup(reply_keyboard, one_time_keyboard=True))

    # Asks confirmation
    if update.message.text == "YES":
        update.message.reply_text(text="Thank you for reporting your working hours in time!")

    elif update.message.text == "NO":
        update.message.reply_text(text="Please, check you time reports and add missing")

elif update.message.text == "NO":
    update.message.reply_text(text="Please, check you time reports and add missing")

I want this function to be triggered every week. I was thinking about using JobQueue. The problem is that in this case the function should have two parameters- bot AND job_queue, but no update:

def callback_30(bot, job):
    bot.send_message(chat_id='@examplechannel',
    text='A single message with 30s delay')

j.run_once(callback_30, 30)

How can I create a Job Scheduler (or any other solution) in telegram bot to be trigger my function once a week?
p.s. No "while True"+time.sleep() solutions please. The loop just stuck forever, I tried it.

Body:
You need to use the context parameter when defining the job in your function. Look at this example:

   from telegram.ext import Updater, CommandHandler, MessageHandler,    Filters, InlineQueryHandler

def sayhi(bot, job):
    job.context.message.reply_text("hi")

def time(bot, update,job_queue):
    job = job_queue.run_repeating(sayhi, 5, context=update)

def main():
    updater = Updater("BOT TOKEN")
    dp = updater.dispatcher
    dp.add_handler(MessageHandler(Filters.text , time,pass_job_queue=True))

    updater.start_polling()
    updater.idle()

if __name__ == '__main__':
    main()

Now in your call back function wherever you need update. type job.context instead.


问:
what's the sequence of channelhandler in netty?
I have an application using netty to implement both server and client end. Server end sends the current time to client end.

```<code>public class TimeServerHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        System.out.println("in timeserverhandler");
        ChannelFuture f = ctx.writeAndFlush(new UnixTime());
        f.addListener(ChannelFutureListener.CLOSE);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }
}
</code>```

the encoder:

```<code>  public class TimeEncoder extends ChannelOutboundHandlerAdapter {
    @Override
    public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) {
        System.out.println("in timeencoder");
        UnixTime m = (UnixTime) msg;
        ByteBuf encoded = ctx.alloc().buffer(4);
        encoded.writeInt(m.value());
        ctx.write(encoded, promise); // (1)
    }

}
</code>```

public class TimeServer {
      private static final int PORT = 9000;

```<code>public static void main(String[] args) throws Exception {
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) {
                        ChannelPipeline p = ch.pipeline();
                        p.addLast(new TimeEncoder(), new TimeServerHandler());
                       //p.addLast(new TimeServerHandler(), new TimeEncoder());

                    }
                });
        ChannelFuture f = b.bind(PORT).sync();
        f.channel().closeFuture().sync();
    } finally {
        workerGroup.shutdownGracefully();
        bossGroup.shutdownGracefully();
    }

}
</code>```

}

In TimeServer, if I change the addList sequnce to the commented line, the Encoder handler will never be called and client side can not print out the current time. Why is that, and what's the excute sequence of handlers in the pipeline?

答:
Short answer: The reason for your commented line to not work is that netty does not understand the java object (UnixTime()). It only understands binary data (ByteBuf).

Explanation: Now the sequence of handler execution depends on the sequence you add them in the pipeline. For inbound data, handlers are executed from first to last. And for outbound data, handlers are executed from last to first. Now during handler execution, netty checks if your handler is capable for handling inbound/Outbound data. This is done by checking if your handler extends ChannelInboundHandlerAdapter or/and ChannelOutboundHandlerAdapter. If it extends ChannelInboundHandlerAdapter, then the same will be executed for inbound data. Or if extends ChannelOutboundHandlerAdapter, it will be executed for outbound data.

Now, in working code, your first handler is encoder(handling outbound event) and the second one is writing java object(handling inbound event). In this case, whenever channel becomes active, inbound event will be generated and same will be passed to first handler in pipeline which is your last handler. Now, that handler will consume the event and write data on the channel which is an outbound event. Now, this outbound even will propagate upstream and goes to the next handler in pipeline which handles outbound event which is your encoder. Now, encoder will convert the unixtime into binary data and same will be passed onto the channel.

Now, in non-working code, when you reverse the order of handler, once the channel becomes active, inbound event will be passed to your first outbound event handler which is the last handler in pipeline (First from beginning but last from the end ). Once, this handler generates unix time, it will generate outbound event which will further propagate upstream. But after this, there is no upstream event handler to consume outbound event and hence your unix time will never be converted into binary data and hence this does not work.

Hope it clarifies.

ContentLicense: CC BY-SA 4.0

Body:
I have an application using netty to implement both server and client end. Server end sends the current time to client end.

public class TimeServerHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        System.out.println("in timeserverhandler");
        ChannelFuture f = ctx.writeAndFlush(new UnixTime());
        f.addListener(ChannelFutureListener.CLOSE);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }
}

the encoder:

  public class TimeEncoder extends ChannelOutboundHandlerAdapter {
    @Override
    public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) {
        System.out.println("in timeencoder");
        UnixTime m = (UnixTime) msg;
        ByteBuf encoded = ctx.alloc().buffer(4);
        encoded.writeInt(m.value());
        ctx.write(encoded, promise); // (1)
    }

}

public class TimeServer {
      private static final int PORT = 9000;

public static void main(String[] args) throws Exception {
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) {
                        ChannelPipeline p = ch.pipeline();
                        p.addLast(new TimeEncoder(), new TimeServerHandler());
                       //p.addLast(new TimeServerHandler(), new TimeEncoder());

                    }
                });
        ChannelFuture f = b.bind(PORT).sync();
        f.channel().closeFuture().sync();
    } finally {
        workerGroup.shutdownGracefully();
        bossGroup.shutdownGracefully();
    }

}

}

In TimeServer, if I change the addList sequnce to the commented line, the Encoder handler will never be called and client side can not print out the current time. Why is that, and what's the excute sequence of handlers in the pipeline?


问:
How can I use std::shared_ptr with the Mysql prepared statements?
How can I use std::shared_ptr with the Mysql prepared statements? is there any requirements which I should know in this case? is there any difference between boost::shared_ptr and std::shared_ptr in this case?

答:
header

```<code>#include <boost/shared_ptr.hpp>
#include <string>
#include <vector>
#include <mysql_connection.h>
#include <cppconn/driver.h>
#include <cppconn/exception.h>
#include <cppconn/resultset.h>
#include <cppconn/statement.h>
#include <cppconn/prepared_statement.h>

sql::Driver *host_1_driver;
boost::shared_ptr <sql::Connection> host_1_conn;
boost::shared_ptr <sql::Statement> host_1_stmt;
boost::shared_ptr <sql::ResultSet> host_1_res;
boost::shared_ptr <sql::PreparedStatement> host_1_pstmt;

bool reconnect_state = true;
std::string host_1_name;
std::string host_1_user_name;
std::string host_1_password;
std::string host_1_database_name;
</code>```

connect

```<code>host_1_driver = get_driver_instance (); // protected
host_1_conn.reset(host_1_driver->connect (host_1_name, host_1_user_name, host_1_password)); // connect to mysql
host_1_conn->setClientOption("OPT_RECONNECT", &reconnect_state);
host_1_conn->setSchema(host_1_database_name);
</code>```

thread

```<code>void float_to_sql(std::string query, std::vector <float> data_to_write, std::vector <float> data_ids)
{
    host_1_driver->threadInit();    // prevents multiple open connections
    if (host_1_conn.get() == NULL)
    {
        ERROR << "host_1 connection is not open";
        throw -1;
    }
    host_1_pstmt.reset (host_1_conn->prepareStatement (query));
    for (int i = 0; i < (int) data_to_write.size(); i++)
    {
        host_1_pstmt->setDouble(1, data_to_write.at(i));
        host_1_pstmt->setInt(2, data_ids.at(i));
        host_1_pstmt->executeUpdate();
    }
    host_1_driver->threadEnd();
    return;
}
</code>```

test

```<code>std::string query = "update ErrorCodes set Val = ? where ID = ?";
std::vector <float> data {1, 1, 1};
std::vector <float> data_ids {3, 5, 9};
float_to_sql(query, data, data_ids);
</code>```

Body:
header

#include <boost/shared_ptr.hpp>
#include <string>
#include <vector>
#include <mysql_connection.h>
#include <cppconn/driver.h>
#include <cppconn/exception.h>
#include <cppconn/resultset.h>
#include <cppconn/statement.h>
#include <cppconn/prepared_statement.h>

sql::Driver *host_1_driver;
boost::shared_ptr <sql::Connection> host_1_conn;
boost::shared_ptr <sql::Statement> host_1_stmt;
boost::shared_ptr <sql::ResultSet> host_1_res;
boost::shared_ptr <sql::PreparedStatement> host_1_pstmt;

bool reconnect_state = true;
std::string host_1_name;
std::string host_1_user_name;
std::string host_1_password;
std::string host_1_database_name;

connect

host_1_driver = get_driver_instance (); // protected
host_1_conn.reset(host_1_driver->connect (host_1_name, host_1_user_name, host_1_password)); // connect to mysql
host_1_conn->setClientOption("OPT_RECONNECT", &reconnect_state);
host_1_conn->setSchema(host_1_database_name);

thread

void float_to_sql(std::string query, std::vector <float> data_to_write, std::vector <float> data_ids)
{
    host_1_driver->threadInit();    // prevents multiple open connections
    if (host_1_conn.get() == NULL)
    {
        ERROR << "host_1 connection is not open";
        throw -1;
    }
    host_1_pstmt.reset (host_1_conn->prepareStatement (query));
    for (int i = 0; i < (int) data_to_write.size(); i++)
    {
        host_1_pstmt->setDouble(1, data_to_write.at(i));
        host_1_pstmt->setInt(2, data_ids.at(i));
        host_1_pstmt->executeUpdate();
    }
    host_1_driver->threadEnd();
    return;
}

test

std::string query = "update ErrorCodes set Val = ? where ID = ?";
std::vector <float> data {1, 1, 1};
std::vector <float> data_ids {3, 5, 9};
float_to_sql(query, data, data_ids);


问:
jvisualvm not displaying thread tab
I'm unable to see threads menu tab and also profiler and sampler are disabled state and getting message "profiling is not supported by this JVM"</p>

答: You can also use 64 bit JVisualVM when you are running java application on 32 bit JVM.</p>

Title: jvisualvm not displaying thread tab


问:
Selenium: finding element by href
How would you find an element in selenium (with python) of the following html:

```<code><a href="/user/login" onclick="ttweb.UserOperations.Login.OpenLoginPopup({ LoginUrl: '/user/login', RedirectUrl: '/' }); return false;">Login</a>
</code>```

答:
As per the HTML you have shared to find the element by href you can use either of the following:

css_selector:

```<code>driver.find_element_by_css_selector("a[href=/user/login]")
</code>```

xpath:

```<code>driver.find_element_by_xpath("//a[@href='/user/login']")
</code>```

xpath (Multiple Attributes):

```<code>driver.find_element_by_xpath("//a[@href='/user/login' and text()='Login']")
</code>```

Title: Selenium: finding element by href

Body:
How would you find an element in selenium (with python) of the following html:

Login

Body:
As per the HTML you have shared to find the element by href you can use either of the following:

css_selector:

driver.find_element_by_css_selector("a[href=/user/login]")

xpath:

driver.find_element_by_xpath("//a[@href='/user/login']")

xpath (Multiple Attributes):

driver.find_element_by_xpath("//a[@href='/user/login' and text()='Login']")


问:
Algorithm for detecting peaks from recorded, noisy data. Graphs inside
So I've recorded some data from an Android GPS, and I'm trying to find the peaks of these graphs, but I haven't been able to find anything specific, perhaps because I'm not too sure what I'm looking for.  I have found some MatLab functions, but I can't find the actual algorithms that do it.  I need to do this in Java, but I should be able to translate code from other languages.

As you can see, there are lots of 'mini-peaks', but I just want the main ones.

答: I guess you have lots of points... Calculate mean value of them, subtract it from all point's values and get highest point value (negative or positive) from each range where points have same sign till they change it. I hope I am clear...</p>

ContentLicense: CC BY-SA 2.5


问:
How to display element when hover on another?
I have tried with like below which I searched from stackoverflow , but not working yet ! This is doing on riot.js so I link what I tried here .
I want to show .overlay div when hover on #over arrow down button but no display yet .

```<code>#over:hover + .overlay {
    opacity:1;
}
#over:hover > .overlay {
    opacity:1;
}
#over:hover ~ .overlay {
    opacity:1;
}
</code>```

答:
None of those selectors work because div.overlay is neither a descendant nor a sibling to div#over.

To do what you want - with pure CSS, you would need to change the HTML structure a bit - in order to make the two div's siblings.

For example, adding div.overlay next to div#over would do the trick:

```<code><h3>{Now} {opts.title}
    <div id='over'>^</div>
    <div class='overlay'>
       <li>Editable</li>
    </div>
</h3>
</code>```

This would require following CSS rule:

```<code>#over:hover + .overlay {
    opacity:1;
}
</code>```

But this would require you to adjust the absolute position of div.overlay. I am leaving that to you.

Here's the updated plnkr: http://plnkr.co/edit/nSNn1t0Lpuw9uUZQ1N8h?p=preview

Body:
I have tried with like below which I searched from stackoverflow , but not working yet ! This is doing on riot.js so I link what I tried here .
I want to show .overlay div when hover on #over arrow down button but no display yet .

#over:hover + .overlay {
    opacity:1;
}
#over:hover > .overlay {
    opacity:1;
}
#over:hover ~ .overlay {
    opacity:1;
}

Body:
None of those selectors work because div.overlay is neither a descendant nor a sibling to div#over.

To do what you want - with pure CSS, you would need to change the HTML structure a bit - in order to make the two div's siblings.

For example, adding div.overlay next to div#over would do the trick:

<h3>{Now} {opts.title}
    <div id='over'>^</div>
    <div class='overlay'>
       <li>Editable</li>
    </div>
</h3>

This would require following CSS rule:

#over:hover + .overlay {
    opacity:1;
}

But this would require you to adjust the absolute position of div.overlay. I am leaving that to you.

Here's the updated plnkr: http://plnkr.co/edit/nSNn1t0Lpuw9uUZQ1N8h?p=preview


问:
How to know when the Draft.js plugins are ready?
I am using Draft.js plugin Linkify.

I am trying to load the content from the local storage and then linkify it.

Now I have to use setTimeout to wait linkifyPlugin ready. If not, the content loaded will be pure text which is not linkified.

Is there any way like event I can use to know when plugin is ready?

```<code>class MyComponent extends Component {
  constructor(props) {
    super(props);

    this.state = {
      editorState: EditorState.createEmpty()
    };
  }

  componentDidMount() {
    // ...
    if (hasDraft) this.loadEditor(draftFromLocalStorage);
  }

  loadEditor = rawContent => {
    // here I have to use setTimeout to wait linkifyPlugin ready
    setTimeout(() => {
      const editorState = EditorState.push(this.state.editorState, convertFromRaw(rawContent));
      this.setState({ editorState });
    }, 5);
  };

  render() {
    return (
      <Editor
        editorState={editorState}
        plugins={[linkifyPlugin]}
        onChange={this.onEditorChange} />
    );
  }
}
</code>```

答:
Strange, looking at the source code there's no reason to think the plugin has async code: https://github.com/draft-js-plugins/draft-js-plugins/tree/master/draft-js-linkify-plugin.

You could try putting a breakpoint on this function: https://github.com/draft-js-plugins/draft-js-plugins/blob/master/draft-js-linkify-plugin/src/linkStrategy.js

That function is called for every block in the state, so you should be able to see whether the text is processed by Linkify or not. If you remove the timeout and the function is still being called, then the problem should be somewhere else (because it would mean that you have a problem with the rendering, and not with the actual processing).

Body:
I am using Draft.js plugin Linkify.

I am trying to load the content from the local storage and then linkify it.

Now I have to use setTimeout to wait linkifyPlugin ready. If not, the content loaded will be pure text which is not linkified.

Is there any way like event I can use to know when plugin is ready?

class MyComponent extends Component {
  constructor(props) {
    super(props);

    this.state = {
      editorState: EditorState.createEmpty()
    };
  }

  componentDidMount() {
    // ...
    if (hasDraft) this.loadEditor(draftFromLocalStorage);
  }

  loadEditor = rawContent => {
    // here I have to use setTimeout to wait linkifyPlugin ready
    setTimeout(() => {
      const editorState = EditorState.push(this.state.editorState, convertFromRaw(rawContent));
      this.setState({ editorState });
    }, 5);
  };

  render() {
    return (
      <Editor
        editorState={editorState}
        plugins={[linkifyPlugin]}
        onChange={this.onEditorChange} />
    );
  }
}


问:
Finding Max date in hive
I have a column named "Date" which is in string datatype.
01-24-2018
04-30-2017

How to find the maximum of these dates which is in string?

I used this query which is not returning the expected max.

```<code>max(to_date(from_unixtime(unix_timestamp(b.Date,'MM-dd-yyyy')))
</code>```

答:
Try

```<code>MAX( cast(to_date(from_unixtime(unix_timestamp(yourdate , 'MM-dd-yyyy'))) as date))
</code>```

EDIT: In your comments you mentioned you need to get the account details for the max date.You could use this.

```<code>SELECT a.id,
       b.contract,
       CAST (
          TO_DATE (
             from_unixtime (unix_timestamp (b.date, 'MM-dd-yyyy'))) AS DATE)
          AS MAX_DATE
  FROM acct a JOIN customer b ON (b.partyid = a.offerid)
 WHERE CAST (
          TO_DATE (
             from_unixtime (unix_timestamp (b.date, 'MM-dd-yyyy'))) AS DATE) IN

  ( SELECT
         MAX (
            CAST (
               TO_DATE (
                  from_unixtime (unix_timestamp (b.date, 'MM-dd-yyyy'))) AS DATE))
    FROM acct a JOIN customer b ON (b.partyid = a.offerid)
   WHERE b.contract = 200427747 );
</code>```

Title: Finding Max date in hive

Body:
I have a column named "Date" which is in string datatype.
01-24-2018
04-30-2017

How to find the maximum of these dates which is in string?

I used this query which is not returning the expected max.

max(to_date(from_unixtime(unix_timestamp(b.Date,'MM-dd-yyyy')))

Body:
Try

MAX( cast(to_date(from_unixtime(unix_timestamp(yourdate , 'MM-dd-yyyy'))) as date))

EDIT: In your comments you mentioned you need to get the account details for the max date.You could use this.

SELECT a.id,
       b.contract,
       CAST (
          TO_DATE (
             from_unixtime (unix_timestamp (b.date, 'MM-dd-yyyy'))) AS DATE)
          AS MAX_DATE
  FROM acct a JOIN customer b ON (b.partyid = a.offerid)
 WHERE CAST (
          TO_DATE (
             from_unixtime (unix_timestamp (b.date, 'MM-dd-yyyy'))) AS DATE) IN

  ( SELECT
         MAX (
            CAST (
               TO_DATE (
                  from_unixtime (unix_timestamp (b.date, 'MM-dd-yyyy'))) AS DATE))
    FROM acct a JOIN customer b ON (b.partyid = a.offerid)
   WHERE b.contract = 200427747 );


问:
How to Align smaller text on top of larger text
I have three text items in a container. The middle text has the larger font. I would like to align the top the first item to the top of the second item.

.container {
  border: 1px solid black;
}

.container p {
  display: inline-block;
}

.large {
  font-size: 50px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
  <div class="container">
    <p class="first">One</p>
    <p class="large">Two</p>
    <p>Three</p>
  </div>
</body></code>```

https://jsfiddle.net/7ofrravh/2/

The only way I can think of to do this is to use absolute position but this gets out of line when I change the screen size. I want to be able to change the size of the screen and have everything stay in place. Does anyone know a way to do this?

答:
That's how I would do it: https://jsfiddle.net/7ofrravh/5/ .
By making container flexible with content alignment an the start by using align-items: flex-start . Then simply fixing first paragraph position with a margin: 10px 0 0 0.

Body:
I have three text items in a container. The middle text has the larger font. I would like to align the top the first item to the top of the second item.

.container {
  border: 1px solid black;
}

.container p {
  display: inline-block;
}

.large {
  font-size: 50px;
}

One

Two

Three

https://jsfiddle.net/7ofrravh/2/

The only way I can think of to do this is to use absolute position but this gets out of line when I change the screen size. I want to be able to change the size of the screen and have everything stay in place. Does anyone know a way to do this?


问:
Unknown column '$data' in 'field list' in codeigniter
Im trying to insert data in my database and this error appears:

Error Number: 1054

Unknown column '$data' in 'field list'

INSERT INTO crud ($data) VALUES ('')

Filename: C:/AppServ/www/parcial/system/database/DB_driver.php

Line Number: 691

This is my form:

```<code> <?php echo form_open('home/save',['class'=>'form-horizontal']); ?>
  <fieldset>

      <label for="exampleInputEmail1">Titulo</label>
    <?php echo form_input(['name'=>'id','class'=>'form-control','placeholder'=>'Titulo', 'value'=>set_value('')]); ?>

      <?php echo form_input(['name'=>'titulo','class'=>'form-control','placeholder'=>'Titulo', 'value'=>set_value('titulo')]); ?>

      <label for="exampleInputEmail1">Resumen</label>
  <?php echo form_input(['name'=>'resumen','class'=>'form-control','placeholder'=>'Titulo', 'value'=>set_value('resumen')]); ?>

      <label for="exampleInputEmail1">Ano</label>
    <?php echo form_input(['name'=>'ano','class'=>'form-control','placeholder'=>'Titulo', 'value'=>set_value('ano')]); ?>

          <label for="exampleInputEmail1">Pais</label>
      <?php echo form_input(['name'=>'pais','class'=>'form-control','placeholder'=>'Titulo', 'value'=>set_value('pais')]); ?>
      <label for="exampleInputEmail1">Protagonista</label>
        <?php echo form_input(['name'=>'progatonista','class'=>'form-control','placeholder'=>'Titulo', 'value'=>set_value('protagonista')]); ?>
  <br>

  <?php echo form_close(); ?>
<?php echo form_submit(['value'=>'Submit', 'class'=>'btn btn-primary']); ?>
</code>```

This is my function to save records:

```<code>  public function save() {

    $data = $this->input->post();
$this->load->model('Crudmodel');
if($this->Crudmodel->saveRecords($data)) {

}
}
</code>```

this is my code to insert:

```<code>public function saveRecords($data) {

  return  $this->db->insert('crud','$data');

}
</code>```

What can i do? please help me

答:
remove the quotes, you need a array of key=>values that map to your table columns </p>

```<code>public function saveRecords($data) {

  return  $this->db->insert('crud',$data);

}
</code>```

Body:
Im trying to insert data in my database and this error appears:

Error Number: 1054

Unknown column '$data' in 'field list'

INSERT INTO crud ($data) VALUES ('')

Filename: C:/AppServ/www/parcial/system/database/DB_driver.php

Line Number: 691

This is my form:

 <?php echo form_open('home/save',['class'=>'form-horizontal']); ?>
  <fieldset>

      Titulo
    <?php echo form_input(['name'=>'id','class'=>'form-control','placeholder'=>'Titulo', 'value'=>set_value('')]); ?>

      <?php echo form_input(['name'=>'titulo','class'=>'form-control','placeholder'=>'Titulo', 'value'=>set_value('titulo')]); ?>

      Resumen
  <?php echo form_input(['name'=>'resumen','class'=>'form-control','placeholder'=>'Titulo', 'value'=>set_value('resumen')]); ?>

      Ano
    <?php echo form_input(['name'=>'ano','class'=>'form-control','placeholder'=>'Titulo', 'value'=>set_value('ano')]); ?>

          Pais
      <?php echo form_input(['name'=>'pais','class'=>'form-control','placeholder'=>'Titulo', 'value'=>set_value('pais')]); ?>
      Protagonista
        <?php echo form_input(['name'=>'progatonista','class'=>'form-control','placeholder'=>'Titulo', 'value'=>set_value('protagonista')]); ?>

  <?php echo form_close(); ?>
<?php echo form_submit(['value'=>'Submit', 'class'=>'btn btn-primary']); ?>

This is my function to save records:

  public function save() {

    $data = $this->input->post();
$this->load->model('Crudmodel');
if($this->Crudmodel->saveRecords($data)) {

}
}

this is my code to insert:

public function saveRecords($data) {

  return  $this->db->insert('crud','$data');

}

What can i do? please help me

Body:
remove the quotes, you need a array of key=>values that map to your table columns

public function saveRecords($data) {

  return  $this->db->insert('crud',$data);

}


问:
Filling textboxes with strings
I have a windows form application that has a slew of textboxes that I fill using a bunch of strings. My question is...the code works fine but it seems like a lot of wasteful typing. Can you fill the textboxes from the strings in a loop functions? Matching up the textbox with the approriate string?
Here is what I have. </p>

```<code>  var client = new WebClient { Credentials = new NetworkCredential(username, password) };
        var financials = client.DownloadString("https://api.intrinio.com/data_point?identifier="+conver+"&item=beta,marketcap,52_week_high,52_week_low,adj_close_price,short_interest,analyst_target_price,next_earnings_date,percent_change,yr_percent_change,implied_volatility, dividendyield,listing_exchange,sector,average_daily_volume");
        var jss = client.DownloadString("https://api.intrinio.com/companies?identifier=" + conver + "");
        JObject rss = JObject.Parse(jss);
        JObject fin = JObject.Parse(financials);
        string RRSTITLE = (string)rss["legal_name"];
        string beta = (string)fin.SelectToken("data[0].value");
        string marketcap = (string)fin.SelectToken("data[1].value");
        string weekhigh = (string)fin.SelectToken("data[2].value");
        string weeklow = (string)fin.SelectToken("data[3].value");
        string adj_close = (string)fin.SelectToken("data[4].value");
        string short_interest = (string)fin.SelectToken("data[5].value");
        string analyst_target = (string)fin.SelectToken("data[6].value");
        string earnings = (string)fin.SelectToken("data[7].value");
        string percent_change = (string)fin.SelectToken("data[8].value");
        string yr_percent_change = (string)fin.SelectToken("data[9].value");
        string implied = (string)fin.SelectToken("data[10].value");
        string divyield = (string)fin.SelectToken("data[11].value");
        string exchange = (string)fin.SelectToken("data[12].value");
        string sector = (string)fin.SelectToken("data[13].value");
        string volume = (string)fin.SelectToken("data[14].value");
        company_textbox.Text = RRSTITLE;
        beta_box.Text = beta;
        marketCap_box.Text = marketcap;
        wekhighbox.Text = weekhigh;
        weklowbox.Text = weeklow;
        adjclosebox.Text = adj_close;
        shortbox.Text = short_interest;
        targetestbox.Text = analyst_target;
        next_earnings.Text = earnings;
        Close_box.Text = percent_change;
        percentytd.Text = yr_percent_change;
        implivolbox.Text = implied;
        divyieldbox.Text = divyield;
        exchangebox.Text = exchange;
        sectorbox.Text = sector;
        daily_Volume_text.Text = volume;
</code>```

答:
Like @Jacky said, the straight forward answer is no. But a really hacky way would be to create two Dictionaries. Something like this

```<code>Dictionary<string, TextBox> TextBoxLookup = new Dictionary<string, TextBox>();
Dictionary<string, string> ValueLookup = new Dictionary<string, string>();

TextBoxLookup["beta"] = beta_box;
TextBoxLookup["marketcap"] = marketCap_box;
TextBoxLookup["weekhigh"] = wekhighbox;

ValueLookup["beta"] = beta;
ValueLookup["marketcap"] = marketcap;
ValueLookup["weekhigh"] = weekhigh;

foreach(string key in TextBoxLookup.Keys)
{
   TextBoxLookup[key].Text = ValueLookup[key];
}
</code>```

You'll have to add each textbook and its value to their respective dictionaries with the same key and iterate through the assignment foreach block everytime you need to assign.

Does this help?

Title: Filling textboxes with strings

Body:
I have a windows form application that has a slew of textboxes that I fill using a bunch of strings. My question is...the code works fine but it seems like a lot of wasteful typing. Can you fill the textboxes from the strings in a loop functions? Matching up the textbox with the approriate string?
Here is what I have.

  var client = new WebClient { Credentials = new NetworkCredential(username, password) };
        var financials = client.DownloadString("https://api.intrinio.com/data_point?identifier="+conver+"&item=beta,marketcap,52_week_high,52_week_low,adj_close_price,short_interest,analyst_target_price,next_earnings_date,percent_change,yr_percent_change,implied_volatility, dividendyield,listing_exchange,sector,average_daily_volume");
        var jss = client.DownloadString("https://api.intrinio.com/companies?identifier=" + conver + "");
        JObject rss = JObject.Parse(jss);
        JObject fin = JObject.Parse(financials);
        string RRSTITLE = (string)rss["legal_name"];
        string beta = (string)fin.SelectToken("data[0].value");
        string marketcap = (string)fin.SelectToken("data[1].value");
        string weekhigh = (string)fin.SelectToken("data[2].value");
        string weeklow = (string)fin.SelectToken("data[3].value");
        string adj_close = (string)fin.SelectToken("data[4].value");
        string short_interest = (string)fin.SelectToken("data[5].value");
        string analyst_target = (string)fin.SelectToken("data[6].value");
        string earnings = (string)fin.SelectToken("data[7].value");
        string percent_change = (string)fin.SelectToken("data[8].value");
        string yr_percent_change = (string)fin.SelectToken("data[9].value");
        string implied = (string)fin.SelectToken("data[10].value");
        string divyield = (string)fin.SelectToken("data[11].value");
        string exchange = (string)fin.SelectToken("data[12].value");
        string sector = (string)fin.SelectToken("data[13].value");
        string volume = (string)fin.SelectToken("data[14].value");
        company_textbox.Text = RRSTITLE;
        beta_box.Text = beta;
        marketCap_box.Text = marketcap;
        wekhighbox.Text = weekhigh;
        weklowbox.Text = weeklow;
        adjclosebox.Text = adj_close;
        shortbox.Text = short_interest;
        targetestbox.Text = analyst_target;
        next_earnings.Text = earnings;
        Close_box.Text = percent_change;
        percentytd.Text = yr_percent_change;
        implivolbox.Text = implied;
        divyieldbox.Text = divyield;
        exchangebox.Text = exchange;
        sectorbox.Text = sector;
        daily_Volume_text.Text = volume;

Body:
Like @Jacky said, the straight forward answer is no. But a really hacky way would be to create two Dictionaries. Something like this

Dictionary<string, TextBox> TextBoxLookup = new Dictionary<string, TextBox>();
Dictionary<string, string> ValueLookup = new Dictionary<string, string>();

TextBoxLookup["beta"] = beta_box;
TextBoxLookup["marketcap"] = marketCap_box;
TextBoxLookup["weekhigh"] = wekhighbox;

ValueLookup["beta"] = beta;
ValueLookup["marketcap"] = marketcap;
ValueLookup["weekhigh"] = weekhigh;

foreach(string key in TextBoxLookup.Keys)
{
   TextBoxLookup[key].Text = ValueLookup[key];
}

You'll have to add each textbook and its value to their respective dictionaries with the same key and iterate through the assignment foreach block everytime you need to assign.

Does this help?


问:
AD CardDAV IIS as a sub virtual folder
As per the install instructions, IT HIT WEBDAV AD CardDAV needs its own virtual server on IIS.

How can this be installed in a subfolder of the original default web site, rather than having to create a new site ?

答:
You can add CalDAV and CadDAV to the existing website using 'Add CalDAV/CardDAV Server Implementation' wizard in Visual Studio. This will create CalDAV/CardDAV repository on a specified virtual path in your project.

Note that many CalDAV/CardDAV client applications require discovery to be supported by your server. Typically your server will need to process discovery requests on your site root, even though the CalDAV/CardDAV will be on some virtual folder. The 'Add CalDAV/CardDAV Server Implementation' wizard adds a handler in your web.config on your site root to process discovery requests.

Title: AD CardDAV IIS as a sub virtual folder


问:
Vue 2 and Vue-Resource [Cannot read property 'get' of undefined(…)]
Recently upgraded to Vue-2 using Broswerify and Vueify. In the main app I had to require vue/dist/vue.js instead of 'vue' since im not using Webpack, however now when I use Vue.use(require('vue-resource')); I get $http is undefined. Vue1 this worked smoothly. What am I missing to get this working with Vue-2?

Error:

Uncaught TypeError: Cannot read property 'get' of undefined(…)

Main.js:

```<code>require('./bootstrap');
var Vue = require('vue/dist/vue.js');
Vue.use(require('vue-resource'));

// var amazon = require('amazon-affiliate-api');

/**
 * Next, we will create a fresh Vue application instance and attach it to
 * the page. Then, you may begin adding components to this application
 * or customize the JavaScript scaffolding to fit your unique needs.
 */

new Vue({
    el: '#wrapper',
    mounted: function () {
        //use mounted instead of ready.
        this.getHttp('/test', this.successFetch);
    },
    data: {
    },
    methods: {
        successFetch: function (results) {
            console.log(results);
        },
        //vue resource methods
        getHttp: function (url,callback) {
            const params = {
                headers: {
                    'X-CSRF-TOKEN': this.token
                }
            }
            this.$http.get(url, params).then(callback).catch(err => console.error(err));
        },
</code>```

Gulp.js:

```<code>const elixir = require('laravel-elixir');

require('laravel-elixir-vue-2');
require('browserify');
require('vueify');

elixir(function(mix){
    mix.sass('main.scss')
        .browserify('app.js');
});
</code>```

Package.json:

```<code>{
  "private": true,
  "scripts": {
    "prod": "gulp --production",
    "dev": "gulp watch"
  },
  "devDependencies": {
    "aliasify": "^2.1.0",
    "bootstrap-sass": "^3.3.7",
    "gulp": "^3.9.1",
    "jquery": "^3.1.0",
    "laravel-elixir": "^6.0.0-14",
    "laravel-elixir-vue-2": "^0.2.0",
    "laravel-elixir-webpack-official": "^1.0.2",
    "lodash": "^4.16.2",
    "vue": "^2.0.1",
    "vue-resource": "^1.0.3",
    "vueify": "^9.3.0"
  },
  "dependencies": {
    "babel-preset-es2015": "^6.18.0",
    "babel-preset-react": "^6.16.0",
    "browserify": "^13.1.1"
  }
}
</code>```

答:
I fixed this issue of the following mode:

```<code>npm install bootstrap-vue --save
npm install vue-resource --save
</code>```

in main.js

```<code>import { Vue, i18n } from './bootstrap'
import BootstrapVue from 'bootstrap-vue'

Vue.use(BootstrapVue)
</code>```

create bootstrap.js

```<code>import Vue from 'vue'
import VueResource from 'vue-resource'

Vue.use(VueResource)

export { Vue }
</code>```

In App.vue

```<code>this.$http.get('/api/module/all').then(...
</code>```

Body:
Recently upgraded to Vue-2 using Broswerify and Vueify. In the main app I had to require vue/dist/vue.js instead of 'vue' since im not using Webpack, however now when I use Vue.use(require('vue-resource')); I get $http is undefined. Vue1 this worked smoothly. What am I missing to get this working with Vue-2?

Error:

Uncaught TypeError: Cannot read property 'get' of undefined(…)

Main.js:

require('./bootstrap');
var Vue = require('vue/dist/vue.js');
Vue.use(require('vue-resource'));

// var amazon = require('amazon-affiliate-api');

/**
 * Next, we will create a fresh Vue application instance and attach it to
 * the page. Then, you may begin adding components to this application
 * or customize the JavaScript scaffolding to fit your unique needs.
 */

new Vue({
    el: '#wrapper',
    mounted: function () {
        //use mounted instead of ready.
        this.getHttp('/test', this.successFetch);
    },
    data: {
    },
    methods: {
        successFetch: function (results) {
            console.log(results);
        },
        //vue resource methods
        getHttp: function (url,callback) {
            const params = {
                headers: {
                    'X-CSRF-TOKEN': this.token
                }
            }
            this.$http.get(url, params).then(callback).catch(err => console.error(err));
        },

Gulp.js:

const elixir = require('laravel-elixir');

require('laravel-elixir-vue-2');
require('browserify');
require('vueify');

elixir(function(mix){
    mix.sass('main.scss')
        .browserify('app.js');
});

Package.json:

{
  "private": true,
  "scripts": {
    "prod": "gulp --production",
    "dev": "gulp watch"
  },
  "devDependencies": {
    "aliasify": "^2.1.0",
    "bootstrap-sass": "^3.3.7",
    "gulp": "^3.9.1",
    "jquery": "^3.1.0",
    "laravel-elixir": "^6.0.0-14",
    "laravel-elixir-vue-2": "^0.2.0",
    "laravel-elixir-webpack-official": "^1.0.2",
    "lodash": "^4.16.2",
    "vue": "^2.0.1",
    "vue-resource": "^1.0.3",
    "vueify": "^9.3.0"
  },
  "dependencies": {
    "babel-preset-es2015": "^6.18.0",
    "babel-preset-react": "^6.16.0",
    "browserify": "^13.1.1"
  }
}

Body:
I fixed this issue of the following mode:

npm install bootstrap-vue --save
npm install vue-resource --save

in main.js

import { Vue, i18n } from './bootstrap'
import BootstrapVue from 'bootstrap-vue'

Vue.use(BootstrapVue)

create bootstrap.js

import Vue from 'vue'
import VueResource from 'vue-resource'

Vue.use(VueResource)

export { Vue }

In App.vue

this.$http.get('/api/module/all').then(...


问:
validate a dropdownlist in asp.net mvc
```<code>//in controller
ViewBag.Categories = categoryRepository.GetAllCategories().ToList();

//in view
 @Html.DropDownList("Cat", new SelectList(ViewBag.Categories,"ID", "CategoryName"))
</code>```

How can I make it so that by default it says "-Select Category-"

And validate to check something is selected (client and on the model)

Thanks

答:
I just can't believe that there are people still using ViewData/ViewBag in ASP.NET MVC 3 instead of having strongly typed views and view models:

```<code>public class MyViewModel
{
    [Required]
    public string CategoryId { get; set; }

    public IEnumerable<Category> Categories { get; set; }
}
</code>```

and in your controller:

```<code>public class HomeController: Controller
{
    public ActionResult Index()
    {
        var model = new MyViewModel
        {
            Categories = Repository.GetCategories()
        }
        return View(model);
    }

    [HttpPost]
    public ActionResult Index(MyViewModel model)
    {
        if (!ModelState.IsValid)
        {
            // there was a validation error =>
            // rebind categories and redisplay view
            model.Categories = Repository.GetCategories();
            return View(model);
        }
        // At this stage the model is OK => do something with the selected category
        return RedirectToAction("Success");
    }
}
</code>```

and then in your strongly typed view:

```<code>@Html.DropDownListFor(
    x => x.CategoryId,
    new SelectList(Model.Categories, "ID", "CategoryName"),
    "-- Please select a category --"
)
@Html.ValidationMessageFor(x => x.CategoryId)
</code>```

Also if you want client side validation don't forget to reference the necessary scripts:

```<code><script src="@Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>
</code>```

Title: validate a dropdownlist in asp.net mvc

Body:
//in controller
ViewBag.Categories = categoryRepository.GetAllCategories().ToList();

//in view
 @Html.DropDownList("Cat", new SelectList(ViewBag.Categories,"ID", "CategoryName"))

How can I make it so that by default it says "-Select Category-"

And validate to check something is selected (client and on the model)

Thanks

Body:
I just can't believe that there are people still using ViewData/ViewBag in ASP.NET MVC 3 instead of having strongly typed views and view models:

public class MyViewModel
{
    [Required]
    public string CategoryId { get; set; }

    public IEnumerable<Category> Categories { get; set; }
}

and in your controller:

public class HomeController: Controller
{
    public ActionResult Index()
    {
        var model = new MyViewModel
        {
            Categories = Repository.GetCategories()
        }
        return View(model);
    }

    [HttpPost]
    public ActionResult Index(MyViewModel model)
    {
        if (!ModelState.IsValid)
        {
            // there was a validation error =>
            // rebind categories and redisplay view
            model.Categories = Repository.GetCategories();
            return View(model);
        }
        // At this stage the model is OK => do something with the selected category
        return RedirectToAction("Success");
    }
}

and then in your strongly typed view:

@Html.DropDownListFor(
    x => x.CategoryId,
    new SelectList(Model.Categories, "ID", "CategoryName"),
    "-- Please select a category --"
)
@Html.ValidationMessageFor(x => x.CategoryId)

Also if you want client side validation don't forget to reference the necessary scripts:

<script src="@Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>


问:
TypeScript - test method against interface, ie T['methodName']
Given interface an interface:

```<code>class A {
   method(x:number) : string
}
</code>```

Given function

```<code>const b = (x: string) : number;
</code>```

The goal - test the function versus the interface

Realisation

```<code>type InterfaceKey = {
    method: any
};

function typecheck<T, K extends keyof InterfaceKey >(imp: () => T, d: T[K]) {
 //                                   K cannot be used to index type T ^
    imp();
    return d;
}

typecheck(someclass, 555); // <-- type check _is actually works_ here

// or

function typecheck <T>(imp: () => T, d: any) {
    imp();
    if(!d) {
        let mock: T;
        mock.default = d; // default does not exists on type T
        return mock;
    }
    return d;
}
</code>```

Look like the first approach is the only way, and it even performs a type check(in Webstorm, not in tsc), but does not compile.

Related: https://github.com/Microsoft/TypeScript/issues/15768

答:
```<code>//base interface
interface MyInterface {
    method: any
}

// check with defined method
interface CheckD<T extends MyInterface> {
    all(keys: {[P in keyof T]?: T[P]}): Check<T>;

    onlyMethod<Ts extends {[K in keyof Ts]: Ts[K]} & T>(fn: Ts['method']): Check<T>;
}

// check without
interface Check<T> {
    all(keys: {[P in keyof T]?: T[P]}): Check<T>;
}

type CCD<T extends MyInterface > = CheckD<T>;
type CC<T> = Check<T>;

// magic
function uncast(a: any): any{
    return <any>a;
}

// function overloading
function load<K extends MyInterface>(a: K): CCD<K>;
function load<T>(a: T): CC<T>;

// type guards
function load<T, K extends MyInterface>(a: T|K): CCD<K> | CC<T>{
    if ((<K>a).method) return <CCD<K>>uncast(a);
    return <CC<T>> uncast(a);
}

// TEST

var C1 = {
    test: a => a + 1,
    method: a => 5
}

var C2 = {
    test: a => a + 1,
}

let a1 = load(C1);
a1.all({ test: a => 1 });
a1.onlyMethod(55); // type error

let a2 = load(C2);
a2.all({ test: (a,b) => 1 }); // type error
a2.all({ test2: a => 1 });// type error
a2.onlyMethod(55); //no such method
</code>```

So, actually, the result is quite understandable.

Body:
Given interface an interface:

class A {
   method(x:number) : string
}

Given function

const b = (x: string) : number;

The goal - test the function versus the interface

Realisation

type InterfaceKey = {
    method: any
};

function typecheck<T, K extends keyof InterfaceKey >(imp: () => T, d: T[K]) {
 //                                   K cannot be used to index type T ^
    imp();
    return d;
}

typecheck(someclass, 555); // <-- type check _is actually works_ here

// or

function typecheck <T>(imp: () => T, d: any) {
    imp();
    if(!d) {
        let mock: T;
        mock.default = d; // default does not exists on type T
        return mock;
    }
    return d;
}

Look like the first approach is the only way, and it even performs a type check(in Webstorm, not in tsc), but does not compile.

Related: https://github.com/Microsoft/TypeScript/issues/15768

Body:
//base interface
interface MyInterface {
    method: any
}

// check with defined method
interface CheckD<T extends MyInterface> {
    all(keys: {[P in keyof T]?: T[P]}): Check<T>;

    onlyMethod<Ts extends {[K in keyof Ts]: Ts[K]} & T>(fn: Ts['method']): Check<T>;
}

// check without
interface Check<T> {
    all(keys: {[P in keyof T]?: T[P]}): Check<T>;
}

type CCD<T extends MyInterface > = CheckD<T>;
type CC<T> = Check<T>;

// magic
function uncast(a: any): any{
    return <any>a;
}

// function overloading
function load<K extends MyInterface>(a: K): CCD<K>;
function load<T>(a: T): CC<T>;

// type guards
function load<T, K extends MyInterface>(a: T|K): CCD<K> | CC<T>{
    if ((<K>a).method) return <CCD<K>>uncast(a);
    return <CC<T>> uncast(a);
}

// TEST

var C1 = {
    test: a => a + 1,
    method: a => 5
}

var C2 = {
    test: a => a + 1,
}

let a1 = load(C1);
a1.all({ test: a => 1 });
a1.onlyMethod(55); // type error

let a2 = load(C2);
a2.all({ test: (a,b) => 1 }); // type error
a2.all({ test2: a => 1 });// type error
a2.onlyMethod(55); //no such method

So, actually, the result is quite understandable.


答:
You need to change your HTML structure to achieve this in CSS and use ~ general sibling selector, like:

In HTML:

```<code><div id='over'>^</div>
  <div class='overlay'>
  <div>Editable</div>
</div>
</code>```

In CSS:

```<code>#over:hover ~ .overlay {
  opacity: 1;
}
</code>```

Have a look at the updated Plunkr.

Hope this helps!

Title: How to display element when hover on another?

Body:
You need to change your HTML structure to achieve this in CSS and use ~ general sibling selector, like:

In HTML:

<div id='over'>^</div>
  <div class='overlay'>
  <div>Editable</div>
</div>

In CSS:

#over:hover ~ .overlay {
  opacity: 1;
}

Have a look at the updated Plunkr.

Hope this helps!


问:
Can I add a subcolumn to a hive struct column using alter table?
I've a very complex table structure in hive, let's say that it's like the following table:

```<code>create table dirceu ( a struct<b:string,c:string>);
</code>```

Now I do need to add another subcolumn to the a column, and it should have the structure b,c and d, I'm trying to do it with the following alter table:

```<code>alter table dirceu change column a a struct<b:string,c:string, d:string>;
</code>```

But this throw the following error:

```<code>Error: Error while processing statement: FAILED: Execution Error, return code 1 from org.apache.hadoop.hive.ql.exec.DDLTask. Unable to alter table. The following columns have types incompatible with the existing columns in their respective positions :
a (state=08S01,code=1)
</code>```

Is there a way to do this using alter table? I know that I can do it using create table and copy the data, but I would like to know if there is another way to do it.
 UPDATE
I'm using hive: 2.1.0.2.6.1.0-129
HortonWorks: HDP-2.6.1.0

答:
I guess it works by this command,

```<code>alter table dirceu add column a struct<d:string>;
</code>```

Please let me know if it doesn't work by comment.

Body:
I've a very complex table structure in hive, let's say that it's like the following table:

create table dirceu ( a struct);

Now I do need to add another subcolumn to the a column, and it should have the structure b,c and d, I'm trying to do it with the following alter table:

alter table dirceu change column a a struct;

But this throw the following error:

Error: Error while processing statement: FAILED: Execution Error, return code 1 from org.apache.hadoop.hive.ql.exec.DDLTask. Unable to alter table. The following columns have types incompatible with the existing columns in their respective positions :
a (state=08S01,code=1)

Is there a way to do this using alter table? I know that I can do it using create table and copy the data, but I would like to know if there is another way to do it.
 UPDATE
I'm using hive: 2.1.0.2.6.1.0-129
HortonWorks: HDP-2.6.1.0

Body:
I guess it works by this command,

alter table dirceu add column a struct<d:string>;

Please let me know if it doesn't work by comment.


问:
How to center two letters inside this css drawn circle?
Using this Codepen example and additional CSS, how would I center the letters "AB" within the circle?
https://codepen.io/joseph-mueller/pen/bNEeGw
This is what I want:

.referral-credit-outer-circle {
  background: #fff;
  width: 92px;
  height: 92px;
  border-radius: 90px;
  box-shadow: 0 0 0 2px #fff, 0 0 0 6px #666;
  margin: 20px;
  position: absolute;
}

.mask-referral-credit-inner-circle {
  transform: rotate(180deg);
  width: 100%;
  height: 50%;
  overflow: hidden;
  position: absolute;
  bottom: 0;
}

.referral-credit-inner-circle {
  width: 80px;
  height: 80px;
  border-radius: 80px;
  border: solid 6px #7aaeda;
  background: #95bee1;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="referral-credit-outer-circle">
  <span class="referral-credit-inner-icon" data-icon="H" style="color:"></span>
  <div class="mask-referral-credit-inner-circle" style="height: 70%">
    <div class="referral-credit-inner-circle"></div>
  </div>
</div></code>```

答:
Adjusted CodePen with flexbox and absolute positioning examples:

Dynamic Circle Progress Bar

Code Snippet demonstrating aforementioned examples:

.referral-credit-outer-circle {
  background: #fff;
  width: 92px;
  height: 92px;
  border-radius: 90px;
  box-shadow: 0 0 0 2px #fff, 0 0 0 6px #666;
  margin: 20px;
  position: absolute;
}

.mask-referral-credit-inner-circle {
  transform: rotate(180deg);
  width: 100%;
  height: 50%;
  overflow: hidden;
  position: absolute;
  bottom: 0;
}

.referral-credit-inner-circle {
  width: 80px;
  height: 80px;
  border-radius: 80px;
  border: solid 6px #7aaeda;
  background: #95bee1;
}

/* Additional */

.referral-credit-outer-circle {
  position: relative;
  /* for the sake of demonstration */
}

.referral-credit-inner-icon {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  text-align: center;
  height: 2rem;
  margin: auto;
  z-index: 1;
  font-size: 2rem;
}

.flex-eg .referral-credit-inner-icon {
  position: relative;
}

.flex-eg {
  display: flex;
  justify-content: center;
  align-items: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h3>Using <code>position: absolute;</code> on nested element</h3>

<div class="referral-credit-outer-circle">
  <span class="referral-credit-inner-icon" data-icon="H" style="color:">AB</span>
  <div class="mask-referral-credit-inner-circle" style="height: 70%">
    <div class="referral-credit-inner-circle"></div>
  </div>
</div>

<hr>

<h3>Using <code>display: flex;</code> on containing element</h3>

<div class="flex-eg referral-credit-outer-circle">
  <span class="referral-credit-inner-icon" data-icon="H" style="color:">AB</span>
  <div class="mask-referral-credit-inner-circle" style="height: 70%">
    <div class="referral-credit-inner-circle"></div>
  </div>
</div>

<hr>

<h3>More methods to align elements vertically or horizontally:</h3>
<ol>
  <li>Horizontal Alignment (Arbitrary Elements)</li>
  <li>Horizontal Alignment (Text Elements)</li>
  <li>Vertical Alignment (Arbitrary Elements)</li>
  <li>Vertical Alignment (Text Elements)</li>
</ol></code>```

More methods to align elements vertically or horizontally:

Horizontal Alignment (Arbitrary Elements)

Horizontal Alignment (Text Elements)

Vertical Alignment (Arbitrary Elements)

Vertical Alignment (Text Elements)

Body:
Adjusted CodePen with flexbox and absolute positioning examples:

Dynamic Circle Progress Bar

Code Snippet demonstrating aforementioned examples:

.referral-credit-outer-circle {
  background: #fff;
  width: 92px;
  height: 92px;
  border-radius: 90px;
  box-shadow: 0 0 0 2px #fff, 0 0 0 6px #666;
  margin: 20px;
  position: absolute;
}

.mask-referral-credit-inner-circle {
  transform: rotate(180deg);
  width: 100%;
  height: 50%;
  overflow: hidden;
  position: absolute;
  bottom: 0;
}

.referral-credit-inner-circle {
  width: 80px;
  height: 80px;
  border-radius: 80px;
  border: solid 6px #7aaeda;
  background: #95bee1;
}

/* Additional */

.referral-credit-outer-circle {
  position: relative;
  /* for the sake of demonstration */
}

.referral-credit-inner-icon {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  text-align: center;
  height: 2rem;
  margin: auto;
  z-index: 1;
  font-size: 2rem;
}

.flex-eg .referral-credit-inner-icon {
  position: relative;
}

.flex-eg {
  display: flex;
  justify-content: center;
  align-items: center;
}

<h3>Using <code>position: absolute;</code> on nested element</h3>

<div class="referral-credit-outer-circle">
  <span class="referral-credit-inner-icon" data-icon="H" style="color:">AB</span>
  <div class="mask-referral-credit-inner-circle" style="height: 70%">
    <div class="referral-credit-inner-circle"></div>
  </div>
</div>

<hr>

<h3>Using <code>display: flex;</code> on containing element</h3>

<div class="flex-eg referral-credit-outer-circle">
  <span class="referral-credit-inner-icon" data-icon="H" style="color:">AB</span>
  <div class="mask-referral-credit-inner-circle" style="height: 70%">
    <div class="referral-credit-inner-circle"></div>
  </div>
</div>

<hr>

<h3>More methods to align elements vertically or horizontally:</h3>
<ol>
  <li><a href="https://codepen.io/UncaughtTypeError/pen/vWGbdb">Horizontal Alignment (Arbitrary Elements)</a></li>
  <li><a href="https://codepen.io/UncaughtTypeError/pen/BmKMra">Horizontal Alignment (Text Elements)</a></li>
  <li><a href="https://codepen.io/UncaughtTypeError/pen/XzdGqO">Vertical Alignment (Arbitrary Elements)</a></li>
  <li><a href="https://codepen.io/UncaughtTypeError/pen/rYeRoR">Vertical Alignment (Text Elements)</a></li>
</ol>

More methods to align elements vertically or horizontally:

Horizontal Alignment (Arbitrary Elements)

Horizontal Alignment (Text Elements)

Vertical Alignment (Arbitrary Elements)

Vertical Alignment (Text Elements)


问:
Android: Get XML from SAX Element
Can I get a string of XML from a SAX Element class in Android? For example, in DOM parsing in .NET, we can get the OuterXml or InnerXml of a node. Unless I'm overlooking something, it seems that there is no way to do that either using SAX or DOM parsing in Android. Am I right about that (I hope not)?

Using SAX, we can do something like:

```<code>Element childElt = rootElt.getChild(CHILD_ELT_NAME);
if(childElt != null) {
 childElt.setEndTextElementListener(new EndTextElementListener() {
  @Override
  public void end(String body) {
   //Do something with the body string
  }
 });
}
</code>```

That will allow us to get at the "value" of the child element. Is there anything similar that will allow us to get at the XML representation of the element and its children?

Thank you.

答:
If you are attempting to do operations that are tree structure sensitive, you should use DOM.  What you appear to be trying to do would seem to fit that description, so I would suggest you use a DOM parser.

For a discussion of SAX v. Dom (Event vs. Tree) see: http://www.saxproject.org/event.html

Title: Android: Get XML from SAX Element

Body:
Can I get a string of XML from a SAX Element class in Android? For example, in DOM parsing in .NET, we can get the OuterXml or InnerXml of a node. Unless I'm overlooking something, it seems that there is no way to do that either using SAX or DOM parsing in Android. Am I right about that (I hope not)?

Using SAX, we can do something like:

Element childElt = rootElt.getChild(CHILD_ELT_NAME);
if(childElt != null) {
 childElt.setEndTextElementListener(new EndTextElementListener() {
  @Override
  public void end(String body) {
   //Do something with the body string
  }
 });
}

That will allow us to get at the "value" of the child element. Is there anything similar that will allow us to get at the XML representation of the element and its children?

Thank you.


问:
What is an Android window?
What is a Window in Android?

I thought the top-most level in Android is called Activity, which is the screen you see.

Can someone tell me what a Window in Android is? do we just have one or multiple of them.

答:
I'd like to say in brief:</p>

```<code>Application --->
  Activity --->
    Window Manager --->
      Window --->
        Surface --->
          Canvas --->
            View Root --->
              View Group --->
                View --->
                  Bitmap/Open GL panel --->
                    Current Surface Buffer --->
                      Surface Flinger --->
                        Screen
</code>```

Title: What is an Android window?

Body:
I'd like to say in brief:

Application --->
  Activity --->
    Window Manager --->
      Window --->
        Surface --->
          Canvas --->
            View Root --->
              View Group --->
                View --->
                  Bitmap/Open GL panel --->
                    Current Surface Buffer --->
                      Surface Flinger --->
                        Screen


问:
Copying a built framework into Python package with package_data
I'm trying to improve the way that PyBluez installs on macOS. Here is what the setup.py code looks like today, before my changes.

In short, on macOS an extra package called lightblue is installed, and this depends on a framework called LightAquaBlue.framework. Today, it invokes xcodebuild to build the framework and install it to /Library/Frameworks, but I want to change it to embed the framework within the Python package.

Here's what I've done:

```<code>packages.append('lightblue')
package_dir['lightblue'] = 'osx'
install_requires += ['pyobjc-core>=3.1', 'pyobjc-framework-Cocoa>=3.1']

# Add the LightAquaBlue framework to the package data as an 'eager resource'
# so that we can extract the whole framework at runtime
package_data['lightblue'] = [ 'LightAquaBlue.framework' ]
eager_resources.append('LightAquaBlue.framework')

# FIXME: This is inelegant, how can we cover the cases?
if 'install' in sys.argv or 'bdist' in sys.argv or 'bdist_egg' in sys.argv:
    # Build the framework into osx/
    import subprocess
    subprocess.check_call([
        'xcodebuild', 'install',
        '-project', 'osx/LightAquaBlue/LightAquaBlue.xcodeproj',
        '-scheme', 'LightAquaBlue',
        'DSTROOT=' + os.path.join(os.getcwd(), 'osx'),
        'INSTALL_PATH=/',
        'DEPLOYMENT_LOCATION=YES',
    ])
</code>```

This builds the LightAquaBlue.framework inside osx/ (which is the lightblue package's directory) and then passes it to setuptools as package_data. However, when I run pip install --upgrade -v ./pybluez/, the LightAquaBlue.framework is not copied:

```<code>creating build/lib/lightblue
copying osx/_bluetoothsockets.py -> build/lib/lightblue
copying osx/_LightAquaBlue.py -> build/lib/lightblue
copying osx/_obexcommon.py -> build/lib/lightblue
copying osx/_IOBluetoothUI.py -> build/lib/lightblue
copying osx/__init__.py -> build/lib/lightblue
copying osx/_IOBluetooth.py -> build/lib/lightblue
copying osx/_obex.py -> build/lib/lightblue
copying osx/_lightblue.py -> build/lib/lightblue
copying osx/obex.py -> build/lib/lightblue
copying osx/_macutil.py -> build/lib/lightblue
copying osx/_lightbluecommon.py -> build/lib/lightblue
</code>```

If I have setup.py create a dummy file inside osx/, and add it to package_data, it does get copied. This suggests to me there's no confusion over paths.

If I add os.system('ls osx/'), it also shows me that LightAquaBlue.framework is present in the same place as my dummy file.

```<code>    LightAquaBlue
--> LightAquaBlue.framework
    DUMMY_FILE_THAT_WORKS
    _IOBluetooth.py
    _IOBluetoothUI.py
    _LightAquaBlue.py
    __init__.py
    _bluetoothsockets.py
    _lightblue.py
    _lightbluecommon.py
    _macutil.py
    _obex.py
    _obexcommon.py
   obex.py
</code>```

Why isn't the framework correctly copied in?

答:
It looks like setuptools' documentation contradicts the implementation and actually you cannot specify a directory to include in package_data.

It's not very elegant, but I used:

```<code># We can't seem to list a directory as package_data, so we will
# recursively add all all files we find
package_data['lightblue'] = []
for path, _, files in os.walk('osx/LightAquaBlue.framework'):
    for f in files:
        include = os.path.join(path, f)[4:]  # trim off osx/
        package_data['lightblue'].append(include)
</code>```

Body:
I'm trying to improve the way that PyBluez installs on macOS. Here is what the setup.py code looks like today, before my changes.

In short, on macOS an extra package called lightblue is installed, and this depends on a framework called LightAquaBlue.framework. Today, it invokes xcodebuild to build the framework and install it to /Library/Frameworks, but I want to change it to embed the framework within the Python package.

Here's what I've done:

packages.append('lightblue')
package_dir['lightblue'] = 'osx'
install_requires += ['pyobjc-core>=3.1', 'pyobjc-framework-Cocoa>=3.1']

# Add the LightAquaBlue framework to the package data as an 'eager resource'
# so that we can extract the whole framework at runtime
package_data['lightblue'] = [ 'LightAquaBlue.framework' ]
eager_resources.append('LightAquaBlue.framework')

# FIXME: This is inelegant, how can we cover the cases?
if 'install' in sys.argv or 'bdist' in sys.argv or 'bdist_egg' in sys.argv:
    # Build the framework into osx/
    import subprocess
    subprocess.check_call([
        'xcodebuild', 'install',
        '-project', 'osx/LightAquaBlue/LightAquaBlue.xcodeproj',
        '-scheme', 'LightAquaBlue',
        'DSTROOT=' + os.path.join(os.getcwd(), 'osx'),
        'INSTALL_PATH=/',
        'DEPLOYMENT_LOCATION=YES',
    ])

This builds the LightAquaBlue.framework inside osx/ (which is the lightblue package's directory) and then passes it to setuptools as package_data. However, when I run pip install --upgrade -v ./pybluez/, the LightAquaBlue.framework is not copied:

creating build/lib/lightblue
copying osx/_bluetoothsockets.py -> build/lib/lightblue
copying osx/_LightAquaBlue.py -> build/lib/lightblue
copying osx/_obexcommon.py -> build/lib/lightblue
copying osx/_IOBluetoothUI.py -> build/lib/lightblue
copying osx/__init__.py -> build/lib/lightblue
copying osx/_IOBluetooth.py -> build/lib/lightblue
copying osx/_obex.py -> build/lib/lightblue
copying osx/_lightblue.py -> build/lib/lightblue
copying osx/obex.py -> build/lib/lightblue
copying osx/_macutil.py -> build/lib/lightblue
copying osx/_lightbluecommon.py -> build/lib/lightblue

If I have setup.py create a dummy file inside osx/, and add it to package_data, it does get copied. This suggests to me there's no confusion over paths.

If I add os.system('ls osx/'), it also shows me that LightAquaBlue.framework is present in the same place as my dummy file.

    LightAquaBlue
--> LightAquaBlue.framework
    DUMMY_FILE_THAT_WORKS
    _IOBluetooth.py
    _IOBluetoothUI.py
    _LightAquaBlue.py
    __init__.py
    _bluetoothsockets.py
    _lightblue.py
    _lightbluecommon.py
    _macutil.py
    _obex.py
    _obexcommon.py
   obex.py

Why isn't the framework correctly copied in?

Body:
It looks like setuptools' documentation contradicts the implementation and actually you cannot specify a directory to include in package_data.

It's not very elegant, but I used:

# We can't seem to list a directory as package_data, so we will
# recursively add all all files we find
package_data['lightblue'] = []
for path, _, files in os.walk('osx/LightAquaBlue.framework'):
    for f in files:
        include = os.path.join(path, f)[4:]  # trim off osx/
        package_data['lightblue'].append(include)


答:
Here is the edited version of your code

.container {
  border: 1px solid black;
}

.container p {
  display: inline-block;
  margin:0;
}
.container p.first {
  vertical-align:top;
  line-height:40px;
}

.large {
  font-size: 50px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
  <div class="container">
    <p class="first">One</p>
    <p class="large">Two</p>
    <p>Three</p>
  </div>
</body></code>```

Title: How to Align smaller text on top of larger text

Body:
I have three text items in a container. The middle text has the larger font. I would like to align the top the first item to the top of the second item.

.container {
  border: 1px solid black;
}

.container p {
  display: inline-block;
}

.large {
  font-size: 50px;
}

One

Two

Three

https://jsfiddle.net/7ofrravh/2/

The only way I can think of to do this is to use absolute position but this gets out of line when I change the screen size. I want to be able to change the size of the screen and have everything stay in place. Does anyone know a way to do this?

Body:
Here is the edited version of your code

.container {
  border: 1px solid black;
}

.container p {
  display: inline-block;
  margin:0;
}
.container p.first {
  vertical-align:top;
  line-height:40px;
}

.large {
  font-size: 50px;
}

<body>
  <div class="container">
    <p class="first">One</p>
    <p class="large">Two</p>
    <p>Three</p>
  </div>
</body>


问:
I am a beginner and I am trying to make a card flip game in netbeans
On clicking an image I want another image to be displayed pause for one second and the original image to be restored and displayed againdisplayed again When I try to do it it action handler such as code given below it sets the image after sleep .I want the image to be displayed pause and the original to be displayed again how can I achieve that</p>

```<code>private void jButton16ActionPerformed(java.awt.event.ActionEvent evt) {
    jButton16.setIcon(new javax.swing.ImageIcon("C:\\Users\\x\\Documents\\O.png"));
    try {           //sleep 1 seconds
        Thread.sleep(1000);
    }
    catch (InterruptedException e)
    {
    }

    jButton16.setIcon(new javax.swing.ImageIcon("C:\\Users\\x\\Documents\\118px-AMIGO.jpg"));     }
</code>```

答:
You should never invoke Thread.sleep() inside Event Dispatch Thread
because Thread.sleep() will block Event Dispatch Thread and your UI will be Freeze , instead you could use a Timer to achieve your goal

Refer below code,

```<code>    jButton16.setIcon(new javax.swing.ImageIcon("C:\\Users\\x\\Documents\\O.png"));
    Timer timer = new Timer(1000, new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            jButton16.setIcon(new javax.swing.ImageIcon("C:\\Users\\x\\Documents\\118px-AMIGO.jpg"));
        }
    });
    timer.setRepeats(false);
    timer.start();
</code>```

Body:
On clicking an image I want another image to be displayed pause for one second and the original image to be restored and displayed againdisplayed again When I try to do it it action handler such as code given below it sets the image after sleep .I want the image to be displayed pause and the original to be displayed again how can I achieve that

private void jButton16ActionPerformed(java.awt.event.ActionEvent evt) {
    jButton16.setIcon(new javax.swing.ImageIcon("C:\\Users\\x\\Documents\\O.png"));
    try {           //sleep 1 seconds
        Thread.sleep(1000);
    }
    catch (InterruptedException e)
    {
    }

    jButton16.setIcon(new javax.swing.ImageIcon("C:\\Users\\x\\Documents\\118px-AMIGO.jpg"));     }

Body:
You should never invoke Thread.sleep() inside Event Dispatch Thread
because Thread.sleep() will block Event Dispatch Thread and your UI will be Freeze , instead you could use a Timer to achieve your goal

Refer below code,

    jButton16.setIcon(new javax.swing.ImageIcon("C:\\Users\\x\\Documents\\O.png"));
    Timer timer = new Timer(1000, new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            jButton16.setIcon(new javax.swing.ImageIcon("C:\\Users\\x\\Documents\\118px-AMIGO.jpg"));
        }
    });
    timer.setRepeats(false);
    timer.start();


问:
pandas column containing list of objects, split this column based upon keynames and store values as comma separated values
I have a dataframe which contains column:

```<code>A
[{"A": 28, "B": "abc"},{"A": 29, "B": "def"},{"A": 30, "B": "hij"}]
[{"A": 31, "B": "hij"},{"A": 32, "B": "abc"}]
[{"A": 28, "B": "abc"}]
[{"A": 28, "B": "abc"},{"A": 29, "B": "def"},{"A": 30, "B": "hij"}]
[{"A": 28, "B": "abc"},{"A": 29, "B": "klm"},{"A": 30, "B": "nop"}]
[{"A": 28, "B": "abc"},{"A": 29, "B": "xyz"}]
</code>```

Output should be such that:

```<code>A              B
28,29,30       abc,def,hij
31,32          hij,abc
28             abc
28,29,30       abc,def,hij
28,29,30       abc,klm,nop
28,29          abc,xyz
</code>```

How do i split the list of objects into columns depending on key names and have them stored as comma separated values as shown above.

答:
I was assuming A was a list of list of dicts

```<code>A = [
    [{"A": 28, "B": "abc"},{"A": 29, "B": "def"},{"A": 30, "B": "hij"}],
    [{"A": 31, "B": "hij"},{"A": 32, "B": "abc"}],
    [{"A": 28, "B": "abc"}],
    [{"A": 28, "B": "abc"},{"A": 29, "B": "def"},{"A": 30, "B": "hij"}],
    [{"A": 28, "B": "abc"},{"A": 29, "B": "klm"},{"A": 30, "B": "nop"}],
    [{"A": 28, "B": "abc"},{"A": 29, "B": "xyz"}]
]
</code>```

First thing I'd do is use comprehensions to create a new dictionary.  Then ','.join within a groupby

```<code>B = {
    (i, j, k): v
    for j, row in enumerate(A)
    for i, d in enumerate(row)
    for k, v in d.items()
}

pd.Series(B).astype(str).groupby(level=[1, 2]).apply(','.join).unstack()

          A            B
0  28,29,30  abc,def,hij
1     31,32      hij,abc
2        28          abc
3  28,29,30  abc,def,hij
4  28,29,30  abc,klm,nop
5     28,29      abc,xyz
</code>```

Body:
I have a dataframe which contains column:

A
[{"A": 28, "B": "abc"},{"A": 29, "B": "def"},{"A": 30, "B": "hij"}]
[{"A": 31, "B": "hij"},{"A": 32, "B": "abc"}]
[{"A": 28, "B": "abc"}]
[{"A": 28, "B": "abc"},{"A": 29, "B": "def"},{"A": 30, "B": "hij"}]
[{"A": 28, "B": "abc"},{"A": 29, "B": "klm"},{"A": 30, "B": "nop"}]
[{"A": 28, "B": "abc"},{"A": 29, "B": "xyz"}]

Output should be such that:

A              B
28,29,30       abc,def,hij
31,32          hij,abc
28             abc
28,29,30       abc,def,hij
28,29,30       abc,klm,nop
28,29          abc,xyz

How do i split the list of objects into columns depending on key names and have them stored as comma separated values as shown above.

Body:
I was assuming A was a list of list of dicts

A = [
    [{"A": 28, "B": "abc"},{"A": 29, "B": "def"},{"A": 30, "B": "hij"}],
    [{"A": 31, "B": "hij"},{"A": 32, "B": "abc"}],
    [{"A": 28, "B": "abc"}],
    [{"A": 28, "B": "abc"},{"A": 29, "B": "def"},{"A": 30, "B": "hij"}],
    [{"A": 28, "B": "abc"},{"A": 29, "B": "klm"},{"A": 30, "B": "nop"}],
    [{"A": 28, "B": "abc"},{"A": 29, "B": "xyz"}]
]

First thing I'd do is use comprehensions to create a new dictionary.  Then ','.join within a groupby

B = {
    (i, j, k): v
    for j, row in enumerate(A)
    for i, d in enumerate(row)
    for k, v in d.items()
}

pd.Series(B).astype(str).groupby(level=[1, 2]).apply(','.join).unstack()

          A            B
0  28,29,30  abc,def,hij
1     31,32      hij,abc
2        28          abc
3  28,29,30  abc,def,hij
4  28,29,30  abc,klm,nop
5     28,29      abc,xyz


问:
How to print the return value of a function using printf()?

Update:

The original code looked a lot like this:

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

#include <string>

int main()
{
   printf(printf("Hello, WORLD!"););
}
</code>```

However, in the original post, printf("Hello, WORLD!") was assigned to a variable, x.

Intended questions:

How do I call the return value of a function within a function?  As a beginner, learning to reference a string variable using %s, I wondered how to reference a the return value of a function (for example, if the return value were a string, would I still use %s).

What does "called to print" mean?  I think a simplistic explanation is: the string is put into memory and assigned an address, and the class definition tells the compiler to look up the location in memory based on the class's input-argument definition; so, the address in memory is called to print by the compiler.

Is the first argument of printf() also the return value of printf() such that x == "Hello, World!" is true in x = printf("Hello, World!")?

Original post:

I'm looking at http://www.cplusplus.com/reference/cstdio/printf/

it says: int printf ( const char * format, ... );, but it doesn't define ....  So, I don't know what ... is referencing.  I wrongly assumed that meant ( const char * format, const char * format, const char * format, ~.  But in fact, I can't decipher the meaning based on guessing and reading.

Using this program:

```<code>#include <stdio.h>
int main(int argc, char ** argv)
{
    str x = printf("Hello, World!\n");
    printf("x has %d characters.\n", x);
    //"x has %d characters.\n" appears first, x appears second.

    return 0;
}
</code>```

We see the result:

```<code>Hello, World!
x has 14 characters.
</code>```

When I expected:

```<code>x has 14 characters.  //because this appears first.
Hello, World!         //because this appear second.
</code>```

Because x comes after x has 14 characters..

Someone please explain why ./a.out is giving me the results in backwards order (using gcc and shell in Ubuntu); furthermore, eclipse is shown to give the results in this same backward order.

Perhaps another way to rephrase the question would be: where is "Hello, World!\n" being called to print?

答:
When you call printf, it will print whatever string you pass it as an argument.
So, you are getting the prints on console in the same order you placed them in your code.

Update after the edit from OP:

I still don't quite comprehend what you meant by //because this appear second. comment there.

```<code>x has 14 characters.  //because this appears first.
Hello, World!         //because this appear second.
</code>```

My take of the problem is, What you are trying to do is get an explanation on why Hello World is printed first and then x has 14 characters. is getting printed.

I can't tell this in simplest of the words than, "Because, when the code is getting executed, processor encounters first call to printf() function with a string argument "Hello World\n". So it dumps that on console.
Then comes the second call with printf("x has %d characters.\n", x);, eventually dumping that on the console later."

Obviously, the value of x is 14 because count of chars in string Hello World! is 13+1 (i.e. 14)

Now the confusion:
If you think that you just defined x as printf("Hello World!\n"), then thats a wrong assumption.
With int x = printf("Hello, World!\n"); statement, you, in fact declared an int variable x and initialized (or assigned) it with value returned by printf("Hello World\n");, which is 14.

Body:
Update:

The original code looked a lot like this:

// printf(printf(););

#include <string>

int main()
{
   printf(printf("Hello, WORLD!"););
}

However, in the original post, printf("Hello, WORLD!") was assigned to a variable, x.

Intended questions:

How do I call the return value of a function within a function?  As a beginner, learning to reference a string variable using %s, I wondered how to reference a the return value of a function (for example, if the return value were a string, would I still use %s).

What does "called to print" mean?  I think a simplistic explanation is: the string is put into memory and assigned an address, and the class definition tells the compiler to look up the location in memory based on the class's input-argument definition; so, the address in memory is called to print by the compiler.

Is the first argument of printf() also the return value of printf() such that x == "Hello, World!" is true in x = printf("Hello, World!")?

Original post:

I'm looking at http://www.cplusplus.com/reference/cstdio/printf/

it says: int printf ( const char * format, ... );, but it doesn't define ....  So, I don't know what ... is referencing.  I wrongly assumed that meant ( const char * format, const char * format, const char * format, ~.  But in fact, I can't decipher the meaning based on guessing and reading.

Using this program:

#include <stdio.h>
int main(int argc, char ** argv)
{
    str x = printf("Hello, World!\n");
    printf("x has %d characters.\n", x);
    //"x has %d characters.\n" appears first, x appears second.

    return 0;
}

We see the result:

Hello, World!
x has 14 characters.

When I expected:

x has 14 characters.  //because this appears first.
Hello, World!         //because this appear second.

Because x comes after x has 14 characters..

Someone please explain why ./a.out is giving me the results in backwards order (using gcc and shell in Ubuntu); furthermore, eclipse is shown to give the results in this same backward order.

Perhaps another way to rephrase the question would be: where is "Hello, World!\n" being called to print?

Body:
When you call printf, it will print whatever string you pass it as an argument.
So, you are getting the prints on console in the same order you placed them in your code.

Update after the edit from OP:

I still don't quite comprehend what you meant by //because this appear second. comment there.

x has 14 characters.  //because this appears first.
Hello, World!         //because this appear second.

My take of the problem is, What you are trying to do is get an explanation on why Hello World is printed first and then x has 14 characters. is getting printed.

I can't tell this in simplest of the words than, "Because, when the code is getting executed, processor encounters first call to printf() function with a string argument "Hello World\n". So it dumps that on console.
Then comes the second call with printf("x has %d characters.\n", x);, eventually dumping that on the console later."

Obviously, the value of x is 14 because count of chars in string Hello World! is 13+1 (i.e. 14)

Now the confusion:
If you think that you just defined x as printf("Hello World!\n"), then thats a wrong assumption.
With int x = printf("Hello, World!\n"); statement, you, in fact declared an int variable x and initialized (or assigned) it with value returned by printf("Hello World\n");, which is 14.


问:
Preparedstatement compile time
I'm using jdbctemplate.queryForList(String sql, Object... args) method to fetch results from teradata. Sometimes I observed that this method takes more time than when i run the same query on teradata studio. Is it because of compilation of sql at web services side?

How a prepared statement will compile the sql statement and the arguments passed to it & how much time it takes for compilation?

Thanks in advance.

答:
According to the doc:

PreparedStatement is derived from Statement .If you want to execute a Statement object many times, it usually reduces execution time to use a PreparedStatement object instead.

The main feature of a PreparedStatement object is that, unlike a Statement object, it is given a SQL statement when it is created. The advantage to this is that in most cases, this SQL statement is sent to the DBMS right away, where it is compiled. As a result, the PreparedStatement object contains not just a SQL statement, but a SQL statement that has been precompiled. This means that when the PreparedStatement is executed, the DBMS can just run the PreparedStatement SQL statement without having to compile it first.

If you want to see PreparedStatement interface then select the PreparedStatement in eclipse and press F3

EDIT :

In reponse to @Kayaman there is no difference between running a PreparedStatement and Statement there can a lot of factors affecting the compilation time depends upon the environment or the query if it is massive query or small one. You really need to take a close look why it's taking additional couple of seconds.

Title: Preparedstatement compile time


问:
How to send data from react to Controller in ASP.NET MVC?
I am new to react. I am trying to build a CRUD application with React and .NET MVC. I am able to find the code for only getting content from controller, but not for posting.

Below is the code for getting data from controller:

```<code>var App = React.createClass({

        getInitialState: function(){
            return{data: ''};
        },

        componentWillMount: function(){
        var xhr = new XMLHttpRequest();
        xhr.open('get', this.props.url, true);
        xhr.onload = function() {
          var response = JSON.parse(xhr.responseText);

          this.setState({ data: response.result });
        }.bind(this);
        xhr.send();
    },

        render: function(){
            return(
                <h1>{this.state.data}</h1>
            );
        }
});
</code>```

Please provide me the code to send data from react to controller.

My data class:

```<code>public partial class EmployeeTable
    {
        public int EmployeeID { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Gender { get; set; }
        public string Designation { get; set; }
        public long Salary { get; set; }
        public string City { get; set; }
        public string Country { get; set; }
    }
</code>```

答:
As mentioned in the comments, sent the data using How to make a rest post call from ReactJS code?

Now create an action in your controller

```<code>[HttpPost]
public void GetInfo([FromBody]EmployeeTable data){

}
</code>```

Body:
I am new to react. I am trying to build a CRUD application with React and .NET MVC. I am able to find the code for only getting content from controller, but not for posting.

Below is the code for getting data from controller:

var App = React.createClass({

        getInitialState: function(){
            return{data: ''};
        },

        componentWillMount: function(){
        var xhr = new XMLHttpRequest();
        xhr.open('get', this.props.url, true);
        xhr.onload = function() {
          var response = JSON.parse(xhr.responseText);

          this.setState({ data: response.result });
        }.bind(this);
        xhr.send();
    },

        render: function(){
            return(

{this.state.data}

            );
        }
});

Please provide me the code to send data from react to controller.

My data class:

public partial class EmployeeTable
    {
        public int EmployeeID { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Gender { get; set; }
        public string Designation { get; set; }
        public long Salary { get; set; }
        public string City { get; set; }
        public string Country { get; set; }
    }

Body:
As mentioned in the comments, sent the data using How to make a rest post call from ReactJS code?

Now create an action in your controller

[HttpPost]
public void GetInfo([FromBody]EmployeeTable data){

}