text:
Q: Error when running koudoku:install I have gem 'koudoku' installed in my application. After running bundle install, I ran rails g koudoku:install user to install koudoku.
After running the command in my terminal, I get this error: Could not find generator 'koudoku:install'.
I have even re-installed the gem several times, but keep getting the same error.
Any help is much appreciate.

A: You get Could not find generator 'koudoku:install' if you don't have Stripe gem Installed.
Remove gem 'koudoku', run bundle install and add Stripe gem to your gem file and run bundle install to install Stripe.
After installing Stripe, you can correctly install gem 'koudoku' and run rails g koudoku:install user


text:
Q: How to display pdf file in reader from database Hello I am working in windows application "winforms" in this I have successfully save pdf file in database now I want to display that in adobe reader which i have been added from toolbox
what should I need to do, thats why I can able to view pdf in adobe reader.
I already try to display pdf file to reader but nothing display.
Here is my code:
{
        con.Open();
        SqlCommand command1 = new SqlCommand("select PDFFILE from help ;", con);
        DataTable dt = new DataTable();
        byte[] img = (byte[])command1.ExecuteScalar();
        MemoryStream ms = new MemoryStream(img);
        string s = System.Text.Encoding.UTF8.GetString(img);

        axAcroPDF1.LoadFile(s);
        con.Close();
}

A: If the adobe control only takes a filename, you will need to save the pdf as a file first. System.IO.Path will get you a temporary path. Using a guid will also prove useful for random names.
If you don't want that, you may use the PdfiumViewer, which is Googles Pdfium wrapped as a .NET control. Works fine, takes streams as load parameter and is easy to use. You can get both the PdfiumViewer and the required Pdfium-DLLs via NuGet. Plus, you won't be dependent on the installed adobe version any more.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Are there other ways to time travel in the Potterverse? There are a lot of questions about the time turners in Harry Potter.  There's a fan theory that Ron could have used one and become Dumbledore at some point in the past (but that's been debunked).  I also asked Why Couldn't a Time Turner Have Been Used to Stop Voldemort?.  It seems that Rowling had them all destroyed to stop time travel issues (such as paradoxes or the idea that one could be used to just undo all the bad with Voldemort before it started).
The time turners are magic machines, so they had to be created at some point.  But are they the only way to time travel and why couldn't one use the same type of magic a time turner uses to move back in time more than just an hour?

A: Per Pottermore, the time-turners are a charm housed in an attractive container;

According to Professor Saul Croaker, who has spent his entire career
  in the Department of Mysteries studying time-magic:
We have been able to encase single Hour-Reversal Charms, which are
  unstable and benefit from containment, in small, enchanted
  hour-glasses that may be worn around a witch or wizard's neck and
  revolved according to the number of hours the user wishes to relive.

So the answer is; yes, a spell (or rather a charm) can be used to travel without the time-turner but not as conveniently.


text:
Q: Identifying the TLD and SLD of a URL I was given a question to identify different parts of a domain and I got the answer wrong. Here is the URL
enter https:\\www.example.co.uk
What is the,
Top-Level Domain?
Second Level Domain?
to which part does example belongs?
Is www a sub-domain?
THANKS IN ADVANCE

A: You can't do this by just looking at the URL (string). You need either to consult the Public Suffix List, or do live DNS queries. Both cases have strengths and drawbacks.
So you can reply into those kind of questions only if you know the rules of all TLDs existing (aka: it is impossible)
Why? Mostly because DNS is both not widespread knowledge, there is a lot of variations per TLDs, because each node in the DNS tree is free to have whatever policies (including names and types of delegations) at his level and everything below, and because, contrary to widely spread belief, a . in a name does not necessarily mean a delegation and hence a cut between administrative and technical boundaries.
Also TLD is often abused. Technically it is the rightmost (top most) label, this is the meaning of T. Hence in your example it should be uk. BUT not long ago it was not possible to register names directly under uk, only co.uk, org.uk,  me.uk and others would be open and hence in this case, we would say that co.uk is the TLD, which is wrong technically but widely understood. It means in fact the "effective TLD" or the "public suffix".
See all these valid hostnames (they work inside an URLs):

*

*dk

*www.sante.gouv.fr

*www.com.com

*www.nominet.co.uk

*www.uk.com

*www.walton.k12.fl.us

*lagazettedesancetres.blogspot.fr

*www.al.ma.leg.br

*ab.m.wikibooks.nom.nu

*1512f1.станок.спб.рус
BTW, useful terminologies I suggest using which may often be clearer than domain/subdomain, as taken from https://url.spec.whatwg.org/#host-miscellaneous

"A host's public suffix is the portion of a host which is included on the Public Suffix List."
"A host's registrable domain is a domain formed by the most specific public suffix, along with the domain label immediately preceding it, if any."


text:
Q: OpenCV build from source fails with Java 11: warning: target release 11 conflicts with default source release 18 I'm working on a Java application that runs Java 11. I've chosen Java 11 because it's the the last Java version with LTS.
I'm using OpenCV in this Java application and am using libraries from the contrib modules. I'm using Homebrew to install OpenCV with the Java bindings and the contrib modules.
The first thing I tried was to install OpenCV from source without specifying the Java target version. When I did this, OpenCV installed correctly, but when I tried to use it in code, I got the following error:
class file has wrong version 61.0, should be 55.0
I take this to mean that because OpenCV was compiled via Java 17, I can't use it in my Java 11 code. It's also worth mentioning that because I'm using Maven with my Java project, I first export the OpenCV JAR into a local Maven module via something like mvn install:install-file -Dfile=/usr/local/Cellar/opencv/4.5.5_1/share/java/opencv4/opencv-455.jar. I'm using OpenJDK 11 as my JRE for this export.
I'm also using OpenJDK 11 as my default JDK on my Mac (java -version and javac -version both return OpenJDK 11). So I was a bit surprised to see this error.
So to solve it, I've been trying to install OpenCV with the flag -DOPENCV_JAVA_TARGET_VERSION=11. However, when I do this, I get the following error:
[ 11%] Generating opencv-455.jar
cd /tmp/opencv-20220410-81173-p3o3uo/opencv-4.5.5/build/modules/java/jar/opencv && /usr/local/bin/ant -noinput -k jar
Picked up _JAVA_OPTIONS: -Duser.home=/Users/dpapp/Library/Caches/Homebrew/java_cache
Buildfile: /private/tmp/opencv-20220410-81173-p3o3uo/opencv-4.5.5/build/modules/java/jar/opencv/build.xml
   [tstamp] Honouring environment variable SOURCE_DATE_EPOCH which has been set to 1640404407

jar:
    [javac] Compiling 280 source files to /private/tmp/opencv-20220410-81173-p3o3uo/opencv-4.5.5/build/modules/java/jar/opencv/build/classes
    [javac] warning: target release 11 conflicts with default source release 18
Target 'jar' failed with message 'Compile failed; see the compiler error output for details.'.

BUILD FAILED
/private/tmp/opencv-20220410-81173-p3o3uo/opencv-4.5.5/build/modules/java/jar/opencv/build.xml:14: Compile failed; see the compiler error output for details

This error makes it sound like OpenCV requires at least JDK 18, which doesn't sound right to me. Is there a minimum JDK for each OpenCV version? Should I be using OpenCV 3 instead? Any help is greatly appreciated, thank you!

A: I partially figured out what's going on here.
As a prereq for running brew install opencv, I ran brew install ant. brew install ant installs the latest OpenJDK (OpenJDK 18 at the time of writing) and ignores the Java home path set on my machine. This causes brew install opencv to try to install OpenCV with Java 18 while the target is set to 11, which throws an error.


text:
Q: fade in fade out of div Im trying to get a div to have a fade out then fade in effect, but the fade out instantly disappears then the fade in works perfectly. Its like the fade in effect interrupts the fade out immediately
js
$('#fillBg').stop(true,false).fadeTo(3000, 0);
$("#fillBg").hide().attr('src', bgImage).stop(false,false).fadeTo(1500, 1.0);

A: You need add anything that is supposed to be happening after the first fadeTo animation into a callback function:
 $('#fillBg').stop(false,false).fadeTo(3000, 0, function() {
    $(this).hide().attr('src', bgImage).stop(false,false).fadeTo(1500, 1.0);
 });

A: Your problem is with the 2nd .stop.  Calling stop is stopping the second fadeTo animation.

A: $('#fillBg').fadeOut(3000, function(){
    $("#fillBg").attr('src', bgImage).fadeIn(1500);
});

Will ensure the fadeIn is run after the fade Out has completed.

A: Try
$("#fillBg").fadeOut().fadeIn();

http://jsfiddle.net/g334J/

A: You can use the callback of the fadeTo method like this
//Cache the value, for performance
var divToHide = $('#fillBg');

divToHide.stop(false,false).fadeTo(3000, 0, function() {
     divToHide.hide().attr('src', bgImage).stop(false,false).fadeTo(1500, 1.0);
});

Or using fadeIn, and fadeOut
//Cache the value, for performance
var divToHide = $('#fillBg');

divToHide.fadeOut(3000, function() {
     divToHide.hide().attr('src', bgImage).fadeIn(1500);
});

A: $('#fillBg').stop(true,false).fadeTo(3000, 0, backIn);
function backIn()
{
    $("#fillBg").fadeTo(1500, 1.0);
}

http://jsfiddle.net/4CnjB/


text:
Q: Counting using a multi-array? (Excel, VBA) I have a relatively simple task and have already found a few solutions, but I have an idea that would be far more efficient, I just don't know if it's possible to code.
Basically, I need to count animals, and their physical traits, then report on that data.  Perhaps column A is for the species, B is for their hair color, and C is their age.  I can solve this using a loop and nested if/else statements, but it balloons in size and looks very sloppy.
What I had hoped to do was something more like:
Loop
    Array(species, color, age) = Array(species, color, age) + 1
End loop

This turns out to be very difficult though, as some of the values I'm getting are strings (species and color) and the array function only seems to accept numbers.
Does anyone know of a way to count information like this in a very efficient manner?  If I was able to store it in an array I could have been able to print all of the results at once, which was part of my goal.

A: You could use a Dictonary to tally up the occurrences of each combination. The Key would be a concatenated string of the species & color & age, and the item would be the count. You would code it very similarly to your idea:
Sub Example(ItemCollection As Variant)
    Dim Counts As Object
    Set Counts = CreateObject("Scripting.Dictionary")

    'Loop through your data set
    Dim Item As Variant
    For Each Item In ItemCollection
        Dim species As String, color As String, age As String
        'Define species, color and age based on each item from your data set
        'Maybe they are object members, or cells in a worksheet row
        'I don't know what your data looks like.

        Dim Key As String
        Key = species & "|" & color & "|" & age

        Counts(Key) = CLng(Counts(Key) + 1)
    Next

    'After the data has been tallied up, the dictionary "Counts", now contains the count of occurences of each combination.
    'You can see the full list of combinations by looking at the array Counts.Keys
    'You can return a specific count from the dictionary using the key: Counts(Key) where the Key is species & color & age
    'You can get the full list of counts from the dictionary by looking at the array Counts.Items
