问:
how to get all keys and values in redis in javascript?
I am creating a node API using javascript. I have used redis as my key value store.
I created a redis-client in my app and am able to get values for perticular key.

I want to retrieve all keys along with their values.
So Far I have done this :

```<code>app.get('/jobs', function (req, res) {
    var jobs = [];
    client.keys('*', function (err, keys) {
        if (err) return console.log(err);
        if(keys){
            for(var i=0;i<keys.length;i++){
                client.get(keys[i], function (error, value) {
                    if (err) return console.log(err);
                    var job = {};
                    job['jobId']=keys[i];
                    job['data']=value;
                    jobs.push(job);
                });
            }
            console.log(jobs);
            res.json({data:jobs});
        }
    });
});
</code>```

but I always get blank array in response.

is there any way to do this in javascript?

Thanks

答:
You may find something useful in this link

https://github.com/NodeRedis/node_redis/tree/master/examples

Body:
I am creating a node API using javascript. I have used redis as my key value store.
I created a redis-client in my app and am able to get values for perticular key.

I want to retrieve all keys along with their values.
So Far I have done this :

app.get('/jobs', function (req, res) {
    var jobs = [];
    client.keys('*', function (err, keys) {
        if (err) return console.log(err);
        if(keys){
            for(var i=0;i<keys.length;i++){
                client.get(keys[i], function (error, value) {
                    if (err) return console.log(err);
                    var job = {};
                    job['jobId']=keys[i];
                    job['data']=value;
                    jobs.push(job);
                });
            }
            console.log(jobs);
            res.json({data:jobs});
        }
    });
});

but I always get blank array in response.

is there any way to do this in javascript?

Thanks


来源: stackexchange

问:
extracting cell values in open office calc to set variables in VB.net
Im intrested in finding out how i can add and extract cell values in open office calc using VB.net

dose anybody know any good refrences online to help me get started

答:
The first think you need is the OpenOffice SDK. Here is that link: http://download.openoffice.org/other.html#tested-sdk

Now, most of the examples are written in JAVA and C++. However, there are several sites out there that have utilities or example code for porting to VB.NET. However, you should really learn about UNO with Open Office through this link here: http://wiki.services.openoffice.org/wiki/Documentation/DevGuide/OpenOffice.org_Developers_Guide.

Use the guide in tandem with any control or interface you use so that you have a clear understanding of what you are attempting to do. Here is an thread from another site that shows some example code: http://user.services.openoffice.org/en/forum/viewtopic.php?f=25&t=15504

ContentLicense: CC BY-SA 2.5


问:
Why is this haskey() condition always false?
I start out with a list of word counts:

```<code>julia> import Iterators: partition
julia> import StatsBase: countmap
julia> s = split("the lazy fox jumps over the brown dog");
julia> vocab_counter = countmap(s)
Dict{SubString{String},Int64} with 7 entries:
  "brown" => 1
  "lazy"  => 1
  "jumps" => 1
  "the"   => 2
  "fox"   => 1
  "over"  => 1
  "dog"   => 1
</code>```

Then I want to compute the no. of ngrams per word and store it in a nested dictionary. The outer key would be the ngram and the inner key the word and inner-most value is the count of the ngram given the word.

I've tried:

```<code>ngram_word_counter = Dict{Tuple,Dict}()
for (word, count) in vocab_counter
    for ng in ngram(word, 2) # bigrams.
        if ! haskey(ngram_word_counter, ng)
            ngram_word_counter[ng] = Dict{String,Int64}()
            ngram_word_counter[ng][word] = 0
        end
        ngram_word_counter[ng][word] += 1
    end
end
</code>```

And that gives me the data structure I need:

```<code>julia> ngram_word_counter
Dict{Tuple,Dict} with 20 entries:
  ('b','r') => Dict("brown"=>1)
  ('t','h') => Dict("the"=>1)
  ('o','w') => Dict("brown"=>1)
  ('z','y') => Dict("lazy"=>1)
  ('o','g') => Dict("dog"=>1)
  ('u','m') => Dict("jumps"=>1)
  ('o','x') => Dict("fox"=>1)
  ('e','r') => Dict("over"=>1)
  ('a','z') => Dict("lazy"=>1)
  ('p','s') => Dict("jumps"=>1)
  ('h','e') => Dict("the"=>1)
  ('d','o') => Dict("dog"=>1)
  ('w','n') => Dict("brown"=>1)
  ('m','p') => Dict("jumps"=>1)
  ('l','a') => Dict("lazy"=>1)
  ('o','v') => Dict("over"=>1)
  ('v','e') => Dict("over"=>1)
  ('r','o') => Dict("brown"=>1)
  ('f','o') => Dict("fox"=>1)
  ('j','u') => Dict("jumps"=>1)
</code>```

But notice that the values are wrong:

```<code>('t','h') => Dict("the"=>1)
('h','e') => Dict("the"=>1)
</code>```

should have been:

```<code>('t','h') => Dict("the"=>2)
('h','e') => Dict("the"=>2)
</code>```

Since the word the appeared twice.

After a closer look, it seems like the haskey(ngram_word_counter, ng) is always false =(

```<code>julia> ngram_word_counter = Dict{Tuple,Dict}()
for (word, count) in vocab_counter
    for ng in ngram(word, 2) # bigrams.
        println(haskey(ngram_word_counter, ng))
    end
end
</code>```

[out]:

```<code>false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
</code>```

Why is this haskey() condition always false?

答:
TL;DR : It should be ngram_word_counter[ng][word] += count instead of ngram_word_counter[ng][word] += 1.

Adding just 1 neglects multiple contribution by a word appearing several times. The number of times the word appears is encoded in vocab_counter values which go into variable count in the for loop. Therefore the increment should be by count.

The later debug check is ineffective, and as often is the case, the debugging code's bugs confuse the problem. The intended check was probably:

```<code>julia> ngram_word_counter = Dict{Tuple,Dict}()
for (word, count) in vocab_counter
    for ng in ngram(word, 2) # bigrams.
        println(haskey(ngram_word_counter, ng))
        ngram_word_counter[ng] = 1
    end
end
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I start out with a list of word counts:

julia> import Iterators: partition
julia> import StatsBase: countmap
julia> s = split("the lazy fox jumps over the brown dog");
julia> vocab_counter = countmap(s)
Dict{SubString{String},Int64} with 7 entries:
  "brown" => 1
  "lazy"  => 1
  "jumps" => 1
  "the"   => 2
  "fox"   => 1
  "over"  => 1
  "dog"   => 1

Then I want to compute the no. of ngrams per word and store it in a nested dictionary. The outer key would be the ngram and the inner key the word and inner-most value is the count of the ngram given the word.

I've tried:

ngram_word_counter = Dict{Tuple,Dict}()
for (word, count) in vocab_counter
    for ng in ngram(word, 2) # bigrams.
        if ! haskey(ngram_word_counter, ng)
            ngram_word_counter[ng] = Dict{String,Int64}()
            ngram_word_counter[ng][word] = 0
        end
        ngram_word_counter[ng][word] += 1
    end
end

And that gives me the data structure I need:

julia> ngram_word_counter
Dict{Tuple,Dict} with 20 entries:
  ('b','r') => Dict("brown"=>1)
  ('t','h') => Dict("the"=>1)
  ('o','w') => Dict("brown"=>1)
  ('z','y') => Dict("lazy"=>1)
  ('o','g') => Dict("dog"=>1)
  ('u','m') => Dict("jumps"=>1)
  ('o','x') => Dict("fox"=>1)
  ('e','r') => Dict("over"=>1)
  ('a','z') => Dict("lazy"=>1)
  ('p','s') => Dict("jumps"=>1)
  ('h','e') => Dict("the"=>1)
  ('d','o') => Dict("dog"=>1)
  ('w','n') => Dict("brown"=>1)
  ('m','p') => Dict("jumps"=>1)
  ('l','a') => Dict("lazy"=>1)
  ('o','v') => Dict("over"=>1)
  ('v','e') => Dict("over"=>1)
  ('r','o') => Dict("brown"=>1)
  ('f','o') => Dict("fox"=>1)
  ('j','u') => Dict("jumps"=>1)

But notice that the values are wrong:

('t','h') => Dict("the"=>1)
('h','e') => Dict("the"=>1)

should have been:

('t','h') => Dict("the"=>2)
('h','e') => Dict("the"=>2)

Since the word the appeared twice.

After a closer look, it seems like the haskey(ngram_word_counter, ng) is always false =(

julia> ngram_word_counter = Dict{Tuple,Dict}()
for (word, count) in vocab_counter
    for ng in ngram(word, 2) # bigrams.
        println(haskey(ngram_word_counter, ng))
    end
end

[out]:

false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false

Why is this haskey() condition always false?

Body:
TL;DR : It should be ngram_word_counter[ng][word] += count instead of ngram_word_counter[ng][word] += 1.

Adding just 1 neglects multiple contribution by a word appearing several times. The number of times the word appears is encoded in vocab_counter values which go into variable count in the for loop. Therefore the increment should be by count.

The later debug check is ineffective, and as often is the case, the debugging code's bugs confuse the problem. The intended check was probably:

julia> ngram_word_counter = Dict{Tuple,Dict}()
for (word, count) in vocab_counter
    for ng in ngram(word, 2) # bigrams.
        println(haskey(ngram_word_counter, ng))
        ngram_word_counter[ng] = 1
    end
end


问:
I can`t connect to database on my server it displays blank page
```<code><!Doctype html>
<html>
<head>
<title>Orders Database</title>
</head>
<body>
<?php
$con = mysql_connect('localhost','wrobell1_1','123');
$db = mysql_select_db('wrobell1_orders',$con);

if($con){
echo 'succefully connected'}
?>
</body>
</html>
</code>```

<p>What can be wrong? I put it on the server in public html folder and nothing displays </p>

答:
The might be two problems with your connection code. 1.
The live server on  might be using a php version that does not support the mysql_* functions that you are using, they are depreciated and no longer used, in the newer php version, better use mysqli or pdo.

The host might be incorrect? check the host,username and password are correct.
When you are on cpanel you can login to phpmyadmin from there once login you may see, the host/server name : its wtitten server:whatever make sure on your communication you write that server name screenshot shows how to see the server name from phpmyadmin of a live server, from your cpanel.

The third and obvious one is the syntax error here : echo 'succefully connected'} there's a semicolon missing which then should generate an error, thus makking your question a possible duplicate of : PHP Parse/Syntax Errors; and How to solve them?

Better start using mysqli or pdo rather than mysql_* functions

Check if your host is indeed correct is localhost, you can check that on php myadmin

Proper connection

```<code><?php
$servername = "localhost";
$username = "wrobell1_1";
$password = "123";
$dbname = "wrobell1_orders";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}
?>
</code>```

Body:
<!Doctype html>

<title>Orders Database</title>

<?php
$con = mysql_connect('localhost','wrobell1_1','123');
$db = mysql_select_db('wrobell1_orders',$con);

if($con){
echo 'succefully connected'}
?>

What can be wrong? I put it on the server in public html folder and nothing displays

Body:
The might be two problems with your connection code. 1.
The live server on  might be using a php version that does not support the mysql_* functions that you are using, they are depreciated and no longer used, in the newer php version, better use mysqli or pdo.

The host might be incorrect? check the host,username and password are correct.
When you are on cpanel you can login to phpmyadmin from there once login you may see, the host/server name : its wtitten server:whatever make sure on your communication you write that server name screenshot shows how to see the server name from phpmyadmin of a live server, from your cpanel.

The third and obvious one is the syntax error here : echo 'succefully connected'} there's a semicolon missing which then should generate an error, thus makking your question a possible duplicate of : PHP Parse/Syntax Errors; and How to solve them?

Better start using mysqli or pdo rather than mysql_* functions

Check if your host is indeed correct is localhost, you can check that on php myadmin

Proper connection

<?php
$servername = "localhost";
$username = "wrobell1_1";
$password = "123";
$dbname = "wrobell1_orders";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}
?>


问:
proxy_pass configuration in NGINX
I'm trying to figure out how to pass an external request via proxy_pass in NGINX. In particular I want to load Sphinx Documentation source from http://example.com/documentation/, but actually after restarting NGINX server I got 502 Bad Gateway, probably derived by a not proper configuration.

