问:
Rails overriding bootstrap's css in an organised way
I have a new rails project, and it is using the following gem:

```<code>gem 'bootstrap-sass'
</code>```

I am using the horizontal-form CSS class - which has by default:

```<code>text-align:right; as part of .horizontal-form
</code>```

I want to override this so that all labels have text-align:left;

In my rails project, under stylesheets I have the following:

```<code>1st_load_framework.scss
</code>```

Which has :

```<code>// import the CSS framework

@import "bootstrap-sprockets";
@import "bootstrap";

...bunch of css classes and @variables.

//I have tried adding:

.horizontal-form{ text-align:left; } into this file however, it is overriding by the generated sass CSS.

application.scss
</code>```

Which has :

```<code>    /*
 * This is a manifest file that'll be compiled into application.css, which will include all the files
 * listed below.
 *
 * Any CSS and SCSS file within this directory, lib/assets/stylesheets, vendor/assets/stylesheets,
 * or vendor/assets/stylesheets of plugins, if any, can be referenced here using a relative path.
 *
 * You're free to add application-wide styles to this file and they'll appear at the bottom of the
 * compiled file so the styles you add here take precedence over styles defined in any styles
 * defined in the other CSS/SCSS files in this directory. It is generally better to create a new
 * file per style scope.
 *
@import "bootstrap-sprockets";
@import "bootstrap";
*= require_tree .
*= require_self
 */

.sign-up{
    background-color:#95ccfb;
}

.log-in{
    background-color:#75d86a;
}

.horizontal-form{ text-align:left !important; }
</code>```

I have also tried adding :

```<code> .horizontal-form{ text-align:left; }
</code>```

to the bottom of application.scss to no avail.

How can I make an override like this? I don't believe this particular class has a sass variable, so I am looking for a normal CSS override here - something scalable for the rest of my project in rails would be great.

Using Rails 5.1.1, bootstrap 3

Please help!

答:
Since you're overriding the bootstrap setting I'm guessing that the CSS is compiling your change above where it's declared by bootstrap CSS. And since it's lower in the cascade it's being given priority. I would try to make it read like this:

.horizontal-form{ text-align:left !important; }

That should override any prior definitions of the class. Use it sparingly though as !important can cause some issues if overused.

Edit

Rearrange your asset pipeline as such:

```<code>*= require_self
*/
@import "bootstrap-sprockets";
@import "bootstrap";
@import "1st_load_framework";
</code>```

The asset pipeline is loaded from top to bottom as well, so load your custom CSS after Bootstrap.

Body:
I have a new rails project, and it is using the following gem:

gem 'bootstrap-sass'

I am using the horizontal-form CSS class - which has by default:

text-align:right; as part of .horizontal-form

I want to override this so that all labels have text-align:left;

In my rails project, under stylesheets I have the following:

1st_load_framework.scss

Which has :

// import the CSS framework

@import "bootstrap-sprockets";
@import "bootstrap";

...bunch of css classes and @variables.

//I have tried adding:

.horizontal-form{ text-align:left; } into this file however, it is overriding by the generated sass CSS.

application.scss

Which has :

    /*
 * This is a manifest file that'll be compiled into application.css, which will include all the files
 * listed below.
 *
 * Any CSS and SCSS file within this directory, lib/assets/stylesheets, vendor/assets/stylesheets,
 * or vendor/assets/stylesheets of plugins, if any, can be referenced here using a relative path.
 *
 * You're free to add application-wide styles to this file and they'll appear at the bottom of the
 * compiled file so the styles you add here take precedence over styles defined in any styles
 * defined in the other CSS/SCSS files in this directory. It is generally better to create a new
 * file per style scope.
 *
@import "bootstrap-sprockets";
@import "bootstrap";
*= require_tree .
*= require_self
 */

.sign-up{
    background-color:#95ccfb;
}

.log-in{
    background-color:#75d86a;
}

.horizontal-form{ text-align:left !important; }

I have also tried adding :

 .horizontal-form{ text-align:left; }

to the bottom of application.scss to no avail.

How can I make an override like this? I don't believe this particular class has a sass variable, so I am looking for a normal CSS override here - something scalable for the rest of my project in rails would be great.

Using Rails 5.1.1, bootstrap 3

Please help!

Body:
Since you're overriding the bootstrap setting I'm guessing that the CSS is compiling your change above where it's declared by bootstrap CSS. And since it's lower in the cascade it's being given priority. I would try to make it read like this:

.horizontal-form{ text-align:left !important; }

That should override any prior definitions of the class. Use it sparingly though as !important can cause some issues if overused.

Edit

Rearrange your asset pipeline as such:

*= require_self
*/
@import "bootstrap-sprockets";
@import "bootstrap";
@import "1st_load_framework";

The asset pipeline is loaded from top to bottom as well, so load your custom CSS after Bootstrap.


来源: stackexchange

问:
How to display even number and a multiple of 3 from arraylist
Sorry, maybe I did not explain clearly. This is my pracitce

input a positive integer. If the input is not positive then then your algorithm should output an error message and re-prompt the user for the input. This process should continue to loop until the input is valid. Your algorithm should then output whether or not the input is an even number and a multiple of 3. Note your solution must make appropriate use of sub modules.

I have to create a method which gets a positive number from user input, And I need to display even numbers and multiple of 3 from this ArrayList. I have written code for that but I have struggled with how to use another submodule to display this ArrayList.

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

public class Array {

    public static void main(String[] args)
    {

        Scanner sc = new Scanner(System.in);
        ArrayList<Integer> list;
        list = new ArrayList<Integer>();
         int number = -1;
        printList(list, number );
        System.out.println("Enter number.  Enter 0 to end.");
        while (true)
        {
            System.out.print(" ");
            number = sc.nextInt();

        while( number < 0)
        {
        System.out.print("Enter your next positive integer, or 0 to end: ");
        number = sc.nextInt();
        }
         if (number == 0)
                break;
            list.add(number);
        }

    }
        public static void printList (ArrayList<Integer> list, int number)
        {
            for(int i = 0;i <= number.size(); i++)
            {
            if(i % 2 ==0 && i % 3 ==0)
            {
                 System.out.println(list(i));
            }
            }
        }
    }
</code>```

答:
Ok I get your problem, looks like you are not able to print the list, you should probably modify your code a little

you just have to paste printList() after the while loop.

```<code>while (true)
{
    System.out.print(" ");
    number = sc.nextInt();

    while( number < 0)
    {
        System.out.print("Enter your next positive integer, or 0 to end: ");
        number = sc.nextInt();
    }
    if (number == 0)
        break;
    list.add(number);
}
printList(list);
</code>```

and your printlist method is not correct, it should be like this

```<code>public void printlist(List<Integer> numberList){
    for(int i = 0;i <= numberList.size(); i++)
    {
        if(i % 2 ==0 && i % 3 ==0)
        {
             System.out.println(numberList.get(i));
        }
    }
}
</code>```

hope this helps!
Good luck!

ContentLicense: CC BY-SA 3.0

Body:
Sorry, maybe I did not explain clearly. This is my pracitce

input a positive integer. If the input is not positive then then your algorithm should output an error message and re-prompt the user for the input. This process should continue to loop until the input is valid. Your algorithm should then output whether or not the input is an even number and a multiple of 3. Note your solution must make appropriate use of sub modules.

I have to create a method which gets a positive number from user input, And I need to display even numbers and multiple of 3 from this ArrayList. I have written code for that but I have struggled with how to use another submodule to display this ArrayList.

import java.util.ArrayList;
import java.util.*;

public class Array {

    public static void main(String[] args)
    {

        Scanner sc = new Scanner(System.in);
        ArrayList<Integer> list;
        list = new ArrayList<Integer>();
         int number = -1;
        printList(list, number );
        System.out.println("Enter number.  Enter 0 to end.");
        while (true)
        {
            System.out.print(" ");
            number = sc.nextInt();

        while( number < 0)
        {
        System.out.print("Enter your next positive integer, or 0 to end: ");
        number = sc.nextInt();
        }
         if (number == 0)
                break;
            list.add(number);
        }

    }
        public static void printList (ArrayList<Integer> list, int number)
        {
            for(int i = 0;i <= number.size(); i++)
            {
            if(i % 2 ==0 && i % 3 ==0)
            {
                 System.out.println(list(i));
            }
            }
        }
    }

Body:
Ok I get your problem, looks like you are not able to print the list, you should probably modify your code a little

you just have to paste printList() after the while loop.

while (true)
{
    System.out.print(" ");
    number = sc.nextInt();

    while( number < 0)
    {
        System.out.print("Enter your next positive integer, or 0 to end: ");
        number = sc.nextInt();
    }
    if (number == 0)
        break;
    list.add(number);
}
printList(list);

and your printlist method is not correct, it should be like this

public void printlist(List<Integer> numberList){
    for(int i = 0;i <= numberList.size(); i++)
    {
        if(i % 2 ==0 && i % 3 ==0)
        {
             System.out.println(numberList.get(i));
        }
    }
}

hope this helps!
Good luck!


问:
Unable to get good example of using memcached from Java boot
I am using java boot for my development. For now I have used 'EhCache' for caching , it is directly supported from Java boot. This is "in-process" cache, i.e., becomes part of your process. It is okay for now. But my server will run on multiple nodes in near future. Hence want to switch to 'Memcached' as common caching layer.

After spending good amount of time, I could not get good sample of using Memcached from java boot. I have looked at 'Simple Spring Memcached' which comes close to my requirement. But still it gives example using XML configuration in Spring way. Java boot does not use such XML configuration as far as possible. At least I could not map the example quickly to java boot world.

I want to use Memcahed ( directly or via cache-abstraction-layer) from java boot. If anybody points me to a relevant java boot example, it will save a lot of time for me.

答:
You can find some materials how to configure SSM using Java configuration instead of XML files here and here.
Basically you have to move definitions of all beans from XML to Java. </p>


问:
issue while outputting the image in code igniter
I'm new to code igniter and learning with how to display images in html page. But the images displays file but it also displays the image tags alt="" also. Here is  my code.

views/admin.php

```<code><div class="row">
        <?php
            //print_r($images_disp);

            foreach($images_disp as $item=>$val){
        ?>
                <div class="col-md-3">
                    <img src="<?php echo base_url().''.$val['imagepath'];?>" width="150px" height="150px" alt="'<?php echo $val['name']?>'" >
                </div>
        <?php
            }
        ?>
        </div>
</code>```

controller/AddProduct_controller

```<code> public function index(){
        $sql['images_disp'] = $this->addProduct_model->show_images();
        /* echo "```";
        print_r($sql);
        echo "```"; */
        $this->load->view('admin',$sql);
    }