End Sub


text:
Q: Summing quantities that are grouped by more than one field This is a follow on from my previous questions. I just feel that its easier if I explain it all again as I want to try to get more detail out of my query. So here we go:
Sample Table:
(note: the table has 100's of ID's each with numerous different LOTNO's)
ITEMNO   LOTNO   TRANS_QUAN   TRANS_TYPE

 1      45        16          PO
 1       3         2          PO
 1      45        47          MH
 1      45         3          MH
 1       3         8          MH

What I have so far does not take into account the different LotNo's for each ID, rather it sums based on ID and TYPE. The code below sums all Quantity values for TYPE = 'PO' with ID = 1. and then compares them with all summed quantity values for TYPE = 'MANUAL/BACKFLUSH' with ID = 1. This code works perfectly in this regard (big thanks to Nicholas Krasnov with this one):
 SELECT *
 FROM (SELECT TR.ITEMNO
         , ROUND(SUM(TR.TRANS_QUAN * (DECODE(TR.TRANS_TYPE, 'PO', 1, 0)))) AS SUM_IN
         , ROUND(SUM(TR.TRANS_QUAN * (DECODE(TR.TRANS_TYPE, 'MANUAL/BACKFLUSH', 1,0))))AS SUM_OUT
     FROM IQMS.TRANSLOG TR
     GROUP BY IQMS.TR.ITEMNO
     ORDER BY IQMS.TR.ITEMNO)
 WHERE SUM_OUT > SUM_IN

I want to break the sum calculation down further and incorporate the LOTNO field. So in the table above, for ID = 1, I want to sum all values for ID = 1, LotNo = 45 and TYPE = PO and then compare them to ID = 1, LotNo = 45 and TYPE = 'MANUAL\BACKFLUSH'.
I then want to move on to compare(ID = 1, LOTNO = 3, TYPE = 'PO') with (ID = 1, LOTNO = 3, TYPE ='MANUAL/BACKFLUSH') and so on.
I also only want to return records in which SUM_OUT > SUM_IN
I would hope for my output to be something like
ID      LOTNO     SUM_IN      SUM_OUT

 1        45        30           50
 1         3         2            8

Any ideas on how i can incorporate this, to give a more specific result set?? Probably something simple like an extra GROUP BY or something?? I hope I have been clear on what I hope to achieve.
Thanks for the continued support guys! :)

A: I think the following query does what you want . . .
select id, lotno,
       sum(case when type = 'PO' then quantity else 0 end) as sum_in,
       sum(case when type = 'MANUAL/BACKFLUSH' then quantity else 0 end) as sum_out
from IQMS.TRANSLOG TR
group by id, lotno

The case statement is standard SQL; decode is specific to Oracle.  Also, I wasn't sure which column names to use, since they are inconsistent between your question and the code sample.  I used the shortest form.
To return records where sum_out > sum_in, you can embed this as a subquery:
select t.*
from (select id, lotno,
             sum(case when type = 'PO' then quantity else 0
                 end) as sum_in,
             sum(case when type = 'MANUAL/BACKFLUSH' then quantity else 0
                 end) as sum_out
      from IQMS.TRANSLOG TR
      group by id, lotno
     ) t
where sum_out > sum_in

You can also do this with a having clause.

A: According to your sample data, is that what you are looking for?
select *
  from ( SELECT TR.ITEMNO
              , tr.lotno
              , ROUND(SUM(TR.TRANS_QUAN * (DECODE(TR.TRANS_TYPE, 'PO', 1, 0)))) AS SUM_IN
              , ROUND(SUM(TR.TRANS_QUAN * (DECODE(TR.TRANS_TYPE, 'MH', 1,0))))AS SUM_OUT
          FROM TRANSLOG TR
         GROUP BY TR.ITEMNO, tr.lotno
         ORDER BY TR.ITEMNO
       )
 where sum_out > sum_in

A: Got it!!! :) :)
SELECT *
FROM

  (SELECT TR.ITEMNO, TR.LOTNO,
       SUM(CASE WHEN TR.TRANS_TYPE = 'PO' THEN TR.TRANS_QUAN ELSE 0 END) AS SUM_IN,
       SUM(CASE WHEN TR.TRANS_TYPE = 'MANUAL/BACKFLUSH' THEN TR.TRANS_QUAN ELSE 0 END)AS SUM_OUT
   FROM IQMS.TRANSLOG TR
   GROUP BY TR.ITEMNO, TR.LOTNO
   ORDER BY TR.ITEMNO, TR.LOTNO)

WHERE SUM_OUT > SUM_IN
AND SUM_IN != '0'

Thanks you guys for all the help!!


text:
Q: Xcode App Running Issue I just updated my iPhone 5 to iOS version 10.1. When I tried to run the app that I'm developing on my device I got the following error from Xcode:
"Could not locate device support files.
This iPhone 5 (Model A1429) is running iOS 10.1 (14B72), which may not be supported by this version of Xcode."
I have the latest version of Xcode i.e. 8.0 (I just double checked to see if there are any available updates). I cannot set the deployment target higher than 10.0 either.
What do I need to do? Is there a way to downgrade my device? When there is an update in the future should I wait until the version is released on Xcode?

A: Xcode 8.1 is now available
Download link.
Note from Apple News:

You can now download Xcode 8.1 from the Mac App Store. This version includes the latest macOS SDKs for building apps that use the all-new Touch Bar on the new MacBook Pro. To develop apps for the Touch Bar, you'll need a Mac running Xcode 8.1 on macOS Sierra 10.12.1 (12B2657) or later.

A: There is an option in order to do not download full xcode, you need to download files from this topic (in Update comment)
Then you need to copy 10.1 (14B65) folder to
/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport/
so the full path will look like:
/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport/10.1 (14B65)
with two files in it: DeveloperDiskImage.dmg.signature and DeveloperDiskImage.dmg
It worked fine for me.

A: Actually your iOS version still fresh and xCode SDK still in beta
you can download the beta SDK's from here
xCode 10.1 beta SDK download
UPDATE:
Now apple have updated Xcode to 8.1 which include the SDK for 10.1, and you can download it from app store.

A: Updates between iOS and macOS are independent though if you are developer they are not because iOS and Xcode have to match. In my case my iOS upgraded automatically but my Xcode did not, and could not, because I had postponed the upgrade of my macOS (laziness). After I upgraded my macOS my Xcode could also upgrade to the right version suitable for the iOS version on my iPad and everything worked fine again.


text:
Q: Javascript Lexical scope I am trying to understand the concept of Lexical scope. As far as i know Lexical scope does not work backwards. In the below javascript code i have declared variable 'name' in scope3() function. But i tried to call it in scope1() and scope2() function. Since Lexical scope does not work backwards, I should have got "name is undefined" but it returns empty string. Can someone explain this?

var scope1 = function () {
  // name should have been undefined but its printing empty string
  console.log(name);
  var scope2 = function () {
    // name should have been undefined but its printing empty string
    console.log(name);
    var scope3 = function () {
      var name = 'Todd'; // locally scoped
    };
  };
  scope2();
};
scope1();

A: JavaScript has name built-in property. So, you'll get an empty string when you try to get name variable as it is pointing to window.name.
You need to use something else instead of name.

A: You need a proper understanding of lexical scoping, below is a brief and direct example to explain the concept and how it works:
lets say:
function(auto) {
   var vehicle = "bus";
   console.log(vehicle);

   function(innerAuto) {
     console.log(vehicle)
   }
   innerAuto();
}
auto();

So the inner function called innerAuto in this context gets an instruction to log the value for vehicle, which is nowhere to be found, immediately the function knows it should go to the outer scope to find it. i.e the JS runtime already knows that when executing this code there is no need to look inside the innerAuto function for a declaration of variable vehicle. So you wonder how does it knows this? It's because during the compile time it didn't see the variable declaration in the innerAuto function rather it saw it in the auto function. So lexical scoping is simply the compiled time scoping. For further information check MDN docs on lexical scoping and closures.

A: name is part of a list predefined names of implementation-dependent JavaScript objects. Therefore, it will not provide the reference error you would expect. Change the binding name to names to see the reference error expected.
You are also absolutely correct in your logical understanding of lexical scope. Lexical (or static) scope, provides for functions (or blocks) to view the bindings of their parent functions (or blocks). However, the parent functions (or blocks) do NOT have a view of the bindings created within their children. Global bindings, on the other hand, are visible to all.
Hope that helps, thanks!


text:
Q: eJabberd with PHP extauth I'm trying to make a PHP extauth script, i configured extauth in ejabberd.cfg and give permission to auth.php file, the script is the following
    #!/usr/bin/php
    <?php

error_reporting(0);

$auth = new JabberAuth();
$auth->dbhost = "";
$auth->dbuser = "";
$auth->dbpass = "";
$auth->dbbase = "";
$auth->play(); // We simply start process !

class JabberAuth {
    var $dbhost; /* MySQL server */
    var $dbuser; /* MySQL user */
    var $dbpass; /* MySQL password */
    var $dbbase; /* MySQL database where users are stored */

    var $debug      = true;/* Debug mode */
    var $debugfile  = "/var/log/pipe-debug.log";  /* Debug output */
    var $logging    = true;                       /* Do we log requests ? */
    var $logfile    = "/var/log/pipe-log.log" ;   /* Log file ... */
    /*
     * For both debug and logging, ejabberd have to be able to write.
     */

    var $jabber_user;   /* This is the jabber user passed to the script. filled by $this->command() */
    var $jabber_pass;   /* This is the jabber user password passed to the script. filled by $this->command() */
    var $jabber_server; /* This is the jabber server passed to the script. filled by $this->command(). Useful for VirtualHosts */
    var $jid;           /* Simply the JID, if you need it, you have to fill. */
    var $data;          /* This is what SM component send to us. */

    var $dateformat = "M d H:i:s"; /* Check date() for string format. */
    var $command; /* This is the command sent ... */
    var $mysock;  /* MySQL connection ressource */
    var $stdin;   /* stdin file pointer */
    var $stdout;  /* stdout file pointer */

    function JabberAuth()
    {
        @define_syslog_variables();
        @openlog("pipe-auth", LOG_NDELAY, LOG_SYSLOG);

        if($this->debug) {
            @error_reporting(E_ALL);
            @ini_set("log_errors", "1");
            @ini_set("error_log", $this->debugfile);
        }
        $this->logg("Starting pipe-auth ..."); // We notice that it's starting ...
        $this->openstd();
    }

