问:
Real-time sensor data as Server-Sent Events (SSE) from Python through PHP?
I'm in the process of updating a web app presenting real-time sensor data, which in it's current first iteration does this by continuous AJAX polling.
However, in order to make this more like a 'true real-time' app, I would like it to be event-based.

I've been reading up on event-based techniques, and based on the fact that the real-time communication only has to go one way (server - > client), I have chosen to go with Server-Sent Events (SSE) for now instead of something like websockets.
As described here on the Mozilla Docs, this is easily implemented on the server side with something like (a little simplified):

```<code><?php
// SSEscript.php
date_default_timezone_set("America/New_York");
header("Content-Type: text/event-stream\n\n");

while (1) {
   if ($new_data_available) {
      echo "data:". $data;
   }

   sleep($short_time_to_spare_cpu);
}
?>
</code>```

and on the client side with:

```<code><script>
var evtSource = new EventSource("SSEscript.php");

evtSource.onmessage = function(e) {
   var data = e.data;
   // Do something with data object
}
</script>
</code>```

All the above works fine for me.
However, the sensor data is initially retrieved by a Python script running continuously on the server, so how do I transfer the sensor data from the Python script to the PHP script IMMEDIATELY when it is retrieved, so that an event can be generated and sent?

Can I do something like depicted below? :

At the same time all new data is stored in a MySQL db, so I could of course make the PHP script query the db really often for new entries, but there has to be a smarter way. So can I make 2.1 and 2.2 in the image happen at the same time?

All the answers I could find in here describes how data can be transferred by making the PHP execute the Python script, but that is not what I want as this has to run whether or not a user asks for data.

Is a kind of socket the way to go, and if so, can you point me in the direction of how to do so?
I hope you can help me out!

答:
I use redis to do the signalling between python and redis. After python do all the stuffs, rpush a token (or the latest data) into a redis queue. In the PHP I use a while(true) loop to hold the request and redis lpop(queue,timeout) to wait for the token, and send data out, something like this:</p>

```<code><?php
    require __DIR__.'/predis-1.0/autoload.php';
    header("Content-Type: text/event-stream");
    header("Cache-Control: no-cache");
    header("Connection: keep-alive");

    $lastId = isset($_SERVER["HTTP_LAST_EVENT_ID"]) ?
              $_SERVER["HTTP_LAST_EVENT_ID"] : null;
    if (isset($lastId) && !empty($lastId) && is_numeric($lastId)) {
        $lastId = intval($lastId);
        $lastId++;
    }

    $index = isset($_GET['index']) ? $_GET['index'] : null;

    echo "retry: 2000\n";

    $client = new Predis\Client();
    while (true) {
        $data = $client->blpop('queue',5);
        if ($data) {
            error_log("$index : " . strlen($data));
            sendMessage($lastId, $data);
            $lastId++;
        }
    }

    function sendMessage($id, $data) {
        echo "id: $id\n";
        echo "data: $data\n\n";
        ob_flush();
        flush();
    }
</code>```

Body:
I'm in the process of updating a web app presenting real-time sensor data, which in it's current first iteration does this by continuous AJAX polling.
However, in order to make this more like a 'true real-time' app, I would like it to be event-based.

I've been reading up on event-based techniques, and based on the fact that the real-time communication only has to go one way (server - > client), I have chosen to go with Server-Sent Events (SSE) for now instead of something like websockets.
As described here on the Mozilla Docs, this is easily implemented on the server side with something like (a little simplified):

<?php
// SSEscript.php
date_default_timezone_set("America/New_York");
header("Content-Type: text/event-stream\n\n");

while (1) {
   if ($new_data_available) {
      echo "data:". $data;
   }

   sleep($short_time_to_spare_cpu);
}
?>

and on the client side with:

All the above works fine for me.
However, the sensor data is initially retrieved by a Python script running continuously on the server, so how do I transfer the sensor data from the Python script to the PHP script IMMEDIATELY when it is retrieved, so that an event can be generated and sent?

Can I do something like depicted below? :

At the same time all new data is stored in a MySQL db, so I could of course make the PHP script query the db really often for new entries, but there has to be a smarter way. So can I make 2.1 and 2.2 in the image happen at the same time?

All the answers I could find in here describes how data can be transferred by making the PHP execute the Python script, but that is not what I want as this has to run whether or not a user asks for data.

Is a kind of socket the way to go, and if so, can you point me in the direction of how to do so?
I hope you can help me out!

Body:
I use redis to do the signalling between python and redis. After python do all the stuffs, rpush a token (or the latest data) into a redis queue. In the PHP I use a while(true) loop to hold the request and redis lpop(queue,timeout) to wait for the token, and send data out, something like this:

<?php
    require __DIR__.'/predis-1.0/autoload.php';
    header("Content-Type: text/event-stream");
    header("Cache-Control: no-cache");
    header("Connection: keep-alive");

    $lastId = isset($_SERVER["HTTP_LAST_EVENT_ID"]) ?
              $_SERVER["HTTP_LAST_EVENT_ID"] : null;
    if (isset($lastId) && !empty($lastId) && is_numeric($lastId)) {
        $lastId = intval($lastId);
        $lastId++;
    }

    $index = isset($_GET['index']) ? $_GET['index'] : null;

    echo "retry: 2000\n";

    $client = new Predis\Client();
    while (true) {
        $data = $client->blpop('queue',5);
        if ($data) {
            error_log("$index : " . strlen($data));
            sendMessage($lastId, $data);
            $lastId++;
        }
    }

    function sendMessage($id, $data) {
        echo "id: $id\n";
        echo "data: $data\n\n";
        ob_flush();
        flush();
    }


来源: stackexchange

问:
removing duplicates from a bool list
I am trying to get a word in a list that is followed by a word with a ''.'' in it. for example, if this is a list

```<code>test_list = ["hello", "how", "are.", "you"]
</code>```

it would select the word ''you'' I have managed to pull this off but I am trying to ensure that I do not get duplicate words.
Here is what I have so far

```<code>list = []
i = 0
bool = False
words = sent.split()
for word in words:
    if bool:
        list.append(word)
        bool = False
   # the bellow if statment seems to make everything worse instead of fixing the duplicate problem
    if "." in word and word not in list:
        bool = True
return list
</code>```

答:
This isn't based off of the code you posted, however it should do exactly what you're asking.

```<code>def get_word_after_dot(words):
    for index, word in enumerate(words):
        if word.endswith('.') and len(words) - index > 1:
            yield words[index + 1]
</code>```

Iterating over this generator will yield words that are followed by a period.

ContentLicense: CC BY-SA 3.0

Title: removing duplicates from a bool list

Body:
I am trying to get a word in a list that is followed by a word with a ''.'' in it. for example, if this is a list

test_list = ["hello", "how", "are.", "you"]

it would select the word ''you'' I have managed to pull this off but I am trying to ensure that I do not get duplicate words.
Here is what I have so far

list = []
i = 0
bool = False
words = sent.split()
for word in words:
    if bool:
        list.append(word)
        bool = False
   # the bellow if statment seems to make everything worse instead of fixing the duplicate problem
    if "." in word and word not in list:
        bool = True
return list

Body:
This isn't based off of the code you posted, however it should do exactly what you're asking.

def get_word_after_dot(words):
    for index, word in enumerate(words):
        if word.endswith('.') and len(words) - index > 1:
            yield words[index + 1]

Iterating over this generator will yield words that are followed by a period.

ContentLicense: CC BY-SA 4.0


问:
Hive execute "insert into ... values ..." very slow
I build a hadoop & hive cluster and try to do some test. But it's really slow.

table

table value_count

```<code>+--------------------------------------------------------------+--+
|                        createtab_stmt                        |
+--------------------------------------------------------------+--+
| CREATE TABLE `value_count`(                                  |
|   `key` int,                                                 |
|   `count` int,                                               |
|   `create_date` date COMMENT '????')                         |
| COMMENT 'This is a group table'                              |
| ROW FORMAT SERDE                                             |
|   'org.apache.hadoop.hive.ql.io.orc.OrcSerde'                |
| STORED AS INPUTFORMAT                                        |
|   'org.apache.hadoop.hive.ql.io.orc.OrcInputFormat'          |
| OUTPUTFORMAT                                                 |
|   'org.apache.hadoop.hive.ql.io.orc.OrcOutputFormat'         |
| LOCATION                                                     |
|   'hdfs://avatarcluster/hive/warehouse/test.db/value_count'  |
| TBLPROPERTIES (                                              |
|   'COLUMN_STATS_ACCURATE'='{\"BASIC_STATS\":\"true\"}',      |
|   'numFiles'='7',                                            |
|   'numRows'='7',                                             |
|   'rawDataSize'='448',                                       |
|   'totalSize'='2297',                                        |
|   'transient_lastDdlTime'='1496217645')                      |
+--------------------------------------------------------------+--+
</code>```

sql execution

```<code>insert into value_count values (5, 1, '2017-05-06');
</code>```

I've execute this sql for several times, each takes about 4 or 5 mins

hadoop container log

