Q:

Phantom space in string

I have an input field which is being sent to the server, checked, then returned. Strangely though, by the time it has returned, it has what looks like a tab break at the end.
jQuery:
var name = $("#name").val();
$.ajax({
    url: "JSON/checkName.php",
    data: "name=" + name,
    method: "POST"
})
.done(function(msg) {
    alert("msg: " + msg + ". Name: " + name + ".");
    }
})

checkName.php:
<?php
require_once "../dbPDO.php";

function clean($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;
}

$name = clean($_POST["name"]);

$sql = "SELECT * FROM `names` WHERE `name` = '$name' AND `valid` = TRUE";
$stmt = $DBcon->prepare($sql);
$stmt->execute();
$count = $stmt->rowCount();
if($count == 1) {
    echo $name;
} else {
    echo "Error";
}
?>

Upon running this, the alert dialog displays:
msg: James  . Name: James.

...when it should display:
msg: James. Name: James.

Any ideas?

A:

If you have any whitespace after the closing ?> tag it will end up in your output. You don't need the end tag anyway (see Why would one omit the close tag?).


Q:

Express Routing Issue using moment.js

I'm new to express.js and backend routing. Below is the exact error and source code I have for my server so far. Any direction as to what the issue is would be appreciated. I've already tried using res.end() with plain text inside of it, and it is still returning the same error.
Thanks everyone.
_http_outgoing.js:489

throw new Error('Can\'t set headers after they are sent.');
^
Error: Can't set headers after they are sent.
   at validateHeader (_http_outgoing.js:489:11)
    at ServerResponse.setHeader (_http_outgoing.js:496:3)
    at Array.write (/app/node_modules/finalhandler/index.js:254:9)
    at listener (/app/node_modules/on-finished/index.js:169:15)
    at onFinish (/app/node_modules/on-finished/index.js:100:5)
    at callback (/app/node_modules/ee-first/index.js:55:10)
    at IncomingMessage.onevent (/app/node_modules/ee-first/index.js:93:5)
    at emitNone (events.js:105:13)
    at IncomingMessage.emit (events.js:207:7)
    at endReadableNT (_stream_readable.js:1059:12)

`
on this code:
`
//server.js

// Set static routes and set view engine as pug
app.use(express.static('public'));
app.set('view engine', 'pug');

// Pug entry point to API

app.get('/', function (req, res) {
  res.render('index', { title: 'Timestamp Microservice API'})
});

app.get('/:time',function (req,res, moment) {
  var time = req.params.time;
  return moment(time, 'MM-DD-YYYY').isValid();
});

// listen for requests :)

var listener = app.listen(process.env.PORT, function () {
  console.log('Your app is listening on port ' + listener.address().port);
});