</code>```

model/AddProduct_model

```<code>public function show_images(){
    $query = $this->db->get('db_images');
    $query = $query->result_array();

    return $query;
}
</code>```

HERE IS THE ISSUE IN BELOW IMAGE
OUTPUT IMAGE

THANKS IN ADVANCE

答:
In your scenario name column contains double quotes(") which is causing problem in echo statement. Double quotes causing alt attribute value issue.
Replace your line of code with this line :

```<code><img src="<?php echo base_url().''.$val['imagepath'];?>" width="150px" height="150px" alt="'<?php echo html_escape($val['name']); ?>'" >
</code>```

html_escape will escape the html character from your string.
Advice :
Always avoid inserting quotes and other character directly in database, escape user input before inserting in database.

At time of insert escape user input like this.

```<code>$escaped_str =  $this->db->escape($input_str);
</code>```

$this->db->escape() method will escape all the quotes from your string.

Body:
I'm new to code igniter and learning with how to display images in html page. But the images displays file but it also displays the image tags alt="" also. Here is  my code.

views/admin.php

        <?php
            //print_r($images_disp);

            foreach($images_disp as $item=>$val){
        ?>

                    <img src="<?php echo base_url().''.$val['imagepath'];?>" width="150px" height="150px" alt="'<?php echo $val['name']?>'" >

        <?php
            }
        ?>

controller/AddProduct_controller

 public function index(){
        $sql['images_disp'] = $this->addProduct_model->show_images();
        /* echo "
";
        print_r($sql);
        echo "
"; */
        $this->load->view('admin',$sql);
    }

model/AddProduct_model

public function show_images(){
    $query = $this->db->get('db_images');
    $query = $query->result_array();

    return $query;
}

HERE IS THE ISSUE IN BELOW IMAGE
OUTPUT IMAGE

THANKS IN ADVANCE

Body:
In your scenario name column contains double quotes(") which is causing problem in echo statement. Double quotes causing alt attribute value issue.
Replace your line of code with this line :

<img src="<?php echo base_url().''.$val['imagepath'];?>" width="150px" height="150px" alt="'<?php echo html_escape($val['name']); ?>'" >

html_escape will escape the html character from your string.
Advice :
Always avoid inserting quotes and other character directly in database, escape user input before inserting in database.

At time of insert escape user input like this.

$escaped_str =  $this->db->escape($input_str);

$this->db->escape() method will escape all the quotes from your string.


问:
golang websocket how to be notified when browser closed unexpectly
I am writing a websocket service in golang.
The program use gollira websocket to accept ws request, and in each request handler, it listen to rabbitmq queue for messages.

The problem is, when i close browser window, the handler thread is still running, i guess there is an mechanism to be notified when connection disconnected.

I try to listen to channel request.Context().Done(), when i doesn't work.

```<code>package main

import (
    "fmt"
    "log"
    "net/http"

    "github.com/gorilla/websocket"
    "github.com/streadway/amqp"
)

var (
    addr     = "localhost:9999"
    upgrader = websocket.Upgrader{
        CheckOrigin: func(r *http.Request) bool { return true },
    }
)

var conn *amqp.Connection

func watch(w http.ResponseWriter, r *http.Request) {
    ns := r.URL.Query().Get("ns")
    if ns == "" {
        return
    }
    c, err := upgrader.Upgrade(w, r, nil)
    if err != nil {
        log.Print("upgrade:", err)
        return
    }
    defer c.Close()

    ch, err := conn.Channel()
    failOnError(err, "Failed to open a channel")
    defer ch.Close()

    err = ch.ExchangeDeclare(
        "notify", // name
        "fanout",           // type
        true,               // durable
        false,              // auto-deleted
        false,              // internal
        false,              // no-wait
        nil,                // arguments
    )
    failOnError(err, "Failed to declare an exchange")

    q, err := ch.QueueDeclare(
        "",    // name
        false, // durable
        false, // delete when usused
        true,  // exclusive
        false, // no-wait
        nil,   // arguments
    )
    failOnError(err, "Failed to declare a queue")

    err = ch.QueueBind(
        q.Name,             // queue name
        ns,                 // routing key
        "dsm_tasks_notify", // exchange
        false,
        nil)
    failOnError(err, "Failed to bind a queue")

    msgs, err := ch.Consume(
        q.Name, // queue
        "",     // consumer
        true,   // auto-ack
        false,  // exclusive
        false,  // no-local
        false,  // no-wait
        nil,    // args
    )
    failOnError(err, "Failed to register a consumer")

    for {
        select {
        case d := <-msgs:
            err = c.WriteMessage(websocket.TextMessage, d.Body)
            if err != nil {
                log.Println("write:", err)
                break
            }
        case <-r.Context().Done():
            log.Println("Disconnect")
            return
        }
    }

}

func failOnError(err error, msg string) {
    if err != nil {
        log.Fatalf("%s: %s", msg, err)
        panic(fmt.Sprintf("%s: %s", msg, err))
    }
}

func main() {
    var err error
    conn, err = amqp.Dial("amqp://guest:guest@localhost:5672/")
    failOnError(err, "Failed to connect to RabbitMQ")
    defer conn.Close()

    http.HandleFunc("/watch", watch)
    log.Fatal(http.ListenAndServe(addr, nil))
}
</code>```

答:
If the browser cleanly closes the connection, then read on the webssocket connection returns an error.  Cleanup the websocket connection as you would on any read error.

The application must PING the connection and expect the corresponding PONGs to detect other situations.  The chat example shows how to send PINGs and receive PONGs.

Body:
I am writing a websocket service in golang.
The program use gollira websocket to accept ws request, and in each request handler, it listen to rabbitmq queue for messages.

The problem is, when i close browser window, the handler thread is still running, i guess there is an mechanism to be notified when connection disconnected.

I try to listen to channel request.Context().Done(), when i doesn't work.

package main

import (
    "fmt"
    "log"
    "net/http"

    "github.com/gorilla/websocket"
    "github.com/streadway/amqp"
)

var (
    addr     = "localhost:9999"
    upgrader = websocket.Upgrader{
        CheckOrigin: func(r *http.Request) bool { return true },
    }
)

var conn *amqp.Connection

func watch(w http.ResponseWriter, r *http.Request) {
    ns := r.URL.Query().Get("ns")
    if ns == "" {
        return
    }
    c, err := upgrader.Upgrade(w, r, nil)
    if err != nil {
        log.Print("upgrade:", err)
        return
    }
    defer c.Close()

    ch, err := conn.Channel()
    failOnError(err, "Failed to open a channel")
    defer ch.Close()

    err = ch.ExchangeDeclare(
        "notify", // name
        "fanout",           // type
        true,               // durable
        false,              // auto-deleted
        false,              // internal
        false,              // no-wait
        nil,                // arguments
    )
    failOnError(err, "Failed to declare an exchange")

    q, err := ch.QueueDeclare(
        "",    // name
        false, // durable
        false, // delete when usused
        true,  // exclusive
        false, // no-wait
        nil,   // arguments
    )
    failOnError(err, "Failed to declare a queue")

    err = ch.QueueBind(
        q.Name,             // queue name
        ns,                 // routing key
        "dsm_tasks_notify", // exchange
        false,
        nil)
    failOnError(err, "Failed to bind a queue")

    msgs, err := ch.Consume(
        q.Name, // queue
        "",     // consumer
        true,   // auto-ack
        false,  // exclusive
        false,  // no-local
        false,  // no-wait
        nil,    // args
    )
    failOnError(err, "Failed to register a consumer")

    for {
        select {
        case d := <-msgs:
            err = c.WriteMessage(websocket.TextMessage, d.Body)
            if err != nil {
                log.Println("write:", err)
                break
            }
        case <-r.Context().Done():
            log.Println("Disconnect")
            return
        }
    }

}

func failOnError(err error, msg string) {
    if err != nil {
        log.Fatalf("%s: %s", msg, err)
        panic(fmt.Sprintf("%s: %s", msg, err))
    }
}

func main() {
    var err error
    conn, err = amqp.Dial("amqp://guest:guest@localhost:5672/")
    failOnError(err, "Failed to connect to RabbitMQ")
    defer conn.Close()

    http.HandleFunc("/watch", watch)
    log.Fatal(http.ListenAndServe(addr, nil))
}


问:
javascript property checking to prevent application break
I face this issue so many time, dealing with nested object.

```<code>this.props.something.something2
</code>```

Above statement is dangerious, it can took my entire application, simply because I didn't aware of this.props.something can be optional. How to do checking in such case?

答:
Before accessing to 'something2' of this.props.something, you should check the existing of 'something' first. </p>

```<code>if(this.props.something) {
   alert(this.props.something.something2);
 }
</code>```

Body:
I face this issue so many time, dealing with nested object.

this.props.something.something2

Above statement is dangerious, it can took my entire application, simply because I didn't aware of this.props.something can be optional. How to do checking in such case?

Body:
Before accessing to 'something2' of this.props.something, you should check the existing of 'something' first.

if(this.props.something) {
   alert(this.props.something.something2);
 }


问:
Powershell substring of a resultset
I have a string in powershell which is having below data ,

```<code>     $job = "diagnosticCode":223412290,
            "severity":"Error",
            "component":"JobManager_User",
            "source":"User",
            "errorId":"VertexFailedFast",
            "message":"Vertex failed with a fail-fast error",
            "description":"Vertex failure triggered quick job abort".
            "resolution":"",
            "helpLink":""
</code>```

Here i wanted to catch "message" and give it to exception in Catch case, tried with $job[3].ToSTring() but could not work out.
Any help please.

答:
That's not a string, it looks more like a hash table desperate for some help.

To create a hash table you can do it this way:

```<code>$job = @{ diagnosticCode=223412290
        severity="Error"
        component="JobManager_User"
        source="User"
        errorId="VertexFailedFast"
        message="Vertex failed with a fail-fast error"
        description="Vertex failure triggered quick job abort"
        resolution=""
        helpLink="" }
