text:
Q: Is there any free multi purpose development server? There are so many tools out there. You can do so much things around developing that it is a full time job on its own. So why not integrating features / tools to an powerful server application.
Is there a server which integrates (some of) these features:

*

*static code analysis

*automated builds (e.g. through maven)

*continuious integreation

*automated tests

*project website (source code, team collaboration, documentation, java doc)

*bug tracking

*version control (e.g. through SVN)

*statistics

*download section

*code coverage

*any other metrics and quality supporting features

I am sure there are more useful features which do not come to my mind right now. There are tools out there supporting one or the other feature.
Is there any software that supports some more of those features? It would be perfect if that software would be free, but at least it should be non commercial. I am mostly using Java.
Thanks in advance.

A: What you need is a setup for Hudson, Maven, Nexus Repository Manager and a Bug Tracking Tool like Redmine. The Redmine can be started with a Bitnami Stack which includes Subversion.
The code analysis can be done by using cobertura, findbugs etc. with Maven (using Plugins). If you need more metrics take a look at sonar with support of a Maven Plugin.
The Web-Site etc. can be done by using Maven (site generation).

A: Sounds like you want Cruise Control or Hudson.  Both can do most of the items on your laundry list.

A: I like Launchpad...
Launchpad is a software collaboration platform that provides:

*

*Bug tracking

*Code hosting using Bazaar Code reviews

*Ubuntu package building

*Hosting Translations

*Mailing lists

*Answer tracking and FAQs

*Specification tracking

Take the tour!
The key is the package building. You should check it out.

A: If your requirement is "[Ff]ree" I'd suggest Hudson.  It's quite modern and has a ton of plugins that can take care of the requirements you've asked for.  Hudson is very actively maintained and the plugins receive lots of attention too.

*

*Homepage here:  http://hudson-ci.org/

*List of plugins here:  http://wiki.hudson-ci.org/display/HUDSON/Plugins

*IRC Channel (great resource for help):  irc://chat.freenode.net/#hudson
Hudson literally takes minutes to setup and bootstrap as well, in simple cases.

A: You can get exactly everything you need in one package, and free, in fazend.com. The platform integrates SVN, Trac, CruiseControl, Maven, etc. You start a project with one click.


text:
Q: source() doesn't work ("node stack overflow") I have the following few lines of code in my R script called assign1.R:
(u <- c(1, 1, 0, 1, 0)) # a)
u[3] # b)
ones_u <- which(u == 1) # c)
ones_u
source("assign1.R")

Only, the source() function does not work. R shows me the following error message:
Error in match(x, table, nomatch = 0L) : node stack overflow
Error during wrapup: node stack overflow

What is the problem?

A: Your are sourcing the file that you are in. That source() line of code should be deleted. If you are sourcing some code from another R file then you would use the source() function, otherwise there is no need to source another file. Also, if all the code works in the one file without running other bits of code in other files, it is likely that you already have the code you need and you wouldn't need to source another file.

A: I didn't get exactly the same error you did, but I was able to get something pretty similar with a trivial example:
writeLines("source('badsource.R')",con="badsource.R")
source("badsource.R")
## Error in guess(ll) : node stack overflow

As one of the comments above states, the file you're sourcing is trying to source() itself.
This is how you would test for that possibility from within R, without just opening the file in a text editor (which is a much more sensible approach):
grepl("source('badsource.R')",readLines("badsource.R"),fixed=TRUE)  ## TRUE

(obviously you should fill in the name of your assignment file here ...)
It feels like you should have noticed this yourself, but I'm answering anyway because the problem is delightfully recursive ...

redpajama_set_name: RedPajamaStackExchange


text:
Q: Let $F(x)=cot\int_{\int_{0}^{x}tan(a)da}^{1}cosh(\int_{0}^{t}udu)dt$ Find $F'(x)$ "Let $F(x)=\cot\int_{\int_{0}^{x}\tan(a)da}^{1}\cosh(\int_{0}^{t}udu)dt$. Find $F'(x).$"
We know:
$F'(x)=-\csc^{2}(\int_{\int_{0}^{x}\tan(a)da}^{1}\cosh(\int_{0}^{t}udu)dt)\times(\int_{\int_{0}^{x}\tan(a)da}^{1}\cosh(\int_{0}^{t}udu)dt)'$
Let $A(x)=\int_{\int_{0}^{x}\tan(a)da}^{1}\cosh(\int_{0}^{t}udu)dt$
Then: $A'(x)=-\cosh(\int_{0}^{\int_{0}^{x}\tan(a)da}udu)\tan(x)$
Then,
$F'(x)=\csc^{2}(\int_{\int_{0}^{x}\tan(a)da}^{1}\cosh(\int_{0}^{t}udu)dt)\cosh(\int_{0}^{\int_{0}^{x}\tan(a)da}udu)\tan(x)$
But I'm not sure my result is correct. Can someone help me?

A: Your function has the form
$$F (x)=\cot (f (x))=$$
$$\cot (-\int_1^{g (x)}h (t)dt )$$
with $$g (x)=\int_0^x\tan (a)da $$
and
$$h (t)=\cosh (\int_0^t udu) .$$
thus
$$F'(x)=-\frac {1}{\sin^2 (f (x))}\Bigl (-h (g (x))g'(x)\Bigr) $$
with $$g'(x)=\tan (x) $$
hence

$$F'(x)=(1+F^2 (x))\cosh (\int_0^{\int_0^x\tan (a)da})\tan (x) $$


text:
Q: Gateway Time_out issue between AJP connector and Tomcat 8.5.54 I have a tomcat 8 server fronted by Apache 2 (2.4.25) on debian 9.12 (stretch) system and I'm using ajp connector between apache2 an tomcat. JDK version is Oracle JDK 1.8.0_252-8u252-b09-1~deb9u1-b09. Everything was working fine until tomcat8 automatically updated to 8.5.54. But now when accesing application through ajp there is a 504 time-out Gateway error.
The tomcat8 server was automatically updated this morning
Start-Date: 2020-05-05  06:01:41
Commandline: /usr/bin/unattended-upgrade
Upgrade: libservlet3.1-java:amd64 (8.5.50-0+deb9u1, 8.5.54-0+deb9u1),
libtomcat8-java:amd64 (8.5.50-0+deb9u1, 8.5.54-0+deb9u1),
tomcat8-examples:amd64 (8.5.50-0+deb9u1, 8.5.54-0+deb9u1),
tomcat8-admin:amd64 (8.5.50-0+deb9u1, 8.5.54-0+deb9u1),
tomcat8-common:amd64 (8.5.50-0+deb9u1, 8.5.54-0+deb9u1), tomcat8:amd64
(8.5.50-0+deb9u1, 8.5.54-0+deb9u1), tomcat8-docs:amd64 (8.5.50-0+deb9u1,
8.5.54-0+deb9u1)
End-Date: 2020-05-05  06:01:52

Nothing changed in the apache2 and tomcat8 configuration file.  I can still acces the tomcat manager interface and I can see my applications running. I can acces the tomcat applications with localhost, but not through the apache2 server.
For example, I have the application QCM1 deployed on the tomcat8 server. If I perform the following wget command
wget http://localhost:8080/QCM1

the response is correct, but when I perform
wget http://myserve.mydomain.fr/QCM1

there is 504 Gateway Time-out error
To enable redirection of HTTP request to the tomcat server, there is the following directive in the apache2 configuration file (that directive was working fie before the update of tomcat8)
ProxyPass /QCM1 ajp://localhost:8009/QCM1

What am I missing?
Thanks for your help.

A: Finally I've found a solution, the stack trace of the error was :
05-May-2020 16:29:01.292 GRAVE [main]
org.apache.catalina.core.StandardService.startInternal Failed to start connector [Connector[AJP/1.3-8009]]
org.apache.catalina.LifecycleException: Le démarrage du gestionnaire de protocole a échoué
at org.apache.catalina.connector.Connector.startInternal(Connector.java:1086)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
at org.apache.catalina.core.StandardService.startInternal(StandardService.java:440)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:766)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
at org.apache.catalina.startup.Catalina.start(Catalina.java:688)
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.apache.catalina.startup.Bootstrap.start(Bootstrap.java:343)
at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:474)

a solution to fix this problem was to change the configuration of the AJP connector in the server.xml file and to add a secretRequired attribute as Jainender Chauhan suggested in his response to Springboot -The AJP Connector is configured with secretRequired="true" but the secret attribute is either null or "" after upgrade to 2.2.5
<Connector protocol="AJP/1.3" port="8009" redirectPort="8443" secretRequired="false" />

It works fine. But I'm not sure it's the best and the most secure way of proceeding


text:
Q: C execvp usage, what am I missing? I am trying to make a program that uses shell commands for a school project. I am able to compile and run the code without errors, but when I input a command such as ls, noting happens. I think I am missing something with the execvp.
I have been trying to use various configurations of inputs.
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <wait.h>
#include <stdlib.h>

#define MAX_LINE 80  /* Maximum length of a command */

int main(void) {
    char args[MAX_LINE / 2 + 1]; /* command line arguments */
    int should_run = 1; /* Flag to determine when to exit the program */
    pid_t pid;
    char *myCmd;
    char *tokens[40];
    pid = fork();

    while (should_run) {
        printf("osh>");
        fflush(stdout);
        scanf("%s", myCmd);

        int i = 0;
        char *token = strtok(myCmd, " ");

        while (token != NULL) {
            tokens[i] = token;
            i++;
            token = strtok(NULL, " ");
        }

        if (pid < 0) {
            printf("Fork Failed\n");
            //exit(1);
        } else
        if (pid == 0) {
            execvp(tokens[0], tokens);
            //exit(1);
        } else {
            if (strcmp(tokens[i - 1], "&")) {
                waitpid(pid, NULL, 0);
            }
        }
    }
    return 0;
}

A: Writing to unallocated memory:
char* myCmd;

only allocates memory for the pointer. The pointer has an indeterminate value i.e. it may be pointing to anything and
any attempt to dereference a pointer with a bad value would result in undefined behaviour.

Automatically and dynamically allocated objects are initialized only
if an initial value is explicitly specified; otherwise they initially
have indeterminate values (typically, whatever bit pattern happens to
be present in the storage, which might not even represent a valid
value for that type).

The subsequent call to scanf() then invokes undefined behaviour, because no memory was ever allocated for the string.
scanf("%s", myCmd);

Possible fix:
If no command is ever going to exceed 80 characters, as stated in this comment:
define MAX_LINE 80 /*Maximum length of a command*/

You can allocate an array[80] of char and then pass it to scanf().
And to limit input, you could specify a width specifier like so:
scanf("%79s", myCmd);

Note:
Don't use scanf(). Use fgets(). With scanf(), it will only grab the first whitespace separated token (e.g. for input of Hello World, scanf() will only return Hello). — @Craig Estey

The array of pointers to execvp shall be null-terminated:

The execv(), execvp(), and execvpe() functions provide an array of
pointers to null-terminated strings that represent the argument list
available to the new program. The first argument, by convention,
should point to the filename associated with the file being executed.
The array of pointers must be terminated by a NULL pointer.