Here's my example configuration:

```<code>server {

    listen 80;
    server_name example.com;
    root /var/www;

    location /documentation {

        proxy_pass http://example.com:8000;
        index index.php index.html index.htm;
    }

}
</code>```

In my opinion it should work, any suggestions?

Consider that if I try to launch the Sphinx source via ssh console without NGINX configuration, it works but the source path is like this: http://example.com:8000, not the best way to display it.

Also because I need to load it every times via the console command:

sphinx-autobuild source build/html --host http://example.com --port8000

I didn't find nothing about launch it in a specific subfolder of the host, for example the subfolder /documentation.

[Update]

I have tried to replace example.com with localhost instruction as suggested by @Johnny Logan, and I got a 502 Bad Request with this strange kind of result request in the address bar:

```<code>http://example.com/documentation:8000:8000:8000:8000:8000:8000:8000:8000:8000:8000:8000:8000:8000:8000:8000:8000:8000:8000:8000:8000/
</code>```

答:
It looks like you're connecting to example.com again -- I suppose you want to get to port 8000 internally? You may want to substitute 'localhost' in the configuration:

```<code>server {

    listen 80;
    server_name example.com;
    root /var/www;

    location /documentation {

        proxy_pass http://localhost:8000;
        index index.php index.html index.htm;
    }

}
</code>```

This way you also don't need to have port 8000 open -- everything goes through port 80 or 443.

Title: proxy_pass configuration in NGINX

Body:
I'm trying to figure out how to pass an external request via proxy_pass in NGINX. In particular I want to load Sphinx Documentation source from http://example.com/documentation/, but actually after restarting NGINX server I got 502 Bad Gateway, probably derived by a not proper configuration.

Here's my example configuration:

server {

    listen 80;
    server_name example.com;
    root /var/www;

    location /documentation {

        proxy_pass http://example.com:8000;
        index index.php index.html index.htm;
    }

}

In my opinion it should work, any suggestions?

Consider that if I try to launch the Sphinx source via ssh console without NGINX configuration, it works but the source path is like this: http://example.com:8000, not the best way to display it.

Also because I need to load it every times via the console command:

sphinx-autobuild source build/html --host http://example.com --port8000

I didn't find nothing about launch it in a specific subfolder of the host, for example the subfolder /documentation.

[Update]

I have tried to replace example.com with localhost instruction as suggested by @Johnny Logan, and I got a 502 Bad Request with this strange kind of result request in the address bar:

http://example.com/documentation:8000:8000:8000:8000:8000:8000:8000:8000:8000:8000:8000:8000:8000:8000:8000:8000:8000:8000:8000:8000/

Body:
It looks like you're connecting to example.com again -- I suppose you want to get to port 8000 internally? You may want to substitute 'localhost' in the configuration:

server {

    listen 80;
    server_name example.com;
    root /var/www;

    location /documentation {

        proxy_pass http://localhost:8000;
        index index.php index.html index.htm;
    }

}

This way you also don't need to have port 8000 open -- everything goes through port 80 or 443.


问:
EaselJS - Best way to detect collision
I'm trying to find a good way for collision detection for my easelJS small app.

I've just created 2 rectangle using createjs.Shape

But after creating a rectangle shape, the API doesn't let me know the width and height of the rectangle (I don't know why).

EaselJS Shape has a method called "hitTest" but it can only be used when you want to test collision of the shape and a point.

//Here's the code http://jsfiddle.net/ZbZjL/16/.

//Create a stage by getting a reference to the canvas
stage = new createjs.Stage("demoCanvas");
//Create a Shape DisplayObject.
redRect = new createjs.Shape();
redRect.graphics.beginFill("red").drawRect(0, 0, 60, 40);
redRect.regX = 30;
redRect.regY = 20;
redRect.x = 200;
redRect.y = 100;

blueRect = new createjs.Shape();
blueRect.graphics.beginFill("blue").drawRect(0, 0, 60, 40);
blueRect.regX = 30;
blueRect.regY = 20;
blueRect.x = 0;
blueRect.y = 100;
//Add Shape instance to stage display list.
stage.addChild(redRect);
stage.addChild(blueRect);
//Update stage will render next frame
stage.update();

document.addEventListener("mousemove", onMouseMove);
function onMouseMove(event) {
    blueRect.x = event.offsetX;
    stage.update();
}
```

答:
here is a nice function from fragenwissen.com,
it controls first the objs visibility an then the objs position.</p>

```<code>function detect_object_collision(obj1, obj2) {
    // user noname from FragenWissen.com
    if (obj1.visible && obj2.visible) {
        obj1.setBounds(obj1.nominalBounds.x + obj1.x, obj1.nominalBounds.y + obj1.y, obj1.nominalBounds.width, obj1.nominalBounds.height);
        obj2.setBounds(obj2.nominalBounds.x + obj2.x, obj2.nominalBounds.y + obj2.y, obj2.nominalBounds.width, obj2.nominalBounds.height);
        obj1 = obj1.getBounds();
        obj2 = obj2.getBounds();
        return !(
            ((obj1.y + obj1.height) < (obj2.y)) ||
            (obj1.y > (obj2.y + obj2.height)) ||
            ((obj1.x + obj1.width) < obj2.x) ||
            (obj1.x > (obj2.x + obj2.width))
        );
    } else {
        return false;
    }
}
</code>```

Title: EaselJS - Best way to detect collision

Body:
here is a nice function from fragenwissen.com,
it controls first the objs visibility an then the objs position.

function detect_object_collision(obj1, obj2) {
    // user noname from FragenWissen.com
    if (obj1.visible && obj2.visible) {
        obj1.setBounds(obj1.nominalBounds.x + obj1.x, obj1.nominalBounds.y + obj1.y, obj1.nominalBounds.width, obj1.nominalBounds.height);
        obj2.setBounds(obj2.nominalBounds.x + obj2.x, obj2.nominalBounds.y + obj2.y, obj2.nominalBounds.width, obj2.nominalBounds.height);
        obj1 = obj1.getBounds();
        obj2 = obj2.getBounds();
        return !(
            ((obj1.y + obj1.height) < (obj2.y)) ||
            (obj1.y > (obj2.y + obj2.height)) ||
            ((obj1.x + obj1.width) < obj2.x) ||
            (obj1.x > (obj2.x + obj2.width))
        );
    } else {
        return false;
    }
}


问:
Hadoop: How to keep track of Clients and client sessions?
I am trying to find popularity of files present on a client's session. Is there a way to determine the client IP and log the files in a clients session? Or do i have to write my own code or it? If so what are the things to be considered while writing that code?
Thanks.</p>

答:
Audit logs are logged from the Hive metastore server for every metastore API invocation. It is logged at the INFO level of log4j, so you need to make sure that the logging at the INFO level is enabled. The name of the log entry is "HiveMetaStore.audit".

Audit logs were added in Hive 0.7 for secure client connections and in Hive 0.10 for non-secure connections


问:
Angular Translate not translating sometimes with one-time binding
I am using Angular 1.x and it's Angular Translate module. Recently, I switched all my translation bindings from two-way to one-time. Everything worked fine, until one day, however, I noticed that sometimes if I started refreshing the page, the translations are not actually getting translated.

Example:

```<code>{{ ::'MyTranslationKey' | translate }}
</code>```

In 90% of the times the result is correct. In the other 10%, however, the rendered result is:

```<code>MyTranslationKey
</code>```

What's the reason for this and how can I fix it?

Edit:

This doesn't happen to elements that are inside ng-if, ng-repeat or directives - e.g. when they are inside a child scope.

答:
By default, angular-translate puts an empty string for the keys without translation.
The reason why in 10% of the times translate doesn't work is that you have received files with translations just after the page was rendered. When you received the translation files, new values for translate directive did not apply, because of one time data binding;
In this case, you can put all content inside ng-if with data receiving condition, ng-if='loaded'.

Body:
I am using Angular 1.x and it's Angular Translate module. Recently, I switched all my translation bindings from two-way to one-time. Everything worked fine, until one day, however, I noticed that sometimes if I started refreshing the page, the translations are not actually getting translated.

Example:

{{ ::'MyTranslationKey' | translate }}

In 90% of the times the result is correct. In the other 10%, however, the rendered result is:

MyTranslationKey

What's the reason for this and how can I fix it?

Edit:

This doesn't happen to elements that are inside ng-if, ng-repeat or directives - e.g. when they are inside a child scope.


问:
WordPress, removing comments block programmatically
I want to remove Word Press comment block from specified 'n' posts. These posts are generated dynamically and don't want comment block</p>

答:
Not tested, but this should work in your index.php/single.php file..</p>

```<code>$posts_to_hide_comments = array(1, 3, 8, 9, 10, 13, 17, 24);

if (! in_array($post->ID, $posts_to_hide_comments, true)) {

    comments_template();

}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Not tested, but this should work in your index.php/single.php file..

$posts_to_hide_comments = array(1, 3, 8, 9, 10, 13, 17, 24);

if (! in_array($post->ID, $posts_to_hide_comments, true)) {

    comments_template();

}


问:
Fineuploader - OnComplete Method can't call a value outside the function
I have a problem with fineuploader in the OnComplete() function when I try to call "customer" value inside it. I'm using Angular and TypeScript for frontside.

The "customer" value is undefined because it is not found in the onComplete() bloc (no auto-completion). So how can I call my importCustomers function? any idea?

Thank you in advance for any help.

答:
Use arrow functions since they have no binding of this:

```<code>onComplete = (id, name, responseJSON) => {
  if(responseJSON.success) {
    console.log("Upload done")
    this.customer.importCustomers(name)
  }
}
</code>```

Alternatively you can pass this on your function arguments :

```<code>onComplete(id, name, responseJSON, this) {
  let _this = this;
  if(responseJSON.success) {
    console.log("Upload done")
    _this.customer.importCustomers(name)
  }
}
</code>```

Body:
Use arrow functions since they have no binding of this:

onComplete = (id, name, responseJSON) => {
  if(responseJSON.success) {
    console.log("Upload done")
    this.customer.importCustomers(name)
  }
}

Alternatively you can pass this on your function arguments :

onComplete(id, name, responseJSON, this) {
  let _this = this;
  if(responseJSON.success) {
    console.log("Upload done")
    _this.customer.importCustomers(name)
  }
}


问:
MySql MariaDB create Procedure error
I am building my first mySQL database for a project, transfering a database from MS Access to mysql. Now I know that I have a huge learning curve but that is okay, I have to learn it one day.

I am building this database in the mySQL database of XAMPP-phpMyAdmin.

The problem I am having is on creating a procedure, here is the full procedure:
(some of the table or variable names have been changed due to confidental nature of my work, so no need to comment that Table1 is a bad name etc.., I already know)

```<code>DELIMITER $$

DROP PROCEDURE IF EXISTS Proc1$$

CREATE PROCEDURE Proc1(IN pType INT)

BEGIN

SET @runningTotal=0, @prevTotal=0, @Aim=5, @Period=21;

DROP TEMPORARY TABLE IF EXISTS temp_table;

CREATE TEMPORARY TABLE IF NOT EXISTS temp_table(
  `id` int(11) NOT NULL,
  `dDate` date DEFAULT NULL,
  `type` int(11) DEFAULT NULL,
  `MyAmountCol` int(11) DEFAULT NULL
);

INSERT INTO temp_table(`id`, `dDate`, `type`, `MyAmountCol`)
  SELECT `id`, `dDate`, `type`, `MyAmountCol`
  FROM Table1
  WHERE type=pType AND
        table1.dDate>=DATE_SUB(CURDATE(), INTERVAL @Period DAY) AND
        table1.dDate!=CURDATE();

DROP TEMPORARY TABLE IF EXISTS temp_table_result;

CREATE TEMPORARY TABLE IF NOT EXISTS temp_table_result AS
  SELECT
    temp_table.Id,
    temp_table.dDate,
    temp_table.MyAmountCol,
    DATE_ADD(temp_table.dDate, INTERVAL @Period DAY) as 'RecDay',
    DATE_ADD(@prevDate, INTERVAL @Period DAY) As 'NextRecDay',
    @prevTotal := @runningTotal as 'PreviousTotal',
    @Aim -@prevTotal as 'MinAmmount',
    @runningTotal := @runningTotal + temp_table.MyAmountCol as 'RunningTotal',
    @prevDate := temp_table.dDate
    pType as 'Type'
  FROM temp_table
  HAVING PreviousTotal <= @Aim
  ORDER BY RunningTotal DESC LIMIT 1;

UPDATE Result A INNER JOIN temp_table_result B (A.type = B.Type)
  SET  A.RecDay=B.RecDay, A.NextRecDay=B.NextRecDay, A.MinHours=B.MinAmmount;

DROP TEMPORARY TABLE IF EXISTS temp_table;
DROP TEMPORARY TABLE IF EXISTS temp_table_result;

END;
$$
DELIMITER ;
</code>```