```

A:

app.get('/:time',function (req,res, moment) {
  var time = req.params.time;
  return moment(time, 'MM-DD-YYYY').isValid();
});

In the above code you have basically exposed the next handler and called it moment.
To access momentjs, just place var moment = require('moment'); at the top of your unit, not need to pass into any parameters.
Next, if all your wanting then to do is valididate dates using momentjs, just res.end it's results.
eg.
app.get('/:time',function (req,res) {
  var time = req.params.time;
  res.end( moment(time, 'MM-DD-YYYY').isValid() );
});

Also in the above route we have  /:time  this would match urls like  /anything  you could do this, but normally you would apply a route for something like this..  eg..   app.get('/time/:time',  this would then match url's like  /time/09-01-2017 stopping collisions from say index.html favicon.ico etc.


Q:

Is eager loading same as join fetch?

Is eager fetch same as join fetch?
I mean whether eagerly fetching a has-many relation fires 2 queries or a single join query?
How does rails active record implement a join fetch of associations as it doesnt know the table's meta-data in first hand (I mean columns in the table)? Say for example i have
people - id, name
things - id, person_id, name
person has one-to-many relation with the things. So how does it generate the query with all the column aliases even though it cannot know it when i do a join fetch on people?

A:

An answer hasn't been accepted so I will try to answer your questions as I understand them:

"how does it know all the fields available in a table?"

It does a SQL query for every class that inherits from ActiveRecord::Base.  If the class is 'Dog', it will do a query to find the column names of the table 'dogs'.  In production mode it should only do this query once per run of the server -- in development mode it does it a lot.  The query will differ depending on the database you use, and it is usually an expensive query.

"Say if i have a same name for column in a table and in an associated table how does it resolve this?"

If you are doing a join, it generates sql using the table names as prefixes to avoid ambiguities.  In fact, if you are doing a join in Rails and want to add a condition (using custom SQL) for name, but both the main table and join table have a name column, you need to specify the table name in your sql.  (e.g. Human.join(:pets).where("humans.name = 'John'"))

"I mean whether eagerly fetching a has-many relation fires 2 queries or a single join query?"

Different Rails versions are different.  I think that early versions did a single join query at all times.  Later versions would sometimes do multiple queries and sometimes a single join query, based on the realization that a single join query isn't always as performant as multiple queries.  I'm not sure of the exact logic that it uses to decide.  Recently, in Rails 3, I am seeing multiple queries happening in my current codebase -- but maybe it sometimes does a join as well, I'm not sure.


Q:

Check if directory is owned by specific user

Is it possible to check if a folder (and all subfolders) are owned by a specific user/rights?
As Example: Can I use cmake to check if /var/www/** is owned by www-data and has the permission to execute files?

A:

CMake does not have this functionality built-in, but you can use a third party CMake module to obtain file permission and owner information.


Q:

Utilizing Async NPM Module

So... I recently came across this node module: async. I just need a little "show and tell" or a Best Practice approach for the situation I have below. Below you can see my function GetBearerToken which takes an argument {bearer_token:token} without an issue.
My issue is the variable ss. I want to use it outside of this function and pass it to another function to do something. Of course when I try and access ss, it's undefined. I have tried some of the ways of making this work as indicated in the documentation, but I am apparently missing something. So any help would be great... Thanks
GetBearerToken({
      bearer_token: token
    }, function(error, result) {
      if (error) throw error;
      if (result) {
        var resultset
        var i;
        for (i = 0; i < result.length; i++) {
          resultset = (simpleObjectify(result[i].meta, result[i].rows))
        }

        var jstring = JSON.stringify(resultset);
        var obj = JSON.parse(jstring);
        var ss = obj[0].uuid;
        console.log(ss)
      })

Outside of function ss is undefined.

A:

First read this
What is the scope of variables in JavaScript?

You can try using .waterfall method

waterfall(tasks, [callback])
Runs the tasks array of functions in series, each passing their
  results to the next in the array. However, if any of the tasks pass an
  error to their own callback, the next function is not executed, and
  the main callback is immediately called with the error.

One example for what you are trying to accomplish
async.waterfall([
      function(callback) {

        GetBearerToken({
              bearer_token: token
            }, function(error, result) {
              if (error) throw error;
              if (result) { // *note* don't forget to handle the result properly if an error occurs or the result is not what you expected.
                var resultset
                var i;
                for (i = 0; i < result.length; i++) {
                  resultset = (simpleObjectify(result[i].meta, result[i].rows))
                }

                var jstring = JSON.stringify(resultset);
                var obj = JSON.parse(jstring);
                var ss = obj[0].uuid;
                callback(null, ss); // call the next callback in waterfall with ss value
              }
            )
          },
          function(arg1, callback) {
            // arg1 now equals ss value
            callback(null,'all completed');
          }
      ],
      function(err, result) {
        // result now equals 'all completed'
      });

but since the code above seems already a step towards to wrong direction when it
comes to debugging. But take a look at example of  .waterfall who it breaks down the callbacks and then calls the .waterfall method.


Q:

MySQL entry storing with blank value in PHP

Have the following code that's executed when a script is ran. (I've just changed the login for display purposes).
<?php

    $conn = mysql_connect("localhost", "root", "pw123");

    mysql_select_db("test_db", $conn);

    $sql = "INSERT INTO test_table (fname)
    VALUES ('$fname')";

    mysql_query($sql);

    mysql_close($conn);

?>

I've edited the code down slightly so it doesn't show every value I'm trying to enter, but essentially, everything is entering as a blank value, or in the case of numerical inputs is defaulting to 0. I can't seem to figure out why this is. The variables are definitely not blank before hand as I've got them out putting on the web page to test as such.
For reference I assign $fname a value when the input box is changed using :
   fname = $("#fname").val();

A:

(Posted on behalf of OP):
Solved this myself anyway, instead of executing the MySQL statements in the initial page that user enters data, I moved it to the secondary web page, which opens once a user has submitted their information.


Q:

Enable softlayer ohai plugin

I wanted to enable the softlayer ohai plugin so that the softlayer metadata will be collected.
I have included the ohai recipe in the chef node's run list. I can see it when I run
knife node show NODE_ID

The softlayer.rb file seems to be missing on the chef node at  /opt/chef/embedded/apps/ohai/lib/ohai/plugins. Lots of plugins are missing at that location.
What might be wrong? What do I need to do to collect the softlayer metadata ?

A:

You need to give ohai a hint. Therefore, create a file called /etc/chef/ohai/hints/softlayer.json with content {}.
Then, this check should trigger calls to the metadata service, which finally populates the automatic attributes.
For debugging purpose, try on the node:
ohai softlayer

After the chef run, these automatic attributes can be read from the chef server with:
knife node show <nodename> -a softlayer


Q:

Door automatic closer - Can it be tightened?

 This is used to automatically close my shelf doors.

What is its exact name so that I may google better for information.
More specifically, I have a similar one with a damper added on top which is getting slack and mis aligned, possibly because of rust (its right under the sink and frequently gets wet). Is it possible to make it last a little longer and tighten it or adjust it in anyway or would I need to just replace it?

Specifically this is the problem I am trying to fix

And this is the faulty hinge

A:

That is a 35mm cup hinge, sometimes known as a Euro hinge.
They wear out over time, so replacement is a cheap and cheerful option. If you buy a cheap one (say, at a big box store), you'll need to replace it at some point; if you buy a Blum/ Hafele/ Salice or other high-end replacement, it'll last as long as the cabinet.
When buying, you'll be faced with a staggering number of options regarding "overlay" and opening angle. Best bet is to remove the existing hinge and bring it into a brick/mortar place. Otherwise, a bit of work googling will allow you to match it up. One other option: you can get ones that clip on (as opposed to being screwed in place), which is very convenient.
Be gentle with the screwdriver when re-attaching the hinges... particle board won't take much abuse. A toothpick and some glue in the hole might help if things feel loose.


Q:

Using bind_param with arrays and loops

according to this example for prepared statements  I first bind parameters and then set values for the parameters.
Let's assume I have a 2-dim array $alias
$array1 = [
    'id' => 1,
    'tstamp' => 123456789,
    'alias' => '$alias',
];

$array2 = [
    'id' => 1,
    'tstamp' => 123456789,
    'alias' => '$alias2',

];

$alias = [$array1, $array2];

Why is this code working
$insert = 'INSERT INTO abcdef VALUES (?,?,?)';
$insertStmt = $conn->prepare($insert);
foreach ($alias as $array) {
    $insertStmt->bind_param('iis', $array['id'], $array['tstamp'], $array['alias']);
    $insertStmt->execute();
}

and this not?
$insert = 'INSERT INTO abcdef VALUES (?,?,?)';
$insertStmt = $conn->prepare($insert);
$insertStmt->bind_param('iis', $array['id'], $array['tstamp'], $array['alias']);
foreach ($alias as $array) {
   $insertStmt->execute();
}

If I have to bind the parameters all the time there's a lot more trafic, isn't it?

A:

bind_param() binds by reference to a specific zval container. On each iteration of the loop a new array symbol table is allocated with its own zval containers. If at the time of binding the zval containers do not exist they will be created. This can be shown with the following code:
$insertStmt = $conn->prepare('INSERT INTO abcdef VALUES (?,?,?)');
$insertStmt->bind_param('sss', $array['id'], $array['tstamp'], $array['alias']);
var_dump($array);

outputs:
array (size=3)
  'id' => null
  'tstamp' => null
  'alias' => null

Even though we didn't declare the $array anywhere, the binding implicitly created it with null values. Bindings will keep on pointing to this empty array.
Of course when we start iterating the alias array, the $array will be created anew each time. The old array symbol table, to which we bound the parameters is now gone. We haven't bound anything to the new array.
To solve this you can simply move the bind_param() inside the foreach loop as:
$insertStmt = $conn->prepare('INSERT INTO abcdef VALUES (?,?,?)');
foreach ($alias as $array) {
    // bind to the new zval containers every iteration
    $insertStmt->bind_param('sss', $array['id'], $array['tstamp'], $array['alias']);
    $insertStmt->execute();
}

A:

If I have to bind the parameters all the time there's a lot more
  traffic, isn't it?

The traffic is generated on prepare and execute events.
Having said that, you can re-arrange your a little to move ->bind_param() outside the loop. The simpler approach is to bind variables instead of array:
$array1 = ['id' => 1, 'tstamp' => 123456789, 'alias' => '$array1'];
$array2 = ['id' => 1, 'tstamp' => 123456789, 'alias' => '$array2'];
$arrays = [$array1, $array2];

$insert = 'INSERT INTO abcdef VALUES (?,?,?)';
$insertStmt = $conn->prepare($insert);

$bv_id      = NULL;
$bv_tstamp  = NULL;
$bv_alias   = NULL;
$insertStmt->bind_param('iis', $bv_id, $bv_tstamp, $bv_alias);

foreach ($arrays as $array) {
    // you could use extract($array, ...) below
    // but its use is highly discouraged
    $bv_id     = $array['id'];
    $bv_tstamp = $array['tstamp'];
    $bv_alias  = $array['alias'];
    $insertStmt->execute();
}

If you must use arrays then use this approach:
$array = ['id' => null, 'tstamp' => null, 'alias' => null];
$insertStmt->bind_param('iis', $array['id'], $array['tstamp'], $array['alias']);
foreach ($arrays as $copy) {
    foreach ($copy as $k => $v) {
        $array[$k] = $v;
    }
    $insertStmt->execute();
}

Notice that I used a different name for the loop variable inside the foreach construct (we need to keep track of the array that is bound to the statement and loop variables get overwritten on each iteration). You will have to manually copy the values from the loop variable to the bound array.


Q:

Creating Model Class in C#?

So I simply have a simple web API that returns JSON format as following
{
"dailyDealId": "432",
"discountPercentage": "0",
"product": {
    "productId": "10",
    "brandId": "10",
    "departmentId": "3",
    "name": "Baby Girl Velour Tunic & Snowflake Legging Set",
    "description": "The pretty set",
    "url": "http://whatever.whatever.com/files/whatever.tif"
}

}
I want to get this data on my C# console code
this is my Model Class Data.cs
class Data
{
    public string dailyDealId { get; set; }
    public string discountPercentage { get; set; }
    public Array product { get; set; }
}

and this is my main Code
static void Main(string[] args)
    {

        HttpClient client = new HttpClient();
        client.BaseAddress = new Uri("http://whatever.com/");

        HttpResponseMessage response = client.GetAsync("product/").Result;

        if (response.IsSuccessStatusCode)
        {
             var products = response.Content.ReadAsAsync<IEnumerable<Data>>().Result;

            foreach (var p in products)
            {

                Console.WriteLine("dailyDealId" + p.dailyDealId);
            }

        }

    }

But it doesnt seem to work and I get Newtonsoft.Json.JsonSerializationException: Cannot deserialize the current JSON Error, any help would be appreciated
Thanks

A:

One problem could be the fact that your class Data treat the member product as an Array when the JSON you are giving us as an example is an object (enclosed in {} not in []).
You need to create a new class and change the type of Data.product:
public class Product
{
    public string productId { get; set; }
    public string brandId { get; set; }
    public string departmentId { get; set; }
    public string name { get; set; }
    public string description { get; set; }
    public string url { get; set; }
}

public class Data
{
    public string dailyDealId { get; set; }
    public string discountPercentage { get; set; }
    public Product product { get; set; }
}

JsonConvert should work with this definition.


Q:

Whats the difference between $_foo and _foo in php?

What is the difference between $_foo and _foo in php?

A:

The first refers to a variable named _foo. The second refers to a global constant named _foo.
By default PHP will issue low-severity errors when you try to access an undefined variable or undefined constant. In such cases, the "value" of the variable will be assumed to be null while the "value" of the constant will be assumed to be the stringified version of its name -- in this case, '_foo'.


Q:

existence of minimal resolutions

Let $X$ be a toric variety. A resolution of singularities $f \colon Y \rightarrow X$ is called minimal if for every resolution $g \colon Z \rightarrow X$, there is a morphism $h \colon Z \rightarrow Y$ such that $f \circ h = g$.
I know and understand that there is a minimal resolution of singularities for toric surfaces. But what about toric varieties in general? I read that minimal resolutions of toric singularities in higher dimensions might not be unique. Does anybody know an example for a toric variety that admits two different minimal resoultions?
Do minimal resolutions of singularities of toric varieties always exist? And if no, is there a nice counterexample?
Thanks in advance!

A:

I think it's useful to separate the toric and non-toric aspects of the question.
The minimal resolution of singularities exsits for any surface, but in general there is no resolution that is minimal (in the sense of your defintion) for higher-dimensional varieties, because of the possibility of birational maps called flops.
Now the question is whether there are toric examples of flops, and the answer is that indeed there are. In fact the simplest example of a flop, the so-called Atiyah flop, is toric. The singular affine threefold $X=\{xy-zw\}=0$ has as its fan the "square" cone $S$ in $\mathbf{R}^3$. We get two different toric resolutions $X_i \rightarrow X \ (i=1,2)$ by subdividing $S$ into simplicial cones in two different ways, namely by including the two diagonals of the square. Note that the resulting fans are isomorphic, showing that the two varities $X_i$ are abstractly isomorphic, but they are not isomorphic over $X$.


Q:

How to programmatically translate/localize taxonomy terms?

I want to use Google Translate for translating taxonomy terms. I have the "Talking to Google" part done, but I can't find much documentation on translating terms & their descriptions programmatically.
Please help!

A:

I was able to do it using the following code:
<?php
    $enabled_languages = array_shift(language_list('enabled'));
    foreach ($enabled_languages as $language => $object) {
        if ($language != 'en') {
            //Translate description
            i18n_string_translation_update(
                array('taxonomy', 'term', 12, 'description'), // Path where to store source and translation.
                autotranslate_translate($term->description, 'en', substr($language, 0, 2)),
                $language
            );
            //Translate name
            i18n_string_translation_update(
                array('taxonomy', 'term', 12, 'name'), // Path where to store source and translation.
                autotranslate_translate($term->name, 'en', substr($language, 0, 2)),
                $language
            );
        }
    }

?>


Q:

Debian Jessie Nginx 1.8.0 Symfony 3 returning 500 response

I have set up a Symphony 3 site on my local computer that works. I then uploaded it to my server which is a Debian Jessie server with Nginx 1.8 set up on it with PHP 7 .
When i try and access the site i get the following error

api.server.com is currently unable to handle this request.
  HTTP ERROR 500

When i look at the error logs i get the following:
2016/06/26 20:45:03 [error] 28099#0: *1 FastCGI sent in stderr: "PHP

message: PHP Fatal error:  Uncaught UnexpectedValueException: The stream or file "/var/www/aqua_note/var/logs/prod.log" could not be opened: failed to open stream: Permission denied in /var/www/aqua_note/vendor/monolog/monolog/src/Monolog/Handler/StreamHandler.php:97
Stack trace:
#0 /var/www/aqua_note/vendor/monolog/monolog/src/Monolog/Handler/AbstractProcessingHandler.php(37): Monolog\Handler\StreamHandler->write(Array)
#1 /var/www/aqua_note/vendor/monolog/monolog/src/Monolog/Handler/FingersCrossedHandler.php(112): Monolog\Handler\AbstractProcessingHandler->handle(Array)
#2 /var/www/aqua_note/vendor/monolog/monolog/src/Monolog/Logger.php(336): Monolog\Handler\FingersCrossedHandler->handle(Array)
#3 /var/www/aqua_note/vendor/monolog/monolog/src/Monolog/Logger.php(643): Monolog\Logger->addRecord(500, 'Uncaught PHP Ex...', Array)
#4 /var/www/aqua_note/vendor/symfony/symfony/src/Symfony/Component/HttpKernel/EventListener/ExceptionListener.php(89): Monolog\Logger->critical('Uncaught PHP Ex...', Array)
#5" while reading response header from upstream, client: 108.46.158.41, server: api.servername.com, request: "GET / HTTP/1.1", upstream: "fastcgi://127.0.0.1:9000", host: "api.servername.com"

my nginx server configuration
server {
    server_name api.servername.com;
    root /var/www/aqua_note/web;

    location / {
        # try to serve file directly, fallback to app.php
        try_files $uri /app.php$is_args$args;
    }

    # PROD
    location ~ ^/app\.php(/|$) {
        fastcgi_pass 127.0.0.1:9000;
        fastcgi_split_path_info ^(.+\.php)(/.*)$;
        include fastcgi_params;
        fastcgi_param  SCRIPT_FILENAME  $realpath_root$fastcgi_script_name;
        fastcgi_param DOCUMENT_ROOT $realpath_root;
        # Prevents URIs that include the front controller. This will 404:
        # http://domain.tld/app.php/some-path
        # Remove the internal directive to allow URIs like this
        internal;
    }

    # return 404 for all other php files not matching the front controller
    # this prevents access to other php files you don't want to be accessible.
    location ~ \.php$ {
      #return 404;
    }

    error_log /var/log/nginx/error.log;
    access_log /var/log/nginx/access.log;
}

Can anyone please offer some help as to what I am doing wrong?

A:

Looks like you need to setup permissions correctly:
http://symfony.com/doc/current/book/installation.html#checking-symfony-application-configuration-and-setup
Do something like this:
$ HTTPDUSER=`ps axo user,comm | grep -E '[a]pache|[h]ttpd|[_]www|[w]ww-data|[n]ginx' | grep -v root | head -1 | cut -d\  -f1`
$ sudo setfacl -R -m u:"$HTTPDUSER":rwX -m u:`whoami`:rwX var
$ sudo setfacl -dR -m u:"$HTTPDUSER":rwX -m u:`whoami`:rwX var

From the Symfony3 install directory. The httpd user needs permission to the var directory. The user might be 'nginx' in your case, I'm not certain.


Q:

what is separation of variables

I was pushing my way through a physics book when the author separated the variables of the Schrödinger equation and I lost the plot:
$$\Psi (x, t) = \psi (x) T(t)$$
can someone please explain how this technique works and is used? It can be in general maths or in the context of this problem. Thanks

A:

Some functions (not all) $\psi (x,t)$ can be written as a product of a function of $x$ and another function of $t$.  For example, $\psi (x,t)=xt$ can be, while $\psi_2 (x,t)=x^2+t^2$ cannot.  The author is guessing that this will yield a solution to the problem and will go on to show that it does.  After some manipulation the equation comes to something like $f(x)=g(t)$ where the left does not depend on $t$ and the right does not depend on $x$.  Then you argue that since the left does not depend on $t$, the right really doesn't either, and both sides must equal some constant.  So now you are solving $f(x)=g(t)=c$.  As equations in single variables it is usually easier.  Proving that this yields a solution is easy.  Proving that all solutions come as a linear combination of solutions of this form is harder.

A:

Regarding your question about the generality of separation of variables, there is an extremely beautiful Lie-theoretic approach to symmetry, separation of variables and special functions,
e.g. see Willard Miller's book [1]. I quote from his introduction:

This book is concerned with the
  relationship between symmetries of a
  linear second-order partial
  differential equation of mathematical
  physics,  the coordinate systems in
  which the equation admits solutions
  via separation  of variables, and the
  properties of the special functions
  that arise in  this manner. It is an
  introduction intended for anyone with
  experience in  partial differential
  equations, special functions, or Lie
  group theory, such  as group
  theorists, applied mathematicians,
  theoretical physicists and  chemists,
  and electrical engineers. We will
  exhibit some modern group-theoretic
  twists in the ancient method of
  separation of variables that can be
  used to provide a foundation for much
  of special function theory. In
  particular, we will show explicitly
  that all special functions that arise
  via separation of variables in the
  equations of mathematical physics can
  be studied using group theory. These
  include the functions of Lame, Ince,
  Mathieu, and others, as well as those
  of hypergeometric type.
This is a very critical time in the
  history of group-theoretic methods in
  special function theory. The basic
  relations between Lie groups, special
  functions, and the method of
  separation of variables have recently
  been  clarified. One can now construct
  a group-theoretic machine that, when
  applied to a given differential
  equation of mathematical physics,
  describes  in a rational manner the
  possible coordinate systems in which
  the equation  admits solutions via
  separation of variables and the
  various expansion  theorems relating
  the separable (special function)
  solutions in distinct  coordinate
  systems. Indeed for the most important
  linear equations, the  separated
  solutions are characterized as common
  eigenfunctions of sets of
  second-order commuting elements in the
  universal enveloping algebra of  the
  Lie symmetry algebra corresponding to
  the equation. The problem of
  expanding one set of separable
  solutions in terms of another reduces
  to a  problem in the representation
  theory of the Lie symmetry algebra.

For an example of effective Lie-theoretic algorithms for first-order ODEs see Bruce Char's paper[2], from which the following useful tables are extracted.

1 Willard Miller. Symmetry and Separation of Variables.
Addison-Wesley, Reading, Massachusetts, 1977 (out of print)
http://www.ima.umn.edu/~miller/separationofvariables.html
http://gigapedia.com/items:links?id=64401
2 Bruce Char. Using Lie transformation groups to find closed form solutions to first order ordinary differential equations.
SYMSAC '81. Proceedings of the fourth ACM symposium on Symbolic and algebraic computation.
http://portal.acm.org/citation.cfm?id=806370


Q:

Uploadify for ASP.NET app returns HTTP Error for large files

My Uploadify script works fine for most files less than 10 MB. But once the file size starts to exceed 40 MB, it will fail to upload with only an error message of "HTTP Error". I tried implementing the onError handler for Uploadify but it does not give me any details what the exact error is. The variable returns as "undefined". I checked my web.config file and the file size limit is set to 50 MB and I have a timeout of 30 minutes, so I'm at a loss as what the problem can be. Here is my script:
$('#uploader').uploadify({
  'uploader': '/js/uploadify/uploadify.swf',
  'script': '/cms/common/uploadify/UploadHandler.ashx',
  'cancelImg': '/images/cancel_upload.png',
  'buttonImg': '/images/select_video_thumbnail_en-us.gif',
  'auto': true,
  'folder': '/Temp',
  'multi': false,
  'sizeLimit': 0,
  'displayData': 'percentage',
  'simUploadLimit': 1,
  'fileExt': '*.jpg;*.gif;*.png',
  'fileDesc': '*.jpg;*.gif;*.png',
  'buttonText': 'Select thumbnail...',
  'width': '120',
  'height': '24',
  'onComplete': function (e, queueId, fileObj, response, data)
  {
    return true;
  },
  'onError': function (a, b, c, d)
  {
    if (d.status == 404)
      alert('Could not find upload script.');
    else if (d.type === "HTTP")
      alert('error ' + d.type + ": " + d.status);
    else if (d.type === "File Size")
      alert(c.name + ' ' + d.type + ' Limit: ' + Math.round(d.sizeLimit / 1024) + 'KB');
    else
      alert('error ' + d.type + ": " + d.text);
  },
  'onCancel': function (e, queueId, fileObj, data)
  {

  }
});

A:

IIS7, which I am running, has a default internal file size limit of 30 MB. Setting maxRequestLength larger than this won't help. The problem is resolved by adding the following to your web.config file:
<system.webServer>
        <security>
            <requestFiltering>
                <requestLimits maxAllowedContentLength="50000000"/>
            </requestFiltering>
        </security>
</system.webServer>

This can also be set in IIS7. For more details, see the following links:
IIS7 File Upload Size Limits
Enabling Request Filtering In IIS 7


Q:

difference between a numeric variable and many others

I have a data.table similar to this one:
require(data.table)
dt = as.data.table(iris[ names(iris) != 'Species' ])[1:26]
dt[ , id := LETTERS ]
setnames(dt, c('col1', 'col2', 'col3', 'col4', 'id'))

I want to calculate the absolute difference of col1 to every other numeric columns (i.e. col2, col3, col4) for every id/row. How can I do that with data.table or other tools in R?
The result should look like this:
+--------+-------------+-------------+-------------+------+
| "col1" | "col1_col2" | "col1_col3" | "col1_col4" | "id" |
+--------+-------------+-------------+-------------+------+
| 5.1    | 1.6         | 3.7         | 4.9         | "A"  |
| 4.9    | 1.9         | 3.5         | 4.7         | "B"  |
+--------+-------------+-------------+-------------+------+

A:

Remove the copy if you don't care about modifying the original table.
cols = paste0('col', 2:4)
# or if you want to be fancy
cols = setdiff(names(dt)[sapply(dt, is.numeric)], 'col1')

copy(dt)[, (cols) := col1 - .SD, .SDcols = cols][]
#    col1 col2 col3 col4 id
# 1:  5.1  1.6  3.7  4.9  A
# 2:  4.9  1.9  3.5  4.7  B
# 3:  4.7  1.5  3.4  4.5  C
# ...


Q:

c# FireBase generated string indexes deserialization

i have a clients list and i want to push them into firebase, i am using firesharp, but when i do, firebase creates a string index for every client i push.
the problem is when i want the data back i cant deserialize it because of the string indexes and the List class.
this is what i have:
 public class Client
{
    public string name { get; set; }
    public string lastname { get; set; }
    public int age { get; set; }
    public string phone { get; set; }
    public string mail { get; set; }
    public string adress { get; set; }
    public List kids { get; set; }

    public Cliente(string nameArg, string lastnameArg, int ageArg, string phoneArg, string mailArg, string adressArg)
    {
        name = nameArg;
        lastname = lastnameArg;
        age = ageArg;
        phone = phoneArg;
        mail = mailArg;
        adress = adressArg;
        kids = new List<kids>();
    }
}

then i made a class to hold this clients (not sure if this is a good idea any suggestion is welcome)
 public class ClientList
{
    public List<Client> clientList
    { get; set; }
}

so i push Client objects to the clientList in firebase like this:
public async void pushClient(Client c) {
        PushResponse response = await client.PushAsync("clientList", c);
        MessageBox.Show (response);//i use this line to check the index
    }

that response is always something like "Ahs74-djAdie8" <-- this is the index firebase gave to my Client object.
firebase json looks like this after the push:
{"clientList":{
    "Gfjy654-hfGfgv":{
        "name":"asasasas",
        "lastname":"ooooooo",
        "age":"22",
        "mail":"hhhh@hhh",
        "phone":"+665544581"
    },
    "H5j7su-UHudufu":{
        name:"asasasas",
        "lastname":"ooooooo",
        "age":"22",
        "mail":"hhhh@hhh",
        "phone":"+665544581"
    }
}
}

now when i try to get this data back and deserialize it doesnt work this is the method and the exception:
    private async void getClients()
    {
        FirebaseResponse response = await client.GetAsync("");
        list = response.ResultAs<ClientList>();
    }

An exception of type 'Newtonsoft.Json.JsonSerializationException' occurred in Newtonsoft.Json.dll but was not handled in user code

i tested changing manually the index in firebase to numbers and Instantly works, but am not tring to do that, i just want to deserialize it right!.
my clue is: List class doesnt work with string indexes;
i am new in c#, have mercy on me :) Thx in advance;

A:

Answer to Updated Question
You need to change clientList to be a dictionary rather than a list:
    public class ClientListResponse
    {
        public Dictionary<string, Client> clientList { get; set; }
    }

Having done so, in theory the JSON you show should now be successfully deserialized, with the dictionary keys being the Gfjy654-hfGfgv strings.


Q:

Is "Fool around" used as an euphemism for "build a relationship" nowadays?

In old Western movies such as True Grit, "Fool around" was used as a substitute for "build a relationship between a man and a woman", is it still used in modern American English?

A:

Actually the idiomatic expression fool around   used with a sexual connotation is mainly  an American English one:

(mainly us) If a married person fools around, they have a sexual relationship with someone who is not their husband or wife:

She'd been fooling around with someone at work.

(Cambridge Dictionary)
This usage is from the '70s according to Etymonline

1970s in sense of "have sexual adventures."


Q:

If $a+b+c=0$ prove that $ 3(a^2+b^2+c^2) \times (a^5+b^5+c^5) = 5(a^3+b^3+c^3) \times (a^4+b^4+c^4) $

If $a+b+c=0$, for $a,b,c \in\mathbb R$, prove
$$ 3(a^2+b^2+c^2) \times (a^5+b^5+c^5) = 5(a^3+b^3+c^3) \times (a^4+b^4+c^4) $$

I made this question as a more difficult (higher degree) version of this question. My idea was that algebraic brute force methods are easy to distinguish from more sophisticated ones if the degree of the terms in the question is higher.
The question was specifically made using the method from my answer to the linked question.

A:

Let's define
$$S_n=a^n+b^n+c^n$$
and consider the generating function
$$F(t)=\sum_{n=0}^\infty S_nt^n=\frac1{1-at}+\frac1{1-bt}+\frac1{1-ct}.$$
Using $a+b+c=0$ gives
$$(1-at)(1-bt)(1-ct)=1+pt^2+qt^3$$
for some $p$ and $q$, and
$$F(t)=\frac{3+pt^2}{1+pt^2+qt^3}.$$
From this we expand as a power series
$$F(t)=(3+pt^2)(1-(pt^2+qt^3)+(pt^2+qt^3)^2-\cdots)
=3-2pt^2-3qt^3+2p^2t^4+5pqt^5+\cdots$$
and now you can read off this, and several other identities...


Q:

pandas.Grouper() returning a grouped date label outside of my data

I'm trying to group a pandas dataframe in last 7 day groups from the most recent date in my dataframe using pd.Grouper().
Why does Grouper return a label which is outside of what dates my data includes? When using closed='right' and label='right' I would think the last label in my Grouper groupby would be the most recent date in my dataframe, and include the last 7 dates worth of data which doesn't seem to be the case.
Real behavior
import pandas as pd

df_test = pd.DataFrame({'Date':['2019-05-07','2019-05-07','2019-05-06', '2019-05-05',
                                '2019-05-04', '2019-05-03', '2019-05-01',
                                '2019-04-28', '2019-04-28','2019-04-23',
                                '2019-04-20','2019-04-18','2019-04-15','2019-04-16'],
                        'Things':[1,1,1,1,1,1,1,1,1,1,1,1,1,1]
                       })
df_test['Date'] = pd.to_datetime(df_test.Date, yearfirst=True)
df_test.groupby(pd.Grouper(key='Date', freq='7D', label='right', closed='right')).count()

Expected behavior

Update: Using Asmus' code snippet
and adding '2019-05-08' to my data since 2019-05-07 may have been an arbitrary even bin given the test data, I expect the latest date in the groupby to be '2019-05-08' not '2019-05-14' since I want to bin backwards 7 days from my most recent data where my label and bin start from the right:
df_test = pd.DataFrame({'Date':['2019-05-08','2019-05-07','2019-05-07','2019-05-06', '2019-05-05', '2019-05-04', '2019-05-03',
                                '2019-05-01', '2019-04-28', '2019-04-28',
                                '2019-04-23', '2019-04-20','2019-04-18',
                                '2019-04-15','2019-04-16'],
                        'Things':[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]
                       })
df_test['Date'] = pd.to_datetime(df_test.Date, yearfirst=True)
df_test=df_test.set_index(pd.to_datetime(df_test.Date),drop=False)
df_test.resample('W-{}'.format(
        df_test.index[-1].strftime('%a')
        ), closed='right', label='right').count()

Produces...

instead of what I expect using closed=right and label=right which would end with the last group 2019-05-08 with Things 7, then 2019-05-01 with Things 3, etc.
But when using Asmus' timedelta adding 1 day, I'm getting the expected grouping behavior with the time group label signifying a group up to but not including '2019-05-09'. Got it :thumbsup!
df_test = pd.DataFrame({'Date':['2019-05-08','2019-05-07','2019-05-07','2019-05-06', '2019-05-05', '2019-05-04', '2019-05-03',
                                '2019-05-01', '2019-04-28', '2019-04-28',
                                '2019-04-23', '2019-04-20','2019-04-18',
                                '2019-04-15','2019-04-16'],
                        'Things':[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]
                       })
df_test['Date'] = pd.to_datetime(df_test.Date, yearfirst=True)
df_test=df_test.set_index(pd.to_datetime(df_test.Date),drop=False)
futureDay= (df_test.Date.max() + pd.Timedelta('1 days')).strftime('%a')
df_test.groupby(pd.Grouper(freq='W-{}'.format(futureDay), closed='right', label='right')).count()

Correctly produces....

Thanks @Asmus !

A:

First of all, let's revisit your expected result upon grouping 7 days, which inherently needs to be inclusive of the most recent day:
2019-05-07       1
2019-05-07       1
2019-05-06       1
2019-05-05       1
2019-05-04       1
2019-05-03       1
2019-05-01       1
                 ## ^ group of 7, until 2019-04-30
2019-04-28       1
2019-04-28       1
                 ## ^ group of 2, until 2019-04-23
2019-04-23       1
2019-04-20       1
2019-04-18       1
                 ## ^ group of 3, until 2019-04-16
2019-04-16       1
2019-04-15       1
                 ## ^ group of 2, the remainder

A solution for this grouping can be found in this answer, if you first set a "proper" index:
df_test=df_test.set_index(pd.to_datetime(df_test.Date),drop=False)

print( df_test.resample('W-{}'.format(
        df_test.index[-1].strftime('%a')
        ), closed='right', label='right').sum() )

which yields:
            Things
Date
2019-04-16       2
2019-04-23       3
2019-04-30       2
2019-05-07       7

Or, for the sake of completeness, if you'd e.g. rather sample backwards from one day into the future of your latest entry, and want to use a d pd.Grouper(), that'd be:
futureDay= (df_test.Date.max() + pd.Timedelta('1 days') ).strftime('%a')
print( df_test.groupby(pd.Grouper(freq='W-{}'.format(futureDay),
                                  closed='right', label='right')).sum() )


Q:

Como controlar o posicionamento de uma div com position fixed?

Como eu posso fazer para que quando a minha div da direita chegar na div da área de comentários voltar a ficar fixa? Quando ela chega em um número X de distancia do topo eu aplico um position fixed para ela ir acompanhando o conteúdo:
Link da materia
 <script type="text/javascript">
            $(document).ready(function () {
                $(window).scroll(function () {
                    if ($(this).scrollTop() > 630) {
                        $('.paginas-especiais-post').css({
                            position: 'fixed',
                            top: '60px'
                        });
                    } else {
                        $('.paginas-especiais-post').css({
                            position: 'relative',
                            top: '0'
                        });
                    }
                });
            });
        </script>

A:

Achei uma alternativa para seu problema que foi adicionar mais uma restrição no if:
&& $(this).scrollTop() < $('.comentarios-pag').position().top - 630

se o scroll for maior que 641 e menor que a distância da div comentários subtraindo o tamanho (mais alguns espaços Ex. navbar e paddings).
Abs.
$(document).ready(function() {
    $(window).scroll(function() {
        var especiais = $('.paginas-especiais-post');

        if( $(this).scrollTop() > 641 && $(this).scrollTop() < $('.comentarios-pag').position().top - 630 ) {
          especiais.css({
            position: 'fixed',
            top: '60px'
          });
        } else {
          especiais.css({
            position: 'relative',
            top: '0'
          });
        };
    });
});


Q:

How to create timer in my games in cocos2dx using c++

I am developing games and facing problem with creating timer. I need some logic like time should start from 60 sec when it reach to 0 game should end. I am new to this platform.

A:

I usually use the  scheduler for this, which you can use to call a method at fixed time intervals, like this:
this->schedule(schedule_selector(Game::UpdateTimer),1.0f);

in this case it calls 'Game:UpdateTimer' once a second.  In update timer you'd just reduce your counter by one, and when it's reach zero stop the timer like this:
this->unschedule( schedule_selector(Game::UpdateTimer));

and add a method underneath to be called
void Game::UpdateTimer(float dt)
{

}


Q:

how to another port setting in weblogic-maven-plugin deploy weblogic in maven

I deploying weblogic war file by maven build, and sucess adminurl to deploy weblogic
but another serverport instead adminurl how to config
weblogic have two servers  adminport(port:7001 (console) ) and serverport(8081 (server) )
I want to deploy serverport 8081 in maven build tool
how to 8081 port server deploy war file with maven plugin
my maven build source code
    <build>
      <plugins>
        <plugin>
          <groupid>com.oracle.weblogic</groupid>
          <artifactid>weblogic-maven-plugin</artifactid>
          <version>10.3.4</version>
          <configuration>
            <adminurl>t3://localhost:7001</adminurl>
            <user>user</user>
            <password>password</password>
            <upload>true</upload>
            <action>deploy</action>
            <remote>false</remote>
            <verbose>true</verbose>
            <source>
${project.build.directory}/${project.build.finalName}.${project.packaging}                </source>
            <name>${project.build.finalName}</name>
          </configuration>
          <executions>
            <execution>
              <phase>install</phase>
              <goals>
                <goal>deploy</goal>
              </goals>
            </execution>
          </executions>
        </plugin>
      </plugins>
    </build>

how to serverport setting in maven xml tag don't know.

A:

I am pretty sure that you can not directly do this, meaning you can directly deploy the application (war/ear) to a managed server . I guess you have a domain (so 1 admin server and 1 managed node). You have to go through the admin server.
Please read here.


Q:

Where to obtain Irish passport stamp when entering from Northern Ireland?

I'm going with an American friend from Belfast to Dublin by bus. Despite the lack of border control at the land border due to the Common Travel Area agreement, non-EU/EFTA nationals are supposed to get processed and stamped into Ireland even when entering from the UK - the Immigration section of the Gardai (Irish Police) has consistently told me this by E-Mail and on the phone
I e-mailed the Gardai asking about entering by bus from Belfast, and they said we should go to the Garda Station in Dundalk for entry processing.
However, Belfast-Dublin buses do not stop in Dundalk, but run non-stop between Newry (UK) and Dublin.
What is the proper procedure in this case?
UPDATE: just found the following on the INIS website:

If you arrive via the border with Northern Ireland, you must report to an immigration officer at Burgh Quay Registration Office Dublin or your local Garda Síochána (police) station as soon as possible.

I've noticed a common belief here on Travelstack that, due to the Common Travel Area, you need to do nothing as long as you were admitted to the UK. That is then clearly not the case.

A:

If you look at the Aliens (Amendment) Order, 1975 , point 5 has the following:
5. (1) An alien coming from a place outside the State other than Great Britain or Northern Ireland shall, on arrival in the State, present himself to an immigration officer for leave to land.
My understanding is that a non-EU national does not need to be stamped if the traveller have been landed in the UK (given permission to enter) and is travelling direct from the UK to the Republic of Ireland.

A:

So, just found the following on the INIS website:

If you arrive via the border with Northern Ireland, you must report to an immigration officer at Burgh Quay Registration Office Dublin or your local Garda Síochána (police) station as soon as possible.

I've noticed a common belief here on Travelstack that, due to the Common Travel Area, you need to do nothing as long as you were admitted to the UK. That is then clearly not the case.


Q:

Why is it ok to pay the kids for the afikoman?

Most Pesach sedarim feature the afikoman hide-and-seek game; either the children steal it and ransom it back or the parents hide it and (in my experience) pay a prize to the child who finds it.  At most of the sedarim I've been to, this has been a cash payment.
Why is it ok to handle and transfer money on Pesach?  And does (or should) this custom change when Pesach is on Shabbat, as it will be this year?
This related question has a lot of good information about this ritual but does not address this aspect of it.

A:

I cannot speak for those who literally give cash (or any gift) on Yom Tov as this is considered a business transaction and is rabbinically forbidden as a safeguard of the labor of writing.  But there is more leeway to talk about the transaction on Yom tov.
Transferring an object to another's possession is definitely a violation of business activities.  Talking about business is not a violation of the above, but is a violation of Yishaya 58:13-14 which warns to steer clear of "your business actions".  All would agree, though, that if the business is not personal but spiritual (chafatzecha excludes cheftzei shamayim), one would be permitted to talk about business.  For example, one would be allowed to tell a mohel that he is interested in hiring him for a job.
There is a debate over how much one can talk about (Rema OC 306:3 and 6).  Can I actually set a price with the mohel and strike a deal.  Some say this is still permitted since it is spiritual business.  Others say this is too close to the rabbinic decree of business activities (similar to transfering objects) which were forbidden under all circumstances (MB 306:14).  [The Mishna Berurah 306:32 equates the debate in 306:3 to 306:6 as well.]
Interestingly, whereas in 306:3 the Rema sides with the stricter approach to forbid making the deal ("v'chen ikar"), he says in 306:6 that the custom is to be lenient and make specific pledges to charity or to pay the chazan ("v'haminhag l'hakil").
So, since you are setting a price for a spiritual deal to eat an afikomen (that you can just take another out of the box does not undermine the spiritual aspect of the "stolen" matza), and you are not transferring the possession since it's already yours, you are at least in line with the "custom".


Q:

How to post message on facebook wall with html link?

In my android app i am using Facebook Api for posting message on his/her wall. Its working fine without any problem. Now i tried to post the message with html link in it. The message get posted on Facebook wall but the html link is not working. It looks like normal text. Here is the message i am trying to post on faceboook wall with the code
private String Facebook = "Facebook";

Message = "Hi"+Html.fromHtml(Facebook);

Am i doing anything wrong.
EDIT
I would like to have like this in facebook wall
Hi,EveryOne Facebook is really nice social website.
Thanks for your help guys.

A:

Try this snippet to add html link :
    Bundle parameters = new Bundle();
    JSONObject attachment = new JSONObject();
    try {
            attachment.put("message", "Messages");
            attachment.put("name", "Message");
            attachment.put("href", "http://www.facebook.com");
    } catch (JSONException e) {}
    parameters.putString("attachment", attachment.toString());
    facebook.request(parameters);


Q:

CSS Transform Skew

Does anyone know how to achieve skew like this:

Using CSS's new transform property?
As you can see I'm trying to skew both corners, anyone know if this is possible?

A:

.red.box {
  background-color: red;
  transform: perspective( 600px ) rotateY( 45deg );
}

Then HTML:

from http://desandro.github.com/3dtransforms/docs/perspective.html

A:

I think you mean webkit transform.. please check this URL out
http://www.the-art-of-web.com/css/3d-transforms/ it could help you.

A:

CSS:
#box {
    width: 200px;
    height: 200px;
    background: black;
    position: relative;
    -webkit-transition: all 300ms ease-in;
}
#box:hover {
    -webkit-transform: rotate(-180deg) scale(0.8);
}
#box:after, #box:before {
    display: block;
    content: "\0020";
    color: transparent;
    width: 211px;
    height: 45px;
    background: white;
    position: absolute;
    left: 1px;
    bottom: -20px;
    -webkit-transform: rotate(-12deg);
    -moz-transform: rotate(-12deg);
}
#box:before {
    bottom: auto;
    top: -20px;
    -webkit-transform: rotate(12deg);
    -moz-transform: rotate(12deg);
}

HTML:

Works in Chrome and FF 4: http://jsfiddle.net/rudiedirkx/349x9/
This might help: http://jsfiddle.net/rudiedirkx/349x9/2880/
And this too (from Erwinus' comment): http://css-tricks.com/examples/ShapesOfCSS/


Q:

Protractor, when should I use then() after a click()

I'm running an Angular app and when testing on protractor a click(), I don't know when should I resolve the promise with a then().
I found this on Protractor API:

A promise that will be resolved when the click command has completed.

So, should I use click().then() in every click?

A:

So, should I use click().then() in every click?

Definitely not.
It's not needed because Protractor/WebDriverJS has this mechanism called "Control Flow" which is basically a queue of promises that need to be resolved:

WebDriverJS maintains a queue of pending promises, called the control
  flow, to keep execution organized.

and Protractor waits for Angular naturally and out-of-the-box:

You no longer need to add waits and sleeps to your test. Protractor
  can automatically execute the next step in your test the moment the
  webpage finishes pending tasks, so you don’t have to worry about
  waiting for your test and webpage to sync.

Which leads to a quite straight-forward testing code:
var elementToBePresent = element(by.css(".anotherelementclass")).isPresent();

expect(elementToBePresent.isPresent()).toBe(false);
element(by.css("#mybutton")).click();
expect(elementToBePresent.isPresent()).toBe(true);

Sometimes though, if you experience synchronization/timing issues, or your app under test is non-Angular, you may solve it by resolving the click() explicitly with then() and continue inside the click callback:
expect(elementToBePresent.isPresent()).toBe(false);
element(by.css("#mybutton")).click().then(function () {
    expect(elementToBePresent.isPresent()).toBe(true);
});

There are also Explicit Waits to the rescue in these cases, but it's not relevant here.

A:

Yes, you should.
Maybe right now it's not necessary, but maybe in next versions it is.
So, if click return a promise, you should use it.
http://www.protractortest.org/#/api?view=webdriver.WebElement.prototype.click


Q:

Car rental Tenerife Sur (south) airport at 2am in the night?

I'm trying to rent a car for a few days.
Location: Tenerife / Spain / Tenerife Sur / Tenerife-Reina Sofia
Time: May - landing 1am - so I need something at 2-3am.
I tried the main ones like Avis and Budget; they state that they are not working at that time and I can't rent it.
I found a couple of others that allow it, but they are not very trustworthy.
Can someone who has been there, or lives there, recommend some trustworthy site for car rental that would allow a 2am pickup? Are there any that are open that time?
Or, worst case scenario, provide some information about ways and prices to get to Adeje at that time.

A:

I've visited the Canary Islands several times and rented cars from Cicar. It was recommended by a German travel guide (book) as reliable company.
Cicar is a native car rental company and claims to be the largest one on the Canary Islands, with the most offices.
Personally, I had no problems with their cars or their service and would choose them again. (However, I only rented cars three times at different locations) Nice goodie: You get a (simple) map with points of interest and an audio-CD giving some information about that points.
According to Cicars web site, office hours at Tenerife South airport are 7:00-23:00, 7 days/week. But their conditions also state that you can also rent cars outside of their office hours. (See here or goto http://www.cicar.com/EN, click "search", and find the link [see conditions] on the left, below the booking details)
OK, this sounds more like an advertisement, but I'm just a pleased customer.


Q:

What is the best practice to clone the default search result display template?

I am using SharePoint 2013. I have created a new search page. On this page you see the search result webpart and the refiner webpart etc. I have selected the search result page layout. Now I have cloned the default item search display template. I give it another name and upload it in the gallery:
Item_Voorraadbeheer.html
Item_Voorraadbeheer_HoverPanel.html

In the settings of my search result property I have selected this custom search display template and it works. I can see my custom logic. But I see in my display template this code:
_#=ctx.RenderBody(ctx)=#_

I would like to clone also the logic begind this method. How can I clone the OOTB body ? See also the red marked area what I mean with the OOTB body of each item.

A:

Body render is defined in another display template, look for "Item_CommonItem_Body.html"


Q:

Silverlight DragDropTarget - just copy, not move

I'd like to ask, how can I in Silverlight just copy an item with drag&drop, not move, if I'm using the DragDropTargets?

I've fount that: Silverlight Toolkit Drag Drop (Part 2): Customizing Drag and Drop Behavior

A:

I guess you need to set the AllowedSourceEffects property for the source *DragDropTarget element, like here:
<toolkit:PanelDragDropTarget VerticalContentAlignment="Stretch" HorizontalContentAlignment="Stretch" AllowedSourceEffects="Copy">
 <!-- here is a panel -->
</toolkit:PanelDragDropTarget>


Q:

angularJs - ngRepeat with custom id

Edit:
So, after messing around with the code and following everyones advice, I found out that, indeed, the id -does- work, but somethign else blocks it.
This is the entire line of code, now: where is the problem located?

HTML:

        {{item.name}}
        {{item.email}}

DATA:
$scope.users = [
    { id: 1, name: "user", email : ""},
    { id: 2, name: "anotherUser", email: ""}];

Problem:
the ID stays "{{item.id}}" and isn't converted to, eg: "1". I tried with ng-attr-id as well, but it didn't work either.
Why isn't the ID "transformed" to what it should be?
To bring the problem a bit further: if I do data-id="{{item.id}}, it DOES work.

A:

All seems to Work

angular.module('app', [])
  .controller('ctrl', ["$scope",
    function($scope) {
      $scope.limiter = 4;
      $scope.users = [{
        id: 1,
        name: 'n1'
      }, {
        id: 2,
        name: 'n2'
      }, {
        id: 3,
        name: 'n3'
      }, {
        id: 4,
        name: 'n4'
      }, {
        id: 5,
        name: 'n5'
      }, {
        id: 6,
        name: 'n6'
      }];
    }
  ]);

    Id - {{item.id}}
    Name - {{item.name}}

A:

My previous  answer is very poor, But some one put up vote. lol.
okay finally i got the issue.
You need to change var users = [...] to $scope.users=[...];
Update

Did you assign controller and ng-app in you html side?
try to use $scope.$apply() in your controller.
$scope.users = [
    { id: 1, name: "user", email : ""},
    { id: 2, name: "anotherUser", email: ""}];
$scope.$apply();


Q:

Can not organize data in input collection

I have payment_type model with 3 elements saved. Also I have an order, where I want to store payment_type_id. I write in order view:
<%= f.input :pay_type_id, :as => :select, collection: PaymentType.names  ...%>
But payment_type_id already saves as 0. As I understand, I'm trying to record payment_type.name instead of payment_type.id. What do I have to write in collection: to fix it?

A:

<%= f.select :pay_type_id, PaymentType.all.collect {|x| [x.name, x.id]} %>

This will display the name of the pay_type to the user in the dropdown, but submit the id of the pay_type to your form.


Q:

UKIP: is it real major third party in UK?

Can anyone suggest some reading on what is UKIP?
Questions I am looking for to answer:

is It real major third party for UK? Is it projected to raise further after last weekend elections?
any serious business supporting or warm to UKIP
could UKIP influence apparently grave situation with Scotland referendum?

A:

Before I answer this I should state that I am not impartial, and am a Labour Party supporter, but having said that I will try to keep my opinions neutral for this.
At the moment in terms of where it sits in the UK, it has no members of Parliament (MPs) so has no national influence. It does have the UK's largest number of European Parliament MPs, but as its aim is to leave the European Union it does not participate fully in that body. It has also aligned itself with a right wing grouping which does not have enough combined votes to have much influence.
In the UK the current third party in the Liberal Democrats, who went into coalition with the Conservatives following the general election in 2010, it would appear that UKIP wish to emulate this, having decided to target just 20 seats in 2015.
This seems to be a bid to gain influence, and in some parts UKIP is seen as a potential right wing adjunct to the conservatives.
UKIP has had some image troubles, with little control over selection of local candidates, including some elected members expressing racist and homophobic views - which is illegal in the UK.
I personally think that the views and policies of UKIP are unpleasant at best, and inflammatory at times, however their leader comes across in the media as a down to earth person who you would chat to in a bar.
Polling indicates that they have some support but not at the moment enough to generate a massive change in the makeup of the political landscape of the UK. And their support seems to be dropping following the EU elections.
You asked about support from business.  From smaller businesses possibly yes, there has been some talk, but not any real UKIP announcement, on relaxing employment legislation, making it easier to fire people, but on the whole larger nationals / regionals/ multinationals are unlikely to be supportive, as if we were to leave the EU then businesses and imports would suffer.
Ukip have a strong anti migrant rhetoric, and organisations have been active in countering its views.  Such As this Tuc booklet.
As to the final question about Scottish independence. I don't think they have that much influence with just one EU MP, and the Scottish wing of UKIP not functioning.


Q:

Simple question about simple arrays in Objective-C

OK this is probably a really stupid question but I can't seem to find the answer.
I know how to sort arrays using sort descriptors but what about a simple array containing only a series of numbers?
For example an array containing the following numbers:
21,3,11,58,32,76,19,45,7,92
I just need the numbers in ascending order.

A:

I'm assuming you mean an NSArray of NSNumbers.
Fairly simple:
NSArray *unorderedNumbers; // assume exists

NSArray *sortedArray = [unorderedNumbers
               sortedArrayUsingSelector:@selector(compare:)];

(See sortedArrayUsingSelector:).
This causes the objects (which happen to be numbers) to be compared using compare:.


Q:

Evaluating $\int_0^\infty \left| \frac{\sin t}{t} \right|^n \, \mathrm{d}t$ for $n = 3, 5, 7, \dots$

I would like to determine the general term of the following sequence defined by an infinite integral:
$$
I_n = \int_0^\infty \left| \frac{\sin t}{t} \right|^n \, \mathrm{d}t \, ,
$$
wherein $n =3, 5, 7, \dots$ is an odd integer.
It can be checked that the integral is convergent for all values of $n$ in the prescribed range. The case of even $n$ is solved in A sine integral $\int_0^{\infty} \left(\frac{\sin x }{x }\right)^n\,\mathrm{d}x$. Also, $I_1 = \infty$.
I have tried to use the method of multiple integrations by parts but in vein.
I was wondering whether there exists a suitable approach to address this problem more effectively.

A:

Here is a partial answer: If $n \geq 2$ is an integer, then
$$ I_n = \frac{1}{(n-1)!2^{n-1}} \sum_{l=0}^{\lfloor n/2 \rfloor} (-1)^l \binom{n}{l} (n-2l)^{n-1} J_{n-2l}, \tag{1} $$
where $J_p$ is defined by
$$ J_{p} = \begin{cases}
\displaystyle \frac{4p}{\pi} \sum_{j=1}^{\infty} \frac{\log(2\pi j)}{4j^2-p^2}, & \text{if $p$ is odd}, \\
\displaystyle \frac{\pi}{2}, & \text{if $p$ is even}.
\end{cases} $$

Proof of $\text{(1)}$. The case of even $n$ has already been discussed in other postings, so we focus on odd $n$. We first note that, if $n \geq 1$ is an odd integer, then
\begin{align*}
\frac{\mathrm{d}^{n-1}}{\mathrm{d}x^{n-1}} \sin^n x
&= \frac{1}{(2i)^n} \sum_{l=0}^{\frac{n-1}{2}} (-1)^l \binom{n}{l} \frac{\mathrm{d}^{n-1}}{\mathrm{d}x^{n-1}} (e^{(n-2l)ix} - e^{-(n-2l)ix}) \\
&= \frac{1}{2^{n-1}} \sum_{l=0}^{\frac{n-1}{2}} (-1)^l \binom{n}{l} (n-2l)^{n-1} \sin((n-2l)x).
\end{align*}
So by applying integration by parts $(n-1)$-times, we get
\begin{align*}
I_n
&= \sum_{k=0}^{\infty} \int_{0}^{\pi} \frac{\sin^n x}{(x+k\pi)^n} \, \mathrm{d}x \\
&= \frac{1}{(n-1)!} \sum_{k=0}^{\infty} \int_{0}^{\pi} \biggl( \frac{1}{x+k\pi} - \frac{1}{(k+1)\pi} \biggr) \biggl( \frac{\mathrm{d}^{n-1}}{\mathrm{d}x^{n-1}} \sin^n x \biggr) \, \mathrm{d}x \\
&= \frac{1}{(n-1)!2^{n-1}} \sum_{l=0}^{\frac{n-1}{2}} (-1)^l \binom{n}{l} (n-2l)^{n-1} J_{n-2l},
\end{align*}
where $J_{p}$ is defined by
\begin{align*}
J_{p}
&= \sum_{k=0}^{\infty} \int_{0}^{\pi} \biggl( \frac{1}{x+k\pi} - \frac{1}{(k+1)\pi} \biggr) \sin(px) \, \mathrm{d}x.
\end{align*}
If $p$ is odd, then the above definition is recast as
\begin{align*}
J_{p}
&= \sum_{k=0}^{\infty} \biggl( \int_{0}^{\pi} \frac{1}{x+k\pi} \sin(px) \, \mathrm{d}x - \frac{2}{p\pi(k+1)} \biggr) \\
&= \lim_{N \to \infty} \biggl( \int_{0}^{N \pi} \frac{\sin(p(x \text{ mod } \pi))}{x} \, \mathrm{d}x - \frac{2}{p\pi} H_N \biggr),
\end{align*}
where $H_N = 1 + \frac{1}{2} + \dots + \frac{1}{N}$ is the $N$-th harmonic number. Still assuming that $p$ is an odd integer, Fourier series computation shows that
\begin{align*}
\sin(p(x \text{ mod } \pi))
&= \frac{2}{p\pi} - \frac{4p}{\pi} \sum_{n=1}^{\infty} \frac{\cos(2\pi n x)}{4n^2-p^2} \\
&= \frac{4p}{\pi} \sum_{j=1}^{\infty} \frac{1 - \cos(2\pi j x)}{4j^2-p^2},
\end{align*}
and so,
\begin{align*}
\int_{0}^{N \pi} \frac{\sin(p(x \mathrm{ mod } \pi))}{x} \, \mathrm{d}x
&= \frac{4p}{\pi} \sum_{j=1}^{\infty} \frac{1}{4j^2-p^2} \int_{0}^{N \pi} \frac{1 - \cos(2 j x)}{x} \, \mathrm{d}x \\
&= \frac{4p}{\pi} \sum_{j=1}^{\infty} \frac{1}{4j^2-p^2} (\gamma + \log(2\pi j N) - \operatorname{Ci}(2\pi j N) ).
\end{align*}
Plugging this back and using the identity $\frac{4p}{\pi} \sum_{j=1}^{\infty} \frac{1}{4j^2-p^2} = \frac{2}{p\pi}$, which itself follows from the Fourier series of $\sin(p(x \text{ mod } \pi))$, we finally obtain
\begin{align*}
J_{p}
&= \frac{4p}{\pi} \lim_{N \to \infty} \sum_{j=1}^{\infty} \frac{1}{4j^2-p^2} (\gamma + \log(2\pi j N) - \operatorname{Ci}(2\pi j N) - H_N ) \biggr) \\
&= \frac{4p}{\pi} \sum_{j=1}^{\infty} \frac{\log(2\pi j)}{4j^2-p^2}
\end{align*}
as desired. $\square$

Addendum. Here is a Mathematica code for numerical verification of $\text{(1)}$:
n = 5; (* Choose your favorite odd integer >= 3*)
NIntegrate[Evaluate[Sum[1/(x + k Pi)^n, {k, 0, Infinity}] Sin[x]^n], {x, 0, Pi}, WorkingPrecision -> 20]
TermJ[p_] := (4 p)/Pi NSum[Log[2 Pi j]/(4 j^2 - p^2), {j, 1, Infinity}, WorkingPrecision -> 20];
1/((n - 1)! 2^(n - 1)) Sum[Binomial[n, l] (-1)^l (n - 2 l)^(n - 1) TermJ[n - 2 l], {l, 0, (n - 1)/2}]
Clear[n, TermJ];


Q:

How to translate this SQL query to DB::getInstance() class?

Prestashop 1.6.0.13
Theme: Panda 1.1.1 (Themeforest)
I'm trying to develop a web that change the prices in real time.
This is the process:
After the web is loaded, this jquery is executed.
     $('#divId').load('../../price.php');
    setInterval(function(){
        $('#divId').load('../../price.php');
}, 3600);

That call this price.php
<?php
$data = file_get_contents("https://gold-feed.com/paid/38940e/all_metals_json_eur.php");
$obj = json_decode($data, true);
$a = $obj['gold_ask_eur_toz'];
echo $a."    ".time();

/*
$name = 10;
Db::getInstance()->insert('ps_54z_product_shop', array(
    'price'      => pSQL($name),
));
*/
?>

The first part calls a JSON file which contains the live prices.
I know that this bit works.
The las bit doesn't work for me. The SQL query in MySQL
UPDATE `ps_54z_product_shop` SET `price`= 10

Works perfectly.
How I can do to translate this query
UPDATE `ps_54z_product_shop` SET `price`= 10

to Db::getInstance() and put it in a php file?

A:

For an update, you should use the update function:
Db::getInstance()->update('ps_54z_product_shop', array('price' => pSQL($name)), '1');
//Replace 1 by "some_id=$id" something

You'll need to get the 3rd parameter right, the where part... As you did not mention any, I've put 1 this will update the whole table to reflect your code, but I'm sure it is not what you want.
Read more about the update function at http://doc.prestashop.com/display/PS15/DB+class+best+practices#DBclassbestpractices-update()
Also note that you can simply run a query, at least while prototyping if it let's you go faster using the execute() function.


Q:

Problems with the encoding of several concatenated files in python?

I have a folder of lots of .txt files in spanish and I decided to merge them in one .txt file as follows:
import os
import shutil
def concatFiles():
    path = '/Users/user/Desktop/OpinionsTAG_txt/'
    files = os.listdir(path)
    with open("/Users/user/Desktop/concat_file.txt", "wb") as fo:
        for f in files:
            with open(os.path.join(path, f), "rb") as fi:
                shutil.copyfileobj(fi, fo)

if __name__ == "__main__":
    concatFiles()

The problem is that the output(i.e. concat_file) doesn't respect the character spanish encoding for example in the concat_file is direcci√≥n instead of dirección. Another thing is that I'm working in OS X, when i open the concat_file with sublime text it looks like this: 0000 0001 2000 0000 0000 0001 4000 0000 and when i open concat_file with text edit it looks as i wanted, why is this happenning and how can i solve it?.

A:

Try using codecs, as suggested here: https://stackoverflow.com/a/19591815/4339369. This will allow you to read and write the files as UTF-8, which may solve your problem.
import codecs
import os
import shutil
def concatFiles():
    path = '/Users/user/Desktop/OpinionsTAG_txt/'
    files = os.listdir(path)
    with codecs.open("/Users/user/Desktop/concat_file.txt", "wb",encoding='utf8') as fo:
        for f in files:
            with codecs.open(os.path.join(path, f), "rb",encoding='utf8') as fi:
                shutil.copyfileobj(fi, fo)

if __name__ == "__main__":
    concatFiles()

A good overview of Unicode issues in Python 2.x can be found here: http://nedbatchelder.com/text/unipain.html.
Edit for anyone in the future: on OS X, you can usually determine a file's encoding by
file -I <filename>

from How do I determine file encoding in OSX?.


Q:

How can I execute python script with command line flag

I have this bit of code:
of = open("oldfile")
nf = open("newfile",'w')
for line in of:
     if len(line) > 17:
             nf.write(line)

of.close()
nf.close()

and instead of specifying 17, I want to be able to use a variable put it in my scripts directory and execute it directly. If there is no flag, it could print something like 'scriptname'. If there is a flag, as there is below, it would execute the code.

$ myscriptname -l 17 oldfile newfile

A:

See the optparse module for checking the flag and setting the value, or the newer (and better) argparse if you're willing to use 2.7+. As for putting it in my scripts directory I don't quite understand what you want exactly.

A:

If you just want quick and dirty access to the command line parameters:
import sys
print sys.argv # <-- this is an array containing all the command line parameters

If you want some more control, you can use the optparse module.


Q:

How to parse this string to array?

How to parse this string with fomat as below to array or anything that can access each string by index?
"[\"string 1\",[\"string 2\",\"string 3\"],\"string 4\"]" // to array_1
"[[\"string 5\",\"string 6\",\"string 7\"],\"string 8\"]" // to array_2

Example, array_1[1][0] == "string 2" or array_2[0][2] == "string 7"
Thank you very much!

A:

I've reproduced your code and got the expected results, I think your issue lies within array_2 having an extra bracket at the end of it.
var array_1 = ["string 1",["string 2","string 3"],"string 4"];
var array_2 = [["string 5","string 6","string 7"],"string 8"];

console.log(array_1[1][0]); // "string 2"
console.log(array_2[0][2]); // "string 7"

You can see it all working here:
http://jsfiddle.net/t7SDr/
Edit
To do this in C#, you can simply do this:
string[] array_1 = {"string 1",{"string 2","string 3"},"string 4"};

var stringItem = array_1[1][2];


Q:

Insect ID. Montreal, Qc (Canada)

I've found this bug in my appartment today and I was wondering what insect it is? Thank you.

A:

This is a "click beetle" (Coleoptera, Elateridae). They have this name because of the loud click sound they produce. They are related to fireflies (Lampyridae), and some click beetle species are themselves luminescent.
According to the link above:

A spine on the prosternum can be snapped into a corresponding notch on the mesosternum, producing a violent "click" that can bounce the beetle into the air.

I don't know about those North American beetles, but in South America I've seen click beetles jumping more than 30cm in the air.
Here is a photo of a click beetle in Montreal, from the Pest Control Canada website, which looks like your specimen:

Unfortunately, the entomologist that identified the animal in the photo above didn't narrow it down to Genus or Species.


Q:

Animation with JavaScript

How to animate a div into determinated coordenades X and Y and choose the velocity with JavaScript?

        <meta charset="UTF-8">
        <title>Animation</title>

<img src="image"

    <form id="xy">
        X<input type="text" id="X">

        Y<input type="text" id="Y">

        V<input type="text" id="V">

        <input type="button" value="Start">
    </form>

Thanks.

A:

You are not giving enough detail, so I can only suggest something quick and fun using CSS transitions. Check it out.

var image = document.querySelector('#img');

document.querySelector('#xy [type=button]').onclick = function() {

    var x = document.querySelector('#X').value,
        y = document.querySelector('#Y').value,
        v = document.querySelector('#V').value;

    image.style.transitionDuration = v + 's';
    image.style.left = x + 'px';
    image.style.top = y + 'px';
};
#img {
    position: absolute;
    transition: all 2s linear;
    left: 200px;
    top: 10px;
}
<form id="xy">
    X <input type="number" id="X" value="100" step="10">

    Y <input type="number" id="Y" value="100" step="10">

    V <input type="number" id="V" value="1" step="0.1">

    <input type="button" value="Start">
</form>


Q:

Jenkins build log has encoded URLs to child jobs/projects

My Jenkins (1.539 on RHEL) job, named "Parent-Job", is configured to "Trigger/call builds on other projects"; the project triggered is named "Child-Job".
Jenkins "console output" shows the proper output (plain text with HTML links to the Child-Job that was triggered), as shown below:
Console Output

Started by user Rodin, A
[EnvInject] - Loading node environment variables.
Building on master in workspace /var/test/build/jendev_home/jobs/Parent-Job/workspace
No emails were triggered.
Waiting for the completion of Child-Job
Child-Job #44 completed. Result was SUCCESS
...

But in the "log" file in the build directory, the links that were present in the console output are all encoded, and I am unable to parse these links because the encoded text does not match expected value, as shown below:
Building on master in workspace /var/test/...
No emails were triggered.
Waiting for the completion of ESC[8mha:A..._very_long_encoded_value_...9M1g0N0AcApv0yfqQAAAA=ESC[0mChild-Job
...

How can I extract the text of the console output, exactly in the same plain text/html format as is displayed on the Jenkins console?
I need to email the log to various users, and long encoded links in the attachment will make them overlook other important details in the log file.

A:

You can get the console output with the wget command (in a post build step script):
wget -O my_console.log ${BUILD_URL}consoleText


Q:

What to expect from the Ferrari Museum in Maranello

I'm planning to visit the Museo Ferrari in Maranello and I want to know if I would be able to sit in the racing cars (especially the F1-single-seaters).
If I want to avoid the confusion of the big tourist groups, on which weekday should I go?

A:

I was there last September. No, you can't sit in the cars or even touch them (there are loads of staff members to make sure nobody touches them). The visit will take you no more than 40 minutes.

When you enter the first thing you will see is the old racing cars and the office of Enzo Ferrari which includes a replica of him. Then when you go upstairs you can see the modern Ferraris and on the opposite side the old Ferraris, then you can move to the other area of the museum, where you can see a Ferrari Racing boat (I liked it), and after that a hall with several Ferrari F1 cars from the modern era along with pictures and helmets from Ferrari F1 drivers.

Also there's a small room where you can hear the different F1 engines.
I hope this information will help you.
P.S. The best part is that in front of the museum you can rent Ferraris and Lambos for a period of time, you can discuss the price and get yourself a treat.. I drove a Ferrari California and it was amazing (They let you floor the accelerator near the Ferrari Factory), but the drive experience is not related in any way with the museum.


Q:

Standards compliant code for document.all replacement

We have ancient code that dynamically creates HTML form data from a database, and it was written that references document.all to fetch an array of non-uniquely Id'd check boxes.  I need to find the "method of fewest changes" to get the code to function in a Standards-compliant manner.  My question is about replacing both the document.myForm and document.all calls with something that produces the same thing, but is standards-compliant.
<form name="myForm">
....
    <input name="2630" id="ck_2630" onclick="click(document.myForm.ck_2630[0]);" type="checkbox" value="139">Ankle, Left

    <input name="2630" id="ck_2630" onclick="click(document.myForm.ck_2630[1]);" type="checkbox" value="140">Ankle, Right

    <input name="2630" id="ck_2630" onclick="click(document.myForm.ck_2630[2]);" type="checkbox" value="141">Arm, Left

    <input name="2630" id="ck_2630" onclick="click(document.myForm.ck_2630[3]);" type="checkbox" value="142">Arm, Right

...
</form>

The code works in all versions of IE, except for IE 11 in Edge mode, because the code uses document.all('ck_2630') to fetch the array.  Edge gets rid of document.all (the statement if (document.all) returns false), but I don't know if it also does away with the document.<form name>.<element name/id> construct, which seems to handle its fields the same way as document.all does.
<form name="myForm" method="post">
  <button onclick="checkElement('139'); return false;">Select Left Ankle</button>

  <button onclick="checkElement('140'); return false;">Select Right Ankle</button>

  <button onclick="checkElement('141'); return false;">Select Left Arm</button>

  <button onclick="checkElement('142'); return false;">Select Right Arm</button>

      <input name="2630" id="ck_2630" onclick="click(document.myForm.ck_2630[0]);" type="checkbox" value="139">Ankle, Left

        <input name="2630" id="ck_2630" onclick="click(document.myForm.ck_2630[1]);" type="checkbox" value="140">Ankle, Right

        <input name="2630" id="ck_2630" onclick="click(document.myForm.ck_2630[2]);" type="checkbox" value="141">Arm, Left

        <input name="2630" id="ck_2630" onclick="click(document.myForm.ck_2630[3]);" type="checkbox" value="142">Arm, Right

</form>

A:

In all of my research, I have found that the best replacement for document.all is document.getElementById, unless the outcome is expected to return multiple hits and then you need to use the Name attribute for it, and use document.getElementsByName.  This is the solution we've been using, and so far it's worked splendidly.  In places where document.<formName> encounters any problems, we've employed the same solution.


Q:

Why is "rm" so much slower than deleting files via the File Manager?

I witnessed that deleting directories (with the size of a couple of gigabytes) which contain many files is very slow when using rm. It takes up to several minutes!
When deleting the same folder via the File Manager, the job is done within a second. (It takes another second to empty the trash afterwards.)
What is the reason for this?

A:

The rm command actually removes the files, File Manager only moves the files to the trash. It is only when you empty the trash that you see the actual time that rm took to delete the files. So put simply, moving files is quicker than deleting. File Manager moves files while rm removes them.


Q:

Angular 6 TypeScript getElementById returning null when element does exist

Does anyone know why document.getElementById("startDateText") will return null from the paragraph element below, yet if I move that id to the element above it return as I would expect it to?
The Typescript code is fired from a button and is not javascript embedded in the HTML.

Start Date and Time

{{ Detail$?.StartDateTime | date:"MM/dd/yyyy 'at' h:mma" }}

TypeScript:
 const myElement: HTMLElement = document.getElementById("startDateText");
 myElement.innerHTML =this.eventDetail$.StartDateTime;

A:

ngIf will not just "hide" the element, it will remove it from the DOM, so you won't be able to access it if isDates==true.
Suggestion:
You could use [class.hidden]="!isDates" instead. Hidden class is the combination of the two style properties : visibility=0 and display:None, so the element will be kept in the dom, but it won't be rendered.


Q:

Do while loops stop executing after a while?

So Im experimenting a bit with multithreading currently, since im still pretty new to Java. Now, I have multiple threads that all influence the same long variable. However, it seems that afer a while of not doing anything but checking the if statement the while loop just stops executing (as in, it loops infinitely). It does work if i just print something within the while-loop.
Does not work:
while(true){
  if(longVariable < 2)
    break;
}

Does somehow work:
while(true){
  System.out.println("hi");
  if(longVariable < 2)
    break;
}

Why is this?

A:

while(true){
  if(longVariable < 2)
    break;
}

In this code, there is no reason for the JVM to believe that longVariable will ever change. It can effectively rewrite it to:
long cached = longVariable;
while(true){
  if(cached < 2)
    break;
}

Which loops infinitely if longVariable is at least two when it executes, because nothing can change cached.
You have to give the compiler a hint that this rewrite isn't allowed. It works with the System.out.println on your JVM because it happens to be implemented with synchronization (which is common, but not required). This inserts memory barriers which means that the cached value of longVariable is invalidated, and has to be read again.
But it's not guaranteed to work. To make it work correctly, either declare the variable volatile:
volatile long longVariable

which prevents its value from being cached.
Or use something like an AtomicLong instead of a plain long variable.
Or, most onerously, use explicit synchronization (ensuring that all reads of and writes to the variable are synchronized on the same "something"):
long v;
synchronized (something) {
  v = longVariable;
}
if (v < 2) ...


Q:

Approx RSSI value range for FAR, NEAR and IMMEDIATE

I'm working on a Cordova mobile application that scan for Beacon signals and the application reacts to the beacon address and RSSI (distance) values. I use Cordova plugin BluetoothLE by Rand Dusing to read the Beacon signals and I use Estimote Beacons. I get the responses, but is there a way to estimate an approximate distance from the RSSI value? Can someone help me with an approx RSSI value range for FAR, NEAR and IMMEDIATE?

A:

In order to get a distance estimate, you also need to be able to read the TxPower reference value transmitted by the beacon.  This indicates what the RSSI should be at one meter.  You can read more about this here: Understanding ibeacon distancing
If the plugin does not provide access to this value, you may hard code it in your app if you know the value is fixed for all the beacons your app will see.  The default value is typically -59.  You can then try using the formula referenced in the link above.
You can then convert the distance to immediate, near and far with numerical ranges.  The exact numbers are not published by Apple, but immediate is about 0.5 meters or less and far anything above 3 meters.  Near is anything in between.
You will note that the RSSI jumps around a lot with radio noise, which will cause your distance estimates to vary, too.  You can smooth this out by calculating a running average over 20 seconds or so, which is similar to what iOS does.
Finally, note that each Android device has a different RSSI to distance conversion.  The formula linked above works well for iPhone and the Nexus 4.  A different formula is required for a Nexus 5, Galaxy S3/S4/S5 and other Android devices.


Q:

Jquery AutoComplete Gets Hidden by Jquery Slider - JQuery Equivalent of wmode?

I'm using Jquery UI's autocomplete, found here, and Nivo slider, found here,  on my website. The Autocomplete is above the nivo slider. What's happening is on the first slide of my nivo slider, when I type in something for the autocomplete, suggestions appear without the banner below covering it. But when the second slide appears the suggestions are hidden underneath the banner. I'm basically using the default settings for both jquery ui autocomplete and nivo slider.
Here's a graphic:

I read about wmode, which is basically a fix if the banner was in flash, but mines in jquery. I'm thinking it will have to do with z-index. Am I correct? How should I fix this?
Thanks for all help!

A:

The dropdown (autocomplete) that comes out from the textbox, as part of jQuery UI's autocomplete: gets dynamically created a with a z-index: 1 within it's wrapper, <ul class="ui-autocomplete" style="z-index: 1; ...etc">
You'd simply need to make sure all autocomplete things (or even just that specific one) have a much higher one than nivo slider.
jsFiddle DEMO (get it to come up, then inspect, you'll see style="z-index: 99999;"
$( ".autocompleteThis" ).autocomplete({
    source: availableTags,
    open: function (event, ui) {
        $('.ui-autocomplete').css('z-index', '99999');
    }
});

Use the open: function (event, ui) {} to set the autocomplete z-index there.


Q:

group by on scipy sparse matrix

I have a scipy sparse matrix with 10e6 rows and 10e3 columns, populated to 1%. I also have an array of size 10e6 which contains keys corresponding to the 10e6 rows of my sparse matrix. I want to group my sparse matrix following these keys and aggregate with a sum function.
Example:
Keys:
['foo','bar','foo','baz','baz','bar']

Sparse matrix:
(0,1) 3              -> corresponds to the first 'foo' key
(0,10) 4             -> corresponds to the first 'bar' key
(2,1) 1              -> corresponds to the second 'foo' key
(1,3) 2              -> corresponds to the first 'baz' key
(2,3) 10             -> corresponds to the second 'baz' key
(2,4) 1              -> corresponds to the second 'bar' key

Expected result:
{
    'foo': {1: 4},               -> 4 = 3 + 1
    'bar': {4: 1, 10: 4},
    'baz': {3: 12}               -> 12 = 2 + 10
}

What is the more efficient way to do it?
I already tried to use pandas.SparseSeries.from_coo on my sparse matrix in order to be able to use pandas group by but I get this known bug:
site-packages/pandas/tools/merge.py in __init__(self, objs, axis, join, join_axes, keys, levels, names, ignore_index, verify_integrity, copy)
    863         for obj in objs:
    864             if not isinstance(obj, NDFrame):
--> 865                 raise TypeError("cannot concatenate a non-NDFrame object")
    866
    867             # consolidate

TypeError: cannot concatenate a non-NDFrame object

A:

I can generate your target with basic dictionary and list operations:
keys = ['foo','bar','foo','baz','baz','bar']
rows = [0,0,2,1,2,2]; cols=[1,10,1,3,3,4]; data=[3,4,1,2,10,1]
dd = {}
for i,k in enumerate(keys):
    d1 = dd.get(k, {})
    v = d1.get(cols[i], 0)
    d1[cols[i]] = v + data[i]
    dd[k] = d1
print dd

producing
{'baz': {3: 12}, 'foo': {1: 4}, 'bar': {10: 4, 4: 1}}

I can generate a sparse matrix from this data as well with:
import numpy as np
from scipy import sparse
M = sparse.coo_matrix((data,(rows,cols)))
print M
print
Md = M.todok()
print Md

But notice that the order of terms is not fixed.  In the coo the order is as entered, but change format and the order changes.  In other words the match between keys and the elements of the sparse matrix is unspecified.
  (0, 1)    3
  (0, 10)   4
  (2, 1)    1
  (1, 3)    2
  (2, 3)    10
  (2, 4)    1

  (0, 1)    3
  (1, 3)    2
  (2, 1)    1
  (2, 3)    10
  (0, 10)   4
  (2, 4)    1

Until you clear up this mapping, the initial dictionary approach is best.


Q:

Is it possible to read Google+ username from PHP without Authentication?

I'd like my web page to say "Welcome, [Google+ name here]!"
and so I've been looking around for a solution and checking whether or not it is possible to do it without asking him/her to log my website through Google+.
Looking around for it I found some libs:
  require_once 'google-api-php-client/apiClient.php';
  require_once 'google-api-php-client/contrib/apiOauth2Service.php';

Are these useful to my purposes? And the main question is: is what I wanna do possible (tips?)?
Thanks in advance.

A:

No, that isn't possible. If you want to know who the user is, you'll have to have them provide access to that information via sign-in or with an OAuth scope that allows you to query for their basic profile information.


Q:

Difficulty racking HP ProLiant Gen8 servers

We're an all Proliant shop with around 50 servers, mostly DL360s and DL380, from G5's through G7's.  We just got our first two G8's in and went to rack them.  We were stunned to find out that the new cable management arms protrude almost 1 inch deeper into the rack then previous iterations of the Proliant line.
Unfortunately that causes them to occupy the same space as the PDU's in our APC racks.  In a non-densely populated section of rack that's no biggie, but in a densely populated section it's impossible to get the cable arm into place without dislodging another machine's power.  Has anyone else run into this?  Obviously racking machines without cable management arms is not an option.  I supposed we could reconfigure our racks but that's a nightmare.

A:

So there are a few things in play here. Model/make of rack? Photos?

Perhaps your rack isn't deep enough to accommodate everything... I'm assuming you're not using HP racks. APC, maybe? Either way, see if there's some flexibility in where you can place your vertical rails on the enclosure. If there's some fore-aft slack, that could be a solution.
Pro-tip... don't use cable management arms. If you're on vertical PDU's, try appropriately-sized power cables for A+B feed (think 1-foot/2-foot cables). Cable management units are complicated and restrict airflow.

There are two cases I can think of for using cable management arms + telescoping rails TODAY.

Servers that have hot-swap RAM, PCI, etc. inside the chassis. This is rare today, though.
Storage servers/enclosures like the Sun x4540, where you need access to running disks inside the chassis.

I think you can get a feeling for the intended use of a particular piece of server equipment based on the mounting hardware/rails and robustness of the cable management. When my 1U DL360 systems started shipping with two pieces of velcro as the cable management, I realized that less emphasis was being placed on the ability to pull the server out of the rack while running.
The examples below have substantial railkits and cable management arms.
Hot-swap RAID RAM and PCI in a running server. HP ProLiant DL740 G1.

Hot-swap disks in a storage server that remained running through multiple disk replacements. Sun x4540.

From the rear...

But really, standard 1U and 2U systems benefit most from short power cables, vertical PDUs and velcro.


Q:

how to move cptscatterplot line little forward

I have implemented cptscatterplot lines.In my app, i have bars under labels and based on yvalues cptscatterplot line will be drawn.
If value is empty then i am breaking the line and continuing again if value is valid, but the line ends with starting point of the bar that bit confusing whether it is valid or not.
can some one help me that can we move line to middle of the bars, i mean starting/ending the line in the middle of the bar.
Thanks in advance. Please help me regarding this struggling alot.

A:

You can move either the bars or the scatter plot line. To move the bars, use the barOffset property or add an offset to the bar locations. To move the scatter plot, add an offset to the x-values of the plot.


Q:

How to make Monoid instance for my type?

I have the following type:
data SomeType = Var String
    deriving (Eq,Show)

newtype TypeA = TypeA [(String, SomeType)]
  deriving (Eq,Show)

Also, I have a function:
fun1 :: TypeA -> TypeA -> TypeA

I can use this function for mappend.
I don't understand, how to implement Monoid interface in my case.

A:

If you already have fun1, just add an instance:
instance Monoid TypeA where
   mempty = .... -- fill this with the neutral element
   mappend = fun1

Probably, you want mempty = TypeA [].


Q:

Understanding the health check and multi region implementation of API Gateway

I'm trying to implement a health check for multiple API Gateways deployed to multiple regions. For this, I'm following this article.
Long story short, you need to replicate the exact same API Gateways (and their corresponding Lambda functions) in all of the regions. The use Route53 to create one domain name backed by multiple endpoints.
My question is related to the way Route53 is setup. In that article, health check endpoints are populated by API Gateway' Stage Invoke URLs. While region endpoints are populated by Target Domain Name from API Gateway's Custom Domain Name.
Why are these two endpoints populated by different values? If we can use Stage Invoke URL in the health check, why do we need to have Custom Domain Name in the first place? Why can't we just use the same Stage Invoke URL to populate the region endpoints?

A:

If we can use Stage Invoke URL in the health check, why do we need to have Custom Domain Name in the first place?

The stage URL is unique to each region.  If you health-checked the custom domain, you'd be implicitly checking the region that was (a) closest to the individual health-checker and (b) already believed to be healthy, which would be useless as a health check target.
On the other hand, if you don't create a custom domain that's the same in each region, then you wouldn't have a common domain name for your clients to access.  You can't just point an arbitrary hostname at an API Gateway endpoint and have it work -- API Gateway needs to expect traffic for that hostname, which is what you're doing when you deploy with a custom domain.
A related question might be why do you need the target domain name? Why not use it for the health checks?  The target domain name is, as its name implies, only a target domain name, used only by DNS for routing.  It shouldn't accept requests sent directly to it that don't use the custom domain for SSL and in the HTTP Host header.


Q:

how to list all questions that has no answer in online discussion forum

I am creating online discussion forum in PHP as my last semester project and I want to list all questions that have no answers in unanswered page, same as in Stack Overflow.
But I have no idea that how to implement that; I search a lot in internet but still I can't find that how to list all questions that has no answers.
Below is my code:
<?php
@session_start();
include("include/user_header.php");
include("include/connection.php");

$query="SELECT * FROM question WHERE NOT EXISTS (SELECT * FROM answer WHERE answer.question_id = question.question_id);"
$result = mysql_query($query) or die(mysql_error());
?>

            <form name="frm_cms" method="post" class="printable">

 Questions

                        <?php
                            while($row = mysql_fetch_array($result))
                            {
                        ?>

                                    <a href="javascript:setAction('pass_id','<?php echo $row['question_id']; ?>');" >
                                        <?php echo $row['title']; ?>

                                    <?php
                                        $tgNm = explode(",",$row['tag_name']);
                                        for($k=0;$k<count($tgNm);$k++)
                                        {
                                            $k+1;
                                    ?>
                                            <a href='question.php?id=<?php echo $tgNm[$k]; ?>'>
                                    <?php
                                                echo getFromId("tag", "tag_name", "id", $tgNm[$k]);
                                    ?>

                                    <?php
                                        }
                                    ?>

                        <?php
                            }
                        ?>

          </form>

<?php
include("include/user_footer.php");
?>

A:

I think something like this is worth a try:
SELECT DISTINCT question.id
FROM question
LEFT JOIN answer ON (question.id = answer.question_id)
WHERE answer.id IS NULL

I've left-joined to the answer table (since we want that join to fail) and then compared a non-null column to NULL. Rows that return are therefore questions that do not have an answer.


Q:

How can I insert multiple row into oracle database using one insert statement?

Possible Duplicate:
Best way to do multi-row insert in Oracle?

I have this insert statement
INSERT INTO mytable VALUES
('val1', 'val2'),
('aa',   'cc'),
('ww',   'dd');

and I got this error
ORA-00933: SQL command not properly ended

A:

you are using oracle, try this
INSERT ALL
    INTO mytable ("id", "name")
         VALUES ('val1', 'val2')
    INTO mytable ("id", "name")
         VALUES ('aa', 'cc')
    INTO mytable ("id", "name")
         VALUES  ('ww', 'dd')
SELECT * FROM dual  ;

or simple
INSERT INTO mytable ("id", "name") VALUES ('val1', 'val2');
INSERT INTO mytable ("id", "name") VALUES ('aa', 'cc');
INSERT INTO mytable ("id", "name") VALUES ('ww', 'dd');