</code>```

Then you can access the message like this:

```<code>$job.message
</code>```

It's unclear, however, how you got that "string", if it was passed to you as is, or if you built it.

Title: Powershell substring of a resultset

Body:
I have a string in powershell which is having below data ,

     $job = "diagnosticCode":223412290,
            "severity":"Error",
            "component":"JobManager_User",
            "source":"User",
            "errorId":"VertexFailedFast",
            "message":"Vertex failed with a fail-fast error",
            "description":"Vertex failure triggered quick job abort".
            "resolution":"",
            "helpLink":""

Here i wanted to catch "message" and give it to exception in Catch case, tried with $job[3].ToSTring() but could not work out.
Any help please.

Body:
That's not a string, it looks more like a hash table desperate for some help.

To create a hash table you can do it this way:

$job = @{ diagnosticCode=223412290
        severity="Error"
        component="JobManager_User"
        source="User"
        errorId="VertexFailedFast"
        message="Vertex failed with a fail-fast error"
        description="Vertex failure triggered quick job abort"
        resolution=""
        helpLink="" }

Then you can access the message like this:

$job.message

It's unclear, however, how you got that "string", if it was passed to you as is, or if you built it.


问:
AWS Cloudwatch logs to ElasticSeacrh via Kinesis Firehose
I am trying to stream AWS cloudwatch logs to Amazon ES using Kinesis Firehose. However, I keep getting the below errors in the ES error log. Any idea?

The data could not be decoded as UTF-8 as in {"attemptsMade":0,"arrivalTimestamp":1494910856979,"errorCode":"InvalidEncodingException","errorMessage":"The data could not be decoded as UTF-8","attemptEndingTimestamp":1494911157268,"rawData":"H4sIAAAAAAAAADWO0QqCMBiFX2XsWiJBQ70LUW8sIYUuQmLpnxvpJttMQnz3ZtrlxzmcQj0RXNBWNMkErmkSKoTfZSrmWQLoV1fBQlWS9ZoLHrNUgFQ5u5a8XvYHrBSfM6rWumdHQpDNjtuM7vr333IPnOtZfbxG4pmjTQ5tegEIK1YvxBlEgraZIPFFtlhgnyzOKmQQqFOzwXM5fj/HcTewAAAA=","esDocumentId":null

答: This is most probably because Cloudwatch logs are compressed. You can use a Firehose transformation lambda blueprint and add code to uncompress the records.</p>


问:
How to stop a Hive metastore service?
How do I stop a Hive metastore service that I started using:

```<code>hive --service metastore
</code>```

without the kill command?

答:
Hive should have been installed with a service script, so that it can be started/shutdown gracefully in the correct order (i.e., after networking is started, database running, etc), so it's likely you can do: sudo service hiveserver2 stop and sudo service hive-metastore stop (e.g., cloudera distro)

As as backup, you can "kill" the parent process using kill {PID} (but not kill -9 {PID}).

Note: never send sigkill (aka -9) signal to any process except as a very last resort. Instead, send the sigterm / sigint (same as ctrl-c, aka "interrupt") signal first, which is what kill sends by default, e.g, ps -ef | egrep -i 'hive', see what the main process is (the parent of other related processes), and terminate the process via kill {PID} e.g., kill 12345. The sigint signal can be caught by the running process and still do a graceful shutdown/clean-up. The sigkill can't be caught, and will almost certainly leave your system in an uncertain state and maybe (or maybe not) it'll have to recover somehow at next startup.

Title: How to stop a Hive metastore service?

Body:
How do I stop a Hive metastore service that I started using:

hive --service metastore

without the kill command?


问:
Convex hull around D3 Force network graphic
I'm trying to add a hull around the D3 network graph that I've build.
My network is based on this JSFiddle (can't share mine because of sensitive data) and basically the end product should be a network with a shade around. I read a lot online and found that a convex hull might be a solution. After trying to implement my data in tutorials like this one http://bl.ocks.org/donaldh/2920551, I must come to the conclusion that my basic D3 knowledge won't be enough to solve this.

Thank you all in advance!

```<code>//Constants for the SVG
var width = 500,
height = 500;

//Set up the colour scale
var color = d3.scale.category20();

//Set up the force layout
var force = d3.layout.force()
.charge(-120)
.linkDistance(30)
.size([width, height]);

//Append a SVG to the body of the html page. Assign this SVG as an object to         svg
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);

//Read the data from the mis element
var mis = document.getElementById('mis').innerHTML;
graph = JSON.parse(mis);

//Creates the graph data structure out of the json data
force.nodes(graph.nodes)
.links(graph.links)
.start();

//Create all the line svgs but without locations yet
var link = svg.selectAll(".link")
.data(graph.links)
.enter().append("line")
.attr("class", "link")
.style("stroke-width", function (d) {
return Math.sqrt(d.value);
});

//Do the same with the circles for the nodes - no
var node = svg.selectAll(".node")
.data(graph.nodes)
.enter().append("circle")
.attr("class", "node")
.attr("r", 8)
.style("fill", function (d) {
return color(d.group);
})
.call(force.drag);