So the problem is I have spent all day looking at brings up the following error:

```<code>#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'as 'Type'
FROM temp_table
HAVING PreviousTotal <= @Aim
ORDER BY Runn' at line 37
</code>```

I know it is a syntax error and I have been slowly fixing the syntax errors one by one, (the joys of learning as you create). But I can't figure out this syntax error.

Thanks for all your help

答:
Just try below code.
Hope this will helps.</p>

```<code>DROP PROCEDURE IF EXISTS Proc1;
DELIMITER $$
CREATE PROCEDURE Proc1(IN pType INT)

BEGIN

SET @runningTotal=0, @prevTotal=0, @Aim=5, @Period=21;

DROP TEMPORARY TABLE IF EXISTS temp_table;

CREATE TEMPORARY TABLE IF NOT EXISTS temp_table(
  `id` int(11) NOT NULL,
  `dDate` date DEFAULT NULL,
  `type` int(11) DEFAULT NULL,
  `MyAmountCol` int(11) DEFAULT NULL
);

INSERT INTO temp_table(`id`, `dDate`, `type`, `MyAmountCol`)
  SELECT `id`, `dDate`, `type`, `MyAmountCol`
  FROM Table1
  WHERE type=pType AND
        table1.dDate>=DATE_SUB(CURDATE(), INTERVAL @Period DAY) AND
        table1.dDate!=CURDATE();

DROP TEMPORARY TABLE IF EXISTS temp_table_result;

CREATE TEMPORARY TABLE IF NOT EXISTS temp_table_result AS
  SELECT
    temp_table.Id,
    temp_table.dDate,
    temp_table.MyAmountCol,
    DATE_ADD(temp_table.dDate, INTERVAL @Period DAY) as 'RecDay',
    DATE_ADD(@prevDate, INTERVAL @Period DAY) As 'NextRecDay',
    @prevTotal := @runningTotal as 'PreviousTotal',
    @Aim -@prevTotal as 'MinAmmount',
    @runningTotal := @runningTotal + temp_table.MyAmountCol as 'RunningTotal',
    @prevDate := temp_table.dDate, <--- Make change at this line.
    pType as 'Type'
  FROM temp_table
  HAVING PreviousTotal <= @Aim
  ORDER BY RunningTotal DESC LIMIT 1;

UPDATE Result A INNER JOIN temp_table_result B ON(A.type = B.Type)
  SET  A.RecDay=B.RecDay, A.NextRecDay=B.NextRecDay, A.MinHours=B.MinAmmount;

DROP TEMPORARY TABLE IF EXISTS temp_table;
DROP TEMPORARY TABLE IF EXISTS temp_table_result;

END;
$$
DELIMITER ;
</code>```

Title: MySql MariaDB create Procedure error

Body:
I am building my first mySQL database for a project, transfering a database from MS Access to mysql. Now I know that I have a huge learning curve but that is okay, I have to learn it one day.

I am building this database in the mySQL database of XAMPP-phpMyAdmin.

The problem I am having is on creating a procedure, here is the full procedure:
(some of the table or variable names have been changed due to confidental nature of my work, so no need to comment that Table1 is a bad name etc.., I already know)

DELIMITER $$

DROP PROCEDURE IF EXISTS Proc1$$

CREATE PROCEDURE Proc1(IN pType INT)

BEGIN

SET @runningTotal=0, @prevTotal=0, @Aim=5, @Period=21;

DROP TEMPORARY TABLE IF EXISTS temp_table;

CREATE TEMPORARY TABLE IF NOT EXISTS temp_table(
  `id` int(11) NOT NULL,
  `dDate` date DEFAULT NULL,
  `type` int(11) DEFAULT NULL,
  `MyAmountCol` int(11) DEFAULT NULL
);

INSERT INTO temp_table(`id`, `dDate`, `type`, `MyAmountCol`)
  SELECT `id`, `dDate`, `type`, `MyAmountCol`
  FROM Table1
  WHERE type=pType AND
        table1.dDate>=DATE_SUB(CURDATE(), INTERVAL @Period DAY) AND
        table1.dDate!=CURDATE();

DROP TEMPORARY TABLE IF EXISTS temp_table_result;

CREATE TEMPORARY TABLE IF NOT EXISTS temp_table_result AS
  SELECT
    temp_table.Id,
    temp_table.dDate,
    temp_table.MyAmountCol,
    DATE_ADD(temp_table.dDate, INTERVAL @Period DAY) as 'RecDay',
    DATE_ADD(@prevDate, INTERVAL @Period DAY) As 'NextRecDay',
    @prevTotal := @runningTotal as 'PreviousTotal',
    @Aim -@prevTotal as 'MinAmmount',
    @runningTotal := @runningTotal + temp_table.MyAmountCol as 'RunningTotal',
    @prevDate := temp_table.dDate
    pType as 'Type'
  FROM temp_table
  HAVING PreviousTotal <= @Aim
  ORDER BY RunningTotal DESC LIMIT 1;

UPDATE Result A INNER JOIN temp_table_result B (A.type = B.Type)
  SET  A.RecDay=B.RecDay, A.NextRecDay=B.NextRecDay, A.MinHours=B.MinAmmount;

DROP TEMPORARY TABLE IF EXISTS temp_table;
DROP TEMPORARY TABLE IF EXISTS temp_table_result;

END;
$$
DELIMITER ;

So the problem is I have spent all day looking at brings up the following error:

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'as 'Type'
FROM temp_table
HAVING PreviousTotal <= @Aim
ORDER BY Runn' at line 37

I know it is a syntax error and I have been slowly fixing the syntax errors one by one, (the joys of learning as you create). But I can't figure out this syntax error.

Thanks for all your help

Body:
Just try below code.
Hope this will helps.

DROP PROCEDURE IF EXISTS Proc1;
DELIMITER $$
CREATE PROCEDURE Proc1(IN pType INT)

BEGIN

SET @runningTotal=0, @prevTotal=0, @Aim=5, @Period=21;

DROP TEMPORARY TABLE IF EXISTS temp_table;

CREATE TEMPORARY TABLE IF NOT EXISTS temp_table(
  `id` int(11) NOT NULL,
  `dDate` date DEFAULT NULL,
  `type` int(11) DEFAULT NULL,
  `MyAmountCol` int(11) DEFAULT NULL
);

INSERT INTO temp_table(`id`, `dDate`, `type`, `MyAmountCol`)
  SELECT `id`, `dDate`, `type`, `MyAmountCol`
  FROM Table1
  WHERE type=pType AND
        table1.dDate>=DATE_SUB(CURDATE(), INTERVAL @Period DAY) AND
        table1.dDate!=CURDATE();

DROP TEMPORARY TABLE IF EXISTS temp_table_result;

CREATE TEMPORARY TABLE IF NOT EXISTS temp_table_result AS
  SELECT
    temp_table.Id,
    temp_table.dDate,
    temp_table.MyAmountCol,
    DATE_ADD(temp_table.dDate, INTERVAL @Period DAY) as 'RecDay',
    DATE_ADD(@prevDate, INTERVAL @Period DAY) As 'NextRecDay',
    @prevTotal := @runningTotal as 'PreviousTotal',
    @Aim -@prevTotal as 'MinAmmount',
    @runningTotal := @runningTotal + temp_table.MyAmountCol as 'RunningTotal',
    @prevDate := temp_table.dDate, <--- Make change at this line.
    pType as 'Type'
  FROM temp_table
  HAVING PreviousTotal <= @Aim
  ORDER BY RunningTotal DESC LIMIT 1;

UPDATE Result A INNER JOIN temp_table_result B ON(A.type = B.Type)
  SET  A.RecDay=B.RecDay, A.NextRecDay=B.NextRecDay, A.MinHours=B.MinAmmount;

DROP TEMPORARY TABLE IF EXISTS temp_table;
DROP TEMPORARY TABLE IF EXISTS temp_table_result;

END;
$$
DELIMITER ;


问:
How to get parent property in JS object?
Not sure if title is formulated correct, but I have a JS object that looks like:

```<code>parent:{
children:[
    {
        id: "1"
        user:[
            {
                id: 'aa',
                email:'aa@google.com'
            },
            {
                id: 'b',
                email:'bbb@google.com'
            },
        ]
    },
    {
        id:"2",
        user: [
            {
                id:'aa',
                email:'aa@google.com'
            },
            {
                id:'eee',
                email:'eee@google.com'
            }
        ]
    }
]
</code>```

}

The object is way bigger but follows the above structure.

How would I go to get a list of topics each user is on, filtered b ID?
E.g. 'aa' participates in children 1 and 2
'b'  participates in child 1
etc.

I figure it out I have to map the object but not sure how to proceed after that

答:
Assuming, you want an object with participant as key and all topic id in an object, then you could iterate the arrays an build a property with the associated id.

var data = { project: { topics: [{ id: "1", participants: [{ id: 'aa', email: 'aa@google.com' }, { id: 'b', email: 'bbb@google.com' }, ] }, { id: "2", participants: [{ id: 'aa', email: 'aa@google.com' }, { id: 'eee', email: 'eee@google.com' }] }] } },
    result = Object.create(null);

data.project.topics.forEach(function (a) {
    a.participants.forEach(function (b) {
        result[b.id] = result[b.id] || [];
        result[b.id].push(a.id);
    });
});

console.log(result);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Body:
Not sure if title is formulated correct, but I have a JS object that looks like:

parent:{
children:[
    {
        id: "1"
        user:[
            {
                id: 'aa',
                email:'aa@google.com'
            },
            {
                id: 'b',
                email:'bbb@google.com'
            },
        ]
    },
    {
        id:"2",
        user: [
            {
                id:'aa',
                email:'aa@google.com'
            },
            {
                id:'eee',
                email:'eee@google.com'
            }
        ]
    }
]

}

The object is way bigger but follows the above structure.

How would I go to get a list of topics each user is on, filtered b ID?
E.g. 'aa' participates in children 1 and 2
'b'  participates in child 1
etc.

I figure it out I have to map the object but not sure how to proceed after that

Body:
Assuming, you want an object with participant as key and all topic id in an object, then you could iterate the arrays an build a property with the associated id.

var data = { project: { topics: [{ id: "1", participants: [{ id: 'aa', email: 'aa@google.com' }, { id: 'b', email: 'bbb@google.com' }, ] }, { id: "2", participants: [{ id: 'aa', email: 'aa@google.com' }, { id: 'eee', email: 'eee@google.com' }] }] } },
    result = Object.create(null);

data.project.topics.forEach(function (a) {
    a.participants.forEach(function (b) {
        result[b.id] = result[b.id] || [];
        result[b.id].push(a.id);
    });
});

console.log(result);

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
Angular not binding data on html directly
I'm a beginner in Angular (ver 1.6.3) and i ran into this problem:

i have a controller called prof:

```<code>(function () {
    'use strict';

    angular
        .module('app.prof', [])
        .controller('ProfController', ProfController);

    /** @ngInject */
    function ProfController($scope, Data)
    {
        var vm = this;
        vm.documents = Data.documents;
        vm.classes = Data.classes;
    }
})();
</code>```

Here's its associated module :

```<code>(function () {
    'use strict';

    angular
        .module('app.prof')
        .config(config);

    /** @ngInject */
    function config($stateProvider, $translatePartialLoaderProvider, msApiProvider) {
        // State
        $stateProvider
            .state('app.prof', {
                url    : '/prof',
                views  : {
                    'content@app': {
                        templateUrl: 'app/main/prof/prof.html',
                        controller : 'ProfController as vm'
                    }
                },
                resolve : {
                    Data : function(msApi){
                        return msApi.resolve('data@get');
                    }
                }
            });

        $translatePartialLoaderProvider.addPart('app/main/prof');
        msApiProvider.register('data', ['app/data/prof/prof-data.json']);
    }
})();
</code>```