Code is missing:
tokens[i] = NULL;

after the while loop.

Aside: A shell in C - Tutorial and Beej's guide to UNIX Interprocess Communication might help to elaborate on what @John pointed out in his answer.

A: In addition to the serious issues with command input and formatting of execvp() arguments called out in another answer, you are fork()ing in the wrong place.  You need to fork() a new child for each command the shell runs, so the fork call should go inside the loop.  Moreover, it should go after printing the prompt and reading a command, because you want only the parent to do those things, not the children.  And you do not need both parent and child to parse the command.  Although you could rely on the child to do that, it would be more conventional to do it in the parent.  But certainly not in both.
It is conceivable that your program would still seem to work despite the other errors (though that would not be any justification for failing to fix them), but the fork() placement issue is absolutely breaking.  It will cause unexpected extra prompting, and the shell will never attempt to execute more than one command (though you might not notice, in part because you do not check the return values of several key function calls).


text:
Q: Pattern for implementing async http handlers in F#? Could someone tell me a good pattern to use when coding asynchronous http handlers in F#?
I have to implement IHttpAsyncHandler and that interface requires a BeginProcessRequest and EndProcessRequest.
Do I return Async.StartTask? How do I handle state:obj and AsyncCallback?

A: Off the top of my head: implement handler using async workflow and then expose it with Async.AsBeginEnd
open System
open System.Web

type HttpAsyncHandler() =

    let processRequestAsync (context : HttpContext) = async {
        // TODO: implement
        return()
        }

    let beginAction, endAction, _ = Async.AsBeginEnd(processRequestAsync)

    interface IHttpAsyncHandler with
        member this.BeginProcessRequest(context, callback, extraData) = beginAction(context, callback, extraData)
        member this.EndProcessRequest(iar) = endAction (iar)
        // other members omitted

A: What are you trying to do, exactly? If you are able, you might want to consider the HttpMessageHandler and its ilk from System.Net.Http. You only have to override the
protected abstract Task<HttpResponseMessage> SendAsync(
    HttpRequestMessage request,
    CancellationToken cancellationToken);

method, which is easy with an async { ... } |> Async.StartAsTask. You also get better access to the various attributes of HTTP through static typing. Various subclasses allow you to run either through ASP.NET, WCF (self-host), or even third-part platforms like OWIN.


text:
Q: What does segmentation fault (core dumped) mean? (quicksort code) I am writing a quicksort function and am getting a segmentation fault error. I'm not sure why this is. Any help is appreciated. Here's my code. I know the error means that I'm trying to access memory that doesn't exist but I'm not sure where exactly the mistake is.
#include <stdio.h>

void swap(int arr[], int i, int j){
  int tmp;
  tmp = arr[i];
  arr[i] = arr[j];
  arr[j] = tmp;
}

int partition(int arr[], int first, int last){
  int pivot = arr[last];
  while(first <= last){
while(arr[first] < pivot){
  first++;
}
while(arr[last] > pivot){
  last--;
}
if(first <= last){
  swap(arr, arr[first], arr[last]);
  first++;
  last--;
}
}
}

void quickSortR(int arr[], int first, int last){
  if(last <= first) return;
  int mid = partition(arr, first, last);
  quickSortR(arr, first, mid-1);
  quickSortR(arr, mid+1, last);
}

void main() {
int arr[14] = {488888, 3, 5, 0, 23, 12124, 6, 7, 2, 1121, 0, 92, 5, 8};
quickSortR(arr, 0, 13);
for (int i = 0; i<14; i++) {
printf("arr[%d] = %d\n", i, arr[i]);
}
}

A: This function return int but you don't return anything:
int partition(int arr[], int first, int last){

so it make the mid is undefined state and make arr[mid-1] or arr[mid] is out of range
int mid = partition(arr, first, last);

Please return the value from function partition.

A: The segmentation fault is in the following lines:
  tmp = arr[i];
  arr[i] = arr[j];
  arr[j] = tmp;

You are sending array elements to swap( as i and j) and using them as indices, obviously these lines will cause seg fault as these addresses may be out of bounds and system reserved.
As told by @Loc the 'partition' function should return the mid value's index, also you forgot to swap the pivot. There are some other minor corrections. I have included the corrected code:
#include <stdio.h>

void swap(int arr[], int i, int j){
        int tmp;
        tmp = arr[i];
        arr[i] = arr[j];
        arr[j] = tmp;
}

int partition(int arr[], int first, int last){
        int pivot = arr[last];
        int p=last;
        last--;
        while(first <= last){
                while(arr[first] < pivot){
                        first++;
                }
                while(arr[last] > pivot){
                        last--;
                }
                if(first <= last){
                        swap(arr, first, last);
                        first++;
                        last--;
                }
        }
        swap(arr, first, p);
        return first;
}

void quickSortR(int arr[], int first, int last){
        if(last <= first) return;
        int mid = partition(arr, first, last);
        quickSortR(arr, first, mid-1);
        quickSortR(arr, mid+1, last);
}

void main() {
        int arr[14] = {488888, 3, 5, 0, 23, 12124, 6, 7, 2, 1121, 0, 92, 5, 8};
        int i;
        quickSortR(arr, 0, 13);
        for (i = 0; i<14; i++) {
                printf("arr[%d] = %d\n", i, arr[i]);
        }
}


text:
Q: Scrum is methodology or framework? I am confuse about scrum .it is methodology or Framework?.
I want to use scrum for development but i want to develop scrum tool but i am confuse scrum is methodology or framework?

A: Sources such as Scrum.org, Scrum Alliance, and even Wikipedia do refer to Scrum as a framework. Something to consider, though, is that Scrum is at the project management level, not at the product development level. It defines activities and artifacts to run a project and manage work, without any specifics as to how to go about designing, building, and testing software - those pieces will need to come from something else, although there are many common characteristics of the Agile methodologies.
However, although many sources call Scrum a framework, a purist would say that if you aren't doing everything that Scrum calls for, you aren't doing Scrum. That would imply that it's more of a methodology, a complete package that's meant to be used as-is (see ScrumBut for more on this). However, in reality, there are very few process methodologies that will work for everyone as-is, and some level of tailoring or adjustment is needed.


text:
Q: Почему Git оставляет старые названия папок после их переименований? Ситуация такая, есть ветка dev и вот такая структура проекта
MyProj/Foo/MyFile.java

Я делаю из нее другую ветку dev -> dev_test_first и добавляю в эту директорию еще несколько файлов
MyProj/Foo/MyFile.java
MyProj/Foo/MyFile2.java
MyProj/Foo/MyFile3.java

Делаю commit тут же.
Теперь делаем еще одну ветку из dev -> dev_test_second меняю название папки, удаляю MyFile.java и добавляю еще файл MyFile4
Получилось вот так
MyProj/Boo/MyFile.java <- !! DELETED !!

MyProj/Boo/MyFile4.java

Делаю commit и merge с dev веткой и push в origin.
Теперь из ветки dev_test_first делаю pull origin dev
и я ожидаю, что структура моего проекта будет иметь во первых переименованую дерикторию, а во вторых я получу дополнительный файл MyFile4 который был создан на ветке dev_test_second
ОЖИДАНИЕ
MyProj/Boo/MyFile.java
MyProj/Boo/MyFile2.java
MyProj/Boo/MyFile3.java
MyProj/Boo/MyFile4.java

но вместо этого получается вот так
РЕАЛЬНОСТЬ
MyProj/Foo/MyFile.java
MyProj/Foo/MyFile2.java
MyProj/Foo/MyFile3.java
MyProj/Boo/MyFile4.java

Почему так получается?
Правка
При чем если посмотреть на такую ситуацию, допустим в ветке dev_test_second мы не будем добавлять никакие файлы, а просто переименуем папку и все. То когда будем сливать эти ветки, то мы получим просто переименованую директорию. Но почему тогда когда мы переименовываем и + добавляем дополнительные файлы, то гит как бы создает новую дирикторию?

A: Так получается по той причине, что git в принципе не отслеживает папки, он следит только за файлами.
А ещё git не отслеживает переименования.
То есть второй коммит с точки зрения git выглядит вот так:
удален MyProj/Foo/MyFile.java
создан MyProj/Boo/MyFile.java
создан MyProj/Boo/MyFile4.java

Соответственно, когда вы сливаете этот коммит с первым, то все файлы сливаются независимо. Файл MyProj/Foo/MyFile.java при этом оказывается в состоянии конфликта (изменён+удалён).


text:
Q: How to create a custom Matrix? I have 2 matrices(yellow color) as follows:
matrix 1 (size of 4x1) and matrix 2 (size of 1x6),
I am allowed to use matrix unit,matrix inverse, transpose matrix function ,square matrix also [multiplication, addition and subtraction,..calculation] from 2 above matrix
Edit: the numbers 1 in the 4x6 matrix are not necessarily = 1, as long as they are nonzero
my question is: how do I create a 4x6 matrix as in the image?
Actually, I find it quite similar to the diagonal matrix but I'm still stuck because I couldn't find the connection to deploy them!
Please give me a solution. Thanks very much!

Here's other types:

A: If the input vectors are X and Y, it looks like the output matrix Z is:
 Z(i,j)  =  1 when X(i)=Y(j)
            0 otherwise

If you have an element-wise comparison function, you can do this process. First multiply your vectors with a vector of ones, to produce matrices that have the rows or columns repeated.
1                      1 1 1 1 1 1
1  * [1 1 1 1 1 1]  =  1 1 1 1 1 1
2                      2 2 2 2 2 2
2                      2 2 2 2 2 2

1                      1 1 1 2 2 2
1  * [1 1 1 2 2 2]  =  1 1 1 2 2 2
1                      1 1 1 2 2 2
1                      1 1 1 2 2 2

An element-wise comparison of these two gives you the result you want.
1 1 1 1 1 1      1 1 1 2 2 2     1 1 1 0 0 0
1 1 1 1 1 1  ==  1 1 1 2 2 2  =  1 1 1 0 0 0
2 2 2 2 2 2      1 1 1 2 2 2     0 0 0 1 1 1
2 2 2 2 2 2      1 1 1 2 2 2     0 0 0 1 1 1


text:
Q: PHP Mailer sends duplicates I have a problem that my current php send duplicate emails using PHPMailer. The php file is to be run by a cronjob, but for we just run it manually.
I tried $mail->ClearAddresses(); but that didn't seem to help.
When we vardump $mail; but it looks like it is only sent once, and our "Message has been sent" message is only being printed once pr email adress in our database.
We also tried select distinct which was suggested in another thread, but it seemed to have no effect.
We also tried adding a counter to different places of the script, but it displayed the correct number of iterations.
<?php
    ini_set("allow_url_fopen", 1);
    include '/home/actiorwd/include/dbinfo.php';

    $counter =0;

    $servername = "localhost";
    $dbname = "actiorwd_websec";

    // Create connection
    $conn = new mysqli($servername, $user, $passw, $dbname);
    // Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }

    $sql = "SELECT DISTINCT * FROM users";
    $result = $conn->query($sql);
    $ch = curl_init();

    if ($result->num_rows > 0) {
        // output data of each row

        while($row = $result->fetch_assoc()) {
            $url = 'https://haveibeenpwned.com/api/v2/breachedaccount/';
            $url.= $row["email"];

            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch,CURLOPT_USERAGENT,'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13');
            curl_setopt($ch, CURLOPT_URL, $url);
            $results = curl_exec($ch);

            $obj = json_decode($results, TRUE);

            $newbreaches = count($obj);

            //run if new breaches are found
            if($row["breaches"]!==$newbreaches){

              require_once('/home/actiorwd/public_html/PHPMailer/PHPMailerAutoload.php');
              $mail = new PHPMailer;
              $mail->isSMTP();                                      // Set mailer to use SMTP
              $mail->Host = 'cpanel40.proisp.no';  // Specify main and backup SMTP servers
              $mail->SMTPAuth = true;                               // Enable SMTP authentication
              $mail->Username = 'breached@actionscript.no';                 // SMTP username
              $mail->Password = 'PASSWORDHERE';                           // SMTP password
              $mail->SMTPSecure = 'ssl';                            // Enable TLS encryption, `ssl` also accepted
              $mail->Port = 465;                                    // TCP port to connect to
              $mail->setFrom('breached@actionscript.no', 'WebSec');
              $mail->ClearAddresses();
              $mail->addAddress($row["email"]);     // Add a recipient
              $mail->addReplyTo('breached@actionscript.no', 'WebSec');
              $mail->isHTML(true);                                  // Set email format to HTML
              $mail->Subject = 'Breached!!!!';
              $mail->Body    = 'Someone hacked your account, there are: '.$newbreaches."breaches";
              $mail->AltBody = 'Someone hacked your account in plain text';
              $mail->send();

              if(!$mail->send()) {
                  echo 'Message could not be sent.
';
                  echo 'Mailer Error: ' . $mail->ErrorInfo . '
';
              } else {
                  echo 'Message has been sent
';
                  $counter++;
              }

              $updatebreach = "INSERT INTO users (`email`, `breaches`) VALUES ('$usermail', '$newbreaches') ON DUPLICATE KEY UPDATE `breaches` = '$newbreaches' ";
              //echo $updatebreach;

              if ($conn->query($updatebreach) === TRUE) {
                  echo "New record created successfully
";
              } else {
                  echo "Error: " . $updatebreach . "
" . $conn->error;
              }

            }

            sleep(2);
        }
    } else {
        echo "0 results";
    }
    curl_close($ch);
    echo $counter;

    $conn->close();
    ?>

