text:
Q: TypeScript infer return type from used arguments I'm not sure if this has been asked under different terminology. I've got a function that takes two arguments, where both can (independently) be a number, string, or undefined. The returned value is statically guaranteed to be also one of those two arguments:
export function wideNarrow(wide:number|string|undefined,
                           narrow:number|string|undefined){
    return isNarrowScreen() ? narrow : wide;
}

In some part of my app I pass two numbers to the function:
wideNarrow(8, 0);
However, the inferred return type is string|number, which shows an error with a numerical operation:
const extendedAreaHeight = 26;
const baseY = extendedAreaHeight + wideNarrow(8, 0);

Operator '+' cannot be applied to types '26' and 'string | number'.ts(2365)
and
Object is possibly 'undefined'.ts(2532)
It can be statically inferred that this particular call will always return a number, why is TypeScript not detecting it and still thinking that a string or undefined might be returned, and how can I fix it without breaking existing functionality (e.g. I may return undefined or string, string or number, undefined or number and any combination of these in other places that I call the function)?
I'm on TypeScript 3.5.2/Vscode 1.36.1.

A: As Thomas suggested (and I simultaneously discovered), having two type arguments with the same signature solves the problem:
export function wideNarrow
  <T=number|string|undefined,
   K=number|string|undefined>
   (wide:T, narrow:K){
  return isNarrowScreen() ? narrow : wide;
}

The reason for having two of exact types instead of one is that they can be different as I've stated in the question. If I made it just T without K and made both wide and narrow type of T, it forces both wide and narrow to be of same type (e.g. both numbers), whereas I sometimes need them to be of different type (e.g. wide string but narrow number).
Note: If anyone really wants to know in what scenario that I need it this way, I'm using it to fill stylesheets in my React Native app where some style elements are perfectly happy with both numbers e.g. (width: 100 of 100 points wide) or strings (e.g. width: '50%') for filling half of the container horizontally).

A: You can add more precise function declarations, like this:
export function wideNarrow(wide: number, narrow: number): number;
export function wideNarrow(wide: number|string|undefined, narrow: number|string|undefined) {
    return isNarrowScreen() ? narrow : wide;
}

The function still has only one implementation, but multiple declarations, which helps the compiler. See Function Overloads documentation section.


text:
Q: Mysql - TABLE field layout using sql statement Is there any to format the sql statement result as given following........
TABLE1
ID ticket_number
1   2001
2   2002

Table2
tn    name                 create_time
2001  sms_to_customer      2013-05-05 10:10:19
2001  sms_to_officer1      2013-05-05 11:17:01
2001  sms_to_officer2      2013-05-05 12:14:05
2002  sms_to_officer1      2013-05-05 09:17:01
2002  sms_to_officer2      2013-05-05 09:30:05

I want the result like........
ticket_number   sms_to_customer      sms_to_officer1        sms_to_officer2
2001            2013-05-05 10:10:19  2013-05-05 11:17:01    2013-05-05 12:14:05
2002            NA                   2013-05-05 09:17:01    2013-05-05 09:30:05

A: If those were only the values for column name on Table2, you can use this static version of the query,
SELECT  tn,
        COALESCE(MAX(CASE WHEN Name = 'sms_to_customer' THEN Create_Time END), 'NA') `sms_to_customer`,
        COALESCE(MAX(CASE WHEN Name = 'sms_to_officer1' THEN Create_Time END), 'NA') `sms_to_officer1`,
        COALESCE(MAX(CASE WHEN Name = 'sms_to_officer2' THEN Create_Time END), 'NA') `sms_to_officer2`
FROM    Table2
GROUP   BY tn

*