    function stop()
    {
        $this->logg("Shutting down ..."); // Sorry, have to go ...
        closelog();
        $this->closestd(); // Simply close files
        exit(0); // and exit cleanly
    }

    function openstd()
    {
        $this->stdout = @fopen("php://stdout", "w"); // We open STDOUT so we can read
        $this->stdin  = @fopen("php://stdin", "r"); // and STDIN so we can talk !
    }

    function readstdin()
    {
        $l      = @fgets($this->stdin, 3); // We take the length of string
        $length = @unpack("n", $l); // ejabberd give us something to play with ...
        $len    = $length["1"]; // and we now know how long to read.
        if($len > 0) { // if not, we'll fill logfile ... and disk full is just funny once
            $this->logg("Reading $len bytes ... "); // We notice ...
            $data   = @fgets($this->stdin, $len+1);
            // $data = iconv("UTF-8", "ISO-8859-15", $data); // To be tested, not sure if still needed.
            $this->data = $data; // We set what we got.
            $this->logg("IN: ".$data);
        }
    }

    function closestd()
    {
        @fclose($this->stdin); // We close everything ...
        @fclose($this->stdout);
    }

    function out($message)
    {
        @fwrite($this->stdout, $message); // We reply ...
        $dump = @unpack("nn", $message);
        $dump = $dump["n"];
        $this->logg("OUT: ". $dump);
    }

    function myalive()
    {
        if(!is_resource($this->mysock) || !@mysql_ping($this->mysock)) { // check if we have a MySQL connection and if it's valid.
            $this->mysql(); // We try to reconnect if MySQL gone away ...
            return @mysql_ping($this->mysock); // we simply try again, to be sure ...
        } else {
            return true; // so good !
        }
    }

    function play()
    {
        do {
            $this->readstdin(); // get data
            $length = strlen($this->data); // compute data length
            if($length > 0 ) { // for debug mainly ...
                $this->logg("GO: ".$this->data);
                $this->logg("data length is : ".$length);
            }
            $ret = $this->command(); // play with data !
            $this->logg("RE: " . $ret); // this is what WE send.
            $this->out($ret); // send what we reply.
            $this->data = NULL; // more clean. ...
        } while (true);
    }

    function command()
    {
        $data = $this->splitcomm(); // This is an array, where each node is part of what SM sent to us :
        // 0 => the command,
        // and the others are arguments .. e.g. : user, server, password ...

        if($this->myalive()) { // Check we can play with MySQL
            if(strlen($data[0]) > 0 ) {
                $this->logg("Command was : ".$data[0]);
            }
            switch($data[0]) {
                case "isuser": // this is the "isuser" command, used to check for user existance
                        $this->jabber_user = $data[1];
                        $parms = $data[1];  // only for logging purpose
                        $return = $this->checkuser();
                    break;

                case "auth": // check login, password
                        $this->jabber_user = $data[1];
                        $this->jabber_pass = $data[3];
                        $parms = $data[1].":".$data[2].":".md5($data[3]); // only for logging purpose
                        $return = $this->checkpass();
                    break;

                case "setpass":
                        $return = false; // We do not want jabber to be able to change password
                    break;

                default:
                        $this->stop(); // if it's not something known, we have to leave.
                        // never had a problem with this using ejabberd, but might lead to problem ?
                    break;
            }

            $return = ($return) ? 1 : 0;

            if(strlen($data[0]) > 0 && strlen($parms) > 0) {
                $this->logg("Command : ".$data[0].":".$parms." ==> ".$return." ");
            }
            return @pack("nn", 2, $return);
        } else {
            // $this->prevenir(); // Maybe useful to tell somewhere there's a problem ...
            return @pack("nn", 2, 0); // it's so bad.
        }
    }

    function checkpass()
    {
        /*
         * Put here your code to check password
         * $this->jabber_user
         * $this->jabber_pass
         * $this->jabber_server
         */
        return true;
    }

    function checkuser()
    {
        /*
         * Put here your code to check user
         * $this->jabber_user
         * $this->jabber_pass
         * $this->jabber_server
         */
        return true;

    }

    function splitcomm() // simply split command and arugments into an array.
    {
        return explode(":", $this->data);
    }

    function mysql() // "MySQL abstraction", this opens a permanent MySQL connection, and fill the ressource
    {
        $this->mysock = @mysql_pconnect($this->dbhost, $this->dbuser, $this->dbpass);
        @mysql_select_db($this->dbbase, $this->mysock);
        $this->logg("MySQL :: ". (is_resource($this->mysock) ? "Connecté" : "Déconnecté"));
    }

    function logg($message) // pretty simple, using syslog.
    // some says it doesn't work ? perhaps, but AFAIR, it was working.
    {
        if($this->logging) {
            @syslog(LOG_INFO, $message);
        }
    }
}

?>

when i start ejabberd live, i get this error in an infinite loop:
extauth script has exitted abruptly with reason 'normal'

A: External authentication script needs to be constantly running and thus must be a loop.
This is explained in ejabberd documentation:
https://www.ejabberd.im/files/doc/dev.html#htoc9
I suspect your script is exiting and not actually looping.
As a starting point, you should have a look at this project:
https://github.com/cburschka/ejabberd-auth-php


text:
Q: How to align mat-cell content with icon to right on angular2/material? To begin with my Code:
<!-- Edit Column -->
<ng-container mdColumnDef="edit">
  <md-header-cell *mdHeaderCellDef> {{'companies.edit-column' | translate}}</md-header-cell>
  <md-cell *mdCellDef="let element"><a (click)="toCompany(element.id)"><md-icon class="md-dark">edit</md-icon></a></md-cell>
</ng-container>