```<code>2017-05-31 16:00:45,041 [INFO] [Dispatcher thread {Central}] |app.DAGAppMaster|: Central Dispatcher queue size after DAG completion, before cleanup: 0
2017-05-31 16:00:45,041 [INFO] [Dispatcher thread {Central}] |app.DAGAppMaster|: Waiting for next DAG to be submitted.
2017-05-31 16:00:45,042 [INFO] [Dispatcher thread {Central}] |app.DAGAppMaster|: Cleaning up DAG: name=insert into value_count valu...'2017-05-06')(Stage-1), with id=dag_1490688643958_53401_1
2017-05-31 16:00:45,042 [INFO] [Dispatcher thread {Central}] |container.AMContainerMap|: Cleaned up completed containers on dagComplete. Removed=0, Remaining=1
2017-05-31 16:00:45,044 [INFO] [Dispatcher thread {Central}] |app.DAGAppMaster|: Completed cleanup for DAG: name=insert into value_count valu...'2017-05-06')(Stage-1), with id=dag_1490688643958_53401_1
2017-05-31 16:00:50,749 [INFO] [DelayedContainerManager] |rm.YarnTaskSchedulerService|: No taskRequests. Container's idle timeout delay expired or is new. Releasing container, containerId=container_1490688643958_53401_01_000002, containerExpiryTime=1496217650577, idleTimeout=5000, taskRequestsCount=0, heldContainers=1, delayedContainers=0, isNew=false
2017-05-31 16:00:50,752 [INFO] [Dispatcher thread {Central}] |history.HistoryEventHandler|: [HISTORY][DAG:dag_1490688643958_53401_1][Event:CONTAINER_STOPPED]: containerId=container_1490688643958_53401_01_000002, stoppedTime=1496217650751, exitStatus=0
2017-05-31 16:00:50,753 [INFO] [ContainerLauncher #1] |launcher.TezContainerLauncherImpl|: Stopping container_1490688643958_53401_01_000002
2017-05-31 16:00:50,753 [INFO] [ContainerLauncher #1] |impl.ContainerManagementProtocolProxy|: Opening proxy : app08.hp.sp.tst.bmsre.com:51640
2017-05-31 16:00:51,628 [INFO] [Dispatcher thread {Central}] |container.AMContainerImpl|: Container container_1490688643958_53401_01_000002 exited with diagnostics set to Container failed, exitCode=-105. Container killed by the ApplicationMaster.
Container killed on request. Exit code is 143
Container exited with a non-zero exit code 143

2017-05-31 16:01:29,678 [INFO] [AMRM Callback Handler Thread] |rm.YarnTaskSchedulerService|: Allocated: <memory:0, vCores:0> Free: <memory:6144, vCores:1> pendingRequests: 0 delayedContainers: 0 heartbeats: 51 lastPreemptionHeartbeat: 50
2017-05-31 16:02:19,740 [INFO] [AMRM Callback Handler Thread] |rm.YarnTaskSchedulerService|: Allocated: <memory:0, vCores:0> Free: <memory:6144, vCores:1> pendingRequests: 0 delayedContainers: 0 heartbeats: 101 lastPreemptionHeartbeat: 100
2017-05-31 16:03:09,801 [INFO] [AMRM Callback Handler Thread] |rm.YarnTaskSchedulerService|: Allocated: <memory:0, vCores:0> Free: <memory:6144, vCores:1> pendingRequests: 0 delayedContainers: 0 heartbeats: 151 lastPreemptionHeartbeat: 150
2017-05-31 16:03:59,858 [INFO] [AMRM Callback Handler Thread] |rm.YarnTaskSchedulerService|: Allocated: <memory:0, vCores:0> Free: <memory:6144, vCores:1> pendingRequests: 0 delayedContainers: 0 heartbeats: 201 lastPreemptionHeartbeat: 200
2017-05-31 16:04:49,915 [INFO] [AMRM Callback Handler Thread] |rm.YarnTaskSchedulerService|: Allocated: <memory:0, vCores:0> Free: <memory:6144, vCores:1> pendingRequests: 0 delayedContainers: 0 heartbeats: 251 lastPreemptionHeartbeat: 250
2017-05-31 16:05:39,971 [INFO] [AMRM Callback Handler Thread] |rm.YarnTaskSchedulerService|: Allocated: <memory:0, vCores:0> Free: <memory:6144, vCores:1> pendingRequests: 0 delayedContainers: 0 heartbeats: 301 lastPreemptionHeartbeat: 300
2017-05-31 16:06:09,581 [INFO] [DAGSubmissionTimer] |rm.TaskSchedulerManager|: TaskScheduler notified that it should unregister from RM
2017-05-31 16:06:09,581 [INFO] [DAGSubmissionTimer] |app.DAGAppMaster|: No current running DAG, shutting down the AM
2017-05-31 16:06:09,581 [INFO] [DAGSubmissionTimer] |app.DAGAppMaster|: DAGAppMasterShutdownHandler invoked
2017-05-31 16:06:09,581 [INFO] [DAGSubmissionTimer] |app.DAGAppMaster|: Handling DAGAppMaster shutdown
2017-05-31 16:06:09,582 [INFO] [AMShutdownThread] |app.DAGAppMaster|: Sleeping for 5 seconds before shutting down
2017-05-31 16:06:14,582 [INFO] [AMShutdownThread] |app.DAGAppMaster|: Calling stop for all the services
2017-05-31 16:06:14,582 [INFO] [AMShutdownThread] |rm.YarnTaskSchedulerService|: Initiating stop of YarnTaskScheduler
2017-05-31 16:06:14,582 [INFO] [AMShutdownThread] |rm.YarnTaskSchedulerService|: Releasing held containers
2017-05-31 16:06:14,583 [INFO] [AMShutdownThread] |rm.YarnTaskSchedulerService|: Removing all pending taskRequests
2017-05-31 16:06:14,583 [INFO] [AMShutdownThread] |history.HistoryEventHandler|: Stopping HistoryEventHandler
2017-05-31 16:06:14,583 [INFO] [AMShutdownThread] |recovery.RecoveryService|: Stopping RecoveryService
2017-05-31 16:06:14,583 [INFO] [AMShutdownThread] |recovery.RecoveryService|: Handle the remaining events in queue, queue size=0
2017-05-31 16:06:14,584 [INFO] [RecoveryEventHandlingThread] |recovery.RecoveryService|: EventQueue take interrupted. Returning
2017-05-31 16:06:14,584 [INFO] [AMShutdownThread] |recovery.RecoveryService|: Closing Summary Stream
2017-05-31 16:06:14,611 [INFO] [AMShutdownThread] |impl.SimpleHistoryLoggingService|: Stopping SimpleHistoryLoggingService, eventQueueBacklog=0
2017-05-31 16:06:14,611 [INFO] [HistoryEventHandlingThread] |impl.SimpleHistoryLoggingService|: EventQueue take interrupted. Returning
2017-05-31 16:06:14,613 [INFO] [DelayedContainerManager] |rm.YarnTaskSchedulerService|: AllocatedContainerManager Thread interrupted
2017-05-31 16:06:14,615 [INFO] [AMShutdownThread] |rm.YarnTaskSchedulerService|: Unregistering application from RM, exitStatus=SUCCEEDED, exitMessage=Session stats:submittedDAGs=0, successfulDAGs=1, failedDAGs=0, killedDAGs=0
, trackingURL=
2017-05-31 16:06:14,620 [INFO] [AMShutdownThread] |impl.AMRMClientImpl|: Waiting for application to be successfully unregistered.
2017-05-31 16:06:14,720 [INFO] [AMShutdownThread] |rm.YarnTaskSchedulerService|: Successfully unregistered application from RM
2017-05-31 16:06:14,721 [INFO] [AMShutdownThread] |rm.TaskSchedulerManager|: Shutting down AppCallbackExecutor
2017-05-31 16:06:14,721 [INFO] [AMRM Callback Handler Thread] |impl.AMRMClientAsyncImpl|: Interrupted while waiting for queue
java.lang.InterruptedException
    at java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.reportInterruptAfterWait(AbstractQueuedSynchronizer.java:2014)
    at java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.await(AbstractQueuedSynchronizer.java:2048)
    at java.util.concurrent.LinkedBlockingQueue.take(LinkedBlockingQueue.java:442)
    at org.apache.hadoop.yarn.client.api.async.impl.AMRMClientAsyncImpl$CallbackHandlerThread.run(AMRMClientAsyncImpl.java:274)
2017-05-31 16:06:14,726 [INFO] [AMShutdownThread] |mortbay.log|: Stopped HttpServer2$SelectChannelConnectorWithSafeStartup@0.0.0.0:0
2017-05-31 16:06:14,826 [INFO] [AMShutdownThread] |ipc.Server|: Stopping server on 49703
2017-05-31 16:06:14,827 [INFO] [IPC Server listener on 49703] |ipc.Server|: Stopping IPC Server listener on 49703
2017-05-31 16:06:14,827 [INFO] [AMShutdownThread] |ipc.Server|: Stopping server on 43709
2017-05-31 16:06:14,827 [INFO] [IPC Server Responder] |ipc.Server|: Stopping IPC Server Responder
2017-05-31 16:06:14,827 [INFO] [IPC Server listener on 43709] |ipc.Server|: Stopping IPC Server listener on 43709
2017-05-31 16:06:14,827 [INFO] [IPC Server Responder] |ipc.Server|: Stopping IPC Server Responder
2017-05-31 16:06:14,830 [INFO] [Thread-2] |app.DAGAppMaster|: DAGAppMasterShutdownHook invoked
2017-05-31 16:06:14,830 [INFO] [Thread-2] |app.DAGAppMaster|: The shutdown handler is still running, waiting for it to complete
2017-05-31 16:06:14,844 [INFO] [AMShutdownThread] |app.DAGAppMaster|: Completed deletion of tez scratch data dir, path=hdfs://avatarcluster/tmp/hive/hadoop/_tez_session_dir/46c45420-9bdf-40a5-83a5-c8d1d496abb8/.tez/application_1490688643958_53401
2017-05-31 16:06:14,844 [INFO] [AMShutdownThread] |app.DAGAppMaster|: Exiting DAGAppMaster..GoodBye!
2017-05-31 16:06:14,844 [INFO] [Thread-2] |app.DAGAppMaster|: The shutdown handler has completed
</code>```

hadoop cluster schema

```<code>app05: NameNode/ResourceManager/JournalNode
app10: NameNode(Standby)/JournalNode
app08: DataNode/NodeManager/JournalNode
app09: DataNode/NodeManager
</code>```

while app05/08/09/10 is my beta machine, each has 32 vcore and 48GB ram.

hadoop configuration

core-site.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="configuration.xsl"?>
<configuration>
    <property>
        <name>fs.defaultFS</name>
        <value>hdfs://avatarcluster</value>
    </property>
    <property>
        <name>io.file.buffer.size</name>
        <value>131072</value>
    </property>
    <property>
        <name>hadoop.proxyuser.hadoop.hosts</name>
        <value>*</value>
    </property>
    <property>
        <name>hadoop.proxyuser.hadoop.groups</name>
        <value>*</value>
    </property>
    <property>
        <name>hadoop.tmp.dir</name>
        <value>/home/hadoop/hadoop-data/</value>
    </property>
    <property>
        <name>ha.zookeeper.quorum</name>
        <value>app02.hp.sp.tst.bmsre.com:2181</value>
    </property>
<property>
    <name>io.compression.codecs</name>
    <value>org.apache.hadoop.io.compress.SnappyCodec</value>
</property>
</configuration>
</code>```

hdfs-site.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="configuration.xsl"?>
<configuration>
    <property>
        <name>dfs.nameservices</name>
        <value>avatarcluster</value>
    </property>
    <property>
        <name>dfs.ha.namenodes.avatarcluster</name>
        <value>nn1,nn2</value>
    </property>
    <property>
        <name>dfs.namenode.rpc-address.avatarcluster.nn1</name>
        <value>app05.hp.sp.tst.bmsre.com:8020</value>
    </property>
    <property>
        <name>dfs.namenode.rpc-address.avatarcluster.nn2</name>
        <value>app10.hp.sp.tst.bmsre.com:8020</value>
    </property>
    <property>
        <name>dfs.namenode.http-address.avatarcluster.nn1</name>
        <value>app05.hp.sp.tst.bmsre.com:50070</value>
    </property>
    <property>
        <name>dfs.namenode.http-address.avatarcluster.nn2</name>
        <value>app10.hp.sp.tst.bmsre.com:50070</value>
    </property>
    <property>
        <name>dfs.namenode.shared.edits.dir</name>
        <value>qjournal://app05.hp.sp.tst.bmsre.com:8485;app10.hp.sp.tst.bmsre.com:8485;app08.hp.sp.tst.bmsre.com:8485/avatarcluster
        </value>
    </property>
    <property>
        <name>dfs.client.failover.proxy.provider.avatarcluster</name>
        <value>org.apache.hadoop.hdfs.server.namenode.ha.ConfiguredFailoverProxyProvider</value>
    </property>
    <property>
        <name>dfs.ha.fencing.methods</name>
        <value>sshfence</value>
    </property>
    <property>
        <name>dfs.ha.fencing.ssh.private-key-files</name>
        <value>/home/hadoop/.ssh/id_rsa</value>
    </property>
    <property>
        <name>dfs.journalnode.edits.dir</name>
        <value>/home/hadoop/hadoop/journal-data</value>
    </property>
    <property>
        <name>dfs.ha.automatic-failover.enabled</name>
        <value>true</value>
    </property>
    <property>
        <name>dfs.namenode.name.dir</name>
        <value>/home/hadoop/hadoop/namenode</value>
    </property>
    <property>
        <name>dfs.blocksize</name>
        <value>134217728</value>
    </property>
    <property>
        <name>dfs.namenode.handler.count</name>
        <value>100</value>
    </property>
    <property>
        <name>dfs.replication</name>
        <value>2</value>
    </property>
</configuration>
</code>```

maprd-site.xml

```<code><?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="configuration.xsl"?>
<configuration>
    <property>
        <name>mapreduce.framework.name</name>
        <value>yarn</value>
    </property>
    <property>
        <name>mapreduce.jobhistory.address</name>
        <value>app05.hp.sp.tst.bmsre.com:10020</value>
    </property>
    <property>
        <name>mapreduce.jobhistory.webapp.address</name>
        <value>app05.hp.sp.tst.bmsre.com:19888</value>
    </property>
    <property>
        <name>mapreduce.jobhistory.intermediate-done-dir</name>
        <value>/mr-history/tmp</value>
    </property>
    <property>
        <name>mapreduce.jobhistory.done-dir</name>
        <value>/mr-history/done</value>
    </property>
    <property>
        <name>mapred.output.compress</name>
        <value>true</value>
    </property>
    <property>
        <name>mapred.output.compression.codec</name>
        <value>org.apache.hadoop.io.compress.SnappyCodec</value>
    </property>
    <property>
        <name>mapred.compress.map.output</name>
        <value>true</value>
    </property>
    <property>
        <name>mapreduce.map.memory.mb</name>
        <value>3048</value>
    </property>
    <property>
        <name>mapreduce.reduce.memory.mb</name>
        <value>3048</value>
    </property>
    <property>
        <name>mapreduce.map.java.opts</name>
        <value>-Xmx2024m</value>
    </property>
    <property>
        <name>mapreduce.reduce.java.opts</name>
        <value>-Xmx2024m</value>
    </property>
</configuration>
</code>```

tez-site.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="configuration.xsl"?>

