Probability of pairs

Question: Suppose $N$ people each generate a random number $[1,\cdots,N]$. On average, how many pairs will there be, given that a pair means that person $i$ generated $j$ and person $j$ generated $i$?
Comment: Interesting question. I assume it does not count as a pair if a person generates their "own" number?
Comment: If you require $i \not =j$ then there are $\frac12N(N-1)$ potential such pairs and each one has probability $\frac1{N^2}$ of occurring then the expected number is $\frac{N-1}{2N} = \frac12 - \frac{1}{2N}$.  (In addition the expected number of cases of people choosing their own number is $1$).
Comment: The possible number of pairs is of course at most $\lfloor N/2 \rfloor$ and in principle grows much slower. (I also assume that everyone generates their number independently, and with a uniform distribution over $1, \dots, N$.) And a little simulation suggests that as $N$ becomes large, the expectation converges from below to $0.5$.
Comment: @Henry: want to post this as an answer? Maybe elaborate that the number of pairs is binomial with parameters $\frac{1}{N^2}$ and $\frac{1}{2}N(N-1)$, for the expectation you give.
Comment: @StephanKolassa I am not sure it is binomial - they are not independent and, as you commented, the maximum is $\lfloor N/2\rfloor$
Comment: This seems connected to the famous [Birthday Problem](https://en.wikipedia.org/wiki/Birthday_problem).
Answer: From comments:
If you require $i \not =j$ then there are $\frac12N(N-1)$ potential such pairs and each one has probability $\frac1{N^2}$ of occurring then, by linearity of expectation, the expected number is $\frac{N-1}{2N} = \frac12 - \frac{1}{2N}$.
(In addition the expected number of cases of people choosing their own number is $1$).
This does not have a binomial distribution: the pairs are not independent and (as
Stephan Kolassa commented) the maximum number of pairs is $\lfloor N/2\rfloor$.
Comment: @StephanKolassa That is the power of linearity of expectation.  You know that the number of cases of a particularly pair appearing is $0$ or $1$ and the expected number of that particularly pair appearing is $\frac1{N^2}$ so the total expected number of pairs is that expectation of a particular pair multiplied by the number of pairs to consider.
Comment: @StephanKolassa  Player $i$ gets number $j$ with probability $\frac1N$ and independently player $j$ gets number $i$ with probability $\frac1N$, so for given $i$ and $j$ distinct, the probability they get each other's number is the product $\frac1{N^2}$.  Then $\frac1{N^2} \times \frac12N(N-1)= \frac{N-1}{2N}$
Comment: I'm getting doubts about this... where does the probability $\frac{1}{N^2}$ come from?
Comment: ... but simulating $N=3, 5, 10$ with 1e6 simulations each yields pretty much the expectation you get. Have an upvote, and I would still be interested in where that probability comes from.
Comment: ... but how does this square with the fact that if $(i,j)$ are a pair, then we *know* that $(i,k)$ and $(k,j)$ *cannot* be a pair for $k\neq i,j$?
Comment: It doesn't matter. The quantity we are looking for is the expectation of a sum (of indicator functions), which is always equal to the sum of the expectations.
Answer: Different approach to get the same answer:
For a person to be part of a pair, they need to choose a number other than their own (which has probability $\frac{N-1}{N}$), and the person/number they chose needs to complete the pair (which has probability $\frac{1}{N}$). The probability a person is part of a pair is, thus, $\frac{N-1}{N^2}$.
By the linearity of expectation, the expected number of people who are part of a pair is $\frac{N-1}{N}$, so the expected number of pairs is $\frac{N-1}{2N}$.
Comment: The number of pairs is equal to half the number of people who are part of a pair.
Comment: That's why I divide the final answer by 2.

Probability of pairs


PHPUnit bootstrap in PhpStorm

Question: I am working with Zend Framework 2 and I want to run tests for all of my modules in PhpStorm 5.0.4. I have PhpStorm set up to check for tests in myproject/module and it successfully finds my tests. The problem is that it doesn't read my configuration file within each module, which is needed (it points to a bootstrap file).
Here is the directory structure for a module (source):
/module
    /User
        /tests
            /UserTest
                /Model
                    /UserTest.php
            Bootstrap.php
            phpunit.xml.dist
            TestConfig.php.dist

When I run the test, it gives me an error because Bootstrap.php is not run prior to running UserTest.php. All of the files are correct, because if I cd to /myproject/module/User/tests/ and run phpunit within the Terminal, it works fine.
I would like it to use the configuration (and thereby bootstrap) within each module. I tried to use the --configuration option with a relative path, but I couldn't get it to work.
Here is my current configuration:

Any pointers on how I can run the configuration file (and bootstrap) when a module is being tested? That is, a module has its own configuration file and bootstrap.
Thanks in advance.
Answer: PHP Storm 7 assumes that you will only need ONE default bootstrap file and thus does not enable individual bootsrap files DIRECTLY for each PHPUnit test configuration.
However, zf2 conducts tests on a per module basis. Thus, after you set the defaults to the first module the other modules don't work. The way around this is to

Remove the default options in File|Settings|PHP|PHPUnit
You don't have to remove the default configuration file but you must EMPTY OUT and uncheck the  default bootstrap file. Just unchecking will not be enough
Go Run|Edit Configurations (there are other shortcuts to this box)
For each module you have to create a test configuration. For example, you'll have the standard Application Module and thus an "Application Module Test" for it, maybe an Admin Module and then an "Admin Module Test" for that
For each test (assuming standard zf2 directory structure)

a. Test Scope: Directory
b. Directory: C:\wamp\www\PROJECT-NAME\module\MODULE-NAME\test
c. Check "Use alternative configuration file:"
d. Enter C:\wamp\www\PROJECT-NAME\module\MODULE-NAME\test\MODULE-NAMETest\phpunit.xml.dist
e. In "Test Runner options", enter "--bootstrap C:\wamp\www\PROJECT-NAME\module\MODULE-NAME\test\MODULE-NAMETest\Bootstrap.php"

Repeat for next module

The issue here is that as long as the default bootsrap field has an entry, phpstorm will add that as default as a --bootstrap option AFTER whatever you put in the case specific Test Runner options. So, no matter what you do, you end up running the wrong bootstrap file everytime except for the first/default test case
Hope this helps
Answer: Unless I missed something, you'll have to set up a test configuration for each module.  In your case, you have myproject.  Instead, you'll want one for each module, and then set up the configuration for each (Use alternative configuration file).
Answer: I make use of the environment variables option in the run configuration to to define a value I can use within a global bootstrap.php to pull in requirements specific to a given module or section of the application.
class GlobalBootstrap
{

private static $applicationSections = [
    'section_a',
    'section_b',
    'section_c'
];

public static function init()
{
    $localMethod = self::fetchLocalMethod();
    if (!is_null($localMethod)) {
        self::$localMethod();
    } else {
       throw new Exception(
            __CLASS__
            . '::'
            . __FUNCTION__
            . 'Says: No local method has been defined for this test section'
        );
    }
}

private static function fetchLocalMethod()
{
    $section = getenv('APPLICATION_SECTION');
    if (is_null($section) || !in_array($section, self::$applicationSections)) {
        return null;
    }
    $section = preg_replace("/[^a-zA-Z]+/", "", $section);
    $method = 'bootstrap' . ucfirst(strtolower($section));

    return $method;
}

/**
 * Section specific methods
 */

protected static function bootstrapSectiona()
{
    require __DIR__ . '/../../{section_a}/module/Test/Bootstrap.php';
}
}

GlobalBootstrap::init();

Any arbitrary variable and value can be created and then referenced in your  bootstrap.php using: getevn(VARIABLE_NAME); This saves a lot of long-winded configuration in PHPStorm, but culd potentially get equally as complex if you're relying on a lot of differing bootstrap functionality.

PHPUnit bootstrap in PhpStorm


How can I find the count of semicolon separated values?

Question: I have a list of all email ids which I have copied from the 'To' field, from an email I received in MS Outlook. These values (email ids) are separated by a semicolon. I have copied this big list of email ids into Excel. Now I want to find the number of email ids in this list; basically by counting the number of semi colons.
One way I can do this is by writing C code. i.e. store the big list as string buffer, and keep comparing the chars to ";" in a while(char == ';') loop.
But I want to do it quickly.
Is there any quick way to find that out using either:
1.) Regular expression (I use powergrep for processing the regexps)
2.) In excel itself (any excel macro/plugin for that?)
3.) DOS script method
4.) Any other quick way of getting it done?
Answer: I believe the following should work in Excel:
= Len(A1) - Len(Substitute(A1, ";", "")) + 1

/EDIT: if you've pasted the email addresses over several cells, you can count the cells with the following function:
= CountA(A1:BY1)

CountA counts non-empty cells in a given range. You can specify the range by typing =CountA( into a cell and then selecting your cell range with the mouse cursor.
Comment: @Malfist: no. If you've got one address, you've got zero semicolons, right? @goldenmean: yes, I thought you had pasted them in one cell. For several cells, why not just count the cells? I've updated my posting.
Comment: This will be off by one. Say you have 0 semicolons, it'll return = x - x + 1, or if you have 1 simicolon it will return x - (x-1) + 1 and so on.
Comment: Hello Konrad,
   When i paste the big list of email ids in Excel they are pasted in a row. They are not in one cell, they are spread across many cells(columns) in that row.When i tried using the formula u mentioned, didnt get correct result. Should i be pasting all the entries in one cell itself?
Answer: Bash/Cygwin One-Liner
$ echo "firstname.lastname@example.com;firstname.lastname@example.com;email@example.com" | sed -e 's/;/\n/g' | wc -l
3

If you already have Cygwin installed it's effectively instant.  If not, cygwin is worth installing IMHO.  It basically provides a Linux bash prompt overlaid over your Windows system.
As an aside, stuff like this is why I prefer *nix over Windows for work stuff, I can't live on a windows box without Cygwin since bash scripts are so much more powerful than batch scripts.
Answer: If counting the number of semicolons is good enough for you, you can do it in Perl using this solution: Perl FAQ 4.24: How can I count the number of occurrences of a substring within a string
Answer: PowerShell:
> $a = 'blah;blah;blah'
> $a.Split(';').Count
3

Answer: 3) if you don't have neither cygwin, nor powershell installed try this .cmd
@echo off
set /a i = 0
for %%i in (email@example.com;firstname.lastname@example.com;email@example.com) do set /a i = i + 1
@echo %i%

Answer: If you are using Excel you can use this code and expose it.
Public Function CountSubString(ByVal RHS As String, ByVal Delimiter As String) As Integer
    Dim V As Variant
    V = Split(RHS, Delimiter)
    CountSubString = UBound(V) + 1
End Function