The Requirement is to adjust the position of the edit icon to the right (with respect of material design's right padding)? Right now it appears to be forcibly left-docked. Applying a style="{text-align: right}"  to md-cell does not work.
version of libs:
"@angular/material": "2.0.0-beta.10"
"@angular/cdk": "^2.0.0-beta.10",
"@angular/common": "^4.1.3"

A: Use either of these:
mat-cell{
  display:flex !important;
  justify-content:flex-end!important;

}

::ng-deep .mat-cell{
  display:flex !important;
  justify-content:flex-end!important;
}

DEMO


text:
Q: LINQ to dictionary with multiple keys for a single value Consider the following code:
public KeyAttribute : Attribute{
    public string Value;
    public KeyAttribute(string value){
        Value = value;
    }
}

[Key("A")]
[Key("AB")]
public class A : IClass
{
    public string FieldA {get;set;}
}

[Key("B")]
public class B : IClass
{
    public string FieldB {get;set;}
}

So I have to through all the implementations of IClass interface, and I've got to construct a dictionary Dictionary<string, ConstructorInfo> where the keys are the Value properties of KeyAttribute, and the values are the corresponding ConstructorInfo.
Notice that there might be several KeyAttribute on a single class, so for that case, there should be the corresponding amount of entries in the dictionary.
For the current example, the desired outcome is:
key     | value
--------+-------------------
"A"     | ConstructorInfo A
"AB"    | ConstructorInfo A
"B"     | ConstructorInfo B

At first I wrote this:
return AppDomain.CurrentDomain.GetAssemblies()
    .SelectMany(s => s.GetTypes())
    .Where(t => typeof(IClass).IsAssignableFrom(t))
    .ToDictionary(t =>
    {
        var key = (KeyAttribute) t.GetCustomAttributes(typeof(KeyAttribute), true).First();
        return key.Value;
    }, t => t.GetConstructors(BindingFlags.Public).First());

But as you can see, the code above does not handle the situation with several attributes.
So I did the following, but it's obviously wrong and I'm not sure how to correct it.
return AppDomain.CurrentDomain.GetAssemblies()
    .SelectMany(s => s.GetTypes())
    .Where(t => typeof(IClass).IsAssignableFrom(t))
    .ToDictionary(t =>
    {
        return t.GetCustomAttributes(typeof(KeyAttribute), true).Select(a => ((KeyAttribute)a).Value);
    }, t => t.GetConstructors(BindingFlags.Public).First());

I know I can do that without LINQ like that:
var types = AppDomain.CurrentDomain.GetAssemblies()
    .SelectMany(s => s.GetTypes())
    .Where(t => typeof(IClass).IsAssignableFrom(t));
var dict = new Dictionary<string, ConstructorInfo>();
foreach (var type in types)
{
    var keys = type.GetCustomAttributes(typeof(KeyAttribute), true).Cast<KeyAttribute>().Select(a => a.Value);
    var ctorInfo = type.GetConstructors(BindingFlags.Public).First();
    foreach (var key in keys)
    {
        dict.Add(key, ctorInfo);
    }
}
return dict;

But I'd rather stick to LINQ, if it is possible.
Sorry about all these somewhat misleading details about attributes and all that, while it is a question about LINQ, but I couldn't think of any other vivid example.

A: This should work:
return AppDomain.CurrentDomain.GetAssemblies()
    .SelectMany(s => s.GetTypes())
    .Where(t => typeof(IClass).IsAssignableFrom(t))
    .SelectMany(t => t.GetCustomAttributes(typeof(KeyAttribute), true)
        .Select(a => new
        {
            constInfo = t.GetConstructors(BindingFlags.Public).First(),
            attrVal = ((KeyAttribute)a).Value
        }))
    .ToDictionary(entry => entry.attrVal, entry => entry.constInfo);

A: Use SelectMany for key attributes
return AppDomain.CurrentDomain.GetAssemblies()
                .SelectMany(s => s.GetTypes())
                .Where(t => typeof(IClass).IsAssignableFrom(t))
                .SelectMany(t =>
                {
                    return t.GetCustomAttributes<KeyAttribute>()
                            .Select(ka => new
                            {
                                Key = ka,
                                Ctor = t.GetConstructors(BindingFlags.Public).First()
                            });
                })
                .ToDictionary(t => t.Key, t.Ctor);


text:
Q: Using MATCH to build cell range returns #VALUE I have a formula which finds the 10 highest values using the LARGE function, with a set cell range.  SALESNew is 52 weeks of figures and the k-th largest value is in SALES Summ $C...
=LARGE('2015SALESNew'!$D$250:$BC$250,'SALES Summ'!$C6)

I need to extend this to dynamically select the row on SALESNew, based upon the product range.  I have tried various methods of building the cell range, all of which return the correct result when used on their own, but #VALUE is returned if I use it within the LARGE formula.
Examples below:
=LARGE(("'2015SALESNew'!$D$"&G43&":$BC$"&G43),'SALES Summ'!$C43)

$G43 contains =MATCH($A38,'2015SALESNew'!A:A,0)

The 3 methods I have tried below all return the correct range
    ('2015SALESNew'!$D$255:$BC$255) but the formula result is always #VALUE.

="'2015SALESNew'!$D$"&G43&":$BC$"&G43
="'2015SALESNew'!$D$"&MATCH($A38,'2015SALESNew'!A:A,0)&":$BC$"&MATCH($A38,'2015SALESNew'!A:A,0)
=CONCATENATE("'2015SALESNew'!$D$",MATCH($A38,'2015SALESNew'!A:A,0),":$BC$",MATCH($A38,'2015SALESNew'!A:A,0))

What am I missing with the cell range not being read correctly?

A: I find the best way to build a dynamic range reference is by using the INDEX function.  As the help file says - Index (reference form) Returns the reference of the cell at the intersection of a particular row and column.
So, as an example, =INDEX($J:$J,5) will return a reference at the intersection of row 5 in the range $J:$J - i.e. $J$5.
Add another INDEX to this formula, say the intersection of row 10 in the range $N:$N and you have a range of cells referenced:  =INDEX($J:$J,5):INDEX($N:$N,10).
Run this through Evaluate Formula and it will show you the range $J$5:$N$10 - wrap it in a SUM function and it will add up all values in that range.
Now to make it dynamic - the formula COUNTA($N:$N) will count all cells in column N that are not empty.  Providing you have no blanks in column N this will effectively give you the last row containing data in column N.
So now we can rewrite the formula to read =$J$5:INDEX($N:$N,COUNTA($N:$N)).
I've changed J5 to a constant - might as well if it's not going to change - and the second reference to the last cell containing data in column N (providing there's no blanks in column N).  This now references J5:N10 in my example.
Wrap this in a LARGE function =LARGE($J$5:INDEX($N:$N,COUNTA($N:$N)),3) and it displays the 3rd largest number in my range.
Edit: As an added bonus the INDEX function is non-volatile, while the similar OFFSET function and the INDIRECT function are volatile - causing an overhead whenever you calculate.
http://www.decisionmodels.com/calcsecretsi.htm

A Volatile Function is one that causes recalculation of the formula in
  the cell where it resides every time Excel recalculates.  This occurs
  regardless of whether the precedent data and formulas on which the
  formula depends have changed, or whether the formula also contains
  non-volatile functions.


text:
Q: about AV for mini laptop is it be clever to install Symantec Endpoint Protection AV on mini laptop ?
is it not to hard for hem ?
thank's in advance

A: SEP is lightwight if you compare to its predecessors.
We are using it in our business and I can tell you that's it pretty neat and it's working fine. It won't slow down a mini laptop as Dell, Asus and Acer (And...) are selling!
It's using, for me, not more than 11-15mo.
So, no worry at all!

A: If you're looking for lightweight antivirus, try Avira; does a nice job without making the app to "bloated"


text:
Q: R foreach loop compare every row to every row I would like to compare every row in a df to every other row in that same df (and compute some functions, too). I've managed to write a foreach loop, but it only compares every row to the last row.
Here's a minimal we of what I did so far:
# create toy df
ID <- c(345, 476, 234, 987, 123) # assign random id
Language <- c("aa", "bb", "cc", "dd", "ee") # names of languages
Latitude <- c(-17, -25, 44, -8, 29)
Longitude <- c(130, 29, -122, 120, -110)
sample <- data.frame(ID, Language, Latitude, Longitude)

sample
   ID Language Latitude Longitude
1 345       aa      -17       130
2 476       bb      -25        29
3 234       cc       44      -122
4 987       dd       -8       120
5 123       ee       29      -110

# foreach loop that should pair every language with every other
sample.rows <- nrow(sample)

loop <- foreach(i=1:(sample.rows-1),.combine=rbind) %do% {
   empty.pairs <- c()
   for(j in (i+1):sample.rows){
     pairs <- rbind(empty.pairs, c(i, j))
   }
  data.frame(Lang1 = sample$Language[pairs[,1]],
              Lang2 = sample$Language[pairs[,2]],
              i= pairs[,1],
              j= pairs[,2])
   }

which outputs the following:
loop
 Lang1 Lang2 i j
1    aa    ee 1 5
2    bb    ee 2 5
3    cc    ee 3 5
4    dd    ee 4 5

i.e. the loop only compares the first four lines to the last line, but I want it to compare all the row to all other rows, so e.g. language "aa" should be compared not only to "ee", but also "bb", "cc" and "dd".
Any hints appreciated!

A: I think what you want is a grid of all combination of languages. You can use expand.grid:
grid <- cbind(
  expand.grid(sample$Language, sample$Language),
  expand.grid(seq_len(sample.rows), seq_len(sample.rows))
)
names(grid) <- c("Lang1", "Lang2", "i", "j")
grid <- grid[grid[["j"]] > grid[["i"]], ]

PS: If you want to e.g. compute distances, using a matrix would be better than a data frame.


text:
Q: Make rustc, cargo, rustup, rustdoc commands work without sudo inside the Windows Subsystem for Linux I'm running a WSL Debian distro because I wanted to follow along with the InterMezzOS tutorials. I followed the installation instructions for Rust and ran curl https://sh.rustup.rs -sSf | sh, but I can only make the rustc command available by running source $HOME/.cargo/env AFTER running sudo su, and when I exit sudo I can't call it, and when I retype sudo su it doesn't work anymore, I have to type it again.
Is there any way I can make it available so the commands work every time I open my shell, without running sudo every time?

A: Notice that curl https://sh.rustup.rs -sSf | sh will add to /home/<user>/.profile a line that appends binaries in ~/.cargo/bin, including rustup and rustc. The addition of the binaries in .cargo however does not take immediate effect. An easy way to associate it with your bash terminal is (immediately after installation):
echo $(cat ~/.profile | tail -1) >> ~/.bashrc
source ~/.bashrc

In your particular case, since you are root, you should copy /root/home/.cargo and /root/home/.profile into your own users home directory.

A: Right after you install Rust, you can find where it was installed in the Linux filesystem by running whereis rustc
It should output something like this:
rustc: /home/damianrivas/.cargo/bin/rustc

You need to add that to your path, so open up .bashrc in an editor
nano ~/.bashrc

(if you use zsh like I do just replace it with ~/.zshrc)
Scroll down to the bottom of the file (or use the keyboard shortcut alt + /, and add Rust's location to PATH by adding this at the end:
# Add Rust to $PATH
export PATH="$HOME/.cargo/bin:$PATH"

I have $HOME because /home/damianrivas/ is my $HOME path. I could've also put
export PATH="/home/damianrivas/.cargo/bin:$PATH"

After this is done, exit all of your open WSL terminals before opening up a new one. You can restart your PC to be sure. Then run rustc --version when you open up a new terminal and it should work.

A: Following their documentation I do this:
$ curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh

...

Current installation options:

   default host triple: aarch64-unknown-linux-gnu
     default toolchain: stable (default)
               profile: default
  modify PATH variable: yes

1) Proceed with installation (default)
2) Customize installation
3) Cancel installation

< I enter 1>

Then the installation completes with this:
Rust is installed now. Great!

To get started you may need to restart your current shell.
This would reload your PATH environment variable to include
Cargo's bin directory ($HOME/.cargo/bin).

To configure your current shell, run:
source $HOME/.cargo/env

So I do the following

*

*You may have to replace ~.bashrc with ~/.zshrc or something similar.

echo "export PATH='\$HOME/.cargo/bin:\$PATH'" >> ~/.bashrc"
source ~/.bashrc

And I check if rust is installed
$ whereis rustc
rustc: /usr/bin/rustc /usr/share/rustc /home/nvidia/.cargo/bin/rustc

$ which rustc
/home/nvidia/.cargo/bin/rustc

$ rustc --version
rustc 1.53.0 (53cb7b09b 2021-06-17)

This looks good, but now let's check out sudo so that system scripts can run without issues.

$ sudo whereis rustc
rustc:

$ sudo rustc --version
sudo: rustc: command not found

OMG! And this is how to fix it
$ sudo apt-get install -y rustc

$ sudo rustc --version
rustc 1.47.0

A: This worked for me:
#For Mac and Linux Users
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh

#window users
Download rustup-init.exe from www.rustup.rs and run.

Note:#run this after
source $HOME/.cargo/env

To verify the current Rust version, use the rustc --version or rustc -V command.


text:
Q: How to obtain picture metadata using perl, php How do I obtain the metadata for a png or jpg image?  I have a few thousand images that get processed by a perl script.  One of the things that I need to be able to get from each image is the metadata for them.
The most important information is the date listed in bold.  I would like to have a script I can run that will grab the date info from each of the pictures that I process.  It would be ideal if it is in perl, but php would work too.  this is running on a Linux system.  Any help would be appreciated.  Thank you
Here is an example of one of the images:

Here is the metadata for this image:
Sep 30, 2010
849×571 pixels – 825KB
Filename: EA_A02_N_1-4_5mM_Xgal_7d_B.cropped.resized.grey.png
Camera: Canon
Model: Canon EOS DIGITAL REBEL XSi
ISO: 200
Exposure: 1/50 sec
Aperture: 2.8
Focal Length: 60mm

A: In php you can use exif_read_data() function .

A: Check out ExifTool

A: You can use ImageMagick,
it's good application that was used in Typo3 to retrieve image's MetaData.
when you want to execute it, you can use the exec() or system() functions


text:
Q: select in 3 tables i have 3 table
table 1 "Sale" that saved date of user sale
table 2 "ProductFactor" that saved factorid and productid in wich factoreid
tabel 3 "Product" that saved productid and product name

i want select in 3 table for this result:
show user factorid +price+ saledate + any product name that avalibe in this factorid
but when do it, for example when in one factorid that have 3 productid, is show this:
 date       factoreid    name     price

2013-09-25    1         x         18261256
2013-09-25    1         y         2365560.0000
2013-09-25    2         w         5500.0000
2013-09-25    3         z         50000.0000
2013-09-25    1         k         324.0000

i want show this:
date    factoreid    name     price

2013-09-25    1    x,y,k      sum of 3 product name
2013-09-25    2     w       5500.0000
2013-09-25    3     z       50000.0000

CREATE PROCEDURE [dbo].[GetUserSaleReport]
@CurrentUserId uniqueidentifier
AS
BEGIN
SELECT dbo.Sale.SaleDate,dbo.ProductFactor.FactoreId,dbo.Product.ProductName,dbo.Product.Price
 FROM Sale INNER JOIN ProductFactor ON
 dbo.Sale.FactoreId=dbo.ProductFactor.FactoreId
 INNER JOIN dbo.Product ON dbo.ProductFactor.ProductId=dbo.Product.ProductId
 WHERE dbo.Sale.UserId = @CurrentUserId AND dbo.Sale.FactoreId=dbo.ProductFactor.FactoreId AND dbo.ProductFactor.ProductId=dbo.Product.ProductId
 ORDER BY dbo.Sale.SaleDate