<configuration>
    <property>
        <name>tez.lib.uris</name>
        <value>${fs.defaultFS}/apps/tez-0.8.5.tar.gz</value>
    </property>
    <property>
        <name>tez.am.resource.memory.mb</name>
        <value>2048</value>
    </property>
    <property>
        <name>tez.task.resource.memory.mb</name>
        <value>2048</value>
    </property>
</configuration>
</code>```

yarn-site.xml

```<code><?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="configuration.xsl"?>
<configuration>
    <property>
        <name>yarn.admin.acl</name>
        <value>*</value>
    </property>
    <property>
        <name>yarn.resourcemanager.address</name>
        <value>app05.hp.sp.tst.bmsre.com:8032</value>
    </property>
    <property>
        <name>yarn.resourcemanager.scheduler.address</name>
        <value>app05.hp.sp.tst.bmsre.com:8030</value>
    </property>
    <property>
        <name>yarn.resourcemanager.resource-tracker.address</name>
        <value>app05.hp.sp.tst.bmsre.com:8031</value>
    </property>
    <property>
        <name>yarn.resourcemanager.admin.address</name>
        <value>app05.hp.sp.tst.bmsre.com:8033</value>
    </property>
    <property>
        <name>yarn.resourcemanager.webapp.address</name>
        <value>app05.hp.sp.tst.bmsre.com:8088</value>
    </property>
    <property>
        <name>yarn.nodemanager.local-dirs</name>
        <value>/home/hadoop/hadoop/nodemanager-workdir</value>
    </property>
    <property>
        <name>yarn.nodemanager.log-dirs</name>
        <value>/home/hadoop/hadoop/nodemanager-logs</value>
    </property>
    <property>
        <name>yarn.nodemanager.log.retain-seconds</name>
        <value>3600</value>
    </property>
    <property>
        <name>yarn.nodemanager.remote-app-log-dir</name>
        <value>/home/hadoop/hadoop/nodemanager-remote-app-logs</value>
    </property>
    <property>
        <name>yarn.nodemanager.remote-app-log-dir-suffix</name>
        <value>logs</value>
    </property>
  <property>
    <name>yarn.nodemanager.aux-services</name>
    <value>mapreduce_shuffle</value>
  </property>
  <property>
    <name>yarn.nodemanager.aux-services.mapreduce_shuffle.class</name>
    <value>org.apache.hadoop.mapred.ShuffleHandler</value>
  </property>
    <property>
        <name>yarn.nodemanager.resource.memory-mb</name>
        <value>4096</value>
    </property>
    <property>
        <name>yarn.scheduler.minimum-allocation-mb</name>
        <value>1024</value>
    </property>