//Now we are giving the SVGs co-ordinates - the force layout is generating the         co-ordinates which this code is using to update the attributes of the SVG elements
force.on("tick", function () {
link.attr("x1", function (d) {
    return d.source.x;
})
    .attr("y1", function (d) {
    return d.source.y;
})
</code>```

答:
By following the basic example here, you should be able to incorporate the minimum convex hull fairly easily. In the basic example, the hull is created here:

```<code>var hull = svg.append("path")
    .attr("class", "hull");
</code>```

And updated here:

```<code>hull.datum(d3.geom.hull(vertices)).attr("d", function(d) { return "M" + d.join("L") + "Z"; });
</code>```

However, I was unable to get the x and y accessors to access d.x and d.y; in the example block above the hull takes an array of points (documentation here, possible solution here). So I've created an example that creates an intermediate variable that contains all the points:

```<code>node.data().forEach(function(d,i) {
    vertices[i] = [d.x,d.y];
})
</code>```

And then updates as in the example above:

```<code>hull.datum(d3.geom.hull(vertices)).attr("d", function(d) {  return "M" + d.join("L") + "Z"; });
</code>```

Here's a block showing it in action based on the example fiddle.

D3v4 doesn't offer much streamlining - there are no accessor functions for d3.polygonHull in v4; I've created a block here for v4.

Body:
I'm trying to add a hull around the D3 network graph that I've build.
My network is based on this JSFiddle (can't share mine because of sensitive data) and basically the end product should be a network with a shade around. I read a lot online and found that a convex hull might be a solution. After trying to implement my data in tutorials like this one http://bl.ocks.org/donaldh/2920551, I must come to the conclusion that my basic D3 knowledge won't be enough to solve this.

Thank you all in advance!

//Constants for the SVG
var width = 500,
height = 500;

//Set up the colour scale
var color = d3.scale.category20();

//Set up the force layout
var force = d3.layout.force()
.charge(-120)
.linkDistance(30)
.size([width, height]);

//Append a SVG to the body of the html page. Assign this SVG as an object to         svg
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);

//Read the data from the mis element
var mis = document.getElementById('mis').innerHTML;
graph = JSON.parse(mis);

//Creates the graph data structure out of the json data
force.nodes(graph.nodes)
.links(graph.links)
.start();

//Create all the line svgs but without locations yet
var link = svg.selectAll(".link")
.data(graph.links)
.enter().append("line")
.attr("class", "link")
.style("stroke-width", function (d) {
return Math.sqrt(d.value);
});

//Do the same with the circles for the nodes - no
var node = svg.selectAll(".node")
.data(graph.nodes)
.enter().append("circle")
.attr("class", "node")
.attr("r", 8)
.style("fill", function (d) {
return color(d.group);
})
.call(force.drag);

//Now we are giving the SVGs co-ordinates - the force layout is generating the         co-ordinates which this code is using to update the attributes of the SVG elements
force.on("tick", function () {
link.attr("x1", function (d) {
    return d.source.x;
})
    .attr("y1", function (d) {
    return d.source.y;
})

Body:
By following the basic example here, you should be able to incorporate the minimum convex hull fairly easily. In the basic example, the hull is created here:

var hull = svg.append("path")
    .attr("class", "hull");

And updated here:

hull.datum(d3.geom.hull(vertices)).attr("d", function(d) { return "M" + d.join("L") + "Z"; });

However, I was unable to get the x and y accessors to access d.x and d.y; in the example block above the hull takes an array of points (documentation here, possible solution here). So I've created an example that creates an intermediate variable that contains all the points:

node.data().forEach(function(d,i) {
    vertices[i] = [d.x,d.y];
})

And then updates as in the example above:

hull.datum(d3.geom.hull(vertices)).attr("d", function(d) {  return "M" + d.join("L") + "Z"; });

Here's a block showing it in action based on the example fiddle.

D3v4 doesn't offer much streamlining - there are no accessor functions for d3.polygonHull in v4; I've created a block here for v4.


问:
how to make a global variable in jquery loop
I want to make  all the keys as variables and want to use outside $.each,instead of using data.company_id, want it to be used as company_id         </p>

```<code>success     : function(data){
             console.log(data);

             $.each(data,function(key,val){
key = val;
                 })
console.log(company_id);
</code>```

答:
```<code>success : function(data){
$(data).each(function(){
console.log(this.company_id)
})
}
</code>```

try somethingb like this

Body:
I want to make  all the keys as variables and want to use outside $.each,instead of using data.company_id, want it to be used as company_id

success     : function(data){
             console.log(data);

             $.each(data,function(key,val){
key = val;
                 })
console.log(company_id);

Body:
success : function(data){
$(data).each(function(){
console.log(this.company_id)
})
}

try somethingb like this


问:
How do you perform address validation?
Is it even possible to perform address (physical, not e-mail) validation?  It seems like the sheer number of address formats, even in the US alone, would make this a fairly difficult task.  On the other hand it seems like a task that would be necessary for several business requirements.</p>

答:
Fixaddress.com service is available that provides following services,

1) Address Validation.

2) Address Correction.

3) Address spell correcting.

4) Correct addresses phonetic mistakes.

Fixaddress.com uses USPS and Tiger data as reference data.

For more detail visit below link,

http://www.fixaddress.com/

OwnerDisplayName: Kevin Pang

ContentLicense: CC BY-SA 4.0

Title: How do you perform address validation?


问:
TYPO3 v6.2.x Tutorials for beginners
I  decided to learning TYPO3 v6.2.x CMS,I installed CMS on local server  but I can't create some basic  template, after long searching in google and here on stackoverflow, I can't find  any useful tutorials or books for beginners.

I need only tutorials  where explained how to create basic template  with TYPO3 CMS v6.x.x or maybe in "github" is some basic start kit with basic template?.

I hope some kind  people suggest me  how  and where to start.
Please don't be lazy, it`s very important for me :).

答: Typo3buddy is more useful tutorials for TYPO3 beginners, In this tutorials where explained in detials how to create basic template with Typo3 CMS.</p>

Title: TYPO3 v6.2.x Tutorials for beginners


问:
How Do I Combine Multiple SQL Queries?
I'm having some trouble figuring out any way to combine two SQL queries into a single one that expresses some greater idea.

For example, let's say that I have query A, and query B. Query A returns the total number of hours worked. Query B returns the total number of hours that were available for workers to work. Each one of these queries returns a single column with a single row.

What I really want, though, is essentially query A over query B. I want to know the percentage of capacity that was worked.

I know how to write query A and B independently, but my problem comes when I try to figure out how to use those prewritten queries to come up with a new SQL query that uses them together. I know that, on a higher level, like say in a report, I could just call both queries and then divide them, but I'd rather encompass it all into a single SQL query.

What I'm looking for is a general idea on how to combine these queries using SQL.

Thanks!

答:
Unconstrained JOIN, Cartesian Product of 1 row by 1 row</p>

```<code>SELECT worked/available AS PercentageCapacity
FROM ( SELECT worked FROM A ),
     ( SELECT available FROM B )
</code>```

ContentLicense: CC BY-SA 2.5

Title: How Do I Combine Multiple SQL Queries?

Body:
Unconstrained JOIN, Cartesian Product of 1 row by 1 row

SELECT worked/available AS PercentageCapacity
FROM ( SELECT worked FROM A ),
     ( SELECT available FROM B )


问:
There is ORDER for HTML tag attributes
I tried the same attributes for input tag but different order, the layout will be difference. I think tag's attributes are no order, can you explain to me?
By the way, class field as below:

```<code>.field {
  font-family: "MS UI Gothic";
  font-size: 12px;
  height: 17px;
  border: 1px solid #ADD566;
  readonly: false;
}
</code>```

Input1 tag:

Input2 tag:

   .field {
   font-family: "MS UI Gothic";
   font-size: 12px;
   height: 17px;
   border: 1px solid #ADD566;
   readonly: false;
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code>Input1 tag:

 <input name="code" size="9" maxlength="6" type="text" onChange="javascript:this.value=this.value.toUpperCase();" style="ime-mode:disabled; text-transform:uppercase"　class="field" value="">

Input2 tag:

 <input name="code" size="9" maxlength="6" type="text" class="field" onChange="javascript:this.value=this.value.toUpperCase();" style="ime-mode:disabled; text-transform:uppercase"　value=""></code>```

答:
There is a special character (U+3000 : IDEOGRAPHIC SPACE) before class, use white space (U+0020 : SPACE [SP]) only.

You can test it here: http://www.babelstone.co.uk/Unicode/whatisit.html

Your code:

.field {
  font-family: "MS UI Gothic";
  font-size: 12px;
  height: 17px;
  border: 1px solid #ADD566 !important;
  readonly: false;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code> Input1 tag:
<input name="code" size="9" maxlength="6" type="text" onChange="javascript:this.value=this.value.toUpperCase();" style="ime-mode:disabled; text-transform:uppercase"　class="field" value="">
Input2 tag:
<input name="code" size="9" maxlength="6" type="text" class="field" onChange="javascript:this.value=this.value.toUpperCase();" style="ime-mode:disabled; text-transform:uppercase" value=""></code>```

After replacing it with white space:

.field {
  font-family: "MS UI Gothic";
  font-size: 12px;
  height: 17px;
  border: 1px solid #ADD566 !important;
  readonly: false;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>Input1 tag:
<input name="code" size="9" maxlength="6" type="text" onChange="javascript:this.value=this.value.toUpperCase();" style="ime-mode:disabled; text-transform:uppercase" class="field" value="">
Input2 tag:
<input name="code" size="9" maxlength="6" type="text" class="field" onChange="javascript:this.value=this.value.toUpperCase();" style="ime-mode:disabled; text-transform:uppercase" value=""></code>```

Title: There is ORDER for HTML tag attributes

Body:
I tried the same attributes for input tag but different order, the layout will be difference. I think tag's attributes are no order, can you explain to me?
By the way, class field as below:

.field {
  font-family: "MS UI Gothic";
  font-size: 12px;
  height: 17px;
  border: 1px solid #ADD566;
  readonly: false;
}

Input1 tag:

Input2 tag:

   .field {
   font-family: "MS UI Gothic";
   font-size: 12px;
   height: 17px;
   border: 1px solid #ADD566;
   readonly: false;
    }

Input1 tag:

 <input name="code" size="9" maxlength="6" type="text" onChange="javascript:this.value=this.value.toUpperCase();" style="ime-mode:disabled; text-transform:uppercase"　class="field" value="">

Input2 tag:

 <input name="code" size="9" maxlength="6" type="text" class="field" onChange="javascript:this.value=this.value.toUpperCase();" style="ime-mode:disabled; text-transform:uppercase"　value="">

Body:
There is a special character (U+3000 : IDEOGRAPHIC SPACE) before class, use white space (U+0020 : SPACE [SP]) only.

You can test it here: http://www.babelstone.co.uk/Unicode/whatisit.html

Your code:

.field {
  font-family: "MS UI Gothic";
  font-size: 12px;
  height: 17px;
  border: 1px solid #ADD566 !important;
  readonly: false;
}

 Input1 tag:
<input name="code" size="9" maxlength="6" type="text" onChange="javascript:this.value=this.value.toUpperCase();" style="ime-mode:disabled; text-transform:uppercase"　class="field" value="">
Input2 tag:
<input name="code" size="9" maxlength="6" type="text" class="field" onChange="javascript:this.value=this.value.toUpperCase();" style="ime-mode:disabled; text-transform:uppercase" value="">

After replacing it with white space:

.field {
  font-family: "MS UI Gothic";
  font-size: 12px;
  height: 17px;
  border: 1px solid #ADD566 !important;
  readonly: false;
}

Input1 tag:
<input name="code" size="9" maxlength="6" type="text" onChange="javascript:this.value=this.value.toUpperCase();" style="ime-mode:disabled; text-transform:uppercase" class="field" value="">
Input2 tag:
<input name="code" size="9" maxlength="6" type="text" class="field" onChange="javascript:this.value=this.value.toUpperCase();" style="ime-mode:disabled; text-transform:uppercase" value="">


问:
Storing random number of foreign keys and values in a single column [Relational Database Design]
I have an entity Product_Cluster which is defined as a collection of key-value pairs, where key is a product attribute and value could either be an attribute value or some wrapper entity.
Example definitions for a cluster of HardDisks:

```<code>Attributes: color | capacity | price
Values :    black | 1TB      | mass

Attributes: color | capacity | price
Values :    black | 1TB      | premium
</code>```

Here values black and 1TB are direct product attributes and values mass and premium are wrapper entities which are defined as follows:

```<code>attribute_id | wrapper_name | definition
price        | mass         | price > 500 and price < 1000
price        | premium      | price > 1000 and brand IN ("A","B","C","D")
</code>```

As you can notice definition of a wrapper could be more complex like

```<code>(exp1 or exp2) and (exp3 or exp4)
</code>```

The above cluster and wrapper definitions result in the following cluster predicates:

```<code>cluster 1: color="black" and capacity="1TB" and  price > 500 and price < 1000
cluster 2: color="black" and capacity="1TB" and  price > 1000 and brand IN ("A","B","C","D")
</code>```

Both wrapper and product_cluster entities will be versioned. So I want to track for a particular product_cluster version what wrapper versions were used for definition.

I was thinking of storing wrapper and product_cluster entities as follows:

```<code>Product_Cluster_Entity
id | cluster_id| version | definition | predicate

Wrapper_Entity
id | attribute_id| wrapper_name | definition | version
</code>```

Here, definition in Product_Cluster_Entity would be a JSON type (MySQL 5.7.18). I am thinking of storing the JSON as an array of objects where each object could have the following structure :-

```<code>attibute_id, value, is_wrapper
</code>```

If is_wrapper == 1 then value is foreign key to wrapper_entity table else it is direct product value.

I would like a few comments regarding the above solution. I couldn't identify any obvious drawbacks of the above solution (DB Design noob :P ) Can we improve this solution?

Thanks in advance.

答:
Those expressions you propose are just strings to MySQL.  No FOREIGN KEYS are possible, no lookups of values, etc.

You could fetch the string expressions into your application and somehow "evaluate" them in the client.  But only if you have already fetched all the possible variables and make sure the expression does not croak and bring down the client.

A database is a repository for data.  It has limited capabilities -- Relations, Aggregations, Sorting, etc.  But not arbitrary string parsing nor arbitrary expression evaluation.

JSON can provide you flexibility (non-relational) data structuring.  But nothing in the direction you are asking about.

Bottom Line:  Don't do it.

Body:
I have an entity Product_Cluster which is defined as a collection of key-value pairs, where key is a product attribute and value could either be an attribute value or some wrapper entity.
Example definitions for a cluster of HardDisks:

Attributes: color | capacity | price
Values :    black | 1TB      | mass

Attributes: color | capacity | price
Values :    black | 1TB      | premium

Here values black and 1TB are direct product attributes and values mass and premium are wrapper entities which are defined as follows:

attribute_id | wrapper_name | definition
price        | mass         | price > 500 and price < 1000
price        | premium      | price > 1000 and brand IN ("A","B","C","D")

As you can notice definition of a wrapper could be more complex like

(exp1 or exp2) and (exp3 or exp4)

The above cluster and wrapper definitions result in the following cluster predicates:

cluster 1: color="black" and capacity="1TB" and  price > 500 and price < 1000
cluster 2: color="black" and capacity="1TB" and  price > 1000 and brand IN ("A","B","C","D")

Both wrapper and product_cluster entities will be versioned. So I want to track for a particular product_cluster version what wrapper versions were used for definition.

I was thinking of storing wrapper and product_cluster entities as follows:

Product_Cluster_Entity
id | cluster_id| version | definition | predicate

Wrapper_Entity
id | attribute_id| wrapper_name | definition | version

Here, definition in Product_Cluster_Entity would be a JSON type (MySQL 5.7.18). I am thinking of storing the JSON as an array of objects where each object could have the following structure :-

attibute_id, value, is_wrapper

If is_wrapper == 1 then value is foreign key to wrapper_entity table else it is direct product value.

I would like a few comments regarding the above solution. I couldn't identify any obvious drawbacks of the above solution (DB Design noob :P ) Can we improve this solution?

Thanks in advance.


问:
Append json_object_arrays in C using jsonc library
I am new to the C language. I need to append two json_object arrays created with the json-c library. This is my code:

```<code>struct json_object *obj1,*array1,*array2,*array3;

obj1 = json_object_new_object();

array1 = json_object_new_array();
json_object_array_add(array1, json_object_new_int(1));
json_object_array_add(array1, json_object_new_int(2));
json_object_array_add(array1, json_object_new_int(3));

json_object_object_add(obj1, "array1", array1);

array2 = json_object_new_array();
json_object_array_add(array2, json_object_new_int(4));
json_object_array_add(array2, json_object_new_int(5));
json_object_array_add(array2, json_object_new_int(6));

json_object_object_add(obj1, "array2", array2);

json_object_object_add(obj1, "array3", array1+array2);
</code>```

But I got the following error:

error: invalid operands to binary + (have ‘struct json_object *’ and ‘struct json_object *’)
         json_object_object_add(obj1, "array3", array1+array2);

Is this not possible? I need output like this:

```<code>{
   "array1:[1,2,3],
   "array2":[4,5,6],
   "array3":[1,2,3,4,5,6]
}
</code>```

Or is it possible to add a normal C integer array to Json, like this

```<code>int32_t smp[100]={0};

smp[0] = 1;
smp[1] = 2;
smp[2] = 3;
smp[3] = 4;
smp[4] = 5;
smp[5] = 6;

json_object_object_add(obj1, "array3", smp);
</code>```

答:
Just remember that above answers do not address the reference counts in json-c.  They add the objects to the destination array, but do not have it take ownership of them. They will likely cause segfaults etc.

The doc: "The reference count will not be incremented."

To ensure that ownership is held by both arrays, you need something like this:

```<code>void json_object_array_append(json_object *dest, json_object *src) {
    int i;
    int src_size = json_object_array_length(src);
    for (i = 0; i < src_size; ++i) {
        json_object *src_item = json_object_array_get_idx(src, i);
        json_object_get(src_item); // increment reference count
        json_object_array_add(dest, src_item); // add to dest array
    }
}

// optional: if you are disposing of the src array, you can then do this:
json_object_put(src);
// after calling the append function.
</code>```

Body:
I am new to the C language. I need to append two json_object arrays created with the json-c library. This is my code:

struct json_object *obj1,*array1,*array2,*array3;

obj1 = json_object_new_object();

array1 = json_object_new_array();
json_object_array_add(array1, json_object_new_int(1));
json_object_array_add(array1, json_object_new_int(2));
json_object_array_add(array1, json_object_new_int(3));

json_object_object_add(obj1, "array1", array1);

array2 = json_object_new_array();
json_object_array_add(array2, json_object_new_int(4));
json_object_array_add(array2, json_object_new_int(5));
json_object_array_add(array2, json_object_new_int(6));

json_object_object_add(obj1, "array2", array2);

json_object_object_add(obj1, "array3", array1+array2);

But I got the following error:

error: invalid operands to binary + (have ‘struct json_object *’ and ‘struct json_object *’)
         json_object_object_add(obj1, "array3", array1+array2);

Is this not possible? I need output like this:

{
   "array1:[1,2,3],
   "array2":[4,5,6],
   "array3":[1,2,3,4,5,6]
}

Or is it possible to add a normal C integer array to Json, like this

int32_t smp[100]={0};

smp[0] = 1;
smp[1] = 2;
smp[2] = 3;
smp[3] = 4;
smp[4] = 5;
smp[5] = 6;

json_object_object_add(obj1, "array3", smp);

Body:
Just remember that above answers do not address the reference counts in json-c.  They add the objects to the destination array, but do not have it take ownership of them. They will likely cause segfaults etc.

The doc: "The reference count will not be incremented."

To ensure that ownership is held by both arrays, you need something like this:

void json_object_array_append(json_object *dest, json_object *src) {
    int i;
    int src_size = json_object_array_length(src);
    for (i = 0; i < src_size; ++i) {
        json_object *src_item = json_object_array_get_idx(src, i);
        json_object_get(src_item); // increment reference count
        json_object_array_add(dest, src_item); // add to dest array
    }
}

// optional: if you are disposing of the src array, you can then do this:
json_object_put(src);
// after calling the append function.


问:
any log search system can help build index locally and grep log in a centralized node?
I read the ELK document and other log grep system,seems all of them need to:

send the logs to a centralized server

centralized server build index

I think those ELK like system cost too much disk and bandwidth.Any implementation works like distributed grep with index？
Log files are distributed in many servers. Log system are implemented on each servers also. centralized server request to each servers for getting the result of grep applied to log data,with the help of index built,this task can be fast,and results are collected to centralized server.

答:
The use case for parsing logs with UNIX powertools (sed, grep, awk etc.) is an age old use case and not really a very efficient one. It also becomes a maintenance nightmare once you change something in your scripts and want to apply it throughout the servers.

Finding patterns across multiple type of log files across multiple applications is challenging and understanding/creating the regular expressions for each is not very easy.

ELK provides good tools for parsing - read up on logstash. It has a fantastic grok filter, wide range of input/output plugins.

From disk usage, infact it would be easier to maintain Elasticsearch data, as you can selective drop indices based on hour/day/month basis (really depends on how you created the index). If your logfile is 10GB for whatever reason with a 6 month old data, and you want to clean it up to keep only last month data, depending upon type of logs, it will be difficult to do that.


问:
C#.NET Getting User Name of machine using Windows Service
I am having difficulty getting the User Name of a person logged into a machine using a windows service.

When using both System.Environment.UserName or WindowsIdentity.GetCurrent().UserName I get NTAUTHORITY\SYSTEM but when this application gets pushed I need to be able to map to the UserID of the person logged in to the system.  The operating system this will be used on will be Windows XP.

Any help would be very appreciated.

答:
For XP only, this advice should apply: Get Window Station for a non-interactive user per process, user or session?

Call OpenWindowStation to get a handle to "winsta0"

Call GetUserObjectInformation to find out who owns winsta0

However, this approach will break when you upgrade your app to Vista, Windows 7 or above, where services run in a different session from interactive logons. You'll need to call the terminal services API to get a list of logged on users, and pick your 'interactive' one.


问:
How do I enable help option in below script?
My program takes command line arguments.

```<code>test.pl --help
</code>```

I want to enable a "help" option in the code. How can I print usage in the code?

```<code>#!/usr/bin/perl
use strict;
use warnings;
use Cwd 'chdir';
use Getopt::Long;
my ($application,$version, $location,$artifactid,$pomversion,$groupid);
GetOptions('application=s' => \$application,

                   'version=s' => \$version,

        'location=s' => \$location,

        'artifactid=s' => \$artifactid,

        'pomversion=s' => \$pomversion,

        'groupid=s' => \$groupid)
 or die "Usage od the script: $!\n";

print "$application, $version, $location, $artifactid, $versionnumber, $groupid \n";

if($application eq 'abc')

{      chdir("/var/ccabc/dst_${application}_${version}/abc/${location}") or die "Cannot Change Directory: $!\n";

print $ENV{PWD};

do_compile();

}
</code>```

I have tried my best..

答:
```<code>#!/usr/bin/env perl
use strict;
use warnings;

use Getopt::Std;
use Cwd 'chdir';

sub usage {
  print <<'HERE';
tbd
HERE
  exit;
}
my %opts = ();

getopts('a:v:l:h', \%opts);
$opts{h} && usage();

my $application = $opts{a};

my $version = $opts{v};

my $location = $opts{l};

print "$application, $version, $location\n";

if ($application eq 'abc') {
    chdir "/viewstore/ccwww/dst_${application}_${version}/abc/${location}";

    print $ENV{PWD};
} ## end if ($application eq 'abc')
</code>```

Body:
My program takes command line arguments.

test.pl --help

I want to enable a "help" option in the code. How can I print usage in the code?

#!/usr/bin/perl
use strict;
use warnings;
use Cwd 'chdir';
use Getopt::Long;
my ($application,$version, $location,$artifactid,$pomversion,$groupid);
GetOptions('application=s' => \$application,

                   'version=s' => \$version,

        'location=s' => \$location,

        'artifactid=s' => \$artifactid,

        'pomversion=s' => \$pomversion,

        'groupid=s' => \$groupid)
 or die "Usage od the script: $!\n";

print "$application, $version, $location, $artifactid, $versionnumber, $groupid \n";

if($application eq 'abc')

{      chdir("/var/ccabc/dst_${application}_${version}/abc/${location}") or die "Cannot Change Directory: $!\n";

print $ENV{PWD};

do_compile();

}

I have tried my best..


问:
cassandra installation on windows 10 , unable to connect to server
i have installed "datastax-ddc-64bit-3.9.0.msi" on windows 10, when i run Cassandra CQL Shell i have got this error.

Connection error: ('Unable to connect to any servers', {'127.0.0.1': error(10061, "Tried connecting to [('127.0.0.1', 9042)]. Last error: No connection could be made because the target machine actively refused it")})

答:
What is the rpc_address configured? And connect CQL with that hostname/IP. E.g.

```<code>cqlsh <rpc_address> <native_transport_port>
</code>```

Check the above values in your Cassandra.yaml file.

Body:
What is the rpc_address configured? And connect CQL with that hostname/IP. E.g.

cqlsh <rpc_address> <native_transport_port>

Check the above values in your Cassandra.yaml file.


问:
Queries in tuple relational calculus re employee department and minimum & maximum salary?
I have to solve the queries using tuple relational calculus and I just want to know if I did them correctly. I'm using this database:

```<code>EMPLOYEE: fname , minit , lname, ssn , bdate , address , sex , salary , superssn , dno
DEPARTMENT: dname dnumber , mgrssn , mgrstartdate
DEPT_LOCATIONS: dnumber , dlocation
PROJECT: pname , pnumber , plocation , dnum
WORKS_ON: essn , pno , hours
DEPENDENT: essn , dependent_name , sex , bdate , relationship
</code>```

Q1: Retrieve the names of employees who make at least $10,000 more than the employee who is paid the least in the Company.

```<code>{e.Lname, e.Fname | EMPLOYEE(e) AND (∃b) (EMPLOYEE (b) AND e.Salary >=
10000 + b.Salary AND NOT (∃a) (EMPLOYEE(a) AND b.Salary > a.Salary))}
</code>```

Q2: Retrieve the names of all employees who work in the department that has the employee with the highest salary among all employees.

```<code>{e.Lname, e.Fname | EMPLOYEE(e) AND (∃b) (EMPLOYEE (b) AND e.dno =
b.dno AND NOT(∃a)(EMPLOYEE(a) AND a.Salary > b.Salary))}
</code>```

Any help will be much appreciated.

edit: Assume that only one employee can have the highest/lowest salary.

答: Guessing at the meaning of base relations, the natural language agrees with the calculus. Nb technically the answer can't be found if you don't give the meanings (predicates) for the base tables. As to whether you got those right answers via correct reasoning, you'd have to give yours. PS The questions are flawed if there can be multiple employees with highest or lowest salary.

Body:
I have to solve the queries using tuple relational calculus and I just want to know if I did them correctly. I'm using this database:

EMPLOYEE: fname , minit , lname, ssn , bdate , address , sex , salary , superssn , dno
DEPARTMENT: dname dnumber , mgrssn , mgrstartdate
DEPT_LOCATIONS: dnumber , dlocation
PROJECT: pname , pnumber , plocation , dnum
WORKS_ON: essn , pno , hours
DEPENDENT: essn , dependent_name , sex , bdate , relationship

Q1: Retrieve the names of employees who make at least $10,000 more than the employee who is paid the least in the Company.

{e.Lname, e.Fname | EMPLOYEE(e) AND (∃b) (EMPLOYEE (b) AND e.Salary >=
10000 + b.Salary AND NOT (∃a) (EMPLOYEE(a) AND b.Salary > a.Salary))}

Q2: Retrieve the names of all employees who work in the department that has the employee with the highest salary among all employees.

{e.Lname, e.Fname | EMPLOYEE(e) AND (∃b) (EMPLOYEE (b) AND e.dno =
b.dno AND NOT(∃a)(EMPLOYEE(a) AND a.Salary > b.Salary))}

Any help will be much appreciated.

edit: Assume that only one employee can have the highest/lowest salary.


问:
How to avoid ignorance of dependencies in android?
I just imported some project into my Android Studio and was testing the application on latest version of android SDK i.e. v7 but when I'm trying to test the application on old devices, the application is not working, as application consist of authentication activity which is working successfully on v7 but not on old android devices.

org.apache.httpcomponents:httpmime:4.5.1'

I noticed that above dependency is getting ignored. I know that after API 23 this dependency is depreciated. Is there any method to avoid ignorance by gradle ? As my whole application is based upon http components.

Gradle file of application is:

Code Updated

```<code>    apply plugin: 'com.android.application'

android {

    compileSdkVersion 23
    buildToolsVersion "25.0.0"
    useLibrary 'org.apache.http.legacy'

    defaultConfig {
        applicationId "com.creative.nerdzprocollegemanager"
        minSdkVersion 14
        targetSdkVersion 21
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        debug {
            debuggable true
        }
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    sourceSets { main { res.srcDirs = ['src/main/res', 'src/main/res/values-fr'] } }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:21.0.3'
    compile 'org.apache.httpcomponents:httpmime:4.5.1'
    compile group: 'org.apache.httpcomponents' , name: 'httpclient-android' , version: '4.3.5.1'

}
</code>```

The Application function is :

```<code>@Override
 protected String doInBackground(Void...params) {
  byte[] result;
  String resultString = "";
  HttpClient httpClient = new DefaultHttpClient();
  HttpPost httpPost = new HttpPost(url);
  try {
   ArrayList < NameValuePair > nameValuePairs = new ArrayList < > ();
   for (String key: postParams.keySet()) {
    nameValuePairs.add(new BasicNameValuePair(key, postParams.get(key)));
   }
   httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
   HttpResponse response = httpClient.execute(httpPost);
   StatusLine statusLine = response.getStatusLine();

   if (statusLine.getStatusCode() == HttpURLConnection.HTTP_OK) {
    errorMessage = "ok";
    result = EntityUtils.toByteArray(response.getEntity());
    resultString = new String(result, "UTF-8");
   }
  } catch (UnsupportedEncodingException e) {
   errorMessage = "Encoding is not supported";
  } catch (Exception e) {
   errorMessage = "An error occurred";
  }
  return resultString;
 }

 @Override
 protected void onPostExecute(String s) {
  if (errorMessage.equals("ok")) {
   sourceActivity.requestFinished(s, requestTag);
  } else
   sourceActivity.requestFailed(errorMessage, requestTag);
 }
 }
</code>```

Is there any method to avoid ignorance of dependencies by gradle ? Or I should use some alternative to httpclient? Please suggest me some solution as I don't have much experience with android.

答:
Add this line in your gradle file in side android

```<code>android{
...
useLibrary 'org.apache.http.legacy'
...
}
</code>```

Edit:
Also replace

```<code>compile group: 'cz.msebera.android' , name: 'httpclient', version:
       '4.4.1.1'
</code>```

with

```<code>compile group: 'org.apache.httpcomponents' , name: 'httpclient-android' , version: '4.3.5.1'
</code>```

or

```<code>compile 'org.apache.httpcomponents:httpclient:4.5.1'
</code>```

Body:
I just imported some project into my Android Studio and was testing the application on latest version of android SDK i.e. v7 but when I'm trying to test the application on old devices, the application is not working, as application consist of authentication activity which is working successfully on v7 but not on old android devices.

org.apache.httpcomponents:httpmime:4.5.1'

I noticed that above dependency is getting ignored. I know that after API 23 this dependency is depreciated. Is there any method to avoid ignorance by gradle ? As my whole application is based upon http components.

Gradle file of application is:

Code Updated

    apply plugin: 'com.android.application'

android {

    compileSdkVersion 23
    buildToolsVersion "25.0.0"
    useLibrary 'org.apache.http.legacy'

    defaultConfig {
        applicationId "com.creative.nerdzprocollegemanager"
        minSdkVersion 14
        targetSdkVersion 21
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        debug {
            debuggable true
        }
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    sourceSets { main { res.srcDirs = ['src/main/res', 'src/main/res/values-fr'] } }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:21.0.3'
    compile 'org.apache.httpcomponents:httpmime:4.5.1'
    compile group: 'org.apache.httpcomponents' , name: 'httpclient-android' , version: '4.3.5.1'

}

The Application function is :

@Override
 protected String doInBackground(Void...params) {
  byte[] result;
  String resultString = "";
  HttpClient httpClient = new DefaultHttpClient();
  HttpPost httpPost = new HttpPost(url);
  try {
   ArrayList < NameValuePair > nameValuePairs = new ArrayList < > ();
   for (String key: postParams.keySet()) {
    nameValuePairs.add(new BasicNameValuePair(key, postParams.get(key)));
   }
   httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
   HttpResponse response = httpClient.execute(httpPost);
   StatusLine statusLine = response.getStatusLine();

   if (statusLine.getStatusCode() == HttpURLConnection.HTTP_OK) {
    errorMessage = "ok";
    result = EntityUtils.toByteArray(response.getEntity());
    resultString = new String(result, "UTF-8");
   }
  } catch (UnsupportedEncodingException e) {
   errorMessage = "Encoding is not supported";
  } catch (Exception e) {
   errorMessage = "An error occurred";
  }
  return resultString;
 }

 @Override
 protected void onPostExecute(String s) {
  if (errorMessage.equals("ok")) {
   sourceActivity.requestFinished(s, requestTag);
  } else
   sourceActivity.requestFailed(errorMessage, requestTag);
 }
 }

Is there any method to avoid ignorance of dependencies by gradle ? Or I should use some alternative to httpclient? Please suggest me some solution as I don't have much experience with android.

Body:
Add this line in your gradle file in side android

android{
...
useLibrary 'org.apache.http.legacy'
...
}

Edit:
Also replace

compile group: 'cz.msebera.android' , name: 'httpclient', version:
       '4.4.1.1'

with

compile group: 'org.apache.httpcomponents' , name: 'httpclient-android' , version: '4.3.5.1'

or

compile 'org.apache.httpcomponents:httpclient:4.5.1'


问:
Where does git keep the local repository stashed file?
I would like to sym link to the directory containing the stashed files.

If there are multiple stash items in the stash list of the local repository then I would like to zip them all from a sym link.

答:
The stash is actually stored as a commit sha and can be viewed in

```<code>./logs/refs/stash
./refs/stash
</code>```

Then you could git show the commit sha or append --name-status to it to view the list of files in stash.

Body:
The stash is actually stored as a commit sha and can be viewed in

./logs/refs/stash
./refs/stash

Then you could git show the commit sha or append --name-status to it to view the list of files in stash.


问:
How to redirect in after executes the query php
Here is my code:

```<code>    $id = $_GET['id'];
$data = $_POST['name'];
$data1 = $_POST['id'];
$c = 0;

foreach ($data1 as $key => $value) {
    $sql = "UPDATE ".$table_comp." SET score = " . $data[$c][$value] . " where id = " . $value .";" ;
    mysqli_query($connect,$sql);
    $c++;
}
header('Location: http://www.csscorecard.com/admin/?id=$id');
</code>```

I have problem in my redirect there is an error:

Warning: Cannot modify header information - headers already sent by (output started at /home/csscorecard/public_html/wp-content/themes/twentyseventeen/ajax/submit.php:3) in /home/csscorecard/public_html/wp-content/themes/twentyseventeen/ajax/submit.php on line 54

答:
use javascript instead of headers.

you can use this code to redirect

```<code><?php

echo "<script>window.location.href = 'http://www.csscorecard.com/admin/?id=".$id."'</script>";

?>
</code>```

Body:
Here is my code:

    $id = $_GET['id'];
$data = $_POST['name'];
$data1 = $_POST['id'];
$c = 0;

foreach ($data1 as $key => $value) {
    $sql = "UPDATE ".$table_comp." SET score = " . $data[$c][$value] . " where id = " . $value .";" ;
    mysqli_query($connect,$sql);
    $c++;
}
header('Location: http://www.csscorecard.com/admin/?id=$id');

I have problem in my redirect there is an error:

Warning: Cannot modify header information - headers already sent by (output started at /home/csscorecard/public_html/wp-content/themes/twentyseventeen/ajax/submit.php:3) in /home/csscorecard/public_html/wp-content/themes/twentyseventeen/ajax/submit.php on line 54

Body:
use javascript instead of headers.

you can use this code to redirect

<?php

echo "<script>window.location.href = 'http://www.csscorecard.com/admin/?id=".$id."'</script>";

?>


问:
SwipeListener on ListView and ClickListener on ListView's items
This is my old question. However this time I have provided my code as well.

I have a ListView with different types of rows. The row may contain text, image, video or something else. If I click on ImageView (inside the row) I will go to another activity to show the image in full screen, If I click on Video (inside the row) I will go to another activity to play he video.

I have implemented right to left swipe listener on my ListView. If I start the ListView swipe from an empty space in ListView, the swipe works (first and second row in below image). However if I start the ListView swipe from the ListView row's item, then the swipe doesn't work (third and fourth row in below image). If I remove the click events from ImageView and Video then the swipe works even if I start the swipe from the ListView row's item i.e. in this case the swipe works on whole ListView, no matter on which row I do the swipe.

How can I get rid on this problem? I think this can be achieved if I disable all the click events on the all the items inside ListView. How can do so? Is there any other way?

I want both swipe on ListView and click on ListView's item.

SwipeDetector.java - For detecting swipes on the ListView

```<code>public class SwipeDetector implements View.OnTouchListener {

private SwipeListener swipeListener;
private ListView mListView;
private int hundred;
private boolean motionInterceptDisallowed = false;

public static enum Action {
    LR, // Left to right
    RL, // Right to left
    TB, // Top to bottom
    BT, // Bottom to top
    None // Action not found
}

private static final int HORIZONTAL_MIN_DISTANCE = 30; // The minimum
// distance for
// horizontal swipe
private static final int VERTICAL_MIN_DISTANCE = 80; // The minimum distance
// for vertical
// swipe
private float downX, downY, upX, upY; // Coordinates
private Action mSwipeDetected = Action.None; // Last action

public SwipeDetector(Context context, ListView listView) {
    hundred = (int) context.getResources().getDimension(R.dimen.hundred);
    mListView = listView;
}

public boolean swipeDetected() {
    return mSwipeDetected != Action.None;
}

public Action getAction() {
    return mSwipeDetected;
}

/**
 * Swipe detection
 */@Override
public boolean onTouch(View v, MotionEvent event) {
    switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN:
        {
            downX = event.getX();
            downY = event.getY();
            mSwipeDetected = Action.None;
            return false; // allow other events like Click to be processed
        }
        case MotionEvent.ACTION_MOVE:
        {
            upX = event.getX();
            upY = event.getY();

            float deltaX = downX - upX;
            float deltaY = downY - upY;

            float absX = Math.abs(deltaX);
            float absY = Math.abs(deltaY);

            if((absX >= (3 * absY)) && absX > HORIZONTAL_MIN_DISTANCE && mListView != null && !motionInterceptDisallowed) {
                mListView.requestDisallowInterceptTouchEvent(true);
                motionInterceptDisallowed = true;
            }

            if((absX >= (3 * absY)) && absX <= hundred) {
                if (deltaX > 0) {
                    mSwipeDetected = Action.RL;
                    swipeListener.onSwipe(MotionEvent.ACTION_MOVE, Action.RL, absX);
                }
            }

            return false;
        }
        case MotionEvent.ACTION_UP:
            swipeListener.onSwipe(MotionEvent.ACTION_UP, Action.BT, 0);
            if (mListView != null) {
                mListView.requestDisallowInterceptTouchEvent(false);
                motionInterceptDisallowed = false;
            }
            return false;
        case MotionEvent.ACTION_CANCEL:
            return true;
    }
    return false;
}

/**
 * Set chat send listener
 * @param listener
 */
public void setSwipeListener(SwipeListener listener) {
    swipeListener = listener;
}

public interface SwipeListener {
    void onSwipe(int event, Action action, float x);
}

}
</code>```

This is how I am setting SwipeDetector on my ListView

```<code>final SwipeDetector swipeDetector = new SwipeDetector(SwipeActivity.this, mListView);
    swipeDetector.setSwipeListener(mSwipeListener);
    mListView.setOnTouchListener(swipeDetector);
</code>```

My Activity implements SwipeDetector.SwipeListener

Below is overridden onSwipe() method

```<code>@Override
public void onSwipe(int event, SwipeDetector.Action action, float x) {
    switch (event) {
            case MotionEvent.ACTION_MOVE:
                System.out.println("list move");
                break;
            case MotionEvent.ACTION_UP:
                System.out.println("list up");
                break;
        }
}
</code>```

In my adapter I am setting onClickListener() on my TextView, ImageView and VideoView

```<code>holder.mTextView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            System.out.println("item textview click");
        }
    });