END

A: This could be your query:
select date, factoreid,GROUP_CONCAT(name) , sum(price)
from tablename
group by factoreid

Refer: http://sqlfiddle.com/#!2/284fd/5


text:
Q: How "trustworthy" is the cost information returned by EXPLAIN in Postgres? I have a database with a table which is accessed with about 5 different SELECT commands. I tested each one of them with the EXPLAIN ... and EXPLAIN ANALYZE .... The database includes some data (about 150,000 rows).
Here is the SELECT in link with the results shown below and as you will see, it matches the index one to one:
SELECT *
  FROM my_table
 WHERE verified
  AND status = 5
  AND col3 IS NOT NULL

Depending on the index I test with, I get quite different results. For example, an index based on a column with a date date:
CREATE INDEX my_table_idx ON my_table (start_date)
       WHERE verified AND status = 5 AND col3 IS NOT NULL;

Index Scan using my_table_idx on my_tables  (cost=0.28..359.01 rows=551 width=2964)

However, when I change the index to not use start_date, because I do not need my results in a specific order, I get:
CREATE INDEX my_table_idx ON my_table ((true))
       WHERE verified AND status = 5 AND col3 IS NOT NULL;

Bitmap Heap Scan on my_table_idx  (cost=21.67..2204.89 rows=551 width=2964)

Here we see that the cost is much higher: 21.67 instead of .28 (77×) and 2204.89 instead of 359.01 (6.1×).
Obviously, the realtime production environment will be completely different than my local database copy that doesn't update all the time, etc. However, if the first index is indeed faster as indicated by the "cost" information, then I think that I should be using that index.
My question here is: Is the cost=... information accurate enough that I can indeed infer that the first index is better than the second one? Will that hold in a production environment? Or is that so inaccurate that I should not even bother doing such upfront work?
Bonus question: Is using a (true) expression ever a good idea in a Postgres INDEX?

A: The costing is at least attempting to be accurate, otherwise there would be no point in doing it.  But estimation is very hard, and there are many ways to get it wrong.  So it is accurate, except for when it isn't.
Some comments on your example:
You should show the actual queries. I'm assuming they were just select * from my_table WHERE verified AND status = 5 AND col3 IS NOT NULL but you shouldn't make us guess.
The first numbers from each cost is useless to you.  That is how much work it takes to return the first row, but since you aren't using a LIMIT (or any of the things equivalent to a LIMIT), that doesn't matter as you can't stop after obtaining the first row.  So only the 2nd number matters for the case shown.
The reason the first numbers are so different is that a bitmap scan needs to build the entire bitmap up front before it can return any rows, so this severally penalizes the first-row cost of the one that uses the bitmap.  But since you aren't stopping after the first row, that doesn't matter in your case.
When you look at the full-run costs, you see they are much closer together relatively, but still a considerable difference (6x).  And I think this difference is unlikely to be real in the case I assumed.  If you follow the partial constant expression index, all the expression values are tied, and so the index lists them in the order the rows physically occur in the table.  Traversing all those rows should be quite efficient as the table is being read in order.  But for the partial index over start_date, the index entries are sorted on start_date, which may have nothing to do with the physical ordering of the rows in table.  so reading all of the rows in the index will involve jumping all over the table, which might not be efficient.  Now the use of the bitmap scan should almost completely ameliorate this while imposing only a small overhead by re-ordering the tuples before reading them, which is why I say the effect is not actually real.  However, I think the planner has a problem accounting both for correlation and for bitmaps on a very selective partial index, so that the index over the constant expression gets an unfair estimation advantage that the bitmap cannot match in costing even though it does match in reality.  I would note that if I inhibit the bitmap scan, then use of your second index actually is substantially faster than use of your first one, assuming I start from a cold cache each time.


text:
Q: Why var result = typeof - "Hello, World"; return a number and not an exception? Is there any explanation why typeof return number in this example :
class MyClass{}

var result = typeof - "Hello, World";
// -----------------^
console.log(result);
// number  -- for me, it's not logic

var result2 = typeof + new MyClass();
// ------------------^
console.log(result2);
// number  -- for me, it's not logic

But for this cases :
var str = - new MyClass();
// NaN -- why not an exception

var str = - "some strings";
// NaN -- why not an exception

var result2 = typeof -24;
console.log(result2);
// number  -- logic because its a number

Maybe some cases is logic, but my question is, why typescript return number as result in the first and second example, logically the result should be "object", "undefined", "NaN", or even throw an exception as it do in this one :
var result2 = typeof % 'Hello, World';

But not a number!
I tried to search in documentation but there are no explanation.
Is this a bug?

A: var result = typeof - "Hello, World";

The meaning of this code is:

*

*Apply the unary negation operator - to "Hello, World"

*The result of this is NaN

*Apply the typeof operator to the value NaN

*The result of this is "number"
"Why doesn't JavaScript throw more exceptions?" is a philosophical question that doesn't really have a concrete answer apart from "Its designer thought that would be better"

A: Because NaN is a number

const nantype = typeof NaN;
console.info(nantype);


text:
Q: KeyPoints opencv FAST detector android I'm trying to use Opencv FAST detector setting a threshold in Android. I found a similar solved problem here. I have listed the keypoints list after detect method as suggested, but still doesn't work for me. In my case I want to detect the key points on my camera frame:
public Mat onCameraFrame(CvCameraViewFrame inputFrame) {
    MatOfKeyPoint points = new MatOfKeyPoint();

    Mat mat=inputFrame.rgba();
    FeatureDetector fast = FeatureDetector.create(FeatureDetector.FAST);
    fast.detect(mat, points);

    // Sort and select 500 best keypoints
    List<KeyPoint> listOfKeypoints = points.toList();
    Collections.sort(listOfKeypoints, new Comparator<KeyPoint>() {
        @Override
        public int compare(KeyPoint kp1, KeyPoint kp2) {
            // Sort them in descending order, so the best response KPs will come first
            return (int) (kp2.response - kp1.response);
        }
    });
    List<KeyPoint> listOfBestKeypoints = listOfKeypoints.subList(0, 500);
    points.fromList(listOfBestKeypoints);

    Scalar redcolor = new Scalar(255,0,0);
    Mat mRgba= mat.clone();
    Imgproc.cvtColor(mat, mRgba, Imgproc.COLOR_RGBA2RGB,4);

    Features2d.drawKeypoints(mRgba, points, mRgba, redcolor, 3);

    return mRgba;
}

Problem is that my listOfKeypoints remains null. If I don't try to set the threshold the code works fine  but too slow.
What am I doing wrong here?
Thanks.

A: I found out that my list is null only the first time onCameraFrame is called. So I can make it works using a class variable and populating my list starting from the second call.
private int count=0;

And then in onCameraFrame;
if (count!=0) {
        //Sort and select 500 best keypoints
        List<KeyPoint> listOfKeypoints =  points.toList();
        Collections.sort(listOfKeypoints, new Comparator<KeyPoint>() {
            @Override
            public int compare(KeyPoint kp1, KeyPoint kp2) {
                // Sort them in descending order, so the best response KPs will come first
                return (int) (kp2.response - kp1.response);
            }
        });
        List<KeyPoint> listOfBestKeypoints = listOfKeypoints.subList(0, 500);
        points.fromList(listOfBestKeypoints);

    }
    count++;

In this way it works, but I still don't understand why on the first call of onCameraFrame the list is null. Any ideas?


text:
Q: Counting True or False I have the following dataframe:
    True_False
2018-01-02  True
2018-01-03  True
2018-01-04  False
2018-01-05  False
2018-01-08  False
... ...
2020-01-20  True
2020-01-21  True
2020-01-22  True
2020-01-23  True
2020-01-24  False
504 rows × 1 columns

I want to know how many successive True or False but not total it must stop counting after it toggles True or False. As such i want to eventually calculate mean(), max() and min() days. is it possible to show this data in Pandas?

A: Solution if all datetimes are consecutive:
You can create helper Series for consecutive groups by Series.shift and Series.cumsum, then get counts by GroupBy.size:
g = df['True_False'].ne(df['True_False'].shift()).cumsum()
s = df.groupby(['True_False',g]).size()
print (s)
True_False  True_False
False       2             3
            4             1
True        1             2
            3             4
dtype: int64

And last aggregate min, max and mean per first level of MultiIndex:
print (s.groupby(level=0).agg(['mean','max','min']))
            mean  max  min
True_False
False          2    3    1
True           3    4    2

If datetimes are not consecutive first step is DataFrame.asfreq:
df = df.asfreq('d')
g = df['True_False'].ne(df['True_False'].shift()).cumsum()
s = df.groupby(['True_False',g]).size()
print (s.groupby(level=0).agg(['mean','max','min']))
                mean  max  min
True_False
False       1.333333    2    1
True        3.000000    4    2


text:
Q: Alternating row-column headers in worksheet with EPPlus I am trying to print output from a custom structure into Excel file. What I am trying to do is:
COLUMN NAME
PLAYER
PLAYER
COLUMN NAME
PLAYER
PLAYER
But What I am getting is
COLUMN NAME
COLUMN NAME
PLAYER
PLAYER
CODE:
int i = 1;

foreach (var item in scoresheet.Positions)
{
    var column = wb.Cells;

    if ((i % 5) == 1)
    {
        column["A" + i].LoadFromText("Initial Rank");
    }
    else
    {
        column["A" + i + 1].LoadFromText(item.Player.FirstName);
    }
    i++;
}

A: Looking at your line:
column["A" + i + 1].LoadFromText(item.Player.FirstName);

I assume you want that to be, say, a result of "A2" when i is equal to 1.  BUT, what you will actually end up with is "A11" since it will do it as a string concatenation.  What you need is:
column["A" + (i + 1)].LoadFromText(item.Player.FirstName);


text:
Q: Should I encapsulate id field with my own type? Considering below snippets:
class User {
  String id;

  ...other fields
}

class Id extends String {

}

class User {
  Id id;

  ...other fields
}

Which one should I use? I've never seen anoyone using their own Id type. Now I'm thinking: are there any drawbacks to do it?

A: This technique is called microtyping, sometimes tiny typing. It tends to make your code more expressive and thus safer and more readable.
However it also creates another layer of indirection: The reader of your code has to learn what an Id is to fully understand it. She probably already knows what a String is.
Generally I highly recommend microtyping. There are probably cases where it could be overdone but I haven't found one so far. So don't worry.
Concerning your specific implementation: In some languages like Java it is not possible to derive from standard classes like String. In other languages like C++ it is possible but not recommended. Therefore I would rather use composition instead of inheritance:
class Id {
    private String id;
    ...
}