A: You are calling $mail->send() twice:
$mail->send();

if(!$mail->send()) { // <--- Here you're actually sending it again.
  echo 'Message could not be sent.
';
  echo 'Mailer Error: ' . $mail->ErrorInfo . '
';
} else {
  echo 'Message has been sent
';
  $counter++;
}

You should store the result of the first send instead like this:
// Store the status in a variable instead
$sent = $mail->send();

if(!$sent) { // Check the result of the variable instead of sending it again
  echo 'Message could not be sent.
';
  echo 'Mailer Error: ' . $mail->ErrorInfo . '
';
} else {
  echo 'Message has been sent
';
  $counter++;
}


text:
Q: low_memory parameter in read_csv function What does the low_memory parameter do in the read_csv function from the pandas library?

A: This come from the docs themselves. Have you read them?

low_memory : boolean, default True
      Internally process the file in chunks, resulting in lower memory use
      while parsing, but possibly mixed type inference.  To ensure no mixed
      types either set False, or specify the type with the dtype parameter.
      Note that the entire file is read into a single DataFrame regardless,
      use the chunksize or iterator parameter to return the data in chunks.
      (Only valid with C parser)


text:
Q: I'm using a social login plugin called miniOrange, but I can't get Twitter meta information The following plugin is used to enable social login, allowing you to log in to Wordpress via Twitter.
https://plugins.miniorange.com/wordpress
And the following code is trying to get the metadata of the Twitter access of the logged in user.
<?
require_once('../wp-load.php');
require_once("codebird.php");

\Codebird\Codebird::setConsumerKey("XXXXXXXXXXXX", "XXXXXXXXXXXXXXXXXXX");
$cb = \Codebird\Codebird::getInstance();

$current_user = wp_get_current_user();
$wp_user_id = $current_user->ID;
$user_info = get_userdata($wp_user_id);
$twitter_id = get_user_meta($wp_user_id, "twitter_id", true);
$access_token = get_user_meta($wp_user_id, "twitter_access_token", true);
$access_token_secret = get_user_meta($wp_user_id, "twitter_access_token_secret", true);

$cb->setToken($access_token, $access_token_secret);

$media_id = $cb->media_upload(array(
  "media" => $_FILES["image"]["tmp_name"]
))->media_id_string;

$params = array(
  "status" => $_POST["text"],
  "media_ids" => $media_id
);
$result = $cb->statuses_update($params);

echo $twitter_id, $access_token, $access_token_secret;

However, the ECHO result is empty.
How can I get the Twitter secret access token and other information of the logged in user?
English may be inaccurate due to the use of a translation site. Please understand.


text:
Q: rock combo -- what does that mean?
The background-attachment property is little used, but very effective. On the web site for top rock combo Dirty Pretty Things (www.dirtyprettythingsband.com), a fixed background image was declared in the body selector, ensuring the background image stayed stationary while the main container and everything inside it scrolled as would be expected (see Figure 5-19).

I suppose the word top in that phrase means something like the best but what exactly does rock combo mean?

A: Colloquial term for a rock band/group, I would imagine.


text:
Q: Excel VBA - Select Case ends select after finding one case true and doesn't complete other cases I created a loop that would check the length of columns and column types.  But once it finds a case to be true it ends the select instead of going to the next case (column) where there could be an additional error.
'(6.1) Create loop to check for format and length errors
           xRowCount = 1
           xFormatErrorCount = 0
       For i = 0 To xNumOfRows - 1

       xColA = Cells(xRowCount, 1).Value
       xColB = Cells(xRowCount, 2).Value
       xColC = Cells(xRowCount, 3).Value
       xColD = Cells(xRowCount, 4).Value
       xColE = Cells(xRowCount, 5).Value
       xColF = Cells(xRowCount, 6).Value
       xColG = Cells(xRowCount, 7).Value
       xColH = Cells(xRowCount, 8).Value
       xColI = Cells(xRowCount, 9).Value
       xColJ = Cells(xRowCount, 10).Value
       xColK = Cells(xRowCount, 11).Value
       xColL = Cells(xRowCount, 12).Value
       xColM = Cells(xRowCount, 13).Value

       Select Case True

        Case Len(xColA) > 2 'Check if length is greater than 2
         Cells(xRowCount, 1).Interior.Color = RGB(255, 0, 0)
         xFormatErrorCount = xFormatErrorCount + 1

        Case Len(xColB) > 5 'Check if length is greater than 5
         Cells(xRowCount, 2).Interior.Color = RGB(255, 0, 0)
         xFormatErrorCount = xFormatErrorCount + 1

        Case Len(xColC) > 5, Cells(xRowCount, 3).NumberFormat <> "0" 'Check if length is greater than 5 and format is number
         Cells(xRowCount, 3).Interior.Color = RGB(255, 0, 0)
         xFormatErrorCount = xFormatErrorCount + 1

        Case Len(xColD) > 18, Cells(xRowCount, 4).NumberFormat <> "0"  'Check if length is greater than 18 and format is number
         Cells(xRowCount, 4).Interior.Color = RGB(255, 0, 0)
         xFormatErrorCount = xFormatErrorCount + 1

        Case Len(xColE) > 11, Cells(xRowCount, 5).NumberFormat <> "0"  'Check if length is greater than 11 and format is number
         Cells(xRowCount, 5).Interior.Color = RGB(255, 0, 0)
         xFormatErrorCount = xFormatErrorCount + 1

        Case Cells(xRowCount, 6).NumberFormat <> "0"  'Check if format is number
         Cells(xRowCount, 6).Interior.Color = RGB(255, 0, 0)
         xFormatErrorCount = xFormatErrorCount + 1

        Case Cells(xRowCount, 7).NumberFormat <> "0"  'Check if #
         Cells(xRowCount, 7).Interior.Color = RGB(255, 0, 0)
         xFormatErrorCount = xFormatErrorCount + 1

        Case Cells(xRowCount, 8).NumberFormat <> "0"  'Check if #
        Cells(xRowCount, 8).Interior.Color = RGB(255, 0, 0)
         xFormatErrorCount = xFormatErrorCount + 1

        Case Cells(xRowCount, 9).NumberFormat <> "0"  'Check if #
         Cells(xRowCount, 9).Interior.Color = RGB(255, 0, 0)
         xFormatErrorCount = xFormatErrorCount + 1

        Case Cells(xRowCount, 10).NumberFormat <> "0.00"  'Check if #
         Cells(xRowCount, 10).Interior.Color = RGB(255, 0, 0)
         xFormatErrorCount = xFormatErrorCount + 1

        Case Len(xColK) > 1 'Check if length is greater than 1
         Cells(xRowCount, 11).Interior.Color = RGB(255, 0, 0)
         xFormatErrorCount = xFormatErrorCount + 1

        Case Len(xColL) > 1  'Check if length is greater than 1
         Cells(xRowCount, 12).Interior.Color = RGB(255, 0, 0)
         xFormatErrorCount = xFormatErrorCount + 1

        Case Len(xColM) > 1  'Check if length is greater than 1
         Cells(xRowCount, 13).Interior.Color = RGB(255, 0, 0)
         xFormatErrorCount = xFormatErrorCount + 1

       End Select
        xRowCount = xRowCount + 1

Next

A: This is how VB select case works.
If you want to have multiple cases that execute the same block, you put them in the same case and delimit them with commas, like this:
Public Sub TestX(ByVal x As Long)

    Select Case x
        Case 1, 2
            Debug.Print "x is One or Two"
        Case 3
            Debug.Print "x is Three"
        Case Else
            Debug.Print ; "is something else"
    End Select

End Sub

A: It looks to me as though you don't want Select Case, which is designed to behave the way you describe, at all but rather a series of separate If statements:
Dim n                           As Long

If Len(xColA) > 2 Then    'Check if length is greater than 2
    Cells(xRowCount, 1).Interior.Color = RGB(255, 0, 0)
    xFormatErrorCount = xFormatErrorCount + 1
End If
If Len(xColB) > 5 Then    'Check if length is greater than 5
    Cells(xRowCount, 2).Interior.Color = RGB(255, 0, 0)
    xFormatErrorCount = xFormatErrorCount + 1
End If
If Len(xColC) > 5 Or Cells(xRowCount, 3).NumberFormat <> "0" Then    'Check if length is greater than 5 and format is number
    Cells(xRowCount, 3).Interior.Color = RGB(255, 0, 0)
    xFormatErrorCount = xFormatErrorCount + 1