If you have .NET you can make a little command line utility
Module CountSubString

    Public Sub Main(ByVal Args() As String)

        If Args.Length <> 2 Then
            Console.WriteLine("wrong arguments passed->")
        Else
            Dim I As Integer = 0
            Dim Items() = Split(Args(0), Args(1))
            Console.WriteLine("There are " & CStr(UBound(Items) + 1) & "
        End If

    End Sub
End Module

Answer: Load the list in your favorite (not Notepad!) editor, replace ; by \n, see in the status bar how many lines you have, remove the last line if needed.
Comment: Hi Philho
tried doing this in Textpad. The \n is taken as a literal character and its special control meaning is not interpreted and instead of each entry going to new line, all it did was put \n instead of semi colons. Or Am i missing something?
Comment: Alternative: replace ";" by the form feed character (= new page), print the whole document and count the number of pages that the printer produced. OR: count how much ink is left, subtract from full cartridge load, and divide by the amount of ink used to print an average e-mail address. :-p
Comment: @goldenmean Using notepad++ you can replace using extended charset. If you use literal replace, as you did, it won't create a newline.
Comment: To do it with Notepad, replace semicolons with tabs (write a tab in Notepad, copy it, and paste it in the Find/Replace dialog), and then copy them to Excel. Once pasted, selecting all cells will show you the count in the status bar.
Comment: @goldenmean: I don't know Textpad, but in SciTE, for example, there is an option to transform \x expressions to control chars.
Comment: Typically, in most text editors, you have to select a "regular expression" option in the search-and-replace dialog bog.
Answer: C# 3.0 with LINQ would make this easy if it is an option for you over C
myString.ToCharArray().Count(char => char = ';')
Answer: If awk, echo is awailable (and it is, even on windows):
echo "addr1;addr2;addr3...." | awk -F ";" "{print NF}"

Answer: looping over it with a while loop and counting the ';' is probably going to be the fastest, and the most readable.
Consider Konrad's suggestions, that too will loop through the string and check every char and see if it is a simicolon, and then in modifies the string (may or may not be mutable, I don't know with excel), and then it counts the length between it and the original string.


What do I need to consider when changing to a Bassist Vocalist from Guitarist Vocalist

Question: I have played the guitar for about 17 years now and I have become quite comfortable with the instrument. I have also been singing for about two years and though its not a very long time, I am okay at it.
Recently I have met this band (actually a duo) comprising a guitarist and a drummer and they need a bass player and singer.
Have any one of you ever made this switch from a (primarily) guitar player to being a bass player and singer in a band. If so what tips do you have?
Comment: Have you rehearsed the set yet? How did you get on? Bass/vox is not as simple as some people would have you think. If there's nothing challenging in the duo's set, try some Police, Thin Lizzy or if you're feeling adventurous, Level 42. Basically, you need to be able to totally forget you're playing bass & only have to concentrate on the vox.
Answer: I made the switch many years ago because the band needed a bass player, and we had a guitarist who was much better than I was. I am a decent singer - sang some lead vocals and some harmony - there was another guitarist who sang well and just played chords.
Since I took up bass, I hardly do any singing unless I put down the bass. When playing bass the best I can do is usually simple harmony. There a few reasons for this:

What you're playing on bass - at least bass in its traditional role
as a rhythm instrument and fundamental harmonic foundation - is
usually very far removed from the melody that you have to sing, both
rhythmically and harmonically: You're playing back-beats and
syncopation in opposition to the forward flow of the music led by the
vocal melody. You're focusing on rhythm and not melody - you're
listening mostly to the drummer and blocking out everything else -
your role as a bass player is entirely different than when you're
playing guitar. The flow of the chords on most guitar work (at least
in more modern music) is closely couple to the melody and works with
it - you're playing something that works harmonically and
rhythmically in sync with the melody line and vocals - vocal enhances
guitar and vice versa so singing comes rather naturally when playing chords on guitar. Not so with bass.
When you sing and play bass  you are essentially playing two
different instruments simultaneously with two different roles that are almost opposition to one another: Your voice
and your bass. Granted, pianists and drummers do similar things all
the time, but I think there is a difference, because bass tends to be
a lot more physically demanding than the left hand of the piano or
the ride cymbal. Bass also demands a great of focus and precision because of of the central role it plays in the rhythm section - it is an unforgiving instrument playing a central role. It also carries its load on its own - bass has a
unique and solitary place in the ensemble, except for some occasional
help from the bass drum or an old school second guitarist (virtually
extinct today...). Bass is also loud and enveloping, putting your
focus on it.
To add to the difficultly, you usually have to play bass almost
constantly. Many lead guitarists also sing lead vocals, but
they don't do much very challenging guitar work when they're singing, and
they have that luxury: They sing, then they play some guitar, then
they sing some more - meanwhile the rest of the band -  the bass, the
drums and the keys, etc  - keep things going while they sing. (Some extraordinarily skilled/talented artists - SRV and Jimi Hendrix come to mind - were often able to do both.)

Certainly there are some great singing bass players - people like Paul McCartney, Jack Bruce, Geddy Lee, Mark King, Sting and  Lemmy come to mind.   But all of those artists are on a completely different level in general in terms of their musical talent. I suppose if I had the talent of Sting I'd also be able to play and sing like he does - also write songs like his...
Interestingly, many in that list play bass in a non-traditional way. For example, Mark King and Lemmy use bass more like a guitar, playing chords to accompany their vocals.
Chris Squire (Yes) and Robert DeLeo (STP)  - both great players - also did quite a bit of singing, but mostly harmony parts.