holder.mImageView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            System.out.println("item imageview click");
        }
    });

holder.mVideoView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            System.out.println("item videoview click");
        }
    });
</code>```

When I start the swipe from the empty area of ListView, the ListView's swipe listener captures it. However, when I start the swipe from the TextView/ImageView/VideoView then that View's onClickListener is fired instead of parent's (ListView's) onTouchListener().

How can I implement the same? I want that when I click on ListView's item then that item's onClick should get fired and when I swipe on the ListView's item then ListView's onSwipe should get fired.

答:
I know this is an old question but still for future search here is a better solution:

Try to use RecyclerView instead of ListView and add OnItemTouchListener of recyclerview's item.

```<code>recyclerView.addOnItemTouchListener(
            new RecyclerItemClickListener(
                    this,
                    new RecyclerItemClickListener.OnItemClickListener() {
                        @Override
                        public void onItemClick(View view, int position) {
                            // Your code here for item on click event...
                        }
                    },
                    runnableSwipeLeftToRight,
                    runnableSwipeRightToLeft)
    );
</code>```

Here are two methods which will execute on appropriate swipes:

```<code>Runnable runnableSwipeRightToLeft = new Runnable() {
    public void run() {
        // Your Code here...
    }
};

Runnable runnableSwipeLeftToRight = new Runnable() {
    public void run() {
        // Your code here...
    }
};
</code>```

And here is class code for touch and swipe detection:

```<code>import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;