End If
If Len(xColD) > 18 Or Cells(xRowCount, 4).NumberFormat <> "0" Then  'Check if length is greater than 18 and format is number
    Cells(xRowCount, 4).Interior.Color = RGB(255, 0, 0)
    xFormatErrorCount = xFormatErrorCount + 1
End If
If Len(xColE) > 11 Or Cells(xRowCount, 5).NumberFormat <> "0" Then  'Check if length is greater than 11 and format is number
    Cells(xRowCount, 5).Interior.Color = RGB(255, 0, 0)
    xFormatErrorCount = xFormatErrorCount + 1
End If
For n = 6 To 9
    If Cells(xRowCount, n).NumberFormat <> "0" Then    'Check if format is number
        Cells(xRowCount, n).Interior.Color = RGB(255, 0, 0)
        xFormatErrorCount = xFormatErrorCount + 1
    End If
Next n
If Cells(xRowCount, 10).NumberFormat <> "0.00" Then    'Check if #
    Cells(xRowCount, 10).Interior.Color = RGB(255, 0, 0)
    xFormatErrorCount = xFormatErrorCount + 1
End If
If Len(xColK) > 1 Then    'Check if length is greater than 1
    Cells(xRowCount, 11).Interior.Color = RGB(255, 0, 0)
    xFormatErrorCount = xFormatErrorCount + 1
End If
If Len(xColL) > 1 Then    'Check if length is greater than 1
    Cells(xRowCount, 12).Interior.Color = RGB(255, 0, 0)
    xFormatErrorCount = xFormatErrorCount + 1
End If
If Len(xColM) > 1 Then  'Check if length is greater than 1
    Cells(xRowCount, 13).Interior.Color = RGB(255, 0, 0)
    xFormatErrorCount = xFormatErrorCount + 1
End If

I think you could probably streamline this more using arrays.


text:
Q: how to program alerts and warning messages using c#.net how to program alerts and warning messages using c#.net

A: In web? Try this:
string textForMessage = @"<script language='javascript'> alert('test\ntest\ntest\ntest');</script>";
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "UserPopup", textForMessage);

Output

Got it here


text:
Q: FullCalendar v4 - time display options I have different eventTimeFormats displaying in different views, e..
{hour: '2-digit', minute: '2-digit'}

in timeGridDay view, but I don't want any eventTimeFormat to show in dayGridMonth view. Is this possible?

A: You can use use displayEventTime to disable the time:
displayEventTime: false

This can be applied to every view, or to specific views via that view's options.


text:
Q: SQL statement is taking long I've been running into this problem for quite a while now. I want to grab all the rows from table sentences, that are not present in another table (with some conditions).
I've already managed to make this work but the query is taking 2-3 seconds. I want to make this faster, but since I am not familiar with SQL I can't manage to get it working.
The particular query is:
/**
* Only find sentences that are allowed to say back.
* 1. WHERE NOT EXISTS sentences said by this bot said in the past 2 weeks
* 2. WHERE NOT EXISTS sentences said in the last 8 minutes
* 3. WHERE NOT EXISTS sentences said to this customer
* 4. WHERE EXIST sentences with [$translation] translation
*/
 select * from `sentences` where `keyword_id` = 396
and not exists (select id from `customer_sentences` where sentences.id = customer_sentences.sentence_id and customer_sentences.bot_id = 1 and customer_sentences.created_at >= "2019-12-30 13:25:58")
and not exists (select id from `customer_sentences` where sentences.id = customer_sentences.sentence_id and customer_sentences.created_at >= "2020-01-13 13:17:58")
and not exists (select id from `customer_sentences` where sentences.id = customer_sentences.sentence_id and customer_sentences.customer_id = 153375)
and exists (select id from `sentence_translations` where sentence_translations.sentence_id = sentences.id and sentence_translations.language_id = 1)

By removing every statement one by one, I've found out the below where not exist statement is slow:
and not exists (select id from `customer_sentences` where sentences.id = customer_sentences.sentence_id and customer_sentences.created_at >= "2020-01-13 13:17:58")

I've managed to improve the speed from 30s to 2-3s by creating indexes on my customer_sentences table:
$table->index(['created_at', 'bot_id']);
$table->index(['bot_id']);
$table->index(['customer_id']);
$table->index(['bot_id', 'created_at', 'sentence_id']);

I read about using a left join instead of the where not exists statement, but I weren't be able to get this working.

A: Correlated subqueries can be inefficient.
You want to use LEFT JOIN together with the condition that some mandatory (NOT NULL) column in the right table IS NULL.
Try this:
SELECT
*
FROM sentences AS s
LEFT JOIN customer_sentences AS cs ON s.id = cs.sentence_id AND cs.bot_id = a AND cs.created_at >= '2019-12-30 13:25:58'
LEFT JOIN customer_sentences AS cs2 ON s.id = cs2.sentence_id AND cs.created_at >= '2020-01-13 13:17:58'
LEFT JOIN customer_sentences AS cs3 ON s.id = cs3.sentence_id AND cs.customer_id = 153375
JOIN sentence_translations AS st ON s.id = st.sentence_id AND st.language_id = 1
WHERE cs.id IS NULL
AND cs2.id IS NULL
AND cs3.id IS NULL

I also noticed that your indexes are inefficient. Fixing those should have a bigger impact than optimizing the query. Your first subquery will use the compound index on ['bot_id', 'created_at', 'sentence_id']. The second subquery will only use the created_at part of ['created_at', 'bot_id']. Your third subquery will use the ['customer_id'] index. Your forth subquery will probably not use any index. Maybe it's a tiny table or you have indexes on that table as well, which you did not include in the question.
If you create a compound index in customer_sentences consisting of first sentence_id followed by created_at, it can be used by all subqueries (or joins) on that table. The subquery missing created_at will still be able to use the first part of this new index. It may be better to only index the sentence_id column. Your existing indexes should probably be removed. Indexes increase the time it takes to write to the table as each write will also need to update all indexes. They also increase the size on disk of your table as well as possibly memory consumption.
You should probably also create an index in sentence_translations on sentence_id.

A: For this clause (which is equivalent to yours):
not exists (select 1
            from customer_sentences cs
            where sentences.id = cs.sentence_id and
                  cs.created_at >= '2020-01-13 13:17:58'
           )

You want an index on customer_sentences(sentence_id, created_at).  The ordering is important, and you want both keys.


text:
Q: Very slow mob spawns in SMP mob farm on modded server I run a very small SMP server running Forge 1.12 hosted through MCProHosting.
I have a very few mods installed: StorageDrawers, WAILA and JEI.
I built the mob farm in this video.

The spawn rates are REALLY low, only a couple mobs in over 10 minutes.  I've done a lot of research but can't find any useful information.  I'm looking for advice on how to make this thing work.  I've read that for various reasons, mob farms are just much worse on SMP.  Here's some useful information:

*

*I wait for spawns between 24 and 128 blocks from the spawning areas.

*I turned the server's render distance to 10.  Helped a LITTLE bit.

*I used the fill command to ensure NO unlit caves are within a 128 block radius

*The server is on the Hard difficulty

*The spawn rate is very low even when I'm alone on the server.

Any help is appreciated.
Thanks!
Edit
I downloaded the world and tested the trap in single player.  To my surprise, it didn't work!!  That's kind of good news.  That means maybe it's possible to have this work on the server once I figure out what's wrong with it.

A: I have recreated this spawner on a test world.  I initially built it on a spigot server.  I played it as single player and also loaded it in a vanilla server.  The spawn rates were substantial all 3 ways.
I can't speak to the possibility that your mods could be causing the issue you are facing though.
Note: A few times, the redstone circuits glitched.  I had the clock at the top freeze which caused the water to just stay out which killed spawning.  I also had the elevator circuit freeze which caused the items to back up into the hoppers and never come up to the surface.  In these cases, the circuits had to be manually reset.
To force the mobs to spawn only on the intended platforms, I filled in most caves and lit the surface for 128 blocks in all directions.  You said you filled the caves, if you have not lit the surface, I recommend it.  Before I lit the surface, the spawn rate was a bit lower.

I took this screenshot when it was running on the vanilla server.  As you can see, every time the water turns off, several mobs spawn.  To get this picture, I used a hacked client with mobESP and freecam.  MobESP highlights the mobs and freecam allowed the screenshot to be taken from underground like this.

View edit below before downloading this version
I uploaded this world to mediafire.  It is named Spawner.zip and it is 5.52MB.  It can be downloaded here.  I recommend you download it and run it temporarily on your server to see if your mods are causing the problem or if it is something else.

Edit:
I recreated this in an empty world out of glass for a smaller world size and a way to view it.  You can see the item stream headed up on the left side of the image.

Download this world here.  It is named Spawner2.zip and is 330.13KB.  Use this temporarily, just to test if the spawner design will work on your server.  To note, the spawner works best at night.  Use /time set night when testing as I left the day cycle functioning.

A: I think I know what you're problem is. You used the fill command to fill caves, but you also filled the mob farm, even just a little bit, and now less things are spawning.
Also, I never saw you put water down. If you did than it's not a problem, but if you didn't it might help.
Also, another player may be stealing your spawns. Make sure nobody else has a mob farm nearby.

A: There are lots of things that Minecraft checks for before spawning mobs. Hostile mobs, however, really only need two requirements:

*

*If a mob spawns, the block that it is standing on must be opaque (solid, like stone or grass) and the two blocks above it must be transparent, like glass or leaves. Air will count as a transparent block.

*The light level of the block must be seven or lower (unless a thunderstorm is happening). Sunlight falling on the block will decrease the chances of the mob spawning by up to 50%.

Make sure both these points are met, or else your mobs will not spawn. Also, try to be withing 32 blocks of the mob farm, because mobs will be guranteed to spawn. Anything past that can be risky.
If there's a mob with no player within 32 blocks of it, the mob will despawn in about a minute.
In addition, here's some tips:

*

*Build a village, so large packs of zombies may be able to spawn.

*Make the area the mobs can spawn in as dark as possible.

*Spiders can spawn in mob farms and block 1x1 wide channels. In other words, place barriers to create 2x2 squares to minimize the chances of them spawning.

I hope this solved your problem. If not, it's probably the fault of the server. The server.properties file should have these values set:
view-distance=10
spawn-monsters=true


text:
Q: BSOD while playing a sound resource I have a VB.NET application that crashes on a client's computer with a BSOD error... KERNEL_DATA_INPAGE_ERROR.
This error occurs at a point where my program does two things:

*

*Locks the computer

*Plays a sound in BackgroundLoop mode

For locking the work station, I am just using this:
<DllImport("user32")> _
Public Shared Sub LockWorkStation()
End Sub

For playing the sound, I am doing this:
My.Computer.Audio.Play(My.Resources.ResourceManager.GetStream("somesound"), AudioPlayMode.BackgroundLoop)