</configuration>
</code>```

答:
I am not sure about your cluster configuration (nodes, memory, cpus), it would be useful if you can update the post with that information. In the meantime, the first guess is that your Tez configuration is wrong, so I would suggest decrease the MB to something smaller (few mbs should be enough for tiny data). Also, try to run the same command using the mapred engine in order to limit the problem</p>

```<code>hive.execution.engine=mr
</code>```

Body:
I build a hadoop & hive cluster and try to do some test. But it's really slow.

table

table value_count

+--------------------------------------------------------------+--+
|                        createtab_stmt                        |
+--------------------------------------------------------------+--+
| CREATE TABLE `value_count`(                                  |
|   `key` int,                                                 |
|   `count` int,                                               |
|   `create_date` date COMMENT '????')                         |
| COMMENT 'This is a group table'                              |
| ROW FORMAT SERDE                                             |
|   'org.apache.hadoop.hive.ql.io.orc.OrcSerde'                |
| STORED AS INPUTFORMAT                                        |
|   'org.apache.hadoop.hive.ql.io.orc.OrcInputFormat'          |
| OUTPUTFORMAT                                                 |
|   'org.apache.hadoop.hive.ql.io.orc.OrcOutputFormat'         |
| LOCATION                                                     |
|   'hdfs://avatarcluster/hive/warehouse/test.db/value_count'  |
| TBLPROPERTIES (                                              |
|   'COLUMN_STATS_ACCURATE'='{\"BASIC_STATS\":\"true\"}',      |
|   'numFiles'='7',                                            |
|   'numRows'='7',                                             |
|   'rawDataSize'='448',                                       |
|   'totalSize'='2297',                                        |
|   'transient_lastDdlTime'='1496217645')                      |
+--------------------------------------------------------------+--+

sql execution

insert into value_count values (5, 1, '2017-05-06');

I've execute this sql for several times, each takes about 4 or 5 mins

hadoop container log

2017-05-31 16:00:45,041 [INFO] [Dispatcher thread {Central}] |app.DAGAppMaster|: Central Dispatcher queue size after DAG completion, before cleanup: 0
2017-05-31 16:00:45,041 [INFO] [Dispatcher thread {Central}] |app.DAGAppMaster|: Waiting for next DAG to be submitted.
2017-05-31 16:00:45,042 [INFO] [Dispatcher thread {Central}] |app.DAGAppMaster|: Cleaning up DAG: name=insert into value_count valu...'2017-05-06')(Stage-1), with id=dag_1490688643958_53401_1
2017-05-31 16:00:45,042 [INFO] [Dispatcher thread {Central}] |container.AMContainerMap|: Cleaned up completed containers on dagComplete. Removed=0, Remaining=1
2017-05-31 16:00:45,044 [INFO] [Dispatcher thread {Central}] |app.DAGAppMaster|: Completed cleanup for DAG: name=insert into value_count valu...'2017-05-06')(Stage-1), with id=dag_1490688643958_53401_1
2017-05-31 16:00:50,749 [INFO] [DelayedContainerManager] |rm.YarnTaskSchedulerService|: No taskRequests. Container's idle timeout delay expired or is new. Releasing container, containerId=container_1490688643958_53401_01_000002, containerExpiryTime=1496217650577, idleTimeout=5000, taskRequestsCount=0, heldContainers=1, delayedContainers=0, isNew=false
2017-05-31 16:00:50,752 [INFO] [Dispatcher thread {Central}] |history.HistoryEventHandler|: [HISTORY][DAG:dag_1490688643958_53401_1][Event:CONTAINER_STOPPED]: containerId=container_1490688643958_53401_01_000002, stoppedTime=1496217650751, exitStatus=0
2017-05-31 16:00:50,753 [INFO] [ContainerLauncher #1] |launcher.TezContainerLauncherImpl|: Stopping container_1490688643958_53401_01_000002
2017-05-31 16:00:50,753 [INFO] [ContainerLauncher #1] |impl.ContainerManagementProtocolProxy|: Opening proxy : app08.hp.sp.tst.bmsre.com:51640
2017-05-31 16:00:51,628 [INFO] [Dispatcher thread {Central}] |container.AMContainerImpl|: Container container_1490688643958_53401_01_000002 exited with diagnostics set to Container failed, exitCode=-105. Container killed by the ApplicationMaster.
Container killed on request. Exit code is 143
Container exited with a non-zero exit code 143

2017-05-31 16:01:29,678 [INFO] [AMRM Callback Handler Thread] |rm.YarnTaskSchedulerService|: Allocated: <memory:0, vCores:0> Free: <memory:6144, vCores:1> pendingRequests: 0 delayedContainers: 0 heartbeats: 51 lastPreemptionHeartbeat: 50
2017-05-31 16:02:19,740 [INFO] [AMRM Callback Handler Thread] |rm.YarnTaskSchedulerService|: Allocated: <memory:0, vCores:0> Free: <memory:6144, vCores:1> pendingRequests: 0 delayedContainers: 0 heartbeats: 101 lastPreemptionHeartbeat: 100
2017-05-31 16:03:09,801 [INFO] [AMRM Callback Handler Thread] |rm.YarnTaskSchedulerService|: Allocated: <memory:0, vCores:0> Free: <memory:6144, vCores:1> pendingRequests: 0 delayedContainers: 0 heartbeats: 151 lastPreemptionHeartbeat: 150
2017-05-31 16:03:59,858 [INFO] [AMRM Callback Handler Thread] |rm.YarnTaskSchedulerService|: Allocated: <memory:0, vCores:0> Free: <memory:6144, vCores:1> pendingRequests: 0 delayedContainers: 0 heartbeats: 201 lastPreemptionHeartbeat: 200
2017-05-31 16:04:49,915 [INFO] [AMRM Callback Handler Thread] |rm.YarnTaskSchedulerService|: Allocated: <memory:0, vCores:0> Free: <memory:6144, vCores:1> pendingRequests: 0 delayedContainers: 0 heartbeats: 251 lastPreemptionHeartbeat: 250
2017-05-31 16:05:39,971 [INFO] [AMRM Callback Handler Thread] |rm.YarnTaskSchedulerService|: Allocated: <memory:0, vCores:0> Free: <memory:6144, vCores:1> pendingRequests: 0 delayedContainers: 0 heartbeats: 301 lastPreemptionHeartbeat: 300
2017-05-31 16:06:09,581 [INFO] [DAGSubmissionTimer] |rm.TaskSchedulerManager|: TaskScheduler notified that it should unregister from RM
2017-05-31 16:06:09,581 [INFO] [DAGSubmissionTimer] |app.DAGAppMaster|: No current running DAG, shutting down the AM
2017-05-31 16:06:09,581 [INFO] [DAGSubmissionTimer] |app.DAGAppMaster|: DAGAppMasterShutdownHandler invoked
2017-05-31 16:06:09,581 [INFO] [DAGSubmissionTimer] |app.DAGAppMaster|: Handling DAGAppMaster shutdown
2017-05-31 16:06:09,582 [INFO] [AMShutdownThread] |app.DAGAppMaster|: Sleeping for 5 seconds before shutting down
2017-05-31 16:06:14,582 [INFO] [AMShutdownThread] |app.DAGAppMaster|: Calling stop for all the services
2017-05-31 16:06:14,582 [INFO] [AMShutdownThread] |rm.YarnTaskSchedulerService|: Initiating stop of YarnTaskScheduler
2017-05-31 16:06:14,582 [INFO] [AMShutdownThread] |rm.YarnTaskSchedulerService|: Releasing held containers
2017-05-31 16:06:14,583 [INFO] [AMShutdownThread] |rm.YarnTaskSchedulerService|: Removing all pending taskRequests
2017-05-31 16:06:14,583 [INFO] [AMShutdownThread] |history.HistoryEventHandler|: Stopping HistoryEventHandler
2017-05-31 16:06:14,583 [INFO] [AMShutdownThread] |recovery.RecoveryService|: Stopping RecoveryService
2017-05-31 16:06:14,583 [INFO] [AMShutdownThread] |recovery.RecoveryService|: Handle the remaining events in queue, queue size=0
2017-05-31 16:06:14,584 [INFO] [RecoveryEventHandlingThread] |recovery.RecoveryService|: EventQueue take interrupted. Returning
2017-05-31 16:06:14,584 [INFO] [AMShutdownThread] |recovery.RecoveryService|: Closing Summary Stream
2017-05-31 16:06:14,611 [INFO] [AMShutdownThread] |impl.SimpleHistoryLoggingService|: Stopping SimpleHistoryLoggingService, eventQueueBacklog=0
2017-05-31 16:06:14,611 [INFO] [HistoryEventHandlingThread] |impl.SimpleHistoryLoggingService|: EventQueue take interrupted. Returning
2017-05-31 16:06:14,613 [INFO] [DelayedContainerManager] |rm.YarnTaskSchedulerService|: AllocatedContainerManager Thread interrupted
2017-05-31 16:06:14,615 [INFO] [AMShutdownThread] |rm.YarnTaskSchedulerService|: Unregistering application from RM, exitStatus=SUCCEEDED, exitMessage=Session stats:submittedDAGs=0, successfulDAGs=1, failedDAGs=0, killedDAGs=0
, trackingURL=
2017-05-31 16:06:14,620 [INFO] [AMShutdownThread] |impl.AMRMClientImpl|: Waiting for application to be successfully unregistered.
2017-05-31 16:06:14,720 [INFO] [AMShutdownThread] |rm.YarnTaskSchedulerService|: Successfully unregistered application from RM
2017-05-31 16:06:14,721 [INFO] [AMShutdownThread] |rm.TaskSchedulerManager|: Shutting down AppCallbackExecutor
2017-05-31 16:06:14,721 [INFO] [AMRM Callback Handler Thread] |impl.AMRMClientAsyncImpl|: Interrupted while waiting for queue
java.lang.InterruptedException
    at java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.reportInterruptAfterWait(AbstractQueuedSynchronizer.java:2014)
    at java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.await(AbstractQueuedSynchronizer.java:2048)
    at java.util.concurrent.LinkedBlockingQueue.take(LinkedBlockingQueue.java:442)
    at org.apache.hadoop.yarn.client.api.async.impl.AMRMClientAsyncImpl$CallbackHandlerThread.run(AMRMClientAsyncImpl.java:274)
2017-05-31 16:06:14,726 [INFO] [AMShutdownThread] |mortbay.log|: Stopped HttpServer2$SelectChannelConnectorWithSafeStartup@0.0.0.0:0
2017-05-31 16:06:14,826 [INFO] [AMShutdownThread] |ipc.Server|: Stopping server on 49703
2017-05-31 16:06:14,827 [INFO] [IPC Server listener on 49703] |ipc.Server|: Stopping IPC Server listener on 49703
2017-05-31 16:06:14,827 [INFO] [AMShutdownThread] |ipc.Server|: Stopping server on 43709
2017-05-31 16:06:14,827 [INFO] [IPC Server Responder] |ipc.Server|: Stopping IPC Server Responder
2017-05-31 16:06:14,827 [INFO] [IPC Server listener on 43709] |ipc.Server|: Stopping IPC Server listener on 43709
2017-05-31 16:06:14,827 [INFO] [IPC Server Responder] |ipc.Server|: Stopping IPC Server Responder
2017-05-31 16:06:14,830 [INFO] [Thread-2] |app.DAGAppMaster|: DAGAppMasterShutdownHook invoked
2017-05-31 16:06:14,830 [INFO] [Thread-2] |app.DAGAppMaster|: The shutdown handler is still running, waiting for it to complete
2017-05-31 16:06:14,844 [INFO] [AMShutdownThread] |app.DAGAppMaster|: Completed deletion of tez scratch data dir, path=hdfs://avatarcluster/tmp/hive/hadoop/_tez_session_dir/46c45420-9bdf-40a5-83a5-c8d1d496abb8/.tez/application_1490688643958_53401
2017-05-31 16:06:14,844 [INFO] [AMShutdownThread] |app.DAGAppMaster|: Exiting DAGAppMaster..GoodBye!
2017-05-31 16:06:14,844 [INFO] [Thread-2] |app.DAGAppMaster|: The shutdown handler has completed

hadoop cluster schema

app05: NameNode/ResourceManager/JournalNode
app10: NameNode(Standby)/JournalNode
app08: DataNode/NodeManager/JournalNode
app09: DataNode/NodeManager

while app05/08/09/10 is my beta machine, each has 32 vcore and 48GB ram.

hadoop configuration

core-site.xml

<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="configuration.xsl"?>
<configuration>
    <property>
        <name>fs.defaultFS</name>
        <value>hdfs://avatarcluster</value>
    </property>
    <property>
        <name>io.file.buffer.size</name>
        <value>131072</value>
    </property>
    <property>
        <name>hadoop.proxyuser.hadoop.hosts</name>
        <value>*</value>
    </property>
    <property>
        <name>hadoop.proxyuser.hadoop.groups</name>
        <value>*</value>
    </property>
    <property>
        <name>hadoop.tmp.dir</name>
        <value>/home/hadoop/hadoop-data/</value>
    </property>
    <property>
        <name>ha.zookeeper.quorum</name>
        <value>app02.hp.sp.tst.bmsre.com:2181</value>
    </property>
<property>
    <name>io.compression.codecs</name>
    <value>org.apache.hadoop.io.compress.SnappyCodec</value>
</property>
</configuration>

hdfs-site.xml

<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="configuration.xsl"?>
<configuration>
    <property>
        <name>dfs.nameservices</name>
        <value>avatarcluster</value>
    </property>
    <property>
        <name>dfs.ha.namenodes.avatarcluster</name>
        <value>nn1,nn2</value>
    </property>
    <property>
        <name>dfs.namenode.rpc-address.avatarcluster.nn1</name>
        <value>app05.hp.sp.tst.bmsre.com:8020</value>
    </property>
    <property>
        <name>dfs.namenode.rpc-address.avatarcluster.nn2</name>
        <value>app10.hp.sp.tst.bmsre.com:8020</value>
    </property>
    <property>
        <name>dfs.namenode.http-address.avatarcluster.nn1</name>
        <value>app05.hp.sp.tst.bmsre.com:50070</value>
    </property>
    <property>
        <name>dfs.namenode.http-address.avatarcluster.nn2</name>
        <value>app10.hp.sp.tst.bmsre.com:50070</value>
    </property>
    <property>
        <name>dfs.namenode.shared.edits.dir</name>
        <value>qjournal://app05.hp.sp.tst.bmsre.com:8485;app10.hp.sp.tst.bmsre.com:8485;app08.hp.sp.tst.bmsre.com:8485/avatarcluster
        </value>
    </property>
    <property>
        <name>dfs.client.failover.proxy.provider.avatarcluster</name>
        <value>org.apache.hadoop.hdfs.server.namenode.ha.ConfiguredFailoverProxyProvider</value>
    </property>
    <property>
        <name>dfs.ha.fencing.methods</name>
        <value>sshfence</value>
    </property>
    <property>
        <name>dfs.ha.fencing.ssh.private-key-files</name>
        <value>/home/hadoop/.ssh/id_rsa</value>
    </property>
    <property>
        <name>dfs.journalnode.edits.dir</name>
        <value>/home/hadoop/hadoop/journal-data</value>
    </property>
    <property>
        <name>dfs.ha.automatic-failover.enabled</name>
        <value>true</value>
    </property>
    <property>
        <name>dfs.namenode.name.dir</name>
        <value>/home/hadoop/hadoop/namenode</value>
    </property>
    <property>
        <name>dfs.blocksize</name>
        <value>134217728</value>
    </property>
    <property>
        <name>dfs.namenode.handler.count</name>
        <value>100</value>
    </property>
    <property>
        <name>dfs.replication</name>
        <value>2</value>
    </property>
</configuration>

maprd-site.xml

<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="configuration.xsl"?>
<configuration>
    <property>
        <name>mapreduce.framework.name</name>
        <value>yarn</value>
    </property>
    <property>
        <name>mapreduce.jobhistory.address</name>
        <value>app05.hp.sp.tst.bmsre.com:10020</value>
    </property>
    <property>
        <name>mapreduce.jobhistory.webapp.address</name>
        <value>app05.hp.sp.tst.bmsre.com:19888</value>
    </property>
    <property>
        <name>mapreduce.jobhistory.intermediate-done-dir</name>
        <value>/mr-history/tmp</value>
    </property>
    <property>
        <name>mapreduce.jobhistory.done-dir</name>
        <value>/mr-history/done</value>
    </property>
    <property>
        <name>mapred.output.compress</name>
        <value>true</value>
    </property>
    <property>
        <name>mapred.output.compression.codec</name>
        <value>org.apache.hadoop.io.compress.SnappyCodec</value>
    </property>
    <property>
        <name>mapred.compress.map.output</name>
        <value>true</value>
    </property>
    <property>
        <name>mapreduce.map.memory.mb</name>
        <value>3048</value>
    </property>
    <property>
        <name>mapreduce.reduce.memory.mb</name>
        <value>3048</value>
    </property>
    <property>
        <name>mapreduce.map.java.opts</name>
        <value>-Xmx2024m</value>
    </property>
    <property>
        <name>mapreduce.reduce.java.opts</name>
        <value>-Xmx2024m</value>
    </property>
</configuration>

tez-site.xml

<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="configuration.xsl"?>

<configuration>
    <property>
        <name>tez.lib.uris</name>
        <value>${fs.defaultFS}/apps/tez-0.8.5.tar.gz</value>
    </property>
    <property>
        <name>tez.am.resource.memory.mb</name>
        <value>2048</value>
    </property>
    <property>
        <name>tez.task.resource.memory.mb</name>
        <value>2048</value>
    </property>
</configuration>

yarn-site.xml

<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="configuration.xsl"?>
<configuration>
    <property>
        <name>yarn.admin.acl</name>
        <value>*</value>
    </property>
    <property>
        <name>yarn.resourcemanager.address</name>
        <value>app05.hp.sp.tst.bmsre.com:8032</value>
    </property>
    <property>
        <name>yarn.resourcemanager.scheduler.address</name>
        <value>app05.hp.sp.tst.bmsre.com:8030</value>
    </property>
    <property>
        <name>yarn.resourcemanager.resource-tracker.address</name>
        <value>app05.hp.sp.tst.bmsre.com:8031</value>
    </property>
    <property>
        <name>yarn.resourcemanager.admin.address</name>
        <value>app05.hp.sp.tst.bmsre.com:8033</value>
    </property>
    <property>
        <name>yarn.resourcemanager.webapp.address</name>
        <value>app05.hp.sp.tst.bmsre.com:8088</value>
    </property>
    <property>
        <name>yarn.nodemanager.local-dirs</name>
        <value>/home/hadoop/hadoop/nodemanager-workdir</value>
    </property>
    <property>
        <name>yarn.nodemanager.log-dirs</name>
        <value>/home/hadoop/hadoop/nodemanager-logs</value>
    </property>
    <property>
        <name>yarn.nodemanager.log.retain-seconds</name>
        <value>3600</value>
    </property>
    <property>
        <name>yarn.nodemanager.remote-app-log-dir</name>
        <value>/home/hadoop/hadoop/nodemanager-remote-app-logs</value>
    </property>
    <property>
        <name>yarn.nodemanager.remote-app-log-dir-suffix</name>
        <value>logs</value>
    </property>
  <property>
    <name>yarn.nodemanager.aux-services</name>
    <value>mapreduce_shuffle</value>
  </property>
  <property>
    <name>yarn.nodemanager.aux-services.mapreduce_shuffle.class</name>
    <value>org.apache.hadoop.mapred.ShuffleHandler</value>
  </property>
    <property>
        <name>yarn.nodemanager.resource.memory-mb</name>
        <value>4096</value>
    </property>
    <property>
        <name>yarn.scheduler.minimum-allocation-mb</name>
        <value>1024</value>
    </property>
</configuration>

Body:
I am not sure about your cluster configuration (nodes, memory, cpus), it would be useful if you can update the post with that information. In the meantime, the first guess is that your Tez configuration is wrong, so I would suggest decrease the MB to something smaller (few mbs should be enough for tiny data). Also, try to run the same command using the mapred engine in order to limit the problem

hive.execution.engine=mr


问:
jquery to switch and display videos
I have this pseudo code to display different content based on user selection, which works fine. Now, I want to take this a step further, say when a user click video1, how can i display a video1 on the video-player , video 2 on then video-player etc?
- thanks</p>

```<code>    <html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<style type="text/css">
#leftmenu-b {width:330px; float:left; bordeR:1px solid #ccc;}
#video-player-b {width:700px; float:left; margin-left:20px;}