text:
Q: Spring Boot Migration 1.5.7 to 2.4.5: Error creating bean with name 'servletEndpointRegistrar' I recently migrated from Spring Boot 1.5.7 to 2.4.5 and somehow my integration tests (all eight) are failing:
Config Details
gradle.wrapper gradle-5.6.4-all.zip
build.gradle:
    apply plugin: 'java'
    apply plugin: 'idea'
    apply plugin: 'org.springframework.boot'
    apply plugin: "jacoco"
    apply plugin: 'no.nils.wsdl2java'
    apply plugin: 'io.spring.dependency-management'

    group 'com.xxx.abc'

    sourceCompatibility = 1.8
    targetCompatibility = 1.8

    jar {
        baseName = 'abcd-service'
    }

    buildscript {
        ext {
            springBootVersion = '2.4.5'
            springWSVersion = '2.4.0.RELEASE'
            springSecurity = '5.1.6.RELEASE'
            slf4jVersion = '1.7.30'
            pivotalConfigClientVersion = '3.0.1.RELEASE'
            dependencyManagementPluginVersion = '1.0.11.RELEASE'
            httpclientVersion = '4.5.2'
            lombokVersion = '1.18.20'
            swaggerVersion = '2.9.2'
    //        swaggerVersion = '3.0.0'
            mockserverVersion = '5.5.1'
    //        mockserverVersion = '3.10.2'
            springVersion = '5.11.2.RELEASE'
            loggingUtilVersion = '0.1.29'
            junitVersion = '4.12'
        }
        repositories {
            maven {
                url '<<artifactoryURL>>'
                metadataSources {
                    mavenPom()
                    artifact()
                }
            }
        }
        dependencies {
            classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
    //        classpath "io.spring.gradle:dependency-management-plugin:$dependencyManagementPluginVersion"
            classpath('no.nils:wsdl2java:0.10')
        }
    }

    // Lets extend the resources of test to avoid duplication in integration test resources
    configurations {
        integrationTestCompile.extendsFrom testCompile
        integrationTestRuntime.extendsFrom testRuntime
    }

    //wsdl2java {
    //    wsdlsToGenerate = [
    //            ['-xjc-Xlombok',
    //             '-xjc-Xbg',
    //             '-xjc-Xvalue-constructor',
    //             '-mark-generated',
    //             '-autoNameResolution',
    //             '-b', "$projectDir/src/main/resources/binding.xjb",
    //             "$projectDir/src/main/resources/wsdl/abc-v1.wsdl"],
    //            ['-xjc-Xlombok',
    //             '-xjc-Xbg',
    //             '-xjc-Xvalue-constructor',
    //             '-mark-generated',
    //             '-autoNameResolution',
    //             '-b', "$projectDir/src/main/resources/binding.xjb",
    //             "$projectDir/src/main/resources/wsdl/xvz_v13.wsdl"]
    //    ]
    //    generatedWsdlDir = file("$projectDir/src/generated-sources")
    //    wsdlDir = file("$projectDir/src/main/resources/wsdl")
    //}

    def baseSvnUrl = "http://abcdef.com/svn/wsdls"

    //default wsdl directory path
    def wsdlDirPath = file(new File('src/main/resources/wsdl'))

    // abc soap client
    def abcUrl = "$baseSvnUrl/abc/abc-v1.wsdl"
    def abcWsdl = file("$wsdlDirPath/abc-v1.wsdl")
    def abcWsdlSafe = "wsdl/abc-v1.wsdl"

    def xyzUrl = "$baseSvnUrl/pqr/xyz-v13.wsdl"
    def xyzWsdl = file("$wsdlDirPath/xyz_v13.wsdl")
    def xyzSafe = "wsdl/xyz_v13.wsdl"

    //download wsdl file

    def downloadWsdl(fileName, wsdlUrl) {
        def f = new File(fileName)
        if (!f.exists()) {
            new URL(wsdlUrl).withInputStream{ i -> f.withOutputStream{ it << i }}
        }
    }

    def createWsdlToGenerateArray(wsdlLocation, wsdlUrl) {
        //xjb Binding location
        def xjbBindingPath = "src/main/resources/binding.xjb"
        return ['-xjc-Xlombok', '-xjc-Xbg', '-xjc-Xvalue-constructor', '-mark-generated', '-autoNameResolution',
                '-b', "$xjbBindingPath", '-wsdlLocation', wsdlLocation, wsdlUrl]
    }
    wsdl2java {
        repositories {
            maven {
                url '<<artifactoryUrl>>'
            }
        }
        generatedWsdlDir = file(new File("src/main/generated-sources"))
        wsdlDir = file("$wsdlDirPath")

        // downloading ABC wsdl file
        downloadWsdl("$abcWsdl", "$abcUrl")
        downloadWsdl("$xyzWsdl", "$xyzUrl")

        // just make a copy of createWsdlToGenerateArray to build another soap service code generation
        wsdlsToGenerate = [
                createWsdlToGenerateArray("$abcWsdlSafe", "$abcUrl"),
                createWsdlToGenerateArray("$xycSafe", "$xyzUrl")
        ]
    }
    // my project integrationTest directories
    sourceSets {
        main.java.srcDirs += "$projectDir/src/generated-sources"
        integrationTest {
            java {
                compileClasspath += main.output + test.output
                runtimeClasspath += main.output + test.output
                srcDir file('src/integrationTest/java')
            }
            resources.srcDir file('src/integrationTest/resources')
        }
    }

    //integrationTest task
    task integrationTest(type: Test) {
        testClassesDirs = sourceSets.integrationTest.output.classesDirs
        classpath = sourceSets.integrationTest.runtimeClasspath
    }

    repositories {
        maven {
            url '<<artifactoryUrl>>'
        }
    }

    apply plugin: "io.spring.dependency-management"

    dependencyManagement {
        imports {
            mavenBom 'org.springframework.cloud:spring-cloud-dependencies:2020.0.2'
        }
    }

    dependencies {
        compile(
            "org.springframework.boot:spring-boot-starter-web:${springBootVersion}",
            "org.springframework.boot:spring-boot-starter",
            "org.springframework.boot:spring-boot-starter-actuator",
            "org.springframework.boot:spring-boot-starter-data-jpa",
            "org.springframework.boot:spring-boot-starter-jdbc",
            "org.springframework.cloud:spring-cloud-starter-config",
            "org.springframework.cloud:spring-cloud-starter-bootstrap",
                "io.pivotal.spring.cloud:spring-cloud-services-starter-config-client:$pivotalConfigClientVersion",
                "javax.servlet:javax.servlet-api:4.0.1",
            "org.slf4j:slf4j-api:${slf4jVersion}",
            "org.springframework.boot:spring-boot-starter-integration:${springBootVersion}",
    //        "org.springframework.boot:spring-boot-starter-web:${springBootVersion}",
    //        "org.springframework.boot:spring-boot-starter-webflux:${springBootVersion}",
            'com.oracle.database.jdbc:ojdbc8-production:21.1.0.0',
    //        "com.oracle.jdbc:ojdbc7:12.1.0.2",
            "org.springframework.ws:spring-ws-core:${springWSVersion}",
            "org.springframework.security:spring-security-config",
            "org.springframework.security:spring-security-core",
            "com.xxx.abc:common-logging-util:$loggingUtilVersion",
            "org.projectlombok:lombok:${lombokVersion}",
            "io.springfox:springfox-swagger-ui:${swaggerVersion}",
            "io.springfox:springfox-swagger2:${swaggerVersion}",
            'org.apache.commons:commons-lang3:3.8.1',
            "org.apache.httpcomponents:httpclient:${httpclientVersion}",

            'org.jvnet.jaxb2_commons:jaxb2-basics-runtime:1.11.1',
    //        'com.jayway.jsonpath:json-path:2.0.0',
            "org.mock-server:mockserver-integration-testing:$mockserverVersion",
            "org.mock-server:mockserver-netty:$mockserverVersion",
    //        'it.yobibit:jaxb-lombok-plugin:1.0.0',
    //        "org.mockito:mockito-core:$mockitoVersion"
        )

        annotationProcessor "org.projectlombok:lombok:${lombokVersion}"
        testAnnotationProcessor "org.projectlombok:lombok:${lombokVersion}"

    //    compile group: 'joda-time', name: 'joda-time', version: '2.9.9'
        compile(files(wsdl2java.generatedWsdlDir).builtBy(wsdl2java))
        wsdl2java 'org.jvnet.jaxb2_commons:jaxb2-basics-runtime:1.11.1'
        wsdl2java 'org.jvnet.jaxb2_commons:jaxb2-basics:1.11.1'
        wsdl2java 'de.plushnikov.xjc:xjc-lombok-plugin:1.0'
        wsdl2java 'org.jvnet.jaxb2_commons:jaxb2-value-constructor:3.0'

        testCompile(
                "org.springframework.boot:spring-boot-starter-test:${springBootVersion}",
    //            "com.jayway.restassured:rest-assured:2.5.0",
    //            'com.jayway.restassured:json-schema-validator:2.5.0',
    //            'com.jayway.jsonpath:json-path:2.0.0',
                "org.mock-server:mockserver-integration-testing:${mockserverVersion}",
                "org.mock-server:mockserver-netty:${mockserverVersion}",
                "org.projectlombok:lombok:${lombokVersion}"
        )

        check.dependsOn integrationTest
        integrationTest.mustRunAfter test
    }

    jacoco {
        toolVersion = "0.8.6"
    }

    test { finalizedBy jacocoTestReport }

    jacocoTestReport {
        reports {
            xml.enabled false
            csv.enabled false
            html.enabled true
            html.destination file("${buildDir}/jacocoHtml")
    //        html.destination "${buildDir}/jacocoHtml"
        }
        afterEvaluate {
            getClassDirectories().setFrom(files(classDirectories.files.collect{
                fileTree(dir: it, exclude: ['**/model/**'])
            }))
        }
    }

    //task jarWithSources(type: Jar, dependsOn: classes) {
    //    classifier = 'source'
    //    from sourceSets.main.allSource
    //    from sourceSets.main.output
    //}

    task listAllDependencies(type: DependencyReportTask) {}
    defaultTasks 'clean', 'build'