Now, this sound loops until the user logs back in.  My software detects the session state switch and stops playing the sound.  Sometimes when I log back in, the sound card plays garbage data for a split second, instead of the rest of the audio buffer.  I get the impression that this has something to do with session switching.
Could my client be having an issue where there is memory corruption occurring at the point of locking the computer?
I apologize for the vagueness of this post... I am not sure where to begin as I cannot reproduce the problem myself.
Edit:  If the sound is left to play on its own, even without locking the computer, eventually the computer will lock up and then bluescreen.  Playing the sound while locking at the same causes it to happen sooner.
Edit #2:  So I've seen it fail now.  The sound loop starts playing correctly but quickly switches to looping of garbage data.  It's as if it is just reading a random location in memory and looping that.  Very strange behavior!
Solved!: It was hardware all along afterall.  Apparently this particular model of laptop has a problem where the speaker is installed right on top of the hard drive.  When playing sounds loudly, it creates all sorts of problems.

A: A blue screen is almost certainly related to defective hardware or drivers. Softwarewise, there's really not much you can do about this apart from putting together a workaround.
You can perform a memory dump and try to determine what specifically went wrong, or with some clever debugging see where it bombs out in order to try to avoid it.
Otherwise, you're probably talking about doing some maintenance work on the machine in question.


text:
Q: How to perform nested anova by groups using R I have several samples which were measured twice daily for 20 days in the format:
sample, concentration, day, replicate

How do I get the nested anova for each sample using the below function?
nest <- aov(concentration ~ day / factor(replicate))

How would I run a nested anova for each "plant_type" without creating 8 subsets?

A: If I understood correctly, this example might help you
Libraries
library(tidyverse)
library(broom)

Example
Code
mtcars %>%
  # Create 2 factors variables
  mutate(
    gear = as.factor(gear),
    cyl = as.factor(cyl)
    ) %>%
  # Group and nest data by each level of gear
  group_nest(gear) %>%
  mutate(
    # Apply ANOVA por each level of gear, for drat~cyl
    anova = map(.x = data,.f = ~anova(aov(drat~cyl,data = .x))),
    # Get results of ANOVA
    results = map(anova,tidy)
    ) %>%
  # "Show" the results for each gear level
  unnest(results)

Output
# A tibble: 6 x 9
  gear                 data anova           term         df sumsq meansq statistic p.value
  <fct> <list<tibble[,10]>> <list>          <chr>     <int> <dbl>  <dbl>     <dbl>   <dbl>
1 3               [15 x 10] <anova [2 x 5]> cyl           2 0.414 0.207      3.91   0.0491
2 3               [15 x 10] <anova [2 x 5]> Residuals    12 0.634 0.0529    NA     NA
3 4               [12 x 10] <anova [2 x 5]> cyl           1 0.107 0.107      1.10   0.318
4 4               [12 x 10] <anova [2 x 5]> Residuals    10 0.967 0.0967    NA     NA
5 5                [5 x 10] <anova [2 x 5]> cyl           2 0.158 0.0790     0.352  0.740
6 5                [5 x 10] <anova [2 x 5]> Residuals     2 0.449 0.225     NA     NA


text:
Q: What is the meaning of this below code? I am just beginner I am having problem with understanding the below code
@Component({
  selector: 'app-heroes',
   templateUrl: './heroes.component.html',
   styleUrls: ['./heroes.component.css']
})
export class HeroesComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

}

My doubts is, What we are doing in export clss HeroesComponent section? and what are OnInit,constructor and ngOnInit?

A: Constructor, ngOnInit both are nothing but methods inside a class.
In general, constructor method will be called when ever instance of the class( i.e. component here) is created whereas ngOnInit will be called after DOM is created for the component.
More details,
Angular bootstrap process consists of the two major stages:

*

*constructing components tree

*running change detection

The constructor of the component is called when Angular constructs components tree.
All life cycle hooks including ngOnInit are called as part of the change detection phase.
Uses:
Constructor is mostly used for dependency injection and any initialization with respect to the component are initialized in ngOnInit. In order to use ngOnInit method we need to implement OnInit interface from angular library.

A: From your question, I derive that you are new to Angular community.
OnInit is an interface.
In the typings file lifecycle_hooks.d.ts it is defined as

export interface OnInit {
      ngOnInit(): void; }

It's use ->  Lifecycle hook that is called after data-bound properties of directives and components are initialized.(or just before initialization, if you want to do some task, you write in this ngOnInit() {
  } method)
One thing to note is (might not be very useful in your case) is the parents OnInit is called before it's child. Also it is invoked only once when the
 * directive is instantiated.
constructor() is a method which will be called when Angular creates an object of your class.
Just like OnInit there are multiple lifecycle hooks.The way you use it is just like OnInit -> implement the interface and define the method, and you can write down any code that you want to run at that life cycle stage of component.
Below is the order in which these hooks are called.

Do mark it as resolved if I was able to solve your problem.


text:
Q: Can we do left padding to a JPA criteria expression? I have a primary key column like colId which has values like 70 71 etc.
Now I want to have a JPA Criteria expression to return it like 0070 0071 etc.
How can we do that in JPA Criteria Expression.
Expression<String> colId = root.get("colId").as(String.class);

Now is there anything to leftpad this expression?

A: You could use the criteria builder 'function' expression which creates an expression to execute a database function. Postgres and MySQL have an 'LPAD' function which could be used in this case. I am still setting up a test case for this, but I have the following:
Expression<String>[] args = new Expression[3];

args[0] = root.get("id_column_name").as(String.class);
args[1] = criteriaBuilder.literal("5");
args[2] = criteriaBuilder.literal("0");

Expression<String> expressionToGetPaddedId =
    criteriaBuilder.function("LPAD", String.class, args);

For reference:

*

*https://www.logicbig.com/tutorials/java-ee-tutorial/jpa/criteria-api-calling-database-function.html

Update:
Using a quick test case, I found that my second argument was incorrectly typed. Here is the 'toPredicate' overridden method from my spec:
    @Override
    public Predicate toPredicate(@NonNull Root<T> root,
                                 @NonNull CriteriaQuery<?> criteriaQuery,
                                 @NonNull CriteriaBuilder criteriaBuilder) {

        Expression<String> eTaskID = root.get("id").as(String.class);
        Expression<Integer> length = criteriaBuilder.literal(4);
        Expression<String> fillText = criteriaBuilder.literal("0");

        Expression<String> expressionToGetPaddedId = criteriaBuilder.function(
                "LPAD",
                String.class,
                eTaskID, length, fillText);

        return criteriaBuilder.like(expressionToGetPaddedId, "0001");
    }

and the resulting sql is:
Hibernate:
    select
        dataset0_.id as id1_2_,
        dataset0_.created_at as created_2_2_,
        dataset0_.is_deleted as is_delet3_2_,
        dataset0_.model as model4_2_,
        dataset0_.name as name5_2_,
        dataset0_.organization as organiza6_2_,
        dataset0_.properties as properti7_2_,
        dataset0_.type as type8_2_,
        dataset0_.updated_at as updated_9_2_
    from
        datasets dataset0_
    where
        LPAD(cast(dataset0_.id as varchar(255)), 4, ?) like ?

The test case runs fine. Looks good, right?


text:
Q: Facebook Socialite get user from token and secret In laravel docs there is a part about getting user from using ->userFromTokenAndSecret however it seems to be not working with facebook and returns an error that this method doesn't exist.
How do I get the user by token and secret?
I'm using Laravel as API so that it works stateless and I don't use any redirects.
I sign in using Angular app and send token then. I need to process that.

A: I've found an answer to my questions and it is userFromToken. What is the idea:
1) I authorize my user on Angular 6 using ngx-social-login
2) I receive user data from Facebook
3) I send authToken to the API
4) I receive user data from Facebook on my backend API using Socialite::driver('facebook')->stateless()->userFromToken($token)
5) Do any stuff what I want. In my case I save data to DB or retrieve user if exists and then create a token for that user using JWT and return it

A: I also got problem but not facebook. I use twitter api with this plugin.
https://github.com/thujohn/twitter
I use socialite after get token from twitter plugin.
This is full that i was try to get token.
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Log;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Session;
use App\Repositories\UserRepository;
use Twitter;
use Redirect;
use Hash;
use App\User;
use Socialite;
use Auth;

class SocialController extends Controller
{
    function login() {
        // your SIGN IN WITH TWITTER  button should point to this route
        $sign_in_twitter = true;
        $force_login = false;

        // Make sure we make this request w/o tokens, overwrite the default values in case of login.
        Twitter::reconfig(['token' => '', 'secret' => '']);
        $token = Twitter::getRequestToken(route('twitter.callback'));

        if (isset($token['oauth_token_secret']))
        {
            $url = Twitter::getAuthorizeURL($token, $sign_in_twitter, $force_login);

            Session::put('oauth_state', 'start');
            Session::put('oauth_request_token', $token['oauth_token']);
            Session::put('oauth_request_token_secret', $token['oauth_token_secret']);

            return Redirect::to($url);
        }

        return Redirect::route('twitter.error');
    }

    function callback() {
        Log::info('callbackk call');
        // You should set this route on your Twitter Application settings as the callback
        // https://apps.twitter.com/app/YOUR-APP-ID/settings
        if (Session::has('oauth_request_token'))
        {
            $request_token = [
                'token'  => Session::get('oauth_request_token'),
                'secret' => Session::get('oauth_request_token_secret'),
            ];

            Twitter::reconfig($request_token);

            $oauth_verifier = false;

            if (Input::has('oauth_verifier'))
            {
                $oauth_verifier = Input::get('oauth_verifier');
                // getAccessToken() will reset the token for you
                $token = Twitter::getAccessToken($oauth_verifier);
                Log::info('token created: ' . print_r($token,true));
            }

            if (!isset($token['oauth_token_secret']))
            {
                Log::info('oauth_token_secret fail');
                return Redirect::route('twitter.error')->with('flash_error', 'We could not log you in on Twitter.');
            }

            $credentials = Twitter::getCredentials([
                'include_email' => 'true',
            ]);

            if (is_object($credentials) && !isset($credentials->error))
            {
                // $credentials contains the Twitter user object with all the info about the user.
                // Add here your own user logic, store profiles, create new users on your tables...you name it!
                // Typically you'll want to store at least, user id, name and access tokens
                // if you want to be able to call the API on behalf of your users.

                // This is also the moment to log in your users if you're using Laravel's Auth class
                // Auth::login($user) should do the trick.

                Session::put('access_token', $token);
                Log::info('access_token: ' . print_r($token,true));

                $users = Twitter::getUsers([
                    'user_id'=>$token['user_id']
                ]);

                Log::info('users: ' . print_r($users,true));
                if(count($users) > 0) {

                    // pakai socialite untuk mengambil email
                    $user = Socialite::driver('twitter')->userFromTokenAndSecret($token['oauth_token'], $token['oauth_token_secret']);
                    $user_email = $user->getEmail();
                    $user_name = $user->getName();

                    if($user_email) {
                        $this->_set_login($user_name, $user_email);
                        Log::info("email sets");
                    } else {
                        Log::info("email not sets and go with id provider");
                    }

                } else {
                    Log::info("users not found");
                }

                return Redirect::to('/')->with('flash_notice', 'Congrats! You\'ve successfully signed in!');
            }

            Log::info('twitter.error');
            return Redirect::route('twitter.error')->with('flash_error', 'Crab! Something went wrong while signing you up!');
        }

        Log::info('end callbackk call');
    }