.videoSelect1 { border:1px solid red;background-color:#ccc;}
.videoSelect2 {border:3px solid green;background-color:#fff;}
.videoSelect3 {border:6px solid yellow;background-color:yellow;}

#video-player { border:1px solid red; height:200px ;width:600px; padding:10px;}

ul li {display:block; width:300px; padding:20px;}
</style>
<script language="javascript" src="jquery.js"> </script>

<script language="javascript">
$(document).ready(function() {

$('#video1').click(function() {

    $('#video-player').attr("class", "videoSelect1"); //video1
    $('#video-player').text("video1");
    $('#video1').addClass('videoSelect1');
    $('#video2').removeClass('videoSelect2');
    $('#video3').removeClass('videoSelect3');
  //$('#video-player').addClass("videoSelect1");
//  $('#video-player2').addClass("videoNotSelected");
 //  $('#video-player3').addClass("videoNotSelected");

});
$('#video2').click(function() {
    $('#video-player').attr("class", "videoSelect2"); //video2
        $('#video2').addClass('videoSelect2');
        $('#video-player').text("video2");
    $('#video1').removeClass('videoSelect1');
//  $('#video2').reomveClass('videoSelect2');
    $('#video3').removeClass('videoSelect3');
//  $('#video-player').addClass("videoSelect2");
//  $('#video-player1').removeClass("videoNotSelected");
 //  $('#video-player3').addClass("videoNotSelected");
  // $('#video-player1').removeClass("videoSelect1");

});
$('#video3').click(function() {
    $('#video-player').attr("class", "videoSelect3"); //video3
        $('#video3').addClass('videoSelect3');
        $('#video-player').text("video3");
    $('#video1').removeClass('videoSelect1');
    $('#video2').removeClass('videoSelect2');
    //$('#video3').reomveClass('videoSelect3');
//  $('#video-player2').addClass("videoNotSelected");
//  $('#video-player1').addClass("videoNotSelected");
//  $('#video-player3').removeClass("videoNotSelected");
  // $('#video-player').addClass("videoSelect3");
  // $('#video-player1').removeClass("videoSelect1");
  //  $('#video-player2').removeClass("videoSelect2");

});
});
</script>
</head>

<body>

<div id="video-wrapper">

    <div id="leftmenu-b">
    <ul>
      <li><a href="#" id="video1" class="videoSelect1">video1</a></li>
      <li><a href="#" id="video2">video2</a></li>
      <li><a href="#" id="video3">video3</a></li>
      </ul>
    </div>
    <div id="video-player-b">
    <div id="video-player" class="videoSelect1">
      VIDEO 1
    </div>
    </div>

    </div>

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

答:
Just to make the code smaller (assuming you are to keep your button names constant), this should work:

```<code>$('leftmenu-b ul li a').click(function()
{
  $('leftmenu-b ul li a').each(function()
  {
    $(this).removeClass('videoSelect' + $(this).attr('id').substring(5, 6));
  });

  number = $(this).attr('id').substring(5, 6);

  $(this).addClass('videoSelect' + number);
  $('#video-player').attr('class', 'videoSelect' + number);
  $('#video-player').text($(this).attr('id'));
});
</code>```

I would seriously rework your classes. You probably don't need a specific class for each element, as that defeats the purpose of classes.

As for the video playback, your element does have the video string, right? Why not just pass a URL to it via the link's text, or a hidden element within the
 (a crude hack).

Good luck!

ContentLicense: CC BY-SA 2.5

Title: jquery to switch and display videos

Body:
I have this pseudo code to display different content based on user selection, which works fine. Now, I want to take this a step further, say when a user click video1, how can i display a video1 on the video-player , video 2 on then video-player etc?
- thanks

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>

video1

video2

video3

      VIDEO 1

Body:
Just to make the code smaller (assuming you are to keep your button names constant), this should work:

$('leftmenu-b ul li a').click(function()
{
  $('leftmenu-b ul li a').each(function()
  {
    $(this).removeClass('videoSelect' + $(this).attr('id').substring(5, 6));
  });

  number = $(this).attr('id').substring(5, 6);

  $(this).addClass('videoSelect' + number);
  $('#video-player').attr('class', 'videoSelect' + number);
  $('#video-player').text($(this).attr('id'));
});

I would seriously rework your classes. You probably don't need a specific class for each element, as that defeats the purpose of classes.

As for the video playback, your element does have the video string, right? Why not just pass a URL to it via the link's text, or a hidden element within the <li> (a crude hack).

Good luck!


问:
Connection strings LocalDB in ASP.NET WebForms Visual Studio
I use ASP.NET sample application using by Microsoft: WingtipToys.

It uses LocalDB.

Which is the difference about connection strings?

```<code><add name="DefaultConnection"
     connectionString="Data Source=(LocalDB)\V11.0;Initial Catalog=aspnet-WingtipToys;Integrated Security=True"
     providerName="System.Data.SqlClient" />
</code>```

```<code><add name="DefaultConnection"
     connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\aspnet-WingtipToys-20131223105750.mdf;Initial Catalog=aspnet-WingtipToys-20131223105750;Integrated Security=True"
     providerName="System.Data.SqlClient" />
</code>```

I get error connection using Data Source=(LocalDB)\V11.0;Initial Catalog=aspnet-WingtipToys;Integrated Security=True

sqlocaldb.exe command:

```<code>C:\Users\Espinete>sqllocaldb.exe v
Microsoft SQL Server 2012 (11.0.3156.0)
Microsoft SQL Server 2014 (12.0.2000.8)
Microsoft SQL Server 2016 Release Candidate 0 (RC0) (13.0.1100.286)

C:\Users\Espinete>sqllocaldb.exe i
MSSQLLocalDB
Projects
ProjectsV13
v11.0
</code>```

答:
First, LocalDB connection strings usually has database file naming convention using unique number suffix with this format:

```<code>aspnet-[project name]-yyyyMMddHHmmss.mdf
</code>```

The unique number suffix represents database creation date & time stamp at nearly same time as project creation time.

By default, when creating a LocalDB database file which not defined in any SQL Server instance, the connection string in web.config uses AttachDBFileName setting. The difference between AttachDBFileName & Initial Catalog setting as described in Common Connection String Settings is there:

AttachDbFileName

This setting specifies the path and name of the database file for SQL
  Server Express or LocalDB databases that are not defined in the local
  SQL Server Express instance. This setting is typically used for database files that you keep in the App_Data folder.

Initial Catalog

This setting specifies the name of the database in the SQL Server
  instance catalog. In LocalDB connection strings, the Visual Studio web project templates add a unique number as a suffix to both the file name and the Initial Catalog setting. The reason for this is to avoid database name collisions in the SQL Server Express LocalDB instance.

From descriptions above, the first connection string certainly doesn't work because LocalDB doesn't know which database file should be attached into its instance. To use Initial Catalog without AttachDBFileName setting you need to attach created LocalDB database in an SQL Server instance (either using SSMS or sqlcmd command line utility to create DB catalog).

Difference summary between first and second connection string:

Initial Catalog without AttachDBFileName => trying to connect using already attached database name defined in SQL Server instance catalog.

Initial Catalog with AttachDBFileName => trying to attach manually & connect using database MDF file inside App_Data directory with Initial Catalog set to attached database file name in LocalDB instance.

NB: sqllocaldb.exe v command lists all installed LocalDB versions in your machine, where sqllocaldb.exe i lists all shared existing LocalDB instances (more info in SqlLocalDB.exe docs).

Additional reference:

SqlConnection.ConnectionString Property (MSDN)

Body:
I use ASP.NET sample application using by Microsoft: WingtipToys.

It uses LocalDB.

Which is the difference about connection strings?

<add name="DefaultConnection"
     connectionString="Data Source=(LocalDB)\V11.0;Initial Catalog=aspnet-WingtipToys;Integrated Security=True"
     providerName="System.Data.SqlClient" />

<add name="DefaultConnection"
     connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\aspnet-WingtipToys-20131223105750.mdf;Initial Catalog=aspnet-WingtipToys-20131223105750;Integrated Security=True"
     providerName="System.Data.SqlClient" />

I get error connection using Data Source=(LocalDB)\V11.0;Initial Catalog=aspnet-WingtipToys;Integrated Security=True

sqlocaldb.exe command:

C:\Users\Espinete>sqllocaldb.exe v
Microsoft SQL Server 2012 (11.0.3156.0)
Microsoft SQL Server 2014 (12.0.2000.8)
Microsoft SQL Server 2016 Release Candidate 0 (RC0) (13.0.1100.286)

C:\Users\Espinete>sqllocaldb.exe i
MSSQLLocalDB
Projects
ProjectsV13
v11.0

Body:
First, LocalDB connection strings usually has database file naming convention using unique number suffix with this format:

aspnet-[project name]-yyyyMMddHHmmss.mdf

The unique number suffix represents database creation date & time stamp at nearly same time as project creation time.

By default, when creating a LocalDB database file which not defined in any SQL Server instance, the connection string in web.config uses AttachDBFileName setting. The difference between AttachDBFileName & Initial Catalog setting as described in Common Connection String Settings is there:

AttachDbFileName

This setting specifies the path and name of the database file for SQL
  Server Express or LocalDB databases that are not defined in the local
  SQL Server Express instance. This setting is typically used for database files that you keep in the App_Data folder.

Initial Catalog

This setting specifies the name of the database in the SQL Server
  instance catalog. In LocalDB connection strings, the Visual Studio web project templates add a unique number as a suffix to both the file name and the Initial Catalog setting. The reason for this is to avoid database name collisions in the SQL Server Express LocalDB instance.

From descriptions above, the first connection string certainly doesn't work because LocalDB doesn't know which database file should be attached into its instance. To use Initial Catalog without AttachDBFileName setting you need to attach created LocalDB database in an SQL Server instance (either using SSMS or sqlcmd command line utility to create DB catalog).

Difference summary between first and second connection string:

Initial Catalog without AttachDBFileName => trying to connect using already attached database name defined in SQL Server instance catalog.

Initial Catalog with AttachDBFileName => trying to attach manually & connect using database MDF file inside App_Data directory with Initial Catalog set to attached database file name in LocalDB instance.

NB: sqllocaldb.exe v command lists all installed LocalDB versions in your machine, where sqllocaldb.exe i lists all shared existing LocalDB instances (more info in SqlLocalDB.exe docs).

Additional reference:

SqlConnection.ConnectionString Property (MSDN)


问:
Array from text file return lots of empty space using php
Currently I'm trying to extract data from a text file that generated from a .asp website that will be load into interface.txt file. Format of the data are below (All the name in the text has been masked):

format of data in text file split by comma

```<code>801B,SAMPING,VAC,25999,2,R**NA** B**T* A** R*H**  ,FEMALE,2017-05-29, ,14:58:01.8000000
820A,SAMPING,VAC,11191,5,M**A*M** H*I**L B** K*M**R*LBA**R*N  ,MALE,2017-05-31, ,20:33:19.0300000
505,SELENDANG,OCC,26194,2,I*F** *MR** B** M**D H**A* *AK*R**D**  ,MALE,2017-06-01, ,17:49:54.6530000
810,SAMPING,VAC,14251,6,P**I** B**T* S*L**H  ,FEMALE,2017-05-29, ,00:10:47.8630000
602B,SUTERA,OCC,26172,2,G**R*E C**E K** Z**  ,MALE,2017-06-01, ,15:22:18.9970000
</code>```

By using below codes, I'm trying to extract the data:

```<code>$file       = "C:/btemp/bed-interface.txt";
$fileToLoad = fopen($file, "rb");
while(!feof($fileToLoad)){
    $data       = fgets($fileToLoad);
    $extract    = array_map('trim', explode(',', $data));
    $bnum       = trim(preg_replace('[^\s]', '', $extract[0]));
    //other array continue here
}
fclose($fileToLoad);
</code>```

Above codes will split the string by using comma but then when I'm trying to check each array strlen return, it will shows the incorrect value. For example, the first row data when return the $bnum it will show strlen of 7 instead 4. This will continue to other data. Can refer to below image to see the result of each return character. Each length are is in bracket. (All the name in the text has been masked)

```<code>801B (7)    SAMPING (13)    O   25999 (9)   2 (1)   R**NA** B**T* A** R*H** (45)                F   2017-05-29 (19) 14:58:01 (15)
820A (7)    SAMPING (13)    O   11191 (9)   5 (1)   M**A*M** H*I**L B** K*M**R*LBA**R*N (69)    F   2017-05-31 (19) 20:33:19 (15)
505 (5)     SELENDANG (17)  O   26194 (9)   2 (1)   I*F** *MR** B** M**D H**A* *AK*R**D** (73)  F   2017-06-01 (19) 17:49:54 (15)
810 (5)     SAMPING (13)    O   14251 (9)   6 (1)   P**I** B**T* S*L**H (37)                    F   2017-05-29 (19) 00:10:47 (15)
602B (7)    SUTERA (11)     O   26172 (9)   2 (1)   G**R*E C**E K** Z** (37)                    F   2017-06-01 (19) 15:22:18 (15)
</code>```

Result of explode and length of each array return

So, how to prevent this to happen. How to remove all the space. Already tried using trim, array_map, preg_replace still space appear when count using strlen. Even to do match in mysql query, it will return false cause the space has made the query return false.

答:
After investigating the value that has been sent to the database, seems that all the character in the database has unknown character after every each value.

For example SAMPING = S□A□M□P□I□N□G□ (there will be □ as unknown char and will read by strlen as 14 character)

By using correct preg_replace for each array retrieve:

```<code>$bnum       = preg_replace('/[^A-Za-z0-9_ -]/','',$extract[0]);
</code>```

instead of this:

```<code>$bnum       = trim(preg_replace('[^\s]', '', $extract[0]));
</code>```

it will remove all unwanted unknown character in the array and will save the correct value to the database.

Body:
Currently I'm trying to extract data from a text file that generated from a .asp website that will be load into interface.txt file. Format of the data are below (All the name in the text has been masked):

format of data in text file split by comma

801B,SAMPING,VAC,25999,2,R**NA** B**T* A** R*H**  ,FEMALE,2017-05-29, ,14:58:01.8000000
820A,SAMPING,VAC,11191,5,M**A*M** H*I**L B** K*M**R*LBA**R*N  ,MALE,2017-05-31, ,20:33:19.0300000
505,SELENDANG,OCC,26194,2,I*F** *MR** B** M**D H**A* *AK*R**D**  ,MALE,2017-06-01, ,17:49:54.6530000
810,SAMPING,VAC,14251,6,P**I** B**T* S*L**H  ,FEMALE,2017-05-29, ,00:10:47.8630000
602B,SUTERA,OCC,26172,2,G**R*E C**E K** Z**  ,MALE,2017-06-01, ,15:22:18.9970000

By using below codes, I'm trying to extract the data:

$file       = "C:/btemp/bed-interface.txt";
$fileToLoad = fopen($file, "rb");
while(!feof($fileToLoad)){
    $data       = fgets($fileToLoad);
    $extract    = array_map('trim', explode(',', $data));
    $bnum       = trim(preg_replace('[^\s]', '', $extract[0]));
    //other array continue here
}
fclose($fileToLoad);

Above codes will split the string by using comma but then when I'm trying to check each array strlen return, it will shows the incorrect value. For example, the first row data when return the $bnum it will show strlen of 7 instead 4. This will continue to other data. Can refer to below image to see the result of each return character. Each length are is in bracket. (All the name in the text has been masked)

801B (7)    SAMPING (13)    O   25999 (9)   2 (1)   R**NA** B**T* A** R*H** (45)                F   2017-05-29 (19) 14:58:01 (15)
820A (7)    SAMPING (13)    O   11191 (9)   5 (1)   M**A*M** H*I**L B** K*M**R*LBA**R*N (69)    F   2017-05-31 (19) 20:33:19 (15)
505 (5)     SELENDANG (17)  O   26194 (9)   2 (1)   I*F** *MR** B** M**D H**A* *AK*R**D** (73)  F   2017-06-01 (19) 17:49:54 (15)
810 (5)     SAMPING (13)    O   14251 (9)   6 (1)   P**I** B**T* S*L**H (37)                    F   2017-05-29 (19) 00:10:47 (15)
602B (7)    SUTERA (11)     O   26172 (9)   2 (1)   G**R*E C**E K** Z** (37)                    F   2017-06-01 (19) 15:22:18 (15)

Result of explode and length of each array return

So, how to prevent this to happen. How to remove all the space. Already tried using trim, array_map, preg_replace still space appear when count using strlen. Even to do match in mysql query, it will return false cause the space has made the query return false.

Body:
After investigating the value that has been sent to the database, seems that all the character in the database has unknown character after every each value.

For example SAMPING = S□A□M□P□I□N□G□ (there will be □ as unknown char and will read by strlen as 14 character)

By using correct preg_replace for each array retrieve:

$bnum       = preg_replace('/[^A-Za-z0-9_ -]/','',$extract[0]);

instead of this:

$bnum       = trim(preg_replace('[^\s]', '', $extract[0]));

it will remove all unwanted unknown character in the array and will save the correct value to the database.


问:
Apache2 won't start with phpMyadmin default module - OpenBSD 6.0
I've installed phpMyadmin in OpenBSD 6.0 and when I do cp  /var/www/conf/modules.sample/phpmyadmin.conf  /var/www/conf/modules/ and restart apache, it fails to work.

In error log it says:

[mpm_prefork:notice] [pid 35797] AH00169: caught SIGTERM, shutting down

I have to remove /var/www/conf/modules/phpmyadmin.conf for apache to come back to life

phpmyadmin.conf content is:

```<code># $OpenBSD: phpMyAdmin-httpd.conf,v 1.2 2013/01/18 15:17:43 giovanni Exp $

Alias /phpMyAdmin /var/www/phpMyAdmin

<IfModule !mod_rewrite.c>
        LoadModule rewrite_module /usr/lib/apache/modules/mod_rewrite.so

        RewriteEngine on

        # Allow only GET and POST verbs
        RewriteCond %{REQUEST_METHOD} !^(GET|POST)$ [NC,OR]

        # Ban Typical Vulnerability Scanners and others
        # Kick out Script Kiddies
        RewriteCond %{HTTP_USER_AGENT} ^(java|curl|wget).* [NC,OR]
        RewriteCond %{HTTP_USER_AGENT} ^.*(libwww-perl|curl|wget|python|nikto|wkito|pikto|scan|acunetix).* [NC,OR]
        RewriteCond %{HTTP_USER_AGENT} ^.*(winhttp|HTTrack|clshttp|archiver|loader|email|harvest|extract|grab|miner).* [NC,OR]

        # Ban Search Engines, Crawlers to your administrative panel
        # No reasons to access from bots
        # Ultimately Better than the useless robots.txt
        # Did google respect robots.txt?
        # Try google: intitle:phpMyAdmin intext:"Welcome to phpMyAdmin *.*.*" intext:"Log in" -wiki -forum -forums -questions in
text:"Cookies must be enabled"
        RewriteCond %{HTTP_USER_AGENT} ^.*(AdsBot-Google|ia_archiver|Scooter|Ask.Jeeves|Baiduspider|Exabot|FAST.Enterprise.Crawl
er|FAST-WebCrawler|www\.neomo\.de|Gigabot|Mediapartners-Google|Google.Desktop|Feedfetcher-Google|Googlebot|heise-IT-Markt-Crawle
r|heritrix|ibm.com\cs/crawler|ICCrawler|ichiro|MJ12bot|MetagerBot|msnbot-NewsBlogs|msnbot|msnbot-media|NG-Search|lucene.apache.o
rg|NutchCVS|OmniExplorer_Bot|online.link.validator|psbot0|Seekbot|Sensis.Web.Crawler|SEO.search.Crawler|Seoma.\[SEO.Crawler\]|SE
Osearch|Snappy|www.urltrends.com|www.tkl.iis.u-tokyo.ac.jp/~crawler|SynooBot|crawleradmin.t-info@telekom.de|TurnitinBot|voyager|
W3.SiteSearch.Crawler|W3C-checklink|W3C_Validator|www.WISEnutbot.com|yacybot|Yahoo-MMCrawler|Yahoo\!.DE.Slurp|Yahoo\!.Slurp|Yaho
oSeeker).* [NC]
        RewriteRule .* - [F]
</IfModule>

<Directory /var/www/phpMyAdmin>
        AllowOverride All

        # Default to only permitting access from localhost.
        Order deny,allow
        Deny from all
        Allow from 127.0.0.1
</Directory>
</code>```

答:
Can you try to change this directory permision from:

```<code><Directory /var/www/phpMyAdmin>
 AllowOverride All
 Order deny,allow
Deny from all
Allow from 127.0.0.1
</Directory>
</code>```

To:

```<code><Directory /var/www/phpMyAdmin>

Require all granted
 </Directory>
</code>```

Body:
I've installed phpMyadmin in OpenBSD 6.0 and when I do cp  /var/www/conf/modules.sample/phpmyadmin.conf  /var/www/conf/modules/ and restart apache, it fails to work.

In error log it says:

[mpm_prefork:notice] [pid 35797] AH00169: caught SIGTERM, shutting down

I have to remove /var/www/conf/modules/phpmyadmin.conf for apache to come back to life

phpmyadmin.conf content is:

# $OpenBSD: phpMyAdmin-httpd.conf,v 1.2 2013/01/18 15:17:43 giovanni Exp $

Alias /phpMyAdmin /var/www/phpMyAdmin

<IfModule !mod_rewrite.c>
        LoadModule rewrite_module /usr/lib/apache/modules/mod_rewrite.so

        RewriteEngine on

        # Allow only GET and POST verbs
        RewriteCond %{REQUEST_METHOD} !^(GET|POST)$ [NC,OR]

        # Ban Typical Vulnerability Scanners and others
        # Kick out Script Kiddies
        RewriteCond %{HTTP_USER_AGENT} ^(java|curl|wget).* [NC,OR]
        RewriteCond %{HTTP_USER_AGENT} ^.*(libwww-perl|curl|wget|python|nikto|wkito|pikto|scan|acunetix).* [NC,OR]
        RewriteCond %{HTTP_USER_AGENT} ^.*(winhttp|HTTrack|clshttp|archiver|loader|email|harvest|extract|grab|miner).* [NC,OR]

        # Ban Search Engines, Crawlers to your administrative panel
        # No reasons to access from bots
        # Ultimately Better than the useless robots.txt
        # Did google respect robots.txt?
        # Try google: intitle:phpMyAdmin intext:"Welcome to phpMyAdmin *.*.*" intext:"Log in" -wiki -forum -forums -questions in
text:"Cookies must be enabled"
        RewriteCond %{HTTP_USER_AGENT} ^.*(AdsBot-Google|ia_archiver|Scooter|Ask.Jeeves|Baiduspider|Exabot|FAST.Enterprise.Crawl
er|FAST-WebCrawler|www\.neomo\.de|Gigabot|Mediapartners-Google|Google.Desktop|Feedfetcher-Google|Googlebot|heise-IT-Markt-Crawle
r|heritrix|ibm.com\cs/crawler|ICCrawler|ichiro|MJ12bot|MetagerBot|msnbot-NewsBlogs|msnbot|msnbot-media|NG-Search|lucene.apache.o
rg|NutchCVS|OmniExplorer_Bot|online.link.validator|psbot0|Seekbot|Sensis.Web.Crawler|SEO.search.Crawler|Seoma.\[SEO.Crawler\]|SE
Osearch|Snappy|www.urltrends.com|www.tkl.iis.u-tokyo.ac.jp/~crawler|SynooBot|crawleradmin.t-info@telekom.de|TurnitinBot|voyager|
W3.SiteSearch.Crawler|W3C-checklink|W3C_Validator|www.WISEnutbot.com|yacybot|Yahoo-MMCrawler|Yahoo\!.DE.Slurp|Yahoo\!.Slurp|Yaho
oSeeker).* [NC]
        RewriteRule .* - [F]
</IfModule>

<Directory /var/www/phpMyAdmin>
        AllowOverride All

        # Default to only permitting access from localhost.
        Order deny,allow
        Deny from all
        Allow from 127.0.0.1
</Directory>

Body:
Can you try to change this directory permision from:

<Directory /var/www/phpMyAdmin>
 AllowOverride All
 Order deny,allow
Deny from all
Allow from 127.0.0.1
</Directory>

To:

<Directory /var/www/phpMyAdmin>

Require all granted
 </Directory>


问:
Search in PHP not showing message when there's no result
I had set a search button in my website. It works fine if there's a result but if there's none, it doesn't show the "no results.....".

What's wrong with my code?

```<code><html !DOCTYPE HTML>
    <body>
<?php
    $title = "DenTEETH";
    include('header.html');
    //connect to database
    $db = mysqli_connect("127.0.0.1", "root", "", "authentication");

    if(isset($_GET['q']) && $_GET['q'] !== '')
    {
        $searchq = $_GET['q'];
        $sql = "SELECT * FROM search WHERE keyword LIKE '%$searchq%' OR title LIKE '%$searchq%'";
        $output='';
        $results = mysqli_query($db, $sql);

        if (count($results) == 0){
            $output .= 'No search results for <b>"' . $searchq . '"</b>';
        }
        else{
            while ($row = mysqli_fetch_array($results)){
                $id = $row['search_id'];
                $title = $row['title'];
                $desc = $row['description'];
                $link = $row['link'];
                $img = '<img src="images/thumbnail/'.$row['search_id'].'.jpg" class="thumbnail">';

                $output .= '<div class="search_thumb">
                            <p class="search_cap"><a href="' . $link . '">' . $img . '<h3>' . $title . '</h3></a>' . $desc .
                            '<div class="clear"></div></p></div>';
            }
        }
    }
    else{
        header("location: ./");
    }
    print($output);
?>

<div class="row">

   </div>
<?php
        include('footer.html');

    ?>

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

答:
Use mysqli_num_rows() try this</p>

```<code><html !DOCTYPE HTML>
    <body>
<?php
    $title = "DenTEETH";
    include('header.html');
    //connect to database
    $db = mysqli_connect("127.0.0.1", "root", "", "authentication");

    if(isset($_GET['q']) && $_GET['q'] !== '')
    {
        $searchq = $_GET['q'];
        $sql = "SELECT * FROM search WHERE keyword LIKE '%$searchq%' OR title LIKE '%$searchq%'";
        $output='';
        $results = mysqli_query($db, $sql);

        if (mysqli_num_rows($results ) == 0){
            $output .= 'No search results for <b>"' . $searchq . '"</b>';
        }
        else{
            while ($row = mysqli_fetch_array($results)){
                $id = $row['search_id'];
                $title = $row['title'];
                $desc = $row['description'];
                $link = $row['link'];
                $img = '<img src="images/thumbnail/'.$row['search_id'].'.jpg" class="thumbnail">';

                $output .= '<div class="search_thumb">
                            <p class="search_cap"><a href="' . $link . '">' . $img . '<h3>' . $title . '</h3></a>' . $desc .
                            '<div class="clear"></div></p></div>';
            }
        }
    }
    else{
        header("location: ./");
    }
    print($output);
?>

<div class="row">

   </div>
<?php
        include('footer.html');

    ?>

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

Body:
I had set a search button in my website. It works fine if there's a result but if there's none, it doesn't show the "no results.....".

What's wrong with my code?

<?php
    $title = "DenTEETH";
    include('header.html');
    //connect to database
    $db = mysqli_connect("127.0.0.1", "root", "", "authentication");

    if(isset($_GET['q']) && $_GET['q'] !== '')
    {
        $searchq = $_GET['q'];
        $sql = "SELECT * FROM search WHERE keyword LIKE '%$searchq%' OR title LIKE '%$searchq%'";
        $output='';
        $results = mysqli_query($db, $sql);

        if (count($results) == 0){
            $output .= 'No search results for "' . $searchq . '"';
        }
        else{
            while ($row = mysqli_fetch_array($results)){
                $id = $row['search_id'];
                $title = $row['title'];
                $desc = $row['description'];
                $link = $row['link'];
                $img = '';

                $output .= '

' . $img . '
' . $title . '
' . $desc .
                            '

';
            }
        }
    }
    else{
        header("location: ./");
    }
    print($output);
?>

<?php
        include('footer.html');

    ?>

Body:
Use mysqli_num_rows() try this

<html !DOCTYPE HTML>
    <body>
<?php
    $title = "DenTEETH";
    include('header.html');
    //connect to database
    $db = mysqli_connect("127.0.0.1", "root", "", "authentication");

    if(isset($_GET['q']) && $_GET['q'] !== '')
    {
        $searchq = $_GET['q'];
        $sql = "SELECT * FROM search WHERE keyword LIKE '%$searchq%' OR title LIKE '%$searchq%'";
        $output='';
        $results = mysqli_query($db, $sql);

        if (mysqli_num_rows($results ) == 0){
            $output .= 'No search results for <b>"' . $searchq . '"</b>';
        }
        else{
            while ($row = mysqli_fetch_array($results)){
                $id = $row['search_id'];
                $title = $row['title'];
                $desc = $row['description'];
                $link = $row['link'];
                $img = '<img src="images/thumbnail/'.$row['search_id'].'.jpg" class="thumbnail">';

                $output .= '<div class="search_thumb">
                            <p class="search_cap"><a href="' . $link . '">' . $img . '<h3>' . $title . '</h3></a>' . $desc .
                            '<div class="clear"></div></p></div>';
            }
        }
    }
    else{
        header("location: ./");
    }
    print($output);
?>

<div class="row">

   </div>
<?php
        include('footer.html');

    ?>

</body>
</html>


问:
How to include the CSRF token in the headers in Dropzone upload request?
I am working on a single page application and I am using Laravel 5 for the web service.

All forms are submitted asynchronously and I use a beforeSend on them to attach the CSRF token which I take from the meta tag like so:

```<code>$.ajax({
    url: '/whatever/route',
    type: 'POST',
    dataType: 'JSON',
    data: $('form#whatever-form').serialize(),
    beforeSend: function(request) {
        return request.setRequestHeader('X-CSRF-Token', $("meta[name='token']").attr('content'));
    },
    success: function(response){
        rivets.bind($('#whateverTag'), {whateverData: response});
    },
    error: function(response){
    }
});
</code>```

All my forms work fine but dropzone upload doesn't. It gives me back a TokenMismatchException exception. Here is my dropzone code to update the profile photo:

```<code>$("#mydropzone").dropzone({
    url: "/profile/update-photo",
    addRemoveLinks : true,
    maxFilesize: 5,
    dictDefaultMessage: '<span class="text-center"><span class="font-lg visible-xs-block visible-sm-block visible-lg-block"><span class="font-lg"><i class="fa fa-caret-right text-danger"></i> Drop files <span class="font-xs">to upload</span></span><span>&nbsp&nbsp<h4 class="display-inline"> (Or Click)</h4></span>',
    dictResponseError: 'Error uploading file!'
});
</code>```

I have tried putting the beforeSend in here too:

```<code>$("#mydropzone").dropzone({
    url: "/profile/update-photo",
    addRemoveLinks : true,
    maxFilesize: 5,
    dictDefaultMessage: '<span class="text-center"><span class="font-lg visible-xs-block visible-sm-block visible-lg-block"><span class="font-lg"><i class="fa fa-caret-right text-danger"></i> Drop files <span class="font-xs">to upload</span></span><span>&nbsp&nbsp<h4 class="display-inline"> (Or Click)</h4></span>',
    dictResponseError: 'Error uploading file!',
    beforeSend: function(request) {
        return request.setRequestHeader('X-CSRF-Token', $("meta[name='token']").attr('content'));
    },
});
</code>```

I have also tried to put a global ajaxSetup in my main file like so:

```<code>$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="token"]').attr('content')
    }
});
</code>```

It is still not working. What am I doing wrong? How can I pass the CSRF token in the header with the dropzone upload so as to not a get an exception?

答:
This also works pretty well :</p>

```<code>$("#mydropzone").dropzone({
  url: "/profile/update-photo",
  addRemoveLinks : true,
  maxFilesize: 5,
  dictResponseError: 'Error uploading file!',
  headers: {
    'X-CSRF-Token': $('input[name="authenticity_token"]').val()
  }
});
</code>```

Body:
I am working on a single page application and I am using Laravel 5 for the web service.

All forms are submitted asynchronously and I use a beforeSend on them to attach the CSRF token which I take from the meta tag like so:

$.ajax({
    url: '/whatever/route',
    type: 'POST',
    dataType: 'JSON',
    data: $('form#whatever-form').serialize(),
    beforeSend: function(request) {
        return request.setRequestHeader('X-CSRF-Token', $("meta[name='token']").attr('content'));
    },
    success: function(response){
        rivets.bind($('#whateverTag'), {whateverData: response});
    },
    error: function(response){
    }
});

All my forms work fine but dropzone upload doesn't. It gives me back a TokenMismatchException exception. Here is my dropzone code to update the profile photo:

$("#mydropzone").dropzone({
    url: "/profile/update-photo",
    addRemoveLinks : true,
    maxFilesize: 5,
    dictDefaultMessage: ' Drop files to upload&nbsp&nbsp
 (Or Click)
',
    dictResponseError: 'Error uploading file!'
});

I have tried putting the beforeSend in here too:

$("#mydropzone").dropzone({
    url: "/profile/update-photo",
    addRemoveLinks : true,
    maxFilesize: 5,
    dictDefaultMessage: ' Drop files to upload&nbsp&nbsp
 (Or Click)
',
    dictResponseError: 'Error uploading file!',
    beforeSend: function(request) {
        return request.setRequestHeader('X-CSRF-Token', $("meta[name='token']").attr('content'));
    },
});

I have also tried to put a global ajaxSetup in my main file like so:

$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="token"]').attr('content')
    }
});