*SQLFiddle Demo
otherwise, use Dynamic SQL if you have values other than that
SET @sql = NULL;
SELECT
  GROUP_CONCAT(DISTINCT
    CONCAT(
      'COALESCE(MAX(case when Name = ''',
      Name,
      ''' then create_time end), ''NA'') AS ',
      CONCAT('`',Name,'`')
    )
  ) INTO @sql
FROM Table2;

SET @sql = CONCAT('SELECT  tn, ', @sql, '
                   FROM Table2
                   GROUP BY tn');

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

*

*SQLFiddle Demo
OUTPUT
╔══════╦═════════════════════╦═════════════════════╦═════════════════════╗
║  TN  ║   SMS_TO_CUSTOMER   ║   SMS_TO_OFFICER1   ║   SMS_TO_OFFICER2   ║
╠══════╬═════════════════════╬═════════════════════╬═════════════════════╣
║ 2001 ║ 2013-05-05 10:10:19 ║ 2013-05-05 11:17:01 ║ 2013-05-05 12:14:05 ║
║ 2002 ║ NA                  ║ 2013-05-05 09:17:01 ║ 2013-05-05 09:30:05 ║
╚══════╩═════════════════════╩═════════════════════╩═════════════════════╝

A: SELECT
   ticket_number, t2.create_time as `sms_to_customer`,t3.create_time as `sms_to_officer1`,t4.create_time as `sms_to_officer2`
  from Table1 t1
    left join Table2 t2 on (t1.ticket_number=t2.tn and t2.name='sms_to_customer')
    left join Table2 t3 on (t1.ticket_number=t3.tn and t3.name='sms_to_officer1')
    left join Table2 t4 on (t1.ticket_number=t4.tn and t4.name='sms_to_officer2');

*

*SQLFiddle Demo

redpajama_set_name: RedPajamaStackExchange


text:
Q: Worksheet_Change doesn't fire up when streaming live data I have read many posts around this topic, however nothing seems to work for my scenario
I would like to Call Sub upon cell change (B2) which contains live data feed from external source -last updated:
Private Sub Worksheet_Change(ByVal Target As Range)
    If Not Intersect(Target, Target.Worksheet.Range("B2")) Is Nothing Then
        Call SubName
    End If
End Sub

I went through numerous posts suggesting to check if Äpplication.EnableEvents = True, or create function to detect the change ( which does work, however I cannot call sub within function) - with no success.
Interestnigly enough, when I click on B2 and press enter - it executes the sub
Thanks

A: Say cell A1 is updated by streaming.  The update will not trigger either:

*

*Worksheet_SelectionChange

*Worksheet_Change

What you need to do is setup an equation somewhere:
=A1

When A1 is refreshed, the formula cell will re-calculate and you can detect it with the Calculate Event.

A: you can simply go
Private Sub Worksheet_Change(ByVal Target As Range)
    If Target.Address = "$B$2" Then SubName
End Sub


text:
Q: Accessing objects returned from a factory So I have a factory that fetches objects from a server:
.factory('Articles', function($http) {

  var articles = [];

  return {
        all: function(){
            $http.get("http://jsonp.afeld.me/?url=http://examplesite.com/page.html?format=json").then(function(response){
                articles = response.data.items;
                console.log(response.data.items);
                return articles;
            });
        },

        get: function(articleId) {
            for (var i = 0; i < articles.length; i++) {
                if (articles[i].id === parseInt(articleId)) {
                    return articles[i];
                }
            }
            return null;
        }
    }
});

this is returning an array like so:
[Object, Object, Object, Object, Object, Object, Object, Object]

each object looks like this:
0: Object
alias: "title"
attachments: Array[0]
author: Object
category: Object
catid: "67"
created: "2015-04-11 08:06:07"
created_by_alias: ""
events: Object
extra_fields: null
featured: "0"
fulltext: ""
gallery: null
hits: "80"
id: "171"
image: ""
 imageLarge: "/url/69bc9c3e85c501b0a6208cc7a55abbf9_L.jpg"
 imageMedium: "/url/69bc9c3e85c501b0a6208cc7a55abbf9_M.jpg"
 imageSmall: "/url/69bc9c3e85c501b0a6208cc7a55abbf9_S.jpg"
 imageWidth: ""
 imageXLarge: "/url/69bc9c3e85c501b0a6208cc7a55abbf9_XL.jpg"
 imageXSmall: "/url/69bc9c3e85c501b0a6208cc7a55abbf9_XS.jpg"
 image_caption: ""
 image_credits: ""
introtext: "
Mpho Mathoholots of text is here....
"
language: "*"
link: "/url/title.html"
modified: "2015-06-02 07:44:30"
numOfComments: "0"
numOfvotes: "(0 votes)"
tags: Array[1]
title: "the title"
video: null
video_caption: ""
video_credits: ""
votingPercentage: 0
__proto__: Object

my controller looks like this:
.controller('GautengCtrl', function($scope, $stateParams, Articles) {
  $scope.articles = Articles.all();
})

all I want to do is return a list of articles and display them on a page. My HTML looks like this:
    <ion-list>
      <ion-item ng-class='{in:$first}' class="item-remove-animate item-thumbnail-left item-icon-right wrap" ng-repeat="article in articles" type="item-text-wrap" href="#/app/provinces/gauteng/{{article.id}}">

{{article.title}}

{{article.created}}

      </ion-item>
    </ion-list>

this is not working though and I really cannot understand why.
Does anyone have any insight into this that can help?

A: I think that your problem may be related to  promises. Bear in mind that when you use $http you're creating promises and you should use the corresponding callbacks when using the return data.
In the service you're already using .then method, but you aren't actually returning anything from the service to the controller. You should return the generated promise and use the .then/.error methods to update your $scope variable.
.factory('Articles', function ($http) {
    var articles = [];
    return {
        all: function () {
            return $http.get("http://jsonp.afeld.me/?url=http://examplesite.com/page.html?format=json").then(function (response) {
                articles = response.data.items;
                console.log(response.data.items);
                return articles;
            });
        },
        get: function (articleId) {
            for (var i = 0; i < articles.length; i++) {
                if (articles[i].id === parseInt(articleId)) {
                    return articles[i];
                }
            }
            return null;
        }
    }
});

And in your controller
.controller('GautengCtrl', function ($scope, $stateParams, Articles) {
    $scope.articles = [];
    Articles.all().then(function(data){
        $scope.articles = data;
    });
})


text:
Q: confused by explanation of electromagnetic wave in physics textbook I'm kind of confused by the proof used in my physics textbook to explain an electromagnetic field using Faraday's law.
The text book uses Faraday's law to try to explain why a uniform electric field pointing in the y direction while moving in the x direction must have a uniform magnetic field perpendicular to it pointing in the z direction. The images provided are:

The explanation goes on to say that since the application of Faraday's law to the change in size by dA of the imaginary boundary "efgh" as the uniform electric field moves in the x direction at the speed of light c for time dt provides a value of $$\oint _{efgh}\overline{E}\cdot d\overline{l}=-Ea$$ for the lefthand side of Faraday's law (since a is the distance from g to h in the image provided and E is parallel to and exists within only that side of the imaginary boundary and in the opposite direction) which is a nonzero value, it must mean that the righthand side of Faraday's law $$-\frac{d\phi _{B}}{dt}$$ must be nonzero as well. This basically tells us that there must be a uniform magnetic field pointing in the z direction perpendicular to the uniform electric field pointing in the y direction.
While I do understand this explanation, I'm kind of confused because what if the boundary "efgh" was drawn like this instead?

If this was the case, from my understanding the lefthand side of Faraday's law $$\oint _{efgh}\overline{E}\cdot d\overline{l}=0$$ because the electric field is parallel and exists on (g to h) and (e to f) of the imaginary boundary "efgh," but since it is opposite in direction to the (g to h) side and in the same direction as the (e to f) side, they should cancel out one another. But wouldn't there still be a change in the magnetic flux through the area dA? So it should mean that the righthand side of Faraday's law $$-\frac{d\phi _{B}}{dt} \neq 0$$ But this seems to contradict Faraday's law since $$\oint _{efgh}\overline{E}\cdot d\overline{l}=0=-\frac{d\phi _{B}}{dt} \neq 0$$ I'm sure there must be something wrong with this approach. What is it that I'm missing? Any ideas?


text:
Q: Ws2812b circuit safety with 5V 12A i am making a arduino project using 5v ws2812b 300leds/meter. Its going to be a motion activated led strip that runs along the side of the stairs. I will be using 3.5m of the led strip so 210leds at 60mA so if all white on full power they will consume 12.6 amps.
I have a 5v 40a meanwell power supply so plenty of overhead. I will put a 1000uf capacitor on the positive and ground leads of the wires just before they reach the leds and 480 ohm resistor on the data line.
I am concerned with voltage drop over 3.5 meters so i will run the wire along the led strip and inject power every meter. My question is what gauge wire should i be using?
The psu will be under the stairs so wire will be 5m long. I am worried about heat and would like some advice about any safety or fire concerns i should be thinking about.
Should there be a fuse in the circuit?

This is the best schematic i can find to show how its wired, where would the fuse go? Power is coming in from both ends of the led strip, would this suffice for a 3.5m strip

A:
My question is what gauge wire should I be using?

The recommended wire size for 13A is 19AWG (which is hard to find) so get 18AWG. 3.5m of 18AWG wire is about 0.12Ω, which would be about 1.5V of loss. So a larger size of cable or paralleling the wires (multiple strands of 18AWG) might be the best way to go.

Should you put a fuse in the circuit?

If you're worried about something shorting and heating up, then yes, put a fuse in. A 20A fuse would ensure that you don't blow the fuse but protect against short circuits.

A: It is usually recommended that you feed the power to the middle of long strips of LEDs. Or even to more than one point (for example both ends and the middle) in order to minimise the voltage drop along any one section of the run.
The advantages are that you can use thinner power distribution wires (the required total current is divided between the different sets of wires) and the illumination will be much more even.
The disadvantage is that you will have to run several power distribution wires.


text:
Q: Как округлить время Unix до начала текущего дня Нужно округлить Unix-timestamp до начала текущего дня т.е. до 00:00 . Например это - 1578747600 (Sat, 11 Jan 2020 13:00:00 +0000) нужно превратить в это 1578700800 (Sat, 11 Jan 2020 00:00:00 +0000)

A: Можно вспомнить старые времена и посчитать попроще:
long timestamp = 1578747600;
long oneDay = 24*60*60; //86400 - количество секунд в сутках
long startOfDay = (timestamp/oneDay)*oneDay; //1578700800

и проще и дешевле

A: Можно воспользоваться import java.util.Calendar; и установить конкретное время
Calendar now = Calendar.getInstance();
//Устанавливаем день и месяц для конкретной даты, если нужно
now.set(Calendar.MONTH, 0);//Jan
now.set(Calendar.DAY_OF_MONTH, 11);
//Округляем время до 00:00:00
now.set(Calendar.HOUR, 0);
now.set(Calendar.MINUTE, 0);
now.set(Calendar.SECOND, 0);

Результат
System.out.println(now.getTime());
System.out.println(now.getTimeInMillis() / 1000);//Unix time

Sat Jan 11 00:00:00 UTC 2020
1578700800


text:
Q: Invalid number error I have a related question and trying to implement their answer to my problem.
When I try to use their proposed solution I get ORA-01722: invalid number.
Here is my table
CREATE TABLE TEMP_PARSE_EXIST
(
PHYS_ST_ADRS        VARCHAR2(64 CHAR),
PHYS_ADRS_LN2       VARCHAR2(64 CHAR),
PHYS_COM_NM         VARCHAR2(50 CHAR),
PROV                VARCHAR2(10 CHAR),
PSTL_CD             VARCHAR2(16 CHAR),
CNTRY               VARCHAR2(50 CHAR),
MAIL_ADRS           VARCHAR2(64 CHAR),
MAIL_ADRS_LN2       VARCHAR2(64 CHAR),
MAIL_COM_NM         VARCHAR2(50 CHAR),
MAIL_PROV           VARCHAR2(10 CHAR),
MAIL_PSTL_CD        VARCHAR2(16 CHAR),
ADRS                VARCHAR2(64),
V_DIRN              VARCHAR2(2),
V_NUM               VARCHAR2(8),
V_STREET_NAME       VARCHAR2(64),
V_SECOND_LINE       VARCHAR2(64),
V_STREET_TYPE       VARCHAR2(64),
V_POSTAL            VARCHAR2(7),
V_COMM_NM           VARCHAR2(64),
R_REC_TYP_CD        VARCHAR2(1),
ADT_ACT             VARCHAR2(200 CHAR)
);

When running the next part of the code, it comes after the table gets truncated and repopulated from the original data source. I always make sure to truncate and repopulate when I am running the tests to make sure previous results are not interfering.
These first updates are for determining 100 Ave and 100th Ave as valid.
DECLARE
    ALLOWED_STREETS VARCHAR2(1400 char) := '(ABBEY|ACRES|WHARF|WOOD|WYND)'; --has been cut down for question
BEGIN
--this one is for when the 3rd "word" is one of the street types
--and the 2nd "word" is purly numbers for a building number like 100 street
    UPDATE TEMP_PARSE_EXIST
    SET ADT_ACT = 'CASE 1', V_NUM = REGEXP_SUBSTR(REGEXP_SUBSTR(ADRS, '^\w+(\s?-\s?)\w+'), '\d+$')
    WHERE REGEXP_LIKE(REGEXP_SUBSTR(ADRS, '^\w+(\s?-\s?)\w+\s\w+', 'i'), ALLOWED_STREETS || '$', 'i') --problem line
    and REGEXP_LIKE(REGEXP_SUBSTR(ADRS, '^\w+(\s?-\s?)\w+'), '^\w+(\s?-\s?)\d+$')
    AND ADT_ACT IS NULL;

--this one is for when the 3rd "word" is one of the street types
--and the 2nd "word" is numbered streets like 1st ave
    UPDATE TEMP_PARSE_EXIST
    SET ADT_ACT = 'CASE 2', V_STREET_NAME = REGEXP_SUBSTR(REGEXP_SUBSTR(ADRS, '^\w+(\s?-\s?)\w+'), '\d+(ST|ND|RD|TH)$')
    WHERE REGEXP_LIKE(REGEXP_SUBSTR(ADRS, '^\w+(\s?-\s?)\w+\s\w+', 'i'), ALLOWED_STREETS || '$', 'i') --problem line
    AND REGEXP_LIKE(REGEXP_SUBSTR(ADRS, '^\w+(\s?-\s?)\w+'), '^\w+(\s?-\s?)\d+(ST|ND|RD|TH)$')
    AND ADT_ACT IS NULL;
END;

When the lines marked as problems are remove, it will run, but the results are not what what I want.
So what I am doing is working with adrs data that includes building number, sub-units, street name, street type, direction. I am currently working on trying to parse when sub-unit and building number are hyphened together and when they are not. So the conditions I will be placing will be strict for the various methods that can exist.
So while there are numbers in the data I am working with, they are stored as characters, and the fields their being stored in are varchar2, and there are no number operations (that I know of) that are being done. So why the invalid number error, and how can I fix it?

A: You're calling REGEXP_SUBSTR() as:
REGEXP_SUBSTR(ADRS, '^\w+(\s?-\s?)\w+\s\w+', 'i')

As you can see from the syntax diagram:

The third argument to that function is the position, and the 'i' you're giving should be the fifth, match_param. Oracle is trying to interpret the letter i as a number since it expects one for the position argument, hence the error you're getting.
You need to supply the position and occurrence arguments too, e.g.:
REGEXP_SUBSTR(ADRS, '^\w+(\s?-\s?)\w+\s\w+', 1, 1, 'i')

I'm not sure you need the case-insensitive flag for that though; you do for the REGEXP_LIKE as you want to match ABBEY, Abbey, abbey etc., but it doesn't seem to be useful for the substring extraction; so you can also probably do:
REGEXP_SUBSTR(ADRS, '^\w+(\s?-\s?)\w+\s\w+')


text:
Q: Why fgets() works wrong? Here's my code
if(passwordCorretta(ds_sock)){
   printf("CLIENT: password aggiungi corretta\n");

   do{
      printf("Cognome >> ");
      fgets(cognome,sizeof(cognome),stdin);
      //scanf("%s", cognome);
      printf("Nome >> ");
      fgets(nome,sizeof(nome),stdin);
      //scanf("%s", nome);
      printf("Telefono >> ");
      fgets(telefono,sizeof(telefono),stdin);
      //scanf("%s", telefono);

in output print first the two printf,skipping first fgets(), why is that?
here's my output
CLIENT: password aggiungi corretta
Cognome >> Nome >> **my input
Telefono >> **my input

any ideas why? thanks
Here's my entire function
void main(){
int ds_sock, length, res;
struct sockaddr_in client;
struct hostent *hp;
char oper[2];

int risPwd;
int op;

char cognome[30];
char nome[20];
char telefono[12];

char continua[3];
char ris[2];
int trovato;
int aggiunto;

ds_sock = socket(AF_INET, SOCK_STREAM, 0);

client.sin_family = AF_INET;
client.sin_port = 1999;

hp = gethostbyname("localhost");  //indirizzo del server
memcpy(&client.sin_addr, hp->h_addr, 4);

res = connect(ds_sock, &client, sizeof(client));
if(res==-1) {
    perror("Errore nella connessione");
}

signal(SIGPIPE, gest_broken_pipe);
signal(SIGINT, gest_interruzione);

do{
    op=scelta();
    sprintf(oper,"%d",op);
    if(write(ds_sock, oper, sizeof(oper))<0){
        if(errno!=EINTR) perror("Errore di scrittura");
    }

    switch(op){
            case 1:
                printf("INSERIMENTO NUOVO CONTATTO\n");

                if(passwordCorretta(ds_sock)){
                    printf("CLIENT: password aggiungi corretta\n");

                    do{
                        printf("Cognome >> ");
                        fgets(cognome,sizeof(cognome),stdin);
                        //scanf("%s", cognome);
                        printf("Nome >> ");
                        fgets(nome,sizeof(nome),stdin);
                        //scanf("%s", nome);
                        printf("Telefono >> ");
                        fgets(telefono,sizeof(telefono),stdin);
                        //scanf("%s", telefono);
                        if(write(ds_sock, cognome, sizeof(cognome))<0){
                            if(errno!=EINTR) perror("Errore di scrittura");
                        }
                        if(write(ds_sock, nome, sizeof(nome))<0){
                            if(errno!=EINTR) perror("Errore di scrittura");
                        }
                        if(write(ds_sock, telefono, sizeof(telefono))<0){
                            if(errno!=EINTR) perror("Errore di scrittura");
                        }

                        if(read(ds_sock, ris, sizeof(ris))<0){
                            if(errno!=EINTR) perror("Errore di lettura");
                        }
                        trovato=atoi(ris);

                        switch(trovato){
                            case 0:
                                printf("Errore di lettura nel Server\n");
                                break;
                            case 1:
                                printf("Il contatto è già presente nell'elenco\n");
                                break;
                            case 2:
                                if(read(ds_sock, ris, sizeof(ris))<0){
                                    if(errno!=EINTR) perror("Errore di lettura");
                                }
                                aggiunto=atoi(ris);
                                if(aggiunto==0) printf("Errore di scrittura nel Server\n");
                                else printf("Il contatto è stato correttamente inserito nell'elenco\n");
                                break;
                        }

                        printf("Vuoi aggiungere un altro contatto? [SI/NO]\n");
                        scanf("%s", continua);
                        if(write(ds_sock, continua, sizeof(continua))<0){
                            if(errno!=EINTR) perror("Errore di scrittura");
                        }
                    }while(strcmp(continua, "SI")==0);

                }
                break;

            case 2:
                printf("RICERCA DI UN NUMERO TELEFONICO\n");

                if(passwordCorretta(ds_sock)){
                    printf("CLIENT: password cerca corretta\n");

                    do{
                        printf("Cognome >> ");
                        scanf("%s", cognome);
                        printf("Nome >> ");
                        scanf("%s", nome);
                        if(write(ds_sock, cognome, sizeof(cognome))<0){
                            if(errno!=EINTR) perror("Errore di scrittura");
                        }
                        if(write(ds_sock, nome, sizeof(nome))<0){
                            if(errno!=EINTR) perror("Errore di scrittura");
                        }

                        if(read(ds_sock, ris, sizeof(ris))<0){
                            if(errno!=EINTR) perror("Errore di lettura");
                        }
                        trovato=atoi(ris);

                        switch(trovato){
                            case 0:
                                printf("Errore di lettura nel Server\n");
                                break;
                            case 1:
                                if(read(ds_sock, telefono, sizeof(telefono))<0){
                                    if(errno!=EINTR) perror("Errore di lettura");
                                }
                                if(strcmp(telefono, "errore")==0) printf("Errore di lettura nel Server\n");
                                else printf("Il telefono del contatto richiesto è: %s\n", telefono);
                                break;
                            case 2:
                                printf("Il contatto non è presente nell'elenco\n");
                                break;
                        }

                        printf("Vuoi cercare un altro numero di telefono? [SI/NO]\n");
                        scanf("%s", continua);
                        if(write(ds_sock, continua, sizeof(continua))<0){
                            if(errno!=EINTR) perror("Errore di scrittura");
                        }
                    }while(strcmp(continua, "SI")==0);

                }
                break;

            case 3:
                printf("USCITA\n");
                break;

            case 0:
                printf("Eseguito lo SHUTDOWN del Server\n");
                break;
    }

}while(op!=3 && op!=0);

close(ds_sock);

}
i use 3 buffer named cognome,nome,telefono. ideas?

A: The problem is in your scelta() function. Both versions of it (with scanf() or fgets()) are wrong.
First I will explain why your fgets() version is wrong.
You declared comando as int, while fgets() expects a char *. This is undefined behavior, and you're lucky (or unlucky) it didn't crash.
As for your scanf() version: This is exactly what I predicted in the comments. scanf() only reads the integer input, and leaves the new line (ENTER key) in the input buffer. This means that your first fgets() call in main() is reading this left-over ENTER key.
One way of doing this correctly is as follows:
long int scelta() {
    char input[20];
    fgets(input, sizeof input, stdin); // this reads input
    while(strchr(input, '\n') == NULL) {
        // the input has not ended
        // it is probably not a long int anyway but you still need to consume it
        // choose your appropriate action, e.g.
        while(getchar() != '\n'); // read everything in input buffer up to (and including) the ENTER key
        puts("error");
        fgets(input, sizeof input, stdin); // read input again
    }
    char *endptr;
    long int comando = strtol(input, &endptr, 10);
    // then check range and check for errors with endptr
    return comando;
}

For a detailed description and example code (with error-checking) of strtol(), please refer to the Linux Programmer's Manual.

A: If it is supported by your system, the function fpurge cleans input streams and could be used in that case :
if(passwordCorretta(ds_sock)){
   fpurge(stdin);
   printf("CLIENT: password aggiungi corretta\n");

   do{

and do not try to use fflush because it only acts on output streams.
But anyway, you should try to understand where the unwanted input comes from. This is not far from a quick and dirty hack but at least is harmless is nothing was left in buffer.


text:
Q: Flask-soketio works partially upon deployment I have created simple chat based on Flask-Socketio, Vue.js and html/css. Application works fine locally, with socketio.run. But upon deployment the application work showing only rendering of html input and button. Background, chat window messages are missing.
Could you please help to understand the reason of the application displayed partially upon deployment?
Here is the server-side code:
import os
from os import environ
from dotenv import load_dotenv, find_dotenv
import eventlet
eventlet.monkey_patch()
from flask import Flask, render_template
from flask_socketio import SocketIO, emit, send
from flask import session

load_dotenv(find_dotenv())
app = Flask(__name__)
#Creating path to the file with secret key
app.config['SECRET_KEY'] = environ.get('KEY')
socketio = SocketIO(app, manage_session = False)

@app.route('/')
def index():
    return render_template('session.html')

@socketio.on('message')
def handle_message(msg):
    send(msg, broadcast = True)

@socketio.on('join')
def join_username(username):
    emit('message', {'user':'Chat', 'message':username  + ' joined this chatroom'}, broadcast = True)
    socketio.sleep(0)

if __name__ == '__main__':
    socketio.run(app, debug = True)

And heroky.yml:

build:
  docker:
    web: Dockerfile
run:
  web: gunicorn --worker-class eventlet -w 1 chat:app


text:
Q: Finding characters of a word in a string, optimized I am doing doing a few code challenges in the hope to learn some new stuff. Currently I have written a piece of code that find charachter of a given word in a string of random letters.
I thought regexp might be the best performance-wise (it's one of the objectives). This code passes the checks but takes too long with absurd long strings. Is there any way I can improve this? It's really ugly as is honestly. I've tried several approaches but I am probably just really a newbie at reg exp etc.
before all the if statements I only used regexp but if str2 which is the word I am looking for had double characters it would come back 'true' because it would count already counted characters. That is why I am using replace to exclude them. That's all I could get.
the goal is to return true if a portion of str1 can be rearranged to form str2, otherwise return false. Only lower case letters will be used (a-z). No punctuation or digits will be included. for example scramble('aabbcamaomsccdd','commas') should return true

function scramble (str1, str2)
{
var o = 0; // tracks amount of matched letters.
 for(i = 0; i < str2.length; i++)
 {
    var regex1 = new RegExp (str2[i]) ; // select letter from word that needs to be found
    if( regex1.test(str1) == true)// if selected character is found us replace to remove it from the random characters string for next iteration.
    {
      str1 = str1.replace(regex1 ,"");
      o++; // increment o if character is removed from random string.
    }
 }
//check if amount of removed characters equals total characters of word that we want.
    if ( o == str2.length)
    {
      return true
    }
    if (o !== str2.length)
    {
      return false
    }
}

Update: I flagged the hash table as answer because afaik this was not doable with regexp it seems also I was able to achieve a proper result with .split and loops myself plus the hash table also achieved this.

A: if-less methodology!
i didnt stress it on tests but looks fine
function scramble(str1, str2) {
  str1 = [...str1];
  return [...str2].filter((str => (str == str1.splice(str1.indexOf(str), 1)))).join('') == str2;

}

A: You could take a hash table, count the wanted characters and return if no count is not more necessary.

function scramble (str1, str2) {
    var counter = {},
        keys = 0;

    for (let i = 0; i < str2.length; i++) {
        if (!counter[str2[i]]) {
            counter[str2[i]] = 0;
            keys++;
        }
        counter[str2[i]]++;
    }

    for (let i = 0; i < str1.length; i++) {
        if (!counter[str1[i]]) continue;
        if (!--counter[str1[i]] && !--keys) return true;
    }
    return false;
}

console.log(scramble('abc', 'cba'));
console.log(scramble('abc', 'aba'));
console.log(scramble('abcdea', 'aba'));
console.log(scramble('aabbcamaomsccdd', 'commas'));


text:
Q: Copying Bit Interval From A Variable To An Array I have a setup of values stored in relatively bigger type of variables, which I have to store in again relatively smaller variables.
Here is the story of the problem: I have different sensor values in different types such as uint16_t, uint32_t and float. I want to store values separated in an uint8_t buffer array to transmit through an RF transmitter. For float type, I accept a finite significant value which then use integer multiplication to store it in an integer variable. Like this:
For this example, I want 3 digits after the comma,
float var1 = 12.3456789;
uint16_t var2;

var1 *= 1000;
var2 = (int) var1;

Which gives the output:
Var2: 12345 , Var1: 12345.679688

The summarization of the problem can be shown in the figure as,
Problem summarization
Where black boxes are uint8_t type of elements in a 32 bytes of buffer, orange boxes are uint16_t variables which I want to separate into two uint8_t variables.
I tried to use memcpy() as,
#include <stdio.h>
#include <stdint.h>
#include <string.h>

int main() {

    uint8_t buffer[32];
    uint16_t var1 = 64000;

    memcpy(&buffer[0], &var1, 1);
    memcpy(&buffer[1], &var1 + 1, 1);

    printf("var1: 0x%x\n\rbuffer[0]: 0x%x\n\rbuffer[1]: 0x%x", var1, buffer[0], buffer[1]);

    return 0;
}

Which gives the output:
var1: 0xfa00
buffer[0]: 0x0
buffer[1]: 0x0

I thought about using bitwise operators to somehow separate, but failed. It would be great if you have any possible solution for this problem.

A: So, when you do this:
memcpy(&buffer[0], &var1, 1);
memcpy(&buffer[1], &var1 + 1, 1);

You're effectively copying 1 byte of data each from &var1, and &var1 + 1.  So the big question here is "what is &var1 + 1?".
Since var1 is a uint16_t, taking the address gives you a uint16_t*, incrementing that pointer by one will jump forward two bytes rather than just one.
If you cast the result of &var1 to a uint8_t:
memcpy(&buffer[0], (uint8_t*)&var1, 1);
memcpy(&buffer[1], (uint8_t*)&var1 + 1, 1);

You will get a result that might be closer to what you're expecting:
var1: 0xfa00
buffer[0]: 0x0
buffer[1]: 0xfa

If you wanted to bitshift data, you could do something like this:
buffer[0] = var1 & 0xFF; // mask off top 8 bits
buffer[1] = var1 >> 8; // shift top 8 bits down to bottom 8 bits

Which yields the same result...
var1: 0xfa00
buffer[0]: 0x0
buffer[1]: 0xfa

Keep in mind that depending on your platform, you may run into endianness issues if the source of the data represents it differently than the consumer of the data.


text:
Q: Hierarchial edge bundling in d3 is not working on my mac I just downloaded d3 on my mac and started exploring the examples inside the folder by opening them in firefox. Most of them are working fine except bundle maps. Could any one please help me what is going on ?

A: I had this problem when I didn't simulate a web server on my machine where I put the code (like MAMP or XAMP). Try using MAMP and put the code in the htdocs folder.

A: If you're referring to this example, it uses XHR to get the JSON data to generate the graph, and that would result in an error due to attempting to access a local resource on your machine.


text:
Q: Errors in long IF statement This formula:
=IF(AND(A2<H2),(A2>=0),G2,IF(AND(A2<H3,A2>=H2),G3),(IF(AND(A2<H4,A2>=H3),G4),(IF(AND(A2<H5,A2>=H4),G5),IF(AND(A2<H6,A2>=H5),G6)

gives me the error, "You've entered too many arguments for this function".
I have no false statements; I just want them to execute when they are true.

A: You can troubleshoot a formula by simply looking at the prompts on the screen. The tooltip will tell you exactly where you are with regards to formula syntax and what is expected next.
Examples:

The cursor is in the middle of an AND() statement. The tooltip shows the current syntax element in bold. We are currently in the first logical condition of the AND(). The next expected entry is a comma and another logical condition. A closing bracket will close the AND() statement.
You continue with a closing bracket, so the AND() statement is closed and the formula continues with the next argument of the encasing IF() statement.

But you think you are still in the AND() function and provide another logical condition, which Excel interprets as the TRUE statement of the IF() function.

Excel now expects the FALSE statement of the IF function and then a bracket that closes the IF statement. You supply a cell reference and then a comma to continue with another IF. By this time you have entered too many arguments for the first IF statement. In the following screenshot, no argument is highlighted. Excel cannot place the current cursor position anywhere in the correct formula syntax.

If you watch the tooltips when you enter a formula, you can see that the AND statement was closed too early. Remove the superfluous brackets and see the tooltip now.

We are now in the FALSE statement of the first IF and start with another nested IF(). Continue in this way and see what the tooltip tells you and you will arrive at the correctly formed
 =IF(AND(A2<H2),(A2>=0),G2,IF(AND(A2<H3,A2>=H2),G3),(IF(AND(A2<H4,A2>=H3),G4),(IF(AND(A2<H5,A2>=H4),G5),IF(AND(A2<H6,A2>=H5),G6)

Watching Excel's helpful tips can save an awful lot of time in troubleshooting.

A: In addition to the AND(...) syntax problem previously mentioned, you are closing off the latter IF(...) statements too early.
=IF(AND(A2<H2,A2>=0),G2,IF(AND(A2<H3,A2>=H2),G3,IF(AND(A2<H4,A2>=H3),G4,IF(AND(A2<H5,A2>=H4),G5,IF(AND(A2<H6,A2>=H5),G6, "nothing matched")))))

... or,
=IF(AND(A2<H2,A2>=0),G2,IF(AND(A2<H3,A2>=H2),G3,IF(AND(A2<H4,A2>=H3),G4,IF(AND(A2<H5,A2>=H4),G5,IF(AND(A2<H6,A2>=H5),G6)))))

Put this into a text editor like Notepad (with line wrap OFF) and put your own formula in the line directly below it to compare the syntax.


text:
Q: How to run my a Java program as an executable .jar file? I was wondering how can I turn my program (which I am currently running from Eclipse) into an executable file?
This will make it more feasible as people with JRE can just access it by clicking on a single file.
Any help would be appreciated.
Thank you.

A: *

*Compile your java code

*Create a manifest.txt file.

*Specifiy the main class in the manifest file like: Main-Class: com.example.Main

*Create a jar by adding the manifest.txt and required .class files: jar cvfm myJar.jar manifest.txt *.class

Note: make sure to add .class files, not .java files.

A: You may create this as a maven project and then simply run mvn clean package and the jar will be created in target directory.


text:
Q: Comparing logarithmic functions. Master Method I'm learning the master method and am looking for help on how to best approach comparing two functions asymptotically.  More specifically, I have:
T(n) = 3T(n/5) + lg^2(n)

and so by the Master method I am comparing
n^(log_5(3))  with  lg^2(n)

I tried graphing the two functions and it looks like lg^2(n) is larger.  But the solution says otherwise. (ie. Case 1.)  Can anyone help clear the fog for me? Thanks.

A: Define $u_n=(\log_53)\cdot\log n$ and $v_n=2\cdot\log\log n$, then $n^{\log_53}=\mathrm e^{u_n}$ and $(\log n)^2=\mathrm e^{v_n}$. Can you show these identities? Next, can you compare $u_n$ and $v_n$ when $n\to\infty$? What does this tell you about $n^{\log_53}$ and $(\log n)^2$ when $n\to\infty$?


text:
Q: Why numpy.ndarray.data is toggle? I'm using python 3.6.7 create a 1-D array, and print its data attribute, and found it is toggle.
But why?
>>> a = np.arange(12)
>>> print(a)
[ 0  1  2  3  4  5  6  7  8  9 10 11]
>>> a.data
<memory at 0x7fef79ae8f48>
>>> a.data
<memory at 0x7fef79505048>
>>> a.data
<memory at 0x7fef79ae8f48>


text:
Q: unclear what you're asking vs. too broad closing reasons
unclear what you're asking
  Please clarify your specific problem or add additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking.
too broad
  There are either too many possible answers, or good answers would be too long for this format. Please add details to narrow the answer set or to isolate an issue that can be answered in a few paragraphs.

What is the difference between these two closing reasons? Both need more details to be answered and I am often confused which one to choose.
I often leave such questions open unless they are very blurred - in hope that the OP may provide missing details. Is this appropriate attitude? Both descriptions contain "please do something with your question".
It looks like there is often high chance to improve it to be valid on SO. Is it really necessary to push it into close-reopen process? There are 56k+ closing requests and rising. Shouldn't be such questions eligible to close for those reasons after say 1 hour?

A:
What is the difference between these two closing reasons?

Unclear what you're asking:
"I have read this question multiple times, but I still have no idea what the actual question is. You should really clarify this.".
Too broad:
"I have read and understood the question, but to answer it would require an amount of effort and content that can not be expected in the scope of Stack Overflow/Stack Exchange".

I often leave such questions open unless they are very blurred - in hope that the OP may provide missing details. Is this appropriate attitude?

Well, it's really up to you, but I'd say "no". Close if they should be closed. But if you don't know how it should be closed, feel free to abstain from voting. And with regards to the close vote queue, simply voting to close less is not a solution. It only leaves problems in place.

Is it really necessary to push it into close-reopen process? ... Shouldn't be such questions eligible to close for those reasons after say 1 hour?

Close early. This prevents users from wasting effort on a question which needs to be changed anyway to hang around. And it provides the OP the time to update their question to be more clear and in line with what we consider a good question. And no, this should not be delayed for an hour. Closure (or putting a question "on hold") is not necessarily a final destination.


text:
Q: finally: txt.close() SyntaxError in Python I can not use finally:txt.close() to close a txt file. Please help me out. Thank you!
txt = open('temp5.txt','r')
for i in range(5):
    try:
        10/i-50
        print(i)
    except:
        print('error:', i)

finally:
    txt.close()

Error:
  File "C:\Users\91985\AppData\Local\Temp/ipykernel_12240/2698394632.py", line 9
    finally:
    ^
SyntaxError: invalid syntax

I was confused because this part was good without error:
txt = open('temp5.txt','r')
for i in range(5):
    try:
        10/i-50
        print(i)
    except:
        print('error:', i)

Output:
error: 0
1
2
3
4

A: Do you really need using open() and close()? I suggest you to use context managers, that will make your life easier:
with open("temp5.txt") as file:
    # Logic, exception handling, ...

A: Your try and except blocks exist only in your for loop and are executed for every iteration of the loop. Because of this, your finally block will not work as it has no try or except part. If you want to close the file after the loop, you can omit the finally block and just have txt.close() after the for loop:
txt = open('temp5.txt','r')
for i in range(5):
    try:
        10/i-50
        print(i)
    except:
        print('error:', i)
txt.close()

Additionally, you could also open the file using with to close it automatically:
with open("temp5.txt") as txt:
    for i in range(5):
        try:
            10/i-50
            print(i)
        except:
            print('error:', i)


text:
Q: Setting the default select option for object data sources You can use track by to label set the default selected option with array data sources: http://plnkr.co/edit/tWr53XfvBIgtntMyZAeK?p=preview.
Yet that doesn't seem to be possible with object data sources: http://plnkr.co/edit/jji4ulB2EzushseFw8vY?p=preview
How can I set the default option with an object data source?

A: The trick is to use a string to set the default option: http://plnkr.co/edit/eXZQnVZ4DKjqd5t9luOy?p=preview
Instead of:
$scope.myColor = 1;

Use:
$scope.myColor = '1';


text:
Q: number of real roots of equation involving derivative and double derivative
Let $k:\Bbb R\to\Bbb R$ be a twice differentiable function such that $ k(a)=k(e)=0 ,k(b)=k(d)=2 , k(c)=1$, where $a<b<c<d<e$.
Find the minimum number of solutions of $(k'(x))^2+k(x)k''(x)=0$ in $[a,e]$.

Try:  By drawing Rough graph. We have  $k(x)=0$ for $x=a,b$.
and for $K'(x)=0$ for at least $3$ values of $x$
And we can write $(k'(x))^2+k(x)k''(x)=(k(x)\cdot k'(x))'$
so from above data we have $k(x)\cdot k'(x)=0$ for at least $5$  values of $x$
so using Rolles theorem , we have $(k'(x))^2+k(x)k''(x)=0$ for at least $4$ values of $x$
could some please explain me , whats wrong in my solution, thanks

A: Your argument is fine.
Moreover, if you let $$k(x)=-x^6+ 2x^2+1$$
then the requirements are satisfied with
$(a,b,c,d,e)=(-\sqrt{\frac{1+\sqrt5}{2}},-1,0,1,\sqrt{\frac{1+\sqrt5}{2}})$,
and there are only $4$ points where $k'^2+kk''$ vanishes on $[a,e]$.
This shows that $4$ is a sharp lower bound.


text:
Q: Mongoose getting newly saved object id off by one I'm using the latest version of mongoose.
var question = new CodingQuestion(reqJSON);
question.save(function(err) {
    if (err) console.log(err);
    else{
        var questionId = question.id;
        console.log("successfully added question with id", questionId);
    }
});

The new object can be saved successfully. The problem is that when I try to obtain the newly added object Id, the value I get is always off by one. For example, the value logged in console is "5356b2162f8a71c00ae48783" but the actual value in the database is "5356b2162f8a71c00ae48784".
Any idea what may cause this problem?

A: I think you are not getting the ID of the saved document. The anonymous function you pass the  save function takes two parameters, error and saved_document.
Try the following:
question.save(function(err, savedQuestion) {
    if (err) console.log(err);
    else{
        var questionId = savedQuestion._id;
        console.log("successfully added question with id", questionId);
    }
});

A: We just ran into this issue.  When you use the new operator it will create an objectID in mongoose.  This is ignored when you call .save() where it will then use the next available objectID, hence it is off by one.


text:
Q: About the proof of Cayley's Theorem I'm reading a proof of Cayley's theorem. In the following two snippets I want to know why it's needed(although it's apparently true) that $\pi_a\circ\pi_b=\pi_{ab}$ to prove that $G^*$ is closed under composition?
I meant, why not just said: Since $a,b\in G, ab\in G$ so by the construction of $\pi_a:G\to G$ clearly $\pi_{ab}\in G^*$.

At the end of the proof the equality is used, so I wonder whether the author just want to condense two steps into one? (I skip the part of $G^*$ is closed on its inverse)

A: You're right that it is clear that $\pi_{ab} \in G^*$. But we want $G^*$ to be closed under the group operation of $G^*$, in which the product of $\pi_a$ and $\pi_b$ is defined to be $\pi_a \circ \pi_b$, not $\pi_{ab}$.
Once we prove that these two are equal - that $\pi_a \circ \pi_b = \pi_{ab}$ - then we know that $G^*$ is closed under $\circ$, precisely because we know that $\pi_{ab} \in G^*$.

A: To prove that $G^*$ is a subgroup of the group of permutations on the set $G$ one should prove that for every $a,b \in G$ there is a $c \in G$ such that $$\pi_a\circ\pi_b=\pi_{c}$$
So the proof needs to provide a way to choose a $c\in G$ such that indeed $\pi_a\circ\pi_b=\pi_c$ holds. The element $c=ab$ is a natural choice.
The apparent complication with this subgroup stuff is due to the fact that the authors wanted to have $G^*$ as the image of the homomorphism, probably because they are interested to show that $\pi$ is an isomorphism.
A different approach could have been to see $\pi$ as an injective homomorphism from $G$ into the group of permutations on $G$ and then simply use that fact that the image of this homomorphism (namely $G^*$) is isomorphic to the starting group ($G$).
In this case one use the fact that the image of an homomorphism is a group to prove that $G^*$ is a group.
Hope this helps.


text:
Q: How to have only one input selected in a tr? Here's an fiddle example: http://jsfiddle.net/YxU2H/9/
I'm trying to just have one checkbox or one radio button selected in the row. What I've tried doesnt work:
function selectedBox() {
      var bothChecked = false;
      var row = $(this).closest('tr');

      var isCboxChecked = $('row', '#cbox').is(':checked');
      var isRadChecked = $('row', '#rad').is(':checked');

      //var isCboxChecked = $('#cbox').is(':checked'); //true or false
      //var isRadChecked = $('#rad').is(':checked');

      if (first == second) {
          bothChecked = true;
          //keep checkbox selected but deselect radio button
      }
      if (bothChecked == true) {
          $('#cbox').attr('checked', false);
      }
      else {
          $('#cbox').attr('checked', true);
      }
  } //);

Then I just added an onclick="selectedBox();" to the checkboxes and buttons. Checkboxes had a id of cbox, and radio buttons had rad

A: Instead of $('#cbox').attr('checked', false); try
  if (bothChecked == true) {
      $('#cbox').removeAttr('checked');
  }
  else {
      $('#cbox').attr('checked', 'checked');
  }

Edit
The complete solution would be like this
$("input:checkbox, input:radio").click(function(e) {

    var row = $(this).closest('tr');

    var chkBox = $(row).find(":checkbox");
    var rdBtn = $(row).find(":radio");

    if ($(chkBox).is(":checked") & $(rdBtn).is(":checked")) {
      $(chkBox).removeAttr('checked');
    }
});

I put it on here jsfiddle

A: you can put these two functions within document.ready block
$('input[type="radio"]').click(function() {
    if ($(this).attr('checked') == 'checked') {
        var chk = $(this).closest('tr').find('input[type="checkbox"]:checked');
        if (chk.length > 0) {
            $(chk).removeAttr('checked');
        }
    }
});

$('input[type="checkbox"]').click(function() {
    if ($(this).attr('checked') == 'checked') {
        var rad= $(this).closest('tr').find('input[type="radio"]:checked');
        if (rad.length > 0) {
            $(rad).removeAttr('checked');
        }
    }
});

Both monitor each others, so you will get your functionality. try it, worked for me. I have updated your fiddle. Here it is http://jsfiddle.net/YxU2H/20/


text:
Q: Passing an env. variable dynamically to Application module, at runtime? In my opt application I have some stuff that gets run on application boot:
    defmodule MyApp.Application do
      use Application

      def start(_type, _args) do
        children = [
          {Phoenix.PubSub, [name: MyApp.PubSub, adapter: Phoenix.PubSub.PG2]},
          {MyAppLib.Repo, []},
          {MyAppWeb.Endpoint, []},
          {MyAppLib.Cache, []},

          # these are GenServer-s, some may work with a database

          {MyApp.Worker1, []},      # 1
          {MyApp.Worker2, []},      # 2
          {MyApp.Initializer, []}   # 3

        ]

        opts = [strategy: :one_for_one, name: MyApp.Supervisor]
        Supervisor.start_link(children, opts)
      end

However, I've found out that whenever I deploy the app on a new server, it'll fail to start up because a database hasn't been created yet. And even starting the application via console won't solve the problem because it'll still crash due to the same reason.
How to fix it?

Should I introduce a boolean env. variable "disable_db_related_workers" which I'd set to 'true' only when running the app the first time on a new server? Then I'd run console and from it I'd run the migrations.
$ MIX_ENV=prod DISABLE_DB_WORKERS=true ~/my_apps/my_app1/bin/my_app1 console

If so, how to do this properly inside Application then? It'll have to be evaluated at runtime, that is, not at compilation.

A: Ecto.Migrator.up/4 is your friend.
It might be called from Application.start/2 directly because it's idempotent. It might be called before starting the application right after deploy.
Besides this advice, the real implementation is actually a matter of taste.


text:
Q: Using a loop to select multiple images, process and then output to a directory at the moment, the below code extracts faces from a single image and then outputs those faces to a folder. How can I input a directory full of images and do the same thing? I can't seem to add a directory into the image - face_recognition.load_image_file(C:/directory) as it keeps coming back with permission denied error. Is there a way I can ask it to loop through all the images in a particular directory and then output them to my path?
from PIL import Image
import face_recognition

image = face_recognition.load_image_file(r"C:\Users\Julio\Desktop\Face Extraction\Input\IMG_0421.JPG")
path = r"C:\Users\Julio\Desktop\Face Extraction\Output\face"

face_locations = face_recognition.face_locations(image)

print("I found {} face(s) in this photograph.".format(len(face_locations)))

face_counter = 0
for face_location in face_locations:
    top, right, bottom, left = face_location
    print("I found a face in image location Top: {}, Left: {}, Bottom: {}, Right: {}".format(top, left, bottom, right))

    face_image = image[top:bottom, left:right]
    pil_image = Image.fromarray(face_image)
    pil_image.save(str(path) + str(face_counter) + ".jpg")
    face_counter += 1

A: I did something similar recently which I hope will be of help to you.  I basically set my path to a variable, then the listdir of that path to a variable called img_list, then cycled through that:
# media thumbnails
path = "/media/default_thumbnails/"
img_list = listdir(path)

for image in img_list:
    """
    Need to open an image file from the directory as a PIL Image.
    Then create a BytesIO and save that as the thumbnail.
    """
    try:
        img = PILImage.open(path + image)
        rawfile = BytesIO()
        img.save(rawfile, format='jpeg')
        mt = MediaThumbnail.objects.create()
    mt.thumbnail.save(image, rawfile)
    rawfile.close()
except:
    print(f"   skipping {image}")
print("   thumbnails created")

To integrate that into your code you'd do something like:
from PIL import Image
import face_recognition

path = "C:\Users\Julio\Desktop\Face Extraction\Input"
img_list = listdir(path)

for input_img in img_list:

    image = face_recognition.load_image_file(input_img)
    [.... the rest of your code ]


text:
Q: compare count of two mysql queries in one query I've got stuck some where in mysql query. I'm having two queries and both are returning results fine.
My requirement is I want to use both query in one query so that I could compare count of both queries.
1st query
SELECT
      user_profile.USERID,
      user_profile.FIRSTNAME,
      user_profile.LASTNAME,
      lastvisit.lastvisit,
      lastvisit.SOURCE as "RegistrationPlatform"
    FROM user_profile
    INNER JOIN lastvisit
   ON user_profile.USERID =lastvisit.USERID
    WHERE MONTH(lastvisit.lastvisit) = 5 AND YEAR(lastvisit.lastvisit) = 2016
    AND lastvisit.SOURCE IN ('Online', 'MobileApp')

2nd query
SELECT
      user_profile.USERID,
      user_profile.FIRSTNAME,
      user_profile.LASTNAME,
      user_profile.registrationDate,
      lastvisit.SOURCE as "RegistrationPlatform"
    FROM user_profile
    INNER JOIN lastvisit
   ON user_profile.USERID =lastvisit.USERID
    WHERE MONTH(user_profile.registrationDate) = 5 AND YEAR(user_profile.registrationDate) = 2016
    AND lastvisit.SOURCE IN ('Online', 'MobileApp')

Output should be like this
Query   UserCount
Query1  100
Query2  200

Any suggestions please ?
Thanks

A: use Count(*) and Union
SELECT
    'query1' as query
    Count(*) as UserCount
    FROM user_profile
    INNER JOIN lastvisit
   ON user_profile.USERID =lastvisit.USERID
    WHERE MONTH(lastvisit.lastvisit) = 5 AND YEAR(lastvisit.lastvisit) = 2016
    AND lastvisit.SOURCE IN ('Online', 'MobileApp')
UNION
SELECT
    'query2' as query
    Count(*)
    FROM user_profile
    INNER JOIN lastvisit
   ON user_profile.USERID =lastvisit.USERID
    WHERE MONTH(user_profile.registrationDate) = 5 AND YEAR(user_profile.registrationDate) = 2016
    AND lastvisit.SOURCE IN ('Online', 'MobileApp')


text:
Q: C# Won't display size in subdirectorys I call the following function to check a specific path and get a list from all the folders located in the given path, for each folder it will check what the folder size is.
This works if i have a file in the folder like this.

Givenfolderpath\Underlying_folder\file.txt

But when there is a subdirectory with a file in it, it will not give me the size of the folder.

Givenfolderpath\Underlying_folder\subdirectory\file.txt

This is my code.
public void ListFolders()
    {
        dataGridView1.Rows.Clear();
        DirectoryInfo di = new DirectoryInfo(Properties.Settings.Default.RevitPath);
        DirectoryInfo[] diArr = di.GetDirectories();

        foreach (DirectoryInfo dri in diArr)
        {
            string strCreateTime = dri.LastWriteTime.ToString();
            string strCreateDate = dri.LastWriteTime.ToString();
            string strCreateSize2 = null;
            string strCreateSizeMb = null;
            int strCreateSize3;

            long strCreateSize1 = GetDirectorySize(Properties.Settings.Default.RevitPath + @"\" + dri);
            string strCreateSize = GetSizeReadable(strCreateSize1);

            strCreateTime = strCreateTime.Remove(strCreateTime.LastIndexOf(" "));
            strCreateDate = strCreateDate.Remove(0,strCreateDate.LastIndexOf(" "));
            strCreateSize2 = strCreateSize.Remove(strCreateSize.LastIndexOf(" "));
            strCreateSizeMb = strCreateSize.Remove(0, strCreateSize.LastIndexOf(" "));
            strCreateSize3 = Convert.ToInt32(strCreateSize2);

            if (strCreateSizeMb == " Mb")
            {
                if (strCreateSize3 >= Properties.Settings.Default.FolderSize)
                {
                    notifyIcon1.ShowBalloonTip(20000, "Attention Required!", dri + " exceed the permissible size " + Properties.Settings.Default.FolderSize + " Mb", System.Windows.Forms.ToolTipIcon.Warning);
                }
            }

            int idx = dataGridView1.Rows.Add();
            DataGridViewRow row = dataGridView1.Rows[idx];
            row.Cells["User"].Value = dri;
            row.Cells["Date"].Value = strCreateTime;
            row.Cells["Time"].Value = strCreateDate;
            row.Cells["Size"].Value = strCreateSize2;
            row.Cells["SizeMB"].Value = strCreateSizeMb;
        }

Where does it go wrong?
It will put the data like this.

static long GetDirectorySize(string p)
        {
            // 1
            // Get array of all file names.
            string[] a = Directory.GetFiles(p, "*.*");
            // 2
            // Calculate total bytes of all files in a loop.
            long b = 0;
            foreach (string name in a)
            {
                // 3
                // Use FileInfo to get length of each file.
                FileInfo info = new FileInfo(name);
                b += info.Length;
            }
            // 4
            // Return total size
            return b;
        }

A: Try replacing the line
DirectoryInfo[] diArr = di.GetDirectories();

with
DirectoryInfo[] diArr = di.GetDirectories("*", SearchOption.AllDirectories);

That should iterate over all directories contained in the given one. See for reference MSDN: DirectoryInfo.GetDirectories Method (String, SearchOption) and MSDN: SearchOption.


text:
Q: Magic Square program Java with array I want to program a Magic Square wherein the utilization of arrays is at place but when i want to run it, it shows Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
        at MagicSquare.main(MagicSquare.java:6)
What should I do? It would show
4   9   2        7 1 6
3   5   7  not   3 5 7
8   1   6        4 9 2

public static void main(String[] args) {
    Scanner input = new Scanner (System.in);

    int n = Integer.parseInt(args[3]);
    if (n % 2 == 0) throw new RuntimeException("n must be odd");

    int[][] magic = new int[n][n];

    int row = n-1;
    int col = n/2;
    magic[row][col] = 1;

    for (int i = 2; i <= n*n; i++) {
        if (magic[(row + 1) % n][(col + 1) % n] == 0) {
            row = (row + 1) % n;
            col = (col + 1) % n;
        }
        else {
            row = (row - 1 + n) % n;

        }
        magic[row][col] = i;
    }

    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            if (magic[i][j] < 10)  System.out.print(" ");
            if (magic[i][j] < 100) System.out.print(" ");
            System.out.print(magic[i][j] + " ");
        }
        System.out.println();
    }

}

What else should I add or take away from this program?

A: According to your program, need to provide 4 arguments when running. ex: If class name is Test:
java Test 1 1 1 3

Result:
  4   9   2
  3   5   7
  8   1   6


text:
Q: Why isn't my function appending a key-value to the dictionary? So I defined this function that queries you about the name of a country and then gives you a fun fact about it. It's supposed to ask you if you want to add the country you asked about to the dictionary (if it doesn't already know it). I think the code is just fine. But it doesn't really add the new country-fact to the dictionary after it asks you :/ Can someone please identify the problem?
def countries():
    param = input("please enter the country you'd like a fun fact about")
    listofcountries = {"Kuwait": "has 10% of the world's oil reserves.", "UAE": "has the world's highest free-standing structrure, Burj Khalifa.", "Qatar": "is hosting the FIFA 2022 world cup.", "Saudi Arabia": "is the largest GCC country.", "Bahrain": "held the Dilmun civilization, one of the world's oldest civilizations.", "Oman": "is known for its beautiful green mountains."}
    if (param in listofcountries):
        print ("I know something about", param)
        print (param, listofcountries[param])
    else:
        print ("I don't know anything about", param)
        add_yesorno = input("Would you like to add something to the list? (yes or no)")
        if add_yesorno == 'yes':
            country_name = input("What's its name again?")
            add_yes = input("please finish this sentence. This country...")
            print ("Thanks a lot for contributing to the list!")
            listofcountries[country_name] = add_yes
        else:
            print ("Thanks then! See you later.")

A: listofcountries is a local variable, and as such will be reset every time you call the function. You need to make it global (or some other higher scope) if you want it to persist its value between calls.
listofcountries = {"Kuwait": "has 10% of the world's oil reserves.", "UAE": "has the world's highest free-standing structrure, Burj Khalifa.", "Qatar": "is hosting the FIFA 2022 world cup.", "Saudi Arabia": "is the largest GCC country.", "Bahrain": "held the Dilmun civilization, one of the world's oldest civilizations.", "Oman": "is known for its beautiful green mountains."}

def countries():
    param = input("please enter the country you'd like a fun fact about")
    if (param in listofcountries):
        print ("I know something about", param)
        print (param, listofcountries[param])
    else:
        print ("I don't know anything about", param)
        add_yesorno = input("Would you like to add something to the list? (yes or no)")
        if add_yesorno == 'yes':
            country_name = input("What's its name again?")
            add_yes = input("please finish this sentence. This country...")
            print ("Thanks a lot for contributing to the list!")
            listofcountries[country_name] = add_yes
        else:
            print ("Thanks then! See you later.")

Also note that I changed all instances of input to raw_input. You want to read in a string, so you definitely want raw_input. The input function will actually evaluate the input, turning it into a symbol or a raw literal value.
As per the comment below, I've reverted to input since apparently that's the correct function in Python 3.

A: Well, listofcountries is a local variable in function countries().  When the function returns, your dictionary disappears!  Along with all the other local variables (like param and add_yes).
Better to define listofcountries outside the function, as a module global.  Then listofcountries will retain its value across calls to countries.
More advanced is to create a class, and store the dict as an attribute of the class.  But, short of that, a making it a module global should fix your problem quickly.

A: listofcountries is local and gets reset each time. You can use an argument with a default value to persist across calls, which allows you to cache any results without polluting the global namespace:
def countries(listofcountries = {}):
    defaultlist = {"Kuwait": "has 10% of the world's oil reserves.", "UAE": "has the world's highest free-standing structrure, Burj Khalifa.", "Qatar": "is hosting the FIFA 2022 world cup.", "Saudi Arabia": "is the largest GCC country.", "Bahrain": "held the Dilmun civilization, one of the world's oldest civilizations.", "Oman": "is known for its beautiful green mountains."}
    if not listofcountries:
        listofcountries.update(defaultlist)
    ...


text:
Q: Concatenating data and text on select mysql Fellows,
I'm using PHP and this code:
SELECT DATE_FORMAT(data,'%d/%m/%Y'' às ''%H:%i:%s') as data FROM infografico GROUP BY data

Displays something like this:
(última atualização: 22/09/2016' às '09:37:16)

The question is: how can the ' doesn't appear?

A: SELECT DATE_FORMAT(data,'%d/%m/%Y'' às ''%H:%i:%s') as data FROM infografico GROUP BY data
                        ^--start string
                                 ^^--escaped quote
                                       ^^--escaped quote
                                                 ^---end of string

The string delimiters are parsed away by MySQL, and then the '' are parsed down to ' for output purposes, because they're not string delimiters - they're treated as a literal quote character. If you want more quotes, you need this ugly construct:
DATE_FORMAT(data, '''%d etc... ''')

e.g.
mysql> select '''foo''bar''';
+-----------+
| 'foo'bar' |
+-----------+
| 'foo'bar' |
+-----------+
1 row in set (0.00 sec)

A: You just need one single quotation mark at the beginning and end
SELECT DATE_FORMAT(data,'%d/%m/%Y às %H:%i:%s')

A: From String Literals (emphasis mine):

There are several ways to include quote characters within a string:

*

*A "'" inside a string quoted with "'" may be written as "''".

*A """ inside a string quoted with """ may be written as """".

*Precede the quote character by an escape character ("\").

*A "'" inside a string quoted with """ needs no special treatment and need not be doubled or escaped. In the same way, """ inside a string
  quoted with "'" needs no special treatment.

But I suspect you wanted to use this other syntax:

Quoted strings placed next to each other are concatenated to a single
  string. The following lines are equivalent:
'a string'
'a' ' ' 'string'

For that, you are missing spaces:
mysql> SELECT '%d/%m/%Y'' às ''%H:%i:%s' as quotes, '%d/%m/%Y' ' às ' '%H:%i:%s' as no_quotes;
+------------------------+----------------------+
| quotes                 | no_quotes            |
+------------------------+----------------------+
| %d/%m/%Y' às '%H:%i:%s | %d/%m/%Y às %H:%i:%s |
+------------------------+----------------------+
1 row in set (0.00 sec)

Of course, as already pointed out, you don't really need to insert quotes manually if you want none.


text:
Q: Understanding sp_spaceused values: reserved and index_size I'm running the following simple script:
create table MyTable (filler char(10))
go

insert into MyTable (filler) values ('a')
go 1

exec sp_spaceused MyTable
go

drop table MyTable
go

and get the following result:
rows   reserved   data   index_size    unused
------ ---------- ------ -----------   -------
1      72 KB      8 KB   8 KB          56 KB

My questions:

*

*Why 72 KB were reserved?

*Why index_size is 8 KB if the table is not even indexed?
EDIT:
I'd like to add a follow-up:
When changing the script a little:
create table MyTable (filler char(69))
go

insert into MyTable (filler) values ('a')
go 100

I get:
rows   reserved   data   index_size    unused
------ ---------- ------ -----------   -------
100    72 KB      16 KB   8 KB          48 KB

Note that defining filler's size to 68 bytes (and inserting 100 rows) still gives 8KB as the data value (we can continue and set it to 148 bytes, which will result in another 8KB increment, i.e. to 24KB).
Can you help me break down the calculation? If (apparently) only 6,900 bytes are used, What is the cause for the 8KB addition?
EDIT #2:
Here's the results of DBCC PAGE:
PAGE: (1:4392)

BUFFER:

BUF @0x00000000061A78C0

bpage = 0x00000001EF3A8000          bhash = 0x0000000000000000          bpageno = (1:4392)
bdbid = 6                           breferences = 0                     bcputicks = 0
bsampleCount = 0                    bUse1 = 18482                       bstat = 0x9
blog = 0x15ab215a                   bnext = 0x0000000000000000          bDirtyContext = 0x0000000000000000
bstat2 = 0x0

PAGE HEADER:

Page @0x00000001EF3A8000

m_pageId = (1:4392)                 m_headerVersion = 1                 m_type = 1
m_typeFlagBits = 0x0                m_level = 0                         m_flagBits = 0x8200
m_objId (AllocUnitId.idObj) = 260   m_indexId (AllocUnitId.idInd) = 256
Metadata: AllocUnitId = 72057594054967296
Metadata: PartitionId = 72057594048151552                                Metadata: IndexId = 0
Metadata: ObjectId = 1698105090     m_prevPage = (0:0)                  m_nextPage = (0:0)
pminlen = 72                        m_slotCnt = 100                     m_freeCnt = 396
m_freeData = 7596                   m_reservedCnt = 0                   m_lsn = (55:8224:2)
m_xactReserved = 0                  m_xdesId = (0:0)                    m_ghostRecCnt = 0
m_tornBits = -2116084714            DB Frag ID = 1

Allocation Status

GAM (1:2) = ALLOCATED               SGAM (1:3) = NOT ALLOCATED          PFS (1:1) = 0x44 ALLOCATED 100_PCT_FULL
DIFF (1:6) = CHANGED                ML (1:7) = NOT MIN_LOGGED

Slot 0 Offset 0x60 Length 75

Record Type = PRIMARY_RECORD        Record Attributes =  NULL_BITMAP    Record Size = 75

Memory Dump @0x0000000012A3A060

0000000000000000:   10004800 61202020 20202020 20202020 20202020  ..H.a
0000000000000014:   20202020 20202020 20202020 20202020 20202020
0000000000000028:   20202020 20202020 20202020 20202020 20202020
000000000000003C:   20202020 20202020 20202020 010000                         ...

Slot 0 Column 1 Offset 0x4 Length 68 Length (physical) 68

filler = a

-- NOTE: The structure of each Slot is identical to that of Slot #0, so we can simply jump to slot 99:

Slot 99 Offset 0x1d61 Length 75

Record Type = PRIMARY_RECORD        Record Attributes =  NULL_BITMAP    Record Size = 75

Memory Dump @0x0000000012A3BD61

0000000000000000:   10004800 61202020 20202020 20202020 20202020  ..H.a
0000000000000014:   20202020 20202020 20202020 20202020 20202020
0000000000000028:   20202020 20202020 20202020 20202020 20202020
000000000000003C:   20202020 20202020 20202020 010000                         ...

Slot 99 Column 1 Offset 0x4 Length 68 Length (physical) 68

filler = a

So we can see the last slot starts after 7521 bytes, and adding its size gives us 7,596 bytes. If we add the size of the slot array (in which each pointer is 2 bytes), we get 7,796 bytes.
However, we need to get to 8,192 bytes to fill the page. What's missing?

A: The 72K of reserved space includes a 64K extent (8 pages of 8K each) plus the 8K IAM page overhead. Of this 72K, only the IAM page and a single data page is actually used.  sp_space_used reports the IAM page in the index_size, albeit not technically an index. You can see these details with the undocumented sys.dm_db_database_page_allocations TVF (use only on a test system):
SELECT extent_file_id, extent_page_id, page_type_desc
FROM sys.dm_db_database_page_allocations(DB_ID(), OBJECT_ID(N'dbo.MyTable'), 0, 1, 'DETAILED');

This database apparently has the MIXED_PAGE_ALLOCATION database option set to OFF so a full 64K extent is allocated a initially. If the option were ON, the single data page would be allocated from a mixed extent instead of a 64K extent dedicated to the table. The space allocated in that case would be 16K - a 8K single data page plus the IAM page.
Although mixed extents do reduce space requirements for small tables (under 64K), mixed extents have more overhead and can cause allocation contention in a high concurrency workload so it is off by default in SQL 2016 onwards. In older SQL versions, mixed extent allocation was on by default and can be turned off at the server level with trace flag 1118.
You can see the mixed extent setting in sys.databases:
SELECT name, is_mixed_page_allocation_on
FROM sys.databases;

To toggle the setting:
ALTER DATABASE Test
    SET MIXED_PAGE_ALLOCATION ON;

EDIT 1:
Space within a data page includes overhead for the page itself as well as records within the page. This overhead, plus the space needed for user data, will determine how many rows can fit on a page and number of data pages required to store a given number of rows.  See Paul Randal's anatomy of a page and anatomy of a record articles for details of that overhead.
EDIT 2:
From your follow-up comment:

7998 bytes, so there are more 194 bytes to go for the next allocation.
  What am I missing?

I almost never use heaps but as you can see in the page dump, the associated PFS (page free space) allocation status for this page is 100 percent full. According to Kalen Delaney's Microsoft SQL Server 2012 Internals book, the PFS status is actually a 3-bit mask of these ranges:

*

*000: empty

*001: 1-50% full

*010: 51-80% full

*011: 81-95% full

*100: 96-100% full

So it looks like once heap page fullness crossed the 96% percent threshold it was considered 100% full and a new page was allocated.  Note this does not happen on a table with a clustered index because the page for a new row is first determined by the CI key and a new page allocated only if it can't fit in that page at all. Yet another reason to avoid heaps.


text:
Q: I want to know the number of times the same image has been added to the ListBox of images I have a ListBox of images. I want to know the  number of times the same image has been added to that ListBox. Any solutions?

A: If you want to check that the image itself, regardless of the file name, is not repeated then generate an MD5 checksum for the image data and store that.
If you want to make sure that the two are always linked then either tag it onto the end of the file or create a class which holds the image and the checksum together.
The MD5 check can be used to differentiate any data file, even different versions of the same file if the content is in anyway different.


text:
Q: querying couchbase with spring-data-couchbase, using multiple columns I am using couchbase3 with spring-data-couchbase, and want to query data using spring data repository with multiple columns.
public interface UserAccountRepository extends CrudRepository<UserAccount, Long> {
public UserAccount findByEmail(Query eMail);
public UserAccount findByEmailAndStatus(Query query); // fn with multiple column, but not getting the result
}

How should I write Map function and Reduce function for the same?
For the function findByEmail(Query eMail); to work, I have added the view with Map fn()
function (doc, meta) {
  emit(doc.email,doc);
}

This view have email as key, and value is the document.
But if i need to query using email and status? How should the view look like ?
I have seen this link, but not very clear.
https://stackoverflow.com/questions/28938755

A: I was able make springdata function to invoke a compound Key view.
My Document name is : Data
Compound Key View
function (doc, meta) {
  if(doc && doc._class == "com.couchbase.entity.Data"){
    emit([doc.key1, doc.key2], doc);
  }
}

SpringData Repository Inferface shown below :
package com.couchbase.repository;

import java.util.List;
import org.springframework.data.couchbase.core.view.View;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import com.couchbase.client.protocol.views.Query;
import com.couchbase.entity.Data;

public interface DataRepository extends CrudRepository<Data, String> {

    @View(designDocument="Data",viewName="findByKey1AndKey2")
    public List<Data> findByKey1AndKey2(Query query);
}

Test Class shown below :
import com.couchbase.client.protocol.views.ComplexKey;
import com.couchbase.client.protocol.views.Query;

public class DataTest extends WebAppConfigurationAware{

    @Autowired
    private DataRepository dataRepository;

    @Test
    public void testStringDataCompoundQuery(){
        Object[] objArr = new Object[2];
        objArr[0] = "aaa";
        objArr[1] = 1;

        Query query = new Query();
        query.setKey(ComplexKey.of(objArr));

        System.out.println(dataRepository.findByKey1AndKey2(query));

    }
}

If this was useful for you, please up vote

A: You could use compound key like describe in the documentation here: http://docs.couchbase.com/developer/dev-guide-3.0/compound-keys.html


text:
Q: multiprocess and parallelism in Python I'm writing a Python script that uses scapy to do some packet sniffing and parsing. That all works pretty well, and I decided to try to get this to work as a multithreaded script to handle processing higher volumes of traffic.
The basic idea is that if scapy sees an interesting packet, throw it into a Queue, and let all of the worker grab a packet out of the Queue, process it, and go back for another one. This cycle only works once, so I'm guessing that when the script goes back to the scapy side of things, it doesn't let go.
How can I get this so that scapy continues to throw packets in the queue, and my threads can keep processing queued packets?
from scapy.all import *
from Queue import Queue
from threading import Thread
max_threads=10

packetqueue=Queue(maxsize=0)

def queue_packet(packet):
        packetqueue.put(packet)

def analyze_packet(q):
        while True:
                packet=q.get()
                <do stuff to packet>
                q.task_done()

for i in range(max_threads):
        worker=Thread(target=analyze_packet,args=(packetqueue,))
        worker.setDaemon(True)
        worker.start()

sniff(iface="eth4", filter = "<filter>", store=0, prn=queue_packet)


text:
Q: "Enter" from keyboard on "Log-in" button doesn't work During the check-out logging-in procedure, pressing "Enter" from keyboard (after entering account details) does not log-in while it works if clicking with the mouse on the button.
What could be the problem?
Here the phtml :

Login

    <form id="login-form" action="/customer/account/loginPost/" method="post">
        <fieldset>
            <input name="form_key" type="hidden" value="" />

Already registered?

Please log in below:

                        Email Address*

                        <input name="login[username]" value="" id="email" class="input-text required-entry-email validate-email" title="Email Address" type="text">

                        Password*

                        <input name="login[password]" class="input-text required-entry-password validate-password" id="pass" title="Password" type="password">

            <input name="context" type="hidden" value="checkout" />
        </fieldset>
    </form>

* Required Fields

        <button type="submit" class="button login" onclick="onepageLogin(this)">Login</button>
        Forgot your password?

And here the JavaScript :
var loginForm = new VarienForm('login-form', true);
$('login-email').observe('keypress', bindLoginPost);
$('login-password').observe('keypress', bindLoginPost);
function bindLoginPost(evt){
    if (evt.keyCode == Event.KEY_RETURN) {
        loginForm.submit();
    }
}
function onepageLogin(button)
{
    if(loginForm.validator && loginForm.validator.validate()){
        button.disabled = true;
        loginForm.submit();
    }
}

A: Move the actions buttons inside the form, remove the onclick from the submit button and add an event listener for the form submit to run that function instead, something like this:
var form = document.querySelector('#login-form');

form.addEventListener('submit', function(e) {
    e.preventDefault();
    onepageLogin(this);
})

A: Enter button doesn't work because "submit" outside of  tag. You may use this one solution:

Login

<form id="login-form" action="/customer/account/loginPost/" method="post">
    <fieldset>
        <input name="form_key" type="hidden" value="" />

Already registered?

Please log in below:

                    Email Address*

                    <input name="login[username]" value="" id="email" class="input-text required-entry-email validate-email" title="Email Address" type="text">

                    Password*

                    <input name="login[password]" class="input-text required-entry-password validate-password" id="pass" title="Password" type="password">

        <input name="context" type="hidden" value="checkout" />
    </fieldset>

* Required Fields

    <button type="submit" class="button login" onclick="onepageLogin(this)">Login</button>
    Forgot your password?

</form>


text:
Q: Java Jama matrix I am working with Jama Matrix. I used it for LSI. It works all fine. However, when I pass a big matrix like, 8000x8000 it kills my whole system. I am simply calling SVD then reducing matrix size and adding up. Nothing else !
Any idea? How can I solve this problem?
core2du
Ram = 10GB
Java runtime setting
-Xmx5000M
There is no other program running while I execute Jama matrix code

A: I also use the Jama for SVD and have the same problem in solving big matrix.
In order to reduce memory overflow cases, I have tuned SingularValueDecomposition.java to compact one. The tuning is that in the matrix A it has so many 0 (zero) value so the compact for all of matrices used such as A, U, V, Work, etc only allows memory for available value which is more than 0.
Before you use the compact SVD, you should make A matrix file like
r /t c /t value /n
r /t c /t value /n
... '/t' and '/n' means tab and new line respectively.
examples, (0, 0, 0), (0, 1, 0.5), (0, 2, 0), (0, 3, 0.2), (1, 0, 1), (1, 1, 0), (1, 2, 0), (1, 3, 0.3) and the matrix size is 2*4 (R*C) then you just make file like
MATRIXSIZE /t 2 /t 4 /n
0 /t 1 /t 0.5 /n
0 /t 3 /t 0.2 /n
1 /t 0 /t 1 /n
1 /t 3 /t 0.3 /n
If you would like to use it, please give me your email address (mg.hwang@gmail.com).
I will give more details to use it on email.
I checked the result was right. However, I am not sure how much effective it is for the computer.
Anyway, it works and shows better even if not much.

A: You're probably facing an out of memory condition. You might want to increase the memory available to your JVM by using the -Xmx option, for instance-Xm256m will give your JVM 256 MB, instead of the default of 64 MB.
You may also consider using alternative libraries that handle memory efficient matrix representations, using the models for sparse matrices like COO, DOK, CSR, etc... Lookup the Wikipedia entry for "sparse matrix" for more details.
This thread provides several alternatives to Jama, maybe this'll help you as well.

A: Peter Taylor is absolutely right.
It is an exponential  big o issue. After all calculating the SVD of a 8000 X 8000 matrix is not a piece of cake since you are talking 64,000,000 elements!
If you run the JAMA MagicSquareExample, with a:
32x32 matrix elapse time is 0.062 sec.64x64 will go up to  0.0328 sec96x96 will elapse in 1.891 sec128x128 in 4.5 sec160x160 in 11.109 sec 192x192 in 24.063 sec224x224 in 46.063 sec256x256 in 83.625 sec512x512 in 1716.719 sec

A: If you're doing LSI, then you can make two important optimizations.  First, your matrix is sparse (assuming you're using a term-by-document matrix).  JAMA operates on dense matrices, so you may want to look into finding a different representation.  As Lolo mentioned, this will greatly reduce your overhead.
Second, LSI only requires the top k singular vectors to be computed.  JAMA computes all of the singular values, which is unnecessary in your case.  Moreover, if you only need to the k largest, you can optimize further by using a thin-SVD, which has a significantly lower memory overhead.  Computing the full-SVD for LSI will become almost impossible for large document collections, so you'll eventually have to switch from something other than JAMA if you want to scale.
SVDLIBJ is one possibility for performing a thin-SVD in Java.  The S-Space Package also has a SVDLIBJ wrapper and command line tool for it, as well as a LSI/LSA implementation if you want to avoid writing LSI altogether.


text:
Q: Indexing Date via Loop I am attempting to determine where dates are located in a matrix with the following code:
#portret is a list of daily returns for three different stocks from 1980-01-01 to 2010-12
#13.These dates are listed in the first column of the portret data frame
library(quantmod)
library(FRAPO)
getSymbols(c("F","AA","IBM"),from="1980-01-01", to="2010-12-31")
port=cbind(F$F.Adjusted,AA$AA.Adjusted,IBM$IBM.Adjusted)
portret=returnseries(port,"discrete",trim=TRUE)
portret=data.frame(index(portret),coredata=portret)
date.list=seq.Date(as.Date("1990-10-01"),as.Date("2010-10-01"),by="month")
length(date.list)
#this equals 241
date.index=matrix(0,241,2)
for(i in 1:241){
    date.index[i,]=which(portret[,1]==as.character(date.list[i]),arr.ind=TRUE)}

I keep receiving this error:
  replacement has length zero
Please advise.

A: the error is because the conditional statement evaluated to FALSE.
ie:
  x      <- 1:5
  x[[2]] <- which(FALSE)

The problem is that not all dates in date.list are in portret[, 1].
Instead, try this inside your for loop:
w <- which(portret[,1]==as.character(date.list[i]),arr.ind=TRUE)
date.index[i,] <- ifelse(identical(w, integer(0)), c(NA, NA), w)

But better still:
date.index <-
  sapply(as.character(date.list), function(D)
      {w <- which(portret[,1]==D, arr.ind=TRUE);
      ifelse(identical(w, integer(0)), c(NA, NA), w)})


text:
Q: Advice for my current MVVM android app architecture I have experience using Java for back-end web applications and I'm trying to make some sense out of the way MVVM architecture has to be laid but I can't stop thinking about Java Services, ServicesImpl, Controllers, etc...
This is the structure of my android app ui so far:
Main activity ---> Fragment -> SubFragment
               |-> Fragment2 -> SubFragment2
               |-> etc...

Simple enough, right?
But that's it. I'm not using services nor ViewModels (so I guess it's not a MVVM structure then lol).
All the logic is written in Main Activity for global stuff, and each fragment has its own logic as well. And its starting to get messy and I've been avoiding making this question a lot too lol.
So I have 4 questions:
Q1) Is it OK that the logic is being written in the fragment class? I.e. MyFragment loads an RV with firestore documents. In my java back-end applications I'm always using services and stuff and the code remains a lot cleaner but in Android, as I said above, it's starting to get messy because in MyFragment I need the Adapter, the ViewHolder and multiple queries and methods because I've implemented some filters. And because these filters are another RV separately I need another Adapter, another ViewHolder, and well... you see my point. For an earlier version of my App I separated the fragment from the adapter creating a "MyFragmentAdapter.kt" file. Would you consider doing this a good solution? Or all of this should go into a ViewModel?
Q2) So far I have no use for a ViewModel because if I need to persist data, I put that data in my Main Activity and that's it. Main activity never dies so the fragments data never dies as well. Would you consider this a good practice?
Q3) Looking at open source android applications I found no structure containing a services folder, which for me is practically a given. Why is that?
Q4) The folders in my project are laid out like this:
.project.login -> some activities with barely any logic
        .models -> just pojos
        .utils -> some utils.kt
        .ui -> recipes (folder) -> bunch of fragments with lots of logic
            -> news (folder) -> more fragments with lots of logic

Would you add something to this structure?

A: I will try to answer as simple as possible. If it works for you (your example), then it is ok. Simple as that. There is no wright/wrong answer, best arch, pattern etc in this world to make android app. Even bigger IT companies follow their own design patterns and some devs loves it, some don't. Anyway, back to your part questions:

*

*Consider Fragment and Activity just to be responsible for UI logic. That is loading views, changing view properties(button color, visibility etc), showing data on those views etc(getting from VM).
MyFragmentAdapter-> yes, make separate adapter class with ViewHolder. I even make single class responsibility, that is separate ViewHolder class.
Or all of this should go into a ViewModel?-> No, ViewModel holds no references to views! It just holds data and communicates with ui!

*Would you consider this a good practice? If you are looking into VM, then this is not a good idea. As I said above, Fragment(and Activity) is only responsible for UI logic. In VM, start your query, REST Api call etc and send that data to UI.
Main activity never dies so the fragments data never dies as well.-> TRUE, but the main MAGIC of VM is, it "survives" configuration changes. When activity recreates, VM is "the same" and holds all data needed to show on UI.

*Services holds no UI, no need for ViewModels.

*Ok, but I would consider every feature module with its own logic. Example: recipes-> ui-> fragment, adapter,viewmodel, di(dependency), data(api,repository), domain(usecases)

A: I would not consider what you're doing good practice.
Whether you follow MVVM, MVP, MVC, or something else, the idea is to decouple your application into at least 2 different layers: UI and Logic.
What this means in a nutshell in Android is to not do any logic in your activities or fragments.
In MVVM, all logic should go in ViewModels. None should go in activities or fragments. Activities and fragments should be updated purely by observing LiveData fields in the ViewModel. LiveData isn't strictly necessary but some observer pattern should be used. The goal is for your views to be as dumb as possible. To have data-driven UI. And your logic should be ignorant of the platform, it shouldn't even know that this is Android.
Some benefits are:

*

*Ability to unit test everything (Many developers don't understand the importance of this)

*Decoupled, can change the UI without changing the logic and vice versa

*Portability, could take that same logic code and put it on another platform or in another application

*Cleaner code, less spaghetti, smaller files, follow SOLID principles, easier to read, debug, refactor, modify, etc.


text:
Q: Populating Kivy widgets with a .csv file Hello everyone I need some help here I have a .csv file containing some data and I'm trying to populate some kivy widgets using the data obtained from it. So far everything runs ok but When adding the widgets I think I'm just adding them to the class instance and not the Box-layout.
this is my .csv:
My hero academics,fighting,midoriya
alice,test,malcolm

Below is my code block.
    from kivy.app import App
    from kivy.uix.button import Button
    from kivy.uix.boxlayout import BoxLayout
    from kivy.uix.label import Label
    from kivy.lang import Builder
    from kivy.properties import ListProperty
    import csv

Builder.load_string("""
<Test>:
    orientation: "vertical"
    padding: 10
    spacing: 10
    BoxLayout:
        Label:
            text:'list 1'
        Label:
            text:'label 2'
"""
)

class Test(BoxLayout):
    label_value = ListProperty()
    testList= ['potato', 'jake', 'ofu', 'zach']
    def __init__(self, **kw):
        super(Test, self).__init__(**kw)
        testlist = open("C:/Users/zfarley/Documents/Development/python_project/kivy-app/TEST/zachList.csv").read()
        #reads in data
        zach_list = testlist.split("\n")
        item_count= 1
        for value in zach_list:
            btn= Button(text= str(value), pos=(100,10))
            label= Label(text=str(item_count) )
            item_count= item_count + 1
            #self.rows= rows
            self.add_widget(label)
            self.add_widget(btn)

class TestApp(App):
    def build(self):
        return Test()

TestApp().run()


text:
Q: How to include jsoncpp library into project on unix? The library I am trying to include is jsoncpp. I am having serious trouble with this. I used the home-brew install for this library, which is brew install jsoncpp (brew install is unix version of linux sudo-apt get). Normally homebrew installs stuff to my path, so I can just use it. I am going off of this example here.
#include <json/json.h>

Returns an error of 10: fatal error: 'json/value.h' file not found.
I am using cmake because CLion automatically sets it up. Right now it is very basic:
#CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Read_JSON)

set(CMAKE_CXX_STANDARD 17)

add_executable(Read_JSON main.cpp)

However, for some reason jsoncpp cannot be found. How can I include this library in my project?

A: You can use in CMake FetchContent capability.
Jsoncpp is available via git repository on GitHub
Here is example how I made with googletest:
https://github.com/adamvm/hello/blob/master/CMakeLists.txt
You need just substitute proper addresses and names

A: On mac install with command.
brew install osrf/simulation/ignition-fuel-tools2

A: In Ubuntu (since 18.04) you need to install libjsoncpp-dev[1] package:
sudo apt install libjsoncpp-dev

[1] https://packages.ubuntu.com/search?keywords=libjsoncpp-dev


text:
Q: Bessel function's roots The Bessel functions are denoted as $J_n(x)$ where $n$ is the nonnegative value of order, and $j_{nm}$ are the roots of the function. I don't get the notation $m$ in here. What does the $m$ index represent?

A: The $J_n(x)$ has an infinite number of roots similar to $\sin(x)$ and $\cos(x)$ and they are numbered in order so $j_{n1}$ is the first positive root of $J_n(x)$ and so on.


text:
Q: Help with Dual Spaces - Prove that either $w\in Im(f)$ **or** there exists ${l\in W^{*}}$ such that $f^{*}\left(l\right)=0$ **and** $l(w)=1$" I'm in need of some assistance regarding this question. I'm learning Linear Algebra by myself using a university textbook and it has this question regarding Dual Spaces:
"Let there be a linear map $f:V\rightarrow W$ between $V,W$ (who are vector spaces over $\mathbb{F}$)
Let there be $w\in W$.
Prove that either $w\in Im(f)$ or there exists ${l\in W^{*}}$ such that  $f^{*}\left(l\right)=0$ and $l(w)=1$"
OK so I know that $f^{*}$ is defined as $W^{*}\rightarrow V^{*}$. I also know(and correct me if I'm wrong) that $l(w)=1$ will occur if $w$ is a vector in the Base for $W$
I understand the first option they want me to prove: if I take some vector in $W$ then it is an image of some vector from $V$ but I don't entirely understand the other option...specifically regarding $f^{*}(l)=0$
Any help is appreciated!
Thanks

A: Vectors in $W^\ast$ are just linear maps $W \to \mathbb F$ and $f^\ast$ takes a map $W \to \mathbb F$ to the composition $V \to W \to \mathbb F$.  So the second condition states that there exists a linear map $l\colon W \to \mathbb F$ such that the composition $l\circ f$ is zero but $l(w) = 1$.
One way to do this question is to make a clever choice of basis, can you take a basis $\{x_i\}_i$ of $im(f)$ and show that by adding the vector $w$ you still get a linearly independent set $\{x_i, w\}_i$ and therefore this can be extended to a basis $\{x_i, w, y_j\}_{i, j}$ of $W$.  Then take the dual basis $\{x_i^\ast, w^\ast, y_j^\ast\}_{i, j}$ and pick $l$ from that set.


text:
Q: Attempt to invoke virtual method 'void androidx.recyclerview.widget.RecyclerView.removeViewAt(int)' on a null object reference Error:
     java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.recyclerview.widget.RecyclerView.removeViewAt (int)' on a null object reference
     W / System.err: at com.arvicapps.geomitric_wallpapers.FavoriteFullImageActivity $ 5.onFavoriteChanged (FavoriteFullImageActivity.java:533)
             at com.github.ivbaranov.mfb.MaterialFavoriteButton.updateFavoriteButton (MaterialFavoriteButton.java:324)
             at com.github.ivbaranov.mfb.MaterialFavoriteButton.setFavorite (MaterialFavoriteButton.java:257)
             at com.github.ivbaranov.mfb.MaterialFavoriteButton.toggleFavorite (MaterialFavoriteButton.java:292)
     W / System.err: at com.github.ivbaranov.mfb.MaterialFavoriteButton $ 1.onClick (MaterialFavoriteButton.java:152)
             at android.view.View.performClick (View.java:6659)
             at android.view.View.performClickInternal (View.java:6631)
             at android.view.View.access $ 3100 (View.java:790)
             at android.view.View $ PerformClick.run (View.java:26187)
             at android.os.Handler.handleCallback (Handler.java:907)

Here are parts of the code from FavoriteFullImageActivity.java:
@Override protected void onCreate (Bundle savedInstanceState) {super.onCreate (savedInstanceState);  setContentView (R.layout.activity_favorite_full_image);  getSupportActionBar (). hide ();  RecyclerView recyclerView = findViewById (R.id.FavoriteCategoryView);  }

 try {
  recyclerView.removeViewAt (position);  recyclerView.notifyAll ();
 myDbHelper.closeDb ();
 myDbHelper.close ();
 myDbHelper.notifyAll ();
 } catch (NullPointerException nullPointerException) {nullPointerException.printStackTrace ();
  }

How to solve?

A: You're trying to access child view without inflating it or that child view does not exist.
set adapter to recycler view
recyclerView.adapter=adapter

A: java.lang.NullPointerException: Attempt to invoke virtual method 'void
androidx.recyclerview.widget.RecyclerView.removeViewAt (int)' on a null
object reference

It means that the property of recyclerView isn't initiated before you use it. Regards this, you need to check the code more carefully.