If you take a survey among bass players, you'll discover that most of those players who they considered the great, iconic players and stylists never sang a note,  or  at most just bit of harmony - people like James Jamerson, Jack Casady, Anthony Jackson, Chuck Rainey, Jaco Pastorious (he could sing very well and play, but he usually didn't), Bruce Babbit, John Entwhistle, Pino Palladino...  (I'll leave traditional jazz out of it) . It's because they were dedicated to the bass, which precluded vocals - musically, or resource-wise - time and effort. They considered themselves bassists, not vocalists: A separate vocation playing an instrument with a special role of its own, not an accessory or subsidiary to something else. I don't believe you'll find nearly as many guitarists or keyboard players in any of the popular genres that assume such a role for themselves. (Drummers tend to be like bassists in that respect - the rhythm section is just different.)

On TalkBass.com - a very popular site for professional bass players, the consensus is that if you want to sing lead and play bass, your bass playing has to go on 'auto-pilot' - you know your part cold and can play it reflexively - without thinking about it all. Then you can focus on your vocals.
So, if you're ready to take that on, go for a lot of up front singing. Otherwise, probably better to stick to harmony parts.
Try it - maybe you've got the talent and you won't find it difficult. Start by playing bare bones bass parts to simple songs while singing the simple melody. Maybe try a simple melody of your own with the bass and metronome - humming even, so you don't have to worry about getting the lyrics right. Try playing a simple 12 bar blues at a slow tempo and just play roots and 5ths while you work out your singing. You must get to the point where you can forgot about what your playing on the bass entirely and not mess up.
Personally I never went that route, because I really enjoyed focusing and working on bass, although in terms of my usefulness in bands that held me back. If you want to sing and play bass and you are able to do it well, you will be a valuable, in-demand musician.

Additional Perspective:
Although your question is about vx, as we've been discussing in the comments with @Basstickler, when you move from guitar to bass, you're not just playing a guitar with thicker strings in a lower register. You are a playing a different instrument with a different role: You're now playing a Bass. It's a Bass Guitar, but in most situations ( to exclude players like Stanley Clarke, Victor Wooten and Mark King... ) , what that means is essentially an upright bass in guitar form, which is how the instrument was originally conceived: As a portable, easier to manage, louder sounding version of the upright bass.
Its musical role is the bass's role: A rhythm instrument that keeps time, provides rhythmic interplay and states the underlying harmonic fundamentals of the music. It's an entirely different role than the guitar, a lead-solo instrument and/or one that's playing chords that enhance the melody line. To be a good bass player you need to aware of that difference and adjust - you're not playing guitar any more. That difference in the role of bass is the biggest factor making singing more challenging for most than guitar and vx.
Comment: I agree with most of this - except the piano or drums bit. Playing proper piano *also* includes putting down a bass line - as well as everything else, making it more arduous. Drums, well, playing ride or hi-hat probably helps with the singing, but when one considers that a drummer is schizophrenic in four directions, then it's a miracle he can even shout at the bassist, let alone sing! One other point, looking at someone like Mark Knopfler, he keeps all the widdly bits for in between the sung parts, so gets away nicely.
Comment: Since I play bass and piano, I have a little experience. 50yrs +. If there's no bass playing, that's what my l.h. tries to compensate for. Obviously if there is, life's just got easier, and the singing with it, too. That's all I'm trying to say.
Comment: @Tim _Playing proper piano also includes putting down a bass line_  Piano does not make the physical demands of bass, and while the left hand is a bass **part** it is not the same as a **bassline** in an ensemble.  There are a zillion singing pianists. The left hand of the piano does not do the rhythmic heavy lifting the bass has to. See BassTickler's answer on here. The issue is not just the multi-tasking - there are things about playing **bass**.
Comment: _If there's no bass playing, that's what my l.h. tries to compensate_ - OK, yeah, that's a little different than the LH in a group with a bass or  even just a pianist/vocalist, where you don't necessarily need a real _bassline_.
Comment: @Tim  Your comment about the drummer being schizoid in 4 directions and shouting at the bassist made me laugh so hard it hurt.  And I have seen keyboardist who can fill in for a missing bass player by playing the bass line with left hand and other stuff with the right hand and it takes as much talent as playing four parts simultaneously on a full drum kit.  I'm not coordinated enough to do either with any proficiency.  But I know how much talent and coordination it takes because I have tried.
Answer: I have to guess that you don't play bass as a rule. If so, you'll find it not so easy - singing one thing and playing something different - and on a new instrument. I often find that when I'm singing, the bass playing takes a back seat - quite a long way back! And I've been doing both for a long, long time. It tends to be very bassic (sic) in comparison to what I play when not singing.
It can be done, as is apparent in bands like Level 42, and guys like Sting and Phil Lynott, as already quoted. But I guess a lot of people who do both simultaneously will have it down pat - in other words, have learned the two parts, and as such will deliver the same or close each time they play/sing.
It may be a better option for the original guitar player - presumably strumming during the singing parts - to play bass, while you sing and strum. In fact, it would be a good feature and increase the set list somewhat.
Answer: As a bass player that is most definitely not a singer, I have a few things to add to the conversation.  First off, I'll note that I do sing all the time on stage, just not into a microphone because no one wants to hear that.  What I've found while just singing for my own pleasure on stage is that there isn't exactly a consistency to what is easy for me to sing and play at the same time.  There are some rather complicated or active bass lines I do that I can easily sing on top of and some rather easy ones that if I try, I tend to mess up the bass part.  I'm ultimately of the opinion that I could sing over anything if I really put my mind to it.  The point of all this is to say that there may be inconsistent struggles you face in developing this multitasking skill.
As others have mentioned, one of the most important parts of this is to get the bass playing to be second nature so that you don't have to think about it to be able to play it.  I might recommend practicing speaking while you play as well, since this may be even more difficult since speech is not necessarily going to be in sync rhythmically.  It will basically allow you to develop a separation between playing and vocal mechanics beyond individual songs.
On a more general note, if you're transitioning from playing guitar to playing bass, there are a lot of things that get missed by others doing this.  There is a lot of subtlety and nuance to bass playing that guitar players miss.  I'm not sure this is the best place to provide all of those thoughts but it's important to think about.  Some of these nuances, such as articulation and tone (as a result of technique) may make it more difficult to sing on top of as well, so it would be good make sure those are actively considered as you progress.  These nuances are what will make you sound like a bass player instead of sounding like a guitar player playing the bass.
Comment: @Stinkfoot Yeah, lots of guitar players miss the mark when they try to play bass or, like one of my friends is dealing with in her band, the bass player does well but plays as if he were playing lead guitar, ie, overplaying.  As you mentioned, there have definitely been plenty of great bass players that are unconventional and still sing, such as Les Claypool, but they are more of an exception.  Similarly, you don't see too many lead guitar players that sing while they're playing lead lines.
Comment: _like one of my friends is dealing with in her band, the bass player does well ..., ie, overplaying_ - Yeah, I had to make that adjustment. My hands got used to bass but that was only part of the problem-I got complaints that my basslines were not good. I did some homework - listened to a lot of unknown old school bass players on blues, RnB and jazz records to learn what **the bass** was supposed to be doing. It didn't help that when i started playing -ancient times - 'lead bass' was the thing in cutting edge rock - players like Jack Bruce and jack Casady were getting lots of attention.
Comment: _Some of these nuances, such as articulation and tone (as a result of technique) may make it more difficult to sing on top of as well_ Yup - good execution on bass can require serious concentration - that's part of what I meant about the physical aspect of bass  that makes vx more difficult. Often I  have to really concentrate on nailing that line just right - bass can be very unforgiving - very hard to sing when that's the case. As I mentioned, many of great singing bass players did not play bass in the traditional way.


Accessing 3 tables in Laravel using foreign key (laravel 6)

Question: I want to show data from a database(sql) that is from a specific user.
I have 3 tables:
Users
Stores
Areas
These are the following relationship between tables:
User hasOne Area
Area hasMany Stores
Basically what I wanted to show is that every user has their own area that has many stores.
User model
function area() {
    return $this->hasOne('App\Area');
}

Area model
 function user() {
    return $this->belongsTo('App\User');
}

function stores() {
    return $this->hasMany('App\Store');
}

Store Model
function area() {
    return $this->belongsTo('App\Area');
}

My database looks like this:
user table
id name role_id area_id
area table
id name user_id
store table
id name area_id
How can I access user->area->store?
This is what I got so far
function show() {
    $id= Auth::user()->id;
    $user = User::find($id);
    echo($user->area->stores);
}

Thank you
Comment: the user table shouldn't contain reference for table area i.e. the area_id column in the user table. the rest is good and should work what's the problem?
Comment: Are you doing blade or api design? and define "want to show"
Comment: Hi, Thanks for asking. You are right about not having the area_id in the user table. I have finally managed it to work by using the hasManythrough relationship. Thank you and god bless.
Answer: you can use the hasManyThrough for get sotres of an area:
define stores function in User model
public function stores()
{
    return $this->hasManyThrough(Store::class, Area::class);
}

and use it :
$stores = auth()->user()->stores;

I hope be useful.
Comment: Hi, thanks for taking the time to help. I just tried this out and finally managed it to work. God bless.


Changing the address of an lcd shield

Question: I'm working on a project, and I'm using an arduino Uno. I want to use 4 shields (OLIMEX Shield lcd 16x2) to print datas (a data for every lcd). So, I think I have to give every lcd an adress (or an ID). I searched on the net to find something, but I didn't found an answer.
Do you have any suggestion ?
Thank you in advance.!!
Answer: I already ask this question and I have the answer of it now.
Well, using a shield type "OLIMEX Shield lcd 16x2" is related to use the library named "LCD16x2.h", which required using I2C protocol, and this library don't let you change the property of the lcd. In this library you have to initialise your lcd this way :
<code>    LCD16x2 lcd;
</code>
The solution is to use normal lcd 16x2 that allows you to use the pins configuration. The code for your 4 lcd is this way :
<code>#include <LiquidCrystal.h>

// You only have to change your second number, make 11 or 10 or 9...

LiquidCrystal lcd1(12, 11, 5, 4, 3, 2);
LiquidCrystal lcd2(12, 10, 5, 4, 3, 2);
LiquidCrystal lcd3(12,  9, 5, 4, 3, 2);
LiquidCrystal lcd4(12,  8, 5, 4, 3, 2);

void setup()
{
// Your code
  lcd1.begin(16, 2);
  lcd2.begin(16, 2);
  lcd3.begin(16, 2);
  lcd4.begin(16, 2);

  lcd1.print("text1");
  lcd2.print("text2");
  lcd3.print("text3");
  lcd4.print("text4");

}

void loop()
{

  lcd1.setCursor(0, 1);
  lcd2.setCursor(0, 1);
  lcd3.setCursor(0, 1);
  lcd4.setCursor(0, 1);

  lcd1.print("anythingYouWant");
  lcd2.print("anythingYouWant");
  lcd3.print("anythingYouWant");
  lcd4.print("anythingYouWant");
}
</code>
Thank you all !!

Changing the address of an lcd shield


Why isn't this function writing anything to my file in Perl?

Question: I'm relatively new to manipulating files in Perl. I don't know what's wrong with this code that it does not write anything to my text file. I don't think it's with my data structure because I have another function which prints the contents of the data structure and the data is there. It just doesn't get written in the file. Am I missing something?
Here is the code :
sub saveFile {
    open( my $out, ">", "inputs.txt" );
    for ( $i = 0; $i < $#students; $i++ ) {
        print $out $students[$i]->{"name"};
        print $out $students[$i]->{"studNum"};
        print $out $students[$i]->{"cNum"};
        print $out $students[$i]->{"emailAdd"};
        print $out $students[$i]->{"gwa"};
        print $out $students[$i]->{"subjNum"};
        for ( $j = 0; $j < $students[$i]->{"subjNum"}; $j++ ) {
            print $out $students[$i]->{"subj"}->[$j]->{"courseNum"};
            print $out $students[$i]->{"subj"}->[$j]->{"courseUnt"};
            print $out $students[$i]->{"subj"}->[$j]->{"courseGrd"};
        }
    }
    close $out;
    print "FILE SAVED.\n";
}

Comment: Do you have `use strict; use warnings;`? If not, add it and fix the warnings. You should also avoid the global variable and instead pass it as an argument to your function.
Comment: Always check the return code from `open` and take appropriate action. `open my $out, '>', 'inputs.txt' or die "Can't open inputs.txt: $!\n";`
Comment: Instead of typing out `$students[$i]->{"subj"}->[$j]->{"courseNum"}` when using hash references, you only need to use one arrow: `$students[$i]->{"subj"}[$j]{"courseNum"}`.
Answer: You have used < where you should have used <= in your loop condition.
for ( $i = 0; $i < $#students; $i++ ) {
#                ^^-- here

Because of this, the last index will not be printed, and I assume you are testing this using just one record.
Note that this is a poor way of looping over an array. A much preferred way -- unless you need the array indexes for something else -- is to loop over the actual elements:
for my $student (@students) {
    print $student->{"name"};
    ...
}

Each element here will be a hash ref, which will simplify your typing considerably and make your code more readable.
You can also use a hash slice to print your records, instead of printing them one by one:
print @{$student}{qw(name studNum cNum emailAdd)};

Note that you may want to delimit the various values with something:
print join ",", @{$student}{qw(name studNum cNum emailAdd)};

And lastly, like I said in the comments, you should avoid using a global variable. Instead pass the array to your function. Combined with all my advice, I came up with this:
saveFile( \@students );

...;
use feature 'say';    # required for say()

sub saveFile {
    my $aref = shift;
    for my $student (@$aref) {
        say join ",", @{$student}{qw(name studNum cNum emailAdd gwa subjNum)};
        for my $subj ( @{ $student->{"subj"} } ) {
            say join ",", @{$subj}{qw(courseNum courseUnt courseGrd)};
        }
    }
}

Note that I have done away with the subjNum key, which is redundant, as it is simple to get the size of the array.
Answer: Though your source formatting wants improvement, your technique is basically right.  However, there is this little error in your code:
$i<$#students

Make it either $i<=$#students or $i<@students.  That should fix your trouble.
By the way, if you wish to improve formatting (and idiom), then this alternative might afford you some ideas:
sub saveFile {

    open(my $out, '>', 'inputs.txt');

    for (my $i = 0; $i <= $#students; ++$i) {

        print $out $students[$i]{name};
        print $out $students[$i]{studNum};
        print $out $students[$i]{cNum};
        print $out $students[$i]{emailAdd};
        print $out $students[$i]{gwa};
        print $out $students[$i]{subjNum};

        for (my $j = 0; $j < $students[$i]{subjNum}; ++$j) {
            print $out $students[$i]{subj}[$j]{courseNum};
            print $out $students[$i]{subj}[$j]{courseUnt};
            print $out $students[$i]{subj}[$j]{courseGrd};
        }

    }

    close $out;
    print "FILE SAVED.\n";

}

Comment: @tbh Prototypes in Perl are different from other languages. They are only there to allow advanced programmers ways to emulate built-in functions, to provide extra functionality to argument handling. When you use prototypes, Perl will expect your function to use a certain amount and type of arguments, and will warn about missing arguments, and whether you do not predeclare your function. The general rule is: If you don't know what prototypes do in Perl: Don't use them. Which is short for: Don't use prototypes.
Comment: Oh i see. Didn't see that. I just realized that the variable mentioned tracks the last element of the array, not the next after it. Thank you!
Comment: @thb OP could also eliminate the extra arrows in the hashrefs, and simple `for (@$students)` and `for (@{$students[$i]})`.
Comment: Using an empty argument list in a prototype is redundant and just complicates things. `sub saveFile { }` is what you should use.
Comment: @TLP:  I did not know that an empty argument list complicated things, for I have been using empty argument lists for many years.  I will remove the empty argument list from my answer, but would you tell me why?  I would like to learn.
Comment: See http://stackoverflow.com/questions/297034/why-are-perl-5s-function-prototypes-bad
Comment: @nowrn29: StackOverflow allows you to upvote answers you find helpful.


In which professional sports league do players share the highest % of revenue?

Question: In which American professional sports league do players share the highest % of league revenue?
Any professional sports league is acceptable so long as most players rely on their participation as their primary source of income (please exclude hobby and semi pro leagues that cannot mean that description).
Answer: For three of the four major US sports leagues the players share the following percentage of revenue:
NFL: 58%
NBA: 57%
MLB: 53%
Source found here.


Log em arquivos separados com SLF4J na AWS

Question: Alguém já implementou log utilizando SLF4J para possibilitar que a aplicação separe os arquivos por tenant em ambiente Amazon?
Fiz essa implementação na minha aplicação, no tomcat rodando local os arquivos de log são gerados normalmente, porém quando faço o deploy na Amazon e posteriormente faço o download dos logs, os arquivos não são gerados, as saídas acabam indo para o catalina.out.
Comment: Que tipo de deploy você faz: direto em EC2? Elastic Beanstalk? CloudFormation? A maioria dos meus problemas com logs residem em caminhos inexistentes ou falta de permissão de acesso.
Comment: Elastic Beanstalk
Answer: Resolvi o problema definindo o caminho que condiz com a estrutura que os logs são armazenados no tomcat da Amazon.
Fiz a seguinte alteração no arquivo de configuração do meu filter.
<File>/var/log/tomcat8/nomedoarquivo.log</File>

http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/using-features.logging.html
Answer: Localmente você deve ter configurações que precisam ser feitas no tomcat, como jars no classpath e parâmetros da JVM, que podem ser configurados pelos arquivos .ebextensions/*.config do Elastic Beanstalk, veja mais em http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/ebextensions.html
Comment: Vou tentar verificar se eu necessito de alguma configuração adicional, porém eu estou achando que minha aplicação não está conseguindo gravar outros arquivos de log por não encontrar a estrutura de pastas semelhante a local do tomcat, por exemplo na minha máquina local configuro para que os arquivos fiquem em ../logs/nomedoarquivo.log, porém ao fazer o download dos log na Amazon não vem nessa estrutura, a pasta descompactada é var/log/tomcat8/...
Comment: Sim, isso depende se voce instala pelo .rpm (eb) ou o .zip (vc)... que bom que encontraste o problema.
Comment: Sim, de qualquer forma agradeço a atenção.  :D


Printing multiple objects in different classes

Question: The details in this example isn't that important just trying to figure out how I can solve this, I have 3 separate classes Person , Interests and Location. all are objects, a person would have an list of interests and each interest will have a list of locations, i'm using a toString to print my person object and the interest but I can't figure out how to print out the locations of each interest. Do i need to overload my toString?
public class Person{
    private String name;
    private ArrayList<Interest> interests = new ArrayList<Interest>();

    public Person(String name, ArrayList<Interest> interests) {
        this.name = name;
        this.interests = interests;
    }

    public void addInterest(Interest newInterest) {
        interests.add(newInterest);
    }

    public Interest getInterest(int indexOfInterest) {
        return interests.get(indexOfInterest);
    }

    public ArrayList<Interest> getInterests() {
        return interests;
    }

    public String getName() {
        return name;
    }

    public String toString() {
        String result = getName() + " ";
        for(Interest interest : interests) {
            result += interest.getName() + "(" + interest.getDangerRating() + ")" + " ";
        }
        return result.trim();
    }
}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public class Interest {
        private int dangerRating;
        private String name;
        private ArrayList<Location> location = new ArrayList<Location>();

    public Interest (int dangerRating, String name, ArrayList<Location> location) {
        this.dangerRating = dangerRating;
        this.name = name;
        this.location = location;
    }
    public int getDangerRating() {
        return dangerRating;
    }
    public String getName() {
        return name;
    }
}

////////////////////////////////////////////////////////////////
public class Location {
    private String location;
    public Location (String location){
        this.location = location;
    }
    public String getLocation() {
        return location;
    }
}

Answer: Learn to use your tools: every IDE can generate an overriden toString() method and they are good for the most cases.
public class Location {
    // ...
    @Override
    public String toString() {
        return "Location{" +
                "location='" + location + '\'' +
                '}';
    }
}

public class Interest {
    // ...
    @Override
    public String toString() {
        return "Interest{" +
                "dangerRating=" + dangerRating +
                ", name='" + name + '\'' +
                ", location=" + location +
                '}';
    }
}

class Person{
    // ...
    @Override
    public String toString() {
        return "Person{" +
              "name='" + name + '\'' +
              ", interests=" + interests +
              '}';
    }
}

I would advise you to stick to your IDE's default toString()s, because that will make your toString()'s look consistent acros all your projects, and soon they will be familiar for you and easy to read.
Comment: So if I call toString in my main what happens? will it call each of them or, sorry my IDE doesn't have that feature on mac
Comment: It will subsequently call toString on all the objects inside your Person. Btw, what IDE do you use? a notepad?
Answer: I reccomend making a toString for each class. That way you can call a Location toString in the Intrest's toString, then the location toString in the Person. Also, the ArrayList class has its own toString that prints all the items in the array.
Currently you only have one toString and you are manualy getting the data for each. So for example:
(In the Location Class):
@Override
public String toString()
{
    return "Location: " + location;
}

(In the Interest Class):
@Override
public String toString()
{
     return "Danger Rating: " + dangerRating +
            "Name: " + name +
            "Location: " location.toString(); //Note, the name location is confusing here since it is an ARRAYLIST of locations.

}

(In the Person Class):
@Override
public String toString()
{
    return "Name: " + name +
           "Intrests: " + intrests.toString();
}

(In the Main Class):
public static void main(String[] args)
{
     Intrest[] intrests = new Intrest[4]; //TODO: Create intrests, currently they are all null.
     Person thePerson = new Person("Eddie", intrests);

     System.out.println("Person Info: " + thePerson.toString());
}

Comment: how do I go about calling this in my main, i  did this i just wasnt sure how i would call them since theyre all separate but i guess thats the point of the override
Comment: The point of the override tells Java to use this function instead of the one in the base class. Its an advanced topic called "Inheritance and Polymorhism" but I wouldn't worry about that for now (https://cs.calvin.edu/activities/books/processing/text/13oop.pdf).

So if you want to call this in your main, I would assume your main class has a person object or a list of person objects? If so you can call toString on those objects.
Answer: In your Person class, you call interest.toString() in a loop for all interests
public String toString() {
    String result = getName() + " ";
    for(Interest interest : interests) {
        // add this function to print interest stuff
        result += interest.toString();
    }
    return result.trim();
}

In your Interest class, you'll want a toString or similar method like so
public String toString(){
    String s = "";
    //print stuff for interest i.e. s+= what you want to add
    //loop through locations associated with Interest
   for(Location l : this.location ){
       // print what you want in location.toString()
       // add this funciton to your Location class
       s += l.toString()
   }
   return s;
}

And then in your Main you just need to call
    person.toString() and it will loop through and print everything for you.


display list of pages of content type using views + edit and delete option

Question: I've installed the Views Bulk Operations module (VBO). Using this I want to create a block/page to  load all the pages of particular content-type. But it should include options like update + check boxes, edit/delete. See the screenshot below.

I couldn't find the built in view 'content', so I've to create from scratch. Please give me solutions.
Answer: I got the solution by installing Admin VBO Views module
Comment: But, I couldn't find check box option to select individual or all option to delete/edit
Answer: Check admin/structure/views/view/admin_views_node
Comment: Can you explain what the user should do on this page?


Executar html5 dentro do WebView android

Question: Tenho uma página em html5, onde gostaria de poder abri-la no WebView do android, mas parece que o WebView não interpreta o javascript.
Existe uma WebView melhor?
Veja meu código:
MainActivity
package br.com.aaaa;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebView;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        WebView webview = new WebView(this);
        setContentView(webview);
        webview.loadUrl("http://www.hostcia.net/testes/html5Assinatura/");

    }
}

Veja: http://www.hostcia.net/testes/html5Assinatura/

O link acima é da página de teste onde é possível marcar pontos do desenho. Essa estrutura também será usada para assinatura.
Comment: Eu editei minha resposta, consegui tratar o clique do botão, recuperar a imagem e salvá-la no armazenamento do celular. Espero que eu tenha ajudado, ou esclarecido alguns pontos. Qualquer coisa só mandar mensagem.
Answer: Olá, é preciso colocar a permissão no Manifest:
 <uses-permission android:name="android.permission.INTERNET" />

Ainda no Manifest, mas dentro de application, acrescente:
android:usesCleartextTraffic="true"

Dentro da sua Activity, antes do webview.loadUrl... acrescente:
    webview.getSettings().setJavaScriptEnabled(true);
    webview.getSettings().setAppCacheEnabled(true);

Edit1:
Baseado nesse link Detectar o clique do Botão
Para fazer o tratamento do botão pra recuperar a imagem gerada e salvá-la crie uma nova Classe
e crie os seguintes métodos:
 public static String parseBase64(String base64) {

        try {
            Pattern pattern = Pattern.compile("((?<=base64,).*\\s*)",Pattern.DOTALL|Pattern.MULTILINE);
            Matcher matcher = pattern.matcher(base64);
            if (matcher.find()) {
                return matcher.group();
            } else {
                return "";
            }
        } catch (Exception e) {
            e.printStackTrace();

        }
        return "";
    }
    public static void downloadFileFromBase64(String fileContent) {
        try {
            File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM), "Camera");
                file.mkdirs();
                if (fileContent != null) {
                    String attachment = parseBase64(fileContent);
                    byte[] byteArr = Base64.decode(attachment, Base64.DEFAULT);
                    File f = new File(file.getAbsolutePath(),"sample.png");
                    f.createNewFile();
                    FileOutputStream fo = new FileOutputStream(f);
                    fo.write(byteArr);
                    fo.close();
                }

            }catch (Exception e){
            e.printStackTrace();
        }
    }

Esses dois métodos faz o parse do base64 e salva a imagem no diretório da camera do celular.
Na Activity que está o webview, abaixo do webview.loadUrl... acrescente:
webview.addJavascriptInterface(new Object() {
           @JavascriptInterface           // For API 17+
           public void performClick(String strl)
           {
               //ação para o clique do botão "save"
               downloadFileFromBase64(strl);

           }
       }, "save");

Para ter sucesso em salvar a imagem você precisa dar as permissões no Manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Mesmo assim é importante verificar se a permissão foi dada, então em sua activity crie o seguinte método:
public static boolean hasPermissions(Context context, String... permissions) {
    if (context != null && permissions != null) {
        for (String permission : permissions) {
            if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
    }
    return true;
}

Ainda na activity, mas dentro do onCreate(); acrescente:
String[] permissions = {
                //aqui pode acrescentar todas as permissões que estão no Manifest
                android.Manifest.permission.WRITE_EXTERNAL_STORAGE,

        };
        if (!hasPermissions(this, permissions)) {
            ActivityCompat.requestPermissions(this, permissions, 1);
        }

IMPORTANTE:
Para conseguir fazer isto, eu alterei seu html, seguindo o link que me baseei, pois como eu havia falado não entendo de javascript, segue o html alterado:
https://jsfiddle.net/wxjkb4Lt/3/
Comment: qualquer coisa me manda email: firstname.lastname@example.com


Handling snippets and views in MVC

Question: if I have a page on my site where i have to show 4 or 5 snippets (news feeds, event feed etc), all relating to different data (in different models and db tables), then what is a sensible way to handle the generation of the snippet content and layout? i could use a single snippet controller which contains static functions which each return a view populated with the relevant data. But each function in this snippet controller will be interacting with different data/models, so i'm not sure how OOP this is. Or, I could just add a static function to each of the controllers which are dealing with each associated set of data - e.g in a News_Controller, as well as functions to show all news items, individual news items etc, i could add a static function to generate the news feed by simply returning the view I need. I think this approach might work, as i don't want to instantiate an object for these simple snippets, so having static functions in the relevant controllers makes a bit of sense. Bit of a stream of consciousness here, but am i making any sense?!
Comment: +1: Good question and i think you should take it as per-page approach, that is putting a controller there for each page whatever it contains.
Answer: Many frameworks have some notion of "partials", which are typically used for this kind of thing.
Since these partials are generally read-only, and are often displayed on every page (or some well-defined set of pages), you can approach them without thinking in terms of controllers like you would for a page.
In other words -- remember that it's fine if your view/layout code talks directly to your models, as long as it's only interrogating them.
I do things like this all the time:
layout.php:

<?PHP $news = Model_News::latest(); ?>
<?PHP foreach($news as $newsitem): ?>

<?PHP endforeach; ?>

Model_News::latest() might implement some caching, etc, since this is layout code and I probably don't want to hit the db on every request.
No controller-bloat necessary!
Comment: frameworks differ in the efficiency of partials. I've used a similar approach to the one recommended by timdev along with caching because my partials appeared on every page of a busy site. I find it tricky to balance the "rightness" of a solution with the practicalities of getting the job done quickly and delivering a result. I'll often start with something simple and ugly and when the "code smell" gets too bad or it i need to use it somewhere else, will refactor it into something nicer and "righter" (grin)
Comment: Thanks Tim, this is the type of thing that I can get bogged down in, even though it involves simple features and only a couple of lines of code for each snippet. Your approach involves the least amount of code and repetition, and doesn't involve me creating new controllers or helpers for such a simple task. Makes perfect sense! Anytime there is slightly more complex code required than the News example, then I think I will add a static function to the most relevant controller.
Answer: You may want to look into Hierarchical Model-View-Controller (HMVC). It's especially suited to making pages with snippets. I believe Kohana implements it.
Basically, you have multiple Model-View-Controller triads each responsible for each snippet. So you could have a controller to access the News database and load a variety of small views for different types of news displays.
Answer: You can architect your MVC pattern to provide a mechanism for allowing data that has been set to be returned as an array. For instance, normally a web request to /news/feed/ would result in pertinent data being set and subsequently passed to a view. In addition to web requests, the system should also allow a controller to make such a request, i.e., $vars = $this->call('/news/feed/'); The system will recognize the internal request and return the set vars rather than invoking a view.
This allows you to keep your controllers and models cohesive.

Handling snippets and views in MVC


When is cache_menu flushed?

Question: I was caching some goodies related to the menu, and putting it in the 'cache_menu' bin, assuming they would get cleared whenever someones edits the menu.
cache_set($cachekey, $mymenu, 'cache_menu', CACHE_TEMPORARY);

When I edit the menu, it isn't cleared. When is it cleared, then?
In what sense is it different from the cache bin?
Answer: Looking at menu_link_save(), you will see that it calls menu_cache_clear() to clear only the cache of the menu the menu item belongs to. Other entries in the menu cache are not cleared.
The entire menu cache is only cleared when menu_cache_clear_all() is called directly (eg. by menu_enable(), which runs whenever a module is enabled) or indirectly (often through menu_rebuild() or drupal_flush_all_caches()).
If I were you, I would store my own data in the default 'cache' bin. I consider the menu cache to be private to the menu system; I don't want to touch it and accidentally mess something up. To clear my cache data at the right moment, I would implement hook_meu_link_insert() and/or hook_meu_link_update() and clear/rebuild my cache data from there.
Comment: Thanks for the feedback. That sounds right, if I'm not mistaken, only alter hooks (eg. hook_form_alter) can live in both themes and modules.
Comment: did that, works (hook must be in a module, not in a theme). used `cache_clear_all($cachekeystart, 'cache', true); drupal_set_message('Custom Menu cache cleared'); ` on insert, update and delete
Comment: Alters, preprocess, and process hooks can be called from both.

When is cache_menu flushed?


FAMD explained variance of components very low

Question: I am dealing with a dataset composed of 50 features. There are both categorical (some with many levels, others dichotomous) and numerical features, so I decided to use FAMD in order to reduce the number of components.
Trying to build 3 components, the explained variance is:

First Component: 0.00613
Second Component: 0.00426
Third Component: 0.00351

The total sum is 0.013, which is very far from 1!
Adding more components, the results are the same.
I am using the prince library in Python to evaluate FAMD and using the explained_inertia_ function.
Here is the documentation:  https://github.com/MaxHalford/prince
How to deal with this? How to improve the explained variance with few components?
Answer: I had the same issue with my dataset. The sum of the explained variance (explained_inertia_) won't add up to 1 unless you specify when instantiating the FAMD() class with the parameter n_components on the same size as the number of variables you are fitting to it. See this link: https://pythonlang.dev/repo/maxhalford-prince/
Also, even when I specified the n_components with the same amount of variables, the explained_inertia_ still wouldn't add to 1. I think this behavior is due to the fact that you fit the FAMD() with raw categorical variables and the algorithm uses the Pandas get_dummies() method to encode those features, thus increasing the total amount of features of your dataset. Here is an example using the documentation data.
import pandas as pd
from prince import FAMD
X = pd.DataFrame(
    data=[
        ['A', 'A', 'A', 2, 5, 7, 6, 3, 6, 7],
        ['A', 'A', 'A', 4, 4, 4, 2, 4, 4, 3],
        ['B', 'A', 'B', 5, 2, 1, 1, 7, 1, 1],
        ['B', 'A', 'B', 7, 2, 1, 2, 2, 2, 2],
        ['B', 'B', 'B', 3, 5, 6, 5, 2, 6, 6],
        ['B', 'B', 'A', 3, 5, 4, 5, 1, 7, 5]
    ],
    columns=['E1 fruity', 'E1 woody', 'E1 coffee',
             'E2 red fruit', 'E2 roasted', 'E2 vanillin', 'E2 woody',
             'E3 fruity', 'E3 butter', 'E3 woody'],
    index=['Wine {}'.format(i+1) for i in range(6)]
)

famd = FAMD(n_components=10, random_state=123)
famd.fit(X)
famd.explained_inertia_.sum()

Which gives us:
0.9999999999999997

I know that's really really close to one even though I specified the n_components=10 which is the same amount of features. But when I tested this approach on my dataset with is comprised of 20+ columns and 3,000,000 data points the explained variance wouldn't add up to 1.
So in order to check the amount of features you can just call the famd.column_correlations() method:
famd.column_correlations(X)

Which gives us:

0   1   2   3   4   5
E1 coffee_A -0.638646   0.054793    -0.357563   0.144806    -0.428958   0.207656
E1 coffee_B 0.638646    -0.054793   0.357563    -0.144806   0.428958    -0.207656
E1 fruity_A -0.398058   -0.377338   -0.430546   -0.126795   -0.237398   0.533383
E1 fruity_B 0.398058    0.377338    0.430546    0.126795    0.237398    -0.533383
E1 woody_A  0.527092    -0.925287   0.327178    -0.451342   0.374655    0.023936
E1 woody_B  -0.527092   0.925287    -0.327178   0.451342    -0.374655   -0.023936
E2 red fruit    0.898924    -0.494724   0.885217    -0.064772   0.862051    -0.678653
E2 roasted  -0.981521   0.703908    -0.836953   0.414603    -0.767083   0.577307
E2 vanillin -0.942450   0.536364    -0.968898   0.324330    -0.813833   0.843984
E2 woody    -0.940691   0.779423    -0.862575   0.587997    -0.915200   0.686830
E3 butter   -0.967765   0.802784    -0.749318   0.570645    -0.760397   0.466162
E3 fruity   0.598539    -0.782967   0.285297    -0.972318   0.321592    -0.098479
E3 woody    -0.965233   0.707537    -0.932395   0.524883    -0.888048   0.781353

That's 13 variables now and keep in mind I didn't run any preprocessing to the data. So changing the n_components parameter to 13 gives us:
0.9999999999999999

Comment: Thanks for your reply. The thing here is that I want the algorithm to run FAMD on 3 components because the intent was to plot these three dimensions. Then, the challenge here is to improve the explainability with the same number of components, if possible!


Error is using opencv with python

Question: I have this code for finding contour in opencv with python
im = cv2.imread('test.jpg')
imgray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
ret,thresh = cv2.threshold(imgray,127,255,0)
image, contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)

When I try to run this I am getting an error saying

"ValueError: need more than two values to unpack"

Any help is appreciated.
Answer: Actually there is some documentation mismatch of cv2.findcontours() method, it simple returns 2 values: contours, hierarchy, so you  should replace the last line with :
contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)

Error is using opencv with python


Listar registos diários?

Question: O meu programa faz a inserção de registos quer dos serviços quer dos computadores de uma biblioteca escolar. Como tal a secretaria da biblioteca tem de fazer um registo diário e eu gostaria de saber se é possível fazer uma listagem apenas das requisições(serviços ou computadores) diárias?

O objetivo era eu através da textbox com a hora do sistema poder listar todas as requisições feitas no proprio dia, quer fosse em ListView ou DataGrid, no entanto o codigo que eu tenho lista todas requisições feitas na BD.

O forma de fazer a inserção das requisições é:

O código do botao "guardar"
Comment: Como você está populando a DataGrid?
Comment: @MaiconCarraro populando?
Comment: Como esta a preencher os dados da DataGrid quando clicado em Guardar?
Comment: @MaiconCarraro editei, está em cima. Faz a inserção no registo de serviços e depois na listagem é suposto que apareça só os registos efetuados num tal dia.
Comment: Digo, quando você clica em `Guardar` como você busca os dados? É por `SqlCommand` ?
Comment: @MaiconCarraro é sim
Comment: Pode colocar o código na sua pergunta pra facilitar a resolução?
Comment: Eu não entendi muito bem como o horário informado vai afetar a consulta se você quer listar todos do dia, mas pra isso você pode alterar seu `sql` para `SELECT * FROM Requisição WHERE dataRequisicao >= Convert(date, getdate())`
Comment: @MaiconCarraro Eu já tinha tentado o select com um `Where` mas não com `Convert(date, getdate())`
Utilizei o seu select e tenho o que queria, obrigado!
Comment: @MaiconCarraro Com o código que eu e o meu colega temos, depois de clicar no botão guardar fica tudo como nós queremos, mas quando saímos e voltamos a entrar na aplicação, os dados guardados desaparecem. Há alguma forma de os manter? Obrigado.
Answer: Primeiramente este suposto comando de "guardar" ou tecnicamente conhecido como inserção está confuso pelo fato de seu comando ser uma uma seleção "Select * from...." somente esta populando o grid na unha ?
quanto a listagem, para conseguir listar todas seus registros de acordo com a data atual basta incluir uma clausula where ..
"Select * from requisicao where(dataRequisicao = getDate())"

(obs: Por boas praticas de programação não se aconselha dar nomes a tabelas,procedures,views,e etc com acentuação)
Comment: Jeferson, posso estar enganado, mas esse `SELECT` tem problema com horários não?
Comment: Problemas com horário?se refere ao fato do valor retornado pelo metodo ´`getDate()` não estar no mesmo formato com o salvo nos registros?
Comment: Exatamente, pelo fato da dataRequisicao ser DATETIME acredito que influencia nesse `=`, não?
Comment: Não , pois o valor retornado pelo método é do tipo datetime, único cuidado a ser tomado e pra ver o idioma atual,pois o retorno traz a data em formato de acordo com o mesmo.
Comment: Por isso o problema, o método retorna hora atual e ele quer qualquer hora do dia de hoje.
Comment: O método retorna tanto hora como data atual
Comment: Sim, mas seu `SELECT` vai fazer algo do tipo `WHERE ('11/06/2015 14:38:49' = '11/06/2015 15:27:32')` e não vai retornar :)
Comment: Ah sim , como eu disse é preciso ver o formato de ambas datas , porem isso é um  fácil  ajuste :)
Comment: Igual eu falei nos comentários da pergunta, eu recomendo fazer cast pra transformar a `dataRequisicao` em date e com operador ">=". [Exemplo](http://sqlfiddle.com/#!3/9eecb7db59d16c80417c72d1/789/0)
Comment: Sim , porém o operador de ">" se torna meio que inútil já que nunca vai existir um registro com uma data maior que a atual não é mesmo ? rs
Comment: eu tentei usar o seguinte select com inner join e dá 1 erro:
`"SELECT Requisição.dataRequisicao, Requisição.codRequisicao, Utilizadores.numProcesso, Utilizadores.nomeUtilizador, Turma.Ano, Turma.Turma, Turma.Curso"

"FROM Requisição INNER JOIN"
"TipoServiço ON Requisição.codTpServico TipoServiço.codTpServico INNER JOIN"
"Utilizadores ON Requisição.numProcesso Utilizadores.numProcesso INNER JOIN"
"TpUtilizador ON Utilizadores.CodUtilizador TpUtilizador.CodUtilizador INNER JOIN"
"Turma ON Utilizadores.codTurma = Turma.codTurma"
"WHERE(Requisição.dataRequisicao >= Convert(Of Date, GETDATE())())"`
Comment: @MaiconCarraro quando uso o seu select sozinho dá bem quando tento fazer o inner join para obter dados na datagrid de outras tabelas aparece um erro
Answer: Acredito que seu SQL correto seja esse aqui:
SELECT Requisição.dataRequisicao,
       Requisição.codRequisicao,
       Utilizadores.numProcesso,
       Utilizadores.nomeUtilizador,
       Turma.Ano,
       Turma.Turma,
       Turma.Curso
FROM Requisição
INNER JOIN TipoServiço ON Requisição.codTpServico = TipoServiço.codTpServico
INNER JOIN Utilizadores ON Requisição.numProcesso = Utilizadores.numProcesso
INNER JOIN TpUtilizador ON Utilizadores.CodUtilizador = TpUtilizador.CodUtilizador
INNER JOIN Turma ON Utilizadores.codTurma = Turma.codTurma
WHERE (Convert(date, Requisição.dataRequisicao) = Convert(date, getdate()))

O que você postou nos comentários está com vários erros de sintaxe, faltando = e com () a mais, então aconselho testar antes no SqlServer.

Listar registos diários?


Is complex exact if its Euler characteristic is zero?

Question: For a bounded complex $M$ of finite-dimensional $k$-vector spaces we define its Euler characteristic as
$$
\chi=\sum_{n\in \mathbb{Z}} (-1)^n\dim(M_n)
$$
In particular, if complex is exact then its Euler characteristic is zero. Is the converse true?
Comment: How long have you thought about this? The euler characteristic knows *nothing* about the boundary maps!
Comment: Evidently, not for long enough.
Answer: Consider $$0\to k\stackrel 0\to k\to 0 $$
Answer: I'd like to mention a positive result. As Martin Brandenburg pointed out, the Euler characteristic knows nothing about the boundary maps, so we might as well define the Euler characteristic of a bounded graded vector space (i.e. graded by $\mathbb Z$ with all spaces null but finitely many).
We say such a bounded graded vector space $V_.$ is:

potentially exact if you can endow it with differentials that turn it into an exact complex.
stably potentially exact if there is a potentially exact bounded graded vector space $V'_.$ such that $V_. \oplus V_.'$ is potentially exact.

Theorem: A bounded graded vector space is stably potentially exact if and only if its Euler characteristic is zero.
For a proof, see Grayson, Algebraic K-theory via binary complexes, lemma 5.4. It is stated and proved in greater generality there.


Remove two dimentional array elements(except first match) which array specific value are same/unique

Question: For example, I have an following two dimentional array is below,
$a = array(
    "one" => array (
        "id" => 111,
        "name" => "Jhon"
    ),
    "two" => array(
        "id" => 222,
        "name" => "Adam"
    ),
    "three" => array(
        "id" => 111,
        "name" => "Mark"
    ),
    "four" => array(
        "id" => 125,
        "name" => "Jhon"
    ),
    "five" => array(
        "id" => 111,
        "name" => "Jhon"
    ),
    "six" => array(
        "id" => 222,
        "name" => "Rock"
    ),
);

I would like to remove array(except first match) which two dimensional array values are same/unique.
For example, I would like to remove all of the arrays(except first match) which id keys values are same.
As, array id keys values 111(has array count 3) and 222(has array count 2).
So after removing the unique key id the result array should be following,
$a = array(
    "one" => array (
        "id" => 111,
        "name" => "Jhon"
    ),
    "two" => array(
        "id" => 222,
        "name" => "Adam"
    ),
    "four" => array(
        "id" => 125,
        "name" => "Jhon"
    ),
);

Answer: Use this code to complete your task
    <?php
$a = array(
    "one" => array (
        "id" => 111,
        "name" => "Jhon"
    ),
    "two" => array(
        "id" => 222,
        "name" => "Adam"
    ),
    "three" => array(
        "id" => 111,
        "name" => "Mark"
    ),
    "four" => array(
        "id" => 125,
        "name" => "Jhon"
    ),
    "five" => array(
        "id" => 111,
        "name" => "Jhon"
    ),
    "six" => array(
        "id" => 222,
        "name" => "Rock"
    ),
);
$unique = [];
$final_array = [];
foreach ($a as  $value) {
    if(in_array($value['id'],$unique)){
        continue;
    }
    else {
        $unique[] = $value['id'];
        $final_array[] = $value;
    }
}
echo "
";
print_r($final_array);
?>

Here i use a unique named array in which i put the unique key and loop through the array if id exsit in unique then it skip that otherwise i add that in final array.
Hope this will sort your problem.
Comment: The keys (`one`,`two` and `four`) are missing in the `final_array`.
Answer: You need to keep an array with added keys. You could use array_filter() to remove unnecessary rows.
Code: (demo)
$array = [
    "one"   => ["id" => 111, "name" => "Jhon"],
    "two"   => ["id" => 222, "name" => "Adam"],
    "three" => ["id" => 111, "name" => "Mark"],
    "four"  => ["id" => 125, "name" => "Jhon"],
    "five"  => ["id" => 111, "name" => "Jhon"],
    "six"   => ["id" => 222, "name" => "Rock"],
];

// store added IDs
$added = [];

// filter array (need to pass $added as reference to be updated)
$output = array_filter($array, function($item) use (&$added)
{
    // shortcut for readability
    $id = $item['id'];
    // Check if id already exists
    if (isset($added[$id])) { return false; }
    // add to reference
    $added[$id] = true;
    // add to final array
    return true;
});

unset($added); // no longer needed.

var_dump($output);

Output:
array(3) {
  ["one"]=>
  array(2) {
    ["id"]=>
    int(111)
    ["name"]=>
    string(4) "Jhon"
  }
  ["two"]=>
  array(2) {
    ["id"]=>
    int(222)
    ["name"]=>
    string(4) "Adam"
  }
  ["four"]=>
  array(2) {
    ["id"]=>
    int(125)
    ["name"]=>
    string(4) "Jhon"
  }
}


Does the Extended Euclidean Algorithm always return the smallest coefficients of Bézout's identity?

Question: Bezout's identity says that there are integers $x$ and $y$ such that $ax + by = gcd(a, b)$ and the Extended Euclidean Algorithm finds a particular solution. For instance,
$333\cdot-83 + 1728\cdot16 = \gcd(333, 1728) = 9$.
Will the Extended Euclidean Algorithm always return the smallest $x$ and $y$ that satisfy the identity? By small, I mean that $|x|, |y|$ are minimized.
Because $333\cdot(-83 + 1728t) + 1728\cdot(16 - 333t) = \gcd(333, 1728)$ is also a solution for all $t \in \mathbf{Z}$.
Comment: You should write $333\cdot(-83 + 192t) + 1728\cdot(16 - 37t) = \gcd(333, 1728)$
Comment: There are many variations on "the" extended Euclidean algorithm. Which version do you refer to?
Comment: Will Jagy - I am not sure what you mean by "You put the smaller number first; try gcd(16,83) by your exact method. You should get the second best pair."
-----
Bill Dubuque - I am referring to the one found here:
-----
http://en.wikibooks.org/wiki/Algorithm_Implementation/Mathematics/Extended_Euclidean_algorithm
Comment: See also https://math.stackexchange.com/questions/1001199/uniqueness-of-extended-euclidean-algorithm
Answer: We can assume that the GCD is $1$, because the Euclidean algorithm for $a/g,\,b/g$ is just the algorithm for $a,b$ "scaled down", that is, the quotients remain the same and the other numbers are divided by $g$.  We'll also assume that $a>b>1$.
As has been pointed out in comments, there are various implementations of the Euclidean algorithm, but suppose you do it this way, taking $n$ steps:
$$\eqalign{
  a&=q_1b+r_1\cr
  b&=q_2r_1+r_2\cr
  &\ \vdots\cr
  r_{n-2}&=q_{n-2}r_{n-1}+1\ .\cr}$$
Then you find the Bezout identity by reversing the procedure:
$$\eqalign{1
  &=r_{n-2}-q_{n-2}r_{n-1}\cr
  &=r_{n-2}-q_{n-2}(r_{n-3}-q_{n-3}r_{n-2})\cr
  &=-q_{n-2}r_{n-3}+(q_{n-2}q_{n-3}+1)r_{n-2}\cr
  &=\cdots\cr
  &=xa+yb\ .\cr}$$
Then we have $|x|\le b/2$ and $|y|\le a/2$.  This can be proved by induction on $n$.
If $n=1$ we have just one line $a=qb+1$, so the Bezout identity is $a-qb=1$: the coefficients are $x=1$, $y=-q$ and we have
$$|x|\le b/2\ ,\quad |y|=q\le qb/2<a/2\ .$$
Now suppose that a procedure of $n-1$ steps gives
$$bX+r_1Y=1$$
where by induction we may assume
$$|X|\le r_1/2\ ,\quad |Y|\le b/2\ .$$
Then the final step is
$$1=bX+(a-qb)Y=aY-(qY-X)b=ax+by$$
where
$$x=Y\ ,\quad y=-(qY-X)\ .$$
Therefore
$$|x|=|Y|\le b/2\quad\hbox{and}\quad |y|\le q|Y|+|X|\le qb/2+r_1/2=a/2\ ,$$
and this completes the proof by induction.
Since the general solution for $x$ is $x=x_0+bt$, any value of $x$ between $-b/2$ and $b/2$ must be numerically the smallest possible; and similarly for $y$.
Comment: Have just added an extra sentence at the end of my answer which I hope clears this up.
Comment: Thank you David for your very detailed response. I guess what I am asking is that, are the x and y that are found by the Extended Euclidean Algorithm the smallest x and y (in the absolute value sense) that satisfy ax + by = 1?
Comment: @David When you reverse the procedure how do you jump from line 2 to line 3. Why've you shortened $-q_{n-2}r_{n-3}$ to just $-q_{n-2}$?
Comment: @Dhruv typo, fixed.
Answer: This question, as well as an extension to the GCD of more than two numbers, is analyzed in Section 3 of this paper by Majewski and Havas:
  http://staff.itee.uq.edu.au/havas/1994mh.pdf
They show that the same bound holds for the case of more than two numbers: one can always find coefficients that are at most half the largest number in absolute value. They also show how to find those coefficients very efficiently.
Comment: The extension to greatest common divisors of more than two numbers is doubtless an interesting Question, but it's not clear if you are actually answering the Question posed here, whether Extended Euclidean algorithm can promise the optimal size coefficients.  The Question is a bit vague (about how size should be measured, and what specific variants of Extended Euclidean algorithm may be specified), but the older Answer offers some details to address that.


Is it the right way to find the maximum of a function? (simple query)

Question: I have a function $f(x)$. I know its derivative is positive for some range of $x<x_1$ and is negative for $x>x_1$. I know this because of the expression for the derivative of the function. Now, since I know that the derivative is strictly positive for $x<x_1$ and strictly negative for $x>x_1$, can I say that the function achieves its maximum value at $x=x_1$?
Comment: Yes, provided $f(x)$ is continuous at $x_1$.
Comment: @XanderHenderson can you give an example?
Answer: Because it was unstated in your question, I am going to assume that the function in question is differentiable for all real $x$.
If $f(x_1)$ is not the maximum value of $f$, then there is another point $y \in \mathbb{R}$ for which $f(x_1) < f(y)$.
If $y > x_1$ then $\frac{f(y) - f(x_1)}{y-x_1} = f'(\xi)$ for some $\xi \in (x_1,y)$ by the mean value theorem. The quantity $\frac{f(y) - f(x_1)}{y-x_1}$ is positive and so $f'(\xi) > 0$. This contradicts your statement of $f'(x) < 0$ for all $x > x_1$.
Similarly, if $x_1 < y$ we find that there must be a point $f'(\xi) < 0$ for some $\xi < x_1$. Which would also be a contradiction.
Thus there can't be any point $y$ for which $f(y) > f(x_1)$. Indeed, $f(x_1)$ is the maximum value of $f$.
Comment: Thank you so much for your answer. So, in essence, we do not need to prove that the function is concave and that the double derivative is always negative.
Comment: You are correct. The negativity of the second derivative is a sufficient condition.
Answer: If $f$ is differentiable for $x \neq x_1$ and continuous everywhere then the $\max$ occurs at $x_1$.
To see this, pick $x<x_1$ then the mean value theorem gives some
$\xi \in (x,x_1)$ such that
$f(x_1) = f(x)+ f'(\xi)(x_1-x) \ge f(x)$ and similarly for
$x_1<x$ we have some other $\xi \in (x_1,x)$ such that
$f(x) = f(x_1) + f'(\xi)(x-x_1) \le f(x_1)$.
$f$ need not be differentiable at $x_1$.
Comment: Thank you for your answer. Actually my function is differentiable for almost all $x$.


Treating missing values as really missing in Vowpal Wabbit

Question: Is there a way to correctly represent missing values in VW input format -- not to impute with the mean or median, not to set them to 0 or any other constant, but to treat them as really missing, so that SGD and FTRL-Proximal algorithms could exclude these coordinates from the gradient computation for a given example?
Answer: VW expects sparse feature representation input format, see VW wiki. So missing values are treated correctly. Simply, don't list the features whose values are missing.
Comment: As far as I know VW will consider unreported features as carrying a value of 0. I'm not sure why this is the right approach, when the unreported features carry numeric semantics in the domain. I'd actually think imputing with the median/mean/etc would make sense in many cases, but happy to learn if I'm wrong here.


Nginx proxy to node.js server SSL ERR_SSL_PROTOCOL_ERROR

Question: EDIT:
I have verified that nodejs is running on the correct port, on http, and I have also tried with and without:
app.use('trust proxy', true);

EDIT 2:
I turned off the nodejs server and tried to serve static files just with nginx, and the error persists, so clearly this has something to do with nginx and my ssl cert.
My domain is a free domain from freenom and the ssl certificate was generated with certbot.
Original:
I have a nodejs server running, and want to use nginx and proxy to the nodejs server. (Nginx https -> nodejs http)
Running nginx -t gives no errors.
On ubuntu 20.04.2, nginx 1.18.0 node 14.5.5
I have verified that my site works fine via http (on port 3000), but i get the following error when visiting via browser on https:

ERR_SSL_PROTOCOL_ERROR

Further if i use openssl cli to try and connect, I get this
openssl s_client -connect my_domain.com:443 -servername my_domain.com

CONNECTED(00000003)
139662603941184:error:1408F10B:SSL routines:ssl3_get_record:wrong version number:../ssl/record/ssl3_record.c:331:
---
no peer certificate available
---
No client certificate CA names sent
---
SSL handshake has read 5 bytes and written 310 bytes
Verification: OK
---
New, (NONE), Cipher is (NONE)
Secure Renegotiation IS NOT supported
Compression: NONE
Expansion: NONE
No ALPN negotiated
Early data was not sent
Verify return code: 0 (ok)
---

/etc/nginx/conf.d/ssl.conf
server {
    listen 443 ssl;

    ssl_certificate     /server/resources/cert.pem;
    ssl_certificate_key /server/resources/privkey.pem;

    location / {
        proxy_pass http://127.0.0.1:3000;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection 'upgrade';
    proxy_set_header Host $host;
    proxy_cache_bypass $http_upgrade;
}
}

Comment: Add more details about the error if you can see any
Comment: This error is often related when accessing a server which is not SSL enabled. Check the log files of nginx, especially the error logs. Note also that errors in other parts of the nginx configuration might lead to such problems, like some server which also listens on port 443 but has not ssl enabled.
Comment: @SteffenUllrich `access.log` and `error.log` are both empty
Comment: Unlikely,  maybe you look into the wrong files. Or maybe you disabled logging. There should at least be information about server start and there will usually be information on ssl errors. Or `my_domain.com:443` is not actually accessing the server you've configured, i.e. DNS does not resolve to the servers IP address.
Comment: @SteffenUllrich I verified logging is enabled and checked the correct log files, and changed `my_domain` and tried with the ip, still produced same errors.
Comment: @SteffenUllrich I tried running https directly from nodejs and disabled the nginx proxy and the site worked fine. Nginx error log level set to debug, still empty error logs.
Comment: Can you try with ssl cert with node js script ->
 const options = {
 key: fs.readFileSync('./key.pem'),
 cert: fs.readFileSync('./cert.pem'),
 passphrase: 'test'
};
server = https.createServer(options, app);
Comment: @AshishSharma running https from nodejs with my certificates runs fine. But I want to proxy https on nginx to http on node.
Answer: If you use Cloudflare, It may Cloudflare not issued SSL certificate for you yet, or Cloudflare failed to connect to origin with secure connection. Check your dashboard.
Answer: Following is the working configuration of nginx.conf
I have also setup SSL with certbot + letsencrypt.
server {
    listen 80;
    listen [::]:80;
    server_name example.com www.example.com;
    return 301 https://$server_name$request_uri;
}

server {
    listen 443 ssl http2 default_server;
    listen [::]:443 ssl http2 default_server;
    server_name example.com www.example.com;
    root "/home/ubuntu/domain/code/directory/path/";
    index index.html index.htm;
    client_max_body_size 75M;   # adjust to taste

    location /api {
        proxy_pass http://localhost:3000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
        proxy_read_timeout 600s;
    }

    location / {
        try_files $uri $uri/ /index.html;
    }

    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
    ssl_session_timeout 1h;
    ssl_prefer_server_ciphers on;
    ssl_session_cache shared:SSL:5m;
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    add_header Strict-Transport-Security "max-age=15768000" always;
    ssl_ciphers EECDH+CHACHA20:EECDH+AES128:RSA+AES128:EECDH+AES256:RSA+AES256:EECDH+3DES:RSA+3DES:!MD5;
}

I guess the above configuration might solve your issue.
URL is https://www.example.com/api/ping redirects to http://localhost:3000/api/ping on the server.


Different/separate session frontend and backend

Question: Firstly, my English is not too good.
Hi, I have problem with my project
I created a website that allows you to login from frontend (as member) and as admin.
I login to both (frontend and backend) using a different username and password but once I logout from the backend, the frontend will logout too.
I think this is because I run the session_destroy() script, and it destroys all sessions including the frontend session.
I have tried to search for this using Zend Framework and Joomla with PHP
Comment: Are you creating session variables for these..??
Comment: Using different session names should solve this.
Comment: @Gumbo : or different session store path on frontend and backed
Comment: yes, i do
i create different session name for both as well
Answer: You should be creating different variables for different sessions..
Here are some of the examples which may get handy in case..
<?php
 // you have to open the session to be able to modify or remove it
 session_start();

 // to change a variable, just overwrite it
 $_SESSION['size']='large';

 //you can remove a single variable in the session
 unset($_SESSION['shape']);

 // or this would remove all the variables in the session, but not the session itself
 session_unset();

 // this would destroy the session variables
 session_destroy();
 ?>

Hope it helps..
Comment: Hi thank you for answer,
is it possible to use only session_unset ?
Comment: You can use `session_unset` but only when you are using multiple session variables.. this will unset all the variables...
Comment: so i can change the logout script
my logout script now is
session_start(); session_destroy();

i will change it to
session_start();
unset($_SESSION['username']);
unset($_SESSION['password']);

thank you very much Hiren, i will try it now
Comment: Hi Hiren, thank you its working very well, i use unset($_SESSION[something]) with the session role system below

thanks for your help :D
Answer: I imagine this is your session when you're logged in as an admin:
$_SESSION['user']['id'] = 1;
$_SESSION['user']['group'] = 'admin';
...

However, this is your session when you're just a user:
$_SESSION['user']['id'] = 99;

Wherever your logout.php is located, do something similar to this:
if ($_SESSION['user']['group'] == 'admin')
    $_SESSION['user']['group'] = null;
else
    destroy_session();

I hope you got the idea!
Update
This might work:
/* Do NOT unset the $_SESSION['user']['role'] */

if ($_SESSION['user']['role'] == 'user') {

    /* For Users */
    $_SESSION['user']['login'] = false;
    $_SESSION['user']['id'] = null;
    $_SESSION['user']['last-visit'] = null;
    $_SESSION['user']['ip'] = null;
}

if ($_SESSION['user']['role'] == 'admin') {

    /* Unset Admin Specific Variables */
    $_SESSION['admin']['login'] = false;
    $_SESSION['admin']['id'] = null;
    $_SESSION['admin']['last-visit'] = null;
    $_SESSION['admin']['ip'] = null;
}

/* Get rid of session_destroy() */
// session_destroy();

By the way, you're just resetting the variables manually, which is somehow equal to destroying the session entirely, but still keeps the session alive for the other side.
Even Better
/* Assign the `user_id` to the session, when you log in ... */
/* login.php */

$_SESSION[$user_id] = array();

/* Now fill-up the new array with data ... */
$_SESSION[$user_id]['role'] = 'admin';
$_SESSION[$user_id]['login'] = true;

/* When you want to Log out, just simply null the array based on the user_id again */
/* logout.php */

$_SESSION[$user_id] = null;

/* Here you go, as long as you have different user_id in your database,
   you have separated sessions! */

Comment: Hi thank you for answer,
i did that, i group the user (like admin and user) but if i logout from backend frontend logged out too,

i also try to have a different table for member and for admin, and different session name , but it still not working :(


Adding link with image in the .tpl.php file

Question: I have just started with drupal and have very little understanding and experience with it. I was able to develop a module by referring to sample modules available online. I have a .tpl.php file that is supposed to have a link in the form of an image, I am hoping to execute a php function (php function is ready) by clicking on that image.
So my question is how to add a link inside the .tpl.php file, do I have to implement a form? if so, what file should have this form? How to execute the php function on click from this link?
Please let me know if the question doesn't make enough sense.
Thanks
Comment: since PHP is a server side script, I don't believe you can execute a php function once the page is loaded, unless you make a POST or GET call to another file. Do you want to hard-code this link?  if that's the case, then it works no different than any other html tag, just decide where you want it.
Answer: I think what you want is something to link to that will execute your PHP "callback". Have a look at hook_menu() in the Drupal API.
Here's an example:
/**
 * Implements hook_menu().
 */
function MODULENAME_menu() {
  $items = array();
  $items['mymodule/callback'] = array(
    'page callback' => 'MODULENAME_do_callback',
    'access arguments' => array('access content'), // You can specify a permission here.
    'type' => MENU_CALLBACK,
  );
  return $items;
}

function MODULENAME_do_callback() {
  // your php here
}

With that you should be able to link your image (just with standard HTML) to yourdomain.com/mymodule/callback and it will execute your code.
Note: Be sure to clear all caches after adding your hook_menu() implementation.


Center horizontally group of elements inside the ConstraintLayout

Question: I have to place three components inside the constraint layout: image, and on the right of the image two textviews one above other. Both text views are centered along the image.

They all together should be centered horizontally inside.
There is my code :
   <com.google.android.material.card.MaterialCardView
    android:id="@+id/downloadPlan"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center_vertical"
    android:layout_marginStart="16dp"
    android:layout_marginEnd="16dp"
    android:layout_marginBottom="16dp"
    android:clickable="true"
    android:focusable="true"
    app:cardBackgroundColor="@color/orange"
    app:cardCornerRadius="32dp"
    app:cardElevation="0dp">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingTop="12dp"
        android:paddingBottom="12dp">

        <androidx.appcompat.widget.AppCompatImageView
            android:id="@+id/icon"
            android:layout_width="20dp"
            android:layout_height="20dp"
            android:layout_marginEnd="12dp"
            android:adjustViewBounds="true"
            android:contentDescription="@null"
            android:src="@drawable/ic_download"
            android:tint="@color/violet"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintEnd_toStartOf="@id/title"
            app:layout_constraintHorizontal_bias="0.4"
            app:layout_constraintHorizontal_chainStyle="packed"
            app:layout_constraintTop_toTopOf="parent" />

        <TextView
            android:id="@+id/title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="@color/violet"
            android:textSize="14sp"
            android:textStyle="bold"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="@id/icon"
            app:layout_constraintTop_toTopOf="parent" />

        <TextView
            android:id="@+id/size"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="@color/violet"
            android:textSize="12sp"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintStart_toStartOf="@id/title"
            app:layout_constraintTop_toBottomOf="@id/title" />
    </androidx.constraintlayout.widget.ConstraintLayout>
</com.google.android.material.card.MaterialCardView>

Is it possible to achieve this centering without the adding of nested layout?
Answer:
First arrange the title and size TextView vertically in the parent. You can use chaining to center them vertically in the parent with packed chain style.

Then arrange the icon wrt to the title and make them horizontally center again with packed chain style.

Finally, instead of centering two TextView to be in center with the Icon, you can make the Icon to be in center with the two TextView.

Below is the final code, ignore colors and icon drawable.
<androidx.constraintlayout.widget.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:paddingTop="12dp"
            android:paddingBottom="12dp">

            <androidx.appcompat.widget.AppCompatImageView
                android:id="@+id/icon"
                android:layout_width="20dp"
                android:layout_height="20dp"
                android:layout_marginEnd="12dp"
                android:adjustViewBounds="true"
                android:contentDescription="@null"
                android:src="@drawable/ic_add"
                android:tint="#000000"
                app:layout_constraintBottom_toBottomOf="@id/size"
                app:layout_constraintEnd_toStartOf="@id/title"
                app:layout_constraintHorizontal_chainStyle="packed"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toTopOf="@id/title" />

            <TextView
                android:id="@+id/title"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text=" Download Test Plan"
                android:textColor="#000000"
                android:textSize="14sp"
                android:textStyle="bold"
                app:layout_constraintBottom_toTopOf="@id/size"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toEndOf="@id/icon"
                app:layout_constraintTop_toTopOf="parent"
                app:layout_constraintVertical_chainStyle="packed" />

            <TextView
                android:id="@+id/size"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="PDF"
                android:textColor="#000000"
                android:textSize="12sp"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintStart_toStartOf="@id/title"
                app:layout_constraintTop_toBottomOf="@id/title" />
</androidx.constraintlayout.widget.ConstraintLayout>

Sample Output :


General expression for the $n$-th derivative of $f(x)=\Gamma(1-\beta x)$

Question: I am trying to find the $n$-th order derivative of the function:
$$f\left(x\right)=\Gamma\left(1-\beta x\right)$$
at $t=0$. To be more specific, the general expression for:
$$\left.\frac{\mathrm{d}^{n}}{\mathrm{d}^{n} x}\Gamma\left(1-\beta x\right) \right|_{x=0}$$
whereby $\beta>0$. I tried using Mathematica to see if there is any pattern, but I couldn't find any. However, from Wikipedia, the general expression
$$\frac{{\rm d}^n}{{\rm d}x^n}\,\Gamma(x) = \int_0^\infty t^{x-1} e^{-t} (\ln t)^n \, \mathrm{d}t$$
gives
$$\frac{{\rm d}^n}{{\rm d}x^n}\,\Gamma(1-\beta x) = \int_0^\infty t^{-\beta x} e^{-t} (\ln t)^n \, \mathrm{d}t.$$
I can't simplify any further than this.
Comment: Please see whether this helps you: http://scipp.ucsc.edu/~haber/ph116A/psifun_11.pdf
Comment: Thank you @Rohan. I managed to find a few more information based on the document and edited my question accordingly. Unfortunately, still no luck.
Comment: Please check if it is $\frac{e^{-t}\times (\ln t)^{n-1}}{a}$.
Comment: @Rohan is that the final answer or the integral?
Comment: I think so. I just integrated your function. I substituted $\beta$ for $a$.
Comment: @Rohen, I don't think that is correct. Kindly refer to the answer provided below
Answer: Using induction, you can easily proof
$$\frac{d^n}{dx^n} \Gamma(1-\beta x) = (-\beta)^n \Gamma^{(n)}(1 -\beta x)$$
It remains to calculate the high order derivatives of the gamma function at $1$. However, I am afraid there is no simple formula for this. The values can be recursively recovered using the polygamma functions, but these formulae will get very big very quickly and contain a lot of values of the zeta function.
Comment: @arvindrajan92 Near the end of the [Wikipedia](https://en.wikipedia.org/wiki/Gamma_function#General) right before you hit the fourier series expansion section, the $n$th derivative of the Gamma function is expressed in closed form in terms of the Riemann zeta function.
Comment: Thank you @Dominik. I arrived to this final form as well. I don't think it can be simplified any further than this.
Comment: Yes, thank you @SimpleArt


Passing a temporary derived object to a method/function that expects a base object reference

Question: Preface: I want to be able to store a (abstract) base class reference from an object of a derived (concrete) class type so it can be returned later and casted to the same derived (concrete) class without resorting to pointers and constantly having to worry about ownership, memory leaks, and dangling pointers/bad references.
Using the hierarchy below, the attempted constructor call: A(/* Other variables */, Bar(/* Bar variables */)); fails with `Warning    3 warning C4239: nonstandard extension used : 'argument' : conversion from 'Bar' to 'Foo&' (Visual Studio 2010 SP1)
Changing the class O to contain a Foo* _foo and the constructor initialization to /*...*/, _foo(&foo) causes a dangling pointer as the temporary object is destroyed when the constructor finishes.
Is there a way to pass a temporary object to a class that expects a reference and not have the code go bonkers?
`
/* ABSTRACT BASE CLASS */
class Foo {
    //...
};

/* DERIVED, CONCRETE CLASS */
class Bar : public Foo {
    //...
};

class O {
    O(/* Other variables */, Foo& foo) : /* Other member variable initializations */, _foo(foo) { }

    //...Other member variables here...
    Foo& _foo;
    friend class A;
};

class A {
    public:
        A(/* Other individual variables used to fully construct object 'O' */, Foo& foo) : /*...*/, _foo(foo) { }
    private:
        O _o

};

Answer:
Is there a way to pass a temporary object to a class that expects a reference and not have the code go bonkers?

No. The very reason why you do not have to worry that much about ownership when you deal with references is that the ownership is dealt with some place else - specifically, at the level owning the variable being referenced.
A reference becomes invalid the moment the object being referenced goes out of scope (yes, references can be dangling too). The object being referenced must stay around as long as the reference to it is in active use. That is why you cannot make temporaries play nicely with references: temporaries go out of scope very quickly, rendering useless the references to them.