    private function _set_login($user_name, $user_email) {
        $UserRepository = new UserRepository;
        $data_user = $UserRepository->getByEmail($user_email);
        if(count($data_user) > 0) {
            // sudah terdaftar
            $user_id = $data_user->id;
        } else {
            // belum terdaftar dan jalankan proses register
            $data_save = [
                'name' => $user_name,
                'email' => $user_email,
                'password' => Hash::make($user_email)
            ];

            $user_id = $UserRepository->save_data($data_save);
        }

        $user = User::find($user_id);
        Auth::login($user);
    }
}

maybe it can help you.
the point code is here
$user = Socialite::driver('twitter')->userFromTokenAndSecret($token['oauth_token'], $token['oauth_token_secret']);

so with $user i can get the email and another property there.

A: I had a work around to avoid method doesn't exist "error"
$user = call_user_func(array(Socialite::driver("facebook"),"userFromToken"),$token);


text:
Q: How can I redirect the STDOUT to STDIN in a C program Lets say I want to write a C program that executes the same command as :  ls -l | wc -l
The following is an attempt :
int main(){
    int fd;
    char *buffer[] = {"ls", "-l", (char *) NULL};
    char *buffer1[] = {"wc", "-l",(char *) NULL};
    if(fork() == 0){
        // I make the STDOUT_FILENO and fd equivalent
        if((fd = dup(STDOUT_FILENO)) == -1){
            perror("error");
            exit(EXIT_FAILURE);
        }
        close(fd);
        if(fork() == 0)
            execvp(buffer[0], buffer);
        // then I make fd and STDIN_FILENO equivalent in order to put the output of the previous command
        // as the input of the second command
        if(dup2(fd, STDIN_FILENO) == -1){
            perror("error");
            exit(EXIT_FAILURE);
        }
        execvp(buffer1[0], buffer1);
    }

    exit(EXIT_SUCCESS);
}

But it just runs ls -l without feeding its output to wc -l

A: You would have to create a pipe between your two processes. (This is also what happens when you use | on the command line.)
There are a lot of examples how to do that, for instance here.
Basically you create the pipe with a call to pipe(), and then each process closes one end of the pipe.


text:
Q: AWS IAM and CLI - How to resolve pass role error? I logged into AWS console as DEV-OPS-ENGINEER and created ROLE-1 with aws managed policy attached. I attached this role to ECS tasks.
Now from my machine I logged into aws cli as DEVELOPER and ran aws ecs update-service command but i am getting below mentioned error:
"An error occurred (AccessDeniedException) when calling the UpdateService operation: User: arn:aws:sts:::assumed-role/DEVELOPER is not authorized to perform: iam:PassRole on resource: arn:aws:iam:::role/ROLE-1"
My idea was all logged in user (with different roles) should be able to use ROLE-1.
Any idea why it is throwing me this error and how can I resolve it ?

A: To pass a role (and its permissions) to an AWS service, a user must have permissions to pass the role to the service. This helps administrators ensure that only approved users can configure a service with a role that grants permissions. To allow a user to pass a role to an AWS service, you must grant the PassRole permission to the user's IAM user, role, or group.
Find out more, including examples, in the AWS User Guide: Granting a user permissions to pass a role to an AWS service


text:
Q: MongoDB aggregation grouping fill missing values I'm using MongoDB aggregation framework. I have a Mongo collection with documents like this:
{
  'step': 1,
  'name': 'house',
  'score': 2
}
{
  'step': 1,
  'name': 'car',
  'score': 3
}
{
  'step': 2,
  'name': 'house',
  'score': 4
}

I'm grouping the documents with same 'step' and pushing 'name' and 'score' into an array of objects. What I get is:
{
  'step': 1,
  'scores':
  [
      {'name':'house','score':2},
      {'name':'car','score':3}
  ]
}
{
  'step': 2,
  'scores':
  [
      {'name':'house','score':4}
  ]
}

For each 'step' I need to copy the value of previous 'step' in case that a 'name' does not exists. I should have something like this:
{
      'step': 1,
      'scores':
      [
          {'name':'house','score':2},
          {'name':'car','score':3}
      ]
    }
    {
      'step': 2,
      'scores':
      [
          {'name':'house','score':4},
          **{'name': 'car', 'score':3}**
      ]
    }

At the second document the element {'name':'car','score':3} has been copied from the previous document because at 'step:2' there is not documents having 'score' for 'car'.
I'm not able to figure out how to do this operation with MongoDB aggregation. Some help will be very appreciated.

A: Required to use $lookup with pipeline, look below step by step,

*

*$group by step and push all scores in one array scores

*push all name in names of each score of particular step, we will use in match condition inside lookup

db.collection.aggregate([
  {
    $group: {
      _id: "$step",
      scores: {
        $push: {
          name: "$name",
          score: "$score"
        }
      },
      names: { $push: "$name" }
    }
  },

*

*$unwind scores because its array and we are going to lookup

  { $unwind: "$scores" },

*

*$lookup let variables step(_id) and names for pipeline level

*$match condition with expression $expr there are 3 conditions

*

*check the size of names It should be one(1), either its car or house,

*match step number, it should be equal

*match not in for ex. if car is already available then it will search for house in lookup, need to use separate $not and than $in

*$project to show required fields

*lookup result will store in clone_score
  {
    $lookup: {
      from: "collection",
      let: {
        step_id: { $subtract: ["$_id", 1] },
        names: "$names"
      },
      pipeline: [
        {
          $match: {
            $expr: {
              $and: [
                { $eq: [{ $size: "$$names" }, 1] },
                { $eq: ["$$step_id", "$step"] },
                { $not: [{ $in: ["$name", "$$names"] }] }
              ]
            }
          }
        },
        {
          $project: {
            _id: 0,
            name: 1,
            score: 1
          }
        }
      ],
      as: "clone_score"
    }
  },

*

*$group by step(_id) and push all scores in one array scores, keep first clone_score
  {
    $group: {
      _id: "$_id",
      scores: { $push: "$scores" },
      clone_score: { $first: "$clone_score" }
    }
  },

*

*from above pipelines, we have two separate array scores and clone_score now,

*$project we need to concat both of them in scores
  {
    $project: {
      _id: 0,
      step: "$_id",
      scores: {
        $concatArrays: ["$scores", "$clone_score"]
      }
    }
  }
])

Playground: https://mongoplayground.net/p/Fytf7NEU7uG


text:
Q: Problem with Picasso while binding image to recyclerview I am not able to bind my image from firebase to recyclerview using Picasso.
Is it incorrect to bind this way?
Picasso.get().load(img).fit().centerCrop()
                        .into(imgViewUser)

Hope someone with experience with Picasso can give me some guidance. Thank you so much in advance.
@SuppressLint("ResourceType")
            override fun onBindViewHolder(holder: UserViewHolder, position: Int, model: Game) {
                val tvGameName: TextView = holder.itemView.findViewById(R.id.tvHeading)
                val imgViewUser: View? = holder.itemView.findViewById(R.id.titleImage)

                tvGameName.text = model.documentId
                val img: URI = model.images?.get(0)
                Picasso.get().load(img).fit().centerCrop()
                    .into(imgViewUser)

                //val tvCounter: TextView = holder.itemView.findViewById(android.R.id.text1)
                //val tvLang: TextView = holder.itemView.findViewById(android.R.id.text2)
                //tvCounter.text = model.counter.toString()
                //tvLang.text = model.documentId

                Toast.makeText(applicationContext, "image is $img", Toast.LENGTH_LONG).show()
            }
        }
        rvUsers.adapter = adapter
        rvUsers.layoutManager = LinearLayoutManager(this)
    }

A: The mistake is the wrongly assigned imgViewUser as View, which should have been ImageView. Now it is all good. Tks!


text:
Q: How do I convert a hexidecimal color (with alpha) to an int in Jython? I need to convert an ARGB hex into an int in Jython for color. I've tried using longs, hex() and a combination of other things and can't seem to get it to work.
I get this error "TypeError : 5th arg can't be coerced to int" when I try to convert 0x80ff3333 to an int.
I guess there are too many bytes in the hex to convert it. Anyone know the syntax for this conversion?
Thanks!

A: Just pass a second argument for the base to the int-function.
Jython 2.5.2b1 (trunk:7081M, Jul 20 2010, 18:56:05)
[Java HotSpot(TM) 64-Bit Server VM (Apple Inc.)] on java1.6.0_20
Type "help", "copyright", "credits" or "license" for more information.
>>> int('0x80ff3333',16)
2164208435L
>>> # verification
>>> hex(_)
'0x80ff3333L'


text:
Q: Constructing a graph in tensorflow-java using OperationBuilder class in Java Hi I am following the official tensorflow example of https://github.com/tensorflow/tensorflow/blob/master/tensorflow/java/src/main/java/org/tensorflow/examples/LabelImage.java
to construct my computation graph inside java instead of using a one constructed in python. I see that they construct a graph for preprocessing the image which does not require any backproagation. So my question is, if I want to construct a computation graph for complete training do I follow the same steps(create static APIs for the ops) , or do I need to do something more in order to manage the gradients for backpropagation?

A: TensorFlow Java bindings don't have support for automatic differentiation. You can compute gradients yourself, by manually adding appropriate operations, but there is no magic like tf.gradients() in python that will add them for you.


text:
Q: right align input in table I'm trying to align a text input to the right of a table td but with no results. Here's what i have:

.right {
  text-align: right;
}

    <input type="text" name="nome" id="nome" placeholder="Nome" />
    <input type="text" name="email" id="email" placeholder="Email" />

    <input type="text" name="msg" id="msg" placeholder="Mensagem" />

      <input type="submit" id="sendform" value="Enviar">

A: The second <input> is right aligned inside the .
But the <input> also happens to be just as wide as the .
Run this to see what happens after forcing the  a bit wider, and the <input> a bit narrower. (I also added borders to make the effect more visible)

td {
  border: 1px solid black;
  width: 100px;
}

input[type="text"] {
  width: 60px;
}

.right {
  text-align: right;
}

    <input type="text" name="nome" id="nome" placeholder="Nome" />
    <input type="text" name="email" id="email" placeholder="Email" />

    <input type="text" name="msg" id="msg" placeholder="Mensagem" />

      <input type="submit" id="sendform" value="Enviar">


text:
Q: how to create xml file from xml schema in java I want to make an java application where user give any xml schema and application generate xml file holding with xml schema and using this application user can put value in xml file.
I try to make this application using jaxb here I generate xml schema to java source using xjc "xsd file name" and then compile it so it creates class file and using them to create xml file.but creating xml file is depends upon generated java source,how can i make it dynamic.how can i make class file from my application automatically and using it to create xml file.


text:
Q: MediaWiki Table of content wrong language bug

Inhaltsverzeichnis

                    1
                    Special features

                    2
                    Importance for search engine optimization

                    3
                    Web links

My table of contents seems to have a weird problem. Whenever I am logged in to my English wiki, it displays correctly as "content". As soon as I am logged out, it displays as "Inhaltsverzeichnis" which is German. It seems to get that info from my browser.
Languages are saved in my wiki/languages/i18n/ files.
Has anyone got a clue why this is happening?