Annotations on all integrationTest classes (same for all failing)
@SpringBootTest(classes = Application.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@RunWith(SpringJUnit4ClassRunner.class)
@ActiveProfiles("test")

Finally Exception in all the failing test cases when I run ./gradlew clean build
java.lang.IllegalStateException: Failed to load ApplicationContext
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:132)
    at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:124)
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:118)
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:83)
    at org.springframework.boot.test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener.prepareTestInstance(SpringBootDependencyInjectionTestExecutionListener.java:43)
    at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:244)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:227)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:289)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:291)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:246)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
    at org.junit.runners.ParentRunner$4.run(ParentRunner.java:331)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:79)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:329)
    at org.junit.runners.ParentRunner.access$100(ParentRunner.java:66)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:413)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
    at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecutor.runTestClass(JUnitTestClassExecutor.java:110)
    at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecutor.execute(JUnitTestClassExecutor.java:58)
    at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecutor.execute(JUnitTestClassExecutor.java:38)
    at org.gradle.api.internal.tasks.testing.junit.AbstractJUnitTestClassProcessor.processTestClass(AbstractJUnitTestClassProcessor.java:62)
    at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.processTestClass(SuiteTestClassProcessor.java:51)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:36)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
    at org.gradle.internal.dispatch.ContextClassLoaderDispatch.dispatch(ContextClassLoaderDispatch.java:33)
    at org.gradle.internal.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:94)
    at com.sun.proxy.$Proxy2.processTestClass(Unknown Source)
    at org.gradle.api.internal.tasks.testing.worker.TestWorker.processTestClass(TestWorker.java:118)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:36)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
    at org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:182)
    at org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:164)
    at org.gradle.internal.remote.internal.hub.MessageHub$Handler.run(MessageHub.java:412)
    at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:64)
    at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:48)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:56)
    at java.lang.Thread.run(Thread.java:748)
Caused by: org.springframework.context.ApplicationContextException: Unable to start web server; nested exception is org.springframework.boot.web.server.WebServerException: Unable to start embedded Tomcat
    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.onRefresh(ServletWebServerApplicationContext.java:162)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:577)
    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:144)
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:782)
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:774)
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:439)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:339)
    at org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:123)
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:99)
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:124)
    ... 51 more
Caused by: org.springframework.boot.web.server.WebServerException: Unable to start embedded Tomcat
    at org.springframework.boot.web.embedded.tomcat.TomcatWebServer.initialize(TomcatWebServer.java:142)
    at org.springframework.boot.web.embedded.tomcat.TomcatWebServer.<init>(TomcatWebServer.java:104)
    at org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory.getTomcatWebServer(TomcatServletWebServerFactory.java:450)
    at org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory.getWebServer(TomcatServletWebServerFactory.java:199)
    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.createWebServer(ServletWebServerApplicationContext.java:181)
    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.onRefresh(ServletWebServerApplicationContext.java:159)
    ... 60 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'servletEndpointRegistrar' defined in class path resource [org/springframework/boot/actuate/autoconfigure/endpoint/web/ServletEndpointManagementContextConfiguration$WebMvcServletEndpointManagementContextConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.boot.actuate.endpoint.web.ServletEndpointRegistrar]: Factory method 'servletEndpointRegistrar' threw exception; nested exception is java.util.NoSuchElementException: Unable to get attribute value for missing annotation
    at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:658)
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:638)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1334)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1177)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:564)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:524)
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:213)
    at org.springframework.boot.web.servlet.ServletContextInitializerBeans.getOrderedBeansOfType(ServletContextInitializerBeans.java:212)
    at org.springframework.boot.web.servlet.ServletContextInitializerBeans.getOrderedBeansOfType(ServletContextInitializerBeans.java:203)
    at org.springframework.boot.web.servlet.ServletContextInitializerBeans.addServletContextInitializerBeans(ServletContextInitializerBeans.java:97)
    at org.springframework.boot.web.servlet.ServletContextInitializerBeans.<init>(ServletContextInitializerBeans.java:86)
    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.getServletContextInitializerBeans(ServletWebServerApplicationContext.java:259)
    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.selfInitialize(ServletWebServerApplicationContext.java:233)
    at org.springframework.boot.web.embedded.tomcat.TomcatStarter.onStartup(TomcatStarter.java:53)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5161)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1384)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1374)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at org.apache.tomcat.util.threads.InlineExecutorService.execute(InlineExecutorService.java:75)
    at java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:134)
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:909)
    at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:843)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1384)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1374)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at org.apache.tomcat.util.threads.InlineExecutorService.execute(InlineExecutorService.java:75)
    at java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:134)
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:909)
    at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:262)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
    at org.apache.catalina.core.StandardService.startInternal(StandardService.java:433)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
    at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:930)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
    at org.apache.catalina.startup.Tomcat.start(Tomcat.java:486)
    at org.springframework.boot.web.embedded.tomcat.TomcatWebServer.initialize(TomcatWebServer.java:123)
    ... 65 more
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.boot.actuate.endpoint.web.ServletEndpointRegistrar]: Factory method 'servletEndpointRegistrar' threw exception; nested exception is java.util.NoSuchElementException: Unable to get attribute value for missing annotation
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185)
    at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:653)
    ... 105 more
Caused by: java.util.NoSuchElementException: Unable to get attribute value for missing annotation
    at org.springframework.core.annotation.MissingMergedAnnotation.getAttributeValue(MissingMergedAnnotation.java:160)
    at org.springframework.core.annotation.AbstractMergedAnnotation.getRequiredAttributeValue(AbstractMergedAnnotation.java:217)
    at org.springframework.core.annotation.AbstractMergedAnnotation.getString(AbstractMergedAnnotation.java:139)
    at org.springframework.boot.actuate.endpoint.annotation.EndpointDiscoverer$EndpointBean.<init>(EndpointDiscoverer.java:414)
    at org.springframework.boot.actuate.endpoint.annotation.EndpointDiscoverer.createEndpointBean(EndpointDiscoverer.java:146)
    at org.springframework.boot.actuate.endpoint.annotation.EndpointDiscoverer.createEndpointBeans(EndpointDiscoverer.java:134)
    at org.springframework.boot.actuate.endpoint.annotation.EndpointDiscoverer.discoverEndpoints(EndpointDiscoverer.java:123)
    at org.springframework.boot.actuate.endpoint.annotation.EndpointDiscoverer.getEndpoints(EndpointDiscoverer.java:117)
    at org.springframework.boot.actuate.autoconfigure.endpoint.web.ServletEndpointManagementContextConfiguration$WebMvcServletEndpointManagementContextConfiguration.servletEndpointRegistrar(ServletEndpointManagementContextConfiguration.java:65)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154)
    ... 106 more

Any help in this regard shall be appreciated.


text:
Q: Quick way to create debug build for visual studio projects I have 15 projects in my Visual studio solution , I didn't create debug builds(was lazy) when I added these projects now I am in need of debug build. Is there a hack to get a debug build of my solution from the release build itself? Any help is greatly appreciated. Thanks

A: Change the build settings to debug and rebuild solution.
VS creates automatically Debug and Release.
If you have modified configuration (only for release) than there is no magic trick here - copy the default DEBUG configuration and change it as well.


text:
Q: Basis in linear Algebra $S=(v_1, \cdots v_n)$ of vectors in $\mathbb{F^n}$ is a basis iff the matrix obtained by forming a matrix (call it A) of the co-ordinate vectors of $v_i$ is invertible
My Idea: I was able to prove the reverse direction wherein we can show that $AX =0$ has trivial solutions so linearly independent and also spans the given vector space so it is a basis.
I am not sure about the forward direction that is to prove that A is invertible. I am just confused about the coordinate vector for $v_i$. That is,we assume $S$ is a basis then how can each element  (namely $v_i'$'s) in a basis have a coordinate vector? Wouldn't it just be a single column for different vector in the vector space?

A: HINT: The determinant of a matrix is zero iff the vectors which form it are linearly independent.
See also:
Using the Determinant to verify Linear Independence, Span and Basis

A: You can rewrite $A$ as a row of vectors $A_1,\dots,A_n$. Then
$$
Ax = x_1 A_1 + \dots + x_n A_n
$$
Think about
$Ax=b$ always solvable means $A_i$ generate $V$
$Ax=b$ uniquely solvable (if at all) means $A_i$ independent
If these two conditions are met, you can find $n$ solutions for $Ax_i=e_i$ (put them in a matrix). This matrix will be the inverse.
If $A$ is invertible, then for every $b$ the equation $Ax=b$ has the unique solution $x=A^{-1}b$. So the $A_i$ are a basis.


text:
Q: printf preventing race conditions In this example code I do a summation from i=0 to i=n and then add the result to itself k times, where k is the number of threads. I purposely did it without critical (surrounding the printf and ans += ans) to cause race conditions. However, to my surprise, no race condition happened:
int summation_with_operation_after_it_wrong1(int n, int k) {
        int ans = 0;
        #pragma omp parallel firstprivate(n) num_threads(k)
        {
                int i; /* Private */
                #pragma omp for schedule(dynamic) reduction(+:ans)
                for (i = 0; i < n; i++) {
                        ans += i;
                }
                printf("Thread %d ans=%d\n", omp_get_thread_num(), ans);
                ans += ans;
        }
        return ans;
}

Using n=10 and k=4, the output is (always the same, except for thread order):
Thread 1 ans=45
Thread 3 ans=45
Thread 0 ans=45
Thread 2 ans=45
720

However, I did noticed something odd about it. ans was always 45, instead of
Thread 3 ans=45
Thread 0 ans=90
Thread 2 ans=180
Thread 1 ans=360
720

When using critical. So I moved the printf to after the ans += ans to see what it was doing, and, for my surprise, the predicted race conditions started to occur all the time!
Thread 3 ans=90
Thread 1 ans=135
Thread 2 ans=90
Thread 0 ans=135
135

So... How does the printf prevented race conditions? And how does that sum ended up to be 720? I'm completely lost here.

A: Section 1.4 of the latest OpenMP standard specifies what is the result of a race condition (emphasis mine):

If multiple threads write without synchronization to the same memory
  unit, including cases due to atomicity considerations as described
  above, then a data race occurs. Similarly, if at least one thread
  reads from a memory unit and at least one thread writes without
  synchronization to that same memory unit, including cases due to
  atomicity considerations as described above, then a data race occurs.
  If a data race occurs then the result of the program is unspecified.

What you notice is completely consistent with the statement in bold. In fact, as the behavior in a program containing a data-race is unspecified, it makes little sense to argue why a particular output results from a given run. In particular, it is only by chance that you obtained 720 when inserting a printf before the ans+=ans command, and there's no guarantee that you will always encounter the same behavior.

A: printf() is a very expensive call to make, and it's not a surprise that using it changes your race condition timing. A better option to see what's happening is to create an array (in advance) to store your results and have each thread deposit its result into this array where you're currently performing the print; then do the actual printf() after all the work has completed.


text:
Q: Log Errors in Azure Mobile Service I'm trying to figure out how to log from my Mobile Service with a .NET backend. So far, I've read that you can do this by calling:
ApiController.ApiServices.Log.Info("log string")

This is fine if you're in an ApiController as you can simply use this.Services, but what would you do if you wanted to log from somewhere besides a controller? Is this even possible?