And here's the main problem : i have this html :

```<code><div class="document" ng-repeat="document in vm.documents">
    <ms-card template="'app/custom-directives/prof-card/prof-card.html'"
             ng-model="document"></ms-card>
</div>
</code>```

it works perfectly fine, the data is correctly binded and all, but when i put the template called directly in the page instead of calling it throught a <ms-card> it doesn't work anymore !
i've tried to put some console.log() a little eveywhere but it always says the data isn't defined; i don't get it.
Plus, the ng-repeat always works fine

Edit : a bit of the html i call :

```<code><md-list-item class="document-item md-white-bg md-2-line" md-ink-ripple>
              <div class="media ml-16">
                <img class="image-apercu" ng-src="{{card.media.image.src}}" alt="{{card.media.image.alt}}" ng-show="card.media.image">
              </div>
</code>```

ps : when i add the html directly i don't forget to put the ng-model="document" but it still doesn't work

This is very confusing for me :/

答:
In the end i found myself - I put the controller back like it was, i renamed all the {{card.something}} as {{document.something}} and i removed the ng-bind="" in the
 that was being looped.

Body:
I'm a beginner in Angular (ver 1.6.3) and i ran into this problem:

i have a controller called prof:

(function () {
    'use strict';

    angular
        .module('app.prof', [])
        .controller('ProfController', ProfController);

    /** @ngInject */
    function ProfController($scope, Data)
    {
        var vm = this;
        vm.documents = Data.documents;
        vm.classes = Data.classes;
    }
})();

Here's its associated module :

(function () {
    'use strict';

    angular
        .module('app.prof')
        .config(config);

    /** @ngInject */
    function config($stateProvider, $translatePartialLoaderProvider, msApiProvider) {
        // State
        $stateProvider
            .state('app.prof', {
                url    : '/prof',
                views  : {
                    'content@app': {
                        templateUrl: 'app/main/prof/prof.html',
                        controller : 'ProfController as vm'
                    }
                },
                resolve : {
                    Data : function(msApi){
                        return msApi.resolve('data@get');
                    }
                }
            });

        $translatePartialLoaderProvider.addPart('app/main/prof');
        msApiProvider.register('data', ['app/data/prof/prof-data.json']);
    }
})();

And here's the main problem : i have this html :

    <ms-card template="'app/custom-directives/prof-card/prof-card.html'"
             ng-model="document"></ms-card>

it works perfectly fine, the data is correctly binded and all, but when i put the template called directly in the page instead of calling it throught a <ms-card> it doesn't work anymore !
i've tried to put some console.log() a little eveywhere but it always says the data isn't defined; i don't get it.
Plus, the ng-repeat always works fine

Edit : a bit of the html i call :

<md-list-item class="document-item md-white-bg md-2-line" md-ink-ripple>

ps : when i add the html directly i don't forget to put the ng-model="document" but it still doesn't work

This is very confusing for me :/

Body: In the end i found myself - I put the controller back like it was, i renamed all the {{card.something}} as {{document.something}} and i removed the ng-bind="" in the <div> that was being looped.


问:
How to implement Intrusion Detection System in NS2 ?
I want to write a TCL script to implement Intrusion Detection System in NS2. I searched a lot, but I could not find proper help. I implemented basic routing protocols in NS2. I have a bit knowledge in TCL. I want to know how to modify a AODV protocol. I request you to help me. </p>

答:
IDS , Intrusion Detection System.

IDS AODV : Patches for ns-2.35 http://www.linuxquestions.org/questions/linux-wireless-networking-41/activate-mode-promiscuous-in-aodv-4175539244/#2 ...
Simulation examples : {blackholeaodv__idsAODV__dokurer.tcl, idsaodv2.tcl, idsAODV_mohawad-blackh.tcl, vanet-idsAODDV-blackhole-aodv.tcl} → https://drive.google.com/drive/folders/0B7S255p3kFXNSmRYb2lGcDRUdWs

IDS AOMDV : https://arxiv.org/pdf/1502.04801.pdf

(3) IDS for NetSim : IDS.zip → ids//{DSR/, WLAN/} https://en.wikipedia.org/wiki/NetSim
.. The code : https://drive.google.com/file/d/0B7S255p3kFXNYkt4TkpBR3FyVjA/view?usp=sharing


问:
Jira Rest API: Requesting issue(s) of a specific user in one or more projects (Beginner)
For testing and practice purposes I want to create a specific request in Jira by using its REST api:

I want to list all issues from a specific user in one or more specific projects.

I tried it with SOAP UI but I was not able to create or get my results with easy GET-HTTP requests (I don't know how to combine more values and parameter together). The other way would be to use a script language but here I don't know what to use.

The documentation is somewhat confusing for a beginner like me and I would like to know how combine different values and paramter and how to start in an easy way.

答:
Try to use advance rest client for chrome browsers to make your Rest requests.
The examples below (from official documentation) are for Curl usage but its simple to pass them to advance rest client. Dont forget the authentication.

Link to advance rest client

Example of create issue:

Request

```<code> curl -D- -u fred:fred -X POST --data {see below} -H "Content-Type:  application/json" http://localhost:8090/rest/api/2/issue/
</code>```

Data

```<code>{
  "fields": {
     "project":
     {
        "key": "TEST"
     },
     "summary": "REST ye merry gentlemen.",
     "description": "Creating of an issue using project keys and issue type names using the REST API",
     "issuetype": {
        "name": "Bug"
     }
  }
}
</code>```

Response

```<code>{
 "id":"39000",
 "key":"TEST-101",
  "self":"http://localhost:8090/rest/api/2/issue/39000"
}
</code>```

Example of making a query issue:

Request:

```<code>curl -D- -u fred:fred -X GET -H "Content-Type: application/json" http://kelpie9:8081/rest/api/2/search?jql=assignee=fred
</code>```

Response:

```<code>{
"expand": "schema,names",
"startAt": 0,
"maxResults": 50,
"total": 6,
"issues": [
    {
        "expand": "html",
        "id": "10230",
        "self": "http://kelpie9:8081/rest/api/2/issue/BULK-62",
        "key": "BULK-62",
        "fields": {
            "summary": "testing",
            "timetracking": null,
            "issuetype": {
                "self": "http://kelpie9:8081/rest/api/2/issuetype/5",
                "id": "5",
                "description": "The sub-task of the issue",
                "iconUrl": "http://kelpie9:8081/images/icons/issue_subtask.gif",
                "name": "Sub-task",
                "subtask": true
            },
            },
            "customfield_10071": null
        },
        "transitions": "http://kelpie9:8081/rest/api/2/issue/BULK-62/transitions",
    },
    {
        "expand": "html",
        "id": "10004",
        "self": "http://kelpie9:8081/rest/api/2/issue/BULK-47",
        "key": "BULK-47",
        "fields": {
            "summary": "Cheese v1 2.0 issue",
            "timetracking": null,
            "issuetype": {
                "self": "http://kelpie9:8081/rest/api/2/issuetype/3",
                "id": "3",
                "description": "A task that needs to be done.",
                "iconUrl": "http://kelpie9:8081/images/icons/task.gif",
                "name": "Task",
                "subtask": false
            },

              "transitions": "http://kelpie9:8081/rest/api/2/issue/BULK-47/transitions",
    }
 ]
}
</code>```

Body:
Try to use advance rest client for chrome browsers to make your Rest requests.
The examples below (from official documentation) are for Curl usage but its simple to pass them to advance rest client. Dont forget the authentication.

Link to advance rest client

Example of create issue:

Request

 curl -D- -u fred:fred -X POST --data {see below} -H "Content-Type:  application/json" http://localhost:8090/rest/api/2/issue/

Data

{
  "fields": {
     "project":
     {
        "key": "TEST"
     },
     "summary": "REST ye merry gentlemen.",
     "description": "Creating of an issue using project keys and issue type names using the REST API",
     "issuetype": {
        "name": "Bug"
     }
  }
}

Response

{
 "id":"39000",
 "key":"TEST-101",
  "self":"http://localhost:8090/rest/api/2/issue/39000"
}

Example of making a query issue:

Request:

curl -D- -u fred:fred -X GET -H "Content-Type: application/json" http://kelpie9:8081/rest/api/2/search?jql=assignee=fred

Response:

{
"expand": "schema,names",
"startAt": 0,
"maxResults": 50,
"total": 6,
"issues": [
    {
        "expand": "html",
        "id": "10230",
        "self": "http://kelpie9:8081/rest/api/2/issue/BULK-62",
        "key": "BULK-62",
        "fields": {
            "summary": "testing",
            "timetracking": null,
            "issuetype": {
                "self": "http://kelpie9:8081/rest/api/2/issuetype/5",
                "id": "5",
                "description": "The sub-task of the issue",
                "iconUrl": "http://kelpie9:8081/images/icons/issue_subtask.gif",
                "name": "Sub-task",
                "subtask": true
            },
            },
            "customfield_10071": null
        },
        "transitions": "http://kelpie9:8081/rest/api/2/issue/BULK-62/transitions",
    },
    {
        "expand": "html",
        "id": "10004",
        "self": "http://kelpie9:8081/rest/api/2/issue/BULK-47",
        "key": "BULK-47",
        "fields": {
            "summary": "Cheese v1 2.0 issue",
            "timetracking": null,
            "issuetype": {
                "self": "http://kelpie9:8081/rest/api/2/issuetype/3",
                "id": "3",
                "description": "A task that needs to be done.",
                "iconUrl": "http://kelpie9:8081/images/icons/task.gif",
                "name": "Task",
                "subtask": false
            },

              "transitions": "http://kelpie9:8081/rest/api/2/issue/BULK-47/transitions",
    }
 ]
}


问:
razor - how to dynamicaly insert id into div element
In my view I have:

```<code>@foreach (var comment in Model.commentList)
{
    var id = comment.CommentId;
    <div id="@(id)" style="height:100px; width: 100px; background-color: red; display:none;"></div>
    <a id=@id onClick="ShowForm(this.id)" href="#">Comment</a>
}
</code>```

And then I have a script:

```<code>function ShowForm(clicked_id) {
    var element = "#" + clicked_id;
    $(element).fadeIn(1000);
}
</code>```

What I want to achieve is to show a certain element after clicking a link but it is not working. Where is my mistake?

答:
The @ before the foreach will cause Razor to interpret the loop contents as C#.

Try prefixing the HTML lines inside the loop with "@:", like this:

```<code>@foreach (var comment in Model.commentList)
{
        var id = comment.CommentId;
        @:<div id="@(id)" style="height:100px; width: 100px; background-color: red; display:none;"></div>
        @:<a id=@id onClick="ShowForm(this.id)" href="#">Comment</a>
}
</code>```

Body:
In my view I have:

@foreach (var comment in Model.commentList)
{
    var id = comment.CommentId;

    Comment
}

And then I have a script:

function ShowForm(clicked_id) {
    var element = "#" + clicked_id;
    $(element).fadeIn(1000);
}

What I want to achieve is to show a certain element after clicking a link but it is not working. Where is my mistake?

Body:
The @ before the foreach will cause Razor to interpret the loop contents as C#.

Try prefixing the HTML lines inside the loop with "@:", like this:

@foreach (var comment in Model.commentList)
{
        var id = comment.CommentId;
        @:<div id="@(id)" style="height:100px; width: 100px; background-color: red; display:none;"></div>
        @:<a id=@id onClick="ShowForm(this.id)" href="#">Comment</a>
}


问:
Pull the previous sibling element
You can use margin-right, for example, to push a next sibling as seen below:

#parent {
  background: tan;
  font-size: 0;
}

#parent * {
  display: inline-block;
  width: 50px;
  height: 50px;
}

#child1 {
  background: teal;
  margin-right: 100px;
}

#child2 {
  background: olive;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="parent">
  <div id="child1"></div>
  <div id="child2"></div>