A: IIRC, the most common cause is that the system message containing the translation of the TOC title is cached in the wrong language. Ensure you configured the caches correctly: https://www.mediawiki.org/wiki/Manual:Cache
To find out where the problem lies, use eval.php to query  with \Cdb\Reader::open and MessageCache, as in https://phabricator.wikimedia.org/T131981#2186195


text:
Q: How can I tell iTunes to stop playing a song? I do mean stop, not pause. If one navigates to, say, the iTunes Store, the Pause button changes to Stop, but I want something that always works no matter my location in iTunes.
Workarounds (such as AppleScript) are acceptable as long as they aren't too difficult to set up.

A: The AppleScript for this is pretty simple:
tell application "iTunes" to stop

You can make this easily accessible by creating a Service.
Open Automator and create a new document. Select the Service document type. Set the Service receives: menu to no input. Drag in a Run AppleScript module and paste that code into its text box. Save the service and give it a name.
You'll now be able to activate it by going to the current app's menu and choosing Services-> Stop iTunes (or whatever you named the service).
You can assign a keyboard shortcut by going to System Preferences-> Keyboard-> Services, finding the service (it should be under General at the bottom) and adding a shortcut.

A: In Applescript, the script tell app "iTunes" to stop should work.
And the pause button is only available in the currently playing playlist; anywhere else, it will be stop.

A: There are three correct answers here. I've tried two of them to see that they work. Command-period stops the currently playing song and so does Option-Pause. I've seen the Command period solution before but cannot remember where I found it. The Option-pause solution is new to me, but I'm glad to have two solutions. Maybe I'll remember at least one of them. ;-)
The Apple Script solution probably works too, but it makes things more difficult then they need to be, given the other two solutions. That said, at some time in the distant past I created a Scripts folder in the ~/Library/iTunes folder and placed some scripts in it. As a result I have a Scripts icon next to the Help menu in iTunes. That's where I'd put the script if I wanted to use it. No need to create a service or keyboard shortcut to it. By the way, I tested this option: I quit iTunes and then put the Scripts folder in the trash. I launched iTunes and the scripts item in the menu bar was gone. I quit iTunes and restored the Scripts folder, launched iTunes and there it was again in the menu bar. From this I conclude that anyone can create a Scripts folder for iTunes if they want to. That would be an easier way to use the script it you wanted to go that route. You cannot create a keyboard shortcut for it, though, because the Scripts item in the iTunes menu uses an icon, not a name. I tried it; no go. Hope this answer isn't too long.

A: Hold the Option key down, while clicking the Pause button.

A: You can't! What I do is either "Quit iTunes" or delete the tract (I only delete if I already have the song on a DVD; I can add it back to my library at a later date).
iTunes is not user friendly. I use it sparingly.


text:
Q: Cramér's $V$ on Rao-Scott adjusted Pearson $\chi^2$ I have survey data with design weights for stratified sampling. My ultimate goal is to estimate Cramér's $V$ for contingency tables, a Pearson $\chi^2$ based measure. To account for the weights, I am thinking about using Rao-Scott adjustment to estimate $\chi^2$ statistics. However, then it is not clear how to get to Cramér's $V$.
Is it accurate to estimate $V$ from a first-order Rao-Scott adjusted $\chi^2$, just like I would estimate it from an unadjusted $\chi^2$? Or should $V$ be adjusted as well?
Thank you!
Some notes:
Link (Original Article)
http://www.amstat.org/sections/srms/proceedings/y2007/Files/JSM2007-000874.pdf (Some summary)

A: I don't think Cramer's V makes much sense with complex survey data, as your $N$ in the denominator is not well defined. There is a number of replacements for it that can be offered: the design degrees of freedom (# of strata minus # of PSUs); the effective sample size (= sample size / design effect); the denominator d.f. of the Rao-Scott 2nd order correction; or there may be something yet else. If Alastair Scott does not discuss Cramer's V, then it likely just does not make sense.
With complex survey data, hypothesis testing can only be conducted using the Rao-Scott corrected test statistic and its (weird fractional) degrees of freedom, anyway. So coming up with interesting transformations of the statistic may be an interesting scholastic exercise, but it will hardly give you any additional insights.

A: I've just been asked how to do this for the survey package. It looks as though Cramer's $V$ and Udny's $\phi$ do have reasonable definitions as (super)population quantities.
In particular, in the $2\times 2$ case
$$\phi=\frac{n_{00}n_{11}-n_{01}n_{10}}{\sqrt{n_{0\cdot}n_{1\cdot}n_{\cdot 0}n_{\cdot 1}}}$$
and this quantity is just the Pearson correlation and for 2x2 tables $V=\phi$
A plug-in estimator of this for the population would be
$$\hat\phi=\frac{\hat N_{00}\hat N_{11}-\hat N_{01}\hat N_{10}}{\sqrt{\hat N_{0\cdot}\hat N_{1\cdot}\hat N_{\cdot 0}\hat N_{\cdot 1}}}.$$
This is also what you get if you compute it from the Pearson $X^2$ statistic on the population table, which fits with the original motivation of Rao-Scott statistics as approximate corrections to statistics inappropriately computed from the estimated population table.
svycramerV<-function(formula,design,...){
    tbl<-svytable(formula,design,...)
    chisq<-chisq.test(tbl, correct=FALSE)$statistic
    N<-sum(tbl)
    V<-chisq/N/min(dim(tbl)-1)
    names(V)<-"V"
    sqrt(V)
}

So I think there's a reasonable case for defining $\hat V$ or $\hat \phi$ from the estimated population contingency table, as long as there isn't a standard definition that contradicts it.


text:
Q: Infinite dimensional vector space I am solving the following : Vector space  $\mathbb{R}$ over rational number
 $\mathbb{Q}$ is infinite dimensional.
I proved this by using that $\mathbb{R}$  is uncountable, but my professor suggested a following slightly different method : Suppose that this vector space is finite-dimensional and let {$r_1,...,r_n$} be a basis for it. Then find an element in $\mathbb{R}$ which doesn't belong to $\operatorname{Span}${$r_1,...,r_n$}. I've tried several methods, but it vain. How can I prove this?

A: Suppose $\mathbb{R}$ is a finite-dimensional $\mathbb{Q}$-vector space, say dimension $n$.
Pick a real transcendental number, such as $e$, and consider $1,e,e^2,e^3,e^4,\dots,e^n$.  This is a set $n+1>\dim_\mathbb{Q}\mathbb{R}$ elements so must be linearly dependent, but that means $e$ satisfies a polynomial with $\mathbb{Q}$ coefficients, contradicting $e$ transcendental.

A: Your approach is fine. The span over $\Bbb Q$ of any finite set of vectors (be they real numbers, or from some other vector space) is necessarily countable, and as such any $\Bbb Q$-vector space with uncountably many vectors must be infinite dimensional.
As for your professor's approach, the best way I can think of would be to first enumerate all elements in the span, and then by Cantor's diagonal argument construct a real number which is not in the span. This feels like it's just the same logic in reverse, though.
If your professor (or anyone else) has a more concise way of constructing a real number not in the span, I would love to hear it.


text:
Q: Practical Queuing Theory I want to learn enough simple/practical queuing theory to model the behavior of a standard web application stack: Load balancer with multiple application server backends.
Given a simple traffic pattern extracted from a tool like NewRelic showing percentage of traffic to a given part of an application and average response time for that part of the application, I think I should be able to model different queueing behaviors with loadbalancer configuration, number of app servers, and queuing models.
Can anyone help point me to queuing theory introductory/fundamentals I would need to represent this system mathematically?  I'm embarrassed to say I knew how to do this as an undergrad but have since forgotten all of the fundamentals.
My goal is to model different load-balancer and app-server queuing models and measure the results.
For example, it seems clear an N-mongrel Ruby on Rails application stack will have worse latency/wait time with a queue on each Mongrel than a Unicorn/Passenger system with a single queue for each group of app workers.

A: I can't point you at theory, but there are a few basic methods in popular usage:

*

*Blind (linear or weighted) round-robining - requests are cycled through n servers, maybe according to some weighting. Each backend maintains a request queue. A slow-running request backs up that worker's request queue. A worker that stops returning results is eventually dropped out of the balancer pool, with all requests currently queued on it getting dropped. This is common for haproxy/nginx balancing setups.

*Global pooling - a master queue maintains a list of requests, and workers report when they are free to accept a new request. The master hands off the front of the queue to the available worker. If a worker goes down, only the currently-being-handled request is lost. Results in slightly diminished performance under ideal circumstances (all workers up and returning requests quickly), since communication between queue master and backends is prerequisite to a job actually being handed off, but with the benefit of naturally avoiding slow, dead, or stalled workers. Passenger uses this balancing algorithm by default, and haproxy uses uses a variant on it with its "leastconn" balancing algorithm.

*Hashed balancing - some component of the request is hashed, and the resulting hash determines which backend to use. memcached uses this sort of strategy for sharded setups. The downside is that if your cluster configuration changes, all the previous hashes become invalid, and may map to different backends than before. In the case of memcached specifically, this results in a likely invalidation of most or all of your cached data (reddit suffered some massive performance problems recently due to this sort of problem).
Generally speaking, for web apps, I tend to prefer the global pooling method, since it maintains the smoothest user experience when you have slow or dead workers.


text:
Q: Navigation drawer fragment - TextWatcher crashes I am trying to add a TextWatcher method to a fragment loaded through the navigation drawer:
  @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }

    testMethod();
}

public void testMethod() {
    EditText tv_filter = (EditText) getActivity().findViewById(R.id.editText);
    tv_filter.addTextChangedListener(new TextWatcher() {
        public void afterTextChanged(Editable s) {
        }
        public void beforeTextChanged(CharSequence s, int start,
                                      int count, int after) {
        }
        public void onTextChanged(CharSequence s, int start,
                                  int before, int count) {
            Toast.makeText(getActivity(), "INPUT TRACKED", Toast.LENGTH_SHORT).show();
        }
    });
}

The problem is, whenever i load this fragment, the app crashes with the following logcat message:
    08-26 12:00:26.553  12842-12842/fest.test.dk.fest E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: fest.test.dk.fest, PID: 12842
java.lang.NullPointerException
at fest.test.dk.fest.menuFragment.testMethod(menuFragment.java:74)
at fest.test.dk.fest.menuFragment.onCreate(menuFragment.java:66)
at android.support.v4.app.Fragment.performCreate(Fragment.java:1766)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:917)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1138)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:740)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1501)
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:458)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)

Usually the logcat will be pretty specefic with the errors, but I am unable to figure out exactly what this error means.

A: getActivity() is probably null. Shift the call of testMethod.  Override onAttach in the fragment and call it from there. Read up on the fragment lifecycle again.