public class RecyclerItemClickListener implements RecyclerView.OnItemTouchListener, RecyclerView.OnLongClickListener {

private OnItemClickListener mListener;
GestureDetector gestureDetector;
Runnable runnableSwipeLeftToRight, runnableSwipeRightToLeft;

private static final String TAG = "RecyclerItemClickListen";
private static final int SWIPE_MIN_DISTANCE = 120;
private static final int SWIPE_MAX_OFF_PATH = 200;
private static final int SWIPE_THRESHOLD_VELOCITY = 200;

@Override
public boolean onLongClick(View view) {
    return false;
}

public interface OnItemClickListener {
    public void onItemClick(View view, int position);
}

GestureDetector mGestureDetector;

public RecyclerItemClickListener(Context context, OnItemClickListener listener, Runnable runnableSwipeLeftToRight, Runnable runnableSwipeRightToLeft) {
    this.mListener = listener;
    this.runnableSwipeLeftToRight = runnableSwipeLeftToRight;
    this.runnableSwipeRightToLeft = runnableSwipeRightToLeft;

    mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
        @Override
        public boolean onSingleTapUp(MotionEvent e) {
            return true;
        }
    });

    gestureDetector = new GestureDetector(context, new GestureDetector.OnGestureListener() {
        @Override
        public boolean onDown(MotionEvent motionEvent) {
            return false;
        }

        @Override
        public void onShowPress(MotionEvent motionEvent) { }

        @Override
        public boolean onSingleTapUp(MotionEvent motionEvent) {
            return false;
        }

        @Override
        public boolean onScroll(MotionEvent motionEvent, MotionEvent motionEvent1, float v, float v1) { return false; }

        @Override
        public void onLongPress(MotionEvent motionEvent) { }

        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float v1) {
            try {
                float diffAbs = Math.abs(e1.getY() - e2.getY());
                float diff = e1.getX() - e2.getX();

                if (diffAbs > SWIPE_MAX_OFF_PATH) {
                    return false;
                }

                // Left swipe
                if (diff > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
                    onLeftSwipe();

                    // Right swipe
                } else if (-diff > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
                    onRightSwipe();
                }
            } catch (Exception e) {
                Log.e("YourActivity", "Error on gestures");
            }
            return false;
        }
    });
}