It is still not working. What am I doing wrong? How can I pass the CSRF token in the header with the dropzone upload so as to not a get an exception?

Body:
This also works pretty well :

$("#mydropzone").dropzone({
  url: "/profile/update-photo",
  addRemoveLinks : true,
  maxFilesize: 5,
  dictResponseError: 'Error uploading file!',
  headers: {
    'X-CSRF-Token': $('input[name="authenticity_token"]').val()
  }
});


问:
Karma Error - Module Parse failed, Unexpected Character '
Can anybody tell me why I am getting this error:

```<code> Uncaught Error: Module parse failed: app\src\app\css\fonts\roboto-300-latin.woff2
 Unexpected character ' ' (1:4)
 You may need an appropriate loader to handle this file type.
 (Source code omitted for this binary file)
 at unit_tests/index.js:138633

npm ERR! Test failed.  See above for more details.
</code>```

My karma config:

```<code>// Karma configuration file, see link for more information
// https://karma-runner.github.io/0.13/config/configuration-file.html
module.exports = function (config) {
  config.set({
     basePath: '',
     frameworks: ['jasmine'],
     plugins: [
        require('karma-jasmine'),
        require("karma-webpack"),
        require('karma-chrome-launcher'),
        require('karma-sourcemap-loader'),
        require('karma-jasmine-html-reporter'),
        require('karma-coverage-istanbul-reporter'),
        require('@angular/cli/plugins/karma'),
         'karma-*'
       ],
      client: {
       clearContext: false // leave Jasmine Spec Runner output visible in browser
      },
     files: [
       'unit_tests/index.js'
     ],
     preprocessors: {
       'unit_tests/index.js': ['webpack', 'sourcemap']
     },
     webpack: {
        resolve: {
          extensions: ['.ts', '.js', '.jsx'],
          alias: {
             components: 'components',
             services: 'services'
          }
         },
       module: {
       rules: [{
        test: /\.ts$/,
        loaders: [
          'awesome-typescript-loader',
          'angular2-template-loader'
        ]
      },
      {
        test: /\.scss$/,
        loaders: [
          'style-loader',
          'css-loader',
          'sass-loader'
         ],
        // exclude: [helpers.root('src/index.html')]
      },
      {
        test: /\.html$/,
        loader: 'raw-loader'
      }
    ]
  },
   devtool: 'inline-source-map'
  },
   reporters: ['progress'],
   port: 9876,
   colors: true,
   logLevel: config.LOG_INFO,
   autoWatch: true,
   browsers: ['Chrome'],
   singleRun: true,
   concurrency: Infinity
  });
};
</code>```