</div></code>```

I know there is no previous sibling selector in CSS. However, I wonder if there's a workaround so #child2 can pull #child1 to a distance of say, 20px. Here's a before-after screenshot:

Note: I don't want to give a margin value to #child1 or alter the HTML. The effect should be achieved using #child2 only.

答:
#parent {
  background: tan;
  font-size: 0;
}

#parent * {
  display: inline-block;
  width: 50px;
  height: 50px;
}
#parent div{
  margin: 0px 20px;
}

#child1 {
  background: teal;
}

#child2 {
  background: olive;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="parent">
  <div id="child1"></div>
  <div id="child2"></div>
</div></code>```

Title: Pull the previous sibling element

Body:
You can use margin-right, for example, to push a next sibling as seen below:

#parent {
  background: tan;
  font-size: 0;
}

#parent * {
  display: inline-block;
  width: 50px;
  height: 50px;
}

#child1 {
  background: teal;
  margin-right: 100px;
}

#child2 {
  background: olive;
}

I know there is no previous sibling selector in CSS. However, I wonder if there's a workaround so #child2 can pull #child1 to a distance of say, 20px. Here's a before-after screenshot:

Note: I don't want to give a margin value to #child1 or alter the HTML. The effect should be achieved using #child2 only.

Body:
#parent {
  background: tan;
  font-size: 0;
}

#parent * {
  display: inline-block;
  width: 50px;
  height: 50px;
}
#parent div{
  margin: 0px 20px;
}

#child1 {
  background: teal;
}

#child2 {
  background: olive;
}

<div id="parent">
  <div id="child1"></div>
  <div id="child2"></div>
</div>


问:
Java Process InputStream bug?
Hey guys. So here is the deal. I have a Java program run a C++ program. The C++ process sends some doubles to the Java program by simply calling write on std::cout with some pointer casting. The Java program uses Process's getInputStream(), reads in 8 bytes and converts them into a double using some byte shifting and Double.longBitsToDouble(). I have made sure that the type sizes as well as byte orders match up between the 2 applications. Now, while this works most of the time, every so often an error occurs.

I have isolated one of the errors to a simple sequence of bytes that I seem to be unable to transfer correctly. Check out the following snippets:

```<code>#include <iostream>

int main(int argc, char** argv) {
  long long l = 0x4048e398b90ae1b6;
  char* ptr = (char*) &l;
  std::cout.write(ptr, 8);
  std::cout.flush();

  //  for (int i = 0; i < 8; ++i)
  //    std::cout.put(ptr[i]);
  //  std::cout.flush()
}
</code>```

And the Java app:

```<code>public static void main(String[] argv) throws IOException {
  Process p = Runtime.getRuntime().exec("prog.exe");
  InputStream is = p.getInputStream();

  for (int i = 0 ; i < 8; ++i) {
    System.err.print(Long.toHexString(is.read()) + " ");
  }
}
</code>```

These are pretty simple examples but they server to demonstrate my problem. When I run this on my Windows 7 machine. I get the following Java output:

```<code>b6 e1 d a b9 98 e3 48
</code>```

The expected output is

```<code>b6 e1 a b9 98 e3 48 40
</code>```

Somehow, an extra 0x0d byte is inserted. However, what is really weird is that if inside the java app we read one more byte (change the 8 to a 9), we get

```<code>b6 e1 d a b9 98 e3 48 40
</code>```

This means that the InputStream actually contained 9 bytes of data and once that extra 0x0d is removed it contains the correct data.

What do you guys think? As I mentioned before, this doesn't happen often but when it does, it is disastrous.

Thanks in advance,
zienkikk

答: C++ is translating 0x0A, which is \n, to 0x0d0a, which is \r\n. There's a method to stop it doing that, can't help you with what it is. I wouldn't use iostreams for binary data myself, I would probably just use write() or fwrite().</p>

Title: Java Process InputStream bug?

Body:
Hey guys. So here is the deal. I have a Java program run a C++ program. The C++ process sends some doubles to the Java program by simply calling write on std::cout with some pointer casting. The Java program uses Process's getInputStream(), reads in 8 bytes and converts them into a double using some byte shifting and Double.longBitsToDouble(). I have made sure that the type sizes as well as byte orders match up between the 2 applications. Now, while this works most of the time, every so often an error occurs.

I have isolated one of the errors to a simple sequence of bytes that I seem to be unable to transfer correctly. Check out the following snippets:

#include <iostream>

int main(int argc, char** argv) {
  long long l = 0x4048e398b90ae1b6;
  char* ptr = (char*) &l;
  std::cout.write(ptr, 8);
  std::cout.flush();

  //  for (int i = 0; i < 8; ++i)
  //    std::cout.put(ptr[i]);
  //  std::cout.flush()
}

And the Java app:

public static void main(String[] argv) throws IOException {
  Process p = Runtime.getRuntime().exec("prog.exe");
  InputStream is = p.getInputStream();

  for (int i = 0 ; i < 8; ++i) {
    System.err.print(Long.toHexString(is.read()) + " ");
  }
}

These are pretty simple examples but they server to demonstrate my problem. When I run this on my Windows 7 machine. I get the following Java output:

b6 e1 d a b9 98 e3 48

The expected output is

b6 e1 a b9 98 e3 48 40

Somehow, an extra 0x0d byte is inserted. However, what is really weird is that if inside the java app we read one more byte (change the 8 to a 9), we get

b6 e1 d a b9 98 e3 48 40

This means that the InputStream actually contained 9 bytes of data and once that extra 0x0d is removed it contains the correct data.

What do you guys think? As I mentioned before, this doesn't happen often but when it does, it is disastrous.

Thanks in advance,
zienkikk


问:
Rewrite/hiding some URL in .htaccess
I'm trying to get right syntax for .htaccess without any result...

I've a URL structured as domain.com/app/public/pageName .

It's working fine but I would "hide" the 'app/public/' part in browsers, basically doing something like:

```<code>[real URL] domain.com/app/public/pageName -> domain.com/pageName [what users type and see in browsers]
</code>```

I think in that way it should be more readable and seo-friendly.

As I understood from docs (and maybe it's wrong because it's not working...) I should tell to Apache to map/redirect all URL like domain.com/pageName to domain.com/app/public/pageName , but only internally, in order to show the minimal URL in users' browsers.

Right now I have something like:

```<code>RewriteEngine on

#RewriteBase /app/public/

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f

RewriteRule ^(.+)$ https://localhost/app/public/index.php?url=$1 [QSA,L]
</code>```

