text:
Q: How to simplify a switch statement to reduce the cyclomatic complexity I have a big switch statement that has a cyclomatic complexity of 31 and it must be refactorized to at least 25.
This is the error: Severity Code    Description Project File    Line    Suppression State   Suppression State
Error   CA1502  'Worker.StartListening()' has a cyclomatic complexity of 31. Rewrite or refactor the method to reduce complexity to 25.
Thank you!
Here is the code:
public void StartListening()
    {
        var consumerSettingsSection= this.configurationManager.GetSection<ConsumerSettingsSection>("appZ/consumer");
        foreach (var setting in consumerSettingsSection.QueueSettings)
        {
            var eventType = ConsumedEventType.NotSpecified;

            switch (setting.Name)
            {
                case "A":
                    eventType = ConsumedEventType.A;
                    break;

                case "B":
                    eventType = ConsumedEventType.B;
                    break;

                case "C":
                    eventType = ConsumedEventType.C;
                    break;

                case "D":
                    eventType = ConsumedEventType.D;
                    break;

                case "E":
                    eventType = ConsumedEventType.E;
                    break;

                case "F":
                    eventType = ConsumedEventType.F;
                    break;

                case "G":
                    eventType = ConsumedEventType.G;
                    break;

                case "H":
                    eventType = ConsumedEventType.H;
                    break;

                case "I":
                    eventType = ConsumedEventType.I;
                    break;

                case "J":
                    eventType = ConsumedEventType.J;
                    break;

                case "K":
                    eventType = ConsumedEventType.K;
                    break;

                case "L":
                    eventType = ConsumedEventType.L;
                    break;

                default:
                    eventType = ConsumedEventType.NotSpecified;
                    break;
            }

            var consumer = new ChannelConsumer(setting, eventType);
            consumer.MessageConsumed += this.Consumer_MessageConsumed;
            consumer.StartConsuming();
        }
    }

A: You can try to simplify your code using Enum.TryParse method:
 if (Enum.TryParse(setting.Name, true, out eventType))
     return eventType;
 else
     return ConsumedEventType.NotSpecified;

You can parse the setting.Name string to ConsumedEventType, use the parsed value, otherwise return ConsumedEventType.NotSpecified value.
It's easier than maintaining a list of values. In terms of your code above you can write something like that
foreach (var setting in consumerSettingsSection.QueueSettings)
{
    var eventType = ConsumedEventType.NotSpecified;
    if (Enum.TryParse(setting.Name, true, out ConsumedEventType parsedEvent))
    {
         eventType = parsedEvent;
    }
    //rest of code
}

Or even easier
if (!Enum.TryParse(setting.Name, true, out ConsumedEventType eventType))
{
    eventType = ConsumedEventType.NotSpecified;
}

Please, keep in mind that inline out variables are supported starting from C# 7

A: Use a Dictionary<string, ConsumedEventType>:
var d = new Dictionary<string, ConsumedEventType>()
{
    { "A", ConsumedEventType.A },
    { "B", ConsumedEventType.B },
    { "C", ConsumedEventType.C },
    ...
}

Now get the actual value that fits your settings.Name:
ConsumedEventType type;
var type = !d.ContainsKey(settings.Name)
    ConsumedEventType.NotSpecified :
    d[setting.sName];


text:
Q: Holomorphic versus algebraic $\mathbb C^*$-actions I believe that the following is true:
Statement. A holomorphic $\mathbb C^*$-action on a complex projective manifold is algebraic if and only if it has a fixed point.
Where can I find a proof of this statement? Is it really true that no one ever wrote down this statement in such a form?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Redshift doesn't work without internet connection because of lacking location info My redshift does only work if there is an internet connection on my notebook. Is there a workaround? It's not convenient that one can't specifiy this inside the software. This is my terminal output:
empedokles@thinkpad:~$ redshift
Trying location provider `geoclue'...
Started Geoclue provider `Geoclue Master'.
Service »geoclue« is used.
Could not get location (3 retries left): Geoclue master client has no usable Position providers.
Couldn't get position from Service.
empedokles@thinkpad:~$