My spec file:

```<code>import { ComponentFixture, TestBed, async } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { DebugElement } from '@angular/core';
import { RouterModule, Router } from '@angular/router';
import { MaterialModule } from '@angular/material';
import { FormsModule } from '@angular/forms';
import { AuthHttp, AuthConfig, AUTH_PROVIDERS, provideAuth, tokenNotExpired
} from 'angular2-jwt';
import { AppModule } from '../../../src/app/app.module';
import { } from 'jasmine';

import { FirmService } from '../../../src/app/containers/dashboard/services/firm.service';
import { FirmListComponent } from '../../../src/app/containers/dashboard/firm-list/firm-list.component';

describe('Firm List Component', () => {
let component;
let fixture;
let de: DebugElement;
let el: HTMLElement;
let de2: DebugElement;
let el2: HTMLElement;

let mockRouter: any;
    class MockRouter {
       public navigate = jasmine.createSpy('navigate');
   }

beforeEach(async(() => {
    TestBed.configureTestingModule({
        imports: [MaterialModule, FormsModule, AppModule],
        declarations: [FirmListComponent],
        providers: [FirmService]
    })
        .compileComponents()
        .then(() => {
            fixture = TestBed.createComponent(FirmListComponent);
            component = fixture.componentInstance;
        });
}));

it('should have a defined component', () => {
    expect(component).toBeDefined();
  });
});
</code>```

I'm getting this error when I try to import my AppModule. I want to import that instead of having to import a bunch of different services and configs separately.Thanks for the help

答:
You have error because there is no loader or transformer which can transform your fonts file. for that first you have to install file-loader

npm install --save-dev file-loader

then Add this object to rules array. its telling webpack that when you find these type of font files transform them with file-loader

```<code>{
        test: /\.(svg|eot|ttf|woff|woff2)$/,
        use:'file-loader'

}
</code>```