(I'm using full URL with https://... in order to get something that will be quick and easy to adapt when I upload all to my hosting, is it right?).

Problem is that RewriteRule actually change the URL, because it perform a redirect and URL rewrite it's not handle internally.

So, first of all: is it possible what I'm trying to do? If so, how can I handle the URL rewrite only internally?

Everything should be uploaded to a shared hosting, so I don't have other than .htaccess.
Anyway, I can consider to upgrade to a vps if there are not other possibilities...

Thanks!

==============

EDIT (should be more clear now)

tl;dr version:

I'm looking for a method that let users to type domain.com/pageName (and they will see that address in their browsers) and rewrite internally that URL in order to point to domain.com/app/public/pageName.

==============

More: after /app/public/ there can be an arbitrary number of elements, separated by / . All of these elements are appended at the end of the URL after index.php. At the end URL looks like:

```<code>  domain/app/public/index.php?url=lot/of/elements/here
</code>```

This is already working with the RewriteRule posted above, I would keep that too.
Thanks!

答:
Just for reference, I found a solution, maybe will be usefull for someone.

Basically I moved .htaccess to the root server (instead of /app/public directory) and changed the RewriteRule as follow:

```<code>RewriteEngine on
RewriteBase /app/public/

#RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f

RewriteRule ^(.*)$ index.php?url=$1 [PT]
</code>```

Now it's working (at least on localhost).

What do you think? Are there any side effects with this config?

Title: Rewrite/hiding some URL in .htaccess

Body:
I'm trying to get right syntax for .htaccess without any result...

I've a URL structured as domain.com/app/public/pageName .

It's working fine but I would "hide" the 'app/public/' part in browsers, basically doing something like:

[real URL] domain.com/app/public/pageName -> domain.com/pageName [what users type and see in browsers]

I think in that way it should be more readable and seo-friendly.

As I understood from docs (and maybe it's wrong because it's not working...) I should tell to Apache to map/redirect all URL like domain.com/pageName to domain.com/app/public/pageName , but only internally, in order to show the minimal URL in users' browsers.

Right now I have something like:

RewriteEngine on

#RewriteBase /app/public/

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f

RewriteRule ^(.+)$ https://localhost/app/public/index.php?url=$1 [QSA,L]

(I'm using full URL with https://... in order to get something that will be quick and easy to adapt when I upload all to my hosting, is it right?).

Problem is that RewriteRule actually change the URL, because it perform a redirect and URL rewrite it's not handle internally.

So, first of all: is it possible what I'm trying to do? If so, how can I handle the URL rewrite only internally?

Everything should be uploaded to a shared hosting, so I don't have other than .htaccess.
Anyway, I can consider to upgrade to a vps if there are not other possibilities...

Thanks!

==============

EDIT (should be more clear now)

tl;dr version:

I'm looking for a method that let users to type domain.com/pageName (and they will see that address in their browsers) and rewrite internally that URL in order to point to domain.com/app/public/pageName.

==============

More: after /app/public/ there can be an arbitrary number of elements, separated by / . All of these elements are appended at the end of the URL after index.php. At the end URL looks like:

  domain/app/public/index.php?url=lot/of/elements/here

This is already working with the RewriteRule posted above, I would keep that too.
Thanks!

Body:
Just for reference, I found a solution, maybe will be usefull for someone.

Basically I moved .htaccess to the root server (instead of /app/public directory) and changed the RewriteRule as follow:

RewriteEngine on
RewriteBase /app/public/

#RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f

RewriteRule ^(.*)$ index.php?url=$1 [PT]

Now it's working (at least on localhost).

What do you think? Are there any side effects with this config?


问:
creating a random background color in SASS
I am attempting to have a rollover effect have 1-3 different colors in Sass. How would I do this? Here's my code so far..

```<code>input[type=submit] {
    font-size:1.3em;
    padding:5px;
    font-family:$paragraphFont;
    width:400px;
    border:1px solid #888;
    box-sizing:border-box;
    margin-top:15px;
    cursor:pointer;
    transition:background-color .2s ease-in-out;

    &:hover {
        cursor:pointer;
        background-color:#3cde77;
    }
}

<form>
    <p>Name:</p><input type="text" />
    <p>Email:</p><input type="text" />
    <p>Message:</p><textarea></textarea>
    <input type="submit" value =" Send Message" />
</form>
</code>```

I image you could use the random() function somehow and assign my colors to a number but I don't know how.

Any thoughts guys?

答:
I was able to do this using JS. It randomly picks from 3 different colors each time your hover over the Send Message button. It then reverts to an initial grey color.

var send = document.querySelector('.send');

send.addEventListener("mouseover", function() {
  var colors3 = ["red", "green", "blue"];
  var randomColor = colors3[Math.floor(Math.random() * 3)];
  this.style.backgroundColor = randomColor;
});

send.addEventListener("mouseout", function() {
  this.style.backgroundColor = "darkgrey";
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>input[type=submit] {
  font-size: 1.3em;
  padding: 5px;
  font-family: $paragraphFont;
  width: 400px;
  border: 1px solid #888;
  box-sizing: border-box;
  margin-top: 15px;
  cursor: pointer;
  transition: background-color .2s ease-in-out;
  background-color: darkgrey;
}</code>```

<form>

Name:
<input type="text" />

Email:
<input type="text" />

Message:
<textarea></textarea>
  <input type="submit" class="send" value=" Send Message" />
</form>```

http://codepen.io/anon/pen/ryowjZ

Body:
I am attempting to have a rollover effect have 1-3 different colors in Sass. How would I do this? Here's my code so far..

input[type=submit] {
    font-size:1.3em;
    padding:5px;
    font-family:$paragraphFont;
    width:400px;
    border:1px solid #888;
    box-sizing:border-box;
    margin-top:15px;
    cursor:pointer;
    transition:background-color .2s ease-in-out;

    &:hover {
        cursor:pointer;
        background-color:#3cde77;
    }
}

<form>

Name:
<input type="text" />

Email:
<input type="text" />

Message:
<textarea></textarea>
    <input type="submit" value =" Send Message" />
</form>

I image you could use the random() function somehow and assign my colors to a number but I don't know how.

Any thoughts guys?

Body:
I was able to do this using JS. It randomly picks from 3 different colors each time your hover over the Send Message button. It then reverts to an initial grey color.

var send = document.querySelector('.send');

send.addEventListener("mouseover", function() {
  var colors3 = ["red", "green", "blue"];
  var randomColor = colors3[Math.floor(Math.random() * 3)];
  this.style.backgroundColor = randomColor;
});

send.addEventListener("mouseout", function() {
  this.style.backgroundColor = "darkgrey";
});

input[type=submit] {
  font-size: 1.3em;
  padding: 5px;
  font-family: $paragraphFont;
  width: 400px;
  border: 1px solid #888;
  box-sizing: border-box;
  margin-top: 15px;
  cursor: pointer;
  transition: background-color .2s ease-in-out;
  background-color: darkgrey;
}

<form>
  <p>Name:</p><input type="text" />
  <p>Email:</p><input type="text" />
  <p>Message:</p><textarea></textarea>
  <input type="submit" class="send" value=" Send Message" />
</form>

http://codepen.io/anon/pen/ryowjZ


问:
how to use jquery to remove option from select box
How to use jquery to delete opt1 row  ?  How about changing opt2 to become selected?
Note that the values are random numbers.</p>

```<code>      <select name="ShippingMethod" >
        <option value="8247(random)">Opt2</option>
        <option value="1939(random)" selected="selected">Opt1</option>
      </select>
</code>```

答:
It depends how you want to select it, to remove by text:

```<code>$("select[name=ShippingMethod] option").filter(function() {
    return this.text == "Opt1";
}).remove();
</code>```

Or the selected one:

```<code>$("select[name=ShippingMethod] option:selected").remove();
</code>```

Or the second one:

```<code>$("select[name=ShippingMethod] option:eq(1)").remove();
</code>```

Or the last one:

```<code>$("select[name=ShippingMethod] option:last").remove();
</code>```

To just select option 2 by text, you can use the same .filter() approach above:

```<code>$("select[name=ShippingMethod] option").filter(function() {
    return this.text == "Opt2";
}).attr("selected", true);
</code>```

You can test it here.

Body:
How to use jquery to delete opt1 row  ?  How about changing opt2 to become selected?
Note that the values are random numbers.

      <select name="ShippingMethod" >
        <option value="8247(random)">Opt2</option>
        <option value="1939(random)" selected="selected">Opt1</option>
      </select>

Body:
It depends how you want to select it, to remove by text:

$("select[name=ShippingMethod] option").filter(function() {
    return this.text == "Opt1";
}).remove();

Or the selected one:

$("select[name=ShippingMethod] option:selected").remove();

Or the second one:

$("select[name=ShippingMethod] option:eq(1)").remove();

Or the last one:

$("select[name=ShippingMethod] option:last").remove();

To just select option 2 by text, you can use the same .filter() approach above:

$("select[name=ShippingMethod] option").filter(function() {
    return this.text == "Opt2";
}).attr("selected", true);

You can test it here.


问:
Is it dangerous to mix ActiveSupport::Concern modules with vanilla modules?
I know there's a dependency management system hidden behind ActiveSupport::Concern. I do not understand it completely (and I'm not sure I am ready to yet), but in a nutshell : is it possible to mix ActiveSupport::Concern with vanilla (non ActiveSupport::Concern) modules, or are there pitfalls ?

Here are some examples of the different usages I can think of

```<code>module Vanilla
  module ModuleIncludedInASC
    # Vanilla module
  end

  module ModuleIncludedInClass
    # Vanilla module
  end

module ASC
  module ConcernIncludedInClass
    extend ActiveSupport::Concern
    ...
  end

  module ConcernIncludedInASC
    extend ActiveSupport::Concern
    ...
  end

  module ConcernIncludingVanillaModulesIncludedInClass
    extend ActiveSupport::Concern
    include Vanilla::VanillaConcernIncludedInASC
  end
  module ConcernIncludingASCConcernIncludedInASC
    extend ActiveSupport::Concern
    include ConcernIncludedInASC
  end
end

class MyFoo
  include Vanilla::ModuleIncludedInClass
  include ASC::ConcernIncludedInClass
  include ASC::ConcernIncludingVanillaModulesIncludedInClass
end

# Ans also possibly, ActiveSupport::Concern modules included in vanilla modules...?
</code>```

Could that potentially lead to problems ?

答:
It shouldn't be a problem.

I can't speak to the deep technical details, but I've never seen anyone mention it's risky, and I do this all the time. I have some models with 10+ includes. Some of those modules are using ActiveSupport::Concern, some aren't. Never encountered any issue.

I'd suggest trying it and post a new question if it does cause problems.

Body:
I know there's a dependency management system hidden behind ActiveSupport::Concern. I do not understand it completely (and I'm not sure I am ready to yet), but in a nutshell : is it possible to mix ActiveSupport::Concern with vanilla (non ActiveSupport::Concern) modules, or are there pitfalls ?

Here are some examples of the different usages I can think of

module Vanilla
  module ModuleIncludedInASC
    # Vanilla module
  end

  module ModuleIncludedInClass
    # Vanilla module
  end

module ASC
  module ConcernIncludedInClass
    extend ActiveSupport::Concern
    ...
  end

  module ConcernIncludedInASC
    extend ActiveSupport::Concern
    ...
  end

  module ConcernIncludingVanillaModulesIncludedInClass
    extend ActiveSupport::Concern
    include Vanilla::VanillaConcernIncludedInASC
  end
  module ConcernIncludingASCConcernIncludedInASC
    extend ActiveSupport::Concern
    include ConcernIncludedInASC
  end
end

class MyFoo
  include Vanilla::ModuleIncludedInClass
  include ASC::ConcernIncludedInClass
  include ASC::ConcernIncludingVanillaModulesIncludedInClass
end

# Ans also possibly, ActiveSupport::Concern modules included in vanilla modules...?

Could that potentially lead to problems ?


问:
How and where should I use the keyword "use" in php
I used use the keyword "use" generally above the class definition. Like this:

```<code><?php
namespace suites\plugins\content\agpaypal;
use \Codeception\Util\Fixtures;
use \Codeception\Verify;
use \Codeception\Specify;

class agpaypalTest extends \Codeception\Test\Unit
{
    protected $tester;
    ...
</code>```

But now I realised, that I have to put the line for the trait Specify into the class definition. Like this:

```<code> <?php
namespace suites\plugins\content\agpaypal;
use \Codeception\Util\Fixtures;
use \Codeception\Verify;

class agpaypalTest extends \Codeception\Test\Unit
{
    use \Codeception\Specify;

    protected $tester;
    ...
</code>```

I think it is because the package \Codeception\Specify; is a trait. But I do not understand why I couldn't reuse this trait when I set the line
use \Codeception\Specify;
before the class definition?

I would be happy if someone could point me to a hint or an explanaiton that explains to me where I should use the keyword "use" the best.

答:
In PHP, the keyword use is used in 3 cases:

As class name alias - simply declares short name for a class (must be declared outside of the class definition)
(manual: Using namespaces: Aliasing/Importing )

To add a trait to a class (must be declared inside (at the top) of the class definition)
(manual: Traits)

In anonymous function definition to pass variables inside the function
(manual: Anonymous functions)

Body:
I used use the keyword "use" generally above the class definition. Like this:

<?php
namespace suites\plugins\content\agpaypal;
use \Codeception\Util\Fixtures;
use \Codeception\Verify;
use \Codeception\Specify;

class agpaypalTest extends \Codeception\Test\Unit
{
    protected $tester;
    ...

But now I realised, that I have to put the line for the trait Specify into the class definition. Like this:

 <?php
namespace suites\plugins\content\agpaypal;
use \Codeception\Util\Fixtures;
use \Codeception\Verify;

class agpaypalTest extends \Codeception\Test\Unit
{
    use \Codeception\Specify;

    protected $tester;
    ...

I think it is because the package \Codeception\Specify; is a trait. But I do not understand why I couldn't reuse this trait when I set the line
use \Codeception\Specify;
before the class definition?

I would be happy if someone could point me to a hint or an explanaiton that explains to me where I should use the keyword "use" the best.


问:
JSON to XML class conversions
I cannot seem to line up the class of the Json into Linq XML.

The c.first, c.second and the c.third are highlighted and states:

"Are you missing a using directive or assembly reference."

```<code>var serializer = new JavaScriptSerializer();
var json1 = "[count:[place:{first:1,second:2,third:3}],[place:{first:11,second:22,third:33}],[place:{first:111,second:222,third:333}]]]";
var jsons = serializer.Serialize(json1);
var jsona = serializer.Deserialize<List<jClass>>(jsons);
var xmld = new XDocument(
    new XElement("count", jsona.Select(c =>
        new XElement("place",
            new XElement("first", c.first),
            new XElement("second", c.second),
            new XElement("third", c.third)
        )
    ))
);
</code>```

Class.cs

```<code>public class jClass
{
    public jNumber[] count { get; set; }
}
public class jNumber
{
    public jTopThree[] place { get; set; }
}
public class jTopThree
{
    public int first { get; set; }
    public int second { get; set; }
    public int third { get; set; }
}
</code>```

答:
```<code>        var json1 = "[{\"place\":{\"first\":1,\"second\":2,\"third\":3}},{\"place\":{\"first\":11,\"second\":22,\"third\":33}},{\"place\":{\"first\":111,\"second\":222,\"third\":333}}]";
        XmlDocument deserializeXmlNode;
        if (json1.IndexOf("[", StringComparison.OrdinalIgnoreCase) == 0)
        {
            deserializeXmlNode = Newtonsoft.Json.JsonConvert.DeserializeXmlNode($"{{\"items\":{json1}}}", "source");
        }
        else
        {
            deserializeXmlNode = Newtonsoft.Json.JsonConvert.DeserializeXmlNode(json1, "source");
        }

        Console.WriteLine(deserializeXmlNode.OuterXml);
</code>```

If you want just copy to XML and can afford Nugget package, go for Newtonsoft.Json and modify the code above to suite your needs. I have slighlty changed the input json, because it was not valid per http://www.json.org/ . It should work with any valid JSON though.

http://www.newtonsoft.com/json/help/html/ConvertingJSONandXML.htm

How to convert JSON to XML or XML to JSON?

Title: JSON to XML class conversions

Body:
I cannot seem to line up the class of the Json into Linq XML.

The c.first, c.second and the c.third are highlighted and states:

"Are you missing a using directive or assembly reference."

var serializer = new JavaScriptSerializer();
var json1 = "[count:[place:{first:1,second:2,third:3}],[place:{first:11,second:22,third:33}],[place:{first:111,second:222,third:333}]]]";
var jsons = serializer.Serialize(json1);
var jsona = serializer.Deserialize<List<jClass>>(jsons);
var xmld = new XDocument(
    new XElement("count", jsona.Select(c =>
        new XElement("place",
            new XElement("first", c.first),
            new XElement("second", c.second),
            new XElement("third", c.third)
        )
    ))
);

Class.cs

public class jClass
{
    public jNumber[] count { get; set; }
}
public class jNumber
{
    public jTopThree[] place { get; set; }
}
public class jTopThree
{
    public int first { get; set; }
    public int second { get; set; }
    public int third { get; set; }
}

Body:
        var json1 = "[{\"place\":{\"first\":1,\"second\":2,\"third\":3}},{\"place\":{\"first\":11,\"second\":22,\"third\":33}},{\"place\":{\"first\":111,\"second\":222,\"third\":333}}]";
        XmlDocument deserializeXmlNode;
        if (json1.IndexOf("[", StringComparison.OrdinalIgnoreCase) == 0)
        {
            deserializeXmlNode = Newtonsoft.Json.JsonConvert.DeserializeXmlNode($"{{\"items\":{json1}}}", "source");
        }
        else
        {
            deserializeXmlNode = Newtonsoft.Json.JsonConvert.DeserializeXmlNode(json1, "source");
        }

        Console.WriteLine(deserializeXmlNode.OuterXml);

If you want just copy to XML and can afford Nugget package, go for Newtonsoft.Json and modify the code above to suite your needs. I have slighlty changed the input json, because it was not valid per http://www.json.org/ . It should work with any valid JSON though.

http://www.newtonsoft.com/json/help/html/ConvertingJSONandXML.htm

How to convert JSON to XML or XML to JSON?


问:
Why is my 2D array of double not accepted as a valid parameter?
I have been trying to resolve an undefined reference error for hours caused by my 2D array, but I don't know what I am missing. I have a 2D array.

```<code>#include <iostream>
#include "ServoJoint.h"
#include "JointedLeg.h"
#include "TwoJointLeg.h"
#include "ThreeJointLeg.h"

int main() {

    //2D array containing the 7 calibrated positions for each of the 10 servo motors
    size_t servoCalibrations[10][7]={{143, 190, 245, 305, 365, 410, 467},
                                     {143, 205, 260, 320, 377, 423, 475},
                                     {115, 168, 230, 280, 340, 392, 440},
                                     {130, 182, 235, 290, 340, 397, 455},
                                     {135, 190, 235, 290, 345, 400, 455},
                                     {140, 190, 250, 305, 355, 415, 465},
                                     {130, 185, 240, 300, 355, 415, 465},
                                     {140, 200, 245, 300, 355, 410, 460},
                                     {140, 200, 245, 300, 355, 410, 460},
                                     {140, 200, 245, 300, 355, 410, 460}};

    double walkCycle[4][2]= {{45, 45},
                            {60, 150},
                            {60, 135},
                            {30, 60}};

    //Array of pointers to 10 size_t arrays of size 7
    //This is because C++ doesn't allow accessing an entire row/column of a 2D array
    //or I don't know how to
    size_t * calibrationArrays[10];
    for(size_t i=0; i<10; i++){
        size_t * tmp= new size_t[7];
        for(size_t j=0; j<7; j++){
            tmp[j]= servoCalibrations[i][j];
        }
        calibrationArrays[i]= tmp;
    }

    //Array of pointers to 10 ServoJoint objects
    ServoJoint * servoJoints[10];

    //Dynamically allocate 10 ServoJoint objects
    for(size_t i=0; i<10; i++){
        servoJoints[i]= new ServoJoint(i, 7, calibrationArrays[i]);
    }

    for(size_t i=0; i<10; i++){
        std::cout << "Servo motor " << i+1 << " has the following PWM values: ";
        for(size_t j=0; j<7; j++){
            std::cout << servoJoints[i]->getPWM(-90+(double)(j*30)) << " ";
        }
        std::cout<< std::endl;
    };

    //Array of pointers to 2 ThreeJointLeg objects
    ThreeJointLeg * threeJointLegs[2];

    //Dynamically allocate 2 ThreeJointLeg objects
    for(size_t i=0; i<6; i+=3){
        threeJointLegs[i]= new ThreeJointLeg(servoJoints[i], servoJoints[i+1], servoJoints[i+2], 1-(i%2)*2, walkCycle);
    }

    //Array of pointers to 2 TwoJointLeg objects
    TwoJointLeg * twoJointLegs[2];

    //Dynamically allocate 2 TwoJointLeg objects
    for(size_t i=6; i<10; i+=2){
        twoJointLegs[i]= new TwoJointLeg(servoJoints[i],servoJoints[i+1], 1, walkCycle);
    }

    return 0;
}
</code>```

JointedLeg.h:

```<code>#ifndef ROBOTLEG_JointedLeg_H
#define ROBOTLEG_JointedLeg_H

#include "ServoJoint.h"

class JointedLeg{

private:
//Pointers to the 2 ServoJoint objects for the upper and lower joint
ServoJoint * upperJoint;
ServoJoint * lowerJoint;

int isRight;

//2D array, where each of the four rows represents each phase in the walk cycle and each column of each row
//represents the upper and lower joint angles respectively

//walkCycle[0][]= home
//walkCycle[1][]= step forward
//walkCycle[2][]= step down
//walkCycle[3][]= step back
double walkCycle[4][2];

public:
JointedLeg(ServoJoint * joint1, ServoJoint * joint2, int side, double givenWalk[][2]);
</code>```

JointedLeg.cpp:

```<code>#include "JointedLeg.h"

JointedLeg::JointedLeg(ServoJoint * joint1, ServoJoint * joint2, int side, double givenWalk[][2]):upperJoint(joint1), lowerJoint(joint2), isRight(side){
    for(size_t i=0; i<4; i++){
        for(size_t j=0; j<2; j++){
            walkCycle[i][j]= givenWalk[i][j];
        }
    }
}
</code>```

TwoJointLeg.h:

```<code>#ifndef QUADRUPEDROBOT_TWOJOINTLEG_H
#define QUADRUPEDROBOT_TWOJOINTLEG_H

#include "JointedLeg.h"

class TwoJointLeg : public JointedLeg{

public:
    TwoJointLeg(ServoJoint * joint1, ServoJoint * joint2, int side, double givenWalk[][2]);

};

#endif //QUADRUPEDROBOT_TWOJOINTLEG_H
</code>```

TwoJointLeg.cpp:

```<code>#include "TwoJointLeg.h"

TwoJointLeg::TwoJointLeg(ServoJoint * joint1, ServoJoint * joint2, int side, double givenWalk[][2])
        :JointedLeg(joint1, joint2, side, givenWalk){}
</code>```

and I wish to pass this as a parameter to the following constructor:

```<code>JointedLeg(ServoJoint * joint1, ServoJoint * joint2, int side, double givenWalk[][2]);
</code>```

I read on Passing a 2D array to a C++ function that when I declare a 2D array with 2 brackets, i.e. [][], I can do the same in the function header and simply pass the array variable name, which is what I believe I have done.

However, my compiler keeps telling me that I am passing a "double (*) [2]." I am aware that a 2D array is technically a pointer to sub-arrays and that the first array can be decayed to a pointer, but why is there a mismatch in the parameter type when I have the same syntax in the function call and the definition?

I've tried both of these in the function header:

```<code>double givenWalk[4][2]
double givenWalk[][2]
</code>```

答:
Look at your array indexes that you used in cycles:</p>

```<code>//Array of pointers to 2 ThreeJointLeg objects
ThreeJointLeg * threeJointLegs[2];

//Dynamically allocate 2 ThreeJointLeg objects
for(size_t i=0; i<6; i+=3){
    threeJointLegs[i/3]= new ThreeJointLeg(servoJoints[i], servoJoints[i+1], servoJoints[i+2], 1-(i%2)*2, walkCycle);
}

//Array of pointers to 2 TwoJointLeg objects
TwoJointLeg * twoJointLegs[2];

//Dynamically allocate 2 TwoJointLeg objects
for(size_t i=6; i<10; i+=2){
    twoJointLegs[(i-6)/2]= new TwoJointLeg(servoJoints[i],servoJoints[i+1], 1, walkCycle);
}
</code>```

Body:
I have been trying to resolve an undefined reference error for hours caused by my 2D array, but I don't know what I am missing. I have a 2D array.

#include <iostream>
#include "ServoJoint.h"
#include "JointedLeg.h"
#include "TwoJointLeg.h"
#include "ThreeJointLeg.h"

int main() {

    //2D array containing the 7 calibrated positions for each of the 10 servo motors
    size_t servoCalibrations[10][7]={{143, 190, 245, 305, 365, 410, 467},
                                     {143, 205, 260, 320, 377, 423, 475},
                                     {115, 168, 230, 280, 340, 392, 440},
                                     {130, 182, 235, 290, 340, 397, 455},
                                     {135, 190, 235, 290, 345, 400, 455},
                                     {140, 190, 250, 305, 355, 415, 465},
                                     {130, 185, 240, 300, 355, 415, 465},
                                     {140, 200, 245, 300, 355, 410, 460},
                                     {140, 200, 245, 300, 355, 410, 460},
                                     {140, 200, 245, 300, 355, 410, 460}};

    double walkCycle[4][2]= {{45, 45},
                            {60, 150},
                            {60, 135},
                            {30, 60}};

    //Array of pointers to 10 size_t arrays of size 7
    //This is because C++ doesn't allow accessing an entire row/column of a 2D array
    //or I don't know how to
    size_t * calibrationArrays[10];
    for(size_t i=0; i<10; i++){
        size_t * tmp= new size_t[7];
        for(size_t j=0; j<7; j++){
            tmp[j]= servoCalibrations[i][j];
        }
        calibrationArrays[i]= tmp;
    }

    //Array of pointers to 10 ServoJoint objects
    ServoJoint * servoJoints[10];

    //Dynamically allocate 10 ServoJoint objects
    for(size_t i=0; i<10; i++){
        servoJoints[i]= new ServoJoint(i, 7, calibrationArrays[i]);
    }

    for(size_t i=0; i<10; i++){
        std::cout << "Servo motor " << i+1 << " has the following PWM values: ";
        for(size_t j=0; j<7; j++){
            std::cout << servoJoints[i]->getPWM(-90+(double)(j*30)) << " ";
        }
        std::cout<< std::endl;
    };

    //Array of pointers to 2 ThreeJointLeg objects
    ThreeJointLeg * threeJointLegs[2];

    //Dynamically allocate 2 ThreeJointLeg objects
    for(size_t i=0; i<6; i+=3){
        threeJointLegs[i]= new ThreeJointLeg(servoJoints[i], servoJoints[i+1], servoJoints[i+2], 1-(i%2)*2, walkCycle);
    }

    //Array of pointers to 2 TwoJointLeg objects
    TwoJointLeg * twoJointLegs[2];

    //Dynamically allocate 2 TwoJointLeg objects
    for(size_t i=6; i<10; i+=2){
        twoJointLegs[i]= new TwoJointLeg(servoJoints[i],servoJoints[i+1], 1, walkCycle);
    }

    return 0;
}

JointedLeg.h:

#ifndef ROBOTLEG_JointedLeg_H
#define ROBOTLEG_JointedLeg_H

#include "ServoJoint.h"

class JointedLeg{

private:
//Pointers to the 2 ServoJoint objects for the upper and lower joint
ServoJoint * upperJoint;
ServoJoint * lowerJoint;

int isRight;

//2D array, where each of the four rows represents each phase in the walk cycle and each column of each row
//represents the upper and lower joint angles respectively

//walkCycle[0][]= home
//walkCycle[1][]= step forward
//walkCycle[2][]= step down
//walkCycle[3][]= step back
double walkCycle[4][2];

public:
JointedLeg(ServoJoint * joint1, ServoJoint * joint2, int side, double givenWalk[][2]);

JointedLeg.cpp:

#include "JointedLeg.h"

JointedLeg::JointedLeg(ServoJoint * joint1, ServoJoint * joint2, int side, double givenWalk[][2]):upperJoint(joint1), lowerJoint(joint2), isRight(side){
    for(size_t i=0; i<4; i++){
        for(size_t j=0; j<2; j++){
            walkCycle[i][j]= givenWalk[i][j];
        }
    }
}

TwoJointLeg.h:

#ifndef QUADRUPEDROBOT_TWOJOINTLEG_H
#define QUADRUPEDROBOT_TWOJOINTLEG_H

#include "JointedLeg.h"

class TwoJointLeg : public JointedLeg{

public:
    TwoJointLeg(ServoJoint * joint1, ServoJoint * joint2, int side, double givenWalk[][2]);

};

#endif //QUADRUPEDROBOT_TWOJOINTLEG_H

TwoJointLeg.cpp:

#include "TwoJointLeg.h"

TwoJointLeg::TwoJointLeg(ServoJoint * joint1, ServoJoint * joint2, int side, double givenWalk[][2])
        :JointedLeg(joint1, joint2, side, givenWalk){}

and I wish to pass this as a parameter to the following constructor:

JointedLeg(ServoJoint * joint1, ServoJoint * joint2, int side, double givenWalk[][2]);

I read on Passing a 2D array to a C++ function that when I declare a 2D array with 2 brackets, i.e. [][], I can do the same in the function header and simply pass the array variable name, which is what I believe I have done.

However, my compiler keeps telling me that I am passing a "double (*) [2]." I am aware that a 2D array is technically a pointer to sub-arrays and that the first array can be decayed to a pointer, but why is there a mismatch in the parameter type when I have the same syntax in the function call and the definition?

I've tried both of these in the function header:

double givenWalk[4][2]
double givenWalk[][2]

Body:
Look at your array indexes that you used in cycles:

//Array of pointers to 2 ThreeJointLeg objects
ThreeJointLeg * threeJointLegs[2];

//Dynamically allocate 2 ThreeJointLeg objects
for(size_t i=0; i<6; i+=3){
    threeJointLegs[i/3]= new ThreeJointLeg(servoJoints[i], servoJoints[i+1], servoJoints[i+2], 1-(i%2)*2, walkCycle);
}

//Array of pointers to 2 TwoJointLeg objects
TwoJointLeg * twoJointLegs[2];

//Dynamically allocate 2 TwoJointLeg objects
for(size_t i=6; i<10; i+=2){
    twoJointLegs[(i-6)/2]= new TwoJointLeg(servoJoints[i],servoJoints[i+1], 1, walkCycle);
}


答:
Quick guess as to question two

```<code>$('select[name=ShippingMethod]').val('19395ss');
</code>```

Nick Carver seems to have answered the first question.

Title: how to use jquery to remove option from select box

Body:
Quick guess as to question two

$('select[name=ShippingMethod]').val('19395ss');

Nick Carver seems to have answered the first question.


问:
The simplest way to cut off unnecessary dots in octave/matlab
I have coordinates of dots (x,y) stored in 1206x2 matrix called data. The command plot(data(:,1),data(:,2)) gives that picture:

I've found maximums in my data with findpeaks command:

```<code>[pks,loc,smth] = findpeaks(data(:,2));
</code>```

And then plot them on previous graph:

```<code>plot(mod(:,1),mod(:,2),mod(loc,1),pks,'o')
</code>```

So, the question is: what is the simplest way to cut off maximums which I do not need, I mean the maximums below red line on this picture:

UPD:
The best way I've found by now is to use "MinPeakDistance" parameter.

答:
try using envelope built-in function:

```<code>% generate signal
x = 1:200;
y = x.*sin(x/5).*sin(3*x);
% get its envelope
npeak = 2;
[yupper,ylower] = envelope(y,npeak,'peak');
plot(x,y,x,yupper)
</code>```

and then you can just add/subtract constant from this envelope to shift it along y-axis.

Body:
I have coordinates of dots (x,y) stored in 1206x2 matrix called data. The command plot(data(:,1),data(:,2)) gives that picture:

I've found maximums in my data with findpeaks command:

[pks,loc,smth] = findpeaks(data(:,2));

And then plot them on previous graph:

plot(mod(:,1),mod(:,2),mod(loc,1),pks,'o')

So, the question is: what is the simplest way to cut off maximums which I do not need, I mean the maximums below red line on this picture:

UPD:
The best way I've found by now is to use "MinPeakDistance" parameter.

Body:
try using envelope built-in function:

% generate signal
x = 1:200;
y = x.*sin(x/5).*sin(3*x);
% get its envelope
npeak = 2;
[yupper,ylower] = envelope(y,npeak,'peak');
plot(x,y,x,yupper)

and then you can just add/subtract constant from this envelope to shift it along y-axis.


问:
Web API Post Issue
I've a Web API, where I have five list of cricketers. By using a Web Form I can perform CRUD operation. When I'm submitting on Get Cricketers then I able to get all the list of cricketers which I passed in my controller as static. I make code for post in my Web Form class and want post one cricketer When I click on to PostCricketer button. It is posted successfully but have some issue that Cricketer should not be insert with same rank, in ascending order. Please help The screenshot points are

After clicking on get cricketers I've successfully get all five cricketers

The inserted record should be in ascending order Duplicate

Rank should not be inserted, should be shows a simple label message that Cricketer already exist with this rank.

This is my Controller Code

```<code>public class CricketersController : ApiController
{
    public static List<Cricketer> cricketers = InitCricketers();
    public IEnumerable<Cricketer> Get()
    {
        return cricketers;
    }
    public Cricketer Get(int id)
    {
        return cricketers.Where(c => c.Rank == id).FirstOrDefault();
    }
    public void Post(Cricketer cricketer)
    {
        cricketers.Add(cricketer);
    }
    public void Put(Cricketer newCricketer)
    {
        Cricketer cricketer = cricketers.Where(c => c.Rank == newCricketer.Rank).FirstOrDefault();
        cricketers.Remove(cricketer);
        cricketers.Add(newCricketer);
    }
    public void Delete(int rank)
    {
        Cricketer cDel = cricketers.Where(p => p.Rank == rank).FirstOrDefault();
        cricketers.Remove(cDel);
    }
    private static List<Cricketer> InitCricketers()
    {
        List<Cricketer> cricketers = new List<Cricketer>();
        cricketers.Add(new Cricketer
        {
            Rank = 1,
            Name = "A.B. de Villiers",
            Runs = 5000
        });
        cricketers.Add(new Cricketer
        {
            Rank = 2,
            Name = "D.A.Warner",
            Runs = 10000
        });
        cricketers.Add(new Cricketer
        {
            Rank = 3,
            Name = "ViratKohli",
            Runs = 8480
        });
        cricketers.Add(new Cricketer
        {
            Rank = 4,
            Name = "J.E.Root",
            Runs = 6620
        });
        cricketers.Add(new Cricketer
        {
            Rank = 5,
            Name = "F.duPlessis",
            Runs = 2000
        });
        return cricketers;
    }
</code>```

This is my PostButton Code

```<code>protected void btnPostCricketer_Click(object sender, EventArgs e)
{
    lblCricketerPosted.Text = "";
    int crank = Int32.Parse(txtNewCricketerRank.Text);
    string cName = txtNewCricketerName.Text;
    int cRuns = int.Parse(txtNewCricketerRuns.Text);
    Cricketer newCricketer = new Cricketer
    {
        Rank = crank,
        Name = cName,
        Runs = cRuns
    };
    HttpResponseMessage response = client.PostAsJsonAsync(address.ToString(), newCricketer).Result;

    // Check that response was successful or throw exception
    response.EnsureSuccessStatusCode();
    response.Content.ReadAsAsync<HttpResponseMessage>().Wait();
    lblCricketerPosted.Text = "New Crciketer Added!";

    btnGetAllCricketers_Click(sender, e);
}
</code>```

答:
The list by itself won't check if the rank value is already added so you need to check the value before adding it to the list.
Also, you should return a response to the requester if the request was successful or not. In this example I just return a IHttpActionResult

```<code>public IHttpActionResult Post(Cricketer cricketer)
{
    if(!cricketer.Any(a=>a.Rank == cricketer.Rank))
    {
        cricketers.Add(cricketer);
        Return Ok("Success");
    }else{
        Return Content(HttpStatusCode.InternalServerError, "Rank already exists!"); //You could use a more suitable http code here
    }
}
</code>```

And to get the values in ascending order you could

```<code>public IEnumerable<Cricketer> Get()
{
    return cricketers.OrderBy(x => x.Rank).ToList();
}
</code>```

Title: Web API Post Issue

Body:
I've a Web API, where I have five list of cricketers. By using a Web Form I can perform CRUD operation. When I'm submitting on Get Cricketers then I able to get all the list of cricketers which I passed in my controller as static. I make code for post in my Web Form class and want post one cricketer When I click on to PostCricketer button. It is posted successfully but have some issue that Cricketer should not be insert with same rank, in ascending order. Please help The screenshot points are

After clicking on get cricketers I've successfully get all five cricketers

The inserted record should be in ascending order Duplicate

Rank should not be inserted, should be shows a simple label message that Cricketer already exist with this rank.

This is my Controller Code

public class CricketersController : ApiController
{
    public static List<Cricketer> cricketers = InitCricketers();
    public IEnumerable<Cricketer> Get()
    {
        return cricketers;
    }
    public Cricketer Get(int id)
    {
        return cricketers.Where(c => c.Rank == id).FirstOrDefault();
    }
    public void Post(Cricketer cricketer)
    {
        cricketers.Add(cricketer);
    }
    public void Put(Cricketer newCricketer)
    {
        Cricketer cricketer = cricketers.Where(c => c.Rank == newCricketer.Rank).FirstOrDefault();
        cricketers.Remove(cricketer);
        cricketers.Add(newCricketer);
    }
    public void Delete(int rank)
    {
        Cricketer cDel = cricketers.Where(p => p.Rank == rank).FirstOrDefault();
        cricketers.Remove(cDel);
    }
    private static List<Cricketer> InitCricketers()
    {
        List<Cricketer> cricketers = new List<Cricketer>();
        cricketers.Add(new Cricketer
        {
            Rank = 1,
            Name = "A.B. de Villiers",
            Runs = 5000
        });
        cricketers.Add(new Cricketer
        {
            Rank = 2,
            Name = "D.A.Warner",
            Runs = 10000
        });
        cricketers.Add(new Cricketer
        {
            Rank = 3,
            Name = "ViratKohli",
            Runs = 8480
        });
        cricketers.Add(new Cricketer
        {
            Rank = 4,
            Name = "J.E.Root",
            Runs = 6620
        });
        cricketers.Add(new Cricketer
        {
            Rank = 5,
            Name = "F.duPlessis",
            Runs = 2000
        });
        return cricketers;
    }

This is my PostButton Code

protected void btnPostCricketer_Click(object sender, EventArgs e)
{
    lblCricketerPosted.Text = "";
    int crank = Int32.Parse(txtNewCricketerRank.Text);
    string cName = txtNewCricketerName.Text;
    int cRuns = int.Parse(txtNewCricketerRuns.Text);
    Cricketer newCricketer = new Cricketer
    {
        Rank = crank,
        Name = cName,
        Runs = cRuns
    };
    HttpResponseMessage response = client.PostAsJsonAsync(address.ToString(), newCricketer).Result;

    // Check that response was successful or throw exception
    response.EnsureSuccessStatusCode();
    response.Content.ReadAsAsync<HttpResponseMessage>().Wait();
    lblCricketerPosted.Text = "New Crciketer Added!";

    btnGetAllCricketers_Click(sender, e);
}

Body:
The list by itself won't check if the rank value is already added so you need to check the value before adding it to the list.
Also, you should return a response to the requester if the request was successful or not. In this example I just return a IHttpActionResult

public IHttpActionResult Post(Cricketer cricketer)
{
    if(!cricketer.Any(a=>a.Rank == cricketer.Rank))
    {
        cricketers.Add(cricketer);
        Return Ok("Success");
    }else{
        Return Content(HttpStatusCode.InternalServerError, "Rank already exists!"); //You could use a more suitable http code here
    }
}

And to get the values in ascending order you could

public IEnumerable<Cricketer> Get()
{
    return cricketers.OrderBy(x => x.Rank).ToList();
}


问:
Execution speed problems on Edge and Safari
I have a suite of WebDriver tests that run perfectly in Chrome, Firefox and IE.  When I try the same code on Edge or Safari, I encounter an identical problem: the tests run too fast and try to click things before the page fully loads. I've played with WebDriverWait, ExplicitWait, etc. to no avail.

When I put sleeps in various locations, the tests slow down enough so they work, but obviously I don't want to do that.  Anyone know of a simple way to slow down test execution - or if there is a common problem with these 2 browsers?  Thanks.

答:
if you have tried WebDriverWait, ExplicitWait, and you don't want to use sleep, you can try use below code:

def waitForElement(driver, by, value):
    elements = driver.find_elements(by, value)
    i=0
    while i < 1000 and len(elements)<1:
        sleep(0.01)
        i = i+1
    if i == 1000:
        print "can not find the element in 10 seconds"
        return False
    else:
        print "find element in %d seconds" % i*0.01
        return True```


问:
How to add new item to top of Dojo DataGrid
I'm trying to implement a data item panel which is more like a mailing system. Where I need to add every new item to top of datagrid. After googling for a long time, I could still not find a proper dojo implementation of my requirement. Any help/guidance me to achieve this will be appreciated

Thank you.

答:
Check the file dojo-release-1.5.0-src/dojox/grid/tests/test_edit_keyNav.html

There is a function in store called newItem()
Just add an item in the store this will be added to the grid. Depending on the sorting in the grid the row is added to the grid.

If you you need some advanced techniques like server push check following url
http://www.sitepen.com/blog/2010/10/31/dojo-websocket/