private void onLeftSwipe() {
    Log.d(TAG, "onLeftSwipe: ");
    runnableSwipeRightToLeft.run();
}

private void onRightSwipe() {
    Log.d(TAG, "onRightSwipe:");
    runnableSwipeLeftToRight.run();
}

@Override
public boolean onInterceptTouchEvent(RecyclerView view, MotionEvent e) {
    View childView = view.findChildViewUnder(e.getX(), e.getY());
    if (childView != null && mListener != null && mGestureDetector.onTouchEvent(e)) {
        mListener.onItemClick(childView, view.getChildAdapterPosition(childView));
    }
    return gestureDetector.onTouchEvent(e);
}

@Override
public void onTouchEvent(RecyclerView view, MotionEvent motionEvent) {
}

@Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {

}

}
</code>```

Hope this will help you.

Body:
This is my old question. However this time I have provided my code as well.

I have a ListView with different types of rows. The row may contain text, image, video or something else. If I click on ImageView (inside the row) I will go to another activity to show the image in full screen, If I click on Video (inside the row) I will go to another activity to play he video.

I have implemented right to left swipe listener on my ListView. If I start the ListView swipe from an empty space in ListView, the swipe works (first and second row in below image). However if I start the ListView swipe from the ListView row's item, then the swipe doesn't work (third and fourth row in below image). If I remove the click events from ImageView and Video then the swipe works even if I start the swipe from the ListView row's item i.e. in this case the swipe works on whole ListView, no matter on which row I do the swipe.

How can I get rid on this problem? I think this can be achieved if I disable all the click events on the all the items inside ListView. How can do so? Is there any other way?

I want both swipe on ListView and click on ListView's item.

SwipeDetector.java - For detecting swipes on the ListView

public class SwipeDetector implements View.OnTouchListener {

private SwipeListener swipeListener;
private ListView mListView;
private int hundred;
private boolean motionInterceptDisallowed = false;

public static enum Action {
    LR, // Left to right
    RL, // Right to left
    TB, // Top to bottom
    BT, // Bottom to top
    None // Action not found
}

private static final int HORIZONTAL_MIN_DISTANCE = 30; // The minimum
// distance for
// horizontal swipe
private static final int VERTICAL_MIN_DISTANCE = 80; // The minimum distance
// for vertical
// swipe
private float downX, downY, upX, upY; // Coordinates
private Action mSwipeDetected = Action.None; // Last action

public SwipeDetector(Context context, ListView listView) {
    hundred = (int) context.getResources().getDimension(R.dimen.hundred);
    mListView = listView;
}

public boolean swipeDetected() {
    return mSwipeDetected != Action.None;
}

public Action getAction() {
    return mSwipeDetected;
}

/**
 * Swipe detection
 */@Override
public boolean onTouch(View v, MotionEvent event) {
    switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN:
        {
            downX = event.getX();
            downY = event.getY();
            mSwipeDetected = Action.None;
            return false; // allow other events like Click to be processed
        }
        case MotionEvent.ACTION_MOVE:
        {
            upX = event.getX();
            upY = event.getY();

            float deltaX = downX - upX;
            float deltaY = downY - upY;

            float absX = Math.abs(deltaX);
            float absY = Math.abs(deltaY);

            if((absX >= (3 * absY)) && absX > HORIZONTAL_MIN_DISTANCE && mListView != null && !motionInterceptDisallowed) {
                mListView.requestDisallowInterceptTouchEvent(true);
                motionInterceptDisallowed = true;
            }

            if((absX >= (3 * absY)) && absX <= hundred) {
                if (deltaX > 0) {
                    mSwipeDetected = Action.RL;
                    swipeListener.onSwipe(MotionEvent.ACTION_MOVE, Action.RL, absX);
                }
            }

            return false;
        }
        case MotionEvent.ACTION_UP:
            swipeListener.onSwipe(MotionEvent.ACTION_UP, Action.BT, 0);
            if (mListView != null) {
                mListView.requestDisallowInterceptTouchEvent(false);
                motionInterceptDisallowed = false;
            }
            return false;
        case MotionEvent.ACTION_CANCEL:
            return true;
    }
    return false;
}

/**
 * Set chat send listener
 * @param listener
 */
public void setSwipeListener(SwipeListener listener) {
    swipeListener = listener;
}

public interface SwipeListener {
    void onSwipe(int event, Action action, float x);
}

}

This is how I am setting SwipeDetector on my ListView

final SwipeDetector swipeDetector = new SwipeDetector(SwipeActivity.this, mListView);
    swipeDetector.setSwipeListener(mSwipeListener);
    mListView.setOnTouchListener(swipeDetector);

My Activity implements SwipeDetector.SwipeListener

Below is overridden onSwipe() method

@Override
public void onSwipe(int event, SwipeDetector.Action action, float x) {
    switch (event) {
            case MotionEvent.ACTION_MOVE:
                System.out.println("list move");
                break;
            case MotionEvent.ACTION_UP:
                System.out.println("list up");
                break;
        }
}

In my adapter I am setting onClickListener() on my TextView, ImageView and VideoView

holder.mTextView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            System.out.println("item textview click");
        }
    });

holder.mImageView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            System.out.println("item imageview click");
        }
    });

holder.mVideoView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            System.out.println("item videoview click");
        }
    });

When I start the swipe from the empty area of ListView, the ListView's swipe listener captures it. However, when I start the swipe from the TextView/ImageView/VideoView then that View's onClickListener is fired instead of parent's (ListView's) onTouchListener().

How can I implement the same? I want that when I click on ListView's item then that item's onClick should get fired and when I swipe on the ListView's item then ListView's onSwipe should get fired.

Body:
I know this is an old question but still for future search here is a better solution:

Try to use RecyclerView instead of ListView and add OnItemTouchListener of recyclerview's item.

recyclerView.addOnItemTouchListener(
            new RecyclerItemClickListener(
                    this,
                    new RecyclerItemClickListener.OnItemClickListener() {
                        @Override
                        public void onItemClick(View view, int position) {
                            // Your code here for item on click event...
                        }
                    },
                    runnableSwipeLeftToRight,
                    runnableSwipeRightToLeft)
    );

Here are two methods which will execute on appropriate swipes:

Runnable runnableSwipeRightToLeft = new Runnable() {
    public void run() {
        // Your Code here...
    }
};

Runnable runnableSwipeLeftToRight = new Runnable() {
    public void run() {
        // Your code here...
    }
};

And here is class code for touch and swipe detection:

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;

public class RecyclerItemClickListener implements RecyclerView.OnItemTouchListener, RecyclerView.OnLongClickListener {

private OnItemClickListener mListener;
GestureDetector gestureDetector;
Runnable runnableSwipeLeftToRight, runnableSwipeRightToLeft;

private static final String TAG = "RecyclerItemClickListen";
private static final int SWIPE_MIN_DISTANCE = 120;
private static final int SWIPE_MAX_OFF_PATH = 200;
private static final int SWIPE_THRESHOLD_VELOCITY = 200;

@Override
public boolean onLongClick(View view) {
    return false;
}

public interface OnItemClickListener {
    public void onItemClick(View view, int position);
}

GestureDetector mGestureDetector;

public RecyclerItemClickListener(Context context, OnItemClickListener listener, Runnable runnableSwipeLeftToRight, Runnable runnableSwipeRightToLeft) {
    this.mListener = listener;
    this.runnableSwipeLeftToRight = runnableSwipeLeftToRight;
    this.runnableSwipeRightToLeft = runnableSwipeRightToLeft;

    mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
        @Override
        public boolean onSingleTapUp(MotionEvent e) {
            return true;
        }
    });

    gestureDetector = new GestureDetector(context, new GestureDetector.OnGestureListener() {
        @Override
        public boolean onDown(MotionEvent motionEvent) {
            return false;
        }

        @Override
        public void onShowPress(MotionEvent motionEvent) { }

        @Override
        public boolean onSingleTapUp(MotionEvent motionEvent) {
            return false;
        }

        @Override
        public boolean onScroll(MotionEvent motionEvent, MotionEvent motionEvent1, float v, float v1) { return false; }

        @Override
        public void onLongPress(MotionEvent motionEvent) { }

        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float v1) {
            try {
                float diffAbs = Math.abs(e1.getY() - e2.getY());
                float diff = e1.getX() - e2.getX();

                if (diffAbs > SWIPE_MAX_OFF_PATH) {
                    return false;
                }

                // Left swipe
                if (diff > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
                    onLeftSwipe();

                    // Right swipe
                } else if (-diff > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
                    onRightSwipe();
                }
            } catch (Exception e) {
                Log.e("YourActivity", "Error on gestures");
            }
            return false;
        }
    });
}

private void onLeftSwipe() {
    Log.d(TAG, "onLeftSwipe: ");
    runnableSwipeRightToLeft.run();
}

private void onRightSwipe() {
    Log.d(TAG, "onRightSwipe:");
    runnableSwipeLeftToRight.run();
}

@Override
public boolean onInterceptTouchEvent(RecyclerView view, MotionEvent e) {
    View childView = view.findChildViewUnder(e.getX(), e.getY());
    if (childView != null && mListener != null && mGestureDetector.onTouchEvent(e)) {
        mListener.onItemClick(childView, view.getChildAdapterPosition(childView));
    }
    return gestureDetector.onTouchEvent(e);
}

@Override
public void onTouchEvent(RecyclerView view, MotionEvent motionEvent) {
}

@Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {

}

}

Hope this will help you.


问:
How to store username entered into database table
I am trying to store username entered during login in the table Login Details. I am keeping track of users trying to login into the application. My code crashes at conn.Open. Please help me with this. Thanks in advance.

Here is the code I have written in Homecontroller:

```<code>public  ActionResult Login(LoginViewModel model, string returnUrl)
        {

            if (!ModelState.IsValid)
            {
                return View(model);
            }
            var wwid = ActiveDirectoryUserHelper.returnWWid(model.UserName, model.UserName.Substring(model.UserName.IndexOf("\\")+1), model.Password);
            if(wwid==null)
            {
                ModelState.AddModelError("", "Invalid login attempt.");
                return View(model);
            }
            else
            {
                Session["UserId"] = model.UserName.Substring(model.UserName.IndexOf("\\") + 1);
                Session["UserPassword"] = model.Password;
                ViewBag.userId = Crypto.EncryptData(model.UserName.Substring(model.UserName.IndexOf("\\") + 1));
                ViewBag.pwd = Crypto.EncryptData(model.Password);
            }

            SqlConnection conn = new SqlConnection(@"data source = XYZ,1433;initial catalog=Application;integrated security=True");

            string sql = "INSERT INTO LoginDetails (username) values (@username)";
            conn.Open();
            SqlCommand cmd = new SqlCommand(sql, conn);
            cmd.Parameters.Add("@username", System.Data.SqlDbType.VarChar, 50).Value = model.UserName;
            //cmd.Parameters["@username"].Value = model.UserName;
            cmd.ExecuteNonQuery();

            return View("Management");

        }