A: If by "besides a controller" you mean in a custom controller, you can declare
public ApiServices Services { get; set; }

and then use the Services.Log.Error("your error")
If this is not what you're asking, please give some more information.


text:
Q: Iterate a pymongo cursor from MLab Why won't the cursor iterate? I feel sure there should be an easy solution.
I have tried multiple Stack Overflow answers and the documentation for Mongodb
https://docs.mongodb.com/getting-started/python/query/
The code is as per below:
from pymongo import MongoClient

#Connect to Mongo Client
client = MongoClient('mongodb://the_username:the_password@ds047124.mlab.com:47124/politicians_from_theage')
db = client.politicians_from_theage #define database used

# Define Collection
collection = db.posts
print collection

Result:
Collection(Database(MongoClient(host=['ds047124.mlab.com:47124'], document_class=dict, tz_aware=False, connect=True), u'politicians_from_theage'), u'posts')

Then the cursor will print its location:
# Define Cursor
my_cursor = collection.find()
print my_cursor

Result:
<pymongo.cursor.Cursor object at 0x0000000003247518>

Then to try and iterate over the cursor provides a timeout:
 # Perform query
    cursor = db.posts.find()
    #Iterate the cursor and print the documents.
for document in cursor:
    print(document)  #No Luck

Traceback Error or Iteration:
Traceback (most recent call last):
  File "C:\PythonC\PythonWebScraping\17_MongoInterface\mongoget.py", line 18, in <module>
    for result_object in my_cursor:
  File "C:\Python27\lib\site-packages\pymongo\cursor.py", line 1090, in next
    if len(self.__data) or self._refresh():
  File "C:\Python27\lib\site-packages\pymongo\cursor.py", line 1012, in _refresh
    self.__read_concern))
  File "C:\Python27\lib\site-packages\pymongo\cursor.py", line 850, in __send_message
    **kwargs)
  File "C:\Python27\lib\site-packages\pymongo\mongo_client.py", line 827, in _send_message_with_response
    server = topology.select_server(selector)
  File "C:\Python27\lib\site-packages\pymongo\topology.py", line 210, in select_server
    address))
  File "C:\Python27\lib\site-packages\pymongo\topology.py", line 186, in select_servers
    self._error_message(selector))
pymongo.errors.ServerSelectionTimeoutError: ds047124.mlab.com:47124: timed out

I have tried iterating on 'cursor', 'my_cursor' and 'collection', each of which provides a traceback error of server timeout.
Any help/insight would be greatly appreciated

A: This may help you:-
 # Perform query
cursor = db.posts.find().toAray(function(err, result){
     #Iterate the cursor and print the documents.
     for document in result:
     print(document);
}) //Will give you array of objects.

Let me know if it works.

A: Found the answer, I was focusing on the cursor rather than loading the object from the cursor from JSON to a list of JSON.
Final code is below (removing the URI)
import json
from datetime import date, timedelta
from pymongo import MongoClient
from bson import json_util

#Connect to Mongo Client
client = MongoClient('mongodb://user:pword@ds047124.mlab.com:47124/politicians_from_theage')
db = client.politicians_from_theage #define database used
print db
# Define Collection
collection = db.posts
print collection # print Collection(Database(MongoClient(host=['ds047124.mlab.com:47124']...

cursor = collection.find()
print cursor

# Obtain json
json_docs = []
for doc in cursor:
    json_doc = json.dumps(doc, default=json_util.default)
    json_docs.append(json_doc)
print json_docs #json result

# List Comprehension version
#json_docs = [json.dumps(doc, default=json_util.default) for doc in cursor]

#To get back from json again as string list
docs = [json.loads(j_doc, object_hook=json_util.object_hook) for j_doc in json_docs]
print docs

print 'kitty terminates program'

A: Try this:
cursor = db.posts.find()
for document in list(cursor):
    print(document)


text:
Q: Simply edit custom line from .txt with PHP Txt file:
Line 1
Line 2
Line 3
Line 4
$contents = file_get_contents('file.txt');
$contents[1] = "Sample edit.";
file_put_contents("file.txt",$contents);
Eddited txt file:
Line 1
Sample edit.
Line 2
Line 3
Line 4
But it's not working for me.

A: Next code is one way to do it. Pay attention to the comments in the code :
<?php
$line = 2; // LINE TO REPLACE.
$my_array = file( "my_file.txt" ); // GET WHOLE FILE AS ARRAY OF STRINGS.
$my_array[ $line ] = "abc" . "\n"; // REPLACE THIRD LINE (2). NOTICE THE "\N".
file_put_contents( "my_file.txt",             // SAVE ARRAY IN FILE.
                   implode( "",$my_array ) ); // CONVERT ARRAY INTO A BIG STRING.
?>

This is the idea : read the entire file as an array (file), now you can replace the desired line by its index, then you convert the array as string (implode), and save it to file (file_put_contents).


text:
Q: Split Delimited String into Columns in SQL Server 2017 I have a table that has following text in a column and I need to convert the texts into multiple columns.
create table Test (
 resource_type varchar(300)
);
insert into Test (resource_type) values
('Number of reservations: 1'),
('Number of reservations: 2  ¶ Perf ID: Event : 51680'),
('Number of reservations: 3  ¶ Perf ID: Event : 51683');

and I have converted this into columns by doing
Select A.*
      ,Pos1 = xDim.value('/x[1]' ,'varchar(100)')
      ,Pos2 = xDim.value('/x[2]' ,'varchar(100)')

From Test A
Cross Apply ( values (convert(xml,'<x>' + replace(A.resource_type,'¶','</x><x>')+'</x>')) )B(xDim)

Output of the code is

Instead, I need Number of reservations and PerfID as columns and under the number of reservations values as 1, 2, and 3 and under perf id null, 51680, and 51683...
Please help me how to proceed further!

A: Please try the following solution.
SQL
DECLARE @tbl TABLE (resource_type VARCHAR(300));
INSERT INTO @tbl (resource_type) VALUES
('Number of reservations: 1'),
('Number of reservations: 2  ¶ Perf ID: Event : 51680'),
('Number of reservations: 3  ¶ Perf ID: Event : 51683');

DECLARE @separator CHAR(1) = ':';

SELECT t.* -- , c
    ,Pos1 = TRIM(c.value('(/root/r[2]/text())[1]' ,'varchar(100)'))
    ,Pos2 = TRIM(c.value('(/root/r[5]/text())[1]' ,'varchar(100)'))
FROM @tbl AS t
CROSS APPLY (SELECT TRY_CAST('<root><r><![CDATA[' +
      REPLACE(REPLACE(resource_type,'¶',@separator), @separator, ']]></r><r><![CDATA[') +
      ']]></r></root>' AS XML)) AS t1(c);

Output

resource_type
Pos1
Pos2

Number of reservations: 1
1
NULL

Number of reservations: 2  ¶ Perf ID: Event : 51680
2
51680

Number of reservations: 3  ¶ Perf ID: Event : 51683
3
51683

A: You could, if you wish, accomplish this just with a bit of charindex / substring, for example:
select resource_type,
  Substring(resource_type, p1.p, IsNull(NullIf(p2.p,0) - p1.p - 1, Len(resource_type))) Pos1,
  Substring(resource_type, p3.p, Len(resource_type)) Pos2
from test
cross apply(values(CharIndex(':', resource_type) + 2))p1(p)
cross apply(values(CharIndex('¶', resource_type) ))p2(p)
cross apply(values(NullIf(CharIndex('Event', resource_type, p1.p), 0) + 8))p3(p);

Demo Fiddle

A: Since you are running 2016+ you can use a bit of JSON.   The JSON approach is FAR MORE PERFORMANT than the XML approach (which looks very familiar :)  )
Select A.resource_type
      ,Pos1 = trim(JSON_VALUE(JS,'$[1]'))
      ,Pos2 = trim(JSON_VALUE(JS,'$[4]'))
 From  Test A
 Cross Apply (values ('["'+replace(string_escape(replace(resource_type,'¶',':'),'json'),':','","')+'"]') ) B(JS)

Results


text:
Q: PHP Script to MD5 Hash Each Line Separately I'm trying to create a script that can MD5 hash many lines (50,000+) quickly. I have a script I've been trying to make work, but it gives me different outputs sometimes and I can't figure out why. Any ideas?
  <?php
     if(isset($_POST['btn'])){
            $value=$_POST['text'];
            $ids = explode(PHP_EOL, $value);
            $content = '';
            for ($i=0;$i<count($ids);$i++){
                $content .= md5($ids[$i]).'
';
            }

            echo nl2br($content);
     }
     ?>

When I try to hash:
apples
bananas
oranges
pineapples

It results in:
265f78fc274d8428fd63dabc24400cb4
63a63ddf49984e0f1cef336aeb6ca39c
229b1cc78a248c6cea47fa95565dc9ca
019b111ec0c13ed923922715bfb1670a

But I should be getting:
daeccf0ad3c1fc8c8015205c332f5b42
ec121ff80513ae58ed478d5c5787075b
91b07b3169d8a7cb6de940142187c8df
019b111ec0c13ed923922715bfb1670a

A: The lines in your input string are separated by \r\n, but on your server PHP_EOL is set to \n. So when you split the input into lines, there's a \r at the end of each line except the last. echo md5("apples\r"); produces 265f78fc274d8428fd63dabc24400cb4.
Use trim() to remove extra whitespace.
$content .= md5(trim($ids[$i])).'
';

A: You have whitespaces in your input data. And don't collect all 50k+ hashes in memory.
Try this
<?php
if(isset($_POST['btn'])){
    $value=$_POST['text'];
    $ids = explode(PHP_EOL, $value);
    for ($i=0;$i<count($ids);$i++){
        echo nl2br(md5(trim($ids[$i])));
    }
}
?>


text:
Q: How to check if a datefield is expired (Laravel/Lumen) I have a table called events and events expire. if their dates and time is up how do i check in my controller if the dateTime field from and to are up if that event time is up i want to set the expired field to 1
public function up()
{
Schema::create('club_events', function (Blueprint $table) {
$table->increments('id');
$table->string('event_name');
$table->string('description');
$table->boolean('special_events');
$table->decimal('event_price');
$table->dateTime('from')->nullable();
$table->dateTime('to')->nullabe();
$table->boolean('expired')->nullable();

$table->integer('club_id')->unsigned();
$table->timestamps();

$table->foreign('club_id')
->references('id')->on('club')
->onDelete('cascade');

});
}

A: You would compare it to the current datetime like:
if (now()->gte($clubEvent->to)) {
    // the event is expired
} else {
    // not expired
}

Here are the Carbon comparison functions.
Update the expired field like:
$clubEvent->update([
     'expired' => now()->gte($clubEvent->to)
]);