A: Look at /usr/share/doc/redshift/example-redshift.conf. Note particularly the bit where lat and lon are assigned manually. Copy this file (or part of it, if you don't like all the settings) to ~/.config/redshift.conf, figure out your latitude and longitude (with google maps?), and edit the manual override appropriately.
Note that you could probably have figured this out by looking at man redshift, info redshift, (which describe setting location manually) and the output of dpkg -L redshift (where you would have seen that it provided example-redshift.conf).


text:
Q: PDO: check for updated or inserted record using mysql INSERT ON DUPLICATE KEY UPDATE Using PDO / PHP and MySQL, how can I check if a record was inserted or updated when I use an INSERT ON DUPLICATE KEY UPDATE statement?
I have seen a solution using mysql_affected_rows() for PHP, but I am looking for a way I can use with PDO.

A: If you use PDO::exec() the return value will be 1 if the row has been inserted and 2 if the row has been updated.
If you're using a prepared statement and PDOStatement::execute() the same is true for PDOStatement::rowCount()


text:
Q: Diamond Operator and Fourier Coefficients Let $d\in(\mathbb{Z}/N\mathbb{Z})^\times$, then one has the Diamond operator $\langle d \rangle$ acting on $M_k(\Gamma_1(N))$ via $\left(\begin{array}{cc}a&b\\c&d\end{array}\right)\in\Gamma_0(N)$ in the usual Hecke way.
I was wondering, given some $f\in M_k(\Gamma_1(N))$ with Fourier expansion $\sum a_nq^n$, if we know exactly how $\langle d\rangle $ acts on the Fourier coefficients $a_n$. I can't seem to find this result in the literature.
Thanks for the help!

A: Unfortunately, there's no straightforward formula for this, which is one of the reasons why one often works with the eigenspaces $M_k(\Gamma_1(N), \chi)$ instead.


text:
Q: PIN based Login in Windows 8.1 Missing I installed a fresh copy of Windows 8.1 Pro using Hyper-V, and updated with all updates via Windows Update. It's not domain joined.

I cannot however activate a PIN based login for the installation and I'm not sure why. I'm using a Microsoft account to login (not just a local login).
I have even manually enabled the feature using group policy (which apparently only should have mattered for a domain joined workstation anyway), rebooted, and it's still not available.
As far as I can tell, everything else seems normal and is working as expected.
For Sign-in options, I only see Password as a choice:


text:
Q: How to safeguard an API against malicious code being sent to it from a 3rd-party site I have a form built in Wordpress which sends data to a remote server of mine running on Node, which then processes the form and sends it to MongoDB.
The form is processed with something similar to:
$('#theForm').submit(function(){
   $.post('http://parthtoserver.com/api/postForm', formdata, function(returnedData){
      if(returnedData === 'Success'){
         // do success stuff here
      }
   });
});

My Node API's code is:
exports.saveNewUser = function (req, res) {
   console.log("Saving a new user");

   var data = req.body;

   var user = {
       firstName: data.firstName,
       lastName: data.lastName,
       location: data.location,
       email: data.email,
       timezone: data.timezone
   };

   db.users.find({email:user.email}, function(err,record){

    if(err){
        console.log("There was an error finding record " + err);
    }else if (record.length){
        if(record[0].paidStatus === 1){
            console.log("User already exists");
            res.header("Access-Control-Allow-Origin", "*");
            res.header("Access-Control-Allow-Headers", "X-Requested-With");
            res.send('UserExists');
        }
    }else{
        db.users.save(user, function(err, record){
            if(err){
                console.log("There was an error: " + err);
            }else{
                console.log("Updated user");
                res.header("Access-Control-Allow-Origin", "*");
                res.header("Access-Control-Allow-Headers", "X-Requested-With");
                res.send('Success');
            }
        });
    }
   });
};

I 'suppose' there's no harm really in another site being able to post data to my API which would then get saved to my database - but from a security standpoint, is there anything I can do to ensure that this isn't malicious code?

A: Can't tell whether you are using express or not, but most likely you are.
In your express app config:
app.use(express.basicAuth('username', 'password'));

// add your middleware to check referrer
app.use(myCheckReferrer);

function myCheckReferrer(req, res, next) {
  if ( req.get('Referrer') === "somesite.com" )
    next();
  else
    res.json(500, { error: 'Oops, no thank you!' })
}

read express doc here
In the client you need to add basic authorization header, referrer is added automatically
$.ajax({
    url: 'http://parthtoserver.com/api/postForm',
    type: 'post',
    data: formdata,
    headers: {
        Authorization: "Basic dXNlcm5hbWU6cGFzc3dvcmQ="
        // the hash is base64 hash of the string "username:password"
        // without the quote include the colon
    },
    dataType: 'json',
    success: function(returnedData){
      if(returnedData === 'Success'){
         // do success stuff here
      }
   }
});


text:
Q: Centering a png on a gradient background I'm trying to center a png on top of my gradient background but I can't get it to work.

html {
  height: 100%;
  background-color: red;
  background: -webkit-linear-gradient(#02747A, #48266C); /* For Safari 5.1 to 6.0 */
  background: -o-linear-gradient(#02747A, #48266C); /* For Opera 11.1 to 12.0 */
  background: -moz-linear-gradient(#02747A, #48266C); /* For Firefox 3.6 to 15 */
  background: linear-gradient(#02747A, #48266C); /* Standard syntax */
}
#rocket1 {
  height: 300px;
  width: auto;
  margin-left: auto;
  margin-right: auto;
}
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title></title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/octicons/3.1.0/octicons.min.css">
    <link rel="stylesheet" href="style.css">

I know that absolute position doesn't work with margin, however, that's the only way I can get the png ON the background instead of leaving a white space. How can I do it?
This is what I have now

This is how I want it to be

A: You can do this with position: absolute and transform: translate()

html {
  height: 100%;
  background-color: red;
  background: -webkit-linear-gradient(#02747A, #48266C); /* For Safari 5.1 to 6.0 */
  background: -o-linear-gradient(#02747A, #48266C); /* For Opera 11.1 to 12.0 */
  background: -moz-linear-gradient(#02747A, #48266C); /* For Firefox 3.6 to 15 */
  background: linear-gradient(#02747A, #48266C); /* Standard syntax */
}

#rocket1 {
  height: 70%;
  width: auto;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

A: You should add
display: block;

to your #rocket1
See Fiddle


text:
Q: Ubuntu 18.04 (ESXi 6.5) -- Live Server crashing -- Pasting 21 Lines Was wondering if anyone has experienced this with 18.04 where if you paste 20+ lines, where it hard locks the system. Looking in ESXi, Ubuntu usually uses about  29 MHz, but after pasting 20~21 lines, CPU spikes to 3.1 GHz and hard locks. Then I have to go to ESXi and reset it. I'm using this VM for a jumpbox for my lab network. Nothing is showing in the /var/log/kern.log as to point towards an issue. Below is what I was pasting:
set interfaces ge-0/0/27 disable
set interfaces ge-0/0/28 disable
set interfaces ge-0/0/29 disable
set interfaces ge-0/0/30 disable
set interfaces ge-0/0/31 disable
set interfaces ge-0/0/32 disable
set interfaces ge-0/0/33 disable
set interfaces ge-0/0/34 disable
set interfaces ge-0/0/35 disable
set interfaces ge-0/0/36 disable
set interfaces ge-0/0/37 disable
set interfaces ge-0/0/38 disable
set interfaces ge-0/0/39 disable
set interfaces ge-0/0/40 disable
set interfaces ge-0/0/41 disable
set interfaces ge-0/0/42 disable
set interfaces ge-0/0/43 disable
set interfaces ge-0/0/44 disable
set interfaces ge-0/0/45 disable
set interfaces ge-0/0/46 disable
set interfaces ge-0/0/47 disable

A: This seems to be caused by VMXNET 3 some how. This issue also spread to all of my VMs running 18.04, including brand new installs with no patches.  I finally got an error message stating something about the driver. I migrated all of my vUbuntu 18.04 to e1000s and they've worked perfectly since.


text:
Q: How can two squads of friends join the same DMZ instance? In the Call of Duty DMZ mode, you are in squads of 3 players, however it's possible to create an alliance when in game by inviting other squads to join you.
You can invite a squad using the ping wheel.
However, when myself and 5 of my clan mates want to play in two separate squads, we cannot seem to be able to get into the same game instance.
Is there a way for us to join the same game instance? We have tried launching at the same time over and over and had no luck.

A: The best luck you'd have for this is just have both groups start matchmaking at the same time. Since player counts are quite high this will probably be difficult, though.
Assimilation isn't really meant for team stacking the way you want it... it's more for like organically created alliances.


text:
Q: Dollar-quotes failing with JDBC I have to write a function in PLPGSQL but I have problem with the function body quoted with dollar-quoting. Using the first tutorial:
CREATE FUNCTION inc(val integer)
RETURNS integer AS
$BODY$
BEGIN
    RETURN val + 1;
END;
$BODY$
LANGUAGE PLPGSQL;

I get an error:

unterminated dollar-quoted string at or near $$

Searching on google I just found it's a JDBC Driver problem but I cannot update it.
So I have tried to change the DELIMITER to remove $$:
DELIMITER ++;
CREATE FUNCTION inc(val integer)
RETURNS integer AS
++BODY++
BEGIN
    RETURN val + 1;
END;
++BODY++
LANGUAGE PLPGSQL;
DELIMITER ;

The command doesn't return any error but function doesn't exists when I try to call it:
select inc(4);

What am I missing?

A: The underlying problem is JDBC's inability to deal with dollar-quotes.
I think this was fixed with JDBC version 9.4.1208 (2016-02-16).
See:

*

*Exceptions when creating a trigger in PostgreSQL 9.1

*How to execute plpgsql anonymous block in Oracle SQL Developer?
You can avoid the problem by using plain quotes for the simple case:
CREATE FUNCTION inc(val integer)
  RETURNS integer AS
'
BEGIN
   RETURN val + 1;
END
' LANGUAGE plpgsql;

See:

*

*What are '$$' used for in PL/pgSQL

*Insert text with single quotes in PostgreSQL


text:
Q: Elegant way to skip elements in an iterable I've got a large iterable, in fact, a large iterable given by:
itertools.permutations(range(10))

I would like to access to the millionth element. I alredy have problem solved in some different ways.

*

*Casting iterable to list and getting 1000000th element:
return list(permutations(range(10)))[999999]

*Manually skiping elements till 999999:
p = permutations(range(10))
for i in xrange(999999): p.next()
return p.next()

*Manually skiping elements v2:
p = permutations(range(10))
for i, element in enumerate(p):
    if i == 999999:
        return element

*Using islice from itertools:
return islice(permutations(range(10)), 999999, 1000000).next()

But I still don't feel like none of them is the python's elegant way to do that. First option is just too expensive, it needs to compute the whole iterable just to access a single element. If I'm not wrong, islice does internally the same computation I just did in method 2, and is almost exactly as 3rd, maybe it has even more redundant operations.
So, I'm just curious, wondering if there is in python some other way to access to a concrete element of an iterable, or at least to skip the first elements, in some more elegant way, or if I just need to use one of the aboves.

A: Finding the nth permutation may just be an example but if this is actually the problem you are trying to solve then there is a much better way to do this.  Instead of skipping the elements of the iterable you can calculate the nth permutation directly.  Borrowing the code from another answer here:
import math

def nthperm(li, n):
    li = list(li)
    n -= 1
    s = len(li)
    res = []
    if math.factorial(s) <= n:
        return None
    for x in range(s-1,-1,-1):
        f = math.factorial(x)
        d = n / f
        n -= d * f
        res.append(li[d])
        del(li[d])
    return res

Example and timing comparison:
In [4]: nthperm(range(10), 1000000)
Out[4]: [2, 7, 8, 3, 9, 1, 5, 4, 6, 0]

In [5]: next(islice(permutations(range(10)), 999999, 1000000))
Out[5]: (2, 7, 8, 3, 9, 1, 5, 4, 6, 0)

In [6]: %timeit nthperm(range(10), 1000000)
100000 loops, best of 3: 9.01 us per loop

In [7]: %timeit next(islice(permutations(range(10)), 999999, 1000000))
10 loops, best of 3: 29.5 ms per loop

Same answer, over 3000 times faster.  Note that I did make a slight modification to the original code so that it will no longer destroy the original list.

A: It is indeed awefully wasteful to slurp up a million items just to get to the next. Unfortunately, whether it can be avoided depends on your iterator: If the iterator has a way to skip directly to a particular offset, it can implement the __getitem__ method and you can use it to request iterator[1000000] directly. (How it gets there is up to the generating algorithm).
If your data source needs to generate all the prior values in order to get there, how you throw them away is the least of your problems. You can choose a nice way, but it's just icing on the cake.
PS. Given the context of your question I was going to outline an algorithm for generating the n-th permutation directly, but I see @F.J. beat me to it. Nice solution! :-)

A: Use the itertools recipe consume to skip n elements:
def consume(iterator, n):
    "Advance the iterator n-steps ahead. If n is none, consume entirely."
    # Use functions that consume iterators at C speed.
    if n is None:
        # feed the entire iterator into a zero-length deque
        collections.deque(iterator, maxlen=0)
    else:
        # advance to the empty slice starting at position n
        next(islice(iterator, n, n), None)

Note the islice() call there; it uses n, n, effectively not returning anything, and the next() function falls back to the default.
Simplified to your example, where you want to skip 999999 elements, then return element 1000000:
return next(islice(permutations(range(10)), 999999, 1000000))

islice() processes the iterator in C, something that Python loops cannot beat.
To illustrate, here are the timings for just 10 repeats of each method:
>>> from itertools import islice, permutations
>>> from timeit import timeit
>>> def list_index():
...     return list(permutations(range(10)))[999999]
...
>>> def for_loop():
...     p = permutations(range(10))
...     for i in xrange(999999): p.next()
...     return p.next()
...
>>> def enumerate_loop():
...     p = permutations(range(10))
...     for i, element in enumerate(p):
...         if i == 999999:
...             return element
...
>>> def islice_next():
...     return next(islice(permutations(range(10)), 999999, 1000000))
...
>>> timeit('f()', 'from __main__ import list_index as f', number=10)
5.550895929336548
>>> timeit('f()', 'from __main__ import for_loop as f', number=10)
1.6166789531707764
>>> timeit('f()', 'from __main__ import enumerate_loop as f', number=10)
1.2498459815979004
>>> timeit('f()', 'from __main__ import islice_next as f', number=10)
0.18969106674194336

The islice() method is nearly 7 times faster than the next fastest method.


text:
Q: how to run a batch file from java using administrator privileges? how to run a batch file from java using administrator privileges?

I am trying to do this.But code is not working.
String cmd = "runas /profile /user:Administrator /cmd.exe /C certutil -addstore ROOT  E:\\WORK\\UI\\DesktopRecorder\\userdata\\certgen\\X509CA\\ca\\new_ca.crt";

Runtime run = Runtime.getRuntime();
Process process = run.exec(cmd);

A: You can create a shortcut to your bat file and make it run as administrator from Properties > Advanced,
Now that you created a shortcut to your bat file lets say its name is example.bat and its located on C drive, so it means that its full name is c:\\example.bat.lnk
In order to run this shortcut, you will need to run it using ProcessBuilder,
it should look like that:
ProcessBuilder pb = new ProcessBuilder("cmd", "/c","c:\\example.bat.lnk");
Process p = pb.start();

It won't work using Runtime.getRuntime().exec();

A: runas needs its main input parameter encapsulated in double quotes.  The kicker is that cmd.exe does too, if you are passing it a command string with spaces, so you will have to use escape characters for it to work on the windows command prompt:
runas /profile /user:Administrator "cmd.exe /C \"certutil -addstore ROOT  E:\\WORK\\UI\\DesktopRecorder\\userdata\\certgen\\X509CA\\ca\\new_ca.crt\""

You would then have to escape that entire string again for it to work in your java code:
String cmd = "runas /profile /user:Administrator \"cmd.exe /C \\\"certutil -addstore ROOT  E:\\\\WORK\\\\UI\\\\DesktopRecorder\\\\userdata\\\\certgen\\\\X509CA\\\\ca\\\\new_ca.crt\\\"\"";

Sometimes in runas with a nested cmd call, you don't have to escape the backslash \ characters, so if that fails, you may want to try replacing the sequences of four backslashes with two.  Good luck!


text:
Q: When returning to a state, when does $scope reload? I have a list object in the parent state of this controller. Every time I load the state that uses this controller, $scope.items is emptied and the controller must load the data from the parent scope again.
ListCtrl corresponds to the list state. The parent state contains many lists.
.controller('ListCtrl', ['$scope','$state','$timeout',
    function($scope, $state, $timeout) {
    console.log($scope.items); // undefined
    if(!$scope.items) { // always evaluates to true
        $timeout(function() {
            $scope.items = $scope.$parent.list.items;
        }, 500);
    } else {
        console.log($scope.items); // never executes here
    }
}])

It was my understanding that AngularJS by default caches some views. Does this mean the caching does not apply to the scope variables in the cached views? And most importantly, is there a way to cache this $scope.items so that every time I return to this state, there isn't this timeout delay?

A: As a beginner of AngularJS, what I understand is that $scope.items is only defined within the current controller. If you want to load items in your html content, just define items under that controller used in that specified html tag.
I made up a toy example ,
angular.module('scopeExample', [])
.controller('MyController', ['$scope', function($scope) {
  $scope.username = 'World';

}]);

which is similar to that on AngularJS Scope documentation.

A: Parent Controller
 .controller('parentController', ['$scope','$state','$timeout','$rootScope'
        function($scope, $state, $timeout, $rootScope) {
        $rootScope.items=['item 1','item 2'];
    }])

Another Controller
.controller('ListCtrl', ['$scope','$state','$timeout','$rootScope'
        function($scope, $state, $timeout,$rootScope) {
        console.log($rootScope.items); // Should give the result
        if(!$scope.items) { // always evaluates to true
            $timeout(function() {
                $scope.items = $scope.$parent.list.items;
            }, 500);
        } else {
            console.log($scope.items); // never executes here
        }
    }])

Dont forget to add $rootScope on top.

A: The solution ended up being to check if the $rootScope.list.item had been loaded, instead of just the $scope.item.
if(!$rootScope.list) {
    $timeout(function() {
        $scope.items = $rootScope.list.items;
    }, 1000);
} else {
    $scope.items = $rootScope.list.items;
}


text:
Q: Quotient ring of complex polynomials and ideal domain Let f(X) = X^2 − 2X + 5 ∈ C[X] and
the ideal generated by f(X) be I = f(X)C[X]. (where C(X) is the set of complex polynomials)
Prove that the quotient ring C[X]/I is not an integral domain.
Since C(X) is commutative and has multiplicative identity 1, so does the quotient ring, satisfying (ID1).
I need to disprove:
(ID2): whenever a, b ∈ C[X]/I satisfy ab=0, either a=0 or b=0 or both,
or (ID2'): whenever a, b ∈ C[X]/I are non-zero, ab is also non zero
And that's where I get stuck, can anyone help me?

A: Hint $\ \Bbb Z/6\,$ is not a domain since $\,2\cdot 3 = 0,\ 2\neq 0,\ 3 \neq 0.\ $ Exactly the same thing happens in your example because over $\,\Bbb C\,$ every quadratic is reducible $\, f = gh,\,$ therefore  $\,g,h\,$ will be nontrivial zero-divisors in $\,\Bbb C[x]/f,\,$ just as were $\,2,3\,$ above.

A: Hint.  Remember that in the ring modulo $f(X)$, you can take $f(X)$ to be the zero element.  So, given that complex numbers are allowed, can you factorise $f(X)$ into two polynomials?
(But not $f(X)=(1)f(X)$ or similar, as then one of the factors is zero.)

A: $\mathbb{C}[X]$ is factorial, so the question of whether $f$ is prime is the same as whether $f$ is irreducible.
So you need to show that $f$ isn't irreducible.


text:
Q: Escape and validation inputs required for two database? I'm currently working on a WordPress website project and I am hoping someone can help me out on this.
In the registration page, the data entered is stored into the WordPress database. I've also build a connection to store those data into an external database as well. So basically, If a visitor registers on the site, their data info gets stored in the WP and external DB.
My question is since the external DB relies on checking to see if the submit button has been pressed, do those data input values need to be escaped to prevent sql injection?
I know the data submitted to WordPress has already been sql escaped.
Thanks for helping.

A: I'd do something like this:
INSERT INTO database2.table ... SELECT ... FROM database1.table WHERE ...

That way you can cut HTML/PHP out of the process entirely.


text:
Q: Display specific products on a CMS page Could someone help me with some code to display specific products on a Magento CMS page?
The idea being that I build a page that has multiple sections on it (sections meaning a heading, some intro text and a small handful of products) and the user can add a selection of the displayed products to their cart from this page.
Ideally, the products should be displayed in the grid format, and I should be able to display between 1 and 6 products in each section.
I am using Magento 1.4.0.1 currently.
Cheers!

A: Consider using a CMS Widget to do this for you.
Here is one: Product List Widget
It isn't free but there are others if you look around.


text:
Q: Using nonce in custom Wordpress API end-point I'm trying to write an plugin that allows a Wordpress authenticated user to access Firebase. I'd like a Javascript app that is delivered from Firebase hosting to make an API request to Wordpress and get back a signed JWT.
Since I want to use the authenticated user, I figure I'll need to send a nonce with the API request. In order to test that I've got the following code Plugin code:
function my_awesome_func($data) {
  $uid = $data['id'];
  // var_dump($data);
  var_dump(wp_create_nonce( 'wp_rest' ));
  var_dump(get_current_user_id());
  return $uid;
}

add_action( 'rest_api_init', function () {
  register_rest_route( 'telomere/firebase_jwt/v1', '/user/(?P<id>\d+)', array(
    'methods' => 'GET',
    'callback' => 'my_awesome_func',
  ) );
} );

The idea being - the first time I hit the end-point it returns the nonce. I'll then append it to the URL and try again, hopefully getting the current user details the second time around.
http://localhost/wp-json/telomere/firebase_jwt/v1/user/1234?_wpnonce=<nonce>
All I get back is
{"code":"rest_cookie_invalid_nonce","message":"Cookie nonce is invalid","data":{"status":403}}
How do I fix this code so that it provides and accepts a nonce?
Thanks,

A: The problem was my misunderstanding of how a nonce was created (despite the docs being excellent).
https://developer.wordpress.org/reference/functions/wp_create_nonce/ states that it uses the user's UID in the generation of the nonce, but when I first called the custom API end-point the user was presenting as unauthenticated. The nonce then created didn't verify.
Instead, I copied the Hello Dolly code and output an authenticated nonce on the admin page and then used that in my test API call.
FWIW, it looks like this
function my_awesome_func($data) {
  $uid = $data['id'];
  return $uid;
}

add_action( 'rest_api_init', function () {
  register_rest_route( 'telomere/firebase_jwt/v1', '/user/(?P<id>\d+)', array(
    'methods' => 'GET',
    'callback' => 'my_awesome_func',
  ) );
} );

function output_nonce() {
  $nonce = wp_create_nonce('wp_rest');
    printf('nonce %s', $nonce);
}

add_action( 'admin_notices', 'output_nonce' );

A: You have used wp_create_nonce in server response area - which is wrong. That is a place for wp_verify_nonce.
You need to create wp_create_nonce at  a client side.
For example:
jQuery.ajax( {
        url: "YOUR_API_URL?api_nonce=<?php echo wp_create_nonce("wp-rest"); ?>",
        method: 'GET'
    } ).done( function ( response ) {
});

And then, inside callback function you can verify it
function my_awesome_func($data) {
  var_dump(wp_verify_nonce( $_GET["api_nonce"], 'wp-rest' ) );
  return $uid;
}

Or better to use official guide for API auth: https://developer.wordpress.org/rest-api/using-the-rest-api/authentication/


text:
Q: Can't delete persistent silly file Linux Mint 18.3 (based on Ubuntu Xenial)
This is a dual-boot machine with W10, which may be significant
I'm trying to delete some backintime jobs. Using rm -rf top-level-dir doesn't work: I get an unexpected message saying "directory not empty".
Drilling down into the offending directory, I get to:
mike@M17A /media/Shared/backintime/backintime/M17A/root/1/20180731-120001-297/backup/home/mike/.local/share/gvfs-metadata $  ls -lsa
total 13
// TOTAL THIRTEEN??? WHY IS ONLY ONE FILE LISTED?
8 drwxrwxrwx 1 root root 8192 Oct 11 23:35 .
4 drwxrwxrwx 1 root root 4096 Oct 11 23:35 ..
1 -rwxrwxrwx 0 root root  200 May 27  2018 computer:
// OH DEAR, THE FILENAME ENDS WITH A COLON: LOOKS OMINOUS
// HERE I'M TRYING TO REMOVE THIS ONE FILE
mike@M17A /media/Shared/backintime/backintime/M17A/root/1/20180731-120001-297/backup/home/mike/.local/share/gvfs-metadata $  rm computer:
rm: cannot remove 'computer:': No such file or directory
mike@M17A /media/Shared/backintime/backintime/M17A/root/1/20180731-120001-297/backup/home/mike/.local/share/gvfs-metadata $  cat computer\:
�meta&op�� [
�&0Khnemo-list-view-sort-columnnemo-list-view-sort-reversednemo-list-view-zoom-level���[
�'/���1falsenamemike@M17A /media/Shared/backintime/backintime/M17A/root/1/20180731-120001-297/backup/home/gvfs-metadata $  e
// HERE I'M TRYING TO MV IT TO A MORE SENSIBLE NAME (NOT ENDING IN COLON)
mike@M17A /media/Shared/backintime/backintime/M17A/root/1/20180731-120001-297/backup/home/mike/.local/share/gvfs-metadata $  mv computer: spot
mv: cannot stat 'computer:': Input/output error

I switch to root:
mike@M17A /media/Shared/backintime/backintime/M17A/root/1/20180731-120001-297/backup/home/mike/.local/share/gvfs-metadata $  su
Password:
M17A gvfs-metadata # ls -lsa
ls: cannot access 'computer:': Input/output error
total 12
8 drwxrwxrwx 1 root root 8192 Oct 11 23:44 .
4 drwxrwxrwx 1 root root 4096 Oct 11 23:35 ..
? -????????? ? ?    ?       ?            ? computer:
// WELL I APPEAR TO HAVE DONE SOMETHING TO THIS "FILE" ... BUT WHAT?
M17A gvfs-metadata # rm computer
rm: cannot remove 'computer': No such file or directory
M17A gvfs-metadata # rm computer:
rm: cannot remove 'computer:': Input/output error
M17A gvfs-metadata # mv computer: spot
mv: cannot stat 'computer:': Input/output error

A: This is an old solution, which means only old guys like me remember it.
Find the inode of the file with ls -i. Let's say it is 1611645009. Then in the directory you mention execute the command
find $NAME_OF_DIRECTORY -inum 1611645009 -exec /bin/rm {} \;
If that doesn't do it, then I'm baffled too.


text:
Q: Preventing delayed_job background jobs from consuming too much CPU on a single server My Rails application has a number of tasks which are offloaded into background processes, such as image resizing and uploading to S3.  I'm using delayed_job to manage these processes.
These processes, particularly thumbnailing PDFs (using Ghostscript) and resizing images (using ImageMagick), are CPU intensive and often consume 100% CPU time.  Since these jobs are running on the same (RedHat Linux) server as the web application itself, as well as the DB, they can lead to our web application being unresponsive.
One solution is to get another server on which to run only the background jobs.  I guess this would be the optimal solution?  However, since this isn't something I can do immediately I wonder whether it would be possible to somehow make the background jobs run at a lower operating system priority, and hence consume less CPU cycles in doing their work?
Thoughts appreciated.

A: If I'm not mistaken, delayed_job uses worker processes that will handle all the background jobs. It should be easily possible to alter the OS scheduling priority of the process when you start it.
So instead of, for example:
ruby script/delayed_job -e production -n 2 start

try:
nice -n 15 ruby script/delayed_job -e production -n 2 start


text:
Q: How to read a specific line from a text file in c++? C++ program that displays on the screen item codes with corresponding
item descriptions and prices. It asks the user to enter the code of the item
purchased by a customer. It looks for a match of the item code stored in items.txt.
How can I output only a specific line from a text file after the user inputs the item code?

A: You need to read the file line-by-line (std::getline), extract (depending on the exact format, e.g. by searching for a whitespace in the string) and compare the code and then return the corresponding line on a match.
It is not possible to access lines from a text file directly by index or content.
This is assuming that you mean the file contains lines in the form
code1 item1
code2 item2
//...

If the code is just the index of the line, then you only need to call std::getline in a loop with a loop counter for the current index of the line.

If you do this multiple times on the same file, you should probably parse the whole content first line-by-line into a std::vector<std::string> or a std::(unordered_)map<std::string, std::string> or something similar to avoid the costly repeated iteration.
Depending on the use case, maybe it would be even better to parse the data into a database first and then query the database, even if it is only e.g. sqlite or something like that.


text:
Q: CSS Trick to show border on table and cells when cells are not empty and show no border otherwise Is there any way to make sure that a table and cells it contains have a border only when the cells are not empty?
If all the cells of the table are empty, then no border should be visible.

A: See the empty-cells CSS property.

A: The only way to do this with pure CSS relies on a very modern browser. You'll need to use CSS advanced selectors to accomplish this. For example, you can use tr:empty to find the cells with no children elements in them, for plain text you'll need to do some more.
Unfortunately, these only exist in CSS3, so if you can't use javascript, or touch the markup, then you'll only be able to accomplish in the very latest browsers.
To learn more about CSS3 selectors Click Here

A: Give the empty cells one class name and the non-empty ones another. One class specifies a border, the other without.

A: To the best of my knowledge, this isn't within the capabilities of CSS, the best option I can think of is to apply classes dynamically either through server-side code while populating the data, or through JavaScript once the page has been loaded into the browser.

A: It looks like the empty-cells property suggested by strager might do the trick.  If it doesn't do what you need, I would look at using some clever javascript library like jQuery.  You can probably set a hook to update the border style of the cell to be getBorderStyle(this) When the content of this cell change.
Look at the jquery "change" hook here: http://docs.jquery.com/Events/change
If you select all your cells (which you can do using a css selector) and add a change hook to run some function you write called updateBorder() or some such, you should be good.  I imagine it would be something like this:
$("table.someClass td").change(function() { updateBorder(this) })

A: Rendering of cell borders is partly dependant on if you are collapsing borders or not. If they are not collapsed border are not show by default if there is no cell content. This can be switched by using the CSS property empty-cells.
If you are collapsing borders you loose the abillity to control border display based on the presence of cell content.


text:
Q: Versioning of android APK Does it make any sense to version Android APK in the version control system (git, mercurial etc.)? Can anyone think of any strong (dis)advantage?
I'm relatively new to Android and after trying it, I haven't spot much benefit of doing so. On the other hand, it wasn't harmful either. Since I wasn't able to find appropriate answer very quickly, thought that informed answer from an Android expert could be helpful reference.

A: You don't need to versionate the APK, but use tags for storing the release of a versionCode in the PlayStore, so you can go back the code to that point.
There's no benefits in having older apks for debugging.

A: I'd recommend create a 'development' branch and a 'release' branch that you will periodically merge with. You handle all of you changes and development work in the development branch and once you've gotten your app to a point you're ready to release it to the Play Store, increment "versionCode" and "versionName" and  merge the code into the release branch with a commit message indicating both the "versionCode" and "versionName". That way, if any build of your app ever experiences a problem you have the code at the correct snapshot the app was released so you can directly "pull" the code and implement a hotfix without having to stash or revert any (possibly destructive) changes you've made inside of your development branch. If you need to make a hotfix for code you've released, just create a temporary branch forking from the 'release' code that has the error. Make all your changes there, again increment "versionCode" and "versionName" and then merge the changes back into 'release' with a very meaningful commit message again indicating the increment "versionCode" and "versionName". This should be a simple Fast-Forward merge (best kind of merge). You'll wanna manually copy the changes over to the 'development' branch to avoid a non Fast-Forward merg when you eventually wanna push the code to release.
I'd also recommend adding a 'experimental' changes branch, that is forked from development so you can use that area as a sandbox for experimental changes that you don't want to disturb the work flow inside of the 'development' branch.
You only wanna "version Android APK" when pushing your code to the release branch in my code. This will help you fix a bug if an old release.


text:
Q: scattered line is not metrizable How to prove: scattered line is not metrizable?
I proved that it is not second countable, not separable. It is normal. Urysohn metrization theorem wont help as it is not separable. What property of metric space is it not satisfying?

A: HINT: Prove that $\Bbb Q$ is a closed set that is not a $G_\delta$-set: in a metric space every closed set is a $G_\delta$-set. You'll want to use the Baire category theorem in $\Bbb R$. (For future reference, you may find it useful to know that this space is also called the Michael line.)

A: To polish up the method Brian M. Scott introduced above,
$\Bbb Q$ is a closed subset of the scattered line because its complement Irr is obviously an open subset of the scattered line. Suppose scattered line can be completely metrizable. Then $\Bbb Q$ can be completely metrizable with the induced topology. Since the interior of $\Bbb Q$ with respect to the scattered line topology is empty, by the Baire Category Theorem this leads to a contradiction.


text:
Q: ImportError after changing the top level directory name I changed the top level directory name on a project, and now I'm getting an import error for Flask:
ImportError: No module named flask
The virtual environment is active - so unless there's something broken in its settings, that's not the problem.
I thought the error was because my path had changed, so in Sublime Text 2 I corrected the path name in the project's .sublime-project file to reflect the new top level directory name. However, this doesn't seem to have worked, or it is insufficient, as I'm still getting errors. Where else might I need to address this path change to get things working again, or is there something else I need to do?
Thanks in advance for your help!


text:
Q: How to create a database In iPhone application? I have a very simple application, and i want to add into it a database. For all of you, to understand what i mean, it should look similar like default application "Contacts" in iPhone. It should contain list of elements (like people names in contact list), and when the user click name, the next view appear, which contain information about contact (and other buttons as well). All of data must be inside of application (not downloading from web pages).
Please help me! I am novice, and i have no clue what i should looking for, not just an array i guess... i will gratefully accept any of advice and links to examples, related to my problem.
PS. My app is not about contacts, its about diet. For example, it should look like: user click element "cheese" in list, and then  next view provide information about product (calories, protein, fat etc.)

A: Take a look at the following free lessons from iTunes U. Paul Hegarty is an excellent teacher. These are dense so I had to watch a couple times, but everything you need is here:
Basic Persistence:
http://www.stanford.edu/class/cs193p/cgi-bin/drupal/node/285
Core Data (Lecture):
http://www.stanford.edu/class/cs193p/cgi-bin/drupal/node/287
Core Data Demo:
http://www.stanford.edu/class/cs193p/cgi-bin/drupal/node/289
These pages have the pdfs, but go to iTunes and download the full lectures for an excellent overview. Also don't miss the CoreDataTableViewController available on the last linked page - handy.
Without this course I would not be an iOS developer, so I can't recommend it highly enough.
Enjoy,
Damien


text:
Q: Tracking VideoJS with Google Tag Manager I would like to track VideoJS using Google Tag Manager. Since I am fairly new to GTM I have no idea how to proceed. I have only done some basic stuff like tracking mailto links and PDF downloads using tutorials.
I found a project on Github called videojs-ga which looks promising, now how would I correctly connect and set this up in GTM? Idealy we would end up tracking the play count and how long the video's get watched. There is no need to track multiple videos per page since there is only one video on a single page at any time.
Also if there is a better way to track VideoJS with GTM I am open to suggestions!

A: I suggest you make a fork from the code in that repository/ download the file from src  and make the changes locally. In line 104 where it says:
 sendbeacon = function(action, nonInteraction, value) {
      if (window.ga) {
        ga('send', 'event', {
          'eventCategory': eventCategory,
          'eventAction': action,
          'eventLabel': eventLabel,
          'eventValue': value,
          'nonInteraction': nonInteraction
        });
      } else if (window._gaq) {
        _gaq.push(['_trackEvent', eventCategory, action, eventLabel, value, nonInteraction]);
      } else if (options.debug) {
        console.log("Google Analytics not detected");
      }
    };

you replace the stuff within the sendbeacton function object in the following way:
 sendbeacon = function(action, nonInteraction, value) {
     dataLayer.push(
          'eventCategory': eventCategory,
          'eventAction': action,
          'eventLabel': eventLabel,
          'event' : 'videojs'
     );
};

(make sure your dataLayer variable is declared somewhere before your GTM code). Create a script tag that links the modified script to our page.
Then create three variables of the "dataLayer" type which read their values from eventCategory, eventAction and eventLabel respectively. Set up a Google Analytics tag and configure it for event tracking, and pass in the variables to the respective fields. Create a trigger type custom event, event eq 'videojs' and use it to fire the GA event tracking tag.


text:
Q: Unit of window.innerWidth Following
var w = (window.innerWidth - 100px);

is not working.
Can someone show me how it works?

A: .innerWidth returns a number in pixels, so you can just subtract 100 from it:
var w = window.innerWidth - 100;

Note that this will be negative, if the browser is under 100px in width.


text:
Q: Using DateTime::createFromFormat to convert the datepicker give me the wrong result Good day here is my date format converter code
$sdate = $_POST['dtpicker'];
$dtpicker = DateTime::createFromFormat('d/m/Y', $sdate);

if ($dtpicker === false) {
   echo
   "<script LANGUAGE='JavaScript'>
    window.alert('Date is Expire Please try again!');
    window.location.href='https://www.home.ae/online-form/';
    </script>";
}

$d = $dtpicker->format('Y-m-d');

echo $d;

[Here is the date I enter from my site]
[1]:
https://i.stack.imgur.com/wiDQC.png
$sdate = 12/29/2021
The expect result should be
2021-12-29
but the result is
2023-05-12
any error in my code?
thank you guys


text:
Q: Как правильно задать условие если у атрибута DATA определенное значение? Как правильно задать условие включения звука если у атрибута DATA определенное значение?
делаю так, но не работает:

<audio id="myaudio" loop><source src="audio.ogg" type="audio/ogg; codecs=vorbis" /> </audio>

A: Ваш скрипт работает, но код вы написали в функции, которая нигде не вызывается, ее надо вызвать, вот пример:

window.onload = function (){

function gdgd(){
     var elem = document.getElementById("st1");
     var ell = elem.getAttribute('data');
     if (ell != 1) {
       alert('не равно единице');
    } else {
       alert('все-таки равно единице');
    }
 }

gdgd();

}

  <audio id="myaudio" loop>
  <source src="audio.ogg" type="audio/ogg; codecs=vorbis" /></audio>


text:
Q: I keep running into this error if I use my custom TF Records when training the Model in TensorFlow Object Detection API V2 Error: tensorflow.python.framework.errors_impl.InvalidArgumentError: assertion failed: [[0.956730783]] [[0.896634638]] [[{{node Assert/AssertGuard/else/_25/Assert/AssertGuard/Assert}}]] [[MultiDeviceIteratorGetNextFromShard]] [[RemoteCall]]
I am using Vehicles Data from RoboFlow and I converted it's PASCAL VOC XML format to TFRecords through TensorFlow's official script and every time I use my data, this error shows up but if use the ones RoboFlow directly gives you then the error doesn't show up at all. A similar error is already reported on TensorFlow issues but it got closed and I tried that solution but It doesn't work for me which involved making sure all my values of label heights and widths were positive


text:
Q: UE4 setting sprite by using C++ I didn't figure out how can i set a sprite in actor class constructor by using its reference.
Reference is "PaperSprite'/Game/cc/combat/units/archer_Sprite_0.archer_Sprite_0'"
I want to make this sprite static. I think should use ConstructorHelpers::FObjectFinder . When i run the code below, i got this error:
sprite = CreateDefaultSubobject<UPaperSpriteComponent>(TEXT("Sprite_comp"));
sprite->SetupAttachment(RootComponent);

ConstructorHelpers::FObjectFinder<UPaperSprite> SpriteAssetObj(TEXT("PaperSprite'/Game/cc/combat/units/archer_Sprite_0.archer_Sprite_0'"));

//sprite->SetSprite(SpriteAssetObj.Object);

"Severity   Code    Description Project File    Line    Suppression State
Error   C2664   'void ConstructorHelpers::ValidateObject(UObject *,const FString &,const TCHAR *)': cannot convert argument 1 from 'T *' to 'UObject *' MyProject   C:\Program Files\Epic Games\UE_4.26\Engine\Source\Runtime\CoreUObject\Public\UObject\ConstructorHelpers.h   110
"
Any help or advice would be nice. Thanks in advance.

A:
I want to make this sprite static.

ConstructorHelpers::FObjectFinder is for finding an asset.
In case of movement would be:
sprite->SetMobility(EComponentMobility::Type::Stationary);

I tested the code below without any problem. Are you sure ConstructorHelpers::FObjectFinder... is causing the error?
static ConstructorHelpers::FObjectFinder<UPaperSprite> SpriteAssetObj(TEXT("PaperSprite'/Game/TEMP/Sprites/SP_TempSprite_1.SP_TempSprite_1'"));
if (SpriteAssetObj.Object)
{
    UE_LOG(LogTemp, Warning, TEXT("PaperSprite loaded"));
}
else
{
    UE_LOG(LogTemp, Warning, TEXT("PaperSprite not found"));
}

Don't forget to add Paper2D module to your YourGame.build.cs file:
PublicDependencyModuleNames.AddRange(new string[] { "Paper2D" });

And add to your file:
#include "PaperSprite.h"


text:
Q: Android Studio - SSLHandshakeException: Trust anchor for certification path not found I'm new to Java/PHP programming and I've tried to find the solution to this (probably simple) fix but I've come up nil. I've checked the Android Developer article on problems with SSL [https://developer.android.com/training/articles/security-ssl#CommonProblems] but that hasn't seemed to solve any of the problems I've been facing so far.
EDIT: This has now been resolved, apparently I forgot to remove the 'S' from 'HTTPS' meaning it was trying to access a secure SSL connection, which I obviously did not have.
The error also includes:
2022-01-23 15:56:27.925 413-1117/? E/audit: avc:  denied  { find } for pid=5704 uid=10342 name=tethering scontext=u:r:permissioncontroller_app:s0:c86,c257,c512,c768 tcontext=u:object_r:tethering_service:s0 tclass=service_manager permissive=0

And the full exception error is displayed as a toast message during running the application:
javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.

I'm trying to access the MySQL PHP of https://192.168.0.159/LoginRegister/signup.php (localhost) via signup.java.
I've also tried adding android:networkSecurityConfig="@xml/network_security_config"  along with along with android:usesCleartextTraffic="true" to the Android Manifest and the certificate.crt/network_security_config.xml in the raw folder and XML folder respectively as per the Android Developer article.
My current Android Gradle Plugin Version is 7.0.4 and my Gradle Version is 7.2 (I've tried changing the versions of both).
If you require any more information regarding the project just let me know.
Thanks a ton,
Brandon.

A: As you have already mentioned, you don't have a SSL certificate to access https for I'm assuming, your localhost ip address.
If you are already using android:usesCleartextTraffic="true" in your manifest, changing the https to http should make things work smoothly.


text:
Q: How to Customize Log File Name and Location in Microsoft Enterprise Library 2.0? I am using .net 2.0 and Microsoft Enterprise Library 2.0. How can I customize the log file name and location. I want to create a log file in my app location and current date as file name. I tried fileName="foo"

A: If you want to incorporate the date into the file name you will have to use programmatic configuration.  See Programatic Configuraton - Enterprise Library (v2.0) Logging Block for an example targeting version 2.0 (luckily enough).
If this is a rolling date (change the date every day for example) then you will have to incorporate some reconfiguration (to change the file name) or to create a custom  trace listener.


text:
Q: What does the animated class do?    $("button").addClass("animated bounce");
   $(".well").addClass("animated shake");
   $("#target3").addClass("fadeOut");

What does the animated class do?
When I take out the "animated" class, the button won't bounce and the well wouldn't shake.
Is the "animated" class part of Bootstrap or jQuery?
I am a beginner and if my question sounds silly, sorry in advance.

A: I figured it out.. thanks to the people who had helped me in the comments section.
Turns out the "animated" class comes from the Animate.css library:
https://animate.style/


text:
Q: What makes Python more used as an implementation language than the others? Perl and Python are often compared to each other (let's not forget Ruby), and almost always those discussions will come to the conclusion pretty much anything you can do in one or the other.
Without going into that, I've noticed that Python however, is often used as an implementation language (uhmm, maybe the term here is incorrect technically - a language you use to, for example, enable some degree of scripting in a large application ... Tecplot, Rhinoceros etc.; these are from the scientific area; there are others surely) and Perl never (well, to my knowledge at least).
So I was wondering - what makes Python more suitable for something like that? What particulars make a language more suitable to be implemented as part of a larger app. for scripting in general? Is it only that that wasn't so common 10 years ago (scripting in applications), and Python is just at its peak at the moment, ... or something else?

A: If you're talking specifically about application scripting, it may simply be that Python is more approachable than Perl to a casual programmer, and thus the developer of the application decides Python would be a better experience for the application's users.  Lets face it, Perl, while powerful, can be... cryptic... at times.
VBScript is also used a lot in Windows applications for this reason.  Its something end users, not programmers, can cobble a small script together in without too much trouble.

A: The term you are after is one of the following, they are (relatively fungible)

*

*Embedded language

*Application scripting language

*Extension language

Lua, JavaScript and Python seem to be some of the most common of these, mainly due to the fact that there is a lot of support for embedding them, and their syntax is considered by many as simple and quite easy to learn.
A few other notable examples of extension languages, Java, used in Eclipse and JetBrains IntelliJ based IDEs.  VimL / VimScript in Vim. Emacs Lisp in GNU/Emacs. (GNU also promote Guile, a Scheme variant as it's extension language of choice.)
At the moment, it's hard to say which language is most commonly used as Extension language, but Lua is extraordinarily easy to embed, JS and Python are relatively difficult (by comparison) but still not especially hard.  MRuby has been developed specifically to be embeddable, however it drops a large part of the standard library as a result.
Within the Microsoft ecosystem, (since the introduction of .Net) CLR languages are all able to extend popular MS apps, VS, MS Office etc.

A: Python is pretty easy to embed and has good documentation on how to do it.
Also, Python has a pretty approachable syntax, even for new users. Perl tends to have obtuse syntax making it less approachable for new users.
Another common language for embedding is Lua. It is known to be fairly easy to embed and has low operating overhead.
Python is well known and used in the Scientific community thanks to SciPy and NumPy, which may influence your particular observations.

A: As a well-known Perl person, I have a few thoughts, and almost none of them are related to one language being better than another. Perl and Python, in the hands of skilled practitioners, can basically do the same things.
You mentioned the perhaps perl hasn't been embedded in anything. I know of or use embedded perls in apache, postgres, nagios, and exim. There are probably many others, but they aren't in the same problem domains that Python dominates.

So, let's think about that a bit more.
First, things take hold often by accident. Perl was initially popular in the biotech community because someone wrote some useful software and other people wanted to use it. If that first person had chosen some other language, people would probably still want to use that initial software.  I've often found people will use the most convenient tool without caring too much about the language it's in.
Second, once something get a foothold, it benefits form a virtuous cycle. Someone builds a useful tool in some language and people start using it. Those people are probably going to stay with that particular language just because it's easier than switching or combining several languages within a project. People only have so much time to think about things. I don't mind working in many languages, but it does take a bit of mental work to switch from one to the other during the day.
Now, as for Perl versus Python, I've been thinking about this for an article for Perl.com (so if you want to tell me about your cool Python stuff, please do!). In my long experience with Perl, I've noticed that we tend to build things for other programmers or what we now call DevOps. There are some turnkey applications out there, but there's much more in the module/framework space to allow you to make applications. This tilts the Perl community toward the hard-core, full-time developer space and lots of backend development.
On the Python side, there are some amazing tools for "normal" people for non-programming tasks. For example, there's youtube-dl, a Python program to download videos. I can't think of that many turnkey Perl things I use that aren't programming tools. Exiftool maybe, but that still seems sysadminy to me? It's not that some other language would have trouble doing this, but the group of people that gravitated to a particular language decided to work on more user-facing things.
Some people don't like Perl's syntax, which is fine, and those people probably aren't the sort that spend quite a bit of time doing shell or systems programming. Perl makes a lot of sense if you come from a unix-heavy background, and if you haven't seen some of those concepts things appear weird (and this is where I like to geek out in my Learning Perl classes). Perl is this beast of a language that pulls in C, awk, sed, shell, BASIC, and anything else Larry Wall thought was useful for getting sysadminy work done. Many of the people I've worked with as Perl programmers work in several languages. That's neither virtue nor vice, just that Perl is the sort of language that attracts that sort of person.
Guido Rossum wasn't designing a language to run the world. He had worked on the teaching language ABC and came up with an evolution of that. The items in the Zen of Python make a lot of sense if you are thinking about classrooms and instructional design. Sometimes those languages escape their initial uses (heck, Macs used to use Pascal!). Since they tend to be simpler or more straightforward, people tend to like them for shorter tasks. I see it similar to how PHP displaced Perl from the CGI webspace. It was a simpler tool that completely satisfied the people doing that stuff.

A: Is Python really more used than other languages?
It depends.
Let's have a look.
In OSS web applications PHP dominates the installations: WordPress, Typo3, Joomla, Magento, ShopWare, Moodle. Maybe the simple templates are a reason for it.
Don't forget that C/C++ is still the gold standard for libraries and system programming.
In academic science, the topics I'm interested in (AI, image recognition, language processing), most projects use C++, Java and/or Python.
Python is mostly used as a glue language just calling libraries. Or there are toolboxes and utilities in some areas (e.g. NLTK, font-utilities) making it convenient to use them out of the box.
In some fields Python is the dominating scripting language. Font making is one of them, where nearly all state of the art tools use Python. Maybe this is caused by history as FontForge supported Python. Nearly all font makers use Python now, also the ones using Perl in the past.
My personal point of view:

*

*as an admin of a web-server farm:

Python, Ruby and Java are a pain. Whatever the reason is, they make problems. PHP since version 7 is also a pain.

*as an application developer:

Perl is my preferred language. Robust, simple for simple problems, complex problems are easier to implement than e.g. in Python or PHP. Perl still has the best Unicode and Regex support. Sure, more keystrokes (~20%) are needed compared to Python, PHP or JavaScript.

*as a scientist

I still prototype in Perl (and port later some parts to JavaScript or C99). My project is mainly implemented in Perl. Either I can use other packages written in Python or whatever without change, or I port "academic quality" Perl/JS/C.
But the pain not using Python grows.

A: Python is easy to embed in C programs and it is easy to add C modules to python.  Python has a lot of inroads in scientific computing with sci.py and numpy, so it is a natural fit for scientific apps.


text:
Q: How to add color to horizontal bar graphs created by giving csv as an input using google charts? I am a newbie to front end development. I am trying a demo example given on Google charts website. I am reading data from a csv file and able to generate a horizontal bar graph. Now i want to give colors to those bars but don't want to write those column names every time.
Below is the code i am referring to. How to read column names run time and color those bars?
  google.charts.load('current', {'packages':['corechart']});
  google.charts.setOnLoadCallback(drawChart);
  function drawChart() {
  $.get("name.csv", function(csvString) {
  var arrayData = $.csv.toArrays(csvString, {onParseValue: $.csv.hooks.castToScalar});
  var data = new google.visualization.arrayToDataTable(arrayData);
  var view = new google.visualization.DataView(data);
  view.setColumns([0,1]);
 var options = {
    title: "Your data in bar format" ,
    hAxis: {title: data.getColumnLabel(0), minValue: data.getColumnRange(0).min, maxValue: data.getColumnRange(0).max},
    vAxis: {title: data.getColumnLabel(1), minValue: data.getColumnRange(1).min, maxValue: data.getColumnRange(1).max},
   legend: 'none'
 };
    var chart = new google.visualization.BarChart(document.getElementById('chart_div'));
 chart.draw(view, options);
  } );

 }

A: looking at the code, the bars are actually represented by rows, not columns.
there are only two columns in the DataView --> view.setColumns([0, 1]);
first column is the name, second the value...
when using rows for the bars, the only way to provide a specific color,
is to use a 'style' column,
you can add using a calculated column in the DataView.
the style column should follow the series column
i'm not sure how you want to assign each color,
but here is an example of adding the calculated 'style' column.
you can read the name using --> dt.getValue(row, 0)
var view = new google.visualization.DataView(data);
view.setColumns([0, 1, {
  role: 'style',
  type: 'string',
  calc: function (dt, row) {
    var color;
    switch (dt.getValue(row, 0)) {
      case 'A':
        color = 'red';
        break;

      case 'B':
        color = 'blue';
        break;

      default:
        color = 'green';
    }
    return color;
  }
}]);


text:
Q: Does spring-data-redis support redis clusters? Does spring-data-redis support redis clusters?
Any example will be helpful for me.

A: Spring Data Redis delegates the Redis connection to a driver library, and Jedis does support clustering. (JRedis is also supported by SDR, but the project appears to have been discontinued as of 2011.)
Sentinels are supported, but only with Jedis.


text:
Q: How to use Storyboard to add Menu to NSTableView? I try to add a context menu to a NSTableView using the interface builder with a storyboard. But I get a strange error message at runtime.
First I created the menu in the scene where the NSTableView is located:

Next I connect the menu outlet of the NSTableView to the menu:

The object structure looks like this:

If I start the application, as soon this view is displayed I get this strange error message:

... Missing placeholder for identifier UpstreamPlaceholder-6yv-X7-Kie
... Attempted to set object of class NSNibExternalObjectPlaceholder as the menu of a NSTableView (0x100b25260).  Ignored.

The view is loaded manually in the code using this method:
eventEditorViewController =
    self.storyboard!.instantiateControllerWithIdentifier("eventEditor") as? NSViewController

What could be the reason for this error message?


text:
Q: CRUD в laravel Уже более 3 лет пишем на Codeigniter, и к сегодняшнему дню он ужасно устарел. Сейчас потихоньку переходим на Laravel, не хватает crud генератора, который был в CI http://www.grocerycrud.com , чтобы быстро генерить админку. Подскажите, есть ли такое в laravel?
A: Есть много Пакетов для Ларавел с CRUD.

*

*Cruddy очень хорошая и можно изменить под свои нужды, интеграция с Sentry Cartalyst для прав доступа.

*Frozennode Administrator Не хуже чем Cruddy.

*SleepingOwl Admin

Есть ещё много других которые поддерживают как 3.0, 4.2 и Laravel 5

A: В документации Laravel всё есть: RESTful Resource Controllers и там же как их создавать artisan'ом.
A: С коробки в Laravel такого нет. Да и не нужно в принципе. Написать нужный CRUD не составляет особого труда. Один раз набросали примерный контроллер, модель и вид, а дальше модифицируйте.
Мне наоборот нравится, что нельзя генерировать сразу админку, так как понимаешь, что пишешь, и можешь легко всё подогнать под свои нужды.


text:
Q: Filter Powerpivot with VBA OK, so this macro is supposed to loop through the pivot's SUPPLIER FILTER based on a list located in another worksheet. After every loop it has to upload the file to the intranet in a .pdf format.
The entire code is:
Sub Adinn()
Dim i As Integer, n As Integer

Application.Calculation = xlCalculateManual

n = Application.WorksheetFunction.CountA(Worksheets("List").Range("A:A")) - 1

ReDim SUPPLIER(n - 1, 1) As String

For i = 1 To n
SUPPLIER(i - 1, 0) = Worksheets("List").Cells(1 + i, 1)
SUPPLIER(i - 1, 1) = Worksheets("List").Cells(1 + i, 2)
Next i

For i = 1 To n
Sheets("To Supplier").Select
ActiveSheet.PivotTables("PivotTable1").PageFields("[Query].[SUPPLIER].[SUPPLIER]").VisibleItemsList = _
"[Query].[SUPPLIER]." & SUPPLIER(i - 1, 0)

Sheets("To Supplier").Calculate

 Sheets("To Supplier").Select

ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
    "http://enterpriseweb.com/portalone/sourcing/Supplier%20documents/" & SUPPLIER(i - 1, 1) _
    & "/Evaluations/" & SUPPLIER(i - 1, 1) & " Credits.pdf" _
    , Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas _
    :=False, OpenAfterPublish:=False
On Error Resume Next

Next i

Application.Calculation = xlCalculationAutomatic

Sheets("Overview").Select

End Sub

I think the issue is with both:
SUPPLIER(i - 1, 0) = Worksheets("List").Cells(1 + i, 1) 'Supplier Name
SUPPLIER(i - 1, 1) = Worksheets("List").Cells(1 + i, 2) 'Supplier Code

When I introduce them as PivotItem and concatenate it to the link.Obviously, what´s supposed to appear there is the value the represent.


text:
Q: Microsoft Excel - Horizontal and Vertical Bars Missing I don't know what I did, but the horizontal and vertical bars are missing in Microsoft 365.
How can I get them back? Is there a particular shortcut?

A: Did you mean the scroll bar?
Did all Workbooks have this problem?
Try to go to File- Options- Advanced- Display options for this workbook- make sure these options are checked:
1. Show horizontal scroll bar
2. Show Vertical scroll bar


text:
Q: VTK Python Wrapper - Exporting Surface Plot I'm using VTK 8.0.1 and python 3.5 and am brand new to VTK. I am trying to export a surface plot using vtkPlotSurface.
By referencing TestSurfacePlot.cxx I have successfully created a surface plot and have been able to render it in python (even though it doesn't really look like a surface plot).
import vtk
import math as m
import numpy as np

## Set things up
chart = vtk.vtkChartXYZ()
view = vtk.vtkContextView()
view.GetRenderWindow().SetSize(800,800)
view.GetScene().AddItem(chart)

## Create a surface
table = vtk.vtkTable()
numPoints = 70;
inc = 9.424778 / (numPoints - 1);
for i in range(0,numPoints):
    arr = vtk.vtkFloatArray()
    table.AddColumn(arr)

table.SetNumberOfRows(numPoints)
for i in range(0,numPoints):
    x = i * inc;
    for j in range(0,numPoints):
        y  = j * inc;
        table.SetValue(i, j, m.sin(m.sqrt(x*x + y*y)))

# Using table, create a surface plot
test = vtk.vtkPlotSurface()
test.SetXRange(0,9.424778)
test.SetYRange(0,9.424778)
test.SetInputData(table)

# Start visualizing the surface plot
chart.AddPlot(test)
view.GetRenderWindow().SetMultiSamples(0)
view.GetInteractor().Initialize()
view.GetRenderWindow().Render()

out = vtk.vtkOBJExporter()
out.SetFilePrefix("test")
out.SetInput(chart)
out.Write()

view.GetInteractor().Start()

In order to better visualize what I've made, I wanted to try and export it and then visualize using Paraview/Visit. However, I'm struggling to find any concrete examples where this type of vtk object is exported...
I have tried adding the following:
out = vtk.vtkOBJExporter()
out.SetFilePrefix("test")
out.SetInput(chart)
out.Write()

But end up with the following type error:
TypeError: SetInput argument 1: method requires a vtkRenderWindow, a vtkContextView was provided.

Can anyone provide assistance? Thanks in advance.

A: You might benefit from using PyVista as it makes creating these types of spatially reference datasets and rendering much more user-friendly. I would avoid using a vtkTable like you have above and move towards VTK data objects that actually represent meshes/surfaces.
import pyvista as pv
import numpy as np

# Create a spatial reference
numPoints = 70
inc = 9.424778 / (numPoints - 1)
x = np.arange(0, numPoints) * inc
y = np.arange(0, numPoints) * inc
xx, yy, _ = np.meshgrid(x, y, [0])
zz = np.sin(np.sqrt(xx*xx + yy*yy))
# Make a PyVista/VTK mesh
surface = pv.StructuredGrid(xx, yy, zz)

# Plot it!
surface.plot(show_edges=True, show_grid=True, notebook=False)

# or save it out for opening in ParaView
surface.save("my_surface.vtk")


text:
Q: PHP 8.1 / imageftbbox Implicit conversion from float to int loses precision I want to write text onto a PNG, since 8.1 I'm getting a warning

PHP Deprecated:  Implicit conversion from float 5.5 to int loses precision

for line
imagefttext($im, 35, 1, $x, $y, $orange, $font, $ausgabecode);

The whole code:
header("Content-type: image/png");
$text = "12345";
$im = imagecreatefrompng("background.png");
$color = imagecolorallocate($im, 255, 255, 255);
$font = './myfont2.ttf';

$bbox = imageftbbox(35, 2, $font, $text);

$x = $bbox[0] + (imagesx($im) / 2) - ($bbox[4] / 2) - 4;
$y = $bbox[1] + (imagesy($im) / 2) - ($bbox[5] / 2) - 5;
if($x < 1){
$x = $x + 1;
}

imagefttext($im, 35, 1, $x, $y, $color, $font, $text);
imagepng($im);
imagedestroy($im);

How do I treat x,y as float at all times?


text:
Q: liferay lucene search not working I am trying to implement Lucene based indexing and searching in Liferay 6.2. I have a custom service builder entity and I want to be able to search on all the fields of this entity. But the problem is it is not searching on all the indexed fields unless I explicitly type the field:value in the search box. It seems like it is just searching on liferay defaults which are
Field.ASSET_CATEGORY_TITLES, Field.ASSET_TAG_NAMES, Field.COMMENTS,
Field.CONTENT, Field.DESCRIPTION, Field.PROPERTIES, Field.TITLE,
Field.URL, Field.USER_NAME

This is my entity
<entity name="Sample" local-service="true" remote-service="true" table="sample">
        <column name="uuid_" type="String" />
        <column name="sampleDbId" type="long" primary="true" />
        <column name="sampleCollectionDbId" type="long" />
        <column name="biobankDbId" type="long" />
        <column name="hashedSampleId" type="String" />
        <column name="hashedIndividualId" type="String" />
        <column name="materialType" type="String" />
        <column name="container" type="String" />
        <column name="storageTemperature" type="String" />
        <column name="sampledTime" type="Date"/>
        <column name="anatomicalPartOntology" type="String" />
        <column name="anatomicalPartOntologyVersion" type="String" />
        <column name="anatomicalPartOntologyCode" type="String" />
        <column name="anatomicalPartOntologyDescription" type="String" />
        <column name="anatomicalPartFreeText" type="String" />
        <column name="sex" type="String" />
        <column name="ageLow" type="long" />
        <column name="ageHigh" type="long" />
        <column name="ageUnit" type="String" />
        <column name="diseaseOntology" type="String" />
        <column name="diseaseOntologyVersion" type="String" />
        <column name="diseaseOntologyCode" type="String" />
        <column name="diseaseOntologyDescription" type="String" />
        <column name="diseaseFreeText" type="String" />
        <column name="countryOfOrigin" type="String" />
        <finder name="uuid" return-type="Collection">
            <finder-column name="uuid_" />
        </finder>

</entity>

I have successfully indexed all the fields that I want to search and I can see it in Luke.
I am indexing it in my indexer as below:
@Override
    protected Document doGetDocument(Object obj) throws Exception {
        // TODO Auto-generated method stub
        System.out.println("-----doGetDocument called------");
        Sample sample = (Sample)obj;

        Document document = getBaseModelDocument(PORTLET_ID, sample);

        if(sample.getSampleCollectionDbId() > 0){
            document.addText("sampleCollectionName", SampleCollectionLocalServiceUtil.getSampleCollection(sample.getSampleCollectionDbId()).getName());
        }
        document.add(new Field("biobankName", BiobankGeneralInformationLocalServiceUtil.getBiobankGeneralInformation(sample.getBiobankDbId()).getBiobankName()));
        document.add(new Field("materialType", sample.getMaterialType()));
        //document.addText("biobankName", BiobankGeneralInformationLocalServiceUtil.getBiobankGeneralInformation(sample.getBiobankDbId()).getBiobankName());
        //document.addKeyword("materialType", sample.getMaterialType());
        document.addKeyword("container", sample.getContainer());
        document.addText("storageTemperature", sample.getStorageTemperature());
        document.addDate("sampledTime", sample.getSampledTime());
        document.addText("anatomicalPartOntology", sample.getAnatomicalPartOntology());
        document.addKeyword("anatomicalPartOntologyVersion", sample.getAnatomicalPartOntologyVersion());
        document.addKeyword("anatomicalPartOntologyCode", sample.getAnatomicalPartOntologyCode());
        document.addText("anatomicalPartOntologyDescription", sample.getAnatomicalPartOntologyDescription());
        document.addText("anatomicalPartFreeText", sample.getAnatomicalPartFreeText());
        document.addKeyword("sex", sample.getSex());
        document.addNumber("ageLow", sample.getAgeLow());
        document.addNumber("ageHigh", sample.getAgeHigh());
        document.addText("ageUnit", sample.getAgeUnit());
        document.addText("diseaseOntology", sample.getDiseaseOntology());
        document.addKeyword("diseaseOntologyVersion", sample.getDiseaseOntologyVersion());
        document.addKeyword("diseaseOntologyCode", sample.getDiseaseOntologyCode());
        document.addText("diseaseOntologyDescription", sample.getDiseaseOntologyDescription());
        document.addText("diseaseFreeText", sample.getDiseaseFreeText());
        document.addKeyword("countryOfOrigin", sample.getCountryOfOrigin());

        return document;
    }

I have also defined the Hits search method in my localserviceimpl class:
public Hits search(long companyId, String keywords) throws SearchException{
        System.out.println("-----SampleLocalServiceImpl search called------");

        SearchContext searchContext = new SearchContext();
        searchContext.setAndSearch(false);

        Map<String, Serializable> attributes = new HashMap<String, Serializable>();

        attributes.put("sampleCollectionName", keywords);
        attributes.put("biobankName", keywords);
        attributes.put("materialType", keywords);
        attributes.put("container", keywords);
        attributes.put("storageTemperature", keywords);
        attributes.put("sampledTime", keywords);
        attributes.put("anatomicalPartOntology", keywords);
        attributes.put("anatomicalPartOntologyVersion", keywords);
        attributes.put("anatomicalPartOntologyCode", keywords);
        attributes.put("anatomicalPartOntologyDescription", keywords);
        attributes.put("anatomicalPartFreeText", keywords);
        attributes.put("sex", keywords);
        attributes.put("ageLow", keywords);
        attributes.put("ageHigh", keywords);
        attributes.put("ageUnit", keywords);
        attributes.put("diseaseOntology", keywords);
        attributes.put("diseaseOntologyVersion", keywords);
        attributes.put("diseaseOntologyCode", keywords);
        attributes.put("diseaseOntologyDescription", keywords);
        attributes.put("diseaseFreeText", keywords);
        attributes.put("countryOfOrigin", keywords);

        searchContext.setAttributes(attributes);
        searchContext.setCompanyId(companyId);
        searchContext.setKeywords(keywords);
        System.out.println(searchContext.getAttributes());

        QueryConfig queryConfig = new QueryConfig();

        queryConfig.setHighlightEnabled(false);
        queryConfig.setScoreEnabled(false);
        //searchContext.setAttribute("materialType:", keywords);
        searchContext.setQueryConfig(queryConfig);

        System.out.println(searchContext.getCompanyId());
        Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(
                Sample.class);
        System.out.println("-----SampleLocalServiceImpl search called------"+indexer.getFullQuery(searchContext));
        System.out.println("-----SampleLocalServiceImpl search called------"+indexer);

        return indexer.search(searchContext);
    }

I am calling this search method from my jsp via localserviceutil class.
So when I type blood in the search box, i get no results but when I type materialType:blood I get the results back.

*

*For emtpy search, the query log gives me
+(+((+(entryClassName:com.xxx.portlet.xxx.model.Sample)))) (gives full result set)

*If I type blood, the query log gives me
+(+((+(entryClassName:com.xxx.portlet.xxx.model.Sample)))) +(assetCategoryTitles:*blood* assetTagNames:*blood* comments:blood content:blood description:blood properties:blood title:blood
   url:blood userName:*blood*)
(empty result set)

*If I type materialType:blood, the query log gives me
+(+((+(entryClassName:com.xxx.portlet.xxx.model.Sample))))
+(materialType:*blood* materialType:blood) (matching result set)
What I want is the user to be able to just type free text in the box and to get back the matching results. But at the moment this is not working as free text search is just searching on the liferay default fields. How can I fix this?
The question is also posted here.

A: It was not enough to set searchContext.setAttributes(attributes); in the Hits search method of localserviceimpl class. I also had to override the postProcessSearchQuery method in my indexer class. So after adding the following method in my indexer class, I got it working.
    @Override
    public void postProcessSearchQuery(BooleanQuery searchQuery, SearchContext searchContext)
        throws Exception {
        System.out.println("-----postProcessSearchQuery called------");

        addSearchTerm(searchQuery, searchContext, "sampleCollectionName", true);
        addSearchTerm(searchQuery, searchContext, "biobankName", true);
        addSearchTerm(searchQuery, searchContext, "materialType", true);
        addSearchTerm(searchQuery, searchContext, "container", true);
        addSearchTerm(searchQuery, searchContext, "storageTemperature", true);
        .....
        .....

        LinkedHashMap<String, Object> params =
            (LinkedHashMap<String, Object>)searchContext.getAttribute("params");

        if (params != null) {
            String expandoAttributes = (String)params.get("expandoAttributes");

            if (Validator.isNotNull(expandoAttributes)) {
                addSearchExpando(searchQuery, searchContext, expandoAttributes);
            }
        }
    }


text:
Q: Loading Garbage values from Database to Listview I want to Load my database data to the arraylist and then from arraylist to listview on button click but when I clicked the button it loads Garbage data to the listview. This is my code. What am I doing wrong?
        save.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
                    final ArrayAdapter<String> adapter = new ArrayAdapter<String>(Bookmarks.this, android.R.layout.simple_list_item_1, list);
                    String query = "Insert into WEB values('" + title.getText().toString() + "','" + address.getText().toString() + "')";
                    db.execSQL(query);
                    Toast.makeText(getApplicationContext(), "Bookmark Inserted", Toast.LENGTH_LONG);
               try {
                    Cursor c = db.rawQuery("SELECT Title FROM WEB", null);
                    c.moveToFirst();
                do {
                    String check = c.getString(c.getColumnIndex("Title"));
                    list.add(check);
                    }
                while (c.moveToNext());
                    lv.setAdapter(adapter);
                    }
                catch (Exception ex) {
                    Toast.makeText(getApplicationContext(), "Error", Toast.LENGTH_LONG);
            }
        }
    });

This is the screenshot of Layout...


text:
Q: PHP Script to copy database from one server to another I have a scenario where I need to copy production database to my dev database on daily basis. Both are different servers. What I have thought of writing a cronjob that will do the stuff. I have written a php script. I am connecting to remote production server via sshpass, taking its dump and then populating that dump.
exec("sshpass -p 'mypassword' ssh root@IP_ADDRESS:PORT");
exec("mysqldump -u root -p DB > production_dump.sql");
exec("mysql -u root -p test < production_dump.sql");

But at first line it throws error of stating
ssh: Could not resolve hostname IP_ADDRESS:PORT: Name or service not known

I have tried given solution on internet but non of them worked. Can any on please explain what I am doing wrong?

A: Your command is failing because it's not formatted right. You need to use one of the following formats:
sshpass -p 'mypassword' ssh root@IP_ADDRESS PORT
sshpass -p 'mypassword' ssh root@IP_ADDRESS -p PORT
sshpass -p 'mypassword' ssh ssh://root@IP_ADDRESS:PORT

However, I'm not sure if the rest of the script will work, especially if it starts asking for a password. A bash script would be the way to go.


text:
Q: C language to show the hex symbol from unsigned char pointer //How to conversion the number 12345 change to the unsigned char*(why is '90') and how to modify code to show the hex value (eg.0x80...)?
#include <stdio.h>
#include <stdlib.h>

typedef unsigned char *byte_pointer;

void show_bytes(byte_pointer, size_t);
void show_bits(int);
void show_int(int);
void show_float(float);
void show_pointer(void *) ;
int  mask_LSbits(int);

void show_bytes(byte_pointer start, size_t len)
{
    size_t i;
    printf("address=%p",start);
    printf("\n");
    for (i = 0; I <len; i++)
    printf(" %x.2x", start[i]);  //modify here, how to change char to hex value
    printf("\n");
}
void show_int(int x) {
    printf("\nival = %d\n", x);
    show_bytes((byte_pointer) &x, sizeof(int));
}
int main()
{
    int ival = 12345;
    float fval = (float) ival;
    int *pval = &ival;

    show_int(ival);

    return 0;

}

A: To display each of the four component bytes of the int value passed (after casting) to your show_bytes function (assuming you want these in the format 0x01), change your printf format string as follows:
printf(" 0x%02x", (unsigned int)start[i]);

The 0x is printed as is; the %02x formats the actual value of start[i] in hexadecimal, always using a field width of 2 and adding leading zeros, if required.
Note that the %x format expects an unsigned int as the corresponding argument, which is why I've added the cast.
The output I get when I run your code (with my suggested modification) is:
ival = 12345
address = 000000CE690FFA30
0x39 0x30 0x00 0x00

Which corresponds to an integer with the following (full) hex value: 0x00003039 - which is 12345, in decimal.
Note, also, that if you add the following line:
printf("address=%p", pval);

in your main function, you will see that the value of the pval address is not the same as the value printed in your show_bytes function! This is because your are passing a copy of ival to show_int, which is placed (most probably) on the stack, and thus is, effectively, a different variable  from the original (which pval points to).


text:
Q: $n-$square root as an exponential If I have for example
$$g(x)=\sqrt[n]{f(x)} \tag 1$$
where it is defined when $f(x)\geq 0$ if $n=2k$, with $k\in \Bbb N$ and if $n=2k+1$ the $\operatorname{dom} g(x)\equiv \operatorname{dom} f(x)$, is it true that
$$\sqrt[3]{f(x)}=\exp(\ln(f(x))/3), \quad ?$$
and in general
$$\sqrt[n]{f(x)}=\exp(\ln(f(x))/n), \quad ?$$

A: Recall that:
$$\ln(x^a) = a\ln(x),$$
for $x > 0$.
Take the logarithm of $\sqrt[n]{f(x)}$:
$$\ln\left(\sqrt[n]{f(x)}\right)=\ln\left[\left(f(x)\right)^\frac{1}{n}\right] = \frac{1}{n}\ln(f(x)).$$
Now, apply the exponential to both sides:
$$\exp\left(\ln\left(\sqrt[n]{f(x)}\right)\right) = \exp\left(\frac{1}{n}\ln(f(x))\right) \Rightarrow$$
$$\sqrt[n]{f(x)}= \exp\left(\frac{1}{n}\ln(f(x))\right).$$
Of course, $f(x) > 0$ for all $x$ in its domain.


text:
Q: Issues using computed.filter and computed.sort together Cross-posted at EmberJS forums
In my app I need to filter a list by one or more properties then sort the filtered results by one or more properties. I've accomplished this with
sortProperties: ['manufacturer:asc', 'modelName:asc', 'series:asc'],

filteredContent: Ember.computed.filter('model', function (model) {
   return model.get('isActive');
}).property('model.@each.isActive'),

sortedContent: Ember.computed.sort('filteredContent', 'sortProperties').property('filteredContent')

The template binds to sortedContent via a normal {{#each item in sortedContent}}
My issues come when trying to edit an item in that list. Editing the first two items in the list is fine - changing the fields shows the changes in the list with no issues. The problem comes when editing anything lower than the first two items. Any changes get reflected on the proper item as well as other items in the list.
I've created a jsbin that shows the issue. I'm not sure if I'm just missing something on how I'm filtering/sorting/binding or if this is a bug within Ember.

A: I fixed it, probably the way you were using the filters/sort that was wrong.
Your fixed and simplified controller :
App.ApplicationController = Ember.ArrayController.extend({
  sortProperties: ['manufacturer', 'modelName', 'series'],
  filteredContent: function() {
    return this.get('arrangedContent').filterBy('isActive');
  }.property('@each.isActive')
});

I also mapped the template to loop over filteredContent instead of sortedContent
And finally two objects had the same ID (not causing the problem but still...)
The working jsbin


text:
Q: (URI::InvalidURIError) "bad URI(is not URI?) I am running a ruby on rails app in the production environment and my ruby version is 1.8.7 and rails version is 3.2.0.
But when ever the URL gets bigger or some one hits that URL I will get a error msg and here is the back trace of the error log.
    /home/ubuntu/.rvm/rubies/ruby-1.8.7-p334/lib/ruby/1.8/uri/common.rb:436:in `split'
 /home/ubuntu/.rvm/rubies/ruby-1.8.7-p334/lib/ruby/1.8/uri/common.rb:485:in `parse'
 /home/ubuntu/.rvm/rubies/ruby-1.8.7-p334/lib/ruby/1.8/open-uri.rb:275:in `open_http'
 /home/ubuntu/.rvm/rubies/ruby-1.8.7-p334/lib/ruby/1.8/open-uri.rb:616:in `buffer_open'
 /home/ubuntu/.rvm/rubies/ruby-1.8.7-p334/lib/ruby/1.8/open-uri.rb:164:in `open_loop'
 /home/ubuntu/.rvm/rubies/ruby-1.8.7-p334/lib/ruby/1.8/open-uri.rb:162:in `catch'
 /home/ubuntu/.rvm/rubies/ruby-1.8.7-p334/lib/ruby/1.8/open-uri.rb:162:in `open_loop'
 /home/ubuntu/.rvm/rubies/ruby-1.8.7-p334/lib/ruby/1.8/open-uri.rb:132:in `open_uri'
 /home/ubuntu/.rvm/rubies/ruby-1.8.7-p334/lib/ruby/1.8/open-uri.rb:518:in `open'
 /home/ubuntu/.rvm/rubies/ruby-1.8.7-p334/lib/ruby/1.8/open-uri.rb:30:in `open'
 app/controllers/home_controller.rb:107:in `import_items'
 /home/ubuntu/.rvm/rubies/ruby-1.8.7-p334/lib/ruby/1.8/open-uri.rb:32:in `open_uri_original_open'
 /home/ubuntu/.rvm/rubies/ruby-1.8.7-p334/lib/ruby/1.8/open-uri.rb:32:in `open'
 app/controllers/home_controller.rb:106:in `import_items'
 actionpack (3.0.7) lib/action_controller/metal/implicit_render.rb:5:in `send_action'
 actionpack (3.0.7) lib/action_controller/metal/implicit_render.rb:5:in `send_action'
 actionpack (3.0.7) lib/abstract_controller/base.rb:150:in `process_action'
 actionpack (3.0.7) lib/action_controller/metal/rendering.rb:11:in `process_action'
 actionpack (3.0.7) lib/abstract_controller/callbacks.rb:18:in `process_action'
 activesupport (3.0.7) lib/active_support/callbacks.rb:461:in `_run__738958071__process_action__908136048__callbacks'
 activesupport (3.0.7) lib/active_support/callbacks.rb:410:in `send'
 activesupport (3.0.7) lib/active_support/callbacks.rb:410:in `_run_process_action_callbacks'
 activesupport (3.0.7) lib/active_support/callbacks.rb:94:in `send'
 activesupport (3.0.7) lib/active_support/callbacks.rb:94:in `run_callbacks'
 actionpack (3.0.7) lib/abstract_controller/callbacks.rb:17:in `process_action'
 actionpack (3.0.7) lib/action_controller/metal/instrumentation.rb:30:in `process_action'
 activesupport (3.0.7) lib/active_support/notifications.rb:52:in `instrument'
 activesupport (3.0.7) lib/active_support/notifications/instrumenter.rb:21:in `instrument'
 activesupport (3.0.7) lib/active_support/notifications.rb:52:in `instrument'
 actionpack (3.0.7) lib/action_controller/metal/instrumentation.rb:29:in `process_action'
 actionpack (3.0.7) lib/action_controller/metal/rescue.rb:17:in `process_action'
 newrelic_rpm (3.3.1) lib/new_relic/agent/instrumentation/rails3/action_controller.rb:34:in `process_action'
 newrelic_rpm (3.3.1) lib/new_relic/agent/instrumentation/controller_instrumentation.rb:255:in `perform_action_with_newrelic_trace'
 newrelic_rpm (3.3.1) lib/new_relic/agent/method_tracer.rb:242:in `trace_execution_scoped'
 newrelic_rpm (3.3.1) lib/new_relic/agent/instrumentation/controller_instrumentation.rb:250:in `perform_action_with_newrelic_trace'
 newrelic_rpm (3.3.1) lib/new_relic/agent/instrumentation/rails3/action_controller.rb:33:in `process_action'
 actionpack (3.0.7) lib/abstract_controller/base.rb:119:in `process'
 actionpack (3.0.7) lib/abstract_controller/rendering.rb:41:in `process'
 actionpack (3.0.7) lib/action_controller/metal.rb:138:in `dispatch'
 actionpack (3.0.7) lib/action_controller/metal/rack_delegation.rb:14:in `dispatch'
 actionpack (3.0.7) lib/action_controller/metal.rb:178:in `action'
 actionpack (3.0.7) lib/action_dispatch/routing/route_set.rb:62:in `call'
 actionpack (3.0.7) lib/action_dispatch/routing/route_set.rb:62:in `dispatch'
 actionpack (3.0.7) lib/action_dispatch/routing/route_set.rb:27:in `call'
 rack-mount (0.6.14) lib/rack/mount/route_set.rb:148:in `call'
 rack-mount (0.6.14) lib/rack/mount/code_generation.rb:93:in `recognize'
 rack-mount (0.6.14) lib/rack/mount/code_generation.rb:89:in `optimized_each'
 rack-mount (0.6.14) lib/rack/mount/code_generation.rb:92:in `recognize'
 rack-mount (0.6.14) lib/rack/mount/route_set.rb:139:in `call'
 actionpack (3.0.7) lib/action_dispatch/routing/route_set.rb:493:in `call'
 newrelic_rpm (3.3.1) lib/new_relic/rack/browser_monitoring.rb:23:in `call'
 /home/ubuntu/.rvm/gems/ruby-1.8.7-p334/bundler/gems/exception_notification-7b77a4ea1a61/lib/exception_notifier.rb:31:in `call'
 spree_core (0.50.2) lib/middleware/seo_assist.rb:23:in `call'
 spree_core (0.50.2) lib/redirect_legacy_product_url.rb:10:in `call'
 warden (1.0.6) lib/warden/manager.rb:35:in `call'
 warden (1.0.6) lib/warden/manager.rb:34:in `catch'
 warden (1.0.6) lib/warden/manager.rb:34:in `call'
 actionpack (3.0.7) lib/action_dispatch/middleware/best_standards_support.rb:17:in `call'
 actionpack (3.0.7) lib/action_dispatch/middleware/head.rb:14:in `call'
 rack (1.2.2) lib/rack/methodoverride.rb:24:in `call'
 actionpack (3.0.7) lib/action_dispatch/middleware/params_parser.rb:21:in `call'
 actionpack (3.0.7) lib/action_dispatch/middleware/flash.rb:182:in `call'
 actionpack (3.0.7) lib/action_dispatch/middleware/session/abstract_store.rb:149:in `call'
 actionpack (3.0.7) lib/action_dispatch/middleware/cookies.rb:302:in `call'
 activerecord (3.0.7) lib/active_record/query_cache.rb:32:in `call'
 activerecord (3.0.7) lib/active_record/connection_adapters/abstract/query_cache.rb:28:in `cache'
 activerecord (3.0.7) lib/active_record/query_cache.rb:12:in `cache'
 activerecord (3.0.7) lib/active_record/query_cache.rb:31:in `call'
 activerecord (3.0.7) lib/active_record/connection_adapters/abstract/connection_pool.rb:354:in `call'
 actionpack (3.0.7) lib/action_dispatch/middleware/callbacks.rb:46:in `call'
 activesupport (3.0.7) lib/active_support/callbacks.rb:416:in `_run_call_callbacks'
 actionpack (3.0.7) lib/action_dispatch/middleware/callbacks.rb:44:in `call'
 rack (1.2.2) lib/rack/sendfile.rb:107:in `call'
 actionpack (3.0.7) lib/action_dispatch/middleware/remote_ip.rb:48:in `call'
 actionpack (3.0.7) lib/action_dispatch/middleware/show_exceptions.rb:47:in `call'
 railties (3.0.7) lib/rails/rack/logger.rb:13:in `call'
 rack (1.2.2) lib/rack/runtime.rb:17:in `call'
 rack (1.2.2) lib/rack/lock.rb:11:in `call'
 rack (1.2.2) lib/rack/lock.rb:11:in `synchronize'
 rack (1.2.2) lib/rack/lock.rb:11:in `call'
 railties (3.0.7) lib/rails/application.rb:168:in `call'
 railties (3.0.7) lib/rails/application.rb:77:in `send'
 railties (3.0.7) lib/rails/application.rb:77:in `method_missing'
 passenger (3.0.7) lib/phusion_passenger/rack/request_handler.rb:96:in `process_request'
 passenger (3.0.7) lib/phusion_passenger/abstract_request_handler.rb:513:in `accept_and_process_next_request'
 passenger (3.0.7) lib/phusion_passenger/abstract_request_handler.rb:274:in `main_loop'
 passenger (3.0.7) lib/phusion_passenger/rack/application_spawner.rb:205:in `start_request_handler'
 passenger (3.0.7) lib/phusion_passenger/rack/application_spawner.rb:170:in `send'
 passenger (3.0.7) lib/phusion_passenger/rack/application_spawner.rb:170:in `handle_spawn_application'
 passenger (3.0.7) lib/phusion_passenger/utils.rb:479:in `safe_fork'
 passenger (3.0.7) lib/phusion_passenger/rack/application_spawner.rb:165:in `handle_spawn_application'
 passenger (3.0.7) lib/phusion_passenger/abstract_server.rb:357:in `__send__'
 passenger (3.0.7) lib/phusion_passenger/abstract_server.rb:357:in `server_main_loop'
 passenger (3.0.7) lib/phusion_passenger/abstract_server.rb:206:in `start_synchronously'
 passenger (3.0.7) lib/phusion_passenger/abstract_server.rb:180:in `start'
 passenger (3.0.7) lib/phusion_passenger/rack/application_spawner.rb:128:in `start'
 passenger (3.0.7) lib/phusion_passenger/spawn_manager.rb:253:in `spawn_rack_application'
 passenger (3.0.7) lib/phusion_passenger/abstract_server_collection.rb:132:in `lookup_or_add'
 passenger (3.0.7) lib/phusion_passenger/spawn_manager.rb:246:in `spawn_rack_application'
 passenger (3.0.7) lib/phusion_passenger/abstract_server_collection.rb:82:in `synchronize'
 passenger (3.0.7) lib/phusion_passenger/abstract_server_collection.rb:79:in `synchronize'
 passenger (3.0.7) lib/phusion_passenger/spawn_manager.rb:244:in `spawn_rack_application'
 passenger (3.0.7) lib/phusion_passenger/spawn_manager.rb:137:in `spawn_application'
 passenger (3.0.7) lib/phusion_passenger/spawn_manager.rb:275:in `handle_spawn_application'
 passenger (3.0.7) lib/phusion_passenger/abstract_server.rb:357:in `__send__'
 passenger (3.0.7) lib/phusion_passenger/abstract_server.rb:357:in `server_main_loop'
 passenger (3.0.7) lib/phusion_passenger/abstract_server.rb:206:in `start_synchronously'
 passenger (3.0.7) helper-scripts/passenger-spawn-server:99

A: Check following sentence from Rails Guide.
"Note that Ruby 1.8.7 p248 and p249 have marshaling bugs that crash Rails. Ruby Enterprise Edition has these fixed since the release of 1.8.7-2010.02. On the 1.9 front, Ruby 1.9.1 is not usable because it outright segfaults, so if you want to use 1.9.x, jump on to 1.9.2 or 1.9.3 for smooth sailing."
It is better to upgrade ruby version(1.9.2).