The end form of your karma config can be

```<code>// Karma configuration file, see link for more information
// https://karma-runner.github.io/0.13/config/configuration-file.html
module.exports = function (config) {
  config.set({
     basePath: '',
     frameworks: ['jasmine'],
     plugins: [
        require('karma-jasmine'),
        require("karma-webpack"),
        require('karma-chrome-launcher'),
        require('karma-sourcemap-loader'),
        require('karma-jasmine-html-reporter'),
        require('karma-coverage-istanbul-reporter'),
        require('@angular/cli/plugins/karma'),
         'karma-*'
       ],
      client: {
       clearContext: false // leave Jasmine Spec Runner output visible in browser
      },
     files: [
       'unit_tests/index.js'
     ],
     preprocessors: {
       'unit_tests/index.js': ['webpack', 'sourcemap']
     },
     webpack: {
        resolve: {
          extensions: ['.ts', '.js', '.jsx'],
          alias: {
             components: 'components',
             services: 'services'
          }
         },
       module: {
       rules: [{
        test: /\.(svg|eot|ttf|woff|woff2)$/,
        use:'file-loader'

        },{
        test: /\.ts$/,
        loaders: [
          'awesome-typescript-loader',
          'angular2-template-loader'
        ]
      },
      {
        test: /\.scss$/,
        loaders: [
          'style-loader',
          'css-loader',
          'sass-loader'
         ],
        // exclude: [helpers.root('src/index.html')]
      },
      {
        test: /\.html$/,
        loader: 'raw-loader'
      }
    ]
  },
   devtool: 'inline-source-map'
  },
   reporters: ['progress'],
   port: 9876,
   colors: true,
   logLevel: config.LOG_INFO,
   autoWatch: true,
   browsers: ['Chrome'],
   singleRun: true,
   concurrency: Infinity
  });
};
</code>```

Body:
Can anybody tell me why I am getting this error:

 Uncaught Error: Module parse failed: app\src\app\css\fonts\roboto-300-latin.woff2
 Unexpected character ' ' (1:4)
 You may need an appropriate loader to handle this file type.
 (Source code omitted for this binary file)
 at unit_tests/index.js:138633

npm ERR! Test failed.  See above for more details.

My karma config:

// Karma configuration file, see link for more information
// https://karma-runner.github.io/0.13/config/configuration-file.html
module.exports = function (config) {
  config.set({
     basePath: '',
     frameworks: ['jasmine'],
     plugins: [
        require('karma-jasmine'),
        require("karma-webpack"),
        require('karma-chrome-launcher'),
        require('karma-sourcemap-loader'),
        require('karma-jasmine-html-reporter'),
        require('karma-coverage-istanbul-reporter'),
        require('@angular/cli/plugins/karma'),
         'karma-*'
       ],
      client: {
       clearContext: false // leave Jasmine Spec Runner output visible in browser
      },
     files: [
       'unit_tests/index.js'
     ],
     preprocessors: {
       'unit_tests/index.js': ['webpack', 'sourcemap']
     },
     webpack: {
        resolve: {
          extensions: ['.ts', '.js', '.jsx'],
          alias: {
             components: 'components',
             services: 'services'
          }
         },
       module: {
       rules: [{
        test: /\.ts$/,
        loaders: [
          'awesome-typescript-loader',
          'angular2-template-loader'
        ]
      },
      {
        test: /\.scss$/,
        loaders: [
          'style-loader',
          'css-loader',
          'sass-loader'
         ],
        // exclude: [helpers.root('src/index.html')]
      },
      {
        test: /\.html$/,
        loader: 'raw-loader'
      }
    ]
  },
   devtool: 'inline-source-map'
  },
   reporters: ['progress'],
   port: 9876,
   colors: true,
   logLevel: config.LOG_INFO,
   autoWatch: true,
   browsers: ['Chrome'],
   singleRun: true,
   concurrency: Infinity
  });
};

My spec file:

import { ComponentFixture, TestBed, async } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { DebugElement } from '@angular/core';
import { RouterModule, Router } from '@angular/router';
import { MaterialModule } from '@angular/material';
import { FormsModule } from '@angular/forms';
import { AuthHttp, AuthConfig, AUTH_PROVIDERS, provideAuth, tokenNotExpired
} from 'angular2-jwt';
import { AppModule } from '../../../src/app/app.module';
import { } from 'jasmine';

import { FirmService } from '../../../src/app/containers/dashboard/services/firm.service';
import { FirmListComponent } from '../../../src/app/containers/dashboard/firm-list/firm-list.component';

describe('Firm List Component', () => {
let component;
let fixture;
let de: DebugElement;
let el: HTMLElement;
let de2: DebugElement;
let el2: HTMLElement;

let mockRouter: any;
    class MockRouter {
       public navigate = jasmine.createSpy('navigate');
   }

beforeEach(async(() => {
    TestBed.configureTestingModule({
        imports: [MaterialModule, FormsModule, AppModule],
        declarations: [FirmListComponent],
        providers: [FirmService]
    })
        .compileComponents()
        .then(() => {
            fixture = TestBed.createComponent(FirmListComponent);
            component = fixture.componentInstance;
        });
}));

it('should have a defined component', () => {
    expect(component).toBeDefined();
  });
});

I'm getting this error when I try to import my AppModule. I want to import that instead of having to import a bunch of different services and configs separately.Thanks for the help

Body:
You have error because there is no loader or transformer which can transform your fonts file. for that first you have to install file-loader

npm install --save-dev file-loader

then Add this object to rules array. its telling webpack that when you find these type of font files transform them with file-loader

{
        test: /\.(svg|eot|ttf|woff|woff2)$/,
        use:'file-loader'

}

The end form of your karma config can be

// Karma configuration file, see link for more information
// https://karma-runner.github.io/0.13/config/configuration-file.html
module.exports = function (config) {
  config.set({
     basePath: '',
     frameworks: ['jasmine'],
     plugins: [
        require('karma-jasmine'),
        require("karma-webpack"),
        require('karma-chrome-launcher'),
        require('karma-sourcemap-loader'),
        require('karma-jasmine-html-reporter'),
        require('karma-coverage-istanbul-reporter'),
        require('@angular/cli/plugins/karma'),
         'karma-*'
       ],
      client: {
       clearContext: false // leave Jasmine Spec Runner output visible in browser
      },
     files: [
       'unit_tests/index.js'
     ],
     preprocessors: {
       'unit_tests/index.js': ['webpack', 'sourcemap']
     },
     webpack: {
        resolve: {
          extensions: ['.ts', '.js', '.jsx'],
          alias: {
             components: 'components',
             services: 'services'
          }
         },
       module: {
       rules: [{
        test: /\.(svg|eot|ttf|woff|woff2)$/,
        use:'file-loader'

        },{
        test: /\.ts$/,
        loaders: [
          'awesome-typescript-loader',
          'angular2-template-loader'
        ]
      },
      {
        test: /\.scss$/,
        loaders: [
          'style-loader',
          'css-loader',
          'sass-loader'
         ],
        // exclude: [helpers.root('src/index.html')]
      },
      {
        test: /\.html$/,
        loader: 'raw-loader'
      }
    ]
  },
   devtool: 'inline-source-map'
  },
   reporters: ['progress'],
   port: 9876,
   colors: true,
   logLevel: config.LOG_INFO,
   autoWatch: true,
   browsers: ['Chrome'],
   singleRun: true,
   concurrency: Infinity
  });
};


问:
Offline (CD, Thumb Drive, etc) No-Install HTML + Video Presentation?
Our company would like to put some marketing/training content onto USB thumb drives to distribute to our clients.

The content is HTML + some embedded videos.  The videos (currently .flv's) are not interactive or anything like that, though they are important to the content.  The tricky bit is that the HTML contains Javascript that needs to run when the video is finished.

Our first thought was to use a Flash video wrapper solution like Jwplayer.  This works fine when the files are
hosted on a web server.  However, due to Flash's security policies, local (e.g. "file://foo.js") Javascript code cannot receive callbacks from Flash objects.  Additionally, Internet Explorer users get nasty security warnings (as they darn well should!) when local web files contain ActiveX objects like Flash.

Ideas?

Ideally, we'd like to be as cross-browser and as cross-platform as possible without requiring users to install anything.  But we can't guarantee they
ll be able or willing to screw around with security settings and we can't guarantee they'll have an HTML5-video capable browser, either.

Seems like the default industry way to do this is to simply package things up into standalone Flash Player executable.  Was wondering if it could be done otherwise, preferably with web standards.

Titanium Appcelerator Desktop would be close to perfect, though the desktop version doesn't support video!

答: If this is just marketing/training content, why don't you embed it in a PowerPoint file where you can still have video?  </p>


问:
SQL How to return all rows of a table and limit the rows of another by id and have them joined
How do i return all rows from the timeslot table and also limit the rows from consultation table by employeeId

This query returns entries with the employeeId =1,

```<code>SELECT TimeSlot, conStart, firstName, lastName, phoneNumber
FROM TimeSlots
LEFT JOIN consultation
ON TimeSlots.TimeSlot = consultation.conStart
LEFT JOIN patient
ON consultation.patientId = patient.patientID
WHERE employeeId = 1
</code>```

Which gives me this

```<code>11:00:00.0000000    11:00:00.0000000    chris   wilson  6666666666
</code>```

I would like to know how to show all the Timeslots but only show entries from
one employeeID

This is how i want it to turn out.

```<code>09:00:00.0000000    NULL    NULL    NULL    NULL

09:20:00.0000000    NULL    NULL    NULL    NULL

09:40:00.0000000    NULL    NULL    NULL    NULL

10:00:00.0000000    NULL    NULL    NULL    NULL

10:20:00.0000000    10:20   tim     is      1111111111

10:40:00.0000000    NULL    NULL    NULL    NULL

11:00:00.0000000    11:00   chris   wilson  6666666666

11:20:00.0000000    NULL    NULL    NULL    NULL
</code>```

答:
Try this</p>

```<code>SELECT TimeSlot, conStart, firstName, lastName, phoneNumber
FROM TimeSlots
     LEFT JOIN (consultation
                LEFT JOIN patient
                ON consultation.patientId = patient.patientID)
     ON TimeSlots.TimeSlot = consultation.conStart AND TimeSlots.employeeId = 1
</code>```

Body:
How do i return all rows from the timeslot table and also limit the rows from consultation table by employeeId

This query returns entries with the employeeId =1,

SELECT TimeSlot, conStart, firstName, lastName, phoneNumber
FROM TimeSlots
LEFT JOIN consultation
ON TimeSlots.TimeSlot = consultation.conStart
LEFT JOIN patient
ON consultation.patientId = patient.patientID
WHERE employeeId = 1

Which gives me this

11:00:00.0000000    11:00:00.0000000    chris   wilson  6666666666

I would like to know how to show all the Timeslots but only show entries from
one employeeID

This is how i want it to turn out.

09:00:00.0000000    NULL    NULL    NULL    NULL

09:20:00.0000000    NULL    NULL    NULL    NULL

09:40:00.0000000    NULL    NULL    NULL    NULL

10:00:00.0000000    NULL    NULL    NULL    NULL

10:20:00.0000000    10:20   tim     is      1111111111

10:40:00.0000000    NULL    NULL    NULL    NULL

11:00:00.0000000    11:00   chris   wilson  6666666666

11:20:00.0000000    NULL    NULL    NULL    NULL

Body:
Try this

SELECT TimeSlot, conStart, firstName, lastName, phoneNumber
FROM TimeSlots
     LEFT JOIN (consultation
                LEFT JOIN patient
                ON consultation.patientId = patient.patientID)
     ON TimeSlots.TimeSlot = consultation.conStart AND TimeSlots.employeeId = 1


问:
Oracle RAC instance fail
I use the Oracle database 11gr2, and it is a RAC environment that has two instances. One day, one instance failed when the hardware failed. The client uses the tnsnames.ora which has two IP addresses to connect to, but it still can't connect to the database and gets some errors. So I want to know if it is the fault that the client didn't write the code to reconnect or it is the fault that the Oracle RAC configuration didn't automatically change the connection to the other instance?

答: It is probably a mistake in the RAC setup, and possibly the tnsnames.ora file.  As long as the application was connecting to a service name in tnsnames.ora then Oracle RAC should have handled the switchover to the other node.

Title: Oracle RAC instance fail