text:
Q: Get dynamic background position using jQuery I'm trying to implement a parallax scrolling effect on a site (using this tutorial from Smashing Magazine). The parallax effect is working fine, but I need to get one of the sprites to stop scrolling when it reaches a certain point. By default, it continues scrolling until it is out of view.
The parallax effect works by animating the background position of the element. I am trying to get the dynamic background position using this code:
jQuery(function($) {

            var elem = $("#heart-box");

            var backgroundPos = $(elem).css("backgroundPosition").split(" ");

            var xPos = backgroundPos[0],
                yPos = backgroundPos[1];

            $(window).scroll(function() {

                console.log(yPos);

                if ( yPos >= 210 ) {
                    $(elem).hide();
                }
            });

        });

Instead, just the starting position is being returned, as defined in the CSS, and isn't changed in the console log when the page is scrolled.
When the page is scrolled, the background Y position is dynamically changed - the range of which is approximately -200px starting, through to 400px at its finish. When the background Y position reaches 210px, I want the element to have a fixed background position of 210px, not keep scrolling.
Any help would be great. Thanks.

A: The initial value is returned because yPos is set to the value of backgroundPosition outside of your scroll callback. In Javascript only objects are passed by reference, so your backgroundPos, yPos and xPos variables (which are primitive types - strings in this case) are not changed when the CSS property you retrieved them from changes; they have the value they were assigned initially since you never reassign them.
To make this work how you are expecting, you will need to retrieve the current background position inside the scroll callback.
$(window).scroll(function() {

    var backgroundPos = $(elem).css("backgroundPosition").split(" ");
    var xPos = backgroundPos[0],
        yPos = backgroundPos[1];

    console.log(yPos);

    if ( yPos >= 210 ) {
        $(elem).hide();
    }

});

To make this slightly more efficient, you could assign the result of $(elem) to a variable outside of the scroll callback so that the selector is not called on every scroll event (more relevant if you were using a string as a selector):
var elem = $(elem);
...
elem.css("backgroundPosition").split(" ");


text:
Q: Как сократить запрос UPDATE, если входные данные - 4 координаты массива? Делаю запрос в базу данных
UPDATE `items` SET `status`=1 WHERE `x`=10 AND `y`=20

Это обновил одну строку.
А как обновить 100 строк, если входные данные - ЧЕТЫРЕ числа X=10,X=20,Y=20,Y=30, то есть для полей Х значением от 10 до 20 и Y от 20 до 30?
Нюанс в том , что структура базы данных такова:
сначала идет 100 строк, где значение поля X возрастает от 1 до 100 и Y=1, затем следующие 100 строк, где X также от 1 до 100, но Y=2, и так далее до Y=100, приложил скрин базы данных.

A: UPDATE items
SET status = 1
WHERE
  (x BETWEEN 10 AND 20) AND
  (y BETWEEN 10 AND 20);


text:
Q: Unable to download some packages on Redhat I am unable to download the pam-devel, zlib-devel and openssl-devel packages on a Red Hat Enterprise Linux Server release 7.4 (Maipo).
When executing # yum install pam-devel I am getting the following error:
error: No package pam-devel available.
error: Nothing to do

While running # yum repolist all the following content is being displayed:

I am not able to enable the repositories running # yum-config-manager --enable epel-source/x86_64.

Why are the packages not available and what I can do to get them?


text:
Q: Dynamic programming algorithm for unweighted interval scheduling? I was wondering if someone could please help me reason about a DP algorithm for unweighted interval scheduling.
I'm given 2 arrays [t1,...,tn] and [d1,...,dn] where ti is the start time of job i and di is the duration of job i. Also the jobs are sorted by start time, so t1 <= t2 <= ... <= tn. I need to maximize the number of jobs that can be executed without any overlaps. I'm trying to come up with a DP algorithm and runtime for this problem. Any help would be much appreciated!
Thank you!

A: I am sorry I don't have any more time now to spend on this problem. Here is an idea, I think it lends itself nicely to Dynamic Programming. [Actually I think it is DP, but almost two decades have passed since I last studied such things...]
Suppose T = {t1, t2, ..., tn} is partitioned as follows:
T = {t1, t2, ..., tn} = {t1, t2, ..., tk} U {tk+1, tk+2, ..., tn}
  = T1(k) U T2(k)

Let T2'(k) be the subset of T2(k) not containing the jobs overlapping T1(k).
Let opt(X) be the optimal value for a subset X of T. Then
opt(T) = min( opt( T1(k) ) + opt( T2'(k) )

where the minimum is taken along any possible k in {1, 2, ..., n}
Of course you need to compute opt() recursively, and take into account overlaps.
Hope this helps!

A: It's easiest for me to think about if I suppose that you work out what the end time would be for each job and sort the jobs into order of increasing end time, although you can probably achieve the same thing using start times working in the opposite direction.
Consider each job in order of increasing end time. For each job work out the maximum number of jobs you can handle up to and including that job if you decide to work on that job. To work this out, look at the answers you have already computed that cover times up to the start time of that job and find the one that covers the maximum number of jobs. The best you can do while handling the job you are considering is one plus that maximum number.
When you have considered all the jobs, the maximum number you can cover is the maximum number you have computed when considering any job. You can work out which jobs to do by storing the previous job that you identified when working out the maximum score possible for a particular job, and then tracing these pointers back from the job with the maximum score.
With N jobs to consider you look back at at most N previously computed answers when working out the best possible score for each job so I think this is O(N^2)


text:
Q: If a full power Tardis went into siege mode how big would it be? In the episode Flatline the power is being drained from the Tardis which resulted in the shrinking to a handy bag sized version. As a last resort to avoid being crushed by a train the Doctor activated Siege Mode which made the little blue box look all rufty toughty and impregnable.
However, if the Tardis had been functioning at full power and Siege Mode was activated would it still be small or would it be a different size? It strikes me that a battle mode which prevented the occupants from escaping is a bad idea!

A: We don't have enough information regarding "siege mode" to know conclusively what apparent size the TARDIS portal would end up being.
What we do know:

*

*The TARDIS' dimensional energies as well as the physical dimensions of the external aspects of the TARDIS were being affected. The TARDIS grew smaller in relation to its appearance in our universe due to its dimensions being absorbed by the two-dimensional aliens.

If we are to assume, the TARDIS found itself without sufficient power to escape a circumstance that required the "siege mode" it would likely change its appearance proportionally.

*

*If the TARDIS were to enter "siege mode" under non-dimensionally challenged conditions, it is safe to assume the cubic mode would be comparable and proportional to its shrunken dimensions.

When we first see the portable TARDIS, before Clara put it in her purse, it was about 12 inches long.

It does shrink further during the episode.

The cube we see later is about three inches. Assuming it didn't shrink further, the proportions would be about 2 to 1. A six inch TARDIS becoming 3 inch cube.

*

*I suspect this would make the TARDIS a cube approximately 4 feet depending on the absolute size of the Police Box appearance.

It isn't the size of the TARDIS under "siege mode" that matters, it's the impregnability. This is one of those instances where "size doesn't matter."

A: My guess is that it would be the in proportion of the sizes of the minitardis and the minisiege. A rough estimate might be 7ft x 7ft.


text:
Q: Javascript objects properties vs array values I'm trying to learn javascript (coming from Delphi/pascal) and am unclear about the similarities and differences between object properties and array values.  I did try searching the archives and the web for this answer.
Consider the following code:
function Show(Arr) {
  var str ='';
  for (var Val in Arr) {
      str += Val + '::' + Arr[Val] + '\n';
  }
  return str;
}
var str = '';
var A1 = ["Yellow", "Red", "Blue"];
var A2 = {"color":"red", "Size": 5, "taste":"sour"}

alert(Show(A1));
//OUTPUTS:
//    0::Yellow
//    1::Red
//    2::Blue

A1.push("Green");
alert(Show(A1));
//OUTPUTS:
//    0::Yellow
//    1::Red
//    2::Blue
//    3::Green

alert('Length: '+A1.length);
//OUTPUTS:
//   Length: 4

alert(Show(A2));
//OUTPUTS:
//  color::red
//  Size::5
//  taste:sour

alert('Length: '+A2.length);
//OUTPUTS:
//   Length: undefined

A2.push("Green");
//ERROR --> execution stops on jsfiddle.net.
alert("OK");  //<-- never executed
alert(Show(A2));  //<-- never executed

I know that almost everything is an object in javascript.  I have been reading here (http://javascript.info/tutorial/objects) and here (http://www.w3schools.com/js/js_objects.asp).
I see that an array can be accessed by index, e.g. A1[3] --> Blue, as in other languages.  But I see also that a property can be accessed this way, e.g. A2["Size"] --> 5.  So at first blush, it looks like array values and property values are essentially the same.  But arrays can be extended with a .push(value) command, whereas properties can't.
It is coincidence that my Show function works for both arrays and objects?
Actually, as I have written this and researched the topic, is it just that all arrays are objects, but not all objects are array?  So then does the for...in loop in Show() actually work differently depending on which type of object is sent in?
Any help clarifying this would be appreciated.  Thanks.

A:
So at first blush, it looks like array values and property values are essentially the same.

Array entries and object properties are indeed the same thing, because JavaScript's standard arrays aren't really arrays at all, they're just objects with some added features. Two of those features are the special length property, and the push function, which is why you don't see those with A2.
Your observation about bracketed notation is particularly spot-on. In JavaScript, you can access object properties using bracketed notation and a string, like this:
var o = {answer: 42};
console.log(o['answer']); // 42

It's not well-known that this is exactly what you're doing when using an array "index":
var a = ['a', 'b', 'c'];
console.log(a[1]); // b

The 1 we're using with a[1], technically according to the specification, is coerced to a string (a["1"]), and then that property name is used to look up the property on the object.

So then does the for...in loop in Show() actually work differently depending on which type of object is sent in?

No, for-in works the same with all objects. It iterates the names of the enumerable properties of the object. Whether you're using an array or any other object doesn't matter.
Note that not all properties are enumerable. For instance, Array#length isn't, nor is Array#push or Object#toString or any of the other built-in properties of objects.
But for instance, you can see that for-in is the same for arrays as for other objects like this:
var a = ['zero'];      // An array with one entry
a.answer = 42;         // We've added a property to the object that isn't an array entry
console.log(a.length); // 1, because `length` only relates to array "indexes" as
                       // defined by the specification
var key;
for (key in a) {
    console.log(key + "=" + value);
}
// Shows (in *no reliable order*):
// 0=zero
// answer=42

More about for-in:

*

*Myths and realities of for..in (on my blog)

*My answer to the question For each in array, how to do that in JavaScript? here on SO


text:
Q: Can I change the instance class of Node.js app on Google App Engine? I deployed my node.js app to Google App Engine. However, it automatically used two g1-small instances under Compute Engine, and there was no room I can set the instance class beforehand.
Because it is insanely expensive to use two such large instances, however, I want to change the instance class.
However, it seems that there are no columns there that let me change it, and a similar question hasn't got any accepted answer, though it is on Python, not node.js.
So is it feasible to change the instance type on Google App Engine? I want to use f1-micro...

A: It's explained here in the resource settings
https://cloud.google.com/appengine/docs/flexible/nodejs/configuring-your-app-with-app-yaml
you don't explicitly defined the instance type, but you defined the cpu and memory