</code>```

答:
Put this at the top of your code:

using System.Web.Configuration;
Put this in Web.Config:

```<code> <connectionStrings >
<add
     name="myConnectionString"
     connectionString="Server=myServerAddress;Database=myDataBase;User ID=myUsername;Password=myPassword;Trusted_Connection=False;"
     providerName="System.Data.SqlClient"/>
</connectionStrings>

and where you want to setup the connection variable:

SqlConnection con = new SqlConnection(
WebConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString);
</code>```

Body:
I am trying to store username entered during login in the table Login Details. I am keeping track of users trying to login into the application. My code crashes at conn.Open. Please help me with this. Thanks in advance.

Here is the code I have written in Homecontroller:

public  ActionResult Login(LoginViewModel model, string returnUrl)
        {

            if (!ModelState.IsValid)
            {
                return View(model);
            }
            var wwid = ActiveDirectoryUserHelper.returnWWid(model.UserName, model.UserName.Substring(model.UserName.IndexOf("\\")+1), model.Password);
            if(wwid==null)
            {
                ModelState.AddModelError("", "Invalid login attempt.");
                return View(model);
            }
            else
            {
                Session["UserId"] = model.UserName.Substring(model.UserName.IndexOf("\\") + 1);
                Session["UserPassword"] = model.Password;
                ViewBag.userId = Crypto.EncryptData(model.UserName.Substring(model.UserName.IndexOf("\\") + 1));
                ViewBag.pwd = Crypto.EncryptData(model.Password);
            }

            SqlConnection conn = new SqlConnection(@"data source = XYZ,1433;initial catalog=Application;integrated security=True");

            string sql = "INSERT INTO LoginDetails (username) values (@username)";
            conn.Open();
            SqlCommand cmd = new SqlCommand(sql, conn);
            cmd.Parameters.Add("@username", System.Data.SqlDbType.VarChar, 50).Value = model.UserName;
            //cmd.Parameters["@username"].Value = model.UserName;
            cmd.ExecuteNonQuery();

            return View("Management");

        }

Body:
Put this at the top of your code:

using System.Web.Configuration;
Put this in Web.Config:

 <connectionStrings >
<add
     name="myConnectionString"
     connectionString="Server=myServerAddress;Database=myDataBase;User ID=myUsername;Password=myPassword;Trusted_Connection=False;"
     providerName="System.Data.SqlClient"/>
</connectionStrings>

and where you want to setup the connection variable:

SqlConnection con = new SqlConnection(
WebConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString);


问:
React Router not working correctly
I am new to react and have no idea why this wouldnt be working.

My router code is here:

```<code>import React from 'react';
import { Route, IndexRoute } from 'react-router';

import App from './components/App';
import HomePage from './components/home/HomePage';

export default (
  <Route path="/" component={App}>
    <IndexRoute component={HomePage} />
    <Route path="example" component={HomePage} />
  </Route>
);
</code>```

So what happens with this code is:

localhost/ displays fine

localhost/example does not display

localhost/example link from the header on the homepage displays, but pressing refresh does not

Thanks for any help, I appreciate it!

here is my webpack config:

```<code>const webpack = require('webpack');
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  context: path.join(__dirname, "/client"),
  entry: [
    'webpack-dev-server/client?http://127.0.0.0:5000/',
    'webpack/hot/only-dev-server',
    'react-hot-loader/patch',
    './src/index.js'
  ],
  output: {
    path: path.join(__dirname, "/client/dist"),
    filename: '[name].js',
    publicPath: '/'
  },
  resolve: {
    extensions: ['.js', '.jsx', '.json']
  },
  devServer: {
    historyApiFallback: true
  },
  module: {
    rules: [
      {
        test: /\.jsx?$/,
        exclude: /node_modules/,
        use: [ 'babel-loader', 'react-hot-loader/webpack' ],
      }
    ]
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: './static/template.html',
      inject: 'body',
      filename: 'index.html'
    }),
    new webpack.optimize.OccurrenceOrderPlugin(),
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoEmitOnErrorsPlugin(),
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': JSON.stringify('development')
    })
  ]
};
</code>```

app.js snippet:

```<code>app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());

app.use(express.static(__dirname + 'client/dist'));
app.use(webpackDevMiddleware(compiler, {
    publicPath: webpackConfig.output.publicPath,
    hot: true,
    historyApiFallback: true,
    stats: {
        colors: true
    }
}));
</code>```

I am using localhost:5000 . The question linked did not fix my problem

答:
FYI, Starting in version 4.0, React Router no longer uses the IndexRoute.

Also for your path, change "example" to "/example"

Title: React Router not working correctly

Body:
I am new to react and have no idea why this wouldnt be working.

My router code is here:

import React from 'react';
import { Route, IndexRoute } from 'react-router';

import App from './components/App';
import HomePage from './components/home/HomePage';

export default (
  <Route path="/" component={App}>
    <IndexRoute component={HomePage} />
    <Route path="example" component={HomePage} />
  </Route>
);

So what happens with this code is:

localhost/ displays fine

localhost/example does not display

localhost/example link from the header on the homepage displays, but pressing refresh does not

Thanks for any help, I appreciate it!

here is my webpack config:

const webpack = require('webpack');
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  context: path.join(__dirname, "/client"),
  entry: [
    'webpack-dev-server/client?http://127.0.0.0:5000/',
    'webpack/hot/only-dev-server',
    'react-hot-loader/patch',
    './src/index.js'
  ],
  output: {
    path: path.join(__dirname, "/client/dist"),
    filename: '[name].js',
    publicPath: '/'
  },
  resolve: {
    extensions: ['.js', '.jsx', '.json']
  },
  devServer: {
    historyApiFallback: true
  },
  module: {
    rules: [
      {
        test: /\.jsx?$/,
        exclude: /node_modules/,
        use: [ 'babel-loader', 'react-hot-loader/webpack' ],
      }
    ]
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: './static/template.html',
      inject: 'body',
      filename: 'index.html'
    }),
    new webpack.optimize.OccurrenceOrderPlugin(),
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoEmitOnErrorsPlugin(),
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': JSON.stringify('development')
    })
  ]
};

app.js snippet:

app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());

app.use(express.static(__dirname + 'client/dist'));
app.use(webpackDevMiddleware(compiler, {
    publicPath: webpackConfig.output.publicPath,
    hot: true,
    historyApiFallback: true,
    stats: {
        colors: true
    }
}));

I am using localhost:5000 . The question linked did not fix my problem